query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
displayAll combines data from the three tables in our database into one | function displayAll() {
connection.query("SELECT e.id, e.first_name, e.last_name, r.title, r.salary, d.name, m.first_name AS ? , m.last_name AS ? FROM employee e JOIN role r ON e.role_id = r.id JOIN department d ON r.department_id = d.id LEFT JOIN employee m on e.manager_id = m.id;", ["manager_first_name", "manager_last_name"], function (err, res) {
renderTable(err, res);
})
} | [
"function viewAll(){\n connection.query(\"select employee.id, first_name, last_name, title, department.name, salary from employee inner join role on employee.id = role.id inner join department on department.id = role.id\",\n (err, data) =>{\n if (err) throw err;\n console.table(data)\n initalise();\n // connection.end\n })\n}",
"function showAll() {\r\n getData().then( (eps) => { \r\n getDisplayHTML(eps); \r\n });\r\n clearAll();\r\n showDisplay(); \r\n}",
"function renderAll()\n\t {\n\t \t// Sorting filters arrays.\n\t \tsortFilterArrays();\n\n\t \t// Rendering filters\n\t \trenderFilters();\n\n\t\t// Rendering publications\n\t\trenderPublications();\n\t}",
"function displayAll() {\r\n displayInput();\r\n displayOutput();\r\n}",
"function showAll(request){\n\tnamesDB.getAll(gotNames);\n\tfunction gotNames(names){\n\t\tnamesText = \"\";\n\t\tif (names.length > 0){\n\t\t\tfor (i =0; i < names.length; i++) {\n\t\t\t\t// create a link like: <a href=\"/view/1DlDQu55m85dqNQJ\">Joe</a><br/>\n\t\t\t namesText += '<a href=\"/view/' + names[i]._id + '\">' + names[i].name + \"</a><br/>\";\n\t\t\t}\n\t\t} else {\n\t\t\tnamesText = \"No people in the database yet.\";\n\t\t}\n\t\t\n\t\t//console.log(namesText);\n\t\tvar footerText = '<hr/><p><a href=\"/search\">Search</a>';\n\t\trequest.respond( namesText + footerText);\n\t}\t\n}",
"function renderAll() {\t\n\tconsole.log('renderAll start'); // optionally create log for debugging the script\n\t// create html that will be shown while the data is being loaded from firebase\n\tloadingHtml = '\\\n\t <div class=\"list-group-item active loading\">\\\n\t\tloading ...\\\n\t </div>\\\n\t';\n\t// place the loading html in the container, it will replace the list if it's already loaded\n\tcontainer.innerHTML = loadingHtml; \n\t// get todos from firebase\n\tfirebase.database().ref('todos/').once('value').then(function(snapshot) {\n\t\t// it returns a snapshot object, that contains list of objects or empty\n\t\tif(!snapshot.val() || snapshot.val().length==0){\n\t\t\t// if it's empty show the Empty message in the container, it wil replace the loading message\n\t\t\tloadingHtml = '\\\n\t\t\t <div class=\"list-group-item active\">\\\n\t\t\t\tEmpty\\\n\t\t\t </div>\\\n\t\t\t';\n\t\t\tcontainer.innerHTML = loadingHtml; \n\t\t}\n\t\telse {\n\t\t\t// otherwise loop the array\n\t\t\tfor (var key in snapshot.val()){\n\t\t\t\t// render object for each record in the array \n\t\t\t\trender(key, snapshot.val()[key], container);\n\t\t\t}\n\t\t}\n\t\tconsole.log('renderAll end');// create log\n\t});\n}",
"function updateDisplay(meals_list) {\n\n // remove the previous contents of the columns\n for(let i=0; i<columns.length; i++) {\n while (columns[i].firstChild) {\n columns[i].removeChild(columns[i].firstChild);\n }\n }\n\n //if no menus match, display \"no results to display\" message\n if (finalGroup.length === 0) {\n let para = document.createElement('h5');\n para.textContent = 'No results to display.';\n columns[0].appendChild(para);\n } else {\n for(let i = 0; i < meals_list.length; i++) {\n showMeal(meals_list[i]);\n }\n }\n }",
"async function renderList( order) {\n tableBodyEl.innerHTML = \"\";\n showProgressBar(\"show\");\n // load a list of all football association records\n const assoRecords = await FootballAssociation.retrieveAll(order),\n presidentsCollRef = db.collection(\"presidents\"),\n membersCollRef = db.collection(\"members\"),\n clubsCollRef = db.collection(\"clubs\");\n\n // for each football association, create a table row with a cell for each attribute\n for (let asso of assoRecords) {\n const presidentQrySn = presidentsCollRef.where(\"assoAssociation_id\", \"==\", parseInt(asso.assoId)),\n memberQrySn = membersCollRef.where(\"assoAssociationIdRefs\", \"array-contains\", parseInt(asso.assoId)),\n clubQrySn = clubsCollRef.where(\"association_id\", \"==\", parseInt(asso.assoId)),\n associatedPresidentDocSns = (await presidentQrySn.get()).docs,\n associatedMemberDocSns = (await memberQrySn.get()).docs,\n associatedClubDocSns = (await clubQrySn.get()).docs;\n\n let row = tableBodyEl.insertRow();\n row.insertCell().textContent = asso.assoId;\n row.insertCell().textContent = asso.name;\n\n const supAssociations = [];\n if (asso.supAssociations.length > 0) {\n for (const sa of asso.supAssociations) {\n supAssociations.push(await FootballAssociation.retrieve(String(sa)).then(value => value.name));\n }\n row.insertCell().innerHTML = '<ul><li>' + supAssociations.join(\"</li><li>\"); + '</li></ul>';\n\n } else {\n row.insertCell().textContent = \"\";\n }\n\n if (associatedPresidentDocSns.length > 0) {\n for (const ap of associatedPresidentDocSns) {\n if (ap) {\n row.insertCell().textContent = await President.retrieve(String(ap.id)).then(value => value.name)\n }\n }\n } else {\n row.insertCell().textContent = \"\";\n }\n\n const assoMembers = [];\n for (const am of associatedMemberDocSns) {\n assoMembers.push(am.id);\n }\n const assoClubs = [];\n for (const ac of associatedClubDocSns) {\n assoClubs.push(ac.id);\n }\n\n const assoMembersName = [];\n for (const m of assoMembers) {\n assoMembersName.push(await Member.retrieve(String(m)).then(value => value.name));\n }\n const assoClubsName = [];\n for (const c of assoClubs) {\n assoClubsName.push(await FootballClub.retrieve(String(c)).then(value => value.name));\n }\n\n // if (assoMembersName.length > 0) {\n // row.insertCell().innerHTML = '<ul><li>' + assoMembersName.join(\"</li><li>\"); + '</li></ul>';\n //\n // } else {\n // row.insertCell().textContent = \"\";\n // }\n row.insertCell().textContent = assoMembers.length > 0 ? assoMembers.length : \"0\";\n\n // if (assoClubsName.length > 0) {\n // row.insertCell().innerHTML = '<ul><li>' + assoClubsName.join(\"</li><li>\"); + '</li></ul>';\n //\n // } else {\n // row.insertCell().textContent = \"\";\n // }\n row.insertCell().textContent = assoClubs.length > 0 ? assoClubs.length : \"0\";\n\n\n }\n showProgressBar( \"hide\");\n}",
"function renderTable() {\n // Set the value of ending index\n var endingIndex = startingIndex + resultsPerPage;\n\n $tbody.innerHTML = \"\";\n // Set the value of ending index\n for (var i = 0; i < filteredAliens.length; i++) {\n // Get the current address object and its fields\n var alien = filteredAliens[i];\n var fields = Object.keys(alien);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the address object, create a new cell and set its inner text to be the current value at the current address's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = alien[field];\n };\n };\n}",
"function renderDatabase(out, db) {\n out.empty();\n var tables = listTables(db);\n if(tables.length > 0)\n tables.forEach(function(t) {\n var results = db.exec(\"SELECT * FROM \" + t);\n renderResults(out, results, t, true);\n });\n else\n out.append(\"Database is empty.\");\n }",
"function fullTable(noPage, groupBy, array){\t\t\t\t \n\t\t\t\t\t var startRec = Math.max(noPage - 1, 0) * groupBy; \n\t\t\t\t\t var recordsToShow = array.splice(startRec, groupBy);\n\t\t\t\t\t $('#list-source-documents tbody').empty();\n\t\t\t\t\t \n\t\t\t\t\t $.each(recordsToShow, function( index, value ) {\t\n\t\t\t\t\t\t \n\t\t\t\t\t\t var actions = $('#actions').clone();\n\t\t\t\t\t\t var url;\n\t\t\t\t\t\t \n\t\t\t\t\t\t url = actions.find(\"a:nth-child(1)\").attr('href');\n\t\t\t\t\t\t actions.find(\"a:nth-child(1)\").attr('href', url + value['key'][0]);\n\t\t\t\t\t\t \n\t\t\t\t\t\t url = actions.find(\"a:nth-child(2)\").attr('href');\n\t\t\t\t\t\t actions.find(\"a:nth-child(2)\").attr('href', url + value['type'] + \"/\" + value['key'][0]);\n\t\t\t\t\t\t \n\t\t\t\t\t\t actions.find(\"a:nth-child(3) input\").val(value['key'][0] + \"_\" + value['value']['_rev']);\t\t\t\t\t\t\n\t\t\t\t\t\t \n\t\t\t\t\t\t url = actions.find(\"a:nth-child(4)\").attr('href');\n\t\t\t\t\t\t actions.find(\"a:nth-child(4)\").attr('href', url + value['type'] + \"/\" + value['key'][0]);\n\t\t\t\t\t\t \n\t\t\t\t\t\t if(value['totalAnalitics'] != 0){\n\t\t\t\t\t\t\t actions.find(\"a:nth-child(5) span\").addClass('badge-info');\n\t\t\t\t\t\t\t actions.find(\"a:nth-child(5) span\").text(value['totalAnalitics']);\n\t\t\t\t\t\t\t actions.find(\"a:nth-child(5)\").attr('href', 'analitics/listDocumentAnalitics/' + value['key'][0]);\n\t\t\t\t\t\t }\t\t\t\t\t\t\n\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t $('#list-source-documents tbody').append( \"<tr>\" +\n\t\t\t\t\t\t \t\t\"<td>\" + value['value']['v2'] + \"</td>\" +\n\t\t\t\t\t\t \t\t\"<td>\" + value['value']['v30'] + \"</td>\" +\n\t\t\t\t\t\t \t\t\"<td>\" + value['value']['v92'] + \"</td>\" +\n\t\t\t\t\t\t \t\t\"<td>\" + value['value']['v64'] + \"</td>\" +\t\n\t\t\t\t\t\t \t\t\"<td class='actions'></td>\"\n\t\t\t\t\t\t \t);\n\t\t\t\t\t\t \n\t\t\t\t\t\t $('#list-source-documents tbody tr:last td:last').append(actions.children());\n\t\t\t\t\t });\t\t\t\t\t\n\t\t\t\t\t \n\t\t\t\t\t $(\"#list-source-documents\").delay(800).fadeIn();\n\t\t\t\t\t $('#paginator').delay(800).fadeIn();\n\t\t\t}",
"function displayTable() {\r\n displayOnly(\"#tableOfContents\");\r\n traverseAndUpdateTableHelper();\r\n prepareText(heirarchy.tree[0].sections[0].id);\r\n activePart = 0;\r\n iconEventListeners();\r\n settingsEventListeners();\r\n scrollEventListener();\r\n}",
"function sort_all_entity_tables() {\n\tsort_entity_table('c1_table');\n\tsort_entity_table('c2_table');\n\tsort_entity_table('c3_table');\n}",
"function showCatalouge() {\n\tfor (var i = 0; i <= bookCatalouge.length - 1; i++) {\n\t\tbookCatalouge[i].getTitleShow();\n\t\tbookCatalouge[i].getAuthorShow();\n\t\tbookCatalouge[i].getPageCountShow();\n\t\tconsole.log(\"-----------------------------------------------------------\");\n\t}\n}",
"function populateResultsTable_by_country() {\n\n\t\t\tvar selectedStates = $(\"#statesListbox_by_country\").val() || [];\n\t\t\tvar HSarray = selected_HS6_Codes\n\n\t\t\timportResultsTable_by_country = searchDBByAbbr(importDestinationDB, selectedStates);\n\t\t\texportResultsTable_by_country = searchDBByAbbr(exportDestinationDB, selectedStates);\n\t\t\tconsole.log('selectedStates: ')\n\t\t\tconsole.log(selectedStates)\n\t\t\tconsole.log('importResultsTable_by_country: ')\n\t\t\tconsole.log(importResultsTable_by_country)\n\t\t\tconsole.log('exportResultsTable_by_country: ')\n\t\t\tconsole.log(exportResultsTable_by_country)\n\t\t\tdrawChart_by_country()\n\t\t\tdrawWorldMap_by_country()\n\t\t}",
"function showEntities() {\n db.allDocs({include_docs: true, descending: true}, function(err, doc) {\n redrawEntitiesUI(doc.rows);\n });\n }",
"function display_All()\n{\n\t\t\ti = 0;\n\t\t\twhile (i < trueNodeids.length) {\n\t\t\t\tconsole.log(trueNodeids[i].id);\n\t\t\t\ti++;\n\t\t\t}\n}",
"function showAllInfo(data) {\n $(\".info_section\").empty();\n if (verifyTeleportDataNotEmpty(data)) {\n const firstCity = data._embedded[`city:search-results`][0];\n showTeleportCityInfo(firstCity);\n showWikipediaInfo(firstCity[`matching_full_name`]);\n } \n else {\n displayNoSearchResults();\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 }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find this extension's directory relative to the brackets root | function _extensionDirForBrowser() {
var bracketsIndex = window.location.pathname;
var bracketsDir = bracketsIndex.substr(0, bracketsIndex.lastIndexOf('/') + 1);
var extensionDir = bracketsDir + require.toUrl('./');
return extensionDir;
} | [
"function getCurrentDirectory() {\r\n\treturn File.GetAbsolutePathName(\".\");\r\n}",
"dir() {\n if (this.program.dir) {\n if (Path.isAbsolute(this.program.dir)) {\n return this.program.dir;\n }\n return Path.resolve(process.cwd(), this.program.dir);\n }\n return process.cwd();\n }",
"function getRoot(cwd, filename, smap) {\n var relativePath = path.relative(cwd, filename);\n\n var segments = relativePath.split('node_modules');\n\n var sourceRoot = smap.getProperty('sourceRoot') || '/source/' + relativePath;\n\n if (segments.length <= 1) {\n return sourceRoot;\n } else {\n return sourceRoot\n .replace(/^\\/source\\//, '/source/' + pathToPackage());\n }\n\n // it works, somehow ¯\\_(ツ)_/¯\n function pathToPackage() {\n var upToNodeModules = segments\n .slice(0, -1)\n .concat('/')\n .join('node_modules');\n\n var packageName = segments[segments.length - 1]\n .split('/', 2)[1]\n + '/';\n\n return upToNodeModules + packageName;\n }\n}",
"function findGitRoot(start) {\n\n start = start || Path.dirname(findParent(module).filename);\n var root;\n\n if (isDir(Path.join(start, '.git'))) {\n root = start;\n }\n else if (Path.dirname(start) !== start) {\n root = exports.findGitRoot(Path.dirname(start));\n }\n\n return root;\n}",
"getPluginPath(plugin) {\n if (plugin.path) {\n return plugin.path;\n }\n\n const name = plugin.package || plugin.name;\n const lookupDirs = [];\n\n // 尝试在以下目录找到匹配的插件\n // -> {APP_PATH}/node_modules\n // -> {EGG_PATH}/node_modules\n // -> $CWD/node_modules\n lookupDirs.push(path.join(this.options.baseDir, 'node_modules'));\n\n // 到 egg 中查找,优先从外往里查找\n for (let i = this.eggPaths.length - 1; i >= 0; i--) {\n const eggPath = this.eggPaths[i];\n lookupDirs.push(path.join(eggPath, 'node_modules'));\n }\n\n // should find the $cwd/node_modules when test the plugins under npm3\n lookupDirs.push(path.join(process.cwd(), 'node_modules'));\n\n for (let dir of lookupDirs) {\n dir = path.join(dir, name);\n if (fs.existsSync(dir)) {\n return fs.realpathSync(dir);\n }\n }\n\n throw new Error(`Can not find plugin ${name} in \"${lookupDirs.join(', ')}\"`);\n }",
"findNcxFilePath() {\n const tocId = this.spine.toc;\n if (tocId) {\n const ncxItem = this.manifest.findItemWithId(tocId);\n if (ncxItem) {\n return FileManager.resolveIriToEpubLocation(\n ncxItem.href,\n this.location\n );\n }\n }\n return;\n }",
"function find( filePath ){\n\tvar i,\n\t\tpathData = path.parse( filePath ),\n\t\tisAbsolute = path.isAbsolute( filePath ),\n\t\tMap = isAbsolute ?\n\t\t\t{\n\t\t\t\t'$BASE' : pathData.dir,\n\t\t\t\t'$DIR' : '',\n\t\t\t\t'$NAME' : pathData.name,\n\t\t\t\t//If no extension, then use the Current one\n\t\t\t\t'$EXT' : pathData.ext || this.Extension\n\t\t\t} :\n\t\t\t{\n\t\t\t\t'$BASE' : this.Base,\n\t\t\t\t'$INITIAL' : this.Initial,\n\t\t\t\t'$CURRENT' : path.parse(this.Location).dir,\n\t\t\t\t'$DIR' : pathData.dir,\n\t\t\t\t'$NAME' : pathData.name,\n\t\t\t\t//If no extension, then use the Current one\n\t\t\t\t'$EXT' : pathData.ext || this.Extension\n\t\t\t},\n\t\tPaths = getPaths( this.Format, Map, isAbsolute );\n\t\n\t//Traverse the Paths until a valid path is Found\n\tfor(i=0;i<Paths.length;i++){\n\t\tif( isFile( Paths[i] ) ){\n\t\t\treturn Resolution.resolve( new Finder( new FilePath( Paths[i], this.Initial, {\n\t\t\t\tBase : this.Base,\n\t\t\t\tFormat : this.Format,\n\t\t\t\tExtension : this.Extension,\n\t\t\t\tEncoding : this.Encoding\n\t\t\t})));\n\t\t}\n\t}\n\t\n\treturn Resolution.reject( new Error( '\\'' + filePath + '\\' does not resolve to a file' ) );\n}",
"_getWorkingDirectory() {\n const activeItem = atom.workspace.getActivePaneItem();\n if (activeItem\n && activeItem.buffer\n && activeItem.buffer.file\n && activeItem.buffer.file.path) {\n return atom.project.relativizePath(activeItem.buffer.file.path)[0];\n } else {\n const projectPaths = atom.project.getPaths();\n let cwd;\n if (projectPaths.length > 0) {\n cwd = projectPaths[0];\n } else {\n cwd = process.env.HOME;\n }\n return path.resolve(cwd);\n }\n }",
"static findFiles (dir) {\n return Walk.dir(dir)\n .catch({code: 'ENOENT'}, error => {\n error.message = `No such file or directory \"${error.path}\"`\n error.simple = `Failed to read templates for \"${this.base_name}\"`\n throw error\n })\n }",
"findTemplateFiles ( dir_path ) {\n if (!dir_path) dir_path = this.path\n dir_path = path.resolve(this.base_path, this.base_name, 'files')\n return Walk.dir(dir_path).then( files => {\n return this.files = this.stripPrefixFromPaths(files, dir_path)\n })\n .catch({code: 'ENOENT'}, error => {\n error.original_message = error.message\n error.message = `Failed to read template set \"${this.base_name}\"\n No such file or directory \"${error.path}\"`\n throw error\n })\n }",
"getFullPath(itemToFind = \"songPath\") {\n if (typeof this[itemToFind] !== \"string\") {\n console.warn(\"Could not find \\\"\" + itemToFind + \"\\\"\");\n return null;\n }\n if (!(Settings.current instanceof Settings)) {\n console.error(\"There is no current settings file.\");\n return null;\n }\n // let fp = Settings.current.songFolder + \"/\" + this[itemToFind];\n let fp;\n if (Settings.current.remote)\n fp = Settings.current.songFolder + \"/\" + this[itemToFind];\n else\n fp = path.resolve(Settings.current.songFolder, this[itemToFind]);\n return fp;\n }",
"function findBaseDirectory(dir, file) {\n return tslib_1.__awaiter(this, void 0, void 0, function* () {\n if (!dir || !file) {\n return;\n }\n for (const d of compilePaths(dir)) {\n const results = yield readDirSafe(d);\n if (results.includes(file)) {\n return d;\n }\n }\n });\n}",
"function getOwningPackageRelativePath(file) {\n return path.relative(owningPackageName, file.shortPath);\n }",
"function moduleDirectory(name, dir) {\n return resolve(name, {basedir: dir}).then(function (filePath) {\n return findup(path.dirname(filePath), 'package.json');\n });\n}",
"function pageDir()\n{\n //global config;\n return (config.GENERAL.PAGES_DIRECTORY);\n}",
"function findPath(app)\n {\n var child = require('child_process').execFile('/bin/sh', ['sh']);\n child.stdout.str = '';\n child.stdout.on('data', function (chunk) { this.str += chunk.toString(); });\n if (process.platform == 'linux' || process.platform == 'freebsd')\n {\n child.stdin.write(\"whereis \" + app + \" | awk '{ print $2 }'\\nexit\\n\");\n }\n else\n {\n child.stdin.write(\"whereis \" + app + \"\\nexit\\n\");\n }\n child.waitExit();\n child.stdout.str = child.stdout.str.trim();\n if (process.platform == 'freebsd' && child.stdout.str == '' && require('fs').existsSync('/usr/local/bin/' + app)) { return ('/usr/local/bin/' + app); }\n return (child.stdout.str == '' ? null : child.stdout.str);\n }",
"function discoverProjectRoot(startdir) {\n var flist = fslib.readdirSync(startdir);\n if (flist.indexOf('sc_config') > -1) {\n var c = fslib.readFileSync(pathlib.join(startdir, 'sc_config')).toString();\n if (c.indexOf(\"BT.serverConfig\") > -1) {\n return startdir;\n }\n }\n if (pathlib.parse(startdir).root === startdir) { // root\n return; // undefined\n }\n return discoverProjectRoot(pathlib.join(startdir, \"..\")); // default\n}",
"async loadAsDirectory(x) {\n assert(typeof x === 'string');\n assert(isAbsolute(x));\n\n const xp = join(x, 'package.json');\n\n if ((await stat(xp)) === 0) {\n const main = await this.readMain(xp);\n\n if (main) {\n const m = join(x, main);\n const c = await this.loadAsFile(m);\n\n if (c)\n return c;\n\n const d = await this.loadIndex(m);\n\n if (d)\n return d;\n }\n }\n\n return this.loadIndex(x);\n }",
"completionsdir() {\n debug('Asking pkg-config for completionsdir');\n return this.pkgconfig('completionsdir');\n }",
"function lookupPackage(currDir) {\n // ideally we stop once we're outside root and this can be a simple child\n // dir check. However, we have to support modules that was symlinked inside\n // our project root.\n if (currDir === '/') {\n return null;\n } else {\n var packageJson = packageByRoot[currDir];\n if (packageJson) {\n return packageJson;\n } else {\n return lookupPackage(path.dirname(currDir));\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the address of this token sorts before the address of the other token | sortsBefore(other) {
invariant(this.chainId === other.chainId, 'CHAIN_IDS');
invariant(this.address !== other.address, 'ADDRESSES');
return this.address.toLowerCase() < other.address.toLowerCase();
} | [
"static isBefore(a, b) {\n if (a.lineNumber < b.lineNumber) {\n return true;\n }\n if (b.lineNumber < a.lineNumber) {\n return false;\n }\n return a.column < b.column;\n }",
"isBefore(point, another) {\n return Point.compare(point, another) === -1;\n }",
"function _ascendingCompare(first, second) {\n return first.position - second.position;\n }",
"isPreceding(node) {\n var nodePos, thisPos;\n nodePos = this.treePosition(node);\n thisPos = this.treePosition(this);\n if (nodePos === -1 || thisPos === -1) {\n return false;\n } else {\n return nodePos < thisPos;\n }\n }",
"function compare(a,b) {\n var compareOn = a.stopName ? 'stopName' : 'routeShortName';\n if (a[compareOn] < b[compareOn]) {\n return -1;\n }\n if (a[compareOn] > b[compareOn]) {\n return 1;\n }\n return 0;\n }",
"isBefore(path, another) {\n return Path.compare(path, another) === -1;\n }",
"function isCrossed(segment1, segment2) {\n return segment1[1] >= segment2[0]\n }",
"compare(other) {\r\n const ivbCmpBegin = compare(this.start, other.start);\r\n const ivbCmpEnd = compare(this.start, other.end);\r\n const iveCmpBegin = compare(this.end, other.start);\r\n if (ivbCmpBegin < 0 && iveCmpBegin <= 0) {\r\n return -1;\r\n }\r\n if (ivbCmpEnd >= 0) {\r\n return 1;\r\n }\r\n return 0;\r\n }",
"function check_addr_order(ip_s, ip_e)\r\n{\r\n\tvar arr_ips = ip_s.split('.');\r\n\tvar arr_ipe = ip_e.split('.');\r\n\r\n\tif (arr_ips == null || arr_ipe == null || \r\n\t\tarr_ips.length != 4 || arr_ipe.length != 4) {\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\tfor (var i=0; i<4; i++) {\r\n\t\tif (arr_ips[i] > arr_ipe[i])\r\n\t\t\treturn false;\r\n\t}\r\n\t\r\n\treturn true;\r\n}",
"function compare(head1, head2){\n let curr1 = head1, curr2 = head2\n while(curr1 !== null){\n if(curr1.data !== curr2.data){\n return false\n }\n curr1 = curr1.next\n curr2 = curr2.next\n }\n return true\n}",
"isAfter(point, another) {\n return Point.compare(point, another) === 1;\n }",
"function occursBefore(name1, name2) {\n var field1 = jQuery(\"[name='\" + escapeName(name1) + \"']\");\n var field2 = jQuery(\"[name='\" + escapeName(name2) + \"']\");\n\n field1.addClass(\"prereqcheck\");\n field2.addClass(\"prereqcheck\");\n\n var fields = jQuery(\".prereqcheck\");\n\n field1.removeClass(\"prereqcheck\");\n field2.removeClass(\"prereqcheck\");\n\n if (fields.index(field1) < fields.index(field2)) {\n return true;\n }\n else {\n return false;\n }\n}",
"function compauthor(a, b) {\n return a.author > b.author;\n}",
"lt(other) {\n return this.boolOps(other, \"lt\");\n }",
"function majorComparator(student1, student2) {\n if (student1.major.toLowerCase() > student2.major.toLowerCase()) {\n return true;\n } else {\n return false;\n }\n}",
"function positCompare(posit1, posit2) {\n return unsignedIntegerFromBitstring(posit1.bitstring) - unsignedIntegerFromBitstring(posit2.bitstring);\n}",
"function isTitleNextToEachother(zeroTitlePosition, titleToSwitchPosition) {\n\t\treturn (zeroTitlePosition[1]-1 == titleToSwitchPosition[1] && zeroTitlePosition[0] == titleToSwitchPosition[0] ) ||\n\t\t\t\t\t\t(zeroTitlePosition[1]+1 == titleToSwitchPosition[1] && zeroTitlePosition[0] == titleToSwitchPosition[0] ) ||\n\t\t\t\t\t\t(zeroTitlePosition[0]-1 == titleToSwitchPosition[0] && zeroTitlePosition[1] == titleToSwitchPosition[1] ) ||\n\t\t\t\t\t\t(zeroTitlePosition[0]+1 == titleToSwitchPosition[0] && zeroTitlePosition[1] == titleToSwitchPosition[1] );\n\t}",
"static pseudo_cmp(a, b) {\n if (a['$reql_type$'] === 'BINARY') {\n if (!('data' in a && 'data' in b)) {\n console.error(\"BINARY ptype doc lacking data field\", a, b);\n throw \"BINARY ptype doc lacking data field\";\n }\n const aData = rethinkdbGlobal.binary_to_string(a['data']);\n const bData = rethinkdbGlobal.binary_to_string(b['data']);\n return aData < bData ? -1 : aData > bData ? 1 : 0;\n }\n if (a['$reql_type$'] === 'TIME') {\n if (!('epoch_time' in a && 'epoch_time' in b)) {\n console.error(\"TIME ptype doc lacking epoch_time field\", a, b);\n throw \"TIME ptype doc lacking epoch_time field\";\n }\n // These are both numbers. And if they aren't, we'll just compare them.\n const aEpoch = a['epoch_time'];\n const bEpoch = b['epoch_time'];\n return aEpoch < bEpoch ? -1 : aEpoch > bEpoch ? 1 : 0;\n }\n console.error(\"pseudo_cmp logic error\", a, b);\n throw \"pseudo_cmp encountered unhandled type\";\n }",
"positionTorculusMarkings(firstNote, secondNote, thirdNote) {\n var hasTopEpisema = this.positionClivisMarkings(secondNote, thirdNote);\n hasTopEpisema =\n this.positionEpisemata(\n firstNote,\n hasTopEpisema ? MarkingPositionHint.Above : MarkingPositionHint.Below\n ) && hasTopEpisema;\n return hasTopEpisema;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
headRequest: Build Head's request | headRequest() {
let operation = {
'api': 'HeadBucket',
'method': 'HEAD',
'uri': '/<bucket-name>',
'params': {
},
'headers': {
'Host': this.properties.zone + '.' + this.config.host,
},
'elements': {
},
'properties': this.properties,
'body': undefined
};
this.headValidate(operation);
return new Request(this.config, operation).build();
} | [
"head(route, ...middleware) {\n return this._addRoute(route, middleware, \"HEAD\");\n }",
"function fetchWithHeader() {\n fetch('https://api.github.com/users?since=135').then(function(response) {\n console.log(response.headers.get('Content-Type'));\n console.log(response.headers.get('Date'));\n\n console.log(response.status);\n console.log(response.statusText);\n console.log(response.type);\n console.log(response.url);\n });\n}",
"appendRobotHeaders()\n\t{\n\t\tconst xRobotsTag = this.currentResponse.headers[\"x-robots-tag\"];\n\n\t\t// @todo https://github.com/nodejs/node/issues/3591\n\t\tif (xRobotsTag != null)\n\t\t{\n\t\t\tthis.currentRobots.header(xRobotsTag);\n\t\t}\n\t}",
"_githubRequest(url, callback) {\n return request({url: url, headers: {'User-Agent': 'request'}, json: true}, callback);\n }",
"collectHeadTags() {\n let tags = {};\n let currentHandlerInfos = this.router.targetState.routerJsState.routeInfos;\n currentHandlerInfos.forEach((handlerInfo) => {\n Object.assign(tags, this._extractHeadTagsFromRoute(handlerInfo.route));\n });\n let tagArray = Object.keys(tags).map((id) => tags[id]);\n this.headData.set('headTags', tagArray);\n }",
"function GenericRequest() {}",
"function addHeadLink(tree, project, link) {\n const { indexPath, src } = getIndexHtmlContent(tree, project);\n if (src.indexOf(link) === -1) {\n const node = getTag(tree, src, 'head');\n const insertion = new change_1.InsertChange(indexPath, node.startOffset, link);\n const recorder = tree.beginUpdate(indexPath);\n recorder.insertLeft(insertion.pos, insertion.toAdd);\n tree.commitUpdate(recorder);\n }\n}",
"function newRequest(data){\n var request = createNewRequestContainer(data.requestId);\n createNewRequestInfo(request, data);\n }",
"function getRequest(event) {\n //code\n return request = {\n headers: event.headers,\n body: JSON.parse(event.body)\n };\n}",
"sendRequest(request) {\n let requestId = \"R\" + this.nextRequestId++;\n this.responseQueue[requestId] = request;\n\n let query = request.query;\n query.extensions = {requestId: requestId};\n this.connection.sendUTF(JSON.stringify(query));\n }",
"procesarHeaders(){\n var headers = {\n \"Accept\": \"*/*\",\n \"User-Agent\": \"Cliente Node.js\"\n };\n if(this.basicAuth != undefined){\n headers.Authorization = \"Basi c\" + this.basicAuth;\n }\n return headers;\n }",
"function buildTableHeading() {\n row = document.createElement(\"tr\");\n\n tableHeadings.forEach(function (heading) {\n console.log(heading);\n row.appendChild(createNodeAndText(\"th\", heading));\n });\n return row;\n }",
"function setCommonHeaders(req) {\n // Set (or clear) user agent\n if (userAgent) {\n req.set('User-Agent', userAgent);\n } else {\n req.unset('User-Agent');\n }\n // Prevent caching so response time will be accurate\n req\n .set('Cache-Control', 'no-cache')\n .set('Pragma', 'no-cache');\n }",
"function request(opts) { http.request(opts, function(res) { res.pipe(process.stdout) }).end(opts.body || '') }",
"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}",
"getPrologRequest(requestString, onSuccess, onError, port) {\r\n var requestPort = port || 8081\r\n var request = new XMLHttpRequest();\r\n request.open('GET', 'http://localhost:' + requestPort + '/' + requestString, true);\r\n\r\n request.onload = onSuccess || function (data) { console.log(\"Request successful. Reply: \" + data.target.response); };\r\n request.onerror = onError || function () { console.log(\"Error waiting for response\"); };\r\n\r\n request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');\r\n request.send();\r\n }",
"function graphQLFetcher() {\n\tlet mergedHeaders;\n\tif (\n\t\ttypeof parameters.headers === 'undefined' ||\n\t\tparameters.headers === null ||\n\t\tparameters.headers.trim() === ''\n\t) {\n\t\tmergedHeaders = defaultHeaders;\n\t} else {\n\t\tmergedHeaders = {\n\t\t\t...defaultHeaders,\n\t\t\t...JSON.parse(parameters.headers),\n\t\t};\n\t}\n\treturn GraphiQL.createFetcher({\n\t\turl: getUrl(),\n\t\tsubscriptionUrl: getWsUrl(),\n\t\theaders: mergedHeaders,\n\t});\n}",
"function headTagToString(head: Object): Function {\n /**\n * Calls `toString` on a given head tag\n */\n return function tagNameToString(tagName: string): string {\n return head[tagName].toString();\n };\n}",
"function isHeaderPassed(){\n if(requestType==\"GET\")\n keyVal = process.argv[process.argv.length - 2];\n if(requestType==\"POST\")\n keyVal = process.argv[process.argv.length - 4];\n\n storage = keyVal.split(':');\n key = storage[0], value= storage[1];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get all the resources | function getResources() {
return $q.when(resources);
} | [
"getResources(includeTs) {\n const resources = this.data.manifest.control.resources;\n let pathsCollection = [];\n Object.keys(resources).forEach(resourceType => {\n let paths;\n if (resourceType !== constants.LIBRARY_ELEM_NAME) {\n paths = (resourceType === constants.CODE_ELEM_NAME && !includeTs) ? [] : resources[resourceType].map((resource) => resource.$.path);\n }\n else {\n paths = flatMap(resources[resourceType], (resource) => resource['packaged_library'] ? resource['packaged_library'].map((packagedLib) => packagedLib.$.path) : []);\n }\n pathsCollection.push(...paths);\n });\n return pathsCollection;\n }",
"function getAllAssets() {\n return new Promise((resolve, reject) => {\n if (!process.env.API_URL_LIST) {\n console.log(process.env.API_URL_LIST);\n reject('No URL found to get all Assets.');\n }\n\n request(process.env.API_URL_LIST, (error, response, body) => {\n if (!error && response.statusCode === 200) {\n const json = JSON.parse(body);\n resolve(json);\n } else {\n reject(error);\n }\n });\n });\n}",
"getResources (itemId, portalOpts) {\n const args = this.addOptions({}, portalOpts);\n return getItemResources(itemId, args)\n .catch(handleError);\n }",
"allResources(type, props) {\n const matchError = (0, resources_1.allResources)(this.template, type, props);\n if (matchError) {\n throw new Error(matchError);\n }\n }",
"allObjects() {\n return fs.readdirSync(Files.gitletPath('objects')).map(Objects.read);\n }",
"function getAllImages() {\n return Images().select();\n}",
"get_all_routes_action(req, res, next) {\n res.send(this.get('RouteRegistry').getAll().map(this._publishRoute));\n }",
"findResources(type, props = {}) {\n return (0, resources_1.findResources)(this.template, type, props);\n }",
"getAll(req, res, next) {\n\n var\n request = new Request(req),\n response = new Response(request, this.expandsURLMap),\n criteria = this._buildCriteria(request);\n\n this.Model.paginate(criteria, request.options, function(err, paginatedResults, pageCount, itemCount) {\n /* istanbul ignore next */\n if (err) { return next(err); }\n\n response\n .setPaginationParams(pageCount, itemCount)\n .formatOutput(paginatedResults, function(err, output) {\n /* istanbul ignore next */\n if (err) { return next(err); }\n\n res.json(output);\n });\n\n });\n }",
"async getAllMateri(_, res){\n const materis = await prisma.materi.findMany({\n include: {\n File: true\n }\n });\n res.json({materis});\n }",
"function get(selector) {\n assert(isNotEmptyString(selector));\n if (resources[selector])\n return [resources[selector]];\n if (cache[selector]) {\n var hrefs = cache[selector];\n var results = [];\n for (var _i = 0; _i < hrefs.length; _i++) {\n var href = hrefs[_i];\n results.push(resources[href]);\n }\n return results;\n }\n return [];\n }",
"static listAllOfMyNews() {\n\t\treturn RestService.get('api/news');\n\t}",
"getAllEntities() {\n let queryParameters = {};\n let headerParams = this.defaultHeaders;\n let isFile = false;\n let formParams = {};\n return this.execute('GET', '/api/user/v1/role/get-all', queryParameters, headerParams, formParams, isFile, false, undefined);\n }",
"async getAll(req, res) {\n try {\n let data = await Pemasok.findAll();\n\n if (!data) {\n return res.status(404).json({\n message: \"Pemasok Not Found\",\n });\n }\n\n return res.status(200).json({\n message: \"Success\",\n data,\n });\n } catch (e) {\n return res.status(500).json({\n message: \"Internal Server Error\",\n error: e,\n });\n }\n }",
"getRoutes() {\n let routes = [];\n this.getGroups().forEach(group => {\n routes = routes.concat(group.routes);\n });\n if (this.fallback) {\n routes = routes.concat(this.fallback.routes);\n }\n return routes;\n }",
"function getAllStreamers() {\r\n clearElements();\r\n getStreamData(\"all\");\r\n }",
"async loadImages() {\n const resources = Array.from(this._resources.entries());\n\n console.info(`[ImageManager] Loading ${resources.length} image assets.`);\n\n await Promise.all(resources.map(([iKey, iValue]) => {\n console.info(`[ImageManager] Loading image ${iValue}.`);\n\n const img = new Image();\n img.src = iValue;\n\n return new Promise((resolve) => img.addEventListener('load', () => {\n this._images.set(iKey, img);\n resolve();\n }))\n }));\n\n this._loaded = true;\n\n console.info('[ImageManager] Images loaded.');\n }",
"function getAllprojects(){\n\n}",
"list(_, res) {\n return pacientes\n .findAll({\n })\n .then(pacientes => res.status(200).send(pacientes))\n .catch(error => res.status(400).send(error))\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find all groups and include all associated groupEvents from the GroupEvent model | list(req, res) {
return Group
.findAll({
include: [{
model: GroupEvent,
as: 'groupEvents',
}],
})
.then(groups => res.status(200).send(groups))
.catch(error => res.status(400).send(error));
} | [
"findEvents (groupId, query) {\n assert.equal(typeof groupId, 'number', 'groupId must be number')\n assert.equal(typeof query, 'object', 'query must be object')\n return this._apiRequest(`/group/${groupId}/events`, 'GET',\n PieceMakerApi._convertData(query), PieceMakerApi._fixEventsResponse)\n }",
"getAllEvents() {\r\n return Event.all;\r\n }",
"selectModelsByGroup(groupName) {\n return this.filterAllByProperty('groupName', groupName)\n }",
"function entityGroups() {\n // Define the data object and include needed parameters.\n // Make the groups API call and assign a callback function.\n}",
"listAllGroups () {\n return this._apiRequest('/groups/all')\n }",
"listEventsOfType (groupId, type) {\n assert.equal(typeof groupId, 'number', 'groupId must be number')\n assert.equal(typeof type, 'string', 'type must be string')\n // TODO: bad api design, type should be part of path instead of query params\n return this._apiRequest(`/group/${groupId}/events`, 'GET', { type }, PieceMakerApi._fixEventsResponse)\n }",
"visitGroup_by_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"getCalendarGroups() {\n return Object.keys(this.groupCalendars).map(id => ({ id }));\n }",
"function getAllEvents() {\n if (dbPromise) {\n dbPromise.then(function (db) {\n var transaction = db.transaction('EVENT_OS', \"readonly\");\n var store = transaction.objectStore('EVENT_OS');\n var request = store.getAll();\n return request;\n }).then(function (request) {\n displayOnMap(request);\n });\n }\n}",
"function collectGroups(groups) {\n let name = \"\"\n let tags = new Set()\n for (let group of groups) {\n name += `[${group.name}]+`\n collect(tags, group.tags)\n }\n\n name = name.substring(0, name.length - 1)\n \n return new Group(name, tags)\n}",
"function build_groups_array(data) {\n var results = new Array();\n \n // Map from CRID to group index.\n var crids_map = {};\n \n var group_title = \"\";\n var group_synopsis = \"\";\n for (var i = 0, len = data.events.length; i < len; i++) {\n var event = data.events[i];\n\n // Check CRID first.\n var crid_index = crids_map[event.event_crid];\n if (crid_index != undefined) {\n\n // Add new member to existing group.\n var members = results[crid_index];\n members.push(i);\n\n } else {\n \n // Is next event in current group, or start a new one?\n if (results.length > 0 && event.title == group_title && event.synopsis == group_synopsis) {\n // Add new member to the latest existing group.\n var members = results[results.length - 1];\n members.push(i);\n } else {\n // Create new members array with this event, and push a new group.\n var new_members = [i];\n results.push(new_members);\n group_title = event.title;\n group_synopsis = event.synopsis;\n \n // Remember the index of this group in the CRID map.\n if (event.event_crid.length > 0) {\n crids_map[event.event_crid] = results.length - 1;\n }\n }\n\n }\n }\n return results;\n }",
"allEventABIs() {\n const allEventABIs = [];\n const { contracts, libraries, related, } = this.repoData;\n if (contracts) {\n mergeDefs(contracts);\n }\n if (libraries) {\n mergeDefs(libraries);\n }\n if (related) {\n mergeDefs(related);\n }\n return allEventABIs;\n // inner utility function for allEventABIs\n function mergeDefs(abiDefs) {\n for (const key of Object.keys(abiDefs)) {\n const defs = abiDefs[key].abi;\n for (const def of defs) {\n if (def.type === \"event\") {\n allEventABIs.push(def);\n }\n }\n }\n }\n }",
"function getEvents(){\nreturn events;\n}",
"visitGroup_by_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function collectAllEvents() {\n // A set for all calendar events displayed on the UI.\n // Each element in this set is a Json string. \n allEventJson = new Set(); \n \n const eventList = document.getElementById('new-event-list');\n \n // Looks at each event card and scrapes the event's name and \n // start and end times from the HTML elements. \n // Add all event information to a set of all Json strings. \n eventList.childNodes.forEach((eventCard) => {\n const eventName = eventCard.childNodes[0].childNodes[0].innerText; \n const startTime = eventCard.childNodes[0].childNodes[1].innerText; \n const endTime = eventCard.childNodes[0].childNodes[2].innerText; \n const event = new CalendarEvent(eventName, startTime, endTime);\n const eventJson = JSON.stringify(event); \n allEventJson.add(eventJson); \n }); \n}",
"findEventsByDate(findDate) {\r\n searchDate = new Date(findDate);\r\n\r\n let results = []\r\n\r\n // Assuming same timezone for now\r\n for (let event of Event.all) {\r\n if (\r\n event.date.getMonth() == searchDate.getMonth()\r\n && event.date.getDay() == searchDate.getDay()\r\n && event.date.getYear() == searchDate.getYear()\r\n ) {\r\n results.add(event);\r\n }\r\n }\r\n console.log(results);\r\n return results;\r\n }",
"groupFields (groupsArray, field, i, fieldsArray) {\n if (field.props.group === 'start') {\n this.openGroup = true\n groupsArray.push([])\n }\n\n if (this.openGroup) {\n groupsArray[groupsArray.length - 1].push(field)\n } else {\n groupsArray.push([field])\n }\n\n if (field.props.group === 'end') {\n this.openGroup = false\n }\n return groupsArray\n }",
"get groupsObject () {\n const result = {}\n for (const [key, val] of this.groups) {\n result[key] = Array.from(val)\n }\n return result\n }",
"visitLog_grp(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stores git collection ID in parent component DuplicateApp | callbackGit(data) {
this.state.extSetState({ gitCollectionId: data.smart_collection.id });
} | [
"function makeApp() {\n window.addEventListener('load', (event) => {\n db.collection(\"apps\").add({})\n .then(function (doc) {\n docAppID = doc.id;\n console.log(\"app id!\" + docAppID);\n })\n });\n }",
"onComponentOutput(componentClass, collectionId) {\n\t\tif(componentClass == 'CollectionSelector') {\n\t\t\tlet cs = this.state.collections;\n\t\t\tif(cs.indexOf(collectionId) == -1) {\n\t\t\t\tcs.push(collectionId);\n\t\t\t\tthis.setState({\n\t\t\t\t\tcollections : cs,\n\t\t\t\t\tactiveCollection : collectionId\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}",
"function getNewCollectionIndex() {\n var d = new Date().getTime();\n var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = (d + Math.random()*16)%16 | 0;\n d = Math.floor(d/16);\n return (c=='x' ? r : (r&0x3|0x8)).toString(16);\n });\n return uuid;\n}",
"preSaveSetId() {\n if (isNone(this.get('id'))) {\n this.set('id', generateUniqueId());\n }\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 }",
"addExternalComponent(appId, externalComponent) {\n externalComponent.appId = appId;\n if (!this.appTouchedExternalComponents.get(appId)) {\n this.appTouchedExternalComponents.set(appId, new Map(Object.entries({ [externalComponent.name]: externalComponent })));\n }\n else {\n const appExternalComponents = this.appTouchedExternalComponents.get(appId);\n appExternalComponents.set(externalComponent.name, externalComponent);\n }\n }",
"createEditCollection(options) {\n if (options.collectionSchemaPath === 'todos') {\n return <EditCollection\n controller={options.controller}\n schemaPath={options.collectionSchemaPath}\n parentIds={options.parentIds}\n rootComponent={options.rootComponent}\n history={options.routeArgs.history}\n />;\n }\n return super.createEditCollection(options);\n }",
"importDesign(design){\n\n if(Meteor.isServer) {\n let designId = Designs.insert(\n {\n designName: design.designName,\n designRawText: design.designRawText,\n isRemovable: design.isRemovable,\n designStatus: design.designStatus\n }\n );\n\n return designId;\n }\n }",
"init(){\n\t\tif( this.packagename ){\n\t\t\tthis.componentname = this.packagename.replace(/[\\/\\.]/g,'_'); // id should not have dot\n\t\t}else{\n\t\t\tthis.componentname = this.constructor.name;\n\t\t}\n\t\tthis.componentId = this.componentname + '_' + this.component_serial;\n\t\tComponentStack.set(this.componentId,this);\n\t\t\n\t\tthis.view.id = this.componentId;\n\t}",
"createNewCollection(){\n // return this.db.createCollection(name)\n }",
"add(state, { layer, corpuUid }) {\n const index = state.lists[corpuUid].length\n Vue.set(state.lists[corpuUid], index, layer)\n }",
"handlePackagingChange(event, data) {\n let packagingId;\n let packagingName = data.value;\n let packagingList = this.state.packaging.packagingList;\n\n for (let i = 0; i < packagingList.length; i++) {\n let currPackaging = packagingList[i];\n if (currPackaging.value == packagingName) {\n packagingId = currPackaging.key;\n break;\n }\n }\n\n let newPackaging = this.state.packaging;\n newPackaging.itemPackaging = { id: packagingId, name: packagingName };\n\n this.setState({\n packaging: newPackaging\n });\n }",
"callbackOrig(data) {\n this.state.extSetState({ origCollectionId: data.smart_collection.id });\n }",
"putV3SnippetsId(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.SnippetsApi()\n/*let id = 56;*/ // Number | The ID of a snippe\n/*let opts = {\n 'UNKNOWN_BASE_TYPE': new Gitlab.UNKNOWN_BASE_TYPE() // UNKNOWN_BASE_TYPE | \n};*/\napiInstance.putV3SnippetsId(incomingOptions.id, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"addToCollectionParentIndex(t, e) {\n if (!this.zt.has(e)) {\n const n = e.lastSegment(),\n s = e.popLast();\n t.addOnCommittedListener(() => {\n // Add the collection to the in memory cache only if the transaction was\n // successfully committed.\n this.zt.add(e);\n });\n const i = {\n collectionId: n,\n parent: Es(s)\n };\n return Ti(t).put(i);\n }\n\n return Ks.resolve();\n }",
"itemCollectionDbRef(uid, archiveId) {\n return firebase\n .firestore()\n .collection(\"archives\")\n .doc(uid)\n .collection(\"userarchives\")\n .doc(archiveId)\n .collection(\"items\");\n }",
"function generateMongoObjectId() {\n var timestamp = (new Date().getTime() / 1000 | 0).toString(16);\n return timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function() {\n return (Math.random() * 16 | 0).toString(16);\n }).toLowerCase();\n }",
"function getTableIdFromChild(component) {\n return jQuery(component).closest('.uif-tableCollectionSection').attr('id');\n}",
"getChangeId() {\n return this.json_.id;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pinPosterMult(locationArray) takes the array and fires off a Google place search for each location. | function pinPosterMult(locationArray) {
// creates a Google place search service object. PlacesService does the work of
// actually searching for location data.
var service = new google.maps.places.PlacesService(map);
// Iterates through the array of locations, creates a search object for each location
locationArray.forEach(function(place){
// the search request object
var request = {
query: place
};
// Actually searches the Google Maps API for location data and runs the callback
// function with the search results after each search.
service.textSearch(request, callback);
});
} | [
"function pinPoster(locations) {\n\n // creates a Google place search service object\n var service = new google.maps.places.PlacesService(map);\n\n // Iterates through the array of locations, creates a search object for each location\n locations.forEach(function(place){\n // the search request object\n var request = {\n query: place\n };\n\n // Actually searches the Google Maps API for location data and runs the callback\n // function with the search results after each search.\n service.textSearch(request, callback);\n });\n }",
"function setPostal(markerArray) {\n \n markerArray.forEach(function(marker) {\n \n let lat = marker.getPosition().lat();\n \n let lng = marker.getPosition().lng();\n \n \n let url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=';\n url += lat;\n url += ',';\n url += lng;\n url += '&key=AIzaSyA0dTID9kEIw0w2LDUE444_M0Go7YM4apA&result_type=postal_code';\n\n $.ajax({\n url : url,\n dataType: 'json',\n success : function(data){\n marker.postal = data.results[0].address_components[0].short_name;\n \n },\n error: function(request, error) {\n window.alert(\"Request: \" + JSON.stringify(request));\n }\n });\n });\n}",
"function addMarker(location,array) {\r\n var marker = new google.maps.Marker({\r\n position: location,\r\n map: map\r\n });\r\n array.push(marker);\r\n }",
"updateItineraryAndMapByArray(places){\n let newMarkerPositions = [];\n this.setState({placesForItinerary: places});\n places.map((place) => newMarkerPositions.push(L.latLng(parseFloat(place.latitude), parseFloat(place.longitude))));\n this.setState({markerPositions: newMarkerPositions});\n this.setState({reverseGeocodedMarkerPositions: []});\n }",
"function setMarkers(location) {\n\n for (i = 0; i < location.length; i++) {\n location[i].holdMarker = new google.maps.Marker({\n position: new google.maps.LatLng(location[i].lat, location[i].lng),\n map: map,\n title: location[i].title,\n icon: {\n url: 'img/marker.png',\n size: new google.maps.Size(25, 40),\n origin: new google.maps.Point(0, 0),\n anchor: new google.maps.Point(12.5, 40)\n },\n shape: {\n coords: [1, 25, -40, -25, 1],\n type: 'poly'\n }\n });\n\n //function to place google street view images within info windows\n //determineImage();\n getFlickrImages(location[i]);\n //Binds infoWindow content to each marker\n //Commented for testing\n // location.contentString = '<img src=\"' + streetViewImage +\n // '\" alt=\"Street View Image of ' + location.title + '\"><br><hr style=\"margin-bottom: 5px\"><strong>' +\n // location.title + '</strong><br><p>' +\n // location.cityAddress + '<br></p><a class=\"web-links\" href=\"http://' + location.url +\n // '\" target=\"_blank\">' + location.url + '</a>';\n\n //Testing flickr out (not yet)\n\n\n var infowindow = new google.maps.InfoWindow({\n content: arrayMarkers[i].contentString\n });\n\n //Click marker to view infoWindow\n //zoom in and center location on click\n new google.maps.event.addListener(location[i].holdMarker, 'click', (function(marker, i) {\n return function() {\n numb = i;\n infowindow.setContent(location[i].contentString);\n infowindow.open(map, this);\n var windowWidth = $(window).width();\n if (windowWidth <= 1080) {\n map.setZoom(14);\n } else if (windowWidth > 1080) {\n map.setZoom(16);\n }\n map.setCenter(marker.getPosition());\n location[i].picBoolTest = true;\n };\n })(location[i].holdMarker, i));\n\n //Click nav element to view infoWindow\n //zoom in and center location on click\n var searchNav = $('#nav' + i);\n searchNav.click((function(marker, i) {\n return function() {\n infowindow.setContent(location[i].contentString);\n infowindow.open(map, marker);\n map.setZoom(16);\n map.setCenter(marker.getPosition());\n location[i].picBoolTest = true;\n };\n })(location[i].holdMarker, i));\n }\n}",
"async function sortPosts(posts_array, keyword, userLat, userLong) {\r\n let post_object_list_with_weights = [];\r\n\r\n\r\n for (let post_id of posts_array) {\r\n \r\n let post_with_weight = await getPost(post_id, keyword, userLat, userLong);\r\n post_object_list_with_weights.push(post_with_weight);\r\n\r\n }\r\n\r\n let sorted_posts = arraySort(post_object_list_with_weights, 'weight'); // Sort weight ascending order\r\n return sorted_posts;\r\n}",
"function initMap(array) {\r\n //new map with options\r\nmap = new google.maps.Map(document.getElementById(\"map\"), {\r\n center: { lat: 40.683347, lng: -73.953903 },\r\n zoom: 12,\r\n});\r\n\r\nfor(let i = 0; i < array.length; i++){\r\n addMarker(array[i])\r\n }\r\n}",
"function getAllLocationsCallback(response){\n\t\n}",
"async function writeToLocationsTable(locations){\n\n for (let i=0, len=locations.length; i<len; i++){\n await models.location.upsert({\n locationid:locations[i].locationId,\n locationname: locations[i].name,\n addressline1: locations[i].postalAddressLine1,\n addressline2: locations[i].postalAddressLine2,\n towncity: locations[i].postalAddressTownCity,\n county: locations[i].postalAddressCounty,\n postalcode: locations[i].postalCode,\n mainservice: (locations[i].gacServiceTypes.length>0) ? locations[i].gacServiceTypes[0].name : null\n })\n }\n }",
"function createRequestUrls(location) {\n\tvar request_urls = {};\n\tvar request_creator = require('./utils/requestCreator.js');\n\tvar base_url = \"https://maps.googleapis.com/maps/api/place/nearbysearch/json\";\n\tfor (var place_type in other_place_config) {\n\t\tif (other_place_config.hasOwnProperty(place_type)) {\n\t\t\tvar url_params = {\n\t\t\t\t\"location\": location,\n\t\t\t\t\"radius\": other_place_config[place_type],\n\t\t\t\t\"type\": place_type,\n\t\t\t\t\"key\": \"AIzaSyCOplY8KvzVh5BMcYRosmuSsbKoi3olP0k\"\n\t\t\t};\n\t\t\trequest_urls[place_type] = request_creator.create(base_url, url_params);\n\t\t\tconsole.log(request_urls[place_type]);\n\t\t}\n\t}\n\n\treturn request_urls;\n}",
"async function populateAllLocations(url){\n let response;\n let nextPage='/locations?page=22&perPage=1000';\n \n do{\n let locationIds = [];\n console.log(\"Fetching remote data: \", url+nextPage)\n response = await axios.get(url+nextPage);\n nextPage = response.data.nextPageUri;\n \n for (let i=0, len=response.data.locations.length; i<len; i++){\n locationIds.push(response.data.locations[i].locationId)\n }\n \n let locations = await getIndividualLocations(locationIds);\n \n for (let i=0, len=locations.length; i<len; i++){\n await models.location.create({\n locationid:locations[i].locationId,\n locationname: locations[i].name,\n addressline1: locations[i].postalAddressLine1,\n addressline2: locations[i].postalAddressLine2,\n towncity: locations[i].postalAddressTownCity,\n county: locations[i].postalAddressCounty,\n postalcode: locations[i].postalCode,\n mainservice: (locations[i].gacServiceTypes.length>0) ? locations[i].gacServiceTypes[0].name : null\n })\n }\n } while (nextPage != null);\n }",
"renderVeteranMarkers() {\n const locations = new Set();\n let currentVets = this.state.currentVets;\n if (this.state.currentVets.length + this.state.currentPos.length > 10) {\n currentVets = this.state.currentVets.slice(\n 0,\n 10 - this.state.currentPos.length\n );\n }\n return currentVets.map(veteran => {\n const coordinate = {\n latitude: parseFloat(veteran.lat),\n longitude: parseFloat(veteran.lng),\n };\n //Change coordinate if two pins are in the same location\n if (locations.has(coordinate)) {\n coordinate[\"latitude\"] =\n coordinate[\"latitude\"] + this.state.region.latitudeDelta / 20;\n }\n locations.add(coordinate);\n return (\n <MapView.Marker\n coordinate={coordinate}\n onPress={this.onMarkerPress(veteran, \"veteran\")}\n key={`veteran-${veteran.id}`}\n >\n <ConnectPin pinType=\"veteran\" />\n </MapView.Marker>\n );\n });\n }",
"async seed(parent, {count, minLat, maxLat, minLng, maxLng}, ctx, info) {\n return await Promise.all(\n [...Array(count).keys()].map(async coordinates => {\n await ctx.db.mutation.createLocation(\n {\n data: {\n lat: chance.latitude({min: minLat, max: maxLat}),\n lng: chance.longitude({min: minLng, max: maxLng})\n },\n },\n info\n )\n })\n );\n }",
"function parseLocationData(locationdata, callback) {\r\n\r\n // shared location data is contained in the first element\r\n let perlocarr = locationdata[0];\r\n let userdataobjarr = [];\r\n\r\n if(perlocarr && perlocarr.length > 0) {\r\n\r\n for(let i=0; i<perlocarr.length;i++) {\r\n extractUserLocationData(perlocarr[i], function(err, obj) {\r\n if(err) {\r\n if(callback) callback(err);\r\n return\r\n } else {\r\n userdataobjarr[i] = obj;\r\n }\r\n });\r\n }\r\n\r\n }\r\n\r\n if(callback) callback(false, userdataobjarr);\r\n}",
"function updateHotelsMap(stadiumIndex) {\n hotelMap.panTo(stadiums[stadiumIndex].location);\n // If zoom is too far you get no results...\n hotelMap.setZoom(14);\n \n // Search for hotels in the selected city, within the viewport of the map.\n var search = {\n bounds: hotelMap.getBounds(),\n types: ['lodging']\n };\n\n hotels.nearbySearch(search, function(results, status) {\n\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n clearHotelMarkers();\n\n for (var i = 0; i < results.length; i++) {\n\n // Create a marker for each hotel found, and assign a letter for the icon label\n var labels = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n \n hotelMarkers[i] = new google.maps.Marker({\n draggable: false,\n position: results[i].geometry.location,\n animation: google.maps.Animation.DROP,\n icon: 'https://developers.google.com/maps/documentation/javascript/images/marker_green'+labels[i]+'.png',\n });\n \n // If the user clicks a hotel marker, show the details of that hotel in an info window.\n hotelMarkers[i].placeResult = results[i];\n google.maps.event.addListener(hotelMarkers[i], 'click', showInfoWindow);\n setTimeout(dropHotelMarker(i), i * 100);\n }\n\n // Keep the stadium on the hotel results map so its easier to see where you are looking\n var stadium = new google.maps.Marker({\n map: hotelMap,\n draggable: false,\n animation: google.maps.Animation.DROP,\n position: stadiums[stadiumIndex].location,\n title: stadiums[stadiumIndex].name,\n icon: 'assets/images/rugby_ball.png'\n });\n stadium.setMap(hotelMap);\n }\n });\n}",
"function extractFastners() {\n self.meetupList().forEach(function(meetup){\n // Need a venue id to pull location\n if (meetup.hasVenue()) {\n var pin;\n var id = meetup.venueObject.id;\n if (hasFastnerId(id)) {\n // push the meetup object onto the pin's meetups\n pin = getFastnerById(id);\n pin.meetups.push(meetup);\n } else {\n // instantiate a new pin object\n pin = new Fastner(meetup.venueObject, map);\n\n // check if has valid location\n if (pin.location()) {\n // push it to the pin list\n self.pinList.push(pin);\n\n // and push the meetup object onto that new pin object\n pin.meetups.push(meetup);\n\n // add a marker callback\n google.maps.event.addListener(pin.marker, 'click', function () {\n self.selectFastner(pin);\n });\n }\n }\n }\n });\n }",
"function createMarkers(result) {\n // console.log(result); \n for (var i=0; i < result.length; i++) {\n\n var latLng = new google.maps.LatLng (result[i].lot_latitude, result[i].lot_longitude); \n\n var marker = new google.maps.Marker({\n position: myLatlng,\n title: result [i].lot_name,\n customInfo: {\n name: result[i].lot_name,\n address: result[i].lot_address,\n available: result[i].spot_id\n };\n });\n\n// To add the marker to the map, call setMap();\nmarker.setMap(map);\n\ncreateMarkers(result);\n };\n }",
"function addMarker(rest_add,count){\n var address = rest_add;\n geocoder.geocode( { 'address': address}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n var marker = new google.maps.Marker({\n map: map,\n position: results[0].geometry.location,\n icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+ (count+1) +'|e74c3c|000000'\n });\n markers.push(marker);\n } else {\n alert('Geocode was not successful for the following reason: ' + status);\n }\n });\n\n}",
"function 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 }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detects intersection between mouse cursor (vector from center to mouse position) and menu item. If detects, activates this item. | intersection () {
var tan = this.vector.y / this.vector.x,
_this = this,
from, to,
cursorDegree = -Math.atan2(-this.vector.y, -this.vector.x) * 180/Math.PI + 180;
for (var i= 0, max = this.cache.length; i < max; i++) {
var item = _this.cache[i];
from = item.range[0];
to = item.range[1];
// If one of item's sides area is on the edge state. For example
// when we have item which 'from' begins from 157 and ends to -157, when all
// 'cursorDegree' values are appear hear. To not let this happen, we compare
// 'from' and 'to' and reverse comparing operations.
if (from > to) {
if (cursorDegree <= from && cursorDegree <= to || cursorDegree >= from && cursorDegree >= to) {
_this.activate(item);
}
} else {
if (cursorDegree >= from && cursorDegree <= to) {
_this.activate(item);
}
}
}
this.cache.forEach(function (item) {
})
} | [
"function theClickedItem(item) {\n setHighlightItem(item);\n }",
"function onSelectStart(event){\n\n if (event instanceof MouseEvent && !renderer.xr.isPresenting()){\n\t// Handle mouse click outside of VR.\n\t// Determine screen coordinates of click.\n\tvar mouse = new THREE.Vector2();\n\tmouse.x = (event.clientX / window.innerWidth) * 2 - 1;\n\tmouse.y = - (event.clientY / window.innerHeight) * 2 + 1;\n\t// Create raycaster from the camera through the click into the scene.\n\tvar raycaster = new THREE.Raycaster();\n\traycaster.setFromCamera(mouse, camera);\n\n\t// Register the click into the GUI.\n\tGUIVR.intersectObjects(raycaster);\n }\n\n}",
"function bindMenuItemEvent(item) {\n\t\t\titem.hover(function () {\n\t\t\t\t// hide other menu\n\t\t\t\titem.siblings().each(function () {\n\t\t\t\t\tif (this.submenu) {\n\t\t\t\t\t\thideMenu(this.submenu);\n\t\t\t\t\t}\n\t\t\t\t\t$(this).removeClass('menu-active');\n\t\t\t\t});\n\n\t\t\t\t// show this menu\n\t\t\t\titem.addClass('menu-active');\n\t\t\t\tvar submenu = item[0].submenu;\n\t\t\t\tif (submenu) {\n\t\t\t\t\tvar left = item.offset().left + item.outerWidth() - 2;\n\t\t\t\t\tif (left + submenu.outerWidth() > $(window).width()) {\n\t\t\t\t\t\tleft = item.offset().left - submenu.outerWidth() + 2;\n\t\t\t\t\t}\n\t\t\t\t\tshowMenu(submenu, {\n\t\t\t\t\t\tleft: left,\n\t\t\t\t\t\ttop: item.offset().top - 3\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}, function (e) {\n\t\t\t\titem.removeClass('menu-active');\n\t\t\t\tvar submenu = item[0].submenu;\n\t\t\t\tif (submenu) {\n\t\t\t\t\tif (e.pageX >= parseInt(submenu.css('left'))) {\n\t\t\t\t\t\titem.addClass('menu-active');\n\t\t\t\t\t} else {\n\t\t\t\t\t\thideMenu(submenu);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\titem.removeClass('menu-active');\n\t\t\t\t}\n\t\t\t});\n\t\t}",
"function shouldChangeActiveMenuItem () {\n // prettier-ignore\n return (\n !activeMenuItem ||\n calculateGradient(previousMouseCoordinates, activeSubMenuTopLeftCoordinates) <\n calculateGradient(currentMouseCoordinates, activeSubMenuTopLeftCoordinates) ||\n calculateGradient(previousMouseCoordinates, activeSubMenuBottomLeftCoordinates) >\n calculateGradient(currentMouseCoordinates, activeSubMenuBottomLeftCoordinates)\n )\n }",
"function bindMenuItemEvent(item){ \n\t\t\titem.hover( \n\t\t\t\tfunction(){ \n\t\t\t\t\t// hide other menu \n\t\t\t\t\titem.siblings().each(function(){ \n\t\t\t\t\t\tif (this.submenu){ \n\t\t\t\t\t\t\thideMenu(this.submenu); \n\t\t\t\t\t\t} \n\t\t\t\t\t\t$(this).removeClass('menu-active'); \n\t\t\t\t\t}); \n\t\t\t\t\t \n\t\t\t\t\t// show this menu \n\t\t\t\t\titem.addClass('menu-active'); \n\t\t\t\t\tvar submenu = item[0].submenu; \n\t\t\t\t\tif (submenu){ \n\t\t\t\t\t\tvar left = item.offset().left + item.outerWidth() - 2; \n\t\t\t\t\t\tif (left + submenu.outerWidth() > $(window).width()){ \n\t\t\t\t\t\t\tleft = item.offset().left - submenu.outerWidth() + 2; \n\t\t\t\t\t\t} \n\t\t\t\t\t\tshowMenu(submenu, { \n\t\t\t\t\t\t\tleft: left, \n\t\t\t\t\t\t\ttop:item.offset().top - 3 \n\t\t\t\t\t\t}); \n\t\t\t\t\t} \n\t\t\t\t}, \n\t\t\t\tfunction(e){ \n\t\t\t\t\titem.removeClass('menu-active'); \n\t\t\t\t\tvar submenu = item[0].submenu; \n\t\t\t\t\tif (submenu){ \n\t\t\t\t\t\tif (e.pageX>=parseInt(submenu.css('left'))){ \n\t\t\t\t\t\t\titem.addClass('menu-active'); \n\t\t\t\t\t\t} else { \n\t\t\t\t\t\t\thideMenu(submenu); \n\t\t\t\t\t\t} \n\t\t\t\t\t\t \n\t\t\t\t\t} else { \n\t\t\t\t\t\titem.removeClass('menu-active'); \n\t\t\t\t\t} \n\t\t\t\t\t \n\t\t\t\t} \n\t\t\t); \n\t\t}",
"function activateMenuElement(name){$(options.menu).forEach(function(menu){if(options.menu&&menu!=null){removeClass($(ACTIVE_SEL,menu),ACTIVE);addClass($('[data-menuanchor=\"'+name+'\"]',menu),ACTIVE);}});}",
"function forceSelectionIfWithinRect(ev, rect)\r\n{\r\n\tlet margin = activationSettings.middleMouseSelectionClickMargin;\r\n\r\n\tif (ev.clientX > rect.left - margin && ev.clientX < rect.right + margin\r\n\t && ev.clientY > rect.top - margin && ev.clientY < rect.bottom + margin)\r\n\t{\r\n\t\t// We got it! Event shouldn't do anything else.\r\n\t\tev.preventDefault();\r\n\t\tev.stopPropagation();\r\n\t\tshowPopupForSelection(ev);\r\n\r\n\t\t// blocks same middle click from triggering popup on down and then a search on up (on an engine icon)\r\n\t\tcanMiddleClickEngine = false;\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}",
"function openSubmenu(menu, item) {\n // mount far offscreen for measurement\n var node = menu.node;\n var style = node.style;\n style.visibility = 'hidden';\n menu.attach(document.body);\n menu.show();\n // compute the adjusted coordinates\n var elem = document.documentElement;\n var maxX = elem.clientWidth;\n var maxY = elem.clientHeight;\n var menuRect = node.getBoundingClientRect();\n var itemRect = item.getBoundingClientRect();\n var x = itemRect.right - SUBMENU_OVERLAP;\n var y = itemRect.top - firstItemOffset(node);\n if (x + menuRect.width > maxX) {\n x = itemRect.left + SUBMENU_OVERLAP - menuRect.width;\n }\n if (y + menuRect.height > maxY) {\n y = itemRect.bottom + lastItemOffset(node) - menuRect.height;\n }\n // move to adjusted position\n style.top = Math.max(0, y) + 'px';\n style.left = Math.max(0, x) + 'px';\n style.visibility = '';\n }",
"function IsItemActivated() { return bind.IsItemActivated(); }",
"function mouseApasat(ev) {\n x1 = my_canvasX(ev);\n y1 = my_canvasY(ev);\n m_apasat = true;\n \n}",
"function changeActiveMenuItemOnScroll() {\r\n\t\tvar scrollPos = $(document).scrollTop();\r\n\t\t$('.header-menu-a').each(function () {\r\n\t\t\t\tvar $currLink = $(this);\r\n\t\t\t\tvar refElement = $($currLink.attr(\"href\"));\r\n\t\t\t\tif (refElement.position().top <= scrollPos && refElement.position().top + refElement.outerHeight(true) > scrollPos) {\r\n\t\t\t\t\t$('.header-menu-a').removeClass(\"header-menu-a_active\");\r\n\t\t\t\t\t$currLink.addClass(\"header-menu-a_active\");\r\n\r\n\t\t\t\t\tpaginationUnderlineTransition(\r\n\t\t\t\t\t\t$(\".header-menu-nav\"),\r\n\t\t\t\t\t\t\".header-pagination-underline\",\r\n\t\t\t\t\t\t$(\".header-menu-a_active\"),\r\n\t\t\t\t\t\t0.99\r\n\t\t\t\t\t);\r\n\r\n\t\t\t\t} else {\r\n\t\t\t\t\t$currLink.removeClass(\"header-menu-a_active\");\r\n\t\t\t\t}\r\n\t\t});\r\n\t}",
"function menuHighlightClick() {\n Data.Edit.Mode = EditModes.Highlight;\n updateMenu();\n}",
"_focusActiveOption() {\n var _a;\n if (!this.useActiveDescendant) {\n (_a = this.listKeyManager.activeItem) === null || _a === void 0 ? void 0 : _a.focus();\n }\n this.changeDetectorRef.markForCheck();\n }",
"function i2uiKeepMenuInWindow(obj, x, y, id, x2)\r\n{\r\n var ExtraSpace = 10;\r\n\r\n var WindowLeftEdge;\r\n var WindowTopEdge;\r\n var WindowWidth;\r\n var WindowHeight;\r\n if (window.innerWidth != null)\r\n {\r\n WindowWidth = window.innerWidth;\r\n WindowHeight = window.innerHeight;\r\n }\r\n else\r\n {\r\n WindowWidth = document.body.clientWidth;\r\n WindowHeight = document.body.clientHeight;\r\n }\r\n if (window.pageXOffset != null)\r\n {\r\n WindowLeftEdge = window.pageXOffset;\r\n WindowTopEdge = window.pageYOffset;\r\n //i2uitrace(1,\"showmenu pageYOffset=\"+WindowTopEdge);\r\n }\r\n else\r\n {\r\n WindowLeftEdge = document.body.scrollLeft;\r\n WindowTopEdge = document.body.scrollTop;\r\n //i2uitrace(1,\"showmenu scrollTop=\"+WindowTopEdge);\r\n }\r\n\r\n\r\n var MenuLeftEdge = x;\r\n var MenuTopEdge = y;\r\n var MenuRightEdge;\r\n var MenuBottomEdge;\r\n if (document.layers)\r\n {\r\n MenuRightEdge = x + obj.clip.width;\r\n MenuBottomEdge = y + obj.clip.height;\r\n }\r\n else\r\n {\r\n // must change visibility in order to compute width !!\r\n i2uiToggleItemVisibility(id,'show');\r\n\r\n MenuRightEdge = x + obj.offsetWidth;\r\n MenuBottomEdge = y + obj.offsetHeight;\r\n }\r\n\r\n //i2uitrace(1,\"showmenu menu l=\"+x+\" t=\"+y);\r\n if (MenuRightEdge > i2uiExtraHSpace && i2uiExtraHSpace > 10)\r\n ExtraSpace = (WindowLeftEdge + WindowWidth) - i2uiExtraHSpace;\r\n var WindowRightEdge = (WindowLeftEdge + WindowWidth) - ExtraSpace;\r\n if (MenuBottomEdge > i2uiExtraVSpace && i2uiExtraVSpace > 10)\r\n ExtraSpace = (WindowTopEdge + WindowHeight) - i2uiExtraVSpace;\r\n var WindowBottomEdge = (WindowTopEdge + WindowHeight) - ExtraSpace;\r\n\r\n //i2uitrace(1,\"showmenu window l=\"+WindowLeftEdge+\" t=\"+WindowTopEdge);\r\n\r\n var dif;\r\n if (MenuRightEdge > WindowRightEdge)\r\n {\r\n if (x2 == null)\r\n {\r\n dif = MenuRightEdge - WindowRightEdge;\r\n }\r\n else\r\n {\r\n dif = MenuRightEdge - x2;\r\n }\r\n x -= dif;\r\n }\r\n if (MenuBottomEdge > WindowBottomEdge)\r\n {\r\n dif = MenuBottomEdge - WindowBottomEdge;\r\n y -= dif;\r\n }\r\n\r\n if (x < WindowLeftEdge)\r\n {\r\n x = 5;\r\n }\r\n\r\n if (y < WindowTopEdge)\r\n {\r\n y = 5;\r\n }\r\n\r\n if (document.layers)\r\n {\r\n obj.moveTo(x,y);\r\n i2uiToggleItemVisibility(id,'show');\r\n }\r\n else\r\n {\r\n obj.style.left = x;\r\n obj.style.top = y;\r\n }\r\n\r\n //fix 2/6/02 to improve placement of menus near right edge of screen\r\n // reset i2uiMenu_x to position of placed menu\r\n if (x2 == null)\r\n i2uiMenu_x = x;\r\n}",
"sliderMenuOnMouseOver(){\n\n const firstMenuItem = this[sliderMenuElement].querySelector('.slider-menu-list > li:first-child');\n const sliderMenuItems = this[sliderMenuElement].querySelectorAll('.slider-menu-list > li:not(:first-child)');\n\n this[sliderMenuElement].classList.add('active');\n firstMenuItem.classList.add('active');\n sliderMenuItems.forEach(function(menuItem){\n\n menuItem.classList.add('active');\n });\n }",
"function setActiveMenu() {\r\n var i;\r\n if (windowResized) {\r\n // reset after possible window resize\r\n scrollPositions = getScrollPositions();\r\n windowResized = false;\r\n }\r\n // Get top Window edge that is just under the Menu\r\n var topEdge = $(window).scrollTop() + menuHeight;\r\n // Special case: last section, don't switch black to\r\n // previous one immediatelly (avoid menu blinking).\r\n if (currentId == lastId && isThreshold(topEdge)) {\r\n return;\r\n }\r\n // explicitly set last section (as it has small height\r\n // and can't be selected otherwise inside a big window)\r\n else if (isPageEndReached(topEdge + $(window).height())) {\r\n setNewPosition(lastId);\r\n }\r\n // Going or scrolling down\r\n else if (topEdge > currentPosBottom) {\r\n for (i = currentId; i < scrollPositions.length; i++) {\r\n // we are looking for bottom edge here\r\n if (topEdge < getPosBottom(i)) {\r\n setNewPosition(i);\r\n return;\r\n }\r\n }\r\n }\r\n // Going up\r\n else if (topEdge < currentPosTop) {\r\n for (i = currentId; i >= 0; i--) {\r\n // is Window's top edge below this section's top?\r\n if (topEdge > scrollPositions[i]) {\r\n setNewPosition(i);\r\n return;\r\n }\r\n }\r\n }\r\n }",
"function onSelectStart(event){\n\n if (event instanceof MouseEvent && !renderer.xr.isPresenting()){\n\t// Handle mouse click outside of VR.\n\n\t// Determine screen coordinates of click.\n\tvar mouse = new THREE.Vector2();\n\tmouse.x = (event.clientX / window.innerWidth) * 2 - 1;\n\tmouse.y = - (event.clientY / window.innerHeight) * 2 + 1;\n\t// Create raycaster from the camera through the click into the scene.\n\tvar raycaster = new THREE.Raycaster();\n\traycaster.setFromCamera(mouse, camera);\n\n\t// Register the click into the GUI.\n\tGUIVR.intersectObjects(raycaster);\n\n } else if (!(event instanceof MouseEvent) && renderer.xr.isPresenting()){\n\t// Handle controller click in VR.\n\n\t// Bug workaround, Oculus Go browser doubles onSelectStart\n\t// event.\n\tif (navigator.platform == \"Linux armv8l\"){\n\t if (oculus_double_click_skip){\n\t\tconsole.log(\"SKIPPING\");\n\t\toculus_double_click_skip = false;\n\t\treturn;\n\t }\n\t oculus_double_click_skip = true;\n\t}\n\n\t// Retrieve the pointer object.\n\tvar controller = event.target;\n\tvar controllerPointer = controller.getObjectByName('pointer');\n\n\t// Create raycaster from the controller position along the\n\t// pointer line.\n\tvar tempMatrix = new THREE.Matrix4();\n\ttempMatrix.identity().extractRotation(controller.matrixWorld);\n\tvar raycaster = new THREE.Raycaster();\n\traycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld);\n\traycaster.ray.direction.set(0, 0, -1).applyMatrix4(tempMatrix);\n\n\t// Register the click into the GUI.\n\tGUIVR.intersectObjects(raycaster);\n\n\t//DEBUG.displaySession(renderer.xr);\n\t//DEBUG.displaySources(renderer.xr);\n\t//DEBUG.displayNavigator(navigator);\n\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}",
"function IsItemClicked(mouse_button = 0) {\r\n return bind.IsItemClicked(mouse_button);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the source for the user inputs to the given gate as the given observable. If there was already a source, it is replaced. | setUserInput (gate, observable) {
if (userInputsSubscriptions.has(gate.id)) {
userInputsSubscriptions.get(gate.id).unsubscribe()
}
userInputsSubscriptions.set(
gate.id,
observable.subscribe((...args) => {
getUserInput(gate).next(...args)
})
)
} | [
"function setUserInput (gate, state, value) {\n state.inputs[gate.id] = value\n}",
"UPDATE_EXCHANGE_SOURCE (_state, _exchangeSource) {\n _state.exchangeSource = _exchangeSource\n }",
"getInputs (gate) {\n if (!inputSubjects.has(gate.id)) {\n const gatePinSubjects = (\n gate.inputs\n .map(pin => (\n pin.connections[0] ? getPin(pin.connections[0]) : of(false)\n )).map(observable => (\n observable.pipe(map(x => (x ^ pin.isInverted) === 1))\n ))\n )\n inputSubjects.set(gate.id, combineLatest(gatePinSubjects))\n }\n return inputSubjects.get(gate.id)\n }",
"function addSource() {\r\n\r\n // Re-start source selection when we press button\r\n //\r\n CurStepObj.stageInStep = StageInStep.SrcSelectStarted;\r\n doNextStage();\r\n}",
"function changeCameraSource() {\n\tfor (var i = 0; i < 2; i++) {\n\t\t(function(i) {\n\t\t\t// Setup options for this camera source.\n\t\t\tvar options = {\n\t\t\t\t'scene-name': cameraCaptureKey[capture],\n\t\t\t\t'item': cameraSourceKey[i],\n\t\t\t\t'visible': false\n\t\t\t};\n\n\t\t\t// If this camera source is the one we want visible, make it so.\n\t\t\tif (i === cam[capture])\n\t\t\t\toptions.visible = true;\n\n\t\t\t// Send settings to OBS.\n\t\t\tobs.send('SetSceneItemProperties', options).catch((err) => {\n\t\t\t\tnodecg.log.warn(`Cannot change OBS source settings [${options['scene-name']}: ${options.item}]: ${err.error}`);\n\t\t\t});\n\t\t} (i));\n\t}\n}",
"setTransSourceUrl(value: string) {\n this.transSourceUrl = value;\n }",
"function switchGate () {\n return {\n id: nextId(),\n type: 'switch',\n inputs: Object.seal([]),\n outputs: Object.seal([pin()])\n }\n}",
"set gw( gw )\n {\n this.gateways.push( gw );\n }",
"function setFilter (input) {\n STORE.filter = input;\n}",
"function setPortObject(port,action){\n\tif(action == \"source\"){\n\t\tportspeedflag = true;\n\t\tportflag = true;\n\t\tsourcePath = port.ObjectPath;\n\t\tif(port.SwitchInfo != \"\"){\n\t\t\tvar switchArr2 = port.SwitchInfo.split(\"^\");\n\t\t\tsourceSwitch = switchArr2[0];\n\t\t}\n\t}else{\n\t\tportspeedflag2 = true;\n\t\tportflag2 = true;\n\t\tdstPath = port.ObjectPath;\n\t\tif(port.SwitchInfo != \"\"){\n\t\t\tvar switchArr2 = port.SwitchInfo.split(\"^\");\n\t\t\tdestSwitch = switchArr2[0];\n\t\t}\n\t}\n}",
"updateSrcSet(newSrc) {\n if (this.srcValues.length > 0) {\n this.srcValues.forEach(function (src) {\n if (src.name === newSrc.name) {\n src.url = newSrc.url;\n }\n }.bind(this));\n }\n\n this.saveSrcSet();\n this.fredCropper.el.dataset.crop = 'true';\n this.fredCropper.pluginTools.fredConfig.setPluginsData('fredcropper'+this.fredCropper.el.fredEl.elId, 'activated', 'true');\n }",
"function getUserInput (gate, state) {\n return state.inputs[gate.id]\n}",
"function setSourceVelocityFn(scope) {\n\tsource_velocity = scope.source_velocity_value; /** Setting the source speed based on the slider value */\n\tcircle_centre = 100; /**Resetting the circle radius while changing the slider */\n}",
"commitSource(source) {\n this._pendingUpdates.push({ kind: 'source', source });\n }",
"changeSrc(e, source) {\n e.preventDefault();\n const src = e.target.elements.source.value || source;\n if (src.includes('www.youtube.com')) {\n this.player.src({type: 'video/youtube', src: src});\n }\n else {\n this.player.src({src: src});\n }\n this.reset();\n }",
"function source_onchange() {\n var DWObject = gWebTwain.getInstance();\n if (DWObject) {\n var vDWTSource = document.getElementById(\"source\");\n if (vDWTSource) {\n\n if (vDWTSource)\n DWObject.SelectSourceByIndex(vDWTSource.selectedIndex);\n else\n DWObject.SelectSource();\n }\n\n DWObject.CloseSource();\n }\n}",
"set CustomProvidedInput(value) {}",
"function updateSource(updateAutoComplete) {\n\n var callback = targetMarker !== '' ? getRoutes : function(){};\n\n getPolygons(callback);\n if ( typeof updateAutoComplete !== 'undefined' && updateAutoComplete ) updateAutocomplete();\n }",
"setExchange (xc) {\n this.xc = xc\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/////////////////////////////////////////////////////////////////////////////////////////// p.258 updating game info updateGameInfo() resets display to initial values when a new game starts | function updateGameInfo() {
var $ = jewel.dom.$;
$("#game-screen .score span")[0].innerHTML = gameState.score;
$("#game-screen .level span")[0].innerHTML = gameState.level;
} | [
"function displayGameInfo(){\n // Game Stats\n document.getElementById(\"dealer-points\").innerHTML = dealer.points;\n document.getElementById(\"player-points\").innerHTML = player.points;\n document.getElementById(\"bet-amount\").innerHTML = player.bet;\n document.getElementById(\"bank-amount\").innerHTML = player.bank;\n document.getElementById(\"wins\").innerHTML = player.wins;\n document.getElementById(\"totalhands\").innerHTML = player.totalhands;\n // Control Buttons\n // document.getElementById(\"bet-button\").style.display = \"none\";\n // document.getElementById(\"cancel-button\").style.display = \"none\";\n // document.getElementById(\"deal-button\").style.display = \"none\";\n // document.getElementById(\"hit-button\").style.display = \"none\";\n // document.getElementById(\"stand-button\").style.display = \"none\";\n document.getElementById(\"messages\").innerHTML = \"Pick the bet amount\";\n document.getElementById(\"playerSection\").style.display = \"flex\";\n\n\n // Array.from(chip).forEach(function(element){\n // element.style.display = \"\";\n // });\n chipbuttons.style.display = \"flex\";\n // document.getElementById(\"controlbuttons\").style.display = \"none\";\n }",
"function updateGuessedDisplay() {\n $('#guessed0').html(currentGuess[0]);\n $('#guessed1').html(currentGuess[1]);\n $('#guessed2').html(currentGuess[2]);\n $('#guessed3').html(currentGuess[3]);\n updateDisplay();\n }",
"function displayGameScreen()\n{\n\t\n\tdisplayResourceElement();\n\t\t\t\n\tdisplayInfoElement();\n\t\n\tdisplayMapElement();\n\t\n\tjoinGame();\n\t\n\tif(player.onTurn == true)\n\t{\n\t\tdisplayEndTurnElement(\"salmon\");\n\t\t\n\t\tdisplayTurnCounterElement(\"lightGreen\");\n\t}\n\telse\n\t{\n\t\tdisplayEndTurnElement(\"lightSlateGrey\");\n\t\n\t\tdisplayTurnCounterElement(\"salmon\");\n\t}\n\t\n\tgameStarted = true;\n\t\n\tstage.update();\n}",
"function reinitializeAppropriateDisplay() {\n updateEventVars(getNow());\n displayOnPage();\n }",
"function updateDisplay(){\n\t\t// Update any changes the Hero element\n\t\t$(\".hero\").html(\n\t\t\t\t\"<p>\" + hero.name + \"</p>\" +\n\t\t\t\t\"<img src='\" + hero.img + \"' >\" +\n\t\t\t\t\"<p> HP: \" + hero.hitPoints + \"</p>\"\n\t\t);\n\t\t// Update any changes the Defender element\n\t\t$(\".defender\").html(\n\t\t\t\t\"<p>\" + defender.name + \"</p>\" +\n\t\t\t\t\"<img src='\" + defender.img + \"' >\" +\n\t\t\t\t\"<p> HP: \" + defender.hitPoints + \"</p>\"\n\t\t);\n\t}",
"function updateGameText() {\n ammoText.text = 'Arrows: ' + game.globals.arrowsLeft; \n healthText.text = 'Health: ' + game.globals.health;\n}",
"_initializeGameValues() {\n this.currentFPS = GameConfig.STARTING_FPS;\n this.scoreBoard.resetScore();\n\n this.player = new Player(this.gameView.getPlayerName(), \"white\");\n this.food = new Food(this.boardView.getRandomCoordinate(this.player.segments), \"lightgreen\");\n this.gameView.hideChangeNameButton();\n }",
"function reshowAllGuiGenes() {\n updateGuiGenes();\n}",
"function updatePlayer() {\n initializePlayer();\n newPlayer.setYearsInLeague(\"16\");\n newPlayer.display();\n\n}",
"function updateSlotDisplays(player){\n\t\tdocument.getElementById(\"header\").innerHTML = \n\t\t\t\t\t\"<h3>3-of-a-Kind Slot-o-Rama</h3>\" + \n\t\t\t\t\t\"<h4>$\" + payout + \" per credit bet<br>\" +\n\t\t\t\t\t\"Max bet = \" + multiplierMax + \" credits</h4>\";\n\t\tdocument.getElementById(\"credit_cost\").innerHTML = \"<b>$\" + creditCost + \"</b><br>per credit\";\n\t\tdocument.getElementById(\"recent_win_payout\").innerHTML = \"Recent Win Payout:<br><b>$\" + recentWinPayout + \"</b>\";\n\t\tdocument.getElementById(\"previous_turn_payout\").innerHTML = \"Previous Turn Payout:<br><b>$\" + previousTurnPayout + \"</b>\";\n\t\tdocument.getElementById(\"current_bet\").innerHTML = \"Current Bet:<br><b>\" + multiplier + \" credit</b>\";\n\t\tif (player) {\n\t\t\tdocument.getElementById(\"balance\").innerHTML = \"Balance:<br><b>$\" + player.getBalance().toFixed(2) + \"</b>\";\t\n\t\t}\n\t\toutputResults();\n\t}",
"function gameReset() { // <--- Create a new function called gameReset. This will store all the things the game will do when it, well, resets! \n if (gameFinished) // <--- If gameFinished = true... \n updateDisplay(); // <--- Oh... we're being referred to another function... Let's see what that one says!\n }",
"function updateActiveGame() {\n // Return if we're not logged in\n if(!Dworek.state.loggedIn)\n return;\n\n // Request new game info if the same game is still active\n if(Dworek.state.activeGame != null && (Dworek.state.activeGame == Dworek.utils.getGameId() || !Dworek.utils.isGamePage()))\n requestGameInfo();\n\n // Return if we're not on a game page\n if(!Dworek.utils.isGamePage()) {\n Dworek.utils.lastViewedGame = null;\n return;\n }\n\n // Get the ID of the game page\n const gameId = Dworek.utils.getGameId();\n\n // Return if the last viewed game is this game\n if(Dworek.state.lastViewedGame == gameId)\n return;\n\n // Check whether this game is different than the active game\n if(Dworek.state.activeGame != gameId) {\n // Automatically select this as active game if we don't have an active game now\n if(Dworek.state.activeGame === null) {\n // Set the active game\n setActiveGame(gameId);\n\n } else {\n // Ask the user whether to select this as active game\n showDialog({\n title: 'Change active game',\n message: 'You may only have one active game to play at a time.<br /><br />Would you like to change your active game to this game now?',\n actions: [\n {\n text: 'Activate this game',\n value: true,\n state: 'primary',\n icon: 'zmdi zmdi-swap',\n action: function() {\n // Set the active game\n setActiveGame(gameId);\n }\n },\n {\n text: 'View current game',\n value: true,\n icon: 'zmdi zmdi-long-arrow-return',\n action: function() {\n // Navigate to the game page\n Dworek.utils.navigateToPath('/game/' + Dworek.state.activeGame);\n }\n },\n {\n text: 'Ignore'\n }\n ]\n\n }, function(value) {\n // Return if the action is already handled\n if(!!true)\n return;\n\n // Show a notification to switch to the active game\n showNotification('Switch to your active game', {\n action: {\n text: 'Switch',\n action: function() {\n $.mobile.navigate('/game/' + Dworek.state.activeGame, {\n transition: 'flow'\n });\n }\n }\n });\n });\n }\n }\n\n // Update the status labels\n updateStatusLabels();\n\n // Update the last viewed game\n Dworek.state.lastViewedGame = gameId;\n}",
"function displayGameplay() {\n image(backgroundImg, width / 2, height / 2, 1500, 800);\n\n // Handle input for the player\n player.handleInput();\n\n // Move all the supplies\n player.move();\n for (let i = 0; i < supply.length; i++) {\n supply[i].move();\n // Handle the bee eating any of the supply\n player.handleEating(supply[i]);\n supply[i].display();\n }\n\n //Display firstAid kit\n firstAid.move();\n firstAid.display();\n\n //Display battery\n battery.move();\n battery.display();\n\n // Handle the player collecting any of the supply\n player.handleEating(water);\n player.handleEating(food);\n player.handleCharging(battery);\n player.handleHealing(firstAid);\n\n //Check if the player is dead and to end game\n player.endGame();\n // Display the player\n player.display();\n\n //display the flashlight\n flashlight.display();\n\n // display health (health bar)\n healthBar.updateHealth(player.health);\n healthBar.display();\n\n //display flashlight battery (battery bar)\n batteryBar.updateBattery(player.batteryLevel);\n batteryBar.display();\n}",
"function updateView() {\n // For every square on the board.\n console.log(MSBoard.rows);\n\n for (var x = 0; x < MSBoard.columns; x++) {\n for (var y = 0; y < MSBoard.rows; y++) {\n squareId = \"#\" + x + \"-\" + y;\n // Removes the dynamic classes from the squares before adding appropiate ones back to it.\n $(squareId).removeClass(\"closed open flagged warning\");\n\n square = MSBoard.squares[x][y];\n\n // These questions determine how a square should appear.\n // If no other text is put into a square, a is inserted because otherwise it disturbs the grid.\n // If a square is open, it should be themed as so and also display the number of nearby mines.\n if (square.open && !square.mine) {\n $(squareId).addClass(\"open\");\n $(squareId).html(square.nearbyMines);\n } \n // Flags are displayed only if the square is still closed.\n else if (square.flag && !square.open) {\n $(squareId).addClass(\"closed\");\n $(squareId).html(\"<img src='redFlag.png' class='boardImg flag' /> \")\n } \n // Mines are displayed either if they're open (Either from opening one and losing or during validating) or while the cheat control is pressed.\n else if (square.mine && (square.open || cheating)) {\n $(squareId).addClass(\"warning\");\n $(squareId).html(\"<img src='mine.png' class='boardImg mine' /> \")\n } \n // The HTML is set to a blank space in case there is nothing else to put in the space. \n else if (!square.open && !square.flag) {\n $(squareId).addClass(\"closed\"); \n $(squareId).html(\" \")\n }\n\n }\n }\n\n if (startMenuOn) {\n $(\"#newGameSettings\").css(\"display\", \"block\");\n } else {\n $(\"#newGameSettings\").css(\"display\", \"none\"); \n }\n\n}",
"function initState() {\r\n var player1, player2, p1tag, p2tag;\r\n\r\n document.getElementsByClassName(\"game-container\")[0].style.display = \"block\";\r\n document.getElementsByClassName(\"game-intro\")[0].style.display = \"none\";\r\n\r\n player1 = document.getElementById('player1');\r\n p1tag = player1.children[2].children[5];\r\n p1tag.innerHTML = p1name +' is ready to fight.';\r\n\r\n player2 = document.getElementById('player2');\r\n p2tag = player2.children[2].children[5];\r\n p2tag.innerHTML = p2name +' is ready to fight.';\r\n\r\n document.getElementById('turn_text').innerHTML = p1name + \"'s turn\";\r\n}",
"function startGame() {\n getDifficulty();\n startTimer();\n addCards();\n $(\"refresh\").addEventListener(\"click\", addCards);\n toggleGame();\n currSetCount = 0;\n $(\"set-count\").innerHTML = currSetCount;\n deselectAll();\n }",
"function displayGame(){\n gameType.style.display ='none';\n gamePlay.style.display ='block';\n}",
"function infoText() {\n // Shows \"PAUSE\" if the game is paused (key: SPACEBAR)\n if (pause) {\n fill(255);\n text(\"PAUSE\", gridX - 7*reso, scoreY);\n }\n \n // Shows infos about the commands at the beginning\n if (time < 10) {\n var alpha = 255;\n if (time > 4) { // After some time, the text fades away\n alpha -= (time - 4) * 100;\n }\n fill(255, alpha);\n \n var textX = gridX - 7*reso;\n text(\"MOVE:\", textX, scoreY + 3.5 * reso)\n text(\"ARROWS\", textX, scoreY + 5 * reso)\n text(\"PAUSE:\", textX, scoreY + 8 * reso)\n text(\"SPACEBAR\", textX, scoreY + 9.5 * reso)\n text(\"RESET:\", textX, scoreY + 12.5 * reso)\n text(\"ENTER\", textX, scoreY + 14 * reso)\n }\n}",
"function updateUiData(info){\n const {date , temp , feelings} = info;\n // update the date div \n dateEntry.innerHTML = \"Date: \" + date;\n\n // update the temp div \n tempEntry.innerHTML = \"Temp: \" + temp;\n\n // update the content entry \n content.innerHTML = \"Feelings: \" + feelings ;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
helper for creating derived property definitions | function createDerivedProperty(modelProto, name, definition) {
var def = modelProto._derived[name] = {
fn: isFunction(definition) ? definition : definition.fn,
cache: (definition.cache !== false),
depList: definition.deps || []
};
// add to our shared dependency list
def.depList.forEach(function (dep) {
modelProto._deps[dep] = union(modelProto._deps[dep] || [], [name]);
});
// defined a top-level getter for derived names
Object.defineProperty(modelProto, name, {
get: function () {
return this._getDerivedProperty(name);
},
set: function () {
throw new TypeError("`" + name + "` is a derived property, it can't be set directly.");
}
});
} | [
"inherit(property) {\n }",
"createProperty(obj, name, value, post = null, priority = 0, transform = null, isPoly = false) {\n obj['__' + name] = {\n value,\n isProperty: true,\n sequencers: [],\n tidals: [],\n mods: [],\n name,\n type: obj.type,\n __owner: obj,\n\n fade(from = 0, to = 1, time = 4, delay = 0) {\n Gibber[obj.type].createFade(from, to, time, obj, name, delay);\n return obj;\n }\n\n };\n Gibber.addSequencing(obj, name, priority, value, '__');\n Object.defineProperty(obj, name, {\n configurable: true,\n get: Gibber[obj.type].createGetter(obj, name),\n set: Gibber[obj.type].createSetter(obj, name, post, transform, isPoly)\n });\n }",
"function ActiveXAwarePropMethodFactory() {\r\n\t\r\n}",
"_addProperties(node, properties, labels, propMaker) {\n let tag = \"/\";\n for (let label of [...labels].sort()) {\n if (tag !== \"/\") tag += \"-\";\n tag += label;\n }\n\n for (let property in properties) {\n // Predicate\n let propertyNode = propMaker[property + tag];\n this._labelize(propertyNode, property);\n this._addQuad(propertyNode, rdf.type, prec.Property);\n this._addQuad(propertyNode, rdf.type, prec.CreatedProperty);\n this._addQuad(prec.CreatedProperty, rdfs.subClassOf, prec.CreatedVocabulary);\n\n // Object\n if (!Array.isArray(properties[property])) {\n let nodeValue = this._makeNodeForPropertyValue(properties[property]);\n this._addQuad(node, propertyNode, nodeValue);\n } else {\n let listHead = this._makeNodeForPropertyValues(properties[property]);\n this._addQuad(node, propertyNode, listHead);\n }\n }\n }",
"_buildPropertyProps(properties = {}) {\n const props = {};\n for (const propertyName in properties) {\n const property = properties[propertyName];\n const propData = NOTION_PAGE_PROPERTIES[property.type];\n\n if (!propData) continue;\n\n props[propertyName] = {\n type: propData.type,\n label: propertyName,\n description: this._buildPropDescription(property.type, propData.example),\n options: propData.options(property),\n optional: true,\n };\n }\n return props;\n }",
"addProperties (target) {\n\n // Property getter/setter injection\n this.position.addProperties(target);\n\n // Component references\n target.position = this.position;\n target.scale = this.scale;\n\n return target;\n\n }",
"function propertyDetails (name) {\n return {\n getter: '_get_' + name,\n setter: '_set_' + name,\n processor: '_process_' + name,\n validator: '_validate_' + name,\n defaultValue: '_default_value_' + name,\n value: '_' + name\n };\n }",
"function MyProperty (name, category, location) {\n this.name = name;\n this.category = category;\n this.location = location;\n}",
"prop(prop) {\n return !prop.perNode\n ? this.type.prop(prop)\n : this.props\n ? this.props[prop.id]\n : undefined\n }",
"function assertValidSuperProps(assertion, makeStr, makeExpr, type, generator, args, static,\n extending)\n {\n let superProperty = superProp(ident(\"prop\"));\n let superMember = superElem(lit(\"prop\"));\n\n let situations = [\n [\"super.prop\", superProperty],\n [\"super['prop']\", superMember],\n [\"super.prop()\", callExpr(superProperty, [])],\n [\"super['prop']()\", callExpr(superMember, [])],\n [\"new super.prop()\", newExpr(superProperty, [])],\n [\"new super['prop']()\", newExpr(superMember, [])],\n [\"delete super.prop\", unExpr(\"delete\", superProperty)],\n [\"delete super['prop']\", unExpr(\"delete\", superMember)],\n [\"++super.prop\", updExpr(\"++\", superProperty, true)],\n [\"super['prop']--\", updExpr(\"--\", superMember, false)],\n [\"super.prop = 4\", aExpr(\"=\", superProperty, lit(4))],\n [\"super['prop'] = 4\", aExpr(\"=\", superMember, lit(4))],\n [\"super.prop += 4\", aExpr(\"+=\", superProperty, lit(4))],\n [\"super['prop'] += 4\", aExpr(\"+=\", superMember, lit(4))],\n [\"super.prop -= 4\", aExpr(\"-=\", superProperty, lit(4))],\n [\"super['prop'] -= 4\", aExpr(\"-=\", superMember, lit(4))],\n [\"super.prop *= 4\", aExpr(\"*=\", superProperty, lit(4))],\n [\"super['prop'] *= 4\", aExpr(\"*=\", superMember, lit(4))],\n [\"super.prop /= 4\", aExpr(\"/=\", superProperty, lit(4))],\n [\"super['prop'] /= 4\", aExpr(\"/=\", superMember, lit(4))],\n [\"super.prop %= 4\", aExpr(\"%=\", superProperty, lit(4))],\n [\"super['prop'] %= 4\", aExpr(\"%=\", superMember, lit(4))],\n [\"super.prop <<= 4\", aExpr(\"<<=\", superProperty, lit(4))],\n [\"super['prop'] <<= 4\", aExpr(\"<<=\", superMember, lit(4))],\n [\"super.prop >>= 4\", aExpr(\">>=\", superProperty, lit(4))],\n [\"super['prop'] >>= 4\", aExpr(\">>=\", superMember, lit(4))],\n [\"super.prop >>>= 4\", aExpr(\">>>=\", superProperty, lit(4))],\n [\"super['prop'] >>>= 4\", aExpr(\">>>=\", superMember, lit(4))],\n [\"super.prop |= 4\", aExpr(\"|=\", superProperty, lit(4))],\n [\"super['prop'] |= 4\", aExpr(\"|=\", superMember, lit(4))],\n [\"super.prop ^= 4\", aExpr(\"^=\", superProperty, lit(4))],\n [\"super['prop'] ^= 4\", aExpr(\"^=\", superMember, lit(4))],\n [\"super.prop &= 4\", aExpr(\"&=\", superProperty, lit(4))],\n [\"super['prop'] &= 4\", aExpr(\"&=\", superMember, lit(4))],\n\n // We can also use super from inside arrow functions in method\n // definitions\n [\"()=>super.prop\", arrowExpr([], superProperty)],\n [\"()=>super['prop']\", arrowExpr([], superMember)]];\n\n for (let situation of situations) {\n let sitStr = situation[0];\n let sitExpr = situation[1];\n\n let fun = methodFun(\"method\", type, generator, args, [exprStmt(sitExpr)]);\n let str = makeStr(sitStr, type, generator, args, static, extending);\n assertion(str, makeExpr(fun, type, static), extending);\n }\n }",
"visitPhysical_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"getProps(){\n let properties = new ValueMap();\n let propWalker = this;\n\n while(propWalker.__type<0x10){\n for(let [k,v] of propWalker.__props){\n properties.set(k,v);\n }\n propWalker = propWalker.getProp(\"__proto__\");\n };\n return properties;\n }",
"function PropertyTransition() {\n this.isFinished = false;\n this._duration = 0;\n this._easeFunc = d3.ease(\"cubic-in-out\"); // also default in d3\n\n this._elapsedTime = 0;\n this._id = null;\n this._propName = null;\n this._endValue = null;\n this._interpolator = null; // Check whether required methods are implemented.\n // This class can't be instantiated, only subclasses\n // implementing specified interface:\n\n if (this.getObjectProperties == null) {\n throw new Error(\"getObjectProperties method must be implemented by descendant!\");\n }\n\n if (this.setObjectProperties == null) {\n throw new Error(\"setObjectProperties method must be implemented by descendant!\");\n }\n}",
"prop(propertyName, propertyValue) {\n\t\t\tif (typeof propertyValue === \"undefined\") {\n\t\t\t\treturn this.preset[propertyName];\n\t\t\t} else {\n\t\t\t\tthis.preset[propertyName] = propertyValue;\n\t\t\t\treturn this;\n\t\t\t}\n\t\t}",
"function defineAllProperties(to, from) {\n to.__model__ = to.__model__ || from;\n each(from, function(m,n) {\n try {\n if (to.__model__ !== from)\n to.__model__[n] = m;\n defineProperty(to,n,m);\n } catch (t) {}\n });\n }",
"extend(...props) {\n let newTypes = []\n for (let type of this.types) {\n let newProps = null\n for (let source of props) {\n let add = source(type)\n if (add) {\n if (!newProps) newProps = Object.assign({}, type.props)\n newProps[add[0].id] = add[1]\n }\n }\n newTypes.push(\n newProps\n ? new dist_NodeType(type.name, newProps, type.id, type.flags)\n : type\n )\n }\n return new NodeSet(newTypes)\n }",
"function makeTestChemProperties(symbol, name, creator,\n colorSolid, colorLiquid, colorGas,\n id, molarMass, meltingPoint, boilingPoint, density, waterSoluble){\n\n let p = {};\n p[CHEMICAL_PROPERTY_ID] = id;\n p[CHEMICAL_PROPERTY_SYMBOL] = symbol;\n p[CHEMICAL_PROPERTY_NAME] = name;\n p[CHEMICAL_PROPERTY_CREATOR] = creator;\n p[CHEMICAL_PROPERTY_COLOR_SOLID] = colorSolid;\n p[CHEMICAL_PROPERTY_COLOR_LIQUID] = colorLiquid;\n p[CHEMICAL_PROPERTY_COLOR_GAS] = colorGas;\n p[CHEMICAL_PROPERTY_MOLAR_MASS] = molarMass;\n p[CHEMICAL_PROPERTY_MELTING_POINT] = meltingPoint;\n p[CHEMICAL_PROPERTY_BOILING_POINT] = boilingPoint;\n p[CHEMICAL_PROPERTY_DENSITY] = density;\n p[CHEMICAL_PROPERTY_WATER_SOLUBLE] = waterSoluble;\n return p;\n}",
"addProperties(features, ranges, propertyName, format) {\n const self = this;\n features.forEach(function(feature) {\n let color = \"#000\";\n for (var i = 0; i < ranges.length; i++) {\n if (feature.properties[propertyName] >= ranges[i].min && feature.properties[propertyName] <= ranges[i].max) {\n color = self.shadingColors[i];\n break;\n }\n }\n feature.properties.color = color;\n\n feature.properties.tooltipValue = self.formatNumber(feature.properties[propertyName], format);\n\n const formattedRanges = [];\n ranges.forEach(function(range) {\n const formattedRange = Object.assign({}, range);\n formattedRange.min = self.formatNumber(formattedRange.min, format);\n formattedRange.max = self.formatNumber(formattedRange.max, format);\n formattedRanges.push(formattedRange);\n });\n\n\n feature.properties.ranges = self.formatRanges(ranges, format);\n });\n }",
"constructor(options) {\n /// @internal\n this.typeNames = [\"\"];\n /// @internal\n this.typeIDs = Object.create(null);\n /// @internal\n this.prop = new NodeProp();\n this.flags = options.flags;\n this.types = options.types;\n this.flagMask = Math.pow(2, this.flags.length) - 1;\n this.typeShift = this.flags.length;\n let subtypes = options.subtypes || 0;\n let parentNames = [undefined];\n this.typeIDs[\"\"] = 0;\n let typeID = 1;\n for (let type of options.types) {\n let match = /^([\\w\\-]+)(?:=([\\w-]+))?$/.exec(type);\n if (!match)\n throw new RangeError(\"Invalid type name \" + type);\n let id = typeID++;\n this.typeNames[id] = match[1];\n this.typeIDs[match[1]] = id;\n parentNames[id] = match[2];\n for (let i = 0; i < subtypes; i++) {\n let subID = typeID++, name = match[1] + \"#\" + (i + 1);\n this.typeNames[subID] = name;\n this.typeIDs[name] = subID;\n parentNames[subID] = match[1];\n }\n }\n this.parents = parentNames.map(name => {\n if (name == null)\n return 0;\n let id = this.typeIDs[name];\n if (id == null)\n throw new RangeError(`Unknown parent type '${name}' specified`);\n return id;\n });\n if (this.flags.length > 30 || this.typeNames.length > Math.pow(2, 30 - this.flags.length))\n throw new RangeError(\"Too many style tag flags to fit in a 30-bit integer\");\n }",
"function ensurePropertyFunctions (Ctor) {\n const props = Ctor.props;\n\n return keys(props).reduce((descriptors, descriptorName) => {\n descriptors[descriptorName] = props[descriptorName];\n if (typeof descriptors[descriptorName] !== 'function') {\n descriptors[descriptorName] = initProps(descriptors[descriptorName]);\n }\n return descriptors;\n }, {});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if the state or payload is malformed | function stateAndPayloadAreValid(config, state, payload) {
// ensure that the instances array exists
if (! Array.isArray(state[config.stateKey])) {
console.error(`State does not contain an "${ config.stateKey }" array.`);
return false;
}
// ensure that the payload contains an id
if (typeof payload !== 'object' || typeof payload[config.instanceKey] === 'undefined') {
console.error(`Mutation payloads must be an object with an "${ config.instanceKey }" property.`);
return false;
}
return true;
} | [
"function stateAndPayloadAreValid(config, state, payload) {\n\n // ensure that the instances array exists\n if (!Array.isArray(state[config.stateKey])) {\n console.error('State does not contain an \"' + config.stateKey + '\" array.');\n return false;\n }\n\n // ensure that the payload contains an id\n if ((typeof payload === 'undefined' ? 'undefined' : _typeof(payload)) !== 'object' || typeof payload[config.instanceKey] === 'undefined') {\n console.error('Mutation payloads must be an object with an \"' + config.instanceKey + '\" property.');\n return false;\n }\n\n return true;\n}",
"function isValidPayload(payloadRules, data){\n // hold the validation errors\n var valBeforeErrors;\n\n //go through all the specified rules and if there is any that is not required the \n // a request Rejection Event will be fired and change in the data structure will be required\n for(var field in payloadRules){\n\n //list of all rules converted into an array\n var rules = payloadRules[field];\n rules = typeof rules == 'array' ? rules : typeof rules == 'string' ? rules.split('|') : new Error(\"Payload structure is invalid! \\n Please check the structure of request in request pool and validate it to string or array\")\n \n if(field in data){\n\n }\n }\n\n}",
"checkValidityProblems() {\n\t\t//Check whether there are any unnamed items or items without prices\n\t\tlet problems = false;\n\t\tif(this.state.albumName === \"\") {\n\t\t\tproblems = true;\n\t\t}\n\t\tfor (let item of this.state.items) {\n\t\t\tif(item.itemName === \"\" || (this.state.isISO && item.description === \"\") || (!this.state.isISO && (item.price === \"\" || item.pic === null)) ) {\n\t\t\t\tproblems = true;\n\t\t\t}\n\t\t}\n\t\tif (problems) {\n\t\t\tlet items = this.state.items;\n\t\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\t\titems[i].highlighted = true;\n\t\t\t}\n\t\t\tthis.setState({\n\t\t\t\tshowMissingFieldsPopup: true,\n\t\t\t\thighlighted: true,\n\t\t\t\titems: items\n\t\t\t})\n\t\t}\n\t\treturn(problems);\n\t}",
"function checkErrors(data) {\n\tif (data['error'] !== false) {\n\t\tconsole.log(data['error']);\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}",
"validateMessage (message) {\n\t\tif (message.post.$set) { return false; }\n\t\tAssert.ifError(this.shouldFail);\t// if this test should fail, we should not have recieved a message\n\t\tAssert(message.requestId, 'received message has no requestId');\n\t\tlet post = message.post;\n\t\tAssert.strictEqual(post.teamId, this.team.id, 'incorrect team ID');\n\t\tAssert.strictEqual(post.streamId, this.teamStream.id, 'incorrect stream ID');\n\t\tAssert.strictEqual(post.parentPostId, this.parentPost.id, 'incorrect parent post ID');\n\t\tAssert.strictEqual(post.text, this.expectedText, 'text does not match');\n\t\tAssert.strictEqual(post.creatorId, this.userData[0].user.id, 'creatorId is not the expected user');\n\t\treturn true;\n\t}",
"validWeather()\n {\n if (Array.isArray(this.state.weather)) {\n if (!this.state.weather[0].id || this.state.weather.length === 0)\n return false;\n else\n return true;\n } else {\n console.log(\"Not an array\");\n return false;\n }\n }",
"static checkParamsValidity (channel) {\n const { clientId, clientSecret, serviceId } = channel\n channel.phoneNumber = channel.phoneNumber.split(' ').join('')\n\n if (!clientId) { throw new BadRequestError('Parameter is missing: Client Id') }\n if (!clientSecret) { throw new BadRequestError('Parameter is missing: Client Secret') }\n if (!serviceId) { throw new BadRequestError('Parameter is missing: Service Id') }\n if (!channel.phoneNumber) { throw new BadRequestError('Parameter is missing: Phone Number') }\n\n return true\n }",
"function checkSecurity(){\t\t\t\n\t\t// Check the security tokens\n\t\tif (messageIn.type!=INIT && (messageIn.tokenParent!=securityTokenParent || messageIn.tokenChild!=securityTokenChild)){\n\t\t\tlog( \"Security token error: Invalid security token received. The message will be discarded.\" );\n\t\t\thandleSecurityError(smash.SecurityErrors.INVALID_TOKEN);\n\t\t\treturn false;\n\t\t}\t\t\n\t\t// Attacks should never pass the security check. Code below is to debug the implementation.\n//\t\tif(oah_ifr_debug){\n//\t\t\tif (messageIn.type!=INIT && messageIn.type!=ACK && messageIn.type!=PART && messageIn.type!=END){\n//\t\t\t\tif(oah_ifr_debug)debug(\"Syntax error: Message Type. The message will be discarded.\");\n//\t\t\t\treturn false;\n//\t\t\t}\n//\t\t\tif (!(messageIn.msn>=0 && messageIn.msn<=99)){\n//\t\t\t\tif(oah_ifr_debug)debug(\"Syntax error: Message Sequence Number. The message will be discarded.\");\n//\t\t\t\treturn false;\n//\t\t\t}\n//\t\t\tif (!(messageIn.ack==0 || messageIn.ack==1)){\n//\t\t\t\tif(oah_ifr_debug)debug(\"Syntax error: ACK. The message will be discarded.\");\n//\t\t\t\treturn false;\n//\t\t\t}\n//\t\t\tif (!(messageIn.ackMsn>=0 && messageIn.ackMsn<=99)){\n//\t\t\t\tif(oah_ifr_debug)debug(\"Syntax error: ACK Message Sequence Number. The message will be discarded.\");\n//\t\t\t\treturn false;\n//\t\t\t}\n//\t\t}\n\t\treturn true;\n\t}",
"isValidRecordingData() {\n if (Array.isArray(this.recordingData)) {\n if (Array.isArray(this.recordingData[0]) && this.recordingData[0].length === 3) {\n return true;\n }\n }\n\n console.log(`Error: Input recording data is not in valid format`);\n return false;\n }",
"function isMessageValid() {\n return $message.val().length > 0;\n }",
"validate(invalidProperties)\n\t{\n\t\tif(typeof this.addressLine1 === \"string\" && this.addressLine1.length > 0 && this.addressLine1.length < 35)\n\t\t{\n\t\t\tdelete invalidProperties.addressLine1;\n\t\t}\n\t\tif(typeof this.addressLine2 === \"string\" && this.addressLine2.length < 35)\n\t\t{\n\t\t\tdelete invalidProperties.addressLine2;\n\t\t}\n\t\tif(typeof this.addressLine3 === \"string\" && this.addressLine3.length < 35)\n\t\t{\n\t\t\tdelete invalidProperties.addressLine3;\n\t\t}\n\t\tif(typeof this.city === \"string\" && this.city.length > 0 && this.city.length < 35)\n\t\t{\n\t\t\tdelete invalidProperties.city;\n\t\t}\n\t\t//TODO: Check to see if countryData has a list of provinces or not, if it doesn't, this is theoretically valid\n\t\tif(countryData.data[this.country] && typeof this.stateProvince === \"string\" && this.stateProvince.length < 35)\n\t\t{\n\n\t\t\tif(Object.keys(countryData.data[this.country].subdivisions).length === 0)\n\t\t\t{\n\t\t\t\tdelete invalidProperties.stateProvince;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//TODO: FIX This hack before deploying to production.\n\t\t\t\tvar valid = false;\n\t\t\t\tObject.keys(countryData.data[this.country].subdivisions).forEach(subdiv => {\n\t\t\t\t\tif(this.stateProvince === subdiv || this.stateProvince === subdiv.split('-')[1])\n\t\t\t\t\t{\n\t\t\t\t\t\tvalid = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif(valid === true)\n\t\t\t\t{\n\t\t\t\t\tdelete invalidProperties.stateProvince;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(typeof this.country === \"string\" && this.country.length > 0 && this.country.length <= 3)\n\t\t{\n\t\t\tdelete invalidProperties.country;\n\t\t}\n\t\tif(this.country === \"CAN\" && typeof this.zipPostalCode === \"string\")\n\t\t{\n\t\t\tif(this.zipPostalCode[3] !== \" \")\n\t\t\t{\n\t\t\t\tthis.zipPostalCode = this.zipPostalCode.slice(0,3).toUpperCase()+\" \"+this.zipPostalCode.slice(3,6).toUpperCase();\n\t\t\t}\n\n\t\t\tif(/^[ABCEGHJKLMNPRSTVXY]\\d[ABCEGHJKLMNPRSTVWXYZ]( )?\\d[ABCEGHJKLMNPRSTVWXYZ]\\d$/i.test(this.zipPostalCode) === true)\n\t\t\t{\n\t\t\t\tthis.zipPostalCode = this.zipPostalCode.toUpperCase();\n\t\t\t\tdelete invalidProperties.zipPostalCode;\n\t\t\t}\n\t\t}\n\t\telse if(this.country === \"USA\" && typeof this.zipPostalCode === \"string\")\n\t\t{\n\t\t\tif(/^[0-9]{5}(?:-[0-9]{4})?$/.test(this.zipPostalCode) === true)\n\t\t\t{\n\t\t\t\tdelete invalidProperties.zipPostalCode;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(typeof this.zipPostalCode === \"string\" && this.zipPostalCode.length < 35)\n\t\t\t{\n\t\t\t\tdelete invalidProperties.zipPostalCode;\n\t\t\t}\n\t\t}\n\t}",
"isNotSpamSubmission() {\n \n var spamFieldValue = this.state.forbiddenInput;\n\n if(spamFieldValue.length !== 0) {\n return false;\n }\n \n return true; \n }",
"isInErrorState_(state) {\n return state == TermsOfServiceScreenState.ERROR;\n }",
"function isRequestValid(req){\n return !(req.body === undefined\n || Object.keys(req.body).length < 4\n || !supportedTypes.includes(req.body.type)\n || !activityFields.every(field => req.body.hasOwnProperty(field)));\n}",
"validateSmac() {\n let regex = /^[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}$/;\n if (regex.test(this.state.smac.replace(/^\\s+|\\s+$/g, \"\"))) return true;\n this.setState(\n {\n smacError: true,\n },\n () => {\n return false;\n }\n );\n }",
"validateDmac() {\n let regex = /^[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}$/;\n if (regex.test(this.state.dmac.replace(/^\\s+|\\s+$/g, \"\"))) return true;\n this.setState(\n {\n dmacError: true,\n },\n () => {\n return false;\n }\n );\n }",
"checkRequiredFieldsFilled()\n {\n var bool = true;\n var requiredFields = this.state.textfields.filter(obj => obj.key.required === true)\n \n requiredFields.forEach(function(element) {\n if(element.value === '')\n {\n alert('Error, please fill out all required body parameters.');\n bool = false;\n }\n });\n return bool;\n }",
"function validateResponse ( packet ) {\n\tlet result = false;\n\n\t//0 0 129 128 0 1 0\n\tif (packet.length > 7 &&\n\t\tpacket[2] === 129 &&\n\t\tpacket[3] === 128 &&\n\t\tpacket[4] === 0 &&\n\t\tpacket[5] === 1 &&\n\t\tpacket[6] === 0 &&\n\t\tpacket[7] > 0\n\t) {\n\t\tresult = true;\n\t}\n\n\treturn result;\n}",
"function validateParry (data, command) {\n // no additional validation necessary\n return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a list of explanations, renders them in the explanation box | function updateExplanation(explanation) {
var update = d3.select('#explanation')
.selectAll('li')
.data(explanation);
update.text(function(d) { return d; });
update.enter()
.append('li')
.text(function(d) { return d; });
update.exit().remove();
} | [
"function questions_html(){\n let html = \"<ol>\";\n let nr = 0;\n if ( Object.keys( self.questions ).length > 0 ) for (const answers of Object.values( self.questions )){\n nr += 1;\n html += \"<li>\";\n if ( self.headers && self.headers[ nr ] ) html += \"<b>\"+ self.headers[ nr ] +\"</b>\";\n html += \"<ol type='a'>\";\n for (const answer of Object.values(answers)){\n html += \"<li>\" + answer + \"</li>\";\n }\n html += \"</ol></li>\";\n }\n html += \"</ol>\";\n return html;\n }",
"render() {\n\t\treturn (\n\t\t\t<div>\n\t\t\t\t<div style={{backgroundColor: '#DC143C', color: 'white'}}>\n\t\t\t\t\t<br />\n\t\t\t\t\t<h1 style={{display: 'flex', justifyContent: 'center'}}><u>PENDULUM</u></h1>\n\t\t\t\t\t<h3 style={{display: 'flex', justifyContent: 'center', paddingBottom: '5px'}}>Diverse stories from a partisan world</h3>\n\t\t\t\t\t<br />\n\t\t\t\t</div>\n\t\t\t\t{ this.state.suggestions.map(( info, idx ) =>\n\t\t\t\t\t<Preview key={ idx } info={ info } />\n\t\t\t\t) }\n\t\t\t</div>\n\t\t);\n\t}",
"showIngredients(ingredients) {\r\n let output = \"\";\r\n ingredients.forEach((ingredient) => {\r\n output += `<li>${ingredient.original}</li>`;\r\n });\r\n\r\n document.getElementById(\"ingredientList\").innerHTML = output;\r\n }",
"_renderInstructions(parseState: PassageParseState): React.Element<any> {\n const firstQuestionNumber = parseState.firstQuestionRef;\n const firstSentenceRef = parseState.firstSentenceRef;\n\n let instructions = \"\";\n if (firstQuestionNumber) {\n instructions += i18n._(\n \"The symbol %(questionSymbol)s indicates that question \" +\n \"%(questionNumber)s references this portion of the \" +\n \"passage.\",\n {\n questionSymbol: \"[[\" + firstQuestionNumber + \"]]\",\n questionNumber: firstQuestionNumber,\n }\n );\n }\n if (firstSentenceRef) {\n instructions += i18n._(\n \" The symbol %(sentenceSymbol)s indicates that the \" +\n \"following sentence is referenced in a question.\",\n {\n sentenceSymbol: \"[\" + firstSentenceRef + \"]\",\n }\n );\n }\n const parsedInstructions = PassageMarkdown.parse(instructions);\n return (\n <div className=\"perseus-widget-passage-instructions\">\n {PassageMarkdown.output(parsedInstructions)}\n </div>\n );\n }",
"function drawResults(obj) {\n\n //Clear the contents of contentsWrapper\n contentsWrapper.innerHTML = '';\n\n //If the object from our lookup exists, write out its properties\n if(obj) {\n for(var prop in obj) {\n if(obj.hasOwnProperty(prop)) {\n contentsWrapper.appendChild(createElementEditor(prop, obj));\n }\n }\n //Add an additional horizontal line\n contentsWrapper.appendChild($.create('hr'));\n }\n\n //Add the property adder elements\n contentsWrapper.appendChild(createElementAdder()); \n}",
"function renderDescs(parentDOM, descs, view) {\n var dom = parentDOM.firstChild, written = false;\n for (var i = 0; i < descs.length; i++) {\n var desc = descs[i], childDOM = desc.dom;\n if (childDOM.parentNode == parentDOM) {\n while (childDOM != dom) { dom = rm$2(dom); written = true; }\n dom = dom.nextSibling;\n } else {\n written = true;\n parentDOM.insertBefore(childDOM, dom);\n }\n if (desc instanceof MarkViewDesc) {\n var pos = dom ? dom.previousSibling : parentDOM.lastChild;\n renderDescs(desc.contentDOM, desc.children, view);\n dom = pos ? pos.nextSibling : parentDOM.firstChild;\n }\n }\n while (dom) { dom = rm$2(dom); written = true; }\n if (written && view.trackWrites == parentDOM) { view.trackWrites = null; }\n }",
"renderDescriptionDiv (options) {\n\t\tconst { review } = options;\n\t\treturn Utils.renderDescriptionDiv(review.text, options);\n\t}",
"addInstructionsToDisplay () {\n banner.appendChild(document.createElement('p'))\n .innerHTML = `win by guessing the phrase before losing all of your hearts`;\n }",
"function appendDemos(demos) {\n let htmlTemplate = \"\";\n for (let demo of demos) {\n console.log(demo.id);\n console.log(demo.artist);\n htmlTemplate += `\n <article>\n <h3>${demo.title}</h3>\n <p>${demo.artist}</p>\n ${demo.soundcloud}\n </article>\n `;\n }\n document.querySelector('#demos').innerHTML = '<a href=\"#home\"><img src=\"img/returnbutton2.png\" class=\"backbutton\" alt=\"backbutton\"></a>' + \"<h1>Public demos</h1>\" + \"<div class='flexContainer'>\" + htmlTemplate + \"</div>\"\n}",
"function renderAnswer(answer, correctAnswer, explanation) {\n\t\n\t// CORRECT ANSWER!\n\tif(answer == correctAnswer) {\n\t\t$(\"main\").html(`\n\t\t<section class=\"answerRightScreen\">\n\t\t\t<h1 class=\"padding-bottom-small\">Correct!</h1>\n\t\t\t<div class=\"bold underline\">The answer is:</div>\n\t\t\t<div>${correctAnswer}</div>\n\t\t\t<div>${explanation}</div>\n\t\t\t<br>\n\t\t\t<button type=\"button\" class=\"nextQuestion\">Next</button>\n\t\t</section>\n\t\t`)\n\t}\n\t// WRONG ANSWER!\n\telse {\n\t\t$(\"main\").html(`\n\t\t<section class=\"answerRightScreen\">\n\t\t\t<h1 class=\"padding-bottom-small\">Wrong answer!</h1>\n\t\t\t<div class=\"bold underline\">Your answer was:</div>\n\t\t\t<div>${answer}</div>\n\t\t\t<br>\n\t\t\t<div class=\"bold underline\">The correct answer is:</div>\n\t\t\t<div>${correctAnswer}</div>\n\t\t\t<div>${explanation}</div>\n\t\t\t<br>\n\t\t\t<button type=\"button\" class=\"nextQuestion\">Next</button>\n\t\t</section>\n\t\t`)\n\t}\n}",
"function renderHTML(listOfEmojis, ulList = ulTag){\t\n\tulList.innerHTML = \"\";\n\tlistOfEmojis.forEach((emoji) => {\n\t\tconst liTag = document.createElement(\"li\");\n\t\tconst emojiSpan = document.createElement(\"span\");\n\t\tsetTimeout(() => {\n\t\t\temojiSpan.innerHTML = emoji.char\n\t\t}, 0);\n\t\t\n\t\temojiSpan.classList.add(\"emoji\");\n\t\tliTag.appendChild(emojiSpan);\n\t\t\n\t\tconst nameSpan = document.createElement(\"span\");\n\t\tsetTimeout(() => {\t\t\n\t\t\tnameSpan.innerHTML = emoji.name;\n\t\t}, 0);\n\t\tnameSpan.classList.add(\"emojiName\");\t\t\n\t\tliTag.appendChild(nameSpan);\n\t\t\t\n\t\t\n\t\t\n\t\t//save to clipboard\n\t\tliTag.addEventListener('click', () => {\n\t\t\temojiClickEventHandler(emoji);\n\t\t})\n\n\t\tulList.appendChild(liTag);\n\t})\n}",
"function createChallengeView(challenge, i) {\n return `<div class=\"column\">\n <h2><b><font color='#7A7A7A'>${challenge.title}</font></b></h2>\n\n <p><b>Description:</b> ${challenge.description}</p>\n\n\n <p><b>Participants:</b> ${challenge.participantNames.join(\", \")}</p>\n\n\n <p><b>Check in: </b> every day by ${challenge.checkInDeadline}</p>\n\n\n <p><b>Cost: </b> ${challenge.cost} Accounta-bux</p>\n\n\n </div>`;\n}",
"displayDificalty(diff) {\n difficulty = diff;\n textSize(15);\n if (difficulty == 5) {\n text(\"Inside joke:\", 19, 273);\n } else if (difficulty == 4) {\n text(\"Phrase:\", 19, 273);\n\n } else if (difficulty == 2) {\n text(\"Moderate phrase:\", 19, 273);\n\n } else if (difficulty == 3) {\n text(\"Hard phrase:\", 19, 273);\n\n } else if (difficulty == 1) {\n text(\"Easy phrase:\", 19, 273);\n } else {\n text(\"Your phrase:\", 19, 273);\n }\n }",
"function updateExamplePositionText() {\n var data = {\n currentExample: nextExample_ + 1,\n totalExamples: examples_.length,\n };\n var format = gettext('Example %(currentExample)s of %(totalExamples)s');\n var string = interpolate(format, data, true);\n document.getElementById('example-counter').textContent = string;\n}",
"function helperFreeText(results) {\n var $responses = $('#helperResponses');\n var content = '';\n for (var i = 0, l = results.length; i<l; i++) {\n var helperResponses = results[i].responses[3];\n content += row(helperResponses);\n }\n $responses.append(content);\n }",
"function createDisplayAnswers() {\r\n\tvar correctPlace = getCorrectPlace();\r\n\tanswers[correctPlace[0]].innerHTML = question[0] + question[1];\r\n\tanswers[correctPlace[1]].innerHTML = Math.floor(Math.random() * 100) + Math.floor(Math.random() * 100);\r\n}",
"render(){\n return(\n <div className=\"container-fluid d:flex\" id=\"main\">\n \n <div id=\"textAreaContainer\">\n <h3 id=\"editor-head\">Markdown Editor</h3>\n <textarea className=\"bg-dark \" id=\"editor\" value={this.state.input} onChange={this.handleChange}/>\n </div>\n\n <div id=\"previewContainer\">\n <h3 id=\"preview-head\">Markdown preview</h3>\n <div id=\"preview\" dangerouslySetInnerHTML={{__html:marked(this.state.input,{breaks:true})}}>\n </div>\n </div>\n\n </div>\n );\n }",
"makeTextToPreviewDiffs() {\n if (editorSvc.sectionDescList &&\n editorSvc.sectionDescList !== editorSvc.sectionDescWithDiffsList\n ) {\n const makeOne = () => {\n let hasOne = false;\n const hasMore = editorSvc.sectionDescList\n .some((sectionDesc) => {\n if (!sectionDesc.textToPreviewDiffs) {\n if (hasOne) {\n return true;\n }\n if (!sectionDesc.previewText) {\n sectionDesc.previewText = sectionDesc.previewElt.textContent;\n }\n sectionDesc.textToPreviewDiffs = diffMatchPatch.diff_main(\n sectionDesc.section.text, sectionDesc.previewText);\n hasOne = true;\n }\n return false;\n });\n if (hasMore) {\n setTimeout(() => makeOne(), 10);\n } else {\n editorSvc.previewTextWithDiffsList = editorSvc.previewText;\n editorSvc.sectionDescWithDiffsList = editorSvc.sectionDescList;\n editorSvc.$emit('sectionDescWithDiffsList', editorSvc.sectionDescWithDiffsList);\n }\n };\n makeOne();\n }\n }",
"function showDescriptionTemplate(body) {\n\t\t\tvar description = buildDescription();\n\t\t\tdescription.title = '';\n\t\t\tdescription.subtitle = '';\n\t\t\tdescription.items.forEach(function(item) {\n\t\t\t\titem.title = '';\n\t\t\t\titem.description = '';\n\t\t\t});\n\n\t\t\tcleanUpPage(body);\n\t\t\tvar header = createAddElement('p', body);\n\t\t\theader.innerHTML = 'This is a template for ' + options.descriptionFile + ' file. <a href=\"?\">Go to gallery content</a>';\n\t\t\tvar textArea = createAddElement('textarea', body, {\n\t\t\t\trows: 30,\n\t\t\t\tcols: 90\n\t\t\t});\n\t\t\ttextArea.value = JSON.stringify(description, null, 4);\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
1. lookup division type def 2. create n number of subdivisions of that type as contents of dividing element 3. optional could be to update the duration of the top level... or maybe it makes sense to create the measures first before creating the staves but if the score is proportional notation, it doesn't matter what the beats are | createSubdivisions(dataset)
{
console.log('createSubdivisions', dataset);
let target = document.getElementById(dataset.target);
// could evaluate function for the tree here
let treeStr = dataset.division_tree;
let tree;
if( treeStr.indexOf("x") != -1 )
{
let multTreeStr = treeStr.split("x");
let mult = parseFloat(multTreeStr[1]);
let base = parseFloat(multTreeStr[0]);
tree = [];
for( let i = 0; i < mult; i++)
{
tree.push(base);
}
}
else
{
tree = JSON.parse(`[${dataset.division_tree}]`);
}
let dur = parseFloat(dataset.element_duration);
let element_time = parseFloat(dataset.element_time);
// console.log(tree, dur, time);
let incr = dur / tree.length;
let divisions = [];
let dividerDef = ui_api.getDef(dataset.marker_type);
// console.log(dividerDef, dataset.marker_type);
// for better resolution, we could store the ratio in the measure, probably better
for( let i = 0; i < tree.length; i++ )
{
dividerDef.fromData({
id: `${dividerDef.class}_u_${ui_api.fairlyUniqueString()}`,
container: target.id,
time: element_time + incr * i,
duration: incr
// default barlineType
}, target );
}
// console.log(divisions);
} | [
"function createMeasureDIV(measure) {\n var positionArray = tixlb[measure];\n var line = positionArray[0];\n var bar = positionArray[1];\n //var measure_width = bars[line].xs[bar] - bars[line].xs[bar-1];\n //var measure_height = bars[line].ys[bar] ;\n\n var coord = getCoordforMeasure(measure);\n\n var cursor = WijzerDIV(measure, line, coord.x, coord.y, coord.width, coord.height);\n var score = $('#notation');\n $(\"#\" + ANNO_ID + measure).remove(); // remove old\n $(cursor).prependTo(score);\n return cursor;\n\n}",
"function renderStats() {\n let stimulant = 0;\n let sedative = 0;\n let hallucinogic = 0;\n let delirant = 0;\n let dissociative = 0;\n let depressant = 0;\n for(substance in selectedSubstances) {\n let substanceAmount = selectedSubstances[substance];\n let substanceConfig = SUBSTANCES[substance];\n power = limitRange(Math.floor(substanceAmount / 2), 1, 5);\n if(substanceConfig.stats.stimulant) {\n stimulant += power;\n }\n if(substanceConfig.stats.sedative) {\n sedative += power;\n }\n if(substanceConfig.stats.hallucinogic) {\n hallucinogic += power;\n }\n if(substanceConfig.stats.delirant) {\n delirant += power;\n }\n if(substanceConfig.stats.dissociative) {\n dissociative += power;\n }\n if(substanceConfig.stats.depressant) {\n depressant += power;\n }\n }\n if(stimulant > 5) stimulant = 5;\n if(sedative > 5) sedative = 5;\n if(hallucinogic > 5) hallucinogic = 5;\n if(delirant > 5) delirant = 5;\n if(dissociative > 5) dissociative = 5;\n if(depressant > 5) depressant = 5;\n\n stimulantData = STATS_LEVELS[stimulant];\n sedativeData = STATS_LEVELS[sedative];\n hallucinogicData = STATS_LEVELS[hallucinogic];\n delirantData = STATS_LEVELS[delirant];\n dissociativeData = STATS_LEVELS[dissociative];\n depressantData = STATS_LEVELS[depressant];\n renderStat('stimulant', stimulantData.value, stimulantData.name, stimulantData.class);\n renderStat('sedative', sedativeData.value, sedativeData.name, sedativeData.class);\n renderStat('hallucinogic', hallucinogicData.value, hallucinogicData.name, hallucinogicData.class);\n renderStat('delirant', delirantData.value, delirantData.name, delirantData.class);\n renderStat('dissociative', dissociativeData.value, dissociativeData.name, dissociativeData.class);\n renderStat('depressant', depressantData.value, depressantData.name, depressantData.class);\n}",
"function test39() {\t\n\t// Example where N is 3 and M is not specified.\n\t\n\t// Universe M Universe of N dimensions \n\t// / \\ ... other dimensions ...\n\t// 1 8 dimension 1 has Two measurements [1, 8]\n\t// / \\ / \\ ... other dimensions ...\n\t// 2 3 9 10 dimension 2 has Four measurements [ [2, 3] [9, 10] ] \n\t// /\\ /\\ /\\ /\\ ... other dimensions ... \n\t// 4 5 6 7 11 12 13 14 dimension 3 has Eight measurements [ [ [4,5] [6, 7] ] [ [11, 12] [13, 14] ] ]\n\t\n\t// This tree has been copyrighted, just kidding.\n\t//\n\n\t// *****First measurments** ***** Last measurements**** \n\t// hop1[0] == 1 hop1[1] == 8\n\t// hop2[0][0] == 2 hop2[1][1] == 10\n\t// hop3[0][0][0] == 4 hop3[1][1][1] == 14\n\t\n\t// treeGator = new TreeGator([hop1, hop2, hop3])\n\t// measure(treeGator[0][0]) == 1\n\t// measure(treeGator[1][0][0]) == 2\n\t// measure(treeGator[2][0][0][0]) == 4\n var div = document.createElement('div');\n div.innerHTML =\t\"<div>Universe M\" + \n\t\" <otherdimension1>\" + \n\t\" <dimension1>1 \" + \n\t\" <otherdimension2>\" + \n\t\"\t <dimension2>2 \" + \n\t\"\t <otherdimension3>\" + \n\t\"\t\t <dimension3>4</dimension3> \" + \n\t\"\t\t <dimension3>5</dimension3>\" + \n\t\"\t\t </otherdimension3>\" + \n\t\"\t\t </dimension2> \" + \n\t\"\t <dimension2>3\" + \n\t\"\t <otherdimension4>\" + \n\t\"\t\t <span dizid=dimension3>6</span>\" + \n\t\"\t\t <span dizid=dimension3>7</span>\" + \n\t\"\t\t </otherdimension4>\" + \n\t\"\t </dimension2>\" + \n\t\"\t </otherdimension2>\" + \n\t\" </dimension1>\" + \n\t\" <dimension1>8 \" + \n\t\"\t <dimension2>9 \" + \n\t\"\t\t <dimension3>11</dimension3> \" + \n\t\"\t\t <dimension3>12</dimension3></dimension2> \" + \n\t\"\t <dimension2>10\" + \n\t\"\t\t <dimension3>13</dimension3>\" + \n\t\"\t\t <dimension3>14</dimension3>\" + \n\t\"\t </dimension2>\" + \n\t\" </dimension1>\" + \n\t\" </otherdimension1>\" + \n\t\"</div>\";\n\tconsole.log(div.innerText); \n\tvar measure = (node) => {\n\t\t const nodes = Array.from(node.childNodes).filter(f => f.nodeName === '#text');\n\t\t return nodes.length ? nodes[0].textContent.trim() : '';\n\t\t}\n var hop1 = new Hop38(div , \"dimension1\",\"dimension1\");\n var hop2 = new Hop38(hop1.html, \"dimension2\",\"dimension2\");\n var hop3 = new Hop38(hop2.html, \"dimension3\",\"dimension3\");\n // *******FIRST MEASUREMENT ************** *******LAST MEASUREMENT ************** \n expect(measure(hop1.html[0])) .toEqual( \"1\" ); expect(measure(hop1.html[1])).toEqual ( \"8\" ); \n expect(measure(hop2.html[0][0])) .toEqual( \"2\" ); expect(measure(hop2.html[1][1])).toEqual ( \"10\" ); \n expect(measure(hop3.html[0][0][0])).toEqual( \"4\" ); expect(measure(hop3.html[1][1][1])).toEqual ( \"14\" ); \n \n // test 40: Can we measure the bottom row?\n //expect(hop3.flatHtml.map(measure).toEqual( [ \"4\", \"5\", '6', '7', '11', '12', '13', '14' ] ); \n\t\n}",
"function Waveform2Score(wave_start, wave_end, measure_start, measure_end) {\n var wavesegment_options = {\n container: '#waveform',\n waveColor: '#dddddd',\n progressColor: '#3498db',\n loaderColor: 'purple',\n cursorColor: '#e67e22',\n cursorWidth: 1,\n selectionColor: '#d0e9c6',\n backend: 'WebAudio',\n normalize: true,\n loopSelection: false,\n renderer: 'Canvas',\n partialRender: true,\n waveSegmentRenderer: 'Canvas',\n waveSegmentHeight: 50,\n height: 100,\n barWidth: 2,\n plotTimeEnd: wavesurfer.backend.getDuration(),\n wavesurfer: wavesurfer,\n ELAN: elan,\n wavesSegmentsArray,\n scrollParent: false\n };\n\n var measure_duration = (wave_end - wave_start) / (measure_end - measure_start);\n\n for (var i = measure_start; i < measure_end; i++) {\n var msr = createMeasureDIV(i);\n var rect = msr.getBoundingClientRect();\n\n var waveSegmentPos = {\n left: rect.left + \"px\",\n top: rect.top + \"px\",\n width: rect.width,\n container: msr.getAttribute('id')\n }\n\n\n wavesSegmentsArray.push(waveSegmentPos);\n\n var repris = tixlb[i][2];\n var bpm = (60 / measure_duration) * tixbts[i - 1];\n console.log(\"tixbts:\" + tixbts[i - 1]);\n elan.addAnnotation(ANNO_ID + i, wave_start + (i - measure_start) * measure_duration,\n wave_start + (i - measure_start + 1) * measure_duration,\n \"Bar \" + i + \" Rep \" + repris,\n \"BPM: \" + bpm);\n\n\n }\n elanWaveSegment.init(wavesegment_options);\n highlightSelectedDIVs();\n\n}",
"function normalizeMeasures(part) {\n const measuresLengths = part.measures.map(a => a.beat.length);\n console.log(\"12121212121212122\", measuresLengths);\n const lcmOfBeatLength = Util.lcm(...measuresLengths);\n // 1.转换成对0 2.把track内所有小节beat统一长度\n\n // 不能用foreach,foreach会直接bypass掉empty的(稀疏数组遍历)\n // part.measures.forEach((measure, measureIndex) => {});\n for (\n let measureIndex = 0;\n measureIndex <= part.measures.length - 1;\n measureIndex += 1\n ) {\n // console.log(\"measure::::::::::\", part.measures[measureIndex]);\n if (!part.measures[measureIndex]) {\n //建一个空小节\n //potential bug here\n part.measures[measureIndex] = {\n measure: measureIndex + 1,\n sequence: \"\",\n beat: Util.createUnderScores(lcmOfBeatLength),\n matchZero: true\n };\n } else {\n // 对位处理成对0\n if (!part.measures[measureIndex].matchZero) {\n // 对位转成对0,抽出对应的音//potential bug here, super mario....seemingly solved\n // const sequenceArray = JSON.parse(\n // `[${part.measures[measureIndex].sequence}]`.replace(\n // /([ABCDEFG]#*b*[1-9])/g,\n // '\"$1\"'\n // )\n // );\n let newSeqArray = part.measures[measureIndex].beat\n .split(\"\")\n .map((beatDigit, index) => {\n if (beatDigit.match(/\\d/g)) {\n return part.measures[measureIndex].sequence[index];\n } else {\n return \"\";\n }\n });\n newSeqArray = newSeqArray.filter(seq => !!seq); // 排掉空的\n console.log(\"bbbbbbbbbbb\", newSeqArray);\n\n // TO FIX HERE!!!\n // let s = JSON.stringify(newSeqArray.filter(note => note != \"\")).replace(\n // /\"/g,\n // \"\"\n // );\n // s = s.substring(1, s.length - 1); // 去掉数组的前后方括号\n // part.measures[measureIndex].sequence = s;\n part.measures[measureIndex].sequence = newSeqArray;\n part.measures[measureIndex].matchZero = true;\n }\n // console.log(\"jjjjjjjjjjjjjj\", part.measures[measureIndex].sequence);\n //对0的,beat延展就行了,原来000的可能变成0--0--0-- (根据最小公倍数)\n if (part.measures[measureIndex].beat.length < lcmOfBeatLength) {\n const ratio = lcmOfBeatLength / part.measures[measureIndex].beat.length;\n // console.log(\"[][][]\");\n // console.log(lcmOfBeatLength);\n // console.log(part.measures[measureIndex].beat.length);\n const append = Util.createScores(ratio - 1);\n part.measures[measureIndex].beat = part.measures[measureIndex].beat\n .split(\"\")\n .join(append);\n part.measures[measureIndex].beat += append;\n }\n }\n }\n\n console.log(\"=== measure after normalization===\");\n console.log(part.measures);\n\n //把所有measure合成一大段 应了老话「不要看小节线」\n part.tonepart = part.measures.reduce((a, b) => {\n // console.log(\"?\", a.sequence);\n return {\n // potential bug: if a/b is empty string, no comma here, seemingly solved\n // sequence: `${a.sequence}${a.sequence && b.sequence ? \",\" : \"\"}${\n // b.sequence\n // }`,\n sequence: a.sequence.concat(b.sequence),\n beat: `${a.beat}${b.beat}`\n };\n });\n console.log(\"=== final part in this part ===\");\n console.log(part.tonepart);\n}",
"function subdivide(tri, nLevels) {\n var a = tri[0];\n var b = tri[1];\n var c = tri[2];\n\n if (--nLevels < 0) {\n renderTriangle( [ inflate(a), inflate(b), inflate(c) ]);\n }else{\n var d = midpoint(a, b);\n var e = midpoint(b, c);\n var f = midpoint(c, a);\n\n subdivide([a,d,f], nLevels);\n subdivide([d,b,e], nLevels);\n subdivide([c,f,e], nLevels);\n subdivide([d,e,f], nLevels);\n }\n}",
"calculatePeriods() {\n\n // go through all jobs and generate compound child elements\n let chart = get(this, 'chart'),\n childs = get(this, 'childLines'),\n start = get(this, 'parentLine._start'),\n end = get(this, 'parentLine._end')\n\n // generate period segments\n let periods = dateUtil.mergeTimePeriods(childs, start, end);\n\n // calculate width of segments\n if (periods && periods.length > 0) {\n periods.forEach(period => {\n period.width = chart.dateToOffset(period.dateEnd, period.dateStart, true);\n period.background = this.getBackgroundStyle(period.childs);\n period.style = htmlSafe(`width:${period.width}px;background:${period.background};`);\n });\n }\n\n set(this, 'periods', periods);\n }",
"function Division() {\n\tthis.minCells = 2 // Can operate on a minimum of 2 cells\n\tthis.maxCells = 2 // Can operate on a maximum of 2 cells\n\tthis.symbol = '÷'\n}",
"function kata21(smplArr){\n let newElement = document.createElement(\"section\");\n newElement.setAttribute(\"id\", \"section3\");\n let headingElement= document.createElement(\"h1\");\n headingElement.className = \"subHeadingClass\";\n headingElement.appendChild(document.createTextNode(\"21--Display 20 solid gray rectangles, each 20px high, with widths in pixels given by the 20 elements of sampleArray.\"));\n \n var destination = document.getElementById(\"mainSection\");\n destination.appendChild(headingElement);\n destination.appendChild(newElement);\n \n destination = document.getElementById(\"section3\");\n let widthDiv;\n for (i=0;i<20;i++){\n let newElement1 = document.createElement(\"div\");\n let newElement2 = document.createElement(\"div\");\n widthDiv=smplArr[i];\n newElement1.style.width = widthDiv+'px';\n newElement1.className = \"drawRect1\";\n newElement2.className=\"spaceClass\";\n destination.appendChild(newElement1);\n destination.appendChild(newElement2);\n }\n \n}",
"function kata20(){\n let newElement = document.createElement(\"section\");\n newElement.setAttribute(\"id\", \"section2\");\n let headingElement= document.createElement(\"h1\");\n headingElement.className = \"subHeadingClass\";\n headingElement.appendChild(document.createTextNode(\"20--Display 20 solid gray rectangles, each 20px high, with widths ranging evenly from 105px to 200px (remember #4, above).\"));\n \n var destination = document.getElementById(\"mainSection\");\n destination.appendChild(headingElement);\n destination.appendChild(newElement);\n \n destination = document.getElementById(\"section2\");\n let widthDiv=105;\n for (i=0;i<20;i++){\n let newElement1 = document.createElement(\"div\");\n let newElement2 = document.createElement(\"div\");\n newElement1.style.width = widthDiv+'px';\n widthDiv+=5;\n newElement1.className = \"drawRect1\";\n newElement2.className=\"spaceClass\";\n destination.appendChild(newElement1);\n destination.appendChild(newElement2);\n }\n \n}",
"function buildRegularSets(dataset, type, dataArray) {\n //let dataArray = generateEmptySetArray();\n dataset.point.forEach((pt) => {\n //Determine the day of week activity was completed - based on end time\n let day = new Date(pt.endTimeNanos / 1000000).getDay();\n let value = pt.value[0].intVal || pt.value[0].fpVal;\n let index = dataArray.findIndex((entry) => entry.day === day);\n //Add value to array - average if speed\n //Note: average is simplified here - for more accuracy it should be\n //a weighted average\n if (type === 'speed') {\n dataArray[index].value += value;\n dataArray[index].value /= 2;\n }\n else {\n dataArray[index].value += value;\n }\n });\n return dataArray;\n}",
"function _updateDurationSettings() {\n durationPerMeasure = divisions * (4 / beatType) * beats;\n }",
"split_() {\n let nextLevel = this.level_ + 1;\n let subWidth = Math.round(this.bounds_.width / 2);\n let subHeight = Math.round(this.bounds_.height / 2);\n let x = Math.round(this.bounds_.x);\n let y = Math.round(this.bounds_.y);\n\n //top right node\n this.nodes_[0] = new Quadtree(new Rectangle(\n x + subWidth,\n y,\n subWidth,\n subHeight\n ), this.maxObjects_, this.maxLevel_, nextLevel);\n\n //top left node\n this.nodes_[1] = new Quadtree(new Rectangle(\n x,\n y,\n subWidth,\n subHeight\n ), this.maxObjects_, this.maxLevel_, nextLevel);\n\n //bottom left node\n this.nodes_[2] = new Quadtree(new Rectangle(\n x,\n y + subHeight,\n subWidth,\n subHeight\n ), this.maxObjects_, this.maxLevel_, nextLevel);\n\n //bottom right node\n this.nodes_[3] = new Quadtree(new Rectangle(\n x + subWidth,\n y + subHeight,\n subWidth,\n subHeight\n ), this.maxObjects_, this.maxLevel_, nextLevel);\n\n }",
"calcTime() {\n const numIng = this.ingredients.length;\n const periods = Math.ceil(numIng/3);\n this.time = periods * 15;\n }",
"newMeasure() {\r\n let measures = this.score.measures;\r\n if(measures[measures.length-1].notes.length > 1) {\r\n measures[measures.length-1].notes.pop();\r\n measures.push(\r\n {\r\n 'attributes': {\r\n repeat: {\r\n left: false,\r\n right: false\r\n }\r\n },\r\n 'notes':[\r\n {'type' : 'input'}\r\n ]\r\n });\r\n }\r\n }",
"get subdivision() {\n return new _Ticks.TicksClass(this.context, this._subdivision).toSeconds();\n }",
"partitionAnalysis() {\n this.setWaypointFields();\n this.partSizes();\n this.calculatePartBdryStats();\n }",
"function parseVariableLengthMeasure(ai_stem, fourthNumber, title, unit) {\r\n // the place of the decimal fraction is given by the fourth number, that's\r\n // the first after the identifier itself.\r\n elementToReturn = new ParsedElement(ai_stem + fourthNumber, title, \"N\");\r\n var offSet = ai_stem.length + 1,\r\n posOfFNC = codestring.indexOf(fncChar),\r\n numberOfDecimals = parseInt(fourthNumber, 10),\r\n numberPart = \"\";\r\n\r\n if (posOfFNC === -1) {\r\n numberPart = codestring.slice(offSet, codestringLength);\r\n elementToReturn.raw = codestring.slice(offSet);\r\n codestringToReturn = \"\";\r\n } else {\r\n numberPart = codestring.slice(offSet, posOfFNC);\r\n codestringToReturn = codestring.slice(posOfFNC + 1, codestringLength);\r\n elementToReturn.raw = codestring.slice(offSet, posOfFNC);\r\n }\r\n // adjust decimals according to fourthNumber:\r\n\r\n elementToReturn.data = parseFloatingPoint(numberPart, numberOfDecimals);\r\n elementToReturn.unit = unit;\r\n }",
"dividePostIds(postIds, posts, numDivs, hasNext) {\n if(numDivs <= 0) {\n return [];\n }\n\n let oldPostIds = clone(postIds);\n let portraitPostIds = [];\n let dividedPostIds = createFixedArray([], numDivs);\n let heights = createFixedArray(0, numDivs);\n let needPush = createFixedArray(true, numDivs);\n let curIndex = 0;\n let heightest = 0;\n\n // Find all portrait posts.\n oldPostIds.forEach((id) => {\n if(this.isPortrait(posts[id])) {\n portraitPostIds.push(id);\n }\n });\n // Handling for there is a \"single\" portrait post.\n if(portraitPostIds.length % 2 === 1) {\n // If there are still posts to load, do not show it at this time;\n // otherwise, place it at the last position.\n const lastPortraitPostId = portraitPostIds.pop();\n oldPostIds.splice(oldPostIds.indexOf(lastPortraitPostId), 1);\n if(!hasNext) {\n oldPostIds.push(lastPortraitPostId);\n portraitPostIds.push(lastPortraitPostId);\n }\n }\n\n // Start to divide post IDs.\n while(oldPostIds.length > 0) {\n if(needPush[curIndex]) {\n const postId = oldPostIds.shift();\n if(!this.isPortrait(posts[postId])) {\n // For landscape post, just push it to current division.\n dividedPostIds[curIndex].push(postId);\n heights[curIndex] += 1;\n } else {\n portraitPostIds.shift();\n if(portraitPostIds.length > 0) {\n // For portrait post, push it and next portrait post (if existed) as peer to current division.\n const peerPostId = portraitPostIds.shift();\n oldPostIds.splice(oldPostIds.indexOf(peerPostId), 1);\n dividedPostIds[curIndex].push(postId);\n dividedPostIds[curIndex].push(peerPostId);\n heights[curIndex] += 2;\n } else {\n if(!hasNext) {\n // If no peer portrait post and no next posts to load,\n // the single portrait post will be at last position,\n // just push it.\n dividedPostIds[curIndex].push(postId);\n }\n }\n }\n // Update heightest.\n heightest = (heightest < heights[curIndex]) ? heights[curIndex] : heightest;\n }\n\n if(curIndex < numDivs - 1) {\n // Not the end of a loop, just increase index.\n curIndex++;\n } else {\n // The end of a loop, update \"needPush\" array and reset index, heightest.\n let allHeightsEqual = true;\n for(let i = 0; i < numDivs - 1;i++) {\n if(heights[i] != heights[i + 1]) {\n allHeightsEqual = false;\n break;\n }\n }\n if(allHeightsEqual) {\n needPush = createFixedArray(true, numDivs);\n } else {\n needPush = heights.map((height) => {\n return (height === heightest) ? false : true;\n });\n }\n curIndex = 0;\n heightest = 0;\n }\n }\n\n return dividedPostIds;\n }",
"function partition(data, n) {\n\t\t\treturn _.chain(data).groupBy(function (element, index) {\n\t\t\t\treturn Math.floor(index / n);\n\t\t\t}).toArray().value();\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Nth cataln number Cn = 1/n+1 2nCn | function catalan(n) {
let c = combination(2 * n, n);
return Math.floor(c / (n + 1));
} | [
"function c(N, K) {\n var C = [];\n for (let n=0; n<=N; n++) {\n C[n] = [1]\n C[0][n] = 0\n }\n for (let n=1; n<=N; n++) {\n for (let k=1; k<=N; k++) {\n let k0 = (k <= n-k) ? k : n-k\n if (n < k)\n C[n][k] = 0\n else if (n===k)\n C[n][k] = 1\n else\n C[n][k] = C[n][n-k] = C[n-1][k0-1] + C[n-1][k0]\n }\n }\n /*\n for(let n=0; n<=N; n++) {\n console.log(\"C[%d]=%j\", n, C[n])\n }\n */\n return C[N][K];\n}",
"diagnum(n) {\n\t\t\treturn n * (n + 3) / 2;\n\t\t}",
"function CByte(n) {\n var i=n*1;\n i=Math.round(i);\n //odd numbers round up if .5, even numbers don't\n if (i%2 != 0) {\n var j=Math.abs(n-i);\n if (j==.5) {i-=1;}\n }\n return i;\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 faculteit(n) {\n\n}",
"function getNthUglyNo(n)\n {\n return findUgly(n, 1, 1);\n }",
"function alwaysOne(n){\n while(n > 1){\n if(n % 2 === 0){\n n = n/2;\n }else{\n n = (n*3)+1;\n }\n }\n return(n)\n}",
"printPascal2 ( n) {\n for (let line = 1; line <= n; line++)\n {\n let C = 1; // used to represent C(line, i)\n\n let str = \" \";\n for (let i = 1; i <= line; i++)\n {\n str += C + \" \";\n // The first value in a line is always 1\n C = C * (line - i) / i;\n }\n console.log(str);\n }\n }",
"function nines(n) {\n let g = n => n == 1 ? 1n : 10n**(--n) + 9n*g(n);\n if (n < 10n) return n == 9 ? 1n : 0n\n let s = n.toString(), h = BigInt(s[0]), t = BigInt(s.slice(1)), a = BigInt(s.length-1),\n r = h == 9 ? t + 1n : nines(t)\n return h * g(a) + r\n}",
"function nbDig(n, d) {\n let res = 0;\n for (let g = 0; g <= n; g++) {\n let square = (g * g + \"\").split(\"\");\n square.forEach((s) => s == d ? res++ : null)\n } return res;\n}",
"getCategoryIndex(cs, ss) {\n let v, i, o, s = 1 << cs[0] | 1 << cs[1] | 1 << cs[2] | 1 << cs[3] | 1 << cs[4];\n for (i = -1, v = o = 0; i < 5; i++, o = Math.pow(2, cs[i] * 4)) {\n v += o * ((v / o & 15) + 1);\n }\n v = v % 15 - ((s / (s & -s) == 31) || (s == 0x403c) ? 3 : 1);\n v -= Number(ss[0] == (ss[1] | ss[2] | ss[3] | ss[4])) * ((s == 0x7c00) ? -5 : 1);\n return v;\n }",
"function calcCNS(pO2, time)\n{\n var percentCNS = Array(0.12, 0.14, 0.18, 0.22, 0.28, 0.33, 0.42, 0.48, 0.56, 0.67, 0.83, 2.22, 10.0, 50.0); // 0.5 - 1.8 ATA PO2\n\n if (pO2 < 0.5)\n return(0.0);\n else if (pO2 > 1.8)\n return(100.0);\n else\n return(time * percentCNS[((pO2.toFixed(1) - 0.5) * 10).toFixed()]);\n}",
"function faktorial(n)\r\n{\r\n\tif (n == 0) return 1\r\n\treturn n * faktorial( n - 1 ) // 5 * ( 4 * ( 3 * ( 2 * ( 1 ) ) ) )\r\n}",
"function collatz(n){\n var result = [n]\n var resultString = '' + n + '-> '\n console.log(resultString)\n while (result[result.length-1] > 1){\n if ( result[result.length-1]%2 !== 0){\n result.push((result[result.length-1]*3)+1)\n resultString += ((result[result.length-1]*3)+1) + '->'\n console.log(resultString)\n } else {\n result.push(result[result.length-1]/2)\n resultString+= (result[result.length-1]/2) +'->'\n }\n// console.log(result)\n// console.log(resultString)\n }\n return result.toString().replace(/,/g, '->')\n}",
"function CSng(num) {\n var dec=7;\n var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);\n return result;\n}",
"function perimeter(n) {\n let total = 0;\n let first = 1;\n let second = 1;\n let third;\n for (let i = 0; i <= n; i++) {\n third = first + second;\n total += first;\n\n first = second;\n second = third;\n \n }\n return (total) * 4;\n}",
"function CCur(num) {\n var dec=4;\n var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);\n return result;\n}",
"function recursiveNthFib(n) {\n // initialization a cache array with a lenght of n\n const cache = Array(n); // cache.length returns n\n\n // define a recursive helper function\n function recursiveHelper(n) {\n // try to access the answer from the cache\n let answer = cache(n);\n\n if (!answer) {\n answer = naiveNthFib(n);\n // save this answer in our cache\n cache(n) = answer;\n }\n\n return answer;\n }\n // don't foget to call the recursiveHelper\n}",
"function collatzSequenceLength(n) {\n let len = 0;\n for (let n1 of collatzSequence(n)) len++;\n return len;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Conversion time from DEGREE fromat to H:M:S:MS format time output time_deg input time in range 0 deg to 360 deg where 0 deg = 0:00 AM and 360 deg = 12:00 PM | SetDegTime(time_deg)
{
var time_hr = 0.0;
time_deg = GCMath.putIn360(time_deg);
// hour
time_hr = time_deg / 360 * 24;
this.hour = parseInt( Math.floor(time_hr));
// minute
time_hr -= hour;
time_hr *= 60;
this.min = parseInt( Math.floor(time_hr));
// second
time_hr -= min;
time_hr *= 60;
this.sec = parseInt( Math.floor(time_hr));
// miliseconds
time_hr -= sec;
time_hr *= 1000;
this.mili = parseInt( Math.floor(time_hr));
} | [
"function getTime(time) {\n var tempTime;\n tempTime = replaceAt(time, 2, \"h\");\n tempTime = replaceAt(tempTime, 5, \"m\");\n tempTime += \"s\";\n return tempTime;\n }",
"function hmsToDegrees(h, m, s) {\n\t//1 hour = 15 degrees\n\t//1 minute = 1/4 degree\n\t//1 second = 1/240 degree\n\treturn h*15 + m/4 + s/240; \n}",
"function minutesToTime(m) {\n var minutes = (m + 4 * 60) % 1440;\n var hh = Math.floor(minutes / 60);\n var ampm;\n if (hh > 12) {\n hh = hh - 12;\n ampm = \"pm\";\n } else if (hh == 12) {\n ampm = \"pm\";\n } else if (hh == 0) {\n hh = 12;\n ampm = \"am\";\n } else {\n ampm = \"am\";\n }\n var mm = minutes % 60;\n if (mm < 10) {\n mm = \"0\" + mm;\n }\n\n return hh + \":\" + mm + ampm\n}",
"function timeConvert(times){\n let hours = 0;\n let minutes = 0;\n times.forEach(function(i){\n var timeSplit = i.split(':');\n let newHr = Number(timeSplit[0]);\n hours += newHr;\n let newMin = Number(timeSplit[1]);\n minutes += newMin;\n });\n let minuteOfHour = Math.floor(minutes / 60);\n let minutesLeft = minutes % 60;\n hours += minuteOfHour;\n const totalTime = hours +':'+ minutesLeft;\n return totalTime;\n}",
"function WhatIsTheTime(timeInMirror){\n\n let mir = timeInMirror.split(':')\n let hour = parseFloat(mir[0])\n let min = parseFloat(mir[1])\n let realHour = 11 - hour\n let realMin = 60 - min\n let realTime\n\n //conditionals if mirrored time hour is 11 or 12 because formula doesn't apply\n if (hour ===12){\n realHour = 11\n }\n else if (hour ===11){\n realHour = 12\n }\n\n //for x:00 times, display mirrored hour rather than i.e 7:60\n if(realMin === 60){\n realHour += 1\n realMin = 0\n }\n\n //single digit times need to concatonate 0 when converted back to string\n if(realHour.toString().length===1){\n realHour = '0'+realHour\n }\n if(realMin.toString().length===1){\n realMin = '0'+realMin\n }\n\n //if 6PM, or 12PM -> realTime is the same, else realTime = realHour + realMin based on calculations\n if (timeInMirror===\"06:00\" || timeInMirror===\"12:00\"){\n realTime = timeInMirror\n } else {\n realTime = realHour + ':' + realMin\n }\n\n return realTime\n}",
"function getDuration(time) {\n var minutes = Math.floor(time / 60000);\n var seconds = ((time % 60000) / 1000).toFixed(0);\n if (seconds < 10) {\n seconds = '0' + seconds;\n }\n return minutes + \":\" + seconds;\n}",
"function CnvToTime(seconds, TimeFormat) {\n\n //alert(milliseconds);\n\n var h = Math.floor(seconds / 3600);\n\n seconds = seconds - h * 3600;\n\n var m = Math.floor(seconds / 60);\n\n seconds = seconds - m * 60;\n\n var s = Math.floor(seconds);\n\n seconds = seconds - s;\n\n if (TimeFormat == 'PAL') {\n var f = Math.floor((seconds * 1000) / 40);\n }\n else if (TimeFormat == 'NTSC') {\n var f = Math.floor((seconds * 1000) / (100 / 3));\n }\n else if (TimeFormat == 'PALp') {\n var f = Math.floor((seconds * 1000) / 20);\n }\n else if (TimeFormat == 'STANDARD') {\n var f = Math.floor(seconds * 1000);\n }\n\n // Check if we need to show hours\n h = (h < 10) ? (\"0\" + h) + \":\" : h + \":\";\n\n // If hours are showing, we may need to add a leading zero.\n // Always show at least one digit of minutes.\n m = (((h) && m < 10) ? \"0\" + m : m) + \":\";\n\n // Check if leading zero is need for seconds\n s = ((s < 10) ? \"0\" + s : s) + \":\";\n\n f = (f < 10) ? \"0\" + f : f;\n\n if (TimeFormat == 'STANDARD')\n f = (f < 100) ? \"0\" + f : f;\n\n return h + m + s + f;\n}",
"printTime(){\n let min = Math.floor(this.project._pot/60);\n let sec = Math.floor(this.project._pot)-min*60;\n let msec = Math.floor((this.project._pot-Math.floor(this.project._pot))*1000);\n if(sec<10) sec = \"0\"+sec;\n if(min<10) min = \"0\"+min;\n return min+\":\"+sec+\":\"+msec;\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 time_convert(num) {\n if (parseInt(num) > 60) return `${Math.floor(parseInt(num) / 60)}h ${parseInt(num) % 60}min`;\n else return num; \n}",
"function timeCode(seconds) {\n\tvar delim = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ':';\n\n\t// const h = Math.floor(seconds / 3600);\n\t// const m = Math.floor((seconds % 3600) / 60);\n\tvar m = Math.floor(seconds / 60);\n\tvar s = Math.floor(seconds % 3600 % 60);\n\t// const hr = (h < 10 ? '0' + h + delim : h + delim);\n\tvar mn = (m < 10 ? '0' + m : m) + delim;\n\tvar sc = s < 10 ? '0' + s : s;\n\t// return hr + mn + sc;\n\treturn mn + sc;\n}",
"function timeCode(seconds) {\n\tvar delim = arguments.length <= 1 || arguments[1] === undefined ? ':' : arguments[1];\n\n\t// const h = Math.floor(seconds / 3600);\n\t// const m = Math.floor((seconds % 3600) / 60);\n\tvar m = Math.floor(seconds / 60);\n\tvar s = Math.floor(seconds % 3600 % 60);\n\t// const hr = (h < 10 ? '0' + h + delim : h + delim);\n\tvar mn = (m < 10 ? '0' + m : m) + delim;\n\tvar sc = s < 10 ? '0' + s : s;\n\t// return hr + mn + sc;\n\treturn mn + sc;\n}",
"function formatTime(hours, minutes){\n return hours + ':' + format(minutes);\n}",
"function convertCompletionTimeToStars(time) {\n let newStarValue;\n if (time < 30) {\n newStarValue = 0;\n } else if (time >= 30 && time < 45) {\n newStarValue = 1;\n } else if (time >= 45 && time < 60) {\n newStarValue = 2;\n } else if (time >= 60) {\n newStarValue = 3;\n }\n\n return newStarValue;\n }",
"function alignTimeText(hours, mins)\n{ \n let digit_1_px = 12; // pixel amount of digit '1' \n let digit_default_px = 27; // default pixel amount of digits 2..9\n\n /* set default values to each digit of xx:xx format */\n let h1_px = 0; // 1st digit (usually 0 except for hours 10, 11, and 12)\n let h2_px = digit_default_px; \n let m1_px = digit_default_px; \n let m2_px = digit_default_px; \n\n /* get 1st and 2nd digits of hours */\n let h1_digit = Math.floor(((hours)/10) % 10); // math is cool!\n let h2_digit = Math.floor(((hours)/1) % 10);\n\n /* check to see if one of the hour digits is a '1' */\n h1_px = (h1_digit == 1)? digit_1_px: h1_px;\n h2_px = (h2_digit == 1)? digit_1_px: h2_px;\n\n /* get 1st and 2nd digits of mins */\n let m1_digit = Math.floor(((mins)/10) % 10); \n let m2_digit = Math.floor(((mins)/1) % 10); \n\n /* check to see if one of the min digits is a '1' */\n m1_px = (m1_digit == 1)? digit_1_px: m1_px; \n m2_px = (m2_digit == 1)? digit_1_px: m2_px; \n\n let digit_space_count = (h1_px == 0)? 3: 4; // spaces in between 'xx:xx am' text based on hour digits \n let digit_space_px = 9 * digit_space_count; // space pixel = 9, multiplied by how many spaces needed\n let ampm_space_px = 9; // space between xx:xx and 'am' \n let ampm_px = 39; // pixel amount for 'am/pm' text\n\n /* calculates the entire pixel amount for the time and ampm label (including spaces) */\n let time_text_total_px = digit_space_px + h1_px + h2_px + m1_px + m2_px + ampm_space_px + ampm_px;\n\n /* calculates the time and ampm label positions based on the total pixel count (see css for alignment anchor info) */\n let time_label_position = (300 - time_text_total_px) / 2; // centers based on 300px span of versa display\n let ampm_label_position = time_label_position + time_text_total_px; \n\n /* set x coordinates of time and ampm labels, noice */\n time_label.x = time_label_position; \n ampm_label.x = ampm_label_position;\n}",
"function SGTimeToString(theTime) {\n var theHours, theMinutes, theSeconds;\n if (theTime == null || theTime == \"\" || !(theTime instanceof Date))\n return \"\";\n theHours = theTime.getHours();\n if (theHours >= 22) { //we have an under par SG to par score between -0:01 and -59:59...\n theSeconds = theTime.getSeconds();\n if (theSeconds > 0) {\n theMinutes = (theHours == 23 ? 60 - theTime.getMinutes() - 1 : 120 - theTime.getMinutes() - 1);\n theSeconds = 60 - theSeconds;\n } else {\n theMinutes = (theHours == 23 ? 60 - theTime.getMinutes() : 120 - theTime.getMinutes());\n }\n return \"-\" + theMinutes + \":\" + zeroPad(theSeconds);\n } else { //assume above par\n theMinutes = theTime.getMinutes() + (theHours * 60);\n theSeconds = theTime.getSeconds();\n return theMinutes + \":\" + zeroPad(theSeconds);\n } \n }",
"function pad(time)\n{\n var array = time.split(\":\");\n array[0] = parseInt(array[0]); //HH\n array[1] = parseInt(array[1]); //MM\n\n if (array[0] < 10)\n {\n array[0] = '0' + array[0];\n }\n\n if (array[1] < 10)\n {\n array[1] = '0' + array[1];\n }\n\n return (array[0] + \":\" + array[1]);\n\n}",
"function secondsToTimeString(timeSeconds) {\n timeSeconds = Math.round(timeSeconds);\n var seconds = timeSeconds % 60;\n timeSeconds = Math.floor(timeSeconds / 60);\n var minutes = timeSeconds % 60;\n timeSeconds = Math.floor(timeSeconds / 60);\n var hours = timeSeconds;\n\n var secondsPadded = (seconds < 10 ? \"0\" : \"\") + seconds;\n var minutesPadded = (minutes < 10 ? \"0\" : \"\") + minutes;\n\n if (hours > 0) {\n return hours + \":\" + minutesPadded + \":\" + secondsPadded;\n } else {\n return minutes + \":\" + secondsPadded;\n }\n}",
"formatVideoLength(time = null){\n if(time == null) return ;\n \n var a = time.match(/\\d+H|\\d+M|\\d+S/g);\n var result = 0;\n \n var d = { 'H': 3600, 'M': 60, 'S': 1 };\n var num;\n var type;\n \n for (var i = 0; i < a.length; i++) {\n num = a[i].slice(0, a[i].length - 1);\n type = a[i].slice(a[i].length - 1, a[i].length);\n \n result += parseInt(num) * d[type];\n }\n\n //Format seconds to actual time\n d = Number(result);\n var h = Math.floor(d / 3600);\n var m = Math.floor(d % 3600 / 60);\n var s = Math.floor(d % 3600 % 60);\n\n var hDisplay = h > 0 ? h + (h == 1 ? \" hour, \" : \" hours, \") : \"\";\n var mDisplay = m > 0 ? m + (m == 1 ? \" minute, \" : \" minutes, \") : \"\";\n var sDisplay = s > 0 ? s + (s == 1 ? \" second\" : \" seconds\") : \"\";\n return hDisplay + mDisplay + sDisplay;\n }",
"function to_db_time(time) {\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
UPDATE TABLE FUNCTIONS /update of table on user input parameters: type sort|filter (two options how to update the table) columnId id of column according to which the update will be performed | function updateDynamicTable(type, colIndex, userInput) {
//console.log("UPDATING");
if (type == "sortUp") {
sortTableUp(colIndex);
} else if (type == "sortDown") {
sortTableDown(colIndex);
} else {
filterTable(colIndex, userInput);
}
// write edited table to HTML
writeTableToHtml();
} | [
"updateColumn({ commit, state, rootState }, details) {\n const {\n columnData, columnIndex, tableIndex, tagIndex,\n } = details;\n const tableId = state.tagList[tagIndex].tables[tableIndex]._id;\n return axios.patch(\n `${constant.api.enframe}apps/${rootState.application.id}/tables/${tableId}/columns/${columnData._id}`,\n columnData,\n ).then(() => {\n commit('updateColumn', {\n columnData,\n columnIndex,\n });\n }).catch(({ response }) => {\n this.dispatch('snackbar/show', {\n type: constant.snackbarTypes.error,\n title: message.inputOutput.errorUpdatingColumn,\n message: response.data.message,\n });\n });\n }",
"function update_filters() {\n //get currently selected (or unselected values for all ids in columns.head)\n for (var i = 0; i < columns.length; i++) {\n columns[i].filter = $('#'+columns[i].cl).val();\n }\n\n // apply filter\n filtered_dataset = full_dataset.filter(filter_function);\n filtered_unique_columns = unique_columns.map(column_filter);\n\n // update display\n update_select_boxes();\n generate_table();\n}",
"dsUpdateTable(table, what) {\n switch (what) {\n case \"add\":\n table.columns = [];\n table.indexes = [];\n table.partitions = [];\n table.relations = [];\n this.gMap.tables.set(table.table_id, table);\n this.gData.tables.push(table);\n\n if (this.gMap.tablesByLetter.has(this.gCurrent.letterSelected)) {\n this.gMap.tablesByLetter.get(this.gCurrent.letterSelected).tables.push(table.table_id);\n } else {\n this.gMap.tablesByLetter.set(this.gCurrent.letterSelected, {tables: [table.table_id]});\n }\n break\n case \"update\":\n this.gMap.tables.get(table.table_id).table_name = table.table_name;\n break\n case \"delete\":\n break\n default:\n break\n }\n }",
"function sortTable(criteria) {\n const nameFilterValue = getById('filter-bar').value;\n let url;\n if (order === 'asc') {\n order = 'desc';\n } else {\n order = 'asc'\n }\n if (nameFilterValue) {\n url = `${server}?action=sort&criteria=${criteria}&order=${order}&name=${nameFilterValue}`;\n } else {\n url = `${server}?action=sort&criteria=${criteria}&order=${order}`\n }\n fetch(url, {\n headers: {\n 'Accept': 'application/json'\n },\n mode: \"no-cors\"\n })\n .then(r => r.json())\n .then(data => insertNewDataIntoTable(data));\n}",
"function buildFilteredTable (type) {\n // Generate \"add column\" cell.\n\n clearElement(addColumnDiv)\n addColumnDiv.appendChild(generateColumnAddDropdown(type))\n\n const query = generateQuery(type)\n\n updateTable(query, type)\n }",
"function User_Update_Type_de_documents_Type_de_documents0(Compo_Maitre)\n{\n var Table=\"typedocument\";\n var CleMaitre = Compo_Maitre.getCleVal();\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var to_nom=GetValAt(229);\n if (!ValiderChampsObligatoire(Table,\"to_nom\",TAB_GLOBAL_COMPO[229],to_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"to_nom\",TAB_GLOBAL_COMPO[229],to_nom))\n \treturn -1;\n var to_description=GetValAt(230);\n if (!ValiderChampsObligatoire(Table,\"to_description\",TAB_GLOBAL_COMPO[230],to_description,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"to_description\",TAB_GLOBAL_COMPO[230],to_description))\n \treturn -1;\n var note=GetValAt(231);\n if (!ValiderChampsObligatoire(Table,\"note\",TAB_GLOBAL_COMPO[231],note,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"note\",TAB_GLOBAL_COMPO[231],note))\n \treturn -1;\n var Req=\"update \"+Table+\" set \";\n Req+=\"to_nom=\"+(to_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(to_nom)+\"'\" )+\",to_description=\"+(to_description==\"\" ? \"null\" : \"'\"+ValiderChaine(to_description)+\"'\" )+\",note=\"+(note==\"\" ? \"null\" : \"'\"+ValiderChaine(note)+\"'\" )+\"\";\n Req+=\" where \"+NomCleMaitre+\"=\"+CleMaitre;\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de la mise à jour\");\nreturn CleMaitre;\n\n}",
"function FilterSortPage(tableName, filters, sorts, pageNum, pageSize) {\r\n /// This function must be called after each change on the _Index page.\r\n /// Changes : filter selection, sort selection, page click, edit, insert, delete.\r\n SpinnerShow();\r\n var sURL = \"/\" + tableName + \"/List\";\r\n if (pageNum === null) {\r\n pageNum = 1;\r\n }\r\n var vars = { \"filters\": filters, \"sorts\": sorts, \"pageNum\": pageNum, \"pageSize\": pageSize };\r\n $.ajax({\r\n url: sURL,\r\n type: \"GET\",\r\n data: vars\r\n })\r\n .done(function (result) {\r\n $(\"#\" + tableName + \"_Container\").html(result);\r\n SetupGrid();\r\n })\r\n .fail(function () {\r\n alert('fail FilterSortPage() function');\r\n })\r\n .always(function () {\r\n SpinnerHide();\r\n });\r\n}",
"function tableFiltering(){\n\t\tlet filterTableRows=sortTableRows.filter(function(item, index, array){\n\t\t\tif (filterTableName){\n\t\t\t\tif(!item.name.includes(filterTableName)) return false;\n\t\t\t}\n\t\t\tif (filterTableChars){\n\t\t\t\tif(!item.chars.includes(filterTableChars)) return false;\n\t\t\t}\n\t\t\tif (filterTablePrice){\n\t\t\t\tif(!item.price.includes(filterTablePrice)) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t\tcurTableRows=filterTableRows;\n\t\ttableRepagination();\n\t}",
"function sqlForPartialUpdate(dataToUpdate, propertyToColumnNameMap = {}) {\n const keys = Object.keys(dataToUpdate);\n if (keys.length === 0) throw new BadRequestError(\"No data\");\n\n // {firstName: 'Aliya', age: 32} => ['\"first_name\"=$1', '\"age\"=$2']\n const cols = keys.map(\n (dataPropertyName, idx) =>\n `\"${propertyToColumnNameMap[dataPropertyName] || dataPropertyName}\"=$${\n idx + 1\n }`\n );\n\n return {\n setCols: cols.join(\", \"),\n values: Object.values(dataToUpdate),\n };\n}",
"function toggleColumn(columnno,tableid,type)\n{\n // var this_link=document.getElementById(\"hq\");\n var table= document.getElementById(tableid);\n var allRows = table.rows; var cellNo = -1; var j=0;\n var cells = allRows[0].cells; \n // get the table columns header row (an array of)\n // and get the index of the column to toggle\n for(var j = 0; j< cells.length; j++){\n if(columnno.value== cells.item(j).id){ cellNo = j;}\n }\n alert(cellNo+\" selected\");\n for(var i=0; i<allRows.length; i++){ // hide all the row cells of this column\n if(allRows[i].cells.length > 1) {\n if(allRows[i].cells.item(cellNo).style.display==\"none\"){\n allRows[i].cells.item(cellNo).width=\"auto\";\n allRows[i].cells.item(cellNo).style.display=\"table-cell\";\n\t }\n\t else allRows[i].cells.item(cellNo).style.display=\"none\";\n }\n }\n}",
"Update(tablename, data, id, callback) {\n elasticClient.update({\n index: indexName,\n type: tablename,\n // version_type:version_type,\n id: id,\n // version: version,\n retry_on_conflict: 5,\n body: {\n doc: data,\n doc_as_upsert: true,\n }\n }, function (err, results) {\n callback(err, results)\n })\n }",
"function sortTable() {\n\t\t\t\t\tsortedBy = $(\"#projects-sort :selected\").text();\n\t\t\t\t\tsortedById = parseInt($(\"#projects-sort\").val());\n\t\t\t\t\tdataTable.order([ [ sortedById, sortOrder ] ]).draw();\n\t\t\t\t}",
"UPDATE_SORT(store,sort){\n // only update sort store if different sort is selected\n // I noticed clicking on sort buttons multiple times was messing with sort so I added this extra check\n if (store.selectedSort !== sort){\n store.selectedSort = sort\n store.weatherData = sortArray(store.weatherData, store.selectedSort)\n } \n }",
"function RefreshDataRows(tblName, update_rows, data_rows, is_update) {\n console.log(\" --- RefreshDataRows ---\");\n // PR2021-01-13 debug: when update_rows = [] then !!update_rows = true. Must add !!update_rows.length\n\n console.log(\"tblName\" , tblName);\n console.log(\"update_rows\" , update_rows);\n console.log(\"data_rows\" , data_rows);\n\n if (update_rows && update_rows.length ) {\n const field_setting = field_settings[tblName];\n console.log(\"field_setting\" , field_setting);\n for (let i = 0, update_dict; update_dict = update_rows[i]; i++) {\n RefreshDatarowItem(tblName, field_setting, update_dict, data_rows);\n }\n } else if (!is_update) {\n // empty the data_rows when update_rows is empty PR2021-01-13 debug forgot to empty data_rows\n // PR2021-03-13 debug. Don't empty de data_rows when is update. Returns [] when no changes made\n data_rows = [];\n }\n } // RefreshDataRows",
"set_col(col, type) {\n this.df = this.df.map(x => {\n switch (type) {\n case \"num\":\n x[col] = Number(x[col]);\n break;\n case \"date\":\n x[col] = new Date(x[col]);\n break;\n case \"int\":\n x[col] = parseInt(x[col]);\n break;\n case \"float\":\n x[col] = parseFloat(x[col]);\n break;\n }\n return x\n })\n }",
"function updateTable(tableID) {\r\n\t//Create a new HTTP request\r\n\tvar req = new XMLHttpRequest(); \r\n\r\n\t//Construct a URL that will send a Select request for the desired table\r\n\tvar url = \"http://flip2.engr.oregonstate.edu:\" + port + \"/select-\" + tableID;\r\n\t\r\n\t//Make the call\r\n\treq.open(\"GET\", url, false); \r\n\treq.addEventListener('load',function(){\r\n\t\t//If the request status is valid, update the table\r\n\t\tif(req.status >= 200 && req.status < 400){\r\n\t\t\t//Parse the JSON response\r\n\t\t\tvar response = JSON.parse(req.responseText); \r\n\t\t\t\r\n\t\t\t//Delete old table contents\r\n\t\t\tdeleteTableContents(tableID);\r\n\t\t\t\r\n\t\t\t//Add new table contents;\r\n\t\t\taddTableContents(tableID, response);\r\n\t\t} \r\n\t\t//If the request status isn't valid, display an error message with the request status\r\n\t\telse {\r\n\t\t\tconsole.log(\"Error in network request: \" + req.statusText);\r\n\t\t}\r\n\t});\t\r\n\treq.send(null); //no need to send additional data\r\n}",
"refreshData(newSearchTerm, newSortBy, newIsAscending) {\n this.updateDataFilters(newSearchTerm, newSortBy, newIsAscending);\n const { searchTerm, sortBy, isAscending } = this.dataFilters;\n const data = this.state.transactions.filtered(\n 'serialNumber BEGINSWITH[c] $0',\n searchTerm,\n );\n let sortDataType;\n switch (sortBy) {\n case 'serialNumber':\n case 'numberOfItems':\n sortDataType = 'number';\n break;\n default:\n sortDataType = 'realm';\n }\n this.setState({ data: sortDataBy(data, sortBy, sortDataType, isAscending) });\n }",
"function makeEditable(elementType, op, parameter) {\n $(elementType).each(function(index, value) {\n $(this).editable({\n url: function(params) {\n var inode_name = $(this).closest('tr').attr('inode-path');\n var absolute_file_path = append_path(current_directory, inode_name);\n var url = '/webhdfs/v1' + encode_path(absolute_file_path) + '?op=' +\n op + '&' + parameter + '=' + encodeURIComponent(params.value);\n\n return $.ajax(url, { type: 'PUT', })\n .fail(network_error_handler(url))\n .done(function() {\n browse_directory(current_directory);\n });\n },\n error: function(response, newValue) {return \"\";}\n });\n });\n }",
"function lc_update_filter_in_page (_param, _colFilters)\n{\n\tvar filter_string = _colFilters.join ('_');\n\n\t// In case all collapsed columns have now been expanded, making filter_string\n\t// empty, make it non-empty so that the server will parse the changes.\n\tif (!filter_string)\n\t\tfilter_string = '_';\n\n\tlc_update_filter_in_links (document.getElementsByTagName ('A'), _param, filter_string);\n\tlc_update_filter_in_links (document.getElementsByTagName ('AREA'), _param, filter_string);\n\n\t// Update the hidden field\n\tvar hidden = document.getElementById (_param);\n\n\tif (hidden)\n\t\thidden.value = filter_string;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
clears the map and tiles. | function clear() {
// set map to 0
for (var x = 0; x < mWidth; x++) {
mMap[x] = mMap[x] || [];
for (var y = 0; y < mHeight; y++) {
mMap[x][y] = 0;
}
}
mMapNextIndex.x = 0;
mMapNextIndex.y = 0;
// reset tiles
mTiles.length = 0;
} | [
"function clearMap() {\n for (var i = 0; i < facilityMarkers.length; ++i) {\n facilityMarkers[i].setMap(null);\n }\n facilityMarkers = [];\n}",
"function eraseMap() {\n document.body.removeChild(map);\n }",
"function cleanMap() {\n\n\t// Disable position selection by mouse click.\n\tdisablePositionSelect();\n\n\t// Remove existing nearby stations layer.\n\tif (map.getLayersByName(\"Nearby Docking Stations\")[0] != null)\n\t\tmap.removeLayer(map.getLayersByName(\"Nearby Docking Stations\")[0]);\n\t\t\n\t// Reset select controls.\n\tif (selectControl !=null) {\n\t\tselectControl.unselectAll();\n\t\tselectControl.deactivate();\n\t}\n \tif (selIncControl !=null) {\n\t\tselIncControl.unselectAll();\n\t\tselIncControl.deactivate();\n\t}\n \tif (voteControl !=null) {\n\t\tvoteControl.unselectAll();\n\t\tvoteControl.deactivate();\n\t} \n\tif (selectDockControl != null) {\n\t\tselectDockControl.unselectAll();\n\t\tselectDockControl.deactivate();\n\t}\n\n\tif (distr_stats != null)\n\t\tmap.removeLayer(distr_stats);\n}",
"function clearhail() {\n if (hailArray) {\n for (i in hailArray) {\n hailArray[i].setMap(null);\n }\n }\n}",
"clearGrid() {\n for (let row = 0; row < this.N; row++) {\n for (let column = 0; column < this.N; column++) {\n this.grid[row][column].element.remove();\n }\n }\n this.grid = null;\n\n this.width = 0;\n this.height = 0;\n this.N = 0;\n\n this.startTile = null;\n this.endTile = null;\n }",
"clear(){\n tiles.forEach(tile =>{\n tile.innerText = '';\n });\n }",
"function clearwind() {\n if (windArray) {\n for (i in windArray) {\n windArray[i].setMap(null);\n }\n }\n}",
"function clearBoxes() {\n if (boxpolys != null) {\n for (var i = 0; i < boxpolys.length; i++) {\n boxpolys[i].setMap(null);\n }\n }\n boxpolys = null;\n }",
"function resetTiles() {\n\t\tvar positions = createPositionArray(xCount, yCount, diameter);\n\t\t\n\t\tfor(var i = 0; i < tiles.length; i++){\n\t\t\ttiles[i].setPosition(positions.pop());\n\t\t}\n\t\trotateTiles();\n\t\tgroupTiles();\n\t}",
"finalize() {\n for (const tile of this._cache.values()) {\n if (tile.isLoading) {\n tile.abort();\n }\n }\n this._cache.clear();\n this._tiles = [];\n this._selectedTiles = null;\n }",
"function clearMarkers() {\n let initialCitiesLength = Object.keys(INITIALCITIES).length;\n for (let i = MARKERS.length - 1; i >= initialCitiesLength; i--) {\n MARKERS[i].setMap(null);\n MARKERS.splice(i, 1);\n }\n }",
"reset() {\n this.map = new Map();\n }",
"function directionsClear() {\n // remove any highlighted trails, POIs, loops, etc. from the map\n highlightsClear();\n\n // remove the line from the map\n // and reposition the start and end markers to nowhere\n if (DIRECTIONS_LINE) MAP.removeLayer(DIRECTIONS_LINE);\n MARKER_FROM.setLatLng([0,0]);\n MARKER_TO.setLatLng([0,0]);\n\n // clear the directions text from the Directions panel\n // and clear/hide the elevation profile image\n $('#directions_list').empty().listview('refresh');\n $('#directions_elevationprofile').prop('src','about:blank').parent().hide();\n\n // on the map panel, hide the Directions button since there are none\n $('#page-map div.map_toolbar a[href=\"#page-directions\"]').closest('td').hide();\n\n // on the Directions panel, show the Map button since we in fact have a line to show\n $('#page-directions div[data-role=\"header\"] a[href=\"#page-map\"]').hide();\n}",
"function clearMap(retainSampleCombo, retainMapMatchedGroups){\n\t\troadGroups.forEach(function (val, idx){\n\t\t\tval.removeAll();\n\t\t});\n\t\troutingGroup.removeAll();\n\t\troadGroups = [];\n\t\troadShapes = [];\n\t\troadEdits = [];\n\t\tif(overlayGroup) overlayGroup.removeAll();\n\t\tdocument.getElementById(\"overlay-def-container\").innerHTML = \"\"\n\t\tdocument.getElementById(\"feedbackTxt\").innerHTML = \"\";\n\t\tif(!retainSampleCombo){\n\t\t\tdocument.getElementById(\"sampleSelector\").selectedIndex = 0;\n\t\t}\n\t\t\n\t\t// remove all road selector items added\n\t\tvar selectobject = document.getElementById(\"roadSelector\");\n\t\tselectobject.selectedIndex = 0;\n\t\t\n\t\tfor (var i=selectobject.length-1; i>0; i--){\n\t\t\tif (i > 0){\n\t\t\t\tselectobject.remove(i);\n\t\t\t}\n\t\t}\n\n\t\tif (retainMapMatchedGroups){ //remove all the groups which display the map matching points/links\n\n\t\t\tif (mapMatchedRoadGroups){\n\t\t\t\tfor (var m=0; m<mapMatchedRoadGroups.length; m++){\n\t\t\t\t\tmapMatchedRoadGroups[m].removeAll();\n\t\t\t\t}\n\t\t\t\tmapMatchedRoadGroups = [];\n\t\t\t\tmapMatchedRoadShapes = [];\n\t\t\t}\n\n\t\t}\n\n\t}",
"function clear() {\n clearCalculation();\n clearEntry();\n resetVariables();\n operation = null;\n }",
"function clear() {\n\t\tgenerations = [];\n\t\tfittest = [];\n\t}",
"function clearPopups(){\n for (var i=0; i<map.popups.length; i++) {\n map.removePopup(map.popups[i]);\n }\n}",
"function refresh() {\n map.remove();\n mapView();\n createRoute();\n busLocation();\n}",
"resetMapAndVars(){\n controller.infoWindow.close();\n model.map.setZoom(13);\n model.map.setCenter(model.athensCenter);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts, formats and downloads the data from chapter message, adds it to the full book, and sends the command to load the next chapter. | function chapterMessage(message) {
let chapterText = createChapter(message.titleText, message.bodyText, ++chapterNum);
fullBook = fullBook.concat(chapterText);
const chapterBlob = new Blob(chapterText);
const chapterURL = URL.createObjectURL(chapterBlob);
let titleText = message.titleText.replace(/\n/g, " ");
titleText = titleText.replace(/<.*>/g, "");
titleText = titleText.replace(/\/|\\|\?|\*|\||"|:/g, ""); // delete illegal text for file name
browser.downloads.download({ url: chapterURL, filename: folder + "chapter " + chapterNum + " - " + titleText + ".html" });
sendMessage({
command: "nextPage",
nextType: this.nextType,
nextTag: this.nextTag,
next: this.next
});
} | [
"loadChapters() {\n\n if(this.getSpecification() === undefined)\n throw \"Specification isn't done loading, can't fetch chapters.\";\n else if(this.getSpecification() === null)\n throw \"Specification failed to load, can't fetch chapters\";\n\n\t\t// Request all of the chapter content...\n\t\tthis.getChapters().forEach(chapter => {\n\n // Create a chapter with no text by default.\n this.setChapter(chapter, null);\n\n // Try to load the chapter if it's not forthcoming.\n if(!chapter.forthcoming)\n fetch(\"chapters/\" + chapter.id + \".md\")\n .then((response) => {\n // Remember that we got a response.\n this.chaptersLoaded++;\n\n // If we got a reasonable response, process the chapter.\n if(response.ok)\n response.text().then(text => this.setChapter(chapter, text));\n \n })\n });\n\n\t}",
"function newPageMessage(message) {\n const loadingTab = goToUrl(tabId, message.url)\n loadingTab.then(function f(tabInfo) {\n const loadingScript = browser.tabs.executeScript(tabId, { file: \"/content_scripts/scraper.js\" });\n loadingScript.then(function f() {\n port = browser.tabs.connect(tabId);\n port.onMessage.addListener(handleMessage);\n sendMessage({\n command: \"fetchChapter\",\n titleType: this.titleType,\n title: this.title,\n bodyType: this.bodyType,\n body: this.body\n });\n })\n .catch(reportExecuteScriptError);\n });\n}",
"async getChapter() {\n try {\n if (this.props.downloaded) {\n this.getDownloadedContent();\n } else {\n if (this.props.baseAPI != null) {\n var content = await vApi.get(\n \"bibles\" +\n \"/\" +\n this.props.sourceId +\n \"/\" +\n \"books\" +\n \"/\" +\n this.props.bookId +\n \"/\" +\n \"chapter\" +\n \"/\" +\n this.state.currentVisibleChapter\n );\n if (content) {\n let header = getHeading(content.chapterContent.contents);\n this.setState({\n chapterHeader: header,\n chapterContent: content.chapterContent.contents,\n error: null,\n isLoading: false,\n currentVisibleChapter: this.state.currentVisibleChapter,\n nextContent: content.next,\n previousContent: content.previous,\n });\n }\n }\n }\n } catch (error) {\n this.setState({\n error: error,\n isLoading: false,\n chapterContent: [],\n unAvailableContent: true,\n });\n }\n this.setState({\n selectedReferenceSet: [],\n showBottomBar: false,\n showColorGrid: false,\n });\n }",
"function identifiersMessage(message) {\n this.titleType = message.titleType;\n this.title = message.title;\n this.bodyType = message.bodyType;\n this.body = message.body;\n this.nextType = message.nextType;\n this.nextTag = message.nextTag;\n this.next = message.next;\n folder = message.href.match(/https?:\\/\\/(www.)?([^\\/]*)/)[2] + \"/\"; // matches the part between www. and the first /\n sendMessage({\n command: \"fetchChapter\",\n titleType: this.titleType,\n title: this.title,\n bodyType: this.bodyType,\n body: this.body\n });\n}",
"function nextchapter(){\n\t\t\tvar curchapt = document.getElementById(\"chaptNum\").innerHTML;\n\t\t\tif(curchapt<10){\n\t\t\t curchapt++;\n\t\t\t}\n\t\t\t//Verification\n\t\t\tdocument.getElementById(\"chaptNum\").innerHTML= curchapt;\n\t\t\tdocument.getElementById(\"reader\").innerHTML = curchapt;\n\t\t\tloadPage(curchapt);\n\t\t}",
"loadData() {\n fetch(`/api/v1/courses/topics/?chapter=${this.id}`)\n .then(response => response.json())\n .then(data => this.chapter = data)\n }",
"async getDownloadedContent() {\n this.setState({ isLoading: true });\n var content = await DbQueries.queryVersions(\n this.props.language,\n this.props.versionCode,\n this.props.bookId,\n this.props.currentVisibleChapter\n );\n if (content != null) {\n this.setState({\n chapterHeader:\n content[0].chapters[this.state.currentVisibleChapter - 1]\n .chapterHeading,\n downloadedBook: content[0].chapters,\n chapterContent:\n content[0].chapters[this.state.currentVisibleChapter - 1].verses,\n isLoading: false,\n error: null,\n previousContent: null,\n nextContent: null,\n });\n } else {\n this.setState({\n chapterContent: [],\n unAvailableContent: true,\n isLoading: false,\n });\n }\n }",
"function loadChapterJSON(chapter, subchapter)\n{\n\n var xobj = new XMLHttpRequest(); //Create a request object to get the data from the JSON File\n xobj.overrideMimeType(\"application/json\"); //Overide the deafult file type it is looking for to JSON\n xobj.open(\"GET\", chapterJSONFile, true); //Give the name of our file (it is located locally) and tell it to load asynchronously\n //(while the rest of the code cannot function until code is loaded - sychronous requests are deprecated according to https://xhr.spec.whatwg.org/#the-open()-method)\n //We use GET as while POST more secure, GET is the only guaranteed method to work in all browsers\n //in current build - REVIEW WHEN MOVED TO FULL LIVE TESTING\n xobj.onreadystatechange = function () //What event listener activates when the task is done\n {\n if (xobj.readyState == 4 /*&& xobj.status == \"200\" I have removed this check now since the status will not change on local tests - RE-ENABLE ON LIVE TESTS*/) //If the the request is DONE(readyState) and OK(status) \n {\n loadChapter(xobj.responseText, chapter, subchapter); //Send the specific chapter and starting subchapter to load\n }\n };\n xobj.send(null); //Send a null to the request to complete the transaction\n}",
"function handleCommand2CompletionMsg(aMsg) {\n\n // Show the completion record in the relevant page fields.\n if (aMsg.Code == 'Ack'){\n divCommand2.innerHTML = aMsg.Code;\n divInfo2.innerHTML = aMsg.Info;\n divProgress2.innerHTML = 'none';\n\n } else if (aMsg.Code == 'Nak'){\n divCommand2.innerHTML = aMsg.Code;\n divInfo2.innerHTML = aMsg.Info;\n\n } else if (aMsg.Code == 'Done'){\n divCommand2.innerHTML = aMsg.Code;\n divInfo2.innerHTML = aMsg.Info;\n divProgress2.innerHTML = 'none';\n\n } else if (aMsg.Code == 'Progress'){\n divProgress2.innerHTML = aMsg.Info;\n\n } else {\n divCommand2.innerHTML = 'bad completion code';\n divInfo2.innerHTML = 'none';\n divProgress2.innerHTML = 'none';\n }\n}",
"function chapterDivide(doc, options) {\n\t\toptions = options || {};\n\t\tvar page = options.page,\n\t\t\t\t// Only use the basename without anchor for the url:\n\t\t\t\turl = options.url.split('/').slice(-1)[0].split('#')[0],\n\t\t\t\tmaxElements = r.preferences.maxChapterElements.value,\n\t\t\t\t// Find the parent element of the repeating elements which exceed the max chapter elements:\n\t\t\t\tparent = $(doc).find(':nth-child(0n+' + (maxElements + 1) + ')').first().parent(),\n\t\t\t\tchildren,\n\t\t\t\tparts,\n\t\t\t\tpart,\n\t\t\t\tprefix,\n\t\t\t\tlastPageSuffix,\n\t\t\t\tnodeName,\n\t\t\t\tindex;\n\t\tif (parent.length) {\n\t\t\tchildren = parent.children();\n\t\t\t// The number of parts to split this chapter into:\n\t\t\tparts = Math.ceil(children.length / maxElements);\n\t\t\t// By default, start with the first part (zero-indexed):\n\t\t\tpart = 0;\n\t\t\t// The prefix to identify anchors to chapter parts:\n\t\t\tprefix = r.Navigation.getChapterPartAnchorPrefix() + '-';\n\t\t\t// The suffix to identify last page positions:\n\t\t\tlastPageSuffix = '-' + r.Navigation.getLastPageAnchorName();\n\t\t\t// The nodeName of the next/prev link-wrapper, a div unless the parent is a list:\n\t\t\tnodeName = /^(ul|ol)$/i.test(parent.prop('nodeName')) ? 'li' : 'div';\n\t\t\tif (r.Navigation.isChapterPartAnchor(page)) {\n\t\t\t\t// Get the current part from the page anchor:\n\t\t\t\tpart = Number(String(page).replace(prefix, '').replace(lastPageSuffix, '')) || 0;\n\t\t\t} else if (r.Navigation.isLastPageAnchor(page)) {\n\t\t\t\t// Anchor points to the last page in the chapter, so select the last part:\n\t\t\t\tpart = parts - 1;\n\t\t\t} else if (r.Navigation.isProgressAnchor(page)) {\n\t\t\t\t// Anchor points to chapter progress, jump to the equivalent part:\n\t\t\t\tpart = (Math.ceil(children.length * r.Navigation.getProgressFromAnchor(page) / maxElements) || 1) - 1;\n\t\t\t} else if (r.CFI.isValidCFI(page)) {\n\t\t\t\tpart = r.Navigation.getChapterPartFromCFI(page);\n\t\t\t} else if ($.type(page) === 'string') {\n\t\t\t\t// Handle page anchors:\n\t\t\t\tindex = $(doc).find('#' + page).closest(children).index();\n\t\t\t\tif (index >= maxElements) {\n\t\t\t\t\tpart = Math.floor(index / maxElements);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Remove all elements up to the current part:\n\t\t\tchildren.slice(0, maxElements * part).remove();\n\t\t\t// Remove all elements after current part:\n\t\t\tchildren.slice(maxElements * (part + 1)).remove();\n\t\t\tif (part) {\n\t\t\t\t// Add a link to the previous part:\n\t\t\t\t$(r.document.createElement(nodeName))\n\t\t\t\t\t.prop('id', 'cpr-subchapter-prev')\n\t\t\t\t\t.addClass('cpr-subchapter-link')\n\t\t\t\t\t.append($('<a></a>').prop('href', url + '#' + prefix + (part - 1) + lastPageSuffix))\n\t\t\t\t\t.attr('data-chapter-part', part)\n\t\t\t\t\t// Add the number of remaining elements for the last chapter part:\n\t\t\t\t\t.attr('data-chapter-part-elements', part < parts - 1 ? undefined : children.length - part * maxElements)\n\t\t\t\t\t.attr('data-chapter-parts', parts)\n\t\t\t\t\t.attr('data-chapter-parts-elements', children.length)\n\t\t\t\t\t.prependTo(parent);\n\t\t\t}\n\t\t\tif (part < parts - 1) {\n\t\t\t\t// Add a link to the next part:\n\t\t\t\t$(r.document.createElement(nodeName))\n\t\t\t\t\t.prop('id', 'cpr-subchapter-next')\n\t\t\t\t\t.addClass('cpr-subchapter-link')\n\t\t\t\t\t.append($('<a></a>').prop('href', url + '#' + prefix + (part + 1)))\n\t\t\t\t\t// Add the number of parts and elements if they're not already added to the prev node:\n\t\t\t\t\t.attr('data-chapter-parts', part ? undefined : parts)\n\t\t\t\t\t.attr('data-chapter-parts-elements', part ? undefined : children.length)\n\t\t\t\t\t.appendTo(parent);\n\t\t\t}\n\t\t}\n\t}",
"loadSpecification() { \n\n // Fetch the JSON\n fetch(this.url)\n .then(response => {\n\n // If it's a valid status, parse the text as JSON.\n if (response.status >= 200 && response.status <= 299) {\n return response.json();\n } \n // Otherwise, return an error.\n else {\n throw Error(response.statusText);\n }\n\n })\n .then(data => {\n\n // Validate the book schema before we get started.\n let ajv = new Ajv();\n let valid = ajv.validate(schema, data);\n\n // Did the specification have schema errors?\n // Initialize the book as null and set the errors.\n if (!valid) {\n this.specification = null;\n this.errors = ajv.errors.map(error => this.url + error.dataPath + \" \" + error.message);\n } \n // If it is valid, then set the specification and load the chapters.\n else {\n this.specification = data;\n this.loadChapters();\n }\n // Notify the progress handler.\n this.progressHandler.call();\n\n // Mark the specification as loaded.\n this.loadedSpecification = true;\n\n })\n // If there was an error, print it to the console and set the errors.\n .catch(err => {\n\n this.loadedSpecification = true;\n\n console.error(err);\n // Uh oh, something bad happened. Set data to null to render an error.\n this.specification = null;\n this.errors = [\"Wasn't able to load the file \" + this.url + \": \" + err.message];\n\n // Notify the progress handler.\n this.progressHandler.call();\n\n });\n \n }",
"function getStory() {\n\txhttp = new XMLHttpRequest(); // <-- create request\n\tchangeSong(); // <-- load first song\n\n\t// Each time the request-state changes...\n\txhttp.onreadystatechange = function() {\n\n\t\t// readyState(4) = Operation complete, status(200) = request succesfull\n\t\tif (this.readyState == 4 && this.status == 200) {\n\n\t\t\tstrStory = xhttp.responseText; // <-- retrieve text from query\n\t\t\tstoryParts = strStory.split(\"<END>\"); // <-- break string into array by '<END>' delimeter (was written into .txt file)\n\t\t\tstoryParts.unshift(intro); // <-- add intro portion\n\n\t\t\t// for each string element in array...\n\t\t\tfor (var i = 0; i < storyParts.length; i++) {\n\t\t\t\tstoryParts[i] = storyParts[i].trim(); // <-- trim any leading/trailing white-spaces\n\t\t\t}\n\t\t\ttextAreaEl.value = storyParts[0]; // <-- set opening window to first string (Intro)\n\t\t}\n\t}\n\txhttp.open(\"GET\", \"pupProcess.php?name=\" + storyName, true); // <-- Open .php file, passing 'name' parameter to open file\n\txhttp.send(); // <-- sent request\n}",
"function processMessage(){\n\t\tack=1;\n\t\t// The child is initialized as soon as there is an ack for the init message sent by the child.\n\t\tif (messageIn.type!=INIT && child && previousOut.type==INIT && messageIn.ack==\"1\" && previousOut.msn==messageIn.ackMsn) {\n\t\t controller.initializationFinished(partnerURL);\n\t }\n\t\t\t\t\t\t\t\n\t\t// Call the actual processing functions\n\t\tswitch(messageIn.type){\n\t\t\tcase INIT:\n\t\t\t\tprocessInit();\n\t\t\t\tbreak;\n\t\t\tcase ACK:\n\t\t\t\tprocessAck();\n\t\t\t\tbreak;\n\t\t\tcase PART:\n\t\t\t\tprocessPart();\n\t\t\t\tbreak;\n\t\t\tcase END:\n\t\t\t\tprocessEnd();\n\t\t\t\tbreak;\t\t\t\t\t\n\t\t}\n\t\t// Set the processed message as the previousIn message\n\t\tpreviousIn=messageIn;\t\t\n\t}",
"function archiveMessageOnLoad(e){\r\n var txt = e.responseText;\r\n\r\n // Find the text we're looking for\r\n txt = txt.split('<form method=\"post\" action=\"nachrichten.php\">')[1];\r\n txt = txt.split('</form></div></div></div><div id=\"lright1\">')[0];\r\n txt = txt.substr(2); // Strip off a leading newline...\r\n\r\n debug(d_med, txt);\r\n\r\n // Save it\r\n var ar = GM_getValue(archive_msg_key, '');\r\n ar += txt;\r\n GM_setValue(archive_msg_key, ar);\r\n\r\n // Go and get the next message\r\n archiveMessage();\r\n}",
"function createChapter(title, body, num) {\n let preTitle = \"<chapter\" + num + \">\\n<h2 id=\\\"ch\" + num + \"\\\">\";\n let preBody = \"</h2>\\n<body>\"\n let postBody = \"</body>\\n</chapter\" + num + \">\\n\"\n return [preTitle, title, preBody, body, postBody];\n}",
"function displayChapter(chapter, idChapter) {\n return function() {\n initDisplay();\n\t\n /**\n * Changing the style of the curretn chapter in summary\n\t \t */\n for (var i = 0; i < chaptersListArray.length - 1; i++) {\n\t document.getElementById(\"chapter\" + i).style.background = \"#120D16\";\n\t document.getElementById(\"chapter\" + i).firstChild.firstChild.style.color = \"lightblue\";\n\t}\n document.getElementById(\"chapter\" + idChapter).style.background = \"#52B6CC\";\n\tdocument.getElementById(\"chapter\" + idChapter).firstChild.firstChild.style.color = \"#120D16\";\n\t\n\tcurrentChapter = idChapter;\n\tisNotFirstPage = false;\n document.getElementById('chaptersList').style.display = \"none\";\n\tdocument.getElementById('containerChapter').style.display = \"block\";\n\t\n\t\t/**\n * Apply parameters (brightness...)\n\t \t */\n var parameters = readJson('parameters');\n\n if (parameters === null) {\n initializeParameter();\n }\n \n applyParameters();\n\n document.getElementById('previous').style.display = 'block';\n document.getElementById('next').style.display = 'block';\n\n\t\t/** \n * Re-Initialize 'paragraphs'\n\t \t */\n var iframe = document.getElementById(\"completeChapter\");\n iframe.contentWindow.document.body.innerHTML = \"\"; \n var paragraphs = document.getElementById('paragraphs');\n while (paragraphs.firstChild) {\n paragraphs.removeChild(paragraphs.firstChild);\n }\n\n document.getElementById(\"paragraphs\").style.display = 'block';\n document.getElementById(\"paragraphs\").addEventListener(\"click\", displayToolbar, false); \n\n iframe.contentWindow.document.body.innerHTML += chapter; \n\n var temp = document.getElementById('completeChapter').contentDocument;\n var ael = temp.getElementsByTagName(\"p\");\n\n for (var i = 0, c = ael.length ; i < c ; i++) {\t\t\n if (i === 0) { //First page of the chapter so display the title\n var title = temp.getElementsByTagName(\"h1\");\n var currentParagraph = title[0].cloneNode(true);\n var paragraph = document.createElement(\"h1\");\n paragraph.id = \"title\" + i;\n paragraph.innerHTML = currentParagraph.innerHTML;\n document.getElementById(\"paragraphs\").appendChild(paragraph);\n }\n\n var currentParagraph = ael[i].cloneNode(true);\n var paragraph = document.createElement(\"p\");\n paragraph.id = \"paragraph\" + i;\n paragraph.innerHTML = currentParagraph.innerHTML;\n document.getElementById(\"paragraphs\").appendChild(paragraph);\n\n if (paragraph instanceof Element) {\n var p = elementInViewport(paragraph);\n if (!p) {\n lastParagraph = i;\n break;\n }\n }\n }\n\tsaveLastPageRead2(currentChapterTitle, currentChapter, -3); //-3 because the last page read is the first page of the chapter\n document.getElementById('toolbar').style.display = \"block\";\n }\n}",
"function start_conversation() {\n send_version();\n}",
"function nextTutorialMessage() {\n\ttutorialInstructionIndex ++;\n\tif(tutorialInstructions[tutorialInstructionIndex+1]) {\n\t\tdisplayMessage( \"Flip-a-Blox Tutorial\", tutorialInstructions[tutorialInstructionIndex].message );\n\t}\n\telse {\n\t\tcallbackAfterMessage = function() {};\n\t\thideMessage();\n\t\tplaying_state = true;\n\t}\n}",
"function Msg_partial_page_setup() {\n $(\"#show_jobs_btn\").click(function () {\n show_job(1, $('#fixed_info_tab').data('process_name'));\n });\n $(\"#msg_load_more\").bind(\"click\", { curPage: more_info_accumulate_page }, function (event) {\n show_message((event.data.curPage + 1), $('#fixed_info_tab').data('process_name'));\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It controls whether all ships are located on the game board, and if so, removes the distribution panel, and replace the original ship drawings with the corresponding locker background images. Parameters: none. | function fleet_ready(){
click_sound.play();
var contador = 0;
for(let i = 0; i < 15; i++) //It counts the emplaced ships.
if(own_fleet[i])
contador++;
if(contador == 15){ //If all ships era emplaced...
document.getElementById("gameboard_container").removeChild(document.getElementById("own_fleet_distrib")); //...it removes the distribution panel...
for(let i = 0; i < 15; i++){
ships_draw[i].remove(); //...remove de original drawings...
if(own_fleet[i].type != 1){ //...and puts the background images according to ships orientation.
if(own_fleet[i].direction == 0){
own_squares[own_fleet[i].occupied_places[0]].style.backgroundImage="url(images/vt.png)";
for(let j = 1; j < own_fleet[i].type - 1; j++)
own_squares[own_fleet[i].occupied_places[j]].style.backgroundImage="url(images/vc.png)";
//let sum = own_fleet[i].occupied_places[0]+own_fleet[i].type*10-10;
own_squares[own_fleet[i].occupied_places[own_fleet[i].type - 1]].style.backgroundImage="url(images/vb.png)";
}else{
own_squares[own_fleet[i].occupied_places[0]].style.backgroundImage="url(images/hl.png)";
for(let j = 1; j < own_fleet[i].type - 1; j++)
own_squares[own_fleet[i].occupied_places[j]].style.backgroundImage="url(images/hc.png)";
//let sum = own_fleet[i].occupied_places[0]+own_fleet[i].type-1;
own_squares[own_fleet[i].occupied_places[own_fleet[i].type - 1]].style.backgroundImage="url(images/hr.png)";
}
}else{
//let sum = own_fleet[i].occupied_places[0];
own_squares[own_fleet[i].occupied_places[0]].style.backgroundImage="url(images/single.png)";
}
sign("Press any enemy position to attack!"); //It invites user to start the game.
}
}else{
sign("Incomplete fleet."); //If any ship are not emplaced, it reports to user.
}
} | [
"function own_board_random_deployment(){\r\n \r\n click_sound.play();\r\n \r\n random_fleet_deployment(own_board, own_fleet); //It calls the random fleet distribution function.\r\n\r\n for(let i = 0; i < 15; i++){ //Loop that puts all distributed ships in place.\r\n\r\n if(i < 10){ //For all ships that occupy more than one position, it sets the drawing that corresponds to their orientation.\r\n if(own_fleet[i].direction == 0){\r\n\r\n ships_draw[i].setAttribute(\"class\", \"vertical\");\r\n \r\n let src = ships_draw[i].getAttribute(\"src\");\r\n src = src.split(\"_\");\r\n ships_draw[i].setAttribute(\"src\", \"images/vertic_\" + src[1]);\r\n\r\n }else{\r\n \r\n ships_draw[i].setAttribute(\"class\",\"horizontal\");\r\n \r\n let src = ships_draw[i].getAttribute(\"src\");\r\n src = src.split(\"_\");\r\n ships_draw[i].setAttribute(\"src\", \"images/horiz_\" + src[1]);\r\n \r\n }\r\n }\r\n\r\n own_squares[own_fleet[i].occupied_places[0]].appendChild(ships_draw[i]); //It appends the ship images to the lockers corresponding to their first position.\r\n }\r\n\r\n sign(\"Complete fleet. Press 'ready' to continue.\");\r\n}",
"function drop(e){\r\n \r\n e.preventDefault();\r\n \r\n background_squares_paint(e.target.id.slice(4, 6), type, dir, \"#7e7e08\"); //It restores the original color of the lockers where the ship was dropped.\r\n\r\n if(ship_validation(type, Number(e.target.id.slice(4,6)), dir, own_board)){ //If the new position is validated...\r\n\r\n click_sound.play();\r\n \r\n var id = e.dataTransfer.getData(\"text/plain\");\r\n \r\n e.target.appendChild(document.getElementById(id)); //...the ship image is put on the board...\r\n\r\n switch(id){ //...and the Ship object is added to the user fleet array. Also the corresponding board positions are overwritten with the ship number.\r\n \r\n case \"ca\":\r\n own_fleet[0] = new Ship(5, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 0);\r\n break;\r\n \r\n case \"v1\":\r\n own_fleet[1] = new Ship(4, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 1);\r\n break;\r\n \r\n case \"v2\":\r\n own_fleet[2] = new Ship(4, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 2);\r\n break;\r\n \r\n case \"s1\":\r\n own_fleet[3] = new Ship(3, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 3);\r\n break;\r\n \r\n case \"s2\":\r\n own_fleet[4] = new Ship(3, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 4);\r\n break;\r\n \r\n case \"s3\":\r\n own_fleet[5] = new Ship(3, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 5);\r\n break;\r\n \r\n case \"c1\":\r\n own_fleet[6] = new Ship(2, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 6);\r\n break;\r\n \r\n case \"c2\":\r\n own_fleet[7] = new Ship(2, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 7);\r\n break;\r\n \r\n case \"c3\":\r\n own_fleet[8] = new Ship(2, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 8);\r\n break;\r\n \r\n case \"c4\":\r\n own_fleet[9] = new Ship(2, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 9);\r\n break;\r\n \r\n case \"b1\":\r\n own_fleet[10] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 10);\r\n break;\r\n \r\n case \"b2\":\r\n own_fleet[11] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 11);\r\n break;\r\n \r\n case \"b3\":\r\n own_fleet[12] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 12);\r\n break;\r\n \r\n case \"b4\":\r\n own_fleet[13] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 13);\r\n break;\r\n \r\n case \"b5\":\r\n own_fleet[14] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 14);\r\n break;\r\n } \r\n }else{ //If the position was not validated, it reports the rejection to the user.\r\n\r\n sign(\"Forbidden place! \\n Please, try again.\");\r\n }\r\n}",
"function displayShip(ship){\n startCoordAcross = ship.start.Across;\n startCoordDown = ship.start.Down;\n endCoordAcross = ship.end.Across;\n endCoordDown = ship.end.Down;\n if(startCoordDown > 10 || startCoordDown < 0 || startCoordDown > 10 || startCoordDown < 0 || endCoordAcross > 10 || endCoordAcross < 0 || endCoordDown > 10 || endCoordDown < 0) {\n setDialogBox(\"failed to place ship.\");\n return;\n }\n if(startCoordAcross > 0){\n if(startCoordAcross == endCoordAcross){\n for (i = startCoordDown; i <= endCoordDown; i++) {\n document.getElementById(i+'_'+startCoordAcross).innerHTML = '<img src=\"sprites/ShipSmall.png\" alt=\"\" border=0 height=24 width=24>';\n }\n } else {\n for (i = startCoordAcross; i <= endCoordAcross; i++) {\n document.getElementById(startCoordDown+'_'+i).innerHTML = '<img src=\"sprites/ShipSmall.png\" alt=\"\" border=0 height=24 width=24>';\n }\n }\n }\n}",
"function resetVisibleBoard() {\n\t$(\".tile\").text(\"\");\n\n\t$(\".horizontal-line\").each(function() {\n\t\tvar el = $(this);\n\t\tsetLineState(el, \"dormant\");\n\t});\n\n\t$(\".vertical-line\").each(function() {\n\t\tvar el = $(this);\n\t\tsetLineState(el, \"dormant\");\n\t});\n}",
"function renderLocalBoard() {\n if(victory) {\n for(let i=0;i<9;i++) {\n localBoardPops[i].visible = false;\n }\n return;\n }\n\n if(currentBoard == -1) {\n localBoard.setTexture(resources[\"res/BoardGray.svg\"].texture);\n for(i=0;i<9;i++) {\n localBoardPops[i].renderable = false;\n localBoardPops[i].interactive = false;\n localBoardPops[i].buttonMode = false;\n }\n return;\n }\n\n localBoard.setTexture(resources[\"res/Board.svg\"].texture);\n\n for(i=0;i<9;i++) {\n switch(boardData[currentBoard].getSquare(i).getState()) {\n case X:\n localBoardPops[i].setTexture(resources[\"res/X.svg\"].texture);\n localBoardPops[i].renderable = true;\n localBoardPops[i].interactive = false;\n localBoardPops[i].buttonMode = false;\n break;\n case O:\n localBoardPops[i].setTexture(resources[\"res/O.svg\"].texture);\n localBoardPops[i].renderable = true;\n localBoardPops[i].interactive = false;\n localBoardPops[i].buttonMode = false;\n break;\n default:\n localBoardPops[i].renderable = false;\n localBoardPops[i].interactive = true;\n localBoardPops[i].buttonMode = true;\n }\n }\n}",
"function resetGame() {\n ships._ships = [];\n currentState = states.Splash;\n score = 0;\n shipGap = shipGapMax;\n}",
"placeShips() {\n if(this.ships.length > 0) {\n for(let i = 0; i < this.ships.length; i++) {\n const ship = this.ships[i];\n for(let j = 0; j < ship.coords.length; j++) {\n const index = this.findCellByXY(ship.coords[j].x, ship.coords[j].y);\n this.matrix[index].status = 's';\n }\n }\n }\n }",
"function disable_draw() {\n drawing_tools.setShape(null);\n}",
"function fillPegs(){\n if (window.shipLength === 5){\n if (window.dir === window.start - 1) {\n Player.ships.battleship.pegs[1] = window.dir;\n Player.ships.battleship.pegs[2] = window.dir - 1;\n Player.ships.battleship.pegs[3] = window.dir - 2;\n Player.ships.battleship.pegs[4] = window.dir - 3;\n }else if (window.dir === window.start + 1) {\n Player.ships.battleship.pegs[1] = window.dir;\n Player.ships.battleship.pegs[2] = window.start + 2;\n Player.ships.battleship.pegs[3] = window.start + 3;\n Player.ships.battleship.pegs[4] = window.start + 4;\n }else if (window.dir === window.start - 10) {\n Player.ships.battleship.pegs[1] = window.dir;\n Player.ships.battleship.pegs[2] = window.dir - 10;\n Player.ships.battleship.pegs[3] = window.dir - 20;\n Player.ships.battleship.pegs[4] = window.dir - 30;\n }else if (window.dir === window.start + 10) {\n Player.ships.battleship.pegs[1] = window.dir;\n Player.ships.battleship.pegs[2] = window.dir + 10;\n Player.ships.battleship.pegs[3] = window.dir + 20;\n Player.ships.battleship.pegs[4] = window.dir + 30;\n }\n }\n else if (window.shipLength === 4) {\n if (window.dir === window.start - 1) {\n Player.ships.cruiser.pegs[1] = window.dir;\n Player.ships.cruiser.pegs[2] = window.dir - 1;\n Player.ships.cruiser.pegs[3] = window.dir - 2;\n }else if (window.dir === window.start + 1) {\n Player.ships.cruiser.pegs[1] = window.dir;\n Player.ships.cruiser.pegs[2] = window.start + 2;\n Player.ships.cruiser.pegs[3] = window.start + 3;\n }else if (window.dir === window.start - 10) {\n Player.ships.cruiser.pegs[1] = window.dir;\n Player.ships.cruiser.pegs[2] = window.dir - 10;\n Player.ships.cruiser.pegs[3] = window.dir - 20;\n }else if (window.dir === window.start + 10) {\n Player.ships.cruiser.pegs[1] = window.dir;\n Player.ships.cruiser.pegs[2] = window.dir + 10;\n Player.ships.cruiser.pegs[3] = window.dir + 20;\n }\n }\n else if (window.shipLength === 3){\n if (window.dir === window.start - 1) {\n Player.ships.sub.pegs[1] = window.dir;\n Player.ships.sub.pegs[2] = window.dir - 1;\n }else if (window.dir === window.start + 1) {\n Player.ships.sub.pegs[1] = window.dir;\n Player.ships.sub.pegs[2] = window.start + 2;\n }else if (window.dir === window.start - 10) {\n Player.ships.sub.pegs[1] = window.dir;\n Player.ships.sub.pegs[2] = window.dir - 10;\n }else if (window.dir === window.start + 10) {\n Player.ships.sub.pegs[1] = window.dir;\n Player.ships.sub.pegs[2] = window.dir + 10;\n }\n }\n else if (window.shipLength === 2){\n if (window.dir === window.start - 1) {\n Player.ships.destroyer.pegs[1] = window.dir;\n }else if (window.dir === window.start + 1) {\n Player.ships.destroyer.pegs[1] =window.dir;\n }else if (window.dir === window.start - 10) {\n Player.ships.destroyer.pegs[1] = window.dir;\n }else if (window.dir === window.start + 10) {\n Player.ships.destroyer.pegs[1] = window.dir;\n }\n }\n }",
"function checkShipPlacement() {\n if (isHorizontal) {\n if (shipLength + col > 10) {\n return false;\n } else {\n return true;\n }\n } else {\n if (shipLength + row > 10) {\n return false;\n } else {\n return true;\n }\n }\n}",
"function resetPlayerShip(){\r\n\t\tmyShip.getSpecs().center.x = canvas.width /2;\r\n\t\tmyShip.getSpecs().center.y = canvas.height /2;\r\n\t\tmyShip.getSpecs().momentum.x = 0;\r\n\t\tmyShip.getSpecs().momentum.y = 0;\r\n\t\tmyShip.getSpecs().rotation = 0;\r\n\t\tmyShip.getSpecs().lives -= 1;\r\n\t\tmyShip.getSpecs().reset = false;\r\n\t\tresetTime = 1.5;\r\n\r\n\t\tmyShip.getSpecs().invincible = true;\r\n\t\tmyShip.getSpecs().texture = invincibleTexture;\r\n\t\tmyShip.getSpecs().width += 20;\r\n\t\tmyShip.getSpecs().height += 10;\r\n\t\tmyShip.getSpecs().hit = false;\r\n\t}",
"function place_ship(ship) {\n for (var i = 0; i < ship.length; i++) {\n spielfeld[ship[i].y][ship[i].x] = true;\n }\n}",
"function freeze(){\r\n if (current.some(index => squares[currentPosition+index+width].classList.contains('taken'))){\r\n current.forEach(index => squares[currentPosition+index].classList.add('taken'));\r\n // select a new piece \r\n random = nextRandom;\r\n nextRandom = Math.floor(Math.random()*piecesArray.length);\r\n current = piecesArray[random][currentRotation];\r\n currentPosition = 4;\r\n draw();\r\n displayShape();\r\n addScore();\r\n endGame();\r\n }\r\n }",
"function invalidateAllPositions() {\n for (let i = 0; i < squares.length; i++) {\n squares[i].isValidPosition = false;\n }\n}",
"defocus(){\n\t\tif(this.focusedTile === null) return;\n\n\t\tthis.focus.x = 10000;\n\t\tthis.focus.y = 10000;\n\t\tthis.focusedTile = null;\n\n\t\tthis.boardMatrix.forEach(row => {\n\t\t\trow.forEach(tile => {\n\t\t\t\ttile.moveable = false;\n\t\t\t})\n\t\t})\n\n\t\tthis.boardMatrix.forEach(row => {\n\t\t\trow.forEach(tile => {\n\t\t\t\tif (tile.figure !== null){\n\t\t\t\t\ttile.figure.hitable = false;\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\n\t\tthis.moveableSprites.forEach(sprite => {\n\t\t\tsprite.destroy();\n\t\t})\n\n\t\tthis.hitmarker.forEach(sprite => {\n\t\t\tsprite.destroy();\n\t\t})\n\t}",
"function drag_start(e){\r\n \r\n e.preventDefault\r\n \r\n//It prepares the image dragged to fit the right size.\r\n dragged_ship.src = e.target.getAttribute(\"src\");\r\n \r\n dragged_ship.className = e.target.className;\r\n \r\n e.dataTransfer.setDragImage(dragged_ship, 15, 15);\r\n \r\n//It stores the dragged ship orientation for the next \"Drag and Drop\" functions.\r\n if(e.target.className == \"vertical\")\r\n dir = 0;\r\n else\r\n dir = 1;\r\n \r\n//It stores the dragged ship type for the next \"Drag and Drop\" functions.\r\n if(e.target.id.startsWith(\"ca\")) \r\n type = 5;\r\n\r\n else if(e.target.id.startsWith(\"v\"))\r\n type = 4;\r\n\r\n else if(e.target.id.startsWith(\"s\"))\r\n type = 3;\r\n\r\n else if(e.target.id.startsWith(\"c\"))\r\n type = 2;\r\n else\r\n type = 1;\r\n \r\n//It set up the Id of event Target as data to be transferred.\r\n e.dataTransfer.setData(\"text/plain\", e.target.id);\r\n \r\n//It cleans the board if the dragged ship still was on it.\r\n if(e.target.parentElement.className == \"square\")\r\n clean_position_ship_draw(e.target, e.target.parentElement.id.slice(4, 6));\r\n}",
"function board_overwrite(fleet, num_boat){\r\n \r\n //It decomposes starting position\r\n let ini_x = Math.trunc(fleet[num_boat].occupied_places[0] / 10);\r\n let ini_y = fleet[num_boat].occupied_places[0] % 10;\r\n \r\n if(fleet == own_fleet) // It searchs the board corresponding to the ship\r\n var board = own_board;\r\n else\r\n var board = enemy_board;\r\n\r\n if(fleet[num_boat].direction == 0) // It prints the number\r\n for(let i = 0; i < fleet[num_boat].type; i++)\r\n board[ini_x + i][ini_y] = num_boat;\r\n\r\n else\r\n for(let i = 0; i < fleet[num_boat].type; i++)\r\n board[ini_x][ini_y + i] = num_boat; \r\n}",
"function completeStripPhase () {\n /* strip the player with the lowest hand */\n stripPlayer(recentLoser);\n updateAllGameVisuals();\n}",
"draw() {\n this.ghosts.forEach((ghost) => ghost.draw());\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
setGreenLights Set the traffic lights to green based on the direction of the traffic | setGreenLights() {
// Get the array traffic lights from the config
let lights = this.config.getDirections()[this.getDirectionIndex()];
// Set the traffic lights to green based on the direction of the traffic
lights.map((direction) => {this.trafficLights[direction].color = TRAFFIC_LIGHT_GREEN;});
// Set the color of the traffic lights visually and print a log
this.draw.traffic(this.getTrafficLights());
} | [
"setYellowLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet lights = this.config.getDirections()[this.getDirectionIndex()];\n\n\t\t// Set the traffic lights to green based on the direction of the traffic\n\t\tlights.map((direction) => {this.trafficLights[direction].color = TRAFFIC_LIGHT_YELLOW;});\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}",
"setRedLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet currentGreenLights = this.config.getDirections()[this.getDirectionIndex()];\n\n // Loop through the greenLights and set the rest to red lights\n\t\tfor (let direction in this.trafficLights) {\n\t\t\tlet elementId = this.trafficLights[direction].name;\n\t\t\tif (currentGreenLights.indexOf(elementId) >= 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.trafficLights[direction].color = TRAFFIC_LIGHT_RED;\n\t\t}\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}",
"function greenLight() {\n\tturnOffLights();\n\t$('#green').toggleClass(\"greenGlow\");\n\tgreenAudio.play();\n}",
"function turnOnLights() {\n lightsFadeIn(bulb1);\n lightsFadeIn(bulb2);\n lightsFadeIn(bulb3);\n lightsFadeIn(bulb4);\n lightsFadeIn(bulb5);\n lightsFadeIn(bulb6);\n lightsFadeIn(leftSpeaker);\n lightsFadeIn(rightSpeaker);\n lightsFadeIn(balloonsButton);\n lightsFadeIn(table);\n lightsFadeIn(cake);\n lightsFadeIn(floor);\n}",
"function setSecondsLights()\n {\n //every even second light is yellow\n //otherwise light is off\n if(time.getSeconds() % 2 == 0)\n {\n addLight(\"yellow\", secondsRow);\n } else {\n addLight(\"off\", secondsRow);\n }\n }",
"ColorUpdate(colors) {\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(127, 127, 127, 255));\n colors.push(vec4(10, 10, 10, 210));\n colors.push(vec4(127, 127, 127, 255));\n\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n \n if (Sky.instance.GlobalTime >= 9 && Sky.instance.GlobalTime < 19){\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 255));\n // StreetLamp Light turn off\n // ColorUpdate => Black\n }\n else {\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 255));\n // StreetLamp Light turn on\n // ColorUpdate => Yell Light\n }\n }",
"function yellowLight() {\n\tturnOffLights()\t\n\t$('#yellow').toggleClass(\"yellowGlow\");\n\tyellowAudio.play();\n}",
"function blueLight() {\n\tturnOffLights()\n\t$('#blue').toggleClass(\"blueGlow\");\n\tblueAudio.play();\n}",
"getGreenLightDuration() {\n\t\treturn GREEN_LIGHT_DURATION;\n\t}",
"get lightsOn()\r\n\t{\r\n\t\treturn this._lightsOn;\r\n\t}",
"function redLight() {\n\tturnOffLights()\n\t$('#red').toggleClass(\"redGlow\");\n\tredAudio.play();\n}",
"lightsOn() {\n console.log('[johnny-five] Lights are on.');\n this.lights.on();\n }",
"function initializeLEDs() {\r\n \r\n greenLed.writeSync(0)\r\n redLed.writeSync(0)\r\n\r\n}",
"function updateGlowStatus(isglow, color) {\r\n clearCanvas(); /* Clear the Canvas first */\r\n drawglow = isglow;\r\n glowClr = color;\r\n drawcells(); /* Redraw the cells */\r\n}",
"getTrafficLights() {\n\t\treturn TRAFFIC_LIGHTS;\n\t}",
"function lightingSetUp(){\n\n keyLight = new THREE.DirectionalLight(0xFFFFFF, 1.0);\n keyLight.position.set(3, 10, 3).normalize();\n keyLight.name = \"Light1\";\n\n fillLight = new THREE.DirectionalLight(0xFFFFFF, 1.2);\n fillLight.position.set(0, -5, -1).normalize();\n fillLight.name = \"Light2\";\n\n backLight = new THREE.DirectionalLight(0xFFFFFF, 0.5);\n backLight.position.set(-10, 0, 0).normalize();\n backLight.name = \"Light3\";\n\n scene.add(keyLight);\n scene.add(fillLight);\n scene.add(backLight);\n}",
"getTrafficLights() {\n\t\treturn this.trafficLights;\n\t}",
"function colorChanged(){\n\tsetGradientColor(lastDirection , rgbString(color1.value) , rgbString(color2.value) , true);\n}",
"loopLights() {\n console.log('[johnny-five] Lights Looping.');\n this.buildLoop();\n\n this.loop = setTimeout(() => {\n this.buildLoop();\n }, 8000);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method takes a batch of inserted item statements and 1) identifies all parent bibIds (even if bibIds not present in those statements), and 2) posts them to the configured "IndexDocumentQueue" stream (which triggers reindexing by the discoveryapiindexer) | _writeToIndexDocumentQueue (batch) {
const streamName = process.env.INDEX_DOCUMENT_STREAM_NAME
const schemaName = process.env.INDEX_DOCUMENT_SCHEMA_NAME
// Make sure stream-writing is configured
if (streamName && schemaName) {
return this._getBibIdsForItemStatements(batch)
.then((bibIds) => {
const kinesisRecords = bibIds.map((bibId) => {
return { type: 'record', uri: bibId }
})
return this._writeToStreamsClient(streamName, kinesisRecords, schemaName)
.then(() => log.debug(`Wrote ${kinesisRecords.length} to ${streamName} (encoded against ${schemaName})`))
})
} else return Promise.resolve(batch)
} | [
"_getBibIdsForItemStatements (statements) {\n // Build hash mapping subject_ids to array of statements:\n const subjectIdGroups = statements.reduce((hash, statement) => {\n if (!hash[statement.subject_id]) hash[statement.subject_id] = []\n hash[statement.subject_id].push(statement)\n return hash\n }, {})\n\n // Turn that hash into a hash mapping subject_ids to bibId (or null if no\n // bibId found):\n const subjectIdsToBibIds = Object.keys(subjectIdGroups).reduce((hash, subjectId) => {\n const bibIdStatement = subjectIdGroups[subjectId].filter((statement) => statement.predicate === 'nypl:bnum')[0]\n hash[subjectId] = bibIdStatement ? bibIdStatement.object_id.replace('urn:bnum:', '') : null\n return hash\n }, {})\n\n // Since some of those bibIds will be null (item deletion), map our bibIds\n // to an array of Promises that fill in missing bibIds via db lookup:\n const bibIdsToReindex = Object.keys(subjectIdsToBibIds).map((subjectId) => {\n // If bibId is set, resolve it immediately:\n if (subjectIdsToBibIds[subjectId]) return Promise.resolve(subjectIdsToBibIds[subjectId])\n else {\n // Otherwise look it up in the db:\n return db.getStatement('resource', subjectId, 'nypl:bnum')\n .then((result) => {\n if (result) return result.object_id.replace('urn:bnum:', '')\n else {\n log.warn(`Skipping bib reindex for item ${subjectId}, could not locate`)\n return null\n }\n })\n }\n })\n\n return Promise.all(bibIdsToReindex)\n .then((ids) => {\n // Remove null entries (bibId could not be found)\n return ids.filter((id) => id)\n })\n }",
"function createDocumentsAndActivities( itcb ) {\n async.eachSeries( ids, createSingle, onCreatedAll );\n\n function onCreatedAll( err ) {\n if( err ) {\n Y.log( `Problem while creating activities and documents: ${JSON.stringify( err )}`, 'warn', NAME );\n return itcb( err );\n }\n Y.log( `Created ${ids.length} activities and documents`, 'debug', NAME );\n itcb( null );\n }\n }",
"process() {\n var dbActivities = await(this.getDbActivities_()),\n uniqueSpheres = this.getUniqueSpheresFromActivities_(dbActivities),\n dbSpheres = await(this.createDbSpheres_(uniqueSpheres)),\n updatedActivities =\n await(this.updateActivities_(dbActivities, dbSpheres));\n\n this.archiveActivities_(updatedActivities);\n this.archiveSpheres_(dbSpheres);\n }",
"function batchUpload() {\n var queueName = dijit.byId('vl-queue-name').getValue();\n currentType = dijit.byId('vl-record-type').getValue();\n\n var handleProcessSpool = function() {\n if( \n vlUploadQueueImportNoMatch.checked || \n vlUploadQueueAutoOverlayExact.checked || \n vlUploadQueueAutoOverlay1Match.checked) {\n\n vlImportRecordQueue(\n currentType, \n currentQueueId, \n function() {\n retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);\n }\n );\n } else {\n retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);\n }\n }\n\n var handleUploadMARC = function(key) {\n dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');\n processSpool(key, currentQueueId, currentType, handleProcessSpool);\n };\n\n var handleCreateQueue = function(queue) {\n currentQueueId = queue.id();\n uploadMARC(handleUploadMARC);\n };\n \n if(vlUploadQueueSelector.getValue() && !queueName) {\n currentQueueId = vlUploadQueueSelector.getValue();\n uploadMARC(handleUploadMARC);\n } else {\n createQueue(queueName, currentType, handleCreateQueue, vlUploadQueueHoldingsImportProfile.attr('value'));\n }\n}",
"async function createMultipleDocuments(client, dataBaseName, collectionName, collData) {\n\t\t// let collData = [\t{ name: \"Jay\",\t\twins: 5, location: { city: \"Chennai\", country: \"India\"} },\n\t\t// \t\t\t\t\t{ name: \"Sridhar\",\twins: 9, location: { city: \"London\", country: \"UK\"}},\n\t\t// \t\t\t\t\t{ name: \"Sumitha\",\twins: 7, location: { city: \"Didcot\", country: \"America\"}}\n\t\t// ];\n\n\t\t// See https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#insertMany for the insertMany() docs\n\t\tconst result = await client.db(dataBaseName).collection(collectionName).insertMany(collData);\n\n\t\tconsole.log(`${result.insertedCount} new listing(s) created with the following id(s):`);\n\t\tconsole.log(result.insertedIds);\n\t}",
"_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 }",
"async prepare() {\n await this.initPublishableStages()\n // Add the venue to the documents to be published\n await this.fetch('*[_type == \"venue\"][0]._id').then(venueId => {\n this.queueIds([venueId])\n })\n // Now go recurse through it all\n await this.chug()\n if (this.failOnUnpublishable && this.unpublishable.length > 0) {\n throw extendBoom(\n Boom.forbidden(\n 'Unable to publish, set includes documents that are not ready to be published at this time'\n ),\n {\n target: this.issueId,\n unpublishable: this.unpublishable\n }\n )\n }\n const result = Object.keys(this.output).map(key => this.output[key])\n return result\n }",
"getIndexes(women, facts) {\n db.collection('indexes').get().then(snapshot => {//get indexing files\n let snaps = {};\n snapshot.forEach(snap => {//put actual ids in to snaps\n if (snap.data() && snap.data()[\"IDs\"]) {\n let IDpool = snap.data()[\"IDs\"];\n let kind = snap.id;\n snaps[kind] = {};\n Object.keys(IDpool).forEach(key => {\n if (IDpool[key].includes(Dictionary.getLanguage()))\n snaps[kind][key] = IDpool[key];\n })\n }\n })\n \n //we are using {all} so I can know what to what collaction the id belongs.\n let all = {};\n //extract the amount of ids that were asked for in the function parameters\n Object.keys(snaps).forEach(key => {\n let arr = [];\n let kind = (key === \"women Index\") ? \"women\" : \"facts\";\n let amount = (kind === \"women\") ? women : facts;\n\n let data = Object.keys(snaps[key]);//make the ids of this kind an array\n\n if (amount > data.length)//make sure that there are enough ids\n amount = data.length;\n\n arr = this.randomizeArr(data, amount);//returns a random arr in the amount size\n\n //add the number of slides reternd so we know how meny slides we will have\n this.setState({ dataslide: this.state.dataslide + arr.length });\n all[key] = arr;\n });\n\n Object.keys(all).forEach(key => {//go over both keys and call all ids from firestore\n let collect = (key === \"women Index\") ? \"women\" : \"didYouKnow\";\n all[key].forEach(id => {//for each id for this key\n\n db.collection(collect).doc(id).get().then(snapshot => {\n if (snapshot.data()) {\n let item;\n let data = snapshot.data();\n if (collect === \"women\") {\n item = this.pushWomen(data);\n }\n else if (collect === \"didYouKnow\") {\n item = this.pushFact(data);\n }\n\n if (item) {//add item to the items state\n let items = this.state.items;\n items.push(item);\n this.setState({ items: items });\n }\n else\n this.setState({ dataslide: this.state.dataslide - 1 });//remove slide becuse id was not used\n\n\n if (this.state.dataslide === this.state.items.length)\n this.mixSlides();\n\n }\n\n }).catch(error => console.log(error))\n })\n })\n\n\n }).catch(error => console.log(error))\n }",
"processInputDocument(doc) {\n if (!this.documentIsPublishable(doc)) {\n this.unpublishable.push(doc._id)\n }\n const rewritten = prepareDocument(doc)\n if (doc._type == 'lyra.imageAsset' || doc._type == 'lyra.fileAsset') {\n this.filesToCopy.push({\n from: doc.path,\n to: rewritten.path\n })\n }\n const ids = findRefs(rewritten)\n this.queueIds(ids)\n this.output[doc._id] = rewritten\n }",
"function refreshIndexes(){\r\n\tvar pubs\r\n\ttry {\r\n\t\tPublication.find({}).then((data) => {\r\n\t\t\tpubs = data\r\n\t\t\tpubs.forEach((pub) => {\r\n\t\t\t\tlet tempPub = indexarPub(pub)\r\n\t\t\t\tPublication.updateOne({\"_id\":pub.id}, tempPub)\r\n\t\t\t})\r\n\t\t})\r\n\t} catch (error) {\r\n\t\tconsole.log(error)\r\n\t}\r\n}",
"function pushToDb() {\n setInterval(function () {\n while(global.instruObj.length){\n // Until the global instruObj is empty, add data to the indexedDb\n let chunks = global.instruObj.splice(0,CHUNCK_LENGTH_TO_DB);\n dbFns.set(shortid.generate(),chunks).then(()=>{\n //console.log(\"Successfully wrote to db\",chunks)\n }).catch((err)=>{\n console.error(\" Error writing to db:\",err)\n });\n }\n },WRITE_TO_DB_INTERVAL)\n}",
"function Batch() {\n this.seq = 0;\n this.state = 'start';\n this.changes = [];\n this.docs = [];\n}",
"function TrackedDocumentAPI(_db) {\n\n db = _db;\n\n return {\n\n exists: function (id, callback) {\n db.document.get(id, function (err, ret) {\n var hasError = (ret.error === true && ret.code !== 404);\n var exists = ((typeof ret !== 'undefined' || ret !== null) && ret.error !== true);\n callback( (hasError)? -1 : null, exists, ret)\n });\n },\n\n create: function (collection, documents, options, callback) {\n if (!_.isArray(documents)) documents = [documents];\n\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n options.waitForSync = true;\n var savedArray = [];\n logger('save count: ', documents.length, callback);\n async.forEachSeries(documents,\n function (document, next) {\n\n document = _.cloneDeep(document);\n\n var handle = generateEntityHandle(collection, document);\n\n var afterCheckIfDocumentExists = function (err, exists, ret) {\n\n if (err) return next(err, ret);\n\n var existingDocument = ret;\n\n // check if requires update (any changes to raw_data)\n var diffKeys = _.difference(_.keys(existingDocument), _.keys(document));\n\n // compare documents while skipping the following keys\n var cloneExistingDocument = _.omit(existingDocument, diffKeys);\n var cloneNewDocument = _.omit(document, diffKeys);\n var requiresUpdate = (!_.isEqual(cloneExistingDocument, cloneNewDocument));\n logger('existingDocument', (existingDocument) ? 'yes' : 'no');\n logger('requiresUpdate', requiresUpdate);\n logger('has crawled before? ', (existingDocument && existingDocument._key) ? 'yes, id: ' + existingDocument._key : 'no');\n logger('requires update? ', (existingDocument && requiresUpdate) ? 'yes' : 'no');\n\n // make decision whether to create new document, create revision or do nothing\n if (!exists) {\n\n _saveNewDocument(collection, document, options, function (err, results) {\n if (err) return next(err, results);\n if (!results) return next(new Error('Missing new saved documents results'), null);\n\n savedArray.push(results);\n next(null, results);\n });\n\n } else if (exists && existingDocument && requiresUpdate) {\n\n _saveNewDocumentRevision(collection, document, existingDocument, options, function (err, results) {\n if (err) return next(err, results);\n if (!results) return next(new Error('Missing saved revision documents results'), null);\n\n savedArray.push(results);\n next(null, results);\n });\n\n } else {\n // is an existing document and does not require update\n next(null, null);\n }\n };\n\n this.exists(handle, afterCheckIfDocumentExists);\n\n }.bind(this),\n function (err, results) {\n logger('create', err, ',', savedArray);\n callback(err, savedArray);\n }\n );\n },\n\n get: function (id, options, callback) {\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n return db.document.get(id, options, callback);\n },\n\n put: function (id, data, options, callback) {\n\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n var idTokens = id.split('/');\n if (!idTokens || idTokens.length !== 2) return callback(-1, {\n error: true,\n errorNum: 1203,\n code: 404\n });\n\n var collection = idTokens[0];\n var key = idTokens[1];\n\n data = _.cloneDeep(data);\n data._key = key;\n\n async.series([\n function getDocument(next) {\n db.document.get(id, options, function (err, results) {\n next(err, results);\n });\n }.bind(this),\n function createIfExists(next) {\n this.create(collection, data, options, next);\n }.bind(this)\n ], function (err, results) {\n callback(err, results[results.length - 1]);\n });\n },\n\n delete: function (id, options, callback) {\n\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n // TODO: delete edges (but keep history?)\n return db.document.delete(id, options, callback);\n },\n\n list: function (collection, callback) {\n return db.document.list(collection, callback);\n }\n\n };\n}",
"function makeFolderIndex(\n folder: string,\n includeSubfolders: boolean,\n): Array<string> {\n console.log(\n `\\nmakeFolderIndex for '${folder}' (${\n includeSubfolders ? 'with' : 'without'\n } subfolders)`,\n )\n\n let noteCount = 0\n const outputArray: Array<string> = []\n let folderList: Array<string> = []\n // if we want a to include any subfolders, create list of folders\n if (includeSubfolders) {\n folderList = DataStore.folders.filter((f) => f.startsWith(folder))\n } else {\n // otherwise use a single folder\n folderList = [folder]\n }\n console.log(`\\tFound ${folderList.length} matching folder(s)`)\n // Iterate over the folders\n // A for-of loop is cleaner and less error prone than a regular for-loop\n for (const f of folderList) {\n const notes = notesInFolderSortedByName(f)\n // console.log(notes.length)\n if (notes.length > 0) {\n // If this is a sub-folder level, then prefix with ### for a 3rd level heading,\n // otherwise leave blank, as a suitable header gets added elsewhere.\n outputArray.push(noteCount > 0 ? `### ${f} Index` : `_index ${f}`)\n outputArray.push(\n `(${notes.length} notes, last updated: ${nowShortDateTime})`,\n )\n // iterate over this folder's notes\n for (const note of notes) {\n outputArray.push(titleAsLink(note))\n }\n outputArray.push('')\n noteCount += notes.length\n }\n }\n\n return outputArray\n}\n\n//----------------------------------------------------------------\n// Command to index folders, creating list of note links\n// Options:\n// 1. This folder only (insert into current note)\n// 2. This folder only (add/update to _index note)\n// 3. This folder + subfolders (add/update into single _index note)\n// 4. TODO: This folder + subfolders (add/update into _index notes in each subfolder)\n\nexport async function indexFolders(): Promise<void> {\n // To start with just operate on current note's folder\n const fullFilename = Editor.filename ?? undefined\n // const currentNote = Editor.note ?? undefined\n let thisFolder: string\n let outputArray: Array<string> = []\n\n if (fullFilename === undefined) {\n console.log(\n ` Info: No current filename (and therefore folder) found, so will ask instead.`,\n )\n thisFolder = await chooseFolder(`Please pick folder to index`)\n } else {\n thisFolder = getFolderFromFilename(fullFilename)\n }\n console.log(`\\nindexFolders from folder ${thisFolder}`)\n\n const option = await chooseOption(\n 'Create index for which folder(s)?',\n [\n {\n label: `This folder only (insert into current note)`,\n value: 'one-to-current',\n },\n {\n label: `This folder only (add/update to _index note)`,\n value: 'one-to-index',\n },\n {\n label: `This folder and sub-folders (add/update to single _index note)`,\n value: 'all-to-one-index',\n },\n {\n label: `(NOT YET WORKING) This folder and sub-folders (add/update to _index notes)`,\n value: 'all-to-many-index',\n },\n {\n label: '❌ Cancel',\n value: false,\n },\n ],\n false,\n )\n\n if (!option) {\n return\n }\n\n console.log(` option: ${option}`)\n if (option.startsWith('one')) {\n outputArray = makeFolderIndex(thisFolder, false)\n } else if (option.startsWith('all')) {\n outputArray = makeFolderIndex(thisFolder, true)\n }\n const outString = outputArray.join('\\n')\n console.log(` -> ${outString}",
"async _saveBlogTags() {\n for (const [key, tags] of Object.entries(this.blogTagsPerBlogPost)) {\n const proms = tags.filter(tag => typeof tag.id === 'string').map(tag => {\n return this._rpc({\n model: 'blog.tag',\n method: 'create',\n args: [{\n 'name': tag.name,\n }],\n });\n });\n const createdIDs = await Promise.all(proms);\n\n await this._rpc({\n model: 'blog.post',\n method: 'write',\n args: [parseInt(key), {\n 'tag_ids': [[6, 0, tags.filter(tag => typeof tag.id === 'number').map(tag => tag.id).concat(createdIDs)]],\n }],\n });\n }\n }",
"function insertAllActivities(){\n var length = activities.length;\n\n if (length > 0) {\n //I go through all activities to get the the ids.\n for (var i = 0; i < activities.length; ++i) {\n getStravaDataActivity(activities[i]);\n }\n } else {\n console.error(\"No data activities\");\n }\n}",
"function accumData(postData) {\n documents.push(postData)\n if(documents.length == 10000){\n // send array of JSON objects to solr server\n console.log('sending')\n sendData(documents)\n documents = []\n }\n}",
"function extGroup_queueDocEditsForDelete(sbObj)\n{\n //walk the list of participants\n var parts = sbObj.getParticipants();\n for (var i=0; i < parts.length; i++)\n {\n //schedule each participant edit to the document\n extPart.queueDocEditsForDelete(parts[i]);\n }\n}",
"function extPart_queueDocEdits(groupName, partName, paramObj, sbObj)\n{\n var location = extPart.getLocation(partName);\n \n // NOTE: This only updates the location for insertion.\n // Finds will need to be done separately, if they\n // rely on this new location.\n if (paramObj.MM_location != null)\n {\n location = paramObj.MM_location;\n }\n\n // Check that we have an insert location and insert text. Also check that we\n // have a prior node, or we have insert text. If we do not have a prior node\n // and have no insert text, the participant should be ignored. This may happen\n // if the entire participant is conditional and the condition fails.\n if ( location && extPart.getRawInsertText(partName)\n && ( (sbObj && sbObj.getNamedSBPart(partName))\n || extPart.getInsertText(partName, paramObj)\n )\n )\n {\n var sbPartList = (sbObj) ? sbObj.getParticipants() : new Array(); // existing SBParticipants\n var sbPart = null; // SBParticipant\n\n var paramArray = extPart.expandParameterObject(groupName, partName, paramObj);\n\n if (extPart.DEBUG && paramArray.length == 0) {\n alert(\"skipping participant \" + partName + \", with empty parameter\");\n }\n\n var priorNodeSegmentArray = null;\n var deleteNodeSegmentArray = null;\n if (extPart.getPartType(groupName, partName) == \"multiple\") {\n\n priorNodeSegmentArray = new Array();\n deleteNodeSegmentArray = new Array();\n\n //find the priorNodeSegments for each parameter object\n\n var partList = dw.getParticipants(partName);\n for (var j=0; partList && j < partList.length; j++) {\n //get the node information\n extPart.extractNodeParam(partName, partList[j].parameters, partList[j].participantNode);\n }\n\n for (var i=0; i < paramArray.length; i++) {\n if (sbObj && !sbObj.getForceMultipleUpdate())\n {\n for (var j=0; j < sbPartList.length; j++)\n {\n if ( sbPartList[j].getName() == partName\n && extPart.parametersMatch(partName, paramArray[i], sbPartList[j].getParameters())\n )\n {\n priorNodeSegmentArray.push(sbPartList[j].getNodeSegment());\n break;\n }\n }\n }\n\n if (!sbObj || j == sbPartList.length) {\n\n var existingNodeSegment = null;\n\n //look for an existing match on the page,\n //if the insert location is aboveHTML, belowHTML, or the child of a node\n if ((!sbObj || !sbObj.getForceMultipleUpdate()) &&\n (location.indexOf(\"aboveHTML\") != -1 ||\n location.indexOf(\"belowHTML\") != -1 ||\n location.indexOf(\"firstChildOfNode\") != -1 ||\n location.indexOf(\"lastChildOfNode\") != -1))\n {\n if (partList)\n {\n //select the correct match and assign it to existingNode\n for (var j=0; j < partList.length; j++)\n {\n //if we have a match, set existingNode and break\n if (extPart.parametersMatch(partName, paramArray[i], partList[j].parameters))\n {\n if (extPart.getVersion(partName) >= 5.0)\n {\n existingNodeSegment = new NodeSegment(partList[j].participantNode, partList[j].matchRangeMin, partList[j].matchRangeMax);\n }\n else\n {\n existingNodeSegment = new NodeSegment(partList[j].participantNode);\n }\n break;\n }\n }\n }\n }\n\n priorNodeSegmentArray.push(existingNodeSegment);\n }\n }\n\n //identify the prior nodes which need to be deleted\n //(no need to delete attributes because their values get replaced anyhow\n if (sbObj && location.indexOf(\"nodeAttribute+\") == -1) {\n for (var i=0; i < sbPartList.length; i++) {\n var nodeSegment = sbPartList[i].getNodeSegment();\n if (sbPartList[i].getName() == partName) {\n for (var j=0; j < priorNodeSegmentArray.length; j++) {\n if (priorNodeSegmentArray[j] != null &&\n nodeSegment.equals(priorNodeSegmentArray[j])) {\n break;\n }\n }\n if (j == priorNodeSegmentArray.length) {\n deleteNodeSegmentArray.push(nodeSegment);\n }\n }\n }\n }\n }\n\n\n //delete the extra multiple parameters\n if (deleteNodeSegmentArray != null) {\n for (var i=0; i < deleteNodeSegmentArray.length; i++) {\n var priorNodeSegment = deleteNodeSegmentArray[i];\n if (priorNodeSegment && !extUtils.isDependentNodeSegment(priorNodeSegment, true)) {\n\n if (extPart.DEBUG) alert(\"deleting the existing node: \" + partName);\n\n //delete the existing node\n sbPart = sbObj.getNamedSBPart(partName, priorNodeSegment.node);\n var weight = sbPart.getWeight();\n\n var optionFlags = 0;\n if (sbPart.getVersion() < 5.0)\n {\n optionFlags = docEdits.QUEUE_DONT_MERGE;\n }\n\n extPart.queueDocEdit(partName, \"\", priorNodeSegment, weight, null, optionFlags);\n }\n }\n }\n\n var optionFlags = 0;\n if (extPart.getVersion(partName) < 5.0)\n {\n optionFlags = docEdits.QUEUE_DONT_MERGE;\n }\n\n //now insert the new edits\n for (var index=0; index < paramArray.length; index++) {\n\n paramObj = paramArray[index];\n\n if (extPart.DEBUG) alert(\"adding edits for participant: \" + partName + \" [\"+ index + \"]\");\n\n var insertNode = extPart.getInsertNode(partName, paramObj);\n\n //handle the create link insert node\n if (typeof insertNode == \"string\" &&\n insertNode.indexOf(\"createAtSelection\") == 0)\n {\n if (location.indexOf(\"nodeAttribute\") == 0)\n {\n //get the tag and attribute names\n\n var whereToSearch = extPart.getWhereToSearch(partName);\n var tagName = whereToSearch.substring(whereToSearch.indexOf(\"+\") + 1);\n var attrName = location.substring(location.indexOf(\"+\") + 1);\n\n //get the text to insert within the tag from the insert node info\n var tagText = \"\";\n if (insertNode.indexOf(\"+\") != -1) {\n tagText = insertNode.substring(insertNode.indexOf(\"+\") + 1);\n }\n\n //create the insertion string\n insertText = extPart.getInsertText(partName, paramObj);\n insertText = \"<\" + tagName + \" \" + attrName + \"=\\\"\" + insertText + \"\\\">\"+ tagText + \"</\" + tagName + \">\";\n\n if (extPart.DEBUG) alert(\"adding new tag at selection for part: \" + partName);\n\n //add to the docEdits\n docEdits.queue(insertText,false,\"replaceSelection\", null, optionFlags);\n\n break;\n }\n else\n {\n // We are creating the node which these are relative to,\n // so change the weight to selection relative.\n if (location.indexOf(\"beforeNode\") == 0)\n {\n location = \"beforeSelection\";\n }\n else if (location.indexOf(\"afterNode\") == 0)\n {\n location = \"afterSelection\";\n }\n else if (location.indexOf(\"replaceNode\") == 0)\n {\n location = \"replaceSelection\";\n }\n }\n }\n\n\n //handle the wrapSelection location\n if (location.indexOf(\"wrapSelection\") == 0)\n {\n var insertText = extPart.getInsertText(partName, paramObj);\n\n if (!sbObj) {\n\n if (paramObj.MM_selection != null) {\n tagText = paramObj.MM_selection;\n } \n else \n {\n tagText = dwscripts.fixUpSelection(dw.getDocumentDOM(), false, false);\n }\n\n var match = insertText.match(/<([^<>%\\s]+)/g);\n\n if (match && (match.length > 0))\n {\n for (var i = 0; i < match.length; i ++)\n {\n match[i] = match[i].substring(1);\n }\n\n // check if insert text already has a close tag, and remove it if found\n\n var closeTagPos = insertText.search(RegExp(\"<\\\\/\"+ match[match.length-1], \"i\"));\n\n if (closeTagPos != -1)\n {\n insertText = insertText.substring(0, closeTagPos);\n }\n\n // now create the full string\n // closing tags go on in reverse order\n\n insertText = insertText + tagText;\n\n for (var i = (match.length - 1); i >= 0; i--)\n {\n insertText += \"</\" + match[i] + \">\";\n }\n }\n\n if (extPart.DEBUG) alert(\"wrapping tag around selection for part: \" + partName);\n\n //add to the docEdits\n docEdits.queue(insertText, false, \"replaceSelection\", null, optionFlags);\n }\n else\n {\n var priorSBPart = sbObj.getNamedSBPart(partName);\n var priorNodeSegment = (priorSBPart) ? priorSBPart.getNodeSegment() : null;\n\n if (priorNodeSegment != null) {\n\n if (extPart.DEBUG) alert(\"wrapping tag around selection for part: \" + partName);\n\n //add to the docEdits\n extPart.updateExistingNodeSegment(partName, priorNodeSegment, paramObj, \"replaceSelection\");\n\n }\n }\n\n break;\n }\n\n\n var priorNodeSegment = null;\n var existingNodeSegment = null;\n var updateNodeSegment = null;\n\n if (priorNodeSegmentArray != null)\n {\n //if we already identified the existing node, just set it\n existingNodeSegment = priorNodeSegmentArray[index];\n }\n else\n {\n //try and find the prior node\n //if re-edit, set the priorNode\n if (sbObj)\n {\n var priorSBPart = sbObj.getNamedSBPart(partName);\n priorNodeSegment = (priorSBPart) ? priorSBPart.getNodeSegment() : null;\n\n if (sbObj.getForcePriorUpdate() &&\n sbObj.getForcePriorUpdate().indexOf(partName) != -1)\n {\n updateNodeSegment = priorNodeSegment;\n }\n }\n\n //look for an existing match on the page,\n //if the insert location is aboveHTML, belowHTML, or the child of a node\n if ((!updateNodeSegment && !existingNodeSegment) &&\n (location.indexOf(\"aboveHTML\") != -1 ||\n location.indexOf(\"belowHTML\") != -1 ||\n location.indexOf(\"firstChildOfNode\") != -1 ||\n location.indexOf(\"lastChildOfNode\") != -1))\n {\n var partList = dw.getParticipants(partName);\n if (partList)\n {\n //get possible family name\n var familyName = extGroup.getFamily(groupName,paramObj);\n\n var ignoreFamily = false;\n if (paramObj.MM_ignoreFamily && paramObj.MM_ignoreFamily.indexOf(partName) != -1)\n {\n ignoreFamily = true;\n }\n\n //select the correct match and assign it to existingNode\n for (var j=0; j < partList.length; j++)\n {\n //get the node information\n extPart.extractNodeParam(partName, partList[j].parameters, partList[j].participantNode);\n if (extPart.getVersion(partName) >= 5.0)\n {\n var nodeSeg = new NodeSegment(partList[j].participantNode, partList[j].matchRangeMin, partList[j].matchRangeMax);\n }\n else\n {\n var nodeSeg = new NodeSegment(partList[j].participantNode);\n }\n \n // Check to make sure we have a valid node segment\n if (nodeSeg.node == null)\n {\n nodeSeg = null;\n }\n \n //if we have a match, set existingNode and break\n if (extPart.parametersMatch(partName, partList[j].parameters, paramObj))\n {\n existingNodeSegment = nodeSeg;\n break;\n }\n else if (!ignoreFamily && location.indexOf(\"HTML\")!=-1 && extUtils.onlyFamilyReferences(nodeSeg, familyName, paramObj.MM_ignoreOtherFamilies))\n {\n //if aboveHTML or belowHTML, check for family references, and may re-use an orphaned node\n updateNodeSegment = nodeSeg;\n //don't break, continue looking, in case there is an exact match\n }\n }\n }\n\n }\n\n //if we found both an existingNode and a node to update, choose the exact match\n if (existingNodeSegment && updateNodeSegment) {\n updateNodeSegment = null;\n }\n\n //if we did not find and existing or update segment, check if we can update\n // the prior node. This is possible if no other server behaviors depend\n // on the node.\n if (priorNodeSegment && !existingNodeSegment && !updateNodeSegment && !extUtils.isDependentNodeSegment(priorNodeSegment,!ignoreFamily)) {\n updateNodeSegment = priorNodeSegment;\n }\n\n }\n\n if (updateNodeSegment != null)\n {\n //change the existing node to match the new parameters\n //if prior object being updated, pass that weight. Otherwise, pass new location weight\n if (sbObj) {\n extPart.updateExistingNodeSegment(partName, updateNodeSegment, paramObj,\n sbObj.getNamedSBPart(partName, updateNodeSegment.node).getWeight()\n );\n } else {\n extPart.updateExistingNodeSegment(partName, updateNodeSegment, paramObj, location);\n }\n\n if (priorNodeSegment && !updateNodeSegment.equals(priorNodeSegment) &&\n !extUtils.isDependentNodeSegment(priorNodeSegment, true)) {\n\n if (extPart.DEBUG) alert(\"deleting the existing node: \" + partName);\n\n //delete the existing node\n extPart.queueDocEdit(partName, \"\", priorNodeSegment,\n sbObj.getNamedSBPart(partName, priorNodeSegment.node).getWeight(),\n null, optionFlags);\n }\n }\n else if (existingNodeSegment != null)\n {\n //correct node was found, possibly delete prior\n if (extPart.DEBUG) alert(\"correct node found, no change needed: \" + partName);\n\n //can we delete the existing one.\n if ( priorNodeSegment && !existingNodeSegment.equals(priorNodeSegment)\n && !extUtils.isDependentNodeSegment(priorNodeSegment,true)\n )\n {\n //delete the existing node\n extPart.queueDocEdit(partName, \"\", priorNodeSegment,\n sbObj.getNamedSBPart(partName, priorNodeSegment.node).getWeight(),\n null, optionFlags);\n }\n\n //add no-op node as positional placeholder so docEdits class knows how to order same-weight inserts\n docEdits.queue(null, existingNodeSegment, location);\n\n }\n else if (!sbObj || extPart.getSearchPatterns(partName).length)\n { //add node for first time\n if (extPart.DEBUG) alert(\"inserting new node: \" + partName + \" with weight \" + location);\n\n var insertText = extPart.getInsertText(partName, paramObj);\n\n docEdits.queue(insertText, false, location, insertNode, optionFlags);\n }\n //else\n //{\n // if (extPart.DEBUG) alert(\"skipping re-add of removed node: \" + partName + \" with weight \" + location);\n //}\n }\n } else {\n if (extPart.DEBUG) alert(\"skipping apply of empty participant: \" + partName);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subtract and carry register from A | subcReg(register) {
const sum = regA[0] - register[0] - ((regF[0] & F_CARRY) ? 1 : 0);
regA[0] = sum;
// TODO: test carry register
regF[0] = F_OP | (regA[0] ? 0 : F_ZERO) | ((sum < 0) ? F_CARRY : 0);
if ((regA[0] ^ register[0] ^ sum) & 0x10) regF[0] |= F_HCARRY;
return 4;
} | [
"function byteopsCSubQ(a) {\r\n a = a - paramsQ; // should result in a negative integer\r\n // push left most signed bit to right most position\r\n // remember javascript does bitwise operations in signed 32 bit\r\n // add q back again if left most bit was 0 (positive number)\r\n a = a + ((a >> 31) & paramsQ);\r\n return a;\r\n}",
"ADCn() {\n let a = regA[0];\n const m = MMU.rb(regPC[0]);\n a += m + ((regF[0] & F_CARRY) ? 1 : 0);\n regPC[0]++;\n regA[0] = a;\n regF[0] = ((a > 0xFF) ? F_CARRY : 0) | (regA[0] ? 0 : F_ZERO);\n if ((regA[0] ^ m ^ a) & 0x10) regF[0] |= F_HCARRY;\n return 8;\n }",
"static mxSub(a,b) { \r\n\t\tvar res = new mx4(); \t\t\r\n\t\tfor (var i=0; i<16; ++i) { res.M[i] = a.M[i] - b.M[i]; }\r\n\t\treturn res; \r\n\t}",
"minus() {\n this._lastX = this.pop();\n let first = this.pop();\n this._stack.push(first - this._lastX);\n }",
"function byteopsMontgomeryReduce(a) {\r\n var u = int16(int32(a) * paramsQinv);\r\n var t = u * paramsQ;\r\n t = a - t;\r\n t >>= 16;\r\n return int16(t);\r\n}",
"function mySubtractFunction(number1, number2) {\n console.log(number1 - number2);\n}",
"function SUBTRACT() {\n for (var _len14 = arguments.length, values = Array(_len14), _key14 = 0; _key14 < _len14; _key14++) {\n values[_key14] = arguments[_key14];\n }\n\n // Return `#NA!` if 2 arguments are not provided.\n if (values.length !== 2) {\n return error$2.na;\n }\n\n // decompose values into a and b.\n var a = values[0];\n var b = values[1];\n\n // Return `#VALUE!` if either a or b is not a number.\n\n if (!ISNUMBER(a) || !ISNUMBER(b)) {\n return error$2.value;\n }\n\n // Return the difference.\n return a - b;\n}",
"subtract(duration) {\n return (0, $5c0571aa5b6fb5da$export$6814caac34ca03c7)(this, duration);\n }",
"function getSum(a, b) { \n return b == 0 ? a : getSum(a ^ b, (a & b) << 1)\n}",
"subtract(duration) {\n return (0, $5c0571aa5b6fb5da$export$fe34d3a381cd7501)(this, duration);\n }",
"function leftCircularShift(num,bits){\nnum = num.toString(2);\nnum = parseInt(num.substr(1,num.length-1)+num.substr(0,1),2);\nnum = parseInt(num,2);\nreturn num;\n}",
"subtract(duration) {\n return (0, $5c0571aa5b6fb5da$export$4e2d2ead65e5f7e3)(this, duration);\n }",
"function subb(a, b) {\n return b - a;\n}",
"complement(){\n this.dna = complementStrand(this.dna);\n }",
"subtract(otherColor) {\n return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);\n }",
"async substract(key, value) {\nif(!key) throw new Error('No key was given')\n if(!value) throw new Error('No value was given')\n if (typeof(value) != 'Number') throw new Error('The value must be a number')\n this.substract(key, value) \n }",
"static vSub(a,b) { return newVec(a.x-b.x,a.y-b.y,a.z-b.z); }",
"function subtractVectors(a, b) {\r\n return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];\r\n}",
"static subtract(map_a, map_b){\n let subtracted = MapSet.deep_copy(map_a)\n for( let key of map_b.keys()){\n if(map_a.has(key)){\n let value = map_a.get(key) - map_b.get(key)\n if(value <= 0)\n subtracted.delete(key)\n else\n subtracted.set(key, value)\n }\n }\n return subtracted\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the environment variables from the specified file. | function getEnvVarsFromFile(envFile) {
const envVars = Object.assign({}, process.env)
if (process.env.APPDATA) {
envVars.APPDATA = process.env.APPDATA
}
// Read from the JSON file.
const jsonString = fs.readFileSync(path.resolve(process.cwd(), envFile), {
encoding: "utf8"
})
const varsFromFile = JSON.parse(jsonString)
Object.assign(envVars, flattenVars(varsFromFile))
return envVars
} | [
"get environment() {\n if (this._enviornment)\n return Promise.resolve(this._enviornment);\n return fs.readFile(this.environmentPath).then((file) => __awaiter(this, void 0, void 0, function* () {\n let localEnvironment = jsonc.parse(file.toString());\n if (!localEnvironment.names || !Array.isArray(localEnvironment.names)) {\n throw new Error('Local environment.json is not properly configured.');\n }\n this._enviornment = localEnvironment;\n return localEnvironment;\n }));\n }",
"loadEnv() {\n let env = dotenvExtended.load({\n silent: false,\n path: path.join(this.getProjectDir(), \".env\"),\n defaults: path.join(this.getProjectDir(), \".env.defaults\")\n });\n\n const options = minimist(process.argv);\n for (let option in options) {\n if (option[0] === \"-\") {\n let value = options[option];\n option = option.slice(1);\n if (option in env) {\n env[option] = value.toString();\n }\n }\n }\n env = dotenvParseVariables(env);\n env = dotenvExpand(env);\n\n this.env = { ...env, project_dir: this.getProjectDir() };\n }",
"loadEnvironmentHostnames() {\n let hostNames = path.join(this.projectFolder, \"hostnames.json\");\n return this.utils.readJsonFile(hostNames);\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 }",
"function loadConfig() {\n var config = JSON.parse(require('fs').readFileSync(__dirname + '/defaults.json', 'utf-8'));\n for (var i in config) {\n config[i] = process.env[i.toUpperCase()] || config[i];\n }\n return config;\n}",
"loadEnvVarsForLocal() {\n const defaultEnvVars = {\n IS_LOCAL: 'true',\n };\n\n _.merge(process.env, defaultEnvVars);\n\n // Turn zero or more --env options into an array\n // ...then split --env NAME=value and put into process.env.\n _.concat(this.options.env || []).forEach(itm => {\n const splitItm = _.split(itm, '=');\n process.env[splitItm[0]] = splitItm[1] || '';\n });\n\n return BbPromise.resolve();\n }",
"function readOurFileOptions(file) {\n return read(file.options, emptyFileOptions, OurFileOptions);\n}",
"async readConfigFile(configFilePath) {\n let tailwindConfigFile = nova.fs.open(configFilePath)\n let contents = tailwindConfigFile.readlines()\n let newContents = ''\n\n tailwindConfigFile.close()\n\n // Remove any lines including the require, such as 'require('@tailwindcss/forms')'\n contents.forEach((line) => {\n if (!line.includes('require(')) {\n newContents = newContents + line\n }\n })\n\n let configObject = eval(newContents)\n\n return configObject\n }",
"function getEnv() {\n\tvar store = JSON.parse(localStorage.getItem(\"AtmosphereEnv\"));\n\tif ((store !== undefined) && (store !== null)) env = store;\n}",
"function fromEnv$1() {\n return function () {\n var accessKeyId = process.env[ENV_KEY];\n var secretAccessKey = process.env[ENV_SECRET];\n var expiry = process.env[ENV_EXPIRATION];\n if (accessKeyId && secretAccessKey) {\n return Promise.resolve({\n accessKeyId: accessKeyId,\n secretAccessKey: secretAccessKey,\n sessionToken: process.env[ENV_SESSION],\n expiration: expiry ? new Date(expiry) : undefined,\n });\n }\n return Promise.reject(new ProviderError(\"Unable to find environment variable credentials.\"));\n };\n}",
"function separateEnvironmentVariablesSet() {\n var varsToFind = [EnvironmentVariables.AZURE_SERVICEBUS_NAMESPACE,\n EnvironmentVariables.AZURE_SERVICEBUS_ACCESS_KEY];\n return varsToFind.every(function (v) { return !!process.env[v]; });\n}",
"function getNodeEnvFromProcess() {\n var nodeEnv = (process.env[NODE_ENV_KEY] || '').toUpperCase(),\n available = false;\n\n if (nodeEnv) {\n /* make sure the nodeEnv is an available value */\n available = nodeEnv in NODE_ENV;\n\n if (!available) {\n logger.warn('[NODE_ENV] %s is not an available NODE_ENV value, ' +\n ', currently only accept the following values: %s', nodeEnv,\n Object.keys(NODE_ENV).map(function(key) {\n return NODE_ENV[key];\n }).join(', '));\n\n /* if not known, fallback to default value. */\n nodeEnv = DEFAULT_NODE_ENV;\n } else {\n nodeEnv = NODE_ENV[nodeEnv];\n }\n } else {\n logger.warn('Failed to find NODE_ENV value' +\n ', fallback to default value: %s.', DEFAULT_NODE_ENV);\n\n nodeEnv = DEFAULT_NODE_ENV;\n }\n\n /* update prcoess.env with new value */\n updateProcessEnv(NODE_ENV_KEY, nodeEnv);\n\n return nodeEnv;\n}",
"async getCredentials(keyFile) {\n const ext = path.extname(keyFile);\n switch (ext) {\n case '.json': {\n const key = await readFile(keyFile, 'utf8');\n const body = JSON.parse(key);\n const privateKey = body.private_key;\n const clientEmail = body.client_email;\n if (!privateKey || !clientEmail) {\n throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS');\n }\n return { privateKey, clientEmail };\n }\n case '.der':\n case '.crt':\n case '.pem': {\n const privateKey = await readFile(keyFile, 'utf8');\n return { privateKey };\n }\n case '.p12':\n case '.pfx': {\n // NOTE: The loading of `google-p12-pem` is deferred for performance\n // reasons. The `node-forge` npm module in `google-p12-pem` adds a fair\n // bit time to overall module loading, and is likely not frequently\n // used. In a future release, p12 support will be entirely removed.\n if (!getPem) {\n getPem = (await Promise.resolve().then(() => __nccwpck_require__(2119))).getPem;\n }\n const privateKey = await getPem(keyFile);\n return { privateKey };\n }\n default:\n throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' +\n 'Current supported extensions are *.json, *.pem, and *.p12.', 'UNKNOWN_CERTIFICATE_TYPE');\n }\n }",
"function getEnvSetting(confKey) {\n return CONFIGURATION_VARS[confKey].envValue;\n}",
"function getFromFile() {\n try {\n const proxyPath = path.resolve(`${process.cwd()}/${config.proxy_file}`);\n return JSON.parse(fs.readFileSync(proxyPath, \"utf8\"));\n } catch (e) {\n return null;\n }\n }",
"function loadJSON(file) {\n return JSON.parse(FS.readFileSync(file, \"utf8\"));\n}",
"function readFile() {\n return fs.readFileSync(path.join.apply(path, arguments), 'utf8');\n}",
"function validateEnvFile() {\n // Validate DEPLOYMENT_PATH\n const deploymentPath = string('DEPLOYMENT_PATH', '');\n const isValidDeploymentPath =\n deploymentPath === '' ||\n (deploymentPath.charAt(0) === '/' &&\n deploymentPath.charAt(deploymentPath.length - 1) !== '/');\n\n if (!isValidDeploymentPath) {\n throw new Error(\n 'Deployment path must start with a slash and end without one: e.g. /something'\n );\n }\n // VALIDATE DEPLOYMENT\n const deployment = string('DEPLOYMENT', '');\n if (\n deployment !== '' &&\n deployment !== 'production' &&\n deployment !== 'staging' &&\n deployment !== 'development'\n ) {\n throw new Error(\n 'Trying to configure an unknow deployment value, allowed ones are [\"production\", \"staging\", \"development\"]'\n );\n }\n}",
"function getEnv() {\n env = env || new Benchmine.Env();\n\n return env;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the template of the ship based on type | getTemplate(type) {
switch (type) {
case SHIP_TYPE_1:
return SHIP_TYPE_1_TEMPLATE;
case SHIP_TYPE_2:
return SHIP_TYPE_2_TEMPLATE;
case SHIP_TYPE_3:
return SHIP_TYPE_3_TEMPLATE;
}
} | [
"getTemplate(tname) {\n let template = this.templates[tname]\n if (!template) {\n template = new Template(this, tname);\n this.templates[tname] = template;\n }\n return template;\n }",
"getTemplate(name) {\n return this.templates.find(template => template.name === name);\n }",
"function getTemplate() {\n if (!$scope.state || _.indexOf($scope.viewStates, $scope.state) === -1) {\n throw new Error('Missing $scope.state');\n }\n var template;\n switch ($scope.state) {\n case 'upsell':\n template = 'enterprise/templates/reports-partial-upsell.html';\n break;\n case 'monthly':\n template = 'enterprise/templates/reports-partial-monthly.html';\n break;\n case 'csv':\n template = 'enterprise/templates/reports-partial-csv.html';\n break;\n }\n return template;\n }",
"getPlacementCampaign(){\n\n let {type, config} = this.state;\n\n switch(type) {\n case StaticBannerPlacementType.getName():\n return <StaticBannerPlacementType image={config.image} link={config.link}/>\n break;\n case HtmlBannerPlacementType.getName():\n return <HtmlBannerPlacementType />\n break;\n default:\n return null;\n }\n\n }",
"function setTemplate() {\n return {\n species: \"\",\n nickname: \"\",\n gender: \"\",\n ability: \"\",\n evs: statTemplate(0),\n ivs: statTemplate(31),\n nature: \"\",\n item: \"\",\n moves: [],\n other: {},\n };\n}",
"getType(){\n const { type } = this.props\n if (type) return type\n return \"posts\"\n }",
"function getDealTemplate() {\n const templateContent = $('[data-role=\"deal-template\"]').get(0).content;\n return $(templateContent).find('[data-role=\"deal\"]');\n}",
"getModel() {\n switch (this.shipper_name.toUpperCase()) {\n case \"UPS\":\n return new UPSShippingModel()\n case \"DHL\":\n return new DHLShippingModel()\n case \"WUUNDER\":\n return new WuunderShippingModel()\n case \"PACKLINK\":\n return new PacklinkShippingModel()\n case 'MANUAL':\n return new ManualShippingModel()\n default:\n throw Boom.badData('(Preferred) ShippingModel is not supported', this.data)\n }\n }",
"function getTemplateByName(req, res) {\n\tqueryName(req.swagger.params.name.value, function(array){\n\t\tif (array.length > 0) {\n\t\t\tres.json(array[0]);\n\t\t} else {\n\t\t\tres.statusCode = 404;\n\t\t\tres.json({message: \"Not Found\"});\n\t\t}\n\t});\n}",
"function getProductFromTemplate(string) {\n if (string.indexOf('governance') >= 0) {\n return 'idg';\n }\n else if (string.indexOf('commons') >= 0) {\n return 'commons';\n }\n else if (string.indexOf('access-request') >= 0) {\n return 'access-request';\n }\n else {\n __.requestError(\"template ids must include 'governance', 'access-request', or 'commons' in them.\", 500);\n }\n}",
"SetNovaTemplate(num) { return [\"Adjacent foes\", \"Medium Burst Template\", \"Large Burst Template\"][num-1]; }",
"function Template(props) {\n return __assign({ Type: 'AWS::SES::Template' }, props);\n }",
"getType() {\n return this.type\n }",
"function pkgFromType(type) {\n const parts = type.split(\":\");\n if (parts.length === 3) {\n return parts[0];\n }\n return undefined;\n}",
"function getShipmentMethod(currentCart) {\n let cart = currentCart || Cart.findOne();\n if (cart) {\n if (cart.shipping) {\n if (cart.shipping[0].shipmentMethod) {\n return cart.shipping[0].shipmentMethod;\n }\n }\n }\n return undefined;\n}",
"function getNoteTemplate(noteObj, noteTemplate) {\n noteDiv = noteMaker(noteObj, noteTemplate).firstChild;\n content.insertBefore(noteDiv, content.childNodes[0]);\n noteDiv.classList.add('show');\n noteDiv.classList.remove('hide');\n }",
"function loadTemplate() {\n\t\t\t\t\t// template url\n\t \tvar url = '/spot/partials/filters.html';\n\t\t\t\t\treturn $templateCache.get(url) || $http.get(url, { cache : true });\n\t\t\t\t}",
"getTranslationString(type) {\n let userString;\n let tts = this.get('typeToString');\n userString = tts[type];\n\n if (userString === undefined) {\n for (let ts in tts) {\n if (type.toLowerCase().indexOf(ts) !== -1) {\n userString = tts[ts];\n break;\n }\n }\n }\n\n if (userString === undefined) {\n userString = type;\n }\n\n return userString;\n }",
"function getItemSubType() {\n return new RegExp(`^${template.bug.headlines[0]}`).test(itemBody)\n ? ItemSubType.bug\n : new RegExp(`^${template.feature.headlines[0]}`).test(itemBody)\n ? ItemSubType.feature\n : new RegExp(`^${template.pr.headlines[0]}`).test(itemBody)\n ? ItemSubType.pr\n : undefined;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the request type from the intent or returns an error | function getRequestTypeFromIntent(request) {
console.log('entering getRequestTypeFromIntent function');
var dataTypeSlot = request.slot('DataType');
// slots can be missing, or slots can be provided but with empty value.
// must test for both.
if (!dataTypeSlot) {
return {
error: true
}
} else {
var capsDataType = dataTypeSlot.toUpperCase();
console.log('capsDataType = ' + capsDataType );
for (var i = 0; i < dataTypes.length; i++) { // loop through each dataType (dataType[0] is products, dataType[1] is states...)
for (var x = 0; x < dataTypes[i].length; x++) { // loop through each array of possible dataType items (ex: products)
//console.log('dataTypes[i][x].ItemName = ' + dataTypes[i][x].ItemName)
if (dataTypes[i][x].ItemName == capsDataType) { //if one of the dataType items matches what the user specified
console.log('************* THERE IS A DATA TYPE MATCH *****************')
var dataType = dataTypes[i][x];
dataType.displayDataType = capsDataType;
return dataType;
}
}
}
// if the return above isn't triggered, return error:true because there was no match
return {
error: true,
displayDataType: capsDataType
}
}
} | [
"static isV1Request(request, type) {\n switch(type) {\n case DaxMethodIds.getItem:\n return !DynamoDBV1Converter._isArrayEmpty(request.AttributesToGet);\n case DaxMethodIds.batchGetItem:\n if(!DynamoDBV1Converter._isMapEmpty(request.RequestItems)) {\n for(const tableName of Object.getOwnPropertyNames(request.RequestItems)) {\n if(!DynamoDBV1Converter._isArrayEmpty(request.RequestItems[tableName].AttributesToGet)) {\n return true;\n }\n }\n }\n return false;\n case DaxMethodIds.putItem:\n case DaxMethodIds.deleteItem:\n return !DynamoDBV1Converter._isMapEmpty(request.Expected);\n case DaxMethodIds.updateItem:\n return !DynamoDBV1Converter._isMapEmpty(request.Expected) ||\n !DynamoDBV1Converter._isMapEmpty(request.AttributeUpdates);\n case DaxMethodIds.query:\n return (!DynamoDBV1Converter._isArrayEmpty(request.AttributesToGet) ||\n !DynamoDBV1Converter._isMapEmpty(request.QueryFilter) ||\n !DynamoDBV1Converter._isMapEmpty(request.KeyConditions));\n case DaxMethodIds.scan:\n return (!DynamoDBV1Converter._isArrayEmpty(request.AttributesToGet) ||\n !DynamoDBV1Converter._isMapEmpty(request.ScanFilter));\n case DaxMethodIds.batchWriteItem:\n return false;\n default:\n throw new DaxClientError('Invalid request type', DaxErrorCode.Validation, false);\n }\n }",
"function handleDataTypeDialogRequest(request, response) {\n\tconsole.log('entering handleDataTypeDialogRequest function');\n\n // Determine request type (inventory, sev 1's, service requests)\n var reqType = getRequestTypeFromIntent(request);\n\n if (reqType.error) {\n // Invalid request type. Prompt for request type which will re-fire DialogGetDataIntent\n\t\trepromptOutput = \"What would you like?\"\n speechOutput = \"I can provide information on \";\n\t\tif ( request.session('customerInfo') ) {\n\t\t\tspeechOutput += request.session('customerInfo').customerName;\n\t\t}\n\t\tspeechOutput += \" products, states and serial numbers. What would you like to hear about?\";\n response.say(speechOutput).reprompt(repromptOutput).shouldEndSession( false );\n\t\t// Must call send to end the original request\n\t\tresponse.send();\n return;\n }\n\n\t// set this so we have access to user's request type later\n\tresponse.session('dataType', reqType);\n if ( request.session('top3requestInFlight') ) { // the user first asked for the top 3 customers for a product, but didn't specify which product\n\t\thandleTop3Request(request, response) // execute handleTop3Request now that we have the product they are interested in\n\t} else { // this was not a top 3 product request\n\t\t// if we don't have a customer name yet, go get it. If we have a customer name/gdun, perform the final request\n\t\tif ( request.session('customerInfo') ) {\n\t\t\tgetSpecificRequest( request.session('customerInfo'), reqType, request, response );\n\t\t} else {\n\t\t\t// The user provided the request type but no customer name. Prompt for customer name.\n\t\t\tspeechOutput = \"Which customer would you like \" + reqType.displayDataType + \" information for?\";\n\t\t\trepromptOutput = \"For which customer?\";\n\t\t\tresponse.say(speechOutput).reprompt(repromptOutput).shouldEndSession( false );\n\t\t\t// Must call send to end the original request\n\t\t\tresponse.send();\n\t\t}\n\t}\n}",
"getType () {\n\t\tlet type = this.definition.type;\n\n\t\t// if it's not a relationship or fetched property, it's an attribute\n\t\t// NOTE: Probably need to separate this out into different classes\n\t\ttype !== 'relationship' && type !== 'fetched' && (type = 'attribute');\n\n\t\treturn type;\n\t}",
"static get __resourceType() {\n\t\treturn 'MedicationRequestDispenseRequest';\n\t}",
"function handleRequest(req, res, urn){\n if(!isRequestValid(req)){\n return res.status(500).json({\n status: 'error',\n message: \"Fields required: \" + activityFields + \" and incorrect type required: Create, Update or Delete\"\n });\n }else return forwardRequest(req, res, urn);\n}",
"selectRequestType(type) {\n\t\t// if this is 'doctor on call' or 'doctor hour' show specialities list\n\t\tif (type.id == 0 || type.id == 3) {\n\t\t\tthis.selectedRequestData = this.CalendarService.dataSource.specialities;\n\t\t\tthis.selectedRequestType = \"specialities\";\n\t\t} else {\n\n\t\t\t// if type is 2 filter by 'procedures' if type is 1 filter by 'med tests'\n\t\t\tif (type.id == 1) {\n\t\t\t\tthis.selectedRequestData = _filter(this.CalendarService.dataSource.services, (service) => {\n\t\t\t\t\treturn service.type == 1;\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (type.id == 2) {\n\t\t\t\tthis.selectedRequestData = _filter(this.CalendarService.dataSource.services, (service) => {\n\t\t\t\t\treturn service.type == 0;\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.selectedRequestType = \"services\";\n\t\t}\n\n\t\t// To show active class\n\t\tthis.typeSelected = type;\n\t\tthis.selectedRequestData.sort(function(a,b){\n\t\t\treturn b.requests.length - a.requests.length;\n\t\t});\n\t\tthis.filteredData = this.selectedRequestData;\n\t}",
"static get __resourceType() {\n\t\treturn 'SupplyRequestWhen';\n\t}",
"function getSearchType() {\n if ('/search/quick.url' === $(location).attr('pathname')) return 'Quick';\n else if ('/search/expert.url' === $(location).attr('pathname')) return 'Expert';\n else if ('/search/thesHome.url' === $(location).attr('pathname')) return 'Thes';\n }",
"get icon_type() {\n return this.args.icon_type;\n }",
"function getChallengeType() {\r\n return new Promise((resolve, reject) => {\r\n dashboardModel.getChallengeType().then((data) => {\r\n resolve({ code: code.OK, message: '', data: data })\r\n }).catch((err) => {\r\n if (err.message === message.INTERNAL_SERVER_ERROR)\r\n reject({ code: code.INTERNAL_SERVER_ERROR, message: err.message, data: {} })\r\n else\r\n reject({ code: code.BAD_REQUEST, message: err.message, data: {} })\r\n })\r\n })\r\n}",
"function getUrlType() {\n let url = document.location.href\n\n if(url.match(/http(s)?:\\/\\/open\\.spotify\\.com\\/playlist\\/.+/) != null)\n return 'playlist'\n\n if(url.match(/http(s)?:\\/\\/open\\.spotify\\.com\\/album\\/.+/) != null)\n return 'album'\n\n if(url.match(/http(s)?:\\/\\/open\\.spotify\\.com\\/collection\\/tracks/) != null)\n return 'collection'\n\n return 'other' // = Nothing of the above\n}",
"function pickVerb(req) {\n\t\t\tconst methodMap = {\n\t\t\t\tGET: 'read',\n\t\t\t\tDELETE: 'delete',\n\t\t\t\tPOST: 'create',\n\t\t\t\tPUT: 'update',\n\t\t\t\tPATCH: 'configure',\n\t\t\t\tHEAD: 'connect',\n\t\t\t\tOPTIONS: 'allow',\n\t\t\t\tVIEW: 'monitor',\n\t\t\t};\n\n\t\t\tif (req.method && methodMap[req.method]) {\n\t\t\t\treturn methodMap[req.method];\n\t\t\t} else {\n\t\t\t\treturn 'monitor';\n\t\t\t}\n\t\t}",
"_getSelectionItemType()\n {\n var keys = this.getSelectedItemKeys();\n var itemType = null;\n var urls = [];\n for (var index in keys)\n {\n var item = this.getSelectedItem(keys[index]);\n if (itemType === null)\n {\n itemType = item.constructor;\n }\n }\n return itemType;\n }",
"async orderTypeValidator(promptContext) {\n const userProfile = await this.userProfileAccessor.get(promptContext.context);\n PizzaBot.addPromptMessageToMessages(userProfile, promptContext.attemptCount, promptContext.options);\n try {\n // get luis prediction with user message after prompt\n const luisPrediction = await predict(promptContext.recognized.value);\n const topIntent = luisPrediction.topScoringIntent.intent;\n // update orderType if intent matches otherwise return false\n if(topIntent.includes(\"pizza\") && topIntent !== luisIntents.pizzaOrder) {\n userProfile.in.orderType = topIntent === luisIntents.pizzaDelivery ? \"delivery\" : \"pickup\";\n await this.userProfileAccessor.set(promptContext.context, userProfile);\n return true; \n } else {\n return false;\n }\n } catch (error) {\n logger.error(error);\n await promptContext.context.sendActivity(\"I'm sorry for the inconvinience but i can't help\" +\n \" you right now. Please try to contact me later\");\n return false;\n }\n }",
"function isReqXml( req ) {\n\tlet headers = req.headers;\n\treturn ( 'content-type' in headers\n\t\t\t && ( headers['content-type'].includes( 'xml' ) ||\n\t\t\t\t headers['content-type'].includes( 'XML' )));\n}",
"getType(){\n const { type } = this.props\n if (type) return type\n return \"posts\"\n }",
"commandType() {\n const { 0: com } = __classPrivateFieldGet(this, __command);\n // console.log(\"com\", com);\n const type = __classPrivateFieldGet(this, _cType).get(com);\n // if (!type) throw new Error(\"Syntax Error\");\n return type;\n }",
"processRequest_() {\n /**\n * Dialogflow action or null if no value\n * https://dialogflow.com/docs/actions-and-parameters\n * @type {string}\n */\n this.agent.action = this.agent.request_.body.result.action;\n debug(`Action: ${this.agent.action}`);\n\n /**\n * Dialogflow parameters included in the request or null if no value\n * https://dialogflow.com/docs/actions-and-parameters\n * @type {Object[]}\n */\n this.agent.parameters = this.agent.request_.body.result.parameters;\n debug(`Parameters: ${JSON.stringify(this.agent.parameters)}`);\n\n /**\n * Dialogflow contexts included in the request or null if no value\n * https://dialogflow.com/docs/contexts\n * @type {string}\n */\n this.agent.contexts = this.agent.request_.body.result.contexts;\n debug(`Input contexts: ${JSON.stringify(this.agent.contexts)}`);\n\n /**\n * Dialogflow fulfillment included in the request or null if no value\n * https://dialogflow.com/docs/fulfillment\n * * @type {string}\n */\n this.agent.fulfillment = this.agent.request_.body.result.fulfillment;\n debug(`Input fulfillment: ${JSON.stringify(this.agent.fulfillment)}`);\n\n /**\n * Dialogflow source included in the request or null if no value\n * https://dialogflow.com/docs/reference/agent/query#query_parameters_and_json_fields\n * @type {string}\n */\n if (this.agent.request_.body.originalRequest) {\n this.agent.requestSource =\n V1_TO_V2_PLATFORM_NAME[this.agent.request_.body.originalRequest.source];\n }\n // Use request source from original request if present\n if (\n !this.agent.requestSource &&\n this.agent.request_.body.originalRequest &&\n this.agent.request_.body.originalRequest.data\n ) {\n const requestSource = this.agent.request_.body.originalRequest.data\n .source;\n this.agent.requestSource = V1_TO_V2_PLATFORM_NAME[requestSource] || requestSource;\n }\n debug(`Request source: ${JSON.stringify(this.agent.requestSource)}`);\n\n /**\n * Original user query as indicated by Dialogflow or null if no value\n * @type {string}\n */\n this.agent.query = this.agent.request_.body.result.resolvedQuery;\n debug(`Original query: ${JSON.stringify(this.agent.query)}`);\n\n /**\n * Original request language code (i.e. \"en\")\n * @type {string} locale language code indicating the spoken/written language of the original request\n */\n this.agent.locale = this.agent.request_.body.lang;\n }",
"getType() {\n return this.type\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets info for all streamers on the twitchStreamers list | function getAllStreamersData(streamerList, onOfforAll) {
streamerList.forEach(function(streamer) {
var url = "https://wind-bow.glitch.me/twitch-api/streams/" + streamer;
var request = new XMLHttpRequest();
request.onload = function () {
if (request.status == 200) {
resultsObject = JSON.parse(request.responseText);
if (resultsObject.stream == null && onOfforAll != "onlineOnly") {
displayOfflineUsers(resultsObject, streamer);
} else if (onOfforAll != "offlineOnly") {
displayOnlineStreamers(resultsObject);
}
}
};
request.open("GET", url);
request.send(null);
});
} | [
"function getAllStreamers() {\r\n clearElements();\r\n getStreamData(\"all\");\r\n }",
"function getStreamList(streamPlayerList) {\n $(\".streams\").remove();\n $(\".streamlist\").append('<img id=\"loadingGIF\" src=\"loading.gif\" >');\n for (var i = 0; i < streamPlayerList.length; i++) {\n $.getJSON(\"https://api.twitch.tv/kraken/streams/\" + streamPlayerList[i] + \"/?callback=?\", function(data) {\n $(\"#loadingGIF\").remove();\n if (data.stream != null) {\n $(\"#streamlist\").append('<li id=\"' + data.stream.channel.name + '\" class=\"streams\"' + '\"></li>');\n $('#' + data.stream.channel.name).append('<img class=\"small_img\" src=\"' + data.stream.channel.logo + '\">');\n $('#' + data.stream.channel.name).append('<img class=\"cap_img\" src=\"' + data.stream.preview.medium + '\">');\n $('#' + data.stream.channel.name).append('<div class=\"topstrip\" id=\"' + data.stream.channel.name + '\"> ' + '<span class=\"streamviews\">' + data.stream.viewers + '</span>' + ' </div>');\n $('#' + data.stream.channel.name).append('<div class=\"bottomstrip\" id=\"' + data.stream.channel.name + '\"> ' + '<span class=\"streamname\">' + data.stream.channel.name + '</span>' + ' </div>');\n\n //Allows appended elements to be draggable\n $('#' + data.stream.channel.name).draggable({\n containment: '#draggablecontainer',\n opacity: '0.60',\n revert: true,\n revertDuration: 0,\n });\n }\n\n });\n } //end for\n }",
"function getOfflineStreamers() {\r\n clearElements();\r\n getStreamData(\"offline\");\r\n }",
"function callApi(streamer) {\n $.ajax({\n url: 'https://wind-bow.gomix.me/twitch-api/streams/' + streamer,\n dataType: 'jsonp',\n success: function(result) {\n var game = '';\n var logo;\n var logoHtml = '<div class=\"logo\"></div>';\n if (result.stream !== null) { // streamer is online\n logo = result.stream.channel.logo;\n game = result.stream.game;\n logoHtml = '<img src=\"' + logo + '\" alt=\"Streamer Logo\" class=\"logo\">';\n $('#' + streamer).addClass('online');\n renderApiInfo(streamer, game, logoHtml);\n } else { // streamer is offline\n $('#' + streamer).addClass('offline');\n $.ajax({\n url: 'https://wind-bow.gomix.me/twitch-api/channels/' + streamer,\n dataType: 'jsonp',\n success: function(result) {\n logo = result.logo;\n if (logo) {\n logoHtml = '<img src=\"' + logo + '\" alt=\"Streamer Logo\" class=\"logo\">';\n }\n renderApiInfo(streamer, game, logoHtml);\n }\n }); \n }\n }\n });\n }",
"loadDataStreamList() {\n this._dataStreamList = [];\n let servers = this.dataModelProxy.getUserConfig().getDashboardConfig().getServerList();\n let serverID = 0;\n for (let server in servers) {\n if (logging) console.log(\"Retrieving Datastreams from Server:\", servers[server].url);\n let sID = serverID;\n let cb = function(a) {\n this.dataStreamListAvailable(a, sID);\n };\n this.sensorThingsCommunications.getDataStreamList(servers[server].url, cb.bind(this));\n serverID++;\n }\n }",
"static getAllAccountStreams () {\n if (!SystemStreamsSerializer.allAccountStreams) {\n SystemStreamsSerializer.allAccountStreams = getStreamsNames(SystemStreamsSerializer.getAccountStreamsConfig(), allAccountStreams);\n }\n return SystemStreamsSerializer.allAccountStreams;\n }",
"broadcastPlayerList() {\n var response = [];\n // prepare the data\n this._players.forEach(p => {\n response.push(p.getPublicInfo());\n });\n // Send to all users\n this.emitToRoom(\"player-list\", response);\n }",
"function TwineToysGetTrackers() {\n return valueTrackers\n}",
"function init_stream_clients (callback) {\n console.log('init streamers');\n for (name in config.ClientList) {\n console.log('init streamer for', name);\n\n var call_args = ('args' in config.ClientList[name]) ? // } \n config.ClientList[name]['args'] : []; // }\n\n var sc = new StreamClient(\n name,\n config.ClientList[name]['endpoint'],\n config.ClientList[name]['call_name'],\n call_args );\n sc.run();\n }\n console.log('end init streamers');\n if (callback) callback();\n}",
"getSystemStreamsList () {\n if (!SystemStreamsSerializer.systemStreamsList) {\n let systemStreams = [];\n let i;\n const streamKeys = Object.keys(this.systemStreamsSettings);\n\n for (i = 0; i < streamKeys.length; i++) {\n systemStreams.push({\n name: streamKeys[i],\n id: SystemStreamsSerializer.addDotToStreamId(streamKeys[i]),\n parentId: null,\n children: buildSystemStreamsFromSettings(\n this.systemStreamsSettings[streamKeys[i]],\n [],\n SystemStreamsSerializer.addDotToStreamId(streamKeys[i])\n )\n });\n }\n SystemStreamsSerializer.systemStreamsList = systemStreams;\n }\n return SystemStreamsSerializer.systemStreamsList;\n }",
"function getTwitterTweets(screen_name) {\n socket.emit('user_tweets', { screen_name: screen_name });\n }",
"function showCorrectStreamers() {\n var search = $('input').val();\n var re = new RegExp('^' + search, 'i');\n var status = $('.notch').parent().attr('id');\n for (var i = 0; i < streamers.length; i++) {\n var $streamer = $('#' + streamers[i]);\n if ($streamer.hasClass(status)) {\n $streamer.show();\n }\n if (!re.test(streamers[i])) {\n $streamer.hide();\n }\n }\n }",
"getTeachers() {\n return getAllTeachers(this._code);\n }",
"static getReadableAccountStreams () {\n if (!SystemStreamsSerializer.readableAccountStreams){\n SystemStreamsSerializer.readableAccountStreams = getStreamsNames(\n SystemStreamsSerializer.getAccountStreamsConfig(),\n readable\n );\n }\n return SystemStreamsSerializer.readableAccountStreams;\n }",
"getAllSystemStreamsIds () {\n if (!SystemStreamsSerializer.allSystemStreamsIds) {\n let systemStreams = [];\n let i;\n const streamKeys = Object.keys(this.systemStreamsSettings);\n\n for (i = 0; i < streamKeys.length; i++) {\n systemStreams.push(SystemStreamsSerializer.addDotToStreamId(streamKeys[i]));\n _.merge(systemStreams,\n Object.keys(getStreamsNames(this.systemStreamsSettings[streamKeys[i]])))\n }\n SystemStreamsSerializer.allSystemStreamsIds = systemStreams;\n }\n return SystemStreamsSerializer.allSystemStreamsIds;\n }",
"function searchStreamers(input) {\n for (var i = 0; i < streamers.length; i++) {\n if(streamers[i].toLowerCase().includes(input)) {\n getStream(streamers[i], currentTab);\n }\n }\n}",
"function getAllPlayers() {\n var players = [];\n\n Object.keys(io.sockets.connected).forEach(function(socketId) {\n var player = io.sockets.connected[socketId].player;\n\n if (player) {\n players.push(player);\n }\n });\n\n return players;\n}",
"listSockets() {\n var list = this.players.map(player => player.socketID);\n list.push(this.hostID);\n return list;\n }",
"function addStreamerDiv(streamer) {\n var html = '<div class=\"row streamerRow all\" id=\"' + streamer + '\">' + \n '<div class=\"col-xs-2 logoHolder\"></div>' +\n '<div class=\"col-xs-8 info\"></div>' + \n '<div class=\"col-xs-2 text-right statusHolder\"></div>' +\n '</div>'; \n $('#streamers').append(html);\n callApi(streamer);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search form at the header | function showSearch() {
tm.fromTo($searchForm, .3, {'display': 'none', y: -220}, {'display': 'block', y: 0, ease: Power3.easeInOut})
} | [
"function search_home_page(){\n $('.header .icon-search .fa-search').on('click', function(){\n $('header').toggleClass('active-search-form');\n $('.header.active-search-form input').focus();\n });\n $('.header .icon-search .fa-remove').on('click', function(){\n $('header').toggleClass('active-search-form');\n $('.header.active-search-form input').focus();\n })\n }",
"function searchFunction () {\n activateSearch($searchInput, 'input');\n activateSearch($submit, 'click');\n}",
"function doSearch(){\n document.SearchCustomer.search.value = true;\n document.SearchCustomer.curpos.value=0;\n submit('SearchCustomer');\n }",
"function appendSearchBar() {\n const header = document.querySelector('.page-header');\n const searchDiv = document.createElement('form');\n searchDiv.innerHTML = `<input placeholder=\"Search for students...\"><button>Search</button>`;\n searchDiv.className = 'student-search';\n header.appendChild(searchDiv);\n\n searchDiv.addEventListener('submit', (e) => {\n e.preventDefault();\n let searchValue = e.target[0].value;\n searchItem(listItems, searchValue);\n e.target[0].value = '';\n });\n}",
"function handleSearch () {\n $('#js-search').on('submit', function (event){\n event.preventDefault();\n let usrInput = $(this).find('.js-search-query').val();\n setFilter(usrInput);\n renderShoppingList();\n });\n}",
"function search() {\n\t\tvar searchVal = searchText.getValue();\n\n\t\tsources.genFood.searchBar({\n\t\t\targuments: [searchVal],\n\t\t\tonSuccess: function(event) {\n\t\t\t\tsources.genFood.setEntityCollection(event.result);\n\t\t\t},\n\t\t\tonError: WAKL.err.handler\n\t\t});\n\t}",
"function searchControl(query, students) {\n //if no input provided to search for students return the main page.\n if (query.length == 0) {\n showPage(data, 1);\n addPagination(data);\n return;\n }\n\n //if the input provided did not match any filtered students.\n else if (students.length == 0) {\n //clean the current list of students and paginationButtons to insert a NOT FOUND message.\n clear(linkList);\n clear(studentList);\n studentList.innerHTML = ` <div class='nomatch'>No Matches were found</div>`;\n\n return;\n }\n\n //Defining the number of student tha will be displayed per page.\n let totalPages = Math.ceil(students.length / 9);\n\n //passing them as arguments to the showPage and addPagination functions.\n showPage(students, 1);\n addPagination(students);\n\n return;\n}",
"function emxCommonAutonomySearch() {\n //=================================================================\n // The URL parameters for emxFullSearch.jsp\n //=================================================================\n \n //\n //This is an optional parameter that can pass to specify the name of the function to be \n //invoked once submit button is clicked on the search component\n this.callbackFunction = null; // At this time this parameter is not working, so use onSubmit property\n\n //\n this.cancelLabel = null;\n\n //\n //List of OIDs to exclude from the search results\n this.excludeOID = null; \n\n //\n //JPO provided by Apps that returns list of OIDs to not display in results. This is used \n //to further filter the results. The method should return a StringList of OIDs to exclude \n //from the search results\n this.excludeOIDprogram = null;\n \n //\n //The parameter specifies the name of the form in the form-based search. It is an optional parameter.\n this.formName = null;\n \n //\n //The parameter specifies the name of the frame that contains the form. It is an optional parameter\n this.frameName = null;\n \n // List of indices and their default/allowed values for the initial search results\n this.field = null;\n //\n //This parameter is deprecated. It is present for the backward compatibility.\n // If user does txtType=\"type_abc\" then field is set to \"TYPES=txt_abc\"\n this.txtType = null;\n\n //\n //Optional parameter - Name of the field to which the selected value from the search results to be returned.\n this.fieldNameActual = null;\n \n //\n //Optional parameter ? If the display value is different from Actual value - Name of the field to which \n //the display value from the search results to be returned\n this.fieldNameDisplay = null;\n \n //\n //The optional parameter will be used to limit the list of indexed attributes displayed on a Form Based search.\n //This will not apply to Navigation based searches. Comma separated list\n this.formInclusionList = null;\n\n //\n //The parameter will be used to either show or hide the header on the search dialog. The header includes \n //the search text box along with the Search and Reset buttons and the page level toolbar\n this.hideHeader = null;\n \n //\n //All the selectable(s) of search criteria are optional by default. User can provide a coma separated \n //list of search criteria that are passed as part of URL parameter mandatorySearchParam to make them mandatory.\n //These refinements will be mandatory and displayed as disabled checked checkboxes in the breadcrumb display.\n //The user will not be allowed to uncheck these search criteria. The values passed as mandatorySearchParam must \n //be a part of the URL parameters.\n this.mandatorySearchParam = null;\n \n //\n //By default, the Search in Collection toolbar button will be displayed on the toolbar when in Navigate mode.\n //Can be turned off by this parameter. Recommended that this is not used when using type specific tables, \n //expandJPOs or relationships in the results table.\n this.searchCollectionEnabled = null;\n\n //\n //Controls whether the table page adds a column of check boxes or radio buttons in the left most column of \n //the search results table. The value passed can be multiple/single/none. \n //multiple ? to display a check box \n //single ? to display radio button.\n //none- no additional column is displayed for selection\n this.selection = null;\n\n //\n //The parameter value will allow display of the OOTB command ?AEFSaveQuery? on the toolbar. \n this.showSavedQuery = \"false\";\n\n //\n //If submitLabel is passed, as an URL parameter then the button will be displayed with the value passed else \n //will be displayed with label ?Done?.\n //This button will be shown only if Callback function is passed in the URL. This display can be suppressed \n //by passing additional parameter submitLink = false. \n //The value can be static text or a property key.\n //This is the existing URL parameter supported by structure browse component\n this.submitLabel = null;\n \n //\n //This parameter is used to define the callback URL. This could be the jsp page to perform the post processing \n //on an Add Existing command.\n //This is the existing URL parameter supported by structure browse component\n this.submitURL = \"../components/emxCommonAutonomySearchSubmit.jsp\";\n \n //\n //This is the table that will be passed to Indented Table to display the searched results\n this.table = \"AEFGeneralSearchResults\";\n \n //\n //This parameter is used to define a custom toolbar, if required for displaying the context \n //search using consolidated search view component. This is the toolbar that will be displayed \n //on the search results frame\n this.toolbar = null;\n\n //\n //This parameter will override the system setting for FormBased vs. Navigation Based.\n this.viewFormBased = null;\n\n \n //=================================================================\n // Other configurable parameters\n //=================================================================\n \n //\n // The height of the search window\n this.windowHeight = 600;\n \n //\n // The width of the search window\n this.windowWidth = 800;\n \n //\n // The Registered Suite parameter to be passed to JSP is needed.\n this.registeredSuite = null;\n \n //\n // The \"program\" parameter for Autonomy Search\n this.searchProgram = null;\n \n //\n //The javascript path of the callback submit javascript function.\n //Selected results will be submitted to this function. In general,\n //when the search is invoked from a chooser button on any dialog, we may pass \"getTopWindow().getWindowOpener().mySubmitCallback\"\n //where function mySubmitCallback is defined in the dialog page.\n //This is mandatory property to set.\n //\n //Example of the callback function\n //function mySubmitCallback(arrSelectedObjects) {\n // alert(\"DEBUG: ->mySubmitCallback \"+ arrSelectedObjects.length);\n // \n // for (var i = 0; i < arrSelectedObjects.length; i++) {\n // var objSelection = arrSelectedObjects[i];\n // objSelection.debug(); // Alerts the following properties\n // ...\n // objSelection.parentObjectId\n // objSelection.objectId\n // objSelection.type\n // objSelection.name\n // objSelection.revision\n // objSelection.relId\n // objSelection.objectLevel\n // ...\n // }\n //}\n this.onSubmit = null;\n \n //=================================================================\n // Opens the Autonomy Search window using the configured parameters\n //=================================================================\n this.open = function () {\n var strURL = \"../common/emxFullSearch.jsp\";\n \n // Collect the url parameters\n var arrParams = new Array;\n if (this.callbackFunction != null) {\n arrParams[arrParams.length] = \"callbackFunction=\" + this.callbackFunction;\n }\n if (this.cancelLabel != null) {\n arrParams[arrParams.length] = \"cancelLabel=\" + this.cancelLabel;\n }\n if (this.excludeOID != null) {\n arrParams[arrParams.length] = \"excludeOID=\" + this.excludeOID;\n }\n if (this.excludeOIDprogram != null) {\n arrParams[arrParams.length] = \"excludeOIDprogram=\" + this.excludeOIDprogram;\n }\n if (this.formName != null) {\n arrParams[arrParams.length] = \"formName=\" + this.formName;\n }\n if (this.frameName != null) {\n arrParams[arrParams.length] = \"frameName=\" + this.frameName;\n }\n if (this.field != null) {\n arrParams[arrParams.length] = \"field=\" + this.field;\n }\n else {\n if (this.txtType != null) {\n arrParams[arrParams.length] = \"field=TYPES=\" + this.txtType;\n }\n }\n if (this.fieldNameActual != null) {\n arrParams[arrParams.length] = \"fieldNameActual=\" + this.fieldNameActual;\n }\n if (this.fieldNameDisplay != null) {\n arrParams[arrParams.length] = \"fieldNameDisplay=\" + this.fieldNameDisplay;\n }\n if (this.formInclusionList != null) {\n arrParams[arrParams.length] = \"formInclusionList=\" + this.formInclusionList;\n }\n if (this.hideHeader != null) {\n arrParams[arrParams.length] = \"hideHeader=\" + this.hideHeader;\n }\n if (this.mandatorySearchParam != null) {\n arrParams[arrParams.length] = \"mandatorySearchParam=\" + this.mandatorySearchParam;\n }\n if (this.searchCollectionEnabled != null) {\n arrParams[arrParams.length] = \"searchCollectionEnabled=\" + this.searchCollectionEnabled;\n }\n if (this.selection != null) {\n arrParams[arrParams.length] = \"selection=\" + this.selection;\n }\n if (this.showSavedQuery != null) {\n arrParams[arrParams.length] = \"showSavedQuery=\" + this.showSavedQuery;\n }\n if (this.submitLabel != null) {\n arrParams[arrParams.length] = \"submitLabel=\" + this.submitLabel;\n }\n if (this.table != null) {\n arrParams[arrParams.length] = \"table=\" + this.table;\n }\n if (this.toolbar != null) {\n arrParams[arrParams.length] = \"toolbar=\" + this.toolbar;\n }\n if (this.viewFormBased != null) {\n arrParams[arrParams.length] = \"viewFormBased=\" + this.viewFormBased;\n }\n if (this.searchProgram != null) {\n arrParams[arrParams.length] = \"program=\" + this.searchProgram;\n }\n if (this.registeredSuite != null) {\n arrParams[arrParams.length] = \"Registered Suite=\" + this.registeredSuite;\n }\n if (this.onSubmit != null) {\n arrParams[arrParams.length] = \"onSubmit=\" + this.onSubmit;\n }\n if (this.submitURL != null) {\n arrParams[arrParams.length] = \"submitURL=\" + this.submitURL;\n }\n \n var strParams = arrParams.join(\"&\");\n strURL += \"?\" + strParams;\n\n // Open the search window\n showModalDialog(strURL, this.windowWidth, this.windowHeight, true);\n }//End: open()\n}//End: emxCommonAutonomySearch()",
"function handleSearch(){\n var term = element( RandME.ui.search_textfield ).value;\n if(term.length){\n requestRandomGif( term, true);\n }\n}",
"function SearchForm(enableClear, parentEl, options){\n options = this.options = mergeObjs(options,{\n 'buttonText' : 'Search',\n 'hintString' : 'Search the map!'\n });\n var z=this,\n input,\n form=z.form=createEl('form','gsc-search-box',[\n createEl('table','gsc-search-box',[createEl('tbody',null,[\n createEl('tr',null,[\n createEl('td','gsc-input',[input=z['input']=createEl('input','gsc-input',null,{\n 'type' : 'text',\n 'autocomplete' : 'off',\n 'size' : 10,\n 'name' : 'search',\n 'title' : 'search',\n 'value' : options['hintString'],\n 'onfocus' : createClosure(z,SearchForm.prototype.toggleHint),\n 'onblur' : createClosure(z,SearchForm.prototype.toggleHint)\n })]),\n createEl('td','gsc-search-button',[z.button=createEl('input','gsc-search-button',null,{\n 'type' : 'submit',\n 'value' : options['buttonText'],\n 'title' : 'search'\n })]),\n z.clearButton=(enableClear ? createEl('td','gsc-clear-button',[createEl('div','gsc-clear-button',[' '],{\n 'title' : 'clear results',\n 'onclick' : function(){\n z.form['clearResults']()\n }\n })]) : null)\n ])\n ])],{\n 'cellspacing':0,\n 'cellpadding':0\n }),\n createEl('table','gsc-branding',[createEl('tbody',null,[\n createEl('tr',null,[\n createEl('td','gsc-branding-user-defined'),\n createEl('td','gsc-branding-text',[createEl('div','gsc-branding-text',['powered by'])]),\n createEl('gsc-branding-img-noclear',[createEl('img','gsc-branding-img-noclear',null,{\n 'src' : 'http://www.google.com/uds/css/small-logo.png'\n })])\n ])\n ])])\n ],{\n 'accept-charset' : 'utf-8'\n });\n if(parentEl){\n parentEl.appendChild(form)\n }\n }",
"showSearchInput(e) {\n this.forcedVisibleSearchInputs = [...this.forcedVisibleSearchInputs, e], Oe(() => {\n document.querySelector(`[name=\"searchInput-${e}\"]`).focus();\n });\n }",
"configureSearch() {\n // If the filterable setting is disabled, no events should be applied automatically\n // (This behavior is intended for allowing custom filtering applications)\n if (this.settings.filterable) {\n accordionSearchUtils.attachFilter.apply(this, [COMPONENT_NAME]);\n accordionSearchUtils.attachFilterEvents.apply(this, [COMPONENT_NAME]);\n } else {\n // Invoke searchfield with default settings here since we found one\n // (main init process ignores searchfields inside nav menus)\n $(this.searchEl).searchfield();\n }\n\n this.searchEl.classList.add('module-nav-search');\n $(this.searchEl).parents('.accordion-section')?.[0].classList.add('module-nav-search-container');\n }",
"function collapseHeaderSearch() {\n\t// Collapse the div\n\t$(\"#header-search\").collapse(\"hide\");\n\t// Clear out the input\n\t$(\"input#global-search\").val(\"\");\n\t// Clear out the query suggestions\n\t$(\"#header-search table#search_suggest\").children().remove();\n}",
"function do_search() {\n var $form = $('#search-form');\n var option = $form.find('select[name=action] option[selected]').val();\n if (!option) return false;\n var search_terms = $form.find('input[name=q]').val();\n var url = str_concat(option , '?q=' , search_terms);\n adr(url);\n return false;\n }",
"buildSearchPage() {\n const myBooks = this.books.getMyBooks();\n if (this.searchedBooks === undefined) {\n return;\n }\n this.booksView.buildBookListing(this.searchedBooks, this.displayBook, myBooks);\n this.booksView.buildPagination(this.totalBooks, 100, this.currentPage, this.gotoPage, \"topPagination\");\n this.booksView.buildPagination(this.totalBooks, 100, this.currentPage, this.gotoPage, \"bottomPagination\");\n }",
"function populateFormFromUrl() {\n const createSearchItems = Private(SearchItemsProvider);\n const {\n indexPattern,\n savedSearch,\n combinedQuery } = createSearchItems();\n\n if (indexPattern.id !== undefined) {\n timeBasedIndexCheck(indexPattern, true);\n $scope.ui.datafeed.indicesText = indexPattern.title;\n $scope.job.data_description.time_field = indexPattern.timeFieldName;\n\n if (savedSearch.id !== undefined) {\n $scope.ui.datafeed.queryText = JSON.stringify(combinedQuery);\n }\n }\n }",
"function search()\n{\n\tvar searchText = searchInput.value;\n\n\t// if input's empty\n\t// displaying everything\n\tif (searchText == \"\")\n\t{\n\t\tshowAllFilteredWordEntries();\n\t\treturn;\n\t}\n\n\t// hiding everything except the matched words\n\tfor (let i = 0; i < loadedData.length; i++)\n\t{\n\t\tlet entry = getFilteredWordEntry(i);\n\t\tvar regx = new RegExp(searchText);\n\t\tif (regx.test(loadedData[i]))\n\t\t\tentry.hidden = false;\n\t\telse\n\t\t\tentry.hidden = true;\n\t}\n}",
"searchDocuments() {\n\n let searchObj = {}\n if (this.searchType === 'query') {\n searchObj.query = this.query;\n } else if (this.searchType === 'field') {\n searchObj.fieldCode = this.queryField;\n searchObj.fieldValue = this.queryFieldValue;\n }\n this.etrieveViewer.Etrieve.searchDocuments(searchObj)\n .catch(err => {\n console.error(err);\n });\n }",
"function searchtoresults()\n{\n\tshowstuff('results');\n\thidestuff('interests');\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
email twitter to all contacts | function bEmailTwitterAllCon(broadCast_sender_email,broadCast_name,broadCast_sender_name,broadCast_message,broadCast_email_subject,x)
{
$('#takeOneAction').val('false');
var rEmail=1;var rTts=0;var rSms=0;var rTwitter=1;
//checks of validations
generalValidations(broadCast_name,broadCast_message);
var isvalid = emailCntVal(broadCast_sender_email,broadCast_sender_name);
console.log("email twitter to all contacts");
//checks for validations
var res = calculateRecipients(rEmail,rTts,rSms,rTwitter);
var Valueofcheckboxtwtvo=res[3];
Valueofcheckbox=res[0];
recipientVal(res[4]);
broadCast_message = broadCast_message.split('"').join('');
broadCast_message = broadCast_message.split('\n').join('');
//setting JSON
datasinfo = '{"senderName":"'+broadCast_sender_email+'","message":"'+broadCast_message+'","emailSubject":"'+broadCast_email_subject+'","broadcastName":"'+broadCast_name+'",'+Valueofcheckbox+','+Valueofcheckboxtwtvo+'}}';
if(broadCast_name!=''&&broadCast_message!=''&&broadCast_message!=' '&&broadCast_sender_name!=''&&broadCast_sender_email!=''&&res[4]!=0&&isvalid)
{
console.log('sending');
$("#main").css({"opacity": "0.3"});
broadcastFunc(datasinfo,x);
}
} | [
"function bEmailSmsTwitterAllCon(senderId,broadCast_sender_email,broadCast_name,broadCast_sender_name,broadCast_message,broadCast_email_subject,x)\n{\n\t$('#takeOneAction').val('false');\n\tvar rEmail=1;var rTts=0;var rSms=1;var rTwitter=1;\n\t//checks of validations\n\tsmsCntVal(senderId);\n\tgeneralValidations(broadCast_name,broadCast_message);\n\tvar isvalid = emailCntVal(broadCast_sender_email,broadCast_sender_name);\n\tconsole.log(\"voice and email and sms twitter to all contacts\");\n\t//checks for validations\n\tvar res = calculateRecipients(rEmail,rTts,rSms,rTwitter);\n\tvar Valueofcheckboxtwtvo=res[3];\n\tvar Valueofcheckboxmob=res[1];\n\tValueofcheckbox=res[0];\n\trecipientVal(res[4]);\n\tbroadCast_message = broadCast_message.split('\"').join('');\n\tbroadCast_message = broadCast_message.split('\\n').join('');\n\t//setting JSON\n\tdatasinfo = '{\"senderName\":\"'+senderId+'\",\"message\":\"'+broadCast_message+'\",\"emailSubject\":\"'+broadCast_email_subject+'\",\"broadcastName\":\"'+broadCast_name+'\",'+Valueofcheckbox+','+Valueofcheckboxmob+','+Valueofcheckboxtwtvo+'}}';\n\tif(broadCast_name!=''&&broadCast_message!=''&&broadCast_message!=' '&&broadCast_sender_name!=''&&broadCast_sender_email!=''&&res[4]!=0&&isvalid&&senderId!='')\n\t\t{\n\t\t\tconsole.log('sending');\n\t\t\t$(\"#main\").css({\"opacity\": \"0.3\"});\n\t\t\tbroadcastFunc(datasinfo,x);\n\t\t}\n}",
"function getTwitterTweets(screen_name) {\n socket.emit('user_tweets', { screen_name: screen_name });\n }",
"function tweetEvent(tweet) {\n\n // Who is this in reply to?\n var reply_to = tweet.in_reply_to_screen_name;\n // Who sent the tweet?\n var name = tweet.user.screen_name;\n // What is the text?\n var txt = tweet.text;\n // If we want the conversation thread\n var id = tweet.id_str;\n\n // Ok, if this was in reply to me\n // Tweets by me show up here too\n if (reply_to === 'InatorBot') {\n\n // Get rid of the @ mention\n txt = txt.replace(/@InatorBot/g,'');\n\n //reply back to the sender\n var replyText = '@'+name + ' thx for doing the twit at me XD';\n\n // Post that tweet\n T.post('statuses/update', { status: replyText, in_reply_to_status_id: id}, tweeted);\n\n // Make sure it worked!\n function tweeted(err, reply) {\n if (err) {\n console.log(err.message);\n } else {\n console.log('Tweeted: ' + reply.text);\n }\n }\n }\n}",
"function bSmsTwitterAllCon(senderId,broadCast_name,broadCast_message,x)\n{\n\t$('#takeOneAction').val('false');\n\tvar rEmail=0;var rTts=0;var rSms=1;var rTwitter=1;\n\t//checks of validations\n\tsmsCntVal(senderId);\n\tgeneralValidations(broadCast_name,broadCast_message);\n\tconsole.log(\"sms twitter to all contacts\");\n\t//checks for validations\n\tvar res = calculateRecipients(rEmail,rTts,rSms,rTwitter);\n\tvar Valueofcheckboxtwtvo=res[3];\n\tvar Valueofcheckboxmob=res[1];\n\trecipientVal(res[4]);\n\tbroadCast_message = broadCast_message.split('\"').join('');\n\tbroadCast_message = broadCast_message.split('\\n').join('');\n\t//setting JSON\n\tdatasinfo = '{\"senderName\":\"'+senderId+'\",\"message\":\"'+broadCast_message+'\",\"broadcastName\":\"'+broadCast_name+'\",'+Valueofcheckboxmob+','+Valueofcheckboxtwtvo+'}}';\n\tif(broadCast_name!=''&&broadCast_message!=''&&broadCast_message!=' '&&res[4]!=0&&senderId!='')\n\t\t{\n\t\t\tconsole.log('sending');\n\t\t\t$(\"#main\").css({\"opacity\": \"0.3\"});\n\t\t\tbroadcastFunc(datasinfo,x);\n\t\t}\n}",
"function mentions(tweet) {\n var string = tweet.split(\" \");\n var hash = [];\n for (var i = 0; i < string.length; i++) {\n if (string[i].startsWith(\"@\")) {\n hash.push(string[i]);\n }\n }\n return hash;\n}",
"sendEmailList (e, template) {\n var subscribers = this.getSubscribers(); //list of subscriber objects\n subscribers.forEach((subscriber) => {this.sendEmail(e, template, subscriber)});\n console.log('Emails sent')\n }",
"function emailSend(results) { // results is returned from getResults()\r\n for (let i = 0; i < results.length; i++) {\r\n let userInfo = results[i];\r\n\r\n // Send email to tutor about appointment\r\n let tutorEmailMsg1 = 'Hello, ' + userInfo[6] + '! ';\r\n let tutorEmailMsg2 = userInfo[0] + ' wants to be tutored by you in ' + userInfo[5] + '. ';\r\n let tutorEmailMsg3 = userInfo[0] + ' is in grade ' + userInfo[2] + ' and goes to ' + userInfo[1] + '. ';\r\n let tutorEmailMsg4 = 'Your appointment is scheduled for ' + userInfo[3] + '. ';\r\n let tutorEmailMsg5 = 'Here is some information they added about their appointment: ' + userInfo[7] + '.';\r\n let tutorEmailSubject = 'Your Tutoring Appointment!';\r\n let tutorEmailMessage = tutorEmailMsg1 + tutorEmailMsg2 + tutorEmailMsg3 + tutorEmailMsg4 + tutorEmailMsg5;\r\n MailApp.sendEmail(userInfo[8], tutorEmailSubject, tutorEmailMessage);\r\n\r\n // Send email to student about appointment\r\n let studentEmailMsg1 = 'Hello, ' + userInfo[0] + '! ';\r\n let studentEmailMsg2 = 'You are going to be tutored by ' + userInfo[6] + '! ';\r\n let studentEmailMsg3 = 'Your appointment is scheduled for ' + userInfo[3] + '. ';\r\n let studentEmailMsg4 = 'Here is the information you added about your appointment: ' + userInfo[7] + '.';\r\n let studentEmailSubject = 'Your Tutoring Appointment!';\r\n let studentEmailMessage = studentEmailMsg1 + studentEmailMsg2 + studentEmailMsg3 + studentEmailMsg4;\r\n MailApp.sendEmail(userInfo[4], studentEmailSubject, studentEmailMessage);\r\n }\r\n}",
"function bTtsSmsTwitterAllCon(senderId,broadCast_name,broadCast_message,lCode,x)\n{\n\t$('#takeOneAction').val('false');\n\tvar rEmail=0;var rTts=1;var rSms=1;var rTwitter=1;\n\t//checks of validations\n\tsmsCntVal(senderId);\n\tgeneralValidations(broadCast_name,broadCast_message);\n\tconsole.log(\"voice and email and sms twitter to all contacts\");\n\t//checks for validations\n\tvar res = calculateRecipients(rEmail,rTts,rSms,rTwitter);\n\tvar Valueofcheckboxtwtvo=res[3];\n\tvar Valueofcheckboxmobvo=res[2];\n\tvar Valueofcheckboxmob=res[1];\n\trecipientVal(res[4]);\n\tbroadCast_message = broadCast_message.split('\"').join('');\n\tbroadCast_message = broadCast_message.split('\\n').join('');\n\tlCode=$('#ldId').val();\n\t//setting JSON\n\tdatasinfo = '{\"senderName\":\"'+senderId+'\",\"message\":\"'+broadCast_message+'\",\"broadcastName\":\"'+broadCast_name+'\",\"audio\": \"null\",'+Valueofcheckboxmob+','+Valueofcheckboxmobvo+','+Valueofcheckboxtwtvo+'},\"language\": \"'+lCode+'\"}';\n\tif(broadCast_name!=''&&broadCast_message!=''&&broadCast_message!=' '&&res[4]!=0&&senderId!='')\n\t\t{\n\t\t\tconsole.log('sending');\n\t\t\t$(\"#main\").css({\"opacity\": \"0.3\"});\n\t\t\tbroadcastFunc(datasinfo,x);\n\t\t\t$('#ldId').val(\"nl-nl\").attr(\"selected\", \"selected\");\n\t\t}\n}",
"function postToTwitter(markovHeadline)\n{\n\tT.post('statuses/update', { status: markovHeadline }, function(err, data, response) {\n\t\tconsole.log(data);\n\t})\n}",
"function writeTwitter(nam,handl){\n\t // takes twitter name from link area box and writes it\n\t \n\t // check for blanks\n\t if ((nam==\"\") || (handl==\"\")){\n\t \talert(\"Real name and Twitter handle are both required. Quitting.\");\n\t\treturn\n\t }\n\t \n\t // check for dupes\n\t var i;\n\t var found = -1;\n\t for (i=0; i < tweeters_anchors.length; i++){\n\t \tif (tweeters_anchors[i].toUpperCase() == nam.toUpperCase()){\n\t\t\tfound = i;\n\t\t}\n\t }\n\t if (found > -1) { // if name already there, then quit\n\t \treturn\n\t }\n\t // not already there\n\t // add to array\n\t tweeters_anchors.push(nam);\n\t tweeters_tweetnames.push(handl);\n\t // save the twitter\n $.post('writetwitter.php', {\n newline: \"\\n\" + nam + \"|\" + handl,\n async: false,\n success: function(){\n alert('Success updating link file!');\n },\n error: function(){\n alert('Error writing link file');\n }\n })\n \n \n}",
"function _sendEmail() {\n\t\t\t}",
"function sendContacts () {\n\t\t\tUser.getContacts(socket.handshake.user.username, function (contacts) {\n\t\t\t\tsocket.emit('contacts', contacts);\n\t\t\t});\n\t\t}",
"function processTweet(data) {\n\t\treturn [[ \"receiving transmission\" ], [\n\t\t\"type : tweet\",\n\t\t\"handle : \"+data.user.screen_name,\n\t\t\"name : \"+data.user.name,\n\t\t\"location : \"+data.user.location,\n\t\t\"message : \"+data.text,\n\t\t/* \"profile : \"+data.user.description, */\n\t\t\"date : \"+data.created_at.substr(0,20),\n\t\t]];\n\t}",
"function main() {\n \n \t//Step 1: Add Email\n\tvar recipient = \"peterstavrop@gmail.com\";\n \n \t//Step 2: Change Subject Line\n\tvar subject = \"Add Subject Line Here\";\n \n\tvar body = AdWordsApp.currentAccount().getName() + \" Paid Search Email \\n\";\n \n \t//Step 3: Add Text to Email Body\n \tbody = body + \"Add Text Here\";\n\n\tMailApp.sendEmail(recipient, subject, body);\n\t\n}",
"function twitterUpdate() {\n\t\t// Twitter読み込み\n\t\tif(twitter_id){\n//\t\t\tgetTwitterSearch();\n\t\t}\n\t\t// 逆ジオコーディング\n\t\tif(userExist){\n\t\t\tgeocoder.getLocations(nowPoint, geocoding);\n\t\t}\n\t\treloadId = setTimeout(twitterUpdate, twitterReloadTime);\n\t}",
"function notifyMember(site,personalMail,firstname,lastname,date){\n var body = \"Documents and information required for employee admission.\";\n var subject = \"Welcome to our company\";\n var options = {name:\"HR Team\",htmlBody:body,replyTo:\"hr@example.com\",from:\"hr@example.com\"};\n MailApp.sendEmail(personalMail,subject,body,options);\n }",
"SendModeratorsListAndSubscribersListOfThisMailingListByEmail(domain, email, name) {\n let url = `/email/domain/${domain}/mailingList/${name}/sendListByEmail`;\n return this.client.request('POST', url, { email });\n }",
"function showTweets(maxTw) {\n\tvar client = new Twitter(twitterKeys);\n\tvar twitParams = {screen_name: 'PmAlias'};\n\tclient.get('statuses/user_timeline', twitParams, function(error, tweets, response) {\n\t if (!error) {\n\t\t\ttweets = tweets.concat(tweets,tweets,tweets,tweets,tweets);\n\t\t\tconsole.log(tweets.length);\n\t\t\t// Limit to the most recent <maxTw> tweets\n\t\t\tif (tweets.length > maxTw) {\n\t\t\t\t// Sort in reverse date order to get most recent at the top\n\t\t\t\tsortTweets(tweets,'descending');\n\t\t\t\t// Keep the most recent tweets up to maxTw\n\t\t\t\ttweets = tweets.slice(0,maxTw);\n\t\t\t}\n\t\t\t// Sort in date order\n\t\t\tsortTweets(tweets,'ascending');\n\t\t\t\n\t \tfor (var i=0,len=tweets.length;i<len;i++) {\n\t\t\t\tconsole.log(\n\t\t\t\t\tmoment(tweets[i].created_at,'ddd MMM DD HH:mm:ss +SSSS YYYY')\n\t\t\t\t\t.format('MM/DD/YYYY hh:mm:ss A'),' ',tweets[i].text);\n\t\t\t}\n\t }\n\t});\n}",
"function thingTweet() {\n request({\n url:\t 'https://api.thingspeak.com/apps/thingtweet/1/statuses/update',\n method: 'POST',\n\tform:\t { api_key: 'EQZMJ3E1FFOZOQE8', status: name } \n }, function (error, response, body) {\n if (!error && response.statusCode == 200) {\n console.log(body)\n }\n }\n);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copies all HTMl attributes from one DOM node to another. | function copyHtmlAttributes(srcEl, dstEl) {
for (var atts = srcEl.attributes, ic = atts.length, i = 0; i < ic; ++i) {
dstEl.setAttribute(atts[i].nodeName, atts[i].nodeValue);
}
} | [
"cloneAttributes(target, source) {\n [...source.attributes].forEach( attr => { target.setAttribute(attr.nodeName === \"id\" ? 'data-id' : attr.nodeName ,attr.nodeValue) })\n }",
"function addAttributes(node, attrs) {\n for (var name in attrs) {\n var mode = attrModeTable[name];\n if (mode === IS_PROPERTY || mode === IS_EVENT) {\n node[name] = attrs[name];\n }\n else if (mode === IS_ATTRIBUTE) {\n node.setAttribute(name.toLowerCase(), attrs[name]);\n }\n else if (dataRegex.test(name)) {\n node.setAttribute(name, attrs[name]);\n }\n }\n var inlineStyles = attrs.style;\n if (!inlineStyles) {\n return;\n }\n var style = node.style;\n for (var name in inlineStyles) {\n style[name] = inlineStyles[name];\n }\n }",
"addAttribute(...args) {\n if (this.setAttribute) {\n return this.setAttribute(...args)\n } else {\n return super.setAttribute(...args)\n }\n }",
"function copyInnerHtml(src, target) {\n var domSupported = document.getElementById ? true : false;\n var se = (domSupported && typeof src == \"string\") ? document.getElementById(src) : src;\n var te = (domSupported && typeof target == \"string\") ? document.getElementById(target) : target;\n if (se.innerHTML && te.innerHTML) te.innerHTML = se.innerHTML;\n}",
"readAttributes() {\n this._previousValueState.state = this.getAttribute('value-state')\n ? this.getAttribute('value-state')\n : 'None';\n\n // save the original attribute for later usages, we do this, because some components reflect\n Object.keys(this._privilegedAttributes).forEach(attr => {\n if (this.getAttribute(attr) !== null) {\n this._privilegedAttributes[attr] = this.getAttribute(attr);\n }\n });\n }",
"function withAlignContentAttributes(attributes) {\n attributes.align_content = {\n type: 'string'\n };\n return attributes;\n }",
"function showAttrs(node, opt) {\n\t\tvar i;\n\t\tvar out = \"<table class='ms-vb' width='100%'>\";\n\t\tfor (i=0; i < node.attributes.length; i++) {\n\t\t\tout += \"<tr><td width='10px' style='font-weight:bold;'>\" + i + \"</td><td width='100px'>\" +\n\t\t\t\tnode.attributes.item(i).nodeName + \"</td><td>\" + checkLink(node.attributes.item(i).nodeValue) + \"</td></tr>\";\n\t\t}\n\t\tout += \"</table>\";\n\t\treturn out;\n\t} // End of function showAttrs",
"function setInputAttributes(element, attributes) {\n for (let key in attributes) {\n element.setAttribute(key, attributes[key]);\n }\n }",
"composeAttributes() {\n this.attributes = Object.assign({}, this.getAttributes(), { class: [\n this.getName(),\n ...this.getParsedClassModifiers(),\n ...this.getParsedNthBlockElements(),\n ...this.getRestClasses(),\n ].join(' ') });\n if (this.bemID)\n this.attributes.id = this.getName();\n }",
"function attrsShouldReturnAttributes() {\n expect(element.attrs(fixture.el.firstElementChild))\n .toEqual({\n class: \"class\",\n id: \"id\"\n })\n}",
"function setSrc(element,attribute){element.setAttribute(attribute,element.getAttribute('data-'+attribute));element.removeAttribute('data-'+attribute);}",
"_setAttributes(elem, dict) {\n for (const [key, value] of Object.entries(dict)) {\n console.log(key, value);\n elem.setAttribute(key, value);\n }\n }",
"defaultAttributes(attributeObj) {\r\n Object.keys(attributeObj).forEach(name => {\r\n let defaultVal = attributeObj[name];\r\n let userVal = this.getAttribute(name);\r\n\r\n if (!userVal) {\r\n this.setAttribute(name, defaultVal);\r\n }\r\n });\r\n }",
"function showAttributes(){\r\n var msg = '';\r\n msg+=\"id: \"+aref.id+\", \"+\"target: \"+aref.target+\", \"+\"href: \"+aref.href+\", \"+\"innerText: \"+aref.innerText;\r\n divref.innerHTML=msg;\r\n}",
"function addAndUpdate () {\n for (let key in nextAttrs) {\n let nextVal = nextAttrs[key];\n let currVal = currAttrs[key];\n if (nextVal instanceof Function) {\n nextVal = nextVal();\n }\n if (key === 'value' && isFormEl(dom)) {\n dom.value = nextVal;\n } else if (nextVal !== currVal) {\n dom.__attrs[key] = nextVal;\n dom.setAttribute(key, nextVal);\n }\n }\n }",
"function remove () {\n for (let key in currAttrs) {\n if (!nextAttrs[key]) {\n dom.removeAttribute(key);\n delete dom.__attrs[key]\n }\n }\n }",
"function withAlignTextAttributes(attributes) {\n attributes.align_text = {\n type: 'string'\n };\n return attributes;\n }",
"function getAttributes(node) {\n\n var attributes = {};\n\n for (var index = 0; index < node.attributes.length; index++) {\n // Extract the attribute name - checking for clashes with javaScript names.\n // Note that we also remove lara: which is used for the Customer attributes.\n var attributeName = checkForPropertyClash(node.attributes[index].nodeName.replace('gam:', '').replace('lara:', ''));\n\n // Store the attribute name and value in the attributes object.\n attributes[attributeName] = node.attributes[index].nodeValue;\n }\n\n return attributes;\n }",
"replaceChild() {\n if (this.el) {\n this.el.innerHTML = \"\";\n }\n\n this.isDomified = false;\n this.contents = [];\n this.atts = [];\n this.props = [];\n\n this.appendChild.apply(this, arguments);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of all the active players present on the provided ref instance (which can be an instance of a directive, component or element). This function will only return players that have been added to the ref instance using `addPlayer` or any players that are active through any template styling bindings (`[style]`, `[style.prop]`, `[class]` and `[class.name]`). | function getPlayers(ref) {
var context = getLContext(ref);
if (!context) {
ngDevMode && throwInvalidRefError();
return [];
}
var stylingContext = getStylingContext(context.nodeIndex, context.lView);
var playerContext = stylingContext ? getPlayerContext(stylingContext) : null;
return playerContext ? getPlayersInternal(playerContext) : [];
} | [
"function getAllPlayers() {\n var players = [];\n\n Object.keys(io.sockets.connected).forEach(function(socketId) {\n var player = io.sockets.connected[socketId].player;\n\n if (player) {\n players.push(player);\n }\n });\n\n return players;\n}",
"setActivePlayersIds() {\n\t\tlet activePlayersIds = [];\n\t\tthis.table.players.forEach((player) => {\n\t\t\tif (player.active) {\n\t\t\t\tactivePlayersIds.push(player.id);\n\t\t\t}\n\t\t});\n\t\tthis.activePlayersIds = activePlayersIds;\n\t}",
"function filter(players, fn) {\n let arr = [];\n for (var i in players) {\n if (fn(players[i])) {\n arr.push(players[i]);\n }\n }\n return arr;\n}",
"function getPlayers() {\n var ref = new Firebase(\"https://tictacstoe.firebaseio.com/players\");\n var players = $firebaseObject(ref);\n\n players.tictacs = [];\n players.tictacs.push({\n type: \"spearmint\",\n image: \"images/green-tic.png\",\n alt: \"green\"\n });\n players.tictacs.push({\n type: \"orange\",\n image: \"images/orange-tic.png\",\n alt: \"orange\"\n });\n players.tictacs.push({\n type: \"wild cherry\",\n image: \"images/red-tic.png\",\n alt: \"red\"\n });\n players.tictacs.push({\n type: \"freshmints\",\n image: \"images/white-tic.png\",\n alt: \"white\"\n });\n\n players.$save();\n\n return players;\n }",
"function getMatchGoals(match){\n return match\n .filter(hasGoals)\n .map(match => match.Goal)\n .reduce((total, current) => {\n return total.concat(current.map(c => c.PlayerRef));\n }, []);\n }",
"function topologyPlayers(topology) {\n if (!topology) {\n return [];\n }\n var players = [];\n players.push(topology.leader);\n var current = topology[FORWARD][topology.leader];\n while (current !== topology.leader) {\n players.push(current);\n current = topology[FORWARD][current];\n }\n return players;\n }",
"function getPlayersList(roomId) {\n return roomsRef.child(`${roomId}/players`).once('value');\n}",
"function createArrayOfPlayers() {\n let arrayOfPlayers = [];\n // Iterate through the array of player sprites,\n // and make new player with each sprite\n for (let i=0; i<ARRAY_PLAYER_SPRITES.length; i++) {\n arrayOfPlayers.push(new Player(ARRAY_PLAYER_SPRITES[i], i));\n }\n // Display the first player\n arrayOfPlayers[0].active = true;\n arrayOfPlayers[0].isVisible = true;\n return arrayOfPlayers;\n}",
"getPlayerPositions() {\n\t\treturn {\n\t\t\tplayer1: this.paddle1Y,\n\t\t\tplayer2: this.paddle2Y\n\t\t}\n\t}",
"function getLobbyPlayers(lobby) {\n return players.filter(player => player.lobby === lobby);\n}",
"function drawPlayers(searchedPlayers) {\n if (searchedPlayers != null) {\n\n var template = '';\n\n for (let i = 0; i < searchedPlayers.length; i++) {\n let player = searchedPlayers[i];\n\n template += `\n <div class=\"player-card\" id=\"${i}\">\n <img src=\"${player.photo}\" alt=\"http://s.nflcdn.com/static/content/public/image/fantasy/transparent/200x200/\">\n <div>Name: ${player.fullname}</div>\n <div>Position: ${player.position}</div>\n <div>Team: ${player.pro_team}</div>\n <div class=\"add\"><button onclick=\"app.controllers.playerController.addToMyTeam(${player.id})\" id=\"btn${i}\">Add</button></div>\n </div>\n `\n }\n\n document.getElementById('search-results').innerHTML = template;\n }\n }",
"function createCursors(players) {\n\t\tfor (var key in players) {\n\t\t\tcreateCursor(players[key]);\n\t\t}\n\t}",
"function getIdPlayers(){\n let { players } = state\n let playersId = []\n \n for (const playerId in players) {\n playersId.push(playerId) \n }\n return playersId \n }",
"getPlayerMoves() {\n return this.moves;\n }",
"function playerIdsInMatches(matches) {\n const playerIdSet = new Set();\n let players = [];\n matches.forEach((match) => {\n match.teams.forEach((team) => {\n team.forEach((player) => {\n if (!playerIdSet.has(player.id)) {\n players.push(player.id);\n // players.push({ id: player.id, name: player.name });\n }\n playerIdSet.add(player.id);\n });\n });\n });\n return players;\n}",
"function getMonitoredPlayerNames() {\n let internalMonitorObj = internalServerData.monitoredPlayers\n let players = {}\n for (const device in internalMonitorObj) {\n for (name of internalMonitorObj[device].names) {\n players[name] = true\n }\n }\n return Object.keys(players)\n}",
"function findAvailableChallenges() {\n vm.availableChallenges = false;\n if (vm.currentUserIsOnCompetition && !vm.hasActiveChallenge) {\n var levelAbove = vm.currentUserPlayer.level > 1 ? vm.currentUserPlayer.level - 1 : null;\n _.forEach(vm.competition.players, function (player) {\n var waitingForPlayer = null;\n if (player.level === levelAbove && player.position !== 99 && player.class !== 'unavailable' && player.available !== false && !player.hold) {\n // Check if there is a waiting period for this player\n waitingForPlayer = _.find(vm.currentUserPlayer.waitingPeriods, { 'player': player._id });\n // If there is a waiting period for this user don't make them available\n if (waitingForPlayer && moment().isBefore(waitingForPlayer.expires)) {\n player.class = 'waiting';\n player.waitUntil = moment(waitingForPlayer.expires).format('MMM Do @ LT');\n } else {\n vm.availableChallenges = true;\n player.available = true;\n player.class = 'available';\n }\n }\n });\n }\n }",
"function orderPlayers() {\n vm.competition.players = $filter('orderBy')(vm.competition.players, 'position');\n }",
"function initPlayers () {\n for (player in room.getOccupants()) {\n\t if (player.getAttribute(ClientAttributes.STATUS, Settings.GAME_ROOMID)\n\t\t== PongClient.STATUS_READY) {\n\t\taddPlayer(player);\n\t }\n\t}\n}",
"collidesPlayers(playerId) {\n let player = this.players[playerId];\n if (player === undefined) return false;\n\n for (let id in this.players) {\n let other = this.players[id];\n\n if (playerId === other.id) continue;\n if (!other.alive) continue;\n\n if (this.collidesObject(player.getTopLeft(), player.getBottomRight(),\n other.getTopLeft(), other.getBottomRight())) {\n return other;\n }\n }\n\n return null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Private methods: Given a latitude and longitude, this method looks through all the stored locations and returns the index of the location with matching latitude and longitude if one exists, otherwise it returns null. | function indexForLocation(latitude, longitude)
{
for (var i = 0; i < locations.length; i++ ){
var location = me.locationAtIndex(i);
if (location.latitude == latitude && location.longitude == longitude){
return i
}
}
} | [
"function indice(lat, lon, array){\n\tvar n = array.length;\n\tindex = -1;\n\tfor (var i = 0 ; i < n; i++) {\n\t\tif (Number(array[i][0]) == lat && Number(array[i][1]) == lon){\n\t\t\tindex = i;\n\t\t\treturn index;\n\t\t}\n\t}\n\treturn index;\t\n\t\t\n}",
"existLatLon(locationObject, array) {\n let exist = false;\n let index = null;\n array.map((item, i) => {\n if (locationObject.hasOwnProperty('lat') && locationObject.hasOwnProperty('lon') && locationObject.lat == item.lat && locationObject.lon == item.lon) {\n exist = true;\n index = i;\n }\n });\n return {\n exist,\n index,\n };\n }",
"function getBlockIndex() {\n log.debug(\"CALL: getBlockIndex()\");\n for (var index = 0; index < path.length; index++) {\n if (grid[path[index].x][path[index].y] == null || ( grid[path[index].x][path[index].y].type == 'ex' && avoidExit)) {\n log.debug(\"RESULT: getBlockIndex() \" + index);\n return index;\n }\n }\n for (var i = 0; i < path.length; i++) {\n for (var j = i; j < path.length; j++) {\n if (i == j) continue;\n if (path[i].x == path[j].x && path[i].y == path[j].y) {\n return j;\n }\n }\n }\n\n log.debug(\"RESULT: getBlockIndex() -1\");\n return -1;\n }",
"function contains_building(buildings, location)\n{\n var building_index = -1;\n\n buildings.forEach(function(element, index, array)\n {\n if(element.Building == location){\n building_index = index;\n }\n });\n\n return building_index;\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}",
"GetCellIndexAt(x, y) {\n let x_idx = parseInt(x / this.cell_size);\n let y_idx = parseInt(y / this.cell_size);\n if (x_idx >= 0 && x_idx < this.num_cells_in_row && y_idx >= 0 &&\n y_idx < this.num_cells_in_row) {\n return y_idx * this.num_cells_in_row + x_idx;\n } else {\n return null;\n }\n }",
"function find_location_from_shared_key(shared_key){\r\n\t\tvar return_result=\"-1\";\r\n\t\tvar locationSearchObj = search.create({\r\n\t\t type: \"location\",\r\n\t\t filters:\r\n\t\t [\r\n\t\t\t//[\"internalid\",\"anyof\",code],\r\n\t\t\t[\"custrecord_tsa_iu_shared_key_loc\", \"is\", shared_key],\r\n \"AND\",\r\n [\"custrecord_tsa_loc_type\", \"is\", 1]\r\n \r\n\t\t ],\r\n\t\t columns:\r\n\t\t [\r\n\t\t\tsearch.createColumn({ name: \"internalid\", label: \"Internal ID\" })\r\n\t\t ]\r\n\t\t});\r\n\t\tlog.debug(\"location_lookup::find_location_id_from_shared_key\", \"Looked up shared_key:\"+shared_key);\r\n\t\t\r\n\t\tlocationSearchObj.run().each(function (result) {\r\n\t\t log.debug(\"location_lookup::find_location_id_from_shared_key\", \"location internalid: \" + result.getValue({ name: \"internalid\" }));\r\n\t\t return_result = result.getValue({ name: \"internalid\" });\r\n\t\t return false;\r\n\t\t});\r\n\t\treturn return_result;\r\n\t}",
"function linearSearch(list, key) {\n let index = -1;\n for (let i = 0; i < list.length; i++) {\n if (list[i] == key) {\n index = i;\n break;\n }\n }\n return index;\n}",
"function locationFinder() {\n\t\t\tvar locations = [];\n\t\t\t// iterates through entries location and appends each location to\n\t\t\t// the locations array\n\t\t\tfunction appendLocations(entriesID) {\n\t\t\t\tmyData.forEach(function(tile) {\n\t\t\t\t\tif (tile.hasOwnProperty(entriesID)) {\n\t\t\t\t\t\ttile[entriesID].forEach(function(entry) {\n\t\t\t\t\t\t\tif (entry.hasOwnProperty('location')) {\n\t\t\t\t\t\t\t\tlocations.push(entry.location);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\tappendLocations('schools');\n\t\t\tappendLocations('works');\n\t\t\tappendLocations('allTheRest');\n\t\t\treturn removeDuplicate(locations);\n\t\t}",
"function linearSearch(searchObj, searchArr){\n\n for(let index = 0; index < searchArr.length; index++){\n if(searchArr[index] === searchObj){\n return index\n }\n }\n return undefined\n}",
"function getPlayerLocation(player) {\n var m = stateMachine.map;\n for (var row=0; row < m.length; row++) {\n for (var col=0; col < m[0].length; col++) {\n if (m[row][col] == player) {\n return [row, col];\n }\n }\n }\n throw(\"cannot getPlayerLocation for player \" + player);\n}",
"function getAdjacentLocation({homeLocation, direction, locations}) {\n const col = homeLocation.charCodeAt(0) - charCodeStart;\n const row = Number(homeLocation.charAt(1));\n\n let newCol;\n let newRow;\n\n // Find the new row and col.\n switch(direction) {\n case 'up':\n newCol = col;\n newRow = row + 1;\n break;\n case 'down':\n newCol = col;\n newRow = row - 1;\n break;\n case 'upLeft':\n newCol = col - 1;\n if (col <= middleCol) {\n newRow = row;\n } else {\n newRow = row + 1;\n }\n break;\n case 'downLeft':\n newCol = col - 1;\n if (col <= middleCol) {\n newRow = row - 1;\n } else {\n newRow = row;\n }\n break;\n case 'upRight':\n newCol = col + 1;\n if (col < middleCol) {\n newRow = row + 1;\n } else {\n newRow = row;\n }\n break;\n case 'downRight':\n newCol = col + 1;\n if (col < middleCol) {\n newRow = row;\n } else {\n newRow = row - 1;\n }\n break;\n }\n\n const newColLetter = String.fromCharCode(charCodeStart + newCol);\n const newLocationId = newColLetter + newRow;\n\n if(locations[newLocationId]) {\n return newLocationId;\n } else {\n return null;\n }\n}",
"function getMatchingIndex(arr, key, value) {\n for (let i = 0; i < arr.length; i++) {\n if (arr[i][key] === value)\n return i;\n }\n return null;\n}",
"function getLocationIndex() {\n // Let's see if this works\n if (viewModel.outingState.pathIndex < 0) {\n return 0;\n }\n return state.historyIndex;\n }",
"function locationFinder() {\n\n // initializes an empty array\n let locations = [];\n\n // adds the single location property from bio to the locations array\n locations.push(bio.contacts.location);\n\n // iterates through school locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide:\n // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop\n education.schools.forEach(function (school) {\n locations.push(school.location);\n });\n\n // iterates through work locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide above.\n work.jobs.forEach(function (job) {\n locations.push(job.location);\n });\n\n return locations;\n }",
"function indexOf(distance) {\n flushPendingChanges.call(this);\n var index = indexOfInternal.call(this, distance);\n return index >= this._length ? -1 : index;\n }",
"getIndex(id, data){\n for(let i=0; i<data.length; i++){\n if(id === data[i].id){\n return i;\n }\n }\n console.log(\"No match found\");\n return 0;\n }",
"function locationFinder() {\n\n // initializes an empty array\n var locations = [];\n\n // adds the single location property from bio to the locations array\n locations.push(bio.contacts.location);\n\n // iterates through school locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide:\n // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop\n education.schools.forEach(function(school){\n locations.push(school.location);\n });\n\n // iterates through work locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide:\n // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop\n work.jobs.forEach(function(job){\n locations.push(job.location);\n });\n // console.log(locations);\n return locations;\n }",
"getIndexForPositionString (positionString = 'a1') {\n const { row, column } = this.getCoordinatesForPositionString(positionString)\n let index = Math.abs(column - 8) + (row * 8)\n index = Math.abs(index - 64)\n return index\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the role definition with the specified name | getByName(name) {
return RoleDefinition(this, `getbyname('${name}')`);
} | [
"function retrieveRoleByName(name) {\n return new Promise(function(resolve, reject) {\n Role.findOne({ name })\n .lean()\n .then(function(role) {\n resolve(role);\n })\n .catch(function(err) {\n reject(err);\n });\n });\n}",
"function getUserRole(name, role){\n switch (role) {\n case \"admin\":\n return `${name} is admin with all access`\n break; //this is not neccesary\n\n case \"subadmin\":\n return `${name} is sub-admin acess to delete and create courses`\n break;\n\n case \"testprep\":\n return `${name} is test-prep access with to delete and create tests `\n break;\n case \"user\":\n return `${name} is a user to consume content`\n break;\n \n default:\n return `${name} is admin access with to delete and create tests `\n break;\n }\n}",
"getRole (roleId) {\n assert.equal(typeof roleId, 'string', 'roleId must be string')\n return this._apiRequest(`/role/${roleId}`)\n }",
"findByName(name) {\n return this.routeGroups.find(g => g.name === name);\n }",
"function roleExists(roleName){\r\n for (i = 0; i < Z_ROLES.length; i++) {\r\n var z_userrole = Z_ROLES[i].toString().substring(0,25).trim();\r\n\t if(z_userrole.toUpperCase() == roleName.toUpperCase()) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}",
"get roleId() {\n return this.getStringAttribute('role_id');\n }",
"visitRole_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function roleDispatcher(name, prototype) {\n var role = roleDetails(name);\n\n if (helpers.isUndefined(prototype[role.pluralName])) {\n prototype._definedRoles.push(name);\n\n prototype[role.pluralName] = function() {\n return this[role.getter]();\n };\n }\n }",
"function getRole(roleIndex) {\n\tif (jQuery.type(roleIndex) == 'string') {\n\t\troleIndex = stripLeadingURL(roleIndex);\n\t\troleIndex = parseInt(roleIndex);\n\t}\n\treturn roles[roleIndex];\n}",
"get(name) {\n if (name.startsWith('$')) {\n return this.getConfig(name);\n }\n\n if (name.startsWith('@')) {\n return this.getAttribute(name);\n }\n\n return this.getChild(name);\n }",
"static get(name, id, state, opts) {\n return new ServiceLinkedRole(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }",
"function setRole(characterName, role) {\n var data = {};\n data.characterName = characterName;\n data.role = role;\n\n var promise = $http.post(UtilsSvc.getUrlPrefix() + \"/api/character/role/\", data).then(function(response) {\n return response.data;\n });\n return promise;\n }",
"getMacro(name) {\n const len = this.stack.length - 1;\n for (let i = len; i >= 0; i--) {\n const inst = this.stack[i]._getMacro(name);\n if (inst !== null) {\n return inst;\n }\n }\n return null;\n }",
"static get noRole() { return NO_ROLE; }",
"getRole() {\n return this.empRole;\n }",
"_getExpansion(name) {\n const definition = this.macros.get(name);\n\n if (definition == null) {\n // mainly checking for undefined here\n return definition;\n }\n\n const expansion = typeof definition === \"function\" ? definition(this) : definition;\n\n if (typeof expansion === \"string\") {\n let numArgs = 0;\n\n if (expansion.indexOf(\"#\") !== -1) {\n const stripped = expansion.replace(/##/g, \"\");\n\n while (stripped.indexOf(\"#\" + (numArgs + 1)) !== -1) {\n ++numArgs;\n }\n }\n\n const bodyLexer = new Lexer(expansion, this.settings);\n const tokens = [];\n let tok = bodyLexer.lex();\n\n while (tok.text !== \"EOF\") {\n tokens.push(tok);\n tok = bodyLexer.lex();\n }\n\n tokens.reverse(); // to fit in with stack using push and pop\n\n const expanded = {\n tokens,\n numArgs\n };\n return expanded;\n }\n\n return expansion;\n }",
"function getLevelRole(level) {\n let roleID;\n for (const reward of role_rewards) {\n if (level >= reward[0]) roleID = reward[1];\n }\n return roleID;\n}",
"getMentorByName(mentorName) {\n const allMentors = this.getMentorList();\n return allMentors.find(mentor => mentor.name.toLowerCase() === mentorName.toLowerCase());\n }",
"_findListByName(name) {\n return this._findList(l => l.name === name);\n }",
"async getRoles() {\n let roles = await groupFunctions.getRoles(this.groupId, this._id);\n return [].concat(roles).map(x=> new Role(x, this.groupId, this._id));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Switches back to default content. For example when you selected the frame and need to get out from it. | static async switchToDefaultContent() {
await browser.switchTo().defaultContent();
} | [
"function clearContentBox(){\n\t\tcontent.html('');\n\t}",
"function OLiframeBack(){\r\n if(parent==self){\r\n alert('This feature is only for iframe content');\r\n return;\r\n }\r\n history.back();\r\n}",
"function backToWinMenu() {\n changeVisibility(\"menu\");\n changeVisibility(\"winScreen\");\n} // backToWinMenu",
"handleFrameSelectDialogClosed() {\n console.log('setting select frame ed to null');\n this.setState( { selectFrame : { ed: null, position: 'start' } } );\n }",
"function backToMain() {\n clearInterval(timer);\n $(\"game-view\").classList.add(\"hidden\");\n $(\"menu-view\").classList.remove(\"hidden\");\n }",
"function backToLoseMenu() {\n changeVisibility(\"menu\");\n changeVisibility(\"loseScreen\");\n} // backToLoseMenu",
"function clearSelectedStory() {\n if(selectedStoryButton) {\n selectedStoryButton.removeClass(\"active\");\n }\n selectedStoryButton = null;\n loadedStory = null;\n editorDirty = false;\n $(\"#editor-placeholder\").removeClass(\"d-none\");\n $(\"#editor-area-activities\").addClass(\"d-none\");\n $(\"#editor-area-missions\").addClass(\"d-none\");\n}",
"function on_mouse_out_editor()\n{\n\t// deselect things on it\n\teditor_deselect(editor_context);\n}",
"function blockContent()\n{\n\t// show stop button\n\tdocument.getElementById('next_link').style.display = \"none\";\n\tdocument.getElementById('submit_link').style.display = \"none\";\n\tdocument.getElementById('exit_link').style.display = \"\";\n\tonLastScreen();\n\t\n\t// set progress bar to 100%\n\tdocument.getElementById('progress_bar').style.width = '100%';\n\n\t// load the screen with the information that content is blocked\n\tframes['myFrame'].location.href = getContentFolderName() + '/blocked.htm';\n}",
"function switchContent() {\n let nodeId= $(clickedNode).attr('id');\n let node = nodeMap.get(nodeId);\n $(clickedNode).children(\".node_inhalt\").toggleClass(\"invis\");\n if($(clickedNode).children(\".node_inhalt\").hasClass(\"invis\")){\n node.toggleToAbstract();\n node.focus(); }\n else{\n node.toggleToDetailed();\n }\n\n}",
"_resetThreadPane() {\n if (gDBView)\n gCurrentlyDisplayedMessage = gDBView.currentlyDisplayedMessage;\n\n ClearThreadPaneSelection();\n ClearThreadPane();\n ClearMessagePane();\n }",
"function AtD_restore_text_area()\n{\n\t/* clear the error HTML out of the preview div */\n\tAtD.remove('content');\n\n\t/* swap the preview div for the textarea, notice how I have to restore the appropriate class/id/style attributes */\n var content = jQuery('#content').html();\n\n\tif ( navigator.appName == 'Microsoft Internet Explorer' )\n\t\tcontent = content.replace(/<BR.*?class.*?atd_remove_me.*?>/gi, \"\\n\");\n\n\tjQuery('#content').replaceWith( AtD.content_canvas );\n\tjQuery('#content').val( content.replace(/\\<\\;/g, '<').replace(/\\>\\;/g, '>').replace(/\\&/g, '&') );\n\tjQuery('#content').height(AtD.height);\n\n\tif ( AtD_qtbutton ) {\n\t\t/* change the link text back to its original label */\n\t\tjQuery(AtD_qtbutton).val( AtD.getLang('button_proofread', 'proofread') );\n\t\tjQuery(AtD_qtbutton).css({ 'color' : '#464646' });\n\n\t\t/* enable the toolbar buttons */\n\t\tjQuery( AtD_qtbutton ).siblings('input').andSelf().attr( 'disabled', false );\n\t}\n\n\t/* restore autosave */\n\tif ( AtD.autosave != undefined )\n\t\tautosave = AtD.autosave;\n}",
"closeContentMetaPreview() {\n this.setState(() => ({ ...CONTENT_META_PREVIEW_BASE_STATE }));\n }",
"function goBack(){\n if(screen.current == screen.combat) showMain();\n else if(screen.current == screen.input) setMain(createCombatTable(), screen.combat);\n}",
"reset() {\r\n\t\tthis.changeState(this.initial);\r\n\t}",
"function clearSelection() {\n\t\t$(\"#rootPanel\").css(\"background\",\"url('images/servergroup/commander bg.png')\");\n\t\t$(\"#rootPanel\").find(\"div\").css(\"color\", \"#000000\");\n\t\t$(\"#rootPanel\").find(\"img.focus\").hide();\n\t\t$(\".server\").css(\"background\", \"#ffffff\");\n\t\t$(\".server\").find(\"div\").css(\"color\", \"#000000\");\n\t\t$(\".server\").find(\"img.focus\").hide();\n\t\t$(\".group\").css(\"background\", \"url('images/servergroup/group bg.png')\");\n\t\t$(\".group\").find(\"div\").css(\"color\", \"#000000\");\n\t\t$(\".group\").find(\".groupIcon\").removeClass(\"groupIconFocus\");\n\t\t$(\".group\").find(\".groupToggleIconFocus\").hide();\n\t\t$(\".group\").find(\".groupToggleIcon\").show();\n\t}",
"function switchToBlockly() {\n Blockly.hideChaff();\n var workspace = ROBERTA_PROGRAM.getBlocklyWorkspace();\n workspace.markFocused();\n $('#brickly').css('display', 'none');\n $('#tabBlockly').click();\n workspace.setVisible(true);\n Blockly.svgResize(workspace);\n bricklyActive = false;\n $(window).resize();\n }",
"function f_resetAll(){\n fdoc.find('.spEdit').removeAttr('contenteditable').removeClass('spEdit');\n fdoc.find('.targetOutline').removeAttr('contenteditable').removeClass('targetOutline');\n fdoc.find('#ipkMenu').hide();\n fdoc.find('.ipkMenuCopyAnime').removeClass('ipkMenuCopyAnime');\n $('.sp-show-edit-only-place').css('opacity','0.2');\n f_resetHiddenBox();\n }",
"function toggleFrames(imgName) {\n\n\t//Show home page if img name is empty\n\tif(imgName === '')\n\t{\n\t\tparent.frame2.location=urls[\"home\"];\n\t\treturn;\n\t}\n\t\n\t//Update frame source if empty\n\tif(imgName !== 'frame2' && imgName !== 'settings')\n\t{\n\t\tvar frameSrc = parent.document.getElementById(imgName + 'Frame').src;\n\t\tif(frameSrc == 'undefined' || frameSrc === '' || frameSrc === window.location.origin + \"/frame.html\")\n\t\t\tparent.document.getElementById(imgName + 'Frame').src = urls[imgName];\n\t}\n\t\n\t//Get the content frameset\n var frameset = parent.document.getElementById(\"content\");\n\tvar count=0;\n\tframeSetCols = \"\";\n\tvar frameIndex = -1;\n\t\n\t//Update the frameset cols, to make the frame corresponding to this imgName visible\n\tfor(i=1;i<frameset.children.length - 1;i++)\n\t{\n\t var frame = frameset.children[i];\n\t\tif(frameSetCols !== '')\n\t\t{\n\t\t\tframeSetCols += \",\"\n\t\t\tframeIndex = i;\n\t\t}\n\t\tif(frame.id === imgName + 'Frame' || frame.id === imgName)\n\t\t{\n\t\t\tframeSetCols += \"*\";\n\t\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tframeSetCols += \"0%\";\n\t\t}\n\t\t\n\t}\n\tframeset.cols= \"5%,\" + frameSetCols + \",5%\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function to construct a legend for the given singleband vis parameters. Requires that the vis parameters specify 'min' and 'max' but not 'bands'. | function makeLegend(vis) {
var lon = ee.Image.pixelLonLat().select('longitude');
var gradient = lon.multiply((vis.max-vis.min)/100.0).add(vis.min);
var legendImage = gradient.visualize(vis);
// In case you really need it, get the color ramp as an image:
print(legendImage.getThumbURL({bbox:'0,0,100,8', dimensions:'256x20'}));
// Otherwise, add it to a panel and add the panel to the map.
var thumb = ui.Thumbnail({
image: legendImage,
params: {bbox:'0,0,100,8', dimensions:'256x20'},
style: {padding: '1px', position: 'bottom-center'}
});
var panel = ui.Panel({
widgets: [
ui.Label(String(vis['min'])),
ui.Label({style: {stretch: 'horizontal'}}),
ui.Label(vis['max'])
],
layout: ui.Panel.Layout.flow('horizontal'),
style: {stretch: 'horizontal'}
});
return ui.Panel().add(panel).add(thumb);
} | [
"function makeLegendBins(input_raster) {\n\t\tvar population_raster_colours = [\"#ffffcc\", \"#a1dab4\", \"#41b6c4\", \"#2c7fb8\", \"#253494\"];\n\t\tvar population_raster_bins = [\"0-4\", \"4-7\", \"7-10\", \"10-14\", \">14\"];\n\t\tvar travel_time_raster_colours = [\"#ca0020\", \"#eb846e\", \"#f5d6c8\", \"#cee3ed\", \"#75b4d4\", \"#0571b0\"];\n\t\t//Set impedance raster road values according to method of transport\n\t\tif ($(\"#impedance_select\").find(\"option:selected\").attr(\"id\") == \"walking\") {\n\t\t\tvar roadSpeed = \"12\";\n\t\t} else if ($(\"#impedance_select\").find(\"option:selected\").attr(\"id\") == \"cycling\") {\n\t\t\tvar roadSpeed = \"4\";\n\t\t} else {\n\t\t\tvar roadSpeed = \"1\";\n\t\t};\t\t\n\t\tvar travel_time_raster_bins = [roadSpeed, \"6\", \"24\", \"36\", \"48\", \"60\"];\n\t\tvar time_cost_raster_colours = [\"#1a9641\", \"#58b353\", \"#96d165\", \"#c3e586\", \"#ebf6ac\", \"#feedaa\", \"#fdc980\", \"#f89d59\", \"#e75b3a\", \"#d7191c\"];\n\t\tvar timeTravel = parseFloat($(\"#time_travel\").val()).toFixed(2);\n\t\tvar greaterThan = \">\";\n\t\tvar time_cost_raster_bins = [\"0\", ((timeTravel/4).toFixed(2)).toString(),((timeTravel/3).toFixed(2)).toString(), ((timeTravel/2).toFixed(2)).toString(),(timeTravel).toString(), (timeTravel * 2).toString(), (timeTravel * 3).toString(), (timeTravel * 4).toString(), (timeTravel * 5).toString(), greaterThan.concat(((timeTravel * 6).toFixed(2)).toString())];\n\t\tvar col_str = \"_colours\";\n\t\tvar bin_str = \"_bins\";\n\t\tvar colour = eval(input_raster.concat(col_str));\n\t\tvar bin_range = eval(input_raster.concat(bin_str));\n\t\tif (input_raster == 'population_raster'){\n\t\t\textraString = ' per grid square';\n\t\t} else if (input_raster == 'travel_time_raster') {\n\t\t\textraString = ' minutes per Km';\n\t\t} else {\n\t\t\textraString = ' hour(s) from facility';\n\t\t}\n\t\tvar html = '<h5>Legend</h5><ul class=\"legend_list\" style=\"list-style-type: none; padding-left:5px;\">';\n\t\tfor (var i = 0; i < colour.length; i++ ) {\n\t\t\thtml += '<li><i style=\"background: ' + colour[i] + '\"></i>' + bin_range[i] + extraString + '</li>'\n\t\t};\n\t\thtml += '</ul>';\n\t\t$(\"#legend_bins\").html(html);\n\t}",
"function drawLegend() {\n var shown = buildLabels();\n var idx = 0;\n var legend = svgPath.selectAll(\".legend\").data(colorPath.domain()).enter()\n .append(\"g\").attr(\"class\", \"legend\").attr(\"transform\", function(d) {\n // Use our enumerated idx for labels, not all-color index i\n var y = 0;\n if (shown.includes(d)) {\n y = ph_m + (idx * (pl_w + 2));\n idx++;\n }\n return \"translate(0,\" + y + \")\";\n });\n legend.append(\"rect\").attr(\"x\", ph_m).attr(\"width\", pl_w).attr(\"height\",\n pl_w).style(\"fill\", colorPath).style(\"visibility\", function(d) {\n return shown.includes(d) ? \"visible\" : \"hidden\";\n });\n var x_offset = (ph_m * 2) + pl_w;\n var y_offset = pl_w / 2;\n legend.append(\"text\").attr(\"x\", x_offset).attr(\"y\", y_offset).attr(\"dy\",\n \".35em\").style(\"text-anchor\", \"begin\").style(\"font-size\", \"12px\")\n .text(function(d) {\n if (shown.includes(d)) {\n var core = '';\n var label = '';\n if (d % 2 === 0) {\n isd = d / 4 + 1;\n core = ' (core)';\n } else {\n isd = (d - 1) / 4 + 1;\n }\n if (iaLabels && iaLabels.ISD && iaLabels.ISD[String(isd)]) {\n label = ' ' + iaLabels.ISD[String(isd)];\n }\n return 'ISD-' + isd + label + core;\n } else {\n return null;\n }\n });\n}",
"initLegend() {\n const self = this;\n\n // Array containing all legend lines (visible or not)\n self.d3.legendLines = [];\n self.curData.forEach(function (datum, index) {\n self.d3.legendLines.push(\n self.d3.o.legend.append(\"p\")\n .style(\"color\", function () {\n if (self.d3.visibleCurves[index]) {\n return self.colorPalette[index];\n } else {\n return \"#CCC\";\n }\n })\n .attr(\"class\", \"ts_label\")\n .style(\"font-size\", \"0.8em\")\n .style(\"cursor\", \"pointer\")\n .style(\"margin\", \"0px 3px\")\n .text(datum.funcId)\n .on(\"click\", function () {\n if (!self.isLoading) {\n // Toggle visibility of the clicked TS\n self.d3.visibleCurves[index] = !self.d3.visibleCurves[index];\n self.quickUpdate();\n }\n })\n .on(\"mouseover\", function () {\n d3.select(this).style(\"text-decoration\", \"underline\");\n })\n .on(\"mouseout\", function () {\n d3.select(this).style(\"text-decoration\", \"none\");\n })\n );\n });\n }",
"function createLegend(legend, chartData, chartOptions, total, rowIndex) {\n\n var totalText = (chartOptions[0].legend[0].totalText) ? chartOptions[0].legend[0].totalText : \"Total : \";\n var legendTitle = (chartOptions[0].legend[0].title) ? chartOptions[0].legend[0].title : \"\";\n var html = \"\";\n\n if (chartOptions[0].legend[0].title) {\n html += \"<div class='spc-legend-head'><h3>\" + legendTitle + \"</h3></div>\";\n }\n html += \"<table class='spc-legend-content'>\";\n html += \"<tr class='spc-legend-th'>\";\n for (var i = 0; i < chartOptions[0].legend[0].columns.length; i++) {\n if (i === 0) {\n html += \"<td colspan='2'>\" + chartOptions[0].legend[0].columns[i] + \"</span></td>\";\n } else {\n html += \"<td>\" + chartOptions[0].legend[0].columns[i] + \"</span></td>\";\n }\n\n }\n html += \"</tr>\";\n var rowsArray = [];\n for (var i = 0; i < chartData.length; i++) {\n var legendGuidesHmtl = \"<div class='spc-legend-guides' style='width:16px;height:16px;background-color:\" + chartData[i].color + \"'></div>\";\n var trId = canvasId + \"_legcol_\" + i;\n\n rowsArray.push(trId);\n\n html += \"<tr id='\" + trId + \"' style='color:\" + chartData[i].color + (typeof rowIndex === 'number' && rowIndex === i ? ';background:' + '#F3F3F3' : '') + \"'>\";\n html += \"<td width='21'>\" + legendGuidesHmtl + \"</td>\"; // Slice guides\n\n for (var k = 0; k < chartOptions[0].legend[0].columns.length; k++) {\n var content = \"\";\n switch (k) {\n case 0:\n content = chartData[i].name;\n break;\n case 1:\n content = chartData[i].value;\n break;\n case 2:\n content = Math.round((chartData[i].value / total) * 100) + \"%\";\n break;\n }\n html += \"<td><span>\" + content + \"</span></td>\";\n }\n html += \"</tr>\";\n\n\n }\n html += \"</table>\";\n if (chartOptions[0].legend[0].showTotal) {\n html += \"<div class='spc-legend-foot'><p>\" + totalText + \"\" + total + \"</span></div>\";\n }\n\n legend.innerHTML = html;\n\n // Interactivity preference\n var interactivity = (chartOptions[0].interactivity) ? chartOptions[0].interactivity : \"enabled\";\n if (interactivity === \"enabled\") { // If enabled\n\n // Attach mouse Event listeners to table rows\n for (var i = 0; i < rowsArray.length; i++) {\n var thisRow = document.getElementById(rowsArray[i]);\n thisRow.chrtData = chartData;\n thisRow.options = chartOptions;\n thisRow.sliceData = chartData[i];\n thisRow.slice = i;\n thisRow.mouseout = true;\n\n thisRow.addEventListener(\"mousedown\", function (e) {\n return function () {\n handleClick(this.chrtData, this.options, this.slice, this.sliceData);\n };\n }(this.chrtData, this.options, this.slice, this.sliceData), false);\n\n var mouseOverFunc = function () {\n\n return function () {\n this.style.background = '#F3F3F3';\n this.style.cursor = 'pointer';\n handleOver(this.chrtData, this.options, this.sliceData);\n };\n };\n\n thisRow.addEventListener(\"mouseover\", mouseOverFunc(this.chrtData, this.options, this.sliceData), false);\n\n thisRow.addEventListener(\"mouseleave\", function (e) {\n if (e.target === this && e.target.clientHeight !== 0) {\n this.style.background = 'transparent';\n this.sliceData.mouseIn = false;\n this.sliceData.focused = false;\n draw(this.chrtData, this.options);\n }\n }, false);\n }\n }\n\n function handleOver(data, options, sliceData) {\n // Assign the hovered element in sliceData\n if (!sliceData.mouseIn) {\n sliceData.mouseIn = true;\n sliceData.focused = true;\n console.log(\"mouse in\");\n draw(data, options);\n }\n return;\n }\n\n /*\n * Handles mouse clicks on legend table rows\n */\n function handleClick(data, options, slice, sliceData) {\n // Reset explode slices\n for (var i = 0; i < data.length; i++) {\n if (i !== slice) {\n data[i].explode = false;\n }\n }\n\n // Check if slice is explode and pull it in or explode it accordingly\n sliceData.explode = (sliceData.explode) ? false : true;\n draw(data, options);\n }\n\n }",
"createLegends() {\n let legends = [];\n //make on legend for each selected stock\n for (var i in this.state.selectedStocks) {\n var name = this.state.selectedStocks[i][\"name\"];\n var col = this.state.selectedStocks[i][\"color\"];\n var categories = [];\n categories.push({ key: name, label: name });\n\n //style for colored line in legend\n var legendLineStyle = {\n backgroundcolor: col,\n width: \"20px\",\n marginLeft: \"3px\",\n marginRight: \"3px\",\n marginTop: \"10px\",\n height: \"3px\",\n backgroundColor: col,\n float: \"left\"\n };\n\n legends.push(\n <span className=\"legend\">\n <hr style={legendLineStyle} />\n {name}\n </span>\n );\n }\n\n return legends;\n }",
"function computeLegend() {\n colorsLegend = [];\n sizesLegend = [];\n sizesLegendText = [];\n R = 0;\n if (sizeType != \"none\" && r!=0 && r!=\"\") {\n if (sizeType == \"scalar\" || sizeType == \"degree\") {\n // test for ints\n var isIntScalar=true,j=0;\n while (j<N && isIntScalar){isIntScalar=isInt(rawSizes[j]); j++;}\n // integer scalars\n if (isIntScalar) {\n var numInts = d3.max(rawSizes)-d3.min(rawSizes)+1;\n // <= 9 values\n if (numInts <= 9){\n sizesLegend = d3.range(d3.min(rawSizes),d3.max(rawSizes)+1);\n }\n // > 9 values\n else\n {\n lower = d3.min(rawSizes);\n upper = d3.max(rawSizes);\n bins = 4;\n step = (upper-lower)/bins;\n sizesLegend.push(lower);\n for (var i=1; i<bins; i++) {sizesLegend.push(lower+i*step);}\n sizesLegend.push(upper);\n }\n }\n // noninteger scalars\n else\n {\n lower = d3.min(rawSizes);\n upper = d3.max(rawSizes);\n bins = 4;\n step = (upper-lower)/bins;\n sizesLegend.push(rounddown(lower,10));\n for (var i=1; i<bins; i++) {sizesLegend.push(round(lower+i*step,10));}\n sizesLegend.push(roundup(upper,10));\n }\n sizesLegendText = sizesLegend.slice(0);\n }\n else if (sizeType == \"binary\") {\n sizesLegendText = [\"false\",\"true\"];\n sizesLegend = [0,1];\n }\n if (sizeType == \"degree\"){\n for (var i in sizesLegend){\n sizesLegend[i] = scaleSize(Math.sqrt(sizesLegend[i]));\n }\n }\n else {\n for (var i in sizesLegend){\n sizesLegend[i] = scaleSize(sizesLegend[i]);\n }\n }\n R = r*d3.max(sizesLegend);\n }\n if (colorType != \"none\") {\n if (colorType == \"categorical\") {\n colorsLegend = scaleColorCategory.domain();\n colorsLegendText = d3.values(catNames);\n }\n else if (colorType == \"binary\") {\n colorsLegend = [0,1];\n colorsLegendText = [\"false\",\"true\"];\n }\n else if (colorType == \"scalar\" || colorType == \"degree\") {\n // test for ints\n var isIntScalar=true,j=0;\n while (j<N && isIntScalar){isIntScalar=isInt(rawColors[j]); j++;}\n // integer scalars\n if (isIntScalar) {\n var numInts = d3.max(rawColors)-d3.min(rawColors)+1;\n // <= 9 values\n if (numInts <= 9){\n colorsLegend = d3.range(d3.min(rawColors),d3.max(rawColors)+1);\n colorsLegendText = colorsLegend.slice(0);\n }\n // > 9 values\n else\n {\n lower = d3.min(rawColors);\n upper = d3.max(rawColors);\n bins = 4;\n step = (upper-lower)/bins;\n colorsLegend.push(lower);\n for (var i=1; i<bins; i++) {colorsLegend.push(lower+i*step);}\n colorsLegend.push(upper);\n colorsLegendText = colorsLegend.slice(0);\n }\n }\n // noninteger scalars\n else\n {\n lower = d3.min(rawColors);\n upper = d3.max(rawColors);\n bins = 4;\n step = (upper-lower)/bins;\n colorsLegend.push(rounddown(lower,10));\n for (var i=1; i<bins; i++) {colorsLegend.push(round(lower+i*step,10));}\n colorsLegend.push(roundup(upper,10));\n colorsLegendText = colorsLegend.slice(0);\n }\n }\n else if (colorType == \"scalarCategorical\") {\n lower = d3.min(rawColors);\n upper = d3.max(rawColors);\n bins = 4;\n step = (upper-lower)/bins;\n colorsLegend.push(lower);\n for (var i=1; i<bins; i++) {colorsLegend.push(Math.round(lower+i*step));}\n colorsLegend.push(upper);\n colorsLegendText = colorsLegend.slice(0);\n }\n }\n drawLegend();\n}",
"function createLegendBrokerDisGB() {\n const path = d3.geoPath();\n const legend_table = d3.select(\"#legend-table\");\n\n // -- broker --\n const broker_row = legend_table.append(\"tr\");\n const broker_svg = broker_row.append(\"td\").append(\"svg\");\n broker_svg\n .attr(\"height\", 20)\n .attr(\"width\", 20);\n const broker_point = createGeoJsonPoint([10,10]);\n\n // point\n path.pointRadius(3.5)\n broker_svg.append(\"path\")\n .attr(\"fill\", \"black\")\n .datum(broker_point)\n .attr(\"d\", path);\n\n // outline\n path.pointRadius(7)\n broker_svg.append(\"path\")\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"black\")\n .attr(\"stroke-width\", \"2.5\")\n .datum(broker_point)\n .attr(\"d\", path);\n\n // text\n broker_row.append(\"td\").text(\"– Broker\");\n\n // -- area --\n const broker_row2 = legend_table.append(\"tr\");\n broker_row2.append(\"td\").text(\"Colored area\")\n broker_row2.append(\"td\").text(\"– Broker area\")\n}",
"function createBweCompoundLegend(peerConnectionElement, reportId) {\n var legend = document.createElement('div');\n for (var prop in bweCompoundGraphConfig) {\n var div = document.createElement('div');\n legend.appendChild(div);\n div.innerHTML = '<input type=checkbox checked></input>' + prop;\n div.style.color = bweCompoundGraphConfig[prop].color;\n div.dataSeriesId = reportId + '-' + prop;\n div.graphViewId =\n peerConnectionElement.id + '-' + reportId + '-bweCompound';\n div.firstChild.addEventListener('click', function(event) {\n var target =\n peerConnectionDataStore[peerConnectionElement.id].getDataSeries(\n event.target.parentNode.dataSeriesId);\n target.show(event.target.checked);\n graphViews[event.target.parentNode.graphViewId].repaint();\n });\n }\n return legend;\n}",
"_applyLayoutOptions() {\n const self = this;\n const base_layout = this._base_layout;\n const render_layout = this.layout;\n const base_color_scale = base_layout.color.find(function (item) {\n return item.scale_function && item.scale_function === 'categorical_bin';\n });\n const color_scale = render_layout.color.find(function (item) {\n return item.scale_function && item.scale_function === 'categorical_bin';\n });\n if (!base_color_scale) {\n // This can be a placeholder (empty categories & values), but it needs to be there\n throw new Error('Interval tracks must define a `categorical_bin` color scale');\n }\n\n const has_colors = base_color_scale.parameters.categories.length && base_color_scale.parameters.values.length;\n const has_legend = base_layout.legend && base_layout.legend.length;\n\n if (!!has_colors ^ !!has_legend) {\n // Don't allow color OR legend to be set manually. It must be both, or neither.\n throw new Error('To use a manually specified color scheme, both color and legend options must be set.');\n }\n\n // Harvest any information about an explicit color field that should be considered when generating colors\n const rgb_option = base_layout.color.find(function (item) {\n return item.scale_function && item.scale_function === 'to_rgb';\n });\n const rgb_field = rgb_option && rgb_option.field;\n\n // Auto-generate legend based on data\n const known_categories = this._generateCategoriesFromData(this.data, rgb_field); // [id, label, itemRgb] items\n\n if (!has_colors && !has_legend) {\n // If no color scheme pre-defined, then make a color scheme that is appropriate and apply to the plot\n // The legend must match the color scheme. If we generate one, then we must generate both.\n\n const colors = this._makeColorScheme(known_categories);\n color_scale.parameters.categories = known_categories.map(function (item) {\n return item[0];\n });\n color_scale.parameters.values = colors;\n\n this.layout.legend = known_categories.map(function (pair, index) {\n const id = pair[0];\n const label = pair[1];\n const item_color = color_scale.parameters.values[index];\n const item = { shape: 'rect', width: 9, label: label, color: item_color };\n item[self.layout.track_split_field] = id;\n return item;\n });\n }\n }",
"function createLegend(colors) {\n\tvar c, text, xloc, yloc, legendWidth, textWidth\n\t// set width based on longest string....\n\ttext = canvasPlot.plotOptions.legendTitle;\n\tvar legendTitleWidth = text.visualLength() \n\tvar maxLabelWidth = Math.max(...colors.map(c => {return c[0].toString().visualLength()}))\n\tvar legendWidth = legendTitleWidth > maxLabelWidth ? legendTitleWidth + 40 : maxLabelWidth + 40\n\tvar nLegendEntries = colors.length;\n\tvar legendHeight = canvasPlot.plotGeometry.legendVSpace * (nLegendEntries + 2);\n\tvar canvas = document.getElementById('legend');\n\tcanvas.width = legendWidth;\n\tcanvas.height = legendHeight;\n\tvar ctx = canvas.getContext('2d');\n\tctx.font = '20px Arial';\n\tctx.fillStyle = 'black'\n\tctx.fillText(text, 10, canvasPlot.plotGeometry.legendVSpace)\n\tctx.beginPath()\n\tctx.fill()\n\tcolors.sort(function(a,b) { // put in alphabetical order\n\t\treturn (a[0] > b[0]) ? 1 : -1\n\t})\n\tfor (var i=0; i<colors.length; i++) {\n\t\tc = colors[i]\n\t\ttext = c[0] \n\t\tyloc = 4+canvasPlot.plotGeometry.legendVSpace*(i+2) \n\t\tctx.fillStyle = 'black';\n\t\tctx.fillText(text, 30, yloc)\n\t\tctx.fillStyle = c[1];\n\t\tctx.beginPath()\n\t\tyloc = yloc - 10\n\t\tctx.arc(15, yloc, 5, 0, Math.PI*2, true)\n\t\tctx.fill()\n\t}\n}",
"function createLegendToggle() {\n\t\tvar toggle = L.easyButton({\n\t\t\tstates: [{\n\t\t\t\tstateName: 'show-legend',\n\t\t\t\ticon: 'fas fa-list',\n\t\t\t\ttitle: 'Toggle Legend',\n\t\t\t\tonClick: function(control) {\n\t\t\t\t\t$(\"div.info.legend.leaflet-control\").hide();\n\t\t\t\t\tcontrol.state('hide-legend');\n\t\t\t\t}\n\t\t\t}, {\n\t\t\t\tstateName: 'hide-legend',\n\t\t\t\ticon: 'fas fa-list',\n\t\t\t\ttitle: 'Toggle Legend',\n\t\t\t\tonClick: function(control) {\n\t\t\t\t\t$(\"div.info.legend.leaflet-control\").show();\n\t\t\t\t\tcontrol.state('show-legend');\n\t\t\t\t}\n\t\t\t}]\n\t\t});\n\t\ttoggle.addTo(map);\n\t}",
"function setSwitch() {\r\n if (document.getElementById(\"rb5\").checked) {\r\n legend.switchType = \"x\";\r\n } else {\r\n legend.switchType = \"v\";\r\n }\r\n legend.validateNow();\r\n }",
"function update_legend(legendData) {\n\n mymap.removeControl(legend);\n\n if(legendData) {\n currentLegendData = new Array();\n //Create an array that holds the bin intervals\n minValue = parseInt(legendData.min);\n interval = parseInt(legendData.interval);\n for(var i = 0; i <= 7; i++)\n currentLegendData.push(minValue + interval * i);\n\n //Remove the legend then add it back with the new values\n legend.addTo(mymap);\n }\n}",
"function drawLegend() {\n var legend = $(\"#legend\");\n legend.empty();\n\n var legendContainer = $(\"<div>\");\n legendContainer.addClass(\"legendContainer\");\n\n // Nur die Labels, die wir auch anzeigen!\n for(var lbl of usedLabels.entries()) {\n var catId = lbl[0];\n var category = categories[catId];\n var color = resourceColorTable[catId];\n legendContainer.append(\"<div class='label'><div class='color' style='background: \"+color+\"'> </div> \"+category+\"</div>\");\n }\n\n legend.append(legendContainer);\n}",
"function genBandName(plasmidId, restricProperty, name, bandStart, bandEnd) {\r\n var eName;\r\n \r\n var nameArray = name.split('-');\r\n if (nameArray.length == 1) {\r\n var enzyme = $.grep(restricProperty, function (d, i) {\r\n return d.name === nameArray[0];\r\n })\r\n eName = enzyme[0].Id + ',' + enzyme[0].Id;\r\n }\r\n if (nameArray.length == 2) {\r\n var enzyme1 = $.grep(restricProperty, function (d, i) {\r\n return d.name === nameArray[0];\r\n })\r\n var enzyme2 = $.grep(restricProperty, function (d, i) {\r\n return d.name === nameArray[1];\r\n })\r\n eName = enzyme1[0].Id + ',' + enzyme2[0].Id;\r\n }\r\n\r\n return plasmidId + \"-\" + eName + \"-\" + bandStart + \"-\" + bandEnd;\r\n}",
"function _initializeLegend(){\r\n // TODO Invoke d3.oracle.ary()\r\n gAry = d3.oracle.ary()\r\n .hideTitle( true )\r\n .showValue( false )\r\n .leftColor( true )\r\n .numberOfColumns( 3 )\r\n .accessors({\r\n color: gLineChart.accessors( 'color' ),\r\n label: gLineChart.accessors( 'series' )\r\n });\r\n\r\n gLegend$ = $( '<div>' );\r\n\r\n if ( pOptions.legendPosition ==='TOP' ) {\r\n gChart$.before( gLegend$ );\r\n } else {\r\n gChart$.after( gLegend$ );\r\n }\r\n }",
"function geneBounds(gn, min, max) {\n var gd = genedefs[gn];\n if (gd === undefined) return;\n min = min !== undefined ? min : gd.basemin;\n max = max !== undefined ? max : gd.basemax;\n gd.min = min;\n gd.max = max;\n var gg = guigenes[gn];\n if (gg) {\n gg.minEle.value = min;\n gg.maxEle.value = max;\n gg.deltaEle.value = gd.delta;\n gg.stepEle.value = gd.step;\n gg.sliderEle.min = min;\n gg.sliderEle.max = max;\n }\n}",
"function createLegendBrokerDHT() {\n const broker_point = createGeoJsonPoint([10,10]);\n\n const path = d3.geoPath();\n const legend_table = d3.select(\"#legend-table\");\n\n // -- broker --\n const broker_row = legend_table.append(\"tr\");\n const broker_svg = broker_row.append(\"td\").append(\"svg\");\n broker_svg\n .attr(\"height\", 20)\n .attr(\"width\", 20);\n\n // point\n path.pointRadius(3.5)\n broker_svg.append(\"path\")\n .attr(\"fill\", \"black\")\n .datum(broker_point)\n .attr(\"d\", path);\n\n // outline\n path.pointRadius(7)\n broker_svg.append(\"path\")\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"black\")\n .attr(\"stroke-width\", \"2.5\")\n .datum(broker_point)\n .attr(\"d\", path);\n\n // text\n broker_row.append(\"td\").text(\"– Broker (can be clicked to highlight corresponding row in table)\");\n\n // -- text for colormap --\n let colormapDHT = [\"#a2c9e6\", \"#7ab4e1\", \"#509edf\", \"#2387e0\", \"#146ec2\", \"#0b559f\"];\n\n const colormap_row = legend_table.append(\"tr\");\n const colormap_svg = colormap_row.append(\"td\").append(\"svg\")\n .attr(\"height\", 20)\n .attr(\"width\", 120);\n\n for (let i = 0; i < colormapDHT.length; i++) {\n colormap_svg.append(\"rect\")\n .attr(\"width\", 20)\n .attr(\"height\", 20)\n .attr(\"x\", 0+i*20)\n .attr(\"y\", 0)\n .attr(\"fill\", colormapDHT[i]);\n }\n\n colormap_row.append(\"td\").html(\"– Broker colors, from 0 topics to most individual topics\");\n}",
"function buildsGridOverParametrizedCurve({\n studyFun, //studyFun: t|->z, z is in study domain,\n curveFun, //studyFun: t|->[x,y], x,y are in model space,\n tA, //tStart\n tB, //tEnd\n tN, //number of steps used to paint measurement arc,\n svgParent, //f.e., stdMod.svgScen,\n\n //conditionally optionals\n //svgel, //possibly existing svgel to avoid recreation\n rgCurveName,\n decorations, //see api in \"destructuring arguments\" below\n\n }){\n\n //-----------------------------\n // //\\\\ destructuring arguments\n //-----------------------------\n decorations = decorations || {};\n var {\n lettersShiftMedpos, //format = [ x, y ]\n decimalDigits,\n measurementStroke,\n measurementStrokeWidth,\n fontSize,\n } = decorations;\n fontSize = fontSize || 12;\n //-----------------------------\n // \\\\// destructuring arguments\n //-----------------------------\n\n\n var returnApi = {};\n\n\n //-----------------------------\n // //\\\\ gets features\n //-----------------------------\n var studyStart = studyFun( tA );\n var studyEnd = studyFun( tB );\n var studyRange = studyEnd - studyStart;\n //-----------------------------\n // \\\\// gets features\n //-----------------------------\n\n\n //--------------------------------------------------------\n // //\\\\ estimates grid thinness\n //--------------------------------------------------------\n //calculates grid's grades\n var decUnitlog = Math.log10( studyRange );\n decUnitlog = Math.floor( decUnitlog );\n\n var decUnit = Math.pow( 10, decUnitlog );\n //if decUnit is too big, decreases it 10 times for dense grid\n decUnit = decUnit > studyRange * 0.5 ? decUnit * 0.1 : decUnit;\n //starts the grid from \"rounded\" grade\n var linesStart = Math.ceil( studyStart / decUnit ) * decUnit;\n\n ///abandoned feature: implements variable scale, for fixed grades\n //var gradeCounter = 0;\n //slider.variableGrades = [];\n //--------------------------------------------------------\n // \\\\// estimates grid thinness\n //--------------------------------------------------------\n\n\n\n\n /*\n //================================================\n // //\\\\ buids thin subgrades\n //================================================\n (function() {\n if( studyRange / decUnit < 7 ) {\n var subGrade = decUnit / 10;\n for( var gline=linesStart-decUnit; gline<=slider.maxVal; gline+=subGrade ) {\n\n if( gline < slider.minVal ) continue; \n ///main level of the grade on vertical axis of the slider\n var mediaModelGradeY =\n //origin on the bottom of svg\n //sconf.pictureHeight + \n mod2inn_scale * (\n //\"-\" because of screen Y inversion:\n - ( gline - slider.minVal ) *\n slider.value2media\n ) + slider.SLIDERS_RULE_BOTTOM\n ;\n ///creates pivots for grid line\n var gridPivots = [\n [ rgBottomPoint.medpos[0], mediaModelGradeY ],\n [ rgTopPoint.medpos[0]+13, mediaModelGradeY ],\n ];\n var svgel = slider.subgrid = nssvg.polyline({\n pivots : gridPivots,\n parent : svgParent,\n style : {\n opacity : 1,\n 'stroke-width' : 1,\n },\n });\n }\n }\n //decSubUnit = decUnit > studyRange * 0.5 ? decUnit * 0.1 : decUnit;\n })();\n //================================================\n // \\\\// buids thin subgrades\n //================================================\n */\n\n\n for( var gline=linesStart; gline<=studyEnd; gline+=decUnit ) {\n\n var t = ( gline - studyStart ) / studyRange * ( tB - tA );\n var gridPos = curveFun( t );\n var gridMedpos = ssF.mod2inn( gridPos, stdMod );\n\n //----------------------------------\n // //\\\\ creates grade radial lines\n //----------------------------------\n var GRID_WIDTH = 0.015;\n var GRID_LETTER_WIDTH = 0.03;\n\n var norm = getsCurveNormal( t, tA, tB );\n var normMedpos = ssF.mod2inn( norm, stdMod );\n var medpos = ssF.mod2inn( [0,0], stdMod );\n var medNorm = [ (normMedpos[0]-medpos[0])*GRID_WIDTH,\n (normMedpos[1]-medpos[1])*GRID_WIDTH,\n ];\n var medLetterNorm = [ (normMedpos[0]-medpos[0])*GRID_LETTER_WIDTH,\n (normMedpos[1]-medpos[1])*GRID_LETTER_WIDTH,\n ];\n var gridPivots = [\n gridMedpos,\n [ gridMedpos[0]-medNorm[0], gridMedpos[1]-medNorm[1] ],\n ];\n var gridLetterPivots = [\n gridMedpos[0]-medLetterNorm[0],\n gridMedpos[1]-medLetterNorm[1]\n ];\n\n nssvg.polyline({\n pivots : gridPivots,\n parent : svgParent,\n style : {\n opacity : 1,\n //for thick grades, width is bigger than from thin grades:\n 'stroke-width' : 2,\n },\n });\n //----------------------------------\n // \\\\// creates grade radial lines\n //----------------------------------\n\n\n\n //---------------------------------------------------------- \n // //\\\\ prints grade digital lablel for math model magnitude\n // measured by the gauge\n //---------------------------------------------------------- \n decimalDigits = decimalDigits || 0;\n\n //implement this ? as a function\n //var variableGrade = slider.variableGrades[ gradeCounter++ ] = {};\n //variableGrade.gline = gline;\n //variableGrade.decimalDigits = decimalDigits;\n //variableGrade.svgel =\n\n var x = gridLetterPivots[0];\n var y = gridLetterPivots[1];\n if( lettersShiftMedpos ) {\n x += lettersShiftMedpos[0];\n y += lettersShiftMedpos[1];\n }\n nssvg.printText({\n text : gline.toFixed( decimalDigits ),\n x,\n y,\n parent : svgParent,\n style : {\n 'font-size' : fontSize,\n 'font-weight' : 'normal',\n 'stroke-width' : '1',\n 'stroke' : '1',\n 'fill' : 'black',\n 'opacity' : 0.5,\n },\n });\n //---------------------------------------------------------- \n // \\\\// prints grade digital lablel for math model magnitude\n //---------------------------------------------------------- \n }\n\n returnApi.measurement = {\n rgName : rgCurveName + '_measurement',\n };\n\n returnApi.drawsMeasurement = drawsMeasurement;\n return returnApi;\n\n\n\n\n function getsCurveNormal( t, tA, tB )\n {\n var step = (tB - tA)/1000;\n var f0 = curveFun( t );\n var f1 = curveFun( t+step );\n //finds \"derivative\", tang\n var tang = [ f1[0]-f0[0], f1[1]-f0[1], ];\n var abs2 = tang[0]*tang[0] + tang[1]*tang[1];\n //finds normal to curve's tangent\n var norm = mat.vector2normalOrts( tang );\n return norm.norm;\n }\n\n\n ///possibly draws the curve-\"pipe\" which is aka \"column\" in thermometer\n function drawsMeasurement( t )\n {\n var step = ( tB - tA ) / tN;\n returnApi.measurement.rgX = ssF.paintsCurve({\n mmedia : svgParent,\n fun : curveFun,\n rgName : returnApi.measurement.rgName,\n strokeWidth : measurementStrokeWidth || 30,\n start : tA, //222, //??? abs value seems irrelevant, just a flag\n step,\n stepsCount : Math.ceil( tN * ( t - tA )/( tB - tA ) ),\n addToStepCount : 1, //adds an extra closing point at the end,\n //addedCssClass : ns.haz( ssD.repoConf[0], 'addedCssClass' ),\n stroke : measurementStroke,\n //for color, otherwise taken\n // from sDomF.getFixedColor( rgName )\n });\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Whether the HTML document is trusted. If trusted, it can execute Javascript in the iframe sandbox. | get trusted() {
return this.content.sandbox.indexOf('allow-scripts') !== -1;
} | [
"function in_iframe () {\r\n try {\r\n return window.self !== window.top;\r\n } catch (e) {\r\n return true;\r\n }\r\n }",
"function secure(spec) {\n\n /*\n * Based on web workers. The sandboxed env. is isolated\n * through a separate process + web browser DOM isolation\n * in Web Workers.\n */\n\n sandbox({\n policy: policy(spec.policy),\n scripts: spec.scripts,\n node: spec.node,\n dependencies: spec.dependencies || []\n });\n }",
"function trust(notebook, translator) {\n translator = translator || nullTranslator;\n const trans = translator.load('jupyterlab');\n if (!notebook.model) {\n return Promise.resolve();\n }\n // Do nothing if already trusted.\n const cells = toArray(notebook.model.cells);\n const trusted = cells.every(cell => cell.trusted);\n // FIXME\n const trustMessage = (React.createElement(\"p\", null,\n trans.__('A trusted Jupyter notebook may execute hidden malicious code when you open it.'),\n React.createElement(\"br\", null),\n trans.__('Selecting trust will re-render this notebook in a trusted state.'),\n React.createElement(\"br\", null),\n trans.__('For more information, see the <a href=\"https://jupyter-server.readthedocs.io/en/stable/operators/security.html\">%1</a>', trans.__('Jupyter security documentation'))));\n if (trusted) {\n return showDialog({\n body: trans.__('Notebook is already trusted'),\n buttons: [Dialog.okButton({ label: trans.__('Ok') })]\n }).then(() => undefined);\n }\n return showDialog({\n body: trustMessage,\n title: trans.__('Trust this notebook?'),\n buttons: [\n Dialog.cancelButton({ label: trans.__('Cancel') }),\n Dialog.warnButton({ label: trans.__('Ok') })\n ] // FIXME?\n }).then(result => {\n if (result.button.accept) {\n cells.forEach(cell => {\n cell.trusted = true;\n });\n }\n });\n }",
"function TrustButtonComponent(props) {\n return (React.createElement(UseSignal, { signal: props.htmlDocument.trustedChanged, initialSender: props.htmlDocument }, session => (React.createElement(ToolbarButtonComponent, { className: \"\", onClick: () => (props.htmlDocument.trusted = !props.htmlDocument.trusted), tooltip: `Whether the HTML file is trusted.\nTrusting the file allows scripts to run in it,\nwhich may result in security risks.\nOnly enable for files you trust.`, label: props.htmlDocument.trusted ? 'Distrust HTML' : 'Trust HTML' }))));\n }",
"function checkIfFramed()\n{\n var anchors, i;\n\n if (window.parent != window) { // Only if we're not the top document\n anchors = document.getElementsByTagName('a');\n for (i = 0; i < anchors.length; i++)\n if (!anchors[i].hasAttribute('target'))\n\tanchors[i].setAttribute('target', '_parent');\n document.body.classList.add('framed'); // Allow the style to do things\n }\n}",
"isOnServer() {\n return !(typeof window !== 'undefined' && window.document);\n }",
"function usingHTMLEditor(){\n\tif(typeof(FCKeditorAPI) != \"undefined\" && (fckEditor = FCKeditorAPI.GetInstance(\"html_body\"))) {\n\t\treturn true;\n\t}else{\n\t\treturn false;\n\t}\n}",
"function formIsInsecure(form) {\n\t\tvar action = form.getAttribute('action');\n\t\tif ( action == null ) return false;\n\t\treturn ( action.substr(0, 8) !== 'https://' );\n\t}",
"function isMixedContent(url){\n if(typeof url === 'undefined' ||\n url === null)\n return false;\n \n var urlObj = getURLObject(url); \n if (urlObj['protocol'] === 'http:' &&\n window.location.protocol === 'https:')\n return true;\n \n return false;\n}",
"function supportsCors() {\n\t\tvar xhr = new XMLHttpRequest();\n\t\tif (\"withCredentials\" in xhr) {\n\t\t\t// Supports CORS\n\t\t\treturn true;\n\t\t} else if (typeof XDomainRequest != \"undefined\") {\n\t\t\t// IE\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}",
"inSafeMode() {\n return this.getLoadSettings().safeMode;\n }",
"function isCalledWithinLightbox() {\n if (jQuery('#renderedInLightBox').val() == undefined) {\n return false;\n }\n\n return jQuery('#renderedInLightBox').val().toUpperCase() == 'TRUE' ||\n jQuery('#renderedInLightBox').val().toUpperCase() == 'YES';\n // reverting for KULRICE-8346\n// try {\n// // For security reasons the browsers will not allow cross server scripts and\n// // throw an exception instead.\n// // Note that bad browsers (e.g. google chrome) will not catch the exception\n// if (jQuery(\"#fancybox-frame\", parent.document).length) {\n// return true;\n// }\n// }\n// catch (e) {\n// // ignoring error\n// }\n//\n// return false;\n}",
"function check_web_storage_support(){\n if(typeof(storage)!==undefined){\n return (true);\n }\n else{\n alert(\"Web storage not supported\");\n return (false);\n }\n}",
"function isEdgeHTML() {\n\t\t// Based on research in October 2020\n\t\tconst w = window\n\t\tconst n = navigator\n\t\treturn (\n\t\t\tcountTruthy([\n\t\t\t\t'msWriteProfilerMark' in w,\n\t\t\t\t'MSStream' in w,\n\t\t\t\t'msLaunchUri' in n,\n\t\t\t\t'msSaveBlob' in n,\n\t\t\t]) >= 3 && !isTrident()\n\t\t)\n\t}",
"function spoofBrowser(){\n\t\tif(haveHTMLAll) return;\n\t\tclass HTMLAllCollection{\n\t\t\tconstructor(){ return undefined; }\n\t\t\tvalueOf(){ return undefined; }\n\t\t}\n\t\tHTMLAllCollection.toString = function toString(){ return htmlAllFn; };\n\t\tconst document = {all: new HTMLAllCollection()};\n\t\tglobalThis.HTMLAllCollection = HTMLAllCollection;\n\t\tglobalThis.window = {HTMLAllCollection, document};\n\t\tglobalThis.document = document;\n\t}",
"function isPortalContainer(window) {\n return window.jQuery('#' + kradVariables.PORTAL_IFRAME_ID).length;\n}",
"function srs_can_republish() {\n var browser = get_browser_agents();\n \n if (browser.Chrome || browser.Firefox) {\n return true;\n }\n \n if (browser.MSIE || browser.QQBrowser) {\n return false;\n }\n \n return false;\n}",
"isInDOM() {\n return document.querySelector(\"#iovon-hybrid-modal\") !== null;\n }",
"function _supportsShadowDom() {\n if (shadowDomIsSupported == null) {\n var head = typeof document !== 'undefined' ? document.head : null;\n shadowDomIsSupported = !!(head && (head.createShadowRoot || head.attachShadow));\n }\n\n return shadowDomIsSupported;\n }",
"function isCookieLockEnabled() {\n return isChromium();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
let procesar = (unArray,callback) => callback (unArray); | function procesar (unArray, callback) {
return callback (unArray)
} | [
"function callback(callback){\n callback()\n}",
"function myFilter(array, callback) {\n return callback(array);\n}",
"function tap(arr, callback){\n callback(arr); \n return arr;\n}",
"function doToArray(array, callback){\n array.forEach(callback)\n}",
"function iterate(callback){\n let array = [\"dog\", \"cat\", \"squirrel\"]\n array.forEach(callback)\n return array\n}",
"function foo(callback){\n callback();\n}",
"function filter(arr, callback){\n var newArr = [];\n for (let i=0; i<arr.length; i++){\n if (callback(arr[i])) newArr.push(arr[i]);\n }\n return newArr;\n}",
"function operate(array, func) {\r\n if (array) {\r\n for (var n=0; n<array.length; n++) {\r\n func(array[n], n);\r\n }\r\n }\r\n return array;\r\n}",
"static conduct(a, b, callback, on) {\r\n callback(a, b)\r\n\r\n }",
"function caonimabzheshiyigewozijixiedeForEach2(arr, fn){\n var newArr = [];\n for(var i = 0; i < arr.length; i++){\n newArr.push(fn(arr[i]));\n }\n return newArr;\n}",
"function mult(valor){\n let arrayMult = array1.map(function (item){\n return item * valor;\n });\n return console.log(arrayMult);\n}",
"function command_executor(arr, light_constructor){\n command_array = command_array_creator(arr);\n light_array = light_array_creator(light_constructor);\n command_array.forEach( command => {\n cmd = command[0],\n [x1, y1] = command[1],\n [x2, y2] = command[2];\n\n for( i = x1; i <= x2; i++){\n for( j = y1; j <= y2; j++){\n light_array[i][j][cmd]();\n }\n }\n })\n return light_array\n}",
"function every(array, callback){\n for (let i = 0; i < arr.length; i++){\n if (!callback(arr[i], i, arr)) return false;\n }\n return true;\n}",
"function receiveCallback(data) {\n receiveIANA(data,session);\n }",
"static fromArray (as) {\n return new Signal(emit => {\n as.map(apply(emit.next))\n emit.complete()\n })\n }",
"function pushAndRun(tark, argArr, callbackIndex) {\n Qtark.push({\n arg: argArr,\n func: tark,\n callbackIndex: callbackIndex\n });\n\n if (!tarking && Qtark.length == 1) {\n processQtark();\n }\n }",
"function giveBackData(error , data){\n console.log('inside callback function');\n console.log(data+\"\");\n}",
"function segregateOddEven(arr,callback){\n let odd=[]\n let even=[] \n arr.map(function(x){\n (x%2==0?odd.push(x):even.push(x));\n })\n console.log(\"segregated array: \"+odd+\" \"+even);\n callback(odd,even,meanCalculator);\n}",
"function mean_with_reduce(array,callback) {\n if (callback) {\n array.map( callback );\n } \n const total = array.reduce((a, b) => a + b);\n return total/array.length;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a 2d plane tag. Image must be in resource folder. does not actuall add to scene. Adds to a list of tags. | function AddTag(image){
var texture = THREE.ImageUtils.loadTexture("img/"+image);
var geometry = new THREE.PlaneGeometry(2,2);
var material = new THREE.MeshBasicMaterial( { map: texture} );
var tag = new THREE.Mesh( geometry, material );
tag.lookAt(camera.position);
$(tag).click(function(){
console.log("clicked!")
});
return tag;
} | [
"function makePlane(width, height){\n var vertexPositionData = [];\n var normalData = [];\n var textureCoordData = [];\n for (var i = 0; i <= height; i++) {\n for (var j = 0; j <= width; j++) {\n //vertex positions rangeing from -1 to 1\n var x = 2*(i / height) - 1;\n var y = 2*(j / width) - 1;\n //texture coordinates rangeing from 0 to 1\n var u = i/height;\n var v = j/width;\n\n normalData.push(0);\n normalData.push(0);\n normalData.push(1);\n textureCoordData.push(u);\n textureCoordData.push(v);\n vertexPositionData.push(x);\n vertexPositionData.push(y);\n vertexPositionData.push(0);\n }\n }\n var indexData = [];\n for (var i = 0; i < height; i++) {\n for (var j = 0; j < width; j++) {\n var first = (i * (width + 1)) + j;\n var second = first + width + 1;\n indexData.push(first);\n indexData.push(second);\n indexData.push(first + 1);\n indexData.push(second);\n indexData.push(second + 1);\n indexData.push(first + 1);\n }\n }\n return {\n position: vertexPositionData,\n normal: normalData,\n texture: textureCoordData,\n index: indexData\n };\n }",
"function definePlane() {\n game.addObject({\n type : 'rect',\n x : 0,\n y : 350,\n width : 800,\n height : 125,\n color : '#333'\n });\n game.draw();\n }",
"function createFeature (active, dir) {\n\n}",
"function gui_add_tag(){\n for (var i = 0 ; i < numbertag_list.length ; i++){\n\ttag = bb1[i].add( workspace.bboxes[i], 'numbertag' ,numbertag_list).name(\"BoundingBoxTag\");\n\tgui_tag.push(tag)\n }\n}",
"function createVehicle() {\n var vehicleAssets = [\"tempCar\"];\n var randomAssetNo = Math.floor(Math.random()*vehicleAssets.length);\n var v = [new Sprite(\"/sprites/vehicles/\"+vehicleAssets[randomAssetNo]),\"right\"];\n v[0].pos[0]= (window.innerWidth/2)-(10*tileSize)/2+(0*tileSize);\n v[0].pos[1]= (window.innerHeight/2)-(10*tileSize)/2+(6*tileSize);\n vehicles[vehicles.length] = v;\n}",
"function CreateSprite(paths, size_factor, size_min,\n\t\t speed_factor, speed_min, left, right){\n\n // Make the mesh \n var size = Math.random()*size_factor + size_min;\n var trand = Math.floor(Math.random()*paths.length);\n var texture= THREE.ImageUtils.loadTexture(paths[trand]);\n var material = new THREE.SpriteMaterial( { map: texture, fog: true, } );\n var sprite = new THREE.Sprite( material );\n sprite.scale.set(size, size, size);\n var speed = Math.random() *speed_factor + speed_min;\n\n // Initial placement\n x = (Math.random()*(right-left))-((right-left)/2);\n y = (Math.random()*3000)-1000;\n sprite = new FallingObject(sprite, speed, x, y, -1000, 0, -1, 0);\n sprite.set_box_rules(2000, -1000, left, right);\n\n \n //sprite.place();\n\n return sprite;\n}",
"function createTag(tag) {\n var btn = $('<button>').text(tag);\n btn.attr(\"value\", tag);\n btn.attr(\"class\", \"tag\");\n\n $(\"#tagsDiv\").append(btn);\n}",
"function createGameObject(src){\n var img = $('<img class=\"draggable game_object\">');\n img.attr('src', src);\n img.appendTo('#playarea_container');\n}",
"function createItem(left, top, image) {\n var item = items.create(left, top, image);\n item.animations.add('spin');\n item.animations.play('spin', 8, true);\n}",
"createPlane(quads){\n\t\tvar plane = {\n\t\t\tvertices:[], normals:[], indices:[], textures:[]\n\t\t};\n\t\tfor (var y = 0; y <= quads; ++y) {\n\t\t\tvar v = -1 + (y * (2 / quads));\n\t\t\tfor (var x = 0; x <= quads; ++x) {\n\t\t\t\tvar u = -1 + (x * (2 / quads));\n\t\t\t\tplane.vertices = plane.vertices.concat([u, v, 0])\n\t\t\t\tplane.normals = plane.normals.concat([0, 0, 1])\n\t\t\t\tplane.textures = plane.textures.concat([x / quads, 1 - (y / quads)]);\n\t\t\t}\n\t\t}\n\t\tvar rowSize = (quads + 1);\n\t\tfor (var y = 0; y < quads; ++y) {\n\t\t\tvar rowOffset0 = (y + 0) * rowSize;\n\t\t\tvar rowOffset1 = (y + 1) * rowSize;\n\t\t\tfor (var x = 0; x < quads; ++x) {\n\t\t\t\tvar offset0 = rowOffset0 + x;\n\t\t\t\tvar offset1 = rowOffset1 + x;\n\t\t\t\tplane.indices = plane.indices.concat(offset0, offset0 + 1, offset1);\n\t\t\t\tplane.indices = plane.indices.concat(offset1, offset0 + 1, offset1 + 1);\n\t\t\t}\n\t\t}\n\t\treturn plane;\n\t}",
"static _create2DShape (typeofShape, width, depth, height, scene) {\n switch (typeofShape) {\n case 0:\n var faceUV = new Array(6)\n for (let i = 0; i < 6; i++) {\n faceUV[i] = new BABYLON.Vector4(0, 0, 0, 0)\n }\n faceUV[4] = new BABYLON.Vector4(0, 0, 1, 1)\n faceUV[5] = new BABYLON.Vector4(0, 0, 1, 1)\n \n var options = {\n width: width,\n height: height,\n depth: depth,\n faceUV: faceUV\n }\n\n return BABYLON.MeshBuilder.CreateBox('pin', options, scene)\n case 1:\n var faceUV2 = new Array(6)\n for (let i = 0; i < 6; i++) {\n faceUV2[i] = new BABYLON.Vector4(0, 0, 0, 0)\n }\n faceUV2[0] = new BABYLON.Vector4(0, 0, 1, 1)\n \n var options2 = {\n diameterTop: width,\n diameterBottom: depth,\n height: height,\n tessellation: 32,\n faceUV: faceUV2\n }\n\n return BABYLON.MeshBuilder.CreateCylinder('pin', options2, scene)\n }\n }",
"function addPlane(color) {\n var customPlaneGeometry = new THREE.PlaneGeometry(project.width, project.height, 1, 1);\n var customPlaneMaterial = new THREE.MeshLambertMaterial(\n {\n color: color,\n transparent: true\n });\n\n customPlane = new THREE.Mesh(customPlaneGeometry, customPlaneMaterial);\n Q3D.application.scene.add(customPlane);\n\n}",
"function setupCat(){\n // cat is the object which you have to shoot. it has the characteristics of an ellipse\n cat.x=width/2;\n cat.y=height/2;\n // the image will be the cat head we used earlier though.\n // since the head is scalable, scale it down\n head.xs=0.1;\n head.ys=0.1;\n}",
"addImgs(single, tiles, z) {\n let queue = [];\n if (single != null) {\n // single image case\n queue.push([new Point(0, 0), single]);\n }\n if (tiles != null) {\n // tiled image case\n for (let tile of tiles) {\n queue.push([new Point(tile.pos[0], tile.pos[1]), tile.img]);\n }\n }\n // add 'em to the game!\n for (let [pos, img] of queue) {\n let e = this.ecs.addEntity();\n this.ecs.addComponent(e, new Component.Position(pos));\n this.ecs.addComponent(e, new Component.StaticRenderable(img, z, StageTarget.World, new Point(0, 0)));\n }\n }",
"function createTempImage(){\n tempImage = game.instantiate(new Sprite('./img/beginplaatje.svg'));\n tempImage.setPosition({x: Settings.canvasWidth/2 - 110, y: Settings.canvasHeight/2 - 110});\n tempImage.setSize({x: 200, y: 200});\n}",
"function create3DTarget(target) {\n let loader = new THREE.TextureLoader();\n let planetSize = .5;\n loader.load(`./assets/img/targets/${target.name}.jpg`, (texture) => {\n let geom = new THREE.SphereGeometry(planetSize, 30, 30);\n let mat = (target.name == 'Sun') ? new THREE.MeshBasicMaterial({map: texture}) : new THREE.MeshLambertMaterial({map: texture});\n let planet = new THREE.Mesh(geom, mat);\n planet.name = target.name; planet.targetIndex = targets.indexOf(target);\n // Positioning\n let targetCartesian = Math.cartesian(target.az, target.el, gridRadius);\n planet.position.x = -targetCartesian.x;\n planet.position.z = -targetCartesian.z;\n planet.position.y = targetCartesian.y;\n planet.lookAt(0, 0, 0); planet.rotateY(Math.radians(target.az));\n // Target specific features\n if (planet.name == 'Saturn') {\n loader.load(`./assets/img/targets/SaturnRing.png`, (texture) => {\n geom = new THREE.RingGeometry(planetSize * 1.116086235489221, planetSize * 2.326699834162521, 84, 1);\n for(var yi = 0; yi < geom.parameters.phiSegments; yi++) {\n var u0 = yi / geom.parameters.phiSegments;\n var u1=(yi + 1) / geom.parameters.phiSegments;\n for(var xi = 0; xi < geom.parameters.thetaSegments; xi++) {\n \t\tvar fi = 2 * (xi + geom.parameters.thetaSegments * yi);\n var v0 = xi / geom.parameters.thetaSegments;\n var v1 = (xi + 1) / geom.parameters.thetaSegments;\n geom.faceVertexUvs[0][fi][0].x = u0; geom.faceVertexUvs[0][fi][0].y = v0;\n geom.faceVertexUvs[0][fi][1].x = u1; geom.faceVertexUvs[0][fi][1].y = v0;\n geom.faceVertexUvs[0][fi][2].x = u0; geom.faceVertexUvs[0][fi][2].y = v1;\n fi++;\n geom.faceVertexUvs[0][fi][0].x = u1; geom.faceVertexUvs[0][fi][0].y = v0;\n geom.faceVertexUvs[0][fi][1].x = u1; geom.faceVertexUvs[0][fi][1].y = v1;\n geom.faceVertexUvs[0][fi][2].x = u0; geom.faceVertexUvs[0][fi][2].y = v1;\n }\n }\n mat = new THREE.MeshLambertMaterial( { map: texture, side: THREE.DoubleSide, transparent: true } );\n let ring = new THREE.Mesh(geom, mat);\n ring.rotateX(27);\n planet.add(ring);\n });\n } else if (target.name == 'Sun') {\n const light = new THREE.PointLight('#d4caba', 1, 500, 0 );\n let lightCartesian = Math.cartesian(target.az, target.el, gridRadius - .5);\n light.position.x = -lightCartesian.x;\n light.position.y = lightCartesian.y;\n light.position.z = -lightCartesian.z;\n scene.add(light);\n }\n // planet.add(new THREE.AxesHelper(5));\n scene.add(planet);\n });\n}",
"function drawEnemyPlanes()\r\n{\r\n for(var i = 0; i < enemyPlanes.length; i++)\r\n {\r\n ctx.drawImage(enemyPlane, enemyPlanes[i][0], enemyPlanes[i][1]);\r\n }\r\n}",
"function addFirstAidItem() {\n //FirstAidKit \n firstAid = new Array();\n firstAidTexture = new THREE.TextureLoader().load('../../Assets/images/firstaid1.png');\n firstAidTexture.wrapS = THREE.RepeatWrapping;\n firstAidTexture.wrapT = THREE.RepeatWrapping;\n firstAidTexture.repeat.set(1, 1);\n firstAidGeometry = new BoxGeometry(2, 1, 2);\n firstAidMaterial = new PhongMaterial({ map: firstAidTexture });\n for (var count = 0; count < 5; count++) {\n firstAid[count] = new Physijs.BoxMesh(firstAidGeometry, firstAidMaterial, 1);\n firstAid[count].receiveShadow = true;\n firstAid[count].castShadow = true;\n firstAid[count].name = \"FirstAid\";\n setFirstAidPosition(firstAid[count]);\n }\n console.log(\"Added FirstAid item to scene\");\n }",
"function addStoneItem() {\n // Stone \n stone = new Array();\n stoneTexture = new THREE.TextureLoader().load('../../Assets/images/stone.jpg');\n stoneTexture.wrapS = THREE.RepeatWrapping;\n stoneTexture.wrapT = THREE.RepeatWrapping;\n stoneTexture.repeat.set(1, 1);\n stoneGeometry = new SphereGeometry(0.5, 5, 5);\n stoneMaterial = new PhongMaterial({ map: stoneTexture });\n for (var count = 0; count < 7; count++) {\n stone[count] = new Physijs.BoxMesh(stoneGeometry, stoneMaterial, 1);\n stone[count].receiveShadow = true;\n stone[count].castShadow = true;\n stone[count].name = \"Stone\";\n setStonePosition(stone[count]);\n }\n console.log(\"Added Stone item to the scene\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enter a parse tree produced by KotlinParsernamedInfix. | enterNamedInfix(ctx) {
} | [
"enterInfixFunctionCall(ctx) {\n\t}",
"enterPreprocessorParenthesis(ctx) {\n\t}",
"enterInOperator(ctx) {\n\t}",
"enterPostfixUnaryOperation(ctx) {\n\t}",
"enterPostfixUnaryExpression(ctx) {\n\t}",
"enterMultiVariableDeclaration(ctx) {\n\t}",
"enterJumpExpression(ctx) {\n\t}",
"enterBlockLevelExpression(ctx) {\n\t}",
"enterPrefixUnaryExpression(ctx) {\n\t}",
"enterParenthesizedType(ctx) {\n\t}",
"function ExpressionParser() {\n \t\tthis.parse = function() {\n\t \t\treturn Statement(); \n\t \t}\n \t\t\n//\t\tStatement := Assignment | Expr\t\n\t\tthis.Statement=function() {return Statement();}\n\t \tfunction Statement() {\n\t \t\tdebugMsg(\"ExpressionParser : Statement\");\n\t\n \t var ast;\n \t // Expressin or Assignment ??\n \t if (lexer.skipLookAhead().type==\"assignmentOperator\") {\n \t \tast = Assignment(); \n \t } else {\n \t \tast = Expr();\n \t }\n \t return ast;\n\t \t}\n\t \t\n//\t\tAssignment := IdentSequence \"=\" Expr \n//\t\tAST: \"=\": l:target, r:source\n \t\tthis.Assignment = function() {return Assignment();}\n \t\tfunction Assignment() {\n \t\t\tdebugMsg(\"ExpressionParser : Assignment\");\n \t\t\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) return false;\n \t\t\n \t\t\tcheck(\"=\"); // Return if it's not an Assignment\n \t\t\n \t\t\tvar expr=Expr();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"=\",ident,expr);\n\t \t}\n \t\t\n\n//\t\tExpr := And {\"|\" And} \t\n//\t\tAST: \"|\": \"left\":And \"right\":And\n \t\tthis.Expr = function () {return Expr();}\t\n \t\tfunction Expr() {\n \t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\n \t\t\tvar ast=And();\n \t\t\tif (!ast) return false;\n \t\t\t\t\t\n \t\t\n \t\t\twhile (test(\"|\") && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"|\",ast,And());\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n \t\n//\t\tAnd := Comparison {\"&\" Comparison}\n//\t\tAST: \"&\": \"left\":Comparasion \"right\":Comparasion\t\n\t\tfunction And() {\n \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\tvar ast=Comparasion();\n \t\t\tif (!ast) return false;\n \t\t\t\t\n \t\t\twhile (test(\"&\") && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"&\",ast,Comparasion());\n\t \t\t}\n\t \t\treturn ast;\n\t \t}\n\t \t \t\n// \t\tComparison := Sum {(\"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" | \"in\") Sum}\n//\t\tAST: \"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" : \"left\":Sum \"right\":Sum\n\t\tfunction Comparasion() {\n \t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\tvar ast=Sum();\n\t\t\tif (!ast) return false;\n\t\t\n\t\t\twhile ((test(\"==\") ||\n\t\t\t\t\ttest(\"!=\") ||\n\t\t\t\t\ttest(\"<=\") ||\n\t\t\t\t\ttest(\">=\") ||\n\t\t\t\t\ttest(\"<\") ||\n\t\t\t\t\ttest(\">\")) ||\n\t\t\t\t\ttest(\"in\") &&\n\t\t\t\t\t!eof())\n\t\t\t{\n \t\t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\t\tvar symbol=lexer.current.content;\n\t\t\t\tlexer.next();\n\t \t\t\tast=new ASTBinaryNode(symbol,ast,Sum());\n\t\t\t} \t\n\t\t\treturn ast;\t\n\t \t}\n\t \t\n//\t\tSum := [\"+\" | \"-\"] Product {(\"+\" | \"-\") Product}\n//\t\tAST: \"+1\" | \"-1\" : l:Product\n//\t\tAST: \"+\" | \"-\" : l:Product | r:Product \n \t\tfunction Sum() {\n \t\t\tdebugMsg(\"ExpressionParser : Sum\");\n\t\t\n\t\t\tvar ast;\n\t\t\t// Handle Leading Sign\n\t\t\tif (test(\"+\") || test(\"-\")) {\n\t\t\t\tvar sign=lexer.current.content+\"1\";\n\t\t\t\tlexer.next();\n\t\t\t\tast=new ASTUnaryNode(sign,Product());\t\n\t \t\t} else {\n\t \t\t\tast=Product();\n\t \t\t} \n \t\t\t\n \t\t\twhile ((test(\"+\") || test(\"-\")) && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Sum\");\n \t\t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Product());\t\t\n \t\t\t} \t\n \t\t\treturn ast;\n \t\t}\n\n//\t\tProduct := Factor {(\"*\" | \"/\" | \"%\") Factor} \t\n\t \tfunction Product() {\n\t \t\tdebugMsg(\"ExpressionParser : Product\");\n\n \t\t\tvar ast=Factor();\n \t\t\n\t \t\twhile ((test(\"*\") || test(\"/\") || test(\"%\")) && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : Product\");\n\n\t \t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Factor());\n \t\t\t} \n\t \t\treturn ast;\n \t\t}\n \t\t\n// \t Factor := \t\t[(\"this\" | \"super\") \".\"]IdentSequence [\"(\" [Expr {\",\" Expr}] \")\"]\n//\t\t\t\t\t | \"!\" Expr \n//\t\t\t\t\t | \"(\" Expr \")\" \n//\t\t\t\t\t | Array \n//\t\t\t\t\t | Boolean\n//\t\t\t\t\t | Integer\n//\t\t\t\t\t | Number\n//\t\t\t\t\t | Character\n//\t\t\t\t\t | String \n \t\tfunction Factor() {\n \t\t\tdebugMsg(\"ExpressionParser : Factor\"+lexer.current.type);\n\n\t \t\tvar ast;\n \t\t\n\t \t\tswitch (lexer.current.type) {\n\t \t\t\t\n\t \t\t\tcase \"token\"\t:\n\t\t\t\t//\tAST: \"functionCall\": l:Ident(Name) r: [0..x]{Params}\n\t\t\t\t\tswitch (lexer.current.content) {\n\t\t\t\t\t\tcase \"new\": \n\t\t\t\t\t\t\tlexer.next();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar ident=Ident(true);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcheck(\"(\");\n\t\t\t\t\t\t\n \t\t\t\t\t\t\tvar param=[];\n \t\t\t\t\t\t\tif(!test(\")\")){\n \t\t\t\t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\t\t\tparam[i]=Expr();\n \t\t\t\t\t\t\t\t}\n \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\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\t\t\t\t\tast=new ASTBinaryNode(\"new\",ident,param);\n \t\t\t\t\t\tbreak;\n \t\t\t\t\t\tcase \"this\":\n \t\t\t\t\t\tcase \"super\":\n\t\t\t\t\t\tcase \"constructor\": return IdentSequence();\n \t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n//\t\t\t\tFactor :=\tIdentSequence \t\t\t\t\n \t\t\t\tcase \"ident\":\n \t\t\t\t return IdentSequence();\n \t\t\t\tbreak;\n \t\t\t\t\n// \t\t\tFactor:= \"!\" Expr\t\t\t\n \t\t\t\tcase \"operator\": \n\t \t\t\t\tif (!test(\"!\")) {\n\t \t\t\t\t\terror.expressionExpected();\n\t \t\t\t\t\treturn false;\n \t\t\t\t\t}\n \t\t\t\t\tlexer.next();\n \t\t\t\t\n\t \t\t\t\tvar expr=Expr();\n \t\t\t\t\tast=new ASTUnaryNode(\"!\",expr);\n\t \t\t\tbreak;\n \t\t\t\t\n//\t\t\t\tFactor:= \"(\" Expr \")\" | Array \t\t\t\n \t\t\t\tcase \"brace\"\t:\n \t\t\t\t\tswitch (lexer.current.content) {\n \t\t\t\t\t\t\n// \t\t\t\t\t \"(\" Expr \")\"\n \t\t\t\t\t\tcase \"(\":\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\tast=Expr();\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\tbreak;\n \t\n \t\t\t\t\t\n \t\t\t\t\t\tdefault:\n \t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t \treturn false;\n\t \t\t\t\t\tbreak;\n\t \t\t\t\t}\n\t \t\t\tbreak;\n \t\t\t\n//\t\t\t\tFactor:= Boolean | Integer | Number | Character | String\n//\t\t\t\tAST: \"literal\": l: \"bool\" | \"int\" | \"float\" | \"string\" | \"char\": content: Value \n\t \t\t\tcase \"_$boolean\" \t\t:\t\t\t\n\t \t\t\tcase \"_$integer\" \t\t:\n\t \t\t\tcase \"_$number\" \t\t:\n\t \t\t\tcase \"_$string\"\t\t\t:\t\t\n\t\t\t\tcase \"_$character\"\t\t:\n\t\t\t\tcase \"null\"\t\t\t\t:\n\t\t\t\t\t\t\t\t\t\t\tast=new ASTUnaryNode(\"literal\",lexer.current);\n \t\t\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\tbreak;\n\t\t\t\t\n//\t\t\t\tNot A Factor \t\t\t\t \t\t\t\t\n \t\t\t\tdefault: \terror.expressionExpected();\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\treturn false;\n\t \t\t\t\t\t\tbreak;\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n\n \n//\t\tIdentSequence := (\"this\" | \"super\") | [(\"this\" | \"super\") \".\"] (\"constructor\" \"(\" [Expr {\",\" Expr}] \")\" | Ident {{ArrayIndex} | \".\" Ident } [\"(\" [Expr {\",\" Expr}] \")\"]);\n//\t\tAST: \"identSequence\": l: [0..x][\"_$this\"|\"_$super\"](\"constructor\" | Ident{Ident | ArrayIndex})\n// \t\tor AST: \"functionCall\": l:AST IdentSequence(Name), r: [0..x]{Params}\n\t\tthis.IdentSequence=function () {return IdentSequence();};\n \t\tfunction IdentSequence() {\n \t\t\tdebugMsg(\"ExpressionParser:IdentSequence()\");\n \t\t\t\n \t\t\tvar ast=new ASTListNode(\"identSequence\");\n \t\t\tif (test(\"this\") || test(\"super\")) {\n \t\t\t\tast.add({\"type\":\"ident\",\"content\":\"_$\"+lexer.current.content,\"line\":lexer.current.line,\"column\":lexer.current.column});\n \t\t\t\tlexer.next();\n \t\t\t\tif (!(test(\".\"))) return ast;\n \t\t\t\tlexer.next();\n \t\t\t}\n\n\t\t\tvar functionCall=false;\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tast.add({\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column});\n\t\t\t\tlexer.next();\n\t\t\t\tcheck(\"(\");\n\t\t\t\tfunctionCall=true;\n\t\t\t} else {\n \t\t\t\tvar ident=Ident(true);\n \t\t\t\n \t\t\t\tast.add(ident);\n \t\t\t\n \t\t\t\tvar index;\n \t\t\t\twhile((test(\".\") || test(\"[\")) && !eof()) {\n \t\t\t\t\t if (test(\".\")) {\n \t\t\t\t\t \tlexer.next();\n \t\t\t\t\t\tast.add(Ident(true));\n \t\t\t\t\t} else ast.add(ArrayIndex());\n \t\t\t\t}\n \t\t\t\tif (test(\"(\")) {\n \t\t\t\t\tfunctionCall=true;\n \t\t\t\t\tlexer.next();\n \t\t\t\t}\n \t\t\t}\n \t\n \t\t\tif (functionCall) {\t\n\t\t\t\tvar param=[];\n\t\t\t\tif(!test(\")\")){\n \t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\tparam[i]=Expr();\t\t\t\t\t\t\t\n \t\t\t\t\t}\n \t\t\t\t}\t \t\t\t\t\t\t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\tast=new ASTBinaryNode(\"functionCall\",ast,param);\n \t\t\t} \n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tArrayIndex:=\"[\" Expr \"]\"\n //\t\tAST: \"arrayIndex\": l: Expr\n \t\tfunction ArrayIndex(){\n \t\t\tdebugMsg(\"ExpressionParser : ArrayIndex\");\n \t\t\tcheck(\"[\");\n \t\t\t \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\"]\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"arrayIndex\",expr);\n \t\t}\n\n//\t\tIdent := Letter {Letter | Digit | \"_\"}\n//\t\tAST: \"ident\", \"content\":Ident\n\t \tthis.Ident=function(forced) {return Ident(forced);}\n \t\tfunction Ident(forced) {\n \t\t\tdebugMsg(\"ExpressionParser:Ident(\"+forced+\")\");\n \t\t\tif (testType(\"ident\")) {\n \t\t\t\tvar ast=lexer.current;\n \t\t\t\tlexer.next();\n \t\t\t\treturn ast;\n \t\t\t} else {\n \t\t\t\tif (!forced) return false; \n \t\t\t\telse { \n \t\t\t\t\terror.identifierExpected();\n\t\t\t\t\treturn SystemIdentifier();\n\t\t\t\t}\n\t\t\t} \t\n \t\t}\n \t}",
"function infixTex(code)\n{\n\treturn function(thing,texArgs)\n\t{\n\t\tvar arity = jme.builtins[thing.tok.name][0].intype.length;\n\t\tif( arity == 1 )\n\t\t{\n\t\t\treturn code+texArgs[0];\n\t\t}\n\t\telse if ( arity == 2 )\n\t\t{\n\t\t\treturn texArgs[0]+' '+code+' '+texArgs[1];\n\t\t}\n\t}\n}",
"function InlineParser() {\n this.preEmphasis = \" \\t\\\\('\\\"\";\n this.postEmphasis = \"- \\t.,:!?;'\\\"\\\\)\";\n this.borderForbidden = \" \\t\\r\\n,\\\"'\";\n this.bodyRegexp = \"[\\\\s\\\\S]*?\";\n this.markers = \"*/_=~+\";\n\n this.emphasisPattern = this.buildEmphasisPattern();\n this.linkPattern = /\\[\\[([^\\]]*)\\](?:\\[([^\\]]*)\\])?\\]/g; // \\1 => link, \\2 => text\n\n // this.clockLinePattern =/^\\s*CLOCK:\\s*\\[[-0-9]+\\s+.*\\d:\\d\\d\\]/;\n // NOTE: this is a weak pattern. does not enforce lookahead of opening bracket type!\n this.timestampPattern =/([\\[<])(\\d{4}-\\d{2}-\\d{2})(?:\\s*([A-Za-z]+)\\s*)(\\d{2}:\\d{2})?([\\]>])/g;\n this.macroPattern = /{{{([A-Za-z]\\w*)\\(([^})]*?)\\)}}}/g;\n }",
"function infixToBtree(expression)\n{\n var tokens = expression.split(/([\\d\\.]+|[\\*\\+\\-\\/\\(\\)])/).filter(notEmpty);\n var operatorStack = [];\n var lastToken = '';\n var queue = [];\n\n while (tokens.length > 0)\n {\n var currentToken = tokens.shift();\n\n if (isNumber(currentToken)) \n {\n\t queue.push(new bigdecimal.BigDecimal(currentToken));\n }\n\telse if (isUnaryOp(currentToken, lastToken))\n\t{\n\t lastToken = currentToken;\n\t //expect next token to be a number\n\t currentToken = tokens.shift();\n\t //minus is the only unary op supported for now\n\t queue.push(new bigdecimal.BigDecimal(currentToken).negate());\t\n\t}\n else if (isOperator(currentToken)) \n {\n while (getPrecedence(currentToken) <= getPrecedence(operatorStack.last) ) \n {\n\t\tvar newNode = new BinaryTree(queue.pop(), queue.pop(), operatorStack.pop()); \t\t\n\t\tqueue.push(newNode);\n }\n\n operatorStack.push(currentToken);\n\n }\n else if (currentToken == '(')\n {\n operatorStack.push(currentToken);\n }\n else if (currentToken == ')')\n {\n while (operatorStack.last != '(')\n {\n \t if (operatorStack.length == 0)\n \t return \"Error in braces count\";\n\n\t\tvar newNode = new BinaryTree(queue.pop(), queue.pop(), operatorStack.pop()); \t\t\n\t\tqueue.push(newNode);\n }\t\n operatorStack.pop();\t\t\n }\n\tlastToken = currentToken; \n } \n\n while (operatorStack.length != 0)\n {\n if (/^[\\(\\)]$/.test(operatorStack.last))\n\t\treturn \"Error in braces count\";\n \n\tvar newNode = new BinaryTree(queue.pop(), queue.pop(), operatorStack.pop()); \t\t\n\tqueue.push(newNode);\n \n }\n //return Btree root\n return queue[0];\n}",
"function parse_IntExpr(){\n\tdocument.getElementById(\"tree\").value += \"PARSER: parse_IntExpr()\" + '\\n';\n\tCSTREE.addNode('IntExpr', 'branch');\n\n\t\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\tif (tempType == 'digit'){\n\t\tmatchSpecChars(tempDesc,parseCounter);\n\t\t\n\t\tparseCounter = parseCounter + 1;\n\t\t\n\t\t\tif (tokenstreamCOPY[parseCounter][0] == '+'){\n\t\t\tdocument.getElementById(\"tree\").value += '\\n';\n\t\t\tparse_intop();\n\t\n\t\t\tparse_Expr();\n\t\n\t\t}\n\t\t\t\t\n\t}\n\t\n\t\n\t\n}",
"function parseExpression() {\n let expr;\n //lookahead = lex();\n // if (!lookahead) { //significa que es white o undefined\n // lookahead = lex();\n // }\n if (lookahead.type == \"REGEXP\") {\n expr = new Regexp({type: \"regex\", regex: lookahead.value, flags: null});\n lookahead = lex();\n return expr;\n } else if (lookahead.type == \"STRING\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"NUMBER\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"WORD\") {\n const lookAheadValue = lookahead;\n lookahead = lex();\n if (lookahead.type == 'COMMA' && lookahead.value == ':') {\n expr = new Value({type: \"value\", value: '\"' + lookAheadValue.value + '\"'});\n return expr;\n }\n if (lookahead.type == 'DOT') {\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n }\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n } else if (lookahead.type == \"ERROR\") {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${lookahead.value}`);\n } else {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${program.slice(offset, offset + 10)}`);\n }\n}",
"function stack_pair(inmode, inexpr)\n{\n\tthis.mode = inmode;\n\tthis.expr = inexpr;\n}",
"enterElvisExpression(ctx) {\n\t}",
"visitImport_name(ctx) {\r\n console.log(\"visitImport_name\");\r\n return {\r\n type: \"ImportName\",\r\n imported: this.visit(ctx.dotted_as_names()),\r\n };\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION FOR POPULATING MY MOVIES FROM FIREBASE | function populateMyMoviesPage() {
getjson('https://user-enter-luke.firebaseio.com/users.json')
p.then(function(data) {
moviesAdded = [];
moviesViewed = [];
if (data !== null) {
for (var i = 0; i < data[userID].movies.length; i++) {
moviesAdded.push(data[userID].movies[i]);
}
for (var i = 0; i < data[userID].watchedMovies.length; i++) {
moviesViewed.push(data[userID].watchedMovies[i]);
}
}
$(document).click(function(e) {
if (e.target.className === "add btn btn-primary") {
addMovie(e);
}
});
$(document).click(function(e) {
if (e.target.className === "remove btn btn-danger") {
removeMovie(e);
}
});
});
} | [
"function getPlayers() {\n var ref = new Firebase(\"https://tictacstoe.firebaseio.com/players\");\n var players = $firebaseObject(ref);\n\n players.tictacs = [];\n players.tictacs.push({\n type: \"spearmint\",\n image: \"images/green-tic.png\",\n alt: \"green\"\n });\n players.tictacs.push({\n type: \"orange\",\n image: \"images/orange-tic.png\",\n alt: \"orange\"\n });\n players.tictacs.push({\n type: \"wild cherry\",\n image: \"images/red-tic.png\",\n alt: \"red\"\n });\n players.tictacs.push({\n type: \"freshmints\",\n image: \"images/white-tic.png\",\n alt: \"white\"\n });\n\n players.$save();\n\n return players;\n }",
"function createItem(url, name = \"\", note = \"\", price = 0, callback = () => {}) {\n chrome.storage.sync.get(['firebase-auth-uid'], function(result){\n var uid = result['firebase-auth-uid'];\n var wishlistRef = database.ref(\"users/\" + uid + \"/wishlist\");\n var itemsRef = database.ref(\"items/\");\n var newItemRef = itemsRef.push({\n gifter : false,\n name : name,\n note : note,\n price : price,\n requester : uid,\n url : url,\n });\n wishlistRef.child(newItemRef.key).set(true).then(function() {\n callback();\n });\n });\n}",
"function popFromDb() {\n setInterval(function () {\n dbFns.getAll().then((data) => {\n let jsonData = idbArrToJson(data);\n jsonData && _.each(jsonData,(val,key)=>{\n fireAndDelete(key, val)\n })\n })\n },READ_FROM_DB_INTERVAL)\n}",
"viewFavourites() {\n const userId = this.state.UserId;\n const list = this.state.favourites;\n if (userId != []) {\n const dbref = firebase.database().ref('SavedNews');\n this.favourite = [];\n if (list == '') {\n dbref.child(userId).once('value', (snapshot) => {\n const favourites = snapshot.val();\n for (const prop in favourites) {\n this.favourite.push(favourites[prop]);\n }\n this.setState({\n favourites: this.favourite\n });\n });\n }\n }\n }",
"function guardarOrden() {\n let cliente = $('#cliente').val();\n let descripcion = $('#descripcion').val();\n let fechaRecep = moment().format('DD/MM/YYYY');\n let fechaEntrega = $('#fechaEntrega').val();\n let estado = \"Pendiente\";\n let encargado = $('#encargado').val();\n\n let ordenes = firebase.database().ref('ordenes/');\n let Orden = {\n cliente: cliente,\n descripcion: descripcion,\n fechaRecep: fechaRecep,\n fechaEntrega: fechaEntrega,\n estado: estado,\n encargado: encargado\n }\n\n ordenes.push().set(Orden); //inserta en firebase asignando un id autogenerado por la plataforma\n $('#agregarOrden').modal('hide');\n}",
"function saveAndPublishUserData(resp) {\n user.name = resp.data.name;\n user.email = resp.data.email;\n user.id = resp.data._id;\n localStorage.setItem('user', JSON.stringify(user)); \n}",
"pushFilmInFavoriteFilms(state, film) {\n state.favoriteFilms.push({\n id: film.id,\n title: film.title,\n poster: film.poster_path,\n });\n }",
"static get DATABASE_GET_ALL_FAVORITES() {\r\n return `http://localhost:${DBHelper.PORT}/restaurants/?is_favorite=true`;\r\n }",
"function collectDetail(){\n\t\n employeeList.push({\n \t\"firstname\":firstName.value,\n \t\"phone\":phoneNo.value,\n \t\"email\":emailId.value,\n \t\"location\":employeeLocation.value\n });\n \n setLocalStorage(\"employeeList\", JSON.stringify(employeeList)); \n }",
"pushRefreshedDatas() {\n var tt = this;\n MongoClient.connect(this.uri, function(err, db) {\n if (err) throw err;\n //Looking for a db called test\n var dbo = db.db(\"test\");\n for (var i = 0; i < tt.collections.length; ++i) {\n dbo.collection(\"rss\").insertOne(tt.collections[i],function(err, result) {\n if (err) throw err;\n });\n }\n db.close();\n });\n }",
"createFeed (context) {\n let ref = db.ref('connections').orderByKey().limitToLast(50)\n\n // watch for changes\n ref.on('value', snapshot => {\n const obj = snapshotToArray(snapshot)\n\n context.commit('setFeed', obj)\n })\n }",
"function commitGroc() {\n var groceryId = grocSel;\n grocSel = null;\n var groc = Parse.Object.extend(\"groceryList\");\n var query = new Parse.Query(groc);\n query.equalTo(\"objectId\", groceryId);\n\n query.first({\n success: function(grocObj) {\n\n grocObj.set('user', Parse.User.current());\n grocObj.save(null, {\n success: function(saveSuccess) {\n alert(\"Success: Host has been notified\");\n $(\"#\" + groceryId).hide();\n\n },\n error: function(dinnerEvent, error) {\n alert(error.message);\n }\n });\n\n },\n error: function(error) {\n alert(\"Error: \" + error.code + \" \" + error.message);\n }\n });\n\n}",
"function getPieces() {\n var ref = new Firebase(\"https://tictacstoe.firebaseio.com/pieces\");\n var pieces = $firebaseObject(ref);\n\n pieces.spaces = [];\n\n for (var i = 1; i < 4; i++) {\n for (var j = 1; j < 4; j++) {\n pieces.spaces.push({\n row: i,\n column: j,\n player: 0,\n ticTacClass: \"\"\n });\n }\n }\n pieces.$save();\n return pieces;\n }",
"async function collectData(){\n let favs = [];\n\n await firebase.database().ref('recommenderData').child('favourite')\n .once('value', x => {\n x.forEach(data => {\n favs.push(data.val());\n checkSkill(data.val().preferenceType, data.val().favouritedAmount);\n })\n })\n}",
"function addArtist() {\n // remove what is in the database\n database.ref().remove();\n\n // grab the artist in the input box\n var artistName = $(\"#band-input\").val().trim();\n\n database.ref().push({\n artistName: artistName\n });\n}",
"function getFavoriteMovies() {\n\t\tlet movieId = $('.movie-id').val();\n\n\t\t$.ajax({\n\t\t\turl: \"/favorites/all\",\n\t\t\tmethod: \"GET\",\n\t\t\tcontentType: \"application/json\",\n\t\t\tdataType: 'json',\n\n\t\t\tcomplete : function(data){ \t\n\t\t\t\tjQuery.each(data.responseJSON, function(index, item) {\n\t\t\t\t\t//favoriteMovies(item.movieId, item.user.id);\n\n\t\t\t\t\tif (item.movieId == movieId && item.user.id == myId) {\n\t\t\t\t\t\t$('.add-to-favorite').addClass(\"is-favorite\")\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},fail : function(){\n\t\t\t\tconsole.log(\"Failed getting favorite movies\");\n\t\t\t}\n\t\t});\n\t}",
"function GetActivities() {\n db.collection('activities').get()\n .then(function (snap) {\n snap.forEach(function (doc) {\n activities.push(doc.data());\n });\n }).then(function () {\n ShowActivities();\n });\n }",
"function addFruit(myobj){\n\t//Link to the fruit section in your database\n\tvar Fruit = Parse.Object.extend(\"Fruit\");\n\n\t//Create a cubby hole in your fruit section\n\tvar apple = new Fruit();\n\n\t//Update your cubby hole online with object you want to save \n\tapple.save(myobj, {success: function(object){\n\t //If didn't save\n\t alert('saved');\n\t },\n\t error: function(model, error){\n\t \t//If did save\n\t alert(\"didn't save\");\n\t }});\n}",
"function databaseQuery() {\n\n userInitial = firebase.database().ref(\"users/\");\n userInvites = firebase.database().ref(\"users/\" + user.uid + \"/invites\");\n\n var fetchData = function (postRef) {\n postRef.on('child_added', function (data) {\n onlineInt = 1;\n\n var i = findUIDItemInArr(data.key, userArr);\n if(userArr[i] != data.val() && i != -1){\n checkGiftLists(data.val());\n\n //console.log(\"Adding \" + userArr[i].userName + \" to most updated version: \" + data.val().userName);\n userArr[i] = data.val();\n }\n\n if(data.key == user.uid){\n user = data.val();\n console.log(\"User Updated: 1\");\n }\n });\n\n postRef.on('child_changed', function (data) {\n var i = findUIDItemInArr(data.key, userArr);\n if(userArr[i] != data.val() && i != -1){\n checkGiftLists(data.val());\n\n console.log(\"Updating \" + userArr[i].userName + \" to most updated version: \" + data.val().userName);\n userArr[i] = data.val();\n }\n\n if(data.key == user.uid){\n user = data.val();\n console.log(\"User Updated: 2\");\n }\n });\n\n postRef.on('child_removed', function (data) {\n var i = findUIDItemInArr(data.key, userArr);\n if(userArr[i] != data.val() && i != -1){\n console.log(\"Removing \" + userArr[i].userName + \" / \" + data.val().userName);\n userArr.splice(i, 1);\n }\n });\n };\n\n var fetchInvites = function (postRef) {\n postRef.on('child_added', function (data) {\n inviteArr.push(data.val());\n\n inviteNote.style.background = \"#ff3923\";\n });\n\n postRef.on('child_changed', function (data) {\n console.log(inviteArr);\n inviteArr[data.key] = data.val();\n console.log(inviteArr);\n });\n\n postRef.on('child_removed', function (data) {\n console.log(inviteArr);\n inviteArr.splice(data.key, 1);\n console.log(inviteArr);\n\n if (inviteArr.length == 0) {\n console.log(\"Invite List Removed\");\n inviteNote.style.background = \"#008222\";\n }\n });\n };\n\n fetchData(userInitial);\n fetchInvites(userInvites);\n\n listeningFirebaseRefs.push(userInitial);\n listeningFirebaseRefs.push(userInvites);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
subscribeclose or outside of form is clicked exit form | function exitSubscribeForm() {
$('.subscribe-overlay').hide();
$('.subscribe-form').css('top', '28%');
$('.subscribe-form').hide();
} | [
"function addCloseButtonFunctionality(){\n\t\t\t\n\t\t\t\n\t\t}",
"close() {\n this.showModal = false;\n\n this.onClose();\n }",
"function cpsh_onClose(evt) {\n if (processed) {\n WapPushManager.close();\n return;\n }\n quitAppConfirmDialog.hidden = false;\n }",
"close() {\n\n // Pop the activity from the stack\n utils.popStackActivity();\n\n // Hide the disclaimer\n this.disclaimer.scrollTop(0).hide();\n\n // Hide the screen\n this.screen.scrollTop(0).hide();\n\n // Reset the fields\n $(\"#field--register-email\").val(\"\");\n $(\"#field--register-password\").val(\"\");\n $(\"#field--register-confirm-password\").val(\"\");\n\n // Reset the selectors\n utils.resetSelector(\"register-age\");\n utils.resetSelector(\"register-gender\");\n utils.resetSelector(\"register-occupation\");\n\n // Set the flag to false\n this._isDisclaimerOpen = false;\n\n }",
"handleClose (evt) {\n if (this.focused() && !this.forceQuit) {\n this.contentWindows.forEach((w) => w.close())\n if (process.platform === 'darwin' || this.appSettings.hasTrayIcon) {\n this.mailboxesWindow.hide()\n evt.preventDefault()\n this.forceQuit = false\n }\n }\n }",
"@action closeDialog() {\r\n\t\tif (this.dialog) this.dialog.opened = false;\r\n\t}",
"function w3int_menu_close(evt)\n{\n //event_dump(evt, 'MENU-CLOSE');\n if ((evt.type == 'keyup' && evt.key == 'Escape') ||\n (evt.type == 'click' && evt.button != 2 )) {\n //console.log('w3int_menu_close '+ evt.type +' button='+ evt.button);\n w3int_menu_onclick(null, w3int_menu_close_cur_id);\n }\n}",
"function closeTaxDetail() {\r\n if (!$isOnView)\r\n $validateTax.resetForm(); \r\n $('#divTaxBreakdown').dialog('close');\r\n}",
"function closePopupForm(action) {\n window.returnValue = action;\n window.close();\n}",
"function cpsh_onQuit(evt) {\n evt.preventDefault();\n quitAppConfirmDialog.hidden = true;\n WapPushManager.close();\n }",
"function cpsh_onFinish(evt) {\n evt.preventDefault();\n finishConfirmDialog.hidden = true;\n WapPushManager.close();\n }",
"function closeContactForm(form) {\n\tif ($(form).attr(\"aria-hidden\") == \"false\") {\n\t\t$(form).attr(\"aria-hidden\", \"true\");\n\t}\n}",
"function handleWidgetClose(){\n confirmIfDirty(function(){\n if(WidgetBuilderApp.isValidationError)\n {\n WidgetBuilderApp.dirtyController.setDirty(true,\"Widget\",WidgetBuilderApp.saveOnDirty);\n return;\n }\n $(\".perc-widget-editing-container\").hide();\n $(\"#perc-widget-menu-buttons\").hide();\n $(\"#perc-widget-def-tabs\").tabs({disabled: [0,1,2, 3]});\n });\n }",
"function closeForm(){\n\t//close the current form\n\tvar currentForm = openedFormList.pop();\n\t$(currentForm).css(\"display\", \"\");\n\tclrFields($(currentForm));\n\t\n\t//close the pop up window if there is no form in the opened form list\n\tif(!openedFormList.length){\n\t\tclosePopup();\n\t\treturn;\n\t}\n\t\n\t//show the last form\n\tvar lastForm = openedFormList[openedFormList.length-1];\n\t$(lastForm).css(\"display\", \"block\");\n}",
"function closecancelpanel(){\n $.modal.close();\n }",
"function hideIfClickOutside(event) {\n if (event.target != $obj[0] && !insideSelector(event)) {\n closeQS();\n };\n }",
"function closeNewUserForm() {\n $(\"#form-popup\").hide(800, $.easing.easeInOutQuart)\n clearNewUserForm()\n}",
"function onClosed() {\n\t// dereference the window\n\t// for multiple windows store them in an array\n\tmainWindow = null;\n}",
"function close() {\n\tcongratModalEl.style.display = 'none';\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Internal) Gets a space separated list of the class names on the element. The list is wrapped with a single space on each end to facilitate finding matches within the list. | function classList(element) {
return (' ' + (element.className || '') + ' ').replace(/\s+/gi, ' ');
} | [
"function getClassNames(node) {\n\tif (node) {\n\t\tvar classAttrName = 'class';\n\t\tvar classNames = node.getAttribute(classAttrName) || \"\";\n\t\treturn classNames.split(/\\s+/).filter(function(n) {\n\t\t\treturn n != '';\n\t\t});\n\n\t}\n}",
"function getClassNames() {\n\tvar names = [];\n\tfor (var name in classes) {\n\t\tnames.push(name);\n\t}\n\treturn names;\n}",
"function ClassListValue(myElement) {\n this.set = function (arg) { myElement.className = arg.trim(); };\n this.get = function () { return myElement.className };\n this.configurable = false;\n }",
"classNames(...classes) {\r\n let classesToAdd = [];\r\n\r\n classes.forEach(classObj => {\r\n // simple class name; apply it outright\r\n if (typeof classObj === 'string') {\r\n classesToAdd.push(classObj);\r\n\r\n } else if (typeof classObj === 'object') {\r\n Object.keys(classObj).forEach(className => {\r\n if (classObj[className] === true) {\r\n classesToAdd.push(className);\r\n }\r\n });\r\n }\r\n });\r\n\r\n this.classList.add(...classesToAdd);\r\n }",
"function addClassesToElmnt (elmnt, classesToAdd) {\n elmnt.className = ''; // removes all classes from element\n let classesToAddVar = \"\" ; // blank string\n // Now loops through the strings in array classesToAdd\n // and concatenate them with blank string in var\n // classesToAddVar: \n for (let i = 0; i < classesToAdd.length; i++) {\n classesToAddVar += classesToAdd[i] ;\n } // end for\n // Now add all the classes to the element in question: \n elmnt.classList.add (classesToAddVar);\n }",
"function allSCComponents(wantClass) {\n var ids = [];\n var d;\n basicColorMenu.forEach(function (item) {\n d = item.elements.map(function (ele) {\n if (wantClass) return `.${ele}`;\n else return ele;\n });\n ids = ids.concat(d);\n });\n idsSet = new Set(ids);\n ids = Array.from(idsSet);\n return ids;\n}",
"function getElements() {\n // logic\n var domEls = [];\n for (var i = 0; i < classNamesArray.length; i++) {\n domEls.push(document.getElementsByClassName(classNamesArray[i]));\n }\n return domEls;\n}",
"get themeClasses() {\n return baseThemeID + \" \" +\n (this.state.facet(darkTheme) ? \"cm-dark\" : \"cm-light\") + \" \" +\n this.state.facet(theme);\n }",
"iconClasses() {\n return this.icon != null ? [iconClass(this.icon)] : [];\n }",
"iconClasses() {\n return iconClasses(this.icon, this.iconSize)\n }",
"function getElementsByClassName(node, classname) {\n\t\t var a = [];\n\t\t var re = new RegExp('(^| )'+classname+'( |$)');\n\t\t var els = node.getElementsByTagName(\"*\");\n\t\t for(var i=0,j=els.length; i<j; i++)\n\t\t if(re.test(els[i].className))a.push(els[i]);\n\t\t return a;\n\t\t}",
"function getClasses(styleSheet) {\n\t var mapping = (0, _utils.find)(sheetMap, { styleSheet: styleSheet });\n\t return mapping ? mapping.classes : null;\n\t }",
"function ajax_getClassName( element ) {\r\n if (ie4 && browser != \"Opera\" && ! ie8)\r\n return (element.getAttribute(\"className\"));\r\n else return (element.getAttribute(\"class\"));\r\n}",
"appliedCssClasss() {\n return this.codePrismLanguage() + this.lineNumberCssClass();\n }",
"function getClass(element, k) {\n return element.attr(\"class\").split(\" \")[k-1];\n}",
"_collectClasses() {\n const result = []\n let current = Object.getPrototypeOf(this)\n while (current.constructor.name !== 'Object') {\n result.push(current)\n current = Object.getPrototypeOf(current)\n }\n return result\n }",
"function CLASS_SELECTOR(className)\n{\n return \".\" + className;\n}",
"function classStripper(idList, className, aaIto){\n let l = idList\n for (let i = 0; i < l.length; i++) {\n e(l[i]).classList.remove(className)\n }\n if (aaIto) { e(aaIto).classList.add(className) }\n}",
"__getClassStartingWith(node, prefix) {\n return _.filter(\n $(node)\n .attr('class')\n .split(' '),\n className => _.startsWith(className, prefix)\n )[0];\n }",
"function replaceClass(element, search, replace) {\n\t\t\tif(element.className) {\n\n\t\t\t\tif(replace && new RegExp(\"(^|\\\\s)\" + replace + \"(\\\\s|$)\").test(element.className)) {\n\t\t\t\t\treplace = ''\n\t\t\t\t}\n\n\t\t\t\tvar subject = element.className,\n\t\t\t\t searchRE = new RegExp(\"(^|\\\\s+)\" + search + \"(\\\\s+|$)\", \"g\"),\n\t\t\t\t m = searchRE.exec(subject);\n\n\t\t\t\tif(m) {\n\t\t\t\t\t// swallow unneeded/extra spaces\n\t\t\t\t\tif(replace)\n\t\t\t\t\t\treplace = (m[1] ? \" \" : \"\") + replace + (m[2] ? \" \" : \"\")\n\t\t\t\t\telse\n\t\t\t\t\t\treplace = m[1] && m[2] ? \" \" : \"\"\n\n\t\t\t\t\telement.className = subject.replace(searchRE, replace)\n\t\t\t\t}\n\t\t\t}\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove Phase from challenge Phases list | removePhase (index) {
const { challenge: oldChallenge } = this.state
const newChallenge = { ...oldChallenge }
const newPhaseList = _.cloneDeep(oldChallenge.phases)
newPhaseList.splice(index, 1)
newChallenge.phases = _.clone(newPhaseList)
this.setState({ challenge: newChallenge })
} | [
"removeTexture(texture) {\n // remove from our textures array\n this.textures = this.textures.filter(element => element.uuid !== texture.uuid);\n }",
"function removeQuestion() {\n removeQuestionID = questions.indexOf(selectedQuestion);\n questions.splice(removeQuestionID, 1);\n answerList.splice(removeQuestionID, 1);\n}",
"_removeAllStages() {\n let stages = S.getProject().getAllStages();\n\n return BbPromise.each(stages, (stage) => {\n let evt = {\n options: {\n stage: stage.name,\n noExeCf: !!this.evt.options.noExeCf\n }\n };\n return S.actions.stageRemove(evt);\n });\n }",
"function removePlaylist( mixtape, change )\r\n{\r\n if ( change.playlistId > mixtape.playlists.length )\r\n {\r\n console.log( \"Playlist with id '\"+change.playlistId+\"' does not exists\");\r\n return;\r\n }\r\n var numId = parseInt(change.playlistId, 10); \r\n var newlist = mixtape.playlists.filter( el => el.id !== change.playlistId);\r\n mixtape.playlists = newlist;\r\n \r\n \r\n}",
"removeConstraint(constraint) {\n var index = constraintList.indexOf(constraint);\n if (index !== -1) {\n constraintList.splice(index, 1);\n }\n }",
"function removeChecklistItem() {\n\t\tremoveFromChecklistArry(this);\n\t\toptions.removeChild(this.parentNode);\t\t\t\n\t}",
"function cancelChallenge() {\n challengesService.getActiveChallengeByCompetitionByPlayer(vm.competitionId, vm.currentUserPlayer._id).then(function (challenge) {\n if (challenge.data) {\n // Allow the challenger to cancel the challenge\n if (challenge.data.challenger._id === vm.currentUserPlayer._id) {\n challengesService.cancelPyramidChallenge(challenge.data).then(function () {\n vm.hasActiveChallenge = false;\n });\n }\n }\n });\n }",
"function removePhenotype(phenotype) {\n if (!!phenotype) {\n let phenotypes = getPhenotypes();\n if (phenotypes === null) {\n phenotypes = [];\n }\n let index = phenotypes.findIndex(p => p.id === phenotype.id);\n if (index > -1) {\n phenotypes.splice(index, 1);\n savePhenotypes(phenotypes);\n }\n } else {\n console.error(\"Phenotype is null\");\n return;\n }\n}",
"removeCourse(languageId) {\r\n\r\n }",
"function removeGameHolderAudio() {\n\t $('#game-intro-audio').remove();\n\t}",
"function removeWantToVisitPark(visit){\nwantToVisitPark.splice(visit, 1);\n\n}",
"function clear_control_panel_options() {\n\tvar control_panel_options_buttons = document.querySelectorAll(\".control_panel .options .button\");\n\tvar control_panel_options_buttons_length = control_panel_options_buttons.length;\n\tfor(var i=0; i<control_panel_options_buttons_length; i++) {\n\t\tcontrol_panel_options_buttons[i].parentNode.removeChild(control_panel_options_buttons[i]);\n\t}\n\tpart+=1;\n\tdeactivate_continue_button()\n\tselect_part();\n}",
"remove(actionToRemove) {\n\t\tthis.actions = this.actions.filter( action => action.name !== actionToRemove.name);\n\t}",
"async remove(inputs = {}) {\n const { stage } = inputs;\n if (stage === \"staging\" || stage === \"prod\") {\n const template = await this.load(\"@serverless/template\", stage);\n const output = await template.remove();\n return output;\n }\n }",
"basketRemove(equipment) {\n for (var i = 0; equipmentBasket.length > i; i++) {\n if (equipmentBasket[i].id == equipment.id) {\n equipmentBasket.splice(i, 1);\n }\n }\n\n this.specify();\n }",
"clearPolicy() {\n this.model.forEach((value, key) => {\n if (key === 'p' || key === 'g') {\n value.forEach(ast => {\n ast.policy = [];\n });\n }\n });\n }",
"static removeAsset(pool, vault) {\n return makeAdminInstruction(pool, { removeAsset: {} }, [\n { pubkey: vault, isSigner: false, isWritable: false },\n ]);\n }",
"function completeStripPhase () {\n /* strip the player with the lowest hand */\n stripPlayer(recentLoser);\n updateAllGameVisuals();\n}",
"function removeChair() {\n if (N > 1) {\n N -= 1;\n chairs.splice(index, 1);\n chairSprites[index].destroy();\n chairSprites.splice(index, 1);\n textSprites[index].destroy();\n textSprites.splice(index, 1);\n index += count;\n index = index % chairs.length;\n count += 1;\n drawChairs(N);\n }\n if (N == 1) {\n running = false;\n runButtonText.data = \"Run Simulation\";\n }\n fromSingleStep = false;\n}",
"function removeCandidatePosition() {\n \t candidatePositions.pop();\n \t numCandidates -= 1;\n } // removeCandidatePosition"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function transfers the collected airport data into a global variable and collects the data of all routes in a country Parameters: Returns: | function generateAirportList(airportData)
{
// Transfer Airport Data to Global Variable
airports = airportData;
// Make Web Service Request
let url = "https://eng1003.monash/OpenFlights/allroutes/";
let data = {
country: countryRef.value,
callback: "generateAllRoutes"
}
webServiceRequest(url,data);
} | [
"function analyticsLaneGeo(){\r\n\r\n // Customer Number\r\n ds_Analytics.cusPrefix = cusprefix;\r\n ds_Analytics.cusBase = cusbase;\r\n ds_Analytics.cusSuffix = cussuffix;\r\n\r\n // Lane Geography\r\n for (var i = 0; i < geo.length; i++) {\r\n switch (geo[i][\"geotype\"]) {\r\n case 'ORG':\r\n ds_Analytics.origCity = geo[i][\"idcity\"];\r\n ds_Analytics.origCounty = geo[i][\"idcounty\"];\r\n ds_Analytics.origZipCode= geo[i][\"zipcode\"];\t\t\t\t\r\n ds_Analytics.origPointSrc = geo[i][\"pointsrc\"];\t\r\n ds_Analytics.origState = geo[i][\"state\"];\t\r\n ds_Analytics.origZone = geo[i][\"zone\"];\t\r\n break;\r\n case 'DST':\r\n ds_Analytics.destCity = geo[i][\"idcity\"];\r\n ds_Analytics.destCounty = geo[i][\"idcounty\"];\r\n ds_Analytics.destZipCode= geo[i][\"zipcode\"];\t\t\t\t\r\n ds_Analytics.destPointSrc = geo[i][\"pointsrc\"];\t\r\n ds_Analytics.destState = geo[i][\"state\"];\t\r\n ds_Analytics.destZone = geo[i][\"zone\"];\t\r\n break;\r\n case 'PEN':\r\n ds_Analytics.entPortCity = geo[i][\"idcity\"];\r\n ds_Analytics.entPortCounty = geo[i][\"idcounty\"];\r\n ds_Analytics.entPortZipCode= geo[i][\"zipcode\"];\t\t\t\t\r\n ds_Analytics.entPortState = geo[i][\"state\"];\t\r\n ds_Analytics.entPortZone = geo[i][\"zone\"];\t\r\n break;\r\n case 'PEX':\r\n ds_Analytics.extPortCity = geo[i][\"idcity\"];\r\n ds_Analytics.extPortCounty = geo[i][\"idcounty\"];\r\n ds_Analytics.extPortZipCode= geo[i][\"zipcode\"];\t\t\t\t\r\n ds_Analytics.extPortState = geo[i][\"state\"];\t\r\n ds_Analytics.extPortZone = geo[i][\"zone\"];\t\r\n break;\t\t\t\t\t\r\n }\r\n }\r\n\r\n // Rate Record Info\r\n if (chrg.length != 0){\r\n ds_Analytics.rateRecordId = chrg[0][\"pricingid\"];\r\n ds_Analytics.transitMiles = chrg[0][\"rmsqty\"];\r\n // Values used for Sandbox - Use Priced\r\n if (chrg[0].proprate != \"0\"){\r\n if (chrg[0].propuom == \"MLS\"){ \r\n ds_Analytics.publishedRate = chrg[0].proprate; \r\n ds_Analytics.publishedFlatRate = \"0\";\r\n ds_Analytics.publishedMiles = chrg[0].propqty;\r\n } else {\r\n ds_Analytics.publishedRate = \"0\";\r\n ds_Analytics.publishedFlatRate = chrg[0].proprate;\r\n ds_Analytics.publishedMiles = chrg[0].rmsqty;\r\n }\r\n \r\n } else {\r\n // Priced Not Entered, Use Published\r\n if (chrg[0].rmsuom == \"MLS\"){\r\n ds_Analytics.publishedRate = chrg[0].rmsrate; \r\n ds_Analytics.publishedFlatRate = \"0\";\r\n } else {\r\n ds_Analytics.publishedRate = \"0\";\r\n ds_Analytics.publishedFlatRate = chrg[0].rmsamount;\r\n }\r\n ds_Analytics.publishedMiles = chrg[0].rmsqty;\r\n }\r\n \r\n } else {\r\n ds_Analytics.rateRecordId = \"0\";\r\n ds_Analytics.transitMiles = \"0\";\r\n ds_Analytics.publishedRate = \"0\";\r\n ds_Analytics.publishedFlatRate = \"0\";\r\n ds_Analytics.publishedMiles = \"0\";\r\n }\r\n}",
"static async getAirportData(params) {\n // Destructuring params\n const { keyword = \"\", page = 0, city = true, airport = true } = params;\n \n // Checking for proper subType\n const subTypeCheck = city && airport ? \"CITY,AIRPORT\" : city ? \"CITY\" : airport ? \"AIRPORT\" : \"\"\n \n // Amadeus API require at least 1 character, so with this we can be sure that we can make this request\n const searchQuery = keyword ? keyword : \"a\";\n \n // prop containing data used to avoid api overload\n const source = CancelToken.source();\n \n // GET request with all params we need\n const out = await axios.get(\n `${BASE_URL}/flights/api/airports/?keyword=${searchQuery}&page=${page}&subType=${subTypeCheck}`,\n {\n cancelToken: source.token\n }\n )\n \n return { out, source };\n }",
"function getRouteData() {\n /* RESET */\n // RESET: Removing all the layers we added to the map (visualisations and route)\n for (i in layers) {\n map.removeLayer(layers[i]);\n };\n\n // Create a new dictionary to have visualisation layers loaded into\n layers = new Object();\n\n reset_checkboxes();\n\n route_data = [];\n coords = [];\n var points = gpxData.getElementsByTagName(\"trkpt\");\n\n var is_ele = true;\n var is_time = true;\n var is_hr = true;\n var is_cad = true;\n\n var to_alert = [];\n\n document.getElementById(\"error-msg\").innerHTML = \"\";\n /* END RESET */\n\n for (i = 0; i < points.length; i++) {\n // Add coords\n try {\n coords.push([points[i].getAttribute(\"lat\"), points[i].getAttribute(\"lon\")]);\n } catch {\n return;\n }\n\n\n // Create dictionary of additional data\n var new_dict = Object();\n\n // Add elevation and time\n // Check if elevation is present\n if (is_ele) {\n try {\n new_dict[\"ele\"] = points[i].getElementsByTagName(\"ele\")[0].childNodes[0].nodeValue;\n } catch (err) {\n is_ele = false\n document.getElementById(\"ele-switch\").disabled = true;\n document.getElementById(\"ele-label\").style.backgroundColor = \"#d9d9d9\";\n document.getElementById(\"ele-label\").style.textDecoration = \"line-through\";\n\n to_alert.push(\"No elevation data found.\\n\");\n }\n }\n \n // Check if time is present\n if (is_time) {\n try {\n new_dict[\"time\"] = points[i].getElementsByTagName(\"time\")[0].childNodes[0].nodeValue;\n } catch (err) {\n is_time = false;\n\n to_alert.push(\"No time data found.\\n\");\n }\n }\n\n // Add heart rate and cadence\n // Check if heartrate is present\n if (is_hr) {\n try {\n new_dict[\"hr\"] = points[i].getElementsByTagNameNS(\"*\", \"hr\")[0]\n .childNodes[0]\n .nodeValue;\n } catch (err) {\n is_hr = false;\n document.getElementById(\"hr-switch\").disabled = true;\n document.getElementById(\"hr-label\").style.backgroundColor = \"#d9d9d9\";\n document.getElementById(\"hr-label\").style.textDecoration = \"line-through\";\n to_alert.push(\"No heart rate data found.\\n\");\n }\n }\n\n // Check if cadence is present\n if (is_cad) {\n try {\n new_dict[\"cad\"] = points[i].getElementsByTagNameNS(\"*\", \"cad\")[0]\n .childNodes[0]\n .nodeValue;\n } catch (err) {\n is_cad = false;\n document.getElementById(\"cad-switch\").disabled = true;\n document.getElementById(\"cad-label\").style.backgroundColor = \"#d9d9d9\";\n document.getElementById(\"cad-label\").style.textDecoration = \"line-through\";\n to_alert.push(\"No cadence data found.\\n\");\n }\n }\n // Add the additional data to a list\n route_data.push(new_dict);\n\n }\n\n if (to_alert.length != 0) {\n alert(to_alert.join(\"\") + \"Functions using the above parameters has been disabled.\");\n }\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}",
"function populateResultsTable_by_country() {\n\n\t\t\tvar selectedStates = $(\"#statesListbox_by_country\").val() || [];\n\t\t\tvar HSarray = selected_HS6_Codes\n\n\t\t\timportResultsTable_by_country = searchDBByAbbr(importDestinationDB, selectedStates);\n\t\t\texportResultsTable_by_country = searchDBByAbbr(exportDestinationDB, selectedStates);\n\t\t\tconsole.log('selectedStates: ')\n\t\t\tconsole.log(selectedStates)\n\t\t\tconsole.log('importResultsTable_by_country: ')\n\t\t\tconsole.log(importResultsTable_by_country)\n\t\t\tconsole.log('exportResultsTable_by_country: ')\n\t\t\tconsole.log(exportResultsTable_by_country)\n\t\t\tdrawChart_by_country()\n\t\t\tdrawWorldMap_by_country()\n\t\t}",
"function getRoutes(){\n\n routeLayer.clearLayers();\n\n var travelOptions = r360.travelOptions();\n travelOptions.addSource(sourceMarker); \n travelOptions.setDate(date);\n travelOptions.setTime(time);\n travelOptions.setTravelType(autoComplete.getTravelType());\n travelOptions.setElevationEnabled(true);\n travelOptions.setWaitControl(waitControl);\n travelOptions.addTarget(targetMarker);\n\n r360.RouteService.getRoutes(travelOptions, function(routes) {\n\n var html = \n '<table class=\"table table-striped\" style=\"width: 100%\"> \\\n <thead>\\\n <tr>\\\n <th>Source</th>\\\n <th>Time</th>\\\n <th>Distance</th>\\\n <th>Target</th>\\\n </tr>\\\n </thead>';\n\n _.each(routes, function(route, index){\n\n currentRoute = route;\n r360.LeafletUtil.fadeIn(routeLayer, route, 500, \"travelDistance\", { color : elevationColors[index].strokeColor, haloColor : \"#ffffff\" });\n\n html +=\n '<tr style=\"margin-top:5px;\">\\\n <td class=\"routeModus routeModus'+index+'\"><img style=\"height: 25px;\" src=\"images/source'+index+'.png\"></td>\\\n <td>' + r360.Util.secondsToHoursAndMinutes(currentRoute.getTravelTime()) + '</td>\\\n <td>' + currentRoute.getDistance().toFixed(2) + ' km </td>\\\n <td class=\"routeModus routeModus'+index+'\"><img style=\"height: 25px;\" src=\"images/target.png\"></td>\\\n </tr>'\n });\n\n html += '</table>';\n\n targetMarker.bindPopup(html);\n targetMarker.openPopup();\n }, \n function(code, message){\n\n if ( 'travel-time-exceeded' == code ) \n alert(\"The travel time to the given target exceeds the server limit.\");\n if ( 'could-not-connect-point-to-network' == code ) \n alert(\"We could not connect the target point to the network.\");\n });\n }",
"function loadLocalData() {\r\n var xmlhttp=new XMLHttpRequest();\r\n xmlhttp.open(\"GET\",\"Buses.xml\",false);\r\n xmlhttp.send();\r\n xmlData=xmlhttp.responseXML;\r\n generateBusList(xmlData, \"SAMPLE\");\r\n loadRouteColors(); // Bus list must be loaded first\r\n displayRoutesFromTripId(tripRouteShapeRef); // Bus list must be loaded first to have the trip IDs\r\n showPOIs();\r\n getTrolleyData(scope);\r\n loadTrolleyRoutes();\r\n getTrolleyStops(scope);\r\n getCitiBikes();\r\n addDoralTrolleys();\r\n addDoralTrolleyRoutes();\r\n addMetroRail();\r\n addMetroRailRoutes();\r\n addMetroRailStations();\r\n addMiamiBeachTrolleys();\r\n addMiamiBeachTrolleyRoutes();\r\n // Refresh Miami Transit API data every 5 seconds\r\n setInterval(function() {\r\n callMiamiTransitAPI();\r\n }, refreshTime);\r\n if (!test) {\r\n alert(\"Real-time data is unavailable. Check the Miami Transit website. Using sample data.\");\r\n }\r\n}",
"getPortals() {\n let portals_buffer = [];\n let rooms_buffer = getReferenceById(g_gamearea.ID).AGRooms;\n this._AGroomID = rooms_buffer[0].ID;\n if (getReferenceById(this._AGroomID).AGobjects.length > 0) {\n getReferenceById(this._AGroomID).AGobjects.forEach(function (element) {\n if (element.type == 'PORTAL') {\n portals_buffer.push(element);\n //select_obj_buffer = select_obj_buffer + '<option value = \"'+ element.ID + '\">' + element.name + '</option>';\n }\n });\n }\n return portals_buffer;\n }",
"async getCities(country) {\n // get yesterday's date\n const offset = new Date().getTimezoneOffset() * 60000;\n const yesterday = new Date(Date.now() - 86400000 - offset)\n .toISOString()\n .slice(0, -5);\n\n // complete request\n const query = `?country=${country}¶meter=pm25&date_from=${yesterday}&limit=500&order_by=value&sort=desc`;\n const response = await fetch(this.openaqURI + query);\n const data = await response.json();\n\n // fill array without repeated cities\n let i = 0;\n const results = [];\n while (results.length < 20) {\n if (results.indexOf(data.results[i].city) === -1) {\n results.push(data.results[i].city);\n results.push(data.results[i].value);\n }\n i += 1;\n }\n // group array [[city, value], ...]\n const chunkedResults = [];\n for (let j = 0; j < results.length; j += 2) {\n chunkedResults.push(results.slice(j, j + 2));\n }\n\n return chunkedResults;\n }",
"function getData(country)\n{\n let callback = \"afterButtonPress\"; // Defining the callback function \n let url = `https://eng1003.monash/OpenFlights/airports/`; // Defining the URL to access the web service\n let params = `?country=${country}&callback=${callback}`; // Defining the parameters for the web service call \n let script = document.createElement('script'); // Creating a script element\n script.src = url + params; // Specifying the external URL \n document.body.appendChild(script); // Appending the script to the bottom of the body of the HTML file\n}",
"function getGoalsByCountry(){\n\t\tvar country = hashValue;\n\t\tcountry = country.charAt(0).toUpperCase() + country.substring(1);\n\t\tshotsPerCountry = _.where(data, {TEAM: country});\n\t\t$('h1#title').html('All of '+ country + '\\'s goals and shots at the 2014 World Cup mapped: click on the dots for more info')\n\t\t_.each(shotsPerCountry, populateGoals);\n\t}",
"function loopData(){\r\n\t\tvar route, item;\r\n\t\tfor(var i in whitelist) {\r\n\t\t\tfor(var j in whitelist[i]){\r\n\t\t\t\troute = i;\r\n\t\t\t\titem = whitelist[i][j];\r\n\t\t\t\tsaveData(route, item);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"function casesByCountry (){\n\n let today = dateToday();\n let endPoint = 'https://api.covid19tracking.narrativa.com/api/' \n let queryCountriesUrl = endPoint + today; \n let URL = {\n url: queryCountriesUrl,\n method: \"GET\" \n } \n\n // making request to pull all Covid data by countries\n $.ajax(URL).then(function(response){\n countriesData(response.dates[today].countries); \n });\n}",
"async function getCountryId(selectedCountry) {\n const response = await fetch('land.json')\n const countryData = await response.json()\n\n for (let i = 0; i < countryData.length; i++) {\n if (selectedCountry === countryData[i].countryname) {\n countryValue = countryData[i].id;\n }\n }\n\n callCityData(countryValue);\n\n}",
"function getForecastData() {\n\t\t\n \tvar forecastBaseURL = 'https://api.forecast.io/forecast/';\n\t\tvar forecastAPIkey = '96556a5d8a419fc71902643785e74d30';\n\t\tvar formattedLL = '/'+ placeLat + ',' + placeLon;\n\t\tvar forecastURL = forecastBaseURL + forecastAPIkey + formattedLL;\n\n\t\t$.ajax({\n\t\t\turl: forecastURL,\n\t\t\tdataType: 'jsonp',\n\t\t\tsuccess: function(data) {\n\t\t\t\tself.dailyForecasts(data.daily.data);\n\t\t\t\tself.currentlyForecasts(data.currently);\n\t\t\t\tself.currentlySkyicon(data.currently.icon);\n\t\t\t}\n\t\t});\n\t}",
"function calculateAirportStats(delayData) {\n\n var max = 0, min = 100;\n\n delayData.forEach(function (d) {\n\n var name = d[\"Airport Full Name\"];\n var iata = d[\"Airport\"];\n var year = +d[\"Year\"];\n var month = +d[\"Month\"];\n var count = +d[\"Arrival Flights Total Count\"];\n var eff = +d[\"Efficiency Factor\"];\n var carrierDelay = +d[\"Carrier Delay Percentage\"];\n var nasDelay = +d[\"NAS Delay Percentage\"];\n var WeatherDelay = +d[\"Weather Delay Percentage\"];\n var SecurityDelay = +d[\"Security Delay Percentage\"];\n var lateAircraftDelay = +d[\"Late Aircraft Delay Percentage\"];\n var delayedFlightsCount = +d[\"Arrival Delay Total Count\"];\n\n delaydataset.push(d);\n\n airportdataset.forEach(function (ads) {\n\n if(ads[\"Airport IATA\"] == iata) {\n\n var tdDelayData;\n if(ads.TimeData.length != 0) {\n\n tdDelayData = ads.TimeData.filter(function (f) {\n if(f.Year == year && f.Month == month) {\n return f;\n }\n });\n }\n if(tdDelayData == null) {\n tdDelayData = {Year: year, Month: month, EffectiveEfficiencyFactor : 0, FlightCount : 0, AvgDelayCarrier : 0, AvgDelayLateAircraft : 0, AvgDelayNas : 0, AvgDelaySecurity : 0, AvgDelayWeather : 0, DelayedFlightsCount : 0};\n ads.TimeData.push(tdDelayData);\n }\n\n tdDelayData.FlightCount = tdDelayData.FlightCount + count;\n tdDelayData.EffectiveEfficiencyFactor = tdDelayData.EffectiveEfficiencyFactor + (count * eff);\n tdDelayData.AvgDelayCarrier = tdDelayData.AvgDelayCarrier + (carrierDelay * delayedFlightsCount);\n tdDelayData.AvgDelayNas = tdDelayData.AvgDelayNas + (nasDelay * delayedFlightsCount);\n tdDelayData.AvgDelayWeather = tdDelayData.AvgDelayWeather + (WeatherDelay * delayedFlightsCount);\n tdDelayData.AvgDelaySecurity = tdDelayData.AvgDelaySecurity + (SecurityDelay * delayedFlightsCount);\n tdDelayData.AvgDelayLateAircraft = tdDelayData.AvgDelayLateAircraft + (lateAircraftDelay * delayedFlightsCount);\n tdDelayData.DelayedFlightsCount = tdDelayData.DelayedFlightsCount + delayedFlightsCount;\n\n }\n });\n });\n airportdataset.forEach(function (ads) {\n ads.TimeData.forEach(function (d) {\n if(d.FlightCount > 0)\n d.EffectiveEfficiencyFactor = d.EffectiveEfficiencyFactor / d.FlightCount;\n if(d.DelayedFlightsCount > 0) {\n d.AvgDelayCarrier = d.AvgDelayCarrier / d.DelayedFlightsCount;\n d.AvgDelayNas = d.AvgDelayNas / d.DelayedFlightsCount;\n d.AvgDelayWeather = d.AvgDelayWeather / d.DelayedFlightsCount;\n d.AvgDelaySecurity = d.AvgDelaySecurity / d.DelayedFlightsCount;\n d.AvgDelayLateAircraft = d.AvgDelayLateAircraft / d.DelayedFlightsCount;\n }\n });\n });\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 getCountryFromApi(country) {\n if (country === \"faroe islands\") {\n $(\"#js-error-message\").append(\n \"Sorry, there was a problem. Please select a country from the drop-down list!\"\n );\n throw new Error(\n \"Sorry, there was a problem. Please select a country from the drop-down list!\"\n );\n }\n\n const url = `https://agile-oasis-81673.herokuapp.com/api/country/${country}`;\n\n request(url)\n .then((rawCountryData) => {\n let translateRes, geoCodeRes, timeZone1Res, timeZone2Res;\n\n let countryData = findCountry(rawCountryData, country);\n\n $(\"html\").removeClass(\"first-background\");\n $(\"html\").addClass(\"second-background\");\n\n const googleTranslatePromise = googleTranslateApi(countryData).then(\n (res) => {\n translateRes = res;\n }\n );\n\n const geoCodingPromise = geoCodeCapitalApi(countryData)\n .then((res) => {\n geoCodeRes = res;\n return timeZoneApi1(geoCodeRes);\n })\n .then((res) => {\n timeZone1Res = res;\n return timeZoneApi2(timeZone1Res);\n })\n .then((res) => {\n timeZone2Res = res;\n });\n\n Promise.all([googleTranslatePromise, geoCodingPromise]).then(() => {\n $(\"body\").addClass(\"centered\");\n let countryCapital = countryData.capital;\n let countryName = countryData.name;\n displayTimeResults(\n timeZone2Res,\n countryCapital,\n countryName,\n translateRes\n );\n restartButton();\n $(\"header\").addClass(\"hidden\");\n $(\"footer\").addClass(\"hidden\");\n });\n })\n .catch((err) => {\n $(\"#js-error-message\").append(\n \"Sorry, there was a problem. Please select a country from the drop-down list! \" +\n err.message +\n \".\"\n );\n });\n}",
"function getCheapestFlightToAllDestinations(destinationCode, callback) {\n console.log('dest code' + destinationCode);\n var minPrice = 99999.9;\n var leg = null;\n var iter = 0;\n var depIndex = -1;\n var offerLegs = null;\n var legs = [];\n var bestData = null;\n for(var j=0;j<departureDateArray.length; j++) {\n var flightSearchUrl = 'http://terminal2.expedia.com/x/mflights/search?'+\n 'departureAirport=' + originAirport + '&' +\n 'arrivalAirport=' + destinationCode + '&' +\n 'departureDate='+departureDateArray[j]+'&'+\n 'returnDate='+returnDateArray[j]+ '&'+\n 'apikey=ZGFHz2FBGb4Sbd7f8zJGYDy1HYRFnMGS';\n\n request(flightSearchUrl, function (error, response, body) {\n var data = JSON.parse(body);\n if(typeof data !== 'undefined'){\n if(typeof data.offers !== 'undefined'){\n var currentPrice = parseFloat(data.offers[0].totalFare);\n if(currentPrice < minPrice) {\n minPrice = currentPrice;\n depIndex = iter;\n offerLegs = data.offers[0].legIds;\n bestData = data;\n }\n }\n }\n\n iter++;\n if(iter === departureDateArray.length) {\n for(var i=0; i<bestData.legs.length; i++) {\n if(bestData.legs[i].legId === offerLegs[0] || bestData.legs[i].legId === offerLegs[1]){\n legs.push(bestData.legs[i]);\n }\n }\n callback({'destination': destinationCode, 'minPrice': minPrice, 'depDate': departureDateArray[depIndex], 'arrDate': returnDateArray[depIndex], 'legs': legs});\n }\n })\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a user or update user info when request with userId | function addUpdateUser (req,res) {
const { userId } = req.body;
// console.log(req.body);
if (userId) {
User.findOneAndUpdate({ _id: userId },
req.body,
{ new: true },
)
.exec()
.then(user => {
// user.password = undefined;
return res.json({ status: 0, data: {} });
})
.catch(err => {
return res.status(500).json({})
})
} else {
const user = new User(req.body);
user.save((error, user) => {
if (error) {
return res.status(500).json({})
}
res.json({
status: 0,
data: {}
});
})
}
} | [
"function signup(userData){\n console.log(\"creating new user \"+userData.id);\n return User.create(userData)\n }",
"async function createUser() {\n const response = await fetch(`/api/users/`, {\n method: 'POST',\n body: JSON.stringify(userData),\n headers:{\n 'Content-Type': 'application/json'\n }\n });\n\n if (response.status !== 200) {\n // A server side error occured. Display the\n // error messages.\n handleServerError(response);\n } else {\n clearUserForm();\n // Re-fetch users after creating new\n fetchUsers()\n }\n }",
"function createUser(id, username) {\n let templateUser = JSON.parse(fs.readFileSync(schemaPath + \"user.json\", \"utf8\"));\n templateUser.id = id;\n if (username)\n templateUser.username = username;\n writeUser(id, templateUser);\n}",
"async approveNewUser(ctx, name, aadhar) {\n // Verify the CLient is an registar or not\n let cid = new ClientIdentity(ctx.stub);\n let mspID = cid.getMSPID();\n if (mspID !== \"registrarMSP\") {\n throw new Error('You are not authorized to invoke this fuction');\n }\n // Create a new composite key for the new User account\n const requestKey = Request.makeKey([name, aadhar]);\n\n // Fetch User Request with given name and aadhar from blockchain\n let existingRequest = await ctx.requestList\n .getRequest(requestKey)\n .catch(err => console.log('Provided User name and aadhar is not valid!'));\n\n let existingUser = await ctx.userList\n .getUser(requestKey)\n .catch(err => console.log('Already this user exists'));\n\n // Make sure User does not already exist.\n if (existingRequest === undefined) {\n throw new Error('Invalid User aadhar ID: ' + aadhar + '. No request with this Aadhar ID and name exists.');\n } else if (existingUser !== undefined) {\n throw new Error(' User already exists with aadhar ID: ' + aadhar);\n }\n\n else {\n // Create a User object to be stored in blockchain\n let UserObject = {\n name: name,\n email: existingRequest.email,\n phone: existingRequest.phone,\n aadhar: aadhar,\n upgradCoins: 0,\n createdAt: new Date(),\n updatedAt: new Date(),\n };\n\n // Create a new instance of User model and save it to blockchain\n let newUserObject = User.createInstance(UserObject);\n await ctx.userList.addUser(newUserObject);\n // Return value of new User created\n return newUserObject;\n }\n }",
"function updateInfo(req, res) {\n User.findOne({_id: req.params.id}, function(err, user) {\n if (err || !user) {\n return res.send({error: 'Could not update user.'});\n }\n \n user.extendedInfo = req.body;\n\n user.save(function(saveErr) {\n if (saveErr) {\n return res.send({error: 'Could not update user'});\n }\n return res.send({success: 'Successfully updated user!'});\n });\n });\n}",
"function createUser(userid){\n users[userid] = { \"userid\": userid.toString(), \"inventory\": [\"laptop\"], \"roomid\": \"strong-hall\"};\n saveState();\n}",
"updateUser (id, email, newEmail, username, password) {\n return apiClient.updateUser(\n storage.getToken(),\n id,\n email,\n newEmail,\n username,\n password\n )\n }",
"function updateUser(user_id) {\n user = {\n Id: user_id,\n First_name: prevName.innerHTML,\n Last_name: prevLast.innerHTML,\n Password: prevPassword.innerHTML,\n IsAdmin: previsAdminCB.checked\n }\n ajaxCall(\"PUT\", \"../api/Users\", JSON.stringify(user), updateUser_success, updateUser_error);\n}",
"editUser( id ) {\n fluxUserManagementActions.editUser( id );\n }",
"async function findOrAddUser(){\n try{\n let currentUser = await User.findOne({github_id: profile.id})\n\n //If user exists, create cookie for user.\n if(currentUser){\n console.log(\"current user was found\")\n done(null, currentUser)\n return currentUser\n\n //If user is new, add them to the database and create a cookie for them.\n }else{\n let newUser = await new User({\n access_token: accessToken,\n github_id: profile.id,\n }).save()\n done(null, newUser)\n console.log(\"new user:\" + newUser)\n return newUser\n }\n\n }catch(err){\n console.log(error)\n }\n }",
"dbSaveUser(user) {\n let userInfo = {\n email: user.email ? user.email : null,\n displayName: user.displayName ? user.displayName : null\n };\n // Overrides any key data given, which is cool for us\n firebase.database().ref('users/' + user.uid).update(userInfo);\n }",
"function createUser(req, res){\n var newUser = req.body;\n // use the userModel to create a User using the api \n // the api will \n var users = userModel.createUser(newUser);\n res.json(users);\n }",
"function setUserID(){\n if(isNew){\n spCookie = getSpCookie(trackerCookieName);\n getLead(isNew, spCookie, appID);\n }\n }",
"function validateUserId(req, res, next) {\n Users.getById(req.params.id)\n .then((user) => {\n req.user = user;\n next();\n })\n .catch((error) => {\n console.log(error);\n res.status(400).json({ message: \"invalid user id\" });\n });\n}",
"function updateUser(req, res) {\n User.findById({_id: req.params.id}, (err, user) => {\n if(err) {\n res.send(err);\n }\n Object.assign(user, req.body)\n .save((err, user) => {\n if(err) {\n res.send(err);\n }\n res.json({ \n message: 'Bucket updated!', \n user \n });\n }); \n });\n}",
"function setAuthedUser (id) {\n return {\n type: SET_AUTHED_USER,\n id\n }\n}",
"updateUser (id, name, email, disable = undefined, refreshPassword = undefined) {\n // TODO: change this to take a user id and an object containing the update payload\n assert.equal(typeof id, 'number', 'id must be number')\n assert.equal(typeof name, 'string', 'name must be string')\n assert.equal(typeof email, 'string', 'email must be string')\n if (disable) assert.equal(typeof disable, 'boolean', 'disable must be boolean')\n if (refreshPassword) assert.equal(typeof refreshPassword, 'boolean', 'refreshPassword must be boolean')\n return this._apiRequest(`/user/${id}`, 'PUT', {\n name,\n email,\n is_disabled: disable,\n new_password: refreshPassword\n })\n }",
"addUser (userid, firstname, lastname) {\n\t\tlet userRef = state.db.collection('users')\n\n\t\t// Add to remote database\n\t\tuserRef.doc(userid).set({\n\t\t\tfirstName : firstname,\n\t\t\tlastName : lastname,\n\t\t})\n\n\t\t// Add to local state\n\t\tstate.allUsers[userid] = {\n\t\t\tfirstName : firstname,\n\t\t\tlastName : lastname,\n\t\t}\n\n\t\tconsole.log(\"Users info: \", state.allUsers);\n\t\tconsole.log(\"Users count: \", Object.keys(state.allUsers).length);\n\t}",
"create(req, res) {\n const userId = req.param('userId');\n\n if(req.token.id !== userId) {\n return res.fail('You don\\'t have permission to do this.');\n }\n\n const allowedParams = [\n 'type', 'name', 'context', 'uuid'\n ];\n\n const applianceData = lodash.pick(req.body, allowedParams);\n ApplianceService.createForUser(userId, applianceData)\n .then(res.success)\n .catch(res.fail);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
NOTE(liayoo): Bytes for some data (e.g. parents & children references, version) are excluded from this calculation, since their sizes can vary and affect the gas costs and state proof hashes. 4(isLeaf) + 132(proofHash) + 8(treeHeight) + 8(treeSize) + 8(treeBytes) = 160 | computeNodeBytes() {
return sizeof(this.value) + 160;
} | [
"function verify(proof, j) {\n const path = proof.path.toString('hex');\n const value = proof.value;\n const parentNodes = proof.parentNodes;\n const header = proof.header;\n const blockHash = proof.blockHash;\n const txRoot = header[j]; // txRoot is the 4th item in the header Array\n try{\n var currentNode;\n var len = parentNodes.length;\n var rlpTxFromPrf = parentNodes[len - 1][parentNodes[len - 1].length - 1];\n var nodeKey = txRoot;\n var pathPtr = 0;\n for (var i = 0 ; i < len ; i++) {\n currentNode = parentNodes[i];\n const encodedNode = Buffer.from(sha3(rlp.encode(currentNode)),'hex');\n if(!nodeKey.equals(encodedNode)){\n return false;\n }\n if(pathPtr > path.length){\n return false\n }\n switch(currentNode.length){\n case 17://branch node\n if(pathPtr == path.length){\n if(currentNode[16] == rlp.encode(value)){\n return true;\n }else{\n return false\n }\n }\n nodeKey = currentNode[parseInt(path[pathPtr],16)] //must == sha3(rlp.encode(currentNode[path[pathptr]]))\n pathPtr += 1\n break;\n case 2:\n pathPtr += nibblesToTraverse(currentNode[0].toString('hex'), path, pathPtr)\n if(pathPtr == path.length){//leaf node\n if(currentNode[1].equals(rlp.encode(value))){\n return true\n }else{\n return false\n }\n }else{//extension node\n nodeKey = currentNode[1]\n }\n break;\n default:\n console.log(\"all nodes must be length 17 or 2\");\n return false\n }\n }\n }catch(e){ console.log(e); return false }\n return false\n}",
"getHashCode() {\n let hash = this.width || 0;\n hash = (hash * 397) ^ (this.height || 0);\n return hash;\n }",
"function merkleConstruct(data) {\n // for simplicity we use padded Merkle trees to avoid complications from unbalanced trees\n const paddedData = data.concat(arrayOf(roundUpPow2_(data.length)-data.length, () => 'empty leaf'))\n \n const tree = merkleConstruct_(paddedData)\n return { root:tree[0].slice(6), branch:(leaf) => merkleBranch_(tree, depth_(data.length), leaf) }\n}",
"numDescendants() {\n let num = 1;\n for (const branch of this.branches) {\n num += branch.numDescendants();\n }\n return num;\n }",
"function heightInorder(_x4,_x5){var _again3=true;_function4: while(_again3) {var n=_x4,x=_x5;_again3 = false;if(n <= 0){return 0;}var r=rootInorder(n);if(x > r){_x4 = n - r - 1;_x5 = x - r - 1;_again3 = true;r = undefined;continue _function4;}else if(x === r){return bits.log2(n);}_x4 = r;_x5 = x;_again3 = true;r = undefined;continue _function4;}}",
"static hashTransactions(transactionDatas){\n let data = [];\n transactionDatas.forEach(transaction => {\n data.push(JSON.stringify(transaction));\n });\n\n // use sha256 to create a merkle tree\n let tree = merkle(\"sha256\").sync(data);\n\n // return the merkle root\n return tree.root();\n }",
"calculateTreeWidth() {\n let leftSubtreeWidth = nodeSize + 2 * nodePadding;\n let rightSubtreeWidth = leftSubtreeWidth;\n if (this.left != null) {\n leftSubtreeWidth = this.left.calculateTreeWidth();\n }\n if (this.right != null) {\n rightSubtreeWidth = this.right.calculateTreeWidth();\n }\n this.width = leftSubtreeWidth + rightSubtreeWidth;\n return this.width;\n }",
"treeHash(str) {\n if (Objects.type(str) === 'commit') {\n return str.split(/\\s/)[1];\n }\n }",
"calculateDirectoryHash(dirpath,contentslist){\n var lowerLevel = Array();\n for (var content of contentslist) {\n lowerLevel.push(content.split(\":\")[1]);\n }\n\n merkleTools.addLeaves(lowerLevel);\n merkleTools.makeTree()\n const root = merkleTools.getMerkleRoot().toString('hex');\n\n merkleTools.resetTree();\n\n return dirpath + \":\" + root;\n }",
"visitHash_partition_quantity(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function iconSize(node)\n{\n return nodeSize * Math.pow(discount, node.depth);\n}",
"function nodeValue(tree) {\n let retval = 0;\n let children = tree.children;\n let metadata = tree.metadata;\n\n if (tree.children.length === 0) {\n retval = sumMetadata(tree);\n } else {\n for (let meta of metadata) {\n if (meta > children.length || meta === 0) continue;\n let step = children[meta-1];\n retval = retval + nodeValue(step);\n }\n }\n return retval;\n}",
"visitHash_partitions_by_quantity(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"get tree() {\n return this.buffer ? null : this._tree._tree\n }",
"visitHash_subparts_by_quantity(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"buildTree() {\n if (!this.drawnAnnotations.length && !this.annosToBeDrawnAsInsets.size) {\n // Remove all exlisting clusters\n this.areaClusterer.cleanUp(new KeySet());\n return;\n }\n\n // if (this.newAnno) this.tree.load(this.drawnAnnotations);\n\n this.createInsets();\n }",
"function sumMetadata(tree) {\n let retval = 0;\n for (let child of tree.children) {\n retval = retval + sumMetadata(child);\n }\n for (let meta of tree.metadata) {\n retval = retval + meta;\n }\n return retval;\n}",
"rebuildTreeIndex() {\n let columnIndex = 0;\n\n this.#rootsIndex.clear();\n\n arrayEach(this.#rootNodes, ([, { data: { colspan } }]) => {\n // Map tree range (colspan range/width) into visual column index of the root node.\n for (let i = columnIndex; i < columnIndex + colspan; i++) {\n this.#rootsIndex.set(i, columnIndex);\n }\n\n columnIndex += colspan;\n });\n }",
"visitIndividual_hash_subparts(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exit a parse tree produced by KotlinParsernullableType. | exitNullableType(ctx) {
} | [
"exitParenthesizedType(ctx) {\n\t}",
"exitAnnotationTypeMemberDeclaration(ctx) {\n\t}",
"exitUnannTypeVariable(ctx) {\n\t}",
"enterNullableType(ctx) {\n\t}",
"exitFloatingPointType(ctx) {\n\t}",
"exitSingleTypeImportDeclaration(ctx) {\n\t}",
"exitUnannPrimitiveType(ctx) {\n\t}",
"exitTypeConstraints(ctx) {\n\t}",
"exitUnannReferenceType(ctx) {\n\t}",
"exitTypeImportOnDemandDeclaration(ctx) {\n\t}",
"exitTypeProjection(ctx) {\n\t}",
"exitTypeParameterModifier(ctx) {\n\t}",
"exitInferredFormalParameterList(ctx) {\n\t}",
"visitNull_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"exitTypeTest(ctx) {\n\t}",
"exitNumericType(ctx) {\n\t}",
"exitTypeRHS(ctx) {\n\t}",
"exitTypeParameters(ctx) {\n\t}",
"exitTypeModifierList(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split this BSplineSurface into two at uk, by refining uknots | splitU(uk) {
let r = this.u_degree;
// Count number of times uk already occurs in the u-knot vector
// We have to add uk until it occurs r-times in the u-knot vector,
// where r is the u-degree of the curve
// In case there are knots in the u-knot vector that are equal to uk
// within the error tolerance, then we replace them with uk
// Such u-knot vector is named safe_uknots.
let safe_uknots = [];
for (let i = 0; i < this.u_knots.data.length; i++) {
if (common_1.isequal(this.u_knots.getN(i), uk)) {
safe_uknots.push(uk);
r--;
}
else {
safe_uknots.push(this.u_knots.getN(i));
}
}
let add_uknots = [];
for (let i = 0; i < r; i++) {
add_uknots.push(uk);
}
let copy = this.clone();
copy.setUKnots(common_1.arr(safe_uknots));
copy.refineKnotsU(add_uknots);
// Find the index of the first uk knot in the new knot vector
let ibreak = -1;
for (let i = 0; i < copy.u_knots.data.length; i++) {
if (common_1.isequal(copy.u_knots.getN(i), uk)) {
ibreak = i;
break;
}
}
console.assert(ibreak >= 0);
// The U-control points of the surface where the split will happen are
// at the index *ibreak-1* in the U-direction of control points array
// The left surface will have *ibreak* u-control point rows
// The right surface will have *N-ibreak+1* u-control point rows
// (where N is the number of control points rows in U direction
// in the original surface)
// The control point at *ibreak-1* will be repeated in left and right
// surfaces. It will be the last u-control point of the left surface
// and first u-control point of the right surface
let lcpoints = copy.cpoints.getA(':' + ibreak, ':');
let rcpoints = copy.cpoints.getA((ibreak - 1) + ':', ':');
let l_uknots = copy.u_knots.getA(':' + ibreak).toArray();
// Scale the internal u knots values, to fit into the left surface's
// 0-1 u parameter range
for (let i = copy.u_degree + 1; i < l_uknots.length; i++) {
l_uknots[i] = l_uknots[i] / uk;
}
// Append clamped knots to the left curve at 1
for (let i = 0; i <= copy.u_degree; i++) {
l_uknots.push(1);
}
let r_uknots = copy.u_knots.getA((ibreak + copy.u_degree) + ':').toArray();
// Scale the internal knot values, to fit into the right surface's
// 0-1 u parameter range
for (let i = 0; i < r_uknots.length - copy.u_degree; i++) {
r_uknots[i] = (r_uknots[i] - uk) / (1 - uk);
}
// Prepend clamped knots to the right curve at 0
for (let i = 0; i <= copy.u_degree; i++) {
r_uknots.unshift(0);
}
// TODO : Rational
let lsurf = new BSplineSurface(copy.u_degree, copy.v_degree, l_uknots, copy.v_knots, lcpoints);
let rsurf = new BSplineSurface(copy.u_degree, copy.v_degree, r_uknots, copy.v_knots, rcpoints);
return [lsurf, rsurf];
} | [
"splitV(vk) {\n let r = this.v_degree;\n // Count number of times vk already occurs in the v-knot vector\n // We have to add vk until it occurs r-times in the v-knot vector,\n // where r is the v-degree of the curve\n // In case there are knots in the v-knot vector that are equal to vk\n // within the error tolerance, then we replace them with vk\n // Such v-knot vector is named safe_vknots\n let safe_vknots = [];\n for (let i = 0; i < this.v_knots.data.length; i++) {\n if (common_1.isequal(this.v_knots.getN(i), vk)) {\n safe_vknots.push(vk);\n r--;\n }\n else {\n safe_vknots.push(this.v_knots.getN(i));\n }\n }\n let add_vknots = [];\n for (let i = 0; i < r; i++) {\n add_vknots.push(vk);\n }\n let copy = this.clone();\n copy.setVKnots(common_1.arr(safe_vknots));\n copy.refineKnotsV(add_vknots);\n // Find the index of the first vk knot in the new knot vector\n let ibreak = -1;\n for (let i = 0; i < copy.v_knots.data.length; i++) {\n if (common_1.isequal(copy.v_knots.getN(i), vk)) {\n ibreak = i;\n break;\n }\n }\n console.assert(ibreak >= 0);\n // The V-control points of the surface where the split will happen are\n // at the index *ibreak-1* in the V-direction of control points array\n // The left surface will have *ibreak* v-control point columns\n // The right surface will have *N-ibreak+1* v-control point columns \n // (where N is the number of control points rows in V direction\n // in the original surface)\n // The control point at *ibreak-1* will be repeated in left and right\n // surfaces. It will be the last v-control point of the left surface\n // and first v-control point of the right surface\n let lcpoints = copy.cpoints.getA(':', ':' + ibreak);\n let rcpoints = copy.cpoints.getA(':', (ibreak - 1) + ':');\n let l_vknots = copy.v_knots.getA(':' + ibreak).toArray();\n // Scale the internal v knot values to fit into the left surface's 0-1\n // v parameter range\n for (let i = copy.v_degree + 1; i < l_vknots.length; i++) {\n l_vknots[i] = l_vknots[i] / vk;\n }\n // Append clamped knots to the left curve at 1\n for (let i = 0; i <= copy.v_degree; i++) {\n l_vknots.push(1);\n }\n let r_vknots = copy.v_knots.getA((ibreak + copy.v_degree) + ':').toArray();\n // Scale the internal knot values to fit into the right surface's\n // 0-1 v parameter range\n for (let i = 0; i < r_vknots.length - copy.v_degree; i++) {\n r_vknots[i] = (r_vknots[i] - vk) / (1 - vk);\n }\n // Prepend clamped knots to the right curve at 0\n for (let i = 0; i <= copy.v_degree; i++) {\n r_vknots.unshift(0);\n }\n // TODO : Rational\n let lsurf = new BSplineSurface(copy.u_degree, copy.v_degree, copy.u_knots, l_vknots, lcpoints);\n let rsurf = new BSplineSurface(copy.u_degree, copy.v_degree, copy.u_knots, r_vknots, rcpoints);\n return [lsurf, rsurf];\n }",
"decompose() {\n let Q = this.decomposeU();\n // Using Q, create Bezier strip surfaces. These are individual BSurf objects\n // Their u curve will be bezier, but will still be expressed as BSpline\n // Their v curve will still be bspline\n let L = 2 * (this.u_degree + 1);\n let u_bez_knots = common_1.empty(L);\n for (let i = 0; i < this.u_degree + 1; i++) {\n u_bez_knots.set(i, 0);\n u_bez_knots.set(L - i - 1, 1);\n }\n let bezStrips = [];\n for (let numUBez = 0; numUBez < Q.length; numUBez++) {\n let cpoints = Q.getA(numUBez);\n bezStrips.push(new BSplineSurface(this.u_degree, this.v_degree, u_bez_knots, this.v_knots, cpoints));\n }\n let bezSurfs = [];\n // Decompose each bezier strip along v\n for (let bezStrip of bezStrips) {\n let Q = bezStrip.decomposeV();\n for (let numUBez = 0; numUBez < Q.length; numUBez++) {\n let cpoints = Q.getA(numUBez);\n bezSurfs.push(new BezierSurface(this.u_degree, this.v_degree, cpoints));\n }\n }\n return bezSurfs;\n }",
"insertKnotU(un, r) {\n let p = this.u_degree;\n // Knot will be inserted between [k, k+1)\n let k = helper_1.findSpan(p, this.u_knots.data, un);\n // If un already exists in the knot vector, s is its multiplicity\n let s = common_1.count(this.u_knots, un, 0);\n if (r + s > p) {\n throw new Error('Knot insertion exceeds knot multiplicity beyond degree');\n }\n let mU = this.u_knots.length - 1;\n let nU = mU - this.u_degree - 1;\n let mV = this.v_knots.length - 1;\n let nV = mV - this.v_degree - 1;\n let P = this.cpoints;\n let Q = common_1.empty([nU + 1 + r, nV + 1, this.dimension]);\n let UP = this.u_knots;\n let UQ = common_1.empty([UP.length + r]);\n let VP = this.v_knots;\n let VQ = common_1.empty([VP.length]);\n // Load u-vector\n for (let i = 0; i < k + 1; i++) {\n UQ.set(i, UP.get(i));\n }\n for (let i = 1; i < r + 1; i++) {\n UQ.set(k + i, un);\n }\n for (let i = k + 1; i < mU + 1; i++) {\n UQ.set(i + r, UP.get(i));\n }\n // Copy v-vector\n VQ.copyfrom(VP);\n let alpha = common_1.empty([p + 1, r + 1]);\n let R = common_1.empty([p + 1, this.dimension]);\n let L = 0;\n // Pre-calculate alphas\n for (let j = 1; j < r + 1; j++) {\n L = k - p + j;\n for (let i = 0; i < p - j - s + 1; i++) {\n alpha.set(i, j, (un - UP.get(L + i)) / (UP.get(i + k + 1) - UP.get(L + i)));\n }\n }\n for (let row = 0; row < nV + 1; row++) {\n // Save unaltered control points\n for (let i = 0; i < k - p + 1; i++) {\n Q.set(i, row, P.get(i, row));\n }\n for (let i = k - s; i < nU + 1; i++) {\n Q.set(i + r, row, P.get(i, row));\n }\n // Load auxiliary control points\n for (let i = 0; i < p - s + 1; i++) {\n R.set(i, P.get(k - p + i, row));\n }\n for (let j = 1; j < r + 1; j++) {\n L = k - p + j;\n for (let i = 0; i < p - j - s + 1; i++) {\n R.set(i, common_1.add(common_1.mul(alpha.get(i, j), R.get(i + 1)), common_1.mul(1.0 - alpha.get(i, j), R.get(i))));\n }\n Q.set(L, row, R.get(0));\n Q.set(k + r - j - s, row, R.get(p - j - s));\n }\n // Load the remaining control points\n for (let i = L + 1; i < k - s; i++) {\n Q.set(i, row, R.get(i - L));\n }\n }\n this.cpoints = Q;\n this.v_knots = VQ;\n }",
"insertKnotV(vn, r) {\n let q = this.v_degree;\n // Knot will be inserted between [k,k+1)\n let k = helper_1.findSpan(this.v_degree, this.v_knots.data, vn);\n // If v already exists in knot vector, s is its multiplicity\n let s = common_1.count(this.v_knots, vn, 0);\n if (r + s > q) {\n throw new Error('Knot insertion exceeds knot multiplicity beyond degree');\n }\n let mU = this.u_knots.length - 1;\n let nU = mU - this.u_degree - 1;\n let mV = this.v_knots.length - 1;\n let nV = mV - this.v_degree - 1;\n let P = this.cpoints;\n let Q = common_1.empty([nU + 1, nV + r + 1, this.dimension]);\n let UP = this.u_knots;\n let UQ = common_1.empty([UP.length]);\n let VP = this.v_knots;\n let VQ = common_1.empty([VP.length + r]);\n // Copy u knot vector\n UQ.copyfrom(UP);\n // Load v knot vector\n for (let i = 0; i < k + 1; i++) {\n VQ.set(i, VP.get(i));\n }\n for (let i = 1; i < r + 1; i++) {\n VQ.set(k + i, vn);\n }\n for (let i = k + 1; i < mV + 1; i++) {\n VQ.set(i + r, VP.get(i));\n }\n let alpha = common_1.empty([q + 1, r + 1]);\n let R = common_1.empty([q + 1, this.dimension]);\n let L = 0;\n // Pre-calculate alphas\n for (let j = 1; j < r + 1; j++) {\n L = k - q + j;\n for (let i = 0; i < q - j - s + 1; i++) {\n alpha.set(i, j, (vn - VP.get(L + i)) / (VP.get(i + k + 1) - VP.get(L + i)));\n }\n }\n for (let col = 0; col < nU + 1; col++) {\n // Save unaltered control points\n for (let i = 0; i < k - q + 1; i++) {\n Q.set(col, i, P.get(col, i));\n }\n for (let i = k - s; i < nV + 1; i++) {\n Q.set(col, i + r, P.get(col, i));\n }\n // Load auxiliary control points\n for (let i = 0; i < q - s + 1; i++) {\n R.set(i, P.get(col, k - q + i));\n }\n for (let j = 1; j < r + 1; j++) {\n L = k - q + j;\n for (let i = 0; i < q - j - s + 1; i++) {\n R.set(i, common_1.add(common_1.mul(alpha.get(i, j), R.get(i + 1)), common_1.mul((1.0 - alpha.get(i, j)), R.get(i))));\n }\n Q.set(col, L, R.get(0));\n Q.set(col, k + r - j - s, R.get(q - j - s));\n }\n // Load remaining control points\n for (let i = L + 1; i < k - s; i++) {\n Q.set(col, i, R.get(i - L));\n }\n }\n this.cpoints = Q;\n this.v_knots = VQ;\n }",
"splitPolygon(polygon, coplanarFront, coplanarBack, front, back) {\n\t\tconst COPLANAR = 0;\n\t\tconst FRONT = 1;\n\t\tconst BACK = 2;\n\t\tconst SPANNING = 3;\n\n\t\t// Classify each point as well as the entire polygon into one of the above\n\t\t// four classes.\n\t\tlet polygonType = 0;\n\t\tlet types = [];\n\t\tfor (let i = 0; i < polygon.vertices.length; i++) {\n\t\t\tlet t = this.normal.dot(polygon.vertices[i].pos) - this.w;\n\t\t\tlet type = t < -Plane.EPSILON ? BACK : t > Plane.EPSILON ? FRONT : COPLANAR;\n\t\t\tpolygonType |= type;\n\t\t\ttypes.push(type);\n\t\t}\n\n\t\t// Put the polygon in the correct list, splitting it when necessary.\n\t\tswitch (polygonType) {\n\t\t\tcase COPLANAR:\n\t\t\t\t(this.normal.dot(polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);\n\t\t\t\tbreak;\n\t\t\tcase FRONT:\n\t\t\t\tfront.push(polygon);\n\t\t\t\tbreak;\n\t\t\tcase BACK:\n\t\t\t\tback.push(polygon);\n\t\t\t\tbreak;\n\t\t\tcase SPANNING:\n\t\t\t\tlet f = [],\n\t\t\t\t\tb = [];\n\t\t\t\tfor (let i = 0; i < polygon.vertices.length; i++) {\n\t\t\t\t\tlet j = (i + 1) % polygon.vertices.length;\n\t\t\t\t\tlet ti = types[i],\n\t\t\t\t\t\ttj = types[j];\n\t\t\t\t\tlet vi = polygon.vertices[i],\n\t\t\t\t\t\tvj = polygon.vertices[j];\n\t\t\t\t\tif (ti != BACK) f.push(vi);\n\t\t\t\t\tif (ti != FRONT) b.push(ti != BACK ? vi.clone() : vi);\n\t\t\t\t\tif ((ti | tj) == SPANNING) {\n\t\t\t\t\t\tlet t = (this.w - this.normal.dot(vi.pos)) / this.normal.dot(tv0.copy(vj.pos).sub(vi.pos));\n\t\t\t\t\t\tlet v = vi.interpolate(vj, t);\n\t\t\t\t\t\tf.push(v);\n\t\t\t\t\t\tb.push(v.clone());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (f.length >= 3) front.push(new Polygon(f, polygon.shared));\n\t\t\t\tif (b.length >= 3) back.push(new Polygon(b, polygon.shared));\n\t\t\t\tbreak;\n\t\t}\n\t}",
"function parabolicInterpolation(tau) {\n var nsdfa = nsdf[tau - 1], nsdfb = nsdf[tau], nsdfc = nsdf[tau + 1], bValue = tau, bottom = nsdfc + nsdfa - 2 * nsdfb;\n if (bottom === 0) {\n turningPointX = bValue;\n turningPointY = nsdfb;\n }\n else {\n var delta = nsdfa - nsdfc;\n turningPointX = bValue + delta / (2 * bottom);\n turningPointY = nsdfb - (delta * delta) / (8 * bottom);\n }\n }",
"function initPointsBySection(xlower, xhigher, ylower, yhigher, widthPoints, heightPoints, split, splitindex) {\n let w = xhigher - xlower;\n let h = yhigher - ylower;\n let winterval = w / widthPoints;\n let hinterval = h / heightPoints;\n\n let pointArray = [];\n\n //split is the number of sections to divide the picture into.\n // splitindex [0..n] is the section number we are calculating\n // only create pointArray for the section we are looking at\n // need t figure out ycount, yhigher and where to stop\n var sectionSize = Math.floor(heightPoints / split);\n //log('split ',heightPoints,' into ',split,' of ',sectionSize,' with ',sectionSize*widthPoints);\n var ycount = splitindex * sectionSize;\n // need to take into account that sectionSize may be rounded down, so last section needs\n // to mop up the last remaining rows\n var yupper;\n if (split - 1 == splitindex) {\n // we are processing the last section\n yupper = heightPoints;\n } else {\n yupper = ycount + sectionSize;\n }\n\n var j = yhigher - ycount * hinterval;\n\n for (; ycount < yupper; j -= hinterval, ycount++) {\n for (var i = xlower, xcount = 0; xcount < widthPoints; i += winterval, xcount++) {\n pointArray.push(new Point(i, j));\n }\n }\n return pointArray;\n}",
"function smoothterrain(rounding) {\n // Smussa il profilo del terreno.\n var n;\n while (rounding) {\n for (ptr = 0; ptr < 39798; ptr++) {\n n = p_surfacemap[ptr];\n n += p_surfacemap[ptr + 1];\n n += p_surfacemap[ptr + 200];\n n += p_surfacemap[ptr + 201];\n p_surfacemap[ptr] = n >> 2;\n }\n rounding--;\n }\n}",
"function reverseKnots(knots, degree) {\n var reversed = [knots.length];\n var o = degree + 1;\n const c = knots[0] + knots[knots.length - 1];\n\n for(var i = 0; i < knots.length; i++) {\n if(i >= o && i <= knots.length - o - 1) {\n var s = knots[knots.length - 1 - i];\n reversed[i] = c - s;\n } else {\n reversed[i] = knots[i];\n }\n }\n\n return reversed;\n}",
"function PHSK_BFeld( draht, BPoint) {\n\tif ( GMTR_MagnitudeSquared( GMTR_CrossProduct( GMTR_VectorDifference(draht.a ,draht.b ),GMTR_VectorDifference(draht.a ,BPoint ) )) < 10E-10)\n\t\treturn new Vec3 (0.0, 0.0, 0.0);\n\n\n\tlet A = draht.a;\n\tlet B = draht.b;\n\tlet P = BPoint;\n\t\n\tlet xd = -(GMTR_DotProduct(A,A) - GMTR_DotProduct(A,B) + GMTR_DotProduct(P , GMTR_VectorDifference(A,B))) / (GMTR_Distance(A,B));\n\tlet x = xd / (GMTR_Distance(A,B));\n\tlet yd = xd + GMTR_Distance(A,B);\n\t\n\tlet F1 = (yd / GMTR_Distance(P,B)) - (xd / GMTR_Distance(P,A));\n\tlet F2 = 1 / (GMTR_Distance(P,GMTR_VectorAddition(A,GMTR_ScalarMultiplication( GMTR_VectorDifference(B,A), x))));\n\tlet F3 = GMTR_CrossProductNormal( GMTR_VectorDifference(A,B),GMTR_VectorDifference(A,P) );\n\n\treturn GMTR_ScalarMultiplication(F3,F1*F2);\n}",
"_blockBreakParticles(blok){\n\t\tvar bpos = new vec2(blok.col.position.x + blok.col.size.x / 2, blok.col.position.y + blok.col.size.y / 2);\n\t\tvar s = 6;\n\t\tfor(var i = 4; i > 0; i--){ //right\n\t\t\tvar p = new seekerParticle(bpos.x, bpos.y + Math.random() * tilesize - tilesize / 2, \"#333\", p1);\n\t\t\tp.vel = new vec2(Math.random() * s, 0);\n\t\t\tp.pos = p.pos.plus(p.vel.multiply(2));\n\t\t\tparticles.push(p);\n\t\t\tp.seekspeed = 2;\n\t\t}\n\t\tfor(var i = 4; i > 0; i--){ //left\n\t\t\tvar p = new seekerParticle(bpos.x, bpos.y + Math.random() * tilesize - tilesize / 2, \"#333\", p1);\n\t\t\tp.vel = new vec2(Math.random() * -s, 0);\n\t\t\tp.pos = p.pos.plus(p.vel.multiply(2));\n\t\t\tparticles.push(p);\n\t\t\tp.seekspeed = 2;\n\t\t}\n\t\tfor(var i = 4; i > 0; i--){ //down\n\t\t\tvar p = new seekerParticle(bpos.x + Math.random() * tilesize - tilesize / 2, bpos.y, \"#333\", p1);\n\t\t\tp.vel = new vec2(0, Math.random() * s);\n\t\t\tp.pos = p.pos.plus(p.vel.multiply(2));\n\t\t\tparticles.push(p);\n\t\t\tp.seekspeed = 2;\n\t\t}\n\t\tfor(var i = 4; i > 0; i--){ //up\n\t\t\tvar p = new seekerParticle(bpos.x + Math.random() * tilesize - tilesize / 2, bpos.y, \"#333\", p1);\n\t\t\tp.vel = new vec2(0, Math.random() * -s);\n\t\t\tp.pos = p.pos.plus(p.vel.multiply(2));\n\t\t\tparticles.push(p);\n\t\t\tp.seekspeed = 2;\n\t\t}\n\t}",
"function Plugin_LogicSeparatingBlock()\n\t{\n\t\tthis._tmpPos = new (PhysicsCore.b2Vec2)();\n\t}",
"SolveBend_PBD_Triangle() {\n const stiffness = this.m_tuning.bendStiffness;\n for (let i = 0; i < this.m_bendCount; ++i) {\n const c = this.m_bendConstraints[i];\n const b0 = this.m_ps[c.i1].Clone();\n const v = this.m_ps[c.i2].Clone();\n const b1 = this.m_ps[c.i3].Clone();\n const wb0 = c.invMass1;\n const wv = c.invMass2;\n const wb1 = c.invMass3;\n const W = wb0 + wb1 + 2.0 * wv;\n const invW = stiffness / W;\n const d = new b2_math_js_1.b2Vec2();\n d.x = v.x - (1.0 / 3.0) * (b0.x + v.x + b1.x);\n d.y = v.y - (1.0 / 3.0) * (b0.y + v.y + b1.y);\n const db0 = new b2_math_js_1.b2Vec2();\n db0.x = 2.0 * wb0 * invW * d.x;\n db0.y = 2.0 * wb0 * invW * d.y;\n const dv = new b2_math_js_1.b2Vec2();\n dv.x = -4.0 * wv * invW * d.x;\n dv.y = -4.0 * wv * invW * d.y;\n const db1 = new b2_math_js_1.b2Vec2();\n db1.x = 2.0 * wb1 * invW * d.x;\n db1.y = 2.0 * wb1 * invW * d.y;\n b0.SelfAdd(db0);\n v.SelfAdd(dv);\n b1.SelfAdd(db1);\n this.m_ps[c.i1].Copy(b0);\n this.m_ps[c.i2].Copy(v);\n this.m_ps[c.i3].Copy(b1);\n }\n }",
"static CreateHermiteSpline(p1, t1, p2, t2, nbPoints) {\n const hermite = new Array();\n const step = 1.0 / nbPoints;\n for (let i = 0; i <= nbPoints; i++) {\n hermite.push(Vector3_1$2.Vector3.Hermite(p1, t1, p2, t2, i * step));\n }\n return new Curve3(hermite);\n }",
"function bezierSurface(u,v, q){\n\n\tvar B = bern3;\n\tvar n=4;\n\n\tvar p = vec3(0,0,0);\n\n\tfor(var i=0; i<n; i++){\n\t\tp = add(p, scale(B(i,u), bezierCurve(v, q[i])));\n\t}\n\n\treturn p;\n}",
"function autoDynamicBboxOld(){\n\tif (INTERSECTED.name.dynamicSeq>-1 && readOnly != 1) {\n\t\tif (splineIsAutoBoxed[INTERSECTED.name.dynamicSeq]==1) {\n\t\t\talert('AutoBox is already generated for this spline');\n\t\t\treturn;\n\t\t} \n\t\t// double check if dynamicOn is turned off\n\t\tif (dynamicOn == true) {\n\t\t\tdynamicOn = false;\n\t\t}\n\t\tvar bbox = INTERSECTED.geometry.boundingBox;\n\t\tvar range_x = Math.round((bbox.max.x - bbox.min.x)/gridSize);\t\n\t\tvar range_y = Math.round((bbox.max.y - bbox.min.y)/gridSize);\t\n\t\tvar range_z = Math.round((bbox.max.z - bbox.min.z)/gridSize);\t\n\t\t//generate a binary grid map counting objects in all labeled frames \n\t\tvar grid = new Array(range_x * range_y * range_z).fill(0);\t\n\t\tvar indexOnSpline = getPointsOnSpline();\n\t\tvar startFrame = INTERSECTED.name.timestamp;\n\t\tvar endFrame = INTERSECTED.name.timestamp;\n\t\tvar labeledFrames = [];\n\t\tvar labeledPoses = [];\n\t\tvar labeledRotations = [];\n\t\tfor (var i=0; i<labels.length; i++) {\n\t\t\tif (labels[i].name.dynamic == 0) { continue; }\n\t\t\tif (labels[i].name.dynamicSeq == INTERSECTED.name.dynamicSeq){\n\t\t\t\tif (labels[i].name.timestamp==-1) {\n\t\t\t\t\talert('All spline control objects should be assigned with timestamp at first');\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlabeledFrames.push(labels[i].name.timestamp);\n\t\t\t\tlabeledPoses.push(labels[i].position);\n\t\t\t\tlabeledRotations.push(labels[i].rotation);\n\t\t\t\tvar indexFrame = getPointsAtTime(indexOnSpline, labels[i].name.timestamp);\n\t\t\t\tvar points = getPointsInCube(indexFrame, labels[i]);\n\t\t\t\tfor (var j = 0; j<points.gridIndex.length; j++){\n\t\t\t\t\tgrid[points.gridIndex[j]] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvar sortedFrames = labeledFrames.concat([]); //deep copy\n\t\tsortedFrames.sort(function(a, b) { return a-b });\n\t\tstartFrame = sortedFrames[0];\n\t\tendFrame = sortedFrames[sortedFrames.length-1];\n\t\tif (startFrame == endFrame) {\n \t\talert('At least two dynamic objects are required');\n\t\t}\n\t\tvar sortedPoses = [];\n\t\tvar sortedRotations = [];\n\t\tfor (var i=0; i<sortedFrames.length; i++){\n\t\t\tvar idx = labeledFrames.indexOf(sortedFrames[i]);\n\t\t\tsortedPoses.push(labeledPoses[idx]);\n\t\t\tsortedRotations.push(labeledRotations[idx]);\n\t\t}\n\n\t\t// densely load the images for dynamic frames\n\t\tvar listName = String('poses/');\n\t\tlistName = sequence.folderName.concat(listName);\n\t\tvar frameName = sequence.folderName + 'cameraIndex.txt';\n\t\tloadCameraParaMultipleDense(listName, frameName, startFrame, endFrame, false); \n\n\t\t//go through each timestamp to search the most matching bbox on the spline \n\t\tvar curve = splineCurves[INTERSECTED.name.dynamicSeq];\n\t\tvar vertices = curve.mesh.geometry.vertices;\n\t\tvar shape = INTERSECTED.clone();\n\t\tvar dis = Math.sqrt((sortedPoses[0].x-sortedPoses[sortedPoses.length-1].x)*(sortedPoses[0].x-sortedPoses[sortedPoses.length-1].x) + \n\t\t\t\t(sortedPoses[0].y-sortedPoses[sortedPoses.length-1].y)*(sortedPoses[0].y-sortedPoses[sortedPoses.length-1].y) ); \n\t\tvar eps = dis/ARC_SEGMENTS;\n\t\tvar startVertice = getVectorIndex(vertices, sortedPoses[0], eps);\n\t\tvar endVertice;\n\t\tvar endRotation;\n\t\tfor (var i=0; i<sortedFrames.length-1; i++){\n\t\t\tendVertice = getVectorIndex(vertices, sortedPoses[i+1], eps);\n\t\t\tvar startRotation = sortedRotations[i]; \n\t\t\tvar endRotation = sortedRotations[i+1]; \n\t\t\tvar rotationList = Array.apply(null, {length: endVertice-startVertice}).map(Number.call, Number);\n\t\t\t// split the spline w.r.t. to the control objects\n\t\t\tvar vertice_min = 0;\n\t\t\tvar vertice_max = ARC_SEGMENTS;\t\n\t\t\tfor (var f = sortedFrames[i]; f < sortedFrames[i+1]; f++){\n\t\t\t\tif (labeledFrames.indexOf(f) > -1 || fullCamList.indexOf(f) < 0) {continue;}\n\t\t\t\tvar indexFrame = getPointsAtTime(indexOnSpline, f);\n\t\t\t\tvar max_count = 0;\n\t\t\t\tvar fit_position; \n\t\t\t\tvar fit_rotation = new THREE.Euler();\n\t\t\t\t// initialize the estimation according to timestamp\n\t\t\t\tvar initEstimation = Math.round((f-sortedFrames[i])/(sortedFrames[i+1]-sortedFrames[i])*(endVertice-startVertice)) + startVertice;\n\t\t\t\t// Not clear why the vertices are not linearly distributed \n\t\t\t\t// when there are only two point, so search the full line \n\t\t\t\t// when there are only two points, otherwise search the vicinity \n\t\t\t\t// based on the initial estimation \n\t\t\t\tif (sortedFrames.length>2){\n\t\t\t\t\tvertice_min = Math.max(0, initEstimation-Math.round(ARC_SEGMENTS/10));\n\t\t\t\t\tvertice_max = Math.min(ARC_SEGMENTS, initEstimation+Math.round(ARC_SEGMENTS/10));\n\t\t\t\t}\n\t\t\t\tvar rotationZRange = endRotation.z - startRotation.z; \n\t\t\t\tif ((Math.abs(rotationZRange))>Math.PI){\n\t\t\t\t\trotationZRange = 2*Math.PI - rotationZRange; \t\n\t\t\t\t}\n\t\t\t\t// search optimal position within fixed range\n\t\t\t\tfor (var v = vertice_min; v<vertice_max; v++){\n\t \t\t\tvar ratio = (v-startVertice)/(endVertice-startVertice);\n\t\t\t\t\tshape.position.copy( vertices[v] );\n\t\t\t\t\tshape.rotation.z = ratio*rotationZRange\t+ startRotation.z; \n\t\t\t\t\tshape.updateMatrixWorld();\n\t\t\t\t\tvar points = getPointsInCube(indexFrame, shape, grid);\n\t\t\t\t\tif (points.index.length > max_count) {\n\t \t\t\t\tmax_count = points.index.length;\n\t \t\t\t\tfit_position = vertices[v];\n\t \t\t\t\tfit_rotation.x = ratio*(endRotation.x-startRotation.x) + startRotation.x;\n\t \t\t\t\tfit_rotation.y = ratio*(endRotation.y-startRotation.y) + startRotation.y;\n\t \t\t\t\tfit_rotation.z = ratio*rotationZRange + startRotation.z;\n\t\t\t\t\t}\t\n\t\t\t\t}\n\t\t\t\tvar object = copyShape(fit_position, fit_rotation);\n\t\t\t\tobject.name.timestamp = f;\n\t\t\t\tobject.name.dynamicIdx = -2; //doesn't belong to control point \n\t\t\t}\n\t\t\tstartVertice = endVertice;\n\t\t}\t\n\t}\t\n\n\t//change the display mode for better visualization\n\tresetParas(true);\n\tsetTimeout(function (){\n\t\tchangeGroupVisbilitybyLabel(false, 'dynamicIdx', -2);\n\t\tcurve.mesh.material.color = new THREE.Color(SPLINE_COLOR[1]);\n\t}, 600)\n\tsetTimeout(function (){\n\t\tif (controlHandler.dispMode!=4 && controlHandler.dispMode!=5){\n\t\t\tchangeDispMode(5);\n\t\t}\n\t\tshaderMaterial.uniforms.timestamp_center.value = startFrame;\n\t\tshaderMaterial.uniforms.jetMode.value = 2;\n\t\tslidingPointCloud();\n\t}, 1200)\n\n\tsplineIsAutoBoxed[INTERSECTED.name.dynamicSeq]=1;\n}",
"function derive(){ // Fills Arrays of 1sd Derivative Coordinates\n\tvar m = 0; // Slope!\n\t\n\t//console.clear(); // For Debug.\n\t//console.log(\"Derivative Points:\"); // For Debug.\n\t// Find the Slope at Every Point of the Function\n\tfor(i=0;i<xPoints.length;i++) {\n\t\tm =(yPoints[i+1]-yPoints[i])/(xPoints[i+1]-xPoints[i]); // Calculate Slope\n\t\t//console.log(\"M: \"+m); // Debug\n\t\t/* if(xPoints[i]>0.5&&xPoints[i]<1)\n\t\t\tconsole.log(xPoints[i]+\", \"+m.toFixed(4)); */\n\n\t\tif(!isNaN(m)&&m!=Infinity&&!(Math.abs(m)>hLines/2*gScale)&&i>0){\n\t\t\t\t\n\t\t\t\n\t\t\tderX[i]=xPoints[i].toFixed(4);\n\t\t\tderY[i]=m.toFixed(4);\n\t\t\tif(functionInput.value.includes(\"abs\")&&derY[i]>0&&derY[i-1]<0||derY[i]<0&&derY[i-1]>0||derY[i]>0&&derY[i-1]==0||derY[i]<0&&derY[i-1]==0){\n\t\t\t\tderY[i]=NaN;\n\t\t\t}\n\t\t\t//if(derX[i]>-0.5&&derX[i]<0.5)\n\t\t\t\t//console.log(derX[i],derY[i]); // Debug\n\t\t}\n\t}\n}",
"continue(curve) {\n const lastPoint = this._points[this._points.length - 1];\n const continuedPoints = this._points.slice();\n const curvePoints = curve.getPoints();\n for (let i = 1; i < curvePoints.length; i++) {\n continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));\n }\n const continuedCurve = new Curve3(continuedPoints);\n return continuedCurve;\n }",
"function skip_short_knots(intersections) \n{ \n let path_lines = []\n for(let i = 0; i < intersections.length; ++i)\n path_lines.push([intersections[i], intersections[(i+1)%intersections.length]])\n\n let found, len = path_lines.length\n if (len == 3)\n return\n do {\n found = false\n // go over the path with 3 indices, look for middle that's different in sign from ends\n let a, b, c, np;\n for(a = 0; a < len; ++a) {\n b = (a+1)%len, c = (a+2)%len\n np = get_line_intersection(path_lines[a], path_lines[c], false)\n if (np !== null) {\n found = true;\n break;\n }\n }\n if (found) {\n np.from_idx = intersections[b].from_idx\n intersections.splice(b, 1, np)\n intersections.splice((b+1)%len, 1)\n path_lines.splice(b, 1)\n }\n len = path_lines.length\n } while(found && len > 3) // if we found one knot and removed it, try to find another one\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Similar to FastPath.prototype.call, except that the value obtained by accessing this.getValue()[name1][name2]... should be arraylike. The callback will be called with a reference to this path object for each element of the array. | each(callback, ...names) {
const {
stack
} = this;
const {
length
} = stack;
let value = getLast(stack);
for (const name of names) {
value = value[name];
stack.push(name, value);
}
for (let i = 0; i < value.length; ++i) {
if (i in value) {
stack.push(i, value[i]); // If the callback needs to know the value of i, call
// path.getName(), assuming path is the parameter name.
callback(this);
stack.length -= 2;
}
}
stack.length = length;
} | [
"each(callback, ...names) {\n const {\n stack\n } = this;\n const {\n length\n } = stack;\n let value = getLast(stack);\n\n for (const name of names) {\n value = value[name];\n stack.push(name, value);\n }\n\n for (let i = 0; i < value.length; ++i) {\n if (i in value) {\n stack.push(i, value[i]); // If the callback needs to know the value of i, call\n // path.getName(), assuming path is the parameter name.\n\n callback(this);\n stack.length -= 2;\n }\n }\n\n stack.length = length;\n }",
"function invoke(arr, methodName, var_args){\n var args = Array.prototype.slice.call(arguments, 2);\n forEach(arr, function(item){\n item[methodName].apply(item, args);\n });\n return arr;\n }",
"applyPathFilterOnFilesList(file, index, array) {\n this[index] = self.applyCustomPath(file);\n }",
"function access(elem, keys) {\n\t\t\t\t// elem becomes thisArg for datasetChainable:\n\t\t\t\treturn elem && keys && keys.length ? map(ssvToArr(keys), datasetChainable, elem) : [];\n\t\t}",
"function doToArray(array, callback){\n array.forEach(callback)\n}",
"function procesar (unArray, callback) {\n return callback (unArray)\n}",
"function exp (arr){\n\tif (Array.isArray(arr)){\n\t\treturn arr[0](arr[1], arr[2]);\n\t\t}\n\treturn arr;\n}",
"function operate(array, func) {\r\n if (array) {\r\n for (var n=0; n<array.length; n++) {\r\n func(array[n], n);\r\n }\r\n }\r\n return array;\r\n}",
"function iterate(callback){\n let array = [\"dog\", \"cat\", \"squirrel\"]\n array.forEach(callback)\n return array\n}",
"function arrayToString()\n{\n\tif ( ! arguments.length ) { return '/' + this.map( mapValue ).join( '/' ) ; } // jshint ignore:line\n\telse { return '/' + Array.prototype.slice.apply( this , arguments ).map( mapValue ).join( '/' ) ; } // jshint ignore:line\n}",
"resolveAll(items, pathArray) {\n this._subgraph_by_id = {};\n this._subgraph = [];\n const finals = this.resolve(items, pathArray, true);\n return [ finals, this._subgraph ];\n }",
"function command_executor(arr, light_constructor){\n command_array = command_array_creator(arr);\n light_array = light_array_creator(light_constructor);\n command_array.forEach( command => {\n cmd = command[0],\n [x1, y1] = command[1],\n [x2, y2] = command[2];\n\n for( i = x1; i <= x2; i++){\n for( j = y1; j <= y2; j++){\n light_array[i][j][cmd]();\n }\n }\n })\n return light_array\n}",
"function forEach(arr1, func1){\n for(var i=0; i < arr1.length; i++){\n // printName(addressBook[i])\n func1(arr1[i]);\n }\n}",
"function firstVal(arg, func) {\n if(Array.isArray(arg) == Array) {\n func(arr[0], index, arr);\n }\n if(arr.constructor == Object) {\n func(arg[key], key, arg);\n}\n}",
"function firstVal(arr, func) {\n func(arr[0], index, arr);\n}",
"function each( a, f ){\n\t\tfor( var i = 0 ; i < a.length ; i ++ ){\n\t\t\tf(a[i])\n\t\t}\n\t}",
"function tap(arr, callback){\n callback(arr); \n return arr;\n}",
"function element(array, generator){\n\treturn function(){\n\t\tvar index = generator();\n\t\tif (index !== undefined){\n\t\t\treturn array[index];\n\t\t}\n\t};\n}",
"function myFilter(array, callback) {\n return callback(array);\n}",
"retrieve ( arr , rect ) {\n\n const index = this.getIndex(rect)\n if (index !== -1 && this.nodes[0]) {\n arr = arr.concat( this.nodes[index].retrieve( arr , rect ) )\n }\n\n arr = arr.concat( this.objects )\n\n return arr\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET testing all stack | function testGetAllStack(done) {
chai.request(server)
.get(BASEURL + 'all')
.end(function(err, res) {
res.should.be.json;
res.body.should.be.a('object');
res.body.should.have.property('status');
res.body.should.have.property('success');
res.body.should.have.property('result');
res.body.status.should.equal(200);
res.body.result.should.be.a('array');
done();
});
} | [
"function testGetStackById(done, stack) {\n chai.request(server)\n .get(BASEURL + 'id/' + stack._id)\n .end(function(err, res) {\n res.should.be.json;\n res.body.should.be.a('object');\n res.body.should.have.property('status');\n res.body.should.have.property('success');\n res.body.should.have.property('result');\n res.body.status.should.equal(200);\n res.body.result.should.be.a('object');\n done();\n });\n}",
"function callStackAPI() {\n $.ajax({\n url: urlStack,\n method: \"GET\"\n }).then(function (response) {\n for (var i = 0; i < 5; i++) {\n var qstnObject = {};\n var keywordURL = \"\";\n var keywordTitle = \"\";\n qstnObject.keywordURL = response.items[i].link;\n qstnObject.keywordTitle = response.items[i].title;\n questionsArray.push(qstnObject);\n }\n showQuestions(questionsArray);\n })\n}",
"async function getResourceStackAssociation() {\n templates = {};\n\n await sdkcall(\"CloudFormation\", \"listStacks\", {\n StackStatusFilter: [\"CREATE_COMPLETE\", \"ROLLBACK_IN_PROGRESS\", \"ROLLBACK_FAILED\", \"ROLLBACK_COMPLETE\", \"DELETE_FAILED\", \"UPDATE_IN_PROGRESS\", \"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS\", \"UPDATE_COMPLETE\", \"UPDATE_ROLLBACK_IN_PROGRESS\", \"UPDATE_ROLLBACK_FAILED\", \"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS\", \"UPDATE_ROLLBACK_COMPLETE\"]\n }, true).then(async (data) => {\n await Promise.all(data.StackSummaries.map(async (stack) => {\n await sdkcall(\"CloudFormation\", \"getTemplate\", {\n StackName: stack.StackId,\n TemplateStage: \"Processed\"\n }, true).then((data) => {\n template = null;\n try {\n template = JSON.parse(data.TemplateBody);\n templates[stack.StackName] = template;\n } catch(err) {\n console.log(\"Couldn't parse\"); // TODO: yaml 2 json\n }\n });\n }));\n });\n\n console.log(templates);\n}",
"listAllGroups () {\n return this._apiRequest('/groups/all')\n }",
"static async getStackInfo(stackName) {\n var client = new AWS.CloudFormation();\n var stacks = await client.describeStacks({ StackName: stackName }).promise();\n return stacks['Stacks'][0];\n }",
"function getStack() {\n return settings.getStack();\n}",
"function getAllprojects(){\n\n}",
"function getStackResource() {\n const { stackResource } = exports.getStore();\n return stackResource;\n}",
"getAllInterests() {\n return fetch(\"http://localhost:8088/interests\")\n .then(response => response.json())\n }",
"function getAllIssues() {\n // Fetches all issues from server\n fetch('http://localhost:1234/whap/issues?' + 'getAllIssues')\n .then((resp) => resp.json())\n .then(function(data) {\n // Loads them all into fuck\n fuck = data[\"result\"];\n });\n}",
"function LabsController($scope, RestFul) {\n $scope.labs_list = function() {\n RestFul.error(\n {\"action\": \"OnlineLearning:LabList\", \"params\": {}},\n function(response) {\n if (response.hasOwnProperty('message')) {\n $scope.labs = response.data;\n console.log($scope.labs);\n }\n }\n )\n }\n\n $scope.labs_list();\n}",
"async getAll(req, res) {\n try {\n let data = await Pemasok.findAll();\n\n if (!data) {\n return res.status(404).json({\n message: \"Pemasok Not Found\",\n });\n }\n\n return res.status(200).json({\n message: \"Success\",\n data,\n });\n } catch (e) {\n return res.status(500).json({\n message: \"Internal Server Error\",\n error: e,\n });\n }\n }",
"function getCompanySpecies() {\r\n return get('/companyspecies/getall').then(function (res) {\r\n return res.data;\r\n }).catch(function (err) {\r\n return err.response.data;\r\n });\r\n}",
"async function getAll(res) {\n let twitter = await getRemoteData(twitterCall);\n let facebook = await getRemoteData(fbCall);\n let instagram = await getRemoteData(instaCall);\n res.send({ \"twitter\": twitter, \"facebook\": facebook, \"instagram\": instagram });\n}",
"async getAllSnowboards(req, res) {\n console.log(\"getAllSnowboards()\")\n\n const docs = await Snowboard.find({})\n\n if (docs) res.json(docs)\n else res.status(404).send(\"not found\")\n }",
"function listClick2Call() {\n api.send('apps.get_list', [false])\n .success((apps) => {\n for (let a of apps) {\n if (a.package.type === 'CLICKTOCALL')\n console.log(`hash: ${a.hash} - name: ${a.name}, type: ${a.package.type}`);\n }\n })\n .error(error);\n}",
"get resourceStack() {\n const actionResource = this.actionProperties.resource;\n if (!actionResource) {\n return undefined;\n }\n const actionResourceStack = core_1.Stack.of(actionResource);\n const actionResourceStackEnv = {\n region: actionResourceStack.region,\n account: actionResourceStack.account,\n };\n return sameEnv(actionResource.env, actionResourceStackEnv) ? actionResourceStack : undefined;\n }",
"function getAll() {\n\t'use strict';\n\tds.historics.get(function(err, response) {\n\t\tif (err)\n\t\t\tconsole.log(err);\n\t\telse {\n\t\t\tconsole.log('Historic queries: ' + JSON.stringify(response));\n\t\t\tcheckStatus();\n\t\t}\n\t});\n}",
"async function ListFunctions() {\n let functionService = new fx.FunctionService(process.env.MICRO_API_TOKEN);\n let rsp = await functionService.list({});\n console.log(rsp);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
when we move from point1 to point2 how we make this move ? The retuen value looks like: | static findMoveDirection(point1, point2) {
return [
point2.y > point1.y ? interface_4.Direction.TOP : interface_4.Direction.BOTTOM,
point2.x > point1.x ? interface_4.Direction.RIGHT : interface_4.Direction.LEFT
];
} | [
"function moveOrigin(points, newOriginX, newOriginY){\n for(var i = 0; i<points.length; i+=2){\n points[i] -= newOriginX;\n points[i+1] -= newOriginY;\n }\n}",
"moveTo(x, y) {\n let coordinates = this.getXY();\n this.x = x + coordinates.x;\n this.y = y + coordinates.y;\n }",
"function increment(v1, v2, dst) {\r\n let d = dist(v1.x, v1.y, v2.x, v2.y);\r\n let t = dst/d;\r\n if (t < 0) return v1;\r\n if (t > 1) return v2;\r\n let x = ((1 - t) * v1.x) + (t * v2.x);\r\n let y = ((1 - t) * v1.y) + (t * v2.y);\r\n return new Vector(x, y);\r\n}",
"moveAround() {\r\n\r\n\r\n }",
"move() {\n this.change = this.mouthGap == 0 ? -this.change : this.change;\n this.mouthGap = (this.mouthGap + this.change) % (Math.PI / 4) + Math.PI / 64;\n this.x += this.horizontalVelocity;\n this.y += this.verticalVelocity;\n }",
"function moveOriginForPoints(points, newOriginX, newOriginY){\n for(var i = 0; i<points.length; i++){\n points[i].x -= newOriginX;\n points[i].y -= newOriginY;\n }\n}",
"actualizarXY(){\n this.x += this.desplX;\n this.y += this.desplY;\n\treturn true;\n }",
"animatePlayerSwap(p1, p2) {\n var done = false;\n if (p1 != undefined) {\n swapping[0] = p1;\n swapping[1] = p2;\n\n for (var p of swapping) {\n if ((p.pos.x < 400) && (p.pos.y < 200)) {\n for (var yval = 110 ; yval <= 300 ; yval += 10) {\n p.addStep(new Point(75, yval));\n }\n } else if ((p.pos.x < 400) && (200 < p.pos.y)) {\n for (var yval = 290 ; 100 <= yval ; yval -= 10) {\n p.addStep(new Point(75, yval));\n }\n } else if ((400 < p.pos.x) && (p.pos.y < 200)) {\n for (var yval = 110 ; yval <= 300 ; yval += 10) {\n p.addStep(new Point(805, yval));\n }\n } else if ((400 < p.pos.x) && (200 < p.pos.y)) {\n for (var yval = 290 ; 100 <= yval ; yval -= 10) {\n p.addStep(new Point(805, yval));\n }\n }\n }\n\n swapInterval = setInterval( function() {\n court.animatePlayerSwap();\n }, 20 );\n } else {\n this.draw();\n\n var moved = 0;\n for (var p of swapping) {\n moved += p.takeStep();\n }\n\n if (moved <= 0) {\n clearInterval(swapInterval);\n }\n }\n }",
"function initP2animate() {\r\n if (oldPlayer2loc < player2loc) {\r\n let curLocationX = waypointArray[oldPlayer2loc][0] - 42;\r\n let curLocationY = waypointArray[oldPlayer2loc][1] - 123;\r\n oldPlayer2loc = oldPlayer2loc + 1;\r\n let newLocationX = waypointArray[oldPlayer2loc][0] - 42;\r\n let newLocationY = waypointArray[oldPlayer2loc][1] - 123;\r\n points = linePoints(curLocationX, curLocationY, newLocationX, newLocationY, frameCount);\r\n currentFrame = 0;\r\n currentX = newLocationX;\r\n currentY = newLocationY;\r\n animRolling = true;\r\n animateP2();\r\n }else if (oldPlayer2loc === player2loc) {\r\n eventChecker();\r\n }\r\n }",
"function diffPoints(point1, point2) {\n return {\n left: point1.left - point2.left,\n top: point1.top - point2.top,\n };\n }",
"function move(currentorder)\n\n/** \n * Every if of the function, checks the value of the objetct direction(string). First step is check where is looking the Rover.\nSedcond step is depending on where is looking the Rover, the function will ++ or -- a position into the Rover coordinates. \nOr change the value of the object direction.\n */ \n{\n if (Myrover.direction === 'up') {\n\n switch (currentorder) {\n case 'f':\n Myrover.position.x++\n break;\n case 'r':\n Myrover.direction = 'right';\n return;\n break;\n case 'b':\n Myrover.position.x--\n break;\n case 'l':\n Myrover.direction = 'left'\n return;\n break;\n };\n };\n\n\n if (Myrover.direction === 'right') {\n switch (currentorder) {\n case 'f':\n Myrover.position.y++\n break;\n case 'r':\n Myrover.direction = 'down';\n return;\n break;\n case 'b':\n Myrover.position.y--\n break;\n case 'l':\n Myrover.direction = 'up';\n return;\n break;\n };\n };\n\n if (Myrover.direction === 'down') {\n switch (currentorder) {\n case 'f':\n Myrover.position.x--\n break;\n case 'r':\n Myrover.direction = 'left'\n return;\n break;\n case 'b':\n Myrover.position.x++\n break;\n case 'l':\n Myrover.direction = 'right'\n return;\n break;\n };\n };\n\n if (Myrover.direction === 'left') {\n switch (currentorder) {\n case 'f':\n Myrover.position.y--\n break;\n case 'r':\n Myrover.direction = 'up'\n return;\n break;\n case 'b':\n Myrover.position.y++\n break;\n case 'l':\n Myrover.direction = 'down'\n return;\n break;\n };\n };\n}",
"function movimentaBolinha(){\n xbolinha += velocidadeXbolinha;\n ybolinha += velocidadeYbolinha;\n}",
"move(destination) {\n if (destination == this.place) return this;\n // the map takes care of the moving and the filter the delivering\n let parcels = this.parcels.map(p => {\n // moving parcels to destination\n // if parcel has not been picked yet return parcel w/o any change\n if (p.place != this.place) return p;\n // parcels moves with the robot i.e there place property gets updated to match the current position\n return {place: destination, address: p.address};\n }).filter(p => p.place != p.address); // delivering parcels when they reach address\n return new VillageState(destination, parcels);\n }",
"function bend (p1, p2, direction) {\n var xLength = p2.x - p1.x;\n var yLength = p2.y - p1.y;\n\n var angle = direction * Math.PI / 4;\n\n var newX = (xLength * Math.cos(angle) - yLength * Math.sin(angle))\n * 0.707106781 + p1.x;\n var newY = (xLength * Math.sin(angle) + yLength * Math.cos(angle))\n * 0.707106781 + p1.y;\n\n return new Point(newX, newY);\n}",
"getPoint1(){\n\t\treturn this.point1\n\t}",
"function movePosition(direction, unit) {\n\t\t\tvar newPosition = [0, 0];\t//initialize variable\n\t\t\tvar index = serverUtility.getUnitIndex(boardgameserver.userID); \n\t\n\t\t\tvar temp = units[index][unit];\n\t\t\tconsole.log(\"Original Position: \" + temp.position); \n\t \t\tnewPosition[0] = direction[0] + temp.position[0];\n\t \t\tnewPosition[1] = direction[1] + temp.position[1];\n\n\t \t\tif (!isValidPosition(newPosition))\n\t \t\t\tconsole.log(\"newPosition: \" + newPosition + \" is off the board\");\n\t \t\telse if (isOverlapping(newPosition))\t//overlapping position\n\t \t\t\tconsole.log(\"newPosition: \" + newPosition + \"is overlapping with another piece\");\n\t \t\telse\n\t \t\t\tunits[index][unit].position = newPosition; \n\t \t\t\n\t\t\treturn newPosition; \n\t\t}",
"function moveForward(marsRover){ // moving depending on the position with x and y\n console.log(\"moveForward was called\");\n if (marsRover.x >= 0 && marsRover.x <= 9 && marsRover.y >=0 && marsRover.y <= 9) { // the grid in 10x10\n switch(marsRover.direction) {\n case \"N\":\n marsRover.y -= 1 \n console.log(\"The Rover is positioned at \" + marsRover.x + \" and \" + marsRover.y);\n break;\n case \"E\":\n marsRover.x += 1\n console.log(\"The Rover is positioned at \" + marsRover.x + \" and \" + marsRover.y);\n break;\n case \"S\":\n marsRover.y += 1\n console.log(\"The Rover is positioned at \" + marsRover.x + \" and \" + marsRover.y);\n break;\n case \"W\":\n marsRover.x -= 1\n console.log(\"The Rover is positioned at \" + marsRover.x + \" and \" + marsRover.y);\n break;\n }\n } else {\n console.log(\"Something is wrong!\");\n }\n}",
"function move(a1, a2){\n a2.push(a1[a1.length-1]);\n a1.pop()\n console.log (a1);\n console.log (a2);\n \n}",
"breshnamDrawLine (point0, point1) {\n let x0 = point0.x >> 0;\n let y0 = point0.y >> 0;\n let x1 = point1.x >> 0;\n let y1 = point1.y >> 0;\n let dx = Math.abs(x1 - x0);\n let dy = Math.abs(y1 - y0);\n let color = new BABYLON.Color4(1,1,0,1);\n\n if(dy > dx){\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dx - dy;\n\n for(let y=y0; y!=y1; y=y+sy){\n this.drawPoint(new BABYLON.Vector2(x0, y), color);\n if(err >= 0) {\n x0 += sx ;\n err -= dy;\n }\n err += dx;\n }\n }\n else{\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dy - dx;\n\n for(let x=x0; x!=x1; x=x+sx){\n this.drawPoint(new BABYLON.Vector2(x, y0), color);\n if(err >= 0) {\n y0 += sy ;\n err -= dx;\n }\n err += dy;\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a function called which verifies that a coupon code is valid, the coupon is not expired. A coupon is no more valid on the day AFTER the expiration date. All dates will be passed as strings in this format: "MONTH DATE, YEAR". | function checkCoupon(enteredCode, correctCode, currentDate, expirationDate){
console.log(enteredCode + ' ' + correctCode + ' ' + currentDate + ' ' + expirationDate)
console.log(enteredCode.length);
if(enteredCode.toString().length < 3 || enteredCode.toString() != correctCode.toString() || enteredCode == '') {
return false;
}
var dateNow = new Date(currentDate);
var dateCoupon = new Date(expirationDate);
if (dateNow > dateCoupon) {
return false;
}
return true;
} | [
"function checkCoupon(coupon) {\n// console.log(\"==checkCoupon==\");\n// set a limit to the expiration date of the coupon\nvar expirationDate = new Date(coupon);\nexpirationDate.setHours(23);\nexpirationDate.setMinutes(59);\nexpirationDate.setSeconds(59);\n// checking if the coupon's date exceeds the END of the date by setting a limit for day (hour, minute, seconds)\n if (expirationDate > new Date()) {\n return false;\n } else {\n return true;\n }\n\n}",
"function validateCoupon(formname)\n{\n \n if(validateForm(formname, 'frmCouponCode', 'Coupon Code', 'R','frmCouponPriceValue', 'Price Value', 'RisDecimal', 'frmMinimumPurchaseAmount', 'Minimum Purchase Amount', 'RisDecimal', 'frmCouponPriceValue', 'Price Value', 'regDecimal','frmCouponActivateDate', 'Coupon Activate date', 'R','frmCouponExpiryDate', 'coupon expiry date', 'R'))\n {\t\n \t\n var CouponActivateDate=document.forms[0].frmCouponActivateDate.value;\n var CouponExpiryDate=document.forms[0].frmCouponExpiryDate.value;\n if(CouponActivateDate > CouponExpiryDate)\n {\n alert(SORRY_CANT_COMPLETE_YOUR_REQ);\n return false;\n }\n } \n else \n {\n return false;\n } \n}",
"function isValidYrMonth(dtStr, FromToCheck){\n\n re = new RegExp(\"/\",\"g\");\n var dtStr = dtStr.replace(re,\"\");\n\n if(!isInteger(dtStr)){\n return false;\n }\n if(dtStr == '000000' && FromToCheck == '1'){\n return false;\n }\n if(dtStr == '999999' && FromToCheck == '2'){\n return false;\n }\n var month;\n var year;\n if(dtStr.length != 6) {\n return false;\n }\n year = dtStr.substring (0, 4);\n month = dtStr.substring (4, 6);\n\n if(year.length != 4 ){\n return false;\n }\n if(month.length != 2 ){\n return false;\n }\n if(month < \"01\" || month > \"12\"){\n return false;\n }\n if(year < \"1000\" || year > \"9999\"){\n return false;\n }\n return true\n}",
"function validateStandardDate(due){\n var mess = \"\";\n if (due == \"\") {\n return mess;\n }\n var patt = /^20[0-9]{2}\\/[01][0-9]\\/[0-3][0-9]$/;\n var tmp = patt.exec(due);\n if (tmp == \"\") {\n return \"Date must take form YYYY/MM/DD.\";\n }\n return tmp;\n\n var DDcap = new Array();\n DDcap[0] = 31;\n DDcap[1] = 28;\n DDcap[2] = 31;\n DDcap[3] = 30;\n DDcap[4] = 31;\n DDcap[5] = 30;\n DDcap[6] = 31;\n DDcap[7] = 31;\n DDcap[8] = 30;\n DDcap[9] = 31;\n DDcap[10] = 30;\n DDcap[11] = 31;\n var PYY = /^[0-9]{1,4}/;\n var YY = parseInt(PYY.exec(due), 10);\n var PTMM = /\\/[0-9]{1,2}\\//;\n var TMM = PTMM.exec(due);\n var PMM = /[0-9]{1,2}/;\n var MM = parseInt(PMM.exec(TMM), 10);\n var PDD = /[0-9]{1,2}$/;\n var DD = parseInt(PDD.exec(due), 10);\n var t = new Date();\n //var et = (t.getTime() - t.getMilliseconds())/1000 - 1293840000; // time since 0:00:00 on Jan 1, 2011\n var bau = true;\n if(YY < 2013){\n mess = \"Date must take form YYYY/MM/DD. \";\n }\n if(MM > 12 || MM < 1){\n mess = \"Date must take form YYYY/MM/DD. \";\n }\n if(DD > DDcap[MM-1] && !(DD==29 && MM==2 && YY % 4 == 0) || DD == 0){\n mess += \"The date you entered is invalid for the month selected\";\n }\n return mess;\n}",
"function checkAllCombination(yyyy, mm, dd) {\n const formateOne = yyyy + mm + dd;\n // console.log(formateOne)\n const formateTwo = dd + mm + yyyy;\n const formateThree = mm + dd + yyyy.substring(2);\n const formateFour = Number(mm) + dd + yyyy;\n\n // checking is palindrome\n\n if (isPailndrome(formateOne)) {\n return `${yyyy} - ${mm} - ${dd}`;\n } else if (isPailndrome(formateTwo)) {\n return `${dd}-${mm}-${yyyy}`;\n } else if (isPailndrome(formateThree)) {\n return `${mm}-${dd}-${yyyy.substring(2)}`;\n } else if (isPailndrome(formateFour)) {\n return `${Number(mm)}-${dd}-${yyyy}`;\n } else {\n return null;\n }\n}",
"function validDates() {\n if (checkIn.val() != '' && checkOut.val() != '') {\n inDate = new Date(checkIn.val())\n outDate = new Date(checkOut.val())\n if (inDate < outDate) {\n return true\n }\n }\n return false\n }",
"function checkValidYear(c,obj)\n\t{\n\t\tvar calendar = eval('calendar'+c);\t\t\t\t\t\n\t\t// ------- 'calendar'+c is calendar componet ID.\n\t\t// ------- if you want to change calendar component ID please \n\t\t// ------- change calendar component ID in calendar generator at method getTagGenerator() too.\n\t\tvar objLength = obj.value.length;\n\t\tvar splitValue\t= \"/\";\n\t\tvar dateArray = obj.value.split(splitValue);\n\t\tvar year = dateArray[2];\n\t\tif( obj.value!=\"\" &&( Number(year) < calendar.minYear || Number(year) > calendar.maxYear) )\n\t\t{\n\t\t\tshowOWarningDialog(\"Data not complete\", \"Year must between \"+calendar.minYear+\" and \"+calendar.maxYear+\".\", \"OK\") ;\n\t\t\tif(Number(year) < calendar.minYear)\n\t\t\t{\n\t\t\t\tobj.value = dateArray[0]+splitValue+dateArray[1]+splitValue+ calendar.minYear;\n\t\t\t}else{\n\t\t\t\tobj.value = dateArray[0]+splitValue+dateArray[1]+splitValue+ calendar.maxYear;\n\t\t\t}\n\t\t\tobj.focus();\n\t\t}\n\t}",
"function chkIsDate(str)\r\n{\r\n\tvar strSeparator = \"-\"; //???????????????\r\n\tvar strDateArray;\r\n\tvar intYear;\r\n\tvar intMonth;\r\n\tvar intDay;\r\n\tvar boolLeapYear;\r\n\tstrDateArray = str.split(strSeparator);\r\n\tif(strDateArray.length!=3) \r\n\t\treturn false;\r\n\t\t\r\n\tif(strDateArray[0].length!=4)\r\n\t\treturn false;\r\n\tintYear = parseInt(strDateArray[0],10);\r\n\tintMonth = parseInt(strDateArray[1],10);\r\n\tintDay = parseInt(strDateArray[2],10);\r\n\r\n\tif(isNaN(intYear)||isNaN(intMonth)||isNaN(intDay)) \r\n\t\treturn false;\r\n\tif(intYear<1 || intYear>2500)\r\n\t\treturn false;\r\n\tif(intMonth>12||intMonth<1) \r\n\t\treturn false;\r\n\r\n\tif((intMonth==1||intMonth==3||intMonth==5||intMonth==7||intMonth==8||intMonth==10||intMonth==12)&&(intDay>31||intDay<1)) \r\n\t\treturn false;\r\n\tif((intMonth==4||intMonth==6||intMonth==9||intMonth==11)&&(intDay>30||intDay<1)) \r\n\t\treturn false;\r\n\tif(intMonth==2){\r\n\t\tif(intDay<1) \r\n\t\t\treturn false;\r\n\r\n\t\tboolLeapYear = false;\r\n\t\tif((intYear%100)==0){\r\n\t\t\tif((intYear%400)==0) \r\n\t\t\t\tboolLeapYear = true;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tif((intYear%4)==0) \r\n\t\t\t\tboolLeapYear = true;\r\n\t\t}\r\n\r\n\t\tif(boolLeapYear){\r\n\t\t\tif(intDay>29) \r\n\t\t\t\treturn false;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tif(intDay>28) \r\n\t\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}",
"function validateGetCalendarForm() {\r\n //TODO: Check valid years, etc.\r\n}",
"function getValidMonth(){\r\n\treturn 3;\r\n}",
"function validateDate(a, b, c) {\n\t\t\t\t\t// Value in the field\n\t\t\t\t\tvar date = $(a).val();\n\t\t\t\t\t// Regular Expression to validate value against\n\t\t\t\t\tvar regularExpression = /^(3[01]|[12][0-9]|0?[1-9])-(1[0-2]|0?[1-9])-(?:[0-9]{2})?[0-9]{2}$/;\n\n\t\t\t\t\tif (c) {\n\t\t\t\t\t\t// Validating field content\n\t\t\t\t\t\tif (!regularExpression.test(date)) {\n\t\t\t\t\t\t\t$(b).text(\"Your input is invalid. Date number only!\")\n\t\t\t\t\t\t\t\t\t.attr(\"class\", \"invalid\");\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$(b).text(\"valid\").attr(\"class\", \"valid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}",
"async function checkForValidIndAndCo(ind, co) {\n const indResult = await db.query(`SELECT code FROM industries`);\n const industries = indResult.rows.map(val => val.code);\n\n const compResult = await db.query(`SELECT code FROM companies`);\n const companies = compResult.rows.map(val => val.code);\n\n if (!(industries.includes(ind) && companies.includes(co))) {\n throw new ExpressError('Please enter valid industry and company codes!', 400);\n }\n}",
"function isAfter(date, ref_date){\n\tvar date_year = parseInt(date.substring(0, 4));\n\tvar date_month = parseInt(date.substring(5, 7));\n\tvar ref_date_year = parseInt(ref_date.substring(0, 4));\n\tvar ref_date_month = parseInt(ref_date.substring(5, 7));\n\t\n\tif(date_year > ref_date_year){\n\t\treturn true;\n\t}\n\tif(date_year == ref_date_year){\n\t\treturn date_month > ref_date_month;\n\t}\n\treturn false;\n}",
"function validateDateFilter() {\n var startEra = getEra(\"start\");\n var endEra = getEra(\"end\");\n var startDate = getDate(\"start\");\n var endDate = getDate(\"end\");\n\n if ((!startEra && startDate) || (startEra && !startDate)) {\n return false;\n }\n if ((!endEra && endDate) || (endEra && !endDate)) {\n return false; \n }\n if ((startEra && startDate) && !(endEra && endDate)) {\n return true;\n }\n if (!(startEra && startDate) && (endEra && endDate)) {\n return true;\n }\n return (compareDates(startDate, startEra, endDate, endEra) <= 0);\n}",
"function validateClassDates(classDesc, classValue, effFromDateDesc, effFromDateValue,\r\n effToDateDesc, effToDateValue) {\r\n if (classValue == null || classValue == '') {\r\n return '';\r\n }\r\n var date1OnOrAfterDate2 = isDate2OnOrAfterDate1(effFromDateValue, effToDateValue);\r\n if (date1OnOrAfterDate2 == 'N') {\r\n return getMessage(\"ci.common.error.classDescription.after\", new Array(classDesc, effToDateDesc, formatDateForDisplay(effToDateValue), effFromDateDesc, formatDateForDisplay(effFromDateValue))) + \"\\n\";\r\n }\r\n else {\r\n return '';\r\n }\r\n}",
"function validateCarYear () {\n let carYear = parseInt(carYearNum.value);\n let currentYear = new Date().getFullYear() + 1;\n \n if (currentYear < carYear) {\n formIsValid = false;\n carYearNum.setCustomValidity('Car year may not exceed ${currentYear}.')\n }\n else {\n carYearNumn.setCustomValidity('');\n }\n }",
"function compareDate(string1, string2) {\n var year1 = string1.substr(0,4);\n var year2 = string2.substr(0,4);\n var month1 = string1.substr(5, 7);\n var month2 = string2.substr(5,7);\n var day1 = string1.substr(8,10);\n var day2 = string2.substr(8,10);\n if (parseInt(year1,10) > parseInt(year2, 10)) {\n return true;\n }\n else if (parseInt(month1, 10) > parseInt(month2, 10) && parseInt(year1, 10) == parseInt(year2, 10)) {\n return true;\n }\n else if (parseInt(day1, 10) > parseInt(day2, 10) && parseInt(month1, 10) == parseInt(month2, 10) && parseInt(year1, 10) == parseInt(year2, 10)) {\n return true;\n }\n else {\n return false;\n }\n}",
"function validateSendCoupon(formname)\n{\n \n if(validateForm(formname, 'frmUserEmail', 'User Email', 'RisEmail'))\n {\t\n return true;\n } \n else \n {\n return false;\n } \n}",
"function dateUsed(monthyear, array) {\n for (k = 0; k < array.length; k++) {\n if (monthyear == array[k]){\n return false;}\n }\n\n return true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
LotLineSprite This Sprite is draw lot line for the slot machines. | function LotLineSprite() {
this.initialize.apply(this, arguments);
} | [
"function hLine(i){\n var x1 = scaleUp(0);\n var x2 = scaleUp(boardSize - 1);\n var y = scaleUp(i); \n drawLine(x1, x2, y, y);\n //alert(\"i:\" + i+ \" x1:\"+x1+ \" x2:\"+x2+\" y1:\"+y+ \" y2:\"+y);\n }",
"function drawLine() {\n let draw = game.add.graphics();\n draw.lineStyle(1, 0xffffff, .3);\n\n draw.moveTo(star1.worldPosition.x + 8, star1.worldPosition.y + 8)\n draw.beginFill();\n draw.lineTo(star2.worldPosition.x + 8, star2.worldPosition.y + 8);\n draw.endFill();\n\n connections.push({\n drawer: draw,\n star1: [star1.worldPosition.x + 8, star1.worldPosition.y + 8],\n star2: [star2.worldPosition.x + 8, star2.worldPosition.y + 8]\n });\n deselectStars();\n }",
"function drawTileSlot(ctx, style, tile_slot, tile_x_pos, tile_y_pos){\n ctx.fillStyle = style;\n tile_slot.drawSelf(ctx, tile_x_pos, tile_y_pos);\n}",
"function DrawMachine(c,x,y) {\n\tvar canvas = document.getElementById(c);\n\tvar context = canvas.getContext(\"2d\");\n\tvar lineWidth = 3;\n\t\n\tcontext.save();\n\t\n\t//draw machine\n\tcontext.beginPath();\n\tcontext.fillStyle=\"#383838\";\n\tcontext.beginPath();\n\tcontext.rect(x, y, 100, -200);\n\tcontext.fill();\n\t\n\tcontext.beginPath();\n\tcontext.fillStyle=\"#ffffff\";\n\tcontext.beginPath();\n\tcontext.rect(x+10, y-130, 80, -60);\n\tcontext.fill();\n\n\tcontext.beginPath();\n\tcontext.moveTo(x+5, y -125);\n\tcontext.lineTo(x+95, y -125);\n\tcontext.lineTo(x+95, y -195);\n\tcontext.lineTo(x+5, y -195);\n\tcontext.lineTo(x+5, y -125);\n\tcontext.lineWidth = lineWidth;\n\tcontext.lineCap = \"round\";\n\tcontext.strokeStyle = \"#C0C0C0\";\n\tcontext.stroke();\n\t\n\tcontext.beginPath();\n\tcontext.fillStyle=\"#ffffff\";\n\tcontext.beginPath();\n\tcontext.rect(x+10, y-60, 60, -50);\n\tcontext.fill();\n\t\n\tcontext.beginPath();\n\tcontext.moveTo(x+5, y -55);\n\tcontext.lineTo(x+75, y -55);\n\tcontext.lineTo(x+75, y -115);\n\tcontext.lineTo(x+5, y -115);\n\tcontext.lineTo(x+5, y -55);\n\tcontext.lineWidth = lineWidth;\n\tcontext.lineCap = \"round\";\n\tcontext.strokeStyle = \"#C0C0C0\";\n\tcontext.stroke();\n\tcontext.restore();\n\t\n\tcontext.beginPath();\n\tcontext.fillStyle=\"#383838\";\n\tcontext.beginPath();\n\tcontext.rect(x+12, y-62, 16, -15);\n\tcontext.rect(x+31, y-62, 16, -15);\n\tcontext.rect(x+50, y-62, 16, -15);\n\tcontext.rect(x+12, y-78, 16, -15);\n\tcontext.rect(x+31, y-78, 16, -15);\n\tcontext.rect(x+50, y-78, 16, -15);\n\tcontext.rect(x+12, y-94, 16, -15);\n\tcontext.rect(x+31, y-94, 16, -15);\n\tcontext.rect(x+50, y-94, 16, -15);\n\tcontext.fill();\n\t\n\t//write numbers\n\tcontext.font = \"12pt Calibri\";\n\tcontext.fillStyle = \"#ffffff\";\n\tcontext.fillText(\"1\", x+15, y-97);\n\tcontext.fillText(\"2\", x+34, y-97);\n\tcontext.fillText(\"3\", x+53, y-97);\n\tcontext.fillText(\"4\", x+15, y-80);\n\tcontext.fillText(\"5\", x+34, y-80);\n\tcontext.fillText(\"6\", x+53, y-80);\n\tcontext.fillText(\"7\", x+15, y-65);\n\tcontext.fillText(\"8\", x+34, y-65);\n\tcontext.fillText(\"9\", x+53, y-65);\n\t\n\tcontext.beginPath();\n\tcontext.fillStyle=\"#ffffff\";\n\tcontext.beginPath();\n\tcontext.rect(x+83, y-70, 10, -40);\n\tcontext.fill();\n\t\n\tcontext.beginPath();\n\tcontext.fillStyle=\"#C0C0C0\";\n\tcontext.beginPath();\n\tcontext.rect(x+85, y-72, 6, -36);\n\tcontext.fill();\n\t\n\tcontext.beginPath();\n\tcontext.fillStyle=\"#ffffff\";\n\tcontext.beginPath();\n\tcontext.rect(x+20, y-25, 50, -20);\n\tcontext.fill();\n\t\n\tcontext.beginPath();\n\tcontext.fillStyle=\"#383838\";\n\tcontext.beginPath();\n\tcontext.rect(x+22, y-27, 46, -16);\n\tcontext.fill();\n\t\n\tcontext.restore();\n}",
"function drawRoad(counter){\n //set background\n background(50);\n //Space between lines\n let space = width / 4;\n //Gap between dashed lines\n let step = height / 10;\n //Line width\n let lineW = 10;\n //Road lines\n //Remove outline on shapes\n noStroke();\n //Dashed lines\n for (i = - 2; i < height; i++) {\n //Yellow lines\n fill(255,i * 25, 0);\n rect(space, step * i + counter, 10, 30);\n rect(space * 3, step * i + counter, 10, 30);\n }\n for(i = 0; i < maxH; i++){\n let val = map(i, 0, maxH, 0, 255);\n stroke(255, val, 0);\n line(0, i, lineW, i);\n \n line(space * 2 - lineW, i, space * 2 - lineW * 2, i);\n line(space * 2 + lineW, i, space * 2 + lineW * 2, i);\n line(maxW - lineW, i, maxW, i); \n }\n}",
"function render_aim_helper_line() {\n var c = {\n x: gamer.x + map.planet_w / 2,\n y: gamer.y + map.planet_h / 2\n };\n\n context.setLineDash([]);\n context.lineWidth = 3;\n context.strokeStyle = '#00ff00';\n context.beginPath();\n context.moveTo(c.x, c.y);\n context.lineTo(c.x + 2 * map.planet_w * Math.cos(deg_to_rad(gamer.angle)), c.y - 2 * map.planet_h * Math.sin(deg_to_rad(gamer.angle)));\n context.stroke();\n }",
"function createMapLine(){\n\tvar pointX = portMapInfo[0].X;\n\tvar pointY = portMapInfo[0].Y;\n\tvar pointX2 = portMapInfo[0].X2;\n\tvar pointY2 = portMapInfo[0].Y2;\n\tvar mapLine = new Kinetic.Line({\n\t\tpoints: [pointX, pointY, pointX2, pointY2],\n\t\tstroke: 'black',\n\t\tstrokeWidth: 3,\n\t\tlineCap: 'round',\n\t\tlineJoin: 'round',\n\t\tDestination: portMapInfo[0].Destination,\n\t\tSource: portMapInfo[0].Source\n\t});\n\treturn mapLine;\n}",
"function buildLine() {\n d3.select(\"#line\").remove();\n var begin = margin.bottom + y(margin.top), final = height;\n var yl = d3.scaleLinear()\n .domain([scoreMax, 0])\n .range([final, 0]);\n\n var score = parseFloat(document.getElementById(\"score\").value) || null;\n \n if(score) {\n var yline = yl(score) + begin;\n\n console.log(yline);\n var svgLine = d3.select(\"#box-line\")\n .append(\"svg\")\n .attr(\"width\", 1260)\n .attr(\"height\", 2)\n .style(\"background\", \"#bc223f\")\n .style(\"opacity\", 1)\n .attr(\"id\", \"line\")\n .attr(\"yl\", yline)\n .attr(\"transform\", \"translate(0,\"+ -yline +\")\");\n }else{\n var allRects = series.selectAll(\"rect\"),\n axisX = d3.selectAll(\".name-courses\")._groups[0];\n axisX.forEach(function(item){\n item.style.opacity = 1\n });\n allRects.style(\"opacity\", 1);\n }\n\n compareCourses();\n\n }",
"shop() {\n // this sets the current scene to \"shop\"\n this.current = \"shop\";\n \n // this draws the floor\n background(148, 82, 52);\n \n //this draws the shelves\n for (let i = 0; i < 4; i++) {\n this.vShelf(50 + this.pxl * 3 * i, 400);\n }\n \n for (let i = 0; i < 2; i++) {\n this.hShelf(25 + this.pxl * 4 * i, 0);\n }\n \n // this draws the welcome mat\n this.mat(2, height/2 - this.pxl);\n \n // this draws a counter\n stroke(191, 179, 157);\n strokeWeight(4);\n for (let i = 0; i < 4; i++) {\n fill(204, 191, 169);\n rect(400 + this.pxl * i, 125, this.pxl, this.pxl);\n }\n \n // this makes Janine\n janine.makeRight();\n }",
"function drawPoweLineCallBack(data, options){\n\tvar newLineShape = options[\"lineShape\"];\n\tvar path = options[\"path\"];\n\tvar dataArray = data.split(\"!\");\n\tvar powerLineId = dataArray[0];\n\tvar color = dataArray[1];\n\tnewLineShape.setOptions({strokeColor:color,path: path});\n\taddMessageWindow(newLineShape,powerLineId)\n\tglobalPlList.set(powerLineId, newLineShape);\n\tvar powerLineAId = dataArray[2];\n\tvar powerLineBId = dataArray[3];\n\tvar holonObjectColor= dataArray[4];\n\tvar holonObjectId = dataArray[5];\n\tvar isCoordinator = dataArray[6];\n\tvar coordinatorLocation=\"\";\n\tvar coordinatorIcon=\"\";\n\tif(typeof powerLineAId != 'undefined' && typeof powerLineBId != 'undefined' && powerLineAId!= 0) {\n\t\t\n\t\tupdateGlobalPowerLineList(powerLineAId,true);\n\t\tupdateGlobalPowerLineList(powerLineBId,false);\n\t}\n\t\n\tif(typeof holonObjectColor != 'undefined' && typeof holonObjectId != 'undefined' && holonObjectId != \"null\" ){\n\t\t var holonObject= globalHoList.get(holonObjectId);\n\t\t holonObject.setOptions({strokeColor:holonObjectColor,fillColor:holonObjectColor });\n\t\t}\n\tif(typeof isCoordinator != 'undefined' && typeof holonObjectId != 'undefined'){\n\t\tif(isCoordinator==\"Yes\"){\n\t\t\tcreateIconOnMap(holonObjectId);\n\t\t}\n\t\telse{\n\t\t\tvar newCoordinatorIds= dataArray[7].split(\"~\");\n\t\t\tvar oldCoordinatorIds= dataArray[8].split(\"~\");\n\t\t\t\n\t\t\tif(oldCoordinatorIds != undefined)\n\t\t\t\t{\n\t\t\t\t\t\tfor (var i=0;i< oldCoordinatorIds.length-1;i++){\n\t\t\t\t\t\t\tvar oldCoordinatorId= oldCoordinatorIds[i];\n\t\t\t\t\t\t\tremoveIconFromMap(oldCoordinatorId);\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tif(newCoordinatorIds != undefined){\n\t\t\t\tfor(var i=0;i< newCoordinatorIds.length-1; i++){\n\t\t\t\t\tvar newCoordinatorId = newCoordinatorIds[i];\n\t\t\t\t\tcreateIconOnMap(newCoordinatorId);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t}\n\t}\n}",
"function CreerMorceauSnakePC (x, y, width, height, dx, dy, historique, color) {\n \n CompteurPC = CompteurPC +1;\n \n //On prepare un tableau vide pour etre passe en parametre de la creation de morceau. Ce tableau contiendra plus tard les objets historiques\n window['Tab'+ CompteurPC] = [];\n \n //On instancie un nouveau morceau de snake\n var morceauSnake = new MorceauSnake(x, y, width, height, dx, dy, window['Tab'+ CompteurPC], color);\n \n //On place notre nouveau morceau de snake dans le tableau\n tableauSnakePC.push(morceauSnake);\n}",
"function drawNet() {\r\n\tcanvasContext.beginPath();\r\n\r\n\t//sets dash length and spacing, first value indicates dash length, second indicates space between dash\r\n\tcanvasContext.setLineDash([30, 15]);\r\n\r\n\t//moves drawing cursor\r\n\tcanvasContext.moveTo(canvas.width / 2, 0);\r\n\tcanvasContext.lineTo(canvas.width / 2, canvas.height);\r\n\tcanvasContext.lineWidth = 5;\r\n\r\n\t//sets line colour\r\n\tcanvasContext.strokeStyle = \"white\";\r\n\tcanvasContext.stroke();\r\n}",
"addLineToLinesDrawn() {\n if (!Array.isArray(this._currentLineCoordinates)) throw Error('Line coordinates must be an array')\n this._linesDrawn.push(this._currentLineCoordinates)\n }",
"drawLine() {\r\n line(this.left.x, this.left.y, this.right.x, this.right.y);\r\n }",
"vShelf(x, y) {\n noStroke();\n for (let i = 0; i < 3; i++) {\n fill(51, 32, 0);\n rect(x, y + this.pxl * i, this.pxl, this.pxl);\n }\n }",
"function CreerMorceauSnake (x, y, width, height, dx, dy, historique, color) {\n \n Compteur = Compteur +1;\n \n //On prepare un tableau vide pour etre passe en parametre de la creation de morceau. Ce tableau contiendra plus tard les objets historiques\n window['Tab'+ Compteur] = [];\n \n //On instancie un nouveau morceau de snake\n var morceauSnake = new MorceauSnake(x, y, width, height, dx, dy, window['Tab'+ Compteur], color);\n \n //On place notre nouveau morceau de snake dans le tableau\n tableauSnake.push(morceauSnake);\n}",
"drawToolRow() {\n let $Div = $('<div />').attr({ id: 'top-row'});\n let $MineCount = $('<input/>').attr({ type: 'text', id: 'mine-count', name: 'mine-count', readonly: true}).val(25);\n let $Timer = $('<input/>').attr({ type: 'text', id: 'timer', name: 'timer', readonly: true}).val('0000');\n let $GridSize = $('<input/>').attr({ type: 'text', id: 'grid-size', name: 'grid-size'}).val(15); // value is the size of the grid. Always a square\n let $Reset = $('<input />').attr({ type: 'button', id: 'reset-button'}).val('Reset').addClass('reset-button');\n let $Music= $('<input />').attr({ type: 'button', id: 'music-button'}).val('Music').addClass('music-button');\n let $gameScreen = $('#game-screen');\n\n $Div.append($MineCount).append($Timer).append($GridSize).append($Reset).append($Music);\n $gameScreen.prepend($Div);\n \n }",
"function addBoxesToLineIds(id){\n var BoxesNumber = Number(Boxes);\n var BoxesArray = [];\n var someNumber = 0;\n if (id<BoxesNumber){\n /**\n * fill only Horizontal lines\n */\n for (var i=(id*BoxesNumber);i<(BoxesNumber+(id*BoxesNumber));i++){\n BoxesArray.push(GameBoxes[i]);\n }\n } else if ((id>=BoxesNumber)&&(id<BoxesNumber*2)){\n /**\n * fill only Vertical lines\n */\n for (var i=0;i<BoxesNumber;i++){\n someNumber = (i*BoxesNumber)+(id-BoxesNumber);\n BoxesArray.push(GameBoxes[someNumber]);\n }\n } else if (id==BoxesNumber*2) {\n for (var i=0;i<BoxesNumber;i++){\n someNumber = (BoxesNumber+1)*i;\n BoxesArray.push(GameBoxes[someNumber]);\n }\n } else {\n for (var i=0;i<BoxesNumber;i++){\n someNumber = (BoxesNumber-1)*(i+1);\n BoxesArray.push(GameBoxes[someNumber]);\n }\n }\n GameLines[id].boxesIds = BoxesArray;\n }",
"static line(spec) {\n return new LineDecoration(spec);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hides any cells and headers in a table if they have no content to prevent empty rows from displaying in grid layout when all cells are render=false or hidden by disclosure | function hideEmptyCells() {
// get all the td elements
jQuery('td.' + kradVariables.GRID_LAYOUT_CELL_CLASS).each(function () {
// check if the children is hidden (progressive) or if there is no content(render=false)
var cellEmpty = jQuery(this).children().is(".uif-placeholder") || jQuery(this).is(":empty");
// hide the header only if the cell and the header is empty
if (cellEmpty) {
var hd = jQuery(this).siblings("th");
var headerEmpty = jQuery(hd).children().is(":hidden") || jQuery(hd).is(":empty");
if (headerEmpty) {
hd.hide();
}
// hide the cell
jQuery(this).hide();
}
});
} | [
"function hide_empty_columns(table) {\r\n\t\tvar column_count = 0;\r\n\t table.each(function(a, tbl) {\r\n\t $(tbl).find('th').each(function(i) {\r\n\t \tcolumn_count++;\r\n\t var remove = true;\r\n\t var currentTable = $(this).parents('table');\r\n\t var tds = currentTable.find('tr td:nth-child(' + (i + 1) + ')');\r\n\t tds.each(function(j) { if (this.innerHTML != '') remove = false; });\r\n\t if (remove) {\r\n\t \tcolumn_count--;\r\n\t $(this).hide();\r\n\t tds.hide();\r\n\t }\r\n\t });\r\n\t });\r\n\r\n\t return column_count;\r\n\t}",
"function unhideColumns (){\n /* hide the \"unhide\" button, reveal the \"hide\" button */\n hideButtonName=\"hide\"+modelKind;\n unhideButtonName=\"unhide\"+modelKind;\n document.getElementById(unhideButtonName).style.visibility=\"hidden\"; \n document.getElementById(hideButtonName).style.visibility=\"visible\";\n/* make the column with that column name re-appear */\n for (var scanHeader=1;scanHeader<colCount;scanHeader++){\n cetteCol=oneRow[0].getElementsByTagName(\"th\")[scanHeader];\n var colHeader=cetteCol.innerText.replace( /^\\s+|\\s+$/g,\"\");\n if (colHeader==modelKind){\n for (var chaqueRow=0;chaqueRow<rowCount;chaqueRow++){\n var chaqueCell=oneRow[chaqueRow].children[scanHeader];\n chaqueCell.style.display=\"table-cell\";\n chaqueCell.style.width=colWidthUsage;\n }\n }\n }\n}",
"function hideEmptySections() {\n\t$('.w-dyn-empty').parents('.section').each(function(){\n\t $(this).hide();\n\t console.log(\"Empty collections have been hidden.\");\n\t});\n}",
"function actionCollapseAll() {\n $('tr[name=action_entry_referer_header]').hide();\n $('tr[name=action_entry_referer]').hide();\n $('tr[name=action_entry_edit_header]').hide();\n $('tr[name=action_entry_edit]').hide();\n}",
"function removeTableData() {\r\n hideTable();\r\n d3.selectAll(\".row_info\").remove();\r\n }",
"function showNoData(tableData, divEle, colspanNo) {\n tableData += '<td align=\"center\" colspan=\"' + colspanNo + '\"> No data to display </td>';\n tableData += '</tbody></table>';\n $('#' + divEle).html(tableData);\n }",
"function hideWatchlistTable() {\n $(\"#watch-table-header\").hide();\n $(\"#watchlist-caption\").hide();\n }",
"function displayTable() {\r\n displayOnly(\"#tableOfContents\");\r\n traverseAndUpdateTableHelper();\r\n prepareText(heirarchy.tree[0].sections[0].id);\r\n activePart = 0;\r\n iconEventListeners();\r\n settingsEventListeners();\r\n scrollEventListener();\r\n}",
"containsHeaders(){\n return this.headerRow.length !== 0;\n }",
"function hideNoTaskHeader(){\n\tif(!pendingTaskCount){\n\t \t$('.pending-task-view .task-left').removeClass('hide');\n\t} else{\n\t \t$('.pending-task-view .task-left').addClass('hide');\n\t}\n}",
"updateColumnDisplay() {\n let i = 0;\n while (i < this.columnData.length) {\n let colData = this.columnData[i];\n let colWidth = colData.getValue('widthVal');\n let colSpan = colData.getValue('colspanVal');\n colData.getElement().show();\n if (colSpan > 1) {\n let colspanEndIndex = ((i + colSpan) < this.columnData.length) ? (i + colSpan) : this.columnData.length;\n i++;\n // hide columns within colspan\n while (i < colspanEndIndex) {\n colWidth += this.columnData[i].getValue('widthVal');\n this.columnData[i].getElement().hide();\n i++;\n }\n } else {\n i++;\n }\n colData.setDisplayWidth(colWidth);\n colData.updateDisplay();\n }\n }",
"function viderTable() {\n var numRows = document.getElementById(\"table\").rows.length;\n var numColumns = document.getElementById(\"table\").rows[0].cells.length;\n for (var i = 0; i < numRows; i++) {\n for (var j = 0; j < numColumns; j++) {\n if (document.getElementById(\"table\").rows[i].cells[j].innerHTML != '') {\n document.getElementById(\"table\").rows[i].cells[j].innerHTML = '';\n changerCouleur(i,j);\n }\n }\n }\n}",
"function clear() {\n $('.tablesorter tbody tr').remove();\n $('.tablesorter').trigger('updateAll');\n}",
"function hideAll() {\n for(let bio in allBios) {\n if(!allBios[bio].hasClass('hidden-heading')) {\n allBios[bio].addClass('hidden-heading');\n }\n }\n }",
"function tableIsVisible() {\r\n if ($(\"#myTable, #gra\").visibility == \"visible\") {\r\n } else {\r\n $(\"#myTable, #gra\").css('visibility', 'visible');\r\n }\r\n }",
"function addNonDataColumn() {\n const htmlTableColumns = getTableColumns();\n config.columns.push({data: null});\n const columnsShort = config.columns.length - htmlTableColumns;\n if (columnsShort > 0) {\n for (let i=0; i<columnsShort; i++) { addTableColumn(); }\n }\n }",
"hideColFilter(state) {\n state.showColFilter = false;\n }",
"function placeEmptyPlaceholder() {\n $('.details-table td').each(function () {\n if ($(this).text() == '' || $(this).text() == null || $(this).text() == 'None' || $(this).text() == 'none') {\n $(this).text('-');\n }\n });\n}",
"function hideDescendants($node) {\n var $temp = $node.closest('tr').siblings();\n if ($temp.last().find('.spinner').length) {\n $node.closest('.orgchart').data('inAjax', false);\n }\n var $visibleNodes = $temp.last().find('.node:visible');\n var $lines = $visibleNodes.closest('table').closest('tr').prevAll('.lines').css('visibility', 'hidden');\n $visibleNodes.addClass('slide slide-up').eq(0).one('transitionend', function() {\n $visibleNodes.removeClass('slide');\n $lines.removeAttr('style').addClass('hidden').siblings('.nodes').addClass('hidden');\n if (isInAction($node)) {\n switchVerticalArrow($node.children('.bottomEdge'));\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
========================================================================== isTouchDevice return true if it is a touch device ========================================================================== | function isTouchDevice() {
return !!('ontouchstart' in window) || ( !! ('onmsgesturechange' in window) && !! window.navigator.maxTouchPoints);
} | [
"get isTouch()\n {\n return \"ontouchstart\" in window;\n }",
"function deviceHasTouchScreen() {\n let hasTouchScreen = false;\n if (\"maxTouchPoints\" in navigator) {\n hasTouchScreen = navigator.maxTouchPoints > 0;\n } else if (\"msMaxTouchPoints\" in navigator) {\n hasTouchScreen = navigator.msMaxTouchPoints > 0;\n } else {\n var mQ = window.matchMedia && matchMedia(\"(pointer:coarse)\");\n if (mQ && mQ.media === \"(pointer:coarse)\") {\n hasTouchScreen = !!mQ.matches;\n } else if ('orientation' in window) {\n hasTouchScreen = true; // deprecated, but good fallback\n } else {\n // Only as a last resort, fall back to user agent sniffing\n var UA = navigator.userAgent;\n hasTouchScreen = (\n /\\b(BlackBerry|webOS|iPhone|IEMobile)\\b/i.test(UA) ||\n /\\b(Android|Windows Phone|iPad|iPod)\\b/i.test(UA)\n );\n }\n }\n return hasTouchScreen;\n }",
"function useTouch() {\n return isNativeApp() || $.browser.mobile || navigator.userAgent.match(/iPad/i) != null;\n}",
"function isReallyTouch(e){//if is not IE || IE is detecting `touch` or `pen`\nreturn typeof e.pointerType==='undefined'||e.pointerType!='mouse';}",
"function didTouchMove(touch) {\n return Math.abs(touch.screenX - touchStartX) > 10 || Math.abs(touch.screenY - touchStartY) > 10;\n }",
"function isAndroidTablet() {\n\t\tif (navigator.userAgent.match(/iPad/i) != null)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}",
"function chkMobile() {\r\n\treturn /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);\r\n}",
"function IsPC() {\n var userAgentInfo = navigator.userAgent\n var Agents = [\"Android\", \"iPhone\", \"SymbianOS\", \"Windows Phone\", \"iPad\", \"iPod\"]\n var devType = 'PC'\n for (var v = 0; v < Agents.length; v++) {\n if (userAgentInfo.indexOf(Agents[v]) > 0) {\n // Determine the system platform used by the mobile end of the user\n if (userAgentInfo.indexOf('Android') > -1 || userAgentInfo.indexOf('Linux') > -1) {\n //Android mobile phone\n devType = 'Android'\n } else if (userAgentInfo.indexOf('iPhone') > -1) {\n //Apple iPhone\n devType = 'iPhone'\n } else if (userAgentInfo.indexOf('Windows Phone') > -1) {\n //winphone\n devType = 'winphone'\n } else if (userAgentInfo.indexOf('iPad') > -1) {\n //Pad\n devType = 'iPad'\n }\n break;\n }\n }\n docEl.setAttribute('data-dev-type', devType)\n }",
"function discard_touch(touch) {\n /* Discard the cached touch location */\n var i = touch_index(touch);\n if (i != -1) { /* should never be -1, but we check to be sure */\n touches.splice(i, 1);\n return true;\n }\n\n return false;\n}",
"function isRectTouching(pt1,sz1,pt2,sz2){\n\t//check if all 4 of the corners of rect1 are in this\n\treturn isPointInRect(pt1,pt2,sz2)//topleft\n\t\t|| isPointInRect(new point(pt1.x +sz1.x,pt1.y),pt2,sz2)//top right\n\t\t|| isPointInRect(new point(pt1.x +sz1.x,pt1.y + sz1.y),pt2,sz2)//bot right\n\t\t|| isPointInRect(new point(pt1.x,pt1.y + sz1.y),pt2,sz2);//bot left\n\n}",
"_isNativePlatform() {\n if ((this._isIOS() || this._isAndroid()) && this.config.enableNative) {\n return true;\n } else {\n return false;\n }\n }",
"function touchStart() {\r\n getTouchPos();\r\n\r\n draw(ctx,touchX,touchY);\r\n lastX = touchX, lastY = touchY;\r\n event.preventDefault();\r\n }",
"deviceStatusLive(device) {\n\t\t\tconst difference = this.getTimeDifference(device.updated_at);\n\n\t\t\treturn (difference <= 15);\n\t\t}",
"function checkDeviceIfExist(devName,type){\n\tvar myReturn = false;\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tif(devName == \"\"){\n\t\tfor(var a=0; a < window['variable' + dynamicLineConnected[pageCanvas]].length;a++){\n\t\t\tif(pageCanvas == window['variable' + dynamicLineConnected[pageCanvas]][a].Page){\n\t\t\t\tmyReturn = true;\n\t\t\t}\n\t\t}\t\n\t}else{\n\t\tfor(var a=0; a<devices.length;a++){\n\t\t\tif (devName == devices[a].DeviceName && type != \"createdev\"){\n\t\t\t\tmyReturn = true;\n\t\t\t}else if(devName == devices[a].DeviceName && type == \"createdev\"){ \n\t\t\t\tmyReturn = true;\n\t\t\t}\t\n\t\t}\n\t}\n\treturn myReturn;\n}",
"function isStillTap(){\n var max = arrayMax(piezoTrack); piezoTrack = [];\n return (max==undefined || max>config.piezoTreshold);\n}",
"function isDeviceExisted(dev_id, devices) {\n\tfor (var i in devices)\n\t{\n\t\tif(devices[i].deviceID == dev_id)\n\t\t{\n\t\t\treturn 1;\n\t\t}\n\t}\n\treturn 0;\n}",
"function twoRectsTouching(rect1,rect2){\n\treturn (rect1.x < rect2.x + rect2.w && rect1.x +rect1.w > rect2.x &&\n\t\t\trect1.y < rect2.y + rect2.h && rect1.y + rect1.h > rect2.y);\n}",
"_isTextInput(inputElement) {\n const that = this;\n\n if (!inputElement) {\n return;\n }\n\n const type = that._getType(inputElement);\n return type === 'text' || type === 'textarea' || type === 'password' || type === 'smart-input-inner' || type === 'smart-numeric-text-box'\n || inputElement.classList.contains('smart-input') || inputElement instanceof Smart.TextBox || inputElement.classList.contains('smart-masked-text-box') || inputElement.classList.contains('smart-text-box') || inputElement.classList.contains('smart-date-time-picker');\n }",
"function isMediaDevicesSuported(){return hasNavigator()&&!!navigator.mediaDevices;}",
"function supportsDisplay() {\n var hasDisplay =\n this.event.context &&\n this.event.context.System &&\n this.event.context.System.device &&\n this.event.context.System.device.supportedInterfaces &&\n this.event.context.System.device.supportedInterfaces.Display\n\n return hasDisplay;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParsernull_statement. | visitNull_statement(ctx) {
return this.visitChildren(ctx);
} | [
"function NilNode() {\n}",
"visitRespect_or_ignore_nulls(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"lesx_parseEmptyExpression() {\n var node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc);\n return this.finishNodeAt(node, 'LesxEmptyExpression', this.start, this.startLoc);\n }",
"EmptyStatement() {\n this._eat(\";\");\n return factory.EmptyStatement();\n }",
"function isEmptyStmt(expr) {\r\n\r\n // for a if/elseif or a foreach statement, if only the root expression\r\n // is present without any children, then it is treated as an \r\n // empty stmt. Note: Forever and Else don't need children.\r\n //\r\n if ((expr.isIf() || expr.isElseIf() || expr.isForeach()) &&\r\n (!expr.exprArr || !expr.exprArr.length)) {\r\n return true;\r\n }\r\n\r\n return false;\r\n}",
"visitSmall_stmt(ctx) {\r\n console.log(\"visitSmall_stmt\");\r\n if (ctx.expr_stmt() !== null) {\r\n return this.visit(ctx.expr_stmt());\r\n } else if (ctx.del_stmt() !== null) {\r\n return this.visit(ctx.del_stmt());\r\n } else if (ctx.pass_stmt() !== null) {\r\n return this.visit(ctx.pass_stmt());\r\n } else if (ctx.flow_stmt() !== null) {\r\n return this.visit(ctx.flow_stmt());\r\n } else if (ctx.import_stmt() !== null) {\r\n return this.visit(ctx.import_stmt());\r\n } else if (ctx.global_stmt() !== null) {\r\n return this.visit(ctx.global_stmt());\r\n } else if (ctx.nonlocal_stmt() !== null) {\r\n return this.visit(ctx.nonlocal_stmt());\r\n } else if (ctx.assert_stmt() !== null) {\r\n return this.visit(ctx.assert_stmt());\r\n }\r\n }",
"visitTest_nocond(ctx) {\r\n console.log(\"visitTest_nocond\");\r\n if (ctx.or_test() !== null) {\r\n return this.visit(ctx.or_test());\r\n } else {\r\n return this.visit(ctx.lambdef_nocond());\r\n }\r\n }",
"visitDatatype_null_enable(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"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}",
"visitNot_test(ctx) {\r\n console.log(\"visitNot_test\");\r\n if (ctx.NOT() !== null) {\r\n return {\r\n type: \"UnaryExpression\",\r\n operator: \"not\",\r\n operand: this.visit(ctx.not_test()),\r\n };\r\n } else {\r\n return this.visit(ctx.comparison());\r\n }\r\n }",
"NullLiteral() {\n this._eat(\"null\");\n return {\n type: \"NullLiteral\",\n value: null,\n };\n }",
"function parse_PrintStatement(){\n\tdocument.getElementById(\"tree\").value += \"PARSER: parse_PrintStatement()\" + '\\n';\n\tCSTREE.addNode('PrintStatment', 'branch');\n\n\t\n\tmatchSpecChars(' print',parseCounter);\n\t\n\tparseCounter = parseCounter + 1;\n\t\n\t\n\tmatchSpecChars('(',parseCounter);\n\t\n\tparseCounter = parseCounter + 1;\n\t\n\t\n\tparse_Expr(); \n\t\n\t\n\t\n\tmatchSpecChars (')',parseCounter);\n\t\n\tCSTREE.endChildren();\n\n\tparseCounter = parseCounter + 1;\n\t\n\t\n}",
"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 paddingBlankHTML(node){if(!isVoid(node)&&!nodeLength(node)){node.innerHTML=blankHTML;}}",
"visitFlow_stmt(ctx) {\r\n console.log(\"visitFlow_stmt\");\r\n if (ctx.break_stmt() !== null) {\r\n return this.visit(ctx.break_stmt());\r\n } else if (ctx.continue_stmt() !== null) {\r\n return this.visit(ctx.continue_stmt());\r\n } else if (ctx.return_stmt() !== null) {\r\n return this.visit(ctx.return_stmt());\r\n } else if (ctx.raise_stmt() !== null) {\r\n return this.visit(ctx.raise_stmt());\r\n } else if (ctx.yield_stmt() !== null) {\r\n return this.visit(ctx.yield_stmt());\r\n }\r\n }",
"enterStatementWithoutTrailingSubstatement(ctx) {\n\t}",
"parseUnknown(tokenizer) {\n const start = tokenizer.advance();\n let end;\n if (start === null) {\n return null;\n }\n while (tokenizer.currentToken &&\n tokenizer.currentToken.is(token_1.Token.type.boundary)) {\n end = tokenizer.advance();\n }\n return this.nodeFactory.discarded(tokenizer.slice(start, end), tokenizer.getRange(start, end));\n }",
"visitCompound_stmt(ctx) {\r\n console.log(\"visitCompound_stmt\");\r\n if (ctx.if_stmt() !== null) {\r\n return this.visit(ctx.if_stmt());\r\n } else if (ctx.while_stmt() !== null) {\r\n return this.visit(ctx.while_stmt());\r\n } else if (ctx.for_stmt() !== null) {\r\n return this.visit(ctx.for_stmt());\r\n } else if (ctx.try_stmt() !== null) {\r\n return this.visit(ctx.try_stmt());\r\n } else if (ctx.with_stmt() !== null) {\r\n return this.visit(ctx.with_stmt());\r\n } else if (ctx.funcdef() !== null) {\r\n return this.visit(ctx.funcdef());\r\n } else if (ctx.classdef() !== null) {\r\n return this.visit(ctx.classdef());\r\n } else if (ctx.decorated() !== null) {\r\n return this.visit(ctx.decorated());\r\n }\r\n }",
"enterStatementNoShortIf(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handler for receiving a new Missile | function handleMissileNew(data){
MyGame.handlers.MissileHandler.handleNewMissile(data.message);//send everything
//Call correct Audio
if(data.message.owner == 'player'){
MyGame.handlers.AudioHandler.handleNewGlobalAudio({
type:'laser',
center:{
x: data.message.state.center.x,
y: data.message.state.center.y
}
})
} else{
MyGame.handlers.AudioHandler.handleNewGlobalAudio({
type:'enemy-laser',
center:{
x: data.message.state.center.x,
y: data.message.state.center.y
}
})
}
} | [
"function handleMissileDestroyed(data){\n MyGame.handlers.MissileHandler.destroyMissile(data.message);//pass in only id of missile\n }",
"function shootMissile() {\n playerMissiles.push(new Sprite(playerObj.top - 8, playerObj.left + 34, 3, 10));\n //invoke draw missiles\n drawMissiles();\n }",
"function updateMissile(missile, action) {\n if (action.type === 'STEP') {\n if (missile.get(\"mode\") === 'MOVING') {\n return countDownToMode(updatePosition(missile), 'GONE');\n } else {\n return missile;\n }\n } else if (action.type === 'EXPLODE') {\n if (missile.get(\"mode\") === 'MOVING') {\n return missile.set(\"mode\", 'GONE').set(\"timer\", 50);\n } else {\n return missile;\n }\n }\n throw new Error(\"Unhandled action: \" + action.type);\n}",
"function repeatAnims() {\n missileInterval = setInterval(beginDroppingMissiles, 500)\n}",
"function OnReceiveDamage(){}",
"function dropMissile(animationTime) {\n var columnNumber = randomNumGen(4)\n var $missile = $('<img src=\"img/missile-drop-down-white.png\" ' +\n 'class=\"missile missile-'+ columnNumber +'\">')\n $('#pos-'+columnNumber).prepend($missile)\n $missile.animate({\n top: \"+=550\"\n }, animationTime, \"linear\", function() {\n missileHitsCity($(this), columnNumber)\n }) \n}",
"function emitEnemyMissle(elapsedTime,item){\r\n\t\tenemyShip.getSpecs().fireCounter -=elapsedTime/1000;;\r\n\t\tif(enemyShip.getSpecs().fireCounter <= 0){\r\n\t\t\t\r\n\t\t\tenemyMissleAudio.play(); \r\n\t\t\tenemyMissles.push(item);\r\n\t\t\tenemyShip.getSpecs().fireCounter = .5;\r\n\t\t}\r\n\t}",
"function enemyMissleCollisionDetection(missle,elapsedTime){\r\n\t\tvar xDiff = myShip.getSpecs().center.x - missle.x;\r\n\t\tvar yDiff = myShip.getSpecs().center.y - missle.y;\r\n\t\tvar distance = Math.sqrt((xDiff * xDiff) + (yDiff*yDiff)); \r\n\r\n\t\tif(distance < myShip.getSpecs().radius + missle.radius){\r\n\t\r\n\t\t\tparticleGenerator.createShipExplosions(elapsedTime, myShip.getSpecs().center);\r\n\r\n\t\t\tmissle.collisionWithPlayer = true;\r\n\t\t\tmyShip.getSpecs().hit = true;\r\n\r\n\t\t\tmyShip.getSpecs().center.x = canvas.width+20;\r\n\t\t\tmyShip.getSpecs().center.y = canvas.height+20;\r\n\t\t\tmyShip.getSpecs().reset = true;\r\n\t\t\tplayerShipDestroyedAudio.play();\r\n\t\t\t\r\n\t\t}\r\n\t}",
"function handleAsteroidNew(data){\n for (let i in data.message){\n if (data.message[i] != null){\n handlers.AsteroidHandler.createAsteroid(data.message[i]);\n }\n }\n }",
"handleHitAnimation() {\n push();\n tint(255, 255, 255, this.explosionHit);\n imageMode(CENTER, CENTER);\n image(imgExplosion, player.x, player.y, player.size * 2, player.size * 2);\n pop();\n if (this.explosionHit > 0) {\n this.explosionHit -= 20;\n }\n }",
"function recivedShot(UID){\n //tank have\n if(UID==GameObjs.Player.UID){\n createShot(0,0,GameObjs.Player,GameObjs.Player.shotColor);\n return ;\n }\n for (var i = GameObjs.TANKs.length - 1; i >= 0; i--) {\n if(UID==GameObjs.TANKs[i].UID){\n createShot(0,0,GameObjs.TANKs[i],GameObjs.TANKs[i].shotColor);\n break;\n }\n }\n \n \n}",
"onMessage(fromSprite, cmd, data) {\n }",
"function onPieceChange(data){\r\n //The image is being changed\r\n if(data.image)\r\n pieces[tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant].image.src = data.image;\r\n //The job is being changed\r\n if(data.job)\r\n pieces[tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant].job = data.job;\r\n //Motion is being changed\r\n if(data.motion)\r\n eval(\"pieces[tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant].motion = \" + data.motion);\r\n //Minion was murdered in cold blood, please may we all take a moment of silence\r\n if(data.alive == false){\r\n pieces[tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant].alive = false;\r\n pieces[tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant].xTile = -1;\r\n pieces[tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant].yTile = -1;\r\n tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant = -1;\r\n }\r\n}",
"function drawMissiles() {\n let content = \"\";\n playerMissiles.forEach(missile => {\n content += `<div class=\"missile\" style=\"top: ${missile.top}px; left: ${missile.left}px\"></div>`;\n });\n document.getElementById('missiles').innerHTML = content;\n }",
"function graveCallback (data) {\n\tconsole.log('>Motion at Gravegrabber');\n\tconsole.log(' event: ', data);\n\n\tif (motionActive) {\n\n\t\tdoit('grave_grabber');\n\t\tdoit('scarecrow_sequence','5,eyes_on,5,left');\n\n\t\t// reset the callback for the scarecrow to go back to sleep\n\t\tscarecrowSleepReset();\n\n\t\t// reset the motion callback timeout\n\t\tmotionWakeReset();\n\t}\n}",
"function shootProjectile() {\n\tif (player.energy > 0) {\n\t\tplayerProjectiles.push(generatePlayerProjectile());\n\t\tplayer.energy -= 2;\n\t\tframesSinceLastEnergyUse = 0;\n\t}\n}",
"function handleUFONew(data){\n MyGame.handlers.UFOHandler.handleNewUFO(data.message);//send state info\n }",
"handleExplosion() {\n this.handleHitAnimation();\n this.handleExplodeSelf();\n }",
"function onMavlinkMessage(msg) {\n d(\"onMavlinkMessage(): msg=\" + msg.name);\n\n switch(msg.name) {\n case \"HEARTBEAT\": {\n // Got a heartbeat message\n marklar.marklarTheMarklar();\n break;\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Log file changes to console | function logFileChange(event) {
var fileName = require('path').relative(__dirname, event.path);
console.log('[' + 'WATCH'.green + '] ' + fileName.magenta + ' was ' + event.type + ', running tasks...');
} | [
"function logFileChange(event) {\n\t\tvar fileName = require('path').relative(__dirname, event.path);\n\t\tconsole.log('[' + 'WATCH'.green + '] ' + fileName.magenta + ' was ' + event.type + ', running tasks...');\n\t}",
"function logFile() {\n\tuserInput = userInput.join(' '); // join the array with spaces\n\tvar logEntry = userCommand + ' ' + userInput + '\\n'; // append new command and input into log\n\tfs.appendFile('log.txt', logEntry, function(err) {\n\t\tif (err) {\n\t\t\tconsole.log(err);\n\t\t} else {\n\t\t\tconsole.log('log was updated');\n\t\t}\n\t})\n}",
"function logFileOp(message) {\n events.emit('verbose', ' ' + message);\n}",
"function logCommand() {\n var timeAdded = moment().format(\"dddd, MMMM Do YYYY, h:mm:ss a\")\n var loggedCommand = `${command}\\n${timeAdded}\\n-------------\\n`;\n fs.appendFile(\"log.txt\", loggedCommand, function (err) {\n // If an error was experienced, it log it to console\n if (err) {\n console.log(err);\n }\n // If no error is experienced, it logs in console that the command was successfully added to log.txt\n else {\n console.log(\"\\nCommand Added to log.txt!\\n\");\n }\n });\n}",
"function fileChanged() {\n \"use strict\";\n if (bTrackChanges) {\n if (!bFileChanged) {\n bFileChanged = true;\n highlightChanged();\n }\n }\n}",
"function logFileOutput(dataToLog) {\n\n file.appendFile(\"./log.txt\", dataToLog, function (err) {\n\n if (err) {\n console.log(err);\n }\n\n });\n\n}",
"start() {\n debug(`Tail: Waiting for log file to appear in ${this.logFile}`)\n this.waitForLogFile()\n }",
"function logtxt(data) {\n fs.appendFile(\"log.txt\", data, function(error) {\n if (error) {\n console.log(error);\n }\n });\n}",
"function readFileForChanges() {\n const newlyReadLastModifiedDateInMillies = new Date(fs.statSync(filePath)['mtime']).getTime();\n //proceed only if file has been modified\n if(lastModifiedDateInMillis < newlyReadLastModifiedDateInMillies){\n let linesToSendBack = [];\n let linesInFile = fs.readFileSync(filePath).toString().split('\\n');\n for(var i = linesInFile.length - 1; i > lastReadLineNumber - 1; i--){\n linesToSendBack.push(linesInFile[i]);\n }\n\n //set values in variables for later use\n lastModifiedDateInMillis = newlyReadLastModifiedDateInMillies;\n lastReadLineNumber = linesInFile.length;\n\n io.emit('logUpdate', { lines : linesToSendBack.reverse() });\n }\n}",
"function logAndWrite(entry){\n console.log(entry);\n writeHistoryEntry(entry);\n}",
"function writeIt() {\n if (index < LOG.length) {\n fs.appendFile('log.txt', LOG[index++] + \"\\n\", writeIt);\n }\n }",
"function notifyLiveServer(changedFile) {\n for (const cli of httpWatches) {\n if (cli === undefined) continue;\n cli.write(\n 'data: ' + path.relative(cfg.outDistRootDir, changedFile) + '\\n\\n');\n }\n}",
"watch (fileChanged) {\n setTimeout(() => {\n fileChanged({\n change: \"modified\",\n path: \"file2.txt\",\n source: this.file2Source\n });\n }, 100);\n }",
"function logMsg(msg){\r\n var moment = require('moment');\r\n moment().format();\r\n var now = moment().format('YYYY-MM-DD HH:mm:ss');\r\n fs.appendFile(logFile, now + ' ' + msg + '\\r\\n', function (error) {\r\n if (error) throw error;\r\n });\r\n}",
"setOutputFile(filePath)\r\n { \r\n const vscode = require('vscode');\r\n this.filePath=filePath;\r\n vscode.debug.activeDebugConsole.appendLine(\"OUTPUT FILE PATH \" + this.filePath);\r\n }",
"function _log_change()\n\t\t{\n\t\t\tvar clone = data.valueCloned;\n\t\t\tvar timestamp = EZ.format.time('@ ms');\n\t\t\t//\ttimestamp = EZ.format.dateTime(data.timestamp,'@ ms');\n\n\t\t\tlogInfo.iconTitle = 'full compare via winmerge with last displayed value';\n\t\t\tlogInfo.summaryClass = 'summary';\n\t\t\tvar priorHeadTags = [this.getTag('dataFileLogHeading')].concat(logInfo.logTag.EZ(['summary'], null));\n\t\t\tEZ.removeClass(priorHeadTags.remove(), ['highlight', 'roundLess']);\n\n\t\t\tlogInfo.icon.class = 'unhide';\n\t\t\tvar count = data.compare.valueHistory.length;\n\t\t\tvar notable = count;\n\t\t\tvar equalsNote = '';\n\n\t\t\tvalue = value || data.value;\t\t\t\t\t\t//1st compare to last logged value\n\t\t\tvar priorValue = data.compare.valueHistory[data.compare.valueHistory.length-1];\n\n\t\t\tvar formattedLog = EZ.equals(priorValue, value, options.log.change.eqOpts)\n\t\t\t\t\t\t\t|| EZ.equals.formattedLog;\n\n\t\t\tif (formattedLog === true)\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t//bail if same as last logged value\n\t\t\t\tif (action != 'save')\t\t\t\t\t\t\t//...and not calld from save\n\t\t\t\t\treturn data.compare.skips++;\n\n\t\t\t\tequalsNote = data.compare.valueHistoryEquals[notable-1];\n\t\t\t\tif (equalsNote.includes('equals'))\n\t\t\t\t\tnotable = '';\n\t\t\t\telse\n\t\t\t\t\tequalsNote = 'equals '\n\n\t\t\t\tformattedLog = data.formattedLog || this.isValueChanged()\n\t\t\t\tif (formattedLog === true)\t\t\t\t\t\t//if samed as last saved value...\n\t\t\t\t{\n\t\t\t\t\ttimestamp = EZ.format.dateTime(data.timestamp_saved || data.timestamp_loaded, '@');\n\t\t\t\t\tlogInfo.icon.class = 'invisible';\n\t\t\t\t\tformattedLog = ['no changes from file saved ' + timestamp];\n\t\t\t\t\t//logInfo.detailHead = 'no TRACKED changed from file saved ' + timestamp;\n\t\t\t\t\tlogInfo.closeDetails = false;\n\t\t\t\t}\n\t\t\t\telse \t\t\t\t\t\t\t\t\t\t\t//otherwise show diff from last saved value\n\t\t\t\t\tlogInfo.iconTitle = 'full compare via with last SAVED value winmerge';\n\t\t\t}\n\t\t\telse\t\t\t\t\t\t\t\t\t\t\t\t//check if equal to any history value\n\t\t\t{\n\t\t\t\tdata.compare.valueHistory.slice(0,-1).every(function(value, idx)\n\t\t\t\t{\n\t\t\t\t\tif (!EZ.equals(value, data.value, options.log.change.eqOpts))\n\t\t\t\t\t\treturn true;\n\n\t\t\t\t\tequalsNote = 'equals '\n\t\t\t\t\tnotable = (idx === 0) ? data.compare.valueHistoryTitle[0] : idx;\n\n\t\t\t\t\tlogInfo.summaryClass += ' highlight roundLess';\n\t\t\t\t\tEZ.addClass(priorHeadTags[notable], logInfo.summaryClass);\n\t\t\t\t});\n\t\t\t}\n\t\t\tcount = count.pad(2);\n\t\t\tif (data.compare.skips)\n\t\t\t\tcount += '/' + data.compare.skips.pad(-2);\n\t\t\tthis.setTag('updatesCount', count);\n\t\t\tif (data.compare.skips >= 99)\n\t\t\t\tdata.compare.skips = 0;\n\n\t\t\tnotable = equalsNote + (notable ? notable.wrap('()'): '');\n\n\t\t\tdata.compare.valueHistoryEquals.push(notable);\n\t\t\tdata.compare.valueHistoryTitle.push(timestamp);\n\t\t\tdata.compare.valueHistory.push(clone || __.cloneValue(value));\n\n\t\t\tlogInfo.notable = notable;\n\t\t\tlogInfo.detailsHead = formattedLog.shift(),\n\t\t\tlogInfo.detailsBody = formattedLog.join('\\n')\n\n\t\t\tlogInfo.timestamp = timestamp;\n\n\t\t\tvar args = data.key.wrap(\"'\") + ',this,' + count+''\t//compare args: 'key', this, historyIdx\n\t\t\tlogInfo.icon.onClick = \"window.EZ.dataFile.compare(\" + args + \")\";\n\n\t\t\tEZ.log.addDetails(logInfo);\n\t\t}",
"function change_process() {\n if (fs.existsSync(logs_dir)) {\n process.chdir(`./logs`);\n } \n}",
"function logActivity(summary) {\n\n // concatenate data into var\n log = '\\n\\nAction chosen: ' + action + ', query: ' + queryLog + '\\n' + summary;\n\n // append log data to log.txt\n fs.appendFile('log.txt', log, function () {});\n}",
"function create_log_files() { \n if (path.basename(process.cwd()) == 'logs') {\n let file_name;\n console.log(`All files in /${path.basename(process.cwd())}`);\n for (let i = 0; i < 10; i++) {\n file_name = `textfile${i + 1}.txt`;\n fs.writeFile(file_name, `This is the text for \"${file_name}\"!`, function (error) {\n if (error) {\n console.log('error', error);\n }\n });\n console.log(file_name);\n }\n console.log(\"10 text files have been created!\"); \n } \n}",
"function createNewLogFile() {\n var basePath = (global.TYPE.int === global.TYPE_LIST.CLIENT.int ? \"./\" : path.join(__dirname, \"..\")); //Get base path\n if (fs.existsSync(path.join(basePath, \"Timbreuse.10.log\"))) //If log 10 exists, delete\n fs.unlinkSync(path.join(basePath, \"Timbreuse.10.log\"));\n for (var i = 9; i > 0; i--)\n if (fs.existsSync(path.join(basePath, \"Timbreuse.\" + i + \".log\"))) //Then move log n to log n+1\n fs.renameSync(path.join(basePath, \"Timbreuse.\" + i + \".log\"), path.join(basePath, \"Timbreuse.\" + (i + 1) + \".log\"));\n if (fs.existsSync(path.join(basePath, \"Timbreuse.log\"))) //If log exists, move it to log 1\n fs.renameSync(path.join(basePath, \"Timbreuse.log\"), path.join(basePath, \"Timbreuse.1.log\"));\n global.logFile = fs.createWriteStream(path.join(basePath, \"Timbreuse.log\"), { //Then create write stream to log file\n flags: 'w'\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a file in specified (bucket, key) | function getFileS3(filename, key, bucket, callback) {
var params = {Bucket: bucket, Key: key};
var file = require('fs').createWriteStream(filename);
s3.getObject(params).createReadStream().on("finish", callback).pipe(file);
} | [
"function getS3(callback, key, bucket, callback) {\n var params = {Bucket: bucket, Key: key};\n s3.getObject(params, callback).send();\n}",
"retrieve(key) {\n // const strKey = typeof key === 'number' ? key.toString() : key;\n const index = getIndexBelowMax(key, this.limit);\n const bucket = this.storage;\n let value;\n\n if (bucket.get(index) !== undefined) { // Verify there's a bucket at index\n bucket.get(index).forEach((kvPair) => { // Cycle through k/v pairs\n if (kvPair[0] === key) { // If pair has the desired key\n value = kvPair[1]; // Save the key's associated value\n return; // Exit the anonymous function\n }\n });\n return value; // Return the saved value\n }\n }",
"async getFile(key) {\n const self = this;\n await U.waitUntil(() => self.made);\n return Path.join(self.directory, Value.encodeValue(key).toString('hex'));\n }",
"function get_blob(topic, options, label, key) {\n return _get_blob(topic, options, label, key, \"blob\");\n}",
"getItemsInBucket(arg = {bucket: null, callback: (bucketItem)=>{}}){\n if(arg.bucket != null && arg.bucket.contents != null){\n let contents = arg.bucket.contents\n if(!Array.isArray(contents)){\n contents = [contents];\n }\n for(let i = 0; i < contents.length; i++){\n let url = `${AWS_BASE_URL}${arg.bucket.name}/${contents[i].Key}`;\n this.makeJSONFetchRequest({url:url, callback:(jsonResponse)=>{\n if(typeof arg.callback === 'function'){\n let data = {\n name: this.jsonFileNameToTitle(contents[i].Key),\n data: jsonResponse\n }\n arg.callback(data);\n }\n }});\n }\n }\n }",
"search(bucket, key, value) {\n const query = tagToQuery(bucket, key, value);\n // console.log(\"search: \" + query);\n // TODO: we will have to paginate when there are more than enough to fit on one page....\n return this.client.txSearch({query, per_page: 100}).catch(err => console.log(err));\n }",
"async readFileIV(path){\n let self = this;\n const isValid = await this.doesS3PathExists(path);\n if(isValid){\n let contents = await self.config.s3.getObject({ Bucket: self.config.bucketName, Key: path, Range: 'bytes=0-34' }).promise().then(data => {return data;}).catch(error => { Logger.log(error); return null; });\n\n if(!contents){ return null; }\n if(!contents.Body){ return null; }\n if(contents.Body.length === 0){ return null; }\n\n let readable = await contents.Body.toString();\n let regex = /\\(([^)]+)\\)/;\n let match = readable.match(regex);\n\n if(!match){ return null; }\n if(match.length < 1){ return null; }\n if(match[1].length < 32){ return null; } // 32 = len of hex, +2 for '(' hex ')'. < 32 for match\n\n return match[1];\n }\n\n return null;\n }",
"function putFileS3(filename, key, bucket, callback) {\n var body = fs.createReadStream(filename);\n putS3(body, key, bucket, callback);\n}",
"function fetchGcsObject(bucket, objectName, responseHandler) {\n console.log('Fetching', bucket, '#', objectName);\n if (!isServingAppFromMachine()) {\n gapi.client.storage.objects.get({\n 'bucket': bucket,\n 'object': objectName,\n 'alt': 'media'\n }).then(function(response) {\n responseHandler(response.body);\n }, function(reason) {\n console.log(reason);\n alert('Could not fetch ', objectName, reason.body);\n });\n } else {\n window.fetch('data/' + bucket + '/' + objectName).then(function(response) {\n if (response.ok) {\n return response.text();\n } else {\n console.log(response.statusText);\n alert('Could not fetch \"' + objectName + '\"\\nReason: ' + response.statusText);\n }\n }).then(function(text) {\n responseHandler(text);\n });\n }\n}",
"function getPublicUrl (bucketName,filename) {\n return `https://storage.googleapis.com/${bucketName}/${filename}`;\n }",
"async searchS3Files(dirPath, query, forceRequestToProvider = false){\n try{\n var files = [];\n if(this.database_handler !== null && forceRequestToProvider === false){\n // At large scale, making a request to s3 every time might affect the cost.\n // If database is connected, search in the database.\n const models = await this.database_handler.getAllModels({ folder: dirPath, userId: this.config.userId, });\n if(Array.isArray(models)){ files = models; }\n }else{\n // If database is not connected, make a request to s3.\n files = await this.getAllFilesOfS3Directory(dirPath, forceRequestToProvider);\n }\n\n let filteredFiles = [];\n const querySplit = query ? query.toLowerCase().split(\":\") : [null, null];\n const queryType = querySplit[0];\n const queryParam = querySplit[1];\n\n if(query !== null && typeof query === \"string\"){\n if(queryType === \"extension\"){\n filteredFiles = files.filter(file => {\n return path.extname(file.path).replace(\".\", \"\").toLowerCase() == queryParam;\n });\n }else{\n if(queryType === \"name\"){\n filteredFiles = files.filter(file => {\n return path.basename(file.path).replace(path.extname(file.path), \"\").toLowerCase() == queryParam;\n });\n }else{\n if(queryType === \"name_contains\"){\n filteredFiles = files.filter(file => {\n return path.basename(file.path).replace(path.extname(file.path), \"\").toLowerCase().includes(queryParam);\n });\n }else{ filteredFiles = files; }\n }\n }\n }else{ filteredFiles = files; }\n\n let finalFiles = [];\n for(let file of filteredFiles){\n const fileObj = await this.getS3File(file.path); // Get data for each s3 file.\n if(fileObj){\n finalFiles.push(fileObj);\n }\n }\n\n return finalFiles;\n }catch(error){ Logger.log(error); }\n\n return [];\n }",
"async function downloadConfigFile(projectId, bucket_name, repo_name, filename) {\n const storage = new Storage({\n projectId: projectId\n });\n\n const bucket = storage.bucket(bucket_name);\n const file = await bucket.file(`${repo_name}/${filename}`).download();\n return yaml.safeLoad(file);\n}",
"function get_signed_request(file, ifLast){\n\t\tvar username;\n\t\tif(document.getElementById('username') != null){\n\t\t\tusername = document.getElementById('username').value;\n\t\t}\n\t\telse{\n\t\t\tusername = 'username';\n\t\t}\n\t\t\n\t var xhr = new XMLHttpRequest();\n\t xhr.open(\"GET\", \"/sign_s3?file_name=\"+file.name+\"&file_type=\"+file.type+\"&username=\"+username);\n\t xhr.onreadystatechange = function(){\n\t if(xhr.readyState === 4){\n\t if(xhr.status === 200){\n\t var response = JSON.parse(xhr.responseText);\n\t upload_file(file, response.signed_request, response.url, ifLast);\n\t }\n\t else{\n\t alert(\"Could not get signed URL.\");\n\t }\n\t }\n\t };\n\t xhr.send();\n\t}",
"static async getAssetBuffer(ctx, assetKey) {\n\t\t//Fetch asset details with given key\n\t\treturn ctx.stub\n\t\t\t\t.getState(assetKey)\n\t\t\t\t.catch(err => console.log(err));\n\t}",
"bucketFor(name) {\n return hashBucket(this.hashFor(name), this.size)\n }",
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('fileasset', 'get', kparams);\n\t}",
"static async getFirstAssetFromKeyPrefix(ctx, assetType, assetKeyPrefix) {\n\t\t//Get iterator of assets based on asset type partial composite key provided\n\t\tlet assetIterator = await PharmanetHelper.getAssetIterator(ctx,pharmaNamespaces[assetType],assetKeyPrefix);\n\t\tlet asset = await assetIterator.next();\n\n\t\t//If there are no assets for given key then iterator will have no results\n\t\t//Thus accessing next() result from iterator will give only done status\n\t\t//If next() returns value then at least one asset is existing with given partial key prefix\n\t\tlet assetValue = asset.value;\n\t\t\n\t\t//Close the iterator if matching assets are existing, if not then iterator is already closed by this point\n\t\tif(assetValue){\n\t\t\tawait assetIterator.close();\n\t\t}\n\n\t\treturn assetValue;\n\t}",
"function deleteImage(fileKey){\n const params = {\n Bucket: bucketName,\n Key: fileKey\n };\n return s3.deleteObject(params);\n}",
"function getAsset(axios$$1, token) {\n return restAuthGet(axios$$1, 'assets/' + encodeURIComponent(token));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To disable logging on stdout, should be enabled in production. Log and debug will only write to the logfile. | function disableStdout() {
isStdoutDisabled = true;
} | [
"function stopLogging() {\n chrome.send('setLoggingEnabled', [false]);\n $('logs').innerHTML = '';\n $('start-logging').hidden = false;\n $('stop-logging').hidden = true;\n}",
"function debugLog() {\n if (_debug) {\n console.log.apply(console, arguments);\n }\n }",
"function configureConsoleLogging () {\n var isEnabled = ('true' === process.env.LOGGING_CONSOLE_ACTIVE) // mandatory envVar\n , expressJsLog = getExpressJsLog()\n , clientAppLog = getClientAppLog();\n\n // remove default console, and if console logging enabled, add new console with our custom settings\n // headless testing doesn't have console instance attached, try-catch to prevent failure\n try { winston.remove(winston.transports.Console); } catch(err) {}\n try { expressJsLog.remove(winston.transports.Console); } catch(err) {}\n try { clientAppLog.remove(winston.transports.Console); } catch(err) {}\n\n if (isEnabled) {\n winston.add(winston.transports.Console, { level: serverAppLogTreshold, timestamp: true });\n expressJsLog.add(winston.transports.Console, { level: serverAppLogTreshold, timestamp: true });\n clientAppLog.add(winston.transports.Console, { level: clientAppLogTreshold, timestamp: true });\n }\n}",
"function setupConsoleLogging() {\n (new goog.debug.Console).setCapturing(true);\n}",
"function isLogEnabled () {\n return flags.DEBUG || flags.LOG_ENABLED\n }",
"function debugLog(str) { if ( DEBUG && window.console ) console.log(str); }",
"noisy( msg ) {\n const self = this;\n if ( !self.useNoisyLogging ) { return; }\n Y.log( `${self.pid()} ${msg}`, 'info', NAME );\n }",
"function mute() {\n console.log = function(){};\n}",
"setDefaultLogger() {\n const defaultLevel = Meteor.isProduction ? 'error' : 'trace';\n const defaultLogger = loglevel.createLogger('', defaultLevel);\n\n this.setLogger(defaultLogger);\n }",
"enableLog() {\n this.enabled = logCfg.enable;\n }",
"static _error() {\n if ( 'production' !== process.env.NODE_ENV || 'true' === config.enableLogging ) {\n console.error.apply( console, arguments )\n }\n }",
"function warn (msg, force) {\n if (force || isLogEnabled()) console.warn(`[egolatron] ${msg}`)\n }",
"function silenceFailureLogging() {\n if (goog.global['G_testRunner']) {\n stubs.set(goog.global['G_testRunner'], 'logTestFailure', goog.nullFunction);\n }\n}",
"function resetLogger() {\n globalLogManager = new DefaultLogManager();\n globalLogLevel = models_1.LogLevel.NOTSET;\n}",
"function setLogger(argv) {\n logger.level = argv.debug ? 'debug' : argv.verbose ? 'verbose' : 'info';\n}",
"function f_RADOME_log(smthg_to_log){\n\tif (go_RADOME_Conf.getConsoleLog()===true) \n\t{\n\t\tconsole.log(smthg_to_log);\n\t}\n}",
"startLogging() {\n this.isLogging = true;\n this.debounceTime$\n .pipe(takeUntil(this.stopLogging$), switchMap((debounceTime) => this.periodicalLogging(debounceTime)))\n .subscribe(() => this.onPostMessages());\n this.postLogs$\n .pipe(takeUntil(this.stopLogging$), switchMap(() => this.postMessages()))\n .subscribe(() => this.onPostMessages());\n this.setLoggingDebounceTime(this.config.debounceTime);\n }",
"function consoleOut(msg) {\n console.log(msg);\n console_log += msg + \"\\n\";\n}",
"clearLogs() {\n Instabug.clearLogs();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enable a previously disabled rule for this node. | enableRule(ruleId) {
this.disabledRules.delete(ruleId);
} | [
"enable() {\n const eqs = this.equations;\n for (let i = 0; i < eqs.length; i++) {\n eqs[i].enabled = true;\n }\n }",
"function setEnabled(){\n\t'use strict';\n\tif($('input:radio[name=cats]:checked').val()===\"opt1\"){\n\t\t$(\"#category\").removeAttr(\"disabled\");\n\t\t$(\"#oldlabel\").css('color', '#000000');\n\n\t\t$(\"#category1\").attr(\"disabled\",\"disabled\");\n\t\t$(\"#newlabel\").css('color', '#808080');\n\n\t}else{\n\t\t$(\"#category1\").removeAttr(\"disabled\");\n\t\t$(\"#newlabel\").css('color', '#000000');\n\n\t\t\n\t\t$(\"#category\").attr(\"disabled\",\"disabled\");\n\t\t$(\"#oldlabel\").css('color', '#808080');\n\n\t}\n}",
"visitEnable_constraint(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"onDisabled() {\n this.updateInvalid();\n }",
"enable() {\n this._enabled = true;\n this._model = new SelectionModel(this._bufferService);\n }",
"function toggleWorkflowEmailRuleHandler(jsonURL, disable) {\n\treturn function() {\n\t\t\n\t\t$this = $(this);\n\t\t$this.html(\"confirm \"+(disable ? \"disable\" : \"enable\")+\"?\");\n\n\t\t\n\t\t$this.click(function() {\n\t\t\tvar backupHTML = $this.html();\n\t\t\t$this.html(\"\");\t\n\t\t\t$this.parents(\"tr\").addClass(\"waiting\");\n\n\t\t\tsuccessCallback = function() {\n\t\t\t\t$this.parents(\"tr\").removeClass(\"waiting\");\n\t\t\t\t$this.parents(\"td\").html((disable ? \"<a href=\\\"#\\\" class=\\\"enableRule\\\" data-id=\\\"\"+$this.attr('data-id')+\"\\\"><em class=\\\"icon-play\\\"></em></a>\" : \"<a href=\\\"#\\\" class=\\\"disableRule\\\" data-id=\\\"\"+$this.attr('data-id')+\"\\\"><em class=\\\"icon-pause\\\"></em></a>\"));\n\t\t\t}\n\n\t\t\tvar failureCallback = function(message) {\n\t\t\t\tif(backupHTML.length > 0) {\n\t\t\t\t\t$this.parents(\"tr\").removeClass(\"waiting\");\n\t\t\t\t\t$this.parents(\"td\").html((disable ? \"<a href=\\\"#\\\" class=\\\"disableRule\\\" data-id=\\\"\"+$this.attr('data-id')+\"\\\"><em class=\\\"icon-pause\\\"></em></a>\" : \"<a href=\\\"#\\\" class=\\\"enableRule\\\" data-id=\\\"\"+$this.attr('data-id')+\"\\\"><em class=\\\"icon-play\\\"></em></a>\"));\n\t\t\t\t\tdisplayAlert(\"emailWorkflowRule-toggle\",\"Unable to toggle email workflow rule: \", message);\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tjQuery.ajax({\n\t\t\t\turl : jsonURL,\n\t\t\t\tdata : {\n\t\t\t\t\truleID: $this.attr('data-id')\n\t\t\t\t},\n\t\t\t\tdataType : 'json',\n\t\t\t\ttype : 'POST',\n\t\t\t\tsuccess : function(data) {\n\n\t\t\t\t\tif (data.success) {\n\t\t\t\t\t\tsuccessCallback(data);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfailureCallback(data.message)\n\t\t\t\t\t}\n\n\t\t\t\t},\n\t\t\t\terror : function(e) {\n\t\t\t\t\tconsole.log(e);\n\t\t\t\t\tfailureCallback(\"Unable to communicate with the server.\");\n\t\t\t\t}\n\t\t\t});\n\n\t\t});\n\t\t\n\n\t\treturn false;\n\t}\n}",
"visitEnable_disable_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"resetRules() {\n this.ruleContextAgent.removeAllListeners();\n this.ruleManager.resetRules();\n }",
"enable() {\n BluetoothSerial.enable()\n .then(res => {\n this.initializeBluetooth();\n BluetoothActions.setIsEnabled(true);\n })\n .catch(err => console.log(err.message));\n }",
"enableLog() {\n this.enabled = logCfg.enable;\n }",
"function OnClickRowEnable(enabled)\r\n{\r\n var rows = iDoc.getElementById(\"dataTable\").rows;\r\n\r\n for (var i = 1; i < rows.length; i++)\r\n {\r\n if (rows[i].getAttribute(\"selected\") == 1)\r\n {\r\n if (enabled == true) StyleRemoveAttributes(rows[i], \"color\"); else StyleSetAttributes(rows[i], \"color: gray;\");\r\n rows[i].setAttribute(\"enabled\", (enabled == true) ? 1 : 0);\r\n changesMade = true;\r\n }\r\n }\r\n}",
"_toggleRecognizer(name, enabled) {\n const {\n manager\n } = this;\n\n if (!manager) {\n return;\n }\n\n const recognizer = manager.get(name); // @ts-ignore\n\n if (recognizer && recognizer.options.enable !== enabled) {\n recognizer.set({\n enable: enabled\n });\n const fallbackRecognizers = _constants__WEBPACK_IMPORTED_MODULE_6__[\"RECOGNIZER_FALLBACK_MAP\"][name];\n\n if (fallbackRecognizers && !this.options.recognizers) {\n // Set default require failures\n // http://hammerjs.github.io/require-failure/\n fallbackRecognizers.forEach(otherName => {\n const otherRecognizer = manager.get(otherName);\n\n if (enabled) {\n // Wait for this recognizer to fail\n otherRecognizer.requireFailure(name);\n /**\n * This seems to be a bug in hammerjs:\n * requireFailure() adds both ways\n * dropRequireFailure() only drops one way\n * https://github.com/hammerjs/hammer.js/blob/master/src/recognizerjs/\n recognizer-constructor.js#L136\n */\n\n recognizer.dropRequireFailure(otherName);\n } else {\n // Do not wait for this recognizer to fail\n otherRecognizer.dropRequireFailure(name);\n }\n });\n }\n }\n\n this.wheelInput.enableEventType(name, enabled);\n this.moveInput.enableEventType(name, enabled);\n this.keyInput.enableEventType(name, enabled);\n this.contextmenuInput.enableEventType(name, enabled);\n }",
"function ruleLine(r) {\n return util.format('%s %s %s', r.uuid,\n r.enabled ? 'true ' : 'false ', r.rule);\n}",
"function enablePowers () {\n var enable = document.querySelectorAll(\".disabled\")\n for (var i = 0; i < enable.length; i++ ) {\n enable[i].classList.replace(\"disabled\", \"enabled\") \n }\n}",
"function toggleStylesheet(stylesheet, toggle) {\n stylesheet.disabled = toggle;\n stylesheet.disabled = toggle; // force the browser to action right now\n}",
"set disabled(value) {\n const isDisabled = Boolean(value);\n if (this._disabled == isDisabled)\n return;\n this._disabled = isDisabled;\n this._safelySetAttribute('disabled', isDisabled);\n this.setAttribute('aria-disabled', isDisabled);\n // The `tabindex` attribute does not provide a way to fully remove\n // focusability from an element.\n // Elements with `tabindex=-1` can still be focused with\n // a mouse or by calling `focus()`.\n // To make sure an element is disabled and not focusable, remove the\n // `tabindex` attribute.\n if (isDisabled) {\n this.removeAttribute('tabindex');\n // If the focus is currently on this element, unfocus it by\n // calling the `HTMLElement.blur()` method.\n if (document.activeElement === this)\n this.blur();\n } else {\n this.setAttribute('tabindex', '0');\n }\n }",
"async function setRules(){\n const data = {\n add: rules\n }\n const response = await needle('post', rulesURL, data, {\n headers:{\n 'content-type': 'application/json',\n Authorization: `Bearer ${process.env.TWITTER_BEARER_TOKEN}`\n }\n });\n return response.body\n}",
"requestEnable() {\n BluetoothSerial.requestEnable()\n .then(res => {\n BluetoothActions.setIsEnabled(true);\n })\n .catch(err => console.log(err.message));\n }",
"enable(emitterID) {\n // sanity check\n if (!this.check(emitterID)) {\n return;\n }\n let pkg = this.emitters.get(emitterID);\n if (pkg.emitter.emit) {\n // console.warn('Emitter \"' + emitterID + '\" is already enabled');\n return;\n }\n pkg.emitter.emit = true;\n }",
"function toggleRules() {\n self.outerWrapper.toggleClass('expanded-widget-rules');\n self.toggleRulesControl.toggleClass('expanded');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prevent element from connecting when it's upgrade disabled. This prevents user code in `attached` from being called. | connectedCallback() {
if (!this.__isUpgradeDisabled) {
super.connectedCallback();
}
} | [
"_onDetachEnabled( event) {\n this.detached = true;\n if( event.cancellable) { event.stopPropagation(); }\n }",
"onDisabled() {\n this.updateInvalid();\n }",
"function checkElementNotDisabled(element) {\r\n if (element.disabled) {\r\n throw {statusCode: 12, value: {message: \"Cannot operate on disabled element\"}};\r\n }\r\n}",
"function ignoreMouseEvents() {\n if ( $webSiteContainer==null ) return;\n\n $webSiteContainer.css(\"pointer-events\", \"none\");\n }",
"disablePlugin() {\n this.settings = {};\n this.hiddenColumns = [];\n this.lastSelectedColumn = -1;\n\n this.hot.render();\n super.disablePlugin();\n this.resetCellsMeta();\n }",
"function disableOtherElement() {\n //Back, home page, learn and speaker icons are disabled\n document.getElementsByClassName('backContainer')[0].setAttribute('disabled',\n 'true');\n document.getElementsByClassName('homePageContainer')[0].setAttribute(\n 'disabled','true');\n document.getElementsByClassName('learnContainer')[0].setAttribute('disabled',\n 'true');\n document.getElementById('speaker').setAttribute('disabled','true');\n\n //Decrease the opacity of header elements\n document.getElementsByClassName('levelHeader')[0].style.opacity = 0.5;\n var images = document.getElementsByClassName(\n 'levelHeader')[0].getElementsByTagName('img');\n\n //Also remove the pointer for header icons\n for(var i=0;i<images.length;i++) {\n images[i].style.cursor = 'default';\n }\n\n //Deacrease opacity for all elements\n document.getElementsByClassName('leftPanelContainer')[0].style.opacity = 0.5;\n document.getElementsByClassName('questionElement')[0].style.opacity = 0.5;\n document.getElementById('answerInputElement').setAttribute('disabled','true');\n document.getElementById('item_'+currentItem.itemId).setAttribute('draggable',\n 'false');\n}",
"wakeUp () {\n this.setProperty('isSleeping', false)\n }",
"bailOutActivate() {\n messaging.peerSocket.send({\n type: \"event\",\n event: \"bailout\"\n });\n }",
"function RemoveUpgrade(){\n\tplayer.upgraded = false;\n\tplayer.sprite =Sprite(currentActivePlayer);\n}",
"disableInteractions() {\n this.setState({\n disableGetLink: true,\n disableNodeRemove: true,\n disableAddMarker: true,\n disableReset: true,\n disableDragMarker: true,\n disableNewSeq: true,\n disableLinkRemove: true\n });\n this.forceUpdate();\n }",
"is_blocker() {\n return false;\n }",
"function adBlockNotDetected() {\n }",
"function makeInvisible(element) {\n\telement.className = \"invisible\";\n}",
"set disabled(value) {\n const isDisabled = Boolean(value);\n if (this._disabled == isDisabled)\n return;\n this._disabled = isDisabled;\n this._safelySetAttribute('disabled', isDisabled);\n this.setAttribute('aria-disabled', isDisabled);\n // The `tabindex` attribute does not provide a way to fully remove\n // focusability from an element.\n // Elements with `tabindex=-1` can still be focused with\n // a mouse or by calling `focus()`.\n // To make sure an element is disabled and not focusable, remove the\n // `tabindex` attribute.\n if (isDisabled) {\n this.removeAttribute('tabindex');\n // If the focus is currently on this element, unfocus it by\n // calling the `HTMLElement.blur()` method.\n if (document.activeElement === this)\n this.blur();\n } else {\n this.setAttribute('tabindex', '0');\n }\n }",
"function storeOriginalDisabledProperty(element) {\n //capture original disabled property value\n if (element.data('original-disabled') === undefined) {\n element.data(\"original-disabled\", element.prop(\"disabled\"));\n }\n}",
"function detachPlayer() {\n //console.log('detachPlayer');\n playerAttached = false;\n // this is an internal player method to add class to an element\n rmp.fw.addClass(rmpContainer, 'rmp-detach');\n rmp.setPlayerSize(detachedWidth, detachedHeight);\n }",
"function disableClickOnCard () {\n\topenCardList.forEach(function (card) {\n\t\tcard.off('click');\n\t});\n}",
"function attachPlayer() {\n //console.log('attachPlayer');\n playerAttached = true;\n // this is an internal player method to remove class to an element\n rmp.fw.removeClass(rmpContainer, 'rmp-detach');\n rmp.setPlayerSize(attachedlWidth, attachedHeight);\n }",
"SetExcludeFromAnyPlatform() {}",
"function stopAttLink() {\n require(['io.ox/core/extPatterns/links'], function (links) {\n new links.Action('io.ox/mail/compose/attachment/shareAttachmentsEnable', {\n id: 'stop',\n index: 1,\n requires: function (e) {\n try {\n if (e.baton.view.model.get('encrypt')) { // Do not offer shareAttachments if encrypted\n console.log('stopping');\n e.stopPropagation();\n return false;\n }\n } catch (f) {\n console.log(f);\n }\n return false;\n }\n });\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: doLMSInitialize() Inputs: None Return: CMIBoolean true if the initialization was successful, or CMIBoolean false if the initialization failed. Description: Initialize communication with LMS by calling the LMSInitialize function which will be implemented by the LMS. | function doLMSInitialize()
{
var api = getAPIHandle();
if (api == null)
{
messageAlert("Unable to locate the LMS's API Implementation.\nLMSInitialize was not successful.");
return "false";
}
var result = api.LMSInitialize("");
if (result.toString() != "true")
{
var err = ErrorHandler();
}
return result.toString();
} | [
"function LMSInitialize() \n{\n\tvar strResult = strCMIFalse\n\tif (objAPI != null){\n\t\tstrResult = objAPI.LMSInitialize(strEmptyString)\n\t\tif(strResult == strCMITrue){\n\t\t\treturn true;\n\t\t}\n\t\telse{\n\t\t\thandleSCORMError();\n\t\t\treturn false;\n\t\t}\n\t}\n\telse{\n\t\thandleSCORMError();\n\t\treturn false;\n\t}\n}",
"function LMSIsInitialized()\n{\n // there is no direct method for determining if the LMS API is initialized\n // for example an LMSIsInitialized function defined on the API so we'll try\n // a simple LMSGetValue and trap for the LMS Not Initialized Error\n\n var api = getAPIHandle();\n if (api == null)\n {\n messageAlert(\"Unable to locate the LMS's API Implementation.\\nLMSIsInitialized() failed.\");\n return false;\n }\n else\n {\n var value = api.LMSGetValue(\"cmi.core.student_name\");\n var errCode = api.LMSGetLastError().toString();\n if (errCode == _NotInitialized)\n {\n return false;\n }\n else\n {\n return true;\n }\n }\n}",
"function doLMSFinish()\n{\n // ignore all calls except the first one\n if( afterLmsFinish )\n\t return \"true\";\n \n \n var api = getAPIHandle();\n if (api == null)\n {\n messageAlert(\"Unable to locate the LMS's API Implementation.\\nLMSFinish was not successful.\");\n return \"false\";\n }\n else\n {\n\t // set time/duration signal\n\t computeTime();\t\n\n\t // call the LMSFinish function that should be implemented by the API\n var result = api.LMSFinish(\"\");\n if (result.toString() != \"true\")\n {\n var err = ErrorHandler();\n }\n\t \n\t // block further calls for LMSFinish\n\t else\n\t\tafterLmsFinish = true;\n\n }\n\n return result.toString();\n}",
"function LMSFinish()\n{\n\tvar strResult = strCMIFalse\n\tif (objAPI != null){\n\t\tstrResult = objAPI.LMSFinish(strEmptyString)\n\t\tif(strResult == strCMITrue){\n\t\t\treturn true;\n\t\t}\n\t\telse{\n\t\t\thandleSCORMError();\n\t\t\treturn false;\n\t\t}\n\t}\n\telse{\n\t\thandleSCORMError();\n\t\treturn false;\n\t}\n}",
"function initSCO() {\n lmsConnected = scorm.init();\n}",
"function soundInit() {\r\n\t\t_soundInitialized = true;\r\n\t\tsoundManager.setup({\r\n\t\t\turl: '.',\r\n\t\t\tdebugMode: false,\r\n\t\t\tonready: function() {\r\n\t\t\t\t_soundReady = true;\r\n\t\t\t}\r\n\t\t});\r\n\t}",
"function doTerminate()\n{ \n if (! initialized) return \"true\";\n \n var api = getAPIHandle();\n if (api == null)\n {\n message(\"Unable to locate the LMS's API Implementation.\\nTerminate was not successful.\");\n return \"false\";\n }\n else\n {\n // switch Terminate/LMSFinish method based on SCORM version\n if (versionIsSCORM2004 == true)\n {\n var result = api.Terminate(\"\");\n }\n else\n {\n var result = api.LMSFinish(\"\");\n } \n \n if (result.toString() != \"true\")\n {\n var err = ErrorHandler();\n message(\"Terminate failed with error code: \" + err.code);\n }\n }\n \n initialized = false;\n window.close();\n return result.toString();\n}",
"function initialize() {\n\tpru.loadDatafile(1, 'pwm_data.bin');\n\tpru.execute(1, 'pwm_text.bin', 408);\n\tzeroMotors();\n}",
"function doIsScorm2004(objectname,callbackname,randomnumber)\n{\n \n var api = getAPIHandle();\n var result = \"false\";\n if (api == null)\n {\n //DebugPrint(\"Unable to locate the LMS's API Implementation.\\nSetValue was not successful.\");\n }\n else if (!initialized && !doInitialize())\n {\n var error = ErrorHandler();\n //DebugPrint(\"doIsScorm2004 failed - Could not initialize communication with the LMS - error code: \" + error.code);\n }\n \n GetUnity().SendMessage(objectname, callbackname, versionIsSCORM2004 + \"|\"+\"|\"+\"|\" + randomnumber);\n}",
"_initializeLayer(layer) {\n try {\n layer._initialize();\n\n layer.lifecycle = _lifecycle_constants__WEBPACK_IMPORTED_MODULE_1__[\"LIFECYCLE\"].INITIALIZED;\n } catch (err) {\n this._handleError('initialization', err, layer); // TODO - what should the lifecycle state be here? LIFECYCLE.INITIALIZATION_FAILED?\n\n }\n }",
"function doLMSCommit()\n{ \n var api = getAPIHandle();\n if (api == null)\n {\n messageAlert(\"Unable to locate the LMS's API Implementation.\\nLMSCommit was not successful.\");\n return \"false\";\n }\n else\n {\n var result = api.LMSCommit(\"\");\n if (result != \"true\")\n {\n var err = ErrorHandler();\n }\n }\n\n return result.toString();\n}",
"async function onInitialize(/**if your code needs to do asynchronous work during initialize, initialize won't finish until the promise is resolved. */ initWork) {\n if (isStarted) {\n throw new Error(\"initialize already started and you are trying to schedule init work\");\n }\n if (initWork != null) {\n initWorkArray.push(initWork);\n // if ( typeof initWork === \"function\" ) {\n // initWorkArray.push( bb.try( initWork ) );\n // } else {\n // initWorkArray.push( bb.resolve( initWork ) );\n // }\n }\n return exports.finishedPromise;\n}",
"function initializeAllModules() {\r\n var modules = mj.modules;\r\n for (var moduleName in modules) {\r\n if (moduleName != 'main' && modules.hasOwnProperty(moduleName)) {\r\n if (typeof modules[moduleName].setup == 'function') {\r\n modules[moduleName].setup();\r\n }\r\n trigger('initialize-' + moduleName, null, true);\r\n }\r\n }\r\n }",
"function DLC() {\n\t\tthis.initialize.apply(this, arguments);\n\t}",
"function initialize(){\n seconds = 0;\n INITIALIZING = true;\n SAVE_DATA = false;\n GEN_PASSENGERS = false; //If true, we are waiting for Python to return from Generating Passengers\n READY_TO_INS_TRIPS = false; //If true, we have finished generating passengers and are ready to insert trips into the system\n INS_TRIPS = false; //If true, we are waiting for Python to return from inserting trips into the system\n \n initialize_simulation_data();\n if(master_interval == false){\n\tmaster_interval = setInterval(function(){master()},1000);}\n}",
"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 demoInitialize() {\n document.title = \"Visia\"\n // create the demo instance\n var demo = new Demo()\n demo.init()\n // register the callback that is called when all module contexts are created\n MLABApp.setModuleContextsReadyCallback(demo.moduleContextsReady)\n}",
"constructor() { \n \n ComDayCqWcmCoreImplLanguageManagerImplProperties.initialize(this);\n }",
"function loraInit() {\n lora = new RN2483(Serial2, {reset:B0});\n\n lora.getStatus(function(x){console.log(\"Device EUI = \" + x.EUI);});\n\n // Setup the LoRa module\n setTimeout(function() {Serial2.println(\"mac set appeui \" + appEUI);} , 1000);\n setTimeout(function() {Serial2.println(\"mac set appkey \" + appKey);}, 2000);\n setTimeout(function() {Serial2.println(\"mac join otaa\");}, 3000);\n \n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw the line d which has 1/d length | function draw_d_line() {
//Calculate x and y endpoints and starting position
var right_edge = EW_CENTER_POINT.x + inverseWavelength
var deltaX = inverseD * Math.cos(radians_90)
var deltaY = inverseD * Math.sin(radians_90)
ctxe.beginPath()
ctxe.moveTo(right_edge, EW_CENTER_POINT.y)
ctxe.lineTo(right_edge - deltaX, EW_CENTER_POINT.y - deltaY)
ctxe.stroke()
} | [
"function drawLine(svg){\t\n\t\t\tsvg.style.strokeOpacity = '0.6';\n\t\t\tvar length = svg.getTotalLength();\n\t\t\t// Clear any previous transition\n\t\t\tsvg.style.transition = svg.style.WebkitTransition ='none';\n\t\t\t// Set up the starting positions\n\t\t\tsvg.style.strokeDasharray = length + ' ' + length;\n\t\t\tsvg.style.strokeDashoffset = length;\n\t\t\t// Trigger a layout so styles are calculated & the browser\n\t\t\t// picks up the starting position before animating\n\t\t\tsvg.getBoundingClientRect();\n\t\t\t// Define our transition\n\t\t\tsvg.style.transition = svg.style.WebkitTransition = 'stroke-dashoffset 2s ease-in-out';\n\t\t\t// Go!\n\t\t\tsvg.style.strokeDashoffset = '0';\n\t\t}",
"function drawDashLine(ctx, x1, y1, x2, y2, dashLen) {\n if (dashLen === undefined || dashLen === null)\n dashLen = 2;\n ctx.moveTo(x1, y1);\n\n var dX = x2 - x1;\n var dY = y2 - y1;\n var dashes = Math.floor(Math.sqrt(dX * dX + dY * dY) / dashLen);\n var dashX = dX / dashes;\n var dashY = dY / dashes;\n\n var q = 0,\n currX = x1,\n currY = y1;\n while (q++ < dashes) {\n currX += dashX;\n currY += dashY;\n if (q % 2 === 0 )\n ctx.moveTo(currX, currY);\n else\n ctx.lineTo(currX, currY);\n }\n ctx.lineTo(x2, y2);\n }",
"function dottedLine(x, y, w, h) {\r\n fill(\"grey\");\r\n rect(x, y - 4, 800, 5);\r\n for (line = 0; line < 15; line++) {\r\n lineSegment(line * 80 + 1, y, 40, 5);\r\n }\r\n}",
"function hLine(i){\n var x1 = scaleUp(0);\n var x2 = scaleUp(boardSize - 1);\n var y = scaleUp(i); \n drawLine(x1, x2, y, y);\n //alert(\"i:\" + i+ \" x1:\"+x1+ \" x2:\"+x2+\" y1:\"+y+ \" y2:\"+y);\n }",
"breshnamDrawLine (point0, point1) {\n let x0 = point0.x >> 0;\n let y0 = point0.y >> 0;\n let x1 = point1.x >> 0;\n let y1 = point1.y >> 0;\n let dx = Math.abs(x1 - x0);\n let dy = Math.abs(y1 - y0);\n let color = new BABYLON.Color4(1,1,0,1);\n\n if(dy > dx){\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dx - dy;\n\n for(let y=y0; y!=y1; y=y+sy){\n this.drawPoint(new BABYLON.Vector2(x0, y), color);\n if(err >= 0) {\n x0 += sx ;\n err -= dy;\n }\n err += dx;\n }\n }\n else{\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dy - dx;\n\n for(let x=x0; x!=x1; x=x+sx){\n this.drawPoint(new BABYLON.Vector2(x, y0), color);\n if(err >= 0) {\n y0 += sy ;\n err -= dx;\n }\n err += dy;\n }\n }\n }",
"function lineSegment(x, y, w, h) {\r\n fill(255, 234, 0);\r\n rect(x, y - 4, w, h);\r\n}",
"function renderLine(ctx, start, end) {\n ctx.save();\n\n ctx.beginPath();\n ctx.moveTo(start.x, start.y);\n ctx.lineTo(end.x, end.y);\n\n ctx.stroke();\n ctx.restore();\n}",
"function GenerateLineElement(x2len, y2len, stroke_width, stroke_color) {\n\tvar aline = document.createElementNS(svgNS, \"line\");\n\taline.setAttribute(\"x2\", x2len);\n\taline.setAttribute(\"y2\", y2len);\n\taline.setAttributeNS(null, 'stroke-width', stroke_width);\n\taline.setAttributeNS(null, 'stroke', stroke_color);\n\treturn aline;\n}",
"drawLine() {\r\n line(this.left.x, this.left.y, this.right.x, this.right.y);\r\n }",
"function drawLineSegment(x1, y1, x2, y2, color, width) {\n if (color == undefined) color = colors[0];\n if (width == undefined) width = LINE_WIDTH;\n\n\tif(x1 != NaN && y1 != NaN && x1 != NaN && y2 != NaN && math.abs(y2-y1) < 10)\n\t{\n\t\tx1 = transformX(x1);\n\t\ty1 = transformY(y1);\n\t\tx2 = transformX(x2);\n\t\ty2 = transformY(y2);\n\n\t\tcontext.beginPath();\n\t\tcontext.moveTo(x1, y1);\n\t\tcontext.lineTo(x2, y2);\n\n\t\tcontext.strokeStyle = color;\n\t\tcontext.lineWidth = width;\n\t\tcontext.stroke();\n\t}\n}",
"function renderLine () {\n // Render each data point\n ctx.beginPath();\n ctx.strokeStyle = typeof dataset['strokeStyle'] !== 'undefined' ? dataset['strokeStyle'] : '#ffffff';\n ctx.lineWidth = typeof dataset['lineWidth'] !== 'undefined' ? dataset['lineWidth'] : 2;\n ctx.moveTo(points[0].x, points[0].y);\n\n for (var j = 1; j < points.length; j++) {\n ctx.lineTo(points[j].x, points[j].y);\n }\n\n ctx.stroke();\n }",
"function dibujarLinea(color, x_inicial, y_inicial, x_final, y_final)\n{\n lienzo.beginPath();\n lienzo.strokeStyle = color;\n lienzo.moveTo(x_inicial, y_inicial);\n lienzo.lineTo(x_final, y_final);\n lienzo.stroke();\n lienzo.closePath();\n}",
"function diagonal(x,y){\nif (x < 300 && y < 200){\n ctx.strokeStyle = 'green'\n} else {\n ctx.strokeStyle = 'red'\n}\nctx.beginPath();\nctx.moveTo(x,y);\nctx.lineTo(x+100,y+100);\nctx.stroke();\n}",
"function dashedLine(value,index,arg){\n tl.to(value,2,{opacity:1},0)\n .to(value,1.5,{opacity:0},2.5);\n\n }",
"function draw_angled_lines() {\n var deltaX = inverseWavelength * Math.cos(2 * radians)\n var deltaY = inverseWavelength * Math.sin(2 * radians)\n\n var halfDeltaX = (inverseWavelength/2) * Math.cos(radians)\n var halfDeltaY = (inverseWavelength/2) * Math.sin(radians)\n\n //Draw line with 2theta\n ctxe.beginPath()\n ctxe.moveTo(EW_CENTER_POINT.x, EW_CENTER_POINT.y)\n ctxe.lineTo(EW_CENTER_POINT.x + deltaX, EW_CENTER_POINT.y - deltaY)\n ctxe.stroke()\n\n //Draw dashed middle line (with theta angle)\n ctxe.beginPath()\n ctxe.setLineDash([2,4])\n ctxe.moveTo(EW_CENTER_POINT.x, EW_CENTER_POINT.y)\n ctxe.lineTo(EW_CENTER_POINT.x + halfDeltaX, EW_CENTER_POINT.y - halfDeltaY)\n ctxe.stroke()\n\n //Draw the arcs\n ctxe.beginPath()\n ctxe.setLineDash([0,0])\n ctxe.arc(EW_CENTER_POINT.x,EW_CENTER_POINT.y, inverseWavelength/6, degToRad(0) , degToRad(360-(theta)),true)\n ctxe.stroke()\n ctxe.beginPath()\n ctxe.arc(EW_CENTER_POINT.x,EW_CENTER_POINT.y, (inverseWavelength/6) + 5, degToRad(360-(theta)) , degToRad(360-(2*theta)),true)\n ctxe.stroke()\n }",
"function render_aim_helper_line() {\n var c = {\n x: gamer.x + map.planet_w / 2,\n y: gamer.y + map.planet_h / 2\n };\n\n context.setLineDash([]);\n context.lineWidth = 3;\n context.strokeStyle = '#00ff00';\n context.beginPath();\n context.moveTo(c.x, c.y);\n context.lineTo(c.x + 2 * map.planet_w * Math.cos(deg_to_rad(gamer.angle)), c.y - 2 * map.planet_h * Math.sin(deg_to_rad(gamer.angle)));\n context.stroke();\n }",
"function drawNet() {\r\n\tcanvasContext.beginPath();\r\n\r\n\t//sets dash length and spacing, first value indicates dash length, second indicates space between dash\r\n\tcanvasContext.setLineDash([30, 15]);\r\n\r\n\t//moves drawing cursor\r\n\tcanvasContext.moveTo(canvas.width / 2, 0);\r\n\tcanvasContext.lineTo(canvas.width / 2, canvas.height);\r\n\tcanvasContext.lineWidth = 5;\r\n\r\n\t//sets line colour\r\n\tcanvasContext.strokeStyle = \"white\";\r\n\tcanvasContext.stroke();\r\n}",
"function drawLine (yarray) {\n var line = svg.append('path').datum(yarray.toArray())\n line.attr('d', renderPath)\n yarray.observe(function (event) {\n // we only implement insert events that are appended to the end of the array\n event.values.forEach(function (value) {\n line.datum().push(value)\n })\n line.attr('d', renderPath)\n })\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 }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add an asynchronous validator or validators to this control, without affecting other validators. When you add or remove a validator at run time, you must call `updateValueAndValidity()` for the new validation to take effect. Adding a validator that already exists will have no effect. | addAsyncValidators(validators) {
this.setAsyncValidators(addValidators(validators, this._rawAsyncValidators));
} | [
"setNewValidators(newValidators) {\r\n super.setValidators(newValidators ? newValidators.validators.map(validator => validator && validator[1]) : null);\r\n super.setAsyncValidators(newValidators && newValidators.asyncValidators\r\n ? newValidators.asyncValidators.map(validator => validator && validator[1])\r\n : null);\r\n this.registeredValidators = this.generateValidatorNames(newValidators);\r\n }",
"registerAttributeValidators() {\n Object.values(this.constructor.attributeDescriptors).forEach((attributeObj) => {\n this._validators.set(attributeObj, [attributeObj]);\n });\n }",
"registerOnValidatorChange(fn) {\n this._onValidatorChange = fn;\n }",
"static register (Vue) {\n Object.keys(validators).forEach(validatorKey => {\n Vue.validator(validatorKey, validators[validatorKey])\n })\n }",
"function addAndUpdate () {\n for (let key in nextAttrs) {\n let nextVal = nextAttrs[key];\n let currVal = currAttrs[key];\n if (nextVal instanceof Function) {\n nextVal = nextVal();\n }\n if (key === 'value' && isFormEl(dom)) {\n dom.value = nextVal;\n } else if (nextVal !== currVal) {\n dom.__attrs[key] = nextVal;\n dom.setAttribute(key, nextVal);\n }\n }\n }",
"static declareFieldValidator(name, validator) {\n if (name in DECLARED_VALIDATORS) {\n logger.warn(`[OWebForm] field validator \"${name}\" overwritten.`);\n }\n DECLARED_VALIDATORS[name] = validator;\n }",
"function TKR_addMultiFieldValueWidget(\n el, field_id, field_type, opt_validate_1, opt_validate_2) {\n var widget = document.createElement('INPUT');\n widget.name = 'custom_' + field_id;\n if (field_type == 'str') {\n widget.size = 90;\n }\n if (field_type == 'user') {\n widget.style = 'width:12em';\n widget.classList.add('userautocomplete');\n widget.classList.add('customfield');\n widget.classList.add('multivalued');\n widget.addEventListener('focus', function(event) {\n _acrob(null);\n _acof(event);\n });\n }\n if (field_type == 'int' || field_type == 'date') {\n widget.style.textAlign = 'right';\n widget.style.width = '12em';\n widget.min = opt_validate_1;\n widget.max = opt_validate_2;\n }\n if (field_type == 'int') {\n widget.type = 'number';\n } else if (field_type == 'date') {\n widget.type = 'date';\n }\n\n el.parentNode.insertBefore(widget, el);\n\n var del_button = document.createElement('U');\n del_button.onclick = function(event) {\n _removeMultiFieldValueWidget(event.target);\n };\n del_button.textContent = 'X';\n el.parentNode.insertBefore(del_button, el);\n}",
"function setInputValidityStatus () {\n if (dependantsInputNamesAndValidators.length > 0) {\n dependantsInputNamesAndValidators.map(function (dependantItem) {\n if (scopeForm[dependantItem.inputName]) {\n scopeForm[dependantItem.inputName].$setValidity(dependantItem.validatorName, dependantItem.validator());\n }\n });\n }\n }",
"updateAriaAttrs () {\n if (!this.aria || this.isHeadless || !isCallable(this.el.setAttribute)) return;\n\n this.el.setAttribute('aria-required', this.isRequired ? 'true' : 'false');\n this.el.setAttribute('aria-invalid', this.flags.invalid ? 'true' : 'false');\n }",
"static installDateTimeValidators (moment) {\n if (typeof moment !== 'function') {\n warn('To use the date-time validators you must provide moment reference.');\n\n return false;\n }\n\n if (date.installed) {\n return true;\n }\n\n const validators = date.make(moment);\n Object.keys(validators).forEach(name => {\n Validator.extend(name, validators[name]);\n });\n\n Validator.updateDictionary({\n en: {\n messages: date.messages\n }\n });\n date.installed = true;\n\n return true;\n }",
"function validateAddLine(collectionGroupId, addViaLightbox) {\n var collectionGroup = jQuery(\"#\" + collectionGroupId);\n var addControls = collectionGroup.data(kradVariables.ADD_CONTROLS);\n\n if (addViaLightbox) {\n collectionGroup = jQuery(\"#kualiLightboxForm\");\n }\n\n var controlsToValidate = jQuery(addControls, collectionGroup);\n\n var valid = validateLineFields(controlsToValidate);\n if (!valid) {\n if (!addViaLightbox) {\n showClientSideErrorNotification();\n }\n\n return false;\n }\n\n return true;\n}",
"function validateCarYear () {\n let carYear = parseInt(carYearNum.value);\n let currentYear = new Date().getFullYear() + 1;\n \n if (currentYear < carYear) {\n formIsValid = false;\n carYearNum.setCustomValidity('Car year may not exceed ${currentYear}.')\n }\n else {\n carYearNumn.setCustomValidity('');\n }\n }",
"isValidatorRegistered(name, validatorName) {\r\n return (this.registeredValidatorsMap[name] &&\r\n this.registeredValidatorsMap[name].some(errorKey => errorKey === validatorName));\r\n }",
"function bootsVal() {\r\n\t$('#form').bootstrapValidator({\r\n\t\tlive : 'enabled',\r\n\t\tsubmitButtons : 'button[id=\"btnGuardar\"]',\r\n\t\tmessage : 'Valor invalido',\r\n\t\tfields : {\r\n\t\t\tresponsable : {\r\n\t\t\t\tgroup: '.form-group',\r\n\t validators: {\r\n\t notEmpty: { message: 'Campo Nombre Obligatorio' }\r\n\t }\r\n\t\t\t},\r\n\t\t\tpara : {\r\n\t\t\t\tgroup: '.form-group',\r\n\t \tvalidators: {\r\n\t \t\tnotEmpty: { message: 'Campo Correo Obligatorio'},\r\n\t \t}\r\n\t\t\t},\t\t\t\r\n\t\t\tdistribuidor : {\r\n\t\t\t\tgroup : '.form-group',\r\n\t\t\t\tvalidators : {\r\n\t\t\t\t\tnotEmpty : {\r\n\t\t\t\t\t\tmessage : 'Campo Distribuidor Obligatorio'\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t},\r\n\t\t\tsector : {\r\n\t\t\t\tgroup : '.form-group',\r\n\t\t\t\tvalidators : {\r\n\t\t\t\t\tnotEmpty : {\r\n\t\t\t\t\t\tmessage : 'Campo Sector Obligatorio'\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t});\r\n}",
"setDefaultDataValidationRules() {\n if(this.getOption('required') == true){\n this.dataValidators.isRequired = true;\n\n this.addDataValidationRule('NotBlank', {});\n }\n\n let rules = this.getOption('rules');\n for (var ruleKey in rules){\n this.addDataValidationRule(ruleKey, rules[ruleKey]);\n }\n }",
"function fn_validaInicioSesion() {\n \n $('#hfrmInicioSesion').bootstrapValidator({\n message: 'El valor es inválido.',\n feedbackIcons: {\n valid: 'fa fa-check-circle icono-verde',\n invalid: 'fa fa-times-circle icono-rojo',\n validating: 'glyphicon glyphicon-refresh'\n },\n live: 'enabled',\n fields: {\n txtLogin: {\n validators: {\n //vacio\n notEmpty: {\n message: \"Favor de ingresar un Usuario\"\n },\n //caracteres y formato\n regexp: {\n regexp: /^[0-9a-zA-Z._-]+$/i,\n message: 'Formato Invalido.'\n }\n }\n },\n txtPassword: {\n validators: {\n //vacio\n notEmpty: {\n message: \"Favor de ingresar un ID de Tarjeta\"\n }\n }\n }\n }\n }).on('success.form.bv', function (e) {\n e.preventDefault();\n //se llama funcion de iniciar sesion\n fn_inicioSesionSistema();\n });\n}",
"checkValidity() {\n this.select.checkValidity();\n }",
"function validate(data, options, cb) {\n var valid = true;\n var messages = {};\n\n if (options.validateAll !== false) {\n data = _.extend(_.object(_.map(_.keys(options.schema), function(name) {\n return [name, null];\n })), data);\n }\n\n // Validate fields asynchronously. Do not stop on any field-level validation\n // failures.\n async.each(_.keys(data), function(name, cb) {\n if (name in options.schema) {\n validateField({\n schema: options.schema[name],\n name: name,\n value: data[name] || ''\n }, options, data, function(message) {\n if (message) {\n valid = false;\n messages[name] = message;\n }\n cb();\n });\n } else {\n cb();\n }\n }, function() {\n if (valid) {\n cb(null, data);\n } else {\n cb(messages);\n }\n });\n}",
"function eventListenerInit() {\r\n // get TOTAL_FORMS element from Django management_form of Skill formset\r\n let totalSkillForms = document.getElementById(\"id_skill-TOTAL_FORMS\");\r\n for (i = 0; i < totalSkillForms.value; i++) {\r\n addSkillValueValidationEvent(i);\r\n }\r\n}",
"function tryToEnableAdd(){\n\tif (insertYearOk && insertNameOk){\n\t\t$(\"#addButton\").removeAttr(\"disabled\", \"disabled\");\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
render a single task assignee | renderAssignee (assignee) {
const assigneeDisplay = assignee.fullName || assignee.displayName || assignee.username || assignee.email;
const assigneeHeadshot = Utils.renderUserHeadshot(assignee);
return `
${assigneeHeadshot}
<span class="assignee">${assigneeDisplay}</span>
`;
} | [
"function assignTask(taskStringId, assigneeStringId) {\n client.tasks.update(taskStringId, {assignee: assigneeStringId});\n}",
"async getTaskAssign() {\n let boardMembers;\n const boardResponse = await boardGet(this.taskData.boardID);\n if (!(await this.handleResponseStatus(boardResponse, (body) => {\n boardMembers = [...(body.members || []), ...(body.admins || [])];\n }))) {\n return;\n }\n\n let assignedMembers;\n const assignsResponse = await taskGet(this.taskData);\n if (!(await this.handleResponseStatus(assignsResponse, (body) => {\n assignedMembers = new Set(body.members?.map((id, i) => body.members[i].id));\n }))) {\n return;\n }\n\n boardMembers.forEach((member) => {\n member.assigned = assignedMembers.has(member.id);\n });\n this.eventBus.call('gotTaskAssigns', boardMembers);\n }",
"function assignAddCurrentEmail() {\n const currentEmail = actionableEmails.shift();\n const newTaskNotes = taskNotesPrefix + emailIdPrefix + currentEmail.id;\n const newTask = new Task(currentEmail.subject, newTaskNotes);\n\n postNewTask(assignTaskListId, newTask);\n assignDisplayNextEmail();\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 }",
"function randomAssigner(unassignedTasks) {\n let shuffledDesigners = shuffleArray(config.designers);\n let numDesigners = shuffledDesigners.length;\n // We will use an interval to control how quickly requests are sent\n // in order to avoid being rate limited. The interval uses the\n // const delay, which determines how long to wait between requests.\n let index = 0;\n let interval = setInterval(function() {\n assignTask(unassignedTasks[index].gid, shuffledDesigners[index % numDesigners]);\n index++;\n if (index >= unassignedTasks.length) {\n clearInterval(interval);\n console.log(\"You've assigned \" + unassignedTasks.length + \" new design requests\");\n }\n }, delay);\n}",
"function assignDisplayNextEmail() {\n const actionItemsCountElement =\n document.getElementById('assign-suspected-action-items');\n const subjectLineElement = document.getElementById('assign-subject');\n\n actionItemsCountElement.innerText = actionableEmails.length;\n if (actionableEmails.length === 0) {\n subjectLineElement.innerText = '';\n disableAssignAcceptRejectButtons();\n return;\n }\n\n subjectLineElement.innerText =\n `(From: ${actionableEmails[0].sender}, ` +\n `Priority: ${actionableEmails[0].priority}) ` +\n `${actionableEmails[0].subject}`;\n}",
"function hGetMyAssignments(inst) {\n let sortedTasks = [];\n let assignedTasks = [];\n if (inst.uiState.get(\"assnSort\") == NAME_TXT) {\n sortedTasks = Tasks.find({owner:{$ne:Meteor.userId()}}, {sort:{createdAt:-1}});\n }\n else {\n sortedTasks = Tasks.find({owner:{$ne:Meteor.userId()}}, {sort:{name:1}});\n }\n sortedTasks.forEach((task)=>{\n if (task.assignees != null && task.assignees.indexOf(Meteor.user().username) >= 0)\n assignedTasks.push(task);\n });\n return assignedTasks;\n}",
"get withAssignee() {\n return issues.filter(obj => obj.assignee !== null)\n .map(obj => obj.id);\n }",
"function assigneeCount() {\n var assignees = {},\n sortedAssignees = [],\n $avatars = $('.table-list-cell-avatar-stack a'),\n // Features might have this pattern, so writing it this way to make it\n // easier to refactor later\n containerClass = 'github-pro-assignee-count',\n containerSelector = '.' + containerClass,\n $container = $('<div>').addClass(containerClass);\n\n // Remove the existing container\n $(containerSelector).remove();\n\n // We only want to show the container if assignees exist on the page\n if ( $avatars.length > 0 ) {\n\n // Collect assignee data from DOM\n $avatars.each(function() {\n var username = $(this).attr('aria-label').replace('View everything assigned to ', ''),\n userFullName = $(this).find('img').attr('alt');\n\n // Store it like hashmap\n assignees[username] = _incrementAssignee(username, userFullName, assignees[username]);\n });\n\n // Sort\n sortedAssignees = _sortAssignees(assignees);\n\n // Create the container\n sortedAssignees.forEach(function (assignee) {\n var $badge = _createBadge(assignee);\n $container.prepend($badge);\n });\n\n // Render!\n $('#js-issues-toolbar').before($container);\n }\n}",
"function AddAssignee(supplierAddress, multi, address, callback) {\n var transactionhash = '';\n var signedDate = Math.floor(Date.now() / 1000);\n var status = props.status_pending;\n multi.addAssignee.sendTransaction(supplierAddress, false, signedDate, status, '', {\n from: address,\n gas: 3000000\n }, function(err, contract) {\n transactionhash = contract;\n });\n callback(null, transactionhash);\n}",
"renderWorker(worker) {\n\n let display = document.querySelector('#display'); \n \n display.innerHTML += `<article>\n <h2 class=\"name\"> ${worker['fullName']} </h2>\n <p>Job: ${worker['job']} </p> <p> Comp: ${worker['company']}</p>\n <p> ID#: ${worker['id']} </p> <p> Salary: ${worker['salary']} </p>\n <p> Taxes to pay: ${worker['taxToPay']} </p>\n <button class=\"del\"> delete </button>\n </article>`; \n }",
"function html_link_from_todoist_task(task_title, task_id) {\n url = 'https://en.todoist.com/app?lang=en#task%2F' + String(task_id)\n html_task = \"<a target='_blank' href='\" + url + \"'>\" + task_title + \"</a>\"\n return html_task\n}",
"function editGoal() {\n\t\tprops.editTask(props.goalId);\n\t}",
"function Task (number, taskName, startDate, endDate, progress) {\n\t\tthis.number = number; \n\t\tthis.taskName = taskName; \n\t\tthis.startDate = startDate;\n\t\tthis.endDate = endDate;\n\t\tthis.progress = progress;\n\t\tthis.details = \"Task Details\" + \"\\n\" + \n\t\t\t \"Name: Lorem ipsum dolor sit amet\" + \"\\n\" + \n\t\t\t \"Requestor: consectetur adipiscing elit\" + \"\\n\" + \n\t\t\t \"PersonCommitted: Phasellus suscipit\"+ \"\\n\" + \n\t\t\t \"ResponsibleSubs: enim eu feugiat vulputate\";\n\t}",
"function getAssignees(value) {\r\n var assignees = new Array();\r\n assignees.push(value[4] + '(' + value[5] + ')' );\r\n \r\n //7: Assignee2\t//8: Assignee2's Department\r\n //9: Assignee3\t//10: Assignee3's Department\r\n //and more\r\n for ( var n = 8; n <= 14; n += 2 ) {\r\n //Logger.log(n);\r\n //return;\r\n \r\n //Loop ends, if there are Nth Assignee, and Nth Assignee's Department\r\n if ( !value[n] || !value[n + 1] ) {\r\n break;\r\n }\r\n assignees.push(value[n] + '(' + value[n + 1] + ')');\r\n //Logger.log(assignees.join(\"、\"));\r\n //return;\r\n } \r\n //assignees = assignees.join(\"、\")\r\n assignees = \"【Assignees】\" + assignees.join(\"、\");\r\n return assignees;\r\n}",
"function clickTaskCard(event) {\r\n // Display view task\r\n popUpView.style.display = \"block\";\r\n\r\n // get local storage\r\n let LocalStorageTaskArray = getLocalStorage(\"task\");\r\n // Get index of taskcard clicked\r\n let index = LocalStorageTaskArray.findIndex(obj => obj.name === event.target.previousSibling.previousSibling.previousSibling.previousSibling.innerHTML);\r\n let thisTask = getLocalStorage(\"task\")[index];\r\n // Render clicked task in view task\r\n renderTaskCard(thisTask);\r\n}",
"function TaskDetails({ match }) {\n const { task_id } = match.params;\n const { tickets } = useContext(AppContext);\n const [task, setTask] = useState(null);\n\n // find and display the correct task on mount\n useEffect(() => {\n let foundTask = null;\n\n for (const ticket of tickets) {\n if (ticket.tasks) {\n for (const t of ticket.tasks) {\n if (t.id === +task_id) {\n foundTask = t;\n }\n }\n }\n }\n\n setTask(foundTask);\n }, [task_id, tickets]);\n\n return (\n task && (\n <div>\n <div>{task.title}</div>\n <div>{task.description}</div>\n <div>{task.status}</div>\n {task.actions && <ActionList actions={task.actions} />}\n </div>\n )\n );\n}",
"function syncSubject() {\n var v_subject = v(self.formData.task_subject);\n var v_task_id = v(self.formData.task_id);\n var $list = $('#task-list-container', window.parent.document);\n var $subject = $list.contents().find(\"div[class~='panel-primary'] span[name='task-subject']\");\n if ($subject.length > 0 && $subject.html() != unescape(v_subject) && v_task_id != \"\") {\n $subject.html(unescape(v_subject));\n } \n }",
"function getDetail() {\n\t\tTasks.get({id: $routeParams.taskId}, function(data) {\n\t\t\t$scope.task = data;\n\t\t});\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to save data from single trial | function saveSingleTrial(data, subjid, task_url, trialnum, correct){
// Use jQuery to send an AJAX post request to savejsptrial/
$.ajax(
{
type: 'POST',
url: '/savejsptrial/',
data: {
// Need to add parent study fields
'jsPsychData': data,
'subjid': subjid,
'task_url': task_url,
'trialnum': trialnum,
'correct': correct
},
success: function(){
}
}
);
} | [
"function saveParticipantData() {\n \n var nameStr = []; valStr = [];\n var firstPFpauses = 0; secondPFpauses = 0;\n var firstPFcorrect = 0; secondPFcorrect = 0;\n var SLcorrect = 0; numCorr = 0; \n exp_data[\"SL2subject\"] = subjectID;\n exp_data[\"SL2condition\"] = condition;\n exp_data[\"PF1type\"] = lasttime;\n exp_data[\"PF2type\"] = condition;\n exp_data[\"lasttime\"] = lasttime;\n for (i = 0; i < (demographics.length-1); i++) {\n exp_data[demographics[i].name] = demographics[i].value;\n }\n for (var i = 0; i<4; i++) {\n str = \"SL2easy\" + (i+1);\n exp_data[str] = easy[i];\n str = \"SL2hard\" + (i+1);\n exp_data[str] = hard[i];\n }\n for (i=0; i<testitems.length; i++) {\n str = 'SL2item' + (i+1);\n exp_data[str] = testitems[i];\n str = 'SL2answer' + (i+1);\n exp_data[str] = testanswers[i];\n if (testanswers[i]==\"correct\") {\n SLcorrect = SLcorrect + 1;\n }\n }\n exp_data[\"SL2correct\"] = SLcorrect/(testitems.length);\n englishwords[0].value = englishwords[0].value.toLowerCase();\n englishwords[0].value = englishwords[0].value.replace(/\\s+/g, '');\n \n for (var i=0; i<5; i++) {\n var word = testwords[i].replace(\".jpg\",\"\");\n if (englishwords[0].value.indexOf(word) > -1) {\n numCorr = numCorr + 1;\n }\n }\n exp_data[\"SL2traincorr\"] = numCorr;\n \n for (i=0; i<pfApauses.length; i++) {\n str = 'PF1pause' + (i+1);\n exp_data[str] = pfApauses[i];\n str = 'PF1answer' + (i+1);\n exp_data[str] = pfAanswers[i];\n str = 'PF1target' + (i+1);\n exp_data[str] = pfTaskAtargets[i];\n firstPFpauses = firstPFpauses + pfApauses[i];\n if (pfAanswers[i]==\"correct\") {\n firstPFcorrect = firstPFcorrect + 1;\n }\n }\n for (i=0; i<pfBpauses.length; i++) {\n str = 'PF2pause' + (i+1);\n exp_data[str] = pfBpauses[i];\n str = 'PF2answer' + (i+1);\n exp_data[str] = pfBanswers[i];\n str = 'PF2target' + (i+1);\n exp_data[str] = pfTaskBtargets[i];\n secondPFpauses = secondPFpauses + pfBpauses[i];\n if (pfBanswers[i]==\"correct\") {\n secondPFcorrect = secondPFcorrect + 1;\n }\n }\n exp_data[\"PF1pauseavg\"] = firstPFpauses/pfApauses.length;\n exp_data[\"PF2pauseavg\"] = secondPFpauses/pfBpauses.length;\n exp_data[\"PF1correct\"] = firstPFcorrect/pfAanswers.length;\n exp_data[\"PF2correct\"] = secondPFcorrect/pfBanswers.length;\n \n console.log(exp_data);\n saveData(exp_data); \n}",
"function saveFitness() {\n}",
"function save_data() {\n\t\n\t// rename old data file to backup file\n\tfs.rename(data_file, backup_data_file, function(err) {\n\t\tif (err) {\n\t\t\tconsole.log(err);\n\t\t\tconsole.log('Failed to backup data');\n\t\t}\n\t\t\n\t\t// write new data to file\n\t\tfs.writeFile(data_file, pprint(tms_data), function(err) {\n\t\t\tif (err) {\n\t\t\t\tconsole.log(err);\n\t\t\t\tconsole.log('Failed to generate new data');\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\t// write to the log file\n\t\t\t\tlast = Date.now();\n\t\t\t\tfs.appendFile(log_file, '\\n' + last, function(err) {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\tconsole.log(err);\n\t\t\t\t\t\tconsole.log('Failed to write to log file');\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\tconsole.log('New data has been generated');\n\t\t\t}\n\t\t});\n\t});\n}",
"function saveData() {\n var self = this;\n\n try {\n localStorage.setItem(\n self.data.name,\n JSON.stringify(self.getArrayOfData())\n );\n } catch (e) {\n console.error('Local storage save failed!', e);\n }\n\n }",
"saveData() {\n let jsonData = {\n lastTicket: this.lastTicket,\n today: this.today,\n tickets: this.tickets,\n lastFour: this.lastFour\n }\n\n let jsonDataString = JSON.stringify(jsonData);\n \n fs.writeFileSync('./server/data/data.json', jsonDataString);\n }",
"save() {\n\n let files = new Visitor(\n this.fullName,\n this.age,\n this.visitDate,\n this.visitTime,\n this.comments,\n this.assistedBy\n );\n let fileData = JSON.stringify(files)\n const fs = require('fs');\n\n id++;\n\n fs.writeFile(`visitor${id}.json`, fileData, err => {\n if (err) {\n throw (Error + 'Cannot save file');\n } else {\n console.log('File was saved');\n\n }\n });\n\n return 'File was saved';\n }",
"nextTrial() {\n\t\t// determine staircase\n\t\tthis.determineStairCase();\n\t\t\n\t\t// if all done, finished\n\t\tif (this.isFinished()) {\n\t\t\treturn null; // signifiy that it's finished\n\t\t}\n\n\t\t// get the params for this trial\n\t\tvar stairparams = this.staircases[this.stairIndex];\n\t\t// calculate the diff value from the stair \n\t\tvar stairValue = this.getCurrentStaircase().stairLevel2Value();\n\t\t// make a trial from the this staircase\n\t\tvar trial = new Trial(\n\t\t\tstairparams.count1, \n\t\t\tstairparams.count2,\n\t\t\tstairValue,\n\t\t\tstairparams.style);\n\t\ttrial.stairLevel = this.getCurrentStaircase().level;\n\t\t// set trial indices\n\t\ttrial.index = this.trials.length;\n\t\ttrial.indexStair = this.getCurrentStaircase().trials.length;\n\t\t// whether to show feedback after response\n\t\ttrial.feedback = trial.indexStair < ROUNDS_OF_FEEDBACK || alwaysFeedback;\n\t\tif (trial.indexStair < ROUNDS_OF_FEEDBACK) {\n\t\t\ttrial.presentationTime = 60 * 60 * 1000;\n\t\t\ttrial.maxValueRequested = 1 - trial.maxMean;\n\t\t\ttrial.minValueRequested = trial.maxMean;\n\t\t\ttrial.makeSets();\n\t\t}\n\t\t// add trial to staircase and experiment history\n\t\tthis.trials.push(trial);\n\t\tthis.getCurrentStaircase().trials.push(trial);\n\t\t// set it as the current trial\n\t\tthis.currentTrial = trial;\n\t\treturn trial;\n\t}",
"function saveAndStore() {\n console.log('saveAndStore was run');\n\n i = allTrips.length;\n\n var beginTrip = document.getElementById(\"beginPoint\").value;\n var endTrip = document.getElementById(\"endPoint\").value;\n var typeTrip = document.getElementById(\"mode\").value;\n var tripDistance = document.getElementById(\"distance\").innerHTML;\n var tripDuration = document.getElementById(\"duration\").innerHTML;\n var tripArticleType = document.getElementById(\"articleType\").value;\n allTrips.push({start: beginTrip, destination: endTrip, type: typeTrip, distance: tripDistance, duration: tripDuration, choice: tripArticleType, id: i++});\n\n listTrip(\"all\", allTrips);\n \n // Searches for what type of trip was taken and runs listTrip to place it into that specific tab\n if(document.getElementById(\"mode\").value == \"DRIVING\") {\n var drivingTrips = allTrips.filter(function(trip){ return trip.type === \"DRIVING\"});\n listTrip(\"driving\", drivingTrips);\n } else if(document.getElementById(\"mode\").value == \"BICYCLING\") {\n var bicyclingTrips = allTrips.filter(function(trip){ return trip.type === \"BICYCLING\"});\n listTrip(\"biking\", bicyclingTrips);\n } else if(document.getElementById(\"mode\").value == \"TRANSIT\") {\n var transitTrips = allTrips.filter(function(trip){ return trip.type === \"TRANSIT\"});\n listTrip(\"public\", transitTrips);\n } else if(document.getElementById(\"mode\").value == \"WALKING\") {\n var walkingTrips = allTrips.filter(function(trip){ return trip.type === \"WALKING\"});\n listTrip(\"walking\", walkingTrips);\n }\n\n storeTrip();\n\n $(\"#beginPoint\").val(\"\");\n $(\"#endPoint\").val(\"\");\n $(\"#mode\").val(\"\");\n $(\"#articleType\").val(\"\");\n}",
"function savePreSetPlans()\r\n{\r\nlocalStorage.setItem(\"planUP\"+1,JSON.stringify(planUP)); \r\nlocalStorage.setItem(\"planUM\"+1,JSON.stringify(planUM)); \r\nlocalStorage.setItem(\"planUR\"+1,JSON.stringify(planUR)); \r\nlocalStorage.setItem(\"planHP\"+1,JSON.stringify(planHP)); \r\nlocalStorage.setItem(\"planHM\"+1,JSON.stringify(planHM)); \r\nlocalStorage.setItem(\"planHR\"+1,JSON.stringify(planHR)); \r\nlocalStorage.setItem(\"planOP\"+1,JSON.stringify(planOP)); \r\nlocalStorage.setItem(\"planOM\"+1,JSON.stringify(planOM)); \r\nlocalStorage.setItem(\"planOR\"+1,JSON.stringify(planOR)); \r\nlocalStorage.setItem(\"planBP\"+1,JSON.stringify(planBP)); \r\nlocalStorage.setItem(\"planBM\"+1,JSON.stringify(planBM)); \r\nlocalStorage.setItem(\"planBR\"+1,JSON.stringify(planBR)); \r\n}",
"function clicSaveEverything() {\r\n var data_export = {};\r\n data_export[\"market\"] = data;\r\n data_export[\"simulation\"] = simopt;\r\n var save = JSON.stringify(data_export);\r\n document.location=\"data:text/csv;base64,\"+btoa(save);\r\n\r\n}",
"function save(){\n const a = JSON.stringify(answers);\n localStorage.setItem(\"answers\", a);\n}",
"function saveDataCreateReport() {\n console.log('Writing data to JSON...');\n const jsonFile = fileName(client,'results/','json');\n fs.writeFileSync(jsonFile, JSON.stringify(AllResults));\n console.log(`Created ${jsonFile}`);\n\n console.log('Creating A11y report...');\n var data = mapReportData(AllResults);\n var report = reportHTML(data, tests, client, runner, standard);\n var dateStamp = dateStamp();\n var name = `${client} Accessibility Audit ${dateStamp}`;\n\n console.log('Writing report to HTML...');\n const htmlFile = fileName(client,'reports/','html');\n fs.writeFileSync(htmlFile, report);\n console.log(`Created ${htmlFile}`);\n\n console.log('Creating Google Doc...');\n googleAPI.createGoogleDoc(name, report);\n }",
"function saveState(){\n writeToFile(userFile, users);\n writeToFile(campusFile, campus);\n}",
"static persist() {\n let questionsJson = JSON.stringify(questions);\n fs.writeFileSync(storagePath, questionsJson, 'utf-8');\n }",
"function saveSettings(){\n localStorage[\"pweGameServerStatus\"] = gameselection;\n //console.log('saved: ' + gameselection);\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}",
"function append_trial_data(tix,tdat) {\n var queue = c.data.datasets[tix].data;\n if(queue.length > c.samples) queue.shift();\n queue[queue.length] = parseInt(tdat);\n}",
"function saveResults(db, type){\n\t\tvar test = getSelectedTest().id;\n\t\tif (test == 0 || test == 1)\n\t\t\ttest = \"post\";\n\t\telse if (test == 2 || test == 3)\n\t\t\ttest = \"get\";\n\t\telse if (test == 4 || test == 5)\n\t\t\ttest = \"update\"\n\n\t\tvar time = $scope.time;\n\t\tfirebase.database().ref('test_history/' + test + '/' + db.name.toLowerCase() + '/' + type).push({\n\t\t\tip: ipInfo,\n\t\t\ttime_ms: time\n\t\t});\n\n\t\t$scope.completedTests.push({\n\t\t\tdb: db,\n\t\t\ttime: time,\n\t\t\tresult: \"Sucess\"\n\t\t});\n\t\tnextTest();\n\t}",
"function MDUO_Save(){\n console.log(\"=== MDUO_Save =====\") ;\n // save subject that have exam_id or ntb_id\n // - when exam_id has value and ntb_id = null: this means that ntb is removed\n // - when exam_id is null and ntb_id has value: this means that there is no exam record yet\n // - when exam_id and ntb_id both have value: this means that ntb_id is unchanged or chganegd\n const exam_list = [];\n if(mod_MDUO_dict.duo_subject_dicts){\n for (const data_dict of Object.values(mod_MDUO_dict.duo_subject_dicts)) {\n\n if (data_dict.exam_id || data_dict.ntb_id){\n exam_list.push({\n subj_id: data_dict.subj_id,\n ntb_id: data_dict.ntb_id,\n dep_pk: data_dict.dep_id,\n level_pk: data_dict.lvl_id,\n subj_name_nl: data_dict.subj_name_nl,\n exam_id: data_dict.exam_id,\n ntb_omschrijving: data_dict.ntb_omschrijving\n });\n };\n };\n };\n if (exam_list.length) {\n const upload_dict = {\n examperiod: setting_dict.sel_examperiod,\n exam_list: exam_list\n };\n// --- upload changes\n const url_str = urls.url_duo_exam_upload;\n console.log(\"upload_dict\", upload_dict) ;\n console.log(\"url_str\", url_str) ;\n\n UploadChanges(upload_dict, url_str);\n };\n $(\"#id_mod_duoexams\").modal(\"hide\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Listener for changes to ColumnMappingManager. Recalculates the number of applicable column mappings to the current layers. | onColumnMappingsChange_() {
this['mappingCount'] = 0;
var mappings = vectortools.getColumnMappings(this.scope_['sourceIds']);
for (var key in mappings) {
var columnsMap = mappings[key];
this['mappingCount'] += googObject.getCount(columnsMap);
}
ui.apply(this.scope_);
} | [
"recalculateColumnWidths() {\n if (!this._columnTree) {\n return; // No columns\n }\n if (this._cache.isLoading()) {\n this._recalculateColumnWidthOnceLoadingFinished = true;\n } else {\n const cols = this._getColumns().filter((col) => !col.hidden && col.autoWidth);\n this._recalculateColumnWidths(cols);\n }\n }",
"function onColumnDefsChange(newVal, oldVal) {\n _.each(oldVal, function (item, index) {\n if (item.selected === undefined) {\n item.selected = false;\n item.visible = typeof item.visible === 'boolean' ? item.visible : true;\n }\n });\n if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {\n logger.info('watch: sitGridOptions.columnDefs', 'column definitions changed, length = ' + ctrl.sitGridOptions.columnDefs.length);\n ctrl.generateCellTemplates(newVal);\n assignGridVisibleCols();\n ctrl.resetGrid(false, false);\n }\n }",
"function onUpdatedGridData() {\n // Publish model changed\n Control.publishModelChanged(component.address, {values: component.model.values});\n // Store event\n component.storeEvent('change');\n // Show/hide save button\n component.repositionSaveButton();\n // Resize the grid (to show or not scrollbars)\n component.resize();\n }",
"function reloadMap() {\n map.invalidateSize();\n}",
"function updateMapExtents() {\n var extent = [];\n if (dataLayers.length == 0) {\n extent = [0.0, 0.0, 1.0, 1.0];\n } else {\n extent = dataLayers[0].mapLayer.getSource().getExtent();\n // Make a clone\n extent = [...extent]\n for (var i = 1; i < dataLayers.length; i++) {\n var layerExtent = dataLayers[i].mapLayer.getSource().getExtent();\n extent[0] = Math.min(extent[0], layerExtent[0])\n extent[1] = Math.min(extent[1], layerExtent[1])\n extent[2] = Math.max(extent[2], layerExtent[2])\n extent[3] = Math.max(extent[3], layerExtent[3])\n }\n }\n zoomAllControl.extent = extent;\n}",
"function addMapWatch(cScope,map,mapid,layers,fallBack) {\n sendMapDimensions=function(evt) {\n cScope.send({\"dimChange\" : {'type': evt.type, 'fromMapId': mapid, 'zoom': map.getZoom(), 'pos': map.getCenter()}})\n }\n\n map.on('moveend',sendMapDimensions)\n map.on('zoomend',sendMapDimensions)\n map.on('move',sendMapDimensions)\n\n\n // Debug layers names\n if(layers) {\n for (const [key, value] of Object.entries(layers)) {\n console.log(\"layer key \",key,\" val=\", value);\n }\n\n for (var key in layers) {\n // check if the property/key is defined in the object itself, not in parent\n if (layers.hasOwnProperty(key)) {\n console.log(\"layer key \",key,\" val=\", layers[key]);\n }\n }\n }\n\n cScope.$watch('msg',function(msg) {\n let refPointMarker\n\n function setRefPointMarker(pos) {\n console.log(\"setRefPointMarker - pairs\")\n\n if (refPointMarker) {\n map.removeLayer(refPointMarker);\n }\n\n let svgPin = '<svg width=\"20\" height=\"20\" xmlns=\"http://www.w3.org/2000/svg\"><metadata id=\"metadata1\">image/svg+xml</metadata><circle fill=\"#fe2244\" cx=\"10\" cy=\"10\" r=\"9\"/><circle fill=\"#ffffbf\" cx=\"10\" cy=\"10\" r=\"5\"/></svg>'\n refPointMarker=L.marker([pos.lat,pos.lng], {icon: L.icon({iconUrl: encodeURI(`data:image/svg+xml,${svgPin}`).replace(/\\#/g,'%23'), iconSize: 20})}).bindPopup(\"Ref Point\").addTo(map);\n }\n\n if(msg) {\n if(\"payload\" in msg) {\n if(\"setDim\" in msg.payload) {\n console.log('setDim',msg.payload.setDim)\n if(map.getZoom()!=msg.payload.setDim.zoom || map.getCenter()!=msg.payload.setDim.pos) {\n map.setView(msg.payload.setDim.pos,msg.payload.setDim.zoom)\n }\n if(\"type\" in msg.payload.setDim && msg.payload.setDim.type=='initMap') {\n setRefPointMarker(msg.payload.setDim.pos)\n }\n } else if(\"setOpacity\" in msg.payload) {\n console.log(\"Setting opcacity\",msg.payload.setOpacity)\n for (var name in layers) {\n if (layers.hasOwnProperty(name)) {\n if(name==msg.payload.setOpacity.layer) {\n console.log(\"Setting layer \",name,\" opacity to \",msg.payload.setOpacity.opacity)\n layers[name].setOpacity(msg.payload.setOpacity.opacity)\n }\n }\n }\n } else if(\"setRefPoint\" in msg.payload) {\n // Set the reference point with a marker\n setRefPointMarker(msg.payload.setRefPoint.pos)\n map.setView(msg.payload.setRefPoint.pos,map.getZoom())\n } else if(fallBack) {\n fallBack(msg.payload,cScope,map,mapid,layers)\n }\n } else {\n console.log(`${mapid} unhandled msg, no payload: `,msg)\n }\n }\n });\n\n // Notify of init complete\n cScope.send({\"initMap\":mapid});\n}",
"launchColumnMappings() {\n windows.openSettingsTo(ColumnMappingSettings.ID);\n }",
"function MapListeners() { }",
"function calcNumRows(){\n \tvar map = document.getElementById('map');\n \tif(map != null){\n \t\tvar height = map.naturalHeight; //calculate the height of the map\n \t\n \t//height -= 16;\n \theight = height / 16;\n \tvar temp = [];\n \t\n \tfor(var i = 0; i < height; i++)\n \t\ttemp.push(i+1);\n \t\n \tif(temp.length != 0){\n \t\t$interval.cancel(rowTimer); //cancel $interval timer\n \t\t$scope.rows = temp;\n \t}\n \t}\n }",
"refreshMap() {\n this.removeAllMarkers();\n this.addNewData(scenarioRepo.getAllEvents(currentScenario));\n this.showAllMarkers();\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 onResize() {\n scope.$applyAsync(() => scope.updateScrollbar('update'));\n }",
"updateLayers() {\n // NOTE: For now, even if only some layer has changed, we update all layers\n // to ensure that layer id maps etc remain consistent even if different\n // sublayers are rendered\n const reason = this.needsUpdate();\n\n if (reason) {\n this.setNeedsRedraw(`updating layers: ${reason}`); // Force a full update\n\n this.setLayers(this._nextLayers || this._lastRenderedLayers, reason);\n } // Updated, clear the backlog\n\n\n this._nextLayers = null;\n }",
"_onAppliedUpdate(view, metadata) {\n if (view && _.isFunction(view.afterApplyUpdate)) {\n view.afterApplyUpdate(metadata);\n }\n }",
"function bindDataLayerListeners(dataLayer) {\n dataLayer.addListener('click', selectFeatures);\n dataLayer.addListener('addfeature', refreshGeoJsonFromData);\n dataLayer.addListener('removefeature', refreshGeoJsonFromData);\n dataLayer.addListener('setgeometry', refreshGeoJsonFromData);\n}",
"function zoom_based_layerchange() {\n $(\"#zoomlevel\").html(map.getZoom());\n var currentZoom = map.getZoom();\n\n if (currentZoom <= 7) {\n clean_map();\n countryLayer.addTo(map);\n $(\"#layername\").html(\"Country\");\n activeLayer = \"Country\";\n } else {\n switch (currentZoom) {\n case 8:\n clean_map();\n regionLayer.addTo(map);\n $(\"#layername\").html(\"Region\");\n activeLayer = \"Region\";\n break;\n case 9:\n clean_map();\n municipLayer.addTo(map);\n $(\"#layername\").html(\"Municipality\");\n activeLayer = \"Municipality\";\n break;\n case 10:\n clean_map();\n municipLayer.addTo(map);\n $(\"#layername\").html(\"Municipality\");\n activeLayer = \"Municipality\";\n break;\n case 11:\n clean_map();\n municipLayer.addTo(map);\n $(\"#layername\").html(\"Municipality\");\n activeLayer = \"Municipality\";\n break;\n case 12:\n clean_map();\n municipLayerNonInteractive.addTo(map);\n unitLayer.addTo(map);\n $(\"#layername\").html(\"Unit\");\n activeLayer = \"Unit\";\n break;\n case 14:\n clean_map();\n municipLayerNonInteractive.addTo(map);\n pilotLayer.addTo(map);\n $(\"#layername\").html(\"Unit\");\n activeLayer = \"Unit\";\n break;\n default:\n // do nothing\n break;\n }\n }\n }",
"function onClickChange(i,j){\n console.log(\"merp i = \"+i+\", j = \"+j)\n if (editTables) {\n //TODO edit table ids\n } else {\n // toggle map block\n mapModified = true;\n console.log(map);\n map[i][j] = mapSyms[(mapSyms.indexOf(map[i][j])+1)%4];\n console.log(map);\n updateMap(); \n }\n \n}",
"function addColumn(event) {\n rowColumns[currentRow] = rowColumns[currentRow] + 1;\n event.column = rowColumns[currentRow];\n }",
"function initializeColumns(flex) {\r\n let promises = [flexgridService.getColumns(), flexgridService.getDatas()];\r\n\r\n $q.all(promises).then(function(values){\r\n var cols = values[0];\r\n var datas = values[1];\r\n\r\n //Define Columns\r\n angular.forEach(cols, function (value, key) {\r\n var col = new wijmo.grid.Column();\r\n col.binding = value.Name;\r\n col.header = value.Text;\r\n col.isReadOnly = value.IsReadOnly;\r\n //var col = { binding: value.Name, header: value.Text, isReadOnly: value.IsReadOnly };\r\n colsBinding.push(col);\r\n flex.columns.push(col);\r\n });\r\n\r\n //Bind Datas\r\n $scope.collectionView = new wijmo.collections.CollectionView(datas);\r\n $scope.collectionView.trackChanges = true;\r\n\r\n flex.initialize({\r\n //columns: colsBinding,\r\n itemsSource: $scope.collectionView,\r\n selectionMode: 'Row', //Values: None, Cell, CellRange, Row, RowRange, ListBox\r\n });\r\n });\r\n\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Conditionally rendering if the button will be highlighted in light blue or else Once button is clicked, handlePending() will run | ifPending() {
if (this.state.status == 'PENDING') {
return <Button size="small" variant="outlined" style={{
textTransform: 'none',
backgroundColor: '#D6E4FF',
fontSize: '10px'
}} onClick={() => this.handlePending()}>Pending</Button>;
} else {
return <Button size="small" variant="outlined" style={{
textTransform: 'none',
backgroundColor: '#E5E7EE',
fontSize: '10px',
}} onClick={() => this.handlePending()}>Pending</Button>;
}
} | [
"ifIncomplete() {\n if (this.state.status == 'INCOMPLETE') {\n return <Button size=\"small\" variant=\"outlined\" style={{\n textTransform: 'none',\n fontSize: '10px',\n backgroundColor: '#D6E4FF',\n }} onClick={() => this.handleIncomplete()}>Incomplete</Button>;\n } else {\n return <Button size=\"small\" variant=\"outlined\" style={{\n textTransform: 'none',\n backgroundColor: '#E5E7EE',\n fontSize: '10px'\n }} onClick={() => this.handleIncomplete()}>Incomplete</Button>;\n }\n }",
"ifPublished() {\n if (this.state.status == 'PUBLISHED') {\n return <Button size=\"small\" variant=\"outlined\" style={{\n textTransform: 'none',\n fontSize: '10px',\n backgroundColor: '#D6E4FF',\n }} onClick={() => this.handlePublished()}>Published</Button>;\n } else {\n return <Button size=\"small\" variant=\"outlined\" style={{\n textTransform: 'none',\n backgroundColor: '#E5E7EE',\n fontSize: '10px'\n }} onClick={() => this.handlePublished()}>Published</Button>;\n }\n }",
"function refreshWidgetAndButtonStatus() {\n var curWidget = self.currentWidget();\n if (curWidget) {\n widgetArray[curWidget.index].isSelected(false);\n self.currentWidget(null);\n }\n self.confirmBtnDisabled(true);\n }",
"ifAll() {\n if (this.state.status == '') {\n return <Button size=\"small\" variant=\"outlined\" style={{\n textTransform: 'none',\n fontSize: '10px',\n backgroundColor: '#D6E4FF',\n }} onClick={() => this.handleAll()}>All</Button>;\n } else {\n return <Button size=\"small\" variant=\"outlined\" style={{\n textTransform: 'none',\n backgroundColor: '#E5E7EE',\n fontSize: '10px',\n }} onClick={() => this.handleAll()}>All</Button>;\n }\n }",
"function btnClicked() {\n if(this.classList.contains('blue')){\n this.classList.remove('blue')\n click = click-1\n } else {\n this.classList.add('blue')\n click = click+1\n }\n }",
"ifDenied() {\n if (this.state.status == 'DENIED') {\n return <Button size=\"small\" variant=\"outlined\" style={{\n textTransform: 'none',\n fontSize: '10px',\n backgroundColor: '#D6E4FF',\n }} onClick={() => this.handleDenied()}>Denied</Button>;\n } else {\n return <Button size=\"small\" variant=\"outlined\" style={{\n textTransform: 'none',\n backgroundColor: '#E5E7EE',\n fontSize: '10px'\n }} onClick={() => this.handleDenied()}>Denied</Button>;\n }\n }",
"function switchToDoneBtn(context) {\n if ($(context).closest(\".timers\").css(\"background-color\")) {\n $(context).closest(\".timers\").css(\"background-color\", \"\");\n }\n deleteBtn(context);\n }",
"isTriggered() {\n return this.buttonClicked;\n }",
"updateGreen(event) {\n\n // Set the green color state.\n this.setState({\n green: event.target.value\n });\n \n return true;\n }",
"function updateMainButton() {\n if ($('#main-button').data('state') == 'start') {\n $('#main-button').text('START NEW GAME');\n }\n else if ($('#main-button').data('state') == 'drawing') {\n $('#main-button').text('DRAWING READY');\n }\n else if ($('#main-button').data('state') == 'disabled') {\n $('#main-button').text('PLEASE WAIT');\n }\n else if ($('#main-button').data('state') == 'upload-hiscore') {\n $('#main-button').text('UPLOAD HISCORE');\n }\n }",
"function prioritize_button(on) {\n\t\t\t$prioritize_btn = $('.tasks_page').find(\"#prioritize_btn\");\n\t\t\tif (on) {\n\t\t\t\t$prioritize_btn.css('background-color', '#ffdb26');\n\t\t\t\t$prioritize_btn.css('border-color', '#f2ca00');\n\t\t\t\t$($prioritize_btn.children('.btn_name')).css('color', 'white');\n\t\t\t} else {\n\t\t\t\t$prioritize_btn.css('background-color', '#fff7cf');\n\t\t\t\t$prioritize_btn.css('border-color', '#ffdb26');\n\t\t\t\t$($prioritize_btn.children('.btn_name')).css('color', '#626262');\n\t\t\t}\n\t\t\tprioritize_mode = on;\n\t\t}",
"function updateBtn() {\n if (btn.textContent === \"Turn On\") {\n btn.textContent = \"Turn Off\";\n msg.textContent = \"This is currently on\";\n } else {\n btn.textContent = \"Turn On\";\n msg.textContent = \"This is currently off\";\n }\n}",
"function globalTapped() {\n if(freeze || victory) return;\n if(!boardData[this.board].isActive()) return;\n select(this.board);\n render();\n}",
"function userColorPicked(event) {\n clickColor = event.target.value;\n mouseClickBtn.style.backgroundColor = clickColor;\n clickButton.style.backgroundColor = clickColor;\n}",
"confirmColor() {\n if (this.state.amount === this.props.amount) {\n return \"light\";\n }\n return \"primary\";\n }",
"powerBtnPress(e) {\n const powerBtn = document.getElementById('power-btn');\n powerBtn.className = 'power-btn btn-press';\n\n this.props.togglePower();\n\n setTimeout(() => {\n powerBtn.className = 'power-btn';\n }, 500);\n }",
"isButtonShouldBeHidden() {\n const { state, entriesType } = this.props;\n\n const selectedEntries = state.selected;\n const currentEntries = state[entriesType];\n\n let isButtonHidden = false;\n\n // Check current entries, if exists, check selected entries\n if(!currentEntries || !currentEntries.items || currentEntries.items.length === 0) {\n isButtonHidden = true;\n } else {\n for(const index in selectedEntries) {\n const entry = selectedEntries[index];\n\n const status = entry.status || entry.status_code;\n\n // If status is `active`\n // if(status === Statuses.ENTRY_ACTIVE) {\n // isButtonHidden = true;\n // break;\n // }\n }\n }\n\n return isButtonHidden;\n }",
"styleButtons () {\n // Check if it was rated\n if (this.props.wasPositive !== null) {\n // Previous rating positive\n if (this.props.wasPositive) {\n // Is this a positive rating button\n return (this.props.isPositive) ? 'green' : 'grey'\n } else {\n // Previous rating was negative\n // Is this a negative rating button\n return (!(this.props.isPositive)) ? 'red' : 'grey'\n }\n } else { // There was no previous rating\n return (this.props.isPositive) ? 'lightgreen' : 'lightred'\n }\n }",
"updateRed(event) {\n\n // Set the red color state.\n this.setState({\n red: event.target.value\n });\n \n return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When clicked on search result, scroll search results window away and select the correct ticket. Scroll the right side of the page to the correct ticket. | function ticketSelectScroll(ticket_number){
$('#search_results').slideUp("fast");
$('#search_field').css('border-radius','10px 10px 10px 10px');
//scroll the right box div
console.log(`Scrolling to: ${ticket_number}`);
var elmnt = document.getElementById(`ticket_row_${ticket_number}`);
//check if the ticket is hidden because of the year it was submitted
if ($(`#${elmnt.id}`).is(":hidden")){
//get the year of the ticket
var unformatted_date = $(`#${elmnt.id}`).find('#date_section').find("span").text()
split_date = unformatted_date.split('-');
var ticket_year = split_date[0].trim()
//change page to that year
$('#year_selector').val(ticket_year)
organizeByYear(ticket_year, ticket_number, ticket_order)
//scroll to it
elmnt.scrollIntoView({behavior: "smooth", block: "nearest"});
}else{
elmnt.scrollIntoView({behavior: "smooth", block: "nearest"});
selectTicket(ticket_number);
}
} | [
"function resultsResetScroll() {\n\t\t\tvar resultListing = document.getElementById('resultListing'),\n\t\t\t\tresultDocs = document.getElementById('resultDocs');\n\n\t\t\tif (resultListing) {\n\t\t\t\tresultListing.scrollTop = 0;\n\t\t\t}\n\n\t\t\tif (resultDocs) {\n\t\t\t\tresultDocs.scrollTop = 0;\n\t\t\t}\n\t\t}",
"function returnToSearchResults() {\n $('.returnSearch').on('click', function() {\n $('.js-search-results').show();\n $('.oneResult').hide();\n $('.returnSearch').hide();\n })\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 }",
"focusAndScroll() {\n this.scrollIntoView({block: 'nearest'});\n this.focus({preventScroll: true});\n }",
"function adjust_result_position() {\n 'use strict';\n // considering result div border size, place the div in the center, underneath of search input\n // outerwidth - border size of the result div\n // adjust result position\n $(result).css({left: query.position().left + 1, width: query.outerWidth() - 2});\n}",
"function jumpToElementByName(name) {\n var theElement = jq(\"[name='\" + escapeName(name) + \"']\");\n if (theElement.length != 0) {\n if (!usePortalForContext() || jQuery(\"#fancybox-frame\", parent.document).length) {\n jQuery.scrollTo(theElement, 1);\n }\n else {\n var headerOffset = top.jQuery(\"#header\").outerHeight(true) + top.jQuery(\".header2\").outerHeight(true);\n top.jQuery.scrollTo(theElement, 1, {offset: {top: headerOffset}});\n }\n }\n}",
"function scrollViews(){\r\n var scroll = 2;\r\n $('#main_area, .ui_city_overview').bind('mousewheel', function(e){\r\n if($('.island_view').hasClass('checked')){\r\n scroll = 2;\r\n } else if($('.strategic_map').hasClass('checked')){\r\n scroll = 1;\r\n } else {\r\n scroll = 3;\r\n }\r\n var delta = 0;\r\n if (e.originalEvent.wheelDelta) {\r\n if(e.originalEvent.wheelDelta < 0) { delta = -1;} else { delta = 1; }\r\n }\r\n else if (e.originalEvent.detail) {\r\n if(e.originalEvent.detail < 0) { delta = 1;} else { delta = -1; }\r\n }\r\n if(delta < 0) {\r\n scroll -= 1;\r\n if(scroll < 1) { scroll = 1; }\r\n }else {\r\n scroll += 1;\r\n if(scroll > 2 && options.tov) { scroll = 2 }\r\n if(scroll > 3) { scroll = 3 }\r\n }\r\n switch(scroll){\r\n case 1: $('.strategic_map').get(0).click(); break;\r\n case 2: $('.island_view').get(0).click(); break;\r\n case 3: $('.city_overview').get(0).click(); break;\r\n }\r\n //prevent page fom scrolling\r\n return false;\r\n });\r\n}",
"function searchtoresults()\n{\n\tshowstuff('results');\n\thidestuff('interests');\t\n}",
"function ensureSelectionInView() {\n\n //Only if open\n if (!$ctrl.isShowingResults) {\n return;\n }\n\n //Check index\n if (!$ctrl.isNullable && selectionIndex < 0) {\n return;\n }\n\n //Find options\n const $container = $input.next().next();\n const $options = $container.find('li');\n\n //Get option now, taking into account the additional nullable element\n const option = $options[selectionIndex + ($ctrl.isNullable ? 1 : 0)];\n if (!option) {\n return;\n }\n\n //Determine container and element top and bottom\n const cTop = $container[0].scrollTop;\n const cBottom = cTop + $container[0].clientHeight;\n const eTop = option.offsetTop;\n const eBottom = eTop + option.clientHeight;\n\n //Check if out of view\n if (eTop < cTop) {\n $container[0].scrollTop -= (cTop - eTop);\n }\n else if (eBottom > cBottom) {\n $container[0].scrollTop += (eBottom - cBottom);\n }\n }",
"scrollCategoriesToCurrent() {\n let currCat = this.category || localStorage.getItem('category');\n if (!currCat) return;\n\n const converter = {\n raw_food: 'Liv',\n restaurants: 'All',\n 'restaurants,bars,food': 'All',\n newamerican: 'Ame',\n tradamerican: 'Ame',\n hotdogs: 'Fas',\n bbq: 'Bar',\n hkcafe: 'Hon',\n };\n\n if (currCat in converter) currCat = converter[currCat];\n location.href = '#';\n location.href = `#${currCat[0].toUpperCase()}${currCat.substr(1, 2)}`;\n const $scrl3 = $('#scrl3');\n // move scrolled category a little lower for better visibility.\n const sT = $scrl3.scrollTop();\n if (sT >= 50) $scrl3.scrollTop(sT - 50);\n else $scrl3.scrollTop(0);\n\n FormFunctsObj.focusBlur();\n }",
"function updateScroll() {\n\t\tlet elements = container.getElementsByClassName('selected');\n\t\tif (elements.length > 0) {\n\t\t\tlet element = elements[0];\n\t\t\t// make group visible\n\t\t\tlet previous = element.previousElementSibling;\n\t\t\tif (previous && previous.className.indexOf('group') !== -1 && !previous.previousElementSibling) {\n\t\t\t\telement = previous;\n\t\t\t}\n\t\t\tif (element.offsetTop < container.scrollTop) {\n\t\t\t\tcontainer.scrollTop = element.offsetTop;\n\t\t\t} else {\n\t\t\t\tlet selectBottom = element.offsetTop + element.offsetHeight;\n\t\t\t\tlet containerBottom = container.scrollTop + container.offsetHeight;\n\t\t\t\tif (selectBottom > containerBottom) {\n\t\t\t\t\tcontainer.scrollTop += selectBottom - containerBottom;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function scrollToPost(id) {\n document.getElementById(id).scrollIntoView(true);\n}",
"function handleSearchResultClick(e) {\n theInterface.emit('ui:zoomToMarker', {\n position: e.currentTarget.getAttribute('data-position'),\n layer: e.currentTarget.getAttribute('data-layer')\n });\n }",
"scrollToCell(cell) {\n // use Phosphor to scroll\n ElementExt.scrollIntoViewIfNeeded(this.node, cell.node);\n // change selection and active cell:\n this.deselectAll();\n this.select(cell);\n cell.activate();\n }",
"function scroll (e) {\n var xyS = scrollXY(iwin) // iframe scroll\n var ifrPos = xy.add(xyS, lastMousePos)\n coords.show(xy.str(ifrPos))\n }",
"function moveMiddle () {\n console.log('│ current index is ' + search_keybindings_currentIndex)\n var mid = Math.floor(search_keybindings_resultLinks.length / 2)\n\n search_keybindings_currentIndex = mid\n console.log('└ targeting ' + search_keybindings_currentIndex)\n selectResult(search_keybindings_currentIndex)\n}",
"function toScroll(div, d, flag) {\n\t\t\t\t\t\t\tvar ndiv = $(div);\n\t\t\t\t\t\t\tvar pos = ndiv.scrollLeft();\n\t\t\t\t\t\t\tvar posDelta = 0;\n\t\t\t\t\t\t\tif (d.depth > 4)\n\t\t\t\t\t\t\t\tposDelta = 3 * (flag ? 40 : -40);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tposDelta = d.depth * (flag ? 40 : -40);\n\t\t\t\t\t\t\tndiv.scrollLeft(pos + posDelta);\n\t// var dId = d.id;\n\t// $('#' + dId).focus();\n\t\t\t\t\t\t}",
"function buildScroll() {\n\tconsole.log('building scroll result');\n\tscrollResult = new IScroll('#results_div', {dimensions:{x:30,y:60}, mouseWheel: true });\n\tresultsDiv.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);\n}",
"setScrollOffset() {\n const {\n isMainPageSearch,\n itemHeight,\n } = this.props;\n const { offset } = this.state;\n\n // $list is populated via the ref in the render method below\n if (this.$list) {\n this.$list.scrollTop = isMainPageSearch ? 0 : offset * itemHeight;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the first item in the list found in the Git tree, or null if none of the items exists in the array. | function getFirstFoundInTree(paths, ...items) {
for (const item of items) {
const path = paths.find(p => p.path === item);
if (path) {
return path;
}
}
return null;
} | [
"findFirst(_value) {\n if (this.head === null && this.tail === null) {\n // no nodes in the list\n return null;\n } else {\n // check each node's value one by one from the beginning of the chain\n let current = this.head;\n while (current.nextNode !== null) {\n if (current.value === _value) return current; // found\n current = current.nextNode;\n }\n return null;\n }\n }",
"function head(arr){\n return arr[0];\n}",
"function zerothItem(arr) {\n\treturn arr[0];\n}",
"get firstItem() {\n return !this.mainItems ? undefined : this.mainItems[0];\n }",
"function firstMatch(array,regex) {\n return array.filter(RegExp.prototype.test.bind(regex))[0];\n}",
"function find(arr, searchValue){\n\treturn arr.filter(i=>{\n\t\treturn i===searchValue;\n\t})[0];\n}",
"first(root, path) {\n var p = path.slice();\n var n = Node$1.get(root, p);\n\n while (n) {\n if (Text.isText(n) || n.children.length === 0) {\n break;\n } else {\n n = n.children[0];\n p.push(0);\n }\n }\n\n return [n, p];\n }",
"function first() {\n return _navigationStack[0];\n }",
"function getFirstElement(iterable) {\n var iterator = iterable[Symbol.iterator]();\n var result = iterator.next();\n if (result.done)\n throw new Error('getFirstElement was passed an empty iterable.');\n\n return result.value;\n }",
"function firstListItem() {\n return $(\"ul#pic-list li:first\")\n}",
"function firstCollectionElem(obj){\n\t//get first element, if any\n\tvar elem = $(obj).first();\n\t//check if collection is empty (i.e. has no first element)\n\tif( elem.length == 0 ){\n\t\t//return null if it is empty\n\t\treturn null;\n\t}\n\t//return first element\n\treturn elem[0];\n}",
"function findEmployeeByName(name, employeesArr) {\n\n let employeeArr = employeesArr.filter(employeeObj => {\n if (employeeObj.name === name) {\n return employeeObj;\n }\n });\n return employeeArr[0];\n}",
"function findFileByAppName(array, appName) {\n if (array.length === 0 || !appName) return null;\n\n for (var i = 0; i < array.length; i++) {\n var path = array[i];\n if (path && path.indexOf(appName) !== -1) {\n return path;\n }\n }\n\n return null;\n }",
"function first(array, n) {\r\n if (array == null) \r\n return 0;\r\n if (n == null) \r\n return array[0];\r\n if (n < 0)\r\n return [];\r\n return array.slice(0, n);\r\n }",
"function lensForCurrentMinElement(tree) {\n\tif (isEmpty(tree)) {\n\t\treturn null;\n\t} else if (isEmpty(tree.left)) {\n\t\treturn R.identity;\n\t} else {\n\t\treturn R.compose(\n\t\t\tlenses.leftChild,\n\t\t\tR.defaultTo(\n\t\t\t\tR.identity,\n\t\t\t\tlensForCurrentMinElement(tree.left)));\n\t}\n}",
"getChildInTree() {\n if (!this._children || this._children.length === 0)\n return null;\n for (var ch of this._children) {\n if (ch.isStartingPerson)\n return ch;\n if (ch.getChildInTree())\n return ch;\n }\n return null;\n }",
"function minRecurse(...num) {\n const array = num[0];\n const array2 = [...array];\n let min = array2[0];\n\n if (array2.length === 1) {return min}\n array2.shift();\n let newMin = minRecurse(array2);\n if (min > newMin) {min = newMin}\n \n return min;\n}",
"function minItem(anArray) {\r\n let smallest = anArray[0]\r\n for (i = 1; i < anArray.length; i++) {\r\n if (anArray[i] < smallest) {\r\n smallest = anArray[i];\r\n }\r\n }\r\n return smallest;\r\n}",
"async function getLeftMostLeaf(leafCheckArray) { //LeafCheckArray must be a since array - in this case it is\n\n let mostRecentLeaf = {}\n let leafURL = '';\n\n //First time you come upon an empty next is your leftmost leaf\n for (annot in leafCheckArray) {\n \tif (leafCheckArray[annot].__rerum.history.next.length == 0) {\n \t\tmostRecentLeaf = leafCheckArray[annot];\n \t\tbreak;\n \t}\n\n }\n\n return mostRecentLeaf;\n}",
"function findObject(index) {\n return repository[index];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enumerate the tokens of an organization This API allows to enumerate the tokens of an organization. organizationId String The organizationid represents an organization that is included in the SigninToday application, also know as slug and it is used as a path parameter to restrict the asked functionality to the specified organization whereUnderscoreuser String Returns the tokens of the specified user, searched by its id (optional) whereUnderscorelabel String Returns the tokens with the specified label (optional) count Integer Sets the number of tokens per page to display (optional) page Integer Restricts the search to chosen page (optional) returns inline_response_200_11 | static list_tokens({ organizationId, whereUnderscoreuser, whereUnderscorelabel, count, page }) {
return new Promise(
async (resolve) => {
try {
resolve(Service.successResponse(''));
} catch (e) {
resolve(Service.rejectResponse(
e.message || 'Invalid input',
e.status || 405,
));
}
},
);
} | [
"static list_user_tokens({ organizationId, userId, page, count }) {\n return new Promise(\n async (resolve) => {\n try {\n resolve(Service.successResponse(''));\n } catch (e) {\n resolve(Service.rejectResponse(\n e.message || 'Invalid input',\n e.status || 405,\n ));\n }\n },\n );\n }",
"static get_token({ organizationId, tokenId }) {\n return new Promise(\n async (resolve) => {\n try {\n resolve(Service.successResponse(''));\n } catch (e) {\n resolve(Service.rejectResponse(\n e.message || 'Invalid input',\n e.status || 405,\n ));\n }\n },\n );\n }",
"static create_token({ organizationId, createToken }) {\n return new Promise(\n async (resolve) => {\n try {\n resolve(Service.successResponse(''));\n } catch (e) {\n resolve(Service.rejectResponse(\n e.message || 'Invalid input',\n e.status || 405,\n ));\n }\n },\n );\n }",
"async validateOrganization(ctx, orgId) {}",
"async removeTokens(count) {\n // Make sure the request isn't for more than we can handle\n if (count > this.tokenBucket.bucketSize) {\n throw new Error(`Requested tokens ${count} exceeds maximum tokens per interval ${this.tokenBucket.bucketSize}`);\n }\n const now = (0,_clock_js__WEBPACK_IMPORTED_MODULE_1__.getMilliseconds)();\n // Advance the current interval and reset the current interval token count\n // if needed\n if (now < this.curIntervalStart || now - this.curIntervalStart >= this.tokenBucket.interval) {\n this.curIntervalStart = now;\n this.tokensThisInterval = 0;\n }\n // If we don't have enough tokens left in this interval, wait until the\n // next interval\n if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) {\n if (this.fireImmediately) {\n return -1;\n }\n else {\n const waitMs = Math.ceil(this.curIntervalStart + this.tokenBucket.interval - now);\n await (0,_clock_js__WEBPACK_IMPORTED_MODULE_1__.wait)(waitMs);\n const remainingTokens = await this.tokenBucket.removeTokens(count);\n this.tokensThisInterval += count;\n return remainingTokens;\n }\n }\n // Remove the requested number of tokens from the token bucket\n const remainingTokens = await this.tokenBucket.removeTokens(count);\n this.tokensThisInterval += count;\n return remainingTokens;\n }",
"static delete_token({ organizationId, tokenId }) {\n return new Promise(\n async (resolve) => {\n try {\n resolve(Service.successResponse(''));\n } catch (e) {\n resolve(Service.rejectResponse(\n e.message || 'Invalid input',\n e.status || 405,\n ));\n }\n },\n );\n }",
"get(data, callback) {\n // Check id is valid\n const id =\n typeof data.queryStringObject.id === 'string'\n && data.queryStringObject.id.trim().length === 20\n ? data.queryStringObject.id.trim()\n : false;\n\n if(id) {\n // Lookup token\n _data.read(\n 'tokens',\n id,\n (err, tokenData) => (\n !err && tokenData\n ? callback(200, tokenData)\n : callback(404)\n )\n );\n }\n else {\n callback(400, { Error: 'Missing required field.' });\n }\n }",
"function createFieldToken(field, id, type){\n \n // Get field value and token container\n \n let value = $(field).val();\n let container = $(field).siblings('.token-container');\n let tokenNo = $(container).find('.token').length + 1;\n \n // If token container doesn't exist, create it\n \n if(container.length == 0){\n \n // Create token container\n \n container = $('<div></div>');\n $(container).addClass('token-container');\n \n // Add token container after field\n \n $(field).after(container);\n \n }\n \n if(id == '' || $(container).find('input[value=\"' + id + '\"]').length == 0){\n \n // Create token\n \n let token = $('<span></span>');\n $(token).addClass('token');\n \n // Add HTML\n \n let html = value + '<button type=\"button\" class=\"exit\"></button>';\n html += '<input type=\"hidden\" name=\"token' + tokenNo + '-id\" value=\"' + id + '\">';\n html += '<input type=\"hidden\" name=\"token' + tokenNo + '-type\" value=\"' + type + '\">';\n $(token).html(html);\n \n // Add token to end of token container\n \n $(container).append(token);\n \n // Set event handlers\n \n setTokenHandlers(token);\n \n }\n \n // Clear field value and focus on field\n \n $(field).val('');\n $(field).focus();\n $(field).siblings('.autocomplete-list').hide();\n \n}",
"ListOfOrganisations() {\n let url = `/me/ipOrganisation`;\n return this.client.request('GET', url);\n }",
"async listTokensFromAddress (addr) {\n try {\n if (!addr) throw new Error('Address not provided')\n\n // Convert to a BCH address.\n addr = _this.bchjs.SLP.Address.toCashAddress(addr)\n // console.log(`addr: ${addr}`)\n\n const utxos = await _this.utxos.getUtxos(addr)\n // console.log(`utxos: ${JSON.stringify(utxos, null, 2)}`)\n\n const hydratedUtxos = await _this.utxos.hydrate(utxos)\n // console.log(`hydratedUtxos: ${JSON.stringify(hydratedUtxos, null, 2)}`)\n\n return _this.listTokensFromUtxos(hydratedUtxos)\n } catch (err) {\n console.error('Error in tokens.js/listTokensFromAddress()')\n throw err\n }\n }",
"function getTeamsWithPagination(\n competitionID,\n offset,\n limit,\n search,\n sortBy,\n sortOrder,\n competitionOrganisationId,\n) {\n return {\n type: ApiConstants.API_LIVE_SCORE_TEAM_WITH_PAGING_LOAD,\n competitionID,\n offset,\n limit,\n search,\n sortBy,\n sortOrder,\n competitionOrganisationId,\n };\n}",
"retrievingManagersByGroup (organization, serviceName, groupName, count = 10, offset = 0) {\n return this.services\n .OvhHttp\n .get(\"/sws/exchange/{organization}/{exchange}/groups/{mailinglist}/managers\", {\n rootPath: \"2api\",\n clearCache: true,\n urlParams: {\n organization,\n exchange: serviceName,\n mailinglist: groupName\n },\n params: {\n count,\n offset\n }\n });\n }",
"function getUnclaimedReportingTokens(db, account, callback) {\n}",
"async removeTokens(count) {\n // Is this an infinite size bucket?\n if (this.bucketSize === 0) {\n return Number.POSITIVE_INFINITY;\n }\n // Make sure the bucket can hold the requested number of tokens\n if (count > this.bucketSize) {\n throw new Error(`Requested tokens ${count} exceeds bucket size ${this.bucketSize}`);\n }\n // Drip new tokens into this bucket\n this.drip();\n const comeBackLater = async () => {\n // How long do we need to wait to make up the difference in tokens?\n const waitMs = Math.ceil((count - this.content) * (this.interval / this.tokensPerInterval));\n await (0,_clock_js__WEBPACK_IMPORTED_MODULE_0__.wait)(waitMs);\n return this.removeTokens(count);\n };\n // If we don't have enough tokens in this bucket, come back later\n if (count > this.content)\n return comeBackLater();\n if (this.parentBucket != undefined) {\n // Remove the requested from the parent bucket first\n const remainingTokens = await this.parentBucket.removeTokens(count);\n // Check that we still have enough tokens in this bucket\n if (count > this.content)\n return comeBackLater();\n // Tokens were removed from the parent bucket, now remove them from\n // this bucket. Note that we look at the current bucket and parent\n // bucket's remaining tokens and return the smaller of the two values\n this.content -= count;\n return Math.min(remainingTokens, this.content);\n }\n else {\n // Remove the requested tokens from this bucket\n this.content -= count;\n return this.content;\n }\n }",
"getAllOrganisationList() {\n const url = `api/organisations/all`;\n return Method.dataGet(url, token);\n }",
"function search_oauth2_token(token_id) {\n\n\treturn models.oauth_access_token.findOne({\n\t\twhere: {access_token: token_id},\n\t\tinclude: [{\n\t\t\tmodel: models.user,\n\t\t\tattributes: ['id', 'username', 'email', 'gravatar']\n\t\t}]\n\t}).then(function (token_info) {\n\t\tif (token_info) {\n\t\t\tif ((new Date()).getTime() > token_info.expires.getTime()) {\n\t\t\t\treturn Promise.reject({ error: {message: 'Oauth token has expired', code: 401, title: 'Unauthorized'}})\t\n\t\t\t}\n\n\t\t\tvar oauth2_token_owner = { oauth_client_id: token_info.oauth_client_id }\n\n\t\t\tif (token_info.user_id) {\n\t\t\t\toauth2_token_owner['user'] = token_info.User\n\t\t\t}\n\n\t\t\tif (token_info.iot_id) {\n\t\t\t\toauth2_token_owner['iot'] = token_info.iot_id\n\t\t\t}\n\t\t\t \n\t\t\treturn Promise.resolve(oauth2_token_owner)\n\t\t} else {\n\t\t\treturn Promise.reject({ error: {message: 'Oauth token not found', code: 404, title: 'Not Found'}})\n\t\t}\n })\n}",
"_createToken() {\n const that = this;\n let icon;\n const fragment = document.createDocumentFragment(),\n lastSelectedIndex = that.selectedIndexes[that.selectedIndexes.length - 1];\n\n if (that.selectionDisplayMode === 'plain' && (that.selectionMode === 'one' || that.selectionMode === 'zeroOrOne' || that.selectionMode === 'radioButton')) {\n icon = '';\n }\n else {\n if (that.selectionDisplayMode === 'tokens') {\n if (that.selectedIndexes.length === 1 && (['oneOrManyExtended', 'oneOrMany', 'one', 'radioButton'].indexOf(that.selectionMode) > -1)) {\n icon = '';\n }\n else {\n icon = '✖';\n }\n }\n else {\n icon = that.selectedIndexes.length === 1 ? '' : ',';\n }\n }\n\n const selectedIndexes = that.selectedIndexes,\n items = that.$.listBox._items;\n\n for (let i = 0; i < selectedIndexes.length; i++) {\n const selectedIndex = selectedIndexes[i];\n\n if (items[selectedIndex]) {\n fragment.appendChild(that._applyTokenTemplate(items[selectedIndex].label, that.selectionDisplayMode !== 'tokens' && selectedIndex === lastSelectedIndex ? '' : icon));\n }\n }\n\n return fragment;\n }",
"function fetchUnboundToken(callback) {\n this.hodRequestLib.authenticateUnboundHmac(this.apiKey, function(err, response) {\n if(err) return callback(err, response);\n\n return callback(null, response.result.token);\n });\n}",
"static update_token({ organizationId, tokenId, updateToken }) {\n return new Promise(\n async (resolve) => {\n try {\n resolve(Service.successResponse(''));\n } catch (e) {\n resolve(Service.rejectResponse(\n e.message || 'Invalid input',\n e.status || 405,\n ));\n }\n },\n );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert tableColumns into List of object | static serializeColumns(list) {
let rslts = [];
for (let m of list) {
if (m instanceof Object) {
if (m instanceof TableColumn) {
rslts.push(m.getData());
} else {
rslts.push(m);
}
}
}
return rslts;
} | [
"static parseColumns(list) {\n let rslt = [];\n\n for (let m of list) {\n if (m != null && m instanceof Object && typeof m['name'] === 'string') {\n let type = 'string';\n\n if (typeof m['type'] === 'string') {\n type = m['type'];\n }\n\n rslt.push(new TableColumn(m['name'], type, m['default']));\n } else if (m instanceof TableColumn) {\n rslt.push(m);\n } else {\n // invalid column data\n return null;\n }\n }\n\n return rslt;\n }",
"function table_jquery_objects_to_array(table_id) {\n list_of_lists = []\n $(\"#\" + table_id + \" tr\").each(function(row_number) {\n col_values = Object.values($(this).find('td'))\n if (col_values.length > 0) {\n col_values.forEach(function(col_val, col_number) {\n new_dictionary = {\n row_number: row_number,\n col_number: col_number,\n cell_value: $(col_val).text(),\n class_name: $(col_val).attr('class')\n }\n list_of_lists.push(new_dictionary)\n })\n }\n });\n return list_of_lists\n}",
"function table_jquery_objects(table_id) {\n list_of_lists = []\n $(\"#\" + table_id + \" tr\").each(function(row_number) {\n row_list = []\n col_values = Object.values($(this).find('td'))\n if (col_values.length > 0) {\n col_values.forEach(function(col_val, col_number) {\n col_val['row_number'] = row_number\n col_val['col_number'] = col_number\n row_list.push(col_val)\n })\n list_of_lists.push(row_list)\n }\n });\n return list_of_lists\n}",
"cellToArray(dt, columns, splitExpr) {\n if (splitExpr === undefined) splitExpr = /\\b\\s+/;\n let j;\n dt.forEach((p) => {\n p = p.data;\n columns.forEach((column) => {\n let list = p[column];\n if (list === null) return;\n if (typeof list === 'number') {\n p[column] = `${list}`;\n return;\n }\n const list2 = list.split(splitExpr);\n list = [];\n // remove empty \"\" records\n for (j = 0; j < list2.length; j++) {\n list2[j] = list2[j].trim();\n if (list2[j] !== '') list.push(list2[j]);\n }\n p[column] = list;\n });\n });\n }",
"function getColumnNames() {\n // fieldName => columnName\n var result = new Array();\n for (var i = 0, len = fields.length; i < len; i++) {\n var value = fields[i];\n if (!value.id) {\n var res = {};\n res[value.fieldName] = value.columnName;\n \n result.push(res);\n }\n }\n \n return result;\n }",
"visitColumn_list(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function datatables_data_get(table) {\n return table.data().toArray();\n}",
"visitModel_column_list(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function convertIntoUserObjects(rows) {\n var userObjects = [];\n rows.forEach( function(item) {\n var user = new User();\n user.setId(item.id)\n .setSalutation(item.salutation)\n .setFirstName(item.first_name)\n .setMiddleName(item.middle_name)\n .setLastName(item.last_name)\n .setSex(item.sex)\n .setEmail(item.email)\n .setPicpath(item.photopath)\n .setRole(item.role)\n .setAddress(item.city, item.state, item.country, item.pincode)\n .setContactNo(item.contactNo)\n .setDepartment(item.dept_name, item.dept_typ);\n userObjects.push(user);\n });\n return userObjects;\n}",
"async _listColumns() {\n return await this.api.queryFields(this.worksheetInfo);\n }",
"async __safeColumns (fields: string[]): Promise<Column[]> {\n await this.isInitialized\n return this.columns.filter(col => fields.indexOf(col.camelName) > -1)\n }",
"function getFieldNames() {\n // columnName => fieldName\n var result = new Array();\n for (var i = 0, len = fields.length; i < len; i++) {\n var value = fields[i];\n if (!value.id) {\n var res = {};\n res[value.columnName] = value.fieldName;\n \n result.push(res);\n }\n }\n \n return result;\n }",
"function getTableData( table ){\n\n var rows = table.rows,\n tlen = rows.length,\n i, j, row, rlen,\n labels = undefined, series = [];\n\n for( i = 0; i < tlen; i++ ){\n\n row = Array.from( rows[i].cells );\n rlen = row.length;\n\n if( row[0].tagName.test( /TH/i ) ){\n\n //get LABELS\n labels = [];\n for( j = 0; j < rlen; j++ ){ labels[j] = row[j].innerHTML; }\n\n } else {\n\n //get SERIES ; convert to numbers\n for( j = 0; j < rlen; j++ ){ row[j] = + row[j].get(\"text\"); }\n series.push(row);\n\n }\n }\n\n return series[0] ? { labels: labels, series: series } : null;\n\n}",
"function columnToColumnModel(column) {\n var isDisabled = InputUtils.isDisabled(column);\n var stackNode = logService.getStackNode(\n column.isForeignKey ? logService.logStackTypes.FOREIGN_KEY : logService.logStackTypes.COLUMN,\n column.table,\n {source: column.compressedDataSource, entity: column.isForeignKey}\n );\n var stackPath = column.isForeignKey ? logService.logStackPaths.FOREIGN_KEY : logService.logStackPaths.COLUMN;\n\n var type;\n if (column.isAsset) {\n type = 'file'\n } else if (isDisabled) {\n type = \"disabled\";\n } else if (column.isForeignKey) {\n type = 'popup-select';\n } else {\n type = UiUtils.getInputType(column.type);\n }\n\n if (type == 'boolean') {\n var trueVal = InputUtils.formatBoolean(column, true),\n falseVal = InputUtils.formatBoolean(column, false),\n booleanArray = [trueVal, falseVal];\n\n // create map\n var booleanMap = {};\n booleanMap[trueVal] = true;\n booleanMap[falseVal] = false;\n }\n\n return {\n allInput: undefined,\n booleanArray: booleanArray || [],\n booleanMap: booleanMap || {},\n column: column,\n isDisabled: isDisabled,\n isRequired: !column.nullok && !isDisabled,\n inputType: type,\n highlightRow: false,\n showSelectAll: false,\n logStackNode: stackNode, // should not be used directly, take a look at getColumnModelLogStack\n logStackPathChild: stackPath // should not be used directly, use getColumnModelLogAction getting the action string\n };\n }",
"function get_table_data(table) {\n rows = table.getElementsByTagName('tr');\n data = new Array(rows.length);\n for (i=1; i<rows.length; i++){\n if (rows[i].style.display == \"none\") {\n continue;\n }\n columns = rows[i].getElementsByTagName('td');\n row_data = new Array(columns.length);\n for(j=0; j<row_data.length; j++) {\n row_data[j] = columns[j].innerHTML;\n }\n data.push(row_data);\n }\n return data;\n }",
"function getColumnsData(sheet, range, rowHeadersColumnIndex) {\r\n rowHeadersColumnIndex = rowHeadersColumnIndex || range.getColumnIndex() - 1;\r\n var headersTmp = sheet.getRange(range.getRow(), rowHeadersColumnIndex, range.getNumRows(), 1).getValues();\r\n var headers = normalizeHeaders(arrayTranspose(headersTmp)[0]);\r\n return getObjects(arrayTranspose(range.getValues()), headers);\r\n}",
"function dataForTable(response) {\n return response;\n }",
"function objectizeRowData(_row) {\r\n\tiobj = new Object();\r\n\tiobj.id = _row.getValue(_row.getAllColumns()[0].getName(),_row.getAllColumns()[0].getJoin()); //internal id\r\n\tiobj.cfrom = _row.getValue(_row.getAllColumns()[1].getName(),_row.getAllColumns()[1].getJoin()); //created from (Linked Trx)\r\n\tiobj.trxrectype = _row.getValue(_row.getAllColumns()[2].getName(),_row.getAllColumns()[2].getJoin()); //transaction record type\r\n\tiobj.trxshipstate = _row.getValue(_row.getAllColumns()[3].getName(),_row.getAllColumns()[3].getJoin()); //transaction shipping state\r\n\tiobj.cfromshipstate = _row.getValue(_row.getAllColumns()[4].getName(),_row.getAllColumns()[4].getJoin()); //created from shipping state\r\n\tiobj.cfromrectype = _row.getValue(_row.getAllColumns()[5].getName(),_row.getAllColumns()[5].getJoin()); //created from record type\r\n\tiobj.trxnumber = _row.getValue(_row.getAllColumns()[6].getName(),_row.getAllColumns()[6].getJoin()); //trx number\r\n}",
"function createRow(col)\n{\n var row = new Object(); \n for(var i=0;i<col.length;i++ )\n {\n // the second array is of the format property value pair \n row[col[i][0]] = col[i][1]; \n \n }\n \n return row;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the array of inspiration ids to check if the current image has been saved or not | function check_set_save_inspirations(current_img_id,save_img_btn) {
$.post(RELATIVE_PATH + '/config/processing.php',{form : 'Inspiration Sidebar Saved Arr'}, function(data) {
// alert(current_img_id);
if ($.inArray(current_img_id, data) !== -1)
{
$(save_img_btn).text('Saved');
}else{
$(save_img_btn).text('Save');
}
},'json');
} | [
"infoResponseIsInStore() {\n const responses = this.currentInfoResponses();\n if (responses.length === this.imageServiceIds().length) {\n return true;\n }\n return false;\n }",
"currentInfoResponses() {\n const { infoResponses } = this.props;\n\n return this.imageServiceIds().map(imageId => (\n infoResponses[imageId]\n )).filter(infoResponse => (infoResponse !== undefined\n && infoResponse.isFetching === false\n && infoResponse.error === undefined));\n }",
"function findImgId(e) {\n setPicId(e.target.id);\n handleShow();\n }",
"function getSelectedImagesId() {\n var imageIds = [];\n $( '#sortable > li' ).each( function() {\n imageIds.push( $( this ).attr( 'data-id' ) );\n });\n return imageIds;\n }",
"function getSelectedImg() {\n return gImgs.find(img => img.id === gMeme.selectedImgId)\n}",
"getPhotoIDs(placeDetails) {\r\n let photoIDs = [];\r\n if (placeDetails.hasOwnProperty('photos')) {\r\n for (var i = 0; i < placeDetails.photos.length; i++) {\r\n photoIDs.push(placeDetails.photos[i].photo_reference);\r\n }\r\n }\r\n return photoIDs;\r\n }",
"function update_active_image_id() {\n var active_img = document.getElementsByClassName(\"big\")[0];\n try {\n active_img_id = active_img.getAttribute('data-img-id');\n } catch (err) {};\n\n }",
"function getMarketoFormIds() {\r\n\t\tvar idArray = [];\r\n\t\t\r\n\t\tfor(var x in _self.form.getValues()) {\r\n\t\t\tidArray.push(x);\r\n\t\t}\r\n\t\treturn idArray;\r\n\t}",
"async function _extract_image_ids (variants){\n if (variants.length == 0 || typeof variants === 'undefined' || variants === null || !Array.isArray(variants)){\n throw new VError(`variants parameter not usable`);\n }\n\n let ids = [];\n\n /*\n * Defaults to plucking the first image. This is fine now but in a future where\n * variants may have multiple images we'll need to do better\n */\n\n for (let i = 0; i < variants.length; i++){\n if (variants[i].image_ids.length > 0){\n ids.push(variants[i].image_ids[0]);\n }\n }\n\n return ids;\n}",
"function saveImageClasses(){\n //saves all images data to local storage\n //if local storage exists and they images haven't been saved\n if(localStorage && !imagesSaved) {\n localStorage.setItem('images', JSON.stringify(images));\n imagesSaved = true;\n }else if(imagesSaved){\n console.log('Image Data: already saved');\n }else{\n alert('There was a problem saving to local storage');\n }\n}",
"function collectClicked() {\n\t\tvar insulaIdsOfClicked = [];\n\t\tvar propertyIdsOfClicked = [];\n\t\tvar selectedInsulae = getUniqueClicked();\n\t\tvar length = selectedInsulae.length;\n\t\tfor (var i=0; i<length; i++) {\n\t\t\tvar property = selectedInsulae[i];\n\t\t\tif (property.feature.properties.Property_Id != undefined){\n\t\t\t\tvar propertyID = property.feature.properties.Property_Id;\n\t\t\t\tpropertyIdsOfClicked.push(propertyID);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tvar insulaID = property.feature.properties.insula_id;\n\t\t\t\tinsulaIdsOfClicked.push(insulaID);\n\t\t\t}\n\t\t}\n\t\treturn [insulaIdsOfClicked, propertyIdsOfClicked];\n\t}",
"getSavedImagesFromLocalStorage() {\n this.savedImagesInLocalStorage = [];\n\n const partialStorageArray = this.getPartialStorageArray();\n\n if (partialStorageArray.length > 0) {\n const finalArray = [];\n partialStorageArray.forEach((jsonImageInfo) => {\n const imageInfo = JSON.parse(jsonImageInfo);\n finalArray.push(imageInfo);\n });\n\n this.savedImagesInLocalStorage = finalArray.reverse();\n }\n }",
"getInterestIDsByType(userID) {\n const user = this._collection.findOne({ _id: userID });\n const interestIDs = [];\n interestIDs.push(user.interestIDs);\n let careerInterestIDs = [];\n _.map(user.careerGoalIDs, (goalID) => {\n const goal = CareerGoals.findDoc(goalID);\n careerInterestIDs = _.union(careerInterestIDs, goal.interestIDs);\n });\n careerInterestIDs = _.difference(careerInterestIDs, user.interestIDs);\n interestIDs.push(careerInterestIDs);\n return interestIDs;\n }",
"function getIds() {\n\tlet ids = []\n\tlet mdls = document.getElementsByClassName('modal')\n\tlet idPrefix = \"product-modal \"\n\tfor (i = 0; i < mdls.length; i++) {\n\t\tlet id = mdls[i].id\n\t\tid = id.slice(idPrefix.length, id.length)\n\t\tids.push(id)\n\t}\n\treturn ids\n}",
"isSaved(id) {\n if ( id in this.state.savedItems ) {\n return true\n }\n else {\n return false\n }\n }",
"function hasImage(attId) {\n var yes;\n var url = getBaseUrl() + \"colorswatch/index/isdir/\";\n jQuery.ajax(url, {\n async: false,\n method: \"post\",\n data: {\n dir: attId,\n },\n success: function (data) {\n yes = JSON.parse(data).yes;\n },\n });\n return yes;\n}",
"hasSaved(cardId) {\n\n for(const card of this.user.savedCards){\n\n if(card.cardID == cardId)return true;\n\n }\n return false;\n }",
"function matchImageswithEvents(images, id) {\n for (let i = 0; i < images.length; i++) {\n if (id === images[i].id) {\n let artistImage = images[i].url;\n return artistImage;\n }\n }\n}",
"function getCurrentImages () {\n\t\treturn Array.from(document.getElementsByClassName('img')).map(function(target){\n\t\t\treturn getImgExtension(target);\n\t\t});\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deselect a single seat | function deselectSeat (id) {
if (parseInt(numSeats) === 1) {
firebase.database().ref('/Saler/' + settings.salNummer + '/Personer/' + sessionId).remove()
removeGreenBoxes()
}
_selected = $.grep(_selected, function (item) {
return item !== id
})
var _seatObj = _seats.filter(function (seat) {
return seat.id === id
})
// Endrar status til at setet ikkje er reservert.
_seatObj[0].selected = false
_seatObj[0].notavailable = false
// Oppdaterar databasen.
var dbRef = firebase.database().ref('/Saler/' + settings.salNummer + '/Plassering/' + _seatObj[0].id)
dbRef.transaction(function (sete) {
if (sete) {
sete.id = _seatObj[0].id
sete.reservert = false
sete.booked = false
sete.label = _seatObj[0].label
sete.sessionId = null
} else {
console.log('Feilmelding for transaksjon')
}
return sete
})
settings.seterReservert--
let resSeterRef = firebase.database().ref('/Saler/' + settings.salNummer + '/Sal_Info/')
resSeterRef.child('SeterReservert').set(settings.seterReservert)
resSeterRef.child('SisteOppdatering').set(firebase.database.ServerValue.TIMESTAMP)
} | [
"deselect() {\n if (this.selected != null) {\n this.selected.deselect();\n this.selected = null;\n }\n }",
"function deselectStars() {\n star1.animations.stop(null, true);\n star1.animations.paused = true;\n star1 = null;\n star2.animations.stop(null, true);\n star2.animations.paused = true;\n star2 = null;\n }",
"removeSeat(e) {\n // retrieve the index through the data attribute\n const { target } = e;\n const seatIndex = target.getAttribute('data-index');\n // update the state removing the selected item\n const { seats: prevSeats } = this.state;\n const index = Number.parseInt(seatIndex, 10);\n const seats = [...prevSeats.slice(0, index), 'available', ...prevSeats.slice(index + 1)];\n\n this.updateState(seats);\n }",
"function unselectCurrentPlayer () {\r\n that.isSelected = false;\r\n this.unhighlightStates();\r\n this.removeClass('selected');\r\n }",
"function unselectByClick() {\n var points = this.getSelectedPoints();\n if (points.length > 0) {\n Highcharts.each(points, function (point) {\n point.select(false, true);\n });\n }\n }",
"function removeSelected(sel){\n if (isNode(sel))\n {\n graph.removeNode(sel)\n }\n else if (isEdge(sel))\n {\n graph.removeEdge(sel)\n } \n selected = undefined\n repaint()\n }",
"function selectSeat(planseat) {\r\n\t\tif( classie.has(planseat, 'row-seat-reserved') ) {\r\n\t\t\treturn false\r\n\t\t}\r\n\t\tif( classie.has(planseat, 'row-seat-selected') ) {\r\n\t\t\tclassie.remove(planseat, 'row-seat-selected')\r\n\t\t\treturn false\r\n\t\t}\r\n\t\tclassie.add(planseat, 'row-seat-selected')\r\n\r\n\t\t// the real seat\r\n\t\tvar seat = seats[ticketSeats.indexOf(planseat)]\r\n\t\t// show the seat´s perspective\r\n\t\tpreviewSeat(seat)\r\n\t}",
"function unselectFeature() {\n if (highlight) {\n highlight.remove();\n }\n }",
"deselect(option) {\n this.deselectValue(option.value);\n }",
"deselectAnnotation() {\n if (this.activeAnnotation) {\n this.activeAnnotation.setControlPointsVisibility(false);\n this.activeAnnotation = false;\n }\n }",
"function deselectAll() {\n selected = 0;\n\n let selectedCards = qsa(\".selected\");\n let i;\n for (i = 0; i < selectedCards.length; i++) {\n selectedCards[i].classList.remove(\"selected\");\n }\n }",
"function render_deselect(context)\n{\n\tif(selection_coordinates != null)\n\t{\n\t\tstroke_tile(selection_coordinates.x, selection_coordinates.y, grid_color, context);\n\t}\n\trender_pivot(context);\n}",
"function deselectAction(prevId) {\n\t//we have to deal with jQuery bug, cannot select 'cz/psp/97'\n\tvar shortPrevIdAr = prevId.split('/');\n var shortPrevId = shortPrevIdAr[shortPrevIdAr.length-1];\n //deselect\n\t$(\".mp-clicked-\"+shortPrevId).addClass('mp-clicked-off');\n\t$(\".mp-clicked-\"+shortPrevId).removeClass('ui-state-highlight mp-clicked-on');\n\t$(\".mp-\"+shortPrevId).draggable({ disabled: false });\n\t$(\".mp-clicked-\"+shortPrevId).draggable({ disabled: false });\n}",
"deSelectAll() {\n this.set('isSelecting', false);\n this.deSelectBlocks();\n }",
"function clearSingleSelection() {\n if (current_mode !== mode.fixation) {\n console.log(\"Warning: request to clear single selection when not in fixation mode.\");\n return;\n }\n path.classed(\"dimmed\", false);\n focusOnNode(selected_singleNode, false);\n selected_singleNode = null;\n current_mode = mode.exploration;\n}",
"function unselect(self, value){\r\n var opts = self.options;\r\n var combo = self.combo;\r\n var values = combo.getValues();\r\n var index = $.inArray(value+'', values);\r\n if (index >= 0){\r\n values.splice(index, 1);\r\n setValues(self, values);\r\n opts.onUnselect.call(self, opts.finder.getRow(self, value));\r\n }\r\n }",
"function deselectDelegate(tblWidget, type, selected, deselect)\n{\n}",
"function unselectMarker () {\n\t\tif (ParkingService.data.selectedParking == null) return;\n\t\tif (ParkingService.data.selectedParking.id == null) return;\n\t\tconsole.log ('it was at least defined.');\n\t\tMapService.unselectMarker (ParkingService.data.selectedParking.id);\n\t\tconsole.log ('unselected marker ' + ParkingService.data.selectedParking.id);\n\t\t$scope.safeApply( function () { ParkingService.data.selectedParking = null; });\n\t}",
"function clearSelection() {\n currentPizza = undefined;\n $('input[name=\"e-item\"]').prop('checked', false);\n $('input[name=\"psize\"]').prop('checked', false);\n $(\".lists-wrapper\").hide();\n\n currentBeverage = undefined;\n $('input[name=\"bsize\"]').prop('checked', false);\n $(\".beverage-size-list\").hide();\n\n currentOrder = undefined;\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compares NFCPushOptions structures that were provided to API and received by the mock mojo service. | function assertNFCPushOptionsEqual(provided, received) {
if (provided.ignoreRead !== undefined)
assert_equals(provided.ignoreRead, !!+received.ignore_read);
else
assert_equals(!!+received.ignore_read, true);
if (provided.timeout !== undefined)
assert_equals(provided.timeout, received.timeout);
else
assert_equals(received.timeout, Infinity);
if (provided.target !== undefined)
assert_equals(toMojoNFCPushTarget(provided.target), received.target);
else
assert_equals(received.target, nfc.NFCPushTarget.ANY);
} | [
"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 }",
"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 assertNFCWatchOptionsEqual(provided, received) {\n if (provided.url !== undefined)\n assert_equals(provided.url, received.url);\n else\n assert_equals(received.url, '');\n\n if (provided.mediaType !== undefined)\n assert_equals(provided.mediaType, received.media_type);\n else\n assert_equals(received.media_type, '');\n\n if (provided.mode !== undefined)\n assert_equals(toMojoNFCWatchMode(provided.mode), received.mode);\n else\n assert_equals(received.mode, nfc.NFCWatchMode.WEBNFC_ONLY);\n\n if (provided.recordType !== undefined) {\n assert_equals(!+received.record_filter, true);\n assert_equals(toMojoNFCRecordType(provided.recordType),\n received.record_filter.record_type);\n }\n }",
"_verifyNoOptionValueCollisions() {\n this.options.changes.pipe(startWith(this.options), takeUntil(this.destroyed)).subscribe(() => {\n var _a;\n const isEqual = (_a = this.compareWith) !== null && _a !== void 0 ? _a : Object.is;\n for (let i = 0; i < this.options.length; i++) {\n const option = this.options.get(i);\n let duplicate = null;\n for (let j = i + 1; j < this.options.length; j++) {\n const other = this.options.get(j);\n if (isEqual(option.value, other.value)) {\n duplicate = other;\n break;\n }\n }\n if (duplicate) {\n // TODO(mmalerba): Link to docs about this.\n if (this.compareWith) {\n console.warn(`Found multiple CdkOption representing the same value under the given compareWith function`, {\n option1: option.element,\n option2: duplicate.element,\n compareWith: this.compareWith,\n });\n }\n else {\n console.warn(`Found multiple CdkOption with the same value`, {\n option1: option.element,\n option2: duplicate.element,\n });\n }\n return;\n }\n }\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 normalizeOptions(options) {\n options = options || {};\n return {\n concatMessages: options.concatMessages === undefined ? true : Boolean(options.concatMessages),\n format: options.format === undefined ? isomorphic_node_1.format\n : (typeof options.format === \"function\" ? options.format : false),\n };\n}",
"_mergeOptions(oldOptions, newOptions) {\n const origKeys = new Set(Object.keys(oldOptions))\n const mergedOptions = { ...oldOptions, ...newOptions }\n\n Object.keys(mergedOptions).forEach( (key) => {\n if (!origKeys.has(key)) {\n console.error(`Unexpected options parameter \"${key}\" will be removed. This should never happen - please investigate.`) // this should not happen\n }\n const value = mergedOptions[key]\n if (!origKeys.has(key) || !value || (Array.isArray(value) && value.length == 0)) delete mergedOptions[key];\n })\n return mergedOptions\n }",
"function checkCommitOptions(){\n\tvar allline = [];\n\tvar devices = getDevicesNodeJSON();\n\n\tfor(var t=0; t<devices.length ; t++){\n\t\tallline = gettargetmap(devices[t].ObjectPath,allline);\n\t}\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n\t\tvar prtArr =[];\n\t\tfor(var s=0;s < devices.length; s++){\n \t \tprtArr = getDeviceChildPort(devices[s],prtArr);\n\t\t}\n }else{\n var devices =devicesArr;\n\t\tvar prtArr= portArr;\n }\n\t\n\tfor(var a=0; a < devices.length;a++){\n\t\tif(devices[a].DeviceType.toLowerCase() == \"testtool\" || devices[a].DeviceType.toLowerCase() == \"dut\" && devices[a].Status.toLowerCase() != \"reserved\"){ \n\t\t\t$(\"#comOpDevSanityTr\").removeAttr(\"style\");\n\t\t\t$(\"#comOpAccSanityTr\").removeAttr(\"style\");\n\t\t\t$(\"#comOpStartResTr\").removeAttr(\"style\");\n\t\t\t$(\"#comOpEndResTr\").removeAttr(\"style\");\n\t\t}else{\n\t\t\t$(\"#comOpDevSanityTr\").css({\"display\":\"none\"});\n\t\t\t$(\"#comOpAccSanityTr\").css({\"display\":\"none\"});\n\t\t\t$(\"#comOpStartResTr\").css({\"display\":\"none\"});\n\t\t\t$(\"#comOpEndResTr\").css({\"display\":\"none\"});\n\n\t\t}\n\t\tif(devices[a].Status.toLowerCase() != \"reserved\" && allline.length > 0){\n\t\t\tif(devices[a].DeviceName == \"\"){\n\t\t\t\t$(\"#comOpConnectivityTr\").removeAttr(\"style\");\n\t\t\t}else{\n\t\t\t\t$(\"#comOpConnectivityTr\").css({\"display\":\"none\"});\n\t\t\t\t$(\"#comOpConnectivity\").prop('checked',false);\n\t\t\t\tfor(var b=0; b < prtArr.length; b++){\n\t\t\t\t\tif(prtArr[b].SwitchInfo != \"\"){\n\t\t\t\t\t\t$(\"#comOpConnectivityTr\").removeAttr(\"style\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(devices[a].Status.toLowerCase() != \"reserved\" && allline.length > 0 && devices[a].Model != \"3750\"){ \n\t\t\tvar dut= 0;var testool= 0;var others= 0;var all= 0;\n\t\t\tfor(var c=0; c < devices.length;c++){\n\t\t\t\tall++;\n\t\t\t\tif(devices[c].DeviceType.toLowerCase() == \"dut\"){\n\t\t\t\t\tdut++;\n\t\t\t\t}else if(devices[c].DeviceType.toLowerCase() == \"testtool\"){\n\t\t\t\t\ttestool++;\n\t\t\t\t}else{\n\t\t\t\t\tothers++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif((dut + testool) == all){\n\t\t\t\t$(\"#comOpLinkSanityTr\").removeAttr(\"style\");\n\t\t\t}else{\n\t\t\t\t$(\"#comOpLinkSanityTr\").css({\"display\":\"none\"});\n\t\t\t}\n\t\t}\n\t\tif(devices[a].Status.toLowerCase() != \"reserved\" && allline.length > 0 && devices[a].Model != \"3750\"){\n\t\t\tvar dut= 0;var testool= 0;var others= 0;var all= 0;var vlanVar =0;var vlansArr=\"\";\n for(var c=0; c < devices.length;c++){\n all++;\n if(devices[c].DeviceType.toLowerCase() == \"dut\"){\n dut++;\n\t\t\t\t}else if(devices[c].DeviceType.toLowerCase() == \"vlan\"){\n\t\t\t\t\tvlansArr = devices[c].ObjectPath;\n\t\t\t\t\tvlanVar++;\n\t\t\t\t}else{\n\t\t\t\t\tothers++;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(dut == all || dut >1){\n\t\t\t\tif(vlanVar == 0){\n\t\t\t\t\t$(\"#comOpEnaInterfaceTr\").removeAttr(\"style\");\n\t\t\t\t}else{\n\t\t\t\t\tvar vlanCtr=0;\n\t\t\t\t\tfor(var d=0; d < allline.length; d++){\n\t\t\t\t\t\tvar source = allline[d].Source;\n\t\t\t\t var destination = allline[d].Destination;\n\t\t\t\t var srcArr = source.split(\".\");\n\t\t\t\t\t\tvar srcObj = getDeviceObject2(srcArr[0]);\n\t\t\t\t var dstArr = destination.split(\".\");\n\t\t\t\t\t\tvar dstObj = getDeviceObject2(dstArr[0]);\n\t\t\t\t\t\tif(allline[d].Destination.split(\".\")[0] == vlansArr){\n\t\t\t\t\t\t\tif(srcObj.DeviceType.toLowerCase() == \"dut\"){\n\t\t\t\t\t\t\t\tvlanCtr++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}else if(allline[d].Source.split(\".\")[0] == vlansArr){\n\t\t\t\t\t\t\tif(dstObj.DeviceType.toLowerCase() == \"dut\"){\n\t\t\t\t\t\t\t\tvlanCtr++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(vlanCtr > 1){\n\t\t\t\t\t\t$(\"#comOpEnaInterfaceTr\").removeAttr(\"style\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\t$(\"#comOpEnaInterfaceTr\").css({\"display\":\"none\"});\n\t\t\t}\n\t\t}\n\t}\t\n}",
"getV3ProjectsIdRepositoryCompare(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 from = \"from_example\";*/ // String | The commit, branch name, or tag name to start compariso\n/*let to = \"to_example\";*/ // String | The commit, branch name, or tag name to stop comparison\napiInstance.getV3ProjectsIdReposiincomingOptions.toryCompare(incomingOptions.id, incomingOptions.from, to, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"static areIdentical(){\n let temp\n\n for(let i = 0; i < arguments.length; i++){\n let argument = arguments[i]\n\n // handle NaN\n if(isNaN(argument.h)) argument.h = argument.h.toString()\n if(isNaN(argument.m)) argument.m = argument.m.toString()\n\n // handle string input\n if(typeof argument.h === \"string\") argument.h = parseInt(argument.h)\n if(typeof argument.m === \"string\") argument.m = parseInt(argument.m)\n\n // if temp is empty -> this is the first argument, store the first temp\n if(!temp){\n temp = argument\n continue\n }\n\n // if the temp and the current argument are not identical, return false\n if(argument.h !== temp.h || argument.m !== temp.m || argument.pm !== temp.pm) return false\n\n // store the current argument as the new temp\n temp = argument\n }\n\n return true\n }",
"options(params) {\n if(!params) {\n return {\n provider: _currentProvider,\n customProvider: customProvider,\n depth: depth,\n weight: weight,\n spamSeed: spamSeed,\n message: message,\n tag: tag,\n numberOfTransfersInBundle: numberOfTransfersInBundle,\n isLoadBalancing: optionsProxy.isLoadBalancing\n }\n }\n if(params.hasOwnProperty(\"provider\")) {\n _currentProvider = params.provider\n initializeIOTA()\n }\n if(params.hasOwnProperty(\"customProvider\")) {\n customProvider = params.customProvider\n initializeIOTA()\n }\n if(params.hasOwnProperty(\"depth\")) { depth = params.depth }\n if(params.hasOwnProperty(\"weight\")) { weight = params.weight }\n if(params.hasOwnProperty(\"spamSeed\")) { spamSeed = params.spamSeed }\n if(params.hasOwnProperty(\"message\")) { message = params.message }\n if(params.hasOwnProperty(\"tag\")) { tag = params.tag }\n if(params.hasOwnProperty(\"numberOfTransfersInBundle\")) { numberOfTransfersInBundle = params.numberOfTransfersInBundle }\n if(params.hasOwnProperty(\"isLoadBalancing\")) { optionsProxy.isLoadBalancing = params.isLoadBalancing }\n if(params.hasOwnProperty(\"onlySpamHTTPS\")) { onlySpamHTTPS = params.onlySpamHTTPS }\n }",
"function performUnitTest() {\n\t// Scenario 1\n\tvar requestBody1 = {\n\t\tEmail: \"test4321@gmail.com\",\n\t\tPassword: \"Password\",\n\t\tAccessToken: \"AccessToken\",\n\t\tCompanyID: \"CompanyID\"\n\t};\n\tvar validateReaults1 = validateRequestBody(requestBody1, new CreateCompanyUserBody());\n\tconsole.log(\"Senario 1\", validateReaults1);\n\n\t// Scenario 2\n\tvar requestBody2 = {\n\t\tPassword: \"Password\",\n\t\tAccessToken: \"AccessToken\",\n\t\tCompanyID: \"CompanyID\"\n\t};\n\tvar validateReaults2 = validateRequestBody(requestBody2, new CreateCompanyUserBody());\n\tconsole.log(\"Senario 2\", validateReaults2);\n\n\t// Scenario 3\n\tvar requestBody3 = {\n\t\tAccessToken: \"AccessToken\",\n\t\tCompanyID: \"CompanyID\"\n\t};\n\tvar validateReaults3 = validateRequestBody(requestBody3, new CreateCompanyUserBody());\n\tconsole.log(\"Senario 3\", validateReaults3);\n\n\t// Scenario 4\n\tvar requestBody4 = {\n\t\tUserId: \"UserId\",\n\t\tPoint: \"Point\",\n\t\tPointType: \"PointType\",\n\t\tDateTime: \"DateTime\",\n\t\tStoreId: \"StoreId\"\n\t};\n\tvar options = {\n\t\toptionalAttributes: [\"CompanyId\"]\n\t};\n\tvar validateReaults4 = validateRequestBody(requestBody4, new RedeemPoint(), options);\n\tconsole.log(\"Senario 4\", validateReaults4);\n\n\t// Scenario 5\n\tvar requestBody5 = {\n\t\tPoint: \"Point\",\n\t\tPointType: \"PointType\",\n\t\tDateTime: \"DateTime\",\n\t\tStoreId: \"StoreId\"\n\t};\n\tvar options = {\n\t\toptionalAttributes: [\"CompanyId\", \"UserId\"]\n\t};\n\tvar validateReaults5 = validateRequestBody(requestBody5, new RedeemPoint(), options);\n\tconsole.log(\"Senario 5\", validateReaults5);\n\n\t// Scenario 6\n\tvar requestBody6 = {\n\t\tUserId: \"UserId\",\n\t\tPoint: \"Point\",\n\t\tPointType: \"PointType\",\n\t\tDateTime: \"DateTime\",\n\t\tStoreId: \"StoreId\"\n\t};\n\tvar options = {\n\t\toptionalAttributes: [\"CompanyId\", \"UserId\"]\n\t};\n\tvar validateReaults6 = validateRequestBody(requestBody6, new RedeemPoint(), options);\n\tconsole.log(\"Senario 6\", validateReaults6);\n\n\t// Scenario 7\n\tvar requestBody7 = {\n\t\tCompanyId: \"CompanyId\",\n\t\tUserId: \"UserId\",\n\t\tPoint: 10,\n\t\tPointType: \"PointType\",\n\t\tDateTime: \"DateTime\",\n\t\tStoreId: \"StoreId\"\n\t};\n\tvar options = {\n\t\tattributeType: {\n\t\t\t\"CompanyId\": \"string\",\n\t\t\t\"Point\": \"number\"\n\t\t}\n\t};\n\tvar validateReaults7 = validateRequestBody(requestBody7, new RedeemPoint(), options);\n\tconsole.log(\"Senario 7\", validateReaults7);\n\n\t// Scenario 8\n\tvar requestBody8 = {\n\t\tCompanyId: \"CompanyId\",\n\t\tPoint: 10,\n\t\tPointType: \"PointType\",\n\t\tDateTime: \"DateTime\",\n\t\tStoreId: \"StoreId\"\n\t};\n\tvar options = {\n\t\toptionalAttributes: [\"UserId\"],\n\t\tattributeType: {\n\t\t\t\"CompanyId\": \"string\",\n\t\t\t\"Point\": \"number\"\n\t\t}\n\t};\n\tvar validateReaults8 = validateRequestBody(requestBody8, new RedeemPoint(), options);\n\tconsole.log(\"Senario 8\", validateReaults8);\n\n\t// Scenario 9\n\tvar requestBody9 = {\n\t\tCompanyId: \"true\",\n\t\tPoint: 10,\n\t\tPointType: \"PointType\",\n\t\tDateTime: \"DateTime\",\n\t\tStoreId: \"StoreId\"\n\t};\n\tvar options = {\n\t\toptionalAttributes: [\"UserId\"],\n\t\tattributeType: {\n\t\t\t\"CompanyId\": \"boolean\",\n\t\t\t\"Point\": \"number\"\n\t\t}\n\t};\n\tvar validateReaults9 = validateRequestBody(requestBody9, new RedeemPoint(), options);\n\tconsole.log(\"Senario 9\", validateReaults9);\n\n\t// Scenario 10\n\tvar requestBody10 = {\n\t\tCompanyId: \"false\",\n\t\tPoint: 10,\n\t\tPointType: \"PointType\",\n\t\tDateTime: \"1990-08-10 20:30\",\n\t\tStoreId: \"StoreId\"\n\t};\n\tvar options = {\n\t\toptionalAttributes: [\"UserId\"],\n\t\tattributeType: {\n\t\t\t\"CompanyId\": \"boolean\",\n\t\t\t\"Point\": \"number\",\n\t\t\t\"DateTime\": \"date\"\n\t\t}\n\t};\n\tvar validateReaults10 = validateRequestBody(requestBody10, new RedeemPoint(), options);\n\tconsole.log(\"Senario 10\", validateReaults10);\n\n\t// Scenario 11\n\tvar requestBody11 = {\n\t\tCompanyId: \"false\",\n\t\tPoint: 10,\n\t\tPointType: \"PointType\",\n\t\tDateTime: \"eewew\",\n\t\tStoreId: \"StoreId\"\n\t};\n\tvar options = {\n\t\toptionalAttributes: [\"UserId\"],\n\t\tattributeType: {\n\t\t\t\"CompanyId\": \"boolean\",\n\t\t\t\"Point\": \"number\",\n\t\t\t\"DateTime\": \"date\"\n\t\t}\n\t};\n\tvar validateReaults11 = validateRequestBody(requestBody11, new RedeemPoint(), options);\n\tconsole.log(\"Senario 11\", validateReaults11);\n\n\tconsole.log(\"Unit test done.\");\n}",
"postV3ProjectsIdRepositoryCommitsShaCherryPick(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let sha = \"sha_example\";*/ // String | A commit sha to be cherry picke\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRepositoryCommitsShaCherryPick(incomingOptions.id, incomingOptions.sha, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"function getBumperOptions() {\n return __awaiter(this, void 0, void 0, function* () {\n const optionsFile = core.getInput('options-file');\n const scheme = core.getInput('scheme');\n const skip = core.getInput('skip');\n const customScheme = core.getInput('custom-scheme');\n const versionFile = core.getInput('version-file');\n const files = core.getInput('files');\n const rules = core.getInput('rules');\n const username = core.getInput('username');\n const email = core.getInput('email');\n let error = \"\"; // error message\n let bumperOptions = {};\n let err = (message) => {\n console.error(message);\n error += message + '\\n';\n };\n if (optionsFile && !fs.existsSync(optionsFile)) {\n console.warn(`Options file with path ${optionsFile} does not exist`);\n // error += `Options file with path ${optionsFile} does not exist\\n`;\n }\n else if (optionsFile && fs.existsSync(optionsFile)) {\n try {\n bumperOptions = JSON.parse(yield fs.readFileSync(optionsFile, { encoding: 'utf8', flag: 'r' }));\n }\n catch (e) {\n console.warn(`Error reading or parsing bumper options file with path ${optionsFile}\\n${e}`);\n }\n }\n if (scheme)\n bumperOptions.scheme = scheme;\n else if (!scheme && (!bumperOptions.hasOwnProperty('scheme')\n || !bumperOptions.scheme\n || bumperOptions.scheme.trim() === \"\")) {\n err(\"Scheme is not defined in option file or workflow input.\");\n }\n if (customScheme && customScheme.trim() !== \"\") {\n bumperOptions.scheme = \"custom\";\n bumperOptions.schemeDefinition = customScheme;\n }\n try {\n bumperOptions.schemeDefinition = getSchemeDefinition(bumperOptions);\n }\n catch (e) {\n err(e);\n }\n if (versionFile && versionFile.trim() !== '') {\n try {\n bumperOptions.versionFile = JSON.parse(versionFile);\n }\n catch (e) {\n // console.log(e.message);\n bumperOptions.versionFile = { path: versionFile };\n }\n }\n else if (!bumperOptions.hasOwnProperty('versionFile')\n || !bumperOptions.versionFile\n || (bumperOptions.versionFile instanceof String && bumperOptions.versionFile.trim() === \"\")) {\n err(\"Version file is not defined in option file or workflow input.\");\n }\n else {\n bumperOptions.versionFile = normalizeFiles([bumperOptions.versionFile])[0];\n }\n if (files && files.trim() !== '') {\n try {\n const filesArray = JSON.parse(files);\n if (!Array.isArray(filesArray)) {\n err(\"Files should be in array stringified JSON format\");\n }\n else\n bumperOptions.files = normalizeFiles([bumperOptions.versionFile, ...filesArray]);\n }\n catch (e) {\n err(\"Files not in JSON format\");\n }\n }\n else if (!bumperOptions.hasOwnProperty('files')\n || !bumperOptions.files\n || !Array.isArray(bumperOptions.files)) {\n err(\"Files are not defined in option file or workflow input.\");\n }\n else\n bumperOptions.files = normalizeFiles([bumperOptions.versionFile, ...bumperOptions.files]);\n if (rules && rules.trim() !== '') {\n try {\n const rulesArray = JSON.parse(rules);\n if (!Array.isArray(rulesArray)) {\n err(\"Rules should be in array stringified JSON format\");\n }\n else\n bumperOptions.rules = rulesArray;\n }\n catch (e) {\n err(\"Rules not in JSON format\");\n }\n }\n else if (!bumperOptions.hasOwnProperty('rules')\n || !bumperOptions.rules\n || !Array.isArray(bumperOptions.rules)) {\n err(\"Rules are not defined in option file or workflow input.\");\n }\n if (skip)\n bumperOptions.skip = skip;\n if (username)\n bumperOptions.username = username;\n if (email)\n bumperOptions.email = email;\n if (error !== \"\")\n throw new Error(error);\n else {\n console.log(JSON.stringify(bumperOptions));\n return bumperOptions;\n }\n });\n}",
"getV3ProjectsIdRepositoryCommitsShaDiff(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let sha = \"sha_example\";*/ // String | A commit sha, or the name of a branch or tag\napiInstance.getV3ProjectsIdRepositoryCommitsShaDiff(incomingOptions.id, incomingOptions.sha, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"static repoDiff (\n workingDir,\n repoPath,\n zipPath,\n commitHashFrom,\n commitHashTo = 'head',\n _exec = ['npm install --production'],\n removeWorkingDirWhenDone = true,\n debug = false\n ) {\n this.lastLogTime = 0\n let l = debug ? this.log : () => 1\n return new Promise((resolve, reject) => {\n l('Removing workingDir if it exists', workingDir)\n rimraf(workingDir, (err) => {\n if (err) { reject(err); return }\n l('Creating empty workingDir', workingDir)\n fs.mkdirSync(workingDir)\n l('Cloning repo into workingDir', repoPath)\n exec(`git clone ${repoPath}`, {cwd: workingDir}, (err, stdOut) => {\n if (err) { reject(err); return }\n let folderA = path.join(workingDir, (fs.readdirSync(workingDir))[0])\n let folderB = folderA + '_b'\n l('Repo cloned to', folderA)\n l('Copying cloned repo to', folderB)\n ncp(folderA, folderB, (err) => {\n if (err) { reject(err); return }\n l('Checking out ', commitHashFrom, ' to folder ', folderA)\n exec(`git checkout ${commitHashFrom}`, {cwd: folderA}, (err, stdOut) => {\n if (err) { reject(err); return }\n l('Checking out ', commitHashFrom, ' to folder ', folderB)\n exec(`git checkout ${commitHashTo}`, {cwd: folderB}, (err, stdOut) => {\n if (err) { reject(err); return }\n let co = 0\n while (_exec.length) {\n co += 2\n let e = _exec.shift()\n l('Executing ', e, ' in folder ', folderA)\n exec(e, {cwd: folderA}, (err) => {\n if (err) { reject(err); return }\n co--\n if (co === 0) { go(zipPath, folderA, folderB) }\n })\n l('Executing ', e, ' in folder ', folderB)\n exec(e, {cwd: folderB}, (err) => {\n if (err) { reject(err); return }\n co--\n if (co === 0) { go(zipPath, folderA, folderB) }\n })\n }\n })\n })\n })\n })\n let go = async (zipPath, folderA, folderB) => {\n let err\n let m = await this.create(zipPath, folderA, folderB, debug, true).catch((e) => { err = e })\n if (err) { reject(err); return }\n if (removeWorkingDirWhenDone) {\n l('Removing workingDir', workingDir)\n rimraf(workingDir, (err) => {\n if (err) { reject(err) }\n l('Zip creation from repo done')\n resolve(m)\n })\n } else {\n l('Zip creation from repo done')\n resolve(m)\n }\n }\n })\n })\n }",
"optionsForCountry(country) {\n if (!country || !SHIPPING_OPTIONS.hasOwnProperty(country)) {\n country = 'international';\n }\n let options = SHIPPING_OPTIONS[country];\n // Sort by price, lowest first\n options.sort((a, b) => {\n return a.price - b.price;\n });\n return options;\n }",
"checkUnknownOptions() {\n const { rawOptions, globalCommand } = this.cli;\n if (!this.config.allowUnknownOptions) {\n for (const name of Object.keys(rawOptions)) {\n if (name !== '--' &&\n !this.hasOption(name) &&\n !globalCommand.hasOption(name)) {\n console.error(`error: Unknown option \\`${name.length > 1 ? `--${name}` : `-${name}`}\\``);\n process.exit(1);\n }\n }\n }\n }",
"function hashOptions(options) {\r\n\toptions = options || {};\r\n\treturn JSON.stringify(options);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
isListWithDateIdPresent() Check if List with Date ID already present in the DOM 1. If yes, append the new task 2. If no, render a new list with all the tasks | function isListWithDateIdPresent(dateid){
_existingList = document.querySelector(`ul[date-id='${dateid}']`);
return Boolean(_existingList);
} | [
"function loadTasksForDate(node, date, jsonData) {\r\n // Store/Convert the date item into a string item\r\n var dateS = date.getUTCFullYear() + \"-\" + (date.getUTCMonth()+1) + \"-\" + (date.getUTCDate());\r\n var listItem;\r\n\r\n // Iterate through each task associated with the date, appending just the title as a list item into the date box\r\n for (task in jsonData[dateS]) {\r\n listItem = document.createElement(\"LI\");\r\n listItem.appendChild(document.createTextNode(jsonData[dateS][task].title));\r\n \r\n if (jsonData[dateS][task].checked == \"true\") {\r\n listItem.style.display = \"none\"; // Hide in date object this task (but kept in for date selection the data isn't lost)\r\n }\r\n\r\n node.appendChild(listItem);\r\n }\r\n \r\n}",
"loadList(listId) {\n //finds list\n let listIndex = -1;\n for (let i = 0; (i < this.toDoLists.length) && (listIndex < 0); i++) {\n if (this.toDoLists[i].id === listId)\n listIndex = i;\n }\n //loads this list\n if (listIndex >= 0) {\n let listToLoad = this.toDoLists[listIndex];\n this.setCurrentList(listToLoad);\n //this.currentList = listToLoad;//change to set current list\n this.view.viewList(this.currentList);\n this.view.refreshLists(this.toDoLists);\n //set currentlist \n }\n this.tps.clearAllTransactions();\n this.buttonCheck();\n }",
"function insertTask(task, nodeList, daysRemaining) {\n for (i = 0; i < nodeList.length; i++) {\n var c = nodeList[i].getElementsByClassName(\"col-3 remove-padding text-center\");\n\n if ((c[0].innerText > daysRemaining)) {\n document.getElementById(\"taskList\").insertBefore(task, nodeList[i]);\n break;\n } else if (i == nodeList.length-1) {\n document.getElementById(\"taskList\").appendChild(task);\n }\n }\n}",
"function handleCreateFinished(list) {\n const finishedDay = new Date();\n const finishDate = `${finishedDay.getFullYear()}/${\n finishedDay.getMonth() + 1\n }/${finishedDay.getDate()}`;\n const li = document.createElement(\"li\");\n const del = document.createElement(\"span\");\n const date = document.createElement(\"span\");\n date.setAttribute(\"class\", \"finished-date\");\n date.innerHTML = finishDate;\n del.innerHTML = `<i class=\"far fa-trash-alt delbtn\"></i>`;\n del.addEventListener(\"click\", handleDelFinished);\n finishedToDo.appendChild(li);\n\n li.innerText = list;\n li.style.textDecoration = \"line-through\";\n\n li.id = finishedDos.length + 1;\n li.appendChild(del);\n li.appendChild(date);\n\n let finishedDosObj = {\n text: list,\n id: finishedDos.length + 1,\n finishedDate: finishDate,\n };\n\n finishedDos.push(finishedDosObj);\n checkFinished();\n saveFinished();\n}",
"function addToDOM(response) {\n $('#viewTasks').empty();\n for (const taskObj of response) {\n // Make a jQuery object of a table row and add the task values to that row.\n const appendStr = '<tr></tr>';\n const jQueryObj = $(appendStr);\n let appendRowStr = '';\n // Loop over every task in the table and add them to the DOM.\n for (const taskKey in taskObj) {\n const taskVal = taskObj[taskKey];\n // If the inputs match certain strings format them to look prettier.\n if (taskKey === 'task_id') {\n // The (arbitrary) \"id\" column is the unique identifier for the current task in\n // the table so embed that which allows updates to be made later.\n $(jQueryObj).attr(dataID, taskVal);\n } else if (taskKey === 'completed') {\n if (taskVal === true) {\n appendRowStr += '<td><input type=\"checkbox\" class=\"toggleCompleted\" checked></td>';\n // Add a class for display purposes and a arbitrary value for whether or not\n // a task has been read into the html data.\n $(jQueryObj).addClass(cssCompleted).attr(dataCompleted, true);\n } else {\n appendRowStr += '<td><input type=\"checkbox\" class=\"toggleCompleted\"></td>';\n $(jQueryObj).addClass(cssNotCompleted).attr(dataCompleted, false);\n }\n } else if (taskKey === 'due' && taskVal !== null) {\n // TODO format date correctly.\n appendRowStr += `<td>${(moment(taskVal).format('YYYY/MM/DD, hh:mm a'))}</td>`;\n } else if (taskVal === null) {\n appendRowStr += '<td></td>';\n } else {\n // The current taskKey doesn't have a preset so just add verbatim whatever the\n // key and value is to the DOM.\n appendRowStr += `<td>${taskVal}</td>`;\n }\n }\n // Add a button for toggling if a task has been read and deleting a task which are then\n // updated in the table.\n const buttonText = '<button class=\"deleteTask\"> Delete </button>';\n $(jQueryObj.html(appendRowStr).append(buttonText));\n // Add this big long element to the tasks HTML table.\n $('#viewTasks').append(jQueryObj);\n }\n // Let jQuery know about the new buttons that have been added.\n updatejQuery();\n}",
"function callbackLoadTaskSuccess(listTask)\n{\n var tasks = [];\n \n listTask.forEach(function(task, index) {\n var taskOnCalendar = {\n id: task['id'],\n title: task['name'],\n start: task['start_date'],\n end: task['end_date'],\n status: task['status'],\n backgroundColor: getBackgroundStatus(task['status'])\n }\n tasks.push(taskOnCalendar);\n });\n \n $(\"#calendar\").fullCalendar('removeEvents'); \n $('#calendar').fullCalendar('addEventSource', tasks);\n $('#calendar').fullCalendar('rerenderEvents');\n \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 }",
"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}",
"function isWaitingListExisting() {\n\tvar waitingList = spaceExpressConsoleDrawing.employeesWaiting;\n\tif(waitingList.length > 0) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}",
"function checkIfnoTasks(){\n let noListItemsMessage = document.getElementById(\"no-tasks-msg\");\n noListItemsMessage.style.display = (tasks === 0) ? \"block\" : \"none\";\n}",
"function appendtoCategory($taskElement){\n $(\".message >span\").css('visibility', 'visible');\n const $task = $taskElement;\n $(\".listContainer\").on(\"click\", function(event){\n $.ajax({\n url: \"/tasks/\"+$($task).data('task-id')+\"?_method=PUT\",\n method: \"PUT\",\n data : {id: $($task).data(\"task-id\"), cat_id: $(event.target).siblings().data('id')},\n success: () => {\n $(\".message > span\").css('visibility', 'hidden');\n $(event.target).siblings().prepend($task);\n }\n });\n $(\".listContainer\").unbind();\n });\n }",
"function displayDoneList() {\n\n\tvar doneData = getFromSession(\"donelist\");\n var finalTemplate = \"\";\n var index;\n \n for(index = 0; index<doneData.length; index++) {\n \tfinalTemplate = finalTemplate + `<tr> \n \t\t<td align=\"left\" valign=\"top\" style=\"padding: 5px;\">${index+1}</td>\n \t\t<td align=\"left\" valign=\"top\" style=\"padding: 5px;\">${doneData[index].toDoTitle}</td>\n \t\t<td align=\"left\" valign=\"top\" style=\"padding: 5px;\">${doneData[index].toDoDescription}</td>\n \t\t<!--<td align=\"left\" valign=\"top\" style=\"padding: 5px;\">\n \t\t\t<input type=\"checkbox\" name=\"\">\n \t\t</td>-->\n \t</tr>`;\n }\n\n $(\"#table_doneList\").html(finalTemplate);\n\n if(doneData.length) {\n \t$(\"#p_nothingToShowInDone\").hide();\t\n } else {\n \t$(\"#p_nothingToShowInDone\").show();\t\n }\n}",
"async function addEventsList(id, eventsList) {\r\n eventsStore.update(state => {\r\n state[id] = eventsList;\r\n return state\r\n });\r\n // get the last element, which is the new event added\r\n var obj = eventsList.slice(-1)[0];\r\n await addEvent({...obj, timelineId: id});\r\n }",
"function loadStepList() {\n var id = $('#form').find('input[name=\"task_id\"]').val();\n if(!id) {\n return;\n }\n\n $.get('/task-steps/' + id, function(steps) {\n for(var i = 0; i < steps.length; i++) {\n appendStep(steps[i]);\n }\n });\n }",
"static loadProjectList() {\n let tasksDone = 0\n domSelectors.projectList.innerHTML = '';\n if (!didInit) DomInput.newProjectBtn();\n const library = ProjectLibrary.getSharedInstance();\n library.projectList.forEach(function (project) {\n\n const projectListItem = document.createElement('div');\n projectListItem.classList = 'projectListItem';\n projectListItem.setAttribute('id', `project${project.id}`);\n domSelectors.projectList.appendChild(projectListItem);\n project.taskList.forEach(function(task) {\n if (task.done) tasksDone++\n })\n if (tasksDone == project.taskList.length) projectListItem.style.opacity = '50%';\n tasksDone = 0;\n\n const projectName = document.createElement('div');\n projectName.classList = 'projectListName';\n projectName.setAttribute('id', `projectName${project.id}`);\n projectName.textContent = `${project.name}`;\n projectListItem.appendChild(projectName);\n\n const projectDeleteBtn = document.createElement('div');\n projectDeleteBtn.classList = 'projectDeleteBtn';\n projectDeleteBtn.setAttribute('id', `deleteBtn${project.id}`)\n projectDeleteBtn.textContent = 'X';\n projectListItem.appendChild(projectDeleteBtn);\n DomInput.removeProject(project);\n\n const projectDueDate = document.createElement('div');\n projectDueDate.classList = 'projectListDueDate';\n projectDueDate.textContent = `Due ${format(new Date(project.dueDate), 'MMM do, yyyy')}`;\n projectListItem.appendChild(projectDueDate);\n\n const projectPriority = document.createElement('div');\n projectPriority.classList = 'projectListPriority';\n if (project.priority == 3) projectPriority.style.backgroundColor = 'red';\n else if (project.priority == 2) projectPriority.style.backgroundColor = 'yellow';\n else if (project.priority == 1) projectPriority.style.backgroundColor = 'green';\n projectListItem.appendChild(projectPriority);\n\n DomInput.applyTaskListBtn(project);\n })\n didInit = true\n }",
"function isListNewer(versusModTime, list, targetDir)\n{\n for (var iItem=0; iItem < list.length; iItem++)\n {\n if(isItemNewer(versusModTime, targetDir + '/' + list[iItem], false))\n {\n return(1);\n }\n }\n return 0;\n}",
"function refreshDoneList(){\n //remove current done items\n doneTable = document.getElementById('done-table');\n while (doneTable.firstChild) {\n doneTable.removeChild(doneTable.firstChild);\n }\n\n user_id = document.getElementById('user-data').getAttribute(\"data-id\");\n doneListSpinner = document.getElementById('done-table-spinner');\n\n //show spinner\n doneListSpinner.innerHTML = `<i class=\"fa fa-refresh fa-spin\" style=\"font-size:24px\"/></i>`;\n\n //update button activation\n activateDoneGroupButtons();\n\n todoApiCall({'callName':'done' ,'request':{user_id, 'done':1}, method:'GET' });\n}",
"function showStravaActivities(){\n var lengthActivities = activities.length;\n if (lengthActivities > 0) {\n var listHTML = '<ul>';\n\n for (var i = 0; i < lengthActivities; ++i) {\n console.log(activities[i].id); \n listHTML += '<li>' + activities[i].name + \" - \" + activities[i].date + \" - \" + activities[i].id + '</li>';\n }\n\n listHTML += '</ul>';\n $( \".listActivities\" ).append( listHTML );\n }\n}",
"function addId(){ //Add ID to events, calendar and list\n var cal = document.getElementsByClassName(\"JScal\");\n var eventList = document.getElementsByClassName(\"JSeventList\");\n\n for (i = 0, length = eventList.length; i < length; i++) { //eventList or cal.lenght\n cal[i].href= \"#JSeventID_\" + (i + 1); //Add link to calendar\n eventList[i].id= \"JSeventID_\" + (i + 1); //Add id to list\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The user enters a POI search string which should be passed on to the service. Previous search results are removed. The search is automatically triggered after the user stopped typing for a certain period of time (DONE_TYPING_INTERVAL) | function handleSearchPoiInput(e) {
clearTimeout(typingTimerSearchPoi);
if (e.keyIdentifier != 'Shift' && e.currentTarget.value.length != 0) {
typingTimerSearchPoi = setTimeout(function() {
//empty search results
var resultContainer = document.getElementById('fnct_searchPoiResults');
while (resultContainer.hasChildNodes()) {
resultContainer.removeChild(resultContainer.lastChild);
}
var numResults = $('#zoomToPoiResults').get(0);
while (numResults.hasChildNodes()) {
numResults.removeChild(numResults.lastChild);
}
searchPoiAtts[3] = e.currentTarget.value;
var lastSearchResults = $('#searchPoi').attr('data-search');
theInterface.emit('ui:searchPoiRequest', {
query: e.currentTarget.value,
nearRoute: searchPoiAtts[0] && routeIsPresent,
maxDist: searchPoiAtts[1],
distUnit: searchPoiAtts[2],
lastSearchResults: lastSearchResults
});
}, DONE_TYPING_INTERVAL);
}
} | [
"searchOnStopTyping() {\n let timer;\n scope.get(this).$watch(() => this.customerName, newVal => {\n // Remove results if search is deleted\n if (!newVal) {\n this.displayData.customerResults = [];\n if (timer) {\n timeout.get(this).cancel(timer);\n timer = null;\n }\n }\n if (timer) {\n timeout.get(this).cancel(timer);\n timer = null;\n }\n timer = timeout.get(this)(() => {\n if (this.customerName) {\n this.searchCustomers();\n }\n }, 250);\n });\n }",
"onSearchInput () {\n clearTimeout(this.searchDebounce)\n this.searchDebounce = setTimeout(async () => {\n this.searchOffset = 0\n this.searchResults = await this.search()\n }, 300)\n }",
"function handleSearchWaypointInput(e) {\n var waypointElement = $(e.currentTarget).parent().parent();\n //index of the waypoint (0st, 1st 2nd,...)\n var index = waypointElement.attr('id');\n clearTimeout(typingTimerWaypoints[index]);\n if (e.keyIdentifier != 'Shift' && e.currentTarget.value.length != 0) {\n var input = e.currentTarget.value;\n waypointElement.attr('data-searchInput', input);\n typingTimerWaypoints[index] = setTimeout(function() {\n //empty search results\n var resultContainer = waypointElement.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: waypointElement.get(0).getAttribute('data-search')\n });\n }, DONE_TYPING_INTERVAL);\n }\n }",
"function handleSearch(){\n var term = element( RandME.ui.search_textfield ).value;\n if(term.length){\n requestRandomGif( term, true);\n }\n}",
"function do_search() {\n var query = input_box.val().toLowerCase();\n\n if (query && query.length) {\n if (selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if (query.length >= settings.minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function () {\n run_search(query);\n }, settings.searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }",
"function callAjaxSearch() {\n\n searchTerm = $(settings.input).val();\n\n //No term - clear results\n if (searchTerm == \"\") {\n\n clear();\n resetPage();\n updateUI();\n\n\n }\n //Different term than last time - clear everything and start search\n else if (searchTerm != lastTerm) {\n\n clear();\n resetPage();\n search();\n\n }\n //Same term but different page - append content (if infinite scroll is active)\n else if (currentPage != lastPage) {\n\n if (!settings.infiniteScroll) {\n\n clear();\n }\n\n search();\n\n }\n\n\n timer = setTimeout(function(){callAjaxSearch()}, settings.delay);\n }",
"function srQuery(container, search, replace, caseSensitive, wholeWord) {\r if (search) {\r var args = getArgs(caseSensitive, wholeWord);\r rng = document.body.createTextRange();\r rng.moveToElementText(container);\r clearUndoBuffer();\r while (rng.findText(search, 10000, args)) {\r rng.select();\r rng.scrollIntoView();\r if (confirm(\"Replace?\")) {\r rng.text = replace;\r pushUndoNew(rng, search, replace);\r }\r rng.collapse(false) ;\r } \r }\r}",
"function searchSpecific() {\n var editor = getEditor();\n var query = getSelectedText(editor);\n var docsets = getDocsets();\n var dash = new dash_1.Dash(OS, getDashOption());\n child_process_1.exec(dash.getCommand(query, docsets));\n}",
"function search() {\n\t\tvar searchVal = searchText.getValue();\n\n\t\tsources.genFood.searchBar({\n\t\t\targuments: [searchVal],\n\t\t\tonSuccess: function(event) {\n\t\t\t\tsources.genFood.setEntityCollection(event.result);\n\t\t\t},\n\t\t\tonError: WAKL.err.handler\n\t\t});\n\t}",
"function do_search() {\n var query = input_box.val();\n\n if((query && query.length) || !$(input).data(\"settings\").minChars) {\n if(selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if(query.length >= $(input).data(\"settings\").minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function(){\n run_search(query);\n }, $(input).data(\"settings\").searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }",
"function checkParcelSearchInput(defaultTextInput){\n\tvar inputTextVal = jQuery('.ptSearchCriteriaDiv').find('.ghostText').val();\n\tvar term=trim(inputTextVal);\n\tif (term!=defaultTextInput){ \n\t\tcallSearchParcel();\n\t} else {\n\t\treturn false;\n\t}\n}",
"function handleSearchTerm(event) {\n setSearchTerm(event.target.value);\n }",
"function handleSearchAddressInput(e) {\n clearTimeout(typingTimerSearchAddress);\n if (e.keyIdentifier != 'Shift' && e.currentTarget.value.length !== 0) {\n typingTimerSearchAddress = setTimeout(function() {\n //empty search results\n var resultContainer = document.getElementById('fnct_searchAddressResults');\n while (resultContainer.hasChildNodes()) {\n resultContainer.removeChild(resultContainer.lastChild);\n }\n var numResults = $('#zoomToAddressResults').get(0);\n while (numResults.hasChildNodes()) {\n numResults.removeChild(numResults.lastChild);\n }\n var lastSearchResults = $('#searchAddress').attr('data-search');\n theInterface.emit('ui:searchAddressRequest', {\n address: e.currentTarget.value,\n lastSearchResults: lastSearchResults\n });\n }, DONE_TYPING_INTERVAL);\n }\n }",
"function search()\n{\n\tvar searchText = searchInput.value;\n\n\t// if input's empty\n\t// displaying everything\n\tif (searchText == \"\")\n\t{\n\t\tshowAllFilteredWordEntries();\n\t\treturn;\n\t}\n\n\t// hiding everything except the matched words\n\tfor (let i = 0; i < loadedData.length; i++)\n\t{\n\t\tlet entry = getFilteredWordEntry(i);\n\t\tvar regx = new RegExp(searchText);\n\t\tif (regx.test(loadedData[i]))\n\t\t\tentry.hidden = false;\n\t\telse\n\t\t\tentry.hidden = true;\n\t}\n}",
"function perform_search() {\n if (lastSearchType == \"D\") {\n searchHistory();\n } else if (lastSearchType == \"E\") {\n searchEpg();\n }\n }",
"searchBarOnKeyPress(e){\n if(e.key === 'Enter'){\n this.searchForDomain();\n e.target.value = '';\n }\n }",
"if (value.length === 0) {\n this.cancelAllSearchRequests();\n }",
"function clear_searchstring()\r\n{\r\n control_sound_exit();\r\n control_canvas_status_search = 1;\r\n searchstring = \"\";\r\n search_sounds = false;\r\n search_images = false;\r\n performclear();\r\n drawControl();\r\n}",
"stopSearching() {\n\t\tthis.liveCounter = this.livePandaUIStr.length + ((MySearchUI.searchGStats && MySearchUI.searchGStats.isSearchOn()) ? this.liveSearchUIStr.length : 0);\n\t\tif (this.timerUnique && this.liveCounter === 0) { if (MySearchTimer) MySearchTimer.deleteFromQueue(this.timerUnique); this.timerUnique = null; }\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use the query and fields to search for documents and view the first document returned. | searchDocuments() {
let searchObj = {}
if (this.searchType === 'query') {
searchObj.query = this.query;
} else if (this.searchType === 'field') {
searchObj.fieldCode = this.queryField;
searchObj.fieldValue = this.queryFieldValue;
}
this.etrieveViewer.Etrieve.searchDocuments(searchObj)
.catch(err => {
console.error(err);
});
} | [
"async getSingleDoc(mongoUri, dbName, coll) {\n const client = await MongoClient.connect(mongoUri, { useNewUrlParser: true});\n const doc = await client.db(dbName).collection(coll).find().toArray().then(docs => docs[0]);\n logger.collectionSingle(doc, dbName, coll);\n client.close();\n }",
"async show({ request }) {\n\t\treturn Term.query()\n\t\t\t.getTerm(request.params.id)\n\t\t\t.withParams(request.params)\n\t\t\t.firstOrFail();\n\t}",
"search(config, options) {\n let documents = [];\n const selector = {\n $distinct: { vpath: 1 }\n };\n if (options.pathmatch) {\n if (typeof options.pathmatch === 'string') {\n selector.vpath = new RegExp(options.pathmatch);\n } else if (options.pathmatch instanceof RegExp) {\n selector.vpath = options.pathmatch;\n } else {\n throw new Error(`Incorrect PATH check ${options.pathmatch}`);\n }\n }\n if (options.renderpathmatch) {\n if (typeof options.renderpathmatch === 'string') {\n selector.renderPath = new RegExp(options.renderpathmatch);\n } else if (options.renderpathmatch instanceof RegExp) {\n selector.renderPath = options.renderpathmatch;\n } else {\n throw new Error(`Incorrect PATH check ${options.renderpathmatch}`);\n }\n }\n if (options.mime) {\n if (typeof options.mime === 'string') {\n selector.mime = { $eeq: options.mime };\n } else if (Array.isArray(options.mime)) {\n selector.mime = { $in: options.mime };\n } else {\n throw new Error(`Incorrect MIME check ${options.mime}`);\n }\n }\n if (options.layouts) {\n if (typeof options.layouts === 'string') {\n selector.docMetadata = {\n layout: { $eeq: options.layouts }\n }\n } else if (Array.isArray(options.layouts)) {\n selector.docMetadata = {\n layout: { $in: options.layouts }\n }\n } else {\n throw new Error(`Incorrect LAYOUT check ${options.layouts}`);\n }\n }\n let coll = this.getCollection(this.collection);\n let paths = coll.find(selector, {\n vpath: 1,\n $orderBy: { renderPath: 1 }\n });\n for (let p of paths) {\n let info = this.find(p.vpath);\n documents.push(info);\n }\n\n if (options.tag) {\n documents = documents.filter(doc => {\n if (!doc.metadata) return false;\n return (doc.metadata.tags.includes(options.tag))\n ? true : false;\n });\n }\n\n if (options.rootPath) {\n documents = documents.filter(doc => {\n return (doc.renderPath.startsWith(options.rootPath))\n ? true : false;\n });\n }\n\n if (options.glob) {\n documents = documents.filter(doc => {\n return minimatch(doc.vpath, options.glob);\n });\n }\n\n if (options.renderglob) {\n documents = documents.filter(doc => {\n return minimatch(doc.renderPath, options.renderglob);\n });\n }\n\n if (options.renderers) {\n documents = documents.filter(doc => {\n if (!options.renderers) return true;\n let renderer = config.findRendererPath(doc.vpath);\n for (let renderer of options.renderers) {\n if (renderer instanceof renderer) {\n return true;\n }\n }\n return false;\n });\n }\n\n if (options.filterfunc) {\n documents = documents.filter(doc => {\n return options.filterfunc(config, options, doc);\n });\n }\n\n return documents;\n }",
"function searchSpecific() {\n var editor = getEditor();\n var query = getSelectedText(editor);\n var docsets = getDocsets();\n var dash = new dash_1.Dash(OS, getDashOption());\n child_process_1.exec(dash.getCommand(query, docsets));\n}",
"getOne(params) {\n return new Promise((resolve, reject) => {\n this.Model.findOne(this.getParams(params)).exec((err, doc) => {\n if (err) {\n reject({ ok: false, err });\n }\n resolve({ ok: true, data: doc });\n });\n });\n }",
"async queryRecord(store, type, query) {\n let upstreamQuery = Ember.assign({}, query);\n upstreamQuery.page = { size: 1 };\n let response = await this._super(store, type, upstreamQuery);\n if (!response.data || !Array.isArray(response.data) || response.data.length < 1) {\n throw new DS.AdapterError([ { code: 404, title: 'Not Found', detail: 'branch-adapter queryRecord got less than one record back' } ]);\n }\n let returnValue = {\n data: response.data[0],\n };\n if (response.meta){\n returnValue.meta = response.meta;\n }\n return returnValue;\n }",
"function search()\n{\n //Show 10 hits\n return client.search({\n index: \"suv\",\n type: 'suv',\n body: {\n sort: [{ \"volume\": { \"order\": \"desc\" } }],\n size: 10,\n }\n });\n}",
"function getOneAuthor(req, res) {\n Author.findById(req.params.authorId, function(err, foundAuthorFromDb) {\n Book.find({author: foundAuthorFromDb._id}, function(err, allBooksByFoundAuthorFromDb) {\n res.render('authorsViews/show', {\n authorReferenceForEJS: foundAuthorFromDb,\n authorsBooksReferenceForEJS: allBooksByFoundAuthorFromDb,\n title: foundAuthorFromDb.name\n })\n })\n })\n}",
"async index({ request }) {\n\t\tconst filters = request.all();\n\n\t\treturn Term.query()\n\t\t\t.withParams(request.params)\n\t\t\t.withFilters(filters)\n\t\t\t.fetch();\n\t}",
"getOne(req, res) {\n Request.findById({ _id: req.params.id })\n .then((request) => res.json(request))\n .catch((err) => res.status(400).json(err));\n }",
"static list(collection, filter={}) {\n return db.db.allDocs({include_docs: true});\n }",
"function itemFromCurrentQuery() {\n\tvar params = getSearchParameters();\n\tparams.title = dojo.byId(\"queryTitle\").value;\n\tparams.comment = dojo.byId(\"queryComment\").value;\n\tparams.query = dojo.byId(\"query\").value;\n\treturn params;\n}",
"function GetDocuments()\n{\n\t// specify criteria for document search\n\tvar Criteria =\n\t{\n\t\t// extensions should be fixed to image\n\t\tDocIds: [1001],\n\t\t//Extensions: new Array(\".jpg\", \".png\", \".gif\", \".bmp\"),\n\t\t//DocTypeIds: new Array(1, 2), // specify document type ids which you canget from GetDocumentTypes()\n\t\t//Titles: ['Addenda_15497_rpt_s15%.pdf', 'Addenda_10000_rpt_s15%.pdf'],\n\t\t//FolderIds: [3]\n\t ExcludeStatuses: [4,5]\n\n\t\t// specify job number\n\t\t//AttributeCriterias: {\n\t\t//\tAttributes:\t[{\n\t\t//\t\t\tValues: {\n\t\t//\t\t\t\tid: 125, // can be fixed 3 (Job No)\n\t\t//\t\t\t\tatbValue: \"15497\" // job number (00007 is a test job number)\n\t\t//\t\t\t},\n\t\t//\t\t\tUseWildCard: false\n\t\t//\t}]\n\t\t//}\n\t}\n\n\t$.ajax({\n\t\turl: action_url + 'GetDocuments/' + UserId,\n\t\ttype: \"POST\",\n\t\tcontentType: \"application/json; charset=utf-8\",\n\t\tdata: JSON.stringify(Criteria), \n\t\tsuccess: function(Result)\n\t\t{\n\t\t\t// returns multiple document infomation\n\t\t\t$.each(Result.Documents, function(index, value)\n\t\t\t{\n\t\t\t\tvar JobNo;\n\t\t\t\tvar Sheet;\n\t\t\t\tvar PhotoType;\n\n\t\t\t\tfor(var i = 0; i < value.Attrs.length; i++)\n\t\t\t\t{\n\t\t\t\t\tswitch(value.Attrs[i].id)\n\t\t\t\t\t{\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\tJobNo = value.Attrs[i].atbValueForUI;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 10:\n\t\t\t\t\t\tSheet = value.Attrs[i].atbValueForUI;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 18:\n\t\t\t\t\t\tPhotoType = value.Attrs[i].atbValueForUI;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\talert(\"Document ID: \" + value.id + \"\\n\" +\n\t\t\t\t\t \"Version ID: \" + value.id_version + \"\\n\" +\n\t\t\t\t\t \"Title: \" + value.title + \"\\n\" +\n\t\t\t\t\t \"JobNo: \" + JobNo + \"\\n\" + \n\t\t\t\t\t \"Sheet: \" + Sheet + \"\\n\" + \n\t\t\t\t\t \"Photo Type: \" + PhotoType);\n\t\t\t});\n\t\t}\n\t});\n}",
"function showSearch(request, response) {\n let SQL = 'SELECT * FROM species ';\n\n if (request.body.pages === undefined) { SQL += 'LIMIT 50' }\n if (request.body.pages) { SQL += `ORDER BY national_dex_id OFFSET ${parseInt(request.body.pages) * 50} FETCH NEXT 50 ROWS ONLY` }\n\n // Get the random Pokemon object\n return getRandomPokemon()\n .then((randomMon) => {\n\n return client.query(SQL)\n .then(result => {\n response.render('./pages/search', { result: result.rows, types: ['none', 'normal', 'fighting', 'flying', 'poison', 'ground', 'rock', 'bug', 'ghost', 'steel', 'fire', 'water', 'grass', 'electric', 'psychic', 'ice', 'dragon', 'dark', 'fairy'], random: randomMon })\n })\n })\n .catch(err => handleError(err, response))\n}",
"queryRemoteContent() {\n var query = this.get('query'),\n lastSearch = this.get('lastSearch') || {};\n query = query.trim();\n if (query === lastSearch.query) {\n return lastSearch.promise;\n }\n lastSearch.query = query;\n lastSearch.promise = DiagnosisRepository.search(query, this.get('requiredCodeSystems'), this.get('optionalCodeSystems'));\n this.set('lastSearch', lastSearch);\n return lastSearch.promise;\n }",
"function getSavedSearches(req, res) {\n const sqlQuery = 'SELECT * FROM apis;';\n client.query(sqlQuery)\n .then(result => {\n res.render('pages/collection.ejs', { apis: result.rows })\n })\n .catch(error => {\n res.status(500).send('Error, apis not found');\n console.log(error);\n });\n}",
"function queryTransport(transport, next) {\n if (options.query) {\n options.query = transport.formatQuery(query);\n }\n \n transport.query(options, function (err, results) {\n if (err) {\n return next(err);\n }\n \n next(null, transport.formatResults(results, options.format));\n });\n }",
"queryRemoteContent() {\n var query = this.get('query'),\n lastSearch = this.get('lastSearch') || {};\n query = query.trim();\n if (query === lastSearch.query) {\n return lastSearch.promise;\n }\n lastSearch.query = query;\n lastSearch.promise = _diagnoses.default.search(query, this.get('requiredCodeSystems'), this.get('optionalCodeSystems'));\n this.set('lastSearch', lastSearch);\n return lastSearch.promise;\n }",
"function loadDocuments() {\n console.log(\"loadDocuments() started\");\n showMessage(\"Loading private documents for '\" + user.name + \"' ...\");\n user.privateDocuments.get({\n limit : 1000\n }).execute(function(response) {\n console.log(\"loadDocuments() response = \" + JSON.stringify(response));\n var html = '<ul>';\n documents = response.data;\n $.each(documents, function(index, doc) {\n html += '<li>';\n html += '<a href=\"#\" class=\"document-select\" data-index=\"' + index + '\">' + doc.subject + '</a>';\n html += ' (' + doc.viewCount + ' views)';\n html += '</li>';\n });\n html += '</ul>';\n $(\"#documents-list\").html(\"\").html(html);\n $(\".document-select\").click(function () {\n var index = $(this).attr(\"data-index\");\n current = documents[index];\n $(\".document-subject\").html(\"\").html(current.subject);\n showDocument();\n });\n showOnly(\"documents-div\");\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sets input in form and submits it | function setInputAndSubmit(aForm, aField, aValue)
{
setInput(aForm, aField, aValue);
aForm.submit();
} | [
"function submit() {\n\tif(!is_valid_value()) {\n\t\t// should return some error code\n\t\t$('#error_msg').html('invalid input, try again')\n\t\tsetTimeout(function() {\n\t\t\t$('#error_msg').html('')\n\t\t}, 1000)\n\t\t$('#valueInput').val('').focus()\n return\n }\n\n // Otherwise, let's roll\n store_block_data(\"value submitted\", get_data('username'), url,\n $(\"#valueInput\").val());\n \n store.refresh()\n find_website(url).block_start_time = new Date().getTime();\n store.save()\n\n\tshow_block_stuff();\n\tsubmit_clicked = true;\n}",
"async function newStoryFormSubmit() {\n console.debug(\"newStoryFormSubmit\");\n\n // grab the author, title, and url\n let author = $(\"#author-input\").val();\n let title = $(\"#title-input\").val();\n let url = $(\"#url-input\").val();\n\n // put newStory data into object\n let newStory = { author, title, url };\n\n // add newStory to API\n await StoryList.addStory(currentUser, newStory);\n\n // clear author, title, and url\n $(\"#author-input\").val(\"\");\n $(\"#title-input\").val(\"\");\n $(\"#url-input\").val(\"\");\n\n putStoriesOnPage();\n\n // hide story form\n $newStoryForm.hide();\n}",
"function handleSubmit(event) {\n event.preventDefault(); // When event happens page refreshed, this function prevents the default reaction\n const currentValue = input.value;\n paintGreeting(currentValue);\n saveName(currentValue);\n}",
"submitFormWith (data) {\n for (let key in data) {\n this.type(data[data], key)\n }\n\n this.wrapper.find('button#submit').trigger('submit')\n }",
"function afterSubmit() {\n getAllQuotes()\n form.reset()\n form.elements[0].focus()\n}",
"function submitForm(formid, task) {\n // get the form\n var f = $(formid);\n // set the action\n if(task && task != '') {\n f.action.value = task\n }\n f.submit();\n}",
"_updateForm() {\n var form = this._getForm();\n form.find('#name').val(this.contact.name);\n form.find('#surname').val(this.contact.surname);\n form.find('#email').val(this.contact.email);\n form.find('#country').val(this.contact.country);\n }",
"function submitScan() {\n\n\t\t// make sure position is not undefined if it is unused\n\t\tif ( type.val() === \"track\" && $( \"#tracktype\" ).val() === \"source\" ) {\n\n\t\t\tras.val( \"0h0m0s\" );\n\t\t\tdec.val( \"0d0m0s\" );\n\t\t}\n\n\t\t// submit form if it is valid\n\t\tif ( validateForm() ) {\n\n\t\t\t// build javascript object with scan parameters\n\t\t\tvar scanvalues = { \"name\": name.val(), \"type\": type.val(), \"source\": sourcelist.val(), \"ras\": ras.val(), \"dec\": dec.val(),\n\t\t\t\t\t\t\t\t\"duration\": duration.val(), \"freqlower\": freqlower.val(), \"frequpper\": frequpper.val(), \"stepnumber\": step_num.val()};\n\n\t\t\t// convert javascript object to json\n\t\t\tvar scanjson = JSON.stringify( scanvalues );\n\n\t\t\t// ajax post request uploading the scan\n\t\t\t// uses the response to update the queue table\n\t\t\t$.post( \"/submitscan\", scanjson, function( response ) {\n\n\t\t\t\tupdateSchedule( response );\n\n\t\t\t}, \"json\");\n\n\t\t\t// close the dialog form\n\t\t\tscandialog.dialog( \"close\" );\n\t\t}\n\t}",
"function submitForm(actionStr) {\n var formObj = document.hiddenform;\n formObj.action = actionStr;\n formObj.outerScroll.value = YAHOO.util.Dom.getDocumentScrollTop();\n if (document.getElementById('divContScroll')) {\n formObj.innerScroll.value = document.getElementById('divContScroll').scrollTop;\n }\n\n if (document.getElementById('scrollSizer')) {\n formObj.scrollSize.value = document.getElementById('scrollSizer').options[document.getElementById('scrollSizer').selectedIndex].value;\n }\n\n formObj.showMatrix.value = 'true';\n formObj.filterDisplayStyle.value = 'none';\n document.hiddenform.submit();\n}",
"submit() {\n const { currentItem, addItem, inputMode, clearCurrentItem, setItemShowInput, editItem } = this.props\n if (inputMode === 'add') {\n addItem(currentItem);\n } else {\n editItem(currentItem)\n }\n clearCurrentItem();\n setItemShowInput(false);\n }",
"function submitAnswer() {\n let answer = app.form.convertToData('#survey-form');\n answer.answerer = loggedInUser.email;\n answer.survey_id = openSurvey.id;\n if (!answered(openSurvey.id)) {\n newAnswer(answer);\n } else {\n updateAnswer(answer);\n }\n}",
"function handlePatientFormSubmit(event) {\n event.preventDefault();\n // Don't do anything if the name fields hasn't been filled out\n if (!nameInput.val().trim().trim()) {\n return;\n }\n // Calling the upsertPatient function and passing in the value of the name input\n upsertPatient({\n name: nameInput\n .val()\n .trim()\n });\n }",
"function parksFormSubmit() {\n $('#national-parks').submit( function(e) {\n e.preventDefault();\n let park = $('#park-name').val();\n let state = $('#state-name').val();\n let maxResults = $('#search-results').val();\n sendRequest(park, state, maxResults);\n });\n}",
"function handleFormSubmit() {\n\t// Get values of inputs\n\t// Pass values to addNewPost()\n var inputName = document.getElementById(\"input-username\").value;\n var inputCaption = document.getElementById(\"input-caption\").value;\n var inputPicture = document.getElementById(\"input-picture\").value;\n addNewPost(inputName, inputPicture, inputCaption);\n}",
"function contactSubmit() {\n $(this).submit();\n }",
"function handleSubmit(button_type) {\n\n // check if there are no more unranked items\n unranked_items = document.getElementById('unranked-items').children;\n if (unranked_items.length > 0) {\n window.alert('Please sort in all items first.');\n }\n else {\n //get the ranking and save it\n var item_ids = [];\n var ranked_items = document.getElementById(\"ranked-items\").children;\n for (var j=0, item; item = ranked_items[j]; j++) {\n item_ids.push(ranked_items[j].getAttribute('id'));\n }\n document.getElementsByName(\"rankingResult\")[0].value = item_ids;\n\n var btn = document.getElementsByName('buttonType')[0];\n if (btn) {\n btn.value = button_type;\n }\n\n // now submit the form\n document.getElementById(\"subForm\").submit();\n }\n\n}",
"function selectAndSubmit(formid, id, task) {\n\t// get the form\n\tvar f = $(formid);\n\t// set the checkbox\n\tcb = eval('f.cb' + id);\n if(cb) {\n cb.checked = true;\n }\n // set the action\n\tif(task && task != '') {\n\t\tf.action.value = task\n\t}\t\t\n\tf.submit();\t\n}",
"function submitForm() {\n \n //collect the value data, close the dialog and send the data back to the caller\n\n //create a dictionary for the macro params\n var paramDictionary = {};\n _.each($scope.macroParams, function (item) {\n\n var val = item.value;\n\n if (item.value != null && item.value != undefined && !_.isString(item.value)) {\n try {\n val = angular.toJson(val);\n }\n catch (e) {\n // not json \n }\n }\n \n //each value needs to be xml escaped!! since the value get's stored as an xml attribute\n paramDictionary[item.alias] = _.escape(val);\n\n });\n \n //need to find the macro alias for the selected id\n var macroAlias = $scope.selectedMacro.alias;\n\n //get the syntax based on the rendering engine\n var syntax;\n if ($scope.dialogData.renderingEngine && $scope.dialogData.renderingEngine === \"WebForms\") {\n syntax = macroService.generateWebFormsSyntax({ macroAlias: macroAlias, macroParamsDictionary: paramDictionary });\n }\n else if ($scope.dialogData.renderingEngine && $scope.dialogData.renderingEngine === \"Mvc\") {\n syntax = macroService.generateMvcSyntax({ macroAlias: macroAlias, macroParamsDictionary: paramDictionary });\n }\n else {\n syntax = macroService.generateMacroSyntax({ macroAlias: macroAlias, macroParamsDictionary: paramDictionary });\n }\n\n $scope.submit({ syntax: syntax, macroAlias: macroAlias, macroParamsDictionary: paramDictionary });\n }",
"function submitToBot(event) {\r\n\tif(event && event.keyCode != 13){\r\n\t\treturn false;\r\n\t}\r\n\tvar v = textInput.value.trim();\r\n\tif(v.length > 0) {\r\n\t\tnewInput(v);\r\n\t}\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List of design ascendants | async ascendants() {
const project = await Project.findOne({ _id: this.project });
const projectAscendants = await project.ascendants();
return [...projectAscendants, project.toObject()];
} | [
"function depth(x) {\n var txt = '';\n\n for (var i=0, max = x.length; i < max; i++){\n var name = x[i].tagName;\n var dashes = $(name).parents().length;\n txt += '-'.repeat(dashes) + name + '\\n';\n console.log('-'.repeat(dashes), name);\n }\n return txt;\n }",
"getImplementations() {\r\n return this.getNameNode().getImplementations();\r\n }",
"get subMenus() {\n\t\tconst slot = this.shadowRoot.querySelector('slot[name=\"sub-menu\"]');\n\t\treturn slot.assignedElements();\n\t}",
"listOfAncestors() {\n let theList = [];\n for (var i = 0; i < this.list.length; i++) {\n if (this.list[i] && this.list[i] > 0) {\n theList.push({ ahnNum: i, id: this.list[i] });\n }\n }\n return theList;\n }",
"getReflectionCategories(reflections) {\n const categories = new Map();\n for (const child of reflections) {\n const childCategories = this.getCategories(child);\n if (childCategories.size === 0) {\n childCategories.add(CategoryPlugin_1.defaultCategory);\n }\n for (const childCat of childCategories) {\n const category = categories.get(childCat);\n if (category) {\n category.children.push(child);\n }\n else {\n const cat = new models_2.ReflectionCategory(childCat);\n cat.children.push(child);\n categories.set(childCat, cat);\n }\n }\n }\n for (const cat of categories.values()) {\n this.sortFunction(cat.children);\n }\n return Array.from(categories.values());\n }",
"function getAllDTNs(){\n var dtns = [];\n var nodes = flattenAll_BF(root);\n for(var i in nodes){\n if(nodes[i].type == \"dtn\") dtns.push(nodes[i]);\n }\n\n return dtns;\n}",
"getElements() {\n const result = new Set();\n for (const item of this.leftSide.concat(this.rightSide))\n item.getElements(result);\n return Array.from(result);\n }",
"function getViews() {\r\n var sections = document.querySelectorAll(\".view\"),\r\n cList = [];\r\n for (var i = 0; i < sections.length; i++) {\r\n cList.push(sections[i].className.match(/view-[^ ]+/g)[0].replace(\"view-\", \"\"));\r\n }\r\n return cList;\r\n }",
"function childrenByClass(element, name) {\n var filtered = [];\n\n for (var i = 0; i < element.children.length; i++) {\n var child = element.children[i];\n if (child.className.indexOf(name) !== -1) {\n filtered.push(child);\n }\n }\n\n return filtered;\n}",
"function elements() {\n return _elements;\n }",
"children(person) {\n return person.sons;\n }",
"async getAllChildrenAsOrderedTree(props = {}) {\n const selects = [\"*\", \"customSortOrder\"];\n if (props.retrieveProperties) {\n selects.push(\"properties\", \"localProperties\");\n }\n const setInfo = await this.select(...selects)();\n const tree = [];\n const childIds = [];\n const ensureOrder = (terms, sorts, setSorts) => {\n // handle no custom sort information present\n if (!isArray(sorts) && !isArray(setSorts)) {\n return terms;\n }\n let ordering = null;\n if (sorts === null && setSorts.length > 0) {\n ordering = [...setSorts];\n }\n else {\n const index = sorts.findIndex(v => v.setId === setInfo.id);\n if (index >= 0) {\n ordering = [...sorts[index].order];\n }\n }\n if (ordering !== null) {\n const orderedChildren = [];\n ordering.forEach(o => {\n const found = terms.find(ch => o === ch.id);\n if (found) {\n orderedChildren.push(found);\n }\n });\n // we have a case where if a set is ordered and a term is added to that set\n // AND the ordering information hasn't been updated in the UI the new term will not have\n // any associated ordering information. See #1547 which reported this. So here we\n // append any terms remaining in \"terms\" not in \"orderedChildren\" to the end of \"orderedChildren\"\n orderedChildren.push(...terms.filter(info => ordering.indexOf(info.id) < 0));\n return orderedChildren;\n }\n return terms;\n };\n const visitor = async (source, parent) => {\n const children = await source();\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n childIds.push(child.id);\n const orderedTerm = {\n children: [],\n defaultLabel: child.labels.find(l => l.isDefault).name,\n ...child,\n };\n if (child.childrenCount > 0) {\n await visitor(this.getTermById(children[i].id).children.select(...selects), orderedTerm.children);\n orderedTerm.children = ensureOrder(orderedTerm.children, child.customSortOrder);\n }\n parent.push(orderedTerm);\n }\n };\n // There is a series of issues where users expect that copied terms appear in the result of this method call. Copied terms are not \"children\" so we need\n // to get all the children + all the \"/terms\" and filter out the children. This is expensive but this method call is already indicated to be used with caching\n await visitor(this.children.select(...selects), tree);\n await visitor(async () => {\n const terms = await Terms(this).select(...selects)();\n return terms.filter((t) => childIds.indexOf(t.id) < 0);\n }, tree);\n return ensureOrder(tree, null, setInfo.customSortOrder);\n }",
"parent() {\n\t const parents = [];\n\t this.each(el => {\n\t if (!parents.includes(el.parentNode)) {\n\t parents.push(el.parentNode);\n\t }\n\t });\n\t return new DOMNodeCollection(parents);\n\t }",
"_allHeadings() {\n return Array.from(this.querySelectorAll('howto-accordion-heading'));\n }",
"getBaseTypes() {\r\n return this.getType().getBaseTypes();\r\n }",
"_collectClasses() {\n const result = []\n let current = Object.getPrototypeOf(this)\n while (current.constructor.name !== 'Object') {\n result.push(current)\n current = Object.getPrototypeOf(current)\n }\n return result\n }",
"visitOrder_by_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function getMandatoryItems(){\n\tvar el = new Array();\n\tvar tags = document.getElementsByTagName('*');\n\tvar tcl = \" mandatory \";\n\tvar i; var j;\n\t\n\tfor(i=0,j=0; i<tags.length; i++) { \n\t\tvar test = \" \" + Right(tags[i].className, 9) + \" \";\n\t\tif (test.indexOf(tcl) != -1) \n\t\t\t\t\n\t\t\tel[j++] = tags[i];\n\t} \n\treturn el;\n}",
"function allSCComponents(wantClass) {\n var ids = [];\n var d;\n basicColorMenu.forEach(function (item) {\n d = item.elements.map(function (ele) {\n if (wantClass) return `.${ele}`;\n else return ele;\n });\n ids = ids.concat(d);\n });\n idsSet = new Set(ids);\n ids = Array.from(idsSet);\n return ids;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function:AddElement () Purpose:Adds an element to the current page | function AddElement ()
{
var ElementType = doAction('REQ_GET_FORMVALUE', "ElementType", "ElementType");
return (AddElementType (ElementType));
} | [
"function appendElement(){\n\t\tif(document && document.body){\n\t\t\tdocument.body.appendChild(iframe);\n\t\t\treturn;\n\t\t}\n\t\tsetTimeout(function(){appendElement()}, 100);\n\t}",
"function addElement(prevElement, element, attribute, attrValue) {\n if (prevElement != \"\") {\n prevElement.after(element);\n if (attribute != \"\" || attrValue != \"\") {\n let attr = document.createAttribute(attribute);\n attr.value = attrValue;\n element.setAttributeNode(attr);\n }\n } else {\n document.querySelector(\"body\").appendChild(element);\n if (attribute != \"\" || attrValue != \"\") {\n let attr = document.createAttribute(attribute);\n attr.value = attrValue;\n element.setAttributeNode(attr);\n }\n }\n}",
"function addToDOM(element, someHTML) {\n var div = document.createElement('div');\n div.id = \"b\";\n div.innerHTML = someHTML;\n element.appendChild(div);\n}",
"function addOnResults(element) {\n\tresultsDiv.appendChild(element);\n}",
"function addTestElement(elemId) {\n var elem = document.createElement('div');\n elem.id = elemId;\n elem.className = 'addedByCssp';\n elem.setAttribute('style', 'position: absolute; width: 1px; height: 1px; top: -1px; left: -1px;');\n \n document.body.insertBefore(elem, document.body.firstChild);\n \n return elem;\n }",
"function BAElement() { }",
"function add_elem(element, index) {\n //Get old element and copy to new element\n var ul = document.getElementById(element);\n var li_old = ul.children[ul.children.length-1];\n var li_new = li_old.cloneNode(true); \n\n //Empty values and change index\n EmptyValues(li_new);\n ChangeIndex(li_new, index+1);\n\n //Change index of all following elements in list.\n for (var i=index+1; i<ul.children.length; i++)\n ChangeIndex(ul.children[i], i+1);\n \n //Insert element at given position.\n InsertIntoList(ul, li_new, index);\n}",
"function addAndReturnElement(elNameToAdd, nameSpace, xmlElement, preserveSpaces)\n {\n var elToAdd = document.createElementNS(nameSpace, elNameToAdd);\n if (preserveSpaces) Utils.setPreserveSpace(elToAdd);\n xmlElement.appendChild(elToAdd);\n return elToAdd;\n }",
"function AddElementType (type)\n{\n\treturn (doActionEx('MPEA_ADD_ELEMENT', 'ElementID', 'ElementType', type));\n}",
"function addElement(doc, parent, name, text) {\n\tvar e = doc.createElement(name);\n\tvar txt = doc.createTextNode(text);\n\t\n\te.appendChild(txt);\n\tparent.appendChild(e);\n\t\n\treturn e;\n}",
"add_element(obj) {\n if (!(obj instanceof GameObject)) throw new TypeError(\"#Animation: Can only add gameobjects to the scene\");\n this.actors.push(obj);\n this.scene.add(obj.mesh);\n }",
"function addElementToCanvas(elementInfo) {\n\n\t console.log(elementInfo);\n\t \n\t if (elementInfo.loaded == undefined) {\n\t messageDialog.show(\"Canvas\",\"Add element to canvas '\"+elementInfo.type+\"'. error: attribute 'loaded' not created in function addElementToCanvas. Element doesnt put on canvas. \");\n\t return;\n\t }\t \n\t \n var elementClass = recognizeElementType(elementInfo.type);\n var elementToAdd = document.createElement(elementClass); \n \n if (elementInfo.type == ELEMENT_TYPE_TEXTEDIT || elementInfo.type == ELEMENT_TYPE_TEXT || \n elementInfo.type == ELEMENT_TYPE_BUTTON) {\n elementToAdd.style.padding = \"4px\";\n var textArea = document.createElement(\"textarea\");\n textArea.style.width = \"98%\";\n textArea.style.height = \"96%\"; \n elementToAdd.appendChild(textArea);\n }\n \n elementToAdd.style.display = \"block\";\n elementToAdd.style.position = \"absolute\";\n \n if (elementInfo.loaded) {\n elementInfo.x_pos = canvas.convertPosXFromIPadToCanvas(elementInfo.x_pos);\n elementInfo.y_pos = canvas.convertPosYFromIPadToCanvas(elementInfo.y_pos); \n elementInfo.width = canvas.convertPosXFromIPadToCanvas(elementInfo.width);\n elementInfo.height = canvas.convertPosYFromIPadToCanvas(elementInfo.height); \n } \n \n if (elementInfo.set_default == undefined) {\n elementInfo.set_default = true;\n }\n \n // common for all\n elementToAdd.dataset.designType = elementInfo.type;\n elementToAdd.dataset.designId = elementInfo.id;\n elementToAdd.dataset.designOutline = 1;\n elementToAdd.dataset.designActions = specialCharsToHtml(elementInfo.actions); \n elementToAdd.dataset.designIsActions = 1; \n \n if (elementInfo.loaded && elementInfo.screen_id != boardId) {\n elementToAdd.dataset.designScreenId = elementInfo.screen_id;\n elementInfo.is_element_from_other_board = true;\n } else {\n elementToAdd.dataset.designScreenId = currentScreenId;\n }\n \n // add element to canvas \n canvas.addElement(elementToAdd); \n \n // default settings\n setDefaultSettingsForElement(elementToAdd, elementInfo.loaded, elementInfo.set_default); \n \n setStyleOfElement(elementToAdd, {\n loaded : elementInfo.loaded,\n new_element : elementInfo.new_element, \n is_element_from_other_board: elementInfo.is_element_from_other_board,\n type: elementInfo.type,\n x_pos : elementInfo.x_pos,\n y_pos : elementInfo.y_pos,\n width : elementInfo.width,\n height : elementInfo.height,\n font_size : elementInfo.font_size,\n font_type : elementInfo.font_type,\n text_color : elementInfo.text_color,\n title_label : elementInfo.title_label,\n title_color : elementInfo.title_color,\n background_image : elementInfo.background_image,\n file_name : elementInfo.file_name,\n area_image : elementInfo.area_image,\n draggable : elementInfo.draggable,\n html_content : elementInfo.html_content,\n text : elementInfo.text,\n name : elementInfo.name,\n visible : elementInfo.visible,\n screen_id : elementInfo.screen_id, \n });\n \n canvas.setCanvasForScreenId(currentScreenId);\n\n // set clickables areas for editor\n Editor.bindObjectTypeToElement(elementInfo.type, elementToAdd);\n\n // set manage of element\n setTextDraggable();\n setButtonsDraggable();\n setMapClickable();\n setEditables(); \n\n // add to database if not \n if (elementInfo.loaded == false) {\n addElementToBase(elementToAdd, elementInfo);\n\n if (elementInfo.isUserCreated) {\n \n // generate code\n codeEditor.generateByNewObject([{name: elementToAdd.dataset.designName, type: elementInfo.type}]);\n if (elementInfo.type == ELEMENT_TYPE_TEXT || elementInfo.type == ELEMENT_TYPE_TEXTEDIT ||\n elementInfo.type == ELEMENT_TYPE_BUTTON) {\n codeEditor.generateByChangeParam([\n {name:elementToAdd.dataset.designName, parameter: \"fontSize\", value: elementToAdd.dataset.designFontSize},\n {name:elementToAdd.dataset.designName, parameter: \"fontType\", value: elementToAdd.dataset.designFontType},\n {name:elementToAdd.dataset.designName, parameter: \"text\", value: elementToAdd.dataset.designText},\n ]);\n }\n codeEditor.generateByChangeParam([\n {name:elementToAdd.dataset.designName, parameter: \"height\", value: elementToAdd.dataset.designHeight},\n {name:elementToAdd.dataset.designName, parameter: \"width\", value: elementToAdd.dataset.designWidth},\n {name:elementToAdd.dataset.designName, parameter: \"y\", value: elementToAdd.dataset.designYPos},\n {name:elementToAdd.dataset.designName, parameter: \"x\", value: elementToAdd.dataset.designXPos}\n ]);\n }\n } else {\n //console.log(\"add element (\"+elementInfo.type+\" ID:\"+elementInfo.id+\") from base to canvas\");\n }\n\n return elementToAdd;\n\t}",
"function createElements() {\n var page = document.getElementById('page-content-wrapper');\n\n var img = document.createElement('img');\n img.setAttribute(\"class\", \"picture\");\n img.setAttribute(\"src\", \"../img/profile/\" + current.pic);\n\n var name = document.createElement('h2');\n name.setAttribute(\"class\", \"user-name\");\n name.innerHTML = current.name;\n\n var username = document.createElement('h3');\n username.setAttribute(\"class\", \"username-tag\");\n username.innerHTML = current.username;\n\n\n //Appends the element to the parent element\n current.win.appendChild(name);\n current.win.appendChild(username);\n current.win.appendChild(img);\n page.appendChild(current.win);\n }",
"function AddElement(name, owner, description, score, issues){\n\t\t\t\t\tadd += \t'<div id=\"repository\">';\n\t\t\t\t\tadd += \t'<div id=\"owner\">';\t\t\t\t\t\n\t\t\t\t\tadd += \towner + '</div>';\n\t\t\t\t\tadd += \t'<div id=\"description\">';\n\t\t\t\t\tadd += \t'<h2 id=\"repoName\">'+ name +'</h2>';\n\t\t\t\t\tadd += \t'<p id=\"repoDescription\">'+desc+'</p>';\n\t\t\t\t\tadd += \t'<ul id=\"list\">';\n\t\t\t\t\tadd += \t'<li id=\"Issues\"> Issues :'+issues+'</li>';\n\t\t\t\t\tadd += \t'<li id=\"score\"> Score :'+score+'</li>';\n\t\t\t\t\tadd += \t'<li>Submitted 30 days ago by '+name+'</li>';\n\t\t\t\t\tadd += \t'</ul>';\n\t\t\t\t\tadd += \t'</div>';\n\t\t\t\t\tadd += \t'</div>';\n\t\t\t\t\t$('#container').append(add);\n}",
"function attachOnDOM(){\n\tdocument.getElementsByTagName('body')[0].appendChild(getComponent())\n}",
"function displayNewElement(){\n generateRandomElement();\n document.getElementById(\"selectedElement\").innerHTML = \"<p><h4>\" + elementName + \"</h4></p>\";\n}",
"static attach(element) {\n return new DomBuilder(element);\n }",
"function addPage(pageNumber)\r{\r var pageTagLocal = tags.myRootXMLElement.xmlElements.add(tags.pageTag);\r var pageName = pageTagLocal.xmlElements.add(tags.pageNameTag);\r pageName.contents = pageNumber;\r return pageTagLocal;\r}",
"add(element) {\n this._buffer.unshift(element);\n this._buffer = this._buffer.splice(0, this._size);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
var HTMLschoolStart = ''; var HTMLschoolName = '%data%'; var HTMLschoolDegree = ' %data%'; var HTMLschoolDates = '%data%'; var HTMLschoolLocation = '%data%'; var HTMLschoolMajor = 'Major: %data%'; var HTMLonlineClasses = 'Online Classes'; var HTMLonlineTitle = '%data%'; var HTMLonlineSchool = ' %data%'; var HTMLonlineDates = '%data%'; var HTMLonlineURL = '%data%'; | function displayEd() {
for (s in education.schools) {
$("#education").append(HTMLschoolStart);
var school = education.schools[s];
var name = HTMLschoolName.replace("%data%", school.name);
name = name.replace("#", school.url);
var location = HTMLschoolLocation.replace("%data%", school.location); // this is causing bug where page doesnt appear
var dates = HTMLschoolDates.replace("%data%", school["degree dates"]);
var major = HTMLschoolMajor.replace("%data%", school.major);
var degree = HTMLschoolDegree.replace("%data%", school.degree);
var transcript = HTMLschoolTranscript.replace("#", school.transcript)
transcript = transcript.replace("%data%", school.gpa)
$(".education-entry").append(name+degree+dates+'<br>'+transcript+location+major);
}
$(".education-entry").append(HTMLonlineClasses);
for (o in education.onlineCourses) {
var course = education.onlineCourses[o];
var title = HTMLonlineTitle.replace("%data%", course.title);
title = title.replace("#", course.url);
var school = HTMLonlineSchool.replace("%data%", course.school);
var dates = HTMLonlineDates.replace("%data%", course.dates);
//var url = HTMLonlineURL.replace("%data%", course.url);
$(".education-entry").append(title+school+dates+"<br>");
}
} | [
"function loadDatafromJson2Html(){\n\tdocument.getElementById(\"File_name\").innerHTML = prsm_data.prsm.ms.ms_header.spectrum_file_name;\n\tdocument.getElementById(\"PrSM_ID\").innerHTML = prsm_data.prsm.prsm_id;\n\tdocument.getElementById(\"Scan\").innerHTML = prsm_data.prsm.ms.ms_header.scans;\n\tdocument.getElementById(\"Precursor_charge\").innerHTML = prsm_data.prsm.ms.ms_header.precursor_charge;\n\tdocument.getElementById(\"precursormz\").innerHTML = prsm_data.prsm.ms.ms_header.precursor_mz ;\n\tdocument.getElementById(\"Precursor_mass\").innerHTML = prsm_data.prsm.ms.ms_header.precursor_mono_mass;\n\tdocument.getElementById(\"Proteoform_mass\").innerHTML = prsm_data.prsm.annotated_protein.proteoform_mass;\n\tdocument.getElementById(\"matched_peaks\").innerHTML = prsm_data.prsm.matched_peak_number;\n\tdocument.getElementById(\"matched_fragment_ions\").innerHTML = prsm_data.prsm.matched_fragment_number;\n\tdocument.getElementById(\"unexpected_modifications\").innerHTML = prsm_data.prsm.annotated_protein.unexpected_shift_number;\n\tdocument.getElementById(\"E_value\").innerHTML = prsm_data.prsm.e_value;\n\tdocument.getElementById(\"P_value\").innerHTML = prsm_data.prsm.p_value;\n\tdocument.getElementById(\"Q_value\").innerHTML = prsm_data.prsm.fdr;\n}",
"function get_blank_sheet ()\n{\n var data;\n clear_data();\n\n\n\n document.getElementById('header_data').innerHTML += \"MAJOR_TRANS:Computer Science, Computer Science;\";\n document.getElementById('header_data').innerHTML += \"TRANS_MAJOR:Computer Science;\";\n document.getElementById('header_data').innerHTML += \"NAME:Blank Sheet;\";\n document.getElementById('header_data').innerHTML += \"BANNER:Y00000000;\";\n\n\n// send the form data\n document.getElementById('header_data_to_send').value =\n document.getElementById('header_data').innerHTML\n\n document.getElementById('textInput').value = \"Paste your data here\";\n document.getElementById('data_to_send_form').submit();\n\n return;\n}",
"function prepareDataForTable(data){\n\n // Return variable:\n var data_json = [];\n\n // Looping through the submitted documents\n $.each(data, (index, study) => {\n\n // data with one row in the data table:\n var tmp = {};\n\n // Skipping study if already processed:\n if (jQuery.inArray(study.id, study_ids) == -1){\n study_ids.push(study.id);\n }\n\n // Save study ID for further checks in global variable:\n\n\n // Do we need to add genotyping icon:\n var genotypingIcon = \"\";\n if ((study.genotypingTechnologies.indexOf(\"Targeted genotyping array\") > -1) ||\n (study.genotypingTechnologies.indexOf(\"Exome genotyping array\") > -1)) {\n genotypingIcon = \"<span style='font-size: 12px' class='glyphicon targeted-icon-GWAS_target_icon context-help'\" +\n \" data-toggle='tooltip'\" +\n \"data-original-title='Targeted or exome array study'></span>\";\n }\n\n // Is summary stats available:\n var linkFullPValue = \"NA\";\n if (study.fullPvalueSet == 1) {\n var a = (study.authorAscii_s).replace(/\\s/g, \"\");\n const ftpdir = getDirectoryBin(study.accessionId);\n var dir = a.concat(\"_\").concat(study.pubmedId).concat(\"_\").concat(study.accessionId);\n var ftplink = \"<a href='http://ftp.ebi.ac.uk/pub/databases/gwas/summary_statistics/\".concat(ftpdir).concat('/').concat(study.accessionId).concat(\"' target='_blank'</a>\");\n linkFullPValue = ftplink.concat(\"FTP Download\");\n }\n\n // Is study loaded to the summary stats database:\n if (loadedStudies.indexOf(study.accessionId) > -1) {\n if (linkFullPValue === \"NA\") {\n linkFullPValue = \"<a href='http://www.ebi.ac.uk/gwas/summary-statistics/docs' target='_blank'>API access</a>\";\n } else {\n linkFullPValue = linkFullPValue.concat(\" or <a href='http://www.ebi.ac.uk/gwas/summary-statistics/docs' target='_blank'>API access</a>\");\n }\n }\n tmp['link'] = linkFullPValue;\n\n // Adding author:\n tmp['Author'] = study.author_s ? study.author_s : \"NA\";\n\n // Number Associations:\n tmp['nr_associations'] = study.associationCount ? study.associationCount : 0;\n\n // Publication date:\n var publication_date_full = study.publicationDate;\n var publication_date = publication_date_full.split('T')[0];\n tmp['publi'] = publication_date;\n\n // AccessionID:\n tmp['study'] = '<a href=\"' + gwasProperties.contextPath + 'studies/' + study.accessionId + '\">' + study.accessionId + '</a>' + genotypingIcon;\n\n // Journal:\n tmp['Journal'] = study.publication;\n\n // Title:\n tmp['Title'] = '<a href=\"' + gwasProperties.contextPath + 'publications/' + study.pubmedId + '\">' + study.title + '</a>';\n\n // Reported trait:\n tmp['reported_trait'] = study.traitName_s;\n\n // Mapped trait:\n tmp['mappedTraits'] = setTraitsLink(study);\n\n // Mapped background trait:\n tmp['mappedBkgTraits'] = setBackgroundTraitsLink(study);\n\n // Initial sample desc\n var splitDescription = [];\n var descriptionToDisplay = [];\n var initial_sample_text = '-';\n if (study.initialSampleDescription) {\n // Split after each sample number, splitDescription[0] is an empty string\n splitDescription = study.initialSampleDescription.split(/([1-9][0-9]{0,2}(?:,[0-9]{3})*)/);\n for (var i = 1; i < splitDescription.length; i++) {\n if (i % 2 == 0) {\n // Join the sample number and it's description as one item\n var item = splitDescription[i - 1] + splitDescription[i].replace(/(,\\s+$)/, \"\");\n descriptionToDisplay.push(\" \".concat(item));\n }\n }\n initial_sample_text = displayArrayAsList(descriptionToDisplay);\n if (splitDescription.length > 3) {\n initial_sample_text = initial_sample_text.html();\n }\n }\n tmp['initial_sample_text'] = initial_sample_text;\n\n // Replicate sample desc\n var replicate_sample_text = '-';\n if (study.replicateSampleDescription) {\n replicate_sample_text = displayArrayAsList(study.replicateSampleDescription.split(', '));\n if (study.replicateSampleDescription.split(', ').length > 1)\n replicate_sample_text = replicate_sample_text.html()\n }\n tmp['replicate_sample_text'] = replicate_sample_text;\n\n // ancestryLinks\n var initial_ancestral_links_text = '-';\n var replicate_ancestral_links_text = '-';\n if (study.ancestryLinks) {\n var ancestry_and_sample_number_data = displayAncestryLinksAsList(study.ancestryLinks);\n initial_ancestral_links_text = ancestry_and_sample_number_data.initial_data_text;\n replicate_ancestral_links_text = ancestry_and_sample_number_data.replicate_data_text;\n if (typeof initial_ancestral_links_text === 'object') {\n initial_ancestral_links_text = initial_ancestral_links_text.html();\n }\n if (typeof replicate_ancestral_links_text === 'object') {\n replicate_ancestral_links_text = replicate_ancestral_links_text.html();\n }\n }\n tmp['initial_ancestral_links_text'] = initial_ancestral_links_text;\n tmp['replicate_ancestral_links_text'] = replicate_ancestral_links_text;\n\n data_json.push(tmp)\n });\n\n return(data_json)\n}",
"function Student(school) {\n var self = this;\n\n self.name = name;\n self.course = course;\n self.grade = grade;\n self.student_id = student_id;\n self.db_id = db_id;\n\n self.getFormInputs = function () {\n for (var x in school.inputIds) {\n var id_temp = school.inputIds[x];\n var value = $('#' + id_temp).val();\n self[id_temp] = value;\n }\n };\n}",
"function fillStudentInfo(studentJson) {\n var firstName = studentJson.etudiant.prenom;\n var lastName = studentJson.etudiant.nom;\n var academicYear = studentJson.monAnnee.anneeAcademique;\n var programTitle = studentJson.monAnnee.monOffre.offre.intituleComplet;\n $(\"#student_name\").append(\"<br>\");\n $(\"#student_name\").append(lastName + \", \" + firstName);\n $(\"#academic_year\").append(\"<br>\");\n $(\"#academic_year\").append(academicYear);\n $(\"#program_title\").append(\"<br>\");\n $(\"#program_title\").append(programTitle);\n}",
"function MSSSS_school_response(tblName, selected_dict, selected_pk) {\n console.log( \"===== MSSSS_school_response ========= \");\n console.log( \"selected_dict\", selected_dict);\n console.log( \"selected_pk\", selected_pk);\n console.log( \"tblName\", tblName);\n\n// --- reset table rows, also delete header\n tblHead_datatable.innerText = null;\n tblBody_datatable.innerText = null;\n\n\n // --- upload new setting and refresh page\n const request_item_setting = {page: \"page_result\",\n sel_schoolbase_pk: selected_pk,\n //sel_depbase_pk: null,\n //sel_lvlbase_pk: null,\n //sel_sctbase_pk: null,\n sel_cluster_pk: null,\n sel_student_pk: null\n };\n DatalistDownload(request_item_setting);\n\n }",
"function loadMarkers( schoolList) {\n\n\t\t// optional argument of school\n\t\tvar schools = ( typeof schoolList !== 'undefined' ) ? schoolList : schoolData;\n\n\t\tvar j = 1; // for lorempixel\n\n\t\tfor( i=0; i < schools.length; i++ ) {\n\t\t\tvar school = schools[i];\n\n\t\t\t// if its already on the map, dont put it there again\n\t\t\tif( markerList.indexOf(school.id) !== -1 ) continue;\n\n\t\t\tvar lat = school.lat,\n\t\t\tlng = school.lng,\n\t\t\tmarkerId = school.id;\n\n\t\t\tvar infoWindow = new google.maps.InfoWindow({\n\t\t\t\tmaxWidth: 400\n\t\t\t});\n\n\t\t\tvar marker = new google.maps.Marker({\n\t\t\t\tposition: new google.maps.LatLng( lat, lng ),\n\t\t\t\ttitle: school.name,\n\t\t\t\tmarkerId: markerId,\n\t\t\t\ticon: markerLocation,\n\t\t\t\tmap: map\n\t\t\t});\n\n\t\t\tmarkers[markerId] = marker;\n\t\t\tmarkerList.push(school.id);\n\n\t\t\t// \tvar content = ['<div class=\"pop-up\"><div class=\"iw-text\"><strong>', school.name,\n\t\t\t// \t'</strong><br>Age: ', school.age, '<br>Followers: ', school.followers,\n\t\t\t// \t'<br>practice_area: ', school.practice_area, '</div></div>'].join('');\n\n\n\t\t\tvar content = ['<div id=\"modal\" class=\"grid\">', school.name,'</div>'].join('');\n\n\n\n\n\n\n\n\n\t\tgoogle.maps.event.addListener(marker, 'click', (function (marker, content) {\n\t\t\treturn function() {\n\t\t\t\tinfoWindow.setContent(content);\n\t\t\t\tinfoWindow.open(map, marker);\n\t\t\t}\n\t\t})(marker, content));\n\t}\n}",
"function constructTooltipHTML(d){\n\t\t\t\t\tvar name = d.name;\n\t\t\t\t\tvar count = d.count;\n\t\t\t\t\tvar university = d.university;\n\t\t\t\t\tvar years = d.dates.toString();\n\t\t\t\t\tvar find =',';\n\t\t\t\t\tvar re = new RegExp(find,'g');\n\t\t\t\t\tvar fYears = years.replace(re,', ');\n\n\t\t\t\t\tvar html = \n\t\t\t\t\t'<div class=\"panel panel-primary\">' + \n\t\t\t\t\t\t'<div class=\"panel-heading\">' +\n\t\t\t\t\t\t\tname +\n\t\t\t\t\t\t'</div>' +\n\t\t\t\t\t\t'<div class=\"panel-body\">' + \n\t\t\t\t\t\t\t'<p><strong class=\"tooltip-body-title\">University: </strong>' + university +\n\t\t\t\t\t\t\t'</p><p><strong class=\"tooltip-body-title\">Number of times coauthored: </strong>' + count +\n\t\t\t\t\t\t\t'</p><p><strong class=\"tooltip-body-title\">Years Co-Authored: </strong>' + fYears + '</p>' +\n\t\t\t\t\t\t\t'<p>Double-Click to go to ' + name + '\\'s</p>'+\n\t\t\t\t\t\t'</div></div>';\n\n\t\t\t\t\treturn html;\n\t\t\t\t}",
"function showPatientInformation() {\n jQueryWriteTextToHTML(\"#patient-assignment\", \"Unassign\");\n jQueryGenerateURL(\"#profile-brain-test-result\", 'brain-test-results.php', patientEmail, \"Brain Test\");\n jQueryGenerateURL(\"#profile-tremor-test-result\", 'tremor-test-results.php', patientEmail, \"Tremor Test\");\n jQueryGenerateURL(\"#profile-message\", 'message.php', patientEmail, \"Messages\");\n jQueryGenerateURL(\"#profile-medication\", 'patient-medication.php', patientEmail, \"Medication\");\n}",
"function getCourseName() {\n $.ajax({\n url: BASE_URL + COURSES_CREATE + \"/\" + courseId + \"/faculties/prerrequisite \",\n type: \"GET\",\n dataType: \"json\",\n success: function(result) {\n console.log(result);\n title.html(\"Evaluaciones de \" + result.name + \" (\" + result.courseCode + \")\");\n },\n error: function(error) {\n showError(error.responseText);\n }\n });\n}",
"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 }",
"function retrieveLocalStorage(school) {\n var tempStorage = localStorage.getItem('student_array');\n\n school.student_array = JSON.parse(tempStorage);\n\n for (var i in school.student_array) {\n school.addStudentToDom(school.student_array[i]);\n }\n}",
"function populateFormData(data) {\n console.log('populateFormData called');\n\n $('#student_id').val(data.student_id);\n $('#student_name').val(data.student_name);\n $('#course').val(data.course);\n $('#grade').val(data.grade);\n}",
"function getMetricsData() {\n //select Average Page View\n data.avgPageView = $('#card_metrics > section.engagement > div.flex > div:nth-child(1) > p.small.data').text().replace(/\\s\\s+/g, '').split(' ')[0];\n\n //select Average Time On Site\n data.avgTimeOnSite = $('#card_metrics > section.engagement > div.flex > div:nth-child(2) > p.small.data').text().replace(/\\s\\s+/g, '').split(' ')[0];\n\n //select Bounce Rate\n data.bounceRate = $('#card_metrics > section.engagement > div.flex > div:nth-child(3) > p.small.data').text().replace(/\\s\\s+/g, '').split(' ')[0];\n\n //select Search Traffic Percent\n data.searchTrafficPercent = $('#card_mini_competitors > section.group > div:nth-child(2) > div.ThirdFull.ProgressNumberBar > span').text();\n\n //select Overall Rank\n data.overallRank = $('#card_rank > section.rank > div.rank-global > div:nth-child(1) > div:nth-child(2) > p.big.data').text().replace(/\\s+/g, ''); //.replace(/,/g, '');\n\n }",
"function parsonStudentWork() {\n request({\n method: 'GET',\n url: 'http://www.newschool.edu/parsons/student-work/'\n }, function(err, response, body) {\n if (err) return console.error(err);\n\n $ = cheerio.load(body);\n\n // $('div.small-up-1').each(function() {\n // var href = $('a', this).attr('href');\n // if (href.lastIndexOf('/') > 0) {\n // console.log($('h3', this).text()); // student name\n // }\n // });\n // $('div.column').each(function() {\n // var img = $('h3');\n // console.log(img.text());\n // });\n\n $('div.column').each(function() {\n var img = $('img', this).attr('src');\n var majorName = $('p.profile-program-name', this).text();\n\n // console.log(''); // markdown images\n // console.log('http://www.newschool.edu' + img + ' , ' + majorName); // csv output\n console.log('http://www.newschool.edu' + img); // just links\n\n });\n\n });\n}",
"function displayEmployees(data) {\n employees = data;\n appendEmployeHTMLStringToDOM(employees);\n}",
"function showSearchParameters() {\n $('.searchParameters').html(`\n <h2 class=\"searchTerm\">Search Term: ${searchResults.params.q}</h2>\n <p class=\"advSearch\">Search Refined By</p>\n <ul>\n <li class=\"bull\"><strong>Calories - </strong>${calValue}</li>\n <li class=\"bull\"><strong>Max Number of Ingredients - </strong>${numIng}</li>\n <li class=\"bull\"><strong>Diet Labels - </strong>${dietLabel}</li>\n <li class=\"bull\"><strong>Allergies - </strong>${allergyLab}</li>\n </ul>\n `);\n}",
"function getQuery(type, name, gender, filldata) {\n\tvar ajax = new XMLHttpRequest();\n\tajax.onload = filldata;\n\tajax.onerror = ajaxBrowserError;\n\tvar url = 'https://webster.cs.washington.edu/cse154/babynames.php?type=';\n\tajax.open('GET', url + type + '&name=' + name + '&gender=' + gender, true);\n\tajax.send();\n}",
"function getSchoolname(schoolName) {\n return schoolName.replace(\"-\", \"-<br>\")\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the first native node for a given LView, starting from the provided TNode. Native nodes are returned in the order in which those appear in the native tree (DOM). | function getFirstNativeNode(lView, tNode) {
if (tNode !== null) {
ngDevMode &&
assertTNodeType(tNode, 3 /* AnyRNode */ | 12 /* AnyContainer */ | 32 /* Icu */ | 16 /* Projection */);
const tNodeType = tNode.type;
if (tNodeType & 3 /* AnyRNode */) {
return getNativeByTNode(tNode, lView);
}
else if (tNodeType & 4 /* Container */) {
return getBeforeNodeForView(-1, lView[tNode.index]);
}
else if (tNodeType & 8 /* ElementContainer */) {
const elIcuContainerChild = tNode.child;
if (elIcuContainerChild !== null) {
return getFirstNativeNode(lView, elIcuContainerChild);
}
else {
const rNodeOrLContainer = lView[tNode.index];
if (isLContainer(rNodeOrLContainer)) {
return getBeforeNodeForView(-1, rNodeOrLContainer);
}
else {
return unwrapRNode(rNodeOrLContainer);
}
}
}
else if (tNodeType & 32 /* Icu */) {
let nextRNode = icuContainerIterate(tNode, lView);
let rNode = nextRNode();
// If the ICU container has no nodes, than we use the ICU anchor as the node.
return rNode || unwrapRNode(lView[tNode.index]);
}
else {
const componentView = lView[DECLARATION_COMPONENT_VIEW];
const componentHost = componentView[T_HOST];
const parentView = getLViewParent(componentView);
const firstProjectedTNode = componentHost.projection[tNode.projection];
if (firstProjectedTNode != null) {
return getFirstNativeNode(parentView, firstProjectedTNode);
}
else {
return getFirstNativeNode(lView, tNode.next);
}
}
}
return null;
} | [
"getNodeAtIndex(index) {\n //if index is not within list return null\n if (index >= this.length || index < 0) return null;\n //iterate through nodes until finding the one at index\n let currentNode = this.head;\n let currentIndex = 0;\n while (currentIndex !== index) {\n currentNode = currentNode.next;\n currentIndex++;\n }\n return currentNode;\n }",
"function fltFindNativeElement(id) {\n //getElementsByTagName('flt-platform-view')[0].shadowRoot.getElementById(t.elementID)\n let fltPlatformViews = document.getElementsByTagName('flt-platform-view');\n for(var i = 0; i < fltPlatformViews.length; i++)\n if (fltPlatformViews[i].shadowRoot.getElementById(id) !== null)\n return fltPlatformViews[i].shadowRoot.getElementById(id);\n return null;\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 }",
"_getNode(idx) {\n let currentNode = this.head;\n let count = 0;\n\n while (currentNode !== null && count !== idx) {\n currentNode = currentNode.next;\n count++;\n }\n return currentNode;\n }",
"function getDebugNode(element) {\n var debugNode = null;\n var lContext = loadLContextFromNode(element);\n var lView = lContext.lView;\n var nodeIndex = lContext.nodeIndex;\n if (nodeIndex !== -1) {\n var valueInLView = lView[nodeIndex];\n // this means that value in the lView is a component with its own\n // data. In this situation the TNode is not accessed at the same spot.\n var tNode = isLView(valueInLView) ? valueInLView[T_HOST] :\n getTNode(lView[TVIEW], nodeIndex - HEADER_OFFSET);\n debugNode = buildDebugNode(tNode, lView, nodeIndex);\n }\n return debugNode;\n}",
"function nextLeft(v){var children=v.children;return children?children[0]:v.t;} // This function works analogously to nextLeft.",
"function getFirstLeaf(node: any): Node {\n while (\n node.firstChild &&\n // data-blocks has no offset\n ((isElement(node.firstChild) &&\n (node.firstChild: Element).getAttribute('data-blocks') === 'true') ||\n getSelectionOffsetKeyForNode(node.firstChild))\n ) {\n node = node.firstChild;\n }\n return node;\n}",
"getTargetNode(props: PropsT) {\n const { children, targetRef, targetSelector } = props\n if (children) {\n return ReactDOM.findDOMNode(this._target)\n }\n if (targetRef) {\n return ReactDOM.findDOMNode(targetRef)\n }\n if (targetSelector) {\n return document.querySelector(targetSelector)\n }\n return null\n }",
"function get_xml_node(which_doc, which_id){\r\n\ttry {\r\n\t\treturn which_doc.getElementsByTagName(which_id)[0];\r\n\t}\r\n\tcatch(err) {\r\n\t\treturn null;\r\n\t}\r\n}",
"function findNearestNodeEl(el) {\n while (el !== document.body && !el.classList.contains('blocks-node')) {\n el = el.parentNode;\n }\n return el === document.body? null : el;\n}",
"get topNode() {\n return new TreeNode(this, 0, 0, null)\n }",
"function lensForCurrentMinElement(tree) {\n\tif (isEmpty(tree)) {\n\t\treturn null;\n\t} else if (isEmpty(tree.left)) {\n\t\treturn R.identity;\n\t} else {\n\t\treturn R.compose(\n\t\t\tlenses.leftChild,\n\t\t\tR.defaultTo(\n\t\t\t\tR.identity,\n\t\t\t\tlensForCurrentMinElement(tree.left)));\n\t}\n}",
"first(root, path) {\n var p = path.slice();\n var n = Node$1.get(root, p);\n\n while (n) {\n if (Text.isText(n) || n.children.length === 0) {\n break;\n } else {\n n = n.children[0];\n p.push(0);\n }\n }\n\n return [n, p];\n }",
"getNode(index){\n\t\t//check in hidden nodes\n\t\tfor (var i = 0; i < this.hiddenNodes.length; i++){\n\t\t\tif (this.hiddenNodes[i].index == index){\n\t\t\t\treturn this.hiddenNodes[i]\n\t\t\t}\n\t\t}\n\n\t\t//check input nodes\n\t\tfor (var i = 0; i < this.inputNodes.length; i++){\n\t\t\tif (this.inputNodes[i].index == index){\n\t\t\t\treturn this.inputNodes[i]\n\t\t\t}\n\t\t}\n\n\t\t//check output nodes\n\t\tfor (var i = 0; i < this.outputNodes.length; i++){\n\t\t\tif (this.outputNodes[i].index == index){\n\t\t\t\treturn this.outputNodes[i]\n\t\t\t}\n\t\t}\n\n\t\t//not found\n\t\treturn -1\n\t}",
"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 simpleXPathToNode(xpath) {\n // error was thrown, attempt to just walk down the dom tree\n var currentNode = document.documentElement;\n var paths = xpath.split('/');\n // assume first path is \"HTML\"\n paths: for (var i = 1, ii = paths.length; i < ii; ++i) {\n var children = currentNode.children;\n var path = paths[i];\n var splits = path.split(/\\[|\\]/);\n\n var tag = splits[0];\n if (splits.length > 1) {\n var index = parseInt(splits[1]);\n } else {\n var index = 1;\n }\n\n var seen = 0;\n children: for (var j = 0, jj = children.length; j < jj; ++j) {\n var c = children[j];\n if (c.tagName == tag) {\n seen++;\n if (seen == index) {\n currentNode = c;\n continue paths;\n }\n }\n }\n getLog('misc').error('xPath child cannot be found', xpath);\n return null;\n }\n return [currentNode];\n}",
"function _nodeIndex(node) {\n\t\t// \n\t\tif (!node.parentNode) return 0;\n\t\t// \n\t\tvar nodes = node.parentNode.childNodes,\n\t\t\tindex = 0;\n\t\t// \n\t\twhile (node != nodes[index]) ++index;\n\t\t// \n\t\treturn index;\n\t}",
"get(index) {\n let foundNode = this._find(index);\n return foundNode ? foundNode.value : undefined;\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 }",
"function walkViewTree(rootView, fn) {\n let visit_ = view => {\n fn(view);\n\n let nsArray = view.subviews();\n let count = nsArray.count();\n for (let i = 0; i < count; i++) {\n visit_(nsArray.objectAtIndex(i));\n }\n };\n\n visit_(rootView);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exit a parse tree produced by ObjectiveCPreprocessorParserpreprocessorParenthesis. | exitPreprocessorParenthesis(ctx) {
} | [
"enterPreprocessorParenthesis(ctx) {\n\t}",
"exitParenthesizedType(ctx) {\n\t}",
"exitPostfixUnaryExpression(ctx) {\n\t}",
"exitPreprocessorDef(ctx) {\n\t}",
"visitExit_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function 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}",
"exitStatementWithoutTrailingSubstatement(ctx) {\n\t}",
"exitPreprocessorBinary(ctx) {\n\t}",
"exitPreprocessorNot(ctx) {\n\t}",
"exitPreprocessorDefined(ctx) {\n\t}",
"exitPreprocessorConditional(ctx) {\n\t}",
"exitConditionalOrExpression(ctx) {\n\t}",
"exitPrefixUnaryExpression(ctx) {\n\t}",
"exitBlockLevelExpression(ctx) {\n\t}",
"exitPreprocessorImport(ctx) {\n\t}",
"exitPreprocessorDefine(ctx) {\n\t}",
"exitOrdinaryCompilation(ctx) {\n\t}",
"exitPostfixUnaryOperation(ctx) {\n\t}",
"exitIfExpression(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
opens culture info page | function openCultureInfo(index){
if (cultures[index].filter != "faded" ) {
self.allInfoPages.gotoAndStop(index+1);
}
disableMainPageButtons()
} | [
"function loadLocale() {\n\tvar xobj = new XMLHttpRequest();\n\txobj.overrideMimeType(\"application/json\");\n\txobj.open('GET', '/locales/' + langCode + '.json', true);\n\txobj.onreadystatechange = function () {\n\t\tif (xobj.readyState == 4) {\n\t\t\tif (xobj.status == \"200\") {\n\t\t\t\tlocale = JSON.parse(xobj.responseText);\n\t\t\t\tholdRelease();\n\t\t\t} else {\n\t\t\t\tsplashHandler(\"doa\");// an app without language is unusable\n\t\t\t}\n\t\t}\n\t};\n\txobj.send(null);\n}",
"function footerLanguage(){\r\n\tif(fileName==\"espana.html\"){\r\n\t\tfooterSpanish();\r\n\r\n\t} else if(fileName!=\"espana.html\"){\r\n\t \tfooterGerman();\r\n\t}\r\n}",
"function availableLanguage (site) {\n // Read the language files available\n var locales = fs.readdirSync(__dirname + '/../sites/' + site + '/locales');\n var html = '';\n // See all file and create the html\n for (var i = 0; i < locales.length; i++) {\n html += '<li><a href=\"/locales/' + locales[i].split('.')[0] + '\">' + locales[i].split('.')[0] + '</a></li>';\n } \n return html;\n}",
"function open_answers(page_template) {\n\t\tanswer_window = window.open(page_template, \"Antworten\", \"width=800,height=600,scrollbars=yes\");\n\t\tanswer_window.focus();\n\t}",
"function ausgabe() {\n\tneuesFenster= window.open(\"\", \"fehlerAusgabe\",\n\t\"scrollbars=yes,width=500,height=400\")\n\n\twith (neuesFenster.document) {\n\n\t\topen();\n\t\twrite(\"<html><head><title>Fehlermeldungen\");\n\t\twrite(\"</title></head>\");\n\n\t\twrite(\"<h1>Folgende Fehler sind aufgetreten:</h1>\");\n\n\t\tfor (i = 0; i < fehlerNummer; i++) {\n\t\t\twrite(\"<b>Datei:</b> <i>\" \n\t\t\t+ fehlerURL[i] + \"</i><br>\");\n\t\t\twrite(\"<b>Zeile:</b> <i>\" \n\t\t\t+ fehlerZeile[i] + \"</i><br>\");\n\t\t\twrite(\"<b>Fehlermeldung:</b> <i>\" \n\t\t\t+ fehlerText[i] + \"</i><br><br>\");\n\t\t}\n\t\n\t\twrite(\"</body></html>\");\n\t\tclose();\n\t}\n\n}",
"function getLocale () {\n return locale\n}",
"function openOptionsPage() {\n runtime.openOptionsPage();\n}",
"function onLocaleLinkClick(e)\r\n{\r\n\te.preventDefault();\r\n\t$(document).trigger(\r\n\t{\r\n\t\ttype: \"changeLocaleEvent\",\r\n\t\tlocale: $(this).attr(\"title\").toLowerCase()\r\n\t});\r\n}",
"function showReg()\n{\n var lang = 'en';\n if ('lang' in args)\n lang = args.lang;\n var\tform\t= this.form;\n var\trecid\t= this.id.substring(7);\n // display details\n window.open('WmbDetail.php?IDMB=' + recid + '&lang=' + lang,\n 'baptism');\n return false;\n}\t\t// showReg",
"function CloseArticleInfoWindow ()\n {\n CloseWindow ( wInfo );\n }",
"function markCulture(index) {\n\t\t\tcultures[index].button.gotoAndStop(2);\n\t\t\tcultures[index].button.cursor = \"pointer\";\n\t\t\tcultures[index].filter = \"marked\";\n\t\t}",
"function onLocaleChange(e)\r\n{\r\n\tvar flashObj = getFlashObject();\r\n\t\r\n\t/* Change the active locale of the flash object. */\r\n\tif (flashObj && flashObj['changeLocale'])\r\n\t{\r\n\t\tflashObj.changeLocale(e.locale);\r\n\t}\r\n\t\r\n\t/* Remove the active-class from the all tabs, add it to the current language. */\r\n\t$(\"#locale a.active\").removeClass('active');\r\n\t$(\"#locale a.\" + e.locale).addClass('active');\r\n\t\r\n\t/* Change alert message if no flash. */\r\n\tif ($(\"#noflash-message div\"))\r\n\t{\r\n\t\t$(\"#noflash-message div\").addClass('hidden');\r\n\t\t$(\"#noflash-message div.\" + e.locale).removeClass('hidden');\r\n\t}\r\n\t\r\n\t/* Update the URL with the selected language. */\r\n\tif (window.history && window.history.pushState)\r\n\t{\r\n\t\twindow.history.pushState(\r\n\t\t{\r\n\t\t\tlocale: e.locale\r\n\t\t}, document.title, \"?locale=\" + e.locale);\r\n\t}\r\n\t\r\n /* Sets a cookie to remember the language use. */\r\n $.cookie(\"locale\", e.locale);\r\n}",
"function openLocationInfo(){\n\tvar myWindow=window.open(\"\",\"\",\"width=1000,height=300\");\n\tmyWindow.document.write(\"Site is hoasted on: \" + location.host + \"(\"+ location.hostname + \":\" + (location.port ? location.port : \"?\") + \")<br>\");\n\tmyWindow.document.write(\"Site URL: \"+ location.href + \"<br>\");\n\tmyWindow.document.write(\"File location: \" + location.pathname + \"<br>\");\n\tmyWindow.document.write(\"Site runs a <b>\" + location.protocol + \"</b> protocol<br>\");\n\tmyWindow.document.write(\"Site URL: \"+ location.hash + \"<br>\");\n\tmyWindow.document.write(\"Site URL: \"+ location.search + \"<br>\");\n\tmyWindow.document.write(\"<a href='#' onClick=window.location.assign('http://google.se')>open google</a><br>\");\n\tmyWindow.document.write(\"<a href='#' onClick=window.location.replace('http://google.se')>Replace document widh google</a>\");\n}",
"dayViewTitle({ date, locale }) {\n return new Intl.DateTimeFormat(locale, {\n day: 'numeric',\n month: 'long',\n year: 'numeric',\n weekday: 'long'\n }).format(date);\n }",
"function TM_P_Infobox_Schienenfahrzeug()\n{\n\tvar self = this;\n\tTM_P_Wiki2Template.call(this);\n\n\tvar name = \"Infobox Schienenfahrzeug\";\n\tthis.opGetName = function() {return name;};\n\n\tvar template = \"Infobox Schienenfahrzeug\";\n\tthis.opGetTemplate = function() {return template;};\n\n\tvar super_opTransform = this.opTransform;\n\tthis.opTransform = function(wiki_text) {\n\t\twiki_text = super_opTransform(wiki_text);\n\t\tvar Template = new Object();\n\t\tTemplate[\"template_name\"] = template;\n\t\tTemplate[\"source\"] = \"plug-in\";\n\t\tvar line = wiki_text.split(\"\\n\");\n\t\tfor (var i = 0; i < line.length; i++) if ((line[i].search(/\\s*(\\|-|\\|\\}|\\{\\|)/) != 0) && (line[i].search(/\\|\\|/) > 0)) {\n\t\t\tvar entry = line[i].split(\"||\");\n\t\t\tif (entry.length != 2) {alert(\"TM_P_Infobox_Schienenfahrzeug: Momentan wird nur ein ||-Trenner pro Zeile unterstützt.\");return null;}\n\t\t\tvar x_wikilink = /\\[\\[[^|]+\\|([^\\]]+)\\]\\]/;\n\t\t\tif (entry[0].search(x_wikilink) >= 0) entry[0] = entry[0].replace(x_wikilink, \"$1\");\n\t\t\tentry[0] = entry[0].replace(/^\\s*\\|\\s*/g, \"\").replace(/^\\s*(\\S.*\\S)\\s*$/g,\"$1\").replace(/[^a-zA-ZäöüÄÖÜß0-9_]/g,\"\");\n\t\t\tentry[1] = entry[1].replace(/^\\s*(\\S.*\\S)\\s*$/g,\"$1\");\n\t\t\tif (entry[1].charAt(0) == \"|\") entry[1] = entry[1].substring(1);\n\t\t\tif (entry[0].search(/^Indienststellung$/i) == 0) entry[0] = \"Baujahre\";\n\t\t\tif ((entry[1].search(/^\\s*k\\s*\\.\\s*A\\s*(\\.){0,1}\\s*$/) < 0) && (entry[1].search(/^\\s*-+\\s*/) < 0)) {\n\t\t\t\tTemplate[\"tm_form_\"+entry[0]] = entry[1];\n\t\t\t}\n\t\t} else if (line[i].search(/^\\s*!.*((color:|background)[^\\|]*){2,2}\\|.*/) == 0) {\n\t\t\tvar base_color_name = {\"aqua\":\"00ffff\", \"black\":\"000000\", \"blue\":\"0000ff\", \"fuchsia\":\"ff00ff\", \"gray\":\"808080\", \"green\":\"008000\", \"lime\":\"00ff00\", \"maroon\":\"800000\", \"navy\":\"000080\", \"olive\":\"808000\", \"purple\":\"800080\", \"red\":\"ff0000\", \"silver\":\"c0c0c0\", \"teal\":\"008080\", \"white\":\"ffffff\", \"yellow\":\"ffff00\"};\n\t\t\t// Baureihe, Farbe1 und Farbe2\n\t\t\tvar baureihe = line[i].substring(line[i].search(/\\|/) + 1).replace(/^\\s*(\\S.*\\S)\\s*$/g,\"$1\");\n\t\t\tvar farbe2 = line[i].replace(/^.*[^a-zA-Z]color\\s*:\\s*(#[a-fA-F0-9]{6,6}|[a-zA-Z]+).*/,\"$1\").replace(/^\\s*(\\S.*\\S)\\s*$/g,\"$1\");\n\t\t\tvar farbe1 = line[i].replace(/^.*[^a-zA-Z]background(-color){0,1}\\s*:\\s*(#[a-fA-F0-9]{6,6}|[a-zA-Z]+).*/,\"$2\").replace(/^\\s*(\\S.*\\S)\\s*$/g,\"$1\");\n\t\t\tif (farbe1.charAt(0) == \"#\") farbe1 = farbe1.substring(1);\n\t\t\telse if (base_color_name[farbe1.toLowerCase()]) farbe1 = base_color_name[farbe1.toLowerCase()]; else farbe1 = null;\n\t\t\tif (farbe2.charAt(0) == \"#\") farbe2 = farbe2.substring(1);\n\t\t\telse if (base_color_name[farbe2.toLowerCase()]) farbe2 = base_color_name[farbe2.toLowerCase()]; else farbe2 = null;\n\t\t\tTemplate[\"tm_form_Baureihe\"] = baureihe;\n\t\t\tif (farbe1 != null) Template[\"tm_form_Farbe1\"] = farbe1;\n\t\t\tif (farbe2 != null) Template[\"tm_form_Farbe2\"] = farbe2;\n\t\t} else if (line[i].search(/^\\s*(!|\\|[^\\-]).*\\[\\[(Bild|Image):[^\\]]+\\]\\]/) == 0) {\n\t\t\tvar bild = line[i].replace(/^\\s*(!|\\|).*\\[\\[(Bild|Image):([^\\]]+)\\]\\].*/,\"$3\");\n\t\t\tbild = bild.split(\"|\");\n\t\t\tTemplate[\"tm_form_Abbildung\"] = bild[0];\n\t\t\tfor (var k = 1; k < bild.length; k++) if (bild[k].search(\"[0-9]px\") < 0) {\n\t\t\t\tTemplate[\"tm_form_Name\"] = bild[k].replace(/^\\s*(\\S.*\\S)\\s*$/g,\"$1\");\n\t\t\t}\n\t\t}\n\t\treturn Template;\n\t}\n}",
"postLocaleToChildren() {\n const country = localStorage.getItem('country');\n const dateTimeFormat = localStorage.getItem('dateTimeFormat');\n const decimalSeparator = localStorage.getItem('decimalSeparator');\n this.postMessageToChild(MessageType.locale, {\n country,\n dateTimeFormat,\n decimalSeparator\n });\n }",
"function reportePagos(){\n //se obtiene el valor elegido del combobox\n let pago = $('#tipoPago').val(); \n //abre el reporte en otra pagina y manda a llamar el dato del combobox\n window.open('../../core/reportes/ventasPago1.php?pago='+pago);\n}",
"constructor() { \n \n LocalizationRead.initialize(this);\n }",
"locale() {\n return d3.formatLocale(this.selectedLocale);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find capability object in service object in network object | function ipFindCapabilityByName(pName, networkServiceObj) {
if(networkServiceObj == null)
return null;
if(networkServiceObj.capability != null) {
for(var i=0; i<networkServiceObj.capability.length; i++) {
var capabilityObj = networkServiceObj.capability[i];
if(capabilityObj.name == pName)
return capabilityObj;
}
}
return null;
} | [
"function ipFindNetworkServiceByName(pName, networkObj) { \n if(networkObj == null)\n return null;\n if(networkObj.service != null) {\n\t for(var i=0; i<networkObj.service.length; i++) {\n\t var networkServiceObj = networkObj.service[i];\n\t if(networkServiceObj.name == pName)\n\t return networkServiceObj;\n\t }\n } \n return null;\n}",
"function getVcapServices() {\n var vcstr = process.env.VCAP_SERVICES;\n if (vcstr != null && vcstr.length > 0 && vcstr != '{}') {\n console.log(\"found VCAP_SERVICES: \" + vcstr)\n\n var vcap = JSON.parse(vcstr);\n if (vcap != null) {\n if (vcap.hasOwnProperty(\"p.redis\")) {\n console.log(\"found redis instance: \" + vcap[\"p.redis\"][0].name);\n return vcap[\"p.redis\"][0]\n }\n else if (vcap.hasOwnProperty(\"p-redis\")) {\n console.log(\"found redis instance: \" + vcap[\"p-redis\"][0].name);\n return vcap[\"p-redis\"][0]\n }\n else {\n console.log(\"ERROR: no redis service bound!\")\n }\n }\n else {\n console.log(\"ERROR: no redis service bound!\")\n }\n }\n else {\n console.log(\"ERROR: VCAP_SERVICES does not contain a redis block\")\n }\n return null\n}",
"function getCapabilities(){\n// Gets available capabilities and update indexes\n getSupervisorCapabilityes(function(err, caps){\n // Just for the ready message\n var descriptions = [];\n // Update indexes\n _.each(caps, function(capsDN , DN){\n capsDN.forEach(function(cap , index){\n var capability = mplane.from_dict(cap);\n //if (!__availableProbes[DN])\n // __availableProbes[DN] = [];\n capability.DN = DN;\n\n // If source.ip4 param is not present we have no way to know where the probe is with respect of our net\n if (_.indexOf(capability.getParameterNames() , PARAM_PROBE_SOURCE) === -1){\n showTitle(\"The capability has no \"+PARAM_PROBE_SOURCE+\" param\");\n }else{\n descriptions.push(\"(\"+DN+\") \" + capability.get_label() + \" : \" +capability.result_column_names().join(\" , \"));\n var sourceParamenter = capability.getParameter(PARAM_PROBE_SOURCE);\n var ipSourceNet = (new mplane.Constraints(sourceParamenter.getConstraints()['0'])).getParam();\n capability.ipAddr= ipSourceNet;\n // Add to the known capabilities\n var index = (__availableProbes.push(capability))-1;\n var netId = ipBelongsToNetId(ipSourceNet);\n if (netId){\n if (!__IndexProbesByNet[netId])\n __IndexProbesByNet[netId] = [];\n __IndexProbesByNet[netId].push(index);\n }\n var capTypes = capability.result_column_names();\n capTypes.forEach(function(type , i){\n if (!__IndexProbesByType[type])\n __IndexProbesByType[type] = [];\n __IndexProbesByType[type].push(index);\n });\n }\n }); // caps of a DN\n });\n info(descriptions.length+\" capabilities discovered on \"+cli.options.supervisorHost);\n descriptions.forEach(function(desc , index){\n info(\"......... \"+desc);\n });\n\n console.log(\"\\n\");\n console.log();\n cli.info(\"--------------------\");\n cli.info(\"INIT PHASE COMPLETED\");\n cli.info(\"--------------------\");\n console.log();\n\n // Periodically scan all the net\n if (cli.options.mode == \"AUTO\"){\n setInterval(function(){\n scan();\n }\n ,configuration.main.scan_period);\n setInterval(function(){\n // Periodically check if results are ready\n checkStatus();\n }\n ,configuration.main.results_check_period);\n }else{\n waitForTriggers();\n }\n });\n}",
"function getSupervisorCapabilityes(callback){\n supervisor.showCapabilities({\n caFile : cli.options.ca,\n keyFile : cli.options.key,\n certFile : cli.options.cert,\n host : cli.options.supervisorHost,\n port: cli.options.supervisorPort\n },\n function(error , caps){\n if (error){\n showTitle(\"Error connecting to the supervisor.\"+error.toString());\n callback(new Error(\"Error connecting to the supervisor.\"+error.toString()), null);\n }\n if (_.keys(caps).length == 0){\n showTitle(\"NO CAPABILITY registered on the supervisor\");\n }else{\n callback(null, caps);\n }\n });\n}",
"function getDeviceObject(){\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tfor(var a=0; a<devices.length; a++){\n\t\tif (devices[a].ObjectPath == glblDevMenImg){\n\t\t\treturn devices[a];\n\t\t}\n\t}\n}",
"isMonitored(node) {\n let monitoredNode = this.monitoredNodes.find(\n monitoredNode => monitoredNode === node.id\n )\n\n if (monitoredNode) {\n return monitoredNode\n }\n }",
"function getFeature(category, feature) {\n function featureFilter(featureObj) {\n if (featureObj.category == category && featureObj.name == feature) { return true; } else { return false; }\n }\n var foundFeature = self.features.filter(featureFilter);\n if (foundFeature.length == 1) {\n return foundFeature[0];\n }\n else {\n throw (new Error(\"No such feature '\" + feature + \"' in category '\" + category + \"' for vpn with id '\" + self.id + \"'\"));\n }\n }",
"function getTargetServiceCreep(creep, creepsByRoleList) {\r\n\t var targetCreep;\r\n\t var highestEnergy = 0;\r\n\t var returnCreep;\r\n\t for (var j in creepsByRoleList['harvester'] ) {\r\n\t\t\ttargetCreep = creepsByRoleList['harvester'][j];\r\n\t\t\t\r\n\t\t\t//console.log(\"Pulled from role list\" + targetCreep);\r\n\t\t\tif(targetCreep.room != creep.room) {\r\n\t\t\t continue;\r\n\t\t\t}\r\n\t\t\tif(targetCreep.memory.inService == true) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif(targetCreep.carry.energy > highestEnergy) {\r\n\t\t\t//if(targetCreep.energy / targetCreep.energyCapacity > .4){\r\n\t\t\t\treturnCreep = j; //the target will be the one with the highest energy, that is not in service by another harvester\r\n\t\t\t\t//console.log(\"highest energy creep was \"+ j);\r\n\t\t\t\thighestEnergy = targetCreep.carry.energy;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn returnCreep;\r\n\t}",
"function findNetworkAddress(criteria) {\n const ifaces = os.networkInterfaces();\n const ifacesKeys = Object.keys(ifaces);\n\n for (let i = 0; i < ifacesKeys.length; i++) {\n const netAddresses = ifaces[ifacesKeys[i]];\n \n const firstExternalNetworkAddress = netAddresses.filter(netAddress => {\n return criteria(netAddress);\n });\n\n if (firstExternalNetworkAddress.length > 0) {\n return firstExternalNetworkAddress[0];\n }\n }\n}",
"static Get(serviceName) {\n\t if(!this.g_services) this.g_services = [];\n\t \n\t return this.g_services[serviceName];\n }",
"function getPortIdforManageConnectivity(portObj,action){\n\tvar port =\"\";\n\tif(globalInfoType == \"JSON\"){\n\t\tvar ojb = portObj.split(\".\")[0];\n\t\tvar objArr = obj.split(\".\");\n var prtArr = getAllPortOfDevice(objArr[0]);\n }else{\n var prtArr= portArr;\n }\n\tfor (var a=0; a<prtArr.length; a++){\n\t\tif (prtArr[a].ObjectPath == portObj){\n\n\t\t\tif (action == \"lineName\"){\n\t\t\t\tport = \"t\"+prtArr[a].Speed+\"_\"+window['variable' + dynamicLineConnected[pageCanvas]].length+1;\t\t\t\t\n\t\t\t}else{\n\t\t\t\tport = prtArr[a].PortId;\n\t\t\t}\n\t\t}\n\t}\n\treturn port;\n}",
"get(service_type) {\n return this._instances.get(service_type)\n }",
"function retrieveUAFromProfile() {\n\n \tvar profileUASet = identity.getAttribute(attributeWhereUAStored);\n if (profileUASet == null || profileUASet.isEmpty()) {\n \n \tlogMessage(\"User agent not found on profile\");\n return false;\n }\n \n profileUA = profileUASet.iterator().next();\n logMessage(\"User agent found on profile as \" + profileUA);\n \n\n}",
"isMultiremote () {\n let caps = this.configParser.getCapabilities()\n return !Array.isArray(caps)\n }",
"function declassifyRec(objInfo, object, objectPolicy, target, targetPolicy, effPolicy) {\n return new Promise(function(resolve, reject) { \n var promises = [];\n\n var filtered = object instanceof Array ? [] : {};\n var curOPol = objectPolicy;\n\n var selfPolicy = objectPolicy.getProperty(\"\");\n if(selfPolicy !== null || effPolicy === undefined)\n effPolicy = selfPolicy;\n\n for(var p in object) {\n if(object.hasOwnProperty(p)) {\n var promise = null;\n\n if(!(curOPol.o.p && curOPol.o.p.hasOwnProperty(p)) && effPolicy === null)\n continue;\n\n // TODO: replace these checks with getSubPolicyObject result\n if(typeof object[p] === \"object\" && curOPol.o.p && curOPol.o.p.hasOwnProperty(p)) {\n var propPolicy = curOPol.getProperty(p);\n if(propPolicy === null)\n promise = genDeclassifyPromise(p, object[p], curOPol.getSubPolicyObject(p), target, targetPolicy, objInfo, effPolicy);\n else\n promise = genDeclassifyPromise(p, object[p], curOPol.getSubPolicyObject(p), target, targetPolicy, objInfo, propPolicy);\n } else {\n // TODO: p is inside a loop => correct as it changes in the promise while looping\n // translate into function call => only way to avoid the same variable scope!\n\n var propPolicy = curOPol.getProperty(p);\n if(propPolicy === null)\n promise = genCheckReadPromise(p, object, target, targetPolicy, objInfo, effPolicy);\n else \n promise = genCheckReadPromise(p, object, target, targetPolicy, objInfo, propPolicy);\n }\n\n promises.push(promise);\n }\n }\n\n var promise = null;\n if(effPolicy !== null)\n promise = pdp.checkRead(target, targetPolicy, objInfo, effPolicy)\n else\n promise = Promise.resolve({ grant: true });\n\n promise.then(function(result) {\n if(promises.length === 0) {\n if(result.grant)\n resolve(clone(object));\n else\n resolve(null);\n } else {\n Promise.all(promises).then(function(values) {\n for(var i in values) {\n if(values[i].value !== undefined)\n filtered[values[i].prop] = values[i].value;\n }\n if(Object.keys(filtered).length > 0)\n resolve(filtered);\n else {\n if(result.grant)\n resolve({})\n else\n resolve(null);\n }\n }, function(reason) {\n reject(reason);\n });\n }\n }, function(e) {\n reject(e);\n });\n });\n}",
"getElementServicesForProbe (probe) {\n // Retrieve target elements for all models or specified one\n let services = this.app.getElementServices(probe.forecast)\n services = services.filter(service => {\n return probe.elements.reduce((contains, element) => contains || (service.name === probe.forecast + '/' + element), false)\n })\n return services\n }",
"function dwscripts_findGroup(groupName, title, sbConstructor)\n{\n // get the list of server behavior objects\n var sbObjList = extGroup.find(groupName, title, sbConstructor);\n\n return sbObjList;\n}",
"getServices() {\n let services = []\n this.informationService = new Service.AccessoryInformation();\n this.informationService\n .setCharacteristic(Characteristic.Manufacturer, \"OpenSprinkler\")\n .setCharacteristic(Characteristic.Model, \"OpenSprinkler\")\n .setCharacteristic(Characteristic.SerialNumber, \"opensprinkler-system\");\n services.push(this.informationService)\n\n // Add the irrigation system service\n this.irrigationSystemService = new Service.IrrigationSystem(this.name);\n this.irrigationSystemService.getCharacteristic(Characteristic.Active)\n .on(\"get\", syncGetter(this.getSystemActiveCharacteristic.bind(this)))\n .on('set', promiseSetter(this.setSystemActiveCharacteristic.bind(this)))\n\n this.irrigationSystemService.getCharacteristic(Characteristic.InUse)\n .on('get', syncGetter(this.getSystemInUseCharacteristic.bind(this)))\n\n this.irrigationSystemService.getCharacteristic(Characteristic.ProgramMode)\n .on('get', syncGetter(this.getSystemProgramModeCharacteristic.bind(this)))\n\n this.irrigationSystemService.addCharacteristic(Characteristic.RemainingDuration)\n .on('get', syncGetter(this.getSystemRemainingDurationCharacteristic.bind(this)))\n\n this.irrigationSystemService.setPrimaryService(true)\n\n services.push(this.irrigationSystemService)\n\n // Add the service label service\n this.serviceLabelService = new Service.ServiceLabel()\n this.serviceLabelService.getCharacteristic(Characteristic.ServiceLabelNamespace).setValue(Characteristic.ServiceLabelNamespace.DOTS)\n\n // Add all of the valve services\n this.sprinklers.forEach(function (sprinkler) {\n sprinkler.valveService = new Service.Valve(\"\", \"zone-\" + sprinkler.sid);\n // sprinkler.valveService.subtype = \"zone-\" + sprinkler.sid\n\n // Set the valve name\n const standardName = 'S' + ('0' + sprinkler.sid).slice(-2);\n let userGaveName = standardName != sprinkler.name;\n // log(\"Valve name:\", sprinkler.name, userGaveName)\n if (userGaveName) {\n sprinkler.valveService.getCharacteristic(Characteristic.Name).setValue(sprinkler.name)\n // sprinkler.valveService.addCharacteristic(Characteristic.ConfiguredName).setValue(sprinkler.name)\n }\n\n sprinkler.valveService.getCharacteristic(Characteristic.ValveType).updateValue(Characteristic.ValveType.IRRIGATION);\n\n sprinkler.valveService\n .getCharacteristic(Characteristic.Active)\n .on('get', syncGetter(sprinkler.getSprinklerActiveCharacteristic.bind(sprinkler)))\n .on('set', promiseSetter(sprinkler.setSprinklerActiveCharacteristic.bind(sprinkler)))\n\n sprinkler.valveService\n .getCharacteristic(Characteristic.InUse)\n .on('get', syncGetter(sprinkler.getSprinklerInUseCharacteristic.bind(sprinkler)))\n\n sprinkler.valveService.addCharacteristic(Characteristic.SetDuration)\n .on('get', syncGetter(() => sprinkler.setDuration))\n .on('set', (duration, next) => {\n sprinkler.setDuration = duration\n log.debug(\"SetDuration\", duration)\n next()\n })\n\n sprinkler.valveService.addCharacteristic(Characteristic.RemainingDuration)\n\n // Set its service label index\n sprinkler.valveService.addCharacteristic(Characteristic.ServiceLabelIndex).setValue(sprinkler.sid)\n \n // Check if disabled\n sprinkler.disabledBinary = this.disabledStations.toString(2).split('').reverse()\n sprinkler.isDisabled = sprinkler.disabledBinary[sprinkler.sid - 1] === '1'\n\n // log('DISABLED length + sid -------->' + this.sprinklers.length + ' ' + sprinkler.sid)\n // log('DISABLED DATA -------->' + sprinkler.disabledBinary + ' ' + (sprinkler.sid - 1) + ' ' + sprinkler.isDisabled)\n\n // Set if it's not disabled\n // const isConfigured = !sprinkler.isDisabled ? Characteristic.IsConfigured.CONFIGURED : Characteristic.IsConfigured.NOT_CONFIGURED\n sprinkler.valveService.getCharacteristic(Characteristic.IsConfigured)\n .on('get', syncGetter(sprinkler.getSprinklerConfiguredCharacteristic.bind(sprinkler)))\n .on('set', promiseSetter(sprinkler.setSprinklerConfiguredCharacteristic.bind(sprinkler)))\n // .setValue(isConfigured)\n\n // Link this service\n this.irrigationSystemService.addLinkedService(sprinkler.valveService)\n this.serviceLabelService.addLinkedService(sprinkler.valveService)\n\n services.push(sprinkler.valveService)\n }.bind(this))\n\n return services\n }",
"function retrieveIPFromProfile() {\n\n \tvar profileIPSet = identity.getAttribute(attributeWhereIPStored);\n if (profileIPSet == null || profileIPSet.isEmpty()) {\n \n \tlogMessage(\"IP address not found on profile\");\n return false;\n }\n \n profileIP = profileIPSet.iterator().next();\n logMessage(\"IP address found on profile as \" + profileIP);\n \n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
mimics FastLED FillSolid method | function FillSolid(stationId,startIndex,numToFill,ledColor){
if(!isNaN(stationId)){
//update server's copy of the LED cluster state
for(var i=startIndex;i<startIndex+numToFill;i++){
colors[stationId][i].r = ledColor.r;
colors[stationId][i].g = ledColor.g;
colors[stationId][i].b = ledColor.b;
}
}
//console.log(ledColor);
var dataBuffer = new Uint8Array([startIndex,numToFill,ledColor.r,ledColor.g,ledColor.b]);
io.sockets.to(stationId).emit('fillSolid',base64js.fromByteArray(dataBuffer));
} | [
"function drawFlat(spectrum){\n colorMode(HSB, bands);\n var w = width / (bands * 1.5);\n var maxF = Math.max(spectrum);\n for (var i = 0; i < spectrum.length; i++) {\n var amp = spectrum[i];\n var y = map(amp, 0, 255, height, 10);\n fill(i,255,255);\n rect(width/2 + i*w,y,w-2,height-y);\n rect(width/2 - i*w,y,w-2,height-y);\n }\n}",
"drawRing (vertexArray, color, filled) {\n if (filled) {\n fill(color)\n noStroke()\n }\n else {\n noFill()\n stroke(color)\n strokeWeight(3)\n }\n beginShape()\n for (let vert of vertexArray) {\n vertex(vert.x, vert.y, vert.z)\n }\n vertex(vertexArray[0].x, vertexArray[0].y, vertexArray[0].z)\n endShape()\n }",
"function blinkBlueSquare(timeStart, timeEnd) {\n if (time < timeStart || time > timeEnd) {\n fill(0, 100, 205); \n } else if (time < timeEnd) {\n fill(128, 179, 255);\n }\n rect(width/2 + displacement, height/2 + displacement, 350, 350);\n}",
"function blinkGreenSquare(timeStart, timeEnd) {\n if (time < timeStart || time > timeEnd) {\n fill(10, 175, 90);\n } else if (time < timeEnd) {\n fill(153, 242, 67);\n }\n rect(displacement, displacement, 350, 350);\n}",
"function renderPallet(){\n\tfor(let i = 0; i < numColor; i++){\n\t\tswatches[i].display();\n\t}\n\tfillIcon.display();\n}",
"function cycleDrawColour() {\n Data.Edit.Node.style.stroke = cycleColour(Data.Edit.Node.style.stroke);\n hasEdits(true);\n}",
"function flushLEDs()\r\n{\r\n\t// changedCount contains number of lights changed\r\n var changedCount = 0;\r\n\r\n // count the number of LEDs that are going to be changed by comparing pendingLEDs to activeLEDs array\r\n for(var i=0; i<80; i++)\r\n {\r\n if (pendingLEDs[i] != activeLEDs[i]) changedCount++;\r\n }\r\n\r\n // exit function if there are none to be changed\r\n if (changedCount == 0) return;\r\n\r\n //uncommenting this displays a count of the number of LEDs to be changed\r\n // //println(\"Repaint: \" + changedCount + \" LEDs\");\r\n\r\n for(var i = 0; i<80; i++)\r\n {\r\n if (pendingLEDs[i] != activeLEDs[i])\r\n { \r\n activeLEDs[i] = pendingLEDs[i];\r\n\r\n var colour = activeLEDs[i];\r\n\r\n if (i < 16) // Main Grid\r\n {\r\n var column = i & 0x7;\r\n var row = i >> 3;\r\n\r\n if (colour >=200 && colour < 328)//flashing colour numeration. need to substract 200 to get the appropriate final color\r\n {\r\n host.getMidiOutPort(1).sendMidi(0x92, 96 + row*16 + column, colour-200);\r\n }\r\n else\r\n {\r\n host.getMidiOutPort(1).sendMidi(0x9F, 96 + row*16 + column, colour);\r\n }\r\n }\r\n\r\n else if (i>=64 && i < 66) // Right buttons\r\n {\r\n host.getMidiOutPort(1).sendMidi(0x9F, 96 + 8 + (i - 64) * 16, colour);\r\n }\r\n }\r\n }\r\n}",
"fill(colour) {\r\n this.ctx.fillStyle = colour;\r\n this.ctx.fillRect(0, 0, this.width, this.height);\r\n }",
"function createPallet(){\n\tfor(let i = 0; i < numColor; i++){\n\t\tswatches.push(new ColorSwatch(\t((i*colorSwatchRadius)+colorSwatchRadius/2), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolorSwatchRadius/2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolorSwatchRadius/2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t colorArray[i]));\n\t}\n\tfillIcon = new FillIcon(canvasWidth-frameThickness*.75, canvasWidth/40, canvasWidth/20);\n}",
"function drawReflectiveShieldIcon(ctx){\n // image of the icon\n // draw the shield line\n ctx.strokeStyle = \"#000000\";\n ctx.lineWidth = 2.0;\n ctx.beginPath();\n ctx.arc(0, 25, 25, 1.32*Math.PI, 1.68*Math.PI, false);\n ctx.stroke();\n ctx.closePath();\n \n // draw the two bullets\n ctx.lineWidth = 3.0;\n ctx.beginPath();\n var gradient = ctx.createLinearGradient(-4, -15, -4, 9);\n gradient.addColorStop(0, \"rgb(192, 192, 192)\");\n gradient.addColorStop(1, \"rgb(160, 0, 0)\");\n ctx.strokeStyle = gradient;\n ctx.moveTo(-4, -12);\n ctx.lineTo(-4, 9);\n ctx.stroke();\n ctx.closePath();\n ctx.beginPath();\n gradient = ctx.createLinearGradient(4, -9, 4, 15);\n gradient.addColorStop(0, \"rgb(160, 0, 0)\");\n gradient.addColorStop(1, \"rgb(192, 192, 192)\");\n ctx.strokeStyle = gradient;\n ctx.moveTo(4, 12);\n ctx.lineTo(4, -9);\n ctx.closePath();\n ctx.stroke();\n}",
"AddQuadFilled(a, b, c, d, col) {\r\n this.native.AddQuadFilled(a, b, c, d, col);\r\n }",
"function blinkYellowSquare(timeStart, timeEnd) {\n if (time < timeStart || time > timeEnd) {\n fill(235, 190, 0); \n } else if (time < timeEnd) {\n fill(255, 230, 128);\n }\n rect(displacement, height/2 + displacement, 350, 350);\n}",
"function fillFromPoint(canvas, p1, rI, gI, bI){\n console.log(canvas);\n var frontier = [];\n var width = canvas.width;\n var height = canvas.height;\n var context = canvas.getContext('2d');\n var imgData = context.getImageData(0, 0, width, height);\n var pos = (p1.y * width + p1.x) * 4;\n\n frontier.push(p1);\n\n var r = imgData.data[pos];\n var g = imgData.data[pos + 1];\n var b = imgData.data[pos + 2];\n\n if (rI == r && g == gI && b == bI){\n return;\n }\n\n imgData.data[pos] = rI;\n imgData.data[pos + 1] = gI;\n imgData.data[pos + 2] = bI;\n\n while (frontier.length){\n var point, left, right;\n point = frontier.pop();\n\n pos = (point.y * width + point.x) * 4;\n\n for (var i=0; i < neigh.length; i++){\n\n var tPosX = point.x + neigh[i][0];\n var tPosY = point.y + neigh[i][1];\n\n if (tPosX >= 0 && tPosX < width && tPosY >= 0 && tPosY < height){\n var tPos = ((tPosY * width + tPosX) * 4);\n\n if (imgData.data[tPos] == r && imgData.data[tPos + 1] == g && imgData.data[tPos + 2] == b){\n imgData.data[pos] = rI;\n imgData.data[pos + 1] = gI;\n imgData.data[pos + 2] = bI;\n frontier.push(new Point(tPosX, tPosY));\n }\n }\n }\n }\n context.putImageData(imgData,0,0 );\n}",
"blendSide(data, left) {\n let _sideLength = data.data.length\n let _sourceX = left ? 0 : this._imageWidth - BLEND\n let _sourceHeight = this._imageHeight + this._offset\n //let _sourceData = this._ctx.getImageData(0, 0, this._imageWidth, this._imageHeight + this._offset)\n let _sourceData = this._ctx.getImageData(_sourceX, 0, BLEND, _sourceHeight)\n\n let _total = 4 * _sourceHeight * BLEND\n //let _total = 4 * this._imageWidth * BLEND\n let pixels = _total;\n let _weight = 0\n let _wT = BLEND\n /*while (pixels--) {\n _sourceData.data[pixels] = Math.floor(Math.random() * 255) // _currentPixelR + _newPixelR\n //_sourceData.data[_p + 1] = 0 // _currentPixelG + _newPixelG\n //_sourceData.data[_p + 2] = 0 //_currentPixelB + _newPixelB\n //_sourceData.data[_p + 3] = 255 //_currentPixelA + _newPixelA\n }\n this._ctx.putImageData(_sourceData, 0, 0)\n return*/\n\n let i = left ? 0 : _total\n i = 0\n let l = left ? _total : 0\n l = _total\n let _a = left ? 4 : -4\n _a = 4\n for (i; i < l; i += _a) {\n let _weight = 1.\n let _roll = i % _sideLength\n _weight = i % (BLEND * 4) / (BLEND * 4)\n\n if (!left) {\n _weight = 1 - _weight\n //_weight = 0\n }\n\n let _newPixelR = Math.floor(data.data[_roll] * (1 - _weight))\n let _newPixelG = Math.floor(data.data[_roll + 1] * (1 - _weight))\n let _newPixelB = Math.floor(data.data[_roll + 2] * (1 - _weight))\n let _newPixelA = Math.floor(data.data[_roll + 3])\n\n let _currentPixelR = Math.floor(_sourceData.data[i] * _weight)\n let _currentPixelG = Math.floor(_sourceData.data[i + 1] * _weight)\n let _currentPixelB = Math.floor(_sourceData.data[i + 2] * _weight)\n let _currentPixelA = Math.floor(_sourceData.data[i + 3])\n\n _sourceData.data[i] = _newPixelR + _currentPixelR\n _sourceData.data[i + 1] = _newPixelG + _currentPixelG\n _sourceData.data[i + 2] = _newPixelB + _currentPixelB\n _sourceData.data[i + 3] = 255\n }\n /*console.log(_total, _sourceData.data.length);\n for (let i = 0; i < _wT * 4; i += 3) {\n _weight = i / _wT\n for (let j = 0; j < _sourceHeight * 4; j += 4) {\n let _p = i * j\n let _newPixelR = Math.floor(data.data[_p] * (_weight))\n let _newPixelG = Math.floor(data.data[_p + 1] * (_weight))\n let _newPixelB = Math.floor(data.data[_p + 2] * (_weight))\n let _newPixelA = Math.floor(data.data[_p + 3] * (_weight))\n\n let _currentPixelR = Math.floor(_sourceData.data[_p] * (1 - _weight))\n let _currentPixelG = Math.floor(_sourceData.data[_p + 1] * (1 - _weight))\n let _currentPixelB = Math.floor(_sourceData.data[_p + 2] * (1 - _weight))\n let _currentPixelA = Math.floor(_sourceData.data[_p + 3] * (1 - _weight))\n\n\n _sourceData.data[_p] = 255 // _currentPixelR + _newPixelR\n _sourceData.data[_p + 1] = 0 // _currentPixelG + _newPixelG\n _sourceData.data[_p + 2] = 0 //_currentPixelB + _newPixelB\n _sourceData.data[_p + 3] = 255 //_currentPixelA + _newPixelA\n }\n }*/\n this._ctx.putImageData(_sourceData, _sourceX, 0)\n }",
"static Clear() {\n return new Color4(0, 0, 0, 0);\n }",
"function flashBead(generation, draw){\n\n var nextColor = rgbString(colors[trial.draws[draw]]);\n\n dotGrid.append('circle')\n .attr('cx', x(generation))\n .attr('cy', y(draw))\n .attr('r', 10)\n .attr('fill', nextColor)\n .transition()\n .delay(100)\n .attr('fill', 'transparent')\n .attr('r', 60);\n\n }",
"function changeColor(cord)\n{\n // set fillStyle to Blue\n context2D.fillStyle = \"Blue\";\n // fill clicked cell \n context2D.fillRect(cord[0] * canvas.width / 8, cord[1] * canvas.height / 8, canvas.width / 8, canvas.height / 8);\n}",
"paintFrame() {\n for (let rowIterator = 0; rowIterator < this.gridState.length; rowIterator++) {\n for (let columnIterator = 0; columnIterator < this.columns; columnIterator++) {\n const cellState = Math.pow(2, columnIterator) & this.gridState[rowIterator]\n this.paintBrick(rowIterator, this.columns - columnIterator - 1, cellState !== 0)\n }\n }\n }",
"function rk_altfill(buffer, size, strong, state) {\n var err;\n\n err = rk_devfill(buffer, size, strong);\n if (err) {\n rk_fill(buffer, size, state);\n }\n return err;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the next `LContainer` that is a sibling of the given container. | function getNextLContainer(container) {
return getNearestLContainer(container[NEXT]);
} | [
"function next () {\r\n return this.siblings()[this.position() + 1]\r\n}",
"function getNextSibling(node, tag){\n\tif (!tag) tag = node.nodeName;\n\ttag = tag.toUpperCase();\n\tvar cont = 20; // Limita o numero de itera��es para evitar sobrecarga no ie\n\twhile (node.nextSibling && node.nextSibling.nodeName && node.nextSibling.nodeName.toUpperCase() != tag && cont-- > 0 ){\n\t\tnode = node.nextSibling;\n\t}\n\treturn node.nextSibling;\n}",
"prevSibling() {\n return this.sibling(-1)\n }",
"function nextLeft(v){var children=v.children;return children?children[0]:v.t;} // This function works analogously to nextLeft.",
"function previousElement(element)\r\n{\r\n\twhile (element = element.previousSibling)\r\n\t{\r\n\t\tif (element.nodeType == 1) return element;\r\n\t}\r\n\treturn null;\r\n}",
"function getLastSibling(node) {\n let sibling = node;\n\n while (sibling && sibling.next) {\n sibling = sibling.next;\n }\n\n return sibling;\n}",
"function find_right_sibling(node)\n{\n if (node === null) \n {\n return;\n }\n var current = node.right;\n var rightSibling = null;\n \n while (current != null)\n {\n if (current.children.length > 0)\n {\n rightSibling = current.children[0];\n break;\n }\n else \n {\n current = current.right;\n }\n }\n \n return rightSibling;\n}",
"function nextChild(iter) {\n if (iter.iter >= children.length) {\n // we don't reset the iterator here; the user should create a new iterator\n return null;\n }\n\n return children[iter.iter++];\n }",
"function followingNonDescendantNode(node) {\n if (node.ownerElement) {\n if (node.ownerElement.firstChild) return node.ownerElement.firstChild;\n node = node.ownerElement;\n }\n do {\n if (node.nextSibling) return node.nextSibling;\n } while (node = node.parentNode);\n return null;\n }",
"function nextAll(item,selector){return untilAll(item,selector,'nextElementSibling');}",
"function siblings () {\r\n return this.parent().children()\r\n}",
"function findPrev(item) {\n var currNode = this.head;\n while (currNode.next.element != item && currNode.next.element != \"head\") {\n currNode = currNode.next;\n }\n if (currNode.next.element == item) {\n return currNode;\n }\n return -1;\n }",
"function setNextImage(image) {\n if(document.getElementById(image.id).parentNode.nextSibling !== null){\n nextImage=document.getElementById(image.id).parentNode.nextSibling.firstChild;\n }\n else{\n nextImage = document.getElementById('container').firstChild.firstChild;\n }\n}",
"function nextNonWhitespace(e) {\n\t\tconst {nextSibling} = (e instanceof $ ? e[0] : e);\n\t\tif (nextSibling &&\n\t\t\t\t((nextSibling instanceof Text && !nextSibling.textContent.trim())\n\t\t\t\t|| (nextSibling.tagName || '').toLowerCase() === \"br\")) {\n\n\t\t\tconst { whitespace, nextElem } = nextNonWhitespace(nextSibling);\n\t\t\treturn { whitespace: $(nextSibling).add(whitespace), nextElem };\n\t\t}\n\t\treturn { whitespace: $(), nextElem: $(nextSibling) };\n\t}",
"_panelForHeading(heading) {\n const next = heading.nextElementSibling;\n if (next.tagName.toLowerCase() !== 'howto-accordion-panel') {\n console.error('Sibling element to a heading need to be a panel.');\n return;\n }\n return next;\n }",
"get dropTargetNodes() {\n let target = this._lastDropTarget;\n\n if (!target) {\n return null;\n }\n\n let parent, nextSibling;\n\n if (this._lastDropTarget.previousElementSibling &&\n this._lastDropTarget.previousElementSibling.nodeName.toLowerCase() === \"ul\") {\n parent = target.parentNode.container.node;\n nextSibling = null;\n } else {\n parent = target.parentNode.container.node.parentNode();\n nextSibling = target.parentNode.container.node;\n }\n\n if (nextSibling && nextSibling.isBeforePseudoElement) {\n nextSibling = target.parentNode.parentNode.children[1].container.node;\n }\n if (nextSibling && nextSibling.isAfterPseudoElement) {\n parent = target.parentNode.container.node.parentNode();\n nextSibling = null;\n }\n\n if (parent.nodeType !== Ci.nsIDOMNode.ELEMENT_NODE) {\n return null;\n }\n\n return {parent, nextSibling};\n }",
"function siblingToSibling() {\n let visibilityStatus = s2sStatus();\n setType(\"s2s\", visibilityStatus);\n}",
"function getParent(eventTarget) {\n return isNode(eventTarget) ? eventTarget.parentNode : null;\n }",
"next() {\n let tmp = this.currentNode.next();\n\n if (!tmp.done) {\n this.currentNode = tmp.value;\n this.ptree();\n }\n\n return tmp;\n }",
"function detectCycle(head) {\n\tlet p1 = head;\n\tlet p2 = head;\n\twhile (p2) {\n\t\tif (!p2.next) {\n\t\t\treturn null;\n\t\t}\n\t\tp1 = p1.next;\n\t\tp2 = p2.next.next;\n\t\tif (p1 === p2) {\n\t\t\tp1 = head;\n\t\t\twhile (true) {\n\t\t\t\tif (p1 === p2) {\n\t\t\t\t\treturn p1;\n\t\t\t\t}\n\t\t\t\tp1 = p1.next;\n\t\t\t\tp2 = p2.next;\n\t\t\t\t\n\t\t\t}\n\t\t} \n\t} \n\treturn null;\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
enables the normal buffer in the VAO | enableNormalBuffer () {
const gl = this.gl;
gl.bindBuffer(gl.ARRAY_BUFFER, this.normalBuffer);
gl.enableVertexAttribArray(1);
gl.vertexAttribPointer(1,
3, gl.FLOAT,
false,
0,
0
);
} | [
"createNormalBuffer () {\n\t\tif (this.normalArray === null) {\n\t\t\tconsole.log(\"normalArray uninitialized\");\n\t\t}\n\n\t\tconst gl = this.gl;\n\t\tthis.normalBuffer = gl.createBuffer();\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, this.normalBuffer);\n\t\tgl.bufferData(gl.ARRAY_BUFFER,\n \t\tnew Float32Array(this.normalArray),\n \t\tgl.STATIC_DRAW);\n\t}",
"enableColorBuffer () {\n\t\tconst gl = this.gl;\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);\n\t gl.enableVertexAttribArray(1);\n\t gl.vertexAttribPointer(1,\n\t 3, gl.FLOAT,\n\t false,\n\t 0,\n\t 0\n\t );\n\t}",
"activate()\r\n\t{\r\n\t\t// TODO\r\n\t\tsuper.activate();\r\n\t\tthis.gl.enableVertexAttribArray(this.colorAttribLocation);\r\n\t\tthis.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.colorBufferObject);\r\n\t\tthis.gl.vertexAttribPointer\r\n\t\t(\r\n\t\t\tthis.colorAttribLocation,\r\n\t\t\t3,\r\n\t\t\tthis.gl.FLOAT,\r\n\t\t\tthis.gl.FALSE,\r\n\t\t\t3 * Float32Array.BYTES_PER_ELEMENT,\r\n\t\t\t0\r\n\t\t);\r\n\r\n\t\tthis.gl.enableVertexAttribArray(this.normalAttribLocation);\r\n\t\tthis.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.normalBufferObject);\r\n\t\tthis.gl.vertexAttribPointer(\r\n\t\t\tthis.normalAttribLocation,\r\n\t\t\t3,\r\n\t\t\tthis.gl.FLOAT,\r\n\t\t\tthis.gl.FALSE,\r\n\t\t\t3 * Float32Array.BYTES_PER_ELEMENT,\r\n\t\t\t0\r\n\t\t);\r\n\t}",
"enablePositionBuffer () {\n\t\tconst gl = this.gl;\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);\n\n\t\t// enable the vertex position buffer as the 0th attribute\n\t gl.enableVertexAttribArray(0);\n\n\t // explain to OpenGL how to parse the vertex position buffer\n\t gl.vertexAttribPointer(0,\n\t 3, gl.FLOAT, // three pieces of float\n\t false, // do not normalize (make unit length)\n\t 0, // tightly packed\n\t 0 // data starts at array start\n \t);\n\t}",
"deactivate()\r\n\t{\r\n\t\t// TODO\r\n\t\tthis.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, null);\r\n\t\tthis.gl.bindBuffer(this.gl.ARRAY_BUFFER, null);\r\n\t\tthis.gl.disableVertexAttribArray(this.positionAttribLocation);\r\n\t\tthis.gl.disableVertexAttribArray(this.normalAttribLocation);\r\n\t}",
"function VertexBufferManager() {}",
"function activateDrawMode() {\n \"use strict\";\n inDrawMode = true;\n inEraseMode = !inDrawMode;\n console.log(\"activated DrawMode\");\n}",
"function OnEnable () { \n gameObject.transform.root.gameObject.GetComponent(FPSInputController).enabled = false;\n gameObject.transform.root.gameObject.GetComponent(MouseLook).enabled = false;\n gameObject.transform.root.gameObject.GetComponent(CharacterMotor).enabled = false;\n transform.root.FindChild(playerCameraPrefab).gameObject.SetActive(false);\n \n}",
"function drawSphere() {\r\n gl.bindBuffer(gl.ARRAY_BUFFER, sphereVertexPositionBuffer);\r\n gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, sphereVertexPositionBuffer.itemSize, \r\n gl.FLOAT, false, 0, 0);\r\n\r\n // Bind normal buffer\r\n gl.bindBuffer(gl.ARRAY_BUFFER, sphereVertexNormalBuffer);\r\n gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, \r\n sphereVertexNormalBuffer.itemSize,\r\n gl.FLOAT, false, 0, 0);\r\n gl.drawArrays(gl.TRIANGLES, 0, sphereVertexPositionBuffer.numItems); \r\n}",
"enable() {\n this._enabled = true;\n this._model = new SelectionModel(this._bufferService);\n }",
"uploadNormalMatrixToShader() {\r\n mat3.fromMat4(this.nMatrix,this.mvMatrix);\r\n mat3.transpose(this.nMatrix,this.nMatrix);\r\n mat3.invert(this.nMatrix,this.nMatrix);\r\n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, this.nMatrix);\r\n }",
"function setNormals(mesh) {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normal);\n\n gl.vertexAttribPointer(shader.faceNormal, 3, gl.FLOAT, false, 0, 0);\n gl.enableVertexAttribArray(shader.faceNormal);\n\n gl.bufferData(gl.ARRAY_BUFFER,\n MV.flatten(mesh.normals),\n gl.STATIC_DRAW);\n}",
"_updateVertexBuffer() {\r\n\r\n // if we don't have vertex buffer, create new one, otherwise update existing one\r\n if (!this.vertexBuffer) {\r\n var allocateVertexCount = this._geometryData.maxVertices;\r\n var format = this._buildVertexFormat(allocateVertexCount);\r\n this.vertexBuffer = new VertexBuffer(this.device, format, allocateVertexCount, this._geometryData.verticesUsage);\r\n }\r\n\r\n // lock vertex buffer and create typed access arrays for individual elements\r\n var iterator = new VertexIterator(this.vertexBuffer);\r\n\r\n // copy all stream data into vertex buffer\r\n var numVertices = this._geometryData.vertexCount;\r\n for (var semantic in this._geometryData.vertexStreamDictionary) {\r\n var stream = this._geometryData.vertexStreamDictionary[semantic];\r\n iterator.writeData(semantic, stream.data, numVertices);\r\n\r\n // remove stream\r\n delete this._geometryData.vertexStreamDictionary[semantic];\r\n }\r\n\r\n iterator.end();\r\n }",
"bind(){ gl.ctx.useProgram( this.shader.program ); return this; }",
"function setVertices(mesh) {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);\n\n gl.vertexAttribPointer(shader.position, 3, gl.FLOAT, false, 0, 0);\n gl.enableVertexAttribArray(shader.position);\n\n gl.bufferData(gl.ARRAY_BUFFER,\n MV.flatten(mesh.vertices),\n gl.STATIC_DRAW);\n}",
"function setMV() {\r\n gl.uniformMatrix4fv(modelViewMatrixLoc, false, flatten(modelViewMatrix) );\r\n normalMatrix = inverseTranspose(modelViewMatrix) ;\r\n gl.uniformMatrix4fv(normalMatrixLoc, false, flatten(normalMatrix) );\r\n}",
"function drawTerrainEdges()\n{\n gl.polygonOffset(1,1);\n gl.bindBuffer(gl.ARRAY_BUFFER, tVertexPositionBuffer);\n gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, tVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);\n\n // Bind normal buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, tVertexNormalBuffer);\n gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, tVertexNormalBuffer.itemSize, gl.FLOAT, false, 0, 0); \n \n //Draw \n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, tIndexEdgeBuffer);\n gl.drawElements(gl.LINES, tIndexEdgeBuffer.numItems, gl.UNSIGNED_SHORT,0); \n}",
"disable() {\n this.vrDisplay.removeEventListener('planesadded', this.onPlaneAdded_);\n this.vrDisplay.removeEventListener('planesupdated', this.onPlaneUpdated_);\n this.vrDisplay.removeEventListener('planesremoved', this.onPlaneRemoved_);\n\n this.planes.keys.forEach(this.removePlane_);\n this.materials.clear();\n }",
"createPositionBuffer () {\n\t\tif (this.positionArray === null) {\n\t\t\tconsole.log(\"positionArray uninitialized\");\n\t\t}\n\n\t\tconst gl = this.gl;\n\n\t\t// allocate space for a buffer\n\t\tthis.positionBuffer = gl.createBuffer();\n\n\t\t// bind current buffer to perform operations on it\n \tgl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);\n\n \t// fill current buffer with vertex information\n \tgl.bufferData(gl.ARRAY_BUFFER,\n \t\tnew Float32Array(this.positionArray),\n \t\tgl.STATIC_DRAW);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Language: Lua Description: Lua is a powerful, efficient, lightweight, embeddable scripting language. | function lua(hljs) {
const OPENING_LONG_BRACKET = '\\[=*\\[';
const CLOSING_LONG_BRACKET = '\\]=*\\]';
const LONG_BRACKETS = {
begin: OPENING_LONG_BRACKET,
end: CLOSING_LONG_BRACKET,
contains: ['self']
};
const COMMENTS = [
hljs.COMMENT('--(?!' + OPENING_LONG_BRACKET + ')', '$'),
hljs.COMMENT(
'--' + OPENING_LONG_BRACKET,
CLOSING_LONG_BRACKET,
{
contains: [LONG_BRACKETS],
relevance: 10
}
)
];
return {
name: 'Lua',
keywords: {
$pattern: hljs.UNDERSCORE_IDENT_RE,
literal: "true false nil",
keyword: "and break do else elseif end for goto if in local not or repeat return then until while",
built_in:
// Metatags and globals:
'_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len ' +
'__gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert ' +
// Standard methods and properties:
'collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring ' +
'module next pairs pcall print rawequal rawget rawset require select setfenv ' +
'setmetatable tonumber tostring type unpack xpcall arg self ' +
// Library methods and properties (one line per library):
'coroutine resume yield status wrap create running debug getupvalue ' +
'debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv ' +
'io lines write close flush open output type read stderr stdin input stdout popen tmpfile ' +
'math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan ' +
'os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall ' +
'string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower ' +
'table setn insert getn foreachi maxn foreach concat sort remove'
},
contains: COMMENTS.concat([
{
className: 'function',
beginKeywords: 'function',
end: '\\)',
contains: [
hljs.inherit(hljs.TITLE_MODE, {
begin: '([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*'
}),
{
className: 'params',
begin: '\\(',
endsWithParent: true,
contains: COMMENTS
}
].concat(COMMENTS)
},
hljs.C_NUMBER_MODE,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
{
className: 'string',
begin: OPENING_LONG_BRACKET,
end: CLOSING_LONG_BRACKET,
contains: [LONG_BRACKETS],
relevance: 5
}
])
};
} | [
"function ola('Javascript'){\n\t\tconsole.log('Hello world!')\n\t}",
"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 codeLove() { //function that does exactly what it looks like it does.\n return \"I love code\";\n}",
"function Jexl() {\n this._customGrammar = null;\n this._lexer = null;\n this._transforms = {};\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 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 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 ola(0){\n\t\tconsole.log('Hello world!')\n\t}",
"function TamperLang() {\n this.init();\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 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 main(){\n\n lib.printBlue(\"hi\");\n lib.printGreen(\"My name\");\n lib.printRed(\"Is Bob\");\n\n }",
"function menutoshowlang(){\n}",
"function greet(name) {\n return \"Hello \" + name + \"!\";\n}",
"function Replayable({\n args: args$$1,\n body\n}) {\n // Push the arguments onto the stack. The args() function\n // tells us how many stack elements to retain for re-execution\n // when updating.\n let {\n count,\n actions\n } = args$$1(); // Start a new label frame, to give END and RETURN\n // a unique meaning.\n\n return [op('StartLabels'), op(0\n /* PushFrame */\n ), // If the body invokes a block, its return will return to\n // END. Otherwise, the return in RETURN will return to END.\n op(6\n /* ReturnTo */\n , label('ENDINITIAL')), actions, // Start a new updating closure, remembering `count` elements\n // from the stack. Everything after this point, and before END,\n // will execute both initially and to update the block.\n //\n // The enter and exit opcodes also track the area of the DOM\n // associated with this block. If an assertion inside the block\n // fails (for example, the test value changes from true to false\n // in an #if), the DOM is cleared and the program is re-executed,\n // restoring `count` elements to the stack and executing the\n // instructions between the enter and exit.\n op(69\n /* Enter */\n , count), // Evaluate the body of the block. The body of the block may\n // return, which will jump execution to END during initial\n // execution, and exit the updating routine.\n body(), // All execution paths in the body should run the FINALLY once\n // they are done. It is executed both during initial execution\n // and during updating execution.\n op('Label', 'FINALLY'), // Finalize the DOM.\n op(70\n /* Exit */\n ), // In initial execution, this is a noop: it returns to the\n // immediately following opcode. In updating execution, this\n // exits the updating routine.\n op(5\n /* Return */\n ), // Cleanup code for the block. Runs on initial execution\n // but not on updating.\n op('Label', 'ENDINITIAL'), op(1\n /* PopFrame */\n ), op('StopLabels')];\n}",
"function getBonusLanguages (intelligenceModifier, luckySign, luckModifier) {\n\tvar bonusLanguages = 0;\n\tif(bonusLanguages != undefined && typeof bonusLanguages === 'number') {\n\t\tbonusLanguages = intelligenceModifier;\n\t}\n\telse {\n\t\treturn \"\";\n\t}\n\t\n\tif(luckySign != undefined && luckySign.luckySign === \"Birdsong\") {\n\t\tbonusLanguages += luckModifier;\n\t}\n\t\n\tif(bonusLanguages <=0) {\n\t\treturn \"\";\n\t}\n\tvar result = \", \" + addBonusLanguages().language, newLanguage = \"\";\n\t\n\t// loop\n\tfor(var i = 1; i < bonusLanguages; i++){\n\t\t// 1) get a random lang\n\t\tnewLanguage = addBonusLanguages().language;\n\t\t// 2) check the new lang is not repeative\n\t\tif(result.indexOf(newLanguage) != -1){\n\t\t\ti--;\n\t\t\t// if yes continue;\n\t\t\tcontinue;\n\t\t} else{\n\t\t\t// if not, add the new lang into the result\n\t\t\tresult += \", \" + newLanguage;\n\t\t}\n\n\t}\n\treturn result;\n}",
"function makeRubyScript(aScript) {\n\tlines = aScript.split(\"\\n\");\n\t// We use the ruby18 supplied by TM for compatibility reasons\n\truby_program = ENV[\"TM_SUPPORT_PATH\"] + \"/bin/ruby18\"\n\truby_program = ruby_program.replace(/ /g, \"\\\\ \")\n command = ruby_program + \" -e \\'\\' \\\\\\n\";\n\tfor (line in lines) {\n\t\tcommand = command + '-e \\''+ lines[line] +'\\' \\\\\\n';\n\t}\n\tcommand = command + '\\n';\n\t\n\treturn command;\n}",
"function greeter (name) {\n return \"hoi \" + name + \"!\";\n}",
"function setLanguage(args) {\n\tSETTINGS.LANGUAGE = args.next() || SETTINGS.LANGUAGE\n}",
"function htmlDefString(def)\n{\n var args = def.getArgs();\n var sym = args[0];\n var lamEx = args[1];\n var lArgs = lamEx.getArgs();\n var vdl = lArgs[0];\n var body = lArgs[1];\n var result = '<b>def</b>';\n result += '\\\\(\\\\ ';\n result += sym.getArg(0);\n result += \"(\";\n result += latexVarDeclListString(vdl);\n result += ')\\\\colon ';\n // do the body\n result += \"\\\\ \";\n result += latexMathString(body);\n result += \"\\\\)\";\n result += \" <b>end</b>\";\n return result;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the Bill Summary or full Bill text, depending on the 'text' parameter passed text = the type of text we want back, either the sting "summary" or "full" path = the text_url of an individual bill, e.g. callback = callback the result | function getBillText(text, path, callback) {
makeTextRequest(text, path, function(err, html) {
if (err) {
callback(err);
}
else {
callback(null, html);
}
});
} | [
"function getDescriptionInBatch() {\n if (Config.placesDescription) {\n Places.findOne({wiki_summary: {$exists: false}})\n .then((result) => {\n if (!result) {\n return 'batch complete';\n }\n else {\n let text = cleanPlace(result.clean_address);\n wikiAPI(text)\n .then((summary) => {\n\n if (summary) {\n //remove patterns\n summary = summary.replace('( ( listen)','');\n //remove anything inside brackets\n summary = summary.replace(/ *\\([^)]*\\) */g, \"\");\n }\n\n Logger.info(summary);\n result.wiki_summary = summary;\n result.save((err) => {\n if (err) {\n Logger.error(err);\n }\n getDescriptionInBatch();\n })\n })\n }\n })\n .catch((err) => {\n Logger.error(err);\n getDescriptionInBatch();\n })\n }\n}",
"function baynote_getSummary() {\n\tvar summary = baynote_getMetaValue(\"description\");\n\tif (summary != \"\"){ return summary;}\n\telse{ summary = baynote_getSummaryFromParagraph();}\n\treturn summary;\n}",
"function getDocumentText(element) {\n element = $(element) || $(\"body\");\n var params = { \"text\": \"\", \"trim\": true };\n\n // iterate through all children of body element\n if (element.length > 0) {\n var children = element[0].childNodes;\n for (var i = 0; i < children.length; i++) {\n var child = children[i];\n params = iterateText(child, addText, params);\n }\n } else {\n console.log(\"element does not exist. no text retrieved\");\n }\n return params.text;\n}",
"async function getTextFromSource(){\n let text;\n if (process.argv[2] === 'file') {\n let filePath = process.argv[3];\n text = await cat(filePath);\n }\n else if (process.argv[2] === 'url') {\n let url = process.argv[3];\n text = await webCat(url);\n }\n else {\n console.error(`Bad input. Please try again.\n * Example: $ node makeText.js file eggs.txt\n * Example2: $ node makeText.js url http://www.gutenberg.org/files/11/11-0.txt`);\n process.exit(1);\n }\n return text;\n}",
"function api_submitText(text) {\n var params = prepareParams({method: \"post\", text: '' + text});\n var response = UrlFetchApp.fetch(production_api_root, params);\n return response.getAllHeaders().Location;\n}",
"_getChoiceResponse(step, text) {\n\t const choice = txt.conversation[step].answer_choice.find((choice) => choice.text === text);\n return choice ? choice.response : '';\n }",
"function CLC_GetTextContent(target){\r\n if (!target){\r\n return \"\";\r\n }\r\n if (target.nodeType == 8){ //Ignore comment nodes\r\n return \"\";\r\n } \r\n var textContentFromRole = CLC_GetTextContentFromRole(target);\r\n if (textContentFromRole){\r\n return textContentFromRole;\r\n }\r\n //Ignore scripts in the body\r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"script\"){\r\n return \"\";\r\n } \r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"noscript\"){\r\n return \"\";\r\n } \r\n //Do textarea twice because it may or may not have child nodes\r\n if (target.tagName && target.tagName.toLowerCase() == \"textarea\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText; \r\n }\r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"textarea\"){\r\n var labelText = CLC_Content_FindLabelText(target.parentNode);\r\n return labelText; \r\n }\r\n //Same logic as textarea applies for buttons\r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"button\"){\r\n var labelText = CLC_Content_FindLabelText(target.parentNode);\r\n return labelText + target.textContent; \r\n }\r\n if (target.tagName && target.tagName.toLowerCase() == \"button\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText + target.textContent; \r\n }\r\n //Form controls require special processing\r\n if (target.tagName && target.tagName.toLowerCase() == \"input\"){\r\n if (target.type.toLowerCase() == \"radio\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindRadioButtonDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if (target.type.toLowerCase() == \"checkbox\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindCheckboxDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if (target.type.toLowerCase() == \"text\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindTextBlankDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if (target.type.toLowerCase() == \"password\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindPasswordDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if ( (target.type.toLowerCase() == \"submit\") || (target.type.toLowerCase() == \"reset\") || (target.type.toLowerCase() == \"button\")){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText + \" \" + target.value;\r\n }\r\n if (target.type.toLowerCase() == \"image\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText + \" \" + target.alt;\r\n }\r\n return \"\";\r\n }\r\n //MathML element - Use the functions in clc_mathml_main.js to handle these\r\n if (target.tagName && target.tagName.toLowerCase() == \"math\"){\r\n return CLC_GetMathMLContent(target);\r\n }\r\n //Images\r\n if (target.tagName && target.tagName.toLowerCase() == \"img\"){\r\n if ( target.hasAttribute(\"alt\") && target.alt == \"\" ){\r\n return \"\";\r\n }\r\n if ( target.hasAttribute(\"alt\") ){\r\n return target.alt;\r\n }\r\n //Treat missing alt as null if the user is in Brief Mode\r\n if (CLC_InfoLang == 3){\r\n return \"\";\r\n }\r\n return target.src;\r\n }\r\n //Select boxes - ignore their textContent, only read out the selected value.\r\n //However, if there is a label, use it.\r\n if (target.tagName && target.tagName.toLowerCase() == \"select\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText;\r\n }\r\n //\"Normal\" elements that are just text content and do not require any special action\r\n if (target.textContent){\r\n return target.textContent;\r\n }\r\n return \"\";\r\n }",
"analyzeText() {\n var self = this;\n\n // Set state variables\n this.setState({showEditor: false, showInstruction: false,\n showRevisionPrompt: true, showRevision: false,\n draftAnalyzed: null,\n durationDraft: (new Date() - this.state.durationDraft) / 1000,\n draftPlainText: getPlainText(this.state.draftText)}, () => {\n // Analyze Text from server\n fetch(this.urls.textanalyzer + this.experiment_id, {\n method: 'POST',\n credentials: 'same-origin',\n body: JSON.stringify({\n text: self.state.draftPlainText\n }),\n headers: new Headers({\n 'Content-Type': 'application/json'\n })\n }).then((response) => {\n return response.json();\n }).catch((error) => {\n console.log(error);\n }).then((data) => {\n // Set state of revisionText according to measurement\n if (self.state.user.next_measure == 'control group' || self.state.user.next_measure == 'Cmap') {\n self.setState({revisionText: self.state.draftText});\n } else {\n self.setState({revisionText: data['html_string']});\n }\n\n self.setState({draftAnalyzed: data, seenEditor: true});\n });\n });\n }",
"function display_text(obj, default_value, key) {\n var text = mql.result.text(obj[key]);\n if (text) {\n return text.value;\n }\n if (default_value != null) {\n return default_value;\n }\n return null;\n}",
"function parse_summary() {\n\n var desc_elms = $('iframe#bookDesc_iframe').contents();\n var desc_text_elms = $(desc_elms).find('div#iframeContent').contents();\n var desc_text = $(desc_text_elms).map(function(i, e) {\n if (this.nodeType === 3) { return $(this).text(); }\n else { return $(this).prop('outerHTML'); }\n }).toArray().join('');\n\n return desc_text;\n}",
"function extractTextInfo(pageContent) {\n\n\ttext_block = pageContent;\n\ttext_info = [];\n\n\tfor (var i = 0; i < text_block.length; i++) {\n\t\t//getting the text coordinate information\n\t\tvar res = text_block[i].split(\";\");\n\t\t\n\t\tvar coordinate_split_left = res[3].split(\":\");\n\t\tvar coordinate_split_top = res[4].split(\":\");\n\t\tvar coordinate_split_width = res[5].split(\":\");\n\t\tvar coordinate_split_height = res[6].split(\":\");\n\n\t\tvar left = coordinate_split_left[1];\n\t\tvar top = coordinate_split_top[1];\n\t\tvar width = coordinate_split_width[1];\n\t\tvar height = coordinate_split_height[1];\n\n\t\tleft = parseInt(left);\n\t\ttop = parseInt(top);\n\t\twidth = parseInt(width);\n\t\theight = parseInt(height);\n\n\t\tvar single_coordinate = [left, top, width, height];\n\n\t\t// getting the text field string, remove the html tag and other redundant information.\n\t\tvar sample = text_block[i];\n\t\tvar mark = 'font-size';\n\t\tvar res = ''; \n\t\tvar index_start = sample.indexOf(mark);\n\n\t\tvar sub_sample = sample.substr(index_start);\n\n\t\tindices = getIndicesOf(sub_sample,'font-size');\n\t\tvar result = \"\";\n\t\tfor (var l = 0; l < indices.length; l++) {\n\t\t\tvar index_start = indices[l];\n\t\t\tvar curr_sample = sub_sample.substr(index_start+16);\n\t\t\tvar index_start = curr_sample.indexOf('</span>');\n\t\t\tif (index_start != -1) {\n\t\t\t\tcurr_sample = curr_sample.substring(0, index_start);\n\t\t\t}\n\t\t\tcurr_sample = curr_sample.split(\"<br>\").join(\"\");\n\t\t\tcurr_sample = curr_sample.split(\"\\n\").join(\"\");\n\n\t\t\tresult += curr_sample;\n\t\t}\n\t\ttext_info.push([single_coordinate, result]);\n\t}\n\treturn text_info;\n}",
"function describeTextbook() {\n\tvar textbookString = brackets.currentTextbook.name;\n\ttextbookString += \" by \" + brackets.currentTextbook.author + \"\\n\";\n\tvar numberOfElements = brackets.currentTextbook.elements.length;\n\tfor (var i = 0; i < length; i++) {\n\t\ttextbookString += \"\\n\" + i + \": \";\n\t\tswitch(brackets.currentTextbook.elements[i].type) {\n\t\t\tcase 'pdfRectangle':\n\t\t\t\ttextbookString += \"Rectangle from \" + brackets.currentTextbook.elements[i].source;\n\t\t\tcase 'pdfHorizontal':\n\t\t\t\ttextbookString += \"Horizontal clip from \" + brackets.currentTextbook.elements[i].source;\n\t\t\tcase 'youtube':\n\t\t\t\ttextbookString += \"YouTube clip from \" + brackets.currentTextbook.elements[i].source;\n\t\t\tcase 'text' :\n\t\t\t\ttextbookString += \"Some text\";\n\t\t\tcase 'wikipedia':\n\t\t\t\ttextbookString += \"Wikipedia clip from \" + brackets.currentTextbook.elements[i].source;\n\t\t\tcase 'image':\n\t\t\t\ttextbookString += \"Image from \" + brackets.currentTextbook.elements[i].source;\n\t\t\tdefault:\n\t\t\t\ttextbookString += \"Undefined type\";\n\t\t}\n\t} \n}",
"_getLinkText() {\n let text = this._gatherTextUnder(this.context.link);\n\n if (!text || !text.match(/\\S/)) {\n text = this.context.link.getAttribute(\"title\");\n if (!text || !text.match(/\\S/)) {\n text = this.context.link.getAttribute(\"alt\");\n if (!text || !text.match(/\\S/)) {\n text = this.context.linkURL;\n }\n }\n }\n\n return text;\n }",
"function getMemeTextForId(_payloadID)\n{\n\tvar payload = findPayloadById(_payloadID);\n\tif ( payload.cleanText)\n\t{\n\t\treturn payload.cleanText;\n\t}\n\telse\n\t{\n\t\treturn \"\";\t\n\t}\n\t\n}",
"function parseText( string, parsedText ) {\n var matches;\n parsedText = parsedText || [];\n\n if ( !string ) {\n return parsedText;\n }\n\n matches = descriptionRegex.exec( string );\n if ( matches ) {\n // Check if the first grouping needs more processing,\n // and if so, only keep the second (markup) and third (plaintext) groupings\n if ( matches[ 1 ].match( descriptionRegex ) ) {\n parsedText.unshift( matches[ 2 ], matches[ 3 ] );\n } else {\n parsedText.unshift( matches[ 1 ], matches[ 2 ], matches[ 3 ] );\n }\n\n return parseText( matches[ 1 ], parsedText );\n } else if ( !parsedText.length ) {\n // No links found\n parsedText.push( string );\n }\n\n return parsedText;\n }",
"getFunText() {\n var texts = [\n [\"bounceIn\", \"Great Job!\", \"1000\"],\n [\"bounceIn\", \"With every tap you help put a family on the map\", \"3000\"],\n [\"bounceIn\", \"Thank you!\", \"1000\"],\n [\"bounceIn\", \"Your effort is helping!\", \"1000\"],\n [\"bounceIn\", \"Keep up the good work!\", \"1000\"],\n ];\n\n\n var random = Math.floor(Math.random() * texts.length);\n return texts[random];\n }",
"function findTagsByText(text) {\n\n return $http.get(URLS.BASE + URLS.TAGS + \"?text=\" + text)\n .then((responce) => {\n return responce.data;\n })\n .catch((error) => {\n console.log(error);\n return $q.reject(error);\n });\n\n }",
"async function getDialog(id, text){\n //Dialogflow Client\n const sessionClient = new dialogflow.SessionsClient();\n const sessionPath = sessionClient.sessionPath(projectId, String(id));\n \n // The text query request.\n const dialogflow_request = {\n session: sessionPath,\n queryInput: {\n text: {\n text: text,\n languageCode: languageCode,\n },\n },\n };\n\n // Send request and get results\n const responses = await sessionClient.detectIntent(dialogflow_request);\n if (responses[0].queryResult.action){ //Process any given\n await processAction(id, responses[0].queryResult.action, responses[0].queryResult.parameters, responses[0].queryResult)\n }\n \n //Itirate between each response message, sending them accordingly\n for (var i in responses[0].queryResult.fulfillmentMessages) {\n let result = responses[0].queryResult.fulfillmentMessages[i];\n if (result.text && result.platform == \"TELEGRAM\"){\n await sendMessage(id, result.text.text[0]);\n }\n }\n}",
"function scrape(text) {\n\n //Regular Expression to check against input string for valid URL\n\n // var urlRegex = /(([a-z]+:\\/\\/)?(([a-z0-9\\-]+\\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\\/[a-z0-9_\\-\\.~]+)*(\\/([a-z0-9_\\-\\.]*)(\\?[a-z0-9+_\\-\\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:@/?]*)?)(\\s+|$)/gi\n var urlRegex= /((?:(?:https?|ftp|file|[A-Za-z]+):\\/\\/|www\\.|ftp\\.)(?:\\([-A-Z0-9+&@#\\/%=~_|$?!:,.]*\\)|[-A-Z0-9+&@#\\/%=~_|$?!:,.])*(?:\\([-A-Z0-9+&@#\\/%=~_|$?!:,.]*\\)|[A-Z0-9+&@#\\/%=~_|$]))/i\n\n\n //Checks if any word within string matches a valid URL\n if (text.search(urlRegex) != -1) {\n console.log($scope.url)\n //Checks if previous url is stored in scope to avoid trim errors\n if($scope.url){\n $scope.url = $scope.url.trim()\n }\n console.log(text.match(urlRegex))\n //Trims url from altered input field\n new_url = text.match(urlRegex)[0].trim()\n console.log(new_url)\n //Checks if url has changed to avoid refreshing preview unnecessarily\n if($scope.url != new_url){\n //Hides preview\n $scope.found = false;\n //Turns on loading gif for UX due to possible long response time\n $scope.loading = true;\n //Resets condition for possible 404 to off\n $scope.failed = false;\n //Updates stored URL with new one\n $scope.url = text.match(urlRegex)[0]\n //Modify string to comply with backend request\n addhttp($scope.url)\n var data = {url: addhttp($scope.url)}\n //Pass url to factory and then to backend (Call cannot be made from front end due to header issues)\n previewFactory.getHTML(data, function(html){\n //Turns on condition if response was 404 (html string is empty from a front end perspective)\n if(html==\"\"){\n $scope.failed = true;\n }\n else{\n //Turns off loading gif\n $scope.failed = false;\n //Shows preview\n $scope.found = true;\n //Scrapes HTML for title\n var title = html.match(/<title>(.*?)<\\/title>/);\n //Scrapes HTML for Open Graph image meta tag\n var image_url = html.match(/<meta [^>]*property=[\\\"']og:image[\\\"'] [^>]*content=[\\\"']([^'^\\\"]+?)[\\\"'][^>]*>/);\n //Scrapes HTML for Open Graph description meta tag\n var description = html.match(/<meta [^>]*property=[\\\"']og:description[\\\"'] [^>]*content=[\\\"']([^'^\\\"]+?)[\\\"'][^>]*>/);\n\n //Creates string without http(s) or www for display purposes\n // if ($scope.url.match(/^https?\\:\\/\\/(?:www\\.)?([^\\/?#]+)(?:[\\/?#]|$)/i)){\n // $scope.link_string = $scope.url.replace(/^(https?:\\/\\/)?(www\\.)?/,'');\n // }\n // else{\n // $scope.link_string = $scope.url;\n // }\n $scope.link_string = $scope.url.replace(/^(https?:\\/\\/)?(www\\.)?/,'');\n //Checks for all three display items in case HTML did not include them\n if(title){\n $scope.title_tag=title[1];\n }\n else{\n $scope.title_tag=\"\"\n }\n if(image_url){\n $scope.banner_url=image_url[1];\n }\n else{\n $scope.banner_url=\"./images/noimg.png\";\n }\n if(description){\n $scope.descript=description[1]\n }\n else{\n $scope.descript=\"\"\n }\n }\n //turns off loading on failure\n $scope.loading = false;\n })\n }\n }\n //hides preview if there is no URL\n else{\n $scope.found = false;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
converts amount of PLT into PLTwei | function PLT(amount) {
return web3.toWei(amount, 'finney');
} | [
"function boltPersoane(n) {\n var directie = \"dreapta\";\n var persoana = 1;\n var str = \"\";\n for (var i = 1; i < n; i++) {\n if (i % 7 === 0 || div7(i)===true) {\n if(directie === \"dreapta\"){\n persoana++;\n if(persoana>5) {\n persoana = 1;\n }\n }else {\n persoana--;\n if(persoana< 1){\n persoana = 5;\n }\n }\n str += \"Bolt\";\n if (directie === \"dreapta\") {\n directie = \"stanga\";\n } else {\n directie = \"dreapta\";\n }\n } else {\n str += \"p\" + persoana+\": \" + i + \"\\n\";\n if(directie === \"dreapta\"){\n persoana++;\n if(persoana>5) {\n persoana = 1;\n }\n }else {\n persoana--;\n if(persoana< 1){\n persoana = 5;\n }\n }\n \n }\n \n }\n return str;\n}",
"function build2points() {\n points += (4 * b2multi);\n totalpoints += (4 * b2multi);\n }",
"static uint72(v) { return n(v, 72); }",
"function compute_LF_hopPP(ibu) {\n var LF_hopPP = 0.0;\n\n // Assume krausen, finings, filtering affect hop PP the same as other nonIAA.\n LF_hopPP = SMPH.LF_hopPP *\n SMPH.ferment_hopPP *\n compute_LF_nonIAA_krausen(ibu) *\n compute_LF_finings(ibu) *\n compute_LF_filtering(ibu);\n\n return(LF_hopPP);\n}",
"function feetToMetres() {\r\n \r\n \r\n}",
"function build3points() {\n points += (10 * b3multi);\n totalpoints += (10 * b3multi);\n }",
"function getPencilHead(x,y,s){\n\tvar result=\"M\"+(x+s)+\" \"+y+\",\";\n\tresult=result+\"L\"+(x+s/3)+\" \"+y+\",\";\n\tresult=result+\"L\"+(x+s/3)+\" \"+(y+s/6)+\",\";\n\tresult=result+\"S\"+(x-s/3)+\" \"+(y+s/2)+\" \"+(x+s/3)+\" \"+(y+s*5/6)+\",\";\n\tresult=result+\"L\"+(x+s/3)+\" \"+(y+s)+\",\";\n\tresult=result+\"L\"+(x+s)+\" \"+(y+s)+\",\";\n\tresult=result+\"Z\";\n\t\n\treturn result;\n}",
"function print34to41() {\n const array = []\n for(let i = 34; i < 42; i++) {\n array.push(i);\n }\n return array.map(item => `<p class=\"output\">${item}</p>`).join(\"\");\n}",
"function updateNumbers() {\n // look how I loop through all tiles\n tileSprites.forEach(function (item) {\n // retrieving the proper value to show\n var value = fieldArray[item.pos];\n // showing the value\n item.getChildAt(0).text = value;\n // tinting the tile\n item.tint = colors[value]\n });\n }",
"function mm2pt(value) {\n return value * 72 / 25.4;\n}",
"function pws(t) {\r\n var T = t + 459.67;\r\n var C1 = -1.0214165e4;\r\n var C2 = -4.8932428;\r\n var C3 = -5.3765794e-3;\r\n var C4 = 1.9202377e-7;\r\n var C5 = 3.5575832e-10;\r\n var C6 = -9.0344688e-14;\r\n var C7 = 4.1635019;\r\n var C8 = -1.0440397e4;\r\n var C9 = -1.129465e1;\r\n var C10 = -2.7022355e-2;\r\n var C11 = 1.289036e-5;\r\n var C12 = -2.478068e-9;\r\n var C13 = 6.5459673;\r\n if (t >= -148 && t <= 32) {\r\n var fpws = C1 / T + C2 + C3 * T + C4 * T ** 2 + C5 * T ** 3 + C6 * T ** 4 + C7 * Math.log(T);\r\n } else if (t > 32 && t <= 392) {\r\n var fpws = C8 / T + C9 + C10 * T + C11 * T ** 2 + C12 * T ** 3 + C13 * Math.log(T);\r\n } else {\r\n window.alert(\"Temperature is out of range\");\r\n }\r\n return Math.exp(fpws);\r\n}",
"function update_counts (n, s) {\n digits = PiMill.get_digits(n, s);\n n = digits.length; // In case we went past the end\n for (var i = 0; i < n; i++) {\n digit_counts[digits.charAt(i)]++;\n }\n return n;\n }",
"function iTri(s){\n let stage = {\n Swim: 2.4,\n Bike: 112,\n Run: 26.2,\n };\n const out = {};\n\n let tmp;\n tmp = stage.Swim + stage.Bike + stage.Run - s;\n tmp = tmp.toFixed(2);\n if (s === 0) { return 'Starting Line... Good Luck!' }\n else if (s > 0 && s <= stage.Swim) {\n out['Swim'] = tmp + ' to go!';\n return out;\n } else if (s > stage.Swim && s <= stage.Bike + stage.Swim) {\n out['Bike'] = tmp + ' to go!';\n return out;\n } else if (s > stage.Bike + stage.Swim && s <= stage.Run + stage.Bike + stage.Swim) {\n if (tmp <= 10) { out['Run'] = 'Nearly there!'; return out; }\n else out['Run'] = tmp + ' to go!';\n return out;\n } else if (tmp < 0) return `You're done! Stop running!`\n}",
"function makeHexagons(){\r\n var hexX = 0;\r\n var hexY = 0;\r\n for(var i = 0; i < 91; i++){\r\n hexagons[i][1][0] = hexX;\r\n hexagons[i][1][1] = hexY;\r\n hexY += 1;\r\n if(hexX == 9 && hexY == 7){\r\n hexX += 1;\r\n hexY = 5;\r\n }\r\n if(hexX == 8 && hexY == 8){\r\n hexX += 1;\r\n hexY = 4;\r\n }\r\n if(hexX == 7 && hexY == 9){\r\n hexX += 1;\r\n hexY = 3;\r\n }\r\n if(hexX == 6 && hexY == 10){\r\n hexX += 1;\r\n hexY = 2;\r\n }\r\n if(hexX == 5 && hexY == 11){\r\n hexX += 1;\r\n hexY = 1;\r\n }\r\n if(hexY == 11){\r\n hexY = 0;\r\n hexX += 1;\r\n }\r\n }\r\n for(var i = 0; i < 91; i++){\r\n hexagons[i][0][1] = hexagons[i][1][1] - 5;\r\n hexagons[i][0][0] = (hexagons[i][0][1]) / importantNumber;\r\n hexagons[i][0][0] = Math.abs(hexagons[i][0][0]);\r\n hexagons[i][0][0] += hexagons[i][1][0];\r\n hexagons[i][0][1] += 5;\r\n hexagons[i][0][0] *= s/13;\r\n hexagons[i][0][1] *= s/14;\r\n hexagons[i][0][0] += s/13 * 1.5;\r\n hexagons[i][0][1] += s/13 * 1.5;\r\n }\r\n for(var i = 0; i < 91; i++){\r\n if(hexagons[i][1][1] == 5) for(var j = 0; j < 91; j++){\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][0] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][1] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][2] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][3] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][4] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][5] = j;\r\n }\r\n }\r\n if(hexagons[i][1][1] < 5) for(var j = 0; j < 91; j++){\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][0] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][1] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][2] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][3] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][4] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][5] = j;\r\n }\r\n }\r\n if(hexagons[i][1][1] > 5) for(var j = 0; j < 91; j++){\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][0] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][1] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][2] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][3] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][4] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][5] = j;\r\n }\r\n }\r\n }\r\n}",
"function ssx(n){\n\treturn n % spriteSheetSizeX;\n}",
"function build1points() {\n points += (1 * b1multi);\n totalpoints += (1 * b1multi);\n }",
"function changePi(str){\n let s = str.indexOf(\"pi\");\n if (s == -1)\n return str;\n return changePi(str.substring(0,s) + \"3.14\" + str.substring(s + 2));\n}",
"static uint40(v) { return n(v, 40); }",
"function adjustIndex(index) {\r\n if(index > 806) { // Any index after 806 is when PokeAPI starts numbering pokemon starting with 10001\r\n index -= 806;\r\n index += 10000;\r\n return index;\r\n }\r\n\r\n return index + 1;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait until the given tab reaches the "complete" status, then return the tab. This also deals with new tabs, which, before loading the requested page, begin at about:blank, which itself reaches the "complete" status. | async function tabCompletion (tab) {
function isComplete (tab) {
return tab.status === 'complete' && tab.url !== 'about:blank'
}
if (!isComplete(tab)) {
return new Promise((resolve, reject) => {
const timer = setTimeout(
function giveUp () {
browser.tabs.onUpdated.removeListener(onUpdated)
if (isComplete(tab)()) {
// Give it one last chance to dodge race condition
// in which it completes between the initial test
// and installation of the update listener.
resolve(tab)
} else {
reject(new Error('Tab never reached the "complete" state, just ' + tab.status + ' on ' + tab.url))
}
},
5000)
function onUpdated (tabId, changeInfo, updatedTab) {
// Must use updatedTab below; using just `tab` seems to remain
// stuck to about:blank.
if (tabId === updatedTab.id && isComplete(updatedTab)) {
clearTimeout(timer)
browser.tabs.onUpdated.removeListener(onUpdated)
resolve(updatedTab)
}
}
browser.tabs.onUpdated.addListener(onUpdated)
})
}
} | [
"function goToUrl(tab, url) {\n browser.tabs.update(tab, { url });\n return new Promise(resolve => {\n browser.tabs.onUpdated.addListener(function onUpdated(id, info) {\n if (id === tab && info.status === 'complete') {\n browser.tabs.onUpdated.removeListener(onUpdated);\n resolve();\n }\n });\n });\n}",
"function waitforButton(tabid) {\n waitfor() {\n chrome.pageAction.show(tabid);\n function listener(tab) { if (tab.id == tabid) resume(); }\n chrome.pageAction.onClicked.addListener(listener);\n }\n finally {\n chrome.pageAction.onClicked.removeListener(listener);\n chrome.pageAction.hide(tabid);\n }\n}",
"function gotoTab() {\n let url_string = window.location.href;\n let url = new URL(url_string);\n let tab = url.searchParams.get(\"open\");\n // console.log('url', tab);\n if (tab) {\n // console.log('has tab');\n let idName = '#' + tab;\n let idTabName = idName + 'Tab';\n // console.log('name', idName, idTabName);\n switchTab($(idTabName), idName);\n }\n}",
"function checkTab(tab){\n if (mainPomodoro.currentMode == 'work' || mainPomodoro.currentMode == 'break_pending' || mainPomodoro.currentMode == 'longbreak_pending') {\n executeInTabIfBlocked('block', tab);\n }else{\n executeInTabIfBlocked('unblock', tab);\n }\n }",
"async getFindBar(aTab = this.selectedTab) {\n let findBar = this.getCachedFindBar(aTab);\n if (findBar) {\n return findBar;\n }\n\n // Avoid re-entrancy by caching the promise we're about to return.\n if (!aTab._pendingFindBar) {\n aTab._pendingFindBar = this._createFindBar(aTab);\n }\n return aTab._pendingFindBar;\n }",
"function getCurrentTab(callback) {\n var queryInfo = {\n active: true,\n currentWindow: true\n };\n\n chrome.tabs.query(queryInfo, function(tabs) {\n callback(tabs[0]);\n });\n}",
"clickUpcomingRacesTab(){\n //this.upcomingRacesTab.waitForExist();\n this.upcomingRacesTab.click();\n }",
"function displayTab() {\n const params = new URLSearchParams(window.location.search);\n const tabToLoad = params.get('tab');\n const defaultTab = '#about-us';\n if (tabToLoad) {\n showTab('#' + tabToLoad);\n } else {\n showTab(defaultTab);\n }\n}",
"function scrapePage(babesQ) {\n console.log('Scrape page function loaded!', babesQ);\n var url = babesQ[0];\n\n chrome.tabs.create({ \n url: url,\n active: true\n }, function(){\n sendScrapeRequest(url);\n });\n }",
"function displayTabContentLoader() {\r\n var $el = $(\"#tab-content-loader\");\r\n var nextUpdate, currentTime = new Date().getTime();\r\n var currentTab = getSettingsBackgroundTabId();\r\n if (currentTab == 0) {\r\n nextUpdate = localStorage.getItem(\"flixel-themes-data-next-update\");\r\n if (!nextUpdate || nextUpdate < currentTime)\r\n if (!$el.is(\":visible\")) $el.show();\r\n }\r\n else if (currentTab == 1) {\r\n nextUpdate = localStorage.getItem(\"available-themes-data-next-update\");\r\n if (!nextUpdate || nextUpdate < currentTime)\r\n if (!$el.is(\":visible\")) $el.show();\r\n }\r\n}",
"function focusOnGenesysTab(){\n\tchrome.tabs.query({}, function(tabs) {\n\t\tfor (var i = 0; i < tabs.length; i++) {\n\t\t\tif (tabs[i].url === \"https://netsuite-wwe-usw1.genesyscloud.com/ui/ad/v1/index.html\"){\n\t\t\t\tvar updateProperties = {\"active\": true};\n\t\t\t\tchrome.tabs.update(tabs[i].id, updateProperties, function(tab){ console.log(\"focused on tab: \" + tab.id)});\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t});\n}",
"function fetchTabs(callback) {\n chrome.tabs.query({}, tabs => {\n window.tabs = tabs.filter(t => t.url.indexOf('http') === 0)\n .map(t => new Tab(t, window.images));\n callback();\n });\n}",
"function showTab(tabName) {\n var template = document.querySelector(tabName);\n\n const params = new URLSearchParams(window.location.search);\n if (tabName === '#announcements') {\n template.content.querySelector('#club-name').value = params.get('name');\n template.content.querySelector('#schedule-club-name').value = params.get('name');\n template.content.querySelector('#timezone').value = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n const node = document.importNode(template.content, true);\n document.getElementById('tab').innerHTML = '';\n document.getElementById('tab').appendChild(node);\n\n if (tabName === '#about-us') {\n getClubInfo();\n } else if (tabName === '#announcements') {\n getClubInfo();\n loadAnnouncements();\n showHidePostAnnouncement();\n loadScheduledAnnouncements();\n } else if (tabName === '#calendar') {\n loadCalendar();\n }\n}",
"function tabExists(tabId, onExists, onNotExists) {\n chrome.windows.getAll({\n populate: true\n }, function(windows) {\n for (var i = 0, window; window = windows[i]; i++) {\n for (var j = 0, tab; tab = window.tabs[j]; j++) {\n if (tab.id == tabId) {\n onExists && onExists(tab);\n return;\n }\n }\n }\n onNotExists && onNotExists();\n });\n }",
"checkTabs() {\n for (let i = 0; i < this.tabs.length; i++) {\n let tab = this.tabs[i]\n let item = this.items[tab.id]\n if (item) {\n item.updateInfo(tab)\n if (item.url.indexOf('chrome') !== 0 && item.url.indexOf('view-source') !== 0) {\n if (item.pinned || item.active) continue // Skip pinned and active tab\n if (item.isSleeping) continue\n let now = Date.now() / 1000\n if (now - item.lastActiveTime > this.tabSleepInterval) { // go sleep\n this.goSleep(item)\n }\n }\n continue\n }\n item = Tab.newByTab(tab)\n item.save()\n this.loadTabItems()\n }\n }",
"adoptTab(aTab, aIndex, aSelectTab) {\n // Swap the dropped tab with a new one we create and then close\n // it in the other window (making it seem to have moved between\n // windows). We also ensure that the tab we create to swap into has\n // the same remote type and process as the one we're swapping in.\n // This makes sure we don't get a short-lived process for the new tab.\n let linkedBrowser = aTab.linkedBrowser;\n let params = {\n eventDetail: { adoptedTab: aTab },\n preferredRemoteType: linkedBrowser.remoteType,\n sameProcessAsFrameLoader: linkedBrowser.frameLoader,\n skipAnimation: true,\n index: aIndex,\n };\n\n let numPinned = this._numPinnedTabs;\n if (aIndex < numPinned || (aTab.pinned && aIndex == numPinned)) {\n params.pinned = true;\n }\n\n if (aTab.hasAttribute(\"usercontextid\")) {\n // new tab must have the same usercontextid as the old one\n params.userContextId = aTab.getAttribute(\"usercontextid\");\n }\n let newTab = this.addWebTab(\"about:blank\", params);\n let newBrowser = this.getBrowserForTab(newTab);\n\n // Stop the about:blank load.\n newBrowser.stop();\n // Make sure it has a docshell.\n newBrowser.docShell;\n\n // We need to select the tab before calling swapBrowsersAndCloseOther\n // so that window.content in chrome windows points to the right tab\n // when pagehide/show events are fired. This is no longer necessary\n // for any exiting browser code, but it may be necessary for add-on\n // compatibility.\n if (aSelectTab) {\n this.selectedTab = newTab;\n }\n\n aTab.parentNode._finishAnimateTabMove();\n this.swapBrowsersAndCloseOther(newTab, aTab);\n\n if (aSelectTab) {\n // Call updateCurrentBrowser to make sure the URL bar is up to date\n // for our new tab after we've done swapBrowsersAndCloseOther.\n this.updateCurrentBrowser(true);\n }\n\n return newTab;\n }",
"function afterTabChange(tabPanel, selectedTabName){\n\n // Detect whether the characteristics tab was selected. If so, set variable, so that\n // the first child tab (the summary characteristics tab) will be displayed first\n if (selectedTabName == 'page4') {\n tabPanel.showDefaultCharTab = true;\n tabPanel.refresh();\n }\n else {\n tabPanel.showDefaultCharTab = false;\n }\n}",
"function activeTabIntoPanel() {\n chrome.tabs.query({\n active: true,\n currentWindow: true\n }, function(tabs) {\n tabIntoPanel(tabs[0]);\n });\n}",
"function goCorrectTab(page) {\n injectClickFunction(page);\n return page.evaluate(function() {\n var allResultsLink = document.querySelector('#allResults a');\n if (! allResultsLink)\n return false;\n\n doClick(allResultsLink);\n return true;\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a binary function subb that takes two numbers and returns their difference | function subb(a, b) {
return b - a;
} | [
"function SUBTRACT() {\n for (var _len14 = arguments.length, values = Array(_len14), _key14 = 0; _key14 < _len14; _key14++) {\n values[_key14] = arguments[_key14];\n }\n\n // Return `#NA!` if 2 arguments are not provided.\n if (values.length !== 2) {\n return error$2.na;\n }\n\n // decompose values into a and b.\n var a = values[0];\n var b = values[1];\n\n // Return `#VALUE!` if either a or b is not a number.\n\n if (!ISNUMBER(a) || !ISNUMBER(b)) {\n return error$2.value;\n }\n\n // Return the difference.\n return a - b;\n}",
"function polySub(a, b) {\r\n for (var i = 0; i < paramsN; i++) {\r\n a[i] = a[i] - b[i];\r\n }\r\n return a;\r\n}",
"static vSub(a,b) { return newVec(a.x-b.x,a.y-b.y,a.z-b.z); }",
"function subNumbers(num1, num2){\n\tlet product = num1 - num2;\n\t\tconsole.log('${num1} - ${num2} is ${product}');\n\t}",
"static mxSub(a,b) { \r\n\t\tvar res = new mx4(); \t\t\r\n\t\tfor (var i=0; i<16; ++i) { res.M[i] = a.M[i] - b.M[i]; }\r\n\t\treturn res; \r\n\t}",
"function mySubtractFunction(number1, number2) {\n console.log(number1 - number2);\n}",
"function getDiff(a, b)\n{\n const len= Math.max(a.length, b.length);\n let r= '', c= 0, d, diff;\n [a,b]= [a,b].map(e=>e.padStart(len,'0'));\n if (a < b) [a,b]= [b,a];\n\n for (let i=len-1; i>=0; i--)\n {\n d= +b[i] + c;\n\n +a[i]>=d ?\n (c= 0, diff= a[i]-d)\n :(c= 1, diff= '1'+a[i]-d)\n\n r = diff + r;\n }\n return r;\n}",
"function subtractVectors(a, b) {\r\n return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];\r\n}",
"function subtract(str1, str2) {\n var end = endNumber(str1);\n var start = startNumber(str2);\n //if missing a value, setting to 0 ensures that the subtraction will not be\n //affected\n if(!start.value) {\n start.value = 0;\n }\n if(!end.value) {\n end.value = 0;\n }\n var diff = end.value - start.value;\n return end.remainder + diff.toString() + start.remainder;\n }",
"function divisibleByB(a, b) {\n\treturn a - a % b + b;\n}",
"function byteopsCSubQ(a) {\r\n a = a - paramsQ; // should result in a negative integer\r\n // push left most signed bit to right most position\r\n // remember javascript does bitwise operations in signed 32 bit\r\n // add q back again if left most bit was 0 (positive number)\r\n a = a + ((a >> 31) & paramsQ);\r\n return a;\r\n}",
"function getSum(a, b) { \n return b == 0 ? a : getSum(a ^ b, (a & b) << 1)\n}",
"function subVectors(vec1, vec2) {\n return new Vector(vec1.x - vec2.x, vec1.y - vec2.y);\n}",
"sub(other, out) {\n out.x = this.x - other.x;\n out.y = this.y - other.y;\n }",
"function mulb(a, b) {\n return a * b;\n}",
"function billet(prix , rendu){\n const result = prix - rendu;\n return result\n }",
"function maxb(a, b) {\n if (a > b) return a;\n return b;\n}",
"function fiveNumbersSub(n1, n2, n3, n4, n5) {\n let difference = 100 - n1 - n2 - n3 - n4 - n5;\n console.log(Math.abs(difference));\n}",
"function backsub(\n u, // u[1..m][1..n], the column-orth. matrix from decomp\n w, // w[1..n], the diagonal matrix from decomp\n v, // v[1..n][1..n], the orth. matrix from decomp\n m, // number of rows\n n, // number of columns\n b // b[1..m] is the right hand side (B)\n)\n{\n var s;\n var tmp = new Array();\n var x = new Array();\n \n // Calculate UT * B\n for (var j=1; j<=n; j++)\n {\n s = 0.0;\n \n // Nonzero result only if w[j] is nonzero\n if (w[j] != 0.0)\n {\n for (var i=1; i<=m; i++)\n s += u[i][j]*b[i];\n s /= w[j];\n }\n tmp[j] = s;\n }\n \n // Matrix multiply by V to get answer.\n for (var j=1; j<=n; j++)\n {\n s = 0.0;\n for (var jj=1; jj<=n; jj++)\n s += v[j][jj]*tmp[jj];\n x[j] = s;\n }\n \n return x;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check to see if player has appropriate key for collided door. | function checkDoorKey(p_sprite, door, game) {
for (var index in p_sprite.entity.key_ring) {
if (p_sprite.entity.key_ring[index] == door.key) {
door.kill()
game.pickup_sound.play()
return
}
}
} | [
"function checkBorderCollision() {\r\n //Player\r\n if (player_x >= (canvas_w - player_w)) rightKey = false;\r\n if (player_x <= (0)) leftKey = false;\r\n if (player_y <= (0)) upKey = false;\r\n if (player_y >= (canvas_h - player_h)) downKey = false;\r\n\r\n //AI\r\n if (AI_x >= (canvas_w - AI_w)) rightAI = false;\r\n if (AI_x <= (0)) leftAI = false;\r\n if (AI_y <= (0)) upAI = false;\r\n if (AI_y >= (canvas_h - AI_h)) downAI = false;\r\n}",
"isHeld(key) {\n if(!this.keyStates[key]) {\n return false;\n }\n return this.keyStates[key].isPressed;\n }",
"checkCollision(player) {\n // Check if the gear and the player overlap each other\n if (this.rowPos == player.rowPos &&\n this.colPos == player.colPos) {\n // If so, then hide the gear item\n this.hasBeenCollected = true;\n this.rowPos = null;\n this.colPos = null;\n this.x = null;\n this.y = null;\n }\n }",
"checkForKey (futureLocation) {\n const isKeyType = this.board.getCell(futureLocation).getType()\n if (isKeyType === 'key') {\n this.keyGained = true\n return true\n } else {\n return false\n }\n }",
"async canPlayerJoin(client, playerId)\n {\n const inGame = this.players.some(x => x.id === playerId);\n return inGame || this.game.allowJoin;\n }",
"keyDown(key) {\n if(this.keydowns[key]) {\n return true;\n }\n return false;\n }",
"function checkMovement(){\n if(keyIsDown(65)){\n player.position.x -=setMode(mode);\n }\n if(keyIsDown(68)){\n player.position.x +=setMode(mode);\n }\n if(keyIsDown(87)){\n player.position.y -=setMode(mode);\n }\n if(keyIsDown(83)){\n player.position.y +=setMode(mode);\n }\n}",
"function checkEnergyCollision() {\r\n energies.forEach(function (e) {\r\n if ((player.X < e.x + energyRadius) &&\r\n (player.X + player.width > e.x) &&\r\n (player.Y < e.y + energyRadius) &&\r\n (player.Y + player.height > e.y)) {\r\n e.onCollide();\r\n //startSound();\r\n }\r\n })\r\n}",
"function isInGame(player)\n\t{\n\t\treturn ((player == boardgameserver.p1) || (player == boardgameserver.p2));\n\t}",
"function C101_KinbakuClub_RopeGroup_PlayerCollared() {\n\tCommon_PlayerOwner = CurrentActor;\n\tCommon_ActorIsOwner = true;\n\tPlayerLockInventory(\"Collar\");\n\tCurrentTime = CurrentTime + 50000;\n}",
"canSeePlayer(){\n\t\t//enemy should act like it doesn't know where the player is if they're dead\n\t\tif(lostgame)\n\t\t\treturn false;\n\t\t\n\t\t// casts a ray to see if the line of sight has anything in the way\n\t\tvar rc = ray.fromPoints(this.pos, p1.pos);\n\t\t\n\t\t// creates a bounding box for the ray so that the ray only tests intersection\n\t\t// for the blocks in that bounding box\n\t\tvar rcbb = box.fromPoints(this.pos, p1.pos);\n\t\tvar poscols = []; // the blocks in the bounding box\n\t\tfor(var i = 0; i < blocks.length; i++){\n\t\t\tif(box.testOverlap(blocks[i].col, rcbb))\n\t\t\t\tposcols.push(blocks[i]);\n\t\t}\n\t\t\n\t\t// tests ray intersection for all the blocks in th ebounding box\n\t\tfor(var i = 0; i < poscols.length; i++){\n\t\t\tif(poscols[i].col.testIntersect(rc))\n\t\t\t\treturn false; // there is a ray intersection, the enemy's view is obstructed\n\t\t}\n\t\treturn true;\n\t}",
"function isThereADoorToGoToRoom (handlerInput, room){\n const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();\n \n // get the doors in the currentRoom\n const currentRoomDoors = sessionAttributes.gamestate.currentRoom.elements.doors\n \n var canGo = false;\n \n // check if there is a door to go to the room\n if (Object.keys(currentRoomDoors).find(key => (currentRoomDoors[key].roomName === room.name))){\n canGo = true;\n }\n \n return canGo;\n}",
"playerWins(){ // i2 - put inline\n\t\tif (this.player === activePlayer && playing === false) {\n\t\t\treturn true;\n\t\t}\t}",
"checkCharacterVicinity() {\n // console.log(\"Vinicinity Hammer function running\");\n //get the position of the main character\n\n\n //variable that allows change in vicinity position in which E needs to be pressed:\n var vicinityLimitZ = 10;\n var vicinityLimitX = 10;\n\n //if the character is in the vicinity\n if (this.inVicinity(vicinityLimitZ, vicinityLimitX)) {\n\n // console.log(\"Player is near the Cupboard\");\n //display interaction overlay if it isn't being shown\n if (this.count == 0) {\n if (this.open == false) {\n gameOverlay.changeText('[E] ENTER CODE');\n //LATER WE CAN ADD A CONDITION IF HE LOOKED AT IT, HE'LL NOTICE IT CAN MOVE, AND THE\n //INTERACTION WILL SAY MOVE PAINTING\n gameOverlay.showOverlay();\n this.count += 1;\n }\n }\n return true;\n }\n //if the character is not in the vicinity, return false\n //hide interaction overlay\n if (this.count == 1) {\n gameOverlay.hideOverlay();\n this.count = 0;\n }\n\n return false;\n }",
"function peopleColiding(person) {\n var result = false;\n Object.keys(people).forEach(key => {\n const other = people[key];\n if (person.x === other.x && person.y === other.y && person.id < other.id) {\n console.log(\"Collision: \" + person.id + \" \" + other.id);\n result = true;\n }\n });\n\n return result;\n}",
"checkLegal (player, x, y) {\n\n //Is the space occupied?\n if (this.board.get(x, y) !== 0) {\n return false;\n }\n\n return this.__evaluationTest(player, x, y);\n\n }",
"function isGameAgainstComp() {\n return !!document.getElementById('computer');\n}",
"collision(dino){\n if (!this.img||!dino.img) return false; \n if(!((this.y>(dino.y+dino.h))||(!this.left&&((this.x>=dino.x+dino.w-25)||(this.x<=dino.x+25)))||(this.left&&((this.x<=dino.x+25)||(this.x>=dino.x+dino.w-25))))){\n if(dino.shield) {\n setTimeout(()=>{dino.shield=false},500); \n return false; \n }\n return true;\n }\n }",
"isGameOver() {\n return this.winner || this.numGuessesRemaining === 0\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
finds specific point based on time input | function findPointAtTime() {
inputTime = document.getElementById("inputTime").value;
refreshGraph();
} | [
"_search(time, param = \"time\") {\n if (this._timeline.length === 0) {\n return -1;\n }\n\n let beginning = 0;\n const len = this._timeline.length;\n let end = len;\n\n if (len > 0 && this._timeline[len - 1][param] <= time) {\n return len - 1;\n }\n\n while (beginning < end) {\n // calculate the midpoint for roughly equal partition\n let midPoint = Math.floor(beginning + (end - beginning) / 2);\n const event = this._timeline[midPoint];\n const nextEvent = this._timeline[midPoint + 1];\n\n if ((0, _Math.EQ)(event[param], time)) {\n // choose the last one that has the same time\n for (let i = midPoint; i < this._timeline.length; i++) {\n const testEvent = this._timeline[i];\n\n if ((0, _Math.EQ)(testEvent[param], time)) {\n midPoint = i;\n } else {\n break;\n }\n }\n\n return midPoint;\n } else if ((0, _Math.LT)(event[param], time) && (0, _Math.GT)(nextEvent[param], time)) {\n return midPoint;\n } else if ((0, _Math.GT)(event[param], time)) {\n // search lower\n end = midPoint;\n } else {\n // search upper\n beginning = midPoint + 1;\n }\n }\n\n return -1;\n }",
"function findNearest(time, callback){\n for(i = 0; i < timestamps.length; i++)\n if (timestamps[i] > time){\n callback(measurments[i]);\n break;\n }\n}",
"getNearestTime (step, time) {\n\t\tlet prev = this.getPreviousTime(step, time);\n\t\tlet next = this.getNextTime(step, time);\n\t\tif (time - prev <= next - time)\n\t\t\treturn prev;\n\t\treturn next;\n\t}",
"function calculateIndex(time) {\n let data = time.split(\":\");\n let currentTime = parseInt(data[0], 10) * 60 + parseInt(data[1], 10);\n let rangeMinutes = parseInt(process.env.rangeMinutes, 10);\n let timeStart = parseInt(process.env.timeStart, 10);\n return Math.floor((currentTime - timeStart) / rangeMinutes);\n}",
"async function findCC(CC, time) {\n\n // console.log(CC, time)\n const matchingCaptions = CC.find(cc => cc.startTime == time && time == cc.endTime)\n return matchingCaptions ? matchingCaptions : null\n\n\n}",
"timeTo (x, y) { return this.get(x, y).time }",
"findCarByTime(timeInMinutes,callback){\n let index=0\n arr=[]\n for(lotIndex=0; lotIndex < noOfLots; lotIndex++ ){\n for(slotIndex=0; slotIndex < noOfSlots; slotIndex++ ){\n if(this.parking[slotIndex][lotIndex]!=undefined){ \n let parkTime=this.minutesConversion(this.parking[slotIndex][lotIndex].parkTime)\n let currentTime=this.minutesConversion(new Date())\n if((currentTime-parkTime)<=timeInMinutes){\n arr[index]=[slotIndex,lotIndex,this.parking[slotIndex][lotIndex].vehicleNumber]\n index++\n }\n }\n }\n }\n this.checkArrayLength(arr,callback)\n }",
"getSessionForTime(time) {\n const finalSession = this.sessions_[this.sessions_.length - 1];\n\n for (let i = 0; i < this.sessions_.length; ++i) {\n if (this.sessions_[i].beginTime >= time && this.sessions_[i].endTime < time)\n return this.sessions_[i]; // exact match\n\n if (this.sessions_[i].endTime < time)\n continue; // the session is in the past\n\n if (this.sessions_[i].beginTime < finalSession.beginTime)\n return this.sessions_[i]; // session that's nearest in the future\n }\n\n return finalSession;\n }",
"getStartPointForTask (event) {\n let start = false;\n let rest = Infinity;\n\n //Check Space between Events currently in the Sequence\n let lastEvent;\n this.sequence.forEach((e, i) => {\n if (i !== 0) {\n const length = this.sequence[i].time.end - lastEvent.time.end;\n if(length > event.time.duration && rest > length - event.time.duration) {\n rest = length - event.time.duration;\n start = this.sequence[i].time.end + 1;\n }\n }\n });\n\n //Get Index of this SequenceElement in the Parent SequenceList\n const id = this.sequenceList.indexOf(this);\n\n //Get SequenceElements next to current Element with different location\n const prev = this.findNextLocation(id, -1);\n const next = this.findNextLocation(id, 1);\n\n //Check Time between previous and current Element, to see if event suits in\n if (prev) {\n const length = this.firstStart - prev.lastEnd - prev.travelTimeToNext;\n if (length > event.time.duration && rest > length - event.time.duration) {\n rest = length - event.time.duration;\n start = this.firstStart - event.time.duration - 1;\n }\n }\n\n //Check Time between next and current Element, to see if event suits in\n if (next) {\n const length = next.firstStart - this.lastEnd - this.travelTimeToNext;\n if (length > event.time.duration && rest > length - event.time.duration) {\n rest = length - event.time.duration;\n start = this.lastEnd + 1;\n }\n }\n return start;\n }",
"getPoint( t ) {\n\n\t\t\tconst d = t * this.getLength();\n\t\t\tconst curveLengths = this.getCurveLengths();\n\t\t\tlet i = 0;\n\n\t\t\t// To think about boundaries points.\n\n\t\t\twhile ( i < curveLengths.length ) {\n\n\t\t\t\tif ( curveLengths[ i ] >= d ) {\n\n\t\t\t\t\tconst diff = curveLengths[ i ] - d;\n\t\t\t\t\tconst curve = this.curves[ i ];\n\n\t\t\t\t\tconst segmentLength = curve.getLength();\n\t\t\t\t\tconst u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;\n\n\t\t\t\t\treturn curve.getPointAt( u );\n\n\t\t\t\t}\n\n\t\t\t\ti ++;\n\n\t\t\t}\n\n\t\t\treturn null;\n\n\t\t\t// loop where sum != 0, sum > d , sum+1 <d\n\n\t\t}",
"function getPwm(hour) {\t\n\tif (LOG) { console.log(\"Looking for TP (\" + hour + \") -----------------\"); }\n\tvar rampe_pwm = { blue: -1, white: -1};\n\tif ( !(TPS[0].hour < hour && hour < TPS[TPS.length-1].hour) ) {\t//hour is in implicit period (night)\n\t\ttp1 = TPS[TPS.length-1];\n\t\ttp2 = TPS[0];\n\t\tif (DEBUG) { console.log( 'night: ' + hour + \" (\" + TPS[TPS.length-1].hour + \"-\" + TPS[0].hour +\")\" ); }\n\t\tif (LOG) { console.log('TP1-TP2', tp1, tp2 ); }\n\t\tvar ratio = ratioPwm(tp1, tp2, hour);\n\t} else {\t//find hour in TPS\n\t\tfor( i = 0; i < TPS.length-1; i++ ) {\n\t\t\ttp1 = TPS[i];\n\t\t\ttp2 = TPS[i+1];\n\t\t\tif ( tp1.hour <= hour && hour <= tp2.hour) {\n\t\t\t\tif (DEBUG) { console.log( tp1.hour + \" <= \" + hour + \" < \" + tp2.hour); }\n\t\t\t\tif (LOG) { console.log( 'TP1-TP2', tp1, tp2 ); }\n\t\t\t\tvar ratio = ratioPwm(tp1, tp2, hour);\n\t\t\t}\n\t\t}\n\t}\n\treturn ratio;\n}",
"at(time, value) {\n const timeInTicks = new _TransportTime.TransportTimeClass(this.context, time).toTicks();\n const tickTime = new _Ticks.TicksClass(this.context, 1).toSeconds();\n\n const iterator = this._events.values();\n\n let result = iterator.next();\n\n while (!result.done) {\n const event = result.value;\n\n if (Math.abs(timeInTicks - event.startOffset) < tickTime) {\n if ((0, _TypeCheck.isDefined)(value)) {\n event.value = value;\n }\n\n return event;\n }\n\n result = iterator.next();\n } // if there was no event at that time, create one\n\n\n if ((0, _TypeCheck.isDefined)(value)) {\n this.add(time, value); // return the new event\n\n return this.at(time);\n } else {\n return null;\n }\n }",
"function getPos(callback){\n\tfindPos(genLap, callback);\n}",
"function determineTimeState(inputHour) {\n let currentHour = moment().format(\"H\");\n if (inputHour < currentHour) return \"past\";\n if (inputHour == currentHour) return \"present\";\n if (inputHour > currentHour) return \"future\";\n}",
"function findSlideNum(time) { //Pre: time is in milliseconds\n let low = 0, high = slides.length - 2, average = Math.floor( (low + high) / 2 );\n\n while (low + 1 != high){\n\n if (slides[average].mark < time){\n low = average;\n average = Math.floor((average + high) / 2);\n }\n else if (slides[average].mark > time){\n high = average;\n average = Math.floor((low + average) / 2);\n }\n else {\n return average;\n }\n }\n\n if (slides[average].mark <= time) {\n return low;\n }\n\n return high;\n }",
"function check_point(p) {\n if (p.x < 0 || p.x > 9) {\n return false;\n } else if (p.y < 0 || p.y > 9) {\n return false;\n } else if (spielfeld[p.y][p.x]) {\n //console.log(\"point already in use:\", p);\n return false;\n } else {\n //console.log(\"point ok:\", p);\n return true;\n }\n}",
"getNextTime (step, time) {\n\t\tlet ret = this.getStepTime(step);\n\t\tlet totalTime = this.getTotalInterval() * 60 * 1000;\n\t\twhile (ret < time)\n\t\t\tret += totalTime;\n\t\treturn ret;\n\t}",
"function spendPoint(point) {\r\n let spendList = []\r\n // Assuming point is larger than 0\r\n while (timeStampData.length > 0 && point > 0) {\r\n if ( (point - timeStampData[0].points) >= 0) {\r\n point = point - timeStampData[0].points;\r\n updateData(timeStampData[0], timeStampData[0].points)\r\n\r\n \r\n\r\n // Updating spendList Array\r\n let notExisted = true;\r\n for (let i = 0; i < spendList.length; i++) {\r\n if (spendList[i].payer == timeStampData[0].payer) {\r\n notExisted = false;\r\n spendList[i].points += -timeStampData[0].points\r\n }\r\n }\r\n if (notExisted) {\r\n let object = {\r\n \"payer\": timeStampData[0].payer,\r\n \"points\": -timeStampData[0].points\r\n }\r\n spendList.push(object)\r\n }\r\n\r\n totalPoints = totalPoints - timeStampData[0].points;\r\n timeStampData.shift();\r\n }\r\n // if timeStampData[0].points is > than current points need to be spent\r\n else{ \r\n timeStampData[0].points = timeStampData[0].points - point;\r\n updateData(timeStampData[0], point)\r\n totalPoints = totalPoints - point;\r\n\r\n // Updating spendList Array\r\n let notExisted = true;\r\n for (let i = 0; i < spendList.length; i++) {\r\n if (spendList[i].payer == timeStampData[0].payer) {\r\n notExisted = false;\r\n spendList[i].points += -point\r\n }\r\n }\r\n if (notExisted) {\r\n let object = {\r\n \"payer\": timeStampData[0].payer,\r\n \"points\": -point\r\n }\r\n spendList.push(object)\r\n }\r\n point = 0;\r\n }\r\n }\r\n return spendList;\r\n}",
"function WhatIsTheTime(timeInMirror){\n\n let mir = timeInMirror.split(':')\n let hour = parseFloat(mir[0])\n let min = parseFloat(mir[1])\n let realHour = 11 - hour\n let realMin = 60 - min\n let realTime\n\n //conditionals if mirrored time hour is 11 or 12 because formula doesn't apply\n if (hour ===12){\n realHour = 11\n }\n else if (hour ===11){\n realHour = 12\n }\n\n //for x:00 times, display mirrored hour rather than i.e 7:60\n if(realMin === 60){\n realHour += 1\n realMin = 0\n }\n\n //single digit times need to concatonate 0 when converted back to string\n if(realHour.toString().length===1){\n realHour = '0'+realHour\n }\n if(realMin.toString().length===1){\n realMin = '0'+realMin\n }\n\n //if 6PM, or 12PM -> realTime is the same, else realTime = realHour + realMin based on calculations\n if (timeInMirror===\"06:00\" || timeInMirror===\"12:00\"){\n realTime = timeInMirror\n } else {\n realTime = realHour + ':' + realMin\n }\n\n return realTime\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
swaps current gun with the previously used one | function swapGun()
{
let tmp = gun;
selectGun(prevGun);
prevGun = tmp;
} | [
"swap() {\n const { top, stack } = this;\n const tmp = stack[top - 2];\n\n stack[top] = stack[this.top];\n stack[this.top] = tmp;\n }",
"swap(dropTarget) {\n const previousDrag = dropTarget.draggable;\n previousDrag.revert();\n this.drop(dropTarget);\n }",
"function swap (a, b) {\n var c = rep_data.data [a];\n rep_data.data [a] = rep_data.data [b];\n rep_data.data [b] = c;\n}",
"swap(first, second)\n\t{\n\n\t\tthis.first = first;\n\t\tthis.second = second;\n\n\t\tvar temp = this.bars[first];\n\t\tthis.bars[first] = this.bars[second];\n\t\tthis.bars[second] = temp;\n\n\t\tvar temp2 = this.bars[first].index;\n\t\tthis.bars[first].index = this.bars[second].index;\n\t\tthis.bars[second].index = temp2;\n\n\t\ttemp2 = this.bars[first].compairednumberXPos;\n\t\tthis.bars[first].compairednumberXPos = this.bars[second].compairednumberXPos;\n\t\tthis.bars[second].compairednumberXPos= temp2;\n\n\t\tthis.bars[first].targetX = this.bars[second].xPos;\n\t\tthis.bars[second].targetX = this.bars[first].xPos;\n\n\t\tthis.numOfSwaps++;\n\n\t\t/* Redundant\n\t\tthis.bar1 = this.bars[j];\n\t\tthis.bar2 = this.bars[j + 1];*/\n\t}",
"function resetGame() {\n ships._ships = [];\n currentState = states.Splash;\n score = 0;\n shipGap = shipGapMax;\n}",
"function weaponSwitch($clickedSquare, weaponString, weapon) {\n $clickedSquare.removeClass(weaponString)\n $clickedSquare.addClass(game.activePlayer.weapon.name)\n game.activePlayer.weapon = weapon\n $clickedSquare.addClass(game.activePlayer.name)\n fight.updateFightArena()\n}",
"resetTurn() {\n let turn = this.state.turn;\n let flipped = this.state.flipped.slice();\n\n flipped[turn[0]] = false;\n flipped[turn[1]] = false;\n turn = Array(2).fill(null);\n\n this.setState( {\n turn: turn,\n flipped: flipped\n });\n }",
"function swap_with_blank(tile) {\n var row = blank.row;\n var col = blank.col;\n blank.col = tile.col;\n blank.row = tile.row;\n position_tile(tile, row, col);\n position_tile(blank, blank.row, blank.col);\n}",
"function vectorSwap(){\n\tchanges = 0;\n\tnoiseLevel = 0;\n\tvar eta = 1;\n\t\n\tvar lchanges = changes;\n\tvar a = fixedSpots[0][2];\n\tvar b = fixedSpots[1][2];\n\tvar c = fixedSpots[2][2];\n\tvar d = fixedSpots[3][2];\n\t\n\tfor (var i=0;i<gridSize2;i++){\n\t\tvar i1 = iToY(i,gridSize);\n\t\tvar j1 = iToX(i,gridSize);\n\t\tlchanges = changes;\n\t\t\ttestCellNeighborsOverGrid(i1,j1);\n\t}\n\t// Annealing - random cell swaps....\n\tvar gSM1 = gridSize-1;\n\tfor (var i = 0; i<gridSize; i++){\n\t\tvar i1 = randGS(gridSize); // i,j +/- foreceRange....\n\t\tvar j1 = randGS(gridSize);\n\t\tvar force1At1 = forceAtGridPoint(i1,j1);\n\t\tvar i2 = Math.min(gSM1,Math.max(0,i1 + randPMFr()));\n\t\tvar j2 = Math.min(gSM1,Math.max(0,j1 + randPMFr()));\n\t\tvar force2At2 = forceAtGridPoint(i2,j2);\n\t\ttrade(i1,j1,i2,j2);\n\t\tvar force1At2 = forceAtGridPoint(i2,j2);\n\t\tvar force2At1 = forceAtGridPoint(i1,j1);\n\t\tvar resetTrade = force1At1 + force2At2 + eta - force1At2 - force2At1;\n\t\tif(resetTrade < 0){\n\t\t\ttrade(i1,j1,i2,j2); // reset if no gain in trades...\n\t\t} else {\n\t\t\tlchanges = changes;\n\t\t\tchanges++;\n\t\t\tnoiseLevel += resetTrade;\n\t\t}\n\t}\n\tlchanges = changes;\n\ttotalChanges += changes;\n}",
"swapPosition(player1, player2, team) {\n this.animatePlayerSwap(player1, player2);\n [player1.pos, player2.pos] = [player2.pos, player1.pos];\n if (team == nameWest) {\n [this.nw, this.sw] = [this.sw, this.nw];\n } else {\n [this.ne, this.se] = [this.se, this.ne];\n }\n }",
"function swap (mapping, rank1, rank2, qualifier) {\n const temp = {...mapping[rank2], qualifier};\n mapping[rank2] = mapping[rank1];\n mapping[rank1] = temp;\n}",
"move(tile) {\r\n if (this.player === this.map.cp) {\r\n if (!this.player.moved) {\r\n this.tile.unit = null\r\n this.tile = tile;\r\n tile.unit = this;\r\n this.mapX = tile.mapX;\r\n this.mapY = tile.mapY;\r\n this.hasFocus = false;\r\n this.pos = tile.pos;\r\n this.player.moved = true;\r\n if (tile.village) {\r\n if (tile.village.owner !== this.player) {\r\n tile.village.enemyStartTurn = this.map.turnCount;\r\n tile.village.attackedBy = this.player;\r\n } else {\r\n tile.village.enemyStartTurn = null;\r\n tile.village.attackedBy = null;\r\n }\r\n }\r\n }\r\n }\r\n }",
"update_disk(disk, t1, t2) {\n\t\tt1.arrDisk.pop() //pop the disk out of the fromTower\n\t\tt2.arrDisk.push(disk) //push the disk being moved into the toTower\n\t}",
"switchPlayers(){\n if(this.currentPlayer == this.player1){\n this.currentPlayer = this.player2;\n }\n else this.currentPlayer = this.player1;\n }",
"_changeTurn() {\n this._currentTurn =\n this._currentTurn === this._redBigPlanet\n ? this._blueBigPlanet\n : this._redBigPlanet;\n if (this._targetPlanet === this._currentTurn) {\n this._changeTarget();\n }\n }",
"function replaceWeapon(value, weapon, num) {\n let tile = $('.box[boxID= ' + num + ']');\n whoIsActive();\n tile.removeClass(weapon).addClass(playerActive.weapon);\n playerActive.weapon = weapon; \n playerNotActive.power = value; \n}",
"function swap(triangle, i , j) {\n var temp = triangle[i];\n triangle[i] = triangle[j];\n triangle[j] = temp;\n return triangle;\n}",
"_changeTarget() {\n this._targetPlanet =\n this._targetPlanet === this._redBigPlanet\n ? this._blueBigPlanet\n : this._redBigPlanet;\n }",
"function swapPieces(face, times) {\n\tfor (var i = 0; i < 6 * times; i++) {\n\t\tvar piece1 = getPieceBy(face, i / 2, i % 2),\n\t\t\t\tpiece2 = getPieceBy(face, i / 2 + 1, i % 2);\n\t\tfor (var j = 0; j < 5; j++) {\n\t\t\tvar sticker1 = piece1.children[j < 4 ? mx(face, j) : face].firstChild,\n\t\t\t\t\tsticker2 = piece2.children[j < 4 ? mx(face, j + 1) : face].firstChild,\n\t\t\t\t\tclassName = sticker1 ? sticker1.className : '';\n\t\t\tif (className)\n\t\t\t\tsticker1.className = sticker2.className,\n\t\t\t\tsticker2.className = className;\n\t\t}\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This should prevent multiple read in a short interval | function lock_read(timeout=2000){
console.log('{DBG] locking');
DETECTION = false;
setTimeout(() => {
console.log('[DBG] UNlocking');
DETECTION = true;
}, timeout);
} | [
"function is_data_stale() {\n\treturn last + max_age < Date.now();\n}",
"checkPendingReads() {\n this.fillBuffer();\n\n let reads = this.pendingReads;\n while (reads.length && this.dataAvailable &&\n reads[0].length <= this.dataAvailable) {\n let pending = this.pendingReads.shift();\n\n let length = pending.length || this.dataAvailable;\n\n let result;\n let byteLength = this.buffers[0].byteLength;\n if (byteLength == length) {\n result = this.buffers.shift();\n }\n else if (byteLength > length) {\n let buffer = this.buffers[0];\n\n this.buffers[0] = buffer.slice(length);\n result = ArrayBuffer.transfer(buffer, length);\n }\n else {\n result = ArrayBuffer.transfer(this.buffers.shift(), length);\n let u8result = new Uint8Array(result);\n\n while (byteLength < length) {\n let buffer = this.buffers[0];\n let u8buffer = new Uint8Array(buffer);\n\n let remaining = length - byteLength;\n\n if (buffer.byteLength <= remaining) {\n this.buffers.shift();\n\n u8result.set(u8buffer, byteLength);\n }\n else {\n this.buffers[0] = buffer.slice(remaining);\n\n u8result.set(u8buffer.subarray(0, remaining), byteLength);\n }\n\n byteLength += Math.min(buffer.byteLength, remaining);\n }\n }\n\n this.dataAvailable -= result.byteLength;\n pending.resolve(result);\n }\n }",
"function readFilePolling(filename) {\n const stream = createReadStream(filename);\n\n stream.on('readable', () => {\n let data;\n while ((data = stream.read()) !== null) {\n console.log(data);\n }\n });\n}",
"onTimeOut() {\n if (this.exhausted) {\n this.stop();\n return;\n }\n\n this.roll();\n }",
"readEvents(checkSemaphore) {\n let fromBlock = this.lastReadBlock;\n let toBlock = fromBlock + 10000;\n if (toBlock > this.highestBlock) {\n toBlock = this.highestBlock;\n }\n if (!checkSemaphore) {\n if (this.readingEvents === true) {\n return;\n }\n this.readingEvents = true;\n }\n logger.info(\n \"Reading block-range %d -> %d (%d remaining)\",\n fromBlock,\n toBlock,\n this.highestBlock - fromBlock\n );\n this.contract.getPastEvents(\n \"PeepethEvent\",\n {\n fromBlock: fromBlock,\n toBlock: toBlock\n },\n (error, events) => {\n events.map(this.parseEvent.bind(this));\n logger.info(\"done..\");\n this.lastReadBlock = toBlock;\n if (this.highestBlock > toBlock) {\n this.readEvents(true);\n } else {\n logger.info(\n \"fromBlock %d - lastReadBlock %d - highestBlock %d\",\n fromBlock,\n this.lastReadBlock,\n this.highestBlock\n );\n logger.info(\"event reader going to sleep\");\n this.dumpUsers();\n this.readingEvents = false;\n }\n }\n );\n }",
"static validateReadingLessThanCounterOverflow(pageClientAPI, dict) {\n\n //Reading is not allowed, or reading is optional and empty\n if (libThis.evalIgnoreReading(dict)) {\n return Promise.resolve(true);\n }\n\n let error = false;\n //Is a counter and has overflow value\n if (libThis.evalIsCounter(dict) && libThis.evalIsCounterOverflow(dict)) {\n //previous = new reading or overflow > new reading\n error = (libThis.evalIsPreviousReadingNotEmptyAndReadingEqualsPrevious(pageClientAPI, dict) || libThis.evalIsOverflowNotEmptyAndOverflowGreaterThanReading(pageClientAPI, dict)) ? false : true;\n }\n if (error) {\n let dynamicParams = [dict.CounterOverflow];\n let message = pageClientAPI.localizeText('validation_reading_less_than_counter_overflow',dynamicParams);\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ReadingSim'), message);\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n } else {\n return Promise.resolve(true);\n }\n }",
"get locked() { return false }",
"async function sendData(){\n //Increment count everytime sendData is invoked. \n COUNT++; \n\n console.log('COUNT: ', COUNT);\n console.log('BUFFER: ', BUFFER); \n \n //Read last three minutes of log data from stream and store into an array of objects.\n const streamData = await redis.readRedisStream();\n \n //Logic should only trigger if a valid response is received from the redis read handler.\n if(streamData.length !== 0){\n \n //Analyze last three minutes of stream data and store output of analysis.\n let output = data.rtData(streamData);\n \n //When 1 minutes have passed (i.e. count is 20, since count only increments every 3 seconds), add to buffer. \n if(COUNT % 20 === 0){\n \n //Add the log object to the buffer. \n BUFFER.push(output[2]); \n \n //Reset count for the next cycle. \n COUNT = 0; \n \n if(BUFFER.length === 5){\n \n console.log('WRITE TO DB TRIGGERED!'); \n\n //Pass buffer into historical data analysis.\n writeToDB(BUFFER); \n \n //Reset buffer for the next cycle.\n BUFFER = []; \n }\n }\n \n } else {\n \n console.log('No usable data from the stream. ')\n }\n \n //Recursive call to trigger function every second. \n setTimeout(() => {\n sendData(); \n }, 3000); \n}",
"startThermsReading() {\n setInterval(() => {\n for (let i = 0; i < this.pins.length; i++) { \n this.board.analogRead(this.pins[i], (value) => {\n this.therms.push(value);\n });\n }\n }, 100);\n }",
"_startPollingData() {\n this._pollDataInterval = setInterval(() => this._getBalance(), 3000);\n\n // We run it once immediately so we don't have to wait for it\n this._getBalance();\n }",
"throttle(callback) {\n if (this._queuing < this._concurrency)\n callback();\n else\n this.once('ready', ()=> this.throttle(callback));\n }",
"function OneShotLimitReached()\n{\n\treturn (crashesStarted + gearShiftsStarted) > oneShotLimit;\n}",
"isStreamingData(data){\n var isStreaming = false;\n var currTime = Math.floor(new Date().getTime());\n if(data && data.length && data.hasOwnProperty('latestTime') && data.latestTime > currTime - 30000){\n isStreaming = true;\n }\n return isStreaming;\n }",
"readStream(){\n redis.consumeFromQueue(config.EVENTS_STREAM_CONSUMER_GROUP_NAME, this.consumerId, 1, config.EVENTS_STREAM_NAME, false, (err, messages) => {\n if (err) {\n this.logger.warn(`Failed to read events. ${err.message}`);\n }\n\n if (messages){\n this.logger.log('Received message from event stream.');\n\n this.processMessages(messages);\n }\n\n setTimeout(()=>{\n this.readStream();\n }, 1000);\n });\n }",
"_read() {\n if (this.index <= this.array.length) {\n //getting a chunk of data\n const chunk = {\n data: this.array[this.index],\n index: this.index\n };\n //we want to push chunks of data into the stream\n this.push(chunk);\n this.index += 1;\n } else {\n //pushing null wil signal to stream its done\n this.push(null);\n }\n }",
"function cycleStream(){\n //push the numbres to the array\n cycleCount_Array.push(cycleCount);\n cycleFollow_Array.push(cycleFollow);\n cycleFollow = cycleFollow / cycleCount;\n //check to see that there has been an increase if not then send 0\n if(typeof cycleFollow === 'undefined' || cycleFollow === null){\n cycleFollow = 0;\n }\n //emit this even\n io.sockets.emit('cycle',{count: cycleCount, follow: cycleFollow});\n //reset the numbers back to 0\n cycleCount = cycleFollow = 0;\n //loop the data\n setTimeout(function(){\n cycleStream();\n },5000);\n}",
"function brokenRecord() {\n // ADD CODE HERE\n // setInterval(sayHiAgain, 1000);\n\n // another approach\n // setInterval(()=>console.log('hi again'), 1000)\n}",
"static validateReadingExceedsLength(pageClientAPI, dict) {\n\n //Reading is not allowed, or reading is optional and empty\n if (libThis.evalIgnoreReading(dict)) {\n return Promise.resolve(true);\n }\n\n //New reading length must be <= global maximum\n let max = libCom.getAppParam(pageClientAPI, 'MEASURINGPOINT', 'ReadingLength');\n\n if (libThis.evalReadingLengthWithinLimit(dict, max)) {\n return Promise.resolve(true);\n } else {\n let dynamicParams = [max];\n let message = pageClientAPI.localizeText('validation_maximum_field_length', dynamicParams);\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ReadingSim'), message);\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n }\n }",
"function setBufferChecker() {\n bufferChecker = window.setInterval(function() {\n var allBuffered = true;\n\n var currTime = getCurrentTime(masterVideoId);\n\n for (var i = 0; i < videoIds.length; ++i) {\n var bufferedTimeRange = getBufferTimeRange(videoIds[i]);\n if (bufferedTimeRange) {\n var duration = getDuration(videoIds[i]);\n var currTimePlusBuffer = getCurrentTime(videoIds[i]) + bufferInterval;\n var buffered = false;\n for (j = 0;\n (j < bufferedTimeRange.length) && !buffered; ++j) {\n currTimePlusBuffer = (currTimePlusBuffer >= duration) ? duration : currTimePlusBuffer;\n if (isInInterval(currTimePlusBuffer, bufferedTimeRange.start(j), bufferedTimeRange.end(j))) {\n buffered = true;\n }\n }\n allBuffered = allBuffered && buffered;\n } else {\n // Do something?\n }\n }\n\n if (!allBuffered) {\n playWhenBuffered = true;\n ignoreNextPause = true;\n for (var i = 0; i < videoIds.length; ++i) {\n pause(videoIds[i]);\n }\n hitPauseWhileBuffering = false;\n $(document).trigger(\"sjs:buffering\", []);\n } else if (playWhenBuffered && !hitPauseWhileBuffering) {\n playWhenBuffered = false;\n play(masterVideoId);\n hitPauseWhileBuffering = false;\n $(document).trigger(\"sjs:bufferedAndAutoplaying\", []);\n } else if (playWhenBuffered) {\n playWhenBuffered = false;\n $(document).trigger(\"sjs:bufferedButNotAutoplaying\", []);\n }\n }, checkBufferInterval);\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.