query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
returns promise, value expected to be an array of the hardcoded files, also puts hardcoded files into local storage | async function getHardcodedFiles() {
const files = listFiles();
let fileNames = [];
for (let i=0;i<files.length;i++) {
const file = files[i];
const text = await file.text();
const fileObj = {
text: text,
name: path.basename(file.name),
type: file.type,
date: file.lastModified
};
fileNames.push(path.basename(file.name));
localStorage.setItem(path.basename(file.name), JSON.stringify(fileObj));
}
localStorage.setItem('fileNames', JSON.stringify(fileNames));
return files;
} | [
"templateFiles() {\n return Promise.map(this.files, file => {\n debug( 'templating file', file )\n return this.templateFile(file)\n .then( newdata => this.writeTemplateFile(file,newdata) )\n })\n }",
"function missingLocalFiles() {\n return [\n {\n absolutePath: '/Users/hyeomans/dev/my-opentable/Web/Resources/Errors.resx',\n relativePath: 'Web/Resources/Errors.resx',\n fileUri: 'https://api.smartling.com/v1/file/get?apiKey=mockApiKey&fileUri=./Web/Resources/Errors.resx&projectId=mockProjectId',\n upload: {\n uri: 'https://api.smartling.com/v1/file/upload',\n params: [\n [ 'apiKey', 'mockApiKey' ],\n [ 'projectId', 'mockProjectId' ],\n [ 'fileUri', './Web/Resources/Errors.resx' ],\n [ 'fileType', 'resx' ]\n ]\n },\n siblings: [{\n absolutePath: '/Users/hyeomans/dev/my-opentable/Web/Resources/Errors.en-AU.resx',\n relativePath: 'Web/Resources/Errors.en-AU.resx',\n fileUri: 'https://api.smartling.com/v1/file/get?apiKey=mockApiKey&fileUri=./Web/Resources/Errors.resx&projectId=mockProjectId&locale=en-AU',\n upload: {\n uri: 'https://api.smartling.com/v1/file/import',\n params: [\n ['apiKey', 'mockApiKey'],\n ['projectId', 'mockProjectId'],\n ['fileUri', './Web/Resources/Errors.resx'],\n ['locale', 'en-AU'],\n ['overwrite', 1],\n ['translationState', 'PUBLISHED'],\n ['fileType', 'resx']\n ]\n },\n tempPath: undefined\n }],\n tempPath: undefined\n }\n ];\n}",
"function sourceFiles2ProjAsync(files) { // Last object of \"files\" will be name of the project where files will be added to NEEDSTOBECHANGED\n logger.debug(\"sourceFiles2ProjAsync\");\n var proj_name = files[files.length - 1];\n var docpath = remote.app.getPath('documents');\n\n var f2p_options = {\n name: proj_name,\n cwd: path.join(docpath, 'SLIPPS DECSV\\\\Projects\\\\' + proj_name + '\\\\')\n }\n const f2p_store = new Store(f2p_options);//\n var pre_dirfiles = f2p_store.get('source-files', []);\n logger.debug(pre_dirfiles);\n\n ipcRenderer.on('async-import-files-reply', (event, arg) => {\n logger.debug(\"BACK FROM APP - import files into project\");\n var dirfiles = fs.readdirSync(path.join(docpath, 'SLIPPS DECSV\\\\Projects\\\\' + proj_name + '\\\\source\\\\'));\n logger.debug(docpath);\n logger.debug(dirfiles);\n //console.log(\"RETURNED FROM APP: \");\n //console.log(arg);\n if (arg[0]) {\n // do something if importing was successful\n logger.debug(\"DONE IMPORTING SOURCE FILES!\");\n }\n else {\n logger.debug(\"ERROR WHILE IMPORTING!\");\n var reason1 = arg[1];\n // SHOW REASON TO USER! \n }\n logger.debug(\"STORE SOURCE: \" + f2p_store.get(\"source-files\", \"NONE!!!!\"));\n f2p_store.set(\"source-files\", dirfiles);\n ipcRenderer.removeAllListeners('async-import-files-reply');\n\n ipcRenderer.on('async-transform-files-reply', (event, arg) => {\n logger.debug(\"BACK FROM APP - returned from transforming src files to temp\");\n if (arg[0]) {\n logger.info(\"SRC to TEMP conversion success!\");\n // successfully ended the temp conversion\n logger.debug(\"SUCCESS AND FAIL ARRAYS\");\n logger.debug(arg[1]);//success array\n logger.debug(arg[2]);//fail array\n // filearr 0 = fileoriginal, 1 = filetemp, 2 = filedonestatus\n\n // fileS,\"temp#\"+fileS+\".json\",false\n for (var a = 0; a < arg[1].length; a++) {\n var fileArr = [];\n fileArr.push(arg[1][a][0], arg[1][a][1], arg[1][a][2]); // NEEDS UPDATE!!!!!! CUSTOM INPUT\n addProjFile(fileArr);\n }\n }\n else {\n logger.error(\"SRC to TEMP conversion failed!\");\n var reason2 = arg[1];\n // SHOW REASON TO USER!\n\n //folders missing\n }\n //var testing_opt = {\n // name: \"temp#\"+arg[1][0],\n // cwd: path.join(docpath, 'SLIPPS DECSV\\\\Projects\\\\' + proj_name + '\\\\temp\\\\')\n //}\n /*\n const testing_store = new Store(testing_opt);\n var teststring = testing_store.get(\"c\",\"AHAHAHAHAHAHAHAH\");\n //THIS IS FOR TESTING\n $(\"#edita-div\").addClass(\"is-shown\");\n $(\"#edit-A-edit-text\").html(teststring);\n */\n\n //updateFileList(proj_name);\n ipcRenderer.removeAllListeners('async-transform-files-reply');\n });\n ipcRenderer.send('async-transform-files', proj_name);\n });\n logger.debug(\"SENDING ASYNC TO MAIN APP!\");\n var send_arg = [];\n send_arg.push(files);\n send_arg.push(pre_dirfiles);\n logger.debug(\"########### LISTING FILELIST GOING TO BE SENT\");\n logger.debug(files);\n logger.debug(pre_dirfiles);\n ipcRenderer.send('async-import-files', send_arg);\n}",
"async function cacheFiles() {\n const files = await io.readdir(PUBLIC_FOLDER);\n const readPromises = [];\n files.forEach(file =>\n readPromises.push(io.readFile(`${PUBLIC_FOLDER}/${file}`)\n .then(data => filesCache.set(file, data))\n .catch(err => err) // prevent breaking on rejection\n ));\n await Promise.all(readPromises);\n JSON.parse(filesCache.get(CITIES_FILE))\n .forEach(city => citiesCache.set(city.id, city));\n}",
"function get_files_from_server(){\n //link with file containning the files and folders distribution\n fetch(\"https://raw.githubusercontent.com/Eduardo-Filipe-Ferreira/ADS-Files-Repository/main/FilesLocation.json\")\n .then(response => response.json())\n .then(json => handle_server_files(json[0]));\n }",
"directoryInjector(directoryPath) {\n return this.getFilesInDirectory(directoryPath)\n .then(files => Promise.all(files.map(file => this.fileInjector(path.join(directoryPath, file)))))\n .catch(err => Promise.reject(`Error injecting into files on '${directoryPath}': ${err}`));\n }",
"function _getSampleTestFiles () {\n return [{\n path: path.join(testSuitesRelativePath, 'test-txt.txt'),\n contents: Assets.getText(path.join('sample-tests', 'suites', 'test-txt.txt'))\n }, {\n path: path.join(testSuitesRelativePath, 'test-tsv.tsv'),\n contents: Assets.getText(path.join('sample-tests', 'suites', 'test-tsv.tsv'))\n }, {\n path: path.join(testSuitesRelativePath, 'test-html.xhtml'),\n contents: Assets.getText(path.join('sample-tests', 'suites', 'test-html.xhtml'))\n }, {\n path: path.join(testSuitesRelativePath, 'resources.txt'),\n contents: Assets.getText(path.join('sample-tests', 'suites', 'resources.txt'))\n }, {\n path: path.join(FRAMEWORK_NAME, 'arguments.txt'),\n contents: Assets.getText(path.join('sample-tests', 'arguments.txt')) \n }];\n }",
"harvest() {\n const { dirPairs: pairs } = JSON.parse(\n fs.readFileSync(path.resolve(process.cwd(), './fileshipper.json')).toString()\n );\n\n this.pairs = pairs;\n\n const filePairs = this.extractFilePair(pairs);\n\n return filePairs;\n }",
"async function sync_files(file_path_list: string[], settingData: any, hashes?: IHashesObject) {\n if (!hashes) {\n hashes = {};\n if (fs.existsSync(hash_filename)) {\n var hashes_str = fs.readFileSync(hash_filename, 'utf-8');\n hashes = JSON.parse(hashes_str);\n }\n }\n\n for (var i = 0; i < file_path_list.length; i++) {\n var result = await sendFile(hashes, settingData['username'], settingData['password'], settingData['mimesync_service'], settingData['mime_url'], file_path_list[i], settingData['request_number'])\n if (result.trim() == '0') {\n console.log(chalk.green(file_path_list[i]) + ' synced successfully.');\n } else if (result == '-1') {\n console.log(chalk.cyan(file_path_list[i]) + ' file not changed after latest mime-sync.');\n } else if (result == '-2') {\n console.log(chalk.yellow(file_path_list[i]) + ' file is empty, skipped.');\n\n } else if (abap_exceptions.hasOwnProperty(result.trim())) {\n console.log(chalk.red(file_path_list[i]) + ' problem with syncing:')\n console.log(chalk.red('ABAP exception in service(mime_repository_api): ' + abap_exceptions[result.trim()]))\n } else {\n console.log(chalk.red(file_path_list[i]) + ' problem with syncing:')\n console.log(chalk.red(result))\n }\n }\n\n //write hash file\n var hashes_json = JSON.stringify(hashes);\n fs.writeFileSync(hash_filename, hashes_json, { encoding: 'utf-8' });\n\n\n}",
"function putResources(files) {\n\n var host = options.host || defaultOptions.host;\n var port = options.port || defaultOptions.port;\n var path = options.path || defaultOptions.path;\n var auth = options.auth || undefined;\n var protocol = options.protocol || defaultOptions.protocol;\n\n if (host.startsWith('https://')) { host = host.substring(8); }\n else if (host.startsWith('http://')) { host = host.substring(7); }\n if (host.endsWith('/')) { host = host.substring(0, host.length - 1); }\n if (!path.startsWith('/')) { path = '/' + path; }\n if (!path.endsWith('/')) { path = path + '/'; }\n\n const promises = [];\n\n files.forEach(function (val, index, array) {\n promises.push(new Promise(resolve => {\n fs.readFile(val, 'utf8', function (err,data) {\n if (!err) {\n try{\n var obj = JSON.parse(data);\n var type = obj.resourceType;\n var id = obj.id;\n var headers = {\n 'Content-Type': 'application/fhir+json;charset=UTF-8',\n 'Accept': 'application/fhir+json;charset=UTF-8'\n };\n if (auth) {\n headers.Authorization = 'Bearer ' + auth;\n }\n var options = {\n host: host,\n port: port,\n path: path + type + \"/\" + (id || ''),\n headers: headers,\n method: id ? 'PUT' : 'POST'\n }\n\n\n \tvar req = http.request(options, function(res) {\n \t res.setEncoding('utf8');\n \t let response = '';\n \t res.on('data', function (chunk) {\n \t response += chunk;\n \t });\n \t res.on('end', function() {\n \t \ttry{\n \t\t\t\tvar resp = JSON.parse(response);\n \t\t\t\tif(resp && resp.resourceType == type){\n resolve([val, true, resp]);\n \t\t\t\t\tconsole.warn(\"\\033[32m\" + val,\" created successfully.\\033[;;m\");\n \t\t\t\t}\n \t\t\t\telse if(resp && resp.issue){\n resolve([val, false]);\n \t\t\t\t\tconsole.warn(\"\\033[31m\" + val,\" failed.\\033[;;m\");\n \t\t\t\t\tfor(var issue of resp.issue){\n \t\t\t\t\t\tif(issue.severity == \"error\"){\n \t\t\t\t\t\t\tconsole.warn(\"Error\", issue.diagnostics);\n \t\t\t\t\t\t}\n \t\t\t\t\t}\n \t\t\t\t}\n \t } catch(parseError){ console.warn(response, parseError); resolve([val, false]); }\n \t });\n \t});\n \treq.on('error', function(e) {\n resolve([val, false]);\n \t console.warn('problem with request: ' + e.message);\n \t});\n \treq.write(data);\n \treq.end();\n }\n catch(e){\n resolve([val, false]);\n \t console.warn(e);\n }\n }\n });\n }));\n });\n return new Promise(resolve => {\n Promise.all(promises).then(results => {\n const resultsJson = {};\n results.forEach(result => resultsJson[result[0]] = result[1] && result[2]);\n resolve(resultsJson);\n });\n });\n}",
"fileListCache() {\n return remote.getGlobal('application').fileListCache;\n }",
"function getFileNamesArray() {\n const fileNames = JSON.parse(localStorage.getItem('fileNames'));\n return fileNames;\n}",
"function getUploadData() {\n var localData = JSON.parse(window.localStorage.getItem(\"advantagescout_scoutdata\"))\n for (var i = 0; i < localData.length; i++) {\n var fields = Object.keys(localData[i])\n for (var f = 0; f < fields.length; f++) {\n var value = localData[i][fields[f]]\n var fileName = String(value).split(\"/\").pop()\n if (imageCache[fileName] != undefined) {\n localData[i][fields[f]] = imageCache[fileName]\n }\n }\n }\n return [JSON.stringify(localData)]\n }",
"getFilesCreateUrl() {\n return this.getFilesCollection().then(function(fileCollection) {\n return this._filesCollectionLink(fileCollection);\n }.bind(this));\n }",
"function loadCustomLibs(){\n return new Promise(function(resolve,reject){\n let style = $.ajax({\n method: \"GET\",\n url: \"https://100l-app.teleows.com/servicecreator/fileservice/get?batchId=2219d2ef-e6bf-4775-ac56-c1933f4feeca&attachmentId=666945\",\n cache: false\n });\n let flat_blue = $.ajax({\n method: \"GET\",\n url: \"https://100l-app.teleows.com/servicecreator/fileservice/get?batchId=8c80323c-54c5-4372-b413-d08542b94fca&attachmentId=638599\",\n cache: false\n });\n $.when(style, flat_blue).done(function (styleResponse, flat_blueResponse) {\n $('<style />').text(styleResponse).appendTo($('head'));\n $('<style />').text(flat_blueResponse).appendTo($('head'));\n resolve();\n console.log(\"loadCustomLibs has Loaded\");\n }).fail(function (error) {\n console.log(\"loadCustomLibs has Failed\");\n reject(error);\n });\n });\n}",
"synthesizeSpeechFile(parts, voiceType) {\n return new Promise(resolve => {\n let audio_file = uuidgen.generate();\n let promArray = [];\n for (var i = 0; i < parts.length; i++) {\n promArray.push(this.getPollyChunk(parts[i], i, audio_file, voiceType));\n }\n\n Promise.all(promArray)\n .then(function(values) {\n logger.debug('resolved the big promise array');\n return polly_tts.concatAudio(values, audio_file);\n })\n .then(function(newAudioFile) {\n resolve(newAudioFile);\n });\n });\n }",
"async saveFiles ({ commit, state }) {\n commit(t.PROJECT_SAVE)\n\n try {\n const { id } = state\n const blob = await Zip.getBlob()\n\n return { id, blob }\n } catch (e) {\n throw e\n }\n }",
"async function cacheResources() {\n const cache = await caches.open(STATIC_CACHE);\n await cache.addAll(FILES_TO_CACHE);\n return self.skipWaiting();\n}",
"async list(force) {\n let _self = this;\n var folders = this.prefs.sources;\n var pattern, savers;\n \n var promises = [];\n \n // exclude system screensavers from the cache check\n // @todo get rid of this\n var systemScreensaverCount = 1;\n\n // use cached data if available\n if ( this.loadedScreensavers.length > systemScreensaverCount &&\n ( typeof(force) === \"undefined\" || force === false ) ) {\n return this.loadedScreensavers;\n }\n\n // note: using /**/ here instead of /*/ would\n // also match all subdirectories, which might be desirable\n // or even required, but is a lot slower, so not doing it\n // for now\n folders = folders.filter((el) => { \n return el !== undefined && el !== \"\" && fs.existsSync(el);\n });\n\n folders.forEach((sourceFolder) => {\n // glob doesn't work with windows style file paths, so convert\n // to posix\n sourceFolder = this.normalizePath(sourceFolder);\n\n pattern = `${sourceFolder}/*/saver.json`;\n savers = glob.sync(pattern);\n\n for ( var i = 0; i < savers.length; i++ ) {\n var f = this.normalizePath(savers[i]);\n var folder = path.dirname(f);\n\n // exclude skippable folders\n var doLoad = ! folder.split(/[/|\\\\]/).reverse()[0].match(/^__/) &&\n ! skipFolder(folder);\n \n if ( doLoad ) {\n promises.push(this.loadFromFile(f));\n }\n } \n });\n\n // filter out failed promises here\n // @see https://davidwalsh.name/promises-results\n promises = promises.map(p => p.catch(() => undefined));\n\n const data = await Promise.all(promises);\n\n // remove any undefined screensavers\n _self.loadedScreensavers = data.\n filter(s => s !== undefined).\n sort((a, b) => { \n return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); \n });\n\n return _self.loadedScreensavers;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PROBLEM: Write a function that takes an array of numbers and returns the sum of the sums of each leading subsequence in that array. Examine the examples to see what we mean. You may assume that the array always contains at least one number. PEDAC PROCESS P: UNDERSTAND THE PROBLEM EXPECTED INPUT AND OUTPUT Input: array of numbers Output: a number representing the sum of the addition of all subsequent number segments TERMS OF THE PROBLEM DOMAIN Terms of the problem domain: sum of sums of eaching leading subsequence: (3) + (3 + 5) + (3 + 5 + 2) > 21 IDENTIFY THE RULES (EXPLICIT & IMPLICIT REQUIREMENTS) 1. The function takes in an array of numbers (the array contains at least one number) 2. A single number is returned, representing the sum of the sums of number segments 3. Clarifying Questions: 1. MENTAL MODEL: E: EXAMPLES/TEST CASES (based on the above rules and edge cases) EXAMPLE ONE Input: Output: D: DATA STRUCTURE A: ALGORITHM START 1. SET input array as listOfNums 2. SET outputArray 3. Convert listOfNums to a string and SET as stringOfNums 4. Create a slice of stringOfNums starting with the fist character, push to outputArray, adding another character in each iteration 5. Iterate through outputArray, converting each character in each element to an number. adding each element's numbers together 6. Add each sum of outputArray's elements to each other and SET to theFinalSum END Verified this works with an example: Input: [3, 5, 2] Output: 21 START 1. SET input array as listOfNums listOfNums = [3, 5, 2] 2. SET outputArray outputArray = [] 3. Convert listOfNums to a string and SET as stringOfNums stringOfNums = 352 4. Create a slice of stringOfNums starting with the fist character, push to outputArray, adding another character in each iteration [3, 35, 352] 5. Iterate through outputArray, converting each character in each element to an number. adding each element's numbers together [3, 8, 10] 6. Add each sum of outputArray's elements to each other and SET to theFinalSum 21 END C: CODE WITH INTENT / START 1. SET input array as listOfNums 2. SET outputArray 3. Convert listOfNums to a string then array and SET as arrayOfNums 4. Create a slice of arrayOfNums starting with the first character, push to outputArray, adding another character in each iteration 5. Iterate through outputArray, converting each character in each element to an number. adding each element's numbers together 6. Add each sum of outputArray's elements to each other and SET to theFinalSum END | function sumOfSums(inputArray) {
let listOfNums = inputArray;
let outputArray = [];
let arrayOfNums = String(listOfNums).split(',');
// iterate through arrayOfNums and accumulatively add the current number to the previous number
for (let index = 1; index <= arrayOfNums.length; index += 1) {
outputArray.push(arrayOfNums.slice(0, index));
}
// iterate through each inner array, converting elements to numbers and adding them, return the sums
outputArray = outputArray.map(num => num.reduce((accumulator, currentNum) => accumulator + Number(currentNum), 0));
// add and return all of numbers of the array
return outputArray.reduce((accumulator, currentNum) => currentNum + accumulator, 0);
} | [
"function sumOfSums(numberArray) {\n return numberArray.map(function (number, idx) {\n return numberArray.slice(0, idx + 1).reduce(function (sum, digit) {\n return sum + digit;\n });\n }).reduce(function (sum, partialSum) {\n return sum + partialSum;\n });\n}",
"function intermediateSums(arr) {\n var lastSet = arr.length % 10;\n var sum = 0;\n for (var i = arr.length - 1; i > arr.length - (1 + lastSet); i--) {\n sum += arr[i];\n }\n arr[arr.length] = sum;\n // for loop incremented by 11 (10 plus the total one)\n for (var i = 0; i < arr.length; i += 11) {\n sum = 0;\n for (var j = i; j < i + 10; j++) {\n sum += arr[j];\n }\n // console.log(\"Sum: \" + sum)\n for (var k = arr.length - 1; k > i + 10; k--) {\n [arr[k], arr[k-1]] = [arr[k-1], arr[k]];\n }\n arr[i + 10] = sum;\n }\n // add first 10 values\n // loop back to 10, shifting all elements one to the right.\n // assign sum to 10,\n // do the next set.\n return arr;\n}",
"function sumOfNumbers(arr) {\n function sum(total, num) {\n return total + num;\n }\n return arr.reduce(sum);\n}",
"function runningSum(nums) {\n let arr = [];\n for(let i = 0; i < nums.length; i++) {\n if(i===0) {\n arr.push(nums[i])\n } else {\n arr.push(nums[i] + arr[i - 1]);\n };\n };\n return arr;\n}",
"function arraySum(array){\n var sum=0;\n var index=0;\n function add(){\n if(index===array.length-1)\n return sum;\n\n sum=sum+array[index];\n index++;\n return add();\n }\n return add();\n}",
"function arraySum(arr){\n\n // code goes here\n // similar to flatten, handle all levels of depth\n // use reduce to flatten the array and add integers to the startValue \n // if the curr value is an array, use recursion to run the function on the array again\n // if the value is a number, then add that to the total sum, else add 0\n // 0 is for any other value that is not a number\n return arr.reduce(function(sum, isNested){\n \n sum += (Array.isArray(isNested)) ? arraySum(isNested) : (typeof isNested === \"number\") ? isNested : 0;\n return sum;\n \n },0);\n\n}",
"function posSum (array) {\r // var sum = 0;\r // for(var i = 0 ; i< array.length ; i++){\r // if(array[i] > 0){\r // sum+= array [i]\r // }\r // }\r // if(i > array.length)\r // return 0;\r // else if(array[i]<0){\r // return 0\r // }\r // else return array[i-1]+posSum(array)\r\r if(array.length===0){\r return 0\r } else { \r var item = array.shift()\r if(item > 0)\r return item+posSum(array)\r else\r return posSum(array)\r }\r\r}",
"function sumArray(input) {\r\n\tvar operands = [];\r\n\tvar result = [];\r\n\tvar sum = 0;\r\n\r\n\tfor (var i = 1; i < input.length; i++) {\r\n\t\toperands = (input[i].split(' '));\r\n\t\tsum = parseInt(operands[0]) + parseInt(operands[1]);\r\n\t\tresult.push(sum);\r\n\t}\r\n\r\n\treturn result;\r\n}",
"function runningSum(nums) {\n const result = []\n \n nums.reduce((acc, curr) => {\n result.push(acc + curr)\n return acc + curr\n }, 0)\n \n return result;\n}",
"function sum(arr, n) {\n\t// Only change code below this line\n\tif ( n == 0 ) {\n\t\treturn 0; \n\t} else { \n\t\treturn arr[n - 1] + sum(arr, n - 1) ;\n\t}\n\t// Only change code above this line\n}",
"function lastKNums (length, sequence) {\n let arrWithNums = [1];\n while (arrWithNums.length < length) {\n let result = 0;\n if (sequence >= arrWithNums.length) {\n let currentNum = arrWithNums.reduce ((acc, val) => {return acc + val});\n result += currentNum;\n arrWithNums.push(result);\n }\n else{\n for (let j = 1; j < sequence + 1; j++) {\n result += arrWithNums[arrWithNums.length - j];\n }\n arrWithNums.push(result);\n }\n }\n console.log(arrWithNums.join(' '));\n}",
"function Arrays_sum(array1, array2) \r\n{\r\n const result = [];\r\n let ctr = 0;\r\n let x=0;\r\n\r\n if (array1.length === 0) \r\n return \"array1 is empty\";\r\n if (array2.length === 0) \r\n return \"array2 is empty\"; \r\n\r\n while (ctr < array1.length && ctr < array2.length) \r\n {\r\n result.push(array1[ctr] + array2[ctr]);\r\n ctr++;\r\n }\r\n\r\n if (ctr === array1.length) \r\n {\r\n for (x = ctr; x < array2.length; x++) {\r\n result.push(array2[x]);\r\n }\r\n } \r\n else\r\n {\r\n for (x = ctr; x < array1.length; x++) \r\n {\r\n result.push(array1[x]);\r\n }\r\n }\r\n return result;\r\n}",
"function maxSubarraySum(arr, number) {\n\tif(arr.length < number) {\n\t\treturn null;\n\t}\n\tlet endPos = arr.length - number;\n\tlet sum = 0, tempSum = 0;\n\tfor(let i = 0; i < number; i++) {\n\t\tsum = sum + arr[i];\n\t}\n\ttempSum = sum;\n\tfor(let i = 1; i <= endPos; i++) {\n\t\ttempSum = tempSum - arr[i - 1] + arr[i + number - 1];\n\t\tif(tempSum > sum) {\n\t\t\tsum = tempSum;\n\t\t}\n\t}\n\treturn sum;\n}",
"function balancedSums(arr) {\n /*var len = arr.length, i = 0, j = len - 1, nl_sum = 0, nr_sum = 0, pl_sum = 0,\n pr_sum = 0;\n for (i = 0; i < len; i++) {\n pr_sum = pr_sum + arr[i];\n }\n i = 0;\n while (i<len) {\n nl_sum = nl_sum + arr[i];\n nr_sum = pr_sum - arr[i];\n\n if (pr_sum > nr_sum) {\n console.log(nl_sum + \" \" + pl_sum + \"--\" + nr_sum + \" \" + pr_sum);\n pr_sum = nr_sum;\n pl_sum = nl_sum;\n } else if (pr_sum <= nr_sum) {\n console.log(\"hello\");\n pr_sum = nr_sum;\n pl_sum = nl_sum;\n break;\n }\n\n i++;\n }\n console.log(nl_sum + \" \" + nr_sum + \"bahar\" + pl_sum + \" \" + pr_sum);\n if (pl_sum == nr_sum && pr_sum == nl_sum)\n return \"YES\";\n else\n return \"NO\";\n */\n var len = arr.length, i = 0, l_sum = 0, r_sum = 0, j;\n for (i = 0; i < len; i++){\n l_sum = 0;\n r_sum = 0;\n for (j = 0; j < i; j++) {\n l_sum = l_sum + arr[j];\n }\n console.log(\"l_sum\"+ l_sum);\n for (j = i + 1; j < len; j++) {\n r_sum = r_sum + arr[j];\n }\n console.log(\"r_sum\" + r_sum);\n if (l_sum == r_sum) {\n return \"YES\";\n }\n } \n return \"NO\";\n}",
"solution(arr, x) {\n\n // Sort the array \n arr.sort();\n console.log(arr)\n // To store the closets sum \n let closestSum = 99999;\n\n // Fix the smallest number among \n // the three integers \n for (let i = 0; i < arr.length - 2; i++) {\n\n // Two pointers initially pointing at \n // the last and the element \n // next to the fixed element \n let left = i + 1, right = arr.length - 1;\n\n // While there could be more pairs to check \n while (left < right) {\n\n // Calculate the sum of the current triplet \n let currentSum = arr[i] + arr[left] + arr[right];\n\n // If the sum is more closer than \n // the current closest sum \n if (Math.abs(x - currentSum) < Math.abs(x - closestSum)) {\n closestSum = currentSum;\n }\n\n // If sum is greater then x then decrement \n // the second pointer to get a smaller sum \n if (currentSum > x) {\n right--;\n }\n\n // Else increment the first pointer \n // to get a larger sum \n else {\n left++;\n }\n }\n }\n\n // Return the closest sum found \n return closestSum;\n }",
"function positiveSum(arr) {\n\n}",
"function FinalArray(array1, array2){\n // created 2 variables and assigned the intitial value to 0\n let aa = 0;\n let bb = 0;\n // this while loop compares the array lengths to variables and \n // push the values into the result array while \n while (aa < array1.length && aa < array2.length) {\n result.push(array1[aa] + array2[aa]);\n aa++;\n }\n\n if (aa === array1.length) {\n for (bb = aa; bb < array2.length; bb++) {\n result.push(array2[bb]);\n }\n }\n else {\n for (bb = aa; bb < array1.length; bb++) {\n result.push(array1[bb]);\n }\n }\n return result;\n }",
"function runningTotal(arr) {\n let outputArr = [];\n let total = 0;\n for (let i = 0; i < arr.length; i++) {\n total += arr[i];\n outputArr.push(total);\n }\n return outputArr;\n}",
"function NumberAddition(str) { \n//search for all the digits in str (returns an array)\nvar nums = str.match(/(\\d)+/g); \n\nif (!nums) {return 0;} //stop if there are no numbers\nelse {\n //convert array elements to numbers using .map()\n //then add all elements together using .reduce()\n return nums.map(function(element, index, array){\n return +element;\n }).reduce(function(previous, current, index, array){\n return previous + current;\n });\n}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
date marker for metrics | function _drawMetricDate(svg,x,y,context){
var gDate = svg.append("g").attr("id","metric_date_"+context.data.title);
var _title = _drawText(gDate,context.data.title,x,y,{"size":"16px","weight":"bold","anchor":"start","color":COLOR_BPTY});
var _m =get_metrics(_title.node());
if (!context.dimension=="goal"){
_drawText(gDate,context.data.line1+" ",x,y+7,{"size":"5px","weight":"normal","anchor":"start","color":COLOR_BPTY});
_drawText(gDate,"[from: "+context.intervalStart.toString('yyyy-MM-dd')+" to: "+context.intervalEnd.toString('yyyy-MM-dd')+" ]",(x+_m.width),y+7,{"size":"6px","weight":"bold","anchor":"end","color":COLOR_BPTY});
_drawText(gDate,context.data.line2+" ",x,y+14,{"size":"5px","weight":"normal","anchor":"start","color":COLOR_BPTY});
if (context.forecastDate)
_drawText(gDate,"[ "+_.last(context.forecastDate).toString('yyyy-MM-dd')+" ]",(x+_m.width),y+14,{"size":"6px","weight":"bold","anchor":"end","color":COLOR_BPTY});
}
} | [
"function drawhook(plot, canvas) {\n var spans = plot.getPlaceholder().parent().children();\n \n spans.filter(\".date_left\").html(\n getTimeString(new Date(plot.getAxes().xaxis.min))\n );\n\n spans.filter(\".date_right\").html(\n getTimeString(new Date(plot.getAxes().xaxis.max))\n );\n }",
"getissueDate(){\n\t\treturn this.dataArray[6];\n\t}",
"function getMarkerIcon(concertDate) {\n var currentDate = +new Date();\n concertDate = convertDateToTimestamp(concertDate);\n var timeToConcert = concertDate - currentDate;\n if (timeToConcert < 1000 * 60 * 60 * 24 * 7) {\n return 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';\n } else if (timeToConcert < 1000 * 60 * 60 * 24 * 30) {\n return 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';\n } else {\n return 'http://maps.google.com/mapfiles/ms/icons/green-dot.png';\n }\n}",
"function update_date() {\n for(let span of query_all('.date')) {\n\tspan.textContent = format_date(span.dataset.ts);\n }\n for(let mark of query_all('.edited_mark')) {\n\tmark.title = format_date(mark.dataset.ts);\n }\n}",
"function MockGoogDate() {}",
"function renderDate() {\n fill(\"black\");\n noStroke();\n textAlign(LEFT, CENTER);\n textSize(height / 2);\n const currentDate = new Date(state.date.from);\n currentDate.setUTCDate(\n currentDate.getUTCDate() + Math.floor(state.daysPassed)\n );\n text(\n currentDate.toISOString().slice(0, 10),\n 30,\n topOffset - gridAreaHeight / 2\n );\n}",
"function addDate_to_image(image){\n var doy = image.date().getRelative('day', 'year');\n var doyBand = ee.Image.constant(doy).uint16().rename('doy');\n doyBand = doyBand.updateMask(image.select('B8').mask());\n\n return image.addBands(doyBand);\n}",
"function getMarkerColour(event_date) {\n if(event_date == null) {\n // Date unknown\n return \"FF00FA\";\n }\n var event_UTC = Date.parse(event_date);\n var current_UTC = Date.now();\n var day_diff = (event_UTC - current_UTC) / (1000*60*60*24);\n\n if(day_diff <= 7) {\n // Within a week\n return \"00BA22\";\n }\n else if(day_diff <= 14) {\n // Within two weeks\n return \"9DFF00\";\n }\n else if(day_diff <= 30) {\n // Within a month\n return \"E5FF00\";\n }\n else if(day_diff <= 60) {\n // Two months\n return \"FFD000\";\n }\n else if(day_diff <= 180) {\n // Six months\n return \"FF8400\";\n }\n else {\n return \"FF4000\";\n }\n }",
"add_date(col) {\n this.df = this.df.map(row => {\n row[\"_date\"] = new Date(row[col])\n return row\n })\n }",
"function plotFiresForDate(date, data) {\n d3.select('#current-date').text(date);\n d3.select('#date-display-svg').text(date);\n updateSelectorSvg();\n\n const satelliteFilter = [...document.getElementsByName('satellites')].map(e => e.checked ? e.value : '').filter(d => !!d);\n const timeFilter = [...document.getElementsByName('time')].map(e => e.checked ? e.value : '').filter(d => !!d);\n\n scatterPlot = document.getElementById('scatterplot-enabled').checked;\n densityPlot = document.getElementById('cdplot-enabled').checked;\n\n const plotData = data[date].filter(d => satelliteFilter.includes(d.satellite) && timeFilter.includes(d.daynight));\n\n drawScatterPlot(plotData, scatterPlot);\n drawDensityPlot(plotData, densityPlot);\n}",
"function date_styler(date) {\n var d = new Date(date);\n return d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();\n }",
"function monthlyReport() {\n\n}",
"function DateFaceter(aAttrDef, aFacetDef) {\n this.attrDef = aAttrDef;\n this.facetDef = aFacetDef;\n}",
"function datadate(selector){\n var y = $(selector).find('header + .episode-row > div:nth-child(2)').text().trim().split(', ');\n var m = y[0].split(' ');\n var d = parseInt(m[1]);\n if(d<10)\n d = '0'+d;\n var monthLabel = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n m = monthLabel.indexOf(m[0]);\n if(m<10)\n m = '0'+m;\n $(selector).attr('data-date', y[1]+m+d);\n }",
"getTimeSeries(now) {\n return {\n labelValues: this.labelValues,\n points: [{ value: this.value, timestamp: now }],\n startTimestamp: this.startTimestamp,\n };\n }",
"function usfEventIcon(objDate) {\n\t\tvar eventIcon = document.createElement('div');\n\t\teventIcon.className = 'widget_calIcon';\n\t\t\n\t\tvar eventIconMonth = document.createElement('span');\n\t\teventIconMonth.className = 'widget_calIconMonth';\n\t\teventIconMonth.appendChild(document.createTextNode(objDate.getAbbrMonthName()));\n\t\t\n\t\tvar eventIconDay = document.createElement('span');\n\t\teventIconDay.className = 'widget_calIconDay';\n\t\teventIconDay.appendChild(document.createTextNode(pad(objDate.Day,2)));\n\t\t\n\t\teventIcon.appendChild(eventIconMonth);\n\t\teventIcon.appendChild(eventIconDay);\n\t\treturn eventIcon;\n\t}",
"function extractStamp(date) {\r\n\treturn Math.round(date.getTime() / 1000);\r\n}",
"toDateString() {\n return `${this.nepaliYear.toString()}/${this.nepaliMonth}/${\n this.nepaliDay\n }`;\n }",
"GenerateStarDate() {\n\t\tlet date = new Date();\n\t\tdate.setDate(date.getDate() - 30);\n\t\tlet month = (date.getMonth() + 1).toString();\n\t\tlet day = date.getDate().toString();\n\t\tif (day.length < 2)\n\t\t\tday = \"0\" + day;\n\t\tif (month.length < 2)\n\t\t\tmonth = \"0\" + month;\n\t\tconst stringDate = date.getFullYear() + \"-\" + month + \"-\" + day;\n\t\treturn stringDate;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
str: a custom projection string, e.g.: "albersusa +PR" | function parseCustomProjection(str) {
var parts = str.trim().split(/ +/);
var params = [];
var names = parts.filter(function(part) {
if (/^\+/.test(part)) {
params.push(part.substr(1)); // strip '+'
return false;
}
return true;
});
var name = names[0];
var opts = parseCustomParams(params);
if (names.length != 1) return null; // parse error if other than one name found
return getCustomProjection(name, opts);
} | [
"function afficheFmtOrigin() {\n var geocoder= viewer.getVariable('geocoder');\n geocoder.resultsElement.value= geocoder.outputResult;\n}",
"toDefaultProjection(lat, long) {\n return ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');\n }",
"function cityName (str) {\n if (str.lenghth >= 3 && (str.substring(0,3) == \"Los\") || (str.substring(0,3) == \"New\"))\n {\n return str\n }\n return \"\"\n\n}",
"function addpoint(lat,lon,text) {\n\n var gpoint = g.append(\"g\").attr(\"class\", \"gpoint\");\n var x = projection([lat,lon])[0];\n var y = projection([lat,lon])[1];\n\n gpoint.append(\"svg:circle\")\n .attr(\"cx\", x)\n .attr(\"cy\", y)\n .attr(\"class\",\"point\")\n .attr(\"r\", 1.5);\n\n //conditional in case a point has no associated text\n if(text.length>0){\n\n gpoint.append(\"text\")\n .attr(\"x\", x+2)\n .attr(\"y\", y+2)\n .attr(\"class\",\"text\")\n .text(text);\n }\n\n }",
"function assemblePublisher(){\n\tif (publisher.value != \"\"){\n\t\tpublisherAssembled = publisher.value.charAt(0).toUpperCase() + publisher.value.slice(1) + \", \"\n\t}\n\telse{\n\t\tpublisherAssembled=\"N.p., \";\n\t}\n}",
"function encodeLatitude(latitude) {\n if (latitude === undefined) {\n return \",\";\n }\n var hemisphere;\n if (latitude < 0) {\n hemisphere = \"S\";\n latitude = -latitude;\n }\n else {\n hemisphere = \"N\";\n }\n // get integer degrees\n var d = Math.floor(latitude);\n // latitude degrees are always 2 digits\n var s = padLeft(d, 2, \"0\");\n // get fractional degrees\n var f = latitude - d;\n // convert to fractional minutes\n var m = (f * 60.0);\n // format the fixed point fractional minutes \"mm.mmmmmm\"\n var t = padLeft(m.toFixed(6), 9, \"0\");\n s = s + t + \",\" + hemisphere;\n return s;\n}",
"function rd_RemoveMarkers_localize(strVar)\r\n\t{\r\n\t\treturn strVar[\"en\"];\r\n\t}",
"function buildDBPediaQuery (name) {\n\t\tindex = name.indexOf(\"City\");\n\t\tvar sparql;\n\t\tif (index==-1) {//it is a county\n\t\t index = name.indexOf(\"County\");\n\t\t\tvar county = name.substring(index+7); \n\t\t\tsparql = \" SELECT distinct ?loc ?web ?img ?map ?wiki \" + //+?area \" +\n\t\t\t\t\t \" WHERE { \" +\n\t\t\t\t\t \" ?loc a <http://dbpedia.org/ontology/Settlement> . \" +\n\t\t\t\t\t \" ?loc <http://purl.org/dc/terms/subject> <http://dbpedia.org/resource/Category:Counties_of_the_Republic_of_Ireland> . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/property/web> ?web . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/ontology/thumbnail> ?img . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/property/mapImage> ?map . \" +\n\t\t\t\t\t \" ?loc <http://www.w3.org/2000/01/rdf-schema#label> ?label . \" +\n\t\t\t\t\t \" ?loc <http://xmlns.com/foaf/0.1/page> ?wiki . \" +\n\t\t\t\t\t //\" ?loc <http://dbpedia.org/property/areaKm> ?area . \" +\n\t\t\t\t\t \" FILTER(REGEX(STR(?label), \\\"\" + county + \"\\\" )) . \" +\n\t\t\t\t\t \" } \";\n\t\t}\n\t\telse {// it is a city\n\t\t\tvar city = name.substring(0,index); \n\t\t\tsparql = \" SELECT distinct ?loc ?web ?img ?wiki \" +\n\t\t\t\t\t \" WHERE { \" +\n\t\t\t\t\t \" ?loc a <http://dbpedia.org/ontology/Place> . \" +\n\t\t\t\t\t \" ?loc <http://purl.org/dc/terms/subject> <http://dbpedia.org/resource/Category:Cities_in_the_Republic_of_Ireland> . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/property/website> ?web . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/ontology/thumbnail> ?img . \" +\n\t\t\t\t\t \" ?loc <http://www.w3.org/2000/01/rdf-schema#label> ?label . \" +\n\t\t\t\t\t \" ?loc <http://xmlns.com/foaf/0.1/page> ?wiki . \" +\n\t\t\t\t\t \" FILTER(REGEX(STR(?label), \\\"\" + city + \"\\\" )) . \" +\n\t\t\t\t\t \" } \" ;\n\t\t}\n\t\treturn sparql;\n\t}",
"function addressComma(st, cty) {\n if (st) {\n return st+ ' ' + cty;\n } else {\n return cty;\n }\n }",
"getPositionName(lat, lng){\n Geocoder.getFromLatLng(lat, lng).\n then(res=>\n {\n const formatted_address = res.results[0].formatted_address;\n const position = {\n lat:lat,\n lng:lng\n };\n\n this.setLocation(formatted_address, position);\n },\n err=>\n {\n return;\n }\n )\n }",
"function formatLocation(city, state, country, zipCode) {\n return (\n city + \", \" + state + \" \" + zipCode + \" \" + country\n );\n}",
"function reformatAddressForRequest(address) {\n return address.split(\" \").join(\"+\").replace(/,/gi, \"\");\n}",
"projection(other_vector) {}",
"function getInString() {\n var retVal = \"\";\n\n var i;\n var values;\n if (clause.showValueField === true) {\n values = clause.selectValueColumn.id.split(',');\n\n } else {\n values = clause.value.split(',');\n }\n\n if (values.length > 0) {\n retVal = \"(\";\n if (clause.filterField.fieldSource) {\n retVal = \"\";\n }\n values.forEach(function (val, idx) {\n if (idx > 0) {\n retVal += \" or \";\n }\n retVal += getCompareString('eq', val);\n });\n retVal += \")\";\n }\n\n return retVal;\n }",
"function Pond (str) {\n this.gridX = spaceParse(str, 0)\n this.gridY = spaceParse(str, 1)\n}",
"static get iso3166() {\n\t\treturn 'CY';\n\t}",
"function getPostalCode(address) {\r\n\tvar firstCommaPos = address.indexOf(\",\");\r\n\tvar lastCommaPos = address.lastIndexOf(\",\", address.length);\r\n\tif (lastCommaPos != firstCommaPos)\r\n\t\treturn address.substring(firstCommaPos + 2, firstCommaPos + 7);\r\n\telse\r\n\t\treturn \"\";\r\n}",
"function create_search_urlparam(search_text, srtype) {\n var param_URL = '';\n var initkey = 1;\n /* Get the common & Locale specific i.e., Fetching global map details to form the -> Search URL Params */\n for (var key in globalsearch_parameter_MAP) {\n if (globalsearch_parameter_MAP.hasOwnProperty(key)) {\n if (initkey == 1) {\n param_URL += key + eq + globalsearch_parameter_MAP[key];\n initkey = 0;\n } else {\n param_URL += amb + key + eq + globalsearch_parameter_MAP[key];\n }\n }\n }\n\n /* Search keyword getting passed */\n param_URL += amb + q + eq + search_text;\n return param_URL;\n }",
"function startOz(str) {\n var result = \"\";\n if (str.length > 1 && (str.charAt(0) == 'o')) {\n result = result + str.charAt(0);\n }\n if (str.length > 2 && (str.charAt(1) == 'z')) {\n result = result + str.charAt(1);\n }\n return result;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instatiates a gizmo manager | function GizmoManager(scene){var _this=this;this.scene=scene;this._gizmosEnabled={positionGizmo:false,rotationGizmo:false,scaleGizmo:false,boundingBoxGizmo:false};this._pointerObserver=null;this._attachedMesh=null;this._boundingBoxColor=BABYLON.Color3.FromHexString("#0984e3");/**
* When bounding box gizmo is enabled, this can be used to track drag/end events
*/this.boundingBoxDragBehavior=new BABYLON.SixDofDragBehavior();/**
* Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
*/this.attachableMeshes=null;/**
* If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
*/this.usePointerToAttachGizmos=true;this._defaultKeepDepthUtilityLayer=new BABYLON.UtilityLayerRenderer(scene);this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=false;this._defaultUtilityLayer=new BABYLON.UtilityLayerRenderer(scene);this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};// Instatiate/dispose gizmos based on pointer actions
this._pointerObserver=scene.onPointerObservable.add(function(pointerInfo,state){if(!_this.usePointerToAttachGizmos){return;}if(pointerInfo.type==BABYLON.PointerEventTypes.POINTERDOWN){if(pointerInfo.pickInfo&&pointerInfo.pickInfo.pickedMesh){var node=pointerInfo.pickInfo.pickedMesh;if(_this.attachableMeshes==null){// Attach to the most parent node
while(node&&node.parent!=null){node=node.parent;}}else{// Attach to the parent node that is an attachableMesh
var found=false;_this.attachableMeshes.forEach(function(mesh){if(node&&(node==mesh||node.isDescendantOf(mesh))){node=mesh;found=true;}});if(!found){node=null;}}if(node instanceof BABYLON.AbstractMesh){if(_this._attachedMesh!=node){_this.attachToMesh(node);}}else{_this.attachToMesh(null);}}else{_this.attachToMesh(null);}}});} | [
"function iglooMain () {\n\tvar me = this;\n\t\n\t// Define state\n\tthis.canvas = null; // igloo exposes its primary canvas to modules for use.\n\tthis.toolPane = null; // igloo exposes its primary toolpane to modules for use.\n\tthis.content = null; // igloo exposes the content panel for convenience.\n\tthis.diffContainer = null; // igloo exposes the diff container for convenience.\n\tthis.ticker = null; // igloo exposes its ticker panel for convenience.\n\n\tthis.currentView = null;\n\t\n\tthis.modules = {};\n\n\t//igloo's logger\n\tthis.log = (window.console && function () {\n\t\tvar args = Array.prototype.slice.call(arguments);\n\t\targs.unshift('Igloo:');\n\t\t//because apparently IE8 console functions don't extend Function\n\t\treturn Function.prototype.apply.call(console.log, console, args);\n\t}) || $.noop;\n\n\tthis.load = function (initData) {\n\t\tvar groups = mw.config.get('wgUserGroups');\n\n\t\tdocument.title = 'igloo - ' + iglooConfiguration.version;\n\n\t\tthis.remoteConnect = initData.doRemoteConnect;\n\t\tthis.firstRun = initData.isFirstRun;\n\t\tthis.sessionKey = initData.sessionId;\n\t\tthis.connectLocal = initData.isDown;\n\n\t\tfor (var i = 0; i < groups.length; i++) {\n\t\t\tif (groups[i] === 'steward' || groups[i] === 'sysop') { \n\t\t\t\tiglooUserSettings.mesysop = true;\n\t\t\t}\n\t\t}\n\n\t\t//Settings\n\t\tthis.cogs = new iglooSettings();\n\t\tthis.cogs.retrieve();\n\n\t\t//Launch\n\t\tthis.launch();\n\t};\n\n\tthis.launch = function () {\n\t\tthis.buildInterface();\n\n\t\tthis.currentView = new iglooView();\n\t\tthis.recentChanges = new iglooRecentChanges();\n\t\tthis.contentManager = new iglooContentManager();\n\t\tthis.statusLog = new iglooStatus();\n\t\tthis.actions = new iglooActions();\n\t\tthis.dropManager = new iglooDropdownManager();\n\t\tthis.piano = new iglooKeys();\n\n\t\tthis.recentChanges.update();\n\t\tthis.recentChanges.setTickTime(iglooUserSettings.updateTime * 1000);\n\t\tthis.statusLog.buildInterface();\n\t\tthis.currentView.displayWelcome();\n\t\tthis.cogs.buildInterface();\n\n\t\tthis.loadModules(); \n\t};\n\n\tthis.buildInterface = function () {\n\t\ttry {\n\t\t\t// Create drawing canvas\n\t\t\tthis.canvas = new jin.Canvas();\n\t\t\tthis.canvas.setFullScreen(true);\n\t\t\t\n\t\t\t// Create base splitter.\n\t\t\tvar mainPanel = new jin.SplitterPanel();\n\t\t\tmainPanel.setPosition(0, 0);\n\t\t\tmainPanel.setSize(0, 0);\n\t\t\tmainPanel.setInitialDrag(260);\n\t\t\tmainPanel.setColour(jin.Colour.DARK_GREY);\n\t\t\tmainPanel.dragWidth = 1;\n\t\t\t\n\t\t\tmainPanel.left.setColour(jin.Colour.DARK_GREY);\n\t\t\tmainPanel.right.setColour(jin.Colour.WHITE);\n\t\t\t\n\t\t\t// Expose recent changes panel.\n\t\t\tthis.ticker = mainPanel.left;\n\t\t\t\n\t\t\t// Create toolbar pane.\n\t\t\tthis.toolPane = new jin.Panel();\n\t\t\tthis.toolPane.setPosition(0, 0);\n\t\t\tthis.toolPane.setSize(0, 100);\n\t\t\tthis.toolPane.setColour(jin.Colour.WHITE);\n\t\t\t\n\t\t\t// Create toolbar border.\n\t\t\tvar toolBorder = new jin.Panel();\n\t\t\ttoolBorder.setPosition(0, 100);\n\t\t\ttoolBorder.setSize(0, 1);\n\t\t\ttoolBorder.setColour(jin.Colour.DARK_GREY);\n\t\t\t\n\t\t\t// Create content panel.\n\t\t\tthis.content = new jin.Panel();\n\t\t\tthis.content.setPosition(0, 101);\n\t\t\tthis.content.setSize(0, 0);\n\t\t\tthis.content.setColour(jin.Colour.WHITE);\n\n\t\t\t//filter bar\n\t\t\tthis.filterBar = new jin.Panel();\n\t\t\tthis.filterBar.setPosition(0, 0);\n\t\t\tthis.filterBar.setSize(0, 11);\n\t\t\tthis.filterBar.setColour(jin.Colour.GREY);\n\n\t\t\t//statusBorder\n\t\t\tvar filterBorder = new jin.Panel();\n\t\t\tfilterBorder.setPosition(0, 11);\n\t\t\tfilterBorder.setSize(0, 1);\n\t\t\tfilterBorder.setColour(jin.Colour.DARK_GREY);\n\n\t\t\t// Create diff container.\n\t\t\tthis.diffContainer = new jin.Panel();\n\t\t\tthis.diffContainer.setPosition(0, 13);\n\t\t\tthis.diffContainer.setSize(0, (mainPanel.right.getHeight() - 160));\n\t\t\tthis.diffContainer.setColour(jin.Colour.WHITE);\n\t\t\tthis.diffContainer.setOverflow('auto');\n\t\t\t\n\t\t\t// Combine interface elements.\n\t\t\tthis.content.add(this.filterBar);\n\t\t\tthis.content.add(filterBorder);\n\t\t\tthis.content.add(this.diffContainer);\n\t\t\tmainPanel.right.add(this.toolPane);\n\t\t\tmainPanel.right.add(toolBorder);\n\t\t\tmainPanel.right.add(this.content);\n\t\t\tthis.canvas.add(mainPanel);\n\t\t\t\n\t\t\t// Do initial render.\n\t\t\tthis.canvas.render(jin.getDocument());\n\n\t\t\tthis.fireEvent('core','interface-rendered', true);\n\t\t} catch (e) {\n\t\t\tjin.handleException(e);\n\t\t}\n\t};\n\n\n\t/*\n\t\tUI ======================\n\t\t*/\n\tthis.getCurrentView = function () {\n\t\treturn this.currentView;\n\t};\n\n\n\t/*\n\t\tEVENTS ==================\n\t\t*/\n\tthis.announce = function (moduleName) {\n\t\tif (!this.modules[moduleName]) this.modules[moduleName] = {};\n\t\tthis.modules[moduleName]['exists'] = true;\n\t\tthis.modules[moduleName]['ready'] = true;\n\t};\n\n\tthis.isModuleReady = function (moduleName) {\n\t\tif (!this.modules[moduleName]) return false;\n\t\treturn this.modules[moduleName]['ready'];\n\t};\n\n\tthis.hookEvent = function (moduleName, hookName, func) {\n\t\tvar me = this;\n\n\t\tif (hookName === 'exists' || hookName === 'ready') return 1;\n\n\t\tif ($.isArray(hookName)) {\n\t\t\tfor (var hook = 0; hook < hookName.length; hook++) {\n\t\t\t\tme.hookEvent(moduleName, hookName[hook], func);\n\t\t\t}\n\t\t} else {\n\t\t\tif (!this.modules[moduleName]) { \n\t\t\t\tthis.modules[moduleName] = {};\n\t\t\t\tthis.modules[moduleName]['exists'] = true;\n\t\t\t\tthis.modules[moduleName]['ready'] = false; \n\t\t\t}\n\n\t\t\tif (!this.modules[moduleName][hookName]) {\n\t\t\t\tthis.modules[moduleName][hookName] = [func];\n\t\t\t} else {\n\t\t\t\tthis.modules[moduleName][hookName].push(func);\n\t\t\t}\n\n\t\t\treturn 0;\n\t\t}\n\t};\n\n\tthis.unhookEvent = function (moduleName, hookName, func) {\n\t\tif (this.modules[moduleName]) {\n\t\t\tif (this.modules[moduleName][hookName]) {\n\t\t\t\tfor (var i = 0; i < this.modules[moduleName][hookName].length; i++) {\n\t\t\t\t\tif (this.modules[moduleName][hookName][i] === func)\n\t\t\t\t\t\tthis.modules[moduleName][hookName][i] = null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\tthis.fireEvent = function (moduleName, hookName, data) {\n\t\tvar me = this;\n\t\tif ($.isArray(moduleName)) {\n\t\t\tfor (var module = 0; module < moduleName.length; module++) {\n\t\t\t\tme.fireEvent(moduleName[module], hookName, data);\n\t\t\t}\n\t\t} else {\n\t\t\tif (this.modules[moduleName]) {\n\t\t\t\tif (this.modules[moduleName][hookName]) {\n\t\t\t\t\tfor (var i = 0; i < this.modules[moduleName][hookName].length; i++) {\n\t\t\t\t\t\tif (this.modules[moduleName][hookName][i] !== null)\n\t\t\t\t\t\t\tthis.modules[moduleName][hookName][i](data, hookName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\tthis.loadModules = function () {\n\t\tthis.justice = new iglooReversion();\n\t\tthis.justice.buildInterface();\n\t\tthis.announce('rollback');\n\n\t\tthis.trash = new iglooDelete();\n\t\tthis.trash.buildInterface();\n\t\tthis.announce('csd');\n\n\t\tthis.archives = new iglooArchive();\n\t\tthis.archives.buildInterface();\n\t\tthis.announce('archives');\n\n\t\tthis.detective = new iglooSearch();\n\t\tthis.detective.buildInterface();\n\t\tthis.announce('search');\n\n\t\tthis.past = new iglooPast();\n\t\tthis.past.buildInterface();\n\t\tthis.announce('hist');\n\n\t\tthis.bindKeys();\n\t\tthis.fireEvent('core', 'modules-loaded', true);\n\t};\n\n\tthis.bindKeys = function () {\n\t\tif (iglooUserSettings.upDownKeys) {\n\t\t\tthis.piano.register('up', 'default', function () {\n\t\t\t\tigloo.recentChanges.browseFeed(-1);\n\t\t\t});\n\n\t\t\tthis.piano.register('down', 'default', function () {\n\t\t\t\tigloo.recentChanges.browseFeed(1);\n\t\t\t});\n\t\t}\n\n\t\tthis.piano.register('backspace', 'default', function () {\n\t\t\tigloo.archives.goBack(1);\n\t\t});\n\n\t\tthis.piano.register('f5', 'default', function () {\n\t\t\tvar keyCheck = confirm('You just pressed the F5 key. By default, this causes the page to refresh in most browsers. To prevent you losing your work, igloo therefore agressively blocks this key. Do you wish to reload the page?');\n\t\t\tif (keyCheck === true) {\n\t\t\t\twindow.location.reload(true);\n\t\t\t}\n\t\t});\n\t};\n}",
"function gameManager() {\n switch (game.gameMode) {\n case \"Classic\":\n {\n classic();\n break;\n }\n case \"Survival\":\n {\n survival();\n break;\n }\n case \"TimeAttack\":\n {\n ui.showUI(\"TimeAttackUI\");\n timeAttack();\n break;\n }\n }\n}",
"async init() {\r\n await Managers.findOne({username: this.username}, function(error, manager) {\r\n if(error) {\r\n console.log(error);\r\n return;\r\n }\r\n else {\r\n this.production = manager.production; \r\n this.powerPlantStatus = manager.powerPlantStatus; \r\n this.electricityPrice = manager.electricityPrice;\r\n this.marketRatio = manager.marketRatio;\r\n this.bufferRatio = manager.bufferRatio;\r\n this.bufferBatteryCapacity = manager.bufferBatteryCapacity;\r\n this.bufferBattery = new BufferBattery(this.username, manager.bufferBatteryCapacity, config.managerBatteryMaxCapacity);\r\n this.blackoutList = manager.blackoutList;\r\n console.log(\"Initialized manager\");\r\n }\r\n }.bind(this)).exec();\r\n }",
"async function createManager() {\n const newManager = await new Manager();\n await newManager.getOfficeNumber();\n await manager.push(newManager);\n await generatorQs();\n}",
"constructor() {\r\n ObjectManager.instance = this;\r\n\r\n }",
"async createManager() {\r\n let newManager = new Managers ({\r\n username: this.username,\r\n production: config.powerplant_production,\r\n powerPlantStatus: \"Running\"\r\n })\r\n\r\n await newManager.save(function(error){\r\n if (error) {\r\n console.log(error);\r\n return;\r\n } else {\r\n console.log(\"Manager added to database yey\")\r\n }\r\n });\r\n }",
"function MonsterManager() {\n Manager.call(this);\n}",
"createPlayerManagers() {\n dg(`creating 4 player managers`, 'debug')\n for (let i = 0; i < 4; i++) {\n let player = new PlayerManager(i, this)\n player.init()\n this._playerManagers.push(player)\n this._playerManagers[0].isTurn = true\n }\n dg('player managers created', 'debug')\n }",
"function loadManager() {\n Media.log('PluginManager::loadManager');\n if (state() != Media.PluginManager.State.Initializing ||\n pluginObj.state() != Media.PluginObject.State.Attached)\n return;\n var options = Media.PluginDataHandler.generateBlob(language, isRtl);\n try {\n startLoadTimer();\n pluginObj.innerObject().Load('__pluginFx', options);\n }\n catch (error) {\n stopLoadTimer();\n cleanupPluginObject(error);\n state.set(Media.PluginManager.State.Deinitialized);\n }\n }",
"getManager(type) {\n return self.managers[self.normalizeType(type)];\n }",
"function InstagramConsumerManager() {\n\n}",
"function AppManager(){\n}",
"function agacharMario() {\n\tif (agachado == true && ultimaDireccion == 0) {\n\t\tmarioSprite = mario.izquierdaAbajo;\n\t\tdibujar();\n\t}\n\telse if (mirando == true && ultimaDireccion == 1)\n\t\tmarioSprite = mario.derechaAbajo;\n\t\tdibujar();\n}",
"function Show(mode : GIZMO_MODE){\n\tif(_selectedObject == null)\n\t\treturn;\n\t\t\n\tfor(var t : Transform in transform){\n\t\tif(t.GetComponent.<Renderer>())\n\t\t\tt.GetComponent.<Renderer>().enabled = true;\n\t\t\n\t\tif(t.GetComponent.<Collider>())\n\t\t\tt.GetComponent.<Collider>().isTrigger = false;\n\t}//for\n\t\n\tSetMode(mode);\n\t_showGizmo = true;\n}//Show",
"giveAI() {\n\n this.isAI = true;\n\n this.AIcontroller = new AIController(this);\n\n\n }",
"inicializa(){\n globais.placar = criarPlacar();\n }",
"function init() {\n cache.set(\"appName\", \"Lunch Box\");\n cache.set(\"currency\", \"ETH\");\n cache.set(\"showAddBalance\", false);\n updateAccountInformation();\n\n // set up event listeners\n var contract = web3.eth.contract(deployedAbi);\n var contractInstance = contract.at(deployedAddress);\n\n var eventListener = contractInstance.allEvents();\n eventListener.watch(function(error, event) {\n // just update the meals cache whenever an event arrives\n getMeals();\n // also update single meal cache whenever the event is about the current displayed meal\n if (cache.get('meal') && cache.get('meal').id == event.args.ID.toNumber()) {\n getMeal(event.args.ID.toNumber());\n }\n // balance could also have been updated after an event, update accordingly\n updateAccountInformation();\n });\n //*/\n\n // update page when MetaMask account is changed\n ethereum.on(\"accountsChanged\", function() {\n updateAccountInformation();\n })\n}",
"_initCLI() {\n console.info(`${this._color(32)}Logged in. Fetching competitions...${this._color(0)}`);\n this._client.arena.competitions()\n .then(this._arenaCompetitions.bind(this));\n }",
"function iglooDropdownManager () {\n\tthis.dropdowns = [];\n\n\tthis.add = function (dropdown) {\n\t\tthis.dropdowns.push(dropdown);\n\t};\n\n\tthis.opened = function (name) {\n\t\tvar drops = this.dropdowns;\n\n\t\tfor (var i = 0; i < drops.length; i++) {\n\t\t\tif (drops[i].name !== name) drops[i].close();\n\t\t}\n\t};\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
logs at most 5 so it only does 5 operations no matter n | function logAtMost5(n) {
for (let i = 0; i <= Math.min(5, n); i ++){
// O(1)
console.log(i)
}
} | [
"function doStuff4(N) {\n let myNum = 2;\n myNum = myNum * myNum * myNum;\n\n doStuff3(N); // O(N+4) + 2\n\n for (let i = 0; i < N; i++) {\n // O(N)\n }\n}",
"function multiples(n) {\n var sum = 0;\n for (var i = 0; i < n; i++) {\n if (i%5 === 0 || i%7 === 0) {\n sum = sum + i;\n }\n }\n return sum;\n}",
"hormonic(n) {\n var value = 0;\n\n while (n > 0) {\n value = value + (1 / n);\n n--\n }\n console.log(' this is the final hormonic value ' + value)\n }",
"function benchmarkN(name, n, f) {\n console.log(name + ':');\n var args = Array.prototype.slice.call(arguments).slice(3);\n var s = Date.now();\n \n for(var i = 0; i < n; i++){\n f.apply(null, args);\n }\n\n var t = Date.now() - s;\n console.log('time = ' + t + 'msec');\n return t;\n}",
"function ThreesFives()\n{\n var sum = 0;\n\n for(var i = 100; i <= 4000000; i++)\n {\n if((i % 3 == 0 || i % 5 == 0) && (i % 15 !== 0))\n {\n sum += i;\n }\n }\n\n console.log(sum);\n}",
"function PrintandCount() {\n\tvar count = 0;\n\tfor (var i = 512; i < 4096; i++) {\n\t\tif(i % 5 == 0){\n\t\t\tconsole.log(i)\n\t\t\tcount = count + 1\n\t\t}\n\t}\n\tconsole.log(\"number of integers multiple of 5:\", count)\n}",
"function task1(n) {\n if (n >= 1) {\n for (i = 1; i <= n; i += 1) {\n console.log(i + ' ');\n }\n }\n else {\n for (i = 1; i >= n; i -= 1) {\n console.log(i + ' ');\n }\n }\n}",
"function faculteit(n) {\n\n}",
"function main() {\n let numerator = [3];\n let denominator = [2];\n let count = 0;\n for (let i = 1; i <= 1000; i += 1) {\n // console.log(numerator, denominator);\n let temp = carryForwardSum(numerator, denominator);\n numerator = carryForwardSum(temp, denominator);\n denominator = temp;\n temp = null;\n if (numerator.length > denominator.length) {\n count += 1;\n }\n }\n return count;\n}",
"repeat (n, f, o) { for (let i = 0; i < n; i++) f(i, o); return o }",
"function repeat(fn, n) {\nfor(let i=0; i<n; i++) {\n\tfn();\n}\n\n}",
"function mult(n){\n var mult=0;\n for (var i = 1; i < n; i++) {\n mult =mult+mult*i;\n }\n \n return mult ;\n }",
"function fiveMultiples(arr,start)\r\n{\r\n \r\n if((start*5)<=100) // creating multiples of 5 till '100'\r\n {\r\n \r\n arr.push(start*5);\r\n \r\n return fiveMultiples(arr,start+1); //recursive loop to keep creating multiples of 5 \r\n }\r\n\r\n else\r\n {\r\n return arr;\r\n }\r\n \r\n}",
"function PagesPerMinute() {\n // Your code here\n for (i = 1, dep = 20; i <= 6; i++) {\n result = dep * i;\n console.log(result);\n }\n}",
"function sumEveryNth(numbers, n) {\n\tlet a = 0;\n\tfor (let i = 0; i < numbers.length; i++) {\n\t\tif ((i + 1) % n === 0) {\n\t\t\ta += numbers[i];\n\t\t}\n\t}\n return a;\n}",
"function sum_odd_5000(){\n var sum = 0;\n for(var i=1; i<5000; i+=2){\n sum = sum + i;\n }\n return sum;\n}",
"steps20(num) {\n let steps = 0;\n while (num > 0) {\n num = (num % 2 === 0) ? num / 2 : --num;\n steps++;\n }\n return steps;\n }",
"function complicatedMath(n1,n2,n3,n4){\n return (n1+n2) % (n3-n4)\n}",
"function memoizeFactorial(n){\r\n\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initiaites the code for creating the Shadowed Button. | init() {
this._createShadowRoot()
this._attachStyles()
this._createElements()
} | [
"function makeWhaleSharkButton() {\n\n // Create the clickable object\n whaleSharkButton = new Clickable();\n \n whaleSharkButton.text = \"\";\n\n whaleSharkButton.image = images[23]; \n\n //makes the button color transparent \n whaleSharkButton.color = \"#00000000\";\n whaleSharkButton.strokeWeight = 0; \n\n //set width + height to image size\n whaleSharkButton.width = 270; \n whaleSharkButton.height = 390;\n\n // placing the button on the page \n whaleSharkButton.locate( width * (31/32) - whaleSharkButton.width * (31/32), height * (1/128) - whaleSharkButton.height * (1/128));\n\n // // Clickable callback functions for the whaleshark button , defined below\n whaleSharkButton.onPress = whaleSharkButtonPressed;\n whaleSharkButton.onHover = beginButtonHover;\n whaleSharkButton.onOutside = animalButtonOnOutside;\n}",
"function makeDolphinButton() {\n\n // Create the clickable object\n dolphinButton = new Clickable();\n \n dolphinButton.text = \"\";\n\n dolphinButton.image = images[18]; \n\n // gives the dolphin a transparent background \n dolphinButton.color = \"#00000000\";\n dolphinButton.strokeWeight = 0; \n\n // set width + height to image size\n dolphinButton.width = 401; \n dolphinButton.height = 266;\n\n // places the button \n dolphinButton.locate( width * (1/2) - dolphinButton.width * (1/2), height * (1/4) - dolphinButton.height * (1/4));\n\n // Clickable callback functions, defined below\n dolphinButton.onPress = dolphinButtonPressed;\n dolphinButton.onHover = beginButtonHover;\n dolphinButton.onOutside = animalButtonOnOutside;\n}",
"function makeMantaRayButton() {\n\n // Create the clickable object\n mantaRayButton = new Clickable();\n \n mantaRayButton.text = \"\";\n\n mantaRayButton.image = images[16]; \n\n // gives the Manta ray a transparent background \n mantaRayButton.color = \"#00000000\";\n mantaRayButton.strokeWeight = 0; \n\n // set width + height to image size\n mantaRayButton.width = 242; \n mantaRayButton.height = 156;\n\n // places the button on the page \n mantaRayButton.locate( width * (1/32) - mantaRayButton.width * (1/32), height * (1/3) - mantaRayButton.height * (1/3));\n\n // // Clickable callback functions, defined below\n mantaRayButton.onPress = mantaRayButtonPressed;\n mantaRayButton.onHover = beginButtonHover;\n mantaRayButton.onOutside = animalButtonOnOutside;\n}",
"function makeOctopusButton() {\n\n // Create the clickable object\n octopusButton = new Clickable();\n \n octopusButton.text = \"\";\n\n octopusButton.image = images[21]; \n\n // makes the image transparent\n octopusButton.color = \"#00000000\";\n octopusButton.strokeWeight = 0; \n\n // set width + height to image size\n octopusButton.width = 290; \n octopusButton.height = 160;\n\n // places the button \n octopusButton.locate( width * (13/16) - octopusButton.width * (13/16), height * (1/2) - octopusButton.height * (1/2));\n\n // Clickable callback functions, defined below\n octopusButton.onPress = octopusButtonPressed;\n octopusButton.onHover = beginButtonHover;\n octopusButton.onOutside = animalButtonOnOutside;\n}",
"function makeCoralReefButton() {\n\n // Create the clickable object\n coralReefButton = new Clickable();\n \n coralReefButton.text = \"Click here to see your coral reef!\";\n coralReefButton.textColor = \"#365673\"; \n coralReefButton.textSize = 37; \n\n coralReefButton.color = \"#8FD9CB\";\n\n // set width + height to image size\n coralReefButton.width = 994;\n coralReefButton.height = 90;\n\n // places the button on the page \n coralReefButton.locate( width/2 - coralReefButton.width/2 , height * (3/4));\n\n // // Clickable callback functions, defined below\n coralReefButton.onPress = coralReefButtonPressed;\n coralReefButton.onHover = beginButtonHover;\n coralReefButton.onOutside = beginButtonOnOutside;\n}",
"button(x, y, content, opts){\n\n let button = new Button(x, y, content, opts);\n this.layer.buttons.push(button);\n return button;\n\n }",
"function makeCoralImportanceButton() {\n\n // Create the clickable object\n coralImportanceButton = new Clickable();\n \n coralImportanceButton.text = \"Why are coral reefs important?\";\n coralImportanceButton.textColor = \"#365673\"; \n coralImportanceButton.textSize = 25; \n\n coralImportanceButton.color = \"#8FD9CB\";\n\n // set width + height to image size\n coralImportanceButton.width = 420;\n coralImportanceButton.height = 62;\n\n // places the button \n coralImportanceButton.locate( width * (1/32) , height * (7/8));\n\n // // Clickable callback functions, defined below\n coralImportanceButton.onPress = coralImportanceButtonPressed;\n coralImportanceButton.onHover = beginButtonHover;\n coralImportanceButton.onOutside = beginButtonOnOutside;\n}",
"function makeClownfishButton() {\n\n // Create the clickable object\n clownfishButton = new Clickable();\n \n clownfishButton.text = \"\";\n\n clownfishButton.image = images[20]; \n\n // makes the button's background transparent \n clownfishButton.color = \"#00000000\";\n clownfishButton.strokeWeight = 0; \n\n // set width + height to image size\n clownfishButton.width = 200; \n clownfishButton.height = 100;\n\n // places the button on the page \n clownfishButton.locate( width * (1/16) - clownfishButton.width * (1/16), height * (10/16) - clownfishButton.height * (10/16));\n\n //Clickable callback functions, defined below\n clownfishButton.onPress = clownfishButtonPressed;\n clownfishButton.onHover = beginButtonHover;\n clownfishButton.onOutside = animalButtonOnOutside;\n}",
"init() {\n if (!this.menuButton) {\n this.menuButton = this.createMenuButton();\n }\n this.menuButton.addEventListener(\n 'click',\n this.handleButtonClick.bind(this)\n );\n if (!this.closeButton) {\n this.closeButton = this.createCloseButton();\n }\n this.closeButton.addEventListener(\n 'click',\n this.handleButtonClick.bind(this)\n );\n this.disableTab(this.overlay);\n }",
"function createDefaultSetupButtons () {\n\t//Removes all buttons\n\t$(\".newButton\").remove();\n\t//Creates Names (if statement changes name of buttons)\n\tvar setupIds = {\n\t\t\"button_human\": \"Human\",\n\t\t\"button_elf\": \"Elf\",\n\t\t\"button_dwarf\": \"Dwarf\"\n\t}\n\t//This is what to edit if you want to add more shared params to the set of buttons that's being created\n\tcreateAndAddSetOfButtons(\".button_stack\", {classes: \"newButton\", mouseleave:mousePreviewLeave, mouseenter:mousePreviewEnter, click:chooseRace}, setupIds);\n}",
"initShadows($MIRROR, $SHADOWS_PANEL, _SOC_DATA) {\n const $mirror_content = $($MIRROR.contents());\n console.debug(\n \"Mirror is loaded: width[%s], height[%s]\",\n $mirror_content.width(),\n $mirror_content.height()\n );\n\n // Set width and height for proper position\n $MIRROR.height($mirror_content.height());\n $SHADOWS_PANEL.height($mirror_content.height());\n\n // Calculate shadows and set correct positions\n const mirrorUtil = new MirrorUtil();\n _SOC_DATA.rootNode = mirrorUtil.getPageComponents($mirror_content.find(\"body\"));\n const pageUtil = new PageUtil();\n pageUtil.shadowsTreeNodes(_SOC_DATA.rootNode).forEach((el) => {\n $SHADOWS_PANEL.append(el);\n });\n\n const HOVER_BORDER_SIZE = 2; // in px\n mirrorUtil\n .getShadows(_SOC_DATA.rootNode.children)\n .forEach((el) => {\n console.debug(\"Set position of: %s\", el[4]);\n const shadow = $(\"#\" + el[4]);\n if (shadow) {\n shadow.css({\n \"top\": el[0],\n \"left\": el[1] + HOVER_BORDER_SIZE,\n \"width\": el[2] - HOVER_BORDER_SIZE * 4,\n \"height\": el[3] - HOVER_BORDER_SIZE * 2\n });\n }\n });\n\n const _menu = new ShadowComponentMenu();\n\n $SHADOWS_PANEL.on(\"click\", \".shadow-component\", (e) => {\n const id = $(e.target).attr(\"id\");\n if (id) {\n const selectedShadow = _SOC_DATA.rootNode.getChildById(id);\n if (selectedShadow) {\n _SOC_DATA.selectedEl = selectedShadow;\n }\n }\n _menu.showToolbar(e.target);\n });\n $SHADOWS_PANEL.show();\n }",
"function setShadow(data, clock) {\n clock.rotateElement(shadow, data.angle);\n shadow.style.opacity = data.opacity;\n}",
"createButton () {\n\n this.button = document.createElement('button')\n\n this.button.title = 'This model has multiple views ...'\n\n this.button.className = 'viewable-selector btn'\n\n this.button.onclick = () => {\n this.showPanel(true)\n }\n\n const span = document.createElement('span')\n span.className = 'fa fa-list-ul'\n this.button.appendChild(span)\n\n const label = document.createElement('label')\n this.button.appendChild(label)\n label.innerHTML = 'Views'\n \n this.viewer.container.appendChild(this.button)\n }",
"BuildMenuButton(){\n // Menu bar Translucide\n NanoXSetMenuBarTranslucide(true)\n // clear menu button left\n NanoXClearMenuButtonLeft()\n // clear menu button right\n NanoXClearMenuButtonRight()\n // clear menu button setttings\n NanoXClearMenuButtonSettings()\n // Show name in menu bar\n NanoXShowNameInMenuBar(false)\n }",
"function makeCrabButton() {\n\n // Create the clickable object\n crabButton = new Clickable();\n \n crabButton.text = \"\";\n\n crabButton.image = images[22]; \n\n // gives the button a transparent background and changes the stroke to 0 \n crabButton.color = \"#00000000\";\n crabButton.strokeWeight = 0; \n\n //set width + height to image size\n crabButton.width = 280; \n crabButton.height = 120;\n\n // placing the button on the page \n crabButton.locate( width * (1/16) - crabButton.width * (1/16), height * (26/32) - crabButton.height * (26/32));\n\n // // Clickable callback functions, defined below\n crabButton.onPress = crabButtonPressed;\n crabButton.onHover = beginButtonHover;\n crabButton.onOutside = animalButtonOnOutside;\n}",
"createUI() {\n var title = panelTitle;\n this.panel = new PanelClass(this.viewer, title);\n var button1 = new Autodesk.Viewing.UI.Button(panelTitle);\n\n button1.onClick = (e) => {\n if (!this.panel.isVisible()) {\n this.panel.setVisible(true);\n } else {\n this.panel.setVisible(false);\n }\n };\n\n button1.addClass('fa');\n button1.addClass('fa-child');\n button1.addClass('fa-2x');\n button1.setToolTip(onMouseOver);\n\n this.subToolbar = this.viewer.toolbar.getControl(\"spinalcom-sample\");\n if (!this.subToolbar) {\n this.subToolbar = new Autodesk.Viewing.UI.ControlGroup('spinalcom-sample');\n this.viewer.toolbar.addControl(this.subToolbar);\n }\n this.subToolbar.addControl(button1);\n this.initialize();\n }",
"function ELEMENT_ARROW_BUTTON$static_(){FavoritesToolbar.ELEMENT_ARROW_BUTTON=( FavoritesToolbar.BLOCK.createElement(\"arrow-button\"));}",
"function makeTurtleButton() {\n\n // Create the clickable object\n turtleButton = new Clickable();\n \n turtleButton.text = \"\";\n\n turtleButton.image = images[17]; \n\n // this makes the turtle's background transparent \n turtleButton.color = \"#00000000\";\n turtleButton.strokeWeight = 0; \n\n // set width + height to image size\n turtleButton.width = 317; \n turtleButton.height = 211;\n\n // places the button on the page \n turtleButton.locate( width * (15/16) - turtleButton.width * (15/16), height * (13/16) - turtleButton.height * (13/16));\n\n // // Clickable callback functions, defined below\n turtleButton.onPress = turtleButtonPressed;\n turtleButton.onHover = beginButtonHover;\n turtleButton.onOutside = animalButtonOnOutside;\n}",
"function makeMainBtn() {\n var mainLayout = new android.widget.RelativeLayout(ctx);\n windows.mainWindow = new android.widget.PopupWindow(mainLayout, -2, -2);\n\n var mainBtn = makeImgButton(GUI_PATH + \"/ic_main.png\", new android.view.View.OnClickListener({\n onClick: function(v) {\n if (!isScriptable) return;\n main();\n }\n }), null, null, false);\n mainLayout.addView(mainBtn);\n\n setWindow(windows.mainWindow, mainLayout, dip2px(50), dip2px(50), new android.graphics.drawable.ColorDrawable(android.graphics.Color.TRANSPARENT), false, [ctx.getWindow().getDecorView(), android.view.Gravity.LEFT | android.view.Gravity.TOP, (readData(\"main_button_x\") == \"\" || readData(\"main_button_x\") == \"undefined\") ? dip2px(2) : parseInt(readData(\"main_button_x\")), (readData(\"main_button_y\") == \"\" || readData(\"main_button_y\") == \"undefined\") ? dip2px(4) : parseInt(readData(\"main_button_y\"))]);\n\n setDragable(windows.mainWindow, mainBtn, \"main_button_x\", \"main_button_y\", 0);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
11 Function daClub Create a function named `daClub` which takes two parameters: `cover` and `age`. | function daClurb(cover, age){
if(age >=21 && cover >=21){
return "Welcome to the Legends Lounge.";
}else{
return "Chuck E Cheese is across the street.";
}
} | [
"function daClub (cover, age) {\n if (cover && age >= 21) {\n return \"Welcome to the Legends Lounge.\";\n }\n else {\n return \"Chuck E. Cheese is across the street.\";\n }\n}",
"function dogFactory(name, gender) {\n // some other code here\n\n return {\n name: name,\n gender: gender,\n nameAndGender: function () {\n return `${name} : ${gender}`;\n },\n };\n}",
"function makeDessert() {\n\n}",
"function retirement(retirementAge) {\n var a = ' years left until retirement.';\n return function(yob) {\n var age = 2020 - yob;\n console.log((retirementAge - age) + a);\n }\n}",
"function calculateDogAge(age, conversionRate) {\n var dogYears = age * conversionRate;\n console.log(`your doggie is ${dogYears} years old in dog years!`);\n}",
"function Harold() {}",
"function getAge() {\n return 41;\n}",
"function inDogYears(age) {\n return age * 7;\n}",
"function peopleWithAgeDrink(age) {\n var drink;\n if (age < 14)\n drink = \"toddy\";\n else if (age < 18)\n drink = \"coke\";\n else if (age < 21)\n drink = \"beer\";\n else if (age >= 21)\n drink = \"whisky\";\n return \"drink \" + drink;\n}",
"function calcAge(birthday, timeMultiplierInFunc) {\n //Get the users D.O.B. and split it into useable chunks\n var days = moment().diff(birthday, 'days');\n siteVisitor.years = days / timeMultiplierInFunc;\n\n \n \n}",
"constructor(_name, age, breed) {\n this._name = _name;\n this.age = age;\n this.breed = breed;\n /* this._name=_name;\n this.age=age;\n this.breed=breed; */\n }",
"function calculateDogYears(dogYears){\n return dogYears * 7;\n}",
"function basicTeenager(age)\n {if (age >= 13 && age <= 19){\n return \"You are a teenager!\";\n }\n }",
"function vig() {\n \n}",
"function SpausdinuVarda(vardas) {\n console.log(vardas);\n}",
"function name(lastName, firstName) {\n console.log()\n \n}",
"function fullAge(adultRequire, age){\r\n return age >= adultRequire;\r\n}",
"function calcAge(yearBorn) {\n return 2019 - yearBorn;\n}",
"function ageCaliculator(dob) {\n\tvar presentDate= new Date();\n\tvar presentYear = presentDate.getFullYear();\n\tvar birthDate = new Date(dob);\n\tvar age = presentYear - birthDate.getFullYear()\n\treturn age;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the AWS CloudFormation properties of an `AWS::S3::Bucket.ReplicaModifications` resource | function cfnBucketReplicaModificationsPropertyToCloudFormation(properties) {
if (!cdk.canInspect(properties)) {
return properties;
}
CfnBucket_ReplicaModificationsPropertyValidator(properties).assertSuccess();
return {
Status: cdk.stringToCloudFormation(properties.status),
};
} | [
"function CfnBucket_ReplicaModificationsPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('status', cdk.requiredValidator)(properties.status));\n errors.collect(cdk.propertyValidator('status', cdk.validateString)(properties.status));\n return errors.wrap('supplied properties not correct for \"ReplicaModificationsProperty\"');\n}",
"function cfnVirtualNodeFileAccessLogPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_FileAccessLogPropertyValidator(properties).assertSuccess();\n return {\n Format: cfnVirtualNodeLoggingFormatPropertyToCloudFormation(properties.format),\n Path: cdk.stringToCloudFormation(properties.path),\n };\n}",
"function cfnVirtualNodeAccessLogPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_AccessLogPropertyValidator(properties).assertSuccess();\n return {\n File: cfnVirtualNodeFileAccessLogPropertyToCloudFormation(properties.file),\n };\n}",
"function displayComponent() {\n var range = SpreadsheetApp.getActiveRange();\n var cell = range.getValue().trim();\n \n var documentProperties = PropertiesService.getDocumentProperties();\n var hdID = documentProperties.getProperty('hdID');\n \n var component = getComponentAttributes(getComponent(hdID,cell));\n \n var header = '<html><head><link rel=\"stylesheet\" href=\"https://unpkg.com/purecss@1.0.0/build/pure-min.css\" integrity=\"sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w\" crossorigin=\"anonymous\"></head><body>';\n var footer = '</body></html>';\n \n var cFlat = '<table class=\"pure-table pure-table-bordered\"><caption>Properties of component \"' + cell + '\"' + '<thead><tr><td>Property</td><td>Value</td></tr></thead>';\n for (var e in component) {\n cFlat += '<tr><td>' + e + '</td><td>'+ component[e] + '</td></tr>';\n }\n cFlat += '</table>';\n \n var html = HtmlService.createHtmlOutput(header + cFlat + footer)\n .setTitle('Component Properties')\n .setWidth(450);\n SpreadsheetApp.getUi()\n .showSidebar(html);\n}",
"function cfnVirtualGatewayVirtualGatewayAccessLogPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayAccessLogPropertyValidator(properties).assertSuccess();\n return {\n File: cfnVirtualGatewayVirtualGatewayFileAccessLogPropertyToCloudFormation(properties.file),\n };\n}",
"function cfnVirtualGatewayVirtualGatewayFileAccessLogPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayFileAccessLogPropertyValidator(properties).assertSuccess();\n return {\n Format: cfnVirtualGatewayLoggingFormatPropertyToCloudFormation(properties.format),\n Path: cdk.stringToCloudFormation(properties.path),\n };\n}",
"update(changedProperties) {\n // Setting properties in `render` should not trigger an update. Since\n // updates are allowed after super.update, it's important to call `render`\n // before that.\n const templateResult = this.render();\n super.update(changedProperties);\n // If render is not implemented by the component, don't call lit-html render\n if (templateResult !== renderNotImplemented) {\n this.constructor\n .render(templateResult, this.renderRoot, { scopeName: this.localName, eventContext: this });\n }\n // When native Shadow DOM is used but adoptedStyles are not supported,\n // insert styling after rendering to ensure adoptedStyles have highest\n // priority.\n if (this._needsShimAdoptedStyleSheets) {\n this._needsShimAdoptedStyleSheets = false;\n this.constructor._styles.forEach((s) => {\n const style = document.createElement('style');\n style.textContent = s.cssText;\n this.renderRoot.appendChild(style);\n });\n }\n }",
"function cfnVirtualNodeLoggingPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_LoggingPropertyValidator(properties).assertSuccess();\n return {\n AccessLog: cfnVirtualNodeAccessLogPropertyToCloudFormation(properties.accessLog),\n };\n}",
"function cfnVirtualRouterVirtualRouterSpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualRouter_VirtualRouterSpecPropertyValidator(properties).assertSuccess();\n return {\n Listeners: cdk.listMapper(cfnVirtualRouterVirtualRouterListenerPropertyToCloudFormation)(properties.listeners),\n };\n}",
"function cfnStorageLensBucketsAndRegionsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_BucketsAndRegionsPropertyValidator(properties).assertSuccess();\n return {\n Buckets: cdk.listMapper(cdk.stringToCloudFormation)(properties.buckets),\n Regions: cdk.listMapper(cdk.stringToCloudFormation)(properties.regions),\n };\n}",
"function cfnMultiRegionAccessPointPolicyPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnMultiRegionAccessPointPolicyPropsValidator(properties).assertSuccess();\n return {\n MrapName: cdk.stringToCloudFormation(properties.mrapName),\n Policy: cdk.objectToCloudFormation(properties.policy),\n };\n}",
"function cfnStorageLensAwsOrgPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_AwsOrgPropertyValidator(properties).assertSuccess();\n return {\n Arn: cdk.stringToCloudFormation(properties.arn),\n };\n}",
"function cfnStorageLensS3BucketDestinationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_S3BucketDestinationPropertyValidator(properties).assertSuccess();\n return {\n AccountId: cdk.stringToCloudFormation(properties.accountId),\n Arn: cdk.stringToCloudFormation(properties.arn),\n Encryption: cfnStorageLensEncryptionPropertyToCloudFormation(properties.encryption),\n Format: cdk.stringToCloudFormation(properties.format),\n OutputSchemaVersion: cdk.stringToCloudFormation(properties.outputSchemaVersion),\n Prefix: cdk.stringToCloudFormation(properties.prefix),\n };\n}",
"function cfnVirtualNodeVirtualNodeGrpcConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_VirtualNodeGrpcConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n MaxRequests: cdk.numberToCloudFormation(properties.maxRequests),\n };\n}",
"function cfnMultiRegionAccessPointPolicyPolicyStatusPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnMultiRegionAccessPointPolicy_PolicyStatusPropertyValidator(properties).assertSuccess();\n return {\n IsPublic: cdk.stringToCloudFormation(properties.isPublic),\n };\n}",
"function cfnVirtualGatewayLoggingFormatPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_LoggingFormatPropertyValidator(properties).assertSuccess();\n return {\n Json: cdk.listMapper(cfnVirtualGatewayJsonFormatRefPropertyToCloudFormation)(properties.json),\n Text: cdk.stringToCloudFormation(properties.text),\n };\n}",
"function cfnVirtualNodeListenerTlsFileCertificatePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_ListenerTlsFileCertificatePropertyValidator(properties).assertSuccess();\n return {\n CertificateChain: cdk.stringToCloudFormation(properties.certificateChain),\n PrivateKey: cdk.stringToCloudFormation(properties.privateKey),\n };\n}",
"function cfnMultiRegionAccessPointRegionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnMultiRegionAccessPoint_RegionPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n BucketAccountId: cdk.stringToCloudFormation(properties.bucketAccountId),\n };\n}",
"function CfnBucket_DeleteMarkerReplicationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('status', cdk.validateString)(properties.status));\n return errors.wrap('supplied properties not correct for \"DeleteMarkerReplicationProperty\"');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compares reports based on processId and host and processState and mainClass | function reportCompare(report) {
if (reports.length > 0) {
for (var i = 0; i < reports.length; i++) {
if (reports[i].processId == report.processId && reports[i].host == report.host && reports[i].processStateChange == report.processStateChange && reports[i].mainClass == report.mainClass)
return i;
}
return -1;
}
return -1;
} | [
"aggregateBrowsers(jobs) {\n // Process failed jobs first, then passed, then incomplete/error.\n jobs = _.sortBy(jobs, job => {\n if (job.passed === false) {\n return 0;\n } else if (job.passed === true) {\n return 1;\n }\n return 2;\n });\n // eslint-disable-next-line complexity\n return jobs.reduce((browsers, job) => {\n const browser = job.browser;\n const version = job.browser_short_version;\n const versions = (browsers[browser] = browsers[browser] || {});\n const browserData = (versions[version] = versions[version] || {\n browser,\n version,\n status: 'unknown'\n });\n // Check for weird cancelled jobs.\n if (\n (job.passed === null || job.passed === undefined) &&\n job.status === 'complete' &&\n job.consolidated_status === 'error' &&\n job.commands_not_successful === 0\n ) {\n // Only count if no pass/fail jobs.\n if (browserData.status === 'unknown') {\n browserData.status = job.consolidated_status;\n } else {\n log(`\n Skipping ${job.browser} ${job.browser_short_version} job with\n error: ${job.error}\n `);\n }\n } else if (\n browserData.status === 'unknown' ||\n browserData.status === 'passed' ||\n job.consolidated_status === 'failed'\n ) {\n // Check if the browser disconnected instead of the assertions failing.\n // SauceLabs doesn't have a flag for this, but Travis will send\n // `disconnected` in the custom data field.\n if (job['custom-data'] && job['custom-data'].disconnected) {\n browserData.status = 'disconnected'; // Maybe just 'error'?\n } else {\n browserData.status = job.consolidated_status;\n }\n }\n return browsers;\n }, {});\n }",
"function countSpawnedProcesses(cb) {\n var pgrep = spawn(\"pgrep\", [spawnedProcessPattern, \"-c\"]);\n pgrep.stdout.on(\"data\", cb);\n }",
"function runReport() {\n checkAnswers();\n calculateTestTime();\n calculateCheckedInputs();\n\n }",
"function compareAgentBinaryHash(agentExeInfo, agentHash) {\n // If this is a temporary agent and the server is set to not update temporary agents, don't update the agent.\n if ((obj.agentInfo.capabilities & 0x20) && (args.temporaryagentupdate === false)) return 0;\n // If we are testing the agent update system, always return true\n if ((args.agentupdatetest === true) || (args.agentupdatetest === 1)) return 1;\n if (args.agentupdatetest === 2) return 2;\n // If the hash matches or is null, no update required.\n if ((agentExeInfo.hash == agentHash) || (agentHash == '\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0')) return 0;\n // If this is a macOS x86 or ARM agent type and it matched the universal binary, no update required.\n if ((agentExeInfo.id == 16) || (agentExeInfo.id == 29)) {\n if (domain.meshAgentBinaries && domain.meshAgentBinaries[10005]) {\n if (domain.meshAgentBinaries[10005].hash == agentHash) return 0;\n } else {\n if (parent.parent.meshAgentBinaries[10005].hash == agentHash) return 0;\n }\n }\n\n // No match, update the agent.\n if (args.agentupdatesystem === 2) return 2; // If set, force a meshcore update.\n if (agentExeInfo.id == 3) return 2; // Due to a bug in Windows 7 SP1 environement variable exec, we always update 32bit Windows agent using MeshCore for now. Upcoming agent will have a fix for this.\n // NOTE: Windows agents with no commit dates may have bad native update system, so use meshcore system instead.\n // NOTE: Windows agents with commit date prior to 1612740413000 did not kill all \"meshagent.exe\" processes and update could fail as a result executable being locked, meshcore system will do this.\n if (((obj.AgentCommitDate == null) || (obj.AgentCommitDate < 1612740413000)) && ((agentExeInfo.id == 3) || (agentExeInfo.id == 4))) return 2; // For older Windows agents, use the meshcore update technique.\n return 1; // By default, use the native update technique.\n }",
"function cloneProcessCov(processCov) {\r\n const result = [];\r\n for (const scriptCov of processCov.result) {\r\n result.push(cloneScriptCov(scriptCov));\r\n }\r\n return {\r\n result,\r\n };\r\n}",
"function monitorInputProcess(args)\n{\t\n\t//<METRIC_STATE> \n\tvar metricState = args[0].replace(\"\\\"\", \"\");\n\t\n\tvar tokens = metricState.split(\",\");\n\n\tvar metricsName = Object.keys(metrics);\n\t\n\tfor(var i in tokens)\n\t{\n\t\tmetrics[metricsName[i]].retrieve = (tokens[i] === \"1\")\n\t}\n\t\n\t\n\t//<CIR_IDS>\n\tvar targetsTest = args[1].split(\",\");\n\t\n\t//<PARAMS>\n\tvar testsArgs = args[2].split(\",\");\n\t\n\t//create tests to pass to the monitor\n\tvar tests = [];\n\t\n\tfor(var i in testsArgs)\n\t{\n\t\tvar t = testsArgs[i].split(\"#\");\n\t\t\n\t\tvar test = new Object()\n\t\ttest.url = t[0].split(\";\")[1];\n\t\ttest.maxRequests = t[1];\n\t\ttest.concurrency = t[2];\n\t\ttest.targetId = targetsTest[i]\n\t\t\n\t\ttests.push(test);\n\t}\n\n\t//call monitor\n\tmonitorApacheLoadTest(tests);\n\t\n}",
"wholePaintingCompare(data){\n let dataColorValues = dataParser(data);\n let matchPercent = 0;\n let matchTotals = 0;\n for (var i = 0; i < dataColorValues.length; i++) {\n let compareValue = this.singleColorCompare(dataColorValues[i].hex);\n if (compareValue != 0) {\n matchTotals++;\n }\n if (compareValue < dataColorValues[i].percent) {\n matchPercent += compareValue;\n } else {\n matchPercent += dataColorValues[i].percent\n }\n }\n return {\"percent\": matchPercent, \"total\": matchTotals};\n }",
"getGeneralSystemStatus() {\n const journey = this.props.spec.journey;\n if (journey.steps.SUBPROCESS_APP_LOAD_OR_EXEC\n && journey.steps.SUBPROCESS_APP_LOAD_OR_EXEC.state === 'STEP_ERRORED')\n {\n return 'app-error';\n }\n if (journey.steps.SUBPROCESS_LISTEN\n && journey.steps.SUBPROCESS_LISTEN.state === 'STEP_ERRORED')\n {\n return 'app-error';\n }\n return 'preparation-error';\n }",
"function comparePokemon(p1, p2) {\n\t/*console.log(pokeData[p1]);\n\tconsole.log(p2);\n\tp1 = pokeData[p1].colors;\n\tp2 = pokeData[p2].colors;*/\n\t\n\t//get the total pixels in the pokemon so we can work with percentages\n\tvar p1Total = 0.0;\n\tvar p2Total = 0.0;\n\tfor (var i = 0; i < p1.length; i++) {\n\t\tp1Total += p1[i].count;\n\t}\n\tfor (var i = 0; i < p2.length; i++) {\n\t\tp2Total += p2[i].count;\n\t}\n\t\n\tvar result = 0.0;\n\tfor (var i = 0; i < p1.length; i++) {\n\t\tfor (var j = 0; j < p2.length; j++) {\n\t\t\t//result += getShades(p1[i].color, p2[j].color);\n\t\t\t\n\t\t\t\t//Average between the percentage make-ups of the two matching shades\n\t\t\t\tresult += Math.sqrt(getShades(p1[i].color, p2[j].color)) * (((p1[i].count * 1.0) / p1Total + (p2[j].count * 1.0) / p2Total) / 2.0);\n\t\t}\n\t}\n\treturn result;\n}",
"function statsMaintenance() {\n /* Call memory handling function */\n maintainMemoryStorage()\n \n /* Output stats about connected test server and forecaster operators */\n let testServerList\n let forecasterList\n if (activeTestServerOperators.size === 0) { testServerList = \"none\" } else { testServerList = Array.from(activeTestServerOperators).join(', ') }\n if (activeForecasterOperators.size === 0) { forecasterList = \"none\" } else { forecasterList = Array.from(activeForecasterOperators).join(', ') }\n console.log((new Date()).toISOString(), '[INFO] Active Test Server Operators: ', testServerList)\n console.log((new Date()).toISOString(), '[INFO] Active Forecaster Operators: ', forecasterList)\n activeTestServerOperators.clear()\n activeForecasterOperators.clear()\n\n /* Delete all messages older than 2 minutes from the network node queue */\n let purgeCounter = 0\n for (let i = 0; i < requestsToServer.length; i++) {\n let requestToServer = requestsToServer[i]\n let now = (new Date()).valueOf()\n if (now - requestToServer.timestamp >= MAXAGEMINUTES * 60 * 1000) {\n purgeCounter++\n requestsToServer.splice(i, 1)\n responseFunctions.delete(requestToServer.queryReceived.messageId)\n }\n }\n if (purgeCounter > 0) {\n console.log((new Date()).toISOString(), '[INFO] Deleted', purgeCounter, 'messages older than ' + MAXAGEMINUTES + ' minutes from the queue.')\n }\n }",
"get isExternallyProcessed() {\n const activeApplicationFlow = this.belongsTo(\n 'activeApplicationFlow'\n ).value();\n const firstApplicationStep = activeApplicationFlow\n .belongsTo('firstApplicationStep')\n .value();\n const externalProcessLink = firstApplicationStep.externalProcessLink;\n const isExternallyProcessed = firstApplicationStep\n .belongsTo('subsidyProceduralStep')\n .value().isExternallyProcessed;\n\n if (externalProcessLink && !isExternallyProcessed) {\n console.warn(\n 'found a link to an external processes, but step is not marked for external processing.'\n );\n\n return false;\n } else if (!externalProcessLink && isExternallyProcessed) {\n console.warn(\n 'found no link to an external processes, but step is marked for external processing.'\n );\n\n return true;\n }\n\n return externalProcessLink && isExternallyProcessed;\n }",
"function checkStatus() {\n\t'use strict';\n\tconsole.log('Checking data coverage for our query period');\n\n\tds.historics.status({\n\t\t'start': startTime,\n\t\t'end': endTime\n\t}, function(err, response) {\n\t\tif (err)\n\t\t\tconsole.log(err);\n\t\telse {\n\t\t\tconsole.log('Historic status for query period: ' + JSON.stringify(response));\n\t\t\tcompileStream();\n\t\t}\n\t});\n}",
"function calculateBestHost() {\n console.log(\"***CALCULATE BEST HOST\");\n hostUrlsConnectionCount = [];\n \n var hostUrls = getHostPorts();\n for(var i=0;i<hostUrls.length;i++) {\n hostUrlsConnectionCount[i]=0;\n }\n for(var c=0;c<carList.length;c++){\n console.log(\"[\"+carList[c].carName+\"]: connection number: \"+carList[c].hostConnectionNumber);\n if(carList[c].hostConnectionNumber != -1) {\n console.log(\"counting connection to: \"+carList[c].hostConnectionNumber);\n if(hostUrlsConnectionCount[carList[c].hostConnectionNumber] == null){\n hostUrlsConnectionCount[carList[c].hostConnectionNumber]=1;\n } else { \n hostUrlsConnectionCount[carList[c].hostConnectionNumber]++;\n }\n }\n }\n console.log(\"hostUrlsConnectionCount: \"+hostUrlsConnectionCount.length);\n var lowest=0;\n for(var h=0;h<hostUrlsConnectionCount.length;h++) {\n console.log(\"[\"+h+\"] connection count: \"+hostUrlsConnectionCount[h]);\n if(hostUrlsConnectionCount[lowest] > hostUrlsConnectionCount[h]) {\n lowest=h;\n }\n }\n console.log(\"Best host number: \"+lowest);\n return lowest;\n }",
"function registerCommonMetrics() {\n\tthis.logger.debug(\"Registering common metrics...\");\n\n\t// --- METRICS SELF METRICS ---\n\n\t// this.register({ name: METRIC.MOLECULER_METRICS_COMMON_COLLECT_TOTAL, type: METRIC.TYPE_COUNTER, description: \"Number of metric collections\" });\n\t// this.register({ name: METRIC.MOLECULER_METRICS_COMMON_COLLECT_TIME, type: METRIC.TYPE_GAUGE, description: \"Time of collecting metrics\", unit: METRIC.UNIT_MILLISECONDS });\n\n\t// --- PROCESS METRICS ---\n\n\tconst item = this.register({\n\t\tname: METRIC.PROCESS_ARGUMENTS,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tlabelNames: [\"index\"],\n\t\tdescription: \"Process arguments\"\n\t});\n\tprocess.argv.map((arg, index) => item.set(arg, { index }));\n\n\tthis.register({\n\t\tname: METRIC.PROCESS_PID,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tdescription: \"Process PID\"\n\t}).set(process.pid);\n\tthis.register({\n\t\tname: METRIC.PROCESS_PPID,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tdescription: \"Process parent PID\"\n\t}).set(process.ppid);\n\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_SIZE_TOTAL,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process heap size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_SIZE_USED,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process used heap size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_RSS,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process RSS size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_EXTERNAL,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process external memory size\"\n\t});\n\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_SPACE_SIZE_TOTAL,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tlabelNames: [\"space\"],\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process total heap space size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_SPACE_SIZE_USED,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tlabelNames: [\"space\"],\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process used heap space size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_SPACE_SIZE_AVAILABLE,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tlabelNames: [\"space\"],\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process available heap space size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_SPACE_SIZE_PHYSICAL,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tlabelNames: [\"space\"],\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process physical heap space size\"\n\t});\n\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_STAT_HEAP_SIZE_TOTAL,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process heap stat size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_STAT_EXECUTABLE_SIZE_TOTAL,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process heap stat executable size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_STAT_PHYSICAL_SIZE_TOTAL,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process heap stat physical size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_STAT_AVAILABLE_SIZE_TOTAL,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process heap stat available size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_STAT_USED_HEAP_SIZE,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process heap stat used size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_STAT_HEAP_SIZE_LIMIT,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process heap stat size limit\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_STAT_MALLOCATED_MEMORY,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Process heap stat mallocated size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_STAT_PEAK_MALLOCATED_MEMORY,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"Peak of process heap stat mallocated size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_MEMORY_HEAP_STAT_ZAP_GARBAGE,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tdescription: \"Process heap stat zap garbage\"\n\t});\n\n\tthis.register({\n\t\tname: METRIC.PROCESS_UPTIME,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_SECONDS,\n\t\tdescription: \"Process uptime\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_INTERNAL_ACTIVE_HANDLES,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_HANDLE,\n\t\tdescription: \"Number of active process handlers\"\n\t});\n\tthis.register({\n\t\tname: METRIC.PROCESS_INTERNAL_ACTIVE_REQUESTS,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_REQUEST,\n\t\tdescription: \"Number of active process requests\"\n\t});\n\n\tthis.register({\n\t\tname: METRIC.PROCESS_VERSIONS_NODE,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tdescription: \"Node version\"\n\t}).set(process.versions.node);\n\n\t// --- OS METRICS ---\n\n\tthis.register({\n\t\tname: METRIC.OS_MEMORY_FREE,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"OS free memory size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_MEMORY_USED,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"OS used memory size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_MEMORY_TOTAL,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_BYTE,\n\t\tdescription: \"OS total memory size\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_UPTIME,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_SECONDS,\n\t\tdescription: \"OS uptime\"\n\t});\n\tthis.register({ name: METRIC.OS_TYPE, type: METRIC.TYPE_INFO, description: \"OS type\" }).set(\n\t\tos.type()\n\t);\n\tthis.register({\n\t\tname: METRIC.OS_RELEASE,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tdescription: \"OS release\"\n\t}).set(os.release());\n\tthis.register({\n\t\tname: METRIC.OS_HOSTNAME,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tdescription: \"Hostname\"\n\t}).set(os.hostname());\n\tthis.register({\n\t\tname: METRIC.OS_ARCH,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tdescription: \"OS architecture\"\n\t}).set(os.arch());\n\tthis.register({\n\t\tname: METRIC.OS_PLATFORM,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tdescription: \"OS platform\"\n\t}).set(os.platform());\n\n\tconst userInfo = getUserInfo();\n\tthis.register({ name: METRIC.OS_USER_UID, type: METRIC.TYPE_INFO, description: \"UID\" }).set(\n\t\tuserInfo.uid\n\t);\n\tthis.register({ name: METRIC.OS_USER_GID, type: METRIC.TYPE_INFO, description: \"GID\" }).set(\n\t\tuserInfo.gid\n\t);\n\tthis.register({\n\t\tname: METRIC.OS_USER_USERNAME,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tdescription: \"Username\"\n\t}).set(userInfo.username);\n\tthis.register({\n\t\tname: METRIC.OS_USER_HOMEDIR,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tdescription: \"User's home directory\"\n\t}).set(userInfo.homedir);\n\n\tthis.register({\n\t\tname: METRIC.OS_NETWORK_ADDRESS,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tlabelNames: [\"interface\", \"family\"],\n\t\tdescription: \"Network address\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_NETWORK_MAC,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tlabelNames: [\"interface\", \"family\"],\n\t\tdescription: \"MAC address\"\n\t});\n\n\tthis.register({\n\t\tname: METRIC.OS_DATETIME_UNIX,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tdescription: \"Current datetime in Unix format\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_DATETIME_ISO,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tdescription: \"Current datetime in ISO string\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_DATETIME_UTC,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tdescription: \"Current UTC datetime\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_DATETIME_TZ_OFFSET,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tdescription: \"Timezone offset\"\n\t});\n\n\tthis.register({\n\t\tname: METRIC.OS_CPU_LOAD_1,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tdescription: \"CPU load1\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_CPU_LOAD_5,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tdescription: \"CPU load5\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_CPU_LOAD_15,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tdescription: \"CPU load15\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_CPU_UTILIZATION,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tdescription: \"CPU utilization\"\n\t});\n\n\tthis.register({\n\t\tname: METRIC.OS_CPU_USER,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tdescription: \"CPU user time\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_CPU_SYSTEM,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tdescription: \"CPU system time\"\n\t});\n\n\tthis.register({\n\t\tname: METRIC.OS_CPU_TOTAL,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tunit: METRIC.UNIT_CPU,\n\t\tdescription: \"Number of CPUs\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_CPU_INFO_MODEL,\n\t\ttype: METRIC.TYPE_INFO,\n\t\tlabelNames: [\"index\"],\n\t\tdescription: \"CPU model\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_CPU_INFO_SPEED,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tlabelNames: [\"index\"],\n\t\tunit: METRIC.UNIT_GHZ,\n\t\tdescription: \"CPU speed\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_CPU_INFO_TIMES_USER,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tlabelNames: [\"index\"],\n\t\tdescription: \"CPU user time\"\n\t});\n\tthis.register({\n\t\tname: METRIC.OS_CPU_INFO_TIMES_SYS,\n\t\ttype: METRIC.TYPE_GAUGE,\n\t\tlabelNames: [\"index\"],\n\t\tdescription: \"CPU system time\"\n\t});\n\n\tstartGCWatcher.call(this);\n\tstartEventLoopStats.call(this);\n\n\tthis.logger.debug(`Registered ${this.store.size} common metrics.`);\n}",
"sortByState() {\n let sortedDate = this.state.data\n .sort((a, b) => new Date(a.submission_date) !== new Date(b.submission_date)\n ? new Date(a.submission_date) < new Date(b.submission_date)\n ? 1\n : -1\n : 0);\n\n let sortedState = sortedDate\n .sort((a, b) => a.state !== b.state\n ? a.state < b.state\n ? -1\n : 1\n : 0);\n\n let uniqueStates = [];\n let result = []\n sortedState.forEach((c) => {\n if (!uniqueStates.includes(c.state)) {\n uniqueStates.push(c.state);\n result.push(c)\n }\n }); \n \n let sortedDeath = result\n .sort((a, b) => parseInt(a.tot_death) !== parseInt(b.tot_death)\n ? parseInt(a.tot_death) < parseInt(b.tot_death)\n ? 1\n : -1\n : 0);\n \n let Finalresult = []\n sortedDeath.forEach((c) => {\n Finalresult.push(c)\n });\n\n const totalDeaths = Finalresult.reduce((a, b) => {\n return a + parseInt(b.tot_death)\n }, 0)\n console.log(totalDeaths)\n\n const newResult = Finalresult.map((c) => {\n c.deathPercentage = this.generatePercent(c.tot_death, totalDeaths)\n return c\n })\n\n this.setState({ data: newResult})\n }",
"function getProc(host) {\n return procs.list[getProcId(host)]\n}",
"compare() {\n let result1 = this.state.gameplayOne;\n let result2 = this.state.gameplayTwo;\n let win = [...this.state.win];\n\n // Setting arrays which will be filled by true or false since a winning combination is detected in the player's game.\n let tabTrueFalse1 = [];\n let tabTrueFalse2 = [];\n // winningLine may help to know which winning combination is on the set and then have an action on it. To think.\n let winningLine = [];\n\n if (this.state.gameplayOne.length >= 3) {\n tabTrueFalse1 = win.map(elt =>\n elt.every(element => result1.includes(element))\n );\n }\n if (this.state.gameplayTwo.length >= 3) {\n tabTrueFalse2 = win.map(elt =>\n elt.every(element => result2.includes(element))\n );\n }\n\n //Launching youWon()\n tabTrueFalse1.includes(true) ? this.youWon(1) : null;\n tabTrueFalse2.includes(true) ? this.youWon(2) : null;\n }",
"reports() {\n return {\n inst: this.instCache.report(),\n data: this.dataCache.report()\n };\n }",
"getScheduleProcess(scheduleProcessId) {\n return this.database.scheduleProcesses.find((sp) => sp.id === scheduleProcessId);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turn a regular instance type into a database instance type | function databaseInstanceType(instanceType) {
return 'db.' + instanceType.toString();
} | [
"function typeDescriptorForInstanceId (instanceId) {\n // Locate the instance in the generic collection.\n const instance = payload[referencesName].find (element => element[primaryKey] === instanceId);\n\n if (isPresent (instance)) {\n // We need to relocate this object to a collection of its concrete types,\n // and update this reference.\n\n const concreteModelName = serializer.modelNameFromPayloadKey (instance.type);\n const concreteTypeNames = pluralize (concreteModelName);\n\n (payload[concreteTypeNames] = payload[concreteTypeNames] || []).push (instance);\n\n // Return the type descriptor for this instance.\n return { type: concreteModelName, id: instanceId };\n }\n else {\n // Just return the instance id.\n return instanceId;\n }\n }",
"static registerType(type) { ShareDB.types.register(type); }",
"function normalizePolymorphicValue (value) {\n /**\n * This helper method will convert an instance id to a JSON-API type descriptor. This\n * is necessary to ensure the instance is cached correctly on the client side.\n *\n * @param instanceId Instance id to convert.\n */\n function typeDescriptorForInstanceId (instanceId) {\n // Locate the instance in the generic collection.\n const instance = payload[referencesName].find (element => element[primaryKey] === instanceId);\n\n if (isPresent (instance)) {\n // We need to relocate this object to a collection of its concrete types,\n // and update this reference.\n\n const concreteModelName = serializer.modelNameFromPayloadKey (instance.type);\n const concreteTypeNames = pluralize (concreteModelName);\n\n (payload[concreteTypeNames] = payload[concreteTypeNames] || []).push (instance);\n\n // Return the type descriptor for this instance.\n return { type: concreteModelName, id: instanceId };\n }\n else {\n // Just return the instance id.\n return instanceId;\n }\n }\n\n switch (relationship.kind) {\n case 'hasMany': {\n // Get the collection of instance ids from the value. Then, let's map the\n // instance ids to their corresponding type descriptor.\n\n const instanceIds = value[relationshipKey];\n\n if (isPresent (instanceIds)) {\n value[relationshipKey] = instanceIds.map (typeDescriptorForInstanceId);\n }\n }\n break;\n\n case 'belongsTo': {\n const instanceId = value[relationshipKey];\n\n if (isPresent (instanceId)) {\n value[relationshipKey] = typeDescriptorForInstanceId (value[relationshipKey]) || instanceId;\n }\n }\n break;\n }\n }",
"function resolveTypeFromSchemaForClass(id) {return options.schema.resolveClassByName(id) }",
"_createType (name) {\n\n\t\tif ( name !== undefined) AssertUtils.isString(name);\n\n\t\tconst getNoPgTypeResult = NoPgUtils.get_result(NoPg.Type);\n\n\t\treturn async data => {\n\n\t\t\tdata = data || {};\n\n\t\t\tif ( name !== undefined ) {\n\t\t\t\tdata.$name = '' + name;\n\t\t\t}\n\n\t\t\tconst rows = await this._doInsert(NoPg.Type, data);\n\n\t\t\tconst result = getNoPgTypeResult(rows);\n\n\t\t\tif ( name !== undefined ) {\n\t\t\t\tawait this.setupTriggersForType(name);\n\t\t\t}\n\n\t\t\treturn result;\n\n\t\t};\n\n\t}",
"function cast(type) {\n var members = [],\n count = app.state[type],\n constructor;\n\n for (var c = 0; c < count; c++) {\n constructor = type.caps().single();\n members.push(new app[constructor]({\n id: self.serial++,\n onDeath: self.remove\n }));\n }\n\n // add to the cast\n self.array = self.array.concat(members);\n\n // assign global name shortcuts\n app[type] = members;\n app[type].each = function(callback) {\n self.select(type, callback);\n };\n\n }",
"function DBInstance(props) {\n return __assign({ Type: 'AWS::Neptune::DBInstance' }, props);\n }",
"function mapTypeToSchema(p) {\n\tvar output;\n\tswitch (p) {\n\tcase \"Place\":\n\t\toutput = \"http://schema.org/Place\";\n\tbreak;\n\tcase \"Organization\":\n\t\toutput = \"http://schema.org/Organization\";\n\tbreak;\n\tcase \"Person\":\n\t\toutput = \"http://schema.org/Person\";\n\tbreak;\t\n\tdefault:\n\t\toutput = null;\n\t}\n\treturn output;\n}",
"function DBInstance(props) {\n return __assign({ Type: 'AWS::RDS::DBInstance' }, props);\n }",
"astype(dtype, options) {\n const { inplace } = { inplace: false, ...options };\n\n if (!dtype) {\n throw Error(\"Param Error: Please specify dtype to cast to\");\n }\n\n if (!(DATA_TYPES.includes(dtype))) {\n throw Error(`dtype ${dtype} not supported. dtype must be one of ${DATA_TYPES}`);\n }\n\n const oldValues = [...this.values];\n const newValues = [];\n\n switch (dtype) {\n case \"float32\":\n oldValues.forEach((val) => {\n newValues.push(Number(val));\n });\n break;\n case \"int32\":\n oldValues.forEach((val) => {\n newValues.push(parseInt(val));\n });\n break;\n case \"string\":\n oldValues.forEach((val) => {\n newValues.push(String(val));\n });\n break;\n case \"boolean\":\n oldValues.forEach((val) => {\n newValues.push(Boolean(val));\n });\n break;\n case \"undefined\":\n oldValues.forEach((_) => {\n newValues.push(NaN);\n });\n break;\n default:\n break;\n }\n\n if (inplace) {\n this.$setValues(newValues, false);\n this.$setDtypes([dtype]);\n } else {\n const sf = this.copy();\n sf.$setValues(newValues, false);\n sf.$setDtypes([dtype]);\n return sf;\n }\n\n }",
"static from(type, value) {\n return new Typed(_gaurd, type, value);\n }",
"static create(field, constraint, schema) {\n if (field.type instanceof GraphQLScalarType) {\n field.type = new this(field.type, constraint);\n } else if (field.type instanceof GraphQLNonNull\n && field.type.ofType instanceof GraphQLScalarType) {\n field.type = new GraphQLNonNull(new this(field.type.ofType, constraint));\n } else if (isWrappingType(field.type) && field.type instanceof GraphQLList) {\n field.type = new GraphQLList(new this(field.type, constraint));\n } else {\n throw new Error(`Type ${field.type} cannot be validated. Only scalars are accepted`);\n }\n\n const typeMap = schema.getTypeMap();\n let { type } = field;\n if (isWrappingType(type)) {\n type = type.ofType;\n }\n\n if (isNamedType(type) && !typeMap[type.name]) {\n typeMap[type.name] = type;\n }\n }",
"function defineVariants(typeId, patterns, adt) {\n return mapObject(patterns, (name, constructor) => {\n // ---[ Variant Internals ]-----------------------------------------\n function InternalConstructor() { }\n InternalConstructor.prototype = Object.create(adt);\n\n extend(InternalConstructor.prototype, {\n // This is internal, and we don't want the user to be messing with this.\n [TAG]: name,\n\n /*~ ~inheritsMeta: constructor */\n get constructor() {\n return InternalConstructor;\n },\n\n /*~\n * ~belongsTo: constructor\n * module: null\n * deprecated:\n * version: 2.0.0\n * replacedBy: .hasInstance(value)w\n */\n get [`is${name}`]() {\n warnDeprecation(`.is${name} is deprecated. Use ${name}.hasInstance(value)\ninstead to check if a value belongs to the ADT variant.`);\n return true;\n },\n \n /*~\n * ~belongsTo: constructor\n * module: null\n * type: |\n * ('a is Variant).({ 'b: (Object Any) => 'c }) => 'c\n * where 'b = 'a[`@@folktale:adt:tag]\n */\n matchWith(pattern) {\n assertObject(`${typeId}'s ${name}#matchWith`, pattern);\n if (name in pattern) {\n return pattern[name](this);\n } else if (ANY in pattern) {\n return pattern[ANY]();\n } else {\n throw new Error(getMatchWithErrorMessage(pattern, name));\n } \n }\n });\n\n function makeInstance(...args) {\n let result = new InternalConstructor(); // eslint-disable-line prefer-const\n extend(result, constructor(...args) || {});\n return result;\n }\n\n extend(makeInstance, {\n // We propagate the original metadata for the constructor to our\n // wrapper, which is what the user will interact with most of the time.\n [META]: constructor[META],\n\n /*~ \n * ~belongsTo: makeInstance \n * module: null\n */\n get tag() {\n return name;\n },\n\n /*~ \n * ~belongsTo: makeInstance \n * module: null\n */\n get type() {\n return typeId;\n },\n\n /*~ \n * ~belongsTo: makeInstance \n * module: null\n */\n get constructor() {\n return InternalConstructor;\n },\n\n /*~ ~belongsTo: makeInstance */\n prototype: InternalConstructor.prototype,\n\n /*~\n * ~belongsTo: makeInstance\n * module: null\n * type: |\n * (Variant) => Boolean\n */\n hasInstance(value) {\n return Boolean(value) \n && adt.hasInstance(value) \n && value[TAG] === name;\n },\n });\n\n\n return makeInstance;\n });\n}",
"function getSingularType(type) {\n var unmodifiedType = type;\n\n while (unmodifiedType instanceof require(\"graphql\").GraphQLList) {\n unmodifiedType = unmodifiedType.ofType;\n }\n\n return unmodifiedType;\n}",
"visitSqlj_object_type_attr(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"prepareEntity(entity) {\n if (entity.__prepared) {\n return entity;\n }\n const meta = this.metadata.get(entity.constructor.name);\n const root = Utils_1.Utils.getRootEntity(this.metadata, meta);\n const ret = {};\n if (meta.discriminatorValue) {\n ret[root.discriminatorColumn] = meta.discriminatorValue;\n }\n // copy all props, ignore collections and references, process custom types\n Object.values(meta.properties).forEach(prop => {\n if (this.shouldIgnoreProperty(entity, prop, root)) {\n return;\n }\n if (prop.reference === enums_1.ReferenceType.EMBEDDED) {\n return Object.values(meta.properties).filter(p => { var _a; return ((_a = p.embedded) === null || _a === void 0 ? void 0 : _a[0]) === prop.name; }).forEach(childProp => {\n ret[childProp.name] = entity[prop.name][childProp.embedded[1]];\n });\n }\n if (Utils_1.Utils.isEntity(entity[prop.name], true)) {\n ret[prop.name] = Utils_1.Utils.getPrimaryKeyValues(entity[prop.name], this.metadata.find(prop.type).primaryKeys, true);\n if (prop.customType) {\n return ret[prop.name] = prop.customType.convertToDatabaseValue(ret[prop.name], this.platform);\n }\n return;\n }\n if (prop.customType) {\n return ret[prop.name] = prop.customType.convertToDatabaseValue(entity[prop.name], this.platform);\n }\n if (Array.isArray(entity[prop.name]) || Utils_1.Utils.isObject(entity[prop.name])) {\n return ret[prop.name] = Utils_1.Utils.copy(entity[prop.name]);\n }\n ret[prop.name] = entity[prop.name];\n });\n Object.defineProperty(ret, '__prepared', { value: true });\n return ret;\n }",
"static cast(t) {\n return new BaseProof(t.toJSON())\n }",
"normalizeType(type) {\n if (type === '@apostrophecms/page') {\n // Backwards compatible\n return '@apostrophecms/any-page-type';\n }\n\n return type;\n }",
"function delete_object_type (type) {\r\n type = type.toLowerCase();\r\n if (TypeData['types'][type]) {\r\n TypeData['types'][type] = null;\r\n TypeData['type_count']--;\r\n DataStore[type] = null;\r\n }\r\n}",
"visitSqlj_object_type(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
query api for todo by name | async function getTodoByName() {
const answer = await inquirer.prompt([
{name: 'title', message: 'Enter a title: '},
]);
const searchTerm = answer.title;
// fetch list and search by title
try {
const { data: { listTodos : { items } } } = await API.graphql(graphqlOperation(listTodos, {filter: {name: {eq: searchTerm}}}));
const result = items[0];
if (!result) {
console.warn(`No Todo named ${searchTerm}`);
}
return result;
} catch (err) {
console.log("filter operation failed", err);
}
return null;
} | [
"async index() {\n const { ctx, service } = this;\n\n // query value is string, should convert types.\n let { completed } = ctx.query;\n if (ctx.query.completed !== undefined) completed = completed === 'true';\n\n ctx.status = 200;\n ctx.body = await service.todo.list({ completed });\n }",
"async function getTodo(name) {\n// Get the service we registered above\n const service = app.service('todos');\n// Call the 'get' method with a name\n const todo = await service.get(name);ƒ\n// Log the todo that we got back\n console.log(todo);\n}",
"async getSingleTodo({ params }, res) {\n\t\tconst foundTodo = await Todo.findOne({ _id: params.id });\n\n\t\tif (!foundTodo) {\n\t\t\treturn res.status(404).json({ message: 'Item not found.' });\n\t\t}\n\t\treturn res.json(foundTodo);\n\t}",
"async getTodos(userId) {\n return this.internalState.todos[userId];\n }",
"taskList(req, res) {\n console.log('req.query>>>>>>>>>>>>>>>>>>>>.',req.query);\n con.query(\"SELECT * FROM `object_query_31` where ActiveStatus=? AND RelatedToId=? AND RelatedToObject=?\",[1,req.query.Id,req.query.Object],function(err, result) {\n if (err)\n throw err;\n else {\n console.log('resultt task>>>>>>>>>>>>..',result);\n return res.status(200).json({\n tasks: result\n })\n }\n })\n }",
"async getListTodos (context, listId) {\n try {\n const response = await fetch(`https://ap-todo-list.herokuapp.com/todosForList?listId=${listId}`)\n const data = await response.json()\n context.commit('setTodos', data)\n } catch (error) {\n // Set the error and clear the todos.\n console.error(error)\n context.commit('setTodos', [])\n }\n }",
"function myTodo(todo) {\n console.log(todo.title + ' : ' + todo.text);\n}",
"function getList(party_id) {\n return db(\"todos\")\n .select(\"id\", \"item\", \"completed\")\n .where({ party_id });\n}",
"function deleteToDos(id) {\n\n var defer = $q.defer();\n\n $http({\n method: 'DELETE',\n url: 'http://localhost:50341/api/ToDoListEntries/' + id\n }).then(function(response) {\n if (typeof response.data === 'object') {\n defer.resolve(response);\n toastr.success('Deleted ToDo List Item!');\n } else {\n defer.reject(response);\n //error if found but empty\n toastr.warning('Failure! </br>' + response.config.url);\n }\n },\n // failure\n function(error) {\n //error if the file isn't found\n defer.reject(error);\n $log.error(error);\n toastr.error('error: ' + error.data + '<br/>status: ' + error.statusText);\n });\n\n return defer.promise;\n }",
"async function importantTodoItemsTitle() {\n const todoItems = await todoItem.findAll({\n where: { important: true },\n include: { model: todoList, attributes: [\"title\"] },\n });\n console.log(todoItems);\n return todoItems;\n}",
"function ensureTodo(req, res, next) {\n assert.arrayOfString(req.todos, 'req.todos');\n\n if (req.params.name && req.todos.indexOf(req.params.name) === -1) {\n req.log.warn('%s not found', req.params.name);\n next(new TodoNotFoundError(req.params.name));\n } else {\n next();\n }\n}",
"function task_complete_todoist(task_name, project_id, todoist_api_token) {\n todoist_api_token = todoist_api_token || 'a14f98a6b546b044dbb84bcd8eee47fbe3788671'\n return todoist_add_tasks_ajax(todoist_api_token, {\n \"content\": task_name,\n \"project_id\": project_id\n }, 'item_complete')\n}",
"deleteTodo() {\n\t let todo = this.get('todo');\n\t this.sendAction('deleteTodo', todo);\n\t }",
"getPublicTasks() {\n if (Template.instance().uiState.get(\"taskSort\") == NAME_TXT)\n return Tasks.find({username:this.username}, {sort:{createdAt:-1}}).fetch();\n return Tasks.find({username:this.username}, {sort:{name:1}}).fetch();\n }",
"async getTrackByName(ctx) {\n await Model.track\n .findOne({ name: ctx.params.name })\n .then(result => {\n if(result) { ctx.body = result; }\n else { throw \"Track not found\"; }\n })\n .catch(error => {\n throw new Error(error);\n });\n }",
"function queryRACByName(req, res) {\n RAC.findOne({\n name: req.query.name\n })\n .then(doc => {\n res.json(doc);\n })\n .catch(err => {\n res.status(500).json(err);\n });\n}",
"function task_update_todoist(task_name, project_id, todoist_api_token) {\n todoist_api_token = todoist_api_token || 'a14f98a6b546b044dbb84bcd8eee47fbe3788671'\n return todoist_add_tasks_ajax(todoist_api_token, {\n \"content\": task_name,\n \"project_id\": project_id\n }, 'item_update')\n}",
"getAllByDate(date) {\n let sql = `\n SELECT *\n FROM tasks\n WHERE date = ?\n `;\n return this.dao.all(sql, [date]);\n }",
"function refreshTodoList(){\n //remove current todo items\n todoTable = document.getElementById('todo-table');\n while (todoTable.firstChild) {\n todoTable.removeChild(todoTable.firstChild);\n }\n\n user_id = document.getElementById('user-data').getAttribute(\"data-id\");\n todoLiStSpinner = document.getElementById('todo-table-spinner');\n\n //show spinner\n todoLiStSpinner.innerHTML = `<i class=\"fa fa-refresh fa-spin\" style=\"font-size:24px\"/></i>`;\n\n //Update button activation\n activateTodoGroupButtons();\n\n todoApiCall({'callName':'index' ,'request':{user_id, 'done':0}, 'method':'GET' });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name : removeServiceProviderFromLabel Return type : text Input Parameter(s) : label Purpose : To get the label for the security elements. History Header : Version Date Developer Name Added By : 1.0 24th July, 2014 UmaMaheswara Rao | function removeServiceProviderFromLabel(label) {
var position = label.lastIndexOf(" ");
var text = label.substring(position);
return text;
} | [
"function myFunctionLabel(){\nconst labelForm = document.querySelector('.screen-reader-text');\nconst elementLabel = document.getElementsByTagName('label')[0];\nelementLabel.setAttribute('id', 'label-id');\n\telementLabel.remove();\n}",
"function hideLabel() { \n marker.set(\"labelVisible\", false); \n }",
"function CLC_Content_FindLabelText(target){\r\n var logicalLineage = CLC_GetLogicalLineage(target);\r\n var labelText = \"\";\r\n for (var i=0; i < logicalLineage.length; i++){\r\n if (logicalLineage[i].tagName && (logicalLineage[i].tagName.toLowerCase() == \"label\")){\r\n labelText = labelText + \" \" + logicalLineage[i].textContent;\r\n }\r\n }\r\n return labelText;\r\n }",
"function removeInsulaLabels(){\n\t\tvar i=0;\n\t\tfor(i;i<insulaMarkersList.length;i++){\n\t\t\tpompeiiMap.removeLayer(insulaMarkersList[i]);\n\t\t}\n\t}",
"function getLabelForSecureElements(elementId, billerCredsElement) {\n\tvar label = \"\";\n\tif ((elementId == 52 || elementId == 53) && addBill) {\n\t\tlabel = bp_biller_corp_creds_obj.name + removeServiceProviderFromLabel(billerCredsElement.label);\n\t} else if ((elementId == 52 || elementId == 53) && !addBill) {\n\t\tfor (var index = 0 ; index < bp_account_lite_obj.billerCorpAccounts.length ; index++) {\n\t\t\tif (bp_account_lite_obj.billerCorpAccounts[index].id == bp_get_corp_account_obj.id) {\n\t\t\t\tlabel = bp_account_lite_obj.billerCorpAccounts[index].nickname + removeServiceProviderFromLabel(billerCredsElement.label);\n\t\t\t} \n\t\t}\n\t} else {\n\t\tlabel = billerCredsElement.label;\n\t}\n\treturn label;\n}",
"_getFilterLabels(label, field)\r\n {\r\n var templateChoice = _.template($(this.options.templateFilterChoice).html());\r\n var templateInput = _.template($(this.options.templateFilterMultipleEnum).html());\r\n var labelCollection = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__GLOBAL_RESOURCELABEL_COLLECTION);\r\n var project = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__PROJECT_GET_ACTIVE);\r\n var project_resources = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__RESOURCES_CURRENT, {data: {project: project.id}});\r\n var labels = new Set();\r\n project_resources.each(function (resource) {\r\n resource.attributes.labels.forEach(function ({ url }) {\r\n labels.add(url);\r\n });\r\n });\r\n var filtered_collection = labelCollection.filter(function (resource) { return labels.has(resource.attributes.url); });\r\n var labelModels = filtered_collection.map((label) => {\r\n return {\r\n label: label.get('name'),\r\n value: label.get('uuid')\r\n };\r\n });\r\n var htmlChoice = templateChoice({label: label, field: field});\r\n var htmlInput = templateInput({label: label, field: field, values: labelModels});\r\n return {collectionItem: htmlChoice, input: htmlInput};\r\n }",
"function setDescription(label) {\n let desBox = descriptionBox[0];\n desBox.style.width = 'auto';\n $(desBox).empty();\n\n let severity = label.getAuditProperty('severity');\n let temporary = label.getAuditProperty('temporary');\n let description = label.getAuditProperty('description');\n let tags = label.getAuditProperty('tags');\n\n desBox.style['background-color'] = util.misc.getLabelColors(label.getAuditProperty('labelType'));\n\n if (severity && severity != 0) {\n let span = document.createElement('span');\n let htmlString = document.createTextNode(i18next.t('severity') + severity + ' ');\n desBox.appendChild(htmlString);\n let img = document.createElement('img');\n img.setAttribute('src', smileyScale[severity]);\n if (isMobile()) {\n img.setAttribute('width', '20px');\n img.setAttribute('height', '20px');\n } else {\n img.setAttribute('width', '12px');\n img.setAttribute('height', '12px');\n }\n\n img.style.verticalAlign = 'middle';\n span.appendChild(img);\n desBox.appendChild(span);\n desBox.appendChild(document.createElement(\"br\"));\n }\n\n if (temporary) {\n let htmlString = document.createTextNode(i18next.t('temporary'));\n desBox.appendChild(htmlString);\n desBox.appendChild(document.createElement(\"br\"));\n }\n\n if (tags && tags.length > 0) {\n // Translate to correct language and separate tags with a comma.\n let tag = tags.map(t => i18next.t('center-ui.tag.' + t)).join(', ');\n let htmlString = document.createTextNode('tags: ' + tag);\n desBox.appendChild(htmlString);\n desBox.appendChild(document.createElement(\"br\"));\n }\n\n if (description && description.trim().length > 0) {\n let htmlString = document.createTextNode(description);\n desBox.appendChild(htmlString);\n }\n\n if (!severity && !temporary && (!description || description.trim().length == 0) &&\n (!tags || tags.length == 0)) {\n let htmlString = document.createTextNode(i18next.t('center-ui.no-info'));\n desBox.appendChild(htmlString);\n }\n\n // Set the width of the des box.\n let bound = desBox.getBoundingClientRect();\n let width = ((bound.right - bound.left) * (isMobile() ? window.devicePixelRatio : 1)) + 'px';\n desBox.style.width = width;\n\n if (isMobile()) {\n desBox.style.fontSize = '30px';\n }\n }",
"function clickClearWarnings(label) {\n $(label + ' #input').validate().resetForm()\n $(\"div.ui-tooltip\").remove();\n}",
"getLabel() { return this.labelP.innerText; }",
"deleteV3ProjectsIdLabels(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let name = \"name_example\";*/ // String | The name of the label to be deleted\napiInstance.deleteV3ProjectsIdLabels(incomingOptions.id, incomingOptions.name, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"_label(label) {\n return `${label}${label && this.required ? '*' : ''}`;\n }",
"function removePVTFromUrl(toremove) {\n let vars = getUrlVars();\n // let newStr = pt + \",\" + mp + \",\" + pvs;\n if (\"ptpv\" in vars) {\n let ptpvs = vars[\"ptpv\"].split(\"__\");\n\n if (ptpvs.includes(toremove)) {\n ptpvs.splice(ptpvs.indexOf(toremove), 1);\n vars[\"ptpv\"] = ptpvs.join(\"__\");\n let evt = window.evtmap[toremove];\n if (evt) {\n if (evt.target.classList.contains(\"checkbox\")) {\n evt.target.classList.toggle(\"checked\");\n } else if (evt.target.classList.contains(\"value-link\")) {\n evt.target.querySelector(\".checkbox\").classList.toggle(\"checked\");\n }\n }\n }\n }\n setSearchParam(vars);\n}",
"function TLabel(){}",
"function removeStat()\r\n{\r\n var selspan = document.getElementById('lang_span');\r\n if (selspan.childNodes[2])\r\n {\r\n selspan.removeChild(selspan.childNodes[2]);\r\n }\r\n}",
"recycleByLabel(label) {\n return spPost(Versions(this, `recycleByLabel(versionlabel='${encodePath(label)}')`));\n }",
"function getLabel(item) {\n\tvar span = angular.element(item).find('span').eq(0);\n\treturn angular.element(span).text();\n }",
"function TdeCtrl_OnToolTipCloseBt() \n{\n LabelOpObj.RemoveToolTip();\n}",
"function createFormControlLabels() {\n let sectionLabels = [\n 'arts', 'automobiles', 'books', 'business', 'fashion', 'food', 'health', 'home', 'insider', 'magazine', \n 'movies', 'ny region', 'obituaries', 'opinion', 'politics', 'real estate', 'science', 'sports', 'sunday review', \n 'technology', 'theater', 't-magazine', 'travel', 'upshot', 'us', 'world'\n ]\n\n const sectionValues = sectionLabels.map(section => {\n const sectionArr = section.split(' ');\n if (sectionArr.length > 1) {\n section = sectionArr.join('');\n console.log('joining section:', section);\n }\n return section;\n })\n\n /** capitalize each word in selction lables */\n sectionLabels = sectionLabels.map( section => {\n // debugger;\n section = section.split(' ');\n let updatedSection = section.map( item => {\n let firstLetter = item.charAt(0).toUpperCase();\n let remainder = item.slice(1);\n item = firstLetter + remainder;\n return item;\n })\n updatedSection = updatedSection.join(' ');\n return updatedSection;\n })\n\n /** Creating the form labels */\n const formLabels = sectionValues.map( (section, index) => (\n <FormControlLabel\n key={section}\n value={section}\n control={<Radio />}\n label={sectionLabels[index]}\n />\n ))\n\n return formLabels;\n }",
"label(text, size = -1) {\n //TODO\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION NAME : validateReservationOption AUTHOR : Anna Marie Paulo DATE : February 28, 2014 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : validation in srat and end reservation PARAMETERS : imgarr, flag, opt, opt2, opt3 | function validateReservationOption(imgarr,flag,opt,opt2,opt3) {
var hostname = new Array();
var hostname2 = new Array();
for ( var t=0 ; t < imgarr.length ; t++) {
switch (flag) {
case 0:
if ($('#tb'+opt+opt3+'URL'+imgarr[t]).val() == "") {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname.push(host);
} else {
var url = $('#tb'+opt+opt3+'URL'+imgarr[t]).val();
var url2 = url.split(":");
if ( url2.length != 2 ) {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname.push(host);
} else {
url2 = url.split(":")[0];
url2 = url2.toLowerCase();
if (/^disk[0-2]|disk$/.test(url2) == false && /^slot[0-1]$/.test(url2) == false && /^NVRAM$/.test(url2) == false && /^bootflash$/.test(url2) == false && /^FTP$/i.test(url2) == false && /^TFTP$/i.test(url2) == false && /^flash[0-1]|flash$/.test(url2) == false) {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname.push(host);
//} else if ( /^FTP$/i.test(url2) == true || /^TFTP$/i.test(url2) == true ) {
var url3 = url.split(":\/\/")[1].split("\/");
if (url3.length < 3) {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname.push(host);
} else {
var ip = url3[0];
var isvalidIP = checkIP(ip);
if (isvalidIP == 1) {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname.push(host);
} else {
var ctr = 1;
var str = "";
for (var k = 1; k < url3.length - 1; k++) {
if (ctr == url3.length - 2) {
str += url3[k];
} else {
str += url3[k]+"\/";
}
ctr++;
}
var isvalidpath = validatePath(str);
if ( isvalidpath == 1 ) {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname.push(host);
} else {
var fname = url3[url3.length - 1];
var isvalidfile = validateFileName(fname,str);
if (isvalidfile == 1) {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname.push(host);
}
}
}
}
} else if (/^disk[0-2]|disk$/.test(url2) == true || /^slot[0-1]$/.test(url2) == true || /^NVRAM$/.test(url2) == true || /^bootflash$/.test(url2) == true || /^flash[0-1]|flash$/.test(url2) == true) {
}
}
}
if ($('#tb'+opt+opt3+'Destination'+imgarr[t]).val() == "") {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname2.push(host);
} else {
if (opt2.toLowerCase() == 'loadimage') {
var url = $('#tb'+opt+opt3+'Destination'+imgarr[t]).val();
var filename = $('#tb'+opt+opt3+'URL'+imgarr[t]).val();
if (filename.indexOf(url) !== -1) {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname2.push(host);
}
}
}
break;
case 1:
var proto2 = $('#tb'+opt+opt3+'DetailProtocol'+imgarr[t]).val();
var ip = $('#tb'+opt+opt3+'DetailIp'+imgarr[t]).val();
var path = $('#tb'+opt+opt3+'DetailPath'+imgarr[t]).val();
var fname = $('#tb'+opt+opt3+'DetailFilename'+imgarr[t]).val();
var dest = $('#tb'+opt+opt3+'DetailDestination'+imgarr[t]).val();
if (proto2 == "" && ip == "" && path == "" && fname == "" && dest == "") {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname.push(host);
} else { //PROTOCOL
var isvalidproto = validateProtocol(proto2,path);
if (isvalidproto == 1) {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname.push(host);
} else {
if (/^disk[0-2]|disk$/.test(path) == true || /^slot[0-1]$/.test(path) == true || /^NVRAM$/.test(path) == true || /^bootflash$/.test(path) == true || /^flash[0-1]|flash$/.test(path) == true) {
var isvalidip = 0;
} else {
var isvalidip = checkIP(ip);
}
if (isvalidip == 1) {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname.push(host);
} else {
var isvalidpath = validatePath(path);
if (isvalidpath == 1) {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname.push(host);
} else {
var isvalidfile = validateFileName(fname,path);
if (isvalidfile == 1) {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname.push(host);
}
}
}
}
}
if ($('#tb'+opt+opt3+'Destination'+imgarr[t]).val() == "") {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname2.push(host);
} else {
if (opt2.toLowerCase() == 'loadimage') {
var proto2 = $('#tb'+opt+opt3+'DetailProtocol'+imgarr[t]).val();
var path = $('#tb'+opt+opt3+'DetailPath'+imgarr[t]).val();
var url = $('#tb'+opt+opt3+'Destination'+imgarr[t]).val();
if (proto2.toLowerCase() == url) {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname2.push(host);
} else if (path.toLowerCase() == url) {
var host = $('#tr'+opt2+opt3+imgarr[t]).find('td').eq(1).text();
hostname2.push(host);
}
}
}
break;
}
}
var msg = "";
if (hostname.length > 0) {
msg = "Invalid "+opt3+" URL for the following device(s):<br/><br/>";
for (var u= 0; u < hostname.length; u++) {
msg += hostname[u]+"<br/>";
}
msg += "<br/>(sample: TFTP://"+CURRENT_IP+"/Directory/FileName or disk0:FileName)<br/>";
if (hostname2.length > 0) {
msg += "<br/>Invalid "+opt3+" Destination for the following device(s):<br/><br/>";
for (var u= 0; u < hostname2.length; u++) {
msg += hostname2[u]+"<br/>";
}
}
} else if (hostname2.length > 0) {
msg = "Invalid "+opt3+" Destination for the following device(s):<br/><br/>";
for (var u= 0; u < hostname2.length; u++) {
msg += hostname2[u]+"<br/>";
}
}
if (msg != "") {
/* $('#manualAlert').dialog({
autoOpen: false,
resizable: false,
modal: true,
height: 250,
width: 350,
closeOnEscape: false,
open: function(event, ui) { $(".ui-dialog-titlebar-close", ui.dialog).hide(); },
buttons: {
"OK": function() {
$(this).dialog('destroy');
}
}
});
$('#manualAlert').empty().append(msg);
$('#manualAlert').dialog("open");
$('.ui-dialog :button').blur();*/
return msg;
}
return;
} | [
"function saveEndReservationAlertConditions(MainEndArr,type,mainMenu,opt){\n\tvar isChecked = false;\n\tvar resInfoFlag = false;\n\tvar adminFlag = (userInformation[0].userLevel=='Administrator');\n\tif(opt==\"Save\"){\n\t\tvar resInfoConfigObj = EndOfReservationInfoForConfig;\n\t\tvar resInfoImageObj = EndOfReservationInfoForImage;\n\t\tvar resOpt = \"comOpEndRes\";\n\t\tvar optSaveFlag = true;\n\t}else{\n\t\tvar resInfoConfigObj = StartOfReservationInfoForConfig;\n\t\tvar resInfoImageObj = StartOfReservationInfoForImage;\n\t\tvar resOpt = \"comOpStartRes\";\n\t\tvar optSaveFlag = false;\n\t}\n\tif(type==\"both\"){\n\t\tvar confFlag = ($('#SaveConfigSetValues').is(':checked'));\n\t\tvar imgFlag = ($('#SaveImageSetValues').is(':checked'));\n\t\tvar resInfoConf = $.isEmptyObject(resInfoConfigObj);\n\t\tvar resInfoImg = $.isEmptyObject(resInfoImageObj);\n\t\tresInfoFlag = (resInfoConf && resInfoImg);\n\t\tisChecked = (confFlag && imgFlag);\n\t}else{\n\t\tisChecked = ($('#'+opt+type+'SetValues').is(':checked'));\n\t\tvar resInfo = \"resInfo\"+type+\"Obj\";\n\t\tresInfoFlag = ($.isEmptyObject(eval(resInfo)));\n\t}\n\tswitch(true){\n\t\tcase (adminFlag && isChecked): \n\t\t\tsaveEndReservationAlerts(mainMenu,1,type,opt);\n\t\t\tbreak;\n\t\tcase (adminFlag && !isChecked && resInfoFlag): \n\t\tcase (!adminFlag && resInfoFlag): \n\t\t\t$(\"#\"+resOpt).prop('checked',true);\n\t\t\t$('#startEndReserve').dialog('destroy');\n\t\t\tif($('#customPage')){toConfig();}\n\t\t\tbreak;\n\t\tcase (adminFlag && !isChecked && !resInfoFlag && optSaveFlag && type!=\"both\"): \n\t\t\tsaveEndReservationAlerts(mainMenu,2,type,opt);\n\t\t\tfor(var a=0; a<MainEndArr.length; a++){\n\t\t\t\tif(type==\"Image\"){saveEndReservationSetAttrImage(MainEndArr[a]);}\n\t\t\t\tif(type==\"Config\"){saveEndReservationSetAttrConfig(MainEndArr[a]);}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase (adminFlag && !isChecked && !resInfoFlag && optSaveFlag && type==\"both\"):\n\t\t\tsaveEndReservationAlerts(mainMenu,2,type,opt);\n\t\t\tfor(var a=0; a<MainEndArr[0].length; a++){\n\t\t\t\tsaveEndReservationSetAttrConfig(MainEndArr[0][a]);\n\t\t\t}\n\t\t\tfor(var b=0; b<MainEndArr[1].length; b++){\n\t\t\t\tsaveEndReservationSetAttrImage(MainEndArr[1][b]);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase (adminFlag && !isChecked && !resInfoFlag && !optSaveFlag && type!=\"both\"): \n\t\t\tsaveEndReservationAlerts(mainMenu,2,type,opt);\n\t\t\tfor(var a=0; a<MainEndArr.length; a++){\n\t\t\t\tif(type==\"Image\"){loadStartReservationSetAttrImage(MainEndArr[a]);}\n\t\t\t\tif(type==\"Config\"){loadStartReservationSetAttrConfig(MainEndArr[a]);}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase (adminFlag && !isChecked && !resInfoFlag && !optSaveFlag && type==\"both\"):\n\t\t\tsaveEndReservationAlerts(mainMenu,2,type,opt);\n\t\t\tfor(var a=0; a<MainEndArr[0].length; a++){\n\t\t\t\tloadStartReservationSetAttrConfig(MainEndArr[0][a]);\n\t\t\t}\n\t\t\tfor(var b=0; b<MainEndArr[1].length; b++){\n\t\t\t\tloadStartReservationSetAttrImage(MainEndArr[1][b]);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase (!adminFlag && !resInfoFlag): \n\t\t\tsaveEndReservationAlerts(mainMenu,2,type,opt);\n\t\t\tbreak;\n\t}\n\treturn;\n}",
"static vsamValidateOptions(options) {\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options, ZosFiles_messages_1.ZosFilesMessages.missingFilesCreateOptions.message);\n /* If our caller does not supply these options, we supply default values for them,\n * so they should exist at this point.\n */\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.dsorg, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"dsorg\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.alcunit, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"alcunit\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.primary, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"primary\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.secondary, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"secondary\");\n // validate specific options\n for (const option in options) {\n if (options.hasOwnProperty(option)) {\n switch (option) {\n case \"dsorg\":\n if (!ZosFiles_constants_1.ZosFilesConstants.VSAM_DSORG_CHOICES.includes(options.dsorg.toUpperCase())) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.invalidDsorgOption.message + options.dsorg\n });\n }\n break;\n case \"alcunit\":\n if (!ZosFiles_constants_1.ZosFilesConstants.VSAM_ALCUNIT_CHOICES.includes(options.alcunit.toUpperCase())) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.invalidAlcunitOption.message + options.alcunit\n });\n }\n break;\n case \"primary\":\n case \"secondary\":\n // Validate maximum allocation quantity\n if (options[option] > ZosFiles_constants_1.ZosFilesConstants.MAX_ALLOC_QUANTITY) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.maximumAllocationQuantityExceeded.message + \" \" +\n ZosFiles_messages_1.ZosFilesMessages.commonFor.message + \" '\" + option + \"' \" + ZosFiles_messages_1.ZosFilesMessages.commonWithValue.message +\n \" = \" + options[option] + \".\"\n });\n }\n break;\n case \"retainFor\":\n if (options[option] < ZosFiles_constants_1.ZosFilesConstants.MIN_RETAIN_DAYS ||\n options[option] > ZosFiles_constants_1.ZosFilesConstants.MAX_RETAIN_DAYS) {\n throw new imperative_1.ImperativeError({\n msg: imperative_1.TextUtils.formatMessage(ZosFiles_messages_1.ZosFilesMessages.valueOutOfBounds.message, {\n optionName: option,\n value: options[option],\n minValue: ZosFiles_constants_1.ZosFilesConstants.MIN_RETAIN_DAYS,\n maxValue: ZosFiles_constants_1.ZosFilesConstants.MAX_RETAIN_DAYS\n })\n });\n }\n break;\n case \"retainTo\":\n case \"volumes\":\n case \"storclass\":\n case \"mgntclass\":\n case \"dataclass\":\n case \"responseTimeout\":\n // no validation at this time\n break;\n default:\n throw new imperative_1.ImperativeError({ msg: ZosFiles_messages_1.ZosFilesMessages.invalidFilesCreateOption.message + option });\n } // end switch\n }\n } // end for\n }",
"function saveEndReservation(mainMenu){\n\tvar imgFlag = ($(\"#ReserveOptionSaveImageDiv\").is(\":visible\"));\n\tvar conFlag = ($(\"#ReserveOptionSaveConfigDiv\").is(\":visible\"));\n\tvar MainEndArr = new Array();\n\tswitch(true){\n\t\tcase (conFlag && !imgFlag):\n\t\t\tvar MainEndConArr = saveEndReservationInfo(\"Config\",\"Save\");\n\t\t\tif(MainEndConArr==\"\"){ return; }\n\t\t\tsaveEndReservationAlertConditions(MainEndConArr,\"Config\",mainMenu,\"Save\");\n\t\t\tbreak;\n\t\tcase (imgFlag && !conFlag):\n\t\t\tvar MainEndImgArr = saveEndReservationInfo(\"Image\",\"Save\");\n\t\t\tif(MainEndImgArr==\"\"){ return; }\n\t\t\tsaveEndReservationAlertConditions(MainEndImgArr,\"Image\",mainMenu,\"Save\");\n\t\t\tbreak;\n\t\tcase (imgFlag && conFlag):\n\t\t\tvar MainEndConArr = saveEndReservationInfo(\"Config\",\"Save\");\n\t\t\tvar MainEndImgArr = saveEndReservationInfo(\"Image\",\"Save\");\t\n\t\t\tif(MainEndConArr!=\"\"){MainEndArr.push(MainEndConArr);}\n\t\t\tif(MainEndImgArr!=\"\"){MainEndArr.push(MainEndImgArr);}\n\t\t\tif(MainEndArr==[]){ return; }\n\t\t\tif(MainEndConArr==\"\" && MainEndImgArr!=\"\"){\n\t\t\t\tsaveEndReservationAlertConditions(MainEndImgArr,\"Image\",mainMenu,\"Save\");\n\t\t\t}else if(MainEndImgArr==\"\" && MainEndConArr!=\"\"){\n\t\t\t\tsaveEndReservationAlertConditions(MainEndConArr,\"Config\",mainMenu,\"Save\");\n\t\t\t}else{\n\t\t\t\tsaveEndReservationAlertConditions(MainEndArr,\"both\",mainMenu,\"Save\");\n\t\t\t}\n\t\t\tbreak;\n\t}\n}",
"function ValidateCognitionTime() {\n var session = $('#ddlCognitionTestSlotID').val();\n var flag = true;\n var timeSelected = $('#txtCognitionTestSlotTime').val();\n var timeSplit = timeSelected.split(\":\");\n var hourTime = parseInt(timeSplit[0]);\n if (session == 1) {\n if (timeSelected.indexOf(\"PM\") !== -1) {\n $('#cognitionTimeValidation').html(\"Select Morning Cognition Slot Time.\");\n $('#cognitionTimeValidation').show();\n flag = false;\n }\n }\n else\n if (session == 2) {\n if (timeSelected.indexOf(\"AM\") !== -1) {\n $('#cognitionTimeValidation').html(\"Select Afternoon Cognition Slot Time.\");\n $('#cognitionTimeValidation').show();\n flag = false;\n }\n else if (hourTime < 12 && hourTime >= 5) {\n $('#cognitionTimeValidation').html(\"The available Afternoon Cognition Slot is between 12:00 PM and 04:59 PM. Please select a time during this period.\");\n $('#cognitionTimeValidation').show();\n flag = false;\n }\n }\n else if (session == 3) {\n if (timeSelected.indexOf(\"AM\") !== -1) {\n $('#cognitionTimeValidation').html(\"Select Evening Cognition Slot Time.\");\n $('#cognitionTimeValidation').show();\n flag = false;\n }\n else if (hourTime < 5 || hourTime == 12) {\n $('#cognitionTimeValidation').html(\"The available Evening Cognition Slot is between 05:00 PM and 11:59 PM. Please select a time during this period. \");\n $('#cognitionTimeValidation').show();\n flag = false;\n }\n }\n return flag;\n}",
"function findRejectionOptions (option) {\n if (option.code === 'SRJ' || option.code === 'LRD') {\n return true;\n } else {\n return false;\n }\n }",
"function validateEquipmentno(oSrc, args) {\n var cols = ifgPreAdvice.Rows(ifgPreAdvice.CurrentRowIndex()).GetClientColumns();\n var _rowI = ifgPreAdvice.rowIndex;\n var sEquipmentno = args.Value\n var checkDigit;\n var sContNo;\n var strContinue = \"\";\n var msg = checkContainerNo(sEquipmentno);\n\n if (msg == \"\") {\n if (el(\"hdnchkdgtvalue\").value == \"True\") {\n if (sEquipmentno.length == 10) {\n sEquipmentno = sEquipmentno + getCheckSum(sEquipmentno.substr(0, 10));\n ifgPreAdvice.Rows(_rowI).SetColumnValuesByIndex(1, sEquipmentno);\n strContinue = \"N\";\n } else {\n checkDigit = getCheckSum(sEquipmentno.substr(0, 10));\n\n if (sEquipmentno.length >= 10) {\n if (checkDigit != sEquipmentno.substr(10)) {\n args.IsValid = false;\n oSrc.errormessage = \"Check Digit is incorrect for the entered Equipment. Correct check digit is \" + checkDigit;\n return;\n }\n }\n }\n }\n } else {\n args.IsValid = false;\n oSrc.errormessage = msg;\n return;\n }\n\n if (strContinue == \"\") {\n validateEquipmentNo(oSrc, args);\n if (args.IsValid == false) {\n return false\n }\n }\n\n var rowState = ifgPreAdvice.ClientRowState();\n var oCallback = new Callback();\n\n oCallback.add(\"EquipmentId\", sEquipmentno);\n oCallback.add(\"GridIndex\", ifgPreAdvice.VirtualCurrentRowIndex());\n oCallback.add(\"RowState\", rowState);\n oCallback.invoke(\"PreAdvice.aspx\", \"ValidateEquipment\");\n if (oCallback.getCallbackStatus()) {\n //Newly added if Equipment no already available in some other depot\n if (oCallback.getReturnValue(\"EquipmentNoInAnotherDepot\") == \"false\") {\n oSrc.errormessage = \"This Equipment \" + sEquipmentno + \" already exists for Pre-Advice in some other Depot.\";\n args.IsValid = false;\n }\n else if (oCallback.getReturnValue(\"StatusOfEquipment\") == \"false\") {\n oSrc.errormessage = \"This Equipment \" + sEquipmentno + \" already is in Active State in some other Depot.\";\n args.IsValid = false;\n }\n else if (oCallback.getReturnValue(\"bNotExists\") == \"true\") {\n args.IsValid = true;\n } \n else if (oCallback.getReturnValue(\"bRentalNotExists\") == \"false\") {\n // args.IsValid = false;\n var strCustomer = oCallback.getReturnValue(\"Customer\");\n var strAllowRental = oCallback.getReturnValue(\"AllowRental\");\n var cols = ifgPreAdvice.Rows(ifgPreAdvice.CurrentRowIndex()).GetClientColumns();\n if (strCustomer != cols[0] && cols[0] != \"\") {\n oSrc.errormessage = \"This Equipment \" + sEquipmentno + \" already exists for Customer \" + strCustomer + \" in Rental\";\n args.IsValid = false;\n }\n else if (strAllowRental == \"False\") {\n oSrc.errormessage = \"This Equipment \" + sEquipmentno + \" cannot be submitted as Rental Gate Out not created \" + strCustomer + \" in Rental\";\n args.IsValid = false;\n }\n }\n else {\n args.IsValid = false;\n var strCustomer = oCallback.getReturnValue(\"Customer\");\n oSrc.errormessage = \"Gate In has been already created for the Equipment \" + sEquipmentno + \" with Customer \" + strCustomer + \",hence cannot create Pre-Advice.\";\n }\n if (oCallback.getReturnValue(\"EquipmentTypeCode\") != '' && oCallback.getReturnValue(\"EquipmentTypeId\") != '') {\n ifgPreAdvice.Rows(ifgPreAdvice.CurrentRowIndex()).SetColumnValuesByIndex(2, new Array(oCallback.getReturnValue(\"EquipmentTypeCode\"), oCallback.getReturnValue(\"EquipmentTypeId\")));\n ifgPreAdvice.Rows(ifgPreAdvice.CurrentRowIndex()).SetReadOnlyColumn(2, true);\n }\n \n }\n else {\n showErrorMessage(oCallback.getCallbackError());\n }\n oCallback = null;\n}",
"static zfsValidateOptions(options) {\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options, ZosFiles_messages_1.ZosFilesMessages.missingFilesCreateOptions.message);\n /* If our caller does not supply these options, we supply default values for them,\n * so they should exist at this point.\n */\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.perms, ZosFiles_messages_1.ZosFilesMessages.missingZfsOption.message + \"perms\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.cylsPri, ZosFiles_messages_1.ZosFilesMessages.missingZfsOption.message + \"cyls-pri\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.cylsSec, ZosFiles_messages_1.ZosFilesMessages.missingZfsOption.message + \"cyls-sec\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.timeout, ZosFiles_messages_1.ZosFilesMessages.missingZfsOption.message + \"timeout\");\n // validate specific options\n for (const option in options) {\n if (options.hasOwnProperty(option)) {\n switch (option) {\n case \"perms\":\n const maxPerm = 777;\n if ((options.perms < 0) || (options.perms > maxPerm)) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.invalidPermsOption.message + options.perms\n });\n }\n break;\n case \"cylsPri\":\n case \"cylsSec\":\n // Validate maximum allocation quantity\n if (options[option] > ZosFiles_constants_1.ZosFilesConstants.MAX_ALLOC_QUANTITY) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.maximumAllocationQuantityExceeded.message + \" \" +\n ZosFiles_messages_1.ZosFilesMessages.commonFor.message + \" '\" + option + \"' \" + ZosFiles_messages_1.ZosFilesMessages.commonWithValue.message +\n \" = \" + options[option] + \".\"\n });\n }\n break;\n case \"owner\":\n case \"group\":\n case \"storclass\":\n case \"mgntclass\":\n case \"dataclass\":\n case \"volumes\":\n case \"timeout\":\n case \"responseTimeout\":\n // no validation at this time\n break;\n default:\n throw new imperative_1.ImperativeError({ msg: ZosFiles_messages_1.ZosFilesMessages.invalidFilesCreateOption.message + option });\n } // end switch\n }\n } // end for\n }",
"function testChoice() {\n var status = 40;\n var qualifiedState = true;\n $.each(checkChoice, function (ele, index) {\n if (checkChoice[ele] == '') {\n status -= 10;\n } else {\n switch (ele) {\n case \"address\":\n var text = $('.info_Choice input[states=address]').val();\n var reg = /^[a-zA-Z0-9\\u4e00-\\u9fa5]+$/;\n if (!reg.test(text)) {\n showTip(\"您的小区名有误请重新输入\");\n $('.info_Choice input[states=address]').focus();\n qualifiedState = false;\n return false;\n }\n break;\n case \"area\":\n var text = $('.info_Choice input[states=area]').val();\n var reg = /^\\+?[1-9][0-9]*$/;\n if (!reg.test(text)) {\n showTip(\"房屋面积为正整数请重新输入\");\n $('.info_import input[states=area]').focus();\n qualifiedState = false;\n return false;\n }\n break;\n case \"budget\":\n var text = $('.info_Choice input[states=budget]').val();\n var reg = /^\\+?[1-9][0-9]*$/;\n if (!reg.test(text)) {\n showTip(\"预算金额为正整数请重新输入\");\n $('.info_import input[states=budget]').focus();\n qualifiedState = false;\n return false;\n }\n break;\n }\n }\n });\n return {\n state:status,\n error:qualifiedState\n };\n }",
"function validateMedicalAidNumberOfDependents() { \n var optionSelected=\"\";\n var numOfOptions = document.TaxCalculator.hasMedicalAid.length;\n var numberOfDepedents = document.TaxCalculator.numberOfDependents.value;\n var regex = /[0-9]|\\./;\n \n for (var index=0; index < numOfOptions; index++) {\n if (document.TaxCalculator.hasMedicalAid[index].selected) {\n optionSelected = document.TaxCalculator.hasMedicalAid[index].value;\n break;\n } \n }\n \n if (optionSelected === \"yes\") {\n if (numberOfDepedents === \"\") {\n errorMessage +=\"Please Enter the Number of Dependents. \\n\";\n document.getElementById(\"numberOfDependents\").style.backgroundColor=\"red\";\n return false;\n } else if (!regex.test(numberOfDepedents)) {\n errorMessage +=\"Please Enter a Numberic Value for Dependents. \\n\";\n document.getElementById(\"numberOfDependents\").style.backgroundColor=\"red\";\n return false;\n } else { \n document.getElementById(\"numberOfDependents\").style.backgroundColor=\"\"; \n return true; \n }\n } else {\n document.getElementById(\"numberOfDependents\").style.backgroundColor=\"\"; \n return true; \n }\n}",
"function valDadosRG() {\r\n\tvar numPreenchidos = 0;\r\n\tvar campoVazio;\r\n\tvar aba = valDadosRG.arguments[4];\r\n\tfor (i=3; i>=0; i--) { // sao 4 campos sobre o RG\r\n\t\tif (valDadosRG.arguments[i].value != \"\") numPreenchidos += 1;\r\n\t\telse campoVazio = valDadosRG.arguments[i];\r\n\t}\r\n\tif (numPreenchidos != 4 && numPreenchidos != 0) {\r\n\t\tif (aba != \"undefined\" && aba != null) Dados.oAbas.selecionaTabDefault(aba);\r\n\t\talert(\"Informe todos os campos referentes ao RG.\");\r\n\t\tcampoVazio.focus();\r\n\t\treturn false;\r\n\t}\r\n\tif (!valData(valDadosRG.arguments[1],\"Data de emissão inválida.\",2)) return false;\r\n\tif (!valPeriodoData(valDadosRG.arguments[1],null,\"Data de emissão tem que ser menor ou igual à data de hoje.\")) return false;\r\n\treturn true;\r\n}",
"function saveEndReservationAlerts(mainMenu,msg,type,opt){\n\tvar mobileFlag = (globalDeviceType == \"Mobile\");\n\tvar msgHeader = \"Notification\";\n\tvar msgStr = \"\"; var typex = \"\";\n\tvar func2Eval = \"\"; var optSaveFlag=false;\n\tif(opt==\"Save\"){var resOpt = \"comOpEndRes\"; optSaveFlag=true;}\n\tif(opt==\"Load\"){var resOpt = \"comOpStartRes\";}\n\tif(mainMenu){\n\t\tfunc2Eval += \"saveEndResQuery('\"+opt+\"');\";\n\t}else{\n\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\tfunc2Eval += \"changePageWithTimeout('commitOptions','\"+resOpt+\"',true);\";\n\t\t}else{\n\t\t\tfunc2Eval += \"$('#startEndReserve').dialog('close');\";\n\t\t\tfunc2Eval += \"$('#\"+resOpt+\"').prop('checked',true);\";\n\t\t}\n\t}\n\tswitch(true){\n\t\tcase (type.toLowerCase()==\"config\" && optSaveFlag): \n\t\t\ttypex = \"Configuration\";\n\t\t\tfunc2Eval += \"setvaluesendconfig=true;\";\n\t\t\tbreak;\n\t\tcase (type.toLowerCase()==\"config\" && !optSaveFlag): \n\t\t\ttypex = \"Configuration\";\n\t\t\tfunc2Eval += \"setvaluesstartconfig=true;\";\n\t\t\tbreak;\n\t\tcase (type.toLowerCase()==\"image\" && optSaveFlag): \n\t\t\ttypex = \"Image\";\n\t\t\tfunc2Eval += \"setvaluesendimage=true;\";\n\t\t\tbreak;\n\t\tcase (type.toLowerCase()==\"image\" && !optSaveFlag): \n\t\t\ttypex = \"Image\";\n\t\t\tfunc2Eval += \"setvaluesstartimage=true;\";\n\t\t\tbreak;\n\t\tcase (type.toLowerCase()==\"both\" && optSaveFlag): \n\t\t\ttypex = \"Image and Configuration\";\n\t\t\tfunc2Eval += \"setvaluesendimage=true;\";\n\t\t\tfunc2Eval += \"setvaluesendconfig=true;\";\n\t\t\tbreak;\n\t\tcase (type.toLowerCase()==\"both\" && !optSaveFlag): \n\t\t\ttypex = \"Image and Configuration\";\n\t\t\tfunc2Eval += \"setvaluesstartimage=true;\";\n\t\t\tfunc2Eval += \"setvaluesstartconfig=true;\";\n\t\t\tbreak;\n\t}\n\tswitch(msg){\n\t\tcase 1: \n\t\t\tmsgStr = \"Are you sure you want to set new values for the \"+typex+\"? \";\n\t\t\tmsgStr += \"This will override what is saved in the database. \";\n\t\t\tmsgStr += \"Please make sure \"+typex.toLowerCase()+\" to be \"+opt.toLowerCase()+\" are compatible \";\n\t\t\tmsgStr += \"with the selected device(s) or this might cause unwanted result\";\n\t\t\talertType = \"alert2\";\n\t\t\tbreak;\n\t\tcase 2: \n\t\t\tmsgStr = \"Please make sure \"+typex.toLowerCase()+\"s to be \"+opt.toLowerCase()+\" are compatible \";\n\t\t\tmsgStr += \"with the selected device(s) or this might cause unwanted result\";\n\t\t\talertType = \"prompt\";\n\t\t\tbreak;\n\t}\n\tswitch(mobileFlag){\n\t\tcase true: confirmation(msgStr,msgHeader,func2Eval); break;\n\t\tcase false: alerts(msgStr,func2Eval,alertType); break;\n\t}\n\treturn;\n}",
"function saveEndReservationSetAttrImage(MainEndArr){\n\tvar saveImg = MainEndArr.split(\"*\");\n\tfor(var i=0; i<devicesArr.length; i++){\n\t\tif(saveImg.length==4){\n\t\t\tdevicesArr[i].SaveImageUrl = saveImg[1];\n\t\t\tdevicesArr[i].SaveImageDestination = saveImg[2];\n\t\t\tdevicesArr[i].SaveTypeImage = saveImg[3];\n\t\t\tdevicesArr[i].SaveImageEnable = \"true\";\n\t\t\tdevicesArr[i].SaveImageDetail = \"false\";\n\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].SaveImageEnable = \"true\";\n\t\t}else{\n\t\t\tdevicesArr[i].SaveImageServer = saveImg[2];\n\t\t\tdevicesArr[i].ImageFilePath = saveImg[3];\n\t\t\tdevicesArr[i].SaveImageFileName = saveImg[4];\n\t\t\tdevicesArr[i].SaveImageDestination = saveImg[5];\n\t\t\tdevicesArr[i].SaveImageType = saveImg[6];\n\t\t\tdevicesArr[i].SaveTypeImage = saveImg[1];\n\t\t\tdevicesArr[i].SaveImageEnable = \"true\";\n\t\t\tdevicesArr[i].SaveImageDetail = \"true\";\n\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].SaveImageEnable = \"true\";\n\t\t}\n \t}\n\treturn;\n}",
"function checkBookingAvailableClosedPassed () {\n\t \t var sliderSeconds = 15*60*parseInt(place_slider_from); // 15 minutes * slider steps\n var sliderSecondsTo = 15*60*parseInt(place_slider_to); // 15 minutes * slider steps\n\n\t var TimeOfTheDatePicker_1970 = +$(\"#datepicker_fe\").datepicker( \"getDate\" ).getTime();\n\t var placeOffset = document.getElementById(\"server_placeUTC\").value;\n\t var dndt = TimeOfTheDatePicker_1970/1000;\n\t var d = new Date();\n\t var utc = d.getTime() + (d.getTimezoneOffset() * 60000);\n\t var nd = new Date(utc + (3600000 * placeOffset));\n\t var ndt = nd.getTime()/1000;\n var diff = ndt - dndt; // seconds passed from the start of the selected date\n if (diff - 60 > sliderSeconds) {\n \t // If less than minute to book return \"place_passed\"\n \t return 1;\n }\n // Else slider is after the place time passed , check if place closed on selected range\n var TimePeriod = sliderSecondsTo - sliderSeconds; // Chosen period of booking\n var endOfBooking = parseInt(sliderSeconds) + parseInt(TimePeriod);\n\t var placeOpen = bookingVars.placeOpen;\n\t var anyOpenRangeValid = false;\n\t for (var ind in placeOpen) { \t\t \n\t\t\t var from = placeOpen[ind].from;\n\t\t\t var to = placeOpen[ind].to;\n\t\t\t if (from <= sliderSeconds && endOfBooking <= to) {\n\t\t\t\t anyOpenRangeValid = true;\n\t\t\t }\n\t }\n\tif(anyOpenRangeValid) {\n\t //Some range valid\n\t return 0;\n\t} else {\n\t // No valid open range\t\n\t return 2;\n\t}\n}",
"function commitOptionsOk(){\n\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].DeviceSanity = \"false\";\n\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].AccessSanity = \"false\";\n\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].LinkSanityEnable = \"false\";\n\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].EnableInterface = \"false\";\n\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].Connectivity = \"false\";\n\tvar devSan = $(\"#comOpDevSanity\").is(\":checked\");\n\tvar accSan = $(\"#comOpAccSanity\").is(\":checked\");\n\tvar connec = $(\"#comOpConnectivity\").is(\":checked\");\n\tvar enaInt = $(\"#comOpEnaInterface\").is(\":checked\");\n\tvar lnkSan = $(\"#comOpLinkSanity\").is(\":checked\");\n\tvar startR = $(\"#comOpStartRes\").is(\":checked\");\n\tvar endR = $(\"#comOpEndRes\").is(\":checked\");\n\tfor(var t=0; t<globalMAINCONFIG.length; t++){\n\t\tif(globalMAINCONFIG[t].MAINCONFIG[0].PageCanvas == pageCanvas){\n\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].DeviceSanity = devSan.toString();\n\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].AccessSanity = accSan.toString();\n\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].LinkSanityEnable = lnkSan.toString();\n\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].EnableInterface = enaInt.toString();\n\t\t\tStartReservation = startR.toString();\n\t\t\tEndReservation = endR.toString();\n\t\t}\n\t}\n\tStartReservation = startR.toString();\n\tEndReservation = endR.toString();\n\tif($(\"#comOpConnectivity\").is(\":visible\")){\n\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].Connectivity = connec.toString();\n\t}\n\tif($(\"#comOpConnectivity\").parent().parent().parent().attr('style') == \"display: none;\"){\n\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].Connectivity = \"false\";\n\t}\n\tif(lnkSan == \"true\" || lnkSan == true){\n\t\tlnkSan = \"yes\";\n\t}else{\n\t\tlnkSan = \"no\";\n\t}\n\tif(globalInfoType == \"JSON\"){\n\t\tvar devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n\t}\n\tfor(var a=0;a < devices.length; a++){\n\t\tdevices[a].ConnectivityFlag = lnkSan;\n\t}\n\tfor(var b=0;b < window['variable' + dynamicLineConnected[pageCanvas]].length; b++){\n\t\twindow['variable' + dynamicLineConnected[pageCanvas]][b].ConnectivityFlag = lnkSan;\n\t}\n\twindow['variable' + ConnectivityFlag[pageCanvas]] = lnkSan;\n\tsetTimeout(function(){\n \tif(TimePicker == false){\n \t$(\"#RequestButton\").trigger(\"click\");\n }\n \t},1000);\n\tshowPickerOption();\n}",
"function validateAdsAddPageForm(formname,isimage)\n{\n var frmAdType = $(\"#\"+formname+\" input[type='radio']:checked\").val();\n \n if(frmAdType=='html'){\n if($('#frmTitle').val() == ''){\n alert(TIT_REQ);\n $('#frmTitle').focus()\n return false;\n }else if($('#frmHtmlCode').val() == ''){\n alert(HTML_REQ);\n $('#frmHtmlCode').focus()\n return false;\n }\n }else{ \n if($('#frmTitle').val() == ''){\n alert(TIT_REQ);\n $('#frmTitle').focus()\n return false;\n }else if($('#frmAdUrl').val() == ''){\n alert(URL_LINK_REQ);\n $('#frmAdUrl').focus()\n return false;\n }else if(IsUrlLink($('#frmAdUrl').val()) ==false){ \n alert(ENTER_VALID_LINK);\n $('#frmAdUrl').select();\n return false;\n }\n \n if(isimage==0){\n if($('#frmImg').val() == ''){\n alert(IMG_REQ);\n $('#frmImg').focus()\n return false;\n }\n }\n if($('#frmImg').val() != ''){\n var ff = $('#frmImg').val();\n var exte = ff.substring(ff.lastIndexOf('.') + 1);\n var ext = exte.toLowerCase();\n if(ext!='jpg' && ext!='jpeg' && ext!='gif' && ext!='png'){\n alert(ACCEPTED_IMAGE_FOR);\n $('#frmImg').focus();\n return false;\n }\n \n }\n }\n}",
"function validaCiudad(){\r\n\t\tvar concepto = $(\"#concepto option:selected\").text();\r\n\t\t\r\n\t\tif((/Comidas/.test(concepto))){\r\n\t\t\tasignaClass(\"ciudad\",\"req\");\r\n\t\t\tmostrarElemento(\"tr_ciudad\");\r\n\t\t}else\r\n\t\t\tocultarElemento(\"tr_ciudad\");\r\n\t}",
"function validateSelection() {\n let length = false;\n let type = false;\n let local = false;\n let inst;\n //check length\n if (selection.length === 1) {\n length = true;\n }\n //check type\n if (selection[0].type === 'INSTANCE') {\n type = true;\n inst = selection[0];\n }\n //check if remote\n if (type) {\n if (inst.masterComponent.remote === false) {\n local = true;\n }\n }\n //put it all together\n if (length && type && local) {\n return true;\n }\n else {\n if (!length) {\n errorMsg = 'Please select a single instance';\n return false;\n }\n else if (!type) {\n errorMsg = 'Selection must be an instance.';\n return false;\n }\n else if (!local) {\n errorMsg = 'Instance is from a library. Please select a local component.';\n return false;\n }\n }\n}",
"function isIVROption(s)\n{\n var i;\n\n if (isEmpty(s))\n if (isIVROption.arguments.length == 1) return defaultEmptyOK;\n else return (isIVROption.arguments[1] == true);\n\n if (s.length == 1) { // could be i or t as only one char entered\n\n \tvar c = s.charAt(0);\n\n \tif ( (!isDialDigitChar(c)) && (c != \"i\") && (c != \"t\") )\n \t\treturn false;\n\n } else { // numbers only\n\n\t for (i = 0; i < s.length; i++)\n\t {\n\t var c = s.charAt(i);\n\n\t if (!isDialDigitChar(c)) return false;\n\t }\n\n\t}\n\n return true;\n}",
"function loadStartReservationSetAttrImage(MainEndArr){\n\tvar loadImg = MainEndArr.split(\"*\");\n\tfor(var i=0; i<devicesArr.length; i++){\n\t\tif(loadImg.length==5){\n\t\t\tdevicesArr[i].ImageUrl = loadImg[2];\n\t\t\tdevicesArr[i].ImageDestination = loadImg[3];\n\t\t\tdevicesArr[i].TypeImage = loadImg[4];\n\t\t\tdevicesArr[i].LoadImageEnable = true;\n\t\t\tdevicesArr[i].ImageDetail = false;\n\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].LoadImageEnable = \"true\";\n\t\t}else{\n\t\t\tdevicesArr[i].ImageServer = loadImg[4];\n\t\t\tdevicesArr[i].ImageFilePath = loadImg[5];\n\t\t\tdevicesArr[i].ImageFileName = loadImg[6];\n\t\t\tdevicesArr[i].ImageDestination = loadImg[7];\n\t\t\tdevicesArr[i].ImageType = loadImg[8];\n\t\t\tdevicesArr[i].TypeImage = loadImg[2];\n\t\t\tdevicesArr[i].LoadImageEnable = true;\n\t\t\tdevicesArr[i].ImageDetail = true;\n\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].LoadImageEnable = \"true\";\n\t\t}\n \t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
looks for an given Note On event in a given step's action list and removes it if present returns true if Note On event is found and removed, otherwise false | function unsetNoteOn(stepNumber, instrumentIndex, noteNumber) {
// search for the Note On event
var searchAction = new Object();
searchAction.type = 'noteOn';
searchAction.instrumentIndex = instrumentIndex;
searchAction.noteNumber = noteNumber;
var searchResult = -1;
step[stepNumber].actionList.some(function(action, actionIndex) {
if (action.type == searchAction.type && action.instrumentIndex == searchAction.instrumentIndex && action.noteNumber == searchAction.noteNumber) {
searchResult = actionIndex;
return true;
}
});
if (searchResult >= 0) {
// remove the action ound by the search
step[stepNumber].actionList.splice(searchResult, 1);
// update sequencer grid to reflect the change
document.getElementById(constructGridId(stepNumber, instrumentIndex, noteNumber)).style.backgroundColor = '';
return true;
} else {
return false;
}
} | [
"remove(actionToRemove) {\n\t\tthis.actions = this.actions.filter( action => action.name !== actionToRemove.name);\n\t}",
"function remove(e) {\n\t\tvar fullPath = path.join(e.watch, e.name), i;\n\n\t\t// if it's in a watched directory or in the set of watches\n\t\tif (watches[e.watch] || watches[fullPath]) {\n\t\t\ti = modifyQueue.indexOf(fullPath);\n\t\t\tif (i >= 0) {\n\t\t\t\tmodifyQueue.splice(i, 1);\n\t\t\t}\n\n\t\t\t// just in case the file was temporary\n\t\t\ti = createQueue.indexOf(fullPath);\n\t\t\tif (i >= 0) {\n\t\t\t\tcreateQueue.splice(i, 1);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// TODO: not sure if this will ever fail\n\t\t\tif (removeQueue.indexOf(fullPath) < 0) {\n\t\t\t\tremoveQueue.push(fullPath);\n\t\t\t}\n\n\t\t\tremoveWatches(removeQueue);\n\t\t}\n\t}",
"onRemoveFromFavorite(e) {\n\t\te.stopPropagation();\n\t\tstoreActions.removeAppFromFolder(FAVORITES, this.props.app);\n\t\tstoreActions.removePin(this.props.app);\n\t}",
"function removeItem(event) {\n var id = event.target.id;\n var listName = id.split('_')[0];\n var listItem = id.split('_')[1];\n \n var index = items[listName].indexOf(listItem);\n items[listName].splice(index, 1);\n onLoad();\n}",
"function checkIfEvent(redditData, db, r) {\n if (redditData.title.toLowerCase().includes(eventMentioned)) {\n sendModMailAlert(redditData, db, r);\n replyToEventHost(redditData);\n r.getSubmission(redditData.name).remove({\n spam: true\n }).then(function (error) {\n console.log(error);\n });\n } else {\n db.run(\"INSERT INTO redditPost (name, processed) VALUES ('\" + redditData.name + \"', '1')\");\n }\n}",
"function handleDelete(event) {\n\tlet id = event.target.id;\n\n\tlet output = [];\n\n\toutput = db_appointments.filter(function (value) {\n\t\treturn value.idPengunjung !== id;\n\t});\n\n\tdb_appointments = output;\n\n\tevent.target.parentElement.remove();\n}",
"remove(eventName) {\n if (this.eventStorage[eventName]) {\n delete this.eventStorage[eventName];\n }\n }",
"function deleteActionItem(id, type) {\n var livestock_id = String(localStorage.LivestockID)\n var startPointID = String(localStorage.startPointIDBelegung)\n ons.notification.confirm({\n message: 'Möchtest du den Eintrag löschen?',\n title: 'Nutztier Eintrag löschen',\n buttonLabels: ['Ja', 'Nein'],\n animation: 'default',\n primaryButtonIndex: 1,\n cancelable: true,\n callback: function (index) {\n if (index == 0) {\n //if type is 'Belegung' then delete also future action items\n if (type == \"Belegung\") {\n db.transaction(function (tx) {\n tx.executeSql('DELETE FROM livestock_action WHERE id = ? OR future = ?',\n [id, 'true']);\n },\n function (error) {\n alert('Error: ' + error.message + ' code: ' + error.code);\n },\n function () {\n setActionDetailView('true')\n });\n //all others only delete action item and update futer itmes display field\n } else {\n db.transaction(function (tx) {\n tx.executeSql('DELETE FROM livestock_action WHERE id = ?', [id]);\n tx.executeSql('UPDATE livestock_action SET display = ? WHERE livestock_id = ? AND type = ? AND future = ? AND id > ?', ['true', livestock_id, type, 'true', startPointID]);\n },\n function (error) {\n alert('Error: ' + error.message + ' code: ' + error.code);\n },\n function () {\n setActionDetailView('true')\n });\n }\n }\n }\n });\n}",
"async function removeStoryfromOwnStoryPage(evt){\n const $storyId = $(evt.target).closest('li').attr('id');\n await storyList.removeStory(currentUser, $storyId);\n putOwnStoriesOnPage(currentUser);\n}",
"eraseEvent(state, num) {\n state.events.splice(num, 1);\n\n }",
"handleDeleteItems(e){\n\t\tconst id = e.target.attributes.keyset.value\n\t\tActions.deleteTodo(id)\n\t}",
"function remove_note(e, i){\n \n e.parentNode.parentNode.removeChild(e.parentNode);\n const task=localStorage.getItem(\"array\");\n const note=JSON.parse(task);\n note.splice(i, 1);\n localStorage.setItem('array',JSON.stringify(note));\n location.reload();\n }",
"function removeScheduled(ticket) {\n return ticket.id !== invoiceToRemove\n }",
"onRemoveMealButtonPressed(event) {\n\t\tevent.currentTarget.parentNode.parentNode.removeChild(event.currentTarget.parentNode);\n\t}",
"function deleteListToAppData(e){\n const title = e.target.closest('.oneLists').querySelector('.tagText').textContent\n const listInAppData = appData.lists.board.find((DataTitle) => title === DataTitle.title)\n let indexOfList = 0;\n\n appData.lists.board.forEach((list, index) => {\n\n if (list.title === listInAppData.title) {\n indexOfList = index;\n appData.lists.board.splice(indexOfList, 1)\n\n }\n });\n}",
"deleteEvent() {\n let updatedEvents = this.state.events.filter(\n event => event[\"start\"] !== this.state.start\n );\n // localStorage.setItem(\"cachedEvents\", JSON.stringify(updatedEvents));\n this.setState({ events: updatedEvents });\n }",
"function confirmWatchListRemove(leadid){\r\n\tvar leadID = leadid;\r\n var choice = confirm('Do you really want to remove this lead from watch list?');\r\n if(choice === true) {\r\n remove_watch_list(leadID);\r\n\t\treturn true;\r\n }\r\n return false;\t\r\n}",
"deleteItemsEventsEtc() {\n let items_buffer = getReferencesOfType('AGItem');\n items_buffer.forEach(function (buffer) {\n deleteItem(buffer);\n });\n let conditions_buffer = getReferencesOfType('AGCondition');\n conditions_buffer.forEach(function (buffer) {\n deleteCondition(buffer);\n });\n let glevents_buffer = getReferencesOfType('GlobalEvent');\n glevents_buffer.forEach(function (buffer) {\n getReferenceById(getReferencesOfType(\"AGEventHandler\")[0]).removeGlobalEventByID(parseInt(buffer));\n });\n let events_buffer = getReferencesOfType('Event');\n events_buffer.forEach(function (buffer) {\n getReferenceById(getReferencesOfType(\"AGEventHandler\")[0]).removeEventByID(parseInt(buffer));\n });\n\n this.listItems();\n this.listEvents();\n this.refreshItemSelect();\n this.listGlobalEvents();\n this.listConditions();\n }",
"purge(evtName) {\n if (typeof evtName === 'string') {\n if (evtName) {\n this.listeners.delete(evtName)\n }\n } else if (evtName === true) {\n this.listeners.clear()\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the current StepContext or an empty object if no StepContext has been defined in the component tree. | function useStepContext() {
return React.useContext(StepContext);
} | [
"get currentStep() {\n return this._wizard.getAttribute('currentpageid');\n }",
"getStepIndex(){\n\t\tvar currentPath = this.state.path;\n\n\t\treturn this.findStepIndex(currentPath);\n\t}",
"function getContext(){\n \n if(!domain.active || !domain.active.context){\n if(this.mockContext) return this.mockContext\n \n logger.error(\"getContext called but no active domain\", domain.active);\n logger.error(\"Caller is \", arguments.callee && arguments.callee.caller && arguments.callee.caller.name, arguments.callee && arguments.callee.caller );\n throw \"Context not available. This may happen if the code was not originated by Angoose\"; \n } \n \n return domain.active.context;\n}",
"getChildContext() {\n return {\n store: this.store,\n };\n }",
"function getFileContext(contentPath){\n\tvar contextPath = getContextFilePath(contentPath),\n\t\t\tparent = '';\n\n\ttry {\n\t\tif (!_.isUndefined(siteContext.files[contextPath])) {\n\t\t\treturn siteContext.files[contextPath].context;\n\t\t} else if (useNearestContext){\n\t\t\t//TODO: try to find the nearest matching context up the tree\n\t\t\t//doc this option for the grunt file\n\t\t\tparent = util.getDirectoryPath(contentPath)+'/'+util.getParentDirectory(contentPath);\n\t\t\tgrunt.log.debug(parent);\n\t\t\tif (parent !== '.'){\n\t\t\t\treturn getFileContext(parent);\n\t\t\t} else {\n\t\t\t\tgrunt.log.debug('ran out of parents');\n\t\t\t\treturn {};\n\t\t\t}\n\t\t}\n\t} catch(error){\n\t\tgrunt.log.error(error);\n\t\treturn {};\n\t}\n}",
"get(context) {\r\n const cached = context.get(this.stateKey);\r\n return typeof cached === 'object' && typeof cached.state === 'object' ? cached.state : undefined;\r\n }",
"getApplicationContext() {\n let context = \"\";\n // figure out the context we need to apply for where the editing creds\n // and API might come from\n // beaker is a unique scenario\n if (typeof DatArchive !== typeof undefined) {\n context = \"beaker\"; // implies usage of BeakerBrowser, an experimental browser for decentralization\n } else {\n switch (window.HAXCMSContext) {\n case \"published\": // implies this is to behave as if it is completely static\n case \"nodejs\": // implies nodejs based backend, tho no diff from\n case \"php\": // implies php backend\n case \"11ty\": // implies 11ty static site generator\n case \"demo\": // demo / local development\n case \"desktop\": // implies electron\n case \"local\": // implies ability to use local file system\n case \"userfs\": // implies hax.cloud stylee usage pattern\n context = window.HAXCMSContext;\n break;\n default:\n // we don't have one so assume it's php for now\n // @notice change this in the future\n context = \"php\";\n break;\n }\n }\n return context;\n }",
"function Step(props) {\n return __assign({ Type: 'AWS::EMR::Step' }, props);\n }",
"function getParentPageState() {\n return sp.result(spNavService.getParentItem(), 'data');\n }",
"getCurrentImporterTask() {\n return this._currentImportTask;\n }",
"function Context(instance,schema,ipath,spath,parent){\n if (!(this instanceof Context)) return new Context(instance,schema,ipath,spath,parent);\n this.instance = instance;\n this.schema = schema;\n this.instancePath = (ipath === undefined ? [] : ipath);\n this.schemaPath = (spath === undefined ? [] : spath);\n this._assertions = [];\n this._delegate = undefined;\n this.contexts = [];\n this.parent = parent;\n this.validAll();\n return this;\n}",
"function getCurrentInstance() {\n return currentInstance && { proxy: currentInstance };\n }",
"getAppContext() {\n return this._appContext;\n }",
"getContextById(context) {\n if (typeof context === 'string' || context instanceof String) {\n return this.contexts[context];\n }\n return context; // might already be a context object\n }",
"function getRfc232TestContext() {\n // Support older versions of `ember-qunit` that don't have\n // `@ember/test-helpers` (and therefore cannot possibly be running an\n // rfc232/rfc268 test).\n if (_require2.default.has('@ember/test-helpers')) {\n let { getContext } = (0, _require2.default)('@ember/test-helpers');\n return getContext();\n }\n }",
"getChildContext() {\n return { translator };\n }",
"get contexts()\n\t{\n\t\tvar priv = PRIVATE.get(this);\n\t\treturn priv.contextsContainer.array;\n\t}",
"function getSelected() {\n\t\t\tif (!activeElement) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tvar elem = document,\n\t\t\t\tpath = JSON.parse(activeElement.getAttribute('data-js-path'));\n\n\t\t\tif (path[0] !== \"\") {\n\t\t\t\tfor (var i = 0, len = path.length; i < len; ++i) {\n\t\t\t\t\telem = elem.childNodes[path[i]];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn elem;\n\t\t}",
"getCurrentlySelectedComponent() {\n return simulationArea.lastSelected;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to buy parts store by storeID | function buyPartStore(storeID, storeName){
window.location.href = site_root+"app/views/part-store-cpanel.php?action=buyStore&store_id="+storeID+"&storeName="+storeName;
} | [
"function functionToBuy() {\n buySpecificItem(someItemFromShop);\n }",
"function openBuyStore(storeID){\n\t// Get the stores cost\n\tvar storeCost = $(\"#ps_name_\"+storeID).data(\"value\");\n\n\t$( \"#buyPartStore\" ).data('storeID', storeID);\n\t$( \"#bps_cost\" ).text(storeCost);\n\t$( \"#buyPartStore\" ).dialog( \"open\" );\n}",
"function clickToBuy(someItemFromShop) {\n someItemFromShop.shopBtnI.addEventListener('click', functionToBuy);\n // Functions starts another function to buy specific item\n function functionToBuy() {\n buySpecificItem(someItemFromShop);\n };\n}",
"function buy(buyerID, listingID) {\n var item = listing.get(listingID);\n var buyer = item.buyer;\n var seller = item.seller;\n \n if (seller === buyerID) {\n return \"You can't buy your own items\";\n }\n if(!buyer) {\n item[\"buyer\"] = buyerID;\n //item.buyer = buyerID;\n //listing.set(listingID, {...item, buyer: buyerID});\n itemsSold.set(listingID, item);\n itemsBought.set(listingID, item);\n fs.writeFileSync('listing-infos.txt', mapToJson(listing));\n return \"Purchase successful!\";\n }\n}",
"function createProduct(name, price) {\n // this.setState({ loading: true });\n const web3 = window.web3;\n // const networkId = web3.eth.net.getId();\n // const networkData = Marketplace.networks[networkId];\n\n\n const { account } = formData;\n console.log(\"account\", account);\n\n\n formData.marketplace.methods\n .createProduct(name, price)\n .send({ from: localStorage.getItem(\"account\") })\n .once(\"receipt\", (receipt) => {\n });\n\n }",
"function sellSpecificItem(someItem) {\n someItem.shopDivI.style.display = 'block';\n someItem.inventoryDivI.style.display = 'none';\n money = money + someItem.sellI();\n prestige = prestige - someItem.owningI;\n someItem.boughtI = false;\n updateStats();\n message(msgSell + someItem.nameI + ' for ' + someItem.sellI() + '$');\n someItem.usageCountI = 0;\n}",
"function purchaseItems() {\n\t// check for atleast one sessionStorage object\n\tif (sessionStorage.itemName) {\n\t\tlet openModal = document.getElementsByClassName('modal')[0]\n\t\topenModal.style.display = 'block'\n\t\tgrandTotal()\n\t} else {\n\t\talert('Please Add An Item To Your Cart.')\n\t\twindow.location.href = '../html/store.html'\n\t}\n}",
"isItemAvailableOnFavoriteStore (skuId, quantity) {\n this.store.dispatch(getSetSuggestedStoresActn(EMPTY_ARRAY)); // clear previous search results\n let storeState = this.store.getState();\n let preferredStore = storesStoreView.getDefaultStore(storeState);\n let {coordinates} = preferredStore.basicInfo;\n let currentCountry = sitesAndCountriesStoreView.getCurrentCountry(storeState);\n\n return this.tcpStoresAbstractor.getStoresPlusInventorybyLatLng(skuId, quantity, 25, coordinates.lat, coordinates.long, currentCountry).then((searchResults) => {\n let store = searchResults.find((storeDetails) => storeDetails.basicInfo.id === preferredStore.basicInfo.id);\n return store && store.productAvailability.status !== BOPIS_ITEM_AVAILABILITY.UNAVAILABLE;\n }).catch(() => {\n // assume not available\n return false;\n });\n }",
"function buyProduct() {\n // query the database for all products on sale. \n /* Documentation: The simplest form of .query() is .query(sqlString, callback), \n where a SQL string is the first argument and the second is a callback: */\n connection.query(\"SELECT * FROM `products`\", function(err, results) {\n if(err) throw err;\n // once all items are displayed, prompt user with two messages: id? / units?\n inquirer\n .prompt([\n // pass in array of objects\n { \n //Requests product ID of item user would like to buy.\n name: \"chooseID\",\n type: \"list\",\n message: \"Please select product ID to place your order:\",\n filter: Number, \n choices: [\"100\", new inquirer.Separator(), \n \"101\", new inquirer.Separator(), \n \"102\", new inquirer.Separator(), \n \"103\", new inquirer.Separator(), \n \"104\", new inquirer.Separator(), \n \"105\", new inquirer.Separator(), \n \"106\", new inquirer.Separator(), \n \"107\", new inquirer.Separator(), \n \"108\", new inquirer.Separator(), \n \"109\", new inquirer.Separator()\n ] \n },\n {\n // Request number of units. \n name: \"numUnits\",\n type: \"list\",\n message: \"How many units would you like to buy?\",\n filter: Number,\n // Documentation: A separator can be added to any choices array: new inquirer.Separator() cool!\n choices: [\"1\", new inquirer.Separator(),\n \"2\", new inquirer.Separator(), \n \"4\", new inquirer.Separator(), \n \"8\", new inquirer.Separator(), \n \"16\", new inquirer.Separator()\n ]\n }\n ]) //prompt({}) ends\n .then(function(answers) { //.then(answers => {...}) [ES6 syntax]\n /* 7. Once the customer has placed the order, your application should check if your store has enough of the product to meet the customer's request.\n If not, the app should log a phrase like Insufficient quantity!, and then prevent the order from going through. */\n console.log(answers); //answers are the USER's FEEDBACK\n for(var i = 0; i < results.length; i++) { //results refer to the data we get from MySQL database\n if(results[i].id === answers.chooseID && results[i].stock_quantity >= answers.numUnits) { //works as expected\n // chooseID refers to the name property value of the promp question constructed in lines 105 to 114\n //return results[i].product_name; //this line cuts through the loop once it finds the selected id\n //create a function to update stock quantity available \n //multiply itme's price * number of units to purchase (USER's INPUT)\n var subtotal = results[i].price * answers.numUnits;\n // add sales tax rate of 8.25% (multiply subtotal * tax rate)\n var salesTax = subtotal * 0.0825;\n // calculate total amount\n var total = subtotal + salesTax;\n // console.log receipt\n console.log(`\n 〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️\n You purchased: ${answers.numUnits + \" \" + results[i].product_name + \"s!\"}\n ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ \n Subtotal: $ ${subtotal}\n Sales Tax: $ ${salesTax.toFixed(2)}\n TOTAL: $ ${total.toFixed(2)}\n ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ \n WE APPRECIATE YOUR BUSINESS!\n 〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️\n `) \n // The toFixed() method converts a number into a string, keeping a specified number of decimals.\n /* 8. However, if your store does have enough of the product, you should fulfill the customer's order.\n This means updating the SQL database to reflect the remaining quantity.\n Once the update goes through, show the customer the total cost of their purchase. */\n var balance = results[i].stock_quantity - answers.numUnits; \n console.log(\"Remaining number of \" + results[i].product_name + \"s in stock : \" + balance);\n // HERE WE NEED TO CONNECT TO MYSQL TO UPDATE THE DATA IN MYSQL DATABASE\n connection.query(\n \"UPDATE `products` SET stock_quantity = ? WHERE id = ?\", [balance, results[i].id],\n function(error) {\n if (error) throw error;\n console.log(\"Stock quantity has been UPDATED!\");\n //delete row with zero stock quantity\n // DELETE statement\n connection.query(\"DELETE FROM `products` WHERE `stock_quantity` = ?\", 0);\n connection.end();\n } \n ); // connection. query ends \n }\n // AS I CONTINUE LOOPING THROUGH MYSQL DATA & I DO NOT HAVE ENOUGH ITEMS IN MY INVENTORY:\n else if(results[i].id === answers.chooseID && results[i].stock_quantity < answers.numUnits) {\n console.log(\"Not enough items in stock! We apologize for the inconvenience.\");\n inquirer\n .prompt({\n type: \"confirm\", \n name: \"buyAgain\",\n message: \"Would you like to decrease the quantity of items?\"\n })\n .then(function(answers) {\n if(answers.buyAgain) {\n //call buyAgain() function\n buyAgain(); \n }\n else {\n connection.end();\n }\n }) //.then ends\n } //else if closes\n } //for loop closes\n }) //.then(){} ends\n }); //connection.query({}) ends\n}",
"handleBuy(e) {\n e.preventDefault();\n let quantity = 0, price = 0;\n let items = [];\n let order = _.get(this.state, 'cart');\n if (!order.length) {\n alert('Please select at least one product');\n return; \n } else {\n order.map((item, index) => {\n price += item.product_price;\n quantity++;\n items.push(item.product_id);\n });\n }\n let url = 'http://localhost:3000/orders/';\n Request.post(url)\n .send({\n quantity,\n price,\n items\n })\n .end((error, response) => {\n if (error || !response.ok) {\n } else {\n }\n this.setState({\n cart: [],\n orders: this.getOrders()\n })\n });\n }",
"async function buy(buyerID, listingID) {\n let sellerID = await itemListings.once('value').then(data => data.val())\n .then(items => items[listingID].sellerID)\n\n return Promise.all([\n itemsBought.child(buyerID).child(listingID).set(true),\n itemsSold.child(sellerID).child(listingID).set(true),\n itemListings.child(listingID).child('forSale').set(false)\n ])\n}",
"buy() {\n if (clickNumber >= this.cost) {\n clickNumber = truncate(clickNumber-this.cost);\n this.inv += 1;\n document.getElementById(\"inv-\" + this.id).innerHTML = this.inv;\n if (this.itemManualClickStrength != 0) {\n clickStrength *= this.itemManualClickStrength; \n }\n autoClickStrength += this.itemClickStrength;\n this.cost *= 2;\n \n document.getElementById(\"cost-\" + this.id).innerHTML = this.cost;\n display();\n }\n }",
"function buyChoices() {\n var stockToPurchase = $(this).attr(\"buy-id\");\n\n console.log(\"in buyChoices(), buy-id: \" + stockToPurchase);\n // Shares you want to purchase:\n // <input type=\"number\" required=\"required\" name=\"nshares\" min=\"0\" value=\"0\"max=\"<shares * price < cashAvailbl>\" />\n }",
"static async getStoreInventory() {\n const storeInventory = storage.get(\"products\").value()\n return storeInventory\n }",
"function show_supplier_selector(product_id)\n{\n\n\n}",
"function expressCheckout(sender, productId) {\n\n apiClient.buyProduct(sender, productId)\n .then(function (response) {\n sessionStore.userData.get(sender).cart = response.id;\n\n apiClient.preCheckout(sender)\n .then(function (response) {\n let jsonResponse = JSON.parse(response);\n\n //Get default address\n let addresses = jsonResponse.shippingAddresses;\n for (let i = 0; i < addresses.length; i++) {\n if (addresses[i].selectedAsDefault)\n sessionStore.userData.get(sender).address = addresses[i].addressId;\n }\n\n //Get default card\n let cards = jsonResponse.cards;\n for (let i = 0; i < cards.length; i++) {\n if (cards[i].selectedAsDefault)\n sessionStore.userData.get(sender).card = cards[i].cardId;\n }\n\n //Do expresscheckout\n let cartId = sessionStore.userData.get(sender).cart;\n let cardId = sessionStore.userData.get(sender).card;\n let addressId = sessionStore.userData.get(sender).address;\n\n apiClient.expressCheckout(sender, cartId, cardId, addressId)\n .then(function (response) {\n console.log(response);\n sendMessage(sender, Templates.buildReceipt(sender, response));\n })\n .catch(errorCallback);\n })\n .catch(errorCallback);\n })\n .catch(errorCallback);\n}",
"function buy_half_shares() {\n // Makes a fair split of cash and shares with start money for initialization\n var half_cash = cash / 2.0;\n var half_shares = Math.round(half_cash / data[0]);\n cash -= half_shares * data[0];\n shares = half_shares;\n liveSend(get_trade_report('Buy', data[0], half_shares));\n update_portfolio();\n\n}",
"function productPage (itm, cst) {\n pref.product = {item: itm, cost: cst};\n storePref();\n window.location.href = '../pages/product.html';\n}",
"function buyMoonDrill(objectKey) {\n let moonDrillElem = shopUpgradesObj[objectKey];\n if (cheese >= moonDrillElem.price) {\n moonDrillElem.quantity++;\n cheese -= moonDrillElem.price;\n moonDrillElem.price += 100;\n multiplied += moonDrillElem.multiplier;\n drawInfoUpgrades();\n drawInfoWindow();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the path to the logo of the institution which ID is passed | institutionIcon(id) {
return 'static/institutions/' + id + '.png'
} | [
"function getImagePath(source){\n\tvar urlPath = url.parse(source).path;\n\tvar lastPath = _.last(urlPath.split(\"/\"));\n\tvar savePath = ORGINAL_IMAGE_PATH + lastPath;\n\treturn savePath;\n}",
"function OHIFLogo() {\n return (\n <div>\n {/* <Icon name=\"ohif-logo\" className=\"header-logo-image\" /> */}\n\n <img className=\"header-logo-image\" src={process.env.PUBLIC_URL + 'assets/uom.png'} />\n </div>\n );\n}",
"function imagePath(item_id, image_index, sold) {\n item_id = ITEM_TO_MASTER_ID_MAP[item_id];\n var path_str = \"\";\n var outlet_code = process.env.OUTLET_CODE\n if (fs.existsSync(source_folder + '/' + outlet_code + '/menu_items/' + item_id)) {\n path_str = source_folder + '/' + outlet_code + '/menu_items/' + item_id;\n } else {\n path_str = source_folder + '/' + item_id;\n }\n var sold_suffix = '';\n if (sold) {\n sold_suffix = '_sold';\n }\n path_str += '/{}{}.png'.format(image_index, sold_suffix);\n return path_str;\n}",
"function getSiteLogoBanda(b) {\n var banda = docXML.getElementsByTagName(\"banda\")[b].getElementsByTagName(\"links\")[0];\n return \"img/\" + banda.getElementsByTagName(\"link\")[2].getAttribute(\"logo\");\n}",
"function generateURL(id) {\n return `https://picsum.photos/id/${id}/400`;\n }",
"function IMNGetHeaderImage()\n{\n return \"imnhdr.gif\";\n}",
"function getQrImagePathToSave()\n{\n return path.join(__dirname,'../../../client/qr-images/');\n}",
"function getWeatherIcon(day){\n let src = './images/'\n switch(day.weather[0].main){\n case 'Thunderstorm':\n if (/rain|drizzle/.test(day.weather[0].description)){\n src += 'rain-thunder'\n }\n break; \n case 'Drizzle':\n case 'Rain': \n src += 'rain'\n break;\n case 'Snow': \n src += 'snow'\n break; \n case 'Clear': \n src += 'sunny'; \n break; \n case 'Clouds': \n if (day.clouds.all < 50) { \n src += 'part-sunny'\n }else{\n src += 'cloudy';\n }\n break;\n default: \n src += 'cloudy'; \n }\n src += '.svg'; \n return src;\n}",
"function overwriteLegalImage(region, locale) {\n\tif (location.pathname == '/sc2/' + region + '/buy-now/digital-deluxe' || location.pathname == '/sc2/' + region + '/buy-now/collectors-edition') {\n\t\t$('.legal-image').attr('src', '/sc2/static/local-common/images/legal/'+ locale + '/sc2-hots.png');\t\t\n\t}\n}",
"static smallImageUrlForRestaurant(restaurant) {\r\n return (`/img/small/${restaurant.photograph}.jpg`);\r\n }",
"function makeImageHtmlStringFromXMLObject(obj) {\n if ($(obj)[0] && $(obj)[0].data) {\n let data = $(obj)[0].data;\n data = data.replace(/\\\\/g, \"/\");\n let name = data.substr(data.lastIndexOf('/') + 1);\n let path = '<ac:image>' +\n '<ri:attachment ri:filename=\"' + name + '\" >' +\n '<ri:page ri:content-title=\"' + space.homepage.title + '\"/>' +\n '</ri:attachment>' +\n '</ac:image>';\n return path;\n };\n return \"\"\n }",
"static imageSrcUrlForRestaurant(restaurant) {\r\n return (`/img2/${restaurant.id}` + `-300_small.webp`);\r\n }",
"function get_img(i,f){var b,a=__CONF__.img_url+\"/img_new/{0}--{1}-{2}-1\",g=__CONF__.img_url+\"/img_src/{0}\",c=\"d96a3fdeaf68d3e8db170ad5\",d=\"43e2e6f41e3b3ebe22aa6560\",k=\"726a17bd880cff1fb375718c\",j=\"6ea1ff46aab3a42c975dd7ab\";i=i||\"0\";f=f||{};ObjectH.mix(f,{type:\"head\",w:30,h:30,sex:1});if(i!=\"0\"){if(f.type==\"src\"){b=g.format(i);}else{b=a.format(i,f.w,f.h);}}else{if(f.type==\"head\"){if(f.sex==1){b=a.format(c,f.w,f.h);}else{b=a.format(d,f.w,f.h);}}else{if(f.type==\"subject\"){b=a.format(k,f.w,f.h);}else{if(f.type==\"place\"){b=a.format(j,f.w,f.h);}else{b=a.format(\"0\",f.w,f.h);}}}}return b;}",
"saveProjectedImage() {\n let imgInf = this.image_config.image_info;\n\n if (typeof imgInf.projection !== PROJECTION.NORMAL) {\n let url =\n this.context.server + this.context.getPrefixedURI(IVIEWER) +\n '/save_projection/?image=' + imgInf.image_id +\n \"&projection=\" + imgInf.projection +\n \"&start=\" + imgInf.projection_opts.start +\n \"&end=\" + imgInf.projection_opts.end;\n if (this.context.initial_type !== INITIAL_TYPES.WELL &&\n typeof imgInf.parent_id === 'number')\n url += \"&dataset=\" + imgInf.parent_id;\n\n $.ajax({\n url: url,\n success: (resp) => {\n let msg = \"\";\n if (typeof resp.id === 'number') {\n let linkWebclient = this.context.server +\n this.context.getPrefixedURI(WEBCLIENT) +\n \"/?show=image-\" + resp.id;\n let linkIviewer = this.context.server +\n this.context.getPrefixedURI(IVIEWER) +\n \"/?images=\" + resp.id;\n if (this.context.initial_type !== INITIAL_TYPES.WELL &&\n typeof imgInf.parent_id === 'number')\n linkIviewer += \"&dataset=\" + imgInf.parent_id;\n msg =\n \"<a href='\" + linkWebclient + \"' target='_blank'>\" +\n \"Navigate to Image in Webclient</a><br>\" +\n \"<br><a href='\" + linkIviewer + \"' target='_blank'>\" +\n \"Open Image in iviewer</a>\";\n } else {\n msg = \"Failed to create projected image\";\n if (typeof resp.error === 'string')\n console.error(resp.error);\n }\n Ui.showModalMessage(msg, 'Close');\n }\n });\n }\n // hide context menu\n this.hideContextMenu();\n // prevent link click behavior\n return false;\n }",
"function logoArt() {\n console.log(\n logo({\n name: \"Employee DB\",\n font: \"Speed\",\n lineChars: 10,\n padding: 2,\n margin: 3,\n borderColor: \"grey\",\n logoColor: \"bold-green\",\n textColor: \"green\",\n })\n .emptyLine()\n .right(\"version 1.0.0\")\n .emptyLine()\n .center(longText)\n .render()\n );\n}",
"getExplorerURL(token_id) {\n if (!token_id) {\n return 'https://omniexplorer.info/';\n } else {\n return `https://omniexplorer.info/asset/${token_id}`;\n }\n }",
"function escogerImagen(objeto)\n{\n var imagen=\"\";\n\n if(objeto.estado == \"Clear\")\n {\n imagen=\"sol.png\";\n }\n else if(objeto.estado == \"Rain\")\n {\n imagen=\"lluvia.png\";\n }\n else if(objeto.estado == \"Clouds\")\n {\n imagen=\"nublado.png\";\n }\n else\n {\n imagen=\"nevado.png\";\n }\n\n return imagen;\n}",
"getUserLogo() {\n return !_.isEmpty(this.props.auth.getLogo())\n ? this.props.auth.getLogo()\n : defultuser;\n }",
"function pathStaticImageS3(id, baseFolder, subFolder, filename, width) {\n\tvar prefix = pathStaticS3(id, baseFolder, subFolder);\n\tvar type = baseFolder + '_' + subFolder;\n\tvar suffix = properImageName(type, filename, width);\n\treturn prefix + suffix;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
substitui o LNG trocando os %s por s se existirem | function LNG_s(str,_char,_recursiva)
{
var char = _char==undefined?'s':_char;
var recursiva = _recursiva==undefined?false:true;
var string = recursiva?str:LNG(str);
if(string.indexOf('%s')>0){
return LNG_s(string.replace('%s',char),char,true);
}else{
return string;
}
} | [
"function construct_phrase()\n{\n\tif (!arguments || arguments.length < 1 || !is_regexp)\n\t{\n\t\treturn false;\n\t}\n\n\tvar args = arguments;\n\tvar str = args[0];\n\tvar re;\n\n\tfor (var i = 1; i < args.length; i++)\n\t{\n\t\tre = new RegExp(\"%\" + i + \"\\\\$s\", \"gi\");\n\t\tstr = str.replace(re, args[i]);\n\t}\n\treturn str;\n}",
"function ReplaceParams() {\n var result = arguments[0];\n for (var iArg = 1; iArg < arguments.length; iArg++) { // Start at second arg (first arg is the pattern)\n var pattern = new RegExp('%' + iArg + '\\\\w*%');\n result = result.replace(pattern, arguments[iArg]);\n }\n return result;\n}",
"function printFlag(lingua) {\n\n var languages=[];\n languages.push(lingua);\n\n if (languages.includes(lingua)) {\n return '<img class=\"flag\" src=\"img/' + lingua + '.svg\"' +' '+'alt=\"'+ lingua + ' '+ 'flag\">';\n } else {\n return lingua;\n } \n }",
"phrase(phrase, ...insert) {\n for (let map of this.facet(EditorState.phrases))\n if (Object.prototype.hasOwnProperty.call(map, phrase)) {\n phrase = map[phrase]\n break\n }\n if (insert.length)\n phrase = phrase.replace(/\\$(\\$|\\d*)/g, (m, i) => {\n if (i == '$') return '$'\n let n = +(i || 1)\n return !n || n > insert.length ? m : insert[n - 1]\n })\n return phrase\n }",
"buildReplacement(character, length) {\n let replacement = '';\n for (let i = 0; i < length; i++) {\n replacement += character;\n }\n return replacement;\n }",
"function replace(format, params) {\n /*jslint unparam: true */\n return format.replace(/\\{([a-zA-Z]+)\\}/g, function (s, key) {\n return (typeof params[key] === 'undefined') ? '' : params[key];\n });\n }",
"function replaceString(oldS,newS,fullS) \r\n{ \r\n for (var i=0; i<fullS.length; i++) \r\n\r\n { \r\n\tif (fullS.substring(i,i+oldS.length) == oldS) \r\n\t\t{ fullS = fullS.substring(0,i)+newS+fullS.substring(i+oldS.length,fullS.length) } \r\n } \r\n\t\t return fullS\r\n}",
"function create_search_urlparam(search_text, srtype) {\n var param_URL = '';\n var initkey = 1;\n /* Get the common & Locale specific i.e., Fetching global map details to form the -> Search URL Params */\n for (var key in globalsearch_parameter_MAP) {\n if (globalsearch_parameter_MAP.hasOwnProperty(key)) {\n if (initkey == 1) {\n param_URL += key + eq + globalsearch_parameter_MAP[key];\n initkey = 0;\n } else {\n param_URL += amb + key + eq + globalsearch_parameter_MAP[key];\n }\n }\n }\n\n /* Search keyword getting passed */\n param_URL += amb + q + eq + search_text;\n return param_URL;\n }",
"function rd_RemoveMarkers_localize(strVar)\r\n\t{\r\n\t\treturn strVar[\"en\"];\r\n\t}",
"function printVardasPavardeKlase(name, lname, klase) { // lokali reiksme\n // var angelas = \"gabrielius\" lokali reiksme taip pat nes funkcijos viduje sukurtas\n console.log(name, lname, klase);\n}",
"function multigreeting(name, language) {\n language = language.toLowerCase() \n if (language === 'en') { return `Hello, ${name}!`}\n if (language === 'es') { return `¡Hola, ${name}!`}\n if (language === 'fr') { return `Bonjour, ${name}!`}\n if (language === 'eo') { return `Saluton, ${name}!`}\n }",
"function SysFmtStringInSet() {}",
"function loopyLighthouse (range, multiples, words){\n let start = range[0];\n let end = range[1];\n let firstMultiple = multiples[0];\n let secondMultiple = multiples[1];\n let firstWordReplace = words[0];\n let secondWordReplace = words[1];\n\n for(var i = start; i <= end; i++){\n if( i % firstMultiple === 0 && i % secondMultiple === 0){\n console.log(firstWordReplace+secondWordReplace);\n }\n else if ( i % firstMultiple === 0){\n console.log(firstWordReplace);\n }\n else if ( i % secondMultiple ===0){\n console.log(secondWordReplace);\n }\n else{\n console.log(i);\n }\n }\n}",
"function convertNorwegianSentence(number) {\n \treturn \"Norwegian Sentence\";\n }",
"function _replacement() {\n if (!arguments[0]) return \"\";\n var i = 1, j = 0, $pattern;\n // loop through the patterns\n while ($pattern = _patterns[j++]) {\n // do we have a result?\n if (arguments[i]) {\n var $replacement = $pattern[$REPLACEMENT];\n switch (typeof $replacement) {\n case \"function\": return $replacement(arguments, i);\n case \"number\": return arguments[$replacement + i];\n }\n var $delete = (arguments[i].indexOf(self.escapeChar) == -1) ? \"\" :\n \"\\x01\" + arguments[i] + \"\\x01\";\n return $delete + $replacement;\n // skip over references to sub-expressions\n } else i += $pattern[$LENGTH];\n }\n }",
"function formatRupiah(angka){\n var number_string = angka.toString(),\n sisa = number_string.length % 3,\n rupiah = number_string.substr(0, sisa),\n ribuan = number_string.substr(sisa).match(/\\d{3}/g);\n \n if (ribuan) {\n separator = sisa ? '.' : '';\n rupiah += separator + ribuan.join('.');\n }\n return rupiah\n}",
"function binden(A1, A1txt) {\r // A1 is een string\r // A1txt is een variable\r for (p=0; p < textID.length ; p++) {\r if(textID[p] == A1) {\r mijnComp.layer(p).property(\"Source Text\").setValue(A1txt);\r }\r }\r}",
"function owofied(sentence) {\n\tconst a = sentence.replace(/i/g, \"wi\");\n\tconst b = a.replace(/e/g, \"we\");\n\treturn b + \" owo\";\n}",
"function languageError() {\n $(\"#results\").append(\n `<p class=\"small\">Sorry, there's no Google translation for Dzongkha, Bhutan's principal language; \n but you may be able to use Nepali phrases!</p>\n \n <p class=\"small\">Nepali:</p>`\n );\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a new S3StorageConfig. Settings for AWS S3 archival storage. If not given, the archival video will be stored on the Tator website. | constructor() {
S3StorageConfig.initialize(this);
} | [
"function getS3Bucket(awsConfig) {\n // set the Amazon Cognito region\n AWS.config.region = awsConfig.awsCognitoRegion;\n // initialize the Credentials object with our parameters\n AWS.config.credentials = new AWS.CognitoIdentityCredentials({\n IdentityPoolId: awsConfig.cognitoIdentityPoolId\n });\n\n // get identity ID and update credentials\n AWS.config.credentials.get(function(err) {\n if (err) {\n console.log(\"Error: \" + err);\n return;\n } else {\n console.log(\"Cognito Identity Id: \" + AWS.config.credentials.identityId);\n AWS.config.update({\n credentials: AWS.config.credentials.identityId\n });\n }\n });\n\n // create the s3 bucket locally\n var s3 = new AWS.S3();\n var bucketName = awsConfig.awsBucketName;\n var bucket = new AWS.S3({\n params: {\n Bucket: bucketName\n }\n });\n\n return bucket;\n}",
"function Bucket(props) {\n return __assign({ Type: 'AWS::S3::Bucket' }, props);\n }",
"function createS3(){\n\treturn s3.createBucket({\n\t\tBucket: CONFIG.s3_image_bucket,\n\t}).promise().catch(err => {\n\t\tif (err.code !== \"BucketAlreadyOwnedByYou\") throw err\n\t})\n}",
"function create(accessKeyId, secretAccessKey) {\n config.accessKeyId = accessKeyId;\n config.secretAccessKey = secretAccessKey;\n\n AWS.config.update(config);\n AWS.config.region = window.AWS_EC2_REGION;\n AWS.config.apiVersions = {\n cloudwatch: '2010-08-01',\n sqs: '2012-11-05'\n };\n\n cloudWatch = new AWS.CloudWatch();\n autoScaling = new AWS.AutoScaling();\n sqs = new AWS.SQS();\n }",
"function ObjectStorageConfigNode(n) {\n // Create a RED node\n\t\tRED.nodes.createNode(this,n);\n\t\t\n\t\t// check the cfgtype\n\t\tthis.cfgtype = n.cfgtype;\n\n\t\tif (this.cfgtype == 'bluemix') {\n\t\t\t// get the VCAP_SERVICES\n\t\t\tvar vcapServices = require('./lib/vcap');\n\t\t\tconsole.log('VCAP: ', vcapServices);\n\t\t\tvar osCred = vcapServices.Object-Storage.credentials;\n\t\t\t\n\t\t\t// Get them\n\t\t\tthis.region = osCred.region;\n\t\t\tthis.userId = osCred.userId;\n\t\t\tthis.projectId = osCred.projectId;\n\t\t\tthis.userName = osCred.userName;\n\t\t\tthis.password = osCred.password;\t\t\n\t\t} else {\t\t\t\n\t\t\t// Store local copies of the node configuration (as defined in the .html)\n\t\t\tthis.region = n.region;\n\t\t\tthis.userId = n.userId;\n\t\t\tthis.projectId = n.projectId;\n\t\t\tthis.userName = n.userName;\n\t\t\tthis.password = n.password;\t\t\n\t\t}\n\t\tthis.name = n.name;\n\t}",
"async function configAWS(){\n aws.config.update({\n region: 'us-east-1', // Put your aws region here\n accessKeyId: config.AWSAccessKeyId,\n secretAccessKey: config.AWSSecretKey\n })\n}",
"function KnoxS3ClientProvider(_config) {\n\t_config = _config || config;\n\n\tthis._cache = LRUCache(_config.lru);\n\tthis._awsOptions = _config.aws;\n}",
"constructor(accessKey, secretKey, region, bucket, callback) {\n\t\tthis._s3 = null;\n\t\tthis._bucket = bucket;\n\t\tlet scriptTag = document.createElement('script');\n\t\tscriptTag.src = 'aws-sdk.min.js';\n\t\tscriptTag.onload = function () {\n\t\t\tAWS.config.update({\n\t\t\t\taccessKeyId: accessKey,\n\t\t\t\tsecretAccessKey: secretKey,\n\t\t\t\tregion: region\n\t\t\t});\n\t\t\tthis._s3 = new AWS.S3();\n\t\t\tcallback();\n\t\t}.bind(this);\n\t\tdocument.body.appendChild(scriptTag);\n\t}",
"function cfnStorageLensS3BucketDestinationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_S3BucketDestinationPropertyValidator(properties).assertSuccess();\n return {\n AccountId: cdk.stringToCloudFormation(properties.accountId),\n Arn: cdk.stringToCloudFormation(properties.arn),\n Encryption: cfnStorageLensEncryptionPropertyToCloudFormation(properties.encryption),\n Format: cdk.stringToCloudFormation(properties.format),\n OutputSchemaVersion: cdk.stringToCloudFormation(properties.outputSchemaVersion),\n Prefix: cdk.stringToCloudFormation(properties.prefix),\n };\n}",
"function assertS3(options) {\n\tconst s3 = options.s3;\n\tif (!s3 || typeof s3 !== 'object') {\n\t\tthrow new TypeError('\"s3\" object must be provided');\n\t}\n\tS3_METHODS.forEach(method => {\n\t\tif (typeof s3[method] !== 'function') {\n\t\t\tthrow new TypeError(`provided \"s3\" object missing \"${method}\" method`);\n\t\t}\n\t});\n\treturn options;\n}",
"function Configuration(props) {\n return __assign({ Type: 'AWS::AmazonMQ::Configuration' }, props);\n }",
"function uploadObjectToS3(params, typeOfFile, callback){\n\tvar bucketName = params.Bucket;\n\tvar keyName = params.Key;\n\t//Variable for Logging the messages to the file.\n\tvar logger = log.logger_rfq;\n\n\ts3.putObject(params, function(err, data) {\n\t\t if (err){\n\n\t\t\t resJson = {\t\n\t\t\t\t\t \"http_code\" : \"500\",\n\t\t\t\t\t\t\"message\" : \"Image Upload to s3 failed.\"\n\t\t\t\t};\n\t\t\tlogger.error(TAG + \" s3 Put Object tasks s3 failed.\" + JSON.stringify(err));\n\t\t\treturn callback(false, resJson);\n\t\t } \t \n\t\t else{\n\t\t\tvar params = {Bucket: bucketName, Key: keyName};\n\t\t\tvar urlWithData = s3.getSignedUrl('getObject', params);\n\t\t\tvar url = urlWithData.split(\"?\"); \n\t\t\t\n\t\t\tvar response = {\n\t\t\t\t\t\"typeOfFile\": typeOfFile,\n\t\t\t\t\t\"url\": url[0]\n\t\t\t\t};\t\n\t\t\treturn callback(false, response);\n\t\t }\t \n\t});\n}",
"function storeInS3(jsonObj, bucketName, fileName, fileType) {\n fileName = fileName + \" \" + getFormattedDate();\n // Serialize JSON object\n const jsonBody = EJSON.stringify(jsonObj);\n // Instantiate an S3 service client\n const s3Service = context.services.get('s3').s3('us-east-1');\n // Put the object in S3\n return s3Service.PutObject({\n 'Bucket': bucketName,\n 'Key': fileName,\n 'ContentType': fileType,\n 'Body': jsonBody\n })\n .then(putObjectOutput => {\n // putObjectOutput: {\n // ETag: <string>, // The object's S3 entity tag\n // }\n return [fileName, putObjectOutput];\n })\n .catch(err => {\n console.error(`Storing document in S3 failed with error: ${err}`);\n throw err;\n });\n}",
"_initializeDeploy(config) {\n\n // Configure and instantiate S3\n this._initializeS3(this.s3Config, (error) => {\n\n if (error) {\n this.log(error, 'ERROR');\n process.exit(0);\n }\n\n // Get last character of build path\n let lastCharOfPath = this.buildPath.slice(-1);\n\n /**\n * If buildpath does not have a trailing slash, add it.\n */\n if (lastCharOfPath !== '/') {\n this.buildPath += '/';\n }\n\n // Grab the files, then go to the _uploadFiles method\n glob(this.options.pathGlob, {cwd: this.buildPath}, (error, files) => {\n\n if (error) {\n this.log(error, 'ERROR');\n process.exit(0);\n }\n\n this.log('Deployer is now running.', 'SUCCESS');\n\n // Set the version variables for the files.\n this._setVersionVars((error, hash) => {\n\n if (error) {\n this.log(error, 'ERROR');\n process.exit(0);\n }\n\n this.log(`Setting deployment to version: ${this.version}`);\n\n // Upload files to S3\n this._uploadFiles(files, (done, fileNum) => {\n\n if (done) {\n\n // Change cloudfront root object\n this._cloudfrontInvalidateEntryHtml((error) => {\n\n if (error) {\n this.log(error, 'ERROR');\n process.exit(0);\n }\n\n this.log(`Deployment finished successfully. ${fileNum} files uploaded.`, 'SUCCESS');\n\n // Check for slack notifs:\n this._configureSlack(config.options.slack, (success) => {\n\n if (success) {\n this.log('Slack has been notified.', 'SUCCESS');\n }\n });\n });\n }\n });\n });\n });\n });\n }",
"constructor() { \n \n UpdateExportSettingsS3Response.initialize(this);\n }",
"get s3RoomImageBucket() {\n return `${this.envName}-room-images`\n }",
"getMediaplayerSettings() {\n return {\n \n stream: { src: App.getPath(`DStv_Promo_(The_Greatest_Show).mp4`) }\n }\n }",
"constructor(scope, id, props) {\n super(scope, id, { type: CfnStorageLens.CFN_RESOURCE_TYPE_NAME, properties: props });\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_s3_CfnStorageLensProps(props);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, CfnStorageLens);\n }\n throw error;\n }\n cdk.requireProperty(props, 'storageLensConfiguration', this);\n this.attrStorageLensConfigurationStorageLensArn = cdk.Token.asString(this.getAtt('StorageLensConfiguration.StorageLensArn', cdk.ResolutionTypeHint.STRING));\n this.storageLensConfiguration = props.storageLensConfiguration;\n this.tags = new cdk.TagManager(cdk.TagType.STANDARD, \"AWS::S3::StorageLens\", props.tags, { tagPropertyName: 'tags' });\n }",
"function BucketPolicy(props) {\n return __assign({ Type: 'AWS::S3::BucketPolicy' }, props);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loop will print 5 times the number 5 because the lexical scope of timeout, access the same i variable | function loop() {
for (var i = 0; i < 5; i++) {
setTimeout(() => {
console.log(i);
}, i * 1000);
}
} | [
"function counter2() {\n for (let i = 0; i < 5; i++) {\n setTimeout(() => {\n console.log(i);\n }, i * 1000);\n }\n}",
"function loopAndPrintWithIFFE() {\n var i;\n var count = 4;\n for (i = 0; i < count; i++) {\n (function(index) {\n setTimeout(function() {\n console.log('loopAndPrintWithIFFE - setTimeout %o', index);\n }, 1000);\n }(i));\n }\n}",
"function start2() {\n for(var i = 0; i < 5; i++) {\n console.log(i);\n }\n\n console.log(i);\n}",
"function printTimeout(str, n) {\r\n const timeInMs = n * 1000;\r\n setTimeout(function() { console.log(str); }, timeInMs);\r\n}",
"function simulate() {\n for (let i = 1; i <= 5; i++) {\n test(i)\n }\n}",
"function five(word) {\n i = 0;\n while (i < 5) {\n console.log(word);\n i++\n }\n}",
"function runForLoop(text, delay) {\n // code goes here\n console.log('runForLoop is called', text, delay);\n for (let i = 0; i < 4; i++) {\n setTimeout(addParagraph, delay * i, text);\n };\n}",
"function repeat(phrase, x) {\n for (let i = 0; i < x ; i++) {\n console.log(phrase);\n }\n\n}",
"function answerTimer() {\n timeoutId = setTimeout(display, 5000);\n clearInterval(intervalId);\n count = 30;\n}",
"function times(num, callback) {\n for (let i = 0; i < num; i++) {\n callback(i)\n }\n}",
"function gamePatterReplay() {\n for (var i = 0; i < gamePattern.length; i++) {\n (function(i) {\n setTimeout(function() {\n $('#' + gamePattern[i]).fadeOut(100).fadeIn(100);\n console.log(gamePattern[i]);\n }, 500 * i);\n })(i);\n }\n setTimeout(nextSequence, 500 * i);\n}",
"function countdownFinal(param1, param2, param3, param4) {\n var i = param3;\n while(i > param2) {\n if(i == param4) {\n i--;\n continue;\n }\n if(i%param1 == 0) {\n console.log(i);\n }\n i--;\n }\n}",
"function repeat(fn, n) {\nfor(let i=0; i<n; i++) {\n\tfn();\n}\n\n}",
"function doWhileLoop(num) {\n let i= 0;\n function incrementVariable() {\n i = i + 1;\n return i;\n }\n do {\n console.log(\"I run once regardless.\");\n } while (incrementVariable() < num);\n}",
"async function sp_timeout(N) {\n await new Promise(function(resolve, reject) {\n setTimeout(resolve, N);\n });\n}",
"getTimeout(){cov_50nz68pmo.f[2]++;cov_50nz68pmo.s[6]++;return this.timeout;}",
"function loop(limit) {\n let printedMessage = '';\n // loop until limit\n for (let currentNumber = 1; currentNumber <= limit; currentNumber++) {\n // loop until currentNumber\n for (let printedNumber = 1; printedNumber <= currentNumber; printedNumber++) {\n printedMessage += currentNumber;\n }\n // add return space for each completed row\n if (currentNumber !== limit) {\n printedMessage += '\\n';\n }\n }\n console.log(printedMessage);\n}",
"function repeatPhrase(phrase, n) {\n\tfor (i = 0; i < n; i++) {\n\t console.log(phrase);\n\t}\n}",
"function playFives(num)\n{\n for(var i = 1; i <= num; i++)\n {\n var random = rollOne();\n if(random === 5)\n {\n console.log(random + \" That's good luck\");\n }\n else\n {\n console.log(random);\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves game state to the history by serialising cards | function saveState() {
const reserveHiddenCards = reservePile.hiddenStack.map(card => serialiseCard(card));
const reserveCards = reservePile.stack.map(card => serialiseCard(card));
const stacksCards = stacks.map(stack => stack.stack.map(card => serialiseCard(card)));
const pilesCards = piles.map(pile => pile.stack.map(card => serialiseCard(card)));
const reduceCardArray = array => array.length ? array.reduce((result, card) => result + card) : '';
// 0xF (\u000F) -> major split character
// 0x1F (\u001F) -> minor split character
const state = [
reduceCardArray(reserveHiddenCards),
reduceCardArray(reserveCards),
stacksCards.map(stack => reduceCardArray(stack)).join('\u001F'),
pilesCards.map(pile => reduceCardArray(pile)).join('\u001F'),
].join('\u000F');
stateHistory.push(state);
} | [
"function saveState() {\n\tvar stackMaxPlusOne = 4;\n\tif(gameType == 'creator') {\n\t\tstackMaxPlusOne = 11;\n\t}\n\tstate = {\n\t\t'level': level,\n\t\t'dimensions': level.dimensions,\n\t\t'row': row,\n\t\t'col': col,\n\t\t'moves': moves,\n\t\t'tiles': tiles,\n\t\t'curColumnsRight': curColumnsRight,\n\t\t'curColumnsLeft': curColumnsLeft,\n\t\t'curRowsTop': curRowsTop,\n\t\t'curRowsBottom': curRowsBottom,\n\t\t'flippedColumnsRight': flippedColumnsRight,\n\t\t'flippedColumnsLeft': flippedColumnsLeft,\n\t\t'flippedRowsTop': flippedRowsTop,\n\t\t'flippedRowsBottom': flippedRowsBottom,\n\t\t'actionStack': actionStack.toString(),\n\t\t'matrix': []\n\t};\n\tfor(var i = 0; i < level.dimensions; i++) {\n\t\tstate.matrix[i] = matrix[i].slice();\n\t}\n\t// add as first element of the stack\n\t// note the first element of the stack matches the current state\n\tundoStack.unshift(state);\n\tif(undoStack.length > stackMaxPlusOne) {\n\t\tundoStack.splice(stackMaxPlusOne, 1);\n\t}\n}",
"function saveGame() {\n pauseGame();\n let cardsData = '';\n $('.card').each(function() {\n cardsData += $(this).attr('class') + '@' + $(this).html() + '@@';\n });\n localStorage.setItem('cardsData', cardsData);\n localStorage.setItem('clockState', clockState);\n localStorage.setItem('playDuration', playDuration);\n localStorage.setItem('moves', moves);\n resumeGame();\n}",
"function storeDeckState(){\n var cardLearnerState = cardLearner.dataDump();\n $.cookie(\"cardLearner\", JSON.stringify(cardLearnerState), { expires:10 });\n}",
"function saveState () {\n stack.splice(stackPointer);\n var cs = slots.slice(0);\n var ci =[];\n cs.forEach(function(s) {\n ci.push(s.slice(0));\n });\n stack[stackPointer] = [cs, ci];\n }",
"saveCards(state, payload) {\n if (payload.cards !== undefined) {\n localStorage.setItem(\"cards\", JSON.stringify(payload.cards));\n }\n }",
"function saveCurrentGame() {\n console.log(\"saving game state...\");\n vm.games.$save(vm.currentGame);\n }",
"save() {\n console.log(state)\n localStorage.setItem('state', JSON.stringify(state))\n }",
"function saveGame() {\r\n\tvar sNewCellID;\r\n\r\n\t// save current board state\r\n\tfor (var x = 0; x < 9; x++) {\r\n\t\tfor (var y = 0; y < 9; y++) {\r\n\t\t\tsNewCellID = cord2ID(x, y);\r\n\r\n\t\t\twindow.localStorage.setItem(sNewCellID, JSON\r\n\t\t\t\t\t.stringify(aCellByIDs[sNewCellID]));\r\n\t\t}\r\n\t}\r\n\r\n\t// save next balls\r\n\tfor (var i = 0; i < 3; i++) {\r\n\t\twindow.localStorage.setItem(\"nextBall\" + i, JSON\r\n\t\t\t\t.stringify(aNextBalls[i]));\r\n\t}\r\n\r\n\t// save total score\r\n\twindow.localStorage.setItem(\"nTotalScore\", nTotalScore);\r\n\r\n\t// save game dificulty\r\n\twindow.localStorage.setItem(\"nMaxColor\", oGameSettings.nMaxColor);\r\n}",
"saveState() {\n\t\tlocalStorage.setItem(\"state\", JSON.stringify(_state));\n\t}",
"function savetosaveCard () {\n step++\n if (step < saveCard.length) { \n saveCard.length = step;\n console.log(`reset Savecard ${step} < ${saveCard.length}`)\n }\n saveCard.push(canvasReal.toDataURL());\n console.log(`this saved to saveCard`);\n}",
"function saveBoard() {\n window.localStorage.setItem(\"board\", board.toJSON());\n}",
"function GameState (state) {\n // Storage class that is passed to all players at end of turn\n this.Players = [] ;//Ordered array of players in game\n this.Name = \"\" ;// Game name\n this.id = \"\";\n this.Started = false\n this.GameOwner = 0; //Index into players array of player that owns game\n this.CurrentPlayer = 0; //Index into players array of current player\n // History is array of TurnStates keeping a detailed history of each turn.\n // Note first TurnState is only interesting in terms of initial bag state and each\n //player's tray state\n this.History = [];\n if (state) {\n this.Players = state.Players\n this.Name = state.Name\n this.id = state.id\n this.Started = state.Started \n if (state.GameOwner) this.GameOwner = state.GameOwner;\n if (state.CurrentPlayer) this.CurrentPlayer = state.CurrentPlayer;\n if (state.History ){\n var history = []\n for(var i=0;i<state.History.length;i++){\n var bag = new Bag(true, state.History[i].Bag.letters)\n var boardState = new BoardState(state.History[i].BoardState.letters)\n var turn = null;\n if (state.History[i].Turn) {\n turn = new Turn(state.History[i].Turn.Type, state.History[i].Turn.LettersIn, state.History[i].Turn.LettersOut, \n state.History[i].Turn.TurnNumber, state.History[i].Turn.Player, state.History[i].Turn.NextPlayer)\n }\n var trayStates = [];\n for(var j=0;j<state.History[i].TrayStates.length;j++){ \n trayStates.push( new TrayState(state.History[i].TrayStates[j].player, state.History[i].TrayStates[j].letters, state.History[i].TrayStates[j].score));\n }\n history.push( new TurnState(bag, boardState, trayStates, state.History[i].End, turn))\n }\n this.History = history ;\n }\n }\n this.GetNextPlayer = function() {\n var next = this.CurrentPlayer +1;\n if (next >= this.Players.length){\n next =0;\n }\n return next;\n }\n this.GetPlayers = function(){\n return this.Players;\n }\n this.GetCurrentPlayerIndex = function(){\n return this.CurrentPlayer\n }\n this.GetNumberOfPlayers = function(){\n return this.Players.length;\n }\n this.IsPlayer = function(playerName){\n for (var i=0;i<Players.length;i++){\n if (playerName == Players[i]) return true;\n }\n return false;\n }\n this.GetBoardState = function(){\n var boardState = null;\n var lastTurn = this.GetLastTurn();\n if (lastTurn){\n boardState = lastTurn.GetBoardState();\n }\n return boardState;\n }\n this.CloneLastTurnState =function(){\n var last = this.GetLastTurnState();\n return last.Clone();\n }\n this.GetLastTurnState = function(){\n var lastTurnState = null;\n if (this.History.length >0 ) {\n lastTurnState = this.History[this.History.length-1]\n }\n return lastTurnState;\n }\n this.HasGameEnded = function(){\n var ended = false;\n var lastTurnState = this.GetLastTurnState();\n if (lastTurnState){\n ended = lastTurnState.End;\n }\n return ended;\n }\n \n this.GetLastTurn = function(){\n //Actually only gets last proper turn because there is no turn object in first turnState\n var lastTurn = null;\n if (this.History.length >=1 ) {\n lastTurn = this.History[this.History.length-1].Turn;\n }\n return lastTurn;\n }\n this.GetMyTrayState =function (playerName) {\n var trayState = null;\n if (this.History.length >=1 ) {\n var trays = this.History[this.History.length-1].GetTrayStates();\n if (trays) {\n for (var i=0;i<trays.length;i++){\n if (trays[i].GetPlayer() == playerName){\n trayState = trays[i]\n break;\n }\n }\n }\n }\n return trayState;\n }\n this.AddTurnState = function(turnState){\n this.History.push(turnState);\n }\n this.HasScores = function(){\n return (this.History.length > 0);\n }\n this.GetBagSize = function(){\n var count = 0;\n if (this.History.length >=1 )\n {\n count = this.History[this.History.length-1].GetBagSize();\n }\n return count;\n }\n this.GetPlayerScore = function (playerName){\n var lastTurnState = this.History[this.History.length-1];\n return lastTurnState.GetPlayerScore(playerName);\n }\n this.GetGameOwner = function(){\n return this.Players[ this.GameOwner];\n }\n this.RemoveLastState = function(){\n var lastTurnState = this.History.pop();\n var newLastTurn = this.GetLastTurn();\n if (newLastTurn){\n this.CurrentPlayer = newLastTurn.NextPlayer;\n }else{\n //This is same code at start game first player is first tray state\n this.SetCurrentPlayerByName(lastTurnState.GetTrayState(0).GetPlayer());\n }\n }\n this.SetCurrentPlayerByName = function(playerName){\n this.CurrentPlayer = 0\n for (var i=0;i<this.Players.length;i++){\n if (this.Players[i] == playerName){\n this.CurrentPlayer = i;\n break;\n }\n }\n }\n this.SetCurrentPlayer = function(index){\n this.CurrentPlayer = index; \n }\n this.GetCurrentPlayer = function(){\n var player = \"\";\n if (this.CurrentPlayer <= (this.Players.length -1) ){\n player = this.Players[this.CurrentPlayer];\n }\n return player\n }\n}",
"function saveUndoState()\n{\n\t// $.extend is used to deep copy the array because JIT doesn't >:|\n\tundoStates.push({ graph: $.extend(true, [], rgraph.toJSON('graph')), root: rgraph.root.id});\n\tif(undoStates.length > MAX_UNDO)\n\t\tundoStates.shift();\n\t$('#undo').removeAttr('disabled');\n}",
"function saveState(){\n writeToFile(userFile, users);\n writeToFile(campusFile, campus);\n}",
"save() {\n undo.push();\n store.content.fromJSON(this.getValue());\n super.save();\n }",
"function savGamNumSess(num){\r\nsessionStorage.setItem(\"gameNum\", JSON.stringify(num));\r\n}",
"Save()\n {\n\n // Check if the board is not alrady in the array of boards\n if(AppState.GetBoards().find(x => x.id == this.id) == undefined)\n {\n AppState.GetBoards().push(this)\n AppState.Save()\n return;\n }\n\n AppState.GetBoards()[this.id] = this;\n AppState.Save()\n\n }",
"function saveGuessHistory(guess) {\n\tguesses.push(guess)\n}",
"function store(player){\n\tvar goods = player.bag;\n\tvar index,card;\n\tfor(var good in goods){\n\t\tindex = player.hand.find(good);\n\t\tif(index){\n\t\t\tcard=player.hand.splice(index,1)[0];\n\t\t\tplayer.bag.push(card);\n\t\t}\n\t}\n\tplayer.action='wait';\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set up SignalR _client | function setupClient() {
_client = new signalR.client(
settingsHelper.settings.hubUri + '/signalR',
['integrationHub'],
10, //optional: retry timeout in seconds (default: 10)
true
);
// Wire up signalR events
/* istanbul ignore next */
_client.serviceHandlers = {
bound: function () {
log("Connection: " + "bound".yellow);
},
connectFailed: function (error) {
log("Connection: " + "Connect Failed: ".red + error.red);
let faultDescription = "Connect failed from mSB.com. " + error;
let faultCode = '00098';
trackException(faultCode, faultDescription);
microServiceBusNode.ReportEvent(faultDescription);
settingsHelper.isOffline = true;
},
connected: function (connection) {
let connectTime = new Date().getTime();
if (_lastConnectedTime) {
if (connectTime - _lastConnectedTime < 3000) {
log("Reconnection loop detected. Restarting");
microServiceBusNode.ReportEvent("Reconnection loop detected");
restart();
return;
}
}
_lastConnectedTime = connectTime;
log("Connection: " + "Connected".green);
if (!settingsHelper.settings.policies) {
settingsHelper.settings.policies = {
"disconnectPolicy": {
"heartbeatTimeout": 120,
"missedHearbeatLimit": 3,
"disconnectedAction": "RESTART",
"reconnectedAction": "NOTHING",
"offlineMode": true
}
};
}
_signInState = "INPROCESS";
microServiceBusNode.settingsHelper = settingsHelper;
if (settingsHelper.isOffline) { // We are recovering from offline mode
log('Connection: *******************************************'.bgGreen.white);
log('Connection: RECOVERED FROM OFFLINE MODE...'.bgGreen.white);
log('Connection: *******************************************'.bgGreen.white);
settingsHelper.isOffline = false;
_missedHeartBeats = 0;
_lastHeartBeatReceived = true;
switch (settingsHelper.settings.policies.disconnectPolicy.reconnectedAction) {
case "UPDATE":
microServiceBusNode.Stop(function () {
microServiceBusNode.SignIn(_existingNodeName, _temporaryVerificationCode, _useMacAddress, false);
});
break;
case "NOTHING":
microServiceBusNode.SignIn(_existingNodeName, _temporaryVerificationCode, _useMacAddress, true);
_signInState = "SIGNEDIN";
default:
break;
}
}
else {
microServiceBusNode.SignIn(_existingNodeName, _temporaryVerificationCode, _useMacAddress, null, _useAssert);
}
microServiceBusNode.ReportEvent("Connected to mSB.com");
startVulnerabilitiesScan();
},
disconnected: function () {
log("Connection: " + "Disconnected".yellow);
let faultDescription = 'Node has been disconnected.';
let faultCode = '00098';
trackException(faultCode, faultDescription);
microServiceBusNode.ReportEvent("Disconnected from mSB.com");
settingsHelper.isOffline = true;
},
onerror: function (error) {
log("Connection: " + "Error: ".red, error);
if (!error) {
return;
}
let faultDescription = error;
let faultCode = '00097';
trackException(faultCode, faultDescription);
try {
if (error.endsWith("does not exist for the organization")) {
if (self.onStarted)
self.onStarted(0, 1);
}
}
catch (e) { }
},
onUnauthorized: function (error) {
log("Connection: " + "Unauthorized: ".red, error);
},
messageReceived: function (message) {
//console.log("Connection: " + "messageReceived: ".yellow + message.utf8Data);
},
bindingError: function (error) {
log("Connection: " + "Binding Error: ".red + error);
// Check if on offline mode
if ((error.code === "ECONNREFUSED" || error.code === "EACCES" || error.code === "ENOTFOUND") &&
!settingsHelper.isOffline &&
settingsHelper.settings.offlineSettings) {
log('*******************************************'.bgRed.white);
log('SIGN IN OFFLINE...'.bgRed.white);
log('*******************************************'.bgRed.white);
settingsHelper.isOffline = true;
microServiceBusNode.SignInComplete(settingsHelper.settings.offlineSettings);
}
startHeartBeat();
},
connectionLost: function (error) { // This event is forced by server
log("Connection: " + "Connection Lost".red);
},
reconnected: function (connection) {
// This feels like it would be a good idea, but I have't got around to test it...
// _client.invoke('integrationHub', 'reconnected', settingsHelper.settings.id);
log("Connection: " + "Reconnected ".green);
},
reconnecting: function (retry /* { inital: true/false, count: 0} */) {
log("Connection: " + "Retrying to connect (".yellow + retry.count + ")".yellow);
return true;
}
};
// Wire up signalR inbound events handlers
_client.on('integrationHub', 'errorMessage', function (message, errorCode) {
OnErrorMessage(message, errorCode);
});
_client.on('integrationHub', 'ping', function (message) {
OnPing(message);
});
_client.on('integrationHub', 'getEndpoints', function (message) {
OnGetEndpoints(message);
});
_client.on('integrationHub', 'updateItinerary', function (updatedItinerary) {
OnUpdateItinerary(updatedItinerary);
});
_client.on('integrationHub', 'changeState', function (state) {
OnChangeState(state);
});
_client.on('integrationHub', 'changeDebug', function (debug) {
OnChangeDebug(debug);
});
_client.on('integrationHub', 'changeTracking', function (enableTracking) {
OnChangeTracking(enableTracking);
});
_client.on('integrationHub', 'sendMessage', function (message, destination) {
OnSendMessage(message, destination);
});
_client.on('integrationHub', 'signInMessage', function (response) {
OnSignInMessage(response);
});
_client.on('integrationHub', 'nodeCreated', function (nodeData) {
OnNodeCreated(nodeData);
});
_client.on('integrationHub', 'heartBeat', function (id) {
log("Connection: Heartbeat received".grey);
_missedHeartBeats = 0;
_lastHeartBeatReceived = true;
});
_client.on('integrationHub', 'forceUpdate', function () {
log("forceUpdate".red);
restart();
});
_client.on('integrationHub', 'restart', function () {
log("restart".red);
restart();
});
_client.on('integrationHub', 'reboot', function () {
log("reboot".red);
reboot();
});
_client.on('integrationHub', 'shutdown', function () {
log("shutdown".red);
shutdown();
});
_client.on('integrationHub', 'refreshSnap', function (snap, mode, connId) {
log("Refreshing snap ".yellow + snap.gray);
log(`devmode = ${snap.indexOf("microservicebus") === 0}`);
OnRefreshSnap(snap, mode, connId);
});
_client.on('integrationHub', 'reset', function (id) {
OnReset(id);
});
_client.on('integrationHub', 'resetKeepEnvironment', function (id) {
OnResetKeepEnvironment(id);
});
_client.on('integrationHub', 'updateFlowState', function (itineraryId, environment, enabled) {
OnUpdateFlowState(itineraryId, environment, enabled);
});
_client.on('integrationHub', 'enableDebug', function (connId) {
OnEnableDebug(connId);
});
_client.on('integrationHub', 'stopDebug', function (connId) {
OnStopDebug();
});
_client.on('integrationHub', 'reportState', function (id) {
OnReportState(id);
});
_client.on('integrationHub', 'uploadSyslogs', function (connectionId, fileName, account, accountKey) {
OnUploadSyslogs(connectionId, fileName, account, accountKey);
});
_client.on('integrationHub', 'resendHistory', function (req) {
OnResendHistory(req);
});
_client.on('integrationHub', 'requestHistory', function (req) {
OnRequestHistory(req);
});
_client.on('integrationHub', 'transferToPrivate', function (req) {
OnTransferToPrivate(req);
});
_client.on('integrationHub', 'updatedToken', function (token) {
OnUpdatedToken(token);
});
_client.on('integrationHub', 'updateFirmware', function (force, connid) {
OnUpdateFirmware(force, connid);
});
_client.on('integrationHub', 'grantAccess', function () {
OnGrantAccess();
});
_client.on('integrationHub', 'runTest', function (testDescription) {
OnRunTest(testDescription);
});
_client.on('integrationHub', 'pingNodeTest', function (connid) {
OnPingNodeTest(connid);
});
_client.on('integrationHub', 'updatePolicies', function (policies) {
OnUpdatePolicies(policies);
});
_client.on('integrationHub', 'setBootPartition', function (partition, connid) {
OnSetBootPartition(partition, connid);
});
_client.on('integrationHub', 'executeScript', function (patchScript, connid) {
OnExecuteScript(patchScript, connid);
});
} | [
"function SetupClient ()\n{\n client.registry.registerDefaults ();\n client.registry.registerGroups ([\n [\"bot\", \"Bot\"],\n [\"user\", \"User\"],\n [\"admin\", \"Admin\"],\n [\"social\", \"Social\"],\n [\"search\", \"Search\"],\n [\"random\", \"Random\"],\n [\"utility\", \"Utility\"],\n [\"reaction\", \"Reaction\"],\n [\"decision\", \"Decision\"],\n ]);\n client.registry.registerCommandsIn (__dirname + \"/Commands\");\n\n client.commandPrefix = config.Prefix;\n\n LogClient ();\n}",
"_buildClient() {\n var metadata = (0, _frames.encodeFrame)({\n type: _frames.FrameTypes.DESTINATION_SETUP,\n majorVersion: null,\n minorVersion: null,\n group: this._config.setup.group,\n tags: this._tags,\n accessKey: this._accessKey,\n accessToken: this._accessToken,\n connectionId: this._connectionId,\n additionalFlags: this._additionalFlags\n });\n var transport = this._config.transport.connection !== undefined ? this._config.transport.connection : new _rsocketWebsocketClient.default({\n url: this._config.transport.url ? this._config.transport.url : 'ws://',\n wsCreator: this._config.transport.wsCreator\n }, _rsocketCore.BufferEncoders);\n var responder = this._config.responder || new _rsocket.UnwrappingRSocket(this._requestHandler);\n var finalConfig = {\n setup: {\n keepAlive: this._keepAlive,\n lifetime: this._lifetime,\n metadata,\n connectionId: this._connectionId,\n additionalFlags: this._additionalFlags\n },\n transport,\n responder\n };\n\n if (this._config.serializers !== undefined) {\n finalConfig.serializers = this._config.serializers;\n }\n\n this._client = new _FlowableRpcClient.default(finalConfig);\n }",
"initializeOnConnection() {\n this.webSocketServer.on('connection', (clientWebSocket) => {\n let client = this.getClient(clientWebSocket);\n this.initializeOnMessage(client);\n this.sendHandShakeRequestCommand(client);\n });\n }",
"function MessageHub(HubProxy) {\n var messageHub = new HubProxy('Chat', { connectionPath: '/signalr', loggingEnabled: true });\n messageHub.start();\n return messageHub; // return MessageHub instance\n }",
"async componentDidMount() {\n // create the server chooser\n const chooser = new DefaultServerChooser();\n chooser.add(`ws://${HOST}:${PORT}/amps/json`);\n\n // create the AMPS HA client object\n const client = new Client('view-server');\n client.serverChooser(chooser);\n client.subscriptionManager(new DefaultSubscriptionManager());\n\n // now we can establish connection \n await client.connect();\n\n // update the state\n this.setState({ client });\n }",
"function buildClient(){\n if(!client){\n\n const {acmEndpoint, kasEndpoint, easEndpoint} = getEndpointsByEnvironment();\n const authType = getAuthType();\n const provider = chooseAuthProviderByType({type: authType, redirectUrl: ''});\n\n client = new Virtru.Client.VirtruClient({\n acmEndpoint, kasEndpoint, easEndpoint,\n authProvider: provider\n });\n }\n\n return client;\n}",
"function MockCuriousClient() { }",
"data () : DataClient {\n if (!this.announcement) {\n throw new Error(\"No handler configured, call open()!\")\n }\n\n return new DataClient(this.appID, this.appAccessKey, this.announcement.mqttAddress)\n }",
"function initClient() {\n \n const keys = {\n // fill\n };\n\n return new Gdax.AuthenticatedClient(\n keys[\"API-key\"],\n keys[\"API-secret\"],\n keys[\"Passphrase\"],\n keys[\"Exchange-url\"]\n );\n}",
"setupWatcherBus() {\n logger.debug('Setting watcher bus up');\n this.watcherBus = new WatcherBus(this.bot);\n }",
"_initSwaggerClient() {\n LOG.debug('Initializing Client with Swagger URL: ', this._swaggerUrl);\n\n const CLIENT = new SwaggerClient({\n url: this._swaggerUrl,\n usePromise: true,\n });\n\n CLIENT.then((client) => {\n this.client = client;\n this._clientReady();\n LOG.debug('SwaggerClient successfully initialized.');\n });\n\n CLIENT.catch((error) => {\n LOG.error('Error initializing SwaggerClient: ', error);\n });\n }",
"function initializeOpcuaClient(){\n client = new OPCUAClient({keepSessionAlive:true});\n client.connect(\"opc.tcp://\" + os.hostname() + \":\" + port, onClientConnected);\n}",
"function onConnect() {\n console.log(\"onConnect\");\n client.subscribe(\"diceRolls\");\n}",
"constructor() {\n //const LATTICE_NUM = globalThis.latticeNum;\n const LATTICE_PORT = 31415;\n const LATTICE_URL = `https://sustain.cs.colostate.edu:${LATTICE_PORT}`;\n this.service = new SustainClient(LATTICE_URL, \"sustainServer\");\n this.modelService = new JsonProxyClient(LATTICE_URL, \"sustainServer\");\n return this;\n }",
"function ensureSubscribed() {\n if (!client) {\n client = getClient()\n }\n\n if (!subscribed) {\n subscribed = true\n client.on('message', (channel, message) => {\n const funcs = handlers[channel] || []\n for (const func of funcs) {\n func(channel, message)\n }\n })\n }\n}",
"constructor(server, id, setup) {\n this.id = id;\n this.setup = setup;\n this._config = server.config;\n this._notify = server.notify;\n\n this._connectPromise = null;\n }",
"_autoSyncClient() {\n const {\n serviceWorker,\n } = navigator;\n\n const updateLog = debug.scope('update');\n\n /* istanbul ignore next: won't occur in tests */\n serviceWorker.addEventListener('controllerchange', async () => {\n try {\n const registration = await connect(true);\n this.controller = registration.active;\n\n updateLog.color('crimson')\n .warn('mocker updated, reload your requests to take effect');\n } catch (error) {\n updateLog.error('connecting to new service worker failed', error);\n }\n });\n }",
"async function setupGateway() {\n \n let connectionProfile = yaml.safeLoad(fs.readFileSync(CONNECTION_PROFILE_PATH, 'utf8'));\n const wallet = new FileSystemWallet('./wallet')\n let connectionOptions = {\n identity: USER_ID,\n wallet: wallet,\n discovery: { enabled: false, asLocalhost: true }\n , eventHandlerOptions: {\n strategy: null\n } \n }\n await gateway.connect(connectionProfile, connectionOptions)\n}",
"function PulsePublisher(client){\n // faye client\n this.client = client;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the bundledNativeModules.json for a given SDK version: Tries to fetch the data from the /sdks/:sdkVersion/nativemodules API endpoint. If the data is missing on the server (it can happen for SDKs that are yet fully released) or there's a downtime, reads the local .json file from the "expo" package. For UNVERSIONED, returns the local .json file contents. | async function getBundledNativeModulesAsync(projectRoot, sdkVersion) {
if (sdkVersion === 'UNVERSIONED') {
return await getBundledNativeModulesFromExpoPackageAsync(projectRoot);
} else {
try {
return await getBundledNativeModulesFromApiAsync(sdkVersion);
} catch {
_log().default.warn(`Unable to reach Expo servers. Falling back to using the cached dependency map (${_chalk().default.bold('bundledNativeModules.json')}) from the package "${_chalk().default.bold`expo`}" installed in your project.`);
return await getBundledNativeModulesFromExpoPackageAsync(projectRoot);
}
}
} | [
"async function getBundledNativeModulesFromExpoPackageAsync(projectRoot) {\n const bundledNativeModulesPath = _resolveFrom().default.silent(projectRoot, 'expo/bundledNativeModules.json');\n\n if (!bundledNativeModulesPath) {\n _log().default.addNewLineIfNone();\n\n throw new (_CommandError().default)(`The dependency map ${_chalk().default.bold(`expo/bundledNativeModules.json`)} cannot be found, please ensure you have the package \"${_chalk().default.bold`expo`}\" installed in your project.\\n`);\n }\n\n return await _jsonFile().default.readAsync(bundledNativeModulesPath);\n}",
"async function getNewestSdkVersionSupportedAsync(context) {\n if (context.type === 'user') {\n return context.data.exp.sdkVersion;\n } else if (context.type === 'service') {\n // when running in universe or on a turtle machine,\n // we care about what sdk version is actually present in this working copy.\n // this might not be the same thing deployed to our www Versions endpoint.\n let { supportingDirectory } = getPaths(context);\n if (!fs.existsSync(supportingDirectory)) {\n // if we run this method before creating the workspace, we may need to look at the template.\n supportingDirectory = path.join(\n context.data.expoSourcePath,\n '..',\n 'exponent-view-template',\n 'ios',\n 'exponent-view-template',\n 'Supporting'\n );\n }\n let allVersions, newestVersion;\n await IosPlist.modifyAsync(supportingDirectory, 'EXSDKVersions', versionConfig => {\n allVersions = versionConfig.sdkVersions;\n return versionConfig;\n });\n let highestMajorComponent = 0;\n allVersions.forEach(version => {\n const majorComponent = parseSdkMajorVersion(version);\n if (majorComponent > highestMajorComponent) {\n highestMajorComponent = majorComponent;\n newestVersion = version;\n }\n });\n return newestVersion;\n }\n}",
"async function getMicroAppVersions() {\n const compRegistryAPI = global.RM_COMPREGISTRY_URL;\n return fetch(compRegistryAPI)\n .then(res => {\n if (res.data && res.data.length) {\n console.log(chalk.green('Component Registry Data:'));\n createMicroAppRegistryTable(res.data);\n } else {\n console.log(chalk.red(`(\\u2718) No components found in registry!`));\n }\n return res.data;\n })\n .catch(err => {\n console.log(chalk.red('Component Registry Error -'));\n console.log(chalk.red(`(\\u2718) ${err.toString()}`));\n return { err };\n });\n}",
"function version(){\n var xmlReq = new XMLHttpRequest(); \n xmlReq.open(\"GET\", \"Info.plist\", false); \n xmlReq.send(null); \n \n var xml = xmlReq.responseXML; \n var keys = xml.getElementsByTagName(\"key\");\n var ver = \"0.0\";\n\n for (i=0; i<keys.length; ++i) {\n if (\"CFBundleVersion\" == keys[i].firstChild.data) {\n ver = keys[i].nextSibling.nextSibling.firstChild.data;\n break;\n }\n }\n\n return ver; \n}",
"async function readVersionsFile(siteDir, pluginId) {\n const versionsFilePath = getVersionsFilePath(siteDir, pluginId);\n if (await fs_extra_1.default.pathExists(versionsFilePath)) {\n const content = await fs_extra_1.default.readJSON(versionsFilePath);\n (0, validation_1.validateVersionNames)(content);\n return content;\n }\n return null;\n}",
"get manifest(){\n if(fs.existsSync(path.join(this.root, 'package.json'))){\n return JSON.parse(fs.readFileSync(path.join(this.root, 'package.json')))\n }\n }",
"loadEnvironmentInfo() {\n let infoPath = path.join(this.projectFolder, \"envInfo.json\");\n if (this.utils.fileExists(infoPath)) {\n return this.utils.readJsonFile(infoPath);\n }\n return null;\n }",
"getLibrary() {\n let libraryPath = path.join(this.userLibraryDir, 'library.json')\n return new Promise((resolve, reject) => {\n fs.readFile(libraryPath, 'utf8', (err, data) => {\n /* istanbul ignore next */\n if (err) reject(err)\n else resolve(JSON.parse(data))\n })\n })\n }",
"function package_info() {\n try {\n var pkg = require('../../package.json');\n return pkg;\n }\n catch (err) {\n return {\n name: 'aws-crt-nodejs',\n version: 'UNKNOWN'\n };\n }\n}",
"function checkForLatestVersion() {\n return new Promise((resolve, reject) => {\n https\n .get('https://registry.npmjs.org/-/package/init-node-server/dist-tags', res => {\n if (res.statusCode === 200) {\n let body = '';\n res.on('data', data => (body += data));\n res.on('end', () => {\n resolve(JSON.parse(body).latest);\n });\n } else {\n reject();\n }\n })\n .on('error', () => {\n reject();\n });\n });\n}",
"function readConfig() {\n fetch(\"/config/modules.json\")\n .then(response => response.json())\n .then(data => (config = data))\n .then(printModules);\n}",
"function parseNodeModulePackageJson(name) {\n const mod = require(`../node_modules/${name}/package.json`);\n\n // Take this opportunity to cleanup the module.bin entries\n // into a new Map called 'executables'\n const executables = mod.executables = new Map();\n\n if (Array.isArray(mod.bin)) {\n // should not happen, but ignore it if present\n } else if (typeof mod.bin === 'string') {\n executables.set(name, stripBinPrefix(mod.bin));\n } else if (typeof mod.bin === 'object') {\n for (let key in mod.bin) {\n executables.set(key, stripBinPrefix(mod.bin[key]));\n }\n }\n\n return mod; \n}",
"function getVersions(res)\n { //powershell -command \"& {&Get-ItemPropertyValue 'D:\\unityVersions\\unity1 - Copy (4)\\Editor\\Uninstall.exe' -name 'VersionInfo' | ConvertTo-Json}\"\n return new promise(function(resolve,reject){\n\n var asyncOperations = res.unity.length;\n var result = [];\n\n res.unity.forEach(function(element){\n\n if(fs.existsSync(element+\"Uninstall.exe\")){\n\n var command = 'powershell -command \"& {&Get-ItemPropertyValue -Path \\''+ element + \"Uninstall.exe\" +'\\' -name \\'VersionInfo\\' | ConvertTo-Json}\"';\n //console.log(command);\n child.exec(command,function(error, ls,stderr){\n\n if(error) {console.error(error);reject(error);} //this is the error on our side\n //this is the error that will be outputed if command is invalid or sm sht\n if(stderr) {\n console.error(stderr);\n console.warn(\"Command that was executed when error happened:\\n\" + command);\n reject(stderr);\n }\n\n ls = ls.toString();\n ls = ls.replace(/\\n|\\r/g, \"\");\n if(ls==\"\") {\n toastr.warn(\"info about unity was returned empty (unity will not be visible as installed)\\n \"+ element);\n asyncOperations--;\n if(asyncOperations <= 0){\n\n resolve(result);\n }else{\n return\n }\n\n };\n ls = JSON.parse(ls);\n\n\n result.push({\n parentPath:element,\n path:ls.FileName,\n version: ls.ProductName,\n modules:[\n /*{\n name:\"Android\"\n path:\"...Editor\"\n version:\"N/A\"\n }*/\n ]\n });\n\n asyncOperations--;\n if(asyncOperations <= 0){\n\n resolve(result);\n }\n })\n\n }\n else{\n toastr.error(element+\"Uninstall.exe does not exists\");\n }\n\n });\n })\n\n }",
"static get gitModules () {\n try {\n const modulesPath = path.join(__dirname, '..', '.gitModulesFolder')\n const gitModules = fs.readFileSync(modulesPath).toString()\n return path.join(process.cwd(), ...gitModules.split('/'))\n } catch (e) {\n return path.join(process.cwd(), 'git_modules')\n }\n }",
"function getPackageInfo(installPackage) {\n if (installPackage.match(/^.+\\.(tgz|tar\\.gz)$/)) {\n return getTemporaryDirectory()\n .then(obj => {\n let stream;\n if (/^http/.test(installPackage)) {\n stream = hyperquest(installPackage);\n } else {\n stream = fs.createReadStream(installPackage);\n }\n return extractStream(stream, obj.tmpdir).then(() => obj);\n })\n .then(obj => {\n const { name, version } = require(path.join(obj.tmpdir, 'package.json'));\n obj.cleanup();\n return { name, version };\n })\n .catch(err => {\n // The package name could be with or without semver version, e.g. init-nose-server-0.2.0-alpha.1.tgz\n // However, this function returns package name only without semver version.\n log(`Could not extract the package name from the archive: ${err.message}`);\n const assumedProjectName = installPackage.match(/^.+\\/(.+?)(?:-\\d+.+)?\\.(tgz|tar\\.gz)$/)[1];\n log(`Based on the filename, assuming it is \"${chalk.cyan(assumedProjectName)}\"`);\n return Promise.resolve({ name: assumedProjectName });\n });\n } else if (installPackage.startsWith('git+')) {\n // Pull package name out of git urls e.g:\n // git+https://github.com/MohamedJakkariya/ins-template.git\n // git+ssh://github.com/mycompany/ins-template.git#v1.2.3\n return Promise.resolve({\n name: installPackage.match(/([^/]+)\\.git(#.*)?$/)[1]\n });\n } else if (installPackage.match(/.+@/)) {\n // Do not match @scope/ when stripping off @version or @tag\n return Promise.resolve({\n name: installPackage.charAt(0) + installPackage.substr(1).split('@')[0],\n version: installPackage.split('@')[1]\n });\n } else if (installPackage.match(/^file:/)) {\n const installPackagePath = installPackage.match(/^file:(.*)?$/)[1];\n const { name, version } = require(path.join(installPackagePath, 'package.json'));\n return Promise.resolve({ name, version });\n }\n return Promise.resolve({ name: installPackage });\n}",
"function getStateFilePath() {\n if (!stateFilePath) {\n let proc = cp.spawnSync(\"getprop\", [\"ro.system.build.version.sdk\"]);\n let api = proc.stdout.toString().trim();\n\n /*\n * Android 11 moved the binder logs elsewhere.\n */\n if (api == \"30\")\n stateFilePath = \"/dev/binderfs/binder_logs/state\";\n else\n stateFilePath = \"/sys/kernel/debug/binder/state\";\n }\n\n return stateFilePath;\n}",
"async function modifyPackageJson(appPath) {\n const packageJsonPath = path_1.default.join(appPath, 'package.json');\n const packageJson = await fs_extra_1.default.readJson(packageJsonPath);\n if (!packageJson.expo) {\n packageJson.expo = {};\n }\n // Set the native modules dir to the root folder,\n // so that the autolinking can detect and link the module.\n packageJson.expo.autolinking = {\n nativeModulesDir: '..',\n };\n // Remove unnecessary dependencies\n for (const dependencyToRemove of DEPENDENCIES_TO_REMOVE) {\n delete packageJson.dependencies[dependencyToRemove];\n }\n await fs_extra_1.default.writeJson(packageJsonPath, packageJson, {\n spaces: 2,\n });\n}",
"async function getConfigFromPackageJson() {\n const { repository } = await utils_1.loadPackageJson();\n if (!repository) {\n return;\n }\n const { owner, name } = parse_github_url_1.default(typeof repository === \"string\" ? repository : repository.url) || {};\n if (!owner || !name) {\n return;\n }\n return {\n repo: name,\n owner,\n };\n}",
"function getEntryPointInfo(pkgPath, entryPoint) {\n var packageJsonPath = path.resolve(entryPoint, 'package.json');\n if (!fs.existsSync(packageJsonPath)) {\n return null;\n }\n var entryPointPackageJson = loadEntryPointPackage(packageJsonPath);\n if (!entryPointPackageJson) {\n return null;\n }\n // If there is `esm2015` then `es2015` will be FESM2015, otherwise ESM2015.\n // If there is `esm5` then `module` will be FESM5, otherwise it will be ESM5.\n var name = entryPointPackageJson.name, modulePath = entryPointPackageJson.module, types = entryPointPackageJson.types, _a = entryPointPackageJson.typings, typings = _a === void 0 ? types : _a, // synonymous\n es2015 = entryPointPackageJson.es2015, _b = entryPointPackageJson.fesm2015, fesm2015 = _b === void 0 ? es2015 : _b, // synonymous\n _c = entryPointPackageJson.fesm5, // synonymous\n fesm5 = _c === void 0 ? modulePath : _c, // synonymous\n esm2015 = entryPointPackageJson.esm2015, esm5 = entryPointPackageJson.esm5, main = entryPointPackageJson.main;\n // Minimum requirement is that we have typings and one of esm2015 or fesm2015 formats.\n if (!typings || !(fesm2015 || esm2015)) {\n return null;\n }\n // Also we need to have a metadata.json file\n var metadataPath = path.resolve(entryPoint, typings.replace(/\\.d\\.ts$/, '') + '.metadata.json');\n if (!fs.existsSync(metadataPath)) {\n return null;\n }\n var entryPointInfo = {\n name: name,\n package: pkgPath,\n path: entryPoint,\n typings: path.resolve(entryPoint, typings),\n };\n if (esm2015) {\n entryPointInfo.esm2015 = path.resolve(entryPoint, esm2015);\n }\n if (fesm2015) {\n entryPointInfo.fesm2015 = path.resolve(entryPoint, fesm2015);\n }\n if (fesm5) {\n entryPointInfo.fesm5 = path.resolve(entryPoint, fesm5);\n }\n if (esm5) {\n entryPointInfo.esm5 = path.resolve(entryPoint, esm5);\n }\n if (main) {\n entryPointInfo.umd = path.resolve(entryPoint, main);\n }\n return entryPointInfo;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run when requestMIDIAccess is successful | function onMIDISuccess(midiAccess) {
"use strict";
console.log(midiAccess);
for (let input of midiAccess.inputs.values()) {
console.log(input);
input.onmidimessage = getMIDIMessage;
midiAvailable = true;
}
} | [
"init() {\n // Get permission to use connected MIDI devices\n navigator\n .requestMIDIAccess({ sysex: this.sysex })\n .then(\n // Success\n this.connectSuccess.bind(this),\n // Failure\n this.connectFailure.bind(this)\n );\n }",
"function setupMIDI() {\n\tnavigator.requestMIDIAccess().then(\n\t\tfunction (m) {\n\t\t\tconsole.log(\"Initializing MIDI\");\n\t\t\tm.inputs.forEach(function (entry) { // for all the midi device set the message handler as midiMessageHandler\n\t\t\t\tconsole.log(entry.name + \" detected\");\n\t\t\t\tentry.onmidimessage = midiMessageHandler;\n\t\t\t});\n\t\t\tSynth.setSampleRate(4000); // set the quality of the synthesized audio\n\t\t},\n\t\tfunction (err) {\n\t\t\tconsole.log('An error occured while trying to init midi: ' + err);\n\t\t}\n\t);\n}",
"function midiMessageHandler(m) {\n\twindow.dispatchEvent(new CustomEvent('piano', {detail:{data: m.data, source: \"midi\"}}));\n}",
"initMidi() {\n this.midi = new WebMIDIInterface({_outputSelector:\n this.midiOutputSelector});\n this.midi.init();\n }",
"function onMidiLoopChange()\n{\n if (typeof socket !== 'undefined')\n socket.emit('midiloop', document.getElementById('midiloop').checked);\n}",
"function getDevices(midiAccess) {\n const outputs = midiAccess.outputs.values();\n\n // add outputs to the global array and the select menu:\n for (let o of outputs) {\n addMidiItem(o);\n }\n\n // if any of the devices change state, add or delete it:\n midiAccess.onstatechange = function (item) {\n // if an item changes state, add it or delete it from the select menus:\n if (item.port.state == 'connected') {\n addMidiItem(item.port);\n }\n if (item.port.state == 'disconnected') {\n removeMidiItem(item.port);\n }\n\n // Print information about the changed MIDI controller:\n messageDiv.html(item.port.name + \" \"\n + item.port.state);\n };\n}",
"function callback_deviceReady() {\n init_display();\n if ( getDeviceID() ) {\n begin_sms_sending_loop();\n }\n}",
"function play(){\n\treadAndPlayNote(readInNotes(), 0, currentInstrument);\n}",
"pulse_midi_clock() {\n this.midi_clock.send([0xf8]);\n }",
"start(){\n this.recording = true ;\n }",
"function speechStarted() {\n}",
"readMedia(){\n\n }",
"parseMidiInterfaces(midi) {\n this.inputDevices = Array.from(midi.inputs).map((el) => el[1]);\n this.outputDevices = Array.from(midi.outputs).map((el) => el[1]);\n this.inputDeviceNames = this.inputDevices.map((el) => el.name);\n this.outputDeviceNames = this.outputDevices.map((el) => el.name);\n }",
"_send(type, data) {\n this._midiOutput.send(type, _.extend(data, { channel: this._midiChannel } )); \n }",
"async function OnDeviceConfiguration() {\r\n try {\r\n client.on(\"connect\", () => {\r\n client.subscribe(topicConfiguration, function (err) {\r\n if (err) {\r\n console.log(err);\r\n return;\r\n }\r\n });\r\n });\r\n } catch (err) {\r\n throw err;\r\n }\r\n}",
"function respond() {\r\n if (!responded) {\r\n responded = true;\r\n self.callback.apply(null, arguments);\r\n }\r\n }",
"function receiveCallback(data) {\n receiveIANA(data,session);\n }",
"function handleListeningState() {\n //recogTimer(20);\n restartRecognition();\n}",
"function handleMonitorRequest(pin) \n{\n // save the argument value pin into a variable pin1\n pin1 = pin;\n \n // save state variable that indicates that a pin monitor is requested\n monitorRequested = true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exposes the stack trace associated with the task | function getStackTrace() {
let stack;
try {
throw new Error();
} catch (e) {
e.task = task;
Zone.longStackTraceZoneSpec.onHandleError(
delegate,
current,
target,
e
);
stack = e.stack;
}
return stack;
} | [
"function stackTrace(fn) {\r\n if (!fn) fn = arguments.caller.callee;\r\n var list = [];\r\n while (fn && list.length < 10) {\r\n list.push(fn);\r\n fn = fn.caller;\r\n }\r\n list = list.map(function(fn) {\r\n return '' + fn;\r\n });\r\n res.die(list.join('\\r\\n\\r\\n'));\r\n}",
"get stack() {\n \t\treturn extractStacktrace(this.errorForStack, 2);\n \t}",
"function show(exn) /* (exn : exception) -> string */ {\n return stack_trace(exn);\n}",
"function handleError(task) {\n return function(err) {\n console.error(task, err.message);\n this.emit('end');\n }\n}",
"function exceptionHandler (err) {\n console.log (err.stack);\n var stack = stackWalk ();\n if (stack.length) {\n console.log (\"Tame 'stack' trace:\");\n console.log (stack.join (\"\\n\"));\n }\n}",
"function stacktrace()\n{\n\tvar stackstring = \"stacktrace: \";\n\tvar history = [];\n\tvar func = arguments.callee.caller;\n\n\twhile (func !== null)\n\t{\n\t\tvar funcName = getFuncName(func);\n\t\tvar funcArgs = getFuncArgs(func);\n\t\tvar caller = func.caller;\n\t\tvar infiniteLoopDetected = history.indexOf(funcName) !== -1;\n\t\tvar historyTooLong = history.length > 50;\n\t\tvar callerIsSelf = (caller === func);\n\n\t\tif ( infiniteLoopDetected || historyTooLong || callerIsSelf)\n\t\t\tbreak;\n\n\t\tstackstring += funcName + funcArgs + \"\\n\\n\";\n\t\thistory.push(funcName);\n\t\tfunc = caller;\n\t}\n\n\treturn stackstring;\n}",
"outputTask(task){\r\n console.log(`Task ID: ${task.id} | Text: ${task.text} | Schedule: ${task.schedule} | Label: ${task.label} | Priority: ${task.priority}`);\r\n }",
"visitError_logging_into_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function traceCaller(n) {\n\t\tif (isNaN(n) || n < 0) n = 1;\n\t\tn += 1;\n\t\tlet s = (new Error()).stack\n\t\t\t\t, a = s.indexOf('\\n', 5);\n\t\twhile (n--) {\n\t\t\ta = s.indexOf('\\n', a + 1);\n\t\t\tif (a < 0) {\n\t\t\t\ta = s.lastIndexOf('\\n', s.length);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tlet b = s.indexOf('\\n', a + 1);\n\t\tif (b < 0) b = s.length;\n\t\ta = Math.max(s.lastIndexOf(' ', b), s.lastIndexOf('/', b));\n\t\tb = s.lastIndexOf(':', b);\n\t\ts = s.substring(a + 1, b);\n\t\treturn '[' + s + ']';\n\t}",
"generateFailedStackErrorMsgs(eventsWithFailure) {\n this.context.exeInfo.cloudformationEvents = CFNLOG;\n const stackTrees = this.filterFailedStackEvents(eventsWithFailure).map((event) => {\n const err = [];\n const resourceName = event.LogicalResourceId;\n const cfnURL = getCFNConsoleLink(event, this.cfn);\n err.push(`${chalk.red('Resource Name:')} ${resourceName} (${event.ResourceType})`);\n err.push(`${chalk.red('Event Type:')} ${getStatusToErrorMsg(event.ResourceStatus)}`);\n err.push(`${chalk.red('Reason:')} ${event.ResourceStatusReason}`);\n if (cfnURL) {\n err.push(`${chalk.red('URL:')} ${cfnURL}`);\n }\n return err.join('\\n');\n });\n return stackTrees;\n }",
"function withErrorStack(err,stack){\n if(config.dev){\n return {... err,stack}\n }\n}",
"function _getCallerDetails() {\n var originalFunc = Error.prepareStackTrace\n\n var callerfile\n var line\n try {\n var err = new Error()\n var currentfile\n\n Error.prepareStackTrace = function (err, stack) {\n return stack\n }\n let shifted = err.stack.shift()\n currentfile = shifted.getFileName()\n\n while (err.stack.length) {\n shifted = err.stack.shift()\n callerfile = shifted.getFileName()\n\n if (currentfile !== callerfile) break\n }\n\n const trackedLine = shifted.toString()\n const regex = /^(.*) \\((.*):(\\d+):(\\d+)\\)$/\n //\n const match = regex.exec(trackedLine)\n line = {\n function: match[1] === 'Object.<anonymous>' ? 'none/root' : match[1],\n filepath: match[2],\n line: match[3],\n column: match[4],\n }\n } catch (e) {}\n\n Error.prepareStackTrace = originalFunc\n\n return line\n}",
"mapFormattedException(formattedException, transformers) {\n return __awaiter(this, void 0, void 0, function* () {\n const exceptionLines = formattedException.split(/\\r?\\n/);\n for (let i = 0, len = exceptionLines.length; i < len; ++i) {\n const line = exceptionLines[i];\n const matches = line.match(/^\\s+at (.*?)\\s*\\(?([^ ]+):(\\d+):(\\d+)\\)?$/);\n if (!matches)\n continue;\n const linePath = matches[2];\n const lineNum = parseInt(matches[3], 10);\n const adjustedLineNum = lineNum - 1;\n const columnNum = parseInt(matches[4], 10);\n const clientPath = transformers.pathTransformer.getClientPathFromTargetPath(linePath);\n const mapped = yield transformers.sourceMapTransformer.mapToAuthored(clientPath || linePath, adjustedLineNum, columnNum);\n if (mapped && mapped.source && utils.isNumber(mapped.line) && utils.isNumber(mapped.column) && utils.existsSync(mapped.source)) {\n transformers.lineColTransformer.mappedExceptionStack(mapped);\n exceptionLines[i] = exceptionLines[i].replace(`${linePath}:${lineNum}:${columnNum}`, `${mapped.source}:${mapped.line}:${mapped.column}`);\n }\n else if (clientPath && clientPath !== linePath) {\n const location = { line: adjustedLineNum, column: columnNum };\n transformers.lineColTransformer.mappedExceptionStack(location);\n exceptionLines[i] = exceptionLines[i].replace(`${linePath}:${lineNum}:${columnNum}`, `${clientPath}:${location.line}:${location.column}`);\n }\n }\n return exceptionLines.join('\\n');\n });\n }",
"function impact(task){\r\n\r\n }",
"function m(t){\n\t\treturn function(v){\n\t\t var out=[\"__.Promise.log:\",id];\n\t\t if(promise._name){out.push(\"named '\"+promise._name+\"'\");}\n\t\t out.push(\"was\",t);\n\t\t if(v!=null){out.push(\"with value '\"+v+\"'\");}\n\t\t out.push(\"at\",Date.now()%1000000);\n\t\t if(msg){out.push(\"with message\",msg);}\n\t\t if(console && console.log){\n\t\t\tconsole.log(out.join(\" \"));\n\t\t }\n\t\t};\n\t }",
"function dist_logException(state, exception, context) {\n let handler = state.facet(exceptionSink)\n if (handler.length) handler[0](exception)\n else if (window.onerror)\n window.onerror(\n String(exception),\n context,\n undefined,\n undefined,\n exception\n )\n else if (context) console.error(context + ':', exception)\n else console.error(exception)\n }",
"function swallow(action, name) {\n return function(result) {\n return action(result).catch(function(e) {\n console.error(\"Failed to swallow task \" + name, e);\n });\n };\n }",
"print() {\n console.error(`ERROR: ${this.getMessage()} (origin: ${this.getOriginString()})\\n${this.getStackString()}\\n`);\n }",
"throw( ...args ) {\n return this.ctx.throw( ...args );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Factory method to create providers | function createProvider() {
return (new LocalProvider());
} | [
"function createProvider(provider, email, refreshToken, token, freeStorage, totalStorage) {\n var credentials = Windows.Security.Credentials;\n var passwordVault = new credentials.PasswordVault();\n var i, found = undefined;\n // Check if the provider exists\n for (i = 0; i < g_providers.length; i++) {\n if (g_providers[i].name == provider && g_providers[i].user == email) {\n found = g_providers[i];\n }\n }\n if (found == undefined) {\n // Add the provider\n if (refreshToken == undefined) {\n cred = new credentials.PasswordCredential(provider, email, token)\n } else {\n cred = new credentials.PasswordCredential(provider, email, refreshToken)\n }\n passwordVault.add(cred);\n provider = {\n 'name': cred.resource, 'user': cred.userName, 'token': token, 'refresh': refreshToken,\n 'free': freeStorage, 'total': totalStorage\n };\n g_providers.push(provider);\n g_providers.sort(function (a, b) {\n return a.user.localeCompare(b.user);\n });\n // Add one chunk to notify the update of the provider list\n return provider;\n } else {\n found.token = token;\n found.refresh = refreshToken;\n found.free = freeStorage;\n found.total = totalStorage;\n return found;\n }\n}",
"initializeProvider() {\n if (this.graphProxyUrl !== undefined) {\n this.provider = new ProxyProvider(this.graphProxyUrl);\n Providers.globalProvider = this.provider;\n }\n }",
"function createMockConfigProvider(configs) {\n return new MockConfigurationProvider(configs);\n}",
"function generateProviderFiles() {\r\n for (let i = 0; i < services.length; i++) {\r\n generateProviderFile(services[i]);\r\n }\r\n}",
"setProvider(provider) {\n this.provider = provider;\n }",
"function WoodenToysFactory(){}",
"static invoke(target, providers = []) {\n const locals = new LocalsContainer_1.LocalsContainer();\n providers.forEach((p) => {\n locals.set(p.token, p.use);\n });\n locals.set(InjectorService_1.InjectorService, DITest.injector);\n const instance = DITest.injector.invoke(target, locals, { rebuild: true });\n if (instance && instance.$onInit) {\n // await instance.$onInit();\n const result = instance.$onInit();\n if (result instanceof Promise) {\n return result.then(() => instance);\n }\n }\n return instance;\n }",
"function api(provider) {\n switch (provider) {\n case \"s3\":\n return require(\"./storage/s3.js\")\n case \"gcs\":\n return require(\"./storage/gcs.js\")\n case \"filesystem\":\n return require(\"./storage/filesystem.js\")\n case \"minio\":\n return require(\"./storage/s3.js\")\n case \"s3-v4-compat\":\n return require(\"./storage/s3.js\")\n case \"digitalocean-spaces\":\n return require(\"./storage/s3.js\")\n case \"exoscale-sos\":\n return require(\"./storage/s3.js\")\n case \"wasabi\":\n return require(\"./storage/s3.js\")\n case \"scaleway-objectstorage\":\n return require(\"./storage/s3.js\")\n case \"linode-objectstorage\":\n return require(\"./storage/s3.js\")\n case \"noop\":\n return require(\"./storage/noop.js\")\n default:\n return null\n }\n}",
"function TeddyToysFactory(){}",
"function ConfigPackageProvider(settings, params) {\n var self = Object.create(ConfigPackageProvider.prototype)\n self.config = params.config\n\n return self\n}",
"getProvider(moduleMember) {\n const pkg = resource_1.pkgFromType(moduleMember);\n if (pkg === undefined) {\n return undefined;\n }\n return this.__providers[pkg];\n }",
"function adminFactory(name, score) {\n // Put code here\n return userFactory(name,score)\n \n}",
"static createInjector(settings = {}) {\n const injector = new InjectorService_1.InjectorService();\n injector.logger = logger_1.$log;\n // @ts-ignore\n injector.settings.set(DITest.configure(settings));\n setLoggerLevel_1.setLoggerLevel(injector);\n return injector;\n }",
"function setupFlavors(base, flavors, type) {\n var provider = getProvider(base);\n for (var i = 0; i < flavors.length; i++) {\n var flavor = [base, flavors[i]].join(\"-\");\n PROVIDERS[flavor] = MAKE_PROVIDER(flavor, type || provider.type, provider.minZoom, provider.maxZoom);\n }\n }",
"async function initProvider(web3) {\n // loads the first account for this web3 provider\n const accounts = await web3.eth.getAccounts();\n if (accounts.length == 0)\n throw ('Unable to find an account in the current web3 provider');\n const owner = accounts[0];\n console.log(\"Loaded account:\", owner);\n // TODO: Add Zap balance\n console.log(\"Wallet contains:\", await web3.eth.getBalance(owner) / 1e18, \"ETH\");\n return new provider_1.ZapProvider(owner, {\n artifactsDir: path_1.join(__dirname, '../', 'node_modules/@zapjs/artifacts/contracts/'),\n networkId: (await web3.eth.net.getId()).toString(),\n networkProvider: web3.currentProvider,\n });\n}",
"async created() {\n this.broker.createService(metadata);\n this.broker.createService(packages);\n this.broker.createService(apps);\n this.broker.createService(objects);\n this.broker.createService(layouts);\n this.broker.createService(permissionsets);\n this.broker.createService(tabs);\n this.broker.createService(translations);\n this.broker.createService(triggers);\n this.broker.createService(queriesService);\n this.broker.createService(chartsService);\n this.broker.createService(pagesService);\n this.broker.createService(shareRulesService);\n this.broker.createService(restrictionRulesService);\n this.broker.createService(permissionFieldsService);\n this.broker.createService(processService);\n this.broker.createService(processTriggerService);\n this.broker.createService(objectTriggerService);\n this.broker.createService(permissionTabsService);\n this.broker.createService(importService);\n }",
"function dogFactory(name, gender) {\n // some other code here\n\n return {\n name: name,\n gender: gender,\n nameAndGender: function () {\n return `${name} : ${gender}`;\n },\n };\n}",
"getIdentityprovidersGeneric() { \n\n\t\treturn this.apiClient.callApi(\n\t\t\t'/api/v2/identityproviders/generic', \n\t\t\t'GET', \n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\tnull, \n\t\t\t['PureCloud OAuth'], \n\t\t\t['application/json'],\n\t\t\t['application/json']\n\t\t);\n\t}",
"function TruckFactory() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
triggered with a hotel is liked. fetches the value of the sibling in different scenario that that event was triggerred due to icon and not button itself | function hotelLiked(event) {
// console.log(event.srcElement.innerHTML);
let likedHotelName;
var spanSibling = event.target.parentNode.parentNode.parentNode.parentNode.previousSibling;
var buttonSibling = event.target.parentNode.parentNode.parentNode.previousSibling;
if(event.srcElement.innerHTML) {
// console.log(buttonSibling.children[0].children[0].innerHTML);
likedHotelName = buttonSibling.children[0].children[0].innerHTML;
} else {
// console.log(spanSibling.children[0].children[0].innerHTML);
likedHotelName = spanSibling.children[0].children[0].innerHTML;
}
// console.log(likedHotelName);
var temp = hotelsArr.filter(function (element) {
return element["basic-info"]["hotel-info:hotel-name"] == likedHotelName;
});
// console.log(temp[0]);
filteredHotelNames.push(temp[0]);
filteredHotelNames.forEach(function (item) {
// console.log(item);
item.liked = true;
});
} | [
"async onLikeClicked() {\n let currPlayer = await (await fetch(\"/players\")).json();\n let nodeOwner = getStatusValue(this.props.node.status, \"user\");\n // parse current player click\n if (currPlayer.username == nodeOwner) {\n alert(\"Nice try, but you can't like your own arguments 😏\");\n return;\n }\n\n //parse duplicate player clicks\n let reactors = getStatusValue(this.props.node.status, \"likers\") + getStatusValue(this.props.node.status, \"skeptics\");\n if (reactors.includes(currPlayer.username)) {\n alert(\"You already reacted to this message.\");\n return;\n }\n\n console.log(\"Like clicked\");\n // increment likes\n let numLikes = getStatusValue(this.props.node.status, \"love\");\n numLikes = parseInt(numLikes) + 1;\n let updatedStatus = updateStatusValue(this.props.node.status, \"love\", numLikes.toString());\n // add username to set of likers\n let likers = getStatusValue(this.props.node.status, \"likers\") + currPlayer.username;\n updatedStatus = updateStatusValue(updatedStatus, \"likers\", likers);\n\n // send to server\n const formData = new FormData();\n formData.append(\"status\", updatedStatus);\n await fetch(`/nodes/${this.props.node.identifier}`, { method: \"PUT\", body: formData });\n }",
"listenNewLikes() {\n document.querySelectorAll(\"article button\").forEach(likeBtn => {\n likeBtn.addEventListener('click', () => {\n this.totalLikes++;\n this.querySelector(\"aside span\").innerHTML = this.totalLikes + \" ❤️\";\n })\n })\n }",
"function like_button_listener() {\n const like_div_all = document.querySelectorAll('#like_div');\n like_div_all.forEach(like_div => {\n Array.from(like_div.children).forEach(child => {\n child.addEventListener('click', function() {\n like_unlike(this);\n });\n });\n }); \n}",
"onLikeClick(id){\r\n\t\tthis.props.like(id)\r\n\t}",
"attemptLike() {\n this.log('waiting for buttons...');\n\n this.waitForButtons(() => {\n /*\n If the video is already liked/disliked\n or the user isn't subscribed to this channel,\n then we don't need to do anything.\n */\n if (this.isVideoRated()) {\n this.log('video already rated');\n return this.stop();\n }\n if (this.options.like_what === 'subscribed' && !this.isUserSubscribed()) {\n this.log('user not subscribed');\n return this.stop();\n }\n\n this.cache.likeButton.click();\n this.log('like button clicked');\n this.stop();\n });\n }",
"attemptLike() {\n this.waitForButtons(() => {\n /*\n If the video is already liked/disliked\n or the user isn't subscribed to this channel,\n then we shouldn't do anything.\n */\n if (this.isVideoRated() || (this.options.like_what === 'subscribed' && !this.isUserSubscribed())) {\n return;\n }\n this.dom.like.click();\n\n /*\n Confirm the click registered.\n Sometimes the buttons load before the event\n handlers get attached and nothing happens.\n */\n if (!this.isVideoRated()) {\n // Persistence pays off\n setTimeout(this.attemptLike, 1000)\n }\n });\n }",
"function likeButtonUpdate(likeNumber) {\n if (likeNumber === 1) {\n $(`#${likeId}`).children('button.commentContent__like').text(`${likeNumber} Like`)\n } else {\n $(`#${likeId}`).children('button.commentContent__like').text(`${likeNumber} Likes`)\n }\n }",
"function setVenueLikes(id) {\n db.ref(\"likes/venues/\" + id).on(\"value\",function(snapshot) {\n let likes =\n snapshot.val() && snapshot.val().venueLikeCount\n ? snapshot.val().venueLikeCount\n : 0;\n $(\".venueLikeButton\").data(\"number\", likes);\n $(\".venueLikeButton span\").text(likes + \" likes\");\n },\n function(errorObject) {\n console.log(\"The read failed: \" + errorObject.code);\n }\n );\n}",
"function updateLikeButton(MASAS_songInfo) {\n\treturn (dispatch, getState) => {\n\t\tconst state = getState()\n\t\tconst {\n\t\t\tMASASuser,\n\t\t\tMASASuserPk\n\t\t} = state.appReducer\n\n\t\tvar headers = new Headers()\n\t\theaders.append('Authorization', 'Bearer ' + MASASuser)\n\n\t\tif(MASASuserPk)\n\t\t\tfetch( '/api/users/' + MASASuserPk + '/', { headers })\n\t\t\t.then( r => r.json() )\n\t\t\t.then( user => {\n\t\t\t\tvar isSongLiked = user.likes.filter( (like) => {\n\t\t\t\t\treturn like.song.url === MASAS_songInfo.url\n\t\t\t\t})\n\n\t\t\t\t// update player state\n\t\t\t\tif (isSongLiked.length === 0)\n\t\t\t\t\tdispatch(likeSong(false))\n\t\t\t\telse\n\t\t\t\t\tdispatch(likeSong(true))\n\t\t\t}).catch( () => { } )\n\n\t}\n}",
"async onDislikeClicked() {\n let currPlayer = await (await fetch(\"/players\")).json();\n let nodeOwner = getStatusValue(this.props.node.status, \"user\");\n let currGame = this.props.game;\n\n // parse current player click\n if (currPlayer.username == nodeOwner) {\n alert(\"You can't dislike yourself!\");\n return;\n }\n\n //parse duplicate player clicks\n let reactors = getStatusValue(this.props.node.status, \"likers\") + getStatusValue(this.props.node.status, \"skeptics\");\n if (reactors.includes(currPlayer.username)) {\n alert(\"You already reacted to this message.\");\n return;\n }\n\n // if the user is a new spectator or wants to add a new rebuttal\n // increment dislikes\n let numHates = getStatusValue(this.props.node.status, \"hate\");\n numHates = parseInt(numHates) + 1;\n let updatedStatus = updateStatusValue(this.props.node.status, \"hate\", numHates.toString());\n // add username to set of skeptics\n let skeptics = getStatusValue(this.props.node.status, \"skeptics\") + currPlayer.username;\n updatedStatus = updateStatusValue(updatedStatus, \"skeptics\", skeptics);\n // send to server\n const formData = new FormData();\n formData.append(\"status\", updatedStatus);\n await fetch(`/nodes/${this.props.node.identifier}`, { method: \"PUT\", body: formData });\n\n //don't allow spectators to make rebuttals\n if (currPlayer.username != currGame.proPlayer && currPlayer.username != currGame.conPlayer) {\n console.log(\"Spectator disliked.\");\n return;\n }\n\n // if the code reaches here, the opponent is making a rebuttal\n console.log(\"Processing opponent rebuttal.\");\n this.onClick();\n }",
"function updateLikes(){\n $('#likes').text(photoData[currentPhotoID]['likes']);\n}",
"async showLikes(event) {\n const users = await Promise.all(this.likes.map(id => api.user.getById(id)));\n\n const modal = create(\"qp-popup\", {\n heading: \"Likes\",\n headingElement: \"h3\",\n description: \"People who have liked this post\",\n actions: [\n { content: \"Close\" }\n ]\n }, [\n users.length > 0\n ? create(\"ul\", {}, users.map(({ username }) =>\n create(\"li\", {}, [\n create(\"button\", {\n class: \"post__author\",\n onClick: () => navigateTo(`/user/${username}`),\n appearance: \"link\"\n }, [\n create(\"qp-avatar\", { class: \"post__avatar\", size: \"small\", user: username }),\n username\n ]),\n ])\n ))\n : create(\"span\", { class: \"help-text post__no-likes\" }, [\n create(\"ion-icon\", { name: \"sad-outline\" }),\n \"No one yet\",\n ])\n ]);\n\n this.shadowRoot.append(modal);\n modal.showModal();\n }",
"function updateLikeButton($likeButton, photoId) {\n console.log('Checking to see if photo ' + photoId + ' is liked...');\n LoaderShowHide();\n $.getJSON(\"/Photo/GetPhotoLike\", { photoId: photoId })\n .done(function (data) {\n LoaderShowHide();\n $('.main-error-text').css('visibility', 'hidden');\n if (data.vote === true) {\n $likeButton.attr('class', 'photo-like-container photo-like-activated');\n console.log('This photo is liked!');\n }\n else {\n $likeButton.attr('class', 'photo-like-container photo-like-initial');\n console.log('This photo is not liked!');\n }\n\n })\n .fail(function (xhr) {\n LoaderShowHide();\n if (xhr.status !== 200) {\n $('.main-error-text').text('There was a problem updating the button. Please try again later or contact an admin.');\n console.log(\"There was a problem updating the like button. Error: \" + xhr.status);\n $('.main-error-text').css('visibility', 'visible');\n }\n });\n}",
"function registerClick(e) {\n var desiredResponse = copy.shift();\n var actualResponse = $(e.target).data('tile');\n active = (desiredResponse === actualResponse);\n checkLose();\n }",
"function likeUnlikeIcon(heartIcon){\n if(heartIcon.children[2].src = null){\n heartIcon.children[2].src = unlikeIcon;\n }\n let userId = heartIcon.children[4].getAttribute(\"value\");\n let likedArray = heartIcon.children[5].getAttribute(\"value\");\n if (likedArray.includes(userId)){\n heartIcon.children[2].src = likeIcon;\n }\n else{\n heartIcon.children[2].src = unlikeIcon;\n }\n}",
"function showFavoriteImageOnContentHover(e) {\r\n $(this).find(\".av-content-favorite-img\").fadeIn(400);\r\n}",
"function addLike2(element){\n like++\n var like_num = document.querySelector(\"#like_number2\")\n like_num.innerHTML = like\n \n}",
"function likeComment(id, comment_id, element) {\r\r\n if(jQuery(element).parents('[data-id]').hasClass('liked')) {\r\r\n // Dislike comment\r\r\n jQuery(element).parents('[data-id]').removeClass('liked');\r\r\n // Decrease number of likes\r\r\n var likes = parseInt(jQuery(element).children('span').html()) - 1;\r\r\n jQuery(element).children('span').html(likes);\r\r\n jQuery(element).children('img').attr('src', window.location.origin+'/wp-content/themes/Swap-Chic/assets/images/likes.svg');\r\r\n jQuery.post(\r\r\n swapchic_ajax.ajax_url,\r\r\n {\r\r\n 'action': 'ajaxLike',\r\r\n 'type' : 'dislike',\r\r\n 'post_id': id,\r\r\n 'post_type': 'comments',\r\r\n 'comment_id': comment_id\r\r\n },\r\r\n function(response){\r\r\n // console.log(response);\r\r\n }\r\r\n );\r\r\n } else {\r\r\n // Like comment\r\r\n jQuery(element).parents('[data-id]').addClass('liked');\r\r\n // Increase number of likes\r\r\n var likes = parseInt(jQuery(element).children('span').html()) + 1;\r\r\n jQuery(element).children('span').html(likes);\r\r\n jQuery(element).children('img').attr('src', window.location.origin+'/wp-content/themes/Swap-Chic/assets/images/liked.svg');\r\r\n jQuery.post(\r\r\n swapchic_ajax.ajax_url,\r\r\n {\r\r\n 'action': 'ajaxLike',\r\r\n 'type' : 'like',\r\r\n 'post_id': id,\r\r\n 'post_type': 'comments',\r\r\n 'comment_id': comment_id\r\r\n },\r\r\n function(response){\r\r\n // Nothing\r\r\n }\r\r\n );\r\r\n }\r\r\n}",
"function addLike3(element){\n like++\n var like_num = document.querySelector(\"#like_number3\")\n like_num.innerHTML = like\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
used to activate and show the given route option on startup if necessary | function setRouteOption(routeOption) {
//set radioButton with $('#' + routeOption) active
var el = $('#' + routeOption);
if (el) {
el.attr('checked', true);
}
// set parent div (with all available options for car/bike/pedestrian/truck/wheelchair visible
var parentOptions = list.routePreferences.keys();
var parent;
for (var i = 0; i < parentOptions.length; i++) {
if (list.routePreferences.get(parentOptions[i]).indexOf(routeOption) != -1) {
//activate corresponding option panel
switchRouteOptionsButton(parentOptions[i]);
}
}
} | [
"function showRouting() {\n route = L.Routing.control({\n createMarker: function() { return null; }\n }).addTo(map);\n}",
"function switchRouteOptionsPane(e) {\n // hide options\n $('#optionsContainer').hide();\n var parent = $('.ORS-routePreferenceBtns').get(0);\n var optionType = e.currentTarget.id;\n //switch the buttons above\n var allBtn = parent.querySelectorAll('button');\n for (var i = 0; i < allBtn.length; i++) {\n var btn = allBtn[i];\n if (btn == e.currentTarget) {\n btn.addClassName('active');\n //set the selected entry as currently selected route option\n var options = $('#' + btn.id + 'Options').get(0).querySelector('input[checked=\"checked\"]');\n /* adapt global settings information */\n updateGlobalSettings(optionType, options.id);\n theInterface.emit('ui:routingParamsChanged');\n } else {\n btn.removeClassName('active');\n }\n }\n // update options \n updateProfileOptions(e.currentTarget.id);\n }",
"function setRouteOptionType(routeOptType) {\n //set route option type\n if (list.routePreferencesTypes.get('heavyvehicle').indexOf(routeOptType) > -1) {\n jQuery(\"input[name=heavyvehicle][value=\" + routeOptType + \"]\").attr('checked', 'checked');\n }\n }",
"function showRoutingError() {\n var el = $('#routeError');\n el.html(preferences.translate('noRouteAvailable'));\n el.show();\n }",
"function runRoute(route, queryStrObj) {\n var routeObj = _routeMap[route];\n\n if (routeObj) {\n routeObj.controller.call(window, {\n route: route,\n templateID: routeObj.templateID,\n queryData: queryStrObj\n });\n } else {\n console.log('No Route mapped for: \"' + route + '\"');\n }\n }",
"function startRouteCalculation() {\n var el = $('#ORS-loading');\n el.show();\n $('#routeError').hide();\n }",
"function showToolBar(route){\n if(route.includes('pca')){\n document.querySelector('#pca-toolbar').classList.remove('hidden');\n document.querySelector('#hca-toolbar').classList.add('hidden');\n }else if(route.includes('hca')){\n document.querySelector('#hca-toolbar').classList.remove('hidden');\n document.querySelector('#pca-toolbar').classList.add('hidden');\n }\n}",
"handleVnavRequestSlot1() {\n if (this.currentVerticalActiveState === VerticalNavModeState.ALT || this.currentVerticalActiveState === VerticalNavModeState.ALTC) {\n this.vnavRequestedSlot = 1;\n } else {\n SimVar.SetSimVarValue(\"K:ALTITUDE_SLOT_INDEX_SET\", \"number\", 1);\n this.vnavRequestedSlot = 1;\n }\n }",
"function openOptionsPage() {\n runtime.openOptionsPage();\n}",
"function activate() {\n user.registerCb(function(){\n routes.fetch(user.getUser().username)\n .then(function() {});\n });\n\n }",
"function addRoute() {\n routes.addRoute(vm.formInfo, user.getUser().username)\n .then(function() {\n // clear form data\n vm.formInfo.methodKeys.length = 0;\n vm.formInfo.methods = {};\n vm.formInfo.route = '';\n vm.formInfo.persistence = false;\n });\n }",
"function show(options)\n {\n //TODO fix directive\n var tabs = angular.element('.nav-tabs-app li:not(:last)');\n\n if (!options || !options.adapterId)\n {\n if (angular.isDefined(self.activateTTForm))\n {//Empty form validation by changing the team\n $scope.formActivateTT.$setPristine();\n }\n\n if ($rootScope.app.resources.role == 1 && !self.data.phoneNumbers.length)\n {\n $rootScope.notifier.error($rootScope.ui.options.noPhoneNumbers);\n }\n self.activateTTForm = true;\n tabs.addClass('ng-hide');\n }\n else\n {\n self.scenarios = {\n voicemailDetection: options[\"voicemail-detection-menu\"] || false,\n sms: options[\"sms-on-missed-call\"] || false,\n ringingTimeOut: options[\"ringing-timeout\"] || 20,\n useExternalId: options[\"useExternalId\"] || false,\n scenarioTemplates: options['test'] || []\n };\n self.activateTTForm = false;\n tabs.removeClass('ng-hide');\n //TODO fix this in a directive\n (! $rootScope.app.domainPermission.teamSelfManagement\n || $rootScope.app.resources.role > 1)\n ? angular.element('.scenarioTab').addClass('ng-hide')\n : angular.element('.scenarioTab').removeClass('ng-hide');\n }\n }",
"function setRoute(route, dataObj) {\n var path = route,\n data = [];\n if (dataObj !== null && dataObj !== undefined) {\n path += \"?\";\n for (var prop in dataObj) {\n if (prop !== 'undefined' && dataObj.hasOwnProperty(prop)) {\n data.push(prop + '=' + encodeURIComponent(dataObj[prop]));\n }\n }\n path += data.join('&');\n }\n\n //console.log('Router, setting URL fragment to: ' + path);\n\n updateURLFragment(path);\n }",
"doRouteBefore() {\n if (Routes.doAppRouteBefore) {\n Routes.doAppRouteBefore()\n }\n }",
"function showServerStarted() {\n var ifs = require('os').networkInterfaces();\n var currentIP = Object.keys(ifs)\n .map(x => [x, ifs[x].filter(x => x.family === 'IPv4')[0]])\n .filter(x => x[1])\n .map(x => x[1].address);\n\n dialog.showMessageBox({\n type: 'info',\n message: `Open http://${currentIP[1]}:3000/admin on another computer to control the cautions and warnings`,\n buttons: ['ok']\n });\n}",
"_beforeHandleRoute() {\n this._afterHandleRouteCalled = false;\n }",
"function showInitialPage(){\n\t// other initiations here\n\tformMessageReset();\n\tinitSettingVal(); // initial settings value\n\tinitNodeCompletion(); // initial public node completion list\n\tinitAddressCompletion();\n\n\tif(!settings.has('firstRun') || settings.get('firstRun') !== 0){\n\t\tchangeSection('section-settings');\n\t\tsettings.set('firstRun', 0);\n\t}else{\n\t\tchangeSection('section-welcome');\n\t}\n\n\tlet versionInfo = document.getElementById('walletShellVersion');\n\tif(versionInfo) versionInfo.innerHTML = WS_VERSION;\n\tlet wVersionInfo = document.getElementById('walletVersion');\n\tif(wVersionInfo) wVersionInfo.innerHTML = remote.app.getVersion();\n}",
"function displayRoute() {\r\n clearOverlays();\r\n var start\r\n var end\r\n if (inputLocation == \"\") { start = currentLocation; end = currentCafeLocation; }\r\n else { start = inputLocation; end = currentCafeLocation; }\r\n\r\n var directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get \"DirectionsRendererOptions\" object\r\n directionsDisplay.setMap(map); // map should be already initialized.\r\n\r\n var request = { origin: start, destination: end, travelMode: google.maps.TravelMode.DRIVING };\r\n var directionsService = new google.maps.DirectionsService();\r\n directionsService.route(request, function (response, status) {\r\n if (status == google.maps.DirectionsStatus.OK) {\r\n directionsDisplay.setDirections(response);\r\n }\r\n });\r\n markersArray.push(directionsDisplay);\r\n}",
"function setOrigin(name)\n{\n let port = localList.pickPortFromName(name);\n origin = port;//overwrite global variable.\n originHTML();\n\n route.origin = origin;\n route.wayPoints = []; //remove all way points.\n route.ship = \"\";\n route.departureDate = \"\";\n route.eta = \"\";\n route.distCalc();\n localStorage.setItem(\"route\", JSON.stringify(route));\n\n addOriginMarker();\n localStorage.setItem(\"origin\",JSON.stringify(origin));//store origin in local storage.\n storePortList(); //store port list into local storage.\n document.getElementById(\"next\").removeAttribute(\"disabled\");//enable user to proceed.\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
jabberDate somewhat opposit to hrTime (see above) expects a javascript Date object as parameter and returns a jabber date string conforming to JEP0082 | function jabberDate(date) {
if (!date.getUTCFullYear)
return;
var jDate = date.getUTCFullYear() + "-";
jDate += (((date.getUTCMonth()+1) < 10)? "0" : "") + (date.getUTCMonth()+1) + "-";
jDate += ((date.getUTCDate() < 10)? "0" : "") + date.getUTCDate() + "T";
jDate += ((date.getUTCHours()<10)? "0" : "") + date.getUTCHours() + ":";
jDate += ((date.getUTCMinutes()<10)? "0" : "") + date.getUTCMinutes() + ":";
jDate += ((date.getUTCSeconds()<10)? "0" : "") + date.getUTCSeconds() + "Z";
return jDate;
} | [
"function smppDate(jsDateObj) {\n\tvar uglyStr = '';\n\n\tuglyStr += jsDateObj.getFullYear().toString().substring(2);\n\n\tif (jsDateObj.getMonth() < 10) {\n\t\tuglyStr += '0';\n\t}\n\n\tuglyStr += jsDateObj.getMonth();\n\n\tif (jsDateObj.getDate() < 10) {\n\t\tuglyStr += '0';\n\t}\n\n\tuglyStr += jsDateObj.getDate();\n\n\tif (jsDateObj.getHours() < 10) {\n\t\tuglyStr += '0';\n\t}\n\n\tuglyStr += jsDateObj.getHours();\n\n\tif (jsDateObj.getMinutes() < 10) {\n\t\tuglyStr += '0';\n\t}\n\n\tuglyStr += jsDateObj.getMinutes();\n\n\treturn uglyStr;\n}",
"function WMIDateStringToDate(dtmDate)\r\n{\r\n if (dtmDate == null) { return \"null date\"; }\r\n var strDateTime;\r\n if (dtmDate.substr(4, 1) == 0) { strDateTime = dtmDate.substr(5, 1) + \"/\"; } \r\n else { strDateTime = dtmDate.substr(4, 2) + \"/\"; }\r\n if (dtmDate.substr(6, 1) == 0)\r\n { strDateTime = strDateTime + dtmDate.substr(7, 1) + \"/\"; }\r\n else { strDateTime = strDateTime + dtmDate.substr(6, 2) + \"/\"; }\r\n strDateTime = strDateTime + dtmDate.substr(0, 4) + \" \" +\r\n dtmDate.substr(8, 2) + \":\" +\r\n dtmDate.substr(10, 2) + \":\" +\r\n dtmDate.substr(12, 2);\r\n return(strDateTime);\r\n}",
"function date2str(date) {\n\n return pad(date.getFullYear(), 4, \"0\") + \"-\" +\n pad(date.getMonth() + 1, 2, \"0\") + \"-\" +\n pad(date.getDate(), 2, \"0\") + \"T\" +\n pad(date.getHours(), 2, \"0\") + \":\" +\n pad(date.getMinutes(), 2, \"0\") + \":\" +\n pad(date.getSeconds(), 2, \"0\") + \"Z\";\n}",
"function portalGetDateTime(valMonth, valDay, valYear, valHH, valMM)\r\n{\r\n //set the value \r\n var strDate = valMonth + '/' + valDay + '/' + valYear;\r\n strDate += ' ';\r\n strDate += valHH;\r\n\r\n strDate += ':';\r\n\r\n strDate += valMM;\r\n\r\n strDate += ':';\r\n\r\n //seconds are always zero!\r\n strDate += '00';\r\n\r\n return strDate;\r\n}",
"function GetRFC822Date(oDate)\n {\n var aMonths = new Array(\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \n \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\");\n \n var aDays = new Array( \"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\");\n var dtm = new String();\n \n dtm = aDays[oDate.getDay()] + \", \";\n dtm += pad(oDate.getDate()) + \" \";\n dtm += aMonths[oDate.getMonth()] + \" \";\n dtm += oDate.getFullYear() + \" \";\n dtm += pad(oDate.getHours()) + \":\";\n dtm += pad(oDate.getMinutes()) + \":\";\n dtm += pad(oDate.getSeconds()) + \" \" ;\n dtm += getTZOString(oDate.getTimezoneOffset());\n return dtm;\n }",
"function dateConvert(unixDate){\r\n var dateStr = new Date(unixDate * 1000)\r\n var n = dateStr.toDateString()\r\n var displayStr = n.substring(4, n.length)\r\n return \"(\" + displayStr + \")\"\r\n }",
"dateformat(date) { return \"\"; }",
"function timeStringAMPMDate(minutes, JD) {\n var julianday = JD;\n var floatHour = minutes / 60.0;\n var hour = Math.floor(floatHour);\n var floatMinute = 60.0 * (floatHour - Math.floor(floatHour));\n var minute = Math.floor(floatMinute);\n var floatSec = 60.0 * (floatMinute - Math.floor(floatMinute));\n var second = Math.floor(floatSec + 0.5);\n minute += (second >= 30)? 1 : 0;\n if (minute >= 60) {\n minute -= 60;\n hour ++;\n }\n if (hour > 23) {\n hour -= 24;\n julianday += 1.0;\n }\n if (hour < 0) {\n hour += 24;\n julianday -= 1.0;\n }\n var PM = false;\n if (hour > 12) {\n hour -= 12;\n PM = true;\n }\n if (hour == 12) {\n PM = true;\n }\n if (hour == 0) {\n PM = false;\n hour = 12;\n }\n var timeStr = hour + \":\";\n if (minute < 10) // i.e. only one digit\n timeStr += \"0\" + minute + ((PM)?\"PM\":\"AM\");\n else\n timeStr += minute + ((PM)?\"PM\":\"AM\");\n return timeStr + \" \" + calcDayFromJD(julianday);\n}",
"function formaterDatePubli(dateJson, format) {\n let dateJ = new Date(dateJson);\n let dateP = formater2Digits(dateJ.getDate()) + \"/\" +\n formater2Digits(dateJ.getMonth() + 1);\n if (format === \"jma\") {\n dateP += \"/\" + dateJ.getFullYear();\n }\n return dateP;\n}",
"function excelDateToJSDate(serial) {\n return new Date((serial - (25567 + 2 - 0.00000001)) * 86400 * 1000);\n}",
"function convertTime(date){\r\n var hh = date.getHours().toString();\r\n var mm = date.getMinutes().toString().length == 1? \"0\"+date.getMinutes().toString() : date.getMinutes().toString();\r\n return hh+\":\"+mm;\r\n}",
"function dateToString(date) {\n 'use strict'\n //function adds zeros if value < 10\n function addZero(i) {\n if (i < 10) {\n i = \"0\" + i;\n }\n return i;\n }\n\n return addZero(date.getDate()) + \".\" + (addZero(date.getMonth() + 1)) + \".\" + date.getFullYear() + \" \" + addZero(date.getHours()) + \":\" + addZero(date.getMinutes()) + \":\" + addZero(date.getSeconds());\n}",
"function transformDate(d) {\n return d.substr(6) + '-' + d.substr(3, 2) + '-' + d.substr(0, 2);\n }",
"function date_format(value, format) {\r\n\t\r\n\t//var datetime = (typeof(value)=='object' ? value : new Date(value)), \r\n\t//alert(format);\r\n\tvar result = format;\r\n\tvar datetime = new Date(value); /* (value instanceof Date ? value : new Date(value)),*/\r\n\tresult = result.replace('Y', datetime.getFullYear());\r\n\tresult = result.replace('d', datetime.getDate()<10 ? ('0'+ datetime.getDate()) : datetime.getDate()); \r\n\tresult = result.replace('m', (datetime.getMonth() + 1<10) ? ('0'+ (datetime.getMonth() + 1)) : (datetime.getMonth() + 1));\r\n\tresult = result.replace('H', (datetime.getHours()<10) ? ('0'+ datetime.getHours()) : datetime.getHours()); \r\n\tresult = result.replace('i', (datetime.getMinutes()<10) ? ('0'+ datetime.getMinutes()) : datetime.getMinutes());\r\n\tresult = result.replace('s', (datetime.getSeconds()<10) ? ('0'+ datetime.getSeconds()) : datetime.getSeconds());\r\n\tvar hours = datetime.getHours();\r\n\tresult = result.replace('a', (hours >= 12) ? 'pm' : 'am');\r\n\tvar ghours = hours > 12 ? (hours - 12) : hours;\r\n\tresult = result.replace('g', (ghours<10) ? ('0'+ ghours) : ghours);\r\n\treturn result;\r\n}",
"function formatDate(date) {\r\n var minutes = date.getMinutes(),\r\n hours = date.getHours() || 12,\r\n meridiem = \" PM\",\r\n formatted;\r\n \r\n if (hours > 12)\r\n hours = hours - 12;\r\n else if (hours < 12)\r\n meridiem = \" AM\";\r\n \r\n // don't want AM & PM, so add line with blank\r\n // if want to add later, then comment out this line \r\n meridiem = \"\";\r\n\r\n if (minutes < 10)\r\n formatted = hours + \":0\" + date.getMinutes() + meridiem;\r\n else\r\n formatted = hours + \":\" + date.getMinutes() + meridiem;\r\n\r\n return formatted;\r\n}",
"function getDebeDate() {\n let date = new Date();\n \n if(date.getUTCHours() < 4) {\n date.setDate(date.getDate() - 1);\n }\n return date.toJSON().split(\"T\")[0]\n}",
"function GetDataAttuale() {\r\n var dt = new Date();\r\n var yyyy = dt.getFullYear().toString();\r\n var mm = (dt.getMonth() + 1).toString();\r\n var dd = dt.getDate().toString();\r\n\r\n var hh = dt.getHours().toString();\r\n var nn = dt.getMinutes().toString();\r\n var ss = dt.getSeconds().toString();\r\n\r\n var result = yyyy + (mm[1] ? mm : \"0\" + mm[0]) + (dd[1] ? dd : \"0\" + dd[0]);\r\n var result2 = yyyy + (mm[1] ? mm : \"0\" + mm[0]) + (dd[1] ? dd : \"0\" + dd[0]) + (hh[1] ? hh : \"0\" + hh[0]) + (nn[1] ? nn : \"0\" + nn[0]) + (ss[1] ? ss : \"0\" + ss[0])\r\n\r\n\r\n return result2\r\n}",
"function dateWriter(year, month, day) {\n \n var date1 = new Date().toDateString();\n ; return date1;\n /*\n ;Output of above code is: Today's date is Sat Jun 02 2018\n ;close but doesn't pass in values and cannot get rid of Sat\n */\n // new Date().toLocaleDateString();\n // return Date();\n // ouput of above code is Today's date is \n // Sat Jun 02 2018 05:09:24 GMT-0500 (Central Daylight Time)\n // cannot get if formated that way I want\n // return dateWriter.day + \" \" + dateWriter.month + \", \" + dateWriter.year;\n // above code doesn't return \"fully qualified\" date object\n \n}",
"toDateString() {\n return `${this.nepaliYear.toString()}/${this.nepaliMonth}/${\n this.nepaliDay\n }`;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the name detected from code matches with explicitly documented name. Also true when no explicit name documented. | function code_matches_doc(docs, code) {
return docs.name === null || docs.name == code.name;
} | [
"function name_check() {\r\n name_warn();\r\n final_validate();\r\n}",
"function isExistingName(mO, fO, sO, name) {\r\n\r\n return (isExistingModuleOrLibName(name) ||\r\n isExistingFuncName(mO, name) ||\r\n isExistingGridNameInFunc(fO, name) ||\r\n isExistingLetNameInStep(sO, name) ||\r\n isExistingIndexVarNameInStep(sO, name) ||\r\n isKeyword(name));\r\n\r\n}",
"function checkName(name) {\n it('Name is defined: ' + name, function() {\n expect(name).toBeDefined();\n expect(name.length).not.toBe(0);\n });\n it('Name is a string', function() {\n expect(name).toEqual(jasmine.any(String));\n });\n }",
"is(name) {\n if (typeof name == 'string') {\n if (this.name == name) return true\n let group = this.prop(dist_NodeProp.group)\n return group ? group.indexOf(name) > -1 : false\n }\n return this.id == name\n }",
"exists(name) {\n return !!this._modifiers[name];\n }",
"function hasAccessibleName(vNode) {\n // testing for when browsers give a <section> a region role:\n // chrome - always a region role\n // firefox - if non-empty aria-labelledby, aria-label, or title\n // safari - if non-empty aria-lablledby or aria-label\n //\n // we will go with safaris implantation as it is the least common\n // denominator\n const ariaLabelledby = sanitize(arialabelledbyText(vNode));\n const ariaLabel = sanitize(arialabelText(vNode));\n\n return !!(ariaLabelledby || ariaLabel);\n}",
"function hasValidNameField(manifest) {\n return misc_utils_1.isTruthyString(manifest[ManifestFieldNames.Name]);\n}",
"function is_predef_app(name) {\n var rule = get_predefined_rules(name);\n\n if(rule.length) {\n rule = rule.split(\"\\x02\");\n if(rule[_category] == CATEGORY_APP) {\n return true;\n }\n }\n return false;\n}",
"function hasMultipleInstancesOfName( name ){\n\treturn usedNames[ name ] > 1;\n}",
"function extPart_getIsIdentifier(groupName, partName)\n{\n var partType = extPart.getPartType(groupName, partName);\n return (!partType || partType == \"identifier\");\n}",
"hasIdentifierDescriptor() {\n return this.__getIdentifierDescriptor() !== undefined;\n }",
"function tagTester(name) {\n var tag = '[object ' + name + ']';\n return function(obj) {\n return _setup[\"t\" /* toString */].call(obj) === tag;\n };\n}",
"function nameMatchesRawTag(lowercaseName, tags) {\n for (let i = 0; i < keysToTestForGenericValues.length; i++) {\n let key = keysToTestForGenericValues[i];\n let val = tags[key];\n if (val) {\n val = val.toLowerCase();\n if (key === lowercaseName ||\n val === lowercaseName ||\n key.replace(/\\_/g, ' ') === lowercaseName ||\n val.replace(/\\_/g, ' ') === lowercaseName) {\n return true;\n }\n }\n }\n return false;\n }",
"function isExistingIndexVarNameInStep(sO, name) {\r\n\r\n for (var d = 0; d < sO.dimNameExprs.length; d++) {\r\n\r\n if (sO.dimNameExprs[d].str == name)\r\n return true;\r\n }\r\n\r\n return false;\r\n}",
"function nameValidation() {\n // Name validation\n const nameValue = name.value;\n const nameValidator = /[a-zA-z]+/.test(nameValue);\n\n return nameValidator;\n}",
"isAssis(name){\n for(u in this.assisList){\n if(u.name == name){\n return true;\n }\n }\n return false;\n }",
"function isIdentifier (s) {\n \treturn /^[a-z]+$/.test(s);\n}",
"supports(name) {\r\n const isEvent = this.supportedEvents.includes(name);\r\n const isMethod = typeof this[name] === 'function';\r\n return isEvent || isMethod;\r\n }",
"isRegisterName(str) {\n return this.architecture.hasRegisterName(str);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
String > Union Converts a string into a union of all characters in the string | function charUnion(chars) {
const tokenized = chars.split('').map(c => char(c));
return new Desugarer(empty()).arbitrary_union(tokenized);
} | [
"function Union() {\n var alternatives = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n alternatives[_i] = arguments[_i];\n }\n var match = function () {\n var cases = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n cases[_i] = arguments[_i];\n }\n return function (x) {\n for (var i = 0; i < alternatives.length; i++) {\n if (alternatives[i].guard(x)) {\n return cases[i](x);\n }\n }\n };\n };\n var self = { tag: 'union', alternatives: alternatives, match: match };\n return (0, runtype_1.create)(function (value, visited) {\n var e_1, _a, e_2, _b, e_3, _c, e_4, _d;\n if (typeof value !== 'object' || value === null) {\n try {\n for (var alternatives_1 = __values(alternatives), alternatives_1_1 = alternatives_1.next(); !alternatives_1_1.done; alternatives_1_1 = alternatives_1.next()) {\n var alternative = alternatives_1_1.value;\n if ((0, runtype_1.innerValidate)(alternative, value, visited).success)\n return (0, util_1.SUCCESS)(value);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (alternatives_1_1 && !alternatives_1_1.done && (_a = alternatives_1.return)) _a.call(alternatives_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return util_1.FAILURE.TYPE_INCORRECT(self, value);\n }\n var commonLiteralFields = {};\n try {\n for (var alternatives_2 = __values(alternatives), alternatives_2_1 = alternatives_2.next(); !alternatives_2_1.done; alternatives_2_1 = alternatives_2.next()) {\n var alternative = alternatives_2_1.value;\n if (alternative.reflect.tag === 'record') {\n var _loop_1 = function (fieldName) {\n var field = alternative.reflect.fields[fieldName];\n if (field.tag === 'literal') {\n if (commonLiteralFields[fieldName]) {\n if (commonLiteralFields[fieldName].every(function (value) { return value !== field.value; })) {\n commonLiteralFields[fieldName].push(field.value);\n }\n }\n else {\n commonLiteralFields[fieldName] = [field.value];\n }\n }\n };\n for (var fieldName in alternative.reflect.fields) {\n _loop_1(fieldName);\n }\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (alternatives_2_1 && !alternatives_2_1.done && (_b = alternatives_2.return)) _b.call(alternatives_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n for (var fieldName in commonLiteralFields) {\n if (commonLiteralFields[fieldName].length === alternatives.length) {\n try {\n for (var alternatives_3 = (e_3 = void 0, __values(alternatives)), alternatives_3_1 = alternatives_3.next(); !alternatives_3_1.done; alternatives_3_1 = alternatives_3.next()) {\n var alternative = alternatives_3_1.value;\n if (alternative.reflect.tag === 'record') {\n var field = alternative.reflect.fields[fieldName];\n if (field.tag === 'literal' &&\n (0, util_1.hasKey)(fieldName, value) &&\n value[fieldName] === field.value) {\n return (0, runtype_1.innerValidate)(alternative, value, visited);\n }\n }\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (alternatives_3_1 && !alternatives_3_1.done && (_c = alternatives_3.return)) _c.call(alternatives_3);\n }\n finally { if (e_3) throw e_3.error; }\n }\n }\n }\n try {\n for (var alternatives_4 = __values(alternatives), alternatives_4_1 = alternatives_4.next(); !alternatives_4_1.done; alternatives_4_1 = alternatives_4.next()) {\n var targetType = alternatives_4_1.value;\n if ((0, runtype_1.innerValidate)(targetType, value, visited).success)\n return (0, util_1.SUCCESS)(value);\n }\n }\n catch (e_4_1) { e_4 = { error: e_4_1 }; }\n finally {\n try {\n if (alternatives_4_1 && !alternatives_4_1.done && (_d = alternatives_4.return)) _d.call(alternatives_4);\n }\n finally { if (e_4) throw e_4.error; }\n }\n return util_1.FAILURE.TYPE_INCORRECT(self, value);\n }, self);\n}",
"function vector_1(s) /* (s : string) -> vector<char> */ {\n return _string_to_chars(s);\n}",
"function getUniversalCharString(){\n // Get lowercase options//\nif (lowerCasePref === true)\nuniversalCharacters = universalCharacters+lowerCharacters; \n\n// Get get upperCase char//\nif (upperCasePref === true)\nuniversalCharacters = universalCharacters+upperCharacters;\n\n// Get get numbers char//\nif (numbersPref === true)\nuniversalCharacters = universalCharacters+numbers;\n\n// Get get special char//\nif (specialPref === true)\nuniversalCharacters = universalCharacters+specialCharacters;\nreturn universalCharacters;\n\n}",
"function getUniqueChars (arrayOfStrings) {\n let uniqueChars = [];\n\n arrayOfStrings.forEach(string => {\n string.split('').forEach(char => {\n if (!uniqueChars.includes(char)) uniqueChars.push(char);\n });\n });\n\n return uniqueChars;\n}",
"function intersectionOfUnionBySetOperations(container, toUnion) {\n if (toUnion.length === 0) {\n return container;\n }\n var intersected = [];\n for (var i = 0; i < toUnion.length; i++) {\n intersected.push(container.intersection(toUnion[i]));\n }\n var result = intersected[0];\n for (var i = 1; i < intersected.length; i++) {\n result = result.union(intersected[i]);\n }\n return result;\n }",
"function ak2uy ( akstr )\n{\n var tstr = \"\" ;\n for ( i = 0 ; i < akstr.length ; i++ ) {\n code = akstr.charCodeAt(i) ;\n if ( code < BPAD || code >= BPAD + akmap.length ) {\n tstr = tstr + akstr.charAt(i) ; \n continue ;\n }\n\n code = code - BPAD ; \n\n if ( code < akmap.length && akmap[code] != 0 ) {\n tstr = tstr + String.fromCharCode ( akmap[code] ) ;\n } else {\n tstr = tstr + akstr.charAt(i) ; \n }\n }\n\n return tstr ;\n}",
"union(otherSet) {\n let newSet = new BetterSet(this);\n newSet.addAll(otherSet);\n return newSet;\n }",
"function solve(s) {\n\tlet result = \"\";\n\tlet regex = /[aeiou]/;\n\tlet consonants = s\n\t\t.split(\"\")\n\t\t.filter(char => {\n\t\t\treturn !regex.test(char);\n\t\t})\n\t\t.sort((a, b) => {\n\t\t\treturn a.charCodeAt(0) - b.charCodeAt(0);\n\t\t});\n\tlet vowels = s\n\t\t.split(\"\")\n\t\t.filter(char => {\n\t\t\treturn regex.test(char);\n\t\t})\n\t\t.sort((a, b) => {\n\t\t\treturn a.charCodeAt(0) - b.charCodeAt(0);\n\t\t});\n\tif (consonants.length > vowels.length) {\n\t\tfor (let i = 0; i < consonants.length; i++) {\n\t\t\tif (!vowels[i]) {\n\t\t\t\tresult += consonants[consonants.length - 1];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += consonants[i];\n\t\t\tresult += vowels[i];\n\t\t}\n\t} else {\n\t\tfor (let i = 0; i < vowels.length; i++) {\n\t\t\tif (!consonants[i]) {\n\t\t\t\tresult += vowels[vowels.length - 1];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += vowels[i];\n\t\t\tresult += consonants[i];\n\t\t}\n\t}\n\tif (result.length !== s.length) {\n\t\treturn \"failed\";\n\t} else {\n\t\treturn result;\n\t}\n}",
"function union(){\n //let arg = [].slice.call(arguments);\n let uniq = [];\n let arr = [];\n //solving it with CONCAT!!\n for(let i=0; i<arguments.length; i++){\n \t//CONACAT RETURNS A NEW ARR, which REFERENCE has to be saved in this case using the same arr var.\n arr = arr.concat(arguments[i]);\n }\n //solving it with PUSH!!\n // for (let i=0; i<arguments.length; i++){\n // for (let j=0; j<arguments[i].length; j++){\n // //console.log(\"arg[i][j] is \" + arg[i][j]);\n // uniq.push(arguments[i][j]);\n // }\n // }\n for (let j=0; j<arr.length; j++){\n if (!uniq.includes(arr[j])) uniq.push(arr[j]);\n }\n \n return uniq;\n}",
"function powerSet (str) {\n var subsets = {};\n\n for (var i = 0; i < str.length; i++) {\n subsets[str[i]] = true;\n }\n\n var uniqueChars = Object.keys(subsets).sort();\n\n function findSubsets(subset, chars) {\n subsets[subset.sort().join(\"\")] = true;\n if (chars.length === 0) return;\n\n for (var j = 0; j < chars.length; j++) {\n findSubsets(subset.concat(chars[j]), chars.slice(0, j).concat(chars.slice(j+1)));\n }\n }\n\n findSubsets([\"\"], uniqueChars);\n return Object.keys(subsets);\n}",
"function stringsAndNumbers(){\n return strings.concat(numbers);\n}",
"shifter(str) {\n\t\tlet newString = '';\n\t\tfor (const char of str) {\n\t\t\tnewString += /[a-z]/.test(char) ? String.fromCharCode(((char.charCodeAt(0) - 18) % 26) + 97) : char;\n\t\t}\n\t\treturn newString;\n\t}",
"function strToarry(str){\n var reg1=/^\"|^'|'$|\"$/g//去掉前面的引号\n var reg2=/^\\[|]$/g//去掉前面的括号\n var reg3=/('\\s*,\\s*')/gi\n var reg4=/(\"\\s*,\\s*\")/gi\n var reg5=/'|\"/gi\n var tmp;\n if(reg3.test(str)){\n tmp=str.replace(reg1,\"\").replace(reg2,\"\").replace(reg3,\"'&_#'\").replace(reg5,\"\").split(\"&_#\");\n if(isArray(tmp)){\n return tmp;\n }\n }\n if(reg4.test(str)){\n tmp=str.replace(reg1,\"\").replace(reg2,\"\").replace(reg4,\"'&_#'\").replace(reg5,\"\").split(\"&_#\");\n if(isArray(tmp)){\n return tmp;\n }\n }\n else{\n tmp=str.replace(reg1,\"\").replace(reg2,\"\").replace(reg5,\"\").split(\",\");\n if(isArray(tmp)){\n return tmp;\n }\n }\n return str;\n}",
"function getAlphabet(string) {\n\t\treturn Array.from(string)\n\t\t\t.map(symbol => symbol.charCodeAt(0))\n\t\t\t.sort((t1, t2) => t1 > t2)\n\t\t\t.filter((symbol, loc, symbols) => loc === 0 || symbol !== symbols[loc - 1]);\n\t}",
"function splitAndMerge(str,sp){\n return str.split(\" \").join(\"\").split(\"\").join(sp)\n \n }",
"function getUnionVector(v1, v2) {\r\n\t//clone v1\r\n\tvar retval = v1.slice(0);\r\n\r\n\tfor (var i = 0; i < v2.length; i++) {\r\n\t\tvar obj = v2[i];\r\n\r\n\t\tif(!v1.contains(obj)) {\r\n\t\t\tretval.push(obj);\r\n\t\t}\r\n\t}\r\n\r\n\treturn retval;\r\n}",
"function unmangleUnicode(str) {\n var result = '';\n for (var i = 0, len = str.length; i < len; i += 2) {\n result += str.charAt(i);\n }\n return result;\n}",
"function string_1(_arg1) /* (vector<char>) -> string */ {\n return _chars_to_string(_arg1);\n}",
"function strConvert() {\n let result = \"\";\n for (let i = 0; i < 4; i++) {\n result += randCombo[i];\n\n }\n return result;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
date Grand total fn over / date Sub+Grand total fn | function grandsub() {
subtotal();
grandtotal();
carthide();
} | [
"function billTotal(subTotal){\nreturn subTotal + (subTotal * .15) + (subTotal * .095);\n}",
"function total() {\n\n let dayOfWeek = new Date().getDay();\n let sub = parseFloat(document.getElementById(\"subtotal\").value);\n let newsubtotal;\n let trueTotal;\n \n//Processing\n\n \n if (sub >= 50 && (dayOfWeek == 2 || dayOfWeek == 3)) {\n newsubtotal = (sub * .9);\n } else {\n newsubtotal = (sub);\n }\n \n trueTotal = (newsubtotal * 1.06);\n \n//Output\n document.getElementById(\"output\").innerHTML = \"Their total is: \" + trueTotal.toFixed(2);\n}",
"function calculateTotalAmount()\n{\n\tvar tableProductLength = $(\"#addSubExpensesTable tbody tr\").length;\n\tvar totalAmount = 0;\n\tfor(x = 0; x < tableProductLength; x++) {\n\t\tvar tr = $(\"#addSubExpensesTable tbody tr\")[x];\n\t\tvar count = $(tr).attr('id');\n\t\tcount = count.substring(3);\n\t\t\t\t\t\n\t\ttotalAmount = Number(totalAmount) + Number($(\"#subExpensesAmount\"+count).val());\n\n\n\t} // /for\n\n\ttotalAmount = totalAmount.toFixed(2);\n\n\t// sub total\n\t$(\"#totalAmount\").val(totalAmount);\n\t$(\"#totalAmountValue\").val(totalAmount);\n\t\n}",
"function userTotals(total, num) {\n return total + num;\n }",
"function calculateGroupTotal(cellsToTotal, totalTd, groupTotalDiv, rowIndex, columnIndex) {\n\n var total = 0;\n var values = new Array();\n var hasInvalidValues = false;\n var extraData = groupTotalDiv.data(\"params\");\n var functionName = groupTotalDiv.data(\"function\");\n\n for (var i = 0; i < cellsToTotal.length; i++) {\n var currentCell = cellsToTotal[i];\n var isCellObject = currentCell != null && typeof currentCell === 'object';\n\n var value;\n\n //check if cell is a cellObject - using mData setting\n if (isCellObject) {\n value = currentCell.val;\n\n if (value == null) {\n value = \"\";\n }\n }\n\n var isAddLine = !isCellObject && currentCell\n && jQuery(currentCell).find(\":input[name^='newCollectionLines']\").length;\n\n // skip over add line\n if (!isAddLine) {\n value = coerceTableCellValue(currentCell, true);\n }\n else {\n continue;\n }\n\n value = convertComplexNumericValue(value);\n\n //set hasInvalidValues to true if value is undefined\n if (value == undefined || (value && !jQuery.isNumeric(value))) {\n hasInvalidValues = true;\n continue;\n }\n\n //skip over value when blank\n if (value != \"\") {\n value = parseFloat(value);\n values.push(value);\n }\n }\n\n if (!hasInvalidValues) {\n if (extraData != undefined) {\n total = window[functionName](values, extraData);\n }\n else {\n total = window[functionName](values);\n }\n }\n else {\n total = \"N/A\";\n }\n\n var groupTotalDisplay = totalTd.find(\"div[data-role='groupTotal'][data-function='\" + functionName + \"']\");\n //clone and append, if no place to display the total has been generated yet\n if (groupTotalDisplay.length == 0) {\n groupTotalDisplay = groupTotalDiv.clone();\n //resetting ids to unique ids on the clone\n groupTotalDisplay = groupTotalDisplay.attr(\"id\", groupTotalDisplay.attr(\"id\") + \"_\" + rowIndex + columnIndex);\n groupTotalDisplay.find(\"[id]\").each(function () {\n jQuery(this).attr(\"id\", jQuery(this).attr(\"id\") + \"_\" + rowIndex + columnIndex);\n });\n totalTd.append(groupTotalDisplay);\n groupTotalDisplay.show();\n }\n\n var totalValueSpan = groupTotalDisplay.find(\"span[data-role='totalValue']\");\n\n if (totalValueSpan.length) {\n totalValueSpan.html(total);\n }\n else {\n var newSpan = jQuery(\"<span data-role='totalValue'>\" + total + \"</span>\");\n groupTotalDisplay.append(newSpan);\n }\n\n}",
"function _totalTaxTable() {\n \ttry {\n \t\tvar total_header \t=\t$('.total-header').text().trim();\n \t\tvar freight_val\t\t=\t0;\n \t\tvar insurance_val\t=\t0;\n \t\tvar tax_jp \t\t\t=\t0;\n \t\tif (!$('.value-freight').hasClass('hidden')) {\n\t \t\tfreight_val \t= \t$('.value-freight').val().trim();\n\t\t}\n \t\tif (!$('.value-insurance').hasClass('hidden')) {\n\t\t\tinsurance_val \t= \t$('.value-insurance').val().trim();\n\t\t}\n \t\tif (!$('.value-jp').hasClass('hidden')) {\n\t\t\ttax_jp \t\t\t= \t$('.value-jp').val().trim();\n\t\t}\n\t\tvar total_footer \t=\tparseFloat(freight_val) + parseFloat(insurance_val) + parseFloat(tax_jp) + parseFloat(total_header);\n\t\t$('.total-footer').text(_convertMoneyToIntAndContra(total_footer));\n\t} catch (e) {\n alert('_totalTaxTable' + e.message);\n }\n }",
"function TotalSpendings(props) {\n let classes = props.fadeout ? 'tile fade-out' : 'tile';\n const today = new Date();\n const totalToday = Utils.calculateSumOfSpendings(Utils.filterSpendingsByDay(props.spendings, today));\n const totalWeek = Utils.calculateSumOfSpendings(Utils.filterSpendingsByWeek(props.spendings, today));\n const totalMonth = Utils.calculateSumOfSpendings(Utils.filterSpendingsByMonth(props.spendings, today));\n const totalYear = Utils.calculateSumOfSpendings(Utils.filterSpendingsByYear(props.spendings, today));\n return (\n <div className={classes}>\n <button className=\"close-tile\" title=\"Close\" onClick={() => props.toggleDisplay('totalSpendings')}>\n x\n </button>\n <h4>Total Spendings</h4>\n <table className=\"table-spendings\">\n <tbody>\n <tr>\n <td>Today:</td>\n <td className=\"cell-amount\">{totalToday.toLocaleString(props.locale, props.currencyOptions)}</td>\n </tr>\n <tr>\n <td>This week:</td>\n <td className=\"cell-amount\">{totalWeek.toLocaleString(props.locale, props.currencyOptions)}</td>\n </tr>\n <tr>\n <td>This month:</td>\n <td className=\"cell-amount\">{totalMonth.toLocaleString(props.locale, props.currencyOptions)}</td>\n </tr>\n <tr>\n <td>This year:</td>\n <td className=\"cell-amount\">{totalYear.toLocaleString(props.locale, props.currencyOptions)}</td>\n </tr>\n </tbody>\n </table>\n </div>\n );\n}",
"function totalCreditsAndQualityPoints(e){\n \n var credit = parseFloat($(e.currentTarget).parent('td').parent('tr').find('input[name=\"credit\"], select[name=\"credit\"] option:selected').val());\n var gpa = $(e.currentTarget).parent('td').parent('tr').find('input[name=\"gpa\"]').val();\n var grade = $(e.currentTarget).parent('td').parent('tr').find('input[name=\"grade\"], select[name=\"grade\"]').val(); \n \n if($('input[name=\"gpa\"]')){ //calculate GPA\n var qualityPointsFirstRowTotal = totalQualityPointsPerRow(parseFloat(gpa, 10), credit); \n $(e.currentTarget).parent('td').parent('tr').find('#qualityPointsFirstRow').text(qualityPointsFirstRowTotal);\n \n }\n if($('select[name=\"grade\"]')){ //calculate Grade\n var qualityPointsPerRowTotal = totalQualityPointsPerRow(parseFloat(computeGradeNum(grade), 10), parseFloat(credit, 10));\n $(e.currentTarget).parent('td').parent('tr').find('#qualityPoints').text(qualityPointsPerRowTotal);\n \n }\n \n var totalAllCredits = 0;\n var totalAllQualityPoints = 0;\n \n totalAllQualityPoints = calculatePoints($allQualityPoints, totalAllQualityPoints);\n totalAllCredits = calculateCredits($allCredits, totalAllCredits);\n \n $('#newCumulativeCredits').text(totalAllCredits); \n $('#newCumulativeQualityPoints').text(totalAllQualityPoints);\n \n overallGPA();\n }",
"function updateOppProjectedTotal(recOpp){\r\n\t\t\r\n\t\tvar arExcludeItemTypes = ['SUBTOTAL', 'DESCRIPTION'];\r\n\t\tvar arSpecialItemTypes = ['DISCOUNT', 'MARKUP']; //item types that depend on the preceding item line\r\n\t\tvar bApply3YrCalcToSpecItemTypes = true; //if true, the 3-yr calculation will apply to discount and markup\r\n\t\t//log.debug('updateOppProjectedTotal', 'bApply3YrCalcToSpecItemTypes: ' + bApply3YrCalcToSpecItemTypes);\r\n\t\t\r\n\t\tvar ar3YrItems;\r\n\t\tvar st3YrItems = runtime.getCurrentScript().getParameter({name: 'custscript_3yr_special_items'}); //may be comma-separated list of item ids\r\n\t\tif(st3YrItems){\r\n\t\t\tar3YrItems = st3YrItems.split(\",\");\r\n\t\t}\r\n\t\t\r\n\t\tvar stProjTotalOld = recOpp.getValue({\r\n\t\t\tfieldId : 'projectedtotal'\r\n\t\t});\r\n\t\tvar intCount = recOpp.getLineCount({\r\n\t\t\tsublistId : 'item'\r\n\t\t});\r\n\t\t\r\n\t\tvar stItem;\r\n\t\tvar stPrevItem;\r\n\t\tvar stItemType;\r\n\t\tvar stAmount;\r\n\t\tvar flProjTotal = 0;\r\n\t\t\r\n\t\tfor(var i = 0; i < intCount; i++){\r\n\t\t\t\r\n\t\t\tstItem = recOpp.getSublistValue({\r\n\t\t\t\tsublistId : 'item',\r\n\t\t\t\tfieldId : 'item',\r\n\t\t\t\tline : i\r\n\t\t\t});\r\n\t\t\t\r\n\t\t\tstAmount = recOpp.getSublistValue({\r\n\t\t\t\tsublistId : 'item',\r\n\t\t\t\tfieldId : 'amount',\r\n\t\t\t\tline : i\r\n\t\t\t});\r\n\t\t\t\r\n\t\t\tstAmount = recOpp.getSublistValue({\r\n\t\t\t\tsublistId : 'item',\r\n\t\t\t\tfieldId : 'amount',\r\n\t\t\t\tline : i\r\n\t\t\t});\r\n\t\t\tstAmount = stAmount ? stAmount : '0'; //for when amount is empty\r\n\t\t\t\r\n\t\t\tstItemType = recOpp.getSublistValue({\r\n\t\t\t\tsublistId : 'item',\r\n\t\t\t\tfieldId : 'itemtype',\r\n\t\t\t\tline : i\r\n\t\t\t});\r\n\t\t\t\r\n\t\t\t//Skip some item types\r\n\t\t\tif(arExcludeItemTypes.indexOf(stItemType.toUpperCase()) > -1){\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t//Calculate projected total\r\n\t\t\tif(ar3YrItems && ar3YrItems.indexOf(stItem) > -1){ \t\t\t\t\t//current line item is a 3-yr product\r\n\t\t\t\t\r\n\t\t\t\tflProjTotal += parseFloat(stAmount) / 3;\r\n\t\t\t\t\r\n\t\t\t} else if(bApply3YrCalcToSpecItemTypes \t\t\t\t\t\t\t\t//apply 3-yr calc to discount, markup\r\n\t\t\t\t&& arSpecialItemTypes.indexOf(stItemType.toUpperCase()) > -1 \t//current line item is a discount, markup\r\n\t\t\t\t&& ar3YrItems && ar3YrItems.indexOf(stPrevItem) > -1){\t\t\t//previous line item is a 3-yr product\r\n\t\t\t\t\t\r\n\t\t\t\tflProjTotal += parseFloat(stAmount) / 3;\r\n\t\t\t\t\r\n\t\t\t} else {\r\n\t\t\t\t\r\n\t\t\t\tflProjTotal += parseFloat(stAmount);\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t//Take note of the line item\r\n\t\t\tif(arSpecialItemTypes.indexOf(stItemType.toUpperCase()) < 0\t\t\t//current line item is not discount, markup\r\n\t\t\t\t&& arExcludeItemTypes.indexOf(stItemType.toUpperCase()) < 0){\t//current line item is not subtotal, description\r\n\t\t\t\tstPrevItem = stItem;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tlog.debug('updateOppProjectedTotal', 'old projtotal: ' + stProjTotalOld + ' | new projtotal: ' + flProjTotal);\r\n\t\t\r\n\t\t//Update Opportunity Projected Total\r\n\t\tif(flProjTotal != parseFloat(stProjTotalOld)){\r\n\t\t\trecord.submitFields({\r\n\t\t\t\ttype: record.Type.OPPORTUNITY,\r\n\t\t\t\tid: recOpp.id,\r\n\t\t\t\tvalues: {\r\n\t\t\t\t\tprojectedtotal : flProjTotal\r\n\t\t\t\t},\r\n\t\t\t\toptions: {\r\n\t\t\t\t\tenableSourcing: false,\r\n\t\t\t\t\tignoreMandatoryFields : true\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t\t\r\n\t\t\tlog.debug('updateOppProjectedTotal', 'updated projected total of opp: ' + recOpp.id);\r\n\t\t}\r\n\t}",
"function calcTotal(){\n\n //Variable to hold total of all expense rows\n var totalExp = 0;\n\n //Adds values from row to totalExp\n for (j = 1; j <= 4; j++){\n totalExp += calcRow(j);\n }\n\n return totalExp;\n}",
"calTotalCharged(){\n this._totalCharged = this._costPerHour * this._hoursParked;\n }",
"function calcTotalDayAgain() {\n var eventCount = $this.find('.everyday .event-single').length;\n $this.find('.total-bar b').text(eventCount);\n $this.find('.events h3 span b').text($this.find('.events .event-single').length)\n }",
"function updateTotals(initialTotal){\n\tvar tempTotal = 0.00;\n\tvar donsTotal = 0.00;\n\tvar membershipTotal = 0.00;\n\tvar subsTotal = 0.00;\n\n\tvar subItems = '';\n\tvar cartItems = '';\n\n\tif(initialTotal != undefined){\n\t\ttempTotal = parseFloat(initialTotal);\n\t}\n\t//all subscription type items\n\t//cycles thorugh all items where class='subItem\n\t//id = subsriptionname\n\t//value = price\n\t//name = type of subscription\n\t$('.subItem').each(function(){\n\t\tif(this.checked){\n\t\t\tif(this.name==\"SUBSCRIPTIONNAME\"){\n\t\t\t\tsubsTotal += parseFloat(this.value);\n\t\t\t}\n\t\t\tif(this.name==\"MEMBERSHIPNAME\"){\n\t\t\t\tmembershipTotal += parseFloat(this.value);\n taxTotal = getMembershipTax( $(this).attr(\"id\"), $(\"#State\").val() );\n\t\t\t}\n\n\t\t\tsubItems += this.id+',';\n\t\t\ttempTotal += parseFloat(this.value) + parseFloat(taxTotal);\n\t\t}\n\n\t\tif((this.type==\"text\") && (parseFloat(this.value) > 0.00)){\n\t\t\tif(this.name==\"DONATIONNAME\"){\n\t\t\t\tdonsTotal += parseFloat(this.value);\n\t\t\t\tsubItems += this.id + '=' +this.value + ',';\n\t\t\t\ttempTotal += parseFloat(this.value);\n\t\t\t}\n\t\t}\n\t});\n\n\t$('#subsTotal').html(parseFloat(subsTotal).toFixed(2));\n\t$('#membershipTotal').html(parseFloat(membershipTotal).toFixed(2));\n\t$('#donsTotal').html(parseFloat(donsTotal).toFixed(2));\n\t$('#totalAmt').html(parseFloat(tempTotal).toFixed(2));\n\n\t//trim trailing comma off subitems\n\t$('#SUBITEMS').val(subItems.substring(0,subItems.length-1));\n\t//debug('Subitems: '+$('SUBITEMS').value);\n}",
"function itemCallback(data){\n subtotal(data.salePrice);\n}",
"function updateTotal(){\n if(lastOp == \"+\"){\n $(\"#history\").html(lastVal + \"+\" + currentVal)\n total = parseFloat(lastVal) + parseFloat(currentVal);\n lastVal = total;\n currentVal = total;\n $(\"#total\").html(total.toString());\n }\n if(lastOp == \"-\"){\n $(\"#history\").html(lastVal + \"-\" + currentVal)\n total = parseFloat(lastVal) - parseFloat(currentVal);\n lastVal = total;\n currentVal = total;\n $(\"#total\").html(total.toString());\n }\n if(lastOp == \"*\"){\n $(\"#history\").html(lastVal + \"*\" + currentVal)\n total = parseFloat(lastVal) * parseFloat(currentVal);\n lastVal = total;\n currentVal = total;\n $(\"#total\").html(total.toString());\n }\n if(lastOp == \"/\"){\n $(\"#history\").html(lastVal + \"/\" + currentVal)\n total = parseFloat(lastVal) / parseFloat(currentVal);\n lastVal = total;\n currentVal = total;\n $(\"#total\").html(total.toString());\n }\n }",
"function friendTotals(total, num) {\n return total + num;\n }",
"function addToAnnualTotals(record) {\n for(var field in record.totals) {\n if (record.totals.hasOwnProperty(field)) {\n if (!$scope.annualTotals.hasOwnProperty(field)) {\n $scope.annualTotals[field] = 0;\n }\n $scope.annualTotals[field] += record.totals[field];\n }\n }\n }",
"function propertyAppreciation(propertyLoan, propertyPurchase, globalData, yearlyChanges, sale, selScen, month, loanPayment, monDep){\n\tvar curPropValue = propertyPurchase[selScen].purchasePrice * Math.pow(1 + ((yearlyChanges[selScen].propertyAppreciation/100)/12), month); //B40\n\tvar salesCharge = curPropValue * sale[selScen].commission/100; //B41\n\tvar costBasis = (propertyPurchase[selScen].closingCost/100 + 1) * propertyPurchase[selScen].purchasePrice + propertyPurchase[selScen].capitalImprovement;\n\tvar taxGain = ((curPropValue - salesCharge - costBasis) * globalData[selScen].longTermCapitalGain/100); //B43\n\tvar totalInitialPayment = propertyPurchase[selScen].closingCost/100 * propertyPurchase[selScen].purchasePrice + propertyPurchase[selScen].capitalImprovement + \n\t\tpropertyPurchase[selScen].purchasePrice * propertyLoan.downPayment/100; //PB35\n\n\treturn (((curPropValue - salesCharge - loanPayment.endingBalance[month]) - taxGain) - totalInitialPayment);\n}//propertyAppreciation",
"function calculateage(yr, mon, day, unit, indecimal)\r\n{\r\n var one_day = 1000*60*60*24;\r\n var one_month = 1000*60*60*24*30;\r\n var one_year = 1000*60*60*24*30*12;\r\n\r\n var today = new Date();\r\n var pastdate = new Date(yr, mon-1, day);\r\n\r\n var countunit = unit;\r\n var decimals = indecimal;\r\n\r\n finalunit = (countunit == \"days\")? one_day : (countunit == \"months\")? one_month : one_year;\r\n decimals = (decimals <= 0)? 1 : decimals*10;\r\n\r\n if (unit != \"years\")\r\n {\r\n return (Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals);\r\n }\r\n else\r\n {\r\n yearspast=today.getFullYear()-yr-1;\r\n tail=(today.getMonth()>mon-1 || today.getMonth()==mon-1 && today.getDate()>=day)? 1 : 0;\r\n pastdate.setFullYear(today.getFullYear());\r\n pastdate2=new Date(today.getFullYear()-1, mon-1, day);\r\n tail=(tail==1)? tail+Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals : Math.floor((today.getTime()-pastdate2.getTime())/(finalunit)*decimals)/decimals;\r\n return (yearspast+tail);\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
callback to set customers | function setCustomers(data) {
//check for errors
$scope.errors = [];
//if duplicate error!
if (data['duplicate_error']) {
$scope.errors.push(data['duplicate_error']);
} else if (data['errors']) {
for(var i in data['errors']) {
$scope.errors.push(data['errors'][i].message);
}
} else {
$scope.customers = data;
$scope.newCustomer = {};
}
} | [
"updateCustomerList() {\r\n this.customers = this.calculateCustomerInfo(this.orders);\r\n }",
"function changeCustomer(v){\r\n\r\n\t\t//var x = document.getElementById(\"mySelect\").selectedIndex;\r\n\t\t//alert(document.getElementsByTagName(\"option\")[x].value);\r\n\r\n\t\tvar index = document.getElementById(\"custList\").selectedIndex\r\n\t\tvar aCustomer = TB.CustomersData['customers'][index];\r\n\t\r\n\t\tTB.setIdValue('Address', aCustomer['Address']);\r\n\t\tTB.setIdValue('City', aCustomer['City']);\r\n\t\tTB.setIdValue('PostalCode', aCustomer['PostalCode']);\r\n\t\tTB.setIdValue('Country', aCustomer['Country']);\r\n\r\n\t\t//In the \"Ship To:\" section set the new ShipName, ShipAddress, ShipCity, ShipPostalCode, ShipCountry\r\n\t\tvar x = document.getElementsByTagName(\"input\");\r\n x[\"ShipName\"].value\t\t\t= aCustomer['CompanyName'];\r\n\t\tx[\"ShipAddress\"].value\t\t= aCustomer['Address'];\r\n\t\tx[\"ShipCity\"].value\t\t\t= aCustomer['City'];\r\n\t\tx[\"ShipPostalCode\"].value\t= aCustomer['PostalCode'];\r\n\t\tx[\"ShipCountry\"].value\t\t= aCustomer['Country'];\r\n\t\t\r\n\t\treturn false;\r\n\t}",
"function setCustomer(e) {\n\n $($gel(\"display-customers-modal\")).modal('hide');\n $gel(\"customer-id\").value = e.value;\n getCustomer();\n}",
"setCustomerName(name) {\n this.customerName = name;\n }",
"registerNewCustomer() {\n // Set store for corporate admin\n if (User.get(this).role === 'corporate-admin') {\n this.selectedStore = corpSettings.get(this).displayData.selectedStore;\n }\n return Service.get(this).newCustomer(this.selectedStore)\n .then(() => {\n const url = Auth.get(this).user.role === 'corporate-admin' ? 'main.corporate.customer' : 'main.employee.customer';\n state.get(this).go(url);\n });\n }",
"function updateCustomer(customer) {\n\t \tconsole.log(customer);\n\t var deferred = $q.defer();\n\t $http.post(BASE_URL + \"customer/update\", customer)\n\t .then(\n\t function (response) {\n\t deferred.resolve(response.data);\n\t },\n\t function(errResponse){\n\t console.error('Error while updating Customer');\n\t deferred.reject(errResponse);\n\t }\n\t );\n\t return deferred.promise;\n\t }",
"getCustomerId() {\n return this.customerId;\n }",
"addCustomer({ commit, state }, customer) {\n state.isLoading = true\n commit('ADD_CUSTOMER', customer)\n }",
"function extractCustomerData(customerId, access_token) {\n\n values = new Object;\n $(\".form_\" + customerId).each(function (index) {\n if ($(this).val() != 0) {\n propertyName = $(this).attr('id');\n\n field = values;\n\n if (propertyName.indexOf('.') > -1) {\n str = propertyName.split(\".\");\n\n for (var i = 0; i < str.length - 1; i++) {\n if (!field.hasOwnProperty(str[i])) {\n field[str[i]] = new Object();\n }\n\n field = field[str[i]];\n }\n\n field[str[str.length - 1]] = $(this).val();\n\n } else {\n values[propertyName] = $(this).val();\n }\n }\n });\n\n $(\"#\" + customerId).html(\"\");\n\n $(\"#\" + customerId).append($(\"<div/>\", {\n style: \"text-align:center\",\n id: \"loaderCustomer\" + customerId\n }).append($(\"<img/>\", {\n src: \"assets/images/loading.gif\"\n })));\n\n\n var request = customerW.updateCustomer(customerId, values, access_token, true);\n\n request.done(function () {\n $(\"#\" + customerId).html(\"\");\n $(\"#\" + customerId).removeClass(\"in\");\n changeExpandButtonIcon(customerId);\n ajaxSuccess(\"Customer data updated successfully\");\n });\n\n request.fail(function () {\n $(\"#\" + customerId).html(\"\");\n $(\"#\" + customerId).removeClass(\"in\");\n changeExpandButtonIcon(customerId);\n ajaxFailed(\"Could not update customer\");\n })\n\n}",
"function createCustomer(so,callback){\n\t// Create customerCode\n\tvar genCode=new Request(\"DECLARE @docCode NVARCHAR(30);EXEC [dbo].GenerateDocumentCode @Transaction='CustomerDetail', @DocumentCode=@docCode output;SELECT @docCode;\",function(err,rowCount,docRows){\n\t\tvar customerCode=docRows[0][0].value;\n\t\t\n\t\t// Generate template\n\t\tvar soTmp=templates.customer(customerCode,so);\n\t\t\n\t\tresolveAddress(soTmp.PostalCode,function(addr){\n\t\t\tsoTmp.State=addr.StateCode.value;\n\t\t\tsoTmp.County=addr.County.value;\n\t\t\tsoTmp.Country=addr.CountryCode.value;\n\t\t\tsoTmp.City=addr.City.value;\n\t\t\t\n\t\t\t// Finalize SQL\n\t\t\tvar sql=templates.generateSQLByTemplate(\"INSERT\",\"Customer\",soTmp);\n\t\t\t\n\t\t\tvar createCustomer=new Request(sql,function(err,rowCount,custRows){\n\t\t\t\tif (err){\n\t\t\t\t\tlog.doLog('error','createCustomer','Failed to create customer: '+err);\n\t\t\t\t}else{\n\t\t\t\t\t// Generate account codes and callback when done\n\t\t\t\t\tlog.doLog('info','createCustomer','Did create customer: '+customerCode);\n\t\t\t\t\tcreateAcctCodes(customerCode,'',function(){\n\t\t\t\t\t\tcallback(customerCode);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\t\t\tconnection.execSqlBatch(createCustomer);\n\t\t});\n\t});\n\t\n\tconnection.execSqlBatch(genCode);\n}",
"watchNewCustomerCreation() {\n scope.get(this).$watch(() => state.get(this).current.name, newVal => {\n // Displaying customers\n this.newCustomer = ['main.employee.customer', 'main.corporate.customer'].indexOf(newVal) === -1;\n // Retrieve customer details if landing on a state displaying customer details\n if (/main.(employee|corporate).customer.(details|edit|intake)/.test(newVal)) {\n // Make sure we don't get the selected customer more than once\n if (this.displayData.selectedCustomer && this.displayData.selectedCustomer._id === state.get(this).params.customerId) {\n return;\n }\n this.getCustomer(state.get(this).params.customerId);\n }\n });\n }",
"function addCustomer(){\n var customerArray = [];\n\n transactions.forEach(function(transaction){\n if (transaction.customer !== undefined ){\n var customer = transaction.customer\n customerArray.push(customer)\n }\n });\n var filterArray = [...new Set(customerArray)]\n return (filterArray)\n}",
"function update_entityuse_codes() {\n //create an object with all unique customers \n nlapiLogExecution('AUDIT', ' -,-,- update entity/use codes -,-,- ');\n var array_of_customers = [];\n // var filters = [];\n // var columns = [\n // new nlobjSearchColumn('internalid')\n // ];\n // //run SuiteScript function to grab all customer ids and put them into an array\n // var customerSearch = nlapiCreateSearch('customer', filters, columns);\n // var result_set = customerSearch.runSearch();\n array_of_customers = nlapiSearchRecord(\"customer\", null,\n [\n [\"internalidnumber\", \"equalto\", \"894942\"],\n \"OR\",\n [\"internalidnumber\", \"equalto\", \"895145\"],\n \"OR\",\n [\"internalidnumber\", \"equalto\", \"895144\"]\n ],\n [\n new nlobjSearchColumn(\"entityid\").setSort(false)\n ]\n );\n // array_of_customers = getAllResults(result_set);\n checkGovernance(max_governance, 'Create Array of Customers', 0, array_of_customers.length);\n //run SuiteScript function to loop through customer ids, check if stage is equal to lead, prospect, then setting new entity fields\n for (var i = 0; i < array_of_customers.length; i++) {\n checkGovernance(max_governance, 'Set Entity/Use Code for Customer', i, array_of_customers.length);\n set_entityuse_code(array_of_customers[i].id, i, array_of_customers.length);\n }\n}",
"async function updateCustomerId(uid, stripeCustomerId) {\n const ref = _1.db.collection('users').doc(uid);\n return ref.set({ stripeCustomerId }, { merge: true });\n}",
"goToCustomerDenials(customer) {\n state.get(this).go('main.corporate.customer-denials', {customerId: customer.customerId});\n }",
"static updateCustomer (id, body) {\n return axios.put(`${url}/${id}`, body)\n }",
"getCustomerName() {\n return this.customerName;\n }",
"function load_customer_list() {\n\t\t\n\t\t//track starting function\n\t\t//console.log('loading the customer list');\n\t\t\n\t\t//gather the data\n\t\tfirebaseService.get.customer_list().then(function success(s) {\n\t\t\t\n\t\t\t//console.log('got this respons', s);\n\t\t\t\n\t\t\t//when the list has been loaded update the variables\n\t\t\t//vm.customerList = s;\n\t\t\tvm.customerList = $firebaseArray(firebase.database().ref().child('customers').child('customer_list'));\n\n\t\t\t//reflect the changes\n\t\t\t$scope.$apply();\n\n\t\t}).catch(function error(e) {\n\t\t\t//if there was an error throw the error\n\t\t\tconsole.log('error');\n\t\t});\n\t}",
"inviteUserToCompanies (callback) {\n\t\tBoundAsync.timesSeries(\n\t\t\tthis,\n\t\t\t2,\n\t\t\tthis.inviteUserToCompany,\n\t\t\tcallback\n\t\t);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DEPRECATED by now, Tours will be generated deivers empty bound to instance return all aviable tour names : getTourNames() | getTourNames(){
return this.tourMap.keys();
} | [
"getTour(tourName){\n return this.tourMap.get(tourName);\n }",
"getTours(){\n return this.tourMap.values();\n }",
"static getDragons(...dragons) {\n return dragons.map((dragon) => dragon.name);\n }",
"async getList() {\n const data = await this.getData();\n return data.map(tour => {\n return {\n title: tour.title,\n shortname: tour.shortname,\n summary: tour.summary,\n card: tour.card\n };\n });\n }",
"function getFullNames(runners) {\n /* CODE HERE */\n let name = [];\n runners.forEach((index) => {\n name.push(index.last_name + \", \" + index.first_name);\n })\n return name;\n}",
"function Tour() {\n\t}",
"get wizardInfos() {\n return `Hi! I am ${this.name}, I'm a student at Hogwarts School year ${this.schoolYear}, my house is ${this.house} and I'm taking these subjects at school: ${this.takenSubjects}`;\n }",
"get generalNames() {\n return this.extnValueObj.subs[0].subs;\n }",
"function TwineToysGetTrackers() {\n return valueTrackers\n}",
"_getClientNames() {\n const names = [];\n for (let key in this.clients) {\n names.push(this.clients[key].name);\n }\n return names;\n }",
"function champIdToName(id) {\n switch (id) {\n case 1: return \"Annie\";\n case 2: return \"Olaf\";\n case 3: return \"Galio\";\n case 4: return \"Twisted Fate\";\n case 5: return \"Xin Zhao\";\n case 6: return \"Urgot\";\n case 7: return \"Leblanc\";\n case 8: return \"Vladimir\";\n case 9: return \"Fiddlesticks\";\n case 10: return \"Kayle\";\n case 11: return \"Master Yi\";\n case 12: return \"Alistar\";\n case 13: return \"Ryze\";\n case 14: return \"Sion\";\n case 15: return \"Sivir\";\n case 16: return \"Soraka\";\n case 17: return \"Teemo\";\n case 18: return \"Tristana\";\n case 19: return \"Warwick\";\n case 20: return \"Nunu\";\n case 21: return \"Miss Fortune\";\n case 22: return \"Ashe\";\n case 23: return \"Tryndamere\";\n case 24: return \"Jax\";\n case 25: return \"Morgana\";\n case 26: return \"Zilean\";\n case 27: return \"Singed\";\n case 28: return \"Evelynn\";\n case 29: return \"Twitch\";\n case 30: return \"Karthus\";\n case 31: return \"Cho'gath\";\n case 32: return \"Amumu\";\n case 33: return \"Rammus\";\n case 34: return \"Anivia\";\n case 35: return \"Shaco\";\n case 36: return \"Dr. Mundo\";\n case 37: return \"Sona\";\n case 38: return \"Kassadin\";\n case 39: return \"Irelia\";\n case 40: return \"Janna\";\n case 41: return \"Gangplank\";\n case 42: return \"Corki\";\n case 43: return \"Karma\";\n case 44: return \"Taric\";\n case 45: return \"Veigar\";\n case 48: return \"Trundle\";\n case 50: return \"Swain\";\n case 51: return \"Caitlyn\";\n case 53: return \"Blitzcrank\";\n case 54: return \"Malphite\";\n case 55: return \"Katarina\";\n case 56: return \"Nocturne\";\n case 57: return \"Maokai\";\n case 58: return \"Renekton\";\n case 59: return \"Jarvan IV\";\n case 60: return \"Elise\";\n case 61: return \"Orianna\";\n case 62: return \"Wukong\";\n case 63: return \"Brand\";\n case 64: return \"Lee Sin\";\n case 67: return \"Vayne\";\n case 68: return \"Rumble\";\n case 69: return \"Cassiopeia\";\n case 72: return \"Skarner\";\n case 74: return \"Heimerdinger\";\n case 75: return \"Nasus\";\n case 76: return \"Nidalee\";\n case 77: return \"Udyr\";\n case 78: return \"Poppy\";\n case 79: return \"Gragas\";\n case 80: return \"Pantheon\";\n case 81: return \"Ezreal\";\n case 82: return \"Mordekaiser\";\n case 83: return \"Yorick\";\n case 84: return \"Akali\";\n case 85: return \"Kennen\";\n case 86: return \"Garen\";\n case 89: return \"Leona\";\n case 90: return \"Malzahar\";\n case 91: return \"Talon\";\n case 92: return \"Riven\";\n case 96: return \"Kog'Maw\";\n case 98: return \"Shen\";\n case 99: return \"Lux\";\n case 101: return \"Xerath\";\n case 102: return \"Shyvana\";\n case 103: return \"Ahri\";\n case 104: return \"Graves\";\n case 105: return \"Fizz\";\n case 106: return \"Volibear\";\n case 107: return \"Rengar\";\n case 110: return \"Varus\";\n case 111: return \"Nautilus\";\n case 112: return \"Viktor\";\n case 113: return \"Sejuani\";\n case 114: return \"Fiora\";\n case 115: return \"Ziggs\";\n case 117: return \"Lulu\";\n case 119: return \"Draven\";\n case 120: return \"Hecarim\";\n case 121: return \"Kha'zix\";\n case 122: return \"Darius\";\n case 126: return \"Jayce\";\n case 127: return \"Lissandra\";\n case 131: return \"Diana\";\n case 133: return \"Quinn\";\n case 134: return \"Syndra\";\n case 143: return \"Zyra\";\n case 150: return \"Gnar\";\n case 154: return \"Zac\";\n case 157: return \"Yasuo\";\n case 161: return \"Vel'koz\";\n case 201: return \"Braum\";\n case 222: return \"Jinx\";\n case 223: return \"Tahm Kench\";\n case 236: return \"Lucian\";\n case 238: return \"Zed\";\n case 245: return \"Ekko\";\n case 254: return \"Vi\";\n case 266: return \"Aatrox\";\n case 267: return \"Nami\";\n case 268: return \"Azir\";\n case 412: return \"Thresh\";\n case 421: return \"Rek'Sai\";\n case 429: return \"Kalista\";\n case 432: return \"Bard\";\n case 999: return \"All Mages\";\n default: return \"Unknown\";\n }\n}",
"static get flightList() {\n return FlightList;\n }",
"function hotelNames(destination){\n destination.hotels.forEach(function(hotel){\n const div = document.querySelector('#hotel')\n //div.innerHTML = ('')\n const pTag = document.createElement('p')\n pTag.className = 'hotel-list'\n pTag.innerText = `Hotel: ${hotel.name}`\n pTag.dataset.id = hotel.id\n div.append(pTag)\n\n renderItineraryHotel(hotel)\n\n pTag.addEventListener('click', function(e){\n //console.log(e.target)\n //debugger\n if (e.target.className === 'hotel-list'){\n const id = e.target.dataset.id\n const div = document.querySelector('#hotel')\n div.innerHTML = ('')\n fetchHotelDetails(id)\n\n }\n })\n })\n }",
"function SBParticipant_getName()\n{\n return this.name;\n}",
"static get flightOnly() {\n return FlightList;\n }",
"parseName() {\n return ionMarkDown_1.Imd.MarkDownToHTML(this.details.artist) + \" - \" + ionMarkDown_1.Imd.MarkDownToHTML(this.details.title);\n }",
"visitDotted_as_names(ctx) {\r\n console.log(\"visitDotted_as_names\");\r\n let returnlist = [];\r\n for (var i = 0; i < ctx.dotted_as_name().length; i++) {\r\n returnlist.push(this.visit(ctx.dotted_as_name(i)));\r\n }\r\n return returnlist;\r\n }",
"get wizardInfos() {\n const wizardInfo = {\n name: this.name,\n wand: {\n wandSize: this.wand.wandSize,\n wandMaterial: this.wand.wandMaterial,\n },\n };\n\n return wizardInfo;\n }",
"static get hotelList() {\n return HotelList;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates the bar chart, which displays a given company's financial information for 2019, 2018, and 2017. | function setBarChart(company) {
const barChart = echarts.init(document.querySelector('#barChartContainer'));
const chart = {
tooltip: {},
legend: { data: ['Revenue', 'Earnings', 'Assets', 'Liabilities'] },
xAxis: { data: ["2019", "2018", "2017"] },
yAxis: {},
grid: {
containLabel: true,
left: 8,
top: 40,
right: 0,
bottom: 0
},
series: [{
name: 'Revenue',
type: 'bar',
barGap: 0,
data: [company.financials.revenue[0], company.financials.revenue[1], company.financials.revenue[2], ]
}, {
name: 'Earnings',
type: 'bar',
barGap: 0,
data: [company.financials.earnings[0], company.financials.earnings[1], company.financials.earnings[2], ]
}, {
name: 'Assets',
type: 'bar',
barGap: 0,
data: [company.financials.assets[0], company.financials.assets[1], company.financials.assets[2], ]
}, {
name: 'Liabilities',
type: 'bar',
barGap: 0,
data: [company.financials.liabilities[0], company.financials.liabilities[1], company.financials.liabilities[2], ]
}],
};
barChart.setOption(chart);
/* Adopted resize event listeners from https://stackoverflow.com/questions/58370315/how-can-we-make-the-echarts-responsive (this source
/* uses jQuery so I modified it to work with purely JS, but the inspiration came from there nonetheless).*/
window.addEventListener('resize', () => { barChart.resize() });
} | [
"function setFinancials(company) {\n const years = company.financials.years;\n const revenues = company.financials.revenue;\n const earnings = company.financials.earnings;\n const assets = company.financials.assets;\n const liabilities = company.financials.liabilities;\n \n /* The 'years' array stores year numbers at each index - 0 is 2019, 1 is 2018, and 2 is 2017. The arrays for each\n * type of financial data also follow this pattern (revenues[0] is the revenue for 2019, revenues[1] is 2018, etc).\n * This means that the index of a 'year' will be the same index of whichever financial data for that year.\n */\n for (let year of years) {\n document.querySelector(`#rev${year}`).textContent = currency(revenues[years.indexOf(year)]);\n document.querySelector(`#earn${year}`).textContent = currency(earnings[years.indexOf(year)]);\n document.querySelector(`#asset${year}`).textContent = currency(assets[years.indexOf(year)]);\n document.querySelector(`#lia${year}`).textContent = currency(liabilities[years.indexOf(year)]);\n }\n }",
"function drawBarChart(canvas, container, data) {\n let ctx = canvas[0].getContext(\"2d\"),\n chart = new Chart(ctx).Bar(data);\n chart.draw();\n return chart;\n}",
"function barChart(ndx) {\n var dim = ndx.dimension(dc.pluck('created'));\n var group = dim.group();\n \n dc.barChart(\"#bar-chart\")\n .width(350)\n .height(250)\n .margins({top: 30, right: 50, bottom: 45, left: 40})\n .dimension(dim)\n .group(group)\n .transitionDuration(1000)\n .x(d3.scale.ordinal())\n .xUnits(dc.units.ordinal)\n .xAxisLabel(\"Customer created\")\n .yAxisLabel(\"# of customers\")\n .yAxis().ticks(10);\n}",
"function newBarChart(ctx,data){\n\tvar myChart = new Chart(ctx, {\n\t\ttype: 'bar',\n\t\tdata: {\n\t\t\tlabels: (data[\"Label\"]?data[\"Label\"]:[\"Red\", \"Blue\", \"Yellow\", \"Green\", \"Purple\", \"Orange\"]),\n\t\t\tdatasets: [{\n\t\t\t\tlabel: (data[\"Title\"]?data[\"Title\"]:'# of Votes'),\n\t\t\t\tdata: (data[\"Data\"]?data[\"Data\"]:[12, 19, 3, 5, 2, 3]),\n\t\t\t\tbackgroundColor: 'rgba(92, 132, 255, 0.2)',\n\t\t\t\tborderColor: 'rgba(92,132,255,1)',\n\t\t\t\tborderWidth: 1\n\t\t\t}]\n\t\t},\n\t\toptions: {\n\t\t\tscales: {\n\t\t\t\tyAxes: [{\n\t\t\t\t\tticks: {\n\t\t\t\t\t\tbeginAtZero:true\n\t\t\t\t\t}\n\t\t\t\t}]\n\t\t\t}\n\t\t}\n\t});\n}",
"function buildCharts(formatedData) {\n buildRevenueChart(formatedData);\n buildGenderChart(formatedData);\n} // END: bulidCharts",
"function undergradEnrollChart() {\r\n\t\t\tvar undergradData = getEnrollmentCout(studentEnrollment);\r\n\t\t\tvar count = undergradData[1];\r\n\t\t\tvar year = undergradData[0];\r\n\r\n\t\t\tvar chartData = google.visualization.arrayToDataTable([\r\n\t\t\t\t['Year', 'Enrollment'],\r\n\t\t\t\t[year.year5, count.year5],\r\n\t\t\t\t[year.year4, count.year4],\r\n\t\t\t\t[year.year3, count.year3],\r\n\t\t\t\t[year.year2, count.year2],\r\n\t\t\t\t[year.year1, count.year1]\r\n\t\t\t]);\r\n\r\n\t\t\tvar options = {\r\n\t\t\t\tchartArea: { width: '100%', height: '100%' }\r\n\t\t\t};\r\n\r\n\t\t\tvar chart = new google.charts.Bar(document.getElementById('undergradEnrollChart'));\r\n\t\t\tchart.draw(chartData, google.charts.Bar.convertOptions(options));\r\n\t\t}",
"function drawBarChart(data, options, element) {\n\n}",
"function createBarcharts(){\n\n // bar charts for age-group and birth cohort in county representation\n makeBarchart(d, featuresCB, \"#barchart1Position\",\"barchart1\",firstTimeData(d, selectedCategories), firstTimeData(d, selectedCategories).length, \"Altersgruppe\", \"value\", 1);\n makeBarchart(d, featuresCB, \"#barchart2Position\",\"barchart2\",secondTimeData(d, selectedCategories), secondTimeData(d, selectedCategories).length, \"Jahrgang\", \"value\", 2);\n // bar charts for age-group and birth cohort in state representation\n makeBarchart(d, featuresCB, \"#barchart1BLPosition\",\"barchart1BL\",firstTimeDataBL(classes[1], selectedCategories), firstTimeDataBL(classes[1], selectedCategories).length, \"Altersgruppe\", \"value\", 1);\n makeBarchart(d, featuresCB, \"#barchart2BLPosition\",\"barchart2BL\",secondTimeDataBL(classes[1], selectedCategories), secondTimeDataBL(classes[1], selectedCategories).length, \"Jahrgang\", \"value\", 2);\n // bar charts for age-group and birth cohort in kv representation\n makeBarchart(d, featuresCB, \"#barchart1KVPosition\",\"barchart1KV\",firstTimeDataKV(aships[1], selectedCategories), firstTimeDataKV(aships[1], selectedCategories).length, \"Altersgruppe\", \"value\", 1);\n makeBarchart(d, featuresCB, \"#barchart2KVPosition\",\"barchart2KV\",secondTimeDataKV(aships[1], selectedCategories), secondTimeDataKV(aships[1], selectedCategories).length, \"Jahrgang\", \"value\", 2);\n\n\n // for the ranking of the top and worst 5 (=cutbarchart) counties when zoomed. If state has equal/less than 10 counties, all counties are shown\n if(lkData().length < 2*cutbarchart){\n makeBarchart(d, featuresCB, \"#barchart3Position\",\"barchart3\",lkData(), numberLK(), \"lk\", rv, 3);\n d3.select(\"#barchart4\").style(\"display\", \"none\");\n d3.selectAll(\".circles\").style(\"display\", \"none\");\n }\n // 3 points shown in county ranking when zoomed\n else{\n d3.selectAll(\".circles\").remove();\n var worstLk = lkData().slice(cutbarchart,lkData().length);\n var topLk = lkData().slice(0,cutbarchart);\n makeBarchart(d, featuresCB, \"#barchart3Position\",\"barchart3\",topLk, cutbarchart, \"lk\", rv, 3); // top 5 counties\n\n var svgCircles = d3.select(\"#circlesPosition\").append(\"g\")\n .attr(\"class\", \"circles\")\n .append(\"svg\")\n .attr(\"width\", 100)\n .attr(\"height\", 12)\n .attr(\"preserveAspectRatio\", \"xMidYMid meet\")\n .attr(\"viewBox\", \"0 0 \" + d3.select(\"#sidebarRight\").style(\"width\").split(\"px\")[0] + \" 12\")\n .append(\"g\")\n .attr(\"transform\", \"translate(0,0)\");\n\n var circles3 = [{\"cx\": 30, \"cy\":2 , \"r\": 1, \"color\": \"black\"},\n {\"cx\": 30, \"cy\":6 , \"r\": 1, \"color\": \"black\"},\n {\"cx\": 30, \"cy\":10 , \"r\": 1, \"color\": \"black\"}];\n\n var circles = svgCircles.selectAll(\"circle\")\n .data(circles3)\n .enter()\n .append(\"circle\");\n\n var circleAttributes = circles\n .attr(\"cx\", function (d) { return d.cx; })\n .attr(\"cy\", function (d) { return d.cy; })\n .attr(\"r\", function (d) { return d.r; })\n .style(\"fill\", function(d) { return d.color; });\n circleAttributes.attr(\"transform\",\"translate(0,0)\");\n\n makeBarchart(d, featuresCB, \"#barchart4Position\",\"barchart4\",worstLk, cutbarchart, \"lk\", rv, 3); // worst 5 counties\n }\n if(!zoomed){\n d3.select(\"#titel3\").style(\"display\", \"none\");\n d3.selectAll(\".circles\").style(\"display\", \"none\");\n }\n }",
"function draw_barchart(caso) {\n\n //'Migration Flow' mode\n if (caso==\"splom\") {\n d3.select(\"#chart-container\").selectAll(\".chartjs-size-monitor\").remove();\n d3.select(\"#chart-container\").select(\"canvas\").remove();\n var name_prov_selected = splom_data.find(element => element[\"Codigo\"]==selected_id)[\"Provincia\"];\n if (type==\"flow\") {\n d3.select(\"#chart-container\")\n .style(\"width\",+svg1Width/3+\"px\")\n .style(\"height\",+(25/269)*svg1Height+20650/269+\"px\")\n .style(\"top\",+(86/273)*svg1Height+86.5+\"px\")\n .append(\"canvas\")\n .attr(\"id\",\"myChart\");\n var ctx = $('#myChart');\n window.myHorizontalBar = new Chart(ctx, {\n type: 'horizontalBar',\n data: {\n labels: ylabels,\n datasets: [{\n data: barchar_data,\n label: '# emmigrants',\n backgroundColor: \"#008000\",\n borderColor: '#000000',\n borderWidth: 1\n }]\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n scales: {\n yAxes: [{\n ticks: {\n beginAtZero: true\n }\n }]\n },\n legend: {\n display: false\n },\n title: {\n display: true,\n text: '# emmigrants from '+ name_prov_selected\n }\n }\n });\n }\n } \n\n //Variable comparison\n if (caso==\"comp\") {\n Chart.defaults.global.defaultFontFamily = 'Quattrocento Sans';\n Chart.defaults.global.defaultFontSize = 15,\n id_province_select_ant = [];\n var ctx = $('#compChart');\n window.myBar = new Chart(ctx, {\n type: 'bar',\n data: {\n labels: province_select,\n datasets: [{\n data: comp_data,\n barPercentage: 0.7,\n borderColor: '#000000',\n borderWidth: 1\n }]\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n scales: {\n yAxes: [{\n ticks: {\n beginAtZero: true\n }\n }]\n },\n legend: {\n display: false,\n },\n title: {\n display: true,\n text: \"\",\n }\n }\n });\n draw_legend_barchart();\n }\n \n}",
"function gradEnrollChart() {\r\n\t\t\tvar gradData = getGradEnrollmentCout(studentEnrollment);\r\n\t\t\tvar count = gradData[1];\r\n\t\t\tvar year = gradData[0];\r\n\r\n\t\t\tvar chartData = google.visualization.arrayToDataTable([\r\n\t\t\t\t['Year', 'Enrollment'],\r\n\t\t\t\t[year.year5, count.year5],\r\n\t\t\t\t[year.year4, count.year4],\r\n\t\t\t\t[year.year3, count.year3],\r\n\t\t\t\t[year.year2, count.year2],\r\n\t\t\t\t[year.year1, count.year1]\r\n\t\t\t]);\r\n\r\n\t\t\tvar options = {\r\n\t\t\t\tchartArea: { width: '100%', height: '100%' }\r\n\t\t\t};\r\n\r\n\t\t\tvar chart = new google.charts.Bar(document.getElementById('gradEnrollChart'));\r\n\t\t\tchart.draw(chartData, google.charts.Bar.convertOptions(options));\r\n\t\t}",
"function drawSchoolFStacked() {\n var data = google.visualization.arrayToDataTable([\n [\"School\", \"Bike, walk, others\", \"School bus, family vehicle, carpool, or city bus\"],\n [\"WES\", 31, 102],\n [\"MGHS\", 24, 73],\n [\"IHoMCS\",11, 11],\n [\"NMCS\", 5, 2],\n [\"MG21\", 4, 2]\n ]);\n\n\n var options = {\n title: \"Figure 9: Mode of Transportation from School by School\",\n chartArea: {width: \"50%\"},\n\t\t\"width\": 600,\n isStacked: true,\n\t\tcolors: ['#C52026','#ADADAD'],\n hAxis: {\n title: \"Number of Response\",\n minValue: 0\n },\n vAxis: {\n title: \"School\"\n }\n };\n var chart = new google.visualization.BarChart(document.getElementById(\"chart_div10\"));\n chart.draw(data, options);\n }",
"function drawSchool2Stacked() {\n var data = google.visualization.arrayToDataTable([\n [\"School\", \"Bike, walk, others\", \"School bus, family vehicle, carpool, or city bus\"],\n [\"WES\", 28, 105],\n [\"MGHS\", 13, 84],\n [\"IHoMCS\", 10, 12],\n [\"NMCS\", 5, 2],\n [\"MG21\", 4, 2]\n ]);\n\n\n var options = {\n \"title\": \"Figure 8: Mode of Transportation to School by School\",\n chartArea: {width: \"50%\"},\n\t\t\"width\": 600,\n isStacked: true,\n hAxis: {\n title: \"Number of Response\",\n minValue: 0\n },\n\t\tcolors: ['#C52026','#ADADAD'],\n vAxis: {\n title: \"School\"\n }\n };\n var chart = new google.visualization.BarChart(document.getElementById(\"chart_div9\"));\n chart.draw(data, options);\n }",
"function draw_g_bar(data) {\n\n let dates = [];\n let series_vivo = [];\n let series_muerto = [];\n let series_nose = [];\n let i = 0;\n while (i < data.length) {\n let j = i;\n dates.push(data[i]['fecha']); // add the new date\n while (j < data.length && data[i]['fecha'] === data[j]['fecha']) { // for all data on that date, append\n switch (data[j]['estado']) {\n case 'vivo':\n series_vivo.push(data[j]['n_avistamientos']);\n break;\n case 'muerto':\n series_muerto.push(data[j]['n_avistamientos']);\n break;\n case 'no sé':\n series_nose.push(data[j]['n_avistamientos']);\n break;\n }\n j++;\n }\n i = j;\n }\n\n\n let options = {\n chart: {\n height: 380,\n width: \"100%\",\n type: 'bar',\n animations: {\n initialAnimation: {\n enabled: false\n }\n }, plotOptions: {\n bar: {\n horizontal: false,\n dataLabels: {\n position: 'top',\n },\n }\n }, dataLabels: {\n enabled: true,\n offsetX: -6,\n style: {\n fontSize: '12px',\n colors: ['#fff']\n }\n }\n },\n stroke: {\n show: true,\n width: 1,\n colors: ['#fff']\n },\n tooltip: {\n shared: true,\n intersect: false\n },\n series: [{\n //data: [44, 55, 41, 64, 22, 43, 21],\n data: series_vivo,\n name: \"Vivo\"\n }, {\n // data: [53, 32, 33, 52, 13, 44, 32],\n data: series_muerto,\n name: \"Muerto\"\n }, {\n data: series_nose,\n name: \"No sé\"\n }],\n xaxis: {\n categories: dates,\n // categories: [2001, 2002, 2003, 2004, 2005, 2006, 2007],\n },\n };\n document.getElementById('grafico_barras_placeholder').innerText = \"\";\n let chart = new ApexCharts(document.getElementById('grafico_barras_placeholder'), options);\n\n chart.render();\n}",
"function populateCPBChart(cpbData, level, id) {\r\n\r\n var CPBChartOption = setCPBOption();\r\n\r\n if (level == 2) {\r\n setMarginForLevel2(CPBChartOption);\r\n }\r\n console.log('CPB DATA');\r\n console.log(cpbData.chartdata);\r\n\r\n var newCPBJson = JSON.parse('{\"chartdata\": []}');\r\n\r\n $.each(cpbData.chartdata === undefined ? JSON.parse('[{\"name\":\"FY YTD Actual Equity\",\"data\":[]},{\"name\":\"Approved CPB Equity\",\"data\":[]},{\"name\":\"FY YEP Equity\",\"data\":[]}]') : cpbData.chartdata, function (i, row) {\r\n var name = validateField(row.name),\r\n dataArray = validateNumberField(row.data);\r\n actualData = {\r\n name : name,\r\n data : dataArray\r\n };\r\n //check if data is complete (12 months) to render the categories on x axis properly\r\n if (dataArray.length < 12) {\r\n var missingNulls = 12 - dataArray.length;\r\n for (var missingIndex = 0; missingIndex < missingNulls; missingIndex++) {\r\n dataArray.push(null);\r\n }\r\n\r\n actualData = {\r\n name : name,\r\n data : dataArray\r\n };\r\n }\r\n newCPBJson.chartdata.push(actualData);\r\n });\r\n console.log(newCPBJson);\r\n CPBChartOption.series = newCPBJson.chartdata;\r\n\r\n $.each(CPBChartOption.series, function (index, row) {\r\n if (row.name == 'FY YTD Actual Equity') {\r\n CPBChartOption.series[index].legendIndex = 2;\r\n } else if (row.name == 'Approved CPB Equity') {\r\n CPBChartOption.series[index].legendIndex = 1;\r\n } else if (row.name == 'FY YEP Equity') {\r\n CPBChartOption.series[index].legendIndex = 3;\r\n }\r\n });\r\n\r\n if (level == 1) {\r\n CPBChartOption.legend.layout = 'vertical';\r\n }\r\n var budgetChart = new Highcharts.Chart(CPBChartOption);\r\n //set title with the Fiscal Year (for filtering purposes)\r\n budgetChart.setTitle({\r\n text : \"CPB Governance (FY\" + reportPeriod + \")\"\r\n });\r\n\r\n if (level == 1) {\r\n nextPage(budgetChart, id);\r\n } else {\r\n backImage(budgetChart);\r\n }\r\n} //end cpb",
"function undergradAdultDataChart() {\r\n\t\t\tvar undergradData = getUndergradAdultData(galbyClassAndGen);\r\n\t\t\tvar maleUGData = undergradData[0];\r\n\t\t\tvar femaleUGData = undergradData[1];\r\n\r\n\t\t\tvar undergradAdultChart = google.visualization.arrayToDataTable([\r\n\t\t\t\t['Year', 'Male', 'Female', { role: 'annotation' }],\r\n\t\t\t\t['Freshman', maleUGData.freshman, femaleUGData.freshman, ''],\r\n\t\t\t\t['Sophomore', maleUGData.sophomore, femaleUGData.sophomore, ''],\r\n\t\t\t\t['Junior', maleUGData.junior, femaleUGData.junior, ''],\r\n\t\t\t\t['Senior', maleUGData.senior, femaleUGData.senior, '']\r\n\t\t\t]);\r\n\r\n\t\t\tvar options = {\r\n\t\t\t\tchartArea: { width: '100%', height: '100%' },\r\n\t\t\t\tisStacked: true\r\n\t\t\t};\r\n\r\n\t\t\tvar chart = new google.charts.Bar(document.getElementById('undergradAdultByClassificatioinGenderChart'));\r\n\t\t\tchart.draw(undergradAdultChart, google.charts.Bar.convertOptions(options));\r\n\t\t}",
"function detailBar1() {\n\t\tlet svgHeight = 70;\n\n\t\tvar margin = {top: 5, right: 20, bottom: 0, left: 20}\n\t\t , width = svgWidth - margin.left - margin.right // Use the window's width \n\t\t , height = svgHeight - margin.top - margin.bottom;\n\n\t\tlet xScale = d3.scaleBand().range([0, width]).padding(0.4);\n\t\tlet yScale = d3.scaleLinear().range([height, 0]);\n\n\t\tlet svg = d3.select(\"svg#detail-1-bar-1\")\n\t\t\t\t\t\t.attr(\"width\", svgWidth)\n\t\t\t\t\t\t.attr(\"height\", svgHeight)\n\t\t\t\t\t\t.attr(\"viewBox\", \"0 0 \" + svgWidth + \" \" + svgHeight);\n\n\t\tvar g = svg.append(\"g\")\n\t\t\t\t.attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n\t\tlet priceData = [records[city][\"2015-2020-price\"]];\n\n\t\txScale = d3.scaleLinear()\n\t\t\t\t.domain([0, price.totalMaximun])\n\t\t\t\t.range([0, width]);\n\n\t\tyScale = d3.scaleBand()\n\t\t\t\t.domain(city)\n\t\t\t\t.range([0, height])\n\t\t\t\t.padding(0.2);\n\n\t\tlet xAxis = g.append(\"g\")\n\t\t\t.attr(\"transform\", \"translate(0,\" + 45 + \")\")\n\t\t\t.call(d3.axisBottom(xScale).tickFormat(function(d){\n\t\t\t\tif (d >= 1000000) {\n\t\t\t\t\treturn d / 1000000 + \"M\";\n\t\t\t\t} else if (d >= 1000) {\n\t\t\t\t\treturn d / 1000 + \"K\";\n\t\t\t\t} else if (d < 1000) {\n\t\t\t\t\treturn d;\n\t\t\t\t}\n\t\t\t})\n\t\t\t.ticks(10))\n\t\t\t.attr(\"class\", \"x-axis\")\n\t\t\t.append(\"text\")\n\t\t\t.attr(\"class\", \"label\")\n\t\t\t.attr(\"x\", 150)\n\t\t\t.attr(\"y\", -40)\n\t\t\t.attr(\"text-anchor\", \"end\")\n\t\t\t.attr(\"stroke\", \"#2d3666\")\n\t\t\t.text(\"Average Home Price (2015-2020)\");\n\n\t\t// Create the bars' container\n\t\tlet bar = g.selectAll(\".bar-price\")\n\t\t\t.data(priceData)\n\t\t\t.enter()\n\t\t\t.append(\"rect\")\n\t\t\t.attr(\"class\", \"bar-price\")\n\t\t\t.attr(\"x\", 0)\n\t\t\t.attr(\"y\", 20)\n\t\t\t.attr(\"width\", function(d) {\n\t\t\t\treturn xScale(d);\n\t\t\t})\n\t\t\t.attr(\"height\", 25)\n\t\t\t.style(\"fill\", colorMain);\n\t}",
"function createBarChart(_params, _parentEl) {\n // Organizing the input data\n var file = _params.dataPath,\n y_legend = _params.yAxisLabel,\n title = _params.title,\n type = _params.valueType,\n layerOfInterest = _params.layerName;\n\n // Inherit the width from the parent node.\n var width = d3.select(_parentEl).node().getBoundingClientRect().width,\n height = width * 0.3 ,\n margin = 0;\n // Setting up the svg element for the bar chart to be contained in\n var svg = d3.select(_parentEl)\n .append(\"svg\")\n .attr('height', height * 1.5)\n .attr('width', width - 15)\n .attr('preserveAspectRatio', 'xMinYMin meet')\n .attr(\n 'viewBox',\n '0 0 ' +\n (width + margin + margin) * 1.3 +\n ' ' +\n (height + margin + margin)\n );\n // Defining the container for the tooltip.\n var div = d3.select(_parentEl).append(\"div\")\n .attr(\"class\", \"tooltip\")\n .style(\"display\", \"none\");\n // Appending the title to svg.\n svg.append(\"text\")\n .attr(\"transform\", \"translate(\" + width * 0.1 + \",0)\")\n .attr(\"x\", width * 0.1)\n .attr(\"y\", width * 0.1)\n .attr(\"font-size\", \"24px\")\n .text(title)\n\n // Defining the the two axis\n var xScale = d3.scaleBand().range([0, width]).padding(0.4),\n yScale = d3.scaleLinear().range([height, 0]); //height\n\n // Defining the g to contain the actual graph\n var g = svg.append(\"g\")\n .classed('chart-body', true)\n .attr(\"transform\", \"translate(\" + margin + 70 + \",\" + margin + 80 + \")\");\n\n // Reading in the data\n d3.csv(file).then(function(data) {\n data.forEach(function(d) {\n d.value = +d.value;\n });\n\n // Placing the data on the axis\n xScale.domain(data.map(function(d) {\n return d.name;\n }));\n yScale.domain([0, d3.max(data, function(d) {\n return d.value;\n })]);\n\n // Setting the axis title and the tick-marks the x-axis.\n g.append(\"g\")\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(d3.axisBottom(xScale))\n .append(\"text\")\n .attr(\"y\", height * 0.2)\n .attr(\"x\", width * 0.45)\n .attr(\"text-anchor\", \"end\")\n .attr(\"stroke\", \"black\")\n .text(\"Name\");\n\n // Setting the axis title and the tick-marks the y-axis.\n g.append(\"g\")\n .call(d3.axisLeft(yScale).tickFormat(function(d) {\n if (type == 'value') {\n return \"$\" + d;\n } else if (type == 'amount') {\n return d;\n }\n })\n .ticks(10))\n .append(\"text\")\n .attr(\"transform\", \"rotate(0)\")\n .attr(\"y\", 5)\n .attr(\"dy\", \"-2.1em\")\n .attr(\"text-anchor\", \"end\")\n .attr(\"stroke\", \"black\")\n .text(y_legend);\n\n // Appending the actual bars using rect elements\n g.selectAll(\".bar\")\n .data(data)\n .enter().append(\"rect\")\n .attr(\"class\", function(d){\n return 'bar '+d.code;\n })\n .attr(\"x\", function(d) {\n return xScale(d.name);\n })\n .attr(\"y\", function(d) {\n return yScale(d.value);\n })\n .attr(\"width\", xScale.bandwidth())\n .attr(\"height\", function(d) {\n return height - yScale(d.value);\n })\n .style('fill-opacity','0.7')\n // Enabling the interactivity when hovering\n .on('mouseenter', function(d) {\n\n d3.selectAll('.' + d.code)\n .classed('active', true)\n .style('fill-opacity','1');\n\n map.setFilter(layerOfInterest +'-highlighted', ['==', 'code', d.code]);\n })\n .on(\"mousemove\", function(d){\n div\n .text('Value: '+d.value)\n .style('display','block')\n .style('opacity','1')\n .style('font-weight','bold')\n .style(\"left\", (d3.mouse(this)[0]) + \"px\")\n .style(\"top\", (d3.mouse(this)[1]) + \"px\");\n })\n .on(\"mouseout\", function(d) {\n map.setFilter(layerOfInterest +'-highlighted', ['==', 'code', '']);\n\n d3.selectAll('.bar')\n .classed('active', false)\n .style('fill-opacity','0.7')\n\n div.style('opacity','0')\n });\n });\n}",
"function createHourlyChart(title,chart_data,output_chart){\n try{\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'Hour of Day');\n data.addColumn('number','available bikes');\n chart_data.forEach(hourlydata=>{\n data.addRow([hourlydata.hour.toString(),hourlydata.available_bike]);\n });\n var options = {\n title: title,\n width:800,\n colors: ['#074b54'],\n legend: {position: 'none'},\n hAxis: {\n title: 'Hour of day',\n showTextEvery: 1\n },\n vAxis: {\n title: 'available bikes'\n }\n };\n // var hourlyChart = new google.charts.Bar(document.getElementById(elementId));\n output_chart.draw(data, options);\n }catch(error){\n console.log(error);\n }\n}",
"function showSeverityDistribution(dataFor2017) {\n\n function severityBySpeed(dimension, severity) {\n return dimension.group().reduce(\n function(p, v) {\n p.total += v.number_of_accidents;\n if (v.accident_severity === severity) {\n p.by_severity += v.number_of_accidents;\n }\n return p;\n },\n function(p, v) {\n p.total -= v.number_of_accidents;\n if (v.accident_severity === severity) {\n p.by_severity -= v.number_of_accidents;\n }\n return p;\n },\n function() {\n return { total: 0, by_severity: 0 };\n }\n );\n }\n\n let dim = dataFor2017.dimension(dc.pluck(\"speed_limit\"));\n let slightBySpeeed = severityBySpeed(dim, \"Slight\");\n let seriousBySpeeed = severityBySpeed(dim, \"Serious\");\n let fatalBySpeeed = severityBySpeed(dim, \"Fatal\");\n\n dc.barChart(\"#severity-distribution\")\n .width(380)\n .height(360)\n .dimension(dim)\n .colors(d3.scale.ordinal().range([\"#e6550e\", \"#fd8c3d\", \"#3182bc\"]))\n .group(fatalBySpeeed, \"Fatal\")\n .stack(seriousBySpeeed, \"Serious\")\n .stack(slightBySpeeed, \"Slight\")\n .valueAccessor(function(d) {\n if (d.value.total > 0) {\n return (d.value.by_severity / d.value.total) * 100;\n }\n else {\n return 0;\n }\n })\n .title(\"Fatal\", function(d) {\n let percent = (d.value.by_severity / d.value.total) * 100;\n return d.key + \" mph: \" + percent.toFixed(1) +\n \"% of fatal accidents\";\n })\n .title(\"Serious\", function(d) {\n let percent = (d.value.by_severity / d.value.total) * 100;\n return d.key + \" mph: \" + percent.toFixed(1) +\n \"% of serious accidents\";\n })\n .title(\"Slight\", function(d) {\n let percent = (d.value.by_severity / d.value.total) * 100;\n return d.key + \" mph: \" + percent.toFixed(1) +\n \"% of slight accidents\";\n })\n .on(\"pretransition\", function(chart) {\n chart.selectAll(\"g.y text\")\n .style(\"font-size\", \"12px\");\n chart.selectAll(\"g.x text\")\n .style(\"font-size\", \"12px\");\n chart.select(\"svg\")\n .attr(\"height\", \"100%\")\n .attr(\"width\", \"100%\")\n .attr(\"viewBox\", \"0 0 380 360\");\n chart.selectAll(\".dc-chart text\")\n .attr(\"fill\", \"#E5E5E5\");\n chart.selectAll(\".dc-legend-item text\")\n .attr(\"font-size\", \"12px\")\n .attr(\"fill\", \"#ffffff\");\n chart.selectAll(\"line\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".domain\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".x-axis-label\")\n .attr(\"font-size\", \"14px\");\n })\n .legend(dc.legend().x(100).y(345).itemHeight(15).gap(5)\n .horizontal(true))\n .margins({ top: 10, right: 30, bottom: 40, left: 40 })\n .x(d3.scale.ordinal())\n .xUnits(dc.units.ordinal)\n .xAxisLabel(\"Speed limit (mph)\", 25)\n .yAxis().tickFormat(function(d) { return d + \"%\"; });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loops through each menu item and sets its position. Refreshes items cache array. | setMenuItemsPosition (pos) {
var step = Math.PI*2 / this.opts.items.length,
angle = Math.PI/2,
opts = this.opts,
range,
_this = this,
position;
Array.prototype.forEach.call(this.$items, function ($item, i) {
position = _this.getItemPosition($item, angle);
if (!pos) {
$item.style.left = position.x + 'px';
$item.style.top = position.y + 'px';
} else {
$item.style.left = position.fromX + 'px';
$item.style.top = position.fromY + 'px';
}
if (!_this.cacheInited) {
_this.cache.push({
item: $item,
correctedX: position.x,
correctedY: position.y,
x: position.originalX,
y: position.originalY,
fromX: position.fromX,
fromY: position.fromY,
range: position.range
});
}
angle -= step;
});
this.cacheInited = true;
} | [
"function setOpacity() {\n for (var i = 0; i < menuItems.length; i++) {\n console.log(\"opacity\");\n menuItems[i].style.opacity = \"0\";\n }\n}",
"function setMenuLocation() {\n\t\tlet menu = ActiveItem.element.getBoundingClientRect();\n\t\t\n\t\tlet x = menu.left + menu.width + 8;\n\t\tlet y = menu.top;\n\t\t\n\t\tctrColor.propMenu.style.left = `${x}px`;\n\t\tctrColor.propMenu.style.top = `${y}px`;\n\t}",
"applyTransitionDelays_() {\n var _MDCSimpleMenuFoundat2 = MDCSimpleMenuFoundation.cssClasses;\n const BOTTOM_LEFT = _MDCSimpleMenuFoundat2.BOTTOM_LEFT,\n BOTTOM_RIGHT = _MDCSimpleMenuFoundat2.BOTTOM_RIGHT;\n\n const numItems = this.adapter_.getNumberOfItems();\n const height = this.dimensions_.height;\n\n const transitionDuration = MDCSimpleMenuFoundation.numbers.TRANSITION_DURATION_MS / 1000;\n const start = MDCSimpleMenuFoundation.numbers.TRANSITION_SCALE_ADJUSTMENT_Y;\n\n for (let index = 0; index < numItems; index++) {\n var _adapter_$getYParamsF = this.adapter_.getYParamsForItemAtIndex(index);\n\n const itemTop = _adapter_$getYParamsF.top,\n itemHeight = _adapter_$getYParamsF.height;\n\n this.itemHeight_ = itemHeight;\n let itemDelayFraction = itemTop / height;\n if (this.adapter_.hasClass(BOTTOM_LEFT) || this.adapter_.hasClass(BOTTOM_RIGHT)) {\n itemDelayFraction = (height - itemTop - itemHeight) / height;\n }\n const itemDelay = (start + itemDelayFraction * (1 - start)) * transitionDuration;\n // Use toFixed() here to normalize CSS unit precision across browsers\n this.adapter_.setTransitionDelayForItemAtIndex(index, `${itemDelay.toFixed(3)}s`);\n }\n }",
"function setMenu(itemList, callback) {\n\tvar counter = 2;\n\tvar stop = false;\n\tvar func = function(err) {\n\t\tif (err && !stop) {\n\t\t\tstop = true;\n\t\t\tcallback(err);\n\t\t}\n\t\tif (!stop) {\n\t\t\tcounter--;\n\t\t\tif (counter == 0)\n\t\t\t\tcallback(null);\n\t\t}\n\t};\n\taddItems(itemList, true, GlobalFood, func);\n\tMenuFood.remove({}, function(err) {\n\t\tif (err && !stop) {\n\t\t\tstop = true;\n\t\t\tcallback(err);\n\t\t}\n\t\tif (!stop)\n\t\t\taddItems(itemList, false, MenuFood, func);\n\t});\n}",
"function handleSortState( items ) {\n\t\tsetItems( [...items] );\n\t}",
"function changeItem(direction){\n\t\t\n\t\tg_parent.switchSlideNums(direction);\n\t\tg_parent.placeNabourItems();\n\n\t}",
"setItems(items){\n const currentFiller = this.numberLeftWithOddEnding()\n /**\n * Will return the indexes (from the old array) of items that were removed\n * @param oldArray\n * @param newArray\n */\n const removedIndexes = (oldArray, newArray) => {\n let rawArray = oldArray.map((oldItem, index) => {\n if(!newArray.some(newItem => newItem === oldItem)){\n return index;\n }\n })\n\n return rawArray.filter( index => (index || index === 0) );\n }\n\n\n /**\n * Will return the indexes (from the new array) of items that were added\n * @param oldArray\n * @param newArray\n */\n const addedIndexes = (oldArray, newArray) => {\n let rawArray = newArray.map((newItem, index) => {\n if(!oldArray.some(oldItem => oldItem === newItem)){\n return index;\n }\n })\n\n return rawArray.filter( index => (index || index === 0) );\n }\n\n\n this.previousItems = this.items.slice();\n this.items = items.slice();\n\n let indexesToRemove = removedIndexes(this.previousItems, this.items);\n let indexesToAdd = addedIndexes(this.previousItems, this.items);\n\n // console.log('add:', indexesToAdd, 'remove:', indexesToRemove)\n\n if(indexesToRemove.length > 0) {\n indexesToRemove.forEach(index => {\n this.removeLastItem(index);\n })\n }\n\n if(indexesToAdd.length > 0) {\n indexesToAdd.forEach(index => {\n this.addItemAtIndex(index);\n })\n }\n\n // When adding we have to update the index every time\n const realElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}:not(.budgie-item-${this.budgieId}--duplicate)`));\n realElements.forEach((element, index) => {\n let className = Array.from(element.classList).filter(_className => _className.match(new RegExp(`budgie-${this.budgieId}-\\\\d`)));\n if(className !== `budgie-${this.budgieId}-${index}`) {\n element.classList.remove(className);\n element.classList.add(`budgie-${this.budgieId}-${index}`);\n }\n })\n\n // remove duplicate elements\n const dupedElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}.budgie-item-${this.budgieId}--duplicate`));\n dupedElements.forEach(element => {\n element.parentNode.removeChild(element);\n })\n\n // remove filler elements\n const fillerElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}--filler`));\n fillerElements.forEach(element => {\n element.parentNode.removeChild(element);\n })\n\n // Insert duplicated elements anew, if this is an infinite scroll\n if(this.options.infiniteScroll) {\n this.prependStartingItems();\n this.appendEndingItems();\n }\n\n // Add filler items to the end if needed\n if(this.numberLeftWithOddEnding() > 0) {\n realElements[realElements.length - this.numberLeftWithOddEnding()]\n .insertAdjacentElement('beforebegin', BudgieDom.createBudgieFillerElement(this))\n\n realElements[realElements.length - 1]\n .insertAdjacentElement('afterend', BudgieDom.createBudgieFillerElement(this))\n }\n\n this.clearMeasurements();\n this.budgieAnimate();\n }",
"async allItems() {\n const allItemMenuLocator = await this.components.menuAllItemsLink()\n await allItemMenuLocator.click()\n }",
"function sf_list_up(){\n\t\n\tjQuery( 'body' ).find( '.studio-container .menu-item' ).each( function( ind ){\n\t\tjQuery( this ).get( 0 ).style.setProperty( '--animation-order', ind.toString() ); // studio container (big list)\n\t});\n\t\n\tjQuery( 'body' ).find( '.list-entry' ).each( function( ind ){\n\t\tjQuery( this ).get( 0 ).style.setProperty( '--animation-order', ind.toString() ); // list entries (normal list)\n\t});\t\n\t\n}",
"function positionItems(items) {\n let rowItems = countRowsItems();\n let y = 0;\n let x = 0;\n let itemCount = 0;\n items.forEach((item, i) => {\n item.style.cssText = `transform: translate3d(${\n x * (parentWidth / rowItems)\n }px, ${y * 220}px, 0); opacity: 1;`;\n x++;\n if (x % rowItems == 0) {\n y++;\n x = 0;\n }\n itemCount = i;\n });\n portfolio.style.height = `${Math.ceil(itemCount / rowItems) * 220}px`;\n}",
"function moveBack() { //return the items to initial state\n document.getElementById(clickedItems[0]).style.backgroundColor = \"\";\n document.getElementById(clickedItems[1]).style.backgroundColor = \"\";\n clickedItems = []; //once items are compared they may be removed from clickedItems array\n ++moveNumber;\n document.getElementById(\"moveId\").innerHTML = \"Move \" + moveNumber; //update move number\n\n let gridItems3 = document.querySelectorAll(\".grid-item\");\n gridItems3.forEach((element, index) => {\n element.style.pointerEvents = \"auto\"; // after checking procedure enable clicking on items\n });\n }",
"_invalidatePositionCache() {\n this._rowPos = [];\n this._columnPos = [];\n }",
"function setListItems(items) {\n // copy the items to a local array\n listItems = [];\n if(items != undefined && items != null && items.length > 0) {\n for(u=0; u<items.length; u++) {\n listItems.splice(0,0,items[u]);\n filterAllowedItems(items[u]);\n }\n }\n\n \n renderListItems();\n }",
"function viewItems () {\n\t//location variables for each bin \n\tlet landfillX = 900;\n\tlet landfillY = 160;\n\tlet compostX = 400;\n\tlet compostY = 160;\n\tlet recycleX = 400;\n\tlet recycleY = 450;\n\n\t//bin indexes used for sorting and organizing the layout of the bins. \n\tlet landfillIndex = 0;\n\tlet recycleIndex = 0;\n\tlet compostIndex = 0;\n\n\tfor ( let i = 0; i < itemLocations.length; i++ ) {\n\t\tif (itemLocations[i] === \"Landfill\") {\n\t\t\tif (landfillIndex === 0) {\n\t\t\t\ttext(shuffledItems[i], landfillX, landfillY);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttext(shuffledItems[i], landfillX, landfillY + (landfillIndex * 18));\n\t\t\t}\n\t\t\tlandfillIndex = landfillIndex +1;\n\t\t}\n\t\telse if (itemLocations[i] === \"Recycle\") {\n\t\t\tif (recycleIndex === 0) {\n\t\t\t\ttext(shuffledItems[i], recycleX, recycleY);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttext(shuffledItems[i], recycleX, recycleY + (recycleIndex * 18));\n\t\t\t}\n\t\t\trecycleIndex = recycleIndex +1;\n\t\t}\n\t\telse if (itemLocations[i] === \"Compost\") {\n\t\t\tif (compostIndex === 0) {\n\t\t\t\ttext(shuffledItems[i], compostX, compostY);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttext(shuffledItems[i], compostX, compostY + (compostIndex * 18));\n\t\t\t}\n\t\t\tcompostIndex = compostIndex +1;\n\t\t}\n\t}\n}",
"updateList(){\n\n\t\t//create an empty div to add the items to\n\t\tvar listItemsDOM = $('<div class=\"listItems\"></div>');\n\n\t\tvar top = this.listDOM.scrollTop();\n\n\t\t//loop over our styles and update the dom list\n\t\tfor(var i=0; i<this.styles.length; i++){\n\n\t\t\t//loop over all our items\n\t\t\tvar item = this.styles[i];\n\n\t\t\t//add a row for this item. Auto add in the \"selected\" identifier if the ID's match\n\t\t\tlistItemsDOM.append('<div id=\"style_'+item.ID+'\" class=\"listItem '+((item.ID==this.selectedStyle)?'selectedClassItem':'')+'\">'+item.name); //+' {'+item.getID()+'}</div>');\n\n\t\t}//next i\n\n\t\t//update the list DOM\n\t\t//this.listDOM.find('.listItems').remove();\n\t\tthis.listDOM.html(listItemsDOM);\n\n\t\tthis.listDOM.scrollTop(top);\n\n\t}",
"function reattachFadeIn() {\n\t\tfor (var i = 1; i <= 3; i++) {\n\t\t\tfor (var j = 0; j < 16; j++) {\n\t\t\t\tvar menu_item = \"#\" + i + \"_\" + j;\n\t\t\t\t$(menu_item).addClass(\"fadein\");\n\t\t\t\t$(menu_item + \"copy\").addClass(\"fadein\");\n\t\t\t}\n\t\t}\n\t}",
"function updateMenu() {\n\t//console.log(\"*&*&*&*&*&*&* Updating menu\");\n// pass in the url of the nodeMenuPage (either the closest older sibling that is displayed on the menu, or if no sibling is on the menu, the closest ancestor that is displayed in the menu).\n\tif (myMenuData && (myScoData.nodeMenuPage)) { // if the menu is loaded and there is a nodeMenuPage\n\t\t//shell.currPageId = myScoData.nodeMenuPage.id;\n\t\tmyMenuData.setCurrentMenuSection(myScoData.nodeMenuPage.id);\n\t} else { // try again\n\t\tsetTimeout(updateMenu,100);\n\t}\n}",
"static updateInventory() {\n\t\tthis.resetInventory();\n\t\tstoryData.story.items.forEach(function(item) {\n\t\t\tif (item.owned) UI.addItem(item);\n\t\t});\n\t}",
"function loadShuffledItems() {\n\tloadItemLabels();\n \tshuffledItems = shuffle(itemLabels);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lerp scroll / bcAdjustHeight adjust the height of an element to some target target using linear interpolation It is a show/hide function with a callback Wrapper for bcLearpHeight en.wikipedia.org/wiki/Linear_interpolation return: null [$el]: and element to show/hide [target]: target height [speed]: animation speed [cb]: callback function | function bcAdjustHeight($el, target, speed = 0.1, cb = null) {
bcLerpHeight($el, target, speed) ;
function bcLerpHeight($el, target, speed = 0.1) {
if (debug) {
console.log(`$el height: ${$el.style.height}`);
}
//the currrent el height
let h = ($el.style.height !== '' && $el.style.height !== undefined ) ? parseFloat($el.style.height) : $el.clientHeight;
if (debug) {
if (i > 500) {
return;
}
console.log(`Lerp ${i}`);
console.log(`---------`);
console.log(`Height: ${h} Target: ${target}`);
console.log(`Difference: ${(h - target)}`);
}
if (Math.floor(target) > Math.floor(h)) {
if (debug) {
console.log(`Target > Height`);
console.log(`Raw height to add: ${(target - h) * speed}`);
}
h += (target - h) * speed;
if (debug) {
console.log(`New height: ${h} Target: ${target}`);
}
$el.style.height = h + 'px';
if (debug) {
console.log(`Element style.height: ${$el.style.height}`);
i++;
}
requestAnimationFrame(() => {
bcLerpHeight($el, target, speed);
});
} else if (Math.floor(h) > Math.floor(target)) {
if (debug) {
console.log(`Height > Target`);
console.log(`Raw height to subtract: ${(h - target) * speed}`);
}
h -= (h - target) * speed;
if (debug) {
console.log(`New height: ${h} Target: ${target}`);
}
$el.style.height = h + 'px';
if (debug) {
console.log(`${$el.style.height}`);
i++;
}
requestAnimationFrame(() => {
bcLerpHeight($el, target, speed);
});
} else {
//Snap to target height
$el.style.height = target + 'px';
return;
}
}//Lerp scroll
if (typeof cb === 'function') {
cb();
}
return;
} | [
"function bcShowHide($el, target, cb) {\n\t\tif (debug) {\n\t\t\tconsole.log('bcShowHide function, target height:');\t\n\t\t\tconsole.log(target);\t\n\t\t}\n\t\ttarget = Number.parseInt(target);\n\t\t$el.style.height = target + 'px';\n\t\tif (typeof cb === 'function') {\n\t\t\t$el.addEventListener('transitionend', () => {\n\t\t\t\trequestAnimationFrame(() => {\n\t\t\t\t\tcb();\n\t\t\t\t});\t\n\t\t\t\t$el.removeEventListener('transitionend', arguments.callee);\n\t\t\t});\t\n\t\t}\n\t}//bcShowHide()",
"setHeight() {\n this.$().outerHeight(this.$(window).height() - this.get('fixedHeight'));\n }",
"function renderHeightAnnouncement() {\n var fsi = 2.5; // font size max increase\n var td = 0.5; // top decrease (per animation segment)\n var ha = -3; // height adjustment\n var dur = 300; // duration (of each animation segment)\n var c = \"rgba( 130, 0, 0, 1 )\"; // color (default to dark red)\n if ( highestRedFlowerPct >= 80) {\n td = -0.5; \n ha = 15;\n c = \"rgba(17, 17, 17, 1)\";\n }\n $(\"#height_announcement\").finish(); // clears the previous height announcement animation if it hasn't completed yet\n $(\"#height_announcement\")\n .text( Math.floor( highestRedFlowerPct ) + \"%\" )\n .css({ \n top: 100-highestRedFlowerPct+ha + \"%\",\n left: pctFromXVal( HeightMarker.chrfx ) + \"%\",\n opacity: 1,\n color: c,\n })\n .animate({ \n fontSize: \"+=\"+fsi+\"pt\",\n top: \"-=\"+td+\"%\",\n opacity: 1,\n }, dur, \"linear\")\n .animate({ \n fontSize: \"-=\"+fsi+\"pt\",\n top: \"-=\"+td*2+\"%\",\n opacity: 0, \n }, dur*2, \"easeOutQuart\", function() { // (uses easing plugin)\n //callback resets original values\n $(\"#height_announcement\").css({\n fontSize: \"10pt\",\n }); \n }\n );\n}",
"function renderHeightMarker() {\n var hrfy = canvas.height - yValFromPct( highestRedFlowerPct ); // highest red flower y value currently\n var chmp = 100-pctFromYVal(HeightMarker.y); // current height marker percentage\n if ( Math.floor( highestRedFlowerPct ) > Math.floor(chmp) ) { // initializes animations if new highest red flower\n HeightMarker.y = hrfy; // y value\n HeightMarker.baa = true; // bounce animation active\n HeightMarker.bat = 0; // bounce animation time elapsed\n HeightMarker.laa = true; // line animation active\n HeightMarker.lat = 0; // line animation time elapsed\n $(\"#height_number\").text( Math.floor( highestRedFlowerPct ) );\n renderHeightAnnouncement();\n }\n //new highest height marker bounce animation (size expansion & contraction)\n if ( HeightMarker.baa ) { \n HeightMarker.bat++;\n var a = -0.12; // corresponds to animation duration ( higher value is longer duration; 0 is infinite)\n var b = 2; // extent of expansion ( higher value is greater expansion )\n var x = HeightMarker.bat; \n var y = a*Math.pow(x,2) + b*x; // current marker expansion extent (quadratic formula; y = ax^2 + bx + c)\n HeightMarker.w = canvas.width*0.025 + y;\n if ( y <= 0 ) { HeightMarker.baa = false; HeightMarker.bat = 0; }\n }\n //new highest height line animation\n if ( HeightMarker.laa ) { \n HeightMarker.lat++;\n var lad = 40; // line animation duration\n var o = 1 - HeightMarker.lat/lad; // opacity\n ctx.beginPath();\n ctx.lineWidth = 2;\n var lGrad = ctx.createLinearGradient( HeightMarker.chrfx-canvas.width, HeightMarker.y, HeightMarker.chrfx+canvas.width, HeightMarker.y );\n lGrad.addColorStop(\"0\", \"rgba( 161, 0, 0, 0 )\");\n lGrad.addColorStop(\"0.4\", \"rgba( 161, 0, 0, \" + 0.3*o + \")\");\n lGrad.addColorStop(\"0.5\", \"rgba( 161, 0, 0, \" + 1*o + \")\");\n lGrad.addColorStop(\"0.6\", \"rgba( 161, 0, 0, \" +0.3*o + \")\");\n lGrad.addColorStop(\"1\", \"rgba( 161, 0, 0, 0 )\");\n ctx.strokeStyle = lGrad;\n ctx.moveTo( HeightMarker.chrfx-canvas.width, HeightMarker.y );\n ctx.lineTo( HeightMarker.chrfx+canvas.width, HeightMarker.y );\n ctx.stroke();\n if ( HeightMarker.lat > lad ) { HeightMarker.laa = false; HeightMarker.lat = 0; }\n }\n //draws marker\n if ( highestRedFlowerPct > 0 ) { \n ctx.beginPath(); // top triangle\n ctx.fillStyle = \"#D32100\";\n ctx.moveTo( canvas.width, HeightMarker.y ); \n ctx.lineTo( canvas.width, HeightMarker.y - HeightMarker.h/2 ); \n ctx.lineTo( canvas.width-HeightMarker.w, HeightMarker.y ); \n ctx.fill(); \n ctx.beginPath(); // bottom triangle\n ctx.fillStyle = \"#A10000\";\n ctx.moveTo( canvas.width, HeightMarker.y ); \n ctx.lineTo( canvas.width, HeightMarker.y + HeightMarker.h/2 ); \n ctx.lineTo( canvas.width-HeightMarker.w, HeightMarker.y ); \n ctx.fill();\n }\n}",
"_calculateHeight() {\n\t\tif (this.options.height) {\n\t\t\treturn this.jumper.evaluate(this.options.height, { '%': this.jumper.getAvailableHeight() });\n\t\t}\n\n\t\treturn this.naturalHeight() + (this.hasScrollBarX() ? 1 : 0);\n\t}",
"function setHeightChangeCallback(callback) {\n // pass the callback along to the sub blocks\n truePart.setHeightChangeCallback(callback);\n falsePart.setHeightChangeCallback(callback);\n }",
"set requestedHeight(value) {}",
"function autoHeightAnimate(element, time){\n var curHeight = element.height(), // Get Default Height\n autoHeight = element.css('height', 'auto').height(); // Get Auto Height\n element.height(curHeight); // Reset to Default Height\n element.stop().animate({ height: autoHeight }, time); // Animate to Auto Height\n}",
"onScroll_() {\n if (!this.isActive_()) {\n return;\n }\n this.vsync_.run(\n {\n measure: state => {\n state.shouldBeFullBleed =\n this.getOverflowContainer_()./*OK*/ scrollTop >=\n FULLBLEED_THRESHOLD;\n },\n mutate: state => {\n this.getShadowRoot().classList.toggle(\n FULLBLEED_CLASSNAME,\n state.shouldBeFullBleed\n );\n },\n },\n {}\n );\n }",
"function reduce() {\n $(\".carousel-item\").css(\"height\", \"20vh\");\n }",
"function setFlashHeight( newHeight ){\n\tdocument.getElementById( \"body\" ).style.height = newHeight + \"px\";\n\t\n\t//alert(newHeight + ' : ' + _scrollHeight());\n\t\n\tif ( newHeight<_scrollHeight() ) \n\t{\n\t\tgetFlash().scrollFlash( 0, 1 );\n\t}\n}",
"_updateHeight() {\n this._updateSize();\n }",
"updateMaxHeightState() {\n this.setState(() => ({\n maxHeight: this._refMainContainer.clientHeight - this.state.mainContainerRestHeight,\n }));\n }",
"bottom(el){\n setTimeout(_=>{\n let parent = el.closest('.window').querySelector('.text')\n parent.scrollTop = parent.scrollHeight\n })\n }",
"function sameHeight(){\n\t\n\telements = $('.js-same-height');\n\n\tif (elements !== null){\n\t\n\t\tArray.prototype.forEach.call(elements, function(el, i){\n\t\t\t\n\t\t\t//Reset de altura\n\t\t\tvar maxHeight = 0;\n\t\t\t\n\t\t\t//Cual es la altura más alta?\t\t\n\t\t\telements = el.querySelectorAll('.js-same');\n\t\t\t\n\t\t\t\n\t\t\tArray.prototype.forEach.call(elements, function(el, i){\n\t\t\t\t\n\t\t\t\tel.removeAttribute('style');\n\t\t\t\t\n\t\t\t\tmaxHeightNew = el.offsetHeight;\n\t\t\t\t\n\t\t\t\tif (maxHeight < maxHeightNew){\n\t\t\t\t\tmaxHeight = maxHeightNew;\n\t\t\t\t}\n\n\t\t\t});\n\n\t\t\tArray.prototype.forEach.call(elements, function(el, i){\n\t\t\t\t\n\t\t\t\t//Ponemos la altura segun los cortes\n\t\t\t\tif (el.classList.contains('no-xs') && windowWidth < xsBreak ){\n\t\t\t\t\tel.style.minHeight = 0+'px';\n\t\t\t\t}else if (el.classList.contains('no-sm') && windowWidth < smBreak ){\n\t\t\t\t\tel.style.minHeight = 0+'px';\n\t\t\t\t}else if (el.classList.contains('no-md') && windowWidth < mdBreak ){\n\t\t\t\t\tel.style.minHeight = 0+'px';\n\t\t\t\t}else{\n\t\t\t\t\tel.style.minHeight = maxHeight+'px';\n\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t});\n\t\n\t\t\t\n\t\t});\n\t}\n\t\n\t\n}",
"static LerpToRef(start, end, amount, result) {\n result.x = start.x + (end.x - start.x) * amount;\n result.y = start.y + (end.y - start.y) * amount;\n result.z = start.z + (end.z - start.z) * amount;\n }",
"function update() {\n var skill = this.model;\n var ratio = skill.curCooldown / skill.cooldown;\n this.filter.set('height', ratio*this.height);\n}",
"function setSlidesHeight() {\n let tallest = 0;\n\n $.each(self.find('.walkthrough__slide'), function () {\n tallest = $(this).height() > tallest ? $(this).height() : tallest;\n });\n\n $('.walkthrough__slide').css('height', tallest);\n }",
"function recalcHeight() {\n // each child element will normally take up 2/3 units\n var y = -1;\n for (var obj of children) {\n // each child lives in its own coordinate system that was scaled by\n // one-third\n y += obj.getHeight() * ONE_THIRD;\n }\n\n if (y > 1.0) {\n maxy = y;\n }\n else {\n // the height may have decreased below 1.0\n maxy = 1.0;\n }\n\n if (adjustHeight != null) {\n adjustHeight(); // propogate the change back up to our parent\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a new mean line ID basically the highest existing ID + 1. | getNewId() {
var id = -1;
this.meanlines.leafletLayer.getLayers().forEach((layer) => {
if (layer.feature.id >= id) {
id = layer.feature.id + 1;
}
});
return id;
} | [
"function lineNo(line) {\n if (line.parent == null) { return null }\n var cur = line.parent, no = indexOf(cur.lines, line);\n for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {\n for (var i = 0;; ++i) {\n if (chunk.children[i] == cur) { break }\n no += chunk.children[i].chunkSize();\n }\n }\n return no + cur.first\n }",
"incrLine() {\n const { line, column } = this;\n return Position.of(line + 1, column);\n }",
"function calculateMean() {\n var mean = 0;\n for (var j = 0; j < $scope.data2.length; j++) {\n mean = mean + $scope.data2[j].y;\n }\n return mean = ((mean / 24).toFixed(2));\n }",
"function uniqueId() {\n return id++;\n }",
"function getNextPID() {\n DropballEntityPIDInc = DropballEntityPIDInc + 1;\n return DropballEntityPIDInc;\n }",
"function getLineNum(element) {\n while (element && element.tagName !== \"LI\") {\n element = element.parentNode;\n }\n var lineNum = element && element.className.match(/L(\\d+)/)[1];\n if (!lineNum) { return; }\n return parseInt(lineNum, 10);\n }",
"getLineNumber(element) {\n if (element &&\n element.nodeName === 'SPAN' &&\n element.getAttribute('class') &&\n element.getAttribute('class').indexOf('os-line-number') > -1) {\n return +element.getAttribute('data-line-number');\n }\n }",
"function getLastGardenId(req, res, next) {\n db.one('SELECT max(id) FROM gardens;')\n .then((data) => {\n let maxid = Number.parseInt(data.max);\n res.gardenid = maxid;\n let user = 1;\n let produce = 1;\n // console.log('id garden is', maxid);\n db.none(`\n INSERT INTO quadrants (garden_id)\n VALUES ($1), ($1), ($1), ($1), ($1), ($1), ($1), ($1), ($1);\n `, maxid)\n .then(() => {\n next();\n })\n })\n .catch(error => next(error));\n}",
"#nextId() {\n const nextId = \"id_\" + this.#currentId;\n this.#currentId++;\n return nextId;\n }",
"assignedPointsMean(arr, len) {\n \n const meanX = arr.map(p => p.x).reduce((a, b) => a + b) / len;\n const meanY = arr.map(p => p.y).reduce((a, b) => a + b) / len;\n return {\n x: meanX,\n y: meanY\n }\n }",
"getAverageHR() {\n let retval=0;\n if (this.countHR>0) { retval=parseInt(this.totalHR/this.countHR) }\n return retval;\n }",
"function getPointId(uniqueId) {\n var markersCount = markers.length - 1;\n for (var j = markersCount; j > -1; j--) {\n if (markers[j].listId == uniqueId) {\n return j;\n }\n }\n}",
"function getInsertionIndex() {\n var _select3 = select('core/block-editor'),\n getBlockIndex = _select3.getBlockIndex,\n getBlockSelectionEnd = _select3.getBlockSelectionEnd,\n getBlockOrder = _select3.getBlockOrder;\n\n var clientId = ownProps.clientId,\n destinationRootClientId = ownProps.destinationRootClientId,\n isAppender = ownProps.isAppender; // If the clientId is defined, we insert at the position of the block.\n\n if (clientId) {\n return getBlockIndex(clientId, destinationRootClientId);\n } // If there a selected block, we insert after the selected block.\n\n\n var end = getBlockSelectionEnd();\n\n if (!isAppender && end) {\n return getBlockIndex(end, destinationRootClientId) + 1;\n } // Otherwise, we insert at the end of the current rootClientId\n\n\n return getBlockOrder(destinationRootClientId).length;\n }",
"function displayLineNumbers (currentLine, fragment) {\n var N = 5;\n var step = $(fragment.node).height() / fragment.lines;\n for (var line = currentLine + 1; line <= currentLine + fragment.lines; line++) {\n if ((line % N) == 0) {\n // highlight(fragment);\n var el = $('<div>' + line + '</div>');\n $('#lineNumbers').append(el);\n\n var offset = fragment.start + step * (line - currentLine -1);\n el.offset({\n top: offset\n });\n }\n }\n return currentLine + fragment.lines;\n}",
"function getIddFromAverage(curr_jitter, jitter_average, g) {\n\tvar percent = curr_jitter / jitter_average * 100;\n\treturn g(percent);\n}",
"nextId(position){\n position+=1;\n if(this.machine.length >position){\n return this.machine[position].activity_id\n }\n return -1\n }",
"function maxID(){\n var res = 0;\n for(var i = 0; i < employees.length; i++){\n if(employees[i].id > res){\n res = employees[i].id;\n }\n }\n return res;\n}",
"getNewPostId() {\n const store = model.getLocalStore();\n\n // Get the current highest post id\n let latestPost = _.max(store.posts, post => {\n return post.id;\n });\n // Return new unique id\n return latestPost.id + 1;\n }",
"low() {\n let mark = Object.values(marks[0]).map(element => {\n return parseInt(element);\n });\n return Math.min(...mark);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function that refreshes the signin object to obtain the current Google user | function refreshValues() {
if (auth2){
console.log('Refreshing values...');
googleUser = auth2.currentUser.get();
console.log(JSON.stringify(googleUser, undefined, 2));
console.log(auth2.isSignedIn.get());
}
} | [
"function signinCallback(authResult) {\n if (authResult['access_token']) {\n // Evitar el inicio de sesion automatico con el valor(PROMPT) de la propiedad \"METHOD\"\n if(authResult['status']['method'] == \"PROMPT\"){\n gapi.auth.setToken(authResult);\n gapi.client.load('oauth2', 'v2', function() {\n var request = gapi.client.oauth2.userinfo.get();\n request.execute(enviarDatosGoogle);\n });\n }\n }\n}",
"function teacherSignIn() {\n base_provider = new firebase.auth.GoogleAuthProvider()\n\n auth.signInWithPopup(base_provider).then(function(result) {\n var token = result.credential.accessToken;\n console.log(token);\n var user = result.user\n console.log(user)\n var uid = user.uid\n var displayName = user.displayName\n var email = user.email\n console.log(email)\n var photo = user.photoURL\n console.log(\"You are now logged in\")\n }).catch(function(err) {\n console.log(err)\n console.log(\"sorry try again\")\n })\n}",
"function signIn() {\n var provider = new firebase.auth.GoogleAuthProvider();\n firebase.auth().signInWithPopup(provider);\n}",
"function refreshAuth() {\n try {\n mySense.getAuth();\n } catch (error) {\n console.log(`Re-auth failed: ${error}. Exiting.`);\n process.exit();\n }\n}",
"function googleLogout() {\n // Wipe localStorage values.\n localStorage.removeItem(GOOGLE_ACCESS_TOKEN_KEY);\n localStorage.removeItem(GOOGLE_REFRESH_TOKEN_KEY);\n\n // Refresh the page.\n window.location.href = window.location.href;\n}",
"function collectFacebookUser(userId){\n var emailAddress = document.getElementById('myVId').value;\n var phoneNumber = document.getElementById('phoneNumber').value;\n\n // Make a google user as a class\n FACEBOOKUSER.configure(userId, emailAddress, phoneNumber);\n\n console.log(FACEBOOKUSER.getId());\n console.log(FACEBOOKUSER.getEmail());\n console.log(FACEBOOKUSER.getMobile());\n\n pushToServer();\n}",
"loginWithRedirect () {\n return this.oidcClient.signinRedirect()\n }",
"async handleRedirectCallback () {\n this.loading = true\n try {\n this.user = await this.oidcClient.signinRedirectCallback()\n this.isAuthenticated = true\n } catch (e) {\n this.isAuthenticated = false\n this.error = e\n } finally {\n this.loading = false\n }\n }",
"appSignIn() {\r\n\r\n if (!msalApp) {\r\n return null\r\n }\r\n\r\n console.log('appSignIn')\r\n this.login().then( () => {\r\n if ( this.user()) {\r\n console.log('user signed in');\r\n // Automaticaly assign accessToken\r\n this.acquireToken().then (accessToken => {\r\n this.accessToken = accessToken \r\n console.log('accessToken: '+ this.accessToken); \r\n store.dispatch('auth/loginSuccess'); \r\n }); \r\n } else {\r\n console.error('Failed to sign in');\r\n store.dispatch('auth/loginFailure'); \r\n } \r\n });\r\n\r\n}",
"async function getGoogleAccountFromCode(req, res, code) {\n const redirect = '/home';\n // console.log(\"Redirecting to...\" + redirect);\n // delete req.session.oauth2return;\n const auth = createConnection();\n const data = await auth.getToken(code);\n const tokens = data.tokens;\n auth.setCredentials(tokens);\n const plus = getGooglePlusApi(auth);\n const me = await plus.people.get({ userId: 'me' });\n const userGoogleId = me.data.id;\n const userGoogleEmail = me.data.emails && me.data.emails.length && me.data.emails[0].value;\n console.log(\"id: \" + userGoogleId + \"email: \" + userGoogleEmail + \"tokens: \" + tokens);\n res.redirect(redirect);\n // return {\n // id: userGoogleId,\n // email: userGoogleEmail,\n // tokens: tokens,\n // };\n}",
"function signin(){\n var payload = {\n \"username\": username.value,\n \"password\": password.value\n };\n\n send_post_request(window.location.origin + '/api/rest-auth/login/', payload, function (data, status){\n\n if (status == 200 || status == 201){\n signin_message.innerHTML = \"Welcome, \" + username.value + \"!\";\n\n // Store token in browser\n sessionStorage.setItem(\"token\", data[\"key\"]);\n sessionStorage.setItem(\"username\", username.value);\n\n // go home\n location.href = window.location.origin\n\n }else{\n signin_message.innerHTML = \"Sign in Failed!\";\n\n }\n \n }, use_token=false)\n}",
"async signInUser(email, password) {\n return await app\n .auth()\n .signInWithEmailAndPassword(email, password)\n .then((user) => {\n localStorage.setItem(\"sprackId\", user.user.uid);\n return user.user.uid;\n })\n .catch((error) => {\n const err = {\n code: error.code,\n message: error.message,\n };\n return err;\n });\n }",
"function saveDataFromGoogle(user, id) {\r\n return new Promise((resolve, reject) => {\r\n // insert google_list_v4\r\n socialAuthModel.saveGoogleData(user, id).then((result) => {\r\n if (result) {\r\n let extraData = { registerGoogle: 1 }\r\n visitModel.checkVisitSessionExtra(db, id, extraData, 0).then((result) =>{\r\n resolve(result)\r\n })\r\n }\r\n }).catch((err) => {\r\n reject(err)\r\n })\r\n })\r\n}",
"function profileHandler(err, resp, body) {\n var profile = profileParser(body), query = {};\n if (profile.error) return console.error(\"Error returned from Google: \", profile.error); //TODO: improve\n\n //Find profile using unique identity provider's id\n query[session.provider + '.id'] = profile.id;\n User.findOne(query, function(err, data) {\n if (err) return console.error(err); //TODO: improve\n if(data === null) { //profile not found\n data = {};\n data[session.provider] = profile;\n user = new User(data);\n } else { //profile found -> update user\n user = data;\n user[session.provider] = profile;\n }\n //Save new or updated user\n user.save(function(err, data){\n if (err) return console.error(err); //TODO: improve\n user = data; //so as to have an _id\n //Find token\n Token.findOne({access : token.access_token }, function(err, data) {\n if (err) return console.error(err); //TODO: improve\n if(data === null) {\n data = {\n user_id: user._id,\n provider: session.provider,\n agent: session.agent,\n address: session.address,\n //updated,\n expires: token.expires_in || token.expires, //Google uses expires_in, Facebook uses expires\n access: token.access_token\n //refresh: ''\n };\n new Token(data).save();\n //TODO: remove expired tokens?\n }\n });\n session.remove(); //.exec();\n //Also purge sessions older than 24 hours\n Session.where('created').lte(Date.now() - 24*60*60*1000).remove().exec();\n });\n });\n }",
"function resetAuth() {\n getOAuthService().reset();\n}",
"function federatedLogin(type,provider){\r\n \t\r\n \tAuth.signInWithPopup(provider).then(function(result) {//firebase auth method for signing in with facebook or google\r\n\t // This gives you a Federated Provider Access Token. You can use it to access the Facebook API.\r\n\t var token = result.credential.accessToken;\r\n\t // The signed-in user info.\r\n\t userObj = result.user;\r\n\t // ...\r\n\t //google and facebook doesn't provide phone number, so we need to ask for this information from user\r\n\t //the code below sets modal to show instructions to user to enter phone number when signing up\r\n\t $(\"#errorMsg\").empty();\r\n\t var type_ext = type==\"su\" ? \"up\":\"in\";\r\n\t $(\"#sign-\"+type_ext+\"-form\").css(\"display\",\"none\");//if the sign in/up form is showing when button is clicked, then when the log-in is successful, hide the form\r\n\t FederatedSignIn_flag = type == \"su\" ? false : true;\r\n\t if(databaseObj == null || databaseObj == undefined){//when database is empty (i.e. brand new)\r\n\t \t\t//do a lot of css to hide components of css and show others\r\n\t \t\t//general purpose is to get modal to ask for user's phone so that we can get the remaining information that is not provided by auth log in\r\n\t\t \t$(\"#sign-\"+type_ext).css(\"display\",\"none\");\r\n\t\t \tif(provider.providerId===\"google.com\"){$(\"#facebook-\"+type).css(\"display\",\"none\");} else {$(\"#google-\"+type).css(\"display\",\"none\");}\r\n\t\t \t$(\"#form-\"+type).css(\"display\",\"none\");\r\n\t\t \t$(\"form#sign-in-form>p\").css(\"display\",\"none\");\r\n\t\t \t$(\"form#sign-up-form>p\").css(\"display\",\"none\");\r\n\t\t\t$(\"form#sign-up-form\").prepend(\"<p>In order to best use our services, please provide a phone number below:</p>\");//prompts user as to why their phone number is being asked for\r\n\t\t \t$(\"form#sign-up-form\").prepend(\"<p>Welcome, \" + userObj.displayName + \"</p>\");\r\n\t\t \t$(\"form#sign-up-form\").css(\"display\",\"block\");\r\n\t\t \t$(\"form#sign-up-form>#instructions\").css(\"display\",\"none\");\r\n\t\t \t$(\"form#sign-up-form>#firstName-su\").css(\"display\",\"none\");\r\n\t\t \t$(\"form#sign-up-form>#lastName-su\").css(\"display\",\"none\");\r\n\t\t \t$(\".awesomplete\").css(\"display\",\"none\");\r\n\r\n\t\t \t$(\"form#sign-up-form>#email-su\").css(\"display\",\"none\");\r\n\t\t\t$(\"form#sign-up-form>#password-su\").css(\"display\",\"none\");\r\n\t\t \t$(\"form#sign-up-form>#phoneNumber-su\").css(\"display\",\"block\");\r\n\t\t \t$(\"form#sign-up-form>#submit-su\").html(\"Set Phone\");//sets submit button to read Set Phone\r\n\r\n\t } else if(!(userObj.uid in databaseObj.users)){//checks whether user who just logged in is in database by using uid - users is a set of uids that have as values objects with user information - all publicly accessible in our app's ui\r\n\t //because this is pretty much the same as the above boolean check, i use the same css setting changes to generate the request for a phone number\r\n\t \t$(\"#sign-\"+type_ext).css(\"display\",\"none\");\r\n\t \tif(provider.providerId===\"google.com\"){$(\"#facebook-\"+type).css(\"display\",\"none\");} else {$(\"#google-\"+type).css(\"display\",\"none\");}\r\n\t \t$(\"#form-\"+type).css(\"display\",\"none\");\r\n\t \t$(\"form#sign-up-form>p\").css(\"display\",\"none\");\r\n\t\t$(\"form#sign-up-form\").prepend(\"<p>In order to best use our services, please provide a phone number below:</p>\");\t\t\t \t\r\n\t \t$(\"form#sign-up-form\").prepend(\"<p>Welcome, \" + userObj.displayName + \"</p>\");\r\n\t \t$(\"form#sign-up-form\").css(\"display\",\"block\");\r\n\t \t$(\"form#sign-up-form>#instructions\").css(\"display\",\"none\");\r\n\t \t$(\"form#sign-up-form>#firstName-su\").css(\"display\",\"none\");\r\n\t \t$(\"form#sign-up-form>#lastName-su\").css(\"display\",\"none\");\r\n\t \t$(\"form#sign-up-form>#email-su\").css(\"display\",\"none\");\r\n\t\t$(\"form#sign-up-form>#password-su\").css(\"display\",\"none\");\r\n\t \t$(\"form#sign-up-form>#phoneNumber-su\").css(\"display\",\"block\");\r\n\t \t$(\"form#sign-up-form>#submit-su\").html(\"Set Phone\");//sets submit button to read Set Phone\r\n\t } else {//user is in database\r\n\t \t$(\"body\").append(\"<p>Welcome, \" + userObj.displayName + \"</p>\");//personal welcome message\r\n\t \t$(\"#sign-in\").css(\"display\",\"none\");\r\n\t\t$(\"#sign-up\").css(\"display\",\"none\");\r\n\t\t$(\"#facebook-su\").css(\"display\",\"none\");\r\n\t\t$(\"#google-su\").css(\"display\",\"none\");\r\n\t \t$(\"#form-su\").css(\"display\",\"none\");\r\n\t\t$(\"#facebook-si\").css(\"display\",\"none\");\r\n\t\t$(\"#google-si\").css(\"display\",\"none\");\r\n\t \t$(\"#form-si\").css(\"display\",\"none\");\r\n\t \t$(\"form#sign-in-form\").css(\"display\",\"none\");\r\n\t \t$(\"form#sign-up-form\").css(\"display\",\"none\");\r\n\t \t$(\".awesomplete\").css(\"display\",\"none\");\r\n\t \t//displays thank you for signing in message and a notice of asking for gps on next page\r\n\t \t$(\".modal-body\").append(\"<p>Thank you, \" + userObj.displayName + \", please click the button below to continue to site.</p><br><p>Please note that, on the next page, you will be asked to allow our website to access your location. This helps us be able to match you with people that are in your vicinity.</p>\");\r\n\t \t$(\"#logInComplete\").css(\"display\",\"block\");\r\n\t }\r\n\t}).catch(function(error) {\r\n\t // Handle Errors here.\r\n\t var errorCode = error.code;\r\n\t var errorMessage = error.message;\r\n\t // The email of the user's account used.\r\n\t var email = error.email;\r\n\t // The firebase.auth.AuthCredential type that was used.\r\n\t var credential = error.credential;\r\n\t $(\"#errorMsg\").empty();\r\n\t $(\"#errorMsg\").append(errorMessage);\r\n\t});\r\n}",
"async renew({ userSession }) {\n try {\n if (this.canSignInUsing('auth0')) {\n await auth0Renew({ userSession, authController: this });\n }\n } catch (err) {\n // instance where a new scope was added and is now required in order to be logged in\n if (err.error === 'consent_required') {\n this.setUserSession(null);\n }\n\n // usually this is just \"user interaction required\" or the like, but just\n // in case the user wants to peek, put it in the console\n /* eslint-disable no-console */\n console.error('Could not renew login:', err);\n }\n }",
"renewTokens() {\n return new Promise((resolve, reject) => {\n const isUserLoggedIn = localStorage.getItem(localStorageKey);\n if (isUserLoggedIn !== \"true\") {\n return reject(\"Not logged in\");\n }\n\n webAuth.checkSession({}, (err, authResult) => {\n if (err) {\n reject(err);\n } else {\n this.localLogin(authResult);\n resolve(authResult);\n }\n });\n });\n }",
"get realmAccessToken() {\n return this.realmUser.then(\n // refresh access_token\n // TODO: should optimally call only when the access_token is close to expiration?\n (user) => user.refreshCustomData().then(() => user.accessToken)\n );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
deal with group message | function groupMsg(mongo, msg, callback) {
var _id = parseInt(msg.togroup);
mongo.db(conf.mongodb.mg1.dbname).collection('Talks').find({
'_id': _id
}).toArray(function(err, res) {
//console.log('!!!!', _id, res, msg);
var gid = 0,
guid = 0;
if (res.length >= 1) {
gid = res[0].groupid;
guid = res[0].creator;
}
var src_obj = {
'uid': msg.poster,
'send_txt': msg.text
};
var dst_obj = {
'gid': gid,
'guid': guid
};
var logJson = {
product: 'yiban4_0',
platform: 'mobile',
module: 'message',
action: 'group',
description: '用户群组聊天发送文本',
time: (msg.time || (+new Date())).toString().substr(0, 10),
src_obj: src_obj,
dst_obj: dst_obj
};
if (callback) callback(logJson);
});
} | [
"function formatGroupMessage(user_idFrom, text) {\n\treturn {\n\t\tfrom: user_idFrom,\n\t\ttext: text,\n\t\tcreatedAt: moment()\n\t}\n}",
"group(rudderElement) {\n let accountObj = {};\n let visitorObj = {};\n const { userId, traits } = rudderElement.message;\n accountObj.id = this.analytics.groupId || this.analytics.anonymousId;\n accountObj = {\n ...accountObj,\n ...traits,\n };\n\n if (userId) {\n visitorObj = {\n id: userId,\n ...(rudderElement.message.context &&\n rudderElement.message.context.traits),\n };\n }\n\n window.pendo.identify({ account: accountObj, visitor: visitorObj });\n }",
"function writeMessagesForGroup(id, data, forceWrite, skipCalculateTotals) {\n var parent = jQuery(\"#\" + id).data(\"parent\");\n\n if (data) {\n var messageMap = data.messageMap;\n var pageLevel = data.pageLevel;\n var order = data.order;\n var sections = data.sections;\n\n //retrieve header for section\n if (data.isSection == undefined) {\n var sectionHeader = jQuery(\"[data-header_for='\" + id + \"']\").find(\"> :header, > label\");\n data.isSection = sectionHeader.length;\n }\n\n //show messages if data is received as force show or if this group is considered a section\n var showMessages = data.isSection || data.forceShow;\n\n //TabGroups rely on tab error indication to indicate messages - don't show messages here\n var type = jQuery(\"#\" + id).data(\"type\");\n if (type && type == kradVariables.TAB_GROUP_CLASS) {\n showMessages = false;\n }\n\n //if this group is in a tab in a tab group show your messages because TabGroups will not\n if (parent) {\n var parentType = jQuery(\"#\" + parent).data(\"type\");\n if (parentType && parentType == kradVariables.TAB_GROUP_CLASS) {\n showMessages = true;\n }\n }\n\n //init empty params\n if (!data.errors) {\n data.errors = [];\n }\n if (!data.warnings) {\n data.warnings = [];\n }\n if (!data.info) {\n data.info = [];\n }\n\n if (!skipCalculateTotals) {\n data = calculateMessageTotals(id, data);\n }\n\n if (showMessages) {\n\n var newList = jQuery(\"<ul class='\" + kradVariables.VALIDATION_MESSAGES_CLASS + \"'></ul>\");\n\n if (data.messageTotal || jQuery(\"span.uif-correctedError\").length || forceWrite) {\n\n newList = generateSectionLevelMessages(id, data, newList);\n\n if (data.summarize) {\n newList = generateSummaries(id, messageMap, sections, order, newList);\n }\n else {\n //if not generating summaries just output field links\n for (var key in messageMap) {\n var link = generateFieldLink(messageMap[key], key, data.collapseFieldMessages, data.displayLabel);\n newList = writeMessageItemToList(link, newList);\n }\n }\n\n var messageBlock = jQuery(\"[data-messages_for='\" + id + \"']\");\n\n //remove old block styling\n messageBlock.removeClass(kradVariables.PAGE_VALIDATION_MESSAGE_ERROR_CLASS);\n messageBlock.removeClass(kradVariables.PAGE_VALIDATION_MESSAGE_WARNING_CLASS);\n messageBlock.removeClass(kradVariables.PAGE_VALIDATION_MESSAGE_INFO_CLASS);\n\n //give the block styling\n if (data.errorTotal > 0) {\n messageBlock.addClass(kradVariables.PAGE_VALIDATION_MESSAGE_ERROR_CLASS);\n }\n else if (data.warningTotal > 0) {\n messageBlock.addClass(kradVariables.PAGE_VALIDATION_MESSAGE_WARNING_CLASS);\n }\n else if (data.infoTotal > 0) {\n messageBlock.addClass(kradVariables.PAGE_VALIDATION_MESSAGE_INFO_CLASS);\n }\n\n //clear and write the new list of summary items\n clearMessages(id, false);\n handleTabStyle(id, data.errorTotal, data.warningTotal, data.infoTotal);\n writeMessages(id, newList);\n //page level validation messsage header handling\n if (pageLevel) {\n if (newList.children().length) {\n var messagesDiv = jQuery(\"[data-messages_for='\" + id + \"']\");\n var countMessage = generateCountString(data.errorTotal, data.warningTotal,\n data.infoTotal);\n\n //set the window title\n addCountToDocumentTitle(countMessage);\n\n var single = isSingularMessage(newList);\n var pageValidationHeader;\n if (!single) {\n pageValidationHeader = jQuery(\"<h3 tabindex='0' class='\" + kradVariables.VALIDATION_PAGE_HEADER_CLASS + \"' \"\n + \"id='pageValidationHeader'>This page has \" + countMessage + \"</h3>\");\n }\n else {\n pageValidationHeader = jQuery(newList).detach();\n }\n\n pageValidationHeader.find(\".uif-validationImage\").remove();\n var pageSummaryClass = \"\";\n var image = errorGreyImage;\n if (data.errorTotal) {\n pageSummaryClass = kradVariables.PAGE_VALIDATION_MESSAGE_ERROR_CLASS;\n image = errorImage;\n }\n else if (data.warningTotal) {\n pageSummaryClass = kradVariables.PAGE_VALIDATION_MESSAGE_WARNING_CLASS;\n image = warningImage;\n }\n else if (data.infoTotal) {\n pageSummaryClass = kradVariables.PAGE_VALIDATION_MESSAGE_INFO_CLASS;\n image = infoImage;\n }\n\n if (!single) {\n pageValidationHeader.prepend(image);\n }\n else {\n pageValidationHeader.find(\"li\").prepend(image);\n pageValidationHeader.addClass(\"uif-pageValidationMessage-single\")\n }\n\n messagesDiv.prepend(pageValidationHeader);\n\n //Handle special classes\n pageValidationHeader.parent().removeClass(kradVariables.PAGE_VALIDATION_MESSAGE_ERROR_CLASS);\n pageValidationHeader.parent().removeClass(kradVariables.PAGE_VALIDATION_MESSAGE_WARNING_CLASS);\n pageValidationHeader.parent().removeClass(kradVariables.PAGE_VALIDATION_MESSAGE_INFO_CLASS);\n pageValidationHeader.parent().addClass(pageSummaryClass);\n\n if (!data.showPageSummaryHeader && !single) {\n pageValidationHeader.hide();\n }\n\n messagesDiv.find(\".uif-validationMessagesList\").attr(\"id\", \"pageValidationList\");\n messagesDiv.find(\".uif-validationMessagesList\").attr(\"aria-labelledby\",\n \"pageValidationHeader\");\n }\n }\n }\n else {\n clearMessages(id, true);\n }\n }\n }\n}",
"groupSpecifier() {\n this._lastStrValue = \"\";\n if (this.eat(unicode_1.QuestionMark)) {\n if (this.eatGroupName()) {\n if (!this._groupNames.has(this._lastStrValue)) {\n this._groupNames.add(this._lastStrValue);\n return;\n }\n this.raise(\"Duplicate capture group name\");\n }\n this.raise(\"Invalid group\");\n }\n }",
"function eventAddChatGroup(data){\n\n\n var time_=jQuery.timeago(data.datetime);/*obtengo el valor del tiempo en texto*/\n var inyectHTML=\"\";\n\n var message=data.message;\n var emoticons = {\n ':)' : '1-feliz.gif',\n ':(' : 'enfadado.gif'\n }, url = \"emoticonos/\";\n // a simple regex to match the characters used in the emoticons\n message = message.replace(/[:\\-)(D]+/g, function (match) {\n return typeof emoticons[match] != 'undefined' ?\n '<img src=\"'+url+emoticons[match]+'\" width=\"20px\"/>' :\n match;\n });\n\n\n\n\n\n if(data.name.email==JSON.parse($.session.get(\"ObjectUser\")).email)\n {\n inyectHTML='<div class=\"mensaje-autor\">'+/*Mensaje del usuario que inició sesión*/\n '<img width=\"50\" src=\"https://desk-cdn.s3.amazonaws.com/unknown.png\" class=\"img-circle\"> '+/*Foto de perfil*/\n '<div class=\"flecha-derecha\"></div>'+/* <!--Mensaje Alineado a la Izquierda-->*/\n '<div class=\"contenido\">'+\n message+ /*<!--Mensaje-->*/\n '</div>'+\n '<div class=\"fecha\">'+time_+'</div>'+/* <!--Hora-->*/\n '</div>';\n }else{\n inyectHTML='<div class=\"mensaje-amigo\">'+ <!--Mensaje de otro contactol-->\n '<div class=\"contenido\">'+\n message+/* <!--Mensaje-->*/\n '</div>'+\n '<div class=\"flecha-izquierda\"></div>'+/* <!--Mensaje Alineado a la Izquierda-->*/\n '<img width=\"50\" src=\"https://desk-cdn.s3.amazonaws.com/unknown.png\" class=\"img-circle\">'+/* <!--Foto de perfil-->*/\n '<div class=\"fecha\">'+time_+' - <span class=\"user-message\" style=\"color: rgb(32, 200, 162);font-weight: bold;\">'+data.name.Name+'</span></div>'/* <!--Hora-->*/\n '</div>';\n }\n\n\n\n $(\".inyect-commit\").append(inyectHTML);\n $(\"#bienvenida\").addClass('hide');\n $(\"#commit-content\").val(\"\");\n\n }",
"function writeMessagesForChildGroups(parentId) {\n jQuery(\"[data-parent='\" + parentId + \"']\").each(function () {\n\n var currentGroup = jQuery(this);\n var id = currentGroup.attr(\"id\");\n var data = getValidationData(currentGroup, true);\n\n if (data) {\n var messageMap = data.messageMap;\n if (!messageMap) {\n messageMap = {};\n data.messageMap = messageMap;\n }\n }\n\n if (!(currentGroup.is(\"div[data-role='InputField']\"))) {\n writeMessagesForChildGroups(id);\n writeMessagesForGroup(id, data);\n displayHeaderMessageCount(id, data);\n }\n });\n}",
"static sendMessage(token, group, time, toSend, image, messageType)\n\t{\n\t\t//Creates some options to let the message be sent with the GroupMe API\n\t\tvar options = {\n\t\t\thostname: 'api.groupme.com',\n\t\t\tpath: `/v3/groups/${group}/messages?token=${token}`,\n\t\t\tmethod: 'POST',\n\t\t\theaders: {\n\t\t\t\t'Content-Type': \"application/json\"\n\t\t\t}\n\t\t}\n\t\tconst guid = time.getTime().toString() + group.toString() + token.toString().substring(0, 5)\n\t\tvar body = {\n\t\t\t\"message\": {\n\t\t\t\t\"source_guid\": guid,\n\t\t\t\t\"text\": toSend,\n\t\t\t\t\"attachments\": image ? [{\"type\": \"image\", \"url\": image}] : []\n\t\t\t}\n\t\t}\n\t\tif (messageType == \"dm\") {\n\t\t\toptions = {\n\t\t\t\thostname: 'api.groupme.com',\n\t\t\t\tpath: `/v3/direct_messages?token=${token}`,\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': \"application/json\"\n\t\t\t\t}\n\t\t\t}\n\t\t\tbody = {\n\t\t\t\t\"message\": {\n\t\t\t\t\t\"source_guid\": guid,\n\t\t\t\t\t\"text\": toSend,\n\t\t\t\t\t\"recipient_id\": group,\n\t\t\t\t\t\"attachments\": image ? [{\"type\": \"image\", \"url\": image}] : []\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//Creates the request to send the request\n\t\tlet req = https.request(options, (response) => {\n\t\t\tconsole.log(`Status: ${response.statusCode}`);\n\t\t\tif (response.statusCode > 399) return;\n\t\t\tresponse.setEncoding('utf8');\n\t\t\t/*response.on('data', (chunk) => {\n\t\t\t\tconsole.log(`Body: ${chunk}`);\n\t\t\t})\n\t\t\tresponse.on('end', () => {\n\t\t\t\tconsole.log(\"End of conversation.\");\n\t\t\t})*/\n\t\t});\n\t\t//Logs errors and sends the request\n\t\treq.on('error', (e) => {console.error(`Problem: ${e.message}`)});\n\t\treq.end(JSON.stringify(body));\n\t}",
"function updateGroup(oContext) {\n\t\t\t\tvar oNewGroup = oBinding.getGroup(oContext);\n\t\t\t\tif (oNewGroup.key !== sGroup) {\n\t\t\t\t\tvar oGroupHeader;\n\t\t\t\t\t//If factory is defined use it\n\t\t\t\t\tif (oBindingInfo.groupHeaderFactory) {\n\t\t\t\t\t\toGroupHeader = oBindingInfo.groupHeaderFactory(oNewGroup);\n\t\t\t\t\t}\n\t\t\t\t\tthat[sGroupFunction](oNewGroup, oGroupHeader);\n\t\t\t\t\tsGroup = oNewGroup.key;\n\t\t\t\t}\n\t\t\t}",
"function AlertGroup(type, groupID, heading, count){\n\tthis.type = type;\t\t//danger, warning, or caution\n\tthis.groupID = groupID;\t//the alerts will refer to this id\n\tthis.heading = heading;\t//heading text for the group\n\tthis.count = count = 0; //total number of alerts within this group\n}",
"function addSocketToGroup(groupId) {\n\n /* create the group if it does not yet exist */\n if (!(groupId in groups)) {\n groups[groupId] = [];\n sequences[groupId] = 0;\n printableGroups[groupId] = [];\n }\n\n /* add the socket to the group */\n groups[groupId].push(socket);\n printableGroups[groupId].push(counter);\n\n console.log('groupAdd: ' + JSON.stringify(printableGroups));\n }",
"createGroup(){\n redis.addGroup(config.EVENTS_STREAM_NAME, config.EVENTS_STREAM_CONSUMER_GROUP_NAME, (err) => {\n if (err){\n this.logger.warn(`Failed to create consumer group '${config.EVENTS_STREAM_CONSUMER_GROUP_NAME}'. ${err.message}`);\n }\n });\n }",
"function group( item ) {\n\n item [ 'type' ] = TYPE.GROUP;\n item [ 'token' ] = item.uuid;\n item [ 'ts' ] = Service.$tools.getTimestamp( item.updatetime );\n \n return item;\n \n }",
"function changeGroup(cGroup_id) {\n\tgetChatSite(cGroup_id).then(data => {\n\t\tgroupID = cGroup_id;\n\t\tdocument.body.innerHTML = data;\n\t\tdocument.getElementById(\"logOutBtn\").addEventListener(\"click\", logOut);\n\t\tdocument.getElementById(\"btnSender\").addEventListener(\"click\", newMessage);\n\t\tdocument.getElementById(\"senderFrom\").addEventListener(\"keypress\", submitOnEnter);\n\t\tstartCountDown();\n\t}).catch((err) => console.error(err.message));\n}",
"function createAlertGroupContainer(group){\n\t\t\tvar containerHtml = \"<li class='ANDI508-alertGroup-container ANDI508-display-\"+group.type+\"' id='ANDI508-alertGroup_\"+group.groupID+\"'>\\\n\t\t\t\t\t\t\t <h4><a href='#' class='ANDI508-alertGroup-toggler' tabindex='0' aria-expanded='false'>\"+group.heading+\n\t\t\t\t\t\t\t\t \" (<span class='ANDI508-total'></span>)</a></h4><ol class='ANDI508-alertGroup-list'></ol></li>\";\n\t\t\t$(\"#ANDI508-alertType-\"+group.type+\"s-container\").append(containerHtml);\n\t\t}",
"function GroupRenderer(){ \n return creatnGroupList.map((item) =>{\n return ( <GroupMember \n key = {item.id} \n id = {item.id} \n uname = {item.fname} \n handleDelFromList = {handleDelFromList}/>)\n })\n }",
"createGroup() {\n this.errorMsg = null;\n this.group.parent = this.selectedSymbolGroup == null ? null : this.selectedSymbolGroup.id;\n\n this.SymbolGroupResource.create(this.project.id, this.group)\n .then(createdGroup => {\n this.ToastService.success('Symbol group <strong>' + createdGroup.name + '</strong> created');\n this.close({$value: createdGroup});\n this.dismiss();\n })\n .catch(response => {\n this.errorMsg = response.data.message;\n });\n }",
"function calculateMessageTotals(id, data) {\n var errorTotal = 0;\n var warningTotal = 0;\n var infoTotal = 0;\n var messageMap = data.messageMap;\n //Add totals for messages of fields in group\n for (var fId in messageMap) {\n var currentData = messageMap[fId];\n errorTotal = errorTotal + currentData.serverErrors.length + currentData.errors.length;\n warningTotal = warningTotal + currentData.serverWarnings.length + currentData.warnings.length;\n infoTotal = infoTotal + currentData.serverInfo.length + currentData.info.length;\n }\n\n var childGroupCount = recursiveGroupMessageCount(id);\n errorTotal += childGroupCount.errorTotal;\n warningTotal += childGroupCount.warningTotal;\n infoTotal += childGroupCount.infoTotal;\n\n //Add totals for messages for THIS Group\n data.errorTotal = errorTotal + data.serverErrors.length + data.errors.length;\n data.warningTotal = warningTotal + data.serverWarnings.length + data.warnings.length;\n data.infoTotal = infoTotal + data.serverInfo.length + data.info.length;\n data.messageTotal = data.errorTotal + data.warningTotal + data.infoTotal;\n\n return data;\n}",
"async function createDirectMessage(user, targetUser) {\n if (user === targetUser) {\n throw new RequestError('user cannot direct message themselves');\n }\n\n // Create a group with the target's name as the group name and no owner\n const userName = await getUserName(user);\n const targetName = await getUserName(targetUser);\n const result = await db.collection(\"Groups\").insertOne({\n name: targetName,\n grpUsers: [{\n user: ObjectId(user),\n role: \"moderator\",\n muted: false,\n }],\n requireApproval: false,\n modDate: Date.now(),\n modules: [],\n });\n\n // Add the group to the user\n const id = result.insertedId;\n await db.collection(\"Users\")\n .updateOne({ _id: ObjectId(user) }, { $push: { groups: id } });\n\n // Invite the target user to the group\n return await sendInvite(user, id.toHexString(), targetUser, \"moderator\", userName);\n}",
"function massactionsChangeMessagePoke()\n\t{\n\t\t// Daten sammeln\n\t\tvar group_id \t\t\t= \t$('#selectMessagePokeGroup').val();\n\t\tvar who\t\t\t\t\t=\t$(\"#selectMessagePokeGroup\").find(':selected').attr('group');\n\t\tvar channel\t\t\t\t=\t$('#selectMessagePokeChannel').val();\n\t\tvar group\t\t\t\t=\t'none';\n\t\tvar res \t\t\t\t= \tgroup_id.split(\"-\");\t// res[3]\n\t\t\n\t\tif(who != 'all')\n\t\t{\n\t\t\tgroup\t\t=\tres[3];\n\t\t};\n\t\t\n\t\t// Daten in Funktion übergeben\n\t\tmassactionsMassInfo(who, group, channel, 'msg');\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Signs the given transaction data and sends it. Abstracts some of the details of buffering and serializing the transaction for web3. | function sendSigned(txData, cb) {
const privateKey = new Buffer(config.privKey, 'hex');
const transaction = new Tx(txData);
transaction.sign(privateKey);
const serializedTx = transaction.serialize().toString('hex');
web3.eth.sendSignedTransaction('0x' + serializedTx, cb);
} | [
"function sendTransaction (transObj, callback){\r\n //var txJSON = TX.toBBE (transObj)\r\n var tx = transObj.serialize()\r\n var txs = {tx: bytes2hex (tx)};\r\n var txj = JSON.stringify (txs)\r\n $.post ('cgi-bin/send.py', txj, callback, 'text')\r\n }",
"sign(privateKey) {\n // encrypts the private key calling getNodePrivateKey on Wallet instance\n const cert = wallet.getNodePrivateKey(this.from, privateKey);\n /*\n createSign creates and returns a Sign object that uses the given algorithm(SHA256).\n .update updates the hash content with the given data which are the signed with cert in hex base.\n */\n const signature = createSign('SHA256').update(this.hash()).sign(cert, 'hex');\n // creates a transaction updating the hash and adding the signature\n return new Transaction({...this, signature});\n }",
"function sendTest() {\n web3.eth.sendTransaction({\n from: web3.eth.coinbase,\n to: '',\n value: web3.toWei(document.getElementById(\"amount\").value, 'ether')\n }, function(error, result) {\n if (!error) {\n document.getElementById('response').innerHTML = 'Success: <a href=\"https://ropsten.etherscan.io/tx/' + result + '\"> View Transaction </a>'\n } else {\n document.getElementById('response').innerHTML = '<pre>' + error + '</pre>'\n }\n })\n}",
"signData(rawData, privKey) {\n let signer = crypto.createSign(this.algorithm);\n\n signer.write(rawData);\n signer.end();\n\n return signer.sign(privKey, this.securityEncoding);\n }",
"function send_the_transaction(tokenBuy,amountBuy,tokenSell,amountSell,address,nonce,expires,v,r,s,type) {\n if (type == \"bid\") {\n var file = 'order_hash_bid.json'\n }\n else if (type == \"ask\") {\n var file = 'order_hash_ask.json'\n }\n else {\n console2.log(\"Error: transaction type is neither bid nor ask\")\n }\n\n\n console2.log(\"Data being sent: \");\n console2.log(\"tokenBuy: \" + tokenBuy);\n console2.log(\"amountBuy: \" + amountBuy);\n console2.log(\"tokenSell: \" + tokenSell);\n console2.log(\"amountSell: \" + amountSell);\n console2.log(\"address: \" + address);\n\n\n\n request({\n method: 'POST',\n url: 'https://api.idex.market/order',\n json: {\n tokenBuy: tokenBuy,\n amountBuy: amountBuy,\n tokenSell: tokenSell,\n amountSell: amountSell,\n address: address,\n nonce: nonce,\n expires: expires,\n v: v,\n r: r,\n s: s\n }\n\n }, function (err, resp, body) {\n console2.log(body);\n if (body.orderHash != undefined) {\n fs.writeFileSync(file, body.orderHash, \"utf8\");\n console2.log(\"Saved hash: \" + body.orderHash);\n console2.log(\"Time: \" + timestamp.timestamp());\n }\n else {\n console2.log(\"Hash is undefined, not saved to hash file.\")\n };\n\n\n })\n\n}",
"async function signOwnInput () {\n try {\n // console.log(`Tx: ${JSON.stringify(unsignedTx, null, 2)}`)\n // Convert the hex string version of the transaction into a Buffer.\n const paymentFileBuffer = Buffer.from(unsignedTx, 'hex')\n\n const allAddresses = [aliceAddr, bobAddr, samAddr]\n\n // Simulate signing own inputs for every individual address\n allAddresses.forEach(function (address) {\n const wif = wifForAddress(address)\n const ecPair = bchjs.ECPair.fromWIF(wif)\n\n // Generate a Transaction object from the transaction binary data.\n const csTransaction = Bitcoin.Transaction.fromBuffer(paymentFileBuffer)\n // console.log(`payments tx: ${JSON.stringify(csTransaction, null, 2)}`)\n\n // Instantiate the Transaction Builder.\n const csTransactionBuilder = Bitcoin.TransactionBuilder.fromTransaction(\n csTransaction,\n 'mainnet'\n )\n // console.log(`builder: ${JSON.stringify(csTransactionBuilder, null, 2)}`)\n\n // find index of the input for that address\n const inputIdx = inputForAddress(address, csTransactionBuilder.tx.ins)\n\n // TODO: user should check also if his own Outputs presents\n // in csTransactionBuilder.tx.outs[]\n\n const addressUTXO = utxoForAddress(address)\n let redeemScript\n csTransactionBuilder.sign(\n inputIdx,\n ecPair,\n redeemScript,\n Bitcoin.Transaction.SIGHASH_ALL,\n addressUTXO.value\n )\n // build tx\n const csTx = csTransactionBuilder.buildIncomplete()\n // output rawhex\n const csTxHex = csTx.toHex()\n // console.log(`Partially signed Tx hex: ${csTxHex}`)\n\n // 'Send' partialially signed Tx to the server\n fs.writeFileSync(`signed_tx_${inputIdx}.json`, JSON.stringify(csTxHex, null, 2))\n })\n\n console.log('signed txs for every user written successfully.')\n } catch (err) {\n console.error(`Error in signOwnInput(): ${err}`)\n throw err\n }\n}",
"function sendSimpleTxn() {\n tools.constructMoneyTx(acc, \"AKQ8cCUoE99ncnRRbaYPit3pV3g58A6FJk\", { gas: 1, neo: 1, remark: \"whatever\" })\n .then(function (txn) { return client.sendRawTransaction(txn).then(function (x) { return console.log(x); }); })\n .catch(function (err) { return console.error(err); });\n}",
"function sendTx(){\n // POST fulfilled \"CREATE\" transaction to the BigchainDB HTTP API endpoint\n var xhr = new XMLHttpRequest();\n var url = \"http://localhost:9984/api/v1/transactions\"; //figure out how to make this dynamic\n xhr.open(\"POST\", url, true);\n xhr.setRequestHeader(\"Content-type\", \"application/json\");\n var data = JSON.stringify(signedCreateTx);\n xhr.send(data);\n}",
"sendPremine(data, stamp, keypair)\n {\n //create and sign message\n var message = new Message(data, stamp);\n message.sign(keypair.secretKey);\n\n //encode\n message = message.toHex();\n\n //trigger receive as if we are seeing a new message\n this.receive(message);\n }",
"eth_sign(address, message) {\n return this.request(\"eth_sign\", Array.from(arguments));\n }",
"commit(transaction) {\n return this._transmit(\"COMMIT\", {\n transaction: transaction\n });\n }",
"function shovelToBitcoin(message) {\n console.log(`shoveling to bitcoin ${message}`);\n datacash.send({\n data: [\"0x6d02\", message],\n cash: { key: wallet.wif }\n });\n //TODO:should raise event saying that tx was sent\n}",
"signTransactionAsync(txParams) {\n return __awaiter(this, void 0, void 0, function* () {\n LedgerSubprovider._validateTxParams(txParams);\n if (txParams.from === undefined || !utils_1.addressUtils.isAddress(txParams.from)) {\n throw new Error(types_1.WalletSubproviderErrors.FromAddressMissingOrInvalid);\n }\n const initialDerivedKeyInfo = yield this._initialDerivedKeyInfoAsync();\n const derivedKeyInfo = this._findDerivedKeyInfoForAddress(initialDerivedKeyInfo, txParams.from);\n this._ledgerClientIfExists = yield this._createLedgerClientAsync();\n const tx = new EthereumTx(txParams);\n // Set the EIP155 bits\n const vIndex = 6;\n tx.raw[vIndex] = Buffer.from([this._networkId]); // v\n const rIndex = 7;\n tx.raw[rIndex] = Buffer.from([]); // r\n const sIndex = 8;\n tx.raw[sIndex] = Buffer.from([]); // s\n const txHex = tx.serialize().toString('hex');\n try {\n const fullDerivationPath = derivedKeyInfo.derivationPath;\n const result = yield this._ledgerClientIfExists.signTransaction(fullDerivationPath, txHex);\n // Store signature in transaction\n tx.r = Buffer.from(result.r, 'hex');\n tx.s = Buffer.from(result.s, 'hex');\n tx.v = Buffer.from(result.v, 'hex');\n // EIP155: v should be chain_id * 2 + {35, 36}\n const eip55Constant = 35;\n const signedChainId = Math.floor((tx.v[0] - eip55Constant) / 2);\n if (signedChainId !== this._networkId) {\n yield this._destroyLedgerClientAsync();\n const err = new Error(types_1.LedgerSubproviderErrors.TooOldLedgerFirmware);\n throw err;\n }\n const signedTxHex = `0x${tx.serialize().toString('hex')}`;\n yield this._destroyLedgerClientAsync();\n return signedTxHex;\n }\n catch (err) {\n yield this._destroyLedgerClientAsync();\n throw err;\n }\n });\n }",
"function signEncryptAndRecord() {\n // 1. University signs a document for a given student (uni will sign the hash of the document basically)\n // 2. Someone adds the university's signature at the bottom of the document. \n signTranscript(schoolAddress, () => {\n // 3. Student encrypts the whole document with a secondary key (using their 2nd private key). --> api\n // 4. Student (or uni) adds document on IPFS. --> api \n encryptAndSendTranscriptSignedToIpfs(transcriptSigned, () => {\n // 5. Student (or uni) stores on the smart contract the IPFS hash for the student.\n recordTranscript(account);\n });\n });\n}",
"getTxRaw() {\n if (!this.hasPubKey()) {\n throw new Error(\"please set pubKey\");\n }\n if (!this.signatures || !this.signatures.length) {\n throw new Error(\"please sign tx\");\n }\n let txRaw = new types.tx_tx_pb.TxRaw();\n txRaw.setBodyBytes(this.body.serializeBinary());\n txRaw.setAuthInfoBytes(this.authInfo.serializeBinary());\n this.signatures.forEach((signature) => {\n txRaw.addSignatures(signature);\n });\n return txRaw;\n }",
"function sign() {\n\n $(\"#messagesPanel\").text('');\n\n // Block the UI while we perform the signature.\n $.blockUI({ message: \"Signing (<span id='signNum'>1</span>/\" + batchElemIds.length + \") ...\" });\n\n // Get the thumbprint of the selected certificate and store it in a global variable (we'll need\n // it later).\n selectedCertThumbprint = $('#certificateSelect').val();\n\n // Call Web PKI to preauthorize the signatures, so that the user only sees one confirmation\n // dialog.\n pki.preauthorizeSignatures({\n certificateThumbprint: selectedCertThumbprint,\n signatureCount: batchElemIds.length // Number of signatures to be authorized by the user.\n }).success(startBatch); // Callback to be called if the user authorizes the signatures.\n }",
"function txHandler (state, tx, context) {\n if (tx.headers) {\n // headers tx, add headers to chain\n headersTx(state, tx, context)\n } else if (tx.transactions) {\n // deposit tx, verify tx and collect UTXO(s)\n depositTx(state, tx, context)\n } else if (tx.signatoryKey) {\n // signatory key tx, add validator's pubkey to signatory set\n signatoryKeyTx(state, tx, context)\n } else {\n throw Error('Unknown transaction type')\n }\n }",
"sign(...signers) {\n if (signers.length === 0) {\n throw new Error('No signers');\n } // Dedupe signers\n\n\n const seen = new Set();\n const uniqueSigners = [];\n\n for (const signer of signers) {\n const key = signer.publicKey.toString();\n\n if (seen.has(key)) {\n continue;\n } else {\n seen.add(key);\n uniqueSigners.push(signer);\n }\n }\n\n this.signatures = uniqueSigners.map(signer => ({\n signature: null,\n publicKey: signer.publicKey\n }));\n\n const message = this._compile();\n\n this._partialSign(message, ...uniqueSigners);\n\n this._verifySignatures(message.serialize(), true);\n }",
"async function main(wallet) {\n\n // Account discovery\n const enabled = await wallet.enable({network: 'testnet-v1.0'});\n const from = enabled.accounts[0];\n\n // Querying\n const algodv2 = await wallet.getAlgodv2();\n const suggestedParams = await algodv2.getTransactionParams().do();\n const txns = makeTxns(from, suggestedParams);\n\n // Sign and post txns\n const res = await wallet.signAndPost(txns);\n console.log(res);\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION NAME : sanityQuery2 AUTHOR : Clarice Salanda DATE : March 20, 2014 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : PARAMETERS : | function sanityQuery2(type){
if(globalDeviceType == "Mobile"){
loading("show");
}
if(globalInfoType == "XML"){
var url = getURL("ConfigEditor")+"action=checkdevicestatus&query=resourceid="+window['variable' + dynamicResourceId[pageCanvas] ]+"^user="+globalUserName+"^feature="+type+"^result=true";
}else{
var url = getURL("ConfigEditor","JSON")+'action=checkdevicestatus&query={"TOPOLOGY":[{"resourceid": "'+window['variable' + dynamicResourceId[pageCanvas]]+'", "user": "'+globalUserName+'", "feature": "'+type+'", "result":"true"}]}';
}
$.ajax({
url: url,
dataType: 'html',
proccessData: false,
success: function(data) {
if(globalDeviceType == "Mobile"){
loading("hide");
}
data = $.trim(data);
var returnflag = false;
if(globalInfoType == "JSON"){
var data2 = data.replace(/'/g,'"');
var b = $.parseJSON(data2);
if(b.RESULT[0].Result){
var alertret = b.RESULT[0].Result;
if(alertret.match(/Alert/gi) != null){
returnflag = true;
alertUser(b.RESULT[0].Result);
return;
}else if(alertret == 1 || alertret == '1'){
returnflag = false;
}else{
returnflag = true;
alertUser("Process Completed");
return;
}
}
if(returnflag == false){
if(globalDeviceType != "Mobile"){
sanityResultTable();
}else{
deviceConfigStat();
}
}
}
}
});
} | [
"function connQueryRunSanity(){\n}",
"function runSanityQueryMenu(){\n\tif(globalDeviceType == \"Mobile\"){\n\t\tloading(\"show\",\"Processing information...\");\n\t}\n\tif(globalInfoType == \"XML\"){\t\n\t\tvar url = getURL(\"ConfigEditor\")+\"action=checkdevicestatus&query=resourceid=\"+window['variable' + dynamicResourceId[pageCanvas] ]+\"^user=\"+globalUserName+\"^feature=linksanity^result=false\";\n\t}else{\n\t\tvar url = getURL(\"ConfigEditor\",\"JSON\")+'action=checkdevicestatus&query={\"TOPOLOGY\":[{\"resourceid\": \"'+window['variable' + dynamicResourceId[pageCanvas]]+'\", \"user\": \"'+globalUserName+'\", \"feature\": \"linksanity\", \"result\":\"false\"}]}';\n\t}\n\t$.ajax({\n\t\turl: url,\n\t\tdataType: 'html',\n\t\tproccessData: false,\n\t\tsuccess: function(data) {\n\t\t\tdata = $.trim(data);\n\t\t\tif(globalInfoType == \"XML\"){\n\t\t\t\tif(data.match(/Alert/gi) != null){\n\t\t\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].LinkSanityEnable = \"false\";\n\t\t\t\t\talertUser(data);\n\t\t\t\t}else{\n\t\t\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].LinkSanityEnable = \"true\";\n\t\t\t\t\tconnQueryRunSanity();return;}\n\t\t\t}else{\n\t\t\t\tdata = data.replace(/'/g,'\"');\n\t\t\t\tvar json = jQuery.parseJSON(data);\n\t\t\t\tif(json.TOPOLOGY[0].Result != '1'){\n\t\t\t\t\talertUser(json.TOPOLOGY[0].Result);\n\t\t\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].LinkSanityEnable = \"false\";\n\t\t\t\t\treturn;\n\t\t\t\t}else{\n\t\t\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].LinkSanityEnable = \"true\";\n\t\t\t\t\tconnQueryRunSanity();return;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n\n}",
"function query_test() {\n DB.clear_all()\n let album1 = create_dummy(Album)\n let album2 = create_dummy(Album)\n let album3 = create_dummy(Album)\n let all_albums_query = create_live_query().all(Album).make()\n check.equals(all_albums_query.current().length(),3,'all album check')\n all_albums_query.sync()\n let album4 = create_dummy(Album)\n all_albums_query.sync()\n check.equals(all_albums_query.current().length(),4)\n\n let yellowsub_query = create_live_query().all(Album).attr_eq(\"title\",\"Yellow Submarine\").make()\n yellowsub_query.sync()\n all_albums_query.sync()\n check.equals(all_albums_query.current().length(),4, 'total album count')\n check.equals(yellowsub_query.current().length(),0,'yellow sub should be 0')\n\n create_dummy(Album, {title: 'Yellow Submarine'})\n yellowsub_query.sync()\n all_albums_query.sync()\n check.equals(all_albums_query.current().length(),5, 'total album count')\n check.equals(yellowsub_query.current().length(),1)\n\n\n // make three tracks. one on album1 and two on album 2\n create_dummy(Track, {album:album1, title:'title1'})\n create_dummy(Track, {album:album2, title:'title2'})\n create_dummy(Track, {album:album2, title:'title3'})\n\n // make a track query. verify three tracks total\n let all_tracks_query = create_live_query().all(Track).make()\n all_tracks_query.sync()\n check.equals(all_tracks_query.current().length(),3)\n\n // make a track query for tracks on album1, verify 1 track\n let album1_tracks_query = create_live_query().all(Track).attr_eq('album',album1).make()\n check.equals(album1_tracks_query.current().length(),1)\n\n\n // make a track query for tracks on album2, verify 2 tracks\n let album2_tracks_query = create_live_query().all(Track).attr_eq('album',album2).make()\n check.equals(album2_tracks_query.current().length(),2)\n //check the titles\n check.equals(create_live_query().all(Track).attr_eq('title','title1').make().current().length(),1)\n check.equals(create_live_query().all(Track).attr_eq('title','title2').make().current().length(),1)\n //this one should fail\n check.equals(create_live_query().all(Track)\n .attr_eq('title','title4').make()\n .current().length(),0)\n\n //check if attr in array\n console.log(\"checking if title in [title1,title2]\")\n check.equals(create_live_query().all(Track)\n .attr_in_array('title',['title1','title2','title4']).make()\n .current().length(),2)\n\n //check if track in one of a set of albums\n check.equals(create_live_query().all(Track)\n .attr_in_array('album',[album1,album2]).make()\n .current().length(),3)\n\n // all tracks for all albums.\n let all_albums = create_live_query().all(Album).make()\n let all_album_tracks = create_live_query().all(Track)\n .attr_in_array('album',all_albums).make()\n check.equals(all_album_tracks.current().length(),3)\n\n // make a Selection which contains an array of Albums\n // let selected_albums = create_dummy(Selection, {albums:[album2, album3]})\n\n // make a query of albums in the selection\n // let selected_albums_query = create_live_query().all(Track)\n // .attr_in_array('album',selected_albums).make()\n // check.equals(selected_albums_query.current().length(),2)\n\n // make a query of tracks in albums in selection\n // let selected_tracks_query = create_live_query().all(Track)\n // .attr_eq('album',selected_albums_query).make()\n // check.equals(selected_tracks_query.current().length(),2)\n}",
"async function test_14_in_params()\n{\n // TODO not expecting this to work yet.\n console.log(\"*** test_14_in_params ***\");\n // initialize a new database\n let [ db, retrieve_root ] = await TU.setup();\n\n // insert data\n const statements = [\n [ DT.addK, \"bob\", K.key(\":name\"), \"Bobethy\" ],\n [ DT.addK, \"bob\", K.key(\":likes\"), \"sandra\" ],\n [ DT.addK, \"sandra\", K.key(\":name\"), \"Sandithan\"]];\n\n db = await DB.commitTxn( db, statements );\n\n // query the data\n const q = Q.parseQuery(\n [Q.findK, \"?a\", \"?b\", \"?c\",\n Q.inK, \"$\", \"?b\", \"?c\",\n Q.whereK, \n [\"?a\", \"?b\", \"?c\"],\n ]\n );\n const r = await Q.runQuery( db, q, K.key( \":name\" ), \"Bobethy\" );\n\n console.log(\"r14\", r);\n assert(\n r.length === 1 && \n r[0][2] === \"Bobethy\", \n \"Query returned an unexpected value\");\n console.log(\"*** test_14_in_params PASSED ***\");\n\n}",
"function devSanityData(data){\n\tvar mydata = data;\n\tif(globalInfoType == \"XML\"){\n\t\tvar parser = new DOMParser();\n\t\tvar xmlDoc = parser.parseFromString( mydata , \"text/xml\" );\n\t\tvar row = xmlDoc.getElementsByTagName('MAINCONFIG');\n\t\tvar uptable = xmlDoc.getElementsByTagName('DEVICE');\n\t\tvar lowtable = xmlDoc.getElementsByTagName('STATUS');\n\t}else{\n\t\tdata = data.replace(/'/g,'\"');\n\t\tvar json = jQuery.parseJSON(data);\t\n\t\tif(!json.RESULT){\n\t\t\tvar uptable = json.MAINCONFIG[0].DEVICE;\n\t\t\tvar lowtable = json.MAINCONFIG[0].STATUS;\n\t\t}\n\t}\n\tvar devStat='';\n\tvar devSanityStat='';\n\tif(!json.RESULT){\n\t\tclearTimeout(TimeOut);\n\t\tTimeOut = setTimeout(function(){\n\t\t\tdevSanXML(uptable,lowtable);\n\t\t},5000);\n\t\treturn;\n\t}\n\tdevSanInit();\n\tTimeOut = setTimeout(function(){\n\t\tsanityQuery('deviceSanity');\n\t},5000);\n}",
"function datasetQuery(query){\r\n\t\tvar select = \"SELECT\";\r\n\t\tvar params = {};\r\n\t\tvar builtConditions = generateConditions(query);\r\n\t\tfor(var paramsk in builtConditions.params){\r\n\t\t\tif (!builtConditions.params.hasOwnProperty(paramsk)) continue;\r\n\t\t\tparams[paramsk]=builtConditions.params[paramsk];\r\n\t\t}\r\n\t\tfor(var i = 0; i < domain.length; i++){\r\n\t\t\tparams[\"domain_value_\" + i] = domain[i];\r\n\t\t\tvar dcond = domainCondition(i);\r\n\t\t\tfor(var paramsk in dcond.params){\r\n\t\t\t\tif (!dcond.params.hasOwnProperty(paramsk)) continue;\r\n\t\t\t\tparams[paramsk]=dcond.params[paramsk];\r\n\t\t\t}\r\n\t\t\tselect += \" \" + fn + \"(CASE WHEN \" + dcond.condition + \" THEN \" + value + \" END) AS \" + domainName + \"_\" + i;\r\n\t\t\tif(i != domain.length-1) select += \",\";\r\n\t\t}\r\n\t\tselect += \" FROM offence\" + (builtConditions.conditions.length?' WHERE ':'') + builtConditions.conditions.join(\" AND \") + \";\"\r\n\t\tconsole.log(select, params);\r\n\t\treturn {select, params};\r\n\t}",
"function linkSanityData(data){\n\tvar linkStat='';\n\tvar linkSanityStat='';\t\n\tvar mydata = data;\n\tif(globalInfoType ==\"XML\"){\n\t\tvar parser = new DOMParser();\n\t\tvar xmlDoc = parser.parseFromString( mydata , \"text/xml\" );\n\t\tvar row = xmlDoc.getElementsByTagName('MAINCONFIG');\n\t\tvar uptable = xmlDoc.getElementsByTagName('DEVICE');\n\t\tvar lowtable = xmlDoc.getElementsByTagName('STATUS');\t \n\t}else{\n\t\tdata = data.replace(/'/g,'\"');\n var json = jQuery.parseJSON(data);\n\t\tif(json.MAINCONFIG){\n var uptable = json.MAINCONFIG[0].DEVICE;\n var lowtable = json.MAINCONFIG[0].STATUS;\n }\n\t}\n\tif(json.MAINCONFIG){\n\t\tclearTimeout(TimeOut);\n\t\tTimeOut = setTimeout(function(){\n\t\t\tlinkSanXML(uptable,lowtable);\n\t\t},5000);\n\t\treturn;\n\t}\n\tlinkSanInit();\n\tTimeOut = setTimeout(function(){\n\t\tsanityQuery('linksanity');\n\t},5000);\n}",
"function ParseQL()\r\n{\r\n var config = JSON.parse(PAL.GetValue(CONFIG_STORAGE_STR));\r\n var i;\r\n var ql_items = [ config.ql1, config.ql2, config.ql3, config.ql4];\r\n\r\n /* Remove spaces from QL which affect exclusion/targeting, and split each QL into sections. */\r\n for (i = 0; i < ql_items.length; i++)\r\n {\r\n ql_items[i] = ql_items[i].replace(/\\s/g, \"\").split(';');\r\n PAL.DebugLog(\"QL\" + i + \": \" + ql_items[i], PAL.e_logLevel.VERBOSE);\r\n }\r\n\r\n for (i = 0; i < ql_items.length; i++)\r\n {\r\n config.pql[i] = {};\r\n\r\n if (ql_items[i].length >= QL_LENGTH_LEGACY)\r\n {\r\n config.pql[i].useMissiles = ql_items[i][QL_USE_MISSILES] ? true: false;\r\n config.pql[i].attackMode = ql_items[i][QL_ATTACK_MODE];\r\n config.pql[i].includeFactions = ql_items[i][QL_TRIGGER_FACTIONS];\r\n config.pql[i].includeSizes = ql_items[i][QL_TRIGGER_SIZES].split(\":\");\r\n config.pql[i].includeClasses = ql_items[i][QL_TRIGGER_CLASSES];\r\n config.pql[i].includeAlliances = ql_items[i][QL_TRIGGER_ALLIANCES].split(',');\r\n config.pql[i].includeIndividuals = ql_items[i][QL_TRIGGER_INDIVIDUALS].split(',');\r\n\r\n config.pql[i].excludeFactions = ql_items[i][QL_EXCLUDE_FACTIONS];\r\n config.pql[i].excludeSizes = ql_items[i][QL_EXCLUDE_SIZES].split(\":\");\r\n config.pql[i].excludeClasses = ql_items[i][QL_EXCLUDE_CLASSES];\r\n config.pql[i].excludeAlliances = ql_items[i][QL_EXCLUDE_ALLIANCES].split(',');\r\n config.pql[i].excludeIndividuals = ql_items[i][QL_EXCLUDE_INDIVIDUALS].split(',');\r\n\r\n config.pql[i].combatRounds = ql_items[i][QL_COMBAT_ROUNDS];\r\n\r\n /* Do bounds checking on the combat round values here, to save on processing when in combat. */\r\n if (config.pql[i].combatRounds > 20) config.pql[i].combatRounds = 20;\r\n if (config.pql[i].combatRounds < 1) config.pql[i].combatRounds = 1;\r\n\r\n PAL.DebugLog(\"Calculated QL \" + i + \":\" +\r\n \"\\nuseMissiles: \" + config.pql[i].useMissiles +\r\n \"\\nattackMode: \" + config.pql[i].attackMode +\r\n \"\\nincludeFactions: \" + config.pql[i].includeFactions +\r\n \"\\nincludeSizes: \" + config.pql[i].includeSizes +\r\n \"\\nincludeClasses: \" + config.pql[i].includeClasses +\r\n \"\\nincludeAlliances: \" + config.pql[i].includeAlliances +\r\n \"\\nincludeIndividuals: \" + config.pql[i].includeIndividuals +\r\n \"\\nexcludeFactions: \" + config.pql[i].excludeFactions +\r\n \"\\nexcludeSizes: \" + config.pql[i].excludeSizes +\r\n \"\\nexcludeClasses: \" + config.pql[i].excludeClasses +\r\n \"\\nexcludeAlliances: \" + config.pql[i].excludeAlliances +\r\n \"\\nexcludeIndividuals: \" + config.pql[i].excludeIndividuals +\r\n \"\\ncombatRounds: \" + config.pql[i].combatRounds,\r\n PAL.e_logLevel.VERBOSE);\r\n }\r\n }\r\n\r\n PAL.SetValue(CONFIG_STORAGE_STR, JSON.stringify(config));\r\n}",
"_validate (entry = [], queries = {}) {\n return this.getLogicalOperator(queries.operator).fn.call(queries.list, (_query) => {\n if (this.isLogicalOperator(queries.operator)) {\n return this._validate(entry, _query);\n } else {\n return this.getQueryOperator(_query[1]).fn.apply(this, [\n (_query[0] ? entry[1][_query[0]] : entry[1]), // Entry value\n _query[2], // Test value\n _query[0], // Test key\n entry // Entry [<Key>, <Value>]\n ]);\n }\n });\n }",
"function accSanityData(data){\n\tvar accStat='';\n\tvar accSanityStat='';\n\tvar mydata = data;\n\tif(globalInfoType == \"XML\"){\n\t\tvar parser = new DOMParser();\n\t\tvar xmlDoc = parser.parseFromString( mydata , \"text/xml\" );\n\t\tvar row = xmlDoc.getElementsByTagName('MAINCONFIG');\n\t\tvar uptable = xmlDoc.getElementsByTagName('DEVICE');\n\t\tvar lowtable = xmlDoc.getElementsByTagName('STATUS');\n\t}else{\n\t\tdata = data.replace(/'/g,'\"');\n\t\tvar json = jQuery.parseJSON(data);\n if(json.MAINCONFIG){\n var uptable = json.MAINCONFIG[0].DEVICE;\n var lowtable = json.MAINCONFIG[0].STATUS;\n }\n\t}\n\tif(json.MAINCONFIG){\n\t\tclearTimeout(TimeOut);\n\t\tTimeOut = setTimeout(function(){\n\t\t\taccSanXML(uptable,lowtable);\n\t\t },5000);\n\t\treturn;\n\t}\n\taccSanInit();\n\tTimeOut = setTimeout(function(){\n\t\tsanityQuery('accessSanity');\n\t},5000);\n}",
"function clean(query, isRecursive, next) {\n var forRet = [];\n //console.log(query);\n var upper = query.toUpperCase();\n var noPunctuation = upper.replace(/[^\\w\\s,]|_/g, \" \");\n var trimmed = noPunctuation.trim();\n var noWhiteSpace = trimmed.replace(/[ \\t\\r]+/g,\"_\");\n //console.log(noWhiteSpace);\n var parts = noWhiteSpace.split(\",\");\n if (parts.length > 1) {\n for (var i = 0; i < parts.length; i++) {\n clean(parts[i], true, function(err, part) {\n if (err) return next(err);\n forRet.push(part);\n if (forRet.length == parts.length) next(null, forRet);\n });\n }\n }\n if (isRecursive) next(null, parts[0]);\n else {\n forRet.push(parts[0]);\n next(null, forRet);\n }\n}",
"function analyzeQuery(query, root)\n {\n let allSubQueries = [{\n exact: [],\n sort: {},\n range: []\n }];\n\n // First, go through the query for all exact match fields\n Object.keys(query).forEach(function(key)\n {\n const value = query[key];\n\n // This is not a special mongo field\n if(key[0] != '$')\n {\n // Now look at the value, and decide what to do with it\n if(value instanceof Date || value instanceof mongodb.ObjectID || value instanceof mongodb.DBRef)\n {\n allSubQueries.forEach(subQuery => subQuery.exact.push(trimPeriods(root + key)));\n }\n else if(value instanceof Object)\n {\n const subQueries = analyzeQuery(value, root + key);\n allSubQueries = mergeSubQueries(allSubQueries, subQueries);\n }\n else\n {\n allSubQueries.forEach(subQuery => subQuery.exact.push(trimPeriods(root + key)));\n }\n }\n else\n {\n if(key == '$lt' || key == '$lte' || key == '$gt' || key == '$gte' || key == '$in' || key == '$nin' || key == '$neq' || key == '$ne' || key == '$exists' || key == '$mod' || key == '$all' || key == '$regex' || key == '$size')\n {\n allSubQueries.forEach(subQuery => subQuery.range.push(trimPeriods(root)));\n }\n else if(key == '$eq')\n {\n allSubQueries.forEach(subQuery => subQuery.exact.push(trimPeriods(root)));\n }\n else if(key == \"$not\")\n {\n const elemSubQueries = analyzeQuery(value, root);\n allSubQueries = mergeSubQueries(allSubQueries, elemSubQueries);\n }\n else if(key == '$elemMatch')\n {\n // For $elemMatch, we have to create a subquery, and then modify its field names and merge\n // it into our existing sub queries\n const elemSubQueries = analyzeQuery(value, root + \".\");\n allSubQueries = mergeSubQueries(allSubQueries, elemSubQueries);\n }\n else if(key == '$options' || key == '$hint' || key == '$explain' || key == '$text')\n {\n // We can safely ignore these\n }\n else if(key == '$and' || key == '$or')\n {\n // Ignore these, they are processed after\n }\n else if(key == '$comment')\n {\n // Comments can be used by the application to provide additional metadata about the query\n allComments.push(value);\n }\n else\n {\n console.error(\"Unrecognized field query command: \", key);\n }\n }\n });\n\n // Now if there are $and conditions, process them\n if (query['$and'])\n {\n query['$and'].forEach(function(andSubQuery)\n {\n allSubQueries = mergeSubQueries(allSubQueries, analyzeQuery(andSubQuery, root));\n });\n }\n\n // Lastly, process any $or conditions\n if (query['$or'])\n {\n allSubQueries = mergeSubQueries(allSubQueries, underscore.flatten(query['$or'].map(subQuery => analyzeQuery(subQuery, root))));\n }\n\n return allSubQueries;\n }",
"function assertExec(q, paramValues, paramTypes, want, cb) {\n var testCb = function(err) {\n t.error(err);\n cb();\n };\n var stream = paramValues === undefined ?\n db.exec(ctx, q, testCb) :\n db.exec(ctx, q, paramValues, paramTypes, testCb);\n stream.on('error', t.error);\n toArray(stream, function(err, got) {\n t.error(err);\n got.sort(arrayCompare);\n want.sort(arrayCompare);\n\n var msg = 'query: \"' + q + '\" returns the correct values';\n t.deepEqual(got, want, msg);\n });\n }",
"function create_echo2_entry_query(type, targetURL, sortOrder, itemsPerPage) {\n return type + ':' + targetURL\n + (sortOrder ? ' sortOrder:' + sortOrder : '')\n + ' type:comment -(user.state:ModeratorBanned OR state:ModeratorDeleted,SystemFlagged,CommunityFlagged) -source:Twitter safeHTML:aggressive children -(user.state:ModeratorBanned OR state:ModeratorDeleted,SystemFlagged,CommunityFlagged) safeHTML:aggressive'\n + (itemsPerPage ? ' itemsPerPage:' + itemsPerPage : '');\n }",
"function extractDatabase2(params, callback) {\n // params: [year, brand, color]\n queryDmCode(params,function(d){\n // TODO: process d on a better way for displaying on client side.\n console.log(\"Sucessfully extracted TOP20 damage codes\");\n console.log(d);\n callback(d);\n });\n}",
"function insertQuery(item) {\n var q = 'INSERT INTO inventory(description, category, date_recieved, storage_location, present, reserved)' +\n 'VALUES(';\n q += '\\'' + item.description + '\\', ';\n q += '\\'' + item.category + '\\', ';\n q += 'NOW(), ';\n q += item.storage_location + ', ';\n\n if(item.present === 'on') {\n q += '\\'yes\\', ';\n } else {\n q += '\\'no\\', ';\n }\n\n if(item.reserved === 'on') {\n q += '\\'yes\\');';\n } else {\n q += '\\'no\\');';\n }\n\n return q;\n}",
"function prepareQuery(hash) {\n\t'use strict';\n\tds.historics.prepare({\n\t\t'hash': hash,\n\t\t'start': startTime,\n\t\t'end': endTime,\n\t\t'sources': 'twitter',\n\t\t'name': 'Example historic query'\n\t}, function(err, response) {\n\t\tif (err)\n\t\t\tconsole.log(err);\n\t\telse {\n\t\t\tconsole.log('Prepared query: ' + response.id);\n\t\t\tcreateSubscription(response.id);\n\t\t}\n\t});\n}",
"queryRunner(data,callback){\n /*\n Function required to run all the queries.\n */\n const query=data.query;\n const insert_data=data.insert_data;\n const that = this;\n this.connection.getConnection(function(err,con){\n if(err){\n con.release();\n }else{\n that.connection.query(String(query),insert_data,function(err,rows){\n con.release();\n if(err){\n callback({\"status\": 500, \"error\": err, \"data\": null});\n } else {\n callback({\"status\": 200, \"error\": null, \"data\": rows});\n }\n });\n }\n });\n }",
"async function introspectionProvider(introspectionQuery) {\n \n const authDetails = getAuthDetails();\n \n return getGQLSchema(introspectionQuery); \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This functions calculates the tax for a company + province. | function calculateTax(totalSales, companyProv){
// Multiple totalSales by province tax rate.
return totalSales * salesTaxRates[companyProv];
} | [
"function calculateTax() {\n return payGrades[getCadre()].taxMultiplier * salary;\n}",
"calcTax() {\n let costGettingIncome, costGettingIncomePercentage, taxBase;\n \n if (elements.workContractCosts20.checked) {\n costGettingIncomePercentage = 0.2;\n } else if (elements.workContractCosts50.checked) {\n costGettingIncomePercentage = 0.5;\n }\n \n if (!elements.flatTax.checked) {\n costGettingIncome = Math.round(this.payment * costGettingIncomePercentage);\n taxBase = Math.round(this.payment - costGettingIncome);\n } else {\n taxBase = Math.round(this.payment);\n }\n\n this.PIT = Math.round(taxBase * 0.17);\n }",
"function calculateTaxes(income) {\n if (income < 10000) {\n return (income * .05);\n } else if (income >10000 <20000) {\n return (income * .10);\n } else if (income > 20000) {\n return (income * 15);\n } \n}",
"function taxCalculator(num1, state) {\n if (state == \"NY\") {\n num1 = 4 / 100 + 1;\n } else {\n num1 = 6.625 / 100 + 1;\n }\n sum = 100 * num1;\n return sum;\n}",
"function taxCalculator(amount, taxrate){\n return amount + (amount * taxrate);\n}",
"function _totalTaxTable() {\n \ttry {\n \t\tvar total_header \t=\t$('.total-header').text().trim();\n \t\tvar freight_val\t\t=\t0;\n \t\tvar insurance_val\t=\t0;\n \t\tvar tax_jp \t\t\t=\t0;\n \t\tif (!$('.value-freight').hasClass('hidden')) {\n\t \t\tfreight_val \t= \t$('.value-freight').val().trim();\n\t\t}\n \t\tif (!$('.value-insurance').hasClass('hidden')) {\n\t\t\tinsurance_val \t= \t$('.value-insurance').val().trim();\n\t\t}\n \t\tif (!$('.value-jp').hasClass('hidden')) {\n\t\t\ttax_jp \t\t\t= \t$('.value-jp').val().trim();\n\t\t}\n\t\tvar total_footer \t=\tparseFloat(freight_val) + parseFloat(insurance_val) + parseFloat(tax_jp) + parseFloat(total_header);\n\t\t$('.total-footer').text(_convertMoneyToIntAndContra(total_footer));\n\t} catch (e) {\n alert('_totalTaxTable' + e.message);\n }\n }",
"function getTaxBill(income) {\n if (income < 0) {\n setTaxBill(0);\n } else if (income < 9875) {\n setTaxBill(income * 0.1);\n } else if (income < 40125) {\n setTaxBill(987.5 + (income - 9875) * 0.12);\n } else if (income < 85525) {\n setTaxBill(4617.5 + (income - 40125) * 0.22);\n } else if (income < 163301) {\n setTaxBill(14605.5 + (income - 85525) * 0.24);\n } else if (income < 207350) {\n setTaxBill(33271.5 + (income - 163300) * 0.32);\n } else if (income < 518400) {\n setTaxBill(47367.5 + (income - 207350) * 0.35);\n } else {\n setTaxBill(156235 + (income - 518400) * 0.37);\n }\n }",
"calcNettoPayment() {\n if (elements.ageInputWork.checked) {\n this.calcTax();\n this.netAmount = this.payment - this.PIT;\n } else {\n this.netAmountUnderAge = this.payment;\n }\n }",
"function tax_on_item(amount, tax_rate)\n{\n return Math.round(tax_rate * amount) / 100.0;\n}",
"calculateCashOnCash() { return parseFloat((this.calculateCashFlow() / this.calculateTotalCapitalRequired()).toFixed(3)) }",
"function calculateFunction () {\r\n income();\r\n expences();\r\n enumenator();\r\n allBudget(); \r\n}",
"function calculateBill(total, tax = 0.12, tip = 0.15) {\n return total + (total * tax) + (total * tip);\n}",
"function math_vat_rate(vat) {\n\tvar math_tax_rate = '';\n\tif(vat.length == 2){ math_tax_rate = parseFloat('1.'+vat); }\n\telse { math_tax_rate = parseFloat('1.'+'0'+vat); }\n\treturn math_tax_rate;\n}",
"function propertyAnalysis(propertyLoan, propertyPurchase, depreciation, rentalIncome, globalData, yearlyChanges, expenses, sale, selScen){\n\n\tvar i = sale[selScen].years * 12;\t\n\tvar propertyValue = Object.create({grossIncome:[i], operatingExpense:[i], netIncomeAfterTD:[i], taxes:[i], cashFlow:[i], propertyAppreciation:[i], alternateInvestment:[i]});\n\t\n\tvar loanPayment = loanCalculator(propertyLoan, propertyPurchase, selScen);\n\tvar monDep = calculateDepreciation(propertyPurchase, depreciation, selScen); //monthly depreciation\n\tvar taxableIncome; //B21\n\tvar netIncome; //B16\n\tvar cumulativeCashFlow = 0; //B28\n\tvar cumulativePrincipal = 0; //B36\n\tvar cumulativeTaxRecapDep = 0; //B42\n\t\n\tfor(var mon = 0; mon < sale[selScen].years * 12; mon++){\n\t\tpropertyValue.grossIncome[mon] = grossIncome(rentalIncome, yearlyChanges, expenses, mon, selScen); //B5\n\t\tpropertyValue.operatingExpense[mon] = operatingExpense(propertyLoan, propertyPurchase, rentalIncome, yearlyChanges, expenses, mon, selScen); //B14\n\t\tnetIncome = propertyValue.grossIncome[mon] - propertyValue.operatingExpense[mon] - loanPayment.interestPayment[mon];\t//B16\n\t\ttaxableIncome = netIncome - monDep; \n\t\tpropertyValue.taxes[mon] = ((netIncome - monDep) > 0 ? (netIncome - monDep) : 0) * globalData[selScen].personalTaxBracket/100; //B22\n\t\tpropertyValue.netIncomeAfterTD[mon] = taxableIncome - propertyValue.taxes[mon]; //B23\n\t\tpropertyValue.cashFlow[mon] = propertyValue.netIncomeAfterTD[mon] + monDep; //B27\n\t\tcumulativeCashFlow = cumulativeCashFlow * (1 + yearlyChanges[selScen].alternateInvestmentReturn/100/12) + propertyValue.cashFlow[mon]; //B28\n\t\tcumulativePrincipal = cumulativePrincipal * (1 + yearlyChanges[selScen].alternateInvestmentReturn/100/12) + (loanPayment.monthlyPayment - loanPayment.interestPayment[mon]); //B36\n\t\tcumulativeTaxRecapDep += (monDep * globalData[selScen].depreciationTaxRate/100) ; //B42\n\n\t\tpropertyValue.propertyAppreciation[mon] = propertyAppreciation(propertyLoan, propertyPurchase, globalData, yearlyChanges, sale, selScen, mon, loanPayment, monDep) +\n\t\t\t\tcumulativeCashFlow - cumulativePrincipal - cumulativeTaxRecapDep; //B45\t\t\t\t\n\t\tpropertyValue.alternateInvestment[mon] = alternateInvestment(propertyLoan, propertyPurchase, globalData, yearlyChanges, selScen, mon); //B50\t\t\n\t}\n\t\n\treturn propertyValue;\n}//propertyAnalysis",
"function paytaxes(x) {\n return 0;\n // int i;\n // int amt;\n //\n // if (x<0) return(0);\n // if (readboard()<0) return(0L);\n // for (i=0; i<SCORESIZE; i++)\n // \tif (strcmp(winr[i].who, logname) == 0) /* look for players winning entry */\n // \t\tif (winr[i].score>0) /* search for a winning entry for the player */\n // \t\t{\n // \t\t\tamt = winr[i].taxes;\n // \t\t\tif (x < amt) amt=x; /* don't overpay taxes (Ughhhhh) */\n // \t\t\twinr[i].taxes -= amt;\n // \t\t\toutstanding_taxes -= amt;\n // \t\t\tif (writeboard()<0)\n // \t\t\t\treturn(0);\n // \t\t\treturn(amt);\n // \t\t}\n // \t\treturn(0L); /* couldn't find user on winning scoreboard */\n}",
"function propertyAppreciation(propertyLoan, propertyPurchase, globalData, yearlyChanges, sale, selScen, month, loanPayment, monDep){\n\tvar curPropValue = propertyPurchase[selScen].purchasePrice * Math.pow(1 + ((yearlyChanges[selScen].propertyAppreciation/100)/12), month); //B40\n\tvar salesCharge = curPropValue * sale[selScen].commission/100; //B41\n\tvar costBasis = (propertyPurchase[selScen].closingCost/100 + 1) * propertyPurchase[selScen].purchasePrice + propertyPurchase[selScen].capitalImprovement;\n\tvar taxGain = ((curPropValue - salesCharge - costBasis) * globalData[selScen].longTermCapitalGain/100); //B43\n\tvar totalInitialPayment = propertyPurchase[selScen].closingCost/100 * propertyPurchase[selScen].purchasePrice + propertyPurchase[selScen].capitalImprovement + \n\t\tpropertyPurchase[selScen].purchasePrice * propertyLoan.downPayment/100; //PB35\n\n\treturn (((curPropValue - salesCharge - loanPayment.endingBalance[month]) - taxGain) - totalInitialPayment);\n}//propertyAppreciation",
"function calculateYears(principal, interest, tax, desired) {\n let year = 0\n\n for (year; principal < desired; year++ ) {\n principal = principal + (principal * interest - (principal * interest * tax))\n }\n return year\n}",
"function solve(meal_cost, tip_percent, tax_percent) {\n // Write your code here\n let mealCost = meal_cost;\n let tipPercent = tip_percent;\n let taxPercent = tax_percent;\n\n // tip = 12 and 12/100 x 20 = 2.4\n let tip = (mealCost / 100) * tipPercent;\n // console.log(tip);\n\n // tax = 8 and 8/100 x 20 = 0.96\n let tax = (mealCost / 100) * taxPercent;\n // console.log(tax);\n\n // total_cost = meal_cost + tip + tax = 12 + 2.4 + 0.96 = 15.36\n let totalCost = Math.round(mealCost + tip + tax);\n // console.log(totalCost);\n\n // round(total_cost) = 15 (rounded total_cost to the nearest integer)\n return totalCost;\n}",
"function getPV(current_cashflow, growth_rate_1, growth_rate_2, discount_rate){\n var pv = 0\n var temp = current_cashflow\n var sum = 0\n for(var i = 0; i < 10; i++){\n var discountFactor = 1 / (1 + discount_rate) ** (i + 1)\n //Before Discount\n if(i < 3)\n temp = temp * growth_rate_1 \n else\n temp = temp * growth_rate_2 \n // console.log(\"temp\", i+1, \": \", temp);\n //After discount\n sum += temp * discountFactor\n // console.log(\"discount\", i+1, \": \", discountFactor);\n // console.log(\"sum \",i+1, \": \",sum)\n }\n pv = sum\n return pv\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send data to a specific client for a specific method | function sendData (client, method, data) {
var packet = { methodName : method, data : data };
client.fn.send("PROJECT", packet);
} | [
"signal (client, {signal, name}) {\n client.signal = signal\n\n let roomId = client.roomId\n let room = this._getRoom(roomId)\n room.signal(client.myName, name, signal)\n }",
"send(...args) {\n this._send_handler(...args)\n }",
"send (channel, data) {\n this.transporters.forEach(transporter => {\n transporter.send(channel, data)\n })\n }",
"function send( type, data ) {\n\tServer.send( type, data );\n}",
"send(otherClient, msg) {\n if (this.id === otherClient.id) {\n throw Error(\"Invalid client\");\n }\n if (otherClient.ws) return sendServerMsg(otherClient.ws, msg);\n this.enqueue(msg);\n }",
"sendInfo() {\n this.sendPlayers();\n this.sendObjects();\n }",
"send(peer_id, data) {\n this.peers[peer_id].send(data);\n }",
"send (action) {\n if(this.options.shouldSend(action)) {\n let tracedAction = Object.assign({},action,{origin:\"client\" });\n this.log('Sending to the server the action ', tracedAction);\n this.ws.send(JSON.stringify(tracedAction ));\n }\n }",
"send(srcClientID, msg) {\n var src = this.client(srcClientID);\n if (this.clients.size === 1) return src.enqueue(msg);\n\n for (var oc of this.clients.values()) {\n if (oc.id !== srcClientID) return src.send(oc, msg);\n }\n throw Error(\"Corrupted room \" + this.id);\n }",
"sendCommand (name, deviceId, remoteType, groupId, command) {\n if (this.mqttClient) {\n var path = this.mqttTopicPattern.replace(':hex_device_id', '0x' + deviceId.toString(16).toUpperCase()).replace(':dec_device_id', deviceId).replace(':device_id', deviceId).replace(':device_type', remoteType).replace(':group_id', groupId);\n const sendBody = JSON.stringify(command);\n try {\n this.log(\"MQTT out: \" + name + \" - \" + path, command);\n this.mqttClient.publish(path, sendBody);\n } catch (e) {\n this.log(e);\n }\n } else {\n var path = '/gateways/' + '0x' + deviceId.toString(16) + '/' + remoteType + '/' + groupId;\n this.log(\"HTTP out: \" + name + \" - \" + path, command);\n this.apiCall(path, command);\n }\n }",
"function write2BleClient(type, data) {\n let obj = {\n cmdtype: type,\n cmdData: data\n };\n if (bleClientSocket != null) {\n bleClientSocket.write(JSON.stringify(obj));\n }\n}",
"_send(type, data) {\n this._midiOutput.send(type, _.extend(data, { channel: this._midiChannel } )); \n }",
"onConnectionMessage(con, msg) {\n var data = JSON.parse(msg);\n\n switch (data.type) {\n case \"1\":\n var userMessage = {\n type: \"5\",\n user: this.listClients.get(con).getUsername(),\n missatge: data.msg\n }\n var userMessageString = JSON.stringify(userMessage);\n this.enviaBroadcastClients(userMessageString);\n break;\n case \"4\":\n // mirar si el nom esta repetit o no:\n // this.listClients.get(con).setUsername(data.nomActualitzat); \n // this.enviaNomsClients();\n // console.log(\"nou nom \" + data.nomActualitzat);\n // console.log(\"id \" + data.idUser);\n this.bd.comprovaNom(data.idUser, data.nomActualitzat, con, this);\n\n break;\n case \"login\":\n this.bd.comprovaUsuari(data.user, data.password, con, this);\n break;\n case \"newUser\":\n this.bd.comprovaEmail(data.email, data.username, data.password,con,this)\n console.log(\"afegir usuari \");\n break;\n case \"foto\":\n this.bd.afegeixFoto(data.idUser, data.foto)\n this.listClients.get(con).setFoto(data.foto)\n console.log(this.listClients.get(con).getFoto())\n var fotoString = JSON.stringify(data);\n this.enviaBroadcastClients(fotoString)\n break;\n\n }\n\n }",
"forward(client, message) {\n client.send(message, this.options.serverPort, this.options.serverAddress);\n }",
"function _send(method, params) {\n console.log({\n \"method\" : method,\n \"params\" : params\n });\n\n // Get JSON Web token test in private functions\n // res: is object that contains the token\n return $http.post(SERVER + method , params ,{ headers : {}}).then(\n function(res){\n if(service.debug)\n console.log({\n \"method\" : method,\n \"params\" : params,\n \"result\" : res.data\n });\n return handleSuccess(res);\n },\n function(res){\n return handleError(res);\n });\n } // end _send",
"function callInitialMethods() {\n console.log(\"EVERYTHIN WE NEED IS clientConnId \", clientConnId,\n \" AND utk \", UTK);\n if (clientConnId) {\n // getHubspotInfo\n ddp.method(\"getHubspotInfo\", [{\n clientIp, clientConnId, UTK\n }], function(err, res) {\n if (err) throw err;\n console.log(\"Success on my part getHubspotInfo\");\n });\n\n // updateHistory\n ddp.method(\"updateHistory\", [{\n clientIp, clientConnId, visitedOne\n }], function(err, res) {\n if (err) throw err;\n console.log(\"UPDATE HISTORY clientIp\", clientIp, \"clientConnId\",\n clientConnId, \"visitedOne\", visitedOne);\n console.log(\"Success on my part history\");\n });\n } else {\n setTimeout(function() {\n callInitialMethods();\n }, 50);\n }\n } //callInitialMethods",
"function sendToDevice(id,message) {\n //get in mirrored array a connection with selected key\n if(connections[id]!=null){\n connections[id].sendText(message);\n console.log(message);\n }\n \n}",
"onAddTetheredClient(tetheredClient) {\n super.onAddTetheredClient(tetheredClient);\n\n const client = tetheredClient.client;\n const myClient = tetheredClient.myClient;\n const incomingData = tetheredClient.incomingData;\n console.log(\"SharedRoom\", \"onAddMyClient\");\n }",
"function callOpcuaMethod(nodeId, args, callback){\n var methodCallRequest = {\n\tobjectId: \"ns=1;i=1000\", // Node ID of the robot arm\n\tmethodId: nodeId,\n\tinputArguments: args\n };\n \n session.call(methodCallRequest, callback);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns whether the user is the owner of this CL. | isOwner(user) {
return this.json_.owner._account_id === user._account_id;
} | [
"function isMasterUser()\n {\n return (masterUser == username && masterUserId == userId);\n }",
"'entries.isOwner' (entryId) {\n console.log('see if user can access this entry');\n\n // If no user is logged in, throw an error\n if (!Meteor.user()) {\n console.log(\"No user is logged in!\");\n return false;\n }\n \n // Locate the entry\n let entry = JournalEntryCollection.findOne({_id: entryId});\n\n // If no entry exists, the logged in user can't access it\n if (!entry) {\n console.log(`entry with ID ${entryId} wasn't found`);\n return false;\n }\n\n console.log(`Entry found: ${entry._id}, ${entry.text}`);\n\n // If the entry's owner is not the logged in user, they\n // can't access it\n if (entry.ownerId != Meteor.userId()) {\n console.log(`This entry belongs to ${entry.ownerId} but the logged in user is ${Meteor.userId()}`);\n return false;\n }\n\n // The entry exists and the logged in user is the owner,\n // so they can access it\n return true;\n }",
"getOwner() {\n this.logger.debug(GuildService.name, this.getOwner.name, \"Executing\");\n this.logger.debug(GuildService.name, this.getOwner.name, \"Getting owner and exiting.\");\n return this.guild.owner.user;\n }",
"async function checkOwner(presentationid, userid) {\n let queryIfOwner = `SELECT * FROM public.presentations t\n WHERE id = '${presentationid}' and user_id = '${userid}'`;\n let isOwner = await db.select(queryIfOwner);\n if (isOwner) {\n return true;\n } else {\n return false;\n }\n}",
"get isOneToOneOwner() {\n return this.isOneToOne && this.isOwning;\n }",
"function isRouteOwner(req, res, next) {\n if (!req.params.user) {\n next(new Error('Invalid route: missing user parameter.'));\n } else if (req.params.user != req.user.username) {\n next(new Error('Is not owner'));\n } else {\n req.isOwner=true;\n next(null);\n }\n}",
"isUserAuthenticated() {\n let token = this.getToken();\n return token !== null && token !== undefined;\n }",
"function isEditable() {\n return (current && current.isOwner && !current.frozen);\n}",
"get isOwning() {\n return !!(this.isManyToOne ||\n (this.isManyToMany && this.joinTable) ||\n (this.isOneToOne && this.joinColumn));\n }",
"canManageTheServer(user_id) {\n return this.userHasPermissions(user_id, P_ADMINISTRATOR) ||\n this.userHasPermissions(user_id, P_MANAGE_GUILD) ||\n this.isServerOwner(user_id);\n }",
"function isAdmin()\n {\n return (adminList.indexOf(socket.username) > -1);\n }",
"isPermitted(user_id) {\n if (!user_id) return false;\n for(var permitted in this.permitted) {\n if ( permitted == user_id ) return this.permitted[permitted] != null;\n if ( botStuff.userHasRole(this.server_id, user_id, permitted)) return this.permitted[permitted] != null;\n }\n return false;\n }",
"isMember(state) {\n return state.oauth.user !== null && ['board', 'member'].indexOf(state.oauth.user.level) !== -1;\n }",
"function canAffect(userRole, targetRole) {\n if (userRole === 'owner') {\n return true;\n }\n\n if (targetRole === 'owner') {\n return false;\n }\n\n return userRole === 'moderator' && targetRole === 'user';\n}",
"get isOneToOneNotOwner() {\n return this.isOneToOne && !this.isOwning;\n }",
"function isModerator(user){\r\n return user.mod;\r\n}",
"isSuperUserForOrg(org) {\n\t\tif (!org) { return false }\n\t\tif (this.position && this.position.type === 'ADMINISTRATOR') { return true }\n\t\tif (this.position && this.position.type !== 'SUPER_USER') { return false }\n\t\tif (org.type === 'PRINCIPAL_ORG') { return true }\n\n\t\tif (!this.position || !this.position.organization) { return false }\n\t\tlet orgs = this.position.organization.allDescendantOrgs || []\n\t\torgs.push(this.position.organization)\n\t\tlet orgIds = orgs.map(o => o.id)\n\n\t\treturn orgIds.includes(org.id)\n\t}",
"canSeePlayer(){\n\t\t//enemy should act like it doesn't know where the player is if they're dead\n\t\tif(lostgame)\n\t\t\treturn false;\n\t\t\n\t\t// casts a ray to see if the line of sight has anything in the way\n\t\tvar rc = ray.fromPoints(this.pos, p1.pos);\n\t\t\n\t\t// creates a bounding box for the ray so that the ray only tests intersection\n\t\t// for the blocks in that bounding box\n\t\tvar rcbb = box.fromPoints(this.pos, p1.pos);\n\t\tvar poscols = []; // the blocks in the bounding box\n\t\tfor(var i = 0; i < blocks.length; i++){\n\t\t\tif(box.testOverlap(blocks[i].col, rcbb))\n\t\t\t\tposcols.push(blocks[i]);\n\t\t}\n\t\t\n\t\t// tests ray intersection for all the blocks in th ebounding box\n\t\tfor(var i = 0; i < poscols.length; i++){\n\t\t\tif(poscols[i].col.testIntersect(rc))\n\t\t\t\treturn false; // there is a ray intersection, the enemy's view is obstructed\n\t\t}\n\t\treturn true;\n\t}",
"checkUserContributor (userId) {\n console.log('checkUserContributor:', userId);\n let user = Auth.requireAuthentication();\n \n // Validate\n check(userId, String);\n \n // Check for the presense of a contributor record\n return Users.findOne(userId).contributor() !== null\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the due date of task in form of mm/dd/yyyy | function getDueDate(dueDate) {
dueDate.setDate(dueDate.getDate());
return `${dueDate.getFullYear()}/${dueDate.getMonth() + 1}/${dueDate.getDate()}`;
} | [
"relDateText(dateStr, now) {\n if (now == null) {\n now = new Date();\n }\n const date = new Date(dateStr);\n const period = Dates.getDateDeltaString(date, now);\n const relDateKey =\n date > now ? 'notification_is_due' : 'notification_was_due';\n return this._format(relDateKey, { period });\n }",
"function getDate() {\n let tmpDate = document.location.hash.replace(\"#\", \"\");\n tmpDate = moment(tmpDate, \"YYYY-MM-DD\");\n if (!tmpDate.isValid()) {\n tmpDate = moment();\n }\n return tmpDate.format(\"YYYY-MM-DD\");\n }",
"function getCurrentDate() {\n var now = new Date();\n var month = (now.getMonth() + 1); \n var day = now.getDate();\n if(month < 10) \n month = \"0\" + month;\n if(day < 10) \n day = \"0\" + day;\n //return now.getFullYear() + '-' + month + '-' + day;\n return month + '/' + day + '/' + now.getFullYear();\n }",
"function formattedDate()\r\n{\r\n var today = new Date();\r\n var dd = today.getDate();\r\n var mm = today.getMonth() + 1;\r\n var yyyy = today.getFullYear();\r\n\r\n if (dd < 10) \r\n {\r\n dd = '0' + dd;\r\n } \r\n if (mm < 10) \r\n {\r\n mm = '0' + mm;\r\n } \r\n\r\n var today = mm + '/' + dd + '/' + yyyy;\r\n \r\n return today;\r\n}",
"dateformat(date) { return \"\"; }",
"function returnDateStr (date) {\n let year = date.getFullYear();\n let month = date.getMonth() + 1;\n let day = date.getDate();\n if (month < 10) {\n month = `0${month}`;\n }\n if (day < 10) {\n day = `0${day}`;\n }\n return `${year}-${month}-${day}`;\n}",
"getissueDate(){\n\t\treturn this.dataArray[6];\n\t}",
"static dateToString(dateObj){\n return dateObj.getDate() + \"/\" + DateUtilities.getMonthString(dateObj.getMonth()) + \"/\" + dateObj.getFullYear();\n }",
"function formatPostDate(date) {\n \tvar date = date.split('T')[0];\n var d = new Date(date),\n month = '' + (d.getMonth() + 1),\n day = '' + d.getDate(),\n year = d.getFullYear();\n\n if (month.length < 2) month = '0' + month;\n if (day.length < 2) day = '0' + day;\n\n return [day,month,year].join('-');\n }",
"function getDebeDate() {\n let date = new Date();\n \n if(date.getUTCHours() < 4) {\n date.setDate(date.getDate() - 1);\n }\n return date.toJSON().split(\"T\")[0]\n}",
"function renewalDate(oh) {\n\n if (oh.planType !== 'A' && oh.status === 'success') {\n return $filter('date')(moment(oh.billingPeriodEndDate).add(1, 'day').format(), 'dd-MMM-yyyy');\n } else {\n return 'N/A';\n }\n\n }",
"function formatDate(dt, dl)\n{\n var dd = (\"0\" + dt.getDate());\n var mm = (\"0\" + (dt.getMonth() + 1));\n var yy = dt.getFullYear();\n\n var fdate = yy + dl + mm.slice(-2) + dl + dd.slice(-2);\n //console.log(\"\\t\\tdd is [\" + dd + \"] mm is [\" + mm + \"] yy = [\" + yy + \"] dl = [\" + dl + \"] -> fdate is [\" + fdate + \"]\");\n return(fdate);\n}",
"function formatDateddMMyyyy(d){\n return d.substr(0,2) + '/' + d.substr(2,2) + '/' + d.substr(4,4) ;\n }",
"toDateString() {\n return `${this.nepaliYear.toString()}/${this.nepaliMonth}/${\n this.nepaliDay\n }`;\n }",
"function datePrecedente(date) {\n var dt = date.split('/');\n var myDate = new Date(dt[2] + '-' + dt[1] + '-' + dt[0]);\n myDate.setDate(myDate.getDate() + -1);\n newDate = formatDateSlash(myDate);\n return newDate;\n}",
"function formatDateTraitement(date){\n\t\t\t\tvar dateArray = date.split(\"/\");\n\t\t\t\treturn dateArray[2] + \"-\" + dateArray[1] + \"-\" + dateArray[0];\n\t\t\t}",
"function getDate(filePath) {\n var arr = filePath.split('/');\n var filename = arr[arr.length - 1];\n var uploadTime = filename.slice(0, 14);\n var date = uploadTime.slice(0, 4) + \"/\"\n + uploadTime.slice(4, 6) + \"/\"\n + uploadTime.slice(6, 8) + \" \"\n + uploadTime.slice(8, 10) + \":\"\n + uploadTime.slice(10, 12) + \":\"\n + uploadTime.slice(12, 14);\n\n return date;\n }",
"function toDatepickerFormat(date) {\r\n var d = new Date(date);\r\n var month = '' + (d.getMonth() + 1);\r\n var day = '' + d.getDate();\r\n var year = d.getFullYear();\r\n\r\n if (month.length < 2) month = '0' + month;\r\n if (day.length < 2) day = '0' + day;\r\n\r\n return [year, month, day].join('-');\r\n}",
"function addIntervalToDate(due, count, unit) {\n let days = 0;\n let months = 0;\n switch (unit) {\n case \"b\":\n // add \"mul\" business days, defined as not Sat or Sun\n {\n let incr = (count >= 0)? 1: -1;\n let bdays_left = count * incr;\n let millisec_due = due.getTime();\n let day_of_week = due.getDay(); // 0=Sunday, 1..5 weekday, 6=Saturday\n while (bdays_left > 0) {\n millisec_due += 1000 * 60 * 60 * 24 * incr; // add a day to time\n if (incr > 0) {\n day_of_week = (day_of_week < 6 ? day_of_week + incr : 0);\n } else {\n day_of_week = (day_of_week > 0 ? day_of_week + incr : 6);\n }\n if (day_of_week > 0 && day_of_week < 6) {\n bdays_left--; // one business day step accounted for!\n }\n }\n return new Date(millisec_due);\n }\n case \"d\":\n days = 1;\n break;\n case \"w\":\n days = 7;\n break;\n case \"m\":\n months = 1;\n break;\n case \"y\":\n months = 12;\n break;\n }\n if (months > 0) {\n let due_month = due.getMonth() + count * months;\n let due_year = due.getFullYear() + Math.floor(due_month/12);\n due_month = due_month % 12;\n let monthlen = new Date(due_year, due_month+1, 0).getDate();\n let due_day = Math.min(due.getDate(), monthlen);\n return new Date(due_year, due_month, due_day);\n }\n due = due.getTime();\n due += 1000 * 60 * 60 * 24 * count * days;\n return new Date(due);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Render a chunk of text, typically one line (but for justified text we render each word as a separate Text object, because spacing is variable). Returns true when it finished the current node. After each chunk it updates `start` to just after the last rendered character. | function doChunk() {
var origStart = start;
var box, pos = text.substr(start).search(/\S/);
start += pos;
if (pos < 0 || start >= end) {
return true;
}
// Select a single character to determine the height of a line of text. The box.bottom
// will be essential for us to figure out where the next line begins.
range.setStart(node, start);
range.setEnd(node, start + 1);
box = actuallyGetRangeBoundingRect(range);
// for justified text we must split at each space, because space has variable width.
var found = false;
if (isJustified || columnCount > 1) {
pos = text.substr(start).search(/\s/);
if (pos >= 0) {
// we can only split there if it's on the same line, otherwise we'll fall back
// to the default mechanism (see findEOL below).
range.setEnd(node, start + pos);
var r = actuallyGetRangeBoundingRect(range);
if (r.bottom == box.bottom) {
box = r;
found = true;
start += pos;
}
}
}
if (!found) {
// This code does three things: (1) it selects one line of text in `range`, (2) it
// leaves the bounding rect of that line in `box` and (3) it returns the position
// just after the EOL. We know where the line starts (`start`) but we don't know
// where it ends. To figure this out, we select a piece of text and look at the
// bottom of the bounding box. If it changes, we have more than one line selected
// and should retry with a smaller selection.
//
// To speed things up, we first try to select all text in the node (`start` ->
// `end`). If there's more than one line there, then select only half of it. And
// so on. When we find a value for `end` that fits in one line, we try increasing
// it (also in halves) until we get to the next line. The algorithm stops when the
// right side of the bounding box does not change.
//
// One more thing to note is that everything happens in a single Text DOM node.
// There's no other tags inside it, therefore the left/top coordinates of the
// bounding box will not change.
pos = (function findEOL(min, eol, max){
range.setEnd(node, eol);
var r = actuallyGetRangeBoundingRect(range);
if (r.bottom != box.bottom && min < eol) {
return findEOL(min, (min + eol) >> 1, eol);
} else if (r.right != box.right) {
box = r;
if (eol < max) {
return findEOL(eol, (eol + max) >> 1, max);
} else {
return eol;
}
} else {
return eol;
}
})(start, Math.min(end, start + estimateLineLength), end);
if (pos == start) {
// if EOL is at the start, then no more text fits on this line. Skip the
// remainder of this node entirely to avoid a stack overflow.
return true;
}
start = pos;
pos = range.toString().search(/\s+$/);
if (pos === 0) {
return false; // whitespace only; we should not get here.
}
if (pos > 0) {
// eliminate trailing whitespace
range.setEnd(node, range.startOffset + pos);
box = actuallyGetRangeBoundingRect(range);
}
}
// another workaround for IE: if we rely on getBoundingClientRect() we'll overlap with the bullet for LI
// elements. Calling getClientRects() and using the *first* rect appears to give us the correct location.
// Note: not to be used in Chrome as it randomly returns a zero-width rectangle from the previous line.
if (microsoft) {
box = range.getClientRects()[0];
}
var str = range.toString();
if (!/^(?:pre|pre-wrap)$/i.test(whiteSpace)) {
// node with non-significant space -- collapse whitespace.
str = str.replace(/\s+/g, " ");
}
else if (/\t/.test(str)) {
// with significant whitespace we need to do something about literal TAB characters.
// There's no TAB glyph in a font so they would be rendered in PDF as an empty box,
// and the whole text will stretch to fill the original width. The core PDF lib
// does not have sufficient context to deal with it.
// calculate the starting column here, since we initially discarded any whitespace.
var cc = 0;
for (pos = origStart; pos < range.startOffset; ++pos) {
var code = text.charCodeAt(pos);
if (code == 9) {
// when we meet a TAB we must round up to the next tab stop.
// in all browsers TABs seem to be 8 characters.
cc += 8 - cc % 8;
} else if (code == 10 || code == 13) {
// just in case we meet a newline we must restart.
cc = 0;
} else {
// ordinary character --> advance one column
cc++;
}
}
// based on starting column, replace any TAB characters in the string we actually
// have to display with spaces so that they align to columns multiple of 8.
while ((pos = str.search("\t")) >= 0) {
var indent = " ".substr(0, 8 - (cc + pos) % 8);
str = str.substr(0, pos) + indent + str.substr(pos + 1);
}
}
if (!found) {
prevLineBottom = box.bottom;
}
drawText(str, box);
} | [
"function EndTextBlock() {\n\tif (arguments.length != 0) {\n\t\terror('Error 110: EndTextBlock(); must have empty parentheses.');\n\t}\n\telse if (EDITOR_OBJECT == null ) {\n\t\terror(\t'Error 111: EndTextBlock(); must come after a call to ' +\n\t\t\t\t'StartNewTextBlock(...);');\n\t}\n\telse if ( !(EDITOR_OBJECT instanceof text_block) ) {\n\t\terror(\t'Error 112: EndTextBlock(); must come after a call to ' +\n\t\t\t\t'StartNewTextBlock(...);');\n\t}\n\telse if (!ERROR_FOUND) {\n\t\tvar current_text_block = EDITOR_OBJECT;\n\t\tvar block_html = \t'<span class=\"' + \n\t\t\t\t\t\t\tcurrent_text_block.class + \n\t\t\t\t\t\t\t'\" ' + \n\t\t\t\t\t\t\tcurrent_text_block.html + '\">';\n\n\t\tfor (j = 0; j < current_text_block.content.length; j++) {\n\t\t\tvar item = current_text_block.content[j];\n\t\t\tblock_html += item.html;\n\t\t}\n\n\t\tcurrent_text_block.html = block_html + '</span>';\n\t\tEDITOR_OBJECT = EDITOR_STACK.pop();\n\t\tconsole.log(block_html);\n\t}\n}",
"function draw(start, stop) {\n if (!state.chunks) state.chunks = {};\n for (let i = start; i <= stop; i++) {\n // clean up trash\n if (camera.children[i] && i < start && i > stop) {\n camera.getChildByName(`${i}`).removeChild().destroy({ children: true });\n state.chunks[i] = null;\n }\n\n if (!state.chunks[i]) {\n const graphics = new PIXI.Graphics();\n graphics.name = `${i}`; // cant have negative child indexes :(\n // only negative indexes are drawn from the left\n const direction = start < 0 ? \"L\" : \"R\";\n state.chunks[i] = state.world.chunk(direction, i);\n const ground = state.chunks[i].ground;\n const trees = state.chunks[i].trees;\n\n graphics.lineStyle(3, state.chunks[i].biome.groundColor, 1);\n\n let moved = false;\n for (const x in ground) {\n if (!moved) graphics.moveTo(x * 1, ground[x]);\n graphics.lineTo(x * 1, ground[x]);\n moved = true;\n }\n for (const t of trees) {\n renderTree(t, graphics);\n }\n camera.addChild(graphics);\n }\n }\n}",
"function StartTextAnimation(i) {\n if (i < dataText[i].length) {\n // text exists! start typewriter animation\n typeWriter(dataText[i], 0, function () {\n // after callback (and whole text has been animated), start next text\n StartTextAnimation(i + 1);\n });\n }\n }",
"eatSpace() {\n let start = this.pos\n while (/[\\s\\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos\n return this.pos > start\n }",
"display() {\n this.scene.pushMatrix();\n this.spritesheet.activateShader();\n\n this.scene.translate(this.center_shift, 0, 0)\n\n for (let i = 0; i < this.text.length; i++) {\n this.spritesheet.activateCellp(this.getCharacterPosition(this.text.charAt(i)));\n this.rectangle.display();\n this.scene.translate(1, 0, 0);\n }\n\n this.scene.setActiveShaderSimple(this.scene.defaultShader);\n this.scene.popMatrix();\n }",
"function isInlineTex(content) {\n\t return content[0] !== '\\n';\n\t}",
"function chunker(text, len){\r\n var chunks = [];\r\n while(text.length > len){\r\n chunks.unshift(text.substr(0,len))\r\n text = text.substr(len);\r\n }\r\n chunks.unshift(text);\r\n return chunks;\r\n }",
"function ensureChars() {\n\t\t\twhile (pos == current.length) {\n\t\t\t\taccum += current;\n\t\t\t\tcurrent = \"\"; // In case source.next() throws\n\t\t\t\tpos = 0;\n\t\t\t\ttry {\n\t\t\t\t\tcurrent = source.next();\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (e != StopIteration) { \n\t\t\t\t\t\tthrow e; \n\t\t\t\t\t} else { return false; }\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}",
"function is_line_container_clean(wrapper) {\n var children = get_real_children(wrapper);\n var ci = children.length;\n if (ci == 1 && children[0].nodeType == 1) {\n //cracking nuts like <p><i><b>LEGACY</b></i></p>\n return is_line_container_clean(children[0]);\n }\n while (ci--) {\n var node = children[ci];\n if (node.nodeType == Node.TEXT_NODE)\n continue; //textNode pass\n return false;\n }\n return true;\n }",
"get isTextblock() { return false }",
"function completed_word()\n{\n if (_line_idx == 0) {\n return (false);\n }\n \n if (_line[_line_idx-1] == 0x20) {\n return (true);\n }\n \n return (false);\n}",
"isEndOfLine(editor) {\n const curPos = editor.getCursor();\n return (curPos.ch == editor.getDoc().getLine(curPos.line).length);\n }",
"render() {\n this.snippet = new vscode_1.SnippetString();\n this.spacer = new spacer_helper_1.SpacerHelper(this.snippet, this.eol);\n this.entities.forEach((entity, index, entities) => {\n if (!this.shouldRenderEntity(entity)) {\n return;\n }\n this.spacer.beforeEntity(entity, entities, index);\n this.renderEntity(entity);\n this.spacer.afterEntity();\n });\n return this.decorateSnippet();\n }",
"function createRedChunk(elementLength,elementStart){\n var redChunk = document.createElement('div');\n redChunk.id = 'redChunk';\n redChunk.style.width = elementLength+'px';\n redChunk.style.height = '16px';\n redChunk.style.left = elementStart+'px';\n redChunk.style.top = redTimelineTop+'px';\n redChunk.style.position = 'absolute';\n redChunk.style.backgroundColor = red;\n document.getElementById('timeline').appendChild(redChunk);\n }",
"function isEmptyNode(node) {\n if (node && node.textContent) {\n return false;\n }\n if (!node ||\n !node.childCount ||\n (node.childCount === 1 && isEmptyParagraph(node.firstChild))) {\n return true;\n }\n var block = [];\n var nonBlock = [];\n node.forEach(function (child) {\n child.isInline ? nonBlock.push(child) : block.push(child);\n });\n return (!nonBlock.length &&\n !block.filter(function (childNode) {\n return (!!childNode.childCount &&\n !(childNode.childCount === 1 && isEmptyParagraph(childNode.firstChild))) ||\n childNode.isAtom;\n }).length);\n}",
"eof() {\n return this.index >= this.tokens.length;\n }",
"function _isLineBreakOrBlockElement(element) {\r\n if (_isLineBreak(element)) {\r\n return true;\r\n }\r\n\r\n if (wysihtml5.dom.getStyle(\"display\").from(element) === \"block\") {\r\n return true;\r\n }\r\n\r\n return false;\r\n }",
"*positions(editor) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var {\n at = editor.selection,\n unit = 'offset',\n reverse: reverse$1 = false\n } = options;\n\n if (!at) {\n return;\n }\n\n var range = Editor.range(editor, at);\n var [start, end] = Range.edges(range);\n var first = reverse$1 ? end : start;\n var string = '';\n var available = 0;\n var offset = 0;\n var distance = null;\n var isNewBlock = false;\n\n var advance = () => {\n if (distance == null) {\n if (unit === 'character') {\n distance = getCharacterDistance(string);\n } else if (unit === 'word') {\n distance = getWordDistance(string);\n } else if (unit === 'line' || unit === 'block') {\n distance = string.length;\n } else {\n distance = 1;\n }\n\n string = string.slice(distance);\n } // Add or substract the offset.\n\n\n offset = reverse$1 ? offset - distance : offset + distance; // Subtract the distance traveled from the available text.\n\n available = available - distance; // If the available had room to spare, reset the distance so that it will\n // advance again next time. Otherwise, set it to the overflow amount.\n\n distance = available >= 0 ? null : 0 - available;\n };\n\n for (var [node, path] of Editor.nodes(editor, {\n at,\n reverse: reverse$1\n })) {\n if (Element.isElement(node)) {\n // Void nodes are a special case, since we don't want to iterate over\n // their content. We instead always just yield their first point.\n if (editor.isVoid(node)) {\n yield Editor.start(editor, path);\n continue;\n }\n\n if (editor.isInline(node)) {\n continue;\n }\n\n if (Editor.hasInlines(editor, node)) {\n var e = Path.isAncestor(path, end.path) ? end : Editor.end(editor, path);\n var s = Path.isAncestor(path, start.path) ? start : Editor.start(editor, path);\n var text = Editor.string(editor, {\n anchor: s,\n focus: e\n });\n string = reverse$1 ? esrever.reverse(text) : text;\n isNewBlock = true;\n }\n }\n\n if (Text.isText(node)) {\n var isFirst = Path.equals(path, first.path);\n available = node.text.length;\n offset = reverse$1 ? available : 0;\n\n if (isFirst) {\n available = reverse$1 ? first.offset : available - first.offset;\n offset = first.offset;\n }\n\n if (isFirst || isNewBlock || unit === 'offset') {\n yield {\n path,\n offset\n };\n }\n\n while (true) {\n // If there's no more string, continue to the next block.\n if (string === '') {\n break;\n } else {\n advance();\n } // If the available space hasn't overflow, we have another point to\n // yield in the current text node.\n\n\n if (available >= 0) {\n yield {\n path,\n offset\n };\n } else {\n break;\n }\n }\n\n isNewBlock = false;\n }\n }\n }",
"function emitTagAndPreviousTextNode() {\n var textBeforeTag = html.slice(currentDataIdx, currentTag.idx);\n if (textBeforeTag) {\n // the html tag was the first element in the html string, or two\n // tags next to each other, in which case we should not emit a text\n // node\n onText(textBeforeTag, currentDataIdx);\n }\n if (currentTag.type === 'comment') {\n onComment(currentTag.idx);\n }\n else if (currentTag.type === 'doctype') {\n onDoctype(currentTag.idx);\n }\n else {\n if (currentTag.isOpening) {\n onOpenTag(currentTag.name, currentTag.idx);\n }\n if (currentTag.isClosing) {\n // note: self-closing tags will emit both opening and closing\n onCloseTag(currentTag.name, currentTag.idx);\n }\n }\n // Since we just emitted a tag, reset to the data state for the next char\n resetToDataState();\n currentDataIdx = charIdx + 1;\n }",
"function checkOperationLength() {\n if (displayEl.textContent.length > 10) {return false;}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
maps all values of an array to the given constant | function getConstant(value) {
return toArrayMap(() => value);
} | [
"function add1ToEach(array) {\n return array.map (function (value2) { return value2 += 1; })\n}",
"function map(v, a, b, c, d) {\n return (v - a) / (b - a) * (d - c) + c\n }",
"function multiplyby10(arr){\nreturn arr.map(function(elem){\nreturn elem*10;\n});\n}",
"function modifyArray(nums) {\n return nums.map(s=> s%2==0 ? s*2: s*3 )\n\n\n }",
"function map(letter) {\n\t if (letter === 'a') return [ 0.1 ];\n\t if (letter === 'b') return [ 0.3 ];\n\t if (letter === 'c') return [ 0.5 ];\n\t return 0;\n\t}",
"function createValueMap(min, max) {\n const map = [...valueMap];\n\n for (let i = 0; i < 256; i++) {\n if (i <= min || i >= max) {\n map[i] = 0;\n }\n }\n return map;\n}",
"function rebuildIndexMapBruteForce() {\n var i;\n indexMap = {};\n\n for (i = 0; i < array.length; i += 1) {\n indexMap[array[i].id] = i;\n }\n }",
"function multiplyArrValues(array){ \nvar result = 1; \n for( let i = 0; i < array.length; i++) { \n for (let j = 0; j < array[i].length ; j++){\n result *= array[i][j]; \n }\n }\n return result;\n}",
"function mapMethod() {\n\tvar testarray=[1,2,3,4];\n\tvar result=_.map(testarray, function(num) {\n\t\treturn num*3;\n\t});\n\tconsole.log(result);\n}",
"function toCelsius(array) {\n const celcius = (x) => (x - 32) * (5 / 9);\n //create a new array with result of calling celcius function\n return array.map(celcius);\n}",
"function array5(celsius){\n var toFahrenheit = celsius.map(function(c) {\n var resultado = (c * 1.8) + 32;\n return resultado.toFixed(1);\n });\n return toFahrenheit;\n}",
"function initCharCodeToOptimizedIndexMap() {\n if ((0, utils_1.isEmpty)(charCodeToOptimizedIdxMap)) {\n charCodeToOptimizedIdxMap = new Array(65536);\n for (var i = 0; i < 65536; i++) {\n /* tslint:disable */\n charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i;\n /* tslint:enable */\n }\n }\n}",
"function mult(valor){\n let arrayMult = array1.map(function (item){\n return item * valor;\n });\n return console.log(arrayMult);\n}",
"function buildAddrOfArray(obj)\n{\n let arr = [obj, obj];\n let tmp = {escapeVal: arr.length};\n arr[tmp.escapeVal] = floatMapObj;\n return arr; \n}",
"function copyArrayToMap(sourceArray, map) {\n\tif (!isDefined(map)) {\n\t\tmap = {};\n\t}\n\tvar len = sourceArray.length;\n\tfor (var i = 0; i<len; i++) {\n\t\tvar v = sourceArray[i];\n\t\tmap[v.id] = v;\n\t}\n\treturn map;\n}",
"function $const(x, y) /* forall<a,b> (x : a, y : b) -> a */ {\n return x;\n}",
"function replace(arr, target, source) {\n\t return arr.map(function (v) {\n\t return v === target ? source : v;\n\t });\n\t}",
"function map(env, fn, exprs) {\n return exprs.map(function (expr) {\n return fn(env, expr);\n });\n}",
"function mapColumnValue(ix, v, cmap, gconf) {\n var cobj = cmap[ix];\n var type = cobj.type;\n\n // JSON-LD context;\n // can be used to map string values to IRIs\n var ctx = cobj['@context'];\n if (ctx != null) {\n if (ctx[v] != null) {\n v = ctx[v];\n }\n else {\n console.warn(\"NO MAPPING: \"+v);\n }\n }\n\n // column\n if (cobj.prefix != null) {\n return mapRdfResource(cobj.prefix + v);\n }\n \n // Remove this code when this is fixed: https://support.crbs.ucsd.edu/browse/NIF-10646\n if (cobj.list_delimiter != null) {\n var vl = v.split(cobj.list_delimiter);\n if (v == '-') {\n // ARRGGH AD-HOCCERY. Sometimes empty lists are denoted '-'...\n vl = [];\n }\n if (v == \"\") {\n // sometimes an empty string\n vl = [];\n }\n if (vl.length == 0) {\n return null;\n }\n if (vl.length > 1) {\n return vl.map(function(e) { return mapColumnValue(ix, e, cmap, gconf) });\n }\n // carry on, just use v, as it is a singleton list\n }\n if (type == 'rdfs:Literal') {\n return engine.quote(v);\n }\n if (v == null) {\n console.warn(\"No value for \"+ix+\" in \"+JSON.stringify(row));\n }\n return mapRdfResource(v);\n}",
"function patternMap(f,a) {\n var result = [], i; // Create a new Array\n for (i = 0; i < a.length; i++)\n// result = result.concat(down(a[i],i,a));\n result = result.concat(f(a[i],i,a));\n return result;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check over the list of available foods to see if we can make an omelette. If so, take out the ingredients and replace them with an omelette. | function omelette(foods) {
var recipe = {
egg: 2,
cheese: 1,
};
var available = organize(foods);
// if we have enough, take out the corresponding amount and add in an omelette
// if we don't, don't touch the food
if (available.egg >= recipe.egg && available.cheese >= recipe.cheese) {
// remove two eggs from `foods`. loop through once per egg that needs to
// be removed, find the index of the first egg in the list, then cut it
// out.
for (var i = 0; i < recipe.egg; i++) {
var index = foods.indexOf('egg');
foods.splice(index, 1);
}
// remove one cheese from `foods`. same approach as above.
for (var i = 0; i < recipe.cheese; i++) {
var index = foods.indexOf('cheese');
foods.splice(index, 1);
}
// add one omelette from `foods`
foods.push('omelette');
}
// returns new list of foods, minus omelette ingredients, plus an omelette
return foods;
} | [
"function ChangeFoodName(j, oldValue) {\n let e = d.Config.enums\n let newValue = u.ID(`t1TableFoodNameInput${j}`).value;\n u.RenameKey(oldValue, newValue, Dict.foods);\n // check whether food is present in any recipes\n let recipeKeys = Object.keys(Dict.recipes);\n var impactedRecipes = [];\n for (let k = 0; k < recipeKeys.length; k++) {\n let recipe = Dict.recipes[recipeKeys[k]];\n if (typeof recipe === \"function\") { continue; }\n let ingredientKeys = Object.keys(recipe.ingredients);\n for (let x = 0; x < ingredientKeys.length; x++) {\n if (oldValue === ingredientKeys[x]) {\n u.RenameKey(oldValue, newValue, recipe.ingredients);\n impactedRecipes.push(recipeKeys[k]);\n }\n }\n }\n // check whether food is present in any menus (t3) and change foodName if it is\n let menuKeys = Object.keys(Dict.menus).sort();\n for (let k = 0; k < menuKeys.length; k++) {\n let menuTitle = menuKeys[k];\n if (typeof Dict.menus[menuTitle] === \"function\") { continue; }\n let mealKeys = Object.keys(Dict.menus[menuTitle].meals);\n for (let x = 0; x < mealKeys.length; x++) {\n let mealNo = parseInt(mealKeys[x]);\n let recipeKeys = Object.keys(Dict.menus[menuTitle].meals[mealNo].recipes);\n for (let y = 0; y < recipeKeys.length; y++) {\n let recipeNo = parseInt(recipeKeys[y]);\n let recipe = Dict.menus.getRecipe(menuTitle, mealNo, recipeNo);\n let recipeTitle = recipe.recipeTitle;\n if (impactedRecipes.indexOf(recipeTitle) > -1) { //is recipe in our array 'impactedRecipes' - if yes, then delete and re-add.\n let morv = recipe.morv;\n Dict.menus.deleteRecipe(menuTitle, mealNo, recipeNo);\n Dict.menus.addRecipe(menuTitle, mealNo, recipeTitle, morv);\n }\n }\n }\n }\n u.WriteDict(0);\n}",
"function ingredients() {\n let meal = this.attributes.ingredients;\n if (meal === undefined || meal === null || meal.length === 0) {\n this.emit(':ask', 'You have no ingredients left to remove.', MESSAGES.REPROMPT);\n } else if (this.attributes.addedItems === undefined\n || this.attributes.addedItems === null\n || this.attributes.addedItems.length === 0) {\n this.emit(':ask', 'You have no ingredients left to remove.', MESSAGES.REPROMPT);\n } else {\n let outputSpeech = 'You have added: ';\n let ingredients = [];\n for (let ingredient in meal) {\n if (meal.hasOwnProperty(ingredient) && meal[ingredient] !== undefined) {\n ingredients.push(ingredient);\n }\n }\n const len = ingredients.length;\n if (len > 0) {\n let ingredient;\n let quantity;\n let unit;\n let calories;\n for (let i = 0; i < len - 1; i += 1) {\n ingredient = ingredients[i];\n quantity = meal[ingredient][0];\n unit = meal[ingredient][1];\n calories = meal[ingredient][2];\n outputSpeech += stringify.call(this, quantity, unit, ingredient, calories);\n if (i < len - 2 || len > 2) {\n outputSpeech += ', ';\n } else {\n outputSpeech += WHITESPACE;\n }\n }\n if (len > 1) {\n outputSpeech += 'and ';\n }\n ingredient = ingredients[len - 1];\n quantity = meal[ingredient][0];\n unit = meal[ingredient][1];\n calories = meal[ingredient][2];\n outputSpeech += stringify.call(this, quantity, unit, ingredient, calories) + '.';\n }\n this.emit(':ask', outputSpeech, MESSAGES.REPROMPT);\n }\n}",
"function makeSandwich(ingredients, flavour) {\n\tconst a = [];\n\tfor (let i = 0; i < ingredients.length; i++) {\n\t\tif (ingredients[i] === flavour) {\n\t\t\ta.push(\"bread\");\t\t\t\n\t\t\ta.push(ingredients[i]);\n\t\t\ta.push(\"bread\");\n\t\t} else {\n\t\t\ta.push(ingredients[i]);\n\t\t}\n\t}\n\treturn a;\n}",
"function changeEatButtons() {\r\n\r\n\t\t$( \"#eatLink\" ).hide();\r\n\t\t$( \"#useGiftLink\" ).hide();\r\n\r\n\t\t$( \"#eatMenu\" ).show();\r\n\t\t$( \"#eatMenu\" ).addClass( \"eatMenuMod\" );\r\n\t\t$( \"#useGiftMenu\" ).show();\r\n\t\t$( \"#useGiftMenu\" ).addClass( \"useGiftMenuMod\" );\r\n\r\n\t\tvar maxIndexFood = 0;\r\n\t\tvar maxIndexGift = 0;\r\n\t\tvar vecItemsFood = [];\r\n\t\tvar vecItemsGift = [];\r\n\r\n\t\tvar index = 0;\r\n\t\t$( \"#foodQuality\" ).find( \"option\" ).each( function() {\r\n\t\t\tif( $(this).attr( \"value\" ) == \"0\" ) { index++; return; }\r\n\r\n\t\t\tvar str = $(this).text();\r\n\t\t\tvar number = str.indexOf( \"(\", 0 );\r\n\t\t\tif( number != -1 ) { str = str.substr( number + 1, str.indexOf( \" \", number ) - number ); }\r\n\r\n\t\t\tvar food = $( \"<div class='foodItem' indexSelect='\"+ index +\"'></div>\" );\r\n\t\t\tfood.append( \"<img class='imageFood' src='\"+ IMGFOOD +\"' />\" );\r\n\t\t\tfood.append( \"<img class='qualityImage' src='\"+ IMGQUALITY + index + IMGEXTENSION +\"' style='' />\" );\r\n\t\t\tfood.append( \"<div class='numberItems'>\"+ str +\"</div>\" );\r\n\r\n\t\t\tif( str != 0 ) {\r\n\t\t\t\tmaxIndexFood = index;\r\n\r\n\t\t\t\tfood.bind( \"mouseover\", function() {\r\n\t\t\t\t\tif( selectedFood.attr( \"indexselect\" ) != $(this).attr( \"indexselect\" ) ) { $(this).addClass( \"foodItemHover\" ); }\r\n\t\t\t\t});\r\n\t\t\t\tfood.bind( \"mouseout\", function() {\r\n\t\t\t\t\tif( selectedFood.attr( \"indexselect\" ) != $(this).attr( \"indexselect\" ) ) { $(this).removeClass( \"foodItemHover\" ); }\r\n\t\t\t\t});\r\n\r\n\t\t\t\tfood.bind( \"click\", function() {\r\n\t\t\t\t\tif( selectedFood ) { selectedFood.removeClass( \"foodItemSelected\" ); }\r\n\t\t\t\t\t$(this).addClass( \"foodItemSelected\" );\r\n\t\t\t\t\tselectedFood = $(this);\r\n\r\n\t\t\t\t\t$( \"#foodQuality option\" )[ $(this).attr( \"indexselect\" ) ].selected = true;\r\n\t\t\t\t\tupdateHealthButtons();\r\n\t\t\t\t});\r\n\r\n\t\t\t} else food.addClass( \"itemDisabled\" );\r\n\r\n\t\t\tvecItemsFood.push( food );\r\n\t\t\t$( \"#eatMenu form\" ).append( food );\r\n\r\n\t\t\tindex++;\r\n\t\t});\r\n\r\n\r\n\t\tindex = 0;\r\n\t\t$( \"#giftQuality\" ).find( \"option\" ).each( function() {\r\n\t\t\tif( $(this).attr( \"value\" ) == \"0\" ) { index++; return; }\r\n\r\n\t\t\tvar str = $(this).text();\r\n\t\t\tvar number = str.indexOf( \"(\", 0 );\r\n\t\t\tif( number != -1 ) { str = str.substr( number + 1, str.indexOf( \" \", number ) - number ); }\r\n\r\n\t\t\tvar gift = $( \"<div class='foodItem' indexSelect='\"+ index +\"'></div>\" );\r\n\t\t\tgift.append( \"<img class='imageFood' src='\"+ IMGGIFT +\"' />\" );\r\n\t\t\tgift.append( \"<img class='qualityImage' src='\"+ IMGQUALITY + index +\".png' />\" );\r\n\t\t\tgift.append( \"<div class='numberItems'>\"+ str +\"</div>\" );\r\n\r\n\t\t\tif( str != 0 ) {\r\n\t\t\t\tmaxIndexGift = index;\r\n\r\n\t\t\t\tgift.bind( \"mouseover\", function() {\r\n\t\t\t\t\tif( selectedGift.attr( \"indexselect\" ) != $(this).attr( \"indexselect\" ) ) { $(this).addClass( \"foodItemHover\" ); }\r\n\t\t\t\t});\r\n\r\n\t\t\t\tgift.bind( \"mouseout\", function() {\r\n\t\t\t\t\tif( selectedGift.attr( \"indexselect\" ) != $(this).attr( \"indexselect\" ) ) { $(this).removeClass( \"foodItemHover\" ); }\r\n\t\t\t\t});\r\n\r\n\t\t\t\tgift.bind( \"click\", function() {\r\n\t\t\t\t\tif( selectedGift ) { selectedGift.removeClass( \"foodItemSelected\" ); }\r\n\t\t\t\t\t$(this).addClass( \"foodItemSelected\" );\r\n\t\t\t\t\tselectedGift = $(this);\r\n\r\n\t\t\t\t\t$( \"#giftQuality option\" )[ $(this).attr( \"indexselect\" ) ].selected = true;\r\n\t\t\t\t\tupdateHealthButtons();\r\n\t\t\t\t});\r\n\r\n\t\t\t} else gift.addClass( \"itemDisabled\" );\r\n\r\n\t\t\tvecItemsGift.push( gift );\r\n\t\t\t$( \"#useGiftMenu form\" ).append( gift );\r\n\r\n\t\t\tindex++;\r\n\t\t});\r\n\r\n\r\n\t\t// Change Eat and Use buttons\r\n\t\tvar newEatButton = $( \"<input type='button' id='newEatButton' value='Eat' />\" )\r\n\t\t$( \"#eatMenu\" ).append( newEatButton );\r\n\t\t$( \"#eatMenu form\" ).append( $( \"#eatButton\" ) );\r\n\r\n\t\tnewEatButton.bind( \"click\", function() {\r\n\t\t\tvar dataString = 'quality='+ $( \"#foodQuality\" ).val(); \r\n\t\t\t$.ajax({ \r\n\t\t\t\ttype: \"POST\",\r\n\t\t\t\turl: \"eat.html\",\r\n\t\t\t\tdata: dataString,\r\n\t\t\t\tsuccess: function( msg ) {\r\n\t\t\t\t\tvar json = jQuery.parseJSON( msg );\r\n\r\n\t\t\t\t\t$( \"#foodLimit\" ).html( json.foodLimit );\r\n\t\t\t\t\t$( \"#healthBar\" ).html( json.wellness );\r\n\r\n\t\t\t\t\t// Update bar from original code\r\n\t\t\t\t\t$i = $(\".health img\");\r\n\t\t\t\t\t$i.eq(1).css(\"width\", json.wellness + \"px\");\r\n\t\t\t\t\t$i.eq(2).css(\"width\", (100 - json.wellness) + \"px\");\r\n\r\n\t\t\t\t\t$( \"#q1FoodStorage\" ).html( \"Q1 Food (\"+json.q1FoodStorage+\" left)\" );\r\n\t\t\t\t\t$( \"#q2FoodStorage\" ).html( \"Q2 Food (\"+json.q2FoodStorage+\" left)\" );\r\n\t\t\t\t\t$( \"#q3FoodStorage\" ).html( \"Q3 Food (\"+json.q3FoodStorage+\" left)\" );\r\n\t\t\t\t\t$( \"#q4FoodStorage\" ).html( \"Q4 Food (\"+json.q4FoodStorage+\" left)\" );\r\n\t\t\t\t\t$( \"#q5FoodStorage\" ).html( \"Q5 Food (\"+json.q5FoodStorage+\" left)\" );\r\n\r\n\t\t\t\t\t//$( \".usedHealth\" ).animate( { \"width\" : json.wellness+\"%\" }, 500 );\r\n\t\t\t\t\tupdateHealthButtons();\r\n\r\n\t\t\t\t\tvar divList = $( \"#eatMenu form\" ).children( \"div\" );\r\n\t\t\t\t\tdivList.eq(0).children( \"div\" ).text( json.q1FoodStorage );\r\n\t\t\t\t\tdivList.eq(1).children( \"div\" ).text( json.q2FoodStorage );\r\n\t\t\t\t\tdivList.eq(2).children( \"div\" ).text( json.q3FoodStorage );\r\n\t\t\t\t\tdivList.eq(3).children( \"div\" ).text( json.q4FoodStorage );\r\n\t\t\t\t\tdivList.eq(4).children( \"div\" ).text( json.q5FoodStorage );\r\n\r\n\t\t\t\t\tif( json.error != \"\" ) {\r\n\t\t\t\t\t\t$( '#hiddenError' ).html( json.error );\r\n\t\t\t\t\t\t$.blockUI({ message: $( '#eatError' ), css: { width: '400px', border: '0px', background: 'rgba(255,255,255,0)' } });\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t});\r\n\r\n\t\tvar newGiftButton = $( \"<input type='button' id='newGiftButton' value='Use' />\" )\r\n\t\t$( \"#useGiftMenu\" ).append( newGiftButton );\r\n\t\t$( \"#useGiftMenu form\" ).append( $( \"#useGiftButton\" ) );\r\n\r\n\t\tnewGiftButton.bind( \"click\", function() {\r\n\t\t\tvar dataString = 'quality='+ $(\"#giftQuality\").val(); \r\n\t\t\t$.ajax({ \r\n\t\t\t\ttype: \"POST\",\r\n\t\t\t\turl: \"gift.html\",\r\n\t\t\t\tdata: dataString,\r\n\t\t\t\tsuccess: function( msg ) {\r\n\t\t\t\t\tvar json = jQuery.parseJSON( msg );\r\n\r\n\t\t\t\t\t$( \"#giftLimit\" ).html( json.giftLimit );\r\n\t\t\t\t\t$( \"#healthBar\" ).html( json.wellness );\r\n\r\n\t\t\t\t\t// Update bar from original code\r\n\t\t\t\t\t$i = $(\".health img\");\r\n\t\t\t\t\t$i.eq(1).css(\"width\", json.wellness + \"px\");\r\n\t\t\t\t\t$i.eq(2).css(\"width\", (100 - json.wellness) + \"px\");\r\n\r\n\t\t\t\t\t$( \"#q1GiftStorage\" ).html( \"Q1 Gift (\"+json.q1GiftStorage+\" left)\" );\r\n\t\t\t\t\t$( \"#q2GiftStorage\" ).html( \"Q2 Gift (\"+json.q2GiftStorage+\" left)\" );\r\n\t\t\t\t\t$( \"#q3GiftStorage\" ).html( \"Q3 Gift (\"+json.q3GiftStorage+\" left)\" );\r\n\t\t\t\t\t$( \"#q4GiftStorage\" ).html( \"Q4 Gift (\"+json.q4GiftStorage+\" left)\" );\r\n\t\t\t\t\t$( \"#q5GiftStorage\" ).html( \"Q5 Gift (\"+json.q5GiftStorage+\" left)\" );\r\n\r\n\t\t\t\t\tvar divList = $( \"#useGiftMenu form\" ).children( \"div\" );\r\n\t\t\t\t\tdivList.eq(0).children( \"div\" ).text( json.q1GiftStorage );\r\n\t\t\t\t\tdivList.eq(1).children( \"div\" ).text( json.q2GiftStorage );\r\n\t\t\t\t\tdivList.eq(2).children( \"div\" ).text( json.q3GiftStorage );\r\n\t\t\t\t\tdivList.eq(3).children( \"div\" ).text( json.q4GiftStorage );\r\n\t\t\t\t\tdivList.eq(4).children( \"div\" ).text( json.q5GiftStorage );\r\n\r\n\t\t\t\t\t//$( \".usedHealth\" ).animate( { \"width\" : json.wellness+\"%\" }, 500 );\r\n\t\t\t\t\tupdateHealthButtons();\r\n\r\n\t\t\t\t\tif( json.error != \"\" ) {\r\n\t\t\t\t\t\t$( '#hiddenError' ).html( json.error );\r\n\t\t\t\t\t\t$.blockUI({ message: $( '#eatError' ), css: { width: '400px', border: '0px', background: 'rgba(255,255,255,0)' } });\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t});\r\n\r\n\r\n\t\t// Redesign food and gift limits\r\n\t\t$( \"#foodLimit\" ).addClass( \"foodLimitMod\" );\r\n\t\t$( \"#giftLimit\" ).addClass( \"giftLimitMod\" );\r\n\t\t$( \"#eatMenu form\" ).append( $( \"#foodLimit\" ) );\r\n\t\t$( \"#useGiftMenu form\" ).append( $( \"#giftLimit\" ) );\r\n\r\n\t\t$( \"#foodQuality\" ).css({ \"display\" : \"none\" });\r\n\t\t$( \"#giftQuality\" ).css({ \"display\" : \"none\" });\r\n\t\t$( \"#eatButton\" ).css({ \"display\" : \"none\" });\r\n\t\t$( \"#useGiftButton\" ).css({ \"display\" : \"none\" });\r\n\r\n\t\t$( \"#eatLink\" ).prev().remove();\r\n\t\t$( \"#eatMenu\" ).prev().remove();\r\n\t\t$( \"#useGiftLink\" ).prev().remove();\r\n\t\t$( \"#useGiftLink\" ).next().remove();\r\n\r\n\t\t// Default max quality items\r\n\t\tif( maxIndexFood > 0 ) { vecItemsFood[ maxIndexFood-1].click(); }\r\n\t\tif( maxIndexGift > 0 ) { vecItemsGift[ maxIndexGift-1].click(); }\r\n\r\n\t\tshowHideButtons();\r\n\t\tupdateHealthButtons();\r\n\r\n\t\tif( $( \"#stats\" ).children( \"form\" ).length != 0 ) {\r\n\t\t\tvar form = $( \"#stats\" ).children( \"form\" );\r\n\t\t\tform.contents().eq(4).remove();\r\n\t\t\tform.children( \"img\" ).css({ \"margin\" : \"2px 7px 0px 0px\" });\r\n\r\n\t\t\t// Rellocate wiki help\r\n\t\t\tvar lastDiv = $( \"#stats\" ).children( \"div:last\" );\r\n\t\t\tlastDiv.css({ \"float\" : \"right\", \"margin\" : \"6px 3px 0px 0px\" });\r\n\t\t\tlastDiv.children( \"a\" ).text( \"\" ).append( lastDiv.children( \"img\" ) );\r\n\t\t\tform.children( \"br\" ).remove();\r\n\t\t\tform.append( lastDiv );\r\n\t\t}\r\n\t}",
"eat() {\n if (this.food >= 1) {\n this.food -= 1\n } else { \n this.isHealthy = false\n }\n }",
"placeOrder(myOrder){\n\n\t\tlet insufficientFlag = false;\n\t\tvar canMakeArray = [];\n\n\t\tfor(let item of myOrder.drinkList){\n\t\t\ttry{\n\t\t\t\t//iterate through all ingrediants needed for current drink.\n\t\t\t\tfor(let drinkIngrediant of item.drink.ingrediantList){\n\t\t\t\t\t//iterate through every ingrediant in inventory to check if that ingrediant is need for the drink.\n\t\t\t\t\t//If ingredient is needed then decrement inventory counter accordingly.\n\t\t\t\t\t//finally check if there is not enough of ingrediant and set flag if true.\n\t\t\t\t\tfor(var i = 0; i < this.myInventory.ingredients.length; i++){\n\t\t\t\t\t\tif(drinkIngrediant === this.myInventory.ingredients[i] && item.drink.drinkSize === \"small\" && this.myInventory.quantity[i] >= 1){\n\t\t\t\t\t\t\tthis.myInventory.quantity[i]--; \n\t\t\t\t\t\t}else if(drinkIngrediant === this.myInventory.ingredients[i] && this.myInventory.quantity[i] >= 2){\n\t\t\t\t\t\t\tthis.myInventory.quantity[i]--;\n\t\t\t\t\t\t\tthis.myInventory.quantity[i]--;\n\t\t\t\t\t\t}else if(drinkIngrediant === this.myInventory.ingredients[i]){\n\t\t\t\t\t\t\tinsufficientFlag = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(insufficientFlag){\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}catch(e){\n\t\t\t\tconsole.log(e);\n\t\t\t}\n\t\t\tif(insufficientFlag == false){\n\t\t\t\tcanMakeArray.push(item);\n\t\t\t}\n\n\t\t\tinsufficientFlag = false;\n\t\t}\n\n\t\treturn(canMakeArray);\n\t}",
"function getNumIngredients(recipe) {\n\t//loop through list looking for empty ingredient\n\tif(recipe.strIngredient1 == \"\")\n\t\treturn 0;\n\tif(recipe.strIngredient2 == \"\")\n\t\treturn 1;\n\tif(recipe.strIngredient3 == \"\")\n\t\treturn 2;\n\tif(recipe.strIngredient4 == \"\")\n\t\treturn 3;\n\tif(recipe.strIngredient5 == \"\")\n\t\treturn 4;\n\tif(recipe.strIngredient6 == \"\")\n\t\treturn 5;\n\tif(recipe.strIngredient7 == \"\")\n\t\treturn 6;\n\tif(recipe.strIngredient8 == \"\")\n\t\treturn 7;\n\tif(recipe.strIngredient9 == \"\")\n\t\treturn 8;\n\tif(recipe.strIngredient10 == \"\")\n\t\treturn 9;\n\tif(recipe.strIngredient11 == \"\")\n\t\treturn 10;\n\tif(recipe.strIngredient12 == \"\")\n\t\treturn 11;\n\tif(recipe.strIngredient13 == \"\")\n\t\treturn 12;\n\tif(recipe.strIngredient14 == \"\")\n\t\treturn 13;\n\tif(recipe.strIngredient15 == \"\")\n\t\treturn 14;\n\tif(recipe.strIngredient16 == \"\")\n\t\treturn 15;\n\tif(recipe.strIngredient17 == \"\")\n\t\treturn 16;\n\tif(recipe.strIngredient18 == \"\")\n\t\treturn 17;\n\tif(recipe.strIngredient19 == \"\")\n\t\treturn 18;\n\tif(recipe.strIngredient20 == \"\")\n\t\treturn 19;\n\treturn 20;\n}",
"function eatFood() {\n if (snake.position = food) {\n snake.length =+ 1;\n }\n }",
"function makePizza5(ingredient1, ingredient2) {\n const pizzaPromise = new Promise(function (resolve, reject) {\n //reject if pineapple\n if (ingredient1 === 'pineapple' || ingredient2 === 'pineapple') {\n reject(\"We don't like pineapple in pizza here\")\n }\n // wait 1 second for the pizza to be cooked\n setTimeout(function () {\n // when you are ready, resolve it\n resolve(`Your ${ingredient1} and ${ingredient2} pizza is ready!`)\n }, 2000)\n // if it fails, let me know\n })\n return pizzaPromise;\n}",
"function customIngredientToShoppingList() {\n let customIngredientName = document.getElementById(\"add-food\").value.toLowerCase()\n addCustomIngredient(customIngredientName)\n addToShoppingListExtra(getIngredientID(customIngredientName))\n toast(customIngredientName + \" Added\", successToast);\n}",
"scoreSelectedTiles() {\n if (this.lineOfSelectedTiles.length < this.MINIMUM_LINE_LENGTH) return;\n \n //First figure out the unique ingredients from the line of selected tiles.\n const uniqueIngredients = {};\n this.lineOfSelectedTiles.map((tile) => {\n const ingval = tile.value.toString();\n if (!uniqueIngredients[ingval]) {\n uniqueIngredients[ingval] = 1;\n } else {\n uniqueIngredients[ingval]++;\n }\n });\n \n //For each available food order, check if the unique ingredients match all\n //the ingredients of the food order.\n let score = 0;\n this.foodOrders = this.foodOrders.filter((foodOrder) => {\n\n //Check 1: does each (unique) selected ingredient have a corresponding\n //ingredient in the food order recipe?\n let selectedIngredientsOK = true;\n Object.keys(uniqueIngredients).map((ingval) => {\n selectedIngredientsOK =\n selectedIngredientsOK &&\n foodOrder.ingredients.includes(ingval);\n });\n \n //Check 2: does each ingredient in the food order recipe appear in the\n //list of selected ingredients?\n let foodOrderIngredientsOK = true;\n foodOrder.ingredients.map((ingval) => {\n foodOrderIngredientsOK =\n foodOrderIngredientsOK &&\n uniqueIngredients[ingval] > 0\n });\n \n const selectedIngredientsMatchOrder = selectedIngredientsOK && foodOrderIngredientsOK;\n \n //If we get a match, increase the score and remove the food order from the list.\n if (selectedIngredientsMatchOrder) {\n score += this.lineOfSelectedTiles.length;\n return false; //Remove from the list.\n } else {\n return true; //Keep the food order on the list.\n }\n });\n \n //Update the score!\n //If the user made any sort of good match - matching selected ingredients\n //to any food order's ingredients - add to the score.\n //If the user selected ingredients and cooked a meal that nobody wanted, add\n //a penalty to the score.\n score *= this.MAKE_SCORE_LOOK_BIG_FACTOR;\n if (score > 0) {\n this.addMessage(\"+\" + score + \" points!\");\n } else {\n score = this.lineOfSelectedTiles.length * -this.BAD_ORDER_PENALTY * this.MAKE_SCORE_LOOK_BIG_FACTOR;\n this.addMessage(\"Bad recipe! \" + score + \" points...\");\n }\n this.score += score;\n \n //OK, if there are any empty slots for new food orders, let's fill 'em up!\n this.fillFoodOrders();\n \n //Also, count down the number of turns available.\n this.turnsLeft--;\n if (this.turnsLeft === 0) {\n this.setState(GAME_STATE.END_MENU);\n }\n }",
"addFood(name){\n var check = 0;\n for (var i = 0; i < inventoryInfo.length; i++) {\n if (foodTypes.food[inventoryInfo[i].itemID].type == name) {\n inventoryInfo[i].itemQty++;\n check++;\n this.emitter.emit(\"inventory\", inventoryInfo[i].itemID, inventoryInfo[i].itemQty);\n }\n }\n if (check == 0) {\n var stuff = {};\n for (var i = 0; i < foodTypes.food.length; i++) {\n if (foodTypes.food[i].type == name) {\n stuff.itemID = i;\n }\n }\n stuff.itemQty = 1;\n stuff.playerID = playerInfo.playerID;\n //missing inventory id\n inventoryInfo.push(stuff);\n\n console.log(inventoryInfo);\n }\n }",
"function checkFood(food){\n if ((Math.pow(this.endX - food.xLoc, 2) + Math.pow(this.endY - food.yLoc, 2)) < Math.pow(foodSize/2, 2)){\n food.remove();\n }\n}",
"function recipesByTags(){\n for (const recipe of recipes) {\n let ingredients = [];\n recipe.ingredients.forEach(ing => ingredients.push(ing.ingredient.toUpperCase())); // Get all recipes ingredients\n for(let k=0; k<allSelectedTag.length; k++){\n if(recipe.appliance.toUpperCase().includes(allSelectedTag[k].innerText.toUpperCase()) || ingredients.join().includes(allSelectedTag[k].innerText.toUpperCase()) || recipe.ustensils.join().toUpperCase().includes(allSelectedTag[k].innerText.toUpperCase())){ // Tags match with one recipe in database or more ...\n if(document.getElementById(\"recipe-\" + recipe.id).classList.contains(\"display-recipe\")){\n document.getElementById(\"recipe-\" + recipe.id).style.display = \"block\"; // ... display cards of the recipes ...\n }\n } else {\n document.getElementById(\"recipe-\" + recipe.id).style.display = \"none\"; // ... hide others\n document.getElementById(\"recipe-\" + recipe.id).classList.remove(\"display-recipe\");\n }\n }\n if(allSelectedTag.length == 0){ // No tag selected ...\n document.querySelectorAll(\".card\").forEach(card => card.style.display = \"block\"); // ... display all cards\n document.querySelectorAll(\".card\").forEach(card => card.classList.add(\"display-recipe\"));\n }\n }\n updateFilters(); // Update filters based on recipes displayed\n}",
"function resetFood() {\n food.arcRot = Math.random() * Math.PI * 2; // reset food position\n food.radius = Math.random() * gameRad * 0.96; // take into scaling and size of food\n // calc x and y\n food.x = gameRad + food.radius * Math.sin(food.arcRot);\n food.y = gameRad - food.radius * Math.cos(food.arcRot);\n\n if (circleCollision(player, food)) {\n resetFood();\n }\n var i;\n for (i = 0; i < bodArray.length; i++) {\n if (circleCollision(bodArray[i], food)) {\n resetFood();\n break;\n }\n }\n}",
"function setFood() {\n\tvar empty = [];\n\t\n\t// find empty grid cells\n\tfor (var x = 0; x < grid.width; x++) {\n\t\tfor (var y = 0; y < grid.height; y++) {\n\t\t\tif (grid.get(x, y) === EMPTY) {\n\t\t\t\tempty.push({x:x, y:y});\n\t\t\t}\n\t\t}\n\t}\n\tvar randomPosition = empty[Math.floor(Math.random() * (empty.length-1))]; // selects a random grid cell\n\tgrid.set(FRUIT, randomPosition.x, randomPosition.y); // sets the \"apple\" to the randomly selected grid cell\n}",
"function findFoods() {\n\n// userRequest will taken in the client information and ask them to type in what they are serching for \n let userRequest = document.getElementById('userRequest').value\n if(userRequest === '') {\n return alert('Please enter an ingrediant for query')\n }\n\n // Here we are delivering what we have found from the WebService\n // All Possible options that have been listed ae what we are able to get from the API \n // The API Has been provided in the assingment document files \n let RequestRecipe = document.getElementById('foundInformation')\n RequestRecipe.innerHTML = ''\n\n// Here we loggining into our documents what we have done \n document.getElementById('userRequest').value = '';\n \n // Here we are completing our HTTP Request\n // We are seeing if the responce is valid \n // If the responce if valid we are giving the client the correct information \n // Our for loop will complete all of this \n let myRequest = new XMLHttpRequest()\n myRequest.onreadystatechange = () => {\n if (myRequest.readyState == 4 && myRequest.status == 200) {\n let response = JSON.parse(myRequest.responseText) \n let foundInformation = response.foundInformation;\n\n // Here we are making sure that we are not over working the server, this was one of the major assingment requirments \n // We are also making sure that we arent requestig too much data at one instatance \n for(let i = 0; i < foundInformation.length; i++){\n RequestRecipe.innerHTML = RequestRecipe.innerHTML + `\n <ul>\n <li><a href=\"${foundInformation[i].f2f_url}\" target=\"_blank\"> <img src=\"${foundInformation[i].image_url}\"> </a></li>\n <li>${foundInformation[i].title}</li>\n </ul>\n `\n }\n }\n }\n\n // Here we are getting the reponce and making sure that all the correct content has been delivered \n myRequest.open('GET', `/recipe?userRequest=${userRequest}`, true)\n myRequest.send()\n}",
"function generateContents(foodName) {\n\tvar food = foodDict[foodName];\n\t\n\t\n\tvar nameText = '<h1 class=\"text-center\">' + foodName + '</h1>';\n\tvar foodURL = '<h5 class=\"text-center\"><a target=\"_blank\" href=\"' + food[\"url\"] + '\">' + food[\"url\"] + '</a></h5>';\n\tvar imgText = '<img style=\"padding-top:30px;float:left\" src=\"' + food[\"image\"] + '\" alt=\"' + foodName + '\">';\n\t\n\t// Nutrients\n\tvar totalNutrients = food[\"totalNutrients\"];\n\tvar calories = parseInt(food[\"calories\"]) + \" Calories\";\n\tvar fat = parseInt(totalNutrients[\"FAT\"][\"quantity\"]) + totalNutrients[\"FAT\"][\"unit\"] + \" Fat\";\n\tvar carbs = parseInt(totalNutrients[\"CHOCDF\"][\"quantity\"]) + totalNutrients[\"CHOCDF\"][\"unit\"] + \" Carbohydrates\"\n\tvar protein = parseInt(totalNutrients[\"PROCNT\"][\"quantity\"]) + totalNutrients[\"PROCNT\"][\"unit\"] + \" Protein\";\n\tvar nutrientText = '<br/><br/><br/><div class=\"nutrient-font text-center\">' + calories + \"<br/>\" + fat + \"<br/>\" + carbs + \"<br/>\" + protein + \"<br/></div>\";\n\t\n\t$(\"#food-facts\").append(nameText + foodURL + imgText + nutrientText + '<br/><br/><br/><br/><br/><br/><br/>');\n\t\n\t\n\t// Ingredients\n\t$(\"#food-facts\").append('<h2>Ingredients</h2>');\n\tvar ingredients = food[\"ingredients\"];\n\tvar ingredientText = '<div class=\"col-md-5\"><ul>'\n\t\tfor (ingredientIndex in ingredients) {\n\t\t\tvar currentIngredient = ingredients[ingredientIndex];\n\n\n\n\t\t\t// If price is undefined, define it.\n\t\t\tvar price = food_dict[currentIngredient[\"food\"]];\n\t\t\tif (price === undefined || price === null) {\n\t\t\t\tprice = \"$3.26\";\n\t\t\t}\n\n\t\t\tingredientText += '<li>' + currentIngredient[\"quantity\"] + \" \" + currentIngredient[\"measure\"]\n\t\t\t\t\t\t\t+ \" \" + currentIngredient[\"food\"] + \" <strong>\" + price + \"</strong></li></br>\";\n\t}\n\tingredientText += '</ul></div>';\n\t$(\"#food-facts\").append(ingredientText);\n\t\n\t\n}",
"function stackBurger(e) { //this function adds the clicked ingredient to the burger stack\n const ingToAdd = ingredients.filter(ing => ing.name === e.target.innerText);//this is an array of all the ingredients added to the burger\n setStack([ingToAdd[0], ...stack]); //this adds clicked ingredients to the array by spreading the original array\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prompt for password if this is a password based credential and the password for the profile was empty and not explicitly set as empty. If it was explicitly set as empty, only prompt if pw not saved | static shouldPromptForPassword(credentials) {
let isSavedEmptyPassword = credentials.emptyPasswordInput
&& credentials.savePassword;
return utils.isEmpty(credentials.password)
&& ConnectionCredentials.isPasswordBasedCredential(credentials)
&& !isSavedEmptyPassword;
} | [
"function askPassword(ok, fail) {\r\n let password = prompt(\"Password?\", '');\r\n if (password === \"rockstar\") ok();\r\n else fail();\r\n}",
"function passwordLengthPrompt() {\n passwordLength = parseInt(prompt(\"How long would you like your password to be (Min: 8 Max: 128)\"));\n if (passwordLength === null || passwordLength === \"\" || passwordLength < 8 || 128 < passwordLength || !passwordLength) {\n passwordLengthPrompt();\n } \n lowerCaseLettersPrompt();\n}",
"function promptForCredentials(){\n var authFailure = getProperty('authFailure');\n if(authFailure == 'true'){\n clearProperties(); \n }\n \n var username = getProperty('username');\n var password = getProperty('password');\n \n //Promt for credentials\n if(username == null || password == null){\n var ui = SpreadsheetApp.getUi();\n var usernameResponse = ui.prompt('Jira Integration', 'This sheet integrates with Jira!\\n\\n Jira Username?', ui.ButtonSet.OK);\n var passwordResponse = ui.prompt('Jira Integration', 'Jira Password?', ui.ButtonSet.OK);\n \n setProperty('username', usernameResponse.getResponseText());\n setProperty('password', passwordResponse.getResponseText()); \n }\n}",
"function newPasswordPrompt(xcoord,ycoord,pw){\n\tif (verboseDebugging){\n\t\tconsole.log(\"we in new pw prompt nao\");\n\t\tconsole.log(\"pw is: \");\n\t\tconsole.log(pw);\n\t}\n\tmessageDiv.style.display = \"none\";\n\t//Gather prompt arguments and pass them along to handler.\n\tvar initCoords = {};\n\tinitCoords.xcoord = xcoord;\n\tinitCoords.ycoord = ycoord;\n\n\t//set up new prompt in HTML DOM. Make sure that defaults are reset.\n\tdisplayPassword(\"If you wish to set a new password, enter it and confirm.\\nIf you wish to keep the previous password, press Don't Change\\nIf you wish to keep the tile public, press Make Public\",\n\t\t\t\t\tcheckPasswordMatch,pw,initCoords);\n\n}",
"requestPassword() {\n var ui = SpreadsheetApp.getUi();\n var result = ui.prompt('Connect to ReadWorks', 'Please enter your ReadWorks password:', ui.ButtonSet.OK_CANCEL);\n var button = result.getSelectedButton();\n var text = result.getResponseText();\n if (button == ui.Button.CANCEL) {\n throw new Error('No password provided, cancelling assignment import.');\n } else if (button == ui.Button.CLOSE) {\n throw new Error('No password provided, cancelling assignment import.');\n }\n\n this.password = text;\n return this.password;\n }",
"function runLogin(){\n console.log(\"welcome to the Employee Tracker!\")\n inquirer\n .prompt([\n {\n type: 'password',\n name: 'defaultpassword',\n message: 'Please enter a password!',\n },\n ])\n .then(answers => {\n if(answers.defaultpassword == \"password\"){\n runApp();\n } else{\n console.log(\"Please enter the correct password!\")\n runLogin();\n }\n });\n}",
"function showPass() {\n const password = document.getElementById('password');\n const rePassword = document.getElementById('masterRePassword');\n if (password.type === 'password') {\n password.type = 'text';\n rePassword.type = 'text';\n logMe(\"User\", \"Toggle-Password\", \"Create ByPass account\", \"ON - Password Confirm Input : \" + password.value);\n } else {\n password.type = 'password';\n rePassword.type = 'password';\n logMe(\"User\", \"Toggle-Password\", \"Create ByPass account\", \"OFF - Password Confirm Input : \" + password.value);\n }\n} // show password function",
"get shouldDeferMessageDisplayUntilAfterServerConnect() {\n let passwordPromptRequired = false;\n\n if (Services.prefs.getBoolPref(\"mail.password_protect_local_cache\")) {\n passwordPromptRequired = this.view.displayedFolder.server\n .passwordPromptRequired;\n }\n\n return passwordPromptRequired;\n }",
"function askForPassword() {\n hideMenu();\n $(\"#imbaPasswordPrompt\").dialog(\"open\");\n $(\"#imbaPasswordPromptInput\").focus();\n}",
"function hidePass(){\n // Thanks again to Sathanus, on discord, for the suggestion of keeping\n // the password hidden \n var currentDisplayText=document.querySelector(\"#password\");\n if(currentDisplayText.value.split(\" \")[1]!=\"password\")\n document.querySelector(\"#password\").value=dummyText;\n ny2qX*RH\n}",
"function initialPrompts() {\n userChoice = window.alert(\n \"Before generating your password, you must select some criteria for your password. Click ok to follow on to the next set of instructions.\"\n );\n userChoice = window.alert(\n \"In the upcoming pop-up, type what set of criteria you may want for your password. The options you may select are: 'capital: for capital letters; special: for special characters; number: for numbers in your password. Click ok to proceed to the typing prompt.'\"\n );\n userChoice = window.prompt(\n \"Type your criteria\",\n \"Capital; Number; Special\"\n );\n /* Converts users input to upper case to minimize input mistakes */\n userChoice = userChoice.toUpperCase();\n /* Prints out what the user has selected in the console for developer to check their choice! Helps to see if code is operational. */\n console.log(\n \"The user has selected \" +\n userChoice +\n \" as their criteria. End of initialPrompts function\"\n );\n\n if (!userChoice) {\n return;\n }\n\n selectCriteria();\n }",
"function getUserInput() {\n var pwLength = prompt(\"Please select a password length between 8 and 128\");\n if(pwLength < 8 || pwLength > 128) {\n alert(\"Your password needs to be at least 8 and no more than 128 characters\")\n } else {\n var lowerChar = confirm(\"Do you want lower case letters?\");\n var upperChar = confirm(\"Do you want upper case letters?\");\n var numChar = confirm(\"Do you want numbers?\");\n var specChar = confirm(\"Do you want special characters?\");\n var userPreference = { pwLength, lowerChar, upperChar, numChar, specChar\n };\n };\n console.log(userPreference)\n return userPreference;\n \n}",
"function generatePassword() {\n // Check user options. False if user cancels prompt\n let check = checkRequirements();\n if (check) {\n // Add to pool of char choices\n if (options.hasLowerCase) {\n choices += lowerCaseChars;\n } if (options.hasUpperCase) {\n choices += upperCaseChars;\n } if (options.hasNumericChars) {\n choices += numericChars;\n } if (options.hasSpecialChars) {\n choices += specialChars;\n }\n for (var i = 0; i < options.length; i++) {\n var char = choices[Math.floor(Math.random() * choices.length)];\n newPassword += char;\n }\n //Password is displayed\n passwordEl.innerHTML = newPassword;\n clear();\n }\n}",
"function changepw(form, password, conf, email=\"testforempty\") {\r\n\t\r\n // Check each field has a value\r\n if ( email.value == '' || password.value == '' || conf.value == '') {\r\n custom_show_message(\"Error\", 'You must provide all the requested details. Please try again', \"alert\");\r\n return false;\r\n }\r\n \r\n\tif(!check_password(password, conf, form)){\r\n\t\treturn false;\r\n\t}\r\n\t\r\n // Create a new element input, this will be our hashed password field. \r\n var p = document.createElement(\"input\");\r\n \r\n // Add the new element to our form. \r\n form.appendChild(p);\r\n p.name = \"p\";\r\n p.type = \"hidden\";\r\n p.value = hex_sha512(password.value);\r\n \r\n // Make sure the plaintext password doesn't get sent. \r\n password.value = \"\";\r\n conf.value = \"\";\r\n\r\n return true;\r\n}",
"function onConfirmPasswordChange(p) {\n let val = p.target.value;\n setConfirmPassword(val);\n setEnabled(password.length > 0 && name.length > 0 && email.length > 0 && val.length > 0 && number.length==10);\n }",
"function doesPasswordMeetStandard(password) {\n if(password == null) {\n return \"You must enter a password.\";\n }\n\n if(password == \"\") {\n return \"You must enter a password.\";\n }\n\n if(password.length < 8) {\n return \"Your password must be at least 8 characters long.\";\n }\n\n if(/[0-9]+/.test(password) == false) {\n return \"Your password must contain at least one number.\";\n }\n\n if(/[a-z]+/.test(password) == false) {\n return \"Your password must contain at least one lowercase letter.\";\n }\n\n if(/[A-Z]+/.test(password) == false) {\n return \"Your password must contain at least one uppercase letter.\";\n }\n\n return true;\n}",
"function pass() {\n ch_push_guess(\"pass\");\n setGuess(\"\");\n }",
"function submitPassword() {\n\tvar currentUser = app.sessionDatabase.read();\n\tvar db = app.database.read();\n\tvar oldPassword = currentUser.password;\n\tvar newPassword = document.getElementById(\"newPassword\").value;\n\tvar newPasswordConfirm = document.getElementById(\"newPasswordConfirm\").value;\n\t\n\t// validation: check that the old password is correct\n\tif (document.getElementById(\"oldPassword\").value != oldPassword){\n\t\talert(\"Old password was entered incorrectly.\");\n\t\treturn;\n\t}\n\n\t// validation: check that the same password both times\n\tif (newPassword != newPasswordConfirm){\n\t\talert(\"Please make sure you typed the same password both times.\");\n\t\treturn;\n\t}\n\n\tcurrentUser.password = newPassword;\n\tapp.search.changeUserPassword(currentUser.email, newPassword); // change permanent user password in local storage\n\tapp.sessionDatabase.write(currentUser);\t\t\t\t\t\t // change current user password in session storage\n\t\n\tdocument.getElementById(\"oldPassword\").value = \"\";\n\tdocument.getElementById(\"newPassword\").value = \"\";\n\tdocument.getElementById(\"newPasswordConfirm\").value = \"\";\n\t$('#passwordModal').modal('hide');\n\n}",
"function setupPasswordCharacters() {\n const charTypes = [\n { desc: \"Lower case letters\", symb: \"l\" },\n { desc: \"Upper case letters\", symb: \"u\" },\n { desc: \"Numbers\", symb: \"n\" },\n { desc: \"Symbols\", symb: \"s\" },\n ];\n \n let pwCharTypes = [];\n\n//Pass password selection for each charachter type when prompt\n for (const charType of charTypes) {\n const includeCharSet = confirm(`Include ${charType.desc} in password`);\n if (includeCharSet) {\n pwCharTypes.push(charType.symb);\n }\n }\n\n if (pwCharTypes.length === 0) {\n alert(\n \"Must select at least 1 password character type to generate a password\"\n );\n pwCharTypes = setupPasswordCharacters();\n }\n \n return pwCharTypes;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Language: Python Description: Python is an interpreted, objectoriented, highlevel programming language with dynamic semantics. Website: Category: common | function python(hljs) {
const RESERVED_WORDS = [
'and',
'as',
'assert',
'async',
'await',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal|10',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield',
];
const BUILT_INS = [
'__import__',
'abs',
'all',
'any',
'ascii',
'bin',
'bool',
'breakpoint',
'bytearray',
'bytes',
'callable',
'chr',
'classmethod',
'compile',
'complex',
'delattr',
'dict',
'dir',
'divmod',
'enumerate',
'eval',
'exec',
'filter',
'float',
'format',
'frozenset',
'getattr',
'globals',
'hasattr',
'hash',
'help',
'hex',
'id',
'input',
'int',
'isinstance',
'issubclass',
'iter',
'len',
'list',
'locals',
'map',
'max',
'memoryview',
'min',
'next',
'object',
'oct',
'open',
'ord',
'pow',
'print',
'property',
'range',
'repr',
'reversed',
'round',
'set',
'setattr',
'slice',
'sorted',
'staticmethod',
'str',
'sum',
'super',
'tuple',
'type',
'vars',
'zip',
];
const LITERALS = [
'__debug__',
'Ellipsis',
'False',
'None',
'NotImplemented',
'True',
];
const KEYWORDS = {
keyword: RESERVED_WORDS,
built_in: BUILT_INS,
literal: LITERALS
};
const PROMPT = {
className: 'meta', begin: /^(>>>|\.\.\.) /
};
const SUBST = {
className: 'subst',
begin: /\{/, end: /\}/,
keywords: KEYWORDS,
illegal: /#/
};
const LITERAL_BRACKET = {
begin: /\{\{/,
relevance: 0
};
const STRING = {
className: 'string',
contains: [hljs.BACKSLASH_ESCAPE],
variants: [
{
begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/, end: /'''/,
contains: [hljs.BACKSLASH_ESCAPE, PROMPT],
relevance: 10
},
{
begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/, end: /"""/,
contains: [hljs.BACKSLASH_ESCAPE, PROMPT],
relevance: 10
},
{
begin: /([fF][rR]|[rR][fF]|[fF])'''/, end: /'''/,
contains: [hljs.BACKSLASH_ESCAPE, PROMPT, LITERAL_BRACKET, SUBST]
},
{
begin: /([fF][rR]|[rR][fF]|[fF])"""/, end: /"""/,
contains: [hljs.BACKSLASH_ESCAPE, PROMPT, LITERAL_BRACKET, SUBST]
},
{
begin: /([uU]|[rR])'/, end: /'/,
relevance: 10
},
{
begin: /([uU]|[rR])"/, end: /"/,
relevance: 10
},
{
begin: /([bB]|[bB][rR]|[rR][bB])'/, end: /'/
},
{
begin: /([bB]|[bB][rR]|[rR][bB])"/, end: /"/
},
{
begin: /([fF][rR]|[rR][fF]|[fF])'/, end: /'/,
contains: [hljs.BACKSLASH_ESCAPE, LITERAL_BRACKET, SUBST]
},
{
begin: /([fF][rR]|[rR][fF]|[fF])"/, end: /"/,
contains: [hljs.BACKSLASH_ESCAPE, LITERAL_BRACKET, SUBST]
},
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE
]
};
// https://docs.python.org/3.9/reference/lexical_analysis.html#numeric-literals
const digitpart = '[0-9](_?[0-9])*';
const pointfloat = `(\\b(${digitpart}))?\\.(${digitpart})|\\b(${digitpart})\\.`;
const NUMBER = {
className: 'number', relevance: 0,
variants: [
// exponentfloat, pointfloat
// https://docs.python.org/3.9/reference/lexical_analysis.html#floating-point-literals
// optionally imaginary
// https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
// Note: no leading \b because floats can start with a decimal point
// and we don't want to mishandle e.g. `fn(.5)`,
// no trailing \b for pointfloat because it can end with a decimal point
// and we don't want to mishandle e.g. `0..hex()`; this should be safe
// because both MUST contain a decimal point and so cannot be confused with
// the interior part of an identifier
{ begin: `(\\b(${digitpart})|(${pointfloat}))[eE][+-]?(${digitpart})[jJ]?\\b` },
{ begin: `(${pointfloat})[jJ]?` },
// decinteger, bininteger, octinteger, hexinteger
// https://docs.python.org/3.9/reference/lexical_analysis.html#integer-literals
// optionally "long" in Python 2
// https://docs.python.org/2.7/reference/lexical_analysis.html#integer-and-long-integer-literals
// decinteger is optionally imaginary
// https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
{ begin: '\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?\\b' },
{ begin: '\\b0[bB](_?[01])+[lL]?\\b' },
{ begin: '\\b0[oO](_?[0-7])+[lL]?\\b' },
{ begin: '\\b0[xX](_?[0-9a-fA-F])+[lL]?\\b' },
// imagnumber (digitpart-based)
// https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
{ begin: `\\b(${digitpart})[jJ]\\b` },
]
};
const PARAMS = {
className: 'params',
variants: [
// Exclude params at functions without params
{begin: /\(\s*\)/, skip: true, className: null },
{
begin: /\(/, end: /\)/, excludeBegin: true, excludeEnd: true,
keywords: KEYWORDS,
contains: ['self', PROMPT, NUMBER, STRING, hljs.HASH_COMMENT_MODE],
},
],
};
SUBST.contains = [STRING, NUMBER, PROMPT];
return {
name: 'Python',
aliases: ['py', 'gyp', 'ipython'],
keywords: KEYWORDS,
illegal: /(<\/|->|\?)|=>/,
contains: [
PROMPT,
NUMBER,
// eat "if" prior to string so that it won't accidentally be
// labeled as an f-string as in:
{ begin: /\bself\b/, }, // very common convention
{ beginKeywords: "if", relevance: 0 },
STRING,
hljs.HASH_COMMENT_MODE,
{
variants: [
{className: 'function', beginKeywords: 'def'},
{className: 'class', beginKeywords: 'class'}
],
end: /:/,
illegal: /[${=;\n,]/,
contains: [
hljs.UNDERSCORE_TITLE_MODE,
PARAMS,
{
begin: /->/, endsWithParent: true,
keywords: 'None'
}
]
},
{
className: 'meta',
begin: /^[\t ]*@/, end: /(?=#)|$/,
contains: [NUMBER, PARAMS, STRING]
},
{
begin: /\b(print|exec)\(/ // don’t highlight keywords-turned-functions in Python 3
}
]
};
} | [
"function ruby(hljs) {\n const RUBY_METHOD_RE = '([a-zA-Z_]\\\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\\\*\\\\*|[-/+%^&*~`|]|\\\\[\\\\]=?)';\n const RUBY_KEYWORDS = {\n keyword:\n 'and then defined module in return redo if BEGIN retry end for self when ' +\n 'next until do begin unless END rescue else break undef not super class case ' +\n 'require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor ' +\n '__FILE__',\n built_in: 'proc lambda',\n literal:\n 'true false nil'\n };\n const YARDOCTAG = {\n className: 'doctag',\n begin: '@[A-Za-z]+'\n };\n const IRB_OBJECT = {\n begin: '#<',\n end: '>'\n };\n const COMMENT_MODES = [\n hljs.COMMENT(\n '#',\n '$',\n {\n contains: [ YARDOCTAG ]\n }\n ),\n hljs.COMMENT(\n '^=begin',\n '^=end',\n {\n contains: [ YARDOCTAG ],\n relevance: 10\n }\n ),\n hljs.COMMENT('^__END__', '\\\\n$')\n ];\n const SUBST = {\n className: 'subst',\n begin: /#\\{/,\n end: /\\}/,\n keywords: RUBY_KEYWORDS\n };\n const STRING = {\n className: 'string',\n contains: [\n hljs.BACKSLASH_ESCAPE,\n SUBST\n ],\n variants: [\n {\n begin: /'/,\n end: /'/\n },\n {\n begin: /\"/,\n end: /\"/\n },\n {\n begin: /`/,\n end: /`/\n },\n {\n begin: /%[qQwWx]?\\(/,\n end: /\\)/\n },\n {\n begin: /%[qQwWx]?\\[/,\n end: /\\]/\n },\n {\n begin: /%[qQwWx]?\\{/,\n end: /\\}/\n },\n {\n begin: /%[qQwWx]?</,\n end: />/\n },\n {\n begin: /%[qQwWx]?\\//,\n end: /\\//\n },\n {\n begin: /%[qQwWx]?%/,\n end: /%/\n },\n {\n begin: /%[qQwWx]?-/,\n end: /-/\n },\n {\n begin: /%[qQwWx]?\\|/,\n end: /\\|/\n },\n // in the following expressions, \\B in the beginning suppresses recognition of ?-sequences\n // where ? is the last character of a preceding identifier, as in: `func?4`\n {\n begin: /\\B\\?(\\\\\\d{1,3})/\n },\n {\n begin: /\\B\\?(\\\\x[A-Fa-f0-9]{1,2})/\n },\n {\n begin: /\\B\\?(\\\\u\\{?[A-Fa-f0-9]{1,6}\\}?)/\n },\n {\n begin: /\\B\\?(\\\\M-\\\\C-|\\\\M-\\\\c|\\\\c\\\\M-|\\\\M-|\\\\C-\\\\M-)[\\x20-\\x7e]/\n },\n {\n begin: /\\B\\?\\\\(c|C-)[\\x20-\\x7e]/\n },\n {\n begin: /\\B\\?\\\\?\\S/\n },\n { // heredocs\n begin: /<<[-~]?'?(\\w+)\\n(?:[^\\n]*\\n)*?\\s*\\1\\b/,\n returnBegin: true,\n contains: [\n {\n begin: /<<[-~]?'?/\n },\n hljs.END_SAME_AS_BEGIN({\n begin: /(\\w+)/,\n end: /(\\w+)/,\n contains: [\n hljs.BACKSLASH_ESCAPE,\n SUBST\n ]\n })\n ]\n }\n ]\n };\n\n // Ruby syntax is underdocumented, but this grammar seems to be accurate\n // as of version 2.7.2 (confirmed with (irb and `Ripper.sexp(...)`)\n // https://docs.ruby-lang.org/en/2.7.0/doc/syntax/literals_rdoc.html#label-Numbers\n const decimal = '[1-9](_?[0-9])*|0';\n const digits = '[0-9](_?[0-9])*';\n const NUMBER = {\n className: 'number',\n relevance: 0,\n variants: [\n // decimal integer/float, optionally exponential or rational, optionally imaginary\n {\n begin: `\\\\b(${decimal})(\\\\.(${digits}))?([eE][+-]?(${digits})|r)?i?\\\\b`\n },\n\n // explicit decimal/binary/octal/hexadecimal integer,\n // optionally rational and/or imaginary\n {\n begin: \"\\\\b0[dD][0-9](_?[0-9])*r?i?\\\\b\"\n },\n {\n begin: \"\\\\b0[bB][0-1](_?[0-1])*r?i?\\\\b\"\n },\n {\n begin: \"\\\\b0[oO][0-7](_?[0-7])*r?i?\\\\b\"\n },\n {\n begin: \"\\\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\\\b\"\n },\n\n // 0-prefixed implicit octal integer, optionally rational and/or imaginary\n {\n begin: \"\\\\b0(_?[0-7])+r?i?\\\\b\"\n }\n ]\n };\n\n const PARAMS = {\n className: 'params',\n begin: '\\\\(',\n end: '\\\\)',\n endsParent: true,\n keywords: RUBY_KEYWORDS\n };\n\n const RUBY_DEFAULT_CONTAINS = [\n STRING,\n {\n className: 'class',\n beginKeywords: 'class module',\n end: '$|;',\n illegal: /=/,\n contains: [\n hljs.inherit(hljs.TITLE_MODE, {\n begin: '[A-Za-z_]\\\\w*(::\\\\w+)*(\\\\?|!)?'\n }),\n {\n begin: '<\\\\s*',\n contains: [\n {\n begin: '(' + hljs.IDENT_RE + '::)?' + hljs.IDENT_RE,\n // we already get points for <, we don't need poitns\n // for the name also\n relevance: 0\n }\n ]\n }\n ].concat(COMMENT_MODES)\n },\n {\n className: 'function',\n // def method_name(\n // def method_name;\n // def method_name (end of line)\n begin: concat(/def\\s*/, lookahead(RUBY_METHOD_RE + \"\\\\s*(\\\\(|;|$)\")),\n relevance: 0, // relevance comes from kewords\n keywords: \"def\",\n end: '$|;',\n contains: [\n hljs.inherit(hljs.TITLE_MODE, {\n begin: RUBY_METHOD_RE\n }),\n PARAMS\n ].concat(COMMENT_MODES)\n },\n {\n // swallow namespace qualifiers before symbols\n begin: hljs.IDENT_RE + '::'\n },\n {\n className: 'symbol',\n begin: hljs.UNDERSCORE_IDENT_RE + '(!|\\\\?)?:',\n relevance: 0\n },\n {\n className: 'symbol',\n begin: ':(?!\\\\s)',\n contains: [\n STRING,\n {\n begin: RUBY_METHOD_RE\n }\n ],\n relevance: 0\n },\n NUMBER,\n {\n // negative-look forward attemps to prevent false matches like:\n // @ident@ or $ident$ that might indicate this is not ruby at all\n className: \"variable\",\n begin: '(\\\\$\\\\W)|((\\\\$|@@?)(\\\\w+))(?=[^@$?])' + `(?![A-Za-z])(?![@$?'])`\n },\n {\n className: 'params',\n begin: /\\|/,\n end: /\\|/,\n relevance: 0, // this could be a lot of things (in other languages) other than params\n keywords: RUBY_KEYWORDS\n },\n { // regexp container\n begin: '(' + hljs.RE_STARTERS_RE + '|unless)\\\\s*',\n keywords: 'unless',\n contains: [\n {\n className: 'regexp',\n contains: [\n hljs.BACKSLASH_ESCAPE,\n SUBST\n ],\n illegal: /\\n/,\n variants: [\n {\n begin: '/',\n end: '/[a-z]*'\n },\n {\n begin: /%r\\{/,\n end: /\\}[a-z]*/\n },\n {\n begin: '%r\\\\(',\n end: '\\\\)[a-z]*'\n },\n {\n begin: '%r!',\n end: '![a-z]*'\n },\n {\n begin: '%r\\\\[',\n end: '\\\\][a-z]*'\n }\n ]\n }\n ].concat(IRB_OBJECT, COMMENT_MODES),\n relevance: 0\n }\n ].concat(IRB_OBJECT, COMMENT_MODES);\n\n SUBST.contains = RUBY_DEFAULT_CONTAINS;\n PARAMS.contains = RUBY_DEFAULT_CONTAINS;\n\n // >>\n // ?>\n const SIMPLE_PROMPT = \"[>?]>\";\n // irb(main):001:0>\n const DEFAULT_PROMPT = \"[\\\\w#]+\\\\(\\\\w+\\\\):\\\\d+:\\\\d+>\";\n const RVM_PROMPT = \"(\\\\w+-)?\\\\d+\\\\.\\\\d+\\\\.\\\\d+(p\\\\d+)?[^\\\\d][^>]+>\";\n\n const IRB_DEFAULT = [\n {\n begin: /^\\s*=>/,\n starts: {\n end: '$',\n contains: RUBY_DEFAULT_CONTAINS\n }\n },\n {\n className: 'meta',\n begin: '^(' + SIMPLE_PROMPT + \"|\" + DEFAULT_PROMPT + '|' + RVM_PROMPT + ')(?=[ ])',\n starts: {\n end: '$',\n contains: RUBY_DEFAULT_CONTAINS\n }\n }\n ];\n\n COMMENT_MODES.unshift(IRB_OBJECT);\n\n return {\n name: 'Ruby',\n aliases: [\n 'rb',\n 'gemspec',\n 'podspec',\n 'thor',\n 'irb'\n ],\n keywords: RUBY_KEYWORDS,\n illegal: /\\/\\*/,\n contains: [\n hljs.SHEBANG({\n binary: \"ruby\"\n })\n ]\n .concat(IRB_DEFAULT)\n .concat(COMMENT_MODES)\n .concat(RUBY_DEFAULT_CONTAINS)\n };\n}",
"function swift(hljs) {\n const WHITESPACE = {\n match: /\\s+/,\n relevance: 0\n };\n // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID411\n const BLOCK_COMMENT = hljs.COMMENT(\n '/\\\\*',\n '\\\\*/',\n {\n contains: [ 'self' ]\n }\n );\n const COMMENTS = [\n hljs.C_LINE_COMMENT_MODE,\n BLOCK_COMMENT\n ];\n\n // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID413\n // https://docs.swift.org/swift-book/ReferenceManual/zzSummaryOfTheGrammar.html\n const DOT_KEYWORD = {\n className: 'keyword',\n begin: concat(/\\./, lookahead(either(...dotKeywords, ...optionalDotKeywords))),\n end: either(...dotKeywords, ...optionalDotKeywords),\n excludeBegin: true\n };\n const KEYWORD_GUARD = {\n // Consume .keyword to prevent highlighting properties and methods as keywords.\n match: concat(/\\./, either(...keywords)),\n relevance: 0\n };\n const PLAIN_KEYWORDS = keywords\n .filter(kw => typeof kw === 'string')\n .concat([ \"_|0\" ]); // seems common, so 0 relevance\n const REGEX_KEYWORDS = keywords\n .filter(kw => typeof kw !== 'string') // find regex\n .concat(keywordTypes)\n .map(keywordWrapper);\n const KEYWORD = {\n variants: [\n {\n className: 'keyword',\n match: either(...REGEX_KEYWORDS, ...optionalDotKeywords)\n }\n ]\n };\n // find all the regular keywords\n const KEYWORDS = {\n $pattern: either(\n /\\b\\w+/, // regular keywords\n /#\\w+/ // number keywords\n ),\n keyword: PLAIN_KEYWORDS\n .concat(numberSignKeywords),\n literal: literals\n };\n const KEYWORD_MODES = [\n DOT_KEYWORD,\n KEYWORD_GUARD,\n KEYWORD\n ];\n\n // https://github.com/apple/swift/tree/main/stdlib/public/core\n const BUILT_IN_GUARD = {\n // Consume .built_in to prevent highlighting properties and methods.\n match: concat(/\\./, either(...builtIns)),\n relevance: 0\n };\n const BUILT_IN = {\n className: 'built_in',\n match: concat(/\\b/, either(...builtIns), /(?=\\()/)\n };\n const BUILT_INS = [\n BUILT_IN_GUARD,\n BUILT_IN\n ];\n\n // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID418\n const OPERATOR_GUARD = {\n // Prevent -> from being highlighting as an operator.\n match: /->/,\n relevance: 0\n };\n const OPERATOR = {\n className: 'operator',\n relevance: 0,\n variants: [\n {\n match: operator\n },\n {\n // dot-operator: only operators that start with a dot are allowed to use dots as\n // characters (..., ...<, .*, etc). So there rule here is: a dot followed by one or more\n // characters that may also include dots.\n match: `\\\\.(\\\\.|${operatorCharacter})+`\n }\n ]\n };\n const OPERATORS = [\n OPERATOR_GUARD,\n OPERATOR\n ];\n\n // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#grammar_numeric-literal\n // TODO: Update for leading `-` after lookbehind is supported everywhere\n const decimalDigits = '([0-9]_*)+';\n const hexDigits = '([0-9a-fA-F]_*)+';\n const NUMBER = {\n className: 'number',\n relevance: 0,\n variants: [\n // decimal floating-point-literal (subsumes decimal-literal)\n {\n match: `\\\\b(${decimalDigits})(\\\\.(${decimalDigits}))?` + `([eE][+-]?(${decimalDigits}))?\\\\b`\n },\n // hexadecimal floating-point-literal (subsumes hexadecimal-literal)\n {\n match: `\\\\b0x(${hexDigits})(\\\\.(${hexDigits}))?` + `([pP][+-]?(${decimalDigits}))?\\\\b`\n },\n // octal-literal\n {\n match: /\\b0o([0-7]_*)+\\b/\n },\n // binary-literal\n {\n match: /\\b0b([01]_*)+\\b/\n }\n ]\n };\n\n // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#grammar_string-literal\n const ESCAPED_CHARACTER = (rawDelimiter = \"\") => ({\n className: 'subst',\n variants: [\n {\n match: concat(/\\\\/, rawDelimiter, /[0\\\\tnr\"']/)\n },\n {\n match: concat(/\\\\/, rawDelimiter, /u\\{[0-9a-fA-F]{1,8}\\}/)\n }\n ]\n });\n const ESCAPED_NEWLINE = (rawDelimiter = \"\") => ({\n className: 'subst',\n match: concat(/\\\\/, rawDelimiter, /[\\t ]*(?:[\\r\\n]|\\r\\n)/)\n });\n const INTERPOLATION = (rawDelimiter = \"\") => ({\n className: 'subst',\n label: \"interpol\",\n begin: concat(/\\\\/, rawDelimiter, /\\(/),\n end: /\\)/\n });\n const MULTILINE_STRING = (rawDelimiter = \"\") => ({\n begin: concat(rawDelimiter, /\"\"\"/),\n end: concat(/\"\"\"/, rawDelimiter),\n contains: [\n ESCAPED_CHARACTER(rawDelimiter),\n ESCAPED_NEWLINE(rawDelimiter),\n INTERPOLATION(rawDelimiter)\n ]\n });\n const SINGLE_LINE_STRING = (rawDelimiter = \"\") => ({\n begin: concat(rawDelimiter, /\"/),\n end: concat(/\"/, rawDelimiter),\n contains: [\n ESCAPED_CHARACTER(rawDelimiter),\n INTERPOLATION(rawDelimiter)\n ]\n });\n const STRING = {\n className: 'string',\n variants: [\n MULTILINE_STRING(),\n MULTILINE_STRING(\"#\"),\n MULTILINE_STRING(\"##\"),\n MULTILINE_STRING(\"###\"),\n SINGLE_LINE_STRING(),\n SINGLE_LINE_STRING(\"#\"),\n SINGLE_LINE_STRING(\"##\"),\n SINGLE_LINE_STRING(\"###\")\n ]\n };\n\n // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID412\n const QUOTED_IDENTIFIER = {\n match: concat(/`/, identifier, /`/)\n };\n const IMPLICIT_PARAMETER = {\n className: 'variable',\n match: /\\$\\d+/\n };\n const PROPERTY_WRAPPER_PROJECTION = {\n className: 'variable',\n match: `\\\\$${identifierCharacter}+`\n };\n const IDENTIFIERS = [\n QUOTED_IDENTIFIER,\n IMPLICIT_PARAMETER,\n PROPERTY_WRAPPER_PROJECTION\n ];\n\n // https://docs.swift.org/swift-book/ReferenceManual/Attributes.html\n const AVAILABLE_ATTRIBUTE = {\n match: /(@|#)available/,\n className: \"keyword\",\n starts: {\n contains: [\n {\n begin: /\\(/,\n end: /\\)/,\n keywords: availabilityKeywords,\n contains: [\n ...OPERATORS,\n NUMBER,\n STRING\n ]\n }\n ]\n }\n };\n const KEYWORD_ATTRIBUTE = {\n className: 'keyword',\n match: concat(/@/, either(...keywordAttributes))\n };\n const USER_DEFINED_ATTRIBUTE = {\n className: 'meta',\n match: concat(/@/, identifier)\n };\n const ATTRIBUTES = [\n AVAILABLE_ATTRIBUTE,\n KEYWORD_ATTRIBUTE,\n USER_DEFINED_ATTRIBUTE\n ];\n\n // https://docs.swift.org/swift-book/ReferenceManual/Types.html\n const TYPE = {\n match: lookahead(/\\b[A-Z]/),\n relevance: 0,\n contains: [\n { // Common Apple frameworks, for relevance boost\n className: 'type',\n match: concat(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/, identifierCharacter, '+')\n },\n { // Type identifier\n className: 'type',\n match: typeIdentifier,\n relevance: 0\n },\n { // Optional type\n match: /[?!]+/,\n relevance: 0\n },\n { // Variadic parameter\n match: /\\.\\.\\./,\n relevance: 0\n },\n { // Protocol composition\n match: concat(/\\s+&\\s+/, lookahead(typeIdentifier)),\n relevance: 0\n }\n ]\n };\n const GENERIC_ARGUMENTS = {\n begin: /</,\n end: />/,\n keywords: KEYWORDS,\n contains: [\n ...COMMENTS,\n ...KEYWORD_MODES,\n ...ATTRIBUTES,\n OPERATOR_GUARD,\n TYPE\n ]\n };\n TYPE.contains.push(GENERIC_ARGUMENTS);\n\n // https://docs.swift.org/swift-book/ReferenceManual/Expressions.html#ID552\n // Prevents element names from being highlighted as keywords.\n const TUPLE_ELEMENT_NAME = {\n match: concat(identifier, /\\s*:/),\n keywords: \"_|0\",\n relevance: 0\n };\n // Matches tuples as well as the parameter list of a function type.\n const TUPLE = {\n begin: /\\(/,\n end: /\\)/,\n relevance: 0,\n keywords: KEYWORDS,\n contains: [\n 'self',\n TUPLE_ELEMENT_NAME,\n ...COMMENTS,\n ...KEYWORD_MODES,\n ...BUILT_INS,\n ...OPERATORS,\n NUMBER,\n STRING,\n ...IDENTIFIERS,\n ...ATTRIBUTES,\n TYPE\n ]\n };\n\n // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID362\n // Matches both the keyword func and the function title.\n // Grouping these lets us differentiate between the operator function <\n // and the start of the generic parameter clause (also <).\n const FUNC_PLUS_TITLE = {\n beginKeywords: 'func',\n contains: [\n {\n className: 'title',\n match: either(QUOTED_IDENTIFIER.match, identifier, operator),\n // Required to make sure the opening < of the generic parameter clause\n // isn't parsed as a second title.\n endsParent: true,\n relevance: 0\n },\n WHITESPACE\n ]\n };\n const GENERIC_PARAMETERS = {\n begin: /</,\n end: />/,\n contains: [\n ...COMMENTS,\n TYPE\n ]\n };\n const FUNCTION_PARAMETER_NAME = {\n begin: either(\n lookahead(concat(identifier, /\\s*:/)),\n lookahead(concat(identifier, /\\s+/, identifier, /\\s*:/))\n ),\n end: /:/,\n relevance: 0,\n contains: [\n {\n className: 'keyword',\n match: /\\b_\\b/\n },\n {\n className: 'params',\n match: identifier\n }\n ]\n };\n const FUNCTION_PARAMETERS = {\n begin: /\\(/,\n end: /\\)/,\n keywords: KEYWORDS,\n contains: [\n FUNCTION_PARAMETER_NAME,\n ...COMMENTS,\n ...KEYWORD_MODES,\n ...OPERATORS,\n NUMBER,\n STRING,\n ...ATTRIBUTES,\n TYPE,\n TUPLE\n ],\n endsParent: true,\n illegal: /[\"']/\n };\n const FUNCTION = {\n className: 'function',\n match: lookahead(/\\bfunc\\b/),\n contains: [\n FUNC_PLUS_TITLE,\n GENERIC_PARAMETERS,\n FUNCTION_PARAMETERS,\n WHITESPACE\n ],\n illegal: [\n /\\[/,\n /%/\n ]\n };\n\n // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID375\n // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID379\n const INIT_SUBSCRIPT = {\n className: 'function',\n match: /\\b(subscript|init[?!]?)\\s*(?=[<(])/,\n keywords: {\n keyword: \"subscript init init? init!\",\n $pattern: /\\w+[?!]?/\n },\n contains: [\n GENERIC_PARAMETERS,\n FUNCTION_PARAMETERS,\n WHITESPACE\n ],\n illegal: /\\[|%/\n };\n // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID380\n const OPERATOR_DECLARATION = {\n beginKeywords: 'operator',\n end: hljs.MATCH_NOTHING_RE,\n contains: [\n {\n className: 'title',\n match: operator,\n endsParent: true,\n relevance: 0\n }\n ]\n };\n\n // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID550\n const PRECEDENCEGROUP = {\n beginKeywords: 'precedencegroup',\n end: hljs.MATCH_NOTHING_RE,\n contains: [\n {\n className: 'title',\n match: typeIdentifier,\n relevance: 0\n },\n {\n begin: /{/,\n end: /}/,\n relevance: 0,\n endsParent: true,\n keywords: [\n ...precedencegroupKeywords,\n ...literals\n ],\n contains: [ TYPE ]\n }\n ]\n };\n\n // Add supported submodes to string interpolation.\n for (const variant of STRING.variants) {\n const interpolation = variant.contains.find(mode => mode.label === \"interpol\");\n // TODO: Interpolation can contain any expression, so there's room for improvement here.\n interpolation.keywords = KEYWORDS;\n const submodes = [\n ...KEYWORD_MODES,\n ...BUILT_INS,\n ...OPERATORS,\n NUMBER,\n STRING,\n ...IDENTIFIERS\n ];\n interpolation.contains = [\n ...submodes,\n {\n begin: /\\(/,\n end: /\\)/,\n contains: [\n 'self',\n ...submodes\n ]\n }\n ];\n }\n\n return {\n name: 'Swift',\n keywords: KEYWORDS,\n contains: [\n ...COMMENTS,\n FUNCTION,\n INIT_SUBSCRIPT,\n {\n className: 'class',\n beginKeywords: 'struct protocol class extension enum',\n end: '\\\\{',\n excludeEnd: true,\n keywords: KEYWORDS,\n contains: [\n hljs.inherit(hljs.TITLE_MODE, {\n begin: /[A-Za-z$_][\\u00C0-\\u02B80-9A-Za-z$_]*/\n }),\n ...KEYWORD_MODES\n ]\n },\n OPERATOR_DECLARATION,\n PRECEDENCEGROUP,\n {\n beginKeywords: 'import',\n end: /$/,\n contains: [ ...COMMENTS ],\n relevance: 0\n },\n ...KEYWORD_MODES,\n ...BUILT_INS,\n ...OPERATORS,\n NUMBER,\n STRING,\n ...IDENTIFIERS,\n ...ATTRIBUTES,\n TYPE,\n TUPLE\n ]\n };\n}",
"function languageGuesswork(code) {\n\tvar htmlBlocks,\n\thtmlVoids;\n\tif ((code.indexOf('$')) === 0) {\n\t\treturn 'bash';\n\t}\n\tif ((code.indexOf('System.out.print')) !== -1) {\n\t\treturn 'java';\n\t}\n\tif ((code.indexOf('public')) !== -1) {\n\t\treturn 'java';\n\t}\n\tif ((code.indexOf('private')) !== -1) {\n\t\treturn 'java';\n\t}\n\tif ((code.indexOf('protected')) !== -1) {\n\t\treturn 'java';\n\t}\n\thtmlBlocks = ['address', 'article', 'aside', 'audio', 'blockquote', 'body', 'canvas', 'center', 'dd', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'html', 'isindex', 'li', 'main', 'menu', 'nav', 'noframes', 'noscript', 'ol', 'output', 'p', 'pre', 'section', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'ul'];\n\thtmlVoids = ['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'];\n\thtmlBlocks.some(function (name) {\n\t\treturn (code.indexOf(\"<\" + name + \">\")) !== -1;\n\t});\n\thtmlVoids.some(function (name) {\n\t\treturn (code.indexOf(\"<\" + name)) !== -1;\n\t});\n\tif ((code.indexOf('var')) !== -1) {\n\t\treturn 'js';\n\t}\n\tif ((code.indexOf('function')) !== -1) {\n\t\treturn 'js';\n\t}\n\tif ((code.indexOf('let')) !== -1) {\n\t\treturn 'js';\n\t}\n\treturn '';\n}",
"function codeLove() { //function that does exactly what it looks like it does.\n return \"I love code\";\n}",
"function ola('Javascript'){\n\t\tconsole.log('Hello world!')\n\t}",
"function add_py(str){\n\tif(str.indexOf(\"Py\") == 0){\n\t\treturn str;\n\t} else {\n\t\treturn \"Py\" + str;\n\t}\n}",
"function Swift(CodeMirror) {\n function wordSet(words) {\n var set = {};\n for (var i = 0; i < words.length; i++) set[words[i]] = true;\n return set\n }\n\n var keywords = wordSet([\"_\",\"var\",\"let\",\"class\",\"enum\",\"extension\",\"import\",\"protocol\",\"struct\",\"func\",\"typealias\",\"associatedtype\",\n \"open\",\"public\",\"internal\",\"fileprivate\",\"private\",\"deinit\",\"init\",\"new\",\"override\",\"self\",\"subscript\",\"super\",\n \"convenience\",\"dynamic\",\"final\",\"indirect\",\"lazy\",\"required\",\"static\",\"unowned\",\"unowned(safe)\",\"unowned(unsafe)\",\"weak\",\"as\",\"is\",\n \"break\",\"case\",\"continue\",\"default\",\"else\",\"fallthrough\",\"for\",\"guard\",\"if\",\"in\",\"repeat\",\"switch\",\"where\",\"while\",\n \"defer\",\"return\",\"inout\",\"mutating\",\"nonmutating\",\"catch\",\"do\",\"rethrows\",\"throw\",\"throws\",\"try\",\"didSet\",\"get\",\"set\",\"willSet\",\n \"assignment\",\"associativity\",\"infix\",\"left\",\"none\",\"operator\",\"postfix\",\"precedence\",\"precedencegroup\",\"prefix\",\"right\",\n \"Any\",\"AnyObject\",\"Type\",\"dynamicType\",\"Self\",\"Protocol\",\"__COLUMN__\",\"__FILE__\",\"__FUNCTION__\",\"__LINE__\"]);\n var definingKeywords = wordSet([\"var\",\"let\",\"class\",\"enum\",\"extension\",\"import\",\"protocol\",\"struct\",\"func\",\"typealias\",\"associatedtype\",\"for\"]);\n var atoms = wordSet([\"true\",\"false\",\"nil\",\"self\",\"super\",\"_\"]);\n var types = wordSet([\"Array\",\"Bool\",\"Character\",\"Dictionary\",\"Double\",\"Float\",\"Int\",\"Int8\",\"Int16\",\"Int32\",\"Int64\",\"Never\",\"Optional\",\"Set\",\"String\",\n \"UInt8\",\"UInt16\",\"UInt32\",\"UInt64\",\"Void\"]);\n var operators = \"+-/*%=|&<>~^?!\";\n var punc = \":;,.(){}[]\";\n var binary = /^\\-?0b[01][01_]*/;\n var octal = /^\\-?0o[0-7][0-7_]*/;\n var hexadecimal = /^\\-?0x[\\dA-Fa-f][\\dA-Fa-f_]*(?:(?:\\.[\\dA-Fa-f][\\dA-Fa-f_]*)?[Pp]\\-?\\d[\\d_]*)?/;\n var decimal = /^\\-?\\d[\\d_]*(?:\\.\\d[\\d_]*)?(?:[Ee]\\-?\\d[\\d_]*)?/;\n var identifier = /^\\$\\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\\1/;\n var property = /^\\.(?:\\$\\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\\1)/;\n var instruction = /^\\#[A-Za-z]+/;\n var attribute = /^@(?:\\$\\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\\1)/;\n //var regexp = /^\\/(?!\\s)(?:\\/\\/)?(?:\\\\.|[^\\/])+\\//\n\n function tokenBase(stream, state, prev) {\n if (stream.sol()) state.indented = stream.indentation();\n if (stream.eatSpace()) return null\n\n var ch = stream.peek();\n if (ch == \"/\") {\n if (stream.match(\"//\")) {\n stream.skipToEnd();\n return \"comment\"\n }\n if (stream.match(\"/*\")) {\n state.tokenize.push(tokenComment);\n return tokenComment(stream, state)\n }\n }\n if (stream.match(instruction)) return \"builtin\"\n if (stream.match(attribute)) return \"attribute\"\n if (stream.match(binary)) return \"number\"\n if (stream.match(octal)) return \"number\"\n if (stream.match(hexadecimal)) return \"number\"\n if (stream.match(decimal)) return \"number\"\n if (stream.match(property)) return \"property\"\n if (operators.indexOf(ch) > -1) {\n stream.next();\n return \"operator\"\n }\n if (punc.indexOf(ch) > -1) {\n stream.next();\n stream.match(\"..\");\n return \"punctuation\"\n }\n if (ch = stream.match(/(\"{3}|\"|')/)) {\n var tokenize = tokenString(ch[0]);\n state.tokenize.push(tokenize);\n return tokenize(stream, state)\n }\n\n if (stream.match(identifier)) {\n var ident = stream.current();\n if (types.hasOwnProperty(ident)) return \"variable-2\"\n if (atoms.hasOwnProperty(ident)) return \"atom\"\n if (keywords.hasOwnProperty(ident)) {\n if (definingKeywords.hasOwnProperty(ident))\n state.prev = \"define\";\n return \"keyword\"\n }\n if (prev == \"define\") return \"def\"\n return \"variable\"\n }\n\n stream.next();\n return null\n }\n\n function tokenUntilClosingParen() {\n var depth = 0;\n return function(stream, state, prev) {\n var inner = tokenBase(stream, state, prev);\n if (inner == \"punctuation\") {\n if (stream.current() == \"(\") ++depth;\n else if (stream.current() == \")\") {\n if (depth == 0) {\n stream.backUp(1);\n state.tokenize.pop();\n return state.tokenize[state.tokenize.length - 1](stream, state)\n }\n else --depth;\n }\n }\n return inner\n }\n }\n\n function tokenString(quote) {\n var singleLine = quote.length == 1;\n return function(stream, state) {\n var ch, escaped = false;\n while (ch = stream.next()) {\n if (escaped) {\n if (ch == \"(\") {\n state.tokenize.push(tokenUntilClosingParen());\n return \"string\"\n }\n escaped = false;\n } else if (stream.match(quote)) {\n state.tokenize.pop();\n return \"string\"\n } else {\n escaped = ch == \"\\\\\";\n }\n }\n if (singleLine) {\n state.tokenize.pop();\n }\n return \"string\"\n }\n }\n\n function tokenComment(stream, state) {\n var ch;\n while (true) {\n stream.match(/^[^/*]+/, true);\n ch = stream.next();\n if (!ch) break\n if (ch === \"/\" && stream.eat(\"*\")) {\n state.tokenize.push(tokenComment);\n } else if (ch === \"*\" && stream.eat(\"/\")) {\n state.tokenize.pop();\n }\n }\n return \"comment\"\n }\n\n function Context(prev, align, indented) {\n this.prev = prev;\n this.align = align;\n this.indented = indented;\n }\n\n function pushContext(state, stream) {\n var align = stream.match(/^\\s*($|\\/[\\/\\*])/, false) ? null : stream.column() + 1;\n state.context = new Context(state.context, align, state.indented);\n }\n\n function popContext(state) {\n if (state.context) {\n state.indented = state.context.indented;\n state.context = state.context.prev;\n }\n }\n\n CodeMirror.defineMode(\"swift\", function(config) {\n return {\n startState: function() {\n return {\n prev: null,\n context: null,\n indented: 0,\n tokenize: []\n }\n },\n\n token: function(stream, state) {\n var prev = state.prev;\n state.prev = null;\n var tokenize = state.tokenize[state.tokenize.length - 1] || tokenBase;\n var style = tokenize(stream, state, prev);\n if (!style || style == \"comment\") state.prev = prev;\n else if (!state.prev) state.prev = style;\n\n if (style == \"punctuation\") {\n var bracket = /[\\(\\[\\{]|([\\]\\)\\}])/.exec(stream.current());\n if (bracket) (bracket[1] ? popContext : pushContext)(state, stream);\n }\n\n return style\n },\n\n indent: function(state, textAfter) {\n var cx = state.context;\n if (!cx) return 0\n var closing = /^[\\]\\}\\)]/.test(textAfter);\n if (cx.align != null) return cx.align - (closing ? 1 : 0)\n return cx.indented + (closing ? 0 : config.indentUnit)\n },\n\n electricInput: /^\\s*[\\)\\}\\]]$/,\n\n lineComment: \"//\",\n blockCommentStart: \"/*\",\n blockCommentEnd: \"*/\",\n fold: \"brace\",\n closeBrackets: \"()[]{}''\\\"\\\"``\"\n }\n });\n\n CodeMirror.defineMIME(\"text/x-swift\",\"swift\");\n }",
"function processPythonInclude( page ){\n\n const dirPath = path.dirname(page.rawPath);\n var lines = page.content.split(\"\\n\");\n // !PYTHON src=\"\" exec=true link=true\n const token = \"!PYTHON\"\n var pageContent = \"\";\n var outputContent = \"\";\n for (let i = 0; i < lines.length; i++) {\n if( lines[i].includes(token) ){\n var line = lines[i];\n var tokens = line.replace(token, \"\").trim().split(\" \");\n var args = {}\n for( let j=0; j<tokens.length; j++){\n var the_arg= tokens[j].split(\"=\");\n args[the_arg[0]] = the_arg[1]; \n }\n\n var pyContent;\n if( \"src\" in args ){\n var relPath = args[\"src\"];\n var py_path = path.join(dirPath, relPath);\n pyContent = fs.readFileSync(py_path, \"utf8\");\n \n if( \"exec\" in args && args.exec == \"true\"){\n // Exec python script and catch stdout\n const wdir = path.dirname(py_path);\n const pyfile = path.basename(py_path);\n const cmd = this.config.get(\"pluginsConfig.python.executable\", \"python\"); \n const cmd_arg = pyfile;\n const timeout = 1000.*this.config.get(\"pluginsConfig.python.timeout\", 60.);\n var child = cp.spawnSync(cmd,[cmd_arg, ], {cwd:wdir, \n timeout:timeout});\n \n if( child.status != 0 ){\n outputContent = \"Execution Error \"\n this.log.warn(pyfile + \" Python execution failed\");\n this.log.debug('error ', child.error);\n this.log.debug('stdout ', child.stdout.toString());\n this.log.debug('stderr ', child.stderr.toString());\n }\n else{\n this.log.info(pyfile + \" succeed\")\n outputContent = child.stdout.toString();\n }\n }\n }\n else{\n this.log.warn(\"!PYTHON tag found but no source file specified\");\n continue; \n }\n\n pageContent += \"```python\\n\"\n pageContent += pyContent + \"\\n\";\n pageContent += \"```\\n\";\n pageContent += \"{\\% Download src=\\\"\" + args.src + \"\\\" \\%} {\\% endDownload \\%}\\n\";\n if( outputContent != \"\"){\n pageContent += \"```\\n\" + outputContent + \"\\n```\\n\";\n }\n\n }\n else{\n pageContent += lines[i] + \"\\n\";\n }\n\n }\n //console.log(this);\n page.content = pageContent;\n return page;\n}",
"function main(){\n\n lib.printBlue(\"hi\");\n lib.printGreen(\"My name\");\n lib.printRed(\"Is Bob\");\n\n }",
"function make ( ) {\n\n //\n // Most of these fields and methods are involved in the variable\n // identification algorithm.\n //\n //\n // The basic way this algorithm works is that as a scope is walked,\n // variables are collected into an 'unknown' array.\n //\n // Assigned variables are also accumulated.\n // When the scope ends, assigned variables are compared to unknown variables.\n // If the variable was assigned in this scope and not in any scope above\n // it (with except possibly the global scope), then the unknown's callback\n // is invoked. This callback is used to set the variable for the\n // corresponding identifiers.\n // Otherwise, if the variable's assignment is not found, the unkown is\n // bubbled up to the scope above.\n // This continues upward until we hit the global scope, where we then store\n // the remaining unknowns as imports.\n //\n // TODO(kzentner): Improve imports and exports, possible using an entirely\n // seperate module.\n //\n\n return {\n unknownses : null,\n scope_depth : null,\n current_scope : null,\n objects : null,\n variables : null,\n get_objects : function ( ) {\n return this.objects [ this.objects.length - 1 ];\n },\n get_unknowns : function ( ) {\n return this.unknownses [ this.unknownses.length - 1 ];\n },\n add_object : function ( obj ) {\n this.get_objects ( ).push ( obj );\n },\n push_object_list : function ( obj_list ) {\n this.objects.push ( obj_list );\n },\n pop_object_list : function ( ) {\n this.objects.pop ( );\n },\n get_text : function ( text, callback ) {\n var unknown = this.get_unknowns ( ).get_text ( text );\n if ( unknown === undefined ) {\n unknown = [];\n this.get_unknowns ( ).set_text ( text, unknown );\n }\n unknown.push ( { scope : this.current_scope,\n callback : callback } );\n },\n set_variable : function ( text, val ) {\n var variable = this.current_scope.get_text ( text );\n if ( variable === undefined || variable.location === 'global' ) {\n // This is a variable declaration.\n variable = varb.make ( text );\n this.variables.push ( variable );\n this.current_scope.set_text ( text, variable );\n }\n variable.assignments.push ( val );\n return variable;\n },\n push_scope : function ( new_scope ) {\n misc.assert ( new_scope.above ( ) === this.current_scope,\n \"New scope should be child of current scope.\" );\n if ( this.current_scope.children === undefined ) {\n this.current_scope.children = [];\n }\n this.current_scope.children.push ( new_scope );\n this.current_scope = new_scope;\n this.scope_depth += 1;\n this.unknownses.push ( scope.make ( ) );\n },\n finalize_scope : function ( ) {\n var unknowns = this.get_unknowns ( );\n var parent_unknowns;\n if ( this.unknownses.length === 1 ) {\n // TODO(kzentner): Remove this hack.\n parent_unknowns = this.root_module.imports;\n }\n else {\n parent_unknowns = this.unknownses[this.unknownses.length - 2];\n }\n var self = this;\n unknowns.each_text ( function ( key, vals ) {\n if ( self.current_scope.text_distance ( key ) === 0 ) {\n // Variable was declared in this scope.\n vals.forEach ( function ( val ) {\n val.callback ( self.current_scope.get_text ( key ) );\n } );\n }\n else {\n // Variable was not declared in this scope, bubble it up.\n var parent_list = parent_unknowns.get_text ( key );\n if ( parent_list === undefined ) {\n parent_unknowns.set_text ( key, vals );\n }\n else {\n parent_unknowns.set_text ( key, parent_list.concat ( vals ) );\n }\n }\n } );\n },\n pop_scope : function ( ) {\n this.finalize_scope ( );\n this.unknownses.pop ( );\n this.current_scope = this.current_scope.above ( );\n this.scope_depth -= 1;\n },\n //\n // Walk the AST.\n //\n recurse : function ( node ) {\n if ( node.analyze !== undefined ) {\n // If we can analyze this node, do so.\n return node.analyze ( this );\n }\n else if ( node.recurse !== undefined ) {\n var self = this;\n return node.recurse ( function ( child ) {\n self.recurse ( child );\n } );\n }\n else {\n throw 'Could not analyze ' + JSON.stringify ( node, null, ' ' );\n }\n },\n init : function ( root_module ) {\n this.unknownses = [ scope.make ( ) ];\n this.scope_depth = 0;\n this.current_scope = root_module.globals;\n this.objects = [ root_module.objects ];\n this.variables = [];\n this.root_module = root_module;\n },\n analyze : function ( tree, modules ) {\n var root_module = modul.make ( '' );\n var core_module;\n // TODO(kzentner): Fix this hackery.\n if ( modules !== undefined ) {\n core_module = modules.get ( 'core' );\n }\n if ( core_module === undefined ) {\n core_module = make_core_module ( );\n }\n root_module.ast = tree;\n this.init ( root_module );\n this.recurse ( tree );\n // TODO(kzentner): Add support for modules besides the core module.\n root_module.imports.each_text ( function ( key, imprts ) {\n var res = core_module.exports.get_text ( key );\n if ( res !== undefined ) {\n imprts.forEach ( function ( imprt ) {\n imprt.callback ( res );\n } );\n }\n } );\n this.map = generate_canonical_map ( root_module );\n generate_enumerations ( this.map );\n this.all_objects = extract_all_objs ( root_module );\n },\n setupScopes : setupScopes,\n };\n }",
"function Programmer (name, title, age, language) {\n\tthis.name = name;\n\tthis.title = title;\n\tthis.age = age;\n\tthis.language = language;\n\tthis.printInfo = function () {\n\t\tconsole.log(\"name: \" + this.name + \"\\ntitle: \" + this.title + \"\\nage: \" + this.age + \"\\nlanguage: \" + this.language);\n\t}\n}",
"function greetings(name, language){\n if(language === \"French\"){\n console.log(`Bonjour, ${name}!`)\n }\n else if(language === \"Spanish\"){\n console.log(`Hola, ${name}!`)\n }\n else{\n console.log(`Hello, ${name}!`)\n }\n}",
"function helloWorld(language) {\r\n if (language === 'fr') {\r\n return 'Bonjour tout le monde';\r\n }\r\n else if (language === 'es') {\r\n return 'Hola, Mundo';\r\n }\r\n else (language === '') {\r\n return 'Hello, World';\r\n }\r\n}",
"function ProgramParser() {\n \t\t\n \t\t this.parse = function(kind) {\n \t\t \tswitch (kind) { \t\n \t\t \t\tcase \"declaration\": return Declaration();\n \t\t \t\tbreak;\n\t \t\t\tdefault: return Program();\n\t \t\t}\n\t \t}\n \t\t\n \t\t// Import Methods from the expression Parser\n \t\tfunction Assignment() {return expressionParser.Assignment();}\n \t\tfunction Expr() {return expressionParser.Expr();}\n \t\tfunction IdentSequence() {return expressionParser.IdentSequence();}\n \t\tfunction Ident(forced) {return expressionParser.Ident(forced);}\t\t\n \t\tfunction EPStatement() {return expressionParser.Statement();}\n\n\n\t\tfunction whatNext() {\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"class\"\t\t: \n \t\t\t\tcase \"function\"\t \t: \n \t\t\t\tcase \"structure\"\t:\n \t\t\t\tcase \"constant\" \t:\n \t\t\t\tcase \"variable\" \t:\n \t\t\t\tcase \"array\"\t\t: \treturn lexer.current.content;\t\n \t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\tdefault\t\t\t\t:\treturn lexer.lookAhead().content;\n \t\t\t}\n\t\t}\n\n// \t\tDeclaration\t:= {Class | Function | VarDecl | Statement} \n\t\tfunction Declaration() {\n\t\t\tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"class\"\t: return Class();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\" : return Function();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"structure\" : return StructDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"array\"\t: return ArrayDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"constant\" :\n \t\t\t\t\tcase \"variable\" : return VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: return false;\n \t\t\t }\n\t\t}\n\n// \t\tProgram\t:= {Class | Function | VarDecl | Structure | Array | Statement} \n//\t\tAST: \"program\": l: {\"function\" | \"variable\" ... | Statement} indexed from 0...x\n\t\tthis.Program=function() {return Program()};\n \t\tfunction Program() {\n \t\t\tdebugMsg(\"ProgramParser : Program\");\n \t\t\tvar current;\n \t\t\tvar ast=new ASTListNode(\"program\");\n \t\t\t\n \t\t\tfor (;!eof();) {\n \t\t\t\t\n \t\t\t\tif (!(current=Declaration())) current=Statement();\n \t\t\t\t\n \t\t\t\tif (!current) break;\n \t\t\t\t\n \t\t\t\tast.add(current);\t\n \t\t\t} \t\t\t\n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tClass:= \"class\" Ident [\"extends\" Ident] \"{\" [\"constructor\" \"(\" Ident Ident \")\"] CodeBlock {VarDecl | Function}\"}\"\n//\t\tAST: \"class\" : l: name:Identifier,extends: ( undefined | Identifier),fields:VarDecl[0..i], methods:Function[0...i]\n\t\tfunction Class() {\n\t\t\tdebugMsg(\"ProgramParser : Class\");\n\t\t\tlexer.next();\n\n\t\t\tvar name=Ident(true);\t\t\t\n\t\t\t\n\t\t\tvar extend={\"content\":undefined};\n\t\t\tif(test(\"extends\")) {\n\t\t\t\tlexer.next();\n\t\t\t\textend=Ident(true);\n\t\t\t}\n\t\t\t\n\t\t\tcheck (\"{\");\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\t\n\t\t\tvar methods=[];\n\t\t\tvar fields=[];\n\t\t\t\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tlexer.next();\n\t\t \t\t//var retType={\"type\":\"ident\",\"content\":\"_$any\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tvar constructName={\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tmethods.push(FunctionBody(name,constructName));\n\t\t\t}\n\t\t\t\n\t\t\tvar current=true;\n\t\t\twhile(!test(\"}\") && current && !eof()) {\n\t\t\t\t \t\n\t\t \tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\"\t: methods.push(Function()); \n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\" : fields.push(VarDecl(true));\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: current=false;\n \t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tcheck(\"}\");\n\t\t\t\n\t\t\tmode.terminatorOff();\n\n\t\t\tsymbolTable.closeScope();\n\t\t\tsymbolTable.addClass(name.content,extend.content,scope);\n\t\t\t\n\t\t\treturn new ASTUnaryNode(\"class\",{\"name\":name,\"extends\":extend,\"scope\":scope,\"methods\":methods,\"fields\":fields});\n\t\t}\n\t\t\n //\t\tStructDecl := \"structure\" Ident \"{\" VarDecl {VarDecl} \"}\"\n //\t\tAST: \"structure\" : l: \"name\":Ident, \"decl\":[VarDecl], \"scope\":symbolTable\n \t\tfunction StructDecl() {\n \t\t\tdebugMsg(\"ProgramParser : StructDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true); \n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\tmode.terminatorOn();\n \t\t\t\n \t\t\tvar decl=[];\n \t\t\t\n \t\t\tvar scope=symbolTable.openScope();\t\n \t\t\tdo {\t\t\t\t\n \t\t\t\tdecl.push(VarDecl(true));\n \t\t\t} while(!test(\"}\") && !eof());\n \t\t\t\n \t\t\tmode.terminatorOff();\n \t\t\tcheck (\"}\");\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\tsymbolTable.addStruct(name.content,scope);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"structure\",{\"name\":name,\"decl\":decl,\"scope\":scope});\n \t\t} \n \t\t\n //\tarrayDecl := \"array\" Ident \"[\"Ident\"]\" \"contains\" Ident\n //\t\tAST: \"array\" : l: \"name\":Ident, \"elemType\":Ident, \"indexTypes\":[Ident]\n \t\tfunction ArrayDecl() {\n \t\t\tdebugMsg(\"ProgramParser : ArrayDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\tcheck(\"[\");\n \t\t\t\t\n \t\t\tvar ident=Ident(!mode.any);\n \t\t\tif (!ident) ident=lexer.anyLiteral();\n \t\t\t\t\n \t\t\tvar indexType=ident;\n \t\t\t\t\n \t\t\tvar bound=ident.content;\n \t\t\t\t\n \t\t\tcheck(\"]\");\n \t\t\t\t\n \t\t\tvar elemType; \t\n \t\t\tif (mode.any) {\n \t\t\t\tif (test(\"contains\")) {\n \t\t\t\t\tlexer.next();\n \t\t\t\t\telemType=Ident(true);\n \t\t\t\t}\n \t\t\t\telse elemType=lexer.anyLiteral();\n \t\t\t} else {\n \t\t\t\tcheck(\"contains\");\n \t\t\t\telemType=Ident(true);\n \t\t\t}\n \t\t\t\n \t\t\tcheck (\";\");\n \t\t\tsymbolTable.addArray(name.content,elemType.content,bound);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"array\",{\"name\":name,\"elemType\":elemType,\"indexType\":indexType});\n \t\t} \n \t\t\n//\t\tFunction := Ident \"function\" Ident \"(\" [Ident Ident {\"[\"\"]\"} {\",\" Ident Ident {\"[\"\"]\"}) } \")\" CodeBlock\n//\t\tAST: \"function\":\tl: returnType: (Ident | \"_$\"), name:name, scope:SymbolTable, param:{name:Ident,type:Ident}0..x, code:CodeBlock \n\t\tthis.Function=function() {return Function();}\n \t\tfunction Function() {\n \t\t\tdebugMsg(\"ProgramParser : Function\");\n \t\t\n \t\t\tvar retType;\n \t\t\tif (mode.decl) retType=Ident(!(mode.any));\n \t\t\tif (!retType) retType=lexer.anyLiteral();\n \t\t\t\n \t\t\tcheck(\"function\");\n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\treturn FunctionBody(retType,name);\n \t\t}\n \t\t\n \n \t\t// The Body of a function, so it is consistent with constructor\n \t\tfunction FunctionBody(retType,name)\t{\n \t\t\tvar scope=symbolTable.openScope();\n \t\t\t\n \t\t\tif (!test(\"(\")) error.expected(\"(\");\n \t\t\n var paramList=[];\n var paramType=[];\n var paramExpected=false; //Indicates wether a parameter is expected (false in the first loop, then true)\n do {\n \t\t\tlexer.next();\n \t\t\t\n \t\t\t/* Parameter */\n \t\t\tvar pName,type;\n \t\t\tvar ident=Ident(paramExpected);\t// Get an Identifier\n \t\t\tparamExpected= true;\n \t\t\t\n \t\t\t// An Identifier is found\n \t\t\tif (ident) {\n \t\t\t\t\n \t\t\t\t// When declaration is possible\n \t\t\t\tif (mode.decl) {\n \t\t\t\t\t\n \t\t\t\t\t// One Identifier found ==> No Type specified ==> indent specifies Param Name\n \t\t\t\t\tif (!(pName=Ident(!(mode.any)))) {\n \t\t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\t\tpName=ident;\n \t\t\t\t\t} else type=ident; // 2 Identifier found\n \t\t\t\t} else {\t// Declaration not possible\n \t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\tpName=ident;\n \t\t\t\t}\t\n\n\t\t\t\t\t// Store Parameter\n\t\t\t\t\tparamType.push(type); \n \t\tparamList.push({\"name\":pName,\"type\":type});\n \t\t \n \t\t \tsymbolTable.addVar(pName.content,type.content);\n \t\t} \n \t\t} while (test(\",\") && !eof());\n\n \tcheck(\")\");\n \t\t\t \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\t\n \t\t\tsymbolTable.addFunction(name.content,retType.content,paramType);\n \t\t\treturn new ASTUnaryNode(\"function\",{\"name\":name,\"scope\":scope,\"param\":paramList,\"returnType\":retType,\"code\":code});\n \t\t}\n \t\t\t\n\t\t\n //\t\tVarDecl := Ident (\"variable\" | \"constant\") Ident [\"=\" Expr] \";\" \n //\t\tAST: \"variable\"|\"constant\": l : type:type, name:name, expr:[expr]\n \t\tthis.VarDecl = function() {return VarDecl();}\n \t\tfunction VarDecl(noInit) {\n \t\t\tdebugMsg(\"ProgramParser : VariableDeclaration\");\n \t\t\tvar line=lexer.current.line;\n \t\t\tvar type=Ident(!mode.any);\n \t\t\tif (!type) type=lexer.anyLiteral();\n \t\t\t\n \t\t\tvar constant=false;\n \t\t\tvar nodeName=\"variable\";\n \t\t\tif (test(\"constant\")) {\n \t\t\t\tconstant=true; \n \t\t\t\tnodeName=\"constant\";\n \t\t\t\tlexer.next();\n \t\t\t}\n \t\t\telse check(\"variable\"); \n \t\t\t \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\tsymbolTable.addVar(name.content,type.content,constant);\n\n\t\t\tvar expr=null;\n\t\t\tif(noInit==undefined){\n\t\t\t\tif (test(\"=\")) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\texpr=Expr();\n\t\t\t\t\tif (!expr) expr=null;\n\t\t\t\t}\n\t\t\t} \n\t\n\t\t\tcheck(\";\");\n\t\t\tvar ast=new ASTUnaryNode(nodeName,{\"type\":type,\"name\":name,\"expr\":expr});\n\t\t\tast.line=line;\n\t\t\treturn ast;\n \t\t}\n \t\t\t\t\n//\t\tCodeBlock := \"{\" {VarDecl | Statement} \"}\" \n//\t\tCodeblock can take a newSymbolTable as argument, this is needed for functions that they can create an scope\n//\t\tcontaining the parameters.\n//\t\tIf newSymbolTable is not specified it will be generated automatical\n// At the End of Codeblock the scope newSymbolTable will be closed again\t\t\n//\t\tAST: \"codeBlock\" : l: \"scope\":symbolTable,\"code\": code:[0..x] {code}\n \t\tfunction CodeBlock() {\n \t\t\tdebugMsg(\"ProgramParser : CodeBlock\");\n\t\t\t\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\tvar begin=lexer.current.line;\n\t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar code=[];\n \t\t\tvar current;\n\n \t\t\twhile(!test(\"}\") && !eof()) {\n \t\t\t\tswitch (whatNext()) {\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\": current=VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault: current=Statement();\t\t\t\t\t\n \t\t\t\t}\n\n \t\t\t\tif(current) {\n \t\t\t\t\tcode.push(current);\n \t\t\t\t} else {\n \t\t\t\t\terror.expected(\"VarDecl or Statement\"); break;\n \t\t\t\t}\n \t\t\t}\t\n \t\t\t\n \t\t\tvar end=lexer.current.line;\n \t\t\tcheck(\"}\");\n \t\t\tsymbolTable.closeScope();\n \t\t\treturn new ASTUnaryNode(\"codeBlock\",{\"scope\":scope,\"code\":code,\"begin\":begin,\"end\":end});\n \t\t}\n \t\t\n//\t\tStatement\t:= If | For | Do | While | Switch | JavaScript | (Return | Expr | Assignment) \";\"\n \t\tfunction Statement() {\n \t\t\tdebugMsg(\"ProgramParser : Statement\");\n \t\t\tvar ast;\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"if\"\t \t\t: ast=If(); \n\t \t\t\tbreak;\n \t\t\t\tcase \"do\"\t \t\t: ast=Do(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"while\" \t\t: ast=While(); \t\t\n \t\t\t\tbreak;\n \t\t\t\tcase \"for\"\t\t\t: ast=For();\n \t\t\t\tbreak;\n \t\t\t\tcase \"switch\"\t\t: ast=Switch(); \t\n \t\t\t\tbreak;\n \t\t\t\tcase \"javascript\"\t: ast=JavaScript(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"return\"\t\t: ast=Return(); \n \t\t\t\t\t\t\t\t\t\t check(\";\");\n \t\t\t\tbreak;\n \t\t\t\tdefault\t\t\t\t: ast=EPStatement(); \n \t\t\t\t\t check(\";\");\n \t\t\t}\n \t\t\tast.line=line;\n \t\t\tast.comment=lexer.getComment();\n \t\t\tlexer.clearComment(); \t\t\t\n \t\t\treturn ast;\t\n \t\t}\n \t\t\n//\t\tIf := \"if\" \"(\" Expr \")\" CodeBlock [\"else\" CodeBlock]\n//\t\tAST : \"if\": l: cond:Expr, code:codeBlock, elseBlock:(null | codeBlock)\n \t\tfunction If() {\n \t\t\tdebugMsg(\"ProgramParser : If\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tvar elseCode;\n \t\t\tif (test(\"else\")) {\n \t\t\t\tlexer.next();\n \t\t\t\telseCode=CodeBlock();\n \t\t\t}\n \t\t\treturn new ASTUnaryNode(\"if\",{\"cond\":expr,\"code\":code,\"elseBlock\":elseCode});\n \t\t}\n \t\t\n// \t\tDo := \"do\" CodeBlock \"while\" \"(\" Expr \")\" \n//\t\tAST: \"do\": l:Expr, r:CodeBlock \n \t\tfunction Do() {\t\n \t\t\tdebugMsg(\"ProgramParser : Do\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tcheck(\"while\");\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\t\n \t\t\tcheck(\";\");\n\n \t\t\treturn new ASTBinaryNode(\"do\",expr,code);\n \t\t}\n \t\t\n// \t\tWhile := \"while\" \"(\" Expr \")\" \"{\" {Statement} \"}\" \n//\t\tAST: \"while\": l:Expr, r:codeBlock\n \t\tfunction While(){ \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : While\");\n \t\t\t\n \t\t\t//if do is allowed, but while isn't allowed gotta check keyword in parser\n \t\t\tif (preventWhile) error.reservedWord(\"while\",lexer.current.line);\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code = CodeBlock();\n \t\t\t\t \t\t\t\n \t\t\treturn new ASTBinaryNode(\"while\",expr,code);\n \t\t}\n \t\t\n//\t\tFor := \"for\" \"(\"(\"each\" Ident \"in\" Ident | Ident Assignment \";\" Expr \";\" Assignment )\")\"CodeBlock\n//\t\tAST: \"foreach\": l: elem:Ident, array:Ident, code:CodeBlock \n//\t\tAST: \"for\": l: init:Assignment, cond:Expr,inc:Assignment, code:CodeBlock\n \t\tfunction For() { \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : For\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tif (test(\"each\")) {\n \t\t\t\tlexer.next();\n \t\t\t\tvar elem=IdentSequence();\n \t\t\t\tcheck(\"in\");\n \t\t\t\tvar arr=IdentSequence();\n \t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\t\n \t\t\t\tvar code=CodeBlock();\n \t\t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"foreach\",{\"elem\":elem,\"array\":arr,\"code\":code});\n \t\t\t\t\n \t\t\t} else {\n \t\t\t\tvar init=Assignment();\n \t\t\t\tif (!init) error.assignmentExpected();\n \t\t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\t\n \t\t\t\tvar cond=Expr();\n \t\t\t\n \t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\n \t\t\t\tvar increment=Assignment();\n \t\t\t\tif (!increment) error.assignmentExpected();\n \t\t\t \n \t\t\t\tcheck(\")\");\n \t\t\t\tvar code=CodeBlock();\t\n \t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"for\",{\"init\":init,\"cond\":cond,\"inc\":increment,\"code\":code});\n \t\t\t}\t\n \t\t}\n \t\t\n//\t\tSwitch := \"switch\" \"(\" Ident \")\" \"{\" {Option} [\"default\" \":\" CodeBlock] \"}\"\t\n// AST: \"switch\" : l \"ident\":IdentSequence,option:[0..x]{Option}, default:CodeBlock\n \t\tfunction Switch() {\t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Switch\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) error.identifierExpected();\n \t\t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar option=[];\n \t\t\tvar current=true;\n \t\t\tfor (var i=0;current && !eof();i++) {\n \t\t\t\tcurrent=Option();\n \t\t\t\tif (current) {\n \t\t\t\t\toption[i]=current;\n \t\t\t\t}\n \t\t\t}\n \t\t\tcheck(\"default\");\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar defBlock=CodeBlock();\n \t\t \t\t\t\n \t\t\tcheck(\"}\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"switch\", {\"ident\":ident,\"option\":option,\"defBlock\":defBlock});\n \t\t}\n \t\t\n//\t\tOption := \"case\" Expr {\",\" Expr} \":\" CodeBlock\n// AST: \"case\" : l: [0..x]{Expr}, r:CodeBlock\n \t\tfunction Option() {\n \t\t\tif (!test(\"case\")) return false;\n \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Option\");\n \t\t\t\n \t\t\tvar exprList=[];\n \t\t\tvar i=0;\n \t\t\tdo {\n \t\t\t\tlexer.next();\n \t\t\t\t\n \t\t\t\texprList[i]=Expr();\n \t\t\t\ti++; \n \t\t\t\t\n \t\t\t} while (test(\",\") && !eof());\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"case\",exprList,code);\n \t\t}\n \t\t\n// JavaScript := \"javascript\" {Letter | Digit | Symbol} \"javascript\"\n//\t\tAST: \"javascript\": l: String(JavascriptCode)\n \t\tfunction JavaScript() {\n \t\t\tdebugMsg(\"ProgramParser : JavaScript\");\n\t\t\tcheck(\"javascript\");\n\t\t\tcheck(\"(\")\n\t\t\tvar param=[];\n\t\t\tvar p=Ident(false);\n\t\t\tif (p) {\n\t\t\t\tparam.push(p)\n\t\t\t\twhile (test(\",\") && !eof()) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\tparam.push(Ident(true));\n\t\t\t\t}\t\n\t\t\t}\n \t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\tvar js=lexer.current.content;\n \t\t\tcheckType(\"javascript\");\n \t\t\t\t\t\t\n \t\t\treturn new ASTUnaryNode(\"javascript\",{\"param\":param,\"js\":js});\n \t\t}\n \t\t\n// \t\tReturn := \"return\" [Expr] \n//\t\tAST: \"return\" : [\"expr\": Expr] \n \t\tfunction Return() {\n \t\t\tdebugMsg(\"ProgramParser : Return\");\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tvar ast=new ASTUnaryNode(\"return\",expr);\n \t\t\tast.line=line;\n \t\t\treturn ast;\n \t\t}\n\t}",
"visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function helloWorld() {\n const hello = 'Hello';\n const world = 'World';\n\n return hello + world;\n}",
"function main() {\n try {\n // implement(access.Sample)(util.Example);\n let exp = util.Example(45);\n console.log(exp);\n } catch (error) {\n console.log(error.message);\n }\n}",
"constructor(\n /**\n The language object.\n */\n language,\n /**\n An optional set of supporting extensions. When nesting a\n language in another language, the outer language is encouraged\n to include the supporting extensions for its inner languages\n in its own set of support extensions.\n */\n support = []\n ) {\n this.language = language\n this.support = support\n this.extension = [language, support]\n }",
"static of(spec) {\n let { load, support } = spec\n if (!load) {\n if (!support)\n throw new RangeError(\n \"Must pass either 'load' or 'support' to LanguageDescription.of\"\n )\n load = () => Promise.resolve(support)\n }\n return new LanguageDescription(\n spec.name,\n (spec.alias || []).concat(spec.name).map((s) => s.toLowerCase()),\n spec.extensions || [],\n spec.filename,\n load,\n support\n )\n }",
"function CodeLocationObj() {\r\n\r\n var module = \"\"\r\n var func = \"\"\r\n var step = \"\";\r\n var box = \"\";\r\n\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParsersingle_table_insert. | visitSingle_table_insert(ctx) {
return this.visitChildren(ctx);
} | [
"visitMulti_table_insert(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function insertStatement1( machine )\n {\n query = machine.popToken();\n tablename = machine.popToken();\n machine.checkToken(\"into\");\n machine.checkToken(\"insert\");\n machine.pushToken( new insertStatement(tablename.identifier, query) );\n }",
"visitInsert_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitInsert_into_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitCreate_table(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitMerge_insert_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function parseTable() {\n var name = t.identifier(getUniqueName(\"table\"));\n var limit = t.limit(0);\n var elemIndices = [];\n var elemType = \"anyfunc\";\n\n if (token.type === _tokenizer.tokens.string || token.type === _tokenizer.tokens.identifier) {\n name = identifierFromToken(token);\n eatToken();\n } else {\n name = t.withRaw(name, \"\"); // preserve anonymous\n }\n\n while (token.type !== _tokenizer.tokens.closeParen) {\n /**\n * Maybe export\n */\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.elem)) {\n eatToken(); // (\n\n eatToken(); // elem\n\n while (token.type === _tokenizer.tokens.identifier) {\n elemIndices.push(t.identifier(token.value));\n eatToken();\n }\n\n eatTokenOfType(_tokenizer.tokens.closeParen);\n } else if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.export)) {\n eatToken(); // (\n\n eatToken(); // export\n\n if (token.type !== _tokenizer.tokens.string) {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Expected string in export\" + \", given \" + tokenToString(token));\n }();\n }\n\n var exportName = token.value;\n eatToken();\n state.registredExportedElements.push({\n exportType: \"Table\",\n name: exportName,\n id: name\n });\n eatTokenOfType(_tokenizer.tokens.closeParen);\n } else if (isKeyword(token, _tokenizer.keywords.anyfunc)) {\n // It's the default value, we can ignore it\n eatToken(); // anyfunc\n } else if (token.type === _tokenizer.tokens.number) {\n /**\n * Table type\n */\n var min = parseInt(token.value);\n eatToken();\n\n if (token.type === _tokenizer.tokens.number) {\n var max = parseInt(token.value);\n eatToken();\n limit = t.limit(min, max);\n } else {\n limit = t.limit(min);\n }\n\n eatToken();\n } else {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected token\" + \", given \" + tokenToString(token));\n }();\n }\n }\n\n if (elemIndices.length > 0) {\n return t.table(elemType, limit, name, elemIndices);\n } else {\n return t.table(elemType, limit, name);\n }\n }",
"function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}",
"function createStatement1( machine )\n {\n machine.checkToken(\")\");\n columns = machine.popToken();\n machine.checkToken(\"(\");\n alias = machine.popToken().identifier;\n machine.checkToken(\"table\");\n machine.checkToken(\"create\");\n machine.pushToken( new createStatement( constructor_table, alias, columns ) );\n }",
"function createTree(){\n var colCount=0;\n head.find(selectors.row).first().find(selectors.th).each(function () {\n var c = parseInt($(this).attr(attributes.span));\n colCount += !c ? 1 : c;\n });\n\n root = new Node(undefined,colCount,0);\n var headerRows = head.find(selectors.row);\n var currParents = [root];\n // Iteration through each row\n //-------------------------------\n for ( var i = 0; i < headerRows.length; i++) {\n\n var newParents=[];\n var currentOffset = 0;\n var ths = $( headerRows[i] ).find(selectors.th);\n\n // Iterating through each th inside a row\n //---------------------------------------\n for ( var j = 0 ; j < ths.length ; j++ ){\n var colspan = $(ths[j]).attr(attributes.span);\n colspan = parseInt( !colspan ? '1' : colspan);\n var newChild = 0;\n\n // Checking which parent is the newChild parent (?)\n // ------------------------------------------------\n for( var k = 0 ; k < currParents.length ; k++){\n if ( currentOffset < currParents[k].colspanOffset + currParents[k].colspan ){\n var newChildId = 'cm-'+i+'-'+j+'-'+k ;\n $(ths[j]).addClass(currParents[k].classes);\n $(ths[j]).addClass(currParents[k].id);\n $(ths[j]).attr(attributes.id, newChildId);\n \n newChild = new Node( currParents[k], colspan, currentOffset, newChildId );\n tableNodes[newChild.id] = newChild;\n currParents[k].addChild( newChild );\n break;\n }\n }\n newParents.push(newChild);\n currentOffset += colspan;\n }\n currParents = newParents;\n }\n\n var thCursor = 0;\n var tdCursor = 0;\n var rows = body.find(selectors.row);\n var tds = body.find(selectors.td);\n /* Searches which 'parent' this cell belongs to by \n * using the values of the colspan */\n head.find(selectors.row).last().find(selectors.th).each(function () {\n var thNode = tableNodes[$(this).attr(attributes.id)];\n thCursor += thNode.colspan;\n while(tdCursor < thCursor) {\n rows.each(function () {\n $(this).children().eq(tdCursor).addClass(thNode.classes + ' ' + thNode.id);\n });\n tdCursor += $(tds[tdCursor]).attr(attributes.span) ? $(tds[tdCursor]).attr(attributes.span) : 1;\n }\n });\n\n /* Transverses the tree to collect its leaf nodes */\n var leafs=[];\n for ( var node in tableNodes){\n if ( tableNodes[node].children.length === 0){\n leafs.push(tableNodes[node]);\n }\n }\n /* Connects the last row of the header (the 'leafs') to the first row of the body */\n var firstRow = body.find(selectors.row).first();\n for ( var leaf = 0 ; leaf < leafs.length ; leaf++){\n firstRow.find('.' + leafs[leaf].id ).each(function(index){\n var newNode = new Node( leafs[leaf] , 1 , 0, leafs[leaf].id + '--' + leaf + '--' + index);\n newNode.DOMelement = $(this);\n leafs[leaf].addChild(newNode);\n tableNodes[newNode.id] = newNode;\n newNode.DOMelement.attr(attributes.id, newNode.id);\n });\n }\n }",
"visitRelational_table(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function constructFromDatabase(table_name, callback) {\n\t// pull tree data from db\n\tcon.query('SELECT * FROM ' + table_name + ';', function(err, result) {\n\t\tif (err) throw err;\n\t\tvar idToNode = new Array();\t// temp link ids to node objects\n\t\tidToNode[0] = global.stableTree.root;\n\n\t\t// iterate through data in triplets (data, probability, parent id)\n\t\tfor (var i = 0; i < result.length; i++) {\n\t\t\tvar n = new Node(result[i].data, parseFloat(result[i].probability));\n\t\t\tvar parent = idToNode[result[i].uid_parent];\t// get parent\n\t\t\tidToNode[result[i].uid] = n;\n\t\t\tparent.children.push(n);\n\t\t}\n\n\t\tcallback();\n\t});\n}",
"visitConditional_insert_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitComment_on_table(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function table_put(dsid, tb) {\n const fixid = a => a ? a.map((row, x) => ({ ...row, id: x+1, })) : [];\n\n const newtb = (tb.id) \n ? topStack().tables.map(t => t.id === tb.id ? { ...t, ...tb } : t)\n : [ ...topStack().tables, { \n id: topStack().tables.length + 1,\n //rows: [], \n datasetid: dsid,\n ...tb,\n rows: fixid(tb.rows),\n fields: fixid(tb.fields),\n } ];\n // validate here\n pushNext({ \n ...topStack(), \n tables: newtb, \n });\n}",
"visitTablespace(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function loadSour(conn, item) {\n var sid = cleanPointer(item.pointer);\n var sql_sour = 'INSERT INTO sour VALUES (?, ?, ?, ?, ?)';\n\n var rec = [sid, null, null, null, []];\n\n for (i in item.tree) {\n switch (item.tree[i].tag) {\n case 'TITL':\n rec[1] = item.tree[i].data;\n break;\n case 'AUTH':\n rec[2] = item.tree[i].data;\n break;\n case 'PUBL':\n rec[3] = item.tree[i].data;\n if (item.tree[i].tree.length > 0) {\n for (j in item.tree[i].tree) {\n if (item.tree[i].tree[j].tag == 'CONC') {\n rec[3] += \"\\n\" + item.tree[i].tree[j].data;\n }\n else {\n console.log('WARNING: unknown tag (' + item.tree[i].tree[j].tag + ')');\n console.log(JSON.stringify(item, null, 2));\n }\n }\n }\n break;\n case 'REPO':\n if (item.tree[i].tree[0].tag == 'NOTE') {\n rec[4].push('NOTE: ' + item.tree[i].tree[0].data);\n }\n else if (item.tree[i].tree[0].tag == 'CALN') {\n rec[4].push('Medium: ' + item.tree[i].tree[0].data);\n }\n else {\n console.log('WARNING: unknown tag (' + item.tree[i].tree[0].tag + ')');\n console.log(JSON.stringify(item, null, 2));\n }\n break;\n }\n }\n\n if (rec[4].length > 0) {\n rec[4] = rec[4].join(\"\\n\");\n }\n else {\n rec[4] = null;\n }\n\n conn.query(sql_sour, rec);\n}",
"function insert(model, callback) {\n\n logger.logInfo('Inserting row in table : ' + model.tableName);\n\n // build query\n var query = buildInsertStatement(model.tableName, model.fields);\n\n pg.connect(db_conString, function(errConnect, client, done) {\n\n if (errConnect) {\n logger.logError('Error while connecting to Database.');\n logger.logError('Error : ' + errConnect);\n callback(errConnect);\n return;\n }\n\n // BEGIN Statement\n logger.logInfo('BEGIN Transaction');\n client.query('BEGIN', function(errBegin) {\n\n if (errBegin) {\n logger.logError('BEGIN : An error occurred while beginning transaction');\n logger.logError('Error : ' + errBegin);\n performRollback(client, done);\n callback(errBegin);\n return;\n }\n\n // This function is a sort of insurance that the passed function will be executed on the next VM internal loop,\n // which means it will be the very first executed lines of code.\n // @see http://nodejs.org/api/all.html#all_process_nexttick_callback for more\n process.nextTick(function() {\n\n // First Insert Statement\n logger.logDebug('INSERT query : ' + query);\n client.query(query, objectToArray(model.fields), function(errQuery, insertedResult) {\n\n // err treatment.\n if (errQuery) {\n logger.logError('INSERT : An error occurred while inserting row : ' + query);\n logger.logError('Error : ' + errQuery);\n performRollback(client, done);\n callback(errQuery);\n return;\n }\n\n logger.logInfo('INSERT o2ms query');\n performOneToManyInserts(client, insertedResult.rows[0].id, model, function(errO2M) {\n\n if (errO2M) {\n logger.logError('INSERT : An error occurred while inserting o2ms rows.');\n logger.logError('Error : ' + errO2M);\n performRollback(client, done);\n callback(errO2M);\n return;\n }\n\n logger.logInfo('INSERT m2ms query');\n performManyToManyInserts(client, insertedResult.rows[0].id, model, function(errM2M) {\n\n if (errM2M) {\n logger.logError('INSERT : An error occurred while inserting m2ms rows.');\n logger.logError('Error : ' + errM2M);\n performRollback(client, done);\n callback(errM2M);\n return;\n }\n\n // COMMIT the transaction\n logger.logInfo('COMMIT Transaction');\n client.query('COMMIT', function() {\n\n done();\n\n // Get the inserted Element with all its objects\n find(model, { id : insertedResult.rows[0].id }, function(errSelect, element) {\n\n if (errSelect) {\n logger.logError('SELECT : An error occurred while Re finding the inserted rows.');\n logger.logError('Error : ' + errSelect);\n }\n\n callback(errSelect, element[0]);\n });\n });\n });\n });\n });\n });\n });\n });\n}",
"function _insertData(conn) {\r\n return function (tableName1, tableName2, tableName3, header, data, nameTranslationTable, callback) {\r\n /*var convertedData = data.map(function (dataLine) {\r\n var convertedDataLine = Object.keys(dataLine).map(function (key) {\r\n var value = dataLine[key];\r\n return value;\r\n });\r\n\r\n return convertedDataLine.join(', ');\r\n });\r\n\r\n var translatedHeader = header;\r\n\r\n if (nameTranslationTable)\r\n translatedHeader = header.map(function (headerEl) {\r\n return nameTranslationTable[headerEl];\r\n });\r\n var query = `insert into ${tableName3} (${translatedHeader.join(', ')}) values (${convertedData.join('), (')})`;\r\n */\r\n var query = `INSERT INTO ${tableName3} (SELECT ${tableName1}.*, \r\n ${tableName2}.REPAIR_TYPE_DETAILS, ${tableName2}.DIG_COMPLETION_YEAR\r\n FROM ${tableName1} FULL OUTER JOIN ${tableName2} ON \r\n ${tableName1}.DISTANCE__M_= ${tableName2}.ILI_CHAINAGE \r\n ORDER BY ${tableName1}.DISTANCE__M_)`;\r\n \r\n console.log(\"Executing SQL query: _insertData()\");\r\n conn.query(query, function (err, queryData) {\r\n if (err) {\r\n console.log(err);\r\n return callback(err);\r\n }\r\n return callback();\r\n });\r\n };\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Foursquare API and append functions Call function foursquareSearch() to execute, assing searchTerm and location | function foursquareSearch(food, longitudeLatitude) { // first ajax call
var queryURL = "https://api.foursquare.com/v2/venues/search";
$.ajax({
url: queryURL,
data: {
client_id: "UYCPKGBHUK5DSQSOGFBATS2015CFIZM1CELCN4AIYPT1LEBH",
client_secret: "EBLDOOVW2FIZBGC0PH3M2NATAUCABKHWRVIC3YFRW1SOTKKF",
ll: longitudeLatitude,
query: food,
v: "20180206",
limit: 3
},
cache: false,
type: "GET",
success: function(response) {
console.log(response);
getImages(response);
appendFourSquare(response);
},
error: function(xhr) {
console.log(xhr);
}
});
} | [
"function callNearBySearchAPI() {\n //\n city = new google.maps.LatLng(coordinates.lat, coordinates.long);\n map = new google.maps.Map(document.getElementById(\"map\"), {\n center: city,\n zoom: 15,\n });\n //\n request = {\n location: city,\n radius: \"5000\", // meters\n type: [\"restaurant\"],\n // openNow: true,\n fields: [\n \"name\",\n \"business_status\",\n \"icon\",\n \"types\",\n \"rating\",\n \"reviews\",\n \"formatted_phone_number\",\n \"address_component\",\n \"opening_hours\",\n \"geometry\",\n \"vicinity\",\n \"website\",\n \"url\",\n \"address_components\",\n \"price_level\",\n \"reviews\",\n ],\n };\n //\n service = new google.maps.places.PlacesService(map);\n service.nearbySearch(request, getGooglePlacesData);\n //\n}",
"getVenues() {\n const endpoint = \"https://api.foursquare.com/v2/venues/explore?\"\n const client_id = \"FDAMFVN2CLVPRFZSHTJCWLYP34V0FZ1U2N0EU3TO4QUDMBHZ\"\n const client_secret = \"1I1TBKGC1CI5Z5LMTCJJRUCFLK5AWPANS4QHHEGMDQXEMJWY\"\n const near = \"Hartford\"\n const query = \"live music\"\n const limit = 12\n fetch(`${endpoint}v=20180323&client_id=${client_id}&client_secret=${client_secret}&near=${near}&query=${query}&limit=${limit}`)\n .then(response => response.json())\n .then(data => {\n this.setState({\n venues: data.response.groups[0].items\n },this.renderMap()) // set renderMap() as callback function\n })\n .catch(error => {\n window.alert(\"Sorry!!! Something went wrong. This page didn't load Foursquare location data correctly. See the JavaScript console for technical details.\")\n })\n }",
"function fetchrestaurants() {\n var data;\n $.ajax({\n url: 'https://api.foursquare.com/v2/venues/search',\n dataType: 'json',\n data: 'client_id=LEX5UAPSLDFGAG0CAARCTPRC4KUQ0LZ1GZSB4JE0GSSGQW3A&client_secret=0QUGSWLF4DJG5TM2KO3YCUXUB2IJUCHDNSZC0FUUA3PKV0MY&v=20170101&ll=28.613939,77.209021&query=restaurant',\n async: true,\n }).done(function (response) {\n data = response.response.venues;\n data.forEach(function (restaurant) {\n var foursquare = new Foursquare(restaurant, map);\n self.restaurantList.push(foursquare);\n });\n self.restaurantList().forEach(function (restaurant) {\n if (restaurant.map_location()) {\n google.maps.event.addListener(restaurant.marker, 'click', function () {\n self.selectrestaurant(restaurant);\n });\n }\n });\n }).fail(function (response, status, error) {\n\t\t\tself.queryResult('restaurant\\'s could not load...');\n });\n }",
"function searchAPI(recipe_search, food_search) {\n $('p.search_error').empty();\n let search_params = 'default';\n if (recipe_search) {\n //use the recipe search\n search_params = recipe_search;\n } else if (food_search) {\n //Or, use the food search\n search_params = food_search;\n }\n var recipeData = $(this).attr(\"data-name\");\n var ourAPIid = \"4dced6d2\";\n var ourAPIkey = \"1a7e0fea32a0ad94892aaeb51b858b48\";\n\n var queryURL = \"https://api.yummly.com/v1/api/recipes\" +\n \"?_app_id=\" + ourAPIid +\n \"&_app_key=\" + ourAPIkey +\n \"&q=\" + search_params;\n\n // Checks if \"use your diets and allergies\" box is checked and creats an updated queryURL\n if ($(\"#search-restrictions\").is(':checked')) {\n queryURL = queryURL + searchCriteria.queryParams;\n }\n\n $.ajax({\n type: 'GET',\n dataType: 'json',\n url: queryURL,\n }).then(function (result) {\n let results_length = result.matches.length; //saves results as a variable\n\n $('div.column_results').append(`Search Results (${results_length})`);\n result.matches.forEach(showFood);\n });\n}",
"function ApiFlickr() {\n\n // Begin public interface methods\n /**\n * unlocalizedSearch - Method used for performing searches without specifying location.\n * @param {Function} callback - A one-parameter function to call with the response from the server.\n * @param {string} searchString - String used to search image titles, descriptions, and keywords.\n * @param {Date[]|string[]} timePeriod - Filter by range of dates. One date implies minimum date to current. Empty array ignores dates.\n */\n this.unlocalizedSearch = function (callback, searchString, timePeriod) {\n var dataObject = new UnlocalizedData(searchString, timePeriod);\n flickrPhotoSearch(dataObject, callback);\n };\n\n /**\n * radiusSearch - Method used for performing searches which return the closest results to a given location.\n * @param {Function} callback - A one-parameter function to call with the response from the server.\n * @param {string} searchString - String used to search image titles, descriptions, and keywords.\n * @param {Date[]|string[]} timePeriod - Filter by range of dates. One date implies minimum date to current. Empty array ignores dates.\n * @param {number} longitude - Longitude of location to search around.\n * @param {number} latitude - Latitude of location to search around.\n * @param {number} radiusInMiles - Maximum radius to include in search.\n */\n this.radiusSearch = function(callback, searchString, timePeriod, longitude, latitude, radiusInMiles){\n var dataObject = new RadialData(searchString, timePeriod, [longitude, latitude, radiusInMiles]);\n flickrPhotoSearch(dataObject, callback);\n };\n\n /**\n * boundingBoxSearch - Method used for performing searches limited by the given location window.\n * @param {Function} callback - A one-parameter function to call with the response from the server.\n * @param {string} searchString - String used to search image titles, descriptions, and keywords.\n * @param {Date[]|string[]} timePeriod - Filter by range of dates. One date implies minimum date to current. Empty array ignores dates.\n * @param {number} minLongitude - Minimum longitude to include.\n * @param {number} minLatitude - Minimum latitude to include.\n * @param {number} maxLongitude - Maximum longitude to include.\n * @param {number} maxLatitude - Maximum latitude to include.\n */\n this.boundingBoxSearch = function(callback, searchString, timePeriod, minLongitude, minLatitude, maxLongitude, maxLatitude){\n var dataObject = new BoundingBoxData(searchString, timePeriod, [minLongitude, minLatitude, maxLongitude, maxLatitude]);\n flickrPhotoSearch(dataObject, callback);\n };\n\n /**\n * getImageUrlBySize - Returns the static url for the given image of the given size.\n * @param {Object} photoObject - Object containing a single image object.\n * @param {string|number} size - Character suffix for determining size of image in returned object. See https://www.flickr.com/services/api/misc.urls.html for list of suffixes.\n * If a number is used, the size of the image is taken so that the largest dimension is at least that number of pixels.\n * @returns {string}\n */\n this.getImageUrlBySize = function(photoObject, size){\n var photoUrl = \"https://farm\" + photoObject.farm + \".staticflickr.com/\" + photoObject.server + \"/\" + photoObject.id + \"_\" + photoObject.secret;\n if (typeof size == \"string\") {\n photoUrl += \"_\" + size;\n } else if (typeof size == \"number\") {\n if (size <= 75) {\n photoUrl += \"_s\";\n } else if (size <= 150) {\n photoUrl += \"_q\";\n } else if (size <= 240) {\n photoUrl += \"_m\";\n } else if (size <= 320) {\n photoUrl += \"_n\";\n } else if (size <= 500) {\n photoUrl += \"_-\";\n } else if (size <= 640) {\n photoUrl += \"_z\";\n } else if (size <= 800) {\n photoUrl += \"_c\";\n } else if (size <= 1024) {\n photoUrl += \"_b\";\n } else if (size <= 1600) {\n photoUrl += \"_h\";\n } else if (size <= 2048) {\n photoUrl += \"_k\";\n }\n }\n photoUrl += \".jpg\";\n return photoUrl;\n };\n // End public interface methods\n\n /**\n * flickrPhotoSearch - Private method for initiating AJAX calls to Flickr API, modified to include the static url.\n * @param {Object} dataObject - Object containing all data keys to be passed to Flickr API.\n * @param {Function} callback - A one-parameter function to call with the response from the server.\n */\n function flickrPhotoSearch(dataObject, callback) {\n $.ajax({\n url: \"https://api.flickr.com/services/rest\",\n method: \"POST\",\n dataType: \"JSON\",\n data: dataObject,\n success: function (response) {\n callback(response.photos.photo);\n },\n fail: function (response) {\n callback(response);\n }\n });\n }\n\n /**\n * FlickrData - Base constructor for data object sent via Flickr API call.\n * @param {string} searchText - Search string\n * @param {Date[]} dateRange - Date range used to limit search. One date acts as minimum date. Empty array ignores date filter.\n * @constructor\n */\n function FlickrData(searchText, dateRange) {\n this.method = \"flickr.photos.search\";\n this.api_key = \"4291af049e7b51ff411bc39565109ce6\";\n this.format = \"json\";\n this.nojsoncallback = 1;\n this.text = searchText;\n if (Array.isArray(dateRange) && dateRange.length >= 1) {\n this.min_taken_date = dateRange[0];\n if (dateRange.length >= 2) {\n this.max_taken_date = dateRange[1];\n }\n }\n this.has_geo = 1;\n this.per_page = 30;\n this.content_type = 1;\n this.extras = \"geo,url_sq,url_t,url_s,url_q,url_m,url_n,url_z,url_c,url_l,url_o\";\n }\n\n /**\n * UnlocalizedData - Constructor based upon FlickrData, used to search without specifying location.\n * @param {string} searchText - Search string\n * @param {Date[]} dateRange - Date range used to limit search. One date acts as minimum date. Empty array ignores date filter.\n * @constructor\n */\n function UnlocalizedData (searchText, dateRange) {\n FlickrData.call(this, searchText, dateRange);\n this.sort = \"relevance\";\n }\n\n /**\n * RadialData - Constructor based upon FlickrData, used to search for closest results to a given location.\n * @param {string} searchText - Search string\n * @param {Date[]} dateRange - Date range used to limit search. One date acts as minimum date. Empty array ignores date filter.\n * @param {Array} location - Array containing longitude, latitude, and radius in miles.\n * @constructor\n */\n function RadialData (searchText, dateRange, location) {\n FlickrData.call(this, searchText, dateRange);\n this.lon = location[0];\n this.lat = location[1];\n this.radius = location[2];\n this.radius_units = \"mi\";\n this.per_page = 15;\n }\n\n /**\n * BoundingBoxData - Constructor based upon FlickrData, used to search for results spread evenly in a bounded geographical area.\n * @param {string} searchText - Search string\n * @param {Date[]} dateRange - Date range used to limit search. One date acts as minimum date. Empty array ignores date filter.\n * @param {number[]|string[]} location - Array containing bounding box information as [min-long, min-lat, max-long, max-lat].\n * @constructor\n */\n function BoundingBoxData (searchText, dateRange, location) {\n FlickrData.call(this, searchText, dateRange);\n this.bbox = location.join(\",\");\n this.sort = \"relevance\";\n }\n}",
"function performSearch(srch, srchType, btnIndex){\n //Make the inputs into the URL and call the API\n //Reset variables\n currentFoodResults = [[],[],[],[],[]];\n currentWineResults = [[],[],[],[],[],[],[]];\n varietalInformation = null;\n foodRunFlag = false;\n wineRunFlag = false;\n numResults = 5;\n maxResults = 0;\n\n if(buttonTrigger === false){//Make API call if new search\n\n if(srchType === \"wine\"){ //If searching for a wine\n foodUrl = makeSearchIntoFoodURL(matchFoodToWine(userSearch, varietals)); //find food that pairs for the search\n wineUrl = makeSearchIntoWineURL(userSearch);\n varietalInformation = varietalInfo[userSearch];\n } else { //Otherwise\n foodUrl = makeSearchIntoFoodURL(userSearch); //assume search was for food\n wineUrl = makeSearchIntoWineURL(matchFoodToWine(userSearch, ingredients)); //Get a wine varietal to search\n }\n\n getFoods(foodUrl, extractFoodResults);\n getWines(wineUrl, extractWineResults);\n\n } else if(buttonTrigger === true) {//Skip the API call and reference the cached result\n extractFoodResults(foodResults[btnIndex][1], btnIndex);\n extractWineResults(wineResults[btnIndex][1], btnIndex);\n }\n }",
"function getLocationsData() {\n middle = getMiddle();\n setPointOnMap(middle.lat, middle.long, key);\n var radiusInMeters = radius * 1609.34;\n\n $('.poweredBy').fadeIn();\n\n // create accessor\n var accessor = {\n consumerSecret: auth.consumerSecret,\n tokenSecret: auth.accessTokenSecret\n };\n\n // push params\n var parameters = [];\n parameters.push(['category_filter', category]);\n parameters.push(['sort', 1]);\n parameters.push(['limit', 10]);\n parameters.push(['radius_filter', radiusInMeters]);\n parameters.push(['ll', middle.lat + ',' + middle.long]);\n parameters.push(['oauth_consumer_key', auth.consumerKey]);\n parameters.push(['oauth_consumer_secret', auth.consumerSecret]);\n parameters.push(['oauth_token', auth.accessToken]);\n parameters.push(['oauth_signature_method', 'HMAC-SHA1']);\n\n var message = {\n 'action': 'http://api.yelp.com/v2/search',\n 'method': 'GET',\n 'parameters': parameters\n };\n\n OAuth.setTimestampAndNonce(message);\n OAuth.SignatureMethod.sign(message, accessor);\n\n var parameterMap = OAuth.getParameterMap(message.parameters);\n parameterMap.oauth_signature = OAuth.percentEncode(parameterMap.oauth_signature);\n\n var qs = '';\n\n for (var p in parameterMap) {\n qs += p + '=' + parameterMap[p] + '&';\n }\n\n var url = message.action + '?' + qs;\n\n\n WinJS.xhr({\n url: url\n }).then(success, failure);\n\n $('#searching').show(); // hide progress\n\n // handles a succesful yelp response\n function success(result) {\n\n var response = window.JSON.parse(result.responseText);\n\n $('#searching').hide(); // hide progress\n\n if (response.businesses.length == 0) { // handle no results error\n $('.error').show();\n\n if (radius == 25) {\n $('.error .noresultsLargest').show();\n }\n else {\n $('.error .noresults').show();\n }\n\n }\n\n var businesses = response.businesses;\n\n var list = new WinJS.Binding.List(); // create a new list to hold items\n\n response.businesses.forEach(function (item) {\n\n var cleaned = [];\n cleaned['name'] = item.name;\n\n var imgurl = item.image_url;\n\n if (imgurl == null || imgurl == '') {\n imgurl = '/images/no-image.png';\n }\n\n cleaned['image_url'] = imgurl;\n\n var address = '';\n var url_address = '';\n\n for (var x = 0; x < item.location.display_address.length; x++) {\n if (x > 0) {\n address += '<br>';\n url_address += ' ';\n }\n address = address + item.location.display_address[x];\n url_address = url_address + item.location.display_address[x];\n }\n\n cleaned['display_address'] = address;\n cleaned['url_address'] = encodeURIComponent(url_address);\n cleaned['city'] = item.location.city;\n cleaned['state'] = item.location.state_code;\n cleaned['city_state'] = item.location.city + ', ' + item.location.state_code;\n cleaned['cross_streets'] = item.location.cross_streets;\n cleaned['latitude'] = item.location.coordinate.latitude;\n cleaned['longitude'] = item.location.coordinate.longitude;\n cleaned['rating_img_url'] = item.rating_img_url;\n cleaned['display_phone'] = item.display_phone;\n cleaned['review_count'] = item.review_count;\n cleaned['url'] = item.url;\n cleaned['distance'] = (item.distance / 1609.34).toFixed(2) + ' miles away from the middle';\n\n list.push(cleaned);\n });\n\n // Set up the ListView\n var listView = el.querySelector(\".itemlist\").winControl;\n ui.setOptions(listView, {\n itemDataSource: list.dataSource,\n itemTemplate: el.querySelector(\".itemtemplate\"),\n layout: new ui.ListLayout(),\n oniteminvoked: itemInvoked\n });\n\n\n function itemInvoked(e) {\n\n var i = e.detail.itemIndex;\n\n // win-item\n var item = $(listView.element).find('.win-item')[i];\n\n var latitude = $(item).find('.lat').val();\n var longitude = $(item).find('.long').val();\n var title = $(item).find('.title').val();\n var address = jQuery.trim($(item).find('.address').val());\n var city_state = jQuery.trim($(item).find('.city_state').val());\n var url_address = jQuery.trim($(item).find('.url_address').val());\n var url = $(item).find('.url').val();\n var photo = $(item).find('.photo').val();\n var ratingimage = $(item).find('.ratingimage').val();\n var reviews = $(item).find('.reviews').val();\n var phone = $(item).find('.phone').val();\n\n current = {\n latitude: latitude,\n longitude: longitude,\n title: title,\n address: address,\n url_address: url_address,\n city_state: city_state,\n url: url,\n photo: photo,\n ratingimage: ratingimage,\n reviews: reviews,\n phone: phone,\n key: key\n };\n\n showCurrentInfoBox();\n }\n\n }\n\n // handles a failed yelp response\n function failure(result) {\n debug(result.responseText);\n }\n }",
"function searchSidebarResults ( term, baseurl, page, sort, search_count ) {\n var new_loc = $specified_loc.split(', ').join(',');\n var data = { what : term, where : new_loc, page_num : page, sortby : sort, count : search_count };\n $.ajax({\n type: \"POST\",\n url: baseurl + \"/api/search.php\",\n dataType: \"JSON\",\n data: data,\n success: function(data){\n if( data.success.results.locations.length > 0 ){\n if(!$.isEmptyObject(data.success.results.locations)){ \n renderSidebarResults(data.success.results.locations); \n }\n }\n }\n });\n }",
"function getWeather() {\n\tif (searchBox.getPlaces().length > 0)\n\t{\n\t\tvar loc = searchBox.getPlaces().pop();\n\t\tvar latLon = loc.geometry.location.lat() + \",\" + loc.geometry.location.lng();\n\t\tgetCity(latLon);\n\t\tgetForecast(latLon);\n\t}\n\telse {\n\t\talert(\"Could not retrieve location. Please enter a new location\");\n\t}\n}",
"function searchCityAndGetWeather(){\n city = $(searchInput).val()\n getWeatherAndForecast()\n }",
"search(foodSearchString, callback) {\n let searchUrl = this.urlRoot + '&sort=n&max=25&offset=0&q=' + foodSearchString;\n \n // hit the API and give it a callback to get the result\n request(searchUrl, (error, response, body) => {\n if (error) {\n callback(error);\n } else {\n let parsedResponse = JSON.parse(body);\n let searchResults = parsedResponse.list.item;\n\n let cleanedResults = this.parseSearchResults(searchResults);\n callback(false, cleanedResults);\n }\n });\n }",
"getFourSquareLikes(location) {\n const api = \"https://api.foursquare.com/v2/venues/search?&client_id=ZC3DM45VDUQXJ2VZ4IN4VWDC51CPRQHOJHHTJA0LZ0CSZMVG&client_secret=ZYKQA5FE4BZNGIRMIUZMJYXGQ4VM4GU5W3SZYKLSG5JOYYYF&v=20180616\";\n const headers = {\n 'Accept': 'application/json',\n };\n\n return new Promise((resolve, reject) => {\n fetch(`${api}&ll=${location.location.lat},${location.location.lng}&query=${location.title}`, {headers})\n .then(res => {\n if (res.ok) return res.json();\n reject();\n })\n .catch(error => reject(error))\n .then(data => {\n const api = `https://api.foursquare.com/v2/venues/${data.response.venues[0].id}/likes?client_id=ZC3DM45VDUQXJ2VZ4IN4VWDC51CPRQHOJHHTJA0LZ0CSZMVG&client_secret=ZYKQA5FE4BZNGIRMIUZMJYXGQ4VM4GU5W3SZYKLSG5JOYYYF&v=20180616`;\n const headers = {\n 'Accept': 'application/json',\n };\n // console.log(data.response.venues)\n fetch(`${api}&ll=${location.location.lat},${location.location.lng}&query=${location.title}`, {headers})\n .then(res => {\n if (res.ok) return res.json();\n reject();\n })\n .catch(error => reject(error))\n .then(data => {\n // console.log(data.response.likes.count);\n resolve(data.response.likes.count);\n }).catch(error => reject(error));\n\n }).catch(error => reject(error));\n });\n }",
"function searchRestaurant() {\n let search = {\n bounds: map.getBounds(),\n types: [\"restaurant\"],\n };\n places.nearbySearch(search, (results, status) => {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n clearResults();\n clearMarkers();\n\n // Create a marker for each resturant found, and\n // assign a letter of the alphabetic to each marker icon.\n for (let i = 0; i < results.length; i++) {\n let markerLetter = String.fromCharCode(\"A\".charCodeAt(0) + (i % 26));\n let markerIcon = MARKER_PATH + markerLetter + \".png\";\n\n // Use marker animation to drop the icons incrementally on the map.\n markers[i] = new google.maps.Marker({\n position: results[i].geometry.location,\n animation: google.maps.Animation.DROP,\n icon: markerIcon,\n });\n\n // If the user clicks a resturant marker, show the details of that place in an info window\n markers[i].placeResult = results[i];\n google.maps.event.addListener(markers[i], \"click\", showInfoWindow);\n setTimeout(dropMarker(i), i * 100);\n addResult(results[i], i);\n }\n }\n });\n}",
"function searchPlace(){\n var search = new google.maps.places.PlacesService(map);\n var request = {\n keyword: [searchType],\n location: map.getCenter(),\n rankBy: google.maps.places.RankBy.DISTANCE\n }\n search.nearbySearch(request, function(data, status){\n if(status == google.maps.places.PlacesServiceStatus.OK){\n loc = data[0].name;\n add = data[0].vicinity;\n rating = data[0].rating;\n latitude = data[0].geometry.location.k;\n longitude = data[0].geometry.location.D;\n\n var placeLoc = data[0].geometry.location;\n var marker = new google.maps.Marker({ map: map, position: data[0].geometry.location});\n google.maps.event.addListener(marker, 'click', function() {\n infowindow.setContent(data[0].name);\n infowindow.open(map, this); //google\n });\n // var loc = data[0].place_id;\n\n }\n });\n\n}",
"function getnearestURACarparkInformation(carparknoinput)\n{\n //var geturacarparkfromuser = \"K0087\";\n //var getlatfromuser = 1.332401;\n //var getlongfromuser = 103.848438;\n\n //To get new token everyday\n var token = \"6hf2NfWWja4j12bn3H4z8g62287rha485Fu7ff1F8gVC0R-AbBC-38YT3c856fV3HCZmet2j54+gbCP40u3@Q184ccRQGzcbXefE\";\n var options = {\n url: 'https://www.ura.gov.sg/uraDataService/invokeUraDS?service=Car_Park_Details',\n headers: {\n 'AccessKey' : '0d5cce33-3002-451b-8f53-31e8c4c54477',\n 'Token' : token\n }\n };\n\n function callback(error, response, body) \n {\n var cv2 = new SVY21();\n var geturacarparkfromuser = carparknoinput;\n \n if (!error && response.statusCode == 200)\n {\n //Parse data\n var jsonobject4 = JSON.parse(body);\n console.log(\"parse data from URA carpark\");\n //console.log(util.inspect(body, false, null));\n\n for (var i = 0; i < jsonobject4.Result.length; ++i)\n {\n //Find car park details for cars\n if (jsonobject4.Result[i].vehCat == \"Car\" && jsonobject4.Result[i].weekdayMin == \"30 mins\")\n {\n //Match car park no from nearby URA carpark and get car park address\n if (jsonobject4.Result[i].ppCode == geturacarparkfromuser)\n {\n console.log(\"URA Carpark Address : \" + jsonobject4.Result[i].ppName);\n var showuracarparkaddress = jsonobject4.Result[i].ppName; \n }\n }\n }\n }\n }\n request(options, callback);\n}",
"function searchUV(lat, lon){\n var apiKey=\"fb387ced59c1ebda042a0c8fd0dabefe\";\n var settings = {\n \"async\": true,\n \"crossDomain\": true,\n \"url\": \"http://api.openweathermap.org/data/2.5/uvi?lat=\"+lat+\"&lon=\"+lon+\"&appid=\"+apiKey,\n \"method\": \"GET\"\n } \n $.ajax(settings).done(function (response) {\n displayUVData(response);\n });\n}",
"function searchFunc() {\n\t // get the value of the search input field\n\t var searchString = $('#search').val(); //.toLowerCase();\n\t markers.setFilter(showFamily);\n\n\t // here we're simply comparing the 'state' property of each marker\n\t // to the search string, seeing whether the former contains the latter.\n\t function showFamily(feature) {\n\t return (feature.properties.last_name === searchString || feature.properties[\"always-show\"] === true);\n\t }\n\t}",
"function searchPlaces(loc) {\n // create places service\n var service = new google.maps.places.PlacesService(map);\n service.nearbySearch({\n location: loc,\n radius: 500\n // type: ['store']\n },\n // callback function for nearbySearch\n function(results, status) {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n for (var i = 0; i < results.length; i++) {\n createMarker(results[i]);\n }\n } else {\n window.alert(\"Google places search failed at that moment, please try again\");\n }\n });\n }",
"function search5Day(lat, lon){\n \n var apiKey=\"fb387ced59c1ebda042a0c8fd0dabefe\";\n var settings = {\n \"async\": true,\n \"crossDomain\": true,\n \"url\": \"https://api.openweathermap.org/data/2.5/onecall?lat=\"+lat+\"&lon=\"+lon+\"&exclude=current,minutely,hourly,alerts&appid=\"+apiKey,\n \"method\": \"GET\"\n } \n $.ajax(settings).done(function (response) {\n displayForecast(response);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the given properties match those of a `GrpcRouteMatchProperty` | function CfnRoute_GrpcRouteMatchPropertyValidator(properties) {
if (!cdk.canInspect(properties)) {
return cdk.VALIDATION_SUCCESS;
}
const errors = new cdk.ValidationResults();
if (typeof properties !== 'object') {
errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));
}
errors.collect(cdk.propertyValidator('metadata', cdk.listValidator(CfnRoute_GrpcRouteMetadataPropertyValidator))(properties.metadata));
errors.collect(cdk.propertyValidator('methodName', cdk.validateString)(properties.methodName));
errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));
errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));
return errors.wrap('supplied properties not correct for "GrpcRouteMatchProperty"');
} | [
"function CfnGatewayRoute_GrpcGatewayRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('hostname', CfnGatewayRoute_GatewayRouteHostnameMatchPropertyValidator)(properties.hostname));\n errors.collect(cdk.propertyValidator('metadata', cdk.listValidator(CfnGatewayRoute_GrpcGatewayRouteMetadataPropertyValidator))(properties.metadata));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));\n return errors.wrap('supplied properties not correct for \"GrpcGatewayRouteMatchProperty\"');\n}",
"function CfnRoute_GrpcRouteMetadataMatchMethodPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnRoute_MatchRangePropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GrpcRouteMetadataMatchMethodProperty\"');\n}",
"function CfnGatewayRoute_HttpGatewayRouteHeaderMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnGatewayRoute_GatewayRouteRangeMatchPropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"HttpGatewayRouteHeaderMatchProperty\"');\n}",
"function CfnGatewayRoute_HttpPathMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n return errors.wrap('supplied properties not correct for \"HttpPathMatchProperty\"');\n}",
"function CfnRoute_HttpPathMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n return errors.wrap('supplied properties not correct for \"HttpPathMatchProperty\"');\n}",
"function CfnGatewayRoute_GatewayRouteMetadataMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnGatewayRoute_GatewayRouteRangeMatchPropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GatewayRouteMetadataMatchProperty\"');\n}",
"function CfnRoute_HttpRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('headers', cdk.listValidator(CfnRoute_HttpRouteHeaderPropertyValidator))(properties.headers));\n errors.collect(cdk.propertyValidator('method', cdk.validateString)(properties.method));\n errors.collect(cdk.propertyValidator('path', CfnRoute_HttpPathMatchPropertyValidator)(properties.path));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('queryParameters', cdk.listValidator(CfnRoute_QueryParameterPropertyValidator))(properties.queryParameters));\n errors.collect(cdk.propertyValidator('scheme', cdk.validateString)(properties.scheme));\n return errors.wrap('supplied properties not correct for \"HttpRouteMatchProperty\"');\n}",
"function CfnGatewayRoute_HttpQueryParameterMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n return errors.wrap('supplied properties not correct for \"HttpQueryParameterMatchProperty\"');\n}",
"function CfnRoute_HttpQueryParameterMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n return errors.wrap('supplied properties not correct for \"HttpQueryParameterMatchProperty\"');\n}",
"function CfnGatewayRoute_GatewayRouteHostnameMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GatewayRouteHostnameMatchProperty\"');\n}",
"function CfnRoute_TcpRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n return errors.wrap('supplied properties not correct for \"TcpRouteMatchProperty\"');\n}",
"function CfnRoute_RouteSpecPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('grpcRoute', CfnRoute_GrpcRoutePropertyValidator)(properties.grpcRoute));\n errors.collect(cdk.propertyValidator('http2Route', CfnRoute_HttpRoutePropertyValidator)(properties.http2Route));\n errors.collect(cdk.propertyValidator('httpRoute', CfnRoute_HttpRoutePropertyValidator)(properties.httpRoute));\n errors.collect(cdk.propertyValidator('priority', cdk.validateNumber)(properties.priority));\n errors.collect(cdk.propertyValidator('tcpRoute', CfnRoute_TcpRoutePropertyValidator)(properties.tcpRoute));\n return errors.wrap('supplied properties not correct for \"RouteSpecProperty\"');\n}",
"function cfnRouteGrpcRouteMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_GrpcRouteMatchPropertyValidator(properties).assertSuccess();\n return {\n Metadata: cdk.listMapper(cfnRouteGrpcRouteMetadataPropertyToCloudFormation)(properties.metadata),\n MethodName: cdk.stringToCloudFormation(properties.methodName),\n Port: cdk.numberToCloudFormation(properties.port),\n ServiceName: cdk.stringToCloudFormation(properties.serviceName),\n };\n}",
"function CfnGatewayRoute_GatewayRouteSpecPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('grpcRoute', CfnGatewayRoute_GrpcGatewayRoutePropertyValidator)(properties.grpcRoute));\n errors.collect(cdk.propertyValidator('http2Route', CfnGatewayRoute_HttpGatewayRoutePropertyValidator)(properties.http2Route));\n errors.collect(cdk.propertyValidator('httpRoute', CfnGatewayRoute_HttpGatewayRoutePropertyValidator)(properties.httpRoute));\n errors.collect(cdk.propertyValidator('priority', cdk.validateNumber)(properties.priority));\n return errors.wrap('supplied properties not correct for \"GatewayRouteSpecProperty\"');\n}",
"function CfnRoute_GrpcRouteActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('weightedTargets', cdk.requiredValidator)(properties.weightedTargets));\n errors.collect(cdk.propertyValidator('weightedTargets', cdk.listValidator(CfnRoute_WeightedTargetPropertyValidator))(properties.weightedTargets));\n return errors.wrap('supplied properties not correct for \"GrpcRouteActionProperty\"');\n}",
"function cfnGatewayRouteGrpcGatewayRouteMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRouteMatchPropertyValidator(properties).assertSuccess();\n return {\n Hostname: cfnGatewayRouteGatewayRouteHostnameMatchPropertyToCloudFormation(properties.hostname),\n Metadata: cdk.listMapper(cfnGatewayRouteGrpcGatewayRouteMetadataPropertyToCloudFormation)(properties.metadata),\n Port: cdk.numberToCloudFormation(properties.port),\n ServiceName: cdk.stringToCloudFormation(properties.serviceName),\n };\n}",
"function CfnGatewayRoute_GrpcGatewayRouteActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('rewrite', CfnGatewayRoute_GrpcGatewayRouteRewritePropertyValidator)(properties.rewrite));\n errors.collect(cdk.propertyValidator('target', cdk.requiredValidator)(properties.target));\n errors.collect(cdk.propertyValidator('target', CfnGatewayRoute_GatewayRouteTargetPropertyValidator)(properties.target));\n return errors.wrap('supplied properties not correct for \"GrpcGatewayRouteActionProperty\"');\n}",
"function CfnGatewayRoute_GatewayRouteRangeMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('end', cdk.requiredValidator)(properties.end));\n errors.collect(cdk.propertyValidator('end', cdk.validateNumber)(properties.end));\n errors.collect(cdk.propertyValidator('start', cdk.requiredValidator)(properties.start));\n errors.collect(cdk.propertyValidator('start', cdk.validateNumber)(properties.start));\n return errors.wrap('supplied properties not correct for \"GatewayRouteRangeMatchProperty\"');\n}",
"function cfnGatewayRouteHttpPathMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpPathMatchPropertyValidator(properties).assertSuccess();\n return {\n Exact: cdk.stringToCloudFormation(properties.exact),\n Regex: cdk.stringToCloudFormation(properties.regex),\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the number of players and save to local storage | setNumPlayers( numPlayers ) {
this.gameConfig.numPlayers = numPlayers;
this.saveGameConfig();
} | [
"function updateNumberOfPlayers(){\n\n // this is the real number of players\n numberOfPlayers = inPlayerId - 1;\n}",
"function resetPlayerStats() {\n localStorage.streak1 = 0;\n localStorage.streak2 = 0;\n localStorage.currentPlayer = 2;\n}",
"function saveNumberOfPizzas(noOfPizzas) {\n window.localStorage.setItem(\"value\", noOfPizzas);\n window.localStorage.setItem(\"timestamp\", new Date().getTime());\n}",
"function updateUserCount(count) {\n database.ref('players/count').set(count);\n}",
"updateCount(count){\r\n //playerCount refers to the database counts whereas count refers to make a change to the original playerCount\r\n database.ref(\"/\").update({playerCount:count});\r\n }",
"function playerName() {\r\n var player = document.getElementById(\"player\").value;\r\n localStorage.setItem(\"playerName\", player);\r\n}",
"initPlayers() {\n\n for( var i = 0; i < this.gameConfig.numPlayers; i++ ) {\n this.gameConfig.players.push({\n name : '',\n imgPath : 'img/ninja-odd.png',\n killed : false,\n nameToKill: '',\n word : ''\n })\n }\n\n this.saveGameConfig();\n }",
"function storeCount() {\n if (localStorage.getItem(userInput) !== null){\n let counter = parseInt(localStorage.getItem(userInput)) + 1;\n localStorage.setItem(userInput, counter);\n } else {\n localStorage.setItem(userInput, 1);\n }\n let currentCount = 0;\n let currentSybol;\n for (let [key, value] of Object.entries(localStorage)) {\n if (parseInt(value) > currentCount) {\n currentCount = value;\n currentSymbol = key;\n }\n }\n updateFavorite(currentSymbol, currentCount);\n}",
"function saveSettings(){\n localStorage[\"pweGameServerStatus\"] = gameselection;\n //console.log('saved: ' + gameselection);\n}",
"function increment() {\n if (!localStorage.getItem(\"count\")) {\n console.log(\"no count in local storage found\");\n localStorage.setItem(\"count\", count);\n } else {\n count = localStorage.getItem(\"count\");\n count++;\n localStorage.setItem(\"count\", count);\n incrementElement.textContent = count;\n }\n}",
"function assignLevelsToPlayers() {\n var level = 0;\n vm.levels = [];\n createBreakPoints();\n for (var i = 0; i < vm.competition.players.length; i++) {\n if (vm.breakPoints.indexOf(i + 1) > -1) {\n level += 1;\n // Set the number of total levels\n vm.levels.push(level);\n }\n // Give each player a level\n vm.competition.players[i].level = level;\n }\n }",
"function updateWinCountAndResetSelection(player) {\n database.ref().once(\"value\", function (snapshot) {\n var player1WinCount = snapshot.val().player1.victories;\n var player2WinCount = snapshot.val().player2.victories;\n if (player == \"player1\") {\n player1WinCount++;\n }\n else if (player == \"player2\") {\n player2WinCount++;\n }\n\n snapshot.ref.update({\n \"player1/victories\": player1WinCount,\n \"player2/victories\": player2WinCount,\n \"player1/selection\": \"\",\n \"player2/selection\": \"\"\n });\n }, function (errorObject) {\n console.log(\"The read failed: \" + errorObject.code);\n });\n }",
"getNumberOfPlayerScreen() {\n\t\tlet boxWidth = 450;\n\t\tlet boxHeight = 50;\n\t\tpush();\n\t\trectMode(CENTER);\n\t\tbgPanel(width / 2, height / 3 - 10, boxWidth, boxHeight);\n\t\tfill(0, 0, 255);\n\t\ttextSize(32);\n\t\ttextAlign(CENTER);\n\t\ttext(\"Enter Number of Players: 1-5\", width / 2, height / 3);\n\t\tpop();\n\t}",
"update(name){\r\n\t\tvar playerIndex = \"player\"+playerCount;\r\n\t\tdatabase.ref(playerIndex).set({\r\n\t\t\tname : name\r\n\t\t})\r\n\t}",
"function saveDuration(number){\r\n durationArray.push(number);\r\n localStorage.setItem(\"durationLocal\", JSON.stringify(durationArray));\r\n}",
"function addUserName () {\n let tag = document.querySelector('#player')\n let myHeadline = document.createElement('h2')\n myHeadline.innerText = 'Curently playing:'\n tag.appendChild(myHeadline)\n let button = document.querySelector('#player button')\n button.addEventListener('click', event => {\n let value = button.previousElementSibling.value\n if (value.length === 0) return\n window.localStorage.setItem('value', value)\n document.getElementById('playername').innerHTML = window.localStorage.getItem('value')\n event.stopPropagation()\n button.previousElementSibling.value = ''\n })\n}",
"function savGamNumSess(num){\r\nsessionStorage.setItem(\"gameNum\", JSON.stringify(num));\r\n}",
"function saveKittens() {\r\n\r\n\r\n\r\n window.localStorage.setItem(\"kittens\", JSON.stringify(kittens));\r\n\r\n}",
"startLocalStorage(){\n //if localStorage does not exist, then create one.\n if(localStorage.getItem(this.playerListLSName) !== null){\n\n this.allPlayerList = JSON.parse(localStorage.getItem(this.playerListLSName))\n }\n else{\n //create localStorage\n //console.log(\"Did not find player list, will create a new with a testPlayer\")\n let playerList = []\n\n playerList.push(new HumanPlayer('Admin', 1))\n //playerList.push(new HumanPlayer('test', 10))\n\n localStorage.setItem(this.playerListLSName, JSON.stringify(playerList))\n this.allPlayerList = playerList\n }\n\n //Create bots local storage.\n if(localStorage.getItem(this.botsListLSName) !== null){\n this.allBotsList = JSON.parse(localStorage.getItem(this.botsListLSName))\n }\n else{\n //create localStorage\n let botsList = []\n \n //botsList.push(new HardBot('testBot', 1))\n botsList.push(new EasyBot('Joey'))\n botsList.push(new MediumBot('Elaine'))\n botsList.push(new HardBot('Amy'))\n\n localStorage.setItem(this.botsListLSName, JSON.stringify(botsList))\n this.allBotsList = botsList\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the instance of `DOM`. | static get instance() {
if (!DOMImpl._instance) {
DOMImpl._instance = new DOMImpl();
}
return DOMImpl._instance;
} | [
"get element() {\n return this.dom;\n }",
"function getXMLDocument(){\n var xDoc=null;\n\n if( document.implementation && document.implementation.createDocument ){\n xDoc=document.implementation.createDocument(\"\",\"\",null);//Mozilla/Safari \n }else if (typeof ActiveXObject != \"undefined\"){\n var msXmlAx=null;\n try{\n msXmlAx=new ActiveXObject(\"Msxml2.DOMDocument\");//New IE\n }catch (e){\n msXmlAx=new ActiveXObject(\"Msxml.DOMDocument\"); //Older Internet Explorer \n }\n xDoc=msXmlAx;\n }\n if (xDoc==null || typeof xDoc.load==\"undefined\"){\n xDoc=null;\n }\n return xDoc;\n}",
"_buildDOM() {\n const HTML = this.render();\n if (!HTML) { return }\n this.DOMbuilder.build( HTML );\n }",
"dom(lastJstComponent, lastJstForm) {\n\n // TEMP protection...\n if (this.tag === \"-deleted-\") {\n console.error(\"Trying to DOM a deleted element\", this);\n return undefined;\n }\n let el = this.el;\n\n if (!el) {\n if (this.ns) {\n el = document.createElementNS(this.ns, this.tag);\n }\n else {\n el = document.createElement(this.tag);\n }\n }\n\n // If the element parameters contains a 'ref' attribute, then fill it in\n if (this.ref && lastJstComponent) {\n lastJstComponent.setRef(this.ref, this);\n }\n\n // Handle forms\n if (lastJstComponent && this.tag === \"form\" && (this.attrs.name || this.attrs.ref || this.attrs.id)) {\n lastJstForm = lastJstComponent.addForm(this);\n }\n else if (lastJstForm &&\n (this.tag === \"input\" ||\n this.tag === \"textarea\" ||\n this.tag === \"select\")) {\n lastJstForm.addInput(this);\n }\n\n if (!this.isDomified) {\n \n this.jstComponent = lastJstComponent;\n\n // Handle all the attributes on this element\n for (let attrName of Object.keys(this.attrs)) {\n let val = this.attrs[attrName];\n\n // Special case for 'class' and 'id' attributes. If their values start with\n // '-' or '--', add the scope to their values\n if (lastJstComponent && (attrName === \"class\" || attrName === \"id\") &&\n val.match && val.match(/(^|\\s)-/)) {\n val = val.replace(/(^|\\s)(--?)/g,\n (m, p1, p2) => p1 +\n (p2 === \"-\" ? lastJstComponent.getClassPrefix() :\n lastJstComponent.getFullPrefix()));\n }\n el.setAttribute(attrName, val);\n }\n\n // Add the properties\n for (let propName of this.props) {\n el[propName] = true;\n }\n\n // Add event listeners\n for (let event of Object.keys(this.events)) {\n // TODO: Add support for options - note that this will require\n // some detection of options support in the browser...\n el.addEventListener(event, this.events[event].listener);\n }\n \n // Now add all the contents of the element\n this._visitContents(\n lastJstComponent,\n // Called per JstElement\n (jstComponent, item) => {\n \n if (item.type === JstElementType.TEXTNODE) {\n if (!item.el) {\n item.el = document.createTextNode(item.value);\n el.appendChild(item.el);\n }\n }\n else if (item.type === JstElementType.JST_ELEMENT) {\n let hasEl = item.value.el;\n let childEl = item.value.dom(jstComponent, lastJstForm);\n if (!hasEl) {\n el.appendChild(childEl);\n }\n else if (childEl.parentNode && childEl.parentNode !== el) {\n childEl.parentNode.removeChild(childEl);\n el.appendChild(childEl);\n }\n }\n else {\n console.error(\"Unexpected contents item type:\", item.type);\n }\n \n },\n // Called per JstComponent\n jstComponent => {\n jstComponent.parentEl = el;\n }\n );\n\n }\n\n this.el = el;\n this.isDomified = true;\n return el;\n\n }",
"getDOMStrings() {\n return DOMstrings;\n }",
"function buildDom(htmlString) {\r\n const div = document.createElement(\"div\");\r\n div.innerHTML = htmlString;\r\n return div.children[0];\r\n}",
"static attach(element) {\n return new DomBuilder(element);\n }",
"function makeNode(javaNode) {\n if (!javaNode) {\n return null;\n }\n if (_domNodes.containsKey(javaNode)) {\n return _domNodes.get(javaNode);\n }\n const isElement = javaNode.getNodeType() === org.w3c.dom.Node.ELEMENT_NODE;\n const jsNode = isElement ? new window.DOMElement(javaNode) : new window.DOMNode(javaNode);\n _domNodes.put(javaNode, jsNode);\n return jsNode;\n }",
"_destroyDOM() {\n this.DOMbuilder.destroy();\n }",
"elementFromHTML(html) {\n const div = document.createElement('div');\n div.innerHTML = html.trim();\n return div.firstChild;\n }",
"function buildDomTree() {\r\n /**\r\n * <div id=\"$root\" class=\"scheduler\"> <div class=\"timeColumn\"></div>\r\n * <div class=\"dayRow\"></div> <div id=\"scrollWrapper\"> <div\r\n * class=\"schedulerContent\"></div> </div> </div>\r\n */\r\n\r\n $root.addClass('scheduler');\r\n $timeColumn = $('<div/>', {\r\n 'class' : 'timeColumn',\r\n })\r\n\r\n $dayRow = $('<div/>', {\r\n 'class' : 'dayRow',\r\n })\r\n\r\n $scrollWrapper = $('<div/>', {\r\n 'id' : 'scrollWrapper',\r\n });\r\n $content = $('<div/>', {\r\n 'class' : 'schedulerContent',\r\n });\r\n $scrollWrapper.append($content);\r\n\r\n $root.append($timeColumn);\r\n $root.append($dayRow);\r\n $root.append($scrollWrapper);\r\n }",
"function initDOMCache() {\r\n this.domCache = {};\r\n }",
"function getEl(id) {\n return document.getElementById(id) || document.getElementsByClassName(id)[0] || document.getElementsByTagName(id)[0] || null;\n}",
"function DeltaXMLFactory() {\n}",
"function createElements() {\r\n _dom = {};\r\n createElementsForSelf();\r\n if (_opts.placement.popup) {\r\n createElementsForPopup();\r\n }\r\n createElementsForColorWheel();\r\n createElementsForNumbersMode();\r\n createElementsForSamples();\r\n createElementsForControls();\r\n }",
"destroyElement() {\n if (this.dom) {\n this.dom.remove();\n }\n }",
"function $(el){\n\tif ($type(el) == 'string') el = document.getElementById(el);\n\tif ($type(el) == 'element'){\n\t\tif (!el.extend){\n\t\t\tUnload.elements.push(el);\n\t\t\tel.extend = Object.extend;\n\t\t\tel.extend(Element.prototype);\n\t\t}\n\t\treturn el;\n\t} else return false;\n}",
"toNODE() {\n switch (this._type) {\n case \"NODE\":\n return this._value;\n case \"STRING\":\n let parser = new DOMParser();\n let doc = parser.parseFromString(this._value, \"text/html\");\n return doc.body.firstChild;\n case \"YNGWIE\":\n return this._value.render();\n default:\n throw new _Transform_main_js__WEBPACK_IMPORTED_MODULE_3__.default(\"Cannot transform to NODE from unsuppoted type\", this._value);\n }\n }",
"getElement(el) {\n return document.getElementsByClassName(el)[0];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes a new instance of `XMLCData` `text` CDATA text | constructor(parent, text) {
super(parent);
if (text == null) {
throw new Error("Missing CDATA text. " + this.debugInfo());
}
this.name = "#cdata-section";
this.type = NodeType.CData;
this.value = this.stringify.cdata(text);
} | [
"function cdata(x) {\n\tif (typeof x === \"undefined\") { return; }\n\treturn x && x.toString && x.toString().length ? '<![CDATA[' + x + ']]>' : x;\n}",
"function createTextElement(text) {\n return new VirtualElement(0 /* Text */, text, emptyObject, emptyArray);\n }",
"function loadCCText(text) {\n\tclearCC();\n\t//console.log(\"Loading: \"+text);\n\t$('#'+shell.caption.textEl).append(text);\n\tif (CCIsDim) enableCC();\n}",
"function loadSubCCText(text) {\n\tclearCC();\n\t$('#'+shell.caption.textEl).append(text);\n\tif (CCIsDim) enableCC();\n}",
"function Text(attrs) {\n var dflt = {\n content: \"\",\n fill: \"black\",\n font: \"12pt Helvetica\",\n height: 12\n };\n attrs = mergeWithDefault(attrs, dflt);\n Drawable.call(this, attrs);\n\t//constructor code \n this.content=attrs.content;\n this.fill = attrs.fill; \n this.font = attrs.font;\n this.height = attrs.height;\n this.left = attrs.left;\n}",
"function setTextContent(node, value) {\n if (predicates_1.isCommentNode(node)) {\n node.data = value;\n }\n else if (predicates_1.isTextNode(node)) {\n node.value = value;\n }\n else {\n const tn = modification_1.constructors.text(value);\n tn.parentNode = node;\n node.childNodes = [tn];\n }\n}",
"function initArticleContent(data) {\n var article_content = document.createElement('p');\n var content = data.fields.body;\n if (content.length > 500) {\n article_content.innerHTML = content.substring(0, 500) + \"...\";\n } else {\n article_content.innerHTML = content;\n }\n article_content.className = \"flavour\";\n return article_content;\n }",
"function makeTextNode(token) {\n var node = makeObj(baseTextNode);\n node.text = token;\n return node;\n }",
"function MarkupTextContainer(markupView, node) {\n MarkupContainer.prototype.initialize.call(this, markupView, node, \"textcontainer\");\n\n if (node.nodeType == Ci.nsIDOMNode.TEXT_NODE) {\n this.editor = new TextEditor(this, node, \"text\");\n } else if (node.nodeType == Ci.nsIDOMNode.COMMENT_NODE) {\n this.editor = new TextEditor(this, node, \"comment\");\n } else {\n throw \"Invalid node for MarkupTextContainer\";\n }\n\n this.tagLine.appendChild(this.editor.elt);\n}",
"function createNodeAndText(type, text, attributes) {\n var node = document.createElement(type);\n var child = document.createTextNode(text);\n var i;\n var attribute;\n\n if (attributes) {\n for (i = 0; i < attributes.length; i += 1) {\n attribute = attributes[i];\n console.log(attribute);\n node.setAttribute(attribute[0], attribute[1]);\n }\n }\n node.appendChild(child);\n return node;\n}",
"createText(){\n let text = Text.createText(this.activeColor);\n this.canvas.add(text);\n this.notifyCanvasChange(text.id, \"added\");\n }",
"get text() {\n return (this._textElement || this._element).textContent;\n }",
"function fixXML( text, parsetext ) {\n\tvar bug1a = text.indexOf( '<head>' );\n\tvar bug1b = text.indexOf( '<!-- start content -->' );\n\tif( bug1a != -1 || bug1b != -1 ) {\n\t\tvar text = text.substring( 0, bug1a ) + '<body><div id=\"bodyContent\">' + text.substring( bug1b );\n\t}\n\n\tvar bug2 = text.indexOf( '<!-- end content -->' );\n\tif( bug2 != -1 ) {\n\t\tvar text = text.substring( 0, bug2 ) + '</div></body></html>';\n\t} else {\n\t\treturn null;\n\t}\n\n\tif( parsetext == false ) {\n\t\treturn text;\n\t}\n\n\ttry {\n\t\tvar fixedXML = new ActiveXObject(\"Microsoft.XMLDOM\");\n\t\tfixedXML.async = 'false';\n\t\tfixedXML.loadXML( text );\n\t\treturn fixedXML;\n\t} catch( e ) {\n\t\ttry {\n\t\t\tvar parser = new DOMParser();\n\t\t\tvar fixedXML = parser.parseFromString( text, \"text/xml\" );\n\t\t\treturn fixedXML;\n\t\t} catch( e ) {\n\t\t\treturn false;\n\t\t}\n\t}\n}",
"function StringToXML(txt) {\n\tif (window.DOMParser) {\n\t\t// code for Chrome, Firefox, Opera, etc.\n\t\tparser=new DOMParser();\n\t\txml=parser.parseFromString(txt,\"text/xml\");\n\t} else {\n\t\t// code for IE\n\t\txml=new ActiveXObject(\"Microsoft.XMLDOM\");\n\t\txml.async=false;\n\t\txml.loadXML(txt); \n\t};\n\treturn xml;\n}",
"function cXparse(src) {\n var frag = new _frag();\n\n // remove bad \\r characters and the prolog\n frag.str = _prolog(src);\n\n // create a root element to contain the document\n var root = new _element();\n root.name = \"ROOT\";\n\n // main recursive function to process the xml\n frag = _compile(frag);\n\n // all done, lets return the root element + index + document\n root.contents = frag.ary;\n root.index = _Xparse_index;\n _Xparse_index = new Array();\n return root;\n}",
"function make (svg, data, config) {\n var attrs = [\n 'font-family', 'font-size', 'stroke', 'fill', 'text-anchor', 'x', 'y'\n ]\n\n var _conf = {}\n var a\n\n for (var i = 0; i < attrs.length; ++i) {\n a = attrs[i]\n if (config.hasOwnProperty(a))\n _conf[a] = config[a]\n }\n\n var group = svg.append('svg:g')\n if ('groupId' in config)\n group.attr('id', config.groupId)\n\n var text = group.selectAll('g')\n .data(data)\n .enter()\n .append('svg:g')\n\n if (config.doubleLayer) {\n text.append('svg:text')\n .attr(_conf)\n .attr('class', config.doubleLayer.className)\n .text(config.text)\n }\n\n text.append('svg:text')\n .attr(_conf)\n .text(config.text)\n\n return text\n }",
"function insertCitation(data) {\n var tTitle = data.itemTitle;\n var url =\n \"https://teva.contentdm.oclc.org/digital/collection/\" +\n global.collAlias +\n \"/id/\" +\n global.itemID;\n var dateToday = new Date().toISOString().slice(0, 10);\n const fieldBlackList = [\"itemTitle\"];\n const itemCite = `<hr /><strong>Citation:</strong> \\n \"${\n data.itemTitle\n },\" ${Object.values(mappings)\n .reduce((acc, cur) => {\n if (fieldBlackList.includes(cur)) return acc;\n const value = data[cur];\n return value ? [...acc, value] : acc;\n }, [])\n .join(\n \", \"\n )}, ${url}, accessed ${dateToday}. <br>Note: This citation is auto-generated and may be incomplete. Check your preferred style guide or the <a href=\"https://teva.contentdm.oclc.org/customizations/global/pages/about.html\">About TeVA page</a> for more information.`;\n const citationContainer = document.createElement(\"div\");\n citationContainer.id = \"citation\";\n citationContainer.innerHTML = itemCite;\n if (tTitle) {\n document\n .querySelector(\".ItemView-itemViewContainer\")\n .appendChild(citationContainer);\n }\n}",
"function _content(node, content) {\n\t\t//\n\t\tvar contentType = node.nodeType == 1 ? 'innerHTML' : 'data';\n\t\t//\n\t\tif (content) node[contentType] = content;\n\t\t//\n\t\treturn node[contentType];\n\t}",
"function appendTextDiv(a_Parent, a_Class, a_Text)\n{\n\tif ((a_Text === undefined) || (a_Text === null))\n\t{\n\t\tconsole.log(\"Attempting to add an empty text div\", a_Class, \" to \", a_Parent);\n\t\treturn;\n\t}\n\tvar div = document.createElement(\"div\");\n\tdiv.setAttribute(\"class\", a_Class);\n\tdiv.appendChild(document.createTextNode(a_Text));\n\ta_Parent.appendChild(div);\n}",
"function DocEdit_initialize(text, priorNodeSegment, weight, relativeNode, optionFlags)\n{\n //public\n this.text = text;\n\n if (priorNodeSegment && dw.nodeExists(priorNodeSegment.node))\n {\n this.priorNodeSegment = priorNodeSegment;\n this.priorNode = priorNodeSegment.node || false;\n this.matchRangeMin = priorNodeSegment.matchRangeMin || 0;\n this.matchRangeMax = priorNodeSegment.matchRangeMax || 0;\n\n if (this.matchRangeMin == this.matchRangeMax)\n {\n // If we are here, we were given a priorNodeSegment which, though non-null and\n\t // in existance, is in fact bogus. Therefore, act like we were given no\n\t // priorNodeSegment at all (i.e., given a null for that param). It is dangerous\n\t // to use priorNodeSegment without clearing it here because we apparently have\n\t // data with bad integrety at this point.\n\t \n alert(\"ERROR: bad node segment offsets\");\n\t priorNodeSegment = null;\n }\n }\n \n if (!priorNodeSegment)\n {\n this.priorNode = false;\n this.matchRangeMin = -1;\n this.matchRangeMax = -1;\n }\n\n this.weight = weight || \"\"; //aboveHTML[+nn], belowHTML[+nn],\n //beforeSelection, afterSelection, replaceSelection,\n //beforeNode, afterNode, replaceNode,\n //nodeAttribute[+attribname]\n this.node = relativeNode || null; //optional: only used with \"...Node\" weights\n \n this.dontMerge = (optionFlags & docEdits.QUEUE_DONT_MERGE);\n\n this.dontPreprocessText = (optionFlags & docEdits.QUEUE_DONT_PREPROCESS_TEXT);\n this.dontFormatForMerge = (optionFlags & docEdits.QUEUE_DONT_FORMAT_FOR_MERGE);\n\n this.defaultWeight = 99;\n this.version = 5.0;\n\n //private\n this.insertPos = null;\n this.replacePos = null;\n this.bDontMergeTop = false;\n this.bDontMergeBottom = false;\n\n\n this.weightType = \"\"; //weight *might* have a preword, like aboveHTML or nodeAttribute\n this.weightNum = null; //weight *might* include a number (set below)\n this.weightInfo = \"\"; //weight *might* have extra info, like an attribute name (set below)\n\n //Initialize weight, weightNum, and weightInfo properties\n //Determine correct weight type, and assign extra weight properties\n if (this.weight)\n {\n //if weight is just number, change to aboveHTML+number\n if (this.weight == String(parseInt(this.weight))) //if just number (old style)\n {\n this.weightNum = parseInt(this.weight); //convert if number\n this.weightType = \"aboveHTML\";\n this.weight = this.weightType + \"+\" + this.weight; //default is aboveHTML\n }\n //if extra weight info (someWeight+someData), extract data\n else if (this.weight.indexOf(\"+\") > 0)\n {\n var data = this.weight.substring(this.weight.indexOf(\"+\")+1);\n this.weightType = this.weight.substring(0,this.weight.indexOf(\"+\"));\n\n //if weight is ??+number, extract the number\n if (data == String(parseInt(data)))\n {\n this.weightNum = parseInt(data); //convert if number\n\n //if weight is ??+??, save data as info\n }\n else\n {\n this.weightInfo = data;\n }\n }\n //if weight is aboveHTML or belowHTML, add default weight number\n else if (this.weight == \"aboveHTML\" || this.weight == \"belowHTML\")\n {\n this.weightType = this.weight;\n this.weight += \"+\"+String(this.defaultWeight);\n this.weightNum = this.defaultWeight;\n }\n //for backward compatibility,convert \"afterDocument\" to \"belowHTML\"\n else if (this.weight == \"afterDocument\")\n {\n this.weightType = \"belowHTML\";\n this.weight = this.weightType + \"+\" + String(this.defaultWeight);\n this.weightNum = this.defaultWeight;\n }\n }\n else //default if no weight given\n {\n this.weight = \"aboveHTML+\"+String(this.defaultWeight);\n this.weightType = \"aboveHTML\";\n this.weightNum = this.defaultWeight;\n }\n\n // Only merge above and below the HTML tag. Merging within\n // the body can cause problems with translators.\n if (this.weightType != \"aboveHTML\" && this.weightType != \"belowHTML\")\n {\n this.preventMerge = true;\n }\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serverview: Server Create: Abort Server Application | function abortServerRequest()
{
teamspeakServerRequestsInit();
} | [
"function deleteServer(args) {\n console.log(\"Deleting server...\");\n const page = args.object;\n page.bindingContext.set(\"server\", undefined);\n}",
"function createServerCB(req, res) {\n\t// Get the url and parse it\n\tlet parsedUrl = url.parse(req.url, true);\n\t\n\t// Get the path from Url\n\tlet path = parsedUrl.pathname;\n\tlet trimmedPath = path.replace(/^\\/+|\\/+$/g, '');\n\n\t// Get the query string and parse as an object\n\tlet queryStringObj = parsedUrl.query;\n\n\t// Get Request method\n\tlet method = req.method.toLowerCase();\n\n\t// Get the headers \n\tlet headers = req.headers;\n\n\t// Get the payload if it exists\n\tlet decoder = new StringDecoder('utf8');\n\tlet buffer = '';\n\treq.on('data', (data) => {\n\t\tbuffer += decoder.write(data);\t\t\n\t});\n\treq.on('end', () => {\n\t\tbuffer += decoder.end();\n\n\t\t// Construct data object for use by handler\n\t\tlet data = {\n\t\t\t'trimmedPath' : trimmedPath,\n\t\t\t'queryStringObj' : queryStringObj,\n\t\t\t'method' : method,\n\t\t\t'headers' : headers,\n\t\t\t'payload' : buffer\n\t\t};\n\n\t\t// if path isn't to hello, return 404\n\t\tif(trimmedPath == 'hello') {\n\t\t\trouter.hello(data, (statusCode, payload) => {\n\t\t\t\t//Sanity Checks\n\t\t\t\tstatusCode = typeof(statusCode) == 'number' ? statusCode : 200;\n\t\t\t\tpayload = typeof(payload) == 'object' ? payload : {};\n\t\t\t\t//Convert payload to a string\n\t\t\t\tlet payloadString = JSON.stringify(payload);\n\t\t\t\t// Return Response\n\t\t\t\tres.setHeader('Content-Type', 'application/json');\n\t\t\t\tres.writeHead(statusCode);\n\t\t\t\tres.end(payloadString);\n\t\t\t});\n\t\t} else {\n\t\t\tnotFound(data, (statusCode) => {\n\t\t\t\t// Return Response\n\t\t\t\tres.setHeader('Content-Type', 'application/json');\n\t\t\t\tres.writeHead(statusCode);\n\t\t\t\tlet msg = {\"Message\" :\"We Only welcome when people come through the right door.\"};\n\t\t\t\tres.end(JSON.stringify(msg));\n\t\t\t});\n\t\t}\n\n\t});\n}",
"function serverUnreachableHandler(e) {\n document.getElementById(\"errorDiv\").innerHTML =\n \"Transliteration Server unreachable\";\n }",
"function main() {\n urlParameters = new URLSearchParams(window.location.search);\n serverClient = new ServerClient(urlParameters);\n noVNCClient = new NoVNCClient(\n connectCallback, disconnectCallback, \n document.getElementById('session-screen'));\n addOnClickListenerToElements();\n let /** number */ setIntervalId = setInterval(() => {\n serverClient.getSession().then(session => {\n clearInterval(setIntervalId);\n noVNCClient.remoteToSession(session.getIpOfVM(), \n session.getSessionId());\n setReadOnlyInputs(session.getSessionId());\n document.getElementById('welcome-message').style.display = 'block';\n updateUI();\n }).catch(error => {\n window.alert('No contact with the server, retrying!');\n });\n }, sessionScriptConstants.SERVER_RECONNECT_CADENCE_MS);\n}",
"static create(appID, configCloudParams, ipcMain, jabraApiMeta, clientInitResponsesRequested, window) {\r\n return jabra_node_sdk_1.createJabraApplication(appID, configCloudParams).then((jabraApi) => {\r\n const server = new JabraApiServer(jabraApi, ipcMain, jabraApiMeta, clientInitResponsesRequested, window);\r\n jabra_node_sdk_1._JabraNativeAddonLog(4 /* info */, \"JabraApiServer.create\", \"JabraApiServer server ready\");\r\n return server;\r\n });\r\n }",
"function startAppli (err,oApplication){\n if(err){\n console.log(err.message);\n }\n else{\n // Merge Application object with oApplication\n var oTemp = Object.assign(Application,oApplication);\n Application = oTemp;\n logger.log(\"Application : \", util.inspect(Application));\n /** Start server */\n debugger\n console.log (\"index port :\", port);\n server.start(port);\n }\n }",
"function handleResponse(){\n\tif((request.status == 200)&&(request.readyState == 4))\n\t\treDirect(\"usr_home.html\");\n//\telse\n//\t\talert(\"There was an error with the application, please restart the app. Error: \"+request.status);\n}",
"function initStartServer(){\n startServer();\n checkServerStatus(1);\n}",
"function removeServer(btnClicked){\n\tif(btnClicked){\n\t\tserverCountToDelete++;\n\t}\n\tif(totalServerCount == 1){\n\t\t$('.message-text').html('Minimum 1 server required');\n\t\t$('.message-text').removeClass('success-msg');\n\t}\n\telse if(totalServerCount && idleServerArr.length){\n\t\tvar x = idleServerArr[0];\n\t\t$('.task-execution-view .server-task-wrapper'+x+'').remove();\n\t\t$('#addServerBtn').removeAttr('disabled');\n\t\tidleServerArr.shift();\n\t\t$('.message-text').html('Server successfully deleted');\n\t\t$('.message-text').addClass('success-msg');\n\t\ttotalServerCount--;\n\t\tserverCountToDelete--;\n\t}\n\tif(pendingTaskCount && idleServerArr.length){\n\t\tisPendingTaskAv();\n\t}\n}",
"abortSession() {\n if (this.isRunning) {\n this.abort = true;\n }\n }",
"RecycleApplicationInstances(Variant, int) {\n\n }",
"function stop (cb) {\n got.post(killURL, { timeout: 1000, retries: 0 }, (err) => {\n console.log(err ? ' Not running' : ' Stopped daemon')\n\n debug(`removing ${startupFile}`)\n startup.remove('hotel')\n\n cb()\n })\n}",
"function startServer(){\n if(isDev()){\n var options = {\n scriptPath: path.join(__dirname, '../../../engine/'),\n args: [TEMP_PATH],\n pythonPath: 'python'\n };\n\n PythonShell.run('dash_server.py', options, function (err, results) {\n if(err){\n window.showAlertMessage({title: 'Dash Server Error', message: \"An error occured while trying to start the Dash Server\"});\n console.error(err);\n }\n if (results) console.log('Results from dash server: ', results);\n });\n }else{\n var opt = function(){\n execFile(DASH_PATH, [TEMP_PATH], function(err, results) { \n if(err){\n window.showAlertMessage({title: 'Dash Server Error', message: \"An error occured while trying to start the Dash Server\"});\n console.error(err);\n }\n if(results) console.log('Results from dash server: ', results.toString()); \n });\n }\n opt();\n }\n\n}",
"function hangUp(){\r\n socket.emit(\"end\", ID, self);\r\n fetch(\"/end\", {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify({\r\n ID: ID\r\n })\r\n }).then(response => {\r\n response.redirected;\r\n window.location.href = response.url;\r\n });\r\n}",
"function cancelApplication() {\n return confirm(\"Are you sure you want to cancel your application at this stage?. No record of your current application will be kept.\");\n}",
"componentWillUnmount() {\n if (this.serverRequest) {\n this.serverRequest.abort();\n }\n }",
"function systemOff (req, res) {\n\t\t// Here we will have calls to public controller functions to switch on/off a boolean\n\t\t// within each controller that lets it know whether it has permission to run\n\t}",
"writeBundle() {\n // Validate that there's no instance already running.\n if (!this._instance) {\n // Get the server basic options.\n const { https: httpsSettings, port } = this._options;\n // Create the server instance.\n this._instance = httpsSettings ?\n createHTTPSServer(httpsSettings, this._handler) :\n createHTTPServer(this._handler);\n\n // Start listening for requests.\n this._instance.listen(port);\n // Log some information messages.\n this._logger.warning(`Starting on ${this.url}`);\n this._logger.warning('waiting for Rollup...');\n // Start listening for process events that require the sever instance to be terminated.\n this._startListeningForTermination();\n // Open the browser.\n this._open();\n // Invoke the `onStart` callback.\n this._options.onStart(this);\n }\n }",
"stop() {\n if (!this.isStarted()) {\n throw new Error('cannot stop backend: not started yet');\n }\n this.started = false;\n this.logWriter.writeLine(`stopping backend for ${this.previewUriScheme}:// at port ${this.serverPort}`);\n this.server.stop();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
HTML READING/WRITING / Read inches from text input box. | function getInches() {
var inches = document.getElementById('inches_input').value;
if(Number(inches)) {
inches = Number(inches);
}
else if(inches == "" || !inches) {
inches = 1;
}
else {
inches = NaN;
}
return inches;
} | [
"function ConvertInchesToCentimeters(){\n\tvar inches = parseInt(document.calculator.setInches.value);\n\tvar inchesPerCentimeters= 2.54;\n\n\t\tcentimeters = inches * inchesPerCentimeters;\n\t\tdocument.calculator.getCentimeters.value = centimeters;\n}",
"function readInValueAndChangeOutput() {\n var readInValue = document.querySelector('#input_2').value;\n document.querySelector('#output_2').innerHTML = readInValue;\n}",
"function ProcIn(){\n var inputLine = document.getElementById(\"in\");\n WriteOut(document.createTextNode(\"<\" + inputLine.value));\n ParseIn(inputLine.value);\n inputLine.value = \"\";\n}",
"function inchesToCentimetres(){\r\n\t\r\n}",
"function scales() {\n enteredKey = document.getElementById(\"in\").value;\n\n document.getElementById(\"scales\").innerHTML = \n 'Major: ' + getMajorScale(enteredKey) + '<br>' + \n 'Minor: ' + getMinorScale(enteredKey) + '<br>'\n ;\n\n}",
"function getInput() {\n\tupdate(equation); // Update the equation in #equation-container\n\thandleMemory(); // Active buttons associated with memory.\n\n\t// Active keyboard for inputs.\n\tdocument.addEventListener(\"keypress\", keyboardInput, true);\n\n\t// Active buttons for inputs.\n\tvar backSpace = document.getElementsByClassName('fa-backspace');\n\tbackSpace[0].addEventListener(\"click\", buttonInput);\n\tvar buttons = document.getElementsByClassName(\"keyboard-item\");\n\tfor(i = 5; i < buttons.length; i++) {\n\t\tbuttons[i].addEventListener(\"click\", buttonInput);\n\t}\n}",
"function inputValue() {\n //*1 Get clicked numpad value\n const value = getNumpadValue();\n\n //*2 if a digit has been clicked\n if (value !== 0 && !isNaN(value)) {\n setCellValue(value);\n } else if (value === \"clear\") {\n setCellValue(\"\");\n } else return;\n resetNumpad();\n}",
"function t8(){\r\n var dis=prompt(\"enter distance b/w cities in km\");\r\n var km=parseInt(dis);\r\n var meter=km*1000;\r\n alert(\" distance in km: \"+dis+\"\\n distance in meters: \"+meter+\"\\n distance in feet: \"+ feet(km) +\"\\n distance in inches: \"+inches(km)+\"\\n distance in centimeters: \"+cent(km));\r\n\r\n }",
"function getHeightInInches(sideInput){\n return storeInputValues(sideInput, 'getHeightInInch');\n }",
"function metersToInches(numMeters){\n let inches = numMeters*(39.3701);\n return inches\n}",
"function spinputvalue () {\n if (!isContentEditable) return element.value;\n return element.innerText;\n }",
"display() {\n\t\tvar result = calc.inputArray.join(' ');\n\t\tif (calc.inputArray.length === 0) {\n\t\t\tresult = '0';\n\t\t}\n\t\t$('.calculatorScreen').val(result);\n\t\tif ($('.calculatorScreen').val().length > 13) {\n\t\t\t$('.calculatorScreen').css('font-size', '22px');\n\t\t\t$('.calculatorScreen').val().length;\n\t\t} else if ($('.calculatorScreen').val().length > 8) {\n\t\t\t$('.calculatorScreen').css('font-size', '32px');\n\t\t} else if ($('.calculatorScreen').val().length > 6) {\n\t\t\t$('.calculatorScreen').css('font-size', '48px');\n\t\t}\n\t}",
"function changeWeight(){\n if(document.getElementById(\"weight\").value == \"\"){\n weight=0\n }\n else{\n weight=document.getElementById(\"weight\").value \n }\n document.getElementById(\"weight1\").innerText=weight+\" kg\"\n}",
"function calculate() {\n\t\t'use strict';\n\t\n\t\t// For storing the volume:\n\t\tvar volume;\n \n // Get a reference to the form values:\n var length = document.getElementById('length').value;\n var width = document.getElementById('width').value;\n var height = document.getElementById('height').value;\n \n // Convert strings into numbers\n length = parseFloat(length);\n width = parseFloat(width);\n height = parseFloat(height);\n \n // Assertions\n try {\n \t\tassertCheck(((typeof length == 'number') && (length > 0)), 'The length must be a positive number.');\n \t\tassertCheck(((typeof width == 'number') && (width > 0)), 'The width must be a positive number.');\n \t\tassertCheck(((typeof height == 'number') && (height > 0)), 'The height must be a positive number.');\n } catch (err) {\n \t\tconsole.log('Caught: ' + err.name + ', because: ' + err.message);\n }\n\n\t\t// Verify box measurements\n console.log('length: ' + length);\n console.log('width: ' + width);\n console.log('height: ' + height);\n \n\t\t// Format the volume:\n\t\tvolume = parseFloat(length) * parseFloat(width) * parseFloat(height);\n\t\tvolume = volume.toFixed(4);\n\t\n\t\t// Display the volume:\n\t\tdocument.getElementById('volume').value = volume;\n\t\n\t\t// Return false to prevent submission:\n\t\treturn false;\n \n} // End of calculate() function.",
"function unitConverter() {\n\n var unit = document.getElementById(\"basic-addon2\").value;\n var num = document.getElementById(\"inputDistance\").value;\n\n if (unit === 'miles') {\n carbonConverter(num)}\n if (unit === 'km'){\n var newNum = num * 0.621371;\n carbonConverter(newNum)\n }\n}",
"function radiusOutput () {\n dInput = document.getElementById('d-input').value\n dInput = parseInt(dInput)\n radius = dInput / 2\n document.getElementById('radius').style.display = 'block'\n document.getElementById('radius-input').innerHTML = radius\n if (document.getElementById('d-input').value === '') {\n document.getElementById('radius').style.display = 'none'\n }\n}",
"function inputvalue(){\n return input.value\n}",
"getHeight() {\r\n let original = this.height; //in decimetres\r\n let meters = original / 10;\r\n let feet = Math.floor(meters * 3.28084); //rounds down to the nearest foot\r\n let inches = (meters * 3.28084 - feet) * 12; //takes the remainder of the foot and converts it to inches\r\n let inchesRounded = Math.round(inches);\r\n if (inchesRounded < 10) {\r\n let format = '0' + inchesRounded;\r\n return `${feet}'${format}\"`;\r\n }\r\n return `${feet}'${inchesRounded}\"`;\r\n }",
"function updateTextInputs() {\n\t\tlet hsvCol = new HSVColor (\n\t\t\tCPicker.markers.hue[0].angle,\n\t\t\tCPicker.markers.satv[0].sat,\n\t\t\tCPicker.markers.satv[0].val,\n\t\t\tctrPicker.alphaSlider.value\n\t\t);\n\t\t\n\t\tctrPicker.hexInput.value = hsvCol.getHexRGBA();\n\t\tctrPicker.hueInput.value = getCoterminalAngle(hsvCol.hue).toFixed();\n\t\tctrPicker.satInput.value = (hsvCol.saturation * 100).toFixed();\n\t\tctrPicker.valInput.value = (hsvCol.value * 100).toFixed();\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
LocalAnomaly: Simplified local object for the anomaly detector resource. | function LocalAnomaly(resource, connection, opts = {}) {
/**
* Constructor for the LocalAnomaly local object.
*
* @param {object} resource BigML anomaly resource
* @param {object} connection BigML connection
*/
var anomaly, self, fillStructure, filename;
this.connection = utils.getDefaultConnection(connection);
this.resourceConnector = new Anomaly(this.connection);
this.resType = "anomaly";
this.inputFields = undefined;
this.fields = undefined;
this.invertedFields = undefined;
this.description = undefined;
this.locale = undefined;
this.ready = undefined;
this.idFields = undefined;
self = this;
fillStructure = function (error, resource) {
/**
* Auxiliary function to load the resource info in the Anomaly detector
* structure.
*
* @param {object} error Error info
* @param {object} resource Anomaly's resource info
*/
var status, fields, inputFields, anomaly, index, len, tree, defaultDepth;
if (error) {
throw new Error('Cannot create the Anomaly detector instance. Could not'
+ ' retrieve the resource: ' + error);
}
status = utils.getStatus(resource);
if ((typeof resource.object) !== 'undefined') {
resource = resource.object;
}
anomaly = resource;
if (status.code === constants.FINISHED) {
self.sampleSize = anomaly['sample_size'];
if ((typeof resource.model) !== 'undefined') {
fields = anomaly.model.fields;
inputFields = anomaly["input_fields"];
self.idFields = anomaly['id_fields'];
if ((typeof anomaly.model['top_anomalies']) !== 'undefined') {
self.meanDepth = anomaly.model['mean_depth'];
self.normalizationFactor = anomaly.model["nomalization_factor"];
self.nodesMeanDepth = anomaly.model["nodes_mean_depth"];
self.norm = ((utils.isEmpty(self.normalizationFactor)) ?
normFactor(self.sampleSize, self.meanDepth) :
self.normalizationFactor);
self.iforest = [];
len = anomaly.model.trees.length;
for (index = 0; index < len; index++) {
tree = anomaly.model.trees[index].root;
self.iforest.push(new AnomalyTree(tree, fields, opts));
}
self.topAnomalies = anomaly.model.top_anomalies;
} else {
throw new Error('Cannot create the Anomaly detector instance. ' +
'Could not find the \'top_anomalies\' key\n');
}
} else {
throw new Error('Cannot create the Anomaly detector instance. ' +
'Could not' +
'find the \'model\' key in the resource\n');
}
self.inputFields = inputFields;
self.fields = fields;
self.invertedFields = utils.invertObject(fields);
self.description = resource.description;
self.locale = resource.locale || constants.DEFAULT_LOCALE;
self.ready = true;
if (NODEJS) {
self.emit('ready', self);
}
}
};
// Loads the model from:
// - the path to a local JSON file
// - a local file system directory or a cache provided as connection storage
// - the BigML remote platform
// - the full JSON information
if (NODEJS && ((typeof resource) === 'string' ||
utils.getStatus(resource).code !== constants.FINISHED)) {
// Retrieving the model info from local repo, cache manager or bigml
utils.getResourceInfo(self, resource, fillStructure);
} else {
// loads when the entire resource is given
fillStructure(null, resource);
}
if (NODEJS) {
events.EventEmitter.call(this);
}
} | [
"function isAnomaly (series) {\n return caseInsensitiveStringSearch(series[0], \"Anomaly\");\n }",
"static GetNearPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] + m[2];\n frustumPlane.normal.y = m[7] + m[6];\n frustumPlane.normal.z = m[11] + m[10];\n frustumPlane.d = m[15] + m[14];\n frustumPlane.normalize();\n }",
"timestampAsLocalString() {\n return this.timestamp().toString();\n }",
"_convertToLocalSpace()\n {\n if (!this._tempLandmarks)\n return null\n\n // clear the Array (and hopefully not to create a new one)\n this._landmarks.splice(0, this._landmarks.length)\n //this._landmarks = []\n\n this._tempLandmarks.forEach((pose, i) => {\n let v = new THREE.Vector3(pose.x, pose.y, pose.z)\n\n // convert to the sceen space\n /*\n v.x = v.x * 2 - 1\n v.y = -v.y * 2 + 1\n v.z = 0\n */\n\n /*\n // making the Head as a center of axes model\n v.x = v.x - this._tempLandmarks[0].x\n v.y = -(v.y - this._tempLandmarks[0].y)\n v.z = -(v.z - this._tempLandmarks[0].z)\n */\n\n // make a repere and convert all points/poses to it\n v.sub(this._reperePosition)\n v.y = -v.y\n v.z = -v.z // invert z to get the mirrar effect\n\n this._landmarks.push(v)\n })\n }",
"function GetTelemetryObj() {\n var myJSON = { \n \"utc\": 0,\n \"soc\": 0,\n \"soh\": 0,\n \"speed\": 0,\n \"car_model\": CAR_MODEL,\n \"lat\": 0,\n \"lon\": 0,\n \"elevation\": 0,\n \"ext_temp\": 0,\n \"is_charging\": 0,\n \"batt_temp\": 0,\n \"voltage\": 0,\n \"current\": 0,\n \"power\": 0\n };\n return myJSON;\n }",
"local() {\n if (this.sources.local !== undefined) {\n return this.satisfying(\"=\" + this.sources.local.version);\n } else {\n return this.newest();\n }\n }",
"function anomalyRanker (series) {\n return isAnomaly(series) ? .7 : 1;\n }",
"function addLocalStream() {\n // if( sender){\n // rtcPeerConn.removeTrack(sender);\n // sender = null;\n // }\n trace('Adding local stream');\n localStream.getTracks().forEach(\n function(track) {\n sender = rtcPeerConn.addTrack(\n track,\n localStream,\n );\n },\n );\n}",
"static ReflectionToRef(plane, result) {\n plane.normalize();\n const x = plane.normal.x;\n const y = plane.normal.y;\n const z = plane.normal.z;\n const temp = -2 * x;\n const temp2 = -2 * y;\n const temp3 = -2 * z;\n Matrix.FromValuesToRef(temp * x + 1, temp2 * x, temp3 * x, 0.0, temp * y, temp2 * y + 1, temp3 * y, 0.0, temp * z, temp2 * z, temp3 * z + 1, 0.0, temp * plane.d, temp2 * plane.d, temp3 * plane.d, 1.0, result);\n }",
"local_compatible() {\n if (this.sources.local !== undefined) {\n return this.satisfying(\"^\" + this.sources.local.version);\n } else {\n return this.newest();\n }\n }",
"function AmbientLight(intensity) {\n\n\tLight.call(this);\n\t\n\tthis.intensity = intensity;\n}",
"constructor(scope, id, props) {\n super(scope, id, { type: CfnAnomalyDetector.CFN_RESOURCE_TYPE_NAME, properties: props });\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_lookoutmetrics_CfnAnomalyDetectorProps(props);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, CfnAnomalyDetector);\n }\n throw error;\n }\n cdk.requireProperty(props, 'anomalyDetectorConfig', this);\n cdk.requireProperty(props, 'metricSetList', this);\n this.attrArn = cdk.Token.asString(this.getAtt('Arn', cdk.ResolutionTypeHint.STRING));\n this.anomalyDetectorConfig = props.anomalyDetectorConfig;\n this.metricSetList = props.metricSetList;\n this.anomalyDetectorDescription = props.anomalyDetectorDescription;\n this.anomalyDetectorName = props.anomalyDetectorName;\n this.kmsKeyArn = props.kmsKeyArn;\n }",
"static GetLeftPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] + m[0];\n frustumPlane.normal.y = m[7] + m[4];\n frustumPlane.normal.z = m[11] + m[8];\n frustumPlane.d = m[15] + m[12];\n frustumPlane.normalize();\n }",
"static GetTopPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] - m[1];\n frustumPlane.normal.y = m[7] - m[5];\n frustumPlane.normal.z = m[11] - m[9];\n frustumPlane.d = m[15] - m[13];\n frustumPlane.normalize();\n }",
"constructor() { \n \n LastStatusInfo.initialize(this);\n }",
"function searchLocal(){\n\t// First call: local\n\t\t$.ajax({\n\t\t\turl: url,\n\t\t\ttype: 'GET',\n\t\t\tsuccess: function(datiString, status, richiesta) {\n\t\t\t\tsuccessAlert(\"Ricerca in corso...\");\t\n\n\t\t\t\tif(datiString.events)\n\t\t\t\t\t$.each(datiString.events, function(index, event){\n\t\t\t\t\t\tvar eventIDRemote = event.event_id;\n\t\t\t\t\t\n\t\t\t\t\t\t// Check if the event already exists in eventArray\n\t\t\t\t\t\tvar result = $.grep(eventArray, function(e){ return e.eventID == eventIDRemote; });\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (result.length == 0) {\n\t\t\t\t\t\t\t// New event from remote server\n\t\t\t\t\t\t \tcreateEvent(event);\n\t\t\t\t\t\t \n\t\t\t\t\t\t} \n\t\t\t\t\t\telse if (result.length == 1) {\n\t\t\t\t\t\t\t// Update local event\n\t\t\t\t\t\t \tupdateEvent(result[0], event, 1, null);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t// Remove spinner animation\n\t\t\t\t$('#spinner').fadeOut(2000, function() { $(this).remove(); });\n\t \t\t},\n\t\t error: function(err) {\n\t\t errorAlert(\"Ajax Search error\");\n\t\t }\n\t\t});\n\t\t$('#search').parent().removeClass('open');\n\t\tif(isiPad) $('#map_canvas').click(); // iPad bugfix\n}",
"constructor() { \n \n TeamEventStatus.initialize(this);\n }",
"function LocalAssociation(resource, connection) {\n /**\n * Constructor for the LocalAssociation local object.\n *\n * @param {object} resource BigML cluster resource\n * @param {object} connection BigML connection\n */\n\n var association, self, fillStructure;\n this.resourceId = utils.getResource(resource);\n if ((typeof this.resourceId) === 'undefined') {\n throw new Error('Cannot build an Association from this resource: '\n + resource);\n }\n\n this.fields = undefined;\n this.invertedFields = undefined;\n this.description = undefined;\n this.locale = undefined;\n this.ready = undefined;\n\n self = this;\n fillStructure = function (error, resource) {\n /**\n * Auxiliary function to load the resource info in the Association\n * structure.\n *\n * @param {object} error Error info\n * @param {object} resource Model's resource info\n */\n var status, fields, field, fieldId, fieldInfo, index, items, itemsLength,\n rules, rulesLength, associations;\n if (error) {\n throw new Error('Cannot create the Association instance. Could not' +\n ' retrieve the resource: ' + error);\n }\n status = utils.getStatus(resource);\n if ((typeof resource.object) !== 'undefined') {\n resource = resource.object;\n }\n if ((typeof resource.associations) !== 'undefined') {\n if (status.code === constants.FINISHED) {\n associations = resource.associations;\n self.complement = associations.complement;\n self.discretization = associations.discretization;\n self.field_discretizations = associations.field_discretizations;\n fields = associations.fields;\n self.items = [];\n items = associations.items;\n itemsLength = items.length;\n for (index = 0; index < itemsLength; index++) {\n self.items.push(new Item(index, items[index], fields));\n }\n self.k = associations.k\n self.max_lhs = associations.max_lhs;\n self.min_coverage = associations.min_coverage\n self.min_leverage = associations.min_leverage\n self.min_strength = associations.min_strength\n self.min_support = associations.min_support\n self.min_lift = associations.min_lift\n self.prune = associations.prune\n self.search_strategy = associations.search_strategy\n rules = associations.rules;\n self.rules = [];\n rules = associations.rules;\n rulesLength = rules.length;\n for (index = 0; index < rulesLength; index++) {\n self.rules.push(new AssociationRule(rules[index]));\n }\n self.significance_level = associations.significance_level;\n self.fields = fields;\n self.invertedFields = utils.invertObject(fields);\n self.description = resource.description;\n self.locale = resource.locale || constants.DEFAULT_LOCALE;\n self.ready = true;\n if (NODEJS) {\n self.emit('ready', self);\n }\n }\n } else {\n throw new Error('Cannot create the Association instance. Could not' +\n ' find the \\'associations\\' key in the resource\\n');\n }\n };\n\n // Loads the association from the association id or from an unfinished object\n if ((NODEJS && ((typeof resource) === 'string')) ||\n utils.getStatus(resource).code !== constants.FINISHED) {\n association = new Association(connection);\n association.get(this.resourceId.resource, true,\n constants.ONLY_MODEL, fillStructure);\n } else {\n // loads when the entire resource is given\n fillStructure(null, resource);\n }\n if (NODEJS) {\n events.EventEmitter.call(this);\n }\n}",
"function eccentricAnomalyToTrueAnomaly(eccentricAnomaly, eccentricity) {\n \n\n // Calculate the number of previous revolutions\n var revs = Math.floor(eccentricAnomaly / CesiumMath.TWO_PI);\n\n // Find angle in current revolution\n eccentricAnomaly -= revs * CesiumMath.TWO_PI;\n\n // Calculate true anomaly from eccentric anomaly\n var trueAnomalyX = Math.cos(eccentricAnomaly) - eccentricity;\n var trueAnomalyY = Math.sin(eccentricAnomaly) * Math.sqrt(1 - eccentricity * eccentricity);\n\n var trueAnomaly = Math.atan2(trueAnomalyY, trueAnomalyX);\n\n // Ensure the correct quadrant\n trueAnomaly = CesiumMath.zeroToTwoPi(trueAnomaly);\n if (eccentricAnomaly < 0)\n {\n trueAnomaly -= CesiumMath.TWO_PI;\n }\n\n // Add on previous revolutions\n trueAnomaly += revs * CesiumMath.TWO_PI;\n\n return trueAnomaly;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Language: Smalltalk Description: Smalltalk is an objectoriented, dynamically typed reflective programming language. | function smalltalk(hljs) {
const VAR_IDENT_RE = '[a-z][a-zA-Z0-9_]*';
const CHAR = {
className: 'string',
begin: '\\$.{1}'
};
const SYMBOL = {
className: 'symbol',
begin: '#' + hljs.UNDERSCORE_IDENT_RE
};
return {
name: 'Smalltalk',
aliases: [ 'st' ],
keywords: 'self super nil true false thisContext', // only 6
contains: [
hljs.COMMENT('"', '"'),
hljs.APOS_STRING_MODE,
{
className: 'type',
begin: '\\b[A-Z][A-Za-z0-9_]*',
relevance: 0
},
{
begin: VAR_IDENT_RE + ':',
relevance: 0
},
hljs.C_NUMBER_MODE,
SYMBOL,
CHAR,
{
// This looks more complicated than needed to avoid combinatorial
// explosion under V8. It effectively means `| var1 var2 ... |` with
// whitespace adjacent to `|` being optional.
begin: '\\|[ ]*' + VAR_IDENT_RE + '([ ]+' + VAR_IDENT_RE + ')*[ ]*\\|',
returnBegin: true,
end: /\|/,
illegal: /\S/,
contains: [ {
begin: '(\\|[ ]*)?' + VAR_IDENT_RE
} ]
},
{
begin: '#\\(',
end: '\\)',
contains: [
hljs.APOS_STRING_MODE,
CHAR,
hljs.C_NUMBER_MODE,
SYMBOL
]
}
]
};
} | [
"static string(v) { return new Typed(_gaurd, \"string\", v); }",
"function pushlex(type, info) {\n var result = function(){\n lexical = new CSharpLexical(indented, column, type, null, lexical, info)\n };\n result.lex = true;\n return result;\n }",
"['@kind']() {\n super['@kind']();\n if (this._value.kind) return;\n\n this._value.kind = 'variable';\n }",
"function makePrimitives(sexpr) {\n var i, value, elems;\n\n if (sexpr.type === 'list') {\n elems = sexpr.value.map(function(s) {\n return makePrimitives(s);\n });\n\n return Data.List(elems);\n }\n\n if (sexpr.type === \"string\") {\n return Data.String(sexpr.value);\n }\n\n if (sexpr.type === 'symbol') {\n return reifySymbol(sexpr);\n }\n\n throw new Error(\"unrecognized s-expression type: \" + sexpr.type);\n }",
"function greeters(Person) {\n return \"Hello\" + Person;\n}",
"_generate(ast) {}",
"function Swift(CodeMirror) {\n function wordSet(words) {\n var set = {};\n for (var i = 0; i < words.length; i++) set[words[i]] = true;\n return set\n }\n\n var keywords = wordSet([\"_\",\"var\",\"let\",\"class\",\"enum\",\"extension\",\"import\",\"protocol\",\"struct\",\"func\",\"typealias\",\"associatedtype\",\n \"open\",\"public\",\"internal\",\"fileprivate\",\"private\",\"deinit\",\"init\",\"new\",\"override\",\"self\",\"subscript\",\"super\",\n \"convenience\",\"dynamic\",\"final\",\"indirect\",\"lazy\",\"required\",\"static\",\"unowned\",\"unowned(safe)\",\"unowned(unsafe)\",\"weak\",\"as\",\"is\",\n \"break\",\"case\",\"continue\",\"default\",\"else\",\"fallthrough\",\"for\",\"guard\",\"if\",\"in\",\"repeat\",\"switch\",\"where\",\"while\",\n \"defer\",\"return\",\"inout\",\"mutating\",\"nonmutating\",\"catch\",\"do\",\"rethrows\",\"throw\",\"throws\",\"try\",\"didSet\",\"get\",\"set\",\"willSet\",\n \"assignment\",\"associativity\",\"infix\",\"left\",\"none\",\"operator\",\"postfix\",\"precedence\",\"precedencegroup\",\"prefix\",\"right\",\n \"Any\",\"AnyObject\",\"Type\",\"dynamicType\",\"Self\",\"Protocol\",\"__COLUMN__\",\"__FILE__\",\"__FUNCTION__\",\"__LINE__\"]);\n var definingKeywords = wordSet([\"var\",\"let\",\"class\",\"enum\",\"extension\",\"import\",\"protocol\",\"struct\",\"func\",\"typealias\",\"associatedtype\",\"for\"]);\n var atoms = wordSet([\"true\",\"false\",\"nil\",\"self\",\"super\",\"_\"]);\n var types = wordSet([\"Array\",\"Bool\",\"Character\",\"Dictionary\",\"Double\",\"Float\",\"Int\",\"Int8\",\"Int16\",\"Int32\",\"Int64\",\"Never\",\"Optional\",\"Set\",\"String\",\n \"UInt8\",\"UInt16\",\"UInt32\",\"UInt64\",\"Void\"]);\n var operators = \"+-/*%=|&<>~^?!\";\n var punc = \":;,.(){}[]\";\n var binary = /^\\-?0b[01][01_]*/;\n var octal = /^\\-?0o[0-7][0-7_]*/;\n var hexadecimal = /^\\-?0x[\\dA-Fa-f][\\dA-Fa-f_]*(?:(?:\\.[\\dA-Fa-f][\\dA-Fa-f_]*)?[Pp]\\-?\\d[\\d_]*)?/;\n var decimal = /^\\-?\\d[\\d_]*(?:\\.\\d[\\d_]*)?(?:[Ee]\\-?\\d[\\d_]*)?/;\n var identifier = /^\\$\\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\\1/;\n var property = /^\\.(?:\\$\\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\\1)/;\n var instruction = /^\\#[A-Za-z]+/;\n var attribute = /^@(?:\\$\\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\\1)/;\n //var regexp = /^\\/(?!\\s)(?:\\/\\/)?(?:\\\\.|[^\\/])+\\//\n\n function tokenBase(stream, state, prev) {\n if (stream.sol()) state.indented = stream.indentation();\n if (stream.eatSpace()) return null\n\n var ch = stream.peek();\n if (ch == \"/\") {\n if (stream.match(\"//\")) {\n stream.skipToEnd();\n return \"comment\"\n }\n if (stream.match(\"/*\")) {\n state.tokenize.push(tokenComment);\n return tokenComment(stream, state)\n }\n }\n if (stream.match(instruction)) return \"builtin\"\n if (stream.match(attribute)) return \"attribute\"\n if (stream.match(binary)) return \"number\"\n if (stream.match(octal)) return \"number\"\n if (stream.match(hexadecimal)) return \"number\"\n if (stream.match(decimal)) return \"number\"\n if (stream.match(property)) return \"property\"\n if (operators.indexOf(ch) > -1) {\n stream.next();\n return \"operator\"\n }\n if (punc.indexOf(ch) > -1) {\n stream.next();\n stream.match(\"..\");\n return \"punctuation\"\n }\n if (ch = stream.match(/(\"{3}|\"|')/)) {\n var tokenize = tokenString(ch[0]);\n state.tokenize.push(tokenize);\n return tokenize(stream, state)\n }\n\n if (stream.match(identifier)) {\n var ident = stream.current();\n if (types.hasOwnProperty(ident)) return \"variable-2\"\n if (atoms.hasOwnProperty(ident)) return \"atom\"\n if (keywords.hasOwnProperty(ident)) {\n if (definingKeywords.hasOwnProperty(ident))\n state.prev = \"define\";\n return \"keyword\"\n }\n if (prev == \"define\") return \"def\"\n return \"variable\"\n }\n\n stream.next();\n return null\n }\n\n function tokenUntilClosingParen() {\n var depth = 0;\n return function(stream, state, prev) {\n var inner = tokenBase(stream, state, prev);\n if (inner == \"punctuation\") {\n if (stream.current() == \"(\") ++depth;\n else if (stream.current() == \")\") {\n if (depth == 0) {\n stream.backUp(1);\n state.tokenize.pop();\n return state.tokenize[state.tokenize.length - 1](stream, state)\n }\n else --depth;\n }\n }\n return inner\n }\n }\n\n function tokenString(quote) {\n var singleLine = quote.length == 1;\n return function(stream, state) {\n var ch, escaped = false;\n while (ch = stream.next()) {\n if (escaped) {\n if (ch == \"(\") {\n state.tokenize.push(tokenUntilClosingParen());\n return \"string\"\n }\n escaped = false;\n } else if (stream.match(quote)) {\n state.tokenize.pop();\n return \"string\"\n } else {\n escaped = ch == \"\\\\\";\n }\n }\n if (singleLine) {\n state.tokenize.pop();\n }\n return \"string\"\n }\n }\n\n function tokenComment(stream, state) {\n var ch;\n while (true) {\n stream.match(/^[^/*]+/, true);\n ch = stream.next();\n if (!ch) break\n if (ch === \"/\" && stream.eat(\"*\")) {\n state.tokenize.push(tokenComment);\n } else if (ch === \"*\" && stream.eat(\"/\")) {\n state.tokenize.pop();\n }\n }\n return \"comment\"\n }\n\n function Context(prev, align, indented) {\n this.prev = prev;\n this.align = align;\n this.indented = indented;\n }\n\n function pushContext(state, stream) {\n var align = stream.match(/^\\s*($|\\/[\\/\\*])/, false) ? null : stream.column() + 1;\n state.context = new Context(state.context, align, state.indented);\n }\n\n function popContext(state) {\n if (state.context) {\n state.indented = state.context.indented;\n state.context = state.context.prev;\n }\n }\n\n CodeMirror.defineMode(\"swift\", function(config) {\n return {\n startState: function() {\n return {\n prev: null,\n context: null,\n indented: 0,\n tokenize: []\n }\n },\n\n token: function(stream, state) {\n var prev = state.prev;\n state.prev = null;\n var tokenize = state.tokenize[state.tokenize.length - 1] || tokenBase;\n var style = tokenize(stream, state, prev);\n if (!style || style == \"comment\") state.prev = prev;\n else if (!state.prev) state.prev = style;\n\n if (style == \"punctuation\") {\n var bracket = /[\\(\\[\\{]|([\\]\\)\\}])/.exec(stream.current());\n if (bracket) (bracket[1] ? popContext : pushContext)(state, stream);\n }\n\n return style\n },\n\n indent: function(state, textAfter) {\n var cx = state.context;\n if (!cx) return 0\n var closing = /^[\\]\\}\\)]/.test(textAfter);\n if (cx.align != null) return cx.align - (closing ? 1 : 0)\n return cx.indented + (closing ? 0 : config.indentUnit)\n },\n\n electricInput: /^\\s*[\\)\\}\\]]$/,\n\n lineComment: \"//\",\n blockCommentStart: \"/*\",\n blockCommentEnd: \"*/\",\n fold: \"brace\",\n closeBrackets: \"()[]{}''\\\"\\\"``\"\n }\n });\n\n CodeMirror.defineMIME(\"text/x-swift\",\"swift\");\n }",
"function SentientBeing(planet, language) {\n // TODO: specify a home planet and a language\n // you'll need to add parameters to this constructor\n this.planet = planet;\n this.language = language;\n this.sayHello = function(sb) {\n console.log(hello[this.language]);\n return hello[sb.language];\n }.bind(this);\n}",
"Super() {\n this._eat(\"super\");\n return {\n type: \"Super\",\n };\n }",
"function ProgramParser() {\n \t\t\n \t\t this.parse = function(kind) {\n \t\t \tswitch (kind) { \t\n \t\t \t\tcase \"declaration\": return Declaration();\n \t\t \t\tbreak;\n\t \t\t\tdefault: return Program();\n\t \t\t}\n\t \t}\n \t\t\n \t\t// Import Methods from the expression Parser\n \t\tfunction Assignment() {return expressionParser.Assignment();}\n \t\tfunction Expr() {return expressionParser.Expr();}\n \t\tfunction IdentSequence() {return expressionParser.IdentSequence();}\n \t\tfunction Ident(forced) {return expressionParser.Ident(forced);}\t\t\n \t\tfunction EPStatement() {return expressionParser.Statement();}\n\n\n\t\tfunction whatNext() {\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"class\"\t\t: \n \t\t\t\tcase \"function\"\t \t: \n \t\t\t\tcase \"structure\"\t:\n \t\t\t\tcase \"constant\" \t:\n \t\t\t\tcase \"variable\" \t:\n \t\t\t\tcase \"array\"\t\t: \treturn lexer.current.content;\t\n \t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\tdefault\t\t\t\t:\treturn lexer.lookAhead().content;\n \t\t\t}\n\t\t}\n\n// \t\tDeclaration\t:= {Class | Function | VarDecl | Statement} \n\t\tfunction Declaration() {\n\t\t\tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"class\"\t: return Class();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\" : return Function();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"structure\" : return StructDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"array\"\t: return ArrayDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"constant\" :\n \t\t\t\t\tcase \"variable\" : return VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: return false;\n \t\t\t }\n\t\t}\n\n// \t\tProgram\t:= {Class | Function | VarDecl | Structure | Array | Statement} \n//\t\tAST: \"program\": l: {\"function\" | \"variable\" ... | Statement} indexed from 0...x\n\t\tthis.Program=function() {return Program()};\n \t\tfunction Program() {\n \t\t\tdebugMsg(\"ProgramParser : Program\");\n \t\t\tvar current;\n \t\t\tvar ast=new ASTListNode(\"program\");\n \t\t\t\n \t\t\tfor (;!eof();) {\n \t\t\t\t\n \t\t\t\tif (!(current=Declaration())) current=Statement();\n \t\t\t\t\n \t\t\t\tif (!current) break;\n \t\t\t\t\n \t\t\t\tast.add(current);\t\n \t\t\t} \t\t\t\n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tClass:= \"class\" Ident [\"extends\" Ident] \"{\" [\"constructor\" \"(\" Ident Ident \")\"] CodeBlock {VarDecl | Function}\"}\"\n//\t\tAST: \"class\" : l: name:Identifier,extends: ( undefined | Identifier),fields:VarDecl[0..i], methods:Function[0...i]\n\t\tfunction Class() {\n\t\t\tdebugMsg(\"ProgramParser : Class\");\n\t\t\tlexer.next();\n\n\t\t\tvar name=Ident(true);\t\t\t\n\t\t\t\n\t\t\tvar extend={\"content\":undefined};\n\t\t\tif(test(\"extends\")) {\n\t\t\t\tlexer.next();\n\t\t\t\textend=Ident(true);\n\t\t\t}\n\t\t\t\n\t\t\tcheck (\"{\");\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\t\n\t\t\tvar methods=[];\n\t\t\tvar fields=[];\n\t\t\t\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tlexer.next();\n\t\t \t\t//var retType={\"type\":\"ident\",\"content\":\"_$any\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tvar constructName={\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tmethods.push(FunctionBody(name,constructName));\n\t\t\t}\n\t\t\t\n\t\t\tvar current=true;\n\t\t\twhile(!test(\"}\") && current && !eof()) {\n\t\t\t\t \t\n\t\t \tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\"\t: methods.push(Function()); \n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\" : fields.push(VarDecl(true));\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: current=false;\n \t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tcheck(\"}\");\n\t\t\t\n\t\t\tmode.terminatorOff();\n\n\t\t\tsymbolTable.closeScope();\n\t\t\tsymbolTable.addClass(name.content,extend.content,scope);\n\t\t\t\n\t\t\treturn new ASTUnaryNode(\"class\",{\"name\":name,\"extends\":extend,\"scope\":scope,\"methods\":methods,\"fields\":fields});\n\t\t}\n\t\t\n //\t\tStructDecl := \"structure\" Ident \"{\" VarDecl {VarDecl} \"}\"\n //\t\tAST: \"structure\" : l: \"name\":Ident, \"decl\":[VarDecl], \"scope\":symbolTable\n \t\tfunction StructDecl() {\n \t\t\tdebugMsg(\"ProgramParser : StructDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true); \n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\tmode.terminatorOn();\n \t\t\t\n \t\t\tvar decl=[];\n \t\t\t\n \t\t\tvar scope=symbolTable.openScope();\t\n \t\t\tdo {\t\t\t\t\n \t\t\t\tdecl.push(VarDecl(true));\n \t\t\t} while(!test(\"}\") && !eof());\n \t\t\t\n \t\t\tmode.terminatorOff();\n \t\t\tcheck (\"}\");\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\tsymbolTable.addStruct(name.content,scope);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"structure\",{\"name\":name,\"decl\":decl,\"scope\":scope});\n \t\t} \n \t\t\n //\tarrayDecl := \"array\" Ident \"[\"Ident\"]\" \"contains\" Ident\n //\t\tAST: \"array\" : l: \"name\":Ident, \"elemType\":Ident, \"indexTypes\":[Ident]\n \t\tfunction ArrayDecl() {\n \t\t\tdebugMsg(\"ProgramParser : ArrayDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\tcheck(\"[\");\n \t\t\t\t\n \t\t\tvar ident=Ident(!mode.any);\n \t\t\tif (!ident) ident=lexer.anyLiteral();\n \t\t\t\t\n \t\t\tvar indexType=ident;\n \t\t\t\t\n \t\t\tvar bound=ident.content;\n \t\t\t\t\n \t\t\tcheck(\"]\");\n \t\t\t\t\n \t\t\tvar elemType; \t\n \t\t\tif (mode.any) {\n \t\t\t\tif (test(\"contains\")) {\n \t\t\t\t\tlexer.next();\n \t\t\t\t\telemType=Ident(true);\n \t\t\t\t}\n \t\t\t\telse elemType=lexer.anyLiteral();\n \t\t\t} else {\n \t\t\t\tcheck(\"contains\");\n \t\t\t\telemType=Ident(true);\n \t\t\t}\n \t\t\t\n \t\t\tcheck (\";\");\n \t\t\tsymbolTable.addArray(name.content,elemType.content,bound);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"array\",{\"name\":name,\"elemType\":elemType,\"indexType\":indexType});\n \t\t} \n \t\t\n//\t\tFunction := Ident \"function\" Ident \"(\" [Ident Ident {\"[\"\"]\"} {\",\" Ident Ident {\"[\"\"]\"}) } \")\" CodeBlock\n//\t\tAST: \"function\":\tl: returnType: (Ident | \"_$\"), name:name, scope:SymbolTable, param:{name:Ident,type:Ident}0..x, code:CodeBlock \n\t\tthis.Function=function() {return Function();}\n \t\tfunction Function() {\n \t\t\tdebugMsg(\"ProgramParser : Function\");\n \t\t\n \t\t\tvar retType;\n \t\t\tif (mode.decl) retType=Ident(!(mode.any));\n \t\t\tif (!retType) retType=lexer.anyLiteral();\n \t\t\t\n \t\t\tcheck(\"function\");\n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\treturn FunctionBody(retType,name);\n \t\t}\n \t\t\n \n \t\t// The Body of a function, so it is consistent with constructor\n \t\tfunction FunctionBody(retType,name)\t{\n \t\t\tvar scope=symbolTable.openScope();\n \t\t\t\n \t\t\tif (!test(\"(\")) error.expected(\"(\");\n \t\t\n var paramList=[];\n var paramType=[];\n var paramExpected=false; //Indicates wether a parameter is expected (false in the first loop, then true)\n do {\n \t\t\tlexer.next();\n \t\t\t\n \t\t\t/* Parameter */\n \t\t\tvar pName,type;\n \t\t\tvar ident=Ident(paramExpected);\t// Get an Identifier\n \t\t\tparamExpected= true;\n \t\t\t\n \t\t\t// An Identifier is found\n \t\t\tif (ident) {\n \t\t\t\t\n \t\t\t\t// When declaration is possible\n \t\t\t\tif (mode.decl) {\n \t\t\t\t\t\n \t\t\t\t\t// One Identifier found ==> No Type specified ==> indent specifies Param Name\n \t\t\t\t\tif (!(pName=Ident(!(mode.any)))) {\n \t\t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\t\tpName=ident;\n \t\t\t\t\t} else type=ident; // 2 Identifier found\n \t\t\t\t} else {\t// Declaration not possible\n \t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\tpName=ident;\n \t\t\t\t}\t\n\n\t\t\t\t\t// Store Parameter\n\t\t\t\t\tparamType.push(type); \n \t\tparamList.push({\"name\":pName,\"type\":type});\n \t\t \n \t\t \tsymbolTable.addVar(pName.content,type.content);\n \t\t} \n \t\t} while (test(\",\") && !eof());\n\n \tcheck(\")\");\n \t\t\t \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\t\n \t\t\tsymbolTable.addFunction(name.content,retType.content,paramType);\n \t\t\treturn new ASTUnaryNode(\"function\",{\"name\":name,\"scope\":scope,\"param\":paramList,\"returnType\":retType,\"code\":code});\n \t\t}\n \t\t\t\n\t\t\n //\t\tVarDecl := Ident (\"variable\" | \"constant\") Ident [\"=\" Expr] \";\" \n //\t\tAST: \"variable\"|\"constant\": l : type:type, name:name, expr:[expr]\n \t\tthis.VarDecl = function() {return VarDecl();}\n \t\tfunction VarDecl(noInit) {\n \t\t\tdebugMsg(\"ProgramParser : VariableDeclaration\");\n \t\t\tvar line=lexer.current.line;\n \t\t\tvar type=Ident(!mode.any);\n \t\t\tif (!type) type=lexer.anyLiteral();\n \t\t\t\n \t\t\tvar constant=false;\n \t\t\tvar nodeName=\"variable\";\n \t\t\tif (test(\"constant\")) {\n \t\t\t\tconstant=true; \n \t\t\t\tnodeName=\"constant\";\n \t\t\t\tlexer.next();\n \t\t\t}\n \t\t\telse check(\"variable\"); \n \t\t\t \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\tsymbolTable.addVar(name.content,type.content,constant);\n\n\t\t\tvar expr=null;\n\t\t\tif(noInit==undefined){\n\t\t\t\tif (test(\"=\")) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\texpr=Expr();\n\t\t\t\t\tif (!expr) expr=null;\n\t\t\t\t}\n\t\t\t} \n\t\n\t\t\tcheck(\";\");\n\t\t\tvar ast=new ASTUnaryNode(nodeName,{\"type\":type,\"name\":name,\"expr\":expr});\n\t\t\tast.line=line;\n\t\t\treturn ast;\n \t\t}\n \t\t\t\t\n//\t\tCodeBlock := \"{\" {VarDecl | Statement} \"}\" \n//\t\tCodeblock can take a newSymbolTable as argument, this is needed for functions that they can create an scope\n//\t\tcontaining the parameters.\n//\t\tIf newSymbolTable is not specified it will be generated automatical\n// At the End of Codeblock the scope newSymbolTable will be closed again\t\t\n//\t\tAST: \"codeBlock\" : l: \"scope\":symbolTable,\"code\": code:[0..x] {code}\n \t\tfunction CodeBlock() {\n \t\t\tdebugMsg(\"ProgramParser : CodeBlock\");\n\t\t\t\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\tvar begin=lexer.current.line;\n\t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar code=[];\n \t\t\tvar current;\n\n \t\t\twhile(!test(\"}\") && !eof()) {\n \t\t\t\tswitch (whatNext()) {\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\": current=VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault: current=Statement();\t\t\t\t\t\n \t\t\t\t}\n\n \t\t\t\tif(current) {\n \t\t\t\t\tcode.push(current);\n \t\t\t\t} else {\n \t\t\t\t\terror.expected(\"VarDecl or Statement\"); break;\n \t\t\t\t}\n \t\t\t}\t\n \t\t\t\n \t\t\tvar end=lexer.current.line;\n \t\t\tcheck(\"}\");\n \t\t\tsymbolTable.closeScope();\n \t\t\treturn new ASTUnaryNode(\"codeBlock\",{\"scope\":scope,\"code\":code,\"begin\":begin,\"end\":end});\n \t\t}\n \t\t\n//\t\tStatement\t:= If | For | Do | While | Switch | JavaScript | (Return | Expr | Assignment) \";\"\n \t\tfunction Statement() {\n \t\t\tdebugMsg(\"ProgramParser : Statement\");\n \t\t\tvar ast;\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"if\"\t \t\t: ast=If(); \n\t \t\t\tbreak;\n \t\t\t\tcase \"do\"\t \t\t: ast=Do(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"while\" \t\t: ast=While(); \t\t\n \t\t\t\tbreak;\n \t\t\t\tcase \"for\"\t\t\t: ast=For();\n \t\t\t\tbreak;\n \t\t\t\tcase \"switch\"\t\t: ast=Switch(); \t\n \t\t\t\tbreak;\n \t\t\t\tcase \"javascript\"\t: ast=JavaScript(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"return\"\t\t: ast=Return(); \n \t\t\t\t\t\t\t\t\t\t check(\";\");\n \t\t\t\tbreak;\n \t\t\t\tdefault\t\t\t\t: ast=EPStatement(); \n \t\t\t\t\t check(\";\");\n \t\t\t}\n \t\t\tast.line=line;\n \t\t\tast.comment=lexer.getComment();\n \t\t\tlexer.clearComment(); \t\t\t\n \t\t\treturn ast;\t\n \t\t}\n \t\t\n//\t\tIf := \"if\" \"(\" Expr \")\" CodeBlock [\"else\" CodeBlock]\n//\t\tAST : \"if\": l: cond:Expr, code:codeBlock, elseBlock:(null | codeBlock)\n \t\tfunction If() {\n \t\t\tdebugMsg(\"ProgramParser : If\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tvar elseCode;\n \t\t\tif (test(\"else\")) {\n \t\t\t\tlexer.next();\n \t\t\t\telseCode=CodeBlock();\n \t\t\t}\n \t\t\treturn new ASTUnaryNode(\"if\",{\"cond\":expr,\"code\":code,\"elseBlock\":elseCode});\n \t\t}\n \t\t\n// \t\tDo := \"do\" CodeBlock \"while\" \"(\" Expr \")\" \n//\t\tAST: \"do\": l:Expr, r:CodeBlock \n \t\tfunction Do() {\t\n \t\t\tdebugMsg(\"ProgramParser : Do\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tcheck(\"while\");\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\t\n \t\t\tcheck(\";\");\n\n \t\t\treturn new ASTBinaryNode(\"do\",expr,code);\n \t\t}\n \t\t\n// \t\tWhile := \"while\" \"(\" Expr \")\" \"{\" {Statement} \"}\" \n//\t\tAST: \"while\": l:Expr, r:codeBlock\n \t\tfunction While(){ \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : While\");\n \t\t\t\n \t\t\t//if do is allowed, but while isn't allowed gotta check keyword in parser\n \t\t\tif (preventWhile) error.reservedWord(\"while\",lexer.current.line);\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code = CodeBlock();\n \t\t\t\t \t\t\t\n \t\t\treturn new ASTBinaryNode(\"while\",expr,code);\n \t\t}\n \t\t\n//\t\tFor := \"for\" \"(\"(\"each\" Ident \"in\" Ident | Ident Assignment \";\" Expr \";\" Assignment )\")\"CodeBlock\n//\t\tAST: \"foreach\": l: elem:Ident, array:Ident, code:CodeBlock \n//\t\tAST: \"for\": l: init:Assignment, cond:Expr,inc:Assignment, code:CodeBlock\n \t\tfunction For() { \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : For\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tif (test(\"each\")) {\n \t\t\t\tlexer.next();\n \t\t\t\tvar elem=IdentSequence();\n \t\t\t\tcheck(\"in\");\n \t\t\t\tvar arr=IdentSequence();\n \t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\t\n \t\t\t\tvar code=CodeBlock();\n \t\t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"foreach\",{\"elem\":elem,\"array\":arr,\"code\":code});\n \t\t\t\t\n \t\t\t} else {\n \t\t\t\tvar init=Assignment();\n \t\t\t\tif (!init) error.assignmentExpected();\n \t\t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\t\n \t\t\t\tvar cond=Expr();\n \t\t\t\n \t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\n \t\t\t\tvar increment=Assignment();\n \t\t\t\tif (!increment) error.assignmentExpected();\n \t\t\t \n \t\t\t\tcheck(\")\");\n \t\t\t\tvar code=CodeBlock();\t\n \t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"for\",{\"init\":init,\"cond\":cond,\"inc\":increment,\"code\":code});\n \t\t\t}\t\n \t\t}\n \t\t\n//\t\tSwitch := \"switch\" \"(\" Ident \")\" \"{\" {Option} [\"default\" \":\" CodeBlock] \"}\"\t\n// AST: \"switch\" : l \"ident\":IdentSequence,option:[0..x]{Option}, default:CodeBlock\n \t\tfunction Switch() {\t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Switch\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) error.identifierExpected();\n \t\t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar option=[];\n \t\t\tvar current=true;\n \t\t\tfor (var i=0;current && !eof();i++) {\n \t\t\t\tcurrent=Option();\n \t\t\t\tif (current) {\n \t\t\t\t\toption[i]=current;\n \t\t\t\t}\n \t\t\t}\n \t\t\tcheck(\"default\");\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar defBlock=CodeBlock();\n \t\t \t\t\t\n \t\t\tcheck(\"}\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"switch\", {\"ident\":ident,\"option\":option,\"defBlock\":defBlock});\n \t\t}\n \t\t\n//\t\tOption := \"case\" Expr {\",\" Expr} \":\" CodeBlock\n// AST: \"case\" : l: [0..x]{Expr}, r:CodeBlock\n \t\tfunction Option() {\n \t\t\tif (!test(\"case\")) return false;\n \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Option\");\n \t\t\t\n \t\t\tvar exprList=[];\n \t\t\tvar i=0;\n \t\t\tdo {\n \t\t\t\tlexer.next();\n \t\t\t\t\n \t\t\t\texprList[i]=Expr();\n \t\t\t\ti++; \n \t\t\t\t\n \t\t\t} while (test(\",\") && !eof());\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"case\",exprList,code);\n \t\t}\n \t\t\n// JavaScript := \"javascript\" {Letter | Digit | Symbol} \"javascript\"\n//\t\tAST: \"javascript\": l: String(JavascriptCode)\n \t\tfunction JavaScript() {\n \t\t\tdebugMsg(\"ProgramParser : JavaScript\");\n\t\t\tcheck(\"javascript\");\n\t\t\tcheck(\"(\")\n\t\t\tvar param=[];\n\t\t\tvar p=Ident(false);\n\t\t\tif (p) {\n\t\t\t\tparam.push(p)\n\t\t\t\twhile (test(\",\") && !eof()) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\tparam.push(Ident(true));\n\t\t\t\t}\t\n\t\t\t}\n \t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\tvar js=lexer.current.content;\n \t\t\tcheckType(\"javascript\");\n \t\t\t\t\t\t\n \t\t\treturn new ASTUnaryNode(\"javascript\",{\"param\":param,\"js\":js});\n \t\t}\n \t\t\n// \t\tReturn := \"return\" [Expr] \n//\t\tAST: \"return\" : [\"expr\": Expr] \n \t\tfunction Return() {\n \t\t\tdebugMsg(\"ProgramParser : Return\");\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tvar ast=new ASTUnaryNode(\"return\",expr);\n \t\t\tast.line=line;\n \t\t\treturn ast;\n \t\t}\n\t}",
"function personFromPersonStore(name, age) {\n // add code here\n this.name=name;\n this.age=age;\n this.greet=function () {\n showMsg(`hello`)\n}\n return Object.create(this) \n}",
"function TamperLang() {\n this.init();\n}",
"enterTypeVariable(ctx) {\n\t}",
"function analyze(stmt) {\n return is_self_evaluating(stmt)\n ? (env, succeed, fail) => succeed(stmt, fail)\n : is_name(stmt)\n ? analyze_name(stmt)\n : is_constant_declaration(stmt)\n ? analyze_constant_declaration(stmt)\n : is_variable_declaration(stmt)\n ? analyze_variable_declaration(stmt)\n : is_assignment(stmt)\n ? analyze_assignment(stmt)\n : is_conditional_expression(stmt)\n ? analyze_conditional_expression(stmt)\n : is_function_definition(stmt)\n ? analyze_function_definition(stmt)\n : is_sequence(stmt)\n ? analyze_sequence(sequence_statements(stmt))\n : is_block(stmt)\n ? analyze_block(stmt)\n : is_return_statement(stmt)\n ? analyze_return_statement(stmt)\n : is_amb(stmt)\n ? analyze_amb(stmt)\n : is_require(stmt)\n ? analyze_require(stmt)\n : is_application(stmt)\n ? analyze_application(stmt)\n : is_boolean_operation(stmt)\n ? analyze_boolean_op(stmt)\n : error(stmt, \"Unknown statement type in analyze\");\n}",
"enterSimpleTypeName(ctx) {\n\t}",
"function STLangVisitor() {\n STLangParserVisitor.call(this);\n this.result = {\n \"valid\": true,\n \"error\": null,\n \"tree\": {\n \"text\": \"\",\n \"children\": null\n }\n };\n\treturn this;\n}",
"function createMyObject() {\n return{\n foo:'bar',\n answerToUniverse: 42,\n \"olly olly\": 'oxen free',\n sayHello: function(){\n \treturn 'hello';\n }\n };\n}",
"function cast(type) {\n var members = [],\n count = app.state[type],\n constructor;\n\n for (var c = 0; c < count; c++) {\n constructor = type.caps().single();\n members.push(new app[constructor]({\n id: self.serial++,\n onDeath: self.remove\n }));\n }\n\n // add to the cast\n self.array = self.array.concat(members);\n\n // assign global name shortcuts\n app[type] = members;\n app[type].each = function(callback) {\n self.select(type, callback);\n };\n\n }",
"function Reflect () {\n //\n }",
"function saliency() {\n\n\tvar conceptCount = countConcepts(); // go through each predication and add the subject/object to an array returned with total and unique counts\n\tvar avgActivationWeight = computeAvgActivationWeight(conceptCount); // use the counts from above to calc the average count for all\n\n\tsetSC1(conceptCount, avgActivationWeight); \t\t\t\t\t\t// map counts >= average to true and rest to false\n\n\t// Calculate SC3 - repeat SC1 using the unique predications count\n\tsetAvgSumOther(conceptCount); \t// calc average of all other concepts for each concept\n\tsetSC3(conceptCount); \t// SC3 is SC2 of concepts from unique predications\n\tsetSalient(conceptCount); // set summaryLinks[i].predicate[j].salient = true if subj AND obj both true by SC1 or SC3.\n\n/* not in production version\n\tvar predicationCount = countPredications();\n\tbalancePredications(predicationCount);\n\tcomputeSRC1(predicationCount);\n\treturn join of conceptCount.SC1==true, uniqueConceptCount.SC3==true, relationCount??? and predicationCount.SRC1==true;\n*/\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Product Page Set pref, link page | function productPage (itm, cst) {
pref.product = {item: itm, cost: cst};
storePref();
window.location.href = '../pages/product.html';
} | [
"function showProductsScreen() {\n\t//Show next page\n\tif($(\"#js-table\").attr(\"data-extractUrl\")){\n\t\t$(\"section.jsContainer #extractResults\").text(\"Extract Next Page\");\n\t\t$(\"section.jsContainer #extractResults\").fadeIn();\n\t}else{\n\t\t$(\"section.jsContainer #extractResults\").css(\"display\",\"none\");\n\t}\n\t\n\t$(\"section.jsContainer .main-screen\").css(\"display\",\"none\");\n\t$(\"section.jsContainer .export-section\").fadeIn();\n\t$(\"section.jsContainer #js-table\").fadeIn();\n}",
"function renderSingleProductPage (index, data) {\n var page = $('.single-product'),\n c = $('.single-product .preview-large');\n\n data.forEach(function (item) {\n if (parseInt(index, 10) === parseInt(item.id, 10)) {\n c.find('h3').text(item.title);\n c.find('img').attr('src', 'http://farm7.staticflickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_z.jpg');\n }\n });\n page.addClass('visible');\n }",
"function renderSingleProductPage(index, data) {\n var page = $('.single-product'),\n container = $('.preview-large');\n\n // Find the wanted product by iterating the data object and searching for the chosen index.\n if (data.length) {\n data.forEach(function(item) {\n if (item.id == index) {\n // Populate '.preview-large' with the chosen product's data.\n container.find('h3').text(item.title);\n container.find('img').attr('src', item.thumbnail);\n container.find('p').text(item.title);\n container.find('#li1').text(item.condition);\n container.find('#li2').text(item.available_quantity);\n container.find('#li3').text(item.address.state_name);\n container.find('#li4').text(`${item.price}$`);\n container.find('a').attr('precio', item.price);\n container.find('a').attr('titulo', item.title);\n // class=\"waves-effect waves-light btn deep-purple darken-4 producto\"\n // precio=\"${item.price}\" titulo=\"${item.price}\" ><i class=\"material-icons right\">add_shopping_cart</i>Añadir`);\n }\n });\n }\n\n // Show the page.\n page.addClass('visible');\n}",
"function replaceUrl(id){\r\n\t$.ajax({\r\n\t\turl : 'https://api.digitalriver.com/v1/shoppers/me/products?expand=product.customAttributes.pdPageURL&apiKey=5de150dc29228095f9811cdf15ea5938&productId='+id,\r\n\t\tdataType: 'xml',\r\n\t\terror : function() {\r\n\t\t\tconsole.log(\"Error to get pdp page of product \"+id);\r\n\t\t},\r\n\t\tsuccess : function(products) {\r\n\t\t\tvar pdp_link = $(products).find(\"customAttributes\").find(\"attribute[name='pdPageURL']\").text();\r\n\t\t\twindow.location.href = pdp_link;\r\n\t\t}\r\n\t});\r\n}",
"function SetSideMenuContentForPositivePay(selectedPage,id)\r\n{\r\n var rc, rc1, rc2, rc3;\r\n rc = showMenuItem('positive');\r\n rc1 = showMenuItem('pospayissue');\r\n rc2 = showMenuItem('pospayexception');\r\n rc3 = showMenuItem('revpospay');\r\n var temp = '<li>';\r\n var temp1 = '<li class=\"leftContentListNavSelected\">';\r\n var str = '';\r\n\r\n if (rc3 == '1' || (rc == '1' && rc2 == '1')) {\r\n if (selectedPage == 'exception') str += temp1; else str += temp;\r\n str += '<a href=\"../positive_pay/except.html\">Positive pay exceptions manager<\\/a><\\/li>';\r\n }\r\n\r\n if (rc == '1' && rc1 == '1') {\r\n if(selectedPage == 'issue')str += temp1;else str += temp;\r\n str += '<a href=\"../positive_pay/entry.html\">Positive pay issue entry<\\/a><\\/li>';\r\n }\r\n if (rc == '1' && rc1 == '1') {\r\n if (selectedPage == 'import') str += temp1; else str += temp;\r\n str += '<a href=\"../positive_pay/import.html\">Positive pay issue file import<\\/a><\\/li>';\r\n }\r\n if (rc3 == '1' || (rc == '1' && rc2 == '1')){\r\n if (selectedPage == 'decision_import') str += temp1; else str += temp;\r\n str += '<a href=\"../positive_pay/decision_import.html\">Positive pay decision file import<\\/a><\\/li>';\r\n }\r\n if (rc == '1' && rc1 == '1') {\r\n if (selectedPage == 'update') str += temp1; else str += temp;\r\n\t str += '<a href=\"../positive_pay/update.html\">Positive pay update issue<\\/a><\\/li>';\r\n }\r\n if (rc == '1' && rc1 == '1') {\r\n if(selectedPage == 'approval')str += temp1;else str += temp;\r\n\t str += '<a href=\"../positive_pay/issue_approval.html\">Positive pay issue approval<\\/a><\\/li>';\r\n }\r\n if (rc == '1' || rc3 == '1') {\r\n if(selectedPage == 'decision')str += temp1;else str += temp;\r\n\t str += '<a href=\"../positive_pay/decision.html\">Positive pay decisions report<\\/a><\\/li>';\r\n }\r\n if (rc == '1' ) {\r\n if(selectedPage == 'oustanding')str += temp1;else str += temp;\r\n\t str += '<a href=\"../positive_pay/outstand.html\">Positive pay outstanding issues report<\\/a><\\/li>';\r\n }\r\n if (rc == '1' ) {\r\n if(selectedPage == 'stale')str += temp1;else str += temp;\r\n\t str += '<a href=\"../positive_pay/stale.html\">Positive pay stale issues report<\\/a><\\/li>';\r\n }\r\n if (rc == '1' ) {\r\n if(selectedPage == 'status')str += temp1;else str += temp;\r\n\t str += '<a href=\"../positive_pay/issue.html\">Positive pay issue status report<\\/a><\\/li>';\r\n }\r\n if (rc3 == '1' || (rc == '1' && rc2 == '1')) {\r\n if (selectedPage == 'decision_approval') str += temp1; else str += temp;\r\n\t str += '<a href=\"../positive_pay/decision_approval.html\">Positive pay decision file approval<\\/a><\\/li>';\r\n }\r\n\r\n helpwriteContent(id,str)\r\n}",
"function setImagePage(){\r\n setPage('image-page');\r\n }",
"function _page2_page() {\n}",
"function settingPage(autoSave = autoSaveGET,useLibraryJS = useLibraryJSGET,language = languageGET) {\n\t\t//___CREATED obj SETTING___\n\t\tvar objSetting = {\n\t\t\t'autoSave': autoSave,\n\t\t\t'useLibraryJS': useLibraryJSGET,\n\t\t\t'language': languageGET\n\t\t}\n\t\t//___SET STORAGE SETTING___\n\t\tstorageSET('settingPage',objSetting);\n\t}",
"function updateAnalyticsPageName(pageName, prodName, workId) {\n\tif(typeof s_setP !== 'undefined' && typeof s_getP !== 'undefined') {\n var setPageName = typeof pageName !== 'undefined' ? pageName.toLowerCase() : '',\n isModal = setPageName !== '' ? true : false,\n setPageType = '',\n isProductTypeModal = false;\n\n switch($.trim(setPageName)) {\n case 'login':\n setPageName = 'sign in';\n break;\n case 'register':\n setPageName = 'create account';\n break;\n case 'add-to-wishlist':\n setPageName = 'add to wishlist';\n break;\n case 'quickview':\n setPageName = 'quickview';\n isProductTypeModal = true;\n break;\n case 'marketplace':\n setPageName = 'marketplace';\n isProductTypeModal = true;\n break;\n case 'allformats':\n setPageName = 'all formats';\n isProductTypeModal = true;\n break;\n case 'puis':\n setPageName = 'instore pickup';\n break;\n case 'puis-tooltip':\n setPageName = 'instore pickup tooltip';\n break;\n case 'kc-create-account-s1':\n setPageName = 'kid\\'s club create account step 1';\n break;\n case 'kc-create-account-s3':\n setPageName = 'kid\\'s club create account step 2';\n break;\n case 'kc-create-account-s4':\n setPageName = 'kid\\'s club create account step welcome';\n break;\n case 'kc-manage-edit-child':\n setPageName = 'kid\\'s club edit child';\n break;\n case 'kc-manage-add-child':\n setPageName = 'kid\\'s club add child';\n break;\n case 'm-kids-club-info':\n setPageName = 'kid\\'s club info';\n break;\n case 'm-kids-club-detail':\n setPageName = 'kid\\'s club your loyalty rewards';\n break;\n case 'm-used-saved-address':\n setPageName = 'saved shipping address';\n break;\n case 'm-add-shipping':\n setPageName = 'add shipping address';\n break;\n case 'm-use-saved-cc':\n setPageName = 'saved credit card';\n break;\n case 'm-add-cc':\n setPageName = 'add credit card';\n break;\n case 'member-sign-up':\n setPageName = 'n&n membership offer';\n break;\n case 'editpayment':\n setPageName = 'edit payment method';\n break;\n case 'delete-payment':\n setPageName = 'delete payment method';\n break;\n case 'editaddress':\n setPageName = 'edit shipping address';\n break;\n case 'delete-address':\n setPageName = 'delete shipping address';\n break;\n }\n\n setPageType = setPageName;\n\n if(typeof window.DEFAULT_PAGE_NAME == 'undefined') {\n window.DEFAULT_PAGE_NAME = s_getP('digitalData.page.pageInfo.pageName');\n window.DEFAULT_PAGE_TYPE = s_getP('digitalData.page.pageInfo.pageType');\n }\n if(typeof setPageName == 'undefined' || setPageName == '') {\n setPageName = window.DEFAULT_PAGE_NAME;\n setPageType = window.DEFAULT_PAGE_TYPE;\n }\n\n var productModalInfo = isProductTypeModal ? (' : ' + prodName + ' | ' + workId) : '';\n\n setPageName = setPageName + productModalInfo.toLowerCase() + (isModal==true ? ' ~ modal' : '');\n s_setP('digitalData.page.pageInfo.pageName', setPageName);\n s_setP('digitalData.page.pageInfo.pageType', setPageType);\n\n trackAnalyticsPrevPage();\n }\n}",
"function chooseProductPage(req, res) {\n return res.render('product-switcher.html');\n}",
"function renderProductShow(id) {\n Products.show(id).then(product => {\n // console.log(`${product.id} - ${product.title}`)\n const showPage = document.querySelector('.page#product-show')\n const showPageHTML = `\n <h2>${product.title}</h2>\n <p>${product.description}</p>\n `\n showPage.innerHTML = showPageHTML;\n navigateTo('product-show')\n })\n}",
"function lienVersPages()\n {\t\n\tvar numeroPage = document.getElementById(\"image\").alt;\n\t//Dans notre site nous avons pas une 4ème page pour le moment nous avons donc décidé\n\t//que si l'utilisateur clique sur la 4ème image le numéro de la page va demeurer 3 \n\t//comme s'il avait cliquer sur la 3ème image.\n\tvar lien = \"index.php?fiche_film=\" + String(numeroPage);\n\tdocument.getElementById(\"lien\").href = lien;\t\t\n }",
"function show_supplier_selector(product_id)\n{\n\n\n}",
"function mp_store_listeners(){\n\t\t// on next/prev link click, get page number and update products\n\t\t$(document).on('click', '#mp_product_nav a', function(e){\n\t\t\te.preventDefault();\n\t\t\t\n\t\t\tvar hrefParts = $(this).attr('href').split('#'),\n\t\t\t\t\tqs = parse_query(hrefParts[1]);\n\t\t\t\n\t\t\tconsole.log($('.mp_product_list_refine').serialize());\n\t\t\tget_and_insert_products($('.mp_product_list_refine').serialize() + '&page=' + qs['page']);\n\t\t});\n\t}",
"function nav_bar(this_product_key, products_data) {\n // This makes a navigation bar to other product pages\n for (let products_key in products_data) {\n if (products_key == this_product_key) continue;\n document.write(`<a href='./display_products.html?products_key=${products_key}'>${products_key}<a>   `);\n }\n}",
"async copyTo(page, publish = true) {\n // we know the method is on the class - but it is protected so not part of the interface\n page.setControls(this.getControls());\n // copy page properties\n if (this._layoutPart.properties) {\n if (hOP(this._layoutPart.properties, \"topicHeader\")) {\n page.topicHeader = this._layoutPart.properties.topicHeader;\n }\n if (hOP(this._layoutPart.properties, \"imageSourceType\")) {\n page._layoutPart.properties.imageSourceType = this._layoutPart.properties.imageSourceType;\n }\n if (hOP(this._layoutPart.properties, \"layoutType\")) {\n page._layoutPart.properties.layoutType = this._layoutPart.properties.layoutType;\n }\n if (hOP(this._layoutPart.properties, \"textAlignment\")) {\n page._layoutPart.properties.textAlignment = this._layoutPart.properties.textAlignment;\n }\n if (hOP(this._layoutPart.properties, \"showTopicHeader\")) {\n page._layoutPart.properties.showTopicHeader = this._layoutPart.properties.showTopicHeader;\n }\n if (hOP(this._layoutPart.properties, \"showPublishDate\")) {\n page._layoutPart.properties.showPublishDate = this._layoutPart.properties.showPublishDate;\n }\n if (hOP(this._layoutPart.properties, \"enableGradientEffect\")) {\n page._layoutPart.properties.enableGradientEffect = this._layoutPart.properties.enableGradientEffect;\n }\n }\n // we need to do some work to set the banner image url in the copied page\n if (!stringIsNullOrEmpty(this.json.BannerImageUrl)) {\n // use a URL to parse things for us\n const url = new URL(this.json.BannerImageUrl);\n // helper function to translate the guid strings into properly formatted guids with dashes\n const makeGuid = (s) => s.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/g, \"$1-$2-$3-$4-$5\");\n // protect against errors because the serverside impl has changed, we'll just skip\n if (url.searchParams.has(\"guidSite\") && url.searchParams.has(\"guidWeb\") && url.searchParams.has(\"guidFile\")) {\n const guidSite = makeGuid(url.searchParams.get(\"guidSite\"));\n const guidWeb = makeGuid(url.searchParams.get(\"guidWeb\"));\n const guidFile = makeGuid(url.searchParams.get(\"guidFile\"));\n const site = Site(this);\n const id = await site.select(\"Id\")();\n // the site guid must match the current site's guid or we are unable to set the image\n if (id.Id === guidSite) {\n const openWeb = await site.openWebById(guidWeb);\n const file = await openWeb.web.getFileById(guidFile).select(\"ServerRelativeUrl\")();\n const props = {};\n if (this._layoutPart.properties) {\n if (hOP(this._layoutPart.properties, \"translateX\")) {\n props.translateX = this._layoutPart.properties.translateX;\n }\n if (hOP(this._layoutPart.properties, \"translateY\")) {\n props.translateY = this._layoutPart.properties.translateY;\n }\n if (hOP(this._layoutPart.properties, \"imageSourceType\")) {\n props.imageSourceType = this._layoutPart.properties.imageSourceType;\n }\n if (hOP(this._layoutPart.properties, \"altText\")) {\n props.altText = this._layoutPart.properties.altText;\n }\n }\n page.setBannerImage(file.ServerRelativeUrl, props);\n }\n }\n }\n await page.save(publish);\n return page;\n }",
"function showLinkDialog_LinkSave(propert_key, url) {\n\tPropertiesService.getDocumentProperties().setProperty(propert_key, url);\n}",
"handleClicVerPromociones() {\n this[NavigationMixin.Navigate]({\n type: \"standard__objectPage\",\n attributes: {\n objectApiName: \"Promocion__c\",\n actionName: \"list\"\n }\n });\n }",
"function getProdLink(pid) {\n return \"onclick=\\\"location.href='./product.php?id=\" + pid + \"'\\\"\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw gradient behind scale break | function drawGradient() {
noFill();
const startPos = rightOffset + maxWidth * (cuttingPoint + 0.02);
const endPos = displayWidth;
function easeOutExpo(x) {
return x === 1 ? 1 : 1 - pow(2, -2 * x);
}
for (let x = startPos; x <= endPos; x++) {
let inter = map(x, startPos, endPos, 0, 1);
stroke(60, 70 * easeOutExpo(inter));
line(x, 0, x, pageHeight);
}
} | [
"function generateRedGradient(){\n var gradient = svg.append(\"svg:defs\")\n .append(\"svg:linearGradient\")\n .attr(\"id\", \"redgradient\")\n .attr(\"x1\", \"200%\")\n .attr(\"y1\", \"0%\")\n .attr(\"x2\", \"0%\")\n .attr(\"y2\", \"0%\")\n .attr(\"spreadMethod\", \"pad\");\n\n gradient.append(\"svg:stop\")\n .attr(\"offset\", \"50%\")\n .attr(\"stop-color\", \"white\")\n .attr(\"stop-opacity\", 1);\n\n gradient.append(\"svg:stop\")\n .attr(\"offset\", \"50%\")\n .attr(\"stop-color\", \"red\")\n .attr(\"stop-opacity\", 1);\n }",
"function initializeGradientColors() {\n gradient.append(\"stop\")\n .attr(\"id\", \"gstart\")\n .attr(\"offset\", \"0%\")\n .attr(\"stop-color\", \"#ffffff\");\n gradient.append(\"stop\")\n .attr(\"id\", \"gstop\")\n .attr(\"offset\", \"100%\")\n .attr(\"stop-color\", \"#ffffff\");\n}",
"function animateGradient() {\n updateGradient();\n requestAnimationFrame(animateGradient);\n}",
"function GradientStop(offset, rgbColor)\n{\n\tthis.offset = offset;\n\tthis.rgbColor = rgbColor;\n}",
"static Lerp(startValue, endValue, gradient) {\n const result = new Matrix();\n Matrix.LerpToRef(startValue, endValue, gradient, result);\n return result;\n }",
"static LerpToRef(startValue, endValue, gradient, result) {\n for (let index = 0; index < 16; index++) {\n result._m[index] =\n startValue._m[index] * (1.0 - gradient) + endValue._m[index] * gradient;\n }\n result._markAsUpdated();\n }",
"drawSlider() {\n let c = color(255, 255, 255);\n fill(c);\n noStroke();\n rect(this.x, this.y + this.topPadding + this.lateralPadding, this.width, this.height, 1, 1, 1, 1);\n }",
"function SVGWriterGradientMap() {\n\n var findMatchingDistributedNSegs = function (stops) {\n var maxNumSegs = 100;\n var matched = false;\n for (var nSegs = 1; !matched && nSegs <= maxNumSegs; nSegs++) {\n var segSize = maxNumSegs / nSegs;\n matched = true;\n for (var i = 1; i < stops.length-1; i++) {\n var pos = stops[i].position;\n if (pos < segSize) {\n matched = false;\n break;\n }\n var rem = pos % segSize;\n var maxDiff = 1.0;\n if (!(rem < maxDiff || (segSize - rem) < maxDiff)) {\n matched = false;\n break;\n }\n }\n \n if (matched) {\n return nSegs;\n }\n } \n \n return nSegs; \n };\n\n var calcDistributedColors = function (stops, nSegs) {\n var colors = new Array(nSegs);\n colors[0] = stops[0].color;\n \n var segSize = 100 / nSegs;\n for (var i = 1; i < stops.length-1; i++) {\n var stop = stops[i];\n var n = Math.round(stop.position / segSize);\n colors[n] = stop.color;\n }\n colors[nSegs] = stops[stops.length-1].color;\n\n var i = 1;\n while (i < colors.length) {\n if (!colors[i]) {\n for (var j = i+1; j < colors.length; j++) {\n if (colors[j])\n break;\n }\n \n // Need to evenly distribute colors stops from svgStop[i-1] to svgStop[j]\n var startColor = colors[i-1];\n var r = startColor.r;\n var g = startColor.g;\n var b = startColor.b;\n var a = startColor.a;\n \n var endColor = colors[j];\n \n var nSegs = j - i + 1;\n var dr = (endColor.r - r) / nSegs;\n var dg = (endColor.g - g) / nSegs;\n var db = (endColor.b - b) / nSegs;\n var da = (endColor.a - a) / nSegs;\n while (i < j) {\n r += dr;\n g += dg;\n b += db;\n a += da;\n colors[i] = { 'r': r, 'g': g, 'b': b, 'a': a };\n i++;\n }\n }\n i++;\n }\n return colors;\n };\n\n this.createGradientMap = function (ctx, stops) {\n var nSegs = findMatchingDistributedNSegs(stops),\n colors = calcDistributedColors(stops, nSegs),\n redTableValues = '',\n greenTableValues = '',\n blueTableValues = '',\n alphaTableValues = '';\n \n colors.forEach(function(color, index, colors) {\n redTableValues += (svgWriterUtils.round10k(color.r / 255) + ' ');\n greenTableValues += (svgWriterUtils.round10k(color.g / 255) + ' ');\n blueTableValues += (svgWriterUtils.round10k(color.b / 255) + ' ');\n alphaTableValues += (color.a + ' ');\n });\n\n if (!String.prototype.trim) { \n String.prototype.trim = function () { \n return this.replace(/^\\s+|\\s+$/g,''); \n }; \n }\n\n writeln(ctx, ctx.currentIndent + '<feComponentTransfer color-interpolation-filters=\"sRGB\">');\n indent(ctx);\n writeln(ctx, ctx.currentIndent + '<feFuncR type=\"table\" tableValues=\"' + redTableValues.trim() + '\"/>');\n writeln(ctx, ctx.currentIndent + '<feFuncG type=\"table\" tableValues=\"' + greenTableValues.trim() + '\"/>');\n writeln(ctx, ctx.currentIndent + '<feFuncB type=\"table\" tableValues=\"' + blueTableValues.trim() + '\"/>');\n undent(ctx);\n writeln(ctx, ctx.currentIndent + '</feComponentTransfer>'); \n };\n }",
"function drawGlass(data, color) {\n // sort the array of data from biggest to smallest value\n // consider only the first 5 observations\n const sortedData = data.sort((a, b) => ((a.value > b.value) ? -1 : 1)).slice(0, 5);\n // compute the total for the linear scale\n const total = sortedData.reduce((acc, curr) => acc + curr.value, 0);\n\n // build an array to emulate a stack, adding an origin property based on the values of the previous observation\n // 0 for the first\n const stackData = [];\n for (let i = 0; i < sortedData.length; i += 1) {\n if (i !== 0) {\n stackData.push(Object.assign(sortedData[i], { origin: sortedData[i - 1].value + sortedData[i - 1].origin }));\n } else {\n stackData.push(Object.assign(sortedData[i], { origin: 0 }));\n }\n }\n\n // linear scale\n const yScale = d3\n .scaleLinear()\n .domain([0, total])\n .range([0, height]);\n\n // divide the update (read: existing elements) from the enter (read: new elements) selection\n const update = containerFrame\n .selectAll('rect');\n\n const enter = update\n .data(stackData)\n .enter();\n\n // when drawing the elements introduce them as a flowing from the top\n enter\n .append('rect')\n .attr('x', 0)\n .attr('y', d => yScale(d.origin))\n .attr('width', width)\n .transition()\n .duration(100)\n .delay((d, i) => i * 100)\n .ease(d3.easeLinear)\n .attr('height', d => yScale(d.value))\n .attr('fill', `#${color}`)\n .attr('opacity', (d, i) => {\n // first one opacity 1, then in decrements according to the number of observations\n const { length } = stackData;\n return 1 - (1 / length) * i;\n });\n\n // when updating the visualization, transition the properties which change with the same pattern\n update\n .transition()\n .duration(100)\n .delay((d, i) => i * 100)\n .ease(d3.easeLinear)\n .attr('y', d => yScale(d.origin))\n .attr('height', d => yScale(d.value))\n .attr('fill', `#${color}`)\n .attr('opacity', (d, i) => {\n const { length } = stackData;\n return 1 - (1 / length) * i;\n });\n\n // select all rectangle elements and show connected information in the tooltip\n d3.selectAll('rect')\n .on('mouseenter', (d) => {\n const format = d3.format(',');\n tooltip\n .append('p')\n .text(`Country: ${d.country}`);\n\n tooltip\n .append('p')\n .text(`Quantity Produced: ${format(d.value)}L`);\n\n tooltip\n .style('opacity', 1)\n .style('left', `${d3.event.pageX}px`)\n .style('top', `${d3.event.pageY}px`);\n })\n .on('mouseout', () => {\n tooltip\n .style('opacity', 0)\n .selectAll('p')\n .remove();\n });\n}",
"function _createColourGradient(colorstops) {\n var ctx = document.createElement('canvas').getContext('2d');\n var grd = ctx.createLinearGradient(0, 0, 256, 0);\n for (var c in colorstops) {\n grd.addColorStop(c, colorstops[c]);\n }\n ctx.fillStyle = grd;\n ctx.fillRect(0, 0, 256, 1);\n return ctx.getImageData(0, 0, 256, 1).data;\n }",
"function drawSky() {\n\n context.save();\n\n var grad = context.createLinearGradient(0, 0, 0, context.canvas.height);\n grad.addColorStop(0.0, 'rgba(0,0,150,1.0)'); \n grad.addColorStop(0.6, 'rgba(0,0,135,0.3)'); \n grad.addColorStop(0.8, 'rgba(242,167,18,0.7)'); \n grad.addColorStop(1.0, 'rgba(242,44,11,0.9)'); \n context.fillStyle = grad;\n context.fillRect(0, \n 0, \n context.canvas.width, \n context.canvas.height);\n\n context.restore();\n}",
"function drawEdge(a, b, c, where, opacity) {\n let shadow = opacity;\n\n let startX;\n let startY;\n let endX;\n let endY;\n if (where == \"edge\") startX = 0, startY = 0;\n if (where == \"edge\") endX = map.width, endY = map.height;\n if (where == \"view\") startX = canvas.x * (-1), startY = canvas.y * (-1);\n if (where == \"view\") endX = canvas.x * (-1) + window.innerWidth, endY = canvas.y * (-1) + window.innerHeight;\n\n var gradient = ctx.createLinearGradient(map.height / 2, startY, map.height / 2, endY);\n gradient.addColorStop(0, \"rgba(\" + a + \",\" + b + \",\" + c + \",\" + shadow + \")\");\n gradient.addColorStop(.4, \"rgba(0, 0, 0, 0)\");\n gradient.addColorStop(.6, \"rgba(0, 0, 0, 0)\");\n gradient.addColorStop(1, \"rgba(\" + a + \",\" + b + \",\" + c + \",\" + shadow + \")\");\n ctx.fillStyle = gradient;\n ctx.fillRect(startX, startY, endX, endY);\n\n gradient = ctx.createLinearGradient(startX, map.width / 2, endX, map.width / 2);\n gradient.addColorStop(0, \"rgba(\" + a + \",\" + b + \",\" + c + \",\" + shadow + \")\");\n gradient.addColorStop(.4, \"rgba(0, 0, 0, 0)\");\n gradient.addColorStop(.6, \"rgba(0, 0, 0, 0)\");\n gradient.addColorStop(1, \"rgba(\" + a + \",\" + b + \",\" + c + \",\" + shadow + \")\");\n ctx.fillStyle = gradient;\n ctx.fillRect(startX, startY, endX, endY);\n}",
"static Lerp(start, end, amount) {\n const result = new Color3(0.0, 0.0, 0.0);\n Color3.LerpToRef(start, end, amount, result);\n return result;\n }",
"static DecomposeLerp(startValue, endValue, gradient) {\n const result = new Matrix();\n Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);\n return result;\n }",
"function render_bottom_border() {\n context.setLineDash([5, 15]);\n\n context.lineWidth = 1;\n context.strokeStyle = '#00ff00';\n context.beginPath();\n context.moveTo(0, (canvas.height - 155));\n context.lineTo(canvas.width, (canvas.height - 155));\n context.stroke();\n }",
"function setGradient() {\n\tbody.style.background =\n\t\"linear-gradient(to right, \" + color1.value + \", \" + color2.value + \")\";\n\tcss.textContent = \"background : linear-gradient(to right, \" + color1.value + \", \" + color2.value + \")\";\n}",
"function calculateGradient(x1, y1, y, m) {\n x = ((-y + y1) / m) + x1\n return x\n }",
"function GradientColor(type, direction, numStops, arrGradientStop)\n{\n\tthis.type = type;\n\tthis.direction = direction;\n\tthis.numStops = numStops;\n\tthis.arrGradientStop = arrGradientStop;\n}",
"function drawBlackPoint(x, y) {\n if (x > 0) {\n setExtremes(x + RADIUS, y + RADIUS);\n var ctx = document.getElementById('canvas').getContext('2d');\n var grd = ctx.createRadialGradient(x, y, 0, x, y, RADIUS);\n grd.addColorStop(0.0, 'rgba(0, 0, 0, ' + INTENSITY + ')');\n grd.addColorStop(1.0, 'transparent');\n ctx.fillStyle = grd;\n ctx.fillRect(x - RADIUS, y - RADIUS, RADIUS*2, RADIUS*2);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overlay canvas: just a semitransparent white canvas for helper views to be shown on top of ("hides" the main app) | function arrangeOverlayCanvas() {
var canvas = $('#app-overlay')[0],
ctx = null;
$('#app-overlay').css('display', 'none');
if (canvas.getContext) {
// Background
ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
} | [
"showContent () {\n this.loadingWrapper.style.display = 'none'\n this.canvas.style.display = 'block'\n }",
"closeCanvas() {\n // empty\n }",
"function drawHidden(url) {\n\n \n\n var can = document.getElementById('can_hidden'),\n\n ctx = can.getContext('2d'),\n\n imgUrl = url;\n\n\n\n var img = new Image();\n\n img.src = url;\n\n\n\n var img2 = new Image();\n\n img2.src = 'https://'+dominio+'img/bg-canvas.jpg';\n\n\n\n ctx.drawImage(img2, 0, 0);\n\n ctx.drawImage(img, 30, 80);\n\n\n\n $('#can_hidden').hide();\n\n }",
"function showingHiddingCanvas(mode){\r\n\t\r\n\t let x = document.getElementById(\"display-mode\");\r\n\t x.style.display = mode;\r\n\r\n}",
"function showHideTLeditPanel(){\n if(trafficLightControl.isActive){ // close panel\n trafficLightControl.isActive=false; //don't redraw editor panel\n if(drawBackground){ // wipe out existing editor panel\n ctx.drawImage(background,0,0,canvas.width,canvas.height);\n }\n document.getElementById(\"editTLbutton\").innerHTML\n =\"Open traffic-light control panel\";\n }\n else{ // open panel\n trafficLightControl.isActive=true;\n document.getElementById(\"editTLbutton\").innerHTML\n =\"Close traffic-light control panel\";\n }\n}",
"function createProcessingWindow(canvas) {\n\n }",
"cloneCanvas ()\n {\n let maxZoomLevel = this.pixelInstance.core.getSettings().maxZoomLevel;\n\n let height = this.pixelInstance.core.publicInstance.getPageDimensionsAtZoomLevel(this.pageIndex, maxZoomLevel).height,\n width = this.pixelInstance.core.publicInstance.getPageDimensionsAtZoomLevel(this.pageIndex, maxZoomLevel).width;\n\n this.canvas = document.createElement('canvas');\n this.canvas.setAttribute(\"class\", \"pixel-canvas\");\n this.canvas.setAttribute(\"id\", \"layer-\" + this.layerId + \"-canvas\");\n this.canvas.width = width;\n this.canvas.height = height;\n\n this.ctx = this.canvas.getContext('2d');\n\n this.resizeLayerCanvasToZoomLevel(this.pixelInstance.core.getSettings().zoomLevel);\n this.placeLayerCanvasOnTopOfEditingPage();\n\n this.backgroundImageCanvas = document.createElement(\"canvas\");\n this.backgroundImageCanvas.width = this.canvas.width;\n this.backgroundImageCanvas.height = this.canvas.height;\n }",
"static paintCanvas() {\n\t\tctx.fillStyle = backgroundColor;\n\t\tctx.fillRect(0, 0, W, H);\n\t}",
"function setCanvasLocation(){\n\tif( window.scrollY > canvasToTop ){\n\t\tintro.style.marginBottom = canvasComputedHeight;\n\t\tcanvas.className = 'canvas-fixed z-depth-4';\n\t}else{\n\t\tintro.style.marginBottom = 0;\n\t\tcanvas.className = '';\n\t}\n}",
"function initCanvas() {\n if ($('#canv').length > 0) {\n onscreen = $('#canv')[0];\n onscreen.ctx = onscreen.getContext('2d');\n onscreen.width = 384 * canvasScale;\n onscreen.height = 256 * canvasScale;\n\n // create offscreen canvas as backing store\n offscreen = document.createElement('canvas');\n offscreen.ctx = offscreen.getContext('2d');\n offscreen.width = 384;\n offscreen.height = 256;\n\n // create another offscreen canvas; it holds the scrolled\n // version of the screen, then we draw the cursor on top of\n // it, then we blit it to the screen, possibly with scaling\n offscreen2 = document.createElement('canvas');\n offscreen2.ctx = offscreen2.getContext('2d');\n offscreen2.width = 384;\n offscreen2.height = 256;\n }\n }",
"_createCanvas(props) {\n let canvas = props.canvas; // TODO EventManager should accept element id\n\n if (typeof canvas === 'string') {\n canvas = document.getElementById(canvas);\n Object(_utils_assert__WEBPACK_IMPORTED_MODULE_16__[\"default\"])(canvas);\n }\n\n if (!canvas) {\n canvas = document.createElement('canvas');\n canvas.id = props.id || 'deckgl-overlay';\n const parent = props.parent || document.body;\n parent.appendChild(canvas);\n }\n\n Object.assign(canvas.style, props.style);\n return canvas;\n }",
"function disable_draw() {\n drawing_tools.setShape(null);\n}",
"createWindowWithCanvas(name, options = {}) {\n let canvas = document.createElement('canvas');\n return this.createWindow(canvas, name, options);\n }",
"showOverlay_() {\n this.overlay_.setAttribute('i-amphtml-lbg-fade', 'in');\n this.controlsMode_ = LightboxControlsModes.CONTROLS_DISPLAYED;\n }",
"function ShowExampleAppSimpleOverlay(p_open) {\r\n const DISTANCE = 10.0;\r\n /* static */ const corner = STATIC(\"corner\", 0);\r\n const io = GetIO();\r\n if (corner.value !== -1) {\r\n const window_pos = new ImVec2((corner.value & 1) ? io.DisplaySize.x - DISTANCE : DISTANCE, (corner.value & 2) ? io.DisplaySize.y - DISTANCE : DISTANCE);\r\n const window_pos_pivot = new ImVec2((corner.value & 1) ? 1.0 : 0.0, (corner.value & 2) ? 1.0 : 0.0);\r\n SetNextWindowPos(window_pos, ImGuiCond.Always, window_pos_pivot);\r\n }\r\n SetNextWindowBgAlpha(0.35); // Transparent background\r\n if (Begin(\"Example: Simple overlay\", p_open, (corner.value !== -1 ? ImGuiWindowFlags.NoMove : 0) | ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoSavedSettings)) {\r\n Text(\"Simple overlay\\nin the corner of the screen.\\n(right-click to change position)\");\r\n Separator();\r\n if (IsMousePosValid())\r\n Text(`Mouse Position: (${io.MousePos.x.toFixed(1)},${io.MousePos.y.toFixed(1)})`);\r\n else\r\n Text(\"Mouse Position: <invalid>\");\r\n if (BeginPopupContextWindow()) {\r\n if (MenuItem(\"Custom\", null, corner.value === -1))\r\n corner.value = -1;\r\n if (MenuItem(\"Top-left\", null, corner.value === 0))\r\n corner.value = 0;\r\n if (MenuItem(\"Top-right\", null, corner.value === 1))\r\n corner.value = 1;\r\n if (MenuItem(\"Bottom-left\", null, corner.value === 2))\r\n corner.value = 2;\r\n if (MenuItem(\"Bottom-right\", null, corner.value === 3))\r\n corner.value = 3;\r\n if (p_open() && MenuItem(\"Close\"))\r\n p_open(false);\r\n EndPopup();\r\n }\r\n }\r\n End();\r\n }",
"drawLobbyView() {\n this.drawState();\n\n this.ctx.font = '20px Arial';\n this.ctx.fillStyle = '#FFF';\n this.ctx.textAlign = 'center';\n this.ctx.fillText('Waiting on another player...', this.canvas.width / 2,\n this.canvas.height / 2 - 60);\n this.ctx.fillStyle = '#000';\n }",
"function isCanvas() {\n return !isHome();\n}",
"function drawNone(can){\n\tc=document.getElementById(can);\n\tvar ctx = c.getContext(\"2d\");\n\tvar wide = c.width;\n\tvar high = c.height;\n\tctx.clearRect(0, 0, wide, high);\t// clear any prior drawing\n\treturn;\n}",
"function CanvasController() {\n // Define the canvas reference and canvas context\n const canvas = document.querySelector('canvas');\n\n // Get the window size dimensions\n this.width = window.width * window.scale;\n this.height = window.height * window.scale;\n\n // Set the canvas dimensions to the window size\n canvas.width = this.width;\n canvas.height = this.height;\n\n // Define the offscreen canvas reference that mirrors the main canvas\n // This is done to optimize image rendering and performance\n const offscreenCanvas = canvas.transferControlToOffscreen();\n\n // Set the offscreen canvas dimensions to the window size\n offscreenCanvas.width = this.width;\n offscreenCanvas.height = this.height;\n\n // Define the offscreen canvas context\n // Since transferControlToOffscreen is used on the offscreen canvas, all\n // drawing will be done with this context\n this.context = offscreenCanvas.getContext('2d');\n\n // Define the canvas context drawing methods\n this.drawImage = canvasContext.drawImage(this);\n\n log.controller.canvas.init.success();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a worker for the decompressed content. | _decompressWorker() {
if (this._data instanceof CompressedObject) {
return this._data.getContentWorker();
} else if (this._data instanceof GenericWorker) {
return this._data;
} else {
return new DataWorker(this._data);
}
} | [
"get _worker() {\n delete this._worker;\n this._worker = new ChromeWorker(\"resource://gre/modules/PageThumbsWorker.js\");\n this._worker.addEventListener(\"message\", this);\n return this._worker;\n }",
"function workerBody() {\n var that = this, lambda, evalInContext, handleErr;\n\n /*\n * Evaluates code within a custom context. This is not\n * used in our main application thread and happens only when\n * when we assign a job to a real Web Worker. Thus it does not\n * hurt performance in our main thread and doesn't make any more use\n * of the interpreter than `importScripts` would.\n */\n evalInContext = function (ctx, src) {\n var newSrc = new Function('return ' + src + ';');\n return newSrc.call(ctx);\n };\n\n /*\n * When we receive a message, determine what to do with it.\n */\n this.onmessage = function (evt) {\n var job;\n switch (evt.data.label) {\n case \"job\" :\n job = new Function(evt.data.msg.params[0], evt.data.msg.body)\n return (lambda = evt.data.msg.immediate ? job() : job);\n case \"cmd\" : return evalInContext(that, evt.data.msg.body);\n case \"message\" : return lambda(evt.data.msg);\n case \"close\" : return self.close();\n }\n };\n}",
"function createWorker(worker) {\n\t if (typeof worker === 'string') {\n\t return new Worker(worker);\n\t }\n\t else {\n\t var blob = new Blob(['self.onmessage = ', worker.toString()], { type: 'text/javascript' });\n\t var url = URL.createObjectURL(blob);\n\t return new Worker(url);\n\t }\n\t}",
"function WebWorkerSource(worker){\n this._worker = worker;\n}",
"function _preloadZip () {\n if (!_URLsToLoad.length) return; // If no zip file to download, that's it, we're done\n var getZipFile = function(url){ // Called for each URL that was passed\n function removeURL() { // Called to remove a URL from the array (when unzipped done, or error)\n let index = _URLsToLoad.indexOf(url);\n if (index >= 0)\n _URLsToLoad.splice(index,1);\n }\n var zip = new JSZip();\n getBinaryContent(url, function(error, data) {\n if (error) {\n removeURL(); // Problem with downloading the file: remove the URL from the array\n throw error; // Throw the error\n }\n zip.loadAsync(data).then(function(){ // Load the zip object with the data stream\n PennEngine.debug.log(\"Download of \"+url+\" complete\");\n var unzippedFilesSoFar = 0; // Number of files unzipped\n zip.forEach(function(path, file){ // Going through each zip file\n file.async('arraybuffer').then(function(content){ // Unzip the file\n if (!path.match(/__MACOS.+\\/\\.[^\\/]+$/)) { // Excluding weird MACOS zip files\n let filename = path.replace(/^.*?([^\\/]+)$/,\"$1\"); // Get rid of path, keep just filename\n let type = getMimetype( hexFromArrayBuffer(content.slice(0,28)) ); // Get type using magic numbers (see utils.js)\n if (type){ // Add only type was recognized\n let url = URL.createObjectURL(new Blob([content], {type: type})); // The URL of the Blob\n var resourceFound = false; // Check extent resources\n for (let r in PennEngine.resources.list){\n let resource = PennEngine.resources.list[r];\n if (resource.name==filename && resource.status!=\"ready\"){\n resource.create.apply( // Create the resource's object\n $.extend({}, resource, { // using a copy of the resource found\n value: url, // with its value set to the Blob's URL\n resolve: function() { // and its resolve taking care of object\n if (resource.status==\"ready\")\n return; // Assign copy's object to original's\n resource.object = this.object;\n resource.resolve();\n }\n })\n );\n resourceFound = true;\n }\n }\n if (!resourceFound) // If no resource was found:\n PennEngine.resources.list.push({ // add a new one to the list\n name: filename,\n value: url, // Use the Blob's URL\n controllers: [],\n object: null,\n status: \"void\",\n create: function(){ this.status=\"pending\"; },\n resolve: function(){ this.status=\"ready\"; }\n });\n }\n }\n unzippedFilesSoFar++; // Keep track of progression\n if (unzippedFilesSoFar >= Object.keys(zip.files).length) // All files unzipped:\n removeURL(); // remove the URL from the array\n });\n });\n });\n });\n };\n \n for (let u in _URLsToLoad) { // Fetch the zip file\n let url = _URLsToLoad[u];\n let extension = url.match(/^https?:\\/\\/.+\\.(zip)$/i);\n if (typeof(url) != \"string\" || !extension) {\n PennEngine.debug.log(\"Preload: entry #\"+u+\" is not a valid URL, ignoring it\");\n continue;\n }\n else if (extension[1].toLowerCase() == \"zip\")\n getZipFile(url);\n }\n}",
"_createWorker(text) {\n if (typeof Worker === \"undefined\") {\n this.view.log(\"Sorry, your browser does not support workers.\");\n return;\n }\n var self = this;\n this.view.log(\"Executing algorithm...\");\n this.webWorker = new Worker(\"js/GAPSolverWorker.js?v=2\");\n this.webWorker.postMessage(text);\n this.webWorker.postMessage(this.algorithm);\n this.webWorker.onmessage = function (event) {\n self.solution = event.data;\n Object.setPrototypeOf(self.solution, GAPSolution.prototype);\n Object.setPrototypeOf(self.solution.getInstance(), GAPInstance.prototype);\n self.computing = false;\n if (self.solution.isFeasible()) {\n self.view.log(\"Done: solution has cost \" + self.solution.getCost());\n self.view.log(self.solution);\n self._updateViewButtons(self.view, false, true);\n } else {\n self.view.log(\"Sorry, could not find a feasible solution!\");\n self._updateViewButtons(self.view, false, false);\n }\n \n };\n }",
"decrypt(file, fileMeta, passphrase, callback) {\n this.isDecrypting = true;\n var workers = window.secureShared.spawnWorkers(window.secureShared\n .workerCount),\n i;\n for (i = 0; i < workers.length; i++) {\n workers[i].addEventListener('message', onWorkerMessage,\n false);\n }\n\n var slices = file.split(window.secureShared.chunkDelimiter);\n\n // Send slices to workers\n for (i = 0; i < slices.length; i++) {\n workers[i % workers.length].postMessage({\n fileData: slices[i],\n fileName: i === 0 ? fileMeta.fileName : '', // only send this once\n passphrase: passphrase,\n decrypt: true,\n index: i\n });\n }\n\n var decryptedFile = {\n fileData: []\n };\n var receivedCount = 0;\n\n function onWorkerMessage(e) {\n // got a slice. Process it.\n if (!_.isObject(e.data)) {\n // error message\n window.alert(\"Incorrect password. Refresh this page to try again.\");\n return;\n }\n receivedCount++;\n onSliceReceived(e.data);\n\n if (receivedCount === slices.length) {\n // last slice, finalize\n onFinish();\n }\n }\n\n function onSliceReceived(slice) {\n if (slice.fileName) decryptedFile.fileName = slice.fileName;\n decryptedFile.fileData[slice.index] = slice.fileData;\n }\n\n function onFinish() {\n // Create blob\n var binaryData = decryptedFile.fileData.join(\"\");\n var blob = new Blob([window.secureShared.str2ab(binaryData)], {\n type: fileMeta.contentType\n });\n\n if (!/Safari/i.test(window.BrowserDetect.browser)) {\n var URL = window.URL || window.webkitURL;\n var url = URL.createObjectURL(blob);\n\n callback(url);\n\n $(\"<a>\").attr(\"href\", url).attr(\"download\",\n decryptedFile.fileName).addClass(\n \"btn btn-success\")\n .html(\n '<i class=\"icon-download-alt icon-white\"></i> Download'\n ).appendTo(\"#downloaded-content\").hide().fadeIn();\n } else {\n // Safari can't open blobs, create a data URI\n // This will fail if the file is greater than ~200KB or so\n // TODO figure out what's wrong with the blob size in safari\n // TODO Why doesn't safari want a dataview here?\n if (blob.size > 200000) return window.alert(\n \"Sorry, this file is too big for Safari. Please try to open it in Chrome.\"\n );\n var fileReader = new FileReader();\n fileReader.readAsDataURL(blob);\n }\n\n this.isDecrypting = false;\n }\n }",
"dequeue() {\n return this.processes.shift();\n }",
"function run() {\n var compactInstance = compactPlugin.run();\n var serializeInstance = serializePlugin.run();\n\n return {\n postValue: serializeInstance.postValue,\n postExtract: compactInstance.postExtract\n };\n}",
"function dequeue(){\n\tvar priority = this.dataStore[0].code;\n\tfor(var i =1; i < this.dataStore.length; ++1){\n\t\tif(this.dataStore[i].code < priority){\n\t\t\tpriority = i;\n\t\t}\n\t}\n\treturn this.dataStore.splice(priority,1);\n}",
"function Worker() {\n var self = this;\n var onReady = null;\n self.busy = false;\n\n /**\n * Set a ready callback on the worker. This will be fired\n * when the worker is done processing a request.\n */\n self.ready = function (callback) {\n onReady = callback;\n return self;\n }\n\n /**\n * Process a request.\n */\n self.process = function (request) {\n self.busy = true;\n\n var markAsDone = function () {\n self.busy = false;\n\n if (onReady != null) {\n onReady();\n }\n };\n\n request.run(markAsDone);\n }\n}",
"function getTarget(target, app, base){\n if(target){\n var offset = base +target.offset;\n var byteArray = app.slice(offset, offset +target.size);\n if(isStringType(target.type)){\n var string = LZString.decompressFromUint8Array(byteArray);\n var byteArray = stringToByteArray(string);\n }\n return Promise.resolve(byteArray);\n }\n return Promise.resolve(null);\n}",
"function parallelize(data, worker, numWorkers, callback) {\n var reg, slices, start, max, t0, t1,nWorkers,dataSize;\n start = 0\n slices = get_slices(data, numWorkers);\n max = slices.length;\n dataSize = data.length;\n nWorkers = slices.length;\n console.log(\"creating \" + slices.length + \" workers\")\n var resultQueue = []\n reg = function(s) {\n\tstart += 1\n\tif (start === max) {\n\t callback(resultQueue);\n\t}\n }\n \n var rec = function(e) {\n\tvar res = ab2obj(e.data)\n\tresultQueue.push(res)\n\treg(1)\n }\n\nfor (var i = 0; i < max; i++) {\n// obj2ab\n\tvar msg = {\n\t data: slices[i],\n\t id: i\n\t}\n// transferable object for zero-length copying to worker\n var ab = obj2ab(msg);\n var proc = new Worker(worker);\n proc.postMessage(ab,[ab.buffer])\n proc.addEventListener('message',rec)\n\n}\n\n}",
"async function zipGetData(entry, writer, options = undefined) {\n try {\n return await entry.getData(writer, options);\n } catch (e) {\n if (e instanceof ProgressEvent && e.type === \"error\") {\n throw e.target.error;\n } else {\n throw e;\n }\n }\n}",
"function withZipFsPerform(callback, onerror) {\n\n if (_zipFs) {\n\n callback(_zipFs, onerror);\n\n } else {\n\n // The Web Worker requires standalone inflate/deflate.js files in libDir (i.e. cannot be aggregated/minified/optimised in the final generated single-file build)\n zip.useWebWorkers = true; // (true by default)\n zip.workerScriptsPath = libDir;\n \n _zipFs = new zip.fs.FS();\n _zipFs.importHttpContent(baseUrl, true, function () {\n\n callback(_zipFs, onerror);\n\n }, onerror)\n }\n }",
"dequeue() {\r\n let deletedData;\r\n if (isEmpty()) {\r\n return -1;\r\n } else if (this.rear == this.front) {\r\n this.front = -1;\r\n this.rear = -1;\r\n } else {\r\n this.front = (this.front + 1) % this.queueSize;\r\n }\r\n deletedData = this.circularLinkedListQueue.deleteNode(0);\r\n return deletedData;\r\n }",
"function videoWorkerLoad() {\n var lazyload = $(\".lazyload\");\n var count = 0;\n\n function removeLazyload() {\n // remove lazyload class each time untill videos finish\n //then remove the rest of lazyload classes\n $.each(lazyload, function(index, element) {\n if (count === 0) {\n loadIframe();\n }\n $(element).removeClass(\"lazyload\");\n count += 1;\n lazyload = lazyload.slice(1);\n if (count < postArr.length) {\n return false;\n }\n });\n }\n\n worker.onmessage = function(e) {\n $.each(domVideos, function(index, value) {\n var id = e.data[0];\n var src = e.data[1];\n var node;\n\n // append src to loaded source and then load video\n if (value.id === id) {\n node = value.node;\n node.src = src;\n\n $(value.video).get(0).load();\n removeLazyload();\n }\n });\n };\n // object to post\n var postArr = $.each(domVideos, function(index, value) {\n value = {\n id: value.id,\n src: value.src\n };\n });\n // make a copy of postArr\n var postObj = JSON.parse(JSON.stringify(postArr));\n\n worker.postMessage(postObj);\n\n worker.onerror = function(error) {\n function WorkerException(message) {\n this.name = \"WorkerException\";\n this.message = message;\n }\n throw new WorkerException('worker error.');\n };\n }",
"function compile(compiler, msg) {\n let b_vert;\n let b_frag;\n try {\n b_vert = compiler.compileGLSL( msg.vertex, \"vertex\" );\n b_frag = compiler.compileGLSL( msg.fragment, \"fragment\");\n\n console.log(\"in worker: vert bytes\", b_vert);\n console.log(\"in worker: frag bytes\", b_frag);\n\n // the items in the seconds argument are the data\n // that will be \"transferred\" with no copying --\n // must be part of the first argument as well (almost seems like syntax magic)\n // Note that apparently the data can only be accessed by \n // the thread that has ownership, so transferring here will make the data\n // unavailable to the worker. This can go back-and-forth I think\n\n // sending the raw bytes back to the main thread \n // (though maybe rendering could be done on this thread, \n // and yet another worker spawned from this worker could handle the compilation)\n // user input could be handled in the main thread since only the main thread can\n // interact with the DOM -- input updates can be transferred via byte buffer,\n // and maybe do a buffer swap \"thing\" on the main thread\n postMessage(\n {\n \"type\" : \"compileResult\",\n\n vdata : b_vert, fdata : b_frag\n }, \n [b_vert.buffer, b_frag.buffer]\n );\n\n } catch (err) {\n console.error(err);\n return;\n }\n}",
"function deQueue(){\n this.string=new Array();\n /*\n * remove the item from back\n */\n this.popback=function(){\n return this.string.pop();\n }\n /*\n * add the item into back\n */\n this.pushback=function(item){\n return this.string.push(item);\n }\n /*\n * remove the item from front\n */\n this.popfront=function(){\n return this.string.shift();\n }\n /*\n * add the item into front\n */\n this.pushfront=function(item){\n return this.string.unshift(item);\n }\n /*\n * print dequeue\n */\n this.printQueue=function(){\n var str='';\n for(var i=0;i<this.string.length;i++){\n str+=this.string[i]+\" \";\n }\n return str;\n }\n /*\n returns the length of deQueue\n */\n this.size=function(){\n return this.string.length;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to Hide Deck Popup | function div_hide_deck(){
document.getElementById('def').style.display = "none";
} | [
"function hide_popup()\n{\n\t$('.overlay').hide();\n\t$(\"#tooltip\").toggle();\n}",
"function hidePopup () {\n $('#popup').css('z-index', -20000);\n $('#popup').hide();\n $('#popup .popup-title').text('');\n $('#popup .popup-content').text('');\n $('.hide-container').hide();\n $('.container').css('background', '#FAFAFA');\n }",
"function hidePopup() {\n // get the container which holds the variables\n var topicframe = findFrame(top, 'topic');\n\n if (topicframe != null) {\n if (topicframe.openedpopup != 1) {\n if ((topicframe.openpopupid != '') && (topicframe.popupdocument != null)) {\n var elmt = topicframe.popupdocument.getElementById(topicframe.openpopupid);\n if (elmt != null) {\n elmt.style.visibility = 'hidden';\n }\n openpopupid = '';\n }\n }\n\n openedpopup = 0;\n }\n}",
"function unhide()\r\n{\r\n if (document.querySelector('.pumpkin').style.visibility == \"visible\")\r\n {\r\n document.querySelector('.pumpkin').style.visibility = \"hidden\";\r\n }\r\n else\r\n {\r\ndocument.querySelector('.pumpkin').style.visibility = \"visible\";\r\n }\r\n}",
"function hidePopup () {\r\n editor.popups.hide('customPlugin.popup');\r\n }",
"function hidePopups(){\n\tvar keys = document.getElementById(\"keysDiv\");\n\tkeys.style.visibility = \"visible\";\n\tvar len=popupList.length;\n\tfor(var i=0;i<len;i++){\n\t\tdocument.getElementById(popupList[i]).style.visibility = \"hidden\";\n\t}\n}",
"function hideImagePopup(){\n\tdocument.getElementById('popupImage').style.visibility = \"hidden\";\n}",
"function hide() {\n if (!settings.shown) return;\n win.hide();\n settings.shown = false;\n }",
"function close_popup(popup) {\r\n popup.style.display = \"none\";\r\n}",
"function CloseBubble()\r\n{\r\n\tdocument.getElementById(\"bubble_main\").style.visibility = \"hidden\";\r\n}",
"function hidePopup() {\n $('#transparented').hide();\n $('#popup').hide();\n $(\"#typebox > textarea\").removeProp(\"disabled\");\n $(\"#typebox > textarea\").focus();\n}",
"function IsHidden(){\n\treturn !_showGizmo;\n}//IsHidden",
"function showingHiddingCanvas(mode){\r\n\t\r\n\t let x = document.getElementById(\"display-mode\");\r\n\t x.style.display = mode;\r\n\r\n}",
"function participants_view_hide() {\n\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"rgba(0,0,0,.2)\";\n\tsetTimeout(function() {\n\t\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"transparent\";\n\t\tparticipants_view_visible = false;\n\t\tDOM(\"PARTICIPANTS_VIEW\").style.top = \"-100%\";\n\t\tsetTimeout(function() {\n\t\t\tDOM(\"PARTICIPANTS_VIEW\").style.display = \"none\";\n\t\t}, 500);\n\t}, 50);\n}",
"function hide_billing() {\n\tif ($('#billing_info').is(\":visible\")) {\n\t\t$('#billing_info').fadeOut();\n\t} \n}",
"function hideCreateDialog() {\n if (document.getElementById('editID').value != '-1') {\n $('#rfelement' + document.getElementById('editID').value).show();\n document.getElementById('editID').value = '-1';\n }\n $('#textarea_preview').hide();\n $('#singlechoice_preview').hide();\n $('#multiplechoice_preview').hide();\n $('#matrix_preview').hide();\n $('#grading_preview').hide();\n $('#tendency_preview').hide();\n $('#newquestion').hide();\n $('#text_preview').show();\n //$('#newquestion_button').show();\n}",
"hide() {\n this.StartOverPopoverBlock.remove();\n this.StartOverPopoverDiv.remove();\n }",
"function _hidePopup(event) {\n if ($reverseNameResolver.css('display') != 'none') {\n $reverseNameResolver.fadeOut(300);\n }\n }",
"function hideMoodSelection()\n{\n document.getElementById(\"mood-panorama-page\").style.visibility = \"hidden\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns number format for a fieldDef | function numberFormat(fieldDef, specifiedFormat, config) {
if (fieldDef.type === type_1.QUANTITATIVE) {
// add number format for quantitative type only
// Specified format in axis/legend has higher precedence than fieldDef.format
if (specifiedFormat) {
return specifiedFormat;
}
// TODO: need to make this work correctly for numeric ordinal / nominal type
return config.numberFormat;
}
return undefined;
} | [
"function flowFmt(num){\n // --- set number of decimal places for reporting flow values\n if ( FlowUnits == MGD || FlowUnits == CMS ) {\n return num.toFixed(3).padStart(9);\n }\n else {\n return num.toFixed(2).padStart(9);\n }\n}",
"function formatValore(field)\n{\n\tformatDecimal(field,9,6,true);\n}",
"static measurementDocumentFieldFormat(sectionProxy) {\n var section = sectionProxy.getName();\n var property = sectionProxy.getProperty();\n var binding = sectionProxy.binding;\n let format = '';\n switch (section) {\n case 'MeasurementDocumentsList': {\n\n switch (property) {\n case 'Footnote': {\n let offset = -1 * libCom.getBackendOffsetFromSystemProperty(sectionProxy);\n let odataDate = new ODataDate(binding.ReadingDate, binding.ReadingTime, offset);\n format = sectionProxy.formatDatetime(odataDate.date());\n break;\n }\n case 'Subhead': {\n format = binding.ReadBy;\n break;\n }\n case 'Description': {\n let value = '';\n if (!libVal.evalIsEmpty(binding.ValuationCode)) {\n if (!libVal.evalIsEmpty(value)) {\n value = value + ': ';\n }\n value = value + libForm.getFormattedKeyDescriptionPair(sectionProxy, binding.ValuationCode, binding.CodeShortText);\n }\n format = value;\n break;\n }\n case 'Title': {\n let value = '';\n if (binding.HasReadingValue === 'X') {\n value = binding.ReadingValue + value + ' ' + binding.UOM;\n } else {\n value = binding.ReadingValue + ' ' + binding.MeasuringPoint.UoM;\n }\n if (!libVal.evalIsEmpty(binding.ValuationCode)) {\n if (!libVal.evalIsEmpty(value)) {\n value = value + ': ';\n }\n value = value + libForm.getFormattedKeyDescriptionPair(sectionProxy, binding.ValuationCode, binding.CodeShortText);\n }\n format = value;\n break;\n }\n default:\n break;\n }\n break;\n }\n default:\n break;\n }\n return format;\n }",
"function withUnits(n) { return formatUserData(n, numberStyle); }",
"getFieldFormatter(key) {\n const field = this.computedFieldsObj[key]\n // `this.computedFieldsObj` has pre-normalized the formatter to a\n // function ref if present, otherwise `undefined`\n return field ? field.formatter : undefined\n }",
"function get_Number_WithOut_Mask(aField)\n{\n lstrValue = aField.value;\n re = new RegExp(\",\",\"g\");\n return lstrValue.replace(re,\"\");\n}",
"function Format(maxIntDigit, maxFractionDigit, minFractionDigit) {\n\n var SetIntDigit = function (val) {\n\n if (isNaN(val) || val === null) {\n return 0;\n }\n var orgStr = val.toString();\n\n var deciPos = orgStr.indexOf('.');\n //if sending object is decimal type\n if (deciPos != -1) {\n var beforeDeciStr = orgStr.substring(0, deciPos);\n if (beforeDeciStr.length > maxIntDigit) {\n beforeDeciStr = beforeDeciStr.substring(0, maxIntDigit);\n var finalStr = beforeDeciStr + orgStr.substring(deciPos, orgStr.Length - deciPos);\n return finalStr;\n }\n }\n else //if sending object is integer type \n {\n //if (orgStr.length > maxIntDigit) {\n // var finalStr = orgStr.substring(0, maxIntDigit);\n // if (finalStr > VIS.EnvConstants.INT32MAXVALUE) {\n // return VIS.EnvConstants.INT32MAXVALUE;\n // }\n // //parseint work fine only when no fraction otherwise it convert 1.8 to 1\n // return parseInt(orgStr.substring(0, maxIntDigit));\n //}\n if (maxFractionDigit === 0 && minFractionDigit === 0) {\n if (orgStr > VIS.EnvConstants.INT32MAXVALUE) {\n //return max integer value\n return VIS.EnvConstants.INT32MAXVALUE;\n }\n else if (orgStr < -1 * (VIS.EnvConstants.INT32MAXVALUE + 1)) {\n //return minimum integer value\n return -1 * (VIS.EnvConstants.INT32MAXVALUE + 1);\n }\n }\n }\n return val;\n };\n\n /// <summary>\n /// return formatted string \n /// if value is greate than system default integer max value\n /// then slice value to set integer max\n /// </summary>\n /// <param name=\"val\"></param>\n /// <returns></returns>\n this.GetFormatedValue = function (val) {\n var o = SetIntDigit(val).toString();\n if (minFractionDigit != 0) {\n if (o.indexOf(\".\") <= -1) {\n o = parseFloat(o).toFixed(minFractionDigit);\n }\n else if (o.split(\".\")[1].length > minFractionDigit) {\n o = parseFloat(o).toFixed(maxFractionDigit);\n o = parseFloat(o);\n }\n else if (minFractionDigit === maxFractionDigit) {\n o = parseFloat(o).toFixed(minFractionDigit);\n }\n }\n //Also remove extra zero before return\n return o;\n };\n\n /* privilized function */\n this.dispose = function () {\n this.GetFormatedValue = null;\n SetIntDigit = null;\n };\n\n\n }",
"function putMask_Number(aField, aintDigits, aintDecimals)\n{\n var lreComma = new RegExp(\",\",\"g\");\n\n lstrValue = aField.value;\n lstrValue = lstrValue.replace(lreComma,\"\");\n\n // Curtailing Blank spaces from the begining and end of the entered text\n lstrValue = trimString(lstrValue);\n\n if( lstrValue == null || lstrValue.length == 0 ){\n aField.value = lstrValue;\n return;\n }\n var posNeg=lstrValue.indexOf('-');\n\n // Get the number of digits that can be there before period (.)\n lintLen = aintDigits;\n // Get the number of digits that can be there after period (.)\n lDeciLen = aintDecimals;\n\n allVal = lstrValue.split(\".\")\n\n if(posNeg != 0) {\n intVal = allVal[0];\n } else {\n intVal = allVal[0].substring(1,allVal[0].length);\n }\n\n floatVal = allVal[1];\n\n var i = intVal.length;\n\n while(i >= 1) {\n\n if(intVal.indexOf(\"0\",0) == 0 ) {\n intVal = intVal.substring(1);\n }\n i = i-1;\n }\n\n if(intVal==null || intVal.length==0 ){\n intVal = \"0\";\n }\n\n if(allVal.length > 1){\n // Validating Float\n if(!validateFloat(lstrValue,lintLen,lDeciLen,true)){\n return;\n }\n }else{\n // Validating Integer\n if(!isInteger(intVal)){\n return;\n }\n }\n if(intVal.length > lintLen) {\n intVal = intVal.substring(0,lintLen);\n }\n if(allVal.length > 1){\n if(floatVal.length > lDeciLen) {\n floatVal = floatVal.substring(0,lDeciLen);\n } else if(floatVal.length < lDeciLen) {\n temp = floatVal.length;\n for(i = 0;i<(lDeciLen - temp);i++) {\n floatVal = floatVal + \"0\";\n }\n }\n }else{\n floatVal = \"\";\n for(i = 0;i<lDeciLen ;i++) {\n floatVal = floatVal + \"0\";\n }\n }\n remString = intVal;\n finalString = \"\";\n if(lintLen > 3) {\n while(remString.length > 3)\n {\n\n finalString = \",\" + remString.substring(remString.length-3) + finalString;\n remString = remString.substring(0,remString.length-3);\n }\n }\n finalString = remString + finalString ;\n finalString = finalString + \".\" + floatVal;\n aField.value = ((posNeg == 0 && finalString != 0)?'-':'') + finalString;\n}",
"function formatDecimal(field,lunghezzaInteri,lunghezzaDecimali,visualizzaSeparatoreMigliaia)\n{\n\tvar obj;\n\n\tformatError=false;\n\n\tif (field.toString().indexOf(\"object\")>=0)\n\t\tobj=field.value; \n\telse \n\t\tobj=field+\"\";\n\t\n\tif (obj==\"\")\n\t\treturn;\n\n\tvar reSeparatoreMigliaia = /\\./g;\n\t\n // Controllo formato numero\n var reFormato = new RegExp('^([-+]?\\\\d{1,'+lunghezzaInteri+'}\\\\,\\\\d{0,'+lunghezzaDecimali+'}|([-+]?\\\\d{1,'+lunghezzaInteri+'}))$');\n var app=obj.replace(reSeparatoreMigliaia,\"\");\t//elimina il separatoreMigliaia dal testo \n if (app.search(reFormato)==-1)\n {\n \talert(\"Numero in formato errato \\n(Formato ammesso: massimo \"+lunghezzaInteri+\" interi e massimo \"+lunghezzaDecimali+\" decimali)\");\n \tif (field.toString().indexOf(\"object\")>=0) field.focus();\n \tformatError=true;\n\t\treturn;\t\n }\n\t\n\t// Formattazione tramite NumberFormat153.js\n\tvar num = new NumberFormat();\n\tnum.setInputDecimal(',');\t\t//separatore dei decimali\n\tnum.setNumber(obj);\t//imposta il numero da formattare\n\tnum.setPlaces(lunghezzaDecimali);\t//numero di decimali, Nota: con -1 non si esegue arrotondamenti sui decimali\n\t//num.setCurrencyValue('�');\t//simbolo valuta\n\tnum.setCurrency(false);\t\t\t//visualizzazione del simbolo valuta\n\tnum.setCurrencyPosition(num.LEFT_OUTSIDE);\t//posizionamento del simbolo valuta\n\tnum.setNegativeFormat(num.LEFT_DASH);\t//posizionamento del segno\n\tnum.setNegativeRed(false);\t//in rosso i numeri negativi\n\tnum.setSeparators(true, '.', ',');\t//separatore delle migliaia e dei decimali\n\tobj = num.toFormatted();\t\t//esegue la formattazione\n\t\n\t// Elimina il separatore delle migliaia se non richiesto\n\tif (visualizzaSeparatoreMigliaia==false)\n\t\tobj=obj.replace(reSeparatoreMigliaia,\"\");\n\t\t\n\tif (field.toString().indexOf(\"object\")<0) \n\t\treturn obj;\n\telse\n\t\tfield.value=obj;\t\n}",
"function justNumberNF(val)\n{\n\tnewVal = val + '';\n\t\n\tvar isPercentage = false;\n\t\n\t// check for percentage\n\t// v1.5.0\n\tif (newVal.indexOf('%') != -1) \n\t{\n\t\tnewVal = newVal.replace(/\\%/g, '');\n\t\tisPercentage = true; // mark a flag\n\t}\n\t\t\n\t// Replace everything but digits - + ( ) e E\n\tvar re = new RegExp('[^\\\\' + this.inputDecimalValue + '\\\\d\\\\-\\\\+\\\\(\\\\)eE]', 'g');\t// v1.5.2\t\n\tnewVal = newVal.replace(re, '');\n\t// Replace the first decimal with a period and the rest with blank\n\t// The regular expression will only break if a special character\n\t// is used as the inputDecimalValue\n\t// e.g. \\ but not .\n\tvar tempRe = new RegExp('[' + this.inputDecimalValue + ']', 'g');\n\tvar treArray = tempRe.exec(newVal); // v1.5.2\n\tif (treArray != null) \n\t{\n\t var tempRight = newVal.substring(treArray.index + treArray[0].length); // v1.5.2\n\t\tnewVal = newVal.substring(0,treArray.index) + this.PERIOD + tempRight.replace(tempRe, ''); // v1.5.2\n\t}\n\t\n\t// If negative, get it in -n format\n\tif (newVal.charAt(newVal.length - 1) == this.DASH ) \n\t{\n\t\tnewVal = newVal.substring(0, newVal.length - 1);\n\t\tnewVal = '-' + newVal;\n\t}\n\telse if (newVal.charAt(0) == this.LEFT_PAREN\n\t && newVal.charAt(newVal.length - 1) == this.RIGHT_PAREN) \n\t{\n\t\tnewVal = newVal.substring(1, newVal.length - 1);\n\t\tnewVal = '-' + newVal;\n\t}\n\t\n\tnewVal = parseFloat(newVal);\n\t\n\tif (!isFinite(newVal)) \n\t\tnewVal = 0;\n\t\n\t// now that it's a number, adjust for percentage, if applicable.\n // example. if the number was formatted 24%, then move decimal left to get 0.24\n // v1.5.0 - updated v1.5.1\n if (isPercentage) \n \t\tnewVal = this.moveDecimalLeft(newVal, 2);\n\t\t\n\treturn newVal;\n}",
"function formatNumber() {\n var n = 64.5;\n n.toFixed(0);\n return n;\n\n}",
"function putMask_PartNumber(aField, aMask, aFranchise){\n\n var lstrValue = aField.value;\n var finalString = '';\n var lintIndex = -1;\n var lintReplaceIndex = -1;\n var lstrFormatMask = aMask;\n\n handlePartFranchise( '0', aField, aFranchise, arguments[3]);\n\n if(validatePartNo(aField)) {\n lstrValue = trimString(lstrValue);\n lstrValue = lstrValue.toUpperCase();\n\n if( aFranchise != null && aFranchise.length > 0 )\n {\n lstrValue = lstrValue.substring(1);\n }\n re = new RegExp(\"-\",\"g\");\n lstrValue = lstrValue.replace(re,'');\n\n finalString = lstrValue;\n\n if(lstrFormatMask != null && lstrFormatMask.length >0 ){\n lstrFormatMask = trimString(aMask.toUpperCase());\n\n while((lintIndex = lstrFormatMask.indexOf(\"-\")) > -1){\n lintReplaceIndex = lintReplaceIndex + lintIndex + 1;\n if(lintReplaceIndex < finalString.length){\n finalString = finalString.substring(0,lintReplaceIndex) +\n '-' +\n finalString.substring(lintReplaceIndex);\n }else{\n break;\n }\n lstrFormatMask = lstrFormatMask.substring(lintIndex +1);\n }\n }\n if( aFranchise != null && aFranchise.length > 0 )\n {\n finalString = aFranchise + '-' + finalString;\n }\n\n aField.value = finalString;\n\n }\n}",
"function SysFmtRoundDecimal() {}",
"toNumberString() {\n return this.toSortedArrayNumber().join(\",\");\n }",
"function format_number(label, unit, ndec, dec, grp) {\n if (isNaN(label)) return '';\n if (unit === undefined) unit = '';\n if (dec === undefined) dec = '.';\n if (grp === undefined) grp = '';\n // round number\n if (ndec !== undefined) {\n label = label.toFixed(ndec);\n } else {\n label = label.toString();\n }\n // Following based on code from \n // http://www.mredkj.com/javascript/numberFormat.html\n x = label.split('.');\n x1 = x[0];\n x2 = x.length > 1 ? dec + x[1] : '';\n if (grp !== '') {\n var rgx = /(\\d+)(\\d{3})/;\n while (rgx.test(x1)) {\n x1 = x1.replace(rgx, '$1' + grp + '$2');\n }\n }\n return(x1 + x2 + unit);\n}",
"function getNmask(field, aSep, lZero, vMin, vMax) {\r\n jQuery ( function($) { \r\n $('#'+field).autoNumeric('init',{aSep:aSep,lZero:lZero,vMin:vMin,vMax:vMax})\r\n })\r\n}",
"fracNum() {\n return styles[fracNum[this.id]];\n }",
"formatValue(cell){\n\t\tvar component = cell.getComponent(),\n\t\tparams = typeof cell.column.modules.format.params === \"function\" ? cell.column.modules.format.params(component) : cell.column.modules.format.params;\n\t\t\n\t\tfunction onRendered(callback){\n\t\t\tif(!cell.modules.format){\n\t\t\t\tcell.modules.format = {};\n\t\t\t}\n\t\t\t\n\t\t\tcell.modules.format.renderedCallback = callback;\n\t\t\tcell.modules.format.rendered = false;\n\t\t}\n\t\t\n\t\treturn cell.column.modules.format.formatter.call(this, component, params, onRendered);\n\t}",
"function noFlagsPercentDataProvider(fid) {\n // Decimal number\n var decimalInput = '[{id: ' + fid + ', value: ' + numberDecimalOnly + '}]';\n var expectedDecimalRecord = '{id: ' + fid + ', value: ' + numberDecimalOnly + ', display: \"0.74765432000000%\"}';\n\n // Double number\n var doubleInput = '[{id: ' + fid + ', value: ' + numberDouble + '}]';\n var expectedDoubleRecord = '{id: ' + fid + ', value: ' + numberDouble + ', display: \"98765432100.74765000000000%\"}';\n\n // Int number\n var intInput = '[{id: ' + fid + ', value: ' + numberInt + '}]';\n var expectedIntRecord = '{id: ' + fid + ', value: ' + numberInt + ', display: \"99.00000000000000%\"}';\n\n // Null number\n var nullInput = '[{id: ' + fid + ', value: null}]';\n var expectedNullRecord = '{id: ' + fid + ', value: null, display: \"\"}';\n\n return [\n {\n message : 'display decimal number with no format flags',\n record : decimalInput,\n format : 'display',\n expectedFieldValue: expectedDecimalRecord\n },\n {\n message : 'raw decimal number with no format flags',\n record : decimalInput,\n format : 'raw',\n expectedFieldValue: decimalInput\n },\n {\n message : 'display double number with no format flags',\n record : doubleInput,\n format : 'display',\n expectedFieldValue: expectedDoubleRecord\n },\n {\n message : 'raw double number with no format flags',\n record : doubleInput,\n format : 'raw',\n expectedFieldValue: doubleInput\n },\n {\n message : 'display int number with no format flags',\n record : intInput,\n format : 'display',\n expectedFieldValue: expectedIntRecord\n },\n {\n message : 'raw int number with no format flags',\n record : intInput,\n format : 'raw',\n expectedFieldValue: intInput\n },\n {\n message : 'display null number with no format flags',\n record : nullInput,\n format : 'display',\n expectedFieldValue: expectedNullRecord\n },\n {\n message : 'raw null number with no format flags',\n record : nullInput,\n format : 'raw',\n expectedFieldValue: nullInput\n }\n ];\n }",
"function FormatNumber(srcStr, nAfterDot){\r\n\tvar srcStr,nAfterDot;\r\n\tvar resultStr,nTen;\r\n\tsrcStr = \"\"+srcStr+\"\";\r\n\tstrLen = srcStr.length;\r\n\tdotPos = srcStr.indexOf(\".\",0);\r\n\tif (dotPos == -1){\r\n\t\tresultStr = srcStr+\".\";\r\n\t\tfor (i=0;i<nAfterDot;i++){\r\n\t\t\tresultStr = resultStr+\"0\";\r\n\t\t}\r\n\t}else{\r\n\t\tif ((strLen - dotPos - 1) >= nAfterDot){\r\n\t\t\tnAfter = dotPos + nAfterDot + 1;\r\n\t\t\tnTen =1;\r\n\t\t\tfor(j=0;j<nAfterDot;j++){\r\n\t\t\t\tnTen = nTen*10;\r\n\t\t\t}\r\n\t\t\tresultStr = Math.round(parseFloat(srcStr)*nTen)/nTen;\r\n\t\t}else{\r\n\t\t\tresultStr = srcStr;\r\n\t\t\tfor (i=0;i<(nAfterDot - strLen + dotPos + 1);i++){\r\n\t\t\t\tresultStr = resultStr+\"0\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn resultStr;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Truncates, at the end, the text content of a node using binary search | function truncateTextEnd($element, $rootNode, $clipNode, options) {
var element = $element[0];
var original = $element.text();
var maxChunk = '';
var mid, chunk;
var low = 0;
var high = original.length;
// Binary Search
while (low <= high) {
mid = low + ((high - low) >> 1); // Integer division
chunk = trimRight(original.substr(0, mid + 1)) + options.ellipsis;
setText(element, chunk);
if ($rootNode.height() > options.maxHeight) {
// too big, reduce the chunk
high = mid - 1;
} else {
// chunk valid, try to get a bigger chunk
low = mid + 1;
maxChunk = maxChunk.length > chunk.length ? maxChunk : chunk;
}
}
if (maxChunk.length > 0) {
setText(element, maxChunk);
return true;
} else {
return truncateNearestSibling($element, $rootNode, $clipNode, options);
}
} | [
"function docClear (node)\n{\n\twhile (node.firstChild)\n\t\tnode.removeChild(node.firstChild);\n\tnode.innerHTML = \"\";\n}",
"function findMatch(node, params) {\n\n var nodeValue = node.nodeValue.trim();\n var nodeIndex = params.nodeIndex;\n var searchTerm = params.searchTerm;\n var searchElements = params.searchElements;\n var field = params.field;\n var total = params.total;\n var count = params.count;\n var text = params.text;\n var currentIndex = params.currentIndex;\n\n if (text === \"\") {\n text = nodeValue;\n } else {\n text += \" \" + nodeValue;\n }\n console.log(\"nodeIndex: \" + nodeIndex + \" - \" + nodeValue);\n console.log(textNodes[nodeIndex]);\n\n // if searchTerm is found, current text node is the end node for one count\n var index = text.toLowerCase().indexOf(searchTerm.toLowerCase(), currentIndex + 1);\n\n // if there is multiple instances of searchTerm in text (loops through while loop), use oldStartIndex to calculate startIndex\n var oldStartIndex, startNodeIndex;\n\n // stores the number of characters the start of searchTerm is from the end of text\n var charactersFromEnd = text.length - index;\n //console.log(\"charactersFromEnd: \" + charactersFromEnd);\n\n // loop through text node in case there is more than one searchTerm instance in text\n while (index !== -1) {\n currentIndex = index;\n\n // remember how many text nodes before current node we are pulling from textNodes\n var textNodesBackIndex = nodeIndex - 1;\n console.log(textNodesBackIndex);\n\n // textSelection will contain a combined string of all text nodes where current searchTerm spans over\n var textSelection = nodeValue;\n var startNode;\n\n // set textSelection to contain prevSibling text nodes until the current searchTerm matches\n while (textSelection.length < charactersFromEnd) {\n console.log(\"textSelection.length: \" + textSelection.length + \" < \" + charactersFromEnd);\n //console.log(\"old textSelection: \" + textSelection);\n console.log(\"textnodesback index: \" + textNodesBackIndex + \" \" + textNodes[textNodesBackIndex].nodeValue);\n\n textSelection = textNodes[textNodesBackIndex].nodeValue.trim() + \" \" + textSelection;\n //console.log(\"space added: \" + textSelection);\n textNodesBackIndex--;\n }\n\n // use old startNodeIndex value before re-calculating it if its the same as new startNodeIndex\n // startIndex needs to ignore previous instances of text\n var startIndex;\n if (startNodeIndex != null && startNodeIndex === textNodesBackIndex + 1) {\n // find index searchTerm starts on in text node (or prevSibling)\n startIndex = textSelection.toLowerCase().indexOf(searchTerm.toLowerCase(), oldStartIndex + 1);\n } else {\n startIndex = textSelection.toLowerCase().indexOf(searchTerm.toLowerCase());\n }\n oldStartIndex = startIndex;\n\n // startNode contains beginning of searchTerm and node contains end of searchTerm\n var startNodeIndex = textNodesBackIndex + 1;\n // possibly null parentNode because highlighted text before, adding MARK tag and then removed it\n startNode = textNodes[startNodeIndex];\n //console.log(\"final textSelection: \" + textSelection);\n\n if (startIndex !== -1) {\n // set parent as first element parent of textNode\n console.log(\"end parent\");\n console.log(node);\n var endParent = node.parentNode;\n\n console.log(\"start parent\");\n console.log(startNode);\n var startParent = startNode.parentNode;\n\n var targetParent;\n // start and end parents are the same\n if (startParent === endParent) {\n console.log(\"start parent is end parent\");\n targetParent = startParent;\n }\n // start parent is target parent element\n else if ($.contains(startParent, endParent)) {\n console.log(\"start parent is larger\");\n targetParent = startParent;\n }\n // end parent is target parent element\n else if ($.contains(endParent, startParent)) {\n console.log(\"end parent is larger\");\n targetParent = endParent;\n }\n // neither parents contain one another\n else {\n console.log(\"neither parent contains the other\");\n // iterate upwards until startParent contains endParent\n while (!$.contains(startParent, endParent) && startParent !== endParent) {\n startParent = startParent.parentNode;\n //console.log(startParent);\n }\n targetParent = startParent;\n }\n\n // set startNode to node before the parent we are calculating with\n if (textNodesBackIndex !== -1) {\n startNode = textNodes[textNodesBackIndex];\n textNodesBackIndex--;\n\n var startElement = startNode.parentNode;\n\n // continue adding text length to startIndex until parent elements are not contained in targetParent\n while (($.contains(targetParent, startElement) || targetParent === startElement) && textNodesBackIndex !== -1) {\n startIndex += startNode.nodeValue.trim().length + 1;\n startNode = textNodes[textNodesBackIndex];\n textNodesBackIndex--;\n startElement = startNode.parentNode;\n }\n }\n\n // find index searchTerm ends on in text node\n var endIndex = startIndex + searchTerm.length;\n /*console.log(\"start index: \" + startIndex);\n console.log(\"end index: \" + endIndex);*/\n\n // if a class for field search already exists, use that instead\n var dataField = \"data-tworeceipt-\" + field + \"-search\";\n if ($(targetParent).attr(dataField) != null) {\n console.log(\"EXISTING SEARCH ELEMENT\");\n console.log($(targetParent).attr(dataField));\n searchElements[count] = {\n start: startIndex,\n end: endIndex,\n data: parseInt($(targetParent).attr(dataField)),\n startNodeIndex: startNodeIndex,\n endNodeIndex: nodeIndex\n };\n } else {\n searchElements[count] = {\n start: startIndex,\n end: endIndex,\n data: count,\n startNodeIndex: startNodeIndex,\n endNodeIndex: nodeIndex\n };\n console.log(\"NEW SEARCH ELEMENT\");\n $(targetParent).attr(dataField, count);\n console.log($(targetParent));\n }\n\n console.log(searchElements[count]);\n\n count++;\n } else {\n console.log(textSelection);\n console.log(searchTerm);\n }\n\n index = text.toLowerCase().indexOf(searchTerm.toLowerCase(), currentIndex + 1);\n charactersFromEnd = text.length - index;\n //console.log(\"characters from end: \" + charactersFromEnd);\n\n if (total != null && count === total) {\n console.log(\"Completed calculations for all matched searchTerms\");\n nodeIndex++;\n return {\n nodeIndex: nodeIndex,\n searchTerm: searchTerm,\n searchElements: searchElements,\n field: field,\n total: total,\n count: count,\n text: text,\n currentIndex: currentIndex,\n result: false\n };\n }\n }\n nodeIndex++;\n return {\n nodeIndex: nodeIndex,\n searchTerm: searchTerm,\n searchElements: searchElements,\n field: field,\n total: total,\n count: count,\n text: text,\n currentIndex: currentIndex,\n result: true\n };\n}",
"fragment(root, range) {\n if (Text.isText(root)) {\n throw new Error(\"Cannot get a fragment starting from a root text node: \".concat(JSON.stringify(root)));\n }\n\n var newRoot = produce(root, r => {\n var [start, end] = Range.edges(range);\n var nodeEntries = Node.nodes(r, {\n reverse: true,\n pass: (_ref) => {\n var [, path] = _ref;\n return !Range.includes(range, path);\n }\n });\n\n for (var [, path] of nodeEntries) {\n if (!Range.includes(range, path)) {\n var parent = Node.parent(r, path);\n var index = path[path.length - 1];\n parent.children.splice(index, 1);\n }\n\n if (Path.equals(path, end.path)) {\n var leaf = Node.leaf(r, path);\n leaf.text = leaf.text.slice(0, end.offset);\n }\n\n if (Path.equals(path, start.path)) {\n var _leaf = Node.leaf(r, path);\n\n _leaf.text = _leaf.text.slice(start.offset);\n }\n }\n\n delete r.selection;\n });\n return newRoot.children;\n }",
"fragment(root, range) {\n if (Text.isText(root)) {\n throw new Error(\"Cannot get a fragment starting from a root text node: \".concat(JSON.stringify(root)));\n }\n\n var newRoot = fn$4({\n children: root.children\n }, r => {\n var [start, end] = Range.edges(range);\n var nodeEntries = Node$1.nodes(r, {\n reverse: true,\n pass: (_ref) => {\n var [, path] = _ref;\n return !Range.includes(range, path);\n }\n });\n\n for (var [, path] of nodeEntries) {\n if (!Range.includes(range, path)) {\n var parent = Node$1.parent(r, path);\n var index = path[path.length - 1];\n parent.children.splice(index, 1);\n }\n\n if (Path.equals(path, end.path)) {\n var leaf = Node$1.leaf(r, path);\n leaf.text = leaf.text.slice(0, end.offset);\n }\n\n if (Path.equals(path, start.path)) {\n var _leaf = Node$1.leaf(r, path);\n\n _leaf.text = _leaf.text.slice(start.offset);\n }\n }\n\n if (Editor.isEditor(r)) {\n r.selection = null;\n }\n });\n return newRoot.children;\n }",
"function trimSearchTerm(search) {\n var maxLength = 200;\n if (search.length > maxLength) {\n search = search.slice(0, maxLength);\n var lastColonPosition = search.lastIndexOf(\":\");\n if (lastColonPosition !== -1) {\n search = search.slice(0, lastColonPosition);\n }\n }\n return search;\n}",
"delete(word) {\n\t\t// Helper function:\n\t\t// Works through the levels of the word/key\n\t\t// Once it reaches the end of the word, it checks if the last node\n\t\t// has any children. If it does, we just mark as no longer an end.\n\t\t// If it doesn't, we continue bubbling up deleting the keys until we find a node\n\t\t// that either has other children or is marked as an end.\n\t\tconst deleteHelper = (word, node, length, level) => {\n\t\t\tlet deletedSelf = false;\n\t\t\tif (!node) {\n\t\t\t\tconsole.log(\"Key doesn't exist\");\n\t\t\t\treturn deletedSelf;\n\t\t\t}\n\n\t\t\t// Base case\n\t\t\tif (length === level) {\n\t\t\t\tif (node.keys.length === 0) {\n\t\t\t\t\tdeletedSelf = true;\n\t\t\t\t} else {\n\t\t\t\t\tnode.setNotEnd();\n\t\t\t\t\tdeletedSelf = false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlet childNode = node.keys.get(word[level]);\n\t\t\t\tlet childDeleted = deleteHelper(word, childNode, length, level + 1);\n\t\t\t\tif (childDeleted) {\n\t\t\t\t\tnode.keys.delete(word[level]);\n\n\t\t\t\t\tif (node.isEnd()) {\n\t\t\t\t\t\tdeletedSelf = false;\n\t\t\t\t\t} else if (node.keys.length) {\n\t\t\t\t\t\tdeletedSelf = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdeletedSelf = true;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tdeletedSelf = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn deletedSelf;\n\t\t};\n\n\t\tdeleteHelper(word, this.root, word.length, 0);\n\t}",
"function merge(n) {\n if (n.nodeType === Node.TEXT_NODE) {\n if (n.nextSibling && n.nextSibling.nodeType === Node.TEXT_NODE) {\n n.textContent += n.nextSibling.textContent;\n n.nextSibling.parentNode.removeChild(n.nextSibling);\n }\n\n if (n.previousSibling && n.previousSibling.nodeType === Node.TEXT_NODE) {\n n.previousSibling.textContent += n.textContent;\n n.parentNode.removeChild(n);\n }\n }\n}",
"delete(val) {\n debugger\n let currentNode = this.root;\n let found = false;\n let nodeToRemove;\n let parent = null;\n\n // find the node we want to remove\n while (!found) {\n if (currentNode === null || currentNode.val === null) {\n return 'the node was not found'\n }\n if (val === currentNode.val) {\n nodeToRemove = currentNode;\n found = true;\n } else if (val < currentNode.val) {\n parent = currentNode;\n currentNode = currentNode.left;\n } else {\n parent = currentNode;\n currentNode = currentNode.right;\n }\n }\n\n console.log(\"We found the node\");\n console.log('parent node', parent);\n\n // helper variable which returns true if the node we've removing is the left\n // child and false if it's right\n const nodeToRemoveIsParentsLeftChild = parent.left === nodeToRemove;\n\n // if nodeToRemove is a leaf node, remove it\n if (nodeToRemove.left === null && nodeToRemove.right === null) {\n if (nodeToRemoveIsParentsLeftChild) parent.left = null;\n else parent.right = null\n } else if (nodeToRemove.left !== null && nodeToRemove.right === null) {\n // only has a left child\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = nodeToRemove.left;\n } else {\n parent.right = nodeToRemove.left;\n }\n } else if (nodeToRemove.left === null && nodeToRemove.right !== null) {\n // only has a right child\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = nodeToRemove.right;\n } else {\n parent.right = nodeToRemove.right;\n }\n } else {\n // has 2 children\n const rightSubTree = nodeToRemove.right;\n const leftSubTree = nodeToRemove.left;\n // sets parent nodes respective child to the right sub tree\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = rightSubTree;\n } else {\n parent.right = rightSubTree;\n }\n\n // find the lowest free space on the left side of the right sub tree\n // and add the leftSubtree\n let currentLeftNode = rightSubTree;\n let currentLeftParent;\n let foundSpace = false;\n while (!foundSpace) {\n if (currentLeftNode === null) foundSpace = true;\n else {\n currentLeftParent = currentLeftNode;\n currentLeftNode = currentLeftNode.left;\n }\n }\n currentLeftParent.left = leftSubTree;\n return 'the node was successfully deleted'\n }\n }",
"function findFirstTextNode(element, startIndex) {\n var index = null;\n startIndex = startIndex || 0;\n\n if (startIndex < textNodes.length) {\n for (var i = startIndex; i < textNodes.length; i++) {\n if ($.contains(element, textNodes[i])) {\n index = i;\n break;\n }\n }\n }\n\n return index;\n}",
"function myExtractContents(range) {\n // \"Let frag be a new DocumentFragment whose ownerDocument is the same as\n // the ownerDocument of the context object's start node.\"\n var ownerDoc = range.startContainer.nodeType == Node.DOCUMENT_NODE\n ? range.startContainer\n : range.startContainer.ownerDocument;\n var frag = ownerDoc.createDocumentFragment();\n\n // \"If the context object's start and end are the same, abort this method,\n // returning frag.\"\n if (range.startContainer == range.endContainer\n && range.startOffset == range.endOffset) {\n return frag;\n }\n\n // \"Let original start node, original start offset, original end node, and\n // original end offset be the context object's start and end nodes and\n // offsets, respectively.\"\n var originalStartNode = range.startContainer;\n var originalStartOffset = range.startOffset;\n var originalEndNode = range.endContainer;\n var originalEndOffset = range.endOffset;\n\n // \"If original start node is original end node, and they are a Text,\n // ProcessingInstruction, or Comment node:\"\n if (range.startContainer == range.endContainer\n && (range.startContainer.nodeType == Node.TEXT_NODE\n || range.startContainer.nodeType == Node.PROCESSING_INSTRUCTION_NODE\n || range.startContainer.nodeType == Node.COMMENT_NODE)) {\n // \"Let clone be the result of calling cloneNode(false) on original\n // start node.\"\n var clone = originalStartNode.cloneNode(false);\n\n // \"Set the data of clone to the result of calling\n // substringData(original start offset, original end offset − original\n // start offset) on original start node.\"\n clone.data = originalStartNode.substringData(originalStartOffset,\n originalEndOffset - originalStartOffset);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Call deleteData(original start offset, original end offset −\n // original start offset) on original start node.\"\n originalStartNode.deleteData(originalStartOffset,\n originalEndOffset - originalStartOffset);\n\n // \"Abort this method, returning frag.\"\n return frag;\n }\n\n // \"Let common ancestor equal original start node.\"\n var commonAncestor = originalStartNode;\n\n // \"While common ancestor is not an ancestor container of original end\n // node, set common ancestor to its own parent.\"\n while (!isAncestorContainer(commonAncestor, originalEndNode)) {\n commonAncestor = commonAncestor.parentNode;\n }\n\n // \"If original start node is an ancestor container of original end node,\n // let first partially contained child be null.\"\n var firstPartiallyContainedChild;\n if (isAncestorContainer(originalStartNode, originalEndNode)) {\n firstPartiallyContainedChild = null;\n // \"Otherwise, let first partially contained child be the first child of\n // common ancestor that is partially contained in the context object.\"\n } else {\n for (var i = 0; i < commonAncestor.childNodes.length; i++) {\n if (isPartiallyContained(commonAncestor.childNodes[i], range)) {\n firstPartiallyContainedChild = commonAncestor.childNodes[i];\n break;\n }\n }\n if (!firstPartiallyContainedChild) {\n throw \"Spec bug: no first partially contained child!\";\n }\n }\n\n // \"If original end node is an ancestor container of original start node,\n // let last partially contained child be null.\"\n var lastPartiallyContainedChild;\n if (isAncestorContainer(originalEndNode, originalStartNode)) {\n lastPartiallyContainedChild = null;\n // \"Otherwise, let last partially contained child be the last child of\n // common ancestor that is partially contained in the context object.\"\n } else {\n for (var i = commonAncestor.childNodes.length - 1; i >= 0; i--) {\n if (isPartiallyContained(commonAncestor.childNodes[i], range)) {\n lastPartiallyContainedChild = commonAncestor.childNodes[i];\n break;\n }\n }\n if (!lastPartiallyContainedChild) {\n throw \"Spec bug: no last partially contained child!\";\n }\n }\n\n // \"Let contained children be a list of all children of common ancestor\n // that are contained in the context object, in tree order.\"\n //\n // \"If any member of contained children is a DocumentType, raise a\n // HIERARCHY_REQUEST_ERR exception and abort these steps.\"\n var containedChildren = [];\n for (var i = 0; i < commonAncestor.childNodes.length; i++) {\n if (isContained(commonAncestor.childNodes[i], range)) {\n if (commonAncestor.childNodes[i].nodeType\n == Node.DOCUMENT_TYPE_NODE) {\n return \"HIERARCHY_REQUEST_ERR\";\n }\n containedChildren.push(commonAncestor.childNodes[i]);\n }\n }\n\n // \"If original start node is an ancestor container of original end node,\n // set new node to original start node and new offset to original start\n // offset.\"\n var newNode, newOffset;\n if (isAncestorContainer(originalStartNode, originalEndNode)) {\n newNode = originalStartNode;\n newOffset = originalStartOffset;\n // \"Otherwise:\"\n } else {\n // \"Let reference node equal original start node.\"\n var referenceNode = originalStartNode;\n\n // \"While reference node's parent is not null and is not an ancestor\n // container of original end node, set reference node to its parent.\"\n while (referenceNode.parentNode\n && !isAncestorContainer(referenceNode.parentNode, originalEndNode)) {\n referenceNode = referenceNode.parentNode;\n }\n\n // \"Set new node to the parent of reference node, and new offset to one\n // plus the index of reference node.\"\n newNode = referenceNode.parentNode;\n newOffset = 1 + indexOf(referenceNode);\n }\n\n // \"If first partially contained child is a Text, ProcessingInstruction, or\n // Comment node:\"\n if (firstPartiallyContainedChild\n && (firstPartiallyContainedChild.nodeType == Node.TEXT_NODE\n || firstPartiallyContainedChild.nodeType == Node.PROCESSING_INSTRUCTION_NODE\n || firstPartiallyContainedChild.nodeType == Node.COMMENT_NODE)) {\n // \"Let clone be the result of calling cloneNode(false) on original\n // start node.\"\n var clone = originalStartNode.cloneNode(false);\n\n // \"Set the data of clone to the result of calling substringData() on\n // original start node, with original start offset as the first\n // argument and (length of original start node − original start offset)\n // as the second.\"\n clone.data = originalStartNode.substringData(originalStartOffset,\n nodeLength(originalStartNode) - originalStartOffset);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Call deleteData() on original start node, with original start\n // offset as the first argument and (length of original start node −\n // original start offset) as the second.\"\n originalStartNode.deleteData(originalStartOffset,\n nodeLength(originalStartNode) - originalStartOffset);\n // \"Otherwise, if first partially contained child is not null:\"\n } else if (firstPartiallyContainedChild) {\n // \"Let clone be the result of calling cloneNode(false) on first\n // partially contained child.\"\n var clone = firstPartiallyContainedChild.cloneNode(false);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Let subrange be a new Range whose start is (original start node,\n // original start offset) and whose end is (first partially contained\n // child, length of first partially contained child).\"\n var subrange = ownerDoc.createRange();\n subrange.setStart(originalStartNode, originalStartOffset);\n subrange.setEnd(firstPartiallyContainedChild,\n nodeLength(firstPartiallyContainedChild));\n\n // \"Let subfrag be the result of calling extractContents() on\n // subrange.\"\n var subfrag = myExtractContents(subrange);\n\n // \"For each child of subfrag, in order, append that child to clone as\n // its last child.\"\n for (var i = 0; i < subfrag.childNodes.length; i++) {\n clone.appendChild(subfrag.childNodes[i]);\n }\n }\n\n // \"For each contained child in contained children, append contained child\n // as the last child of frag.\"\n for (var i = 0; i < containedChildren.length; i++) {\n frag.appendChild(containedChildren[i]);\n }\n\n // \"If last partially contained child is a Text, ProcessingInstruction, or\n // Comment node:\"\n if (lastPartiallyContainedChild\n && (lastPartiallyContainedChild.nodeType == Node.TEXT_NODE\n || lastPartiallyContainedChild.nodeType == Node.PROCESSING_INSTRUCTION_NODE\n || lastPartiallyContainedChild.nodeType == Node.COMMENT_NODE)) {\n // \"Let clone be the result of calling cloneNode(false) on original\n // end node.\"\n var clone = originalEndNode.cloneNode(false);\n\n // \"Set the data of clone to the result of calling substringData(0,\n // original end offset) on original end node.\"\n clone.data = originalEndNode.substringData(0, originalEndOffset);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Call deleteData(0, original end offset) on original end node.\"\n originalEndNode.deleteData(0, originalEndOffset);\n // \"Otherwise, if last partially contained child is not null:\"\n } else if (lastPartiallyContainedChild) {\n // \"Let clone be the result of calling cloneNode(false) on last\n // partially contained child.\"\n var clone = lastPartiallyContainedChild.cloneNode(false);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Let subrange be a new Range whose start is (last partially\n // contained child, 0) and whose end is (original end node, original\n // end offset).\"\n var subrange = ownerDoc.createRange();\n subrange.setStart(lastPartiallyContainedChild, 0);\n subrange.setEnd(originalEndNode, originalEndOffset);\n\n // \"Let subfrag be the result of calling extractContents() on\n // subrange.\"\n var subfrag = myExtractContents(subrange);\n\n // \"For each child of subfrag, in order, append that child to clone as\n // its last child.\"\n for (var i = 0; i < subfrag.childNodes.length; i++) {\n clone.appendChild(subfrag.childNodes[i]);\n }\n }\n\n // \"Set the context object's start and end to (new node, new offset).\"\n range.setStart(newNode, newOffset);\n range.setEnd(newNode, newOffset);\n\n // \"Return frag.\"\n return frag;\n}",
"search(suffix, node=this.root) {\n if (suffix === \"\") return true;\n\n let i;\n\n for (i = 0; i < node.substring.length; i++) {\n if (suffix.charAt(i) !== node.substring.charAt(i)) return false;\n if (i === suffix.length - 1) return true;\n }\n\n let result = false;\n\n node.children.forEach(child => result ||= this.search(suffix.slice(i), child));\n\n return result;\n }",
"textAfterPos(pos) {\n var _a, _b;\n let sim = (_a = this.options) === null || _a === void 0 ? void 0 : _a.simulateBreak;\n if (pos == sim && ((_b = this.options) === null || _b === void 0 ? void 0 : _b.simulateDoubleBreak))\n return \"\";\n return this.state.sliceDoc(pos, Math.min(pos + 100, sim != null && sim > pos ? sim : 1e9, this.state.doc.lineAt(pos).to));\n }",
"function removeStrainSearch() {\n const resultsContainer = document.querySelector('.results-container')\n while (resultsContainer.lastChild) {\n resultsContainer.removeChild(resultsContainer.lastChild)\n }\n}",
"function findTextNodeInElement(direction, element) {\r\n if (direction == \"left\") {\r\n // find node for element\r\n var node = element.childNodes[0];\r\n while (node.childNodes.length > 0) {\r\n node = node.childNodes[0];\r\n }\r\n \r\n // iterate right through element until node contains TEXT_ID\r\n var previous_node, const_index;\r\n if (node.nodeValue == null) {\r\n const_index = -1;\r\n } else {\r\n const_index = node.nodeValue.indexOf(TEXT_ID);\r\n }\r\n while (const_index == -1) {\r\n //previous_node = node;\r\n node = findNextNode(\"right\", node);\r\n if (node.nodeValue == null) {\r\n const_index = -1;\r\n } else {\r\n const_index = node.nodeValue.indexOf(TEXT_ID);\r\n }\r\n }\r\n return node;\r\n } else {\r\n // find node for element\r\n var node = element.childNodes[element.childNodes.length - 1];\r\n while (node.childNodes.length > 0) {\r\n node = node.childNodes[node.childNodes.length - 1];\r\n }\r\n \r\n // iterate left through element until node contains TEXT_ID\r\n var previous_node, const_index;\r\n if (node.nodeValue == null) {\r\n const_index = -1;\r\n } else {\r\n const_index = node.nodeValue.indexOf(TEXT_ID);\r\n }\r\n while (const_index == -1) {\r\n //previous_node = node;\r\n node = findNextNode(\"left\", node);\r\n if (node.nodeValue == null) {\r\n const_index = -1;\r\n } else {\r\n const_index = node.nodeValue.indexOf(TEXT_ID);\r\n }\r\n }\r\n return node;\r\n }\r\n}",
"prune(callback) {\n if (_.isArray(this.contents)) {\n const length = this.contents.length;\n\n if ((this.type === \"REPEAT\" && length > 0) || (this.type === \"REPEAT1\" && length > 1)) {\n // Any subtree may be removed\n for (let i = 0; i < length; i++) {\n const tree = _.cloneDeep(this);\n tree.contents.splice(i, 1);\n if (!callback(tree)) {\n return;\n }\n }\n }\n\n for (let i = 0; i < length; i++) {\n let callbackResult = true;\n\n this.contents[i].prune(t => {\n const tree = _.cloneDeep(this);\n tree.contents[i] = t;\n callbackResult = callback(tree);\n return callbackResult;\n });\n\n if (!callbackResult) {\n return;\n }\n }\n }\n }",
"function runText(elem, f)\r\n{\r\n // text node\r\n if (elem.nodeType == 3)\r\n {\r\n return f(elem);\r\n }\r\n\r\n // iterate over children recursively\r\n elem = elem.firstChild;\r\n if (elem)\r\n {\r\n do\r\n {\r\n var ret = runText(elem, f);\r\n if (ret) {\r\n return ret;\r\n }\r\n }\r\n while (elem = elem.nextSibling);\r\n }\r\n return 0;\r\n}",
"function getTitleFromNode(node) {\n let titleLength = 13\n\n var fullText = getFullTextFromNode(node)\n\n // remove metadata (stuff after ##)\n var textWithoutMetadata\n if (fullText.includes('##')) {\n textWithoutMetadata = fullText.split('##').slice(0, -1).join(' ')\n } else {\n textWithoutMetadata = fullText\n }\n\n // get the first x words to use as the title\n if (textWithoutMetadata.split(' ').length <= titleLength) {\n return textWithoutMetadata\n } else {\n // add ... if the text is longer than 10 words\n return textWithoutMetadata.split(' ').slice(0,titleLength).join(' ') + \"...\"\n }\n}",
"visitTruncate_table(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"textNodes(...args) {\n let filter = \"\", i = 0, a = [], recursive = false;\n $sel = $();\n while(arguments[i]){\n if (typeof arguments[i] === \"string\"){\n filter += (filter) ? \"|\" : \"\";\n filter += arguments[i];\n }else if (Array.isArray(arguments[i])){\n\t\t\t\t\tfilter += (filter) ? \"|\" : \"\";\n\t\t\t\t\tfilter += arguments[i].join(\"|\");\n\t\t\t\t}\n i++;\n }\n lastArg = arguments[arguments.length-1];\n if(typeof lastArg === \"boolean\" && lastArg) {recursive = true;}\n that = (recursive) ? this.find(\"*\").addBack() : this;\n that.each(function() {\n $sel = $sel.add($(this).contents());\n });\n $sel.each(function(){\n if(filter){\n reg = new RegExp(filter);\n }\n keep = (this.nodeType === 3 && (!filter || this.textContent.search(filter)+1)) ? true : false;\n if (keep) a.push(this);\n });\n $sel = $(a);\n $sel.prevObject = this;\n $sel.selector = filter;\n return $sel;\n }",
"function clearRange(value, start, end) {\n return value.substring(0, start) + value.substring(end);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A somewhat cheesy demo that adds instructions to the task list every 1.5 seconds. Disabled by setting demoMode = false in the TodoListStore. | cheesyDemo() {
function setTimeouts(arrayOfFunctions, period) {
let counter = 0;
// queues up functions every `period` milliseconds
for (const f of arrayOfFunctions) {
setTimeout(f, counter);
counter += period;
}
}
const { addTodo } = this.props.store;
setTimeouts([
() => { addTodo('Welcome to this nested task list!'); },
() => { addTodo('You\'ll find it quite intuitive. Just type!'); },
() => { addTodo('You can add a new item by pressing enter.').indent(); },
() => {
const n = addTodo('Move up/down using the arrows. Indent with tab/shift+tab.');
n.indent();
n.indent();
},
() => { addTodo('Move an item up/down with cmd+up/cmd+down.').indent(); },
() => { addTodo('Delete an empty line with backspace, or click the trashcan.'); },
() => { addTodo('Enjoy!'); },
],
1000);
} | [
"function createNewTask(task) {\n storeTaskLocalStorage(task);\n appendToList(task);\n}",
"function runAddReminder() {\n var reminderString = getReminderInput();\n var reminderItem = createReminderItem(reminderString);\n addReminderItemToList(reminderItem);\n clearReminderInput();\n}",
"function addTask(e) {\n // fetch the current value input in task box\n lkj('In addTask() Event');\n\n let task = {\n description: submitTaskBox.value,\n status: 0\n }\n lkj(task);\n\n currentTaskList.push(task);\n displaycurrentTaskList();\n\n updateLocalStorage();\n displayLocalStorage(); \n\n // alert('Task saved');\n\n //creating task on the HTML Page\n createTask(task);\n}",
"function displaytodo(todo) {\r\n console.log(\"Display\")\r\n if (todo.state == 0) {\r\n // create an item on the pending list\r\n var list = $(\"#todo\");\r\n list.append(`<li id=\"${todo.id}\" class=\"list-group-item\">${todo.text} <button class=\"btn btn-outline-primary float-right\" onclick=\"markDone(${todo.id});\" > Done </button> </li>`);\r\n }\r\n else {\r\n // create an item on the done list\r\n var list = $(\"#donetodo\");\r\n list.append('<li class=\"list-group-item\">' + todo.text + '</li>');\r\n }\r\n}",
"listTodos() {\n this.todosParent.innerHTML = null;\n const list = lsModule.readFromLS();\n if (!list) {\n console.log(\"No tasks\");\n renderEmptyList(this.todosParent)\n const btnComplete = utilitiesModule.qs('#btnComplete');\n const btnActive = utilitiesModule.qs('#btnActive');\n const btnAll = utilitiesModule.qs('#btnAll');\n const btnSubmit = utilitiesModule.qs('#btnSubmit');\n const btnRemove = utilitiesModule.qss('#btnRemove'); // Node List\n const btnCheck = utilitiesModule.qss('#btnCheck'); // Node List\n utilitiesModule.onTouch(btnComplete, this.showTodosComplete.bind(this));\n utilitiesModule.onTouch(btnActive, this.showTodosActive.bind(this));\n utilitiesModule.onTouch(btnAll, this.listTodos.bind(this));\n btnSubmit.addEventListener('click', this.addTodo);\n this.showTodoBadge();\n btnRemove.forEach(btn => {\n btn.addEventListener('touchend', e => {\n this.removeTodo(e.currentTarget.dataset.id)\n })\n })\n btnCheck.forEach(btn => {\n btn.addEventListener('touchend', e => {\n this.checkTodo(btn, e.currentTarget.dataset.id)\n })\n })\n } else {\n renderTodoList(Array.from(list), this.todosParent);\n const btnComplete = utilitiesModule.qs('#btnComplete');\n const btnActive = utilitiesModule.qs('#btnActive');\n const btnAll = utilitiesModule.qs('#btnAll');\n const btnSubmit = utilitiesModule.qs('#btnSubmit');\n const btnRemove = utilitiesModule.qss('#btnRemove'); // Node List\n const btnCheck = utilitiesModule.qss('#btnCheck'); // Node List\n utilitiesModule.onTouch(btnComplete, this.showTodosComplete.bind(this));\n utilitiesModule.onTouch(btnActive, this.showTodosActive.bind(this));\n utilitiesModule.onTouch(btnAll, this.listTodos.bind(this));\n this.showTodoBadge();\n btnSubmit.addEventListener('touchend', this.addTodo);\n btnRemove.forEach(btn => {\n btn.addEventListener('touchend', e => {\n this.removeTodo(e.currentTarget.dataset.id)\n })\n })\n btnCheck.forEach(btn => {\n btn.addEventListener('touchend', e => {\n this.checkTodo(btn, e.currentTarget.dataset.id)\n })\n })\n }\n }",
"function Todos({DOM, History, storage}) {\n // THE LOCALSTORAGE STREAM\n // Here we create a localStorage stream that only streams\n // the first value read from localStorage in order to\n // supply the application with initial state.\n const localStorage$ = storage.local.getItem('todos-cycle').take(1);\n // THE INITIAL TODO DATA\n // The `deserialize` function takes the serialized JSON stored in localStorage\n // and turns it into a stream sending a JSON object.\n const sourceTodosData$ = deserialize(localStorage$);\n // THE PROXY ITEM ACTION STREAM\n // We use an Rx.Subject as a proxy for all the actions that stream\n // from the different todo items.\n const proxyItemAction$ = new Subject();\n // THE INTENT (MVI PATTERN)\n // Pass relevant sources to the intent function, which set up\n // streams that model the users intentions.\n const actions = intent(DOM, History, proxyItemAction$);\n // THE MODEL (MVI PATTERN)\n // Actions get passed to the model function which transforms the data\n // coming through the intent streams and prepares the data for the view.\n const state$ = model(actions, sourceTodosData$);\n // AMEND STATE WITH CHILDREN\n const amendedState$ = state$.map(amendStateWithChildren(DOM)).shareReplay(1);\n // A STREAM OF ALL ACTIONS ON ALL TODOS\n // Each todo item has an action stream. All those action streams are being\n // merged into a stream of all actions. Below this stream is passed into\n // the proxyItemActions Subject that we passed to the intent function above.\n // This is how the intent on all the todo items flows back through the intent function\n // of the list and can be handled in the model function of the list.\n const itemAction$ = amendedState$.flatMapLatest(({list}) =>\n Observable.merge(list.map(i => i.todoItem.action$))\n );\n // PASS ITEM ACTIONS TO PROXY\n // The item actions are passed to the proxy object.\n itemAction$.subscribe(proxyItemAction$);\n // WRITE TO LOCALSTORAGE\n // The latest state is written to localStorage.\n const storage$ = serialize(state$).map((state) => ({\n key: 'todos-cycle', value: state\n }));\n // COMPLETE THE CYCLE\n // Write the virtual dom stream to the DOM and write the\n // storage stream to localStorage.\n return {\n DOM: view(amendedState$),\n History: actions.url$,\n storage: storage$,\n };\n}",
"function loadTodos() {\n const ul = document.querySelector('.todoList');\n const todos = getTodosFromLocalStorage();\n\n for (const todo of todos) {\n const li = createTodoElement(todo);\n ul.append(li);\n }\n}",
"constructor(){\n\t\tthis.todoList = [];\n\t}",
"function task_create_todoist(task_name, project_id, todoist_api_token) {\n todoist_api_token = todoist_api_token || 'a14f98a6b546b044dbb84bcd8eee47fbe3788671'\n return todoist_add_tasks_ajax(todoist_api_token, {\n \"content\": task_name,\n \"project_id\": project_id\n })\n}",
"function createToDoList() {\n\n //add them to HTML file\n lineBreak2.appendChild(taskAndTime);\n taskAndTime.appendChild(toDoList);\n toDoList.appendChild(spanTask); \n toDoList.appendChild(spanTime);\n taskAndTime.appendChild(startButton);\n taskAndTime.appendChild(pauseButton);\n taskAndTime.appendChild(resetButton);\n \n //setting innerHTML's\n startButton.innerHTML = \"START\";\n pauseButton.innerHTML = \"PAUSE\";\n resetButton.innerHTML = \"RESET\";\n spanTask.innerHTML = task.value + \" - \";\n spanTime.innerHTML = time.value;\n\n}",
"function submitHandler(e) {\n\n //create a new list item within a list tag\n let newTodo = document.createElement('li');\n\n //todo inner text is what is inputted within the text field\n newTodo.innerText = textField.value;\n\n //add the new todo list item to the list of tasks\n tasks.appendChild(newTodo);\n\n //create a new button element\n let newButton = document.createElement('button')\n\n //add the text inside the button\n newButton.innerText = 'X';\n\n //add the button to the new list item\n newTodo.appendChild(newButton);\n\n //add an event listener to delete the new list item\n newButton.addEventListener('click', function() {\n newTodo.remove(); //remove the newtodo item\n });\n\n //prevent from auto-refreshing\n e.preventDefault();\n }",
"function createTodo() {\n // get the string value of input todo\n var newTodo = $('#newTodo').val();\n\n pushToTodos(newTodo);\n\n displayTodoItems(todos);\n\n storeTodos();\n\n // empty the input feild\n $('#newTodo').val('');\n }",
"generate() {\n document.querySelector(\".modal-window__task_media\").innerHTML = \"\";\n document.getElementById(\"answer\").value = \"\";\n const tasks = [\n this.arithmetics,\n this.translate,\n this.listening,\n this.capitals,\n this.sort,\n this.redundant,\n this.equation,\n this.triangle,\n this.animals\n ];\n const currentTask = _mylib__WEBPACK_IMPORTED_MODULE_0__[\"default\"]\n .getRandomArrayElement(tasks)\n .bind(this);\n currentTask();\n }",
"function newList() {\n let article = gen(\"article\");\n let titleInput = gen(\"input\");\n let taskInput = gen(\"input\");\n let ul = gen(\"ul\");\n\n article.classList.add(\"list\");\n\n titleInput.type = \"text\";\n titleInput.placeholder = \"Title\";\n titleInput.classList.add(\"title-in\");\n article.appendChild(titleInput);\n titleInput.addEventListener(\"keyup\", (event) => {\n if (event.keyCode === ENTER_KEY) {\n addTitle(titleInput);\n }\n });\n\n taskInput.type = \"text\";\n taskInput.placeholder = \"+ New task\";\n taskInput.classList.add(\"task-in\");\n article.appendChild(taskInput);\n article.appendChild(ul);\n taskInput.addEventListener(\"keyup\", (event) => {\n if (event.keyCode === ENTER_KEY) {\n addTask(taskInput);\n }\n });\n\n qs(\"section\").insertBefore(article, id(\"add\"));\n\n article.addEventListener(\"dblclick\", removeObj);\n }",
"addOne(todo) {\n\t\tlet view = new TodoView({ model: todo });\n\t\t$('#todo-list').append(view.render().el);\n\t}",
"function startTutorial() {\n\t// May or may not be necessary\n\tgameType = 'tutorial';\n\tstartGame();\n\ttutorialInstructionIndex = -1;\n\tcallbackAfterMessage = nextTutorialMessage;\n\tnextTutorialMessage();\n}",
"function TodoListConstroller () {}",
"function example2() {\nsetTimeout(() => console.log(\"hi\"), 0); // macro task\nqueueMicrotask(() => console.log(\"interesting hello\")); // micro\nqueueMicrotask(() => console.log(\"interesting hello 1\")); // micro\nconsole.log(\"hello\");\nconsole.log(\"hello1\");\nconsole.log(\"hello2\");\nconsole.log(\"hello3\");\nconsole.log(\"hello4\");\n}",
"function myTodo(todo) {\n console.log(todo.title + ' : ' + todo.text);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
purpose of function is to get item details of all ids listed in item.upgrades then replace upgrades with an array of those item upgrades | function fillUpgradeDetails(items) {
//first get a list of ids to query
let upgradeIDs = []
items.forEach((item) => {
if (item.upgrades) {
item.upgrades = item.upgrades.split()
upgradeIDs.push(item.upgrades)
}
})
if (upgradeIDs.length > 0){
upgradeIDs = upgradeIDs.flat()
return gw2DB.getItemDetailsAsObject(upgradeIDs)
.then((upgradeDetails) => {
items.forEach((item) => {
if (item.upgrades) {
let newUpgrades = []
item.upgrades.forEach((upgradeID) => {
newUpgrades.push(upgradeDetails[upgradeID])
})
item.upgrades = newUpgrades
}
})
})
.then(() => {
return items
})
}
else return items
} | [
"updateExistingItems(){\n this.items.forEach((item, index) => {\n Array.from(document.getElementsByClassName(`budgie-${this.budgieId}-${index}`)).forEach((element) => {\n // If the element has changed then update, otherwise do nothing\n\n let newElement = BudgieDom.createBudgieElement(this, item, index);\n // update the element if it does not currently match\n if (element.innerHTML !== newElement.innerHTML) {\n element.innerHTML = newElement.innerHTML;\n }\n });\n });\n }",
"function refillInventory(inventory){\n\tfor(let key in inventory){\n\t\tif(itemInventory[key]==undefined){\n\t\t\titemInventory[key] = inventory[key]\n\t\t}\n\t\telse{\n\t\t\titemInventory[key] = itemInventory[key] + inventory[key];\n\t\t}\n\t}\n}",
"loadAvailableItems() {\n // Load the available items and parses the data\n var tempList = lf.getAvailableItems();\n tempList.then((value) => {\n // Get the items, their ids, and data\n var items = value.items;\n var ids = value.ids;\n var genNames = value.genNames;\n\n // Save the item information\n var temp = [];\n for (var i = 0; i < ids.length; i++) {\n temp.push({\n name: items[i],\n title: items[i],\n id: ids[i],\n genName: genNames[i]\n });\n }\n\n // Add the option to register a new item to the list\n temp.push({ name: NEW_ITEM, title: NEW_ITEM, id: -1 });\n\n availableItems = temp;\n });\n }",
"function updateInventory(){\n console.log(\"updating inventory...\");\n debugLog += \"updating inventory... \"+ '\\n';\n for(var i = 0; i < soldItems.length; i++){\n var indexOfMatchingBarcodes = [];\n var matchFound = false;\n var sellingItem = soldItems[i];\n var sellingBarcode = sellingItem[3];\n var sellingQTY = sellingItem[4];\n console.log(\"removing item \" + sellingBarcode + \" in the amount of \"+ sellingQTY);\n debugLog += \"removing item \" + sellingBarcode + \" in the amount of \"+ sellingQTY + '\\n';\n \n var invItem;\n for(var j = 0; j < inventory.length; j++){\n invItem = inventory[j]\n if(invItem[invUPCCol] === sellingBarcode){ //barcode match\n matchFound = true;\n indexOfMatchingBarcodes.push(j);\n }\n }\n //check if there was more than one match, if so, also match on size & color fields\n if(matchFound){\n var barcodeMatchItem;\n if(indexOfMatchingBarcodes.length == 1){\n barcodeMatchItem = inventory[indexOfMatchingBarcodes[0]];\n console.log(\"Found match! Item \" + barcodeMatchItem + \" has barcode \" + sellingBarcode);\n debugLog += \"Found match! Item \" + barcodeMatchItem + \" has barcode \" + sellingBarcode + '\\n';\n barcodeMatchItem[invQtyCol]-=sellingQTY; //reduce inventory by QTY of sold item \n console.log(\"Item now has quantity: \" + barcodeMatchItem[invQtyCol]);\n debugLog += \"Item now has quantity: \" + barcodeMatchItem[invQtyCol] + '\\n';\n }\n else{\n //check that the barcodeMatchItem matches other fields of sellingItem (we already know barcode is a match)\n for(var k = 0; k < indexOfMatchingBarcodes.length; k++){\n console.log(\"Found \" + indexOfMatchingBarcodes.length + \" matching barcodes, narrowing search\");\n debugLog += \"Found \" + indexOfMatchingBarcodes.length + \" matching barcodes, narrowing search\" + '\\n';\n barcodeMatchItem = inventory[indexOfMatchingBarcodes[k]];\n if(barcodeMatchItem[invSzCol] === sellingItem[2] && barcodeMatchItem[invColorCol] === sellingItem[1]){\n console.log(\"Found match! Item \" + barcodeMatchItem + \" has barcode \" + sellingBarcode + \"and matches other fields\");\n debugLog += \"Found match! Item \" + barcodeMatchItem + \" has barcode \" + sellingBarcode + \"and matches other fields\" + '\\n';\n barcodeMatchItem[invQtyCol]-=sellingQTY; //reduce inventory by QTY of sold item \n console.log(\"Item now has quantity: \" + barcodeMatchItem[invQtyCol]);\n debugLog += \"Item now has quantity: \" + barcodeMatchItem[invQtyCol] + '\\n';\n }\n }\n }\n }\n else{\n console.log(\"Couldn't find match for \" + soldItems[i][3]);\n debugLog += \"Couldn't find match for \" + soldItems[i][3] + '\\n';\n }\n matchFound = false;\n indexOfMatchingBarcodes = [];\n }\n console.log(inventory);\n console.log(\"inventory successfully updated\");\n debugLog += \"inventory successfully updated\" + '\\n';\n writeInventory();\n }",
"updateItem(items, key, target, updateItemCB) {\n var newItems = [];\n for (var i = 0; i < items.length; i++) {\n if ( items[i][key] === target[key] ) {\n var newItem = updateItemCB(_.clone(items[i]));\n if ( newItem !== undefined ) {\n newItems.push(newItem);\n }\n } else {\n newItems.push(items[i]);\n }\n }\n return newItems;\n }",
"static updateInventory() {\n\t\tthis.resetInventory();\n\t\tstoryData.story.items.forEach(function(item) {\n\t\t\tif (item.owned) UI.addItem(item);\n\t\t});\n\t}",
"setItems(items){\n const currentFiller = this.numberLeftWithOddEnding()\n /**\n * Will return the indexes (from the old array) of items that were removed\n * @param oldArray\n * @param newArray\n */\n const removedIndexes = (oldArray, newArray) => {\n let rawArray = oldArray.map((oldItem, index) => {\n if(!newArray.some(newItem => newItem === oldItem)){\n return index;\n }\n })\n\n return rawArray.filter( index => (index || index === 0) );\n }\n\n\n /**\n * Will return the indexes (from the new array) of items that were added\n * @param oldArray\n * @param newArray\n */\n const addedIndexes = (oldArray, newArray) => {\n let rawArray = newArray.map((newItem, index) => {\n if(!oldArray.some(oldItem => oldItem === newItem)){\n return index;\n }\n })\n\n return rawArray.filter( index => (index || index === 0) );\n }\n\n\n this.previousItems = this.items.slice();\n this.items = items.slice();\n\n let indexesToRemove = removedIndexes(this.previousItems, this.items);\n let indexesToAdd = addedIndexes(this.previousItems, this.items);\n\n // console.log('add:', indexesToAdd, 'remove:', indexesToRemove)\n\n if(indexesToRemove.length > 0) {\n indexesToRemove.forEach(index => {\n this.removeLastItem(index);\n })\n }\n\n if(indexesToAdd.length > 0) {\n indexesToAdd.forEach(index => {\n this.addItemAtIndex(index);\n })\n }\n\n // When adding we have to update the index every time\n const realElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}:not(.budgie-item-${this.budgieId}--duplicate)`));\n realElements.forEach((element, index) => {\n let className = Array.from(element.classList).filter(_className => _className.match(new RegExp(`budgie-${this.budgieId}-\\\\d`)));\n if(className !== `budgie-${this.budgieId}-${index}`) {\n element.classList.remove(className);\n element.classList.add(`budgie-${this.budgieId}-${index}`);\n }\n })\n\n // remove duplicate elements\n const dupedElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}.budgie-item-${this.budgieId}--duplicate`));\n dupedElements.forEach(element => {\n element.parentNode.removeChild(element);\n })\n\n // remove filler elements\n const fillerElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}--filler`));\n fillerElements.forEach(element => {\n element.parentNode.removeChild(element);\n })\n\n // Insert duplicated elements anew, if this is an infinite scroll\n if(this.options.infiniteScroll) {\n this.prependStartingItems();\n this.appendEndingItems();\n }\n\n // Add filler items to the end if needed\n if(this.numberLeftWithOddEnding() > 0) {\n realElements[realElements.length - this.numberLeftWithOddEnding()]\n .insertAdjacentElement('beforebegin', BudgieDom.createBudgieFillerElement(this))\n\n realElements[realElements.length - 1]\n .insertAdjacentElement('afterend', BudgieDom.createBudgieFillerElement(this))\n }\n\n this.clearMeasurements();\n this.budgieAnimate();\n }",
"function castTagArrayForDB(item, tagArrayName, tagDBName, indexer) {\n let result = []\n let array = item[tagArrayName]\n if (array && array.length > 0){\n array.forEach((value) => {\n let next = {item_id: item.id}\n next[tagDBName] = indexer[value]\n result.push(next)\n })\n }\n return result\n}",
"updatedShelf(shelf, author) {\n return shelf.map( (elem) => {\n return this.bookFromAuthorData(elem, author)\n })\n }",
"_fetchFromAPI() {\n // Generate new items\n let { indexedDb } = this;\n\n return indexedDb.add('item', [\n this._createItemPayload(),\n this._createItemPayload(),\n this._createItemPayload(),\n ]);\n }",
"function mergeItem(tmpList, body) {\n item.resetOutput();\n let output = item.getOutput();\n for (let key in tmpList.data[0].Inventory.items) {\n if (tmpList.data[0].Inventory.items.hasOwnProperty(key)) {\n if (tmpList.data[0].Inventory.items[key]._id && tmpList.data[0].Inventory.items[key]._id === body.with) {\n for (let key2 in tmpList.data[0].Inventory.items) {\n if (tmpList.data[0].Inventory.items[key2]._id && tmpList.data[0].Inventory.items[key2]._id === body.item) {\n let stackItem0 = 1;\n let stackItem1 = 1;\n if (typeof tmpList.data[0].Inventory.items[key].upd !== \"undefined\")\n stackItem0 = tmpList.data[0].Inventory.items[key].upd.StackObjectsCount;\n if (typeof tmpList.data[0].Inventory.items[key2].upd !== \"undefined\")\n stackItem1 = tmpList.data[0].Inventory.items[key2].upd.StackObjectsCount;\n\n if (stackItem0 === 1)\n Object.assign(tmpList.data[0].Inventory.items[key], {\"upd\": {\"StackObjectsCount\": 1}});\n\n tmpList.data[0].Inventory.items[key].upd.StackObjectsCount = stackItem0 + stackItem1;\n\n output.data.items.del.push({\"_id\": tmpList.data[0].Inventory.items[key2]._id});\n tmpList.data[0].Inventory.items.splice(key2, 1);\n\n profile.setCharacterData(tmpList);\n return output;\n }\n }\n }\n }\n }\n\n return \"\";\n}",
"function upgrade_new_products($) {\n const imax = 1199;\n const v = $('body').find('section#new-products').find('article')\n console.log(`found ${v.length} articles`)\n v.each((i,e)=>{\n const id = $(e).attr('id');\n const sku = $(e).data('sku');\n// console.log(`id:${id} sku[${i}]:${sku}`)\n// console.log(`id:${id} sku[${i}]:${e.data}`)\n// console.log({e})\n\n if (true || !id) {\n// $(e).attr('id',`${imax-i}~${sku}`);\n $(e).attr('id',imax-i);\n $(e).addClass('js-e3dkz')\n $(e).removeClass('e3dkz')\n }\n // add \"js-e3dkz\"\n\n\n\n console.log(`id:${$(e).attr('id')} sku[${i}]:${sku}`)\n\n })\n\n\n\n set_meta($,'e3:revision', '1.0')\n console.log(`e3:revision: ${get_meta($,'e3:revision')}`);\n}",
"function mergeItems(){\n\tfor(var i = 0; i < invArray.length; i++){\n\t\tif(invArray[i].select){\n\t\t\tvar item1 = invArray[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor(var i = item1.invPos + 1; i < invArray.length; i++){\n\t\tif(invArray[i].select){\n\t\t\tvar item2 = invArray[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tcombine(item1, item2);\n}",
"getUpgradeMap(model) {\n\n let upgradeMap = {};\n\n for (let newTableName in model.tables) {//this gets the STRING name of the property into 'table'\n let newTableObject = model.tables[newTableName];//this on the other hand, gets the whole table object\n\n for (let newColumnName in newTableObject.columns)\n {\n let currentColumnObj = newTableObject.columns[newColumnName];\n let prevColArray = currentColumnObj.previous_columns;\n\n if((prevColArray == undefined) || prevColArray.length==0) {\n continue;\n }\n\n if (prevColArray &&\n prevColArray.length === 1) {\n let previousColTableName = prevColArray[0].table;\n let previousColumnName = prevColArray[0].column;\n if(!upgradeMap[previousColTableName]) upgradeMap[previousColTableName] = {};\n if(!upgradeMap[previousColTableName][previousColumnName]) upgradeMap[previousColTableName][previousColumnName] = [];\n\n //TEST FOR TABLE/COLUMNS WITH NO CHANGES\n if(newColumnName == previousColumnName && newTableName == previousColTableName){\n upgradeMap[previousColTableName][previousColumnName].push({table:newTableName,column:newColumnName});\n //console.log(`NO CHANGE in table and column with no change detected. table:${newTableName}. Column name = ${newColumnName}` );\n continue;\n }\n\n //TEST FOR RENAMED TABLES OR COLUMNS\n if ((newTableName != previousColTableName) || (newColumnName != previousColumnName)) {\n //console.log(`RENAMED table or column detected. Previous table name : ${previousColTableName} New table: ${newTableName}.` );\n //console.log(`Previous column name = ${previousColumnName}. New column name = ${newColumnName}` );\n upgradeMap[previousColTableName][previousColumnName].push({table:newTableName,column:newColumnName});\n continue;\n }\n }\n\n //TEST FOR MERGED COLUMNS...If there is more than one previous column, that indicates a MERGE to this version\n if (prevColArray && (prevColArray.length > 1))\n {\n for(let prevColIdx in prevColArray)\n {\n let tmpPreviousColumnName = prevColArray[prevColIdx].column;\n let tmpPreviousColTableName = prevColArray[prevColIdx].table;\n\n /*if(!upgradeMap[tmpPreviousColTableName] || upgradeMap[tmpPreviousColTableName]==undefined)\n upgradeMap[tmpPreviousColTableName] = {};\n if(!upgradeMap[tmpPreviousColTableName][tmpPreviousColumnName] || upgradeMap[tmpPreviousColTableName][tmpPreviousColumnName]==undefined)\n upgradeMap[tmpPreviousColTableName][tmpPreviousColumnName] = [];\n\n upgradeMap[tmpPreviousColTableName][tmpPreviousColumnName].push([{table:newTableName, column:newColumnName}]);*/\n if(!upgradeMap[tmpPreviousColTableName])\n upgradeMap[tmpPreviousColTableName] = {};\n if(!upgradeMap[tmpPreviousColTableName][tmpPreviousColumnName])\n upgradeMap[tmpPreviousColTableName][tmpPreviousColumnName] = [];\n\n upgradeMap[tmpPreviousColTableName][tmpPreviousColumnName].push({table:newTableName, column:newColumnName});\n }\n }\n }\n }\n\n//console.log(`Upgrade Map ${JSON.stringify(upgradeMap)}`);\n return upgradeMap;\n\n }",
"function allItemsBought(buyerID) {\n return itemsBought.child(buyerID).once('value')\n .then(data => data.val())\n .then(items => Object.keys(items))\n .catch(err => [])\n}",
"updateShoppingCar(state, update) {\n for (var i = 0; i < state.shoppingCar.length; i++) {\n if (state.shoppingCar[i].item.id_item == update.id) {\n state.shoppingCar[i] = update.item;\n }\n if (state.shoppingCar[i].quantity == 0) {\n state.shoppingCar.splice(i, 1)\n }\n }\n }",
"function updateIngredients(base) {\n ingredients.forEach(ingredient => ingredient.updateAmount(base));\n}",
"function inventory(req, res, next) {\n\tconst id = req.params.userId;\n\n\tUser.findOne({userId: id}, function(err, user) {\n\t\tif (err) res.send(err)\n\t\tconst inventory = user.inventory.map(function(item){\n\t\t\treturn item.itemId;\n\t\t});\n\t\t//res.json(inventory);\n\t\tItem.find({ itemId: {$in: inventory} }, function(err, items) {\n\t\t\tif(err) res.send(err);\n\t\t\tres.json(items);\n\t\t})\n\t});\n}",
"function parseEquipment(rawEquips){\n // Parse all of the Equipment out of the json\n let equips = [];\n for(var i = 0; i < rawEquips.length; i++){\n // Get the Equipment\n let rawEq = rawEquips[i];\n\n // Get the attributes\n var amount = rawEq[EXP_JSON_EQUIP_AMOUNT];\n var id = rawEq[EXP_JSON_EQUIP_OBJ_ID];\n\n // Create the appropriate Equipment\n for(var j = 0; j < amount; j++){\n equips.push(idToEquipment(id));\n }\n }\n return equips;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
drawGrid (main Grid Drawing Method) Draw a Grid (main function for drawing a Grid) ASSUMPTIONS: Side effects: gridObj.htmlId is set to htmlId. This is done to register htmlId with gridObj within the current step as a temporary measure. | function drawGrid(gridObj, indObj, htmlId, edit) {
// Create some shortcut names for commonly used members in gridObj
//
var pO = CurProgObj;
var gO = gridObj; // shortcut reference to gridObj
var iO = indObj;
var caption = gO.caption;
//var hasRowTitles = gO.dimHasTitles[RowDimId];
//var hasColTitles = gO.dimHasTitles[ColDimId];
//var hasRowIndices = gO.dimHasIndices[RowDimId];
//var hasColIndices = gO.dimHasIndices[ColDimId];
var isHeaderStep = CurStepObj.isHeader;
// We use the show data state of the current Step object by default.
// If it is necessary to override this, we can pass in an arg
// to this function
//
var showData = pO.showData;
// Draw assignment arrows when we are drawing non-editable output grid.
// Also, we don't draw arrows for templates
//
var drawArrows = (OutHtmlId == htmlId) && !edit && !gO.isTemplate;
clearTip();
// Register this htmlId with the grid Object. This assumes that the same
// gridObj is not drawn on the screen twice -- i.e., we always clone
//
gO.htmlId = htmlId;
//gO.showData = showData; // record show data status
var str = ""; // html code holder
// STEP A.1: ----------- Draw outermost container -----------------------
//
// This is the outermost container table for all cases. It is also
// used to draw the 'assignment arrow'. This has the 'htmllId' assigned.
//
var id = "id='" + htmlId + "'"; // html id for outermost table
str += "<table class='outArrow' " + id + " >";
if (gO.typesInDim < 0) { // global type in row1
// We allow changing the data type while editing a grid OR
// for all grids w/ a global type (including return value) in a header
//
var type_sel = edit || CurStepObj.isHeader;
var tstr = (type_sel)?
getTypeSelectStr(0, gO.dataTypes[0], htmlId ) :
"(" + TypesArr[gO.dataTypes[0]] + ")";
str += "<tr><td class='type'>" + tstr + "</td></tr>";
}
//
//
str += "<tr><td>"; // row2 for contents/arrows
// STEP A.2: ----------- Draw Multi-Dimensional Panes --------------------
//
for (var d = gO.numDims - 1; d >= 2; d--) { // draw outer dimensions first
// start an entire tabbed 2D pane
//
str += "<table class='tabPane' " + id + " >"; // 2D-pane
var color = TabColors[(d-2) % TabColors.length]; // tab color & style
var has_titles = gO.dimHasTitles[d];
//
var sel =" class=select "; // selected style
var sty = " style='background-color:#" + color + "' ";
sel += sty;
//
// non-selected style
//
var nosel = " class=noselect style='background-color:#fefefe' ";
// If the dimension has indices, draw it above titles (and types)
//
if (gO.dimHasIndices[d] && (iO || showData)) {
str += "<tr>";
// Select the background color of indices
//
var sty2 = "";
if (gO.selIndDim == d) {
// if this index range highligted
//
sty2 = " style='background-color:#dcffed' ";
} else if (d < gO.numDims - 1) {
// if not the outermost dim, use the background color of the
// outer dim (d+1) -- not TabColors[0] is for dim 2
//
var color = TabColors[d - 2 + 1];
sty2 = " style='background-color:#" + color + "' ";
}
// Find which tabs to show if we are showing data
//
var tab_start = (showData) ? gO.dimShowStart[d] : 0;
var tab_end = getDimEnd(gO, d, tab_start, showData);
//
for (var t = tab_start; t < tab_end; t++) {
var onc_args = "this, '" + htmlId + "'," + d + "," + t;
onc = " onmousedown=\"gridIndMouseDown(" + onc_args +
")\" ";
onc += " onmouseup=\"gridIndMouseUp(" + onc_args + ")\" ";
var istr = (showData) ? t : getIndExprStr(iO.dimIndExprs[
d][t]);
//
// Draw left/right arrows for scrolling a larger matrix
//
if (showData && (t == tab_start) && (tab_start > 0)) {
var newstart =
gO.dimShowStart[d] - gO.dimShowSize[d];
if (newstart < 0) newstart = 0;
//
var args = "'" + htmlId + "'," + d + "," + newstart;
var click = " onclick=\"scrollData(" + args + ")\" ";
//
istr = "<img src='images/larrow1.png' " + click +
" width=16px height=16px>" + istr;
} else if (showData &&
(t == (tab_end - 1)) && (tab_end < gO.dimActSize[d])) {
var args = "'" + htmlId + "'," + d + "," + tab_end;
var click = " onclick=\"scrollData(" + args + ")\" ";
//
istr += "<img src='images/rarrow1.png' " + click +
"width=16px height=16px>";
}
str += "<th class='index' " + sty2 + onc + ">" + istr +
"</th>";
}
str += "</tr>";
}
// draw tab TYPES, if the types are in this dimension
//
if (gO.typesInDim == d) {
str += "<tr>";
for (var t = 0; t < gO.dimShowSize[d]; t++) {
var tstr = (edit) ?
getTypeSelectStr(t, gO.dataTypes[t], htmlId) : "";
str += "<td class='type'>" + tstr + "</td>";
}
str += "</tr>";
}
// draw tab heads. If the current tab is selected, it is drawn
// differently than the other (un-selected) tabs.
//
str += "<tr>";
for (var t = 0; t < gO.dimShowSize[d]; t++) {
var prop = (t == gO.dimSelectTabs[d]) ? sel : nosel;
// create the call for event handler. If we are editing, we
// can change the tab and edit the title. Otherwise, just change
// the tab.
//
if (edit && has_titles) { // editable titles
//
var args = "this, '" + htmlId + "'," + d + "," + t + "," +
edit;
prop += " contenteditable oninput=\"changeTabTitle(" +
args + ",0)\"" + " onclick=\"changeTabTitle(" + args +
",1)\" "; + " onblur=\"changeTabTitle(" + args +
",2)\" ";
} else { // NO-tiltles OR non-editable titles - allow tab change
var args = "this, '" + htmlId + "'," + d + "," + t + "," +
edit;
prop += " onclick=\"selectTab(" + args + ")\" ";
}
//
// if the tab has titles, use it. Otherwise, put an empty
// cell - note we cannot put a div in 'cont' because it is picked up
// by cell formula.
//
var cont = (has_titles) ? gO.dimTitles[d][t] : "";
str += "<td " + prop + ">" + cont + "</td>";
}
str += "</tr>";
// start the contents cell. We draw another 2D pane, or a 2D grid
// in a 'content' cell
//
str += "<tr><td class='contents' " + sty + " colspan="
+ gO.dimShowSize[d] + ">";
}
//
// END STEP A: ----- End of Multi-Dimensional Panes -------------------
// STEP ................................................................
//
// Draw the inner 2D grid of type 'gridTable' for each higher dimensional
// tab. If we are showing data image, just get a canvas for drawing it --
// the canvas will be filled at the end of this function.
//
if (showData == ShowDataState.DataImage)
str += getCanvasFor2DGrid(gridObj, htmlId);
else
str += drawInner2DGrid(gridObj, indObj, htmlId, edit, showData);
// STEP Z: --------------- Close Multi-Dimensional Pane(s) --------------
//
for (var d = 2; d < gO.numDims; d++) {
str += "</td></tr></table>";
}
// STEP : ...............................................................
//
// Close the outermost container table (of type 'outArrow') after
// putting in the assign arrow image AND caption of table
//
var img = ""; // draw Assign Arrow
if (drawArrows) {
img = "<img src='images/bigarrow.jpg' width=60px height=60px>";
}
//
//
str += "</td><td>" + img + "</td></tr>"; // close row2 of outermost table
// STEP: Row for config button / context menu
//
var configbut = (edit || showData) ? "" :
getGridConfContextMenu(htmlId, gO.isConst);
//
str += "<tr><td class='gridconfbut'>" + configbut + "</td></tr>";
// Draw the caption cell at the bottom row of Multi-Dimension Pane
// First, create a contenteditable caption (in div) an add oninput function
//
var attrib = "";
if (gO.inArgNum >= 0 && (gO.deleted == DeletedState.None)) {
attrib += "<span class='captionParam'> (Parameter " + gO.inArgNum +
") </span>";
}
//
var oninp = "";
var indargs = ""; // index paramenters for grid cell reference
//
var isCapEdit = (edit || isHeaderStep) && !gO.beingReConfig;
//
if (isCapEdit) { // if caption is editable
var args = "this, '" + htmlId + "'";
//var args = "this";
//oninp = " oninput=\"changeCaption(" + args + ")\" contenteditable ";
oninp = " onblur=\"changeCaption(" + args + ")\" contenteditable ";
} else { // if caption is NOT editable
// When the user clicks on a grid name, insert a grid reference
// (mainly as a function arg)
//
var args = "'" + htmlId + "'";
oninp = " onclick=\"putGridRef(" + args + ")\" ";
oninp += " style='cursor:pointer' ";
//if (gO.isGridCellRef) { // TODO:
// indargs = getGridCellIndArgs(gO);
//}
}
// Draw grid specific buttons at the bottom right corner of the grid
//
var configbut = ""; //"<img src='images/gear.jpg' width=15px height=15px " +
" title='re-configure grid'" + ">";
if (edit || showData) configbut = "";
var buttons = "<div class='gridButDiv'>" + configbut + "</div>";
/*
//
// Navaigation buttons for scrolling through data grids
// TODO: complete these.
//
var leftarr = "", rightarr = "";
if (showData) {
leftarr = "<span style='float:left'><img src='images/larrow.jpg'" +
" width=16px height=16px></span>";
rightarr = "<span style='float:right'><img src='images/rarrow.jpg'" +
" width=16px height=16px> </span>";
}
*/
str += "<tr><td class='caption'>" +
"<span " + oninp + ">" + caption + "</span>" + indargs + "" +
buttons + "</td></tr>" + "<tr><td>" + attrib + "</td></tr>";
//
str += "</table>"; // close outermost table
// STEP : update html object .............................................
// Get the HTML object in the gridObj and update its innerHTML
//
var grid1 = document.getElementById(htmlId);
grid1.innerHTML = str; // update HTML of grid
grid1.className = 'outArrow'; // change class of htmlId
var grid2d = document.getElementById(htmlId + "2dgrid");
grid2d.className = 'gridTable'; // change class of 2d grid table
// STEP
// If we are showing the data image, draw the data on a canvas
//
if (showData == ShowDataState.DataImage) {
draw2DGridOnCanvas(gridObj, htmlId);
}
} | [
"function drawInner2DGrid(gO, iO, htmlId, edit, showData) {\r\n\r\n\r\n // Create some shortcut names for commonly used members in gridObj\r\n // \r\n var pO = CurProgObj;\r\n\r\n var hasRowTitles = gO.dimHasTitles[RowDimId];\r\n var hasColTitles = gO.dimHasTitles[ColDimId];\r\n var hasRowIndices = gO.dimHasIndices[RowDimId];\r\n var hasColIndices = gO.dimHasIndices[ColDimId];\r\n var isHeaderStep = CurStepObj.isHeader;\r\n var isGlobal = gO.isGlobal; //MPI:\r\n var isDistributed = gO.isDistributed; //MPI:\r\n var dimIsExtended = gO.dimIsExtended; //MPI:\r\n //\r\n var colorize = (showData == ShowDataState.DataAndColor);\r\n //\r\n //\r\n var perColTy = (gO.typesInDim == ColDimId);\r\n var perRowTy = (gO.typesInDim == RowDimId);\r\n\r\n\r\n var str = \"\";\r\n\r\n // STEP : ...............................................................\r\n // table for the 2D grid (gridTable)\r\n //\r\n str += \"<table class='gridTable' id='\" + htmlId + \"2dgrid'>\";\r\n //\r\n // STEP 1: ...............................................................\r\n // Draw indices (or types) over columns.\r\n // Note: ColIndices/RowIndices contain indicies and/or types\r\n // based on the type of the Grid\r\n //\r\n // start a new row and leave columns for row labeles + indices/types\r\n //\r\n\r\n\r\n // STEP 1A: Draw indices .................................................\r\n //\r\n // Top Left Corner Cell always present -- in the same row as\r\n // column indices/titles AND same column as row indices/titles \r\n //\r\n //var configbut = \"<img src='images/gear.jpg' width=20px height=20px \" +\r\n //\t\" title='re-configure grid'\" + \">\";\r\n\r\n\r\n var commentId = getCommentHtmlId(CommentType.Grid, htmlId);\r\n var commentSpan =\r\n getCommentStr('span', commentId, \" style='margin:4px' \", gO.comment);\r\n var topleft = commentSpan;\r\n\r\n // STEP 2a: Draw column indices if required\r\n //\r\n var indstr = \"\";\r\n\r\n if (hasColIndices && (iO || showData)) { // draw column indices \r\n\r\n var col_start = (showData) ? gO.dimShowStart[ColDimId] : 0;\r\n var col_end = getDimEnd(gO, ColDimId, col_start, showData);\r\n\r\n // if showing data, draw left arrow to scroll. The left arrow is\r\n // drawn if and only if there are columns to the left to be shown\r\n // NOTE: The left arrow (when present) replaces table comment\r\n //\r\n if (showData && (col_start > 0)) {\r\n\r\n var newstart = gO.dimShowStart[ColDimId] - gO.dimShowSize[\r\n ColDimId];\r\n if (newstart < 0) newstart = 0;\r\n //\r\n var onc_args = \"'\" + htmlId + \"',\" + ColDimId + \",\" +\r\n newstart;\r\n var onc = \" onclick=\\\"scrollData(\" + onc_args + \")\\\" \";\r\n //\r\n topleft = \"<img src='images/larrow1.png' \" + onc +\r\n \" width=16px height=16px>\";\r\n }\r\n\r\n // skip cell for row types/titles\r\n //\r\n if (perRowTy) // if types present\r\n indstr += \"<td class='topLeft'></td>\";\r\n if (hasRowTitles && hasRowIndices) // if both titles/indices\r\n indstr += \"<td class='topLeft'></td>\";\r\n\r\n for (var c = col_start;\r\n (c < col_end) && gO.multiCol; c++) {\r\n\r\n // Draw column index cells\r\n //\r\n var onc = \"\";\r\n if (!edit) {\r\n var onc_args = \"this, '\" + htmlId + \"',\" + ColDimId + \",\" +\r\n c;\r\n onc = \" onmousedown=\\\"gridIndMouseDown(\" + onc_args +\r\n \")\\\" \";\r\n onc += \" onmouseup=\\\"gridIndMouseUp(\" + onc_args + \")\\\" \";\r\n }\r\n\r\n // whether to highlight col indices\r\n //\r\n var ishigh = (gO.selIndDim == ColDimId);\r\n var indclass = (ishigh) ? \"colindexhigh\" : \"colindex\";\r\n\r\n // if showing data, just use column number \r\n //\r\n var indname = (showData) ? c :\r\n getIndExprStr(iO.dimIndExprs[ColDimId][c]);\r\n indstr += \"<td class='\" + indclass + \"' \" + onc + \">\" +\r\n indname + \"</td>\";\r\n\t //MPI: 'indname' shows 0, col, end1 (for columns in 2D)\r\n\t // if NOT showing data (in which case it takes them\r\n\t // from iO.dimIndExprs[][]. Otherwise shows col number\r\n\t // Num columns it gets from col_start/col_end that take\r\n\t // it from dimShowStart[] if showing data or 0, and\r\n\t // getDimEnd() for end respectively.\r\n\r\n }\r\n\r\n // Draw a right arrow to scroll to right. Draw the arrow if and only if\r\n // there is more data to show\r\n // \r\n if (showData && (col_end < gO.dimActSize[ColDimId])) {\r\n\r\n var onc_args = \"'\" + htmlId + \"',\" + ColDimId + \",\" + col_end;\r\n var onc = \" onclick=\\\"scrollData(\" + onc_args + \")\\\" \";\r\n //\r\n indstr += \"<td><img src='images/rarrow1.png' width=16px \" +\r\n \" height=16px \" + onc + \" ></td>\";\r\n }\r\n }\r\n //\r\n str += \"<tr> <td class='topLeft' >\" + topleft + \"</td>\" + indstr +\r\n \"</tr>\";\r\n\r\n\r\n // STEP 2b: ...............................................................\r\n // Draw column titles (and types), if available\r\n //\r\n if (hasColTitles) { // draw column titles .................\r\n\r\n // Since we have column titles, the number of columns we show \r\n // are fixed\r\n //\r\n var showCols = gO.dimShowSize[ColDimId];\r\n\r\n // Draw per-column data types, if needed .....................\r\n //\r\n // Note: Col Types can be present only when there are col titles\r\n // Draw column types if necessary\r\n //\r\n if (perColTy) { // if data type in every col\r\n\r\n // skip cells for row indices/types/titles\r\n //\r\n if (hasRowIndices)\r\n str += \"<tr> <td class='topLeft'></td>\";\r\n if (hasRowTitles)\r\n str += \"<td class='topLeft'></td>\";\r\n\r\n // put type over each column\r\n //\r\n for (var c = 0; c < showCols; c++) {\r\n var sel = \"(\" + TypesArr[gO.dataTypes[c]] + \")\";\r\n if (edit) sel = getTypeSelectStr(c, gO.dataTypes[c],\r\n htmlId);\r\n str += \"<td class='colindex'>\" + sel + \"</td>\";\r\n }\r\n\r\n str += \"</tr>\"; // close index/type row\r\n }\r\n\r\n\r\n // Now draw actual COLUMN TITLES\r\n //\r\n str += \"<tr>\"; // start col-titles row\r\n //\r\n if (hasRowIndices) str += \"<td class='topLeft'></td>\";\r\n if (perRowTy) str += \"<td class='topLeft'></td>\";\r\n if (hasRowTitles) str += \"<td class='topLeft'></td>\";\r\n\r\n for (var c = 0; c < showCols; c++) {\r\n\r\n var onc_args = \"this, '\" + htmlId + \"',\" + ColDimId + \",\" + c;\r\n var fun = (!edit) ? \" onclick=\\\"titleClicked(\" + onc_args +\r\n \")\\\"\" :\r\n \" oninput='changeColTitle(this,\" + c +\r\n \")' contenteditable\";\r\n //\r\n var tip = (edit) ? \" title='click to edit' \" : \"\";\r\n var sty = \" style='padding:4px' \";\r\n var divstr = \"<div \" + fun + tip + sty + \">\" +\r\n gO.dimTitles[ColDimId][c];\r\n\r\n var commentId = getCommentHtmlId(CommentType.DimTitle +\r\n ColDimId, c);\r\n var cur_comment = gO.dimComments[ColDimId][c];\r\n var commentDiv = getCommentStr('div', commentId, \"\",\r\n cur_comment);\r\n\r\n str += \"<td class='coltitle'>\" + divstr + \"</div>\" +\r\n commentDiv + \"</td>\";\r\n }\r\n str += \"</tr>\"; // close column title row\r\n\r\n } // if there are column titles\r\n\r\n\r\n\r\n // STEP 3: ...............................................................\r\n // Draw each row (types/indices/titles/content-cells)\r\n //\r\n var row_start = (showData) ? gO.dimShowStart[RowDimId] : 0;\r\n var row_end = getDimEnd(gO, RowDimId, row_start, showData);\r\n\r\n for (var r = row_start;\r\n (r < row_end); r++) {\r\n\r\n str += \"<tr>\"; // start content row\r\n\r\n\r\n if (hasRowIndices && (iO || showData)) { // draw index in cell\r\n var onc = \"\";\r\n if (!edit) {\r\n var onc_args = \"this, '\" + htmlId + \"',\" + RowDimId + \",\" +\r\n r;\r\n onc = \" onmousedown=\\\"gridIndMouseDown(\" + onc_args +\r\n \")\\\" \";\r\n onc += \" onmouseup=\\\"gridIndMouseUp(\" + onc_args + \")\\\" \";\r\n }\r\n\r\n\r\n\r\n // whether to highlight row indices\r\n //\r\n var ishigh = (gO.selIndDim == RowDimId);\r\n //\r\n var indclass = (ishigh) ? \"rowindexhigh\" : \"rowindex\";\r\n\r\n // index string. If showing data, it is just the row number\r\n //\r\n var istr = \"\";\r\n //\r\n if (showData) {\r\n\r\n // Draw the up and down arrows, when we are showing data -- for\r\n // scrolling large matrices\r\n // Note: The arrows are shown if and only if there are more\r\n // rows to be seen in the given direction\r\n //\r\n if ((r == row_start) && (row_start > 0)) {\r\n\r\n var newstart =\r\n gO.dimShowStart[RowDimId] - gO.dimShowSize[\r\n RowDimId];\r\n if (newstart < 0) newstart = 0;\r\n //\r\n var args = \"'\" + htmlId + \"',\" + RowDimId + \",\" +\r\n newstart;\r\n var onc = \" onclick=\\\"scrollData(\" + args + \")\\\" \";\r\n //\r\n istr += \"<img src='images/uparrow1.png' \" + onc +\r\n \" width=16px height=16px>\";\r\n\r\n } else if (r == (row_end - 1) &&\r\n (row_end < gO.dimActSize[RowDimId])) {\r\n\r\n var args = \"'\" + htmlId + \"',\" + RowDimId + \",\" +\r\n row_end;\r\n var onc = \" onclick=\\\"scrollData(\" + args + \")\\\" \";\r\n //\r\n istr += \"<img src='images/downarrow1.png' \" + onc +\r\n \" width=16px height=16px>\";\r\n }\r\n\r\n istr += \"\" + r; // row number whiles showing data\r\n\r\n //logMsg(\"rowIndices w/ showdata: \" + hasRowIndices +\" \"+istr);\r\n\r\n\r\n } else if (gO.multiRow && iO) {\r\n istr = getIndExprStr(iO.dimIndExprs[RowDimId][r]);\r\n\t\t//MPI: 'istr' shows 0, row, end0 (if showing data, then\r\n\t\t// it has endered the \"if\" not this \"else if\"...\r\n }\r\n\r\n var rind_str = \"<td class='\" + indclass + \"' \" + onc + \">\" +\r\n istr + \"</td>\";\r\n\r\n // add row index only if multi-row\r\n //\r\n var scalar_str = \"<td class='rowindex'></td>\"; // empty cell\r\n str += (gO.multiRow) ? rind_str : scalar_str;\r\n\r\n } else if (hasRowIndices) {\r\n\r\n // We have row indices but no index object (e.g., for Header step)\r\n // Just draw an empty row-index cell.\r\n //\r\n str += \"<td class='rowindex'></td>\"; // empty cell\r\n\r\n }\r\n\r\n\r\n\r\n // Draw row types/titles, if present\r\n //\r\n if (hasRowTitles) { // draw TYPE in cell when row titles\r\n\r\n // if data type is in every row, draw it now \r\n //\r\n if (perRowTy) { // data type in every row\r\n\r\n str += \"<td class='rowindex'>\";\r\n //\r\n var sel = \"(\" + TypesArr[gO.dataTypes[r]] + \")\";\r\n if (edit) sel = getTypeSelectStr(r, gO.dataTypes[r],\r\n htmlId);\r\n str += sel;\r\n //\r\n str += \"</td>\";\r\n }\r\n\r\n // Now Draw the actual title\r\n //\r\n var fun = (!edit) ? \"\" :\r\n \" oninput='changeRowTitle(this,\" + r +\r\n \")' contenteditable\";\r\n //\r\n var tip = (edit) ? \" title='click to edit' \" : \"\";\r\n var sty = \" style='padding:4px' \";\r\n var tstr = \" <span \" + fun + tip + sty + \">\" +\r\n gO.dimTitles[RowDimId][r];\r\n\r\n var comId = getCommentHtmlId(CommentType.DimTitle + RowDimId,\r\n r);\r\n var cur_comment = gO.dimComments[RowDimId][r];\r\n var comSpan = getCommentStr('span', comId,\r\n \" style='margin:4px' \", cur_comment);\r\n\r\n str += \"<td class='rowtitle'>\" + comSpan + tstr + \"</span>\" +\r\n \"</td>\";\r\n\r\n } // if row titles (and types)\r\n\r\n\r\n // If this is a scalar grid, there are no row types/titles/indices\r\n // So, to move it right of the the topLeft comment, add a dummy\r\n // cell (beacause we assume there is always row titles/indices\r\n // will be present\r\n //\r\n if (gO.numDims == 0)\r\n str += \"<td></td>\";\r\n\r\n\r\n // Now draw CONTENT cells for all columns in this row\r\n //\r\n var col_start = (showData) ? gO.dimShowStart[ColDimId] : 0;\r\n var col_end = getDimEnd(gO, ColDimId, col_start, showData);\r\n //\r\n for (var c = col_start; c < col_end; c++) {\r\n\r\n // Select default cell class based on the row\r\n //\r\n var cell_class = (r % 2) ? \" class='odd' \" : \" class='even' \";\r\n\r\n\r\n\t //MPI: Show dotted cells type for extended dimensions' cells\r\n\t // Only when editing a grid\r\n\t if (edit) {\r\n\t if (gO.dimIsExtended[RowDimId] && \r\n\t\t !gO.dimIsExtended[ColDimId]) {\r\n\r\n\t if (r < 2 || r >= row_end - 2)\r\n\t\t cell_class = \" class='extended' \";\r\n\r\n\t } else if (gO.dimIsExtended[ColDimId] && \r\n\t\t !gO.dimIsExtended[RowDimId]) {\r\n\r\n\t \t if (c < 2 || c >= col_end - 2)\r\n\t\t cell_class = \" class='extended' \";\r\n\r\n\t } else if (gO.dimIsExtended[RowDimId] && \r\n\t\t gO.dimIsExtended[ColDimId]) {\r\n\r\n\t \t if ( (r < 2 || r >= row_end -2) || \r\n\t\t ( (r >= 2 || r <= row_end - 2) && \r\n\t\t (c<2 || c >= col_end - 2)) )\r\n\t\t cell_class = \" class='extended' \";\r\n\r\n\t }\r\n\t }\r\n\r\n\r\n var tip = \"\",\r\n val = \"\",\r\n prop = \"\";\r\n if (!edit && !showData && !isHeaderStep && iO) {\r\n var cel = getCellExpr(gO, iO, r, c); // array notation string\r\n if (cel.length) { // if not empty\r\n var args = \"'\" + htmlId + \"',\" + r + \",\" + c;\r\n var onc = \" onclick=\\\"putCellInd(\" + args + \")\\\"\";\r\n tip = \"title='\" + cel + \"' \" + onc;\r\n }\r\n }\r\n\r\n // if initilizatio of data is required, make cells contentedible.\r\n //\r\n if (edit && gO.hasInitData) {\r\n\r\n /*\r\n\t\tval = getDataVal(gO.numDims-1, gO.data, r, c, gO.dimSelectTabs);\r\n\t\tval = (val === undefined) ? \"\" : val;\r\n\t\t*/\r\n\r\n prop += \" contenteditable \";\r\n\r\n }\r\n\r\n\r\n // Highlight any selected cells.\r\n // We highlight only if an expression is selected in the \r\n // code window. \r\n //\r\n var ishigh = gO.hasSelection && !showData;\r\n var cell_high = false;\r\n //\r\n if ((gO.dimSelectTabs[RowDimId] == r) && ishigh &&\r\n (gO.dimSelectTabs[ColDimId] == c)) {\r\n cell_class = \" class='select' \";\r\n cell_high = true;\r\n }\r\n //\r\n if (showData && !edit && gO.data) { // data to show\r\n\r\n val = getDataValOfCell(gO, r, c);\r\n\r\n val = (val === undefined) ? \"\" : val;\r\n if (colorize && !cell_high) {\r\n var hexcol = getHexColor(val, CurStepObj.maxDataVal);\r\n cell_class += \" style='background-color:#\" + hexcol +\r\n \"' \";\r\n }\r\n }\r\n //\r\n str += \"<td \" + cell_class + tip + prop + \">\" + val + \"</td>\";\r\n }\r\n\r\n // Insert/Delete Row. \r\n //\r\n if (!edit) {\r\n str += \"<td class='insrow' onclick='sliceClicked(this,\" +\r\n RowDimId + \",\" + r + \",\\\"\" + htmlId + \"\\\")'></td>\";\r\n }\r\n //\r\n // close the row \r\n //\r\n str += \"</tr>\";\r\n\r\n } // for all rows\r\n\r\n str += \"</table>\"; // close grid table\r\n\r\n\r\n return str;\r\n\r\n}",
"function drawGrid() {\n for(let i = 0; i < HEIGHT; i++) {\n // create a new raw\n let raw = $('<div class=\"raw\"></div>');\n // fill the raw with squares\n for(let j = 0; j < WIDTH; j++) {\n raw.append('<div class=\"block\"></div>');\n }\n // append the raw to the grid container to create the grid\n $('#grid-container').append(raw);\n } \n console.log('[GRID] drawn');\n addGridListeners();\n }",
"function drawGrid(cw, ch){\n /*\n Draw the grid. \n */\n var v = 36;\n ctx.globalAlpha = 0.5;\n ctx.lineWidth=1;\n ctx.strokeStyle='blue';\n ctx.setLineDash([5, 15]);\n for( var i=0; i<cw/100; i++){\n drawLine( i * 100, 0+v, i*100, ch+v); ctx.stroke();\n }\n for(var j=0; j<ch/100; j++){\n drawLine(0, j*100+v, cw, j*100+v); ctx.stroke();\n }\n \n /* Randomly initialize puzzle piece elements on the grid (for now).. \n\tChange this later.. \n */\n if( progIter<1){\n for( var i =0; i<=cw/100; i++){\n for(var j=0; j<=ch/100; j++){\n var cI = i.toString()+'-'+j.toString();\n if( cI in gridContent){\n\t\t\t\t//pass\n }else{\n\t\t\t\tif( Math.random()<.4){////if( i%3==0 || j%==0){\n\t\t\t\t\tgridContent[cI]=(nextPuzzlePieceName++);\n\t\t\t\t}else{\n\t\t\t\t\tgridContent[cI]=-1;\n\t\t\t\t}\n }\n }\n }\n }\n ctx.globalAlpha = 1.;\n}",
"function drawGrid(){\r\n\t\r\n\tfor (var i = 0; i < grid.length; i++){\r\n\t\tfor (var j = 0; j < grid[i].length; j++){\r\n\t\t\t//Set the color to the cell's color\r\n\t\t\tctx.fillStyle = grid[i][j].color;\r\n\t\t\t//Offset each reactangle so that they are drawn in a grid\r\n\t\t\tctx.fillRect(10*i, 10*j, grid[i][j].len, grid[i][j].len);\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n}",
"function drawHTMLGrid(node) {\n\t//clear the node first\n\tnode.innerHTML = \"\";\n\n\t//table tr th\n\tlet table = document.createElement(\"table\");\n\t\n\t//insert trs and ths\n\tfor(let i=0;i<9;i++){\n\t\tlet tr = document.createElement(\"tr\");\n\t\ttr.setAttribute(\"id\",\"y\"+i);\n\t\tfor(let j=0;j<9;j++){\n\t\t\tlet td = document.createElement(\"td\");\n\t\t\ttd.setAttribute(\"id\",\"x\"+j+\"y\"+i);\n\t\t\tlet pile;\n\t\t\tlet num = getPile(j,i);\n\t\t\tpile = document.createElement(\"input\");\n\t\t\t//will use css later\n\t\t\tpile.setAttribute(\"autocomplete\",\"off\");\n\t\t\tpile.setAttribute(\"maxlength\",\"1\");\n\t\t\tpile.setAttribute(\"size\",\"2\");\n\t\t\t//if it's a pure num, set the input box to readonly\n\t\t\tif(num > 0){\n\t\t\t\tpile.setAttribute(\"readonly\",\"\");\n\t\t\t\tpile.setAttribute(\"value\",num);\n\t\t\t}\n\t\t\tpile.setAttribute(\"id\",j+\",\"+i);\n\t\t\ttd.append(pile);\t\n\t\t\ttr.append(td);\n\t\t}\n\t\ttable.append(tr);\n\t}\n\tnode.append(table);\n}",
"function renderGrid(ctx) {\n drawGridLines(ctx);\n drawGridCells(ctx, minesweeper.cells );\n}",
"function redrawCurStep() {\r\n\r\n\r\n var fO = CurFuncObj;\r\n var sO = CurStepObj;\r\n\r\n // for all grid objects in sO (stepObject)\r\n //\r\n for (var id = 0; id < sO.allGridIds.length; id++) {\r\n\r\n var htmlId = AllHtmlGridIds[id];\r\n var gO = fO.allGrids[sO.allGridIds[id]];\r\n var iO = sO.allIndObjs[id];\r\n\r\n CurHtmlGridId = htmlId;\r\n\r\n drawGrid(gO, iO, htmlId, false);\r\n }\r\n\r\n\r\n // Finally redraw code window\r\n //\r\n drawCodeWindow(sO);\r\n\r\n}",
"draw() {\n push();\n translate(GSIZE / 2, GSIZE / 2);\n // Ordered drawing allows for the disks to appear to fall behind the grid borders\n this.el_list.forEach(cell => cell.drawDisk());\n this.el_list.forEach(cell => cell.drawBorder());\n this.el_list.filter(cell => cell.highlight)\n .forEach(cell => cell.drawHighlight());\n pop();\n }",
"function drawCanvasGrid(node){\n\n}",
"function drawGridContent(){\n for( var i =0; i<=cw/100; i++){\n for(var j=0; j<=ch/100; j++){\n var cI = i.toString()+'-'+j.toString();\n if( cI in gridContent){\n\tif(gridContent[cI]>=0){\n\t if( pickThis == cI){\n\t /* Mouse motion: puzzle piece follows mouse coordiantes: */\n\t drawPiece(mx, my, 100,100, cI==selectedItem, cI);\n\t\t\t\t//0 + 100*i,21 + 100*j, 100,100);\n\t }else{\n\t //Puzzle piece is static: \n\t drawPiece(0 + 100*i,21 + 100*j, 100,100, cI==selectedItem, cI);\n\t }\n\t //draw(mx, my, 100, 100);\n\t}\n }\n }\n }\n}",
"function drawGrid() {\n for(var i = 0; i < nRows; i++) {\n\tfor(var j = 0; j < nCols; j++) {\n\t if(gol.getCell(i, j) == 1)\n\t\tgridCtx.fillStyle = \"white\";\n\t else\n\t\tgridCtx.fillStyle = \"black\";\n\t gridCtx.fillRect(j * cellWidth + 1, i * cellHeight + 1, cellWidth - 2, cellHeight - 2);\n\t}\n }\n //console.log(gol.toString());\n}",
"deleteGrid() {\n this.gridArray.length = 0; // deleting the grid array\n let child = this.gridDOM.lastElementChild;\n\n // deleting all the squares from the grid\n while(child) {\n this.gridDOM.removeChild(child);\n child = this.gridDOM.lastElementChild;\n }\n }",
"function createGrid() {\n // set CSS properties\n document.documentElement.style.setProperty('--grid_size', gridSize);\n document.documentElement.style\n .setProperty('--font_size_tile_adaptable', `${6 - gridSize/3}vh`);\n\n // get grid HTML element and empty its content from previous grid\n const grid = document.getElementById('grid');\n grid.innerHTML = '';\n\n for (let iRow = 0; iRow < gridSize; iRow += 1) {\n const row = document.createElement('div');\n row.className = 'row';\n\n for (let iCol = 0; iCol < gridSize; iCol += 1) {\n const tile = document.createElement('button');\n tile.disabled = true;\n tile.className = 'tile';\n tile.id = `tileR${iRow}C${iCol}`;\n tile.addEventListener('click', () => newMove([iRow, iCol]));\n row.appendChild(tile);\n }\n\n grid.appendChild(row);\n }\n\n // make 2D array that holds tile objects\n tiles = new Array(gridSize);\n for (let iRow = 0; iRow < gridSize; iRow++) {\n tiles[iRow] = new Array(gridSize);\n }\n}",
"function draw() {\n // clear the canvas\n canvas.width = canvas.width;\n drawBlocks();\n drawGrid();\n }",
"function clearGrid() {\n initializeColorGrid();\n draw();\n }",
"function Grid() {\n $.jqplot.ElemContainer.call(this);\n // Group: Properties\n \n // prop: drawGridlines\n // wether to draw the gridlines on the plot.\n this.drawGridlines = true;\n // prop: gridLineColor\n // color of the grid lines.\n this.gridLineColor = '#cccccc';\n // prop: gridLineWidth\n // width of the grid lines.\n this.gridLineWidth = 1.0;\n // prop: background\n // css spec for the background color.\n this.background = '#fffdf6';\n // prop: borderColor\n // css spec for the color of the grid border.\n this.borderColor = '#999999';\n // prop: borderWidth\n // width of the border in pixels.\n this.borderWidth = 2.0;\n // prop: shadow\n // wether to show a shadow behind the grid.\n this.shadow = true;\n // prop: shadowAngle\n // shadow angle in degrees\n this.shadowAngle = 45;\n // prop: shadowOffset\n // Offset of each shadow stroke from the border in pixels\n this.shadowOffset = 1.5;\n // prop: shadowWidth\n // width of the stoke for the shadow\n this.shadowWidth = 3;\n // prop: shadowDepth\n // Number of times shadow is stroked, each stroke offset shadowOffset from the last.\n this.shadowDepth = 3;\n // prop: shadowAlpha\n // Alpha channel transparency of shadow. 0 = transparent.\n this.shadowAlpha = '0.07';\n this._left;\n this._top;\n this._right;\n this._bottom;\n this._width;\n this._height;\n this._axes = [];\n // prop: renderer\n // Instance of a renderer which will actually render the grid,\n // see <$.jqplot.CanvasGridRenderer>.\n this.renderer = $.jqplot.CanvasGridRenderer;\n // prop: rendererOptions\n // Options to pass on to the renderer,\n // see <$.jqplot.CanvasGridRenderer>.\n this.rendererOptions = {};\n this._offsets = {top:null, bottom:null, left:null, right:null};\n }",
"drawGrid() {\n const { id, selected } = this.currentWord;\n\n clear();\n this.logger.log(figlet.textSync(wordsearchConstants.GAME_TITLE, { font: 'Mini' }));\n this.logger.log(wordsearchConstants.GAME_INFO);\n this.logger.log(chalk.grey(wordsearchConstants.GAME_INSTRUCTIONS));\n\n this.grid.forEach((row, rowIdx) => {\n // first add all letters in the row (with correct colours)\n const rowData = [];\n row.forEach((item, itemIdx) => {\n if (this.guessedWords.indexOf(item.word) !== -1) {\n rowData.push(chalk.green(item.letter));\n } else if (item.word === id && selected.indexOf(`${rowIdx},${itemIdx}`) !== -1) {\n rowData.push(chalk.black.bgGreen(item.letter));\n } else {\n rowData.push(item.letter);\n }\n });\n let rowStr = rowData.join(' ');\n\n // then add a word from the word list to the right of the grid\n if (this.wordsearchWordList[rowIdx]) {\n rowStr += wordsearchConstants.WORD_SPACING;\n let word = this.wordsearchWordList[rowIdx];\n if (this.guessedWords.indexOf(rowIdx) !== -1) {\n word = chalk.green(word);\n }\n rowStr += word;\n }\n\n this.logger.log(rowStr);\n });\n\n this.setCursorPos();\n }",
"function draw() {\n\n // These two variables represent the width and height of each grid item.\n var gridItemWidth = canvas.width / grid.width;\n var gridItemHeight = canvas.height / grid.height;\n\n // The grid (large rectangle) is made of many grid items (small rectangles).\n // Loop through the grid to determine color for each grid item,\n // and then draw each grid item.\n for(var x = 0; x < grid.width; x ++) {\n for(var y = 0; y < grid.height; y ++) {\n\n // Switch color for different values of the grid item.\n switch(grid.get(x, y)) {\n case EMPTY:\n ctx.fillStyle = \"#000\";\n break;\n\n case SNAKE:\n ctx.fillStyle = \"#E74C3C\";\n break;\n\n case FOOD:\n ctx.fillStyle = \"#3498DB\";\n break;\n }\n\n // Drawing grid item.\n ctx.fillRect(x * gridItemWidth, y * gridItemHeight, gridItemWidth, gridItemHeight);\n }\n }\n\n // Write score on canvas.\n ctx.fillStyle = \"#fff\";\n ctx.fillText(\"SCORE: \" + score, 10, canvas.height - 10);\n ctx.fillText(\"SPEED: \" + snakeMovingSpeed, canvas.width - 90, canvas.height - 10);\n}",
"function createGrid() {\n for (let i = 0; i < width * height; i++) {\n const cell = document.createElement('div')\n grid.appendChild(cell)\n cells.push(cell)\n }\n for (let i = 2; i < 22; i++) {\n rowArray.push(cells.slice(i * 10, ((i * 10) + 10)))\n }\n for (let i = 0; i < 20; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('top')\n }\n for (let i = 10; i < 20; i++) {\n cells[i].classList.remove('top')\n cells[i].classList.add('topline')\n }\n for (let i = 220; i < 230; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('bottom')\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
L1 norm of x pi (where pi is the uniform distribution) | function normL1(x) {
return x.reduce(function (acc, curr) {
return acc + Math.abs(curr - uniform);
}, 0);
} | [
"get norm () { return Math.sqrt(this.normSquared); }",
"function L2normalization(array){\r\n var normalizedArray = new Array();\r\n var powArray = new Array();\r\n for(let i = 0; i < array.length; i++){\r\n powArray.push(Math.pow(array[i],2));\r\n }\r\n var sum = powArray.reduce((x, y) => x + y);\r\n var norm = Math.sqrt(sum);\r\n for(let i = 0; i < array.length; i++){\r\n normalizedArray.push(array[i]/norm);\r\n }\r\n return normalizedArray;\r\n}",
"function normaliseScale(s) {\n if (s > 1) throw('s must be <1');\n s = 0 | (1 / s);\n var l = log2(s);\n var mask = 1 << l;\n var accuracy = 4;\n while (accuracy && l) {\n l--;\n mask |= 1 << l;\n accuracy--;\n }\n return 1 / ( s & mask );\n }",
"function myPi(n) {\n\treturn parseFloat(Math.PI.toFixed(n));\n}",
"function minimum_1(xs) /* (xs : list<double>) -> double */ {\n return (xs == null) ? 0.0 : foldl(xs.tail, xs.head, min_1);\n}",
"function gauss(x, s) {\n // 2.5066282746310005 is sqrt(2*pi)\n return Math.exp(-0.5 * x*x / (s*s)) / (s * 2.5066282746310005);\n}",
"function DotVectorNormal(v,n){\r\n\t\t\treturn (v.ux*n.nx+v.uy*n.ny+v.uz*n.nz);\r\n\t\t}",
"function TAU() {\n return τ;\n}",
"function probability_mass(x, trials, probability) {\n return factorial(trials) /\n (factorial(x) * factorial(trials - x)) *\n (Math.pow(probability, x) * Math.pow(1 - probability, trials - x));\n }",
"dtdxn(x) {\n const r0 = this.r0Vec.length();\n const z = this.z(x);\n const term1 = Math.pow(x, 2) * this.C(x);\n const term2 = ( this.r0Vec.dot( this.v0Vec ) / this.rootMu ) * x * ( 1 - z * this.S(x) );\n const term3 = r0 * ( 1 - z * this.C(x) );\n\n return ( term1 + term2 + term3 ) / this.rootMu;\n }",
"function buscarCuadrados(inicial,final)\n{ \n cuadrados = 0;\n for(contador=inicial; contador<=final; contador++)\n {\n if(Math.sqrt(contador)%1 == 0)\n {\n cuadrados++;\n }\n else{}\n }\n console.log(cuadrados);\n}",
"function unegyptian(array) {\n let total = 1 / array[0];\n for (let index = 1; index < array.length; index++) {\n total += (1 / array[index]);\n }\n\n return total;\n}",
"function gaussianKernel1D(s, n) {\n if (typeof n !== 'number') n = 7;\n var kernel = new Float64Array(n),\n halfN = Math.floor(n * 0.5),\n odd = n % 2,\n i;\n if (!s || !n) return kernel;\n for (i = 0; i <= halfN; i++) {\n kernel[i] = gauss(s * (i - halfN - odd * 0.5), s);\n }\n for (; i < n; i++) {\n kernel[i] = kernel[n - 1 - i];\n }\n return kernel;\n}",
"#rms(array) {\n const squares = array.map((value) => value * value);\n const sum = squares.reduce((accumulator, value) => accumulator + value);\n const mean = sum / array.length;\n return Math.sqrt(mean);\n }",
"function PerlinNoise() {\n //srandom(clock());\n \n this.perlin_TWOPI = SINCOS_LENGTH;\n this.perlin_PI = this.perlin_TWOPI / 2;\n \n this.cosTable = [];\n for (i = 0; i < SINCOS_LENGTH; i++) {\n //sinLUT[i] = (float) sin(i * DEG_TO_RAD * SINCOS_PRECISION);\n this.cosTable[i] = Math.cos(i * DEG_TO_RAD * SINCOS_PRECISION);\n }\n\n this.perlin = [];\n for (i = 0; i < PERLIN_SIZE + 1; i++) {\n this.perlin[i] = Math.random();\n }\n}",
"function VxEuclideanRythm ()\n{\n\tthis.k = 4;\n\tthis.N = 16;\n\tthis.R = 0;\n\tthis.algorithm = 'bjorklund';\n\tthis.integermode = 0;\n}",
"static length2sq(it) { return (it.x*it.x)+(it.y*it.y); }",
"function lanczosCreate(lobes) {\r\n return function (x) {\r\n if (x > lobes)\r\n return 0;\r\n x *= Math.PI;\r\n if (Math.abs(x) < 1e-16)\r\n return 1;\r\n var xx = x / lobes;\r\n return Math.sin(x) * Math.sin(xx) / x / xx;\r\n };\r\n}",
"static Normalize(vector) {\n const newVector = new Vector2(vector.x, vector.y);\n newVector.normalize();\n return newVector;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves a copy of this page as a template in this library's Templates folder | async saveAsTemplate(publish = true) {
const data = await spPost(ClientsidePage(this, `_api/sitepages/pages(${this.json.Id})/SavePageAsTemplate`));
const page = ClientsidePage(this, null, data);
page.title = this.title;
await page.save(publish);
return page;
} | [
"function createPage() {\n\t\t// check to see if the directory exists\n\t\tif (!fs.existsSync(OUTPUT_DIR)) {\n\t\t\t// if it does not, then make it\n\t\t\tfs.mkdirSync(OUTPUT_DIR);\n\t\t}\n\t\t// write the html file using the render(coworkers) data\n\t\tfs.writeFileSync(outputPath, render(coworkers), \"utf-8\");\n\t}",
"function SavePage ()\n{\n\tvar PageName = doAction('REQ_GET_FORMVALUE', \"PageName\", \"PageName\");\n\tif (!PageName)\n\t{\n\t\tPageName = doAction('ST_GET_STATEDATA', 'CurrentPageName', 'CurrentPageName');\n\t\tif (!PageName || PageName == '')\n\t\t\tPageName = gHOME_PAGE;\n\t}\n\tvar seObj = generateSEObjects (gCURRENT_PAGE);\n\taddUpdateSiteEditorCfg (PageName, seObj.pageObjArray[gCURRENT_PAGE], \n\t\t\t\t\t\t\tseObj.pageObjArray[gBASE_PAGE], seObj.colNames);\n\treturn (SavePageByName (PageName));\n}",
"_writingSampleCode() {\n\n this.fs.copy(\n this.templatePath('sample/src/templates/HelloWorld.hbs'),\n this.destinationPath('src/webparts/templates/HelloWorld.hbs')\n )\n\n }",
"storeTemplate(name, template) {\n let configSnippetsPath = path.join(this.projectFolder, \"config-snippets\", name);\n this.utils.writeJsonFile(configSnippetsPath, template);\n return configSnippetsPath;\n }",
"async copyTo(page, publish = true) {\n // we know the method is on the class - but it is protected so not part of the interface\n page.setControls(this.getControls());\n // copy page properties\n if (this._layoutPart.properties) {\n if (hOP(this._layoutPart.properties, \"topicHeader\")) {\n page.topicHeader = this._layoutPart.properties.topicHeader;\n }\n if (hOP(this._layoutPart.properties, \"imageSourceType\")) {\n page._layoutPart.properties.imageSourceType = this._layoutPart.properties.imageSourceType;\n }\n if (hOP(this._layoutPart.properties, \"layoutType\")) {\n page._layoutPart.properties.layoutType = this._layoutPart.properties.layoutType;\n }\n if (hOP(this._layoutPart.properties, \"textAlignment\")) {\n page._layoutPart.properties.textAlignment = this._layoutPart.properties.textAlignment;\n }\n if (hOP(this._layoutPart.properties, \"showTopicHeader\")) {\n page._layoutPart.properties.showTopicHeader = this._layoutPart.properties.showTopicHeader;\n }\n if (hOP(this._layoutPart.properties, \"showPublishDate\")) {\n page._layoutPart.properties.showPublishDate = this._layoutPart.properties.showPublishDate;\n }\n if (hOP(this._layoutPart.properties, \"enableGradientEffect\")) {\n page._layoutPart.properties.enableGradientEffect = this._layoutPart.properties.enableGradientEffect;\n }\n }\n // we need to do some work to set the banner image url in the copied page\n if (!stringIsNullOrEmpty(this.json.BannerImageUrl)) {\n // use a URL to parse things for us\n const url = new URL(this.json.BannerImageUrl);\n // helper function to translate the guid strings into properly formatted guids with dashes\n const makeGuid = (s) => s.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/g, \"$1-$2-$3-$4-$5\");\n // protect against errors because the serverside impl has changed, we'll just skip\n if (url.searchParams.has(\"guidSite\") && url.searchParams.has(\"guidWeb\") && url.searchParams.has(\"guidFile\")) {\n const guidSite = makeGuid(url.searchParams.get(\"guidSite\"));\n const guidWeb = makeGuid(url.searchParams.get(\"guidWeb\"));\n const guidFile = makeGuid(url.searchParams.get(\"guidFile\"));\n const site = Site(this);\n const id = await site.select(\"Id\")();\n // the site guid must match the current site's guid or we are unable to set the image\n if (id.Id === guidSite) {\n const openWeb = await site.openWebById(guidWeb);\n const file = await openWeb.web.getFileById(guidFile).select(\"ServerRelativeUrl\")();\n const props = {};\n if (this._layoutPart.properties) {\n if (hOP(this._layoutPart.properties, \"translateX\")) {\n props.translateX = this._layoutPart.properties.translateX;\n }\n if (hOP(this._layoutPart.properties, \"translateY\")) {\n props.translateY = this._layoutPart.properties.translateY;\n }\n if (hOP(this._layoutPart.properties, \"imageSourceType\")) {\n props.imageSourceType = this._layoutPart.properties.imageSourceType;\n }\n if (hOP(this._layoutPart.properties, \"altText\")) {\n props.altText = this._layoutPart.properties.altText;\n }\n }\n page.setBannerImage(file.ServerRelativeUrl, props);\n }\n }\n }\n await page.save(publish);\n return page;\n }",
"function template_edit()\n{\n}",
"async createProjectTemplate(event, data) {\n const result = await this.templateCreator.create(data.type, data.location);\n if (!result || result.err) {\n let msg = `Could not create ${data.type} template at ${data.location}`;\n if (result && result.err) {\n msg = result.err;\n }\n dialog.showErrorBox('Failed to create template', msg);\n }\n else if (result.success) {\n projectInfo.location = data.location;\n captionInfo.audioLocation = data.location;\n }\n this.window.webContents.send(EVENTS.PROJECT_CREATION_COMPLETE, result && !!result.success);\n }",
"function addPage(page) {\r\n document.querySelector(\"#pages\").innerHTML += `\r\n <section id=\"${page.slug}\" class=\"page\">\r\n <header class=\"topbar\">\r\n <h2>${page.title.rendered}</h2>\r\n </header>\r\n ${page.content.rendered}\r\n </section>\r\n `;\r\n}",
"function feedbackPageCreation(page) {\n Page.findOne({\n page: page\n }, function(err, foundPage) {\n if (!foundPage) {\n const viewPage = new Page({\n page: page,\n contents: [],\n ratings: []\n });\n viewPage.save();\n }\n });\n}",
"function addPage(page) {\n document.querySelector(\"#pages\").innerHTML += `\n <section id=\"${page.slug}\" class=\"page\">\n ${page.content.rendered}\n </section>\n `;\n}",
"function FileTemplateAdder() {\n\tvar tempOptions = {\n\t\t'{{Jpeg}}': '.JPG',\n\t\t'{{Trans}}': 'Needs trans',\n\t\t'{{Imagequality}}': 'Poor quality'\n\t};\n if (wgUserGroups.indexOf(\"sysop\") != -1) {\n tempOptions['{{SDS}}'] = \"SDS\";\n }\n\tvar tempOptStr = '';\n\tfor(i in tempOptions) {\n\t\ttempOptStr += '<option value=\"' + i + '\" style=\"text-align:center;\">' + tempOptions[i] + '</option>';\n\t}\n \tvar html = '<p style=\"text-align:center;\" class=\"TemplateAdder\"><select id=\"FileTemplateAdder\">' + tempOptStr + '</select> <a class=\"wikia-button\" style=\"margin:0 1em; cursor:pointer;\" id=\"templateSubmit\">Add template</a>';\n\t$('#filetoc').append(html);\n\t$('#templateSubmit').click(function(event) {\n\t\tthis.innerHTML = '<img src=\"https://images.wikia.nocookie.net/dev/images/8/82/Facebook_throbber.gif\" style=\"vertical-align: baseline;\" border=\"0\" />';\n\t\t$.getJSON(\"/api.php\", {action: \"query\", prop: \"info\", titles: wgPageName, intoken: \"edit\", format: \"json\", indexpageids: 1}, function(json) {\n\t\t\tvar pageIdentification = json.query.pageids[0];\n\t\t\tvar pageToken = json.query.pages[pageIdentification].edittoken;\n\t\t\t$.post(\"/api.php\", {action: \"edit\", title: wgPageName, token: pageToken, bot: true, prependtext: $('#FileTemplateAdder').val() + \"\\n\"}, function (result) {$(\".TemplateAdder\").remove();});\n\t\t});\n\t});\n}",
"function finishContent(siteIndex, siteConfig) {\n // Copy supporting files.\n fileHandlers.copyHandler(siteConfig);\n\n // Loop through our pages, process each and copy its content into place.\n siteIndex.content.forEach((file) => {\n templates.processTemplate(file, siteIndex, siteConfig);\n });\n}",
"getLayoutAndSaveAsCookie() {\n const botsLayout = this.getBotLayoutFromPage();\n u.setCookie(`${window.location.pathname}-bots-layout`,\n JSON.stringify(botsLayout));\n }",
"static async replaceSaveFile(that, gameClass, savedGames){\n\t\tawait FileManager.removePreviousSave(savedGames);\n\t\tgameClass.createPage(that);\n\t}",
"static generate_settings() {\n // Initialise variables\n var html_content = {}\n var html_heading = {}\n\n // Setup content and heading variables\n for (var item of this.settings_json[\"categories\"]) {\n html_content[item] = \"\"\n\n html_heading[item] = this.html_settings_heading\n .replace(/{{item}}/g, item)\n }\n\n // Loop through setttings JSON and create HTML file\n for (var item of this.settings_json[\"settings\"]) {\n\n var category = item[\"category\"]\n\n // Select correct template based on advanced setting or not\n var temp_out\n if (item[\"advanced\"]) {\n temp_out = this.html_settings_advanced\n } else {\n temp_out = this.html_settings\n }\n\n // Replace variables\n temp_out = temp_out\n .replace(/{{title}}/g, item[\"title\"])\n .replace(/{{id}}/g, item[\"id\"])\n .replace(/{{unit}}/g, item[\"unit\"])\n .replace(/{{help}}/g, item[\"help\"])\n\n // Update main string\n html_content[category] = html_content[category].concat(temp_out)\n }\n\n var temp_html = \"\"\n for (item of this.settings_json[\"categories\"]) {\n temp_html = temp_html\n .concat(html_heading[item])\n .concat(html_content[item])\n }\n\n // Update HMTL on page\n document.querySelector(\"#settings_template_div\").innerHTML = temp_html\n }",
"function SavePageByName (PageName)\n{\n\tdoActionEx('MPEA_SAVE_PAGE', 'Result', 'PageName', PageName);\n\treturn (PageName);\n}",
"async function saveEditing() {\n // Gets the files contents from #fileEditor\n const selectedFileContent = document.getElementById(\"fileEditor\").innerText;\n let type;\n\n if (selectedFile.substr(0, 3) === '/pa') {\n type = 'pages';\n } else if (selectedFile.substr(0, 3) === '/st') {\n type = 'styles';\n } else if (selectedFile.substr(0, 3) === '/sc') {\n type = 'scripts';\n }\n\n // Asks for confirmation of current action\n if (window.confirm(\"Are you sure you want to save the changes made to \" + selectedFile + \" ? \" + \"These changes could cause knock on effects to other pages and files being used on live displays.\")) {\n\n // The selectedFileContent will be saved to the selectedFile\n await fetch('/api/' + type + '/' + selectedFileName, {\n method: 'PUT',\n headers: { 'Content-Type' : 'application/json' },\n body: JSON.stringify({\n file: {\n content: selectedFileContent\n }\n })\n });\n // The page will be reloaded\n reloadPage();\n }\n}",
"_setTemplate () {\n if (this._options.templatePath) {\n this._template = this._options.templatePath\n return\n }\n const generationTemplates = templates[this._options.generation]\n if (!generationTemplates) {\n throw new Error(`Generation not supported: ${generationTemplates}`)\n }\n this._template = generationTemplates[this._options.semicolons ? 'semicolons' : 'default']\n }",
"function CreatePageByName (PageName)\n{\n\tif (!PageName || PageName == '')\n\t\tvar PageName = gHOME_PAGE;\n\tvar seObj = generateSEObjects ('');\n\tvar newPage = new SE_Obj ();\n\t\n\tif (seObj.pageObjArray[PageName])\n\t{\n\t\tnewPage[gBUTTON_ORDER] = seObj.pageObjArray[PageName][gBUTTON_ORDER];\n\t\tnewPage[gTITLE] = seObj.pageObjArray[PageName][gTITLE];\n\t}\n\telse\n\t{\n\t\t// negative button order numbers are not in the nave buttons, so count the\n\t\t// pages with non-negative button orders\n\t\tvar numButtons = new Array();\n\t\tfor (var n = 0; n < seObj.pageList.length; n++)\n\t\t{\n\t\t\tvar pos = parseInt (seObj.pageObjArray[seObj.pageList[n]][gBUTTON_ORDER]);\n\t\t\tif (seObj.pageList[n] != gBASE_PAGE && pos > 0)\n\t\t\t\tnumButtons.push(seObj.pageList[n]);\n\t\t}\n\t\tnewPage[gBUTTON_ORDER] = (numButtons.length+1).toString();\n\t\tnewPage[gTITLE] = PageName;\n\t}\n\t\n\tvar getRet = addUpdateSiteEditorCfg (PageName, newPage, seObj.pageObjArray[gBASE_PAGE], \n\t\t\t\t\t\t\t\t\t\tseObj.colNames);\n\tdoActionEx('MPEA_CREATE_PAGE', 'Result', 'PageName', PageName);\n\treturn PageName;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a function for postV3ProjectsIdBuildsBuildIdCancel | postV3ProjectsIdBuildsBuildIdCancel(incomingOptions, cb) {
const Gitlab = require('./dist');
let defaultClient = Gitlab.ApiClient.instance;
// Configure API key authorization: private_token_header
let private_token_header = defaultClient.authentications['private_token_header'];
private_token_header.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_header.apiKeyPrefix = 'Token';
// Configure API key authorization: private_token_query
let private_token_query = defaultClient.authentications['private_token_query'];
private_token_query.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_query.apiKeyPrefix = 'Token';
let apiInstance = new Gitlab.ProjectsApi()
/*let id = "id_example";*/ // String | The ID of a projec
/*let buildId = 56;*/ // Number | The ID of a build
apiInstance.postV3ProjectsIdBuildsBuildIdCancel(incomingOptions.id, incomingOptions.buildId, (error, data, response) => {
if (error) {
cb(error, null)
} else {
cb(null, data)
}
});
} | [
"postV3ProjectsIdMergeRequestsMergeRequestIdCancelMergeWhenBuildSucceeds(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let mergeRequestId = 56;*/ // Number | \napiInstance.postV3ProjectsIdMergeRequestsMergeRequestIdCancelMergeWhenBuildSucceeds(incomingOptions.id, incomingOptions.mergeRequestId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdPipelinesPipelineIdCancel(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The project I\n/*let pipelineId = 56;*/ // Number | The pipeline ID\napiInstance.postV3ProjectsIdPipelinesPipelineIdCancel(incomingOptions.id, incomingOptions.pipelineId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdMergeRequestMergeRequestIdCancelMergeWhenBuildSucceeds(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let mergeRequestId = 56;*/ // Number | \napiInstance.postV3ProjectsIdMergeRequestMergeRequestIdCancelMergeWhenBuildSucceeds(incomingOptions.id, incomingOptions.mergeRequestId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdBuildsBuildIdErase(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let buildId = 56;*/ // Number | The ID of a build\napiInstance.postV3ProjectsIdBuildsBuildIdErase(incomingOptions.id, incomingOptions.buildId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdBuildsBuildIdRetry(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let buildId = 56;*/ // Number | The ID of a build\napiInstance.postV3ProjectsIdBuildsBuildIdRetry(incomingOptions.id, incomingOptions.buildId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdBuildsBuildIdArtifactsKeep(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let buildId = 56;*/ // Number | The ID of a build\napiInstance.postV3ProjectsIdBuildsBuildIdArtifactsKeep(incomingOptions.id, incomingOptions.buildId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"function cancel() {\n if (parentPort) {\n parentPort.postMessage('Email analytics fetch-latest job cancelled before completion');\n parentPort.postMessage('cancelled');\n } else {\n setTimeout(() => {\n process.exit(0);\n }, 1000);\n }\n}",
"postV3ProjectsIdRefReftriggerBuilds(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let ref = \"ref_example\";*/ // String | The commit sha or name of a branch or ta\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRefReftriggerBuilds(incomingOptions.id, incomingOptions.ref, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdBuildsBuildIdPlay(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let buildId = 56;*/ // Number | The ID of a Build\napiInstance.postV3ProjectsIdBuildsBuildIdPlay(incomingOptions.id, incomingOptions.buildId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdTriggers(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a project\napiInstance.postV3ProjectsIdTriggers(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"function cancel(id) {\n\n var execItem = execData[id];\n\n if (execItem && execItem.state == 'waiting') {\n clearTimeout(execItem.timeoutID);\n execItem.timeoutID = 0;\n execItem.state = 'cancelled';\n }\n\n return this;\n }",
"deleteV3ProjectsIdMergeRequestsMergeRequestId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let mergeRequestId = 56;*/ // Number | The ID of a merge request\napiInstance.deleteV3ProjectsIdMergeRequestsMergeRequestId(incomingOptions.id, incomingOptions.mergeRequestId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"postV3ProjectsIdMergeRequestsMergeRequestIdComments(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let mergeRequestId = 56;*/ // Number |\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdMergeRequestsMergeRequestIdComments(incomingOptions.id, incomingOptions.mergeRequestId, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdMergeRequestMergeRequestIdComments(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let mergeRequestId = 56;*/ // Number |\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdMergeRequestMergeRequestIdComments(incomingOptions.id, incomingOptions.mergeRequestId, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdMergeRequestsMergeRequestIdResetSpentTime(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let mergeRequestId = 56;*/ // Number | The ID of a project merge_request\napiInstance.postV3ProjectsIdMergeRequestsMergeRequestIdResetSpentTime(incomingOptions.id, incomingOptions.mergeRequestId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"cancel() {\n\t\tthis.reconciling = false;\n\t}",
"deleteV3ProjectsIdMergeRequestSubscribableIdSubscription(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let subscribableId = \"subscribableId_example\";*/ // String | The ID of a resource\napiInstance.deleteV3ProjectsIdMergeRequestSubscribableIdSubscription(incomingOptions.id, incomingOptions.subscribableId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdIssues(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdIssues(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"deleteV3ProjectsIdDeployKeysKeyIdDisable(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of the projec\n/*let keyId = 56;*/ // Number | The ID of the deploy key\napiInstance.deleteV3ProjectsIdDeployKeysKeyIdDisable(incomingOptions.id, incomingOptions.keyId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform pow on the message and return the nonce of at least targetScore. | pow(message, targetScore) {
return __awaiter(this, void 0, void 0, function* () {
const powRelevantData = message.slice(0, -8);
const powDigest = iota_js_1$1.Blake2b.sum256(powRelevantData);
const targetZeros = iota_js_1$1.PowHelper.calculateTargetZeros(message, targetScore);
return new Promise((resolve, reject) => {
const chunkSize = BigInt(18446744073709551615) / BigInt(this._numCpus);
const workers = [];
let hasFinished = false;
for (let i = 0; i < this._numCpus; i++) {
const worker = new worker_threads_1$1.Worker(path_1.default.join(__dirname, "pow-node.js"), {
workerData: { powDigest, targetZeros, startIndex: chunkSize * BigInt(i) }
});
workers.push(worker);
worker.on("message", (msg) => __awaiter(this, void 0, void 0, function* () {
hasFinished = true;
for (let j = 0; j < workers.length; j++) {
yield workers[j].terminate();
}
resolve(BigInt(msg));
}));
worker.on("error", err => {
reject(err);
});
worker.on("exit", code => {
if (!hasFinished && code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`));
}
});
}
});
});
} | [
"async getNumberOfCoinsPicked() {\n return Math.random() < 0.5 ? 1 : 2;\n }",
"function other_function(n, m){\n var result = Math.pow( n, m );\n return result;\n}",
"getNonce() {\n return this.web3.eth.getTransactionCount(this.coinbase);\n }",
"proofOfWork(difficulty,pendingTransactions) {\n //TODO\n let nonce = 0\n let prevHash = this.chain.length !== 0 ? this.chain[this.chain.length - 1].hash : '0';\n let hash = this.getHash(prevHash,pendingTransactions,nonce).toString()\n while (hash.substring(0, difficulty) !== Array(difficulty + 1).join('0')) {\n nonce++;\n hash = this.getHash(prevHash,pendingTransactions,nonce);\n }\n return nonce;\n }",
"function pow (baseNum, power){\n var answer = 1;\n\n for(var i = 0; i < (power) ; i++){\n answer *= multiply(baseNum, 1);\n console.log(answer);\n }\n console.log(answer);\n return answer;\n\n}",
"function partyHPS() {\n let power = 10;\n if (!character.party) return power;\n //Add priest heals\n for (let key in parent.party_list) {\n let member = parent.party_list[key];\n let entity = getCharacterData()[member] || parent.entities[member];\n if (!entity || entity.ctype !== 'priest') continue;\n power += entity.attack * entity.frequency * damage_multiplier(-entity.rpiercing || 0) * 0.925;\n }\n return power * 0.9;\n}",
"function powOutput() {\r\n console.log(\"POW-service : The result of raising <base = \" + powObj.base + \"> to the <power = \" + powObj.exponent + \">\\n\\\r\n EQUALS <\" + powObj.result + \">\");\r\n}",
"function numberToPower(num, pow) { //\n if(pow === 0) {\n return 1;\n } else {\n return num * numberToPower(num, pow-1)\n }\n}",
"async computeHashPOS( newTimestamp, posNewMinerAddress, balance ){\n\n let virtualBalance = balance;\n\n let whoIsMining = posNewMinerAddress || this.posMinerAddress || this.data.minerAddress;\n let whoIsReceivingMoney = this.data.minerAddress;\n\n try {\n\n // SHA256(prevhash + address + timestamp) <= 2^256 * balance / diff\n\n let buffer = Buffer.concat([\n\n Serialization.serializeBufferRemovingLeadingZeros( Serialization.serializeNumber4Bytes(this.height) ),\n Serialization.serializeBufferRemovingLeadingZeros( this.difficultyTargetPrev ),\n Serialization.serializeBufferRemovingLeadingZeros( this.hashPrev ),\n Serialization.serializeBufferRemovingLeadingZeros( whoIsMining ),\n Serialization.serializeBufferRemovingLeadingZeros( Serialization.serializeNumber4Bytes( newTimestamp || this.timeStamp) ),\n\n ]);\n\n let hash = await WebDollarCrypto.SHA256(buffer);\n\n if (balance === undefined)\n balance = Blockchain.blockchain.accountantTree.getBalance( whoIsMining );\n\n //reward already included in the new balance\n if ( Blockchain.blockchain.accountantTree.root.hash.equals( this.data.hashAccountantTree ) && balance !== null) {\n\n if ( whoIsReceivingMoney .equals( whoIsMining )) { //in case it was sent to the minerAddress\n\n balance -= this.reward;\n balance -= this.data.transactions.calculateFees();\n\n }\n\n for (let tx of this.data.transactions.transactions){\n\n for (let from of tx.from.addresses)\n if ( from.unencodedAddress.equals( whoIsMining ) )\n balance += from.amount;\n\n for (let to of tx.to.addresses)\n if ( to.unencodedAddress.equals( whoIsMining ))\n balance -= to.amount;\n\n }\n\n }\n\n //also solo miners need to subtract the transactions as well\n if ( !virtualBalance && !Blockchain.MinerPoolManagement.minerPoolSettings.minerPoolActivated ) {\n\n //console.log(\"Before Balance \", balance); let s = \"\";\n\n for (let i = this.height - 1; i >= 0 && i >= this.height - 1 - consts.BLOCKCHAIN.POS.MINIMUM_POS_TRANSFERS; i--) {\n\n let block = await this.blockValidation.getBlockCallBack( i );\n\n if ( !block ) continue;\n\n //s += block.height + \" \";\n\n for (let tx of block.data.transactions.transactions)\n for (let to of tx.to.addresses)\n if (to.unencodedAddress.equals(whoIsMining))\n balance -= to.amount;\n }\n\n //console.log(\"After Balance \", balance, s);\n }\n\n if (balance === null || balance < consts.BLOCKCHAIN.POS.MINIMUM_AMOUNT * WebDollarCoins.WEBD)\n return consts.BLOCKCHAIN.BLOCKS_MAX_TARGET_BUFFER;\n\n let number = new BigInteger( hash.toString(\"hex\"), 16);\n\n let hex = number.divide( balance ).toString(16);\n if (hex.length % 2 === 1) hex = \"0\"+hex;\n\n return Serialization.serializeToFixedBuffer( consts.BLOCKCHAIN.BLOCKS_POW_LENGTH, Buffer.from( hex , \"hex\") );\n\n } catch (exception){\n console.error(\"Error computeHash\", exception);\n //return Buffer.from( consts.BLOCKCHAIN.BLOCKS_MAX_TARGET_BUFFER);\n throw exception;\n }\n }",
"'players.reduceVentureCoins'(num_coins){\n var current_coins = Players.findOne({'owner': Meteor.userId()}).goldCoin;\n if(current_coins < num_coins){\n return false;\n }\n \n Players.update(\n { 'owner': Meteor.userId()},\n { $inc:{'goldCoin': -1 * num_coins}}\n );\n return true;\n }",
"function bnModPowInt( e, m ) {\n var z;\n if ( e < 256 || m.isEven() ) z = new Classic( m );\n else z = new Montgomery( m );\n return this.exp( e, z );\n }",
"function pow(i, exp) /* (i : int, exp : int) -> int */ {\n return _int_pow(i,exp);\n}",
"takeCoin(player, coin){\n coin.kill();\n }",
"function REG(toHitNum){\n let my_num = new Big(toHitNum);\n let chance = my_num.times(.05).times(100);\n return Number(chance.valueOf());\n }",
"getNumberOfCoins() {\n let numberOfCoins = 120000 + (this.numberOfBlocks) * 100;\n return numberOfCoins;\n }",
"function score(state) {\n const result = calculateWinner(state.squares);\n if (result === 'X') {\n return -10;\n } else if (result === 'O') {\n return 10;\n } else {\n return 0;\n }\n}",
"function modCalc(score){\n let mod;\n //determine attribute score\n if(score<2){\n mod=-5;\n }else if(score<=3){\n mod=-4;\n }else if(score<=5){\n mod=-3\n }else if(score<=7){\n mod=-2\n }else if(score<=9){\n mod=-1\n }else if(score<=11){\n mod=0\n }else if(score<=13){\n mod=1\n }else if(score<=15){\n mod=2\n }else if(score<=17){\n mod=3\n }else if(score<=19){\n mod=4\n }else if(score<=21){\n mod=5\n }else if(score<=23){\n mod=6\n }else if(score<=25){\n mod=8\n }else if(score<=27){\n mod=9\n }else if(score<=30){\n mod=10\n }\n return mod;//return modifier value\n }",
"function _weisPerToken(_pricePerEth) {//internal view returns(uint) {\n return (ONE_ETHER / _pricePerEth);\n }",
"function generateTarget() {\n targetScore = Math.floor(Math.random() * (121 - 19) + 19);\n $(\"#targetScore\").text(targetScore);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sanitizeCmd sanitizes and formats the raw string command from the user _________________________________________________________________ | function sanitizeCmd(input) {
input = input.split(' ')
//sanitize the array
for (var i in input) {
input[i] = input[i].toLowerCase().replace(/[^\w\s]/gi, '')
}
return {
'command': input[0],
'args': input.slice(1) //array slice the command off the args list
}
} | [
"function formatInput(command){\n\n if(command === undefined || command.length < 3){\n return \"default\";\n }\n\n else{\n return command.toLowerCase().trim();\n }\n}",
"submitCmd(){\n this.cmdText += `> ${this.cmd}\\n`\n let parsed = this.cmd.replace(/^\\s+/, '').split(/\\s+/)\n\n if(parsed[0]){\n let query = parsed[0].toLowerCase()\n if(cmds[query]){\n cmds[query](this, parsed.slice(1), mrp, db)\n }\n else {\n this.cmdText += `Command '${query}' not found. Type 'help' for a manual.`\n }\n }\n\n this.cmd = ''\n }",
"function _sanitize(value) {\n\t\t\treturn (\"\" + value).replace(/[^a-zA-Z0-9_]/g, \"\").replace(/^_+/, \"\");\n\t\t}",
"function stripString(v) {\r\n\tuserInput.isQuestion = v.includes('?');\r\n\tvar pless = v.replace(/[.,\\/#!?$%\\^&\\*;:{}=\\-_`~()]/g,\"\");\r\n\tvar fs = pless.replace(/\\s{2,}/g,\" \");\r\n\tfs = fs.toLowerCase();\r\n\tfs = fs.trim();\r\n\treturn fs;\r\n}",
"function invalidCommand(cmd) {\n\t\tconsole.log('Invalid Command', cmd);\n\t\tswitch(Math.floor(Math.random() * 4) + 1) {\n\t\t\tcase 1:\n\t\t\t\toutput.before(\"I don't know the word \\\"\"+cmd+\"\\\".<br />\");\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\toutput.before(\"We're not going down that road again!<br /><br />\");\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\toutput.before(\"What a concept!<br /><br />\");\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\toutput.before(\"Sorry, my memory is poor. Please give a direction.<br /><br />\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\toutput.before(\"I'm not sure i get it!.<br /><br />\");\n\t\t}\n\t\tscrollDown();\n\t}",
"function transrateCommand(command){\n\tvar array_tmp = command.split(\"、\");\t\n\tvar str_tmp = \"\";\n\tswitch(array_tmp[0]){\n\t\t\tcase \"■背景\":\n\t\t\t\tstr_tmp = \"bg\";\n\t\t\tbreak;\n\t\t\n\t\t\tcase \"■タイトル\":\n\t\t\t\tstr_tmp = \"title\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■キャラ\":\n\t\t\t\tstr_tmp = \"char\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■キャラ消し\":\n\t\t\t\tstr_tmp = \"rm\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■音楽\":\n\t\t\t\tstr_tmp = \"music\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■音楽ストップ\":\n\t\t\t\tstr_tmp = \"musicstop\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■ジャンプ\":\n\t\t\t\tstr_tmp = \"goto\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■フラグセット\":\n\t\t\t\tstr_tmp = \"flagset\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■フラグ計算\":\n\t\t\t\tstr_tmp = \"flagcal\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■もし\":\n\t\t\t\tstr_tmp = \"if\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■選択肢\":\n\t\t\t\tstr_tmp = \"select\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■ウェイト\":\n\t\t\t\tstr_tmp = \"wait\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■SE\":\n\t\t\t\tstr_tmp = \"se\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■シェイク\":\n\t\t\t\tstr_tmp = \"shake\";\n\t\t\tbreak;\n\t\t\tcase \"■キャラシェイク\":\n\t\t\t\tstr_tmp = \"charshake\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■#\":\n\t\t\t\tstr_tmp = \"#\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"//\":\n\t\t\t\tstr_tmp = \"//\";\n\t\t\tbreak;\n\t\t}\n\n\t\t//もし置き換えが発生していたら変換\n\t\tif(str_tmp != \"\"){\n\t\t\tcommand = command.replace(/、/g, \" \");\n\t\t\tcommand = command.replace(array_tmp[0], str_tmp);\n\t\t}\n\t\treturn command;\n}",
"_validateCommandArguments() {\n const validatedCommandList = _map(this.commandList, (command) => {\n if (typeof command === 'undefined') {\n return null;\n }\n\n const errorMessage = command.validateArgs();\n\n if (errorMessage) {\n // we only return here so all the errors can be thrown at once\n // from within the calling method\n return errorMessage;\n }\n\n command.parseArgs();\n });\n\n return _compact(validatedCommandList);\n }",
"_normalizeCommandKeys() {\n // Normalize all command keys to be lowercase\n for (const [key, value] of this.Commands.entries()) {\n const lowercaseKey = key.toLowerCase();\n if (key !== lowercaseKey) {\n logger.info(`Switching ${key} command to lowercase ${lowercaseKey}`);\n this.Commands.set(lowercaseKey, value);\n this.Commands.delete(key);\n }\n }\n }",
"function handleCommand(cmd,argu,id) {\r\n words = argu.split(\" \");\r\n switch(cmd.toLowerCase()) {\r\n case \"yell\":\r\n case \"say\": respond(argu); break; \r\n case \"kick\": kick(id,\"Requested.\"); break;\r\n case \"ban\": ban(id,\"Requested\", argu[1]);\r\n case \"member\": member(id); break;\r\n case \"guest\": guest(id); break;\r\n case \"mod\": mod(id); break;\r\n }\r\n}",
"function cleanInput(data) {\n return data.toString().replace(/(\\r\\n|\\n|\\r)/gm, \"\");\n }",
"_validateAndParseCommandArguments() {\n const validationErrors = this._validateCommandArguments();\n\n if (validationErrors.length > 0) {\n _forEach(validationErrors, (error) => {\n throw error;\n });\n }\n }",
"function printCommand(cmd) {\r\n\r\n\t// Get the command to show\r\n\tvar command = cmd || submit.value;\r\n\r\n\t// Pull from the global namespace\r\n\tterminal.innerHTML += Filesystem.user + '@' + Filesystem.host + ':' + Filesystem.path + '$ ' + command + '\\n';\r\n\r\n}",
"function sanitize(text) {\n try {\n // Si no se encuentra undefined\n if (text !== undefined && typeof text === \"string\") {\n return text.replace(/'/g, \"''\");\n }\n }\n catch (err) {\n console.error(`(sanitize): error (${err.stack})`);\n }\n return text;\n}",
"function parseCommand(message) {\n const regexp = new RegExp(`^[${Config.allowedCommandPrefixes.join('')}](\\\\w+)\\\\s*((?:\\\\s*[\\\\w-]+)*)`, 'i');\n const match = message.match(regexp);\n let parsedCommand = null;\n if (match !== null) {\n parsedCommand = {\n command: match[1],\n arguments: match[2].replace(/ +/g, ' ').split(' ')\n };\n }\n return parsedCommand;\n}",
"function _sanitize( raw, clean ){\n // error & warning messages\n const messages = { errors: [], warnings: [] };\n\n if (clean.hasOwnProperty('parsed_text') && iso3166.is2(_.toUpper(clean.parsed_text.country))) {\n clean.parsed_text.country = iso3166.to3(_.toUpper(clean.parsed_text.country));\n }\n\n return messages;\n}",
"function usageString(cmd, style) {\n var com = COMMANDS[cmd];\n var usage = (style ? tt(cmd,'cmd') : cmd)+\" \";\n $.each(com.args, function(i,arg) {\n usage += \"[\"+arg.n+\"] \";\n });\n return usage;\n}",
"updateCommandInput() {\n const v = this.range;\n const nextPosition = this.nextPosition.value; // will be \"undefined\" in 2d.. defines behaviour of how next positions are computed\n const robots = [...canvasScript.robots].map(([label, {position: {x}, data: {faulty, localPosition: {y}}}]) => ({\n label,\n faulty,\n x: x - canvasScript.MIN_X,\n y: canvasScript.is2d() ? y : undefined,\n }));\n const command = {v, nextPosition, robots};\n this.commandInput.value = JSON.stringify(command, null, '\\t');\n\n // we know the command is good, no need to `parseCommandValue` it...\n // but we need to make sure it has at least 2 robots for it to be 100% valid\n if (robots.length < 2) {\n this.goodCommandIcon.classList.remove(\"show\");\n this.badCommandIcon.classList.add(\"show\");\n this.saveButton.disabled = true;\n } else {\n this.goodCommandIcon.classList.add(\"show\");\n this.badCommandIcon.classList.remove(\"show\");\n this.saveButton.disabled = false;\n }\n\n }",
"scrub(secret, string) { return scrub(secret, string); }",
"function getCmd()\n{\n\tvar abort = false; // Indicates whether to stop the processing.\n\t// Whenever a new command is input, the error box is cleared in preparation.\n\tclearError();\n\t// First, the text is retrieved from the player action box.\n\tvar playerInput = document.getElementById(\"actionbox\").value;\n\t// Next, the text is capitalized and split into multiple parts, based on spaces.\n\tvar inputArray = playerInput.toUpperCase().split(' ');\n\t// Once finished, we clean out the field.\n\tdocument.getElementById(\"actionbox\").value = \"\";\n\t// Right now, what we care about is what's in the first part; namely, whether it's a valid command or the beginning of one.\n\t// The following if/else chain describes all valid commands and handles them.\n\t// MOVE: This command can be any valid directional input (\"W\", \"NW\", \"N\", \"NE\", \"E\", \"SE\", \"S\", \"SW\", \"IN\", \"OUT\", \"UP\", and \"DOWN\"). It will need to be the only command.\n\tif ((inputArray[0] == \"W\") || (inputArray[0] == \"NW\") || (inputArray[0] == \"N\") || (inputArray[0] == \"NE\") || (inputArray[0] == \"E\") || (inputArray[0] == \"SE\")\n\t\t\t|| (inputArray[0] == \"S\") || (inputArray[0] == \"SW\")|| (inputArray[0] == \"IN\") || (inputArray[0] == \"OUT\") || (inputArray[0] == \"UP\") || (inputArray[0] == \"DOWN\"))\n\t{\n\t\t// If any extraneous commands were inserted, the player will be warned; otherwise, the function executes.\n\t\tif (inputArray.length == 1)\t{ cmdMove(inputArray[0]); }\n\t\t// If that direction's invalid, print an error.\n\t\telse { printError(\"Only input the direction in which you want to move.\"); }\n\t// LOOK: You can LOOK at a thing (to see it instead of the room) or LOOK with no other command (to look back at the room).\n\t} else if (inputArray[0] == \"LOOK\") {\n\t\t// Delete the first input.\n\t\tinputArray.splice(0,1);\n\t\t// If the form 'LOOK AT' was used, that's identical to 'LOOK'.\n\t\tif (inputArray[0] == \"AT\") { inputArray.splice(0,1); }\n\t\t// Then fuse the array back into a string, getting the total input of what the player wanted to look at.\n\t\tvar lookObject = inputArray.join(' ');\n\t\t// Activate the 'look' command with the thing being looked at as its input.\n\t\tcmdLook(lookObject);\n\t// GET: You can GET certain things, allowing you to place them into your INVENTORY. Synonymous with TAKE.\n\t} else if ((inputArray[0] == \"GET\") || (inputArray[0] == \"TAKE\")) {\n\t\t// Delete the first input.\n\t\tinputArray.splice(0,1);\n\t\t// The form \"GET THE\" or \"TAKE THE\" is identical to \"GET\".\n\t\tif (inputArray[0] == \"THE\") { inputArray.splice(0,1); }\n\t\t// Then fuse the array back into a string, getting the total input of what the player wanted to get.\n\t\tvar getObject = inputArray.join(' ');\n\t\t// Activate the 'get' command with the thing to take as its input.\n\t\tcmdGet(getObject);\n\t// USE: The most versatile command, this allows you to USE an item and activate its own unique function.\n\t} else if (inputArray[0] == \"USE\") {\n\t\t// Delete the first input.\n\t\tinputArray.splice(0,1);\n\t\t// The form \"USE THE\" is identical to \"USE\".\n\t\tif (inputArray[0] == \"THE\") { inputArray.splice(0,1); }\n\t\t// USE has two special forms: one that uses a single object and one that uses two. These can be differentiated by the presence of \"ON\" or \"WITH\".\n\t\tfor (var key in inputArray)\n\t\t{\n\t\t\t// If the key belongs to the array and not the prototype:\n\t\t\tif (inputArray.hasOwnProperty(key))\n\t\t\t{\n\t\t\t\t// If the key is one of the special terms we're looking for:\n\t\t\t\tif ((inputArray[key] == \"ON\") || (inputArray[key] == \"WITH\"))\n\t\t\t\t{\n\t\t\t\t\t// If the key has been located, splice the array around the phrase (which will then be removed) and join both arrays.\n\t\t\t\t\tvar useTargetOne = inputArray.splice(0,key).join(' ');\n\t\t\t\t\tinputArray.splice(0,1);\n\t\t\t\t\tvar useTargetTwo = inputArray.join(' ');\n\t\t\t\t\t// Call the two-target USE command.\n\t\t\t\t\tcmdUseTwo(useTargetOne,useTargetTwo);\n\t\t\t\t\tabort = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// If we couldn't find either of the USE-splitting keywords, call the command as a regular USE.\n\t\tif (!abort)\n\t\t{\n\t\t\tvar useTarget = inputArray.join(' ');\n\t\t\tcmdUse(useTarget);\n\t\t}\n\t// ITEMS: Just lets you look at what's currently in your inventory.\n\t} else if ((inputArray[0] == \"ITEMS\") || (inputArray[0] == \"INVENTORY\")) {\n\t\tlookAtInventory();\n\t// TALK: Allows you to try and strike up conversations with the locals.\n\t} else if (inputArray[0] == \"TALK\") {\n\t\t// Delete the first input.\n\t\tinputArray.splice(0,1);\n\t\t// The form \"TALK TO\" is identical to \"TALK\".\n\t\tif (inputArray[0] == \"TO\") { inputArray.splice(0,1); }\n\t\t// The form \"TALK THE\" is identical to \"TALK\". (Mostly relevant for \"TALK TO THE\".)\n\t\tif (inputArray[0] == \"THE\") { inputArray.splice(0,1); }\n\t\t// Fuse the array back into a string, getting the total input of what the player wanted to get.\n\t\tvar talkObject = inputArray.join(' ');\n\t\t// Activate the 'talk' command with the thing to talk to as its input.\n\t\tcmdTalk(talkObject);\t\n\t// HELP: This just shows you the list of commands again.\n\t} else if (inputArray[0] == \"HELP\") {\n\t\tlookAtHelp();\n\t} else {\n\t\t// Finally; if no valid command was input, say as much.\n\t\tprintError(\"That's not a valid command.\");\t\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set a mood config | function setConfigForPattern(patternName, configName, configVal, cb) {
ion.setMoodConfig(patternName, configName, configVal, function(err) {
if (!err) {
if (typeof configVal !== 'undefined')
console.log('set ' + configName + ' to ' + configVal + ' for mood ' + patternName);
else
console.log('set ' + configName + ' for mood ' + patternName);
if (cb)
cb();
}
});
} | [
"function setCurrentMood(newMood)\n{\n currentMood = newMood;\n // change the picture representing the user's current mood\n document.getElementById(\"mood-image-main\").href = moodNameToFilename(moodEnumToName(currentMood));\n // send the mood, heart rate, and steps to the server\n sendMoodUpdate(newMood); \n}",
"$set (path, value) {\n _.set(this._config, path, value)\n return this\n }",
"set_mood_check(value) {\n this.mood_check = value;\n return this;\n }",
"function setMouth(state) {\n TweenMax.set([mBigSmile, mSmile, mOoh,mSad,mNormal], {visibility:'hidden'});\n TweenMax.set(state, {visibility:'visible'});\n mCurrentState=state;\n\n}",
"function config() {\n\toutlet(0, 'host', addr_broadcast);\n\toutlet(0, 'port', iotport);\n\toutlet(0, '/config');\n}",
"function privateSetConfig( user_config ){\n\t\t/*\n\t\t\tIf Amplitude is not in dynamic mode, we determine what the \n\t\t\tstart song should be. Dynamic mode doesn't have any songs on \n\t\t\tconfig because the user will be sending them to Amplitude \n\t\t\tdynamically.\n\t\t*/\n\t\tif( !config.dynamic_mode ){\n\t\t\t/*\n\t\t\t\tIf the user provides a starting song index then we set\n\t\t\t\tthe active song information to the song at that index.\n\t\t\t*/\n\t\t\tif( user_config.start_song != undefined ){\n\t\t\t\tprivateSetActiveSongInformation( user_config.start_song, false );\n\t\t\t\t/*\n\t\t\t\t\tTODO: REMOVE Sets the user defined index.\n\t\t\t\t*/\n\t\t\t\tconfig.active_index = user_config.start_song;\n\t\t\t}else{\n\t\t\t\tprivateSetActiveSongInformation( 0, false );\n\n\t\t\t\t/*\n\t\t\t\t\tTODO: REMOVE Sets the active index to the first song.\n\t\t\t\t*/\n\t\t\t\tconfig.active_index = 0;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tIf live is not defined, assume it is false. The reason for\n\t\t\tthis definition is if we play/pause we disconnect\n\t\t\tand re-connect to the stream so we don't fill up our cache\n\t\t\twith unused audio and we aren't playing outdated audio upon\n\t\t\tresume.\n\t\t*/\n\t\tif( config.active_metadata.live == undefined ){\n\t\t\tconfig.active_metadata.live = false;\n\t\t}\n\n\t\t/*\n\t\t\tIf the user wants the song to be pre-loaded for instant\n\t\t\tplayback, they set it to true. By default it's set to just\n\t\t\tload the metadata.\n\t\t*/\n\t\tconfig.active_song.preload = ( user_config.preload != undefined ? user_config.preload : \"metadata\" );\n\t\t\n\t\t/*\n\t\t\tInitializes the user defined callbacks. This should be a JSON\n\t\t\tobject that contains a key->value store of the callback name\n\t\t\tand the name of the function the user needs to call.\n\t\t*/\n\t\tconfig.callbacks = ( user_config.callbacks != undefined ? user_config.callbacks : {} );\n\n\t\t/*\n\t\t\tThe user can define a starting volume in a range of 0-1 with\n\t\t\t0 being muted and 1 being the loudest. After the config is set\n\t\t\tAmplitude sets the active song's volume to the volume defined\n\t\t\tby the user.\n\t\t*/\n\t\tconfig.volume = ( user_config.volume != undefined ? user_config.volume : .5 );\n\t\tconfig.active_song.volume = config.volume;\n\n\t\t/*\n\t\t\tThe user can set the volume increment and decrement values between 1 and 100\n\t\t\tfor when the volume up or down button is pressed. The default is an increase\n\t\t\tor decrease of 5.\n\t\t*/\n\t\tconfig.volume_increment = ( user_config.volume_increment != undefined ? user_config.volume_increment : 5 );\n\t\tconfig.volume_decrement = ( user_config.volume_decrement != undefined ? user_config.volume_decrement : 5 );\n\n\t\t/*\n\t\t\tThe user can turn off Amplitude handling the song elements (putting the meta data into\n\t\t\tcertain fields when the song is playing or changed). This would be if the user wanted\n\t\t\tto hard code this information which would probably be most popular in single song \n\t\t\tinstances.\n\t\t*/\n\t\tconfig.handle_song_elements = ( user_config.handle_song_elements != undefined ? user_config.handle_song_elements : true );\n\n\t\t/*\n\t\t\tIf the user defines default album art, this image will display if the active\n\t\t\tsong doesn't have album art defined.\n\t\t*/\n\t\tconfig.default_album_art = ( user_config.default_album_art != undefined ? user_config.default_album_art : '' );\t\t\n\t\t\n\t\t/*\n\t\t\tThe user can define a visualization backup to use if they are using\n\t\t\tvisualizations (song visualizations not song time visualizations) and the\n\t\t\tbrowser doesn't support it. This can be \"nothing\" meaning that the\n\t\t\tvisualization element is removed otherwise it can be the album art\n\t\t\tof the song being played.\n\t\t*/\n\t\tconfig.visualization_backup = ( user_config.visualization_backup != undefined ? user_config.visualization_backup : 'nothing' );\n\n\t\t/*\n\t\t\tSets initialized to true, so the user can't re-initialize\n\t\t\tand mess everything up.\n\t\t*/\n\t\tconfig.initialized = true;\n\n\t\t/*\n\t\t\tSince the user can define a start volume, we want our volume\n\t\t\tsliders to sync with the user defined start value.\n\t\t*/\n\t\tprivateSyncVolumeSliders();\n\n\t\t/*\n\t\t\tSets up the player if the browser doesn't have the audio context\n\t\t*/\n\t\tprivateSyncNoAudioContext();\n\n\t\t/*\n\t\t\tSet all of the current time elements to 0:00 upon initialization\n\t\t*/\n\t\tprivateSyncCurrentTimes();\n\n\t\t/*\n\t\t\tSyncs all of the song status sliders so the user can't set the\n\t\t\tHTML 5 range element to be something invalid on load like half\n\t\t\tway through the song by default.\n\t\t*/\n\t\tprivateResetSongStatusSliders();\n\n\t\tprivateCheckSongVisualization();\n\n\t\t/*\n\t\t\tInitialize the visual elements for the song if the user\n\t\t\twants Amplitude to handle the changes. This is new \n\t\t\tcompared to previous versions where Amplitude automatically\n\t\t\thandled the song elements.\n\t\t*/\n\t\tif( config.handle_song_elements ){\n\t\t\tprivateDisplaySongMetadata();\n\t\t}\n\n\t\t/*\n\t\t\tRemoves any classes set by the user so any inconsistencies\n\t\t\twith start song and actual song are displayed correctly.\n\t\t*/\n\t\tprivateSyncVisualPlayingContainers();\n\n\t\t/*\n\t\t\tSets the active song container for the song that will be\n\t\t\tplayed. This adds a class to an element containing the\n\t\t\tvisual representation of the active song .\n\t\t*/\n\t\tprivateSetActiveContainer();\n\n\t\t/*\n\t\t\tSets the temporary user conifg back to empty. We are done\n\t\t\tusing it.\n\t\t*/\n\t\ttemp_user_config = {};\n\n\t\t/*\n\t\t\tRun after init callback\n\t\t*/\n\t\tprivateRunCallback(\"after_init\");\n\n\t\t/*\n\t\t\tIf the user turns on autoplay the song will play automatically.\n\t\t*/\n\t\tif( user_config.autoplay ){\n\t\t\t/*\n\t\t\t\tGets the attribute for song index so we can check if\n\t\t\t\tthere is a need to change the song. In some scenarios\n\t\t\t\tthere might be multiple play classes on the page. In that\n\t\t\t\tcase it is possible the user could click a different play\n\t\t\t\tclass and change the song.\n\t\t\t*/\n\t\t\tvar playing_song_index = config.start_song;\n\n\t\t\t/*\n\t\t\t\tWe set the new song if the user clicked a song with a different\n\t\t\t\tindex. If it's the same as what's playing then we don't set anything. \n\t\t\t\tIf it's different we reset all song sliders.\n\t\t\t*/\n\t\t\tif( privateCheckNewSong( playing_song_index ) ){\n\t\t\t\tprivateChangeSong( playing_song_index );\n\n\t\t\t\tprivateResetSongStatusSliders();\n\t\t\t}\n\n\t\t\t/*\n\t\t\t\tStart the visualizations for the song.\n\t\t\t*/\n\t\t\tprivateStartVisualization();\n\t\t\t\n\t\t\t/*\n\t\t\t\tIf there are any play pause buttons we need\n\t\t\t\tto sync them to playing for auto play.\n\t\t\t*/\n\t\t\tprivateChangePlayPauseState('playing');\n\n\t\t\t/*\n\t\t\t\tPlay the song through the core play function.\n\t\t\t*/\n\t\t\tprivatePlay();\n\t\t}\n\t}",
"function configure(parameters) {\n\t _merge(ToneDen.parameters, parameters);\n\t}",
"function setConfig (argv) {\n var configLookup = {}\n \n // expand defaults/aliases, in-case any happen to reference\n // the config.json file.\n applyDefaultsAndAliases(configLookup, aliases, defaults)\n \n Object.keys(flags.configs).forEach(function (configKey) {\n var configPath = argv[configKey] || configLookup[configKey]\n if (configPath) {\n try {\n var config = require(path.resolve(process.cwd(), configPath))\n \n Object.keys(config).forEach(function (key) {\n // setting arguments via CLI takes precedence over\n // values within the config file.\n if (argv[key] === undefined) {\n delete argv[key]\n setArg(key, config[key])\n }\n })\n } catch (ex) {\n if (argv[configKey]) error = Error('invalid json config file: ' + configPath)\n }\n }\n })\n }",
"function setMode(mode){\n\t\tif(mode !== undefined){\n\t\t\tcm.setOption('mode', mode);\n\t\t\tCodeMirror.autoLoadMode(cm, mode);\n\t\t\t/*var script = 'lib/codemirror/mode/'+mode+'/'+mode+'.js';\n\n\t\t\t$.getScript(script, function(data, success) {\n\t\t\t\tif(success) cm.setOption('mode', mode);\n\t\t\t\telse cm.setOption('mode', 'clike');\n\t\t\t});*/\n\t\t}else{\n\t\t\tcm.setOption('mode', 'clike');\n\t\t}\n\t}",
"function setValue(param, value) {\n if (lmsConnected) {\n DEBUG.LOG(`setting ${param} to ${value}`);\n scorm.set(param, value);\n scorm.save();\n } else {\n DEBUG.WARN('LMS NOT CONNECTED');\n }\n}",
"set_mood_induction(value) {\n this.mood_induction = value;\n return this;\n }",
"function ServerBehavior_setParameter(name, value)\n{\n if (this.bInEditMode)\n {\n this.applyParameters[name] = value;\n }\n else\n {\n this.parameters[name] = value; \n }\n}",
"function writeConfig () {\n self._repo.config.set(config, (err) => {\n if (err) return callback(err)\n\n addDefaultAssets()\n })\n }",
"function config(path, val){\n if(!path) return options; /**@todo: probably a deep copy */\n if(!angoose.initialized && typeof(path) == 'string') throw \"Cannot call config(\" + path+\") before angoose is intialized\";\n //if(angoose.initialized && typeof(conf) == 'object') throw \"Cannot config Angoose after startup\";\n \n if(typeof (path) === 'string'){\n if(val === undefined)\n return toolbox.getter(options, path);\n toolbox.setter(options, path, val);\n }\n \n if(typeof(path) === 'object'){\n // deep merge\n options = toolbox.merge(options, path);\n\n }\n}",
"function setGlossary(match, defin, phrase) {\n matches = match;\n definitions = defin;\n phrases = phrase;\n}",
"function setConfigOption(key, value){\n chrome.storage.sync.get(null, (result) =>{\n let config = result[\"config\"];\n if(!config)\n config = {};\n if(value)\n config[key] = value;\n else\n delete config[key];\n chrome.storage.sync.set({config: config});\n });\n}",
"function assignMole() {\n\tvar circle = circles[Math.floor(Math.random() * circles.length)];\n\tcircle.style.backgroundImage = \"url(mole.png)\";\n\tcircle.hasMole = true;\n}",
"configuring() {\n // creates .yo-rc config file\n this.config.save()\n }",
"function configure(){\n Webcam.set({\n width: 320,\n height: 240,\n image_format: 'jpeg',\n jpeg_quality: 90\n });\n Webcam.attach( '#my_camera' );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
concatinate the items and there products into JSONobject | toJSON() {
let items = _items.get(this);
let JSONItems = [];
for( let i = 0; i < items.length ; i++ ) {
console.log(items[i].getCount());
JSONItems.push({
count: items[i].getCount(),
name: items[i].getProduct().getName(),
id: items[i].getProduct().getId(),
price: items[i].getProduct().getPrice(),
image: items[i].getProduct().getImage()
});
}
return { JSONItems };
} | [
"function getProducts() {\n $.ajax({\n url: \"files/productlist.json\",\n dataType: 'json',\n success: function(data) {\n var product =\"\";\n\n $.each(data, function(key, value) { // Execute for each set of data\n product = Object.values(value);\n productlist.push(product);\n }); \n },\n error(xhr, status, error) { // Function for error message and error handling\n console.log(error);\n }\n })\n }",
"function AjoutProduit() {\n\n let product = {\n \"name\": document.getElementById(\"addName\").value,\n \"type\": document.getElementById(\"AddSelectType\").value,\n \"description\": document.getElementById(\"addDesc\").value,\n \"price\": document.getElementById(\"addPrice\").value,\n \"quantity\": document.getElementById(\"addQts\").value,\n \"traduction\": document.getElementById(\"AddSelectType\").value\n };\n\n jsonDatas.push(product);\n console.log(jsonDatas);\n allProducts(jsonDatas);\n\n alert(produit.name + \" \" + produit.type + \" \" + produit.traduction);\n\n}",
"async loadFromJSON(JSONs) {\n if(JSONs) {\n let JSONObj = JSONs.JSONItems\n for (let i = 0; i < JSONObj.length; i++) {\n let product = new Product(JSONObj[i].id, JSONObj[i].name, JSONObj[i].price, JSONObj[i].image);\n for (let j = 0; j < JSONObj[i].count; j++) {\n await this.addItem(product);\n }\n }\n }\n }",
"function convertItemDataForOutput(item){\n\t\t\n\t\tvar output = {\n\t\t\t\tindex: item.index,\n\t\t\t\ttitle: item.title,\n\t\t\t\tdescription: item.description,\n\t\t\t\turlImage: item.urlImage,\n\t\t\t\turlThumb: item.urlThumb\n\t\t\t};\n\t\t\t\n\t\t\t//add aditional variables to the output\n\t\t\tvar addData = item.objThumbImage.data();\n\t\t\t\n\t\t\tfor(var key in addData){\n\t\t\t\tswitch(key){\n\t\t\t\t\tcase \"image\":\n\t\t\t\t\tcase \"description\":\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\toutput[key] = addData[key];\n\t\t\t}\n\t\t\t\n\t\t\treturn(output);\n\t}",
"function mergeItem(tmpList, body) {\n item.resetOutput();\n let output = item.getOutput();\n for (let key in tmpList.data[0].Inventory.items) {\n if (tmpList.data[0].Inventory.items.hasOwnProperty(key)) {\n if (tmpList.data[0].Inventory.items[key]._id && tmpList.data[0].Inventory.items[key]._id === body.with) {\n for (let key2 in tmpList.data[0].Inventory.items) {\n if (tmpList.data[0].Inventory.items[key2]._id && tmpList.data[0].Inventory.items[key2]._id === body.item) {\n let stackItem0 = 1;\n let stackItem1 = 1;\n if (typeof tmpList.data[0].Inventory.items[key].upd !== \"undefined\")\n stackItem0 = tmpList.data[0].Inventory.items[key].upd.StackObjectsCount;\n if (typeof tmpList.data[0].Inventory.items[key2].upd !== \"undefined\")\n stackItem1 = tmpList.data[0].Inventory.items[key2].upd.StackObjectsCount;\n\n if (stackItem0 === 1)\n Object.assign(tmpList.data[0].Inventory.items[key], {\"upd\": {\"StackObjectsCount\": 1}});\n\n tmpList.data[0].Inventory.items[key].upd.StackObjectsCount = stackItem0 + stackItem1;\n\n output.data.items.del.push({\"_id\": tmpList.data[0].Inventory.items[key2]._id});\n tmpList.data[0].Inventory.items.splice(key2, 1);\n\n profile.setCharacterData(tmpList);\n return output;\n }\n }\n }\n }\n }\n\n return \"\";\n}",
"addProducts() {\n document.querySelector('#product-list').innerHTML = '';\n document.querySelector('#update').innerHTML = '';\n Product.all.forEach(\n product => (document.querySelector('#product-list').innerHTML += product.renderProduct())\n );\n }",
"findProducts() {\n var self = this;\n var products = [];\n\n self.initShoppingCart();\n self.req.session.shoppingCart.forEach(function(elem) {\n var product = { productId : elem.productId, quantity : elem.quantity };\n products.push(product);\n });\n\n return self.res.status(200).json(products);\n }",
"function createJSON(items) {\n return {\n readings: items.map(element => {\n return {point: element, consumption: Math.floor(Math.random() * 5)}\n })\n }\n}",
"function inventoryBuckets(env, fc, productList, options) {\n return new Promise((resolve, reject) => {\n /*\n {\n \"productId\": product.id,\n \"mapping\" : {},\n \"quantity\" : product.quantity * deal.quantity,\n \"wmf\": deal.defaultWhId,\n \"dealId\": deal._id\n } \n */\n var config = _getConfig(env);\n\n var skuList = [];\n\n productList.map(p => {\n if (p.mapping && p.mapping.sku) {\n skuList.push(p.mapping.sku);\n }\n });\n\n var walmartProductPromise = new Promise((resolve, reject) => {\n Promise.all(productList.map(p => {\n return new Promise((_resolve, _reject) => {\n\n var url = `${config.basePath}/Product/Information/${config.MerchantId}/${p.mapping.productId}`;\n\n _fire(config, url, 'GET', null).then(result => {\n _resolve(result);\n }).catch(e => {\n _reject(e);\n });\n\n });\n })).then(walmartProducts => {\n if (walmartProducts && walmartProducts.length) {\n resolve(walmartProducts);\n } else {\n reject(new Error(`Could not get walmart products....`));\n }\n }).catch(e => reject(e));\n });\n\n\n var volumetricPromise = new Promise((resolve, reject) => {\n Promise.all(productList.map(p => {\n return new Promise((_resolve, _reject) => {\n\n const url = `${config.frontApi}/VolumetricPricing/${config.MerchantId}`;\n\n const options = {\n query: {\n productid: productId,\n storeId: fc.partner.locationId\n }\n }\n\n\n _fire(config, url, 'GET', options).then(result => {\n _resolve(result);\n }).catch(e => {\n _resolve();\n });\n //Here add productid to the response;\n });\n })).then(volumes => {\n resolve();\n }).catch(e => reject(e));\n });\n\n Promise.all([walmartProductPromise, volumetricPromise]).then(result => {\n\n var walmartProductList = result[0];\n var volumeList = result[1];\n var sortedGroup = {};\n\n if (!walmartProductList || !walmartProductList.length) {\n reject(new Error(`Could not get walmart product list.....`));\n return;\n }\n //Convert to bucket format;\n productList.map(p => {\n\n // var walmartProduct = _.find(walmartProductList, { \"Product.ProductId\": parseInt(p.mapping.productId) });\n\n var walmartProduct = _.find(walmartProductList, (pr => {\n if (pr.Product.ProductId === parseInt(p.mapping.productId)) {\n return true;\n }\n }));\n\n if (walmartProduct) {\n\n if (!sortedGroup[p.whId]) {\n\n sortedGroup[p.whId] = [];\n\n sortedGroup[p.whId].push({\n \"productId\": p.productId,\n \"totalQty\": 0,\n \"snapShots\": [{\n whId: p.whId,\n productId: p.productId,\n mappedProductId: walmartProduct.Product.ProductId,\n mrp: walmartProduct.Product.MRP,\n transferPrice: walmartProduct.Product.WebPrice,\n stock: parseInt(walmartProduct.Product.Inventory),\n onHold: 0,\n key: walmartProduct.Product.MRP,\n snapShotIds: []\n }],\n \"buckets\": {},\n \"bucketKeys\": []\n });\n\n } else {\n //if wmf key exists , then check if in that wmf this productId exists; If not then add;\n var exisiting = _.find(sortedGroup[p.whId], { productId: p.productId, whId: p.whId });\n\n if (!exisiting) {\n sortedGroup[p.whId].push({\n \"productId\": p.productId,\n \"totalQty\": 0,\n \"snapShots\": [{\n whId: p.whId,\n productId: p.productId,\n mappedProductId: walmartProduct.Product.ProductId,\n mrp: walmartProduct.Product.MRP,\n transferPrice: walmartProduct.Product.WebPrice,\n stock: parseInt(walmartProduct.Product.Inventory),\n onHold: 0,\n key: walmartProduct.Product.MRP,\n snapShotIds: []\n }],\n \"buckets\": {},\n \"bucketKeys\": []\n });\n }\n\n }\n\n }\n });\n\n Object.keys(sortedGroup).map(whId => {\n var whGroup = sortedGroup[whId]; // List of product snapshots;\n whGroup.map(product => {\n product.totalQty = _.sumBy(product.snapShots, \"stock\");\n var group = _.groupBy(product.snapShots, \"key\");\n product.buckets = group;\n Object.keys(product.buckets).map(mrpKey => {\n var _list = product.buckets[mrpKey];\n var count = _.sumBy(_list, \"stock\");\n product.buckets[mrpKey] = {\n \"whId\": _list[0].whId,\n \"productId\": _list[0].productId,\n \"mappedProductId\": _list[0].mappedProductId,\n \"mrp\": _list[0].mrp,\n \"transferPrice\": _list[0].transferPrice,\n \"stock\": count,\n \"onHold\": 0,\n \"snapShotIds\": []\n }\n })\n /* product.buckets[product.key] = {\n \"whId\": _list[0].whId,\n \"productId\": _list[0].productId,\n \"mappedProductId\": walmartProduct.Product.ProductId,\n \"mrp\": _list[0].mrp,\n \"transferPrice\": _list[0].WebPrice,\n \"stock\": count,\n \"onHold\": 0,\n \"snapShotIds\": []\n } */\n product.bucketKeys = Object.keys(group);\n delete product.snapShots;\n });\n\n })\n\n if (options && options.bucketsOnly) {\n resolve({ buckets: sortedGroup });\n } else {\n var products = walmartProductList.map(p => p.Product);\n resolve({ buckets: sortedGroup, productList: products });\n }\n\n }).catch(e => reject(e));\n\n // Sample response format to send;\n /* var mock = {\n \"WMF3\": [\n {\n productId: \"PR10964\",\n totalQty: 10,\n snapShots: [],\n buckets: {\n \"10_Walmart Offer\": {\n whId: \"WMF3\",\n productId: \"PR10964\",\n mrp: 60,\n transferPrice: _list[0].WebPrice,\n stock: 10,\n onHold: 0,\n snapShotIds: []\n }\n },\n bucketKeys: [\"10_Walmart Offer\"]\n }\n ]\n }; */\n });\n}",
"function insertItemToJSON(item, feedName, json) {\n json.forEach(function (e) {\n if (e['feed-name'] == feedName) {\n if (e['items'] == undefined) {\n e['items'] = [ item ];\n }\n else {\n e['items'].push(item);\n }\n }\n });\n}",
"function constructData(data){\r\n const constructedData=[];\r\n data.map(function(i){\r\n constructedData.push({\r\n 'Item_Number': i.gsx$itemnumber.$t,\r\n 'Product_Name': i.gsx$productname.$t\r\n });\r\n });\r\n return constructedData;\r\n }",
"function listProductOrder(data) {\n const tab = [\"imageUrl\",\"name\",\"lenses\",\"price\"];\n var cost = 0;\n for (let i = 0 ; i < data.products.length; i++) {\n createObject(listProductOrderTarget,\"tr\",listProductOrderProductTarget,null,0);\n const product = data.products[i];\n for (let j = 0 ; j < tab.length; j++) {\n for (let key in product) {\n if (key == tab[j]) {\n switch (key) {\n case \"imageUrl\":\n createObject(listProductOrderProductTarget,\"td\",imageProductResumTarget,\"<img src=\\\"\"+product[key]+\"\\\" alt=\\\"product view\\\">\",i);\n break;\n case \"name\":\n createObject(listProductOrderProductTarget,\"td\",nameProductResumTarget,product[key],i);\n break;\n case \"lenses\":\n createObject(listProductOrderProductTarget,\"td\",lensesProductResumTarget,\"Possibilités offertes: \"+ product[key],i);\n break;\n case \"price\":\n createObject(listProductOrderProductTarget,\"td\",priceProductResumTarget,product[key]/100+\"€\",i);\n cost += product[key]/100;\n break;\n }\n } \n } \n }\n }\n createObject(productOrderCostTarget,\"tr\",labelProductOrderCostTarget,\"<td>Coût total de la commande: </td><td>\"+cost+\" €</td>\" ,0);\n}",
"function loadArray() {\n connection.query(\"SELECT * FROM products\", function (err, res) {\n if (err) throw err;\n res.forEach(element => {\n var newProduct = element.item_id + \" | \" + element.product_name + \" | $\" + element.customer_price;\n productArr.push(newProduct);\n });\n });\n}",
"function getProducts(order, callback) {\n const date = moment(order.dataValues.createdAt).format('LLLL');\n order.date = date;\n\n const { items } = order.dataValues.cart;\n const productIds = Object.keys(items);\n\n models.Product.findAll({\n attributes: ['id', 'title'],\n where: { id: productIds }\n })\n .then(products => {\n let productsObject = {};\n products.forEach(product => {\n productsObject[product.id] = product.title;\n });\n order.items = generateArray(productsObject, items);\n callback();\n }) // END .then(products => {\n .catch(err => callback(err));\n} // END (order, callback) => {",
"static getSmallBusinessesItems(){\n fetch(this.itemsURL)\n .then(response => response.json())\n .then(json => {\n json.data.forEach(smallBusinessItem => {\n const newBizItem = new SmallBusinessItem({id: smallBusinessItem.id, ...smallBusinessItem.attributes})\n newBizItem.addSmallBizItemToDom()\n });\n })\n }",
"function addNewItem(product) {\n var item = orderItemType.createInstance();\n item.order = this;\n item.product = product;\n this.orderItems.push(item);\n return item;\n }",
"function getOrderedItems(listOrderedItems){\n\n for(let i = 0; i < listOrderedItems.length; i++){\n\n let cartItemTitle = listOrderedItems[i][0].name;\n let cartItemPrice =listOrderedItems[i][1].price;\n let cartItemQuantity = listOrderedItems[i][2].quantity;\n let cartItemImg = listOrderedItems[i][3].image;\n let cartItemInstruction = listOrderedItems[i][5].instruction;\n\n let options = [];\n for(let j = 0; j < listOrderedItems[i][4].options.length; j++){\n options.push(listOrderedItems[i][4].options[j]);\n }//end nested for\n \n displayOrderedItem(cartItemTitle,cartItemPrice,cartItemQuantity,cartItemImg,options,cartItemInstruction);\n }//end for\n\n displayTotalPrice();\n }",
"function mergeItems(){\n\tfor(var i = 0; i < invArray.length; i++){\n\t\tif(invArray[i].select){\n\t\t\tvar item1 = invArray[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor(var i = item1.invPos + 1; i < invArray.length; i++){\n\t\tif(invArray[i].select){\n\t\t\tvar item2 = invArray[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tcombine(item1, item2);\n}",
"function pusher() {\n //var obj = JSON_Obj.orders\n var resposta = [];\n obj.forEach(element => {\n resposta.push(element)\n });\n //for (var i in obj)\n \n //console.log(obj)\n //console.log(typeof resposta[7])\n console.log(resposta)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show the user the form to create a practice event when the practice tab is selected | function showPracticeFields() {
if(document.getElementById('nav_create_game').classList.contains('active')) {
document.getElementById('nav_create_practice').classList.add('active');
document.getElementById('nav_create_game').classList.remove('active');
document.getElementById('practice-other-form').style.display = 'block';
document.getElementById('game-create-form').style.display = 'none';
}
else if(document.getElementById('nav_create_practice').classList.contains('active')) {
return false;
}
else {
document.getElementById('nav_create_practice').classList.add('active');
document.getElementById('nav_create_other').classList.remove('active');
}
} | [
"function loadCreateSchedule() {\n document.getElementById('practice-other-form').style.display = 'none';\n}",
"function handleShowNewIdeaForm() {\n $('body').on(\"click\", \".js-show-new-idea-form-btn\", () => {\n displayNewIdeaForm($('.js-content'));\n });\n}",
"function changeLecturerContent(event, tab){\n document.getElementById('profile').style.display = 'none';\n if (tab == \"Profile\") {\n //TODO: Pass the current user to the function\n editUserInfo(\"lecturerContent\");\n\n } else if(tab == \"Student\"){\n \n } else if(tab == \"Evaluation\"){\n \n } else if(tab == \"Message\"){\n \n } else if(tab == \"References\"){\n\t\t\n\t\tdocument.getElementById('lecturerContent').innerHTML=template_references(); \n\t\n } else if(tab == \"Editing\"){\n \n } else if(tab == \"New\"){\n \n }\n}",
"function handleShowEditableIdeaForm() {\n $('body').on(\"click\", \".js-show-edit-idea-form-btn\", (event) => {\n const ideaID = $(event.currentTarget).data('id');\n const success = response => {\n displayEditableIdeaForm(response, ('.js-content'), false);\n }\n\n getIdeaDetails({\n jwToken: user,\n ideaID,\n onSuccess: success\n });\n });\n}",
"function showAddTopic(){\n // show form and set the form fields to null\n createForm.style.display = \"block\";\n document.getElementById(\"create-topic\").value = \"\";\n document.getElementById(\"create-description\").value = \"\";\n formType = \"addTopic\";\n}",
"function handleStartQuiz() {\n $('#startQuiz').on('click', function(event) {\n startNewQuiz();\n });\n}",
"showEditableAnswer(e){\n e.preventDefault();\n document.getElementById('editAnswerContent').style.display = \"inherit\";\n document.getElementById('answerContent').style.display = \"none\";\n document.getElementById('clickEdit').style.display = \"none\";\n document.getElementById('submitAnswer').style.display = \"initial\";\n document.getElementById('cancelAnswer').style.display = \"initial\";\n }",
"function createFormHandler(e) {\n e.preventDefault()\n// Add innerHTML apending to Brainstormer in this section\n const characterInput = document.querySelector(\"#user-edit-character\").value\n const setupInput = document.querySelector(\"#user-edit-setup\").value\n const twistInput = document.querySelector(\"#user-edit-twist\").value\n const genreInput = document.querySelector(\"#user-edit-genre_id\").value\n \n postIdea(characterInput, setupInput, twistInput, genreInput)\n }",
"showAddExerciseDialog()\n {\n this.addDialog.MaterialDialog.show();\n this.addExerciseName.focus();\n }",
"function onProceedClick() {\n setDisplayValue('q1');\n updateLastViewed('q1');\n showHideElements();\n}",
"function show(options)\n {\n //TODO fix directive\n var tabs = angular.element('.nav-tabs-app li:not(:last)');\n\n if (!options || !options.adapterId)\n {\n if (angular.isDefined(self.activateTTForm))\n {//Empty form validation by changing the team\n $scope.formActivateTT.$setPristine();\n }\n\n if ($rootScope.app.resources.role == 1 && !self.data.phoneNumbers.length)\n {\n $rootScope.notifier.error($rootScope.ui.options.noPhoneNumbers);\n }\n self.activateTTForm = true;\n tabs.addClass('ng-hide');\n }\n else\n {\n self.scenarios = {\n voicemailDetection: options[\"voicemail-detection-menu\"] || false,\n sms: options[\"sms-on-missed-call\"] || false,\n ringingTimeOut: options[\"ringing-timeout\"] || 20,\n useExternalId: options[\"useExternalId\"] || false,\n scenarioTemplates: options['test'] || []\n };\n self.activateTTForm = false;\n tabs.removeClass('ng-hide');\n //TODO fix this in a directive\n (! $rootScope.app.domainPermission.teamSelfManagement\n || $rootScope.app.resources.role > 1)\n ? angular.element('.scenarioTab').addClass('ng-hide')\n : angular.element('.scenarioTab').removeClass('ng-hide');\n }\n }",
"function editPage(OR, LoD, NoR, additional, firstName, lastName, courseKey) {\n\n // Rate My Professor additions\n $(additional).append(\"<span class=ls-label>★</span>\");\n $(additional).append(\"<span>\" + OR + \"</span>\");\n $(additional).append(\"<span class=ls-label>  LoD:</span>\");\n $(additional).append(\"<span>\" + LoD + \"</span>\");\n $(additional).append(\"<span class=ls-label>  #</span>\");\n $(additional).append(\"<span>\" + NoR + \"</span>\");\n\n //Add grade distribution button\n var button = document.createElement(\"a\");\n button.className = \"grade-button\";\n button.innerText = \"Grades!\";\n\n additional.appendChild(button);\n button.setAttribute(\"courseKey\", courseKey);\n\n // Parses instructor to match Berkeley Time API\n parsedName = lastName + \", \" + firstName.substring(0, 1);\n button.setAttribute(\"instructor\", parsedName.toUpperCase());\n\n // Handles popup events due to mouse hovering over the button\n button.addEventListener(\"mouseover\", showInfo(button, additional, firstName, lastName));\n button.addEventListener(\"mouseout\", removeInfo(button, additional));\n}",
"function openFeedbackForm(event) {\n var modal = document.getElementById('kfModal') || injectModal();\n modal.style.display = \"block\";\n document.getElementById(\"kfEmail\").focus();\n }",
"function openAbExhib() {\n document.getElementById(\"about__exhibition\").style.display = \"block\";\n document.getElementById(\"menuPopupBackg\").style.display = \"block\";\n}",
"function ShowSelectedFieldInputForm(field_title, field_type, field_id){\n \n}",
"function onOpen() {\n var ss = SpreadsheetApp.getActiveSpreadsheet(),\n menuItems = [{name: \"Show Form\", functionName: \"showForm\"}];\n ss.addMenu(\"Data Entry\", menuItems);\n}",
"function showCompanyForm(mode, callback) {\n\n }",
"function quizStartPageStartButton() {\n $('.js-main').on('click', '.js-start-page-submit', (evt) => {\n evt.preventDefault();\n STORE.quizStarted = true;\n render();\n });\n}",
"function addQuizForm() {\n $('main').find('fieldset').html(loadQuizQuestion)}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
========== ATTRIBUTES ========== auto_recovery_supported computed: true, optional: false, required: false | get autoRecoverySupported() {
return this.getBooleanAttribute('auto_recovery_supported');
} | [
"get hibernationSupported() {\n return this.getBooleanAttribute('hibernation_supported');\n }",
"get instanceStorageSupported() {\n return this.getBooleanAttribute('instance_storage_supported');\n }",
"visitManaged_standby_recovery(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"get efaSupported() {\n return this.getBooleanAttribute('efa_supported');\n }",
"function isForgeEnabled() {\n // TODO should return true if the service \"fabric8-forge\" is valid\n return true;\n }",
"get ebsEncryptionSupport() {\n return this.getStringAttribute('ebs_encryption_support');\n }",
"get ebsNvmeSupport() {\n return this.getStringAttribute('ebs_nvme_support');\n }",
"function notifyPasswordNotSupported () {\n console.warn('room passwords not supported');\n APP.UI.messageHandler.showError(\n \"dialog.warning\", \"dialog.passwordNotSupported\");\n}",
"function set_new_patron_defaults(prs) {\n if (!$scope.patron.passwd) {\n // passsword may originate from staged user.\n $scope.generate_password();\n }\n $scope.hold_notify_type.phone = true;\n $scope.hold_notify_type.email = true;\n $scope.hold_notify_type.sms = false;\n\n // staged users may be loaded w/ a profile.\n $scope.set_expire_date();\n\n if (prs.org_settings['ui.patron.default_ident_type']) {\n // $scope.patron needs this field to be an object\n var id = prs.org_settings['ui.patron.default_ident_type'];\n var ident_type = $scope.ident_types.filter(\n function(type) { return type.id() == id })[0];\n $scope.patron.ident_type = ident_type;\n }\n if (prs.org_settings['ui.patron.default_inet_access_level']) {\n // $scope.patron needs this field to be an object\n var id = prs.org_settings['ui.patron.default_inet_access_level'];\n var level = $scope.net_access_levels.filter(\n function(lvl) { return lvl.id() == id })[0];\n $scope.patron.net_access_level = level;\n }\n if (prs.org_settings['ui.patron.default_country']) {\n $scope.patron.addresses[0].country = \n prs.org_settings['ui.patron.default_country'];\n }\n }",
"function verifyExtraFieldsFromProduct() {\n if ($scope.device.product.extraFields) {\n\n }\n }",
"get rootVolumeEncryptionEnabled() {\n return this.getBooleanAttribute('root_volume_encryption_enabled');\n }",
"get userVolumeEncryptionEnabled() {\n return this.getBooleanAttribute('user_volume_encryption_enabled');\n }",
"get defaultDataSchema() {\n\t\treturn {\n\t\t\tprefix: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: this.client.config.prefix,\n\t\t\t\tmin: null,\n\t\t\t\tmax: 10,\n\t\t\t\tarray: this.client.config.prefix.constructor.name === 'Array',\n\t\t\t\tconfigurable: true,\n\t\t\t\tsql: `VARCHAR(10) NOT NULL DEFAULT '${this.client.config.prefix.constructor.name === 'Array' ? JSON.stringify(this.client.config.prefix) : this.client.config.prefix}'`\n\t\t\t},\n\t\t\tlanguage: {\n\t\t\t\ttype: 'language',\n\t\t\t\tdefault: this.client.config.language,\n\t\t\t\tmin: null,\n\t\t\t\tmax: null,\n\t\t\t\tarray: false,\n\t\t\t\tconfigurable: true,\n\t\t\t\tsql: `VARCHAR(5) NOT NULL DEFAULT '${this.client.config.language}'`\n\t\t\t},\n\t\t\tdisableNaturalPrefix: {\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t\tmin: null,\n\t\t\t\tmax: null,\n\t\t\t\tarray: false,\n\t\t\t\tconfigurable: Boolean(this.client.config.regexPrefix),\n\t\t\t\tsql: `BIT(1) NOT NULL DEFAULT 0`\n\t\t\t},\n\t\t\tdisabledCommands: {\n\t\t\t\ttype: 'command',\n\t\t\t\tdefault: [],\n\t\t\t\tmin: null,\n\t\t\t\tmax: null,\n\t\t\t\tarray: true,\n\t\t\t\tconfigurable: true,\n\t\t\t\tsql: 'TEXT'\n\t\t\t}\n\t\t};\n\t}",
"async setGuestMode_() {\n try {\n const guest = await util.isInGuestMode();\n if (guest !== null) {\n this.guestMode_ = guest;\n }\n } catch (error) {\n console.warn(error);\n // Leave this.guestMode_ as its initial value.\n }\n }",
"inSafeMode() {\n return this.getLoadSettings().safeMode;\n }",
"get isReadyForRestart() {\n if (this.updateStagingEnabled) {\n let errorCode;\n if (this.update) {\n errorCode = this.update.errorCode;\n } else if (this.um.readyUpdate) {\n errorCode = this.um.readyUpdate.errorCode;\n }\n // If the state is pending and the error code is not 0, staging must have\n // failed and Firefox should be restarted to try to apply the update\n // without staging.\n return this.isApplied || (this.isPending && errorCode != 0);\n }\n return this.isPending;\n }",
"async loadDefaults () {\n // No default config files for seeded assets right now.\n const walletDef = app().walletDefinition(this.currentAsset.id, this.currentWalletType)\n if (walletDef.seeded) return\n const loaded = app().loading(this.form)\n const res = await postJSON('/api/defaultwalletcfg', {\n assetID: this.currentAsset.id,\n type: this.currentWalletType\n })\n loaded()\n if (!app().checkResponse(res)) {\n this.setError(res.msg)\n return\n }\n this.subform.setLoadedConfig(res.config)\n }",
"loadResource() {\n // Load Selects\n // Assign Values\n this.is_auto_reclaimable.property('checked', this.resource.is_auto_reclaimable)\n this.ddl_statement.property('value', this.resource.ddl_statement)\n this.capacity_mode.property('value', this.resource.table_limits.capacity_mode)\n this.max_storage_in_gbs.property('value', this.resource.table_limits.max_storage_in_gbs)\n this.max_read_units.property('value', this.resource.table_limits.max_read_units)\n this.max_write_units.property('value', this.resource.table_limits.max_write_units)\n this.estimated_on_demand_reads_per_month.property('value', this.resource.pricing_estimates.estimated_on_demand_reads_per_month)\n this.estimated_on_demand_writes_per_month.property('value', this.resource.pricing_estimates.estimated_on_demand_writes_per_month)\n this.showHideReadWrite()\n this.loadIndexes()\n }",
"getConfigurationErrors() {\n let errors = [];\n if (typeof this.config.keyboard_listener === 'undefined') {\n errors.push('keyboard_listener must be defined');\n } else {\n if (typeof this.config.keyboard_listener.enable_delete_object !== 'boolean') {\n errors.push('keyboard_listener.enable_delete_object must be defined as a boolean');\n }\n\n if (typeof this.config.keyboard_listener.enable_move_object !== 'boolean') {\n errors.push('keyboard_listener.enable_move_object must be defined as a boolean');\n }\n }\n\n return errors;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
On Signup Button is Clicked Validate all the required Fields Show validation errors if inValid If valid: Hit Signup API | function onSignUpClicked (event) {
let isValid = true;
let userType = 'student';
$(getClassName(userType, 'signUpFirstNameError')).hide()
$(getClassName(userType, 'signUpLastNameError')).hide()
$(getClassName(userType, 'signUpCountryCodeError')).hide()
$(getClassName(userType, 'SignUpPhoneNumberError')).hide()
$(getClassName(userType, 'SignUpEmailError')).hide()
$(getClassName(userType, 'SignUpPasswordError')).hide()
const firstName = $(getClassName(userType, 'signUpFirstName'))[0].value;
const lastName = $(getClassName(userType, 'signUpLastName'))[0].value;
const countryCode = $(getClassName(userType, 'signUpCountryCode'))[0].value;
const phoneNumber = $(getClassName(userType, 'signUpPhoneNumber'))[0].value;
const emailId = $(getClassName(userType, 'signUpEmail'))[0].value;
const password = $(getClassName(userType, 'signUpPassword'))[0].value;
if (!firstName) {
$(getClassName(userType, 'signUpFirstNameError')).text('Please provide First Name');
$(getClassName(userType, 'signUpFirstNameError')).show()
isValid = false;
}
if (!lastName) {
$(getClassName(userType, 'signUpLastNameError')).text('Please provide Last Name');
$(getClassName(userType, 'signUpLastNameError')).show()
isValid = false;
}
if (countryCode === 'none') {
$(getClassName(userType, 'signUpCountryCodeError')).text('Please select country code');
$(getClassName(userType, 'signUpCountryCodeError')).show()
isValid = false;
}
if (phoneNumber && !isPhoneNumberValid(phoneNumber)) {
$(getClassName(userType, 'SignUpPhoneNumberError')).text('Please add valid phone number');
$(getClassName(userType, 'SignUpPhoneNumberError')).show()
isValid = false;
}
if (!emailId) {
$(getClassName(userType, 'SignUpEmailError')).text('Please provide email');
$(getClassName(userType, 'SignUpEmailError')).show()
isValid = false;
}
if (!password) {
$(getClassName(userType, 'SignUpPasswordError')).text('Please provide password');
$(getClassName(userType, 'SignUpPasswordError')).show()
isValid = false;
}
if (isValid) {
signUpAPI(userType, firstName, lastName, `${countryCode}${phoneNumber}`, emailId, password)
}
} | [
"static sign_up(callback = null) {\n // Hide the inputs\n window.UI.hide(\"authenticate-inputs\");\n // Change the output message\n this.output(\"Hold on - Signing you up...\");\n // Send the API call\n window.API.send(\"authenticate\", \"signup\", {\n name: window.UI.find(\"authenticate-name\").value,\n password: window.UI.find(\"authenticate-password\").value\n }, (success, result) => {\n if (success) {\n // Call the signin function\n this.sign_in(callback);\n } else {\n // Show the inputs\n window.UI.show(\"authenticate-inputs\");\n // Change the output message\n this.output(result, true);\n }\n });\n }",
"function signUp(form) {\r\n\r\n var user =\r\n {\"email\" : form.email.value,\r\n \"password\" : form.password[1].value,\r\n \"firstname\" : form.firstname.value,\r\n \"familyname\" : form.familyname.value,\r\n \"gender\" : form.gender.value,\r\n \"city\" : form.city.value,\r\n \"country\" : form.country.value};\r\n\r\n var result = serverstub.signUp(user);\r\n\r\n // status message\r\n document.getElementById('message').innerHTML = \"<h2>\" + result.message + \"</h2>\";\r\n}",
"function registrationForm() {\n app.getForm('profile').handleAction({\n confirm: function () {\n var email, profileValidation, password, passwordConfirmation, existingCustomer, Customer, target, customerExist;\n\n Customer = app.getModel('Customer');\n email = app.getForm('profile.customer.email').value();\n \n profileValidation = true;\n customerExist = false;\n \n password = app.getForm('profile.login.password').value();\n passwordConfirmation = app.getForm('profile.login.passwordconfirm').value();\n\n if (password !== passwordConfirmation) {\n app.getForm('profile.login.passwordconfirm').invalidate();\n profileValidation = false;\n }\n\n // Checks if login is already taken.\n existingCustomer = Customer.retrieveCustomerByLogin(email);\n if (existingCustomer !== null) {\n app.getForm('profile.customer.email').invalidate();\n profileValidation = false;\n customerExist = true;\n }\n\n if (profileValidation) {\n profileValidation = Customer.createAccount(email, password, app.getForm('profile'));\n }\n\n if (!profileValidation) {\n \tif(customerExist){\n \t\tresponse.redirect(URLUtils.https('Login-Show','existing', true));\n \t} else {\n \t\tresponse.redirect(URLUtils.https('Account-Show'));\n \t}\n } else {\n \tif (Site.getCurrent().getCustomPreferenceValue('MailChimpEnable')) {\n if (app.getForm('profile.customer.addtoemaillist').value()) {\n \tvar mailchimpHelper = require('*/cartridge/scripts/util/MailchimpHelper.js');\n \tmailchimpHelper.addNewListMember(app.getForm('profile.customer.firstname').value(), app.getForm('profile.customer.email').value());\n }\n } else {\n \tltkSignupEmail.Signup();\n }\n app.getForm('profile').clear();\n target = session.custom.TargetLocation;\n if (target) {\n delete session.custom.TargetLocation;\n //@TODO make sure only path, no hosts are allowed as redirect target\n dw.system.Logger.info('Redirecting to \"{0}\" after successful login', target);\n response.redirect(target);\n } else {\n response.redirect(URLUtils.https('Account-Show', 'registration', 'true'));\n }\n }\n }\n });\n}",
"function startRegister() {\n\tif(request.httpParameterMap.MailExisted.value != null && request.httpParameterMap.MailExisted.value != 'true'){\n\t\tapp.getForm('profile').clear();\n\t}\n\n if (app.getForm('login.username').value() !== null) {\n app.getForm('profile.customer.email').object.value = app.getForm('login.username').object.value;\n }\n app.getView({\n ContinueURL: URLUtils.https('Account-RegistrationForm')\n }).render('account/user/registration');\n}",
"async handleCompleteSignup() {\n const { user: { id, fuid }, firebase, setUserAction } = this.getProps(); \n const values = this._getUserSignupValues();\n \n this.toState({ userSectionLoading: true });\n\n let toApi = StateToApi.updateFirebaseUser(values);\n let promise = await this.userRepo.updateFirebaseUser(toApi, fuid);\n if(promise.err) {\n this.toState({ userSectionLoading: false });\n throw new Error('Error updating firebase user');\n }\n \n await SocialMediaHelper.signInWithEmailAndPassword(firebase, values.signupEmail, values.signupPassword);\n \n toApi = StateToApi.signupUser(values);\n promise = await this.userRepo.updateUser(toApi, id);\n if(!promise.err) {\n setUserAction(new User(promise.data));\n }\n \n this.toState({ userSectionLoading: false, openedSection: 'address', isUserSectionDone: true });\n }",
"function signUp()\n {\n var email = document.getElementById(\"email\");\n var password = document.getElementById(\"password\");\n const promise = auth.createUserWithEmailAndPassword(email.value, password.value);\n promise.catch(e => alert(e.message));\n \n alert(\"You've successfully signed up, please log in to continue shopping!\");\n if (auth.createUserWithEmailAndPassword(email.value, password.value))\n {\n window.location.href=\"LogInApparelStation.html\"\n }\n }",
"_signup() {\n\t\tconst { email, password, verify } = this.state;\n\t\tif(!email || !password || !verify) this.setState({ message: 'Not all fields were filled out.' }); \n\t\telse if(email.indexOf('@') < 0) this.setState({ message: 'Invalid email provided.' });\n\t\telse if(password !== verify){\n\t\t\t\tthis.setState({ message: 'Passwords don\\'t match.' });\n\t\t} else {\n\t\t\tthis.props.signup(email, password);\n\t\t}\n }",
"verifyCreateAccountPage(){\n utils.verifyTheCurrentUrl('register');\n }",
"function finishAutoSkipReview() {\r\n\tif ( !$('#tcsignup').validate().form() ) {\r\n\t\tpresentTCBusinessCard();\r\n\t}\r\n\r\n\t$('#btnNextStep').trigger('click');\r\n}",
"affiliateSignup (form_data, success_callback, failure_callback)\n {\n var url = '/global/crm/user/affiliate/signup';\n return WebClient.basicPost(form_data, url, success_callback, failure_callback);\n }",
"function RegisterClicked(){\r\n // set pwd length\r\n _registerControl.PLength(_pwdLength);\r\n // remember me\r\n var persist = false;\r\n var r = $get('register-remember-me');\r\n if( r != null ){\r\n persist = r.checked;\r\n }\r\n // register user\r\n _registerControl.RegisterUser(persist);\r\n}",
"function onProceedButtonClicked () {\n let isValid = true;\n let isProfileUrl = true;\n $('#onboardingProfessionError').hide()\n $('#onboardingBioError').hide()\n $('#onboardingPageNameError').hide()\n $('#onboardingProfileImageError').hide()\n const profileUrl = $('#profileImageDataURl')[0].src;\n const profession = $('#onboardingProfession')[0].value;\n const bio = $('#onboardingBio')[0].value;\n const subDomain = $('#onboardingPageName')[0].value;\n if (profileUrl === 'data:image/jpeg;base64') {\n // $('#onboardingProfileImageError').text('Please select profile image');\n // $('#onboardingProfileImageError').show()\n isProfileUrl = false\n }\n if (!profession) {\n $('#onboardingProfessionError').text('Please provide profession name');\n $('#onboardingProfessionError').show()\n isValid = false;\n }\n if (!bio) {\n $('#onboardingBioError').text('Please provide bio');\n $('#onboardingBioError').show()\n isValid = false;\n }\n if (!subDomain && validateSubdomain(subDomain)) {\n $('#onboardingPageNameError').text('Please provide page name');\n $('#onboardingPageNameError').show()\n isValid = false;\n }\n if (isValid && window.subdomainValid) {\n if (isProfileUrl) {\n createTeacherProfile(profession, bio, subDomain, profileUrl)\n } else {\n createTeacherProfile(profession, bio, subDomain)\n }\n }\n}",
"function checkRegistrationFormInputs() {\n let emailValue = email.value.trim();\n let passwordValue = password.value.trim();\n let passwordConfirmationValue = passwordConfirmation.value.trim();\n\n if (emailValue === \"\") {\n setErrorFor(email, \"Email cannot be blank\");\n } else if (!isEmail(emailValue)) {\n setErrorFor(email, \"Email is not valid\");\n } else {\n setSuccessFor(email);\n }\n\n if (passwordValue === \"\") {\n setErrorFor(password, \"Password cannot be blank\");\n } else if (passwordValue.length < 8) {\n setErrorFor(password, \"Password length must be minimum 8 symbols\");\n } else {\n setSuccessFor(password);\n }\n\n if (passwordConfirmationValue === \"\") {\n setErrorFor(passwordConfirmation, \"Confirmation field cannot be blank\");\n } else if (passwordValue !== passwordConfirmationValue) {\n setErrorFor(passwordConfirmation, \"Passwords does not match\");\n } else {\n setSuccessFor(passwordConfirmation);\n }\n}",
"signup(request, response) {\n const viewData = {\n title: 'Sign Up',\n };\n response.render('signup', viewData);\n }",
"function validateCheckoutRegistrationFields(){\n\t$('#emailIdPromoCode').blur(function () {\n\t\tthis.value = this.value.toLowerCase();\n\t\tvalidateEmailInfo('emailIdPromoCode', 'errorPromoCode1', 'invalidMsgPromoCode1', messages['createAccount.invalidEmailMsg'],\n\t\t\t\t'frmGuestPromoCodeRes', 'btnRegisterPromoCodeNew','chkoutPaymentSec');\n\t});\n\t$('#confrmEmailIdPromoCode').blur(function () {\n\t\tthis.value = this.value.toLowerCase();\n\t\tvalidateReenterEmail('emailIdPromoCode', 'confrmEmailIdPromoCode', 'errorPromoCode2', 'invalidMsgPromoCode2',\n\t\t\t\tmessages['createAccount.invalidreEnterEmailMsg'], 'frmGuestPromoCodeRes', 'btnRegisterPromoCodeNew', 'chkoutPaymentSec');\n\t});\n\t$('#passwordPromoCode').blur(function () {\n\t\tpasswordMatchUserName('emailIdPromoCode', 'passwordPromoCode', 'errorPromoCode3', 'invalidMsgPromoCode3',\n\t\t\t\tmessages['createAccount.invalidpasswordMsgSame'], 'frmGuestPromoCodeRes', 'btnRegisterPromoCodeNew','chkoutPaymentSec');\n\t});\n\t$('#mobileNoPromoCode').blur(function () {\n\t\tvalidatePhoneInfo('mobileNoPromoCode', 'errorPromoCode4', 'invalidMsgPromoCode4', messages['createAccount.invalidphoneMsg'],\n\t\t\t\t'frmGuestPromoCodeRes', 'btnRegisterPromoCodeNew','chkoutPaymentSec');\n\t});\n\t$('#zipCodePromoCode').blur(function () {\n\t\tvalidateZipcodeInfo('zipCodePromoCode', 'errorPromoCode5', 'invalidMsgPromoCode5', messages['createAccount.invalidzipCodeMsg'],\n\t\t\t\t'frmGuestPromoCodeRes', 'btnRegisterPromoCodeNew', 'chkoutPaymentSec');\n\t});\n\tcustomKeypressValidator('mobileNoPromoCode');\n}",
"function handleShowSignUp() {\n $('body').on(\"click\", \"#js-show-sign-up-form-btn\", (event) => {\n displaySignUpForm($('.js-content'));\n });\n}",
"function signUp() {\n $('#main-header').text(\"B-Day List\");\n $('#login-container').hide();\n $('#logout-btn').removeClass('hide');\n $('#add-btn').removeClass('hide');\n }",
"static triggerEmailRequired() {\n const form = document.getElementById('user-register-form')\n // Alter validation to only require email.\n form.querySelectorAll('input, .form-required').forEach((elm) => {\n if (elm.matches('input') && elm.getAttribute('required') && elm.getAttribute('id') !== 'edit-mail') {\n elm.removeAttribute('required')\n }\n if (elm.classList.contains('form-required') && elm.getAttribute('for') && elm.getAttribute('for') !== 'edit-mail') {\n elm.classList.remove('form-required')\n }\n })\n form.reportValidity()\n }",
"function submitRegisterForm() {\r\n var form = document.getElementById('register-form');\r\n\r\n if (form.checkValidity()) {\r\n registerBox.fadeOut('fast');\r\n $('.loaded').removeClass(\"loaded\");\r\n form.submit();\r\n } else {\r\n validateForm();\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
take the code and make tokens rules: spaces split tokens names stay complete symbol stuff gets chopped in single chars convert indentation (with spaces) to indent tokens | function lex(code) {
// create a 'lines' array
var lines = (function() {
var row = 0
return code.split('\n').map(function(code) {
return {code: code, row: ++row}
}).filter(function(line) {
line = line.code.trim()
if (line.length === 0) return false;
if (line.slice(0, 2) === '//') return false;
return true;
}).map(function(line) {
line.indent = /^ */.exec(line.code)[0].length
line.code = line.code.slice(line.indent)
return line
})
})()
// add indentation levels
;(function() {
var indentStack = [0]
lines.forEach(function(line) {
var indent = line.indent
if (indent > last(indentStack))
indentStack.push(indent)
while (indent < last(indentStack)) indentStack.pop()
if (indent !== last(indentStack))
throw new Error('invalid outdent on line '+line.row+' (actual: '+indent+', expected: '+last(indentStack)+')')
line.level = indentStack.length
})
})()
return (function() {
var tokens = []
var level = 1
lines.forEach(function(line) {
while (line.level > level) level++, tokens.push({type: 'indent'})
while (line.level < level) level--, tokens.push({type: 'outdent'})
tokens = tokens.concat(lexLine(line.code))
})
while (level > 1) level--, tokens.push({type: 'outdent'})
return tokens
})()
} | [
"codeToScopes(code){\n if (typeof code !== 'string') return null;\n var bodys = [];\n var body = '';\n var open = 0;\n var inScope = false;\n for (var i = 0; i < code.length; i++){\n var char = code[i];\n open += char == '{' ? 1 : 0;\n open -= char == '}' ? 1 : 0;\n\n if (!inScope && open == 1){\n bodys.push({\n scope: 'global',\n code: body,\n });\n body = '';\n inScope = true;\n }\n\n body += char;\n\n if (inScope && open == 0){\n bodys.push({\n scope: 'local',\n code: body,\n })\n body = '';\n inScope = false;\n }\n }\n return bodys;\n }",
"function getTokens(characters){\n var tokenPointer = 0;\n while (tokenPointer < characters.length){\n if (characters[tokenPointer] == \" \") {\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"-\") {\n tokens.push(\"neg\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"*\") {\n tokens.push(\"and\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"V\") {\n tokens.push(\"or\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"(\" || characters[tokenPointer] == \"[\") {\n if (tokenPointer+4<characters.length && characters[tokenPointer+1]==\"U\"\n && characters[tokenPointer+2]==\"Q\" && characters[tokenPointer+3]\n != characters[tokenPointer+3].toUpperCase() && characters[tokenPointer+4] == \")\"){\n tokens.push(\"uq\");\n tokenPointer += 5;\n }\n else if (tokenPointer+4<characters.length && characters[tokenPointer+1]==\"E\"\n && characters[tokenPointer+2]==\"Q\" && characters[tokenPointer+3]\n != characters[tokenPointer+3].toUpperCase() && characters[tokenPointer+4] == \")\"){\n tokens.push(\"eq\");\n tokenPointer += 5;\n }\n else {\n tokens.push(\"lp\")\n tokenPointer+=1\n }\n }\n else if (characters[tokenPointer] == \")\" || characters[tokenPointer] == \"]\") {\n tokens.push(\"rp\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] != characters[tokenPointer].toLowerCase()) {\n if(tokenPointer+1<characters.length && characters[tokenPointer+1]\n != characters[tokenPointer+1].toUpperCase()){\n tokens.push(\"pred\");\n tokenPointer += 1;\n while(tokenPointer<characters.length && characters[tokenPointer]\n != characters[tokenPointer].toUpperCase()){\n tokenPointer+=1;\n }\n }\n else {\n tokens.push(\"error\");\n break;\n }\n }\n else if (characters[tokenPointer] != characters[tokenPointer].toUpperCase()){\n tokens.push(\"sentLet\");\n tokenPointer+= 1;\n }\n else if (characters[tokenPointer] == \"<\") {\n if(tokenPointer+2<characters.length && characters[tokenPointer+1]==\"=\"\n && characters[tokenPointer+2]==\">\"){\n tokens.push(\"bicond\");\n tokenPointer += 3;\n }\n }\n else if (characters[tokenPointer] == \"=\") {\n if(tokenPointer+1<characters.length && characters[tokenPointer+1]==\">\"){\n tokens.push(\"cond\");\n tokenPointer += 2;\n }\n else {\n tokens.push(\"eqOp\");\n tokenPointer += 1;\n }\n }\n else if (characters[tokenPointer] == \"!\") {\n if(tokenPointer+1<characters.length && characters[tokenPointer+1]==\"=\"){\n tokens.push(\"notEqOp\");\n tokenPointer += 2;\n }\n else{\n tokens.push(\"error\");\n break;\n }\n }\n else {\n tokens.push(\"error\");\n break;\n }\n }\n}",
"function copy(){\n var _lexical = lexical, _cc = cc.concat([]), _tokenState = tokens.state;\n \n return function copyParser(input){\n lexical = _lexical;\n cc = _cc.concat([]); // copies the array\n column = indented = 0;\n tokens = tokenizeCSharp(input, _tokenState);\n return parser;\n };\n }",
"function Code(props) {\n\t var className = props.className,\n\t value = props.value,\n\t indentChars = props.indentChars,\n\t language = props.language,\n\t showIndentGuide = props.showIndentGuide,\n\t otherProps = _objectWithoutProperties(props, ['className', 'value', 'indentChars', 'language', 'showIndentGuide']);\n\t\n\t var indentBlock = (0, _lodash.repeat)(' ', indentChars);\n\t var makeIndentGuide = function makeIndentGuide(spaces) {\n\t var level = Math.floor(spaces / indentChars);\n\t var rest = spaces % indentChars;\n\t var spans = (0, _lodash.times)(level, function (idx) {\n\t return _react2.default.createElement(\n\t 'span',\n\t { className: _Code2.default.indent, key: idx.toString() },\n\t indentBlock\n\t );\n\t });\n\t if (rest) {\n\t spans.push((0, _lodash.repeat)(' ', rest));\n\t }\n\t return spans;\n\t };\n\t\n\t var tokens = (0, _syntax.tokenize)(value, language);\n\t\n\t var render = function render(tks) {\n\t return tks.map(function (part, idx) {\n\t if (typeof part === 'string') {\n\t if (!showIndentGuide) {\n\t return part;\n\t }\n\t\n\t var lines = part.split('\\n');\n\t if (lines.length === 1) {\n\t return part;\n\t }\n\t\n\t return (0, _lodash.flatten)(lines.map(function (line, lineNo) {\n\t var res = lineNo === 0 ? [] : ['\\n'];\n\t\n\t var indentMatch = line.match(/(\\s+)(.*)/);\n\t if (!indentMatch) {\n\t res.push(line);\n\t } else {\n\t res.push(_react2.default.createElement(\n\t 'span',\n\t { key: idx.toString() + ':' + lineNo.toString() },\n\t makeIndentGuide(indentMatch[1].length)\n\t ), indentMatch[2]);\n\t }\n\t\n\t return res;\n\t }));\n\t }\n\t\n\t var content = typeof part.content === 'string' ? part.content : render(part.content);\n\t\n\t return _react2.default.createElement(\n\t 'span',\n\t {\n\t className: (0, _toClassName2.default)(_Code2.default[part.type]),\n\t key: idx.toString()\n\t },\n\t content\n\t );\n\t });\n\t };\n\t\n\t var codeContent = render(tokens);\n\t\n\t return _react2.default.createElement(\n\t 'pre',\n\t _extends({\n\t className: (0, _toClassName2.default)(_Code2.default.pre, className)\n\t }, (0, _testSupport.createTestHook)(__filename), otherProps),\n\t _react2.default.createElement(\n\t 'code',\n\t { className: (0, _toClassName2.default)(_Code2.default.code, 'language-' + language) },\n\t codeContent\n\t )\n\t );\n\t}",
"parseSubmission(s) {\n // define the parser (babel) and the abstract syntax tree generated\n // from parsing the submission\n const babel = require(\"@babel/core\");\n const ast = babel.parse(s.getSubmission);\n // define iterating variable\n let i = 0;\n // define empty arrays for storing individual strings and tokens.\n // The array of strings is used to generate the array of tokens\n //let myStrings : Array<string> = []\n let myTokens = [];\n // myOriginalText = original strings from submission\n // myTypes = the type of expression of each string (e.g. NumericLiteral)\n let myOriginalText = [];\n let myTypes = [];\n // the parser traverses through the abstract syntax tree and adds\n // any strings that it passes through to the array of strings\n babel.traverse(ast, {\n enter(path) {\n myTypes.push(path.node.type);\n myOriginalText.push(path.node.name);\n }\n });\n // each string in the array of strings is used to create a new\n // token, which is then added to the array of tokens\n for (i = 0; i < myOriginalText.length; i++) {\n myTokens.push(new Token_1.default(myOriginalText[i], myTypes[i]));\n }\n // create a TokenManager that holds the array of tokens\n let myTokenManager = new TokenManager_1.default(myTokens);\n // return the TokenManager which holds all of the tokens generated\n // by the strings extracted from the original submission\n return myTokenManager;\n // t1 = new Token(originaltext1: String, identifier1: String)\n // t2 = new Token(originaltext2: String, identifier2: String)\n // ...\n // tokenList = new List<Token>\n // tokenList.add(t1)\n // tokenList.add(t2)\n // ...\n // tmanager = new TokenManager(tokenList)\n // this.tokenizedSubmission = tmanager\n }",
"function normalizeOptions(code, opts, tokens) {\n var style = \" \";\n if (code && typeof code === \"string\") {\n var indent = (0, _detectIndent2.default)(code).indent;\n if (indent && indent !== \" \") style = indent;\n }\n\n var format = {\n auxiliaryCommentBefore: opts.auxiliaryCommentBefore,\n auxiliaryCommentAfter: opts.auxiliaryCommentAfter,\n shouldPrintComment: opts.shouldPrintComment,\n retainLines: opts.retainLines,\n comments: opts.comments == null || opts.comments,\n compact: opts.compact,\n minified: opts.minified,\n concise: opts.concise,\n quotes: opts.quotes || findCommonStringDelimiter(code, tokens),\n indent: {\n adjustMultilineComment: true,\n style: style,\n base: 0\n }\n };\n\n if (format.minified) {\n format.compact = true;\n\n format.shouldPrintComment = format.shouldPrintComment || function () {\n return format.comments;\n };\n } else {\n format.shouldPrintComment = format.shouldPrintComment || function (value) {\n return format.comments || value.indexOf(\"@license\") >= 0 || value.indexOf(\"@preserve\") >= 0;\n };\n }\n\n if (format.compact === \"auto\") {\n format.compact = code.length > 100000; // 100KB\n\n if (format.compact) {\n console.error(\"[BABEL] \" + messages.get(\"codeGeneratorDeopt\", opts.filename, \"100KB\"));\n }\n }\n\n if (format.compact) {\n format.indent.adjustMultilineComment = false;\n }\n\n return format;\n}",
"function tokenize(templ) {\n return (function (arr) {\n var tokens = [];\n for (i = 0; i < arr.length; i++) {\n (function (token) {\n return token === \"\" ?\n null :\n tokens.push(token);\n }(arr[i]));\n }\n return tokens;\n }(split(templ, new RegExp(\"(\" + VAR_TAG.source + \"|\" +\n BLOCK_TAG.source + \"|\" +\n END_BLOCK_TAG.source + \")\"))));\n }",
"function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}",
"toTokens(msg) {\n // remove the prefix\n let tokensString = msg.content.slice(1).trim();\n // parse the tokens into an array\n let tokens = parse(tokensString)['_'];\n return tokens;\n }",
"tokenizeWhitespace(offset) {\n const start = offset;\n common_1.matcher.whitespaceGreedy.lastIndex = offset;\n const match = common_1.matcher.whitespaceGreedy.exec(this.cssText);\n if (match != null && match.index === offset) {\n offset = common_1.matcher.whitespaceGreedy.lastIndex;\n }\n return new token_1.Token(token_1.Token.type.whitespace, start, offset);\n }",
"function compileAction(lexer, ruleName, action) {\n if (!action) {\n return { token: '' };\n }\n else if (typeof (action) === 'string') {\n return action; // { token: action };\n }\n else if (action.token || action.token === '') {\n if (typeof (action.token) !== 'string') {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'a \\'token\\' attribute must be of type string, in rule: ' + ruleName);\n return { token: '' };\n }\n else {\n // only copy specific typed fields (only happens once during compile Lexer)\n var newAction = { token: action.token };\n if (action.token.indexOf('$') >= 0) {\n newAction.tokenSubst = true;\n }\n if (typeof (action.bracket) === 'string') {\n if (action.bracket === '@open') {\n newAction.bracket = 1 /* Open */;\n }\n else if (action.bracket === '@close') {\n newAction.bracket = -1 /* Close */;\n }\n else {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'a \\'bracket\\' attribute must be either \\'@open\\' or \\'@close\\', in rule: ' + ruleName);\n }\n }\n if (action.next) {\n if (typeof (action.next) !== 'string') {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'the next state must be a string value in rule: ' + ruleName);\n }\n else {\n var next = action.next;\n if (!/^(@pop|@push|@popall)$/.test(next)) {\n if (next[0] === '@') {\n next = next.substr(1); // peel off starting @ sign\n }\n if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists\n if (!__WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"i\" /* stateExists */](lexer, __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"j\" /* substituteMatches */](lexer, next, '', [], ''))) {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'the next state \\'' + action.next + '\\' is not defined in rule: ' + ruleName);\n }\n }\n }\n newAction.next = next;\n }\n }\n if (typeof (action.goBack) === 'number') {\n newAction.goBack = action.goBack;\n }\n if (typeof (action.switchTo) === 'string') {\n newAction.switchTo = action.switchTo;\n }\n if (typeof (action.log) === 'string') {\n newAction.log = action.log;\n }\n if (typeof (action.nextEmbedded) === 'string') {\n newAction.nextEmbedded = action.nextEmbedded;\n lexer.usesEmbedded = true;\n }\n return newAction;\n }\n }\n else if (Array.isArray(action)) {\n var results = [];\n var idx;\n for (idx in action) {\n if (action.hasOwnProperty(idx)) {\n results[idx] = compileAction(lexer, ruleName, action[idx]);\n }\n }\n return { group: results };\n }\n else if (action.cases) {\n // build an array of test cases\n var cases = [];\n // for each case, push a test function and result value\n var tkey;\n for (tkey in action.cases) {\n if (action.cases.hasOwnProperty(tkey)) {\n var val = compileAction(lexer, ruleName, action.cases[tkey]);\n // what kind of case\n if (tkey === '@default' || tkey === '@' || tkey === '') {\n cases.push({ test: null, value: val, name: tkey });\n }\n else if (tkey === '@eos') {\n cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });\n }\n else {\n cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture\n }\n }\n }\n // create a matching function\n var def = lexer.defaultToken;\n return {\n test: function (id, matches, state, eos) {\n var idx;\n for (idx in cases) {\n if (cases.hasOwnProperty(idx)) {\n var didmatch = (!cases[idx].test || cases[idx].test(id, matches, state, eos));\n if (didmatch) {\n return cases[idx].value;\n }\n }\n }\n return def;\n }\n };\n }\n else {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'an action must be a string, an object with a \\'token\\' or \\'cases\\' attribute, or an array of actions; in rule: ' + ruleName);\n return '';\n }\n}",
"function expand_spaces(message)\r\n{\r\n var exclude_open = new Array(\"[code]\", \"[pre]\", \":[\", \":/\");\r\n var exclude_close = new Array(\"[/code]\", \"[/pre]\", \"]:\", \"/:\");\r\n var open, close;\r\n var colon_on = false;\r\n \r\n var level = 0;\r\n var store_unformatted = false;\r\n var store_formatted = false;\r\n var last_store = 0;\r\n \r\n var res = \"\";\r\n \r\n for (var i = 0; i < message.length; )\r\n {\r\n var initial_i = i;\r\n \r\n if (open = prefix_in(message, exclude_open, i)) // Or in pre-formatted tag\r\n {\r\n level++;\r\n i += open.length;\r\n }\r\n\r\n if (close = prefix_in(message, exclude_close, i))\r\n {\r\n level--;\r\n i += close.length;\r\n }\r\n \r\n level = Math.max(level, 0);\r\n \r\n var spaces = take_while(\" \", message, i);\r\n if (level == 0 && spaces.length >= 3)\r\n {\r\n i += spaces.length;\r\n res += message.substring(initial_i, i).replace(\" \", \" \", \"g\");\r\n }\r\n else\r\n {\r\n i++;\r\n res += message.substring(initial_i, i);\r\n }\r\n }\r\n\r\n return res;\r\n}",
"function identAndHighlightMacro(origin) {\n\n // count the number of slashes before character i in origin\n function countSlashes(i) {\n var count = 0;\n while(count < i && origin.charAt(i-count-1) == '\\\\')\n count++;\n return count;\n }\n\n var len = origin.length;\n var result = \"\";\n var ident= \"\\n\";\n var parenLevel = 0;\n var string = 0; //0 = none 1=\" 2='\n var lineLen = 0;\n\n for (var i = 0; i < len; ++i) {\n var c = origin.charAt(i);\n switch (c) {\n case '>': lineLen++; result+=\">\"; break;\n case '<': lineLen++; result+=\"<\"; break;\n case '&': lineLen++; result+=\"&\"; break;\n case ')':\n result+=\")\";\n if (!string) {\n parenLevel--;\n if (parenLevel < 0) parenLevel = 0;\n }\n break;\n case '(':\n result+=\"(\";\n if (!string && i > 1)\n parenLevel++;\n break;\n case ';':\n result+=\";\";\n if (parenLevel==0 && !string) {\n result += ident;\n lineLen = 0;\n }\n break;\n case '{':\n result+=\"{\";\n if (parenLevel==0 && !string) {\n ident+=\" \";\n result+=ident;\n lineLen = 0;\n }\n break;\n case '}':\n if (parenLevel==0 && !string) {\n if (lineLen == 0 && ident.length > 2)\n result = result.slice(0, -2)\n result += \"}\";\n ident = ident.slice(0, -2);\n if (i+1 < len && origin.charAt(i+1) != ';') {\n result += ident;\n lineLen = 0;\n }\n } else {\n result+=\"}\";\n }\n break;\n case '\"':\n if (string == 0) {\n result += \"<q>\\\"\"\n string = 1;\n } else if (string == 1 && (countSlashes(i)%2) == 0) {\n string = 0;\n result += \"\\\"</q>\"\n } else {\n result += c;\n }\n break;\n case '\\'':\n if (string == 0) {\n result += \"<kbd>\\'\"\n string = 2;\n } else if (string == 2 && (countSlashes(i)%2) == 0) {\n string = 0;\n result += \"\\'</kbd>\"\n } else {\n result += c;\n }\n break;\n case ' ':\n if (lineLen != 0)\n result += \" \";\n break;\n default:\n lineLen++;\n result+=c;\n break;\n }\n }\n result = result.replace(/\\b(auto|void|int|bool|long|uint|unsigned|signed|char|float|double|volatile|const)\\b/g,\"<em>$1</em>\");\n result = result.replace(/\\b(asm|__attribute__|break|case|catch|class|__finally|__exception|__try|const_cast|continue|copnstexpr|private|public|protected|__declspec|default|delete|deprecated|dllexport|dllimport|do|dynamic_cast|else|enum|explicit|extern|if|for|friend|goto|inline|mutable|naked|namespace|new|noinline|noreturn|nothrow|operator|register|reinterpret_cast|return|selectany|sizeof|static|static_cast|struct|switch|template|this|thread|throw|true|typeof|false|try|typedef|typeid|typename|union|using|uuid|virtual|while)\\b/g,\"<b>$1</b>\");\n result = result.replace(/\\b(\\d+)\\b/g,\"<var>$1</var>\");\n result = result.replace(/\\b(0x[0-9a-f]+)\\b/gi,\"<var>$1</var>\");\n return result;\n }",
"function SAS(CodeMirror) {\n CodeMirror.defineMode(\"sas\", function () {\n var words = {};\n var isDoubleOperatorSym = {\n eq: 'operator',\n lt: 'operator',\n le: 'operator',\n gt: 'operator',\n ge: 'operator',\n \"in\": 'operator',\n ne: 'operator',\n or: 'operator'\n };\n var isDoubleOperatorChar = /(<=|>=|!=|<>)/;\n var isSingleOperatorChar = /[=\\(:\\),{}.*<>+\\-\\/^\\[\\]]/;\n\n // Takes a string of words separated by spaces and adds them as\n // keys with the value of the first argument 'style'\n function define(style, string, context) {\n if (context) {\n var split = string.split(' ');\n for (var i = 0; i < split.length; i++) {\n words[split[i]] = {style: style, state: context};\n }\n }\n }\n //datastep\n define('def', 'stack pgm view source debug nesting nolist', ['inDataStep']);\n define('def', 'if while until for do do; end end; then else cancel', ['inDataStep']);\n define('def', 'label format _n_ _error_', ['inDataStep']);\n define('def', 'ALTER BUFNO BUFSIZE CNTLLEV COMPRESS DLDMGACTION ENCRYPT ENCRYPTKEY EXTENDOBSCOUNTER GENMAX GENNUM INDEX LABEL OBSBUF OUTREP PW PWREQ READ REPEMPTY REPLACE REUSE ROLE SORTEDBY SPILL TOBSNO TYPE WRITE FILECLOSE FIRSTOBS IN OBS POINTOBS WHERE WHEREUP IDXNAME IDXWHERE DROP KEEP RENAME', ['inDataStep']);\n define('def', 'filevar finfo finv fipname fipnamel fipstate first firstobs floor', ['inDataStep']);\n define('def', 'varfmt varinfmt varlabel varlen varname varnum varray varrayx vartype verify vformat vformatd vformatdx vformatn vformatnx vformatw vformatwx vformatx vinarray vinarrayx vinformat vinformatd vinformatdx vinformatn vinformatnx vinformatw vinformatwx vinformatx vlabel vlabelx vlength vlengthx vname vnamex vnferr vtype vtypex weekday', ['inDataStep']);\n define('def', 'zipfips zipname zipnamel zipstate', ['inDataStep']);\n define('def', 'put putc putn', ['inDataStep']);\n define('builtin', 'data run', ['inDataStep']);\n\n\n //proc\n define('def', 'data', ['inProc']);\n\n // flow control for macros\n define('def', '%if %end %end; %else %else; %do %do; %then', ['inMacro']);\n\n //everywhere\n define('builtin', 'proc run; quit; libname filename %macro %mend option options', ['ALL']);\n\n define('def', 'footnote title libname ods', ['ALL']);\n define('def', '%let %put %global %sysfunc %eval ', ['ALL']);\n // automatic macro variables http://support.sas.com/documentation/cdl/en/mcrolref/61885/HTML/default/viewer.htm#a003167023.htm\n define('variable', '&sysbuffr &syscc &syscharwidth &syscmd &sysdate &sysdate9 &sysday &sysdevic &sysdmg &sysdsn &sysencoding &sysenv &syserr &syserrortext &sysfilrc &syshostname &sysindex &sysinfo &sysjobid &syslast &syslckrc &syslibrc &syslogapplname &sysmacroname &sysmenv &sysmsg &sysncpu &sysodspath &sysparm &syspbuff &sysprocessid &sysprocessname &sysprocname &sysrc &sysscp &sysscpl &sysscpl &syssite &sysstartid &sysstartname &systcpiphostname &systime &sysuserid &sysver &sysvlong &sysvlong4 &syswarningtext', ['ALL']);\n\n //footnote[1-9]? title[1-9]?\n\n //options statement\n define('def', 'source2 nosource2 page pageno pagesize', ['ALL']);\n\n //proc and datastep\n define('def', '_all_ _character_ _cmd_ _freq_ _i_ _infile_ _last_ _msg_ _null_ _numeric_ _temporary_ _type_ abort abs addr adjrsq airy alpha alter altlog altprint and arcos array arsin as atan attrc attrib attrn authserver autoexec awscontrol awsdef awsmenu awsmenumerge awstitle backward band base betainv between blocksize blshift bnot bor brshift bufno bufsize bxor by byerr byline byte calculated call cards cards4 catcache cbufno cdf ceil center cexist change chisq cinv class cleanup close cnonct cntllev coalesce codegen col collate collin column comamid comaux1 comaux2 comdef compbl compound compress config continue convert cos cosh cpuid create cross crosstab css curobs cv daccdb daccdbsl daccsl daccsyd dacctab dairy datalines datalines4 datejul datepart datetime day dbcslang dbcstype dclose ddm delete delimiter depdb depdbsl depsl depsyd deptab dequote descending descript design= device dflang dhms dif digamma dim dinfo display distinct dkricond dkrocond dlm dnum do dopen doptname doptnum dread drop dropnote dsname dsnferr echo else emaildlg emailid emailpw emailserver emailsys encrypt end endsas engine eof eov erf erfc error errorcheck errors exist exp fappend fclose fcol fdelete feedback fetch fetchobs fexist fget file fileclose fileexist filefmt filename fileref fmterr fmtsearch fnonct fnote font fontalias fopen foptname foptnum force formatted formchar formdelim formdlim forward fpoint fpos fput fread frewind frlen from fsep fuzz fwrite gaminv gamma getoption getvarc getvarn go goto group gwindow hbar hbound helpenv helploc hms honorappearance hosthelp hostprint hour hpct html hvar ibessel ibr id if index indexc indexw initcmd initstmt inner input inputc inputn inr insert int intck intnx into intrr invaliddata irr is jbessel join juldate keep kentb kurtosis label lag last lbound leave left length levels lgamma lib library libref line linesize link list log log10 log2 logpdf logpmf logsdf lostcard lowcase lrecl ls macro macrogen maps mautosource max maxdec maxr mdy mean measures median memtype merge merror min minute missing missover mlogic mod mode model modify month mopen mort mprint mrecall msglevel msymtabmax mvarsize myy n nest netpv new news nmiss no nobatch nobs nocaps nocardimage nocenter nocharcode nocmdmac nocol nocum nodate nodbcs nodetails nodmr nodms nodmsbatch nodup nodupkey noduplicates noechoauto noequals noerrorabend noexitwindows nofullstimer noicon noimplmac noint nolist noloadlist nomiss nomlogic nomprint nomrecall nomsgcase nomstored nomultenvappl nonotes nonumber noobs noovp nopad nopercent noprint noprintinit normal norow norsasuser nosetinit nosplash nosymbolgen note notes notitle notitles notsorted noverbose noxsync noxwait npv null number numkeys nummousekeys nway obs on open order ordinal otherwise out outer outp= output over ovp p(1 5 10 25 50 75 90 95 99) pad pad2 paired parm parmcards path pathdll pathname pdf peek peekc pfkey pmf point poisson poke position printer probbeta probbnml probchi probf probgam probhypr probit probnegb probnorm probsig probt procleave prt ps pw pwreq qtr quote r ranbin rancau ranexp rangam range ranks rannor ranpoi rantbl rantri ranuni read recfm register regr remote remove rename repeat replace resolve retain return reuse reverse rewind right round rsquare rtf rtrace rtraceloc s s2 samploc sasautos sascontrol sasfrscr sasmsg sasmstore sasscript sasuser saving scan sdf second select selection separated seq serror set setcomm setot sign simple sin sinh siteinfo skewness skip sle sls sortedby sortpgm sortseq sortsize soundex spedis splashlocation split spool sqrt start std stderr stdin stfips stimer stname stnamel stop stopover subgroup subpopn substr sum sumwgt symbol symbolgen symget symput sysget sysin sysleave sysmsg sysparm sysprint sysprintfont sysprod sysrc system t table tables tan tanh tapeclose tbufsize terminal test then timepart tinv tnonct to today tol tooldef totper transformout translate trantab tranwrd trigamma trim trimn trunc truncover type unformatted uniform union until upcase update user usericon uss validate value var weight when where while wincharset window work workinit workterm write wsum xsync xwait yearcutoff yes yyq min max', ['inDataStep', 'inProc']);\n define('operator', 'and not ', ['inDataStep', 'inProc']);\n\n // Main function\n function tokenize(stream, state) {\n // Finally advance the stream\n var ch = stream.next();\n\n // BLOCKCOMMENT\n if (ch === '/' && stream.eat('*')) {\n state.continueComment = true;\n return \"comment\";\n } else if (state.continueComment === true) { // in comment block\n //comment ends at the beginning of the line\n if (ch === '*' && stream.peek() === '/') {\n stream.next();\n state.continueComment = false;\n } else if (stream.skipTo('*')) { //comment is potentially later in line\n stream.skipTo('*');\n stream.next();\n if (stream.eat('/'))\n state.continueComment = false;\n } else {\n stream.skipToEnd();\n }\n return \"comment\";\n }\n\n if (ch == \"*\" && stream.column() == stream.indentation()) {\n stream.skipToEnd();\n return \"comment\"\n }\n\n // DoubleOperator match\n var doubleOperator = ch + stream.peek();\n\n if ((ch === '\"' || ch === \"'\") && !state.continueString) {\n state.continueString = ch;\n return \"string\"\n } else if (state.continueString) {\n if (state.continueString == ch) {\n state.continueString = null;\n } else if (stream.skipTo(state.continueString)) {\n // quote found on this line\n stream.next();\n state.continueString = null;\n } else {\n stream.skipToEnd();\n }\n return \"string\";\n } else if (state.continueString !== null && stream.eol()) {\n stream.skipTo(state.continueString) || stream.skipToEnd();\n return \"string\";\n } else if (/[\\d\\.]/.test(ch)) { //find numbers\n if (ch === \".\")\n stream.match(/^[0-9]+([eE][\\-+]?[0-9]+)?/);\n else if (ch === \"0\")\n stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);\n else\n stream.match(/^[0-9]*\\.?[0-9]*([eE][\\-+]?[0-9]+)?/);\n return \"number\";\n } else if (isDoubleOperatorChar.test(ch + stream.peek())) { // TWO SYMBOL TOKENS\n stream.next();\n return \"operator\";\n } else if (isDoubleOperatorSym.hasOwnProperty(doubleOperator)) {\n stream.next();\n if (stream.peek() === ' ')\n return isDoubleOperatorSym[doubleOperator.toLowerCase()];\n } else if (isSingleOperatorChar.test(ch)) { // SINGLE SYMBOL TOKENS\n return \"operator\";\n }\n\n // Matches one whole word -- even if the word is a character\n var word;\n if (stream.match(/[%&;\\w]+/, false) != null) {\n word = ch + stream.match(/[%&;\\w]+/, true);\n if (/&/.test(word)) return 'variable'\n } else {\n word = ch;\n }\n // the word after DATA PROC or MACRO\n if (state.nextword) {\n stream.match(/[\\w]+/);\n // match memname.libname\n if (stream.peek() === '.') stream.skipTo(' ');\n state.nextword = false;\n return 'variable-2';\n }\n\n word = word.toLowerCase();\n // Are we in a DATA Step?\n if (state.inDataStep) {\n if (word === 'run;' || stream.match(/run\\s;/)) {\n state.inDataStep = false;\n return 'builtin';\n }\n // variable formats\n if ((word) && stream.next() === '.') {\n //either a format or libname.memname\n if (/\\w/.test(stream.peek())) return 'variable-2';\n else return 'variable';\n }\n // do we have a DATA Step keyword\n if (word && words.hasOwnProperty(word) &&\n (words[word].state.indexOf(\"inDataStep\") !== -1 ||\n words[word].state.indexOf(\"ALL\") !== -1)) {\n //backup to the start of the word\n if (stream.start < stream.pos)\n stream.backUp(stream.pos - stream.start);\n //advance the length of the word and return\n for (var i = 0; i < word.length; ++i) stream.next();\n return words[word].style;\n }\n }\n // Are we in an Proc statement?\n if (state.inProc) {\n if (word === 'run;' || word === 'quit;') {\n state.inProc = false;\n return 'builtin';\n }\n // do we have a proc keyword\n if (word && words.hasOwnProperty(word) &&\n (words[word].state.indexOf(\"inProc\") !== -1 ||\n words[word].state.indexOf(\"ALL\") !== -1)) {\n stream.match(/[\\w]+/);\n return words[word].style;\n }\n }\n // Are we in a Macro statement?\n if (state.inMacro) {\n if (word === '%mend') {\n if (stream.peek() === ';') stream.next();\n state.inMacro = false;\n return 'builtin';\n }\n if (word && words.hasOwnProperty(word) &&\n (words[word].state.indexOf(\"inMacro\") !== -1 ||\n words[word].state.indexOf(\"ALL\") !== -1)) {\n stream.match(/[\\w]+/);\n return words[word].style;\n }\n\n return 'atom';\n }\n // Do we have Keywords specific words?\n if (word && words.hasOwnProperty(word)) {\n // Negates the initial next()\n stream.backUp(1);\n // Actually move the stream\n stream.match(/[\\w]+/);\n if (word === 'data' && /=/.test(stream.peek()) === false) {\n state.inDataStep = true;\n state.nextword = true;\n return 'builtin';\n }\n if (word === 'proc') {\n state.inProc = true;\n state.nextword = true;\n return 'builtin';\n }\n if (word === '%macro') {\n state.inMacro = true;\n state.nextword = true;\n return 'builtin';\n }\n if (/title[1-9]/.test(word)) return 'def';\n\n if (word === 'footnote') {\n stream.eat(/[1-9]/);\n return 'def';\n }\n\n // Returns their value as state in the prior define methods\n if (state.inDataStep === true && words[word].state.indexOf(\"inDataStep\") !== -1)\n return words[word].style;\n if (state.inProc === true && words[word].state.indexOf(\"inProc\") !== -1)\n return words[word].style;\n if (state.inMacro === true && words[word].state.indexOf(\"inMacro\") !== -1)\n return words[word].style;\n if (words[word].state.indexOf(\"ALL\") !== -1)\n return words[word].style;\n return null;\n }\n // Unrecognized syntax\n return null;\n }\n\n return {\n startState: function () {\n return {\n inDataStep: false,\n inProc: false,\n inMacro: false,\n nextword: false,\n continueString: null,\n continueComment: false\n };\n },\n token: function (stream, state) {\n // Strip the spaces, but regex will account for them either way\n if (stream.eatSpace()) return null;\n // Go through the main process\n return tokenize(stream, state);\n },\n\n blockCommentStart: \"/*\",\n blockCommentEnd: \"*/\"\n };\n\n });\n\n CodeMirror.defineMIME(\"text/x-sas\", \"sas\");\n }",
"tokenBefore(types) {\n let token = this.state.tree.resolve(this.pos, -1);\n while (token && types.indexOf(token.name) < 0)\n token = token.parent;\n return token ? { from: token.start, to: this.pos,\n text: this.state.sliceDoc(token.start, this.pos),\n type: token.type } : null;\n }",
"cfg2ast (cfg) {\n /* establish abstract syntax tree (AST) node generator */\n let asty = new ASTY()\n const AST = (type, ref) => {\n let ast = asty.create(type)\n if (typeof ref === \"object\" && ref instanceof Array && ref.length > 0)\n ref = ref[0]\n if (typeof ref === \"object\" && ref instanceof Tokenizr.Token)\n ast.pos(ref.line, ref.column, ref.pos)\n else if (typeof ref === \"object\" && asty.isA(ref))\n ast.pos(ref.pos().line, ref.pos().column, ref.pos().offset)\n return ast\n }\n\n /* establish lexical scanner */\n let lexer = new Tokenizr()\n lexer.rule(/[a-zA-Z_][a-zA-Z0-9_]*/, (ctx, m) => {\n ctx.accept(\"id\")\n })\n lexer.rule(/[+-]?[0-9]+/, (ctx, m) => {\n ctx.accept(\"number\", parseInt(m[0]))\n })\n lexer.rule(/\"((?:\\\\\\\"|[^\\r\\n]+)+)\"/, (ctx, m) => {\n ctx.accept(\"string\", m[1].replace(/\\\\\"/g, \"\\\"\"))\n })\n lexer.rule(/\\/\\/[^\\r\\n]+\\r?\\n/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/[ \\t\\r\\n]+/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/./, (ctx, m) => {\n ctx.accept(\"char\")\n })\n\n /* establish recursive descent parser */\n let parser = {\n parseCfg () {\n let block = this.parseBlock()\n lexer.consume(\"EOF\")\n return AST(\"Section\", block).set({ ns: \"\" }).add(block)\n },\n parseBlock () {\n let items = []\n for (;;) {\n let item = lexer.alternatives(\n this.parseProperty.bind(this),\n this.parseSection.bind(this),\n this.parseEmpty.bind(this))\n if (item === undefined)\n break\n items.push(item)\n }\n return items\n },\n parseProperty () {\n let key = this.parseId()\n lexer.consume(\"char\", \"=\")\n let value = lexer.alternatives(\n this.parseNumber.bind(this),\n this.parseString.bind(this))\n return AST(\"Property\", value).set({ key: key.value, val: value.value })\n },\n parseSection () {\n let ns = this.parseId()\n lexer.consume(\"char\", \"{\")\n let block = this.parseBlock()\n lexer.consume(\"char\", \"}\")\n return AST(\"Section\", ns).set({ ns: ns.value }).add(block)\n },\n parseId () {\n return lexer.consume(\"id\")\n },\n parseNumber () {\n return lexer.consume(\"number\")\n },\n parseString () {\n return lexer.consume(\"string\")\n },\n parseEmpty () {\n return undefined\n }\n }\n\n /* parse syntax character string into abstract syntax tree (AST) */\n let ast\n try {\n lexer.input(cfg)\n ast = parser.parseCfg()\n }\n catch (ex) {\n console.log(ex.toString())\n process.exit(0)\n }\n return ast\n }",
"function docEdits_mergeCodeBlocks(srcArray, openDelim, closeDelim)\n{\n var pattern, myRe, match, whiteSpace, innerWhiteSpace, retval = \"\";\n var eolCount = 0, i;\n var block2 = srcArray.pop();\n var block1 = srcArray.pop();\n var before = \"\";\n var block1New = \"\";\n\n pattern = \"(\\\\s*)\" + dwscripts.escRegExpChars(closeDelim) + \"([\\\\s|(?: )]*)$\";\n myRe = new RegExp(pattern, \"i\");\n match = block1.match(myRe);\n if (match)\n {\n innerWhiteSpace = match[1];\n whiteSpace = match[2];\n i = block1.lastIndexOf(openDelim);\n before = block1.substring(0, i);\n block1New = block1.substring(i, match.index);\n\n pattern = \"^([\\\\s|(?: )]*)\" + dwscripts.escRegExpChars(openDelim) + \"(\\\\s*)\";\n myRe = new RegExp(pattern, \"i\");\n match = block2.match(myRe);\n if (match)\n {\n whiteSpace += match[1];\n innerWhiteSpace += match[2];\n\n //ensure separation of at least 2 newlines between code blocks\n for (i = 0; i < innerWhiteSpace.length; i++)\n {\n var tempChar = innerWhiteSpace.charAt(i);\n if (tempChar == \"\\n\" || tempChar == \"\\r\")\n {\n eolCount++;\n // If using windows style newline, \"\\r\\n\", need to step past '\\n'.\n if ( tempChar == \"\\r\" && (i + 1 < innerWhiteSpace.length)\n && innerWhiteSpace.charAt(i + 1) == \"\\n\"\n )\n {\n ++eolCount;\n }\n }\n }\n\n for (i = eolCount; i < 2; i++)\n {\n innerWhiteSpace += dwscripts.getNewline();\n }\n\n retval = before + whiteSpace + block1New + innerWhiteSpace + block2.substring(match[0].length);\n srcArray.push(retval);\n }\n }\n\n // If we couldn't merge, push the two blocks back onto the array\n if (!retval)\n {\n srcArray.push(block1);\n srcArray.push(block2);\n }\n}",
"function Yacas(CodeMirror) {\n CodeMirror.defineMode('yacas', function(_config, _parserConfig) {\n\n function words(str) {\n var obj = {}, words = str.split(\" \");\n for (var i = 0; i < words.length; ++i) obj[words[i]] = true;\n return obj;\n }\n\n var bodiedOps = words(\"Assert BackQuote D Defun Deriv For ForEach FromFile \" +\n \"FromString Function Integrate InverseTaylor Limit \" +\n \"LocalSymbols Macro MacroRule MacroRulePattern \" +\n \"NIntegrate Rule RulePattern Subst TD TExplicitSum \" +\n \"TSum Taylor Taylor1 Taylor2 Taylor3 ToFile \" +\n \"ToStdout ToString TraceRule Until While\");\n\n // patterns\n var pFloatForm = \"(?:(?:\\\\.\\\\d+|\\\\d+\\\\.\\\\d*|\\\\d+)(?:[eE][+-]?\\\\d+)?)\";\n var pIdentifier = \"(?:[a-zA-Z\\\\$'][a-zA-Z0-9\\\\$']*)\";\n\n // regular expressions\n var reFloatForm = new RegExp(pFloatForm);\n var reIdentifier = new RegExp(pIdentifier);\n var rePattern = new RegExp(pIdentifier + \"?_\" + pIdentifier);\n var reFunctionLike = new RegExp(pIdentifier + \"\\\\s*\\\\(\");\n\n function tokenBase(stream, state) {\n var ch;\n\n // get next character\n ch = stream.next();\n\n // string\n if (ch === '\"') {\n state.tokenize = tokenString;\n return state.tokenize(stream, state);\n }\n\n // comment\n if (ch === '/') {\n if (stream.eat('*')) {\n state.tokenize = tokenComment;\n return state.tokenize(stream, state);\n }\n if (stream.eat(\"/\")) {\n stream.skipToEnd();\n return \"comment\";\n }\n }\n\n // go back one character\n stream.backUp(1);\n\n // update scope info\n var m = stream.match(/^(\\w+)\\s*\\(/, false);\n if (m !== null && bodiedOps.hasOwnProperty(m[1]))\n state.scopes.push('bodied');\n\n var scope = currentScope(state);\n\n if (scope === 'bodied' && ch === '[')\n state.scopes.pop();\n\n if (ch === '[' || ch === '{' || ch === '(')\n state.scopes.push(ch);\n\n scope = currentScope(state);\n\n if (scope === '[' && ch === ']' ||\n scope === '{' && ch === '}' ||\n scope === '(' && ch === ')')\n state.scopes.pop();\n\n if (ch === ';') {\n while (scope === 'bodied') {\n state.scopes.pop();\n scope = currentScope(state);\n }\n }\n\n // look for ordered rules\n if (stream.match(/\\d+ *#/, true, false)) {\n return 'qualifier';\n }\n\n // look for numbers\n if (stream.match(reFloatForm, true, false)) {\n return 'number';\n }\n\n // look for placeholders\n if (stream.match(rePattern, true, false)) {\n return 'variable-3';\n }\n\n // match all braces separately\n if (stream.match(/(?:\\[|\\]|{|}|\\(|\\))/, true, false)) {\n return 'bracket';\n }\n\n // literals looking like function calls\n if (stream.match(reFunctionLike, true, false)) {\n stream.backUp(1);\n return 'variable';\n }\n\n // all other identifiers\n if (stream.match(reIdentifier, true, false)) {\n return 'variable-2';\n }\n\n // operators; note that operators like @@ or /; are matched separately for each symbol.\n if (stream.match(/(?:\\\\|\\+|\\-|\\*|\\/|,|;|\\.|:|@|~|=|>|<|&|\\||_|`|'|\\^|\\?|!|%|#)/, true, false)) {\n return 'operator';\n }\n\n // everything else is an error\n return 'error';\n }\n\n function tokenString(stream, state) {\n var next, end = false, escaped = false;\n while ((next = stream.next()) != null) {\n if (next === '\"' && !escaped) {\n end = true;\n break;\n }\n escaped = !escaped && next === '\\\\';\n }\n if (end && !escaped) {\n state.tokenize = tokenBase;\n }\n return 'string';\n }\n function tokenComment(stream, state) {\n var prev, next;\n while((next = stream.next()) != null) {\n if (prev === '*' && next === '/') {\n state.tokenize = tokenBase;\n break;\n }\n prev = next;\n }\n return 'comment';\n }\n\n function currentScope(state) {\n var scope = null;\n if (state.scopes.length > 0)\n scope = state.scopes[state.scopes.length - 1];\n return scope;\n }\n\n return {\n startState: function() {\n return {\n tokenize: tokenBase,\n scopes: []\n };\n },\n token: function(stream, state) {\n if (stream.eatSpace()) return null;\n return state.tokenize(stream, state);\n },\n indent: function(state, textAfter) {\n if (state.tokenize !== tokenBase && state.tokenize !== null)\n return CodeMirror.Pass;\n\n var delta = 0;\n if (textAfter === ']' || textAfter === '];' ||\n textAfter === '}' || textAfter === '};' ||\n textAfter === ');')\n delta = -1;\n\n return (state.scopes.length + delta) * _config.indentUnit;\n },\n electricChars: \"{}[]();\",\n blockCommentStart: \"/*\",\n blockCommentEnd: \"*/\",\n lineComment: \"//\"\n };\n });\n\n CodeMirror.defineMIME('text/x-yacas', {\n name: 'yacas'\n });\n\n }",
"function step4(token) {\n\treturn replacePatterns(token, [['al', ''], ['ance', ''], ['ence', ''], ['er', ''],\n ['ic', ''], ['able', ''], ['ible', ''], ['ant', ''],\n ['ement', ''], ['ment', ''], ['ent', ''], [/([st])ion/, '$1'], ['ou', ''], ['ism', ''],\n ['ate', ''], ['iti', ''], ['ous', ''], ['ive', ''],\n ['ize', '']], 1);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw the timeline at the bottom of the screen | function draw_timeline() {
var size = canvas.width/dpi * 0.75;
var start = x_center - size/2;
var finish = x_center - size/2 + size;
ctx.fillRect(0, canvas.height/dpi - 30, canvas.width/dpi, 6);
ctx.globalAlpha = 1;
// Calculate where the position marker should be on the screen
var position = start + (((serial_date - earliest) / (latest - earliest)) * size);
ctx.fillRect(position - 3, canvas.height/dpi - 30, 6, 6);
} | [
"redrawTimeline() {\n this._canvas.clearRect(0, 0, this._canvasWidth, this._canvasHeight);\n this.drawBackground();\n this.drawLayerLabels();\n // Recompute objects positions\n this._timelineState = this.getTimelineDrawState(this._resolvedStates);\n // Draw the current state.\n this.drawTimelineState(this._timelineState);\n this.drawPlayhead();\n this.checkAutomaticReresolve();\n }",
"function drawTail(){\n\tfor(var i = 0; i < tailPos.length; i++){\n\t\tctx.fillStyle = \"#00ff00\";\n\t\tctx.fillRect(tailPos[i][0], tailPos[i][1], blockSize, blockSize);\n\t}\n\tif(tailPos.length > score){\n\t\ttailPos.shift();\n\t}\n}",
"function render_bottom_border() {\n context.setLineDash([5, 15]);\n\n context.lineWidth = 1;\n context.strokeStyle = '#00ff00';\n context.beginPath();\n context.moveTo(0, (canvas.height - 155));\n context.lineTo(canvas.width, (canvas.height - 155));\n context.stroke();\n }",
"drawPlayhead() {\n // If the playhead should be draw.\n if (this._drawPlayhead) {\n if (this.istimeInView(this._playHeadTime)) {\n this._canvas.fillStyle = COLOR_PLAYHEAD;\n this._canvas.fillRect(this.timeToXCoord(this._playHeadTime), 0, THICKNESS_PLAYHEAD, this._canvasHeight);\n }\n }\n }",
"function moveToCurrentTime() {\r\n timeline.setVisibleChartRangeNow();\r\n}",
"function resetTimelineView() {\n\n ViewVideo.OverlayTimeline.css('height', '');\n ViewVideo.OverlayTimeline.children('.timelineElement').css({\n top: '',\n right: '',\n bottom: '',\n height: ''\n });\n\n }",
"function drawControl_grow(header_ypos)\r\n{\r\n // now draw the feedback panel with an appropriate sized gap\r\n header_ypos += (button_gap*3);\r\n \r\n // set up fonts\r\n Hcontext.fillStyle = 'rgb(0,0,0)';\r\n Hcontext.font = (24.0).toString() + 'px '+fonttype;\r\n Hcontext.textAlign = 'center';\r\n // draw title\r\n \r\n \r\n if (timelim > 0 )\r\n {\r\n if (timelim >10)\r\n {\r\n Hcontext.font = (40.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText((Math.round(timelim*10)/10.0).toString() , 185, header_ypos);\r\n drawclock(80,header_ypos,20,1-(timelim/original_timelim),'rgb(0,0,0)',Hcontext);\r\n\r\n header_ypos += 45;\r\n \r\n Hcontext.font = (20.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText('Million years ago' , 147, header_ypos);\r\n }\r\n else\r\n {\r\n // if (timelim >1)\r\n // {\r\n Hcontext.font = (40.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText((Math.round(timelim*100)/100.0).toString() , 185, header_ypos);\r\n drawclock(80,header_ypos,20,1-(timelim/original_timelim),'rgb(0,0,0)',Hcontext);\r\n\r\n header_ypos += 45;\r\n\r\n \r\n Hcontext.font = (20.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText('Million years ago' , 147, header_ypos);\r\n // }\r\n }\r\n header_ypos += 30;\r\n Hcontext.font = (20.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText( gpmapper(timelim) + ' period', 147, header_ypos);\r\n \r\n \r\n }\r\n else\r\n {\r\n //header_ypos += 25;\r\n //Hcontext.font = (30.0).toString() + 'px '+fonttype;\r\n //Hcontext.fillText('Present day' , 147, header_ypos);\r\n //header_ypos += 50;\r\n \r\n Hcontext.font = (40.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText('0' , 147, header_ypos);\r\n \r\n header_ypos += 45;\r\n \r\n Hcontext.font = (20.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText('Million years ago' , 147, header_ypos);\r\n \r\n header_ypos += 30;\r\n Hcontext.font = (20.0).toString() + 'px '+fonttype;\r\n Hcontext.fillText( 'Present day', 147, header_ypos);\r\n \r\n }\r\n \r\n header_ypos += 30;\r\n \r\n // growth control buttons\r\n control_button(\"Reverse\",header_ypos,\"growrev\",null,(!growing)||growingdir);\r\n draw_reverse_symbol(control_margin+button_width*(5/6),header_ypos+button_height/2,25,Hcontext)\r\n Hcontext.fillStyle ='rgb(0,0,0)';\r\n Hcontext.fill();\r\n header_ypos += (button_gap+button_height);\r\n \r\n control_button(\"Pause\",header_ypos,\"growpause\",null,!growingpause);\r\n draw_pause_symbol(control_margin+button_width*(5/6),header_ypos+button_height/2,25,Hcontext)\r\n Hcontext.fillStyle ='rgb(0,0,0)';\r\n Hcontext.fill();\r\n header_ypos += (button_gap+button_height);\r\n \r\n control_button(\"Play\",header_ypos,\"growplay\",null,(!growing)||(!growingdir));\r\n draw_play_symbol(control_margin+button_width*(5/6),header_ypos+button_height/2,25,Hcontext)\r\n Hcontext.fillStyle ='rgb(0,0,0)';\r\n Hcontext.fill();\r\n header_ypos += (button_gap+button_height);\r\n \r\n control_button(\"End\",header_ypos,\"growend\",null,(growing)||((growingpause)||(timelim >= 0)));\r\n draw_stop_symbol(control_margin+button_width*(5/6),header_ypos+button_height/2,25,Hcontext)\r\n Hcontext.fillStyle ='rgb(0,0,0)';\r\n Hcontext.fill();\r\n header_ypos += (button_gap+button_height);\r\n \r\n // reset button\r\n control_button(\"Reset tree view\",header_ypos,\"viewReset\",null,true);\r\n header_ypos += (button_gap+button_height);\r\n\r\n \r\n // set up fonts\r\n Hcontext.fillStyle = 'rgb(0,0,0)';\r\n Hcontext.font = (18.0).toString() + 'px '+fonttype;\r\n Hcontext.textAlign = 'left';\r\n // draw title\r\n\r\n \r\n temp_txt = [\" \",\r\n \"This function shows you an\",\r\n \"animation of the tree growing\",\r\n \"over time. The tree doesn't\",\r\n \"show extinct species, other than\",\r\n \"those where extinction has\",\r\n \"occured very recently. You can\",\r\n \"still explore the tree in the\",\r\n \"usual way during this animation.\",\" \",\r\n \"Touch the screen with two\",\r\n \"fingers and pinch to zoom in or\",\r\n \"out. You can also tap any of\",\r\n \"the circular images to zoom in\",\r\n \"to that area of the tree.\"];\r\n skipper = 22\r\n \r\n for (var iii = 0 ; iii < temp_txt.length ; iii ++)\r\n {\r\n Hcontext.fillText (temp_txt[iii] , control_margin, header_ypos+skipper*iii);\r\n }\r\n \r\n \r\n \r\n}",
"function drawContentItems() {\r\n // Get current range\r\n var range = Canvas.Timescale.getRange();\r\n drawContentItemsLoop(_contentItems, range, true);\r\n drawContentItemsLoop(_contentItems, range, false);\r\n }",
"function positionElementBottom(){\n\t\t\n\t\tvar totalTextHeight = getTotalTextHeight();\n\t\tvar startY = g_objTextWrapper.height() - totalTextHeight - g_options.slider_textpanel_padding_bottom;\n\t\t\n\t\tpositionElementsTop(false, startY);\n\t}",
"showLastLine() {\n this.el.style.transform = 'translatey(-' + ( ( this.lines.length * this.lineHeight ) - ( this.lineHeight * this.opts.rows ) ) + 'px )';\n this.overlay.style.transform = 'translatey(-' + ( ( this.lines.length * this.lineHeight ) - ( this.lineHeight * this.opts.rows ) ) + 'px )';\n }",
"function topContentRight() {\n let top_content_R = gsap.timeline({\n id: \"top content right\"\n });\n top_content_R.from($top_Content_Right, {\n y: -200,\n autoAlpha: 0,\n duration: 1.5,\n ease: bo,\n delay: 3\n })\n }",
"show() {\n var pos = this.body.position;\n var angle = this.body.angle;\n\n push();\n translate(pos.x, pos.y);\n rotate(angle);\n rectMode(CENTER);\n\n drawSprite(this.birdspr);\n /* strokeWeight(1);\n stroke(255);\n fill(127);\n ellipse(0, 0, this.r * 2);\n line(0, 0, this.r, 0);*/\n pop();\n }",
"function stackTimelineView() {\n\n ViewVideo.OverlayTimeline.CollisionDetection({spacing:0, includeVerticalMargins: true});\n ViewVideo.adjustLayout();\n ViewVideo.adjustHypervideo();\n\n }",
"static scrollToBottom() {\n\t\tvar storyEl = document.getElementsByTagName(\"jw-story\")[0];\n\t\t// Create invisible div element after the end of the story element\n\t\tvar storyBottomEl = storyEl.appendChild(document.createElement(\"div\"));\n\t\t// Scroll it into view\n\t\tstoryBottomEl.scrollIntoView();\n\t\t// Now we don't need that element anymore\n\t\tstoryBottomEl.remove();\n\t}",
"drawLobbyView() {\n this.drawState();\n\n this.ctx.font = '20px Arial';\n this.ctx.fillStyle = '#FFF';\n this.ctx.textAlign = 'center';\n this.ctx.fillText('Waiting on another player...', this.canvas.width / 2,\n this.canvas.height / 2 - 60);\n this.ctx.fillStyle = '#000';\n }",
"function drawYAxis(ymin, ymax, visObject){\n \n visObject.context.font = visObject.fontheight + \"px sans-serif\";\n visObject.context.fillStyle = \"rgb(0,0,0)\";\n \n // --- //\n var ydiff = ymax - ymin;\n var inc = getDataIncrement(3, (visObject.drawheight / visObject.fontheight) * 0.66, ydiff);\n \n var i = null;\n while ((i = getNextDataIncrement(ymin, inc, i)) <= ymax){\n var y = visObject.drawheight - ((i-ymin)*visObject.drawheight/ydiff-visObject.fontheight/3) + visObject.yoff;\n \n var gridy = visObject.drawheight - ((i-ymin)*visObject.drawheight/ydiff) + visObject.yoff;\n \n label = (formatData(i, inc));//.toString();//(i.toFixed(n)).toString();\n \n //if( y > visObject.fontheight + visObject.yoff && y < visObject.yoff + visObject.drawheight - visObject.fontheight/2 )\n \n visObject.context.fillText( label.toString(), visObject.drawwidth + visObject.fontheight/2, y );\n \n visObject.context.strokeStyle = visObject.gridcolor;\n visObject.context.lineWidth = 0.25; \n visObject.context.beginPath();\n visObject.context.moveTo(0, gridy);\n visObject.context.lineTo(visObject.drawwidth, gridy);\n visObject.context.stroke();\n visObject.context.closePath();\n \n }\n \n return 0;\n \n}",
"function drawTime() {\r\n var text = 'God morgon!'\r\n // var text = '06.00'\r\n var textSize = 50\r\n context.fillStyle = getFillstyleString(stampColor[0], stampColor[1], stampColor[2], alpha)\r\n context.font = `${textSize}` + 'px OpenSans'\r\n context.fillText(text, X + RADIUS * Math.sin(-Math.PI/2 + ROTATION * Math.PI) - context.measureText(text).width / 2, Y + RADIUS * Math.cos(Math.PI/2 + ROTATION * Math.PI) + textSize / 2)\r\n // Swedish\r\n putText('Morgon', -0.5)\r\n\r\n putText('Förmiddag', 0.5)\r\n putText('Tidig eftermiddag', 1.5)\r\n putText('Sen eftermiddag', 2.5)\r\n putText('Tidig kväll', 3.5)\r\n putText('Sen kväll', 4.5)\r\n putText('Natt', 5.5)\r\n putText('Natt', 6.5)\r\n \r\n /* // English\r\n putText('Morning', -0.5)\r\n putText('Early lunch', 0.5)\r\n putText('Early Afternoon', 1.5)\r\n putText('Late Afternoon', 2.5)\r\n putText('Early evening', 3.5)\r\n putText('Late evening', 4.5)\r\n putText('Night', 5.5)\r\n putText('Night', 6.5)\r\n */\r\n\r\n /*\r\n var time = 6\r\n for(var i = 0; i < SIZE; i++) {\r\n time = (time + Math.floor(24/SIZE)) % 24\r\n if(time === 6) continue // 06.00 is rendered above\r\n if(time < 10) {\r\n putText('0' + time + '.00', i)\r\n\r\n } else {\r\n putText(time + '.00', i)\r\n }\r\n }\r\n */\r\n if(alpha < 1) alpha += 0.8 / fps\r\n}",
"drawBallReleaseBar() {\n const canvas = document.getElementById(\"myCanvas\");\n const ctx = canvas.getContext(\"2d\");\n ctx.beginPath();\n // ctx.rect(releaseBarX, releaseBarY, canvas.width-releaseBarWidth, releaseBarHeight, releaseBarWidth);\n ctx.strokeRect(381, 560, 280, 500);\n // ctx.fillStyle = \"#000000\";\n // ctx.fill();\n ctx.closePath();\n ctx.stroke();\n }",
"function draw() {\n // clear the canvas\n canvas.width = canvas.width;\n drawBlocks();\n drawGrid();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a geo chart of China and adds it to the page | function drawChinaMap() {
const data = google.visualization.arrayToDataTable(CHINA_MAP_TABLE);
const options = {
region: CHINA_REGION,
width: 500,
height: 310,
colorAxis: {colors: ['#4374e0', '#4374e0']}
};
const chart = new google.visualization.GeoChart(document.getElementById(DOM_CONTAINARS_IDS.MAP_CHART));
chart.draw(data, options);
} | [
"function addVolunteersCountryMap(number_of_users_per_country) {\n var number_of_users_per_country_data = []\n var MIN = 1000000;\n var MAX = -1;\n \n for(var i=0;i<number_of_users_per_country.rows.length;i++){\n var c = number_of_users_per_country.rows[i]\n var data_point = {}\n if(country_code_map[c[0].replace(\"&\",\"&\")] !== undefined){\n data_point[\"hc-key\"] = country_code_map[c[0].replace(\"&\",\"&\")].toLowerCase()\n data_point[\"value\"] = parseInt(c[1])\n if(parseInt(c[1]) > MAX) {\n MAX = parseInt(c[1]);\n };\n \n if(parseInt(c[1]) < MIN) {;\n MIN = parseInt(c[1]);\n }\n number_of_users_per_country_data.push(data_point);\n }else {\n console.log(\"Wrong mapping: \" + c[0]);\n }\n }\n\n\n // Initiate the chart\n $('#map').highcharts('Map', {\n\n title : {\n text : ''\n },\n mapNavigation: {\n enabled: true,\n enableMouseWheelZoom: false,\n buttonOptions: {\n verticalAlign: 'bottom',\n align: \"right\"\n }\n },\n\n colorAxis: {\n min: MIN,\n max: MAX\n },\n\n\n series : [{\n data : number_of_users_per_country_data,\n mapData: Highcharts.maps['custom/world'],\n joinBy: 'hc-key',\n name: 'Total Volunteers',\n states: {\n hover: {\n color: '#BADA55'\n }\n },\n dataLabels: {\n enabled: false,\n format: '{point.name}'\n }\n }],\n credits: {\n enabled: true\n } \n }).unbind(document.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel');\n}",
"function show_country_map(ndx, countriesJson) {\n\n //Data dimension for country\n let country_dim = ndx.dimension(dc.pluck('country'));\n \n //Data group for no of suicides per 100k people for each country\n let total_suicide_by_country = country_dim.group().reduceSum(dc.pluck('suicides_100k'));\n\n dc.geoChoroplethChart(\"#map-chart\")\n .width(1000)\n .height(480)\n .dimension(country_dim)\n .group(total_suicide_by_country)\n .colors([\"#f0f9e8\", \"#ccebc5\", \"#a8ddb5\", \"#7bccc4\", \"#43a2ca\", \"#0868ac\"])\n .colorAccessor(function(d) { return d; })\n .colorDomain([1, 6000])\n .overlayGeoJson(countriesJson[\"features\"], \"country\", function(d) {\n return d.properties.name;\n })\n .projection(d3.geo.mercator()\n .center([10, 40])\n .scale(110))\n .useViewBoxResizing(true)\n .title(function(d) {\n if (d.value == undefined) {\n return \"Country: \" + d.key +\n \"\\n\" +\n \"Data Unavailable\";\n }\n else {\n return \"Country: \" + d.key +\n \"\\n\" +\n \"Total Suicides: \" + d.value;\n }\n });\n}",
"function drawProvincesPieChart() {\n const data = new google.visualization.DataTable();\n data.addColumn('string', 'Ethnic Group');\n data.addColumn('number', 'Count');\n data.addRows(CHINA_PROVINCES_TABLE);\n\n const options = {\n title: CHARTS_TITLES.MINORITIES_PIE_CHART,\n width: 700,\n height: 500\n };\n\n const chart = new google.visualization.PieChart(document.getElementById(DOM_CONTAINARS_IDS.DEMOGRAPHIC_CHART));\n chart.draw(data, options);\n}",
"function createMap(){\n\n // Add place searchbar to map\n L.Control.openCageSearch(options).addTo(map);\n\n // Add zoom control (but in top right)\n L.control.zoom({\n position: 'topleft'\n }).addTo(map);\n\n // build easy bar from array of easy buttons\n L.easyBar(buttons).addTo(map);\n\n // Add easy button to pull up splash screen\n L.easyButton('<img src=\"img/noun_Info_1845673_blk.svg\">', function(){\n $('#splash-screen').modal('show');\n },'info window',{ position: 'topleft' }).addTo(map);\n\n //load tile layer\n L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}', {\n\t attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ',\n }).addTo(map);\n\n L.control.attribution({\n position: 'bottomright'\n }).addTo(map);\n //call getData function\n getData(map);\n}",
"function drawTreeMapChart() {\n var area = $(\"#treeMapChart\");\n area.empty();\n\n\n var chart = {\n chart: {\n margin: [0,0,0,0]\n },\n series: [{\n type: \"treemap\",\n layoutAlgorithm: 'squarified',\n data: []\n }],\n title: {\n text: null\n },\n tooltip: {\n formatter: function(){\n return '<strong>' + this.point.name + '</strong>: $ ' + Math.floor(this.point.value * 1000);\n }\n }\n };\n\n var cData = {};\n $.each(current_data, function(key, value) {\n if(current_dimension === key || current_dimension === \"totals\") {\n $.each(value, function (key, value) {\n if(!(value[\"cc\"] in cData)) {\n cData[value[\"cc\"]] = 0;\n }\n\n cData[value[\"cc\"]] += value[\"amount\"];\n });\n }\n });\n\n for (cc in cData) {\n chart.series[0].data.push({\n name: countries[cc][\"full_name\"],\n value: cData[cc]\n });\n }\n\n Highcharts.chart('treeMapChart', chart);\n\n var title = $(\"#treeMapTitle\");\n\n if(current_dimension === \"totals\")\n title.text(\"Absolute Trade Amounts\");\n if(current_dimension === \"exports\")\n title.text(\"Largest Export Partners\");\n if(current_dimension === \"imports\")\n title.text(\"Largest Import Partners\");\n}",
"function initMap() {\n $('#widgetRealTimeMapliveMap .loadingPiwik, .RealTimeMap .loadingPiwik').hide();\n map.addLayer(currentMap.length == 3 ? 'context' : 'countries', {\n styles: {\n fill: colorTheme[currentTheme].fill,\n stroke: colorTheme[currentTheme].bg,\n 'stroke-width': 0.2\n },\n click: function (d, p, evt) {\n evt.stopPropagation();\n if (currentMap.length == 2){ // zoom to country\n updateMap(d.iso);\n } else if (currentMap != 'world') { // zoom out if zoomed in\n updateMap('world');\n } else { // or zoom to continent view otherwise\n updateMap(UserCountryMap.ISO3toCONT[d.iso]);\n }\n },\n title: function (d) {\n // return the country name for educational purpose\n return d.name;\n }\n });\n if (currentMap.length == 3){\n map.addLayer('regions', {\n styles: {\n stroke: colors['region-stroke-color']\n }\n });\n }\n var lastVisitId = -1,\n lastReport = [];\n refreshVisits(true);\n }",
"function createMap() {\n currentTerritory= viewerOptions.territory || 'FXX';\n // viewer creation of type <Geoportal.Viewer>\n // création du visualiseur du type <Geoportal.Viewer>\n // HTML div id, options\n territoriesViewer[currentTerritory]= new Geoportal.Viewer.Default('viewerDiv', OpenLayers.Util.extend(\n OpenLayers.Util.extend({}, viewerOptions),\n // API keys configuration variable set by\n // <Geoportal.GeoRMHandler.getConfig>\n // variable contenant la configuration des clefs API remplie par\n // <Geoportal.GeoRMHandler.getConfig>\n window.gGEOPORTALRIGHTSMANAGEMENT===undefined? {'apiKey':'nhf8wztv3m9wglcda6n6cbuf'} : gGEOPORTALRIGHTSMANAGEMENT)\n );\n if (!territoriesViewer[currentTerritory]) {\n // problem ...\n OpenLayers.Console.error(OpenLayers.i18n('new.instance.failed'));\n return;\n }\n\n territoriesViewer[currentTerritory].addGeoportalLayers([\n 'ORTHOIMAGERY.ORTHOPHOTOS',\n 'GEOGRAPHICALGRIDSYSTEMS.MAPS'],\n {\n });\n territoriesViewer[currentTerritory].getMap().setCenter(\n territoriesViewer[currentTerritory].viewerOptions.defaultCenter,\n territoriesViewer[currentTerritory].viewerOptions.defaultZoom);\n // cache la patience - hide loading image\n territoriesViewer[currentTerritory].div.style[OpenLayers.String.camelize('background-image')]= 'none';\n}",
"function createPixiMap() {\n\n\t///////////////////////////////////////////////////////////////////////////\n\t//////////////////////////// Set the PIXI stage ///////////////////////////\n\t///////////////////////////////////////////////////////////////////////////\n\n\tconst width = 2000; //document.body.clientWidth;\n\tconst mapRatio = 0.5078871;\n\tconst height = Math.round(mapRatio * width);\n\n\t//Create the canvas\n\tvar renderer = new PIXI.autoDetectRenderer(width, height, { backgroundColor : 0xFFFFFF, antialias: true });\n\t//Add to the document\n\tdocument.getElementById(\"chart\").appendChild(renderer.view);\n\trenderer.view.id = \"canvas-map\";\n\n\t//Get the visible size back to 1000 px\n\trenderer.view.style.width = (width*0.5) + 'px';\n\trenderer.view.style.height = (height*0.5) + 'px';\n\n\t//Create the root of the scene graph\n\tvar stage = new PIXI.Stage(0xFFFFFF); //or PIXI.Container(0xFFFFFF);\n\n\t//var container = new PIXI.ParticleContainer(50000, [true, true, false, false, true]);\n\tvar container = new PIXI.Container(0xFFFFFF);\n\tstage.addChild(container);\n\n\t//Create a texture to be used as a Sprite from a white circle png image\n\tconst circleTexture = new PIXI.Texture.fromImage(\"img/circle.png\");\n\n\t///////////////////////////////////////////////////////////////////////////\n\t///////////////////////// Create global variables /////////////////////////\n\t///////////////////////////////////////////////////////////////////////////\n\n\tconst nWeeks = 52;\t\t//Number of weeks in the year\n\tconst startMap = 12;\t//The week of the first map to be drawn\n\n\t//Will save the coordinate mapping\n\tvar loc;\n\n\t//The minimum and maximum values of the layer variable\n\tconst maxL = 0.8,\n\t\t minL = 0; //-0.06;\n\n\t//Will stop the animation\n\tvar animate;\n\tvar stopAnimation = false;\n\n\t//Will save the drawn circle settings\n\tvar dots = [];\n\n\t//Months during those weeks\n\tvar months = [\n\t\t\"January\", //1\n\t\t\"January\", //2\n\t\t\"January\", //3\n\t\t\"January\", //4\n\t\t\"February\", //5\n\t\t\"February\", //6\n\t\t\"February\", //7\n\t\t\"February\", //8\n\t\t\"February & March\", //9\n\t\t\"March\", //10\n\t\t\"March\", //11\n\t\t\"March\", //12\n\t\t\"March & April\", //13\n\t\t\"April\", //14\n\t\t\"April\", //15\n\t\t\"April\", //16\n\t\t\"April & May\", //17\n\t\t\"May\", //18\n\t\t\"May\", //19\n\t\t\"May\", //20\n\t\t\"May\", //21\n\t\t\"May & June\", //22\n\t\t\"June\", //23\n\t\t\"June\", //24\n\t\t\"June\", //25\n\t\t\"June & July\", //26\n\t\t\"July\", //27\n\t\t\"July\", //28\n\t\t\"July\", //29\n\t\t\"July\", //30\n\t\t\"August\", //31\n\t\t\"August\", //32\n\t\t\"August\", //33\n\t\t\"August\", //34\n\t\t\"August & September\", //35\n\t\t\"September\", //36\n\t\t\"September\", //37\n\t\t\"September\", //38\n\t\t\"September & October\", //39\n\t\t\"October\", //40\n\t\t\"October\", //41\n\t\t\"October\", //42\n\t\t\"October\", //43\n\t\t\"October & November\", //44\n\t\t\"November\", //45\n\t\t\"November\", //46\n\t\t\"November\", //47\n\t\t\"November & December\", //48\n\t\t\"December\", //49\n\t\t\"December\", //50\n\t\t\"December\", //51\n\t\t\"December & January\", //52\n\t];\n\n\t///////////////////////////////////////////////////////////////////////////\n\t/////////////////////////////// Create scales /////////////////////////////\n\t///////////////////////////////////////////////////////////////////////////\n\n\tvar xScale = d3.scaleLinear()\n\t\t.domain([1, 500])\n\t\t.range([0, width]);\n\n\tvar yScale = d3.scaleLinear()\n\t\t.domain([1, 250])\n\t\t.range([height, 0]);\n\n\t// var radiusScale = d3.scaleSqrt()\n\t// \t.domain([minL, maxL])\n\t// \t.range([0, 2.5])\n\t// \t.clamp(true);\n\tvar pixelScale = d3.scaleSqrt()\n\t\t.domain([minL, maxL])\n\t\t.range([0, 0.65])\n\t\t.clamp(true);\n\n\tvar opacityScale = d3.scaleLinear()\n\t\t.domain([minL, maxL])\n\t\t.range([1, 0.5]);\n\n\tvar greenColor = d3.scaleLinear()\n\t\t.domain([-0.08, 0.1, maxL])\n\t\t.range([\"#FAECAB\", \"#f2ec82\", \"#0c750c\"]);\n\n\t///////////////////////////////////////////////////////////////////////////\n\t//////////////////////////// Read in the data /////////////////////////////\n\t///////////////////////////////////////////////////////////////////////////\n\n\t//Adjust the title\n\td3.select(\"#week\").text(\"Week \" + (startMap+1) + \", \" + months[startMap] + \", 2016 | loading all 52 weeks...\");\n\n\td3.queue() \n\t\t.defer(d3.csv, \"../../data/nadieh/worldMap_coordinates.csv\")\n\t\t.defer(d3.csv, \"../../data/nadieh/VIIRS/mapData-week-\" + startMap +\".csv\")\n\t\t.await(drawFirstMap);\n\n\tfunction drawFirstMap(error, coordRaw, data) {\n\n\t\t///////////////////////////////////////////////////////////////////////////\n\t\t///////////////////////////// Final data prep /////////////////////////////\n\t\t///////////////////////////////////////////////////////////////////////////\n\t\t\n\t\tif (error) throw error;\n\n\t\tcoordRaw.forEach(function(d) {\n\t\t\td.x = +d.x;\n\t\t\td.y = +d.y;\n\t\t});\n\t\t//Save the variable to global\n\t\tloc = coordRaw;\t\n\n\t\t//Adjust map data and calculate the different circle appearance variables beforehand\n\t\tdata.forEach(function(d) {\n\t\t\td.layer = +d.layer;\n\t\t\td.color = d3.rgb(greenColor(d.layer));\n\t\t\td.opacity = opacityScale(d.layer);\n\t\t\td.size = pixelScale(d.layer);\n\t\t});\n\n\t\t///////////////////////////////////////////////////////////////////////////\n\t\t///////////////////////////// Create first map ////////////////////////////\n\t\t///////////////////////////////////////////////////////////////////////////\n\n\t\t//Draw each circle\n\t\tdata.forEach(function(d,i) {\n\t\t\t//Get the color in the weird hex format\n\t\t\tvar color = (d.color.r << 16) + (d.color.g << 8) + d.color.b;\n\n\t\t\t//Set all characterstics of the circle\n\t\t\tvar dot = new PIXI.Sprite(circleTexture);\n\t\t\tdot.tint = color;\n\t\t\tdot.blendMode = PIXI.blendModes.MULTIPLY;\n\t\t\tdot.anchor.x = 0.5;\n\t\t\tdot.anchor.y = 0.5;\n\t\t\tdot.position.x = xScale(loc[i].x);\n\t\t\tdot.position.y = yScale(loc[i].y);\n\t\t\tdot.scale.x = dot.scale.y = d.size;\n\t\t\tdot.alpha = d.opacity;\n\n\t\t\t//Save the circle\n\t\t\tdots[i] = dot;\n\n\t\t\t//Add to the container\n\t\t\tcontainer.addChild(dot);\n\t\t});//forEach\n\n\t\t//Render to the screen\n\t\tsetTimeout(function() { renderer.render(stage); }, 1000);\n\n\t\t///////////////////////////////////////////////////////////////////////////\n\t\t//////////////////////////// Draw the other maps //////////////////////////\n\t\t///////////////////////////////////////////////////////////////////////////\n\t\t\n\t\tsetTimeout(function() {\n\t\t\tconsole.log(\"reading in maps\");\n\t\t\t//Create a queue that loads in all the files first, before calling the draw function\n\t\t\tvar q = d3.queue();\n\n\t\t\tfor(var i = 0; i < nWeeks; i++) {\n\t\t\t\t//Add each predefined file to the queue\n\t\t\t\tq = q.defer(d3.csv, \"../../data/nadieh/VIIRS/mapData-week-\" + (i+1) + \".csv\");\n\t\t\t}//for i\n\t\t\tq.await(drawAllMaps);\n\t\t}, 1000);\n\n\t}//function drawFirstMap\n\n\tfunction drawAllMaps(error) {\n\n\t\tif (error) throw error;\n\n\t\t///////////////////////////////////////////////////////////////////////////\n\t\t////////////////////////// Final data preparation /////////////////////////\n\t\t///////////////////////////////////////////////////////////////////////////\n\n\t\tconsole.log(\"preparing map data\");\n\n\t\t//Create array that will hold all data\n\t\tvar rawMaps = arguments;\n\t\tmaps = new Array(nWeeks);\n\n\t\t//Save each map in a variable, loop over it to make all variables numeric\n\t\t//From: https://github.com/tungs/breathe and https://breathejs.org/Using-Breathe.html\n\t\t//Using breathe.js to not block the browser during data prep\n\t\tbreathe.times(nWeeks+1, function(i) {\n\t\t\tif(i !== 0) {\n\t\t\t\tvar data = rawMaps[i];\n\t\t\t\tdata.forEach(function(d) {\n\t\t\t\t\td.layer = +d.layer;\n\t\t\t\t\td.color = d3.rgb(greenColor(d.layer));\n\t\t\t\t\td.opacity = opacityScale(d.layer);\n\t\t\t\t\td.size = pixelScale(d.layer);\n\t\t\t\t});\n\t\t\t\t//And save in a new array\n\t\t\t\tmaps[(i-1)] = data;\n\t\t\t}//if\n\t\t})\n\t\t.then(function() {\n\t\t\t//Run after the map data loop above is finished\n\t\t\tconsole.log(\"prepared all maps, starting animation\");\n\n\t\t\t//Delete the arguments since we now have all the data in a new variable\n\t\t\tdelete arguments;\n\t\t\tdelete rawMaps;\n\n\t\t\t//Adjust the appearance of the animation \"button\" below the map\n\t\t\td3.select(\"#stopstart\")\n\t\t\t\t.style(\"cursor\", \"pointer\")\n\t\t\t\t.text(\"stop the animation\");\n\t\t\t//Function attached to the stop/start button\n\t\t\td3.select(\"#stopstart\").on(\"click\", function() { \n\t\t\t\tif(!stopAnimation) {\n\t\t\t\t\tstopAnimation = true;\n\t\t\t\t\td3.select(this).text(\"restart the animation\");\n\t\t\t\t} else {\n\t\t\t\t\tstopAnimation = false;\n\t\t\t\t\td3.select(this).text(\"stop the animation\");\n\t\t\t\t\tanimate();\n\t\t\t\t}//else \n\t\t\t});\n\n\t\t\t//Start the animation\n\t\t\tanimate();\n\t\t});\n\n\t\t// //Old standard loop function\n\t\t// for (var i = 1; i < arguments.length; i++) {\n\t\t// \tvar data = arguments[i];\n\t\t// \tdata.forEach(function(d) {\n\t\t// \t\td.layer = +d.layer;\n\t\t// \t\td.color = d3.rgb(greenColor(d.layer));\n\t\t// \t\td.opacity = opacityScale(d.layer);\n\t\t// \t\td.size = pixelScale(d.layer);\n\t\t// \t});\n\t\t// \t//And save in a new array\n\t\t// \tmaps[(i-1)] = data;\n\t\t// }//for i\n\n\t\t//I could not have done the part below without this great block \n\t\t//https://bl.ocks.org/rflow/55bc49a1b8f36df1e369124c53509bb9\n\t\t//to make it performant, by Alastair Dant (@ajdant)\n\n\t\t//Animate the changes between states over time\n\t\tconst fps = 5;\n\t\tconst tweenTime = 2;\n\t\tconst tweenFrames = fps * tweenTime;\n\n\t\tvar counter = startMap-1, \n\t\t\tframe = 0, \n\t\t\tprogress = 0;\n\n\t\tvar extraText;\n\t\t\n\t\t//Called every requestanimationframe\n\t\tanimate = function() {\n\t\t\t//Track circles between current and next week's map\n\t\t\tvar currColor, nextColor, r, g, b, color;\n\t\t\tvar currSize, nextSize, size;\n\t\t\tvar currOpacity, nextOpacity, opacity;\n\n\t\t\t//Track progress as proportion of frames completed\n\t\t\tframe = ++frame % tweenFrames;\n\t\t\tprogress = (frame / tweenFrames) || 0;\n\t\t\t//console.log(counter, frame, progress);\n\n\t\t\t//Increment state counter once we've looped back around\n\t\t\tif (frame === 0) {\n\t\t\t\tcounter = ++counter % nWeeks;\n\t\t\t\textraText = counter < 4 ? \" | missing data in the North\" : \"\";\n\t\t\t\t//Adjust the title\n\t\t\t\td3.select(\"#week\").text(\"Week \" + (counter+1) + \", \" + months[counter] + \", 2016\" + extraText);\n\t\t\t};\n\n\t\t\t//Assign the maps\n\t\t\tvar currMap = maps[counter],\n\t\t\t\tnextMap = maps[(counter+1) % nWeeks];\n\n\t\t\t//Update scale and color of all circles by\n\t\t\t//Interpolating current state and next state\n\t\t\tfor (var i = 0; i < dots.length; i++) {\n\n\t\t\t\t//Trial and testing has taught me that it's best to \n\t\t\t\t//do all of these values separately\n\t\t\t\tcurrSize = currMap[i].size;\n\t\t\t\tnextSize = nextMap[i].size;\n\t\t\t\t//Interpolate between them\n\t\t\t\tsize = currSize + ((nextSize - currSize) * progress);\n\n\t\t\t\tcurrOpacity = currMap[i].opacity;\n\t\t\t\tnextOpacity = nextMap[i].opacity;\n\t\t\t\t//Interpolate between them\n\t\t\t\topacity = currOpacity + ((nextOpacity - currOpacity) * progress);\n\n\t\t\t\tcurrColor = currMap[i].color;\n\t\t\t\tnextColor = nextMap[i].color;\n\t\t\t\t//Interpolate between them\n\t\t\t\tr = currColor.r + ((nextColor.r - currColor.r) * progress);\n\t\t\t\tg = currColor.g + ((nextColor.g - currColor.g) * progress);\n\t\t\t\tb = currColor.b + ((nextColor.b - currColor.b) * progress);\n\t\t\t\tcolor = (r << 16) + (g << 8) + b;\n\n\t\t\t\t//Finally set the new values on the circle\n\t\t\t\tdots[i].scale.x = dots[i].scale.y = size;\n\t\t\t\tdots[i].tint = color;\n\t\t\t\tdots[i].alpha = opacity;\n\n\t\t\t}//for i\n\n\t\t\t//Cue up next frame then render the updates\n\t\t\trenderer.render(stage);\n\t\t\tif(!stopAnimation) requestAnimationFrame(animate);\n\t\t};\n\n\t\t//animate();\n\n\t}//function drawAllMaps\n\n}//function drawPixiMap",
"function createPieChart(charDataList) {\n var chart = new javafx.scene.chart.PieChart(charDataList)\n chart.setTitle(\"Population of the Continents\")\n\n return chart\n}",
"function worldMap(allData) {\n\n // Creates div for the datamap to reside in\n d3v3.select(\"body\")\n .append(\"div\")\n .attr(\"id\", \"container\")\n .style(\"position\", \"relative\")\n .style(\"width\", \"700px\")\n .style(\"height\", \"450px\")\n .style(\"margin\", \"auto\");\n\n // Gets neccesary info from JSON file\n var data = [];\n for (country in datafile) {\n data.push([datafile[country][\"Country code\"],\n datafile[country][\"Happy Planet Index\"],\n datafile[country][\"GDP/capita ($PPP)\"]]);\n }\n\n // Finds specified values and their minimum and maximum\n var dataset = {};\n var score = data.map(function(obj){ return parseFloat(obj[1]); });\n var minValue = Math.min.apply(null, score);\n var maxValue = Math.max.apply(null, score);\n\n // Adds Colour palette based on minimum and maximum\n var paletteScale = d3v3.scale.linear()\n .domain([minValue,maxValue])\n .range([\"#ece7f2\",\"#2b8cbe\"]);\n\n // Converts dataset to appropriate format\n data.forEach(function(item){\n var country = item[0];\n var happy = item[1];\n var gdp = item[2];\n dataset[country] = { HappyPlanetIndex: happy,\n Gdp: gdp,\n fillColor: paletteScale(happy) };\n });\n\n // Renders map based on dataset\n new Datamap({\n element: document.getElementById(\"container\"),\n projection: \"mercator\",\n fills: { defaultFill: \"#F5F5F5\" },\n data: dataset,\n done: function(data) { data.svg.selectAll(\".datamaps-subunit\")\n .on(\"click\", function(geo) {\n scatterPlot(geo.id, datafile); }\n );\n },\n geographyConfig: {\n borderColor: \"#000000\",\n highlightBorderWidth: 2,\n highlightFillColor: function(geo) { return \"#FEFEFE\"; },\n highlightBorderColor: \"#B7B7B7\",\n popupTemplate: function(geo, data) {\n if (!data) { return [\"<div class='hoverinfo'>\",\n \"<strong>\", geo.properties.name, \"</strong>\",\n \"<br>No data available <strong>\", \"</div>\"].join(\"\"); }\n return [\"<div class='hoverinfo'>\",\n \"<strong>\", geo.properties.name, \"</strong>\",\n \"<br>Happy planet index: <strong>\", data.HappyPlanetIndex,\n \"</strong>\",\n \"<br>Gdp: <strong>\", data.Gdp, \"($PPP)</strong>\",\n \"</div>\"].join(\"\");\n }\n }\n });\n }",
"function CreateRegionCharts(region, title) {\n $.getJSON(\"crimes/6-2013/\" + region + \"/json\", function(data) {\n \n // Raw data\n $(\"#searchRegionData\").html(JSON.stringify(data, null,4));\n \n var crimeData = null;\n \n // Need to check for Further Stats, else we treat it as normal\n if (region === \"Action_Fraud\" || region === \"British_Transport_Police\") {\n var fStatsArray = new Array(data.response.crimes.national);\n crimeData = fStatsArray;\n }\n else {\n crimeData = data.response.crimes.region.areas;\n }\n \n // Loop through adding it to the table\n $.each(crimeData, function() {\n $(\"#searchRegionTable tr:last\").after(\"<tr><td>\" + this.id + \"</td><td>\" + this.total + \"</td></tr>\");\n });\n \n // Creates the region serach charts\n CreateCharts(\n crimeData,\n document.getElementById(\"region-chart-pie\"),\n document.getElementById(\"region-chart-bar\"),\n title,\n \"Region Name\",\n \"Total Including Fraud\");\n }).fail(function(data){\n alert(\"Error Occured. Failed to search for data\");\n });\n}",
"function initializeMap() {\n\n /*\n Instantiate a new Virginia Tech campus map object and set its properties.\n document.getElementById('map') --> Obtains the Google Map style definition\n from the div element with id=\"map\" in TripDetails.xhtml \n */\n map = new google.maps.Map(document.getElementById('map'), {\n zoom: 15,\n center: {lat: 37.227264, lng: -80.420745},\n mapTypeControl: true,\n mapTypeControlOptions: {\n style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,\n position: google.maps.ControlPosition.BOTTOM_LEFT\n },\n mapTypeId: google.maps.MapTypeId.HYBRID\n });\n\n // Show the desired map using the map created above by calling the display() function.\n display();\n\n}",
"function load_graph_to_map(results){\n load_markers(results.locations);\n //draw_lines(results);\n draw_spanning_tree(results);\n\n}",
"function addPolygons() {\n \n if (typeof postcodeAreas !== 'undefined') {\n postcodeAreas.addTo(mymap);\n legend.addTo(mymap);\n } else {\n postcodeAreas = L.geoJSON(postcodeGeoJSON, {\n onEachFeature: onEachFeature,\n }).addTo(mymap);\n legend.addTo(mymap);\n } \n}",
"function myMap() {\r\nlet allcountries = [[61.92410999999999,25.7481511],[-30.559482,\t22.937506],[15.870032,100.992541]];\r\nlet countryselector = [0,1,2];\r\nlet randomselection = countryselector[Math.floor(Math.random() * countryselector.length)];\r\nlet mapProp= {\r\n center:new google.maps.LatLng(allcountries[(randomselection)][0],allcountries[(randomselection)][1]),\r\n zoom:5,\r\n};\r\nlet map=new google.maps.Map(document.getElementById(\"googleMap\"),mapProp);\r\n}",
"function addBaseMap(basemap) {\n //project europe and have it fit within the div\n // +660 to push it over to the right side\n projection.fitSize([width + 660, height], basemap);\n basemapG\n .selectAll(\"path\")\n .data(basemap.features)\n .enter()\n .append(\"path\")\n .attr(\"d\", geoPath)\n .attr(\"stroke\", \"#323232ff\") //stroke color black\n .attr(\"stroke-width\", 0.5)\n .attr(\"fill\", \"#0f0f0f\") //fill color black\n .attr(\"class\", \"europe\"); //set the class of this element to europe\n\n}",
"function mapLoad() {\n\n // define starting center of map as center of contiguous US\n var center = new google.maps.LatLng(39.828182,-98.579144);\n\n // define map options to show roughly entire US\n var mapOptions = {\n zoom: 4,\n center: center\n }\n\n // create new map\n map = new google.maps.Map($('#map-canvas')[0], mapOptions);\n}",
"function displayMap(){\n var coordinates = infoForMap();\n createMap(coordinates);\n}",
"function showcountries() {\r\nlet finland = new Destination(\"Finland\", \"Europe\", 5.5);\r\nlet southAfrica = new Destination(\"South Africa\", \"Africa\",55 );\r\nlet thailand = new Destination(\"Thailand\", \"Asia\", 68);\r\n let allcountries = [[61.92410999999999,25.7481511],[-30.559482,\t22.937506],[15.870032,100.992541]];\r\n\r\ndocument.getElementById('country1').innerHTML = (finland.toString());\r\ndocument.getElementById('country2').innerHTML = (southAfrica.toString());\r\ndocument.getElementById('country3').innerHTML = (thailand.toString());\r\n\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add fuel to player | function collectFuel(){
powerUpSound.play();
playerFuel += 20;
if(playerFuel > 100){
playerFuel = 100;
}
updateFuel();
} | [
"fuelUp(gallons) {\n this.fuelLevel = this.fuelLevel + gallons\n\n //ensures no matter how much gas you add it can be more than the tank's capacity\n if(this.fuelLevel > this.gasTankCapacity) {\n this.fuelLevel = this.gasTankCapacity\n } else if(this.fuelLevel < 0) { // siphon off gas limit\n this.fuelLevel = 0\n }\n }",
"burnFuel(){\n this.fuel -=1;\n }",
"updateThrust() {\n this._thrust = this.fuel * 0.04;\n }",
"drive(miles) {\n let gallonsConsumed = miles/this.mpg\n let milesMax = this.gasTankCapacity * this.mpg\n\n this.fuelLevel = this.fuelLevel - gallonsConsumed\n if(this.fuelLevel < 0) { //can't drive more miles than available fuel\n this.fuelLevel = 0\n }\n\n if(miles > milesMax) {\n this.odometer = this.odometer + milesMax\n } else {\n this.odometer = this.odometer + miles\n }\n }",
"_addWeapons() {\n this.primaryWeapon = this.game.add.existing(new PrimaryWeapon(this.game, this.data[\"weapons\"][\"primary\"], this.type))\n this.primaryWeapon.trackSprite(this)\n\n this.secondaryWeapon = this.game.add.existing(new SecondaryWeapon(this.game, this.data[\"weapons\"][\"secondary\"], this.type))\n this.secondaryWeapon.trackSprite(this, 0, -20)\n }",
"hunt() {\n this.food += 2\n }",
"function addPoo( quantity ) { _playerState[\"Statistics\"][\"TotalPooCollect\"] += quantity; }",
"function initializePlayer(){\n let scale = scalePlayer(mode);\n playerHP = 100;\n playerFuel = 100;\n carsPassed = 0;\n //Player start position\n player = createSprite(playerX,playerY, \n carW / scale, carH / scale);\n player.addImage('start', p00);\n player.addImage('dmg01', p01);\n player.addImage('dmg02', p02);\n player.addImage('dmg03', p03);\n player.addImage('dmg04', p04);\n player.addImage('dmg05', p05);\n player.changeImage('start');\n}",
"accelerate() {\n\t\tthis.velocity.add(this.acceleration)\n\t}",
"function increaseEnergy(){\r\n energy+=50;\r\n}",
"function fuelManage(fuelEvent) {\n\t\n\t$(\"#fuelWgt\").text(presentValues(888.45, 1))\n\n\tswitch (fuelEvent) {\n\n\t\tcase \"Set Full\": //Set Full Fuel button is pressed\n\n\t\t\tsetVolumeWeight(24);\n\t\t\tbreak;\n\n\t\tcase \"Fuel Load\": // clicks on number selector or types in a fuel value\n\n\t\t\tbreak;\n\n\t\tcase \"Volume\":\n\n\t\t\tfuelPref = \"V\";\n\n\t\t\tbreak;\n\n\t\tcase \"Weight\":\n\n\t\t\tfuelPref = \"W\";\n\n\t\t\tbreak;\n\t}\n\n\tfunction setVolumeWeight(fuelAmount) {\n\n\t\tif (fuelPref == \"V\") {\n\n\t\t\tfuelAmount = fuelAmount;\n\n\t\t} else {\n\n\t\t\tfuelAmount = fuelAmount * fuelWeight;\n\n\t\t}\n\t\tconsole.log(fuelAmount);\n\n\t\treturn fuelAmount;\n\t}\n}",
"function Rockets (consuption) {\n this.consuption = consuption;\n this.fuel = 0;\n}",
"increaseSpeed(value){\r\n this.speed += value;\r\n }",
"function C006_Isolation_Yuki_AddRope() {\n\tPlayerClothes(\"Underwear\");\n\tPlayerLockInventory(\"Rope\");\n}",
"function panel_fuel_update(KaTZPit_data){\n\t\n\t// Panneau de gestion fuel et de démarrage APU/Moteur\n\t\n\t\t// Affichage quantité fuel réservoir AV, AR, Total\n\t\tdocument.getElementById('Fuel_AV').innerHTML = KaTZPit_data[\"Fuel_1\"]\n\t\tdocument.getElementById('Fuel_AR').innerHTML = KaTZPit_data[\"Fuel_2\"]\n\t\tdocument.getElementById('Fuel_T').innerHTML = KaTZPit_data[\"Fuel_1\"] + KaTZPit_data[\"Fuel_2\"]\n\t\t\n\n\t\t\t\n\t\t\n\t// Position des Vannes (Fonctionnement des voyants de vannes Droite et Gauche inversé)\n\t// Pour la commande on utilise la commande de type 2 spécifique au KA50\n\t// 3 ordres executes dans DCS ouverturecapot/basculeinter/fermeturecapot\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_V\"],2) ==0) {\n\t\t\t$(\"#F-Vanne-G\").attr('src','images/fuel/FV-Vanne_V_O.gif')\n\t\t\t$(\"#F-Vanne-G\").data('internal-id','20300600')}\n\t\telse {\n\t\t\t$(\"#F-Vanne-G\").attr('src','images/fuel/FV-Vanne_V_F.gif')\n\t\t\t$(\"#F-Vanne-G\").data('internal-id','20300601')}\n\t\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_V\"],1)==0) {\n\t\t\t$(\"#F-Vanne-D\").attr('src','images/fuel/FV-Vanne_V_O.gif')\n\t\t\t$(\"#F-Vanne-D\").data('internal-id','20300800')}\n\t\telse {\n\t\t\t$(\"#F-Vanne-D\").attr('src','images/fuel/FV-Vanne_V_F.gif')\n\t\t\t$(\"#F-Vanne-D\").data('internal-id','20300801')}\n\t\t\t\n\t\t//if (KaTZPit_data[\"APU_V_Fuel\"] ==1) {\n\t\t//\t$(\"#F-Vanne-APU\").attr('src','images/fuel/FV-Vanne_V_O.gif')\n\t\t//\t$(\"#F-Vanne-APU\").data('internal-id','10301000')}\n\t\t//else {\n\t\t//\t$(\"#F-Vanne-APU\").attr('src','images/fuel/FV-Vanne_V_F.gif')\n\t\t//\t$(\"#F-Vanne-APU\").data('internal-id','10301001')}\n\t\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_V\"],3) ==1) {\n\t\t\t$(\"#F-Vanne-X\").attr('src','images/fuel/FV-Vanne_H_O.gif')\n\t\t\t$(\"#F-Vanne-X\").data('internal-id','20301200')}\n\t\telse {\n\t\t\t$(\"#F-Vanne-X\").attr('src','images/fuel/FV-Vanne_H_F.gif')\n\t\t\t$(\"#F-Vanne-X\").data('internal-id','20301201')}\n\n\t// Voyant des Cut Off et du frein de Rotor\n\t\tif (dataread_posit(KaTZPit_data[\"COff\"],2) ==1) {\n\t\t\t$(\"#FV-CutOff-G\").attr('src','images/fuel/FV_Cutoff_Off.gif')\n\t\t\t$(\"#FV-CutOff-G\").data('internal-id','10400900')}\n\t\telse {\n\t\t\t$(\"#FV-CutOff-G\").attr('src','images/fuel/FV_Cutoff_On.gif')\n\t\t\t$(\"#FV-CutOff-G\").data('internal-id','10400901')}\n\t\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"COff\"],1) == 1) {\n\t\t\t$(\"#FV-CutOff-D\").attr('src','images/fuel/FV_Cutoff_Off.gif')\n\t\t\t$(\"#FV-CutOff-D\").data('internal-id','10401000')}\n\t\telse {\n\t\t\t$(\"#FV-CutOff-D\").attr('src','images/fuel/FV_Cutoff_On.gif')\n\t\t\t$(\"#FV-CutOff-D\").data('internal-id','10401001')}\n\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"COff\"],3) == 1) {\n\t\t\t$(\"#FV-RotBrk\").attr('src','images/fuel/FV_RotorBtk_On.gif')\n\t\t\t$(\"#FV-RotBrk\").data('internal-id','10401100')}\n\t\telse {\n\t\t\t$(\"#FV-RotBrk\").attr('src','images/fuel/FV_RotorBtk_Off.gif')\n\t\t\t$(\"#FV-RotBrk\").data('internal-id','10401101')}\n\n\n\t// Fonctionnement des Pompes de Carburant\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_P\"],2) == 1) {\n\t\t\t$(\"#F-Pump-AV\").attr('src','images/fuel/FV_Pump_M.gif')\n\t\t\t$(\"#F-Pump-AV\").data('internal-id','10300100')}\n\t\telse {\n\t\t\t$(\"#F-Pump-AV\").attr('src','images/fuel/FV_Pump_A.gif')\n\t\t\t$(\"#F-Pump-AV\").data('internal-id','10300101')}\n\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_P\"],1) ==1) {\n\t\t\t$(\"#F-Pump-AR\").attr('src','images/fuel/FV_Pump_M.gif')\n\t\t\t$(\"#F-Pump-AR\").data('internal-id','10300200')}\n\t\telse {\n\t\t\t$(\"#F-Pump-AR\").attr('src','images/fuel/FV_Pump_A.gif')\n\t\t\t$(\"#F-Pump-AR\").data('internal-id','10300201')}\n\t\t\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_PE\"],3) ==1) {\n\t\t\t$(\"#F-Pump-IL\").attr('src','images/fuel/FV_Pump_M.gif')\n\t\t\t$(\"#F-Pump-IL\").data('internal-id','10300300')}\n\t\telse {\n\t\t\t$(\"#F-Pump-IL\").attr('src','images/fuel/FV_Pump_A.gif')\n\t\t\t$(\"#F-Pump-IL\").data('internal-id','10300301')}\n\t\t\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_PE\"],2) ==1) {\n\t\t\t$(\"#F-Pump-IR\").attr('src','images/fuel/FV_Pump_M.gif')\n\t\t\t$(\"#F-Pump-IR\").data('internal-id','10300300')}\n\t\telse {\n\t\t\t$(\"#F-Pump-IR\").attr('src','images/fuel/FV_Pump_A.gif')\n\t\t\t$(\"#F-Pump-IR\").data('internal-id','10300301')}\n\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_PE\"],4) ==1) {\n\t\t\t$(\"#F-Pump-EL\").attr('src','images/fuel/FV_Pump_M.gif')\n\t\t\t$(\"#F-Pump-EL\").data('internal-id','10300400')}\n\t\telse {\n\t\t\t$(\"#F-Pump-EL\").attr('src','images/fuel/FV_Pump_A.gif')\n\t\t\t$(\"#F-Pump-EL\").data('internal-id','10300401')}\n\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"Fuel_PE\"],1) ==1) {\n\t\t\t$(\"#F-Pump-ER\").attr('src','images/fuel/FV_Pump_M.gif')\n\t\t\t$(\"#F-Pump-ER\").data('internal-id','10300400')}\n\t\telse {\n\t\t\t$(\"#F-Pump-ER\").attr('src','images/fuel/FV_Pump_A.gif')\n\t\t\t$(\"#F-Pump-ER\").data('internal-id','10300401')}\n\t\t\n\t\t\n\t// RPM Moteur et Rotor\n\t\tEngRpm = dataread_split_2(KaTZPit_data[\"Eng_rpm\"])\n\t\tdocument.getElementById('F-RPM-G').innerHTML = (EngRpm[1]/10).toFixed(0)\n\t\tdocument.getElementById('F-RPM-D').innerHTML = (EngRpm[0]/10).toFixed(0)\n\t\t\n\t\tdocument.getElementById('F-RPM-RO').innerHTML = KaTZPit_data[\"RPM_Rot\"]\n\t\t\n\t// Températures\tAPU\n\n\t\tdocument.getElementById('F-DEG-APU').innerHTML = dataread_split_2(KaTZPit_data[\"APU_Data\"])[0]\n\t\t\n\t// Voyants de l'APU\n\t// On va lire la valeur de chaque voyant dans la chaine \"APU_Voyants\"\n\t// avec la fonction dataread_posit(chaine,position), fonction se trouvant dans function_calcul.js\n\t\n\t\t// Ignition\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"APU_Voyants\"],1) ==1) {\n\t\t\t$(\"#F-Vanne-APU\").attr('src','images/fuel/FV-Vanne_V_O.gif')\n\t\t\t$(\"#F-Vanne-APU\").data('internal-id','20301000')\n\t\t\t$(\"#F-APU-Fuel\").fadeIn()} \n\n\t\telse {\n\t\t\t$(\"#F-Vanne-APU\").attr('src','images/fuel/FV-Vanne_V_F.gif')\n\t\t\t$(\"#F-Vanne-APU\").data('internal-id','20301001')\n\t\t\t$(\"#F-APU-Fuel\").fadeOut()}\n\n\n\t\t// Oil OK\n\t\tif (dataread_posit(KaTZPit_data[\"APU_Voyants\"],2) ==1) {$(\"#F-APU-Oil\").fadeIn()} else {$(\"#F-APU-Oil\").fadeOut()}\n\t\t// RPM OK\n\t\t//if (dataread_posit(KaTZPit_data[\"APU_Voyants\"],3) ==1) {$(\"#APU-V-RPM-OK\").fadeIn()} else {$(\"#APU-V-RPM-OK\").fadeOut()}\n\t\t// RPM High Alarm\n\t\tif (dataread_posit(KaTZPit_data[\"APU_Voyants\"],4) ==1) {$(\"#F-APU-Rpm\").fadeIn()} else {$(\"#F-APU-Rpm\").fadeOut()}\n\n\t\tif (dataread_posit(KaTZPit_data[\"APU_Voyants\"],3) ==1) {\n\t\t\t$(\"#F-APU-ON\").attr('src','images/fuel/FV_APU_ON.gif')\n\t\t\t// Bouton Start type press bouton 1000>0000\n\t\t\t$(\"#F-APU-ON\").data('internal-id','50400701')}\n\n\t\telse {\n\t\t\t// Bouton Stop type press bouton 1000>0000\n\t\t\t$(\"#F-APU-ON\").attr('src','images/fuel/FV_APU_Off.gif')\n\t\t\t$(\"#F-APU-ON\").data('internal-id','50400701')}\n\t\t\n\t\t\n\t\t//if (KaTZPit_data[\"APU_V_1\"] ==1) {$(\"#F-APU-Fuel\").fadeIn()} else {$(\"#F-APU-Fuel\").fadeOut()}\n\t\t//if (KaTZPit_data[\"APU_V_2\"] ==1) {$(\"#F-APU-Oil\").fadeIn()} else {$(\"#F-APU-Oil\").fadeOut()}\n\t\t//if (KaTZPit_data[\"APU_V_4\"] ==1) {$(\"#F-APU-Rpm\").fadeIn()} else {$(\"#F-APU-Rpm\").fadeOut()}\n\n\t// Sub-Panel Demarrage\n\t\tif (dataread_posit(KaTZPit_data[\"Start_V\"],1) == 1) {\n\t\t\t$(\"#F-Start-ON\").attr('src','images/fuel/FV_START.gif')\n\t\t\t// Bouton Start type press bouton 1000>0000\n\t\t\t$(\"#F-Start-ON\").data('internal-id','50400601')}\n\t\telse {\n\t\t\t// Bouton Stop type press bouton 1000>0000\n\t\t\t$(\"#F-Start-ON\").attr('src','images/fuel/FV_START_off.gif')\n\t\t\t$(\"#F-Start-ON\").data('internal-id','50400501')}\n\n\t\t// Alarme si collectif est levé pour éviter demmarage\n\t\t//if (KaTZPit_data[\"RPM_L\"] >70\t|| KaTZPit_data[\"RPM_R\"] >70) {\n\t\t//\tif (KaTZPit_data[\"Collectif\"]>10) {$(\"#FW-Collectif\").fadeIn()} else {$(\"#FW-Collectif\").fadeOut()}\n\t\t//\t}\n\n\t\t//\tSi selecteur = maintenance on efface le repère de selection\n\t\tif (KaTZPit_data[\"Start_Sel\"] == 3) {$(\"#F-1APU2\").fadeOut()} else {$(\"#F-1APU2\").fadeIn()}\n\n\n\t\t// Selecteur 3 positions Eng1, APU, Eng2\n\t\t// Selecteur 3 positions Start, Vent, Crank\t\n\t\tvar sel = 10 \t// Demarrage APU\n\t\tvar typ = 0 \t// Start\n\t\tif (KaTZPit_data[\"Start_Sel\"] == 1 ) {sel=0} \t// Demarrage Eng 1\n\t\tif (KaTZPit_data[\"Start_Sel\"] == 2 ) {sel=20}\t// Demarrage Eng 2\n\n\t\tif (KaTZPit_data[\"Start_Typ\"] == 1 ) {typ=10}\t// Venting\n\t\tif (KaTZPit_data[\"Start_Typ\"] == 2 ) {typ=20}\t// Cranking\n\t\t\n\t\tStart_Switch(sel,typ)\n\n\t// EEG Moteur\n\t\tif (dataread_posit(KaTZPit_data[\"E_AC_V\"],6) ==1) {\n\t\t\t$(\"#F-EEG-G\").attr('src','images/fuel/FV_EEG.gif')\n\t\t\t$(\"#F-EEG-G\").data('internal-id','20400100')}\n\t\telse {\n\t\t\t$(\"#F-EEG-G\").attr('src','images/fuel/FV_EEG_Off.gif')\n\t\t\t$(\"#F-EEG-G\").data('internal-id','20400101')}\n\t\t\t\n\t\tif (dataread_posit(KaTZPit_data[\"E_AC_V\"],5) ==1) {\n\t\t\t$(\"#F-EEG-D\").attr('src','images/fuel/FV_EEG.gif')\n\t\t\t$(\"#F-EEG-D\").data('internal-id','20400300')}\n\t\telse {\n\t\t\t$(\"#F-EEG-D\").attr('src','images/fuel/FV_EEG_Off.gif')\n\t\t\t$(\"#F-EEG-D\").data('internal-id','20400301')}\n\t\t\n}",
"function addLuckToSpeed (luckySign, luckModifier) {\n\tvar addSpeed = 0;\n\tif (luckySign.luckySign != undefined && luckySign.luckySign === \"Wild child\" && luckModifier == 1){\n\t\taddSpeed = 5;\n\t}\n\telse if (luckySign.luckySign != undefined && luckySign.luckySign === \"Wild child\" && luckModifier == 2){\n\t\taddSpeed = 10;\n\t}\n\telse if (luckySign.luckySign != undefined && luckySign.luckySign === \"Wild child\" && luckModifier == 3){\n\t\taddSpeed = 15;\n\t}\n\treturn addSpeed;\n}",
"function buyTick(){\n if(nutrients >= tickCost && minions < maxMinions)\n {\n hatch.play();\n\n ticks += 1;\n nutrients -= tickCost;\n\n //Update labels and calculate new values\n performCalculations();\n updateLabels();\n\n tickArray.push(new Tick());\n\n\n }\n}",
"spawnFruit(x,y,velX,velY) {\r\n let random = Phaser.Math.Between(0, 9);\r\n let spawnPointX = x;\r\n let spawnPointY = y;\r\n let fruit = this.physics.add.sprite(spawnPointX, spawnPointY, 'fruit' + random).setInteractive();\r\n fruit.name = 'fruit';\r\n fruit.setScale(Phaser.Math.Between(2.0, 3.0));\r\n fruit.body.setVelocityX(Phaser.Math.Between(-velX + 500, -velX - 500));\r\n fruit.body.setVelocityY(Phaser.Math.Between(-velY + 500, -velY - 500));\r\n }",
"function addInventory() {\n\n\t//Lets manager identify which item to credit\n\tinquirer\n\t\t.prompt ({\n\t\t\tname: \"restock_product\",\n\t\t\ttype: \"input\",\n\t\t\tmessage: \"Type the Id of the product you want to re-stock:\"\n\t\t})\n\t\t//Initiates database credit process\n\t\t.then(function(answer) {\n\n\t\t\t//Queries database and increases quantity by +5\n\t\t\tconnection.query(\"UPDATE products SET quantity = quantity + 5 WHERE id =\"+answer.restock_product, function(err, res) {\n\t\t\tif (err) throw err;\n\n\t\t\t//Returns the updated inventory table\n\t\t\tallInventory();\n\t\t\t})\n\t\t}\n\t)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set default stairs model for empty stairs | defaultStairsModel() {
return {
stair: {
label: this.$translate.instant(
'telecom_pack_migration_building_details_none',
),
value: STAIR_FLOOR.unknown,
},
floors: [
{
label: this.$translate.instant(
'telecom_pack_migration_building_details_none',
),
value: STAIR_FLOOR.unknown,
},
],
};
} | [
"handleSetStatesToDefault() {\n this.setState({\n gridData: {},\n gridLoadToggle: false,\n noError: true,\n currentStudent: {},\n currentProject: {},\n errorMessage: \"\",\n showStudent: false,\n showProject: false,\n studentPriorityValue: 20,\n helpToggle: false,\n legendToggle: false\n });\n }",
"setSurroundModeToStandard() {\n this._setSurroundMode(\"s_standard\");\n }",
"function resetChairColors() {\n // change the \"chosenColor\" variable\n model.changeChosenColorVar(model.defaultColor);\n // change chair object\n model.resetChairToDefault();\n // colorize chair parts based on newly changed chair object\n view.colorizeSvg();\n // highlight the default color on the color palette\n\n view.changeActiveClass(\n document.querySelector(`.colors .color[data-color=\"${model.defaultColor}\"]`)\n );\n}",
"function makeDefaultedModel() {\n const model = {};\n spec.parameters.layout.forEach((id) => {\n const paramSpec = spec.parameters.specs[id];\n let modelValue;\n if (paramSpec.data.type === 'struct') {\n if (paramSpec.data.constraints.required) {\n modelValue = lang.copy(paramSpec.data.defaultValue);\n } else {\n modelValue = paramSpec.data.nullValue;\n }\n } else {\n modelValue = lang.copy(paramSpec.data.defaultValue);\n }\n model[id] = modelValue;\n });\n return model;\n }",
"_onResetDefaults(event) {\n event.preventDefault();\n game.settings.set(\"core\", DrawingsLayer.DEFAULT_CONFIG_SETTING, {});\n this.object.data = canvas.drawings._getNewDrawingData({});\n this.render();\n }",
"function commonSelectDefault(obj) {\r\n var modelName = obj.value;\r\n var subArray = inputDefaults[modelName];\r\n var subArrayLength = subArray.length;\r\n for (var i = 0; i < subArrayLength; ++i) {\r\n // Change parameter values into default ones\r\n document.getElementById(subArray[i][0]).value = subArray[i][1] ;\r\n }\r\n\r\n // Default speed setting\r\n // For discrete-time model, default speed is set as \"full-time\"\r\n // For continuous-time model, default speed is according to the speedDefault array\r\n if(speedDefaults[modelName][0] == \"discrete\") {\r\n // Discrete-time situation\r\n document.getElementById(speedDefaults[modelName][1]).checked = true;\r\n }\r\n else {\r\n // Continuous-time situation\r\n document.getElementById(speedDefaults[modelName][1]).checked = true;\r\n }\r\n}",
"function resetChair() {\n // color the chair with default color\n resetChairColors();\n view.renderSelectedColors();\n // remove all features\n view.renderFeatures();\n // remove highlight on all options (features)\n view.resetChosenOptions();\n // clear the selected features ul\n view.resetSelectedFeatures();\n}",
"function makeDefaultDataset() {\r\n fillDefaultDataset(dataOrigin);\r\n fillDefaultDataset(dataAsylum);\r\n}",
"function init_model () {\n setup_board ();\n setup_houses ();\n setup_clues ();\n}",
"function reset() {\n svg_g.selectAll(\".brush\").call(brush.move, null);\n svg_g.selectAll(\".brushMain\").call(brush.move, null);\n }",
"function setSequenceLinkDefaultFlow(obj) {\n\t\t\n\t\t myDiagram.startTransaction(\"setSequenceLinkDefaultFlow\");\n\t\t var model = myDiagram.model;\n\t\t model.setDataProperty(obj.data, \"isDefault\", true);\n\t\t // Set all other links from the fromNode to be isDefault=null\n\t\t obj.fromNode.findLinksOutOf().each(function(link) {\n\t\t if (link !== obj && link.data.isDefault) {\n\t\t model.setDataProperty(link.data, \"isDefault\", null);\n\t\t }\n\t\t });\n\t\t myDiagram.commitTransaction(\"setSequenceLinkDefaultFlow\");\n\t\t }",
"function resetRack() {\n rack.bestScore = 0;\n rack.bestAnswers = [];\n}",
"setSurroundModeToAuto() {\n this._setSurroundMode(\"s_auto\");\n }",
"clear() {\n // From wfactory_model.js:createDefaultSelectedIfEmpty()\n this.categoryList = [];\n this.flyout = new ListElement(ListElement.TYPE_FLYOUT);\n this.selected = this.flyout;\n this.xml = Blockly.Xml.textToDom('<xml></xml>');\n }",
"static withInitialScope() {\n const initialModel = this.getInitialModel();\n\n if (this._schema !== initialModel._schema || this._schemaDelimiter !== initialModel._schemaDelimiter) {\n return initialModel.withSchema({\n schema: this._schema,\n schemaDelimiter: this._schemaDelimiter,\n });\n }\n\n return initialModel;\n }",
"setSurroundModeToMatrix() {\n this._setSurroundMode(\"s_matrix\");\n }",
"function set_new_patron_defaults(prs) {\n if (!$scope.patron.passwd) {\n // passsword may originate from staged user.\n $scope.generate_password();\n }\n $scope.hold_notify_type.phone = true;\n $scope.hold_notify_type.email = true;\n $scope.hold_notify_type.sms = false;\n\n // staged users may be loaded w/ a profile.\n $scope.set_expire_date();\n\n if (prs.org_settings['ui.patron.default_ident_type']) {\n // $scope.patron needs this field to be an object\n var id = prs.org_settings['ui.patron.default_ident_type'];\n var ident_type = $scope.ident_types.filter(\n function(type) { return type.id() == id })[0];\n $scope.patron.ident_type = ident_type;\n }\n if (prs.org_settings['ui.patron.default_inet_access_level']) {\n // $scope.patron needs this field to be an object\n var id = prs.org_settings['ui.patron.default_inet_access_level'];\n var level = $scope.net_access_levels.filter(\n function(lvl) { return lvl.id() == id })[0];\n $scope.patron.net_access_level = level;\n }\n if (prs.org_settings['ui.patron.default_country']) {\n $scope.patron.addresses[0].country = \n prs.org_settings['ui.patron.default_country'];\n }\n }",
"function resetGame() {\n ships._ships = [];\n currentState = states.Splash;\n score = 0;\n shipGap = shipGapMax;\n}",
"initSnake() {\n\t\tconst {r, c} = this.getRandomEmptyBoardPiece();\n\t\tthis.snake.push({r, c});\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A CpuSlice represents a slice of time on a CPU. | function CpuSlice(cat, title, colorId, start, args, opt_duration) {
Slice.apply(this, arguments);
this.threadThatWasRunning = undefined;
this.cpu = undefined;
} | [
"function ThreadTimeSlice(thread, schedulingState, cat,\n start, args, opt_duration) {\n Slice.call(this, cat, schedulingState,\n this.getColorForState_(schedulingState),\n start, args, opt_duration);\n this.thread = thread;\n this.schedulingState = schedulingState;\n this.cpuOnWhichThreadWasRunning = undefined;\n }",
"function ThreadSlice(cat, title, colorId, start, args, opt_duration,\n opt_cpuStart, opt_cpuDuration, opt_argsStripped,\n opt_bind_id) {\n Slice.call(this, cat, title, colorId, start, args, opt_duration,\n opt_cpuStart, opt_cpuDuration, opt_argsStripped, opt_bind_id);\n // Do not modify this directly.\n // subSlices is configured by SliceGroup.rebuildSubRows_.\n this.subSlices = [];\n }",
"function Cpu(kernel, number) {\n if (kernel === undefined || number === undefined)\n throw new Error('Missing arguments');\n this.kernel = kernel;\n this.cpuNumber = number;\n this.slices = [];\n this.counters = {};\n this.bounds_ = new tr.b.Range();\n this.samples_ = undefined; // Set during createSubSlices\n\n // Start timestamp of the last active thread.\n this.lastActiveTimestamp_ = undefined;\n\n // Identifier of the last active thread. On Linux, it's a pid while on\n // Windows it's a thread id.\n this.lastActiveThread_ = undefined;\n\n // Name and arguments of the last active thread.\n this.lastActiveName_ = undefined;\n this.lastActiveArgs_ = undefined;\n }",
"function Cpu(kernel, number) {\n if (kernel === undefined || number === undefined)\n throw new Error('Missing arguments');\n this.kernel = kernel;\n this.cpuNumber = number;\n this.slices = [];\n this.counters = {};\n this.bounds = new tr.b.Range();\n this.samples_ = undefined; // Set during createSubSlices\n\n // Start timestamp of the last active thread.\n this.lastActiveTimestamp_ = undefined;\n\n // Identifier of the last active thread. On Linux, it's a pid while on\n // Windows it's a thread id.\n this.lastActiveThread_ = undefined;\n\n // Name and arguments of the last active thread.\n this.lastActiveName_ = undefined;\n this.lastActiveArgs_ = undefined;\n }",
"slice(begin, end) {\n const size = this.size();\n const b = resolveBegin(begin, size);\n const e = resolveEnd(end, size);\n\n if (b === 0 && e === size ) {\n return this;\n }\n\n const events = [];\n for (let i = b; i < e; i++) {\n events.push(this.at(i));\n }\n\n return new TimeSeries({ name: this._name,\n index: this._index,\n utc: this._utc,\n meta: this._meta,\n events });\n }",
"function testSlice() {\n checkSlice();\n}",
"function sliceArray(anim, beginSlice, endSlice) {\n // Add your code below this line\n return anim.slice(beginSlice, endSlice);\n // Add your code above this line\n}",
"pie() {\n for (var i = 1; i <= this.slices; i++) {\n push();\n rotate(TWO_PI * i / this.slices);\n this.pieces.push(new Slice(this.size, this.slices, this.org));\n pop();\n }\n }",
"function slice () {\n if (settings.vshrink || settings.hshrink) {\n var slices = {};\n if (settings.vshrink) {\n slices['rows'] = getRows();\n }\n if (settings.hshrink) {\n slices['cols'] = getCols();\n }\n return slices;\n }\n else {\n return null;\n }\n }",
"function calcSlicedPart() {\n return slicedPart = innerBoxWidth % containerWidth;\n }",
"function getCrossSlice(startSlice,endSlice)\n{\n var sliceString;\n\n //trying to move z slices from the top towards the upper right corner\n //start from x_slice1 and land on x_slice2 or x_slice3, or start from\n //x_slice2 or x_slice3 and land on x_slice1\n if(((startSlice === \"x_slice1\") && ((endSlice === \"x_slice2\") || (endSlice === \"x_slice3\")))\n || (((startSlice === \"x_slice2\") || (startSlice === \"x_slice3\")) \n && ((endSlice === \"x_slice2\") || (endSlice === \"x_slice1\")))){\n if((startX < .531) && (startX > -.106) && (startY < .383) && (startY > .227)\n && (endX < .531) && (endX > -.106) && (endY < .383) && (endY > .227)){\n sliceString = \"z_slice1\";\n //window.alert(\"In here z1\"); \n }\n else if((startX < .367) && (startX > -.309) && (startY < .422) && (startY > .273)\n && (endX < .367) && (endX > -.309) && (endY < .422) && (endY > .273)){\n sliceString = \"z_slice2\";\n //window.alert(\"In here z2\"); \n }\n else if((startX < .145) && (startX > -.484) && (startY < .465) && (startY > .305)\n && (endX < .145) && (endX > -.484) && (endY < .465) && (endY > .305)){\n sliceString = \"z_slice3\";\n //window.alert(\"In here z3\"); \n } \n }//end z slices\n //y slices right side\n if(((startSlice === \"x_slice1\") && ((endSlice === \"x_slice2\") || (endSlice === \"x_slice3\")))\n || (((startSlice === \"x_slice2\") || (startSlice === \"x_slice3\")) && \n ((endSlice === \"x_slice2\") || (endSlice === \"x_slice1\")))\n ){\n if((startX < .563) && (startX > .059) && (startY < .344) && (startY > -.012)\n && (endX < .563) && (endX > .059) && (endY < .344) && (endY > -.012)){\n sliceString = \"y_slice1\";//right side \n //window.alert(\"In here y1 right\");\n } \n else if((startX < .574) && (startX > .051) && (startY < .098) && (startY > -.277)\n && (endX < .574) && (endX > .051) && (endY < .098) && (endY > -.277)){\n sliceString = \"y_slice2\";//right side \n //window.alert(\"In here y2 right\");\n } \n else if((startX < .578) && (startX > .051) && (startY < -.152) && (startY > -.538)\n && (endX < .578) && (endX > .051) && (endY < -.152) && (endY > -.538)){\n sliceString = \"y_slice3\";//right side \n //window.alert(\"In here y3 right\");\n } \n }//end y right slices\n //y slices left side\n if(((startSlice === \"z_slice1\") && ((endSlice === \"z_slice2\") || (endSlice === \"z_slice3\")))\n || (((startSlice === \"z_slice2\") || (startSlice === \"z_slice3\")) && \n ((endSlice === \"z_slice2\") || (endSlice === \"z_slice1\")))\n ){\n if((startX < .043) && (startX > -.576) && (startY < .332) && (startY > -.027)\n && (endX < .043) && (endX > -.576) && (endY < .332) && (endY > -.027)){\n sliceString = \"y_slice1\";//right side \n //window.alert(\"In here y1 left\");\n } \n else if((startX < .051) && (startX > -.512) && (startY < .078) && (startY > -.28)\n && (endX < .051) && (endX > -.512) && (endY < .078) && (endY > -.28)){\n sliceString = \"y_slice2\";//right side \n //window.alert(\"In here y2 left\");\n } \n else if((startX < .051) && (startX > -.512) && (startY < -.179) && (startY > -.531)\n && (endX < .051) && (endX > -.512) && (endY < -.179) && (endY > -.531)){\n sliceString = \"y_slice3\";//right side \n //window.alert(\"In here y3 left\");\n } \n }//end y left slices\n return sliceString;\n}",
"function arraySlice(){\r\nvar sArray8 = array8.slice(\"lName\");\r\nconsole.log(\"Slice array8: \" + sArray8);\r\n} // Result - Syntax error",
"function sliceMovementStop(x,y)\n{\n endX = x;\n endY = y;\n var startSlice = getSliceRange(startX,startY).slice;\n var endSlice = getSliceRange(endX,endY).slice;\n var movDir;\n var degreeAdd;\n var sliceString;\n var sliceArr;\n var results = {};\n/*\n window.alert(\"Start Slice \" + startSlice);\n window.alert(\"End Slice \" + endSlice);\n\n window.alert(\"start X \" + startX);\n window.alert(\"start Y \" + startY);\n window.alert(\"end X \" + endX); \n window.alert(\"end Y \" + endY);\n*/ \n if(startSlice === endSlice){\n if(endY > startY){//moved up\n movDir = -1;//up towards upper left corner\n degreeAdd = -3;\n }\n else if((endX < startX) && (endY > 0)){//top of cube move\n movDir = -1;//up towards upper left corner\n degreeAdd = -3;\n }\n else if((endX > startX) && (endY > 0)){//top of cube move\n movDir = 1;//down towards bottom right corner\n degreeAdd = 3;\n }\n else if(endY < startY){//moved down\n movDir = 1;//down towards bottom right corner\n degreeAdd = 3;\n }\n sliceString = endSlice; \n }\n //slices compositions\n else{\n sliceString = getCrossSlice(startSlice,endSlice);\n //window.alert(\"In here \" + sliceString);\n if((sliceString === \"z_slice1\") || (sliceString === \"z_slice2\") || (sliceString === \"z_slice3\")){\n if(startSlice === \"x_slice1\"){\n movDir = -1;//down towards bottom right corner\n degreeAdd = -3; \n }\n else{\n movDir = 1;//down towards bottom right corner\n degreeAdd = 3;\n }\n }\n else if((sliceString === \"y_slice1\") || (sliceString === \"y_slice2\") || (sliceString === \"y_slice3\")){\n //window.alert(\"In here\");\n if((startSlice === \"x_slice1\") || (startSlice === \"z_slice3\")){\n movDir = 1;//spin towards right\n degreeAdd = 3; \n }\n else{\n movDir = -1;//spin towards left\n degreeAdd = -3;\n } \n }\n }//end else slices compositions\n\n sliceArr = sliceArrayIndexs(sliceString);//in slices.js\n\n results.movDir = movDir;\n results.degreeAdd = degreeAdd;\n results.sliceString = sliceString;\n results.sliceArr = sliceArr;\n\n return results;\n}",
"function slice(){\n\tvar aku = 'saya belajar di pasar';\n\tconsole.log(aku.slice(5));\n\tconsole.log(aku.slice(5,13));\n\tconsole.log(aku.slice(5,6));\n}",
"doCPUWork(time) {\n const process = this.peek();\n process.executeProcess(time);\n this.manageTimeSlice(process, time);\n }",
"manageTimeSlice(currentProcess, time) {\n // manageTimeSlice() is only for handling a running process. If blocking process, handle it differently\n if (currentProcess.isStateChanged()) {\n this.quantumClock = 0; // so that the next process that gets dequeued starts off with its full time.\n return;\n }\n // otherwise it is a running process\n this.quantumClock += time;\n // check to see if the process has used up all of its alloted time\n if (this.quantumClock >= this.quantum) {\n // reset quantumClock for next process\n this.quantumClock = 0;\n // dequeueing because either the process is finished and needs to be removed from scheduler, or did not finish and needs to put in another priority queue\n const process = this.dequeue();\n\n if (!process.isFinished()) {\n this.scheduler.handleInterrupt(\n this,\n process,\n SchedulerInterrupt.LOWER_PRIORITY\n );\n }\n }\n }",
"function loadSliceMesh( slices ) {\n\tvar ret = new Array()\n\t\n\tfor( s = 0; s < N_SLICES; s++ ) {\n\t\tvar verts = gl.createBuffer()\n\t\tgl.bindBuffer( gl.ARRAY_BUFFER, verts )\n\t\t\n\t\tvar indis = gl.createBuffer()\n\t\tgl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indis )\n\t\t\n\t\tvar tex = genTex2d();\n\t\t\n\t\tgl.vertexAttribPointer( positionLoc2d, 3, gl.FLOAT, false, vertSize, 0 )\n\t\tgl.vertexAttribPointer( uvLoc2d, 2, gl.FLOAT, false, vertSize, 16 )\n\t\tnIndis = genMesh2dSlice( texData, slices[s], verts, indis, tex );\n\t\t\n\t\tret[s] = [verts, indis, tex];\n\t\t//sliceMesh.push( [ verts, indis, tex ] )\n\t}\n\t\n\treturn ret\n}",
"generateCPU() {\n return {\n /** 16 bit counter to iterate through the memory array */\n programCounter: 512,\n /** array representing the register which is 8bit data register and 16 bloc of 8bit long */\n register: new Uint8Array(16),\n /** 16 bit counter to iterate through the Memory array (called I in most documentation) */\n I: 0,\n //array representing the stack\n stack: new Uint16Array(16),\n /** stack jump counter to iterate through the stack array must not go past 15 since the stack is 16 indexes long*/\n stackJumpCounter: 0,\n /** */\n delayTimer: 0,\n /** */\n soundTimer: 0\n }\n }",
"get subdivision() {\n return new _Ticks.TicksClass(this.context, this._subdivision).toSeconds();\n }",
"createSliceSize() {\n if (this.frames % 420 === 0) {\n let Sy = 0\n let SminGap = 0\n let SmaxGap = this.canvasSize.w - 30\n let SGap = Math.floor(Math.random() * (SmaxGap - SminGap + 1) + SminGap)\n this.sliceSize.push(new Slicebar(this.ctx, SGap, Sy, 35, 94, '../images/sliceSize.png'))\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
WAYPOINTS the user typed input for the waypoint search. forward the input to start a query | function handleSearchWaypointInput(e) {
var waypointElement = $(e.currentTarget).parent().parent();
//index of the waypoint (0st, 1st 2nd,...)
var index = waypointElement.attr('id');
clearTimeout(typingTimerWaypoints[index]);
if (e.keyIdentifier != 'Shift' && e.currentTarget.value.length != 0) {
var input = e.currentTarget.value;
waypointElement.attr('data-searchInput', input);
typingTimerWaypoints[index] = setTimeout(function() {
//empty search results
var resultContainer = waypointElement.get(0).querySelector('.searchWaypointResults');
while (resultContainer && resultContainer.hasChildNodes()) {
resultContainer.removeChild(resultContainer.lastChild);
}
//request new results
theInterface.emit('ui:searchWaypointRequest', {
query: input,
wpIndex: index,
searchIds: waypointElement.get(0).getAttribute('data-search')
});
}, DONE_TYPING_INTERVAL);
}
} | [
"function handleSearchAgainWaypointClick(e) {\n var wpElement = $(e.currentTarget).parent();\n // make input field selectable\n //var selectedDiv = $(e.currentTarget).parent()[0];\n //var thisDiv = selectedDiv.className\n //var myDiv = thisDiv.replace(/ /g,\".\");\n //$('.'+myDiv).css('cursor', 'default');\n //$('.'+myDiv).css('pointer-events', 'auto');\n var index = wpElement.attr('id');\n var addrElement = wpElement.get(0).querySelector('.address');\n var featureId = addrElement.getAttribute('id');\n var layer = addrElement.getAttribute('data-layer');\n var resultComponent = wpElement.get(0).querySelector('.waypointResult');\n $(resultComponent).hide();\n var searchComponent = wpElement.get(0).querySelector('.guiComponent');\n $(searchComponent).show();\n var searchResults = wpElement.attr('data-search');\n if (searchResults) {\n //this waypoint was created by a search input. Only then it is useful to view previous search results\n //therefore we have to re-calculate the search\n //index of the waypoint (0st, 1st 2nd,...)\n var input = wpElement.attr('data-searchInput');\n //empty search results\n invalidateWaypointSearch(index);\n var resultContainer = wpElement.get(0).querySelector('.searchWaypointResults');\n while (resultContainer && resultContainer.hasChildNodes()) {\n resultContainer.removeChild(resultContainer.lastChild);\n }\n //request new results\n theInterface.emit('ui:searchWaypointRequest', {\n query: input,\n wpIndex: index,\n searchIds: null\n });\n } else {\n resultComponent.removeChild(addrElement);\n var responses = searchComponent.querySelector('.responseContainer');\n if (responses) {\n $(responses).hide();\n }\n }\n //remove old waypoint marker\n theInterface.emit('ui:searchAgainWaypoint', {\n waypointFeature: featureId,\n waypointLayer: layer,\n wpIndex: index\n });\n }",
"function handleSearchPoiInput(e) {\n clearTimeout(typingTimerSearchPoi);\n if (e.keyIdentifier != 'Shift' && e.currentTarget.value.length != 0) {\n typingTimerSearchPoi = setTimeout(function() {\n //empty search results\n var resultContainer = document.getElementById('fnct_searchPoiResults');\n while (resultContainer.hasChildNodes()) {\n resultContainer.removeChild(resultContainer.lastChild);\n }\n var numResults = $('#zoomToPoiResults').get(0);\n while (numResults.hasChildNodes()) {\n numResults.removeChild(numResults.lastChild);\n }\n searchPoiAtts[3] = e.currentTarget.value;\n var lastSearchResults = $('#searchPoi').attr('data-search');\n theInterface.emit('ui:searchPoiRequest', {\n query: e.currentTarget.value,\n nearRoute: searchPoiAtts[0] && routeIsPresent,\n maxDist: searchPoiAtts[1],\n distUnit: searchPoiAtts[2],\n lastSearchResults: lastSearchResults\n });\n }, DONE_TYPING_INTERVAL);\n }\n }",
"function parseWaypoints(waypoints){\n var wpArray=[]\n \twaypoints.forEach(function(WP){\n \t\twpArray.push({\n \t\t\tlocation: \"\" + WP.location.A + \" \" + WP.location.F\n \t\t})\n \t})\n return wpArray;\n }",
"function createWaypoints(result) {\n\n // turn overview path of route into polyline\n var pathPolyline = new google.maps.Polyline({\n path: result.routes[0].overview_path\n });\n\n // get points at intervals of 85% of range along overview path of route\n var points = pathPolyline.GetPointsAtDistance(0.85 * range);\n\n // iterate over these points\n for (var i = 0, n = points.length; i < n; i++) {\n\n // find the closest charging station to that point\n var closeStation = getClosestStation(points[i]);\n\n // create waypoint at that station\n var newWaypoint = {\n location: closeStation.latlng,\n stopover: true\n };\n\n // add it to the waypoints array\n waypoints.push(newWaypoint);\n\n // add station info to station stops array\n stationStops.push(closeStation);\n\n // create invisible marker\n var marker = new google.maps.Marker({\n position: closeStation.latlng,\n map: map,\n icon: 'img/invisible.png',\n zIndex: 3,\n });\n\n // add to markers array\n markers.push(marker);\n }\n}",
"function directionsParseAddressAndValidate() {\n // part 0 - cleanup\n\n // clear the Feature identification, as they likely did not use a Feature search and will likely need to go through a Did You Mean autocomplete sorta thing\n // if they did mean it, this gets populated in the \"features\" switch case below\n var form = $('#page-directions');\n form.find('input[name=\"feature_gid\"]').val('');\n form.find('input[name=\"feature_type\"]').val('');\n\n // clear any prior directions text, map lines, etc.\n directionsClear();\n\n // part 1 - simple params we can extract now\n // we use these to fine-tune some of the routing params, e.g. re-geocoding opints to their nearest parking lot; see part 3\n // prior versions of this app and website, had selectors for some of these options; but we decided to simplify and hardcode the defaults\n // historical note: that's why Bike is called bike_advanced; prior versions had us select bicycle difficulty\n\n var via = form.find('div.directions_buttons img[data-selected=\"true\"]').attr('data-mode');\n var tofrom = \"to\";\n var prefer = \"recommended\";\n\n // part 2 - figure out the origin\n\n // can be any of address geocode, latlon already properly formatted, current GPS location, etc.\n // this must be done before the target is resolved (below) because resolving the target can mean weighting based on the starting point\n // e.g. directions to parks/reservations pick the closest gate or parking lot to our starting location\n // this also has our bail conditions, e.g. an address search that cannot be resolved, a feature name that is ambiguous, ... look for \"return\" statements below\n\n // we must do some AJAX for the target location and the origin location, but it must be done precisely in this sequence\n var sourcelat, sourcelng;\n var addresstype = form.find('select[name=\"origin\"]').val();\n var address = form.find('input[name=\"address\"]').val();\n switch (addresstype) {\n // GPS origin: simplest possible case: lat and lng are already had\n case 'gps':\n sourcelat = MARKER_GPS.getLatLng().lat;\n sourcelng = MARKER_GPS.getLatLng().lng;\n break;\n // GEOCODE origin: but a hack (of course), that it can be either an address or else GPS coordinates in either of 2 formats\n case 'geocode':\n if (! address) return navigator.notification.alert('Please enter an address, city, or landmark.', null, 'Enter an Address');\n var is_decdeg = /^\\s*(\\d+\\.\\d+)\\s*\\,\\s*(\\-\\d+\\.\\d+)\\s*$/.exec(address); // regional assumption in this regular expression: negative lng, positive lat\n var is_gps = /^\\s*N\\s+(\\d+)\\s+(\\d+\\.\\d+)\\s+W\\s+(\\d+)\\s+(\\d+\\.\\d+)\\s*$/.exec(address); // again, regional assumption that we're North and West\n if (is_decdeg) {\n sourcelat = parseFloat( is_decdeg[1] );\n sourcelng = parseFloat( is_decdeg[2] );\n } else if (is_gps) {\n var latd = parseFloat( is_gps[1] );\n var latm = parseFloat( is_gps[2] );\n var lngd = parseFloat( is_gps[3] );\n var lngm = parseFloat( is_gps[4] );\n sourcelat = latd + (latm/60); // regional assumption; lat increases as magnitude increases cuz we're North\n sourcelng = -lngd - (lngm/60); // regional assumption; lng dereases as magnitude increases cuz we're West\n } else {\n var params = {};\n params.address = address;\n params.bing_key = BING_API_KEY;\n params.bbox = GEOCODE_BIAS_BOX;\n\n $.ajaxSetup({ async:false });\n $.get(BASE_URL + '/ajax/geocode', params, function (result) {\n $.ajaxSetup({ async:true });\n\n if (! result) return navigator.notification.alert('Could not find that address.', null, 'Address Not Found');\n sourcelat = result.lat;\n sourcelng = result.lng;\n },'json').error(function (error) {\n $.ajaxSetup({ async:true });\n\n return navigator.notification.alert('Could not find that address. Check the address, and that you have data service turned on and a good signal.', null, 'No connection?');\n });\n }\n break;\n // FEATURES origin: use a variant of the keyword autocomplete concept, to provide a list of names as they type\n // having exactly one result, or the first result matching your search exactly, fills in the Feature Type and GID for later, as well as grabbing its latlng\n // to clarify: submitting the form\n case 'features':\n var params = {};\n params.keyword = address;\n params.limit = 25;\n params.lat = MARKER_GPS.getLatLng().lat;\n params.lng = MARKER_GPS.getLatLng().lng;\n params.via = via;\n\n $.ajaxSetup({ async:false });\n $.get(BASE_URL + '/ajax/keyword', params, function (candidates) {\n $.ajaxSetup({ async:true });\n\n // we got back a list of autocomplete candidates\n // see if any of them are an exact match for what we typed, if so then truncate the list to that 1 perfect item\n // see if there's only 1 autocomplete candidate (perhaps the one we picked above), in which case we call that a match\n var matchme = address.replace(/\\W/g,'').toLowerCase();\n for (var i=0, l=candidates.length; i<l; i++) {\n var stripped = candidates[i].name.replace(/\\W/g,'').toLowerCase();\n if (stripped == matchme) { candidates = [ candidates[i] ]; break; }\n }\n\n if (candidates.length == 1) {\n // only 1 autocomplete candidate\n // save the lat/lng and the type/gid\n // and fill in the name so it's all spelled nicely, instead of the user's presumably-partial wording\n // then empty the autocomplete candidate listing, cuz we only had 1 and it's now in effect\n form.find('input[name=\"feature_gid\"]').val(candidates[0].gid);\n form.find('input[name=\"feature_type\"]').val(candidates[0].type);\n sourcelat = candidates[0].lat;\n sourcelng = candidates[0].lng;\n form.find('input[name=\"address\"]').val( candidates[0].name );\n $('#directions_autocomplete').empty().hide();\n } else {\n // okay, there's more than 1 candidate for this autocomplete, so fill in that listview of options\n // each option has a click handler to basically do what the \"length == 1\" option did above: fill it in, empty listing, ...\n // note: item 0 is not a result, but the words \"Did you mean...\" and has no click behavior\n var listing = $('#directions_autocomplete').empty().show();\n for (var i=0, l=candidates.length; i<l; i++) {\n var name = candidates[i].name.replace(/^\\s*/,'').replace(/\\s*$/,'');\n var item = $('<li></li>').data('raw',candidates[i]).appendTo(listing);\n $('<span></span>').addClass('ui-li-heading').text(name).appendTo(item);\n item.click(function () {\n // click this item: fill in the name, gid and type, lat and lng, ... empty the listing cuz we made a choice\n var info = $(this).data('raw');\n form.find('input[name=\"feature_gid\"]').val(info.gid);\n form.find('input[name=\"feature_type\"]').val(info.type);\n sourcelat = info.lat;\n sourcelng = info.lng;\n form.find('input[name=\"address\"]').val( info.name );\n $('#directions_autocomplete').empty().hide();\n });\n }\n listing.listview('refresh');\n }\n },'json').error(function (error) {\n $.ajaxSetup({ async:true });\n\n return navigator.notification.alert('Could fetch any locations. Check that you have data service turned on and a good signal.', null, 'No connection?');\n });\n break;\n }\n if (! sourcelat || ! sourcelng) return; // if this failed, do nothing; likely indicates that an AJAX call was used to do something other than bail or get coordinates, e.g. Features search\n // if we got here then we either loaded sourcelat and sourcelng, or else bailed with an error or some other task completed\n\n // part 3 - figure out the target location and perhaps re-figure-out the starting location as well\n // seems dead simple at first: we got here from the Details Panel and it has data('raw') with lat and lng\n // but some routing scenarios actually use alternate points e.g. the entrance gate or parking lot closest to each other\n // so we likely will do a re-geocode for target AND source to find their closest geocoding-target-points\n\n // 3a: start with the default points for the target location\n var targetlat = $('#page-details').data('raw').lat;\n var targetlng = $('#page-details').data('raw').lng;\n var targettype = $('#page-details').data('raw').type;\n var targetgid = $('#page-details').data('raw').gid;\n\n var origtype = form.find('input[name=\"feature_type\"]').val();\n var origgid = form.find('input[name=\"feature_gid\"]').val();\n\n // 3b: if the origin is a Feature AND it's a type that supports alternate destinations\n // then do some AJAX and replace sourcelat and sourcelng with the version that's closest to our target location\n if (origtype && origgid) {\n switch (origtype) {\n case 'poi':\n case 'reservation':\n case 'building':\n case 'trail':\n var params = {};\n params.type = origtype;\n params.gid = origgid;\n params.lat = targetlat;\n params.lng = targetlng;\n params.via = via;\n\n $.ajaxSetup({ async:false });\n $.get(BASE_URL + '/ajax/geocode_for_directions', params, function (reply) {\n $.ajaxSetup({ async:true });\n sourcelat = reply.lat;\n sourcelng = reply.lng;\n }, 'json').error(function (error) {\n $.ajaxSetup({ async:true });\n // error handling here, would be simply to leave sourcelat and sourcelng alone\n // rather than bug the uer that we couldn't find an even-better location than the ones they already picked\n });\n break;\n }\n }\n\n // 3c: if the target is a Feature and it's a type that supports alternate destinations\n // then do some AJAX and replace sourcelat and sourcelng with the version that's closest to our origin location\n // yes, we potentially revised the origin above; now we potentially adjust the target as well\n // hypothetically this could have a situation where we now route to a point further away, shuffling both points back and forth\n // but that's not a realistic problem; parking lots aren't on the far side of town from their facility, for example\n if (targettype && targetgid) {\n switch (targettype) {\n case 'poi':\n case 'reservation':\n case 'building':\n case 'trail':\n var params = {};\n params.type = targettype;\n params.gid = targetgid;\n params.lat = sourcelat;\n params.lng = sourcelng;\n params.via = via;\n\n $.ajaxSetup({ async:false });\n $.get(BASE_URL + '/ajax/geocode_for_directions', params, function (reply) {\n $.ajaxSetup({ async:true });\n targetlat = reply.lat;\n targetlng = reply.lng;\n }, 'json').error(function (error) {\n $.ajaxSetup({ async:true });\n // error handling here, would be simply to leave targetlat and targetlng alone\n // rather than bug the uer that we couldn't find an even-better location than the ones they already picked\n });\n break;\n }\n }\n // if we got here then we successfully loaded targetlat and targetlng\n\n // afterthought: they decided that they want to use native navigation for all transit & driving directions,\n // rather than our own UI. So if they're aksing for those types of directions, bail to do that\n if (via == 'car' || via == 'bus') {\n openDirections(sourcelat,sourcelng,targetlat,targetlng);\n return false;\n }\n\n // part 100 - done and ready!\n // slot the numbers into the form, really for debugging\n // then do the directions-getting from all those params we fetched and calculated above\n\n form.find('input[name=\"origlat\"]').val(sourcelat);\n form.find('input[name=\"origlng\"]').val(sourcelng);\n form.find('input[name=\"destlat\"]').val(targetlat);\n form.find('input[name=\"destlng\"]').val(targetlng);\n\n directionsFetch(sourcelat,sourcelng,targetlat,targetlng,tofrom,via,prefer);\n}",
"function handleSearchWaypointResultClick(e) {\n var rootElement = $(e.currentTarget).parent().parent().parent().parent();\n // var selectedDiv = $(e.currentTarget).parent().parent().parent().parent()[0];\n var index = rootElement.attr('id');\n rootElement.removeClass('unset');\n rootElement = rootElement.get(0);\n rootElement.querySelector('.searchAgainButton').show();\n var component = rootElement.querySelector('.guiComponent');\n if (!component.hasClassName('routeOptions')) {\n component.hide();\n var waypointResultElement = rootElement.querySelector('.waypointResult');\n //remove older entries:\n while (waypointResultElement.firstChild) {\n waypointResultElement.removeChild(waypointResultElement.firstChild);\n }\n waypointResultElement.insert(e.currentTarget);\n waypointResultElement.show();\n //remove search markers and add a new waypoint marker\n theInterface.emit('ui:waypointResultClick', {\n wpIndex: index,\n featureId: e.currentTarget.id,\n searchIds: rootElement.getAttribute('data-search')\n });\n } else {\n handleSearchAgainWaypointClick({\n currentTarget: e.currentTarget.up('.waypointResult')\n });\n }\n }",
"function genWayPoints()\n{\n\tvar ix = 0;\n\n\tvar numWayPoints = waypoints.length\n\tvar bounds = new google.maps.LatLngBounds();\n\tvar iw = new google.maps.InfoWindow();\n\tvar totDistance = 0;\t\t// Total distance for trip\n\tvar aryPrevWpt;\n\tconsole.log(\"Starting new Waypoints:\");\n\t\n\tfor (var kx in waypoints)\n\t{ \n\t\tif(++ix >= 26) ix = 0 // 26 letters in the alphabet\n\t\tvar thisCode = String.fromCharCode(65 + ix) + \".png\"\t// Create the waypoint alphabetic label\n\t\tvar thisPath = \"icons/markers/\";\n\t\n\t\t// Assume a normal marker\n\t\tvar wptColor = thisPath + \"green_Marker\" + thisCode \n\t\n\t\t// If there was a tag associated with this, make it BLUE, unless it was queued\n\t\tif(waypoints[kx][\"tag\"] != \"0\") wptColor = thisPath + \"blue_Marker\" + thisCode\n\n\t\t// If it was queued, we lose the BLUE tag - / Indicates queued/deferred item\n\t\tif(waypoints[kx][\"flg\"] == \"1\") wptColor = thisPath + \"red_Marker\" + thisCode\n\n\t\t // Indicates first after queued/deferred items, use Yellow\n\t\t if(waypoints[kx][\"flg\"] == \"3\") wptColor = thisPath + \"yellow_Marker\" + thisCode \n\t \n\t\t // Generate the WayPoint\n\t\t var latlng = {lat: Number(waypoints[kx][\"gpslat\"]), lng: Number(waypoints[kx][\"gpslng\"])};\n\t\t bounds.extend(latlng)\n\t \n\t\t var latlngA = waypoints[kx][\"gpslat\"] + \", \" + waypoints[kx][\"gpslng\"];\n\n\t\t var wpt = new google.maps.Marker({icon: wptColor, \n\t\t\t\t\t\t\t\t\t\t position: latlng, \n\t\t\t\t\t\t\t\t\t\t title: latlngA}) \n\t\t wpt.setMap(map);\t\t// Display the waypoint\t\t \n\t\t markers.push(wpt);\t\t// Save the Waypoint\n\t\t // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\t\t // Now make sure we have the Cell Tower\n\t\t genCellTower(waypoints[kx][\"cid\"], kx);\n\t \n\t\t // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\t\t // Now generate the info for this point\n\t\t // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\t\t// Get distance to cell tower and between waypoints\n\t\tvar arycel = {lat: Number(waypoints[kx][\"gsmlat\"]) , lng: Number(waypoints[kx][\"gsmlng\"])}\n\t\tvar distToCell = distCalc(latlng, arycel)\n\t\n\t\tvar thisDist = (aryPrevWpt == null ? 0 : distance(Number(waypoints[kx][\"gpslat\"]), Number(waypoints[kx][\"gpslng\"]), Number(aryPrevWpt[\"lat\"]), Number(aryPrevWpt[\"lng\"]), \"M\"))\n\n\t\ttotDistance += thisDist\n\t\taryPrevWpt = latlng\n\t\n\t\tif(LOG_DS == true)\n\t\t{\n\t\t\tconsole.log(\"thisDist \",thisDist);\n\t\t\tconsole.log(\"totDist \",totDistance);\n\t\t}\n\t\n\t\t// This is a function type called \"closure\" - no idea how it works, but it does\n\t\t(function(kx, wpt) {\n\t\t\t// Generate the VAR\n\t\t\taryInfoVars[\"iv\" + kx] = \n\t\t\t\t\"<div>\" +\n\t\t\t\t\"<h3>\" + (waypoints[kx][\"tag\"] != '0' ? waypoints[kx][\"tag\"] : (waypoints[kx][\"flg\"] != '0' ? 'No Svc' : 'WPT ')) + \" @ \" + Number(waypoints[kx][\"gpslat\"]) + \", \" + Number(waypoints[kx][\"gpslng\"]) + \"</h3>\" +\n\t\t\t\t\"<p>\" + waypoints[kx][\"dat\"] + \" - \" + waypoints[kx][\"tim\"] + (waypoints[kx][\"qct\"] != 0 ? ', Queued: ' + waypoints[kx][\"qct\"] : \" \") + \"</p>\" +\n\t\t\t\t\"<p>cell tower (\" + waypoints[kx][\"cid\"] + \"): \" + Math.round(distToCell,2) + \" Miles, \" + waypoints[kx][\"css\"] + \" dBm</p>\" +\n\t\t\t\t\"<p>From Start: \" + Math.round(totDistance,2) + \" mi, From Last: \" + Math.round(thisDist,2) + \" mi</p>\" +\n\t\t\t\t\"<div>\" +\n\t\t\t\t\"<p><b> Alt: \" + Math.round(waypoints[kx][\"alt\"]*3.28) + \" ft, Speed: \" + Math.round(waypoints[kx][\"spd\"]*.621371,2) + \" mph, Course: \" + waypoints[kx][\"crs\"] + \"°</b></p>\" +\n\t\t\t\t\"</div></div>\"\n\n\t\t\t// Generate the InfoWindow\n\t\t\tiw.setContent(aryInfoVars[\"iv\" + kx]);\n\n\t\t\t// Generate the Listener\n\t\t\twpt.addListener('click', function() {iw.open(map, wpt)})\n\t\t})(kx, wpt);\n\t\t//\n\t\t/*\n\t\t\t(function(kx, wpt) {\n\t\t\t// Generate the VAR\n\t\t\tgoogle.maps.event.addListener(wpt, 'click',\n\t\t\t\tfunction() {\n\t\t\t\t\tvar iw = \n\t\t\t\t\t\"<div>\" +\n\t\t\t\t\t\"<h3>\" + (waypoints[kx][\"tag\"] != '0' ? waypoints[kx][\"tag\"] : (waypoints[kx][\"flg\"] != '0' ? 'No Svc' : 'WPT ')) + \" @ \" + Number(waypoints[kx][\"gpslat\"]) + \", \" + Number(waypoints[kx][\"gpslng\"]) + \"</h3>\" +\n\t\t\t\t\t\"<p>\" + waypoints[kx][\"dat\"] + \" - \" + waypoints[kx][\"tim\"] + (waypoints[kx][\"qct\"] != 0 ? ', Queued: ' + waypoints[kx][\"qct\"] : \" \") + \"</p>\" +\n\t\t\t\t\t\"<p>cell tower (\" + waypoints[kx][\"cid\"] + \"): \" + Math.round(distToCell,2) + \" Miles, \" + waypoints[kx][\"css\"] + \" dBm</p>\" +\n\t\t\t\t\t\"<p>From Start: \" + Math.round(totDistance,2) + \" mi, From Last: \" + Math.round(thisDist,2) + \" mi</p>\" +\n\t\t\t\t\t\"<div>\" +\n\t\t\t\t\t\"<p><b> Alt: \" + Math.round(waypoints[kx][\"alt\"]*3.28) + \" ft, Speed: \" + Math.round(waypoints[kx][\"spd\"]*.621371,2) + \" mph, Course: \" + waypoints[kx][\"crs\"] + \"°</b></p>\" +\n\t\t\t\t\t\"</div></div>\"\n\t\t\t\t});\n\t\t\t// Generate the InfoWindow\n\t\t\tiw.open(map, wpt);\n\t\t\tbacs0 ----})(kx, wpt);\n\t\t*/\n\t}\t// End of For Loop\n\n\t// Now adjust the map to fit our waypoints\n\tmap.fitBounds(bounds);\n\n\t// Generate the pathways to the cell towers\n\tgenPathways(waypoints);\n\n}",
"function searchWithinTime() {\n // Initialize the distance matrix service.\n var distanceMatrixService = new google.maps.DistanceMatrixService();\n var address = document.getElementById('search-within-time-text').value;\n // Check to make sure the place entered isn't blank.\n if (address === '') {\n window.alert('You must enter an address.');\n } else {\n hideMarkers(markers);\n // Use the distance matrix service to calculate the duration of the\n // routes between all our markers, and the destination address entered\n // by the user. Then put all the origins into an origin matrix.\n var origins = [];\n for (var i = 0; i < markers.length; i++) {\n origins[i] = markers[i].position;\n }\n var destination = address;\n var mode = document.getElementById('mode').value;\n // Now that both the origins and destination are defined, get all the\n // info for the distances between them.\n distanceMatrixService.getDistanceMatrix({\n origins: origins,\n destinations: [destination],\n travelMode: google.maps.TravelMode[mode],\n unitSystem: google.maps.UnitSystem.IMPERIAL,\n }, function(response, status) {\n if (status !== google.maps.DistanceMatrixStatus.OK) {\n window.alert('Error was: ' + status);\n } else {\n displayMarkersWithinTime(response);\n }\n });\n }\n}",
"function getWaypoints() {\n var waypoints = [];\n for (var i = 0; i < $('.waypoint').length - 1; i++) {\n var address = $('#' + i).get(0);\n if (address.querySelector('.address')) {\n address = $(address).children(\".waypointResult\");\n address = $(address).find(\"li\").attr(\"data-shortaddress\");\n waypoints.push(address);\n }\n }\n return waypoints;\n }",
"function handleSearchPoiNearRoute(e) {\n searchPoiAtts[0] = e.currentTarget.checked;\n if (!routeIsPresent) {\n $('#checkboxWarn').text(preferences.translate('noRouteFound'));\n $('#checkboxWarn').show();\n } else if (searchPoiAtts[3].length > 0 && routeIsPresent) {\n theInterface.emit('ui:searchPoiRequest', {\n query: searchPoiAtts[3],\n nearRoute: searchPoiAtts[0],\n maxDist: searchPoiAtts[1],\n distUnit: searchPoiAtts[2],\n lastSearchResults: $('#searchPoi').attr('data-search')\n });\n }\n //if we're not searching near route, hide erorr message\n if (searchPoiAtts[0] == false) {\n $('#checkboxWarn').hide();\n }\n }",
"function onUserInput() {\n columnID = this.getAttribute('data-city')\n if(deactivatedLasers[columnID - 1]) {\n return\n }\n $city = $('#city-' + columnID)\n shootLaser($city)\n isHit()\n}",
"function additionalPass(result, status) {\n\n // if Maps returns a valid response\n if (status == google.maps.DirectionsStatus.OK) {\n \n // initialize variable for checking if route needs any changes\n var needsCorrection = false;\n\n // iterate over legs of route\n for (var i = 0, n = result.routes[0].legs.length; i < n; i++) {\n\n var legLength = result.routes[0].legs[i].distance.value;\n\n // if leg is longer than range\n if (legLength > range) {\n\n // create new polyline for this leg\n var polyline = new google.maps.Polyline({ path: [] });\n\n // iterate over steps of the leg\n for (var j = 0, m = result.routes[0].legs[i].steps.length; j < m; j++) {\n\n // iterate over segments of step\n for (var k = 0, l = result.routes[0].legs[i].steps[j].path.length; k < l; k++) {\n\n // add segment to polyline\n polyline.getPath().push(result.routes[0].legs[i].steps[j].path[k]);\n }\n }\n \n // find point 75% of range along this line\n var nextPoint = polyline.GetPointAtDistance(0.75 * range);\n\n // get closest station to halfway point\n var newStation = getClosestStation(nextPoint);\n \n // create waypoint at that station\n var newWaypoint = {\n location: newStation.latlng,\n stopover: true\n }\n\n // add to waypoints array\n waypoints.push(newWaypoint);\n\n // add station to station stops array\n stationStops.push(newStation);\n\n // create invisible marker\n var marker = new google.maps.Marker({\n position: stationStops[i].latlng,\n map: map,\n icon: 'img/invisible.png',\n zIndex: 3,\n });\n\n // add to markers array\n markers.push(marker);\n\n // indicate that route needs correction\n needsCorrection = true;\n }\n }\n\n // if route needs correction\n if (needsCorrection == true) {\n\n // create new directions request\n var nextRequest = {\n origin: origin,\n destination: destination,\n travelMode: google.maps.TravelMode.DRIVING,\n unitSystem: google.maps.UnitSystem.IMPERIAL,\n waypoints: waypoints,\n optimizeWaypoints: true\n }\n\n // send new directions request\n directionsService.route(nextRequest, function(nextResult, nextStatus) {\n\n // try again\n additionalPass(nextResult, nextStatus)\n });\n }\n\n // otherwise our route is fine as is\n else {\n\n // check for legs longer than 85% of range\n warnLong(result);\n\n // create a clickable info window for each waypoint\n createInfoWindows();\n\n // display route\n directionsDisplay.setDirections(result);\n }\n }\n \n // handle errors returned by the Maps API\n else {\n \n handleErrors(status);\n }\n}",
"function handleMoveUpWaypointClick(e) {\n //index of waypoint\n var waypointElement = $(e.currentTarget).parent();\n var index = parseInt(waypointElement.attr('id'));\n var prevIndex = index - 1;\n var previousElement = $('#' + prevIndex);\n waypointElement.insertBefore(previousElement);\n //adapt IDs...\n previousElement.attr('id', index);\n waypointElement.attr('id', prevIndex);\n //define the new correct order\n var currentIndex = prevIndex;\n var succIndex = index;\n //-1 because we have an invisible draft waypoint\n var numWaypoints = $('.waypoint').length - 1;\n //decide which button to show\n if (currentIndex === 0) {\n //the waypoint which has been moved up is the first waypoint: hide move up button\n $(waypointElement.get(0).querySelector('.moveUpWaypoint')).hide();\n $(waypointElement.get(0).querySelector('.moveDownWaypoint')).show();\n } else {\n //show both\n $(waypointElement.get(0).querySelector('.moveUpWaypoint')).show();\n $(waypointElement.get(0).querySelector('.moveDownWaypoint')).show();\n }\n if (succIndex == (numWaypoints - 1)) {\n //the waypoint which has been moved down is the last waypoint: hide the move down button\n $(previousElement.get(0).querySelector('.moveUpWaypoint')).show();\n $(previousElement.get(0).querySelector('.moveDownWaypoint')).hide();\n } else {\n //show both\n $(previousElement.get(0).querySelector('.moveUpWaypoint')).show();\n $(previousElement.get(0).querySelector('.moveDownWaypoint')).show();\n }\n //adapt marker-IDs, decide about wpType\n theInterface.emit('ui:movedWaypoints', {\n id1: currentIndex,\n id2: succIndex\n });\n theInterface.emit('ui:routingParamsChanged');\n }",
"function calcWaypoints(vertices) {\n var waypoints = [];\n for (var i = 1; i < vertices.length; i+=2) {\n var pt0 = (vertices[i-1].x)*CANVAS_SIZE;\n var pt1 = (vertices[i].x)*CANVAS_SIZE;\n var dx = pt1 - pt0;\n var y0 = CANVAS_SIZE - (vertices[i-1].y)*CANVAS_SIZE; \n var y1 = CANVAS_SIZE - (vertices[i].y)*CANVAS_SIZE;\n var dy = y1 - y0;\n for (var j = 0; j < 100; j++) {\n var x = pt0 + dx * j / 100;\n var y = y0 + dy * j / 100;\n // var ver is later used to check if an object is hit at this vertex\n // as it can only be hit when j==99 (a top waypoint), set ver=-1 to indicate\n // that this waypoint is not a vertex\n var ver = {x: -1, y:-1}; \n if (j==99) {\n // since this waypoint is a vertex, set ver\n ver = {x: vertices[i].x, y: vertices[i].y}; \n } \n // \"ignore\" (aka do not draw) the last and first point to avoid drawing vertical lines\n // points with ignore=true use context.moveTo instead of context.lineTo\n var ignore = false; \n if (j==0 || j==99) {\n ignore = true;\n }\n\n waypoints.push({\n x: x, // the x coordinate on the graph\n y: y, // the y coordinate on the graph\n ignore: ignore, // if waypoint should NOT be drawn to \n hit: ver, // the specific vertex point, used to check if object is hit\n });\n }\n waypoints.push({x: pt1, y: 0, ignore: true, hit: {x: -1, y:-1}});\n } \n return (waypoints);\n }",
"function getBestWaypoints (args) {\n const routeSortKey = args.routeSortKey || 'distance'\n return getOptimizedRoutes(args).then(function (routeWaypointPairs) {\n return sortRoutesBy({routeWaypointPairs, routeSortKey})[0]\n })\n}",
"function handleAddWaypointClick(e) {\n //id of prior to last waypoint:\n var waypointId = $(e.currentTarget).prev().attr('id');\n var oldIndex = parseInt(waypointId);\n addWaypointAfter(oldIndex, oldIndex + 1);\n theInterface.emit('ui:selectWaypointType', oldIndex);\n var numwp = $('.waypoint').length - 1;\n }",
"function handleKeyDownEvent(){\n if(d3.event.keyCode == 49){\n // Number 1: Set start point\n } else if(d3.event.keyCode == 50){\n // Number 2: Set end point\n } else if(d3.event.keyCode == 83){\n // Character S: Start search\n startSearch();\n } else if(d3.event.keyCode == 82){\n // Character R: Reset search\n resetSearch();\n } else if(d3.event.keyCode == 67){\n // Character C: Clear walls\n clearWalls();\n }\n}",
"function handleAnalyzeAccessibility() {\n var distance = $('#accessibilityDistance').val();\n var position = $('.guiComponent.waypoint.start .address').attr('data-position');\n if (!position) {\n var position = $('.guiComponent.waypoint.end .address').attr('data-position');\n }\n theInterface.emit('ui:analyzeAccessibility', {\n distance: distance,\n position: position\n });\n }",
"function addWaypointAfter(idx, numWaypoints) {\n //for the current element, show the move down button (will later be at least the next to last one)\n var previous = $('#' + idx);\n previous.children()[3].show();\n //'move' all successor waypoints down from idx+1 to numWaypoints\n for (var i = numWaypoints - 1; i >= idx + 1; i--) {\n var wpElement = $('#' + i);\n if (i < numWaypoints - 1) {\n //this is not the last waypoint, show move down button\n wpElement.children()[3].show();\n }\n wpElement.attr('id', i + 1);\n }\n //generate new id\n var newIndex = parseInt(idx) + 1;\n var predecessorElement = $('#' + idx);\n var waypointId = predecessorElement.attr('id');\n waypointId = waypointId.replace(idx, newIndex);\n //generate DOM elements\n var newWp = $('#Draft').clone();\n newWp.attr('id', waypointId)\n newWp.insertAfter(predecessorElement);\n newWp.show();\n //decide which buttons to show\n var buttons = newWp.children();\n //show remove waypoint + move up button\n buttons[1].show();\n buttons[2].show();\n //including our new waypoint we are constructing here, we have one more waypoint. So we count to numWaypoints, not numWaypoints-1\n if (newIndex < numWaypoints) {\n //not the last waypoint, allow moving down\n buttons[3].show();\n } else {\n buttons[3].hide();\n }\n //add event handling\n newWp = newWp.get(0);\n newWp.querySelector('.searchWaypoint').addEventListener('keyup', handleSearchWaypointInput);\n newWp.querySelector('.moveUpWaypoint').addEventListener('click', handleMoveUpWaypointClick);\n newWp.querySelector('.moveDownWaypoint').addEventListener('click', handleMoveDownWaypointClick);\n newWp.querySelector('.removeWaypoint').addEventListener('click', handleRemoveWaypointClick);\n newWp.querySelector('.searchAgainButton').addEventListener('click', handleSearchAgainWaypointClick);\n newWp.querySelector('.waypoint-icon').addEventListener('click', handleZoomToWaypointClick);\n theInterface.emit('ui:addWaypoint', newIndex);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if the given comment is a tripleslash | function isRecognizedTripleSlashComment( text, commentPos, commentEnd )
{
// Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
// so that we don't end up computing comment string and doing match for all // comments
if ( text.charCodeAt( commentPos + 1 ) === CharacterCodes.slash &&
commentPos + 2 < commentEnd &&
text.charCodeAt( commentPos + 2 ) === CharacterCodes.slash )
{
const textSubStr = text.substring( commentPos, commentEnd );
return textSubStr.match( fullTripleSlashReferencePathRegEx ) ||
textSubStr.match( fullTripleSlashAMDReferencePathRegEx ) ||
textSubStr.match( fullTripleSlashReferenceTypeReferenceDirectiveRegEx ) ||
textSubStr.match( defaultLibReferenceRegEx );
}
return false;
} | [
"function isComment(token) {\n return token.type === 'LineComment' || token.type === 'BlockComment';\n}",
"function isUNC(path) {\n if (!__WEBPACK_IMPORTED_MODULE_0__platform_js__[\"g\" /* isWindows */]) {\n // UNC is a windows concept\n return false;\n }\n if (!path || path.length < 5) {\n // at least \\\\a\\b\n return false;\n }\n var code = path.charCodeAt(0);\n if (code !== 92 /* Backslash */) {\n return false;\n }\n code = path.charCodeAt(1);\n if (code !== 92 /* Backslash */) {\n return false;\n }\n var pos = 2;\n var start = pos;\n for (; pos < path.length; pos++) {\n code = path.charCodeAt(pos);\n if (code === 92 /* Backslash */) {\n break;\n }\n }\n if (start === pos) {\n return false;\n }\n code = path.charCodeAt(pos + 1);\n if (isNaN(code) || code === 92 /* Backslash */) {\n return false;\n }\n return true;\n}",
"function isLineTerminator(token) {\n return /(?:^|\\/\\*.*)[\\r\\n\\u2028\\u2029]/.test(token);\n}",
"function isSlap(text, mention) {\n return text == ('/slap ' + mention);\n}",
"function isoscelesTriangle(sides) {\n return !(sides.length === sides.filter((side, i) => i === sides.indexOf(side)).length);\n}",
"function isPolygram(word) {\n if (word.length % 2) return \"\";\n\n const half = word.slice(0, word.length / 2);\n \n if ([...half].every(w => w === half[0])) return \"\";\n \n return half;\n}",
"hasDocstring(line){\n if (typeof line == 'undefined'){ return false;}\n return line.indexOf('*/')>=0\n}",
"function canFormTriangle(lineOne, lineTwo, lineThree) {\n var lineOneLength = lineOne.length(),\n lineTwoLength = lineTwo.length(),\n lineThreeLength = lineThree.length();\n if (lineOneLength + lineTwoLength > lineThreeLength && lineOneLength + lineThreeLength > lineTwoLength &&\n lineTwoLength + lineThreeLength > lineOneLength) {\n return true;\n } else {\n return false;\n }\n }",
"function isAuxUrl(url) {\n return (url.length >= 3 && url.substring(0, 3) == \"aux\");\n}",
"function isOkLine (previousLine) {\n\n return line === '# ok' && previousLine.indexOf('# pass') > -1;\n }",
"comments(node, { value: text, type }) {\n return type === 'comment2' && bannerRegex.test(text)\n }",
"function isWord(str) {\n\treturn wordArray.includes('\\n' + str + '\\r');\n}",
"function ruleThree(lineNumber){\n var citation = document.getElementById('cite'+lineNumber).value.trim();\n if (citation != \"\"){\n return false;\n }\n var premises = document.getElementById('prem'+lineNumber).value.trim();\n if (premises != \"\"){\n return false;\n }\n //check that schema is of form u=v=>(R<=>S)\n var line = document.getElementById('line'+lineNumber).value.trim();\n var lineChars = getCharacters(line);\n if (lineChars.length<12){\n return false;\n }\n if (lineChars[0].toUpperCase()==lineChars[0]){\n return false;\n }\n else{\n var u = lineChars[0];\n }\n if (lineChars[1]!=\"=\"){\n return false;\n }\n if (lineChars[2].toUpperCase()==lineChars[2]){\n return false;\n }\n else{\n var v = lineChars[2];\n }\n if (lineChars[3]!=\"=\"){\n return false;\n }\n if (lineChars[4]!=\">\"){\n return false;\n }\n if (lineChars[5]!=\"(\"){\n return false;\n }\n var i = 6;\n //compare R and S- same but R has free u at some places where S has free v\n var r = [];\n while (i<lineChars.length && lineChars[i]!=\"<\"){\n if (lineChars[i]!= \" \"){\n r.push(lineChars[i]);\n }\n i++;\n }\n if (lineChars[i] != \"<\") {\n return false;\n }\n i++;\n if (lineChars[i] != \"=\"){\n return false;\n }\n i++;\n if (lineChars[i] != \">\"){\n return false;\n }\n i++;\n var s = [];\n while (i<lineChars.length-1){\n if (lineChars[i]!= \" \"){\n s.push(lineChars[i]);\n }\n i++;\n }\n if (lineChars[i]!= \")\"){\n return false;\n }\n if (r.length != s.length){\n return false;\n }\n for (var j = 0; j< r.length; j++){\n if (r[j] != u){\n if (r[j] != s[j]){\n return false;\n }\n }\n else {\n if (isFreeSubline(u, r)){\n if (!isFreeSubline(v, s)){\n return false;\n }\n }\n else {\n if (r[j]!=s[j]){\n return false;\n }\n }\n }\n }\n return true;\n}",
"function isLineOverlong(text) {\n\t\tvar checktext;\n\t\tif (text.indexOf(\"\\n\") != -1) { // Multi-line message\n\t\t\tvar lines = text.split(\"\\n\");\n\t\t\tif (lines.length > MAX_MULTILINES)\n\t\t\t\treturn true;\n\t\t\tfor (var i = 0; i < lines.length; i++) {\n\t\t\t\tif (utilsModule.countUtf8Bytes(lines[i]) > MAX_BYTES_PER_MESSAGE)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t} else if (text.startsWith(\"//\")) // Message beginning with slash\n\t\t\tchecktext = text.substring(1);\n\t\telse if (!text.startsWith(\"/\")) // Ordinary message\n\t\t\tchecktext = text;\n\t\telse { // Slash-command\n\t\t\tvar parts = text.split(\" \");\n\t\t\tvar cmd = parts[0].toLowerCase();\n\t\t\tif ((cmd == \"/kick\" || cmd == \"/msg\") && parts.length >= 3)\n\t\t\t\tchecktext = utilsModule.nthRemainingPart(text, 2);\n\t\t\telse if ((cmd == \"/me\" || cmd == \"/topic\") && parts.length >= 2)\n\t\t\t\tchecktext = utilsModule.nthRemainingPart(text, 1);\n\t\t\telse\n\t\t\t\tchecktext = text;\n\t\t}\n\t\treturn utilsModule.countUtf8Bytes(checktext) > MAX_BYTES_PER_MESSAGE;\n\t}",
"function isDialrule (s) {\n\tvar i;\n\n\tif (isEmpty(s))\n if (isDialrule.arguments.length == 1) return defaultEmptyOK;\n else return (isDialrule.arguments[1] == true);\n\n\tfor (i = 0; i < s.length; i++) {\n\t\tvar c = s.charAt(i);\n\t\tif ( !isDialruleChar(c) ) {\n\t\t\tif (c.charCodeAt(0) != 13 && c.charCodeAt(0) != 10) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}",
"function isPrefix(trie, word){ \n for(let temp_word of trie){\n if( temp_word.substr(0, word.length) == word){\n return true;\n }\n }\n return false; \n}",
"function validRule(in_rule){\n var rule = new String(in_rule);\n if(rule.length > 6 && rule != \"\" && rule.indexOf(\"\\x02\")!=-1){\n rule = rule.split(\"\\x02\");\n if(rule.length >= 5)\n return true;\n }\n\n return false;\n}",
"function isRightTriangle(side, base, hypotenuse) {\n if (side ** 2 + base ** 2 === hypotenuse ** 2) {\n return true\n } else {\n return false\n }\n }",
"function isHashtagTextChar(char) {\n return char === '_' || alphaNumericAndMarksRe.test(char);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParserupdate_set_clause. | visitUpdate_set_clause(ctx) {
return this.visitChildren(ctx);
} | [
"visitUpdate_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitFor_update_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitColumn_based_update_set_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitMerge_update_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitAlter_session_set_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"_add_assignment_statement_subtree_to_ast(cst_current_node) {\n var _a;\n this.verbose[this.verbose.length - 1].push(new NightingaleCompiler.OutputConsoleMessage(SEMANTIC_ANALYSIS, INFO, `Adding assignment statement subtree to abstract syntax tree.`) // OutputConsoleMessage\n ); // this.verbose[this.verbose.length - 1].push\n let identifier_node = cst_current_node.children_nodes[0].children_nodes[0];\n // Check scope tree if the variable exists and get its type\n let error = true;\n let var_matadata = this.is_variable_declared(identifier_node);\n if (var_matadata !== null) {\n var_matadata.isInitialized = true;\n error = false;\n } // if\n // Add root Node(Assignment Statement) for asignment statement subtree\n this._current_ast.add_node(cst_current_node.name, NODE_TYPE_BRANCH, error, false);\n // Add the identifier to assignment statement subtree\n this._current_ast.add_node(identifier_node.name, NODE_TYPE_LEAF, error, false, cst_current_node.getToken());\n // Ignore the assignment operator: Node(=)\n // let assignment_op = cst_current_node.children_nodes[1]\n // Add the expression node to assignment statement subtree at the SAME LEVEL\n let expression_node = cst_current_node.children_nodes[2];\n // I've used null-aware operators in Dart, apparently Typescript has them too, damn...\n this._add_expression_subtree(expression_node, (_a = var_matadata === null || var_matadata === void 0 ? void 0 : var_matadata.type) !== null && _a !== void 0 ? _a : UNDEFINED);\n }",
"visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitModify_mv_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitRebuild_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitModify_column_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitExpr_stmt(ctx) {\r\n console.log(\"visitExpr_stmt\");\r\n if (ctx.augassign() !== null) {\r\n return {\r\n type: \"AugAssign\",\r\n left: this.visit(ctx.testlist_star_expr(0)),\r\n right: this.visit(ctx.getChild(2)),\r\n };\r\n } else {\r\n let length = ctx.getChildCount();\r\n let right = this.visit(ctx.getChild(length - 1));\r\n for (var i = length; i > 1; i = i - 2) {\r\n let temp_left = this.visit(ctx.getChild(i - 3));\r\n right = {\r\n type: \"Assignment\",\r\n left: temp_left,\r\n right: right,\r\n };\r\n }\r\n return right;\r\n }\r\n }",
"visitAssignment_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitModify_lob_storage_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function extUtils_replaceValuesInNodeSegment(nodeSeg, updatePatterns, paramObj)\n{\n var retVal = '';\n var theNode = nodeSeg.node;\n var theStr = extUtils.convertNodeToString(theNode);\n\n if (typeof theStr == \"string\" && theStr.length && theNode.outerHTML)\n {\n var innerLength = dwscripts.getInnerHTML(theNode).length;\n var closeTagPos = dwscripts.getOuterHTML(theNode).lastIndexOf(\"</\");\n var innerStart = closeTagPos - innerLength;\n var tagStart = theStr.substring(0,innerStart);\n var tagInner = theStr.substring(innerStart,closeTagPos);\n var tagEnd = theStr.substring(closeTagPos);\n for (var i=0; i < updatePatterns.length; i++)\n {\n var limitSearch = updatePatterns[i].limitSearch;\n var newParamValue = paramObj[updatePatterns[i].paramName];\n if (updatePatterns[i].pattern) //if there is a pattern, use it to update\n {\n var pattern = eval(updatePatterns[i].pattern);\n if (!limitSearch || limitSearch == \"tagOnly\")\n {\n tagStart = extUtils.safeReplaceBetweenSubExpressions(tagStart, pattern, newParamValue);\n }\n if (!limitSearch || limitSearch == \"innerOnly\")\n {\n var localBeginOffset = nodeSeg.matchRangeMin - innerStart;\n var localEndOffset = nodeSeg.matchRangeMax - innerStart;\n if (localBeginOffset >= 0 && localBeginOffset < localEndOffset && localEndOffset < innerLength)\n {\n var tinyString = tagInner.substring(localBeginOffset, localEndOffset);\n tinyString = extUtils.safeReplaceBetweenSubExpressions(tinyString, pattern, newParamValue);\n tagInner = tagInner.substring(0,localBeginOffset) + tinyString + tagInner.substring(localEndOffset);\n }\n else\n {\n tagInner = extUtils.safeReplaceBetweenSubExpressions(tagInner, pattern, newParamValue);\n }\n }\n if (!limitSearch)\n {\n tagEnd = extUtils.safeReplaceBetweenSubExpressions(tagEnd , pattern, newParamValue);\n }\n }\n else\n {\n if (limitSearch == \"innerOnly\") //innerOnly update pattern, so blow away inner\n {\n tagInner = newParamValue;\n }\n else if (limitSearch == \"tagOnly\") //tag update pattern, so blow away inner\n {\n tagStart = newParamValue;\n }\n else if (!limitSearch) //no update pattern, so blow away whole thing\n {\n tagStart = newParamValue;\n tagInner = \"\";\n tagEnd = \"\";\n }\n }\n }\n retVal = tagStart + tagInner + tagEnd;\n }\n\n return retVal;\n}",
"visitModify_col_substitutable(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitModifier_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function parse_AssignmentStatement(){\n\tdocument.getElementById(\"tree\").value += \"PARSER: parse_AssignmentStatement()\" + '\\n';\n\tCSTREE.addNode('AssignmentStatement', 'branch');\n\n\t\n\tparse_ID();\n\tCSTREE.endChildren();\n\tCSTREE.endChildren();\n\n\t\n\tmatchSpecChars(' =',parseCounter);\n\n\tparseCounter = parseCounter + 1;\n\t\n\tparse_Expr();\n\n\tCSTREE.endChildren();\n\t\n\t\n}",
"mutate(levelSet) {\n return levelSet.withMutations(\n nodeSet => {\n this.nodesToRemove.forEach(\n node => { nodeSet.remove(node); }\n );\n this.nodesToAdd.forEach(\n node => { nodeSet.add(node); }\n );\n });\n }",
"function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get and create pois | function getPois(map) {
jQuery.ajax({
url: poi_url + "?apiKey=" + api_key,
dataType: "json",
async: true,
type: "GET",
success: function(data, status, jqXHR) {
$.each(data, function(i, obj) {
//console.log(obj);
createPois(obj, map);
});
pois.addTo(map);
}
});
} | [
"function createPokemon(_id, name, classification, type1, type2, hp, attack, defense, speed, sp_attack, sp_defense){\n return {\n \"_id\": _id,\n \"name\": name,\n \"classification\": classification,\n \"type1\": type1,\n \"type2\": type2,\n \"stats\": {\n \"hp\": hp,\n \"attack\": attack,\n \"defense\": defense,\n \"speed\": speed,\n \"sp_attack\": sp_attack,\n \"sp_defense\": sp_defense\n }\n }\n\n}",
"function poCreation(orderID) {\n /* \n - Add this order to Walmarts cart;\n - checkout at walmart;\n - update walmart response at order;\n - raise a po against walmart;\n */\n return new Promise((resolve, reject) => {\n crud.model.findOne({\n _id: orderID,\n isSkWarehouse: false,\n status: {\n $in: [\"Confirmed\"]\n }\n }).lean().exec().then(order => {\n if (order) {\n logger.trace(\"Walmart order , creating a PO.....\");\n async.waterfall([\n _getFc(order),\n _createPo,\n _addToParterCart,\n _partnerCartCheckout,\n _orderUpdate\n ], function (err, result) {\n if (err) {\n reject(err);\n } else {\n resolve(result);\n }\n });\n } else {\n resolve();\n }\n }).catch(e => reject(e));\n });\n}",
"async criarPessoa(pessoa) {\n this.validarPessoa(pessoa);\n\t\tconst pessoaCriada = await PessoaRepository.create(pessoa);\n\t\treturn pessoaCriada;\n }",
"function agregarPeli () {\n\n\t\t//Tomamos los valores de los inputs del titulo, la descripcion y la imagen.\n\t\tvar nuevoTitulo = document.getElementById('titulo').value;\n\t\tvar nuevaDescripcion = document.getElementById('descripcion').value;\n\t\tvar rutaImagen = document.getElementById('imagen').value;\n\n\t\t//Con esos valores, creamos un nuevo objeto \"pelicula\"\n\t\tvar pelicula = {\n\t\t\tid: peliculas.length + 1, //Con esto le damos un id diferente a cada peli que creemos\n\t\t\ttitulo:nuevoTitulo,\n\t\t\tdescripcion:nuevaDescripcion,\n\t\t\timagen:rutaImagen\n\t\t}\n\n\t\t//Finalmente ponemos nuestra pelicula en nuestro array de películas.\n\t\tpeliculas.push(pelicula);\n\t\talert('Película agregada correctamente');\n\t\tconsole.log(peliculas);\n\n\t}",
"function createPassageObject (passage, noMeta) {\n var ret = {};\n // core data \n Object.assign(ret, {\n name : passage.name,\n pid : passage.id,\n tags : passage.tags.split(' ').filter( function (tag) { return !!tag; }),\n source : passage.source\n });\n // metadata\n if (!noMeta) {\n Object.assign(ret, {\n referTo : passage.links.to,\n referFrom : passage.links.from,\n position : passage.pos,\n size : passage.size,\n rawTags : passage.tags\n });\n }\n return ret;\n }",
"function initPoses() {\n let num = 0;\n this.joints = {\n // wrist\n Wrist: new _JointObject.JointObject(\"wrist\", num++, this),\n // thumb\n T_Metacarpal: new _JointObject.JointObject(\"thumb-metacarpal\", num++, this),\n T_Proximal: new _JointObject.JointObject(\"thumb-phalanx-proximal\", num++, this),\n T_Distal: new _JointObject.JointObject(\"thumb-phalanx-distal\", num++, this),\n T_Tip: new _JointObject.JointObject(\"thumb-tip\", num++, this),\n // index\n I_Metacarpal: new _JointObject.JointObject(\"index-finger-metacarpal\", num++, this),\n I_Proximal: new _JointObject.JointObject(\"index-finger-phalanx-proximal\", num++, this),\n I_Intermediate: new _JointObject.JointObject(\"index-finger-phalanx-intermediate\", num++, this),\n I_Distal: new _JointObject.JointObject(\"index-finger-phalanx-distal\", num++, this),\n I_Tip: new _JointObject.JointObject(\"index-finger-tip\", num++, this),\n // middle\n M_Metacarpal: new _JointObject.JointObject(\"middle-finger-metacarpal\", num++, this),\n M_Proximal: new _JointObject.JointObject(\"middle-finger-phalanx-proximal\", num++, this),\n M_Intermediate: new _JointObject.JointObject(\"middle-finger-phalanx-intermediate\", num++, this),\n M_Distal: new _JointObject.JointObject(\"middle-finger-phalanx-distal\", num++, this),\n M_Tip: new _JointObject.JointObject(\"middle-finger-tip\", num++, this),\n // ring\n R_Metacarpal: new _JointObject.JointObject(\"ring-finger-metacarpal\", num++, this),\n R_Proximal: new _JointObject.JointObject(\"ring-finger-phalanx-proximal\", num++, this),\n R_Intermediate: new _JointObject.JointObject(\"ring-finger-phalanx-intermediate\", num++, this),\n R_Distal: new _JointObject.JointObject(\"ring-finger-phalanx-distal\", num++, this),\n R_Tip: new _JointObject.JointObject(\"ring-finger-tip\", num++, this),\n // little\n L_Metacarpal: new _JointObject.JointObject(\"pinky-finger-metacarpal\", num++, this),\n L_Proximal: new _JointObject.JointObject(\"pinky-finger-phalanx-proximal\", num++, this),\n L_Intermediate: new _JointObject.JointObject(\"pinky-finger-phalanx-intermediate\", num++, this),\n L_Distal: new _JointObject.JointObject(\"pinky-finger-phalanx-distal\", num++, this),\n L_Tip: new _JointObject.JointObject(\"pinky-finger-tip\", num++, this)\n };\n }",
"function createPlayShips(){\n // playShipOptions.forEach(ship => {\n // createShip(ship)\n // })\n formatPlayShips()\n }",
"returnSystemAndPlanets(pid) {\n \n if (this.game.board[pid] == null) {\n return;\n }\n \n if (this.game.board[pid].tile == null) {\n return;\n }\n \n let sys = this.game.systems[this.game.board[pid].tile];\n let planets = [];\n \n for (let i = 0; i < sys.planets.length; i++) {\n planets[i] = this.game.planets[sys.planets[i]];\n }\n \n return {\n s: sys,\n p: planets\n };\n }",
"function fetchOrCreatePun (punId, callback) {\n punsDb.get(punId, function (err, pun) {\n if (typeof pun !== 'undefined') return callback(null, pun);\n\n fetchPunTweet(punId, function (err, pun) {\n // console.dir(pun);\n // console.dir('ID: ' + punId);\n // console.dir('tweet ID: ' + pun.id_str);\n createPun(punId, pun, function (err) {\n if (!err) return punsDb.get(punId, callback);\n });\n });\n });\n}",
"populate() {\n populating = this;\n var sentences = rm.generateSentences(4);\n this.desc = sentences;\n \n var objs = nlp(this.desc).nouns().out('array');\n\n // just removes all \"heres\"\n for (var i = 0; i < objs.length; i++) {\n if (objs[i] === \"here\") objs.splice(i, 1);\n }\n\n this.objects = objs;\n\n for (var i = 0; i < this.objects.length; i++) {\n var query = trim(this.objects[i]);\n query = query.replace(/\\s/g, \"+\");\n\n // console.log(query);\n var url = api + apiKey + query;\n loadJSON(url, this.gotData);\n\n var biased_y = sqrt(random()) * 340;\n var img_x = random(width/2 - 200, \n width/2 + 200);\n \n // hopefully bias towards floor\n var img_y = height/2 - 340/3 + biased_y;\n\n // populate object data\n this.object_coords.push({x: img_x, y: img_y});\n // this.object_hp.push(1);\n }\n }",
"static readByUserId(userId) {\n return new Promise((resolve, reject) => {\n (async () => {\n try {\n const pool = await sql.connect(con);\n const result = await pool.request()\n .input('userId', sql.Int(), userId)\n .query(`\n SELECT u.userId, p.pokName, p.pokAbilities, p.pokHeight, p.pokWeight, p.pokGender, p.pokPokemonId, t.pokTypeId, t.pokTypeName\n FROM pokUser u\n JOIN pokFavoritPokemon f\n ON u.userId = f.FK_userId\n JOIN pokPokemon p\n ON f.FK_pokPokemonId = p.pokPokemonId\n JOIN pokPokemonTypes pt\n ON pt.FK_pokPokemonId = p.pokPokemonId\n JOIN pokType t\n ON t.pokTypeId = pt.FK_pokPokemonId\n WHERE u.userId = @userId\n `)\n\n const pokemons = [];\n let lastPokemonIndex = -1;\n result.recordset.forEach(record => {\n if (pokemons[lastPokemonIndex] && record.pokPokemonId == pokemons[lastPokemonIndex].pokPokemonId) {\n console.log(`Pokemon with id ${record.pokPokemonId} already exists.`);\n const newType = {\n pokTypeId: record.pokTypeId,\n pokTypeName: record.pokTypeName,\n pokTypeDescription: record.pokTypeDescription\n }\n pokemons[lastPokemonIndex].pokTypes.push(newType);\n } else {\n console.log(`Pokemon with id ${record.pokPokemonId} is a new pokemon.`)\n const newPokemon = {\n pokPokemonId: record.pokPokemonId,\n pokName: record.pokName,\n pokHeight: record.pokHeight,\n pokWeight: record.pokWeight,\n pokAbilities: record.pokAbilities,\n pokGender: record.pokGender,\n pokFavorite: record.userId,\n pokTypes: [\n {\n pokTypeId: record.pokTypeId,\n pokTypeName: record.pokTypeName,\n pokTypeDescription: record.pokTypeDescription\n }\n ]\n }\n pokemons.push(newPokemon);\n lastPokemonIndex++;\n }\n });\n const validPokemons = [];\n pokemons.forEach(pokemon => {\n const { error } = Pokemon.validate(pokemon);\n if (error) throw { errorMessage: `Pokemon validation failed.` };\n\n validPokemons.push(new Pokemon(pokemon));\n });\n\n resolve(validPokemons);\n\n } catch (error) {\n reject(error);\n }\n\n sql.close();\n })();\n });\n }",
"function createShip( shipObj , onFinish )\n{\n //create a new company object\n var protoObj = defaultObj();\n\n //assign each of the properties to the one in shipObj parameter\n for ( var prop in protoObj )\n {\n protoObj[ prop ] = shipObj[ prop ];\n }\n\n //assign the id field of the new ship object to the shipObj parameter id\n if ( shipObj[ ID_KEY ] )\n {\n protoObj[ ID_KEY ] = shipObj[ ID_KEY ];\n }\n\n shipDAO.createShip( protoObj , onFinish );\n}",
"function buildPokemonDatabase(id) {\n let url = `https://pokeapi.co/api/v2/pokemon-species/${id}`;\n\n superagent.get(url)\n .then((speciesResult) => {\n let newUrl = speciesResult.body.varieties.filter((variety) => variety.is_default)[0].pokemon.url;\n\n superagent.get(newUrl)\n .then(result => {\n\n let SQL = `INSERT INTO species (national_dex_id, name, image_url, fem_image_url, type_primary_id, type_secondary_id, height, weight) VALUES ($1, $2, $3, $4, $5, $6, $7, $8);`;\n let values = [result.body.id, result.body.species.name, result.body.sprites.front_default, result.body.sprites.front_female || 'null', (result.body.types[0].slot === 1) ? parseInt(result.body.types[0].type.url.split('/')[6]) : parseInt(result.body.types[1].type.url.split('/')[6]), (result.body.types[0].slot === 2) ? parseInt(result.body.types[0].type.url.split('/')[6]) : 0, result.body.height, result.body.weight];\n client.query(SQL, values)\n .then(() => {\n console.log(`Pokemon #${id}, ${result.body.species.name} complete`);\n });\n })\n })\n}",
"getPokeDetails() {\n let pokeData = this.state;\n return {\n name: pokeData.name,\n imgData: this.getPokeImgs(pokeData.sprites),\n type: this.getPokeType(pokeData.types),\n hp: pokeData.base_experience,\n weight: pokeData.weight,\n height: pokeData.height,\n stats: this.getPokeStats(pokeData.stats),\n moves: this.getPokeMoves(pokeData.moves)\n }\n }",
"createObjects() {\n //this.createCube();\n //this.createSphere();\n //this.createFloor();\n this.createLandscape();\n this.createWater();\n }",
"async index(req, res) {\n // Get all oportunities\n const { data } = await pipedrive_api.get();\n if (data.data) {\n data.data.forEach(async client => {\n // Find WON oportunities\n if (client.status == 'won') {\n const {\n title,\n value,\n person_id: { name },\n creator_user_id: { id },\n } = client;\n\n var nome_cliente = name;\n //var id_venda = Math.ceil(Math.random() * (1000 - 1) + 1);\n var id_venda = id + value;\n var descricao_produto = title;\n var valor_produto = value;\n var valor_parcela = value;\n\n // Create a new Order request in Bling\n await OrderController.store(\n nome_cliente,\n id_venda,\n descricao_produto,\n valor_produto,\n valor_parcela\n );\n }\n });\n }\n return res.json({ saved: true });\n }",
"async getPokemons() {\n if (!this.store.list) {\n const count = await this.get('pokemon').then((data) => data.count);\n this.store.list = await this.get('pokemon', { limit: count }).then((data) => data.results);\n }\n }",
"function _createTeams() {\n gTeams = storageService.load('teams')\n storageService.store('teams', gTeams)\n}",
"function createQuest(req, res) {\n // Find a classroom matching the classroom_id in the request\n classroom.findOne({classroom_id: req.body.classroom_id}, (err, doc) => {\n // Add the quest and it's deatils to the quests subdocument\n doc.quests.push({\n classroom_id: req.body.classroom_id,\n coursework_id: req.query.class_id,\n due_date: req.body.due_date,\n creation_date: Date.now(),\n last_modified: Date.now(),\n name: req.body.name,\n reward_amount: req.body.reward_amount,\n type: parseInt(req.body.type)\n })\n // Save the document\n doc.save()\n })\n res.status(201).send()\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This sample demonstrates how to Creates or updates an availability group listener. | async function createsOrUpdatesAnAvailabilityGroupListenerThisIsUsedForVMSPresentInMultiSubnet() {
const subscriptionId =
process.env["SQLVIRTUALMACHINE_SUBSCRIPTION_ID"] || "00000000-1111-2222-3333-444444444444";
const resourceGroupName = process.env["SQLVIRTUALMACHINE_RESOURCE_GROUP"] || "testrg";
const sqlVirtualMachineGroupName = "testvmgroup";
const availabilityGroupListenerName = "agl-test";
const parameters = {
availabilityGroupName: "ag-test",
multiSubnetIpConfigurations: [
{
privateIpAddress: {
ipAddress: "10.0.0.112",
subnetResourceId:
"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/testrg/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/default",
},
sqlVirtualMachineInstance:
"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/testrg/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/testvm2",
},
{
privateIpAddress: {
ipAddress: "10.0.1.112",
subnetResourceId:
"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/testrg/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/alternate",
},
sqlVirtualMachineInstance:
"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/testrg/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/testvm1",
},
],
port: 1433,
};
const credential = new DefaultAzureCredential();
const client = new SqlVirtualMachineManagementClient(credential, subscriptionId);
const result = await client.availabilityGroupListeners.beginCreateOrUpdateAndWait(
resourceGroupName,
sqlVirtualMachineGroupName,
availabilityGroupListenerName,
parameters
);
console.log(result);
} | [
"async function createsOrUpdatesAnAvailabilityGroupListenerUsingLoadBalancerThisIsUsedForVMSPresentInSingleSubnet() {\n const subscriptionId =\n process.env[\"SQLVIRTUALMACHINE_SUBSCRIPTION_ID\"] || \"00000000-1111-2222-3333-444444444444\";\n const resourceGroupName = process.env[\"SQLVIRTUALMACHINE_RESOURCE_GROUP\"] || \"testrg\";\n const sqlVirtualMachineGroupName = \"testvmgroup\";\n const availabilityGroupListenerName = \"agl-test\";\n const parameters = {\n availabilityGroupName: \"ag-test\",\n loadBalancerConfigurations: [\n {\n loadBalancerResourceId:\n \"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/testrg/providers/Microsoft.Network/loadBalancers/lb-test\",\n privateIpAddress: {\n ipAddress: \"10.1.0.112\",\n subnetResourceId:\n \"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/testrg/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/default\",\n },\n probePort: 59983,\n sqlVirtualMachineInstances: [\n \"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/testrg/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/testvm2\",\n \"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/testrg/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/testvm3\",\n ],\n },\n ],\n port: 1433,\n };\n const credential = new DefaultAzureCredential();\n const client = new SqlVirtualMachineManagementClient(credential, subscriptionId);\n const result = await client.availabilityGroupListeners.beginCreateOrUpdateAndWait(\n resourceGroupName,\n sqlVirtualMachineGroupName,\n availabilityGroupListenerName,\n parameters\n );\n console.log(result);\n}",
"function BindWeChatGroup(token, group_id, suc_func, error_func) {\n let api_url = 'bnd_group.php',\n post_data = {\n 'token': token,\n 'group_id': group_id\n };\n CallApi(api_url, post_data, suc_func, error_func);\n}",
"createGroup(){\n redis.addGroup(config.EVENTS_STREAM_NAME, config.EVENTS_STREAM_CONSUMER_GROUP_NAME, (err) => {\n if (err){\n this.logger.warn(`Failed to create consumer group '${config.EVENTS_STREAM_CONSUMER_GROUP_NAME}'. ${err.message}`);\n }\n });\n }",
"static async createRule(targetGroupArn) {\n\t\tconst client = new AWS.ELBv2();\n\t\tconst listenerArn = Config.str(\"listenerArn\");\n\t\t\n\t\t// Need to go through the listener to figure out the highest priority rule\n\t\tconst rules = await ELBManager.describeRules(listenerArn);\n\t\tlet highestPriority = 0;\n\t\tfor (const rule of rules) {\n\t\t\tconst priority = parseInt(rule.Priority);\n\t\t\tif (priority > highestPriority) {\n\t\t\t\thighestPriority = priority;\n\t\t\t}\n\t\t}\n\n\t\tlet hostname = Config.str(\"serviceName\") + \".bespoken.io\";\n\t\tif (Config.has(\"hostname\")) {\n\t\t\thostname = Config.str(\"hostname\");\n\t\t}\n\t\t\n\t\tvar params = {\n\t\t\tActions: [\n\t\t\t \t{\n\t\t\t \t\tTargetGroupArn: targetGroupArn, \n\t\t\t \t\tType: \"forward\"\n\t\t\t \t}\n\t\t\t], \n\t\t\tConditions: [\n\t\t\t\t{\n\t\t\t \t\tField: \"host-header\", \n\t\t\t \t\tValues: [hostname]\n\t\t\t \t}\n\t\t\t], \n\t\t\tListenerArn: listenerArn, \n\t\t\tPriority: highestPriority + 1,\n\t\t};\n\t\tconst response = await client.createRule(params).promise();\n\t\treturn response;\n\t}",
"static async createTargetGroup() {\n\t\tconst client = new AWS.ELBv2();\n\t\tvar params = {\n\t\t\tName: Config.str(\"serviceName\"),\n\t\t\tHealthCheckEnabled: Config.bool(\"healthCheckEnabled\", true),\n\t\t\tHealthCheckIntervalSeconds: Config.int(\"healthCheckIntervalSeconds\", 30),\n\t\t\tHealthCheckPath: Config.str(\"healthCheckPath\", \"/\"),\n\t\t\tHealthCheckPort: Config.str(\"containerPort\"),\n\t\t\tHealthCheckProtocol: Config.str(\"healthCheckProtocol\", \"HTTP\"),\n\t\t\tHealthCheckTimeoutSeconds: Config.int(\"healthCheckTimeoutSeconds\", 5),\n\t\t\tHealthyThresholdCount: Config.int(\"unhealthyThresholdCount\", 3),\n\t\t\tMatcher: {\n\t\t\t HttpCode: \"200\"\n\t\t\t},\n\t\t\tPort: Config.int(\"containerPort\"),\n\t\t\tProtocol: \"HTTP\",\n\t\t\tTargetType: \"ip\",\n\t\t\tUnhealthyThresholdCount: Config.int(\"unhealthyThresholdCount\", 3),\n\t\t\tVpcId: Config.str(\"vpcId\")\n\t\t};\n\t\tconsole.log(\"TargetGroup: \" + JSON.stringify(params, null, 2));\n\t\tconst targetGroupResponse = await client.createTargetGroup(params).promise();\n\t\treturn targetGroupResponse;\n\t}",
"async registerListeners () {\n this.container.on(DockerEventEnum.STATUS_UPDATE, newStatus => this.updateStatus(newStatus));\n this.container.on(DockerEventEnum.CONSOLE_OUTPUT, data => this.onConsoleOutput(data));\n\n this.on(DockerEventEnum.STATUS_UPDATE, newStatus => {\n if (newStatus === ServerStatus.OFFLINE) {\n if (this.config.properties.deleteOnStop) {\n this.logger.info('Server stopped, deleting container...');\n this.remove()\n .catch(err => this.logger.error('Failed to delete the container!', { err }));\n } else if (this.config.properties.autoRestart) {\n this.logger.info('Restarting the server...');\n this.start();\n }\n }\n });\n }",
"constructor() { \n \n ScheduledInstanceAvailability.initialize(this);\n }",
"addNestedSub(listener) {\n //First, ensure itself has been subscribed, that's how the order of subscription is maintained\n this.trySubscribe()\n //THEN, subscribe the nested listener to its own listener collection\n this.listeners.push(listener)\n }",
"function createParticipantEvent(participant_ids, hangout_id, timestamp) {\n app.service('participant_events').create(\n {\n participants: participant_ids,\n hangout_id: hangout_id,\n timestamp: timestamp\n }, function(error, data) {\n if (error) {\n } else {\n winston.log(\"info\", \"created new participant event for hangout\", hangout_id);\n }\n });\n}",
"async function createNetworkSecurityGroup() {\n const subscriptionId = process.env[\"NETWORK_SUBSCRIPTION_ID\"] || \"subid\";\n const resourceGroupName = process.env[\"NETWORK_RESOURCE_GROUP\"] || \"rg1\";\n const networkSecurityGroupName = \"testnsg\";\n const parameters = {};\n const credential = new DefaultAzureCredential();\n const client = new NetworkManagementClient(credential, subscriptionId);\n const result = await client.networkSecurityGroups.beginCreateOrUpdateAndWait(\n resourceGroupName,\n networkSecurityGroupName,\n parameters\n );\n console.log(result);\n}",
"function listeners_(){this.listeners$bq6g=( {});}",
"async function createNetworkSecurityGroupWithRule() {\n const subscriptionId = process.env[\"NETWORK_SUBSCRIPTION_ID\"] || \"subid\";\n const resourceGroupName = process.env[\"NETWORK_RESOURCE_GROUP\"] || \"rg1\";\n const networkSecurityGroupName = \"testnsg\";\n const parameters = {\n securityRules: [\n {\n name: \"rule1\",\n access: \"Allow\",\n destinationAddressPrefix: \"*\",\n destinationPortRange: \"80\",\n direction: \"Inbound\",\n priority: 130,\n sourceAddressPrefix: \"*\",\n sourcePortRange: \"*\",\n protocol: \"*\",\n },\n ],\n };\n const credential = new DefaultAzureCredential();\n const client = new NetworkManagementClient(credential, subscriptionId);\n const result = await client.networkSecurityGroups.beginCreateOrUpdateAndWait(\n resourceGroupName,\n networkSecurityGroupName,\n parameters\n );\n console.log(result);\n}",
"async function initFriendsListener() {\n\n await updateUserFriends()\n \n\n // fill initial group panel\n friendHeader.innerHTML = `Friends\n <button id=\"friend-invit-btn\" type=\"button\" class=\"btn btn-light\">Invit users</button>`;\n \n friendContent.innerHTML = getHtmlFriendsList( userFriends );\n\n // attach listener to add button friends\n let invitFriendBtn = document.getElementById(\"friend-invit-btn\");\n invitFriendBtn.addEventListener( 'click', () => invitFriendListener() );\n\n // attach listener to all see friends button\n let seeFriendBtn = [...document.getElementsByClassName(\"btn-list-friend\")];\n seeFriendBtn.forEach( btn => btn.addEventListener( 'click', () => seeFriendListener(btn) ));\n\n // attach listener to all see friends button\n let chatFriendBtn = [...document.getElementsByClassName(\"btn-chat-friend\")];\n chatFriendBtn.forEach( btn => btn.addEventListener( 'click', () => {\n const friendid = btn.getAttribute(\"data-friendid\");\n openChatBox(friendid);\n }));\n}",
"function roomAttributeUpdateListener (e) {\n var scores;\n \n switch (e.getChangedAttr().name) {\n // When the \"ball\" attribute changes, synchronize the ball\n case RoomAttributes.BALL:\n\tdeserializeBall(e.getChangedAttr().value);\n\tbreak;\n \n // When the \"score\" attribute changes, update player scores\n case RoomAttributes.SCORE:\n\tscores = e.getChangedAttr().value.split(\",\");\n\thud.setLeftPlayerScore(scores[0]);\n\thud.setRightPlayerScore(scores[1]);\n\tbreak;\n }\n}",
"async function attestationProviderPutPrivateEndpointConnection() {\n const subscriptionId = \"{subscription-id}\";\n const resourceGroupName = \"res7687\";\n const providerName = \"sto9699\";\n const privateEndpointConnectionName = \"{privateEndpointConnectionName}\";\n const properties = {\n privateLinkServiceConnectionState: {\n description: \"Auto-Approved\",\n status: \"Approved\",\n },\n };\n const credential = new DefaultAzureCredential();\n const client = new AttestationManagementClient(credential, subscriptionId);\n const result = await client.privateEndpointConnections.create(\n resourceGroupName,\n providerName,\n privateEndpointConnectionName,\n properties\n );\n console.log(result);\n}",
"function startListener(listener) {\n var delayed = q.delay(2000);\n const out = fs.createWriteStream(log_path + \"\\\\iso-\" + listener.company + \".\" + listener.environment + \"-\" + ts + \".log\", {\n flags: \"a\",\n defaultEncoding: \"utf8\" \n });\n deployListener(listener, out).then(function(path) {\n const child = spawn(config.get(\"iso.cmd\"), [], {\n detached: true,\n shell: true,\n stdio: [\"ignore\", out, out],\n cwd: path\n });\n log.write(\"ISO Listener (\" + name + \") starting up with PID \" + child.pid + \"\\r\\n\");\n child.on(\"close\", function(code) {\n if (code === 0) {\n log.write(\"ISO Listener (\" + name + \") shutdown successfully.\\r\\n\");\n } else {\n log.write(\"ISO Listener (\" + name + \") failed (\" + code + \"), please check the appropriate log.\\r\\n\");\n }\n });\n child.on(\"error\", function(err) {\n out.write(\"ERR: \" + err);\n out.end();\n });\n }, function() {\n out.end();\n });\n return delayed;\n}",
"function AddMemberToGroup(event) {\n\t\t\t\n\t\tvar grp=event.target.name;\n\t\t\n\t\t//alert(\"This is Group id \" + event.target.name + \" : \" + event.target.id);\n\t\t\n\t\t$.ajax({\n\t\t\turl : 'http://localhost:8080/facebook_v01/webapi/groupdetails/addMemberToGroup/'\n\t\t\t\t\t+ event.target.name + '/' + event.target.id,\n\t\t\ttype : 'POST',\n\t\t\tasync:false,\n\t\t\tcomplete : function(request, textStatus, errorThrown){\n\t\t\t\tif(request.status===201){\n\t\t\t\t\t\n\t\t\t\t\t//location.reload();\n\t\t\t\t\n\t\t\t\t\t$('#AddMemberToGrouplist1').empty();\n\t\t\t\t\t$('#AddMemberToGrouplist2').empty();\n\t\t\t\t\taddComponentAddMembersToGroupList(grp);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\twindow.location.href = 'errorpage.html';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}",
"function clientAttributeUpdateListener (e) {\n // If the client is now ready (i.e., the \"status\" attribute's value is\n // now \"ready\"), add the client to the game simulation\n if (e.getChangedAttr().name == ClientAttributes.STATUS\n\t&& e.getChangedAttr().scope == Settings.GAME_ROOMID\n\t&& e.getChangedAttr().value == PongClient.STATUS_READY) {\n addPlayer(PongClient(e.getClient()));\n }\n}",
"function createLocalGroup() {\n tm && tm.record('Group_CreateLocal');\n var dfd = new Task(), group = createGroup(dfd.promise);\n pendingHrefs.push(dfd);\n pendingGroups.push(group);\n return group;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Promotes the given constant string to a TrustedScriptURL. | function ɵɵtrustConstantResourceUrl(url) {
return trustedScriptURLFromString(url);
} | [
"function sendTransferenciaToPageScript() {\n loadTransferenciaFromStorage()\n .then( transferencia => { \n window.postMessage({ // send message to page script\n from: \"autopac\", // from autopac extension\n transferencia: transferencia\n }, \"*\"); // to any targetOrigin\n });\n}",
"async function injectNamedScript(cdp, code, url, extra) {\n const {\n frame, // puppeteer Frame object; if given, create isolated world in here\n exeCtx // puppeteer ExecutionContext object; if given, use that isolated world\n } = extra || {};\n\n let xcid = null;\n if (frame) {\n const { executionContextId } = await cdp.send('Page.createIsolatedWorld', {\n frameId: frame._id, // EEEK implementation detail\n worldName: \"fuelInjector\",\n grantUniversalAccess: false\n });\n xcid = executionContextId;\n } else if (exeCtx) {\n xcid = exeCtx._contextId; // EEEK implementation detail\t\n }\n\n if (typeof code === \"function\") {\n code = `(${code.toString()})();`;\n }\n let params = {\n expression: code,\n sourceURL: url,\n persistScript: true,\n };\n if (xcid) {\n params.executionContextId = xcid;\n }\n const { scriptId, exceptionDetails } = await cdp.send('Runtime.compileScript', params);\n\n if (exceptionDetails) {\n throw exceptionDetails;\n }\n\n params = {\n scriptId: scriptId,\n silent: true,\n returnByValue: true,\n };\n if (xcid) {\n params.executionContextId = xcid;\n }\n return await cdp.send('Runtime.runScript', params);\n}",
"setTransSourceUrl(value: string) {\n this.transSourceUrl = value;\n }",
"function smf_prepareScriptUrl(sUrl)\n{\n\treturn sUrl.indexOf('?') == -1 ? sUrl + '?' : sUrl + (sUrl.charAt(sUrl.length - 1) == '?' || sUrl.charAt(sUrl.length - 1) == '&' || sUrl.charAt(sUrl.length - 1) == ';' ? '' : ';');\n}",
"function test_import(str) {\n importScripts('echo.php?' + str);\n assert_equals(echo_output, str);\n}",
"function onSuccess() {\n print(\"Url set successfully\");\n}",
"function assignPromiseEngine(engine) {\n NativePromise = engine;\n}",
"executeFunctionString() {\n this.setProperties({\n isProcessing: true\n });\n post('/evalFunctionString', { 'function': this.functionString }, this, 'json')\n .then(this.showFunctionStringResults.bind(this), this.runScriptFailure.bind(this), this.runScriptError.bind(this));\n }",
"function goStatPrdUrlTrc(url, prdNo, code, target, typGugn, areaGubn, trcNo)\t{\n\tstck( typGugn, areaGubn, trcNo);\n\tgoStatPrdUrl(url, prdNo, code, target);\n}",
"function apply_policy(url, applicable_policy) {\n // console.debug(\"# apply_policy to url: \" + url);\n // console.debug(\"# apply_policy applicable_policy: \" + JSON.stringify(applicable_policy));\n\n var precceding_result = url;\n var new_url = url;\n try {\n var domain_pol = applicable_policy.sourceDomainPolicyDB;\n if (typeof domain_pol !== 'undefined') {\n // console.debug(\"carry out rule on: \" + new_url);\n // console.debug(domain_pol);\n new_url = execute_rule(domain_pol, new_url);\n }\n precceding_result = new_url;\n } catch (e) {\n new_url = precceding_result;\n }\n try {\n\n var hostname_pol = applicable_policy.sourceHostnamePolicyDB;\n if (typeof hostname_pol !== 'undefined') {\n // console.debug(\"carry out rule on: \" + new_url);\n // console.debug(hostname_pol);\n new_url = execute_rule(hostname_pol, new_url);\n }\n precceding_result = new_url;\n\n } catch (e) {\n new_url = precceding_result;\n\n }\n\n try {\n var url_pol = applicable_policy.sourceURLPolicyDB;\n if (typeof url_pol !== 'undefined') {\n // console.debug(\"carry out rule on: \" + new_url);\n // console.debug(url_pol);\n new_url = execute_rule(url_pol, new_url);\n }\n\n } catch (e) {\n new_url = precceding_result;\n\n }\n //console.debug(domain_pol);\n //console.debug(hostname_pol);\n //console.debug(url_pol);\n\n // console.debug(\"carry out policy on: \" + new_url);\n\n\n return new_url;\n\n}",
"function showLinkDialog_LinkSave(propert_key, url) {\n\tPropertiesService.getDocumentProperties().setProperty(propert_key, url);\n}",
"function addURLParam(element,newParam){var originalSrc=element.getAttribute('src');element.setAttribute('src',originalSrc+getUrlParamSign(originalSrc)+newParam);}",
"function processUrlTemplate(url, document_ = document) {\n const scriptUrl = currentScriptUrl(document_);\n if (scriptUrl) {\n url = url.replace('{current_host}', scriptUrl.hostname);\n url = url.replace('{current_scheme}', scriptUrl.protocol.slice(0, -1));\n }\n return url;\n}",
"function addStyleString(style, source) {\n\t\t// We don't use `style.cssText` because browsers must block it when no `unsafe-eval` CSP is presented: https://csplite.com/csp145/#w3c_note\n\t\t// Even though the browsers ignore this standard, we don't use `cssText` just in case.\n\t\tfor (const property of source.split(';')) {\n\t\t\tconst match = /^\\s*([\\w-]+)\\s*:\\s*(.+?)(\\s*!([\\w-]+))?\\s*$/.exec(\n\t\t\t\tproperty,\n\t\t\t)\n\t\t\tif (match) {\n\t\t\t\tconst [, name, value, , priority] = match\n\t\t\t\tstyle.setProperty(name, value, priority || '') // The last argument can't be undefined in IE11\n\t\t\t}\n\t\t}\n\t}",
"_applyScript(value, old) {\n qx.bom.storage.Web.getSession().setItem(cboulanger.eventrecorder.UiController.CONFIG_KEY.SCRIPT, value);\n if (this.getRecorder()) {\n this.getRecorder().setScript(value);\n }\n }",
"function inject(html, url) {\n\tvar inlineScript = `<script data-streamurl=\"${url}\">${clientScript}</script>`;\n\treturn inlineScript + html;\n}",
"function org_store_link (url,title,window) {\n var cmd_str = 'emacsclient \\\"org-protocol://store-link?url='+url+'&title='+title+'\\\"';\n if (window != null) {\n window.minibuffer.message('Issuing ' + cmd_str);\n }\n shell_command_blind(cmd_str);\n}",
"function set_target_function(exp, fake_object, function_ptr) {\n\t// RPC_MESSAGE -> RpcInterfaceInformation -> InterpreterInfo -> DispatchTable\n\tvar rpc_interface = exp.read_ptr(fake_object.add(0x28));\n\tvar midl_server_info = exp.read_ptr(rpc_interface.add(0x50));\n\tvar function_table = exp.read_ptr(midl_server_info.add(8));\n\texp.write_ptr(function_table.add(0), function_ptr); // Target\n}",
"function deriveServantURL(adviseLaunchInfo, adviseMessage){\n \n if (typeof adviseMessage === 'undefined' ||\n adviseMessage === null ||\n adviseMessage.length === 0){\n \n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_BAD_SERVANT_URL'));\n cancelJob(adviseLaunchInfo,\n adviseLaunchInfo.translator.translate('LAUNCH_NO_SERVANT_URL'));\n return;\n } else {\n if (adviseMessage.substr(adviseMessage.length - 1) !== '/')\n adviseMessage += '/';\n }\n \n // BB message is a servant url\n if ((adviseMessage.indexOf('http:') === 0) || (adviseMessage.indexOf('https:') === 0)){\n \n adviseLaunchInfo['servantURL'] = adviseMessage;\n return;\n } \n \n // BB message isnt a url -deprecated\n if ((adviseMessage.indexOf('http:') < 0) && (adviseMessage.indexOf('https:') < 0)){\n \n // Check for existence or proxy\n if (typeof adviseLaunchInfo.proxyServer !== 'undefined'&&\n adviseLaunchInfo.proxyServer !== null){\n \n // Valid proxy url \n if (adviseLaunchInfo.proxyServer.indexOf('http') === 0){\n \n \tif (adviseLaunchInfo.proxyServer.slice(-1) !== '/' )\n \t\tadviseLaunchInfo.proxyServer += '/';\n adviseLaunchInfo['servantURL'] = adviseLaunchInfo['proxyServer'] +\n adviseMessage;\n }\n return;\n }\n else {\n \n // No proxy and BB msg isnt a url - failure\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_BAD_SERVANT_URL'));\n cancelJob(adviseLaunchInfo,\n adviseLaunchInfo.translator.translate('LAUNCH_BAD_SERVANT_URL') + ' = ' + adviseMessage + '\".' );\n return;\n }\n }\n}",
"function getWSEndpoint(browserURL, cancellationToken) {\n return __awaiter(this, void 0, void 0, function* () {\n const jsonVersion = yield fetchJson(url_1.resolve(browserURL, '/json/version'), cancellationToken);\n if (jsonVersion === null || jsonVersion === void 0 ? void 0 : jsonVersion.webSocketDebuggerUrl) {\n return fixRemoteUrl(browserURL, jsonVersion.webSocketDebuggerUrl);\n }\n // Chrome its top-level debugg on /json/version, while Node does not.\n // Request both and return whichever one got us a string.\n const jsonList = yield fetchJson(url_1.resolve(browserURL, '/json/list'), cancellationToken);\n if (jsonList === null || jsonList === void 0 ? void 0 : jsonList.length) {\n return fixRemoteUrl(browserURL, jsonList[0].webSocketDebuggerUrl);\n }\n throw new Error('Could not find any debuggable target');\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add image resource references for the provided platforms to the project's config.xml file. | async function addResourcesToConfigXml(conf, platformList, resourceJson) {
for (const platform of platformList) {
conf.ensurePlatformImages(platform, resourceJson[platform]);
}
conf.ensureSplashScreenPreferences();
} | [
"function updatePlatformConfig(platform) {\n var configData = parseConfigXml(platform),\n platformPath = path.join(rootdir, 'platforms', platform);\n\n _.each(configData, function (configItems, targetFileName) {\n var targetFilePath;\n if (platform === 'ios') {\n if (targetFileName.indexOf(\"Info.plist\") > -1) {\n targetFileName = projectName + '-Info.plist';\n targetFilePath = path.join(platformPath, projectName, targetFileName);\n ensureBackup(targetFilePath, platform, targetFileName);\n updateIosPlist(targetFilePath, configItems);\n }else if (targetFileName === \"project.pbxproj\") {\n targetFilePath = path.join(platformPath, projectName + '.xcodeproj', targetFileName);\n ensureBackup(targetFilePath, platform, targetFileName);\n updateIosPbxProj(targetFilePath, configItems);\n updateXCConfigs(configItems, platformPath);\n }\n\n } else if (platform === 'android' && targetFileName === 'AndroidManifest.xml') {\n targetFilePath = path.join(platformPath, targetFileName);\n ensureBackup(targetFilePath, platform, targetFileName);\n updateAndroidManifest(targetFilePath, configItems);\n } else if (platform === 'wp8') {\n targetFilePath = path.join(platformPath, targetFileName);\n ensureBackup(targetFilePath, platform, targetFileName);\n updateWp8Manifest(targetFilePath, configItems);\n }\n });\n }",
"function updateConfig(target, callback) {\n try {\n var contents = fs.readFileSync(path.join(__dirname, '../../config.xml'), 'utf-8');\n if(contents) {\n //Windows is the BOM. Skip the Byte Order Mark.\n contents = contents.substring(contents.indexOf('<'));\n }\n\n var doc = new et.ElementTree(et.XML(contents)),\n root = doc.getroot();\n\n if(root.tag !== 'widget') {\n throw new Error('config.xml has incorrect root node name (expected \"widget\", was \"' + root.tag + '\")');\n }\n\n var platformElement = doc.find('./platform/[@name=\"' + target + '\"]');\n\n if(platformElement) {\n // Find all the child icon elements\n var icons = platformElement.findall('./icon');\n\n // Remove all the icons in the platform element\n icons.forEach(function(icon) {\n platformElement.remove(icon);\n });\n }\n else {\n // Create a new element if no element was found\n platformElement = new et.Element('platform');\n platformElement.attrib.name = target;\n\n // Only append the element if it does not yet exist\n doc.getroot().append(platformElement);\n }\n\n // Add all the icons\n for(var i=0; i<platforms[target].icons.length; i++) {\n var iconElement = new et.Element('icon');\n iconElement.attrib.src = 'res/' + target + '/' + platforms[target].icons[i].file;\n\n platformElement.append(iconElement);\n }\n\n // Write the file\n fs.writeFileSync(path.join(__dirname, '../../config.xml'), doc.write({indent: 4}), 'utf-8');\n\n callback();\n }\n catch (e) {\n console.error('Could not loading config.xml');\n throw e;\n }\n}",
"function refreshPlatforms(platforms) {\n if(platforms === undefined) return;\n deleteDirSync(\"platforms\");\n\n if(platforms.indexOf(\"a\") !== -1)\n runShell(\"npx ionic cordova platform add android\");\n\n if(platforms.indexOf(\"i\") !== -1)\n if (OS.platform() === \"darwin\") runShell(\"npx ionic cordova platform add ios\");\n else consoleOut(`(set_brand.js) did not add ios-platform on the operating system \"${OS.platform()}\"`);\n}",
"async function getSourceImages(projectDir, buildPlatforms, resourceTypes) {\n const resourceDir = path.resolve(projectDir, 'resources'); // TODO: hard-coded\n const srcDirList = buildPlatforms\n .map(platform => ({ platform, path: path.resolve(resourceDir, platform) }))\n .concat({ platform: 'global', path: resourceDir });\n const sourceImages = [];\n for (const srcImgDir of srcDirList) {\n const srcImageDirContents = await utils_fs_1.readdirSafe(srcImgDir.path);\n for (const srcImage of srcImageDirContents) {\n const ext = path.extname(srcImage);\n const resType = path.basename(srcImage, ext);\n if (SUPPORTED_SOURCE_EXTENSIONS.includes(ext) && resourceTypes.includes(resType)) {\n sourceImages.push({\n ext,\n resType,\n platform: srcImgDir.platform,\n path: path.join(srcImgDir.path, srcImage),\n vector: false,\n height: 0,\n width: 0,\n });\n }\n }\n }\n const sourceImageChecksums = await Promise.all(sourceImages.map(async (img) => {\n const [md5, cachedMd5] = await utils_fs_1.getFileChecksums(img.path);\n if (cachedMd5) {\n debug(`${color_1.ancillary('getSourceImages')}: ${color_1.strong(format_1.prettyPath(img.path))} cache md5: ${color_1.strong(cachedMd5)}`);\n img.cachedId = cachedMd5;\n }\n return md5;\n }));\n return sourceImages.map((img, i) => ({\n ...img,\n imageId: sourceImageChecksums[i],\n }));\n}",
"function getConfigFilesByTargetAndParent(platform) {\n var configFileData = configXml.findall('platform[@name=\\'' + platform + '\\']/config-file');\n var result = keyBy(configFileData, function(item) {\n var parent = item.attrib.parent,\n add = item.attrib.add;\n //if parent attribute is undefined /* or */, set parent to top level elementree selector\n if(!parent || parent === '/*' || parent === '*/') {\n parent = './';\n }\n return item.attrib.target + '|' + parent + '|' + add;\n });\n return result;\n }",
"function setValuesInProjectConfig(config) {\n if (!config.projectConfig) { return }\n // for each entry, the 'setValueInTag'-method is called until the tag was found once\n let toDoList = [\n {tag: \"<widget \", pre: \"id=\\\"\", value: config.projectConfig.id, post: \"\\\"\", done: false},\n {tag: \"<name>\", pre: \"<name>\", value: config.projectConfig.name, post: \"</name>\", done: false},\n {tag: \"<description>\", pre: \"<description>\", value: config.projectConfig.description, post: \"</description>\", done: false}\n ];\n\n // iterate trough lines of 'config.xml' until all tags have ben found\n let lines = FS.readFileSync(\"config.xml\", \"utf8\").split(\"\\n\");\n let done = false;\n for(let i = 0; (i < lines.length) && !done; i++) {\n done = true;\n toDoList.forEach(e => {\n [lines[i], e.done] = (e.done) ? [lines[i], e.done] : setValueInTag(lines[i], e.tag, e.pre, e.value, e.post);\n done &= e.done;\n });\n }\n\n if(!done) {\n let notDone = \"\";\n toDoList.forEach(function(e) {\n notDone += (e.done) ? \"\" : `${e.tag} `;\n });\n throw new Error(`(set_brand.js) unable to set the value(s) for the following tag(s) [ ${notDone}] in 'config.xml'`);\n }\n\n FS.writeFileSync(\"config.xml\", lines.join(\"\\n\"));\n}",
"function findAssets(projectRoot, platform) {\n const updatesPath = path.join(projectRoot, 'updates');\n const updatesJson = require(path.join(updatesPath, 'metadata.json'));\n const assets = updatesJson.fileMetadata[platform].assets;\n return assets.map((asset) => {\n return {\n path: path.join(updatesPath, asset.path),\n ext: asset.ext,\n };\n });\n}",
"function addPlatforms() {\n platforms = game.add.physicsGroup();\n platforms.create(600, 100, 'platform');\n platforms.setAll('body.immovable', true);\n}",
"function parseConfigXml(platform) {\n var configData = {};\n parsePlatformPreferences(configData, platform);\n parseConfigFiles(configData, platform);\n\n return configData;\n }",
"function parsePlatformPreferences(configData, platform) {\n var preferences = getPlatformPreferences(platform);\n switch(platform){\n case \"ios\":\n parseiOSPreferences(preferences, configData);\n break;\n case \"android\":\n parseAndroidPreferences(preferences, configData);\n break;\n }\n }",
"getPaths(projectName, imagesCount) {\n const srcsetWidths = [320, 480, 640, 960, 1280];\n const fallbackWidth = 640;\n\n let imagesPaths = [];\n\n // This would build the images path for how they appear in the folder\n // The assumption is that the cloudinary folder contains images that are sequenced\n // the way we want them. And, that they share the same name as the folder they are placed\n // in\n for (i = 1; i < imagesCount + 1; i++) {\n imagesPaths.push(`${projectName}\\/${projectName}-${i}`);\n }\n\n // We grab and set the srcset widths for all the images we want to show\n const finalPaths = [];\n imagesPaths.forEach((path) => {\n const fetchBase = `https://res.cloudinary.com/yesh/image/upload/`;\n const src = `${fetchBase}q_auto,f_auto,w_${fallbackWidth}/${path}.jpg`;\n\n const srcset = srcsetWidths\n .map((w) => {\n return `${fetchBase}q_auto:eco,f_auto,w_${w}/${path}.jpg ${w}w`;\n })\n .join(', ');\n finalPaths.push(\n `<img src=\"${src}\" srcset=\"${srcset}\" sizes=\"(max-width: 400px) 320px, 480px\" alt=\"images for project ${projectName}\">`\n );\n });\n\n return finalPaths;\n }",
"function platform_init() {\r\n\tplatform.push(new Platform(0, 400, 400, 0, 0));\r\n\t\tvar plat_num = 0;\r\n\t\tvar plat_y = 400;\r\n\t\tvar plat_x = Math.floor(Math.random()*300);\r\n\t\twhile (plat_num < 10) {\r\n\t\t\tvar next_plat_y = Math.floor(Math.random()*35) + 50;\r\n\t\t\tplat_y -= next_plat_y;\r\n horiz = Math.min(canvas.width - (plat_x + 200), Math.min(plat_x, Math.random() * 300));\r\n if (horiz < 5) {\r\n horiz = 0;\r\n }\r\n\t\t\tplatform.push(new Platform(plat_x, plat_y, 100, horiz, 0));\r\n\t\t\tvar next_plat_x = Math.floor(Math.random()*150);\r\n\t\t\tif(plat_num % 2 === 1)\r\n\t\t\t\tnext_plat_x += 150;\r\n\t\t\tplat_x = next_plat_x;\r\n\t\t\tif (plat_x > 300 || plat_x < 0)\r\n\t\t\t\tplat_x = Math.floor(Math.random()*200) + Math.floor(Math.random()*100);\r\n\t\t\tplat_num++;\r\n\t\t}\r\n}",
"function insertIMGlinks() {\n //LOGGER.debug(\"FMA insertIMGlinks Function Executing\");\n let imgsrc = $('#image-1 img.sbar-fullimg').attr('src');\n imgsrc = imgsrc.substring(0, imgsrc.indexOf('?'));\n //LOGGER.debug(\" insertIMGlinks > imgsrc:\", imgsrc);\n $('#album-images').append(`<p><img src=\"http://musicbrainz.org/favicon.ico\" /><a href=\"${imgsrc}\">MB High Res Image</a></p>`);\n}",
"function mapImageResources(rootDir, subDir, type, resourceName) {\n var pathMap = {};\n shell.ls(path.join(rootDir, subDir, type + '-*'))\n .forEach(function (drawableFolder) {\n var imagePath = path.join(subDir, path.basename(drawableFolder), resourceName);\n pathMap[imagePath] = null;\n });\n return pathMap;\n}",
"function initImgs(){\n for(var i = 1; i <= datas.nbrOfImages; i++) {\n // génère les images dans l'index.html\n $scope.data.items.push({src: \"img/bd/Case\" + i + \".jpg\"});\n }\n }",
"_addResources(resources, forceUpdate = false) {\n for (const id in resources) {\n this.layerManager.resourceManager.add({\n resourceId: id,\n data: resources[id],\n forceUpdate\n });\n }\n }",
"SetCompatibleWithPlatform() {}",
"function parseiOSPreferences(preferences, configData){\n _.each(preferences, function (preference) {\n if(preference.attrib.name.match(new RegExp(\"^ios-\"))){\n var parts = preference.attrib.name.split(\"-\"),\n target = \"project.pbxproj\",\n prefData = {\n type: parts[1],\n name: parts[2],\n value: preference.attrib.value\n };\n if(preference.attrib.buildType){\n prefData[\"buildType\"] = preference.attrib.buildType;\n }\n if(preference.attrib.quote){\n prefData[\"quote\"] = preference.attrib.quote;\n }\n\n prefData[\"xcconfigEnforce\"] = preference.attrib.xcconfigEnforce ? preference.attrib.xcconfigEnforce : null;\n\n if(!configData[target]) {\n configData[target] = [];\n }\n configData[target].push(prefData);\n }\n });\n }",
"function createplat(){\n platforms.push(\n {\n x: 0,\n y: 200,\n width: 200,\n height: 15\n },\n {\n x: 100,\n y: 300,\n width: 200,\n height: 15\n },\n {\n x: 300,\n y: 200,\n width: 200,\n height: 15\n },\n {\n x: 550,\n y: 300,\n width: 200,\n height: 15\n },\n {\n x: 700,\n y: 250,\n width: 270,\n height: 15\n }\n );\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export layer to image | function ExportLayer(layer, file){
var docDup = docRef.duplicate();
// docDup.artLayers.add();
app.activeDocument = docRef; // for following layer duplicate
var lyCopy = layer.duplicate(docDup, ElementPlacement.INSIDE);
app.activeDocument = docDup; // for save document
SaveJPEG(docDup, file, 12);
app.activeDocument = docRef; // to default
docDup.close(SaveOptions.DONOTSAVECHANGES);
} | [
"function SaveCurLayerset(){\n var lySetCur = docRef.activeLayer;\n var isLayer = lySetCur.typename == \"ArtLayer\"? true: false;\n var diagName = \"输出目录:当前选择的是 \" + (isLayer? \"层\": \"组\"); //FIXME: not displayed on windows\n var DirSaved = Folder.selectDialog(diagName); // using \"var path\" get wrong directory\n \n if(DirSaved == null)return;\n var file; //file name saved\n if(isLayer){ \n file = new File(DirSaved + \"/50.jpg\");\n ExportLayer(lySetCur, file);\n }else{\n var lysCount = lySetCur.artLayers.length\n for (var i = 0; i < lysCount; i++) {\n var lyCur = lySetCur.artLayers[i];\n //* layers order: from top to bottom; output order: from bottom to top\n var invertIndex = lysCount-i-1; \n var fileName = (invertIndex==4) ? 15: invertIndex + 1; //1, 2, 3, 4, 15\n file = new File(DirSaved + \"/\" + fileName + \".jpg\");\n ExportLayer(lyCur, file);\n }\n }\n\n alert(\"主人,我已经把图片都导出去了!\");\n}",
"addExportCanvasListener(){\n uiElements.BTN_EXPORT.addEventListener(\"click\", () => {\n uiElements.CANAVS.toBlob(function(blob){\n saveAs(blob, \"image.png\");\n });\n });\n }",
"saveToPNG() {\n this.downloadEl.download = 'pattar.png';\n this.downloadEl.href = this.renderCanvas.toDataURL(\"image/png\").replace(\"image/png\", \"image/octet-stream\");\n this.downloadEl.click();\n }",
"function exportPngClick() {\n const filename = Data.IsSavedDiagram ?\n Data.SavedDiagramTitle :\n decodeURIComponent(Data.Filename);\n\n const svgXml = getSvgXml();\n const background = window.getComputedStyle(document.body).backgroundColor;\n exportPng(filename + '.png', svgXml, background);\n}",
"function rasterizeLayer() {\n try {\n var id1242 = stringIDToTypeID(\"rasterizeLayer\");\n var desc245 = new ActionDescriptor();\n var id1243 = charIDToTypeID(\"null\");\n var ref184 = new ActionReference();\n var id1244 = charIDToTypeID(\"Lyr \");\n var id1245 = charIDToTypeID(\"Ordn\");\n var id1246 = charIDToTypeID(\"Trgt\");\n ref184.putEnumerated(id1244, id1245, id1246);\n desc245.putReference(id1243, ref184);\n executeAction(id1242, desc245, DialogModes.NO);\n } catch (e) {\n // do nothing\n }\n}",
"function exportImages() {\n let frontImage = frontCanvas.toDataURL({format: 'jpeg'});\n let backImage = backCanvas.toDataURL({format: 'jpeg'});\n\n clearGuides();\n\n console.log('Exporting canvases as images...');\n\n // return front and back images\n return(\n {\n 'front' : frontImage,\n 'back': backImage\n }\n )\n}",
"function exportGraphicFiles()\r{\r var graphics = docData.selectedDocument.allGraphics;\r $.writeln(\"exportResolution Default: \" + app.pngExportPreferences.exportResolution);\r app.pngExportPreferences.pngQuality = PNGQualityEnum.MAXIMUM; // set MAXIMUM Resolution\r app.pngExportPreferences.exportResolution = scriptSettings.exportResolution;\r $.writeln(\"exportResolution setTo: \" + app.pngExportPreferences.exportResolution);\r for (var y = 0; y < graphics.length; y++){\r var graphic = graphics[y]; \r if (graphic.itemLink != null) {\r var exportFile = new File(docData.imagesFolder + \"/\" + graphic.itemLink.name + \".png\");\r $.writeln(\"export to: \" + exportFile);\r graphic.exportFile(ExportFormat.PNG_FORMAT,exportFile);\r }\r }\r}",
"function saveDrawingSurface() {\n\t\tdrawingSurfaceImageData = context.getImageData(0, 0,\n\t\t\tcanvas.width,\n\t\t\tcanvas.height);\n\t}",
"function downloadCanvas() {\n saveCanvas('ohwow', 'png');\n}",
"function downloadImage() {\n var link = document.createElement('a');\n link.download = 'diagram.png';\n link.href = myDiagram.makeImage().src;\n link.click();\n}",
"capture(){\n // Create a hidden canvas of the appropriate size\n let output = document.createElement(\"canvas\");\n output.setAttribute(\"height\", this.height);\n output.setAttribute(\"width\", this.width);\n output.style.display = \"none\";\n\n let outputCtx = output.getContext(\"2d\");\n\n // Draw each canvas to the hidden canvas in order of z index\n for(let z=0; z < privateProperties[this.id].canvases.length; z++){\n outputCtx.drawImage(privateProperties[this.id].canvases[i], 0, 0);\n }\n\n // Get the image data\n let dataUrl = output.toDataURL();\n\n // Save the image as a png\n let a = document.createElement(\"a\");\n a.href = dataUrl;\n a.download = \"ScreenShot\" + (new Date().getDate())+\".png\";\n document.body.appendChild(a);\n a.click();\n a.remove();\n }",
"function saveImage() {\n var data = canvas.toDataURL();\n $(\"#url\").val(data);\n }",
"function saveLastDrawing() {\n lastImage.src = canvas.toDataURL('image/png');\n }",
"export() {\n let data = [];\n let totalAnimationSteps = this.stepCount + 1;\n\n writeUint8(totalAnimationSteps, data);\n \n for (var i = 0; i < totalAnimationSteps; i++) \n {\n\n let totalColorsInCurrentStep = Object.keys(this.colors[i]).length;\n\n if (totalColorsInCurrentStep === 0 && totalAnimationSteps === 0)\n {\n console.log(\"Nothing to export.\")\n return;\n }\n\n writeUint16(totalColorsInCurrentStep, data);\n\n for (const color of Object.keys(this.colors[i])) \n {\n let rgb = hexToRgb(color)\n writeUint8(rgb.r, data)\n writeUint8(rgb.g, data)\n writeUint8(rgb.b, data)\n let ledsWithThisColor = this.getLedsWithColor(i, color);\n writeUint16(ledsWithThisColor.length, data)\n ledsWithThisColor.forEach(elem => {\n writeUint16(elem, data);\n })\n }\n\n\n }\n\n var blob = new Blob(data, { type: \"application/octet-stream\" });\n var blobUrl = URL.createObjectURL(blob);\n window.location.replace(blobUrl);\n\n var fileLink = document.createElement('a');\n fileLink.href = blobUrl\n fileLink.download = \"animation.bin\"\n fileLink.click();\n\n }",
"function saveToCameraRoll() {\n\tif (typeof canvas2ImagePlugin !== 'undefined') {\n\t\tcanvas2ImagePlugin.saveImageDataToLibrary(\n\t\tfunction(msg) {\n\t\t\t//console.log(msg);\n\t\t}, function(err) {\n\t\t\t//console.log(err);\n\t\t}, 'savespot');\n\t}\n}",
"_downloadSvgAsPng() {\n savesvg.saveSvgAsPng(document.getElementById(\"svg\"), \"timeline.png\");\n }",
"handleSave() {\n const can = document.getElementById('paint');\n const img = new Image();\n\n /**\n * If the state of the default canvas is the same that\n * the canvas after click on save we show an error instead\n * send the image in png to the father component\n */\n if (can.toDataURL() === this.state.defaultCanvas) {\n alert('Canvas is blank');\n } else {\n img.src = can.toDataURL('image/png');\n this.props.onReciveSign(img.src);\n }\n }",
"function stamenLayer(stamenType, retina) {\n return 'http://{s}.tile.stamen.com/'+stamenType+'/{z}/{x}/{y}'+(retina ? '@2x': '')+'.png';\n}",
"function convertCanvastoImage(){\n var filename=document.getElementById(\"filename\").value;\n var canvas=document.getElementById(\"canvasID\"+pageCanvas);\n canvas.toBlob(function(blob){\n\t saveAs(blob, filename +\".jpg\");\n }, \"image/jpg\");\n $(\"#configPopUp\").dialog('destroy');\n\treturn;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exercise One Choosing a color for a light. Given a number, decide which color should be returned. Complete the following ternary statement. If the number is > 10, return "blue" otherwise return "red"; | function getColor(number) {
return number > 10 ? "blue" : "red";
} | [
"getColor() {\n if (this.temperature <= 15) {\n return \"blue\";\n } else if (this.temperature <= 30) {\n return \"orange\";\n } else {\n return \"red\";\n }\n }",
"function tempColorSelector(temp) {\n var tempColor = \"\";\n\n var t = parseFloat(temp);\n\n if ( t < 50 ) {\n\ttempColor = tempColorBlue;\n } else if ( t < 55 ) {\n\ttempColor = tempColorGreen;\n } else if ( t < 60 ) {\n\ttempColor = tempColorOrange;\n } else {\n\ttempColor = tempColorRed;\n }\n\n return tempColor;\n}",
"function mapcolor(c) {\n if (c === '#eb565c') {\n return 'retail';\n }\n else if (c === '#e7cd77') {\n return 'residential';\n }\n else if (c === '#98eaa6') {\n return 'office';\n }\n else if (c === 'black') {\n return 'void';\n }\n}",
"function getLikeColor(a_color) {\n let its_red = p5.red(a_color);\n let its_green = p5.green(a_color);\n let its_blue = p5.blue(a_color);\n let total_colors = its_red + its_green + its_blue;\n if (total_colors == 0) {\n //if it's black, need to set so that total isn't zero\n its_red = 10;\n its_green = 10;\n its_blue = 10;\n total_colors = its_red + its_green + its_blue;\n }\n //if it's a light color, get a like color that's darker\n let new_total_colors = p5.int(p5.random(0, 255 * 3));\n //set same proportions of each color in the old color for the new color\n let new_color = p5.color(\n (its_red * new_total_colors) / total_colors,\n (its_green * new_total_colors) / total_colors,\n (its_blue * new_total_colors) / total_colors\n );\n return new_color;\n }",
"function randLightColor() {\r\n\tvar rC = Math.floor(Math.random() * 256);\r\n\tvar gC = Math.floor(Math.random() * 256);\r\n\tvar bC = Math.floor(Math.random() * 256);\r\n\twhile (Math.max(rC, gC, bC) < 200) {\r\n\t\trC = Math.floor(Math.random() * 256);\r\n\t\tgC = Math.floor(Math.random() * 256);\r\n\t\tbC = Math.floor(Math.random() * 256);\r\n\t}\r\n\treturn tColor(rC, gC, bC, 1.0);\r\n}",
"function checkForRedPetals( color ) { // color as hue & lightness object: { h: <value>, l: <value> }\n var hq = color.h <= 15 || color.h >= 345; // hue qualifies\n var lq = color.l >= 30 && color.l <= 50; // lightness qualifies\n return hq && lq;\n}",
"function analyzeColor(input) {\n if (input === \"blue\") {\n return \"blue is the color of the sky\";\n }\n if (input === \"red\") {\n return \"Strawberries are red\";\n }\n if (input === \"cyan\") {\n return \"I don't know anything about cyan\";\n } else {\n return \"A girl has no \" + input + \" color.\";\n }\n}",
"colorForAmount(amount) {\n return amount < 0 ? 'red--text' : 'green--text'\n }",
"function color(num) { return sign(num) > 0 ? BGP.UP : sign(num) < 0 ? BGP.DOWN : BGP.STAY; }",
"getColor(value) {\n if (undefined == value) { return 'lightgrey'; }\n if (value < 0) {\n return this.negativeColorScale(value);\n } else {\n return this.selectedPosColorScale(value);\n }\n }",
"function selectColor(input) {\n \n\n if(input == \"color\") {\n userColor();\n } else if(input == \"rainbow\") {\n rainbowColor();\n } else {\n greyScale();\n }\n\n }",
"function chooseFinalColor(){\n //code colors at the beggiing has value -1 which mean not find\n var white = -1;\n var orange = -1;\n var red = -1;\n var blue = -1;\n var yellow = -1;\n //array to put code colors from all ingredients\n var colorCode = [];\n //putting code colors in array\n for(var i =0; i<dataIngredients.length; i++){\n colorCode.push(dataIngredients[i][0].colorGroup)\n }\n //checking if in array is one this code colors\n white = colorCode.indexOf(\"white\");\n orange = colorCode.indexOf(\"orange\");\n red = colorCode.indexOf(\"red\");\n blue = colorCode.indexOf(\"blue\");\n yellow = colorCode.indexOf(\"yellow\");\n //assiging final coctail color base of find code colors\n if(white >= 0){\n if(red >=0 && yellow>=0 && blue <0){\n finalColor = \"#efa17f\";\n }else if(red>=0 && blue >= 0){\n finalColor = \"#ab5d72\";\n }else if(red>=0 && yellow<0 && blue<0){\n finalColor = \"#ec929b\";\n }else if(blue>=0) {\n finalColor = \"#7d69b1\";\n }else{\n finalColor = \"#f8e994\";\n }\n }\n if(orange>=0){\n if(red>= 0 && blue>=0){\n finalColor = \"#b2336e\";\n }else if(red>=0 && blue<0){\n finalColor = \"#f27911\";\n }else if(blue>=0){\n finalColor = \"#8c976e\";\n }else{\n finalColor = \"#f0cc34\";\n }\n }\n}",
"confirmColor() {\n if (this.state.amount === this.props.amount) {\n return \"light\";\n }\n return \"primary\";\n }",
"function changeToRed(red){\n if (red >= 20000){\n $('#monthlyBudget').addClass('makeRed');\n }\n }",
"function pickColor(depth) {\n switch (true) {\n case depth > 90:\n return \"#FE3B00\";\n case depth > 70:\n return \"#FE6300\";\n case depth > 50:\n return \"#FE8A00\";\n case depth > 30:\n return \"#FEB200\";\n case depth > 10:\n return \"#FED900\";\n default:\n return \"#FEED00\";\n }\n }",
"function setColor(population) {\n\tvar population_num = parseInt(population);\n\n\tif (population_num > 150000) {\n\t\treturn '#005824';\n\t} else if (population_num > 125000) {\n\t\treturn '#238b45';\n\t} else if (population_num > 100000) {\n\t\treturn '#41ae76';\n\t} else if (population_num > 75000) {\n\t\treturn '#66c2a4';\n\t} else if (population_num > 50000) {\n\t\treturn '#99d8c9';\n\t} else if (population_num > 25000) {\n\t\treturn '#ccece6';\n\t} else {\n\t\treturn '#edf8fb';\n\t}\n}",
"function analyzeColor(color) {\n var colorMessage = \"\";\n if(color === \"blue\") {\n colorMessage = \"blue is the color of the sky\";\n } else if(color === \"red\") {\n colorMessage = \"Strawberries are red\";\n } else if(color === \"cyan\") {\n colorMessage = \"I don't know anything about cyan\";\n } else {\n colorMessage = \"I don't know about that color\";\n }\n\n return colorMessage;\n}",
"function colorTarget() {\n let colorPicked = Math.floor(Math.random() * colors.length);\n return colors[colorPicked];\n}",
"function getClassColor(colors) {\n\n let colorClass;\n\n if (colors.r > colors.g && colors.r > colors.b) {\n colorClass = 1;\n } else if (colors.g > colors.r && colors.g > colors.b) {\n colorClass = 2;\n } else if (colors.b > colors.r && colors.b > colors.g) {\n colorClass = 3;\n } else {\n colorClass = 0;\n }\n\n return colorClass;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Author: HK Name: _getSelectedTilesKeys Description: collects selected tiles Keys Params: none Return: tilesKeys = array of selected tiles keys | function _getSelectedTilesKeys() {
var tilesKeys = [];
var nbSelectedtiles = lv_cockpits.winControl.selection.count();
for (var tileIterator = 0; tileIterator < nbSelectedtiles; tileIterator++) {
var currentItem = lv_cockpits.winControl.selection.getItems()._value[tileIterator];
tilesKeys.push(currentItem.key);
}
return tilesKeys;
} | [
"function _getSelectedTilesIds() {\n var tilesIds = [];\n var nbSelectedtiles = lv_cockpits.winControl.selection.count();\n for (var tileIterator = 0; tileIterator < nbSelectedtiles; tileIterator++) {\n var currentItemData = lv_cockpits.winControl.selection.getItems()._value[tileIterator].data;\n tilesIds.push(currentItemData.id);\n }\n\n return tilesIds;\n }",
"getSelectedItemKeys()\n {\n return Object.keys(this._selectedItems);\n }",
"function _removeTiles() {\n var tilesKeys = _getSelectedTilesKeys();\n var tilesIds = _getSelectedTilesIds();\n\n var _succeedHandler = function () {\n _removeTileSucceed(tilesKeys, tilesIds);\n };\n\n if (tilesIds.length > 0) {\n //join promise remove keys for mutli remove if needed\n CDHelper.showHideLoading(true);\n CockpitsServices.removeTiles(tilesIds[0], _succeedHandler, _removeTileFailed);\n }\n }",
"function render_select(context)\n{\n\tif(selection_coordinates != null)\n\t{\n\t\tstroke_tile(selection_coordinates.x, selection_coordinates.y, grid_selected_color, context);\n\t}\n}",
"function giveKeys(chords){\n\t\tvar addKey = true;\n\t\tvar retKeys = [];\n\t\tfor(var key in keys){\n\t\t\tfor(var chord in chords){\n\t\t\t\t//TESTING ONLY --- //$('div#testDiv p#testP').append(' --- Testing' + ' ' + chords[chord] + ' in ' + keys[key] + ', and the result is: ' + jQuery.inArray(chords[chord],keys[key])); //testing//\n\t\t\t\t\n\t\t\t\tif(jQuery.inArray(chords[chord],keys[key])===-1) {\n\t\t\t\t\taddKey = false;\n\t\t\t\t}\n\t\t\t} \n\t\t\tif(addKey===true){\n\t\t\t\tretKeys.push(key);\n\t\t\t}\t\t\t\t\t\t\n\t\t\taddKey = true;\t\t\t\t\t\t\n\t\t}\n\t\treturn retKeys;\n\t}",
"function getPressedKeys() {\n //holds all the keys that are pressed down\n let pressed = [];\n //itterates over every key in 'keysDown'\n for (var key in keysDown){\n if (keysDown.hasOwnProperty(key)) {\n //if key is held down, add it to 'pressed'\n if (keysDown[key] === true){\n pressed.push(key);\n }\n }\n }\n return pressed;\n}",
"function selectTile( e ){\n\tconsole.log( e );\n\t// this variable brings back the selected tile\n\tvar selected = e.path[ 0 ],\n\t\tplayer = getCurrentPlayer();\n\n\t// console.log( \"current player \", player );\n\t\n\t// we have access to the id of this element, so push to the array and cap at ship length * total no of ships\n\t// prevent the board itself from being pushed to the array and causing issues\n\tif ( selected.id !== \"battleship-board\" ){\n\t\tif ( player.ships[ player.shipNumber ].length < SHIPLENGTH ){\n\t\t\tcheckIfValidTile( selected.id, player.ships[ player.shipNumber ] );\n\t\t\tif ( player.ships[ player.shipNumber ].length === SHIPLENGTH ){\n\t\t\t\tplayer.shipNumber++;\n\t\t\t}\n\t\t}\n\t}\n\n\t// check the length and array for the ships\n\t// console.log( 'playerOneShips 1 length: ', playerOne.ships[ 0 ].length );\n\n\tif ( playerOne.turn && ( totalShips( playerOne ) === TOTALHITS ) ) {\n\t\tclearTiles();\n\t\tnextPlayerTurn();\n\t} \n\n\t// check to see if two humans are playing or human v computer\n\tif ( playerTwo.turn ) {\n\t\tif ( twoHumans ) {\n\t\t\ttotalShips( playerTwo ) === TOTALHITS ? beginBattle() : \"\"\n\t\t} else {\n\t\t\tcomputerSelectTiles();\n\t\t}\n\t}\n\n}",
"getDatasetsKeys(){\n let keys=this.localStorageService.keys();\n\n return keys;\n }",
"selectedList(state) {\n const selectedDirectories = state.directories.filter((directory) =>\n state.selected.directories.includes(directory.path)\n );\n\n const selectedFiles = state.files.filter((file) => state.selected.files.includes(file.path));\n\n return selectedDirectories.concat(selectedFiles);\n }",
"get selectedDataItems() {\n return this.composer.queryItemsByPropertyValue('selected', true);\n }",
"function getSelectedNodeIds() {\n return figma.currentPage.selection.filter(({ type }) => type === \"VECTOR\").map(({ id }) => id);\n}",
"lookupSelectedRegions() {\r\n const collection = Array();\r\n for (const region of this.regions) {\r\n if (region.isSelected) {\r\n collection.push(region);\r\n }\r\n }\r\n return collection;\r\n }",
"getSelectedElements() {\n return this.getSelectableElements().filter(item => item.selected);\n }",
"assignTilesEx(excludedIndexes)\n {\n let indices = [];\n while(indices.length<7){\n let pickedIndex =Math.floor((Math.random()*100)%28);\n if(indices.indexOf(pickedIndex)<0 && excludedIndexes.indexOf(pickedIndex)<0)\n {\n indices.push(pickedIndex);\n }\n }\n this.unassignedTilePositions = this.unassignedTilePositions.filter(pos=>indices.indexOf(pos)<0);\n return indices;\n }",
"getTourNames(){\n return this.tourMap.keys();\n }",
"function getTileArray () {\n var tileArray = $(\".mdl-card__title-text\").toArray();\n var result = [];\n tileArray.forEach(function (item) {\n result.push($(item).text().charCodeAt(0));\n });\n return result;\n }",
"loadKeysToActions() {\n // Clear beforehand in case we're reloading.\n this.keysToActions.clear();\n this.actions.forEach((action) => {\n const keys = action.getKeys();\n // TODO: For local co-op/split screen, set player-specific bindings.\n keys.forEach((key, inputType) => {\n // Get if this key is for a specific player, denoted by a \"-[0-9]\".\n if (SPLIT_SCREEN_REG.test(inputType)) {\n // This is a split-screen binding, add the player number to the key.\n const playerNumber = inputType.split('-').pop();\n key = `${key}-${playerNumber}`;\n }\n if (!this.keysToActions.has(key)) {\n this.keysToActions.set(key, new Array());\n }\n this.keysToActions.get(key).push(action);\n });\n });\n }",
"function getSelectedImagesId() {\n var imageIds = [];\n $( '#sortable > li' ).each( function() {\n imageIds.push( $( this ).attr( 'data-id' ) );\n });\n return imageIds;\n }",
"function getPathItemsInSelection( min_pathpoint_count, paths ){\n if(documents.length < 1) return;\n \n var selected_items = activeDocument.selection;\n \n if (!(selected_items instanceof Array)\n || selected_items.length < 1) return;\n \n extractPaths(selected_items, min_pathpoint_count, paths);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function:generateBaseStyleHeaderHTML (styleSrc, retPage) Purpose:generates HTML output with a sample header, the name of the style in italics, and two buttons. | function generateBaseStyleHeaderHTML (styleSrc, retPage)
{
// this code would normally go directly into the theme pages since its page
// specific, but it's used on 2 seperate pages relating to themes, and I didn't
// want to maintain this in 2 areas
var out = generateStyleHTML (styleSrc);
var myStyle = styleSrc;
if ((myStyle.indexOf("SC_") == 0) || (myStyle.indexOf("SS_") == 0))
myStyle = myStyle.slice (3);
out += "</p><p><a href='javascr";
out += "ipt:void(0)' onClick = 'if (submitToWindow){submitToWindow(\""+retPage+"\", \""+styleSrc;
out += "\", \"\", \""+gBASE_PAGE+"\", \""+gSTYLE_EDIT_PAGE+"\", \"495\", \"700\");}'>";
out += "<img src='/cgi-docs/Mercantec/PC_F_6.6.1/images/Edit_Nbtn_base2.gif' border='0' width='86' height='30' align='middle' alt='Edit your base style'></a>";
out += "<a href='javascr";
out += "ipt:void(0)' onClick = 'if (submitToWindow){submitToWindow(\""+retPage+"\", \""+styleSrc;
out += "\", \"\", \""+gBASE_PAGE+"\", \""+gSTYLE_SELECT_PAGE+"\", \"570\", \"670\");}'>";
out += "<img src='/cgi-docs/Mercantec/PC_F_6.6.1/images/Replace_Nbtn_base2.gif' border='0' width='86' height='30' align='middle' alt='Replace your base style'></a>";
out += "<a href='javascr";
out += "ipt:if (saveWindow){saveWindow();}";
out += "parent.SubmitForm (\"SE_SetAllToBaseStyle\", \""+retPage+"\", \"mainFrame\", \"\");'>";
out += "<img border='0' src='/cgi-docs/Mercantec/PC_F_6.6.1/images/Replace_All_With_Base_Nbtn_base_slg.gif' width='150' height='30' align='middle' alt='Replace all page styles with current base style'></a><br>";
return (out);
} | [
"function generateStyleHTML (styleSrc)\n{\n\treHeader = /\\.text-header\\s*\\{([^}]*)/\n\treBody = /\\.text-body\\s*\\{([^}]*)/\n\t\t\n\tif (styleSrc.indexOf(\"SS_\") == 0)\n\t\tvar style = doActionEx\t('DATA_READFILE',styleSrc, 'FileName', styleSrc,'ObjectName',\n\t\t\t\t\t\t\t\tgSTYLE_OBJ, 'FileType', 'txt');\n\telse\t\t\n\t\tvar style = doActionEx\t('DATA_READFILE',gSTYLES_DIR+styleSrc, 'FileName', gSTYLES_DIR+styleSrc,\n\t\t\t\t\t\t\t\t'ObjectName', gPUBLIC, 'FileType', 'txt');\n\n\tvar rc = \"<table width = '100%' border='1' bgcolor='#FFFFFF'><tr><td>\";\n rc += \"<div align='center'><b><i>\";\n rc += \"<font size='5' color='#000000' style = '\"+reHeader(style)[1]+\";TEXT-ALIGN: center;'>\";\n rc += \"Sample Header<br></font></i></b>\";\n rc += \"<font size='4' color='#000000' style = '\"+reBody(style)[1]+\";TEXT-ALIGN: center;'>\";\n rc += \"Sample Body</font></div></td></tr></table>\";\n\treturn (rc);\n}",
"function generateBaseThemeHeaderHTML (themeSrc, retPage)\n{\n\t// this code would normally go directly into the style pages since its page\n\t// specific, but it's used on 2 seperate pages relating to styles, and I didn't\n\t// want to maintain this in 2 areas\n\tvar myTheme = themeSrc;\n\tif ((myTheme.indexOf(\"TC_\") == 0) || (myTheme.indexOf(\"TS_\") == 0))\n\t\tmyTheme = myTheme.slice (3);\n\t\n\tvar out =generateThemeThumb (themeSrc, '');\n\tout += \"</p><p><a href='javascr\";\n\tout += \"ipt:void(0)' onClick = 'if (submitToWindow){submitToWindow(\\\"\"+retPage+\"\\\", \\\"\\\", \\\"\";\n\tout +=\tthemeSrc+\"\\\", \\\"\"+gBASE_PAGE+\"\\\", \\\"\"+gTHEME_EDIT_PAGE+\"\\\", \\\"500\\\", \\\"600\\\");}'>\";\n\tout += \"<img src='/cgi-docs/Mercantec/PC_F_6.6.1/images/Edit_Nbtn_base2.gif' border='0' width='86' height='30' align='middle' alt='Edit your base theme'></a>\";\n\tout += \"<a href='javascr\";\n\tout += \"ipt:void(0)' onClick = 'if (submitToWindow){submitToWindow(\\\"\"+retPage+\"\\\", \\\"\\\", \\\"\";\n\tout +=\tthemeSrc+\"\\\", \\\"\"+gBASE_PAGE+\"\\\", \\\"\"+gTHEME_SELECT_PAGE+\"\\\", \\\"570\\\", \\\"670\\\");}'>\";\n\tout += \"<img src='/cgi-docs/Mercantec/PC_F_6.6.1/images/Replace_Nbtn_base2.gif' border='0' width='86' height='30' align='middle' alt='Replace your base theme'></a>\";\n\tout += \"<a href='javascr\";\n\tout += \"ipt:if (saveWindow){saveWindow();}\";\n\tout +=\t\"parent.SubmitForm (\\\"SE_SetAllToBaseTheme\\\", \\\"\"+retPage+\"\\\", \\\"mainFrame\\\", \\\"\\\");'>\";\n\tout += \"<img border='0' src='/cgi-docs/Mercantec/PC_F_6.6.1/images/Replace_All_With_Base_Nbtn_base_slg.gif' width='150' height='30' align='middle' alt='Replace all page themes with current base theme'></a><br>\";\n\treturn (out);\n\t\n}",
"function T1_Header (link_num) {\n\n var codeBuffer = \"\";\n\n codeBuffer += '<div class=\"wrapper row1\">';\n codeBuffer += '<header id=\"header\" class=\"clear\">';\n codeBuffer += '<div id=\"hgroup\">';\n codeBuffer += '<h1><a href=\"#\">Generated Website</a></h1>';\n codeBuffer += '<h2>Your Motto Goes Here</h2>';\n codeBuffer += '</div>';\n codeBuffer += '<nav>';\n codeBuffer += '<ul>';\n \n // Populate links as neccessary\n for(var i = 0; i < link_num - 1; i++){\n codeBuffer += '<li><a href=\"#\">Text Link</a></li>';\n }\n\n // Force minimum one link for CSS.\n codeBuffer += '<li class=\"last\"><a href=\"#\">Text Link</a></li>';\n\n codeBuffer += '</ul></nav></header></div>';\n \n return codeBuffer;\n}",
"function htmlHeader( title, config )\n{\n origTitle = title;\n if (title==\"HomePage\") \n title = config.GENERAL.HOMEPAGE; \n print(\"<!DOCTYPE html PUBLIC \\\"-//W3C//DTD XHTML 1.0 Strict//EN\\\" \\\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\\\">\\n\");\n print(\"<html xmlns=\\\"http://www.w3.org/1999/xhtml\\\" xml:lang=\\\"ja-JP\\\" lang=\\\"ja-JP\\\">\\n\");\n print(\"<head>\");\n print(\"\\n\");\n print(\"\\t<meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=\"+config.GENERAL.ENCODE+\"\\\" />\\n\");\n css(origTitle);\n print(\"\\t<title>\");\n if (config.GENERAL.TITLE==title)\n print(config.GENERAL.TITLE);\n else\n print(config.GENERAL.TITLE+\">\"+title); \n print(\"</title>\\n\");\n print(\"</head>\\n\");\n print(\"<body>\\n\");\n}",
"function constructHeaderTbl() {\t\n\tprintHeadInnerTable = '<div class=\"page\"><table cellspacing=\"0\" class=\"printDeviceLogTable ContentTable\" style=\"font-size: 15px;height:45%;min-height:700px;max-height:780px;table-layout: fixed; width: 1100px;\" width=\"100%\">'\n\t\t+'<thead><tr><th rowspan=\"2\" width=\"50px\">Article</th>'\n\t\t+'<th rowspan=\"2\" width=\"5px\"></th>'\n\t\t+'<th rowspan=\"2\" class=\"columnDivider\">Description</th>'\n\t\t+'<th colspan=\"3\" class=\"centerValue columnDivider\">Last Received Details</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">OM</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">SOH</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"80px\">Units to Fill</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"100px\">LTO</th>'\n\t\t+'<th rowspan=\"2\" class=\"lastColumn leftValue\" width=\"140px\">Comment</th>'\n\t\t+'</tr><tr class=\"subHeader\">'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Date</th>'\n\t\t+'<th class=\"centerValue columnDivider\" width=\"50px\">Qty.</th>'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Order</th></tr></thead>';\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n}",
"function constructHeaderTbl1() {\t\n\tprintHeadInnerTable = '<div class=\"page\"><table cellspacing=\"0\" class=\"printDeviceLogTable ContentTable\" style=\"font-size: 15px;height:45%;min-height:580px;max-height:580px;table-layout: fixed; width: 1100px;\" width=\"100%\">'\n\t\t+'<thead><tr><th rowspan=\"2\" width=\"50px\">Article</th>'\n\t\t+'<th rowspan=\"2\" width=\"5px\"></th>'\n\t\t+'<th rowspan=\"2\" class=\"columnDivider\">Description</th>'\n\t\t+'<th colspan=\"3\" class=\"centerValue columnDivider\">Last Received Details</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">OM</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">SOH</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"80px\">Units to Fill</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"100px\">LTO</th>'\n\t\t+'<th rowspan=\"2\" class=\"lastColumn leftValue\" width=\"140px\">Comment</th>'\n\t\t+'</tr><tr class=\"subHeader\">'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Date</th>'\n\t\t+'<th class=\"centerValue columnDivider\" width=\"50px\">Qty.</th>'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Order</th></tr></thead>';\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n}",
"function generateTableHeaderRow(){\n var headerRowHTML = \"\";\n\n // TODO: Question 2 - Add additional table headers here to\n // give a header for each table data element.\n\n headerRowHTML += '<tr>';\n headerRowHTML += generateTableHeader(\"ID#\");\n headerRowHTML += generateTableHeader(\"First\");\n headerRowHTML += generateTableHeader(\"Last\");\n headerRowHTML += generateTableHeader(\"Email\");\n headerRowHTML += generateTableHeader(\"Home Address\");\n headerRowHTML += generateTableHeader(\"Job\");\n headerRowHTML += '</tr>';\n\n return headerRowHTML;\n }",
"function CreateWindowHeader(title, imgsrc, lng)\n {\n\t\ttext = \"<html>\\n\";\n\t\ttext += \" <head>\\n\";\n\t\ttext += \" <title>\" + title + \"</title>\\n\";\n\n\t\ttext += \" </head>\\n\";\n\t\ttext += \" <body bgcolor=\\\"#FFFFFF\\\" link=\\\"#000080\\\" vlink=\\\"#800080\\\">\\n\";\n\t\ttext += \" <form>\\n\";\n \n text += \" <table width=\\\"100%\\\">\\n\";\n text += \" <tr>\\n\";\n\t\ttext += \" <td width=\\\"50%\\\" valign=\\\"center\\\"><img src=\\\"\" + imgsrc + \"\\\"></td>\\n\";\n\t\ttext += \" <td width=\\\"50%\\\" valign=\\\"center\\\" align=\\\"right\\\">\\n\";\n \ttext += \" <font face=\\\"Verdana\\\" size=\\\"2\\\">\\n\"; \n text += \" <a href=\\\"javascript:void(0)\\\" onclick=\\\"self.close();\\\">\"\n \n switch (language)\n {\n case 'es': text += \"Cerrar\"; break;\n case 'pt': text += \"Fechar\"; break;\n default: text += \"Close\"; \n }\n text += \"</a>\\n\"\n text += \" </font>\\n\";\n text += \" </td>\\n\";\n text += \" </tr>\\n\";\n text += \" </table><br>\\n\";\n \n\t\ttext += \" <table>\\n\"; \n language = lng;\n }",
"function IMNGetHeaderImage()\n{\n return \"imnhdr.gif\";\n}",
"function getTableTitles() {\n return \"<thead class=\\\"tealColor\\\"><tr class=\\\"text-white\\\"><th>Order ID</th><th>Customer ID</th><th>Customer</th><th>Delivery Address</th><th>Delivery Date</th><th>Order Status</th></tr></thead>\";\n\n}",
"function renderHeader(sound) {\n var htmlEl = createEl('div');\n addClass(htmlEl,'header');\n htmlEl.appendChild(renderPlayButton(sound));\n htmlEl.appendChild(renderSoundTitle(sound));\n return htmlEl;\n }",
"function formatHeader( str ) {\n var defaultInfo = ['title','author','version','date','description','dependancies','references'];\n var info = {\n title : undefined,\n author : undefined,\n version : undefined,\n date : undefined,\n description : undefined,\n dependancies : undefined,\n references : undefined\n },\n headerinfo = [];\n\n // go thru each line of header\n str.split(/\\|/).forEach( function( line, indx ) {\n\n // parse file attributes and store name + value ( will use markdown to handle links/emphasis )\n headerinfo = line.match(/@(.+?) *?: *?(.+)/);\n\n if ( headerinfo ) {\n info[headerinfo[1]] = cheapMarkdown( headerinfo[2] );\n }\n\n } );\n\n // use custom user formater\n if ( settings.header ) {\n str = settings.headerFormater( info );\n } else {\n // build special `html` for header info\n var sourceFile = '<small><a href=\"'+ settings.source +'\"><span class=\"glyphicon glyphicon-file\"></span></a></small>';\n var authorStr = ( info.author ) ? '<small> by '+info.author + '</small>' : '';\n var descriptionStr = ( info.description ) ? '<p class=\"lead\">'+info.description+'</p>' : '';\n var versionStr = ( info.version ) ? 'Version '+info.version : '';\n var dateStr = ( info.date ) ? ' from '+info.date : '';\n var dependanciesStr = ( info.dependancies ) ? 'Dependancies : '+info.dependancies : '';\n var referencesStr = ( info.references ) ? 'References : '+info.references : '';\n\n str = '<h1>' + sourceFile + info.title + authorStr + '</h1>' + descriptionStr + '<p>'+ versionStr + dateStr +'<br>'+ dependanciesStr + '<br>'+ referencesStr + '</p>';\n\n var usrStr = '';\n // look for other user custom fields\n for (var key in info) {\n if ( $.inArray( key, defaultInfo ) === -1 ) {\n usrStr += key[0].toUpperCase()+key.slice(1)+' : '+info[key]+'<br>';\n }\n }\n\n str += '<p>' + usrStr + '</p>' + '<hr>';\n }\n\n return str;\n }",
"function generateThemeTableHTML (themeSrc, pageObj, ratio)\n{\n\tvar thumb_ratio = 0.0625;\n\tvar publish = 0;\n\tif (ratio < 0)\n\t{\n\t\tpublish = 1;\n\t\tratio = Math.abs(ratio);\n\t}\n\n\t// regular expression objects used for parsing info out of style sheets\n\t// do this so multiple tables can appear on a page, each with its own set of\n\t// style attributes\n\treTop = /\\.bkgrd-top\\s*\\{([^}]*)/\n\treLeft = /\\.bkgrd-left\\s*\\{([^}]*)/\n\treContent = /\\.bkgrd-content\\s*\\{([^}]*)/;\n\t\n\tvar mode = doAction('ST_GET_STATEDATA', 'PE_OutputMode', 'PE_OutputMode');\n\tif (mode && mode!=\"PE_EditMode\" && pageObj.SecureBaseHref.toLowerCase() == \"yes\")\n\t{\n\t\treTop = /\\.secure-bkgrd-top\\s*\\{([^}]*)/\n\t\treLeft = /\\.secure-bkgrd-left\\s*\\{([^}]*)/\n\t\treContent = /\\.secure-bkgrd-content\\s*\\{([^}]*)/;\n\t}\n\t\n\t\n\tif (themeSrc.indexOf(\"TS_\") == 0)\n\t\tvar theme = doActionEx\t('DATA_READFILE',themeSrc, 'FileName', themeSrc,'ObjectName',\n\t\t\t\t\t\t\t\tgTHEME_OBJ, 'FileType', 'txt');\n\telse\n\t\tvar theme = doActionEx\t('DATA_READFILE',gTHEMES_DIR+themeSrc, 'FileName', \n\t\t\t\t\t\t\t\tgTHEMES_DIR+themeSrc,'ObjectName', gPUBLIC, 'FileType', 'txt');\n\t\t\t\t\t\t\t\n\tif (!pageObj)\n\t{\n\t\tvar basePage = generateSEObjects (gBASE_PAGE);\n\t\tpageObj = basePage.pageObjArray[gBASE_PAGE];\n\t}\n\n\tratio = (ratio ? ratio : thumb_ratio);\n\tvar topHeight = (isNaN (pageObj.layoutObjArray.top.height) ? 5 : parseInt (pageObj.layoutObjArray.top.height * ratio));\n\tvar topWidth = (isNaN (pageObj.layoutObjArray.top.width) ? 50 : parseInt (pageObj.layoutObjArray.top.width * ratio));\n\tvar mainHeight = (isNaN (pageObj.layoutObjArray.main.height) ? 33 : parseInt (pageObj.layoutObjArray.main.height * ratio));\n\tvar mainWidth = (isNaN (pageObj.layoutObjArray.main.width) ? 38 : parseInt (pageObj.layoutObjArray.main.width * ratio));\n\tvar leftHeight = (isNaN (pageObj.layoutObjArray.left.height) ? 33 : parseInt (pageObj.layoutObjArray.left.height * ratio));\n\tvar leftWidth = (isNaN (pageObj.layoutObjArray.left.width) ? 12 : parseInt (pageObj.layoutObjArray.left.width * ratio));\n\n\t//var topHeight = 5, topWidth = 50, leftHeight = 33, leftWidth = 12, mainHeight = 33, mainWidth = 38; \t\t\t\t\t\t\n\t\n\t(leftWidth ? topColSpan = \"colspan=2\" : topColSpan = \"\");\n\n\tif (publish)\n\t{\n\t\tvar pageHeight = doAction('MPEA_GET_PAGEHEIGHT', 'Minimum', mainHeight.toString());\n\t\tif (!isNaN(pageHeight))\n\t\t\tmainHeight = pageHeight;\n\t\tvar rc = \"<table width=\"+topWidth+\" height=\"+(topHeight+mainHeight)+\" border=0 cellpadding=0 cellspacing=0>\";\n\t\trc += ((topHeight && topWidth) ? \"<tr><td \"+topColSpan+\" width=\"+topWidth+\" height=\"+topHeight+\" style = 'font-size: 2px;\"+reTop(theme)[1]+\"'><!--Begin_Top_Content--><img src=\\\"/cgi-docs/Mercantec/PC_F_6.6.1/images/pxtransparent.gif\\\" width=\"+topWidth+\" height=\"+topHeight+\"><!--End_Top_Content--></td></tr>\" : \"\");\n\t\trc += \"<tr>\";\n\t\trc += ((leftHeight && leftWidth) ? \"<td width=\"+leftWidth+\" height=\\\"100%\\\" style = '\"+reLeft(theme)[1]+\"'><!--Begin_Left_Content--><img src=\\\"/cgi-docs/Mercantec/PC_F_6.6.1/images/pxtransparent.gif\\\" width=\"+leftWidth+\" height=\"+leftHeight+\"><!--End_Left_Content--></td>\" : \"\");\n\t\trc += ((mainHeight && mainWidth) ? \"<td width=\"+mainWidth+\" height=\\\"100%\\\" style = '\"+reContent(theme)[1]+\"'><!--Begin_Main_Content--><img src=\\\"/cgi-docs/Mercantec/PC_F_6.6.1/images/pxtransparent.gif\\\" width=\"+mainWidth+\" height=\"+mainHeight+\"><!--End_Main_Content--></td>\" : \"\");\n\t\trc += \"</tr>\";\n\t\trc += \"</table>\";\n\t}\n\telse\n\t{\n\t\tif (ratio != thumb_ratio)\n\t\t{\n\t\t\t// Displaying a thumbnail, don't get page height\n\t\t\tvar pageHeight = doAction('MPEA_GET_PAGEHEIGHT', 'Minimum', mainHeight.toString());\n\t\t\tif (!isNaN(pageHeight))\n\t\t\t\tmainHeight = pageHeight;\n\t\t}\n\t\tvar rc = \"<table width=\"+topWidth+\" height=\"+(topHeight+mainHeight)+\" border=0 cellpadding=0 cellspacing=0>\";\n\t\trc += ((topHeight && topWidth) ? \"<tr><td \"+topColSpan+\" width=\"+topWidth+\" height=\"+topHeight+\" style = 'font-size: 2px;\"+reTop(theme)[1]+\"'><!--Begin_Top_Content--><img src=\\\"/cgi-docs/Mercantec/PC_F_6.6.1/images/pxtransparent.gif\\\" width=\"+topWidth+\" height=1><!--End_Top_Content--></td></tr>\" : \"\");\n\t\trc += \"<tr>\";\n\t\trc += ((leftHeight && leftWidth) ? \"<td width=\"+leftWidth+\" height=\"+leftHeight+\" style = '\"+reLeft(theme)[1]+\"'><!--Begin_Left_Content--><img src=\\\"/cgi-docs/Mercantec/PC_F_6.6.1/images/pxtransparent.gif\\\" width=\"+leftWidth+\" height=1><!--End_Left_Content--></td>\" : \"\");\n\t\trc += ((mainHeight && mainWidth) ? \"<td width=\"+mainWidth+\" height=\"+mainHeight+\" style = '\"+reContent(theme)[1]+\"'><!--Begin_Main_Content--><img src=\\\"/cgi-docs/Mercantec/PC_F_6.6.1/images/pxtransparent.gif\\\" width=\"+mainWidth+\" height=1><!--End_Main_Content--></td>\" : \"\");\n\t\trc += \"</tr>\";\n\t\trc += \"</table>\";\n\t}\n\treturn (rc);\n}",
"function addHeaderStyle(element) {\n element.style.margin = '6px 0px 3px 0px';\n element.style.width = width + 'px';\n element.style.textAlign = 'center';\n element.style.backgroundColor = '#cccccc';\n element.style.fontVariant = 'small-caps';\n element.style.fontWeight = 'normal';\n element.style.fontSize = '0.8em';\n }",
"function echoHeader()\n{\n echo('<html><head>');\n echo('<title>Select Address</title>');\n echo('</head>');\n echo('<body>');\n}",
"function generatePotHeader(options) {\n\n\t// Get the date\n\tvar d = new Date();\n\tvar now = d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2) + ' ' +\n\t\t\t+('0' + d.getHours()).slice(-2) + ':' + ('0' + d.getMinutes()).slice(-2) + \"+0000\";\n\n\t// Assemble Header\n\treturn '# POT Base Template for '+options.project+' Translation\\n' +\n\t\t\t'# Copyright (C) 2018 '+options.company+'\\n' +\n\t\t\t'# This file is distributed under the same license as the '+options.package+' package.\\n' +\n\t\t\t'# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.\\n' +\n\t\t\t'#\\n' +\n\t\t\t'#, fuzzy\\n' +\n\t\t\t'msgid \"\"\\n' +\n\t\t\t'msgstr \"\"\\n' +\n\t\t\t'\"Project-Id-Version: PACKAGE VERSION\\\\n\"\\n' +\n\t\t\t'\"Report-Msgid-Bugs-To: \\\\n\"\\n' +\n\t\t\t'\"POT-Creation-Date: ' + now + '\\\\n\"\\n' +\n\t\t\t'\"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\\\n\"\\n' +\n\t\t\t'\"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\\\n\"\\n' +\n\t\t\t'\"Language-Team: LANGUAGE <LL@li.org>\\\\n\"\\n' +\n\t\t\t'\"Language: \\\\n\"\\n' +\n\t\t\t'\"MIME-Version: 1.0\\\\n\"\\n' +\n\t\t\t'\"Content-Type: text/plain; charset=UTF-8\\\\n\"\\n' +\n\t\t\t'\"Content-Transfer-Encoding: 8bit\\\\n\"\\n';\n}",
"generateHeader() {\n let res = []\n for (var i = 0; i < columnHeader.length; i++) {\n res.push(<th key={columnHeader[i]}>{columnHeader[i]}</th>)\n }\n return res;\n }",
"generate_preamble(headers) {\n let header_class = '';\n if (this.kramdown) {\n header_class = (this.global.final === true || this.global.auto === false) ? '{: .no_toc}' : '{: .no_toc .draft_notice_needed}';\n }\n else {\n header_class = '';\n }\n const no_toc = (this.kramdown) ? '{: .no_toc}' : '';\n const core_header = `\n# ${headers.meeting} — Minutes\n${header_class}\n${this.global.final === true || this.global.auto === true ? '' : '***– DRAFT Minutes –***'}\n${(this.global.final === true || this.global.auto === true) && this.kramdown ? '' : '{: .draft_notice}'}\n\n**Date:** ${headers.date}\n\nSee also the [Agenda](${headers.agenda}) and the [IRC Log](${this.global.orig_irc_log})\n\n## Attendees\n${no_toc}\n**Present:** ${headers.present.join(', ')}\n\n**Regrets:** ${headers.regrets.join(', ')}\n\n**Guests:** ${headers.guests.join(', ')}\n\n**Chair:** ${headers.chair.join(', ')}\n\n**Scribe(s):** ${headers.scribe.join(', ')}\n`;\n return core_header;\n }",
"function createStyleSheet() {\n \n //Create stylesheet\n var stylesheet = Banana.Report.newStyleSheet();\n \n //Set page layout\n var pageStyle = stylesheet.addStyle(\"@page\");\n\n //Set the margins\n pageStyle.setAttribute(\"margin\", \"10mm 5mm 10mm 5mm\");\n pageStyle.setAttribute(\"size\", generalParam.pageSize);\n\n\n /*\n General styles\n */\n stylesheet.addStyle(\"body\", \"font-family : Times New Roman; font-size:10pt; color:\" + generalParam.frameColor);\n stylesheet.addStyle(\".font-size-digits\", \"font-size:6pt\");\n stylesheet.addStyle(\".text-green\", \"color:\" + generalParam.frameColor);\n stylesheet.addStyle(\".text-black\", \"color:black\");\n\n stylesheet.addStyle(\".border-top\", \"border-top: thin solid \" + generalParam.frameColor);\n stylesheet.addStyle(\".border-right\", \"border-right: thin solid \" + generalParam.frameColor);\n stylesheet.addStyle(\".border-bottom\", \"border-bottom: thin solid \" + generalParam.frameColor);\n stylesheet.addStyle(\".border-left\", \"border-left: thin solid \" + generalParam.frameColor);\n stylesheet.addStyle(\".border-left-1px\", \"border-left: 1px solid \" + generalParam.frameColor);\n stylesheet.addStyle(\".border-top-double\", \"border-top: 0.8px double black\");\n\n stylesheet.addStyle(\".border-top-black\", \"border-top: 0.5px solid black\");\n stylesheet.addStyle(\".border-right-black\", \"border-right: thin solid black\");\n stylesheet.addStyle(\".border-bottom-black\", \"border-bottom: thin solid black\");\n stylesheet.addStyle(\".border-left-black\", \"border-left: thin solid black\");\n\n stylesheet.addStyle(\".padding-left\", \"padding-left:5px\");\n stylesheet.addStyle(\".padding-right\", \"padding-right:5px\");\n stylesheet.addStyle(\".underLine\", \"border-top:thin double black\");\n\n stylesheet.addStyle(\".heading1\", \"font-size:16px;font-weight:bold\");\n stylesheet.addStyle(\".heading2\", \"font-size:12px\");\n stylesheet.addStyle(\".bold\", \"font-weight:bold\");\n stylesheet.addStyle(\".alignRight\", \"text-align:right\");\n stylesheet.addStyle(\".alignCenter\", \"text-align:center\");\n\n \n /* \n Info table style\n */\n style = stylesheet.addStyle(\"table_info\");\n style.setAttribute(\"width\", \"100%\");\n style.setAttribute(\"font-size\", \"8px\");\n stylesheet.addStyle(\"table.table_info td\", \"padding-bottom: 2px; padding-top: 5px;\");\n\n //Columns for the info table\n stylesheet.addStyle(\".col1\", \"width:37%\");\n stylesheet.addStyle(\".col2\", \"width:5%\");\n stylesheet.addStyle(\".col3\", \"width:5%\");\n stylesheet.addStyle(\".col4\", \"width:2%\");\n stylesheet.addStyle(\".col5\", \"width:5%\");\n stylesheet.addStyle(\".col6\", \"width:2%\");\n stylesheet.addStyle(\".col7\", \"width:5%\");\n stylesheet.addStyle(\".col8\", \"width:2%\");\n stylesheet.addStyle(\".col9\", \"width:15%\");\n stylesheet.addStyle(\".col10\", \"width:15%\");\n stylesheet.addStyle(\".col11\", \"width:%\");\n\n /*\n Transactions table style\n */\n style = stylesheet.addStyle(\"table\");\n style.setAttribute(\"width\", \"100%\");\n style.setAttribute(\"font-size\", \"8px\");\n stylesheet.addStyle(\"table.table td\", \"padding-bottom: 4px; padding-top: 6px\");\n\n //Columns for the transactions table\n stylesheet.addStyle(\".c1\", \"width:25%\");\n stylesheet.addStyle(\".c2\", \"width:25%\");\n stylesheet.addStyle(\".c3\", \"width:25%\");\n stylesheet.addStyle(\".cs1\", \"width:0.4%\");\n stylesheet.addStyle(\".c4\", \"width:10%\");\n stylesheet.addStyle(\".cs2\", \"width:0.4%\");\n stylesheet.addStyle(\".c5\", \"width:10%\");\n stylesheet.addStyle(\".cs3\", \"width:0.4%\");\n stylesheet.addStyle(\".c6\", \"width:3.2%\");\n\n stylesheet.addStyle(\".ct1\", \"width:20%\");\n stylesheet.addStyle(\".ct2\", \"width:20%\");\n stylesheet.addStyle(\".ct3\", \"width:10%\");\n stylesheet.addStyle(\".ct4\", \"width:10%\");\n stylesheet.addStyle(\".ct5\", \"width:10%\");\n stylesheet.addStyle(\".ct6\", \"width:10%\");\n stylesheet.addStyle(\".cts1\", \"width:0.4%\");\n stylesheet.addStyle(\".ct7\", \"width:10%\");\n stylesheet.addStyle(\".cts2\", \"width:0.4%\");\n stylesheet.addStyle(\".ct8\", \"width:10%\");\n stylesheet.addStyle(\".cts3\", \"width:0.4%\");\n stylesheet.addStyle(\".ct9\", \"width:3.2%\");\n\n /*\n Signatures table style\n */\n style = stylesheet.addStyle(\"table_signatures\");\n style.setAttribute(\"width\", \"100%\");\n style.setAttribute(\"font-size\", \"8px\");\n stylesheet.addStyle(\"table.table_signatures td\", \"padding-bottom: 5px; padding-top: 5px;\");\n\n //Column for the signatures table\n stylesheet.addStyle(\".colSig1\", \"width:16.6%\");\n stylesheet.addStyle(\".colSig2\", \"width:16.6%\");\n stylesheet.addStyle(\".colSig3\", \"width:16.6%\");\n stylesheet.addStyle(\".colSig4\", \"width:16.6%\");\n stylesheet.addStyle(\".colSig5\", \"width:16.6%\");\n stylesheet.addStyle(\".colSig6\", \"width:16.6%\");\n\n return stylesheet;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find multiple radar problems that match a query | function find(query, callBack) {
// use a custom radar fieldset appropriate for a grid view (avoid any ws performance hit)
var fields = 'id,title,component,assignee,lastModifiedAt,state,substate,classification,priority,'+
'resolution,reproducible,milestone';
post('/problems/find', { query: query, fields: fields }, callBack);
} | [
"function getProblemsByPermalinks(permalinsArray){\n var problemsObj=[];\n lab1:for (var i=0; i<permalinsArray.length; i++) {\n for (var j=0;j<problems.length; j++) {\n if (problems[j].permalink == permalinsArray[i]) {\n problemsObj.push(problems[j]);\n continue lab1;\n }\n }\n }\n // sort problems by complexity\n return sortByComplexity(problemsObj);\n \n}",
"function relevance() { \n\n\tfor (var i = 0; i < selection.network.links.length; i++) { // for each link\n\t\tif ((selection.network.links[i].source == selection.seed || selection.network.links[i].target == selection.seed) && // one of the arguments is the seed\n\t\t\t(selection.network.links[i].source != selection.network.links[i].target ) &&\t\t\t// link is not circular (subject != object)\n\t\t\t(selection.network.links[i].source.novel == true && selection.network.links[i].target.novel == true)) { // arguments are novel\n\n\t\t\tfor (var j = 0; j < selection.network.links[i].predicate.length; j++) { \t// for each predicate of each link\n\n\t\t\t\tvar checkRule = findRelevanceRule(selection.network.links[i].predicate[j].label, \n\t\t\t\t\t\t \t\t\tselection.network.links[i].source.semtype, selection.network.links[i].target.semtype);\n\n\t\t\t\tif (checkRule != -1) {\n\n\t\t\t\t\t//position in middle of canvas\t\t\t\t \n\t\t\t\t\tselection.network.links[i].source.x = selection.network.links[i].target.x = width/2;\n\t\t\t\t\tselection.network.links[i].source.y = selection.network.links[i].target.y = height/2;\n\t\t\t\t\tselection.network.links[i].source.fixed = selection.network.links[i].target.fixed = false;\n\n\t\t\t\t\tif (findNode(selection.network.links[i].source.id, summaryNodes) == -1) summaryNodes.push(selection.network.links[i].source);\n\n\t\t\t\t\tif (findNode(selection.network.links[i].target.id, summaryNodes) == -1) summaryNodes.push(selection.network.links[i].target);\n\n\t\t\t\t\tvar linkFound = findLink(selection.network.links[i], summaryLinks);\n\n\t\t\t\t\tif (linkFound != -1) { // link exists\n\n\t\t\t\t\t\tvar predicateFound = findPredicate(selection.network.links[i].predicate[j], summaryLinks[linkFound] );\n\n\t\t\t\t\t\tif (predicateFound == -1 ) { // predicate doesn't exist\n\n\t\t\t\t\t\t\tsummaryLinks[linkFound].predicate.push(selection.network.links[i].predicate[j]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t} else { summaryLinks.push(selection.network.links[i]); }\n\t\t\t\t\t\t\n\t\t\t\t} // found relevance rule\n\n\t\t\t} // for each predicate of each link\n\t\t\t\t\t\t\n\t\t} // one of the arguments is the seed node AND link is not circular AND arguments are novel\n\t\t\n\t} // for each link\n\n}",
"static getMismatches(rushConfiguration, options = {}) {\n // Collect all the preferred versions into a single table\n const allPreferredVersions = {};\n const commonVersions = rushConfiguration.getCommonVersions(options.variant);\n commonVersions.getAllPreferredVersions().forEach((version, dependency) => {\n allPreferredVersions[dependency] = version;\n });\n // Create a fake project for the purposes of reporting conflicts with preferredVersions\n // or xstitchPreferredVersions from common-versions.json\n const projects = [...rushConfiguration.projects];\n projects.push({\n packageName: 'preferred versions from ' + RushConstants_1.RushConstants.commonVersionsFilename,\n cyclicDependencyProjects: new Set(),\n packageJsonEditor: PackageJsonEditor_1.PackageJsonEditor.fromObject({ dependencies: allPreferredVersions }, 'preferred-versions.json') // tslint:disable-line:no-any\n });\n return new VersionMismatchFinder(projects, commonVersions.allowedAlternativeVersions);\n }",
"function getPossibleMatches(plays)\n{\n //an object that represents all the possible win outcomes by box index\n let matches =\n {\n horizontal: '012/345/678/', vertical: '036/147/258/', diagonal: '048/246/'\n };\n\n //replaces 'matches' indexes with the respective value from 'plays'\n matches = plays.reduce((matches, play, index) =>\n {\n matches.horizontal = matches.horizontal.replace(`${index}`, play);\n matches.vertical = matches.vertical.replace(`${index}`, play);\n matches.diagonal = matches.diagonal.replace(`${index}`, play);\n matches.diagonal = matches.diagonal.replace(`${index}`, play);\n\n return matches;\n\n }, matches);\n\n return matches;\n}",
"function getSearchArray(original, originalu, query) {\n var destination = [];\n var destinationu = [];\n\n for (var i = 0; i < original.length; ++i) {\n var penalty = find(original[i].toLowerCase(), query);\n if (penalty > -1 && penalty < original[i].length / 3) {\n destination.push(original[i]);\n destinationu.push(originalu[i]);\n }\n }\n\n return [destination, destinationu];\n}",
"function findProblems(graph, x) {\n\t\tvar problems = [],\n\t\t\tproblem_start,\n\t\t\tproblem_width,\n\t\t\tnodes = graph.querySelectorAll('[data-info]');\n\n\t\tfor (var i = 0, l = nodes.length; l > i; i++) {\n\t\t\tproblem_start = +nodes[i].getAttribute('x');\n\t\t\tproblem_width = +nodes[i].getAttribute('width');\n\n\t\t\tif (x > problem_start && problem_start + problem_width > x) {\n\t\t\t\tproblems.push(JSON.parse(nodes[i].getAttribute('data-info')));\n\t\t\t}\n\t\t}\n\n\t\treturn problems;\n\t}",
"async function getParcoursupCoverage(formation) {\n const sirets = [formation.siret_cerfa ?? \"\", formation.siret_map ?? \"\"];\n const uais = [\n formation.uai_affilie,\n formation.uai_gestionnaire,\n formation.uai_composante,\n formation.uai_insert_jeune ?? \"\",\n formation.uai_cerfa ?? \"\",\n formation.uai_map ?? \"\",\n ];\n\n const m0 = await getMatch({\n $or: [{ rncp_code: { $in: formation.codes_rncp_mna } }, { cfd_entree: { $in: formation.codes_cfd_mna } }],\n published: true,\n });\n\n // strength 1\n const m1 = m0.filter((f) => hasInsee(f, formation.code_commune_insee)); // insee + (rncp ou cfd)\n\n // strength 2\n const m2 = m0.filter((f) => hasSiret(f, sirets)); // siret + (rncp ou cfd)\n const m3 = m0.filter((f) => hasUai(f, uais)); // uai + (rncp ou cfd)\n\n // strength 3\n const m4 = m1.filter((f) => hasUai(f, uais)); // insee + uai + (rncp ou cfd)\n\n // strength 5\n const m5 = m1.filter((f) => hasPostalCode(f, formation.code_postal)); // code postal + insee + (rncp ou cfd)\n const m6 = m5.filter((f) => hasRncp(f, formation.codes_rncp_mna) && hasCfd(f, formation.codes_cfd_mna)); // code postal + insee + rncp + cfd\n const m7 = m5.filter((f) => hasUai(f, uais)); // uai + code postal + insee + (rncp ou cfd)\n const m8 = m6.filter((f) => hasUai(f, uais)); // uai + code postal + insee + rncp + cfd\n\n // strength 6\n const m9 = m5.filter((f) => hasAcademy(f, formation.nom_academie)); // academie + code postal + insee + (rncp ou cfd)\n const m10 = m6.filter((f) => hasAcademy(f, formation.nom_academie)); // academie + code postal + insee + rncp + cfd\n const m11 = m7.filter((f) => hasAcademy(f, formation.nom_academie)); // academie + uai + code postal + insee + (rncp ou cfd)\n const m12 = m8.filter((f) => hasAcademy(f, formation.nom_academie)); // academie + uai + code postal + insee + rncp + cfd\n\n // strength 7\n const m13 = m2.filter((f) => hasInsee(f, formation.code_commune_insee) && hasAcademy(f, formation.nom_academie)); // insee + academie +siret + (rncp ou cfd)\n const m14 = m13.filter((f) => hasUai(f, uais)); // uai + insee + academie +siret + (rncp ou cfd)\n\n // strength 8\n const m15 = m13.filter((f) => hasRncp(f, formation.codes_rncp_mna) && hasCfd(f, formation.codes_cfd_mna)); // insee + academie +siret + rncp + cfd\n const m16 = m14.filter((f) => hasRncp(f, formation.codes_rncp_mna) && hasCfd(f, formation.codes_cfd_mna)); // uai + insee + academie + siret + rncp + cfd\n\n const psMatchs = [\n {\n strength: \"8\",\n result: m16,\n },\n {\n strength: \"8\",\n result: m15,\n },\n {\n strength: \"7\",\n result: m14,\n },\n {\n strength: \"7\",\n result: m13,\n },\n {\n strength: \"6\",\n result: m12,\n },\n {\n strength: \"6\",\n result: m11,\n },\n {\n strength: \"6\",\n result: m10,\n },\n {\n strength: \"6\",\n result: m9,\n },\n {\n strength: \"5\",\n result: m8,\n },\n {\n strength: \"5\",\n result: m7,\n },\n {\n strength: \"5\",\n result: m6,\n },\n {\n strength: \"5\",\n result: m5,\n },\n {\n strength: \"3\",\n result: m4,\n },\n {\n strength: \"2\",\n result: m3,\n },\n {\n strength: \"2\",\n result: m2,\n },\n {\n strength: \"1\",\n result: m1,\n },\n ];\n\n let match = null;\n\n for (let i = 0; i < psMatchs.length; i++) {\n const { result, strength } = psMatchs[i];\n\n if (result.length > 0) {\n match = {\n matching_strength: strength,\n data_length: result.length,\n data: result.map(({ _id, cle_ministere_educatif, intitule_court, parcoursup_statut }) => {\n return {\n intitule_court,\n parcoursup_statut,\n _id,\n cle_ministere_educatif,\n };\n }),\n };\n\n break;\n }\n }\n\n return match;\n}",
"async function matchJobTitle(userIdIn, preferenceIn) {\n\n var db = await MongoClient.connect(process.env.PROD_MONGODB);\n var searchPreferences = await db.collection('preferences').find({userId: new ObjectID(userIdIn)}).toArray();\n //console.log(searchPreferences);\n var locationPrefs = [];\n for (var i = 0; i < searchPreferences.length; i++) {\n if (searchPreferences[i].type == 'location') {\n //var commaIndex = searchPreferences[i].preference.indexOf(',');\n locationPrefs.push(searchPreferences[i].preference); //.slice(0, commaIndex));\n }\n }\n var {preference} = preferenceIn;\n\n var locationsOR = [];\n for (var i = 0; i < locationPrefs.length; i++) {\n var commaIndex = locationPrefs[i].indexOf(',');\n var citySegment = locationPrefs[i].slice(0, commaIndex);\n var stateSegment = locationPrefs[i].slice(commaIndex + 2);\n locationsOR.push({city: citySegment, state: stateSegment});\n }\n\n if (locationsOR.length > 0) {\n var matches = await db.collection('jobs').find(\n {crawled: true, jobTitle: { $regex: preference, $options: 'i' }, $or: locationsOR }\n ).project({_id: 1}).toArray();\n\n await db.close();\n return matches.map(function(a) {return a._id;});\n }\n else {\n await db.close();\n return [];\n }\n}",
"function getRightAnswers() {\n}",
"function reCluster() {\n console.log(cluster);\n for (var i = 0; i < cluster.length; i++) {\n if (cluster[i].checked === false) {\n findMatch(cluster[i].row, cluster[i].col);\n }\n }\n}",
"function multiSearch ( params ) {\n logger.silly('Multi search on params', params);\n var url = 'http://www.thecocktaildb.com/api/json/v1/1/filter.php?';\n if (params.hasOwnProperty('i')) {\n for (var param in params['i']) {\n url = url + 'i=' + param + '&';\n }\n }\n if (params.hasOwnProperty('c')) {\n if (checkType(params['c'])) {\n url = url + 'c=' + params['c'] + '&';\n } else {\n logger.warn('Multisearch given incorrect type (' + params['c'] + '), skipping in search');\n }\n }\n if (params.hasOwnProperty('a')) {\n if (params['a']) {\n url = url + 'a=' + 'Alcoholic' + '&';\n } else {\n url = url + 'a=' + 'Non_Alcoholic' + '&';\n }\n }\n logger.info('Created search term ' + url + ' from multisearch');\n\n return rp( {\n url: url,\n json: true\n }).then(function (res) {\n return res.drinks;\n }, function (err) {\n return err;\n });\n}",
"function findRelevanceRule(label, subSemtype, objSemtype) {\n\n\t\tfor (var j = 0; j < selection.summarization.rules.length; j++) {\n\t\t\t\n\t\t\tif (selection.summarization.rules[j].label == label){\n\t\t\n\t\t\t\tfor (var k = 0; k < selection.summarization.rules[j].typePairs.length; k++) {\n\n\t\t\t\t\tvar foundSubject = findSemtypeInDomain(subSemtype, selection.summarization.rules[j].typePairs[k].subject);\n\t\t\t\t\tvar foundObject = findSemtypeInDomain(objSemtype, selection.summarization.rules[j].typePairs[k].object);\n\n\t\t\t\t\tif (foundSubject != -1 && foundObject != -1) return j + \".\" + k;\n\t\t\t\t\t\n\t\t\t\t} // for each rule's semantic type pair\t\t\n\t\t\t\n\t\t\t} // if correct predicate\n\t\t\t\t\n\t\t} // for each rule\n\n\treturn -1;\n}",
"async familiarityDistance(l, r) {\n let distanceSum = 0;\n let lCategories = await l.getCategories();\n let rCategories = await r.getCategories();\n for (let lc of lCategories) {\n for (let rc of rCategories) {\n distanceSum += this.levenshteinDistance(lc, rc);\n }\n }\n let titleDistance = this.levenshteinDistance(l.getTitle(), r.getTitle()); //distance between titles\n distanceSum += titleDistance;\n return distanceSum / (lCategories.length * rCategories.length + 1); //Total sum divided by number of distaces\n }",
"displayTopEightMatchedRespondents() {\n console.log(\"\\nTop 8 matches- by matching scores:\");\n console.log(\"===================================\\n\");\n\n for (let i = 0; i < 8; i++) {\n const curr = this.results[this.results.length - 1 - i];\n console.log(i);\n console.log(\n `Name: ${curr.name.slice(0, 1).toUpperCase()}${curr.name.slice(\n 1\n )}`\n );\n console.log(\n `Distance to closest available city: ${curr.closestAvailableCity.distance}km`\n );\n console.log(`Matching Score: ${curr.score}`);\n console.log(\"-------------------------------\");\n }\n }",
"static getAll() {\n return db.any(`\n SELECT * FROM results`\n )\n .then(resultArray => {\n const instanceArray = resultArray.map(resultObj => {\n return new Result(resultObj.id, resultObj.id_resultset, resultObj.id_question, resultObj.correct);\n });\n return instanceArray;\n });\n }",
"function findResults(lines, keyword){\n arr = [];\n for (var i in lines){\n var terms = parseTerms(lines[i])[0][0];\n if (terms){\n if (terms.predicate != undefined){\n if (terms.predicate==\"result\"){\n try{\n if (keyword==\"tick\"){\n var keyword2 = terms.terms[0].predicate;\n }\n else{\n var keyword2 = terms.terms[0].terms[0].predicate;\n }\n\n if (keyword==keyword2){\n arr.push(lines[i].substring(6));\n }\n }catch(err){}\n }\n }\n }\n }\n return arr;\n }",
"function getMatchingPieces(){\n let ret = {\n \"head\": new Set(),\n \"chest\": new Set(),\n \"arms\": new Set(),\n \"waist\": new Set(),\n \"legs\": new Set()\n }\n \n // Add each required skill's pieces to the set by name\n // For each armor type (head, chest, ...)\n let realSearch = false;\n for(let key of Object.keys(ret)){\n // Add placeholder item (imitates an empty/unneeded piece)\n\n // For each armor skill in this armor piece\n for(let skill of Object.keys(selectedSkills)){\n // Check if the skill level has been set to 0\n if(selectedSkills[skill] != \"0\"){\n realSearch = true;\n // For each entry in the list of armor names\n for(let name of armorsBySkill[key][skill]){\n ret[key].add(name)\n }\n }\n }\n\n if(!realSearch){\n return ret;\n } else{\n ret[\"head\"].add(\"---\")\n ret[\"chest\"].add(\"---\");\n ret[\"arms\"].add(\"---\");\n ret[\"waist\"].add(\"---\");\n ret[\"legs\"].add(\"---\");\n }\n\n // Include slot-only armors if checked\n if(inclSlotArmors && realSearch){\n ret[\"head\"].add(\"Skull\")\n ret[\"chest\"].add(\"Vaik\");\n ret[\"arms\"].add(\"Jyura\");\n ret[\"waist\"].add(\"Chrome Metal\");\n ret[\"legs\"].add(\"Arzuros\");\n }\n }\n\n return ret;\n}",
"function buscarCoincidencias(palabra) {\n\t elegidos=[];\n\t if (palabra == \"Todas las rutas\") {\n\t elegidos = rutas;\n\t }else {\n\t for (var i = 0; i < rutas.length; i++) {\n\t if (rutas[i].categoria.indexOf(palabra) !== -1) {\n\t elegidos.push(rutas[i]);\n\t }\n\t }\n\t }\n\t return elegidos;\n\t}",
"loadIcd10RelatedDiagnoses(diagnosis, searchByField) {\n if (!diagnosis.get('needsIcd10Refinement')) {\n return Ember.RSVP.resolve([]);\n }\n var DEFAULT_SEARCH_BY_FIELD = 'icd9Code',\n searchTerm;\n searchByField = searchByField || DEFAULT_SEARCH_BY_FIELD;\n searchTerm = diagnosis.get(searchByField) || diagnosis.get(DEFAULT_SEARCH_BY_FIELD) || diagnosis.get('name');\n return this.search(searchTerm, ['icd10', 'icd9'], []).then(function (searchResults) {\n var shallowFlatFlag = true,\n sortFlag = false,\n icd9Code = diagnosis.get('icd9Code'),\n resultsForThisIcd9 = searchResults,\n diagnosisCodesForThisIcd9,\n icd10CodesForThisIcd9,\n uniqueIcd10Codes,\n icd10Diagnoses,\n icd10DiagnosesArray;\n\n if (icd9Code) {\n resultsForThisIcd9 = searchResults.filter(function (searchResult) {\n // Filter by icd9\n const list = _.flatten(searchResult.get('icd9Codes')).mapBy('code');\n if (list.includes(icd9Code)) {\n return true;\n }\n /*\n Check for trailing zeros where simple string comparison won't work (ex. 60.0 is equal to 60.00)\n Since ICD-9 codes can start with a V or E we can't just use parseFloat for comparison\n */\n for (let i = 0; i < list.length; i++) {\n const currentCode = list[i];\n if (currentCode.length !== icd9Code.length && currentCode.indexOf('.') > 0 && icd9Code.indexOf('.') > 0) {\n const longerCode = currentCode.length > icd9Code.length ? currentCode : icd9Code;\n const shorterCode = longerCode === currentCode ? icd9Code : currentCode;\n\n if (longerCode.match('^' + shorterCode) && parseInt(longerCode.substring(shorterCode.length)) === 0) {\n return true;\n }\n }\n }\n return false;\n });\n }\n diagnosisCodesForThisIcd9 = _.flatten(resultsForThisIcd9.mapBy('diagnosisCodes'), shallowFlatFlag);\n icd10CodesForThisIcd9 = diagnosisCodesForThisIcd9.filter(function (codeObject) {\n return codeObject.isEvery('codeSystem', 'ICD10');\n });\n uniqueIcd10Codes = _.unique(icd10CodesForThisIcd9, sortFlag, function (codes) {\n // Removes dups considering all the sets of combinatory codes as unique\n return codes.mapBy('code').sort().join('&');\n });\n icd10Diagnoses = uniqueIcd10Codes.map(function (diagnosisCodes) {\n return _diagnosis.default.wrap({\n diagnosisCodes: diagnosisCodes\n });\n });\n icd10DiagnosesArray = _diagnosesArray.default.createArray(icd10Diagnoses);\n return icd10DiagnosesArray;\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.