query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Utility function to reload Blockly.Language functions. These next three functions are needed for any App Inventor blocks. Redefined here because we've redefined Blockly.Language TODO: This is a HACK that should be fixed, perhaps by writing a function to clear Blockly.Language of all its elements, preserving its functions. | function resetBlocklyLanguage() {
Blockly.Language.setTooltip = function(block, tooltip) {
block.setTooltip("");
}
Blockly.Language.YailTypeToBlocklyTypeMap = {
'number':Number,
'text':String,
'boolean':Boolean,
'list':Array,
'component':"COMPONENT",
'InstantInTime':Blockly.Language.InstantInTime,
'any':null
//add more types here
}
Blockly.Language.YailTypeToBlocklyType = function(yail) {
var bType = Blockly.Language.YailTypeToBlocklyTypeMap[yail];
if (bType != null || yail == 'any') {
return bType;
} else {
throw new Error("Unknown Yail type: " + yail + " -- YailTypeToBlocklyType");
}
}
} | [
"function initQuizmeLanguage() {\n if (DEBUG) console.log(\"RAM: initQuizmeLanguage \");\n \n var whitelist = [];\n whitelist = whitelist.concat(MATH_BLOCKS).concat(LOGIC_BLOCKS).concat(VARIABLES_BLOCKS).concat(PROCEDURES_BLOCKS);\n whitelist = whitelist.concat(CONTROLS_BLOCKS).concat(LISTS_BLOCKS).concat(TEXT_BLOCKS).concat(COLOR_BLOCKS).concat(TOPLEVEL_BLOCKS);\n\n // Initialize Blockly.Language by copying whitelisted blocks from WholeLanguage\n Blockly.Language = {}\n for (var propname in Blockly.WholeLanguage) {\n if (whitelist.indexOf(propname) != -1)\n Blockly.Language[propname] = Blockly.WholeLanguage[propname];\n }\n\n resetComponentInstances(); // In quizme-helper.js\n var components = ['Button', 'Sound', 'Label', 'Canvas'];\n Blockly.Quizme.addComponents(components);\n \n // Remove generics\n for (var k = 0; k < components.length; k++) {\n var component_name = components[k];\n delete(Blockly.Language[component_name + \"_setproperty\"]);\n delete(Blockly.Language[component_name + \"_getproperty\"]);\n } \n}",
"function clearLanguages() {\n\t\tlangs = [];\n\t}",
"function customizeQuizmeLanguage(quizname, keepers, components) {\n if (DEBUG) console.log(\"RAM: customizeQuizmeLanguage() quizname = \" + quizname + \" keepers = \" + keepers);\n\n // If the language has already been set for this quiz type, just exit \n // NOTE: Leave quizname=undefined to reset the language\n\n if (quizname && Blockly.Quizme.language_type == quizname) {\n if (DEBUG) console.log(\"RAM: language set to \" + quizname + \" ... exiting\");\n return;\n }\n\n // Initialize the language with all blocks.\n initQuizmeLanguage();\n var newLanguage = {}\n for (var propname in Blockly.Language) {\n if (keepers.indexOf(propname) != -1) {\n newLanguage[propname] = Blockly.Language[propname];\n }\n if (Blockly.Language[propname].category == 'Component' &&\n Blockly.Language[propname].blockType != 'genericmethod') {\n var typeName = Blockly.Language[propname].typeName;\n if (components.indexOf(typeName) != -1) {\n newLanguage[propname] = Blockly.Language[propname];\n }\n }\n }\n Blockly.Language = newLanguage;\n\n // Construct the languageTree used to populate the toolbox.\n Blockly.languageTree = initToolboxLanguageTree(Blockly.Language);\n\n Blockly.Quizme.language_type = quizname;\n if (DEBUG) console.log(\"RAM: Blockly.Quizme.language_type = \" + Blockly.Quizme.language_type);\n\n resetBlocklyLanguage(); // Hack to add certain neede properties back onto Blockly.Language.\n\n // Add the App Inventor components to the langauge and initialize the Toolbox \n resetComponentInstances();\n Blockly.Quizme.addComponents(components);\n \n // Delete the current toolbox tree (svg element) from the webpage.\n var html = Blockly.Toolbox.HtmlDiv;\n var children = html.childNodes;\n if (children[1])\n children[1].parentNode.removeChild(children[1]);\n\n Blockly.Toolbox.init();\n}",
"async modifyLanguages(client, data, trx) {\n await client.languages().delete(trx);\n await client.languages().createMany(data, trx);\n }",
"function menutoshowlang(){\n}",
"function updateLanguage(select_language, select_dialect) {\n var list = langs[select_language.selectedIndex];\n select_dialect.style.visibility = list[1].length == 1 ? 'hidden' : 'visible';\n localStorage['dialect'] = select_dialect.selectedIndex; \n document.getElementById('voiceBtn').setAttribute('lang', list[select_dialect.selectedIndex + 1][0]);\n}",
"function setLanguage() {\n const queryParams = new URLSearchParams(window.location.search);\n const language = (queryParams.get(\"language\") || localStorage.getItem(\"language\") || \"\").toLowerCase();\n const languages = new Map();\n const codeTabs = document.querySelectorAll(\".multitab-code:not(.dependencies) li\") || [];\n Array.from(codeTabs).forEach(it => {\n languages.set(it.textContent.toLowerCase(), it.getAttribute(\"data-tab\")); // language and index\n });\n if (languages.get(language) !== undefined) {\n codeTabs[0].parentElement.querySelector(`[data-tab='${languages.get(language)}']`).click();\n }\n }",
"function updateLanguageToKorean() {\n localStorage.setItem('lang', 'ko');\n document.title = $('#title-ko').val();\n $('.navbar__language--english').removeClass('language--active');\n $('.navbar__language--korean').addClass('language--active');\n $('[data-lang=\"en\"]').addClass('hidden');\n $('[data-lang=\"ko\"]').removeClass('hidden');\n}",
"function setCodeLanguage(lang) {\n selectedLanguageName = lang;\n selectedLanguageCodes = allCodes[lang];\n return;\n }",
"function patchFlatpickrLocales () {\n hookLibrary('flatpickr', async flatpickr => {\n for (const code in flatpickrLocales) {\n flatpickr.l10ns[code] = flatpickrLocales[code]\n }\n observe('.flatpickr-calendar', {\n add: disableGoogleTranslate\n })\n })\n}",
"setDefaultWordlist(language) {\n bip39.setDefaultWordlist(language);\n }",
"function initToolboxLanguageTree(language) {\n resetBlocklyLanguage(); // Hack to add some special Language properties\n\n // Start with an empty tree.\n Blockly.languageTree = Blockly.Xml.textToDom(\"<xml id='toolbox' style='display:none'></xml>\");\n\n // Initialize the category list\n var cats = [];\n\n // Iterate through the blocks in the language to construct the toolbox languageTree\n // for (var propname in Blockly.WholeLanguage) {\n for (var propname in language) {\n if (DEBUG) console.log(\"Adding to Blockly.languageTree \" + propname);\n\n // Use a tempWorkspace so that procedure def blocks are not set to visible.\n var tempWorkspace = new Blockly.Workspace();\n var blk = new Blockly.Block(tempWorkspace, propname);\n\n // If this block has a category, append the category name to category list.\n var catname = blk['category'];\n if (catname) {\n if (catname == 'Component') {\n cats[''] = '';\n cats['COMPONENTS'] = '';\n catname = blk.typeName; // For components use the typename for category.\n }\n var category = cats[catname];\n if (!category) {\n category = \"\";\n cats[catname] = category;\n }\n category = category.concat(\"<block type='\" + propname + \"'></block>\");\n cats[catname] = category;\n }\n }\n // Now build and return the categorized tree.\n var treeString = \"<xml id='toolbox' style='display:none'>\";\n for (var cat in cats) {\n treeString = treeString.concat(\"<category name='\" + cat + \"'>\" + cats[cat] + \"</category>\");\n }\n treeString = treeString.concat(\"</xml>\");\n return Blockly.Xml.textToDom(treeString);\n}",
"function setLang(l){\n\tif(lockLangButtons == true){\n\t\treturn;\n\t}\n\tdisableNav();\n\t$('.zone').empty();\n\t$(\".zone\").slideUp(1000);\n\t$(\".zone\").slideDown(1000);\n\tlang = l;\n\tsetTimeout(function(){\n\t\t\n\t\tnewGame();\n\t}, 1100);\n}",
"async _loadDicts() {\n // Remove if replace is unset\n if (!game.user || !game.user.isGM || this.data.name.replace !== \"replace\") {\n // Useful to free up memory? its \"just\" up to 17MB...\n // delete this.dict;\n return;\n }\n if (!this.dict) this.dict = {};\n const options = this.data.name.options;\n let languages = this.languages;\n for (let lang of languages) {\n if (this.dict[lang]) continue;\n this.dict[lang] = (await import(`./dict/${lang}.js`)).lang;\n }\n }",
"function setMenuLang(){\n \n // Browser basic settings\n var currentLang = \"lang_\"+getNavigatorLang();\n \n \n if(localStorage.myLang)\n {\n currentLang= \"lang_\"+localStorage.myLang;\n }\n\n //Menu setting\n \n var menu = document.querySelectorAll(\"ul.nav li a\");\n for(var i=0; i<menu.length; i++)\n {\n var data = menu[i].getAttribute(\"data-name\");\n menu[i].innerHTML= window[currentLang][data];\n }\n \n // Navbar title and header setting\n \n var getSelector = document.querySelector(\".navbar-header a\");\n \n var dataName = getSelector.getAttribute(\"data-title\");\n \n getSelector.innerHTML = window[currentLang][dataName];\n \n \n var getSelector = document.querySelector(\".starter-template h1\");\n \n var dataName = getSelector.getAttribute(\"header-title\");\n \n getSelector.innerHTML = window[currentLang][dataName]; \n}",
"function clearTranslations() {\n $localize.TRANSLATIONS = {};\n}",
"function TamperLang() {\n this.init();\n}",
"codePrismLanguageLoad() {\n return Prism.languages[this.codeLanguage];\n }",
"async getInstalledLanguages() {\n const results = await SPCollection(this, \"installedlanguages\")();\n return results.Items;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Team Constructor String TeamName String TeamColour Integer Number of Dice Integer Number of Backlog allowed Boolean true/false if backlog is prefilled // relevant only to first team Integer Maximum size of Activity > 7 means any activity can't take more than 7 units to finish | function Team(teamName, teamColour, numberOfDice, numberOfBacklog, backlogFilled, maximumTaskSize) {
this.teamName = teamName;
this.teamColour = teamColour;
this.numberOfDice = ((numberOfDice != null) ? numberOfDice : defaultNumberOfDice);
this.numberOfBacklog = ((numberOfBacklog != null) ? numberOfBacklog : defaultNumberOfBacklog);
this.backlogFilled = ((backlogFilled != null) ? backlogFilled : defaultBacklogFilled);
this.maximumTaskSize = ((maximumTaskSize != null) ? maximumTaskSize : defaultMaximumTaskSize);
/*
Counter to measure how many tasks are completed
in current sprint
*/
this.unitOfWorkCompleted = 0;
/* array of completed tasks per sprint
*/
this.unitOfWorkCompletedArray = new Array();
/*
Counter to measure wasted one dice
in current sprint
*/
this.wastedOneDice = 0;
/* array of wasted one dice per sprint
*/
this.wastedOneDiceArray = new Array();
this.teamID = "team_" + teamCounter++;
this.tasksArray = new Array();
this.backlogTasksArray = new Array();
this.workInProgressTasksArray = new Array();
this.doneTasksArray = new Array();
} | [
"function Team() {\n this.Team = undefined;\n this.Liga = undefined;\n this.Land = undefined;\n this.LdNr = 0;\n this.LgNr = 0;\n}",
"function Off_Teams(a_team){\n\tthis.against = a_team; // This is the team that the offense is built against\n\tthis.num = 0;\n\t\n\tthis.addTeam = function(team, score, version, comment = \"\"){\n\t\tif(comment === null) comment = \"\";\n\t\tthis[this.num] = {team: team, score: score, version: version, comment: comment};\n\t\tthis.num++;\n\t}\n\t\n\tthis.getDefStr = function(){\n\t\treturn this.against.unitsStr();\n\t}\n\t\n\tthis.getTeam = function(num){\n\t\treturn this[num].team.unitsStr();\n\t}\n\t\n\tthis.getScore = function(num){\n\t\treturn this[num].score;\n\t}\n\t\n\tthis.getVersion = function(num){\n\t\treturn this[num].version;\n\t}\n\t\n\tthis.getComment = function(num){\n\t\treturn this[num].comment;\n\t}\n\t\n\t// example properties\n\t// this[0] = Jun_Miyako_Kuka_Ilya_Hiyori\n\t// this[\"Jun_Miyako_Kuka_Ilya_Hiyori\"] = 512\n\t\n\tthis.teamStr = function(num){\n\t\tlet data = this[num];\n\t\tlet team = data.team.split(\"_\");\n\t\tlet main = \":\" + team.join(\": :\") + \": \" + \"Score:\" + data.score + \" V\" + data.version;\n\t\tlet comm = data.comment;\n\t\tif(comm !== \"\"){\n\t\t\tmain = main + \"\\n\" + comm;\n\t\t}\n\t\treturn main;\n\t}\n\t\n\tthis.filtStr = function(){\n\t\tif(this.num == 1){\n\t\t\treturn [this.teamStr(0)];\n\t\t}else{\n\t\t\tlet arr = [];\n\t \t\tfor(let i = 0; i < this.num; i++){\n\t \t\t\tarr[i] = this.teamStr(i);\n\t \t\t}\n\t \t\treturn arr;\n\t \t}\n\t}\n}",
"function selectTeam(data, config) {\n const constraints = config.constraints;\n const t = config.team_type.team;\n let max_players_from_fav_team = constraints.max;\n if (config.team_type.type === 'balanced')\n max_players_from_fav_team = 6;\n \n let players = [];\n let creditLeft = config.max_credit;\n const team1 = t === 1 ? data.team1 : data.team2;\n const team2 = t !== 1 ? data.team1 : data.team2;\n const fav_team_sorted = t === 1 ? _.cloneDeep(data.t1_sorted) : _.cloneDeep(data.t2_sorted);\n const other_team_sorted = t !== 1 ? _.cloneDeep(data.t1_sorted) : _.cloneDeep(data.t2_sorted);\n let fav_team_count = 0;\n let other_team_count = 0;\n\n let counts = {\n wk: 0,\n ar: 0,\n bt: 0,\n bl : 0,\n }\n let totalPlayersToSelect = constraints.wk[0] + constraints.bt[0] + constraints.ar[0] + constraints.bl[0];\n for (let i = 0; i < fav_team_sorted.length; i++) {\n const p = fav_team_sorted[i];\n if (canSelectPlayer(p, counts, constraints, creditLeft)) {\n players.push(p);\n creditLeft -= p.credit;\n counts[p.role]++;\n fav_team_count++;\n totalPlayersToSelect--;\n }\n if (totalPlayersToSelect === 0 || fav_team_count === max_players_from_fav_team)\n break;\n }\n\n // find what are remaining min players and add from other team\n if (totalPlayersToSelect > 0)\n Object.keys(counts).forEach((k) => {\n if (counts[k] < constraints[k][0]) {\n let ot = addPlayer(k, other_team_sorted, constraints[k][0] - counts[k], creditLeft, players);\n creditLeft = ot.rem_credit;\n other_team_count += ot.added_players || 0;\n if (ot.rem_players === 0) // constraints met update counts\n counts[k] = constraints[k][0]\n }\n })\n \n // need to select remaining players from other team with remaining credits left\n totalPlayersToSelect = 11 - players.length; \n const remPlayers = getMaxPointPlayersUnderCredit(other_team_sorted, creditLeft)\n if (remPlayers && remPlayers.players) {\n other_team_count += remPlayers.players.length;\n if (remPlayers.players.length < totalPlayersToSelect) {\n console.error('[getMaxPointPlayersUnderCredit] could not find remaining players within credit limit')\n }\n }\n // console.log('all players')\n const playing11 = [...players, ...remPlayers.players];\n // console.log(playing11)\n const sortedPlaying11 = _.orderBy(playing11, ['points'], ['desc']);\n // console.log('all players - sorted')\n // console.log(sortedPlaying11)\n const cvc_candidates = _.slice(sortedPlaying11, 0, 2);\n // console.log(cvc_candidates)\n return {\n rem_credit: remPlayers.rem_credit,\n players: playing11,\n cvc_candidates: cvc_candidates,\n counts: counts,\n t1: {\n name: team1.name,\n code: team1.code,\n color: team1.color,\n playingCount: fav_team_count\n },\n t2: {\n name: team2.name,\n code: team2.code,\n color: team2.color,\n playingCount: other_team_count\n },\n }\n}",
"function TeamClassification() {\n this.team = new Team();\n this.teamParams = { };\n\n this.renameParamFun = function() {\n const __MYTEAM = this.team;\n\n getMyTeam(this.optSet, this.teamParams, __MYTEAM);\n\n if (__MYTEAM.LdNr !== undefined) {\n // Prefix fuer die Optionen mit gesonderten Behandlung...\n return __MYTEAM.LdNr.toString() + __MYTEAM.LgNr.toString();\n } else {\n return undefined;\n }\n };\n}",
"function teamNumber(teamtext) {\n if(teamtext == 'CT') {\n if(structure.rounds.length > 15) {\n return 2;\n } else {\n return 1;\n }\n } else if(teamtext == 'TERRORIST') {\n if(structure.rounds.length > 15) {\n return 1;\n } else {\n return 2;\n }\n }\n}",
"setPlayerTeam(player, zone, team = undefined) {\n const location = DeathMatchLocation.getById(zone);\n if (!location.hasTeams)\n return;\n\n if (!this.teamScore_.has(zone))\n this.teamScore_.set(zone, new DeathMatchTeamScore());\n\n if (!this.zoneTextDraws_.has(zone)) {\n this.zoneTextDraws_.set(zone, -1);\n const textDraw = new TextDraw({\n position: [482, 311],\n text: '_',\n\n color: Color.fromNumberRGBA(-1),\n shadowColor: Color.fromRGBA(0, 0, 0, 255),\n font: 2,\n letterSize: [0.33, 1.5],\n outlineSize: 1,\n proportional: true,\n });\n\n\n this.zoneTextDraws_.set(zone, textDraw);\n textDraw.displayForPlayer(player);\n } else {\n const textDraw = this.zoneTextDraws_.get(zone);\n textDraw.displayForPlayer(player);\n }\n\n this.updateTextDraw(zone);\n\n if (!isNaN(team) && team < 2) {\n this.playerTeam_.set(player, { zone: zone, team: team });\n return;\n }\n\n const teams = [...this.playerTeam_]\n .filter(item => item[1].zone === zone)\n .map(item => item[1].team);\n\n const amountOfRedTeam = teams.filter(item => item === RED_TEAM).length;\n const amountOfBlueTeam = teams.filter(item => item === BLUE_TEAM).length;\n\n const newTeam = amountOfRedTeam <= amountOfBlueTeam ? RED_TEAM : BLUE_TEAM;\n\n this.playerTeam_.set(player, { zone: zone, team: newTeam });\n }",
"function printTeam (a, b, c) {\n console.log(\"A baseball team consists of: \" + a + ', ' + b + ', ' + c);\n}",
"function getTeam(number) {\n\t\t\t\tfor (var i = 0; i < teams.length; i++) {\n\t\t\t\t\tif (teams[i].number === number) {\n\t\t\t\t\t\treturn teams[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvar newTeam = new Team(number);\n\t\t\t\tteams.push(newTeam);\n\t\t\t\treturn newTeam;\n\t\t\t}",
"function checkRequestPostTeam (req, res, next) {\r\n\tvar body = JSON.parse(JSON.stringify(defaultBodyPostTeam));\r\n\r\n\tbody.team.team_id = uuidv4();\r\n\tbody.team.team_valid = 0;\r\n\r\n\tbody.team_manager.participant_id = uuidv4();\r\n\tbody.team_manager.participant_payment = 0;//service_participant.participantPaymentValidityValueMatch.PAYMENT_NOT_RECEIVED.value;\r\n\tbody.team_manager.participant_medical_certificate_valid = 0;//service_participant.participantCertificateValidityValueMatch.MEDICAL_CERTIFICATE_NOT_RECEIVED.value;\r\n\r\n\tif (req.body.hasOwnProperty('team')) {\r\n\t\tif (req.body.team.hasOwnProperty('team_name')) {\r\n\t\t\tif (req.body.team.team_name) {\r\n\t\t\t\tbody.team.team_name = req.body.team.team_name;\r\n\t\t\t} else {\r\n\t\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t}\r\n\t\tif (req.body.team.hasOwnProperty('team_password')) {\r\n\t\t\tif (req.body.team.team_password) {\r\n\t\t\t\tbody.team.team_salt = uuidv4();\r\n\t\t\t\tbody.team.team_password = service_authentication.hashPassword(req.body.team.team_password, body.team.team_salt);\r\n\t\t\t} else {\r\n\t\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t}\r\n\t\tif (req.body.team.hasOwnProperty('team_category_id')) {\r\n\t\t\tbody.team.team_category_id = req.body.team.team_category_id;\r\n\t\t} else {\r\n\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t}\r\n\t\tif (req.body.team.hasOwnProperty('team_valid')) {\r\n\t\t\tif (req.body.team.team_valid>=0) {\r\n\t\t\t\tbody.team.team_valid = req.body.team.team_valid;\r\n\t\t\t} else {\r\n\t\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t\t}\r\n\t\t}\r\n\t} else {\r\n\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t}\r\n\tif (req.body.hasOwnProperty('team_manager')) {\r\n\t\tif (req.body.team_manager.hasOwnProperty('participant_name')) {\r\n\t\t\tif (req.body.team_manager.participant_name) {\r\n\t\t\t\tbody.team_manager.participant_name = req.body.team_manager.participant_name;\r\n\t\t\t} else {\r\n\t\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t}\r\n\t\tif (req.body.team_manager.hasOwnProperty('participant_surname')) {\r\n\t\t\tif (req.body.team_manager.participant_surname) {\r\n\t\t\t\tbody.team_manager.participant_surname = req.body.team_manager.participant_surname;\r\n\t\t\t} else {\r\n\t\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t}\r\n\t\tif (req.body.team_manager.hasOwnProperty('participant_birthdate')) {\r\n\t\t\tif (req.body.team_manager.participant_birthdate) {\r\n\t\t\t\tbody.team_manager.participant_birthdate = req.body.team_manager.participant_birthdate;\r\n\t\t\t} else {\r\n\t\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t}\r\n\t\tif (req.body.team_manager.hasOwnProperty('participant_telephone')) {\r\n\t\t\tif (req.body.team_manager.participant_telephone) {\r\n\t\t\t\tbody.team_manager.participant_telephone = req.body.team_manager.participant_telephone;\r\n\t\t\t} else {\r\n\t\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t}\r\n\t\tif (req.body.team_manager.hasOwnProperty('participant_email')) {\r\n\t\t\tif (req.body.team_manager.participant_email) {\r\n\t\t\t\tbody.team_manager.participant_email = req.body.team_manager.participant_email;\r\n\t\t\t} else {\r\n\t\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t}\r\n\t\tif (req.body.team_manager.hasOwnProperty('participant_student')) {\r\n\t\t\tif (req.body.team_manager.participant_student) {\r\n\t\t\t\tbody.team_manager.participant_student = req.body.team_manager.participant_student\r\n\t\t\t} else {\r\n\t\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (req.body.team_manager.hasOwnProperty('participant_medical_certificate')) {\r\n\t\t\tif (req.body.team_manager.participant_medical_certificate) {\r\n\t\t\t\tbody.team_manager.participant_medical_certificate = req.body.team_manager.participant_medical_certificate\r\n\t\t\t} else {\r\n\t\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (req.body.team_manager.hasOwnProperty('participant_medical_certificate_file')) {\r\n\t\t\tif (req.body.team_manager.participant_medical_certificate_file) {\r\n\t\t\t\tbody.team_manager.participant_medical_certificate_file = req.body.team_manager.participant_medical_certificate_file\r\n\t\t\t} else {\r\n\t\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (req.body.team_manager.hasOwnProperty('participant_tee_shirt_size')) {\r\n\t\t\tif (req.body.team_manager.participant_tee_shirt_size) {\r\n\t\t\t\tbody.team_manager.participant_tee_shirt_size = req.body.team_manager.participant_tee_shirt_size\r\n\t\t\t} else {\r\n\t\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (req.body.team_manager.hasOwnProperty('participant_comment')) {\r\n\t\t\tif (req.body.team_manager.participant_comment) {\r\n\t\t\t\tbody.team_manager.participant_comment = req.body.team_manager.participant_comment\r\n\t\t\t} else {\r\n\t\t\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t\t\t}\r\n\t\t}\r\n\t} else {\r\n\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t}\r\n\r\n\treturn {params: null, query: null, body: body};\r\n}",
"function makeTeams() {\n for (var i = 0; i < data.players.length; i++) {\n if (data.players[i].team_name === team1Name) {\n team1 = team1.concat(data.players[i]);\n } else {\n team2 = team2.concat(data.players[i]);\n }\n }\n}",
"function createPieces(team) {\n var row = 0;\n var column = 1;\n // Creates 12 pieces for the team\n if (team === 'red') {\n for (i = 0; i < 12; i++) {\n game.redTeam[i] = new Piece(team, i, row, column);\n };\n for (i = 0; i < 3; i++) {\n game.redTeam[i*4].row = i;\n game.redTeam[i*4 + 1].row = i;\n game.redTeam[i*4 + 2].row = i;\n game.redTeam[i*4 + 3].row = i;\n };\n var n = 0;\n for (i = 0; i < 12; i++) {\n if (isOdd(game.redTeam[i].row)) {\n game.redTeam[i].column = n;\n } else {\n game.redTeam[i].column = n + 1;\n };\n if (n < 6) {\n n = n + 2;\n } else {\n n = 0;\n };\n };\n } else if (team === 'white') {\n for (i = 0; i < 12; i++) {\n game.whiteTeam[i] = new Piece(team, i, row, column);\n };\n for (i = 0; i < 3; i++) {\n game.whiteTeam[i*4].row = 7 - i;\n game.whiteTeam[i*4 + 1].row = 7 - i;\n game.whiteTeam[i*4 + 2].row = 7 - i;\n game.whiteTeam[i*4 + 3].row = 7 - i;\n };\n var n = 0;\n for (i = 0; i < 12; i++) {\n if (isOdd(game.whiteTeam[i].row)) {\n game.whiteTeam[i].column = n;\n } else {\n game.whiteTeam[i].column = n + 1;\n };\n if (n < 6) {\n n = n + 2;\n } else {\n n = 0;\n };\n };\n }\n}",
"winningTeam() {\n if (Math.random() < 0.50) {\n return(nameWest);\n } else {\n return(nameEast);\n }\n }",
"function createTeams(arr, numberOfTeams) {\n let rest = arr.length % numberOfTeams,\n restUsed = rest,\n partLength = Math.floor(arr.length / numberOfTeams),\n result = [];\n\n for (let i = 0; i < arr.length; i += partLength) {\n let end = partLength + i,\n add = false;\n\n if (rest !== 0 && restUsed) {\n end++;\n restUsed--;\n add = true;\n }\n\n result.push(arr.slice(i, end));\n\n if (add) {\n i++;\n }\n }\n return result;\n}",
"function createTeam(evt, teamName) {\n var divId = \"teamDiv_\" + teamCounter + \"_0\";\n var listId = 'team_' + teamCounter + \"_0\";\n if (teamName == undefined) {\n teamName = \"Team \";\n\n //Add leading zero as requested in CodePlex ticket #695\n if (teamCounter < 10) {\n teamName += \"0\" + teamCounter;\n }\n else {\n teamName += teamCounter;\n }\n }\n var newContent = '<div style=\"display:none;\" id=\"' + divId + '\" class=\"TeamDiv\">' +\n '<input type=\"text\" class=\"TeamNameTextBox\" value=\"' + teamName + '\" />' +\n '<img class=\"RemoveTeamIcon\" src=\"/Content/images/delete_up.png\" alt=\"remove team\" title=\"remove team\" onclick=\"removeTeam(\\'' + divId + '\\')\" />' +\n '<ul id=\"' + listId + '\" class=\"TeamSortable\"></ul>' +\n '</div>';\n if (teamCounter % 3 == 0) {\n newContent += '<div style=\"clear:both;\"></div>';\n }\n $(\"#TeamsDiv\").append(newContent);\n $(\"#\" + listId).sortable({ connectWith: \".TeamSortable\" }).disableSelection();\n $(\"#\" + divId).fadeIn('slow');\n teamCounter++;\n return divId;\n}",
"function getDatabaseParameterPostTeamCreateTeam (params, query, body){\r\n\treturn body.team;\r\n}",
"function teamValidation() {\r\n //Setup team\r\n var team = $(\".team\");\r\n\r\n //Validate the team when we select\r\n team.change(function() {\r\n var teamSelect = $(this).val();\r\n\r\n //Make sure that it is in the teams array\r\n if($.inArray(teamSelect, teams) !== -1) {\r\n $(this).css({\"borderColor\": \"lime\"});\r\n if($(this).parent().is(\"div\")) {\r\n $(this).unwrap();\r\n $(this).siblings().remove();\r\n Global.enableButton($(\"#saveAll\"));\r\n }\r\n } else {\r\n //It isn't valid, create the tooltip, set the border color to red for failure and disable the save all button\r\n $(this).wrap(\"<div class='tooltip'>\");\r\n $(this).after(\"<span class='tooltipMessage'>Please select a valid team.</span>\");\r\n $(this).css({\"borderColor\": \"red\"});\r\n Global.disableButton($(\"#saveAll\"));\r\n }\r\n });\r\n }",
"function addNATeams(teamDropdown) {\n\t$(teamDropdown).append(createTeamOption('Team Solo Mid',TSMimg));\n\t$(teamDropdown).append(createTeamOption('Counter Logic Gaming',CLGimg));\n\t$(teamDropdown).append(createTeamOption('Cloud9 HyperX',C9img));\n\t$(teamDropdown).append(createTeamOption('XDG',XDGimg));\n\t$(teamDropdown).append(createTeamOption('Evil Geniuses',EGimg));\n\t$(teamDropdown).append(createTeamOption('Dignitas',DIGimg));\n\t$(teamDropdown).append(createTeamOption('Team Coast',CSTimg));\n\t$(teamDropdown).append(createTeamOption('Curse Gaming',CRSimg));\n\t$(teamDropdown).append(createTeamOption('LMQ',LMQimg));\n\t$(teamDropdown).append(createTeamOption('compLexity Gaming',COLimg));\n\t/* ADD OTHER TEAMS HERE */\n}",
"init_teams(teams)\n {\n console.log(teams);\n this.teams = {};\n // insert each team object in the teams array\n Object.keys(teams).forEach((t, idx) =>\n {\n // this.teams.push(new this.team_class(this, team_name, teams[team_name], idx));\n this.teams[teams[t][\"name\"]] = new this.team_class(this, teams[t][\"name\"], teams[t][\"score\"], idx, teams[t][\"color\"]);\n });\n }",
"hasTeams() {\n let has = false;\n this.entrants.forEach((entrant) => {\n if (entrant.team !== \"\") {\n has = true;\n }\n });\n return has;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update movie collection changes from local storage | function updateLocalStorage(){
localStorage.setItem("movie_collection", angular.toJson($scope.movieList));
} | [
"updateListMovies() {\n this.listMovie.current.state.movies = this.state.moviesFiltred;\n this.listMovie.current.forceUpdate();\n }",
"addMovieToLS(data) {\n const movies = this.getMovieFromLS()\n movies.push(data)\n localStorage.setItem('movies', JSON.stringify(movies))\n }",
"removeMovieFromLS(target) {\n const movies = this.getMovieFromLS()\n movies.forEach((movie, index) => {\n if (movie.name === target) {\n movies.splice(index, 1)\n }\n })\n localStorage.setItem('movies', JSON.stringify(movies))\n }",
"getMovieFromLS() {\n let movies\n if (localStorage.getItem('movies') === null) {\n movies = []\n } else {\n movies = JSON.parse(localStorage.getItem('movies'))\n }\n return movies\n }",
"function removeFromCollection(movieId) {\n\n // fetch the Collection first.\n let collectionName = document.getElementById('searchFilterText').textContent;\n let collectionId = null;\n\n let url = \"http://localhost:3000/userCollections?name=\" + collectionName;\n\n // Fetch Collection details\n httpSync(url, (responseText) => {\n let response = JSON.parse(responseText);\n let index = response[0].movies.indexOf(parseInt(movieId));\n collectionId = response[0].id;\n if (index > -1) {\n response[0].movies.splice(index, 1);\n }\n\n //Update the DB\n var url = 'http://localhost:3000/userCollections/' + collectionId;\n\n // create a Post Request\n var json = JSON.stringify(response[0]);\n httpPostOrPut(url, 'PUT', json);\n\n }, 'GET', null);\n\n // Update the Store\n //store.dispatch(setActionFilter(ActionFilters.SHOW_MOVIE_REMOVED));\n currentAction = ActionFilters.MOVIE_REMOVED;\n store.dispatch(removeMovieFromCollectionStore(collectionId, movieId));\n}",
"function deleteMovie() {\n\n let movieList = JSON.parse(sessionStorage.getItem(\"movieList\"));\n for (let i = 0; i < movieList.length; i++) {\n if (movieList[i].title == this.parentNode.id) {\n movieList.splice(i, 1);\n }\n }\n sessionStorage.setItem(\"movieList\", JSON.stringify(movieList));\n addMovies();\n}",
"displayMovieFromLS() {\n const movies = this.getMovieFromLS()\n movies.forEach(movie => {\n this.addMovieToUI(movie)\n })\n }",
"function checkWatchedVideos(title_content, image_url, video_url) {\n recently_watched_videos = JSON.parse(localStorage.getItem('watchedVideosArray'));\n\n if (recently_watched_videos.length == 0) {\n // ADD FIRST VIDEO TO JSON\n pushVideosToWatchedList(title_content, image_url, video_url);\n } else {\n // ADD MORE VIDEO TO JSON\n var isExistInWatched = false;\n var watchedVideoIndex = 0;\n $.each(recently_watched_videos, function(ind, obj_val) {\n watchedVideoIndex = ind + 1;\n if (obj_val.title === title_content && obj_val.image === image_url && obj_val.video === video_url) {\n isExistInWatched = true;\n console.log(\"Index number = \" + ind);\n recently_watched_videos.splice(ind, 1);\n }\n if (recently_watched_videos.length === watchedVideoIndex) {\n pushVideosToWatchedList(title_content, image_url, video_url);\n }\n });\n }\n}",
"function pushVideosToWatchedList(title_content, image_url, video_url) {\n recently_watched_videos.push({ title: title_content, image: image_url, video: video_url });\n localStorage.setItem('watchedVideosArray', JSON.stringify(recently_watched_videos));\n}",
"function changeMovie(index , movie){\n movieQueue[index]=movie;\n return movie;\n \n}",
"static getMovies() {\n let movies;\n if (localStorage.getItem('movies') === null) {\n movies = [];\n } else {\n movies = JSON.parse(localStorage.getItem('movies'));\n }\n return movies;\n }",
"function migrate() {\n migrateNowPlaying();\n migratePlaylist();\n }",
"pushFilmInFavoriteFilms(state, film) {\n state.favoriteFilms.push({\n id: film.id,\n title: film.title,\n poster: film.poster_path,\n });\n }",
"function updateArrays() {\n var storedHighScore = JSON.parse(localStorage.getItem(\"highScore\"));\n\n if (storedHighScore !== null) {\n highScore = storedHighScore;\n }\n\n var storedInitials = JSON.parse(localStorage.getItem(\"initials\"));\n\n if (storedInitials !== null) {\n initials = storedInitials;\n }\n}",
"function updateLocalStorage() {\n\t\t// Ensure they have local storage\n\t\tif(typeof(localStorage) == 'undefined') return;\n\n\t\t// Grab the stored maps\n\t\tldb.get('maps', function(storedMaps) {\n\t\t\tif(storedMaps == null) {\n\t\t\t\tstoredMaps = {};\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tstoredMaps = JSON.parse(storedMaps);\n\t\t\t\t} catch(e) {\n\t\t\t\t\tstoredMaps = {};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Store our map\n\t\t\tstoredMaps[window.activeMap.name] = {\n\t\t\t\tData: window.activeMap.Data,\n\t\t\t\tInfo: window.activeMap.Info\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Store into local storage\n\t\t\t\tldb.set('maps', JSON.stringify(storedMaps));\n\t\t\t} catch(e) {\n\t\t\t\talertify.error('FAILED TO SAVE MAP LOCALLY!');\n\t\t\t\talertify.error(e.message);\n\t\t\t}\n\t\t\t\n\t\t});\n\t}",
"function update_current_download_videos_path(newPath){ \n if (update_json_path_validity(newPath) == \"valid path\") {\n const current_download_videos = FileSystem.readFileSync(newPath);\n currentDownloadVideos = JSON.parse(current_download_videos);\n current_download_videos_path = newPath;\n return \"currentDownloadVideos updated\";\n } \n}",
"function updateStoredState() {\r\n localStorage.setItem('displayedProducts', JSON.stringify(displayedProducts));\r\n localStorage.setItem('currentVoteCount', JSON.stringify(currentVoteCount));\r\n}",
"updateSimilarMovies(item, genresName) {\n\t\tthis.props.selectMovie(item, genresName);\n\n\t\tconst { id } = this.props.match.params;\n\t\tconst url = `https://api.themoviedb.org/3/tv/${id}/similar?api_key=c93f9215f2085cf5f8aa18a05afa9861`;\n\n\t\taxios(url)\n\t\t\t.then(res => {\n\t\t\t\tthis.setState({ similarMovies: res.data.results });\n\t\t\t})\n\t\t\t.catch(err => console.log(err.message));\n\t}",
"savingChange (movie) {\n this.props.dispatch({ type: 'EDIT_MOVIE', payload: movie });\n this.props.dispatch({type: 'SET_MOOVIE', payload: movie});\n this.props.history.push(`/details/${this.state.id}`);\n\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
copy a key content | function copyKey(target, key) {
for (var i = 2; i < arguments.length; i++) {
if (key in arguments[i]) {
target[key] = arguments[i][key];
return;
}
}
} | [
"function copyTextToClipboard() {\n const textarea = document.createElement(\"textarea\");\n textarea.innerHTML = Key;\n textarea.style.display = \"hidden\";\n document.body.appendChild(textarea);\n textarea.focus();\n textarea.select();\n try {\n document.execCommand(\"copy\");\n document.body.removeChild(textarea);\n generatePopUp(\"Key Copied\")\n } catch (err) {\n generatePopUp(`some error happened: ${err}`);\n }\n\n /*other way for copying in clipboard -->\n\n navigator.clipboard\n .writeText(text)\n .then(() => {\n generatePopUp(\"Key Copied\")\n })\n .catch((err) => generatePopUp(`some error happened: ${err}`)); */\n}",
"function addObject(copy, key, value) {\n\tcopy[key] = value;\n\treturn copy[key];\n}",
"function add (copy, key, value) {\n if (copy instanceof Array) {\n copy.push(value)\n return copy[copy.length - 1]\n }\n else if (copy instanceof Object) {\n copy[key] = value\n return copy[key]\n }\n }",
"function CopySongData() {\n document.querySelector('#songDataHolder').value = JSON.stringify(songData, null, 2);\n document.querySelector('#songDataHolder').select();\n document.execCommand('copy');\n}",
"changeKeyFromChord(chord=this.lastChord) {\n // common key modulation\n let keys = this.chordToKeys[chord.toString()]\n\n if (!keys) {\n // chord doesn't have key, eg. A#m\n return\n }\n\n keys = keys.filter(key => key.name() != this.keySignature.name())\n if (!keys.length) {\n // some chords are only in one key\n return\n }\n\n let newKey = keys[this.generator.int() % keys.length]\n\n // console.warn(`Going from ${this.keySignature.name()} to ${newKey.name()}`)\n this.keySignature = newKey\n this.scale = this.keySignature.defaultScale()\n this.chords = null\n }",
"function copyObject(first, second) {\n\tclearObject(second);\n\t\n\tfor(var k in first) {\n\t\tsecond[k] = first[k];\n\t}\n}",
"set surround_key(string){ \n this.key_prefix = string\n this.key_suffix = string\n }",
"function assign(dst, src) {\n Object.keys(src).forEach(function forKey(key) {\n dst[key] = src[key];\n });\n return dst;\n}",
"function copy_json() {\n\tdocument.getElementById(\"json_box\").select();\n\tdocument.execCommand(\"copy\");\n}",
"function saveKey(id, key) {\n savedKeys[id] = key;\n}",
"function KeyPaste(evt)\r\n{\r\n var nKeyCode;\r\n nKeyCode = GetKeyCode(evt);\r\n switch (nKeyCode)\r\n {\r\n case 13: //enter\r\n Paste();\r\n break;\r\n default:\r\n //do nothing\r\n break;\r\n }\r\n}",
"generateOriginalFile () {\n return _.map(this.original_file.split('\\n'), line => {\n if ( line.match(/^\\s*$/) ) return line\n let m = line.match(this.config_line_re)\n if ( !m ) return line\n let line_key = m[0]\n let line_value = m[1]\n debug('found key \"%s\" value \"%s\" in line', line_key, line_value, line)\n if ( this.has(key) ) {\n let value = this.get(key)\n debug('replaced key \"%s\" value \"%s\" with new value \"%s\"', line_key, line_value, value)\n let new_line = this.generateLine(key, value)\n debug('new line', new_line)\n }\n })\n }",
"function expandkey(key56) {\n\tvar key64 = new Buffer(8);\n\n\tkey64[0] = key56[0] & 0xFE;\n\tkey64[1] = key56[0] << 7 & 0xFF | key56[1] >> 1;\n\tkey64[2] = key56[1] << 6 & 0xFF | key56[2] >> 2;\n\tkey64[3] = key56[2] << 5 & 0xFF | key56[3] >> 3;\n\tkey64[4] = key56[3] << 4 & 0xFF | key56[4] >> 4;\n\tkey64[5] = key56[4] << 3 & 0xFF | key56[5] >> 5;\n\tkey64[6] = key56[5] << 2 & 0xFF | key56[6] >> 6;\n\tkey64[7] = key56[6] << 1 & 0xFF;\n\n\treturn key64;\n}",
"function set_data(dest, key, data, context)\n{\n // If there is a transformation function, call the function.\n if (typeof context.transform == 'function') {\n dest = dest || {}\n data = context.transform(data, context.src, dest, context.srckey, context.destkey)\n }\n\n // See if data is null and there is a default\n if (typeof context.default !== 'undefined' && (data == null || typeof data == 'undefined')) {\n // There is a default function, call the function to set the default\n if (typeof context.default == 'function') {\n dest = dest || {}\n data = context.default(context.src, context.srckey, dest, context.destkey)\n }\n // The default is a specific value\n else\n data = context.default\n }\n\n // Set the object to the data if it is not undefined\n if (typeof data !== 'undefined' && key && key.name) {\n // Set the data if the data is not null, or if the 'allow nulls' key is set, or if there is a default (in the case of default=null, make sure to write this out)\n if (data !== null || key.nulls || (typeof context.default !== 'undefined' && context.default == null)) {\n dest = dest || {}\n dest[key.name] = data\n }\n }\n\n // Return the dest variable back to the caller.\n return dest\n}",
"function copyToClipboard() {\n const el = document.createElement('textarea');\n el.value = event.target.getAttribute('copy-data');\n el.setAttribute('readonly', '');\n el.style.position = 'absolute';\n el.style.left = '-9999px';\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n}",
"encodeKey(key) {\n return `${key.hostname}+${key.rrtype}`\n }",
"function addArray(copy, key, value) {\n\tcopy.push(value);\n\treturn copy[copy.length - 1];\n}",
"static #cloneObjectExceptKeys(src = {}, excludeKeys = []) {\n const cloned = {}\n for (const key in src) {\n if (!excludeKeys.includes(key)) {\n cloned[key] = src[key]\n }\n }\n\n return cloned\n }",
"function updateKey(keyboardKey,pianoKey){\n //update Array key\n //write to file system\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the max height or width value from the given slice | function getMax(slice, prop) {
var max = 0;
slice.each(function () {
var size = $(this)[prop]();
if (size > max) max = size;
});
return max;
} | [
"function largestRectangle(h) {\n\n let stack = [];\n let mx = -1;\n stack.push(0);\n for (let i = 1; i < h.length; i++) {\n let last_index = stack.slice(-1)[0];\n let stack_h = h[last_index];\n let curr_h = h[i];\n if (curr_h > stack_h || stack.length == 0) {\n stack.push(i);\n }\n else {\n let anchor = i;\n while (curr_h <= stack_h && stack.length > 0) {\n last_index = stack.pop();\n let area = stack_h * (anchor - last_index);\n mx = Math.max(area, mx);\n stack_h = h[last_index];\n }\n }\n }\n\n let anchor = h.length;\n let curr_h = h[h.length - 1];\n let stack_h = h[stack.slice(-1)[0]];\n while (curr_h >= stack_h && stack.length > 0) {\n let last_index = stack.pop();\n stack_h = h[last_index];\n let area = stack_h * (anchor - last_index);\n mx = Math.max(area, mx);\n\n }\n\n return mx;\n}",
"getMaxRect(x, y, aspect) {\n return Rect.getMax(Math.abs(this.locked[0] - x), Math.abs(this.locked[1] - y), aspect)\n }",
"function findMaxArea(heights) {\n //0, 1, \n let max = 0;\n \n for (let i = 0; i <= heights.length; i++){//x=0 \n for (let j = i; j < heights.length; j++){\n let height = height[j] < height[i] ? height[j] :height[i] ;//8 \n \n let width = Math.abs(j - i); //1\n \n \n if (max < height * width){ \n max = height * width;//8\n }\n \n }\n }\n \n return max;\n \n }",
"get inputMaxHeight(){\n var {footer, header, maxHeight} = this.props;\n var inputMaxHeight = maxHeight;\n if(footer) inputMaxHeight-=1;\n if(header) inputMaxHeight-=1;\n return inputMaxHeight;\n }",
"_getMaxPointSize() {\n const e = this.encoders.size;\n if (e.constant) {\n return e(null);\n } else {\n return /** @type {number[]} */ (e.scale.range()).reduce((a, b) =>\n Math.max(a, b)\n );\n }\n }",
"function getHeight() {\n return maxy + 1;\n }",
"static getMaxHeight() { \n var result = Math.max(MainUtil.findAllRooms().map(room => (room.memory.console && room.memory.console.height)));\n return result || 10;\n }",
"function find_dimensions()\n{\n numColsToCut= parseInt(NumberofColumns);\n numRowsToCut= parseInt(NumberofRows);\n \n widthOfOnePiece=Target_width/numColsToCut;\n heightOfOnePiece=Target_height/numRowsToCut; \n}",
"function max(){return colorScale.domain()[2];}",
"function GetItemRectSize(out = new ImVec2()) {\r\n return bind.GetItemRectSize(out);\r\n }",
"function get_max_height_divs(elements)\n{\n return Math.max.apply(null, elements.map(function ()\n {\n //~ alert($(this).attr(\"id\") + \" \" + $(this).height());\n return $(this).height();\n }).get());\n}",
"getMaxLevel(capLevelIndex) {\r\n let result = 0,\r\n i,\r\n level,\r\n mWidth = this.mediaWidth,\r\n mHeight = this.mediaHeight,\r\n lWidth = 0,\r\n lHeight = 0;\r\n\r\n for (i = 0; i <= capLevelIndex; i++) {\r\n level = this.levels[i];\r\n if (this.isLevelRestricted(i)) {\r\n break;\r\n }\r\n result = i;\r\n lWidth = level.width;\r\n lHeight = level.height;\r\n if (mWidth <= lWidth || mHeight <= lHeight) {\r\n break;\r\n }\r\n }\r\n return result;\r\n }",
"get tileSize() {}",
"getRectSize() {\n\t\treturn {\n\t\t\t'width':this.rectArea.width / this.horizontalPeriod.count - this.rectMargin / 2,\n\t\t\t'height':this.rectArea.height / this.verticalPeriod.count - this.rectMargin / 2\n\t\t}\n\t}",
"function getHeight() {\n return 2;\n }",
"get height() {\n this._logService.debug(\"gsDiggThumbnailDTO.height[get]\");\n return this._height;\n }",
"function findMaximumValue(array) {\n\n}",
"function getBubbleSizeRange(values) {\n var sizeMinMax = [];\n sizeMinMax = d3.extent(values, function (obj) {\n return obj['size']\n });\n if (sizeMinMax[0] == sizeMinMax[1]) {\n sizeMinMax = [sizeMinMax[0] * .9, sizeMinMax[0] * 1.1];\n } else {\n sizeMinMax = [sizeMinMax[0], sizeMinMax[1]];\n }\n return sizeMinMax;\n}",
"get maxHeight() {\n\t\tlet maxHeight = 0, height;\n\n\t\tfor (let i = 0; i < this.count; i++) {\n\t\t\tif (this.cache[i]) {\n\t\t\t\theight = this.cache[i];\n\t\t\t} else {\n\t\t\t\theight = this.traverse(i);\n\t\t\t\t\n\t\t\t\tthis.cache[i] = height;\n\t\t\t\tthis.cache[this.tree[i]] = height - 1;\n\t\t\t}\n\n\t\t\tmaxHeight = Math.max(maxHeight, height);\n\t\t}\n\n\t\treturn maxHeight;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update chart data on measure change | function measureChange() {
measure = document.getElementById(measureName + "-select").value;
updateColorAxis();
chart.series[0].setData(get_data());
} | [
"function measureChange() {\n measure = document.getElementById(measureName + \"-select\").value;\n updateData();\n }",
"function updateChartValue(){\r\n myChart.data.datasets[0].data[0] = sumNo;\r\n myChart.data.datasets[0].data[1] = sumYes;\r\n myChart.update()\r\n}",
"componentDidUpdate() {\n this.buildChart();\n }",
"function updateChart() {\n const extent = d3.event.selection;\n \n if(!extent) {\n if (!idleTimeout) return idleTimeout = setTimeout(idled, 350); // This allows to wait a little bit\n x.domain(d3.extent(computedData, function(d) {\n return d.dateObj }))\n } else {\n x.domain([ x.invert(extent[0]), x.invert(extent[1]) ])\n areaChart.select(\".brush\").call(brush.move, null)\n }\n\n // Update axis and area position\n xAxis.transition().duration(1000).call(d3.axisBottom(x).ticks(6))\n areaChart\n .selectAll(\"path\")\n .transition().duration(1000)\n .attr(\"d\", area);\n \n }",
"handleSubChartPropertyChange(key, value) {\n const state = this.state;\n state.configuration.charts[0][key] = value;\n this.setState(state);\n this.props.onConfigurationChange(state.configuration);\n }",
"onChartRender() {\n this.updateProxyOverlays();\n }",
"componentDidUpdate() {\n this.updateChart(this.props);\n }",
"function dataChange(stat) {\n updatePieGraph(dataset, stat);\n\n // update municipality map\n selection.each(function() {\n let score = response[0][this.getAttribute('cbs')][stat];\n d3.select(this).attr(\"fill\", mapColours[score]);\n });\n\n // update district map\n selection2.each(function() {\n let areaCode = this.getAttribute('id');\n let score = response[1][areaCode][stat] || 0;\n d3.select(this).attr(\"fill\", mapColours[score]);\n });\n\n currentStat = stat;\n }",
"function onRefresh3() {\n\tconfig3.data.datasets.forEach(function (dataset) {\n\t\tdataset.data.push({\n\t\t\tx: Date.now(),\n\t\t\ty: powerGenerate_real_2\n\t\t});\n\t});\n}",
"setMeasureActive() {\n this.measureActive = true;\n this.profile.measure.clearMeasure();\n this.profile.measure.setMeasureActive();\n }",
"function updateLoSideChart() {\r\n\t\t\t\t\thandleLoSideTrack(2);\r\n\t\t\t\t\tupdateLoSideChart2();\r\n\t\t\t\t}",
"function calculateData() {\n\tvar percentage = 0;\n\ttotalData = 0;\n\thighestData = 0;\n\t//Calculate Total of Chart Value\n\tfor (var i = 0; i < Object.size(chartData); i++) {\n\t\ttotalData += parseInt(chartData[i]['value']);\n\t\tif (highestData < parseInt(chartData[i]['value']))\n\t\t\thighestData = parseInt(chartData[i]['value']);\n\t}\n\t//Calculate Percentage of Chart Value\n\tfor (var i = 0; i < Object.size(chartData); i++) {\n\t\tpercentage = (chartData[i]['value'] / totalData) * 100;\n\t\tchartData[i]['percentage'] = percentage.toFixed(2);\n\t}\n}",
"function trend_periodically_update_graph () {\n\t$.ajax({\n\t\ttype: 'GET',\n\t\turl: '/dashboard/trend_data',\n\t\tdataType: 'json',\n\t\tsuccess: trend_generate_graph\n\t});\n}",
"function updateTotals(data)\n{\n\tif (data.length != 0) {\n\tvar totalDataLength = totalChart.datasets[0].points.length-1;\n\ttotalChart.datasets[0].points[totalDataLength].value = data[data.length-1].total;\n\tif (totalDataLength-1 > labelLength) {\n\t\tvar label = totalChart.datasets[0].points[totalDataLength].label;\n\t\tvar eventCount = 0;\n\t\tfor (var title in events) {\n\t\t\teventAtCurrentLabel = null;\n\t\t\tvar ev = events[title];\n\t\t\tfor (var t in ev) {\n\t\t\t\tif (ev[t].start <= label && ev[t].end >= label) {\n\t\t\t\t\teventAtCurrentLabel = -10-(eventCount*10);\n\t\t\t\t}\n\t\t\t}\n\t\t\ttotalChart.datasets[eventCount+1].points[totalDataLength].value = eventAtCurrentLabel;\n\t\t\teventCount++;\n\t\t}\n\t}\n\ttotalChart.update();\n}\n}",
"function updateConditionsTrackChart2(){\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar temp = getDpsActive();\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar myData = \t[{\r\n\t\t\t\t\t\t\t\t\t\ttype: \"bar\",\r\n\t\t\t\t\t\t\t\t\t\tshowInLegend: true,\r\n\t\t\t\t\t\t\t\t\t\tcolor: \"blue\",\r\n\t\t\t\t\t\t\t\t\t\tname: \"Active\",\r\n\t\t\t\t\t\t\t\t\t\tdataPoints: dpsActive\r\n\t\t\t\t\t\t\t\t\t}, {\r\n\t\t\t\t\t\t\t\t\t\ttype: \"bar\",\r\n\t\t\t\t\t\t\t\t\t\tshowInLegend: true,\r\n\t\t\t\t\t\t\t\t\t\tcolor: \"green\",\r\n\t\t\t\t\t\t\t\t\t\tname: \"winCount\",\r\n\t\t\t\t\t\t\t\t\t\tdataPoints: [\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond1.winCount, label: \"cond1\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond2.winCount, label: \"cond2\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond3.winCount, label: \"cond3\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond4.winCount, label: \"cond4\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond5.winCount, label: \"cond5\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond6.winCount, label: \"cond6\"}\r\n\t\t\t\t\t\t\t\t\t\t]\r\n\t\t\t\t\t\t\t\t\t},{\r\n\t\t\t\t\t\t\t\t\t\ttype: \"bar\",\r\n\t\t\t\t\t\t\t\t\t\tshowInLegend: true,\r\n\t\t\t\t\t\t\t\t\t\tcolor: \"red\",\r\n\t\t\t\t\t\t\t\t\t\tname: \"lossCount\",\r\n\t\t\t\t\t\t\t\t\t\tdataPoints: [\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond1.lossCount, label: \"cond1\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond2.lossCount, label: \"cond2\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond3.lossCount, label: \"cond3\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond4.lossCount, label: \"cond4\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond5.lossCount, label: \"cond5\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond6.lossCount, label: \"cond6\"}\r\n\t\t\t\t\t\t\t\t\t\t]\r\n\t\t\t\t\t\t\t\t\t}];\r\n\t\t\t\r\n\t\t\t\t\t// Options to display value on top of bars\r\n\t\t\t\t\tvar myoption = {\r\n\t\t\t\t\t\ttooltips: {\r\n\t\t\t\t\t\t\tenabled: true\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\thover: {\r\n\t\t\t\t\t\t\tanimationDuration: 1\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\tanimation: {\r\n\t\t\t\t\t\tduration: 1,\r\n\t\t\t\t\t\tonComplete: function () {\r\n\t\t\t\t\t\t\tvar chartInstance = this.chart,\r\n\t\t\t\t\t\t\t\tctx = chartInstance.ctx;\r\n\t\t\t\t\t\t\t\tctx.textAlign = 'center';\r\n\t\t\t\t\t\t\t\tctx.fillStyle = \"rgba(0, 0, 0, 1)\";\r\n\t\t\t\t\t\t\t\tctx.textBaseline = 'bottom';\r\n\t\t\t\t\t\t\t\tthis.data.datasets.forEach(function (dataset, i) {\r\n\t\t\t\t\t\t\t\t\tvar meta = chartInstance.controller.getDatasetMeta(i);\r\n\t\t\t\t\t\t\t\t\tmeta.data.forEach(function (bar, index) {\r\n\t\t\t\t\t\t\t\t\t\tvar data = dataset.data[index];\r\n\t\t\t\t\t\t\t\t\t\tctx.fillText(data, bar._model.x, bar._model.y - 5);\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t};\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tconditionsTrackChart = new CanvasJS.Chart(\"chartContainer5\", {\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\tbackgroundColor: \"black\",\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\ttitle: {\r\n\t\t\t\t\t\t\t\t\t\ttext: \"Conditions Success Rate\",\r\n\t\t\t\t\t\t\t\t\t\tfontColor: \"white\"\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\taxisX: {\r\n\t\t\t\t\t\t\t\t\t\t//title: \"Conditions\",\r\n\t\t\t\t\t\t\t\t\t\ttitleFontColor: \"green\",\r\n\t\t\t\t\t\t\t\t\t\tlabelFontColor: \"white\"\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\taxisY: {\r\n\t\t\t\t\t\t\t\t\t\ttitle: \"Count\",\r\n\t\t\t\t\t\t\t\t\t\ttitleFontColor: \"red\",\r\n\t\t\t\t\t\t\t\t\t\tlabelFontColor: \"white\"\r\n\t\t\t\t\t\t\t\t\t\t//interval: 10\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\tlegend: {\r\n\t\t\t\t\t\t\t\t\t\tcursor:\"pointer\",\r\n\t\t\t\t\t\t\t\t\t\titemclick : toggleDataSeries\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\ttoolTip: {\r\n\t\t\t\t\t\t\t\t\t\tshared: true,\r\n\t\t\t\t\t\t\t\t\t\tcontent: toolTipFormatter\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\tdata: myData, \t// Chart data\r\n\t\t\t\t\t\t\t\t\toptions: myoption \t// Chart Options [This is optional paramenter use to add some extra things in the chart].\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\tconditionsTrackChart.render();\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t }",
"function addDataToCharts(data)\n{\n\t// Probably a better way to do this\n\tif (data.length != 0) {\n\tif (data[data.length-1].timekey.substring(11,16) == totalChart.datasets[0].points[totalChart.datasets[0].points.length-1].label)\n\t{\n\t\t/*console.log(\"den siste labelen er : \" + totalChart.datasets[0].points[totalChart.datasets[0].points.length-1].label)*/\n\t\ttotalChart.update();\n\t}\n\telse\n\t{\n\t\ttotalChart.addData([data[data.length-1].total],data[data.length-1].timekey.substring(11,16));\n\t\tvar totalDataLength = totalChart.datasets[0].points.length-2;\n\t\ttotalChart.datasets[0].points[totalDataLength].value = data[data.length-2].total;\n\t\ttotalChart.update();\n\t\t/*totalChart.removeData();*/\n\t}\n}\n\t//FABFIVE: try to update labels automatically when new data arrives.\n\t//updateLabels(data);\n}",
"function updateHiSideChart() {\r\n\t\t\t\t\thandleHiSideTrack(2);\r\n\t\t\t\t\tupdateHiSideChart2();\r\n\t\t\t\t}",
"function updateBidChart() {\r\n\t\t\t\t\tupdateBidChart2();\r\n\t\t\t\t}",
"function updateView() {\n \n $.when ($.getJSON(BASE_URL + \"/rides/count/per_month\", perYear), \n ).then(updateChart);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when client changes the team. | function teamNameChanged(event, teamName){
self.teamName = teamName;
} | [
"acceptServerChanges() {\n this.props.updateCode(this.props.serverCode, this.props.projectName);\n this.props.startStreamingEditor();\n }",
"function goToTeamSelection(){\n clientValuesFactory.setActiveWindow(windowViews.selectTeam);\n }",
"changeName(newName) {\n this.name = newName;\n updateTeam(this._id, \"name\", this.name);\n }",
"setGroupTeams(state, teams) {\n\t\tstate.teams = teams\n\t}",
"_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 OnJoinTeamPressed() {\n // Get the team id asscociated with the team button that was pressed\n var teamId = $.GetContextPanel().GetAttributeInt(\"team_id\", -1);\n\n // Request to join the team of the button that was pressed\n Game.PlayerJoinTeam(teamId);\n}",
"setPlayerTeam(player, zone, team = undefined) {\n const location = DeathMatchLocation.getById(zone);\n if (!location.hasTeams)\n return;\n\n if (!this.teamScore_.has(zone))\n this.teamScore_.set(zone, new DeathMatchTeamScore());\n\n if (!this.zoneTextDraws_.has(zone)) {\n this.zoneTextDraws_.set(zone, -1);\n const textDraw = new TextDraw({\n position: [482, 311],\n text: '_',\n\n color: Color.fromNumberRGBA(-1),\n shadowColor: Color.fromRGBA(0, 0, 0, 255),\n font: 2,\n letterSize: [0.33, 1.5],\n outlineSize: 1,\n proportional: true,\n });\n\n\n this.zoneTextDraws_.set(zone, textDraw);\n textDraw.displayForPlayer(player);\n } else {\n const textDraw = this.zoneTextDraws_.get(zone);\n textDraw.displayForPlayer(player);\n }\n\n this.updateTextDraw(zone);\n\n if (!isNaN(team) && team < 2) {\n this.playerTeam_.set(player, { zone: zone, team: team });\n return;\n }\n\n const teams = [...this.playerTeam_]\n .filter(item => item[1].zone === zone)\n .map(item => item[1].team);\n\n const amountOfRedTeam = teams.filter(item => item === RED_TEAM).length;\n const amountOfBlueTeam = teams.filter(item => item === BLUE_TEAM).length;\n\n const newTeam = amountOfRedTeam <= amountOfBlueTeam ? RED_TEAM : BLUE_TEAM;\n\n this.playerTeam_.set(player, { zone: zone, team: newTeam });\n }",
"static async processEdit(ctx) {\n if (ctx.state.auth.user.Role != 'admin') {\n ctx.flash = { _error: 'Team management requires admin privileges' };\n return ctx.response.redirect('/login'+ctx.request.url);\n }\n\n const body = ctx.request.body;\n\n // update team details\n if ('Name' in body) {\n try {\n\n const validation = { // back-end validation matching HTML5 validation\n Name: 'required',\n };\n\n if (validationErrors(body, validation)) {\n throw new Error(validationErrors(body, validation));\n }\n\n await Team.update(ctx.params.id, body);\n\n // return to list of members\n ctx.response.redirect('/teams');\n\n } catch (e) {\n // stay on same page to report error (with current filled fields)\n ctx.flash = { formdata: body, _error: e.message };\n ctx.response.redirect(ctx.request.url);\n }\n }\n\n // add member to team\n if ('add-member' in body) {\n const values = {\n TeamId: ctx.params.id,\n MemberId: body['add-member'],\n JoinedOn: new Date().toISOString().replace('T', ' ').split('.')[0],\n };\n\n try {\n\n const id = await TeamMember.insert(values);\n ctx.response.set('X-Insert-Id', id); // for integration tests\n\n // stay on same page showing new team member\n ctx.response.redirect(ctx.request.url);\n\n } catch (e) {\n // stay on same page to report error\n ctx.flash = { formdata: body, _error: e.message };\n ctx.response.redirect(ctx.request.url);\n }\n }\n\n // remove member from team\n if ('del-member' in body) {\n try {\n\n await TeamMember.delete(body['del-member']);\n // stay on same page showing new members list\n ctx.response.redirect(ctx.request.url);\n\n } catch (e) {\n // stay on same page to report error\n ctx.flash = { _error: e.message };\n ctx.response.redirect(ctx.request.url);\n }\n }\n }",
"function teamDataSavedListener () {\n debug('match data saved, resolving state promise')\n module.exports.internal.teamDataSavedPromiseResolver()\n}",
"function change_player( current_player )\n{\n\tdimPlayer(current_player);\n\tplayerGo();\n\tvar next_player = players.players[players.current];\n\thighlightPlayer(next_player);\n}",
"projectChanged() {\n const oldSI = this.getSimulationInterface();\n this.checkForDepositLibrary();\n this.treeController.reloadTree();\n this.workspaceController.resetEditors();\n const newSI = this.getSimulationInterface();\n oldSI.transferCallbacks(newSI);\n }",
"changeYear(newYear){\n this.yearReleased = newYear;\n }",
"function setCurrentGame(key) {\n console.log(\"in setCurrentGame...\");\n console.log(\"was given key: \" + key);\n\n vm.currentGame = getGame(key);\n\n //if player is on a team in the game then set it\n if (vm.playerName === vm.currentGame.player1) {\n vm.playerTeam = \"x\";\n } else if (vm.playerName === vm.currentGame.player2) {\n vm.playerTeam = \"o\";\n }\n\n }",
"function changeTeams() {\n\tvar gameNum = $('#time option:selected').data('game');\n\tvar week = $('#week').val();\n\t$('#gameNum').val(GAMES[week-1][gameNum].game);\n\t$('#homeTeam').val(GAMES[week-1][gameNum].home);\n\t$('#awayTeam').val(GAMES[week-1][gameNum].away);\n\t$('#homeScore').val(GAMES[week-1][gameNum].homeScore);\n\t$('#awayScore').val(GAMES[week-1][gameNum].awayScore);\n}",
"_suiteChange() {\n if (DEBUG) {\n console.log('[*] ' + _name + ':_suiteChange ---');\n }\n\n this.setState({\n suites: getSuitesState()\n });\n }",
"function goToTeamPoints(){\n clientValuesFactory.setActiveWindow(windowViews.teamPoints);\n }",
"changeTurn() {\n this.setupFog(false);\n super.changeTurn();\n }",
"async updateMatchStatus(team, margin, status) {\n // Let other team chase\n if (status == \"endOfInnings\") {\n await getPrompt(\"End of Innings !\", \"end\");\n this.endInnings();\n await this.initializeInnings();\n document.querySelector(`#${this.battingTeam.id}-tab`).click(); // Switch scoreboard tab\n\n // End game\n } else {\n let msg = \"\";\n if (status == \"Draw\") {\n msg = \"Match Draw\";\n } else {\n msg = `${team.name} WON by ${margin} ${status}`;\n }\n await getPrompt(msg, \"win\");\n endMatch();\n }\n }",
"disbandTeam(teamName) {\n this.entrants.forEach((entrant) => {\n if (entrant.team === teamName) {\n entrant.team = \"\";\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turns projection depth coding on/off | function toggleDepthCoding(enabled) {
$('.proj-x, .proj-y, .proj-z').attr('depthCoded', enabled ? 1.0 : 0.0);
} | [
"function deOptimize() {\n\n\t\t// There is already no optimization occuring\n\t\tif ( params.level == 0 ) {\n\n\t\t\treturn\n\n\t\t// enable FXAA\n\t\t} else if ( params.level == 1 ) {\n\n\t\t\trenderer.setPixelRatio( window.devicePixelRatio );\n\t\t\tparams.level = 0 ;\n\n\t\t// set pixel ratio to the default device pixel ratio\n\t\t} else if ( params.level == 2 ) {\n\n\t\t\tparams.level = 1 ;\n\n\t\t// enable shadows on dynamic objects\n\t\t} else if ( params.level == 3 ) {\n\n\t\t\trenderer.shadowMap.enabled = true;\n\n\t\t\tassetManager.toggleCharacterShadows( true );\n\n\t \tparams.level = 2 ;\n\n\t\t} else if ( params.level == 4 ) {\n\n\t\t\tcamera.far = 23.5 ;\n\t\t\tcamera.updateProjectionMatrix();\n\n\t\t\tparams.level = 3 ;\n\n\t\t};\n\n\t}",
"setDepths() {\n this.r3a1_char_north.setDepth(50);\n this.r3a1_char_south.setDepth(50);\n this.r3a1_char_west.setDepth(50);\n this.r3a1_char_east.setDepth(50);\n this.r3a1_floor.setDepth(0);\n this.r3a1_exitDoor.setDepth(1);\n //this.r3a1_hole.setDepth(1);\n this.r3a1_Activity.setDepth(1);\n this.character.setDepth(50);\n this.r3a1_E_KeyImg.setDepth(49);\n this.r3a1_map.setDepth(100);\n this.r3a1_notebook.setDepth(100);\n this.r3a1_help_menu.setDepth(100);\n this.r3a1_redX.setDepth(49);\n this.r3a1_greenCheck.setDepth(49);\n this.profile.setDepth(0);\n }",
"function optimize() {\n\n\t\t// Will disable FXAA\n\t\tif ( params.level == 0 ) {\n\n\t\t\trenderer.setPixelRatio( 1 );\n\t\t\tparams.level = 1 ;\n\n\t\t// set pixel ratio to 1, which has effect mostly on smartphones\n\t\t} else if ( params.level == 1 ) {\n\n\t\t\tparams.level = 2 ;\n\n\t\t// Remove the shadow from the dynamic objects,\n\t\t// and stop rendering shadows dynamically\n\t\t} else if ( params.level == 2 ) {\n\n\t\t\tassetManager.toggleCharacterShadows( false );\n\n\t\t\tsetTimeout( ()=> {\n\t\t\t\trenderer.shadowMap.enabled = false;\n\t\t\t}, 0);\n\n\t \tparams.level = 3 ;\n\n\t\t} else if ( params.level == 3 ) {\n\n\t\t\tcamera.far = 11.5 ;\n\t\t\tcamera.updateProjectionMatrix();\n\n\t\t\tparams.level = 4 ;\n\n\t\t};\n\n\t}",
"function toggle_postcodes_visibility() {\r\n // Toggle node\r\n for (let i = 0; i < nodes.length; i++) {\r\n if (this.value == nodes[i].location.split(\" \")[0]) {\r\n if (map.hasLayer(nodes[i].layer)) {\r\n nodes[i].layer.removeFrom(map);\r\n nodes[i].label.removeFrom(map);\r\n } else {\r\n nodes[i].layer.addTo(map);\r\n }\r\n }\r\n }\r\n\r\n // Toggle edges\r\n for (let i = 0; i < edges.length; i++) {\r\n if (this.value == edges[i].start_node.location.split(\" \")[0]) {\r\n if (map.hasLayer(edges[i].layer)) {\r\n edges[i].layer.removeFrom(map);\r\n edges[i].label.removeFrom(map);\r\n } else {\r\n edges[i].layer.addTo(map);\r\n }\r\n }\r\n }\r\n}",
"function activateDrawMode() {\n \"use strict\";\n inDrawMode = true;\n inEraseMode = !inDrawMode;\n console.log(\"activated DrawMode\");\n}",
"function prerender() {\n if (tileEngine.layers) {\n tileEngine.layers.map(function (layer) {\n layer._d = false;\n layerMap[layer.name] = layer;\n\n if (layer.visible !== false) {\n tileEngine._r(layer, offscreenContext);\n }\n });\n }\n }",
"function ProjectionOverlay() {\n }",
"function DepthRenderer(scene,type,camera){if(type===void 0){type=BABYLON.Engine.TEXTURETYPE_FLOAT;}if(camera===void 0){camera=null;}var _this=this;/**\n * Specifiess that the depth renderer will only be used within\n * the camera it is created for.\n * This can help forcing its rendering during the camera processing.\n */this.useOnlyInActiveCamera=false;this._scene=scene;// Register the G Buffer component to the scene.\nvar component=scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);if(!component){component=new BABYLON.DepthRendererSceneComponent(scene);scene._addComponent(component);}this._camera=camera;var engine=scene.getEngine();// Render target\nthis._depthMap=new BABYLON.RenderTargetTexture(\"depthMap\",{width:engine.getRenderWidth(),height:engine.getRenderHeight()},this._scene,false,true,type);this._depthMap.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE;this._depthMap.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE;this._depthMap.refreshRate=1;this._depthMap.renderParticles=false;this._depthMap.renderList=null;// Camera to get depth map from to support multiple concurrent cameras\nthis._depthMap.activeCamera=this._camera;this._depthMap.ignoreCameraViewport=true;this._depthMap.useCameraPostProcesses=false;// set default depth value to 1.0 (far away)\nthis._depthMap.onClearObservable.add(function(engine){engine.clear(new BABYLON.Color4(1.0,1.0,1.0,1.0),true,true,true);});// Custom render function\nvar renderSubMesh=function renderSubMesh(subMesh){var mesh=subMesh.getRenderingMesh();var scene=_this._scene;var engine=scene.getEngine();var material=subMesh.getMaterial();if(!material){return;}// Culling and reverse (right handed system)\nengine.setState(material.backFaceCulling,0,false,scene.useRightHandedSystem);// Managing instances\nvar batch=mesh._getInstancesRenderList(subMesh._id);if(batch.mustReturn){return;}var hardwareInstancedRendering=engine.getCaps().instancedArrays&&batch.visibleInstances[subMesh._id]!==null;var camera=_this._camera||scene.activeCamera;if(_this.isReady(subMesh,hardwareInstancedRendering)&&camera){engine.enableEffect(_this._effect);mesh._bind(subMesh,_this._effect,BABYLON.Material.TriangleFillMode);_this._effect.setMatrix(\"viewProjection\",scene.getTransformMatrix());_this._effect.setFloat2(\"depthValues\",camera.minZ,camera.minZ+camera.maxZ);// Alpha test\nif(material&&material.needAlphaTesting()){var alphaTexture=material.getAlphaTestTexture();if(alphaTexture){_this._effect.setTexture(\"diffuseSampler\",alphaTexture);_this._effect.setMatrix(\"diffuseMatrix\",alphaTexture.getTextureMatrix());}}// Bones\nif(mesh.useBones&&mesh.computeBonesUsingShaders&&mesh.skeleton){_this._effect.setMatrices(\"mBones\",mesh.skeleton.getTransformMatrices(mesh));}// Draw\nmesh._processRendering(subMesh,_this._effect,BABYLON.Material.TriangleFillMode,batch,hardwareInstancedRendering,function(isInstance,world){return _this._effect.setMatrix(\"world\",world);});}};this._depthMap.customRenderFunction=function(opaqueSubMeshes,alphaTestSubMeshes,transparentSubMeshes,depthOnlySubMeshes){var index;if(depthOnlySubMeshes.length){engine.setColorWrite(false);for(index=0;index<depthOnlySubMeshes.length;index++){renderSubMesh(depthOnlySubMeshes.data[index]);}engine.setColorWrite(true);}for(index=0;index<opaqueSubMeshes.length;index++){renderSubMesh(opaqueSubMeshes.data[index]);}for(index=0;index<alphaTestSubMeshes.length;index++){renderSubMesh(alphaTestSubMeshes.data[index]);}};}",
"setWireframe() {\n this.scene.traverse( ( child ) => {\n if ( child.isMesh ) {\n child.material.wireframe = !this.props.data.wireframe;\n }\n });\n }",
"turnOff() {\n\t\tthis.lightMap.makeDarkness();\n\t}",
"function configureProjectiveMat() {\n var projectionMat = mat4.create();\n var screenRatio = gl.drawingBufferWidth / gl.drawingBufferHeight;\n mat4.perspective(projectionMat, glMatrix.toRadian(45), screenRatio, 1, 100);\n gl.uniformMatrix4fv(ctx.uProjectionMatId , false , projectionMat);\n}",
"toggleProjectionMatrixHandInPlace() {\n const m = this._m;\n m[8] *= -1;\n m[9] *= -1;\n m[10] *= -1;\n m[11] *= -1;\n this._markAsUpdated();\n }",
"static set DefaultRaycastLayers(value) {}",
"setSurroundModeToStereo() {\n this._setSurroundMode(\"s_stereo\");\n }",
"toggleCamera() {\n this.controls.enable = false;\n if (this.camera === this.orthoCamera) {\n this.camera = this.perspCamera;\n this.controls = this.perspControls;\n }\n else {\n this.camera = this.orthoCamera;\n this.controls = this.orthoControls;\n }\n this.controls.enable = true;\n this.controls.reset();\n }",
"function ToggleDraw(){\n self.canvas.isDrawingMode = !self.canvas.isDrawingMode;\n }",
"function enablePanning() {\n panningDisabled = false;\n }",
"function createDepthMaterial() {\n\n\t\t\t// create main/default override material first\n\t\t\tvar depthShader = zvs.NormalsShader;\n\t\t\t_depthMaterial = zvs.createShaderMaterial(depthShader);\n\t\t\t_depthMaterial.blending = THREE.NoBlending;\n\t\t\t_depthMaterial.packedNormals = true;\n\t\t\t// normally the color target will write to the z-buffer, so depth does not need to do so.\n\t\t\t_depthMaterial.depthWrite = false;\n\n\t\t\t// Flags to define alternative depth material variants.\n\t\t\tvar DepthMaterialFlags = {\n\t\t\t\tNoCutPlanes: 0x1, // Without cutplanes to render section caps\n\t\t\t\tInstancing: 0x2, // Using instancing\n\t\t\t\tCount: 0x4\n\t\t\t};\n\n\t\t\t// create special-case material variants\n\t\t\tvar variants = [];\n\t\t\tvariants[0] = null; // index 0 = null (=use default depthMaterial)\n\t\t\tfor(var i = 1; i < DepthMaterialFlags.Count; i++) {\n\t\t\t\tvar variant = _depthMaterial.clone();\n\n\t\t\t\t// cutplanes: with/without\n\t\t\t\tif(i & DepthMaterialFlags.NoCutPlanes) {\n\t\t\t\t\tvariant.cutPlanes = null;\n\t\t\t\t\tvariant.blending = THREE.NoBlending;\n\t\t\t\t\tvariant.packedNormals = true;\n\t\t\t\t\tvariant.doNotCut = true; // make sure that cutplanes keep null (see MaterialManager.addMaterialNonHDR)\n\t\t\t\t}\n\n\t\t\t\t// instancing yes/no\n\t\t\t\tif(i & DepthMaterialFlags.Instancing) {\n\t\t\t\t\tvariant.useInstancing = true;\n\t\t\t\t}\n\n\t\t\t\tvariants[i] = variant;\n\t\t\t}\n\n\t\t\t_depthMaterial.variants = variants;\n\n\t\t\t// Define a custom override function: It decides for a shape\n\t\t\t// which depthMaterial variant will be used by WebGLRenderer.\n\t\t\t_depthMaterial.getCustomOverrideMaterial = function(shapeMaterial) {\n\n\t\t\t\t// If the original shape material has no cutplanes, use the alternative\n\t\t\t\t// _noCutplanesMaterial for normal/depth.\n\t\t\t\tvar noCutPlanes = (!shapeMaterial || !shapeMaterial.cutplanes || shapeMaterial.cutplanes.length == 0);\n\n\t\t\t\t// If the original material applies the instance transform, depthMaterial must do this as well.\n\t\t\t\tvar instanced = shapeMaterial.useInstancing;\n\n\t\t\t\t// return the appropriate material variant\n\t\t\t\tvar index =\n\t\t\t\t\t(noCutPlanes ? DepthMaterialFlags.NoCutPlanes : 0) |\n\t\t\t\t\t(instanced ? DepthMaterialFlags.Instancing : 0);\n\t\t\t\treturn this.variants[index];\n\t\t\t};\n\t\t}",
"set resolutionMode(value) {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParsercluster_name. | visitCluster_name(ctx) {
return this.visitChildren(ctx);
} | [
"visitCreate_cluster(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitAlter_cluster(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitCluster_index_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"_createNodes() {\n // Test all statements for leadership\n // If they are leaders, create node\n for (const $stmt of Query.searchFromInclusive(this.#jp, \"statement\")) {\n if (CfgUtils.isLeader($stmt)) {\n\n if (this.#splitInstList && CfgUtils.getNodeType($stmt) === CfgNodeType.INST_LIST) {\n this._getOrAddNode($stmt, true, CfgNodeType.INST_LIST);\n\n for (const $right of $stmt.siblingsRight) {\n if (!CfgUtils.isLeader($right))\n this._getOrAddNode($right, true, CfgNodeType.INST_LIST);\n else \n break;\n }\n }\n else\n this._getOrAddNode($stmt, true);\n }\n }\n\n // Special case: if starting node is a statement and a graph node was not created for it (e.g. creating a graph starting from an arbitrary statement),\n // create one with the type INST_LIST\n if (\n this.#jp.instanceOf(\"statement\") &&\n this.#nodes.get(this.#jp.astId) === undefined\n ) {\n this._getOrAddNode(this.#jp, true, CfgNodeType.INST_LIST);\n }\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}",
"visitNew_partition_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitParallel_clause(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}",
"visitProcedure_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitGlobal_stmt(ctx) {\r\n console.log(\"visitGlobal_stmt\");\r\n let globallist = [];\r\n for (var i = 0; i < ctx.NAME().length; i++) {\r\n globallist.push(this.visit(ctx.NAME(i)));\r\n }\r\n return { type: \"GlobalStatement\", globallist: globallist };\r\n }",
"visitOracle_namespace(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSchema_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function parseData(apiData)\n{\n intervals = apiData[1].children;\n intervals[currentInterval].children[1].children.slice(0,3).forEach(function(cluster,index){\n var name = cluster.name.split('cluster ')[1];\n setTimeout(function(){\n new Cluster(name,cluster,currentInterval);\n },index*2000);\n\n });\n}",
"visitLocal_xmlindex_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitIndex_partitioning_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitQuery_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSubpartition_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDatabase_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when a videa is clicked and saves the videoId in SessionStorage | function videoClick(clickedVideo){
console.log('video es'+clickedVideo);
sessionStorage.setItem('videoid', clickedVideo);
} | [
"function video_click(e) {\n\t//console.log(e);\n\t//console.log(this);\n\tif (this.paused == true) {\n\t\tthis.play();\n\t} else {\n\t\tthis.pause();\n\t}\n}",
"function addVideo(e) {\n const id = (e.target.id !== 'addVideo')\n ? e.target.value\n : domCache['videoId'].value;\n const found = state.videos.filter(video => id === video.id);\n\n if (e && e.target.id === 'addVideo' && found.length > 0) {\n log('add video', `not added; id ${id} already in list`);\n return;\n }\n\n const func = (!state.player)\n ? setPlayer\n : loadVideo;\n\n func(id).then((loaded) => {\n // video is loaded, will be updated in loaded event.\n }).catch(function(error) {\n // the video did not load.\n log(`${func.name} called`, `video id ${id} not loaded.`);\n });\n }",
"function openVideo(video_id) {\n $(modal.replace(\"{VIDEO_ID}\", video_id)).appendTo('body').modal();\n}",
"function onclick_add(e, video_id) {\n var video = video_map[video_id];\n if (typeof video == \"undefined\") {\n console.log(\"Failed to add video with ID \" + video_id);\n }\n else {\n flixstack_api.add_to_stack(video.title, video_id, video.image, function(data, textStatus) {\n update_link(video_id, true);\n });\n }\n\n e.preventDefault();\n e.stopPropagation();\n return false;\n}",
"onListItemClick(clickedVideo) {\n\n this.setState({\n // swap the player to the clicked video\n player: clickedVideo,\n });\n }",
"function onclick_watched(e, video_id) {\n flixstack_api.mark_as_watched(video_id, function(data, textStatus) {\n update_link(video_id, false);\n }); \n\n e.preventDefault();\n e.stopPropagation();\n return false;\n}",
"function displayVideo() {\n\tvar correctVideoLink = questionID.videoLink;\n\t//console.log(\"value of src = \" + correctVideoLink);\n\t$(\"#answer-media\").attr(\"src\", correctVideoLink);\n}",
"chooseVideo: function (newVideo){\n this.setState({\n src: VIDEOS[newVideo]\n });\n }",
"function search_for_video() {\n\n\t// console.log(\"search clicked\\n\");\n\n\tvar new_link = search_bar_input.value;\n\tif (new_link.length !== 0) {\n\n\t\tvar data_sections = new_link.split(\"&\");\n\t\t// console.log(data_sections);\n\n\t\tvar time = \"\";\n\t\tvar playlist = \"\";\n\t\tvar playlist_index = \"\";\n\n\t\tfor (var i = 0; i < data_sections.length; i++) {\n\n\t\t\tif (data_sections[i].includes(\"v=\")) {\n\n\t\t\t\tnew_link = data_sections[i].split(\"v=\").pop();\n\n\t\t\t} else if (data_sections[i].includes(\"t=\")\n\t\t\t\t&& !data_sections[i].includes(\"list=\")) {\n\n\t\t\t\ttime = data_sections[i].split(\"t=\").pop();\n\n\t\t\t} else if (data_sections[i].includes(\"list=\")) {\n\n\t\t\t\tplaylist = data_sections[i].split(\"list=\").pop();\n\n\t\t\t} else if (data_sections[i].includes(\"index=\")) {\n\n\t\t\t\tplaylist_index = data_sections[i].split(\"index=\").pop();\n\n\t\t\t}\n\n\t\t}\n\n\t\tyt_player.loadVideoById({videoId:new_link});\n\n\t\twhile(note_logs.firstChild) {\n\t\t\tnote_logs.removeChild(note_logs.firstChild);\n\t\t}\n\n\t\t// console.log(\"new video\\n\");\n\t\tsearch_bar_input.value = \"\";\n\t\twrite_note_textarea.value = \"\";\n\n\t\tpopulateNotes(new_link);\n\t\tsetSessionVideoId(new_link);\n\n\t}\n\n}",
"function openVideo() {\r\n\t\tTitanium.Platform.openURL(movie.trailerUrl);\r\n\t}",
"function goToDetails(id){\n localStorage.setItem(\"movieId\",`${id}`); // Save the id in localStorage\n window.location.href = \"movieDetails.html\"; // Go to new page\n }",
"function videoToggle() {\n // set video state.\n setVideoState(!videoState);\n\n // toggle the video track.\n toggleTracks(userStream.getVideoTracks());\n\n // send update to all user, to update the status.\n sendUpdate(!videoState, audioState);\n }",
"function playVideo(videoData) {\n document.querySelector(\"#modalYT div div div div iframe\").src = \"https://www.youtube.com/embed/\" + videoData.youtubeId;\n document.querySelector(\"#watch-video-detail\").href = \"pages/watch.html?yid=\" + videoData.youtubeId;\n videoDataToSend.data.attributes = videoData;\n if (!$(\"#modalYT\").hasClass(\"show\")) {\n setTimeout(function () {\n $(\"#modalYT\").modal('show');\n }, 100);\n }\n}",
"function video_doubleclick(e) {\n\te.preventDefault();\n\tthis.currentTime = 0;\n\tthis.play();\n}",
"function categoryClick(clicked_id) {\n sessionStorage.setItem(\"category\", clicked_id);\n location.href = '../wordbank/words.html';\n}",
"function toggleUserVideoVote(videoId)\n\t{\n var videoIndex = indexById(videoId);\n if (videoIndex == -1)\n {\n // Couldn't find video in list\n console.log(\"Error: attempted to vote on non-existent video [\" + videoId + \"]\");\n return;\n }\n \n var user = getUserById(userId);\n if (user)\n { \n if (!user.votedVideo || user.votedVideo.length == 0)\n {\n if (!videoVotes[videoId])\n {\n videoVotes[videoId] = 1;\n }\n else\n {\n videoVotes[videoId] += 1;\n }\n \n user.votedVideo = videoId;\n }\n else if (user.votedVideo == videoId)\n {\n videoVotes[videoId] -= 1;\n user.votedVideo = \"\";\n }\n }\n \n if (videoVotes[videoId] == 0)\n {\n // Remove video from vote list\n delete videoVotes[videoId];\n }\n \n var voteCount = videoVotes[videoId] ? videoVotes[videoId] : 0; \n \n // Tell everyone about the vote change\n io.sockets.emit('videoVoteSync', videoIndex, voteCount);\n }",
"click_raceMeetingNewsVideoTab(){\n this.raceMeetingNewsVideo_Tab.waitForExist();\n this.raceMeetingNewsVideo_Tab.click();\n }",
"function getVideoId(videojsVideo) {\n if (useVideoJs() && videojsVideo) {\n var id = videojsVideo.Q ? videojsVideo.Q : videojsVideo.U;\n return id;\n } else {\n return videojsVideo;\n }\n }",
"function updatevideostatus(){\n \n \n if(video.paused)\n {\n \n video.play();\n }\n else{\n video.pause();\n }\n\n \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is called when the split view changes based on the umbvariantcontent | function splitViewChanged() {
//send an event downwards
$scope.$broadcast("editors.content.splitViewChanged", { editors: vm.editors });
} | [
"function _handleSplitViewVertical() {\n MainViewManager.setLayoutScheme(1, 2);\n }",
"function closeSplitView(editorIndex) {\n // TODO: hacking animation states - these should hopefully be easier to do when we upgrade angular\n var editor = vm.editors[editorIndex];\n editor.loading = true;\n editor.collapsed = true;\n $timeout(function () {\n vm.editors.splice(editorIndex, 1);\n //remove variant from open variants\n vm.openVariants.splice(editorIndex, 1);\n //update the current culture to reflect the last open variant (closing the split view corresponds to selecting the other variant)\n $location.search(\"cculture\", vm.openVariants[0]);\n splitViewChanged();\n }, 400);\n }",
"onSplitClick(event) {\n /* istanbul ignore next */\n if (this.disabled) {\n this.visible = false\n return\n }\n this.$emit(EVENT_NAME_CLICK, event)\n }",
"function setActiveCulture() {\n // set the active variant\n var activeVariant = null;\n _.each(vm.content.variants, function (v) {\n if (v.language && v.language.culture === vm.culture) {\n v.active = true;\n activeVariant = v;\n }\n else {\n v.active = false;\n }\n });\n if (!activeVariant) {\n // Set the first variant to active if we can't find it.\n // If the content item is invariant, then only one item exists in the array.\n vm.content.variants[0].active = true;\n activeVariant = vm.content.variants[0];\n }\n\n insertVariantEditor(0, initVariant(activeVariant, 0));\n\n if (vm.editors.length > 1) {\n //now re-sync any other editor content (i.e. if split view is open)\n for (var s = 1; s < vm.editors.length; s++) {\n //get the variant from the scope model\n var variant = _.find(vm.content.variants, function (v) {\n return v.language.culture === vm.editors[s].content.language.culture;\n });\n vm.editors[s].content = initVariant(variant, s);\n }\n }\n\n }",
"_verticalSplitStyle() {\n this.$containerEl.find('.te-md-container').removeClass('te-preview-style-tab');\n this.$containerEl.find('.te-md-container').addClass('te-preview-style-vertical');\n }",
"function afterChange() {\n\n\t\t\t// Make current page inactive\n\t\t\tcurrentContentPage.classList.remove('active');\n\t\t\thelper.setData(currentContentPage, 'currentcontent', false);\n\n\t\t\t// Set the title\n\t\t\telems.dashboardContentTitle.innerHTML = helper.getData(newPage, 'title');\n\n\t\t\tdocument.title = `${pageTitleBase} - ${helper.getData(newPage, 'title')}`;\n\t\t\tcallback();\n\t\t}",
"toggleSplitTracks() {\n this.layout.split_tracks = !this.layout.split_tracks;\n if (this.parent.legend && !this.layout.always_hide_legend) {\n this.parent.layout.margin.bottom = 5 + (this.layout.split_tracks ? 0 : this.parent.legend.layout.height + 5);\n }\n this.render();\n return this;\n }",
"contentChanged(prev, next) {\n if (this.proxy instanceof HTMLOptionElement) {\n this.proxy.textContent = this.textContent;\n }\n this.$emit(\"contentchange\", null, { bubbles: true });\n }",
"childrenChanged() {\n if (true === this.adjustGroupWhenChildrenChange) {\n this.adjustChildrenVertically();\n this.adjustChildrenHorizontally();\n }\n }",
"_updateTitleTab() {\n var self = this;\n super._updateTitleTab();\n if (_.isUndefined(self.m_sceneMime))\n return;\n $(Elements.BLOCK_SUBPROPERTIES_TITLE).text(self.m_config[self.m_sceneMime].tabTitle);\n }",
"function SelectedProcessChanged(){\n \n GetCurrentProcessFromCombo();\n \n LoadTaskArray();\n \n _curSelectedTask = null;\n \n LoadSLDiagram();\n \n ShowTaskPanel(false);\n \n ShowProcessProperties();\n}",
"updateDivContent() {\n var server = getServer(this.serverKey);\n\n if(this.type == 'status') {\n this.#updateStatusContent(server);\n }\n\n if(this.type == 'queue') {\n this.#updateQueueContent(server);\n }\n\n if(this.type == 'controls') {\n this.#updateControlsContent();\n }\n }",
"restoreViewsSize(location, node, orientation, widthScale, heightScale) {\r\n if (!isGridBranchNode(node)) {\r\n return;\r\n }\r\n const scale = orientation === Orientation.VERTICAL ? heightScale : widthScale;\r\n for (let i = 0; i < node.children.length; i++) {\r\n const child = node.children[i];\r\n const childLocation = [...location, i];\r\n if (i < node.children.length - 1) {\r\n const size = orientation === Orientation.VERTICAL ? child.box.height : child.box.width;\r\n this.gridview.resizeView(childLocation, Math.floor(size * scale));\r\n }\r\n this.restoreViewsSize(childLocation, child, orthogonal(orientation), widthScale, heightScale);\r\n }\r\n }",
"updateSplitTrackAxis(categories) {\n const legend_axis = this.layout.track_split_legend_to_y_axis ? `y${this.layout.track_split_legend_to_y_axis}` : false;\n if (this.layout.split_tracks) {\n const tracks = +categories.length || 0;\n const track_height = +this.layout.track_height || 0;\n const track_spacing = 2 * (+this.layout.bounding_box_padding || 0) + (+this.layout.track_vertical_spacing || 0);\n const target_height = (tracks * track_height) + ((tracks - 1) * track_spacing);\n this.parent.scaleHeightToData(target_height);\n if (legend_axis && this.parent.legend) {\n this.parent.legend.hide();\n this.parent.layout.axes[legend_axis] = {\n render: true,\n ticks: [],\n range: {\n start: (target_height - (this.layout.track_height / 2)),\n end: (this.layout.track_height / 2),\n },\n };\n // There is a very tight coupling between the display directives: each legend item must identify a key\n // field for unique tracks. (Typically this is `state_id`, the same key field used to assign unique colors)\n // The list of unique keys corresponds to the order along the y-axis\n this.layout.legend.forEach((element) => {\n const key = element[this.layout.track_split_field];\n let track = categories.findIndex((item) => item === key);\n if (track !== -1) {\n if (this.layout.track_split_order === 'DESC') {\n track = Math.abs(track - tracks - 1);\n }\n this.parent.layout.axes[legend_axis].ticks.push({\n y: track - 1,\n text: element.label,\n });\n }\n });\n this.layout.y_axis = {\n axis: this.layout.track_split_legend_to_y_axis,\n floor: 1,\n ceiling: tracks,\n };\n }\n // This will trigger a re-render\n this.parent_plot.positionPanels();\n } else {\n if (legend_axis && this.parent.legend) {\n if (!this.layout.always_hide_legend) {\n this.parent.legend.show();\n }\n this.parent.layout.axes[legend_axis] = { render: false };\n this.parent.render();\n }\n }\n return this;\n }",
"function detect() {\n // Get the active content\n const active = getActive(data, settings);\n\n // if there's no active content, deactivate and bail\n if (!active) {\n if (current) {\n deactivate(current, settings);\n current = null;\n }\n return;\n }\n\n // If the active content is the one currently active, do nothing\n if (current && active.content === current.content) return;\n\n // Deactivate the current content and activate the new content\n deactivate(current, settings);\n activate(active, settings);\n\n // Update the currently active content\n current = active;\n }",
"function needSplitPageForPlan()//page 5 split page base on rider\n{\n \n \n isNeedSplit = \"NO\";//split data\n appendPage('page5','PDS/pds2HTML/PDSTwo_ENG_Page5.html');\n isNeedSplit = \"YES\";\n appendPage('page5b','PDS/pds2HTML/PDSTwo_ENG_Page5b.html');\n loadInterfacePage();//to check to hide some division\n \n \n}",
"function _updateUIStates() {\n var spriteIndex,\n ICON_CLASSES = [\"splitview-icon-none\", \"splitview-icon-vertical\", \"splitview-icon-horizontal\"],\n layoutScheme = MainViewManager.getLayoutScheme();\n\n if (layoutScheme.columns > 1) {\n spriteIndex = 1;\n } else if (layoutScheme.rows > 1) {\n spriteIndex = 2;\n } else {\n spriteIndex = 0;\n }\n\n // SplitView Icon\n $splitViewMenu.removeClass(ICON_CLASSES.join(\" \"))\n .addClass(ICON_CLASSES[spriteIndex]);\n\n // SplitView Menu\n _cmdSplitNone.setChecked(spriteIndex === 0);\n _cmdSplitVertical.setChecked(spriteIndex === 1);\n _cmdSplitHorizontal.setChecked(spriteIndex === 2);\n\n // Options icon\n _updateWorkingSetState();\n }",
"function initContentmanagment()\r\n{\r\n\t_carouselResponseId = 0;\r\n\t_emptyBreadcrumbContent = $(BREADCRUM_ID).html()\r\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}",
"function optionViewLoaded() {\r\n disableDataUpdate();\r\n LoadingBar.hide();\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
change background color of bars | function changeBgColorOfBar(i, color) {
bars[i].style.backgroundColor = color;
} | [
"function highlightBar(bar) {\n bar.fillColor = \"rgba(186,0,0,0.1)\";\n bar.strokeColor = \"rgba(186,0,0,0.5)\";\n bar.highlightStroke = \"rgba(208,0,0,0.5)\";\n bar.highlightFill = \"rgba(186,0,0,0.05)\";\n}",
"function barColor(progress) {\n var intCol = interpolateColor(lowColor, medColor, progress*2);\n if(progress > .5){\n intCol = interpolateColor(intCol, highColor, (1-progress)*2);\n }\n return intCol;\n}",
"function resetAllBarColors() {\n for(var i = 0; i < categoryIdentifiers.length; i++) {\n setBarColorAtIndex(i, barColors[i]);\n }\n }",
"function renderBarChart() {\n var i, j, p, a, x, y, w, h, len;\n\n if (opts.orient === \"horiz\") {\n rotate();\n }\n\n drawAxis();\n\n ctx.lineWidth = opts.stroke || 1;\n ctx.lineJoin = \"miter\";\n\n len = sets[0].length;\n\n // TODO fix right pad\n for (i = 0; i < sets.length; i++) {\n for (j = 0; j < len; j++) {\n p = 1;\n a = rotated ? height : width;\n w = ((a / len) / sets.length) - ((p / sets.length) * i) - 1;\n x = (p / 2) + getXForIndex(j, len + 1) + (w * i) + 1;\n y = getYForValue(sets[i][j]);\n h = y - getYForValue(0) || 1;\n\n if (isStacked()) {\n // TODO account for negative and positive values in same stack\n w = (a / len) - 2;\n x = getXForIndex(j, len + 1);\n y = getYForValue(sumY(sets.slice(0, i + 1), j));\n }\n\n drawRect(x, y, w, h, getColorForIndex(i));\n }\n }\n }",
"barMethod() {\n const wide = Math.abs(this.props.qual.score / 10.0).toString() + \"vw\";\n const color = this.props.qual.color;\n let style1 = {\n width: wide,\n backgroundColor: color,\n paddingTop: \"0.3vw\",\n paddingBottom: \"0.3vw\"\n };\n\n let style3 = {\n marginLeft: \"6vw\"\n };\n\n let style4 = {\n marginRight: \"1vw\"\n };\n\n let right = {\n borderRight: \"1px dashed\",\n borderLeftStyle: \"hidden\",\n borderTopStyle: \"hidden\",\n borderBottomRightStyle: \"dashed\",\n borderRightColor: \"black\",\n color: \"white\"\n };\n\n let left = {\n borderLeft: \" 1px dashed\",\n borderRightStyle: \"hidden\",\n borderTopStyle: \"hidden\",\n borderBottomLeftStyle: \"dashed\",\n borderLeftColor: \"black\",\n color: \"white\"\n };\n\n if (this.props.qual.score > 0) {\n return (\n <div className=\"dot-line\" style={style3}>\n <div style={right}>|</div>\n <div className=\"bar\" style={style1} />\n </div>\n );\n }\n return (\n <div className=\"dot-line\" style={style4}>\n <div className=\"bar\" style={style1} />\n <div style={left}>|</div>\n </div>\n );\n }",
"get barParts() {\n return this.barFill ? 'bar' : 'bar bar-zero';\n }",
"drawBarsRemoveOld(){\n }",
"updateBars(data) {\n\t\t/* Pixel color */\n\t\tlet colorBar = this.updateBar(data, \"color\", d3.select(\".colorbar\"), this.totalBars);\n\t\tif (colorBar) colorBar.style(\"fill\", (d, i) => {return d3.rgb(d.color.red,d.color.blue,d.color.green);});\n\n\t\t/* Pixel render time */\n\t\tlet timeBar = this.updateBar(data, \"time\", d3.select(\".timebar\"), this.totalBars);\n\t\tvar timeColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_render_time, this.rawData.max_render_time])\n .range(['black','white']);\n\t\tif (timeBar) timeBar.style(\"fill\", (d) => {return timeColor(d.time);});\n\n\t\t/* Total secondary rays */\n\t\tlet secondaryRayBar = this.updateBar(data, \"branches\", d3.select(\".branchesbar\"), this.totalBars);\n\t\tvar srColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_secondary_rays, this.rawData.max_secondary_rays])\n .range(['black','white']);\n\t\tif (secondaryRayBar) secondaryRayBar.style(\"fill\", (d) => {return srColor(d.branches);});\n\n\t\t/* Total samples */\n\t\tlet samplesBar = this.updateBar(data, \"samples\", d3.select(\".samplesbar\"), this.totalBars);\n\t\tvar scColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_sample_count, this.rawData.max_sample_count])\n .range(['black','white']);\n\t\tif (samplesBar) samplesBar.style(\"fill\", (d) => {return scColor(d.samples);});\n\n\t\t/* Pixel depth */\n\t\tlet depthBar = this.updateBar(data, \"depth\", d3.select(\".depthbar\"), this.totalBars);\n\t\tvar dColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_depth, this.rawData.max_depth])\n .range(['black','white']);\n\t\tif (depthBar) depthBar.style(\"fill\", (d) => {return dColor(d.depth);});\n\n\t\t/* Pixel variance */\n\t\tlet varianceBar = this.updateBar(data, \"variances\", d3.select(\".variancebar\"), this.totalBars);\n\t\tvar vColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_variance, this.rawData.max_variance])\n .range(['black','white']);\n\t\tif (varianceBar) varianceBar.style(\"fill\", (d) => {return vColor(d.variance);});\n\n\t\t/* Ray Box interections */\n\t\tlet boxBar = this.updateBar(data, \"boxIntersections\", d3.select(\".boxIntersections\"), this.totalBars);\n\t\tvar vColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_box_intersections, this.rawData.max_box_intersections])\n .range(['black','white']);\n\t\tif (boxBar) boxBar.style(\"fill\", (d) => {return vColor(d.boxIntersections);});\n\n\t\t/* Ray Obj interections */\n\t\tlet objBar = this.updateBar(data, \"objIntersections\", d3.select(\".objIntersections\"), this.totalBars);\n\t\tvar vColor = d3.scaleLinear()\n\t\t\t.domain([this.rawData.min_primitive_intersections, this.rawData.max_primitive_intersections])\n .range(['black','white']);\n\t\tif (objBar) objBar.style(\"fill\", (d) => {return vColor(d.objIntersections);});\n\n\t\t/* Selectable bars */\n\t\tlet selectableBar = this.updateSelectable(data, d3.select(\".selectableBar\"))\n\t}",
"function getBars(){\n for(var i = 0; i < dataset.length; i++){\n let height = getHeight(highNumberForYAxis, max, dataset[i]);\n let width = dataset.length > 2 ? (highNumberForXAxis - lowNumberForXAxis) / dataset.length - barPadding : 70;\n let x = (lowNumberForXAxis + barPadding) + rectangles.length * (highNumberForXAxis - lowNumberForXAxis - 5) / dataset.length;\n let y = highNumberForYAxis - height;\n rectangles.push(<Rect key={rectangles.length} x={x} y={y} width={width} height={height} fill={'rgb(23,153,173)'} />)\n }\n }",
"function getColor() {\n randomcolor = Math.floor(Math.random() * colors.length);\n quotesBkg.style.backgroundColor = colors[randomcolor];\n // topbar.style.backgroundColor = colors[randomcolor];\n}",
"function drawUpdateBar(){\n\t\t\td3.select(\"#bar-cover #bar-chart\").selectAll(\"svg\").remove();\n\t\t\tdrawBar();\n\t\t}",
"function histogramRenderBar(params, api) {\n var yValue = api.value(2);\n var start = api.coord([api.value(0), yValue]);\n var size = api.size([api.value(1) - api.value(0), yValue]);\n var style = api.style();\n\n return {\n type: 'rect',\n shape: {\n x: start[0] + 1,\n y: start[1],\n width: size[0] - 2,\n height: size[1]\n },\n style: style\n };\n }",
"function refreshSwatch() {\nvar coloredSlider = $( \"#coloredSlider\" ).slider( \"value\" ),\ncurrentColor = getTheColor( coloredSlider );\nstrokeStyle = currentColor;\n\n$( \"#coloredSlider .ui-state-default, .ui-widget-content .ui-state-default\" ).css( \"background-color\", currentColor );\n}",
"function getBarColor(status) {\n switch (status.toLowerCase()) {\n case 'failed':\n return 'red';\n case 'skipped':\n case 'incomplete':\n return 'grey';\n case 'passed':\n return 'green';\n }\n }",
"function drawGrade2Stacked() {\n var data = google.visualization.arrayToDataTable([\n [\"Grade\", \"Bike, walk, others\", \"School bus, family vehicle, carpool, or city bus\"],\n [\"Pre-school\", 15, 151],\n [\"Primary school\", 8, 80],\n [\"Middle school\", 20, 19],\n [\"Highschool\", 15, 151]\n ]);\n\n var options = {\n \"title\": \"Figure 10: Mode of Transportation to School by Grade\",\n chartArea: {width: \"50%\"},\n \"isStacked\": true,\n\t\tcolors: ['#C52026','#ADADAD'],\n\t\t\"width\": 800,\n hAxis: {\n title: \"Number of Response\",\n minValue: 0\n },\n vAxis: {\n title: \"Grade\"\n }\n };\n var chart = new google.visualization.BarChart(document.getElementById(\"chart_div11\"));\n chart.draw(data, options);\n }",
"function setBarColorsExcept(index, color) {\n for(var i = 0; i < categoryIdentifiers.length; i++) {\n if(i == index) {\n continue;\n } else {\n setBarColorAtIndex(i, color);\n }\n }\n }",
"function renderErrorBar2(params, api) {\n\n // oss is [last.barGap, last.barCategoryGap, totSeries]\n let oss = JSON.parse(sessionStorage.getItem('ErrorBar.oss'));\n if (oss===null || !Object.keys(oss).length) return null; // cant work without it\n\n let totSeries = Number(oss[2]);\n\n let xValue = api.value(0);\n let highPoint = api.coord([xValue, api.value(1)]);\n let lowPoint = api.coord([xValue, api.value(2)]);\n let halfWidth = api.size([1, 0])[0] * 0.1;\n\t\n let csil = api.currentSeriesIndices().length / 2;\n\t// idx is index of related main bar\n let idx = params.seriesIndex - (params.seriesIndex < totSeries ? 0 : totSeries);\t\n\n if (csil > 1 && totSeries > 1) {\n \tlet bgm = oss[0];\n \tlet bcgm = oss[1];\n \tlet olay = { count: csil };\n \tolay.barGap = bgm!=='' ? bgm : '30%';\t\t// '30%' is default for e_bar\n \tolay.barCategoryGap = bcgm!=='' ? bcgm : '20%';\n \tlet barLayouts = api.barLayout(olay);\t\t// will be csil # of barLayouts\n \t\n \tif (barLayouts) {\n\t \tlet mbar = 0;\n\t \tapi.currentSeriesIndices().some( (item, index) => {\n\t \t\tif (item == idx) {\n\t \t\t\thighPoint[0] += barLayouts[mbar].offsetCenter;\n\t \t\t\thalfWidth = barLayouts[mbar].width /2;\n\t \t\t\treturn true;\n\t \t\t}\n\t \t\tmbar++;\n\t \t\treturn mbar >= csil; // false until true\n\t \t});\n \t}\n }\n lowPoint[0] = highPoint[0];\n \n var style = api.style({\n stroke: api.visual('color'),\n fill: null\n });\n return {\n type: 'group',\n children: [{\n type: 'line',\n shape: {\n x1: highPoint[0] - halfWidth, y1: highPoint[1],\n x2: highPoint[0] + halfWidth, y2: highPoint[1]\n },\n style: style\n }, {\n type: 'line',\t\t// vertical\n shape: {\n x1: highPoint[0], y1: highPoint[1],\n x2: lowPoint[0], y2: lowPoint[1]\n },\n style: style\n }, {\n type: 'line',\n shape: {\n x1: lowPoint[0] - halfWidth, y1: lowPoint[1],\n x2: lowPoint[0] + halfWidth, y2: lowPoint[1]\n },\n style: style\n }]\n };\n}",
"function drawGradeFStacked() {\n var data = google.visualization.arrayToDataTable([\n [\"Grade\", \"Bike, walk, others\", \"School bus, family vehicle, carpool, or city bus\"],\n [\"Pre-school\", 15, 151],\n [\"Primary school\", 8, 80],\n [\"Middle school\", 20, 19],\n [\"Highschool\", 15, 151]\n ]);\n\n var options = {\n \"title\": \"Figure 11: Mode of Transportation to School by Grade\",\n chartArea: {width: \"50%\"},\n \"isStacked\": true,\n\t\tcolors: ['#C52026','#ADADAD'],\n\t\t\"width\": 800,\n hAxis: {\n title: \"Number of Response\",\n minValue: 0\n },\n vAxis: {\n title: \"Grade\"\n }\n };\n\n var chart = new google.visualization.BarChart(document.getElementById(\"chart_div12\"));\n chart.draw(data, options);\n }",
"function drawSchoolFStacked() {\n var data = google.visualization.arrayToDataTable([\n [\"School\", \"Bike, walk, others\", \"School bus, family vehicle, carpool, or city bus\"],\n [\"WES\", 31, 102],\n [\"MGHS\", 24, 73],\n [\"IHoMCS\",11, 11],\n [\"NMCS\", 5, 2],\n [\"MG21\", 4, 2]\n ]);\n\n\n var options = {\n title: \"Figure 9: Mode of Transportation from School by School\",\n chartArea: {width: \"50%\"},\n\t\t\"width\": 600,\n isStacked: true,\n\t\tcolors: ['#C52026','#ADADAD'],\n hAxis: {\n title: \"Number of Response\",\n minValue: 0\n },\n vAxis: {\n title: \"School\"\n }\n };\n var chart = new google.visualization.BarChart(document.getElementById(\"chart_div10\"));\n chart.draw(data, options);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Closes the current window, but it assigns a returnValue first PARAM action String with the value that should be returned when the window closes (works for modal windows) | function closePopupForm(action) {
window.returnValue = action;
window.close();
} | [
"function exoduswindowclose(returnvalues) {\n\n //window.opener.gchildwin_returnvalue = returnvalues\n if (window.opener) {\n window.opener.focus()//for MSEDGE\n if (window.opener.exodus_setchildwin_returnvalue) {\n if (typeof returnvalues == 'undefined')\n returnvalues = ''\n returnvalues.exodusisarray = true\n window.opener.exodus_setchildwin_returnvalue(returnvalues)\n }\n }\n window.returnValue = returnvalues\n window.close()\n}",
"function closePopup()\n{\n win.close();\n return true;\n}",
"function recordsetDialog_onClickCancel(theWindow)\r\n{\r\n // No need to do any additional processing for now.\r\n dwscripts.setCommandReturnValue(recordsetDialog.UI_ACTION_CANCEL);\r\n theWindow.close();\r\n}",
"function jConfirmWindowClosed(callbackFunction)\n\t\t\t\t{\n\t\t\t\t\t//User can't click on buttons anymore\n\t\t\t\t\tconfirmWindow.find('input').attr('disabled','true');\n\t\t\t\t\tif(callbackFunction)\n\t\t\t\t\t{\n\t\t\t\t\t\tcallbackFunction(link);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif(parameters.splash)\n\t\t\t\t\t{\n\t\t\t\t\t\tsplash.fadeOut('slow');\n\t\t\t\t\t}\n\t\t\t\t\tconfirmWindow.fadeOut('slow',function()\n\t\t\t\t\t{\n\t\t\t\t\t\tif(parameters.onclose)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tparameters.onclose(link);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$(this).remove();\n\t\t\t\t\t});\n\t\t\t\t}",
"function closeSecret(){\n\tmySecretWindow.close();\n\treturn false;\n}",
"close() {\n this.showModal = false;\n\n this.onClose();\n }",
"@action closeDialog() {\r\n\t\tif (this.dialog) this.dialog.opened = false;\r\n\t}",
"function closeWin()\r\n{\r\n var browserWin = getBrowserWindow();\r\n if (browserWin && browserWin.gStatusManager\r\n && browserWin.gStatusManager.closeMsgDetail)\r\n {\r\n browserWin.gStatusManager.closeMsgDetail();\r\n }\r\n else\r\n { \r\n self.close();\r\n }\r\n return;\r\n}",
"function CloseArticleInfoWindow ()\n {\n CloseWindow ( wInfo );\n }",
"function closeWindow( param ) {\n\t\t\n\t\tvar\n\t\t\thWnd = typeof param === 'object' ? param.hWnd : param;\n\n\t\tif( persistent.windows[ hWnd ] ) {\n\n\t\t\tvar\n\n\t\t\t\twin =\n\t\t\t\t\troot\n\t\t\t\t\t\t.find( '#' + hWnd ),\n\n\t\t\t\twinInfo =\n\t\t\t\t\twin.data( 'wininfo' );\n\n\t\t\tsendMessage( { msg: 'wm_before_close' }, winInfo.hWnd );\n\n\t\t\twin\n\t\t\t\t.removeData( 'wininfo' );\n\t\t\t\n\t\t\tdelete winInfo.hWnd;\n\n\t\t\tvar e = new $.Event( 'notify' );\n\t\t\te.msg = 'before_close_window';\n\t\t\te.winInfo = winInfo;\n\t\t\tthat.trigger( e );\n\t\t\t\n\t\t\twin\n\t\t\t\t.remove();\n\n\t\t\tdelete persistent.windows[ hWnd ];\n\n\t\t\te = new $.Event( 'notify' );\n\t\t\te.msg = 'close_window';\n\t\t\te.winInfo = winInfo;\n\t\t\tthat.trigger( e );\n\t\t\t\n\t\t\te = new $.Event( 'notify' );\n\t\t\te.msg = 'after_close_window';\n\t\t\te.winInfo = winInfo;\n\t\t\tthat.trigger( e );\n\t\t}\n\t}",
"function closecancelpanel(){\n $.modal.close();\n }",
"okAction() {\n if (this.attrs.okAction) {\n get(this, 'okAction')();\n }\n this.send('closeDialog');\n }",
"function CloseWindow ( w )\n {\n \tif ( w && !w.closed )\n \t{\n \t\tw.close();\n \t}\n }",
"function closeEditingWindow() {\n document.getElementById(\"fileEditing\").style.display = \"none\";\n document.getElementById(\"pageTitle\").childNodes[1].textContent = \"Files\";\n document.getElementById(\"fileBrowser\").style.display = \"block\";\n\n console.log(\"HUB: Closing editing tool\");\n}",
"function popupPVAsWindow_onunload(event)\n{\n\ttry\n\t{\n\t\tif (!window.close())\n\t\t{\n\t\t\tdt_pvClosePopUp(false);\n\t\t}\n\t}\n\tcatch(e)\n\t{\n\t}\n}",
"function closeReportWindow () {\n\tset_element_display_by_id_safe('ReportWindow', 'none');\n\tset_element_display_by_id_safe('report_error1', 'none');\n\tset_element_display_by_id_safe('report_error2', 'none');\n\tset_element_display_by_id_safe('error_div', 'none');\n}",
"function closeModal() {\n\twinningMessage.style.display = 'none';\n}",
"function closeRecordWindow () {\r\n\r\n\tif (typeof selectWindow != 'undefined' && selectWindow != null) {\r\n\t\tselectWindow.close();\r\n\t}\r\n\tif (typeof listWindow != 'undefined' && listWindow != null) {\r\n\t\tlistWindow.close();\r\n\t}\r\n\t\r\n}",
"function doExitMgen()\r\n{\r\n // For now, just close the window\r\n $('#monsteredit').slideUp();\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Click to delete a task | 'click .delete'() {
Meteor.call('tasks.remove', this._id, (error) => {
if (error)
Bert.alert( 'An error occured: ' + error.reason + '! Only the creator of the task can delete it.', 'danger', 'growl-top-right' );
else
Bert.alert( 'Task removed successfully!', 'success', 'growl-top-right' );
});
} | [
"function deleteTask(){\n // get indx of tasks\n let mainTaskIndx = tasksIndxOf(delTask['colName'], delTask['taskId']);\n // del item\n tasks.splice(mainTaskIndx, 1);\n // close modal\n closeModal();\n // update board\n updateBoard();\n // update backend\n updateTasksBackend();\n}",
"function viewTaskdeleteThisTask() {\r\n if (confirm(\"You are about to delete this task?\")) {\r\n // Get taskobject === clicked taskCard\r\n TempLocalStorageTaskArray = getLocalStorage(\"task\");\r\n tempIndex = TempLocalStorageTaskArray.findIndex(obj => obj.name === viewTaskTitleDiv.innerHTML);\r\n //delete from localstorage where thisTask === \"task\".name\r\n // finn index og splice fra array\r\n TempLocalStorageTaskArray.splice(tempIndex, 1);\r\n setLocalStorage(\"task\", TempLocalStorageTaskArray);\r\n } else {\r\n console.log('no task was deleted');\r\n }\r\n\r\n\r\n}",
"function addDeleteBtns() {\n let deleteTasks = document.querySelectorAll('input[type=\"image\"]');\n\n deleteTasks.forEach(\n task => {\n task.addEventListener('click', (e) => {\n let selectedId = e.target.dataset.id; //Select trash image id that was clicked\n let selectedTask = toDoList.findIndex(todo => todo.Id === parseInt(selectedId)); //Find the index of the selected id in the list of task objects\n toDoList.splice(selectedTask, 1); //Remove that object\n\n displayTasks(toDoList);\n localStorage.setItem('Tasks', JSON.stringify(toDoList));\n });\n }\n );\n}",
"function deleteTaskFromLocalStorage(task) {\r\n let LocalStorageTaskArray = getLocalStorage(\"task\");\r\n let taskTitle = document.getElementById(task).firstElementChild.innerHTML;\r\n let index = LocalStorageTaskArray.findIndex(obj => obj.name === taskTitle);\r\n LocalStorageTaskArray.splice(index, 1);\r\n setLocalStorage(\"task\", LocalStorageTaskArray);\r\n}",
"deleteTodo() {\n\t let todo = this.get('todo');\n\t this.sendAction('deleteTodo', todo);\n\t }",
"function deleteTask(req, res) {\n var id = req.params.id;\n\n knex('task_items').where('id', id)\n .delete()\n .then(function () {\n res.sendStatus(204);\n }).catch(function (err) {\n console.log('Error Querying the DB', err);\n });\n}",
"function deleteTask(){\n // TODO: IF program.task exists you should use mongoose's .remove function\n // on the model to remove the task with {name: program.task}\n\n // YOUR CODE HERE\n if(program.task){\n ToDoItem.remove({ name: program.task }, function (err) {\n if (err) return console.error(err);\n console.log(\"Deleted task with name: \" + program.task);\n mongoose.connection.close();\n });\n } else {\n console.log(\"No task specified\");\n mongoose.connection.close();\n }\n}",
"function deleteAlert() {\n swal({\n title: 'Are you sure?',\n text: 'Once deleted, you will not be able to recover this Task!',\n icon: 'warning',\n buttons: true,\n dangerMode: true,\n }).then((willDelete) => {\n if (willDelete) {\n const taskId = $(this).data('id');\n deleteTask(taskId);\n swal('Poof! Your Task has been deleted!', {\n icon: 'success',\n });\n } else {\n swal('Your Task is safe!');\n }\n });\n} // end deleteAlert",
"function newTask(task)\n {\n var line=document.createElement('div'); line.classList.add('row','col-sm-12','justify-content-center'); \n tasks.appendChild(line);\n\n var lineText=document.createElement('h2'); lineText.innerHTML=task; //whatever input was\n line.appendChild(lineText);\n\n var lineButton=document.createElement('button'); lineButton.innerHTML=\"DONE\"; //inner=can include strong, etc. within text\n lineButton.setAttribute('type', 'button'); //syntax stuff\n line.appendChild(lineButton);\n\n /* INDIVIDUAL TASK BUTTON EVENT */\n //=this way, you can use each of the button's local info to know which button does what, rather than having variables for each (which is hard to automate anyway) \n lineButton.addEventListener('click', function()\n {\n tasks.removeChild(line); //remove the div+all w/in it\n });\n }",
"function domDeleteTodo(dom_element) {\n \n}",
"function deleteTask(){\n //DECLARE THE VARIABLE FOR THE POSITION OF THE TASK TO BE REMOVED\n var position;\n //LOOP THROUGH, GET POSITION, SPLICE FROM LIST\n for(var i = 0; i < this.tasks.length; i++){\n if(this.tasks[i]._id == id){\n position = this.tasks[i].position;\n this.tasks.splice(tasks[i], 1);\n }\n }\n\n //REMOVE THE ITEM FROM TASK LIST\n //IT IS ASYNC, NO WORRIES\n Task.remove({_id: id}, function(err){\n if(err) {\n console.log(err);\n res.render('error', {message: \"Could not update tasks\", error: err});\n }\n });\n\n //LOOP THROUGH, UPDATE THE TASKS WITH POSITION GREATER THAN DELETED\n for(var i = 0; i < this.tasks.length; i++){\n //IF THE POSITION IS GREATER THAN THE ONE DELETED\n if(this.tasks[i].position > position){\n\n //SUBTRACT ONE FROM THE POSITION TO MAKE UP FOR THE MISSING ONE\n var newPos = this.tasks[i].position - 1;\n\n //UPDATE EACH TASK\n Task.update({_id: this.tasks[i]._id }, { position: newPos }, function(err){\n if(err){\n console.log(err);\n res.render('error', {message: \"Could not update tasks\", error: err});\n }\n });\n }\n }\n\n //REDIRECT TO /\n res.redirect('/');\n }",
"function confirmDeleteAndRefresh() {\n View.confirm(getMessage(\"confirmPtaskDelete\"), function (button) {\n if (button === 'yes') {\n var panel = pgnavPageEditorController.assignedTasksGrid;\n if (panel != null && panel.selectedRowIndex >= 0) {\n var parameters = {\n viewName: panel.viewDef.viewName,\n groupIndex: (typeof panel.viewDef.tableGroupIndex === 'undefined') ? 0 : panel.viewDef.tableGroupIndex,\n controlId: (typeof panel.panelId === 'undefined') ? panel.id : panel.panelId,\n version: Ab.view.View.version,\n dataSourceId: panel.dataSourceId\n };\n\n var row = panel.rows[panel.selectedRowIndex];\n if (row != null) {\n var pKeyValues = panel.getPrimaryKeysForRow(row);\n parameters.fieldValues = toJSON(pKeyValues);\n }\n\n var wfrResult = Ab.workflow.Workflow.runRuleAndReturnResult('AbCommonResources-deleteDataRecords', parameters);\n if (wfrResult.code !== 'executed') {\n Ab.workflow.Workflow.handleError(wfrResult);\n }\n }\n\n pgnavPageEditorController.assignedTasksGrid.refresh();\n }\n });\n}",
"function deleteExpense(id) {\n console.log(\"DELETE BUTTON WORKS\");\n }",
"function deleteClickListener() {\n\t\t$('.container').on('click', '.delete-submission', event => {\n\t\t\tevent.stopImmediatePropagation();\n\t\t\tconst submission = $(event.currentTarget)\n\t\t\t\t.parents('.submission-thumb')\n\t\t\t\t.prop('id');\n\n\t\t\tif (\n\t\t\t\tconfirm(\n\t\t\t\t\t'Are you sure that you would like to permanently remove this submission?'\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tapi\n\t\t\t\t\t.remove(`/api/submissions/${submission}`)\n\t\t\t\t\t.then(() => {\n return api\n .search(`/api/users/mysubmissions`)\n .then(res => {\n $('#user-submissions').empty();\n store.userSubmissions = res;\n \n displayUserSubmissions(res);\n \t })\n });\n\t\t }\n });\n }",
"function deleteButton() {\n const idToDelete = $(this)\n .parent()\n .attr('data-id');\n console.log(idToDelete);\n\n API.deleteBill(idToDelete).then(() => {\n refreshBillList();\n });\n}",
"function deleteButtonPressed(entity) {\n db.remove(entity);\n }",
"function clickDeleteSCmd() {\n console.log('Cancelling Command', selectedGuild, this.value);\n socket.emit('cancelScheduledCommand', selectedGuild, this.value);\n }",
"function deleteToDo(position){\r\ntoDos.splice(position, 1);\r\ndisplayToDos();\r\n}",
"function removeCompleted(n){\n //get id of task element(input) from parent elements\n taskElement = n.parentElement.parentElement.parentElement;\n taskId = taskElement.childNodes[0].id;\n //find task instance using the array and the id(index)\n curr = Task.ALLTASKS[taskId]; \n curr.complete();\n taskElement.style.display = 'none';\n addCompletedToDisplay() \n drawPercentage();\n updateReward();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show a user's personal key information. | showPrivateKey() {
this.showKey(this.privateKey, true);
} | [
"formatUser() {\n\t\tconst user = this.currentUser();\n\t\treturn `\nName (Client Email): ${user.name}\nKey (Client ID): ${user.key}\nAPI Key ID: ${user.api_key_id}\nAPI Secret: ${user.api_secret}\nPublic Key: ${user.public_key}\nPrivate Key: ${user.private_key}\nPublic Signing Key: ${user.public_signing_key}\nPrivate Signing Key: ${user.private_signing_key}\n`;\n\t}",
"function getPubkey(callback) {\n sbot.whoami(function(err, msg) {\n if(err) { \n console.log('getPubkey(callback) err', err, '\\n\\n\\n\\n')\n return callback(err)\n } else {\n console.log('getPubkey(callback) msg', msg, '\\n\\n\\n\\n')\n return callback(null, msg)\n }\n })\n }",
"function showKeyElements() {\n $(\"#input-container\").css({ display: \"\" });\n $(\"#feedback-placeholder\").css({ display: \"\" });\n $(\"#card-button-container-1\").css({ display: \"\" });\n $(\"#firebaseui-auth-container\").css({ display: \"none\" });\n var keyStatus = sessionStorage.getItem(\"key\");\n if (keyStatus) {\n if (JSON.parse(key).status == \"valid\") {\n hideKeyElements();\n }\n }\n}",
"function DisplayInfo() {\n showAccessToken();\n whenTheTokenWillExpire();\n}",
"showPasswordView() {\n const view = new Passphrase({model: this.collection.get('privateKey')});\n Radio.request('Layout', 'show', {view, region: 'modal'});\n }",
"function openKeyManager() {\n window.browsingContext.topChromeWindow.openDialog(\n \"chrome://openpgp/content/ui/enigmailKeyManager.xhtml\",\n \"enigmail:KeyManager\",\n \"dialog,centerscreen,resizable\",\n {\n cancelCallback: null,\n okCallback: null,\n }\n );\n}",
"function getUserInfo() {\n return user;\n }",
"function showOtherUser(){\n removeFollowList();\n removeSearchArea();\n var userId = this.dataset.user; // get the user of the clicked name or image\n showedUser = userId;\n removeWritenFields();\n removeErrorSuccesFields();\n document.getElementById(\"profileSection\").style.display = \"block\";\n document.getElementById(\"messagesSection\").style.display = \"none\";\n hideAllProfileSection();\n document.getElementById(\"showProfile\").style.display = \"block\";\n\n getOtherProfile(userId);\n}",
"function showUser (req, res) {\n console.log(req.params.id)\n User.findById(req.params.id, function (err, user) {\n if (err) return res.status(401).json({error: '/users users/:id error 1'})\n res.status(200).json({user: user})\n })\n}",
"function displayUser() {\n var user = firebase.auth().currentUser;\n var email;\n if (user != null) {\n email = user.email;\n }\n}",
"function currentProfile() {\n return {\n handle: $('#handle').text(),\n email: $('#email').text(),\n keys: [{\n name: 'default',\n signature: $('.signature').first().text()\n }]\n };\n}",
"ListOfYourPublicSSHKeys() {\n let url = `/me/sshKey`;\n return this.client.request('GET', url);\n }",
"function show_api_key(){\n\t$(\"span.api_cell\").dblclick(function(){\n\t\t$(\"#api_key\").show();\n\t\t$(this).hide();\n\t});\t\t\t\t \n\t$(\"span#api_key\").dblclick(function(){\n\t\t$(\"span.api_cell\").show();\n\t\t$(this).hide();\n\t});\n}",
"function displayUsername() {\n $navWelcome.children('#nav-user-profile').text(currentUser.username);\n $navWelcome.show();\n }",
"function getConsumerKey(){\n prompt( 'Enter OAuth consumer key:', function( key ){\n consumerKey = key;\n getConsumerSecret();\n } );\n }",
"function showIcon() {\n const user = User.getUser();\n const profileImage = [...document.getElementsByClassName('user-image')];\n profileImage.forEach((element) => {\n element.style.backgroundImage = `url(${ROOT}/${user.profile})`;\n });\n document.getElementById('userName').innerHTML = `${user.firstname} ${user.othernames} ${user.lastname}`;\n document.getElementById('userEmail').innerHTML = user.email;\n document.getElementById('userFirstName').innerHTML = user.firstname;\n}",
"function GetUser() {\n\n\tvar client = new SpiderDocsClient(SpiderDocsConf);\n\n\tclient.GetUser('administrator', 'Welcome1')\n\t\n .then(function (user) {\n debugger;\n console.log(user);\n });\n}",
"function getUserInfo(username) {\n fetch(`https://api.github.com/search/users?q=${username}`)\n\t.then(response => response.json())\n\t.then((responseObject) => {\n renderObject(responseObject)\n })\n}",
"function viewUserHandler(app, auth, res, id){\n\tapp.users.account(id, auth)\n\t.then((data) => {\n \t\tres.send(doMustache(app, 'account', {fn: data.firstName, ln: data.lastName}));\n\t})\n\t.catch(() => res.redirect('../../login'));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Emits the change event as defined in AppConstants.CHANGE_EVENT | emitChange() {
this.emit(AppConstants.CHANGE_EVENT);
} | [
"on_change(ev){\r\n\t\tthis.val = this.get_value();\r\n\t\t// hack to get around change events not bubbling through the shadow dom\r\n\t\tthis.dispatchEvent(new CustomEvent('pion_change', { \r\n\t\t\tbubbles: true,\r\n\t\t\tcomposed: true\r\n\t\t}));\r\n\t\t\r\n\t\tif(!this.hasAttribute(\"noupdate\")){ //Send value to server\t\t\r\n\t\t\tsend_update(this, this.getAttribute(\"item_name\"), new Value(this.val));\t\t\t\r\n\t\t}\r\n\t\t\r\n\t}",
"add_change(func) {\n this.add_event(\"change\", func);\n }",
"changed() {\n ++this.revision_;\n this.dispatchEvent(EventType.CHANGE);\n }",
"_emitChangeEvent(option) {\n this.selectionChange.emit({\n source: this,\n option: option,\n });\n }",
"_setOnChange() {\n let self = this;\n this.onChange = function() {\n self.value = self.innerGetValue(); // Update inner value\n if (self._onChangeCB) self._onChangeCB.call(self); // call user defined callback\n };\n this.innerMapOnChange(); // Map the event that will trigger onChange\n }",
"function emitConsoleChange(elevatorConsole) {\r\n var consoleState = buildFullConsole(elevatorConsole);\r\n\r\n debug(\"Emitting \" + EVENTS.CONSOLE_CHANGE + \" event. Buttons state: \" + JSON.stringify(consoleState));\r\n userInteractionObservable.emit(EVENTS.CONSOLE_CHANGE, consoleState);\r\n}",
"function onConnectionChange() {\n window.console.log('Connection changed. Attempting to sync…');\n syncIfPossible();\n }",
"static sendUpdatedEvent (model) {\n const PluginHelper = require('../helpers/plugin');\n PluginHelper.events().emit('update', {\n action: 'updated',\n name: 'account',\n model\n });\n }",
"watchEvents () {\n // TODO: Figure out how robust this is.\n this.contract.allEvents().watch((error, event) => {\n if (error) {\n console.log(error)\n } else {\n this.emit(`event:${event.event}`, event)\n }\n })\n }",
"emitter(editor, data, value) {\n // Emit code change to socket\n socket.emit('code change', value); \n }",
"modelChanged() {\n }",
"despatchChangeEvent() {\n const eventDetail = {\n fldorigin: this.fldorigin,\n fieldName: this.fldname,\n fieldType: this.fldtype,\n isRange: false,\n isMulti: true,\n fieldValue: this.filterValue\n };\n const changeEvent = new CustomEvent(\"filtervaluechange\", {\n detail: eventDetail\n });\n this.dispatchEvent(changeEvent);\n }",
"onModelChange(value) {\n this.newValue = value\n }",
"function onSelectedChanged(val) {\n scope.$emit('selectedchange', val);\n }",
"function stateChangeListener(event) {\n var message = {\n port: event.target.id,\n type: event.port.state,\n interface: event.port.type\n };\n\n // Include original event.\n message.originalEvent = event;\n\n // Trigger events.\n PubSub.trigger('statechange', [message]);\n PubSub.trigger(message.type, [message]);\n PubSub.trigger(message.type + ':' + message.interface, [message]);\n PubSub.trigger('id:' + event.target.id, [message]);\n PubSub.trigger('id:' + event.target.id + ':' + message.type, [message]);\n}",
"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 onUpdate(fromVersion, toVersion) {\n\tconsole.log('Extension has been updated from version ', fromVersion, ' to version ', toVersion);\n}",
"handleChainChanged() {\n console.log(\"Chain changed to\", this.chainId);\n }",
"onDatabaseVersionChange(_) {\n Log.debug('IndexedDb: versionchange event');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
int Read (Variant, int) | Read(Variant, int) {
} | [
"function read(){\n\n }",
"function decodeTyped(){\n let res;\n let type = readByte();\n switch(type){ // Read Type\n case 0:\n res = readInt16();\n break;\n case 1:\n res = readAscii();\n break;\n case 2:\n res = readByte();\n break;\n case 3:\n res = readFloat32();\n break;\n case 4:\n res = readInt32();\n }\n\n return res;\n}",
"get read_item(){\n\t\treturn this.Item.read\n\t}",
"read(size)\n\t{\n\t\tif (this.pos+size > this.input.length)\n\t\t\tsize = this.input.length-this.pos;\n\t\tlet result = this.input.substring(this.pos, this.pos+size);\n\t\tthis.pos += size;\n\t\treturn result;\n\t}",
"function readState(data) {\n\n gamestate = data.val();\n\n}",
"readUint16() {\n const value = this._data.getUint16(this.offset, this.littleEndian);\n\n this.offset += 2;\n return value;\n }",
"function get_value(loc, mode, intcode) {\r\n if (mode == 0) {\r\n // position mode\r\n return intcode[loc];\r\n } else if (mode == 1) {\r\n // immediate mode\r\n return loc;\r\n }\r\n}",
"function readHealth(data) {\n\n dogHealth = data.val();\n \n}",
"readDataByIndex(index) {\n return this.content[index];\n }",
"function readNWord(bytes, index, length)\n{\n\tif (length <= 4)\n\t{\n\t\t// Word fits in 32-bit\n\t\tlet result = 0;\n\t\tfor (let b = 0; b < length; b++)\n\t\t{\n\t\t\tresult <<= 8;\n\t\t\tresult |= bytes[index++];\n\t\t}\n\t\treturn result;\n\t}\n\telse\n\t{\n\t\t// Word requires 64-bit JS nastiness\n\t\tlet lo = 0, hi = 0;\n\t\tfor (let b = 4; b < length; b++)\n\t\t{\n\t\t\thi <<= 8;\n\t\t\thi |= bytes[index++];\n\t\t}\n\t\tfor (let b = 0; b < 4; b++)\n\t\t{\n\t\t\tlo <<= 8;\n\t\t\tlo |= bytes[index++];\n\t\t}\n\t\treturn { hi, lo };\n\t}\n}",
"function readPidData() {\n return txChar.readValue()\n .then(originalPid => {\n\n // Convert from dataView to Uint8Array and save original PID data for possible reset\n originalPidData = new Uint8Array(originalPid.buffer, 0, 20);\n txCharVal = originalPidData;\n console.log(\"Original PID data received:\", originalPid);\n\n // Write original PID data to input boxes\n for(var i = 1; i <= 18; i++) {\n select(inputMap[i]).value = originalPidData[i];\n }\n resolve(originalPidData);\n });\n}",
"function readValue(textfile, logline, logstring) { \n\t// example of how to parse files for numeric values \n\tvar val = 0; \n\tif (textfile != null && logline >= 0 && logstring != null) { \n\t\tvar data = readPaths(textfile); \n\t\tif (data.length > logline) { \n\t\t\tvar row = data[logline]; \n\t\t\tif (row.length() >= logstring.length && \n\t\t\t\trow.substring(0, logstring.length) == logstring) { \n\t\t\t\t// read the rest of the line following the logstring \n\t\t\t\tvar temp = Packages.java.lang.Float.parseFloat(row.substring(logstring.length,row.length())); \n\t\t\t\tif (temp != null && temp > 0) { \n\t\t\t\t\tval = temp; \n\t\t\t\t} \n\t\t\t} \n\t\t} \n\t} \n\treturn val; \n}",
"static validateReadingIsNumeric(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 must be a number\n if (libLocal.isNumber(pageClientAPI, dict.ReadingSim)) { \n return Promise.resolve(true);\n } else {\n let message = pageClientAPI.localizeText('validation_reading_is_numeric');\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ReadingSim'), message);\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n }\n }",
"constructor(fields, samples, formatTypes, infoTypes, contigLength){\n\t\tthis.fields = fields;\n\t\tthis.contig = this.fields[0];\n\t\tthis.position = parseInt(fields[1], 10) || 0;\n\t\tif(this.position > contigLength + 1){\n\t\t\tthrow {\n\t\t\t\tname: 'VariantError',\n\t\t\t\tmessage: `Variant position ${this.position} is nonsensical given contig length ${contigLength}`\n\t\t\t};\n\t\t}\n\t\tthis.telomere = this.position === 0 || this.position === contigLength + 1;\n\t\tthis.identifiers = fields[2].split(';');\n\t\tthis.ref = fields[3];\n\t\tthis.alt = fields[4];\n\t\tthis.quality = parseFloat(fields[5]) || 0;\n\t\tthis.filter = fields[6];\n\t\tthis.info = {}; \n\t\tfields[7].split(';').forEach((infoField) => {\n\t\t\tlet infoParts = infoField.split('=');\n\t\t\tswitch (infoTypes[infoParts[0]].type){\n\t\t\t\tcase 'Flag':\n\t\t\t\t\tthis.info[infoParts[0]] = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Integer':\n\t\t\t\t\tif (infoTypes[infoParts[0]].number === '1'){\n\t\t\t\t\t\tthis.info[infoParts[0]] = parseInt(infoParts[1]) || 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.info[infoParts[0]] = infoParts[1].split(',').map((val) => {\n\t\t\t\t\t\t\treturn parseInt(val) || 0;\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Float':\n\t\t\t\t\tif (infoTypes[infoParts[0]].number === '1'){\n\t\t\t\t\t\tthis.info[infoParts[0]] = parseFloat(infoParts[1]) || 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.info[infoParts[0]] = infoParts[1].split(',').map((val) => {\n\t\t\t\t\t\t\treturn parseFloat(val) || 0;\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tif (infoTypes[infoParts[0]].number === '1'){\n\t\t\t\t\t\tthis.info[infoParts[0]] = infoParts[1].toString();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.info[infoParts[0]] = infoParts[1].split(',');\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t});\n\t\tthis.format = {};\n\t\tlet formatFields = fields[8].split(':');\n\t\tlet sampleFormats = fields.slice(9);\n\t\tlet self = this;\n\t\tsampleFormats.forEach((sf, sampleIndex) => {\n\t\t\tif(!samples[sampleIndex]){\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet sampleValues = sf.split(':');\n\t\t\tlet sampleName = samples[sampleIndex].name;\n\t\t\tthis.format[sampleName] = {};\n\t\t\tformatFields.forEach((ff, index) => {\n\t\t\t\tswitch (formatTypes[ff].type){\n\t\t\t\t\tcase 'Integer':\n\t\t\t\t\t\tif (formatTypes[ff].number === '1'){\n\t\t\t\t\t\t\tself.format[sampleName][ff] = \n\t\t\t\t\t\t\t\tparseInt(sampleValues[index]) || 0;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself.format[sampleName][ff] = sampleValues[index]\n\t\t\t\t\t\t\t\t.split(',').map((val) => {\n\t\t\t\t\t\t\t\t\treturn parseInt(val) || 0;\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'Float':\n\t\t\t\t\t\tif (formatTypes[ff].number === '1'){\n\t\t\t\t\t\t\tself.format[sampleName][ff] = \n\t\t\t\t\t\t\t\tparseFloat(sampleValues[index]) || 0;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself.format[sampleName][ff] = sampleValues[index]\n\t\t\t\t\t\t\t\t.split(',').map((val) => {\n\t\t\t\t\t\t\t\t\treturn parseFloat(val) || 0;\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t//String or Character\n\t\t\t\t\t\tif (formatTypes[ff].number === '1'){\n\t\t\t\t\t\t\tself.format[sampleName][ff] = sampleValues[index].toString();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself.format[sampleName][ff] = sampleValues[index].split(',');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}",
"function readDigital(args) {\n try {\n var pin = args[2];\n var value = board.digitalRead(pin);\n response.message = value;\n response.result = \"SUCCESS\";\n logger.info(\"[GPIO] - readDigital: \" + response.message);\n return response;\n } catch (ex) {\n response.message = ex.message;\n response.result = \"ERROR\";\n logger.error(\"[GPIO] - readDigital: \" + response.message);\n return response;\n }\n}",
"function get (str) {\n if (registers.hasOwnProperty(str))\n return Number(registers[str]);\n else if (str === \"$zero\")\n return 0;\n else\n output(\"Error getting register \" + str + \" on Line \" + line, 'e');\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 }",
"get(index){\n // return the value of an element at given index\n return memory.get(index);\n }",
"function readHumid() {\r\n\tvar humidity;\r\n\tsensor.read(2, function(err, res) {\r\n\t\tif(err) {\r\n\t\t\tconsole.log(\"readHumid: err: \" + err);\r\n\t\t}\r\n\t\t// console.log(\"readHumid: \" + res);\r\n\t\thumidity = ((((res[0]<<8) + res[1]) * 125) / 65536) - 6;\t// p21\r\n\t\tconsole.log(\"humidity: \" + humidity.toFixed(2));\r\n\t\tsendTempCmd();\r\n\t});\r\n}",
"function jkn_rdr_read_get() {\n var $option = jkn_rdr_url_param(JKNRendererSwitch.get_key);\n if ($option) {\n $select = $('#' + JKNRendererSwitch.id_select);\n\n // Only change if we have such an option\n if ($select.has('[value=\"' + $option + '\"]').length > 0) {\n $select.val($option);\n $select.change();\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all displayed elements inside of a root node that match a provided selector | function getDisplayedNodes(rootNode, selector) {
if (!isHTMLElement(rootNode)) {
return;
}
const nodes = Array.from(rootNode.querySelectorAll(selector));
// offsetParent will be null if the element isn't currently displayed,
// so this will allow us to operate only on visible nodes
return nodes.filter((node) => node.offsetParent !== null);
} | [
"function query(selector) {\n return Array.prototype.slice.call(document.querySelectorAll(selector));\n }",
"function children(selector) {\n var nodes = [];\n each(this, function(element) {\n each(element.children, function(child) {\n if (!selector || (selector && matches(child, selector))) {\n nodes.push(child);\n }\n });\n });\n return $(nodes);\n}",
"function _getChildren(element, selector) {\n\t\tvar allChildren = element.childNodes,\n\t\t\tlength = allChildren.length,\n\t\t\tchildren = [],\n\t\t\ti = 0;\n\n\t\tfor(; i < length; i++) {\n\t\t\tvar item = allChildren[i];\n\n\t\t\tif(allChildren[i].nodeType === 1) {\n\t\t\t\tif(selector) {\n\t\t\t\t\tif(_isId.test(selector) && item.id === selector.substr(1)) {\n\t\t\t\t\t\tchildren.push(item);\n\t\t\t\t\t}\n\t\t\t\t\telse if(_isClass.test(selector) && (' ' + item.className + ' ').indexOf(' ' + selector.substr(1) + ' ') !== -1) {\n\t\t\t\t\t\tchildren.push(item);\n\t\t\t\t\t}\n\t\t\t\t\telse if(_isTag.test(selector) && item.tagName === selector.toUpperCase()) {\n\t\t\t\t\t\tchildren.push(item);\n\t\t\t\t\t}\n\t\t\t\t\telse if(item === element.querySelector(selector)) {\n\t\t\t\t\t\tchildren.push(item);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tchildren.push(item);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn children;\n\t}",
"function findFirstVisible(root, selector) {\n if (!root || !root.querySelectorAll || !selector) {\n return null;\n }\n var els = Object(__WEBPACK_IMPORTED_MODULE_2__utils_array__[\"c\" /* from */])(root.querySelectorAll(selector));\n\n // IE 10 & 11 do not support native array.find()\n // So we try native find first, then fall back to a loop\n var el = els.find ? els.find(function (el) {\n return isVisible(el);\n }) : null;\n for (var i = 0; !el && i < els.length; i++) {\n if (isVisible(els[i])) {\n el = els[i];\n }\n }\n return el;\n}",
"textNodes(...args) {\n let filter = \"\", i = 0, a = [], recursive = false;\n $sel = $();\n while(arguments[i]){\n if (typeof arguments[i] === \"string\"){\n filter += (filter) ? \"|\" : \"\";\n filter += arguments[i];\n }else if (Array.isArray(arguments[i])){\n\t\t\t\t\tfilter += (filter) ? \"|\" : \"\";\n\t\t\t\t\tfilter += arguments[i].join(\"|\");\n\t\t\t\t}\n i++;\n }\n lastArg = arguments[arguments.length-1];\n if(typeof lastArg === \"boolean\" && lastArg) {recursive = true;}\n that = (recursive) ? this.find(\"*\").addBack() : this;\n that.each(function() {\n $sel = $sel.add($(this).contents());\n });\n $sel.each(function(){\n if(filter){\n reg = new RegExp(filter);\n }\n keep = (this.nodeType === 3 && (!filter || this.textContent.search(filter)+1)) ? true : false;\n if (keep) a.push(this);\n });\n $sel = $(a);\n $sel.prevObject = this;\n $sel.selector = filter;\n return $sel;\n }",
"*elements(root) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n for (var [node, path] of Node$1.nodes(root, options)) {\n if (Element$1.isElement(node)) {\n yield [node, path];\n }\n }\n }",
"function collectTextNodes($, $el) {\n let textNodes = [];\n $el.contents().each((ii, node) => {\n if (isTextNode(node)) {\n let $node = $(node);\n textNodes.push($node);\n } else {\n textNodes.push(...collectTextNodes($, $(node)));\n }\n });\n return textNodes;\n}",
"function queryHTMLElement(parent, selector) {\n return parent.query(selector);\n}",
"function filteredElements(nodeList) {\n var filtered = [];\n for (var i = 0; i < nodeList.length; i++) {\n var node = nodeList[i];\n if (node.nodeType !== 3) { // Don't process text nodes\n var $element = $(node);\n if ( $element.closest('.ant,.ant_indicator,.ant-custom-cta-container').length === 0 ) {\n filtered.push($element);\n }\n }\n }\n return filtered;\n }",
"function getNodes(ns, mode, tagName){\n var result = [], ri = -1, cs,\n i, ni, j, ci, cn, utag, n, cj;\n if(!ns){\n return result;\n }\n tagName = tagName || \"*\";\n // convert to array\n if(typeof ns.getElementsByTagName != \"undefined\"){\n ns = [ns];\n }\n\n // no mode specified, grab all elements by tagName\n // at any depth\n if(!mode){\n for(i = 0, ni; ni = ns[i]; i++){\n cs = ni.getElementsByTagName(tagName);\n for(j = 0, ci; ci = cs[j]; j++){\n result[++ri] = ci;\n }\n }\n // Direct Child mode (/ or >)\n // E > F or E/F all direct children elements of E that have the tag\n } else if(mode == \"/\" || mode == \">\"){\n utag = tagName.toUpperCase();\n for(i = 0, ni, cn; ni = ns[i]; i++){\n cn = ni.childNodes;\n for(j = 0, cj; cj = cn[j]; j++){\n if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){\n result[++ri] = cj;\n }\n }\n }\n // Immediately Preceding mode (+)\n // E + F all elements with the tag F that are immediately preceded by an element with the tag E\n }else if(mode == \"+\"){\n utag = tagName.toUpperCase();\n for(i = 0, n; n = ns[i]; i++){\n while((n = n.nextSibling) && n.nodeType != 1);\n if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){\n result[++ri] = n;\n }\n }\n // Sibling mode (~)\n // E ~ F all elements with the tag F that are preceded by a sibling element with the tag E\n }else if(mode == \"~\"){\n utag = tagName.toUpperCase();\n for(i = 0, n; n = ns[i]; i++){\n while((n = n.nextSibling)){\n if (n.nodeName == utag || n.nodeName == tagName || tagName == '*'){\n result[++ri] = n;\n }\n }\n }\n }\n return result;\n }",
"function fetchTags(xmlDoc,nodeType)\n {\n var node = xmlDoc.documentElement;\n var nodes = node.querySelectorAll(\"*\");\n var childrenNodes =[];\n for (var i = 0; i < nodes.length; i++) \n {\n var text = null;\n if (nodes[i].childNodes.length == 1 && nodes[i].childNodes[0].nodeType == nodeType) //if nodeType == text node\n if(doesNotExist(nodes[i].tagName,childrenNodes))\n childrenNodes.push(nodes[i].tagName);\n }\n return childrenNodes;\n }",
"async findElement (selector) {\n return new Promise(resolve => {\n this.page.evaluate((selector) => {\n return document.querySelector(selector)\n },\n selector,\n (err, result) => {\n if (!result) {\n return resolve(null)\n }\n resolve(new Element(this.page, selector))\n })\n })\n }",
"function flattenVisible(root){\n var nodes = [], i = 0;\n\n function recurse(node, indx, arr) {\n if (node.children) node.children.forEach(recurse);\n nodes.push(node);\n }\n\n recurse(root, 0, null);\n return nodes;\n}",
"visitWindowing_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function searchVisibleResults(){\n target = $('.list .asked');\n target = target.filter(function () {\n return $(this).css('visibility') == 'visible'\n });\n target = target.filter(function () {\n return $(this).closest('.tldResults').css('display') != 'none'\n });\n return target;\n}",
"collectInteractiveChildren() {\n if (undefined === this.targetElement) {\n // eslint-disable-next-line no-console\n console.error(\n 'No `targetElement` specified for collectInteractiveChildren'\n );\n return;\n }\n\n const interactiveElements = this.targetElement.querySelectorAll(\n this.selectors\n );\n this.interactiveChildElements = Array.prototype.filter.call(\n interactiveElements,\n (child) =>\n this.constructor.isVisible(child)\n );\n }",
"function elements() {\n return _elements;\n }",
"function selection_selectAll(selector) {\n var depth = this._depth,\n stack = new Array(depth * 2);\n\n if (typeof selector !== \"function\") selector = selectorAllOf(selector);\n\n function visit(nodes, depth) {\n var i = -1,\n n = nodes.length,\n node,\n subnode,\n subnodes = new Array(n);\n\n if (--depth) {\n var stack0 = depth * 2,\n stack1 = stack0 + 1;\n while (++i < n) {\n if (node = nodes[i]) {\n stack[stack0] = node._parent.__data__, stack[stack1] = i;\n subnodes[i] = visit(node, depth);\n }\n }\n }\n\n // Data is not propagated since there is a one-to-many mapping.\n // The parent of the new leaf group is the old node.\n else {\n while (++i < n) {\n if (node = nodes[i]) {\n stack[0] = node.__data__, stack[1] = i;\n subnodes[i] = subnode = selector.apply(node, stack);\n subnode._parent = node;\n }\n }\n }\n\n subnodes._parent = nodes._parent;\n return subnodes;\n }\n\n return new Selection(visit(this._root, depth), depth + 1);\n }",
"function xpath(query)\n {\n var ret = new Array();\n var snap = document.evaluate(query, document, null,\n XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);\n if( snap.snapshotLength > 0){\n for (i=0; i< snap.snapshotLength; i++){\n ret[i] = snap.snapshotItem(i);\n }\n return ret;\n }\n return null;\n }",
"visitSubquery_basic_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the simulation modes to `sim_mode_id' dropdown | static fillSimModes(id, modes) {
const json = JSON.parse(modes);
const element =
document.querySelector(`#diseases-simulation-node_${id}-sim_mode`);
$(element).selectpicker('destroy');
CosmoScout.gui.clearHtml(element);
json.forEach((mode) => {
const option = document.createElement('option');
option.text = mode.split('/').pop();
option.value = mode;
element.appendChild(option);
});
$(element).selectpicker();
const node = CosmoScout.vestecNE.editor.nodes.find(
(editorNode) => editorNode.id === id);
if (typeof node !== 'undefined') {
node.data.simMode = $(element).val();
console.log('Set ensemble');
window.callNative('DiseasesSimulationNode.setNumberOfEnsembleMembers',
parseInt(node.id, 10), node.data.simMode);
} else {
console.error(`Node with id ${id} not found.`);
}
} | [
"function select_simulations(itype, clusters, ligandonly, rev, stnd){\n \n //variables\n var simulationlist, code, URL, custombutton;\n\n //Get selected simulations dynIDs\n simulationlist = $(\".simulation_checkbox:checked\").map(function(){return $(this).attr(\"name\");}).get();\n\n //(Pseudo-)Random identifier for this customized heatmap\n code = Math.random().toString(36).substring(7);\n\n //Open new tab with the results\n URL = window.location.origin + '/contmaps/customized/?itype=' + itype + \"&cluster=\" + clusters + \"&prtn=\" + ligandonly + \"&rev=\" + rev + \"&stnd=\" + stnd + \"&code=\" + code;\n\n //Set new attributes to the custom form, and enable it if any simulations are selected\n custombutton = $(\"#CustomButton\");\n $(\"input[name='SimList']\").val(simulationlist.join(\"&\"));\n custombutton.attr('formaction',URL);\n if (simulationlist.length == 0){\n custombutton.attr('disabled',true);\n }\n else {\n custombutton.attr('disabled',false);\n }\n}",
"function modeSelect(modeToAdd, firstRemove, secondRemove) {\r\n\t\tmodeToAdd.classList.add(\"active\");\r\n\t\tfirstRemove.classList.remove(\"active\");\r\n\t\tsecondRemove.classList.remove(\"active\");\r\n\t}",
"function updateScenarioMenu(msa){\n\tconsole.log(msa, msas[msa]);\n\n\t$(\"#output\").val( msa +\": \\n\"+ JSON.stringify(msas[msa]) ); // testing\n\n\t// use msa to update the scenario box\n\tvar scenario_options = \"<option val=''></option>\";\n\n\t// for each scenario\n\tfor (var i = 0; i < msas[msa].length; i++) {\n\t\t//console.log( msas[msa][i]);\n\n\t\tvar scenario = msas[msa][i].scenario;\n\n\t\t// add optiongroup with scenario\n\t\tscenario_options += \"<optgroup label='\"+ dataDict[ scenario ] +\"'>\";\n\n\t\t// for each data type\n\t\tfor (var j = 0; j < msas[msa][i].data.length; j++) {\n\t\t\t//console.log( msas[msa][i].data[j]);\n\n\t\t\tvar data = msas[msa][i].data[j];\n\n\t\t\t// add scenario\n\t\t\tscenario_options += optionHTML(scenario +\"-\"+ data, dataDict[data]);\n\t\t}\n\t\tscenario_options += \"</optgroup>\";\n\t}\n\n\t// update options\n\t$(\"#scenario_select_box\").append( scenario_options ).trigger('chosen:updated');\n \t// trying to open it... :-P\n\t$('#scenario_select_box').trigger('chosen:open');\n\n}",
"function loadModes() {\n\tconsole.log(\"Loading modes...\");\n\tvar options = [];\n\toptions[0] = new Option(\"Train\", 0);\n\toptions[1] = new Option(\"Tram\", 1);\n\toptions[2] = new Option(\"Bus\", 2);\n\toptions[3] = new Option(\"V/Line\", 3);\n\toptions[4] = new Option(\"Nightrider\", 4);\n\t\n\t// Load the mode options into the selector... stringyfying here is silly, you should parse local storage first before sending to this function (above)\n\tloadOptions(options, selectObjMode);\n\n\t// Reset routes & directions selectors\n\tresetOptions(selectObjRoute);\n\tresetOptions(selectObjDirection);\n\tdisableSelector(selectObjRoute);\n\tdisableSelector(selectObjDirection);\n\t\n\t\n}",
"function createElementsForControls() {\r\n if (_opts.behavior.switchMode) {\r\n _dom.modeSwitch = $(\"<div></div>\")\r\n .appendTo(_dom.el)\r\n .addClass(\"s-c-p-mode-switch\");\r\n }\r\n }",
"setMatrixSelectValues() {\n // generate the matrix names based on the number of matrix inputs, e.g. A, B, C...\n const names = this.matrixInputs.map((_, i) => String.fromCharCode('A'.charCodeAt(0) + i));\n let options = \"\";\n names.forEach((name, i) => options += `<option value=${i}>${name}</option>`);\n this.matrixSelects.forEach(select => select.innerHTML = options);\n }",
"function set_settings(machine) {\r\n\t\tlet $st_ring = $('#stator').prop('disabled', false).val('')\r\n\t\t\t\t.find('option').prop('disabled', false),\r\n\t\t\t$a_ring = $('#a_ring').prop('disabled', false).val('')\r\n\t\t\t\t.find('option').prop('disabled', false),\r\n\t\t\t$b_ring = $('#b_ring').prop('disabled', false).val('')\r\n\t\t\t\t.find('option').prop('disabled', false),\r\n\t\t\t$c_ring = $('#c_ring').prop('disabled', false).val('')\r\n\t\t\t\t.find('option').prop('disabled', false),\r\n\t\t\t$th_ring = $('#thin_ring').prop('disabled', false).val('')\r\n\t\t\t\t.find('option').prop('disabled', false),\r\n\t\t\t$re_ring = $('#reflector').prop('disabled', false).val('')\r\n\t\t\t\t.find('option').prop('disabled', false),\r\n\r\n\t\t\t$st_set = $('#stator_ring_setting').prop('disabled', false).val('0'),\r\n\t\t\t$a_set = $('#a_ring_ring_setting').prop('disabled', false).val('0'),\r\n\t\t\t$b_set = $('#b_ring_ring_setting').prop('disabled', false).val('0'),\r\n\t\t\t$c_set = $('#c_ring_ring_setting').prop('disabled', false).val('0'),\r\n\t\t\t$th_set = $('#thin_ring_ring_setting').prop('disabled', false).val('0'),\r\n\t\t\t$re_set = $('#reflector_ring_ring_setting').prop('disabled', false).val('0'),\r\n\r\n\t\t\t$st_grd = $('#stator_ground_setting').prop('disabled', false).val('0'),\r\n\t\t\t$a_grd = $('#a_ring_ground_setting').prop('disabled', false).val('0'),\r\n\t\t\t$b_grd = $('#b_ring_ground_setting').prop('disabled', false).val('0'),\r\n\t\t\t$c_grd = $('#c_ring_ground_setting').prop('disabled', false).val('0'),\r\n\t\t\t$th_grd = $('#thin_ring_ground_setting').prop('disabled', false).val('0'),\r\n\t\t\t$re_grd = $('#reflector_ring_ground_setting').prop('disabled', false).val('0');\r\n\r\n\t\tfilter_ring($st_ring, machine.entry, $st_set, $st_grd); // the stator ring\r\n\t\tfilter_ring($a_ring, machine.rings, $a_set, $a_grd); // the a ring\r\n\t\tfilter_ring($b_ring, machine.rings, $b_set, $b_grd); // the b ring\r\n\t\tfilter_ring($c_ring, machine.rings, $c_set, $c_grd); // the c ring\r\n\t\tfilter_ring($th_ring, machine.extra, $th_set, $th_grd); // the thin ring\r\n\t\tfilter_ring($re_ring, machine.reflector, $re_set, $re_grd); // the reflector ring\r\n\r\n\t\tfilter_stecker(machine);\r\n\r\n\t\t// none of the machines have movable stators\r\n\t\t// disable the settings in strict mode\r\n\t\t$st_set.prop('disabled', true);\r\n\t\t$st_grd.prop('disabled', true);\r\n\r\n\t\t// reflector options\r\n\t\t$re_set.prop('disabled', ! machine.movable_reflector);\r\n\t\t$re_grd.prop('disabled', ! machine.movable_reflector);\r\n\t}",
"function updateMode(newMode) {\n mode = newMode; // sets global 'mode' variable\n\n // Toggle the correct mode button\n d3.select('div#modes')\n .selectAll('button')\n .attr('class', null);\n d3.select('div#modes')\n .selectAll('button#' + mode)\n .attr('class', 'hidden');\n\n // Toggle the correct sub controls\n d3.select('div#sub-controls')\n .selectAll('div')\n .attr('class', 'hidden');\n d3.select('div#sub-controls')\n .select('div#sub-controls-' + mode)\n .attr('class', null);\n\n // Enable/disable editing the command list\n if (mode === 'run') {\n command_list.option('disabled', true);\n d3.select('ul#commands').attr('class', null);\n resetAries();\n } else {\n command_list.option('disabled', false);\n d3.select('ul#commands')\n .attr('class', 'editable')\n .selectAll(\"li\")\n .attr('class','');\n }\n }",
"function showSimulation() {\r\n document.getElementById(\"simulationView\").style.display = \"block\";\r\n document.getElementById(\"propertiesInput\").style.display = \"none\";\r\n updateRestart();\r\n if (simulationParameters[\"interleaver\"]) {\r\n document.getElementById(\"interleaverSection\").style.display = \"block\";\r\n document.getElementById(\"deinterleaverSection\").style.display = \"block\";\r\n } else {\r\n document.getElementById(\"interleaverSection\").style.display = \"none\";\r\n document.getElementById(\"deinterleaverSection\").style.display = \"none\";\r\n\r\n }\r\n hideTransitionText();\r\n\r\n}",
"function setSelectMode() {\n mode = modes.SELECT\n GameScene.setRegionSelectPlaneVis(true)\n }",
"function update_run_selection(run_id) {\n $.ajax({\n url: '/runs',\n type: 'post',\n data: {run_id: run_id},\n success: function(data) {\n json = JSON.parse(data);\n $(\"#run_selection\").find('option').remove();\n\n ks = json.ks;\n for (var i = 0; i < ks.length; i++) {\n var op = $(\"<option />\").text(ks[i]);\n $(\"#run_selection\").append(op);\n };\n }\n });\n}",
"function changeBoardSize() {\n const boardSizeSelector = getById('board-size');\n if (mode === 'same-value') {\n boardSizeSelector.removeChild(boardSizeSelector.options[3]);\n } else {\n const option = createElement('option');\n option.value = '52';\n option.innerText = '52';\n boardSizeSelector.appendChild(option);\n }\n}",
"function displayModePatch() {\n\tif (PLAYER.type!=PLAYERTYPE) {\n\t\tPLAYERTYPE=PLAYER.type;\n\t\tif ($_modesel.val()==\"chMode\" || $_modesel.val()==\"rMode\") {\n\t\t\t$videowidth.removeClass().addClass('span1');\n\t\t\t$(\"#ytapiplayer\").attr(\"width\", '1').attr(\"height\", '1');\n\t\t}\n\n\t}\n}",
"function initSimon() {\n $('[data-action=start]').on('click', startGame);\n\n }",
"static toggleSimulation({ eTag, enabled, id }) {\n return HttpClient.patch(`${ENDPOINT}simulations/${id}`, { ETag: eTag, Enabled: enabled })\n .map(toSimulationModel)\n .catch(resolveConflict);\n }",
"function testbedOptionSave(){\n\tif(globalInfoType == \"JSON\"){\n devicesArr = getDevicesNodeJSON();\n deviceArr = getDevicesNodeJSON();\n\t}\n\n $(\"#deviceMenuPopUp\").dialog({\n modal: true,\n width: \"auto\",\n autoResize: true,\n maxHeight: 500,\n open: function(event, ui){\n $(this).parent().css('position', 'fixed');\n },\n\t\topen: function(event, ui) { $(\".ui-dialog-titlebar-close\").show(); }\n });\n $(\"#deviceMenuPopUp\").empty().load(\"pages/ConfigEditor/testbedOption.html\", function(){\n window['variable' + DeviceSanity[pageCanvas] ] = \"true\";\n for(var a=0; a<devicesArr.length; a++){\n if(devicesArr[a].DeviceName == \"\" || devicesArr[a].Status.toLowerCase() != \"\"){\n $(\"#bothTbID\").remove();\n $(\"#staticTbID\").remove();\n tbSelectOption();\n }else{\n $(\"#bothTbID\").remove();\n $(\"#staticTbID\").remove();\n $(\"#fileTypeSelectID\").prepend(\"<option value='both' id='bothTbID'>Both</option> <option value='static' id='staticTbID'>Static</option>\");\n tbSelectOption();\n }\n }\n for(var b=0; b<window['variable' + dynamicLineConnected[pageCanvas]].length; b++){\n if(window['variable' + dynamicLineConnected[pageCanvas]][b].DestinationDeviceObjectPath != \"\" || window['variable' + dynamicLineConnected[pageCanvas]][b].SourceDeviceObjectPath != \"\"){\n $(\"#checkenableint\").attr(\"disabled\", false);\n $(\"#checkconnectivity\").attr(\"disabled\", false);\n $(\"#checklinksanity\").attr(\"disabled\", false);\n $(\"#checkportmapping\").attr(\"disabled\", false);\n $(\"#checktgenconfig\").attr(\"disabled\", false)\n\n }else{\n $(\"#checkenableint\").attr(\"disabled\", true);\n $(\"#checkconnectivity\").attr(\"disabled\", true);\n $(\"#checklinksanity\").attr(\"disabled\", true);\n $(\"#checkportmapping\").attr(\"disabled\", true);\n $(\"#checktgenconfig\").attr(\"disabled\", true)\n }\n }\n/*\t\tif(lineConnected==[] || lineConnected.length==0){\n $(\"#checkenableint\").attr(\"disabled\", true);\n $(\"#checkconnectivity\").attr(\"disabled\", true);\n $(\"#checklinksanity\").attr(\"disabled\", true);\n $(\"#checkportmapping\").attr(\"disabled\", true);\n $(\"#checktgenconfig\").attr(\"disabled\", true)\n }*/\n if(window['variable' + DeviceSanity[pageCanvas] ].toString()==\"true\")$(\"#checkdevsanity\").prop('checked', true);\n if(Commit==\"true\")$(\"#checkcommit\").prop('checked',true);\n\n\n $(\".ui-dialog\").position({\n my: \"center\",\n at: \"center\",\n of: window\n });\n });\n return;\n\n\n}",
"function configure_event_handlers(){\n\n document.getElementById('btn-start').addEventListener(\"click\", btn_start_click_function);\n document.getElementById('btn-save').addEventListener(\"click\", btn_save_click_function);\n document.getElementById('btn-continue').addEventListener(\"click\", btn_continue_click_function);\n\n document.getElementById('game-mode-select').addEventListener(\"click\", game_mode_option_change_function);\n\n}",
"function updateAddEmiAnswerOptionsCount(){\n\t\tvar count = highestOptionId-currentOptions +1;\n\n\t\tif (currentOptions==(highestOptionId+1)) {\n\t\t\temiOptionAddLink.hide();\n\t\t\taddEmiAnswerOptionsSelect.hide();\n\t\t}else{\n\t\t\temiOptionAddLink.show();\n\t\t\taddEmiAnswerOptionsSelect.show();\n\t\t}\n\t\t\n\t\taddEmiAnswerOptionsSelect.empty();\n\t\tfor (j=1; j<=count; j++) {\n\t\t\tif (j == 1) {\n\t\t\t\taddEmiAnswerOptionsSelect.append('<option selected=\"selected\" value=\"'+ j +'\">'+ j +'</option>');\n\t\t\t}\n\t\t\telse {\n\t\t\t\taddEmiAnswerOptionsSelect.append('<option value=\"'+ j +'\">'+ j +'</option>');\n\t\t\t}\n\t\t}\n\t}",
"function addRulesetTypesToSelect() {\n var selectBox = document.getElementById(\"type\");\n for (let i = 0; i < ruleSets.length; i++) {\n selectBox.add(new Option(ruleSets[i].name, i));\n }\n\n updateFieldsWithTypeDefaults(ruleSets[0]);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
crop the image from the webcam region of interest: center portion | function cropImage(img) {
const size = Math.min(img.shape[0], img.shape[1]);
const centerHeight = img.shape[0] / 2;
const beginHeight = centerHeight - (size / 2);
const centerWidth = img.shape[1] / 2;
const beginWidth = centerWidth - (size / 2);
return img.slice([beginHeight, beginWidth, 0], [size, size, 3]);
} | [
"function cropCanvas(canvas, ctx) {\n var imgWidth = ctx.canvas.width;\n var imgHeight = ctx.canvas.height;\n var imageData = ctx.getImageData(0, 0, imgWidth, imgHeight),\n data = imageData.data,\n getAlpha = function (x, y) {\n return data[(imgWidth * y + x) * 4 + 3];\n },\n scanY = function (fromTop) {\n var offset = fromTop ? 1 : -1;\n\n // loop through each row\n for (var y = fromTop ? 0 : imgHeight - 1; fromTop ? (y < imgHeight) : (y > -1); y += offset) {\n\n // loop through each column\n for (var x = 0; x < imgWidth; x++) {\n if (getAlpha(x, y)) {\n return y;\n }\n }\n }\n return null; // all image is white\n },\n scanX = function (fromLeft) {\n var offset = fromLeft ? 1 : -1;\n\n // loop through each column\n for (var x = fromLeft ? 0 : imgWidth - 1; fromLeft ? (x < imgWidth) : (x > -1); x += offset) {\n\n // loop through each row\n for (var y = 0; y < imgHeight; y++) {\n if (getAlpha(x, y)) {\n return x;\n }\n }\n }\n return null; // all image is white\n };\n\n var cropTop = scanY(true),\n cropBottom = scanY(false),\n cropLeft = scanX(true),\n cropRight = scanX(false);\n\n var relevantData = ctx.getImageData(cropLeft, cropTop, cropRight - cropLeft, cropBottom - cropTop);\n canvas.width = cropRight - cropLeft + imageBorder;\n canvas.height = cropBottom - cropTop + imageBorder * 1.3;\n\n\n\n ctx.putImageData(relevantData, imageBorder / 2, imageBorder / 2);\n\n\n\n }",
"_crop(section) {\n engine.trace(`cropping '${ this._name }' at { x: ${ section.x }, y: ${ section.y }, w: ${ section.w }, h: ${ section.h } }...`);\n\n return sharp(this._file)\n .extract({ left: section.x, top: section.y, width: section.w, height: section.h })\n .toBuffer()\n .then(buffer => sharp(buffer).toFile(this._file)) // only way to save back to same filename in sharp\n .catch(err => engine.error('failure cropping'))\n .finally(() => engine.trace('cropped'));\n }",
"function croppedImage () {\n ctx.fillStyle = \"#000\"\n ctx.fillRect(0, 0, w, h)\n starfield()\n\n let img = new Image()\n img.src = \"res/img/kerrigan.png\"\n img.addEventListener('load', drawCropped, false)\n\n function drawCropped() {\n ctx.drawImage(img, 500, 500)\n\n // cropped\n for (let i = 0; i < 10; i++) {\n ctx.drawImage(\n img,\n // source\n 0, 0, 500, 500,\n // destination location\n i * 10, i * 10,\n // destination scale\n i * 0.2 * 170, i * 0.2 * 170\n )\n }\n }\n}",
"initCropper(image,controlPanel = null) {\n let size = this.activeCrop.size.split('x');\n let width = Math.round(parseInt(size[0]));\n let height = Math.round(parseInt(size[1]));\n\n // Aspect ratio is worked out by dividing the width and then the height by the greatest common denominator.\n function gcd (a, b) { // recursive\n return (b === 0) ? a : gcd (b, a%b);\n }\n let r = gcd (width, height);\n //console.log( (size[0] / r) + ' / ' + (size[1] / r));\n\n let cropper = new Cropper(image, {\n viewMode: 1,\n dragMode: 'move',\n aspectRatio: (width / r) / (height / r),\n autoCropArea: 1\n });\n image.addEventListener('ready', function (e) {\n this.cropper = cropper;\n image.parentNode.style.visibility = 'visible';\n if(controlPanel !== null) {\n this.buildControlPanel(controlPanel);\n }\n }.bind(this));\n }",
"_redraw() {\n\t\tlet p = this._points;\n\n\t\tlet leftX = p.nw.x;\n\t\tlet leftY = p.nw.y;\n\t\tlet size = this._getSize();\n\n\t\tthis._dom.cropTop.style.left = leftX + \"px\";\n\t\tthis._dom.cropTop.style.width = size.width + \"px\";\n\t\tthis._dom.cropTop.style.height = leftY + \"px\";\n\n\t\tthis._dom.cropBottom.style.left = leftX + \"px\";\n\t\tthis._dom.cropBottom.style.width = size.width + \"px\";\n\t\tthis._dom.cropBottom.style.height = (this._dim.areaHeight - p.sw.y) + \"px\";\n\n\t\tthis._dom.cropLeft.style.width = leftX + \"px\";\n\t\tthis._dom.cropLeft.style.height = this._dim.areaHeight + \"px\";\n\n\t\tthis._dom.cropRight.style.width = (this._dim.areaWidth - p.ne.x) + \"px\";\n\t\tthis._dom.cropRight.style.height = this._dim.areaHeight + \"px\";\n\n\t\tthis._dom.cropMiddle.style.width = size.width + \"px\";\n\t\tthis._dom.cropMiddle.style.height = size.height + \"px\";\n\t\tthis._dom.cropMiddle.style.left = leftX + \"px\";\n\t\tthis._dom.cropMiddle.style.top = leftY + \"px\";\n\t}",
"function cropBoundingBox(r, width, height) {\n\t\tif (r.x < 0)\n\t\t\tr.x = 0;\n\t\tif (r.y < 0)\n\t\t\tr.y = 0;\n\t\tif ((r.x + r.width) > width)\n\t\t\tr.width = width - r.x;\n\t\tif ((r.y + r.height) > height)\n\t\t\tr.height = height - r.y;\n\n\t\treturn r;\n\t}",
"crop(data, xspan, yspan) {\n var halfx = xspan / 2,\n halfy = yspan / 2;\n\n return _.filter(data, function(entry) {\n return -halfx < entry.mercator[0] && halfx > entry.mercator[0]\n && -halfy < entry.mercator[1] && halfy > entry.mercator[1];\n });\n }",
"function applyCropping(obj){\n\t\tobj.on(\"mousedblclick\", () => {\n\t\t\tobj.cropPhotoStart()\n\t\t\tobj.activeCrop.initEventListeners()\n\t\t})\n\t\tobj.initEventListeners()\n\t\tobj.setFitting(\"cover\");\n\t}",
"initializeCropper() {\n this.image.style.display = 'block';\n\n this.cropper = new Cropper(image, {\n aspectRatio: this.aspectRatio,\n responsive: true,\n guides: true\n });\n\n window.setTimeout(this._setCropperToCoverWholeImage, 100);\n }",
"onSkippedCrop() {\n const attachment = this.frame.state().get('selection').first().toJSON()\n this.setImageFromAttachment(attachment)\n }",
"function getCrops(filename) {\n const inp = cv.imread(`./uploads/${filename}`);\n // const borderWidth = Math.floor(inp.sizes[0]*0.1)\n // const img = inp.copyMakeBorder(borderWidth, borderWidth, borderWidth, borderWidth, cv.BORDER_CONSTANT, new cv.Vec3(255,255,255))\n const img = inp;\n const gray = img.cvtColor(cv.COLOR_BGR2GRAY);\n let threshold = gray.adaptiveThreshold(255, cv.ADAPTIVE_THRESH_GAUSSIAN_C,\n cv.THRESH_BINARY, 151, 25);\n let blurred = threshold.gaussianBlur(new cv.Size(31, 31), 51, 3);\n blurred = blurred.medianBlur(11);\n let thresh2 = blurred.threshold(240, 255, cv.THRESH_BINARY);\n // blurred = threshold.gaussianBlur(new cv.Size(101, 101), 51, 7)\n // thresh2 = blurred.threshold(235, 255, cv.THRESH_BINARY)\n // blurred = threshold.gaussianBlur(new cv.Size(101, 101), 51, 7)\n // thresh2 = blurred.threshold(235, 255, cv.THRESH_BINARY)\n // cv.imshow('a window name', gray.resize(0, 0, 0.4, 0.4))\n // cv.waitKey()\n // cv.imshow('a window name', threshold.resize(0, 0, 0.4, 0.4))\n // cv.waitKey()\n // cv.imshow('a window name', blurred.resize(0, 0, 0.4, 0.4))\n // cv.waitKey()\n let contours = thresh2.findContours(cv.RETR_TREE, cv.CHAIN_APPROX_NONE);\n // Create first mask for rotation\n let mask = new cv.Mat(img.rows, img.cols, cv.CV_8U, 255);\n\n // Draw contours on the mask with size and ratio of borders for threshold\n contours.forEach((cnt) => {\n let size = cnt.area;\n let x = cnt.boundingRect().x;\n let y = cnt.boundingRect().y;\n let w = cnt.boundingRect().width;\n let h = cnt.boundingRect().height;\n if (img.cols * img.rows / 2 > size && size > 35 && w * 2.5 > h && h >\n img.cols * 0.01) {\n // console.log(cnt)\n mask.drawContours([cnt], new cv.Vec3(0, 0, 0), -1, cv.LINE_8, -1);\n }\n });\n\n // Connect neighbour contours and select the biggest one (text).\n let kernel = new cv.Mat(11, 100, cv.CV_8U, 1);\n let gray_op = mask.morphologyEx(kernel, cv.MORPH_OPEN);\n let threshold_op = gray_op.threshold(170, 255, cv.THRESH_BINARY_INV);\n\n // Remove holes\n let floodfill = threshold_op.copy();\n let floodMask = new cv.Mat(\n threshold_op.sizes[0],\n threshold_op.sizes[1],\n cv.CV_8U,\n 0,\n );\n floodfill.floodFill(new cv.Point2(0, 0), 255);\n let floodfillInv = floodfill.bitwiseNot();\n let out = threshold_op.bitwiseOr(floodfillInv);\n let contours_op = out.findContours(cv.RETR_TREE, cv.CHAIN_APPROX_NONE);\n\n // cv.imshow('a window name', mask.resize(0, 0, 0.4, 0.4))\n // cv.waitKey()\n // cv.imshow('a window name', gray_op.resize(0, 0, 0.4, 0.4))\n // cv.waitKey()\n // cv.imshow('a window name', threshold_op.resize(0, 0, 0.4, 0.4))\n // cv.waitKey()\n // cv.imshow('a window name', out.resize(0, 0, 0.4, 0.4))\n // cv.waitKey()\n\n contours_op = contours_op.filter(cnt => {\n return img.cols * img.rows / 2 > cnt.area && cnt.area > 10;\n })\n\n contours_op.sort((a, b) => {\n return a.boundingRect().y - b.boundingRect().y;\n });\n\n let names = [];\n contours_op.forEach((cont, ind) => {\n gray.drawRectangle(cont.boundingRect(), new cv.Vec3(0, 0, 255), 3);\n // cv.imshow('a window name', threshold.getRegion(cont.boundingRect()))\n // cv.waitKey()\n cv.imwrite(`./crops/${filename}-${ind}.jpg`,\n threshold.getRegion(cont.boundingRect()));\n // out.push(gray.getRegion(cont.boundingRect()).getData())\n names.push(`${filename}-${ind}.jpg`);\n // Replace region with white so we don't do things twice\n gray.drawRectangle(cont.boundingRect(), new cv.Vec3(255, 255, 255), -1);\n });\n // cv.imshow('a window name', gray.resize(0, 0, 0.4, 0.4))\n // cv.waitKey()\n // console.log(names);\n return names;\n}",
"function center_view(x, y) {\n if (x === undefined) x = 0;\n if (y === undefined) y = 0;\n\n // compute view\n view.rect.w = view.pix.w / view.scale.x;\n view.rect.h = view.pix.h / view.scale.y;\n view.rect.x = x - view.rect.w / 2;\n view.rect.y = y - view.rect.h / 2;\n \n step = step_pix / view.scale.x;\n}",
"function center_pivot(piece)\n{\n\tpiece.pivot_x = Math.floor(piece.width / 2);\n\tpiece.pivot_y = Math.floor(piece.height / 2);\n}",
"function getCameraCropping(i) {\n\tobs.send('GetSceneItemProperties', {\n\t\t'scene-name': nodecg.bundleConfig.obsScenes.gameLayout,\n\t\t'item': cameraCaptureKey[i]\n\t}, (err, data) => {\n\t\tif (!err)\n\t\t\tcropCache[i] = data.crop;\n\t});\n}",
"function centerImage() {\n let container = document.getElementById(\"sliderImages\");\n const containerHeight = parseInt(window.getComputedStyle(container,null).getPropertyValue(\"height\"), 10);\n const topPos = (imageContainer.height - containerHeight)/2;\n if(topPos > 0) {\n imageContainer.style.top = `-${topPos}px`;\n }\n}",
"function applyCropping() {\n\t// Setup options for this rack.\n\tvar options = {\n\t\t'scene-name': nodecg.bundleConfig.obsScenes.gameLayout,\n\t\t'item': cameraCaptureKey[capture],\n\t\t'crop': cropCache[capture]\n\t};\n\n\t// Send settings to OBS.\n\tobs.send('SetSceneItemProperties', options).catch((err) => {\n\t\tnodecg.log.warn(`Cannot change OBS source settings [${options['scene-name']}: ${options.item}]: ${err.error}`);\n\t});\n}",
"trimEdges(stage) {\n if (!stage.srcCtx) {\n return;\n }\n\n const srcData = stage.srcCtx.getImageData(0, 0, stage.srcSize.w, stage.srcSize.h);\n\n // Always trim by top-left pixel color\n const trimPixel = getPixel_(stage, srcData, 0, 0);\n\n let insetRect = {l:0, t:0, r:0, b:0};\n let x, y;\n\n // Trim top\n trimTop:\n for (y = 0; y < stage.srcSize.h; y++) {\n for (x = 0; x < stage.srcSize.w; x++) {\n if (getPixel_(stage, srcData, x, y) != trimPixel) {\n break trimTop;\n }\n }\n }\n insetRect.t = y;\n // Trim left\n trimLeft:\n for (x = 0; x < stage.srcSize.w; x++) {\n for (y = 0; y < stage.srcSize.h; y++) {\n if (getPixel_(stage, srcData, x, y) != trimPixel) {\n break trimLeft;\n }\n }\n }\n insetRect.l = x;\n // Trim bottom\n trimBottom:\n for (y = stage.srcSize.h - 1; y >= 0; y--) {\n for (x = 0; x < stage.srcSize.w; x++) {\n if (getPixel_(stage, srcData, x, y) != trimPixel) {\n break trimBottom;\n }\n }\n }\n insetRect.b = stage.srcSize.h - y - 1;\n // Trim right\n trimRight:\n for (x = stage.srcSize.w - 1; x >= 0; x--) {\n for (y = 0; y < stage.srcSize.h; y++) {\n if (getPixel_(stage, srcData, x, y) != trimPixel) {\n break trimRight;\n }\n }\n }\n insetRect.r = stage.srcSize.w - x - 1;\n\n if (insetRect.l <= 0 && insetRect.t <= 0 && insetRect.r <= 0 && insetRect.b <= 0) {\n // No-op\n return;\n }\n\n // Build a new stage with inset values\n const size = {\n w: stage.srcSize.w - insetRect.l - insetRect.r,\n h: stage.srcSize.h - insetRect.t - insetRect.b\n };\n\n const rects = {\n contentRect: constrain_(size, {\n x: stage.contentRect.x - insetRect.l,\n y: stage.contentRect.y - insetRect.t,\n w: stage.contentRect.w,\n h: stage.contentRect.h\n }),\n stretchRect: constrain_(size, {\n x: stage.stretchRect.x - insetRect.l,\n y: stage.stretchRect.y - insetRect.t,\n w: stage.stretchRect.w,\n h: stage.stretchRect.h\n }),\n opticalBoundsRect: constrain_(size, {\n x: stage.opticalBoundsRect.x - insetRect.l,\n y: stage.opticalBoundsRect.y - insetRect.t,\n w: stage.opticalBoundsRect.w,\n h: stage.opticalBoundsRect.h\n })\n };\n\n stage.name = `${stage.name}-EDGES_TRIMMED`;\n let newCtx = studio.Drawing.context(size);\n newCtx.drawImage(stage.srcCtx.canvas,\n insetRect.l, insetRect.t, size.w, size.h,\n 0, 0, size.w, size.h);\n stage.loadSourceImage(newCtx, rects);\n }",
"function center_image(){\n\t\tvar theWindow = $(window),\n\t\t $bg = $(\".featured-img\"),\n\t\t aspectRatio = $bg.width() / $bg.height();\n\t\t \t\t\t \t\t\n\t\tfunction resizeBg() {\n\t\t\tif ( (theWindow.width() / theWindow.height()) < aspectRatio ) {\n\t\t\t $bg\n\t\t\t \t.removeClass('bgwidth')\n\t\t\t \t.addClass('bgheight');\n\t\t\t} else {\n\t\t\t $bg\n\t\t\t \t.removeClass('bgheight')\n\t\t\t \t.addClass('bgwidth');\n\t\t\t}\t\t\t\t\t\n\t\t}\n\t\t \t\t\t\n\t\ttheWindow.resize(resizeBg).trigger(\"resize\");\t\t\n\t}",
"addMinimapCutout(posX, posY, minimapWidth, minimapHeight) {\n let cutout = new Phaser.GameObjects.Graphics(this);\n cutout.fillRect(posX, posY, minimapWidth, minimapHeight);\n // let mask = new Phaser.Display.Masks.GeometryMask(this, cutout);\n let mask = new Phaser.Display.Masks.BitmapMask(this, cutout);\n // mask.invertAlpha = true;\n // lowerPanel.mask = mask;\n this.lowerPanelBackground.setMask(mask);\n this.lowerPanelBackground.mask.invertAlpha = true;\n }",
"cropX(data, angle) {\n var halfangle = angle / 2;\n\n return _.filter(data, function(entry) {\n return -halfangle < entry.mercator[0] && halfangle > entry.mercator[0];\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates a new main_evolution_obj from the slider values. the main_evolution_obj is global. | function create_main_obj(){
chart_container.show();
var newValues={};
newValues.pop=population_slider.slider("value");
newValues.genome=genome_slider.slider("value");
newValues.mutate=mutation_prob_slider.slider("value");
newValues.fight=tournament_size_slider.slider("value");
newValues.gens=generations_slider.slider("value");
main_evolution_obj = new ea(newValues.pop, newValues.genome, newValues.mutate, newValues.fight);
} | [
"function createSlider() {\n\n //the value that we'll give the slider - if it's a range, we store our value as a comma separated val but this slider expects an array\n var sliderVal = null;\n\n //configure the model value based on if range is enabled or not\n if ($scope.model.config.enableRange == true) {\n //If no value saved yet - then use default value\n //If it contains a single value - then also create a new array value\n if (!$scope.model.value || $scope.model.value.indexOf(\",\") == -1) {\n var i1 = parseFloat($scope.model.config.initVal1);\n var i2 = parseFloat($scope.model.config.initVal2);\n sliderVal = [\n isNaN(i1) ? $scope.model.config.minVal : (i1 >= $scope.model.config.minVal ? i1 : $scope.model.config.minVal),\n isNaN(i2) ? $scope.model.config.maxVal : (i2 > i1 ? (i2 <= $scope.model.config.maxVal ? i2 : $scope.model.config.maxVal) : $scope.model.config.maxVal)\n ];\n }\n else {\n //this will mean it's a delimited value stored in the db, convert it to an array\n sliderVal = _.map($scope.model.value.split(','), function (item) {\n return parseFloat(item);\n });\n }\n }\n else {\n //If no value saved yet - then use default value\n if ($scope.model.value) {\n sliderVal = parseFloat($scope.model.value);\n }\n else {\n sliderVal = $scope.model.config.initVal1;\n }\n }\n\n // Initialise model value if not set\n if (!$scope.model.value) {\n setModelValueFromSlider(sliderVal);\n }\n\n //initiate slider, add event handler and get the instance reference (stored in data)\n var slider = $element.find('.slider-item').bootstrapSlider({\n max: $scope.model.config.maxVal,\n min: $scope.model.config.minVal,\n orientation: $scope.model.config.orientation,\n selection: $scope.model.config.reversed ? \"after\" : \"before\",\n step: $scope.model.config.step,\n precision: $scope.model.config.precision,\n tooltip: $scope.model.config.tooltip,\n tooltip_split: $scope.model.config.tooltipSplit,\n tooltip_position: $scope.model.config.tooltipPosition,\n handle: $scope.model.config.handle,\n reversed: $scope.model.config.reversed,\n ticks: $scope.model.config.ticks,\n ticks_positions: $scope.model.config.ticksPositions,\n ticks_labels: $scope.model.config.ticksLabels,\n ticks_snap_bounds: $scope.model.config.ticksSnapBounds,\n formatter: $scope.model.config.formatter,\n range: $scope.model.config.enableRange,\n //set the slider val - we cannot do this with data- attributes when using ranges\n value: sliderVal\n }).on('slideStop', function (e) {\n var value = e.value;\n angularHelper.safeApply($scope, function () {\n setModelValueFromSlider(value);\n });\n }).data('slider');\n }",
"function SliderConfig() {\n\n _self = this;\n\n this.data = {\n barsCount: config.bars.count,\n maxDecibels: config.analyser.maxDecibels,\n minDecibels: config.analyser.minDecibels,\n playerWidth: config.player.width,\n rectPadding: config.rect.padding,\n rectVelocity: config.rect.velocity,\n wheelLineWidth: config.wheel.lineWidth,\n wheelRadius: config.wheel.radius\n };\n this.sliders = {};\n}",
"function initialSliderValues() {\n\t// set initial values for config\n\tupdateSliderValue('cannyConfigThreshold1Slider',\n\t\t\t'cannyConfigThreshold1Textbox');\n\tupdateSliderValue('cannyConfigThreshold2Slider',\n\t\t\t'cannyConfigThreshold2Textbox');\n\tupdateSliderValue('houghConfigRhoSlider', 'houghConfigRhoTextbox');\n\tupdateSliderValue('houghConfigThetaSlider', 'houghConfigThetaTextbox');\n\tupdateSliderValue('houghConfigThresholdSlider',\n\t\t\t'houghConfigThresholdTextbox');\n\tupdateSliderValue('houghConfigMinLineLengthSlider',\n\t\t\t'houghConfigMinLineLengthTextbox');\n\tupdateSliderValue('houghConfigMaxLineGapSlider',\n\t\t\t'houghConfigMaxLineGapTextbox');\n\tupdateSliderValue('houghConfigMaxLineGapSlider',\n\t\t\t'houghConfigMaxLineGapTextbox');\n\n\t// set initial values for cam config\n\tupdateSliderValue('camEcSlider', 'camEcTextbox');\n\tupdateSliderValue('camBrSlider', 'camBrTextbox');\n\tupdateSliderValue('camSaSlider', 'camSaTextbox');\n}",
"function Collider() {}",
"addSlider(slider) {\n this.slider = slider;\n }",
"function onSlide(event, ui) {\n\tvar values = ui.values;\n\tCLUB.lowValue = values[0];\n\tCLUB.highValue = values[1];\n\tupdateSliderValues();\n\tsetSelectedData();\n}",
"function updateSliderValues() {\n\t$('.slider_min').text(CLUB.lowValue);\n\t$('.slider_max').text(CLUB.highValue);\n}",
"function geneCallback(g, name) {\n g.nameEle = g.getElementsByClassName(\"name\")[0];\n g.name = name;\n guigenes[g.name] = g;\n g.minEle = g.getElementsByClassName(\"min\")[0];\n g.maxEle = g.getElementsByClassName(\"max\")[0];\n g.deltaEle = g.getElementsByClassName(\"delta\")[0];\n g.stepEle = g.getElementsByClassName(\"step\")[0];\n g.currentEle = g.getElementsByClassName(\"current\")[0];\n g.sliderEle = g.getElementsByClassName(\"slider\")[0];\n g.addgeneEle = g.getElementsByClassName(\"addgene\")[0];\n g.genehelpEle = g.getElementsByClassName(\"help\")[0];\n g.minEle.onchange = minEleonchange;\n g.maxEle.onchange = maxEleonchange;\n g.deltaEle.onchange = deltaEleonchange;\n g.stepEle.onchange = stepEleonchange;\n g.minEle.oninput = minEleonchange;\n g.maxEle.oninput = maxEleonchange;\n g.deltaEle.oninput = deltaEleonchange;\n g.stepEle.oninput = stepEleonchange;\n g.nameEle.onchange = nameEleonchange;\n g.onkeydown = geneonkeydown;\n g.currentEle.onchange = currentEleonchange;\n g.currentEle.oninput = currentEleonchange;\n g.currentEle.onclick = currentEleonclick;\n g.currentEle.onfocus = currentEleonfocus;\n g.sliderEle.onchange = sliderEleonchange;\n g.sliderEle.oninput = sliderEleonchange;\n g.nameEle.onmouseover = elemouseover;\n g.nameEle.onmouseout = elemouseout;\n //g.sliderEle.onkeypress = sliderEleonkeypress;\n g.addgeneEle.onclick = addgeneEleonclick;\n var gdx = genedefs[g.name];\n g.minEle.value = gdx.min;\n g.maxEle.value = gdx.max;\n g.deltaEle.value = gdx.delta;\n g.stepEle.value = gdx.step;\n g.currentEle.value = gdx.def;\n g.currentEle.step = gdx.step;\n if (g.genehelpEle !== null) {\n if (gdx.help !== null)\n g.genehelpEle.innerHTML = \"<b>\" + g.name + \"</b><br>\" + gdx.help;\n else\n g.genehelpEle.style.display = \"none\";\n }\n}",
"function minEleonchange(evt) {\n var uig = getg(this);\n uig.sliderEle.min = this.value*1;\n genedefs[uig.name].min = this.value*1;\n}",
"onSliderValueChanged() {\n this.setBase();\n const label = `${this.name}: ${JSON.stringify(this.value)}`;\n ChromeGA.event(ChromeGA.EVENT.SLIDER_VALUE, label);\n }",
"onDemandCreateGUI() {\n \n if (this.internal.parentDomElement===null)\n return;\n \n this.internal.parentDomElement.empty();\n \n let basediv=webutil.creatediv({ parent : this.internal.parentDomElement});\n this.internal.domElement=basediv;\n \n let f1 = new dat.GUI({autoPlace: false});\n basediv.append(f1.domElement);\n\n // Global Properties\n let s1_on_cb=(e) => {\n let ind=this.internal.data.allnames.indexOf(e);\n this.setCurrentGrid(ind);\n };\n\n this.internal.data.allnames=[];\n for (let i=0;i<this.internal.multigrid.getNumGrids();i++) {\n this.internal.data.allnames.push(this.internal.multigrid.getGrid(i).description);\n }\n \n let sl=f1.add(this.internal.data,'currentname',this.internal.data.allnames).name(\"Current Grid\");\n sl.onChange(s1_on_cb);\n\n let dp=f1.add(this.internal.data,'showmode',this.internal.data.allshowmodes).name(\"Grids to Display\");\n let dp_on_cb=() => {\n this.showhidemeshes();\n this.updategui(true);\n };\n dp.onChange(dp_on_cb);\n\n webutil.removedatclose(f1);\n\n \n // --------------------------------------------\n let ldiv=$(\"<H4></H4>\").css({ 'margin':'15px'});\n basediv.append(ldiv);\n\n this.internal.landlabelelement=webutil.createlabel( { type : \"success\",\n name : \"Current Electrode Properties\",\n parent : ldiv,\n });\n let sbar=webutil.creatediv({ parent: basediv});\n let inlineform=webutil.creatediv({ parent: sbar});\n let elem1=webutil.creatediv({ parent : inlineform,\n css : {'margin-top':'20px', 'margin-left':'10px'}});\n \n let elem1_label=$(\"<span>Electrode: </span>\");\n elem1_label.css({'padding':'10px'});\n elem1.append(elem1_label);\n this.internal.currentelectrodeselect=webutil.createselect({parent : elem1,\n values : [ 'none' ],\n callback : (e) => {\n this.selectElectrode(e.target.value,true);\n this.centerOnElectrode();\n },\n });\n\n this.internal.checkbuttons={};\n\n let sbar2=webutil.creatediv({ parent: basediv});\n for (let i=0;i<PROPERTIES.length;i++) {\n this.internal.checkbuttons[PROPERTIES[i]]=\n webutil.createcheckbox({\n name: PROPERTIES[i],\n type: \"info\",\n checked: false,\n parent: sbar2,\n css: { 'margin-left': '5px' ,\n 'margin-right': '5px',\n 'width' : '100px'}\n });\n }\n \n \n \n\n // ----------- Landmark specific stuff\n\n if (this.internal.gridPropertiesGUI===null) {\n const f2 = new dat.GUI({autoPlace: false});\n console.log('F2=',f2,JSON.stringify(this.internal.data));\n \n console.log('Creating modal');\n let modal=webutil.createmodal(\"Grid Properties\",\"modal-sm\");\n this.internal.gridPropertiesGUI=modal.dialog;\n modal.body.append(f2.domElement);\n\n \n console.log('Radius=',this.internal.data.radius);\n \n f2.add(this.internal.data, 'radius',0.5,8.0).name(\"Radius\").step(0.5).onChange(() => {\n let grid=this.internal.multigrid.getGrid(this.internal.currentgridindex);\n grid.radius=this.internal.data.radius;\n this.updateMeshes(true);\n });\n \n console.log('Color=',this.internal.data.color);\n \n f2.addColor(this.internal.data, 'color').name(\"Landmark Color\").onChange(()=> { \n this.updatecolors();\n });\n \n webutil.removedatclose(f2);\n this.internal.folders=[f1, f2];\n } else {\n this.internal.folders[0]=f1;\n }\n // Save self for later\n \n // ---------------\n // rest of gui \n // ---------------\n\n let bbar0=webutil.createbuttonbar({ parent: basediv,\n css : {'margin-top': '20px','margin-bottom': '10px'}});\n\n \n let update_cb=() => { this.updateGridProperties();};\n webutil.createbutton({ type : \"primary\",\n name : \"Display Properties\",\n position : \"bottom\",\n tooltip : \"Click this to set advanced display properties for this set (color,radius)\",\n parent : bbar0,\n callback : update_cb,\n });\n\n let load_cb=(f) => { this.loadMultiGrid(f); };\n webfileutil.createFileButton({ type : \"warning\",\n name : \"Load\",\n position : \"bottom\",\n tooltip : \"Click this to load points from either a .mgrid or a .bisgrid file\",\n parent : bbar0,\n callback : load_cb,\n },{\n filename : '',\n title : 'Select file to load current landmark set from',\n filters : [ { name: 'Landmark Files', extensions: ['bisgrid','land' ]}],\n save : false,\n suffix : \".bisgrid,.mgrid\",\n });\n\n let save_cb=(f) => {\n f=f || 'landmarks.bisgrid';\n console.log('f=',f);\n let suffix=f.split(\".\").pop();\n if (suffix===\"land\")\n return this.exportMultiGrid(f);\n else\n return this.saveMultiGrid(f);\n };\n\n\n \n webfileutil.createFileButton({ type : \"primary\",\n name : \"Save\",\n position : \"bottom\",\n tooltip : \"Click this to save points to a .bisgrid or .mgrid file\",\n parent : bbar0,\n callback : save_cb,\n },\n {\n filename : '',\n title : 'Select file to load current landmark set from',\n filters : [ { name: 'Landmark Files', extensions: ['bisgrid','land' ]}],\n save : true,\n suffix : \".bisgrid,.mgrid\",\n initialCallback : () => { return this.getInitialSaveFilename(); },\n });\n\n \n webutil.createbutton({ type : \"info\",\n name : \"Multisnapshot (Current Grid)\",\n parent : bbar0,\n css : {\n 'margin-top': '20px',\n 'margin-left': '10px'\n },\n callback : () => { this.multisnapshot(false).catch( (e) => { console.log(e);});}\n });\n\n webutil.createbutton({ type : \"danger\",\n name : \"Multisnapshot (All Grids)\",\n parent : bbar0,\n css : {\n 'margin-top': '20px',\n 'margin-left': '10px'\n },\n callback : () => { this.multisnapshot(true).catch( (e) => { console.log(e);});}\n });\n\n \n webutil.tooltip(this.internal.parentDomElement);\n \n // ----------------------------------------\n // Now create modal\n // ----------------------------------------\n\n \n\n }",
"function SliderContext() {\n /**\n * Flag that determines if slide can or cannot be changed (for user request)\n *\n * @member SliderContext\n */\n this.canChangeSlide = true;\n /**\n * Default Slider setting object (@see Slider)\n *\n * @member SliderContext\n */\n this.defaults = null;\n /**\n * Navigation object (@see Navigation)\n *\n * @member SliderContext\n */\n this.navigation = null;\n /**\n * Slider object that this context is attached to.\n *\n * @member SliderContext\n */\n this.owner = null;\n /**\n * Flag that determines if change of a slide can or can not be scheduled.\n *\n * @member SliderContext\n */\n this.preventScheduling = false;\n /**\n * Slider setting object\n *\n * @member SliderContext\n */\n this.settings = null;\n /**\n * Instance of Timer class (@see Timer) that is used to store how much\n * time is left to change the slide.\n *\n * @member SliderContext\n */\n this.slideTimer = new Timer();\n /**\n * Instance of TimeIndicator class (@see TimeIndicator)\n *\n * @member SliderContext\n */\n this.timeIndicator = null;\n /**\n * Timers array.\n *\n * @member SliderContext\n */\n this.timers = [];\n /**\n * Last timeout identifier.\n *\n * @member SliderContext\n */\n this.timeoutId = null;\n /**\n * Transition (@see XA.component.carousels.Transitions.Transition) used while changing slides\n *\n * @member SliderContext\n */\n this.transition = null;\n /**\n * Transition settings object (@see XA.component.carousels.Transitions.TransitionSettings)\n *\n * @member SliderContext\n */\n this.transitionSettings = new XA.component.carousels.Transitions.TransitionSettings();\n /**\n * jQuery object that contains all slides\n *\n * @member SliderContext\n */\n this.$slides = null;\n /**\n * jQuery object that contains the element that wraps slides\n *\n * @member SliderContext\n */\n this.$wrapper = null;\n /**\n * Reference to method that should change current slide\n *\n * @member SliderContext\n */\n this.changeCurrentSlide = null;\n /**\n * Reference to method that should return jQuery object with current slide\n *\n * @member SliderContext\n */\n this.getCurrentSlide = null;\n\n this.timers.push(this.slideTimer);\n }",
"function getSliderValue() {\n if (!AgeRecalculating) {//todo: weird bug that a second map-move is asked with strange params\n AgeRecalculating = true;\n //get center from map and convert to pix\n slider_lastvalue = slider_value;\n slider_value = 650 - ((timeslider.center.lat + 48.75) / 97.5 * 650);\n getSeqDetails(slider_value, \"closest\");\n \n }\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 }",
"constructor(gameEngine, topLeftCornerX, topLeftCornerY, ctx, level) {\n Object.assign(this, {\n gameEngine,\n topLeftCornerX,\n topLeftCornerY,\n ctx,\n level,\n });\n\n // interact with the user entity that is fielded in sceneManager entity\n this.user = this.gameEngine.camera.user;\n\n this.menuBoxWidth = 140;\n this.menuBoxHeight = 590;\n\tthis.widthScale = widthScaling();\n\t\n this.selectedIcon = \"none\";\n this.storeIcons = [];\n this.towerImagesArray = this.retrieveTowerIconImages();\n\n\t// create the icon buttons for the menu\n this.initializeIcons();\n\t\n\t// create the mouse interactions for the tower store menu\t\n\tthis.towerStoreClick = this.createMouseClick(this);\n\tthis.towerStoreMove = this.createMouseMove(this);\n\tthis.implementMouseInteractions();\n }",
"function sliderInit(options) {\r\n\r\n // na strance mame tri bloky pro zobrazeni aktualnich hodnot, ktere mame nastavene pomoci slideru\r\n // id bloku: #amount, #repayment-period a #procentual-repayment\r\n\r\n\r\n /* ------------------------------------------------------------------------------------------------------- */\r\n /* ------------------------------------------------------------------------------------------------------- */\r\n /* ---------------------------------- #AMOUNT SLIDER --------------------------------------------------- */\r\n /* ------------------------------------------------------------------------------------------------------- */\r\n\r\n //inicializuje se slider #amount-slider s nastavenim, ktere jsme dostali na zaklade hodnoty #select\r\n // popis toho jak se zjistuje options je ukazan v metode setRepaymentOptions();\r\n $(\"#amount-slider\").slider(options.amount);\r\n\r\n // pomoci $(\"#amount-slider\").slider(\"value\") zjistujeme aktualni hodnotu, kterou ma slider a prirazime do amountVal\r\n var amountVal = $(\"#amount-slider\").slider(\"value\");\r\n\r\n // zjistenou amountVal hodnotu nacitame do bloku #amount pomoci funkci .text()\r\n $(\"#amount\").text(amountVal);\r\n\r\n // slider ve jquery ui ma metody, ktere muzeme pouzit pro evidenci jednotlivych udalosti, ktere vznikaji behem interakci s uzivatelem\r\n // metoda slide umoznuje zjistit, jestli uzivatel zmenil hodnotu slideru\r\n $(\"#amount-slider\").slider(\"option\", {\r\n\r\n // jakmile uzivatel zmeni hodnotu slideru tak vyvola se funkce, ktera ma argumenty event a ui\r\n // event rika jaka akce prave probehla\r\n // ui je object s hodnotami, ktere ma slider.\r\n // potrebujeme jenom ui.value, aby zjistit jakou hodnotu ma slider po zmene\r\n slide: function (event, ui) {\r\n\r\n // potrebujeme jenom ui.value, aby zjistit jakou hodnotu ma slider po zmene\r\n // zjistenou hodnotu ui.value nacitame do bloku #amount pomoci funkci .text()\r\n $(\"#amount\").text(ui.value);\r\n\r\n // nastavujeme novou hodnotu pro slider #amount-slider\r\n $(\"#amount-slider\").slider(\"value\", ui.value);\r\n\r\n // dale volame funkci ktera vypocita vysledek a nastavuje vyslednou hodnotu pro zobrazeni na strance\r\n calculateResult();\r\n }\r\n });\r\n\r\n\r\n /* ------------------------------------------------------------------------------------------------------- */\r\n /* ------------------------------------------------------------------------------------------------------- */\r\n /* ---------------------------------- #REPAYMENT PERIOD SLIDER ----------------------------------------- */\r\n /* ------------------------------------------------------------------------------------------------------- */\r\n\r\n\r\n //inicializuje se slider #repayment-period-slider s nastavenim? ktere jsme dostali na zaklade hodnoty #select\r\n // popis toho jak se zjistuje options je ukazan v metode setRepaymentOptions();\r\n $(\"#repayment-period-slider\").slider(options.repayment_period);\r\n\r\n // pomoci $(\"#repayment-period-slider\").slider(\"value\") zjistujeme aktualni hodnotu, kterou ma slider a prirazime do repaymentPeriodVal\r\n var repaymentPeriodVal = $(\"#repayment-period-slider\").slider(\"value\");\r\n\r\n // nastavujeme editedSlider na hodnotu repayment period jako defaultni\r\n editedSlider = \"repaymentPeriod\";\r\n\r\n // zjistenou repaymentPeriodVal hodnotu nacitame do bloku #amount pomoci funkci .text()\r\n $(\"#repayment-period\").text(repaymentPeriodVal);\r\n\r\n // metoda pro zobrazeni urcitych koncovek pro slovo mesic.\r\n // 1 mesic, 2-3-4 mesice, pro 5 - mesicu.\r\n setRepaymentPeriodLabel(repaymentPeriodVal);\r\n\r\n // slider ve jquery ui ma metody, ktere muzeme pouzit pro evidenci jednotlivych udalosti, ktere vznikaji behem interakci s uzivatelem\r\n // metoda slide umoznuje zjistit, jestli uzivatel zmenil hodnotu slideru\r\n $(\"#repayment-period-slider\").slider(\"option\", {\r\n\r\n // jakmile uzivatel zmeni hodnotu slideru tak vyvola se funkce, ktera ma argumenty event a ui\r\n // event rika jaka akce prave probehla\r\n // ui je object s hodnotami, ktere ma slider.\r\n slide: function (event, ui) {\r\n\r\n\r\n // potrebujeme jenom ui.value, aby zjistit jakou hodnotu ma slider po zmene\r\n // zjistenou hodnotu ui.value nacitame do bloku #repayment-period pomoci funkci .text()\r\n $(\"#repayment-period\").text(ui.value);\r\n\r\n // nastavujeme novou hodnotu pro slider #repayment-period-slider\r\n $(\"#repayment-period-slider\").slider(\"value\", ui.value);\r\n\r\n\r\n\r\n // prirazime hodnotu repaymentPeriod do editedSlider\r\n // pri vypocetnu vysledni hodnoty budeme pouzivat hodnotu ze slideru #repayment-period-slider\r\n editedSlider = \"repaymentPeriod\";\r\n\r\n // metoda pro zobrazeni urcitych koncovek pro slovo mesic.\r\n // 1 mesic, 2-3-4 mesice, pro 5 a vice - mesicu.\r\n // ma jeden arument ui.value - hodnota, kterou slider #repayment-period-slider\r\n setRepaymentPeriodLabel(ui.value);\r\n\r\n // dale volame funkci ktera vypocita vysledek a nastavuje vyslednou hodnotu pro zobrazeni na strance\r\n calculateResult();\r\n }\r\n });\r\n\r\n\r\n /* ------------------------------------------------------------------------------------------------------- */\r\n /* ------------------------------------------------------------------------------------------------------- */\r\n /* ---------------------------------- #PROCENTUAL REPAYMENT SLIDER ------------------------------------- */\r\n /* ------------------------------------------------------------------------------------------------------- */\r\n\r\n\r\n //inicializuje se slider #procentual-repayment-slider s nastavenim? ktere jsme dostali na zaklade hodnoty #select\r\n // popis toho jak se zjistuje options je ukazan v metode setRepaymentOptions();\r\n $(\"#procentual-repayment-slider\").slider(options.procentual_repayment);\r\n\r\n // pomoci $(\"#procentual-repayment-slider\").slider(\"value\") zjistujeme aktualni hodnotu, kterou ma slider a prirazime do procentualRepayment\r\n var procentualRepayment = $(\"#procentual-repayment-slider\").slider(\"value\");\r\n\r\n // zjistenou procentualRepayment hodnotu nacitame do bloku #procentual-repayment pomoci funkci .text()\r\n $(\"#procentual-repayment\").text(procentualRepayment);\r\n\r\n // slider ve jquery ui ma metody, ktere muzeme pouzit pro evidenci jednotlivych udalosti, ktere vznikaji behem interakci s uzivatelem\r\n // metoda slide umoznuje zjistit, jestli uzivatel zmenil hodnotu slideru\r\n $(\"#procentual-repayment-slider\").slider(\"option\", {\r\n\r\n // jakmile uzivatel zmeni hodnotu slideru tak vyvola se funkce, ktera ma argumenty event a ui\r\n // event rika jaka akce prave probehla\r\n // ui je object s hodnotami, ktere ma slider.\r\n slide: function (event, ui) {\r\n\r\n // potrebujeme jenom ui.value, aby zjistit jakou hodnotu ma slider po zmene\r\n // zjistenou hodnotu ui.value nacitame do bloku #procentual-repayment-period pomoci funkci .text()\r\n var procentualRepayment = $(\"#procentual-repayment\").text(ui.value);\r\n\r\n // nastavujeme novou hodnotu pro slider #procentual-repayment-slider\r\n $(\"#procentual-repayment-slider\").slider(\"value\", ui.value);\r\n\r\n // prirazime hodnotu procentualRepayment do editedSlider\r\n // pri vypocetnu vysledni hodnoty budeme pouzivat hodnotu ze slideru #procentual-repayment-slider\r\n editedSlider = \"procentualRepayment\";\r\n\r\n // dale volame funkci ktera vypocita vysledek a nastavuje vyslednou hodnotu pro zobrazeni na strance\r\n calculateResult();\r\n }\r\n });\r\n\r\n\r\n // volame funkci ktera vypocita vysledek a nastavuje vyslednou hodnotu pro zobrazeni na strance\r\n calculateResult();\r\n\r\n\r\n}",
"function createVegInitialConditionsDict(){\n\n // current_proejct.definitions can be slow to initialize. Keep trying until it's defined.\n\n if (typeof current_project.definitions != \"undefined\") {\n\n var veg_initial_conditions = {};\n veg_initial_conditions[\"veg_sc_pct\"] = {};\n\n $.each(current_scenario.config.initial_conditions_nonspatial_distributions, function (index, object) {\n var strata_object = $.grep(current_project.definitions.strata, function (e) {\n return e.id == object.stratum;\n });\n var strata_name = strata_object[0].name;\n if (!(strata_name in veg_initial_conditions[\"veg_sc_pct\"])) {\n veg_initial_conditions[\"veg_sc_pct\"][strata_name] = {};\n }\n\n var state_class_object = $.grep(current_project.definitions.stateclasses, function (e) {\n return e.id == object.stateclass;\n });\n var state_class_name = state_class_object[0].name;\n if (object.relative_amount != 0) {\n veg_initial_conditions[\"veg_sc_pct\"][strata_name][state_class_name] = object.relative_amount\n }\n });\n\n return veg_initial_conditions\n\n } else {\n\n setTimeout(createVegInitialConditionsDict,250);\n }\n}",
"function dataWeather(data) {\n let kelvinDelta = 273.15;\n var calcCelcius = Math.round(parseFloat(data.main.temp) - kelvinDelta);\n\n let weather = new Weather();\n weather.main = data.weather[0].main;\n weather.temp = calcCelcius;\n weather.wind = data.wind.speed;\n weather.location = data.name;\n document.getElementById(\"main\").innerHTML = weather.main;\n document.getElementById(\"temp\").innerHTML = weather.temp;\n document.getElementById(\"location\").innerHTML = weather.location;\n document.getElementById(\"wind\").innerHTML = weather.wind;\n}",
"function setHtmlSlider(){\n\t\t\n\t\t//get if the slide has controls\n\t\tvar loaderClass = getLoaderClass();\n\t\tvar galleryOptions = g_gallery.getOptions();\n\t\t\n\t\tvar html = \"<div class='ug-slider-wrapper'>\";\n\t\t\n\t\thtml += \"<div class='ug-slider-inner'>\";\n\t\thtml += getHtmlSlide(loaderClass,1);\n\t\thtml += getHtmlSlide(loaderClass,2);\n\t\thtml += getHtmlSlide(loaderClass,3);\n\t\t\t\t\n\t\thtml += \"</div>\";\t//end inner\n\t\t\n\t\t//----------------\n\t\t\t\t\n\t\t//add arrows\n\t\tif(g_options.slider_enable_arrows == true){\n\t\t\thtml += \"<div class='ug-slider-control ug-arrow-left ug-skin-\"+g_options.slider_arrows_skin+\"'></div>\";\n\t\t\thtml += \"<div class='ug-slider-control ug-arrow-right ug-skin-\"+g_options.slider_arrows_skin+\"'></div>\";\n\t\t}\n\t\t\n\t\t//add play button\n\t\tif(g_options.slider_enable_play_button == true){\n\t\t\thtml += \"<div class='ug-slider-control ug-button-play ug-skin-\"+g_options.slider_play_button_skin+\"'></div>\";\n\t\t}\n\t\t\n\t\t//add fullscreen button\n\t\tif(g_options.slider_enable_fullscreen_button == true){\n\t\t\thtml += \"<div class='ug-slider-control ug-button-fullscreen ug-skin-\"+g_options.slider_fullscreen_button_skin+\"'></div>\";\n\t\t}\n\t\t\n\t\t\n\t\thtml +=\t\"</div>\";\t//end slider\n\t\t\n\t\t\n\t\tg_objWrapper.append(html);\n\t\t\n\t\t//----------------\n\t\t\n\t\t//set objects\n\t\tg_objSlider = g_objWrapper.children(\".ug-slider-wrapper\");\n\t\tg_objInner = g_objSlider.children(\".ug-slider-inner\");\n\t\t\n\t\t\n\t\tg_objSlide1 = g_objInner.children(\".ug-slide1\");\n\t\tg_objSlide2 = g_objInner.children(\".ug-slide2\");\n\t\tg_objSlide3 = g_objInner.children(\".ug-slide3\");\n\t\t\n\t\t//set slides data\n\t\tg_objSlide1.data(\"slidenum\",1);\n\t\tg_objSlide2.data(\"slidenum\",2);\n\t\tg_objSlide3.data(\"slidenum\",3);\n\t\t\t\t\n\t\t//add bullets\n\t\tif(g_objBullets)\n\t\t\tg_objBullets.appendHTML(g_objSlider);\n\t\t\n\t\t//----------------\n\t\t\n\t\t//get arrows object\n\t\tif(g_options.slider_enable_arrows == true){\n\t\t\tg_objArrowLeft = g_objSlider.children(\".ug-arrow-left\");\n\t\t\tg_objArrowRight = g_objSlider.children(\".ug-arrow-right\");\n\t\t}\n\t\t\t\t\n\t\t//get play button\n\t\tif(g_options.slider_enable_play_button == true){\n\t\t\tg_objButtonPlay = g_objSlider.children(\".ug-button-play\");\n\t\t}\n\t\t\n\t\t//get fullscreen button\n\t\tif(g_options.slider_enable_fullscreen_button == true){\n\t\t\tg_objButtonFullscreen = g_objSlider.children(\".ug-button-fullscreen\");\n\t\t}\n\t\t\n\t\t\n\t\t//----------------\n\t\t\n\t\t//add progress indicator\n\t\tif(g_options.slider_enable_progress_indicator == true){\n\t\t\t\n\t\t\tg_objProgress = g_functions.initProgressIndicator(g_options.slider_progress_indicator_type, g_options, g_objSlider);\n\t\t\t\n\t\t\tvar finalType = g_objProgress.getType();\n\t\t\t\n\t\t\t//change options in case of type change\n\t\t\tif(finalType == \"bar\" && g_options.slider_progress_indicator_type == \"pie\"){\n\t\t\t\tg_options.slider_progress_indicator_type = \"bar\";\n\t\t\t\tg_options = jQuery.extend(g_options, g_defaultsProgressBar);\n\t\t\t}\t\n\t\t\t\n\t\t\tg_gallery.setProgressIndicator(g_objProgress);\n\t\t}\n\t\t\n\t\t//----------------\n\t\t\n\t\t//add text panel (hidden)\n\t\tif(g_options.slider_enable_text_panel == true){\n\t\t\t\n\t\t\t//add panel to controls:\n\t\t\tif(g_options.slider_textpanel_always_on == false && hasControls == true && g_options.slider_controls_always_on == false)\n\t\t\t\tg_objTextPanel.appendHTML(g_objSlider);\n\t\t\telse{\t//add panel to slider\n\t\t\t\t\n\t\t\t\tg_objTextPanel.appendHTML(g_objSlider);\n\t\t\t\t\t\t\t\t\n\t\t\t\t//hide panel saparatelly from the controls object\n\t\t\t\tif(g_options.slider_textpanel_always_on == false){\n\t\t\t\t\t\n\t\t\t\t\t//hide the panel\n\t\t\t\t\tvar panelElement = g_objTextPanel.getElement();\n\t\t\t\t\tpanelElement.hide().data(\"isHidden\", true);\n\n\t\t\t\t\tg_temp.isTextPanelSaparateHover = true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\t\n\t\t//----------------\n\t\t\n\t\t//add zoom buttons panel:\n\t\tif(g_options.slider_enable_zoom_panel == true){\n\t\t\tg_objZoomPanel.appendHTML(g_objSlider);\n\t\t}\n\t\n\t\t\n\t\t//add video player\n\t\tg_objVideoPlayer.setHtml(g_objSlider);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
logarithmic scaling all feature ranges so that circle radius always fits in [0,maxCircleRadius] for all properties | function featureLogScale(featureRange) {
let x = d3.scaleLog()
.domain([featureRange[0]+0.0001,featureRange[1]])
.range([1, maxCircleRadius]);
return x;
} | [
"function logMap(val, inMin, inMax, outMin, outMax) {\n\n // log( = infinity)\n for (var i = 0; i < arguments.length; i++) {\n if (arguments[i] === 0) {\n arguments[i] = 0.0000000000000001;\n }\n }\n\n var minv = Math.log(outMin);\n var maxv = Math.log(outMax);\n\n var numerator = maxv - minv;\n var denom = inMax - inMin;\n\n // dont divide by zero\n if (denom === 0) {\n denom = 0.000000000001;\n }\n\n // calculate adjustment factor\n var scale = numerator / denom;\n\n return Math.exp(minv + scale*(val-inMin));\n}",
"function updateRadiusScale(newMax) {\n \n var largerDim = self.width > self.height ? self.width : self.height;\n self.earthquakeRadiusScale = d3.scaleLinear()\n .domain([0, magToEnergy(newMax)])\n .range([1, largerDim * 0.09]);\n \n self.maxEarthquakeMagnitude = newMax;\n \n self.nodes.forEach(function(d)\n {\n d.radius = magToRadius(d.magnitude);\n });\n }",
"function xLog(vMin, vMax, xSize, v) {\n\tif (v >= vMin && v <= vMax) {\n\t\tif (vMin > 0) {\n\t\t\treturn Math.log(v / vMin) / Math.log(vMax / vMin) * xSize;\n\t\t} else {\n\t\t\treturn Math.log(v) / Math.log(vMax) * xSize;\n\t\t}\n\t} else {\n\t\treturn 0;\n\t}\n}",
"function max(){return colorScale.domain()[2];}",
"function linearScale(domain, range, value) {\n return ((value - domain[0]) / (domain[1] - domain[0])) * (range[1] - range[0]) + range[0];\n}",
"function min(){return colorScale.domain()[0];}",
"function computeTickInterval(xMin, xMax) \n {\n var zoomRange = xMax - xMin;\n \n if (zoomRange <= 2)\n currentTickInterval = 0.5;\n if (zoomRange < 20)\n currentTickInterval = 1;\n else if (zoomRange < 100)\n currentTickInterval = 5;\n }",
"function geneBaseBounds(gn, min, max) {\n var gd = genedefs[gn];\n var gg = guigenes[gn];\n if (gd === undefined) return;\n if (gd.basemin === gd.min) {\n gd.min = min;\n gg.minEle.value = min;\n gg.sliderEle.min = min;\n }\n gd.basemin = min;\n if (gd.basemax === gd.max) {\n gd.max = max;\n gg.maxEle.value = max;\n gg.sliderEle.max = max;\n }\n gd.basemax = max;\n\n gg.deltaEle.value = gd.delta;\n gg.stepEle.value = gd.step;\n}",
"function scale_changed() {\n\n var s = document.getElementById(\"scale_input\");\n //alert(\"slider value \" + s.value);\n\n var range = s.value / 100; // .25 - 2\n\n g_config.scale_factor = range;\n\n if (g_enableInstrumentation) {\n alert(\"scale_factor \" + g_config.scale_factor);\n }\n\n updateScaleCSS(g_config.scale_factor);\n\n refreshMode();\n}",
"function scaleGDP(x) {\nreturn x/1000000000;\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 normaliseScale(s) {\n if (s > 1) throw('s must be <1');\n s = 0 | (1 / s);\n var l = log2(s);\n var mask = 1 << l;\n var accuracy = 4;\n while (accuracy && l) {\n l--;\n mask |= 1 << l;\n accuracy--;\n }\n return 1 / ( s & mask );\n }",
"function colour_scale(x) {\r\n return \"rgb(0,0,\"+((x-min_colour)/(max_colour-min_colour)*256).toString() +\")\"\r\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 }",
"get forceScale() {}",
"function setZoomExtent(k) {\n var numOfPoints = currSeries[0].data.length;\n //choose the max among all the series\n for (var i = 1; i < currSeries.length; i++) {\n if (numOfPoints < currSeries[i].data.length) {\n numOfPoints = currSeries[i].data.length;\n }\n }\n if (!k || k > numOfPoints) k = 3;\n zoom.scaleExtent([1, numOfPoints / k]);\n maxScaleExtent = parseInt(numOfPoints / k);\n }",
"onTransformScaling() {\n const scale = this.getClosestScaleToFitExtentFeature();\n this.setScale(scale);\n }",
"scaleToRange(x) {\r\n var t;\r\n t = this.minHeight + ((x - this.minTemp) * (this.maxHeight - this.minHeight)) / (this.maxTemp - this.minTemp); // Based on a formula googled from various sources.\r\n return t;\r\n }",
"function colorScale6(d) {\n let colorScale = d3.scaleQuantize(d3.schemePuOr[4])\n .domain([dMin,dMax])\n\n return colorScale(d)\n}",
"function updateSize(x) {\n\n\tvar xMin = d3.min(x);\n\tvar xMax = d3.max(x);\n\n\tbubbleScale = d3.scalePow().exponent(2).domain([Math.floor(xMin), Math.ceil(xMax)]).range([2.5, 15]);\n\n\t// update points\n\td3.selectAll('.point')\n\t\t.attr('r', function(d,i) {return bubbleScale(x[i])});\n\n} // end of updateHist()"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParserdeallocate_unused_clause. | visitDeallocate_unused_clause(ctx) {
return this.visitChildren(ctx);
} | [
"visitSupplemental_plsql_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitUnpivot_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDel_stmt(ctx) {\r\n console.log(\"visitSivisitDel_stmt\");\r\n return { type: \"DeleteStatement\", deleted: this.visit(ctx.exprlist()) };\r\n }",
"visitTemporary_tablespace_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDrop_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDrop_constraint_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDrop_procedure(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitMv_log_purge_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDelete_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitOn_delete_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitFrom_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function removeExpr() {\r\n\r\n var sO = CurStepObj;\r\n var pos;\r\n\r\n // If an expression is active, we remove that expression AND activate\r\n // the space just before that removed expression (i.e., the sapce\r\n // id same as that of removed expression)\r\n //\r\n if (!sO.isSpaceActive) { // expression highlighted\r\n\r\n // console.log(\"no space\");\r\n\r\n pos = sO.activeChildPos;\r\n\r\n if (pos != ROOTPOS) {\r\n\r\n //console.log(\"not root\");\r\n\r\n // If we are deleting an arg of a function call, update the\r\n // header\r\n // \r\n var removed = true;\r\n if (sO.activeParentExpr.isUserFuncCall()) {\r\n removed = removeFuncArg(sO.activeParentExpr, pos);\r\n }\r\n\t //\r\n if (removed) {\r\n sO.activeParentExpr.exprArr.splice(pos, 1);\r\n sO.isSpaceActive = true; // activate space before removed expr\r\n }\r\n\r\n } else { // can't remove root str (e.g., if/else)\r\n\r\n\r\n if (sO.activeParentExpr.exprArr.length ||\r\n sO.activeParentExpr.isCondition()) {\r\n\r\n // Cannot delete non-empty 'foreach' OR any mask box \r\n //\r\n showTip(TipId.RootEdit);\r\n\r\n } else {\r\n\r\n // if no children, mark as deleted (e.g., bare 'foreach')\r\n //\r\n sO.activeParentExpr.deleted = DeletedState.Deleted;\r\n }\r\n }\r\n\r\n } else { // if space highlighted\r\n\r\n // console.log(\"space @\" + sO.activeChildPos);\r\n\r\n //pos = -1; // remove at very end by default\r\n\r\n if (sO.activeChildPos > 0) {\r\n pos = --sO.activeChildPos; // -- to move to previous space\r\n\r\n /*\r\n\t if (pos < 0) { // if we moved to ROOTPS\r\n\t\tsO.isSpaceActive = false; // space no longer active\r\n\t }\r\n\t */\r\n\r\n sO.activeParentExpr.exprArr.splice(pos, 1);\r\n }\r\n\r\n\r\n\r\n // var expr = sO.activeParentExpr.exprArr[pos];\r\n // if (expr.isDefinition()) expr.str = 'DELETED';\r\n\r\n\r\n\r\n }\r\n\r\n}",
"visitOver_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitPragma_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"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 }",
"visitDrop_primary_key_or_unique_or_generic_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"exitVariableDeclaratorList(ctx) {\n\t}",
"visitKeep_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitRebuild_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Button component that redirect to different page props: title: the title on the button target: the page the button is going to direct to size: aize of the button, must be Large or Small category: which category the button us linking to, optional category will also change the colour of the button options for category are: trigger, thing, feedback, animation | function LinkButton(props) {
const [title] = useState(props.title)
const [path] = useState(props.target)
const [category] = useState(props.category)
const [size] = useState(props.size + "Button")
let colour = "#F08A00"
let fontColour = "#F3EAC2"
//change the colour of the button based on the category or page the button is connected to(sent with props)
if (category === "things") {
colour = "#D64539"
} else if (category === "feedback") {
colour = "#FFCD00"
fontColour = "#484848"
} else if (category === "animation") {
colour = "#84AD64"
}
return (
<Link
to={{
pathname: path,
state: { category: category, color: colour, card: props.card }
}} disabled={props.disabled}>
<Button style={{ backgroundColor: colour, color: fontColour }} className={size} variant="primary" onClick={props.onClick} disabled={props.disabled}>{title}</Button>
</Link>
)
} | [
"renderPageButtons() {\n const { page, hits, perpage } = this.state;\n const last = Math.ceil(hits / perpage);\n const pages = pagination(page, last);\n const pageButtons = pages.map((pageNo) => {\n if (pageNo === 'First') {\n return <Button color=\"primary\" size=\"sm\" key={pageNo} onClick={() => this.changePage(1)}>«</Button>;\n }\n if (pageNo === 'Last') {\n return <Button color=\"primary\" size=\"sm\" key={pageNo} onClick={() => this.changePage(last)}>»</Button>;\n }\n return <Button color=\"primary\" size=\"sm\" key={pageNo} onClick={() => this.changePage(pageNo)} className={(pageNo === this.state.page) ? 'active' : ''} disabled={(pageNo === this.state.page)}>{pageNo}</Button>;\n });\n\n return pageButtons;\n }",
"function Button(label, size = ImVec2.ZERO) {\r\n return bind.Button(label, size);\r\n }",
"function addButton(size) {\r\n\r\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 }",
"clickToGoToBikeLookup(event) {\n console.log(\"clickToGoToBikeLookup has been clicked\")\n return <BikeLookupPage />\n // window.location.assign(\"/bicyclelookuppage\");\n }",
"function makeWhaleSharkButton() {\n\n // Create the clickable object\n whaleSharkButton = new Clickable();\n \n whaleSharkButton.text = \"\";\n\n whaleSharkButton.image = images[23]; \n\n //makes the button color transparent \n whaleSharkButton.color = \"#00000000\";\n whaleSharkButton.strokeWeight = 0; \n\n //set width + height to image size\n whaleSharkButton.width = 270; \n whaleSharkButton.height = 390;\n\n // placing the button on the page \n whaleSharkButton.locate( width * (31/32) - whaleSharkButton.width * (31/32), height * (1/128) - whaleSharkButton.height * (1/128));\n\n // // Clickable callback functions for the whaleshark button , defined below\n whaleSharkButton.onPress = whaleSharkButtonPressed;\n whaleSharkButton.onHover = beginButtonHover;\n whaleSharkButton.onOutside = animalButtonOnOutside;\n}",
"function makeGoToCoralReefButton() {\n\n // Create the clickable object\n goToCoralReefButton = new Clickable();\n \n goToCoralReefButton.text = \"Click here to go to the interactive reef\";\n goToCoralReefButton.textColor = \"#365673\"; \n goToCoralReefButton.textSize = 37; \n\n goToCoralReefButton.color = \"#8FD9CB\";\n\n // set width + height to image size\n goToCoralReefButton.width = 739;\n goToCoralReefButton.height = 84;\n\n // places button on the page \n goToCoralReefButton.locate( width/2 - goToCoralReefButton.width/2 , height * (3/4));\n\n //Clickable callback functions, defined below\n goToCoralReefButton.onPress = goToCoralReefButtonPressed;\n goToCoralReefButton.onHover = beginButtonHover;\n goToCoralReefButton.onOutside = beginButtonOnOutside;\n}",
"function Page2(cathead, arg2) {\n this.catheader = createElement(\"h1\",'');\n this.header = createElement('h2', cathead);\n this.options = [];\n var container = createDiv('');\n \n// creates chekboxes based on the length of the chosen array.\n for (n = 0; n < arg2.length; n++) {\n this.options.push(createCheckbox(arg2[n], false));\n this.options[n].id(arg2[n]);\n this.options[n].position(window.innerWidth*0.35, 200 + (n*30));\n this.options[n].parent(container);\n }\n//makes submit buttons\n this.submit = createButton('Submit');\n this.submit.addClass('submit');\n this.noSubmit = createButton('Don\\'t Submit');\n this.noSubmit.addClass('noSubmit');\n}",
"hitButton(e) {\n c.history.push(e.target.textContent);\n c.controller(e.target.textContent);\n }",
"function Chapter ({rule}){\n return <Link href={'/rules/' + rule.id} key={rule.id} >\n <a className={styles.single}> \n <h3>{ rule.id }) { rule.text }</h3>\n </a>\n </Link>;\n}",
"function Loadmore() {\n return (\n <div className='flex flex-col gap-5 items-center w-full'>\n {loading ? <ResponsiveArticle /> : ''}\n <button\n className='flex flex-row items-center justify-center gap-2 bg-gray-300 hover:bg-gray-400 text-gray-800 font-semibold py-2 px-4 w-40 h-12 rounded disabled:bg-gray-100 disabled:cursor-not-allowed'\n disabled={disable}\n onClick={() => updatePage(page * 1 + 1)}\n >\n <SVGReload />\n {loading ? 'Loading...' : 'Load more'}\n </button>\n </div>\n )\n }",
"handleClick() {\n\t\t\tthis.setState(\n\t\t\t\t() => ({ newCategory: this.props.buttons.buttonCategory }),\n\t\t\t \t() => { this.props.handleClick(this.state.newCategory) }\n\t\t)}",
"render() {\n const isButtonHidden = false; // this.isButtonShouldBeHidden();\n const { onClick } = this.props;\n\n // className=\"action action_type_entry-delete\"\n return <Button variant=\"outlined\" color=\"secondary\" className=\"action action_type_delete\" type=\"button\" onClick={onClick}>\n Удалить\n </Button>;\n }",
"function Link(props) {\n const { activeClassName, router, className: classNameProps, naked, ...other } = props;\n\n const className = clsx(classNameProps, {\n [activeClassName]: router.pathname === props.href && activeClassName,\n });\n\n if (naked) {\n return <NextComposed className={className} {...other} />;\n }\n\n return <MuiLink component={NextComposed} className={className} {...other} />;\n}",
"function stateChangeButtonPress(button) {\n switch (button.name) {\n case 'To Title Screen':\n game.state.start('titleScreen');\n break;\n case 'To Main Game':\n game.state.start('mainGame');\n break;\n case 'To Game Over':\n game.state.start('gameOver');\n break;\n }\n }",
"function createButton(options) {\r\n var menu = {\r\n id: 'MyAddon-menupopup',\r\n onShow: function() {},\r\n onHide: function() {},\r\n position: 'after_start',\r\n items: [\r\n {\r\n id: 'export-tabs',\r\n label: 'Add link (Ctrl+Shift+Z)',\r\n onCommand: function() {\r\n addLink(tabs.activeTab.url,0);\r\n }\r\n //tooltiptext: ''\r\n },\r\n {\r\n id: 'export-tabs',\r\n label: 'Export tabs',\r\n onCommand: function() {\r\n for each (var tab in tabs){\r\n addLink(tab.url,0); \r\n }\r\n }\r\n //tooltiptext: ''\r\n }\r\n ]\r\n }\r\n\r\n return toolbarbutton.ToolbarButton({\r\n id: \"Zoomlinks\",\r\n label: \"Zoomlinks\",\r\n tooltiptext: \"Zoomlinks\",\r\n image: data.url(\"icons/zoomlinks_icon.png\"),\r\n menu: menu,\r\n onCommand: function() {\r\n addLink(tabs.activeTab.url,0);\r\n\r\n }\r\n });\r\n}",
"function makeCoralReefButton() {\n\n // Create the clickable object\n coralReefButton = new Clickable();\n \n coralReefButton.text = \"Click here to see your coral reef!\";\n coralReefButton.textColor = \"#365673\"; \n coralReefButton.textSize = 37; \n\n coralReefButton.color = \"#8FD9CB\";\n\n // set width + height to image size\n coralReefButton.width = 994;\n coralReefButton.height = 90;\n\n // places the button on the page \n coralReefButton.locate( width/2 - coralReefButton.width/2 , height * (3/4));\n\n // // Clickable callback functions, defined below\n coralReefButton.onPress = coralReefButtonPressed;\n coralReefButton.onHover = beginButtonHover;\n coralReefButton.onOutside = beginButtonOnOutside;\n}",
"render() {\n const {image, link, name} = this.props\n return(\n <a className={styles.link} href={link}>\n <div className={styles.PromotionContainer} >\n <div className={styles.PromotionCard}>\n <div className={styles.PromotionWrapper}>\n <img className={styles.PromotionImage} src={image} alt=\"promo\"></img>\n <div className={styles.PromotionTitle}>\n {name}\n </div>\n </div>\n </div>\n </div>\n </a>\n )\n }",
"function ColorButton(desc_id, col, flags = 0, size = ImVec2.ZERO) {\r\n return bind.ColorButton(desc_id, col, flags, size);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds to the builder the nodes in the form of a proper RDF list. | _addList(list) {
let head = rdf.nil;
const prefix = "list" + (++this.counters.lists) + "_";
for (let i = list.length - 1 ; i >= 0 ; --i) {
let node = N3.DataFactory.blankNode(prefix + (i + 1));
//this._addQuad(node, rdf.type, rdf.List);
this._addQuad(node, rdf.first, list[i]);
this._addQuad(node, rdf.rest, head);
head = node;
}
return head;
} | [
"nodes(...args) {\n return this.node.list(...args);\n }",
"append(data) {\n if (this.head == null) {\n this.head = new Node(data);\n return;\n } \n\n let currentNode = this.head;\n while (currentNode.next != null) {\n currentNode = currentNode.next;\n }\n currentNode.next = new Node(data);\n }",
"function list (builder, node) {\n\tfinishPending (builder);\n\n\tvar key = node [1];\n\tvar sub = subBuilder (builder);\n\n\tdispatch.nodes (sub, builder.dispatch, node, 2, node.length);\n\n\tvar template = getTemplate (sub);\n\tappendNode (builder, spec.listNode (key, template));\n}",
"extractLists({ remove = false, ignoreErrors = false } = {}) {\n const lists = {}; // has scalar keys so could be a simple Object\n const onError = ignoreErrors ? (() => true) :\n ((node, message) => { throw new Error(`${node.value} ${message}`); });\n\n // Traverse each list from its tail\n const tails = this.getQuads(null, IRIs[\"default\"].rdf.rest, IRIs[\"default\"].rdf.nil, null);\n const toRemove = remove ? [...tails] : [];\n tails.forEach(tailQuad => {\n const items = []; // the members found as objects of rdf:first quads\n let malformed = false; // signals whether the current list is malformed\n let head; // the head of the list (_:b1 in above example)\n let headPos; // set to subject or object when head is set\n const graph = tailQuad.graph; // make sure list is in exactly one graph\n\n // Traverse the list from tail to end\n let current = tailQuad.subject;\n while (current && !malformed) {\n const objectQuads = this.getQuads(null, null, current, null);\n const subjectQuads = this.getQuads(current, null, null, null);\n let quad, first = null, rest = null, parent = null;\n\n // Find the first and rest of this list node\n for (let i = 0; i < subjectQuads.length && !malformed; i++) {\n quad = subjectQuads[i];\n if (!quad.graph.equals(graph))\n malformed = onError(current, 'not confined to single graph');\n else if (head)\n malformed = onError(current, 'has non-list arcs out');\n\n // one rdf:first\n else if (quad.predicate.value === IRIs[\"default\"].rdf.first) {\n if (first)\n malformed = onError(current, 'has multiple rdf:first arcs');\n else\n toRemove.push(first = quad);\n }\n\n // one rdf:rest\n else if (quad.predicate.value === IRIs[\"default\"].rdf.rest) {\n if (rest)\n malformed = onError(current, 'has multiple rdf:rest arcs');\n else\n toRemove.push(rest = quad);\n }\n\n // alien triple\n else if (objectQuads.length)\n malformed = onError(current, 'can\\'t be subject and object');\n else {\n head = quad; // e.g. { (1 2 3) :p :o }\n headPos = 'subject';\n }\n }\n\n // { :s :p (1 2) } arrives here with no head\n // { (1 2) :p :o } arrives here with head set to the list.\n for (let i = 0; i < objectQuads.length && !malformed; ++i) {\n quad = objectQuads[i];\n if (head)\n malformed = onError(current, 'can\\'t have coreferences');\n // one rdf:rest\n else if (quad.predicate.value === IRIs[\"default\"].rdf.rest) {\n if (parent)\n malformed = onError(current, 'has incoming rdf:rest arcs');\n else\n parent = quad;\n }\n else {\n head = quad; // e.g. { :s :p (1 2) }\n headPos = 'object';\n }\n }\n\n // Store the list item and continue with parent\n if (!first)\n malformed = onError(current, 'has no list head');\n else\n items.unshift(first.object);\n current = parent && parent.subject;\n }\n\n // Don't remove any quads if the list is malformed\n if (malformed)\n remove = false;\n // Store the list under the value of its head\n else if (head)\n lists[head[headPos].value] = items;\n });\n\n // Remove list quads if requested\n if (remove)\n this.removeQuads(toRemove);\n return lists;\n }",
"function populateRankList(node, ranklist) {\n //console.log(node.r.toLowerCase());\n node.listPosition = ranklist[node.r.toLowerCase()].length;\n ranklist[node.r.toLowerCase()].push(node);\n}",
"function buildList() {\n $log.debug(\"Building list...\");\n vm.list = Object.keys(queryFields); //get the keys\n vm.definitions = queryFields;\n $log.debug(vm.definitions);\n }",
"append(node) {\n\n // Checks if argument is a node:\n if (node instanceof YngwieNode) {\n\n // If given node has parent, detach that node from it's parent:\n if (node._parent) {\n node.detach();\n }\n\n // Set new node as last sibling:\n if (this._first !== undefined) {\n node._prev = this._last; // Sets new last child's previous node to old last node\n this._last._next = node; // Set old last child next element to new last child\n this._last = node; // Set new last child to given node\n } else {\n // If ther are no children, then this node is an only child:\n this._first = node;\n this._last = node;\n }\n\n // Set parent\n node._parent = this;\n\n // Return instance:cosnole\n return this;\n\n }\n\n throw new _Error_main_js__WEBPACK_IMPORTED_MODULE_0__.default(\"Can only apppend YngwieNode to other YngwieNodes\", node);\n\n }",
"async function addNodes() {\n const territoryKeys = Object.keys(territoryGraph);\n let lenTerritories = territoryKeys.length;\n while (lenTerritories) {\n lenTerritories -= 1;\n const territoryKey = territoryKeys[lenTerritories];\n territoryGraphStructure.add(territoryKey);\n }\n}",
"get nodelist() {\n\t\treturn this.nodes.values();\n\t}",
"function updateNodeReferenceData() {\n draggableNodes = getDraggableNodes();\n if (setParentListDataAttribute) {\n listParentNode.setAttribute('data-list-data', getDraggableNodeListData(draggableNodes));\n }\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 }",
"addAdjacent(node) {\n this.adjacents.push(node);\n }",
"function createList(scene) {\n id += 1;\n var html='';\n var c = scene.children;\n if (scene.name == '' && c.length <= 1) {\n if (c.length == 1) {\n html = createList(c[0]);\n }\n }\n else if (c.length == 0) {\n html+='<li data-sceneid='+id+'>'+scene.name+'</li>';\n scenes[id]=scene; \n }\n else {\n if (scene.name == '') {\n scene.name = 'All' // just a placeholder...\n }\n html+='<li data-sceneid='+id+'>'+scene.name+'<ul>';\n scenes[id]=scene;\n for (var i=0; i<c.length; i++) {\n html+=createList(c[i]);\n }\n html += '</ul>';\n }\n return html;\n}",
"addToHead(val) {\n // console.log('something')\n\n const node = new Node(val)\n if(this.head === null){\n this.head = node;\n this.tail = node;\n\n } else {\n const temp = this.head;\n this.head = node;\n this.head.next = temp;\n\n }\n\n this.length++\n return this\n }",
"_addToLists(list) {\n const listObj = {\n index: this.lists.length,\n name: list.getAttribute('name'),\n element: list,\n editable: this.isEditable(list),\n };\n if(this.lists.length === 0) this.activeList = listObj;\n this.lists.push(listObj);\n }",
"function node_fromJRON (jronnode, prefixes, options)\n {\n if (typeof jronnode == \"string\")\n {\n return $.rdf.literal('\"'+jronnode+'\"', options);\n };\n if (typeof jronnode == \"number\")\n {\n var xsdNs = \"http://www.w3.org/2001/XMLSchema#\";\n var nums = String(jronnode);\n var numt = ( nums.match(/^[0-9]+$/) ? \"integer\" : \"double\" );\n var opts = $.extend({}, options, { datatype: xsdNs+numt });\n return $.rdf.literal(nums, opts);\n };\n if (typeof jronnode == \"boolean\")\n {\n return $.rdf.literal(jronnode, options);\n };\n if (jronnode instanceof Array)\n {\n // Return blank node or rdf:nil for head of list\n return jronnode.length == 0 ? $.rdf.nil : $.rdf.blank('[]');\n }; \n if (typeof jronnode == \"object\")\n {\n var uri = jronnode.__iri;\n if (uri)\n {\n // CURIE or URI here { __iri: ... }\n if (uri.match(/^<.*>/))\n {\n return $.rdf.resource(uri, options);\n }\n else\n {\n try\n {\n // Try for CURIE - more restrictive than JRON proposal\n uri = $.curie(uri, options);\n return $.rdf.resource(uri, options);\n }\n catch (e)\n {\n // Expand prefix and process as URI\n uri = uri_fromJRON(uri, prefixes);\n return $.rdf.resource(\"<\"+uri+\">\", options);\n };\n };\n };\n if (jronnode.__text)\n {\n // Text literal, with or without language\n // { \"__text\": \"chat\",\n // \"__lang\": \"fr\" }\n var opts = options;\n if (jronnode.__lang)\n {\n opts = $.extend({}, options, { lang: jronnode.__lang }); \n }\n return $.rdf.literal(jronnode.__text, opts);\n };\n if (jronnode.__repr)\n {\n // Typed literal\n // { \"__repr\": \"2010-03-06\",\n // \"__type\": \"http://www.w3.org/2001/XMLSchema#date\" }\n var opts = $.extend({}, options, { datatype: \"[\"+jronnode.__type+\"]\" });\n return $.rdf.literal(jronnode.__repr, opts);\n \n };\n // bnode, with or without __node_id value\n // { \"foaf_name\": \"Sandro Hawke\",\n // \"foaf_knows: { \"foaf_name\": \"Eric Prud'hommeaux\",\n // \"foaf_knows: { \"__node_id\": \"n334\" },\n // \"__node_id\": \"n334\" }\n var nodeid = '[]';\n if (jronnode.__node_id)\n {\n nodeid = \"_:\"+jronnode.__node_id;\n }\n return $.rdf.blank(nodeid);\n };\n e = \"node_fromJRON unrecognized node: \"+$.toJSON(jronnode);\n log.debug(e);\n throw e;\n }",
"addPrefixes(prefixes, done) {\n // Ignore prefixes if not supported by the serialization\n if (!this._prefixIRIs) return done && done(); // Write all new prefixes\n\n let hasPrefixes = false;\n\n for (let prefix in prefixes) {\n let iri = prefixes[prefix];\n if (typeof iri !== 'string') iri = iri.value;\n hasPrefixes = true; // Finish a possible pending quad\n\n if (this._subject !== null) {\n this._write(this._inDefaultGraph ? '.\\n' : '\\n}\\n');\n\n this._subject = null, this._graph = '';\n } // Store and write the prefix\n\n\n this._prefixIRIs[iri] = prefix += ':';\n\n this._write(`@prefix ${prefix} <${iri}>.\\n`);\n } // Recreate the prefix matcher\n\n\n if (hasPrefixes) {\n let IRIlist = '',\n prefixList = '';\n\n for (const prefixIRI in this._prefixIRIs) {\n IRIlist += IRIlist ? `|${prefixIRI}` : prefixIRI;\n prefixList += (prefixList ? '|' : '') + this._prefixIRIs[prefixIRI];\n }\n\n IRIlist = IRIlist.replace(/[\\]\\/\\(\\)\\*\\+\\?\\.\\\\\\$]/g, '\\\\$&');\n this._prefixRegex = new RegExp(`^(?:${prefixList})[^\\/]*$|` + `^(${IRIlist})([a-zA-Z][\\\\-_a-zA-Z0-9]*)$`);\n } // End a prefix block with a newline\n\n\n this._write(hasPrefixes ? '\\n' : '', done);\n }",
"addChildren(valuesAdded) {\n this.children.push(new Node('()' + this.val, 'right'));\n valuesAdded.push('()' + this.val);\n this.children.push(new Node('(' + this.val + ')', 'right'));\n valuesAdded.push('(' + this.val + ')');\n this.children.push(new Node(this.val + '()', 'right'));\n valuesAdded.push(this.val + '()');\n }",
"linksAdd(links) {\n for(var i = 0; i < links.length; i++)\n this.linkAdd(links[i]);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
args is an object that looks like the arguments for `getOptimizedRoutes` It can also have a `routeSortKey` property ('distance' or 'duration') | function getBestWaypoints (args) {
const routeSortKey = args.routeSortKey || 'distance'
return getOptimizedRoutes(args).then(function (routeWaypointPairs) {
return sortRoutesBy({routeWaypointPairs, routeSortKey})[0]
})
} | [
"function RouteSearchResultCollector() {\n\n}",
"routes(agencyTag, cb) {\n var routes = [ ];\n\n this._newRequest().query({ command: 'routeList', a: agencyTag }, function(e) {\n switch(e.name) {\n case 'error':\n cb(null, e.data);\n break;\n\n case 'opentag':\n var tag = e.data;\n var attributes = tag.attributes;\n \n if (tag.name === 'route') {\n routes.push(attributes);\n }\n break;\n\n case 'end':\n cb(routes);\n break;\n }\n });\n }",
"dijkstraHandler(indoorDestination, indoorDestinationFloor) {\n const updatedDirectionPath = {};\n const [waypoints, graphs, floors] = this.indoorDirectionHandler(\n indoorDestination, indoorDestinationFloor\n );\n\n if (waypoints.length > 0) {\n const paths = dijkstraPathfinder.dijkstraPathfinder(waypoints, graphs);\n\n for (let i = 0; i < paths.length; i++) {\n updatedDirectionPath[floors[i]] = paths[i];\n }\n }\n this.setState({\n indoorDirectionsPolyLine: updatedDirectionPath,\n showDirectionsModal: false,\n showPolyline: true\n });\n }",
"roadLineDrawtest()\n {\n this.direction.route({\n origin:{lng:-78,lat:39.137},\n destination:{lat:39.281,lng:-76.60},\n travelMode:google.maps.TravelMode.DRIVING\n },(r,s)=>{\n var pathPoints=r.routes[0].overview_path;\n var path=new google.maps.Polyline({\n path:pathPoints\n });\n\n path.setMap(this.map);\n });\n }",
"function makeReqBy(model) {\n\n var origin = new Coordinates(model.origin_attributes.coordinates).toLatLng();\n var destination;\n\n var waypoints = delivr.util.values(model.destinations_attributes).map(function (destination) {\n return new Coordinates(destination.coordinates).toLatLng();\n });\n\n\n function euclidSquaredDistance(a, b) {\n return Math.pow(a.lat() - b.lat(), 2) + Math.pow(a.lng() - b.lng(), 2);\n }\n\n if (waypoints.length < 2) {\n\n destination = waypoints[0];\n\n } else {\n\n var bb = (function (points) {\n var nw, se;\n\n if (points.length < 2)\n throw \"\";\n\n nw = points[0];\n se = points[1];\n\n for (var i = 2; i < points.length; ++i) {\n var p = points[i];\n\n // FIXME: Scale those to not to break into denormalized ones\n\n if (p.lat() > se.lat() || p.lng() > se.lng())\n se = p;\n else if (p.lat() < nw.lat() || p.lng() < nw.lng())\n nw = p;\n }\n\n return [ nw, se ];\n })(waypoints);\n\n //\n // Take the most far waypoint as a \"destination\"\n //\n\n if (euclidSquaredDistance(origin, bb[0]) > euclidSquaredDistance(origin, bb[1]))\n destination = bb[0];\n else\n destination = bb[1];\n }\n\n waypoints = waypoints.filter(function (wp) {\n return !wp.equals(destination);\n });\n\n return {\n origin: origin,\n destination: destination,\n\n waypoints: waypoints.map(function (waypoint) {\n return {\n location: waypoint,\n stopover: true\n }\n }),\n\n optimizeWaypoints: true,\n\n provideRouteAlternatives: true,\n travelMode: google.maps.TravelMode.DRIVING,\n unitSystem: google.maps.UnitSystem.METRIC\n }\n }",
"function calcRoute() {\n\t// Prepare the API call\n\tvar start = start_location.geometry.location;\n\tvar end = end_location.geometry.location;\n\tvar request = {\n\t\torigin: start,\n\t\tdestination: end,\n\t\ttravelMode: 'DRIVING'\n\t};\n\n\t// Call Google Maps API\n\tdirectionsService.route(request, function (result, status) {\n\t\tconsole.log(result);\n\t\tif (status == 'OK') {\n\t\t\t// Update the map to show the route\n\t\t\tdirectionsDisplay.setDirections(result);\n\n\t\t\t// List out the roads that the route includes\n\t\t\tvar routes = result.routes;\n\n\t\t\tdocument.getElementById(\"routeslist\").innerHTML = '';\n\t\t\tfor (var i = 0; i < routes[0].legs[0].steps.length; i++) {\n\t\t\t\tvar routePath = routes[0].legs[0].steps[i].path;\n\t\t\t\tvar road_location = routePath[Math.floor(routePath.length / 2)];\n\t\t\t\tvar duration = routes[0].legs[0].steps[i].duration.value;\n\t\t\t\tvar distance = routes[0].legs[0].steps[i].distance.value;\n\n\t\t\t\t// speed in miles per hour\n\t\t\t\tvar speed = distance * 0.000621371 / (duration / 3600);\n\n\t\t\t\t\n\t\t\t\t//console.log(\"Speed: \" + speed);\n\n\t\t\t\tspeed = Math.max(20, Math.round(speed/10) * 10);\n\n\t\t\t\t//console.log(\"New Speed: \" + speed);\n\t\t\t\tvar polyline = routes[0].legs[0].steps[i].polyline;\n\n\t\t\t\tprocessStep(road_location, duration, distance, speed, routePath, polyline);\n\t\t\t}\n\t\t}\n\n\n\t});\n}",
"match(path, params={}) {\n params.router = this;\n params.route = this.routes.find(({ re }) => {\n const match = re.exec(path);\n if (match) {\n params.length = 0;\n re.keys.forEach((key, i) => {\n params[key.name] = match[i + 1];\n if (typeof key.name === 'number') {\n params.length = key.name + 1;\n }\n });\n return true;\n }\n });\n return params;\n }",
"function handleClickRouteInstr(e) {\n theInterface.emit('ui:zoomToRouteInstruction', e.currentTarget.id);\n }",
"function processStep(location, duration, distance, speed, path, polyline) {\n\tvar latLngArray = new String(location).replace(\"(\", \"\").replace(\")\", \"\").split(',', 2);\n\tvar latlng = { lat: parseFloat(latLngArray[0]), lng: parseFloat(latLngArray[1]) };\n\n\thttpGetAsync(\"https://nominatim.openstreetmap.org/reverse?format=json&lat=\" + latlng.lat + \"&lon=\" + latlng.lng + \"&zoom=18&addressdetails=1\", function (data) {\n\t\tvar road;\n\t\ttry {\n\t\t\troad = JSON.parse(data).address.road;\n\t\t} catch (err) {\n\t\t\tconsole.warn(\"Error finding road name from GPS coordinates \" + location + \" :(\");\n\t\t}\n\n\t\tif (!road) {\n\t\t\tconsole.warn(\"Error finding road name from GPS coordinates \" + location + \" :(\");\n\t\t}\n\t\telse if (!roads[road]) {\n\t\t\tvar listNode = getListNode(road, duration, distance, speed);\n\t\t\troads[road] = {\n\t\t\t\tduration: duration,\n\t\t\t\telement: listNode,\n\t\t\t\tlatitude: latlng.lat,\n\t\t\t\tlongitude: latlng.lng,\n\t\t\t\troadName: road,\n\t\t\t\tdistance: distance,\n\t\t\t\tspeed: speed,\n\t\t\t\tpaths: [path],\n\t\t\t\tpolylines: [polyline]\n\t\t\t};\n\t\t} else {\n\t\t\tvar road = roads[road];\n\t\t\troad.duration += duration;\n\t\t\troad.distance += distance;\n\t\t\troad.paths.push(path);\n\t\t\troad.polylines.push(polyline);\n\t\t}\n\t\trenderList();\n\t});\n}",
"function formUrlRoad(locLat,locLng,apiKey){\n\treturn \t\"https://roads.googleapis.com/v1/nearestRoads?points=\" + locLat + \",\" + locLng + \"&key=\" + apiKey;\n}",
"function dijkstraRoute(x1, y1, x2, y2) {\n var graph = createBoxGraph();\n dijkstra(graph, keyFromCoordinates(x1, y1));\n\n var foundRoute = [];\n\n var startNode = getNode(graph, x1, y1),\n endNode = getNode(graph, x2, y2),\n node = endNode,\n distance = node.distance;\n if (startNode === null || endNode === null || distance === Infinity) {\n // Start point is a wall\n return [Infinity, []];\n }\n\n while (node.predecessor.node !== null) {\n foundRoute.push(node.position);\n node = node.predecessor.node;\n }\n\n if (!(node.position[0] === x1 && node.position[1] === y1)) {\n // No route found\n return [Infinity, []];\n }\n\n foundRoute.reverse();\n grid.setBoxColor(x1, y1, options.routeColor);\n colorBoxes(foundRoute, options.routeColor);\n\n return [distance, foundRoute];\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 }",
"setCache (state, args) {\n state.cache[args.property].args = args\n }",
"function runRoute(route, queryStrObj) {\n var routeObj = _routeMap[route];\n\n if (routeObj) {\n routeObj.controller.call(window, {\n route: route,\n templateID: routeObj.templateID,\n queryData: queryStrObj\n });\n } else {\n console.log('No Route mapped for: \"' + route + '\"');\n }\n }",
"routes() {\n const dispatch = async (context, next) => {\n const { path, method } = context.request;\n const { routesMatched, matches } = this._match(path, method);\n const contextRoutesMatched = contextRouteMatches.get(context);\n contextRouteMatches.set(context, contextRoutesMatched\n ? [...contextRoutesMatched, ...routesMatched]\n : routesMatched);\n context.router = this;\n if (!matches.length) {\n return next();\n }\n const chain = matches.reduce((prev, layer) => {\n prev.push((context, next) => {\n const captures = layer.captures(path);\n context.params = layer.params(captures, context.params);\n return next();\n });\n return [...prev, ...layer.stack];\n }, []);\n return middleware_ts_2.compose(chain)(context);\n };\n return dispatch;\n }",
"addEntry (state, args) {\n const cache = state.cache[args.property]\n const turn = state.turns[state.currentTurn]\n turn.push(args.entry)\n\n cache.turn = state.currentTurn\n cache.entryId = args.entry.entryId\n state.entryId++\n }",
"getNextRoutes(path: PathElement<*, *>[], location: Location): Route<*, *>[] {\n const query = getQueryParams(location)\n return path.map(element => {\n const matchedQueryParams = this.getMatchedQueryParams(element.node, query)\n const newRoute = createRoute(element.node, element.parentUrl, element.segment, element.params, query)\n const existingRoute = this.routes.find(x => areRoutesEqual(x, newRoute))\n \n if (existingRoute) {\n return existingRoute\n } else {\n return observable(createRoute(element.node, element.parentUrl, element.segment, element.params, matchedQueryParams))\n }\n })\n }",
"function route2Anim(){\n if(delta < 1){\n delta += 0.2;\n } else {\n visitedRoutes.push(allCoordinates[coordinate]) // Once it has arrived at its destination, add the origin as a visited location\n delta = 0;\n coordinate ++;\n drawRoute(); // Call the drawRoute to update the route\n }\n\n const latitude_origin = Number(runLocations2.getString(coordinate, 'Position/LatitudeDegrees'));\n const longitude_origin = Number(runLocations2.getString(coordinate, 'Position/LongitudeDegrees'));\n\n const latitude_destination = Number(runLocations2.getString(coordinate +1,'Position/LatitudeDegrees'));\n const longitude_destination = Number(runLocations2.getString(coordinate +1, 'Position/LongitudeDegrees'));\n origin = myMap.latLngToPixel(latitude_origin,longitude_origin);\n originVector = createVector(origin.x, origin.y);\n destination = myMap.latLngToPixel(latitude_destination,longitude_destination);\n destinationVector = createVector(destination.x, destination.y);\n\n runPosition = originVector.lerp(destinationVector, delta);\n\n noStroke(); // remove the stroke from the route\n fill(255,255,0);\n ellipse(runPosition.x, runPosition.y, 7, 7);\n}",
"function calcRoute(startLat, startLong, finishLat, finishLong){\r\n var start = new google.maps.LatLng(startLat, startLong);\r\n var end = new google.maps.LatLng(finishLat, finishLong);\r\n var directionsDisplay = new google.maps.DirectionsRenderer()\r\n var directionsService = new google.maps.DirectionsService()\r\n var request = {\r\n origin: start,\r\n destination: end,\r\n travelMode: google.maps.TravelMode.WALKING\r\n };\r\n\r\n directionsService.route(request, function(response, status) {\r\n if (status == google.maps.DirectionsStatus.OK) {\r\n directionsDisplay.setDirections(response);\r\n directionsDisplay.setMap(map1);\r\n } else {\r\n alert(\"Directions Request from \" + start.toUrlValue(6) + \" to \" + end.toUrlValue(6) + \" failed: \" + status);\r\n }\r\n });\r\n marker.setMap(null)\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a session with the set of launch parameters. | create(params) {
return __awaiter(this, void 0, void 0, function* () {
const session = new session_1.Session();
this.sessions.set(params.launchId, session);
session.onClose(() => this.sessions.delete(params.launchId));
session.onError(err => {
vscode.window.showErrorMessage(`Error running browser: ${err.message || err.stack}`);
this.sessions.delete(params.launchId);
});
yield Promise.all([
this.addChildSocket(session, params),
params.attach
? this.addChildAttach(session, params.attach)
: this.addChildBrowser(session, params),
]);
});
} | [
"startNew(options) {\n let serverSettings = this.serverSettings;\n return session_1.Session.startNew(Object.assign({}, options, { serverSettings })).then(session => {\n this._onStarted(session);\n return session;\n });\n }",
"function buildInitialSession() {\n const session = {\n start: Date.now(),\n currentState: 'notebook',\n projectId: '',\n currentStateParams: {}\n };\n\n\n // session.currentStateParams.user = '';\n // session.currentStateParams.corpus = 'default';\n\n\n return new Promise((resolve, reject) => {\n Session.insert(session, (err, data) => {\n if (err) {\n console.log('Error creating initial session', err);\n reject(err)\n }\n resolve(data)\n })\n });\n\n}",
"async function startWebDriverSession(params) {\n /**\n * validate capabilities to check if there are no obvious mix between\n * JSONWireProtocol and WebDriver protoocol, e.g.\n */\n if (params.capabilities) {\n const extensionCaps = Object.keys(params.capabilities).filter((cap) => cap.includes(':'));\n const invalidWebDriverCaps = Object.keys(params.capabilities)\n .filter((cap) => !constants_1.VALID_CAPS.includes(cap) && !cap.includes(':'));\n /**\n * if there are vendor extensions, e.g. sauce:options or appium:app\n * used (only WebDriver compatible) and caps that aren't defined\n * in the WebDriver spec\n */\n if (extensionCaps.length && invalidWebDriverCaps.length) {\n throw new Error(`Invalid or unsupported WebDriver capabilities found (\"${invalidWebDriverCaps.join('\", \"')}\"). ` +\n 'Ensure to only use valid W3C WebDriver capabilities (see https://w3c.github.io/webdriver/#capabilities).');\n }\n }\n /**\n * the user could have passed in either w3c style or jsonwp style caps\n * and we want to pass both styles to the server, which means we need\n * to check what style the user sent in so we know how to construct the\n * object for the other style\n */\n const [w3cCaps, jsonwpCaps] = params.capabilities && params.capabilities.alwaysMatch\n /**\n * in case W3C compliant capabilities are provided\n */\n ? [params.capabilities, params.capabilities.alwaysMatch]\n /**\n * otherwise assume they passed in jsonwp-style caps (flat object)\n */\n : [{ alwaysMatch: params.capabilities, firstMatch: [{}] }, params.capabilities];\n const sessionRequest = new request_1.default('POST', '/session', {\n capabilities: w3cCaps,\n desiredCapabilities: jsonwpCaps // JSONWP compliant\n });\n let response;\n try {\n response = await sessionRequest.makeRequest(params);\n }\n catch (err) {\n log.error(err);\n const message = exports.getSessionError(err, params);\n throw new Error('Failed to create session.\\n' + message);\n }\n const sessionId = response.value.sessionId || response.sessionId;\n /**\n * save actual receveived session details\n */\n params.capabilities = response.value.capabilities || response.value;\n return { sessionId, capabilities: params.capabilities };\n}",
"async function createSession() {\n const idvClient = new IDVClient(config.YOTI_CLIENT_SDK_ID, config.YOTI_PEM);\n\n const sessionSpec = new SessionSpecificationBuilder()\n .withClientSessionTokenTtl(600)\n .withResourcesTtl(90000)\n .withUserTrackingId('some-user-tracking-id')\n // For zoom liveness check [only one type of liveness check to be enabled at a time]\n .withRequestedCheck(new RequestedLivenessCheckBuilder()\n .forZoomLiveness()\n .build())\n // For static liveness check\n // .withRequestedCheck(\n // new RequestedLivenessCheckBuilder()\n // .forStaticLiveness()\n // .build()\n // )\n .withRequestedCheck(new RequestedFaceComparisonCheckBuilder()\n .withManualCheckNever()\n .build())\n .withSdkConfig(new SdkConfigBuilder()\n .withSuccessUrl(`${config.YOTI_APP_BASE_URL}/success`)\n .withErrorUrl(`${config.YOTI_APP_BASE_URL}/error`)\n .withPrivacyPolicyUrl(`${config.YOTI_APP_BASE_URL}/privacy-policy`)\n .withJustInTimeBiometricConsentFlow() // or withEarlyBiometricConsentFlow()\n .build())\n .build();\n\n return idvClient.createSession(sessionSpec);\n}",
"function newSession() {\n\n // Get a session from the API.\n sessionPromise = SessionDataService.create().then(\n function (session) {\n\n // Replace currently stored session.\n replace(sessionObject, session);\n\n return sessionObject;\n });\n\n return sessionPromise;\n }",
"static startSession(id, tokenHash, userId = null, type = null, expiry = null, sessionPrivileges = null){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.tokenHash = tokenHash;\n\t\tkparams.userId = userId;\n\t\tkparams.type = type;\n\t\tkparams.expiry = expiry;\n\t\tkparams.sessionPrivileges = sessionPrivileges;\n\t\treturn new kaltura.RequestBuilder('apptoken', 'startSession', kparams);\n\t}",
"function createSession(username){\n var now = Date.now();\n sessions.set(username, now);\n console.log('session created for ' + username);\n}",
"connect(){\n // add a session\n App.core.use(bodyParser.urlencoded({extended: true}));\n App.core.use(bodyParser.json());\n App.core.use(cookieParser());\n\n // init store\n this.config.store = new sessionStore({\n database: App.db.connection, // there will be stablished connection in lazyLoad mode\n sessionModel: App.db.models.sessions,\n transform: function (data) {\n return data;\n },\n ttl: (60 * 60 * 24),\n autoRemoveInterval: (60 * 60 * 3)\n });\n\n // run session \n App.core.use(session(this.config));\n }",
"function createWindow(nodeint) {\r\n\treturn new BrowserWindow({\r\n\t\twidth: 800,\r\n\t\theight: 600,\r\n\t\twebPreferences: {\r\n\t\t\tnodeIntegration: nodeint\r\n\t\t}\r\n\t});\r\n}",
"function createSessionFromTemplate(templatePartialPath, options) {\n\toptions = options || {};\n\tconst syncServerUrl = options.server || 'http://localhost:3000';\n\n\tconst reqOptions = {\n\t\turl: urlJoin(syncServerUrl, 'api/session'),\n\t\tmethod: 'POST',\n\t\tdata: {\n\t\t\ttemplate: {\n\t\t\t\tname: path.basename(templatePartialPath, path.extname(templatePartialPath)),\n\t\t\t\tpath: path.dirname(templatePartialPath)\n\t\t\t}\n\t\t}\n\t};\n\tif (options.environment) {\n\t\treqOptions.data.environment = options.environment;\n\t}\n\tif (options.actorTags) {\n\t\treqOptions.data.actorTags = options.actorTags;\n\t}\n\tif (options.sessionLabel) {\n\t\treqOptions.data.sessionLabel = options.sessionLabel;\n\t}\n\n\treturn new Promise(function (resolve, reject) {\n\t\taxios(reqOptions)\n\t\t\t.then(function (res) {\n\t\t\t\tconst sessionId = res.data.sessionId;\n\t\t\t\tconsole.log(\"Started test session \" + sessionId);\n\t\t\t\tresolve(sessionId);\n\t\t\t})\n\t\t\t.catch(function (err) {\n\t\t\t\tconsole.log('Error: ', err.message);\n\t\t\t\tif (err.response && err.response.data) {\n\t\t\t\t\tconsole.log('Response payload: ', err.response.data);\n\t\t\t\t}\n\t\t\t\treject(err);\n\t\t\t});\n\t});\n}",
"function WebXRSessionManager(\n /** The scene which the session should be created for */\n scene) {\n this.scene = scene;\n this._sessionEnded = false;\n this.baseLayer = null;\n /** WebXR timestamp updated every frame */\n this.currentTimestamp = -1;\n /**\n * Used just in case of a failure to initialize an immersive session.\n * The viewer reference space is compensated using this height, creating a kind of \"viewer-floor\" reference space\n */\n this.defaultHeightCompensation = 1.7;\n /**\n * Fires every time a new xrFrame arrives which can be used to update the camera\n */\n this.onXRFrameObservable = new Observable();\n /**\n * Fires when the reference space changed\n */\n this.onXRReferenceSpaceChanged = new Observable();\n /**\n * Fires when the xr session is ended either by the device or manually done\n */\n this.onXRSessionEnded = new Observable();\n /**\n * Fires when the xr session is ended either by the device or manually done\n */\n this.onXRSessionInit = new Observable();\n }",
"function sessionIdCreator() {\r\n let idLength = 8;\r\n sessionStorage.userType = 1;\r\n let chars = \"abcdefghijklmnopqrstuvwxyz1234567890\";\r\n for (let x = 0; x < idLength; x++) {\r\n let i = Math.floor(Math.random() * chars.length);\r\n sessionId += chars.charAt(i);\r\n }\r\n sessionStorage.sessionId = sessionId;\r\n}",
"function main() {\n urlParameters = new URLSearchParams(window.location.search);\n serverClient = new ServerClient(urlParameters);\n noVNCClient = new NoVNCClient(\n connectCallback, disconnectCallback, \n document.getElementById('session-screen'));\n addOnClickListenerToElements();\n let /** number */ setIntervalId = setInterval(() => {\n serverClient.getSession().then(session => {\n clearInterval(setIntervalId);\n noVNCClient.remoteToSession(session.getIpOfVM(), \n session.getSessionId());\n setReadOnlyInputs(session.getSessionId());\n document.getElementById('welcome-message').style.display = 'block';\n updateUI();\n }).catch(error => {\n window.alert('No contact with the server, retrying!');\n });\n }, sessionScriptConstants.SERVER_RECONNECT_CADENCE_MS);\n}",
"function startNew(options) {\n return __awaiter(this, void 0, void 0, function* () {\n let settings = options.serverSettings || __1.ServerConnection.makeSettings();\n let url = coreutils_1.URLExt.join(settings.baseUrl, KERNEL_SERVICE_URL);\n let init = {\n method: 'POST',\n body: JSON.stringify({ name: options.name })\n };\n let response = yield __1.ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n throw new __1.ServerConnection.ResponseError(response);\n }\n let data = yield response.json();\n validate.validateModel(data);\n return new DefaultKernel(Object.assign({}, options, { name: data.name, serverSettings: settings }), data.id);\n });\n }",
"function initializeTokboxSession() {\n session = OT.initSession(projectAPIKey, sessionID);\n session.on('sessionDisconnected', (event) => {\n console.log('You were disconnected from the session.', event.reason);\n });\n\n // Connect to the session\n session.connect(token, (error) => {\n if (error) {\n handleError(error);\n }\n });\n}",
"function createSession (booking, product, paymentRequestId, paymentId) {\n var productSession = new ProductSession();\n var departureDetails = {\n // Just add this to display at different screens of host side\n startTime: booking.actualSessionTime == 'Select Time' ? '' : booking.actualSessionTime,\n startDate: booking.openDatedTourDepartureDate,\n repeatBehavior : \"Do not repeat\"\n };\n productSession.sessionDepartureDetails = departureDetails;\n productSession.isSessionPricingValid = true;\n productSession.sessionPricingDetails = product.productPricingOptions;\n var keySeatsBooking = booking.actualSessionDate + booking.actualSessionTime;\n productSession.numberOfBookings[keySeatsBooking] = 1;\n productSession.numberOfSeats[keySeatsBooking] = parseInt(booking.numberOfSeats);\n productSession.markModified('numberOfBookings');\n productSession.markModified('numberOfSeats');\n var keySession = booking.actualSessionDate;\n productSession.numberOfBookingsSession[keySession] = 1\n productSession.numberOfSeatsSession[keySession] = parseInt(booking.numberOfSeats);\n productSession.markModified('numberOfBookingsSession');\n productSession.markModified('numberOfSeatsSession');\n var eventDate = new Date(booking.openDatedTourDepartureDate);\n var uniqueString = eventDate.getMonth().toString() + eventDate.getUTCFullYear().toString();\n productSession.monthsThisSessionCovering = uniqueString;\n productSession.hostCompany = product.hostCompany;\n productSession.product = product._id;\n productSession.sessionInternalName = undefined;\n productSession.sessionDepartureDate = new Date(booking.openDatedTourDepartureDate).toISOString();\n productSession.save(function (err, res) {\n if (err) {\n // session saving failed\n } else {\n Booking.findOne({_id: booking._id}).exec(function (err, bookingInstance) {\n bookingInstance.productSession = res._id;\n bookingInstance.save();\n });\n \n // session successfully saved\n }\n });\n}",
"function createSessionFromTemplateAndWait(templatePartialPath, options) {\n\toptions = options || {};\n\tconst timeout = options.timeout || 7200;\n\tconst syncServerUrl = options.server || 'http://localhost:3000';\n\tlet outFile = null;\n\tif (typeof options.outFile === 'string' || options.outFile instanceof String) {\n\t\toutFile = helpers.trimChars(options.outFile);\n\t}\n\tconst createOptions = { server: syncServerUrl };\n\tif (options.environment) {\n\t\tcreateOptions.environment = options.environment;\n\t}\n\tif (options.actorTags) {\n\t\tcreateOptions.actorTags = options.actorTags;\n\t}\n\tif (options.sessionLabel) {\n\t\tcreateOptions.sessionLabel = options.sessionLabel;\n\t}\n\n\tcreateSessionFromTemplate(templatePartialPath, createOptions)\n\t\t.then(function (sessionId) {\n\t\t\tlet startTime = Date.now();\n\n\t\t\tconsole.log(`Session completion timeout is set to ${timeout} seconds`);\n\t\t\tconsole.log(`Waiting for the test session to complete...`);\n\n\t\t\t// Check the test session status periodically, until the test\n\t\t\t// session is complete or the configured timeout expires\n\t\t\tsetTimeout(checkSessionCompleted, sessionCompleteCheckInterval);\n\n\t\t\tfunction checkSessionCompleted() {\n\t\t\t\texitIfSessionCompleted(sessionId, startTime, timeout, syncServerUrl, outFile);\n\t\t\t\tsetTimeout(checkSessionCompleted, sessionCompleteCheckInterval);\n\t\t\t}\n\t\t})\n\t\t.catch(function (err) {\n\t\t\tconsole.log('ERROR: ', err);\n\t\t\tprocess.exit(1);\n\t\t});\n}",
"function sessionStart() {\n\t///////////////////////////////////\n\t// USED FOR TESTING! DELETES ALL LOCAL DATA!\n\t// ONLY UNCOMMENT IF YOU WANT TO DELETE LOCAL DATA!\n //localStorage.clear();\n\t///////////////////////////////////\n\t\n //var _tempData = queryServer();\n //dataObj.steps = stepCount;\n //dataObj[\"totalSteps\"] += dataObj.steps;\n dataObj[\"sessionStartTime\"] = Date.now();\n \n //offlineCalculations(serverTime, dataObj[\"sessionStartTime\"]);\n \n //setupPlayer(serverPlayerData);\n \n //setupParty(serverPartyComp);\n}",
"async prepare() {\n const {\n debug,\n launchArgs\n } = this.options;\n const launchOpts = {\n headless: !debug,\n slowMo: debug ? 1000 : 0,\n args: launchArgs\n };\n\n // Launch the browser instance\n this.browser = await puppeteer.launch(launchOpts);\n\n // Get the default about:blank page\n this.page = (await this.browser.pages())[0];\n\n // Optionally set the default headers\n if (this.options.headers) {\n await this.page.setExtraHTTPHeaders(this.options.headers);\n }\n\n // Optionally override the default navigation timeout\n if (this.options.timeout) {\n this.page.setDefaultNavigationTimeout(this.options.timeout);\n }\n\n // Set the page viewport\n if (this.options.viewport.viewport) {\n await this.page.emulate(this.options.viewport);\n } else {\n await this.page.setViewport(this.options.viewport);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get script object based on the `src` URL | function getScriptFromUrl(url) {
if (typeof url === "string" && url) {
for (var i = 0, len = scripts.length; i < len; i++) {
if (scripts[i].src === url) {
return scripts[i];
}
}
}
//return undefined;
} | [
"function extractScriptSrcs(scriptUrl) {\n return session.get$(scriptUrl).then(($) => {\n return $(SCRIPT_TAG_SELECTOR).toArray().map((el) => el.attribs.src);\n });\n}",
"function getSoleInlineScript() {\n\t var script;\n\t for (var i = 0, len = scripts.length; i < len; i++) {\n\t if (!scripts[i].src) {\n\t\tif (script) {\n\t\t return undefined;\n\t\t}\n\t\tscript = scripts[i];\n\t }\n\t }\n\t return script;\n \t}",
"function getScripts() {\n\t\tvar result = [];\n\t\tvar scripts = targetWindow.document.scripts;\n\t\tforEach(scripts, function(script) {\n\t\t\tif (script.src) {\n\t\t\t\tresult.push({\n\t\t\t\t\ttype: script.type,\n\t\t\t\t\tsrc: script.src,\n\t\t\t\t\tasync: script.async,\n\t\t\t\t\tdefer: script.defer\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\treturn result;\n\t}",
"function addJs( src, document )\n{\n e = document.createElement(\"script\");\n e.async = true;\n e.type = \"text/javascript\";\n e.src = src;\n document.body.appendChild(e);\n}",
"function getSource() {\n const queryString = window.location.search;\n const urlParams = new URLSearchParams(queryString);\n const source = (urlParams.get(\"source\"));\n return source;\n}",
"function injectJsSrc(src, attrs) {\r\n let scriptElem = document.createElement('script');\r\n if (typeof attrs === 'undefined') attrs = [];\r\n\r\n scriptElem.src = src;\r\n scriptElem.type = 'application/javascript';\r\n\r\n for (let i = 0; i < attrs.length; i += 1) {\r\n let attr = attrs[i];\r\n scriptElem.setAttribute(attr[0], attr[1]);\r\n }\r\n\r\n document.head.appendChild(scriptElem);\r\n document.head.removeChild(scriptElem);\r\n}",
"async function loadScriptAsIframe(script) {\n const iframe = document.createElement('iframe');\n iframe.srcdoc = generateHTML(script);\n const iframeLoaded = new Promise(resolve => iframe.onload = resolve);\n document.body.appendChild(iframe);\n await iframeLoaded;\n return iframe;\n}",
"function dynamicLoadPluginJs(source, callback) {\n var label = source.label ? source.label : getStream(source.type);\n\n // if (label == 'hls') {\n // loadScript('../../node_modules/videojs-contrib-hls/dist/videojs-contrib-hls.js', callback)\n // } else if (label == 'dash') {\n // loadScript('../../node_modules/dashjs/dist/dash.all.min.js', function() {\n // loadScript('../../node_modules/videojs-contrib-dash/dist/videojs-dash.js', callback)\n // })\n // } else {\n // callback();\n // }\n\n if (label == 'hls') {\n loadScript('../../dist/GPlayer/lib/videojs-contrib-hls.min.js', callback)\n } else if (label == 'dash') {\n loadScript('../../dist/GPlayer/lib/dash.all.min.js', function() {\n loadScript('../../dist/GPlayer/lib/videojs-dash.min.js', callback)\n })\n } else {\n callback();\n }\n\n function getStream(type) {\n var streamingFormats = {\n 'rtmp/mp4': 'rtmp',\n 'rtmp/flv': 'rtmp',\n 'application/x-mpegURL': 'hls',\n 'application/dash+xml': 'dash'\n }\n return streamingFormats[type]\n }\n}",
"getSiteScriptFromWeb(webUrl, info) {\n return SiteScriptsCloneFactory(this, \"getSiteScriptFromWeb\").run({ webUrl, info });\n }",
"function getGlobalScriptContent(axios$$1, identifier, scriptId, versionId) {\n return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/scripting/tenants/' + tenantId + '/scripts/' + identifier + '/' + scriptId + '/versions/' + versionId + '/content');\n }",
"function getInitialScripts() {\n\t\tvar scripts = [];\n\t\tdocument.querySelectorAll( 'script' ).forEach( function( script ) {\n\t\t\tif ( script.src && script.crossOrigin === 'anonymous' && !script.src.match( /\\/base\\/tests\\// ) ) {\n\t\t\t\tscripts.push( script.src );\n\t\t\t}\n\t\t} );\n\t\treturn scripts;\n\t}",
"function getAppJavaScriptUrls(pageUrl) {\n return browser.url(pageUrl)\n .getAttribute('script', 'src')\n .then(srcs => srcs.filter(assets.isAppJavaScript));\n }",
"function getMapForScript(url) {\n if (cache[url]) {\n return cache[url];\n } else {\n var promise = $http.get(url).then(function (response) {\n var m = response.data.match(/\\/\\/# sourceMappingURL=(.+\\.map)/);\n if (m) {\n var path = url.match(/^(.+)\\/[^/]+$/);\n path = path && path[1];\n return $http.get(path + '/' + m[1]).then(function (response) {\n return new SMConsumer(response.data);\n });\n } else {\n return $q.reject();\n }\n });\n cache[url] = promise;\n return promise;\n }\n }",
"function addScriptToPage(src, label, callback) {\n let $script = document.createElement('script');\n $script['src'] = src;\n $script['data-label'] = label;\n $script.onload = callback;\n document.head.appendChild($script);\n }",
"function includeJS(file_path){ \r\n var j = document.createElement(\"script\");\r\n j.type = \"text/javascript\";\r\n j.onload = function(){\r\n lib_loaded(file_path);\r\n };\r\n j.src = file_path;\r\n document.getElementsByTagName('head')[0].appendChild(j); \r\n}",
"function getJavaScriptContent(url, processor) {\n return bluebird.map(getAppJavaScriptUrls(url), requests.fetch)\n .then(responses => bluebird.map(responses, response => response.body))\n .then(function(contents) {\n return contents.forEach(function(content) {\n processor(content);\n });\n });\n }",
"function loadDynamicScripts(context) {\n var scriptPaths = context.scriptPaths;\n// var temp = scriptPaths[0];\n// scriptPaths[0] = scriptPaths[6];\n// scriptPaths[6] = temp;\n// console.log(\"scriptPaths Length: \" + scriptPaths.length);\n\n //console.log(\"scriptPaths: \" + scriptPaths);\n\n return new Promise(function (resolve, reject) {\n var loadScript, loadNext, settings;\n\n function failure() {\n var err = new Error(\"Unable to load \" + settings.url);\n reject(err);\n }\n\n\n settings = {};\n settings.dataType = \"script\";\n settings.contentType = false;\n settings.cache = true;\n\n loadScript = function (path) {\n settings.url = path;\n\n if (path) {\n $.ajax(settings).then(loadNext, failure);\n } else {\n resolve(context);\n }\n };\n\n loadNext = function () {\n loadScript(scriptPaths.shift());\n };\n\n loadNext();\n });\n }",
"function executeScript() {\n chrome.tabs.executeScript(null, {\n file: 'scripts/getPagesSource.js'\n }, function() {\n // If you try and inject into an extensions page or the webstore/NTP you'll get an error\n if (chrome.runtime.lastError) {\n showErrorNotification('There was an error injecting script : \\n' + chrome.runtime.lastError.message, true);\n }\n });\n}",
"function getEndpoint(path) {\r\n\tvar script = document.createElement('script');\r\n\r\n\tscript.type = \"text/javascript\";\r\n\tscript.src = \"https://ign-apis.herokuapp.com\" + path;\r\n\r\n\tdocument.body.appendChild(script);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds a `Touch` with a specific ID in a `TouchList`. | function findMatchingTouch(touches, id) {
for (var i = 0; i < touches.length; i++) {
if (touches[i].identifier === id) {
return touches[i];
}
}
return undefined;
} | [
"function finditembyid (id) {\n\tfor (var i = 0; i < food_pickup.length; i++) {\n\t\tif (food_pickup[i].id == id) {\n\t\t\treturn food_pickup[i]; \n\t\t}\n\t}\n\treturn false; \n}",
"function findPerson(id) {\n var foundPerson = null;\n for (var i = 0; i < persons.length; i++) {\n var person = persons[i];\n if (person.id == id) {\n foundPerson = person;\n break;\n }\n }\n\n return foundPerson;\n }",
"getTouchesFromIDs(targetTouches, touchIDs) {\n const usedTouches = new Array(touchIDs.length);\n for (let i = 0; i < usedTouches.length; i++) {\n for (const targetTouch of targetTouches) {\n if (targetTouch.identifier === touchIDs[i]) {\n usedTouches[i] = targetTouch;\n }\n }\n }\n return usedTouches;\n }",
"function findTruckWithID (truckID) {\n\tif(isArrayEmpty(localTruckArray)) return -2; // aey - if no trucks\n\tfor(let i = 0; i < localTruckArray.length; i++) {\n\t\tif(localTruckArray[i].id == truckID) return i; // aey - id was found, return where it was found\n\t}\n\treturn -1;\n}",
"function getIndexOfId(list, item) {\n return list.map(function(e) {\n return e.ID;\n }).indexOf(item);\n}",
"function searchForIdInArray(id,array){\n var returnValue;\n var position;\n\n (DEBUG || ALL ) && console.debug(\"Searching for id\",id,\"in\",array);\n for (position = 0; position < array.length; position++) {\n if (array[position].keyID === id) {\n returnValue = array[position];\n (DEBUG || ALL) && console.log(\"found!\");\n break;\n }\n }\n return returnValue;\n }",
"function findID(videos, id){\r\n for(var k = 0; k < videos.length;k++){\t\t\t\t// Iterate through videos.\r\n if(videos[k].id == id) return videos[k];\t\t\t// Return if it matches given id.\r\n }\r\n}",
"findObject(id) {\n\t\tfor (var i in this.gameobjects) {\n\t\t\tif (this.gameobjects[i].id == id) {\n\t\t\t\treturn this.gameobjects[i];\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"findItem(id) {\n if (this.manifest && id) {\n return this.manifest.items.find((item) => {\n if (item.id !== id) {\n return false;\n }\n return true;\n });\n }\n return null;\n }",
"function movieExistsById(movieList, id){\r\n\r\n for(let i = 0; i < movieList.length; i++){\r\n if (movieList[i].id === id) {\r\n return true\r\n }\r\n }\r\n\r\n return false\r\n}",
"function selectItemByAttr(attrName, attrValue, targetList)\n{\n for(var i = 0; i< targetList.length; i++)\n {\n if(targetList[i][attrName] == attrValue)\n return targetList[i];\n }\n return null;\n}",
"function extractItem(items, id) {\n for (var i = 0; i < items.length; i++)\n if (items[i].id == id)\n return items.splice(i, 1)[0];\n }",
"function lookupPersonByID(id, people) {\n let person = people.find(function (person) {\n if (person.id === id) {\n return person;\n } else {\n return undefined;\n }\n });\n console.log('selected: ', person);\n return person; // person\n}",
"findImage (data, id) {\n return data.find(image => image.id === id);\n }",
"function SearchUserById(userId) {\n for (var i = 0; i < Users.length; i++) {\n if (Users[i].id === userId) {\n return Users[i];\n }\n }\n return null;\n}",
"checkID(id){\n for (var i = 0; i < this.player_list.length; i++) {\n if (this.player_list[i].id == id) {\n return true;\n }\n }\n return false;\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 getPointId(uniqueId) {\n var markersCount = markers.length - 1;\n for (var j = markersCount; j > -1; j--) {\n if (markers[j].listId == uniqueId) {\n return j;\n }\n }\n}",
"function selectList(listid) {\n let list = lists.filter(list => list.id == listid)[0];\n list.selected = true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get backgrounds elements in screen | function getElementsInScreen () {
return new Promise((resolve, reject) => {
elements.firstBackground = document.getElementById(firstBackground)
elements.secondBackground = document.getElementById(secondBackground)
if (elements.firstBackground && elements.secondBackground) resolve()
if (!elements.firstBackground || !elements.secondBackground) reject(new Error('Error finding elements'))
})
} | [
"function getBackground() {\n if ($('body').css('backgroundImage')) {\n return $('body').css('backgroundImage').replace(/url\\(\"?(.*?)\"?\\)/i, '$1');\n }\n }",
"function get_background_image()\n{\n\t//Get bg image\n \t$('#instagram-feed .slick-active:not(.loaded)').each(function()\n \t{\n\t var $bg = $(this).attr(\"data-background\");\n\t \t\n\t $(this).css('background-image','url(' + $bg + ')').addClass(\"loaded\");\t \n \t});\t\n}",
"function createTitleScreenBackground() {\n for (var i = 0; i < 10; i++) {\n titleBackground[i] = [];\n for (var j = 0; j < 8; j++) {\n titleBackground[i][j] = new TitleBackground(Math.floor(random(0, width)), Math.floor(random(0, height)), random(1, 5));\n }\n }\n}",
"function getNutrientBackgroundColors() {\n let carbsColor = getComputedStyle(document.body).getPropertyValue('--carbs-color');\n let fatColor = getComputedStyle(document.body).getPropertyValue('--fat-color');\n let proteinColor = getComputedStyle(document.body).getPropertyValue('--protein-color');\n return [carbsColor, fatColor, proteinColor];\n}",
"function GetBgColor()\n{\n\t// if (3.0 > h5Ver && !MainPhotos[startIdxY][startIdxX].complete) return;\n\t// if (3.0 <= h5Ver && !MainPhotosTiny[startIdxY][startIdxX].complete) return;\n\t// if (isBgColorSet) return;\n\t// var tempCanvas = document.createElement('canvas'); \n\t// tempCanvas.width = 1; \n\t// tempCanvas.height = 1; \n\t// var tempContext = tempCanvas.getContext(\"2d\"); \n\t// if (3.0 > h5Ver) tempContext.drawImage(MainPhotos[startIdxY][startIdxX], 10, 10, 1, 1, 0, 0, 1, 1);\n\t// else tempContext.drawImage(MainPhotosTiny[startIdxY][startIdxX], 10, 10, 1, 1, 0, 0, 1, 1);\n\t// var imgData = tempContext.getImageData(0, 0, 1, 1);\n\t// bgRed = imgData.data[0];\n\t// bgGreen = imgData.data[1];\n\t// bgBlue = imgData.data[2];\n\t// isBgColorSet = true;\n\t// delete tempCanvas;\n\t// Log(\"BackColor: \" + bgRed + \", \" + bgGreen + \", \" + bgBlue);\n}",
"function selBackground(name) {\n if (name === 'Death Star') return DeathStarBackgrounds[Math.floor(Math.random()*DeathStarBackgrounds.length)];\n else if (name === 'Star Destroyer') return starDestroyersBackgrounds[Math.floor(Math.random()*starDestroyersBackgrounds.length)];\n else if (name === 'Millennium Falcon') return MilleniumFalconBackgrounds[Math.floor(Math.random()*MilleniumFalconBackgrounds.length)];\n else if (name === 'X-wing') return XWingBackgrounds[Math.floor(Math.random()*XWingBackgrounds.length)];\n else if (name === 'Rebel transport') return RebelTransportBackground;\n else if (name === 'CR90 corvette') return corvetteBackground;\n else if (name === 'Sentinel-class landing craft') return landingCraftBackgrounds[Math.floor(Math.random()*landingCraftBackgrounds.length)];\n else if (name === 'Y-wing') return YWingBackground;\n else if (name === 'TIE Advanced x1') return TIEbackgrounds[Math.floor(Math.random()*TIEbackgrounds.length)];\n else if (name === 'Executor') return executorBackgrounds[Math.floor(Math.random()*executorBackgrounds.length)];\n}",
"function updateBackground() {\n var whichBackgroundIndex = (currentStep / bgChangeStepInterval) - 1;\n // print(\"whichBackgroundIndex: \"+whichBackgroundIndex);\n bg = loadImage(\"images/\" + bgImageNames[whichBackgroundIndex]);\n}",
"setBackgroundSizeConfig() {\n let backgroundSizeConfig = [];\n for (let xAxisIndex = 0; xAxisIndex < 4; xAxisIndex++) {\n for (let yAxisIndex = 0; yAxisIndex < 3; yAxisIndex++) {\n backgroundSizeConfig.push((xAxisIndex * this.blockWidth) + 'px ' + (yAxisIndex * this.blockHeight) + 'px ');\n }\n }\n return backgroundSizeConfig;\n }",
"getBackgroundStyle(childs) {\n\n if (!isArray(childs) || childs.length === 0) {\n return 'transparent';\n }\n\n let colors = A(A(childs).getEach('color'));\n colors = colors.uniq(); // every color only once!\n colors = colors.sort(); // assure color-order always the same\n colors = colors.filter(color => !isEmpty(color)); // remove empty color strings\n\n\n // single-color\n if (colors.length === 1) {\n return colors[0];\n }\n\n // multi-color\n let background = 'repeating-linear-gradient(90deg,'; // or 180? ;)\n let pxOffset = 0;\n let stripeWidth = get(this, 'stripeWidth');\n\n colors.forEach(color => {\n let nextOffset = pxOffset+stripeWidth;\n background+= `${color} ${pxOffset}px,${color} ${nextOffset}px,`;\n pxOffset = nextOffset;\n });\n\n background = background.substring(0, background.length-1) + ')';\n\n return background;\n }",
"function createBgChooser() {\n let bgChooserList = document.createElement('ul');\n for (let i = 1; i <= 5; i++) {\n let bgElem = document.createElement('li');\n bgElem.classList.add('bgChooser');\n let bg = document.createElement('img');\n let imgSrc = \"./assets/backgrounds/bg\" + i + \".jpg\";\n bg.src = imgSrc;\n bgElem.appendChild(bg);\n bgElem.addEventListener('click', () => {\n let imageObj = new Image();\n imageObj.onload = function () {\n context.drawImage(imageObj, 0, 0, board.width, board.height);\n };\n imageObj.src = imgSrc;\n });\n bgChooserList.appendChild(bgElem);\n }\n bgImgHolder.appendChild(bgChooserList);\n bgListOpened = true;\n}",
"function getColors(){\n var rgb = mixerBottle.attr('style').replace('background-color: rgb(', '').replace(')', '').split(',');\n return rgb.map(x => parseInt(x));\n }",
"function initBgImages() {\n if ($('.has-background-image').length) {\n $(\".has-background-image\").each(function () {\n var bgImage = $(this).attr('data-background');\n if (bgImage !== undefined) {\n $(this).css('background-image', 'url(' + bgImage + ')');\n }\n }\n )\n }\n}",
"function initBackgroundImages() {\n const self = this;\n\n if (!self.options.enableMouseParallax) {\n return;\n }\n\n const $parallaxImages = $('.nk-main .bg-image').parent().add($('.nk-main .bg-image'));\n\n // fix for Jarallax\n $parallaxImages.css('transform', 'translate3d(0,0,0)');\n\n self.parallaxMouseInit();\n $wnd.on('resize scroll load', () => {\n self.parallaxMouseInit();\n });\n}",
"function _renderBackground () {\n\t_ctx.fillStyle = _getColor(\"background\");\n _ctx.fillRect(0, 0, _ctx.canvas.clientWidth, _ctx.canvas.clientHeight);\n}",
"function drawGround() {\n //back layer\n for (let i = 0; i < PLAYING_FIELD_LENGTH; i = i + 2) {\n addBackgroundImage(backgroundImages.ground[0], bg3_ground_x, bg_element_y, i);\n addBackgroundImage(backgroundImages.ground[1], bg3_ground_x, bg_element_y, i + 1);\n }\n //middle layer\n for (let i = 0; i < PLAYING_FIELD_LENGTH; i = i + 2) {\n addBackgroundImage(backgroundImages.ground[2], bg2_ground_x, bg_element_y, i);\n addBackgroundImage(backgroundImages.ground[3], bg2_ground_x, bg_element_y, i + 1);\n }\n //front layer\n for (let i = 0; i < PLAYING_FIELD_LENGTH; i = i + 2) {\n addBackgroundImage(backgroundImages.ground[4], bg1_ground_x, bg_element_y, i);\n addBackgroundImage(backgroundImages.ground[5], bg1_ground_x, bg_element_y, i + 1);\n }\n}",
"function _initDebugBackground() {\n if (!this.options.debug) return;\n\n this.containers.forEach(function(containerObj, i) {\n\n var background = new Surface({\n properties: {\n background: 'black',\n border: '1px dashed green',\n zIndex: '-9999999'\n }\n });\n\n containerObj.container.add(background);\n });\n}",
"function generateDefaultShibeImgs() {\n const shibeImg = document.getElementsByClassName(\"img-bk\")\n\n for(let i = 0; i < shibeImg.length; i++) {\n shibeImg[i].style.backgroundImage = `url(${shibeImgs[Math.floor(\n Math.random() * shibeImgs.length)]}\n )`\n }\n}",
"function drawBackground() {\n image(imgBackground, width / 2, height / 2); // dimensions: 100 X 56\n\n // table for tray\n rectMode(CORNER);\n fill(\"#B8F4FA\"); // light blue\n rect(0, height - 30, width, 30);\n\n image(imgTray, trayX, trayY); // tray dimensions: 130 X 78\n\n displayScore();\n drawStacked();\n}",
"function createBackground() {\n var background = this.add.image(256, 256, \"background\");\n background.setScale(2.2, 2.5);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the current host, including the protocol, origin and port (if any). Does not end with a trailing '/'. | function getHost() {
return location.protocol + '//' + location.host
} | [
"_getHostname() {\r\n let host = this._os.hostname() || '';\r\n if (host.indexOf('.') < 0) { // ignore if not FQDN\r\n host = '[127.0.0.1]';\r\n }\r\n else if (host.match(/^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/)) { // IP mut be enclosed in []\r\n host = `[${host}]`;\r\n }\r\n return host;\r\n }",
"function NLGetCurrentScriptFileHostName()\n{\n var scripts = document.getElementsByTagName('script');\n if (!scripts || scripts.length == 0)\n return null;\n\n var currentScriptFileUrl = scripts[scripts.length - 1].src;\n if (!currentScriptFileUrl)\n return null;\n\n var hostName = currentScriptFileUrl.match(/^((http|https):\\/\\/)?[^\\/]+/g);\n if (hostName && hostName.length>0)\n hostName = hostName[0];\n if (!hostName)\n hostName = \"\";\n\n return hostName;\n}",
"function getHostByArg() {\n\t//Recojemos los parametros con slice a partir del segundo elemento de la peticion\n\tvar args = process.argv.slice(2);\n\n\t//Valor por defecto para el host\n\tvar host = '127.0.0.1';\n\n\t//console.log(\"Host \" + host);\n\n\tif (args.length > 0) {\n\t\t//Procesamos el array de parametros para conocer el par host:puerto\n\t\tvar aux = args[0]\n\t\tvar args_split = aux.split(\":\");\n\n\t\t//Asignamos a host el valor anterior a la aparicion del separador :\n\t\thost = args_split[0];\n\n\t\t//console.log(\"Host \" + host);\n\t}\n\n\treturn host;\n}",
"getServiceBaseHostURL() {\n let routeInfo = this.store.peekRecord('nges-core/engine-route-information', 1);\n\n //if(!routeInfo) routeInfo = this.store.peekRecord('nges-core/engine-route-information', 2);\n let hostUrl = 'http://' + routeInfo.appCode + '.' + routeInfo.appModuleCode + config.NGES_SERVICE_HOSTS.APP_SERVICE_POST_HOST;\n return hostUrl;\n }",
"function getPrimaryDomain(givenHost) {\n\tif (givenHost.toLowerCase().indexOf(\"www.\") === 0)\n\t\tgivenHost = givenHost.substring(4, givenHost.length);\n\n\tvar splitHost = givenHost.split(\".\");\n\n\tvar lastTerm = splitHost[splitHost.length - 1];\n\t\t\n\tif (splitHost.length > 2) {\n\t\tif (lastTerm === \"au\" || lastTerm === \"jp\" || lastTerm === \"nz\" || lastTerm === \"za\") {\n\t\t\tif (splitHost[splitHost.length - 2] === \"co\" || splitHost[splitHost.length - 2] === \"com\")\n\t\t\t\tgivenHost = splitHost[splitHost.length - 3] + \".\" + splitHost[splitHost.length - 2] + \".\" + splitHost[splitHost.length - 1];\n\t\t\telse\n\t\t\t\tgivenHost = splitHost[splitHost.length - 2] + \".\" + splitHost[splitHost.length - 1];\n\t\t}\n\t\telse\n\t\t\tgivenHost = splitHost[splitHost.length - 2] + \".\" + splitHost[splitHost.length - 1];\n\n\t}\n\tconsole.log (\"currentHost: \" + givenHost);\n\t\n\treturn givenHost;\n}",
"function extractHostname(t) {\n return (t.indexOf(\"//\") > -1 ? t.split(\"/\")[2] : t.split(\"/\")[0]).split(\":\")[0].split(\"?\")[0]\n}",
"function getManagementAPIServerBaseUrl() {\n\n // todo: implementation will change after changes are done to the IS.\n\n const baseOrganizationUrl = config.AuthorizationConfig.BaseOrganizationUrl;\n const matches = baseOrganizationUrl.match(/^(http|https)?\\:\\/\\/([^\\/?#]+)/i);\n const domain = matches && matches[0];\n\n return domain;\n}",
"function isLocalhost(){\n return window.location.origin.includes(\"localhost:8088\");\n}",
"function resolveHost(domain)\r\n{\r\n var hostString = \"www\";\r\n \r\n if(domain == \"lexis\" || domain == \"nexis\") \r\n hostString = \"w3\"; \r\n \r\n return hostString;\r\n}",
"function domainParse(){\n var l = location.hostname\n return {\n \"prot\": location.protocol,\n \"host\": l,\n \"statics\" : 'cdn.kaskus.com'\n };\n}",
"function getRootUrl(url) {\n var domain = url.replace('http://','').replace('https://','').replace('www.', '').split(/[/?#]/)[0];\n return domain;\n}",
"get domain() {\n var result = 'unknown';\n if (this.sourceInfo_ && this.sourceInfo_.domain)\n result = this.sourceInfo_.domain;\n if (result === 'unknown' && this.parentFrame)\n result = this.parentFrame.domain;\n return result;\n }",
"function getServerTargetUrl(path) {\n var x = require('MeshAgent').ServerUrl;\n //sendConsoleText(\"mesh.ServerUrl: \" + mesh.ServerUrl);\n if (x == null) { return null; }\n if (path == null) { path = ''; }\n x = http.parseUri(x);\n if (x == null) return null;\n return x.protocol + '//' + x.host + ':' + x.port + '/' + path;\n}",
"function PT_getSubdomain() {\n var PT_regexParse = new RegExp('[a-z\\-0-9]{2,63}\\.[a-z\\.]{2,5}$');\n var PT_urlParts = PT_regexParse.exec(window.location.hostname);\n\n return window.location.hostname.replace(PT_urlParts[0], '').slice(0, -1);\n}",
"function getSiteRoot() {\r\n\tvar url = window.location.protocol + '//' + window.location.host,\r\n\t\tpath = '/Site';\r\n\tif (window.location.pathname.indexOf(path) == 0) {\r\n\t\turl += path\r\n\t}\r\n\treturn url + '/';\r\n}",
"function getServerUrl() {\n\n var url = null,\n localServerUrl = window.location.protocol + \"//\" + window.location.host,\n context = getContext();\n\n\n if ( Xrm.Page.context.getClientUrl !== undefined ) {\n // since version SDK 5.0.13\n // http://www.magnetismsolutions.com/blog/gayan-pereras-blog/2013/01/07/crm-2011-polaris-new-xrm.page-method\n\n url = Xrm.Page.context.getClientUrl();\n }\n else if ( context.isOutlookClient() && !context.isOutlookOnline() ) {\n url = localServerUrl;\n }\n else {\n url = context.getServerUrl();\n url = url.replace( /^(http|https):\\/\\/([_a-zA-Z0-9\\-\\.]+)(:([0-9]{1,5}))?/, localServerUrl );\n url = url.replace( /\\/$/, \"\" );\n }\n return url;\n }",
"function getServerUrl() {\n\n if (SERVER_URL === null) {\n\n var url = null,\n localServerUrl = window.location.protocol + \"//\" + window.location.host,\n context = getContext();\n\n\n if ( Xrm.Page.context.getClientUrl !== undefined ) {\n // since version SDK 5.0.13 \n // http://www.magnetismsolutions.com/blog/gayan-pereras-blog/2013/01/07/crm-2011-polaris-new-xrm.page-method\n\n url = Xrm.Page.context.getClientUrl();\n }\n else if ( context.isOutlookClient() && !context.isOutlookOnline() ) {\n url = localServerUrl;\n }\n else {\n url = context.getServerUrl();\n url = url.replace( /^(http|https):\\/\\/([_a-zA-Z0-9\\-\\.]+)(:([0-9]{1,5}))?/, localServerUrl );\n url = url.replace( /\\/$/, \"\" );\n }\n\n SERVER_URL = url;\n\n }\n\n return SERVER_URL; \n }",
"function _format(host, port) {\n return url.format({\n slashes: true,\n protocol: 'tcp',\n hostname: host,\n port: port\n });\n}",
"parsePath() {\n var protocol = goog.array.contains(this.map_['schemes'], 'https') ?\n 'https' : 'http';\n var host = this.map_['host'];\n var basepath = goog.isString(this.map_['basePath']) ?\n this.map_['basePath'] : '';\n var uri = new goog.Uri();\n uri.setScheme(protocol);\n uri.setDomain(host);\n uri.setPath(basepath);\n this.path = uri.toString();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
realestateobject update on PUT. | function realestateobject_update(req, res, next) {
console.log('Real estate object update');
RealEstateObjects.findByIdAndUpdate(req.params.id, req.body)
.then(realestateobject => {
res.send(realestateobject);
})
.catch(error => next(error));
} | [
"updateObject({dispatch, commit, state, getters}, data) {\n var config = {data: prepareData(data, state.prepare) };\n config.method = 'PUT';\n config.url = getters.urlID;\n return dispatch('callAPI', config, {root:true}).then(response=>{\n commit('updateModel', response.data);\n return response.data;\n });\n\n }",
"function put() {\n\n // Create a url for the ajax request.\n $.each(editObject, function(index, value) {\n if(index == 'id') {\n url += index+\"=\"+value;\n } else {\n url += \"&\"+index+\"=\"+value;\n }\n });\n\n $.ajax({\n url: 'api/?'+url,\n method: 'PUT',\n data: editObject,\n success: function() {\n // Log a message apon success.\n console.log(\"Item updated in inventory.\");\n\n // Reload the search from's select dropdowns and the table body.\n reloadSelectDropdowns();\n get();\n\n // Clear the url string.\n url = \"\";\n },\n error: function (xhr, ajaxOptions, thrownError) {\n // Log any error messages.\n console.log(xhr.status);\n console.log(thrownError);\n }\n });\n}",
"patch(req, res) {\n return this.endpoint.store.update(req.user, req.query, req.body)\n }",
"update(req, res) {\n Request.findByIdAndUpdate(req.params.id, req.body, {\n runValidators: true,\n new: true,\n })\n .then((updatedRequest) => res.json(updatedRequest))\n .catch((err) => res.status(400).json(err));\n }",
"function handle_put(parsedRequest,data) {\n // TODO: enforce put vs post rules, for now\n // they can both do the same\n return handle_post(parsedRequest,data);\n }",
"async update ({ params, request, response }) {\n const requestAll = request.all()\n\n const find = await Vagas.find(params.id)\n\n if(!find){\n response.status(404)\n return HelpersStatusCode.status404()\n }\n\n find.merge({...requestAll})\n\n await find.save()\n\n return HelpersStatusCode.status200()\n }",
"update(id, entity, config) {\n const url = this.resolveUrl(config, id);\n const method = (config && config.method) || this.getHttpMethod(HttpMethod.PUT);\n this.loader.dispatch({\n method,\n loading: true,\n entityId: id,\n storeName: this.store.storeName,\n });\n const configWithBody = Object.assign(Object.assign({}, config), { body: entity });\n return this.http.request(method, url, configWithBody).pipe(mapResponse(config), tap((responseEntity) => {\n if (!config || (config && !config.skipWrite)) {\n this.store.update(id, responseEntity);\n }\n this.dispatchSuccess({\n method,\n payload: responseEntity,\n successMsg: config && config.successMsg,\n });\n }), catchError((error) => this.handleError(method, error, config && config.errorMsg)), finalize(() => {\n this.loader.dispatch({\n method,\n loading: false,\n entityId: id,\n storeName: this.store.storeName,\n });\n }));\n }",
"update(req, res) {\n Origin.update(req.body, {\n where: {\n id: req.params.id\n }\n })\n .then(function (updatedRecords) {\n res.status(200).json(updatedRecords);\n })\n .catch(function (error){\n res.status(500).json(error);\n });\n }",
"function update(Model,_id,updated_obj){\n const promise = new Promise((resolve,reject)=>{\n Model.findOneAndReplace(_id,updated_obj,(err,docs)=>{\n \tif (err) {\n \t\treject(err);\n \t\treturn;\n \t}\n \tresolve(docs)\n })\n })\n return promise;\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 updatePlaceResultObject(tobeupdated,update){\n\ttobeupdated.geometry= update.geometry;\n\ttobeupdated.icon=update.icon;\n\ttobeupdated.name=update.name;\n\ttobeupdated.vicinity=update.vicinity;\n\t}",
"updateById(id, data) {\n return this.post('/' + id + '/edit', data);\n }",
"async function update(req, res) {\n let _id = req.params.venueId;\n let {\n name, type, imgUrl, about, phone, email, \n minCustomers, maxCustomers, zip, address \n } = req.body;\n\n let doc = compressDoc({\n _id, name, type, imgUrl, about, phone, email,\n minCustomers, maxCustomers, zip, address\n });\n\n let data = await venueService.update(doc);\n let payload = new Res.Ok({ data });\n res.status(payload.status).json(payload);\n}",
"function editLibraryMethod(req, res, libraryEncontrado, body) {\n updateLibrary(libraryEncontrado.id, body)\n .then((libraryUpdated) => {\n libraryUpdated ? RESPONSE.success(req, res, libraryUpdated, 200) : RESPONSE.error(req, res, 'No se puede modificar este libro.', 404);\n })\n .catch((err) => {\n console.log(err);\n return RESPONSE.error(req, res, 'Error Interno', 500);\n });\n}",
"update(req, res) {\n return Education\n .find({\n where: {\n id: req.params.educationId,\n resumeId: req.params.resumeId,\n },\n })\n .then(education => {\n if (!education) {\n return res.status(404).send({\n message: 'education Not Found',\n });\n }\n \n return education\n .update(req.body, { fields: Object.keys(req.body) })\n\n .then(updatedEducation => res.status(200).send(updatedEducation))\n .catch(error => res.status(400).send(error));\n })\n .catch(error => res.status(400).send(error));\n }",
"updateQuantity(post, newQuantity) {\n // Field to send to /api/v3/posts/:post_id\n const field = {\n quantity: parseInt(newQuantity),\n };\n\n // Make API request to Rogue to update the quantity on the backend\n let request = this.api.patch(`api/v3/posts/${post['id']}`, field);\n\n request.then(result => {\n // Update the state\n this.setState(previousState => {\n const newState = { ...previousState };\n newState.posts[post['id']].quantity = result.data['quantity'];\n\n return newState;\n });\n });\n\n // Close the modal\n this.hideHistory();\n }",
"function updateSupplier(req, res, next){ \n supplierService.update(req.params.id, req.body)\n .then((result)=> res.status(200).json(result))\n .catch((err)=>next(err));\n}",
"function updateRequest(obj) {\n var url = \"/api/club/\" + obj.id;\n var xhr = new XMLHttpRequest;\n xhr.open(\"post\", url);\n xhr.onload = function(ev) {\n console.log(ev.target.response);\n };\n xhr.send(JSON.stringify(obj));\n}",
"function apiUpdate(req, res) {\n // console.log('PUT /api/breed/:name');\n // console.log(req.params.name);\n // console.log(req.body);\n\n // update the specified breed\n db.Breed.find({'name': req.params.name}, function(err, sheep) {\n //console.log(sheep);\n if (err) {\n res.status(404).send('ERROR: breed not found; you probably need to add this breed');\n } else {\n if (req.body.infoSources) {\n // get the list of new sources\n let infoList = req.body.infoSources.split(', ');\n // we're replacing the current list of sources with the new list\n req.body.infoSources = [];\n for (let i = 0; i < infoList.length; i++) {\n req.body.infoSources.push(infoList[i]);\n }\n //console.log('srcs: ' + req.body.infoSources);\n }\n\n //console.log(sheep[0]._id);\n db.Breed.update({ '_id': sheep[0]._id }, { $set: req.body }, function(err, updatedSheep) {\n if (err) {\n res.status(503).send('ERROR: could not update sheep info');\n } else {\n res.json(updatedSheep);\n }\n });\n }\n\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the center of the cluster by taking the mean of the x and y coordinates. | function computeClusterCenter(cluster) {
return [
d3.mean(cluster, function(d) { return d.x; }),
d3.mean(cluster, function(d) { return d.y; })
];
} | [
"static centroid(cluster) {\n // NOTE: latitude [-90, 90] (South-North)\n // longitude [-180, 180] (West-East)\n let x = 0, y = 0, z = 0 // Cartesian coordinates\n for (let i = 0; i < cluster.stops.length; ++i) {\n let lat = cluster.stops[i].latitude / 180 * Math.PI\n let lon = cluster.stops[i].longitude / 180 * Math.PI\n // Convert lat/lon to Cartesian and calculate (rolling) average\n x = x * (i)/(i+1) + Math.cos(lat) * Math.cos(lon) / (i+1)\n y = y * (i)/(i+1) + Math.cos(lat) * Math.sin(lon) / (i+1)\n z = z * (i)/(i+1) + Math.sin(lat) / (i+1)\n }\n // Convert back to lat/lon\n return {latitude: Math.atan2(z, Math.sqrt(x*x + y*y)) * 180 / Math.PI, longitude: Math.atan2(y, x) * 180 / Math.PI}\n }",
"clusterMean(data) {\n let half = data.slice(0, Math.floor(data.length / 2)); // first half of distances array\n const halfMeanX = half.map(p => p.x).reduce((a, b) => a + b) / half.length; \n const halfMeanY = half.map(p => p.y).reduce((a, b) => a + b) / half.length;\n\n let end = data.slice(Math.floor(data.length / 2), data.length); // second half of distances array\n const endMeanX = end.map(p => p.x).reduce((a, b) => a + b) / end.length;\n const endMeanY = end.map(p => p.y).reduce((a, b) => a + b) / end.length;\n\n const halfMean = {\n x: halfMeanX,\n y: halfMeanY\n }\n\n const endMean = {\n x: endMeanX,\n y: endMeanY\n }\n\n return {\n half: halfMean,\n end: endMean\n }\n\n }",
"get center() {\n\n // Check if the face is bound to a mesh and if not throw an error\n if (!this.mesh) throw new Error(`Cannot compute the face center - the face is not bound to a Mesh`);\n\n // Calculate the center of the face\n return new Point(divide(add(this.a, this.b, this.c), 3));\n }",
"center() {\n return this.normal.mulX(this.d);\n }",
"static seed(cluster) {\n let centroid = this.centroid(cluster)\n let mean = undefined\n let closestDistance = undefined\n for (let s = 0; s < cluster.stops.length; ++s) { \n let distance = this.distance(centroid.latitude, centroid.longitude, cluster.stops[s].latitude, cluster.stops[s].longitude)\n if (!closestDistance || distance < closestDistance) {\n mean = cluster.stops[s]\n closestDistance = distance\n }\n }\n if (!mean) console.log(\"Could not find centroid of cluster with id: \" + cluster.id)\n return mean\n }",
"function getCenter(points) {\n\t var center = { x: 0, y: 0 };\n\t for (var i = 0; i < points.length; ++i) {\n\t center.x += points[i].x;\n\t center.y += points[i].y;\n\t }\n\t center.x /= points.length;\n\t center.y /= points.length;\n\t return center;\n\t }",
"function compute_centroid(facet, vertices) { \n var va = vertices[facet.a];\n var vb = vertices[facet.b];\n var vc = vertices[facet.c];\n\n return new THREE.Vector3(\n (va.x + vb.x + vc.x)/3,\n (va.y + vb.y + vc.y)/3,\n (va.z + vb.z + vc.z)/3\n );\n }",
"_setCenter() {\n\t\tlet width = this._dim.width;\n\t\tlet height = this._dim.height;\n\n\t\tlet leftDiff = Math.round((this._dim.areaWidth - width) / 2);\n\t\tlet topDiff = Math.round((this._dim.areaHeight - height) / 2);\n\n\t\tlet p = this._points;\n\n\t\tp.nw.x = leftDiff;\n\t\tp.nw.y = topDiff;\n\n\t\tp.ne.x = p.nw.x + width;\n\t\tp.ne.y = p.nw.y + height;\n\n\t\tp.sw.x = this._dim.areaWidth - leftDiff;\n\t\tp.sw.y = this._dim.areaHeight - topDiff;\n\n\t\tp.se.x = p.ne.x;\n\t\tp.se.y = p.ne.y;\n\t}",
"getCenter(nodes){\n var x = 0, y = 0;\n nodes.forEach(node => {x += node.x; y+= node.y; });\n return { x : x/nodes.length, y: y/nodes.length };\n}",
"function findClosestCentroid(point) {\n let closest = {i: -1, distance: width * 2};\n centroids.forEach(function(d, i) {\n let distance = getEuclidianDistance(d, point);\n if (distance < closest.distance) {\n closest.i = i;\n closest.distance = distance;\n }\n });\n return (centroids[closest.i]); \n }",
"function cell_center(x, y){\n var cell_offset = cells[x][y].cell.getBoundingClientRect();\n var grid_offset = grid.getBoundingClientRect();\n\n var cx = cell_offset.left - grid_offset.left + cell_offset.width / 2;\n var cy = cell_offset.top - grid_offset.top + cell_offset.height / 2;\n\n return { x: Math.round(cx), y: Math.round(cy) };\n }",
"function findCenter(c1, c2, c3) {\n\tvar x = (c1.x + c2.x + c3.x) / 3;\n\tvar y = (c1.y + c2.y + c3.y) / 3;\n\tvar z = (c1.z + c2.z + c3.z) / 3;\n\t\n\treturn {x: x, y: y, z: z};\n}",
"getCenter() {\n const vertices = this.vertices;\n let areaSum = 0;\n let x = 0;\n let y = 0;\n\n vertices.forEach((currVertex, currIndex) => {\n const nextIndex = (currIndex + 1) % vertices.length;\n const nextVertex = vertices[nextIndex];\n\n const areaDiff = currVertex.x * nextVertex.y - nextVertex.x * currVertex.y;\n areaSum += areaDiff;\n\n x += (currVertex.x + nextVertex.x) * areaDiff;\n y += (currVertex.y + nextVertex.y) * areaDiff;\n });\n\n // If this is a straight line\n if (!areaSum) {\n return vertices.reduce((sumVertex, currVertex) => ({\n x: sumVertex.x + (currVertex.x / this.vertices.length),\n y: sumVertex.y + (currVertex.y / this.vertices.length)\n }), {\n x: 0,\n y: 0\n });\n }\n\n const factor = areaSum * 3;\n\n return new Vertex({\n x: x / factor,\n y: y / factor\n });\n }",
"function find_perfect_center(xy_data){\n let x = Vector.transpose(Vector.pull(xy_data,[0,xy_data.length-1], [0, 0]))\n let y = Vector.transpose(Vector.pull(xy_data,[0,xy_data.length-1], [1, 1]))\n let x_bounds = [Vector.min(x), Vector.max(x)]\n let y_bounds = [Vector.min(y), Vector.max(y)]\n let mesh = generate_mesh(x_bounds, y_bounds, 6)\n //out(mesh)\n //out(xy_data)\n let inside_mesh = []\n for(let i = 0; i < mesh.length; i++){\n if(is_inside(xy_data, mesh[i])){\n inside_mesh.push(mesh[i])\n }\n }\n //out(inside_mesh)\n\n return center_calc(xy_data, inside_mesh)\n}",
"static Center(value1, value2) {\n const center = Vector3.Add(value1, value2);\n center.scaleInPlace(0.5);\n return center;\n }",
"function findCentroid(vertices) {\n\t//make a copy so that we don't mess anything up\n\tvar copy = []\n\tfor (var i = 0; i < vertices.length; i++) {\n\t\tvar p = vertices[i];\n\t\tcopy.push(new Point(p.RA, p.Dec));\n\t}\n\n\tvar min = Math.min.apply(null, copy.map(function(a){return a.RA;}));\n\tvar max = Math.max.apply(null, copy.map(function(a){return a.RA;}));\n\n\tif(max - min > FULL_CIRCLE / 2) {\n\t\tfor (var i = 0; i < copy.length; i++) {\n\t\t\tvar p = vertices[i];\n\t\t\tif(p.RA < FULL_CIRCLE / 2) {\n\t\t\t\tcopy[i].RA += FULL_CIRCLE;\n\t\t\t}\n\t\t}\n\t}\n\n\t//see also http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon\n\tvar cx = 0;\n\tvar cy = 0;\n\tvar A = 0;\n\n\tvar last = copy[copy.length - 1];\n\tfor (var i = 0; i < copy.length; i++) {\n\t\tvar p = copy[i];\n\t\tcx += (last.RA + p.RA )*(last.RA*p.Dec - p.RA*last.Dec);\n\t\tcy += (last.Dec + p.Dec)*(last.RA*p.Dec - p.RA*last.Dec);\n\t\tA += (last.RA*p.Dec - p.RA*last.Dec);\n\n\t\tlast = p;\n\t}\n\t\n\tA /= 2;\n\tcx /= (6*A);\n\tcy /= (6*A);\n\t\n\treturn new Point(cx, cy);\n}",
"static Center(value1, value2) {\n const center = Vector2.Add(value1, value2);\n center.scaleInPlace(0.5);\n return center;\n }",
"centreOn() {\r\n let mx, my;\r\n if (typeof arguments[0] === \"number\" && typeof arguments[1] === \"number\") {\r\n mx = constrain(arguments[0], 0, this.SIZE - 1);\r\n my = constrain(arguments[1], 0, this.SIZE - 1);;\r\n } else if (typeof arguments[0] === \"string\") {\r\n if ((arguments[0].toLowerCase() === 'center') || (arguments[0].toLowerCase() === 'centre')) {\r\n mx = (this.SIZE - 1) / 2;\r\n my = (this.SIZE - 1) / 2;\r\n }\r\n } else {\r\n throw new Error(\"Unexpected Input\");\r\n }\r\n let x, y;\r\n x = width / 2 - this.TILE_SIZE * constrain(mx, 0, this.SIZE - 1);\r\n y = height / 2 - this.TILE_SIZE * constrain(my, 0, this.SIZE - 1);\r\n this.offset.set(createVector(x, y));\r\n }",
"static Center(value1, value2) {\n const center = Vector4.Add(value1, value2);\n center.scaleInPlace(0.5);\n return center;\n }",
"function findCenter(coordinatesList){\n\t\tvar i=0;\n\t\tvar x=0;\n\t\tvar y=0\n\t\tvar pointsSoFar=0;\n\t\tfor(i;i<coordinatesList.length;i++){\n\t\t\tx+=coordinatesList[i][0];\n\t\t\ty+=coordinatesList[i][1];\n\t\t\tpointsSoFar+=1;\n\t\t}\n\t\treturn [x/pointsSoFar,y/pointsSoFar];\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get html contents from assets directory | retrieveHtml() {
const html = fs.readFileSync('./assets/plano.html', 'utf-8')
return html
} | [
"function getHtmlContent(){\n \n }",
"function assetsTask() { return src('assets/**/*') .pipe(dest('dist/assets')) }",
"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}",
"function html() {\n return src('src/pug/*.pug')\n .pipe(pug({\n pretty: true\n }))\n // .on(\"error\", notify.onError(\"Error: <%= error.message %>\"))\n .pipe(dest('dist'))\n}",
"getStyleAssets() {\n if (this.css.length > 0) {\n this.css.forEach((css, index, arry) => {\n const rewriter = new URLRewriter(function (url) {\n if (!helper.assetCheck(url)) {\n return url;\n }\n // If url hast '?' in it, this may be used for parameter. We should cut off this, for file access.\n const checkParam = url.indexOf(\"?\");\n let cleanUrl = url;\n if (checkParam > -1) {\n cleanUrl = url.substring(0, checkParam);\n // console.log(\"URL: \" + url + \" -> \" + cleanUrl);\n }\n const srcPath = helper.getPathFile(\"\", css.src, cleanUrl);\n const destPath = helper.getPathFile(\"\", css.dest, cleanUrl);\n css.assets.push({\n html: css.name,\n dest: destPath,\n src: srcPath,\n name: url,\n type: path.extname(cleanUrl).substring(1)\n });\n return url;\n });\n const result = rewriter.rewrite(css.content);\n });\n }\n return this;\n }",
"function assetsHandler(url, response) {\n var extension = url.split(\".\")[1];\n var extensionType = {\n html: \"text/html\",\n css: \"text/css\",\n js: \"application/javascript\",\n ico: \"image/x-icon\",\n jpg: \"image/jpeg\",\n png: \"image/png\",\n json: \"application/json\"\n };\n var filePath = path.join(__dirname, \"..\", \"public\", url);\n fs.readFile(filePath, function(error, file) {\n if (error) {\n response.writeHead(500, { \"Content-Type\": \"text/html\" });\n response.end(\"<h1>sorry, something went wrong</h1>\");\n } else {\n response.writeHead(200, { \"Content-Type\": extensionType[extension] });\n response.end(file);\n }\n });\n}",
"function rmHtml() {\n\treturn rm(`${config.dist}/*.html`);\n}",
"getProjectsHtmlFolder(): string {\n let projectsPathHtml = join(this.projectFolder, 'html');\n if (!existsSync(projectsPathHtml)) {\n mkdirSync(projectsPathHtml);\n }\n return projectsPathHtml;\n }",
"contentFor(page) {\n\t\tlet reader = this.readers[page.extension];\n\t\tlet pathToFile = this.pathToPageContent(page);\n\n\t\tlet content = '';\n\t\tif (typeof reader.readFile !== 'undefined') {\n\t\t\tcontent = reader.readFile(pathToFile);\n\t\t} else {\n\t\t\tcontent = fs.readFileSync(pathToFile, 'utf8');\n\t\t}\n\n\t\tif (!reader) {\n\t\t\tthrow new Error(`No reader for file extension '${page.extension}'`)\n\t\t} else if (typeof reader.read !== 'function') {\n\t\t\tthrow new Error(`Reader for file extension '${page.extension}' has no read method`);\n\t\t}\n\n\t\treturn reader.read(content);\n\t}",
"function writeHtml() {\n return gulp.src('index.html')\n .pipe(htmlreplace({\n 'js-bundle': 'bundle.js'\n })).pipe(useref())\n .pipe(gulp.dest('build/'));\n}",
"async web (relativePath, systemPath, stripSlashes) {\n const indexNames = []\n const file = new File(join(systemPath, 'index.html'))\n try {\n await file.stat()\n } catch (err) {}\n const hasIndex = file.mode && file.isFile()\n if (hasIndex) {\n indexNames.push('index.html')\n }\n return handler(relativePath, systemPath, stripSlashes, false, !hasIndex, indexNames)\n }",
"function fun( error , response , data ){\n // current directory => homepage.html , => html file of webpage\n parseData(data);\n}",
"function copyAssets () {\n return gulp.src(ASSET_SOURCE_PATH + '/**/*')\n .pipe(gulp.dest(BUILD_PATH + '/assets'));\n}",
"function getIndexHtml(searchString) {\n var deferred = $q.defer();\n $http.get(secSearchServiceBase + 'fetchIndex?url=' + searchString)\n .success(function(data) {\n deferred.resolve(data);\n })\n .error(function(msg, status) {\n deferred.reject(msg);\n })\n return deferred.promise;\n }",
"function getSPProjectAssets() {\n\tvar root = window.location.origin;\n\tvar pathname = window.location.pathname;\n\tvar projectname = pathname.substring(pathname.lastIndexOf('/')-1);\n\tvar filename = pathname.substring(pathname.lastIndexOf('/')+1);\n\tvar file_arr = filename.split(\".aspx\");\n\tvar mode = file_arr[0].split(\"_\");\n\tvar url = \"\";\n\t\n\tif (mode.length > 1) {\n\t\t// Not production mode\n\t\turl = root + \"/siteassets/team_portal_\" + mode[1];\n\t} else {\n\t\t// Production mode\n\t\turl = root + \"/siteassets/team_portal\";\n\t}\n\treturn url;\n}",
"function fetchBlkFileContent(projectName, callback) {\r\n if (typeof blocksIO !== 'undefined') {\r\n // html/js is within the WebView component within the Android app.\r\n fetchBlkFileContentViaBlocksIO(projectName, callback);\r\n } else if (window.location.protocol === 'http:' || window.location.protocol === 'https:') {\r\n // html/js is in a browser, loaded as an http:// URL.\r\n fetchBlkFileContentViaHttp(projectName, callback);\r\n } else if (window.location.protocol === 'file:') {\r\n // html/js is in a browser, loaded as an file:// URL.\r\n fetchBlkFileContentViaFile(projectName, callback);\r\n }\r\n}",
"function allMenusHtml(req, res) {\n\n menus.getAllMenus()\n .then((results) => res.render('pages/index', results))\n .catch(err => {\n console.log('error in allMenusHtml: ', err);\n res.send('There was an error, sorry!')\n });\n}",
"function catalogSync() {\n return walkSync(path.resolve(__dirname, 'content'));\n}",
"getResolvedAssetElement(assetElementHtml, tagName, attrName, plugin, pluginName) {\n const $ = cheerio.load(assetElementHtml);\n const el = $(`${tagName}[${attrName}]`);\n\n el.attr(attrName, (i, assetPath) => {\n if (!assetPath || utils.isUrl(assetPath)) {\n return assetPath;\n }\n\n const srcPath = path.resolve(plugin._pluginAbsolutePath, assetPath);\n const srcBaseName = path.basename(srcPath);\n\n fs.ensureDir(plugin._pluginAssetOutputPath)\n .then(() => {\n const outputPath = path.join(plugin._pluginAssetOutputPath, srcBaseName);\n fs.copySync(srcPath, outputPath, { overwrite: false });\n })\n .catch(err => logger.error(`Failed to copy asset ${assetPath} for plugin ${pluginName}\\n${err}`));\n\n return path.posix.join(this.pageConfig.baseUrl || '/', PLUGIN_SITE_ASSET_FOLDER_NAME,\n pluginName, srcBaseName);\n });\n\n return $.html();\n }",
"function renderAll(templateName) {\n\ttemplateName = path.basename(templateName, '.html');\n\n\t// Read the directory's content\n\tfs.readdir(path.join(__dirname, templateName), function(error, files) {\n\t\t// Render each file\n\t\tfiles.forEach(function(file) {\n\t\t\trender(templateName, file);\n\t\t});\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lista todos os pedidos de um cliente especifico | async listAllClientRequests(req, res) {
try {
const id_cliente = req.clientId.id;
const requests = await Request.find({
id_cliente,
}).populate(["produtos", "id_empresa"]);
const count = requests.length;
if (count === 0)
return res.status(404).send({ NOTFOUND: "Nenhum pedido encontrado" });
return res.status(200).send({ TOTAL: count, requests });
} catch (error) {
return res.status(400).send({ error: error.message });
}
} | [
"function mostrarProductoC(cliente) {\n console.log(\"***************************\");\n cliente.forEach((client) => {\n console.log(\"ID CLIENTE \" + client.id);\n console.log(\"NOMBRE CLIENTE \" + client.name);\n console.log(\"EMAIL \" + client.email);\n console.log(\"EDAD \" + client.age);\n console.log(\"***************************\");\n });\n}",
"function listProdutosPorPedido(numeroPedido) {\n return new Promise((resolve, reject) => {\n con.query(\n \"select pb.*, produto.* from pedido_produto as pb inner join produto on produto.codigo = pb.codigo_produto where pb.numero_pedido = ?\",\n numeroPedido,\n (err, result) => {\n if (err) reject(err);\n resolve(result);\n }\n );\n });\n}",
"function listarEncargados(req, res){\n Encargado.find({}, (err, encargados)=>{\n if(err){\n res.status(500).send({message: 'Error al traer los profesores'});\n }else{\n res.status(200).send({encargados});\n }\n });\n }",
"function Listar() {\n $(\"#tbCadastro\").html(\"\");\n $(\"#tbCadastro\").html(\n \"<thead>\" +\n \" <tr>\" +\n \" <th>CPF</th>\" +\n \" <th>Nome</th>\" +\n \" <th></th>\" +\n \" </tr>\" +\n \"</thead>\" +\n \"<tbody>\" +\n \"</tbody>\"\n );\n\t\tfor (var i in tbDados) {\n var cli = JSON.parse(tbDados[i]);\n var novaLinha = $(\"<tr>\");\n var cols = \"\";\n cols += \"<td>\" + cli.cpf + \"</td>\";\n cols += \"<td>\" + cli.nome + \"</td>\";\n cols += \"<td>\" +\n \" <img src='img/edit.png' alt='\" +\n i + \"' class='btnEditar'/>\" + \" \" +\n \"<img src='img/delete.png' alt='\" +\n i + \"' class='btnExcluir'/>\" + \"</td>\";\n novaLinha.append(cols);\n\t\t\t$(\"#tbCadastro\").append(novaLinha);\n }\n }",
"function listarRepartidores(){\n vm.listaRepartidores = servicioUsuarios.obtenerRepartidores();\n }",
"function handleListarCompeticionesFavoritas(agent) {\n const nickname = agent.parameters.nickname;\n let refFavoritos = db.ref(`users/${nickname}/favoritos/competiciones`);\n return refFavoritos.once('value').then((snapshot) => {\n if (snapshot.exists()) {\n return snapshot.forEach((childSnapshot) => {\n\n var aux = childSnapshot.val();\n let nombre = childSnapshot.key;\n let logo = aux.logo;\n let pais = aux.pais;\n agent.add(new Card({ title: `Nombre: ${nombre}`, imageUrl: logo, text: `País: ${pais}`, buttonText: \"Ver detalles\", buttonUrl: `Quiero información sobre la competición ${nombre}` }));\n agent.add(new Card({ title: `Nombre: ${nombre}`, buttonText: \"Quitar de favoritos\", buttonUrl: `Quiero eliminar la competición ${nombre} de favoritos` }));\n agent.add(new Card({ title: `Clasificación de la ${nombre}`, buttonText: \"Ver clasificación\", buttonUrl: `Ver la clasificación de la ${nombre}` }));\n agent.add(new Card({ title: `Lista de máximos goleadores de la ${nombre}`, buttonText: \"Ver lista de máximos goleadores\", buttonUrl: `Ver los máximos goleadores de la ${nombre}` }));\n agent.setContext({ \"name\": \"Home\", \"lifespan\": 1, \"parameters\": { \"nickname\": nickname } });\n\n });\n } else {\n agent.add(\"Vaya, parece que tu lista de favoritos está vacía. Puedes añadir competiciones a tu lista de favoritos al buscar información sobre ellas.\");\n agent.setContext({ \"name\": \"Home\", \"lifespan\": 1, \"parameters\": { \"nickname\": nickname } });\n }\n });\n }",
"async function cargarClientes()\n{\n // Se obtienen los clientes de la pagina web usando el modulo axios\n const clientesJSON = await axios.get('https://gist.githubusercontent.com/josejbocanegra/986182ce2dd3e6246adcf960f9cda061/raw/f013c156f37c34117c0d4ba9779b15d427fb8dcd/clientes.json');\n\n // Se obtiene la información requerida de los clientes\n const dataClientes = clientesJSON.data.map(function (act) {\n return [act.idCliente, act.NombreCompania, act.NombreContacto];\n })\n\n escribirHTML(\"clientes\", dataClientes);\n}",
"function cargarListaPedidos(parametros) {\n\t$.ajax({\n\t\tdata: parametros,\n\t\turl: \"./vistas/listapedidos.php\",\n\t\ttype: 'post',\n\t\tbeforeSend: function () {\n\t\t\t$(\"#conten-detalles\").load('/vistas/loader.php');\n\t\t},\n\t\tsuccess: function (response) {\n\t\t\t$(\"#conten-detalles\").html(response);\n\t\t\t//cargarTabla(parametros.tabla);\n\t\t}\n\t});\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 }",
"function CommandeFontion(CommandeService) {\n var vm = this;\n vm.loadAll = loadAll;\n\n loadAll();\n\n function loadAll() {//Fontion qui affiche la liste des commandes\n\n CommandeService.query(null, onSuccess, onError);\n\n function onSuccess(data, headers) {\n vm.commandes = data;\n //console.log('je suis ...'+data[0]._id);\n }\n function onError(error) {\n console.log('error.data.message');\n }\n }\n\n }",
"async index(req, res) {\n // Get all oportunities\n const { data } = await pipedrive_api.get();\n if (data.data) {\n data.data.forEach(async client => {\n // Find WON oportunities\n if (client.status == 'won') {\n const {\n title,\n value,\n person_id: { name },\n creator_user_id: { id },\n } = client;\n\n var nome_cliente = name;\n //var id_venda = Math.ceil(Math.random() * (1000 - 1) + 1);\n var id_venda = id + value;\n var descricao_produto = title;\n var valor_produto = value;\n var valor_parcela = value;\n\n // Create a new Order request in Bling\n await OrderController.store(\n nome_cliente,\n id_venda,\n descricao_produto,\n valor_produto,\n valor_parcela\n );\n }\n });\n }\n return res.json({ saved: true });\n }",
"function obtenInvitados(tramite){\r\n\t\tvar objetoInvitados = obtenDatosInvitados(tramite);\r\n\t\tif(objetoInvitados != null){\r\n\t\t\tfor(var prop in objetoInvitados){\r\n\t\t\t\tvar partida = objetoInvitados[prop];\r\n\t\t\t\tfor(var propPar in partida)\r\n\t\t\t\t\tpartida[propPar] = (partida[propPar] == \"\" || partida[propPar] == null) ? \"N/A\" : partida[propPar];\r\n\t\t\t\t\r\n\t\t\t\tvar id = obtenTablaLength(\"invitado_table\")+1;\r\n\t\t\t\tvar\trenglon = creaRenglonInvitados(objetoInvitados[prop], id);\r\n\t\t\t\tagregaRenglon(renglon, \"invitado_table\");\r\n\t\t\t}\r\n\t\t\tasignaText(\"span_totalInvitados\", id);\r\n\t\t\tasignaVal(\"numInvitados\", id);\r\n\t\t}\r\n\t}",
"function listarUsuarios() {\r\n\t\t\tconsole.log('refrescando.......');\r\n\t\t\thttpservice.get('semestresAnteriores/listaUsuarios', null,\r\n\t\t\t\t\tsuccess = function(data, status, headers, config) {\r\n\t\t\t\t\t\tconsole.log('success.......');\r\n\t\t\t\t\t\t$scope.usuarios = data.obj;\r\n\t\t\t\t\t}, null);\r\n\t\t}",
"async function getClients(management, pagination) {\n let allClients = [];\n var clientPage = await getClientPage(management,pagination)\n allClients.push( clientPage );\n if ( clientPage.length > 0 ) {\n pagination.page = pagination.page + 1;\n console.log ( 'We got ' + clientPage.length + ' results with pagination of ' + pagination.per_page );\n allClients.push(await getClients(management, pagination));\n } else {\n console.log ( 'We got ' + clientPage.length + ' results with pagination of ' + pagination.per_page );\n return;\n }\nreturn allClients.flatArr();\n}",
"async function cargarProveedores()\n{\n // Se obtienen los proveedores de la pagina web usando el modulo axios\n const proveedoresJSON = await axios.get('https://gist.githubusercontent.com/josejbocanegra/d3b26f97573a823a9d0df4ec68fef45f/raw/66440575649e007a9770bcd480badcbbc6a41ba7/proveedores.json');\n\n // Se obtiene la informacion requerida de los proveedores\n const dataProveedores = proveedoresJSON.data.map(function (act) {\n return [act.idproveedor, act.nombrecompania, act.nombrecontacto];\n })\n\n escribirHTML(\"proveedores\", dataProveedores);\n}",
"async getListTodos (context, listId) {\n try {\n const response = await fetch(`https://ap-todo-list.herokuapp.com/todosForList?listId=${listId}`)\n const data = await response.json()\n context.commit('setTodos', data)\n } catch (error) {\n // Set the error and clear the todos.\n console.error(error)\n context.commit('setTodos', [])\n }\n }",
"function xsetearContacto(cliente) {\n\t$.ajax({\n\t\ttype: 'POST',\n\t\turl: 'Clientes/ObtenerContactos',\n\t\tdataType: 'json',\n\t\tdata: { idempresa: cliente },\n\t\tasync: false,\n\t\tsuccess: function (response) {\n\t\t\tif (response.length > 0) {\n\t\t\t\t$('#contacto').empty().append(\"<option value=''>Selecciona...</option>\");\n\t\t\t\t$.each(response, function (index, item) {\n\t\t\t\t\t$('#contacto').append(\"<option value=\" + item.intidcontacto + \">\" + item.strnombre + \"</option>\");\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t});\n}",
"function obtenerCodigoInspeccionesPendientesAscensores(estado){\n $('#ascensores').show('fast');\n db.transaction(function (tx) {\n var query = \"SELECT * FROM auditoria_inspecciones_ascensores WHERE o_estado_envio = ?\";\n tx.executeSql(query, [estado], function (tx, resultSet) {\n for(var x = 0; x < resultSet.rows.length; x++) {\n var k_codusuario = resultSet.rows.item(x).k_codusuario;\n var codigo_inspeccion = resultSet.rows.item(x).k_codinspeccion;\n var cantidad_nocumple = resultSet.rows.item(x).v_item_nocumple;\n var consecutivo_inspe = resultSet.rows.item(x).o_consecutivoinsp;\n visualizarInspeccionesAscensores(k_codusuario,codigo_inspeccion,cantidad_nocumple,consecutivo_inspe);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n}",
"_getClientNames() {\n const names = [];\n for (let key in this.clients) {\n names.push(this.clients[key].name);\n }\n return names;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reset callbacks that only fire once, so they can fire agan | resetCallbacks() {
for ( let i = 0; i < this._callbacks.length; ++i ) {
this._callbacks[ i ].called = false;
}
} | [
"clearCallbacks() {\n this._callbackMapper.reset();\n }",
"function resetAllEvents(){\n\t\t\tevents.forEach( ev => { \n\t\t\t\tev.button.gotoAndStop(0);\n\t\t\t\tev.button.cursor = \"pointer\";\n\t\t\t\tev.choosen = false; \n\t\t\t});\n\t\t\t// update instructions\n\t\t\tself.instructions.gotoAndStop(0);\n\t\t\t// update side box\n\t\t\tself.sideBox.gotoAndStop(0);\n\t\t}",
"reset() {\n\t\tthis.ready = false;\n\t\tthis.states = [];\n\t\tthis.battles = [];\n\t\tthis.fighters = [];\n\t}",
"function resetAll () {\n resetOutput();\n resetRegisters();\n updateRegisterOutput();\n error = false;\n}",
"reset() {\n this.removeAllListeners();\n this.handle.reset();\n // add callbacks back as reset will remove them\n this.handle.setOpt(Curl.option.WRITEFUNCTION, this.defaultWriteFunction.bind(this));\n this.handle.setOpt(Curl.option.HEADERFUNCTION, this.defaultHeaderFunction.bind(this));\n return this;\n }",
"resetEverything() {\n this.resetLoader();\n this.remove(0, Infinity);\n }",
"function resetSuccessFountain(){\n runSuccess = false;\n successFountain.reset(successParticle);\n coordinates = [];\n}",
"callAllCallbacks() {\n this.callbackSets.forEach((set) => {\n this.callCallbackSet(set);\n });\n }",
"reset() {\n\tthis.progress = new Progress(0);\n\tthis.question = [];\n\tthis.setChanged();\n\tthis.notifyObservers(this.progress);\n\tthis.clearChanged();\n }",
"resetAll () {\n this.data = this.defaults\n }",
"function reset() {\n defaultRenderers_ = {};\n decoratorFunctions_ = {};\n}",
"reset() {\r\n\t\tthis.changeState(this.initial);\r\n\t}",
"reset(){\n\t\tDEFAULT_BUCKET['*'].handlers = []\n\t\tthis.Bucket = Object.assign({}, DEFAULT_BUCKET)\n\t}",
"function resetCalculations() {\n calculatedBogoMips = null;\n clientEffectsLevel = null;\n calculateJsBogoMips();\n }",
"function resetVars(state) {\n keepBallAttached = false;\n ballIsUp = false;\n fired = false;\n }",
"resetApiChanges() {\n this.state.apiChanges = null;\n this.state.apiChangesCounts = apiChangesCountsFactory();\n }",
"clearAndResetUpdate(){\n\t\tclearTimeout(timer);\n\t\tthis.getChats();\t\n\t}",
"reset() {\n /** \n * @property {Sprite[]} _sprites - The sprites that currently exist within the game.\n * @private\n */\n this._sprites = [];\n\n /** \n * @property {Phaser.Sprite[]} _phaserSprites - An array of Phaser sprites to support collision handling.\n * @private\n */\n this._phaserSprites = [];\n\n /**\n * @property {number} _lastKeyCode - Caches code of last pressed key, allowing sync of Phaser keyboard callbacks with game loop.\n * @private\n */\n this._lastKeyCode = undefined;\n\n this._phaserGame.state.start(\"PlayState\");\n }",
"unregisterLoadCallback () {\n this.loadCallback = null;\n }",
"function resetOwnActionTimer() {\n actionTimer = new Date()\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses a time string and returns a Date | function parseTime(str) {
let segments = str.split(':');
let hour = parseInt(segments[0]) % 12;
let min = parseInt(segments[1].substr(0, 2));
let suf = segments[1].substr(2, 2);
if (suf === 'pm') hour += 12;
let date = new Date(1970, 1, 1, hour, min, 0);
return date;
} | [
"function parseTime(str) {\n\t if (!str) {\n\t return 0;\n\t }\n\t\n\t var strings = str.split(\":\");\n\t var l = strings.length, i = l;\n\t var ms = 0, parsed;\n\t\n\t if (l > 3 || !/^(\\d\\d:){0,2}\\d\\d?$/.test(str)) {\n\t throw new Error(\"tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits\");\n\t }\n\t\n\t while (i--) {\n\t parsed = parseInt(strings[i], 10);\n\t\n\t if (parsed >= 60) {\n\t throw new Error(\"Invalid time \" + str);\n\t }\n\t\n\t ms += parsed * Math.pow(60, (l - i - 1));\n\t }\n\t\n\t return ms * 1000;\n\t }",
"function tryToParse(txt) {\r\n\r\n // The listing of all possible formats that can reasonably be parsed, listed\r\n // in order from shortest to longest string.\r\n var formatArray = [ \"H\",\r\n \"HH\",\r\n \"HHm\",\r\n \"HHmm\",\r\n \"H:\",\r\n \"HH:\",\r\n \"H:m\",\r\n \"HH:m\",\r\n \"H:mm\",\r\n \"HH:mm\",\r\n \"H:mt\",\r\n \"HH:mt\",\r\n \"H:mmt\",\r\n \"HH:mmt\",\r\n \"H:mtt\",\r\n \"HH:mtt\",\r\n \"H:mmtt\",\r\n \"HH:mmtt\" ];\r\n\r\n // An index to be used for iterating through the format array\r\n var formatIdx = null;\r\n\r\n // Get rid of any spaces\r\n var hourText = txt.replace(/\\s/g, \"\");\r\n\r\n // Iterate through every format, and attempt to parse using that format.\r\n for (formatIdx in formatArray) {\r\n var cTime = Date.parseExact(hourText, formatArray[formatIdx]);\r\n if (cTime) {\r\n return cTime;\r\n }\r\n }\r\n\r\n // If not a single format matches, then return null\r\n return null;\r\n}",
"static parseDate(dateString){\n return new Date(\n parseInt(dateString.split(\"/\")[2]),\n DateUtilities.getMonthNumber(dateString.split(\"/\")[1]),\n parseInt(dateString.split(\"/\")[0])\n )\n }",
"function SimpleDateFormat(pattern) {\n this.pattern = pattern;\n this.regex = new RegExp(\"^\" + pattern.replace(\"yyyy\", \"\\\\d{4}\").replace(\"MM\", \"(0\\\\d|1[12])\").replace(\"dd\", \"([0-2]\\\\d|3[0-1])\")\n .replace(\"HH\", \"([0-1]\\\\d|2[0-3])\").replace(\"hh\", \"(0\\\\d|1[0-2])\").replace(\"mm\", \"[0-5]\\\\d\").replace(\"ss\", \"[0-5]\\\\d\") + \"$\");\n this.position = {\n year: pattern.indexOf(\"yyyy\"), month: pattern.indexOf(\"MM\"), day: pattern.indexOf(\"dd\"),\n hour: pattern.toLowerCase().indexOf(\"hh\"), minute: pattern.indexOf(\"mm\"), second: pattern.indexOf(\"ss\")\n };\n this.parse = function (source) {\n if (!this.regex.test(source))\n throw new Error(\"Unparseable date: \\\"\" + source + \"\\\"\");\n var time = {\n year: source.substr(this.position.year, 4),\n month: source.substr(this.position.month, 2),\n day: source.substr(this.position.day, 2)\n };\n if (this.position.hour != -1)\n time.hour = source.substr(this.position.hour, 2);\n if (this.position.minute != -1)\n time.minute = source.substr(this.position.minute, 2);\n if (this.position.second != -1)\n time.second = source.substr(this.position.second, 2);\n var day31 = \"01,03,05,07,08,10,12\";\n if (time.day == 31 && day31.indexOf(time.month) == -1)\n throw new Error(\"Unparseable date: \\\"\" + source + \"\\\"\");\n if (time.month == 2 && time.day == 29 && !(time.year % 4 == 0 && time.year % 100 != 0)\n && !(time.year % 100 == 0 && time.year % 400 == 0)) {\n throw new Error(\"Unparseable date: \\\"\" + source + \"\\\"\");\n }\n var date = new Date();\n date.setFullYear(time.year, time.month - 1, time.day);\n if (time.hour != undefined) date.setHours(time.hour);\n if (time.minute != undefined) date.setMinutes(time.minute);\n if (time.second != undefined) date.setSeconds(time.second);\n return date;\n };\n this.format = function (date) {\n function fmt(v, n) {\n for (var i = n - (v + \"\").length; i > 0; i--) {\n v = \"0\" + v;\n }\n return v;\n }\n var h24 = date.getHours();\n return this.pattern.replace(\"yyyy\", fmt(date.getFullYear(), 4)).replace(\"MM\", fmt(date.getMonth() + 1, 2))\n .replace(\"dd\", fmt(date.getDate(), 2)).replace(\"HH\", fmt(h24, 2)).replace(\"hh\", fmt((h24 - 1) % 12 + 1, 2))\n .replace(\"mm\", fmt(date.getMinutes(), 2)).replace(\"ss\", fmt(date.getSeconds(), 2));\n };\n}",
"function parseTime(datetime, format) {\n\tvar parser = d3.timeParse(format);\n\treturn parser(datetime);\n}",
"function parseDate(str) {\n\t if (!str) {\n\t return;\n\t }\n\t\n\t /* RFC6265 S5.1.1:\n\t * 2. Process each date-token sequentially in the order the date-tokens\n\t * appear in the cookie-date\n\t */\n\t var tokens = str.split(DATE_DELIM);\n\t if (!tokens) {\n\t return;\n\t }\n\t\n\t var hour = null;\n\t var minute = null;\n\t var second = null;\n\t var dayOfMonth = null;\n\t var month = null;\n\t var year = null;\n\t\n\t for (var i=0; i<tokens.length; i++) {\n\t var token = tokens[i].trim();\n\t if (!token.length) {\n\t continue;\n\t }\n\t\n\t var result;\n\t\n\t /* 2.1. If the found-time flag is not set and the token matches the time\n\t * production, set the found-time flag and set the hour- value,\n\t * minute-value, and second-value to the numbers denoted by the digits in\n\t * the date-token, respectively. Skip the remaining sub-steps and continue\n\t * to the next date-token.\n\t */\n\t if (second === null) {\n\t result = parseTime(token);\n\t if (result) {\n\t hour = result[0];\n\t minute = result[1];\n\t second = result[2];\n\t continue;\n\t }\n\t }\n\t\n\t /* 2.2. If the found-day-of-month flag is not set and the date-token matches\n\t * the day-of-month production, set the found-day-of- month flag and set\n\t * the day-of-month-value to the number denoted by the date-token. Skip\n\t * the remaining sub-steps and continue to the next date-token.\n\t */\n\t if (dayOfMonth === null) {\n\t // \"day-of-month = 1*2DIGIT ( non-digit *OCTET )\"\n\t result = parseDigits(token, 1, 2, true);\n\t if (result !== null) {\n\t dayOfMonth = result;\n\t continue;\n\t }\n\t }\n\t\n\t /* 2.3. If the found-month flag is not set and the date-token matches the\n\t * month production, set the found-month flag and set the month-value to\n\t * the month denoted by the date-token. Skip the remaining sub-steps and\n\t * continue to the next date-token.\n\t */\n\t if (month === null) {\n\t result = parseMonth(token);\n\t if (result !== null) {\n\t month = result;\n\t continue;\n\t }\n\t }\n\t\n\t /* 2.4. If the found-year flag is not set and the date-token matches the\n\t * year production, set the found-year flag and set the year-value to the\n\t * number denoted by the date-token. Skip the remaining sub-steps and\n\t * continue to the next date-token.\n\t */\n\t if (year === null) {\n\t // \"year = 2*4DIGIT ( non-digit *OCTET )\"\n\t result = parseDigits(token, 2, 4, true);\n\t if (result !== null) {\n\t year = result;\n\t /* From S5.1.1:\n\t * 3. If the year-value is greater than or equal to 70 and less\n\t * than or equal to 99, increment the year-value by 1900.\n\t * 4. If the year-value is greater than or equal to 0 and less\n\t * than or equal to 69, increment the year-value by 2000.\n\t */\n\t if (year >= 70 && year <= 99) {\n\t year += 1900;\n\t } else if (year >= 0 && year <= 69) {\n\t year += 2000;\n\t }\n\t }\n\t }\n\t }\n\t\n\t /* RFC 6265 S5.1.1\n\t * \"5. Abort these steps and fail to parse the cookie-date if:\n\t * * at least one of the found-day-of-month, found-month, found-\n\t * year, or found-time flags is not set,\n\t * * the day-of-month-value is less than 1 or greater than 31,\n\t * * the year-value is less than 1601,\n\t * * the hour-value is greater than 23,\n\t * * the minute-value is greater than 59, or\n\t * * the second-value is greater than 59.\n\t * (Note that leap seconds cannot be represented in this syntax.)\"\n\t *\n\t * So, in order as above:\n\t */\n\t if (\n\t dayOfMonth === null || month === null || year === null || second === null ||\n\t dayOfMonth < 1 || dayOfMonth > 31 ||\n\t year < 1601 ||\n\t hour > 23 ||\n\t minute > 59 ||\n\t second > 59\n\t ) {\n\t return;\n\t }\n\t\n\t return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second));\n\t}",
"function parsear_tiempo(tiempo){\n tiempo = tiempo.split(\":\")\n var hora = parseInt(tiempo[0])\n //console.log(hora)\n if ( hora > 12 && hora<22)\n return \"0\"+(hora - 12) + \":\" + tiempo[1] + \" PM\"\n else if (hora < 12) { \n if (hora < 10)\n return \"0\" + hora + \":\" + tiempo[1] + \" AM\"\n else return hora + \":\" + tiempo[1] + \" AM\"\n }\n else if (hora == 12)\n return hora + \":\" + tiempo[1] + \" PM\"\n else if (hora >= 22 && hora < 24) return (hora - 12) + \":\" + tiempo[1] + \" PM\"\n else return \"00:\" + tiempo[1] + \" AM\"\n}",
"function parseYYYYMMDD(str) {\n if (!/^(\\d){8}$/.test(str))\n return 0;\n var y = str.substr(0, 4), m = str.substr(4, 2) - 1, d = str.substr(6, 2);\n return new Date(y, m, d).getTime();\n }",
"function parseRFC3339(date) {\r\n var newDate = new Date();\r\n\r\n // Parse date portion.\r\n // first 10 chars 'XXXX-XX-XX'\r\n var datePart = date.substring(0, 10);\r\n datePart = datePart.split(\"-\");\r\n\r\n if (datePart.length != 3) {\r\n return null;\r\n }\r\n\r\n newDate.setUTCFullYear(datePart[0]);\r\n newDate.setUTCMonth(datePart[1] - 1);\r\n newDate.setUTCDate(datePart[2]);\r\n\r\n // Check for 'T'.\r\n var tPart = date.substring(10, 11);\r\n\r\n if (tPart != 'T' && tPart != 't') {\r\n return null;\r\n }\r\n\r\n // Parse time portion.\r\n // 'XX:XX:XX'\r\n var timePart = date.substring(11, 19);\r\n timePart = timePart.split(\":\");\r\n\r\n if (timePart.length != 3) {\r\n return null;\r\n }\r\n\r\n newDate.setUTCHours(timePart[0]);\r\n newDate.setUTCMinutes(timePart[1]);\r\n newDate.setUTCSeconds(timePart[2]);\r\n\r\n var index = 19;\r\n var dateLen = date.length;\r\n\r\n if (date.charAt(index) == '.') {\r\n // Consume fractional sec.\r\n do {\r\n ++index;\r\n } while (date.charAt(index) >= '0' &&\r\n date.charAt(index) <= '9' &&\r\n index < date.length);\r\n }\r\n\r\n if (index >= date.length) {\r\n // No zone to parse;\r\n return newDate;\r\n }\r\n\r\n if (date.charAt(index) == 'Z') {\r\n // No offset.\r\n return newDate;\r\n }\r\n\r\n var offsetSign = date.charAt(index);\r\n\r\n if (offsetSign != '+' && offsetSign != '-') {\r\n return null;\r\n }\r\n\r\n ++index;\r\n\r\n // Parse offset.\r\n var offsetPart = date.substring(index, index + 5);\r\n\r\n if (offsetPart.length == 4) {\r\n // Assume colon-less format.\r\n var tempOffsetPart = [];\r\n tempOffsetPart[0] = offsetPart.substr(0, 2);\r\n tempOffsetPart[1] = offsetPart.substr(2, 2);\r\n offsetPart = tempOffsetPart;\r\n } else {\r\n offsetPart = offsetPart.split(\":\");\r\n }\r\n\r\n if (offsetPart.length != 2) {\r\n return null;\r\n }\r\n\r\n var offsetSeconds = (Number(offsetPart[0]) * 60) + Number(offsetPart[1]);\r\n var offsetMs = offsetSeconds * 60 * 1000;\r\n\r\n // Adjust for offset.\r\n if (offsetSign == '+') {\r\n newDate.setTime(newDate.getTime() - offsetMs);\r\n } else {\r\n newDate.setTime(newDate.getTime() + offsetMs);\r\n }\r\n\r\n return newDate;\r\n}",
"function driplineStringToDate(dripstring) {\n\tvar date_time=dripstring.split(\" \");\n\tvar ymd=date_time[0].split(\"-\");\n\tvar hms=date_time[1].split(\":\");\n\treturn new Date(ymd[0],ymd[1],ymd[2],hms[0],hms[1],hms[2],0);\n}",
"function parseDateToMs(input) {\n\ttry {\n\t\tvar dateString = input;\n\t\tvar parts = dateString.split(',');\n\t\t\n\t\tvar date = parts[0].split('-');\n\t\t/*var year = date[0];\n\t\tvar month = date[1];\n\t\tvar day = date[2];*/\n\t\t\n\t\tvar time = parts[1].split(':');\n\t\t/*var hour = time[0];\n\t\tvar minute = time[1];\n\t\tvar secs = time[2];\n\t\tvar millisecs = time[3];*/\n\t\t// new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])\n\t\treturn new Date(date[0], date[1]-1, date[2], time[0],time[1],time[2],time[3]).getTime();\n\t\t// Note: we use date[1]-1 because months are 0-based\n\t}\n\tcatch(err) {\n\t\tprint(\"ERROR: parseDateToMs(). Following input cause an error:\" + input);\n\t\tthrow new Error(\"Something went badly wrong!\");\n\t}\n\t\n}",
"function parseDateFromFilter(strDate) {\n//\t\t\t\tvar parts = strDate.split(' ');\n//\t\t\t\treturn new Date(parts[2], parts[1] - 1, parts[0]);\n\t\t\t\treturn new Date(strDate);\n\t\t\t}",
"static fromPartialString(v) {\n let match = /^(\\d{4})\\/(\\d{1,2})\\/(\\d{1,2})$/.exec(v);\n if (match) {\n return new NepaliDate(match[1], match[2], match[3]);\n }\n match = /^(\\d{1,2})\\/(\\d{1,2})$/.exec(v);\n if (match) {\n const nd = NepaliDate.today();\n let y = nd.nepaliYear;\n const m = match[1];\n const d = match[2];\n if (m > nd.nepaliMonth || (m === nd.nepaliMonth && d > nd.nepaliDay)) {\n y -= 1;\n }\n return new NepaliDate(y, m, d);\n }\n }",
"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 }",
"parseDate(formattedDate) {\n const [monthDayStr, yearStr] = formattedDate.split(', ');\n const [monthStr, dayStr] = monthDayStr.split(' ');\n return {\n month: this.getMonthInt(monthStr),\n day: parseInt(dayStr),\n year: parseInt(yearStr)\n };\n }",
"date(time){\n return moment(time);\n }",
"function _parseDuration(timestampText) {\n var a = timestampText.split(/\\s+/);\n var lastword = a[a.length - 1]; // ex: Duration: 2:27, Kesto: 1.07.54\n // replace all non :, non digits and non .\n\n var timestamp = lastword.replace(/[^:.\\d]/g, '');\n if (!timestamp) return {\n toString: function toString() {\n return a[0];\n },\n seconds: 0,\n timestamp: 0\n }; // remove trailing junk that are not digits\n\n while (timestamp[timestamp.length - 1].match(/\\D/)) {\n timestamp = timestamp.slice(0, -1);\n } // replaces all dots with nice ':'\n\n\n timestamp = timestamp.replace(/\\./g, ':');\n var t = timestamp.split(/[:.]/);\n var seconds = 0;\n var exp = 0;\n\n for (var i = t.length - 1; i >= 0; i--) {\n if (t[i].length <= 0) continue;\n var number = t[i].replace(/\\D/g, ''); // var exp = (t.length - 1) - i;\n\n seconds += parseInt(number) * (exp > 0 ? Math.pow(60, exp) : 1);\n exp++;\n if (exp > 2) break;\n }\n\n ;\n return {\n toString: function toString() {\n return seconds + ' seconds (' + timestamp + ')';\n },\n seconds: seconds,\n timestamp: timestamp\n };\n}",
"function parseDateTimeSkeleton(skeleton) {\n var result = {};\n skeleton.replace(DATE_TIME_REGEX, function (match) {\n var len = match.length;\n switch (match[0]) {\n // Era\n case 'G':\n result.era = len === 4 ? 'long' : len === 5 ? 'narrow' : 'short';\n break;\n // Year\n case 'y':\n result.year = len === 2 ? '2-digit' : 'numeric';\n break;\n case 'Y':\n case 'u':\n case 'U':\n case 'r':\n throw new RangeError('`Y/u/U/r` (year) patterns are not supported, use `y` instead');\n // Quarter\n case 'q':\n case 'Q':\n throw new RangeError('`q/Q` (quarter) patterns are not supported');\n // Month\n case 'M':\n case 'L':\n result.month = ['numeric', '2-digit', 'short', 'long', 'narrow'][len - 1];\n break;\n // Week\n case 'w':\n case 'W':\n throw new RangeError('`w/W` (week) patterns are not supported');\n case 'd':\n result.day = ['numeric', '2-digit'][len - 1];\n break;\n case 'D':\n case 'F':\n case 'g':\n throw new RangeError('`D/F/g` (day) patterns are not supported, use `d` instead');\n // Weekday\n case 'E':\n result.weekday = len === 4 ? 'short' : len === 5 ? 'narrow' : 'short';\n break;\n case 'e':\n if (len < 4) {\n throw new RangeError('`e..eee` (weekday) patterns are not supported');\n }\n result.weekday = ['short', 'long', 'narrow', 'short'][len - 4];\n break;\n case 'c':\n if (len < 4) {\n throw new RangeError('`c..ccc` (weekday) patterns are not supported');\n }\n result.weekday = ['short', 'long', 'narrow', 'short'][len - 4];\n break;\n // Period\n case 'a': // AM, PM\n result.hour12 = true;\n break;\n case 'b': // am, pm, noon, midnight\n case 'B': // flexible day periods\n throw new RangeError('`b/B` (period) patterns are not supported, use `a` instead');\n // Hour\n case 'h':\n result.hourCycle = 'h12';\n result.hour = ['numeric', '2-digit'][len - 1];\n break;\n case 'H':\n result.hourCycle = 'h23';\n result.hour = ['numeric', '2-digit'][len - 1];\n break;\n case 'K':\n result.hourCycle = 'h11';\n result.hour = ['numeric', '2-digit'][len - 1];\n break;\n case 'k':\n result.hourCycle = 'h24';\n result.hour = ['numeric', '2-digit'][len - 1];\n break;\n case 'j':\n case 'J':\n case 'C':\n throw new RangeError('`j/J/C` (hour) patterns are not supported, use `h/H/K/k` instead');\n // Minute\n case 'm':\n result.minute = ['numeric', '2-digit'][len - 1];\n break;\n // Second\n case 's':\n result.second = ['numeric', '2-digit'][len - 1];\n break;\n case 'S':\n case 'A':\n throw new RangeError('`S/A` (second) patterns are not supported, use `s` instead');\n // Zone\n case 'z': // 1..3, 4: specific non-location format\n result.timeZoneName = len < 4 ? 'short' : 'long';\n break;\n case 'Z': // 1..3, 4, 5: The ISO8601 varios formats\n case 'O': // 1, 4: miliseconds in day short, long\n case 'v': // 1, 4: generic non-location format\n case 'V': // 1, 2, 3, 4: time zone ID or city\n case 'X': // 1, 2, 3, 4: The ISO8601 varios formats\n case 'x': // 1, 2, 3, 4: The ISO8601 varios formats\n throw new RangeError('`Z/O/v/V/X/x` (timeZone) patterns are not supported, use `z` instead');\n }\n return '';\n });\n return result;\n }",
"function parseJSON(string) {\n function dateReviver(key, value) {\n var a;\n if (typeof value === 'string') {\n a = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/.exec(value);\n if (a) {\n return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],\n +a[5], +a[6]));\n }\n }\n return value;\n }\n\n return JSON.parse(string, dateReviver);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create an obscure path for calling cron in order to provide a little extra security | function _createCronPath(){
return new Promise(function(resolve, reject){
let len = 32;
crypto.randomBytes(len, function(err, cronPath){
if(err){ return reject(err); }
cronPath = cronPath.toString('base64'); // convert from buffer to text
// remove any percent signs as a precaution to ensure decoding the path does not create any weird effects
// e.g. inserting new paths or parameters into the cron path
cronPath = encodeURIComponent(cronPath).replace(/%/g, 'p');
// get current cron setting
let cronRecord = system.systemVariable.getConfig('cronRecord');
cronRecord.path = cronPath;
// save cron setting
system.systemVariable.updateConfig({cronRecord: cronRecord}, function(err){
if(err){ return reject(err); }
resolve();
});
});
});
} | [
"function startCron() {\n fs.readdirSync(__dirname).filter(file =>\n (file.lastIndexOf('.js') >= 0) && (file !== 'index.js')\n ).map((file) => {\n const config = require(path.join(__dirname, file)).default;\n cron.schedule(config.expression, config.func, true);\n if (config.immediateStart) {\n config.func();\n }\n return file;\n });\n}",
"function SystemPath()\n{\t \n}",
"function makeWorkPath() {\r\n\tvar idMk = charIDToTypeID( \"Mk \" );\r\n\t\tvar desc92 = new ActionDescriptor();\r\n\t\tvar idnull = charIDToTypeID( \"null\" );\r\n\t\t\t\tvar ref34 = new ActionReference();\r\n\t\t\t\tvar idPath = charIDToTypeID( \"Path\" );\r\n\t\t\t\tref34.putClass( idPath );\r\n\t\tdesc92.putReference( idnull, ref34 );\r\n\t\tvar idFrom = charIDToTypeID( \"From\" );\r\n\t\t\t\tvar ref35 = new ActionReference();\r\n\t\t\t\tvar idcsel = charIDToTypeID( \"csel\" );\r\n\t\t\t\tvar idfsel = charIDToTypeID( \"fsel\" );\r\n\t\t\t\tref35.putProperty( idcsel, idfsel );\r\n\t\tdesc92.putReference( idFrom, ref35 );\r\n\t\tvar idTlrn = charIDToTypeID( \"Tlrn\" );\r\n\t\tvar idPxl = charIDToTypeID( \"#Pxl\" );\r\n\t\tdesc92.putUnitDouble( idTlrn, idPxl, 2 );\r\n\texecuteAction( idMk, desc92, DialogModes.NO );\r\n}",
"function postReminder() {\n cron.schedule('13***', () => {\n communityCallReminder();\n }, {\n scheduled: true,\n timezone: \"America/New_York\"\n });\n}",
"function get_started_url() {\n\n //\n // Return a constant\n //\n return COMMONCRAWL_GET_STARTED;\n\n}",
"static sanitizeUssPathForRestCall(ussPath) {\n let sanitizedPath = path.posix.normalize(ussPath);\n if (sanitizedPath.charAt(0) === \"/\") {\n // trim leading slash from unix files - API doesn't like it\n sanitizedPath = sanitizedPath.substring(1);\n }\n return encodeURIComponent(sanitizedPath);\n }",
"function getJobPathFromName(job) {\n var jobData = loadJobData(job);\n var fileName = jobData.fileName;\n var unGroupName = jobData.unGroupName;\n\n if (unGroupName){\n fileName = unGroupName;\n }\n\n var parsedJobName = fileName.split(\"-\");\n var order = parsedJobName[0];\n var jobNumber = parsedJobName[1];\n var flowName = jobData.flowName;\n var server = \"//tbg-prod/TBG/Jobs/\";\n\n if (flowName.find(\"SF\") != -1){\n server = \"//spdc-prod/Production/Jobs/\"\n }\n\n//search through the order folder to find the job\n var dirpath = server + order + \"/\";\n var dir = new Dir(dirpath);\n var folder = dir.entryList(\"*\" + jobNumber + \"*\", Dir.Dirs);\n var jobPath = folder.toString();\n\n return jobPath;\n}",
"function url_build () {\n return spawn('python',\n ['./lib/python/change_url.py', 'build'], {stdio: 'inherit'})\n}",
"function makePath(path){\n return '/' + [prefix, path].join('/');\n }",
"function generateHistoricURLs() {\n return [{\n url: `${config.baseURL}?&fechaInicio=01/01/1998&fechaFinal=${moment().format('DD/MM/YYYY')}&PreciosPorId=2&RegistrosPorPagina=1000000&OrigenId=25&Origen=Sinaloa&DestinoId=-1&Destino=Todos`, source: true,\n }, {\n url: `${config.baseURL}?&fechaInicio=01/01/1998&fechaFinal=${moment().format('DD/MM/YYYY')}&PreciosPorId=2&RegistrosPorPagina=1000000&OrigenId=-1&Origen=Todos&DestinoId=250&Destino=Sinaloa`, source: false\n }];\n}",
"function _initializeCronTasks(defaultCronSettings){\n return new Promise(function(resolve, reject){\n // get current cron settings and do not override them if they exist\n let currentCronRecord = system.systemVariable.getConfig('cronRecord'); // this contains task names, frequency and last time run (stored to db)\n let currentCronTask = system.systemVariable.get('cronTask') || {}; // this contains the task names and functions (not stored to db)\n \n defaultCronSettings.forEach(function(cronSet){\n let freq, lastrun;\n // check if this record already exists in currentCronRecord, if not, update with default values\n if(!currentCronRecord.task[cronSet.taskName]){\n currentCronRecord.task[cronSet.taskName] = {};\n currentCronRecord.task[cronSet.taskName].freq = cronSet.description.freq;\n currentCronRecord.task[cronSet.taskName].lastrun = cronSet.description.lastrun;\n }\n \n // update currentCronTask\n currentCronTask[cronSet.taskName] = cronSet.description.run;\n system.systemVariable.set('cronTask', currentCronTask);\n });\n\n // update config\n system.systemVariable.updateConfig({cronRecord: currentCronRecord}, function(err){\n if(err){ return reject(err); }\n\n _addBackupToCron()\n .then(_addLoggingToCron)\n .then(function(){\n resolve();\n })\n .catch(function(err){\n reject(err);\n });\n\n function _addBackupToCron(){\n return new Promise(function(_resolve, _reject){\n let freq = system.systemVariable.getConfig('backupFreq');\n let destination = system.systemVariable.getConfig('backupDestination');\n let destType = system.systemVariable.getConfig('backupDestinationType');\n if (freq && destination && destType){\n freq = parseInt(freq) * 60;\n system.addCronTask('handy scheduled backup', system.backupDatabase, freq, function(err){\n if(err){ return _reject(err); }\n _resolve();\n });\n } else {\n _resolve();\n }\n });\n }\n\n function _addLoggingToCron(){\n return new Promise(function(_resolve, _reject){\n let reportFreq = system.systemVariable.getConfig('reportFreq');\n let reportDestination = system.systemVariable.getConfig('reportDestination');\n\n if(reportFreq && reportDestination){\n reportFreq = parseInt(reportFreq) * 60;\n system.addCronTask('handy scheduled activity report', system.logger.report, reportFreq, function(err){\n if(err){ return _reject(err); }\n _resolve();\n });\n } else {\n _resolve();\n }\n });\n }\n });\n });\n}",
"function pullExistingCron() {\n pool.getConnection(function(err, connection) {\n if(err) { console.log(err); return; }\n var sql = 'select * from f_schedule';\n connection.query(sql, [], function(err, results) {\n\n // if there is a result\n if (results) {\n\n results.forEach(function(result) {\n var report = {accountid:result.accountid,groupid: result.groupid,startdate:result.startdate,enddate:result.enddate, lengthdays:result.lengthdays};\n var schedule = ''+ result.seconds+' '+result.minutes+' '+result.hours+' '+result.dayofmonth+' '+result.months+' '+result.dayofweek+'';\n console.log(report);\n console.log(schedule);\n // creae the job\n var job = new CronJob({\n cronTime: schedule,\n onTick: function() {\n // this is the scheduled task\n pullautoreport(report);\n },\n start: true,\n //timeZone: \"America/Los_Angeles\"\n });\n // start the job\n job.start();\n });\n\n }\n\n connection.release(); // always put connection back in pool after last query\n if(err) { console.log(err); return; }\n });\n });\n\n\n}",
"function wrapApiHandlerWithSentryVercelCrons(\n handler,\n vercelCronsConfig,\n) {\n return new Proxy(handler, {\n apply: (originalFunction, thisArg, args) => {\n return runWithAsyncContext(() => {\n if (!args || !args[0]) {\n return originalFunction.apply(thisArg, args);\n }\n\n const [req] = args;\n\n let maybePromiseResult;\n const cronsKey = 'nextUrl' in req ? req.nextUrl.pathname : req.url;\n const userAgentHeader = 'nextUrl' in req ? req.headers.get('user-agent') : req.headers['user-agent'];\n\n if (\n !vercelCronsConfig || // do nothing if vercel crons config is missing\n !_optionalChain([userAgentHeader, 'optionalAccess', _ => _.includes, 'call', _2 => _2('vercel-cron')]) // do nothing if endpoint is not called from vercel crons\n ) {\n return originalFunction.apply(thisArg, args);\n }\n\n const vercelCron = vercelCronsConfig.find(vercelCron => vercelCron.path === cronsKey);\n\n if (!vercelCron || !vercelCron.path || !vercelCron.schedule) {\n return originalFunction.apply(thisArg, args);\n }\n\n const monitorSlug = vercelCron.path;\n\n const checkInId = captureCheckIn(\n {\n monitorSlug,\n status: 'in_progress',\n },\n {\n maxRuntime: 60 * 12, // (minutes) so 12 hours - just a very high arbitrary number since we don't know the actual duration of the users cron job\n schedule: {\n type: 'crontab',\n value: vercelCron.schedule,\n },\n },\n );\n\n const startTime = Date.now() / 1000;\n\n const handleErrorCase = () => {\n captureCheckIn({\n checkInId,\n monitorSlug,\n status: 'error',\n duration: Date.now() / 1000 - startTime,\n });\n };\n\n try {\n maybePromiseResult = originalFunction.apply(thisArg, args);\n } catch (e) {\n handleErrorCase();\n throw e;\n }\n\n if (typeof maybePromiseResult === 'object' && maybePromiseResult !== null && 'then' in maybePromiseResult) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n captureCheckIn({\n checkInId,\n monitorSlug,\n status: 'ok',\n duration: Date.now() / 1000 - startTime,\n });\n },\n () => {\n handleErrorCase();\n },\n );\n\n // It is very important that we return the original promise here, because Next.js attaches various properties\n // to that promise and will throw if they are not on the returned value.\n return maybePromiseResult;\n } else {\n captureCheckIn({\n checkInId,\n monitorSlug,\n status: 'ok',\n duration: Date.now() / 1000 - startTime,\n });\n return maybePromiseResult;\n }\n });\n },\n });\n}",
"function shiftTrashSchedule() {\n /**\n * queryString -> Shift the first user in trash schedule to be the last\n * queryString2 -> Delete the cron job for trash\n * queryString3 -> Get the next user for trash\n * queryString4 -> Add the user into cron\n */\n const queryString =\n \"UPDATE trash SET sequence = ((SELECT sequence FROM (SELECT * FROM trash) AS temp3 ORDER BY sequence DESC LIMIT 1) + 1) WHERE id = (SELECT id FROM (SELECT * FROM trash ORDER BY sequence ASC LIMIT 1) AS temp) \";\n const queryString2 = \"DELETE FROM cron WHERE job = 'trash'\";\n const queryString3 = \"SELECT * FROM `trash` ORDER BY sequence ASC LIMIT 1\";\n const queryString4 =\n \"INSERT INTO `cron` (`id`,`user_id`,`username`,`job`,`status`) VALUES (?,?,?,?,?)\";\n\n pool.getConnection(function(err, connection) {\n if (err) throw err;\n\n connection.query(queryString, [], (err, rows, fields) => {\n if (err) {\n throw err;\n } else {\n connection.query(queryString2, [], (err2, rows2, fields2) => {\n if (err2) {\n throw err2;\n } else {\n connection.query(queryString3, [], (err3, rows3, fields3) => {\n if (err3) {\n throw err3;\n } else {\n connection.query(\n queryString4,\n [\"DEFAULT\", rows3[0].user_id, rows3[0].username, \"trash\", 0],\n (err4, rows4, fields4) => {\n if (err4) {\n throw err4;\n } else {\n connection.release();\n }\n }\n );\n }\n });\n }\n });\n }\n });\n });\n}",
"_initializePath() {\n let argPath = \"\";\n program\n .arguments('<path/to/components')\n .action((basePath) => {\n const validatedDirectory = validateDirectory(basePath);\n if (validatedDirectory.isValid ) {\n argPath = basePath;\n } else {\n die(validatedDirectory.error);\n }\n })\n .parse(process.argv);\n\n return argPath;\n }",
"function shiftCookSchedule() {\n /**\n * queryString -> Shift the first user in cook schedule to be the last\n * queryString2 -> Delete the cron job for cook\n * queryString3 -> Get the next user for cook\n * queryString4 -> Add the user into cron\n */\n const queryString =\n \"UPDATE Cook SET sequence = ((SELECT sequence FROM (SELECT * FROM Cook) AS temp3 ORDER BY sequence DESC LIMIT 1) + 1) WHERE id = (SELECT id FROM (SELECT * FROM Cook ORDER BY sequence ASC LIMIT 1) AS temp) \";\n const queryString2 = \"DELETE FROM cron WHERE job = 'cook'\";\n const queryString3 = \"SELECT * FROM `cook` ORDER BY sequence ASC LIMIT 1\";\n const queryString4 =\n \"INSERT INTO `cron` (`id`,`user_id`,`username`,`job`,`status`) VALUES (?,?,?,?,?)\";\n\n pool.getConnection(function(err, connection) {\n if (err) throw err;\n\n connection.query(queryString, [], (err, rows, fields) => {\n if (err) {\n throw err;\n } else {\n connection.query(queryString2, [], (err2, rows2, fields2) => {\n if (err2) {\n throw err2;\n } else {\n connection.query(queryString3, [], (err3, rows3, fields3) => {\n if (err3) {\n throw err3;\n } else {\n connection.query(\n queryString4,\n [\"DEFAULT\", rows3[0].user_id, rows3[0].username, \"cook\", 0],\n (err4, rows4, fields4) => {\n if (err4) {\n throw err4;\n } else {\n connection.release();\n }\n }\n );\n }\n });\n }\n });\n }\n });\n });\n}",
"function generateFullURL(host, path) {\n let protocol = 'http';\n if (config.server.ssl.enabled === true) {\n protocol += 's';\n }\n let fullURL = `${protocol}://${host}${path}`;\n return fullURL\n}",
"function scheduleCommandInvocation(axios$$1, token, schedule, payload) {\n return restAuthPost(axios$$1, 'assignments/' + token + '/invocations/schedules/' + schedule, payload);\n }",
"function calendarURL(date, month, year){\n if (date.length < 2) date = \"0\" + date;\n let day = new Date(year, month, date).getDay();\n return \"/calendar/\" + DAYS_OF_WEEK_ABRV[day] + \" \" + MONTHS_ABRV[month] + \" \" + date + \" \" + year;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cheking to see if a slider goes outside a swipable area. If so depending on the direction accordingly assigning a true value to the variables: leftSide and rightSide | function checkSlidersEdges () {
let outer = obj.getBoundingClientRect();
let inner = innerSlider.getBoundingClientRect();
// Check to prevent a swipe of the first slide to the right
if ( parseInt( innerSlider.style.left ) >= 0 ) {
settings[`${obj.id}`].boundary = true;
settings[`${obj.id}`].leftSide = true;
return true;
}
// If a inslide slider's right position is less than outer slider's right position
if ( inner.right < outer.right ) {
settings[`${obj.id}`].boundary = true;
settings[`${obj.id}`].rightSide = true;
return true;
}
// Storing a differance beetwen outer and inside slider's right sides.
settings[`${obj.id}`].diff = inner.width - outer.width;
} | [
"function checkBoundries() {\n if (x > 560) { // if ship is more than the right of the screen\n rightMove = false; // stop it moving\n } else if (x < 40) { // if ship is more than the left of the screen\n moveLeft = false; // stop it moving\n }\n if (y > 560) { // if ship is more than the bottom of the screen\n downmove = false; // stop it moving\n } else if (y < 30) { // if ship is more than the top of the screen\n upmove = false; // stop it moving\n }\n}",
"function opposite(dir1, dir2) {\n dir1 = dir1.toLowerCase()\n dir2 = dir2.toLowerCase()\n \n if (dir1 === 'north' && dir2 === 'south') { \n return true\n } else if (dir1 === 'south' && dir2 === 'north') {\n return true \n } else if (dir1 === 'east' && dir2 === 'west') { \n return true \n } else if (dir1 === 'west' && dir2 === 'east') { \n return true\n } else { \n return false \n }\n }",
"localClipped (x, y) {\n if (x !== null && (x < 0 || x >= this.Config.size.width)) return true;\n if (y !== null && (y < 0 || y >= this.Config.size.height)) return true;\n return false;\n }",
"function isFocusOutside(e){var allFocusables=getFocusables(document);var currentFocusIndex=allFocusables.indexOf(document.activeElement);var focusDestinationIndex=e.shiftKey?currentFocusIndex-1:currentFocusIndex+1;var focusDestination=allFocusables[focusDestinationIndex];var destinationItemSlide=nullOrSlide(closest(focusDestination,SLIDE_SEL));var destinationItemSection=nullOrSection(closest(focusDestination,SECTION_SEL));return!destinationItemSlide&&!destinationItemSection;}//Scrolling horizontally when clicking on the slider controls.",
"function toggleButton() {\n leftPosition == 0 ? arrowLeft.hide() : arrowLeft.show();\n Math.abs(leftPosition) >= innerBoxWidth - containerWidth ? arrowRight.hide() : arrowRight.show();\n }",
"function canJewelMove(x,y) {\n \n // Can swap with left\n if (x > 0 && canSwap(x,y,x-1,y))\n return true;\n\n // Can swap with right\n if (x < (cols-1) && canSwap(x,y,x+1,y))\n return true;\n\n // Can swap with down\n if (y > 0 && canSwap(x,y,x,y-1))\n return true;\n \n // Can swap with up\n if (y < (rows-1) && canSwap(x,y,x,y+1))\n return true;\n\n return false;\n }",
"function clipSutherland() { \r\n\r\n clip1x = x1;\r\n clip1y = y1;\r\n clip2x = x2;\r\n clip2y = y2;\r\n\r\n var x = 0;\r\n var y = 0;\r\n var m = (clip2y - clip1y) / (clip2x - clip1x);\r\n\r\n var code1 = getCode(clip1x, clip1y);\r\n var code2 = getCode(clip2x, clip2y);\r\n\r\n while (code1 != INSIDE || code2 != INSIDE) {\r\n\r\n var clipCode;\r\n\r\n if ((code1 & code2) != INSIDE) {\r\n return false;\r\n }\r\n if (code1 == INSIDE) {\r\n clipCode = code2;\r\n }\r\n else { \r\n clipCode = code1\r\n }\r\n if ((clipCode & LEFT) != INSIDE) {\r\n x = xMin;\r\n y = (x - clip1x) * m + clip1y;\r\n }\r\n else if ((clipCode & RIGHT) != INSIDE) {\r\n x = xMax;\r\n y = (x - clip1x) * m + clip1y;\r\n }\r\n else if ((clipCode & BOTTOM) != INSIDE) {\r\n y = yMin;\r\n x = (y - clip1y) / m + clip1x;\r\n }\r\n else if ((clipCode & TOP) != INSIDE) {\r\n y = yMax;\r\n x = (y - clip1y) / m + clip1x;\r\n }\r\n if (clipCode == code1) {\r\n clip1x = x;\r\n clip1y = y;\r\n code1 = getCode(clip1x, clip1y);\r\n }\r\n else {\r\n clip2x = x;\r\n clip2y = y;\r\n code2 = getCode(clip2x, clip2y);\r\n }\r\n }\r\n return true;\r\n}",
"function handleSliderDrag(event){\n\t\t\n\t\tvar diff = g_temp.lastMouseX - g_temp.startMouseX;\n\t\t\n\t\tif(diff == 0)\n\t\t\treturn(true);\n\t\t\n\t\tvar direction = (diff < 0) ? \"left\":\"right\";\n\t\t\n\t\tvar objZoomSlider = g_parent.getObjZoom();\n\t\t\t\t\n\t\t//don't drag if the zoom panning enabled\n\t\t//store init position after image zoom pan end\n\t\tif(objZoomSlider){\n\t\t\t\n\t\t\tvar isPanEnabled = objZoomSlider.isPanEnabled(event,direction);\n\t\t\t\t\t\t\n\t\t\tif(isPanEnabled == true){\n\t\t\t\tg_temp.isInitDataValid = false;\n\t\t\t\treturn(true);\t\t\t\t\n\t\t\t}else{\n\t\t\t\t\n\t\t\t\tif(g_temp.isInitDataValid == false){\n\t\t\t\t\tstoreInitTouchData(event);\n\t\t\t\t\treturn(true);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\t\t\t\t\t\n\t\t//set inner div position\n\t\tvar currentPosx = g_temp.startPosx + diff;\n\t\t\n\t\t//check out of borders and slow down the motion:\n\t\tif(diff > 0 && currentPosx > 0)\n\t\t\tcurrentPosx = currentPosx / 3;\t\t\n\t\t\n\t\telse if(diff < 0 ){\n\t\t\t\n\t\t\tvar innerEnd = currentPosx + g_objInner.width();\n\t\t\tvar sliderWidth = g_objSlider.width();\n\t\t\t\n\t\t\tif( innerEnd < sliderWidth ){\n\t\t\t\tcurrentPosx = g_temp.startPosx + diff/3;\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tg_objInner.css(\"left\", currentPosx+\"px\");\n\t\t\n\t}",
"hasWallInDirection (x, y, direction) {\n return !(this.getBlockValue(x, y) & direction);\n }",
"isInside(modelSpacePoint) {\n\t\t// jshint unused:vars\n\t\treturn false;\n\t}",
"function out_of_screen(){\r\n ax = airplane_pos.worldMatrix[6];\r\n ay = airplane_pos.worldMatrix[7];\r\n if (ax < -30 || ax > width + 30 || ay < -30 || ay > height + 30) return true;\r\n return false;\r\n}",
"function onSwipe(curHand) {\r\n var direction = curHand.palmVelocity[0];\r\n if (direction < 0) { // Negative direction => moving right to left => swipe left\r\n swipeRightCount = 0;\r\n circleFingerCount = 0;\r\n swipeLeftCount++;\r\n if (swipeLeftCount >= SWIPE_LEFT_THRESHOLD) { \r\n swipeLeftCount = 0;\r\n shiftShelfUpward(); \r\n //console.log(\"left\"); // SWIPE LEFT DETECTED \r\n }\r\n } else { // Otherwise must be positive direction => moving left to right => swipe right\r\n swipeLeftCount = 0;\r\n circleFingerCount = 0;\r\n swipeRightCount++;\r\n if (swipeRightCount >= SWIPE_RIGHT_THRESHOLD) {\r\n swipeRightCount = 0;\r\n cycleSortPriority(); \r\n //console.log(\"right\"); // SWIPE RIGHT DETECTED\r\n }\r\n }\r\n }",
"function checkYLimit(idOrientation, idFranckyPositionY, heightOfWorld) {\r\n\r\n // Get the orientation & pos Y\r\n var orientation = document.getElementById(idOrientation).innerHTML;\r\n var intPosY = parseInt(document.getElementById(idFranckyPositionY).innerHTML, 10);\r\n\r\n // Deal with up side\r\n // -----------------------------------------\r\n if ((intPosY == heightOfWorld) && (orientation == 'North')) {\r\n return false;\r\n }\r\n\r\n // Deal with down side\r\n // -----------------------------------------\r\n if ((intPosY == 1) && (orientation == 'South')) {\r\n return false;\r\n }\r\n\r\n // End of function\r\n // -----------------------------------\r\n return true;\r\n\r\n}",
"function checkForOverlap(currentDropArea , leftPos,width) {\n\t\tvar children = currentDropArea.children;\n\t\tfor(var i = 0; i < children.length; i++) {\n\t\t\tvar currentChild = children[i].getBoundingClientRect();\n\t\t\tif((leftPos <= currentChild.right && leftPos >= currentChild.left) || (leftPos + width <= currentChild.right && leftPos + width >= currentChild.left)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}",
"function sliderClick(slider, point) {\n\tif (insideBox([slider.x,slider.y,slider.x+slider.width,slider.y+slider.height], point)) {\n\t\tslider.active = !slider.active;\n\t\t//console.log(\"clicked\");\n\t\treturn true;\n\t}\n\telse {\n\t\tvar divX = slider.width*1/5;\n\t\tif (slider.active) {\n\t\t\tdivX = divX*3;\n\t\t}\n\t\tif (insideBox([slider.x+divX,slider.y-slider.height/3,slider.x+divX+slider.width*1.3/5, slider.y+slider.height*5/3], point)) {\n\t\t\tslider.active = !slider.active;\n\t\t\treturn true;\n\t\t}\n\t}\t\n\treturn false;\n}",
"moveSlotSlider(index, newWidth) {\n var left_closet_face_x_value = this.group.getObjectById(this.closet_faces_ids[2]).position.x;\n var rigth_closet_face_x_value = this.group.getObjectById(this.closet_faces_ids[3]).position.x;\n this.selected_slot = this.group.getObjectById(this.closet_slots_faces_ids[index]);\n if (index == 0) {\n let newPosition = left_closet_face_x_value + newWidth;\n this.selected_slot.position.x = newPosition;\n } else {\n var positionLefthSlot = this.group.getObjectById(this.closet_slots_faces_ids[index - 1]).position.x;\n if (positionLefthSlot + newWidth >= rigth_closet_face_x_value) {\n this.selected_slot.position.x = positionLefthSlot;\n } else {\n this.selected_slot.position.x = positionLefthSlot + newWidth;\n }\n }\n }",
"function isNotColiding(obj){\n\tvar s = obj.scale;\n\tvar p = obj.position;\n\tvar cp = {'x':newPosX,'z':newPosZ};\n\tif(cp.x < (s.x+0.5)/2.25+p.x && cp.x > p.x-(s.x+0.5)/2.25 && cp.z < (s.z+0.75)/2.25+p.z && cp.z > p.z-(s.z+0.75)/2.25){\n\t\treturn false;\n\t}else{\n\t\treturn true;\n\t}\n}",
"function inBounds(p) {\n // check bounds of display\n if((p[0]-2*bcr) <= width * 0.1 || //left\n (p[0]+2*bcr) >= width - (width * 0.1) || //right\n (p[1]-2*bcr) <= height * 0.1 ||\n (p[1]+2*bcr) >= height - (height * 0.1)) {\n return false;\n }\n return true;\n}",
"function check_if_can_move(location, direction){\n if(direction == \"secret\"){\n if (location[0] % 4 == 0 && location[1] % 4 == 0){\n return true;\n }\n return false;\n }\n \n switch(direction) {\n case \"left\": \n if ((location[0] - 1) < 0)\n return false;\n break;\n case \"up\":\n if ((location[1] + 1) > 4)\n return false;\n break;\n case \"right\":\n if((location[0] + 1) > 4)\n return false;\n break;\n case \"down\":\n if((location[1] - 1) < 0)\n return false;\n break;\n }\n return true;\n}",
"function boxSide(boxName) {\n\t\t(boxName == 'one') || (boxName == 'two') || (boxName == 'three') || (boxName == 'four') ? side = 'left' : side = 'right'\n\t\treturn side\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens MOS card video overlay | function openOverlay(e) {
const videoWrapper =
e.target.parentNode.parentNode.parentNode.parentNode.children[0];
const videoWrapperInner = e.target.parentNode.parentNode;
const mosVideo = videoWrapper.children[0];
videoWrapper.style.display = "block";
videoWrapperInner.style.visibility = "hidden";
mosVideo.play();
setIsVideoOpen(true);
} | [
"function openVideo() {\r\n\t\tTitanium.Platform.openURL(movie.trailerUrl);\r\n\t}",
"function w3_openvd() {\n\tdocument.getElementById(\"closevideo\").style.display = \"block\";\n}",
"addMedia() {\n\n this.mediaFrame.open();\n }",
"function startVideo() {\n mini_peer.setLocalStreamToElement({ video: true, audio: true }, localVideo);\n}",
"function closeOverlay(e) {\n if (isVideoOpen === true) {\n const mosVideoWrapper =\n document.getElementsByClassName(\"mos-video-wrapper\");\n const flipCardInner = document.getElementsByClassName(\"flip-card-inner\");\n const mosVideo = document.getElementsByClassName(\"mos-video\");\n\n for (let i = 0; i < mosVideoWrapper.length; i++) {\n mosVideoWrapper[i].style.display = \"none\";\n }\n\n for (let i = 0; i < mosVideo.length; i++) {\n mosVideo[i].pause();\n mosVideo[i].currentTime = 0;\n }\n\n for (let i = 0; i < flipCardInner.length; i++) {\n flipCardInner[i].style.visibility = \"visible\";\n }\n\n setIsVideoOpen(false);\n }\n }",
"function openVideo(video_id) {\n $(modal.replace(\"{VIDEO_ID}\", video_id)).appendTo('body').modal();\n}",
"function SCVideoGalleryOpenCreateVideoCommentWindow(vgId, videoControlId) { \n window.open('ControlWrapper.aspx?control=../EPiServerCommunity/Modules/VideoGallery/CreateVideoCommentControl.ascx&videoId=' + vgId + '&videoControlId=' + videoControlId, '_blank', 'width=745, height=497, scrollbars=yes, resizable=yes');\n}",
"showOverlay_() {\n this.overlay_.setAttribute('i-amphtml-lbg-fade', 'in');\n this.controlsMode_ = LightboxControlsModes.CONTROLS_DISPLAYED;\n }",
"function StartRemoteMov(url) {\n\tremoteWin = window.open('',\"GAGMEREMOTE2\",'width=670,height=520,resizable=yes,scrollbars=yes,statusbar=yes');\n\tremoteWin.statusbar.visibe = true;\n\tremoteWin.location = url;\n\tremoteWin.focus();\n}",
"_onVaadinOverlayOpen() {\n this.__alignOverlayPosition();\n this.$.overlay.style.opacity = '';\n this.__forwardFocus();\n }",
"function SCVideoGalleryOpenEditVideoCommentWindow(vcId, videoControlId) {\n window.open('ControlWrapper.aspx?control=../EPiServerCommunity/Modules/VideoGallery/EditVideoCommentControl.ascx&videoCommentId=' + vcId + '&videoControlId=' + videoControlId, '_blank', 'width=745, height=497, scrollbars=yes, resizable=yes');\n}",
"function reproducirVideo(){\n\t$('#videoModal').modal('show');\n\tvideo.play(); \n}",
"function cargarVideo(url,imagen){\r\n var v = document.createElement(\"video\"); \r\n //if ( (!v.play) && (!Liferay.Browser.isSafari())) { // If no, use Flash.\r\n if(!Modernizr.video){\r\n var params = {\r\n allowfullscreen: \"true\",\r\n allowscriptaccess: \"always\",\r\n wmode:\"transparent\"\r\n };\r\n var flashvars = {\r\n config: \"{'playlist':[ {'url': '\"+url+\"','autoPlay':false,'autoBuffering':true}]}&\" \r\n };\r\n //swfobject.embedSWF(\"http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf\", \"video\", \"480\", \"272\", \"9.0.0\", \"expressInstall.swf\", flashvars, params);\r\n swfobject.embedSWF(\"flowplayer-3.2.1.swf\", \"video\", \"480\", \"272\", \"9.0.0\", \"expressInstall.swf\", flashvars, params);\r\n }\r\n}",
"function displayVideo(videoBlob, outerDiv){\n var video = document.createElement(\"video\");\n video.setAttribute(\"class\", \"videoClasses\")\n video.autoplay = true;\n video.controls = false; // optional\n video.loop = true;\n video.height = VIDEO_HEIGHT;\n var source = document.createElement(\"source\");\n source.src = URL.createObjectURL(base64_to_blob(videoBlob));\n source.type = \"video/webm\";\n\n video.appendChild(source);\n if(version === \"A\"){\n outerDiv.innerHTML = \"\";\n }else{\n\n }\n outerDiv.appendChild(video);\n}",
"openAudioPanel() {\n this.props.toogleOverlay();\n }",
"function video_click(e) {\n\t//console.log(e);\n\t//console.log(this);\n\tif (this.paused == true) {\n\t\tthis.play();\n\t} else {\n\t\tthis.pause();\n\t}\n}",
"function connected() {\n\n $('#loader').fadeOut();\n $('#stream img').attr('src', 'http://' + window.location.hostname.split(':')[0] + ':4444/stream/video.mjpeg');\n\n}",
"function switchVideo(video1, video2 , h , w){\n\n if(!video1)\n video1=document.getElementById(\"localVideo\");\n\n if(video2==undefined){\n if(document.getElementById(\"remotes\").getElementsByTagName(\"video\")[0]!=undefined)\n video2=document.getElementById(\"remotes\").getElementsByTagName(\"video\")[0];\n else\n video2=null;\n }\n\n if(webrtc.webrtc.getPeers().length==0){\n hideDiv(\"localVideo\");\n $(\"#media_settings_btn\").removeClass(\"hidedisplay\");\n \n if (callflag==0){\n showDiv(\"notificationsDiv\");\n }\n else if(callflag==1){\n showDiv(\"notificationsDiv\"); \n $('#notifications').text('Your partner has left');\n }\n }else if(webrtc.webrtc.getPeers().length>0){\n console.log(\"remote members to canvas center\");\n // stop the waiting music \n // stopWaitingMusic();\n if(video1 && video2 && video1!=video2){ \n showDiv(\"localVideo\");\n }\n $('#notifications').text('');\n hideDiv(\"notificationsDiv\");\n $(\"#media_settings_btn\").addClass(\"hidedisplay\");\n hidetooltip(tooltiproomnotifications);\n } \n \n drawStuff(video1,video2,h,w);\n}",
"async function screenShare() {\n // if we're already sharing, then stop\n if (my_screen_stream) {\n // unpublish\n await bandwidthRtc.unpublish(my_screen_stream.endpointId);\n\n // stop the tracks locally\n var tracks = my_screen_stream.getTracks();\n tracks.forEach(function (track) {\n console.log(`stopping stream`);\n console.log(track);\n track.stop();\n });\n document.getElementById(\"screen_share\").innerHTML = \"Screen Share\";\n\n my_screen_stream = null;\n document.getElementById(\"share\").style.display = \"none\";\n } else {\n video_constraints = {\n frameRate: 30,\n };\n // getDisplayMedia is the magic function for screen/window/tab sharing\n try {\n my_screen_stream = await navigator.mediaDevices.getDisplayMedia({\n audio: false,\n video: video_constraints,\n });\n } catch (err) {\n if (err.name != \"NotAllowedError\") {\n console.error(`getDisplayMedia error: ${err}`);\n }\n }\n\n if (my_screen_stream != undefined) {\n // we're now sharing, so start, and update the text of the link\n document.getElementById(\"screen_share\").innerHTML = \"Stop Sharing\";\n\n // start the share and save the endPointId so we can unpublish later\n var resp = await bandwidthRtc.publish(\n my_screen_stream,\n undefined,\n \"screenshare\"\n );\n my_screen_stream.endpointId = resp.endpointId;\n document.getElementById(\"share\").style.display = \"inline-block\";\n document.getElementById(\"share\").onClick = fullScreenShare();\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asserts that an IndexedDbStore is associated with a database. | _assertDb () {
if (!this._db) throw new Error(IndexedDbStore.errMsgs.NO_DB)
} | [
"function createDb(){\n const createDb = window.indexedDB.open('crm',1);\n\n createDb.onerror = () => console.log('Hubo un error');\n\n createDb.onsuccess = () => DB = createDb.result;\n\n createDb.onupgradeneeded = e => {\n const db = e.target.result;\n \n const objectStore = db.createObjectStore('crm',{ keyPath:'id', autoIncrement:true });\n\n objectStore.createIndex('nombre','nombre', {unique:false});\n objectStore.createIndex('email','email', {unique:true});\n objectStore.createIndex('telefono','telefono', {unique:false});\n objectStore.createIndex('empresa','empresa', {unique:false});\n objectStore.createIndex('id','id', {unique:true});\n\n console.log('Lista');\n }\n }",
"static createIDBObjects(){\r\n\r\n\t\treturn idb.open(DBHelper.IDB_DATABASE, 1, upgradeDb => {\r\n\r\n\t\t\tvar restaurantsStore = upgradeDb.createObjectStore('restaurants',{\r\n\t\t\t\tkeyPath: 'id'\r\n\t\t\t});\r\n\r\n\t\t\tvar reviewsStore = upgradeDb.createObjectStore('reviews',{\r\n\t\t\t\tkeyPath: 'id'\r\n\t\t\t});\r\n\t\t\treviewsStore.createIndex(\"restaurant_id\", \"restaurant_id\");\r\n\r\n\t\t\tvar offlineStore = upgradeDb.createObjectStore('offlineRequests',{\r\n\t\t\t\tkeyPath: 'id',\r\n\t\t\t\tautoIncrement: true\r\n\t\t\t});\r\n\r\n\t\t});\r\n\t}",
"function checkDatabase() {\n // Open transaction on pending DB\n const transaction = db.transaction([\"pending\"], \"readwrite\");\n\n // Access pending object store\n const store = transaction.objectStore(\"pending\");\n\n // Get all pending records\n const getAll = store.getAll();\n\n // Get all transaction with JSON\n getAll.onsuccess = function() {\n if (getAll.result.length > 0) {\n fetch(\"/api/transaction/bulk\", {\n method: \"POST\",\n body: JSON.stringify(getAll.result),\n headers: {\n Accept: \"application/json, text/plain, */*\",\n \"Content-Type\": \"application/json\"\n }\n })\n .then(response => response.json())\n .then(() => {\n // If sucessful, a new transaction will open as pending\n const transaction = db.transaction([\"pending\"], \"readwrite\");\n\n //Acces pending object store\n const store = transaction.objectStore(\"pending\");\n\n // Clear all items\n store.clear();\n })\n }\n }\n}",
"function storeTheDataInIndexedDb(db, data) {\n return new Promise(function(resolve, reject) {\n const transaction = db.transaction('metal', 'readwrite');\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => reject(transaction.error);\n const store = transaction.objectStore('metal');\n for(let obj of data) {\n store.put(obj);\n }\n });\n }",
"function idbCreate_entity() {\t// name, url, position of entity \r\n\tvar request = db.setVersion('1');\r\n\trequest.onerror = function(e){log(\"Error: IndexedDB create entity\");};\r\n\trequest.onsuccess = function(e) {\r\n\t\tif (!db.objectStoreNames.contains('entity')) {\r\n\t\t\ttry {\t\t\t\t\r\n\t\t\t\tdb.createObjectStore('entity', {keyPath: 'id'});\r\n\t\t\t\tlog(\"Object store entity created\");\r\n\t\t\t} catch (err) {\t\r\n\t\t\t\tlog(\"Error: IndexedDB create entity\");\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tlog(\"Object store entity already exists\");\r\n\t\t}\r\n\t}\r\n}",
"function baseFeatureStoreTests(makeStore, clearExistingData, isCached) {\n var feature1 = {\n key: 'foo',\n version: 10\n };\n var feature2 = {\n key: 'bar',\n version: 10\n };\n\n beforeEach(function(done) {\n if (clearExistingData) {\n clearExistingData(done);\n } else {\n done();\n }\n });\n\n function initedStore(cb) {\n var store = makeStore();\n var initData = {};\n initData[dataKind.features.namespace] = {\n 'foo': feature1,\n 'bar': feature2\n };\n store.init(initData, function() {\n cb(store);\n });\n }\n\n it('is initialized after calling init()', function(done) {\n initedStore(function(store) {\n store.initialized(function(result) {\n expect(result).toBe(true);\n done();\n });\n });\n });\n\n it('init() completely replaces previous data', function(done) {\n var store = makeStore();\n var flags = {\n first: { key: 'first', version: 1 },\n second: { key: 'second', version: 1 }\n };\n var segments = { first: { key: 'first', version: 2 } };\n var initData = {};\n initData[dataKind.features.namespace] = flags;\n initData[dataKind.segments.namespace] = segments;\n\n store.init(initData, function() {\n store.all(dataKind.features, function(items) {\n expect(items).toEqual(flags);\n store.all(dataKind.segments, function(items) {\n expect(items).toEqual(segments);\n\n var newFlags = { first: { key: 'first', version: 3 } };\n var newSegments = { first: { key: 'first', version: 4 } };\n var initData = {};\n initData[dataKind.features.namespace] = newFlags;\n initData[dataKind.segments.namespace] = newSegments;\n\n store.init(initData, function() {\n store.all(dataKind.features, function(items) {\n expect(items).toEqual(newFlags);\n store.all(dataKind.segments, function(items) {\n expect(items).toEqual(newSegments);\n\n done();\n })\n })\n });\n });\n });\n });\n });\n\n if (!isCached && clearExistingData) {\n function testInitStateDetection(desc, initData) {\n it(desc, function(done) {\n var store1 = makeStore();\n var store2 = makeStore();\n\n store1.initialized(function(result) {\n expect(result).toBe(false);\n\n store2.init(initData, function() {\n store1.initialized(function(result) {\n expect(result).toBe(true);\n done();\n });\n });\n });\n });\n }\n\n testInitStateDetection('can detect if another instance has initialized the store',\n { features: { foo: feature1 } });\n\n testInitStateDetection('can detect if another instance has initialized the store, even with empty data',\n { features: {} });\n }\n\n it('gets existing feature', function(done) {\n initedStore(function(store) {\n store.get(dataKind.features, feature1.key, function(result) {\n expect(result).toEqual(feature1);\n done();\n });\n });\n });\n\n it('does not get nonexisting feature', function(done) {\n initedStore(function(store) {\n store.get(dataKind.features, 'biz', function(result) {\n expect(result).toBe(null);\n done();\n });\n });\n });\n\n it('gets all features', function(done) {\n initedStore(function(store) {\n store.all(dataKind.features, function(result) {\n expect(result).toEqual({\n 'foo': feature1,\n 'bar': feature2\n });\n done();\n });\n });\n });\n\n it('upserts with newer version', function(done) {\n var newVer = { key: feature1.key, version: feature1.version + 1 };\n initedStore(function(store) {\n store.upsert(dataKind.features, newVer, function(result) {\n store.get(dataKind.features, feature1.key, function(result) {\n expect(result).toEqual(newVer);\n done();\n });\n });\n });\n });\n\n it('does not upsert with older version', function(done) {\n var oldVer = { key: feature1.key, version: feature1.version - 1 };\n initedStore(function(store) {\n store.upsert(dataKind.features, oldVer, function(result) {\n store.get(dataKind.features, feature1.key, function(result) {\n expect(result).toEqual(feature1);\n done();\n });\n });\n });\n });\n\n it('upserts new feature', function(done) {\n var newFeature = { key: 'biz', version: 99 };\n initedStore(function(store) {\n store.upsert(dataKind.features, newFeature, function(result) {\n store.get(dataKind.features, newFeature.key, function(result) {\n expect(result).toEqual(newFeature);\n done();\n });\n });\n });\n });\n\n it('handles upsert race condition within same client correctly', function(done) {\n var ver1 = { key: feature1.key, version: feature1.version + 1 };\n var ver2 = { key: feature1.key, version: feature1.version + 2 };\n initedStore(function(store) {\n var counter = 0;\n var combinedCallback = function() {\n counter++;\n if (counter == 2) {\n store.get(dataKind.features, feature1.key, function(result) {\n expect(result).toEqual(ver2);\n done();\n });\n }\n };\n // Deliberately do not wait for the first upsert to complete before starting the second,\n // so their transactions will be interleaved unless we're correctly serializing updates\n store.upsert(dataKind.features, ver2, combinedCallback);\n store.upsert(dataKind.features, ver1, combinedCallback);\n });\n });\n\n it('deletes with newer version', function(done) {\n initedStore(function(store) {\n store.delete(dataKind.features, feature1.key, feature1.version + 1, function(result) {\n store.get(dataKind.features, feature1.key, function(result) {\n expect(result).toBe(null);\n done();\n });\n });\n });\n });\n\n it('does not delete with older version', function(done) {\n initedStore(function(store) {\n store.delete(dataKind.features, feature1.key, feature1.version - 1, function(result) {\n store.get(dataKind.features, feature1.key, function(result) {\n expect(result).not.toBe(null);\n done();\n });\n });\n });\n });\n\n it('allows deleting unknown feature', function(done) {\n initedStore(function(store) {\n store.delete(dataKind.features, 'biz', 99, function(result) {\n store.get(dataKind.features, 'biz', function(result) {\n expect(result).toBe(null);\n done();\n });\n });\n });\n });\n\n it('does not upsert older version after delete', function(done) {\n initedStore(function(store) {\n store.delete(dataKind.features, feature1.key, feature1.version + 1, function(result) {\n store.upsert(dataKind.features, feature1, function(result) {\n store.get(dataKind.features, feature1.key, function(result) {\n expect(result).toBe(null);\n done();\n });\n });\n });\n });\n });\n}",
"function idbReady() {\n const isSafari = /Safari\\//.test(navigator.userAgent) &&\n !/Chrom(e|ium)\\//.test(navigator.userAgent);\n // No point putting other browsers through this mess.\n if (!isSafari)\n return Promise.resolve();\n let intervalId;\n return new Promise((resolve) => {\n const tryIdb = () => indexedDB.databases().finally(resolve);\n intervalId = setInterval(tryIdb, 100);\n tryIdb();\n }).finally(() => clearInterval(intervalId));\n}",
"function ensure_database_exists(callback) {\n var options = {\n host: config.couch.host,\n port: config.couch.port,\n path: '/' + config.couch.db,\n method: 'PUT',\n headers: {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": user_agent,\n \"Accept\": \"application/json\"\n }\n };\n http.request(options, function(response) {\n /* CouchDB returns 201 if the DB was created or 412 if it already exists. */\n if (response.statusCode === 201 || response.statusCode === 412) {\n response.on('end', callback);\n } else {\n util.error(\"couldn't make database; request returned \" + response.statusCode);\n }\n }).end();\n}",
"static insertDataIDB(tableName, data) {\n\n return DBHelper.openDB().then(function(db) {\n\n let tx = db.transaction(tableName, 'readwrite');\n let store = tx.objectStore(tableName);\n //console.log(store);\n //console.log('Inserting in IDB: ' + data);\n store.put(data);\n\n return tx.complete;\n }).catch((err) => {\n console.log(\"error inserting something into the idb\", err);\n return;\n });\n }",
"function runTest() {\n try {\n var db = openTestDatabase();\n db.transaction(function(tx) {\n // Create the Test table if it does not exist\n tx.executeSql(\"CREATE TABLE IF NOT EXISTS Test (Foo int);\", [],\n function(result) {}, function(tx, error) {});\n }, function(error) {\n log(\"Creating the Test table failed: \" + error.message);\n }, function() {\n // The Test table was created successfully\n var db1 = openTestDatabase();\n var db2 = openTestDatabase();\n if (db1 == db2)\n log(\"failure: db1 == db2\");\n else {\n runTransaction(db1, \"db1\", 1);\n runTransaction(db2, \"db2\", 2);\n }\n });\n } catch(err) {}\n}",
"function testGetTableIndices_NoIndices() {\n asyncTestCase.waitForAsync('testGetTableIndices');\n\n var schema = new lf.testing.MockSchema();\n\n indexStore.init(schema).then(function() {\n var tableWithNoIndexName = 'tableC';\n // There should be at least one row id index.\n assertEquals(1, indexStore.getTableIndices(tableWithNoIndexName).length);\n assertNotNull(indexStore.getRowIdIndex(tableWithNoIndexName));\n asyncTestCase.continueTesting();\n });\n}",
"constructor(dbFilePath) {\n if (dbFilePath) {\n //embedded\n this.db = new Datastore({ filename: dbFilePath, autoload: true });\n } else {\n //in memory \n this.db = new Datastore();\n }\n }",
"function runTransaction(db, dbName, val)\n{\n db.transaction(function(tx) {\n // Execute a read-only statement\n tx.executeSql(\"SELECT COUNT(*) FROM Test;\", [],\n function(result) { statementSuccessCallback(dbName, \"read\"); },\n function(tx, error) { statementErrorCallback(dbName, \"read\", error); });\n\n // Execute a write statement to make sure SQLite tries to acquire an exclusive lock on the DB file\n tx.executeSql(\"INSERT INTO Test VALUES (?);\", [val],\n function(result) { statementSuccessCallback(dbName, \"write\"); },\n function(tx, error) { statementErrorCallback(dbName, \"write\", error); });\n }, function(error) {\n // Transaction failure callback\n log(dbName + \" transaction failed: \" + error.message);\n checkCompletion();\n }, function() {\n // Transaction success callback\n log(dbName + \" transaction succeeded\");\n checkCompletion();\n });\n}",
"function Database(props) {\n return __assign({ Type: 'AWS::Glue::Database' }, props);\n }",
"static _createStores(connection) {\n store.forEach(store => {\n if (connection.objectStoreNames.contains(store)) { // caso tenha uma store, ela será deletada.\n connection.deleteObjectStore(store);\n }\n \n connection.createObjectStore(store, { // Caso tudo esteja correto, será criado uma nova store.\n autoIncrement: true\n });\n });\n\n }",
"function idbCreate_attributes(){\r\n\tvar request = db.setVersion('1');\r\n\trequest.onerror = function(e){log(\"Error: IndexedDB create attributes\");};\r\n\trequest.onsuccess = function(e) {\r\n\t\tif (!db.objectStoreNames.contains('attributes')) {\r\n\t\t\ttry {\r\n\t\t\t\tdb.createObjectStore('attributes', {keyPath: 'id'});\r\n\t\t\t\tvar key = '__default_attributes__';\r\n\t\t\t\t$.ajax({\r\n\t\t\t\t\turl:'bin/xml_to_json.php',\r\n\t\t\t\t\ttype:'POST',\r\n\t\t\t\t\tdataType:'json',\r\n\t\t\t\t\tdata:{filename:'attributes.xml'},\r\n\t\t\t\t\tsuccess:function(d){\r\n\t\t\t\t\t\tM3D.DB.setAttributes({name:key, value:d.attributes});\r\n\t\t\t\t\t},\r\n\t\t\t\t\terror:function(){\r\n\t\t\t\t\t\talert('Could not load Models attributes! A server error has occured!');\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\tlog(\"Object store attributes created\");\r\n\t\t\t} catch (err) {\r\n\t\t\t\tlog(\"Error: IndexedDB create attributes\");\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tlog(\"Object store attributes already exists\");\r\n\t\t}\r\n\t}\r\n}",
"function databaseSingletonTest(){\n var oracle = DatabaseSingleton.getInstance();\n var postgres = DatabaseSingleton.getInstance();\n console.log(\"\\nSame database instance? %s\", (oracle === postgres));\n}",
"function idbCreate_grammar(name) {\t// grammar \r\n\tvar request = db.setVersion('1');\r\n\trequest.onerror = function(e){log(\"Error: IndexedDB create grammar\");};\r\n\trequest.onsuccess = function(e) {\r\n\t\tif (!db.objectStoreNames.contains('grammar')) {\r\n\t\t\ttry {\r\n\t\t\t\tdb.createObjectStore('grammar', {keyPath: 'id'});\r\n\t\t\t\tlog(\"Object store grammar created\");\r\n\t\t\t\tvar ini='// Game created by 3DWIGS\\n// On '+(new Date()).toGMTString()+'\\n\\ngame has name at \"'+name+'\";\\n';\r\n\t\t\t\tM3D.DB.setGrammar(ini);\r\n\t\t\t\tM3D.Editor.initDB(ini);\r\n\t\t\t\t\r\n\t\t\t} catch (err) {\r\n\t\t\t\tlog(\"Error: IndexedDB create grammar\");\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tlog(\"Object store grammar already exists\");\r\n\t\t}\r\n\t}\r\n}",
"function testInit_PersistentIndices() {\n asyncTestCase.waitForAsync('testInit_PersistentIndices');\n\n var tableSchema = env.schema.table('tableA');\n var rows = getSampleRows(tableSchema, 10, 0);\n\n simulatePersistedIndices(tableSchema, rows).then(\n function() {\n var prefetcher = new lf.cache.Prefetcher(lf.Global.get());\n return prefetcher.init(env.schema);\n }).then(\n function() {\n // Check that RowId index has been properly reconstructed.\n var rowIdIndex = env.indexStore.get(tableSchema.getRowIdIndexName());\n assertTrue(rowIdIndex instanceof lf.index.RowId);\n assertEquals(rows.length, rowIdIndex.getRange().length);\n\n // Check that remaining indices have been properly reconstructed.\n var indices = env.indexStore.getTableIndices(\n tableSchema.getName()).slice(1);\n indices.forEach(function(index) {\n assertTrue(index instanceof lf.index.BTree);\n assertEquals(rows.length, index.getRange().length);\n });\n\n asyncTestCase.continueTesting();\n }, fail);\n}",
"function upgradeDB(db) {\n cal.ASSERT(db, \"Database has not been opened!\", true);\n if (!db.tableExists(\"cal_calendar_schema_version\")) {\n cal.LOG(\"Storage: Creating tables from scratch\");\n beginTransaction(db);\n try {\n executeSimpleSQL(db, getAllSql());\n setDbVersionAndCommit(db, DB_SCHEMA_VERSION);\n } catch (e) {\n reportErrorAndRollback(db, e);\n }\n } else {\n let version = getVersion(db);\n if (version < DB_SCHEMA_VERSION) {\n // First, create a backup\n backupDB(db, version);\n\n // Then start the latest upgrader\n cal.LOG(\"Storage: Preparing to upgrade v\" + version +\n \" to v\" + DB_SCHEMA_VERSION);\n upgrade[\"v\" + DB_SCHEMA_VERSION](db, version);\n } else if (version > DB_SCHEMA_VERSION) {\n throw Components.interfaces.calIErrors.STORAGE_UNKNOWN_SCHEMA_ERROR;\n }\n }\n\n ensureUpdatedTimezones(db);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add coin when switch button clicked | function addActiveCoin(inptSwtch, coin) {
inptSwtch
.unbind("click")
.bind("click", () => removeActiveCoin(inptSwtch, coin));
coin.checked = true;
//save in state active coins
state.activeCoins.push(coin);
let activeListFull = checkIfTheActiveListFull();
if (activeListFull) {
$("#btnSaveActiveCoins").attr("disabled", true);
}
//if active coins more then 5 open modal window
if (activeListFull && !state.modalIsOpen) {
state.modalIsOpen = true;
openModalWindow();
}
} | [
"updateCoinCount(){\n\t\t$(`#coinCount${this.playerId}`).text(`${this.coinCount}`);\n\t}",
"function addEventToSwitch(inptSwtch, coin) {\n let checkSelected = isCoinSelected(coin);\n if (checkSelected) {\n inptSwtch\n .attr(\"checked\", true)\n .bind(\"click\", () => removeActiveCoin(inptSwtch, coin));\n } else {\n inptSwtch.bind(\"click\", () => addActiveCoin(inptSwtch, coin));\n }\n }",
"insertCoin(type) {\n\t\t\n\t\tif(type == \"quarter\"){\n\t\t\t\n\t\t\tthis.cashTendered += 25;\n\t\t\t\n\t\t}else if(type == \"dime\"){\n\t\t\t\n\t\t\tthis.cashTendered += 10;\n\t\t\t\n\t\t}else if(type == \"nickle\"){\n\t\t\t\n\t\t\tthis.cashTendered += 5;\n\t\t\t\n\t\t}else if(type == \"penny\"){\n\t\t\t\n\t\t\tthis.cashTendered += 1;\n\t\t\t\n\t\t}\n\t\t\n }",
"buy() {\n if (clickNumber >= this.cost) {\n clickNumber = truncate(clickNumber-this.cost);\n this.inv += 1;\n document.getElementById(\"inv-\" + this.id).innerHTML = this.inv;\n if (this.itemManualClickStrength != 0) {\n clickStrength *= this.itemManualClickStrength; \n }\n autoClickStrength += this.itemClickStrength;\n this.cost *= 2;\n \n document.getElementById(\"cost-\" + this.id).innerHTML = this.cost;\n display();\n }\n }",
"function increaseDogeCoins(){\n if(counter % doge.happiness === 0){dogecoins++;}\n document.getElementById(\"dogecoinValue\").innerHTML = \"Dogecoins:\" + \" \" + dogecoins;\n window.requestAnimationFrame(increaseDogeCoins);\n}",
"function coin() {\n var coin = Math.floor((Math.random()*2)+1);\n var val = (coin == 1) ? \"Head\" : \"Tail\";\n document.write(\"Random coin value \"+ val);\n}",
"function AddCoins() {\n if (ircClient && ircClient.chans && ircClient.chans[channel] && ircClient.chans[channel].users) {\n _.each(_.keys(ircClient.chans[channel].users), function (u) {\n userDB.findOne({ channel: channel, nick: u }, function (e, r) {\n if (e) {\n console.log(e);\n }\n else if (!r) {\n var baby = new userDB({\n channel: channel,\n nick: u,\n coins: config.coinAcc.amount + config.coinAcc.firstTimeBonus,\n });\n baby.save();\n }\n else {\n r.coins += config.coinAcc.amount;\n r.save();\n }\n });\n });\n }\n setTimeout(AddCoins, config.coinAcc.frequency);\n }",
"function coinCombo(cents) {\n return 'TODO'\n}",
"function addInputCheckbox(switchLabel, coin) {\n let inptSwtch = $(\"<input>\").attr(\"type\", \"checkbox\");\n addEventToSwitch(inptSwtch, coin);\n inptSwtch.appendTo(switchLabel);\n }",
"function collectCoin(player, Coin){\n \tCoinPU.play();\n Coin.kill();\n coinsCollected+=1;\n }",
"takeCoin(player, coin){\n coin.kill();\n }",
"function addPoints() {\n points += pointMulti;\n clickcount++;\n pointsfromclick += pointMulti;\n totalpoints += pointMulti;\n document.getElementById(\"clickcount\").innerHTML = \"You have \" + clickcount + \" total clicks.\";\n document.getElementById(\"pointsfromclick\").innerHTML = \"You have made \" + pointsfromclick + \" bread objects from clicking.\";\n document.getElementById(\"totalpointcount\").innerHTML = \"You have made \" + totalpoints + \" total bread objects.\";\n var pointsArea = document.getElementById(\"pointdisplay\");\n pointsArea.innerHTML = \"You have \" + Math.round(points) + \" bread objects!\";\n if(points >= 1 && buyupgrade === 0) {\n var multiply_button = document.getElementById(\"btn_multiply\");\n multiply_button.style.display = \"inline\";\n }\n }",
"function CoinContainer(props) {\n const [coin, setCoin] = useState(null);\n const [headCount, setHeadCount] = useState(0);\n const [tailCount, setTailCount] = useState(0);\n\n const handleClick = () => {\n const newCoin = choice(props.coins);\n setCoin(newCoin);\n if (newCoin.side === \"head\") {\n setHeadCount(oldCount => oldCount + 1);\n } else {\n setTailCount(oldCount => oldCount + 1);\n }\n };\n\n const currCoin = coin ? (\n <Coin side={coin.side} imgSrc={coin.imgSrc} />\n ) : null;\n\n return (\n <div className=\"CoinContainer\">\n <h2>Let's flip a coin</h2>\n {currCoin}\n <button onClick={handleClick}>Flip Me!</button>\n <p>\n Out of {headCount + tailCount} flips, there have been {headCount} heads\n and {tailCount} tails.\n </p>\n </div>\n );\n}",
"function generateCoinChange(amount){\n let quarters = Math.round(amount / 25)\n amount = amount % 25\n let dimes = Math.round(amount / 10)\n amount = amount % 10\n let nickels = Math.round(amount / 5)\n amount = amount % 5\n pennies = amount\n\n console.log(\n `quarters: ${quarters}`,\n `dimes: ${dimes}`,\n `nickels: ${nickels}`,\n `pennies: ${pennies}`\n )\n}",
"function displayCoins() {\r\n $('.loadIcon').show();\r\n\r\n const coinsAPI = \"https://api.coingecko.com/api/v3/coins/list\";\r\n\r\n $.get(coinsAPI, function (response) {\r\n let objCoins = response;\r\n // let objCoins = JSON.parse(JSON.stringify(response));\r\n const partialCoins = objCoins.slice(1500, 2200);\r\n\r\n let coinsHTML = `<div class=\"cardsContainer\">`;\r\n\r\n $.each(partialCoins, function (i, coin) {\r\n coinsHTML += `<div class=\"card\">\r\n <label class=\"switch\" title=\"select for live reports\">\r\n <input type=\"checkbox\" class=\"checkbox\" name=${coin.name.replace(/\\s+/g, '-').toLowerCase()} onchange=\"toggleSelected(event)\">\r\n <span class=\"slider round\"></span>\r\n </label>\r\n <p class=\"id\">${coin.id}</p>\r\n <p class=\"symbol uppercase\">${coin.symbol}</p>\r\n <p class=\"name\">${coin.name.toLowerCase()}</p> \r\n <div class=\"expander\"></div>\r\n <button class=\"infoBtn\" name=${coin.id} onclick=\"showInfo(event)\">More Info</button>\r\n </div>`;\r\n });\r\n\r\n coinsHTML += '</div>'\r\n\r\n $('.loadIcon').fadeOut();\r\n $('#results').hide().html(coinsHTML).fadeIn(2000);\r\n\r\n });\r\n}",
"makeCoin(){\n for (let i = 0; i < this.numberOfCoins; i++){\n this.randX = Math.floor(random(this.mapSize));\n this.randY = Math.floor(random(this.mapSize));\n if (this.gameMap[this.randY][this.randX] === 0) {this.gameMap[this.randY][this.randX] = 4;}\n else {i--;}\n }\n \n }",
"function coinflip(target, context) {\r\n var coin = Math.floor(Math.random() * 2);\r\n\r\n // Print coin;\r\n if (coin == 0)\r\n sendMessage(target, context, 'The coin landed on Tails');\r\n else if (coin == 1)\r\n sendMessage(target, context, 'The coin landed on Heads');\r\n}",
"function handleIncrease() {\n if (selectedAmount < stockCount) setSelectedAmount(selectedAmount + 1);\n }",
"function getMoneyToBank() {\n if (person.pay !== 0) {\n balance.textContent = `${person.balance += person.pay}kr`\n person.pay = 0;\n pay.textContent = `${person.pay} kr`\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Flattens the raw errors. | errors() {
return ys(this.rawErrors, (e) => e.join(`
`));
} | [
"rawErrors() {\n return p.validationErrors(this.stack);\n }",
"getErrorsAsString() {\n\t\tif (!this.items || !this.items.error || this.items.error.length <= 0) {\n\t\t\treturn \"\";\n\t\t}\n\t\tconst str = this.items.error.join(\". \");\n\t\treturn str;\n\t}",
"function transformAjvErrors() {\n\t var errors = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n\n\t if (errors === null) {\n\t return [];\n\t }\n\n\t return errors.map(function (e) {\n\t var dataPath = e.dataPath,\n\t keyword = e.keyword,\n\t message = e.message,\n\t params = e.params;\n\n\t var property = \"\" + dataPath;\n\n\t // put data in expected format\n\t return {\n\t name: keyword,\n\t property: property,\n\t message: message,\n\t params: params, // specific to ajv\n\t stack: (property + \" \" + message).trim()\n\t };\n\t });\n\t}",
"ensureTransactionErrors(transaction) {\n if (!transaction.results) {\n transaction.results = {};\n }\n if (!transaction.errors) {\n transaction.errors = [];\n }\n\n return transaction.errors;\n }",
"function MultiError(errors)\n\t{\n\t\tmod_assertplus.array(errors, 'list of errors');\n\t\tmod_assertplus.ok(errors.length > 0, 'must be at least one error');\n\t\tthis.ase_errors = errors;\n\t\n\t\tVError.call(this, {\n\t\t 'cause': errors[0]\n\t\t}, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's');\n\t}",
"function widgetChangeErrors(errors) {\n\t\t\treturn shiftArrayErrorsKeys(errors, {\n\t\t\t\tarrayKey: schema.key,\n\t\t\t\tminIndex: indexToRemove,\n\t\t\t\tshouldRemoveIndex: index => index === indexToRemove,\n\t\t\t\tgetNextIndex: index => index - 1,\n\t\t\t});\n\t\t}",
"updateErrors() {\n $('#rbro_style_panel .rbroFormRow').removeClass('rbroError');\n $('#rbro_style_panel .rbroErrorMessage').text('');\n let selectedObj = this.rb.getDataObject(this.selectedObjId);\n if (selectedObj !== null) {\n for (let error of selectedObj.getErrors()) {}\n }\n }",
"_setErrorList (errorList) {\n this.errorList = []\n\n _.toArray(errorList)\n .forEach(fieldSet => this._addErrorList(fieldSet))\n }",
"errorView() {\n var table = this.table;\n var reg = this.getReg();\n return this.singleLine(table, reg.errorFetchingData);\n }",
"updateErrors() {\n $('#rbro_page_break_element_panel .rbroFormRow').removeClass('rbroError');\n $('#rbro_page_break_element_panel .rbroErrorMessage').text('');\n let selectedObj = this.rb.getDataObject(this.selectedObjId);\n if (selectedObj !== null) {\n for (let error of selectedObj.getErrors()) {}\n }\n }",
"function attributesFromErr (err) {\n let n = 0\n const attrs = {}\n const keys = Object.keys(err)\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n if (key === 'stack') {\n continue // 'stack' seems to be enumerable in Node 0.11\n }\n if (key === 'code') {\n continue // 'code' is already used for `error.exception.code`\n }\n\n let val = err[key]\n if (val === null) {\n continue // null is typeof object and well break the switch below\n }\n switch (typeof val) {\n case 'function':\n continue\n case 'object':\n // Ignore all objects except Dates.\n if (typeof val.toISOString !== 'function') {\n continue\n }\n val = val.toISOString()\n }\n attrs[key] = val\n n++\n }\n return n ? attrs : undefined\n}",
"function createTransformError(error: any): string {\n if (error instanceof RelayTransformError) {\n return `Relay Transform Error: ${error.message}`;\n }\n\n const {sourceText, validationErrors} = error;\n if (validationErrors && sourceText) {\n const sourceLines = sourceText.split('\\n');\n return validationErrors\n .map(({message, locations}) => {\n return (\n 'GraphQL Validation Error: ' +\n message +\n '\\n' +\n locations\n .map(location => {\n const preview = sourceLines[location.line - 1];\n return (\n preview &&\n [\n '>',\n '> ' + preview,\n '> ' + ' '.repeat(location.column - 1) + '^^^',\n ].join('\\n')\n );\n })\n .filter(Boolean)\n .join('\\n')\n );\n })\n .join('\\n');\n }\n\n return util.format(\n 'Relay Transform Error: %s\\n\\n%s',\n error.message,\n error.stack,\n );\n}",
"clearAllErrorsInputLayer(){\n for(var i = 0; i < neuralNet.layers[0].neurons.length; i++){\n neuralNet.layers[0].neurons[i].receivedErrors = [];\n neuralNet.layers[0].neurons[i].receivedWeightsError = [];\n }\n }",
"function removeAllErrors() {\n this.select('errorMessageSelector').remove();\n this.select('errorGroupSelector').removeClass(this.attr.errorClass);\n}",
"function flattenBeamMessage(message) {\n\tvar result = '';\n\tif (message.length !== undefined) {\n\t\tif(message.length > 1 ) {\n\t\t\tresult = message.reduce(function (previous, current) {\n\t\t\t\tif (!previous) {\n\t\t\t\t\tprevious = '';\n\t\t\t\t}\n\t\t\t\tif (typeof previous === 'object') {\n\t\t\t\t\tprevious = extractTextFromMessagePart(previous);\n\t\t\t\t}\n\t\t\t\treturn previous + extractTextFromMessagePart(current);\n\t\t\t});\n\t\t} else if(message.length === 1) {\n\t\t\tresult = extractTextFromMessagePart(message[0]);\n\t\t} else {\n\t\t\treturn '';\n\t\t}\n\t} else {\n\t\tresult = message;\n\t}\n\treturn ent.decode(result);\n}",
"function firstMessage(errors) {\n if (!Array.isArray(errors) || errors.length === 0) return null;\n\n var error = errors[0];\n if (error.message) {\n return error.message;\n } else {\n return error;\n }\n}",
"function transformErrors(selector){\r\n\t\r\n\tvar errors = $(selector);\r\n\r\n\t$(errors).each(function() {\r\n\t\t\r\n\t\tvar prev_el = $(this).prev();\r\n\t\tvar content = [];\r\n\t\t\r\n\t\t$(this).find('li').each(function() {\r\n\t\t\tcontent.push($(this).html());\r\n\t\t })\r\n\t\t\r\n\t\t\t$(prev_el).popover({\r\n\t\t\t\t offset: 10,\r\n\t\t\t placement : 'top',\r\n\t\t\t html: 'true',\r\n\t\t\t content : function(){\r\n\t\t\t \t return getErrorHtml(content);\r\n\t\t\t }\r\n\t\t\t}).popover('show');\r\n\t});\r\n\t\r\n\treturn;\r\n\r\n}",
"_getErrors() {\n this._client.lpopAsync(this._queueName + ERRORS_QUEUE_TAG).then((reply) => {\n if (reply === null) {\n this._log('All errors processed');\n this.stop();\n this._closeConnection();\n } else {\n this._log(reply);\n setTimeout(this._getErrors.bind(this), 0);\n }\n }).catch(this._onError);\n }",
"_addErrorList (list) {\n if (_.isArray(list)) {\n list.forEach(message => this.errorList.push(message))\n } else {\n this.errorList.push(list)\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copy longitude, latitude to clipboard | copyLnglat () {
const lnglat = `${this.clickLatlng.lng}, ${this.clickLatlng.lat}`
if (this.copyToClipboard(lnglat)) {
this.showSuccess(this.$t('mapLeftClick.lnglatCopied'), { timeout: 2000 })
}
} | [
"function copyToClipboard() {\n const el = document.createElement('textarea');\n el.value = event.target.getAttribute('copy-data');\n el.setAttribute('readonly', '');\n el.style.position = 'absolute';\n el.style.left = '-9999px';\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n}",
"function copyToClipboard() {\n var el = document.createElement('textarea');\n el.value = loremIpsumText.textContent;\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n}",
"function gui_toClipBoard(text) {\n\tif (typeof text == 'undefined') {text = document.getElementById('html_container').value;}\n\ttry {\n\t\tif (window.clipboardData) {\n\t\t\t// IE send-to-clipboard method.\n\t\t\twindow.clipboardData.setData('Text', text);\n\t\t}\n\t\telse if (typeof air == 'object') {\n\t\t\tair.Clipboard.generalClipboard.clear();\n\t\t\tair.Clipboard.generalClipboard.setData(\"air:text\", text, false);\n\t\t}\n\t}\n\tcatch (err) {\n\t\tmyimgmap.log(\"Unable to set clipboard data\", 1);\n\t}\n}",
"function dc_copy_to_clipboard(div) {\n let copyText = document.getElementById(div).innerText;\n //console.log(copyText);\n /* Copy the text inside the text field */\n navigator.clipboard.writeText(copyText);\n}",
"function copyToClipboard(){\n // It's a little tricky to copy the password to the clipboard without\n // displaying it on screen. These folks suggested just putting it way off\n // the screen instead:\n // https://stackoverflow.com/questions/31593297/using-execcommand-javascript-to-copy-hidden-text-to-clipboard\n\n var passElement=document.createElement(\"input\");\n passElement.style=\"position:absolute; left:-1000px; top:-1000px;\";\n passElement.value=finalPassword;\n // My understanding is that until we call appendChild(), our new element \n // isn't a part of the DOM, and doesn't have a parent at all\n document.body.appendChild(passElement);\n passElement.select();\n document.execCommand('copy');\n\n}",
"function copyToClipboard(info) {\n\t// Get the selected text\n\tvar result = searchOracle(info.selectionText);\n\t// If something was found\n\tif (result != null) {\n\t\t // Copy result to clipboard\n\t\t toClipboard(result);\n // If nothing was returned\n\t} else {\n\t\t// Show error\n\t\talert(\"GIF Not Found\");\n\t}\n}",
"function handlePartsListCopy() {\n var copyText = document.getElementById(\"parts-box\");\n copyText.select();\n copyText.setSelectionRange(0, 99999);\n document.execCommand(\"copy\");\n setShow(true);\n setalertTitle(\"Copied\");\n setalertText(\"Copied the text: \" + copyText.value);\n setalertIcon(\"fas fa-copy mr-3\");\n setalertColor(\"bg-alert-success\");\n }",
"function CopySongData() {\n document.querySelector('#songDataHolder').value = JSON.stringify(songData, null, 2);\n document.querySelector('#songDataHolder').select();\n document.execCommand('copy');\n}",
"function copy()\n{\n var params = arguments;\n var paramsLength = arguments.length;\n var e = params[0];\n var c = params[paramsLength-1];\n if($(e).length < 1)\n {\n var uniqueid = unique_id();\n var textareaId = \"__temp_textarea__\"+uniqueid;\n var element = $(\"<textarea id='\"+textareaId+\"'></textarea>\");\n element.appendTo('body')\n .each(function(){\n $(this).val(e)\n $(this).select()\n })\n }else\n {\n $(e).select();\n }\n\n try {\n var successful = document.execCommand('copy');\n var msg = successful ? 'successful' : 'unsuccessful';\n console.log('Copying text was ' + msg);\n if($(e).length < 1)\n {\n $(this).remove();\n }\n if(typeof c == 'function')\n {\n c()\n }\n } catch (err) {\n console.error('Oops, unable to copy');\n }\n}",
"function copyTextToClipboard() {\n const textarea = document.createElement(\"textarea\");\n textarea.innerHTML = Key;\n textarea.style.display = \"hidden\";\n document.body.appendChild(textarea);\n textarea.focus();\n textarea.select();\n try {\n document.execCommand(\"copy\");\n document.body.removeChild(textarea);\n generatePopUp(\"Key Copied\")\n } catch (err) {\n generatePopUp(`some error happened: ${err}`);\n }\n\n /*other way for copying in clipboard -->\n\n navigator.clipboard\n .writeText(text)\n .then(() => {\n generatePopUp(\"Key Copied\")\n })\n .catch((err) => generatePopUp(`some error happened: ${err}`)); */\n}",
"function copyBattleToClipboard () {\n $('.copy-button').on('click', function() {\n var copy_link = $(this).closest('.copy-modal').find('.copy-link');\n copy_link.focus();\n copy_link.select();\n document.execCommand('copy');\n });\n}",
"copyToClipboard(e){\n e.preventDefault();\n var copyTextarea = document.getElementById('post');\n copyTextarea.select();\n try{\n document.execCommand('copy');\n console.log(\"Post copied succesfully.\");\n }\n catch(err){\n console.log(\"Unable to copy the post. Please, do it manually selecting the text and pressing Crtl + C keys.\");\n console.log(err)\n }\n }",
"function copy(list){\n\t//Empty the background page, add a textarea\n\t$('body').html(\"<textarea></textarea>\");\n\t//For each item in the list, add it to the textarea\n\tfor (var i = 0; i < list.length; i++){\n\t\t$('textarea').append(list[i]);\n\t}\n\t//Select the content to be copied\n\t$('textarea').select();\n\ttry{\n\t\t//Try to cut the data\n\t\tvar success = document.execCommand('cut');\n\t\tif (success){\n\t\t\t//Notify successful cut!\n\t\t\tchrome.notifications.create({'type':'basic','iconUrl':'icon-48.png','title':'Requisitions Copied','message':'Your Halo 5 requisition list has been copied to your clipboard.'});\n\t\t}else{\n\t\t\t//Didn't work, throw an error for the failed message\n\t\t\tthrow 404;\n\t\t}\n\t} catch(err) { \n\t\t//Notify that it failed\n\t\tchrome.notifications.create({'type':'basic','iconUrl':'icon-48.png','title':'Error','message':'Unable to copy the requisition list to your clipboard.'}); \n\t} \n}",
"function copy_json() {\n\tdocument.getElementById(\"json_box\").select();\n\tdocument.execCommand(\"copy\");\n}",
"function copyToClipboard(calendarItemArray) {\n if (!calendarItemArray) {\n calendarItemArray = currentView().getSelectedItems({});\n }\n\n if (!calendarItemArray.length) {\n return false;\n }\n\n let icsSerializer = Components.classes[\"@mozilla.org/calendar/ics-serializer;1\"]\n .createInstance(Components.interfaces.calIIcsSerializer);\n icsSerializer.addItems(calendarItemArray, calendarItemArray.length);\n let icsString = icsSerializer.serializeToString();\n\n let clipboard = getClipboard();\n let trans = Components.classes[\"@mozilla.org/widget/transferable;1\"]\n .createInstance(Components.interfaces.nsITransferable);\n\n if (trans && clipboard) {\n // Register supported data flavors\n trans.addDataFlavor(\"text/calendar\");\n trans.addDataFlavor(\"text/unicode\");\n\n // Create the data objects\n let icsWrapper = Components.classes[\"@mozilla.org/supports-string;1\"]\n .createInstance(Components.interfaces.nsISupportsString);\n icsWrapper.data = icsString;\n\n // Add data objects to transferable\n // Both Outlook 2000 client and Lotus Organizer use text/unicode\n // when pasting iCalendar data.\n trans.setTransferData(\"text/calendar\",\n icsWrapper,\n icsWrapper.data.length * 2); // double byte data\n trans.setTransferData(\"text/unicode\",\n icsWrapper,\n icsWrapper.data.length * 2);\n\n clipboard.setData(trans,\n null,\n Components.interfaces.nsIClipboard.kGlobalClipboard);\n\n return true;\n }\n return false;\n}",
"copyDataListToClipboard() {\n const { dataList } = this.state;\n const cleanList = encounterDataUtils.formatEncounterList(dataList);\n NotificationManager.info('Copied All Data', undefined, 1000);\n copyToClipboard(JSON.stringify(cleanList));\n }",
"function pasteFromClipboard() {\n if (!canPaste()) {\n return;\n }\n\n let clipboard = getClipboard();\n let trans = Components.classes[\"@mozilla.org/widget/transferable;1\"]\n .createInstance(Components.interfaces.nsITransferable);\n\n if (!trans || !clipboard) {\n return;\n }\n\n // Register the wanted data flavors (highest fidelity first!)\n trans.addDataFlavor(\"text/calendar\");\n trans.addDataFlavor(\"text/unicode\");\n\n // Get transferable from clipboard\n clipboard.getData(trans, Components.interfaces.nsIClipboard.kGlobalClipboard);\n\n // Ask transferable for the best flavor.\n let flavor = {};\n let data = {};\n trans.getAnyTransferData(flavor, data, {});\n data = data.value.QueryInterface(Components.interfaces.nsISupportsString).data;\n switch (flavor.value) {\n case \"text/calendar\":\n case \"text/unicode\":\n let destCal = getSelectedCalendar();\n if (!destCal) {\n return;\n }\n\n let icsParser = Components.classes[\"@mozilla.org/calendar/ics-parser;1\"]\n .createInstance(Components.interfaces.calIIcsParser);\n try {\n icsParser.parseString(data);\n } catch(e) {}\n\n let items = icsParser.getItems({});\n if (items.length == 0) {\n return;\n }\n\n // If there are multiple items on the clipboard, the earliest\n // should be set to the selected day and the rest adjusted.\n let earliestDate = null;\n for each (let item in items) {\n let date = null;\n if (item.startDate) {\n date = item.startDate.clone();\n } else if (item.entryDate) {\n date = item.entryDate.clone();\n } else if (item.dueDate) {\n date = item.dueDate.clone();\n }\n\n if (!date) {\n continue;\n }\n\n if (!earliestDate || date.compare(earliestDate) < 0) {\n earliestDate = date;\n }\n }\n let firstDate = currentView().selectedDay;\n\n // Timezones and DT/DST time may differ between the earliest item\n // and the selected day. Determine the offset between the\n // earliestDate in local time and the selected day in whole days.\n earliestDate = earliestDate.getInTimezone(calendarDefaultTimezone());\n earliestDate.isDate = true;\n let offset = firstDate.subtractDate(earliestDate);\n let deltaDST = firstDate.timezoneOffset - earliestDate.timezoneOffset;\n offset.inSeconds += deltaDST;\n\n startBatchTransaction();\n for each (let item in items) {\n let newItem = item.clone();\n // Set new UID to allow multiple paste actions of the same\n // clipboard content.\n newItem.id = cal.getUUID();\n cal.shiftItem(newItem, offset);\n doTransaction('add', newItem, destCal, null, null);\n }\n endBatchTransaction();\n break;\n default:\n break;\n }\n}",
"function copyEmail() {\n const email = document.querySelector(\"#contact-email\");\n const copyText = document.createElement(\"textarea\");\n copyText.value = email.textContent.replace(/\\s/g, \"\");\n copyText.style.position = \"fixed\";\n\n document.body.appendChild(copyText);\n copyText.focus();\n copyText.select();\n\n try {\n var successful = document.execCommand(\"copy\");\n if (!successful) {\n console.log(\"Error while copying\");\n }\n } catch (err) {\n console.log(\"Error while copying\");\n }\n document.body.removeChild(copyText);\n}",
"function textArea(){\r\n\tvar text = document.getElementById(\"info\").value;\r\n\tvar splitValue = [];\r\n\tsplitValue = text.split(\"\\n\");\r\n\timportLatLng(splitValue);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a sign depending on the charge. | function getSign(charge) {
if (charge > 0) {
return '+';
} else if (charge < 0) {
return '-';
}
return '0';
} | [
"function charge(d) {\n return -Math.pow(d.radius, 2.0) / 8;\n }",
"function signTest() {\n var signFlag1 = (numbers[0].indexOf('-') !== -1); //true if there, false if not there\n var signFlag2 = (numbers[1].indexOf('-') !== -1);\n \n //If numerator and denominator are both negative, or both positive, return empty string\n if (signFlag1 === true && signFlag2 === true || signFlag1 === false && signFlag2 === false) {\n return '';\n //Otherwise, one of them is negative, return a negative sign\n } else {\n return '-';\n };\n }",
"function hash2sign(h, k){ return bytes2hex(bigInt2ECKey(hex2bigInt(k)).sign(hex2bytes(h))); }",
"function buildBikeSign(scene, posX, posZ, rotation) {\n\n width = 0.5;\n height = 20;\n depth = 0.5;\n radius = 4;\n \n postGeometry = new THREE.PlaneGeometry(width, height - radius);\n postMaterial = new THREE.MeshPhongMaterial({color: 0xbfbfbf, shininess: 100});\n\n //post of the sign (metal like plane)\n post = new THREE.Mesh( postGeometry, postMaterial );\n post.position.x = posX;\n post.position.y = (height - radius)/2;\n post.position.z = posZ;\n post.rotation.y += rotation;\n post.material.side = THREE.DoubleSide;\n scene.add(post);\n\n //Textured circle with bike logo\n circleGeometry = new THREE.CircleGeometry( radius, 32 );\n textureSign = new THREE.TextureLoader().load( 'textures/bikeSign.png' );\n materialSign = new THREE.MeshPhongMaterial( { map: textureSign, shininess:10 } );\n sign = new THREE.Mesh( circleGeometry, materialSign );\n sign.position.x = posX;\n sign.position.y = height;\n sign.position.z = posZ;\n sign.rotation.y += rotation;\n sign.material.side = THREE.DoubleSide;\n scene.add(sign);\n}",
"function getSurcharge(totalCar)\n {\n let surcharge = 0;\n if (document.getElementById(\"age25\").checked)\n {\n surcharge = totalCar * 1.3\n }\n\n return surcharge;\n }",
"function buildBikeSigns(scene) {\n buildBikeSign(scene, -110, 0, 0);\n buildBikeSign(scene, -110, -400, 0);\n buildBikeSign(scene, -110, 400, 0);\n\n buildBikeSign(scene, 60, 0, 0);\n buildBikeSign(scene, 60, 400, 0);\n buildBikeSign(scene, 60, -400, 0);\n}",
"function getPay(isCustomer) {\n return isCustomer ? \"$5.0\" : \"$7.0\";\n}",
"displayCharge() {\n push();\n if (this.chargeEmpty === true) {\n this.charge += .5 * this.maxCharge / 100;\n this.charge = constrain(this.charge, 0, this.maxCharge);\n laserCharging.playMode('untilDone');\n laserCharging.play();\n }\n if (this.charge === this.maxCharge) {\n this.chargeEmpty = false;\n laserCharging.stop();\n }\n textAlign(CENTER, CENTER);\n textSize(width * 1 / 100);\n fill(100, 255, 255);\n text(\"CHARGE\", width / 2 + 37.5, height - this.charge - 10);\n rectMode(CORNERS);\n fill(100, 255, 255, 150);\n strokeWeight(7);\n stroke(100, 255, 255, 150);\n rect(width / 2 + 25, height, width / 2 + 50, height - this.charge);\n pop();\n }",
"charge(payee, amt){\n if (this.balance()< amt){\n return;\n// This is overdraft protection. It basically says that if the charge issued\n// to the account is greater than the account balance then do not allow the \n// charge to process. \n }\n let charge = new Transaction (-amt, payee)\n// charge is using the same structure of deposit however its taking on the negative\n// of the amount value and a payee.\n\n this.transactions.push(charge)\n// In the same manner as the deposit. We are taking in the charge method, and pushing\n// our inputs to the end of the transactions array\n}",
"function reserveGas(cuFt)\n{\n var reserveGas = 0.0;\n var gasRule = document.querySelector('input[name=\"GasRule[]\"]:checked');\n\n if (gasRule) {\n switch (gasRule.value) {\n default:\n case \"All\":\n break;\n case \"Half\":\n reserveGas = cuFt;\n break;\n case \"Thirds\":\n reserveGas = cuFt * 2.0;\n break;\n }\n }\n return(reserveGas);\n}",
"function getRefund() {\n const tempVal = Math.min(credits - taxBill, 1000);\n const refund = tempVal + withholdings;\n return refund;\n }",
"function getCurrencyConvertSpeech(intent, stock) {\n switch (intent) {\n case \"get_share_price\":\n return \"The share price of \" + stock + \" is \";\n default:\n return null;\n }\n }",
"async function sign(message, key) {\n if (typeof message === 'string') {\n message = stringToBuffer(message)\n }\n const hashPoint = await bls.PointG2.hashToCurve(message)\n return bufferToBigInt(hashPoint.multiply(new math.Fq(key)).toSignature())\n}",
"function insertSign(value, sign) {\n return value + (sign ? '-' : ' ');\n }",
"eth_sign(address, message) {\n return this.request(\"eth_sign\", Array.from(arguments));\n }",
"sign(privateKey) {\n // encrypts the private key calling getNodePrivateKey on Wallet instance\n const cert = wallet.getNodePrivateKey(this.from, privateKey);\n /*\n createSign creates and returns a Sign object that uses the given algorithm(SHA256).\n .update updates the hash content with the given data which are the signed with cert in hex base.\n */\n const signature = createSign('SHA256').update(this.hash()).sign(cert, 'hex');\n // creates a transaction updating the hash and adding the signature\n return new Transaction({...this, signature});\n }",
"function SingleUseAuthCapture(card, order) {\n var dfd = $q.defer();\n var token = OrderCloud.Auth.ReadToken();\n var cc = {\n \"buyerID\": OrderCloud.BuyerID.Get(),\n \"orderID\": order.ID,\n \"transactionType\": \"authOnlyTransaction\",\n \"amount\": order.Total,\n \"cardDetails\": {\n \"paymentID\": null,\n \"creditCardID\": null,\n \"cardType\": card.CardType,\n \"cardNumber\": card.CardNumber,\n \"expirationDate\": card.ExpMonth + card.ExpYear,\n \"cardCode\": card.CVV\n }\n };\n //authorize payment\n $resource(authorizeneturl, {}, {authorize: {method: 'POST', headers: {'Authorization': 'Bearer ' + token, 'Content-type': 'application/json'}}}).authorize(cc).$promise\n .then(function(response){\n if(response.messages && response.messages.resultCode && response.messages.resultCode == 'Error') {\n toastr.info('Sorry, something went wrong. Please try again');\n } else if(response.Error) {\n toastr.info('Sorry, something went wrong. Please try again');\n } else {\n cc = {\n \"buyerID\": OrderCloud.BuyerID.Get(),\n \"orderID\": order.ID,\n \"transactionType\": \"priorAuthCaptureTransaction\",\n \"amount\": order.Total,\n \"cardDetails\": {\n \"paymentID\": response.PaymentID,\n \"creditCardID\": null,\n \"cardType\": null,\n \"cardNumber\": null,\n \"expirationDate\": null,\n \"cardCode\": null\n }\n };\n //capture payment\n $resource(authorizeneturl, {}, {authorize: {method: 'POST', headers: {'Authorization': 'Bearer ' + token, 'Content-type': 'application/json'}}}).authorize(cc).$promise\n .then(function(){\n if(response.messages && response.messages.resultCode && response.messages.resultCode == 'Error') {\n toastr.info('Sorry, something went wrong. Please try again');\n } else if(response.Error) {\n toastr.info('Sorry, something went wrong. Please try again');\n }\n dfd.resolve();\n })\n .catch(function(){\n toastr.info('Sorry, something went wrong. Please try again')\n dfd.resolve();\n });\n }\n })\n .catch(function(){\n toastr.info('Sorry, something went wrong. Please try again')\n });\n return dfd.promise;\n }",
"function canIGetADrivingLicense(age) {\n if (age >= 20) {\n var result = \" yes you can\"\n return result\n } else {\n var x = 20 - age;\n var result = \"please come back after \" + x + \" years to get one\"\n return result\n }\n}",
"function calculateGST(gstId, unitPrice, quantity) {\n const gstObj = newSlab.GST_SLAB.find(gst => gst.id === gstId);\n if (gstObj) {\n return ((unitPrice * gstObj.rate) / 100) * quantity;\n }\n else {\n throw (\"GST_SLAB not found\");\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to be called by clicking on buttons for setting the duration. Accepts a number of minutes or a string. | function setDuration (minutes) {
// sets etaDuration to passed in value
etaDuration = minutes;
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].classList.remove('active');
}
document.getElementById('button'+minutes).classList.add("active");
} | [
"function increaseDuration() {\n let maxDuration = 4; // MODDABLE\n let durationDisplay = $(\"selectedDuration\");\n let duration = parseInt(durationDisplay.textContent);\n if (duration < maxDuration) {\n let hr = parseInt($(\"selectedHour\").textContent);\n // if no hour is selected then there is no problem updating duration\n if (isNaN(hr)) {\n durationDisplay.textContent = duration + 1 + \" hour(s) long\";\n } else { // hour is selected, make sure it works with the duration\n // convert hr to 0-23\n if ($(\"selectedHour\").textContent.split(\" \")[1] == \"PM\") {\n if (hr == 12) {\n hr = 0;\n }\n hr += 12;\n } else {\n if (hr == \"12\") {\n hr = 0;\n }\n }\n if (hr + duration + 1 <= parseInt(normalHours.start) + parseInt(normalHours.num_hours)) {\n durationDisplay.textContent = (duration + 1) + \" hour(s) long\";\n }\n }\n }\n }",
"function decreaseDuration() {\n let durationDisplay = $(\"selectedDuration\");\n let duration = parseInt(durationDisplay.textContent);\n if (duration > 1) {\n durationDisplay.textContent = (duration - 1) + \" hour(s) long\";\n }\n }",
"callDurationCalculator(duration){\n let totalSeconds = parseInt(duration); \n let minute = 0;\n if(totalSeconds < 60){\n return duration+' seconds';\n }else{\n while(totalSeconds > 60){\n minute += 1; \n totalSeconds -= 60\n }\n\n let _duration = minute+':'+totalSeconds+ ' seconds';\n return(_duration);\n }\n }",
"function onDurationChange(e) {\n var newDuration = Math.floor(video.duration);\n if (newDuration != durInt) {\n durInt = newDuration;\n dur_str = \" / \" + toTimeString(durInt);\n updateTimeBar();\n }\n}",
"changeMinuteSelection(e) {\n e.preventDefault();\n\n StateManager.UpdateValue(\"UI.FeedRecorder.SelectedMinute\", parseInt(e.target.innerText));\n StateManager.ResetModal();\n\n }",
"increaseTime() {\r\n this.duration += 1;\r\n }",
"function updateDuration() {\n\tconst deltaS = (dateInput(\"dateEnd\") + timeInput(\"timeEnd\") - (dateInput(\"dateStart\") + timeInput(\"timeStart\"))) / 1000;\n\tconst round = 3600 / parseInt(ele(\"timeResolutionsInput\").value);\n\tconst duration = Math.ceil(deltaS / round) * round;\n\tconst hours = Math.floor(duration / 3600);\n\tconst minutes = Math.floor((duration - hours * 3600) / 60);\n\tconst seconds = Math.floor(duration - hours * 3600 - minutes * 60);\n\tele(\"duration\").innerText = `${hours}:${pad(minutes, 2)}:${pad(seconds, 2)}`;\n}",
"set duration(val) {\n this.timestamp.end = new Date(this.timestamp.start);\n this.timestamp.end.setHours(this.timestamp.end.getHours()+val);\n }",
"function validate_minutes(element){\n if (element.value <_MIN_MINUTES){\n element.value=_MIN_MINUTES;\n }\n\n if (element.value > _MAX_MINUTES){\n element.value=_MAX_MINUTES;\n }\n}",
"function setTimer()\n{\n\tvar value = document.getElementById('timer').value;\n\ttimer = value * 1000;\n}",
"handleSitClick(e) {\n const newSitTime = this.props.SitTime;\n\n switch (e.target.id) {\n case \"Sit-increment\":\n newSitTime.add(1, 'minutes');\n break;\n case \"Sit-decrement\":\n newSitTime.subtract(1, 'minutes');\n break;\n default:\n break;\n }\n\n\n if (this.props.SitTime.get('minutes') < 0) {\n this.props.SitTime.add(1, 'minutes')\n }\n\n\n this.props.changeSitTime(newSitTime); \n }",
"onDecreaseMinute() {\n\t\tconst { hour, minute, minStep } = this.state;\n\t\tconst minDecreased = minute - minStep;\n\n\t\tlet inputValue = this.getValue(hour, minDecreased);\n\n\t\tif (minDecreased >= 0) {\n\t\t\tthis.setState({\n\t\t\t\tminute: minDecreased,\n\t\t\t\tinputValue\n\t\t\t});\n\t\t} else {\n\t\t\tinputValue = this.getValue(hour, 60 - minStep);\n\n\t\t\tthis.setState({\n\t\t\t\tminute: 60 - minStep,\n\t\t\t\tinputValue\n\t\t\t});\n\t\t}\n\t}",
"displayMinuteSelection(e) {\n e.preventDefault();\n\n let options = [];\n for (let i = 0; i < 60; i += 5) {\n let className = \"\";\n if (i <= StateManager.GetFeedRecorderData().SelectedMinute && i > (StateManager.GetFeedRecorderData().SelectedMinute - 5)) className = \"selected\";\n options.push(\n <button\n key={\"minute-\" + i}\n className={FormatCssClass(className)}\n onClick={this.changeMinuteSelection}\n >{i.toString().padStart(2, \"0\")}</button>\n )\n }\n\n let modalContent = (\n <div className={FormatCssClass(\"options-minute\")}>\n {options}\n </div>\n );\n\n StateManager.UpdateValue(\n \"UI.SelectedModalData\",\n {\n AllowDismiss: true,\n Content: modalContent\n }\n );\n\n }",
"function setMaxsec(){\n\tmaxsec = $(\"#audio-player\")[0].duration;\n\t$(\"#maxsec\").text(timeConvert(maxsec));\n changeWaveLength();\n audioPlay();\n}",
"function setTimeLeft(min, sec) {\n chrome.storage.local.set({ timeLeft: { minutes: min, seconds: sec } });\n}",
"function showTrackDuration(audioId) {\n var oO = \"\";\n if((document.getElementById(audioId).duration % 60) < 10) {\n oO = \"0\";\n }\n var dur = document.getElementById(audioId).duration;\n var mins = Math.floor(dur / 60);\n var secs = Math.floor(dur % 60);\n document.getElementById(\"track1Duration\").innerHTML = mins + \":\" + oO + secs;\n}",
"function changeToMinutes(movie) {\n var minutes = 0;\n var hours = 0;\n\n var partition = movie.duration.split(\" \");\n if (movie.duration.includes(\"h\") && movie.duration.includes(\"min\")) {\n hours = parseInt(partition[0]);\n minutes = parseInt(partition[1]);\n } else if (movie.duration.includes(\"min\")) {\n minutes = parseInt(partition[0]);\n } else {\n hours = parseInt(partition[0]);\n }\n\n return hours * 60 + minutes;\n}",
"static calculateDuration (duration) {\n let seconds = duration * 15\n let days = Math.floor(seconds / (3600 * 24))\n seconds -= days * 3600 * 24\n let hrs = Math.floor(seconds / 3600)\n seconds -= hrs * 3600\n let mnts = Math.floor(seconds / 60)\n seconds -= mnts * 60\n const response = days + ' days, ' + hrs + ' Hrs, ' + mnts + ' Minutes, ' + seconds + ' Seconds'\n return response\n }",
"setDefaultInterpolationTime(duration) {\n this.timedRot .default_duration = duration;\n this.timedPan .default_duration = duration;\n this.timedzoom.default_duration = duration;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the etag header if an entity was found. | function setEtag (ctx, entity, options) {
if (!entity) return
ctx.res.set('ETag', calculate(entity, options))
} | [
"function doesEtagMatch (request, response) {\n const etag = response.getHeader('etag')\n if (!etag) return false\n const target = request.getHeader('if-none-match')\n if (!target) return false\n return etag === target\n}",
"function ETagStream() {\n\n // Call super constructor.\n stream.Writable.call( this );\n\n // I hold the ETag after it has been generated.\n this._etag = null;\n\n // I build the content digest, one chunk at a time.\n this._hasher = crypto.createHash( \"md5\" );\n\n this._destroyed = false;\n\n // Listen for the finish event - once the incoming pipe closes the stream, we'll know\n // that we have all the information we need (or can get) to generate the message\n // digest that is the ETag hash.\n this.once( \"finish\", this._handleFinish.bind( this ) );\n\n}",
"setHeader(key, value) {\n this._headers[key] = value\n }",
"update() {\r\n this.updateHeader();\r\n }",
"update(id, entity, config) {\n const url = this.resolveUrl(config, id);\n const method = (config && config.method) || this.getHttpMethod(HttpMethod.PUT);\n this.loader.dispatch({\n method,\n loading: true,\n entityId: id,\n storeName: this.store.storeName,\n });\n const configWithBody = Object.assign(Object.assign({}, config), { body: entity });\n return this.http.request(method, url, configWithBody).pipe(mapResponse(config), tap((responseEntity) => {\n if (!config || (config && !config.skipWrite)) {\n this.store.update(id, responseEntity);\n }\n this.dispatchSuccess({\n method,\n payload: responseEntity,\n successMsg: config && config.successMsg,\n });\n }), catchError((error) => this.handleError(method, error, config && config.errorMsg)), finalize(() => {\n this.loader.dispatch({\n method,\n loading: false,\n entityId: id,\n storeName: this.store.storeName,\n });\n }));\n }",
"function updateEsRecord(data) {\n esClient.search({\n index: 'products',\n body: {\n query : {\n term: { \"id\" : data.id }\n }\n }\n }).then(found => {\n \n console.log('Found item: ', found.hits.hits[0]._id);\n\n if(found){\n esClient.update({\n index: 'products',\n id: found.hits.hits[0]._id,\n body: {\n doc: {\n id: data.id,\n title: data.title,\n description: data.description\n }\n }\n })\n .then(response => {\n console.log('Updated successfully.');\n })\n .catch(err => {\n console.log('Update error: ' +err);\n })\n }\n })\n .catch(err => {\n console.log('Not found Error: '+ err);\n });\n}",
"function updateItemToList(item)\n{\n return jQuery.ajax({\n url: item.__metadata.uri,\n type: \"POST\",\n contentType: \"application/json;odata=verbose\",\n data: JSON.stringify(item),\n headers: {\n \"Accept\": \"application/json;odata=verbose\",\n \"X-HTTP-Method\": \"MERGE\",\n \"If-Match\": item.__metadata.etag\n }\n });\n}",
"isUpdated(metadata) {\n const newTimestamp = moment.utc(metadata.updatedTimestamp).toDate();\n\n /* Normalize these to null, if undefined or empty. */\n const newETag = metadata.etag || null;\n const entryETag = this.get('etag') || null;\n\n return (newTimestamp > this.get('updatedTimestamp') ||\n newETag !== entryETag);\n }",
"function setContentDispositionHeader(res, type, name, size, altname) {\n if (name != null) { name = require('path').basename(name).split('\\\\').join('').split('/').join('').split(':').join('').split('*').join('').split('?').join('').split('\"').join('').split('<').join('').split('>').join('').split('|').join('').split('\\'').join(''); } else { name = altname; }\n try {\n var x = { 'Cache-Control': 'no-store', 'Content-Type': type, 'Content-Disposition': 'attachment; filename=\"' + encodeURIComponent(name) + '\"' };\n if (typeof size == 'number') { x['Content-Length'] = size; }\n res.set(x);\n } catch (ex) {\n var x = { 'Cache-Control': 'no-store', 'Content-Type': type, 'Content-Disposition': 'attachment; filename=\"' + altname + '\"' };\n if (typeof size == 'number') { x['Content-Length'] = size; }\n try { res.set(x); } catch (ex) { }\n }\n }",
"respondWithEntity(res, statusCode = 200) {\n return (entity) => {\n if (entity) {\n return res.status(statusCode).json(entity);\n }\n return null;\n };\n }",
"function setExpiresAt() {\n if (!service.token) {\n return;\n }\n if (typeof (service.token.expired_in) !== 'undefined' && service.token.expired_in !== null) {\n var expires_at = new Date();\n expires_at.setSeconds(expires_at.getSeconds() + parseInt(service.token.expired_in) - 60); // 60 seconds less to secure browser and response latency\n service.token.expires_at = expires_at;\n }\n else {\n service.token.expires_at = null;\n }\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 setHeaderWithToken() {\n var cookie = $.cookie(\"accessToken\");\n\n $(document).ajaxSend(function (event, jqxhr, settings) {\n jqxhr.setRequestHeader('Authorization', 'bearer ' + cookie);\n });\n }",
"GetEntityPosition( entity ) { return null; }",
"function emlFileOnload(docObj) {\n var loc = docObj.location;\n if (loc.hash) {\n var line = loc.hash.substring(1);\n hiliteEmlLine(docObj, line);\t\t \n }\t\n}",
"function setHeaderProp(name, value) {\n _HEADER[name] = value;\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}",
"async _fetchWrite( fd, offset, length ) { \n const res = await fetch( this.URL, { headers: {\n 'range': `bytes=${offset}-${offset+length}`,\n 'Authorization': `Bearer ${this.token}`\n }});\n if (res.status != 206) \n throw(`error:${res.statusText}, bytes=${offset}-${offset+length}`)\n const buff = await res.buffer();\n fs.writeSync(fd, buff, 0, buff.length, offset);\n return res.status;\n }",
"async function edit(req, res, next) {\n try {\n const { albumId } = req.params\n const album = await Album.findById(albumId)\n if (!album) {\n throw new NotFound(`Album with id: ${albumId} does not exist.`)\n }\n if (!req.currentUser.equals(album.user._id)) {\n throw new NotAuthorized(`Album with id: ${albumId} does not belong to ${req.currentUser.username}`)\n }\n await Album.updateOne({ '_id': albumId }, req.body)\n if (album.nModified < 1) {\n return res.sendStatus(304)\n }\n res.status(200).json(await Album.findById(albumId))\n\n } catch (err) {\n next(err)\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Concatenate a 2D source of sources, returning a new accumulatable 1D source where items are ordered by source order. concat([[1, 2, 3], ['a', 'b', 'c']]) >> | function concat(source) {
return accumulatable(function accumulateConcat(next, initial) {
function nextAppend(a, b) {
if(b === end) return accumulate(a, next, initial);
return a === null ? b : append(a, b);
}
accumulate(source, nextAppend, null);
});
} | [
"function Concatenate() {\n var attrs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n _classCallCheck(this, Concatenate);\n\n var _this = _possibleConstructorReturn(this, (Concatenate.__proto__ || Object.getPrototypeOf(Concatenate)).call(this, attrs));\n\n _this.layerClass = 'Concatenate';\n\n _this.mode = 'concat';\n\n var _attrs$axis = attrs.axis,\n axis = _attrs$axis === undefined ? -1 : _attrs$axis;\n\n // no mini-batch axis here, so we subtract 1 if given axis > 0\n\n _this.concatAxis = axis <= 0 ? axis : axis - 1;\n\n // GPU setup\n if (_this.gpu) {\n _this.mergeProgram = _WebGL.webgl2.compileProgram(require('./Concatenate.webgl2.glsl'));\n }\n return _this;\n }",
"function concat(...params) {\n return output(params).apply((array) => array.join(\"\"));\n}",
"function combine(arr1, arr2){\n return arr1.concat(arr2).sort()\n}",
"function mergeArrays(sequence, added, compFunc, startPos)\n{\n if(!startPos)\n startPos = 0;\n \n var modPos = startPos;\n var addedLength = added.length;\n var addedPos = 0;\n var nextSeq = sequence;\n var nextLength = sequence.length;\n var nextPos = modPos;\n var buffer = []; // buffer for elements pushed to the end of the sequence\n \n while(nextPos < nextLength || addedPos < addedLength) {\n\n if(nextPos == nextLength && nextSeq != sequence) {\n nextPos = modPos;\n nextSeq = sequence;\n nextLength = sequence.length;\n }\n \n if(nextPos < nextLength && nextSeq[nextPos] == undefined) {\n nextPos++;\n continue;\n }\n if(addedPos < addedLength && added[addedPos] == undefined) {\n addedPos++;\n continue;\n }\n \n if(addedPos == addedLength ||\n (nextPos < nextLength && \n compFunc(nextSeq[nextPos], added[addedPos]) <= 0)) {\n // next element from the 'nextSeq' array, could be the\n // sequence itself.\n if(nextSeq != sequence || modPos != nextPos) {\n var entry;\n if(entry = sequence[modPos]) {\n // store to be re-inserted later\n nextSeq.push(entry);\n nextLength++;\n }\n sequence[modPos] = nextSeq[nextPos];\n nextSeq[nextPos] = undefined;\n }\n nextPos++;\n } else { // next element from the 'added' array\n var entry;\n if(entry = sequence[modPos]) {\n // store to be re-inserted later\n if(nextSeq == sequence) {\n nextSeq = buffer;\n nextPos = 0;\n nextLength = 1;\n nextSeq.push(entry);\n } else {\n nextSeq.push(entry);\n nextLength++;\n }\n }\n sequence[modPos] = added[addedPos];\n addedPos++;\n }\n modPos++;\n }\n \n if(modPos < sequence.length)\n sequence.length = modPos;\n}",
"static concatTypedArrays(a, b) {\n const c = new (a.constructor)(a.length + b.length);\n c.set(a, 0);\n c.set(b, a.length);\n return c;\n }",
"function joinArrays(){\n var newArr = [...arguments];\n\tvar ret = [];\n\tnewArr.forEach(el => ret.push(...el));\n\treturn ret;\n}",
"function pushArray(thisArg, src) {\n if (!(src instanceof Array)) {\n thisArg.push(src);\n return;\n }\n src.forEach(function (item) {\n thisArg.push(item);\n });\n }",
"function mergeArrays(arr1, arr2){\n \n const merged = arr1.concat(arr2);\n \n return merged;\n\n}",
"function joinArrays(...args){\n\tlet res = [];\n\tfor (let i of args) res.push(...i);\n\treturn res;\n}",
"combineResults(prev, next = []) {\n return prev.concat(next)\n }",
"function appendConnectedNodes(sourceNodes) {\n var tempSourceNodes = [];\n // first we make a copy of the nodes so we do not extend the array we loop over.\n for (var i = 0; i < sourceNodes.length; i++) {\n tempSourceNodes.push(sourceNodes[i])\n }\n\n for (i = 0; i < tempSourceNodes.length; i++) {\n var nodeId = tempSourceNodes[i];\n if (sourceNodes.indexOf(nodeId) == -1) {\n sourceNodes.push(nodeId);\n }\n var connectedNodes = graph.getConnectedNodes(nodeId);\n addUnique(connectedNodes, sourceNodes);\n }\n tempSourceNodes = null;\n}",
"function CONCATENATE() {\n for (var _len4 = arguments.length, values = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n values[_key4] = arguments[_key4];\n }\n\n // Combine into a single string value\n return values.reduce(function (acc, item) {\n return \"\" + acc + item;\n });\n}",
"function concat(generator1, generator2){\n\treturn function (){\n\t\tvar gen1 = generator1();\n\t\tif (gen1 !== undefined){\n\t\t\treturn gen1;\n\t\t}\n\t\telse{\n\t\t\tvar gen2 = generator2();\n\t\t\treturn gen2;\n\t\t}\n\t};\n}",
"function merge(x, y, len_x) {\n // cnt is number of out of order triples\n // res is the new sorted array(each element is tri)\n // x and y are going to be combined\n // len_x is number of elements that have not been added to the new array\n // used_y is number of elements that have been added to the new array\n function helper(cnt, res, x, y, len_x, used_y) {\n if(is_empty_list(x) && is_empty_list(y)) {\n return pair(cnt, res);\n } else if(is_empty_list(x)) {\n const yy = head(y);\n const num_y = head(yy);\n const lf_y = head(tail(yy));\n const rt_y = tail(tail(yy));\n return helper(cnt, append(res, list(tri(num_y,\n lf_y,\n rt_y))), \n x, tail(y), len_x, used_y + 1);\n } else if(is_empty_list(y)) {\n const xx = head(x);\n const num_x = head(xx);\n const lf_x = head(tail(xx));\n const rt_x = tail(tail(xx));\n return helper(cnt + lf_x * used_y, \n append(res, list(tri(num_x, \n lf_x,\n rt_x + used_y))), \n tail(x), y, len_x - 1, used_y);\n } else {\n const xx = head(x);\n const yy = head(y);\n const num_x = head(xx);\n const num_y = head(yy);\n const lf_x = head(tail(xx));\n const rt_x = tail(tail(xx));\n const lf_y = head(tail(yy));\n const rt_y = tail(tail(yy));\n if(num_x <= num_y) {\n return helper(cnt + lf_x * used_y, \n append(res, list(tri(num_x, \n lf_x,\n rt_x + used_y))), \n tail(x), y, len_x - 1, used_y);\n } else {\n return helper(cnt + len_x * rt_y,\n append(res, list(tri(num_y,\n len_x + lf_y,\n rt_y))), \n x, tail(y), len_x, used_y + 1);\n }\n }\n }\n return helper(0, [], x, y, len_x, 0);\n }",
"function concatenar() {\n return src(\"./css/*\")\n .pipe(concat(\"final.css\"))\n .pipe(dest(\"./css/\"));\n}",
"function collect(s1, s2) {\n for (let elem of s2) {\n s1.add(elem);\n }\n}",
"function combine(){\n var array = []\n for (i=3;i<process.argv.length;i++) {\n array.push(process.argv[i]);\n }\n return array.join(\"+\");\n }",
"function update_arr(dest, key, data, keys, context)\n{\n // The 'add' instruction is set. This means to take the data and add it onto a new array node \n if (key.add) {\n if (data !== null && typeof data !== 'undefined') {\n dest = dest || []\n dest.push(applyTransform(data,dest,context))\n // dest = dest.concat(data)\n }\n return dest\n }\n\n // Just update a single array node\n if (key.ix !== '') {\n return update_arr_ix(dest, key.ix, applyTransform(data,dest,context), keys, context)\n }\n\n // If the data is in an array format then make sure that there is a dest index for each data index\n if (Array.isArray(data)) {\n dest = dest || []\n // Loop through each index in the data array and update the destination object with the data\n dest = data.reduce(function(dest,d,i) {\n // If the instruction is to update all array indices ('') or the current index, update the child data element. Otherwise, don't bother\n if (key.ix == '' || key.ix == i) {\n return update_arr_ix(dest, i, applyTransform(d,dest,context), keys.slice(), context)\n }\n }, dest)\n\n return dest\n }\n\n // Set the specific array index with the data\n else \n return update_arr_ix(dest, '0', data, keys, context)\n}",
"function concat_maybe(xs) /* forall<a> (xs : list<maybe<a>>) -> list<a> */ {\n return concat(map_5(xs, list_3));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one. | multiply(otherVector) {
return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
} | [
"multiplyToRef(otherVector, result) {\n return result.copyFromFloats(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);\n }",
"clone() {\n return new Vector4(this.x, this.y, this.z, this.w);\n }",
"multiplyToRef(q1, result) {\n const x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;\n const y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;\n const z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;\n const w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;\n result.copyFromFloats(x, y, z, w);\n return this;\n }",
"static Add(vector1, vector2) {\n return new Vector4(vector1.x, vector1.y, vector1.z, vector1.w).addInPlace(vector2);\n }",
"add(otherVector) {\n return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);\n }",
"multiply(otherVector) {\n return new Vector2(this.x * otherVector.x, this.y * otherVector.y);\n }",
"multiplyInPlace(q1) {\n this.multiplyToRef(q1, this);\n return this;\n }",
"multiplyByFloats(x, y, z, w) {\n return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);\n }",
"function Vector4(/** x value of the vector */x,/** y value of the vector */y,/** z value of the vector */z,/** w value of the vector */w){this.x=x;this.y=y;this.z=z;this.w=w;}",
"multv(v) {\n // check column must match vector's row count\n if (this.n !== v.m) {\n console.error('matrix column must match vector\\'s row count')\n return undefined\n }\n // check if v is a vector\n if (v.n !== 1) {\n console.error(v, 'is not a vector')\n return undefined\n }\n const C = []\n let rn = []\n for (let i=1; i<=this.m; i++) {\n let n = 0\n for (let j=1; j<=this.n; j++) {\n n += this.at(i,j)*v.at(j,1)\n }\n C.push([n])\n }\n return new Matrix(C)\n }",
"addToRef(otherVector, result) {\n return result.copyFromFloats(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);\n }",
"projection(other_vector) {}",
"static vConv(a,b) { return newVec(a.x*b.x,a.y*b.y,a.z*b.z); }",
"static vAdd(a,b) { return newVec(a.x+b.x,a.y+b.y,a.z+b.z); }",
"divide(otherVector) {\n return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);\n }",
"multiply(matrix)\n\t{\n\t\tif (matrix != null && matrix instanceof FourMatrix)\n\t\t{\n\t\t\tvar ret = new FourMatrix();\n\n\t\t\tret._data[0][0] = this._data[0][0] * matrix._data[0][0] + this._data[0][1] * matrix._data[1][0] + this._data[0][2] * matrix._data[2][0] + this._data[0][3] * matrix._data[3][0];\n\t\t\tret._data[0][1] = this._data[0][0] * matrix._data[0][1] + this._data[0][1] * matrix._data[1][1] + this._data[0][2] * matrix._data[2][1] + this._data[0][3] * matrix._data[3][1];\n\t\t\tret._data[0][2] = this._data[0][0] * matrix._data[0][2] + this._data[0][1] * matrix._data[1][2] + this._data[0][2] * matrix._data[2][2] + this._data[0][3] * matrix._data[3][2];\n\t\t\tret._data[0][3] = this._data[0][0] * matrix._data[0][3] + this._data[0][1] * matrix._data[1][3] + this._data[0][2] * matrix._data[2][3] + this._data[0][3] * matrix._data[3][3];\n\n\t\t\tret._data[1][0] = this._data[1][0] * matrix._data[0][0] + this._data[1][1] * matrix._data[1][0] + this._data[1][2] * matrix._data[2][0] + this._data[1][3] * matrix._data[3][0];\n\t\t\tret._data[1][1] = this._data[1][0] * matrix._data[0][1] + this._data[1][1] * matrix._data[1][1] + this._data[1][2] * matrix._data[2][1] + this._data[1][3] * matrix._data[3][1];\n\t\t\tret._data[1][2] = this._data[1][0] * matrix._data[0][2] + this._data[1][1] * matrix._data[1][2] + this._data[1][2] * matrix._data[2][2] + this._data[1][3] * matrix._data[3][2];\n\t\t\tret._data[1][3] = this._data[1][0] * matrix._data[0][3] + this._data[1][1] * matrix._data[1][3] + this._data[1][2] * matrix._data[2][3] + this._data[1][3] * matrix._data[3][3];\n\n\t\t\tret._data[2][0] = this._data[2][0] * matrix._data[0][0] + this._data[2][1] * matrix._data[1][0] + this._data[2][2] * matrix._data[2][0] + this._data[2][3] * matrix._data[3][0];\n\t\t\tret._data[2][1] = this._data[2][0] * matrix._data[0][1] + this._data[2][1] * matrix._data[1][1] + this._data[2][2] * matrix._data[2][1] + this._data[2][3] * matrix._data[3][1];\n\t\t\tret._data[2][2] = this._data[2][0] * matrix._data[0][2] + this._data[2][1] * matrix._data[1][2] + this._data[2][2] * matrix._data[2][2] + this._data[2][3] * matrix._data[3][2];\n\t\t\tret._data[2][3] = this._data[2][0] * matrix._data[0][3] + this._data[2][1] * matrix._data[1][3] + this._data[2][2] * matrix._data[2][3] + this._data[2][3] * matrix._data[3][3];\n\n\t\t\tret._data[3][0] = this._data[3][0] * matrix._data[0][0] + this._data[3][1] * matrix._data[1][0] + this._data[3][2] * matrix._data[2][0] + this._data[3][3] * matrix._data[3][0];\n\t\t\tret._data[3][1] = this._data[3][0] * matrix._data[0][1] + this._data[3][1] * matrix._data[1][1] + this._data[3][2] * matrix._data[2][1] + this._data[3][3] * matrix._data[3][1];\n\t\t\tret._data[3][2] = this._data[3][0] * matrix._data[0][2] + this._data[3][1] * matrix._data[1][2] + this._data[3][2] * matrix._data[2][2] + this._data[3][3] * matrix._data[3][2];\n\t\t\tret._data[3][3] = this._data[3][0] * matrix._data[0][3] + this._data[3][1] * matrix._data[1][3] + this._data[3][2] * matrix._data[2][3] + this._data[3][3] * matrix._data[3][3];\n\t\t\treturn ret;\n\t\t}\n\t\telse\n\t\t\treturn null;\n\t}",
"static Normalize(vector) {\n const result = Vector4.Zero();\n Vector4.NormalizeToRef(vector, result);\n return result;\n }",
"set(vec) {\n for (var i = 0; i < this.size; i++)\n this.v[i] = vec[i];\n return this;\n }",
"divideToRef(otherVector, result) {\n result.x = this.x / otherVector.x;\n result.y = this.y / otherVector.y;\n return this;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
colorButton addEventListener click > / Turn off colors / window.localStorage.setItem('color', "false") | function startColor() {
// set color to true
window.localStorage.setItem("color", "true");
// remove eventListener
colorButton.removeEventListener("click", startColor);
colorButton.addEventListener("click", stopColor);
colorButton.textContent = "Turn colors off";
let html = document.querySelector("html");
// set eventlisteners to mousemove and mousedown
html.addEventListener("mousemove", updateColor);
html.addEventListener("mousedown", plusClick);
} | [
"function colorizeButton() {\n document.getElementById(\"colorizeBtn\").addEventListener(\"click\", function () {\n colorMode == \"Colorize\" ? colorMode = \"Normal\" : colorMode = \"Colorize\";\n });\n}",
"function shaderButton() {\n document.getElementById(\"shaderBtn\").addEventListener(\"click\", function () {\n colorMode == \"Shader\" ? colorMode = \"Normal\" : colorMode = \"Shader\";\n });\n}",
"function Save_Username_Color (type) {\n if (type === \"save\") {\n var usercolor_llama = document.getElementById(\"llama_clear_usercolorsrc\").value\n document.documentElement.style.setProperty(\"--thememode-usernamecolor\", usercolor_llama)\n body.classList.add(\"usercolor\")\n localStorage.setItem(\"llama_username_color\", usercolor_llama)\n } else if (type === \"reset\") {\n body.classList.remove(\"usercolor\")\n document.documentElement.style.setProperty(\"--thememode-usernamecolor\", \"\")\n document.getElementById(\"llama_clear_usercolorsrc\").value = \"\"\n document.documentElement.style.setProperty(\"--thememode-usernamecolor\", \"\")\n localStorage.setItem(\"llama_username_color\", \"\")\n }\n}",
"function updatePaletteSwatch(button, color)\n{\n if(color) \n button.setAttribute(\"data-color\", color);\n\n button.firstElementChild.style.background = \n button.getAttribute(\"data-color\");\n}",
"function buttonrandomcolorclick() {\n\tfunction get_random_color() {\n\t\tvar h = rand(1, 360);\n\t\tvar s = rand(0, 100);\n\t\tvar l = rand(10, 90);\n\t\treturn 'hsl(' + h + ',' + s + '%,' + l + '%)';\n\t}\n\tfor (var i = 0, max = px.$swatchpixels.length; i < max; i++) {\n\t\tpx.$swatchpixels[i].style.backgroundColor = get_random_color();\n\t}\n}",
"function selectedColor(color){\n\n color.addEventListener('click', e=>{\n eliminarSeleccion();\n e.target.style.border = '2px solid #22b0b0';\n\n // Agregar color seleccionado al input de color\n document.querySelector('input[name=color]').value = e.target.style.background;\n\n })\n}",
"forColorModel(){\n if((this.tps.mostRecentTransaction == -1)){ \n document.getElementById('undo-button').disabled = true;\n document.getElementById('undo-button').style.pointerEvents = \"none\";\n document.getElementById('undo-button').style.color = \"#322D2D\";\n }\n else{\n document.getElementById('undo-button').disabled = false;\n document.getElementById('undo-button').style.pointerEvents = \"auto\";\n document.getElementById('undo-button').style.color = \"#e9edf0\";\n }\n if((this.tps.mostRecentTransaction+1) < this.tps.numTransactions){\n document.getElementById('redo-button').disabled = false;\n document.getElementById('redo-button').style.pointerEvents = \"auto\";\n document.getElementById('redo-button').style.color = \"#e9edf0\";\n }\n else{\n document.getElementById('redo-button').disabled = true;\n document.getElementById('redo-button').style.pointerEvents = \"none\";\n document.getElementById('redo-button').style.color = \"#322D2D\";\n } \n }",
"function turnOff() {\n\t\twindow.nexpaqAPI.DevMod.send(\"Primary_colors\", [0]); //send Primary_colors, arg 0\n\t}",
"function userColorPicked(event) {\n clickColor = event.target.value;\n mouseClickBtn.style.backgroundColor = clickColor;\n clickButton.style.backgroundColor = clickColor;\n}",
"function Save_User_BG_Color (type) {\n if (type === \"save\") {\n body.classList.add(\"userbg_color\")\n var usercolor_llama = document.getElementById(\"llama_clear_user_bgcolorsrc\").value\n document.documentElement.style.setProperty(\"--thememode-user_bgcolor\", usercolor_llama)\n localStorage.setItem(\"llama_user_bgcolorsrc\", usercolor_llama)\n } else if (type === \"reset\") {\n body.classList.remove(\"userbg_color\")\n document.documentElement.style.setProperty(\"--thememode-user_bgcolor\", \"\")\n document.getElementById(\"llama_user_bgcolorsrc\").value = \"\"\n document.documentElement.style.setProperty(\"--thememode-user_bgcolor\", \"\")\n localStorage.setItem(\"llama_user_bgcolorsrc\", \"\")\n } else if (type === \"open\") {\n body.classList.toggle(\"userbg_color\")\n }\n}",
"function addDarkModeListener() {\n document.getElementById(\"dark-mode-btn\").addEventListener(\"click\", function(){\n userPreferences.darkMode = !userPreferences.darkMode;\n chrome.storage.local.set({\"preferences\": userPreferences}, function(){\n darkMode(userPreferences.darkMode);\n });\n });\n}",
"resetCustomColors() {\n this.themeSwitch.removeCustomTheme();\n this.removeFromLocalStorage();\n this.colorButtons.forEach(button => {\n button.style.backgroundColor = ``;\n })\n this.assignColorsToButtonsDataAttribute();\n this.removeFromLocalStorage();\n this.colors = this.themeSwitch.getColors();\n }",
"function setColorPickerListener() {\n document.getElementById(\"picker\").addEventListener(\"change\", function(){\n setCurrentColor(document.getElementById(\"picker\").value);\n changePoint (currentColor, document.getElementById(\"currentColor_r0c0\"), \"black\");\n });\n }",
"function setColor() {\r\n console.log('color button pressed');\r\n\r\n let note = this.parentNode.parentNode;\r\n let newColor = this.style.backgroundColor;\r\n\r\n note.style.backgroundColor = newColor;\r\n note.children[0].style.backgroundColor = newColor;\r\n note.children[1].style.backgroundColor = newColor;\r\n}",
"function setUserColor() {\r\n\tif (typeof(Storage) !== \"undefined\") {\r\n\t\tif (localStorage.color) {\r\n\t\t\t//botdata.characters.user.avatar = localStorage.avatar;\r\n\t\t\tbotdata.characters.user.color = localStorage.color;\r\n\t\t} else {\r\n\t\t\tvar col = randColor();\r\n\t\t\t//var r = Math.random() < 0.5 ? 1 : 2;\r\n\t \t//localStorage.setItem(\"avatar\", \"frog\" + r + \".png\");\r\n\t \tlocalStorage.setItem(\"color\", col);\r\n\t\t\t//botdata.characters.user.avatar = localStorage.avatar;\r\n\t\t\tbotdata.characters.user.color = localStorage.color;\r\n\t\t}\r\n\t} else {\r\n\t\tbotdata.characters.user.color = randColor();\r\n\t\t//var rnd = Math.random() < 0.5 ? 1 : 2;\r\n\t\t//botdata.characters.user.avatar = \"frog\" + rnd + \".png\";\r\n\t}\r\n\t//textInput.parentNode.style.backgroundColor = botdata.characters.user.color;\r\n}",
"function updateColorOnClick(number, hex) {\n\t$('input[name=color]:nth('+ number +')').attr(\"checked\",\"checked\");\t\t\t\n\t$('#miniColors').miniColors('value', hex);\n\t$('#miniColors').focus();\n\treturn false;\n}",
"function SaveColor(picker)\n{\n newColor = picker.toHEXString()\n StoreColor(newColor)\n}",
"_setColor() {\n this._container.classList.remove(\n `alert--${this._data.color === \"red\" ? \"green\" : \"red\"}`\n );\n this._container.classList.add(`alert--${this._data.color}`);\n }",
"function changeBrushColor () {\n myColor = document.getElementById('colorPicker').value;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the AWS CloudFormation properties of an `AWS::LookoutMetrics::Alert.Action` resource | function cfnAlertActionPropertyToCloudFormation(properties) {
if (!cdk.canInspect(properties)) {
return properties;
}
CfnAlert_ActionPropertyValidator(properties).assertSuccess();
return {
LambdaConfiguration: cfnAlertLambdaConfigurationPropertyToCloudFormation(properties.lambdaConfiguration),
SNSConfiguration: cfnAlertSNSConfigurationPropertyToCloudFormation(properties.snsConfiguration),
};
} | [
"function cfnAlertPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAlertPropsValidator(properties).assertSuccess();\n return {\n Action: cfnAlertActionPropertyToCloudFormation(properties.action),\n AlertSensitivityThreshold: cdk.numberToCloudFormation(properties.alertSensitivityThreshold),\n AnomalyDetectorArn: cdk.stringToCloudFormation(properties.anomalyDetectorArn),\n AlertDescription: cdk.stringToCloudFormation(properties.alertDescription),\n AlertName: cdk.stringToCloudFormation(properties.alertName),\n };\n}",
"function cfnGatewayRouteGrpcGatewayRouteActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRouteActionPropertyValidator(properties).assertSuccess();\n return {\n Rewrite: cfnGatewayRouteGrpcGatewayRouteRewritePropertyToCloudFormation(properties.rewrite),\n Target: cfnGatewayRouteGatewayRouteTargetPropertyToCloudFormation(properties.target),\n };\n}",
"function cfnRouteHttpRouteActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_HttpRouteActionPropertyValidator(properties).assertSuccess();\n return {\n WeightedTargets: cdk.listMapper(cfnRouteWeightedTargetPropertyToCloudFormation)(properties.weightedTargets),\n };\n}",
"function cfnRouteGrpcRouteActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_GrpcRouteActionPropertyValidator(properties).assertSuccess();\n return {\n WeightedTargets: cdk.listMapper(cfnRouteWeightedTargetPropertyToCloudFormation)(properties.weightedTargets),\n };\n}",
"getAlerts() {\n return [\n {\n key: 'applicationUpdated',\n icon: 'cloud download',\n message: (\n <div className={styles['single-line-message']}>\n New application version available\n ({this.renderVersionChange()})\n {this.renderClickToUpgradeLink()}\n </div>\n ),\n isVisible: this.isApplicationUpdatedAlertVisible,\n onDismiss: this.createGenericOnDismiss('applicationUpdated'),\n heightPx: 48,\n severity: 'info',\n },\n ];\n }",
"function cfnGatewayRouteHttpGatewayRouteActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRouteActionPropertyValidator(properties).assertSuccess();\n return {\n Rewrite: cfnGatewayRouteHttpGatewayRouteRewritePropertyToCloudFormation(properties.rewrite),\n Target: cfnGatewayRouteGatewayRouteTargetPropertyToCloudFormation(properties.target),\n };\n}",
"function cfnAnomalyDetectorMetricPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAnomalyDetector_MetricPropertyValidator(properties).assertSuccess();\n return {\n AggregationFunction: cdk.stringToCloudFormation(properties.aggregationFunction),\n MetricName: cdk.stringToCloudFormation(properties.metricName),\n Namespace: cdk.stringToCloudFormation(properties.namespace),\n };\n}",
"function cfnStorageLensActivityMetricsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_ActivityMetricsPropertyValidator(properties).assertSuccess();\n return {\n IsEnabled: cdk.booleanToCloudFormation(properties.isEnabled),\n };\n}",
"function Alarm(props) {\n return __assign({ Type: 'AWS::CloudWatch::Alarm' }, props);\n }",
"function cfnStorageLensCloudWatchMetricsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_CloudWatchMetricsPropertyValidator(properties).assertSuccess();\n return {\n IsEnabled: cdk.booleanToCloudFormation(properties.isEnabled),\n };\n}",
"function cfnAnomalyDetectorMetricSetPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAnomalyDetector_MetricSetPropertyValidator(properties).assertSuccess();\n return {\n DimensionList: cdk.listMapper(cdk.stringToCloudFormation)(properties.dimensionList),\n MetricList: cdk.listMapper(cfnAnomalyDetectorMetricPropertyToCloudFormation)(properties.metricList),\n MetricSetDescription: cdk.stringToCloudFormation(properties.metricSetDescription),\n MetricSetFrequency: cdk.stringToCloudFormation(properties.metricSetFrequency),\n MetricSetName: cdk.stringToCloudFormation(properties.metricSetName),\n MetricSource: cfnAnomalyDetectorMetricSourcePropertyToCloudFormation(properties.metricSource),\n Offset: cdk.numberToCloudFormation(properties.offset),\n TimestampColumn: cfnAnomalyDetectorTimestampColumnPropertyToCloudFormation(properties.timestampColumn),\n Timezone: cdk.stringToCloudFormation(properties.timezone),\n };\n}",
"function formatAction(req) {\n\t\tconst iam_action = getFirstAction(req);\t\t\t\t\t\t\t// get the iam action on the request\n\n\t\tif (req._client_event === true) {\n\t\t\tconst resource = (req.params && req.params.resource) ? simpleStr(req.params.resource) : '-';\n\t\t\tconst verb = (req.body && req.body.action_verb) ? req.body.action_verb : pickVerb(req);\n\t\t\tconst str = ev.STR.SERVICE_NAME + '.' + resource + '.' + verb;\n\t\t\treturn str.toLowerCase();\n\t\t} else {\n\t\t\tlet str = '';\t\t\t\t\t\t\t\t\t\t\t\t// populated below\n\t\t\tif (!iam_action) {\t\t\t\t\t\t\t\t\t\t\t// no action b/c its public\n\t\t\t\tstr = get_last_word_in_path(req) + '.' + pickVerb(req);\n\t\t\t} else if (iam_action === ev.STR.CREATE_ACTION) {\n\t\t\t\tstr = 'components.create';\n\t\t\t} else if (iam_action === ev.STR.DELETE_ACTION) {\n\t\t\t\tstr = 'components.delete';\n\t\t\t} else if (iam_action === ev.STR.REMOVE_ACTION) {\n\t\t\t\tstr = 'components.remove';\n\t\t\t} else if (iam_action === ev.STR.IMPORT_ACTION) {\n\t\t\t\tstr = 'components.import';\n\t\t\t} else if (iam_action === ev.STR.EXPORT_ACTION) {\n\t\t\t\tstr = 'components.export';\n\t\t\t} else if (iam_action === ev.STR.RESTART_ACTION) {\n\t\t\t\tif (req && req.path.includes('/sessions')) {\n\t\t\t\t\tstr = 'sessions.delete';\n\t\t\t\t} else if (req && req.path.includes('/cache')) {\n\t\t\t\t\tstr = 'cache.delete';\n\t\t\t\t} else {\n\t\t\t\t\tstr = 'ibp_console.start';\n\t\t\t\t}\n\t\t\t} else if (iam_action === ev.STR.LOGS_ACTION) {\n\t\t\t\tstr = 'logs.read';\n\t\t\t} else if (iam_action === ev.STR.VIEW_ACTION) {\n\t\t\t\tif (req && req.path.includes('/notifications')) {\n\t\t\t\t\tstr = 'notifications.read';\n\t\t\t\t} else if (req && req.path.includes('/signature_collections')) {\n\t\t\t\t\tstr = 'signature_collections.read';\n\t\t\t\t} else if (req && req.path.includes('/components')) {\n\t\t\t\t\tstr = 'components.read';\n\t\t\t\t} else {\n\t\t\t\t\tstr = 'ibp_console.read';\n\t\t\t\t}\n\t\t\t} else if (iam_action === ev.STR.SETTINGS_ACTION) {\n\t\t\t\tstr = 'ibp_console.' + pickVerb(req);\n\t\t\t} else if (iam_action === ev.STR.USERS_ACTION) {\n\t\t\t\tstr = 'users.' + pickVerb(req);\n\t\t\t} else if (iam_action === ev.STR.API_KEY_ACTION) {\n\t\t\t\tstr = 'api_keys.' + pickVerb(req);\n\t\t\t} else if (iam_action === ev.STR.NOTIFICATIONS_ACTION) {\n\t\t\t\tif (req && req.path.includes('/bulk')) {\n\t\t\t\t\tstr = 'notifications.delete';\n\t\t\t\t} else {\n\t\t\t\t\tstr = 'notifications.' + pickVerb(req);\n\t\t\t\t}\n\t\t\t} else if (iam_action === ev.STR.SIG_COLLECTION_ACTION) {\n\t\t\t\tstr = 'signature_collections.' + pickVerb(req);\n\t\t\t} else if (iam_action === ev.STR.C_MANAGE_ACTION) {\n\t\t\t\tif (req && req.path.includes('/actions')) {\n\t\t\t\t\tstr = 'components.configure';\n\t\t\t\t} else {\n\t\t\t\t\tstr = 'components.' + pickVerb(req);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlogger.warn('[act track] unknown iam action, please add it to activity_tracker_lib:', iam_action, req.actions);\n\t\t\t\tstr = 'unknown.' + pickVerb(req);\n\t\t\t}\n\n\t\t\t// end format is <service name>.<object descriptor>.<action verb>\n\t\t\treturn (ev.STR.SERVICE_NAME + '.' + str).toLowerCase();\t\t\t// pre-append the service name and we are done\n\t\t}\n\n\t\t// pick a action verb from the request method for this crud call\n\t\tfunction 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}\n\t}",
"function CfnAlertPropsValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('action', cdk.requiredValidator)(properties.action));\n errors.collect(cdk.propertyValidator('action', CfnAlert_ActionPropertyValidator)(properties.action));\n errors.collect(cdk.propertyValidator('alertDescription', cdk.validateString)(properties.alertDescription));\n errors.collect(cdk.propertyValidator('alertName', cdk.validateString)(properties.alertName));\n errors.collect(cdk.propertyValidator('alertSensitivityThreshold', cdk.requiredValidator)(properties.alertSensitivityThreshold));\n errors.collect(cdk.propertyValidator('alertSensitivityThreshold', cdk.validateNumber)(properties.alertSensitivityThreshold));\n errors.collect(cdk.propertyValidator('anomalyDetectorArn', cdk.requiredValidator)(properties.anomalyDetectorArn));\n errors.collect(cdk.propertyValidator('anomalyDetectorArn', cdk.validateString)(properties.anomalyDetectorArn));\n return errors.wrap('supplied properties not correct for \"CfnAlertProps\"');\n}",
"function AssessmentTemplate(props) {\n return __assign({ Type: 'AWS::Inspector::AssessmentTemplate' }, props);\n }",
"function cfnStorageLensDetailedStatusCodesMetricsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_DetailedStatusCodesMetricsPropertyValidator(properties).assertSuccess();\n return {\n IsEnabled: cdk.booleanToCloudFormation(properties.isEnabled),\n };\n}",
"function getAction() {\r\n\r\n return( action );\r\n\r\n }",
"function generateActionResultMessage(item, id, action, success) {\n if (success) {\n return 'Issue ' + id + ' was ' + action;\n } else {\n return 'Failed to ' + action + ' ' + item.toLowerCase();\n }\n }",
"function cfnAccessPointAliasPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAccessPoint_AliasPropertyValidator(properties).assertSuccess();\n return {\n Status: cdk.stringToCloudFormation(properties.status),\n Value: cdk.stringToCloudFormation(properties.value),\n };\n}",
"function cfnAnomalyDetectorCloudwatchConfigPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAnomalyDetector_CloudwatchConfigPropertyValidator(properties).assertSuccess();\n return {\n RoleArn: cdk.stringToCloudFormation(properties.roleArn),\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add enemy kill count to the score bonus timer | addCount( points, isBoardWipeDeath ){
let self = this
this.points.push(points)
if( !isBoardWipeDeath ) this.hitCount++
if( !this.timer ){
this.timer = this.game.time.events.loop(100, ()=>{
self.interations++
if( !self.startTime ) self.startTime = self.game.time.totalElapsedSeconds()
//console.log('timer timering')
if(self.interations == Math.round(self.elaspedTimeMax*10) && self.hitCount < 3){
let elapsedTime = self.game.time.totalElapsedSeconds() - self.startTime
//console.log('no bonus triggered')
//console.log('time elapsed: '+elapsedTime+' elaspedTimeMax '+self.elaspedTimeMax)
self.points = []
self.hitCount = 0
self.interations = 0
self.startTime = 0
self.game.time.events.remove( self.timer )
self.timer = null
return
}
if( (self.game.time.totalElapsedSeconds() - self.startTime) > self.elaspedTimeMax && self.hitCount >= 3){
let pointsForbonus = self.points
let hitCountForbonus = self.hitCount
self.points = []
self.hitCount = 0
self.interations = 0
self.startTime = 0
self.game.time.events.remove( self.timer )
self.timer = null
this.showBonusMessage( pointsForbonus, hitCountForbonus )
}
})
}
} | [
"function timeAttack() {\n ui.setText(\"EnemyCounter\", \"\");\n if (game.enemiesAlive == 0 && !game.waveActive) {\n ui.setText(\"Timer\", Math.floor(game.countDown));\n waveCooldown();\n } else if (game.waveActive) {\n game.countDown = game.countDown - (1 / 60);\n ui.setText(\"Timer\", Math.floor(game.countDown));\n if (game.enemiesAlive < 10) {\n gameWorld.createEnemy();\n }\n }\n if (game.countDown <= 0) {\n gameWorld.player.death();\n }\n}",
"function survival() {\n ui.setText(\"EnemyCounter\", \"\");\n if (game.enemiesAlive == 0 && !game.waveActive) {\n waveCooldown();\n } else if (game.waveActive) {\n if (game.enemiesAlive < 10) {\n gameWorld.createEnemy();\n }\n }\n}",
"function addDeathCounter(val){\n \t\t\tvar qty = deaths;\n \t\t\tvar new_qty = parseInt(qty, 10) + val;\n \t\t\tif (new_qty < 0) {\n \t\t\t\tnew_qty = 0;\n \t\t\t\t\t }\n \t\t\t\t\t deaths = new_qty;\n \t\t\t\treturn new_qty;\n \t\t}",
"function hitEnemy (shot, enemy){\n shot.kill();\n enemy.kill();\n score += 5;\n }",
"function updateKills() {\n\t\tctx.fillStyle = \"white\"\n\t\tctx.font = fontSize + \" 'Press Start 2P'\";\n\t\tctx.textAlign = \"left\"\n\t\tctx.fillText(\"Kills:\" + killCount , 50, 80);\n\t\tctx.strokeStyle = \"black\";\n\t\tctx.strokeText(\"Kills:\" + killCount , 50, 80);\n\t}",
"function addScore() {\n if (streak > 17) {\n $(\"#scoreMultiplier\").text(\"10\");\n scoreAninmation();\n score = score + 10;\n }\n else if (streak > 5) {\n $(\"#scoreMultiplier\").text(\"5\");\n scoreAninmation();\n score = score + 5;\n }\n else if (streak == 5) {\n $(\"#scoreMultiplier\").text(\"4\");\n scoreAninmation();\n score = score + 4;\n setTimeout(function () {\n $(\"#heatMed\").fadeOut(1000);\n $(\"#heatHi\").fadeIn(1000);\n }, 1500);\n }\n else if (streak == 4) {\n $(\"#scoreMultiplier\").text(\"2\");\n scoreAninmation();\n score = score + 2;\n setTimeout(function () {\n $(\"#heatLo\").fadeOut(1000);\n $(\"#heatMed\").fadeIn(1000);\n }, 1500);\n }\n else if (streak == 3) {\n $(\"#scoreMultiplier\").text(\"2\");\n scoreAninmation();\n score = score + 2;\n }\n else if (streak == 2) {\n $(\".deactive\").fadeOut(1000)\n $(\"#heatLo\").fadeIn(1000)\n score = score + 1;\n }\n else {\n score = score + 1;\n }\n }",
"function lost() {\n score = 0;\n scoreSpan.textContent = score;\n allEnemies.forEach(function(enemy) {\n enemy.speed = enemy.originalSpeed;\n });\n player.goBack();\n}",
"function defeat() {\n losses++;\n $('#totalLosses').text(losses);\n alert(\"DEFEAT!\");\n reset();\n }",
"function kills(monsters) {\n killCount += monsters;\n for (var i = 0; i < monsters; i++){\n playerGold += Math.floor((Math.random() * 3) + 1);\n };\n update();\n}",
"function enemyHitsPlayer (player,bad) {\r\n \r\n bad.kill();\r\n\tkillPlayer();\r\n\r\n}",
"removeLife () {\n document.querySelectorAll('#scoreboard img')[this.missed].setAttribute(\"src\", \"images/lostHeart.png\");\n this.missed += 1;\n if (this.missed === 4 && document.querySelector('#hint p').innerHTML !== this.activePhrase.hint) {\n document.getElementById('hint').style.display = \"none\";\n } else if (this.missed === 5) {\n checkSound([\"gameLost\"], \"start\");\n this.end(500, 450, false);\n }\n }",
"function decrementLeaderboardTimer(){\n GAME.masterLeaders(currLeaderboardVersion);\n leaderboardDecrementor = leaderboardDecrementor + 1000;\n // console.log(\"leaderboardDecrementor = \" + leaderboardDecrementor);\n setTimeout(function(){\n decrementLeaderboardTimer();\n },leaderboardDecrementor);\n }",
"function updateScore(elapsedTime){\r\n\t\tif(!myShip.getSpecs().hit && !myShip.getSpecs().invincible){\r\n\t\t\tvar oldCounter = Math.floor(updateScoreCounter);\r\n\t\t\tupdateScoreCounter += elapsedTime/1000;\r\n\t\t\tvar newCounter = Math.floor(updateScoreCounter);\r\n\r\n\t\t\tif(newCounter == oldCounter + 1){\r\n\t\t\t\taddToScore(10);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"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 nextFlareon() { //* need to fix this function so that it doesn't decrease life when reaching end points and respawning!!!!!!!\n flareonPosition = startingPosition //* takes player back to starting position\n if (!playerWinFlag) {\n playerLives-- //* so player lives will decrease when you \"die\"\n playerScore -= 20\n scoreDisplay.textContent = playerScore\n }\n playerWinFlag = false\n remainingLives.textContent = playerLives //* prints number of lives remaining here\n if (playerLives === 0) { //* if plyaer loses all lives\n setTimeout(theGameOver, 500)\n } else {\n addPlayer('flareonIdle')\n }\n\n }",
"function onHit() {\n this.classList.remove(\"active\");\n this.classList.add(\"target\");\n scoreIncrement();\n time = time - 10;\n}",
"totalEnemies()\n {\n this.numberOfEnemies++;\n }",
"function enemyMoveHeight() {\n if(isHidden==true){return;}\n if(enemy.offsetTop>=700){\n lives--;\n var audioLifeLost= new Audio(\"lifeLost.wav\");\n audioLifeLost.play();\n LivesDiv.innerHTML=\"lives \"+lives;\n enemy.remove();\n //when the play reaches 0 lives the function is called to end the game\n if(lives<=0){\n gameOver();\n }\n }\n //enemy will keep moving until it has reacher 669px\n else if(enemy.offsetTop<=699){\n enemyPosition++;\n enemy.style.top = enemyPosition + 'px';\n }\n }",
"function updateLives() {\n // detecting contact between the player and the paperAgenda\n if (isCollided(player._spriteRun, paperAgendas[0]) == true) {\n paperAgendas.splice(0, 1);\n if (playerLives > 0) {\n playerLives -= 1;\n } else {\n // when game ends, plays die audio\n endGame();\n dieAudio.play();\n }\n\n updateLivesHTML();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a control that recenters the map on Chicago. | function createCenterControl(map) {
const controlButton = document.createElement("button");
// Set CSS for the control.
controlButton.style.backgroundColor = "#fff";
controlButton.style.border = "2px solid #fff";
controlButton.style.borderRadius = "3px";
controlButton.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
controlButton.style.color = "rgb(25,25,25)";
controlButton.style.cursor = "pointer";
controlButton.style.fontFamily = "Roboto,Arial,sans-serif";
controlButton.style.fontSize = "16px";
controlButton.style.lineHeight = "38px";
controlButton.style.margin = "8px 0 22px";
controlButton.style.padding = "0 5px";
controlButton.style.textAlign = "center";
controlButton.textContent = "Set City Bounds";
controlButton.title = "Click to save the bounds";
controlButton.type = "button";
// Setup the click event listeners: simply set the map to Chicago.
controlButton.addEventListener("click", () => {
//map.setCenter(chicago);
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
webViewBridge.cityBounds( ne.lat(), ne.lng(), sw.lat(), sw.lng());
});
return controlButton;
} | [
"function bicycleControl(map) {\n\n // Initialize control div\n var controlDiv = document.createElement('div');\n map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);\n controlDiv.id = 'maptype_button';\n controlDiv.title = 'Show bicycle map';\n controlDiv.innerHTML = 'Bicycling';\n\n // Initialize map with control off\n var toggled = false;\n var layer = new google.maps.BicyclingLayer();\n\n // Setup the click event listeners\n google.maps.event.addDomListener(controlDiv, 'click', function() {\n if (toggled) {\n layer.setMap(null);\n controlDiv.style.fontWeight = 'normal';\n controlDiv.style.color = '#565656';\n controlDiv.style.boxShadow = '0px 1px 1px -1px rgba(0, 0, 0, 0.4)';\n toggled = 0;\n } else {\n layer.setMap(map);\n controlDiv.style.fontWeight = '500';\n controlDiv.style.color = '#000';\n controlDiv.style.boxShadow = '0px 1px 1px -1px rgba(0, 0, 0, 0.6)';\n toggled = 1;\n }\n });\n}",
"function createMap(){\n\n // Add place searchbar to map\n L.Control.openCageSearch(options).addTo(map);\n\n // Add zoom control (but in top right)\n L.control.zoom({\n position: 'topleft'\n }).addTo(map);\n\n // build easy bar from array of easy buttons\n L.easyBar(buttons).addTo(map);\n\n // Add easy button to pull up splash screen\n L.easyButton('<img src=\"img/noun_Info_1845673_blk.svg\">', function(){\n $('#splash-screen').modal('show');\n },'info window',{ position: 'topleft' }).addTo(map);\n\n //load tile layer\n L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}', {\n\t attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ',\n }).addTo(map);\n\n L.control.attribution({\n position: 'bottomright'\n }).addTo(map);\n //call getData function\n getData(map);\n}",
"function CenterControl(controlDiv, map) {\n\n // Set CSS for the control border.\n var controlUI = document.createElement('div');\n controlUI.style.backgroundColor = '#fff';\n controlUI.style.border = '2px solid #fff';\n controlUI.style.borderRadius = '3px';\n controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';\n controlUI.style.cursor = 'pointer';\n controlUI.style.marginBottom = '22px';\n controlUI.style.textAlign = 'center';\n controlUI.title = 'Click to recenter the map';\n controlDiv.appendChild(controlUI);\n\n // Set CSS for the control interior.\n var controlText = document.createElement('div');\n controlText.style.color = 'rgb(25,25,25)';\n controlText.style.fontFamily = 'Roboto,Arial,sans-serif';\n controlText.style.fontSize = '16px';\n controlText.style.lineHeight = '38px';\n controlText.style.paddingLeft = '5px';\n controlText.style.paddingRight = '5px';\n controlText.innerHTML = 'Center Map';\n controlUI.appendChild(controlText);\n\n // Setup the click event listeners: simply set the map to Chicago.\n controlUI.addEventListener('click', function() {\n map.setCenter(marker.getPosition());\n });\n\n}",
"function LightControl(controlDiv, map) {\n controlDiv.style.padding = '30px';\n\n // Set CSS for the control border\n var controlUI = document.createElement('div');\n controlUI.style.backgroundColor = 'white';\n controlUI.style.borderStyle = 'solid';\n controlUI.style.borderWidth = '2px';\n controlUI.style.cursor = 'pointer';\n controlUI.style.textAlign = 'center';\n controlUI.title = 'Click to create a new light at the cursor position';\n controlDiv.appendChild(controlUI);\n\n // Set CSS for the control interior\n var controlText = document.createElement('div');\n controlText.style.fontFamily = 'Arial,sans-serif';\n controlText.style.fontSize = '14px';\n controlText.style.paddingLeft = '8px';\n controlText.style.paddingRight = '8px';\n controlText.innerHTML = '<b>Add Light</b>';\n controlUI.appendChild(controlText);\n\n google.maps.event.addDomListener(controlUI, 'click', function() {\n createLight();\n });\n }",
"function initializeMap() {\n\n /*\n Instantiate a new Virginia Tech campus map object and set its properties.\n document.getElementById('map') --> Obtains the Google Map style definition\n from the div element with id=\"map\" in TripDetails.xhtml \n */\n map = new google.maps.Map(document.getElementById('map'), {\n zoom: 15,\n center: {lat: 37.227264, lng: -80.420745},\n mapTypeControl: true,\n mapTypeControlOptions: {\n style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,\n position: google.maps.ControlPosition.BOTTOM_LEFT\n },\n mapTypeId: google.maps.MapTypeId.HYBRID\n });\n\n // Show the desired map using the map created above by calling the display() function.\n display();\n\n}",
"function addControls() {\n // Add home button\n L.easyButton(\n \"fa-home\",\n function (btn, map) {\n map.setView([home.lat, home.lng], home.zoom);\n },\n \"Zoom To Home\",\n { position: \"topright\" }\n ).addTo(myMap);\n\n // Reposition the zoom control\n myMap.zoomControl.setPosition(\"topright\");\n\n // Add a fullscreen toggle\n myMap.addControl(new L.Control.Fullscreen({ position: \"topright\" }));\n\n // Add scale bar\n L.control.betterscale().addTo(myMap);\n}",
"function createMap() {\n currentTerritory= viewerOptions.territory || 'FXX';\n // viewer creation of type <Geoportal.Viewer>\n // création du visualiseur du type <Geoportal.Viewer>\n // HTML div id, options\n territoriesViewer[currentTerritory]= new Geoportal.Viewer.Default('viewerDiv', OpenLayers.Util.extend(\n OpenLayers.Util.extend({}, viewerOptions),\n // API keys configuration variable set by\n // <Geoportal.GeoRMHandler.getConfig>\n // variable contenant la configuration des clefs API remplie par\n // <Geoportal.GeoRMHandler.getConfig>\n window.gGEOPORTALRIGHTSMANAGEMENT===undefined? {'apiKey':'nhf8wztv3m9wglcda6n6cbuf'} : gGEOPORTALRIGHTSMANAGEMENT)\n );\n if (!territoriesViewer[currentTerritory]) {\n // problem ...\n OpenLayers.Console.error(OpenLayers.i18n('new.instance.failed'));\n return;\n }\n\n territoriesViewer[currentTerritory].addGeoportalLayers([\n 'ORTHOIMAGERY.ORTHOPHOTOS',\n 'GEOGRAPHICALGRIDSYSTEMS.MAPS'],\n {\n });\n territoriesViewer[currentTerritory].getMap().setCenter(\n territoriesViewer[currentTerritory].viewerOptions.defaultCenter,\n territoriesViewer[currentTerritory].viewerOptions.defaultZoom);\n // cache la patience - hide loading image\n territoriesViewer[currentTerritory].div.style[OpenLayers.String.camelize('background-image')]= 'none';\n}",
"function drawChinaMap() {\n const data = google.visualization.arrayToDataTable(CHINA_MAP_TABLE);\n\n const options = {\n region: CHINA_REGION,\n width: 500,\n height: 310,\n colorAxis: {colors: ['#4374e0', '#4374e0']}\n };\n\n const chart = new google.visualization.GeoChart(document.getElementById(DOM_CONTAINARS_IDS.MAP_CHART));\n chart.draw(data, options);\n}",
"addControls () {\n /**\n * @type {ControlsConfig}\n */\n this.controlsConfig = this.map_.get('mapConfig').controls\n if (checkFor(this.controlsConfig, 'onMap')) {\n this.addControlMultipleInternal_(this.map_, this.controlsConfig.onMap)\n }\n }",
"function setPlayerWorldMapPositionIndicatorTo(map) {\n\tlet zoneName = ZONES[map];\n\tlet zoneId = zoneName.toLowerCase().replace(/\\s+/g, \"_\");\n\tlet zone = document.getElementById(zoneId);\n\tlet youAreHere = document.createElement(\"span\");\n\tyouAreHere.innerHTML = '⇣';\n\tyouAreHere.setAttribute(\"class\", \"you_are_here\");\n\tzone.appendChild(youAreHere);\n}",
"function MapViewFactory() {}",
"function initMap() {\n $('#widgetRealTimeMapliveMap .loadingPiwik, .RealTimeMap .loadingPiwik').hide();\n map.addLayer(currentMap.length == 3 ? 'context' : 'countries', {\n styles: {\n fill: colorTheme[currentTheme].fill,\n stroke: colorTheme[currentTheme].bg,\n 'stroke-width': 0.2\n },\n click: function (d, p, evt) {\n evt.stopPropagation();\n if (currentMap.length == 2){ // zoom to country\n updateMap(d.iso);\n } else if (currentMap != 'world') { // zoom out if zoomed in\n updateMap('world');\n } else { // or zoom to continent view otherwise\n updateMap(UserCountryMap.ISO3toCONT[d.iso]);\n }\n },\n title: function (d) {\n // return the country name for educational purpose\n return d.name;\n }\n });\n if (currentMap.length == 3){\n map.addLayer('regions', {\n styles: {\n stroke: colors['region-stroke-color']\n }\n });\n }\n var lastVisitId = -1,\n lastReport = [];\n refreshVisits(true);\n }",
"function MapLayers_Time_CreateSlider() {\n\nMapLayers.Time.\nToolbar = new MapLayers.Time._TimeBar();\n\n}",
"function createControls(){\n\tcontrols = new THREE.FlyControls(camera);\n\tcontrols.movementSpeed = 1.0;\n\tcontrols.domElement = container;\n\tcontrols.rollSpeed = Math.PI / 240;\n\tcontrols.autoForward = false;\n\tcontrols.dragToLook = false;\n}",
"function init (){\n\tvar num_troops = 120/num_player;\n\t//initialize map with same number of troops for each player\n\tfor (var i=0 ; i < num_troops; i++){\n\t\tfor(game.currentUserTurn ;game.currentUserTurn<num_player; game.currentUserTurn++){\n\t\t\t//calling object\n\n\t\t\tgame.regions[].controlledBy=game.currentUserTurn;\n\t\t\taddTroops (game.currentUserTurn, game.regions[territory]);\n\t\t\t//game.regions[/*input*/].controlledBy=game.currentUserTurn;\n\n\t\t}\n\t}\n}",
"function createMapClones() {\n \t var clonemapfirst = setInterval(function() {\n\t\t\t\t\tif (jQuery('#mapgyver_holder').hasClass(\"mapisready\")) {\n\t\t\t\t\t\tsetTimeout(function() {\n\t\t\t\t\t\t\trecreateMapClones();\n\t\t\t\t\t\t\tfoldMapHandler();\n\t\t\t\t\t\t},300)\n\t\t\t\t\t\tclearInterval(clonemapfirst);\n\t\t\t\t\t}\n\t\t },50)\n}",
"function RouteRangeControl(options) {\n var _this = _super.call(this) || this;\n /****************************\n * Private Properties\n ***************************/\n /** Default options. */\n _this._options = {\n markerOptions: {\n color: '#F2C811',\n secondaryColor: '#011C2C',\n htmlContent: '<svg xmlns=\"http://www.w3.org/2000/svg\" style=\"cursor:move\" width=\"28px\" height=\"39px\" viewBox=\"-1 -1 27 38\"><path d=\"M12.25.25a12.254 12.254 0 0 0-12 12.494c0 6.444 6.488 12.109 11.059 22.564.549 1.256 1.333 1.256 1.882 0C17.762 24.853 24.25 19.186 24.25 12.744A12.254 12.254 0 0 0 12.25.25Z\" style=\"fill:{color};stroke:{secondaryColor};stroke-width:2\"/><g style=\"transform:scale(0.2);transform-origin: 13% 10%;\"><path d=\"m50 38h-4v14c0 0 0 1 0 1l9 9 2-2-9-9v-13z\" fill=\"{secondaryColor}\" stroke=\"{secondaryColor}\" stroke-width=\"2px\"/><path d=\"m48 81c-15 0-28-12-28-28s12-28 28-28 28 12 28 28-12 28-28 28zm23-52 3-3c1-1 1-3-0-4-1-1-3-1-4-0l-3 3c-4-3-10-5-16-5v-4h9v-6h-24v6h9v4c-15 1-28 13-30 29s7 31 22 36 31-0 40-14 6-31-5-42z\" fill=\"{secondaryColor}\" stroke=\"{secondaryColor}\" stroke-width=\"2px\"/></g></svg>'\n },\n style: azmaps.ControlStyle.light,\n isVisible: true,\n position: 'left',\n collapsible: false,\n calculateOnMarkerMove: true\n };\n /** How long to delay a search after the marker has been moved using the keyboard. */\n _this._markerMoveSearchDelay = 600;\n /** How many pixels the marker will move for an arrow key press occurs on the top level route range container. */\n _this._arrowKeyOffset = 5;\n /** When map is small, this specifies how long the options should be hidden to give the user a chance to move the marker. */\n _this._showOptionsDelay = 0;\n /** Data bound settings used for requesting a route range polygon. */\n _this._settings = {};\n /****************************\n * Private Methods\n ***************************/\n /**\n * Callback function for when localization resources have loaded.\n * Create the content of the container.\n * @param resx The localization resource.\n */\n _this._createContainer = function (resx) {\n //Cache variables and function for better minification. \n var self = _this;\n var css = RouteRangeControl._css;\n var createElm = Utils.createElm;\n //Create a binding to the settings object.\n var binding = new SimpleBinding(self._settings);\n self._binding = binding;\n //Create the main container.\n var container = Utils.createElm('div', {\n class: ['azure-maps-control-container', RouteRangeControl._css.container],\n style: {\n display: (self._options.isVisible) ? '' : 'none'\n },\n attr: {\n 'aria-label': resx.routeRangeControl,\n tabindex: '-1'\n }\n });\n container.addEventListener('keydown', _this._onContainerKeyDown);\n self._container = container;\n //Create travelTime option.\n //<input type=\"number\" value=\"15\" min=\"1\" max=\"1440\">\n var travelTime = createElm('input', {\n attr: {\n type: 'number',\n value: '15',\n min: '1',\n max: '1440'\n },\n propName: 'travelTime'\n }, resx, binding);\n var timeOptionRow = self._createOptionRow(resx.travelTime, travelTime);\n //Create distance options.\n /*\n <input type=\"number\" value=\"5\" min=\"1\" max=\"1000\">\n <select class=\"distanceUnits\">\n <option value=\"meters\">Meters</option>\n <option value=\"miles\">Miles</option>\n <option value=\"kilometers\" selected>Kilometers</option>\n <option value=\"yards\">Yards</option>\n </select>\n */\n var distance = createElm('input', {\n attr: {\n type: 'number',\n value: '5',\n min: '1',\n max: '1000'\n },\n propName: 'distance'\n }, resx, binding);\n var distanceUnits = createElm('select', {\n selectVals: ['meters', 'miles', 'kilometers', 'yards'],\n selected: 'kilometers',\n propName: 'distanceUnits'\n }, resx, binding);\n var distanceOptionRow = self._createOptionRow(resx.distance, [distance, distanceUnits]);\n //Create show area option.\n //<input type=\"checkbox\" checked=\"checked\"/>\n var showArea = createElm('input', {\n attr: {\n type: 'checkbox',\n checked: 'checked'\n },\n propName: 'showArea'\n }, resx, binding);\n //Create traffic options.\n /*\n <div class=\"atlas-route-range-row traffic-option\" style=\"display:none;\">\n <div class=\"atlas-route-range-col1\">Leave at</div>\n <div class=\"atlas-route-range-col2\">\n <input type=\"date\">\n <input type=\"time\" step=\"300\">\n </div>\n </div>\n */\n var leaveAtDate = createElm('input', {\n attr: {\n type: 'date'\n },\n style: {\n marginBottom: '3px'\n },\n propName: 'leaveAtDate'\n }, resx, binding);\n var leaveAtTime = createElm('input', {\n attr: {\n type: 'time',\n step: '300'\n },\n propName: 'leaveAtTime'\n }, resx, binding);\n var trafficOption = self._createOptionRow(resx.leaveAt, [leaveAtDate, leaveAtTime]);\n trafficOption.style.display = 'none';\n var isDateTimeSupported = Utils.isDateTimeInputSupported();\n //Set the initial date/time to the current date/time to the next 5 minute round value.\n if (isDateTimeSupported) {\n //Set the date and time pickers.\n var d = new Date();\n var hour = d.getHours();\n var min = d.getMinutes();\n //Round minutes to the next 5 minute.\n min = Math.ceil(min / 5) * 5;\n if (min === 60) {\n hour++;\n min = 0;\n }\n d = new Date(d.toDateString());\n d = new Date(d.setHours(hour, min));\n //Just in case the hours have increased into a new day.\n hour = d.getHours();\n self._settings.leaveAtDate = d.toISOString().split('T')[0];\n leaveAtDate.value = self._settings.leaveAtDate;\n leaveAtDate.setAttribute('min', self._settings.leaveAtDate);\n var hh = ((hour < 10) ? '0' : '') + Utils.USNumberFormat(hour);\n var mm = ((min < 10) ? '0' : '') + Utils.USNumberFormat(min);\n self._settings.leaveAtTime = hh + \":\" + mm;\n leaveAtTime.value = self._settings.leaveAtTime;\n }\n //Create length options.\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">Length</div>\n <div class=\"atlas-route-range-col2\">\n <input type=\"number\" min=\"0\"/>\n <select>\n <option value=\"feet\">Feet</option>\n <option value=\"meters\" selected>Meters</option>\n <option value=\"yards\">Yards</option>\n </select>\n </div>\n </div>\n */\n var length = createElm('input', {\n attr: {\n type: 'number',\n min: '0'\n },\n propName: 'length'\n }, resx, binding);\n var lengthUnits = createElm('select', {\n selectVals: ['feet', 'meters', 'yards'],\n selected: 'meters',\n propName: 'lengthUnits'\n }, resx, binding);\n var lengthRow = self._createOptionRow(resx.length, [length, lengthUnits], true);\n //Create height options.\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">Height</div>\n <div class=\"atlas-route-range-col2\">\n <input type=\"number\" min=\"0\"/>\n </div>\n </div>\n */\n var height = createElm('input', {\n attr: {\n type: 'number',\n min: '0'\n },\n propName: 'height'\n }, resx, binding);\n var heightRow = self._createOptionRow(resx.height, height, true);\n //Create width options.\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">Width</div>\n <div class=\"atlas-route-range-col2\">\n <input type=\"number\" min=\"0\"/>\n </div>\n </div>\n */\n var width = createElm('input', {\n attr: {\n type: 'number',\n min: '0'\n },\n propName: 'width'\n }, resx, binding);\n var widthRow = self._createOptionRow(resx.width, width, true);\n //Create weight options.\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">Axle weight</div>\n <div class=\"atlas-route-range-col2\">\n <input type=\"number\" min=\"0\"/>\n <select>\n <option value=\"kilograms\" selected>Kilograms</option>\n <option value=\"longTon\">Long ton</option>\n <option value=\"metricTon\">Metric ton</option>\n <option value=\"pounds\">Pounds</option>\n <option value=\"shortTon\">Short ton</option>\n </select>\n </div>\n </div>\n */\n var axleWeight = createElm('input', {\n attr: {\n type: 'number',\n min: '0'\n },\n propName: 'axleWeight'\n }, resx, binding);\n var weightUnits = createElm('select', {\n selectVals: ['kilograms', 'longTon', 'metricTon', 'pounds', 'shortTon'],\n selected: 'kilograms',\n propName: 'weightUnits'\n }, resx, binding);\n var weightRow = self._createOptionRow(resx.axleWeight, [axleWeight, weightUnits], true);\n //Create toggle button for truck dimensions.\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">\n <button class=\"atlas-route-range-expand-btn\" aria-expanded=\"false\" aria-label=\"Toggle truck dimension options\">Truck dimensions <span class=\"atlas-route-range-toggle-icon\"></span></button>\n </div>\n </div>\n */\n var truckDimensionsToggle = self._createToggleBtn(resx.truckDimensions, resx.truckDimensionsToggle, [\n lengthRow, heightRow, widthRow, weightRow\n ]);\n //Create load type options.\n /*\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">\n <button class=\"atlas-route-range-expand-btn\" aria-expanded=\"false\" aria-label=\"Toggle load type options\">Load type <span class=\"atlas-route-range-toggle-icon\"></span></button>\n </div>\n </div>\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\" style=\"display:none;\">\n <input value=\"USHazmatClass2\" type=\"checkbox\"/>Compressed gas<br/>\n <input value=\"USHazmatClass8\" type=\"checkbox\"/>Corrosives<br/>\n <input value=\"USHazmatClass1\" type=\"checkbox\"/>Explosives<br/>\n <input value=\"USHazmatClass3\" type=\"checkbox\"/>Flammable liquids<br/>\n <input value=\"USHazmatClass4\" type=\"checkbox\"/>Flammable solids\n </div>\n <div class=\"atlas-route-range-col2\" style=\"display:none;\">\n <input value=\"otherHazmatHarmfulToWater\" type=\"checkbox\"/>Harmful to water<br/>\n <input value=\"USHazmatClass9\" type=\"checkbox\"/>Miscellaneous<br/>\n <input value=\"USHazmatClass5\" type=\"checkbox\"/>Oxidizers<br/>\n <input value=\"USHazmatClass6\" type=\"checkbox\"/>Poisons<br/>\n <input value=\"USHazmatClass7\" type=\"checkbox\"/>Radioactive\n </div>\n </div>\n */\n var loadTypeOptions = self._createCheckboxGroup('loadType', ['USHazmatClass2', 'USHazmatClass8', 'USHazmatClass1', 'USHazmatClass3', 'USHazmatClass4', 'otherHazmatHarmfulToWater', 'USHazmatClass9', 'USHazmatClass5', 'USHazmatClass6', 'USHazmatClass7'], resx, function (values) {\n //Cross reference USHazmatClass1 with otherHazmatExplosive.\n var USHazmatClass1 = values.indexOf('USHazmatClass1');\n var otherHazmatExplosive = values.indexOf('otherHazmatExplosive');\n if (USHazmatClass1 > 0) {\n if (otherHazmatExplosive === -1) {\n values.push('otherHazmatExplosive');\n }\n }\n else if (otherHazmatExplosive > 0) {\n //Remove this value as the USHazmatClass1 is unselected.\n values = values.splice(otherHazmatExplosive, 1);\n }\n //Cross reference USHazmatClass9 with otherHazmatGeneral.\n var USHazmatClass9 = values.indexOf('USHazmatClass9');\n var otherHazmatGeneral = values.indexOf('otherHazmatGeneral');\n if (USHazmatClass9 > 0) {\n if (otherHazmatGeneral === -1) {\n values.push('otherHazmatGeneral');\n }\n }\n else if (otherHazmatGeneral > 0) {\n //Remove this value as the USHazmatClass9 is unselected.\n values = values.splice(otherHazmatGeneral, 1);\n }\n });\n //Group truck options.\n var truckToggleOptions = [truckDimensionsToggle, loadTypeOptions[0]];\n // const truckOptions = [lengthRow, heightRow, widthRow, weightRow, loadTypeOptions[1]];\n //Create avoid options.\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">\n <button class=\"atlas-route-range-expand-btn\" aria-expanded=\"false\" aria-label=\"Toggle avoid type options list\">Avoid <span class=\"atlas-route-range-toggle-icon\"></span></button>\n </div>\n </div>\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\" style=\"display:none;\">\n <input value=\"borderCrossings\" type=\"checkbox\" />Border crossings<br/>\n <input value=\"carpools\" type=\"checkbox\" />Carpools<br/>\n <input value=\"ferries\" type=\"checkbox\" />Ferries\n </div>\n <div class=\"atlas-route-range-col2\" style=\"display:none;\">\n <input value=\"motorways\" type=\"checkbox\" />Motorways<br/>\n <input value=\"tollRoads\" type=\"checkbox\" />Toll roads<br/>\n <input value=\"unpavedRoads\" type=\"checkbox\" />Unpaved roads\n </div>\n </div>\n */\n var avoidOptions = self._createCheckboxGroup('avoid', ['borderCrossings', 'carpools', 'ferries', 'motorways', 'tollRoads', 'unpavedRoads'], resx);\n //Create traffic option.\n var useTraffic = createElm('input', {\n attr: { type: 'checkbox' },\n propName: 'traffic',\n bindingChanged: function (val) {\n trafficOption.style.display = self._getDateTimePickerDisplay();\n }\n }, resx, binding);\n var useTrafficRow = self._createOptionRow(resx.traffic, useTraffic);\n //Create selection area option.\n /*\n <select>\n <option value=\"distance\">Distance</option>\n <option value=\"time\" selected>Time</option>\n </select>\n */\n var selectionArea = createElm('select', {\n selectVals: ['distance', 'time'],\n selected: 'time',\n propName: 'selectionArea',\n bindingChanged: function (val) {\n //Hide/show options depending on the selection area value.\n var isTime = (val === 'time');\n timeOptionRow.style.display = (isTime) ? '' : 'none';\n distanceOptionRow.style.display = (!isTime) ? '' : 'none';\n useTrafficRow.style.display = (isTime && (self._settings.travelMode === 'car' || self._settings.travelMode === 'truck')) ? '' : 'none';\n trafficOption.style.display = self._getDateTimePickerDisplay();\n }\n }, resx, binding);\n //Create travel mode option.\n /*\n <select>\n <option value=\"car\" selected>Car</option>\n <option value=\"bicycle\">Bicycle</option>\n <option value=\"pedestrian\">Pedestrian</option>\n <option value=\"truck\">Truck</option>\n </select>\n */\n var travelMode = createElm('select', {\n selectVals: ['car', 'bicycle', 'pedestrian', 'truck'],\n selected: 'car',\n propName: 'travelMode',\n bindingChanged: function (val) {\n //Hide/show certain options depending on the selected travel mode.\n var isVehicle = true;\n var isTruck = false;\n switch (val) {\n case 'pedestrian':\n case 'bicycle':\n isVehicle = false;\n break;\n case 'truck':\n isTruck = true;\n break;\n }\n avoidOptions.forEach(function (ao) {\n ao.style.display = (isVehicle) ? '' : 'none';\n });\n truckToggleOptions.forEach(function (toggle) {\n toggle.style.display = (isTruck) ? '' : 'none';\n //Toggle close all truck options if not showing truck,\n if (!isTruck && toggle.getAttribute('aria-expanded') === 'true') {\n toggle.click();\n }\n });\n useTrafficRow.style.display = (isVehicle && self._settings.selectionArea === 'time') ? '' : 'none';\n trafficOption.style.display = self._getDateTimePickerDisplay();\n }\n }, resx, binding);\n //Create buttons\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\"><button class=\"atlas-route-range-search-btn\">Search</button></div>\n <div class=\"atlas-route-range-col2\"><button class=\"atlas-route-range-cancel-btn\">Cancel</button></div>\n </div>\n */\n //Create search button.\n var searchBtn = createElm('button', {\n class: [css.searchBtn],\n propName: 'search',\n innerHTML: resx['search']\n }, resx);\n searchBtn.onclick = self._onSearch;\n self._searchBtn = searchBtn;\n //Create cancel button.\n var cancelBtn = createElm('button', {\n class: [css.cancelBtn],\n propName: 'cancel',\n innerHTML: resx['cancel']\n }, resx);\n if (!self._options.collapsible) {\n cancelBtn.style.display = 'none';\n }\n cancelBtn.onclick = self._onCancel;\n //Create button row.\n var btnRow = Utils.createElm('div', {\n class: [css.row],\n style: {\n display: 'block'\n },\n children: [Utils.createElm('div', {\n style: {\n 'text-align': 'center'\n },\n children: [searchBtn, cancelBtn]\n })]\n });\n //Create options container.\n self._optionSection = createElm('div', { class: [css.options], children: [\n //Add travel mode.\n self._createOptionRow(resx.travelMode, travelMode),\n //Add selection area option.\n self._createOptionRow(resx.selectionArea, selectionArea),\n //Add travelTime option.\n timeOptionRow,\n //Add distance options.\n distanceOptionRow,\n //Add show area option.\n self._createOptionRow(resx.showArea, showArea),\n //Add use traffic option.\n useTrafficRow,\n //Add traffic option.\n trafficOption,\n //Add truck dimension toggle.\n truckDimensionsToggle,\n //Add truck dimenion options.\n lengthRow, heightRow, widthRow, weightRow,\n //Add load type options.\n loadTypeOptions[0], loadTypeOptions[1],\n //Add avoid options.\n avoidOptions[0], avoidOptions[1]\n ] });\n //Add options to container.\n Utils.appendChildren(container, [\n //Add the intstructions.\n createElm('div', { class: [css.instructions], innerHTML: resx.selectOrigin }, resx),\n //Add options container.\n self._optionSection,\n //Add buttons.\n btnRow\n ]);\n self._map.events.add('resize', self._mapResized);\n self._mapResized();\n if (self._options.isVisible) {\n self.setVisible(self._options.isVisible);\n }\n };\n /** Event handler for when the search button is pressed. */\n _this._onSearch = function () {\n //Cache functions and variables for better minification.\n var self = _this;\n var convertDistance = azmaps.math.convertDistance;\n var round = Math.round;\n var request = self._settings;\n //Ensure numbers are properly formatted when converted to a string. Don't allow comma groupings.\n var numberFormatter = Utils.USNumberFormat;\n //Create the query string value. Have to manually create string since loadType and avoid values have to be added as individual parameters which JSON objects don't allow.\n var queryString = []; //encodeURIComponent\n //Origin query\n queryString.push(\"query=\" + numberFormatter(request.origin[1]) + \",\" + numberFormatter(request.origin[0]));\n queryString.push(\"travelMode=\" + request.travelMode);\n if (request.selectionArea === 'time') {\n queryString.push(\"timeBudgetInSec=\" + numberFormatter(round(request.travelTime * 60)));\n if (request.traffic) {\n queryString.push(\"traffic=true\");\n if (request.leaveAtDate && request.leaveAtTime) {\n //Check to see if seconds need to be added.\n var t = request.leaveAtTime;\n if (t.match(/:/g).length === 1) {\n t += ':00';\n }\n //1996-12-19T16:39:57 - Don't specify timezone in request. The service will use the timezone of the origin point automatically.\n queryString.push(\"departAt=\" + request.leaveAtDate + \"T\" + t);\n }\n }\n }\n else {\n queryString.push(\"distanceBudgetInMeters=\" + numberFormatter(round(convertDistance(request.distance, request.distanceUnits, 'meters'))));\n }\n if (request.travelMode === 'car' || request.travelMode === 'truck') {\n //avoid\n if (request.avoid) {\n request.avoid.forEach(function (a) {\n queryString.push(\"avoid=\" + a);\n });\n }\n }\n if (request.travelMode === 'truck') {\n //vehcileLength (m), vehicleWidth (m), vehicleHeight (m), vehicleAxleWeight (kg), vehicleLoadType \n if (!isNaN(request.length)) {\n queryString.push(\"vehcileLength=\" + numberFormatter(round(convertDistance(request.length, request.lengthUnits, 'meters'))));\n }\n if (!isNaN(request.width)) {\n queryString.push(\"vehicleWidth=\" + numberFormatter(round(convertDistance(request.width, request.lengthUnits, 'meters'))));\n }\n if (!isNaN(request.height)) {\n queryString.push(\"vehicleHeight=\" + numberFormatter(round(convertDistance(request.height, request.lengthUnits, 'meters'))));\n }\n if (!isNaN(request.height)) {\n queryString.push(\"vehicleAxleWeight=\" + numberFormatter(round(MapMath.convertWeight(request.axleWeight, request.weightUnits, 'kilograms'))));\n }\n if (request.loadType) {\n request.loadType.forEach(function (lt) {\n queryString.push(\"vehicleLoadType=\" + lt);\n });\n }\n }\n //Create the URL request. \n var url = \"https://\" + self._map.getServiceOptions().domain + \"/route/range/json?api-version=1.0&\" + queryString.join('&');\n //Sign the request. This will use the same authenication that the map is using to access the Azure Maps platform.\n //This gives us the benefit of not having to worry about if this is using subscription key or Azure AD.\n var requestParams = self._map.authentication.signRequest({ url: url });\n fetch(requestParams.url, {\n method: 'GET',\n mode: 'cors',\n headers: new Headers(requestParams.headers)\n })\n .then(function (r) { return r.json(); }, function (e) { return self._invokeEvent('error', self._resx.routeRangeError); })\n .then(function (response) {\n if (response.reachableRange) {\n //Convert the response into GeoJSON and add it to the map.\n var positions = response.reachableRange.boundary.map(function (latLng) {\n return [latLng.longitude, latLng.latitude];\n });\n var isochrone = new azmaps.data.Polygon([positions]);\n self._invokeEvent('rangecalculated', isochrone);\n if (self._settings.showArea) {\n self._invokeEvent('showrange', isochrone);\n }\n }\n else {\n self._invokeEvent('error', self._resx.routeRangeError);\n }\n }, function (error) { return self._invokeEvent('error', self._resx.routeRangeError); });\n if (self._options.collapsible) {\n //Hide the input panel and marker.\n self.setVisible(false);\n }\n };\n /** Event handler for when the cancel button is clicked. */\n _this._onCancel = function () {\n //Hide the input panel and marker.\n _this.setVisible(false);\n };\n /** Event handler for when the origin marker is dragged. */\n _this._onMarkerDragged = function () {\n var self = _this;\n self._settings.origin = self._marker.getOptions().position;\n self._optionSection.style.display = '';\n self._searchBtn.style.display = '';\n self._hideOptionsTimeout = null;\n if (self._options.calculateOnMarkerMove) {\n self._onSearch();\n }\n };\n /** Clears the timeout that is preventing the route range options panel from appearing. */\n _this._onMarkerDargStart = function () {\n if (_this._hideOptionsTimeout) {\n clearTimeout(_this._hideOptionsTimeout);\n _this._hideOptionsTimeout = null;\n }\n };\n /** Event handler for when a the container has focus and arrow keys are used to adjust the position of the marker. */\n _this._onContainerKeyDown = function (e) {\n //If the top level container has focus and an arrow key is pressed, move the marker.\n if (e.keyCode > 36 && e.keyCode < 41 && e.target.classList.contains('azure-maps-control-container')) {\n var self_1 = _this;\n //Convert the position of the marker to pixels based on the current zoom level of the map, then offset it accordingly. \n var zoom = self_1._map.getCamera().zoom;\n var pixel = azmaps.math.mercatorPositionsToPixels([self_1._marker.getOptions().position], zoom)[0];\n var offset = self_1._arrowKeyOffset;\n //Left arrow = 37, Up arrow = 38, Right arrow = 39, Down arrow = 40\n if (e.keyCode === 37) {\n pixel[0] -= offset;\n }\n else if (e.keyCode === 38) {\n pixel[1] -= offset;\n }\n else if (e.keyCode === 39) {\n pixel[0] += offset;\n }\n else if (e.keyCode === 40) {\n pixel[1] += offset;\n }\n var pos = azmaps.math.mercatorPixelsToPositions([pixel], zoom)[0];\n self_1._marker.setOptions({\n position: pos\n });\n self_1._settings.origin = pos;\n if (self_1._options.calculateOnMarkerMove) {\n if (self_1._markerKeyMoveTimeout) {\n clearTimeout(self_1._markerKeyMoveTimeout);\n }\n self_1._markerKeyMoveTimeout = setTimeout(function () {\n self_1._onSearch();\n }, self_1._markerMoveSearchDelay);\n }\n e.preventDefault();\n e.stopPropagation();\n }\n };\n /** Event handler for when the map resizes. */\n _this._mapResized = function () {\n var self = _this;\n var mapSize = self._map.getMapContainer().getBoundingClientRect();\n //If the map is 750 pixels wide or more, offset the position of the control away from the edge a little.\n var min = '';\n var delay = 0;\n var position = self._options.position;\n if (mapSize.width < 750 || (position === 'center' && mapSize.height < 600)) {\n min = '-min';\n //If the map is less 750 pixels width or 600 pixels high when centered, delay the display of options in the container so that the user has a chance to move the marker before it is covered up. \n //This delay will be be short circuited when the user stops dragging the marker.\n delay = 5000;\n }\n else if (position !== 'center') {\n //Check to see see if there are any other controls on the same side as this control. If not, then minimize the gap between the control and the side of the map.\n var controlContainers = Array.from(self._map.controls['controlContainer'].children);\n var cnt_1 = 0;\n controlContainers.forEach(function (c) {\n if (c.classList.toString().indexOf(position) > -1) {\n cnt_1 += c.children.length;\n }\n });\n if (cnt_1 === 0) {\n min = '-min';\n }\n }\n self._container.classList.remove('left', 'right', 'center', 'left-min', 'right-min', 'center-min');\n self._container.classList.add(position + min);\n self._showOptionsDelay = delay;\n };\n var self = _this;\n if (options.markerOptions) {\n Object.assign(options.markerOptions, self._options.markerOptions);\n }\n self._options = Object.assign(self._options, options || {});\n self._marker = new azmaps.HtmlMarker(Object.assign(self._options.markerOptions, { draggable: true }));\n return _this;\n }",
"function panToCityHall(){\n\n // let startPoint = new google.maps.LatLng(43.044240, -87.906446);\n map.panTo(new google.maps.LatLng(43.044240, -87.906446));\n}",
"createElement() {\r\n super.createElement();\r\n\r\n // call setTimeout without passing in a time param. (never seen that before)\r\n // See: <http://www.w3schools.com/jsref/met_win_settimeout.asp> setTimeout\r\n // calls a function or evaluates and expression after a set amount of time.\r\n // if we dont pass in any time, we are just telling it to call setTimeout,\r\n // then do the next thing.\r\n setTimeout(() => {\r\n var map = new window.google.maps.Map(document.getElementById('map'), {\r\n zoom: 13,\r\n center: this.centerOfMap\r\n });\r\n // loop over data. create array with lat and long. Get the \r\n // latlong data off of vehicle, and split it into an array based\r\n // on space between lat long. so basically, this is saying, lat and\r\n // long is equal to the array produced from calling split .latlong\r\n // value.\r\n for (let vehicle of this.data) {\r\n let [lat, long] = vehicle.latLong.split(' ');\r\n console.log('lat:' + lat);\r\n // pass in lat and long from array to LatLng method \r\n // on google maps api to create myLatLng\r\n let myLatLng = new window.google.maps.LatLng(lat, long);\r\n \r\n var marker = new window.google.maps.Marker({\r\n position: myLatLng,\r\n map: map\r\n });\r\n \r\n marker.setMap(map);\r\n }\r\n \r\n }, 0);\r\n\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
timerNav is how I created the timer | function timerNav() {
if (timerStart == false) {
setInterval(nextStudent, 5000);
timerStart = true;
};
} | [
"function timerJuego() {\n // Genera el letrero del timer\n mensajeTimer = pad(minutos) + \":\" + pad(segundos);\n // Muestra el timer en la página\n $(\"#labelTimer\").text(mensajeTimer);\n // Verifica si se debe pasar el siguiente minuto\n if (segundos == 59) {\n segundos = -1;\n minutos++;\n }\n // Incrementa los segundos\n segundos++;\n }",
"function timer() {\n var timeleft = 29;\n var downloadTimer = setInterval(function() {\n if (timeleft <= 0) {\n clearInterval(downloadTimer);\n playEnd();\n document.getElementById(\"time\").innerHTML = \"The End!\";\n document.getElementById(\"go-home\").innerHTML = `\n <a href=\"index.html\">\n <button class=\"btn-options\">Home</button>\n </a> `;\n document.getElementById(\"play-again\").innerHTML = `\n <button class=\"btn-options\" >Play Again</button> `;\n\n } else {\n document.getElementById(\"time\").innerHTML = timeleft + \" s\";\n }\n timeleft -= 1;\n }, 1000);\n}",
"init() {\n this.#elemetn = this.getElement(this.UiSelectors.timer);\n }",
"function timer() {\n d3.range(nodes.length).map(function (i) {\n var curr_node = nodes[i],\n curr_moves = curr_node.moves;\n\n // Time to go to next activity\n if (curr_node.next_move_time == curr_minute) {\n if (curr_node.moves == curr_node.sched.length - 1) {\n curr_moves = 0;\n } else {\n curr_moves += 1;\n }\n\n // Subtract from current activity count\n act_counts[curr_node.act] -= 1;\n\n // Move on to next activity\n curr_node.act = curr_node.sched[curr_moves].act;\n\n // Add to new activity count\n act_counts[curr_node.act] += 1;\n\n curr_node.moves = curr_moves;\n curr_node.cx = foci[curr_node.act].x;\n curr_node.cy = foci[curr_node.act].y;\n\n nodes[i].next_move_time += nodes[i].sched[curr_node.moves].duration;\n }\n\n });\n\n force.resume();\n curr_minute += 1;\n\n // Update percentages\n label.selectAll(\"tspan.actpct\")\n .text(function (d) {\n return readablePercent(act_counts[d.index]);\n });\n\n // Update time\n var true_minute = curr_minute % 1440;\n d3.select(\"#current_time\").text(minutesToTime(true_minute));\n\n setTimeout(timer, speeds[USER_SPEED]);\n }",
"function timer() {\n nodes.forEach(function (o, i) {\n o.timeleft -= 1;\n if (o.timeleft == 0 && o.istage < o.stages.length - 1) {\n // Decrease count for previous group.\n groups[o.group].cnt -= 1;\n // Update current node to new group.\n o.istage += 1;\n o.group = o.stages[o.istage].grp;\n o.timeleft = o.stages[o.istage].duration;\n // Increment count for new group.\n groups[o.group].cnt += 1;\n }\n });\n // Increment time.\n time_so_far += 1;\n d3.select(\"#timecount .cnt\").text(time_so_far);\n // Update counters.\n svg.selectAll('.grpcnt').text(d => groups[d].cnt);\n // Do it again.\n d3.timeout(timer, 1000);\n } // @end timer()",
"function topSugSlide() {\n if (timer !== undefined) {\n clearInterval(timer); // stop previous cycle\n }\n timer = cycle(); // set new cycle\n}",
"function startBattleTimer() {\n // Swap button\n document.getElementById('startButton').remove();\n document.getElementById('attackButton').classList.remove('d-none');\n document.getElementById('retreatButton').classList.remove('d-none');\n \n // Add battle log entry\n document.getElementById(\"battleLog\").append(\"Battle Commenced!\");\n \n // Start Battle\n engageBattle();\n}",
"function timerCounter() {\n\tvar currentDate = new Date();\n\tvar remainingNow = targetDate.valueOf() - currentDate.valueOf();\n\n\n if (! roundStarting) {\n\t\tif (remainingNow < 0) {\n\t\t\t$('#time').html(\"(Kierros päättynyt)\");\n\t\t\troundEnded();\n\t\t} else {\n\t\t\tvar seconds = Math.floor((remainingNow / 1000)) % 60;\n\t\t\tvar minutes = Math.floor((remainingNow / 1000) / 60);\n\t\t\tif (seconds < 10) { seconds = '0' + seconds; }\n\t\t\t$(\"#time\").text(minutes + \":\" + seconds);\n\t\t}\n\t\n\t\tif (remainingNow < 60000) {\n\t\t\tif (lastMinute == false) {\n\t\t\t\tlastMinute = true;\n\t\t\t\tupdateButtons();\n\t\t\t}\n\t\t} else {\n\t\t\tif (lastMinute == true) {\n\t\t\t\tlastMinute = false;\n\t\t\t\tupdateButtons();\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (remainingNow < 0) {\n\t\t\t$('#time').html(\"Alkaa: 0:00\");\n//\t\t\troundEnded();\n\t\t} else {\n\t\t\tvar seconds = Math.floor((remainingNow / 1000)) % 60;\n\t\t\tvar minutes = Math.floor((remainingNow / 1000) / 60);\n\t\t\tif (seconds < 10) { seconds = '0' + seconds; }\n\t\t\t$(\"#time\").text(\"Alkaa: \" + minutes + \":\" + seconds);\n\t\t}\n\t}\n\n}",
"_removeTimer() {\n // use clearInterval() to remove your interval. You need to include the timer reference\n\n }",
"function timer () {\n var intervalId = setInterval(function() {\n if (currentGame.remainingTime > 0) {\n $('#timer').html(currentGame.remainingTimeString);\n timerColor();\n } else {\n $('#timer').html('0');\n clearTimer(intervalId);\n $('.color-1').css('background', 'black');\n $('.color-2').css('background', 'black');\n $('.color-1').css('border', '2px solid black');\n $('.color-2').css('border', '2px solid black');\n $('.color-1').html('GAME');\n $('.color-2').html('OVER!');\n };\n }, 100);\n}",
"function fastupdateGodTimer(){\r\n\t\r\n\t//Check if round is ongoing\r\n\tif(godtimer_in_seconds > 0){\r\n\t\tgodtimer_in_seconds = godtimer_in_seconds - 0.2;\r\n\t\t////console.log(godtimer_in_seconds);\r\n\t\tgod_numhours = Math.floor(godtimer_in_seconds / 3600);\r\n\t\tgod_numminutes = Math.floor((godtimer_in_seconds % 3600) / 60);\r\n\t\tgod_numseconds = parseFloat((godtimer_in_seconds % 3600) % 60).toFixed(0);\r\n\t\t\r\n\t\ta_godTimer = god_numhours + \"h \" + god_numminutes + \"m \" + god_numseconds + \"s \";\r\n\t\tgodtimerdoc.textContent = a_godTimer;\r\n\t}\r\n}",
"function timer() {\n number--\n $(\"#show-number\").html(\"<h2>\" + number + \"</h2>\");\n if (number === 0) {\n stop();\n }\n }",
"function startSlideShowTimer()\n{\n //clear out the user timer and set to null\n if (timers.user !== null){\n clearTimeout(timers.user);\n timers.user = null;\n }\n\n //activate the slideshow\n activateSlideShow();\n\n //set a timer for the slideshow\n timers.slideShow = setTimeout(function () {\n //go to next slide\n moveToNextSlide(1);\n startSlideShowTimer();\n }, 5000); \n}",
"function OnTimeSliderClick()\n{\n\t\n\tnDomain = DVD.CurrentDomain;\n\tif (nDomain == 2 || nDomain == 3) \n\t\treturn;\n\n\tlTitle = DVD.CurrentTitle;\n\ttimeStr = GetTimeSliderBstr();\n\n\tDVD.PlayAtTimeInTitle(lTitle, timeStr);\n\tDVD.PlayForwards(DVDOpt.PlaySpeed);\n}",
"function setTimerEl(){\n document.getElementById('time').innerText=timer;\n}",
"function e_timer() {\n if (!localStream)\n getVideo();\n\n if (peerConnection == null) {\n f_showTextMessage(\"Not connected\")\n if (started) start(true);\n }\n else\n f_showTextMessage(peerConnection.iceConnectionState);\n}",
"pauseTimer() { MySearchTimer.paused = true; if (MySearchTimer.paused) MySearchUI.nowPaused(); }",
"function battleTimer() {\n battleCountdown--;\n // $(\"#battle-timer\").html(\"<h3>\" + \"Battle in: \" + battleCountdown + \"</h3>\");\n $(\"#battle-timer\").html(\"<h3>Battle!</h3><h3>\" + battleCountdown + \"</h3>\");\n if (battleCountdown === 0) {\n stopBattleTimer();\n $(\"#card-timer\").hide();\n var winner = determineWinner();\n updateWinCountAndResetSelection(winner);\n displayResults(winner);\n transitionToNextRound();\n }\n }",
"function timerControl( pAction ) {\n console.log( \"Entered timer control, action = '\" + pAction + \"'\" );\n\tif ( pAction === \"start\" ) {\n\t\tptrTimer.innerHTML = secondsPerQuestion;\n\t\tsecondsRemaining = secondsPerQuestion;\n\t\twindow.clearInterval( timer ); // Ensure that the timer has stopped\n\t\ttimer = window.setInterval( updateTimer, 1000 );\n\t\tpauseTimer = false;\n\t} else if ( pAction === \"stop\" ) {\n\t\twindow.clearInterval( timer );\n\t} else if ( pAction === \"pause\" ) {\n\t\tconsole.log( \"Pausing timer: \" + pauseTimer );\n\t\tpauseTimer = ! pauseTimer;\n if ( pauseTimer ) {\n ptrPause.innerHTML = \"Resume Game\"\n } else {\n ptrPause.innerHTML = \"Pause Game\" \n }\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reports a list of PR base on the input array of github PR json objects | reportPRList( dataPR ) {
if( dataPR === undefined ) {
return(
<div><h3>Array was undefined</h3></div>
);
}
if( dataPR.length === 0 ) {
return(
<div><h3>Found no data</h3></div>
);
}
return(
dataPR.map( eachElement => (
<PullRequest key={eachElement.id} content={eachElement}/>
))
);
} | [
"reportPRListDetailed( dataPR ) {\n if( dataPR === undefined ) {\n return(\n <div><h3>Array was undefined</h3></div>\n );\n }\n\n if( dataPR.length === 0 ) {\n return(\n <div><h3>Found no data</h3></div>\n );\n }\n\n var githubPRsDataDetailed;\n\n githubPRsDataDetailed = dataPR.map(\n eachElement => (\n <PullRequest key={eachElement.id} content={eachElement}/>\n )\n );\n\n return githubPRsDataDetailed;\n }",
"async getOpenPRs(ref) {\n const { data: prs } = await this.api.pulls.list({\n ...this.userInfo,\n state: 'open',\n base: ref.toBranch,\n head: ref.fromBranch,\n });\n return prs;\n }",
"function extractIssues(html, repoName, topicName) {\n let selTool = cheerio.load(html);\n let IssuesAnchAr = \n selTool(\"a.Link--primary.v-align-middle.no-underline.h4.js-navigation-open.markdown-title\");\n let arr = [];\n for (let i = 0; i < IssuesAnchAr.length; i++) {\n let name = selTool(IssuesAnchAr[i]).text();\n let link = selTool(IssuesAnchAr[i]).attr(\"href\");\n arr.push({\n \"Name\": name,\n \"Link\": \"https://github.com\" + link\n })\n }\n //console.log(arr);\n //path of pdf file\n let filePath = path.join(__dirname, topicName, repoName + \".pdf\");\n\n //instance for pdf file functions\n let pdfDoc = new PDFDocument;\n\n //save the file\n pdfDoc.pipe(fs.createWriteStream(filePath));\n\n //add contents to the file\n pdfDoc.text(JSON.stringify(arr));\n\n //end the stream\n pdfDoc.end();\n // fs.writeFileSync(filePath, JSON.stringify(arr));\n // file write \n console.table(arr);\n}",
"async function getPr() {\n const params = {\n owner: item.owner,\n repo: item.repo,\n pull_number: item.number,\n };\n\n const pr = await client.rest.pulls.get(params);\n core.debug(`getPr: ${JSON.stringify(pr)}`);\n return undefined;\n}",
"async getApprovals(prNum) {\n let call =\n \"https://api.github.com/repos/\" +\n this.props.content +\n \"/pulls/\" +\n prNum +\n \"/reviews\";\n let reviews = await this.fetchGithub(call);\n let sum = 0;\n for (let i = 0; i < reviews.length; i++) {\n if (reviews[i].state == \"APPROVED\") sum++;\n }\n return sum;\n }",
"parseGithubPRJson( githubPRJsonSet = this.githubPRsData, condition, key ) {\n var parsedPRSet = [];\n\n if( key === undefined || key === null || key === '' ) {\n return githubPRJsonSet;\n }\n\n if( condition === 'byAll' ) {\n return githubPRJsonSet;\n }\n\n if( condition === 'byName' ) {\n parsedPRSet = githubPRJsonSet.filter( eachElement => (\n eachElement.user.login === key\n ));\n }\n\n if( condition === 'byMergeStatus' && key === 'merged' ) {\n parsedPRSet = githubPRJsonSet.filter( eachElement => (\n eachElement.merged_at !== null\n ));\n }\n\n return parsedPRSet;\n }",
"function List(github, data) {\n this.github = github;\n this.data = data;\n if (data.url == null) {\n throw \"Missing required `data.url`\";\n }\n \n this.pages = [];\n this.pageCount = -1;\n this.size = 0;\n }",
"createIssueListofMilestone() {\n let milestoneIssues = [];\n let milestoneTitle = this.props.data[\"title\"];\n this.props.issueList.forEach(function (issue) {\n if (issue[\"milestone\"] != null) {\n if (issue[\"milestone\"][\"title\"] === milestoneTitle) {\n let object = {\n url: issue[\"url\"],\n html_url: issue[\"html_url\"],\n title: issue[\"issue_title\"],\n };\n milestoneIssues.push(object)\n }\n }\n });\n\n return milestoneIssues;\n }",
"function updateList(repos) {\n var $ul = $(\"<ul/>\");\n \n // For each repository, create an item that when clicked on is expected\n // to display further information of the repository.\n for (var i in repos) {\n var repo = repos[i];\n\n\n // Give the link a special class for delegating clicks, store the\n // repository as data for the link, and give a defined text string for\n // display.\n var $link = $('<a href=\"#\" class=\"github-alert\"/>').\n data(\"repo\", repo).\n text(repo.owner + \"/\" + repo.name);\n\n // Add the item to the list\n var $li = $('<li/>');\n $li.append($link);\n $ul.append($li);\n }\n\n // Update the results to display the list\n $results.html($ul);\n }",
"async function getAllGHPullRequests(owner, repo) {\n let allPullRequests = []\n let page = 1;\n const perPage = 100;\n\n while (true) {\n await sleep(2000);\n // get a paginated list of pull requests\n const pullRequests = await github.pulls.list({owner: owner, repo: repo, state: 'all', per_page: perPage, page: page });\n\n // if this page has zero PRs then we are done!\n if (pullRequests.data.length === 0)\n break;\n\n // join this list of PRs with the master list\n allPullRequests = allPullRequests.concat(pullRequests.data);\n\n // if there are strictly less PRs on this page than the maximum number per page\n // then we can be sure that this is all the PRs. No use querying again.\n if (pullRequests.data.length < perPage)\n break;\n\n // query for the next page of PRs next iteration\n page++;\n }\n\n return allPullRequests;\n}",
"function getRepoLinks(html) {\n let selTool = cheerio.load(html);\n let topicNameElem = selTool(\".h1-mktg\");\n let repolinks = selTool(\"a.text-bold\");\n // console.log(topicNameElem.text());\n let topicName = topicNameElem.text().trim();\n dirCreater(topicName);\n for (let i = 0; i < 8; i++) {\n let repoPageLink = selTool(repolinks[i]).attr(\"href\");\n //console.log(repoPageLink);\n let repoName = repoPageLink.split(\"/\").pop();\n //let repoName = repoPageLink.split(\"/\");\n //console.log(repoName);\n repoName = repoName.trim();\n // console.log(repoName);\n createFile(repoName, topicName);\n let fullRepoLink = \"https://github.com\" + repoPageLink + \"/issues\";\n //console.log(fullRepoLink);\n getIssues(repoName, topicName, fullRepoLink);\n }\n console.log(\"`````````````````````````\");\n}",
"showRepos(repos){\r\n let output = ' <h3>Latest Repos</h3>';\r\n console.log(repos);\r\n repos.forEach(repo => {\r\n output +=`\r\n <div class=\"repo-list row\">\r\n <span class=\"repo-name col-md-6\"><a href=\"${repo.html_url}\">${repo.name}</a></span>\r\n <button type=\"button\" class=\"btn btn-primary\">\r\n Stars <span class=\"badge badge-light\">${repo.stargazers_count}</span>\r\n </button>\r\n <button type=\"button\" class=\"btn btn-primary\">\r\n Watchers <span class=\"badge badge-light\">${repo.watchers}</span>\r\n </button>\r\n <button type=\"button\" class=\"btn btn-primary\">\r\n Forks <span class=\"badge badge-light\">${repo.forms}</span>\r\n </button>\r\n </div>\r\n `;\r\n\r\n });\r\n document.querySelector('.repos').innerHTML=output;\r\n }",
"get withPullRequest() {\n return issues.filter(obj => obj.pull_request !== undefined\n && obj.pull_request !== null)\n .map(obj => obj.id);\n }",
"function getGithubPerfilRepos() {\n fetch(URL_GITHUB_PROFILE_REPOS)\n .then((response) => response.json())\n .then((data) => {\n data.map((item) => {\n list.innerHTML += `\n <li>${item.name}</li>\n `\n })\n })\n}",
"getV3ProjectsIdRepositoryCommitsShaComments(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 ta\n/*let opts = {\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3ProjectsIdRepositoryCommitsShaComments(incomingOptions.id, incomingOptions.sha, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"function updateContributors() {\n const contributors = {}\n Promise.all(repos.map(repo => fetch('http://api.github.com/repos/' + repo + '/contributors').then(res => res.json())))\n .then(jsons => {\n jsons.forEach(json => {\n json\n .filter(item => !githubExcludes.includes(item.login))\n .forEach(item => {\n const contributor = contributors[item.id]\n if (contributor) {\n contributor.count += item.contributions\n } else {\n contributors[item.id] = {\n // id: item.id,\n name: item.login,\n logo: item.avatar_url + '&s=' + getLogoSize(item),\n link: item.html_url,\n count: item.contributions\n }\n }\n })\n })\n const sortedContributors = Object.values(contributors).sort((a, b) => b.count - a.count)\n fs.writeFileSync(__dirname + '/../data/contributors.json', JSON.stringify(sortedContributors, null, 2))\n })\n .catch(err => {\n console.error(err.stack)\n process.exit(1)\n })\n}",
"function createReview(data, title) {\r\n var reviewList = [];\r\n // const regTitle = new RegExp('^' + title, \"i\");\r\n data[\"results\"].forEach(function(currObj) {\r\n // if (regTitle.test(currObj[\"display_title\"])) {\r\n if (currObj[\"display_title\"] == title) {\r\n // console.log(currObj[\"display_title\"]);\r\n let review = new reviewItem;\r\n\r\n review.reviewLink = currObj[\"link\"][\"url\"];\r\n review.title = currObj[\"headline\"];\r\n review.author = currObj[\"byline\"];\r\n\r\n reviewList.push(review);\r\n }\r\n });\r\n\r\n // create the html\r\n let s = \"\";\r\n reviewList.forEach((currReview) => {\r\n s += \"<a href=\\\"\" + currReview.reviewLink + \"\\\" target=\\\"_blank\\\">\";\r\n s += currReview.title;\r\n s += \"</a> by \" + titleCase(currReview.author) + \"<br>\";\r\n });\r\n return s;\r\n}",
"function updateMilestonePage(sprSheet,milestone,issues) {\n\n var mileSheet=sprSheet.getSheetByName(milestone)\n if ( mileSheet == null ) return\n if ( mileSheet.getMaxRows() == 1 ) return // no PRs, nothing to do\n \n //get the existing sheet information\n var range=mileSheet.getRange(2,1,mileSheet.getMaxRows()-1,6)\n var data=range.getValues()\n // \n \n // otherwise, loop over the data and look for updates\n var foundPRs={}\n for ( var i in issues) { //issues is the new updated information\n var iss = issues[i]\n var pr = iss['prNum']\n var sigInfo=parseSigInfo(iss['labels'])\n var approvedSigs=sigInfo[0]\n var pendingSigs=sigInfo[1]\n var testsPassed=sigInfo[2]\n \n //check this against the info we have from before\n for ( var row in data ) {\n if ( data[row][0] != pr ) {\n continue;\n }\n foundPRs[data[row][0]]=1\n\n //now just update information as needed to match current github state\n if ( data[row][3] != approvedSigs ) {\n mileSheet.getRange(parseInt(row)+2,4).setValue(approvedSigs) //add one for 0->1 and one for the header row\n }\n if ( data[row][4] != pendingSigs ) {\n mileSheet.getRange(parseInt(row)+2,5).setValue(pendingSigs) \n }\n if ( data[row][5] != testsPassed ) {\n mileSheet.getRange(parseInt(row)+2,6).setValue(testsPassed)\n }\n break // no need to keep going\n } \n }\n // done updating old information\n \n // hide rows for PRs that are closed already\n for ( var row in data) {\n if ( foundPRs[data[row][0]] != 1 ) {\n mileSheet.hideRows(parseInt(row)+2)\n }\n }\n \n // now add new rows for new PRs\n var data=[]\n var formulas=[]\n for ( var i in issues ) { //this code must be repeated elsewhere - could be consolidated\n var iss=issues[i]\n var pr=iss['prNum']\n if ( foundPRs[pr] == 1 ) {\n continue\n }\n\n var sigInfo=parseSigInfo(iss['labels'])\n var approvedSigs=sigInfo[0]\n var pendingSigs=sigInfo[1]\n var testsPassed=sigInfo[2]\n var comments=''\n data.push( [ extractDate(iss['date']),iss['title'],approvedSigs,pendingSigs,testsPassed,comments] )\n formulas.push( ['=HYPERLINK(\"http://www.github.com/cms-sw/cmssw/pull/'+pr+'\",\"'+pr+'\")'] )\n }\n \n //in one set of commands, add all the new rows\n var nCols=7\n var nNewRows=data.length\n if ( nNewRows > 0 ) {\n mileSheet.insertRowsAfter(1,nNewRows)\n var rangeD=mileSheet.getRange(2,2,nNewRows,nCols-1)\n var rangeF=mileSheet.getRange(2,1,nNewRows,1)\n rangeD.setValues(data)\n rangeF.setFormulas(formulas)\n }\n \n \n // Protect the active sheet, then remove all other users from the list of editors.\n var protection = mileSheet.protect().setDescription('Protected sheet');\n \n // Ensure the current user is an editor before removing others. Otherwise, if the user's edit\n // permission comes from a group, the script will throw an exception upon removing the group.\n var me = Session.getEffectiveUser();\n protection.addEditor(me);\n protection.removeEditors(protection.getEditors());\n if (protection.canDomainEdit()) {\n protection.setDomainEdit(false);\n }\n\n //redo the formatting with the new rows\n var nRows=mileSheet.getLastRow()\n if ( nRows>1 ) {\n var range=mileSheet.getRange(2,nCols,nRows-1,1)\n protection.setUnprotectedRanges([range])\n }\n mileSheet.getRange(1,1,nRows,nCols).setWrap(true)\n \n}",
"function updateORP(ssheet,issues,lastORPDetails,recentReleases) {\n var sprSheet=SpreadsheetApp.open(DriveApp.getFileById(ssheet))\n var genSheet=makeGeneralPage(sprSheet,recentReleases,lastORPDetails) \n var releases=releaseList()\n for ( r in releases ) {\n var release=releases[r]\n var mileSheet=updateMilestonePage(sprSheet,release,issues[release])\n } \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays a specific beer object to the user. | function displayBeer(beer) {
console.log(beer);
$(".beerList").hide();
// Assign beer display stuff
$('.singleBeer').show();
} | [
"function apiShow(req, res) {\n //console.log('GET /api/breed/:name');\n // return JSON object of specified breed\n db.Breed.find({name: req.params.name}, function(err, oneBreed) {\n if (err) {\n res.send('ERROR::' + err);\n } else {\n res.json({breeds: oneBreed});\n }\n });\n}",
"function getBeerById(req, res) {\n brewerydbModel\n .getBeerById(req.params.beerid)\n .then(function(beerData) {\n res.json(beerData);\n });\n }",
"function showBookShelf() {}",
"function renderMain(response) {\n\tBurger.getAllBurgers()\n\t\t.then((burgers) => {\n\t\t\tburgers = burgers.map( el => {\n\t\t\t\treturn {\n\t\t\t\t\tid: el.id,\n\t\t\t\t\tburger_name: el.name,\n\t\t\t\t\tdevoured: el.devoured\n\t\t\t\t};\n\t\t\t} )\n\t\t\t// render the page\n\t\t\tresponse.render(\"index\", { burgers: burgers });\n\t\t});\n}",
"function showBook(book, div) {\n console.log(\"showBook()\", book);\n\n // find the book detail element\n const bookDetail = document.getElementById(\"book-detail\");\n\n // populate the template with the data in the provided book\n bookDetail.getElementsByClassName(\"title\")[0].innerText = book.fields.title; //\n bookDetail.getElementsByClassName(\"description\")[0].innerText =\n book.fields.description;\n bookDetail.getElementsByClassName(\"more\")[0].href = book.fields.more;\n bookDetail.getElementsByClassName(\"cover-image\")[0].src =\n book.fields.cover_image[0].url;\n\n // remove the .active class from any book spines that have it...\n const shelf = document.getElementById(\"shelf\");\n const bookSpines = shelf.getElementsByClassName(\"active\");\n for (const bookSpine of bookSpines) {\n bookSpine.classList.remove(\"active\");\n }\n // ...and set it on the one just clicked\n div.classList.add(\"active\");\n\n // reveal the detail element, we only really need this the first time\n // but its not hurting to do it more than once\n bookDetail.classList.remove(\"hidden\");\n}",
"function getBeers() {\n //\n //\n //beers.list(); listBeer\n //\n var req = gapi.client.birra.beers.list();\n req.execute(function(data) {\n $(\"#results\").html('');\n showList(data); \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}",
"function displayBreed(image) {\r\n $('#breed_image').attr('src', image.url);\r\n $(\"#breed_data_table tr\").remove();\r\n \r\n var breed_data = image.breeds[0]\r\n $.each(breed_data, function(key, value) {\r\n // as 'weight' and 'height' are objects that contain 'metric' and 'imperial' properties, just use the metric string\r\n if (key == 'weight' || key == 'height') value = value.metric\r\n // add a row to the table\r\n $(\"#breed_data_table\").append(\"<tr><td>\" + key + \"</td><td>\" + value + \"</td></tr>\");\r\n });\r\n }",
"display() {\n console.log(`Title: ${this.title}\\nAuthor: ${this.author}\\nPrice: ${this.price}`);\n }",
"async function show(req, res) {\n const habits = await Habit.find({\n user: req.params.userid\n })\n res.json(habits);\n}",
"function displayCurrentBooking() {\n\trebu.getCurrentBooking(function(booking) {\n\t\t// create vehicle marker\n\t\tbookedVehicle = booking.vehicle;\n\t\tbookedVehicle.marker = createVehicleMarker(bookedVehicle, map, true);\n\t\t\n\t\t// display the card\n\t\tvar currentBookingCard = view.currentBookingCard(booking, findBookedVehicle, extendBooking, endBooking, onBookingExpire);\n\t\t\t\n\t\t// fancy transition\n\t\tcurrentBookingCard.className = \"transition-start\";\n\t\tsetTimeout(function() {\n\t\t\tcurrentBookingCard.className = \"\";\n\t\t}, 200);\n\t\tdocument.body.appendChild(currentBookingCard);\n\t});\n}",
"function makeBeerObject(apiBeer) {\n var beer = new Beer();\n beer.id = apiBeer.id;\n beer.name = apiBeer.name;\n beer.styleId = apiBeer.style.id;\n beer.styleName = apiBeer.style.name;\n beer.styleDescription = apiBeer.style.description;\n beer.categoryName = apiBeer.style.category.name;\n if (apiBeer.abv) { beer.abv = apiBeer.abv; } // check if provided\n if (apiBeer.ibu) { beer.ibu = apiBeer.ibu; } // check if provided\n beer.isOrganic = apiBeer.isOrganic;\n if (apiBeer.glass) { beer.glassName = apiBeer.glass.name; } // check if provided\n if (apiBeer.foodPairings) { beer.foodPairings = apiBeer.foodPairings; } // check if provided\n if (apiBeer.servingTemperature) { beer.servingTemperature = apiBeer.servingTemperature; } // check if provided\n if (apiBeer.year) { beer.year = apiBeer.year; } // check if provided\n if (apiBeer.labels) { // check if provided\n beer.imgLinkSmall = apiBeer.labels.icon;\n beer.imgLinkLarge = apiBeer.labels.large;\n }\n beer.price = ((Math.random() * (6 - 2 + 1)) + 2).toFixed(2); // random number between 20 and 2, with 2 decimals\n if (apiBeer.description) { beer.description = apiBeer.description; } // check if provided\n beerList.push(beer);\n}",
"function engineerCard(engineerObj) {\n var name = engineerObj.getName();\n var id = engineerObj.getID();\n var email = engineerObj.getEmail();\n var github = engineerObj.getGithub();\n var role = engineerObj.getRole();\n\n var html = `<div class=\"card\">\n <h4 class=\"card-header\" id=\"name\">`+ name + `</h4>\n <h4 class=\"card-header\" id=\"name\">`+ `<i class=\"fas fa-wrench\"></i>` + role + `</h4>\n <div class=\"card-body\">\n <p class=\"card-text\">ID : `+ id + `</p>\n <p class=\"card-text\">Email : <a href=\"mailto:`+email+`\">`+email+`</a></p>\n <p class=\"card-text\">Github : <a href=\"https://github.com/`+github+`\">`+github+`</a></p>\n </div>\n </div>`;\n return html;\n}",
"function displayBook(){\n document.getElementById(\"reviews\").innerHTML = \"\";\n document.getElementById(\"singlebook\").style.display = \"block\";\n document.getElementById(\"allbooks\").innerHTML = \"\";\n getInfo(this.id);\n getDescription(this.id);\n getReviews(this.id);\n }",
"function displayCreature(object){\n\tvar table = document.getElementById('statsTable');\n\tvar row = table.insertRow(table.rows.length);\n\trow.insertCell(0).appendChild(makeButton(object));\n\tvar requiredAttributes = [object.strength, object.dexterity, object.constitution, object.wisdom, object\n\t.intelligence, object.charisma];\n\tfor (var i = 0; i < requiredAttributes.length; i++) {\n\t\trow.insertCell(i+1).innerHTML = requiredAttributes[i];\n\t} \n\tif (object.playerClass){ \n\t\trow.insertCell(7).innerHTML = object.playerClass;\n\t} else {\n\t\trow.insertCell(7).innerHTML = '';\n\t}\n}",
"function fetchBurgers(){\n fetch(\"http://localhost:3000/burgers\")\n .then(r=>r.json())\n .then(burgers => renderAllBurgers(burgers))\n}",
"function showTeam(e) {\n e.preventDefault();\n $.ajax({\n type: 'GET',\n url: e.target.id,\n success: (response) => {\n let teamObj = new Team(\n response.data.id,\n response.data.attributes.name,\n response.data.attributes.hq,\n response.data.attributes['image-url']\n )\n let newDiv = createNewDiv(\"team_page\")\n let template = Handlebars.compile(document.getElementById('team-show-template').innerHTML)\n let team = template(teamObj)\n newDiv.innerHTML += team\n loadTeamShowLinks();\n }\n });\n}",
"kiesDeBeurt()\n {\n if (this.spelActief) {\n this.gi.innerHTML = \"Het is de beurt aan: Speler \" + this.actieveSpeler + \" <span class='player\"+this.actieveSpeler+\"'>(\" + this.kleurSpeler[this.actieveSpeler] + \")</span>\";\n }\n }",
"function getClozeCard(){\n\n var data = clozeObject[Math.floor(Math.random() * clozeObject.length)];\n var card = new ClozeCard(data.fullText, data.cloze);\n showClozeCards(card.partial, card.cloze, card.fullText);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns adventure chosen from home list | getChosenAdventure(){
return chosenAdventure;
} | [
"getCurrentAdventure() {\n\t\t\treturn currentAdventure;\n\t\t}",
"getCurrentAdventureName() {\n\t\t\treturn currentAdventure.adventure[0].title;\n\t\t}",
"setChosenAdventure(newAdventure){\n\t\t\tchosenAdventure = newAdventure;\n\t\t}",
"function getComputerChoice(){\n\t//constant variables \n\tconst choices = ['Rock', 'Paper', 'Scissors']; //storing options in an array\n\tconst randomNumber = Math.floor(Math.random()*3); //using the maths class to round up to nearest whole number and output random numbers (0-2)\n\treturn choices[randomNumber]; //returns the choice stored in the array\n}",
"viewAnimals() {\n let speciesString = '';\n for (let i =0; i < this.animalSpecies.length; i++) {\n speciesString += i + ') ' + this.animalSpecies[i].name + '\\n';\n }\n let index = prompt(`${speciesString}` + '\\n' +\n '----------------------------------------' + '\\n' +\n 'Enter the index of the species you would like to view:');\n\n if (index > -1 && index < this.animalSpecies.length) {\n this.selectedSpecies = this.animalSpecies[index];\n let description = 'Viewing: ' + this.selectedSpecies.name + '\\n';\n let currentIndex = index\n \n for (let i = 0; i < this.selectedSpecies.pets.length; i++) {\n description += i + ') ' + this.selectedSpecies.pets[i].name \n + ' - ' + this.selectedSpecies.pets[i].breed\n + ' - ' + this.selectedSpecies.pets[i].sex\n + ' - age: ' + this.selectedSpecies.pets[i].age + '\\n';\n }\n let selection = this.showAdoptionMenuOptions(description);\n switch (selection) {\n case '1':\n this.adoptPet(currentIndex);\n break;\n }\n }\n }",
"getAdjective() {\n\n // Prompt user input of a specific adjective category\n const adjective = prompt('Pick an adjective category: Any, Common, Vulgar, or Sexy? ');\n // Change all versions of input to lowercase for handling errors\n const adjectiveLower = adjective.toLowerCase();\n\n // Use selected category to late a string in the given array\n switch (adjectiveLower) {\n case 'any':\n // Store all adjectives categories\n const adjectiveArray = [ common, vulgar, sexy ];\n // Get random index and random category then update the state of adjective in MixedMessages constructor\n const adjectiveCategory = adjectiveArray[this.generateRandomNumber(adjectiveArray)];\n this.adjective = adjectiveCategory[this.generateRandomNumber(adjectiveCategory)];\n break;\n\n case 'common':\n // Get random index and update the state of adjective in MixedMessages constructor\n this.adjective = common[this.generateRandomNumber(common)];\n break;\n\n case 'vulgar':\n this.adjective = vulgar[this.generateRandomNumber(vulgar)];\n break;\n\n case 'sexy':\n this.adjective = sexy[this.generateRandomNumber(sexy)];\n break;\n\n default:\n console.log('Sorry, not an option. Please try again.');\n // Prompt user again for proper input\n this.getAdjective();\n\n }\n // Move on to selecting a noun\n this.getNoun();\n }",
"function placePicker (whoComes, howMuch, whatDo) {\n\n\n\t//This is the big honkin' array that houses the choices\n\tvar choiceList = [\n\t{\n\t\"placeName\": \"Broad St Diner\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Midtown III\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Oregon Diner\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Teri's\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Silk City\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Tom Jones Restaurant\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"South Street Diner\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Melrose Diner\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"West Chester Diner\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Penrose Diner\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Darling's Diner\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Aki\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"The Continental\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"The Cantina\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"El Rey\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"SideCar\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Trolley Car Cafe\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Marathon\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Morimoto\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Parc\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Fork\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Le Bec Fin\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"LaCroix\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Los Catrines Tequilas\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Koo Zee Doo\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Chima Brazilian Steakhouse\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"Butcher and Singer\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"dinner\"\n\t},\n\t{\n\t\"placeName\": \"El Bar\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Locust Bar\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"The Druid's Keep\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"The Dive Bar\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"McGillin's\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Paddy's\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Kung Fu Necktie\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Tattoed Mom\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"JR's South Philly\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Graffiti Bar\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Eulogy\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Fergie's\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Tria\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"National Mechanics\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"P.O.P.E.\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Prohibition\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Monk's\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Good Dog\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Emmanuelle\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Jamonera\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Tinto\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"The Ranstead Room\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Bar Ferdinand\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"XIX\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Voltage Cafe\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Xochitl\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Cuba Libre\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"drinks\"\n\t},\n\t{\n\t\"placeName\": \"Union Transfer\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Johnny Brenda's\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"The Rusty Nail\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Magic Gardens\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Philly Improv Theater\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"ComedySportz\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"The Legendary Dobbs\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Danger Danger\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"The Grape Room\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"low\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"The Tin Angel\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"The Troc\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Ritz Bourse\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Lucky Strike\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"World Cafe Live\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Club Polaris\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Shampoo/Nocturne\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"North Bowl\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Barcade\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"mid\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"The Actor's Center\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Tower Theatre\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Stay Home and Burn Money\",\n\t\"numPeople\": \"me\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Rumor\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Kimmel Center\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Opera Philadelphia\",\n\t\"numPeople\": \"we\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Skirmish Paintball\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Laser Pink Floyd\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"activity\"\n\t},\n\t{\n\t\"placeName\": \"Get in the Van! We're going to Burning Man!\",\n\t\"numPeople\": \"us\",\n\t\"pricePoint\": \"high\",\n\t\"activityType\": \"activity\"\n\t}\n\t];\n\t\n\t//This is the area that choices get pushed to\n\t//This is also what resets the array, because it lives inside the function\n\tvar deciderArray = [];\n\n\t//This is how for loops work\n\tvar i = 0;\n\t\n\tfor (i=0; i < choiceList.length; i++) {\n\t\n\t\t//This takes the passed variables and passes them through this big fat equation\n\t\tif ((choiceList[i].numPeople == whoComes) && (choiceList[i].pricePoint == howMuch) && (choiceList[i].activityType == whatDo)) {\n\t\t\n\t\t//This is the array that gets populated by the previous equation\n\t\tdeciderArray.push(choiceList[i].placeName);\n\t\t\n\t\t\n\t\t\n\t\t}\n\t\n\t}\n\n\t//console.log(deciderArray);\n\t\n\t//This randomizes your decisions for you\n\tvar decision = deciderArray[Math.floor(Math.random() * deciderArray.length)];\n\t\n\t//This returns your decision!\n\t//console.log(decision);\n\t$(\"<p>\" + decision + \"</p>\").appendTo(\"#decisionDiv\");\n\t\n}",
"function chooseword() {\n chosenword = possiblewords[Math.floor(Math.random() * possiblewords.length)].toUpperCase();\n \n}",
"function getProfession(){\n\tvar professions = ['escort', 'servant', 'noble', 'landlord', 'inkeep', 'bartender', 'merchant', 'mercenary',\n\t'craftsman', 'comedian', 'guard', 'soldier', 'urchin', 'outlaw', 'performer',\n\t'convict', 'conman', 'adventurer', 'acolyte', 'hero', 'slave', 'royal'];\n\treturn professions[Math.floor((Math.random() * professions.length) + 1)-1];\n}",
"function SPS() {\n var randomiser = Math.floor(Math.random() * 3); // using randomiser to pick a number\n var computer = [\"scissors\", \"paper\", \"stone\"];\n return computer[randomiser]; // returning the results of the randomised choice\n}",
"function getPsychicLetter () {\n var random = Math.floor(Math.random() *(psychicGuess.length-1));\n \n //Pics random index value from psychicGuess array\n console.log(\"Computer's Choice: \" + psychicGuess[random]);\n return psychicGuess[random];\n}",
"function determineHomeAway(event,game){\n let teams = event.summary.split('at');\n if (teams.length !== 2){\n teams = event.summary.split('vs');\n }\n game.homeTeam = teams[1];\n game.awayTeam = teams[0];\n\n return game;\n}",
"function getLetterChoice(title = 'Let\\s Play!', text = 'Choose your letter') {\r\n\r\n // user modal letter choice\r\n let pickedLetter = '';\r\n\r\n // misc messages to diplay at game start\r\n const startMessages = [\r\n 'Let\\'s Play',\r\n 'Let\\'s Dance',\r\n 'Let\\'s Tango',\r\n 'Let\\'s Waltz',\r\n 'Let\\'s Do This',\r\n 'Let\\'s Rendevous'\r\n ];\r\n\r\n const titleMessage = startMessages[Math.floor(Math.random() * startMessages.length)];\r\n\r\n // sweet alert to determine player letters\r\n swal({\r\n title: titleMessage,\r\n text: text,\r\n type: 'success',\r\n showCancelButton: true,\r\n confirmButtonColor: 'grey',\r\n confirmButtonText: 'X',\r\n cancelButtonText: 'O',\r\n closeOnConfirm: true,\r\n closeOnCancel: true\r\n }, function(isConfirm) {\r\n if (isConfirm) {\r\n pickedLetter = 'X';\r\n } else {\r\n pickedLetter = 'O';\r\n }\r\n // apply the appropriate letter(s) to players\r\n applyPlayerLetters(pickedLetter);\r\n // initialize the game board\r\n\r\n // show gameboard\r\n $gameBoard.removeClass('hidden').animateCss('pulse');\r\n $difficulty.animateCss('flash');\r\n\r\n refreshBoard();\r\n });\r\n\r\n }",
"function chooseRandomGesture() {\n var filteredPlayers = store.getState().players.filter(function (player) {\n return player.isHuman() === true;\n });\n //by now there is only one human player\n var player = filteredPlayers[0];\n var gestures = store.getState().gestures.slice(0);\n //don't set same gesture\n var index = gestures.indexOf(player.getGesture());\n if (index !== -1) {\n gestures.splice(index, 1);\n }\n var gesture = guessStrategy.random(gestures);\n changeGesture(player.getName(), gesture);\n }",
"function chooseHerculesAction(hercules){\n let herculesAction = prompt(`What action would you like to take? \\. 1. kick \\. 2. punch \\. 3. throw \\. 4. regenerate health`);\n switch(herculesAction){\n case '1' :{\n let herculesAction = 'kicks';\n alert('You have chosen Kick');\n hercules.attackPower = 40;\n return herculesAction;\n }\n case '2' :{\n let herculesAction = 'punches';\n alert('you have chosen Punch');\n hercules.attackPower = 50;\n return herculesAction;\n }\n case '3':{\n let herculesAction = 'throws';\n alert('You have chosen throws');\n hercules.attackPower = 20;\n return herculesAction;\n }\n case '4': {\n let herculesAction = 'regenerates health';\n alert('You have chosen Regenerate Health');\n hercules.health += 50;\n hercules.attackPower = 0;\n return herculesAction;\n }\n default: {\n alert('that was not a valid response please try again');\n return chooseHerculesAction(hercules);\n }\n }\n}",
"function sithSelect() {\n\tfor (var l = 0; l < siths.length; l++) {\n\t\tif (siths[l].Eliminated === false) {\n\t\t\tsith_vs.Name(siths[l].Name);\n\t\t\tsith_vs.Health(siths[l].Health);\n\t\t\tsith_vs.Attack(siths[l].Attack);\n\t\t\tsith_vs.Counter(siths[l].Counter);\n\t\t\tsith_vs.Image(siths[l].Image);\n\n\t\t\t// Set the character in the array that is fighting\n\t\t\tsithVsChar = l;\n\n\t\t\t// play a lightsaber start-up sound effect\n\t\t\taudio1 = new Audio(\"assets/audio/saber_engage.wav\");\n\t\t\taudio1.play();\n\n\t\t\t// exit the loop once a Sith has been set\n\t\t\treturn;\n\t\t}\n\t}\n}",
"function chooseVisitLong() {\n (places = [\"Church\", \"Tavern\", \"Market\", \"City Gates\"]),\n (index = rls.keyInSelect(\n places,\n \"You walk to the town to see what it has to offer. \\n The local tavern has artisanal beer and rooms to rest. \\n Nearby marketplace has a variety of shops to browse, e.g. an armory stocked with all sorts of swords and leather armor. \\n You can also see the steeple of a a local church. \\n A little bit further down you can see the high towers of city gates where you can leave the town and continue your journey. \\n Where would you like to go?\"\n ));\n\n switch (index) {\n case 0:\n console.log(`Ok, ${playerName} is going to ` + places[index]);\n visitChurch();\n break;\n case 1:\n console.log(`Ok, ${playerName} is going to ` + places[index]);\n visitTavern();\n break;\n case 2:\n console.log(`Ok, ${playerName} is going to ` + places[index]);\n visitMarket();\n break;\n case 3:\n console.log(`Ok, ${playerName} is going to ` + places[index]);\n visitCityGates();\n break;\n case -1:\n forrestOrTown();\n }\n}",
"static getChoiceById(id) {\n\t\t// Loop through every choice\n\t\tfor (var i = 0; i < storyData.story.scene.choices.length; i++) {\n\t\t\tvar choice = storyData.story.scene.choices[i];\n\t\t\t// If the IDs match, return this choice\n\t\t\tif (choice.name == id) return choice;\n\t\t}\n\t}",
"getRandomDishFromCourse(courseName){\n const dishes = this.courses[courseName];\n return dishes[Math.floor(Math.random() * dishes.length)] //Generate random dish\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Closes the specified stream with the given code. The QuicStream object will be destroyed. | [kStreamClose](id, code) {
const stream = this.#streams.get(id);
if (stream === undefined)
return;
stream.destroy();
} | [
"[kClose](family, code) {\n // Do nothing if the QuicSession has already been destroyed.\n if (this.#destroyed)\n return;\n\n // Set the close code and family so we can keep track.\n this.#closeCode = code;\n this.#closeFamily = family;\n\n // Shutdown all pending streams. These are Streams that\n // have been created but do not yet have a handle assigned.\n for (const stream of this.#pendingStreams)\n stream[kClose](family, code);\n\n // Shutdown all of the remaining streams\n for (const stream of this.#streams.values())\n stream[kClose](family, code);\n\n // By this point, all necessary RESET_STREAM and\n // STOP_SENDING frames ought to have been sent,\n // so now we just trigger sending of the\n // CONNECTION_CLOSE frame.\n this[kHandle].close(family, code);\n }",
"destroy(error) {\n // Destroy can only be called once. Multiple calls will be ignored\n if (this.#destroyed)\n return;\n this.#destroyed = true;\n this.#closing = false;\n\n if (typeof error === 'number' ||\n (error != null &&\n typeof error === 'object' &&\n !(error instanceof Error))) {\n const {\n closeCode,\n closeFamily\n } = validateCloseCode(error);\n this.#closeCode = closeCode;\n this.#closeFamily = closeFamily;\n error = new ERR_QUIC_ERROR(closeCode, closeFamily);\n }\n\n // Destroy any pending streams immediately. These\n // are streams that have been created but have not\n // yet been assigned an internal handle.\n for (const stream of this.#pendingStreams)\n stream.destroy(error);\n\n // Destroy any remaining streams immediately.\n for (const stream of this.#streams.values())\n stream.destroy(error);\n\n this.removeListener('newListener', onNewListener);\n this.removeListener('removeListener', onRemoveListener);\n\n if (error) process.nextTick(emit.bind(this, 'error', error));\n\n const handle = this[kHandle];\n if (handle !== undefined) {\n // Copy the stats for use after destruction\n this.#stats = new BigInt64Array(handle.stats);\n this.#idleTimeout = !!handle.state[IDX_QUIC_SESSION_STATE_IDLE_TIMEOUT];\n // Calling destroy will cause a CONNECTION_CLOSE to be\n // sent to the peer and will destroy the QuicSession\n // handler immediately.\n handle.destroy(this.#closeCode, this.#closeFamily);\n } else {\n process.nextTick(emit.bind(this, 'close'));\n }\n\n // Remove the QuicSession JavaScript object from the\n // associated QuicSocket.\n this.#socket[kRemoveSession](this);\n this.#socket = undefined;\n }",
"function closeChangeStream(timeInMs = 60000, changeStream) {\n\t\treturn new Promise((resolve) => {\n\t\t\tsetTimeout(() => {\n\t\t\t\tconsole.log(\"Closing the change stream\");\n\t\t\t\tchangeStream.close();\n\t\t\t\tresolve();\n\t\t\t}, timeInMs);\n\t\t});\n\t}",
"function stopStream (response) {\n\n\tchild.send('stop');\n\t\n\tresponse.writeHead(200, {\"Content-Type\": \"text/json\"});\n\tresponse.end('{\"status\":\"ok\"}');\n}",
"close(callback) {\r\n debugLog(\"ServerSecureChannelLayer#close\");\r\n // close socket\r\n this.transport.disconnect(() => {\r\n this._abort();\r\n if (_.isFunction(callback)) {\r\n callback();\r\n }\r\n });\r\n }",
"close () {\n if (this.closed) {\n // TODO: this should do something meaningful. May be throw an error or reject a Promise?\n return\n }\n if (!this.closed) {\n this.mediaRoom.close()\n }\n\n /**\n * Call close event\n *\n * @event Call#close\n *\n */\n this.emit('close', this._callId)\n }",
"close(callback) {\n if (this.#state === kSocketDestroyed)\n throw new ERR_QUICSOCKET_DESTROYED('close');\n\n // If a callback function is specified, it is registered as a\n // handler for the once('close') event. If the close occurs\n // immediately, the close event will be emitted as soon as the\n // process.nextTick queue is processed. Otherwise, the close\n // event will occur at some unspecified time in the near future.\n if (callback) {\n if (typeof callback !== 'function')\n throw new ERR_INVALID_CALLBACK();\n this.once('close', callback);\n }\n\n // If we are already closing, do nothing else and wait\n // for the close event to be invoked.\n if (this.#state === kSocketClosing)\n return;\n\n // If the QuicSocket is otherwise not bound to the local\n // port, destroy the QuicSocket immediately.\n if (this.#state !== kSocketBound) {\n this.destroy();\n }\n\n // Mark the QuicSocket as closing to prevent re-entry\n this.#state = kSocketClosing;\n\n // Otherwise, gracefully close each QuicSession, with\n // [kMaybeDestroy]() being called after each closes.\n const maybeDestroy = this[kMaybeDestroy].bind(this);\n\n // Tell the underlying QuicSocket C++ object to stop\n // listening for new QuicServerSession connections.\n // New initial connection packets for currently unknown\n // DCID's will be ignored.\n if (this[kHandle]) {\n this[kHandle].stopListening();\n }\n this.#serverListening = false;\n\n // If there are no sessions, calling maybeDestroy\n // will immediately and synchronously destroy the\n // QuicSocket.\n if (maybeDestroy())\n return;\n\n // If we got this far, there a QuicClientSession and\n // QuicServerSession instances still, we need to trigger\n // a graceful close for each of them. As each closes,\n // they will call the kMaybeDestroy function. When there\n // are no remaining session instances, the QuicSocket\n // will be closed and destroyed.\n for (const session of this.#sessions)\n session.close(maybeDestroy);\n }",
"close()\n\t{\n\n\t\tthis._closed = true;\n\n\t\t// Close the protoo Room.\n\t\tthis._protooRoom.close();\n\n\t\t// Emit 'close' event.\n\t\tthis.emit('close');\n\n\t\t// Stop network throttling.\n\t\tif (this._networkThrottled)\n\t\t{\n\t\t\tthrottle.stop({})\n\t\t\t\t.catch(() => {});\n\t\t}\n\t}",
"close() {\n this[_socket].close();\n\n if (this[_timeout] !== null) {\n clearTimeout(this[_timeout]);\n }\n }",
"static disposeMediaStream(stream){stream.getVideoTracks().forEach(x=>x.stop());stream=undefined;}",
"destroy(error) {\n // If the QuicSocket is already destroyed, do nothing\n if (this.#state === kSocketDestroyed)\n return;\n\n // Mark the QuicSocket as being destroyed.\n this.#state = kSocketDestroyed;\n\n // Immediately close any sessions that may be remaining.\n // If the udp socket is in a state where it is able to do so,\n // a final attempt to send CONNECTION_CLOSE frames for each\n // closed session will be made.\n for (const session of this.#sessions)\n session.destroy(error);\n\n this[kDestroy](error);\n }",
"function endWebSocketConnection(ws, code, message) {\n try {\n console.log('Terminating socket');\n ws.end(code, message);\n } catch(err) {\n console.error('Error ending web socket connection');\n console.error(err);\n }\n}",
"close() {\n // _close will also be called later from the requester;\n this.requester.closeRequest(this);\n }",
"destroyStreamData(){\n\t\tthis.buffer = this.buffer.slice(1,this.buffer.length);\n\t}",
"function decompressStream(stream, headers) {\n var transferEncoding = headers.get('Transfer-Encoding');\n var contentEncoding = headers.get('Content-Encoding');\n if (contentEncoding === 'deflate' || transferEncoding === 'deflate') return stream.pipe(Zlib.createInflate());\n if (contentEncoding === 'gzip' || transferEncoding === 'gzip') return stream.pipe(Zlib.createGunzip());\n return stream;\n}",
"async close() {\n // close chokidar watchers\n if (this.watchers && this.watchers.length) {\n this.watchers.forEach(watcher => {\n watcher.close();\n });\n this.watchers = [];\n }\n // close devMiddleware\n if (this.devMiddleware) {\n await new Promise(resolve => {\n this.devMiddleware.close(() => resolve());\n });\n }\n // stop serverCompiler watching in ssr mode\n if (this.serverWatching) {\n await new Promise(resolve => {\n this.serverWatching.close(() => resolve());\n });\n this.serverWatching = null;\n }\n }",
"close() {\n\t\t// Close all live sockets\n\t\tthis.sockets.forEach(socket => {\n\t\t\tif (!socket.destroyed) socket.end();\n\t\t});\n\n\t\tthis.sockets.clear();\n\t}",
"function wrap(stream) {\n stream.on('error', error => {\n gutil.log(gutil.colors.red(error.message));\n gutil.log(error.stack);\n if (watching) {\n gutil.log(gutil.colors.yellow('[aborting]'));\n stream.end();\n } else {\n gutil.log(gutil.colors.yellow('[exiting]'));\n process.exit(1);\n }\n ringBell();\n });\n return stream;\n}",
"function onPythonClose(err, script){\n if(err) logAndWrite((\"PYTHON: \" + err.toString()).red);\n script.end(function(err, code, signal){onPythonEnd(err, code, signal, script)}); // After pythonsycript closed, end this object and free ressources\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return list of files on the remote directory. | function getRemoteFiles(remote) {
var deferred = Q.defer();
ftp.ls(remote, function(err, res) {
if (err) {
deferred.reject(new Error(err));
} else {
deferred.resolve(res);
}
});
return deferred.promise;
} | [
"function getLocalFiles(local) {\n return fs.readdirSync(local);\n}",
"async function getRemoteFileTree({path, fromName='getRemoteFileTree'}) {\n\treturn new Promise(async (resolve, reject) => {\n\t\ttry {\n\t\t\tconst command = buildRemoteFindCommand(path);\n\t\t\tconst result = await executeRemoteCommand(command, null, `${fromName}::getRemoteFileTree`, true);\n\t\t\n\t\t\tconst absoluteFiles = result.split(path)\n\t\t\t\t.filter(file => /\\.[a-zA-Z]{2,4}$/g.test(file))\n\t\t\t\t.map(file => `${path}${file}`);\n\n\t\t\treturn resolve(absoluteFiles);\n\t\t} catch(err){\n\t\t\treturn reject(`getRemoteFileTree::${err}`)\n\t\t}\n\t});\n}",
"function getListOfFilesToDownload(destination, remoteFiles) {\n var filesToDownload = [];\n for (var rfi in remoteFiles) {\n if (!fileExistLocaly(destination + remoteFiles[rfi].name, remoteFiles[rfi])) {\n filesToDownload = filesToDownload.concat(remoteFiles[rfi].name);\n }\n }\n return filesToDownload;\n}",
"function get_files_from_server(){\n //link with file containning the files and folders distribution\n fetch(\"https://raw.githubusercontent.com/Eduardo-Filipe-Ferreira/ADS-Files-Repository/main/FilesLocation.json\")\n .then(response => response.json())\n .then(json => handle_server_files(json[0]));\n }",
"getFiles(dir) {\n return (new fs.Dir(this.dst, dir)).files;\n }",
"function getRepoFiles(repoPath) {\n var cwd = repoPath;\n // console.log('running git ls-files on: ' + cwd);\n var filesNamesString = ShellCommander_1.runShellCommand('git ls-files', repoPath);\n var fileNamesArray = ShellCommander_1.formatOutputNewLine(filesNamesString);\n return fileNamesArray;\n}",
"function downloadFiles(list, remote, destination) {\n var deferred = Q.defer();\n var downloaded = [];\n async.eachSeries(list, function iterator(item, cb) {\n download(remote + item, destination + item, cb, downloaded);\n }, function done() {\n deferred.resolve(downloaded);\n });\n return deferred.promise;\n\n}",
"function readdirSyncR(dir) {\r\n\r\n var results = []\r\n var list = fs.readdirSync(dir)\r\n list.forEach(function(file) {\r\n file = dir + '/' + file\r\n var stat = fs.statSync(file)\r\n if (stat && stat.isDirectory()) results = results.concat(readdirSyncR(file))\r\n else results.push(file)\r\n })\r\n\t\r\n return results;\r\n\t\r\n}",
"function listCall(path, refreshCallback){\n\n\tMeteor.call(\"listContents\", path, \"d\", function(error, result){\n\t if(error){\n\t console.log(error.reason);\n\t return;\n\t }\n\t Session.set(\"folderArr\", result.split('\\n'));\n\t Meteor.call(\"listContents\", path, \"f\", function(error, result){\n\t if(error){\n\t console.log(error.reason);\n\t return;\n\t }\n\t Session.set(\"fileArr\", result.split('\\n'));\n\t refreshCallback();\n\t });\n\t});\n}",
"function getFileListing(basePath, testPath, dir, srvScope)\n{\n var uri = getResolvedURI(basePath);\n var chromeDir = getChromeDir(uri);\n //chromeDir.appendRelativePath(dir);\n //basePath += '/' + dir;\n\n var ioSvc = Components.classes[\"@mozilla.org/network/io-service;1\"].\n getService(Components.interfaces.nsIIOService);\n var testsDirURI = ioSvc.newFileURI(chromeDir);\n var testsDir = ioSvc.newURI(testPath, null, testsDirURI)\n .QueryInterface(Components.interfaces.nsIFileURL).file;\n\n var singleTestPath;\n if (testPath != undefined) {\n var extraPath = testPath;\n \n var fileNameRegexp = /(browser|test)_.+\\.(xul|html|js)$/;\n\n // Invalid testPath...\n if (!testsDir.exists())\n return [];\n\n if (testsDir.isFile()) {\n if (fileNameRegexp.test(testsDir.leafName))\n var singlePath = basePath + '/' + testPath;\n var links = {};\n links[singlePath] = true;\n return [links, null];\n\n // We were passed a file that's not a test...\n return [];\n }\n\n // otherwise, we were passed a directory of tests\n basePath += \"/\" + testPath;\n }\n var [links, count] = srvScope.list(basePath, testsDir, true);\n return [links, null];\n}",
"static readdirSync (dir) {\n return fs.readdirSync(dir)\n .map( entry => {\n let entry_path = path.join(dir, entry)\n let entry_stat = fs.lstatSync(entry_path)\n if ( entry_stat.isDirectory() ) return Walk.readdirSync(entry_path)\n return entry_path\n })\n .reduce((entries, result) => entries.concat(result), [])\n }",
"fileListCache() {\n return remote.getGlobal('application').fileListCache;\n }",
"function getLocalFileList() {\n var fileListPath = 'filelist.txt';\n var localFileURL;\n if (chrome.extension) localFileURL = chrome.extension.getURL(fileListPath);\n var txtFile = new XMLHttpRequest();\n txtFile.open(\"GET\", localFileURL, true);\n txtFile.onreadystatechange = function()\n {\n if (txtFile.readyState === 4) { // document is ready to parse.\n if (txtFile.status === 200) { // file is found\n allText = txtFile.responseText;\n // Convert all slashes to forward slashes\n lines = txtFile.responseText.replace(/\\\\/g,\"/\").split(\"\\n\");\n fileList = lines;\n fileCount = fileList.length - 1\n fileIndex = 0;\n handleLocalFile(fileList[0]);\n }\n }\n }\n txtFile.send(null);\n}",
"static readdir (dir) {\n return fs.readdirAsync(dir).map( entry => {\n let entry_path = path.join(dir, entry)\n // `stat` the entry\n return fs.lstatAsync(entry_path).then( stat => {\n // Recurse for a directory, return a file\n if ( stat.isDirectory() ) return Walk.readdir(entry_path)\n return entry_path\n })\n\n // `readdirAsync().map` concurrency\n }, { concurrency: 2})\n\n // Promise recursion produces an array of array entries, flatten them\n .reduce((entries, result) => entries.concat(result), [])\n }",
"function listObjects(path) {\n var opts = {};\n client.ls('/' + process.env.MANTA_USER + path, opts, function(err, res) {\n assert.ifError(err);\n console.log(err);\n\n res.on('object', function(obj) {\n console.log(obj.name);\n });\n\n res.on('directory', function(dir) {\n console.log(dir);\n });\n\n res.once('error', function(err) {\n console.error(err.stack);\n process.exit(1);\n });\n\n res.once('end', function() {\n console.log('all done');\n process.exit();\n });\n });\n}",
"function fetchChangedFiles(structure, credentials, mTime) {\n var\n cnt = [], fav = [], all = [], chg = [],\n q = $q.defer(),\n remotePath = remote + '/data/' + md5.createHash(credentials.email + credentials.password) + '/',\n localPath = localStructurePath(credentials) + '/',\n localPathFull = localStructurePath(credentials, true) + '/'\n ;\n\n if (structure.content.length) {\n cnt = getChangedFilesList(structure.content, mTime);\n }\n\n if (structure.favorites.length) {\n fav = getChangedFilesList(structure.favorites, mTime);\n }\n\n chg = cnt.concat(fav);\n\n for (var i = 0, len = chg.length; i < len; i++) {\n var file = chg[i];\n\n all.push(removeLocalFile(localPath + file));\n all.push($cordovaFile.downloadFile(remotePath + file, localPathFull + file, true, {}).then(q.resolve));\n }\n\n return $q.all(all);\n }",
"function listDriveFiles() {\n var fileIt = DriveApp.getFiles(),\n file;\n Logger.log(\"File Names:\");\n while (fileIt.hasNext()) {\n file = fileIt.next()\n Logger.log(file.getName());\n }\n}",
"function apiFiles() {\n\treturn fs\n\t\t.readdirSync(__dirname)\n\t\t.map((item) => {\n\t\t\tconst parts = item.split('.');\n\t\t\tif (parts.pop() !== 'json' || parts.shift() !== 'api-extractor') {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\treturn parts.length === 1 ? parts[0] : '';\n\t\t})\n\t\t.filter((item) => item !== '');\n}",
"static getRemotePaths(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('flavorasset', 'getRemotePaths', kparams);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns object with id and view params (if present) of the view | function parseViewData(view) {
var data = {};
var params = parseViewParams(view);
if (params != null) {
data = params;
}
var id = $(view).parseData('id');
data.id = id;
return data;
} | [
"getViews() {\n const viewMap = {};\n this.views.forEach(view => {\n viewMap[view.id] = view;\n });\n return viewMap;\n }",
"getViewState(viewOrViewId) {\n const view = typeof viewOrViewId === 'string' ? this.getView(viewOrViewId) : viewOrViewId; // Backward compatibility: view state for single view\n\n const viewState = view && this.viewState[view.getViewStateId()] || this.viewState;\n return view ? view.filterViewState(viewState) : viewState;\n }",
"matchView(name, request) {\n // Retrieve the views with the given name\n let viewList = this._viewMatchers[name];\n if (!viewList || !viewList.length)\n throw new ViewCollectionError('No view named ' + name + ' found.');\n // Negotiate the view best matching the request's requirements\n let viewDetails = negotiate.choose(viewList, request)[0];\n if (!viewDetails)\n throw new ViewCollectionError('No matching view named ' + name + ' found.');\n return viewDetails;\n }",
"get(viewPath) {\r\n return this.views.get(viewPath);\r\n }",
"getViewUrl(viewID) {\n return appEnv.rootPath + \"View/\" + viewID;\n }",
"getViewStrategy(value: any): ViewStrategy {\n if (!value) {\n return null;\n }\n\n if (typeof value === 'object' && 'getViewStrategy' in value) {\n let origin = Origin.get(value.constructor);\n\n value = value.getViewStrategy();\n\n if (typeof value === 'string') {\n value = new RelativeViewStrategy(value);\n }\n\n viewStrategy.assert(value);\n\n if (origin.moduleId) {\n value.makeRelativeTo(origin.moduleId);\n }\n\n return value;\n }\n\n if (typeof value === 'string') {\n value = new RelativeViewStrategy(value);\n }\n\n if (viewStrategy.validate(value)) {\n return value;\n }\n\n if (typeof value !== 'function') {\n value = value.constructor;\n }\n\n let origin = Origin.get(value);\n let strategy = metadata.get(ViewLocator.viewStrategyMetadataKey, value);\n\n if (!strategy) {\n if (!origin.moduleId) {\n throw new Error('Cannot determine default view strategy for object.', value);\n }\n\n strategy = this.createFallbackViewStrategy(origin);\n } else if (origin.moduleId) {\n strategy.moduleId = origin.moduleId;\n }\n\n return strategy;\n }",
"originalView(viewPath) {\r\n return __VIEWS__.get(viewPath);\r\n }",
"visitObject_view_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function userView(targetid, user){\n apply_template(targetid, \"user-detail-template\", user);\n}",
"constructor(id, view, model) {\n this.id = id;\n this._view = view;\n this._model = model;\n \n view.setController(this);\n model.setController(this);\n \n this.load();\n }",
"_createView(type) {\n\t\tlet self = this;\n\t\tAssertUtils.isString(type);\n\n\t\tfunction createView2(name, data) {\n\t\t\treturn NoPgUtils.extendPromise( [NoPg], NoPgUtils.nr_fcall(\"nopg:_createView\", function() {\n\n\t\t\t\tif ( data !== undefined) AssertUtils.isObject(data);\n\t\t\t\tdata = data || {};\n\n\t\t\t\tAssertUtils.isStringWithMinLength(name, 1);\n\n\t\t\t\tdata.$type = ''+type;\n\t\t\t\tdata.$name = ''+name;\n\n\t\t\t\treturn self._getType(type).then(function(type_obj) {\n\t\t\t\t\tAssertUtils.isObject(type_obj);\n\t\t\t\t\tAssertUtils.isUuidString(type_obj.$id);\n\t\t\t\t\tdata.$types_id = type_obj.$id;\n\t\t\t\t\treturn self._doInsert(NoPg.View, data).then(NoPgUtils.get_result(NoPg.View));\n\t\t\t\t});\n\t\t\t}));\n\t\t}\n\n\t\treturn createView2;\n\t}",
"visitCreate_view(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"async show ({ params, request }) {\n const find = await Vagas.find(params.id)\n\n return find\n }",
"onNonArticleView(name, data = {}) {\n }",
"async show({ params }) {\n const { id } = params;\n return Type.findOrFail(id);\n }",
"function mainViewCtrl(viewToShow, data) {\n switch(viewToShow){\n // if course+/edit was clicked\n case 'add-course':\n $('#count').hide();\n emptyDetails(\"course\");\n studentDetails.addClass(\"hidden\");\n studentForm.addClass(\"hidden\");\n courseDetails.addClass(\"hidden\");\n // show course add form\n courseForm.removeClass(\"hidden\");\n showListForSelection('course');\n\n if (typeof data === 'object' && data != null){\n fillDetails(data);\n }\n break;\n // if student+/edit was clicked\n case 'add-student':\n $('#count').hide();\n emptyDetails(\"student\");\n studentDetails.addClass(\"hidden\");\n courseForm.addClass(\"hidden\");\n courseDetails.addClass(\"hidden\");\n // show student add form\n studentForm.removeClass(\"hidden\");\n // show all available courses for new student\n showListForSelection('student');\n\n if (typeof data === 'object' && data != null){\n fillDetails(data);\n }\n break;\n // if clicked on the specific student\n case 'show-student':\n $('#count').hide();\n studentForm.addClass(\"hidden\");\n courseForm.addClass(\"hidden\");\n courseDetails.addClass(\"hidden\");\n // show details view\n studentDetails.removeClass(\"hidden\");\n\n if (data.s_ID !== null || data.s_ID !== false){\n showStudentDetails(data);\n }\n break;\n // if clicked on the specific course\n case 'show-course':\n $('#count').hide();\n studentForm.addClass(\"hidden\");\n courseForm.addClass(\"hidden\");\n studentDetails.addClass(\"hidden\");\n // show details view\n courseDetails.removeClass(\"hidden\");\n\n if (data.c_ID !== null || data.c_ID !== false){\n showCourseDetails(data);\n }\n break;\n }\n }",
"function MapViewFactory() {}",
"function displayView(view) {\n console.log(view);\n // hämta alla sidor/get all views\n const pageView = document.getElementById(\"page1\") \n const loginView = document.getElementById(\"logIn\") \n const varningView = document.getElementById(\"varning\") \n \n \n // dölj alla sidor/hide all views\n pageView.style.display = \"none\"\n loginView.style.display = \"none\"\n varningView.style.display = \"none\" \n \n\n // visa den specifika sidan/display specified view\n if (view === 'pageView') {\n pageView.style.display = \"block\"\n }\n \n if (view === 'loginView') {\n loginView.style.display = \"block\"\n }\n\n if (view === 'varningView') {\n varningView.style.display = \"block\"\n } \n \n}",
"function renderIndThreadView(id, state) {\n var postIdArr = [];\n\n var thread = $.grep(state.movieThreads, function (elem, ind) {\n return elem._id == id;\n });\n\n hideAllViews();\n $('.js-btn-edit-thread').remove();\n\n // Add Thread ID to Section id\n $('.thread.view').attr('id', thread[0]._id);\n\n // Clear Posts\n $('.thread-view-title-posts').empty();\n\n // Fill in Thread Title Info\n $('.thread-view-title').text(thread[0].title);\n $('.thread-view-content').text(thread[0].content);\n $('.thread-creator').html('Thread Created by: <span class=\"js-thread-title-author\">' + thread[0].author + '</span>');\n $('.thread-created').text('' + new Date(thread[0].date).toLocaleString());\n if (thread[0].author === state.user) {\n $('.add-post-wrapper').append('<button type=\"button\" class=\"btn-add-post js-btn-edit-thread\">Edit</button>');\n } else {\n //\n }\n \n showView('thread');\n\n // Load Thread Posts\n if(thread[0].posts.length){\n thread[0].posts.forEach(function (post, index) {\n $('.thread-view-title-posts').append('<article class=\"post-wrapper\" id=' + post._id + '>\\n\\n <span class=\"post-content-date\"><span class=\"js-pc-user\">' + post.user.slice(0, 1) + '</span> <span class=\"js-pc-full-user\">' + post.user + '</span> ' + new Date(post.created).toLocaleString() + '</span>\\n <div class=\"post-content-wrapper\">\\n \\n <div class=\"post-content\">' + post.content + '</div>\\n\\n <div class=\"post-meta\">\\n <button class=\"likes\"> <span class=\"thumb\">👍</span> </button>\\n <span class=\"likes\">' + post.likes.count + '</span>\\n <span class=\"btn-comment\" id=\"btn-comment\">Comment</span> \\n </div> \\n </div> \\n </article> \\n ');\n\n // Add divider between Posts\n $('.thread-view-title-posts').append('<div class=\"js-separate\"></div>');\n\n // Check to see if current user liked post then change thumbs up class.\n var match = false;\n post.likes.users.forEach(function (user) {\n if (user.trim() === state.user.trim()) {\n $('#' + post._id).find('.thumb').addClass('thumb-liked');\n }\n });\n\n if (post.user === state.user) {\n var btn_render = '<span class=\"btn-comment\" id=\"btn-delete\">Delete</span><span class=\"btn-post\" id=\"btn-edit-post\">Edit</span>';\n $('.post-meta')[index].innerHTML += btn_render;\n }\n\n if (post.comments.length) {\n post.comments.forEach(function (comment) {\n $('#' + post._id).append('\\n\\n\\n\\n\\n\\n\\n<div class=\"js-comment\">\\n' + comment.comment + '\\n<p class=\"js-comment-user\"><span class=\"by\">by:</span> ' + comment.user + '</p>\\n</div>\\n');\n });\n }\n });\n }\n // End Posts\n showView('thread');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the value of a point in the polynomial. | function polynomialValue(poly, point) {
let value = new math.Fr(0n)
let pow = 1n
for (let i = 0; i < poly.length; i++) {
value = value.add(new math.Fr(poly[i]).multiply(pow))
pow *= point
}
return value.value
} | [
"function getFunctionValue(func, point) {\n return func[0] * point.x + func[1] * point.y + func[2] * point.x * point.y + func[3];\n }",
"function calculateCurvePoint(coeffs, x) {\r\n return Math.floor(Math.pow(x, 3) * coeffs[0] + Math.pow(x, 2) * coeffs[1] + x * coeffs[2] + coeffs[3])\r\n}",
"function polyEval(evalPoint, constTerm, ...coeffs) {\n return add(constTerm, ...coeffs.map((c, j) => c.mul(scalar(evalPoint).toThe(scalar(j+1)))))\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}",
"getPoint1(){\n\t\treturn this.point1\n\t}",
"point(param) {\n return this._edgeSegment.point(param);\n }",
"function getLatLon(point){\n return studyDb.get(point).then(function(doc){\n\t //console.log(doc.latlon);\n \treturn doc.latlon;\n });\n}",
"get curve() {}",
"function getResultForChromosome(chromosome,x){\n\t //\n\t return this.calculatePolynomialInPoint(Math.round(chromosome[8]),chromosome,x);\n\t\t//return (chromosome[0]*Math.pow(x,2))+(chromosome[1]*x)+chromosome[2];\n\t}",
"function printPoint(p) {\n return p[0].toFixed(1) + \" \" + p[1].toFixed(1);\n }",
"get(x, z) {\n\t\tlet { zSize } = this;\n\t\treturn this.data[ x*zSize + z ];\n\t}",
"function hashToPoint(m) {\n let buf = Buffer.alloc(pkLength), ret\n \n // uniformly choose whether the y-coord is odd or even\n buf[0] = (hashToBuf(m)[0] % 2) ? 2 : 3\n\n for (let i = 0; ; i++) {\n // uniformly choose the x-coord; has a ~50% chance of lying on the curve\n buf.set(hashToBuf(i+'||'+m), 1)\n\n try {\n // TODO this code currently involves a square root even if buf is not on the curve\n // due to the way elliptic.js works. this could be made ~2x faster using fast\n // Legendre symbol computation\n ret = ecc.curve.decodePoint(buf)\n break\n } catch (e) { }\n }\n\n return point(ret)\n}",
"dotCoordinate(point) {\n return (this.normal.x * point.x +\n this.normal.y * point.y +\n this.normal.z * point.z +\n this.d);\n }",
"get_voltageSetPoint()\n {\n return this.liveFunc._voltageSetPoint;\n }",
"function randomPoint() { return pick(points); }",
"function getTestPoint(ring) {\n // Use the point halfway along first segment rather than an endpoint\n // (because ring might still be enclosed if a segment endpoint touches an indexed ring.)\n // The returned point should work for point-in-polygon testing if two rings do not\n // share any common segments (which should be true for topological datasets)\n // TODO: consider alternative of finding an internal point of @ring (slower but\n // potentially more reliable).\n var arcId = ring[0],\n p0 = arcs.getVertex(arcId, 0),\n p1 = arcs.getVertex(arcId, 1);\n return [(p0.x + p1.x) / 2, (p0.y + p1.y) / 2];\n }",
"function getValue(fLabel, t) {\n var series = plot.getData();\n for (var i = 0; i < series.length; ++i)\n if (series[i].label == fLabel) {\n return getValueFromSeries(series[i],t)\n }\n return null\n }",
"function getEventPoint(evt) {\n var p = root.createSVGPoint();\n\n p.x = evt.pageX;\n p.y = evt.pageY;\n\n return p;\n}",
"function getJointPoint(joint, label)\n {\n if (!joint.Point.length)\n {\n if (joint.Point.Label === label)\n return joint.Point;\n }\n else // array\n {\n // Iterate over points\n for (var i = 0; i < joint.Point.length; ++i)\n {\n if (joint.Point[i].Label === label)\n return joint.Point[i];\n }\n }\n\n return null; // not found\n }",
"function getNoiseValue(x, y, frequency) {\n\treturn Math.abs(noise.perlin2(x / frequency, y / frequency));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a new MachineDetectionConfiguration. | constructor() {
MachineDetectionConfiguration.initialize(this);
} | [
"constructor() { \n \n ComputeInfoProtocol.initialize(this);\n }",
"constructor() { \n \n ConfigHash.initialize(this);\n }",
"constructor() { \n \n DetectionDetailsResponse.initialize(this);\n }",
"function createInstance() {\n /**\n * Initialize the configuration.\n *\n * @method module:ConfigurationHandler#init\n * @param {string} region - REGION name where the App Configuration service instance is\n * created.\n * @param {string} guid - GUID of the App Configuration service.\n * @param {string} apikey - APIKEY of the App Configuration service.\n */\n function init(region, guid, apikey) {\n _guid = guid;\n urlBuilder.setRegion(region);\n urlBuilder.setGuid(guid);\n urlBuilder.setApikey(apikey);\n urlBuilder.setAuthenticator();\n }\n\n /**\n * Used to re-initialize this module\n *\n * 1. Clears the interval set for internet check\n * 2. Clears any scheduled retries if they were set\n * 3. Deletes the configurations stored in SDK defined file path\n * @method module:ConfigurationHandler#cleanup\n */\n function cleanup() {\n clearInterval(interval);\n clearTimeout(retryScheduled);\n if (_persistentCacheDirectory) {\n FileManager.deleteFileData(path.join(_persistentCacheDirectory, 'appconfiguration.json'));\n }\n _onSocketRetry = false;\n }\n\n /**\n * Stores the given configurations data into respective maps.\n * (_featureMap, _propertyMap, _segmentMap)\n *\n * @method module:ConfigurationHandler#loadConfigurationsToCache\n * @param {JSON} data - The configurations data\n */\n function loadConfigurationsToCache(data) {\n if (data) {\n if (data.features && Object.keys(data.features).length) {\n const { features } = data;\n _featureMap = {};\n features.forEach((feature) => {\n _featureMap[feature.feature_id] = new Feature(feature);\n });\n }\n if (data.properties && Object.keys(data.properties).length) {\n const { properties } = data;\n _propertyMap = {};\n properties.forEach((property) => {\n _propertyMap[property.property_id] = new Property(property);\n });\n }\n if (data.segments && Object.keys(data.segments).length) {\n const { segments } = data;\n _segmentMap = {};\n segments.forEach((segment) => {\n _segmentMap[segment.segment_id] = new Segment(segment);\n });\n }\n }\n }\n\n /**\n * Writes the given data on to the persistent volume.\n *\n * @async\n * @param {JSON|string} fileData - The data to be written\n * @returns {undefined} If fileData is null\n */\n async function writeToPersistentStorage(fileData) {\n if (fileData == null) {\n logger.log('No data');\n return;\n }\n const json = JSON.stringify(fileData);\n FileManager.storeFiles(json, (path.join(_persistentCacheDirectory, 'appconfiguration.json')), () => { });\n }\n\n /**\n * Creates API request and waits for the response.\n * If response has data, then passes the response data to `writeToPersistentStorage()` method\n * for further actions. Else, logs the error message to console.\n *\n * @async\n * @method module:ConfigurationHandler#fetchFromAPI\n */\n async function fetchFromAPI() {\n retryCount -= 1;\n try {\n const query = {\n environment_id: _environmentId,\n };\n const parameters = {\n options: {\n url: `/apprapp/feature/v1/instances/${_guid}/collections/${_collectionId}/config`,\n method: 'GET',\n qs: query,\n },\n defaultOptions: {\n serviceUrl: urlBuilder.getBaseServiceUrl(),\n headers: urlBuilder.getHeaders(),\n },\n };\n const response = await ApiManager.createRequest(parameters);\n if (response && _liveUpdate) {\n // load the configurations in the response to cache maps\n loadConfigurationsToCache(response.result);\n emitter.emit(Constants.MEMORY_CACHE_ACTION_SUCCESS);\n // asynchronously write the response to persistent volume, if enabled\n if (_persistentCacheDirectory) {\n writeToPersistentStorage(response.result);\n }\n } else if (retryCount > 0) {\n logger.log('Retrying to fetch the configurations');\n fetchFromAPI();\n } else {\n logger.error(`Failed to fetch the configurations. Retrying after ${retryTime} minutes`);\n retryCount = 3;\n retryScheduled = setTimeout(() => fetchFromAPI(), retryTime * 60000);\n }\n } catch (error) {\n logger.error(error.message);\n }\n }\n\n /**\n * Perform websocket connect to appconfiguration server\n *\n * @async\n * @method module:ConfigurationHandler#connectWebSocket\n */\n async function connectWebSocket() {\n try {\n const urlForWebsocket = urlBuilder.getWebSocketUrl(_collectionId, _environmentId);\n const _bearerToken = await urlBuilder.getToken();\n const headers = {\n Authorization: _bearerToken,\n };\n closeWebSocket(); // close existing websocket connection if any\n socketClient.connect(\n urlForWebsocket, [], [], headers,\n );\n } catch (error) {\n logger.warning(error.message);\n logger.warning('Connection to the App Configuration server failed with unexpected error');\n }\n }\n\n function isJSONDataEmpty(jsonData) {\n if (Object.keys(jsonData).length === 0) {\n return true;\n }\n return false;\n }\n\n async function fetchConfigurationsData() {\n if (_liveUpdate) {\n await fetchFromAPI();\n connectWebSocket();\n }\n }\n\n /**\n * Sets the context of the SDK\n *\n * @method module:ConfigurationHandler#setContext\n * @param {string} collectionId - Id of the collection created in App Configuration service\n * instance.\n * @param {string} environmentId - Id of the environment created in App Configuration\n * service instance.\n * @param {object} [options] - Options object\n * @param {string} [options.persistentCacheDirectory] - Absolute path to a directory which has\n * read & write permissions for file operations.\n * @param {string} [options.bootstrapFile] - Absolute path of configuration file. This parameter\n * when passed along with `liveConfigUpdateEnabled` value will drive the SDK to use the\n * configurations of this file to perform feature & property evaluations.\n * @param {boolean} [options.liveConfigUpdateEnabled] - live configurations update from the server.\n * Set this value to `false` if the new configuration values shouldn't be fetched from the server.\n */\n function setContext(collectionId, environmentId, options) {\n // when setContext is called more than one time with any of collectionId, environmentId or options\n // different from its previous time, cleanup method is invoked.\n // don't do the cleanup when setContext is called for the first time.\n if ((_collectionId && (_collectionId !== collectionId))\n || (_environmentId && (_environmentId !== environmentId))\n || (_persistentCacheDirectory && (_persistentCacheDirectory !== options.persistentCacheDirectory))\n || (_bootstrapFile && (_bootstrapFile !== options.bootstrapFile))\n ) {\n cleanup();\n }\n _collectionId = collectionId;\n _environmentId = environmentId;\n _persistentCacheDirectory = options.persistentCacheDirectory;\n _bootstrapFile = options.bootstrapFile;\n _liveUpdate = options.liveConfigUpdateEnabled;\n\n if (_persistentCacheDirectory) {\n persistentData = FileManager.getFileData(path.join(_persistentCacheDirectory, 'appconfiguration.json'));\n // no emitting the event here. Only updating cache is enough\n loadConfigurationsToCache(persistentData);\n try {\n fs.accessSync(_persistentCacheDirectory, fs.constants.W_OK);\n } catch (err) {\n logger.error(Constants.ERROR_NO_WRITE_PERMISSION);\n return;\n }\n }\n\n if (_bootstrapFile) {\n if (_persistentCacheDirectory) {\n if (isJSONDataEmpty(persistentData)) {\n try {\n const bootstrapFileData = FileManager.getFileData(_bootstrapFile);\n loadConfigurationsToCache(bootstrapFileData);\n emitter.emit(Constants.MEMORY_CACHE_ACTION_SUCCESS);\n writeToPersistentStorage(bootstrapFileData)\n } catch (error) {\n logger.error(error);\n }\n } else {\n // only emit the event here. Because, cache is already updated above (line 270)\n emitter.emit(Constants.MEMORY_CACHE_ACTION_SUCCESS);\n }\n } else {\n const bootstrapFileData = FileManager.getFileData(_bootstrapFile);\n loadConfigurationsToCache(bootstrapFileData);\n emitter.emit(Constants.MEMORY_CACHE_ACTION_SUCCESS);\n }\n }\n\n if (_liveUpdate) {\n checkInternet().then((val) => {\n if (!val) {\n logger.warning(Constants.NO_INTERNET_CONNECTION_ERROR);\n _isConnected = false;\n }\n });\n interval = setInterval(() => {\n checkInternet().then((val) => {\n if (!val) {\n logger.warning(Constants.NO_INTERNET_CONNECTION_ERROR);\n _isConnected = false;\n } else {\n if (!_isConnected) {\n _onSocketRetry = false;\n fetchFromAPI();\n connectWebSocket();\n }\n _isConnected = true;\n }\n });\n }, 30000); // 30 second\n }\n\n fetchConfigurationsData();\n }\n\n async function socketActions() {\n fetchFromAPI();\n }\n\n /**\n * Get the Feature object containing all features\n *\n * @method module:ConfigurationHandler#getFeatures\n * @returns {object} Feature object\n */\n function getFeatures() {\n return _featureMap;\n }\n\n /**\n * Get the Feature with give Feature Id\n *\n * @method module:ConfigurationHandler#getFeature\n * @param {string} featureId - The Feature Id\n * @returns {object|null} Feature object\n */\n function getFeature(featureId) {\n if (Object.prototype.hasOwnProperty.call(_featureMap, featureId)) {\n return _featureMap[featureId];\n }\n logger.error(`Invalid feature id - ${featureId}`);\n return null;\n }\n\n /**\n * Get the Property object containing all properties\n *\n * @method module:ConfigurationHandler#getProperties\n * @returns {object} Property object\n */\n function getProperties() {\n return _propertyMap;\n }\n\n /**\n * Get the Property with give Property Id\n *\n * @method module:ConfigurationHandler#getProperty\n * @param {string} propertyId - The Property Id\n * @returns {object|null} Property object\n */\n function getProperty(propertyId) {\n if (Object.prototype.hasOwnProperty.call(_propertyMap, propertyId)) {\n return _propertyMap[propertyId];\n }\n logger.error(`Invalid property id - ${propertyId}`);\n return null;\n }\n\n function getSegment(segmentId) {\n if (Object.prototype.hasOwnProperty.call(_segmentMap, segmentId)) {\n return _segmentMap[segmentId];\n }\n logger.error(`Invalid segment id - ${segmentId}`);\n return null;\n }\n\n function evaluateSegment(segmentKey, entityAttributes) {\n if (Object.prototype.hasOwnProperty.call(_segmentMap, segmentKey)) {\n const segmentObjc = _segmentMap[segmentKey];\n return segmentObjc.evaluateRule(entityAttributes);\n }\n return null;\n }\n\n function _parseRules(segmentRules) {\n const rulesMap = {};\n segmentRules.forEach((rules) => {\n rulesMap[rules.order] = new SegmentRules(rules);\n });\n return rulesMap;\n }\n\n function evaluateRules(_rulesMap, entityAttributes, feature, property) {\n const resultDict = {\n evaluated_segment_id: Constants.DEFAULT_SEGMENT_ID,\n value: null,\n };\n\n try {\n for (let index = 1; index <= Object.keys(_rulesMap).length; index += 1) {\n const segmentRule = _rulesMap[index];\n\n if (segmentRule.rules.length > 0) {\n for (let level = 0; level < segmentRule.rules.length; level += 1) {\n const rule = segmentRule.rules[level];\n\n const { segments } = rule;\n if (segments.length > 0) {\n for (let innerLevel = 0; innerLevel < segments.length; innerLevel += 1) {\n const segmentKey = segments[innerLevel];\n\n if (evaluateSegment(segmentKey, entityAttributes)) {\n resultDict.evaluated_segment_id = segmentKey;\n if (segmentRule.value === '$default') {\n if (feature !== null) {\n resultDict.value = feature.enabled_value;\n } else {\n resultDict.value = property.value;\n }\n } else {\n resultDict.value = segmentRule.value;\n }\n return resultDict;\n }\n }\n }\n }\n }\n }\n } catch (error) {\n logger.error(`RuleEvaluation ${error}`);\n }\n\n if (feature !== null) {\n resultDict.value = feature.enabled_value;\n } else {\n resultDict.value = property.value;\n }\n return resultDict;\n }\n\n /**\n * Records each of feature & property evaluations done by sending it to metering module.\n * See {@link module:Metering}\n *\n * @method module:ConfigurationHandler#recordEvaluation\n * @param {string} featureId - The Feature Id\n * @param {string} propertyId - The Property Id\n * @param {string} entityId - The Entity Id\n * @param {string} segmentId - The Segment Id\n */\n function recordEvaluation(featureId, propertyId, entityId, segmentId) {\n meteObj.addMetering(_guid,\n _environmentId,\n _collectionId,\n entityId,\n segmentId,\n featureId,\n propertyId);\n }\n\n /**\n * Feature evaluation\n *\n * @method module:ConfigurationHandler#featureEvaluation\n * @param {object} feature - Feature object\n * @param {string} entityId - Entity Id\n * @param {object} entityAttributes - Entity attributes object\n * @returns {boolean|string|number} Feature evaluated value\n */\n function featureEvaluation(feature, entityId, entityAttributes) {\n let resultDict = {\n evaluated_segment_id: Constants.DEFAULT_SEGMENT_ID,\n value: null,\n };\n try {\n if (feature.enabled) {\n if (!entityAttributes || Object.keys(entityAttributes).length <= 0) {\n return feature.enabled_value;\n }\n if (feature.segment_rules && feature.segment_rules.length > 0) {\n const _rulesMap = _parseRules(feature.segment_rules);\n resultDict = evaluateRules(_rulesMap, entityAttributes, feature, null);\n return resultDict.value;\n }\n return feature.enabled_value;\n }\n return feature.disabled_value;\n } finally {\n recordEvaluation(feature.feature_id, null, entityId, resultDict.evaluated_segment_id);\n }\n }\n\n /**\n * Property evaluation\n *\n * @method module:ConfigurationHandler#propertyEvaluation\n * @param {object} property - Property object\n * @param {string} entityId - Entity Id\n * @param {object} entityAttributes - Entity attributes object\n * @returns {boolean|string|number} Property evaluated value\n */\n function propertyEvaluation(property, entityId, entityAttributes) {\n let resultDict = {\n evaluated_segment_id: Constants.DEFAULT_SEGMENT_ID,\n value: null,\n };\n try {\n if (!entityAttributes || Object.keys(entityAttributes).length <= 0) {\n return property.value;\n }\n if (property.segment_rules && property.segment_rules.length > 0) {\n const _rulesMap = _parseRules(property.segment_rules);\n resultDict = evaluateRules(_rulesMap, entityAttributes, null, property);\n return resultDict.value;\n }\n return property.value;\n } finally {\n recordEvaluation(null, property.property_id, entityId, resultDict.evaluated_segment_id);\n }\n }\n\n // Other event listeners\n emitter.on(Constants.MEMORY_CACHE_ACTION_SUCCESS, () => {\n emitter.emit(Constants.APPCONFIGURATION_CLIENT_EMITTER);\n });\n\n // Socket Listeners\n emitter.on(Constants.SOCKET_CONNECTION_ERROR, (error) => {\n logger.warning(`Connecting to app configuration server failed. ${error}`);\n logger.warning(Constants.CREATE_NEW_CONNECTION);\n _onSocketRetry = true;\n connectWebSocket();\n });\n\n emitter.on(Constants.SOCKET_LOST_ERROR, (error) => {\n logger.warning(`Connecting to app configuration server lost. ${error}`);\n logger.warning(Constants.CREATE_NEW_CONNECTION);\n _onSocketRetry = true;\n connectWebSocket();\n });\n\n emitter.on(Constants.SOCKET_CONNECTION_CLOSE, () => {\n logger.warning('server connection closed. Creating a new connection to the server.');\n logger.warning(Constants.CREATE_NEW_CONNECTION);\n _onSocketRetry = true;\n connectWebSocket();\n });\n\n emitter.on(Constants.SOCKET_MESSAGE_RECEIVED, (data) => {\n logger.log(`Received message from server. ${data}`);\n });\n\n emitter.on(Constants.SOCKET_CALLBACK, () => {\n socketActions();\n });\n\n emitter.on(Constants.SOCKET_MESSAGE_ERROR, () => {\n logger.warning('Message received from server is invalid.');\n });\n\n emitter.on(Constants.SOCKET_CONNECTION_SUCCESS, () => {\n logger.log('Successfully connected to App Configuration server');\n if (_onSocketRetry === true) {\n socketActions();\n }\n _onSocketRetry = false;\n });\n\n return {\n init,\n setContext,\n getFeature,\n getFeatures,\n getProperty,\n getProperties,\n getSegment,\n featureEvaluation,\n propertyEvaluation,\n cleanup,\n };\n }",
"constructor() { \n \n GKETargetDetails.initialize(this);\n }",
"constructAxiosRequestConfig() {\n const input = this._getInput(this.edge);\n const config = {\n url: this._getUrl(this.edge, input),\n params: this._getParams(this.edge, input),\n data: this._getRequestBody(this.edge, input),\n method: this.edge.query_operation.method,\n timeout: 50000\n }\n this.config = config;\n return config;\n }",
"constructor() { \n \n ComDayCqWcmCoreImplLanguageManagerImplProperties.initialize(this);\n }",
"init() {\n logger.debug('Initializing failover class');\n\n return configWorker.getConfig()\n .then((data) => {\n logger.debug(`config: ${util.stringify(data)}`);\n this.config = data;\n if (!this.config) {\n logger.debug('Can\\'t find config.environment');\n return Promise.reject(new Error('Environment not provided'));\n }\n\n this.cloudProvider = CloudFactory.getCloudProvider(this.config.environment, { logger });\n return this.cloudProvider.init({\n tags: util.getDataByKey(this.config, 'failoverAddresses.scopingTags'),\n routeTags: util.getDataByKey(this.config, 'failoverRoutes.scopingTags'),\n routeAddresses: util.getDataByKey(this.config, 'failoverRoutes.scopingAddressRanges'),\n routeNextHopAddresses: {\n // provide default discovery type of 'routeTag' for backwards compatability...\n type: util.getDataByKey(this.config, 'failoverRoutes.defaultNextHopAddresses.discoveryType') || 'routeTag',\n items: util.getDataByKey(this.config, 'failoverRoutes.defaultNextHopAddresses.items'),\n tag: constants.ROUTE_NEXT_HOP_ADDRESS_TAG\n },\n storageTags: util.getDataByKey(this.config, 'externalStorage.scopingTags')\n });\n })\n .then(() => this.device.init())\n .catch((err) => {\n const errorMessage = `Cloud Provider initialization failed with error: ${util.stringify(err.message)} ${util.stringify(err.stack)}`;\n return Promise.reject(new Error(errorMessage));\n });\n }",
"static getInstance() {\n if (!instance) instance = new KamstrupMultical21Meter();\n return instance;\n }",
"static init()\n {\n let aeMachines = Component.getElementsByClass(document, PCx86.APPCLASS + \"-machine\");\n\n for (let iMachine = 0; iMachine < aeMachines.length; iMachine++) {\n\n let eMachine = aeMachines[iMachine];\n let parmsMachine = Component.getComponentParms(eMachine);\n\n let aeComputers = Component.getElementsByClass(eMachine, PCx86.APPCLASS, \"computer\");\n\n for (let iComputer = 0; iComputer < aeComputers.length; iComputer++) {\n\n let eComputer = aeComputers[iComputer];\n let parmsComputer = Component.getComponentParms(eComputer);\n\n /*\n * We set fSuspended in the Computer constructor because we want to \"power up\" the\n * computer ourselves, after any/all bindings are in place.\n */\n let computer = new Computer(parmsComputer, parmsMachine, true);\n\n if (DEBUG) computer.printf(\"onInit(%b)\\n\", computer.flags.powered);\n\n /*\n * Bind any \"power\", \"reset\" and \"save\" buttons. An \"erase\" button was also considered,\n * but \"reset\" now provides a way to force the machine to start from scratch again, so \"erase\"\n * may be redundant now.\n */\n Component.bindComponentControls(computer, eComputer, PCx86.APPCLASS);\n\n /*\n * Power on the computer, giving every component the opportunity to reset or restore itself.\n */\n if (computer.fAutoPower) computer.wait(computer.powerOn);\n }\n }\n }",
"constructor() { \n \n OrgApacheJackrabbitOakSegmentSegmentNodeStoreFactoryProperties.initialize(this);\n }",
"constructor() { \n \n ComDayCqReplicationImplAgentManagerImplInfo.initialize(this);\n }",
"constructor() { \n \n WorkflowTransitionRules.initialize(this);\n }",
"function Configuration(props) {\n return __assign({ Type: 'AWS::AmazonMQ::Configuration' }, props);\n }",
"static build($element) {\n let model = $element.data('model')\n let messenger = DuplicateResourceDetectorFactory.propertyMessenger\n\n switch(model) {\n case 'ScannedResource':\n messenger = DuplicateResourceDetectorFactory.sourceMetadataIdMessenger\n break\n case 'EphemeraBox':\n messenger = DuplicateResourceDetectorFactory.barcodeMessenger\n break\n case 'EphemeraFolder':\n messenger = DuplicateResourceDetectorFactory.barcodeMessenger\n break\n }\n\n return new DuplicateResourceDetector($element, messenger)\n }",
"forName(name) {\n let loader = ServiceLoader.load(\"io.swagger.codegen.CodegenConfig\");\n let availableConfigs = new StringBuilder();\n for (const config of loader) {\n if ((config.getName() === name)) {\n return config;\n }\n availableConfigs.append(config.getName()).append(\"\\n\");\n }\n try {\n return Class.forName(name).newInstance();\n }\n catch (e) {\n throw new Error(\"Can\\'t load config class with name \".concat(name) + \" Available: \" + availableConfigs.toString(), e);\n }\n }",
"async createSelf (initValues = {}) {\n const selfData = {\n type: initValues.type\n }\n\n // Aggregate data from the IPFS adapter.\n selfData.ipfsId = this.adapters.ipfs.ipfsPeerId\n selfData.ipfsMultiaddrs = this.adapters.ipfs.ipfsMultiaddrs\n\n // Aggregate data from the BCH adapter.\n const bchData = await this.adapters.bch.generateBchId()\n selfData.bchAddr = bchData.cashAddress\n selfData.slpAddr = bchData.slpAddress\n selfData.publicKey = bchData.publicKey\n // selfData.mnemonic = this.adapters.bch.mnemonic\n\n // Generate an OrbitDB for other peers to pass messages to this node.\n selfData.orbit = await this.adapters.orbit.createRcvDb(selfData)\n\n const schemaConfig = {\n ipfsId: selfData.ipfsId,\n type: selfData.type,\n ipfsMultiaddrs: selfData.ipfsMultiaddrs,\n isCircuitRelay: this.isCircuitRelay,\n circuitRelayInfo: this.circuitRelayInfo,\n cashAddress: selfData.bchAddr,\n slpAddress: selfData.slpAddr,\n publicKey: selfData.publicKey,\n orbitdbId: selfData.orbit.id,\n // apiInfo: '',\n announceJsonLd: this.announceJsonLd\n }\n selfData.schema = new Schema(schemaConfig)\n\n // console.log('selfData: ', selfData)\n\n // Create the thisNode entity\n const thisNode = new ThisNodeEntity(selfData)\n this.thisNode = thisNode\n\n // Attach ther useCases (which includes adapters and controllers) to the\n // thisNode entity.\n this.thisNode.useCases = this.useCases\n\n return thisNode\n }",
"constructor(scope, id, props) {\n super(scope, id, { type: CfnAnomalyDetector.CFN_RESOURCE_TYPE_NAME, properties: props });\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_lookoutmetrics_CfnAnomalyDetectorProps(props);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, CfnAnomalyDetector);\n }\n throw error;\n }\n cdk.requireProperty(props, 'anomalyDetectorConfig', this);\n cdk.requireProperty(props, 'metricSetList', this);\n this.attrArn = cdk.Token.asString(this.getAtt('Arn', cdk.ResolutionTypeHint.STRING));\n this.anomalyDetectorConfig = props.anomalyDetectorConfig;\n this.metricSetList = props.metricSetList;\n this.anomalyDetectorDescription = props.anomalyDetectorDescription;\n this.anomalyDetectorName = props.anomalyDetectorName;\n this.kmsKeyArn = props.kmsKeyArn;\n }",
"constructor ({modelName, requestDiscriminationData}) {\n this.modelName = modelName\n this.requestDiscriminationData = requestDiscriminationData\n this.models = ModgelConfig\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
General functions for access, creation and modification of the website returns all elements of a tag where attribute attr contains value | function getElementsByAttribute(tag, attr, value) {
return document.evaluate('//'+tag+'[contains(@'+attr+',"'+value+'")]', document, null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
} | [
"function getAttributes()\n{\n var u = document.getElementById(\"w3r\").href;\n alert(('href value is : '+u));\n\n var v = document.getElementById(\"w3r\").hreflang; \n alert((' hreflang is : '+v));\n\n var w = document.getElementById(\"w3r\").rel; \n alert(('Link value is : '+w));\n\n var x = document.getElementById(\"w3r\").target; \n alert(('Target value is : '+x));\n \n var y = document.getElementById(\"w3r\").type; \n alert(('type value is : '+y)); \n}",
"function readElements(){\n//clears old table at first\n aContainer.splice(0, aContainer.length);\n// read every element with subimglist class\n// and push it to the array\n for(var i=0; i<aElements.length; i++){\n var attrChecker = aElements[i].readAttribute('class');\n if(attrChecker==null) continue;\n attrChecker = attrChecker.toString();\n if(attrChecker.indexOf('subimglist')>=0){\n aContainer.push(aElements[i]);\n }\n }\n}",
"function grabAssociatedTagsUsingSpaceDelimitedListAttribute(element,attribute){\n\t\tvar ids = $.trim($(element).attr(attribute));//get the ids to search for\n\t\tvar idsArray = ids.split(\" \"); //split the list on the spaces, store into array. So it can be parsed through one at a time.\n\t\tvar accumulatedText = \"\";//this variable is going to store what is found. And will be returned\n\t\tvar message, splitMessage = \"\";\n\t\t//Traverse through the array\n\t\tfor (var x=0;x<idsArray.length;x++){\n\t\t\t//Can the aria list id be found somewhere on the page?\n\t\t\tvar referencedId = andiUtility.escapeCssCharactersInId(idsArray[x]);\n\t\t\tvar referencedElement = $(\"#\"+referencedId);//will escape css syntax and treat as literals\n\t\t\tvar referencedElementText = \"\";\n\t\t\t\n\t\t\tif($(referencedElement).attr('aria-label')){\n\t\t\t\t//Yes, this id was found and it has an aria-label\n\t\t\t\treferencedElementText += andiUtility.formatForHtml($(referencedElement).attr('aria-label'));\n\t\t\t\t//Aria-label found on reference element\n\t\t\t\tmessage = attribute + alert_0064.message;\n\t\t\t\tandiAlerter.throwAlert(alert_0064,message);\n\t\t\t}\n\t\t\telse if($(referencedElement).html() !== undefined){\n\t\t\t\t//Yes, this id was found\n\t\t\t\treferencedElementText += andiUtility.formatForHtml(andiUtility.getTextOfTree(referencedElement,true));\n\t\t\t\t\n\t\t\t\tif(referencedElementText != \"\"){\n\t\t\t\t\t//Add referenceId\n\t\t\t\t\treferencedElementText = andiLaser.createLaserTarget(attribute,referencedId,referencedElementText);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//headers\n\t\t\t\tif(attribute == \"headers\" && !$(referencedElement).is(\"th\")){\n\t\t\t\t\t//referenced element is not a th\n\t\t\t\t\tif($(referencedElement).is(\"td\")){\n\t\t\t\t\t\tsplitMessage = alert_0067.message.split(\"||\");\n\t\t\t\t\t\tmessage = splitMessage[0] + idsArray[x] + splitMessage[1];\n\t\t\t\t\t\tandiAlerter.throwAlert(alert_0067,message);\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tsplitMessage = alert_0066.message.split(\"||\");\n\t\t\t\t\t\tmessage = splitMessage[0] + idsArray[x] + splitMessage[1];\n\t\t\t\t\t\tandiAlerter.throwAlert(alert_0066,message);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\t//No, this id was not found, add to list.\n\t\t\t\talert_0065.list += idsArray[x] + \" \"; //will be used if more than one idrefs missing\n\t\t\t\talert_0063.list = idsArray[x]; //will be used if only one idref missing\n\t\t\t}\n\t\t\t\n\t\t\t//Add to accumulatedText\n\t\t\taccumulatedText += referencedElementText + \" \";\n\t\t}\n\t\t//Check if any ids were not found\n\t\tif(alert_0065.list!=\"\"){\n\t\t\tvar missingIdsList = $.trim(alert_0065.list).split(\" \");\n\t\t\tif(missingIdsList.length > 1){//more than one id missing; Possible misuse\n\t\t\t\tsplitMessage = alert_0065.message.split(\"||\");\n\t\t\t\tmessage = splitMessage[0] + attribute + splitMessage[1] + $.trim(alert_0065.list) + splitMessage[2];\n\t\t\t\tandiAlerter.throwAlert(alert_0065,message);\n\t\t\t\talert_0063.list = \"\"; //reset the other list\n\t\t\t}\n\t\t\telse{//only one id missing\n\t\t\t\tsplitMessage = alert_0063.message.split(\"||\");\n\t\t\t\tmessage = splitMessage[0] + attribute + splitMessage[1] + alert_0063.list + splitMessage[2];\n\t\t\t\tandiAlerter.throwAlert(alert_0063,message);\n\t\t\t\talert_0065.list = \"\"; //reset the other list\n\t\t\t}\n\t\t}\n\t\treturn $.trim(accumulatedText);\n\t}",
"_getAttributes(elem, mandatory, optional=[]) {\n var res = {};\n for (let i = 0; i < mandatory.length; i++) {\n if (elem.hasAttribute(mandatory[i])) {\n let val = elem.getAttribute(mandatory[i]);\n res[mandatory[i]] = val;\n } else {\n return null;\n }\n }\n\n for (let i = 0; i < optional.length; i++) {\n if (elem.hasAttribute(optional[i])) {\n let val = elem.getAttribute(optional[i]);\n res[optional[i]] = val;\n }\n }\n\n return res;\n }",
"findSignInElement(data,matchCriteria){\n var elemmentToSearch=\"input\";\n if(matchCriteria.element){\n elemmentToSearch=matchCriteria.element;\n }\n if(!data[elemmentToSearch]){\n data[elemmentToSearch]={\n elements:document.getElementsByTagName(elemmentToSearch)\n };\n }\n var elementsToMatch=data[elemmentToSearch].elements;\n\n if((!elementsToMatch) || (!elementsToMatch.length)){\n //if there is no any controllable elements in the page, it will not operate\n return null;\n }\n\n\n for(var x=0;x<elementsToMatch.length;x++){\n var currentElement=elementsToMatch[x];\n var attrData={matched:0};\n this.matchAttribute(attrData,currentElement,\"id\",matchCriteria.id);\n this.matchAttribute(attrData,currentElement,\"name\",matchCriteria.name);\n this.matchAttribute(attrData,currentElement,\"type\",matchCriteria.type);\n this.matchAttribute(attrData,currentElement,\"class\",matchCriteria.className);\n this.matchAttribute(attrData,currentElement,\"data-callback\",matchCriteria.dataCallback);\n this.matchAttribute(attrData,currentElement,\"value\",matchCriteria.value);\n this.matchAttribute(attrData,currentElement,\".textContent\",matchCriteria.textContent);\n this.matchChildElement(attrData,currentElement,matchCriteria.childElement);\n if(attrData.matched===1){\n return currentElement;\n }\n }\n return null;\n }",
"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 findNodeWithAtt(nodes, nodeName, att, attValue, checkSameLengthValue){\r\n\tfor(var i = (nodes.length - 1); i >= 0; i--){\r\n \t\tvar currentNode = nodes[i];\r\n \t\tif(currentNode.nodeName == nodeName && currentNode.attributes.getNamedItem(att) != null){\r\n \t\t\tvar nodeAttValue = currentNode.attributes.getNamedItem(att).value;\r\n \t\t\tif(nodeAttValue != null && checkSameLengthValue\r\n \t\t\t\t\t&& nodeAttValue.length > attValue.length){\r\n \t\t\t\tnodeAttValue = nodeAttValue.substring(0, attValue.length);\r\n \t\t\t}\r\n \t\t\tif(nodeAttValue == attValue){\r\n \t\t\t\treturn currentNode;\r\n \t\t\t}\r\n \t\t}\r\n \t\tif(currentNode.hasChildNodes()){\r\n \t\t\tvar rtn = findNodeWithAtt(currentNode.childNodes, nodeName, att, attValue, checkSameLengthValue);\r\n \t\t\tif(rtn != null){\r\n \t\t\t\treturn rtn;\r\n \t\t\t}\r\n \t\t}\r\n \t}\r\n \treturn null;\r\n}",
"function filteredElements(nodeList) {\n var filtered = [];\n for (var i = 0; i < nodeList.length; i++) {\n var node = nodeList[i];\n if (node.nodeType !== 3) { // Don't process text nodes\n var $element = $(node);\n if ( $element.closest('.ant,.ant_indicator,.ant-custom-cta-container').length === 0 ) {\n filtered.push($element);\n }\n }\n }\n return filtered;\n }",
"function GetContentScanner( tagNameArray, optionalAttribName, attribValueArray )\n{\n\tthis._optionalAttribName = optionalAttribName;\n\tthis._attribValueArray = {};\n\tthis._findLookup = {};\n\tthis._eachAttribValue = false;\n\tvar index;\n\tif (tagNameArray)\n\t{\n\t\tfor( index = 0; index < tagNameArray.length; index++)\n\t\t\tthis._findLookup[ tagNameArray[ index ] ] = 1;\n\t}\n\tif (attribValueArray)\n\t{\n\t\tif (attribValueArray.length == 0)\n\t\t{\n\t\t\t// if the value array is there but empty, collect contents for all attrib values,\n\t\t\t// but each value separately (like for media type in style tags)\n\t\t\tthis._eachAttribValue = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor( index = 0; index < attribValueArray.length; index++)\n\t\t\t\tthis._attribValueArray[ attribValueArray[ index ] ] = 1;\n\t\t}\n\t}\n}",
"function getAllHtml(elements) {\n\n\tvar retArr = jQuery.map(elements, function(item, index) {\n\t\treturn objectOrEmptyString($(item).html())\n\t})\n\n\treturn retArr\n\n}",
"function getDisabledItems(){\n\tvar el = new Array();\n\tvar tags = document.getElementsByTagName('*');\n\tvar tcl = \" disabled \";\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, 8) + \" \";\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 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}",
"getAttributeList() {\n this.ensureParsed();\n return this.attributes_;\n }",
"function loadElementsAttributes(abilityNames, defenseNames, attributeNames){\n\tvar output = ''\n\t\n\t//Load main abilities\n\tfor (var i = 0; i < abilityNames.length; i++ ) {\n\t\tvar buffer = replaceAll('{ability}', abilityNames[i], abilityTemplate);\n\t\toutput += replaceAll('{ABILITY}', abilityNames[i].toUpperCase(), buffer);\n\t}\n\t\n\t//Load defense abilities\n\tfor (var i = 0; i < defenseNames.length; i++ ) {\n\t\tvar buffer = replaceAll('{defense}', defenseNames[i], defenseTemplate);\n\t\toutput += replaceAll('{DEFENSE}', defenseNames[i].toUpperCase(), buffer);\n\t}\n\tabilityContainer.innerHTML = output;\n\t\n\toutput = '';\n\t//Load attributes\n\tfor (var i = 0; i < attributeNames.length; i++ ) {\n\t\tvar buffer = replaceAll('{attr}', attributeNames[i], attributeTemplate);\n\t\toutput += replaceAll('{Attr}', capitalize(attributeNames[i]), buffer);\n\t}\n\tattributes.innerHTML = output;\n}",
"getElement(elementText){\n return $('//span[contains(text(), \"'+elementText+'\")]')\n }",
"function fetchTags(xmlDoc,nodeType)\n {\n var node = xmlDoc.documentElement;\n var nodes = node.querySelectorAll(\"*\");\n var childrenNodes =[];\n for (var i = 0; i < nodes.length; i++) \n {\n var text = null;\n if (nodes[i].childNodes.length == 1 && nodes[i].childNodes[0].nodeType == nodeType) //if nodeType == text node\n if(doesNotExist(nodes[i].tagName,childrenNodes))\n childrenNodes.push(nodes[i].tagName);\n }\n return childrenNodes;\n }",
"getMetaTags() {\n return this._currentDom.getElementsByTagName(\"meta\");\n }",
"function elements() {\n return _elements;\n }",
"function getInputs() {\n var allInputArea = document.getElementsByTagName('input')\n var results = []\n\n for (var i = 0; i < allInputArea.length; i++) {\n results.push(allInputArea[i])\n }\n return results\n}",
"function genAttrQueries(a, h, t, rxs) {\r\n\t\tvar ra = {\r\n\t\t\titems : [],\r\n\t\t\tsel : '',\r\n\t\t\tmethod : h,\r\n\t\t\ttype : t\r\n\t\t};\r\n\t\tvar y = '';\r\n\t\tvar x = $.isArray(a) ? a : a && typeof a === 'string' ? a.split(',')\r\n\t\t\t\t: [];\r\n\t\tfor (var i = 0; i < x.length; i++) {\r\n\t\t\ty = '[' + x[i] + ']';\r\n\t\t\tra.items.push({\r\n\t\t\t\tname : x[i],\r\n\t\t\t\tsel : y,\r\n\t\t\t\tregExp : new RegExp('\\\\s' + x[i] + rxs, 'ig')\r\n\t\t\t});\r\n\t\t\tra.sel += ra.sel.length > 0 ? ',' + y : y;\r\n\t\t}\r\n\t\treturn ra;\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The function saveMeme attempts to save the meme to the database | function saveMeme() {
//Get the meme data as provided by the user
var title = document.getElementById("title").value;
var topText = document.getElementById("topText").value;
var bottomText = document.getElementById("bottomText").value;
var fontSize = document.getElementById("fontSize").value;
var fontFamily = document.getElementById("fontFamily").value;
var imgSrc = document.getElementById("img1").src;
//Call applyChanges to make the changes in canvas
applyChanges();
//Save the canvas image's URL
var memeSrc = document.getElementById("memeCanvas").toDataURL();
//Get the current date to save the date modified
var dateObj = new Date();
var date = dateObj.getDate();
var month = dateObj.getMonth();
var year = dateObj.getFullYear();
var today = month + "/" + date + "/" + year;
//Make a JSON object for the meme data
var meme = {
title: title,
topText: topText,
bottomText: bottomText,
fontSize: fontSize,
fontFamily: fontFamily,
imgSrc: imgSrc,
memeSrc: memeSrc,
date: today
};
//Get the user's memes from Firebase
var database = firebase.database();
var user = firebase.auth().currentUser;
var ref = database.ref(user.uid);
//If the user is adding a new meme push the new meme
if (sessionStorage.getItem("index") == "-1") {
ref.push(meme, function (error) {
//Let the user know of the error that occurred
if (error) {
alert(error);
}
//Let the user know their meme was saved successfully and redirect them to their read page
else {
alert("Meme Saved!");
window.location = "read.html";
}
});
}
//If the user is editing an existing meme call updateMeme
else {
ref.once('value', function (data) { updateMeme(meme,data); }, errData);
}
} | [
"function addMemeToAccount(uid, meme) {\n let topText = meme.topText;\n let bottomText = meme.bottomText;\n let imageURL = meme.backgroundImage;\n let memeUri = meme.memeUri;\n var d = new Date().toString();\n db.ref(\"profile/\" + uid + \"/memes\")\n .push({\n topText: topText,\n bottomText: bottomText,\n backgroundImageURL: imageURL,\n memeUri: memeUri,\n dateCreated: d \n })\n .then(res => {\n console.log(res);\n alert(\"Success\");\n })\n .catch(error => {\n console.log(error.message);\n });\n}",
"save() {\n var elem = this._view.getNote(),\n data = validate.getSanitizedNote({\n id: this.id,\n content: elem.html(),\n settings: elem.data(\"settings\")\n });\n \n this._model.setData(\n data,\n (d) => {\n console.log(\"saved\");\n }, (e) => {\n console.log(e);\n }\n );\n }",
"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 }",
"saveGoal(data) {\n let goal = this.get('store').createRecord('goal', data);\n goal.save()\n }",
"function editSave() {\n if (!inputValid()) return;\n vm.editObj.id = -3;\n server.addBuoy(vm.editObj).then(function(res) {\n queryBuoys();\n queryBuoyInstances();\n gui.alertSuccess('Buoy added.');\n }, function(res) {\n gui.alertBadResponse(res);\n vm.buoys.splice(vm.buoys.length - 1, 1);\n });\n vm.editId = -1;\n }",
"function myLoansSaveLoan() {\n \n // TO DO\n // save the details of the loan to the db\n \n}",
"function doSaveMonster()\r\n{\r\n\tconsole.log(\"saving monster\");\r\n\tvar blank = bestiary[0]; \r\n\tblank.name = $('#m_name').val();\r\n\tblank.classes.class1.name = $('#m_class1').val(); \r\n\tblank.classes.class2.name = $('#m_class2').val();\r\n\tblank.alignment = $('#m_alignment').val();\r\n\tblank.hitPoints.hp = $('#m_hp').val();\r\n\tblank.hitPoints.hitDie = $('#m_hitdie').val(); \r\n\tblank.spatial.size = $('#m_size').val(); \r\n\tblank.combatInfo.ac = $('#m_ac').val(); \r\n\tblank.combatInfo.cr = $('#m_cr').val(); \r\n\tblank.combatInfo.melee = $('#m_melee').val(); \r\n\tblank.combatInfo.ranged = $('#m_ranged').val(); \r\n\tblank.combatInfo.ac_touch = $('#m_actouch').val(); \r\n\tblank.combatInfo.ac_flatFooted = $('#m_acflat').val(); \r\n\tblank.savingThrows.fort = $('#m_forts').val(); \r\n\tblank.savingThrows.ref = $('#m_refs').val(); \r\n\tblank.savingThrows.wil = $('#m_wils').val(); \r\n\r\n\tblank.abilityScores.str = $('#m_str').val(); \r\n\tblank.abilityScores.dex = $('#m_dex').val(); \r\n\tblank.abilityScores.con = $('#m_con').val(); \r\n\tblank.abilityScores.int = $('#m_int').val(); \r\n\tblank.abilityScores.wis = $('#m_wis').val();\r\n\tblank.abilityScores.cha = $('#m_cha').val(); \r\n\r\n\tblank.notes = $('#notesarea').val();\r\n\r\n\tblank.classes.class1.levels = $('#m_class1levels').val(); \r\n\tblank.classes.class2.levels = $('#m_class2levels').val(); \r\n\r\n\tvar skills = $('#m_skills').val(); \r\n\tskills = skills.split(','); \r\n\tfor(var i = 0; i < skills.length; i++)\r\n\t{\r\n\t\tblank.skills.push(skills[i]);\r\n\t}\r\n\r\n\tvar feats = $('#m_feats').val(); \r\n\tfeats = feats.split(','); \r\n\tfor(var i = 0; i < feats.length; i++)\r\n\t{\r\n\t\tblank.feats.push(feats[i]);\r\n\t}\r\n\r\n\tconsole.log(blank);\r\n\r\n\r\n\t var a = document.createElement('div'); \r\n\t $(a).addClass('iconarea')\r\n\t var b = document.createElement('div'); \r\n\t $(b).addClass('monstericon genericicon');\r\n\t $(a).append(b); \r\n\t var p = document.createElement('p'); \r\n\t $(p).html(blank.name);\r\n\t $(a).append(p); \r\n\t $('#newmonster').before(a);\r\n}",
"saveVisit() {\n\t\tthis.errorBox.style.display = \"none\";\n\n\t\t//Assemble the names.\n\t\tvar name = \"\";\n\t\tvar nameTokens = this.namesBox.querySelectorAll(\".name-token\");\n\t\tfor (var i = 0; i < nameTokens.length; i++) {\n\t\t\tvar token = nameTokens[i];\n\t\t\tif (name != \"\") {\n\t\t\t\tname += \", \";\n\t\t\t}\n\t\t\tname += nameTokens[i].innerText;\n\t\t}\n\n\t\t//If there are no names, display an error.\n\t\tif (name == \"\") {\n\t\t\tthis.errorBox.innerText = \"Du musst mindestens einen Namen eingeben.\";\n\t\t\tthis.errorBox.style.display = \"\";\n\t\t\treturn;\n\t\t}\n\n\t\t//Gather the served meals.\n\t\tvar meals = [ ];\n\t\tvar mealRows = this.servedMealsContainer.querySelectorAll(\".meal-row\");\n\t\tfor (var i = 0; i < mealRows.length; i++) {\n\t\t\tvar row = mealRows[i];\n\t\t\tvar mealTypeField = row.querySelector(\".meal-type-field\");\n\t\t\tvar mealField = row.querySelector(\".meal-field\");\n\n\t\t\t//If both fields are empty, skip this meal row.\n\t\t\tif (!mealTypeField.value && !mealField.value) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tmeals.push({\n\t\t\t\tmeal_type: mealTypeField.value,\n\t\t\t\tmeal: mealField.value\n\t\t\t});\n\t\t}\n\n\t\tvar visit = {\n\t\t\tname: name,\n\t\t\tdate: this.dateField.value,\n\t\t\tvisit_type: this.visitTypeSelect.value,\n\t\t\tvisit_purpose: this.visitPurposeField.value,\n\t\t\tmeals: meals,\n\t\t\tbrought_items: this.broughtItemsField.value,\n\t\t\tdescription: this.descriptionField.value\n\t\t};\n\n\t\tif (this.visitId) {\n\t\t\tvisit.visit_id = this.visitId;\n\t\t}\n\n\t\tthis.saveVisitRequest.send(visit);\n\t}",
"function save(params) {\n var item = {\n roomName: { S: 'kari' },\n unixTime: { N: (new Date().getTime()).toString() },\n name: { S: params.name },\n message: { S: params.message },\n date: { S: params.date },\n size: { S: params.size || 'normal' },\n color: { S: params.color || 'color1' },\n isSystem: { BOOL: params.isSystem }\n };\n var params = {\n TableName: 'goodbye-cgiboy',\n Item: item\n };\n dy.putItem(params, function (err, data) {\n if (err) {\n console.log(err);\n } else {\n console.log(data);\n }\n });\n}",
"async save() {\n // Use replace instead of has been fully updated in any way\n if (this.__fullUpdate) {\n return await this.replace();\n }\n\n // Ensure model is registered before saving model data\n assert.instanceOf(this.constructor.__db, DbApi, 'Model must be registered.');\n\n // Call internal DB API to save changes to this Model instance\n const id = await this.constructor.__db.save(this, this.__updates, this.__id);\n\n // Set ID if ID returned\n if (id != null) {\n this.__id = id;\n }\n\n // Reset internally stored updates\n this.__updates = new Set();\n this.__fullUpdate = false;\n }",
"saveToDB() {\n\t\t// Saves Session info to state\n\t\tthis.sessionToDB = {\n\t\t\tcourse : this.selectedCourse,\n\t\t\ttime : this.activeSession.time,\n\t\t\tdate : new Date()\n\t\t};\n\t\t// Writes to DB\n\t\tglobal.createSession(this.sessionToDB);\n\t}",
"function saveFitness() {\n}",
"function save () {\n\n\tvar title = postTitle.value;\n\tvar content = postContent.value;\n\tvar savedPost = { \"title\": title, \"content\": content };\n\n\tsaving = setInterval( saveItemToLocalStorage, 5000, savedPost, 'savedPost' );\n\n}",
"function MEX_Save() {\n if (mod_MEX_dict.is_permit_admin){\n MEXQ_Save();\n }\n } // MEX_Save",
"function sendDataToPersist() {\n let inputs = memeForm.getElementsByTagName(\"input\");\n let inputname = inputs[\"name\"].value;\n log(\"inputname => \" + inputname);\n if (inputname === \"\") {\n log(\"makePatchRequest\");\n makePatchRequest(inputs);\n } else {\n log(\"makePostRequest\");\n makePostRequest(inputs);\n }\n}",
"function save_instance(form, instance) { \n var arg = new Arguments(arguments, {'fields':null, 'fail_message':'saved', 'commit':true, 'exclude':null});\n var kwargs = arg.kwargs;\n var models = require('doff.db.models.base');\n var opts = instance._meta;\n if (bool(form.errors))\n throw new ValueError(\"The %s could not be %s because the data didn't validate.\".subs(opts.object_name, kwargs['fail_message']));\n var cleaned_data = form.cleaned_data;\n var file_field_list = [];\n for each (var f in opts.fields) {\n if (!f.editable || isinstance(f, models.AutoField) || !(f.name in cleaned_data))\n continue;\n if (kwargs['fields'] && !include(kwargs['fields'], f.name))\n continue;\n if (kwargs['exclude'] && inlcude(kwargs['exclude'], f.name))\n continue;\n // Defer saving file-type fields until after the other fields, so a\n // callable upload_to can use the values from other fields.\n if (isinstance(f, models.FileField))\n file_field_list.push(f);\n else\n f.save_form_data(instance, cleaned_data[f.name]);\n }\n for each (var f in file_field_list)\n f.save_form_data(instance, cleaned_data[f.name]);\n\n // Wrap up the saving of m2m data as a function.\n function save_m2m() {\n var opts = instance._meta;\n var cleaned_data = form.cleaned_data;\n for each (var f in opts.many_to_many) {\n if (kwargs['fields'] && !include(kwargs['fields'], f.name))\n continue;\n if (include(cleaned_data, f.name))\n f.save_form_data(instance, cleaned_data[f.name]);\n }\n }\n if (kwargs['commit']) {\n // If we are committing, save the instance and the m2m data immediately.\n instance.save();\n save_m2m();\n } else {\n // We're not committing. Add a method to the form to allow deferred\n // saving of m2m data.\n form.save_m2m = save_m2m;\n }\n return instance;\n}",
"function updateMeme(meme, data) {\n //Get the index of the image the user edited\n var index = sessionStorage.getItem(\"index\");\n index = parseInt(index);\n\n var counter = 1;\n for (var key2 in data.val()) {\n if (counter == index) {\n //If the meme was found, get the user's UID\n var user = firebase.auth().currentUser;\n\n //Update the meme data with the edits\n firebase.database().ref(user.uid).child(key2).update(meme, function (error) {\n //Let the user know of the error that occurred\n if (error) {\n alert(error);\n }\n\n //Let the user know their edits were saved\n else {\n alert(\"Meme Saved!\");\n window.location = \"read.html\";\n }\n });\n\n //Once the correct meme has been edited we do not need to continue searching the database\n break;\n }\n counter++;\n }\n}",
"save() {\n let component = this;\n let comment = get(this, 'comment');\n\n comment.save().then((comment) => {\n component.set('isEditing', false);\n this._fetchMentions(comment);\n });\n }",
"function save(){\n EWD.sockets.sendMessage({\n type: \"saveLabOrder\",\n params: {\n id: \"1\",\n comment: document.getElementById(\"comment\").value,\n selectedTest: document.getElementById(\"testList\").value,\n collectionType: document.getElementById(\"collectionType\").value ,\n howOften: document.getElementById(\"howOften\").value,\n collectionDate: document.getElementById(\"collectionDate\").value,\n collectionSample: document.getElementById(\"collectionSample\").value,\n specimen: document.getElementById(\"specimen\").value,\n urgency: document.getElementById(\"urgency\").value,\n notifyProviders: document.getElementById(\"selectProvHidden\").value, \n howLong: document.getElementById(\"howLong\").value,\n sender: 'ELOM',\n date: new Date().toUTCString() \n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: checkProjectName Checks whether the current projects name is a valid one or not. | function checkProjectName( name ) {
return !!name && name !== _projectTitlePlaceHolderText;
} | [
"hasProject(name) {\n return this.allWorkspaceProjects.has(name);\n }",
"function checkServerName(serverName) {\n const validationResult = validateProjectName(serverName);\n if (!validationResult.validForNewPackages) {\n error(\n chalk.red(`Cannot create a project named ${chalk.green(`\"${serverName}\"`)} because of npm naming restrictions:\\n`)\n );\n [...(validationResult.errors || []), ...(validationResult.warnings || [])].forEach(err => {\n error(chalk.red(` * ${err}`));\n });\n error(chalk.red('\\nPlease choose a different project name.'));\n process.exit(1);\n }\n\n // TODO: there should be a single place that holds the dependencies\n const dependencies = ['debug', 'dotenv', 'express', 'mysql', 'prettier', 'morgan'].sort();\n\n if (dependencies.includes(serverName)) {\n error(\n chalk.red(\n `Cannot create a project named ${chalk.green(\n `\"${serverName}\"`\n )} because a dependency with the same name exists.\\n` +\n `Due to the way npm works, the following names are not allowed:\\n\\n`\n ) +\n chalk.cyan(dependencies.map(depName => ` ${depName}`).join('\\n')) +\n chalk.red('\\n\\nPlease choose a different project name.')\n );\n process.exit(1);\n }\n}",
"function name_check() {\r\n name_warn();\r\n final_validate();\r\n}",
"function checkName(name) {\n it('Name is defined: ' + name, function() {\n expect(name).toBeDefined();\n expect(name.length).not.toBe(0);\n });\n it('Name is a string', function() {\n expect(name).toEqual(jasmine.any(String));\n });\n }",
"function isValidProject(project) {\n const isValid = VALID_TRACKING_PROJECTS.indexOf(project) !== -1;\n if (!isValid) {\n console.log(chalk.red('Tracking Error:'));\n console.log(`\"${project}\" is invalid project. Must be one of`, VALID_TRACKING_PROJECTS);\n }\n return isValid;\n}",
"function validName(input) {\n return input.length > 0\n }",
"generateProjectName(firstInit) {\n\n // name has not been modified by the user\n if (firstInit || (this.projectInformationForm['deskname'].$pristine && this.projectInformationForm.name.$pristine)) {\n // generate a name\n\n // starts with project\n var name = 'project';\n\n // type selected\n if (this.importProjectData.project.type) {\n name = this.importProjectData.project.type;\n }\n\n name = name + '-' + (('0000' + (Math.random()*Math.pow(36,4) << 0).toString(36)).slice(-4)); // jshint ignore:line\n\n this.importProjectData.project.name = name;\n\n\n }\n\n }",
"function checkProfileName(profileNameToCheck)\n{\n // Check for emtpy profile name.\n if (!/\\S/.test(profileNameToCheck))\n return gProfileManagerBundle.getString(\"profileNameEmpty\");\n\n // Check whether all characters in the profile name are allowed.\n if (/([\\\\*:?<>|\\/\\\"])/.test(profileNameToCheck))\n return gProfileManagerBundle.getFormattedString(\"invalidChar\", [RegExp.$1]);\n\n // Check whether a profile with the same name already exists.\n if (profileExists(profileNameToCheck))\n return gProfileManagerBundle.getString(\"profileExists\");\n\n // profileNameToCheck is valid.\n return \"\";\n}",
"function isValidGroupName(name) {\n\treturn isValidUsername(name);\n}",
"function nameValidation() {\n // Name validation\n const nameValue = name.value;\n const nameValidator = /[a-zA-z]+/.test(nameValue);\n\n return nameValidator;\n}",
"function groupNameValid(name) {\n return (typeof name === \"string\" && name.length <= 50 && name.length > 2)\n}",
"_onInputProjectNameChanged(projectName) {\n if(projectName) {\n this.shadowRoot.getElementById(\"dialog-button-create\").disabled = false;\n } else {\n this.shadowRoot.getElementById(\"dialog-button-create\").disabled = true;\n }\n }",
"function deleteProject() {\n const projectName = helpers.toTitleCase(app.getArgument('projectName'));\n\n if (projectName) {\n let userProjects = db.ref('projects/' + userId);\n\n userProjects.orderByChild('projectName').equalTo(projectName).once('value').then((snapshot) => {\n let projectKey;\n snapshot.forEach((childSnapshot) => {\n if (childSnapshot.val().projectName.toUpperCase() === projectName.toUpperCase()) {\n projectKey = childSnapshot.key;\n }\n });\n\n if (projectKey) {\n app.ask(`Are you sure you want to delete \"${projectName}\"`);\n } else {\n app.tell(`Sorry! We couldn't find any project with the name ${projectName}`);\n }\n\n });\n } else {\n console.error('deleteProject(): Project name is undefined while delete');\n app.tell('Sorry! something went wrong. Please try again later');\n }\n }",
"function isNameOK(field) {\r\n\t\r\n\tvar name = field.value.trim();\r\n\tconsole.log(name); // TEST CODE\r\n\t\r\n\tif (emptyString(name)) {\r\n\t\talert('Le nom du groupe doit être renseigné.');\r\n\t\treturn false;\r\n\t}\r\n\telse if (fiftyChar(name)) {\r\n\t\talert('Le nom du groupe ne peut pas dépasser cinquante caractères.');\r\n\t\treturn false;\r\n\t}\r\n\telse {\r\n\t\treturn true;\r\n\t}\r\n}",
"function isValidPackageName(name) {\n // return isNormalPackageName(name) || isScopedPackageName(name);\n return validate(name).validForNewPackages;\n}",
"function nameValidate(name) {\r\n var nameValue = document.getElementById('contact-name').value;\r\n var nameRegex = /^[a-zA-Z \\-\\']+(?:\\s[a-zA-Z]+)*$/.test(nameValue);\r\n var inputErr = document.getElementsByTagName('input')[1];\r\n\r\n if (nameValue == null || nameValue == \"\") {\r\n document.getElementById('name-err').innerHTML = \"This field is required.\";\r\n inputErr.setAttribute('class', 'input-err');\r\n document.getElementById('name-err').style.display = 'block';\r\n return false;\r\n } else if (!nameRegex) {\r\n document.getElementById('name-err').innerHTML = \"Alphabet characters only.\";\r\n inputErr.setAttribute('class', 'input-err');\r\n document.getElementById('name-err').style.display = 'block';\r\n return false;\r\n } else if (nameRegex) {\r\n var inputValid = document.getElementsByTagName('input')[1];\r\n inputValid.setAttribute('class', 'input-valid');\r\n document.getElementById('name-err').style.display = 'none';\r\n return true;\r\n }\r\n }",
"function checkContractName(contractName) {\n if (!contractName || (typeof contractName !== 'string') || contractName.trim() === '') {\n throw new Error('Contract: Contract name: \"' + contractName + '\" is invalid.');\n }\n }",
"function checkInProject() {\n const projectName = helpers.toTitleCase(app.getArgument('projectName'));\n const description = app.getArgument('description');\n\n let userCheckIn = db.ref('checkIn/' + userId);\n\n userCheckIn.once('value').then((snapshot) => {\n if (snapshot.exists() && snapshot.val().checkInStatus) {\n let oldProjectName = snapshot.val().projectName;\n app.ask(`You are currently clocked in to ${oldProjectName}. Simply say, \"Switch\" to log in to another project.`);\n } else {\n let userProjects = db.ref('projects/' + userId);\n\n userProjects.orderByChild('createdOn').once('value').then((snapshot) => {\n\n // if user have not created any projects yet\n if (snapshot.numChildren() <= 0) {\n app.ask(`Sorry! Haven't seen you create a project. Say, \"Create a project\", to create a new project.`);\n return;\n }\n\n let projectNameExists = false;\n snapshot.forEach((childSnapshot) => {\n if (childSnapshot.val().projectName.toUpperCase() === projectName.toUpperCase()) {\n projectNameExists = true;\n }\n });\n\n if (projectNameExists) {\n\n const checkInTime = new Date().getTime();\n\n let date = moment().format('DD-MM-YYYY');\n let userLogs = db.ref('logs/' + userId);\n let userCheckIn = db.ref('checkIn/' + userId);\n\n userCheckIn.set({projectName: projectName, checkInTime: checkInTime, checkInStatus: true});\n userLogs.push({\n projectName: projectName,\n checkInDate: date,\n checkInTime: checkInTime,\n description: description,\n checkOutTime: ''\n });\n\n app.tell(`Great! You have been successfully checked in to ${projectName}.`);\n } else {\n app.ask(`Oops! ${projectName} doesn't exist. Please say \"create a project\" to create a new one.`);\n }\n });\n }\n });\n }",
"function validatePlayerName() {\n const name = getGameForm()['player-name'].value;\n if (!name.trim()) {\n getById('play-button').style.visibility = 'hidden';\n } else {\n playerName = name;\n getById('play-button').style.visibility = 'visible';\n }\n}",
"function validateName()\n{\n\t//variable name is set by element id contactName from the form\n\tvar name = document.getElementById(\"contactName\").value; \n\t\n\t//validation for name\n\tif(name.length == 0)\n\t{\n\t\tproducePrompt(\"Name is Required\", \"namePrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tif(!name.match(/^[A-Za-z]*\\s{1}[A-Za-z]*$/))\n\t{\n\t\tproducePrompt(\"First and Last name Please\", \"namePrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tproducePrompt(\"Welcome \" + name, \"namePrompt\", \"green\"); \n\t\treturn true; \n\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is the old translateNested2 helper function. Translates e.g. "health(e1)" to "e1_health". | function translateNested2(x){
var newX = x;
if (x.indexOf("(")>0){
// Find inner and outer terms.
var innerStart = x.indexOf("(");
var innerEnd = x.indexOf(")");
var inside = x.substring(innerStart+1,innerEnd);
var outside = x.substring(0,innerStart);
newX = inside+"_"+outside;
}
return newX;
} | [
"function translateNested(x){\n var newX = x;\n if (x.indexOf(\"(\")>0){\n // Find inner and outer terms.\n var innerStart = x.indexOf(\"(\");\n var innerEnd = x.indexOf(\")\");\n var inside = x.substring(innerStart+1,innerEnd);\n var outside = x.substring(0,innerStart);\n newX = inside+\".\"+outside;\n }\n return newX;\n }",
"_evalExpression(exp) {\n exp = exp.trim();\n\n // catch special cases, with referenced properties, e.g. resourceGroup().location\n let match = exp.match(/(\\w+)\\((.*)\\)\\.(.*)/);\n if(match) {\n let funcName = match[1].toLowerCase();\n let funcParams = match[2];\n let funcProps = match[3].toLowerCase();\n if(funcName == 'resourcegroup' && funcProps == 'id') return 'resource-group-id'; \n if(funcName == 'resourcegroup' && funcProps == 'location') return 'resource-group-location'; \n if(funcName == 'subscription' && funcProps == 'subscriptionid') return 'subscription-id'; \n if(funcName == 'deployment' && funcProps == 'name') return 'deployment-name'; \n }\n \n // It looks like a function\n match = exp.match(/(\\w+)\\((.*)\\)/);\n if(match) {\n let funcName = match[1].toLowerCase();\n let funcParams = match[2];\n //console.log(`~~~ function: *${funcName}* |${funcParams}|`);\n \n if(funcName == 'variables') {\n return this._funcVariables(this._evalExpression(funcParams));\n }\n if(funcName == 'uniquestring') {\n return this._funcUniquestring(this._evalExpression(funcParams));\n } \n if(funcName == 'concat') {\n return this._funcConcat(funcParams, '');\n }\n if(funcName == 'parameters') {\n // This is a small cop out, but we can't know the value of parameters until deployment!\n // So we just display curly braces around the paramter name. It looks OK\n return `{{${this._evalExpression(funcParams)}}}`;\n } \n if(funcName == 'replace') {\n return this._funcReplace(funcParams);\n } \n if(funcName == 'tolower') {\n return this._funcToLower(funcParams);\n } \n if(funcName == 'toupper') {\n return this._funcToUpper(funcParams);\n } \n if(funcName == 'substring') {\n return this._funcSubstring(funcParams);\n } \n if(funcName == 'resourceid') {\n // Treat resourceId as a concat operation with slashes \n let resid = this._funcConcat(funcParams, '/');\n // clean up needed\n resid = resid.replace(/^\\//, '');\n resid = resid.replace(/\\/\\//, '/');\n return resid;\n } \n }\n\n // It looks like a string literal\n match = exp.match(/^\\'(.*)\\'$/);\n if(match) {\n return match[1];\n }\n\n // It looks like a number literal\n match = exp.match(/^(\\d+)/);\n if(match) {\n return match[1].toString();\n }\n\n // Catch all, just return the expression, unparsed\n return exp;\n }",
"visitDotted_as_name(ctx) {\r\n console.log(\"visitDotted_as_name\");\r\n if (ctx.NAME() !== null) {\r\n return {\r\n type: \"Imported\",\r\n name: this.visit(ctx.dotted_name()),\r\n alias: ctx.NAME().getText(),\r\n };\r\n } else {\r\n return {\r\n type: \"Imported\",\r\n name: this.visit(ctx.dotted_name()),\r\n alias: null,\r\n };\r\n }\r\n }",
"getFieldLabels() {\n return {\n \"name\":t(\"Name\"),\n \"parent\": t(\"Parent Category\")\n }\n }",
"function createCustomTypeName(type, parent) {\n var parentType = parent ? parent.key : null;\n var words = type.split(/\\W|_|\\-/);\n if (parentType) words.unshift(parentType);\n words = words.map(function (word) {\n return word[0].toUpperCase() + word.slice(1);\n });\n return words.join('') + 'Type';\n}",
"function abbreviatedFun(fullname) {\n let array = fullname.split(' ');\n let result = array[0];\n for (i = 1; i < array.length; i++) {\n result += ' ' + (array[i])[0];\n }\n result += '.';\n return result;\n \n}",
"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 convertToL33t(leetLevel, message)\n{\n\tif (leetLevel > -1) {\n\t\tvar ret = message.toLowerCase();\n\t\tfor (var item = 0; item < alphabet.length; item++)\n\t\t\tret = ret.replace(alphabet[item], levels[leetLevel][item]);\n\t\treturn ret;\n\t}\n\treturn message;\n}",
"async function getName(ctx) {\n await CONTEXT_SCHEMA.validate(ctx);\n if (ctx.sub.length < 1) {\n return ctx.name;\n }\n\n return `${ctx.name}(${ctx.sub.join(',')})`;\n}",
"visitLabel_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function replaceInnerComma(str){\n\t\t\tvar pos=str.indexOf(\"(\");\n\t\t\twhile(pos>-1){\n\t\t\t\tvar endPos=str.indexOf(\")\",pos+1);\n\t\t\t\tvar newMiddle=str.substr(pos,endPos-pos).replace(/,/g,\"##comma##\");\n\t\t\t\tstr=str.substr(0,pos)+newMiddle+str.substr(endPos);\n\t\t\t\tpos=str.indexOf(\"(\",endPos+1);\n\t\t\t};\n\t\t\treturn str;\n\t\t}",
"function fixStateName(state){\r\n if(state.parent){\r\n state.name = (angular.isObject(state.parent) ? state.parent.name : state.parent) + '.' + state.name;\r\n }\r\n }",
"visitString_function_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSubpartition_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitNested_item(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function translateParserNames(name) {\n var translated;\n switch (name) {\n case '\\'ALL\\'':\n case '\\'ANY\\'':\n case '\\'IP\\'':\n case '\\'SUBNET\\'':\n case '\\'TAG\\'':\n case '\\'VM\\'':\n case 'WORD':\n translated = name.toLowerCase();\n break;\n default:\n translated = name;\n break;\n }\n\n return translated;\n}",
"function translateResourceLabel(terms){\n var name = terms[0].terms[0].predicate;\n var label = terms[1].predicate;\n var readWriteValue = \"private\"\n if(terms[2] !== undefined){\n //if it has a read write value\n readWriteValue = terms[2].predicate;\n }\n return {\"l\": [name], \"relation\":\"has_label\", \"r\":[label], \"readWrite\" : readWriteValue}\n //return translateSimpleTriple(\"has_label\",terms);\n }",
"function getSub (tag){\n var sub = \"\";\n for(var i = 0; i < tags.length; ++i){\n if(tags[i].name == tag) sub = tags[i].Sub;\n }\n return sub;\n }",
"visitParameter_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function to switch between two objects | function toggleBetween(obj1, obj2) {
toggle(obj1);
toggle(obj2);
} | [
"switchPlayers(){\n if(this.currentPlayer == this.player1){\n this.currentPlayer = this.player2;\n }\n else this.currentPlayer = this.player1;\n }",
"_changeTarget() {\n this._targetPlanet =\n this._targetPlanet === this._redBigPlanet\n ? this._blueBigPlanet\n : this._redBigPlanet;\n }",
"function switchItem2(toHide, toShow) {\r\n hideItem(toHide);\r\n showItem(toShow);\r\n}",
"function switchPlayers() {\r\n if (currentPlayer == \"p1\") {\r\n currentPlayer = \"p2\";\r\n $(\"h1\").removeClass(\"p1T\");\r\n $(\"h1\").addClass(\"p2T\");\r\n // $(\"playerInd\").addClass(\"srb\");\r\n $(\".button\").removeClass(\"element-animation\");\r\n } else {\r\n currentPlayer = \"p1\";\r\n $(\"h1\").removeClass(\"p2T\");\r\n $(\"h1\").addClass(\"p1T\");\r\n $(\".button\").removeClass(\"element-animation1\");\r\n }\r\n }",
"function swapGun()\n{\n let tmp = gun;\n selectGun(prevGun);\n prevGun = tmp;\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 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}",
"function testOutOfOrderSwitchB() {\n\n\n var frp = new recoil.frp.Frp();\n var tm = frp.tm();\n var map = {0: frp.createB(\"a\")};\n var chooserB = frp.createB(0);\n var selectorB = frp.liftB(function (v) {\n console.log(\"V\", v, map[v]);\n return map[v];\n },chooserB);\n\n \n var swB = frp.switchB(selectorB);\n\n tm.attach(swB);\n\n\n assertEquals(\"a\", swB.unsafeMetaGet().get());\n \n map[1]= frp.createB(\"b\");\n frp.accessTrans(function() {\n chooserB.set(1);\n }, chooserB);\n \n\n assertEquals(\"b\", swB.unsafeMetaGet().get());\n\n\n \n frp.accessTrans(function() {\n map[1].set(\"bb\");\n }, chooserB);\n\n assertEquals(\"bb\", swB.unsafeMetaGet().get());\n\n\n \n}",
"function switchPlayer() {\n if (curPlayer == \"NASA\") {\n curPlayer = \"USSR\";\n } else { //curPlayer == \"USSR\"\n curPlayer = \"NASA\";\n }\n }",
"function switchPlayer(id)\n{\n\t// There is no use in switching to itself again\n\tif(playerId != id)\n\t{\n\t\tconsole.log(\"Player switched to: \" + id);\n\t\tplayerId = id;\n\t\tupdateCamera();\n\t\tanimate();\n\t}\n}",
"transitTakenInteractable(fromScene, toScene) {\n if (this.takenInteractable) {\n /**\n * Menu 'Put back' is available only in the VLabScene from which takenInteractable has been taken\n */\n for (let i = 0; i < this.takenInteractable.menu.length; i++) {\n if (this.takenInteractable.menu[i].label == 'Put back') {\n if (this.takenInteractable.menu[i].context && this.takenInteractable.menu[i].originalScene) {\n if (this.takenInteractable.menu[i].originalScene == toScene) {\n this.takenInteractable.menu[i].enabled = true;\n } else {\n this.takenInteractable.menu[i].enabled = false;\n }\n } else {\n this.takenInteractable.menu[i].enabled = false;\n }\n }\n }\n\n fromScene.currentCamera.remove(this.takenInteractable.vLabSceneObject);\n toScene.currentCamera.add(this.takenInteractable.vLabSceneObject);\n\n fromScene.currentCamera.remove(this.takenInteractable.boundsSprite);\n toScene.currentCamera.add(this.takenInteractable.boundsSprite);\n\n /**\n * Transit all siblings of this.takenInteractable, updating toScene.interactables;\n * Used this.takenInteractable.vLabSceneObject siblings' names\n */\n this.takenInteractable.vLabSceneObject.traverse((takenInteractableVLabSceneObjectSibling) => {\n if (fromScene.interactables[takenInteractableVLabSceneObjectSibling.name] !== undefined) {\n toScene.interactables[takenInteractableVLabSceneObjectSibling.name] = fromScene.interactables[takenInteractableVLabSceneObjectSibling.name];\n toScene.interactables[takenInteractableVLabSceneObjectSibling.name].vLabScene = toScene;\n delete fromScene.interactables[takenInteractableVLabSceneObjectSibling.name];\n }\n });\n\n /**\n * Hold this.takenInteractable selection\n */\n if ((this.takenInteractable.selection && this.takenInteractable.selection.hold) && toScene.selectedInteractables.indexOf(this.takenInteractable) == -1) {\n toScene.selectedInteractables.push(this.takenInteractable);\n }\n\n this.vLab.EventDispatcher.notifySubscribers({\n target: 'VLabSceneInteractable',\n type: 'transitTakenInteractable',\n interactable: this.takenInteractable,\n fromScene: fromScene,\n toScene: toScene\n });\n }\n }",
"function alternateDisplay(obj1,obj2)\n{\n obj1.style.display=\"inline\";\n obj2.style.display=\"none\";\n}",
"function moveObject(object) {\n // Switch based on object's current location to select destination\n // Your items <--> Your offerings\n // Their items <--> Their offerings\n var parentName = $(object).parent().attr('id');\n switch (parentName) {\n case \"yourItems\":\n $(\"#yourOffering\").append(object);\n $(object).addClass(\"item-preview-in-trade\");\n filterTradeItems(true);\n\n itemsOffered++;\n $(\"#yourOffering\").find('.placeholder').hide();\n break;\n case \"theirItems\":\n $(\"#theirOffering\").append(object);\n $(object).addClass(\"item-preview-in-trade\");\n filterTradeItems(false);\n\n itemsReceived++;\n $(\"#theirOffering\").find('.placeholder').hide();\n break;\n case \"yourOffering\":\n $(\"#yourItems\").append(object);\n $(object).removeClass(\"item-preview-in-trade\");\n filterTradeItems(true);\n\n itemsOffered--;\n if (itemsOffered == 0) {\n $(\"#yourOffering\").find('.placeholder').show();\n }\n break;\n case \"theirOffering\":\n $(\"#theirItems\").append(object);\n $(object).removeClass(\"item-preview-in-trade\");\n filterTradeItems(false);\n\n itemsReceived--;\n if (itemsReceived == 0) {\n $(\"#theirOffering\").find('.placeholder').show();\n }\n break;\n }\n updateTradeValue();\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}",
"function _jsTabControl_switchTo(idTo, idFrom) {\n\tdocument.getElementById(idFrom).style.visibility = \"hidden\";\n\tdocument.getElementById(idFrom).style.top = \"-1000pt\";\n\tdocument.getElementById(idTo).style.visibility = \"visible\";\n\tdocument.getElementById(idTo).style.top = this.top;\t\n}",
"switchUser() {\n this.currentPlayer = this.currentPlayer == 1 ? 0 : 1;\n this.io.to(this.id).emit('g-startTurn', this.players[this.currentPlayer]);\n }",
"function switchPressTwo(){\n\t\tif(document.getElementById(\"relay2\").className == \"relay2 active\"){\n\t\t\tmicrogear.chat(\"pieplug\",\"OFF2\");\n\t\t}else if(document.getElementById(\"relay2\").className == \"relay2\"){\n\t\t\tmicrogear.chat(\"pieplug\",\"ON2\");\n\t\t}\n\t}",
"function SetPositionObjectByOtherObject(objToubication, objReference,diffX,diffY)\n {\n \tvar posx = findPosX(objReference);\n\tvar posy = findPosY(objReference);\n\t\n\n\t\n\tnewposx = posx + diffX;\n\tnewposty = posy + diffY;\n\t\n\t\n\tobjToubication.style.left = newposx + 'px';\n\tobjToubication.style.top=newposty + 'px';\n\t\t\n\t\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 }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this will be responsible for updating the score | function updateScore() {
} | [
"set score(newScore) {\r\n score = newScore;\r\n _scoreChanged();\r\n }",
"function updateScore() {\n\t\t\t// Score rule: pass level n in t seconds get ((100 * n) + (180 - t)) points \n\tlevelScore = (levelTime + 100) + Math.floor(levelTime * (currentLevel-1));\n\t// Set original \"levelScore\" to extraLevelScore for testing purpose\n\tfinalScore += levelScore + extraLevelScore;\t\t\n\t// Add finalTime\n\tfinalTime += startLevelTime - levelTime;\n}",
"updateScore() {\n this.serverComm.updateScore(this.userId, this);\n }",
"updateScore(){\n this.score += 1;\n this.labelScore.text = this.score;\n }",
"function updateScore() {\n humanScoreSpan.innerHTML = humanScore;\n computerScoreSpan.innerHTML = computerScore;\n return;\n }",
"function updateScore(){\n scoreText.setText(\"Score: \"+score);\n }",
"set score(val) {\n this._score = val;\n console.log('score updated');\n emitter.emit(G.SCORE_UPDATED);\n }",
"setScore() {\n this.#gameScore += this.#rules[this.#gameLevel - 1].score\n document.dispatchEvent(this.#gameScoreEvent)\n }",
"function updateScoreOverlay() {\n let one = playerNetscore(team.getT1());\n write(t1Players, one);\n one = team.getT1();\n write(t1Score, one.points);\n\n let two = playerNetscore(team.getT2());\n write(t2Players, two);\n two = team.getT2();\n write(t2Score, two.points);\n}",
"function updateScore(elapsedTime){\r\n\t\tif(!myShip.getSpecs().hit && !myShip.getSpecs().invincible){\r\n\t\t\tvar oldCounter = Math.floor(updateScoreCounter);\r\n\t\t\tupdateScoreCounter += elapsedTime/1000;\r\n\t\t\tvar newCounter = Math.floor(updateScoreCounter);\r\n\r\n\t\t\tif(newCounter == oldCounter + 1){\r\n\t\t\t\taddToScore(10);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"function clearScore() {\n currentScore = 0;\n }",
"function getScore()\n {\n return score\n }",
"function addPoint() {\n currentScore = currentScore + 1;\n}",
"function checkScore() {\n if (locArray[currentLocation].hasVisited === false) {\n locArray[currentLocation].hasVisited = true;\n score = score + 5; \n } else if (locArray[currentLocation].hasVisited === true) {\n score = score + 0; \n } \n }",
"setScore () {\n var text = document.getElementById(\"marker\");\n text.innerHTML = \"Score: \" + this.score;\n\n //It sets the difficulty\n if (this.difficulty == this.compareDifficulty && this.score >= this.compareScore && this.difficulty < 9) {\n this.model.remove(this.fly[this.difficulty]);\n var loader = new THREE.TextureLoader();\n var texture = loader.load (\"imgs/fuego.jpg\");\n this.fly[this.difficulty] = new FlyObj(new THREE.MeshPhongMaterial ({map: texture}), false);\n this.model.add(this.fly[this.difficulty]);\n\n this.difficulty++;\n this.compareDifficulty++;\n this.compareScore += 10;\n }\n }",
"function success() {\n score += 1;\n scoreSpan.textContent = score;\n if (score > highScore) {\n highScore = score;\n highScoreSpan.textContent = highScore;\n }\n allEnemies.forEach(function(enemy) {\n enemy.speed = enemy.speed * 1.1;\n });\n player.goBack();\n}",
"function addToScore(points){\r\n\t\tscore += points;\r\n\t\taddLifeRunningTotal += points;\r\n\t}",
"set score(rawScore) {\n this._score.raw = rawScore;\n setValue(`cmi.objectives.${this.index}.score.raw`, rawScore);\n }",
"function incrementScoreAndSendNewBrick() {\n score++;\n $('#score #value').text(score);\n catJumpedOverCurrentBlock = false;\n sendBrick();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the items corresponding to the cases selected by the user. When no cases are selected, all the case are returned as "selected." | getSelectedItems(context) {
return this.codapInterface.sendRequest({
action: 'get',
resource: `dataContext[${context}].selectionList`
}).then(result => {
let selectedItems;
if (result.success) {
let caseIDs = result.values.map(v => v.caseID);
if (caseIDs.length) {
selectedItems = caseIDs
.map(id => {
// item.id is actually the case ID.
return this.items[context]
.find(item => item && item.id === id)
});
} else {
selectedItems = this.items[context];
}
}
else {
selectedItems = [];
}
return selectedItems.filter(item => typeof(item) !== 'undefined');
});
} | [
"get selectedDataItems() {\n return this.composer.queryItemsByPropertyValue('selected', true);\n }",
"function renderSelection()\r\n{\r\n var totalZbllSel = 0;\r\n for (var oll in zbllMap) if (zbllMap.hasOwnProperty(oll)) {\r\n var ollNoneSel = true, ollAllSel = true; // ollNoneSel = 0 selected, ollAllSel = all cases selected\r\n var zbllsInOll = 0;\r\n var ollMap = zbllMap[oll];\r\n for (var coll in ollMap) if (ollMap.hasOwnProperty(coll)) {\r\n var collNoneSel = true, collAllSel = true; // ollNoneSel = 0 selected, ollAllSel = all cases selected\t\r\n var zbllsInColl = 0;\r\n collMap = ollMap[coll];\r\n for (var zbll in collMap) if (collMap.hasOwnProperty(zbll)) {\r\n var zbllAlg = collMap[zbll];\r\n if (collMap[zbll][\"c\"])\r\n {\r\n // case selected\r\n ollNoneSel = false;\r\n collNoneSel = false;\r\n zbllsInColl++; zbllsInOll++; totalZbllSel++;\r\n }\r\n else {\r\n // case not selected\r\n ollAllSel = false;\r\n collAllSel = false;\r\n }\r\n }\r\n // render coll item background\r\n document.getElementById( idTdColl(oll, coll) ).style.backgroundColor = colorBySelection(collAllSel, collNoneSel);\r\n document.getElementById( idHeaderColl(oll, coll) ).innerHTML = collHeaderContent(oll, coll, zbllsInColl);\r\n }\r\n document.getElementById( idTdOll(oll) ).style.backgroundColor = colorBySelection(ollAllSel, ollNoneSel);\r\n document.getElementById( idHeaderOll(oll) ).innerHTML = ollHeaderContent(oll, zbllsInOll);\r\n }\r\n\r\n // Save the selection to local storage if possible\r\n if (window.saveSelection) { // No guarantee that saveSelection function is ready, so test first\r\n saveSelection();\r\n }\r\n}",
"function values(){\n\t\treturn selection;\n\t}",
"getFilters() {\n let cats = _.uniq(_.map(users, function(item){\n return item[filterBy];\n }));\n\n userFilterTitle = `PICK A ${filterBy.toUpperCase()}`;\n userFilters = [{ label: 'ALL', value: 'all', checked: true}];\n cats.forEach(function(cat){\n userFilters.push({\n value: cat,\n label: cat.toUpperCase()\n })\n });\n }",
"checkSelectedDetail() {\n let selectedDetail = '';\n for (var i = 0; i < this.detailOptions.length; i++) {\n if (this.detailOptions[i].value === this.state.levelOfDetail) {\n selectedDetail = this.detailOptions[i].description;\n }\n }\n return selectedDetail;\n }",
"getSelectedValues() {\n return this._options.filter(option => option.selected).map(option => option.value);\n }",
"getSelectedTypes() {\n // get the one or two types selected\n let selectedTypes = [];\n selectedTypes.push(this.type1Picker.querySelector(\".option\").getAttribute(\"data-type\"));\n selectedTypes.push(this.type2Picker.querySelector(\".option\").getAttribute(\"data-type\"));\n\n selectedTypes = selectedTypes.filter((t) => {\n return t.toLowerCase() !== \"unselected\";\n })\n\n return _.uniq(selectedTypes);\n }",
"getSelectedElements() {\n return this.getSelectableElements().filter(item => item.selected);\n }",
"lookupSelectedRegions() {\r\n const collection = Array();\r\n for (const region of this.regions) {\r\n if (region.isSelected) {\r\n collection.push(region);\r\n }\r\n }\r\n return collection;\r\n }",
"function get_datadicts_from_sel_btn() {\n return (selected_btn === \"btn_ete_exams\") ? ete_exam_dicts :\n (selected_btn === \"btn_duo_exams\") ? duo_exam_dicts :\n (selected_btn === \"btn_ntermen\") ? ntermentable_dicts :\n (selected_btn === \"btn_results\") ? grade_exam_result_dicts : null;\n }",
"function anyItemSelected(){\n\tvar result = false;\n\t$(\".filleditem\").each(function() {\n\t\tif ($(this).hasClass(\"selected\")) {\n\t\t\tconsole.log(\"An item is selected\");\n\t\t\tresult = true;\n\t\t}\n\t});\n\treturn result;\n}",
"function ngGridSelectItems(items, state, clear) {\n //items is expected to be an array of numbers or objects\n if (!items || items.constructor !== Array) {\n return;\n }\n\n // block notifications during programmatic selection\n vm.blockSelectionNotifications = true;\n\n var i, index, selItem, dataItem;\n var uniqueID = vm.gridOptions.uniqueID;\n // only operate on the current page of data\n var data = $scope.slicedGridData;\n\n // when selecting consider option to clear existing selections\n if (state && clear) {\n for (i = 0; i < vm.selectedItems.length; i++) {\n selItem = vm.selectedItems[i]\n selItem.selected = false;\n }\n vm.gridOptions.selectAll(false);\n }\n\n // items may be either an index into the data arrary, or references to the actual objects in the data array\n if (items.length > 0) {\n if (typeof items[0] === 'number') {\n // handle selection by index\n for (i = 0; i < items.length; i++) {\n index = items[i];\n selItem = data[index];\n if (selItem) {\n selItem.selected = state;\n vm.gridOptions.selectRow(index, state);\n //vm.gridOptions.selectItem(index, state);\n }\n }\n } else {\n // handle selection by data object\n\n items.forEach(function (item) {\n index = getRowIndex(item, data, uniqueID);\n\n // ng-grid programatically selects items by index if the item is present in current page data\n if (index !== -1) {\n data[index].selected = state;\n vm.gridOptions.selectRow(index, state);\n } else {\n var itemIndex = getRowIndex(item, vm.selectedItems, uniqueID);\n if (itemIndex === -1) {\n state && vm.selectedItems.push(item);\n } else {\n !state && vm.selectedItems.splice(itemIndex, 1);\n }\n }\n });\n }\n }\n // re-enable notifications on UI triggered selection change \n vm.blockSelectionNotifications = false;\n vm.notifySelectionChanged(null);\n updateSelectedItemsCount();\n }",
"selectedList(state) {\n const selectedDirectories = state.directories.filter((directory) =>\n state.selected.directories.includes(directory.path)\n );\n\n const selectedFiles = state.files.filter((file) => state.selected.files.includes(file.path));\n\n return selectedDirectories.concat(selectedFiles);\n }",
"function GetSelectedFields(){\n for (var i = 0; i < fields.selected.length; i++) {\n\n ShowSelectedFieldInputForm(fields.selected., type, id);\n }\n}",
"function getRelatedMenu(value){\r\n\tif(value.length == 0 || value == \"\"){\r\n\t\ttest('No Value is Selected!');\r\n\t\tselectElement(\"addRelatedMenu\").innerHTML = \"<p class='text-center red' style='color: red; border: 1px solid;'>Must Select Menu Category!</p>\"; \r\n\t}\r\n\telse{\r\n\t\ttest(value + ' is Selected!');\r\n\t\t//match selected item\r\n\t\tvar itemName, itemPrice, itemId, \r\n\t\t\tcustomOrder, descriptionRslt, \r\n\t\t\tdescriptionSection, itemDescriped,\r\n\t\t\titemCustom, itemCustomButtons, customItemDetails,\r\n\t\t\tcustomItemAre, customItemTitle = \"\";\r\n\t\tselectElement(\"addRelatedMenu\").innerHTML = \"<h3 class='text-center'>\"+ value +\"</h3>\";\r\n\t\t//get all items on the menu - as long as it is active and the value is the same as the category value selected\r\n\t\tfor(x in Menu['Menu']){\r\n\t\t\tif(Menu['Menu'][x].Category == value && Menu['Menu'][x].Active == true){\r\n\t\t\t\tconsole.log(Menu['Menu'][x].Item + ' ........\\n\\t\\t\\t\\t\\t\\t $' + Menu['Menu'][x].Price); //test: item name and price\r\n\t\t\t\titemName = Menu['Menu'][x].Item, //get item name\r\n\t\t\t\titemPrice = Menu['Menu'][x].Price;//get item price\r\n\t\t\t\titemId\t= Menu['Menu'][x].id;//get item id\r\n\t\t\t\titemDescriped = Menu['Menu'][x].IsDescriped;//is item have a description\r\n\t\t\t\tdescriptionRslt\t= Menu['Menu'][x].Description;//what is the item description\r\n\t\t\t\titemCustom\t= Menu['Menu'][x].IsCustomItem;//does item have a custom item\r\n\t\t\t\tcustomItemAre = Menu['Menu'][x].CustomItem; //what are the options for this custom item\r\n\t\t\t\t//check if description is true, if so -> show description section\t\t\t\t\r\n\t\t\t\tif(itemDescriped == true)\r\n\t\t\t\t\tdescriptionSection = \"<label class='text-muted itemDescription'>- \"+descriptionRslt + \"</label>\";\r\n\t\t\t\telse\r\n\t\t\t\t\tdescriptionSection = \"\"; //keep empty\r\n\t\t\t\t//show custom info: IsCustomItem - add a custom button to be shown\r\n\t\t\t\tif(itemCustom == true ){\r\n\t\t\t\t\titemCustomButtons = '<div class=\"orderBtnSection\"><button type=\"button\" class=\"col-xs-3 btn btn-info\" data-toggle=\"collapse\" href=\"#collapseItem_'+\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\titemId+'\" role=\"button\" aria-expanded=\"false\" aria-controls=\"collapseItem_'+\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\titemId+'\">Custom</button><span class=\"col-xs-6\"></span>';\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t\titemCustomButtons = '<div class=\"orderBtnSection\"><span class=\"col-xs-3\"></span><span class=\"col-xs-6\"></span>';\r\n\t\t\t\t\r\n\t\t\t\t//show custom item title:\r\n\t\t\t\tcustomItemTitle = '<div class=\"col-xs-12 customItemOptions\">';\r\n\t\t\t\tcustomItemTitle += '<div class=\"col-xs-5\"> Item</div>';\r\n\t\t\t\tcustomItemTitle += '<div class=\"col-xs-2\"> Price</div>';\r\n\t\t\t\tcustomItemTitle += '<div class=\"col-xs-5\"> Select</div></div>'+clearHTMLDiv; \r\n\t\t\t\t//show item name, description, custom btn, add btn, custom item options as well\r\n\t\t\t\tcustomOrder = '<div class=\"col-xm-12 menuItemsSmall\"><span id= \"item_name_'+itemId+'\" class=\"itemName col-xs-10\">'+\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\titemName + \"</span><span class='itemPrice col-xs-2'>$\" + itemPrice;\r\n\t\t\t\tcustomOrder +='</span><div class=\"clearfix\"></div>'+ descriptionSection +' <div class=\"clearfix\"></div>' + itemCustomButtons;\r\n\t\t\t\tcustomOrder += '<button type=\"button\" class=\"col-xs-3 btn btn-primary\" onclick=\"addItemToCheckOut('+itemId+\", 'addYourOrderHere'\"+')\">'+\r\n\t\t\t\t\t\t\t\t\t\t\t\t\taddBtnGlyphicon+'</button><div class=\"clearfix\"></div>';\r\n\t\t\t\t//start a collapse div here\r\n\t\t\t\tcustomOrder += '<div class=\"collapse\" id=\"collapseItem_'+itemId+'\"><div class=\"addTitleToCustomItems\">'+\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcustomItemTitle+'<div class=\"gridSection mt-12\" id=\"showCustomItemsHere_'+itemId+\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'\"></div></div>'+\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'<button class=\"btn btn-primary\" onclick=\"addAllCurrentCustomItem(this,\\'showCustomAddedOrder_'+itemId+'\\',\\''+itemId+'\\',\\'addYourOrderHere\\')\">Add to Order</button></h3>'+\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'<button class=\"pull-right btn btn-danger addCustomOrderToCart\" onclick=\"removeAllCurrentCustomItem(\\'showCustomAddedOrder_'+itemId+'\\',\\''+itemId+'\\')\">Start Over</button></h3>'+clearHTMLDiv+\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'<div class=\"table-responsive tableCheckOrder\"><table class=\"table\"><tbody class=\"p2 showCustomAddedOrder_'+itemId+'\" id=\"showCustomAddedOrder_'+itemId+'\"></tbody></table></div>'+\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'</div></div>';\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//add in between the custom items and also show the custom items being added\r\n\t\t\t\tselectElement(\"addRelatedMenu\").innerHTML += customOrder;\r\n\t\t\t\t//get all dropdown list items on each dropdown:\r\n\t\t\t\t//get all extra custom items option: for(x in Menu['Menu'][3].CustomItem) console.log(Menu['Menu'][3].CustomItem[x].custItem);\r\n\t\t\t\tvar myCustomMenuId, addTo = '';\r\n\t\t\t\tfor(y in customItemAre){\r\n\t\t\t\t\taddTo = \"showCustomAddedOrder_\"+itemId;\r\n\t\t\t\t\tcountCustomDeleteOrAddAll = \"deleteOrAddOrderId-\"+counterCustomItemAdd;\r\n\t\t\t\t\tcustomItemDetails = '<div class=' + countCustomDeleteOrAddAll + ' id=\"addCustomItemTitle_'+ Menu[\"Menu\"][x].CustomItem[y].id + '\" > </div> <div class=\"col-xs-12 customItemOptions\">';\r\n\t\t\t\t\tcustomItemDetails += '<div class=\"col-xs-5 eachItemCustomName\">' + Menu['Menu'][x].CustomItem[y].custItem + ' </div>';\r\n\t\t\t\t\tcustomItemDetails += '<div class=\"col-xs-2\"> $' + Menu['Menu'][x].CustomItem[y].price + '</div>';\r\n\t\t\t\t\tcustomItemDetails += '<div class=\"col-xs-4 form-group\" role=\"group\" aria-label=\"select item\">';\t\r\n\t\t\t\t\tcustomItemDetails += '<button type=\"button\" class=\"addCustomSelectionBtn btn btn-warning col-xs-12\" onclick=\"addCustomItemToPreCheckOut('+Menu['Menu'][x].CustomItem[y].id+ ', \\''+ addTo+'\\')\">'+\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taddBtnGlyphicon + '</button></div>'+\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclearHTMLDiv;\r\n\t\t\t\t\tcustomItemDetails += '</div>';\r\n\t\t\t\t\tselectElement(\"showCustomItemsHere_\"+itemId).innerHTML += customItemDetails; //must be called after appending customOrder btn, so it can read it \"showCustomItemsHere_\"+itemId\r\n\t\t\t\t\tcounterCustomItemAdd += 142; //let second custom order class such as deleteOrderId-### or addOrderId-###\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}",
"function checkItemSelected(itemCd){\r\n\tvar flag = false;\r\n\t$(\".comboboxItemInputCd\").each(function(index){\r\n\t\tvar valueInputItemCd = $(this).val().replace(/[\\(\\)]/g, \"\");\r\n\t\tif (itemCd === valueInputItemCd){\r\n\t\t\tflag = true;\r\n\t\t\treturn;\r\n\t\t}\r\n\t});\r\n\treturn flag;\r\n}",
"getSelectedItemKeys()\n {\n return Object.keys(this._selectedItems);\n }",
"function derivePortionSelectionLists(preSelectedPortions) {\n\tgrainPortionSelectListHtml = '<select name=\"portionSelection\" class=\"Grain\"><optgroup label=\"Grain\">';\n\tproteinPortionSelectListHtml = '<select name=\"portionSelection\" class=\"Protein\"><optgroup label=\"Protein\">';\n\tvegetablesPortionSelectListHtml = '<select name=\"portionSelection\" class=\"Vegetables\"><optgroup label=\"Vegetables\">';\n\tfruitsPortionSelectListHtml = '<select name=\"portionSelection\" class=\"Fruits\"><optgroup label=\"Fruits\">';\n\tdairyPortionSelectListHtml = '<select name=\"portionSelection\" class=\"Dairy\"><optgroup label=\"Dairy\">';\n\t\n\t// tjs 120307\n\tvar len = portions.length;\n\t//alert(\"plateSlateCellApp getPortionSelections len \" + len);\n\tvar portionName;\n\tvar portionNames = new Array();\n\tvar keys = new Array();\n\tif (len > 0) {\n\t\t// tjs 120227\n\t\tfor (var i = 0; i < len; i++) {\n\t\t\t//if (i in portions) {\n\t\t\t\tvar currentPortion = portions[i];\n\t\t\t\tif (currentPortion != null) {\n\t\t\t\t\t//TODO if (currentPlate.master == 1)\n\t\t\t\t\t//alert(\"plateslate updatePortionsDialogs portion type \" + currentPortion.type + \" portion name \" + currentPortion.name);\n\t\t\t\t\tvar currentPortionId = currentPortion.id;\n\t\t\t\t\tvar isPreSelected = false;\n\t\t\t\t\tfor (var j = 0; j < preSelectedPortions.length; j++) {\n\t\t\t\t\t\tif (currentPortionId == preSelectedPortions[j]) {\n\t\t\t\t\t\t\tisPreSelected = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (isPreSelected == false) {\n\t\t\t\t\t\t\tportionName = currentPortion.name;\n\t\t\t\t\t\t\tportionNames[portionName] = i;\n\t\t\t\t\t\t\tkeys.push(portionName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t//}\n\t\t}\n\t}\n\n\tkeys.sort();\n\n//\tvar len = portions.length;\n\tif (len > 0) {\n\t\t//for (var i = 0; i < len; i++) {\n\t\tfor (var j = 0; j < keys.length; j++) {\n\t\t\tvar i = portionNames[keys[j]];\n\t\t\t//alert(\"plateslate populatePlateMenus i \" + i);\n\t\t\t//if (i in portions) {\n\t\t\t\tvar currentPortion = portions[i];\n\t\t\t\tif (currentPortion != null) {\n\t\t\t\t\tvar currentPortionId = currentPortion.id;\n\t\t\t\t\t//var isPreSelected = false;\n\t\t\t\t\t//for (var j = 0; j < preSelectedPortions.length; j++) {\n\t\t\t\t\t\t//if (currentPortionId == preSelectedPortions[j]) {\n\t\t\t\t\t\t//\tisPreSelected = true;\n\t\t\t\t\t\t//\tbreak;\n\t\t\t\t\t\t//}\n\t\t\t\t\t//}\n\t\t\t\t\t//if (isPreSelected == false) {\n\t\t\t\t\t//TODO if (currentPlate.master == 1)\n\t\t\t\t\t//alert(\"plateslate updatePortionsDialogs portion type \" + currentPortion.type + \" portion name \" + currentPortion.name);\n\t\t\t\t\t\tif (currentPortion.type == \"Grain\") {\n\t\t\t\t\t\t\tgrainPortionSelectListHtml += '<option value =\"' + currentPortion.id + '\">' + currentPortion.name + '</option>';\n\t\t\t\t\t\t} else if (currentPortion.type == \"Protein\") {\n\t\t\t\t\t\t\tproteinPortionSelectListHtml += '<option value =\"' + currentPortion.id +'\">' + currentPortion.name + '</option>';\n\t\t\t\t\t\t} else if (currentPortion.type == \"Vegetables\") {\n\t\t\t\t\t\t\tvegetablesPortionSelectListHtml += '<option value =\"' + currentPortion.id +'\">' + currentPortion.name + '</option>';\n\t\t\t\t\t\t} else if (currentPortion.type == \"Fruits\") {\n\t\t\t\t\t\t\tfruitsPortionSelectListHtml += '<option value =\"' + currentPortion.id +'\">' + currentPortion.name + '</option>';\n\t\t\t\t\t\t} else if (currentPortion.type == \"Dairy\") {\n\t\t\t\t\t\t\tdairyPortionSelectListHtml += '<option value =\"' + currentPortion.id +'\">' + currentPortion.name + '</option>';\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}\n\t\tgrainPortionSelectListHtml += '</optgroup>';\n\t\tproteinPortionSelectListHtml += '</optgroup>';\n\t\tvegetablesPortionSelectListHtml += '</optgroup>';\n\t\tfruitsPortionSelectListHtml += '</optgroup>';\n\t\tdairyPortionSelectListHtml += '</optgroup>';\n\t}\n\tgrainPortionSelectListHtml += '</select>';\n\tproteinPortionSelectListHtml += '</select>';\n\tvegetablesPortionSelectListHtml += '</select>';\n\tfruitsPortionSelectListHtml += '</select>';\n\tdairyPortionSelectListHtml += '</select>';\n\t//alert(\"plateslate derivePortionSelectionLists grainPortionSelectListHtml \" + grainPortionSelectListHtml);\n}",
"prepareSelectItems() {\n let that = this;\n let items_buffer = getReferencesOfType('AGItem');\n let select_item_buffer = '';\n if (items_buffer.length > 0) {\n items_buffer.forEach(function (element) {\n select_item_buffer = select_item_buffer + '<option value = \"' + getReferenceById(element).ID + '\">' + getReferenceById(element).name + '</option>';\n });\n }\n return select_item_buffer;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the new value in the patch if its actual value in the contact is different | function addInPatch(patch, contact, property, newValue) {
if (JSON.stringify(newValue) !== JSON.stringify(contact[property])) {
// adds the property:value in the patch
patch[property] = newValue;
// updates the contact property
contact[property] = newValue;
return true;
}
return false;
} | [
"function patchContact(contact) {\n var patch = { id: contact.id };\n if (rnd(-10)) {\n if (addInPatch(patch, contact, 'firstname', faker.name.firstName())) {\n addInPatch(patch, contact, 'homeemail', createEmailAddress(contact.firstname, contact.lastname));\n addInPatch(patch, contact, 'workemail', createEmailAddress(contact.firstname, contact.lastname, createDomainName(contact.company)));\n }\n }\n else if (rnd(-10)) {\n addInPatch(patch, contact, 'homeemail', rnd(-3) ? null : createEmailAddress(contact.firstname, contact.lastname));\n }\n\n if (rnd(-10)) {\n addInPatch(patch, contact, 'homephone', rnd(-3) ? null : faker.phone.phoneNumber());\n }\n\n if (rnd(-10)) {\n addInPatch(patch, contact, 'avatar', rnd(-3) ? null : faker.image.imageUrl());\n }\n\n if (rnd(-10)) {\n addInPatch(patch, contact, 'homeaddress', rnd(-3) ? null : createAddress());\n }\n // updates professional data\n if (rnd(-10)) {\n var companyName = rnd(-3) ? null : faker.company.companyName();\n addInPatch(patch, contact, 'company', companyName);\n // nullifies the professional data\n if (companyName === null) {\n addInPatch(patch, contact, 'workwebsite', null);\n addInPatch(patch, contact, 'workemail', null);\n addInPatch(patch, contact, 'workaddress', null);\n addInPatch(patch, contact, 'workphone', null);\n }\n // updates the otherwise\n else {\n // builds the domain name\n var domainname = createDomainName(contact.company);\n if (addInPatch(patch, contact, 'workwebsite', rnd(-3) ? null : 'www.' + domainname)) {\n addInPatch(patch, contact, 'workemail', rnd(-3) ? null : createEmailAddress(contact.firstname, contact.lastname, domainname));\n }\n if (rnd(-5)) {\n addInPatch(patch, contact, 'workaddress', rnd(-3) ? null : createAddress(contact.company));\n }\n if (rnd(-5)) {\n addInPatch(patch, contact, 'workphone', rnd(-3) ? null : faker.phone.phoneNumber());\n }\n if (rnd(-8)) {\n addInPatch(patch, contact, 'workaddress', rnd(-3) ? null : createAddress(contact.company));\n }\n }\n }\n\n return patch;\n }",
"function override( pointId, value, valueType, callee, success, failure) {\n\n var arg = {\n value: value,\n valueType: valueType\n },\n url = '/models/1/points/' + pointId + '/override'\n\n rest.post( url, arg, null, null,\n function( data) {\n success.call( callee, data)\n },\n function( ex, statusCode, headers, config){\n console.log( 'gbMeasurementValueRest ERROR overriding point with ID: ' + pointId + ' to value \"' + value + '\" with type: \"' + valueType + '\". Exception: ' + ex.exception + ' - ' + ex.message)\n failure.call( callee, pointId, ex, statusCode)\n }\n )\n\n return true\n }",
"changeContact(newContactId,domElement){\n let selectedContact = this.getContactById(Number(newContactId));\n this.currentChatPartner = selectedContact;\n super.notifyObservers(\"contactChanged\",{contact:selectedContact,elem:domElement,userId:this.personnelId});\n }",
"function handlerChangeContactVal(event, setVal) {\n setVal(event.target.value);\n}",
"updateFieldItem(core, field, event) {\n return new Promise((resolve) => {\n if (IsValidFieldPatchEvent(core, event)) {\n const patch = {};\n const path = StringReplaceAll(ParseUrlForParams(`#path/#entityId`, core.params), '//', '/');\n patch[field.name] = {\n field_entry_id: +event.data_key,\n field_id: +field.id,\n id: field.data[event.data_key].id ? field.data[event.data_key].id : null\n };\n patch[field.name][event.column] = event.config.control.value;\n this.srv.request.doPatch(path, patch, 1, false).subscribe((res) => {\n if (res.data)\n res = res.data;\n const value = res[field.name].record[event.column];\n field.data[event.data_key].id = res[field.name].record.id;\n field.data[event.data_key][event.column] = value;\n // if( IsObject(core.entity[ field.name ], true) ){\n // core.entity[ field.name ][ event.column ] = value;\n // }else if( IsArray(core.entity[ field.name ], true) ){\n // console.log('session the data', core.entity[ field.name ], value);\n // }\n return resolve(true);\n }, (err) => {\n const fieldPatch = event.config.patch;\n const control = event.config.control;\n fieldPatch.running = false;\n control.markAsDirty();\n control.setValue(this.asset.storedValue);\n control.setErrors({ server: true });\n event.config.message = GetHttpErrorMsg(err);\n return resolve(false);\n });\n }\n });\n }",
"set(target, property, value, receiver) {\n const updateWasSuccessful = trap.set(target, property, value, receiver);\n return updateWasSuccessful;\n }",
"function isDifferrent(existing, entry) {\n\tfor (var prop in entry) {\n\t\tif (existing.hasOwnProperty(prop)) {\n\t\t\t// comparing array of interests otherwise suggests new data present\n\t\t\tif ((typeof entry[prop] !== 'object' && existing[prop] !== entry[prop])\n\t\t\t\t|| (typeof entry[prop] == 'object' && !arraysEqual(existing[prop], entry[prop]))) {\n\n\t\t\t\t// ****ideally want this logged to a temp file\n\t\t\t\t// console.log(`updated ${prop}: ${entry.orgName.substr(0,20)}: ${existing[prop]} -> ${entry[prop]}`);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} else {\n\t\t\t// new data field supplied, also considered an update\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}",
"addContact(contact){\n this.contactList.push(contact);\n super.notifyObservers(\"addContact\",contact);\n }",
"update ( data ) {\n if ( !this.deepEqual(data, this.data) ) {\n Object.assign(this.data, data);\n this.notify();\n }\n }",
"function _generate(mirror, obj, patches, path) {\r\n if (obj === mirror) {\r\n return;\r\n }\r\n if (typeof obj.toJSON === \"function\") {\r\n obj = obj.toJSON();\r\n }\r\n var newKeys = helpers_1._objectKeys(obj);\r\n var oldKeys = helpers_1._objectKeys(mirror);\r\n var changed = false;\r\n var deleted = false;\r\n //if ever \"move\" operation is implemented here, make sure this test runs OK: \"should not generate the same patch twice (move)\"\r\n for (var t = oldKeys.length - 1; t >= 0; t--) {\r\n var key = oldKeys[t];\r\n var oldVal = mirror[key];\r\n if (helpers_1.hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) {\r\n var newVal = obj[key];\r\n if (typeof oldVal == \"object\" && oldVal != null && typeof newVal == \"object\" && newVal != null) {\r\n _generate(oldVal, newVal, patches, path + \"/\" + helpers_1.escapePathComponent(key));\r\n }\r\n else {\r\n if (oldVal !== newVal) {\r\n changed = true;\r\n patches.push({ op: \"replace\", path: path + \"/\" + helpers_1.escapePathComponent(key), value: helpers_1._deepClone(newVal) });\r\n }\r\n }\r\n }\r\n else if (Array.isArray(mirror) === Array.isArray(obj)) {\r\n patches.push({ op: \"remove\", path: path + \"/\" + helpers_1.escapePathComponent(key) });\r\n deleted = true; // property has been deleted\r\n }\r\n else {\r\n patches.push({ op: \"replace\", path: path, value: obj });\r\n changed = true;\r\n }\r\n }\r\n if (!deleted && newKeys.length == oldKeys.length) {\r\n return;\r\n }\r\n for (var t = 0; t < newKeys.length; t++) {\r\n var key = newKeys[t];\r\n if (!helpers_1.hasOwnProperty(mirror, key) && obj[key] !== undefined) {\r\n patches.push({ op: \"add\", path: path + \"/\" + helpers_1.escapePathComponent(key), value: helpers_1._deepClone(obj[key]) });\r\n }\r\n }\r\n}",
"onValueUpdate(fieldKey, viewValue, modelValue, validationResult) {\n //the field calls this function with its key and the updated value\n //if the fieldGroup have separated model it updates it and send it to the parent model to be updated\n //while if the field group had no separate model it updates send the field key and the new value to its parent to handle updating the model\n\n if (this.props.config.key) {\n this.props.viewValues[fieldKey] = viewValue;\n this.props.fieldsValidation[fieldKey] = validationResult;\n\n if (modelValue === undefined)\n delete this.props.model[fieldKey];\n else\n this.props.model[fieldKey] = modelValue;\n\n this.props.onValueUpdate(this.props.config.key, this.props.viewValues, this.props.model, this.props.fieldsValidation);\n }\n else\n this.props.onValueUpdate(fieldKey, viewValue, modelValue,validationResult);\n\n\n\n }",
"parametersChanged() {\n let arr = Object.entries(this.parameters)\n let res = arr.map(item=>{\n return this.prevParameters[item[0]] == item[1]\n }).find(item=>!item)\n\n this.prevParameters = {...this.parameters}\n return !res\n }",
"function handleUpdateContact() {\n updateContact(editContact);\n }",
"write(patch) {\n if (this[completed]) {\n throw new Error('This response has already completed.');\n }\n\n if (Array.isArray(patch)) {\n this[send]({patch});\n } else {\n this[send]({patch: [patch]});\n }\n }",
"function utilPatch(orig, diff) /* patched object */ {\n\t\tconst\n\t\t\tkeys = Object.keys(diff || {}),\n\t\t\tpatched = clone(orig);\n\n\t\tfor (let i = 0, klen = keys.length; i < klen; ++i) {\n\t\t\tconst\n\t\t\t\tkey = keys[i],\n\t\t\t\tdiffP = diff[key];\n\n\t\t\tif (diffP === DiffOp.Delete) {\n\t\t\t\tdelete patched[key];\n\t\t\t}\n\t\t\telse if (Array.isArray(diffP)) {\n\t\t\t\tswitch (diffP[0]) {\n\t\t\t\tcase DiffOp.SpliceArray:\n\t\t\t\t\tpatched.splice(diffP[1], 1 + (diffP[2] - diffP[1]));\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase DiffOp.Copy:\n\t\t\t\t\tpatched[key] = clone(diffP[1]);\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase DiffOp.CopyDate:\n\t\t\t\t\tpatched[key] = new Date(diffP[1]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpatched[key] = Util.patch(patched[key], diffP);\n\t\t\t}\n\t\t}\n\n\t\treturn patched;\n\t}",
"set useContactForce(value) {}",
"function test_saving_contact() {\n let done = false;\n let contact = new Contact(kTestFields);\n contact.dba = {\n handleSync: function(aMethod, aModel, aOptions) {\n aModel.id = 1; // Simulating we inserted a contact at row 1.\n assert_equals(aMethod, \"create\");\n assert_serializations_equal(aModel, kResultingFields);\n done = true;\n }\n };\n\n contact.save();\n mc.waitFor(function() done);\n\n done = false;\n // Ok, now let's try updating that contact.\n const kUpdatedName = [\"Something else\"];\n let updatedFields = _.extend({}, kResultingFields);\n updatedFields.name = kUpdatedName;\n\n contact.dba = {\n handleSync: function(aMethod, aModel, aOptions) {\n assert_equals(aMethod, \"update\");\n assert_serializations_equal(aModel, updatedFields);\n done = true;\n }\n };\n\n contact.save({name: kUpdatedName});\n mc.waitFor(function() done);\n}",
"_getPatchBody(value) {\n let body = {};\n const patch = this.config.patch;\n value = typeof value !== 'undefined' ? value : this.config.control.value;\n if (IsObject(value)) {\n const val = value;\n body = Object.assign(Object.assign({}, body), val);\n }\n else if (IsArray(value)) {\n body[this.config.patch.field] = value;\n }\n else {\n body[this.config.patch.field] = value;\n if (this.config.empty && !body[this.config.patch.field]) {\n body[this.config.patch.field] = PopTransform(String(value), this.config.empty);\n }\n }\n if (this.config.patch.json)\n body[this.config.patch.field] = JSON.stringify(body[this.config.patch.field]);\n if (patch && patch.metadata) {\n for (const i in patch.metadata) {\n if (!patch.metadata.hasOwnProperty(i))\n continue;\n body[i] = patch.metadata[i];\n }\n }\n return body;\n }",
"attemptNewValue(newValue) {\n const upperbound = this.props.upperBound || 25;\n const lowerbound = this.props.lowerBound || 0;\n if (newValue <= upperbound && newValue >= lowerbound) {\n this.props.setValue(newValue);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the value at location index in the TensorArray. | read(index) {
if (this.closed_) {
throw new Error(`TensorArray ${this.name} has already been closed.`);
}
if (index < 0 || index >= this.size()) {
throw new Error(`Tried to read from index ${index}, but array size is: ${this.size()}`);
}
const tensorWithState = this.tensors[index];
if (tensorWithState.cleared) {
throw new Error(`TensorArray ${this.name}: Could not read index ${index} twice because it was cleared after a previous read ` +
`(perhaps try setting clear_after_read = false?).`);
}
if (this.clearAfterRead) {
tensorWithState.cleared = true;
}
tensorWithState.read = true;
return tensorWithState.tensor;
} | [
"getAt(idx) {\n try {\n if (idx >= this.length || idx < 0) throw new Error('Index is invalid!');\n return this._getNode(idx).val;\n } catch (e) {\n console.warn(e);\n }\n }",
"function getValueAtIndex(chart, index) {\n return chart.data()[0].values[index].value;\n }",
"readDataByIndex(index) {\n return this.content[index];\n }",
"get(index){\n // return the value of an element at given index\n return memory.get(index);\n }",
"get(index) {\n let foundNode = this._find(index);\n return foundNode ? foundNode.value : undefined;\n }",
"get(index) {\n return this._taskArr[index];\n }",
"getVariable (index, isGlobal) {\n if (isGlobal) {\n return this.op(\"get_global\").varuint(index, \"global_index\");\n } else {\n return this.op(\"get_local\").varuint(index, \"local_index\");\n }\n }",
"function GetInputValue(inputV , row , col) {\r\n mat [row] [col] = parseInt(inputV); \r\n}",
"offsetOf(variable, index) {\n const slot = this.getLocalDepth(variable);\n const depth = this.getMemoryOffset(slot);\n const size = this.sizeOfVal(variable);\n\n if (this.stackTop().size != 1) {\n this.error(\n \"Cannot assign value larger than 1 byte to bus or string index.\"\n );\n } else if (size != 1) {\n this.error(\"cannot index a variable that is not a bus or string.\");\n }\n\n return depth + index + 2; // account for 2 bytes of padding prior.\n }",
"function get_value(loc, mode, intcode) {\r\n if (mode == 0) {\r\n // position mode\r\n return intcode[loc];\r\n } else if (mode == 1) {\r\n // immediate mode\r\n return loc;\r\n }\r\n}",
"testStoredValueForIndex( accTypeEnumIndex )\n {\n if ( accTypeEnumIndex < 0 || accTypeEnumIndex > CMD4_ACC_TYPE_ENUM.EOL )\n return undefined;\n\n return this.storedValuesPerCharacteristic[ accTypeEnumIndex ];\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}",
"getLocalPlayMatrixValue(row, col){\n return this.state.playMatrix[row][col];\n }",
"_getDataIndex(coord) {\n if (coord.x < 0 || coord.x > this.getWidth() - 1 ||\n coord.y < 0 || coord.y > this.getHeight() - 1) {\n return null;\n }\n // Image data is stored as a one-dimensional array of colors in rgba order\n // with integer values between 0 and 255 (included).\n // Index 0 (x = 0, y = 0) is at the top left corner of the image.\n return ((this.getWidth() * coord.y) + coord.x) * 4;\n }",
"getVariable(index) {\n const depth = this.getLocalDepth(index); // depth of the local in the stack.\n const memoryOffset = this.getMemoryOffset(depth); // actual depth in BF memory.\n const size = this.sizeOfVal(index); // how many byes to copy.\n const type = this.typeOfVal(index);\n\n for (let i = 0; i < size; i++) {\n this.copyByte(memoryOffset, true);\n }\n\n this.stack.push(StackEntry(type, size));\n }",
"function at(v, index) /* forall<a> (v : vector<a>, index : int) -> maybe<a> */ {\n var idx = $std_core._int_to_int32(index);\n var _x2 = (((idx < 0)) || (((((v).length)) <= idx)));\n if (_x2) {\n return Nothing;\n }\n else {\n return Just((v)[idx]);\n }\n}",
"function YDataStream_get_data(row, col)\n {\n if(this._values.length == 0) this.loadStream();\n if(row >= this._values.length) return Y_DATA_INVALID;\n if(col >= this._values[row].length) return Y_DATA_INVALID;\n return this._values[row][col];\n }",
"get(r, c) {\n if (r < 0 || r >= this.numRows || c < 0 || c >= this.numCols)\n throw new RangeError(\"Index out of bounds\");\n return this.cells[r][c];\n }",
"function row(matrix, i) {\n return matrix[i]\n}",
"getValue(address) {\n let value = this.store.read(address);\n\n if (this.store.references[address] <= 0) throw new Error();\n // If the value is undefined, return an Undefined object\n if (value == undefined) {\n value = Evaluator.create(this, Types.Undefined);\n value.address = address;\n this.store.locations[address] = value;\n // this.store.write(address, value);\n }\n\n return value;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
loads JSON file and reinstantiates CARender based upon it | static LoadCARender(json, callback)
{
// stops attempting to load file if there is no file
if (json === undefined)
{
return;
}
json.text(); // begins asynchronous call to load json
json.text().then( (text) =>
{
var obj = JSONConverter.JSONToJS(text);
callback(obj);
// console.log(Date.now(), obj)
// return obj;
// JSONConverter.LoadCARenderFromObj(render, obj)
})
} | [
"function LoadJson(){}",
"function init() {\n loadJSON(function(response) {\n let actual_JSON = JSON.parse(response);\n triggered(actual_JSON);\n });\n}",
"function initialize () {\n\n request(\"slideshow.json\", parseData);\n\n}",
"static loadJson(pathToJson) {\n\t\tconsole.log(\"Loading story.json...\");\n\t\tvar r = new XMLHttpRequest();\n\t\tr.open(\"GET\", pathToJson, true);\n\t\tr.onload = function() {\n\t\t\tif (this.status >= 200 && this.status < 400)\n\t\t\t{\n\t\t\t\t// Set the active story to the loaded JSON\n\t\t\t\tstoryData.story = JSON.parse(this.responseText);\n\t\t\t\tStoryPlayer.initStory();\n\t\t\t}\n\t\t};\n\t\tr.send();\n\t\tconsole.log(\"story.js loaded!\");\n\t}",
"function loadJSON() {\n var client = new XMLHttpRequest();\n client.open(\"GET\", databasefilename, true);\n client.onreadystatechange = function () { //callback\n if (client.readyState === 4) {\n if (client.status === 200 || client.status === 0) {\n database_obj = JSON.parse(client.responseText);\n processInput();\n }\n }\n };\n client.send();\n }",
"loadFromJSON (digimonObject) {\n\t\t//let digimonObject = JSON.parse(digimonJSON);\n\n\t\tfor (let property in digimonObject) {\n\t\t\tthis[property] = digimonObject[property];\n\t\t}\n\t\t\n\t\tDigimonData.extraMovementDiscount(this.qualityFlags['movementDiscount'], this.stageIndex >= ChampionIndex);\n\n\t\t/*if (Number.isInteger(digimonObject.burstIndex)) {\n\t\t\tthis.burstIndex = 0;\n\t\t\tfor (let i = 0; i < digimonObject.burstIndex; i++) {\n\t\t\t\tthis.modifyBurstIndex(true);\n\t\t\t}\n\t\t}*/\n\t}",
"load(statsFile = Statistics.defaultLocation) {\n if (!fs.existsSync(path.dirname(statsFile))) {\n fs.mkdirSync(path.dirname(statsFile), { recursive: true });\n }\n if (!fs.existsSync(statsFile)) {\n if (fs.existsSync(\"./data/stats.json\")) {\n fs.renameSync(\"./data/stats.json\", statsFile);\n }\n else {\n console.error(\"No existing file! Creating file\");\n this.save();\n return;\n }\n }\n let object = JSON.parse(fs.readFileSync(statsFile, \"utf-8\"));\n for (const key in this) {\n if (this.hasOwnProperty(key) && object.hasOwnProperty(key)) {\n this[key] = object[key];\n }\n }\n }",
"load() {\n\n this.cars = []\n //readFile(this.fileName).then(function(data){console.log(data)}) //2.We are reading the file because we are using promisify\n readFile(this.fileName, 'utf8')\n //.then(data => console.log(typeof data))\n .then(data => JSON.parse(data)) //3.JSON.parse is converting text into jSON data and push/add the content to the list of cars\n .then(carsList => { //4. then we are looping the array of objects and add each object into the list of cars.\n //console.log('before', this.cars)\n carsList.forEach(car => {\n // this.cars.push(car)\n this.add(new Car(car))\n })\n //console.log('after', this.cars)\n })\n\n }",
"async load() {\n await this.ensureExists();\n this.conf = await fs.readJSON(this.location);\n }",
"loadAnimations(json){\n\n // go through the json\n Object.keys(json).forEach( function(objectKey) {\n let animGroup = {};\n\n Object.keys(json[objectKey]).forEach(function (typeKey) {\n\n let animation = json[objectKey][typeKey];\n let animLookup = new AnimationLookup(typeKey, objectKey);\n animGroup[typeKey] = animLookup.lookup;\n if (animation.frames.frame || animation.frames.frame === 0) {\n\n // yes - load the animation from the json data\n this.anims.create({\n key: animLookup.lookup,\n frames: [animation.frames],\n frameRate: animation.frameRate,\n });\n\n } else {\n\n // multi frame animation - create\n let anim =this.anims.create({\n key: animLookup.lookup,\n frames: this.anims.generateFrameNumbers(animation.frames.key, animation.frames),\n frameRate: animation.frameRate,\n repeat: animation.repeat\n });\n }\n }, this);\n\n animations[objectKey] = animGroup;\n }, this)\n }",
"function loadJSON(file) {\n return JSON.parse(FS.readFileSync(file, \"utf8\"));\n}",
"load(){\n const file_name = \"hashdumpyard.json\"\n const fs = require('fs')\n const dumped = fs.readFileSync(file_name)\n this.primary_table = JSON.parse(dumped).primary_table\n this.slot_size = this.primary_table.length\n this.processed = true\n }",
"function init() {\n var test = AppConfig.testPaper;\n DataManager.loadJSON('/test_assets/' + test + '/' + test + '.json')\n .done(function(){\n\n // load assets\n DataManager.setAssetIndexes({ assetIndex: 0, fileIndex: 0 });\n loadAssets('core');\n })\n .fail(function(){\n\n // stop everything and notify user\n var message = {\n header: \"Initialisation Failure\",\n body: \"<div style='width:400px;'>Unable to initialise \" + test + \".json</div>\",\n footer: \"<button class='close'>OK</button>\",\n modal: true\n }\n Modal.showModal(message);\n });\n }",
"function loadAsset(url, type, callback) \r\n{\r\n\t//Using the fretch Api to geyt the data fro the json file uploaded ont he web server.\r\n\t//fetching the url and then setting the reponse function to response.json and then creating a PEoducts function that will reteive the data from the json file.\r\n\tfetch(url)\r\n\t.then(function (response)\r\n\t{\r\n\t\t response.json()\r\n\t\t.then(function(cats)\r\n\t\t {\r\n\t\t\tcallback(cats);\r\n\t\t});\r\n\t });\r\n}",
"async loadFromJSON(JSONs) {\n if(JSONs) {\n let JSONObj = JSONs.JSONItems\n for (let i = 0; i < JSONObj.length; i++) {\n let product = new Product(JSONObj[i].id, JSONObj[i].name, JSONObj[i].price, JSONObj[i].image);\n for (let j = 0; j < JSONObj[i].count; j++) {\n await this.addItem(product);\n }\n }\n }\n }",
"function loadJSON() {\n return {\n resolve: {\n extensions: [\".json\"],\n },\n };\n}",
"function loadJSON(url, callback) {\n // return immediately if data is in cache\n if (JayWalker.data[url]) {\n callback(JayWalker.data[url]);\n return;\n }\n // choose load method depending on protocol\n switch (window.location.protocol) {\n // loading over http/https\n case 'http:':\n case 'https:':\n var XHR_1 = new XMLHttpRequest();\n // override MIME in case server is misconfigured.\n XHR_1.overrideMimeType('application/json');\n XHR_1.open('GET', url, true);\n // Note: add after open to save cycles\n XHR_1.onreadystatechange = function () {\n if (XHR_1.readyState === 4 && XHR_1.status === 200) {\n JayWalker.data[url] = JSON.parse(XHR_1.responseText);\n callback(JayWalker.data[url]);\n }\n };\n XHR_1.send();\n break;\n // loading from local file system\n case 'file:':\n // inserts compiled JSON as script\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.onload = function () {\n callback(JayWalker.data[url]);\n };\n script.src = url.substring(0, url.length - 2);\n document.head.appendChild(script);\n break;\n // throw error if protocol unknown; I'm sorry future\n default:\n throw new Error('Unknown protocol');\n }\n }",
"load() {\n rp({\n uri: this.path,\n json: true\n }).then((data) => {\n assert(typeof data === 'object');\n\n this.keys = data;\n this.emit('update');\n }).catch((err) => {\n this.emit('error', err);\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}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Map the given display option to a numeric point value. | mapDisplayToPoints(displayOption) {
switch (displayOption[0]) {
case 'one-third': return 1;
case 'two-thirds': return 2;
case 'full': return 3;
default: return 0;
}
} | [
"function updateDisplay(value) {\n string = value.toString();\n if (string.length > 11) {\n displayValue = value.toPrecision(11);\n }\n document.getElementById(\"output\").innerHTML = displayValue;\n return;\n}",
"getDisplayValue() {}",
"function csys_display(value)\n{\n //value can be: yes or no //\n env_stat=document.wm.pwlConfigoptSet('display_coordinate_sys', value);\n}",
"function displayHoverValue( td ) {\n\n\t\t\tvar type\t\t= td.data( 'resistanceType' )\n\t\t\t\t, value\t\t= td.data( 'resistanceValue' );\n\n\t\t\t//console.error( '%o - %o', type, value );\n\n\t\t\t// Type is (class)ResistanceDefault: Don't display numbers\n\t\t\tif( type === 'classResistanceDefault' || type === 'resistanceDefault' || type === 'undefined' ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ttd\n\t\t\t\t// Store original text (for mouseleave)\n\t\t\t\t.data( 'originalText', td.text() )\n\t\t\t\t.text( value );\n\n\t\t}",
"function set_display(value)\n{\n\t//value can be: wireframe, hiddenvis, hiddeninvis, or shade //\n\tenv_stat=document.wm.pwlConfigoptSet('display', value);\n}",
"setLabelPrecision(event) {\n // Updates the precision of the lat-lng display label\n // based on the available screen width\n const width = event.posX;\n let latlngLabelPrecision;\n\n if (width < 600) {\n latlngLabelPrecision = 2;\n } else if (width < 800) {\n latlngLabelPrecision = 3;\n } else {\n latlngLabelPrecision = 4;\n }\n\n this.setState({\n latlngLabelPrecision,\n });\n }",
"handleNumberOutput() {\n this._value = this.handlePrecision(this._value);\n this.updateValue();\n }",
"function displayDigit(event) {\r\n let buttonValue = event.target.dataset.value;\r\n display.textContent += buttonValue;\r\n}",
"function displayNumericRgb() {\r\n $.each(_color.toRgb(), function(part, num) {\r\n $(\"#s-c-p-txt-\" + _id + \"-rgb-\" + part, _dom.el).val(num);\r\n });\r\n }",
"function withUnits(n) { return formatUserData(n, numberStyle); }",
"constructor(born, survive, display, options){\n this.born = born.map(Number);\n this.survive = survive.map(Number);\n this.display = {\n deadNumeric: display[0] || 0,\n liveNumeric: display[1] || 1,\n deadString: display[2] || \" \",\n liveString: display[3] || \"#\",\n };\n }",
"function pressPlusMinus() {\n\tif (displayVal !== \"0\") {\n\t\tif (displayVal.charAt(0) === \"-\") {\t\n\t\t\tdisplayVal = displayVal.slice(1);\n\t\t}\n\t\telse {\n\t\t\tdisplayVal = \"-\" + displayVal;\n\t\t}\n\t\toutput(displayVal);\t\n\t}\n}",
"function showPoints(id,type){\n var taxa = document.getElementById('hiddenTaxa').value;\n\n //Show loading\n showWaitingDialog();\n //Indicate de current selected\n indicateCurrent('t'+id,'map');\n //Show map\n map.render('map');\n //Drowing the points\n showSpecimenPoints(\"\",taxa,\"\");\n}",
"function CMA_AnimDisplayValue(noMesh, nbDigit) \r\n\t{\r\n\t\tthis.mNoMesh = noMesh;\r\n\t\tthis.mNbDigit = nbDigit;\r\n\t}",
"function printPoint(p) {\n return p[0].toFixed(1) + \" \" + p[1].toFixed(1);\n }",
"function handleNumKey(digit) {\r\n\r\n var sO = CurStepObj;\r\n\r\n // Do not accept the decimal point into an index expression\r\n //\r\n if ((sO.focusBoxId == CodeBoxId.Index) && (digit == '.')) {\r\n showTip(TipId.NoPeriod);\r\n return;\r\n }\r\n\r\n // If the number expression is empty, then create a new ExprObj\r\n // to record the number AND record that expression in the \r\n // activeExpr (whatever code box/index edit/... is active)\r\n // If the number expression is NOT empty (i.e., subsequent numbers)\r\n // then updte the number expression's string.\r\n //\r\n if (!sO.numberExpr) {\r\n\r\n sO.numberExpr = new ExprObj(true, ExprType.Number, digit.toString());\r\n replaceOrAppendExpr(sO.numberExpr);\r\n\r\n } else {\r\n\r\n sO.numberExpr.str = sO.numberExpr.str + \"\" + digit.toString();\r\n }\r\n\r\n // if we inserted '.' into a function call arg (which is a number),\r\n // change its type\r\n // \r\n if (sO.activeParentExpr.isUserFuncCall()) {\r\n var pos = sO.activeChildPos - 1;\r\n updateFuncArgType(sO.activeParentExpr, pos, sO.numberExpr.str);\r\n }\r\n\r\n redrawAfterKey();\r\n}",
"function unitConverter() {\n\n var unit = document.getElementById(\"basic-addon2\").value;\n var num = document.getElementById(\"inputDistance\").value;\n\n if (unit === 'miles') {\n carbonConverter(num)}\n if (unit === 'km'){\n var newNum = num * 0.621371;\n carbonConverter(newNum)\n }\n}",
"function getUserZoomUI() {\n return parseInt($(\"#mapZoom\").prop('value'));\n }",
"function displayNumericHsv() {\r\n $.each(_color.toHsv(), function(part, num) {\r\n $(\"#s-c-p-txt-\" + _id + \"-hsv-\" + (part === \"v\" ? \"b\" : part), _dom.el).val(Math.round(num));\r\n });\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the given properties match those of a `CfnVirtualServiceProps` | function CfnVirtualServicePropsValidator(properties) {
if (!cdk.canInspect(properties)) {
return cdk.VALIDATION_SUCCESS;
}
const errors = new cdk.ValidationResults();
if (typeof properties !== 'object') {
errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));
}
errors.collect(cdk.propertyValidator('meshName', cdk.requiredValidator)(properties.meshName));
errors.collect(cdk.propertyValidator('meshName', cdk.validateString)(properties.meshName));
errors.collect(cdk.propertyValidator('meshOwner', cdk.validateString)(properties.meshOwner));
errors.collect(cdk.propertyValidator('spec', cdk.requiredValidator)(properties.spec));
errors.collect(cdk.propertyValidator('spec', CfnVirtualService_VirtualServiceSpecPropertyValidator)(properties.spec));
errors.collect(cdk.propertyValidator('tags', cdk.listValidator(cdk.validateCfnTag))(properties.tags));
errors.collect(cdk.propertyValidator('virtualServiceName', cdk.requiredValidator)(properties.virtualServiceName));
errors.collect(cdk.propertyValidator('virtualServiceName', cdk.validateString)(properties.virtualServiceName));
return errors.wrap('supplied properties not correct for "CfnVirtualServiceProps"');
} | [
"function CfnVirtualGatewayPropsValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('meshName', cdk.requiredValidator)(properties.meshName));\n errors.collect(cdk.propertyValidator('meshName', cdk.validateString)(properties.meshName));\n errors.collect(cdk.propertyValidator('meshOwner', cdk.validateString)(properties.meshOwner));\n errors.collect(cdk.propertyValidator('spec', cdk.requiredValidator)(properties.spec));\n errors.collect(cdk.propertyValidator('spec', CfnVirtualGateway_VirtualGatewaySpecPropertyValidator)(properties.spec));\n errors.collect(cdk.propertyValidator('tags', cdk.listValidator(cdk.validateCfnTag))(properties.tags));\n errors.collect(cdk.propertyValidator('virtualGatewayName', cdk.validateString)(properties.virtualGatewayName));\n return errors.wrap('supplied properties not correct for \"CfnVirtualGatewayProps\"');\n}",
"function CfnGatewayRoute_GatewayRouteVirtualServicePropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('virtualServiceName', cdk.requiredValidator)(properties.virtualServiceName));\n errors.collect(cdk.propertyValidator('virtualServiceName', cdk.validateString)(properties.virtualServiceName));\n return errors.wrap('supplied properties not correct for \"GatewayRouteVirtualServiceProperty\"');\n}",
"function CfnVirtualService_VirtualServiceProviderPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('virtualNode', CfnVirtualService_VirtualNodeServiceProviderPropertyValidator)(properties.virtualNode));\n errors.collect(cdk.propertyValidator('virtualRouter', CfnVirtualService_VirtualRouterServiceProviderPropertyValidator)(properties.virtualRouter));\n return errors.wrap('supplied properties not correct for \"VirtualServiceProviderProperty\"');\n}",
"function CfnVirtualService_VirtualServiceSpecPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('provider', CfnVirtualService_VirtualServiceProviderPropertyValidator)(properties.provider));\n return errors.wrap('supplied properties not correct for \"VirtualServiceSpecProperty\"');\n}",
"function CfnVirtualNodePropsValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('meshName', cdk.requiredValidator)(properties.meshName));\n errors.collect(cdk.propertyValidator('meshName', cdk.validateString)(properties.meshName));\n errors.collect(cdk.propertyValidator('meshOwner', cdk.validateString)(properties.meshOwner));\n errors.collect(cdk.propertyValidator('spec', cdk.requiredValidator)(properties.spec));\n errors.collect(cdk.propertyValidator('spec', CfnVirtualNode_VirtualNodeSpecPropertyValidator)(properties.spec));\n errors.collect(cdk.propertyValidator('tags', cdk.listValidator(cdk.validateCfnTag))(properties.tags));\n errors.collect(cdk.propertyValidator('virtualNodeName', cdk.validateString)(properties.virtualNodeName));\n return errors.wrap('supplied properties not correct for \"CfnVirtualNodeProps\"');\n}",
"function CfnVirtualNode_VirtualServiceBackendPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('clientPolicy', CfnVirtualNode_ClientPolicyPropertyValidator)(properties.clientPolicy));\n errors.collect(cdk.propertyValidator('virtualServiceName', cdk.requiredValidator)(properties.virtualServiceName));\n errors.collect(cdk.propertyValidator('virtualServiceName', cdk.validateString)(properties.virtualServiceName));\n return errors.wrap('supplied properties not correct for \"VirtualServiceBackendProperty\"');\n}",
"function CfnVirtualService_VirtualRouterServiceProviderPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('virtualRouterName', cdk.requiredValidator)(properties.virtualRouterName));\n errors.collect(cdk.propertyValidator('virtualRouterName', cdk.validateString)(properties.virtualRouterName));\n return errors.wrap('supplied properties not correct for \"VirtualRouterServiceProviderProperty\"');\n}",
"function CfnVirtualService_VirtualNodeServiceProviderPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('virtualNodeName', cdk.requiredValidator)(properties.virtualNodeName));\n errors.collect(cdk.propertyValidator('virtualNodeName', cdk.validateString)(properties.virtualNodeName));\n return errors.wrap('supplied properties not correct for \"VirtualNodeServiceProviderProperty\"');\n}",
"function CfnRoute_GrpcRouteMetadataMatchMethodPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnRoute_MatchRangePropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GrpcRouteMetadataMatchMethodProperty\"');\n}",
"function CfnRoute_GrpcRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('metadata', cdk.listValidator(CfnRoute_GrpcRouteMetadataPropertyValidator))(properties.metadata));\n errors.collect(cdk.propertyValidator('methodName', cdk.validateString)(properties.methodName));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));\n return errors.wrap('supplied properties not correct for \"GrpcRouteMatchProperty\"');\n}",
"function CfnGatewayRoute_GatewayRouteMetadataMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnGatewayRoute_GatewayRouteRangeMatchPropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GatewayRouteMetadataMatchProperty\"');\n}",
"function CfnVirtualGateway_VirtualGatewaySpecPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('backendDefaults', CfnVirtualGateway_VirtualGatewayBackendDefaultsPropertyValidator)(properties.backendDefaults));\n errors.collect(cdk.propertyValidator('listeners', cdk.requiredValidator)(properties.listeners));\n errors.collect(cdk.propertyValidator('listeners', cdk.listValidator(CfnVirtualGateway_VirtualGatewayListenerPropertyValidator))(properties.listeners));\n errors.collect(cdk.propertyValidator('logging', CfnVirtualGateway_VirtualGatewayLoggingPropertyValidator)(properties.logging));\n return errors.wrap('supplied properties not correct for \"VirtualGatewaySpecProperty\"');\n}",
"function CfnGatewayRoute_GrpcGatewayRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('hostname', CfnGatewayRoute_GatewayRouteHostnameMatchPropertyValidator)(properties.hostname));\n errors.collect(cdk.propertyValidator('metadata', cdk.listValidator(CfnGatewayRoute_GrpcGatewayRouteMetadataPropertyValidator))(properties.metadata));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));\n return errors.wrap('supplied properties not correct for \"GrpcGatewayRouteMatchProperty\"');\n}",
"function hasProperties(json, properties) {\n return properties.every(property => {\n return json.hasOwnProperty(property);\n });\n}",
"function CfnVirtualNode_VirtualNodeSpecPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('backendDefaults', CfnVirtualNode_BackendDefaultsPropertyValidator)(properties.backendDefaults));\n errors.collect(cdk.propertyValidator('backends', cdk.listValidator(CfnVirtualNode_BackendPropertyValidator))(properties.backends));\n errors.collect(cdk.propertyValidator('listeners', cdk.listValidator(CfnVirtualNode_ListenerPropertyValidator))(properties.listeners));\n errors.collect(cdk.propertyValidator('logging', CfnVirtualNode_LoggingPropertyValidator)(properties.logging));\n errors.collect(cdk.propertyValidator('serviceDiscovery', CfnVirtualNode_ServiceDiscoveryPropertyValidator)(properties.serviceDiscovery));\n return errors.wrap('supplied properties not correct for \"VirtualNodeSpecProperty\"');\n}",
"function CfnMultiRegionAccessPointPolicyPropsValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('mrapName', cdk.requiredValidator)(properties.mrapName));\n errors.collect(cdk.propertyValidator('mrapName', cdk.validateString)(properties.mrapName));\n errors.collect(cdk.propertyValidator('policy', cdk.requiredValidator)(properties.policy));\n errors.collect(cdk.propertyValidator('policy', cdk.validateObject)(properties.policy));\n return errors.wrap('supplied properties not correct for \"CfnMultiRegionAccessPointPolicyProps\"');\n}",
"function CfnVirtualNode_AwsCloudMapServiceDiscoveryPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('attributes', cdk.listValidator(CfnVirtualNode_AwsCloudMapInstanceAttributePropertyValidator))(properties.attributes));\n errors.collect(cdk.propertyValidator('ipPreference', cdk.validateString)(properties.ipPreference));\n errors.collect(cdk.propertyValidator('namespaceName', cdk.requiredValidator)(properties.namespaceName));\n errors.collect(cdk.propertyValidator('namespaceName', cdk.validateString)(properties.namespaceName));\n errors.collect(cdk.propertyValidator('serviceName', cdk.requiredValidator)(properties.serviceName));\n errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));\n return errors.wrap('supplied properties not correct for \"AwsCloudMapServiceDiscoveryProperty\"');\n}",
"matches(text, props) {\n for (var key in props) {\n if (key === 'text') {\n continue;\n }\n\n if (!text.hasOwnProperty(key) || text[key] !== props[key]) {\n return false;\n }\n }\n\n return true;\n }",
"function cfnVirtualServiceVirtualServiceSpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualService_VirtualServiceSpecPropertyValidator(properties).assertSuccess();\n return {\n Provider: cfnVirtualServiceVirtualServiceProviderPropertyToCloudFormation(properties.provider),\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SVGR has dropped some elements not supported by reactnativesvg: filter | function SvgShop(props) {
return (
<Svg
width={27}
height={24}
viewBox="0 0 27 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className=""
{...props}
>
<G filter="url(#Shop_svg__filter0_ii)" fill="currentColor">
<Path d="M8.7 15.834h14.345a.791.791 0 00.76-.575L26.97 4.176a.792.792 0 00-.761-1.01H6.875L6.309.62A.791.791 0 005.537 0H.791a.791.791 0 000 1.583h4.112l2.856 12.863a2.378 2.378 0 00-1.43 2.179A2.377 2.377 0 008.7 19h14.344a.791.791 0 000-1.583H8.701a.792.792 0 01-.002-1.584zM25.16 4.75l-2.712 9.5H9.336l-2.11-9.5H25.16zM8 21.5C8 22.88 9.12 24 10.5 24c1.378 0 2.5-1.121 2.5-2.5 0-1.378-1.122-2.5-2.5-2.5A2.503 2.503 0 008 21.5zm2.5-.833a.834.834 0 010 1.667.834.834 0 010-1.667zM19 21.5c0 1.379 1.121 2.5 2.5 2.5 1.378 0 2.5-1.121 2.5-2.5 0-1.378-1.122-2.5-2.5-2.5a2.503 2.503 0 00-2.5 2.5zm2.5-.833a.834.834 0 010 1.667.834.834 0 010-1.667z" />
</G>
<Defs></Defs>
</Svg>
)
} | [
"function SvgProfile(props) {\n return (\n <Svg\n width={24}\n height={24}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n className=\"\"\n {...props}\n >\n <G filter=\"url(#Profile_svg__filter0_ii)\">\n <Path\n d=\"M20.67 3.693A11.981 11.981 0 0011.996 0C5.38-.008.008 5.35 0 11.967a11.983 11.983 0 003.693 8.667c.007.007.01.017.016.023.07.067.145.124.215.188.193.171.386.349.589.514.109.086.222.171.333.25.192.143.384.286.584.418.137.086.277.172.417.258.185.11.37.223.56.325.162.086.328.16.492.238.18.085.357.17.542.248.184.077.369.137.556.204.186.067.348.128.527.183.202.061.41.108.615.159.171.042.337.09.514.124.236.047.476.077.716.11.149.02.293.05.443.064.393.039.789.06 1.188.06.4 0 .795-.021 1.188-.06.15-.015.294-.044.442-.064.24-.033.48-.063.717-.11.171-.034.343-.086.514-.124.206-.05.413-.098.615-.159.18-.055.352-.121.527-.183.175-.062.374-.129.556-.204.183-.076.362-.164.542-.248.164-.078.33-.152.492-.238.19-.102.375-.214.56-.325.14-.086.28-.164.416-.258.2-.132.393-.275.585-.418.111-.086.224-.163.333-.25.203-.163.396-.336.589-.514.07-.064.145-.12.215-.188.007-.006.01-.016.016-.023 4.779-4.578 4.941-12.163.363-16.941zm-1.926 16.044a10.003 10.003 0 01-.77.61 9.556 9.556 0 01-.829.537c-.15.086-.304.172-.459.257a11.7 11.7 0 01-.864.397c-.152.061-.313.118-.472.171-.144.05-.29.102-.436.145-.171.052-.35.094-.528.137-.138.032-.275.069-.416.096-.203.04-.41.067-.619.096-.118.015-.235.036-.355.048-.329.032-.662.051-.999.051-.336 0-.67-.019-.999-.05-.119-.013-.236-.034-.354-.05-.209-.028-.416-.055-.62-.095-.14-.027-.277-.064-.416-.096a11.77 11.77 0 01-.527-.137c-.147-.043-.292-.095-.436-.145a11.81 11.81 0 01-.472-.17c-.154-.062-.3-.129-.447-.196a7.79 7.79 0 01-.877-.459 10.444 10.444 0 01-1.599-1.147c-.037-.028-.072-.064-.108-.097a6.875 6.875 0 014.672-6.422 5.08 5.08 0 004.365 0 6.875 6.875 0 014.673 6.422c-.037.033-.07.065-.108.097zM9.01 6.87a3.427 3.427 0 114.667 4.667c-.004 0-.01 0-.014.005a3.633 3.633 0 01-.717.304c-.044.013-.086.03-.133.04-.085.023-.175.038-.264.054-.166.029-.334.046-.503.05h-.097a3.465 3.465 0 01-.503-.05c-.086-.016-.177-.031-.264-.053-.046-.011-.086-.028-.133-.041a3.626 3.626 0 01-.716-.304l-.016-.005A3.428 3.428 0 019.01 6.87zm11.363 11.07a8.612 8.612 0 00-4.588-5.907 5.142 5.142 0 10-7.575 0 8.612 8.612 0 00-4.587 5.907C.336 13.313 1.424 6.897 6.052 3.61a10.278 10.278 0 0116.227 8.386c0 2.132-.667 4.21-1.908 5.944z\"\n fill=\"currentColor\"\n />\n </G>\n <Defs></Defs>\n </Svg>\n )\n}",
"function readFilterValuesfromSvg() {\n const filters = Data.Svg.Node.style.filter;\n if (filters === '') return false;\n\n const bIndex = filters.indexOf('brightness');\n const cIndex = filters.indexOf('contrast');\n const hIndex = filters.indexOf('hue-rotate');\n const sIndex = filters.indexOf('saturate');\n\n const bString = getStringBetween(filters, bIndex, '(', ')');\n const cString = getStringBetween(filters, cIndex, '(', ')');\n const hString = getStringBetween(filters, hIndex, '(', 'deg');\n const sString = getStringBetween(filters, sIndex, '(', ')');\n\n if (bString) Data.Controls.Brightness.value = bString * 10;\n if (cString) Data.Controls.Contrast.value = cString * 10;\n if (hString) Data.Controls.Hue.value = hString;\n if (sString) Data.Controls.Saturation.value = sString * 10;\n\n return true;\n}",
"function filterChange() {\n Data.Svg.Node.style.filter = getFiltersCss(\n Data.Controls.Brightness.value,\n Data.Controls.Contrast.value,\n Data.Controls.Hue.value,\n Data.Controls.Saturation.value);\n}",
"svgOptimize() {\n return async (buffer) => {\n let b = buffer;\n if (Buffer.isBuffer(buffer)) {\n b = buffer.toString();\n }\n\n if (!isSvg(b)) {\n return Promise.resolve(b);\n }\n\n let result;\n\n try {\n result = SVGO.optimize(b, this.getOption('svgo', {}));\n } catch (exception) {\n this.Console.error(exception);\n }\n\n return result && result.data ? Buffer.from(result.data) : Buffer.from(b);\n };\n }",
"_updateSVG() {\n this.SVGInteractor.updateView(this.currentXRange, this.currentYRange, this.width, this.height);\n this.SVGInteractor.updateSelectView(this._currentSelectionPoints);\n }",
"function SvgComponent(props) {\n return (\n <svg height=\"5vw\" viewBox=\"0 0 512 512\" width=\"5vw\" >\n <path\n d=\"M383.301 31H128.699L0 256l128.699 225H383.3L512 256z\"\n fill=\"#ff8fb8\"\n />\n <path d=\"M512 256L383.301 481H256V31h127.301z\" fill=\"#ff5f96\" />\n </svg>\n )\n}",
"function addSVGBlurToPolygons(basemap) {\n // must add a polygon to the map for the overlay layer to be created,\n // so add a random one to the north pole somewhere out of view\n var someLineIntheNorthPole = [[-126.562500,84.802474],[-122.343750,84.802474]];\n var polygon = L.polygon(someLineIntheNorthPole).addTo(basemap.leafletmap());\n\n var svg = basemap.leafletmap().getPanes().overlayPane.firstChild;\n var svgFilter = document.createElementNS('http://www.w3.org/2000/svg', 'filter');\n var svgBlur = document.createElementNS('http://www.w3.org/2000/svg', 'feGaussianBlur');\n\n svgFilter.setAttribute('id', 'blur');\n svgFilter.setAttribute('x', '-100%');\n svgFilter.setAttribute('y', '-100%');\n svgFilter.setAttribute('width', '500%');\n svgFilter.setAttribute('height', '500%');\n svgBlur.setAttribute('stdDeviation', 5);\n\n svgFilter.appendChild(svgBlur);\n svg.appendChild(svgFilter);\n}",
"function getSVG(features,skip,options) {\n var svg = `<svg\n id=\"uk\"\n class=\"uk svg-map\"\n width=\"${options.width}\"\n height=\"${options.height}\"\n viewBox=\"0 0 ${options.width} ${options.height}\"\n version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"><g class=\"transformBox\">`;\n\n if (options.colorType != \"simple\") {\n var fills = [];\n paths.each(function(d,i) {\n fills.push(d3.select(this).attr(\"fill\"));\n });\n }\n\n features.forEach(function(d,i) {\n var fill;\n if (skip && skip.indexOf(i) != -1) return true;\n\n if (options.colorType == \"simple\") {\n fill = options.fill;\n } else if (!fills[i].length) {\n fill = \"none\";\n } else {\n fill = fills[i];\n }\n\n svg += `<path stroke-width=\"${options.strokeWidth}\" stroke=\"${options.stroke}\" fill=\"${fill}\" d=\"${options.path(d)}\" `\n\n // gov.uk geodata\n // 1. find the gssids (gov.uk geodata)\n if (options.whichId === 'gssid') {\n svg += `${d.properties.id ? ` id=\"${d.properties.id}\"` : ``}\n ${d.properties.gssid ? ` id=\"${d.properties.gssid}\"` : ``}\n ${d.properties.LAD20CD ? ` id=\"${d.properties.LAD20CD}\"` : ``}\n ${d.properties.pcon19cd ? ` id=\"${d.properties.pcon19cd}\"` : ``}\n ${d.properties.spc16cd ? ` id=\"${d.properties.spc16cd}\"` : ``}\n ${d.properties.lac18cd ? ` id=\"${d.properties.lac18cd}\"` : ``}\n ${d.properties.nawc17cd ? ` id=\"${d.properties.nawc17cd}\"` : ``}\n ${d.properties.nawc18cd ? ` id=\"${d.properties.nawc18cd}\"` : ``}`\n }\n // add English names only\n else if (options.whichId === 'name') {\n svg += `${d.properties.n ? ` id=\"${d.properties.n}\"` : ``}\n ${d.properties.name ? ` id=\"${d.properties.name}\"` : ``}\n ${d.properties.LAD20NM ? ` id=\"${d.properties.LAD20NM}\"` : ``}\n ${d.properties.pcon19nm ? ` id=\"${d.properties.pcon19nm}\"` : ``}\n ${d.properties.spc16nm ? ` id=\"${d.properties.spc16nm}\"` : ``}\n ${d.properties.lac18nm ? ` id=\"${d.properties.lac18nm}\"` : ``}\n ${d.properties.nawc17nm ? ` id=\"${d.properties.nawc17nm}\"` : ``}\n ${d.properties.nawc18nm ? ` id=\"${d.properties.nawc18nm}\"` : ``}`\n }\n // add English names, then override those names with the Welsh one (if any)\n else if (options.whichId === 'namew') {\n svg += `${d.properties.n ? ` id=\"${d.properties.n}\"` : ``}\n ${d.properties.name ? ` id=\"${d.properties.name}\"` : ``}\n ${d.properties.LAD20NM ? ` id=\"${d.properties.LAD20NM}\"` : ``}\n ${d.properties.pcon19nm ? ` id=\"${d.properties.pcon19nm}\"` : ``}\n ${d.properties.spc16nm ? ` id=\"${d.properties.spc16nm}\"` : ``}\n ${d.properties.lac18nm ? ` id=\"${d.properties.lac18nm}\"` : ``}\n ${d.properties.nawc17nm ? ` id=\"${d.properties.nawc17nm}\"` : ``}\n ${d.properties.nawc18nm ? ` id=\"${d.properties.nawc18nm}\"` : ``}\n ${d.properties.nawc17nm ? ` id=\"${d.properties.nawc17nm}\"` : ``}\n ${d.properties.nawc18nm ? ` id=\"${d.properties.nawc18nm}\"` : ``}`\n }\n\n // add data checks from other sources here\n\n svg += ` />`;\n });\n\n // this bit is needed by https://github.com/bbc/news-vj-component-map\n svg += '<g id=\"map-hovered\"></g><g id=\"map-selected\"></g></g></svg>';\n\n // now return our finished SVG\n return svg;\n}",
"createSVGElement(w,h){const svgElement=document.createElementNS(svgNs$1,'svg');svgElement.setAttribute('height',w.toString());svgElement.setAttribute('width',h.toString());return svgElement;}",
"function getSvg(){\r\n return d3.select('svg');\r\n }",
"filterSubLayer(context) {\n return true;\n }",
"function loadFilter() {\n const sepia = document.getElementById('sepia');\n // si existe el elemento sepia entonces ejecuta el JS que aplica el atributo style al elemento\n if (sepia !== null) {\n sepia.setAttribute('style', 'filter: sepia(75%)');\n } else {\n console.log('No existe el elemento sepia');\n }\n \n const blackAndWhite = document.getElementById('blackAndWhite');\n // si existe el elemento blackAndWhite entonces ejecuta el JS que aplica el atributo style al elemento\n if (blackAndWhite !== null) {\n blackAndWhite.setAttribute('style', 'filter: grayscale(100%)');\n } else {\n console.log('No existe el elemento blackAndWhite');\n }\n\n const saturation = document.getElementById('saturation');\n // si existe el elemento saturation entonces ejecuta el JS que aplica el atributo style al elemento\n if (saturation !== null) {\n saturation.setAttribute('style', 'filter: saturate(180%)');\n } else {\n console.log('No existe el elemento saturation');\n }\n}",
"function applyFilter(context, searchItems, amount, fromDate, toDate) { \n // iterate over all the nodes in the graph\n // if the node attributes do NOT match the filter criteria, hide the node\n var self = context;\n \n if (self && self.GraphVis) {\n var gv = self.GraphVis.getGv();\n var checkNumbers = (searchItems && searchItems.length > 0);\n var checkAmount = (amount && amount.length > 0);\n var checkDates = (fromDate != null && fromDate > 0) || (toDate != null && toDate > 0);\n var nodes2Hide = []; \n var edges2Hide = [];\n if (gv) {\n gv.nodes().not(\".toggled-hide\").each(function(indx, node) {\n if (node) {\n var numMatch = false;\n var dateMatch = false;\n\n if (checkNumbers) {\n if (numberInList(node.data().name, searchItems)) {\n numMatch = true;\n } \n }\n\n // Amount is checked on the Edges and not the nodes\n if (checkDates) { \n if (eventTimeInDateRange(node.data().name, fromDate, toDate)) {\n dateMatch = true;\n }\n }\n\n if ((checkNumbers && numMatch == false) || (checkDates && dateMatch == false)) {\n // Do the all the shows first then all of the hides. \n // Can't mix both show and hide in this loop because of an issue with edge labels being redisplayed that should be hidden\n //self.GraphVis.hideNode(node);\n nodes2Hide.push(node);\n }\n else {\n self.GraphVis.showNode(node, true);\n }\n }\n }); // end each node\n\n // Only check edges if an amount is specified\n if (checkAmount) {\n gv.edges().not(\".toggled-hide\").each(function(indx, edge) {\n if (edge) {\n var amountMatch = false;\n\n if (amountInList(edge.data().amount, amount)) {\n amountMatch = true;\n } \n\n if (amountMatch == false) {\n // Do the all the shows first then all of the hides. \n // Can't mix both show and hide in this loop because of an issue with edge labels being redisplayed that should be hidden\n //self.GraphVis.hideNode(node);\n edges2Hide.push(edge);\n }\n else {\n self.GraphVis.showEdge(edge, true);\n }\n }\n }); // end each edge\n } // if checkAmount\n\n // now the hides (if any)\n for (var h = 0; h < nodes2Hide.length; h++) {\n self.GraphVis.hideNode(nodes2Hide[h], true); \n }\n for (h = 0; h < edges2Hide.length; h++) {\n self.GraphVis.hideEdge(edges2Hide[h], true); \n }\n \n self.GraphVis.gv.fit();\n }\n }\n else {\n Ext.Msg.alert(\"No graph data is available for this Entity.\");\n }\n}",
"function clearFilter(context) { \n // iterate over all the nodes in the graph and show them (unhide)\n var self = context;\n if (self && self.GraphVis) {\n self.GraphVis.showAll(true);\n }\n \n self.GraphVis.gv.fit();\n}",
"function evaluateIfSVG () {\n let existingSVG = document.getElementById('for_svg')\n if (existingSVG.hasChildNodes()) {\n existingSVG.innerHTML = ''\n }\n }",
"function getSvgXml() {\n return new XMLSerializer().serializeToString(Data.Svg.Node);\n}",
"function rangedGrayScaleOFF(){\n var rangedHero = document.getElementsByClassName(\"ranged\");\n for (var i = 0; i < rangedHero.length; i++) {\n rangedHero[i].style.filter = \"grayscale(0%)\";\n }\n}",
"function updateSelectorSvg() {\n const currentDateIndex = getCurrentDateIndex() - 1;\n miniSvg.selectAll('.date-bar').attr('fill', '#dee2e6');\n miniSvg.selectAll('.date-bar-alt').attr('fill', '#343a40');\n miniSvg.select(`#date-bar-${currentDateIndex}`).attr('fill', '#007bff')\n miniSvg.select(`#date-bar-alt-${currentDateIndex}`).attr('fill', '#515961')\n}",
"createSvgRectElement(x,y,w,h){const rect=document.createElementNS(svgNs$1,'rect');rect.setAttribute('x',x.toString());rect.setAttribute('y',y.toString());rect.setAttribute('height',w.toString());rect.setAttribute('width',h.toString());rect.setAttribute('fill','#000000');return rect;}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return original DOM references which are polluted by tags | function getOriginalDomRefs( reference, relation, offset ) {
var refNodeFound = false,
prevSib;
if( relation === "prev-sib" ) {
offset += reference.innerHTML.length;
}
else if( relation === "parent" || relation === "none" ) {
relation = "prev-sib";
}
prevSib = reference.previousSibling;
while( prevSib ) { // look for prev sibling != <h-l> and calc offset for it
if( prevSib.nodeType === 1 ) {
if( prevSib.nodeName.toLowerCase() !== "h-l" ) {
reference = prevSib;
refNodeFound = true;
break;
} else {
offset += prevSib.innerHTML.length;
}
}
else { // text-node
offset += prevSib.nodeValue.length;
}
prevSib = prevSib.previousSibling;
}
if( !refNodeFound ) { // fallback on parent node and calc offset for it
reference = reference.parentNode;
relation = "parent";
}
return new Location( reference, relation, offset );
} | [
"visitReferencing_element(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"getDOMStrings() {\n return DOMstrings;\n }",
"getImagesTags() {\n return [...this._currentDom.getElementsByTagName(\"img\")];\n }",
"function preserveWrapperATag(newMarkup) {\r\n var range = scope.editor.getRange();\r\n var anchor = getAnchorElement(range);\r\n if (anchor) {\r\n $(anchor).html(newMarkup);\r\n return anchor.outerHTML;\r\n }\r\n else {\r\n return newMarkup;\r\n }\r\n }",
"function extPart_getInnerHTMLOffsets(partName, node)\n{\n var ret = new Object();\n ret.begin = -1;\n ret.end = -1;\n \n // The old call to dwscipts.getInnerHTML() doesn't work for\n // parts that insert nested tags like\n // <ASP:Repeater><ItemTemplate> because it only looks\n // for the first begin/end tag pair. Now, we call\n // extPart.getInnerHTMLPos(), which knows exactly how\n // many tags were inserted. We only care about this logic\n // for \"wrapSelection\" parts.\n\n if (partName && (extPart.getLocation(partName).indexOf(\"wrapSelection\") != -1))\n {\n var rawText = extPart.getRawInsertText(partName);\n\n // Count the open tags that aren't inside quotes\n // TODO: We should just do this once at startup\n\n var tagCount = 0;\n var inQuotes = false;\n var innerHtmlBegin = 0;\n var c;\n\n for (var i = 0; i < rawText.length; i++)\n {\n c = rawText[i];\n\n if ((c == '\"') || (c == '\\''))\n {\n inQuotes = !inQuotes;\n }\n else if ((c == '<') && !inQuotes)\n {\n tagCount++;\n }\n }\n\n var outerHTML = dwscripts.getOuterHTML(node);\n\n var callback = new Object();\n callback.tagName = \"\";\n callback.tagCount = tagCount;\n callback.tagNameCount = 0;\n callback.innerStart = -1;\n callback.innerEnd = -1;\n callback.openTagBegin = new Function(\"tag,offset\",\"this.tagCount--; if (this.tagCount == 0 && !this.tagName) { this.tagName = tag; } if (this.tagName.toUpperCase() == tag.toUpperCase()) { ++this.tagNameCount; }\");\n callback.openTagEnd = new Function(\"offset\",\"if (this.tagCount == 0) { this.innerStart = offset; }\");\n callback.closeTagBegin = new Function(\"tag,offset\",\"if (this.tagName.toUpperCase() == tag.toUpperCase()) { --this.tagNameCount; if (this.tagNameCount == 0) { this.innerEnd = offset; this.tagName = ''; } }\");\n\n dw.scanSourceString(outerHTML, callback);\n\n ret.begin = callback.innerStart;\n ret.end = callback.innerEnd;\n }\n\n if (ret.begin < 0 || ret.end < 0)\n {\n var lastTagPos = dwscripts.getOuterHTML(node).lastIndexOf(\"</\");\n\n ret.begin = (lastTagPos - dwscripts.getInnerHTML(node).length);\n ret.end = lastTagPos;\n }\n\n return ret;\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 }",
"function updatetags(){\n\tvar e=document.getElementsByTagName(\"body\").item(0).innerHTML;\n\tdocument.getElementsByTagName(\"body\").item(0).innerHTML=addTwitterLinks(e);\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 myExtractContents(range) {\n // \"Let frag be a new DocumentFragment whose ownerDocument is the same as\n // the ownerDocument of the context object's start node.\"\n var ownerDoc = range.startContainer.nodeType == Node.DOCUMENT_NODE\n ? range.startContainer\n : range.startContainer.ownerDocument;\n var frag = ownerDoc.createDocumentFragment();\n\n // \"If the context object's start and end are the same, abort this method,\n // returning frag.\"\n if (range.startContainer == range.endContainer\n && range.startOffset == range.endOffset) {\n return frag;\n }\n\n // \"Let original start node, original start offset, original end node, and\n // original end offset be the context object's start and end nodes and\n // offsets, respectively.\"\n var originalStartNode = range.startContainer;\n var originalStartOffset = range.startOffset;\n var originalEndNode = range.endContainer;\n var originalEndOffset = range.endOffset;\n\n // \"If original start node is original end node, and they are a Text,\n // ProcessingInstruction, or Comment node:\"\n if (range.startContainer == range.endContainer\n && (range.startContainer.nodeType == Node.TEXT_NODE\n || range.startContainer.nodeType == Node.PROCESSING_INSTRUCTION_NODE\n || range.startContainer.nodeType == Node.COMMENT_NODE)) {\n // \"Let clone be the result of calling cloneNode(false) on original\n // start node.\"\n var clone = originalStartNode.cloneNode(false);\n\n // \"Set the data of clone to the result of calling\n // substringData(original start offset, original end offset − original\n // start offset) on original start node.\"\n clone.data = originalStartNode.substringData(originalStartOffset,\n originalEndOffset - originalStartOffset);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Call deleteData(original start offset, original end offset −\n // original start offset) on original start node.\"\n originalStartNode.deleteData(originalStartOffset,\n originalEndOffset - originalStartOffset);\n\n // \"Abort this method, returning frag.\"\n return frag;\n }\n\n // \"Let common ancestor equal original start node.\"\n var commonAncestor = originalStartNode;\n\n // \"While common ancestor is not an ancestor container of original end\n // node, set common ancestor to its own parent.\"\n while (!isAncestorContainer(commonAncestor, originalEndNode)) {\n commonAncestor = commonAncestor.parentNode;\n }\n\n // \"If original start node is an ancestor container of original end node,\n // let first partially contained child be null.\"\n var firstPartiallyContainedChild;\n if (isAncestorContainer(originalStartNode, originalEndNode)) {\n firstPartiallyContainedChild = null;\n // \"Otherwise, let first partially contained child be the first child of\n // common ancestor that is partially contained in the context object.\"\n } else {\n for (var i = 0; i < commonAncestor.childNodes.length; i++) {\n if (isPartiallyContained(commonAncestor.childNodes[i], range)) {\n firstPartiallyContainedChild = commonAncestor.childNodes[i];\n break;\n }\n }\n if (!firstPartiallyContainedChild) {\n throw \"Spec bug: no first partially contained child!\";\n }\n }\n\n // \"If original end node is an ancestor container of original start node,\n // let last partially contained child be null.\"\n var lastPartiallyContainedChild;\n if (isAncestorContainer(originalEndNode, originalStartNode)) {\n lastPartiallyContainedChild = null;\n // \"Otherwise, let last partially contained child be the last child of\n // common ancestor that is partially contained in the context object.\"\n } else {\n for (var i = commonAncestor.childNodes.length - 1; i >= 0; i--) {\n if (isPartiallyContained(commonAncestor.childNodes[i], range)) {\n lastPartiallyContainedChild = commonAncestor.childNodes[i];\n break;\n }\n }\n if (!lastPartiallyContainedChild) {\n throw \"Spec bug: no last partially contained child!\";\n }\n }\n\n // \"Let contained children be a list of all children of common ancestor\n // that are contained in the context object, in tree order.\"\n //\n // \"If any member of contained children is a DocumentType, raise a\n // HIERARCHY_REQUEST_ERR exception and abort these steps.\"\n var containedChildren = [];\n for (var i = 0; i < commonAncestor.childNodes.length; i++) {\n if (isContained(commonAncestor.childNodes[i], range)) {\n if (commonAncestor.childNodes[i].nodeType\n == Node.DOCUMENT_TYPE_NODE) {\n return \"HIERARCHY_REQUEST_ERR\";\n }\n containedChildren.push(commonAncestor.childNodes[i]);\n }\n }\n\n // \"If original start node is an ancestor container of original end node,\n // set new node to original start node and new offset to original start\n // offset.\"\n var newNode, newOffset;\n if (isAncestorContainer(originalStartNode, originalEndNode)) {\n newNode = originalStartNode;\n newOffset = originalStartOffset;\n // \"Otherwise:\"\n } else {\n // \"Let reference node equal original start node.\"\n var referenceNode = originalStartNode;\n\n // \"While reference node's parent is not null and is not an ancestor\n // container of original end node, set reference node to its parent.\"\n while (referenceNode.parentNode\n && !isAncestorContainer(referenceNode.parentNode, originalEndNode)) {\n referenceNode = referenceNode.parentNode;\n }\n\n // \"Set new node to the parent of reference node, and new offset to one\n // plus the index of reference node.\"\n newNode = referenceNode.parentNode;\n newOffset = 1 + indexOf(referenceNode);\n }\n\n // \"If first partially contained child is a Text, ProcessingInstruction, or\n // Comment node:\"\n if (firstPartiallyContainedChild\n && (firstPartiallyContainedChild.nodeType == Node.TEXT_NODE\n || firstPartiallyContainedChild.nodeType == Node.PROCESSING_INSTRUCTION_NODE\n || firstPartiallyContainedChild.nodeType == Node.COMMENT_NODE)) {\n // \"Let clone be the result of calling cloneNode(false) on original\n // start node.\"\n var clone = originalStartNode.cloneNode(false);\n\n // \"Set the data of clone to the result of calling substringData() on\n // original start node, with original start offset as the first\n // argument and (length of original start node − original start offset)\n // as the second.\"\n clone.data = originalStartNode.substringData(originalStartOffset,\n nodeLength(originalStartNode) - originalStartOffset);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Call deleteData() on original start node, with original start\n // offset as the first argument and (length of original start node −\n // original start offset) as the second.\"\n originalStartNode.deleteData(originalStartOffset,\n nodeLength(originalStartNode) - originalStartOffset);\n // \"Otherwise, if first partially contained child is not null:\"\n } else if (firstPartiallyContainedChild) {\n // \"Let clone be the result of calling cloneNode(false) on first\n // partially contained child.\"\n var clone = firstPartiallyContainedChild.cloneNode(false);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Let subrange be a new Range whose start is (original start node,\n // original start offset) and whose end is (first partially contained\n // child, length of first partially contained child).\"\n var subrange = ownerDoc.createRange();\n subrange.setStart(originalStartNode, originalStartOffset);\n subrange.setEnd(firstPartiallyContainedChild,\n nodeLength(firstPartiallyContainedChild));\n\n // \"Let subfrag be the result of calling extractContents() on\n // subrange.\"\n var subfrag = myExtractContents(subrange);\n\n // \"For each child of subfrag, in order, append that child to clone as\n // its last child.\"\n for (var i = 0; i < subfrag.childNodes.length; i++) {\n clone.appendChild(subfrag.childNodes[i]);\n }\n }\n\n // \"For each contained child in contained children, append contained child\n // as the last child of frag.\"\n for (var i = 0; i < containedChildren.length; i++) {\n frag.appendChild(containedChildren[i]);\n }\n\n // \"If last partially contained child is a Text, ProcessingInstruction, or\n // Comment node:\"\n if (lastPartiallyContainedChild\n && (lastPartiallyContainedChild.nodeType == Node.TEXT_NODE\n || lastPartiallyContainedChild.nodeType == Node.PROCESSING_INSTRUCTION_NODE\n || lastPartiallyContainedChild.nodeType == Node.COMMENT_NODE)) {\n // \"Let clone be the result of calling cloneNode(false) on original\n // end node.\"\n var clone = originalEndNode.cloneNode(false);\n\n // \"Set the data of clone to the result of calling substringData(0,\n // original end offset) on original end node.\"\n clone.data = originalEndNode.substringData(0, originalEndOffset);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Call deleteData(0, original end offset) on original end node.\"\n originalEndNode.deleteData(0, originalEndOffset);\n // \"Otherwise, if last partially contained child is not null:\"\n } else if (lastPartiallyContainedChild) {\n // \"Let clone be the result of calling cloneNode(false) on last\n // partially contained child.\"\n var clone = lastPartiallyContainedChild.cloneNode(false);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Let subrange be a new Range whose start is (last partially\n // contained child, 0) and whose end is (original end node, original\n // end offset).\"\n var subrange = ownerDoc.createRange();\n subrange.setStart(lastPartiallyContainedChild, 0);\n subrange.setEnd(originalEndNode, originalEndOffset);\n\n // \"Let subfrag be the result of calling extractContents() on\n // subrange.\"\n var subfrag = myExtractContents(subrange);\n\n // \"For each child of subfrag, in order, append that child to clone as\n // its last child.\"\n for (var i = 0; i < subfrag.childNodes.length; i++) {\n clone.appendChild(subfrag.childNodes[i]);\n }\n }\n\n // \"Set the context object's start and end to (new node, new offset).\"\n range.setStart(newNode, newOffset);\n range.setEnd(newNode, newOffset);\n\n // \"Return frag.\"\n return frag;\n}",
"testUidNotUndefinedOnReusedElement() {\n const div = dom.createElement(TagName.DIV);\n document.body.appendChild(div);\n div.innerHTML = '<form id=\"form\"></form>';\n const span = dom.getElementsByTagName(TagName.FORM, div)[0];\n goog.getUid(span);\n\n div.innerHTML = '<form id=\"form\"></form>';\n const span2 = dom.getElementsByTagName(TagName.FORM, div)[0];\n assertNotUndefined(goog.getUid(span2));\n }",
"function getOldSpans(doc, change) {\n var found = change[\"spans_\" + doc.id];\n if (!found) { return null }\n var nw = [];\n for (var i = 0; i < change.text.length; ++i)\n { nw.push(removeClearedSpans(found[i])); }\n return nw\n }",
"function getElements() {\n\n for(let i = 0; i < 6; i++) {\n var idxBeg = $(\"source\").value.indexOf(begSubstrings[i]);\n eoeElements[i] = $(\"source\").value.substring(idxBeg + begSubstrings[i].length - 1);\n var idxEnd = eoeElements[i].indexOf(\"</\");\n eoeElements[i] = eoeElements[i].substring(i,idxEnd);\n }\n\n //A little post-loop cleanup to catch irregularities in styling from page to page\n eoeElements[0] = eoeElements[0].substring(1,eoeElements[0].length)\n\n if(eoeElements[1].substring(0,7) == ` class=`) {\n eoeElements[1] = eoeElements[1].substring(19,eoeElements[1].length)\n }\n\n startOfLinkText = eoeElements[4].lastIndexOf(`>`) + 1\n eoeElements[4] = eoeElements[4].substring(startOfLinkText,eoeElements[4].length)\n\n endOfLink = eoeElements[3].indexOf('jcr:') -1\n eoeElements[3] = \"http://www.buffalo.edu/ubit/news/article.host.html/\" + eoeElements[3].substring(0, endOfLink) + \".detail.html\"\n\n endOfImageLink = eoeElements[5].indexOf(`\"`)\n eoeElements[5] = \"http://www.buffalo.edu/content/shared/www\" + eoeElements[5].substring(0,endOfImageLink)\n\n $(\"textArea\").innerHTML = \"<b>Title: </b>\" + eoeElements[0] +\n \"<br><b>Teaser: </b>\" + eoeElements[1] +\n \"<br><b>Link text: </b>\" + eoeElements[4] +\n \"<br><b>Link: </b>\" + eoeElements[3];\n\n $(\"image\").innerHTML = \"<img src='\" + eoeElements[5] + \"'></img>\"\n}",
"function getAllHtml(elements) {\n\n\tvar retArr = jQuery.map(elements, function(item, index) {\n\t\treturn objectOrEmptyString($(item).html())\n\t})\n\n\treturn retArr\n\n}",
"function elements() {\n return _elements;\n }",
"function collectRefsRecursive(host, content, refs) {\n var childNodes = host.childNodes;\n for (var i = 0, n = content.length; i < n; ++i) {\n var elem = content[i];\n var type = elem.type;\n if (type === 1 /* Node */) {\n var node = childNodes[i];\n var ref = elem.data.ref;\n if (ref)\n refs[ref] = node;\n collectRefsRecursive(node, elem.children, refs);\n }\n else if (type === 2 /* Component */) {\n var ref = elem.data.ref;\n if (ref)\n refs[ref] = componentMap.get(childNodes[i]);\n }\n }\n }",
"function deepClone(el) {\r\n var clone = el.cloneNode(true);\r\n copyStyle(el, clone);\r\n var vSrcElements = el.getElementsByTagName(\"*\");\r\n var vDstElements = clone.getElementsByTagName(\"*\");\r\n for (var i = vSrcElements.length; i--;) {\r\n var vSrcElement = vSrcElements[i];\r\n var vDstElement = vDstElements[i];\r\n copyStyle(vSrcElement, vDstElement);\r\n }\r\n return clone;\r\n}",
"preprocessNodes(node) {\n let cleanedNode = node.cloneNode();\n if (node.nodeType === Node.ELEMENT_NODE) {\n const tag = tagName(node);\n // If we have to replace the tagname we create another node with the new\n // tagname and copy all the attribute of the original node\n if (this.tagMap[tag]) {\n cleanedNode = document.createElement(this.tagMap[tag]);\n this.copyAllAttrs(node, cleanedNode);\n }\n // Clean all node childs\n cleanedNode.textContent = '';\n if (this.lumpTags.includes(tag)) {\n cleanedNode.setAttribute(\"property\", \"http://lblod.data.gift/vocabularies/editor/isLumpNode\");\n }\n if (node.hasChildNodes()) {\n let children = node.childNodes;\n for (let i = 0; i < children.length; i++) {\n const cleanedChild = this.preprocessNodes(children[i]);\n if (cleanedChild) {\n if (this.lumpTags.includes(tag)) {\n // make sure we can place the cursor before the non editable element\n cleanedNode.appendChild(document.createTextNode(\"\"));\n }\n cleanedNode.appendChild(cleanedChild);\n if (this.lumpTags.includes(tag)) {\n // make sure we can place the cursor after the non editable element\n cleanedNode.appendChild(document.createTextNode(\"\"));\n }\n }\n }\n }\n }\n else if (node.nodeType === Node.TEXT_NODE) {\n // remove invisible whitespace (so keeping non breaking space)\n // \\s as per JS [ \\f\\n\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff].\n cleanedNode.textContent = node.textContent.replace(invisibleSpace,'')\n .replace(/[ \\f\\n\\r\\t\\v\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/g,' ');\n if (cleanedNode.length == 0)\n return null;\n }\n return cleanedNode;\n }",
"function override(overrides){\r\n return newElementHolderProxy(undefined,overrides)\r\n }",
"function reinjectStyles() {\n if (!styleElements) {\n orphanCheck();\n return;\n }\n ROOT = document.documentElement;\n docRootObserver.stop();\n const imported = [];\n for (const [id, el] of styleElements.entries()) {\n const copy = document.importNode(el, true);\n el.textContent += \" \"; // invalidate CSSOM cache\n imported.push([id, copy]);\n addStyleElement(copy);\n }\n docRootObserver.start();\n styleElements = new Map(imported);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
setUpListeners adds the annotationOnClick function to each of the tags encountered in the genius lyrics. this will be used instead of the href genius uses to bring up the annotations | function setUpListeners() {
var i = 0;
for(i = 0; i < linkIds.length; i++) {
var anchor = document.getElementById(linkIds[i]);
$('#'+linkIds[i]).click(function() {
annotationOnClick(this.id);
});
}
} | [
"function addOnClicks(relevantHtml) {\n var relHTML = relevantHtml.replace(\"<p>\", \"\");\n relHTML = relHTML.replace(\"</p>\", \"\");\n \n var html = $.parseHTML(relHTML);\n //console.log(relevantHtml);\n var links = $(\".lyrics\", html);\n //iterate over links and add onclick and remove href to <a>\n for(i = 0; i < links[0].children.length; i++) {\n if(links[0].children[i].tagName == 'A') {\n links[0].children[i].removeAttribute(\"href\");\n links[0].children[i].id = links[0].children[i].getAttribute(\"data-id\");\n linkIds.push(links[0].children[i].id);\n links[0].children[i].onclick = function() {\n annotationOnClick(this.id);\n };\n }\n }\n return links;\n}",
"function artistEvents (template, artist) {\n\n\t\tvar plyAll = template.querySelector('.play-all');\n\t\tplyAll.addEventListener('click', emitEvent('artist: play-all', artist));\n\n\t\tvar addAll = template.querySelector('.add-all');\n\t\taddAll.addEventListener('click', emitEvent('artist: add-all', artist));\n\n\t\tvar back = template.querySelector('.back-button');\n\t\tback.addEventListener('click', emitEvent('menu: artists'));\n\n\t}",
"function setAnnotation()\n{\n var tipo;\n var tipo2;\n var attr;\n numAnnTot++;\n \n //in base al tipo di annotazione si inseriscono i dati relativi\n if ($('#inserimentocommento').css('display') === 'block') {\n tipo = 'hasComment';\n tipo2 = 'commento';\n attr = $('#insertcomment').val();\n } else if ($('#inserimentoretorica').css('display') === 'block') {\n tipo = 'denotesRhetoric';\n tipo2 = 'retorica';\n attr = $('#insertreth option:selected').text();\n } else if ($('#inserimentoautore2').css('display') === 'block') {\n if ($('#selectauthor2 option:selected').val() !== \"nothing\") \n {\n attr = $(\"#selectauthor2 option:selected\").val();\n tipo = 'hasAuthor';\n tipo2 = 'autore';\n }\n else {\n attr = $('#insertauthor2').val();\n //nuova istanza di Autore\n tipo = 'hasAuthor';\n tipo2 = 'nuovoAutore';\n }\n // tipo = 'autore';\n } else if ($('#inserimentotitolo2').css('display') === 'block') {\n tipo = 'hasTitle';\n tipo2 = 'titolo';\n attr = $('#inserttitle2').val();\n } else if ($('#inserimentopubblicazione2').css('display') === 'block') {\n tipo = 'hasPublicationYear';\n tipo2 = 'pubblicazione';\n attr = $('#insertpubb2').val();\n } else if ($('#inserimentodoi2').css('display') === 'block') {\n tipo = 'hasDOI';\n tipo2 = 'doi';\n attr = $('#insertdoi2').val();\n } else if ($('#inserimentourl2').css('display') === 'block') {\n tipo = 'hasURL';\n tipo2 = 'url';\n attr = $('#inserturl2').val();\n }\n \n var escapeAttr = attr.replace(/(['\"&;])/g, ''); // Replace di virgolette singole, doppie e caratteri speciali con un escape\n \n setSpanAttributes(escapeAttr, tipo, time, email, username, true, 'Heisenberg');\n \n arrayAnnotazioni.push({\n code : numeroAnnotazioni,\n username : username.trim(),\n email : email.trim(),\n id : id,\n start : startFrag,\n end : endFrag,\n type : tipo2.trim(),\n content : attr.trim(),\n date : time\n });\n databaseAnnotations.push({\n code : numeroAnnotazioni,\n username : username.trim(),\n email : email.trim(),\n id : id,\n start : startFrag,\n end : endFrag,\n type : tipo2.trim(),\n content : attr.trim(),\n date : time\n });\n\n if (tipo === 'hasAuthor') {\n if (istanzeAutori.indexOf(attr) === -1)\n istanzeAutori.push(attr);\n }\n\n $('.badgeAnnOnDocument').text(numAnnTot + \" Totali\");\n \n //ora che l'annotazione esiste, è possibile legargli l'ascoltatore che la evidenzia in caso di hovering\n onHover();\n}",
"function newAnnotation(type) {\n \n updateAutori();\n //ricavo il testo selezionato\n selezione = selection();\n \n //differenza tra selezione e fragmentselection: per operare sui nodi serve il primo, poichè è sostanzialmente\n //un riferimento all'interno del documento; il secondo invece estrapola dallo stesso il contenuto selezionato ogni\n //volta che viene rilasciato il tasto sinistro del mouse. dal secondo non si può risalire ai nodi, o almeno non si\n //può con il metodo utilizzato sotto. tuttavia, usando selezione è impossibile detectare se \"esiste\" la selezione\n //stessa o se è vuota, poichè jQuery per qualche motivo non riesce a confrontare l'oggetto con \"\", '', null o \n //undefined; allo stesso tempo, è molto più difficile visualizzare selezione nel modale di inserimento annotazioni.\n //per questo motivo, viene più comodo e semplice usare due variabili separate che prelevano la stessa cosa e che \n //la gestiscono in modo diverso e in momenti diversi.\n if (fragmentselection === '') {\n avviso(\"Attenzione! Nessun frammento selezionato.\");\n } \n else {\n registerAnnotation(type);\n }\n}",
"function addArtistListener(artistName, artistID, num) {\n (function () {\n var id = document.getElementById(num); //get element\n if (id) {\n id.addEventListener('click', function () {\n parent.document.getElementById('mainPane').src = \"artistAlbums.html?artistid=\"\n + artistID + \"&artistName=\" + artistName;\n }, false);\n }\n }());\n}",
"function addElementListeners() {\n addDarkModeListener();\n addColorSchemeListener();\n addResizeListener();\n addCreateNoteListener();\n addDeleteNoteListener();\n addFilterNoteListener();\n addFilterHashesListener();\n addTitleListener();\n addDownloadListener();\n addCitationButtonListener();\n addModeSwitchListeners();\n addOnCloseListener();\n addOptionsListeners();\n}",
"function setupClickListener(id, types) {\n var radioButton = document.getElementById(id);\n /*radioButton.addEventListener('click', function() {\n autocomplete.setTypes(types);\n });*/\n }",
"#registerEventListeners() {\n this.#addOnFocusEventListener();\n this.#addOnHelpIconClickEventListener();\n }",
"function addLyricsToPage(lyrics, title) {\n var str = consolidateHtml(lyrics);\n //console.log(str);\n var links = addOnClicks(str);\n //console.log(links);\n var output = \"<div class='lyric-title-container'>\" + \n \"<h2 class='lyric-title'>\" + title + \"</h2>\" + \"</div>\";\n links[0].id = \"lyricsContainer\";\n for(i = 0; i < links.length; i++) {\n output += links[i].outerHTML;\n }\n output = output;\n document.getElementById(\"watch-discussion\").innerHTML = \"\";\n document.getElementById(\"watch-discussion\").innerHTML = output;\n setUpListeners();\n linkIds = [];\n}",
"attachEvents() {\n const data = {\n mode: this.drawingMode,\n container: this.canvasDrawer,\n target: this.target\n };\n //When clicking the <label>, fire this event.\n $(this.target).click(data, function () {\n data.container.drawingMode = data.mode;\n data.container.componentSelected(data.target);\n });\n }",
"function addOnClickListenerToElements() {\n document.getElementById('session-info-span').addEventListener('click', \n openSessionInfo);\n document.querySelectorAll('.close').forEach(element => {\n element.addEventListener('click', event => {\n closeParentDisplay(event.target);\n });\n });\n document.querySelectorAll('.session-id-input').forEach(element => {\n element.addEventListener('click', event => {\n copyTextToClipboard(event.target);\n });\n });\n}",
"function addResultClickListeners() {\n $(\"#searchResults a.gs-title\").each(function(index, link) {\n // When user clicks enter for Google search results, track it\n $(link).click(function() {\n ga('send', 'event', 'Google Click', 'clicked: ' + $(this).attr('href'),\n 'query: ' + $(\"#search_autocomplete\").val().toLowerCase());\n });\n });\n}",
"function addDownloadGoogleEvents() {\n var downloadIds = ['download-hubs', 'download-exposure', 'download-assets', 'download-threats', 'download-aquatic', 'download-terrestrial', 'download-populationdensity', 'download-socialvulnerability', 'download-criticalfacilities', 'download-criticalinfrastructure', 'download-drainage', 'download-erosion', 'download-floodproneareas', 'download-sealevelrise', 'download-stromsurge', 'download-geostressor', 'download-slope'];\n\n downloadIds.forEach(function (id) {\n var elem = document.getElementById(id);\n if (elem) {\n elem.addEventListener('click', function (ev) {\n // ga event action, category, label\n googleAnalyticsEvent('click', 'downloads', id);\n });\n }\n });\n\n var watersheds = ['whatcando-btn-reslinceprojects', 'whatcando-btn-analyzesites', 'whatcando-btn-learnmore', 'whatcando-btn-targetedwatershed', 'whatcando-btn-finalreport', 'whatcando-btn-startusingCREST'];\n\n watersheds.forEach(function (id) {\n var elem = document.getElementById(id);\n if (elem) {\n elem.addEventListener('click', function (ev) {\n // ga event action, category, label\n googleAnalyticsEvent('click', 'landingpage', id);\n });\n }\n });\n}",
"function addGenreListener() {\n document.querySelectorAll('.card').forEach(card => {\n card.addEventListener('click', event => {\n if (event.target.classList.contains('genre-in-card')) {\n const order = Number(event.target.dataset.genre)\n $(`#genre-list li:nth-child(${order}) a`).tab('show')\n } \n })\n })\n }",
"function addNavListeners() {\n const li = navBarList.querySelectorAll('li') // Linst nodes in the ul\n for (let i = 0; i < li.length; i++) {\n li[i].addEventListener('click', navClick); //Add the event listener to the nav bar options\n }\n}",
"function createEventListeners(){\n var leftarrow=document.getElementById(\"leftarrow\");\n if (leftarrow.addEventListener){\n leftarrow.addEventListener(\"click\",leftArrow,false);\n } else if (leftarrow.attachEvent){\n leftarrow.attachEvent(\"onclcick\",leftArrow);\n }\n var rightarrow=document.getElementById(\"rightarrow\");\n if (rightarrow.addEventListener){\n rightarrow.addEventListener(\"click\",rightArrow,false);\n } else if (rightarrow.attachEvent){\n rightarrow.attachEvent(\"onclcick\",rightArrow);\n }\n var mainFig=document.getElementsByTagName(\"img\")[1];\n if (mainFig.addEventListener){\n mainFig.addEventListener(\"click\",zoomFig,false);\n } else if (mainFig.attachEvent){\n mainFig.attachEvent(\"onclick\",zoomFig);\n }\n var showAllButton=document.querySelector(\"#fiveButton p\");\n if (showAllButton.addEventListener){\n showAllButton.addEventListener(\"click\",previewFive,false);\n } else if (showAllButton.attachEvent){\n showAllButton.attachEvent(\"onclick\",previewFive);\n }\n}",
"function gifClicked() {\n largeGifAppears(this);\n automatedSpeech();\n}",
"setListeners(table) {\n if (!table) return;\n var self = this;\n\n if (table.element && KingTableTextBuilder.options.handleLoadingInfo) {\n self.listenTo(table, \"fetching:data\", () => {\n self.loadingHandler(table);\n });\n self.listenTo(table, \"fetched:data\", () => {\n self.unsetLoadingHandler();\n });\n self.listenTo(table, \"fetch:fail\", () => {\n self.unsetLoadingHandler().display(table, self.errorView());\n });\n self.listenTo(table, \"no-results\", () => {\n self.unsetLoadingHandler().display(table, self.emptyView());\n });\n }\n }",
"_defineListeners() {\n this.editor.model.on('insertContent', (eventInfo, [modelElement]) => {\n if (!isDrupalMedia(modelElement)) {\n return;\n }\n this.upcastDrupalMediaIsImage(modelElement);\n // Need to upcast DrupalMediaType to model so it can be used to show\n // correct buttons based on bundle.\n this.upcastDrupalMediaType(modelElement);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize communication with the parent frame. This should not be called until the app's custom listeners are registered (via our 'addListener' public method) because, once we open the communication, the parent window may send any messages it may have queued. Messages for which we don't have handlers will be silently ignored. | function initialize() {
if (isInitialized) {
return;
}
isInitialized = true;
if (window.parent === window) return;
// We kick off communication with the parent window by sending a "hello" message. Then we wait
// for a handshake (another "hello" message) from the parent window.
startPostingHello();
window.addEventListener('message', messageListener, false);
} | [
"init() {\n this._eventLoop.on(EventNames.APP_NAVIGATION_MENU_LOAD, () => this._loadMenu());\n this._eventLoop.on(EventNames.MENUITEMS_OPENPREFERENCES, (evt) => this._handleOpenPreferences(evt.evtData));\n this._eventLoop.on(EventNames.MENUITEMS_OPENGENIUS, (evt) => this._handleOpenGenius(evt.evtData));\n }",
"function CustomEventDispatcher() { this._init(); }",
"init() {\n if (!this.menuButton) {\n this.menuButton = this.createMenuButton();\n }\n this.menuButton.addEventListener(\n 'click',\n this.handleButtonClick.bind(this)\n );\n if (!this.closeButton) {\n this.closeButton = this.createCloseButton();\n }\n this.closeButton.addEventListener(\n 'click',\n this.handleButtonClick.bind(this)\n );\n this.disableTab(this.overlay);\n }",
"_initEvent() {\n this.eventManager.listen('hide', this.hide.bind(this));\n this.eventManager.listen('show', this.show.bind(this));\n }",
"function setupMessageBus() {\n // create message bus for communications between receiver and sender\n window.castMB = castReceiverManager.getCastMessageBus(window.namespace)\n \n // onMessage gets called every time the sender sends a message\n // It receives messages through ooyala's message bus \n window.castMB.onMessage = function(evt) {\n // Adds error handling to the received messages\n var message = null;\n var ERROR_MESSAGE = \"Exception in message format\";\n\n // verify message \n var message = null;\n if (evt && evt.data) {\n message = JSON.parse(evt.data);\n if (!message || !message.action) {\n console.error(ERROR_MESSAGE);\n return;\n }\n }\n\n switch (message.action) {\n case \"setCCLanguage\":\n setClosedCaptionsLanguage(message.data);\n break;\n case \"getstatus\":\n // if status is requested, return the state, playhead, and embedcode\n var status = {\n state: player.getState(),\n playhead: currentPlayheadTimeInfo,\n embed: currentEmbedCode\n }\n // only send the status back to the sender that requested it\n window.castMB.send(evt.senderId, JSON.stringify(status));\n break;\n case \"error\":\n // This message came from sender through ooyala namespace, its purpose is to render on \n // Chromecast display errors that may come from sender side. This message has structure:\n // { action: 'error', message: chrome.cast.Error }\n // Both chrome.cast.Error's code and description will be printed on the screen\n displayCastMediaError(message.message);\n break;\n }\n }\n }",
"function onReady() {\n if (isDevelopment()) {\n installDevExtensions()\n }\n //setupGolem()\n createWindow()\n tray = createTray(win)\n\n ipcHandler(app, tray, win, createPreviewWindow, APP_WIDTH, APP_HEIGHT)\n}",
"init() {\n chrome.input.ime.onActivate.addListener(this.onActivate_.bind(this));\n chrome.input.ime.onDeactivated.addListener(this.onDeactivated_.bind(this));\n chrome.input.ime.onFocus.addListener(this.onFocus_.bind(this));\n chrome.input.ime.onBlur.addListener(this.onBlur_.bind(this));\n chrome.input.ime.onInputContextUpdate.addListener(\n this.onInputContextUpdate_.bind(this));\n chrome.input.ime.onKeyEvent.addListener(\n this.onKeyEvent_.bind(this), ['async']);\n chrome.input.ime.onReset.addListener(this.onReset_.bind(this));\n chrome.input.ime.onMenuItemActivated.addListener(\n this.onMenuItemActivated_.bind(this));\n this.connectChromeVox_();\n }",
"function onStart ()\r\n{\r\n var url = null;\r\n if (window.arguments[0])\r\n {\r\n url = window.arguments[0];\r\n }\r\n var win = document.getElementById('messages-window');\r\n win.setAttribute(\"height\", 300);\r\n win.setAttribute(\"width\", 800);\r\n win.setAttribute(\"screenX\", 0);\r\n win.setAttribute(\"screenY\", screen.height - 300);\r\n \r\n var messages = document.getElementById(\"messages\");\r\n if (url)\r\n {\r\n messages.loadURI(url);\r\n }\r\n else\r\n {\r\n// messages.loadURI(\"www.google.cn\");\r\n ;\r\n }\r\n addEventListener('keydown', onKey, true);\r\n}",
"function FrshClient() {\n var _this = this;\n \n _classCallCheck(this, FrshClient);\n \n this.HANDSHAKE_SIGN = 'iframe:handshake';\n //Hash for all services and handlers, used for data back from parent\n this.services = {};\n \n return new Promise(function (resolve) {\n window.onmessage = function (message) {\n if (message.data.type === _this.HANDSHAKE_SIGN) {\n //One port for each app.\n _this.channel = message.ports[0];\n _this.instanceId = message.data.instanceId;\n \n _this.channel.postMessage({ type: 'iframe:loaded', 'height': document.body.scrollHeight });\n //Initialize services\n _this.initServices(message.data.services);\n \n //Message handler for the channel\n _this.channel.onmessage = function (appMsg) {\n if (typeof appMsg.data === 'string') {\n appMsg = JSON.parse(appMsg.data);\n } else {\n appMsg = appMsg.data;\n }\n /**\n * Check the `service` in the message to find out which service this response corresponds to.\n * If the service is not a part of this app (which should NEVER happen), silently log the message(?)\n * and move on.\n */\n if (_this.services[appMsg.service]) {\n _this.services[appMsg.service].handleResponse(appMsg);\n } else {\n console.error('Response received from parent for unrecognized service.', appMsg);\n }\n };\n \n resolve(_this);\n }\n };\n });\n }",
"function ChatBoxWindow( userObject, parentElement )\n{\n\t/** private variables **/\n\t\n\tvar myUser = userObject;\n\tvar windowElement = null;\n\tvar chatBoxContentElement = null;\n\tvar chatBoxBufferTextInputElement = null;\n\tvar listenerList = new Array( );\n\tvar selfReference = this;\n\t\n\t/** methods **/\n\t\n\t/**\n\t * This function registers the specified listener with this chat box window.\n\t * @param listener The listener to register.\n\t * @return void \n\t */\n\tChatBoxWindow.prototype.registerListener = this.registerListener = function( listener )\n\t{\n\t\tlistenerList.push( listener );\n\t};\n\t\n\t/**\n\t * This function unregisters the specified listener from this chat box window.\n\t * @param listener The listener to be unregistered.\n\t * @return void\n\t */\n\tChatBoxWindow.prototype.unregisterListener = this.unregisterListener = function( listener )\n\t{\n\t\tvar index = listenerList.indexOf( listener );\n\t\tif ( index >= 0 )\n\t\t{\n\t\t\tlistenerList.splice( index, 1 );\n\t\t}\n\t};\n\t\n\t/**\n\t * This function returns the user object associated with this window.\n\t * @return The user object associated with this window.\n\t */\n\tChatBoxWindow.prototype.getUserObject = this.getUserObject = function( )\n\t{\n\t\treturn myUser;\n\t};\n\t\n\t/**\n\t * This private function notifies all registered listeners that a message is being sent from this chat box window.\n\t * @param message The message to be sent.\n\t * @return void\n\t */\n\tfunction notifyListenersMessageSend( message )\n\t{\n\t\tvar listenerListIterator = new ArrayIterator( listenerList );\n\t\twhile( listenerListIterator.hasNext( ) )\n\t\t{\n\t\t\tvar listener = listenerListIterator.next( );\n\t\t\tlistener.notifyChatBoxMessageSend( selfReference, message );\n\t\t}\n\t}\n\t\n\t/**\n\t * This private function notifies all registered listeners that this chat box window has closed.\n\t * @return void\n\t */\n\tfunction notifyListenersClose( )\n\t{\n\t\tvar listenerListIterator = new ArrayIterator( listenerList );\n\t\twhile( listenerListIterator.hasNext( ) )\n\t\t{\n\t\t\tvar listener = listenerListIterator.next( );\n\t\t\tlistener.notifyChatBoxWindowClosed( selfReference );\n\t\t}\n\t}\n\t\n\t/**\n\t * This private function closes this chat box window causing it to be removed from it's parent element.\n\t * @return void\n\t */\n\tfunction close( )\n\t{\n\t\t// remove the window element from it's parent\n\t\twindowElement.remove( );\n\t\t// notify listeners of this window closing\n\t\tnotifyListenersClose( );\n\t\t\n\t\tmyUser.unregisterListener( selfReference );\n\t}\n\t\n\t/**\n\t * This function process's the specified message. It will update the chat box content div.\n\t * @param sender If the specified message is a user sent message, this is the user object whom the message originated from.\n\t * Otherwise, specify a value of null.\n\t * @param string message The message to process.\n\t * @param messageType The type of message being processed.\n\t * @return void\n\t */\n\tfunction processMessage( sender, message, messageType )\n\t{\t\n\t\t// prepare the new p element container for the message\n\t\tvar newMessageContainer = $( \"<p></p>\" );\n\t\t\n\t\t// if the message is a system message\n\t\tif ( messageType == ChatBoxWindow.MESSAGE_TYPE_SYSTEM )\n\t\t{\n\t\t\t// prepare the message span, and apply the .chatBoxContentSystemMessageText style to it\n\t\t\tvar messageSpan = $( \"<span></span>\", { class: \"chatBoxContentSystemMessageText\" } );\n\t\t\t// append the message to the message span\n\t\t\t$( messageSpan ).append( message );\n\t\t\t// append it to the new message container\n\t\t\t$( newMessageContainer ).append( messageSpan );\n\t\t}\n\t\t// otherwise format as a user message\n\t\telse\n\t\t{\n\t\t\tvar senderNameSpan = $(\"<span></span>\" );\n\t\t\t// if the sender name is the same as this window's id, then the message is from the other user\n\t\t\tif ( messageType == ChatBoxWindow.MESSAGE_TYPE_OTHER_USER )\n\t\t\t{\n\t\t\t\t$( senderNameSpan ).addClass(\"chatBoxContentMessageSenderOther\" );\n\t\t\t\t// set the sender name in the span\n\t\t\t\t$( senderNameSpan ).html( \"[\" + sender.getUsername( ) +\"]: \" );\n\t\t\t}\n\t\t\t// otherwise assume the message was from this client's user.\n\t\t\telse\n\t\t\t{\n\t\t\t\t$( senderNameSpan ).addClass( \"chatBoxContentMessageSenderSelf\" );\n\t\t\t\t$( senderNameSpan ).html( \"[You]: \" );\n\t\t\t}\n\t\t\t\n\t\t\t// append the sender name span to the new message container\n\t\t\t$( newMessageContainer ).append( senderNameSpan );\n\t\t\t\n\t\t\t// create and append the message span to the new message container\n\t\t\tvar messageSpan = $( \"<span></span>\", { class: \"chatBoxContentUserMessageText\" } );\n\t\t\t$( messageSpan ).append( message );\n\t\t\t$( newMessageContainer ).append( messageSpan );\n\t\t}\n\t\t\n\t\t// append the new message container to the chat content box\n\t\t$( chatBoxContentElement ).append( newMessageContainer );\n\t\t\n\t\t// automatically scroll the div\n\t\t$( chatBoxContentElement ).prop( { scrollTop: $( chatBoxContentElement ).prop( \"scrollHeight\" ) } );\n\t};\n\t\n\t/**\n\t * This function facilitates the sending of a message from this chat box window.\n\t * @return void\n\t */\n\tfunction processSendMessage( )\n\t{\n\t\t// retrieve the value from the input buffer\n\t\tvar message = $(chatBoxBufferTextInputElement).val( );\n\t\t\n\t\t// if there is a message to send\n\t\tif ( message )\n\t\t{\t\n\t\t\t// clear the input buffer\n\t\t\t$(chatBoxBufferTextInputElement).val( \"\" );\n\t\t\t\n\t\t\t// append the send message to the chat content element\n\t\t\tprocessMessage( null, message, ChatBoxWindow.MESSAGE_TYPE_SELF );\n\t\t\t\n\t\t\t// notify listeners of the sent message\n\t\t\tnotifyListenersMessageSend( message );\n\t\t}\n\t}\n\t\n\t/**\n\t * This function handles a notification of a change in status from the specified user object.\n\t * @param user The notifying user object.\n\t * @param newStatus The new status being notified of.\n\t * @return void\n\t */\n\tChatBoxWindow.prototype.notifyUserStatusChange = this.notifyUserStatusChange = function( user, newStatus )\n\t{\n\t\t// notify the client' user of this user's new status\n\t\tvar notificationMessage = \"Changed status to: \" + newStatus.statusStringValue; \n\t\tprocessMessage( null, notificationMessage, ChatBoxWindow.MESSAGE_TYPE_SYSTEM ); \n\t};\n\t\n\t/**\n\t * This function handles a notification of a message being sent from the specified user object.\n\t * @param user The user sending the message.\n\t * @param message The message being sent.\n\t * @return void\n\t */\n\tChatBoxWindow.prototype.notifyUserSentMessage = this.notifyUserSentMessage = function( user, message )\n\t{\n\t\tprocessMessage( user, message, ChatBoxWindow.MESSAGE_TYPE_OTHER_USER );\n\t};\n\t\n\t/** initialization **/\n\t\n\t// register this window as a listener for it's user object.\n\tmyUser.registerListener( this );\n\t\n\t/* initialize the HTML element's structure for the ChatBoxWindow */\n\t\n\t// create the out window div\n\twindowElement = $( \"<div/>\", { class: \"chitChatWindow\", width: \"300px\" } );\n\t\n\t\n\t// create the chat box title div\n\tvar chatBoxTitleDiv = $( \"<div/>\", { class: \"chitChatWindowTitle\" } );\n\t// create the chat box title text span\n\tvar chatBoxTitleTextSpan = $( \"<span></span>\" );\n\t$( chatBoxTitleTextSpan ).html( myUser.getUsername( ) );\n\t// append the title span to the box title div\n\t$( chatBoxTitleDiv ).append( chatBoxTitleTextSpan );\n\t// create the title close button\n\tvar chatBoxTitleCloseButton = $( \"<input></input>\", { type: \"button\", class: \"chitChatWindowTitleButton\", value: \"X\" } );\n\t// register the event handler for the close button\n\t$( chatBoxTitleCloseButton ).click( function( )\n\t{\n\t\t$( windowElement ).fadeOut( \"slow\", function( ) { close( ); } );\n\t} );\n\t// append the close button to the title div\n\t$( chatBoxTitleDiv ).append( chatBoxTitleCloseButton );\n\t\n\t// append the chat box title div to the chat box window\n\t$( windowElement ).append( chatBoxTitleDiv );\n\t\n\t// create the chat box content div\n\tchatBoxContentElement = $( \"<div/>\", { class: \"chitChatWindowContent\", height: \"150px\" } );\n\t// append the chat box content div to the chat box window\n\t$( windowElement ).append( chatBoxContentElement );\n\t\n\t// create the chat box buffer div\n\tvar chatBoxBufferDiv = $( \"<div/>\", { class: \"chatBoxBuffer\" } );\n\t// create the buffer text input and append it to the chat box buffer\n\tchatBoxBufferTextInputElement = $( \"<input></input>\", { type: \"text\" } );\n\t// ensure that when the text field receives focus to select all text inside of it\n\t$( chatBoxBufferTextInputElement ).focus( function ( ) { $( chatBoxBufferTextInputElement ).select( ); } );\n\t// assign the event for handling sending a message\n\t$( chatBoxBufferTextInputElement ).keyup( function( event )\n\t\t{\n\t\t\tif ( event.keyCode == 13 )\n\t\t\t{\n\t\t\t\tprocessSendMessage( );\n \t\t\t}\n\t\t} );\n\t\n\t\n\t$( chatBoxBufferDiv ).append( chatBoxBufferTextInputElement );\n\t// create the buffer text send button and append it to the chat box buffer\n\tvar sendButton = $( \"<input></input>\", { type: \"button\", value: \"Send\" } );\n\t$( sendButton ).click( function( event ) { processSendMessage( ); } );\n\t$( chatBoxBufferDiv ).append( sendButton );\n\t\n\t// append the chat box buffer div to the chat box window div\n\t$( windowElement ).append( chatBoxBufferDiv );\n\t\n\t// append the element to the content pane\n\t$( parentElement ).append( windowElement );\n\t// slowly fade in to look slick ;)\n\t$( windowElement ).css( { display: \"none\" } );\n\t$( windowElement ).fadeIn( \"slow\" );\n}",
"connectedCallback() {\n this.parent = this.queryParentRouterSlot();\n }",
"function _initWatchers()\n {\n var lasth = null, fn; // previous body height value\n\n function childSend() \n {\n var h = height(), l = childs.length, i = 0;\n\n if (!l || lasth === h) {\n return;\n }\n\n lasth = h;\n\n for (; i < l; i += 1) {\n childs[i].sendHeight();\n }\n } \n\n function parentSend() \n {\n var l = parents.length, i = 0, parent;\n\n if (!l) {\n return;\n }\n\n for (; i < l; i += 1) {\n parent = parents[i];\n parent.sendMessage('position', offset.encode(offset(parent.iframe)));\n }\n } \n\n fn = throttle(parentSend, 16);\n\n on('resize', fn);\n on('scroll', fn);\n\n setInterval(childSend, 16);\n }",
"function Window_SlotCommand() {\n this.initialize.apply(this, arguments);\n}",
"function openChildWindow(){\n setErrorFlag();\n var lstrWidth = '750px';//set default width\n var lstrHeight = '450px';//set default height\n var lstrURL;\n var lstrArgument;\n\n lstrURL = openChildWindow.arguments[0];\n if( lstrURL.indexOf(\"?\") == -1 ) {\n lstrURL = lstrURL + \"?childFw=Y\" ;\n } else {\n lstrURL = lstrURL + \"&childFw=Y\" ;\n }\n lstrURL = encodeURI(lstrURL);\n lstrArgument = openChildWindow.arguments[1];\n\n //set the width\n if(openChildWindow.arguments[2] != null && openChildWindow.arguments[2].length > 0 ){\n lstrWidth= openChildWindow.arguments[2];\n }\n\n //set the height\n if(openChildWindow.arguments[3] != null && openChildWindow.arguments[3].length > 0 ){\n lstrHeight= openChildWindow.arguments[3];\n }\n\n // for appending the readonly flag of Parent Screen\n if(document.getElementById('readOnlyFlg') != null && document.getElementById('readOnlyFlg')!= undefined){\n if(lstrURL.indexOf('?') != -1 ){\n lstrURL = lstrURL+ '&childScreen=true&readOnlyFlg='+document.getElementById('readOnlyFlg').value;\n }else{\n lstrURL = lstrURL+ '?childScreen=true&readOnlyFlg='+document.getElementById('readOnlyFlg').value;\n }\n }\n\n //open model dialog\n window.showModalDialog(lstrURL,lstrArgument, 'dialogHeight:' + lstrHeight + ';dialogWidth:' + lstrWidth + ';center:yes;status:no');\n // Set Error Flag to true so that Buttons are not disabled of parent\n isErrFlg = true;\n}",
"function helloHandler() {\n error('PARENT: Got direct message from child');\n}",
"initFrame() {\n const l10n = window._wpMediaViewsL10n || {}\n const labels = this.model.get('labels')\n\n this.frame = wp.media({\n button: {\n text: l10n.select,\n close: false\n },\n states: [\n new wp.media.controller.Library({\n title: labels.frame_title,\n library: wp.media.query({ type: 'image' }),\n multiple: false,\n date: false,\n priority: 20,\n suggestedWidth: this.model.get('width'),\n suggestedHeight: this.model.get('height')\n }),\n new wp.media.controller.Cropper({\n imgSelectOptions: this.calculateImageSelectOptions,\n control: this\n })\n ]\n })\n\n this.frame.on('select', this.onSelect, this)\n this.frame.on('cropped', this.onCropped, this)\n this.frame.on('skippedcrop', this.onSkippedCrop, this)\n }",
"connectedCallback() {\n this._form = this.findContainingForm();\n if (this._form) {\n this._form.addEventListener('formdata', this._handleFormData);\n }\n }",
"init() {\n this._initCalled = true;\n\n if (this.isDummy)\n return;\n\n this._overview = new OverviewActor();\n this._overview._delegate = this;\n Main.layoutManager.overviewGroup.add_child(this._overview);\n\n this._shellInfo = new ShellInfo();\n\n Main.layoutManager.connect('monitors-changed', this._relayout.bind(this));\n this._relayout();\n\n Main.wm.addKeybinding(\n 'toggle-overview',\n new Gio.Settings({ schema_id: WindowManager.SHELL_KEYBINDINGS_SCHEMA }),\n Meta.KeyBindingFlags.IGNORE_AUTOREPEAT,\n Shell.ActionMode.NORMAL | Shell.ActionMode.OVERVIEW,\n this.toggle.bind(this));\n\n const swipeTracker = new SwipeTracker.SwipeTracker(global.stage,\n Clutter.Orientation.VERTICAL,\n Shell.ActionMode.NORMAL | Shell.ActionMode.OVERVIEW,\n { allowDrag: false, allowScroll: false });\n swipeTracker.orientation = Clutter.Orientation.VERTICAL;\n swipeTracker.connect('begin', this._gestureBegin.bind(this));\n swipeTracker.connect('update', this._gestureUpdate.bind(this));\n swipeTracker.connect('end', this._gestureEnd.bind(this));\n this._swipeTracker = swipeTracker;\n }",
"initializeOnConnection() {\n this.webSocketServer.on('connection', (clientWebSocket) => {\n let client = this.getClient(clientWebSocket);\n this.initializeOnMessage(client);\n this.sendHandShakeRequestCommand(client);\n });\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 }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clear the user projection if set. Note that this method is not yet a part of the stable API. Support for user projections is not yet complete and should be considered experimental. | function clearUserProjection() {
userProjection = null;
} | [
"function unproject(coord) {\n return map.unproject(coord, map.getMaxZoom());\n}",
"unproject(xy) {\n Object(_utils_assert__WEBPACK_IMPORTED_MODULE_10__[\"default\"])(this.internalState);\n const viewport = this.internalState.viewport || this.context.viewport;\n return viewport.unproject(xy);\n }",
"toDefaultProjection(lat, long) {\n return ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');\n }",
"clearSourceSelections() {\n this.mappingSelectionsService_.removeSourceProvider(\n this.selectedSourceProviderId);\n }",
"function clearLat() {\n lat = [];\n}",
"function resetSelectedRegion() {\n selectedRegion = undefined\n }",
"function preserveOriginalCRS(dataset, jsonObj) {\n var info = dataset.info || {};\n if (!info.crs && 'input_geojson_crs' in info) {\n // use input geojson crs if available and coords have not changed\n jsonObj.crs = info.input_geojson_crs;\n\n }\n\n // Removing the following (seems ineffectual at best)\n // else if (info.crs && !isLatLngCRS(info.crs)) {\n // // Setting output crs to null if coords have been projected\n // // \"If the value of CRS is null, no CRS can be assumed\"\n // // source: http://geojson.org/geojson-spec.html#coordinate-reference-system-objects\n // jsonObj.crs = null;\n // }\n}",
"function clearExistingProposalCoordinators() {\n\t$j('#' + propCoordId).empty();\n}",
"function clearUserForm() {\n setErrorMessages([])\n setUserData(emptyUserFormData)\n }",
"function resetData() {\n geoJSON = {\n type: \"FeatureCollection\",\n features: []\n };\n myMap.data.forEach(function(feature) {\n myMap.data.remove(feature);\n });\n }",
"function emptyUserForm(){\n\t\t$scope.user ={};\n\t\t$scope.useremailexist = false;\n\t\t$scope.usernamexist = false;\n\t}",
"function clearSelectedPoints () {\n\tselectedPoints = [];\n}",
"function reset() {\n var bottomLeft = project(bounds[0]),\n topRight = project(bounds[1]);\n\n svg.attr(\"width\", topRight[0] - bottomLeft[0])\n .attr(\"height\", bottomLeft[1] - topRight[1])\n .style(\"margin-left\", bottomLeft[0] + \"px\")\n .style(\"margin-top\", topRight[1] + \"px\");\n\n g.attr(\"transform\", \"translate(\" + -bottomLeft[0] + \",\" + -topRight[1] + \")\");\n feature.attr(\"d\", path);\n }",
"clear() {\n this.context.clearRect(\n this.frame.x / this.getZoomFactor(), \n this.frame.y / this.getZoomFactor(), \n this.frame.w / this.getZoomFactor(), \n this.frame.h / this.getZoomFactor()\n );\n }",
"function reset() {\n var browserWidth = $(window).width();\n if(browserWidth <= 1000) {\n map.setCenter(mapOptions.center);\n map.setZoom(11);\n } else if(browserWidth > 1000) {\n map.setCenter(mapOptions.center);\n map.setZoom(12);\n }\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}",
"clearAllZoomRegions() {\n for (let i = 0; i < this._zoomRegions.length; i++)\n this._zoomRegions[i].setActive(false);\n\n this._zoomRegions.length = 0;\n this.stopTrackingMouse();\n this.showSystemCursor();\n }",
"function clearSelectedPointsCanvas() {\n\tvar selectedPointsCanvas = document.getElementById('select-points')\n\tvar selectedCtx = selectedPointsCanvas.getContext('2d')\n\tselectedCtx.clearRect(0, 0, selectedPointsCanvas.offsetWidth, selectedPointsCanvas.offsetHeight)\n}",
"function resetProject() {\n\tprojectManager.resetProject();\n // Reset ractive bindings\n setRactives();\n update();\n showProjectResetDialogue();\n}",
"function clearOrgunitAssignment() {\n\tfor (var i = 0; metaData.dataSets && i < metaData.dataSets.length; i++) {\n\t\tmetaData.dataSets[i].organisationUnits = [];\n\t}\n\n\tfor (var i = 0; metaData.programs && i < metaData.programs.length; i++) {\n\t\tmetaData.programs[i].organisationUnits = [];\n\t}\n\n\tfor (var i = 0; metaData.users && i < metaData.users.length; i++) {\n\t\tmetaData.users[i].organisationUnits = [];\n\t\tmetaData.users[i].dataViewOrganisationUnits = [];\n\t\tmetaData.users[i].teiSearchOrganisationUnits = [];\n\t}\n\n\n\tfor (var i = 0; metaData.hasOwnProperty(\"predictors\") && i < metaData.predictors.length; i++) {\n\t\tmetaData.predictors[i].organisationUnitLevels = [];\n\t}\n\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add controls to the figure for the current color system. This requires that the visualization is inside a .figure and that this .figure contains a .visualizationcontrols. | init_controls() {
if (this.$controls.length == 0) {
return;
}
this.color_system_controls = make_sliders_for_color_system(this.color_system, this.$controls);
// fullscreen button
if (!this.$figure.find('.fullscreen-button').length) {
// if no fullscreen button exists yet (can happen in comparisons), create one
this.$fullscreen_button = $(
'<span class="fullscreen-button">Fullscreen</span>'
).prependTo(this.$figure.find('.figure-title'));
this.$fullscreen_button.click(() => {
toggle_full_screen(this.$figure[0]);
/*
* Other changes will be done in the fullscreenchange event listener below.
* This is necessary for other visualizations to keep working as well in case
* this figure is inside a visualization comparison.
*/
});
}
$(document).on("webkitfullscreenchange mozfullscreenchange fullscreenchange", () => {
this.$container.find("canvas").removeAttr("style"); // otherwise, the figure will keep the previously calculated size
if (is_fullscreen()) { // just changed to fullscreen
//this.keep_aspect = false; // will be re-set to true on fullscreenchange (see below)
console.log("entered fullscreen");
this.$fullscreen_button.text("Exit fullscreen");
} else { // just exited fullscreen
//this.keep_aspect = true;
console.log("exited fullscreen");
this.$fullscreen_button.text("Fullscreen");
}
this.on_resize();
});
} | [
"init_advanced_controls(color_system_name) {\n let that = this;\n if (this.$figure.find(\".visualization-controls-advanced-toggle\").length == 0) {\n /* Add toggle for showing/hiding controls. */\n this.$controls_advanced.before(\n '<h3 class=\"visualization-controls-advanced-toggle\">' +\n '<span class=\"arrow\">▶ </span><span class=\"text\">Advanced controls</span></h3>'\n );\n this.$controls_advanced.hide();\n let $toggle = this.$figure.find(\".visualization-controls-advanced-toggle\");\n $toggle.click(function () {\n if (that.$controls_advanced.is(\":visible\")) {\n $toggle.find(\".arrow\").removeClass(\"arrow-rotated\");\n } else {\n $toggle.find(\".arrow\").addClass(\"arrow-rotated\");\n }\n that.$controls_advanced.toggle(300);\n });\n }\n\n this.$controls_advanced.append(\n '<h3 class=\"visualization-controls-system-header\">' +\n color_system_name +\n '</h3>'\n );\n this.show_only_color_solid_control = new VisualizationControlCheck(\n this.$controls_advanced,\n \"Show the color solid only\"\n );\n this.show_only_color_solid_control.add_listener((event) =>\n that.show_only_color_solid_changed.call(that, event));\n }",
"function setupColorControls()\n{\n dropper.onclick = () => setDropperActive(!isDropperActive()) ;\n color.oninput = () => setLineColor(color.value);\n colortext.oninput = () => setLineColor(colortext.value);\n\n //Go find the origin selection OR first otherwise\n palettedialog.setAttribute(\"data-palette\", getSetting(\"palettechoice\") || Object.keys(palettes)[0]);\n\n palettedialogleft.onclick = () => { updatePaletteNumber(-1); refreshPaletteDialog(); }\n palettedialogright.onclick = () => { updatePaletteNumber(1); refreshPaletteDialog(); }\n refreshPaletteDialog();\n}",
"function setupImageControls() {\n Data.Controls.Brightness = document.getElementById('brightness');\n Data.Controls.Contrast = document.getElementById('contrast');\n Data.Controls.Hue = document.getElementById('hue');\n Data.Controls.Saturation = document.getElementById('saturation');\n\n Data.Controls.Brightness.value = Settings.Filters.Brightness;\n Data.Controls.Contrast.value = Settings.Filters.Contrast;\n Data.Controls.Hue.value = Settings.Filters.Hue;\n Data.Controls.Saturation.value = Settings.Filters.Saturation;\n\n Data.Controls.Brightness.addEventListener('input', filterChange);\n Data.Controls.Contrast.addEventListener('input', filterChange);\n Data.Controls.Hue.addEventListener('input', filterChange);\n Data.Controls.Saturation.addEventListener('input', filterChange);\n\n document.getElementById('image-controls-reset').\n addEventListener('click', imageControlsResetClick);\n document.getElementById('image-controls-save').\n addEventListener('click', imageControlsSaveClick);\n}",
"function addControls() {\n // Add home button\n L.easyButton(\n \"fa-home\",\n function (btn, map) {\n map.setView([home.lat, home.lng], home.zoom);\n },\n \"Zoom To Home\",\n { position: \"topright\" }\n ).addTo(myMap);\n\n // Reposition the zoom control\n myMap.zoomControl.setPosition(\"topright\");\n\n // Add a fullscreen toggle\n myMap.addControl(new L.Control.Fullscreen({ position: \"topright\" }));\n\n // Add scale bar\n L.control.betterscale().addTo(myMap);\n}",
"addControls () {\n /**\n * @type {ControlsConfig}\n */\n this.controlsConfig = this.map_.get('mapConfig').controls\n if (checkFor(this.controlsConfig, 'onMap')) {\n this.addControlMultipleInternal_(this.map_, this.controlsConfig.onMap)\n }\n }",
"function placeControlsElements(){\n\t\t\n\t\tif(g_objButtonPlay)\t\t\t\n\t\t\tg_functions.placeElement(g_objButtonPlay, g_options.slider_play_button_align_hor, g_options.slider_play_button_align_vert, g_options.slider_play_button_offset_hor, g_options.slider_play_button_offset_vert);\t\t\t\n\t\t\n\t\t//position fullscreen button\n\t\tif(g_objButtonPlay)\t\t\t\n\t\t\tg_functions.placeElement(g_objButtonFullscreen, g_options.slider_fullscreen_button_align_hor, g_options.slider_fullscreen_button_align_vert, g_options.slider_fullscreen_button_offset_hor, g_options.slider_fullscreen_button_offset_vert);\n\t\t\n\t\t//position zoom panel\n\t\tif(g_objZoomPanel){\n\t\t\tvar zoomPanelElement = g_objZoomPanel.getElement();\n\t\t\tg_functions.placeElement(zoomPanelElement, g_options.slider_zoompanel_align_hor, g_options.slider_zoompanel_align_vert, g_options.slider_zoompanel_offset_hor, g_options.slider_zoompanel_offset_vert);\n\t\t}\n\t}",
"function showControls() {\n var controls = arguments;\n\n if (controls.length == 0) {\n controls = ocean.controls;\n }\n\n $.each(controls, function (i, control) {\n var parent = _controlVarParent(control);\n\n parent.show();\n parent.parent('.controlgroup').show();\n\n $('#' + control).change();\n });\n}",
"function controlChangeHandler () {\n setColours(this.value);\n }",
"createUI() {\n var title = panelTitle;\n this.panel = new PanelClass(this.viewer, title);\n var button1 = new Autodesk.Viewing.UI.Button(panelTitle);\n\n button1.onClick = (e) => {\n if (!this.panel.isVisible()) {\n this.panel.setVisible(true);\n } else {\n this.panel.setVisible(false);\n }\n };\n\n button1.addClass('fa');\n button1.addClass('fa-child');\n button1.addClass('fa-2x');\n button1.setToolTip(onMouseOver);\n\n this.subToolbar = this.viewer.toolbar.getControl(\"spinalcom-sample\");\n if (!this.subToolbar) {\n this.subToolbar = new Autodesk.Viewing.UI.ControlGroup('spinalcom-sample');\n this.viewer.toolbar.addControl(this.subToolbar);\n }\n this.subToolbar.addControl(button1);\n this.initialize();\n }",
"function enableChartView() {\n for (let element of defaultViewElements) element.style.display = \"none\";\n for (let element of chartViewElements) element.style.display = \"block\";\n }",
"function createElementsForControls() {\r\n if (_opts.behavior.switchMode) {\r\n _dom.modeSwitch = $(\"<div></div>\")\r\n .appendTo(_dom.el)\r\n .addClass(\"s-c-p-mode-switch\");\r\n }\r\n }",
"function showgreen() {\r\n var o_panel_info = document.getElementById(\"outputpanel\").classList\r\n if(o_panel_info.length > 1){\r\n o_panel_info.remove(\"redbg\", \"darkbg\", \"lightbg\");\r\n }\r\n o_panel_info.add(\"greenbg\");\r\n}",
"function showControls() {\n if (videoControls.classList.contains(\"hidden\")) {\n videoControls.classList.remove('hidden');\n videoControls.classList.remove('hide');\n videoContainer.classList.remove('hidden-controls');\n referrer.that.invokeMethodAsync(\"onControlsStatusChange\", true);\n }\n }",
"function setControlsPosition() {\n const menu = document.getElementById('menu');\n const panel = document.getElementById('image-controls');\n\n const top = Data.Controls.Open ? menu.clientHeight : -panel.clientHeight - 2;\n panel.style.top = top + 'px';\n\n if (Data.Controls.Open)\n document.getElementById('menu-controls').classList.add('active');\n else\n document.getElementById('menu-controls').classList.remove('active');\n}",
"function showred() {\r\n var o_panel_info = document.getElementById(\"outputpanel\").classList\r\n if(o_panel_info.length > 1){\r\n o_panel_info.remove(\"greenbg\", \"darkbg\", \"lightbg\");\r\n }\r\n o_panel_info.add(\"redbg\");\r\n}",
"function showHideTLeditPanel(){\n if(trafficLightControl.isActive){ // close panel\n trafficLightControl.isActive=false; //don't redraw editor panel\n if(drawBackground){ // wipe out existing editor panel\n ctx.drawImage(background,0,0,canvas.width,canvas.height);\n }\n document.getElementById(\"editTLbutton\").innerHTML\n =\"Open traffic-light control panel\";\n }\n else{ // open panel\n trafficLightControl.isActive=true;\n document.getElementById(\"editTLbutton\").innerHTML\n =\"Close traffic-light control panel\";\n }\n}",
"function addControl(ctrl, cType, options) {\n for (var i = 0; i < p.controls.length; ++i) {\n if (p.controls[i].control == ctrl) {\n console.warn(\"Already added control: %o\", ctrl);\n return;\n }\n }\n\n options = options || {};\n\n var ctrlData = { control: ctrl, elements: [], controlType: cType }\n p.controls.push(ctrlData);\n\n var addControlTo = function (cntr) {\n if (cntr == 'container') {\n cntr = options.container || dom.find('container');\n if (typeof cntr == 'string') { cntr = document.getElementById(cntr); }\n if (!cntr.dom) { dom.claim(cntr, 'controlContainer'); }\n } else if (cntr == 'overlay') {\n cntr = dom.find('overlay');\n }\n if (typeof ctrl.createControlElements != 'function') { return; }\n var ctrlElem = ctrl.createControlElements(cntr);\n if (!ctrlElem) { return; }\n cntr.appendChild(ctrlElem);\n ctrlData.elements.push(ctrlElem);\n Monocle.Styles.applyRules(ctrlElem, Monocle.Styles.control);\n return ctrlElem;\n }\n\n if (!cType || cType == 'standard' || cType == 'invisible') {\n addControlTo('container');\n } else if (cType == 'page') {\n forEachPage(addControlTo);\n } else if (cType == 'modal' || cType == 'popover' || cType == 'hud') {\n addControlTo('overlay');\n ctrlData.usesOverlay = true;\n } else if (cType == 'invisible') {\n addControlTo('container');\n } else {\n console.warn('Unknown control type: ' + cType);\n }\n\n if (options.hidden) {\n hideControl(ctrl);\n } else {\n showControl(ctrl);\n }\n\n if (typeof ctrl.assignToReader == 'function') {\n ctrl.assignToReader(API);\n }\n\n return ctrl;\n }",
"renderHolderControls() {\n let holderNode = this.getHolderNode();\n if (!holderNode.data('matrix-initialized')) {\n holderNode.find('.value-wrap').remove();\n holderNode.data('matrix-initialized', true);\n let registry = this.getInput(holderNode, 'registry');\n let registry2 = this.getInput(holderNode, 'registry2');\n let registryStringify = this.getInput(holderNode, 'registryStringify');\n let registry2Stringify = this.getInput(holderNode, 'registry2Stringify');\n jQuery([registryStringify, registry2Stringify]).each(function (i, input) {\n input.attr('type', 'hidden');\n jQuery('<div class=\"fields-wrap\"/>').appendTo(input.parent())\n .on('change', ':checkbox', function () {\n this.onFieldListChange(input);\n }.bind(this))\n }.bind(this));\n registry.change(function(){\n this.renderRegistryFields(registry, registryStringify);\n }.bind(this)).change();\n registry2.change(function(){\n this.renderRegistryFields(registry2, registry2Stringify);\n }.bind(this)).change();\n }\n }",
"function visualize() {\n\n visualizer.updatePitchChart(audioProcessor.getPitches(), audioProcessor.getTimestamps());\n visualizer.updateRateChart(audioProcessor.getVibratoRates(), audioProcessor.getTimestamps());\n visualizer.updateWidthChart(audioProcessor.getVibratoWidths(), audioProcessor.getTimestamps());\n calcPitch();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GFV[] Get Freedom Vector 0x0C | function GFV(state) {
var stack = state.stack;
var fv = state.fv;
if (exports.DEBUG) { console.log(state.step, 'GFV[]'); }
stack.push(fv.x * 0x4000);
stack.push(fv.y * 0x4000);
} | [
"static FromFloatArrayToRef(array, offset, result) {\n Vector4.FromArrayToRef(array, offset, result);\n }",
"static FromFloatArray(array, offset) {\n return Vector3.FromArray(array, offset);\n }",
"static FromFloatArrayToRef(array, offset, result) {\n return Vector3.FromArrayToRef(array, offset, result);\n }",
"static FromArray(array, offset = 0) {\n return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n }",
"static get VERTEX_FLOAT_SIZE() { return 3 + 3 + 2; }",
"buildFeatureVector() {\n // create empty feature vector\n let featureVector = [];\n // get all partial feature vectors and merge them together\n for (let i in this.nodes) {\n let dataAvailable = this.nodes[i].checkDataAvailability();\n if (dataAvailable == false) {\n console.log(\"Can not be generated!\");\n return [];\n }\n let partialFeatureVector = this.nodes[i].getPartialFeatureVector();\n featureVector = featureVector.concat(partialFeatureVector);\n }\n // return the feature vector\n return featureVector;\n }",
"get f32() { return new Float32Array(module.memory.buffer, this.ptr, this.len); }",
"function polyvecNew(paramsK) {\r\n // make array containing 3 elements of type poly\r\n var pv = new Array(paramsK);\r\n for (var i = 0; i < paramsK; i++) {\r\n pv[i] = new Array(384);\r\n }\r\n return pv;\r\n}",
"static FromArray(array, offset = 0) {\n return new Vector3(array[offset], array[offset + 1], array[offset + 2]);\n }",
"getVector() {\n if (this.parent) {\n let dx = this.parent.loc.x - this.loc.x;\n let dy = this.parent.loc.y - this.loc.y;\n let v = new JSVector(dx, dy);\n return v;\n }\n else return (JSVector(0, 0));\n }",
"static Zero() {\n return new Vector2(0, 0);\n }",
"static vRandom(r) { return newVec((Math.random()-0.5)*r, (Math.random()-0.5)*r, (Math.random()-0.5)*r); }",
"static mxVMult(v,m) {\r\n\t\tvar res = new mVec3(); \r\n\t\tres.x = (v.x * m.M[0]) + (v.y * m.M[4]) + (v.z * m.M[8]) + m.M[12];\r\n\t\tres.y = (v.x * m.M[1]) + (v.y * m.M[5]) + (v.z * m.M[9]) + m.M[13];\r\n\t\tres.z = (v.x * m.M[2]) + (v.y * m.M[6]) + (v.z * m.M[10]) + m.M[14];\r\n\t\treturn res; \r\n\t}",
"static FromArray(array, offset = 0) {\n return new Vector2(array[offset], array[offset + 1]);\n }",
"_normalVector(v0, vt, va) {\n let normal0;\n let tgl = vt.length();\n if (tgl === 0.0) {\n tgl = 1.0;\n }\n if (va === undefined || va === null) {\n let point;\n if (!Scalar_1.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, types_1.Epsilon)) {\n // search for a point in the plane\n point = new Vector3_1.Vector3(0.0, -1.0, 0.0);\n }\n else if (!Scalar_1.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, types_1.Epsilon)) {\n point = new Vector3_1.Vector3(1.0, 0.0, 0.0);\n }\n else if (!Scalar_1.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, types_1.Epsilon)) {\n point = new Vector3_1.Vector3(0.0, 0.0, 1.0);\n }\n else {\n point = Vector3_1.Vector3.Zero();\n }\n normal0 = Vector3_1.Vector3.Cross(vt, point);\n }\n else {\n normal0 = Vector3_1.Vector3.Cross(vt, va);\n Vector3_1.Vector3.CrossToRef(normal0, vt, normal0);\n }\n normal0.normalize();\n return normal0;\n }",
"get centre() { return new vector2(this.centrex, this.centrey);}",
"function formVector(p, q)\n{\n var pq = {lantitude: 0.0, longitude: 0.0, height: 0.0};\n pq.lantitude = q.lantitude - p.lantitude;\n pq.longitude = q.longitude - p.longitude;\n pq.height = q.height - p.height;\n return pq;\n}",
"function getVassals(){\r\n g_vassals = [];\r\n\r\n var v = GM_getValue(vassal_key, '').split(\"||\");\r\n\r\n if (v=='') return;\r\n \r\n for (var i=0; i < v.length; i++){\r\n\tg_vassals[i] = makeVassal(v[i]);\r\n\tg_paid[v[i]] = [];\r\n }\r\n}",
"function vectorOperation(v1, v2, op) {\n let minLength = Math.min(v1.length, v2.length);\n let newV = [];\n for (let i = 0; i < minLength; i++) {\n newV.push(op(v1[i] * 1.0, v2[i]));\n }\n return newV;\n}",
"static flipVector(vec){\n\t\treturn [vec[0] * -1, vec[1] * -1];\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to update the prominently displayed episode title and number | function updateEpisode(episode, episodeIndex) {
$('.episodeNumber')
.text(episodeIndex+1)
.next().text(episode.title);
} | [
"function UpdateDVDTitle() {\n\n\tif (g_bFirstPlaying) {\n\t\tTitleFull.Text = L_DVDPlayer_TEXT;\n\t\tTitle.Text = L_DVDPlayer_TEXT;\n\t}\n\n\telse {\n\t\ttry { \n\t\t\tnTitle = DVD.CurrentTitle;\n\t\t\tnChap = DVD.CurrentChapter;\n\n var tempstr = L_DVDPlayerTitleChapter_TEXT.replace(/%1/i, nTitle).replace(/%2/i, nChap);\n\t\t\tTitleFull.Text = tempstr;\n\t\t\tTitle.Text = tempstr;\n\t\t}\n\t\tcatch(e) {\n\t\t\tTitleFull.Text = L_DVDPlayer_TEXT;\n\t\t\tTitle.Text = L_DVDPlayer_TEXT;\n\t\t}\n\t}\n\n\tif (g_bFullScreen && !g_bActivityDeclined) \n {\n if (g_LTRReading)\n {\n xCoord = g_nButPosFull[g_nIndexTitle][0];\n }\n else\n {\n xCoord = g_ConWidth - g_nButPosFull[g_nIndexTitle][0] - TitleFull.TextWidth;\n }\n yCoord = g_nButPosFull[g_nIndexTitle][1];\n \n\t\tMFBar.SetObjectPosition(\"TitleFull\", xCoord, yCoord,\n\t\t\tTitleFull.TextWidth, g_nButPos[g_nIndexTitle][3]);\n\n\t\tMFBar.SetObjectPosition(\"Title\", xCoord, yCoord - 1000,\n\t\t\tTitle.TextWidth, g_nButPos[g_nIndexTitle][3]);\n\t}\n\telse if (!g_bFullScreen) \n {\n if (g_LTRReading)\n {\n xCoord = g_nButPos[g_nIndexTitle][0];\n }\n else\n {\n xCoord = g_ConWidth - g_nButPos[g_nIndexTitle][0] - Title.TextWidth;\n }\n yCoord = g_nButPos[g_nIndexTitle][1];\n\n\t\tMFBar.SetObjectPosition(\"Title\", xCoord, yCoord,\n\t\t\tTitle.TextWidth, g_nButPos[g_nIndexTitle][3]);\n\n\t\tMFBar.SetObjectPosition(\"TitleFull\", xCoord, yCoord - 1000,\n\t\t\tTitleFull.TextWidth, g_nButPos[g_nIndexTitle][3]);\n\t}\n\n\tUpdateDVDMessage();\n}",
"_updateTitle()\n {\n document.head.querySelector('title').innerText = `[${this._toString('HH:mm:ss')}] @amjs/working-on`;\n }",
"function saveTitle() {\n\n var id = $(\"#current-note-display\")[0].getAttribute(\"data-id\");\n var title = $(\"#current-note-title\").text();\n editNote(id=id, title=title);\n\n //Replace title of note block in notes display with new title\n var curNote = findNoteElement(id);\n if (curNote != null) {\n curNote.innerHTML = trimTitle(title, titleDisplayLen);\n }\n\n}",
"function changeTitle() {\n\t$currenttitle.text($currenttitle.text().replace(/Currently Playing:/, TitleBarDescription_Caption));\n}",
"titleUpdated(event) {\n this.lessonToUpdate.title = event.target.value;\n }",
"_updateTitle() {\n let ttl = '';\n if (this._curPage) {\n ttl = this._curPage.title();\n }\n document.title = this._rootArea.title(ttl);\n }",
"_updateTitleTab() {\n var self = this;\n super._updateTitleTab();\n if (_.isUndefined(self.m_sceneMime))\n return;\n $(Elements.BLOCK_SUBPROPERTIES_TITLE).text(self.m_config[self.m_sceneMime].tabTitle);\n }",
"function moviedescription(data, idNumber) {\n document.getElementById(\"moviedescription\").innerHTML =\n data[idNumber].fields.opening_crawl;\n document.getElementById(\"moviedirector\").innerHTML = \"Directed by: \" + data[idNumber].fields.director + \".\";\n }",
"function setupTitle() {\n var alarmRichlist = document.getElementById(\"alarm-richlist\");\n var reminders = alarmRichlist.childNodes.length;\n\n let title = PluralForm.get(reminders, calGetString(\"calendar\", \"alarmWindowTitle.label\"));\n document.title = title.replace(\"#1\", reminders);\n}",
"updatePanel() {\n document.getElementById(\"score\").innerText = this.score\n document.getElementById(\"lives\").innerText = '💖'.repeat(this.lives)\n }",
"function updateNumbering(){\n var counter = 1;\n var sortedIDs = $('#sortable_rf').sortable('toArray');\n for(var i = 0; i<sortedIDs.length; i++){\n var question = sortedIDs[i];\n if(question != \"newquestion\" && question != \"newlayout\" && question != \"\") {\n var title = $(\"#\"+question).find(\".question_headline\").find(\"b\").html();\n var number = title.substr(0, title.indexOf('.'));\n number = parseInt(number);\n if(!isNaN(number)){\n var newTitle = counter + \".\" + title.substr(title.indexOf('.')+1);\n counter++;\n $(\"#\"+question).find(\".question_headline\").find(\"b\").html(newTitle);\n }\n }\n }\n}",
"function updateDOM() {\n document.querySelector('.slash').style.display = allData[lastWatched[index]].site =='9anime'? \"none\":\"inline\"\n if (lastWatched.length > 0) {\n if(isTracking){\n isTracking=false;\n }\n toggleLoadingAnimation();\n\n // for currently airing update broadcast time\n if (lastWatched[index] in broadcastTimes)\n scheduleElement.innerHTML = broadcastTimes[lastWatched[index]]\n\n artworkElement.src = artwork[lastWatched[index]]\n document.querySelector('.sectionLabel').innerHTML = lastWatched[index] == currWatching ? \"Currently Watching\" : \"Last Watched\"\n document.getElementById('lastWatched').innerHTML = lastWatched[index]\n let episodeObj = allData[lastWatched[index]]\n document.getElementById('lastWatchedEpisode').innerHTML = episodeObj.episode\n document.getElementById('lastWatchedTime').innerHTML = episodeObj.time\n document.getElementById('lastWatchedTotalTime').innerHTML = episodeObj.totalTime\n document.getElementById('lastWatchedSite').innerHTML = episodeObj.site\n if(episodeObj.nextEpisodeLink != undefined && episodeObj.nextEpisodeLink != \"\"){\n document.getElementById('nextEpisode').style.display = \"inline-block\"\n }\n else{\n document.getElementById('nextEpisode').style.display = \"none\"\n }\n \n }\n else {\n // display help text if user is not tracking anything\n for (let e of helpText) {\n e.style.display = \"block\"\n }\n showHelp = !showHelp\n }\n\n}",
"function exerciseDetailsOne() {\r\n exerciseTitleExternal.innerHTML = ex1.innerHTML;\r\n checkExerciseTitle();\r\n scrollWin();\r\n }",
"function assignVideo(item, numVideo) {\n\t$(\"#\"+item).attr(\"data-video\",numVideo);\n\t$(\"#\"+item+\"-header\").text(videoList[numVideo].title);\n\t$(\"#\"+item+\"-pubdate\").text(videoList[numVideo].datePub);\n}",
"function updateTitleAndKmlLink() {\n\tif (netcdf) {\n\n\t\tdateForCal = '';\n\t\tdateText = '';\n\n\t\tcurrElevation = '';\n\t\tcurrElevationTxt = '';\n\n\t\t//Building elevation text.\n\t\tif (layerDetails.zaxis != undefined)\n\t\t{\n\t\t\tcurrElevation = layerDetails.zaxis.values[elev_glob_counter];\n\t\t\tunits = layerDetails.zaxis.units;\n\t\t\tcurrElevationTxt = \" \" + getZaxisText() + \" \" + currElevation + ' ' + units;\n\t\t}\n\n\t\tif (typeof calStart != 'undefined') {\n\t\t\tlocstartSel = calStart.selection.get();\n\t\t\tlocstartDate = Calendar.intToDate(locstartSel);\n\t\t\tdateText = Calendar.printDate(locstartDate, '%d-%B-%Y');\n\t\t\tdateForCal = Calendar.printDate(locstartDate, '%Y-%m-%d');\n\t\t}\n\t\tupdateKmlLink(dateForCal, currElevation, '');\n\t\tupdateTitle(dateText, currElevationTxt);\n\t}\n}",
"function changeList(){\n const sortedMovies = movieDB.movies.sort(); \n\n const promoInteractiveItems = document.querySelectorAll('.promo__interactive-item');\n for(let i = 0; i <= promoInteractiveItems.length - 1 ; i++){\n promoInteractiveItems[i].textContent = (i+1) + '. ' + sortedMovies[i];\n }\n}",
"function getSeasonOfEpisodeNumber( epsNumber ){\n\n\tif(epsNumber > 0){\n\t\tfor(var i = 0; i < dkGlobalOverviewTable.arrayOfEpisodesInSeasons.length; i++){\n\t\t\tepsNumber -= dkGlobalOverviewTable.arrayOfEpisodesInSeasons[i];\n\t\t\tif(epsNumber <= 0){\n\t\t\t\treturn i+1;\n\t\t\t}\n\t\t}\n\n\t}\n\treturn null;\n\n\n} //end ",
"function updatePlaylistDisplay(videoID, entryID, title) {\n var playlistItem = createPlaylistItem(videoID, entryID, title);\n appendPlaylist(playlistItem);\n var entry = $('#' + videoID);\n initializeDeleteButtonHandler(entry); //eslint-disable-line no-use-before-define\n}",
"function updateCountDisplays() {\n\tdocument.getElementById(\"watcherCount\").innerHTML = ((watchers == 0) ? \"No\" : watchers) + \" viewer\" + ((watchers != 1) ? \"s\" : \"\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Event for pressing on open string to toggle it closed. | function toggleStringClosed(el) {
let isChecked = el.getAttribute('data-checked')
let colNum = parseInt(el.id.split('-')[1]);
isChecked == "false" ? isChecked = "true" : isChecked = "false"
// el.innerHTML = ( isChecked == "true" ? "X" : "O");
if(isChecked == "true") {
// set X and -1 for the pressed down strings
el.innerHTML = "X";
pressedDownStrings[colNum] = -1;
}
else {
// it is currently an X and should be a O
el.innerHTML = "O";
pressedDownStrings[colNum] = 0;
}
checkIfChord();
el.setAttribute('data-checked', isChecked)
} | [
"_onOpen(ev) {\n ev.getData().set(this._tree.getOpenProperty(), true);\n }",
"function ontoggle() {\n selected = !selected;\n logic.ontoggle(selected);\n }",
"function open() {\n\n this.classList.toggle(\"open\");\n }",
"function toggle_button(event_target) {\r\n\tvar event_target_aria_pressed = event_target.getAttribute(\"aria-pressed\");\r\n\tdocument.getElementById(\"introduction\").innerHTML += \"c \" + event_target.getAttribute(\"aria-pressed\");\r\n\tif (!event_target_aria_pressed) { //if false\r\n\t\tevent_target_aria_pressed = true;\r\n\t} else {\r\n\t\tevent_target_aria_pressed = false;\r\n\t}\r\n\tevent_target.setAttribute(\"aria-pressed\", event_target_aria_pressed);\r\n\tdocument.getElementById(\"introduction\").innerHTML += \" \" + event_target.getAttribute(\"aria-pressed\");\r\n}",
"listenEditorToggle() {\n const editorToggleEl = h.getEditorToggleLink();\n editorToggleEl.addEventListener('click', function () {\n editor.toggle();\n event.preventDefault();\n }, false);\n }",
"set open(state) {\n this.skeleton.open = state;\n }",
"_onClose(ev) {\n ev.getData().set(this._tree.getOpenProperty(), false);\n }",
"function toggleEvents() {\n events.style.display = events.style.display == \"none\" ? \"\" : \"none\";\n}",
"function keyToggle(key = '', state = 'down', modified = []) {\n try {\n robot.keyToggle(key, state, modified);\n } catch (err) {\n // Only on debug\n console.error(err);\n }\n}",
"function gripClick() {\n Data.Menu.Open = !Data.Menu.Open;\n setMenuPosition();\n\n if (!Data.Menu.Open && Data.Controls.Open) {\n Data.Controls.Open = false;\n setControlsPosition();\n }\n\n if (!Data.Menu.Open && Data.Edit.Open) {\n Data.Edit.Open = false;\n setEditMenuPosition();\n\n Data.Edit.LastMode = Data.Edit.Mode;\n Data.Edit.Mode = EditModes.Off;\n updateMenu();\n }\n}",
"function toggleState ( stateOff, stateOn, attrOff, attrOn, expOff, expOn ) {\n btnMenu.attr('data-state', btnMenu.attr('data-state') === stateOff ? stateOn : stateOff);\n\n btnMenu.attr('aria-label', btnMenu.attr('aria-label') === attrOff ? attrOn : attrOff);\n\n btnMenu.attr('aria-expanded', btnMenu.attr('aria-expanded') === expOff ? expOn : expOff);\n}",
"toggleKeyPress() {\r\n const style = this.class + '-pressed';\r\n this.el.classList.toggle(style);\r\n }",
"function menuEditClick() {\n Data.Edit.Open = !Data.Edit.Open;\n setEditMenuPosition();\n\n if (Data.Edit.Open) {\n if (Data.Edit.LastMode)\n Data.Edit.Mode = Data.Edit.LastMode;\n } else {\n Data.Edit.LastMode = Data.Edit.Mode;\n Data.Edit.Mode = EditModes.Off;\n }\n updateMenu();\n\n if (Data.Edit.Open && Data.Controls.Open) {\n Data.Controls.Open = false;\n setControlsPosition();\n }\n}",
"function toggleButton() {\n if(expandButton.textContent === '+'){\n expandButton.textContent = 'X';\n } else{\n expandButton.textContent = '+';\n }\n}",
"function menuTextClick() {\n Data.Edit.Mode = EditModes.Text;\n updateMenu();\n}",
"handleOpenQuote(e) {\n const test = this.state.check_opened_module();\n const value = this.props.value;\n if (test) {\n this.setState({\n showEditQuote: true,\n quote: value,\n });\n }\n }",
"toggle() {\n let editorEl = h.getEditorEl(),\n toggleEl = h.getEditorToggleEl(),\n mainNav = h.getMainNavEl();\n\n // Clear menus and load edit panel\n editor.clearMenus();\n editor.currentPost = view.currentPost;\n editor.currentPostType = view.currentPost.type;\n editor.currentMenu = 'edit';\n\n // Toggle editor and nav hidden classes\n editorEl.classList.toggle('hidden');\n toggleEl.classList.toggle('hidden');\n // Toggle whether view nav is disabled\n mainNav.classList.toggle('inactive');\n\n // Take specific actions if opening or closing editor\n if (toggleEl.classList.contains('hidden') === false) {\n // If opening editor\n var navTitleLink = h.getEditorNavTitleLink();\n editor.showEditPanel();\n navTitleLink.addEventListener('click', editor.listenSecondaryNavTitle, false);\n view.listenDisableMainNavLinks();\n } else {\n // If closing editor\n if (view.currentPost.type === 'posts') {\n router.updateHash('blog/' + view.currentPost.slug);\n } else {\n if (editor.currentPost.slug === '_new') {\n // If closing a new post editor\n router.updateHash('blog');\n router.setCurrentPost();\n } else {\n router.updateHash(view.currentPost.slug);\n }\n }\n view.listenMainNavLinksUpdatePage();\n }\n }",
"_onClick() {\n this.expanded = !this.expanded;\n\n // Dispatch an event that signals a request to expand to the\n // `<howto-accordion>` element.\n this.dispatchEvent(\n new CustomEvent('change', {\n detail: {isExpandedNow: this.expanded},\n bubbles: true,\n })\n );\n }",
"onSplitClick(event) {\n /* istanbul ignore next */\n if (this.disabled) {\n this.visible = false\n return\n }\n this.$emit(EVENT_NAME_CLICK, event)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Website select The has_website function uses dc.js to make an HTML select element based on whewther or not the customer has a website. This function is called from the makeGraphs function. | function has_website(ndx) {
var dim = ndx.dimension(dc.pluck('website'));
var group = dim.group();
dc.selectMenu("#website-selector")
.dimension(dim)
.group(group)
.order(function (a,b) { return a.value > b.value ? 1 : b.value > a.value ? -1 : 0;});
} | [
"function displayWebsitesOnCategorySelect(websites) {\n\tdeleteAllWebsites();\n\n\tif(websites.length === 0) return;\n\n\tfor(var i = 0; i<websites.length; i++){\n\t\tcreateWebsiteElement(websites[i].name,websites[i].url);\n\t}\n}",
"function makeGraphs(data) {\n \n var ndx = crossfilter(data);\n \n has_website(ndx);\n pieChart(ndx);\n barChart(ndx);\n table(ndx, 10);\n \n dc.renderAll();\n $(\".dc-select-menu\").addClass(\"custom-select\");\n\n}",
"function showLandingGraph(ndx, element, width, height) {\n var selector = document.getElementById(\"landingSelect\");\n var selectorValue = selector.options[selector.selectedIndex].value;\n\n var regionDim = ndx.dimension(dc.pluck(\"Region\"));\n var landingSelection = regionDim.group().reduceSum(dc.pluck(selectorValue));\n //Making chart responsive for table/mobile users\n var newWidth;\n var newHeight;\n //If height is larger than width it must scale differently\n if(height > width){\n newHeight = height / 2.3;\n newWidth = width / 1.05;\n } else {\n //Keeping same size for laptop and desktop\n newWidth = 800;\n newHeight = 500;\n }\n dc.barChart(element)\n .width(newWidth)\n .height(newHeight)\n .margins({ top: 10, right: 50, bottom: 100, left: 80 })\n .dimension(regionDim)\n .group(landingSelection)\n .transitionDuration(1000)\n .ordinalColors([\"#31FFAB\"])\n .x(d3.scale.ordinal())\n .xUnits(dc.units.ordinal)\n .elasticX(true)\n .elasticY(true)\n .yAxisLabel(getYAxisLabel(selectorValue))\n .yAxis().ticks(4);\n}",
"function getSelectedDomain() {\n var dName = document.getElementById(\"domainName\"); \n var selectedDomain = dName.options[dName.selectedIndex].value;\n \n return selectedDomain;\n} // end of \"getSelectedDomain\" function",
"function loadSites(values, selectAll) {\n\trequire([\"dojo/ready\", \"dijit/form/MultiSelect\", \"dijit/form/Button\", \"dojo/dom\", \"dojo/_base/window\"], function(ready, MultiSelect, Button, dom, win){\n\t\tready(function(){\n\t\t\tif (sitesMultiSelect != null) sitesMultiSelect.destroyRecursive(true);\n\t\t\tselSites = dom.byId('selectSites');\n\t\t\tselSites.innerHTML = '';\n\t\t\t$.each(values, function(i, val) {\n\t\t\t\tvar c = win.doc.createElement('option');\n\t\t\t\tif (connectionStatus[val] == 'Up') {\n\t\t\t\t\t$(c).css('color', 'green');\n\t\t\t\t} else if (connectionStatus[val] == 'Down') {\n\t\t\t\t\t$(c).css('color', 'red');\n\t\t\t\t\t$(c).attr('disabled', 'disabled');\n\t\t\t\t} else if (connectionStatus[val] == null) {\n\t\t\t\t\t$(c).css('color', 'blue');\n\t\t\t\t}\n\t\t\t\tc.innerHTML = val;\n\t\t\t\tc.value = val;\n\t\t\t\tselSites.appendChild(c);\n\t\t\t});\n\t\t\tsitesMultiSelect = new MultiSelect({ name: 'selectSites'}, selSites);\n\t\t\tsitesMultiSelect.watch('value', function () {\n\t\t\t\tloadMethods(emptyValue);\n\t\t\t\tloadLibraries(emptyValue);\n\t\t\t\tvar selValues = sitesMultiSelect.get('value');\n\t\t\t\t$('#analysisSpecifications').css('display', 'none');\n\t\t\t\t$('#statusQueryWrapperDiv').css('display', 'none');\n\t\t\t\t$('#queryDiv').css('display', 'none');\n\t\t\t\tif (selValues != null) { \n\t\t\t\t\tif (selValues.length == 1 && selValues[0] == emptySelectionString) {\n\t\t\t\t\t\tsitesMultiSelect.set('value', '');\n\t\t\t\t\t} else if (selValues.length >= 1) {\n\t\t\t\t\t\trenderAvailableLibraries();\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t});\n\t\t\tif (!selectAll) {\n\t\t\t\tsitesMultiSelect.set('value', '');\n\t\t\t} else {\n\t\t\t\tsitesMultiSelect.set('value', values);\n\t\t\t}\n\t\t\tsitesMultiSelect.startup();\n\t\t});\n\t});\n}",
"function handleDomainSelection(e) {\r\n\r\n\t$(\".nodeWord\").css(\"color\", \"\");\r\n\t$(\".relArrow\").css(\"color\", \"\");\r\n\t$(\"#chart\").empty();\r\n\tgraphPlotted = false;\r\n\r\n\t// rebuild selected node domain list\r\n\tnodeDomainLabelMap = {};\r\n\tnodeDomain = [];\r\n\tavailNodeDomain.forEach(function(domain) {\r\n\t\tvar checkedVal = $(\"input[name='\" + domain + \"']:checked\").val();\r\n\t\tif (typeof(checkedVal) != \"undefined\" && checkedVal != \"EXCLUDE\") {\r\n\t\t\tnodeDomainLabelMap[domain] = checkedVal;\r\n\t\t\tnodeDomain.push(domain);\r\n\t\t}\r\n\t});\r\n\r\n\t// rebuild selected relationship domain list\r\n\trelDomain = [];\r\n\tavailRelDomain.forEach(function(domain) {\r\n\t\tvar parts = getRelDomainParts(domain);\r\n\t\t\r\n\t\tif (nodeDomainLabelMap[parts.sourceKey] && nodeDomainLabelMap[parts.targetKey]) {\r\n\t\t\t$(\"#rel\" + domain).removeClass(\"disabled\");\r\n\t\t\t$(\"#lbl\" + domain).html(getRelHtml(nodeDomainLabelMap[parts.sourceKey], nodeDomainLabelMap[parts.targetKey], parts.type, domain));\r\n\t\t\tif ($(\"#chk\" + domain).is(\":checked\")) {\r\n\t\t\t\trelDomain.push(domain);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\t$(\"#rel\" + domain).addClass(\"disabled\");\r\n\t\t}\r\n\t});\r\n\t\r\n\t// if at least 2 node domains and 1 relationship are selected, then regenerate the plot\r\n\tif (nodeDomain.length > 1 && relDomain.length > 0) {\r\n\t\tvar args = {\r\n\t\t\tcontainerSelector: \"#chart\",\r\n\t\t\tgraph: graph,\r\n\t\t\tnodeDomain: nodeDomain,\r\n\t\t\trelationshipDomain: relDomain,\r\n\t\t\tgetNodeName: generateNodeName,\r\n\t\t\tgetNodeLabel: getNodeLabel\r\n\t\t};\r\n\t\t\r\n\t\tHivePlot.Plotter.draw(args);\r\n\r\n\t\t// color the node and relationship text according to the colors in the plot\r\n\t\tnodeDomain.forEach(function(d) {\r\n\t\t\t$(\".nodeWord.\" + d + \".\" + nodeDomainLabelMap[d]).css(\"color\", HivePlot.Plotter.getNodeColor(d));\r\n\t\t});\r\n\t\t\r\n\t\trelDomain.forEach(function(d) {\r\n\t\t\t$(\".relArrow.\" + d).css(\"color\", HivePlot.Plotter.getRelationshipColor(d));\r\n\t\t});\r\n\t\t\r\n\t\tdefaultInfo = \"Showing \" + formatNumber(HivePlot.Plotter.getRelationshipCount()) + \" links among \" + formatNumber(HivePlot.Plotter.getNodeCount()) + \" nodes.\";\r\n\t\tsetStatus(defaultInfo);\r\n\t\t\r\n\t\tgraphPlotted = true; \r\n\t}\r\n}",
"function newDeviceAvailableDom(){\n\tvar userid = userInformation[0].userId \n\tvar userinfo = userInformation[0].resourceDomain\n\tvar ctr = 0;var str = \"\";\n\tfor(var a =0; a< userinfo.length; a++){\n\t\tvar resource = userinfo[a];\n\t\tif (userinfo[a]==\"Default\"){var ctr =1;}\n\t\tstr += \"<option value='\"+resource+\"'>\"+resource+\"</option>\";\n\t}\n\tvar val = \"\"\n\tif (ctr==0){\n\t\tval += \"<option value='Default'>Default</option>\";\n\t\tval += str\n\t\t$(\"#dropdowndomain\").append(val);\n\t}else{\n\t\t$(\"#dropdowndomain\").append(str);\n\t}\n}",
"function optionChangedProduction() {\n\n // Assign dropdown menu to variable using D3 and ID for menu given in HTML\n let dropdownMenu = d3.select(\"#dropdownPro\");\n\n // Assign the value of the country dropdown menu option to a variable\n let country = dropdownMenu.property(\"value\");\n \n // Clear the already displayed country\n d3.select(\"#country\").html(\"\");\n\n // Display the selected country in the countries page using header tag h3\n d3.select(\"#country\").insert(\"h3\").text(country);\n\n\n // Display the graphs for the desired country\n displayLineGraph_Production(apiData, country);\n displayLineGraph_DomConsumption(apiData, country);\n displayLineGraph_Exports(apiData, country);\n}",
"function aSelectToStatic(selector)\n{\n $(selector).find('select').each(function() {\n if ((this.options.length == 1) && (this.options[0].selected))\n {\n $(this).after('<span class=\"a-static-select\">' + this.options[0].innerHTML + '</span>');\n $(this).hide();\n }\n });\n}",
"function show_cohort_selector(ndx) {\n dim = ndx.dimension(dc.pluck('cohort'));\n group = dim.group();\n \n dc.selectMenu(\"#cohort-selector\")\n .dimension(dim)\n .group(group);\n \n}",
"function setOptions(domains) {\n $(\"#edit-field-domain-source option\").each(function(index, obj) {\n if (jQuery.inArray(obj.value, domains) == -1 && obj.value != '_none') {\n // If the current selection is removed, reset the selection to _none.\n if ($(\"#edit-field-domain-source\").val() == obj.value) {\n $(\"#edit-field-domain-source\").val('_none');\n }\n $(\"#edit-field-domain-source option[value=\" + obj.value + \"]\").hide();\n }\n else {\n $(\"#edit-field-domain-source option[value=\" + obj.value + \"]\").show();\n // If we reselected the initial value, reset the select option.\n if (obj.value == initialOption) {\n $(\"#edit-field-domain-source\").val(obj.value);\n }\n }\n });\n }",
"function openSiteSelector() {\n\t\t\tsiteSelector.fadeIn();\n\t\t\tsiteSelectorToggle.off('click', openSiteSelector);\n\t\t}",
"function create_filter_list_select(select) {\n\t\n\t//Get the user name\n\tvar user = \"test_user\";\t\n\t\n\t//Indicates the filter_name to get (if empty, get the list of all the filter names)\n\tvar filter_name = \"\";\t\n\t\t\t\n\t//XML generation (user parameter = \"\" to get back to the list the filters of one user only)\n\tvar xml = '<xml version=\"1.0\">' +\n\t\t\t\t'<user>' + user + '</user>' +\n\t\t\t\t'<parameter>' + filter_name + '</parameter>' +\n\t\t\t\t'<user_parameter></user_parameter>' +\n\t\t\t'</xml>';\n\n\t// AJAX call (json callback, here)\n\tvar request = $.ajax({\n\t\t\t\t\t\t\ttype: \"POST\",\n\t\t\t\t\t\t\turl: \"model/reporting/get_filters.php\",\n\t\t\t\t\t\t\tdata: xml,\n\t\t\t\t\t\t\tcontentType: \"text/xml; charset=utf-8\",\n\t\t\t\t\t\t\tdataType: \"xml\",\n\t\t\t\t\t\t\tsuccess: OnSuccess,\n\t\t\t\t\t\t\terror: OnError\n\t});\n\n\t//If success, complete the select with the list of sites or display the error message\n\tfunction OnSuccess(data,status,request) {\n\n\t\tvar error = $(request.responseText).find(\"error\").text();\t\n\t\t\n\t\t// If there are no errors, complete the select field\n\t\tif (error == \"\"){\n\t\t\t//Get the number of filter to include on the list\n\t\t\tvar filters_number = $(request.responseText).find(\"filter_name\").length;\n\t\t\t\n\t\t\t//Get each filter name and insert it into an option; then, into a select\n\t\t\tfor (i = 0; i < filters_number; i++) {\n\t\t\t\tvar filter_name = $(request.responseText).find(\"filter_name\").eq(i).text()\n\t\t\t\tvar option = document.createElement(\"option\");\n\t\t\t\toption.innerHTML = filter_name;\n\t\t\t\toption.value = filter_name;\n\t\t\t\toption.id = \"pre_set_filters_option\" + i;\n\t\t\t\toption.className = \"user_filters\";\n\t\n\t\t\t\tselect.append(option);\n\t\t\t}\n\t\t}\n\t\t//Else print the error message\n\t\telse if (error !== \"\"){\n\t\t\tmessage = $(request.responseText).find(\"error\").text();\n\t\t\tDeleteMessage();\n\t\t\tCreateMessage(\"red\", message, 0.5, 3, 0.5);\n\t\t}\n\t}\n\t\n\t//Else : error\n\tfunction OnError(request, data, status) {\t\t\t\t\n\t\tmessage = \"Network problem: XHR didn't work (perhaps, incorrect URL is called).\";\n\t\tDeleteMessage();\n\t\tCreateMessage(\"red\", message, 0.5, 3, 0.5);\n\t}\n}",
"async getSite() {\n const d = await this.select(\"SiteUrl\")();\n return Site([this, d.SiteUrl]);\n }",
"function brand()\r\n{\r\n selBrand= def.options[def.selectedIndex].text;\r\n}",
"function chooseCountry() {\n let firstDropdown = document.getElementById(\"countries\")\n let countryIndex;\n let countryName;\n firstDropdown.addEventListener(\"change\", function() {\n countryName = this.value\n let countries = covidData.countries\n for (let i = 0; i < countries.length; i++) {\n let country = countries[i]\n if (country === countryName) {\n countryIndex = i\n }\n }\n if (chart) {\n chart.destroy()\n }\n createBarGraph(countryIndex)\n displayTextData(countryName, countryIndex)\n })\n}",
"function detectStore(dom) {\r\n var site_name = $(dom).find('meta[property=\"og:site_name\"]')!==undefined ? $(dom).find('meta[property=\"og:site_name\"]').attr('content') : null;\r\n if (site_name == null) {\r\n if (/Mage\\.Cookies\\.domain/.test($(dom).text())) {site_name = \"Magento\";}\r\n if (/Amazon\\.com/.test($(dom).find('.nav_last').text())) {site_name = \"Amazon\";}\r\n if ($(dom).find('link[rel^=\"shortcut\"]') && (/demandware/.test($(dom).find('link[rel^=\"shortcut\"]').attr('href')))) {site_name = \"Demandware\";}\r\n if ($(dom).find(\"input[name^=\\\"\\/atg\\/commerce\\\"]\").length>0) {site_name = \"ATGCommerce\";}\r\n }\r\n switch (site_name){\r\n case 'Walmart.com':\r\n return new WalmartParser();\r\n case 'Best Buy':\r\n return new BestBuyParser();\r\n case 'Magento':\r\n return new MagentoParser();\r\n case 'Target':\r\n return new TargetParser();\r\n case 'Amazon':\r\n return new AmazonParser();\r\n case 'Demandware':\r\n return new DemandwareParser();\r\n case 'ATGCommerce':\r\n return new ATGCommerceParser();\r\n default: //magento\r\n return null;\r\n }\r\n}",
"function getDomains() {\n var domains = new Array();\n $(\"#edit-field-domain-access :checked\").each(function(index, obj) {\n domains.push(obj.value);\n });\n setOptions(domains);\n }",
"function tryToCreateDropDown(){\r\n\tvar sel = document.getElementById('programList');\r\n\tif(sel){\r\n\t\tcreateDropDown();\r\n\t}else{//trigger a reload\r\n\t\tlocation.reload();\r\n\t}\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
TimedEvent is a base type for any entity in the trace model with a specific start and duration. | function TimedEvent(start) {
tr.model.Event.call(this);
this.start = start;
this.duration = 0;
this.cpuStart = undefined;
this.cpuDuration = undefined;
// The set of contexts this event belongs to (order is unimportant). This
// array should never be modified.
this.contexts = Object.freeze([]);
} | [
"function FlowEvent(category, id, title, colorId, start, args, opt_duration) {\n tr.model.TimedEvent.call(this, start);\n\n this.category = category || '';\n this.title = title;\n this.colorId = colorId;\n this.start = start;\n this.args = args;\n\n this.id = id;\n\n this.startSlice = undefined;\n this.endSlice = undefined;\n\n this.startStackFrame = undefined;\n this.endStackFrame = undefined;\n\n if (opt_duration !== undefined)\n this.duration = opt_duration;\n }",
"function Sample(cpu, thread, title, start, leafStackFrame,\n opt_weight, opt_args) {\n tr.model.TimedEvent.call(this, start);\n\n this.title = title;\n this.cpu = cpu;\n this.thread = thread;\n this.leafStackFrame = leafStackFrame;\n this.weight = opt_weight;\n this.args = opt_args || {};\n }",
"function DoorEventPeriod(start_event, end_event) {\n this.startEvent = start_event; \n this.endEvent = end_event;\n}",
"static _eventCheckerDurationTimeline(e) {\n let offset = e._triggerPosition - OnScroll._getYOffsetViewport(e._triggerElem);\n if (offset < 0 && e._eventState !== __EVENT_STATES__.__INITIAL__) {\n e._targetElem.setAttribute(\"style\", e._initialStyle); \n e._eventState = __EVENT_STATES__.__INITIAL__;\n \n } else if (offset > 0 && offset < e._duration) {\n for(let i = 0 ; i < e._timelineTiming.length ; i++) {\n if(offset < e._timelineTiming[i]) {\n OnScroll._playTransitionAtTimeline(e, (offset - e._timelineTiming[i-1]) / e._timelineDuration[i], i)\n break;\n }\n }\n } else if (offset > e._duration && e._eventState !== __EVENT_STATES__.__FINISHED__) {\n e._targetElem.setAttribute(\"style\", e._transformation[e._transformation.length - 1]);\n e._eventState = __EVENT_STATES__.__FINISHED__;\n }\n }",
"function EthTransDuration() {\n\tlet errPrefix = '(EthTransDuration) ';\n\t\n\tvar self = this;\n\n\t/** @property {Date|null} - The time that the transaction started execution at. */\n\tthis.startTime = null;\n\t/** @property {Date|null} - The time that the transaction ended execution at, whether\n\t* \tdue to success or failure. */\n\tthis.endTime = null;\n\t\n\t/**\n\t * This function returns the duration in milliseconds between the start and end times this\n\t * \tobject carries.\n\t *\n\t * @return {number}\n\t */\n\tthis.calcDurationInMilliseconds = function() {\n\t\tif (self.startTime == null || self.endTime == null)\n\t\t\tthrow new Error(errPrefix + 'Both the start time and end time have not been set yet.');\n\t\tif (self.startTime == null)\n\t\t\tthrow new Error(errPrefix + 'The start time has not been set yet.');\n\t\tif (self.startTime == null || self.endTime == null)\n\t\t\tthrow new Error(errPrefix + 'The end time has not been set yet.');\n\t\tif (self.startTime > self.endTime)\n\t\t\tthrow new Error(errPrefix + 'The start time is greater than the end time.');\n\t\t\t\n\t\tlet durationMS = self.endTime - self.startTime;\n\t\t\n\t\treturn durationMS;\n\t}\n}",
"function LogicNodeTime() {\n\tLogicNode.call(this);\n\tthis.wantsProcessCall = true;\n\tthis.logicInterface = LogicNodeTime.logicInterface;\n\tthis.type = 'LogicNodeTime';\n\tthis._time = 0;\n\tthis._running = true;\n}",
"stop() {\n if (!this.startTime) throw new (_exceptions().TimerNotStarted)();\n const endTime = Date.now();\n return new (_response().TimerResponse)(this.calculateElapsed(this.startTime, endTime));\n }",
"function ChildEvent(type, child) {\n _super.call(this, type);\n this._m_child = child;\n }",
"function Time (greeting, background) {\n this.greeting = greeting;\n this.background = background;\n }",
"visitTiming_point_section(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"constructor(title,days,time,duration,relative_time,relative_to,till,relative_to_till)\r\n {\r\n this.m_start = '' //moment object for start time\r\n this.title = title;\r\n this.days = days;\r\n this.time = time;\r\n this.duration = duration;\r\n this.relative_time = relative_time;\r\n this.relative_to = relative_to;\r\n this.till = till;\r\n this.relative_to_till = relative_to_till;\r\n this.type = ''; //i not put in constructor yet\r\n }",
"initStartTime() {\n if (!this.client.emitter.hasListeners(this.eventName) || !this.debug) {\n return;\n }\n this.startTime = process.hrtime();\n }",
"static __record__(timer) {\n TaskTimer.timers[timer.id] = timer;\n }",
"handleBreakStarted(event) {\n let data = {};\n this.breakStarted = true;\n this.breakId = event.breakId;\n\n data.action = event.type;\n data.id = event.breakId;\n\n // Adobe Agent specific values\n data.startTime = event.currentMediaTime;\n data.position = event.index;\n\n this.sendData(data);\n }",
"function ThreadTimeSlice(thread, schedulingState, cat,\n start, args, opt_duration) {\n Slice.call(this, cat, schedulingState,\n this.getColorForState_(schedulingState),\n start, args, opt_duration);\n this.thread = thread;\n this.schedulingState = schedulingState;\n this.cpuOnWhichThreadWasRunning = undefined;\n }",
"send(events, metrics) {\n\t\t\t// This is where we connect EmPerfSender with our persistent metrics adapter, in this case, trackPerf\n\t\t\t// is our instance of a Weppy interface\n\t\t\ttrackPerf.trackPerf({\n\t\t\t\tmodule: metrics.klass.split('.')[0].toLowerCase(),\n\t\t\t\tname: metrics.klass,\n\t\t\t\ttype: 'timer',\n\t\t\t\tvalue: metrics.duration\n\t\t\t});\n\t\t}",
"function RotatorEvent(whenstr, runtime, whatstr) {\r\n\r\n // Fix up short date and time formats\r\n if ( whenstr.length < 10 ) {\r\n var year = this.now.getYear();\r\n if ( year < 1000 ) year += 1900;\t// Nav 2&3 bug!\r\n if ( whenstr.substring(2,3) == \":\" ) {\r\n // Prepend current date to time-only format\r\n whenstr = this.now.getDate() + this.now.toString().substring(3,8) + year + \" \" + whenstr;\r\n } else {\r\n // Append current year to day-and-date format\r\n whenstr = whenstr + \" \" + year;\r\n }\r\n }\r\n\r\n // Create and check variable from event date/time format\r\n var when = new Date(whenstr);\r\n if ( when == 0 || isNaN(when) ) alert(\"Bad date: \"+whenstr);\r\n\r\n // Calcuate event duration based on units (hours, days, weeks)\r\n var unit = units[runtime.substring(runtime.length-1)];\r\n if ( typeof(unit) == \"undefined\" ) alert(\"Bad duration: \"+runtime);\r\n var len = runtime.substring(0,runtime.length-1) * unit;\r\n\r\n // See if this event is currently active\r\n if ( this.now.getTime() < when.getTime() ) return; // hasn't started yet\r\n if ( when.getTime()+len < this.now.getTime() ) return; // already finished\r\n\r\n // Event is active, assign its text string to the object\r\n this.content = whatstr;\r\n}",
"function MusicTimeSignatureInputComponent() {\n this.type = 'timeSignature';\n }",
"function normaliseEvent(evt) {\n var duration = {};\n\n if (!evt.dtend) {\n if (evt.duration) {\n duration.original = evt.duration;\n duration.minutes = evt.duration.match(/^PT(\\d+)M$/)[1];\n evt.dtend = new Date();\n evt.dtend.setTime(\n evt.dtstart.getTime() + duration.minutes * 60000);\n } else {\n evt.dtend = evt.dtstart;\n duration.minutes = 0;\n }\n } else {\n duration.minutes = (evt.dtend.getTime() - evt.dtstart.getTime());\n duration.minutes /= 60000;\n }\n\n if (duration.minutes >= 60) {\n duration.hours = Math.floor(duration.minutes / 60);\n duration.minutes -= duration.hours * 60;\n } else {\n duration.hours = 0;\n }\n\n duration.str = pad(duration.hours) + pad(duration.minutes);\n evt.duration = duration;\n\n evt.dtstart.iso8601 = iso8601(evt.dtstart);\n evt.dtend.iso8601 = iso8601(evt.dtend);\n }",
"emitQueryEvent(error) {\n if (!this.startTime) {\n return;\n }\n const eventData = { duration: process.hrtime(this.startTime), ...this.data, error };\n this.client.emitter.emit(this.eventName, eventData);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
START/STOP/PAUSE Bind start/stop/pause events from the clock and emit them. | _bindClockEvents() {
this._clock.on("start", (time, offset) => {
offset = new _Ticks.TicksClass(this.context, offset).toSeconds();
this.emit("start", time, offset);
});
this._clock.on("stop", time => {
this.emit("stop", time);
});
this._clock.on("pause", time => {
this.emit("pause", time);
});
} | [
"function playbackEvents () {\n\n\t\tvar play = document.getElementById('play');\n\t\tvar overlayPlay = document.getElementById('overlay-play');\n\t\tvar pause = document.getElementById('pause');\n\t\tvar overlayPause = document.getElementById('overlay-pause');\n\t\tvar previous = document.getElementById('previous');\n\t\tvar next = document.getElementById('next');\n\n\t\tplay.addEventListener('click', emitEvent('play'));\n\t\toverlayPlay.addEventListener('click', emitEvent('play'));\n\t\tpause.addEventListener('click', emitEvent('pause'));\n\t\toverlayPause.addEventListener('click', emitEvent('pause'));\n\t\tprevious.addEventListener('click', emitEvent('previous'));\n\t\tnext.addEventListener('click', emitEvent('next'));\n\n\t}",
"startClock() {\r\n // Every millisecond, perform one cpu cycle\r\n this.clock = setInterval(() => this.tick(), 1); // 1 ms delay == 1 KHz clock == 0.000001 GHz\r\n\r\n // Fire interrupt timer at a cycle of once per second\r\n this.interrupt = setInterval(() => this.reg[IS] |= 1, 1000); // every second, set the bit 0 of IS to 1\r\n }",
"processStartButton() {\n\t\tclearTimeout(this.timer);\n\t\tthis.timer = null;\n\t\tthis.game.switchScreens('play');\n\t}",
"start() {\n if (!this.stop) return\n this.stop = false\n this.__poll()\n }",
"async sendStartSignal() {\n console.log(\"Sending instructions to teams.\");\n let instructions = this.getInstructions();\n await this.sendMessageToAllTeams(instructions);\n console.log(\"Game started: instructions sent to all teams.\");\n let teamsArray = this.getTeamsAsArray();\n await Util.asyncForEach(teamsArray, async team => {\n console.log(`Startlocatie van team ${team.name}: ${team.game.startLocation}.`);\n let teamPlayers = nconf.get(`teams:${team.channelId}:players`);\n await Util.sendToChannel(team.channelId, `**Jullie team bestaat uit de volgende personen: ${teamPlayers}.**`);\n });\n await Util.asyncForEach(teamsArray, async team => {\n console.log(`Startlocatie van team ${team.name}: ${team.game.startLocation}.`);\n let startLocationDescription = team.game.startLocation.describeAsStartLocationText();\n team.game.readyForNextGame = false;\n await Util.sendToChannel(team.channelId, startLocationDescription);\n });\n console.log(\"Start location sent to all teams.\");\n }",
"start(){\n\t\t// Run immediately to avoid having to wait for the first timeout\n\t\tthis.onUpdate();\n\n\t\tvar updater = this.onUpdate.bind(this);\n\t\tthis.interval = setInterval(updater, this.updateInterval);\n\t}",
"start() {\n if (!this.eb) {\n this.eb = new EventBus(this.busUrl);\n this.eb.onopen = function() {\n simulatorVerticle.eb.registerHandler(CALLSIGN_FLASH,simulatorVerticle.heartBeatHandler);\n simulatorVerticle.eb.registerHandler(CALLSIGN_BO,simulatorVerticle.carMessageHandler)\n };\n };\n this.enabled=true;\n }",
"pulse_midi_clock() {\n this.midi_clock.send([0xf8]);\n }",
"start(){\n this.recording = true ;\n }",
"play(startTime, endTime) {\n let { remote, fullScreen, playing } = this.props\n let { vc } = this\n log(`play startTime=${startTime}, endTime=${endTime}, playing=${playing}`)\n\n if (playing) { \n log('play - stop before restarting play')\n this.stop() \n }\n\n if (!isNaN(startTime)) {\n vc.currentTime = startTime\n }\n\n if (fullScreen) this.requestFullScreen()\n\n this.endTime = endTime\n\n let { playbackRate } = remote\n vc.playbackRate = playbackRate || 1.0\n\n this.startupdater()\n remote.playing = true\n //console.log('play!!!')\n this.vc.play()\n }",
"initStartTime() {\n if (!this.client.emitter.hasListeners(this.eventName) || !this.debug) {\n return;\n }\n this.startTime = process.hrtime();\n }",
"handleGameStartEvent() {\n \n }",
"send(events, metrics) {\n\t\t\t// This is where we connect EmPerfSender with our persistent metrics adapter, in this case, trackPerf\n\t\t\t// is our instance of a Weppy interface\n\t\t\ttrackPerf.trackPerf({\n\t\t\t\tmodule: metrics.klass.split('.')[0].toLowerCase(),\n\t\t\t\tname: metrics.klass,\n\t\t\t\ttype: 'timer',\n\t\t\t\tvalue: metrics.duration\n\t\t\t});\n\t\t}",
"toggle() {\n if (this._simulation.started)\n this.stop();\n else\n this.start();\n }",
"function privateInitializeEventHandlers(){\n\t\t/*\n\t\t\tOn time update for the audio element, update visual displays that\n\t\t\trepresent the time on either a visualized element or time display.\n\t\t*/\n\t\tconfig.active_song.addEventListener('timeupdate', privateUpdateTime );\n\n\t\t/*\n\t\t\tWhen the audio element has ended playing, we handle the song\n\t\t\tending. In a single song or multiple modular song instance,\n\t\t\tthis just synchronizes the visuals for time and song time\n\t\t\tvisualization, but for a playlist it determines whether\n\t\t\tit should play the next song or not.\n\t\t*/\n\t\tconfig.active_song.addEventListener('ended', privateHandleSongEnded );\n\n\t\t/*\n\t\t\tBinds handlers for play classes\n\t\t*/\n\t\tvar play_classes = document.getElementsByClassName(\"amplitude-play\");\n\n\t\tfor( var i = 0; i < play_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tplay_classes[i].addEventListener('touchstart', privatePlayClickHandle );\n\t\t\t}else{\n\t\t\t\tplay_classes[i].addEventListener('click', privatePlayClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for pause classes\n\t\t*/\n\t\tvar pause_classes = document.getElementsByClassName(\"amplitude-pause\");\n\n\t\tfor( var i = 0; i < pause_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tpause_classes[i].addEventListener('touchstart', privatePauseClickHandle );\n\t\t\t}else{\n\t\t\t\tpause_classes[i].addEventListener('click', privatePauseClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for stop classes\n\t\t*/\n\t\tvar stop_classes = document.getElementsByClassName(\"amplitude-stop\");\n\n\t\tfor( var i = 0; i < stop_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tstop_classes[i].addEventListener('touchstart', privateStopClickHandle );\n\t\t\t}else{\n\t\t\t\tstop_classes[i].addEventListener('click', privateStopClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for play/pause classes\n\t\t*/\n\t\tvar play_pause_classes = document.getElementsByClassName(\"amplitude-play-pause\");\n\n\t\tfor( var i = 0; i < play_pause_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tplay_pause_classes[i].addEventListener('touchstart', privatePlayPauseClickHandle );\n\t\t\t}else{\n\t\t\t\tplay_pause_classes[i].addEventListener('click', privatePlayPauseClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for mute classes\n\n\t\t\tWARNING: If iOS, we don't do anything because iOS does not allow the\n\t\t\tvolume to be adjusted through anything except the buttons on the side of\n\t\t\tthe device.\n\t\t*/\n\t\tvar mute_classes = document.getElementsByClassName(\"amplitude-mute\");\n\n\t\tfor( var i = 0; i < mute_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\t/*\n\t\t\t\t\tChecks for an iOS device and displays an error message if debugging\n\t\t\t\t\tis turned on.\n\t\t\t\t*/\n\t\t\t\tif( /iPhone|iPad|iPod/i.test(navigator.userAgent) ) {\n\t\t\t\t\tprivateWriteDebugMessage( 'iOS does NOT allow volume to be set through javascript: https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW4' );\n\t\t\t\t}else{\n\t\t\t\t\tmute_classes[i].addEventListener('touchstart', privateMuteClickHandle );\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tmute_classes[i].addEventListener('click', privateMuteClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for volume up classes\n\n\t\t\tWARNING: If iOS, we don't do anything because iOS does not allow the\n\t\t\tvolume to be adjusted through anything except the buttons on the side of\n\t\t\tthe device.\n\t\t*/\n\t\tvar volume_up_classes = document.getElementsByClassName(\"amplitude-volume-up\");\n\n\t\tfor( var i = 0; i < volume_up_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\t/*\n\t\t\t\t\tChecks for an iOS device and displays an error message if debugging\n\t\t\t\t\tis turned on.\n\t\t\t\t*/\n\t\t\t\tif( /iPhone|iPad|iPod/i.test(navigator.userAgent) ) {\n\t\t\t\t\tprivateWriteDebugMessage( 'iOS does NOT allow volume to be set through javascript: https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW4' );\n\t\t\t\t}else{\n\t\t\t\t\tvolume_up_classes[i].addEventListener('touchstart', privateVolumeUpClickHandle );\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tvolume_up_classes[i].addEventListener('click', privateVolumeUpClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for volume down classes\n\n\t\t\tWARNING: If iOS, we don't do anything because iOS does not allow the\n\t\t\tvolume to be adjusted through anything except the buttons on the side of\n\t\t\tthe device.\n\t\t*/\n\t\tvar volume_down_classes = document.getElementsByClassName(\"amplitude-volume-down\");\n\t\t\n\t\tfor( var i = 0; i < volume_down_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\t/*\n\t\t\t\t\tChecks for an iOS device and displays an error message if debugging\n\t\t\t\t\tis turned on.\n\t\t\t\t*/\n\t\t\t\tif( /iPhone|iPad|iPod/i.test(navigator.userAgent) ) {\n\t\t\t\t\tprivateWriteDebugMessage( 'iOS does NOT allow volume to be set through javascript: https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW4' );\n\t\t\t\t}else{\n\t\t\t\t\tvolume_down_classes[i].addEventListener('touchstart', privateVolumeDownClickHandle );\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tvolume_down_classes[i].addEventListener('click', privateVolumeDownClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for song slider classes. The song sliders are HTML 5 \n\t\t\tRange Elements. This event fires everytime a slider has changed.\n\t\t*/\n\t\tvar song_sliders = document.getElementsByClassName(\"amplitude-song-slider\");\n\n\t\tfor( var i = 0; i < song_sliders.length; i++ ){\n\t\t\tsong_sliders[i].addEventListener('input', privateSongStatusBarInputHandle );\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for volume slider classes. The volume sliders are HTML 5\n\t\t\tRange Elements. This event fires everytime a slider has changed.\n\n\t\t\tWARNING: If iOS, we don't do anything because iOS does not allow the\n\t\t\tvolume to be adjusted through anything except the buttons on the side of\n\t\t\tthe device.\n\t\t*/\n\t\tvar volume_sliders = document.getElementsByClassName(\"amplitude-volume-slider\");\n\n\t\tfor( var i = 0; i < volume_sliders.length; i++ ){\n\t\t\t/*\n\t\t\t\tChecks for an iOS device and displays an error message if debugging\n\t\t\t\tis turned on.\n\t\t\t*/\n\t\t\tif( /iPhone|iPad|iPod/i.test(navigator.userAgent) ) {\n\t\t\t\tprivateWriteDebugMessage( 'iOS does NOT allow volume to be set through javascript: https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW4' );\n\t\t\t}else{\n\t\t\t\tvolume_sliders[i].addEventListener('input', privateVolumeInputHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for next button classes.\n\t\t*/\n\t\tvar next_classes = document.getElementsByClassName(\"amplitude-next\");\n\n\t\tfor( var i = 0; i < next_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tnext_classes[i].addEventListener('touchstart', privateNextClickHandle );\n\t\t\t}else{\n\t\t\t\tnext_classes[i].addEventListener('click', privateNextClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for previous button classes.\n\t\t*/\n\t\tvar prev_classes = document.getElementsByClassName(\"amplitude-prev\");\n\n\t\tfor( var i = 0; i < prev_classes.length; i++ ){\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tprev_classes[i].addEventListener('touchstart', privatePrevClickHandle );\n\t\t\t}else{\n\t\t\t\tprev_classes[i].addEventListener('click', privatePrevClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for shuffle button classes.\n\t\t*/\n\t\tvar shuffle_classes = document.getElementsByClassName(\"amplitude-shuffle\");\n\n\t\tfor( var i = 0; i < shuffle_classes.length; i++ ){\n\t\t\tshuffle_classes[i].classList.remove('amplitude-shuffle-on');\n\t\t\tshuffle_classes[i].classList.add('amplitude-shuffle-off');\n\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\tshuffle_classes[i].addEventListener('touchstart', privateShuffleClickHandle );\n\t\t\t}else{\n\t\t\t\tshuffle_classes[i].addEventListener('click', privateShuffleClickHandle );\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tBinds handlers for repeat button classes.\n\t\t*/\n\t\tvar repeat_classes = document.getElementsByClassName(\"amplitude-repeat\");\n\n\t\tfor( var i = 0; i < repeat_classes.length; i++ ){\n\t\t\trepeat_classes[i].classList.remove('amplitude-repeat-on');\n\t\t\trepeat_classes[i].classList.add('amplitude-repeat-off');\n\n\t\t\tif( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n\t\t\t\trepeat_classes[i].addEventListener('touchstart', privateRepeatClickHandle );\n\t\t\t}else{\n\t\t\t\trepeat_classes[i].addEventListener('click', privateRepeatClickHandle );\n\t\t\t}\n\t\t}\n\t}",
"runClock() {\n throw ( \"Override this function\" );\n }",
"function start() {\n dbg('start (schedule)');\n wait = $timeout(startAnim, waitDelay);\n }",
"stop_midi_clock() {\n this.midi_clock.send([0xfc]);\n }",
"function updateClock(){\n document.getElementById(\"app\").innerHTML = currentTime();\n\n updateStopWatches();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
si se usa este evento en otro js, borrar este y ejecutar la funcion loadUser() dentro de la otra funcion | function loadUser() {
makeHTTPRequest(`/usuarios/0`, 'GET', '', cbOk1);
} | [
"function loadUser() {\n console.log(\"loadUser() started\");\n showMessage(\"Loading the currently logged in user ...\");\n osapi.jive.core.users.get({\n id : '@viewer'\n }).execute(function(response) {\n console.log(\"loadUser() response = \" + JSON.stringify(response));\n user = response.data;\n $(\".user-name\").html(user.name);\n loadUsers();\n });\n}",
"loadUserSession() {\n const storedUserSession = localStorage.getItem('userSession');\n const userSession = storedUserSession\n ? UserSession.deserialize(storedUserSession)\n : null;\n\n this.userSession = userSession;\n this.resetRenewalTimer(userSession);\n this.emit('user-session-changed', userSession);\n }",
"function userOnload(){\n checkLoginAndSetUp(); \n sidebar();\n fetchOUs();\n}",
"function loadUsers() {\n var loadedUsers = JSON.parse(localStorage.getItem(\"trivia-users\"));\n\n if (loadedUsers) {\n users = loadedUsers;\n }\n}",
"function _loadUsers()\n {\n var sql = \"select * from Users where 1\"\n db.all(sql, function(err, rows)\n {\n if(rows)\n {\n rows.map(function(row)\n {\n var user = new User(db, row)\n Users[row.userId] = user\n })\n }\n })\n }",
"function loadName() {\n const currentUser = localStorage.getItem(USER_LS);\n if (currentUser === null) {\n askForName();\n } else {\n paintGreeting(currentUser);\n }\n}",
"async loadSearchedUser() {\n const currentUserId = await AsyncStorage.getItem('searchID');\n const formattedUserId = await JSON.parse(currentUserId);\n this.setState({\n userID: formattedUserId,\n });\n this.getProfile();\n console.log(\n 'Loaded logged credentials of the user, user ID: ' +\n this.state.userID +\n ' and x-Auth: ' +\n this.state.xAuth,\n );\n }",
"async loadUser(username) {\n return this.UserModel.findOne({ username });\n }",
"async function loadUserById(req, res, next) {\n let userId = req.params.id;\n let query = \"\";\n if (typeof req.query.username !== 'undefined') {\n let queryId = User.find().where('username', userId);\n await queryId.exec(function (err, id) {\n if (err) {\n next(err);\n }\n userId = id[0]._id;\n req.params.id = userId;\n query = User.findById(userId);\n query.exec(function (err, user) {\n if (err) {\n next(err);\n } else if (!user) {\n return userNotFound(res, userId);\n }\n req.user = user;\n console.log('loadUserById :' + req.user);\n next();\n });\n })\n } else if (!ObjectId.isValid(userId)) {\n return userNotFound(res, userId);\n } else {\n query = User.findById(userId);\n query.exec(function (err, user) {\n if (err) {\n next(err);\n } else if (!user) {\n return userNotFound(res, userId);\n }\n req.user = user;\n console.log('loadUserById :' + req.user);\n next();\n });\n }\n}",
"function loadUsersByCompanyId(companyId) {\n var queryString = \"companyId=\" + companyId;\n clearUserDD();\n if (companyId !== \"\") {\n $.ajax({\n type: \"GET\",\n url: \"emulation/users\",\n data: queryString,\n dataType: \"json\",\n beforeSend: function() {\n $.blockUI({\n message: '<div><img src=\"' + globalBaseURL + '/static/positivepay/images/ajax/ajax-loader.gif\"/>Loading users for the selected company...</div>',\n blockMsgClass: 'alert',\n css: {padding: '10px', color: '#000', border: '1px solid #006B87', 'border-radius': '5px', '-moz-border-radius': '5px', '-webkit-border-radius': '5px'}\n });\n },\n complete: function() {\n \t$.unblockUI();\n },\n success: function(userListJson) {\n \tsortByName(userListJson,\"name\");\n if (userListJson.length > 0) {\n $('#userName').find('option').remove();\n $('#userName').append($(\"<option value=''>Now select a user...</option>\"));\n $.each(userListJson, function(index, value) {\n $('#userName').append($('<option>', {\n value: value.userName,\n text: value.userName\n }));\n });\n $('#userName').notify(\"Users populated.\", \"success\");\n } else {\n \t$('#userName').notify(\"No user found\", \"warn\");\n }\n },\n error: function() {\n \t$('#userName').notify(\"Error Populating Users.\", \"error\");\n }\n });\n }\n}",
"load() {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n if (this.session.isAuthenticated) {\n let user = await this.store.queryRecord('user', { me: true });\n this.set('user', user);\n resolve(user);\n } else {\n reject(new Error('User not authenticated.'));\n }\n });\n }",
"function init() {\n var storedUsers = JSON.parse(localStorage.getItem(\"Users\"));\n if (storedUsers !== null) {\n users = storedUsers;\n //renderUsers();\n }\n}",
"function loadUserProfile(targetUserData) {\n console.log(targetUserData);\n name.text(targetUserData.name);\n name.attr('style', 'color: black;')\n age.text(targetUserData.age);\n gender.text(targetUserData.gender);\n joined.text(targetUserData.joined);\n hikes.text(targetUserData.hikes);\n rep.text(targetUserData.rep);\n addBadge(targetUserData);\n bio.text(targetUserData.bio);\n bio.attr('style', \"color: black;\")\n addTags(targetUserData);\n emptyLinks(targetUserData);\n}",
"onUsuarioSelecionado (callback) {\r\n this.$on('usuarioSelecionado', callback)\r\n }",
"function initializeUserIfNeeded(uid) {\n}",
"function loadUsers() {\n if( !userList ) {\n userList = new $.bb.lists.Users();\n }\n return userList;\n }",
"function activate() {\n user.registerCb(function(){\n routes.fetch(user.getUser().username)\n .then(function() {});\n });\n\n }",
"function loadFromUserType() {\n console.log(\"UserService: Loading additional information for user type: %s\", userType);\n\n factory.isCompany = function () {\n return userType === \"Company\";\n };\n\n factory.isStudent = function () {\n return userType === \"Student\";\n };\n\n factory.isAdmin = function () {\n return userType === \"Admin\";\n };\n\n if (userType === \"Student\") {\n // Then, this user must be in the student list as well\n var studentList = clientContext.get_web().get_lists().getByTitle(\"StudentList\");\n var camlQuery = new SP.CamlQuery();\n var query = \"<View><Query><Where>\" +\n \"<Eq><FieldRef Name='Email' /><Value Type='Text'>\" + factory.user.email + \"</Value></Eq>\" +\n \"</Where></Query></View>\";\n camlQuery.set_viewXml(query);\n var entries = studentList.getItems(camlQuery);\n\n clientContext.load(entries);\n clientContext.executeQueryAsync(function () {\n console.log(\"UserService: Additional user information loaded from student list\");\n var enumerator = entries.getEnumerator();\n if (!enumerator.moveNext()) {\n // not a student\n console.log(\"UserService: User is not a student\");\n factory.isStudent = function () {\n return false;\n };\n\n userType = null;\n } else {\n factory.user.name = enumerator.get_current().get_item(\"FullName\");\n }\n\n factory.userLoaded = true;\n\n }, onError);\n\n } else if (userType === \"Company\") {\n // Then, this user must be in the student list as well\n var companyList = clientContext.get_web().get_lists().getByTitle(\"CompanyList\");\n var camlQuery = new SP.CamlQuery();\n var query = \"<View><Query><Where>\" +\n \"<Eq><FieldRef Name='Email' /><Value Type='Text'>\" + factory.user.email + \"</Value></Eq>\" +\n \"</Where></Query></View>\";\n camlQuery.set_viewXml(query);\n var entries = companyList.getItems(camlQuery);\n\n clientContext.load(entries);\n clientContext.executeQueryAsync(function () {\n console.log(\"UserService: Additional company information loaded from company list\");\n var enumerator = entries.getEnumerator();\n if (!enumerator.moveNext()) {\n // not a company\n console.log(\"UserService: User is not a Company\");\n factory.isCompany = function () {\n return false;\n };\n\n userType = null;\n } else {\n factory.user.company = enumerator.get_current().get_item(\"Company\");\n }\n\n factory.userLoaded = true;\n }, onError);\n } else {\n factory.userLoaded = true;\n }\n }",
"function loadLogInOffMessages(){\r\n //load settings\r\n logInOffMessages = settings.get('LogInOffMessages',false);\r\n \r\n //add the command\r\n commands.set('addOnSettings',\"LogInOffMessages\",toggleLogInOffMessages);\r\n \r\n // Overwriting Adduser\r\n var oldAddUser = unsafeWindow.addUser,\r\n oldRemoveUser = unsafeWindow.removeUser;\r\n\r\n unsafeWindow.addUser = function(user, css, sort) {\r\n // Only if blackname or mod\r\n if (user.loggedin && logInOffMessages){\r\n unsafeWindow.addMessage('', user.username + ' logged on.', '','hashtext'); \r\n if (user.username === 'JustPassingBy'){\r\n unsafeWindow.addMessage('','Wish him a happy birthday !', '', 'hastext');\r\n }\r\n }\r\n oldAddUser(user,css,sort);\r\n };\r\n\r\n // Overwriting removeUser\r\n\r\n unsafeWindow.removeUser = function(id) {\r\n var user = unsafeWindow.users[getIndexOfUser(id)];\r\n if (user.loggedin && logInOffMessages){\r\n unsafeWindow.addMessage('',user.username + ' logged off.', '','hashtext');\r\n }\r\n oldRemoveUser(id);\r\n };\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Global ToneDen configuration function. | function configure(parameters) {
_merge(ToneDen.parameters, parameters);
} | [
"setDefaultToneType(type) {\r\n this.out(\"Setting Tone Type: \" + type);\r\n if (type == Piano2.OSC_SINE || type == Piano2.OSC_TRIANGLE || type == Piano2.OSC_SAWTOOTH || type == Piano2.OSC_SQUARE) {\r\n this.toneType = type;\r\n } else { //Assume Int Index\r\n type = Math.abs(parseInt(type)) % Piano2.OSC_TYPES.length; //Force valid index\r\n this.out(\"Tone Index Parsed: \" + type);\r\n this.toneType = Piano2.OSC_TYPES[type];\r\n }\r\n }",
"constructor () {\r\n this.context = new AudioContext(); //AudioContext for Oscillators to generate tones\r\n this.debug = false;\r\n this.duration = Piano2.DEFAULT_DURATION;\r\n this.toneType = Piano2.DEFAULT_TONE;\r\n }",
"set OverrideSampleRate(value) {}",
"_initAudioParams() {\n this.pan = this.audioComponents.channelStrip.pan;\n this.gain = this.audioComponents.channelStrip.outputGain;\n // TODO: can also expose frequency as frequency of first overtone?\n }",
"getSkinTone(){\n\t\treturn this.dataArray[4];\n\t}",
"set OptimizeSampleRate(value) {}",
"function scalePlayer(unit, scale, direction, tempo) {\n\n\n// overwrite players interval variables with toneIndex values for scale type\n\n// if statement for reversing intervalic direction\n\n if (direction === \"up\"){\n\n first = unit[0];\n second = unit[1];\n third = unit[2];\n fourth = unit[3];\n fifth = unit[4];\n sixth = unit[5];\n seventh = unit[6];\n octave = unit[7];\n } else if (direction === \"down\"){\n first = unit[7];\n second = unit[6];\n third = unit[5];\n fourth = unit[4];\n fifth = unit[3];\n sixth = unit[2];\n seventh = unit[1];\n octave = unit[0];\n }\n\n // keySelector value brought in as 'scale' -- modifies oscillator.detune via 'detune'\n\n if (scale === \"B\") {\n var detune = 100;\n } else if (scale === \"A#/Bb\"){\n var detune = 200;\n } else if (scale === \"A\"){\n var detune = 300;\n } else if (scale === \"G#/Ab\"){\n var detune = 400;\n } else if (scale === \"G\"){\n var detune = 500;\n } else if (scale === \"F#/Gb\"){\n var detune = 600;\n } else if (scale === \"F\"){\n var detune = 700;\n } else if (scale === \"E\"){\n var detune = 800;\n } else if (scale === \"D#/Eb\"){\n var detune = 900;\n } else if (scale === \"D\"){\n var detune = 1000;\n } else if (scale === \"C#/Db\"){\n var detune = 1100;\n } else {\n var detune = 0;\n }\n\n// if statement makes sure ALL needed variables are in-function before allowing the synth to instantiate and trigger\n\n if ((unit !== undefined) && (scale !== undefined) && (direction !== undefined)){\n\n// initializes WebAudio API\n console.log(tempo);\n\n var oscillator = context.createOscillator();\n var gain = context.createGain();\n gain.value = .5\n\n oscillator.type = 'sine';\n\n oscillator.detune.value = detune;\n\n var quarterNoteTime = 60/tempo;\n\n var startTime = 1\n\n oscillator.frequency.setValueAtTime(first, startTime)\n oscillator.frequency.setValueAtTime(second, startTime + quarterNoteTime)\n oscillator.frequency.setValueAtTime(third, startTime + 2*quarterNoteTime)\n oscillator.frequency.setValueAtTime(fourth, startTime+ 3*quarterNoteTime)\n oscillator.frequency.setValueAtTime(fifth, startTime+ 4*quarterNoteTime)\n oscillator.frequency.setValueAtTime(sixth, startTime+ 5*quarterNoteTime)\n oscillator.frequency.setValueAtTime(seventh, startTime+ 6*quarterNoteTime)\n oscillator.frequency.setValueAtTime(octave, startTime+ 7*quarterNoteTime)\n\n//\n\n oscillator.connect(gain)\n gain.connect(context.destination)\n\n oscillator.start(startTime)\n gain.gain.linearRampToValueAtTime(0, startTime+ 8*quarterNoteTime + 1)\n oscillator.stop(startTime + 8*quarterNoteTime + 2)\n\n }\n}",
"set PreserveSampleRate(value) {}",
"get options$noise()\r\n\t{\r\n\t\treturn _.cloneDeep( this._options.noise );\r\n\t}",
"function thermometer(ctx,x,y,w,h,value,min,max,text) {\n ctx.save();\n // compute scale factor for entire ifc\n var scale = Math.min(w,h) / 10;\n // write the temperature value\n var fs = 3.25 * scale;\n ctx.font = fs+\"px sans-serif\";\n ctx.textAlign = \"center\";\n ctx.fillText(value+text,x+(w/2),y+h-2);\n // set up our coordinate transform\n ctx.translate(x+(w/2),y+(h/2));\n ctx.scale(scale,scale);\n ctx.translate(0,-1);\n ctx.lineWidth = 1.5/scale;\n // build the thermometer shape\n ctx.beginPath();\n ctx.moveTo(-1,3);\n ctx.lineTo(-1,-5);\n ctx.arc(0,-5,1,0-Math.PI,0,false);\n ctx.lineTo(1,3);\n ctx.arc(0,4.5,2,0-(Math.PI/3),Math.PI*1.33,false);\n // stroke the thermometer shape\n ctx.stroke();\n // clip to the thermometer shape\n ctx.clip();\n // fill the thermometer with red\n ctx.fillStyle = \"red\";\n // draw mercury\n var normalizedValue = (value - min) / (max - min);\n ctx.fillRect(-2,6.5,4,-4-(normalizedValue/0.12));\n // restroke to get the interior of the outline\n ctx.stroke();\n //\n ctx.restore();\n}",
"_calculateLedProperties() {\n\t\t// no need for this if in discrete frequencies or area fill modes\n\t\tif ( this._mode % 10 == 0 || ! this._initDone )\n\t\t\treturn;\n\n\t\tconst analyzerHeight = this._lumiBars ? this._canvas.height : this._canvas.height * ( 1 - this._reflexRatio ) | 0;\n\n\t\tlet spaceV = Math.min( 6, analyzerHeight / ( 90 * this._pixelRatio ) | 0 ); // for modes 3, 4, 5 and 6\n\t\tlet nLeds;\n\n\t\tswitch ( this._mode ) {\n\t\t\tcase 8:\n\t\t\t\tspaceV = Math.min( 16, analyzerHeight / ( 33 * this._pixelRatio ) | 0 );\n\t\t\t\tnLeds = 24;\n\t\t\t\tbreak;\n\t\t\tcase 7:\n\t\t\t\tspaceV = Math.min( 8, analyzerHeight / ( 67 * this._pixelRatio ) | 0 );\n\t\t\t\tnLeds = 48;\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\tnLeds = 64;\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\t// fall through\n\t\t\tcase 4:\n\t\t\t\tnLeds = 80;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tnLeds = 96;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tspaceV = Math.min( 4, analyzerHeight / ( 135 * this._pixelRatio ) | 0 );\n\t\t\t\tnLeds = 128;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tspaceV = Math.min( 3, Math.max( 2, analyzerHeight / ( 180 * this._pixelRatio ) | 0 ) );\n\t\t\t\tnLeds = 128;\n\t\t}\n\n\t\tspaceV *= this._pixelRatio;\n\t\tnLeds = Math.min( nLeds, ( analyzerHeight + spaceV ) / ( spaceV * 2 ) | 0 );\n\n\t\tthis._ledOptions = {\n\t\t\tnLeds,\n\t\t\tspaceH: this._barWidth * ( this._mode == 1 ? .45 : this._mode < 5 ? .225 : .125 ),\n\t\t\tspaceV,\n\t\t\tledHeight: ( analyzerHeight + spaceV ) / nLeds - spaceV\n\t\t};\n\t}",
"function texttoMusic(string) {\n \n //There are three different synths users can choose.\n switch (selectedSound) {\n case 1:\n var synth = new Tone.SimpleSynth().fan(waveform).toMaster();\n break;\n\n case 2:\n var synth = new Tone.MonoSynth().fan(waveform).toMaster();\n break;\n\n case 3:\n var synth = new Tone.SimpleFM().fan(waveform).toMaster();\n break;\n }\n \n //Generates a waveform to add to the novelty.\n //If a waveform already exists this skips creation.\n if(waveContext == 0) {\n //the waveform HTML generation.\n waveContext = $(\"<canvas>\", {\n \"id\" : \"waveform\"\n }).appendTo(\"#soundgroup\").get(0).getContext(\"2d\");\n }\n\t\n var waveformGradient;\n\n //Analyses and draws the waveform based on incoming data from the synth\n function drawWaveform(values){\n //draw the waveform\n waveContext.clearRect(0, 0, canvasWidth, canvasHeight);\n var values = waveform.analyse();\n\t\twaveContext.beginPath();\n\t\twaveContext.lineJoin = \"round\";\n\t\twaveContext.lineWidth = 6;\n\t\twaveContext.strokeStyle = waveformGradient;\n\t\twaveContext.moveTo(0, (values[0] / 255) * canvasHeight);\n\t\tfor (var i = 1, len = values.length; i < len; i++){\n \t\tvar val = values[i] / 255;\n\t\t var x = canvasWidth * (i / len);\n\t\t var y = val * canvasHeight;\n\t\t waveContext.lineTo(x, y);\n\t\t}\n\t\twaveContext.stroke();\n\t }\n\n //Calculates the size the waveform canvas element should be.\n var canvasWidth, canvasHeight;\n function sizeCanvases(){\n\t canvasWidth = $(\"#page\").width();\n\t canvasHeight = 255;\n\t waveContext.canvas.width = canvasWidth;\n\t waveContext.canvas.height = canvasHeight;\n\n\t //Form the gradient the waveform will use.\n\t waveformGradient = waveContext.createLinearGradient(0, 0, canvasWidth, canvasHeight);\n\t waveformGradient.addColorStop(0, \"#ddd\");\n\t waveformGradient.addColorStop(1, \"#000\"); \n }\n\n sizeCanvases();\n\t \n //Loops while the synth is outputting in order to draw the waveform.\n function loop(){\n requestAnimationFrame(loop);\n //Get waveform values in order to draw it.\n var waveformValues = waveform.analyse();\n drawWaveform(waveformValues);\n }\n loop();\n \n var j = 0.0;\n var k = \"\";\n \n //Converts ASCII to a note based on the tonemap.\n for(i = 0; i < string.length; i++) {\n var ascii = string[i].charCodeAt();\n if (ascii > 31 && ascii < 84) {\n ascii = ascii - 32;\n }\n else {\n ascii = ascii - 84;\n }\n k = \"+\" + j;\n \n //Triggers the note at the set interval k.\n synth.triggerAttack(tonemap[ascii], k);\n j += 0.25;\n }\n //Stops the synth after all notes have been played.\n synth.triggerRelease(k);\n \n //Starts the progress bar.\n progressBar(j);\n}",
"function setFrequency(value) {\n var minValue = 40;\n var maxValue = AUDIO.sampleRate / 2;\n var numberOfOctaves = Math.log(maxValue / minValue) / Math.LN2;\n var multiplier = Math.pow(2, numberOfOctaves * (value - 1.0));\n filterNode.frequency.value = maxValue * multiplier;\n}",
"function setFrequency(){\n radio.frequency = (radio.range.high + radio.range.low)/2\n}",
"function setFrequency() {\n radio.frequency = (radio.range.low + radio.range.high) / 2;\n}",
"function _updateDurationSettings() {\n durationPerMeasure = divisions * (4 / beatType) * beats;\n }",
"_initAudioParams() {\n this.inputGain = this.audioComponents.inputGain.gain;\n this.outputGain = this.audioComponents.outputGain.gain;\n this.pan = this.audioComponents.panner.pan;\n }",
"function initAudio() {\n\n // Default values for the parameters\n AudBuffSiz = 4096;\n AudAmplify = 0.02;\n AudAmpScale = 0.8; // 1.3 is good to emphasise \"peakiness\", 0.5 good to \"smooth\" the sounds out a bit\n AudMinFreq = 30.0; // In Hz\n AudMaxFreq = 900.0;\n\n AudioCtx = new AudioContext();\n GainNode = AudioCtx.createGain();\n //GainNode.connect(AudioCtx.destination);\n //GainNode.gain.value = 1;\n AudSampleRate = AudioCtx.sampleRate;\n AudioBuffer = AudioCtx.createBuffer(1, AudBuffSiz, AudSampleRate);\n\n PlayingSpec = -1;\n\n}",
"function initAnalyser() {\n//Creates an AnalyserNode\n\tanalyser = audioContext.createAnalyser();\n\t/*A value from 0 - 1 where 0 represents no time averaging with the last analysis frame. The default value is 0.8 */\n\tanalyser.smoothingTimeConstant = SMOOTHING;\n\t//The size of the FFT used for frequency-domain analysis. Must be a power of 2\n\tanalyser.fftSize = FFT_SIZE;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
TODO: after the first call to _renderFood, we should just render the single food cell instead of rerendering all of the food cells. | _renderFood(foodCells) {
for (var key in foodCells) {
if (!foodCells.hasOwnProperty(key)) continue;
this._setCellStyle(foodCells[key].x, foodCells[key].y, 'food');
}
for(var i = 0; i < foodCells.length; i++) {
this._setCellStyle(foodCells[i].x, foodCells[i].y, 'food');
}
} | [
"function setFood() {\n\tvar empty = [];\n\t\n\t// find empty grid cells\n\tfor (var x = 0; x < grid.width; x++) {\n\t\tfor (var y = 0; y < grid.height; y++) {\n\t\t\tif (grid.get(x, y) === EMPTY) {\n\t\t\t\tempty.push({x:x, y:y});\n\t\t\t}\n\t\t}\n\t}\n\tvar randomPosition = empty[Math.floor(Math.random() * (empty.length-1))]; // selects a random grid cell\n\tgrid.set(FRUIT, randomPosition.x, randomPosition.y); // sets the \"apple\" to the randomly selected grid cell\n}",
"renderTableData() {\n window.$(\"#expenses\").find(\"tr:gt(0)\").remove();\n let table = document.getElementById(\"expenses\");\n for (let i = 0; i<exps.length; i++) {\n let row = table.insertRow();\n let cell0 = row.insertCell(0);\n let cell1 = row.insertCell(1);\n let cell2 = row.insertCell(2);\n cell0.innerHTML = exps[i].name;\n cell1.innerHTML = exps[i].cost;\n cell2.innerHTML = exps[i].category;\n }\n }",
"function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredUFO.length; i++) {\n // Get get the current UFO object and its fields\n var ufo = filteredUFO[i];\n var observations = Object.keys(ufo);\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 < observations.length; j++) {\n // For every observations in the ufo object, create a new cell at set its inner text to be the current value at the current ufo'sobservation\n var observation = observations[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = ufo[observation];\n }\n }\n}",
"static generateFood(model, rows, columns) {\n const FOOD_LIMIT = rows;\n let size = FOOD_LIMIT;\n for (let i = 0; i < size; i++) {\n const x = Math.floor(Math.random() * FOOD_LIMIT);\n const y = Math.floor(Math.random() * columns);\n const currentValue = model[x][y];\n if (currentValue === \"FOOD\" && x !== 0 && y !== 0) {\n console.log(\"already allocated in this x,y\");\n size++;\n } else {\n model[x][y] = \"FOOD\";\n }\n }\n return model;\n }",
"function generateContents(foodName) {\n\tvar food = foodDict[foodName];\n\t\n\t\n\tvar nameText = '<h1 class=\"text-center\">' + foodName + '</h1>';\n\tvar foodURL = '<h5 class=\"text-center\"><a target=\"_blank\" href=\"' + food[\"url\"] + '\">' + food[\"url\"] + '</a></h5>';\n\tvar imgText = '<img style=\"padding-top:30px;float:left\" src=\"' + food[\"image\"] + '\" alt=\"' + foodName + '\">';\n\t\n\t// Nutrients\n\tvar totalNutrients = food[\"totalNutrients\"];\n\tvar calories = parseInt(food[\"calories\"]) + \" Calories\";\n\tvar fat = parseInt(totalNutrients[\"FAT\"][\"quantity\"]) + totalNutrients[\"FAT\"][\"unit\"] + \" Fat\";\n\tvar carbs = parseInt(totalNutrients[\"CHOCDF\"][\"quantity\"]) + totalNutrients[\"CHOCDF\"][\"unit\"] + \" Carbohydrates\"\n\tvar protein = parseInt(totalNutrients[\"PROCNT\"][\"quantity\"]) + totalNutrients[\"PROCNT\"][\"unit\"] + \" Protein\";\n\tvar nutrientText = '<br/><br/><br/><div class=\"nutrient-font text-center\">' + calories + \"<br/>\" + fat + \"<br/>\" + carbs + \"<br/>\" + protein + \"<br/></div>\";\n\t\n\t$(\"#food-facts\").append(nameText + foodURL + imgText + nutrientText + '<br/><br/><br/><br/><br/><br/><br/>');\n\t\n\t\n\t// Ingredients\n\t$(\"#food-facts\").append('<h2>Ingredients</h2>');\n\tvar ingredients = food[\"ingredients\"];\n\tvar ingredientText = '<div class=\"col-md-5\"><ul>'\n\t\tfor (ingredientIndex in ingredients) {\n\t\t\tvar currentIngredient = ingredients[ingredientIndex];\n\n\n\n\t\t\t// If price is undefined, define it.\n\t\t\tvar price = food_dict[currentIngredient[\"food\"]];\n\t\t\tif (price === undefined || price === null) {\n\t\t\t\tprice = \"$3.26\";\n\t\t\t}\n\n\t\t\tingredientText += '<li>' + currentIngredient[\"quantity\"] + \" \" + currentIngredient[\"measure\"]\n\t\t\t\t\t\t\t+ \" \" + currentIngredient[\"food\"] + \" <strong>\" + price + \"</strong></li></br>\";\n\t}\n\tingredientText += '</ul></div>';\n\t$(\"#food-facts\").append(ingredientText);\n\t\n\t\n}",
"function renderDayAndWeekCosts(date) {\r\n // Check if cost/hour information exists for particular day (If not it's all 0)\r\n if (!hoursAndCosts['day_hours_costs'].hasOwnProperty(date)) {\r\n _resetDayCosts(date);\r\n } else {\r\n // Display day hours and cost\r\n var dayCosts = hoursAndCosts['day_hours_costs'][date];\r\n for (var department in dayCosts) {\r\n if (!dayCosts.hasOwnProperty(department)) {\r\n continue;\r\n }\r\n var $depRow = $dayCostTable.find(\"tr[data-dep-id=\"+department+\"]\");\r\n var $depHours = $depRow.find(\"td[data-col=hours]\");\r\n var $depOvertime = $depRow.find(\"td[data-col=overtime]\");\r\n var $depCost = $depRow.find(\"td[data-col=cost]\");\r\n\r\n $depHours.text(dayCosts[department]['hours']);\r\n $depOvertime.text(dayCosts[department]['overtime_hours']);\r\n commaCost = numberWithCommas(Math.round(dayCosts[department]['cost']));\r\n $depCost.text(\"$\" + commaCost);\r\n }\r\n }\r\n // Find what workweek the day clicked belongs to\r\n var weekCosts = {};\r\n var weekDuration = {};\r\n var allWorkweekCosts = hoursAndCosts['workweek_hours_costs'];\r\n for (var i=0; i < allWorkweekCosts.length; i++) {\r\n var weekStart = allWorkweekCosts[i]['date_range']['start'];\r\n var weekEnd = allWorkweekCosts[i]['date_range']['end'];\r\n if (moment(date).isSameOrAfter(weekStart) && moment(date).isSameOrBefore(weekEnd)) {\r\n weekCosts = allWorkweekCosts[i]['hours_cost'];\r\n weekDuration = allWorkweekCosts[i]['date_range'];\r\n break;\r\n }\r\n }\r\n // Display week hours and cost\r\n for (var department in weekCosts) {\r\n if (!weekCosts.hasOwnProperty(department)) {\r\n continue;\r\n }\r\n var $depRow = $weekCostTable.find(\"tr[data-dep-id=\"+department+\"]\");\r\n var $depHours = $depRow.find(\"td[data-col=hours]\");\r\n var $depOvertime = $depRow.find(\"td[data-col=overtime]\");\r\n var $depCost = $depRow.find(\"td[data-col=cost]\");\r\n\r\n $depHours.text(weekCosts[department]['hours']);\r\n $depOvertime.text(weekCosts[department]['overtime_hours']);\r\n commaCost = numberWithCommas(Math.round(weekCosts[department]['cost']));\r\n $depCost.text(\"$\" + commaCost);\r\n }\r\n // Render day and week titles\r\n var dayTitle = moment(date).format(\"dddd, MMMM Do\");\r\n var weekStart = moment(weekDuration['start']).format(\"MMMM Do\");\r\n var weekEnd = moment(weekDuration['end']).format(\"MMMM Do\");\r\n\r\n $dayCostTitle.text(dayTitle);\r\n $weekCostTitle.text(weekStart + \" - \" + weekEnd);\r\n }",
"_renderBodyCellsContent(renderer, cells) {\n if (!cells || !renderer) {\n return;\n }\n\n this.__renderCellsContent(renderer, cells);\n }",
"function refreshView() {\n let DOMcellCollection = document.getElementsByClassName('cell');\n for (let i = 0; i < DOMcellCollection.length; i++) {\n let DOMcell = DOMcellCollection[i];\n let DOMcellX = DOMcell.getAttribute('x');\n let DOMcellY = DOMcell.getAttribute('y');\n if (currentGame.grid[DOMcellX][DOMcellY].revealed) {\n DOMcell.classList.add('revealed');\n DOMcell.classList.remove('unrevealed');\n DOMcell.firstChild.classList.remove('hidden')\n }\n if (!currentGame.playing && currentGame.grid[DOMcellX][DOMcellY].isMine) {\n DOMcell.classList.add('exploded');\n DOMcell.classList.remove('unrevealed');\n DOMcell.firstChild.classList.remove('hidden')\n }\n }\n}",
"function eat(data) {\n //send to all clients\n io.emit('dead cell', data);\n\n //update mass\n for(var i = 0; i < players.length; i++){\n if(players[i].id == socket.id){\n players[i].mass = data.mass;\n break;\n }\n }\n\n if(data.isFood){\n console.log(chalk.green('User ' + socket.id + ' ate food'));\n\n for(var i = 0; i < food.length; i++){\n if(food[i].id == data.id){\n food.splice(i,1);\n break;\n }\n }\n //regenerate food with same id\n var newFood = new Cell(\n random(-worldX, worldX),\n random(-worldY, worldX),\n foodMass,\n rgb2hex([random(0,255),random(0,255),random(0,255)]),\n data.id);\n food.push(newFood);\n //send new cell to all clients\n io.emit('new food', [newFood]);\n } else {\n for(var i = 0; i < players.length; i++){\n if(players[i].id == data.id){\n players.splice(i,1);\n }\n }\n console.log(chalk.yellow('User ' + data.id + ' died'));\n }\n }",
"function drawFruit() {\n var myFruitClass = formatName(myFruit);\n $(\".fruit\").removeClass(\"fruit\");\n $(\"#board-game tr .\" + myFruitClass).addClass(\"fruit\");\n }",
"function renderIngredient (food) {\n\tlet nutrients = food.food.nutrients;\n\tlet image = food.food.image;\n\tconst $username = $('#hidden_user').attr('name').toString();\n\tconst plans = $('#hidden_plans').text().split(',');\n\n\tconst htmlPlans = addPlans(plans, $username);\n\n\treturn `\n <div class=\"row\">\n <div class=\"col-sm\">\n <h3><b>${food.food.label}</b></h3>\n <img src=${image} onError=\"this.onerror=null; this.className='default-image'; this.src='/static/images/no-image-found.png';\"></a>\n <h4>Category: ${food.food.category}</h4>\n <ul class=\"list-group\">\n <li id=\"kcal\" class=\"list-group-item\">ENERGY (KCAL) : <b>${nutrients.ENERC_KCAL.toFixed(0)}</b></li>\n <li id=\"pro\" class=\"list-group-item\">PROTEIN : <b>${nutrients.PROCNT.toFixed(0)}</b></li>\n <li id=\"fat\" class=\"list-group-item\">FAT : <b>${nutrients.FAT.toFixed(0)}</b></li>\n <li id=\"car\" class=\"list-group-item\">CARBOHYDRATES : <b>${nutrients.CHOCDF.toFixed(0)}</b></li>\n <li id=\"fib\" class=\"list-group-item\">DIETARY FIBER : <b>${nutrients.FIBTG.toFixed(0)}</b></li>\n </ul>\n <div class=\"dropdown\">\n <button id=\"btn_add_daily\" class=\"btn btn-success dropdown-toggle\"\n data-bs-toggle=\"dropdown\" aria-expanded=\"false\">\n <i class=\"fas fa-bread-slice\"></i>\n Add to Recipe\n </button>\n <ul class=\"dropdown-menu\" aria-labelledby=\"btn_add_recipe\">\n ${htmlPlans}\n <li><a id=\"new_recipe\" class=\"dropdown-item\" href=\"/users/add_recipe\">New Recipe</a></li>\n </ul>\n </div>\n </div>\n </div>\n `;\n}",
"showCellsId(G,ctx){\n\t\t\tconst cells = [...G.cells];\n\t\t\tfor (let i = 0; i < boardHeight; i++) {\n\t\t\t\tfor(let j=0;j<boardWidth;j++) {\n\t\t\t\t\tlet id = boardWidth * i + j;\n\t\t\t\t\tcells[id].setDisplay(id);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {...G,cells};\n\t\t}",
"render() {\n this.map.render(this.snake.getBody(), this.food.getCoordinates());\n }",
"function redrawEpisodesTbl(tbl, episodes) {\n // dont redraw a table that does not exists\n if (episodesTbl == null)\n return;\n // the table exists\n $(\"#adminEpisodePH .header\").html(\"\");\n drawEpisodesHeader();\n\n episodesTbl.clear();\n for (var i = 0; i < episodes.length; i++) {\n episodesTbl.row.add({\n Episode_num: episodes[i].Episode_num,\n Episode_name: episodes[i].Episode_name,\n RuppinPopularity: episodes[i].RuppinPopularity,\n Date: episodes[i].Date,\n Img: episodes[i].Img\n });\n }\n episodesTbl.draw();\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 drawCell(cell) {\n ctx.beginPath();\n ctx.rect(cell.x, cell.y, cell.w, cell.h);\n ctx.fillStyle = CELL_COLOR[cell.type];\n ctx.fill();\n ctx.closePath();\n }",
"function Cell({ flipCellsAroundMe, isLit, coords}) {\n const handleClick = () => {\n flipCellsAroundMe(coords);\n };\n\n const classes = `Cell ${isLit ? \"Cell-lit\" : \"\"}`;\n return <div className={classes} onClick={handleClick}></div>;\n}",
"function drawFood() {\n foodPos = Math.floor(Math.random() * TOTALBOXES) + 1;\n\n // If box id = snake id generate new number\n while (snakePos.includes(foodPos)) {\n foodPos = Math.floor(Math.random() * TOTALBOXES) + 1;\n }\n $(\"#grid\").find(\"#\" + foodPos).addClass(\"food\");\n}",
"randomize () {\n\t\tfor (var column = 0; column < this.numberOfColumns; column ++) {\n for (var row = 0; row < this.numberOfRows; row++) {\n this.cells[column][row].setIsAlive(floor(random(2)));\n\t\t\t\tthis.cells[column][row].draw();\n }\n }\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a string db query for all the flat data we can get about the docks: 1 row per dock | getDockDataQuery() {
return 'SELECT d.id, d.loaders_count, ' +
'(SELECT COUNT(*) FROM Containers WHERE container_hold = d.id) as container_count, ' +
' (SELECT container_hold as ship_id FROM Ships WHERE dock_id = d.id) as connected_ship_id ' +
' FROM ContainerHold ch JOIN Docks d ON ch.id = d.id ' +
' JOIN Timelines tl ON ch.timeline_id = tl.id ' +
` WHERE tl.id = "${this.timeline_id}" ` +
`AND tl.simulation_id = "${this.simulation_id}" ` +
` AND type = "dock";`;
} | [
"getDockScheduledShipsQuery() {\n return `SELECT DISTINCT(ship_id), eta, i.dock_id ` +\n `FROM Intervals i JOIN Timelines tl ON i.timeline_id = tl.id ` +\n `WHERE ship_id is not null ` +\n `AND i.timeline_id = \"${this.timeline_id}\" ` +\n `AND tl.simulation_id = \"${this.simulation_id}\" ORDER by eta; `;\n }",
"toString() {\n var statement = this._statement;\n this._applyHas();\n this._applyLimit();\n\n var parts = {\n fields: statement.data('fields').slice(),\n joins: statement.data('joins').slice(),\n where: statement.data('where').slice(),\n limit: statement.data('limit')\n };\n\n var noFields = !statement.data('fields');\n if (noFields) {\n statement.fields({ [this.alias()]: ['*'] });\n }\n var sql = statement.toString(this._schemas, this._aliases);\n\n for (var name in parts) {\n statement.data(name, parts[name]);\n }\n this._aliasCounter = {};\n this._aliases = {};\n this.alias('', this.schema());\n return sql;\n }",
"function getAllSql(version) {\n let tblData = getSqlTable(version);\n let sql = \"\";\n for (let tblName in tblData) {\n sql += getSql(tblName, tblData) + \"\\n\\n\";\n }\n cal.LOG(\"Storage: Full SQL statement is \" + sql);\n return sql;\n}",
"function displayAllDrinks() {\n console.log(\"displaying top 1000 Drinks\");\n return new sql.Request().query('SELECT TOP 1000 * FROM dbo.DRINK ORDER BY DrinkID DESC');\n}",
"prettyPrintSql(file, connectionName) {\n console.log(this.logger.colors.gray(`------------- ${file.file.name} -------------`));\n console.log();\n file.queries.map((sql) => {\n prettyPrint_1.prettyPrint({\n connection: connectionName,\n sql: sql,\n ddl: true,\n method: utils_1.getDDLMethod(sql),\n bindings: [],\n });\n console.log();\n });\n console.log(this.logger.colors.gray('------------- END -------------'));\n }",
"buildSOQL() {\n let soql;\n if (this.fields) soql = this.appendField();\n soql += this.appendWhere();\n soql += ' WITH SECURITY_ENFORCED ';\n\n //if we filter on a column then we ignore the ORDER BY defined in the configuration\n if (this.orderBy && !this.sortBy) {\n soql += ` ORDER BY ${this.orderBy}`;\n } else if (this.sortBy && this.sortDirection) {\n soql += ` ORDER BY ${this.sortBy} ${this.sortDirection} `;\n }\n\n if (this.limit && this.limit > 0) {\n soql += this.appendLimit();\n soql += this.appendOffset();\n }\n\n this.soql = soql;\n }",
"function makeExerciseSqlStr(exercisesValuesArr) {\n let finalStr = \"\";\n for (let c in exercisesValuesArr) {\n if (c < exercisesValuesArr.length -1) {\n finalStr = finalStr + makeStr(exercisesValuesArr[c]) + ','}\n else {\n finalStr = finalStr + makeStr(exercisesValuesArr[c])\n }\n }\nreturn finalStr\n}",
"function generateQuery (type) {\n const query = new rdf.Query()\n const rowVar = kb.variable(keyVariable.slice(1)) // don't pass '?'\n\n addSelectToQuery(query, type)\n addWhereToQuery(query, rowVar, type)\n addColumnsToQuery(query, rowVar, type)\n\n return query\n }",
"toString() {\n var widthOfGrid = this.grid.length;\n var output = '\\n #|';\n var border = '\\n --';\n var item;\n var i;\n var j;\n // var id;\n\n // Render the table header\n for (i = 0; i < widthOfGrid; i++) {\n output += ' ' + this._padNumber(i, ' ');\n border += '---';\n }\n output += border;\n\n // Render table contents row by row, as we go on the y axis\n for (i = 0; i < this._options.lanes; i++) {\n output += '\\n' + this._padNumber(i, ' ') + '|';\n for (j = 0; j < widthOfGrid; j++) {\n output += ' ';\n item = this.grid[j][i];\n // id = this.items.indexOf(item);\n // id = item.id;\n output += item ? this._padNumber(item.id, '0') : '--';\n }\n }\n output += '\\n';\n return output;\n }",
"formatRawSequencingFileQuery() {\n const query = this.buildBasicQuery();\n query.addKeyValue(`${this._fileQueryKey}.output_type`, this._outputType);\n query.addKeyValue(`${this._fileQueryKey}.output_category`, this._outputCategory);\n this._rawSequencingFileQueryString = query.format();\n }",
"function generateMapMount (){\n sql.open(connectionString, function (err, con) {\n if (err) {\n console.log('failed to open ' + err.message);\n return\n }\n\n con.query('SELECT Quantity_energy_on_step, Def_bonus, Texture_link FROM Texture WHERE Title = \\'Mount\\'', function (err, rows) {\n if (err) {\n console.log(err.message);\n return\n }\n //console.log(rows);\n return rows;\n })\n });\n} //Почему-то не возвращает результат",
"function datasetQuery(query){\r\n\t\tvar select = \"SELECT\";\r\n\t\tvar params = {};\r\n\t\tvar builtConditions = generateConditions(query);\r\n\t\tfor(var paramsk in builtConditions.params){\r\n\t\t\tif (!builtConditions.params.hasOwnProperty(paramsk)) continue;\r\n\t\t\tparams[paramsk]=builtConditions.params[paramsk];\r\n\t\t}\r\n\t\tfor(var i = 0; i < domain.length; i++){\r\n\t\t\tparams[\"domain_value_\" + i] = domain[i];\r\n\t\t\tvar dcond = domainCondition(i);\r\n\t\t\tfor(var paramsk in dcond.params){\r\n\t\t\t\tif (!dcond.params.hasOwnProperty(paramsk)) continue;\r\n\t\t\t\tparams[paramsk]=dcond.params[paramsk];\r\n\t\t\t}\r\n\t\t\tselect += \" \" + fn + \"(CASE WHEN \" + dcond.condition + \" THEN \" + value + \" END) AS \" + domainName + \"_\" + i;\r\n\t\t\tif(i != domain.length-1) select += \",\";\r\n\t\t}\r\n\t\tselect += \" FROM offence\" + (builtConditions.conditions.length?' WHERE ':'') + builtConditions.conditions.join(\" AND \") + \";\"\r\n\t\tconsole.log(select, params);\r\n\t\treturn {select, params};\r\n\t}",
"async select(params) {\n try {\n const selectCore_tickData = `SELECT * FROM core_tickData_${params.feed};`;\n return await this._core.DBManager.engine.execute(selectCore_tickData);\n } catch (e) {\n console.log(e);\n }\n }",
"function TKR_formatContextQueryArgs() {\n let args = '';\n let colspec = _ctxDefaultColspec;\n const colSpecElem = TKR_getColspecElement();\n if (colSpecElem) {\n colspec = colSpecElem.value;\n }\n\n if (_ctxHotlistID != '') args += '&hotlist_id=' + _ctxHotlistID;\n if (_ctxCan != 2) args += '&can=' + _ctxCan;\n args += '&q=' + encodeURIComponent(_ctxQuery);\n if (_ctxSortspec != '') args += '&sort=' + _ctxSortspec;\n if (_ctxGroupBy != '') args += '&groupby=' + _ctxGroupBy;\n if (colspec != _ctxDefaultColspec) args += '&colspec=' + colspec;\n if (_ctxStart != 0) args += '&start=' + _ctxStart;\n if (_ctxNum != _ctxResultsPerPage) args += '&num=' + _ctxNum;\n if (!colSpecElem) args += '&mode=grid';\n return args;\n}",
"function selectFields(camposSelecionados){\n var query;\n query = 'SELECT * ';//+ camposSelecionados;\n return query;\n}",
"function frageSql(db, sql) {\n\tvar qry, a, b, c, d;\n\tqry = db.query(sql, {json:true});\n\tif (qry.length > 0) {\n\t\ta = JSON.stringify(qry);\n\t\t//Rückgabewert ist in \"\" eingepackt > entfernen\n\t\tb = a.slice(1, a.length -1);\n\t\t//im Rückgabewert sind alle \" mit \\\" ersetzt. Das ist kein valid JSON!\n\t\tc = b.replace(/\\\\\\\"/gm, \"\\\"\");\n\t\t//jetzt haben wir valid JSON. In ein Objekt parsen\n\t\t//console.log(c);\n\t\td = JSON.parse(c);\n\t\treturn d;\n\t} else {\n\t\treturn null;\n\t}\n}",
"function buildDBPediaQuery (name) {\n\t\tindex = name.indexOf(\"City\");\n\t\tvar sparql;\n\t\tif (index==-1) {//it is a county\n\t\t index = name.indexOf(\"County\");\n\t\t\tvar county = name.substring(index+7); \n\t\t\tsparql = \" SELECT distinct ?loc ?web ?img ?map ?wiki \" + //+?area \" +\n\t\t\t\t\t \" WHERE { \" +\n\t\t\t\t\t \" ?loc a <http://dbpedia.org/ontology/Settlement> . \" +\n\t\t\t\t\t \" ?loc <http://purl.org/dc/terms/subject> <http://dbpedia.org/resource/Category:Counties_of_the_Republic_of_Ireland> . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/property/web> ?web . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/ontology/thumbnail> ?img . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/property/mapImage> ?map . \" +\n\t\t\t\t\t \" ?loc <http://www.w3.org/2000/01/rdf-schema#label> ?label . \" +\n\t\t\t\t\t \" ?loc <http://xmlns.com/foaf/0.1/page> ?wiki . \" +\n\t\t\t\t\t //\" ?loc <http://dbpedia.org/property/areaKm> ?area . \" +\n\t\t\t\t\t \" FILTER(REGEX(STR(?label), \\\"\" + county + \"\\\" )) . \" +\n\t\t\t\t\t \" } \";\n\t\t}\n\t\telse {// it is a city\n\t\t\tvar city = name.substring(0,index); \n\t\t\tsparql = \" SELECT distinct ?loc ?web ?img ?wiki \" +\n\t\t\t\t\t \" WHERE { \" +\n\t\t\t\t\t \" ?loc a <http://dbpedia.org/ontology/Place> . \" +\n\t\t\t\t\t \" ?loc <http://purl.org/dc/terms/subject> <http://dbpedia.org/resource/Category:Cities_in_the_Republic_of_Ireland> . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/property/website> ?web . \" +\n\t\t\t\t\t \" ?loc <http://dbpedia.org/ontology/thumbnail> ?img . \" +\n\t\t\t\t\t \" ?loc <http://www.w3.org/2000/01/rdf-schema#label> ?label . \" +\n\t\t\t\t\t \" ?loc <http://xmlns.com/foaf/0.1/page> ?wiki . \" +\n\t\t\t\t\t \" FILTER(REGEX(STR(?label), \\\"\" + city + \"\\\" )) . \" +\n\t\t\t\t\t \" } \" ;\n\t\t}\n\t\treturn sparql;\n\t}",
"function makeDefaultColorbarQueries(entry) {\n for (i = 0; i < entry[\"datasets\"].length; i++) {\n\n var ds_info = entry[\"datasets\"][i];\n\n for (j = 0; j < ds_info.parameters.length; j++) {\n var colorbarInfo = ds_info.parameters[j][\"colorbar\"];\n cbitems = [];\n cbitems.push(colorbarInfo.palette);\n cbitems.push(colorbarInfo.continuity);\n //because I already have these in my config file a little differently\n if (colorbarInfo.logscale == \"TRUE\") {\n cbitems.push(\"Log\");\n } else {\n cbitems.push(\"\");\n }\n cbitems.push(colorbarInfo.colorbarmin);\n cbitems.push(colorbarInfo.colorbarmax);\n cbitems.push(colorbarInfo.sections);\n ds_info.parameters[j][\"colorbar\"][\"query\"] = cbitems.join(\",\");\n }\n }\n}",
"function getFiltersQuery() {\n var filterModel = that.tableOptions.api.getFilterModel();\n var colStrs = [];\n Object.keys(filterModel).forEach(function (col) {\n colStrs.push(filterToSql(col, filterModel[col]));\n });\n if (that.searchText && that.searchText.length > 2) {\n var globalSearchVal = globalSearchToSql() !== '' ? globalSearchToSql() : '1=2';\n if (globalSearchVal) {\n // do not push an empty global search\n colStrs.push(\"(\" + globalSearchVal + \")\");\n }\n }\n return colStrs.join(' AND ');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A configuration object for notebook settings. | get notebookConfig() {
return this._notebookConfig;
} | [
"function SliderConfig() {\n\n _self = this;\n\n this.data = {\n barsCount: config.bars.count,\n maxDecibels: config.analyser.maxDecibels,\n minDecibels: config.analyser.minDecibels,\n playerWidth: config.player.width,\n rectPadding: config.rect.padding,\n rectVelocity: config.rect.velocity,\n wheelLineWidth: config.wheel.lineWidth,\n wheelRadius: config.wheel.radius\n };\n this.sliders = {};\n}",
"function NotebookInstanceLifecycleConfig(props) {\n return __assign({ Type: 'AWS::SageMaker::NotebookInstanceLifecycleConfig' }, props);\n }",
"function Window_ModPatchConfig() {\r\n this.initialize.apply(this, arguments);\r\n}",
"initAnnotSettings() {\n if (\n this.config.annotationsPath ||\n this.config.localAnnotationsPath ||\n this.annots || this.config.annotations\n ) {\n if (!this.config.annotationHeight) {\n var annotHeight = Math.round(this.config.chrHeight / 100);\n this.config.annotationHeight = annotHeight;\n }\n\n if (this.config.annotationTracks) {\n this.config.numAnnotTracks = this.config.annotationTracks.length;\n } else {\n this.config.numAnnotTracks = 1;\n }\n this.config.annotTracksHeight =\n this.config.annotationHeight * this.config.numAnnotTracks;\n\n if (typeof this.config.barWidth === 'undefined') {\n this.config.barWidth = 3;\n }\n } else {\n this.config.annotTracksHeight = 0;\n }\n\n if (typeof this.config.annotationsColor === 'undefined') {\n this.config.annotationsColor = '#F00';\n }\n }",
"get config() {\n return this._vm.$data.config\n }",
"_updateEditorConfig() {\n for (let i = 0; i < this.widgets.length; i++) {\n const cell = this.widgets[i];\n let config;\n switch (cell.model.type) {\n case 'code':\n config = this._editorConfig.code;\n break;\n case 'markdown':\n config = this._editorConfig.markdown;\n break;\n default:\n config = this._editorConfig.raw;\n break;\n }\n let editorOptions = {};\n Object.keys(config).forEach((key) => {\n var _a;\n editorOptions[key] = (_a = config[key]) !== null && _a !== void 0 ? _a : null;\n });\n cell.editor.setOptions(editorOptions);\n cell.editor.refresh();\n }\n }",
"function iglooSettings () {\n\tthis.popup = null;\n\tthis.settingsEnabled = true;\n\tthis.isOpen = false;\n}",
"function getDefaultConfig() {\n\tvar config = {};\n\t\n\tvar configZen = CSScomb.getConfig('zen');\n\t\n\t// Copy only sort-order data:\n\tconfig['sort-order'] = configZen['sort-order'];\n\t\n\t// If sort-order is separated into sections, add an empty section at top:\n\tif (config['sort-order'].length > 1) {\n\t\tconfig['sort-order'].unshift([]);\n\t}\n\t\n\t// Add sort-order info for SCSS, Sass and Less functions into the first section:\n\tconfig['sort-order'][0].unshift('$variable', '$include', '$import');\n\t\n\t// Add configuration that mimics most of the settings from Espresso:\n\tconfig['block-indent'] = process.env.EDITOR_TAB_STRING;\n\tconfig['strip-spaces'] = true;\n\tconfig['always-semicolon'] = true;\n\tconfig['vendor-prefix-align'] = true;\n\tconfig['unitless-zero'] = true;\n\tconfig['leading-zero'] = true;\n\tconfig['quotes'] = 'double';\n\tconfig['color-case'] = 'lower';\n\tconfig['color-shorthand'] = false;\n\tconfig['space-before-colon'] = '';\n\tconfig['space-after-colon'] = ' ';\n\tconfig['space-before-combinator'] = ' ';\n\tconfig['space-after-combinator'] = ' ';\n\tconfig['space-before-opening-brace'] = ' ';\n\tconfig['space-after-opening-brace'] = process.env.EDITOR_LINE_ENDING_STRING;\n\tconfig['space-before-closing-brace'] = process.env.EDITOR_LINE_ENDING_STRING;\n\tconfig['space-before-selector-delimiter'] = '';\n\tconfig['space-after-selector-delimiter'] = process.env.EDITOR_LINE_ENDING_STRING;\n\tconfig['space-between-declarations'] = process.env.EDITOR_LINE_ENDING_STRING;\n\t\n\treturn config;\n}",
"function ConfigFunction () {\n\n\n }",
"setConfig() {\n if (this._datepicker) {\n this._datepicker.hide();\n }\n this._config = Object.assign({}, this._config, this.bsConfig, {\n value: this._bsValue,\n isDisabled: this.isDisabled,\n minDate: this.minDate || this.bsConfig && this.bsConfig.minDate,\n maxDate: this.maxDate || this.bsConfig && this.bsConfig.maxDate,\n dateCustomClasses: this.dateCustomClasses || this.bsConfig && this.bsConfig.dateCustomClasses,\n dateTooltipTexts: this.dateTooltipTexts || this.bsConfig && this.bsConfig.dateTooltipTexts,\n datesDisabled: this.datesDisabled || this.bsConfig && this.bsConfig.datesDisabled,\n datesEnabled: this.datesEnabled || this.bsConfig && this.bsConfig.datesEnabled\n });\n this._datepickerRef = this._datepicker\n .provide({ provide: BsDatepickerConfig, useValue: this._config })\n .attach(BsDatepickerInlineContainerComponent)\n .to(this._elementRef)\n .show();\n }",
"function WidgetConfigurationAPI(window){\n this.api_ = api(window);\n this.params_ = params(window);\n this.engagement_ = engagement(window);\n}",
"get rawConfig() {\n return this.conf || readOnly(this.defaults);\n }",
"function Config(obj) {\n if (!(this instanceof Config)) {\n return new Config(obj)\n }\n\n obj = obj || {}\n\n this.data = null\n this._loadObj(obj)\n}",
"DisplayAspNetConfigSettings() {\n\n }",
"function getConfig() {\n var wb = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = wb.getSheetByName('configuration'); \n var configdata = getRowsData(sheet, sheet.getDataRange(), 1);\n\n config = {};\n for (i=1; i<configdata.length; i++) {\n var param = configdata[i];\n var thisparam = normalizeHeader(param.parameter)\n config[thisparam] = param.value;\n\n // special processing this script\n if (thisparam == 'open' && param.value) {\n config[thisparam] = param.value.toLowerCase();\n }\n };\n\n Logger.log( 'config = ' + Utilities.jsonStringify(config) );\n return config;\n}",
"function getConfig() {\n if (config === null) {\n populateConfigFromSheet();\n }\n return config;\n}",
"static defaultConfig() {\r\n if (_defaultConfig == null) {\r\n _defaultConfig = new Config(\"./config/etc/config.json\");\r\n }\r\n\r\n return _defaultConfig;\r\n }",
"config() {\n if (this.isBound(exports.names.APP_SERVICE_CONFIG)) {\n return this.get(exports.names.APP_SERVICE_CONFIG);\n }\n else {\n throw new Error('configuration object not yet loaded!');\n }\n }",
"configuring() {\n // creates .yo-rc config file\n this.config.save()\n }",
"static get defaultOptions() {\n const options = super.defaultOptions;\n options.template = \"public/modules/ffg-roller/templates/roller-window.html\";\n options.width = 150;\n options.height = \"auto\";\n return options;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check the web console DOM element output for the given inputs. Each input is checked for the expected JS eval result. The JS eval result is also checked if it opens the inspector with the correct node selected on inspector icon click | function checkDomElementHighlightingForInputs(hud, inputs) {
function* runner() {
let toolbox = gDevTools.getToolbox(hud.target);
// Loading the inspector panel at first, to make it possible to listen for
// new node selections
yield toolbox.selectTool("inspector");
let inspector = toolbox.getCurrentPanel();
yield toolbox.selectTool("webconsole");
info("Iterating over the test data");
for (let data of inputs) {
let [result] = yield jsEval(data.input, {text: data.output});
let {msg} = yield checkWidgetAndMessage(result);
yield checkNodeHighlight(toolbox, inspector, msg, data);
}
}
function jsEval(input, message) {
info("Executing '" + input + "' in the web console");
hud.jsterm.clearOutput();
hud.jsterm.execute(input);
return waitForMessages({
webconsole: hud,
messages: [message]
});
}
function* checkWidgetAndMessage(result) {
info("Getting the output ElementNode widget");
let msg = [...result.matched][0];
let widget = [...msg._messageObject.widgets][0];
ok(widget, "ElementNode widget found in the output");
info("Waiting for the ElementNode widget to be linked to the inspector");
yield widget.linkToInspector();
return {widget, msg};
}
function* checkNodeHighlight(toolbox, inspector, msg, testData) {
let inspectorIcon = msg.querySelector(".open-inspector");
ok(inspectorIcon, "Inspector icon found in the ElementNode widget");
info("Clicking on the inspector icon and waiting for the " +
"inspector to be selected");
let onInspectorSelected = toolbox.once("inspector-selected");
let onInspectorUpdated = inspector.once("inspector-updated");
let onNewNode = toolbox.selection.once("new-node-front");
let onNodeHighlight = toolbox.once("node-highlight");
EventUtils.synthesizeMouseAtCenter(inspectorIcon, {},
inspectorIcon.ownerDocument.defaultView);
yield onInspectorSelected;
yield onInspectorUpdated;
yield onNodeHighlight;
let nodeFront = yield onNewNode;
ok(true, "Inspector selected and new node got selected");
is(nodeFront.displayName, testData.displayName,
"The correct node was highlighted");
if (testData.attrs) {
let attrs = nodeFront.attributes;
for (let i in testData.attrs) {
is(attrs[i].name, testData.attrs[i].name,
"Expected attribute's name is present");
is(attrs[i].value, testData.attrs[i].value,
"Expected attribute's value is present");
}
}
info("Unhighlight the node by moving away from the markup view");
let onNodeUnhighlight = toolbox.once("node-unhighlight");
let btn = inspector.toolbox.doc.querySelector(".toolbox-dock-button");
EventUtils.synthesizeMouseAtCenter(btn, {type: "mousemove"},
inspector.toolbox.win);
yield onNodeUnhighlight;
info("Switching back to the console");
yield toolbox.selectTool("webconsole");
}
return Task.spawn(runner);
} | [
"function checkOutputForInputs(hud, inputTests) {\n let container = gBrowser.tabContainer;\n\n function* runner() {\n for (let [i, entry] of inputTests.entries()) {\n info(\"checkInput(\" + i + \"): \" + entry.input);\n yield checkInput(entry);\n }\n container = null;\n }\n\n function* checkInput(entry) {\n yield checkConsoleLog(entry);\n yield checkPrintOutput(entry);\n yield checkJSEval(entry);\n }\n\n function* checkConsoleLog(entry) {\n info(\"Logging\");\n hud.jsterm.clearOutput();\n hud.jsterm.execute(\"console.log(\" + entry.input + \")\");\n\n let consoleOutput = \"consoleOutput\" in entry ?\n entry.consoleOutput : entry.output;\n\n let [result] = yield waitForMessages({\n webconsole: hud,\n messages: [{\n name: \"console.log() output: \" + consoleOutput,\n text: consoleOutput,\n category: CATEGORY_WEBDEV,\n severity: SEVERITY_LOG,\n }],\n });\n\n let msg = [...result.matched][0];\n\n if (entry.consoleLogClick) {\n yield checkObjectClick(entry, msg);\n }\n\n if (typeof entry.inspectorIcon == \"boolean\") {\n info(\"Checking Inspector Link\");\n yield checkLinkToInspector(entry.inspectorIcon, msg);\n }\n }\n\n function checkPrintOutput(entry) {\n info(\"Printing\");\n hud.jsterm.clearOutput();\n hud.jsterm.execute(\"print(\" + entry.input + \")\");\n\n let printOutput = entry.printOutput || entry.output;\n\n return waitForMessages({\n webconsole: hud,\n messages: [{\n name: \"print() output: \" + printOutput,\n text: printOutput,\n category: CATEGORY_OUTPUT,\n }],\n });\n }\n\n function* checkJSEval(entry) {\n info(\"Evaluating\");\n hud.jsterm.clearOutput();\n hud.jsterm.execute(entry.input);\n\n let evalOutput = entry.evalOutput || entry.output;\n\n let [result] = yield waitForMessages({\n webconsole: hud,\n messages: [{\n name: \"JS eval output: \" + entry.evalOutput,\n text: entry.evalOutput,\n category: CATEGORY_OUTPUT,\n }],\n });\n\n let msg = [...result.matched][0];\n if (!entry.noClick) {\n yield checkObjectClick(entry, msg);\n }\n if (typeof entry.inspectorIcon == \"boolean\") {\n info(\"Checking Inspector Link: \" + entry.input);\n yield checkLinkToInspector(entry.inspectorIcon, msg);\n }\n }\n\n function* checkObjectClick(entry, msg) {\n info(\"Clicking\");\n let body;\n if (entry.getClickableNode) {\n body = entry.getClickableNode(msg);\n } else {\n body = msg.querySelector(\".message-body a\") ||\n msg.querySelector(\".message-body\");\n }\n ok(body, \"the message body\");\n\n let deferredVariablesView = promise.defer();\n entry._onVariablesViewOpen = onVariablesViewOpen.bind(null, entry,\n deferredVariablesView);\n hud.jsterm.on(\"variablesview-open\", entry._onVariablesViewOpen);\n\n let deferredTab = promise.defer();\n entry._onTabOpen = onTabOpen.bind(null, entry, deferredTab);\n container.addEventListener(\"TabOpen\", entry._onTabOpen, true);\n\n body.scrollIntoView();\n\n if (!entry.suppressClick) {\n EventUtils.synthesizeMouse(body, 2, 2, {}, hud.iframeWindow);\n }\n\n if (entry.inspectable) {\n info(\"message body tagName '\" + body.tagName + \"' className '\" +\n body.className + \"'\");\n yield deferredVariablesView.promise;\n } else {\n hud.jsterm.off(\"variablesview-open\", entry._onVariablesView);\n entry._onVariablesView = null;\n }\n\n if (entry.expectedTab) {\n yield deferredTab.promise;\n } else {\n container.removeEventListener(\"TabOpen\", entry._onTabOpen, true);\n entry._onTabOpen = null;\n }\n\n yield promise.resolve(null);\n }\n\n function onVariablesViewOpen(entry, {resolve, reject}, event, view, options) {\n info(\"Variables view opened\");\n let label = entry.variablesViewLabel || entry.output;\n if (typeof label == \"string\" && options.label != label) {\n return;\n }\n if (label instanceof RegExp && !label.test(options.label)) {\n return;\n }\n\n hud.jsterm.off(\"variablesview-open\", entry._onVariablesViewOpen);\n entry._onVariablesViewOpen = null;\n ok(entry.inspectable, \"variables view was shown\");\n\n resolve(null);\n }\n\n function onTabOpen(entry, {resolve, reject}, event) {\n container.removeEventListener(\"TabOpen\", entry._onTabOpen, true);\n entry._onTabOpen = null;\n let tab = event.target;\n let browser = gBrowser.getBrowserForTab(tab);\n\n Task.spawn(function* () {\n yield loadBrowser(browser);\n let uri = yield ContentTask.spawn(browser, {}, function* () {\n return content.location.href;\n });\n ok(entry.expectedTab && entry.expectedTab == uri,\n \"opened tab '\" + uri + \"', expected tab '\" + entry.expectedTab + \"'\");\n yield closeTab(tab);\n }).then(resolve, reject);\n }\n\n return Task.spawn(runner);\n}",
"function runCode() {\r\n const code = editor.getValue();\r\n if (!code) return;\r\n let { response, logs, error } = evaluate(code);\r\n\r\n if (error) response = '<span class=\"error\">' + response + '</span>';\r\n if (logs.length && response) response = logs.join('\\n') + '\\n' + response;\r\n else if (logs.length) response = logs.join('\\n');\r\n\r\n consoleHTML.innerHTML += `<pre class=\"log\">${response}\\n</pre>`;\r\n}",
"function evalDoubleInput() {\n // Check validity of both input strings\n if (!funcObj.validInput(evalInputFirstStr)) {\n alert(\"First input '\" + evalInputFirstStr + \"' is not valid for this function\")\n return\n }\n if (!funcObj.validInput(evalInputSecondStr)) {\n alert(\"Second input '\" + evalInputSecondStr + \"' is not valid for this function\")\n return\n }\n // Parse the inputs to objects\n var firstParsed = funcObj.parseInput(evalInputFirstStr)\n var secondParsed = funcObj.parseInput(evalInputSecondStr)\n var evaluated = funcObj.function(firstParsed, secondParsed)\n // Get formatted strings for use in the database\n var firstDBstr = funcObj.inputDBStr(firstParsed)\n var secondDBstr = funcObj.inputDBStr(secondParsed)\n\n // Check to see if input being evaluated is allowed to be evaluated (if it was seen during a quiz)\n var gens = funcObj.inputGenerators()\n var forbiddenInputs = []\n gens.forEach((g) => {forbiddenInputs.push(g())})\n var currentlyForbidden = forbiddenInputs.slice(0, getNextQ())\n var forbiddenFound = false\n currentlyForbidden.forEach((inputs) => { \n if (funcObj.equivalentInputs(inputs[0], firstParsed) === true && funcObj.equivalentInputs(inputs[1], secondParsed) === true) {\n alert(\"Cannot evaluate inputs seen during a quiz attempt!\")\n var action = {}\n action.id = localStorage.getItem('userID')\n action.fcn = funcObj.description()\n action.type = \"cheat_attempt\"\n action.time = Util.getCurrentTime()\n action.in = firstDBstr + \" \" + secondDBstr\n action.out = funcObj.outputDBStr(evaluated)\n if (localStorage.getItem(funcObj.description()) === null) {\n action.key = Util.newServerKey()\n Util.sendToServer(action)\n }\n forbiddenFound = true\n }\n })\n if (forbiddenFound === true) {\n return\n }\n\n // Send an input evaluation log action to the server, and also build an\n // action object for use in displaying the evaluation in the guessing screen console\n var serverGuess = {}\n var displayGuess = {}\n serverGuess.id = localStorage.getItem('userID')\n displayGuess.id = localStorage.getItem('userID')\n serverGuess.fcn = funcObj.description()\n displayGuess.fcn = funcObj.description()\n serverGuess.type = \"eval_input\"\n displayGuess.type = \"eval_input\"\n displayGuess.key = Util.newDisplayKey()\n serverGuess.time = Util.getCurrentTime()\n displayGuess.time = Util.getCurrentTime()\n\n serverGuess.in = firstDBstr + \" \" + secondDBstr\n\n var firstDisplayStr = funcObj.inputDisplayStr(firstParsed)\n var secondDisplayStr = funcObj.inputDisplayStr(secondParsed)\n displayGuess.in = firstDisplayStr + \", \" + secondDisplayStr\n\n serverGuess.out = funcObj.outputDBStr(evaluated)\n displayGuess.out = funcObj.outputDisplayStr(evaluated)\n\n serverGuess.finalGuess = funcGuess.trim()\n displayGuess.finalGuess = funcGuess.trim()\n\n // Only if this function wasn't already done (description not already seen)\n if (localStorage.getItem(funcObj.description()) === null) {\n // console.log(\"sent to server\", serverGuess)\n serverGuess.key = Util.newServerKey()\n Util.sendToServer(serverGuess)\n }\n\n // Update the display console\n guesses.push(displayGuess)\n updateFunc()\n }",
"function runTest()\n{\n FBTest.openNewTab(basePath + \"console/766/issue766.html\", (win) =>\n {\n FBTest.openFirebug(() =>\n {\n FBTest.enableConsolePanel(() =>\n {\n var config = {\n tagName: \"div\",\n classes: \"logRow logRow-log\"\n }\n\n // Wait for an error log in the Console panel.\n FBTest.waitForDisplayedElement(\"console\", config, (element) =>\n {\n var log = element.\n getElementsByClassName(\"objectBox objectBox-array hasTwisty\")[0];\n FBTest.ok(log, \"There must be an expandable button\");\n\n FBTest.click(log);\n\n var arrayProps = element.getElementsByClassName(\"arrayProperties\")[0];\n var domTable = element.getElementsByClassName(\"domTable\")[0];\n FBTest.ok(domTable, \"There must be a list of expanded properties\");\n\n var props = element.getElementsByClassName(\"memberLabelCell\");\n var values = element.getElementsByClassName(\"memberValueCell\");\n\n FBTest.ok(props.length == 2, \"There must be two properties\");\n FBTest.ok(values.length == 2, \"There must be two values\");\n\n FBTest.compare(props[0].textContent, \"key-1\", \"The key must be == 'key-1'\");\n FBTest.compare(props[1].textContent, \"key-2\", \"There key must be == 'key-2'\");\n FBTest.compare(values[0].textContent, \"\\\"test1\\\"\",\n \"There value must be == 'test1'\");\n FBTest.compare(values[1].textContent, \"\\\"test2\\\"\",\n \"There value must be == 'test2'\");\n\n FBTest.testDone();\n });\n\n // Run test implemented on the page.\n FBTest.click(win.document.getElementById(\"testButton\"));\n });\n });\n });\n}",
"function printResult(input) {\r\n\tfor (var i = 0; i < input.length; i++) {\r\n\t\tstdout.write(input[i] + \"\\n\");\r\n\t}\r\n}",
"function equals() {\n let box = document.getElementById('display');\n x = box.value;\n x = eval(x);\n box.value = x;\n}",
"function runAssertions(){\n var i,\n len,\n item;\n //Show totals for groups, test, assertions before running the tests.\n showTotalsToBeRun();\n //A slight delay so user can see the totals and they don't flash.\n setTimeout(function(){\n //Synchronously iterate over the assertionsQueue, running each item's assertion.\n for (i = 0, len = assertionsQueue.length; i < len; i++) {\n item = assertionsQueue[i];\n item.result = item.assertion(typeof item.value === 'function' ? item.value() : item.value, item.expectation);\n if(item.result){\n totAssertionsPassed++;\n }else{\n totAssertionsFailed++;\n }\n switch(item.assertion.name){\n case 'assertIsTrue':\n item.displayAssertionName = 'isTrue';\n break;\n case 'assertIsTruthy':\n item.displayAssertionName = 'isTruthy';\n break;\n case 'assertIsFalse':\n item.displayAssertionName = 'isFalse';\n break;\n case 'assertIsNotTruthy':\n item.displayAssertionName = 'isNotTruthy';\n break;\n case 'assertEqual':\n item.displayAssertionName = 'equal';\n break;\n case 'assertNotEqual':\n item.displayAssertionName = 'notEqual';\n break;\n }\n results.push(item);\n if(config.shortCircuit && totAssertionsFailed){\n reporter();\n return;\n }\n }\n //Record the end time.\n timerEnd = Date.now();\n //Report the results.\n reporter();\n }, 1);\n }",
"function dumpConsoles() {\n if (gPendingOutputTest) {\n console.log(\"dumpConsoles start\");\n for (let [, hud] of HUDService.consoles) {\n if (!hud.outputNode) {\n console.debug(\"no output content for\", hud.hudId);\n continue;\n }\n\n console.debug(\"output content for\", hud.hudId);\n for (let elem of hud.outputNode.childNodes) {\n dumpMessageElement(elem);\n }\n }\n console.log(\"dumpConsoles end\");\n\n gPendingOutputTest = 0;\n }\n}",
"function powOutput() {\r\n console.log(\"POW-service : The result of raising <base = \" + powObj.base + \"> to the <power = \" + powObj.exponent + \">\\n\\\r\n EQUALS <\" + powObj.result + \">\");\r\n}",
"function checkAllInputs() {}",
"function extUtils_evaluateRTCElements(rtcElements, paramObj)\n{\n // Stack to keep track of nested directives.\n var directiveStack = new Array();\n var processedInsText = \"\";\n\n // Hash table to match loop parameters with associated nested loop. If we support\n // nested loops, we have to change the variable used to iterate through nested\n // loops in the script. Each value of this mapping is a list of variables iterated over\n // for a given loop. The key of the map denotes the level of nesting of the loop.\n // For example, key of 1 means the loop has 1 parent loop - it's nested 1 level.\n // When finding a reference to an array parameter, we look up it's nesting level\n // in this table to figure out which index to use for it.\n // Note - we don't currently support nested loops.\n var levelToLoopParams = new Object();\n var nestLevel = 0;\n\n // Array to store the parameters used in a given loop.\n var loopParams = null;\n // Length of the array parameters used in a given loop.\n var arrLength = 0;\n\n // Initialize JavaScript function body that will be evaluated to generate the Insert Text.\n //var generateTextFtn;\n var strGenTextFtn = \"function \"+extUtils.STR_FTN_NAME+\"(\"+extUtils.STR_FTN_PARAM+\") { var _arr = new Array();\\n\"\n + \"var _i = 0;\\n\"\n + \"var _stackBuiltIns = new Array();\\n\";\n\n for (var i = 0; i < rtcElements.length; ++i)\n {\n var elmType = rtcElements[i].getElementType();\n var elmStr = rtcElements[i].getElementString();\n\n switch(elmType)\n {\n case extUtils.DIRECTIVE_IF:\n directiveStack.push(extUtils.DIRECTIVE_IF);\n strGenTextFtn += \"if (\"\n + extUtils.replaceParamsInExprStr(elmStr, paramObj, directiveStack, levelToLoopParams, true)\n + \") {\\n\";\n break;\n case extUtils.DIRECTIVE_ELSEIF:\n strGenTextFtn += \"}\\nelse if (\"\n + extUtils.replaceParamsInExprStr(elmStr, paramObj, directiveStack, levelToLoopParams, true)\n + \") {\\n\";\n break;\n case extUtils.DIRECTIVE_ELSE:\n directiveStack.pop();\n directiveStack.push(extUtils.DIRECTIVE_ELSE);\n strGenTextFtn += \"}\\nelse {\\n\";\n break;\n case extUtils.DIRECTIVE_ENDIF:\n directiveStack.pop();\n strGenTextFtn += \"}\\n\";\n break;\n case extUtils.DIRECTIVE_LOOP:\n directiveStack.push(extUtils.DIRECTIVE_LOOP);\n\n // Loop parameters are comma separated in elmStr.\n loopParams = elmStr.split(\",\");\n // Must be at least one parameter in the loop, so use length of the first.\n // If the parameter is null, use a length of 0.\n arrLength = (paramObj[loopParams[0]]) ? paramObj[loopParams[0]].length : 0;\n\n // Add nest level to track parameters used in the current loop.\n levelToLoopParams[nestLevel] = loopParams;\n\n // Build JS loop to represent the loop directive. Also, push a new set of\n // builtin variables on the stack for this loop. Make sure the new instance of\n // builtin variables is used within this loop by using 'with' statement.\n // Note: if we ever have support for nested loops, the _length and _index builtin\n // variables will refer to the innermost loop's version of these builtins.\n strGenTextFtn +=\"_stackBuiltIns[\"+nestLevel+\"] = {_length: \" + arrLength + \", _index: 0};\\n\"\n + \"with (_stackBuiltIns[\"+nestLevel+\"]) {\\n\"\n + \"for (; _index < _length; ++_index) {\\n\";\n ++nestLevel;\n break;\n case extUtils.DIRECTIVE_ENDLOOP:\n directiveStack.pop();\n strGenTextFtn +=\"}\\n\"\n + \"}\\n\";\n // Remove param list for current nest level.\n --nestLevel;\n levelToLoopParams[nestLevel] = [];\n break;\n case extUtils.PARAMETER:\n strGenTextFtn += \"_arr[_i++] = \"\n + extUtils.replaceParamsInExprStr(elmStr, paramObj, directiveStack, levelToLoopParams, false)\n + \";\\n\";\n break;\n case extUtils.RAW_CODE:\n // Escape characters that cause trouble inside an explicit string, e.g. \"charsToEscape\"\n elmStr = elmStr.replace(/(\"|'|\\\\)/g, \"\\\\$1\");\n elmStr = elmStr.replace(/\\n/g, \"\\\\n\");\n elmStr = elmStr.replace(/\\r/g, \"\\\\r\");\n\n // Add text entry\n strGenTextFtn += \"_arr[_i++] = '\" + elmStr + \"';\\n\";\n break;\n }\n }\n\n // Finish off JavaScript function body to generate insert text.\n strGenTextFtn += \"return _arr.join('');} \"+extUtils.STR_FTN_NAME+\"(\"+extUtils.STR_FTN_PARAM+\");\";\n\n try\n {\n // BUG: creating new Function sometimes fails due to memory issues I believe?\n //generateTextFtn = new Function(extUtils.STR_FTN_PARAM, strGenTextFtn);\n //processedInsText = generateTextFtn(paramObj);\n\n // The function argument 'paramObj' is defined in this scope.\n processedInsText = eval(strGenTextFtn);\n }\n catch (e)\n {\n throw new ProcInsTextException(ProcInsTextException.ERR_COULD_NOT_EVAL_DIRECTIVE, e);\n }\n\n return processedInsText;\n}",
"function showTestingInstructions(parentDocViewId)\r\n{\r\n\tvar url = \"view\";\r\n url += \"&parentDocViewId=\"+parentDocViewId;\r\n \t // Check for valid record to show the screen(tab).\r\n if(!isValidMaterialQuote(true))\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\tProcess.execute(url, \"testinginstructionsplm.do\");\r\n}",
"function printValue(val) {\n let displayOuput = document.querySelector('#calculator-screen');\n let currentOutput = displayOuput.value;\n\n if(displayOuput.value == \"0\") {\n if(val !=\"RESET\" && val != \"DEL\") {\n displayOuput.value = \"\";\n displayOuput.value += val;\n }\n } else{\n if(val == \"DEL\") {\n displayOuput.value = currentOutput.slice(0, -1);\n if(displayOuput.value.length<=1){\n displayOuput.value = \"0\";\n }\n }\n\n if(val !=\"RESET\" && val != \"DEL\" && val != \"=\") {\n displayOuput.value = displayOuput.value + val;\n }\n\n if(val == \"RESET\"){\n displayOuput.value = \"0\";\n }\n\n // add formula via new function called eval()\n if(val == \"=\") {\n let res = displayOuput.value;\n displayOuput.value = eval(res)\n }\n\n\n }\n}",
"function getDomVariables() {\n // the form\n registerFormDiv = document.querySelector('#log-in_form'); // the inputs\n\n usernameInput = document.querySelector('#username');\n emailInput = document.querySelector('#email');\n passwordInput = document.querySelector('#password');\n passwordBisInput = document.querySelector('#password-bis'); // the spans to display errors\n\n usernameErrorSpan = document.querySelector('label[for=\"username\"] span.msg-error');\n emailErrorSpan = document.querySelector('label[for=\"email\"] span.msg-error');\n passwordErrorSpan = document.querySelector('label[for=\"password\"] span.msg-error');\n passwordBisErrorSpan = document.querySelector('label[for=\"password-bis\"] span.msg-error'); // array including inputs and error spans\n\n inputsAndSpans = [['username', usernameInput, usernameErrorSpan], ['email', emailInput, emailErrorSpan], ['password', passwordInput, passwordErrorSpan], ['password-bis', passwordBisInput, passwordBisErrorSpan]]; // the clickable question marks to display input rule helps\n\n usernameQuestionMark = document.querySelector('#username-help');\n passwordQuestionMark = document.querySelector('#password-help');\n passwordBisQuestionMark = document.querySelector('#password-bis-help'); // array including question marks and text to display\n\n helpers = [[usernameQuestionMark, usernameHelp], [passwordQuestionMark, passwordHelp], [passwordBisQuestionMark, passwordBisHelp]];\n} // check the value of the input",
"function Main() {\n var output;\n var outputArea = document.getElementById('outputArea');\n var problemType;\n \n // Get the problem type field from the webpage\n var problemTypeField = document.getElementById('problemTypeField');\n\n // This prevents the form from being submitted to a server\n selectProblemType.addEventListener(\"submit\", function(event) {\n event.preventDefault();\n\n problemType = problemTypeField.value;\n\n \n // Once the user selects which type of problem they would like to work with,\n // the switch statement calls the appropriate operator function. The program\n // loops through the operator function 3 times and sends the output to the\n // the WriteOutput function to be displayed to the user.\n \n switch (problemType) {\n case \"a\":\n for(var additionCounter = 0; additionCounter < 3; additionCounter ++){\n output = Addition();\n WriteOutput(output);\n }\n break;\n case \"s\":\n for(var subtractionCounter = 0; subtractionCounter < 3; subtractionCounter ++){\n output = Subtraction();\n WriteOutput(output);\n }\n break;\n case \"m\":\n for(var multiplicationCounter = 0; multiplicationCounter < 3; multiplicationCounter ++){\n output = Multiplication();\n WriteOutput(output);\n }\n break;\n case \"d\":\n for(var divisionCounter = 0; divisionCounter < 3; divisionCounter ++){\n output = Division();\n WriteOutput(output);\n }\n break;\n default:\n WriteOutput(\"Please enter a, s, m or d.\");\n }\n\n outputArea.innerHTML = output;\n \n });\n\n \n}",
"function benchOnClick(button, results, benchName, bencher) {\n button.addEventListener(\n \"click\",\n async function(e) {\n e.preventDefault();\n\n const buttons = [...document.querySelectorAll(\"button\")];\n buttons.forEach(b => b.setAttribute(\"disabled\", true));\n results.innerHTML = \"\";\n await new Promise(r => requestAnimationFrame(r));\n\n var stats = await bencher();\n\n buttons.forEach(b => b.removeAttribute(\"disabled\"));\n\n const csv = stats.xs\n .map(x => `\"${implAndBrowser}\",${testSourceMap.mappings.length},\"${benchName}\",${x}`)\n .join(\"\\n\");\n\n results.innerHTML = `\n <table>\n <thead>\n <tr>\n <td>Samples</td>\n <td>Total (${stats.unit})</th>\n <td>Mean (${stats.unit})</th>\n <td>Standard Deviation (${stats.unit})</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>${stats.samples()}</td>\n <td>${stats.total().toFixed(2)}</td>\n <td>${stats.mean().toFixed(2)}</td>\n <td>${stats.stddev().toFixed(2)}</td>\n </tr>\n </tbody>\n </table>\n <pre style=\"overflow:scroll;max-height:100px; max-width:500px;outline:1px solid black\">${csv}</pre>\n `;\n },\n false\n );\n}",
"function waitForHtmlOutput() {\n // Since we are using `$wait_for_idle(duration = 500)`,\n // no need for the following logic with a fixed time.\n shinytest2.ready = true;\n return;\n\n // // Old code kept for future reference\n\n // var htmlOutputBindings = Shiny.outputBindings\n // .bindingNames['shiny.htmlOutput'].binding.find(document);\n\n // if (htmlOutputBindings.length > 0) {\n // shinytest2.log(\"Waiting for first output\");\n // shinytest2.outputValuesWaiter.start(5000);\n // shinytest2.outputValuesWaiter.finish(true, function() {\n // shinytest2.ready = true;\n // });\n // }\n // else {\n // shinytest2.log(\"Ready\");\n // shinytest2.ready = true;\n // }\n }",
"executeJavaScriptInDevTools(code) {\n return ipcRenderer.send('call-devtools-webcontents-method', 'executeJavaScript', code);\n }",
"function inspectBehavior(enteredStr) {\n var i;\n var argArray = extractArgs(enteredStr);\n\n if (argArray.length == 4) { //first arg is fn name, so ignore that\n document.theForm.URL.value = unescape(argArray[1]);\n document.theForm.winName.value = argArray[2];\n var featuresStr = argArray[3];\n var tokArray = getTokens(featuresStr, \"=,\");\n\n var checkBoxNames = new Array(\"toolbar\",\"location\",\"status\",\"menubar\",\"scrollbars\",\"resizable\");\n for (i in checkBoxNames) {\n if (featuresStr.indexOf(checkBoxNames[i]) != -1)\n theCheckBox = eval(\"document.theForm.\" + checkBoxNames[i] + \".checked = true\");\n }\n for (i=0; i < (tokArray.length-1); i++) {\n if (tokArray[i] == \"height\") document.theForm.height.value = tokArray[i+1];\n if (tokArray[i] == \"width\") document.theForm.width.value = tokArray[i+1];\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transation This class is to add items from basket into an order in the database. It has to get todays date for when the order was made. | transaction() {
let today = new Date();
let day = today.getDate();
let month = today.getMonth() + 1;
let year = today.getFullYear();
let time = today.getHours();
let minutes = today.getMinutes();
if (day < 10) day = '0' + day;
if (month < 10) month = '0' + month;
let orderType = 1;
let todaysDate = year + '-' + month + '-' + day + ' ' + time + ':' + minutes + ':00';
if (this.state.inBasket[0].dayRent == true) {
orderType = 2;
}
orderService.makeOrder(
this.state.activeC[0].id,
orderType,
todaysDate,
this.state.inBasket[0].startDate,
this.state.inBasket[0].endDate,
this.discPrice,
employeeID
);
for (let i = 0; i < this.state.inBasket.length; i++) {
orderService.makeBikeOrder(this.state.activeC[0].id, todaysDate, this.state.inBasket[i].id);
}
if (equipmentBasket.length > 0) {
for (let i = 0; i < equipmentBasket.length; i++) {
orderService.makeEquipOrder(this.state.activeC[0].id, todaysDate, equipmentBasket[i].id);
}
}
basket.length = 0;
equipmentBasket.length = 0;
this.totalPrice = 0;
this.discPrice = 0;
this.removeCustomer();
this.updateBasket();
this.handleClose();
history.push('/overview/');
} | [
"function updateOrderAndDate() {\n let date = new Date();\n date.setHours(0, 0, 0, 0);\n let lastDate = new Date(playlist[playlist.length - 1]['date']);\n let offset = 1;\n let newList = playlist.slice();\n\n // All dates in playlist already passed\n if (lastDate < date) {\n lastDate = new Date();\n offset = 0;\n }\n\n for (let item of playlist) {\n if (date > new Date(item['date'])) {\n let putLast = newList.splice(0, 1)[0];\n lastDate.setDate(lastDate.getDate() + offset);\n putLast['date'] = lastDate.toISOString().substr(0, 10);\n newList.push(putLast);\n offset++;\n }\n }\n playlist = newList;\n logger.info('Updated date and order');\n}",
"function addToToday(justDrank)\n{\n\tif (total.day==null)\n\t{\n\n\t\ttotal.drinks.push(justDrank);\n\t\ttotal.day = justDrank.today;\n\t\ttotal.alcohol = justDrank.alcohol;\n\t\ttotal.calories = justDrank.calories;\n\t\ttotal.sugar = justDrank.sugar;\n\t\ttotal.price = justDrank.price;\n\n\t}\n\telse\n\t{\n\t\ttotal.drinks.push(justDrank);\n\t\ttotal.day += justDrank.today;\n\t\ttotal.alcohol += justDrank.alcohol;\n\t\ttotal.calories += justDrank.calories;\n\t\ttotal.sugar += justDrank.sugar;\n\t\ttotal.price += justDrank.price;\n\n\t}\n}",
"function addItem(item) {\n item.order = this;\n var items = this.orderItems;\n if (items.indexOf(item) == -1) {\n items.push(item);\n }\n }",
"function addNewItem(product) {\n var item = orderItemType.createInstance();\n item.order = this;\n item.product = product;\n this.orderItems.push(item);\n return item;\n }",
"handleBuy(e) {\n e.preventDefault();\n let quantity = 0, price = 0;\n let items = [];\n let order = _.get(this.state, 'cart');\n if (!order.length) {\n alert('Please select at least one product');\n return; \n } else {\n order.map((item, index) => {\n price += item.product_price;\n quantity++;\n items.push(item.product_id);\n });\n }\n let url = 'http://localhost:3000/orders/';\n Request.post(url)\n .send({\n quantity,\n price,\n items\n })\n .end((error, response) => {\n if (error || !response.ok) {\n } else {\n }\n this.setState({\n cart: [],\n orders: this.getOrders()\n })\n });\n }",
"createDepartmentStockIssueHistory() {\n this.NewDepartmentStockIssueHistory.dateReceived = new Date();\n this.NewDepartmentStockIssueHistory.departmentId = this.department.id;\n this.NewDepartmentStockIssueHistory.stockItemId = this.stockItem.id;\n // this.NewDepartmentStockIssueHistory.SubmissionDate = new Date();\n }",
"addItemOnPress() {\n var receipt = this.state.receipt;\n receipt.addNewItem(\n this.state.quantityFieldValue,\n this.state.nameFieldValue,\n this.state.pricePerUnitFieldValue\n )\n\n this.setState({\n receipt: receipt\n })\n\n receipt.save()\n }",
"function addItemToWishList(){\n\n\t\t\t\tconsole.log(wishlist);\n\t\t//increase the quantity of the item in case same item is added//\n\t\t\t\tfor (var i in wishlist){\n\t\t\t\t\tif (wishlist[i].name === name){\n\t\t\t\t\t\tif (wishlist[i].size === size){\n\t\t\t\t\t\t\tif (wishlist[i].flavors === flavors){\n\t\t\t\t\t\t\t\twishlist[i].quantity += quantity;\n\t\t\t\t\t\treturn;\n\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\t\t\n\t\t\t\t}\n\t\t\t\tif (wishlist === null){\n\t\t\t\t\twishlist = [];\n\t\t\t\t}\n\t\t\t\t//push new item to wishlist//\n\t\t\t\tvar item = new Item ();\n\t\t\t\tconsole.log(wishlist);\n\t\t\t\tconsole.log(item);\n\t\t\t\twishlist.push(item);\n\t\t\t\tsaveWishList();\n\t\t\t}",
"function addItem(item){\n basket.push(item);\n return true;\n}",
"async getOrCreateBasket() {\n const customerBaskets = await api.shopperCustomers.getCustomerBaskets({\n parameters: {customerId: customer?.customerId}\n })\n\n if (Array.isArray(customerBaskets?.baskets)) {\n return setBasket(customerBaskets.baskets[0])\n }\n\n // Back to using ShopperBaskets for all basket interaction.\n const newBasket = await api.shopperBaskets.createBasket({})\n setBasket(newBasket)\n }",
"setDate() {\n // Do nothing if the model doesn't have date fields\n if (_.isUndefined(this.defaults.created)) {\n return;\n }\n\n this.set('updated', Date.now());\n this.set('created', this.get('created') || Date.now());\n }",
"addItemToCartGuest({commit}, data){\n commit('ADD_TO_CART', data)\n }",
"basketAdd(equipment) {\n equipmentBasket.push(equipment);\n this.specify();\n }",
"async handleOrderItemCreatedEvent(data={}) {\n let {orderItem,trackId} = data,\n logger = Logger.create(\"handleOrderItemCreatedEvent\", trackId);\n\n logger.info(\"enter\", {orderItem});\n\n // @WARNING : We do not modify stock for orders items generated\n // from list subscriptions.\n if(orderItem.listSubscription) {return;}\n\n // Decrement product stock.\n logger.debug(\"decrement stock for product\", orderItem.product);\n\n this.collection.findOneAndUpdate({\n _id: Mongo.toObjectID(orderItem.product),\n deletedAt: {$type: \"null\"}\n }, {$inc: {stock: -(orderItem.quantity)}}, {returnOriginal: false})\n .then((result) => {\n let product = result.value;\n\n logger.debug(\"product stock updated\", product);\n\n // Emit to users\n Socket.shared.emit(\"product:updated\", {\n result: FindHandler.Model.format(product),\n updatedKeys: [\"stock\"]\n });\n });\n }",
"addNewItem() {\n\t\tconst newItem = {itemName: \"\", tag: \"None\", description:\"\", price:\"\", pic:\"\"};\n\t\tthis.setState((prevState, props) => ({\n\t\t\titems: prevState.items.concat(newItem)\n\t\t}))\n\t}",
"addItem(item) {\n let newItem = { ...item, id: uuidv4() }; //taking the existing item with only name and id coming from the form and adding an id field\n this.setState(state => ({\n items: [...state.items, newItem] //spread operator syntax, it sets items to be all the existing state items plus the new item\n }));\n }",
"function basket_add(produkt_id){\n var found = false;\n if (!basket_increase_amount(produkt_id, 1)){\n var item = {\n productId: produkt_id,\n amount: 1,\n stock: 10,\n customerId: gkid,\n };\n basket.push(item);\n basket_update();\n }\n}",
"function massageOrderData(order_data) {\n const orders = [];\n for(let i = 0; i < order_data.length; i += 5) {\n\n let t, message, diff;\n \n t = new Date(order_data[i + 4]);\n diff = Math.floor((t - new Date()) / 60000);\n\n if(diff > 0) {\n message = C.MESSAGE_TO_CUSTOMER(diff);\n }\n else if(isNaN(diff)) {\n message = order_data[i + 4];\n }\n else {\n message = 'Ready for pickup.';\n }\n \n\n orders.push({\n id: order_data[i],\n time_stamp: order_data[i + 1],\n total: order_data[i + 2],\n items: order_data[i + 3],\n status: message \n });\n } \n return orders;\n }",
"setDate(now = new Date()) {\n let startDay = new Date(now.getFullYear(), now.getMonth(), 1).getDay() - 1;\n startDay = startDay < 0 ? 6 : startDay;\n\n this.date = {\n year: now.getFullYear(),\n month: now.getMonth(),\n day: now.getDate(),\n startDay: startDay,\n daysOfMonth: new Date(now.getFullYear(), now.getMonth()+1, 0).getDate()\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION NAME : portSlotContent AUTHOR : Krisfen G. Ducao DATE : March 7, 2014 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : PARAMETERS : | function portSlotContent(){
var content = "";
var a = conterninfor.num
var addinfo = conterninfor.str
content += "<table "+addinfo+" id='tabs-"+a+"-slot"+GlobalSlotId+"'";
content += " class='infoshowhide'>";
content += "<tr><td style='width: 90px;'>";
content += "<p>Physical port type: <br></td><td><br>";
content += "<select id='porttypeinfo"+a+"' ";
content += "data-mini='true' style='width: 150px;'>";
content += "<option value=''>Layer 1</option>";
content += "<option value=''>Layer 2</option>"
content += "<option value=''>Open Port</option>";
content += "<option value=''>Direct connect";
content += "</option></select>";
content += "</p><br></td><td><br><p>Media type</p><br></td>";
content += "<td><br><p><select></select></p><br></td>";
content += "</tr><tr><td><p>Port name: <br></td><td><br>";
content += "<input id='portnamenumber"+a+"' ";
content += "type='text'/></p><br></td>";
content += "</tr><tr><td style='width: 90px;'><br>";
content += "<p>Sub chanel</p></td></tr></table>";
return content
} | [
"function slotPOrtContent(num,id,name,limit){\n\tvar tab = \"\";\n\tvar msg = \"Port per device is over the limit.\\nMaximum ports perr device is 256\"\n\t$('#devicetypetabs').tabs();\n\tif (num>=limit) {\n\t\terror(msg,\"Notification\")\t\n\t\tvar val = 0;\t\n\t\t$('#portperdevice').val(\"\");\n\t}\n\tif(num==\"\"){return 0;}\n\tfor(var a=1; a<=num; a++){\n\t\ttab +=\"<li id='\"+id+a+\"' style='display:none'\";\n\t\ttab +=\" style='width: auto;'\";\n\t\ttab +=\" onclick=\\\"slotPortInfoShow('\"+id+a+\"','\"+a+\"')\\\" \";\n\t\ttab +=\"class='ui-tabs-anchor ui-state-default ui-corner-top plimitshow'>\";\n\t\ttab +=\"<a href='#tabs-\"+a+\"' style='color: \";\n\t\ttab +=\"white;font-weight: bold;'>\"+name+a+\"</a></li>\";\t\n\t}\n\tvar ret = ({tabs:tab});//,contents:content});\n\treturn ret;\n}",
"function modulePortContent(num,id,name,limit){\n\tvar tab = \"\";\n\tvar msg = \"Port per device is over the limit.\\nMaximum ports perr device is 256\"\n\t$('#devicetypetabs').tabs();\n\tif (num>=limit) {\n\t\terror(msg,\"Notification\")\t\n\t\tvar val = 0;\t\n\t\t$('#portperdevice').val(\"\");\n\t}\n\tif(num==\"\"){return 0;}\n\tfor(var a=1; a<=num; a++){\n\t\ttab +=\"<li id='\"+id+a+\"' style='display:none'\";\n\t\ttab +=\" style='width: auto;'\";\n\t\ttab +=\" onclick=\\\"slotPortInfoShow('\"+id+a+\"','\"+a+\"')\\\" \";\n\t\ttab +=\"class='ui-tabs-anchor ui-state-default ui-corner-top plimitshow'>\";\n\t\ttab +=\"<a href='#tabs-\"+a+\"' style='color: \";\n\t\ttab +=\"white;font-weight: bold;'>\"+name+a+\"</a></li>\";\t\n\t}\n\tvar ret = ({tabs:tab});//,contents:content});\n\treturn ret;\n\n}",
"function dynamicSlotTab(num,id,name,limit,type){\n\tvar tab = \"\";\n\tvar msg = \"Port per device is over the limit.\\n\"\n\tmsg += \"Maximum ports perr device is 256.\"\n\tif (num>=limit) {\n\t\terror(msg,\"Notification\")\t\n\t\tvar val = 0;\t\n\t\treturn 0;\n\t}\n\tif(num==\"\"){return 0;}\n\tfor(var a=1; a<=num; a++){\n\t\tif (type ==\"slotport\"){\n\t\t\ttab +=\"<li id='\"+id+a+\"' style='display:none'\";\n\t\t\ttab +=\" style='width: auto;'\";\n\t\t\ttab +=\" onclick=\\\"slotinfoshow('\"+id+a+\"','\"+a+\"','slotport')\\\" \";\n\t\t\ttab +=\"class='ui-tabs-anchor ui-state-default ui-corner-top splimitshow'>\";\n\t\t\ttab +=\"<a href='#tabs-\"+a+\"' style='color: \";\n\t\t\ttab +=\"white;font-weight: bold;'>\"+name+a+\"</a></li>\";\t\n\t\t}else if (type==\"slotmodule\"){\n\t\t\ttab +=\"<li id='\"+id+a+\"' style='display:none'\";\n\t\t\ttab +=\" style='width: auto;'\";\n\t\t\ttab +=\" onclick=\\\"slotinfoshow('\"+id+a+\"','\"+a+\"','slotmodule')\\\" \";\n\t\t\ttab +=\"class='ui-tabs-anchor ui-state-default ui-corner-top splimitshow'>\";\n\t\t\ttab +=\"<a href='#tabs-\"+a+\"' style='color: \";\n\t\t\ttab +=\"white;font-weight: bold;'>\"+name+a+\"</a></li>\";\t\n\n\t\t}\n\t}\n\tvar ret = ({tabs:tab});//,contents:content});\n\treturn ret;\n\n\n}",
"function slotPortInfoShow(id,val){\n $(\".infoshowhide\").hide();//Hide content\n $(\"#infoshowhide-\"+val+\"\").show();//Show content\n for(var a=1; a<=257; a++){\n \t$(\"#slot-port-\"+a+\" li a\").css(\"color\",\"#fffff\");\n\t}\n $(\"#\"+id+\" a\").css(\"color\",\"#00000\");\n\t//$(\"#tabs-\"+val+\"-slot\").show();\n\t$(\"#tabs-\"+val+\"-slot\"+GlobalSlotId).show();\n}",
"function viewNewPortInfo(portIndex)\r\n{\r\n document.getElementById(\"portInfoCard\").style.display = \"block\";\r\n\tdocument.getElementById(\"portNameCard\").innerText = newPortList[portIndex].name;\r\n\tdocument.getElementById(\"country\").innerText = newPortList[portIndex].country;\r\n document.getElementById(\"type\").innerText = newPortList[portIndex].type;\r\n document.getElementById(\"size\").innerText = newPortList[portIndex].size;\r\n document.getElementById(\"locPrecision\").innerText = newPortList[portIndex].locprecision;\r\n document.getElementById(\"lat\").innerText = newPortList[portIndex].lat;\r\n document.getElementById(\"lng\").innerText = newPortList[portIndex].lng;\r\n\r\n}",
"function portContentMobile(){\n\tvar content = \"\";\n\tcontent += \"<table \";\n\tcontent += \" class='infoshowhide' style='width: 100%;'>\";\n\tcontent += \"<tr><td><table><tr>\"\n\tcontent += \"<td style='width: 20px;' !important;></td>\";\n\tcontent += \"<td style='width: 150px;'>\";\n\tcontent += \"Port type: <br></td><td><br>\";\n\tcontent += \"<select id='porttypeinfo1' onchange='appendToArrayInfo()'\";\n\tcontent += \" data-mini='true' style='width: 150px;'>\";\n\tcontent += \"<option value=''></option>\"+GlobalDevicePortType+\"</select>\";\n\tcontent += \"<br></td><td><br>Media type<br></td>\";\n\tcontent += \"<td><br><select id='mediatype' onchange='appendToArrayInfo()'><option value=''></option>\"+GlobalMedia+\"</select><br /></td>\";\n\tcontent += \"</tr><tr><td style='width: 20px;'></td>\";\n\tcontent += \"<td style='width: 150px;'>Port name: <br></td><td>\";\n\tcontent += \"<input id='portnamenumber' \";\n\tcontent += \"type='text' onblur='appendToArrayInfo()'/><br>\";\n\tcontent += \"</td></tr><tr><td style='width: 20px;'></td></tr></table></td></tr>\";\n\tcontent += \"<tr><td><table style='width: 100%;' cellspacing='10'><tr><td style='width: 100%;'> <fieldset style='border:2px solid #1c5a8d;border-radius:10px;overflow:auto;'>\";\n content += \"<legend style='margin-left:20px;'>Map Partner Port</legend>\";\n content += \"<table cellspacing='10' id='newDeviceinfo' style='width: 100%; overflow:auto;margin-left:15px;text-align:center;width:95%'><br><tr><td>\";\n\tcontent += \"Host Name: <select id='partnerhostname' onchange='appendToArrayInfo();checkHostIpaddress(this.value);'\";\n content += \"data-mini='true' style='width: 150px;'></select>\";\n\tcontent += \"Ip Address: <input id='partneripaddress' onchange='appendToArrayInfo()'\";\n content += \" style='width: 150px;'></input>\";\n\tcontent += \"</td><td>Slot Number: <select id='partnerslot' onchange='appendToArrayInfo(); checkSlotPortNumber();' data-mini='true' style='width: 150px;'></select>\";\n\tcontent += \"Port Name: <select id='partnerportinfo' onchange='appendToArrayInfo();' data-mini='true' style='width: 150px;'></select>\";\n\tcontent += \"</td></tr></table>\"\n\tcontent += \"</fieldset></td></tr></table></td></tr>\";\n\tcontent +=\t\"</table>\";\n\treturn content\n}",
"function dynamicPortTab(num,id,name,limit){\n\tvar tab = \"\";\n\tvar msg = \"Port per device is over the limit.\\n\"\n\tmsg += \"Maximum ports perr device is 256.\"\n\tif (num>=limit) {\n\t\terror(msg,\"Notification\")\t\n\t\tvar val = 0;\t\n\t\treturn 0;\n\t}\n\tif(num==\"\"){return 0;}\n\tfor(var a=1; a<=num; a++){\n\t\ttab +=\"<li id='\"+id+a+\"' style='display:none'\";\n\t\ttab +=\" style='width: auto;'\";\n\t\ttab +=\" onclick=\\\"portinfoshow('\"+id+a+\"','\"+a+\"')\\\" \";\n\t\ttab +=\"class='ui-tabs-anchor ui-state-default ui-corner-top plimitshow'>\";\n\t\ttab +=\"<a href='#tabs-\"+a+\"' style='color: \";\n\t\ttab +=\"white;font-weight: bold;'>\"+name+a+\"</a></li>\";\t\n\t}\n\tvar ret = ({tabs:tab});//,contents:content});\n\treturn ret;\n\n}",
"function portdynamictab(val){\n\tvar pageval = val/10;\n\tif (pageval > Math.floor(pageval)) {\n\t\tvar pageval = pageval + 1;\n\t\tvar pageval = parseInt(pageval);\t\t\n\t}\n\tvar pageinfo = \"\";\n\tfor(var a=1; a<=pageval; a++){\n\t\tpageinfo +=\"<option value='\"+a+\"'>\"+a+\"</option>\"\n\t}\n\tif($(\"#dropdownstruction\").val() == \"devport\"){\n\t\tglobalTabId = \"port\";\n\t\tvar ret = createdynamictab(val,\"newportid\",\"Port \",257);\n\t\tvar con = createDynamictabContent(val,257,\"portcontent();\");\n\t}else if($(\"#dropdownstruction\").val() == \"devslotport\"){\n\t\tglobalTabId = \"slot\";\n\t\tvar ret = createSlotTab(val,\"newslotid\",\"Slot \",257);\n\t\tvar con = createDynamictabContent(val,257,\"slotContent();\");\n\t}else if($(\"#dropdownstruction\").val() == \"devmodport\"){\n\t\tglobalTabId = \"module\";\t\n\t\tvar ret = createdynamictab(val,\"newportid\",\"Module \",257);\n\t\tvar con = createDynamictabContent(val,257,\"moduleContent();\");\n\t}else if($(\"#dropdownstruction\").val() == \"devslotmod\"){\n\t\tglobalTabId = \"slotmodule\";\n\t\tvar ret = createdynamictab(val,\"newportid\",\"Slot \",257);\n\t\tvar con = createDynamictabContent(val,257,\"slotModuleContent();\");\n\t}else{\n\t\tvar ret = createdynamictab(val,\"newportid\",\"Rack \",257);\n\t\tvar con = createDynamictabContent(val,257,\"rackContent();\");\n\t}\n\tvar tabs = ret.tabs\n\tvar contents = con.contents\n\t$(\"#tabspage\").empty().append(pageinfo);\n\t$(\"#porttabs\").empty().append(tabs);\n\t$(\"#portinfotabs\").empty().append(contents);\n\t$('#devicetypetabs').tabs();\n\tif($(\"#dropdownstruction\").val() == \"devport\"){\n\t\tlimittabsshow(1,\"newportid\",val);\n\t}else if($(\"#dropdownstruction\").val() == \"devslotport\"){\n\t\tlimittabsshow(1,\"newslotid\",val);\n\t}else{\n\t\tlimittabsshow(1,\"newslotid\",val);\n\t}\n}",
"function DeviceSlot() {}",
"function dynamicModuleTab(num,id,name,limit,type){\n\tvar tab = \"\";\n\tvar msg = \"Port per device is over the limit.\\n\"\n\tmsg += \"Maximum ports perr device is 256.\"\n\tif (num>=limit) {\n\t\terror(msg,\"Notification\")\t\n\tval = 0;\t\n\t\treturn 0;\n\t}\n\tif(num==\"\"){return 0;}\n\tfor(var a=1; a<=num; a++){\n\t\tif (type == \"slotmodule\"){\n\t\t\ttab +=\"<li id='\"+id+a+\"' style='display:none'\";\n\t\t\ttab +=\" style='width: auto;'\";\n\t\t\ttab +=\" onclick=\\\"moduleinfoshow('\"+id+a+\"','\"+a+\"','slotmodule')\\\" \";\n\t\t\ttab +=\"class='ui-tabs-anchor ui-state-default ui-corner-top splimitshow'>\";\n\t\t\ttab +=\"<a href='#tabs-slot-\"+a+\"' style='color: \";\n\t\t\ttab +=\"white;font-weight: bold;'>\"+name+a+\"</a></li>\";\t\n\n\t\t}else{\n\t\t\ttab +=\"<li id='\"+id+a+\"' style='display:none'\";\n\t\t\ttab +=\" style='width: auto;'\";\n\t\t\ttab +=\" onclick=\\\"moduleinfoshow('\"+id+a+\"','\"+a+\"')\\\" \";\n\t\t\ttab +=\"class='ui-tabs-anchor ui-state-default ui-corner-top splimitshow'>\";\n\t\t\ttab +=\"<a href='#tabs-\"+a+\"' style='color: \";\n\t\t\ttab +=\"white;font-weight: bold;'>\"+name+a+\"</a></li>\";\t\n\t\t}\n\t}\n\tvar ret = ({tabs:tab});//,contents:content});\n\treturn ret;\n}",
"function checkSlotPortNumber(){\n\tvar ipadd = GlobalMapPort.MAINCONFIG[0].DEVICE\t\n\tvar slot = \"\";\n\tvar newslot = \"\";\n\tvar slotnumber = $(\"#partnerslot\").val();\n\tvar ports = \"\";\n\tvar port = \"\";\n\tvar portid = \"\";\n\tvar val = $(\"#partnerhostname\").val();\n\tfor (var a=0; a<ipadd.length; a++){\n\t\thost = ipadd[a].HostName\n\t\tvar ip = ipadd[a].IpAddress\n\t\tif(val == host){\n\t\t\tfor (var x=0; x<ipadd[a].SLOT.length; x++){\n\t\t\t\tnewslot = ipadd[a].SLOT[x].Number;\n\t\t\t\tif(slotnumber==newslot){\n\t\t\t\t\tfor (var z=0; z<ipadd[a].SLOT[x].PORT.length; z++){\n\t\t\t\t\t\tport = ipadd[a].SLOT[x].PORT[z].PortName\n\t\t\t\t\t\tportid = ipadd[a].SLOT[x].PORT[z].PortId\n\t\t\t\t\t\tports += \"<option value='\"+port+\"_\"+portid+\"'>\"+port+\"</option>\"\t\n\t\t\t\t\t}\n\t\t\t\t\t$(\"#partnerportinfo\").empty().append(ports);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n}",
"function generatePortList()\r\n{\r\n\r\n\tlet output = \"\";\r\n\r\n //create row for local port\r\n for (let j = 0; j < newPortList.length; j++)\r\n\t{\r\n output += \"<tr>\"\r\n output += \"<td onmousedown=\\\"viewNewPortInfo(\"+j+\")\\\" class=\\\"full-width mdl-data-table__cell--non-numeric\\\">\"\r\n output += \"<b>*NEW PORT*</b><br><br>\"\r\n output += \"Port Name: \" + newPortList[j].name ;\r\n output += \"<div class=\\\"subtitle\\\">\" + \"Country: \" + newPortList[j].country +\"<br><br><b>VIEW</b></div></td></tr>\";\r\n\t}\r\n\r\n //create row for port from API\r\n\tfor (let i = 0; i < portList.length; i++)\r\n\t{\r\n output += \"<tr>\"\r\n output += \"<td onmousedown=\\\"viewPortInfo(\"+i+\")\\\" class=\\\"full-width mdl-data-table__cell--non-numeric\\\">\"\r\n output += \"Port Name: \" + portList[i].name ;\r\n output += \"<div class=\\\"subtitle\\\">\" + \"Country: \" + portList[i].country +\"<br><br><b>VIEW</b></div></td></tr>\";\r\n\t}\r\n\r\n return output\r\n}",
"_findInnerSlotInfos() {\n return Array.from(this._dom.querySelectorAll(\"[slotid]\")).map(s => {\n return {\n context: s,\n id: s.getAttribute('slotid')\n }\n });\n }",
"function Window_SlotInstruction() {\n this.initialize.apply(this, arguments);\n}",
"_addSlot() {\n if (this[_value]) {\n this[_fillElement].appendChild(this[_slotElement]);\n } else {\n this[_trackElement].appendChild(this[_slotElement]);\n }\n }",
"function SetContent(selectedContentNumber) {\n\n SetPicture(selectedContentNumber);\n SetDescriptionText(selectedContentNumber);\n\n}",
"_processNodes(){\n this.shadowRoot\n .querySelector('slot')\n .assignedNodes()\n .forEach((n) => this._processNode(n));\n }",
"function addNodeVideoSequence(nodeId) {\n\t\t\t\tvar res =\"\",\n\t\t\t\t\tseq_type,\n\t\t\t\t\tmyObj;\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tmyObj=contentObj[nodeId].sequences[FS.currentSequence];\n\t\t\t\t\tseq_type=myObj.type;\n\t\t\t\t\tif (FS.currentSequence == 0) {res =\"<div class='row' id='seqWrapper'>\"}\n\n\t\t\t\t\tswitch (seq_type) {\n\t\t\t\t\t\tcase \"video\":\n\t\t\t\t\t\t\tres +=\"<div class='centered eleven columns'><div class='loading' id='loader_0'><div class='track'></div><div class='spinner'><div class='mask'><div class='maskedCircle'></div></div></div></div>\";\n\t\t\t\t\t\t\tres +=\"<article class='vimeo video videoBg'>\";\n\t\t\t\t\t\t\tres +=\"<iframe id='iframe_\"+myObj.sequenceID+\"' style='visibility:hidden;' onload='FS.showIframe(\"+myObj.sequenceID+\")' \";\n\t\t\t\t\t\t\tres += \"src='\" + myObj.url + \"?title=0&byline=0&portrait=0&autoplay=1&api=1&player_id=iframe_\"+myObj.sequenceID+\"' width='500' height='281' frameboder='0' webkitallowfullscreen='' mozallowfullscreen='' allowfullscreen=''>\";\n\t\t\t\t\t\t\tres +=\"</iframe></article></div>\";\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"question\":\n\t\t\t\t\t\t\tres +=\"<div class='centered eleven columns'>\";\n\t\t\t\t\t\t\tres +=\"<article class=''>\";\n\t\t\t\t\t\t\tres +=\"<div class='sequenceHeadline'>\"+myObj.text +\"</div>\";\n\t\t\t\t\t\t\tfor (var i=0; i<_.size(myObj.answers); i++) {\n\t\t\t\t\t\t\t\tres +=\"<div class='sequenceAnswer videoQuestion' onClick='FS.gotoSequence(\"+myObj.answers[i].gotoID+\")'>\"+ myObj.answers[i].text +\"</div>\";\n\t\t\t\t\t\t\t//if(myObj.answers[1]!=undefined) res +=\"<div class='sequenceAnswer videoQuestion' onClick='FS.gotoSequence(\"+myObj.answers[1].gotoID+\")'>\"+ myObj.answers[1].text +\"</div>\";\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tres +=\"</article></div>\";\n\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\tres +=\"<div class='centered eleven columns'>\";\n\t\t\t\t\t\t\tres +=\"<article class=''>\";\n\t\t\t\t\t\t\tif (myObj.header!=undefined) res +=\"<div class='sequenceHeadline'>\"+myObj.header +\"</div>\";\n\t\t\t\t\t\t\tif (myObj.content!=undefined) res +=\"<div class='sequenceText'>\"+ myObj.content +\"</div>\";\n\t\t\t\t\t\t\tres +=\"</article></div>\";\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\n\n\n\t\t\t\t\t}\n\t\t\t\t\tif (FS.currentSequence == 0) res+=\"</div>\"\n\t\t\t\t\n\t\t\t\treturn res;\n\t\t\t}",
"slot$(name,ctx){\n\t\tvar slots_;\n\t\tif (name == '__' && !this.render) {\n\t\t\treturn this;\n\t\t}\t\t\n\t\treturn (slots_ = this.__slots)[name] || (slots_[name] = imba$1.createLiveFragment(0,null,this));\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find and return the dog breed with the highest count | function findMax() {
var max = dog.data[0].count;
var winner = dog.data[0];
for (var i = 0; i < dog.data.length; i++) {
if (dog.data[i].count > max) {
max = dog.data[i].count
winner = dog.data[i]
}
}
return winner;
} | [
"function mostProlificAuthor(authors) {\n // Your code goes here\n\n let x = bookCountsByAuthor(authors);\n // console.log(x);\n\n const compare = (a, b) => {\n let comparison = 0;\n if (a.bookCount > b.bookCount) {\n comparison = 1;\n } else if (a.bookCount < b.bookCount) {\n comparison = -1;\n }\n return comparison;\n };\n let y = x.sort(compare);\n console.log(y);\n\n return y.pop();\n\n // let x = authors.map(author => author.books.length);\n // console.log(x);\n // // let y = Math.max(...x);\n // // return authors.forEach(author => {\n // // if (author.books.length === y) {\n // // console.log(author.name);\n // // }\n // // });\n\n // if (bookCountsByAuthor(authors).bookCount)\n}",
"function best( dict ) {\n\t\tvar id, result, max = -Infinity;\n\t\tfor ( id in dict ) {\n\t\t\tif ( dict[id] > max ) {\n\t\t\t\tresult = id;\n\t\t\t\tmax = dict[ id ];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}",
"function bestHit(hits) {\n\t\tvar max = Number.MIN_VALUE, pos,\n\t\t\t\ti, tmp;\n\t\tfor (i = 0; i < hits.length; i++) {\n\t\t\ttmp = hits[i].count;\n\t\t\tif (tmp > max) {\n\t\t\t\tmax = tmp;\n\t\t\t\tpos = i;\n\t\t\t}\n\t\t}\n\t\treturn hits[pos];\n\t}",
"function getMostPopular() {\n\tmoviesAbove70 = [];\n\t//clears array at the start to ensure no constant addons\n\tfor (movie in movieData) {\n\t\tlet fileName = path.join(\"jsonData/movies/\" + movieData[movie].Title);\n\n\t\tif (fs.existsSync(fileName)) {\n\t\t\tlet data = fs.readFileSync(fileName);\n\t\t\tlet movData = JSON.parse(data);\n\n\t\t\tif (movData.imdbRating > 7) {\n\t\t\t\tmoviesAbove70.push(movieData[movie]);\n\t\t\t}\n\n\t\t} else {\n\t\t\tres.status(404).send(\"Could not find Movie.\");\n\t\t}\n\t}\n}",
"function mostFrequentItem(array) {\n\n let last = 0;\n let lastIndex = -1;\n for (let i = 0; i < array.length; i++) {\n let current = 0;\n for (let k = 0; k < array.length; k++) {\n if (array[k] == array[i]) {\n current++;\n }\n }\n if (current > last) {\n last = current;\n lastIndex = i;\n }\n }\n console.log(`Most frequent item: ${array[lastIndex]} -> ${last} times.`);\n}",
"function biggestCompanyName() {\n return _.reverse(_.sortBy(groupByCompany(), ['users.length'])).splice(0, 1)[0].name\n}",
"findMaxEdgeValue(){\n let heaviestEdgeWeight = 0;\n for (let edge of this.props.edges) {\n if (edge.weight > heaviestEdgeWeight) {\n heaviestEdgeWeight = edge.weight;\n }\n }\n return heaviestEdgeWeight;\n }",
"function maxID(){\n var res = 0;\n for(var i = 0; i < employees.length; i++){\n if(employees[i].id > res){\n res = employees[i].id;\n }\n }\n return res;\n}",
"function mostFollowers(){\n var mostFollowersPersonId = 0;\n var maxNumFollowers = 0;\n for(var person in data){\n var followersNumber = getFollowers(person).length;\n if(maxNumFollowers <= followersNumber){\n maxNumFollowers = followersNumber;\n mostFollowersPersonId = person;\n }\n }\n console.log(\"The person with most followers is: \" + data[mostFollowersPersonId].name);\n\n}",
"highestScoringWord() {\n let example = Scrabble.highestScoreFrom(this.plays);\n return example;\n }",
"highestWordScore() {\n let highestWord = this.highestScoringWord();\n return Scrabble.score(highestWord);\n }",
"function findMaxOpponentHealth(largestValue) {\n const opponentCards = document.querySelectorAll('.computer-cardinplay')\n const numOfOpponentCards = computerCardSlot2.childElementCount;\n const alliedCards = document.querySelectorAll('player-cardinplay')\n const numOfAlliedCards = playerCardSlot.childElementCount;\n let healthValues = []\n let biggestValue = 0\n for(let i=0; i<opponentCards.length; i++) {\n healthValues.push(opponentCards[i].children[1].children[0].innerText);\n }\n for(let i=0; i<healthValues.length; i++) {\n if(opponentCards[i].children[0].children[0].innerText > biggestValue) {\n biggestValue = opponentCards[i].children[1].children[0].innerText;\n }\n }\n for (let i=0; i<largestValue; i++) {\n let index = healthValues.indexOf(biggestValue);\n healthValues.splice(index, 1);\n for(let i=0; i<healthValues.length; i++) {\n if(opponentCards[i].children[0].children[0].innerText > biggestValue) {\n biggestValue = opponentCards[i].children[1].children[0].innerText;\n }\n }\n }\n for(let i=0; i<opponentCards.length; i++) {\n if(opponentCards[i].children[1].children[0].innerText == biggestValue) {\n return opponentCards[i]\n }\n }\n return true\n}",
"function mostPopularDays(week) {\n\tif (week == null || week.length == 0){\n\t\tconsole.log ('mostPopularDays() - null or empty input');\n\t\treturn null;\n\t}\n\t\n\tvar maxDay = new Weekday(\"\",0);\n\t// first pass -- just try to print max\n\tfor (var i = 0; i < week.length; i++) {\n\t\t// current object is week[i]\n\t\tvar today = week[i];\n\t\t//console.log('item = ' + i + ' name= ' + today.name + ' traffic = ' + today.traffic);\n\t\t// is today the new max?\n\t\tif (today.traffic > maxDay.traffic) {\n\t\t\tmaxDay.traffic = today.traffic;\n\t\t\tmaxDay.name = today.name;\n\t\t}\n\t\n\t}\n\tconsole.log('Most popular is ' + maxDay.name + ' with traffic of ' + maxDay.traffic + ' days');\n\treturn maxDay.name\n}",
"function mostTitle(characters) {\n let count = 0;\n let name = [];\n let nameWithSameNumbers = [];\n characters.forEach(function (array) {\n if (array.titles.length > count) {\n count = array.titles.length;\n name = array.name;\n }\n });\n characters.forEach(function (array) {\n if (count === array.titles.length) {\n nameWithSameNumbers.push(array.name);\n }\n });\n // console.log(name);\n return [`Who has the most titles?: ${nameWithSameNumbers}`, `Number of titles: ${count}`];\n}",
"getCatHighest(cat) {\n cat = JSON.parse(JSON.stringify(this.categories.filter(c => c.name === cat)[0]));\n cat.grades.forEach(element =>{\n if (element.pointsEarned === undefined || element.notYetGraded){\n element.pointsEarned = element.maxPoints + (element.possibleExtraScore ? element.possibleExtraScore : 0);\n }\n })\n return this.getCatGrade(cat,false);\n }",
"function sortDessertsByPopularity(dessertObject) {\n let dessertArray = Object.values(dessertObject)\n let countObject = {}\n\n dessertArray.forEach((dessert) =>{\n countObject[dessert] = 0\n })\n\n dessertArray.forEach((dessert) =>{\n countObject[dessert] = countObject[dessert] + 1\n })\n console.log('this is the count object', countObject)\n\n let keysArray = Object.keys(countObject);\n\n\n return keysArray.sort((a,b) =>{\n console.log('this is a',a) //a is a dessert\n console.log('this is b',b)\n let countA = countObject[a] //this is the number of the a variable dessert\n let countB = countObject[b]\n // console.log('this is countA', countA)\n // console.log('this is countB', countB)\n if (countA < countB){ //if the number of a desserts is inferior to b desserts, keep a and b in order, else switch them\n return 1\n } else {\n return -1\n }\n })\n}",
"function FindMostHelpfulReview(gameReviews){\n if(gameReviews == undefined)\n return;\n if(gameReviews.reviews[0] == undefined)\n return;\n let currentScore = gameReviews.reviews[0].votes_up;\n let MostHelpfulReview = gameReviews.reviews[0];\n for (let i = 0; i < gameReviews.reviews.length; i++) {\n //gameReviews.reviews[i].review +\n //console.log(\" \" + gameReviews.reviews[i].votes_up + \" \" + gameReviews.reviews[i].votes_funny);\n if(currentScore <= gameReviews.reviews[i].votes_up){\n MostHelpfulReview = gameReviews.reviews[i];\n currentScore = gameReviews.reviews[i].votes_up;\n\n }\n }\n //console.log(gameReviews.reviews.length + \" Number of reviews2222\");\n //console.log(\"Resulting Highest Review: \" + MostHelpfulReview.review + \" Score\" + MostHelpfulReview.votes_up + \" Voted Up: \" + MostHelpfulReview.voted_up);\n if(MostHelpfulReview.votes_up == undefined)\n return undefined;\n return MostHelpfulReview;\n}",
"get maxHeight() {\n\t\tlet maxHeight = 0, height;\n\n\t\tfor (let i = 0; i < this.count; i++) {\n\t\t\tif (this.cache[i]) {\n\t\t\t\theight = this.cache[i];\n\t\t\t} else {\n\t\t\t\theight = this.traverse(i);\n\t\t\t\t\n\t\t\t\tthis.cache[i] = height;\n\t\t\t\tthis.cache[this.tree[i]] = height - 1;\n\t\t\t}\n\n\t\t\tmaxHeight = Math.max(maxHeight, height);\n\t\t}\n\n\t\treturn maxHeight;\n\t}",
"function findMaxPlayerHealth(largestValue) {\n const opponentCards = document.querySelectorAll('.computer-cardinplay')\n const numOfOpponentCards = computerCardSlot2.childElementCount;\n const alliedCards = document.querySelectorAll('.player-cardinplay')\n const numOfAlliedCards = playerCardSlot.childElementCount;\n let healthValues = []\n let biggestValue = 0\n for(let i=0; i<alliedCards.length; i++) {\n healthValues.push(alliedCards[i].children[1].children[0].innerText);\n }\n for(let i=0; i<healthValues.length; i++) {\n if(alliedCards[i].children[0].children[0].innerText > biggestValue) {\n biggestValue = alliedCards[i].children[1].children[0].innerText;\n }\n }\n for (let i=0; i<largestValue; i++) {\n let index = attackValues.indexOf(biggestValue);\n attackValues.splice(index, 1);\n for(let i=0; i<healthValues.length; i++) {\n if(alliedCards[i].children[0].children[0].innerText > biggestValue) {\n biggestValue = alliedCards[i].children[1].children[0].innerText;\n }\n }\n }\n for(let i=0; i<alliedCards.length; i++) {\n if(alliedCards[i].children[1].children[0].innerText == biggestValue) {\n return alliedCards[i]\n }\n }\n return true\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
======================================== | Websocket send END GAME | function sendEndGameMSG() {
let message = {
messageType: "END GAME",
};
theSocket.sendJSON(message);
} | [
"function end_game(){\n\tsocket.emit(\"leave_game\");\n}",
"function sendRoundEndMSG() {\n let message = {\n messageType: \"END ROUND\",\n };\n\n theSocket.sendJSON(message);\n}",
"leavePlayerChannel() {\n this.sendMessage('/playerchannel leave');\n }",
"function hostMessage() {\n if (websocket != null && websocket.readyState == 1) {\n var input = document.getElementById(\"gameID\").innerHTML.toString();\n var message = { messageType: 'HOST', message: input };\n websocket.send(JSON.stringify(message));\n }\n}",
"function restartGame(){\r\n\tsocket.emit(\"restart\");\r\n}",
"function endWebSocketConnection(ws, code, message) {\n try {\n console.log('Terminating socket');\n ws.end(code, message);\n } catch(err) {\n console.error('Error ending web socket connection');\n console.error(err);\n }\n}",
"function hangUp(){\r\n socket.emit(\"end\", ID, self);\r\n fetch(\"/end\", {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify({\r\n ID: ID\r\n })\r\n }).then(response => {\r\n response.redirected;\r\n window.location.href = response.url;\r\n });\r\n}",
"endTurn() {\n let gameState = gameEngine.endTurn();\n if (gameState.isGameOver()) {\n GameScript.gameOver(gameState);\n } else {\n GameScript.newTurn(gameState);\n }\n }",
"function wsCloseConnection(){\n\twebSocket.close();\n}",
"endGame() {\n // All timers must be cleared to prevent against server crashes during prematurely ended games.\n if (this.serverState !== undefined) {\n this.serverState.clearTimers();\n clearTimeout(this.currentForcedTimer);\n }\n\n this.serverState = undefined;\n this.playerMap.removeInactivePlayers();\n this.playerMap.doAll((player) => { player.reset(); });\n }",
"function receivePlayerRestart() {\n\tsocket.on('player restart', function(_) {\n\t console.log('player restart');\n\t restore();\n\t});\n }",
"function endCall() {\n setMessages([]);\n setChatUsers([]);\n socketRef.current.emit(\"leaveRoom\");\n socketRef.current = null;\n }",
"function sendQuestionClosedMSG() {\n let message = {\n messageType: \"QUESTION CLOSED\",\n };\n\n theSocket.sendJSON(message);\n}",
"function announceResults() {\n socket.sockets.emit(\"gameOver\");\n}",
"function stopHeartbeat() {\n\tGAME_OVER = true;\n\taddMessage(\"Game over! Score: &e0\", \"error\");\n\tdelete_cookie(\"chocolateChipCookie\");\n\tclearInterval(nIntervId);\n}",
"async endAllGames() {\n this.ended = true;\n for (const [key, game] of Object.entries(this.games)) {\n game.ended = true;\n game.currentLocation = this.endLocation;\n }\n let message = \"Het spel is gedaan.\";\n this.sendMessageToAllTeams(message);\n console.log(\"Games ended.\");\n }",
"function receivePlayerMove() {\n\tsocket.on('player move', function(index) {\n\t if (winflag) {\n\t\trestart();\n\t\twinflag = false;\n\t }\n\n\t playerMove(index);\n\n\t if (isOver()) {\n\t\twinflag = true;\n\t }\n\t});\n }",
"function onPlayerQuit() {\n const player = this.player;\n\n this.broadcast.to(player.roomCode).emit('player quit', player);\n}",
"function endGame(villagersWin) {\n console.log(\"Endgame called\");\n\n var cycleNumber = GameVariables.findOne(\"cycleNumber\").value - 1;\n var winnerText = \"\";\n\n if (villagersWin) {\n console.log(\"Villagers win\");\n winnerText = \"The Villagers have won!\";\n } else {\n console.log(\"Werewolves win\");\n winnerText = \"The Werewolves have won!\";\n }\n\n EventList.insert({type: \"info\", cycleNumber: cycleNumber, text: winnerText, timeAdded: new Date()});\n\n GameVariables.update(\"lastGameResult\", {$set: {value: villagersWin, enabled: true}});\n\n var players = Players.find({joined: true});\n var werewolfId = Roles.findOne({name: \"Werewolf\"})._id;\n\n // Let's set the variables for all the players that were in the game\n players.forEach(function(player) {\n Players.update(player._id, {$set: {seenEndgame: false, ready: false}});\n\n if (villagersWin) {\n if (player.role == werewolfId) {\n Players.update(player._id, {$set: {alive: false}});\n }\n } else {\n if (player.role != werewolfId) {\n Players.update(player._id, {$set: {alive: false}});\n }\n }\n });\n\n // Re-enable the lobby\n GameVariables.update(\"gameMode\", {$set: {value: \"lobby\"}});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/motors/guide/id/plot.html. Motor guide plot motors page, renders with guide/plot.hbs. | function doPlotPage(req, res, rockets) {
loadGuideResult(req, res, function(result) {
res.render('guide/plot', locals(req, defaults, {
title: "Motor Guide Motor Plot",
rockets: rockets,
result,
stats: RESULT_STATS,
firstStat: RESULT_STATS[0],
secondStat: RESULT_STATS[1],
summaryLink: '/motors/guide/' + result._id + '/summary.html',
chartLink: '/motors/guide/' + result._id + '/plot.svg',
}));
});
} | [
"function plotQtl(div, symptom){\n\t$.get('/scripts/plot_qtl/run?symptom='+symptom).done(function(data){\n\t\tvar data = extractBodyFromHTML(data);\n\t\t//var dataURI = createDataUri(data);\n\t\t$(div).html(data);\n\t\trunScanone();\n\t});\n}",
"constructor(p, x, y){\r\n\t\tsuper(\"plot\", x, y, \"Hoe\");\r\n\t\tthis.plot = p;\r\n\t}",
"plotExternalHTML(url, plot_name) {\n fetch(url)\n .then((response) => {\n if (response.ok) {\n return response.json()\n } else {\n throw new Error('Something went wrong');\n }\n })\n .then((responseJson) => {\n let data = JSON.parse(responseJson);\n this.newPlotWidgetIframe(plot_name, data.url);\n })\n .catch(error => console.log(error));\n }",
"function plot(can,ctx,x,y,xwidth,ywidth,options){\n\n}",
"function draw_plots(plot_list)\r\n{\r\n\r\n\t// get database ids for plots\r\n\tvar database_ids = []\r\n\tfor (var j=0; j < plot_list.length; j++) {\r\n\t\tdatabase_ids.push(plots_selected[plot_list[j]])\r\n\t}\r\n\r\n\t// get x, y limits for zoom for plots\r\n\tvar zoom_x = []\r\n\tvar zoom_y = []\r\n\tfor (var j=0; j < plot_list.length; j++) {\r\n\t\tzoom_x.push(plots_selected_zoom_x[plot_list[j]])\r\n\t\tzoom_y.push(plots_selected_zoom_y[plot_list[j]])\r\n\t}\r\n\r\n\t// compile selections into one list\r\n\tvar refresh_selections = [];\r\n\tfor (var k = 0; k < max_num_sel; k++) {\r\n\r\n\t // get current selection\r\n\t var curr_sel = selections.filtered_sel(k+1);\r\n\r\n\t // add to list, up to max number of plots\r\n\t for (var j = 0; j < Math.min(curr_sel.length, max_num_plots); j++) {\r\n\t\t refresh_selections.push (curr_sel[j]);\r\n\t }\r\n\r\n\t}\r\n\r\n\t// if selection is non-empty show display indicator\r\n\tfor (var j=0; j < plot_list.length; j++) {\r\n\t\tif (refresh_selections.length == 0) {\r\n\t\t\tplots_selected_displayed[j] = 0;\r\n\t\t} else {\r\n\t\t\tplots_selected_displayed[j] = 1;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// call to server to get subsampled data\r\n\tclient.post_sensitive_model_command(\r\n\t{\r\n\t\tmid: mid,\r\n\t\ttype: \"DAC\",\r\n\t\tcommand: \"subsample_time_var\",\r\n\t\tparameters: {plot_list: plot_list, \r\n\t\t\t\t\t database_ids: database_ids,\r\n\t\t plot_selection: refresh_selections,\r\n\t\t num_subsamples: max_time_points,\r\n\t\t zoom_x: zoom_x,\r\n\t\t zoom_y: zoom_y},\r\n\t\tsuccess: function (result)\r\n\t\t{\r\n\r\n\t\t // convert to variable\r\n\t\t result = JSON.parse(result);\r\n\t\t\t\r\n\t\t\t// recover plot id\r\n\t\t\tvar plot_list = result[\"plot_list\"];\r\n\r\n\t\t\t// do each plot in list\r\n\t\t\tfor (var j=0; j < plot_list.length; j++) {\r\n\r\n\t\t\t\t// get plot id\r\n\t\t\t\tvar plot_id = plot_list[j]\r\n\r\n\t\t\t\t// save new time points\r\n\t\t\t\tplots_selected_time[plot_id] = result[\"time_points\"][j];\r\n\r\n\t\t\t\t// save new data, if there was a selection\r\n\t\t\t\tif (result[\"var_data\"].length > 0) {\r\n\t\t\t\t\tplots_selected_data[plot_id] = result[\"var_data\"][j];\r\n\t\t\t\t} else {\r\n\t\t\t\t\tplots_selected_data[plot_id] = [];\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// save resolution indicator (for null selection do not show indicator)\r\n\t\t\t\tif (plots_selected_data[plot_id].length > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tplots_selected_resolution[plot_id] = result[\"resolution\"][j];\r\n\t\t\t\t} else {\r\n\t\t\t\t\tplots_selected_resolution[plot_id] = -1;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// was zoom range changed? (this is an error condition,\r\n\t\t\t\t// likely from a template application)\r\n\t\t\t\tif (result[\"range_change\"][j]) {\r\n\r\n\t\t\t\t\t// reset zoom\r\n\t\t\t\t\tplots_selected_zoom_x[plot_id] = result[\"data_range_x\"][j];\r\n\t\t\t\t\tplots_selected_zoom_y[plot_id] = result[\"data_range_y\"][j];\r\n\r\n\t\t\t\t\t// unlink plot\r\n\t\t\t\t\t$(\"#dac-link-plot-\" + (plot_id+1).toString()).prop(\"checked\", false);\r\n\t\t\t\t\tlink_plots[plot_id] = 0;\r\n\r\n\t\t\t\t\t// plot zoom change event\r\n\t\t\t\t\tvar plotZoomEvent = new CustomEvent(\"DACPlotZoomChanged\", { detail: {\r\n\t\t\t\t\t\t\t\t\t\tplots_zoom_x: plots_selected_zoom_x,\r\n\t\t\t\t\t\t\t\t\t\tplots_zoom_y: plots_selected_zoom_y} });\r\n\t\t\t\t\tdocument.body.dispatchEvent(plotZoomEvent);\r\n\r\n\t\t\t\t\t// link plot change event\r\n\t\t\t\t\tvar linkPlotEvent = new CustomEvent(\"DACLinkPlotsChanged\", {detail:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlink_plots});\r\n\t\t\t\t\tdocument.body.dispatchEvent(linkPlotEvent);\r\n\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// now update data in d3\r\n\t\t\t\tupdate_data_d3(plot_id);\r\n\r\n\t\t\t\t// then re-draw d3 plot\r\n\t\t\t\tdraw_plot_d3(plot_id);\r\n\r\n\t\t\t\t// update indicators for this plot\r\n\t\t\t\tupdate_indicators(plot_id);\r\n\r\n\t\t\t\t// done, check links\r\n\t\t\t\tcheck_links(plot_id);\r\n\r\n\t\t\t}\r\n\r\n\t\t},\r\n\t\terror: function ()\r\n\t\t{\r\n\t\t\tdialog.ajax_error ('Server failure: could not subsample variable data.')(\"\",\"\",\"\");\r\n\t\t}\r\n\t});\r\n\r\n}",
"function visualize() {\n\n visualizer.updatePitchChart(audioProcessor.getPitches(), audioProcessor.getTimestamps());\n visualizer.updateRateChart(audioProcessor.getVibratoRates(), audioProcessor.getTimestamps());\n visualizer.updateWidthChart(audioProcessor.getVibratoWidths(), audioProcessor.getTimestamps());\n calcPitch();\n}",
"function jqPlot() {\n // Group: Properties\n // These properties are specified at the top of the options object\n // like so:\n // > {\n // > axesDefaults:{min:0},\n // > series:[{color:'#6633dd'}],\n // > title: 'A Plot'\n // > }\n //\n // prop: data\n // user's data. Data should *NOT* be specified in the options object,\n // but be passed in as the second argument to the $.jqplot() function.\n // The data property is described here soley for reference. \n // The data should be in the form of an array of 2D or 1D arrays like\n // > [ [[x1, y1], [x2, y2],...], [y1, y2, ...] ].\n this.data = [];\n // The id of the dom element to render the plot into\n this.targetId = null;\n // the jquery object for the dom target.\n this.target = null; \n this.defaults = {\n // prop: axesDefaults\n // default options that will be applied to all axes.\n // see <Axis> for axes options.\n axesDefaults: {},\n axes: {xaxis:{}, yaxis:{}, x2axis:{}, y2axis:{}, y3axis:{}, y4axis:{}, y5axis:{}, y6axis:{}, y7axis:{}, y8axis:{}, y9axis:{}},\n // prop: seriesDefaults\n // default options that will be applied to all series.\n // see <Series> for series options.\n seriesDefaults: {},\n gridPadding: {top:10, right:10, bottom:10, left:10},\n series:[]\n };\n // prop: series\n // Array of series object options.\n // see <Series> for series specific options.\n this.series = [];\n // prop: axes\n // up to 4 axes are supported, each with it's own options, \n // See <Axis> for axis specific options.\n this.axes = {xaxis: new Axis('xaxis'), yaxis: new Axis('yaxis'), x2axis: new Axis('x2axis'), y2axis: new Axis('y2axis'), y3axis: new Axis('y3axis'), y4axis: new Axis('y4axis'), y5axis: new Axis('y5axis'), y6axis: new Axis('y6axis'), y7axis: new Axis('y7axis'), y8axis: new Axis('y8axis'), y9axis: new Axis('y9axis')};\n // prop: grid\n // See <Grid> for grid specific options.\n this.grid = new Grid();\n // prop: legend\n // see <$.jqplot.TableLegendRenderer>\n this.legend = new Legend();\n this.baseCanvas = new $.jqplot.GenericCanvas();\n this.seriesCanvas = new $.jqplot.GenericCanvas();\n this.eventCanvas = new $.jqplot.GenericCanvas();\n this._width = null;\n this._height = null; \n this._plotDimensions = {height:null, width:null};\n this._gridPadding = {top:10, right:10, bottom:10, left:10};\n // don't think this is implemented.\n this.equalXTicks = true;\n // don't think this is implemented.\n this.equalYTicks = true;\n // prop: seriesColors\n // Ann array of CSS color specifications that will be applied, in order,\n // to the series in the plot. Colors will wrap around so, if their\n // are more series than colors, colors will be reused starting at the\n // beginning. For pie charts, this specifies the colors of the slices.\n this.seriesColors = [ \"#4bb2c5\", \"#EAA228\", \"#c5b47f\", \"#579575\", \"#839557\", \"#958c12\", \"#953579\", \"#4b5de4\", \"#d8b83f\", \"#ff5800\", \"#0085cc\"];\n // prop: sortData\n // false to not sort the data passed in by the user.\n // Many bar, stakced and other graphs as well as many plugins depend on\n // having sorted data.\n this.sortData = true;\n var seriesColorsIndex = 0;\n // prop textColor\n // css spec for the css color attribute. Default for the entire plot.\n this.textColor;\n // prop; fontFamily\n // css spec for the font-family attribute. Default for the entire plot.\n this.fontFamily;\n // prop: fontSize\n // css spec for the font-size attribute. Default for the entire plot.\n this.fontSize;\n // prop: title\n // Title object. See <Title> for specific options. As a shortcut, you\n // can specify the title option as just a string like: title: 'My Plot'\n // and this will create a new title object with the specified text.\n this.title = new Title();\n // container to hold all of the merged options. Convienence for plugins.\n this.options = {};\n // prop: stackSeries\n // true or false, creates a stack or \"mountain\" plot.\n // Not all series renderers may implement this option.\n this.stackSeries = false;\n // array to hold the cumulative stacked series data.\n // used to ajust the individual series data, which won't have access to other\n // series data.\n this._stackData = [];\n // array that holds the data to be plotted. This will be the series data\n // merged with the the appropriate data from _stackData according to the stackAxis.\n this._plotData = [];\n // Namespece to hold plugins. Generally non-renderer plugins add themselves to here.\n this.plugins = {};\n \n this.colorGenerator = ColorGenerator;\n \n // Group: methods\n //\n // method: init\n // sets the plot target, checks data and applies user\n // options to plot.\n this.init = function(target, data, options) {\n for (var i=0; i<$.jqplot.preInitHooks.length; i++) {\n $.jqplot.preInitHooks[i].call(this, target, data, options);\n }\n this.targetId = target;\n this.target = $('#'+target);\n if (!this.target.get(0)) {\n throw \"No plot target specified\";\n }\n \n // make sure the target is positioned by some means and set css\n if (this.target.css('position') == 'static') {\n this.target.css('position', 'relative');\n }\n if (!this.target.hasClass('jqplot-target')) {\n this.target.addClass('jqplot-target');\n }\n \n // if no height or width specified, use a default.\n if (!this.target.height()) {\n this._height = 300;\n this.target.css('height', '300px');\n }\n else {\n this._height = this.target.height();\n }\n if (!this.target.width()) {\n this._width = 400;\n this.target.css('width', '400px');\n }\n else {\n this._width = this.target.width();\n }\n \n this._plotDimensions.height = this._height;\n this._plotDimensions.width = this._width;\n this.grid._plotDimensions = this._plotDimensions;\n this.title._plotDimensions = this._plotDimensions;\n this.baseCanvas._plotDimensions = this._plotDimensions;\n this.seriesCanvas._plotDimensions = this._plotDimensions;\n this.eventCanvas._plotDimensions = this._plotDimensions;\n this.legend._plotDimensions = this._plotDimensions;\n if (this._height <=0 || this._width <=0 || !this._height || !this._width) {\n throw \"Canvas dimensions <=0\";\n }\n \n this.data = data;\n \n this.parseOptions(options);\n \n if (this.textColor) {\n this.target.css('color', this.textColor);\n }\n if (this.fontFamily) {\n this.target.css('font-family', this.fontFamily);\n }\n if (this.fontSize) {\n this.target.css('font-size', this.fontSize);\n }\n \n this.title.init();\n this.legend.init();\n for (var i=0; i<this.series.length; i++) {\n for (var j=0; j<$.jqplot.preSeriesInitHooks.length; j++) {\n $.jqplot.preSeriesInitHooks[j].call(this.series[i], target, data, this.options.seriesDefaults, this.options.series[i]);\n }\n this.populatePlotData(this.series[i], i);\n this.series[i]._plotDimensions = this._plotDimensions;\n this.series[i].init(i, this.grid.borderWidth);\n for (var j=0; j<$.jqplot.postSeriesInitHooks.length; j++) {\n $.jqplot.postSeriesInitHooks[j].call(this.series[i], target, data, this.options.seriesDefaults, this.options.series[i]);\n }\n }\n\n for (var name in this.axes) {\n this.axes[name]._plotDimensions = this._plotDimensions;\n this.axes[name].init();\n }\n \n if (this.sortData) {\n sortData(this.series);\n }\n this.grid.init();\n this.grid._axes = this.axes;\n \n this.legend._series = this.series;\n\n for (var i=0; i<$.jqplot.postInitHooks.length; i++) {\n $.jqplot.postInitHooks[i].call(this, target, data, options);\n }\n }; \n \n // sort the series data in increasing order.\n function sortData(series) {\n var d;\n for (var i=0; i<series.length; i++) {\n d = series[i].data;\n if (series[i]._stackAxis == 'x') {\n d.sort(function(a,b){\n var ret = a[1] - b[1];\n if (ret) {\n return ret;\n }\n return 0;\n });\n }\n else {\n d.sort(function(a,b){\n var ret = a[0] - b[0];\n if (ret) {\n return ret;\n }\n return 0;\n });\n }\n }\n }\n \n // populate the _stackData and _plotData arrays for the plot and the series.\n this.populatePlotData = function(series, index) {\n // if a stacked chart, compute the stacked data\n this._plotData = [];\n this._stackData = [];\n series._stackData = [];\n series._plotData = [];\n if (this.stackSeries) {\n series._stack = true;\n var sidx = series._stackAxis == 'x' ? 0 : 1;\n var idx = sidx ? 0 : 1;\n // push the current data into stackData\n //this._stackData.push(this.series[i].data);\n var temp = $.extend(true, [], series.data);\n // create the data that will be plotted for this series\n var plotdata = $.extend(true, [], series.data);\n // for first series, nothing to add to stackData.\n for (var j=0; j<index; j++) {\n var cd = this.series[j].data;\n for (var k=0; k<cd.length; k++) {\n temp[k][0] += cd[k][0];\n temp[k][1] += cd[k][1];\n // only need to sum up the stack axis column of data\n plotdata[k][sidx] += cd[k][sidx];\n }\n }\n this._plotData.push(plotdata);\n this._stackData.push(temp);\n series._stackData = temp;\n series._plotData = plotdata;\n }\n else {\n this._stackData.push(series.data);\n this.series[index]._stackData = series.data;\n this._plotData.push(series.data);\n series._plotData = series.data;\n }\n if (index>0) {\n series._prevPlotData = this.series[index-1]._plotData;\n }\n };\n \n // function to safely return colors from the color array and wrap around at the end.\n this.getNextSeriesColor = (function(t) {\n var idx = 0;\n var sc = t.seriesColors;\n \n return function () { \n if (idx < sc.length) {\n return sc[idx++];\n }\n else {\n idx = 0;\n return sc[idx++];\n }\n };\n })(this);\n \n this.parseOptions = function(options){\n for (var i=0; i<$.jqplot.preParseOptionsHooks.length; i++) {\n $.jqplot.preParseOptionsHooks[i].call(this, options);\n }\n this.options = $.extend(true, {}, this.defaults, options);\n this.stackSeries = this.options.stackSeries;\n if (this.options.seriesColors) {\n this.seriesColors = this.options.seriesColors;\n }\n var cg = new this.colorGenerator(this.seriesColors);\n this._gridPadding = this.options.gridPadding;\n this.sortData = (this.options.sortData != null) ? this.options.sortData : this.sortData;\n for (var n in this.axes) {\n var axis = this.axes[n];\n $.extend(true, axis, this.options.axesDefaults, this.options.axes[n]);\n axis._plotWidth = this._width;\n axis._plotHeight = this._height;\n }\n if (this.data.length == 0) {\n this.data = [];\n for (var i=0; i<this.options.series.length; i++) {\n this.data.push(this.options.series.data);\n } \n }\n \n var normalizeData = function(data) {\n // return data as an array of point arrays,\n // in form [[x1,y1...], [x2,y2...], ...]\n var temp = [];\n var i;\n if (!(data[0] instanceof Array)) {\n // we have a series of scalars. One line with just y values.\n // turn the scalar list of data into a data array of form:\n // [[1, data[0]], [2, data[1]], ...]\n for (var i=0; i<data.length; i++) {\n temp.push([i+1, data[i]]);\n }\n }\n \n else {\n // we have a properly formatted data series, copy it.\n $.extend(true, temp, data);\n }\n return temp;\n };\n\n for (var i=0; i<this.data.length; i++) { \n var temp = new Series();\n for (var j=0; j<$.jqplot.preParseSeriesOptionsHooks.length; j++) {\n $.jqplot.preParseSeriesOptionsHooks[j].call(temp, this.options.seriesDefaults, this.options.series[i]);\n }\n $.extend(true, temp, this.options.seriesDefaults, this.options.series[i]);\n temp.data = normalizeData(this.data[i]);\n switch (temp.xaxis) {\n case 'xaxis':\n temp._xaxis = this.axes.xaxis;\n break;\n case 'x2axis':\n temp._xaxis = this.axes.x2axis;\n break;\n default:\n break;\n }\n temp._yaxis = this.axes[temp.yaxis];\n temp._xaxis._series.push(temp);\n temp._yaxis._series.push(temp);\n if (temp.show) {\n temp._xaxis.show = true;\n temp._yaxis.show = true;\n }\n\n // parse the renderer options and apply default colors if not provided\n if (!temp.color && temp.show != false) {\n temp.color = cg.next();\n }\n if (!temp.label) {\n temp.label = 'Series '+ (i+1).toString();\n }\n // temp.rendererOptions.show = temp.show;\n // $.extend(true, temp.renderer, {color:this.seriesColors[i]}, this.rendererOptions);\n this.series.push(temp); \n for (var j=0; j<$.jqplot.postParseSeriesOptionsHooks.length; j++) {\n $.jqplot.postParseSeriesOptionsHooks[j].call(this.series[i], this.options.seriesDefaults, this.options.series[i]);\n }\n }\n \n // copy the grid and title options into this object.\n $.extend(true, this.grid, this.options.grid);\n // if axis border properties aren't set, set default.\n for (var n in this.axes) {\n var axis = this.axes[n];\n if (axis.borderWidth == null) {\n axis.borderWidth =this.grid.borderWidth;\n }\n if (axis.borderColor == null) {\n if (n != 'xaxis' && n != 'x2axis' && axis.useSeriesColor === true && axis.show) {\n axis.borderColor = axis._series[0].color;\n }\n else {\n axis.borderColor = this.grid.borderColor;\n }\n }\n }\n \n if (typeof this.options.title == 'string') {\n this.title.text = this.options.title;\n }\n else if (typeof this.options.title == 'object') {\n $.extend(true, this.title, this.options.title);\n }\n this.title._plotWidth = this._width;\n $.extend(true, this.legend, this.options.legend);\n \n for (var i=0; i<$.jqplot.postParseOptionsHooks.length; i++) {\n $.jqplot.postParseOptionsHooks[i].call(this, options);\n }\n };\n \n \n // method: redraw\n // Empties the plot target div and redraws the plot.\n // This enables plot data and properties to be changed\n // and then to comletely clear the plot and redraw.\n // redraw *will not* reinitialize any plot elements.\n // That is, axes will not be autoscaled and defaults\n // will not be reapplied to any plot elements. \n this.redraw = function() {\n this.target.trigger('jqplotPreRedraw');\n this.target.empty();\n for (var ax in this.axes) {\n this.axes[ax]._ticks = [];\n \t }\n for (var i=0; i<this.series.length; i++) {\n this.populatePlotData(this.series[i], i);\n }\n this.draw();\n this.target.trigger('jqplotPostRedraw');\n };\n \n // method: draw\n // Draws all elements of the plot into the container.\n // Does not clear the container before drawing.\n this.draw = function(){\n this.target.trigger('jqplotPreDraw');\n for (var i=0; i<$.jqplot.preDrawHooks.length; i++) {\n $.jqplot.preDrawHooks[i].call(this);\n }\n // create an underlying canvas to be used for special features.\n this.target.append(this.baseCanvas.createElement({left:0, right:0, top:0, bottom:0}, 'jqplot-base-canvas'));\n var bctx = this.baseCanvas.setContext();\n this.target.append(this.title.draw());\n this.title.pack({top:0, left:0});\n for (var name in this.axes) {\n this.target.append(this.axes[name].draw(bctx));\n this.axes[name].set();\n }\n if (this.axes.yaxis.show) {\n this._gridPadding.left = this.axes.yaxis.getWidth();\n }\n var ra = ['y2axis', 'y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis'];\n var rapad = [0, 0, 0, 0];\n var gpr = 0;\n for (var n=8; n>0; n--) {\n var ax = this.axes[ra[n-1]];\n if (ax.show) {\n rapad[n-1] = gpr;\n gpr += ax.getWidth();\n }\n }\n if (gpr > this._gridPadding.right) {\n this._gridPadding.right = gpr;\n }\n if (this.title.show && this.axes.x2axis.show) {\n this._gridPadding.top = this.title.getHeight() + this.axes.x2axis.getHeight();\n }\n else if (this.title.show) {\n this._gridPadding.top = this.title.getHeight();\n }\n else if (this.axes.x2axis.show) {\n this._gridPadding.top = this.axes.x2axis.getHeight();\n }\n if (this.axes.xaxis.show) {\n this._gridPadding.bottom = this.axes.xaxis.getHeight();\n }\n \n this.axes.xaxis.pack({position:'absolute', bottom:0, left:0, width:this._width}, {min:this._gridPadding.left, max:this._width - this._gridPadding.right});\n this.axes.yaxis.pack({position:'absolute', top:0, left:0, height:this._height}, {min:this._height - this._gridPadding.bottom, max: this._gridPadding.top});\n this.axes.x2axis.pack({position:'absolute', top:this.title.getHeight(), left:0, width:this._width}, {min:this._gridPadding.left, max:this._width - this._gridPadding.right});\n for (var i=8; i>0; i--) {\n this.axes[ra[i-1]].pack({position:'absolute', top:0, right:rapad[i-1]}, {min:this._height - this._gridPadding.bottom, max: this._gridPadding.top});\n }\n // this.axes.y2axis.pack({position:'absolute', top:0, right:0}, {min:this._height - this._gridPadding.bottom, max: this._gridPadding.top});\n \n this.target.append(this.grid.createElement(this._gridPadding));\n this.grid.draw();\n this.target.append(this.seriesCanvas.createElement(this._gridPadding, 'jqplot-series-canvas'));\n var sctx = this.seriesCanvas.setContext();\n this.target.append(this.eventCanvas.createElement(this._gridPadding, 'jqplot-event-canvas'));\n var ectx = this.eventCanvas.setContext();\n ectx.fillStyle = 'rgba(0,0,0,0)';\n ectx.fillRect(0,0,ectx.canvas.width, ectx.canvas.height);\n \n // bind custom event handlers to regular events.\n this.bindCustomEvents();\n \n // draw legend before series if the series needs to know the legend dimensions.\n if (this.legend.preDraw) { \n this.target.append(this.legend.draw());\n this.legend.pack(this._gridPadding);\n if (this.legend._elem) {\n this.drawSeries(sctx, {legendInfo:{location:this.legend.location, width:this.legend.getWidth(), height:this.legend.getHeight(), xoffset:this.legend.xoffset, yoffset:this.legend.yoffset}});\n }\n else {\n this.drawSeries(sctx);\n }\n }\n else { // draw series before legend\n this.drawSeries(sctx);\n this.target.append(this.legend.draw());\n this.legend.pack(this._gridPadding); \n }\n \n // register event listeners on the overlay canvas\n for (var i=0; i<$.jqplot.eventListenerHooks.length; i++) {\n var h = $.jqplot.eventListenerHooks[i];\n // in the handler, this will refer to the eventCanvas dom element.\n // make sure there are references back into plot objects.\n this.eventCanvas._elem.bind(h[0], {plot:this}, h[1]);\n }\n\n for (var i=0; i<$.jqplot.postDrawHooks.length; i++) {\n $.jqplot.postDrawHooks[i].call(this);\n }\n this.target.trigger('jqplotPostDraw', [this]);\n };\n \n this.bindCustomEvents = function() {\n this.eventCanvas._elem.bind('click', {plot:this}, this.onClick);\n this.eventCanvas._elem.bind('dblclick', {plot:this}, this.onDblClick);\n this.eventCanvas._elem.bind('mousedown', {plot:this}, this.onMouseDown);\n this.eventCanvas._elem.bind('mouseup', {plot:this}, this.onMouseUp);\n this.eventCanvas._elem.bind('mousemove', {plot:this}, this.onMouseMove);\n this.eventCanvas._elem.bind('mouseenter', {plot:this}, this.onMouseEnter);\n this.eventCanvas._elem.bind('mouseleave', {plot:this}, this.onMouseLeave);\n };\n \n function getEventPosition(ev) {\n \t var plot = ev.data.plot;\n // var xaxis = plot.axes.xaxis;\n // var x2axis = plot.axes.x2axis;\n // var yaxis = plot.axes.yaxis;\n // var y2axis = plot.axes.y2axis;\n \t var offsets = plot.eventCanvas._elem.offset();\n \t var gridPos = {x:ev.pageX - offsets.left, y:ev.pageY - offsets.top};\n // var dataPos = {x1y1:{x:null, y:null}, x1y2:{x:null, y:null}, x2y1:{x:null, y:null}, x2y2:{x:null, y:null}};\n \t var dataPos = {xaxis:null, yaxis:null, x2axis:null, y2axis:null, y3axis:null, y4axis:null, y5axis:null, y6axis:null, y7axis:null, y8axis:null, y9axis:null};\n \t \n \t var an = ['xaxis', 'yaxis', 'x2axis', 'y2axis', 'y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis'];\n \t var ax = plot.axes;\n \t for (var n=11; n>0; n--) {\n \t var axis = an[n-1];\n \t if (ax[axis].show) {\n \t dataPos[axis] = ax[axis].series_p2u(gridPos[axis.charAt(0)]);\n \t }\n \t }\n\n return ({offsets:offsets, gridPos:gridPos, dataPos:dataPos});\n }\n \n function getNeighborPoint(plot, x, y) {\n var ret = null;\n var s, i, d0, d, j, r;\n var threshold;\n for (var i=0; i<plot.series.length; i++) {\n s = plot.series[i];\n r = s.renderer;\n if (s.show) {\n threshold = Math.abs(s.markerRenderer.size/2+s.neighborThreshold);\n for (var j=0; j<s.gridData.length; j++) {\n p = s.gridData[j];\n // neighbor looks different to OHLC chart.\n if (r.constructor == $.jqplot.OHLCRenderer) {\n if (r.candleStick) {\n var yp = s._yaxis.series_u2p;\n if (x >= p[0]-r.bodyWidth/2 && x <= p[0]+r.bodyWidth/2 && y >= yp(s.data[j][2]) && y <= yp(s.data[j][3])) {\n ret = {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};\n }\n }\n // if an open hi low close chart\n else if (!r.hlc){\n var yp = s._yaxis.series_u2p;\n if (x >= p[0]-r.tickLength && x <= p[0]+r.tickLength && y >= yp(s.data[j][2]) && y <= yp(s.data[j][3])) {\n ret = {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};\n }\n }\n // a hi low close chart\n else {\n var yp = s._yaxis.series_u2p;\n if (x >= p[0]-r.tickLength && x <= p[0]+r.tickLength && y >= yp(s.data[j][1]) && y <= yp(s.data[j][2])) {\n ret = {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};\n }\n }\n \n }\n else {\n d = Math.sqrt( (x-p[0]) * (x-p[0]) + (y-p[1]) * (y-p[1]) );\n if (d <= threshold && (d <= d0 || d0 == null)) {\n d0 = d;\n ret = {seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]};\n }\n }\n } \n }\n }\n return ret;\n }\n \n this.onClick = function(ev) {\n // Event passed in is unnormalized and will have data attribute.\n // Event passed out in normalized and won't have data attribute.\n var positions = getEventPosition(ev);\n var p = ev.data.plot;\n var neighbor = getNeighborPoint(p, positions.gridPos.x, positions.gridPos.y);\n \t ev.data.plot.eventCanvas._elem.trigger('jqplotClick', [positions.gridPos, positions.dataPos, neighbor, p]);\n };\n \n this.onDblClick = function(ev) {\n // Event passed in is unnormalized and will have data attribute.\n // Event passed out in normalized and won't have data attribute.\n var positions = getEventPosition(ev);\n var p = ev.data.plot;\n var neighbor = getNeighborPoint(p, positions.gridPos.x, positions.gridPos.y);\n \t ev.data.plot.eventCanvas._elem.trigger('jqplotDblClick', [positions.gridPos, positions.dataPos, neighbor, p]);\n };\n \n this.onMouseDown = function(ev) {\n var positions = getEventPosition(ev);\n var p = ev.data.plot;\n var neighbor = getNeighborPoint(p, positions.gridPos.x, positions.gridPos.y);\n \t ev.data.plot.eventCanvas._elem.trigger('jqplotMouseDown', [positions.gridPos, positions.dataPos, neighbor, p]);\n };\n \n this.onMouseUp = function(ev) {\n var positions = getEventPosition(ev);\n \t ev.data.plot.eventCanvas._elem.trigger('jqplotMouseUp', [positions.gridPos, positions.dataPos, null, ev.data.plot]);\n };\n \n this.onMouseMove = function(ev) {\n var positions = getEventPosition(ev);\n var p = ev.data.plot;\n var neighbor = getNeighborPoint(p, positions.gridPos.x, positions.gridPos.y);\n \t ev.data.plot.eventCanvas._elem.trigger('jqplotMouseMove', [positions.gridPos, positions.dataPos, neighbor, p]);\n };\n \n this.onMouseEnter = function(ev) {\n var positions = getEventPosition(ev);\n var p = ev.data.plot;\n \t ev.data.plot.eventCanvas._elem.trigger('jqplotMouseEnter', [positions.gridPos, positions.dataPos, null, p]);\n };\n \n this.onMouseLeave = function(ev) {\n var positions = getEventPosition(ev);\n var p = ev.data.plot;\n \t ev.data.plot.eventCanvas._elem.trigger('jqplotMouseLeave', [positions.gridPos, positions.dataPos, null, p]);\n };\n \n this.drawSeries = function(sctx, options){\n // first clear the canvas, since we are redrawing all series.\n sctx.clearRect(0,0,sctx.canvas.width, sctx.canvas.height);\n // if call series drawShadow method first, in case all series shadows\n // should be drawn before any series. This will ensure, like for \n // stacked bar plots, that shadows don't overlap series.\n for (var i=0; i<this.series.length; i++) {\n // console.log('series %s data: %s', i, this.series[i].data);\n this.series[i].drawShadow(sctx, options);\n }\n for (var i=0; i<this.series.length; i++) {\n this.series[i].draw(sctx, options);\n // console.log('series %s data: %s', i, this.series[i].data);\n }\n };\n }",
"function showPolarArea(traits, selector) {\n var labels = [], data = [], graph = []\n , traitsCanvas = $$(selector)\n , traitsCx = traitsCanvas.getContext('2d')\n , traitsChart\n , traitsLegend = $$('.traits-legend');\n\n traits.map(function(trait) {\n graph.push({\n value: trait.percentage * 100\n , color: getColour(trait.percentage)\n , highlight: getColour(trait.percentage)\n , label: trait.name\n });\n });\n\n traitsChart = new Chart(traitsCx).PolarArea(graph, {responsive:true});\n\n traitsLegend.innerHTML = traitsChart.generateLegend();\n }",
"function plot() {\r\n \r\n //this gets the data to plot from parseData\r\n var plotData = parseData(data)\r\n \r\n //if else is to determine if the user wants their plot saved as a jpg file\r\n if (document.getElementById(\"save\").checked == false){\r\n \r\n //this creates the plot then renders it\r\n var graph = new CanvasJS.Chart(\"chartContainer\",{\r\n title: {\r\n text: document.getElementById(\"title\").value\r\n },\r\n axisX: {\r\n title: document.getElementById(\"xLabel\").value\r\n },\r\n axisY: {\r\n title: document.getElementById(\"yLabel\").value\r\n },\r\n data: [{\r\n type: \"line\",\r\n dataPoints: plotData\r\n }]\r\n });\r\n graph.render();\r\n }else{\r\n \r\n //this creates the plot, renders it and then saves it\r\n var graph = new CanvasJS.Chart(\"chartContainer\",{\r\n title: {\r\n text: document.getElementById(\"title\").value\r\n },\r\n axisX: {\r\n title: document.getElementById(\"xLabel\").value\r\n },\r\n axisY: {\r\n title: document.getElementById(\"yLabel\").value\r\n },\r\n data: [{\r\n type: \"line\",\r\n dataPoints: plotData\r\n }]\r\n });\r\n \r\n //the only reason this render is here is incase the user wants to save before they've tried plotting atleast once\r\n graph.render();\r\n graph.exportChart({format: \"jpg\"});\r\n }\r\n}",
"function showViz() {\n viz.show();\n}",
"function renderViz() {\n\n // Define variables for viz\n var mainVizDiv = $(\"#tableauViz\");\n var mainVizOptions = {\n hideTabs: true,\n hideToolbar: true,\n //toolbarPositon: top, // (or \"bottom\")\n width: 850,\n height: 860,\n onFirstInteractive: function () {\n mainWorkbook = mainViz.getWorkbook();\n }\n };\n // Create viz\n mainViz = new tableauSoftware.Viz(mainVizDiv[0], url, mainVizOptions);\n}",
"plot (d) {\r\n var track = this.track();\r\n var pathArray = null;\r\n\r\n if (track) {\r\n pathArray = track.plot(d);\r\n }\r\n\r\n return (d == null) ? pathArray : this\r\n }",
"function sparkline_charts() {\r\n\t\t\t$('.sparklines').sparkline('html');\r\n\t\t}",
"function PhotonsView(html_id) {\n var DEFAULT_ID = 'energy2d-photons-view',\n DEFAULT_CLASS = 'energy2d-photons-view',\n PHOTON_LENGTH = 10,\n $photons_canvas,\n canvas_ctx,\n canvas_width,\n canvas_height,\n photons,\n scale_x,\n scale_y,\n scene_width,\n scene_height,\n //\n // Private methods.\n //\n initHTMLelement = function initHTMLelement() {\n $photons_canvas = $('<canvas />');\n $photons_canvas.attr('id', html_id || DEFAULT_ID);\n $photons_canvas.addClass(DEFAULT_CLASS);\n canvas_ctx = $photons_canvas[0].getContext('2d');\n },\n setCanvasStyle = function setCanvasStyle() {\n canvas_ctx.strokeStyle = \"rgba(255,255,255,128)\";\n canvas_ctx.lineWidth = 0.5;\n },\n //\n // Public API.\n //\n photons_view = {\n // Render vectormap on the canvas.\n renderPhotons: function renderPhotons() {\n var photon, sx, sy, r, i, len;\n\n if (!photons) {\n throw new Error(\"Photons view: bind parts array before rendering.\");\n }\n\n canvas_ctx.clearRect(0, 0, canvas_width, canvas_height);\n\n for (i = 0, len = photons.length; i < len; i += 1) {\n photon = photons[i];\n sx = photon.x * scale_x;\n sy = photon.y * scale_y;\n r = 1 / Math.sqrt(photon.vx * photon.vx + photon.vy * photon.vy);\n canvas_ctx.beginPath();\n canvas_ctx.moveTo(sx, sy);\n canvas_ctx.lineTo(sx + PHOTON_LENGTH * photon.vx * r, sy + PHOTON_LENGTH * photon.vy * r);\n canvas_ctx.stroke();\n }\n },\n // Bind vector map to the view.\n bindPhotonsArray: function bindPhotonsArray(new_photons, new_scene_width, new_scene_height) {\n photons = new_photons;\n scene_width = new_scene_width;\n scene_height = new_scene_height;\n scale_x = canvas_width / scene_width;\n scale_y = canvas_height / scene_height;\n },\n getHTMLElement: function getHTMLElement() {\n return $photons_canvas;\n },\n resize: function resize() {\n canvas_width = $photons_canvas.width();\n canvas_height = $photons_canvas.height();\n scale_x = canvas_width / scene_width;\n scale_y = canvas_height / scene_height;\n $photons_canvas.attr('width', canvas_width);\n $photons_canvas.attr('height', canvas_height);\n setCanvasStyle();\n }\n }; // One-off initialization.\n\n\n initHTMLelement();\n setCanvasStyle();\n return photons_view;\n}",
"function plot_resp() {\n /** Response of DoF r **/\n for (i = 0; i < n; i++) {\n t[i] = i*dt;\n r[i] = A1 * Math.cos(omega1 * t[i]) * s11 + A2 * Math.cos(omega2 * t[i]) * s21;\n r1[i] = -omega1 * A1 * Math.sin(omega1 * t[i]) * s11 - omega2 * A2 * Math.sin(omega2 * t[i]) * s21;\n r2[i] = -Math.pow(omega1, 2) * A1 * Math.cos(omega1 * t[i]) * s11 - Math.pow(omega1, 2) * A2 * Math.cos(omega2 * t[i]) * s21;\n }\n\n //Update the graph immediately after the parameters change\n Plotly.animate(div = \"plot_r\", {\n data: [trace_r, trace_r1, trace_r2],\n traces: [0, 1, 2],\n layout: {}\n }, {\n transition: {duration: 0},\n frame: {duration: 0, redraw: false}\n });\n\n Plotly.relayout( 'plot_r',{\n 'yaxis.autorange': true\n });\n\n}",
"function drawGexpOverview(i) {\n \n //var gexp = getCol(dataPro,1).map(function(d) { return d.value })\n var gexp = getCol(dataPro,i)\n\n var g = document.getElementById('gexp_panel1'),\n\twindowWidth = g.clientWidth,\n\twindowHeight = g.clientHeight;\n\n var margin = {top: 30, right: 0, bottom: 30, left: 30},\n\twidth = windowWidth - margin.left - margin.right,\n\theight = windowHeight - margin.top - margin.bottom;\n \n var chart1;\n chart1 = makeDistroChart({\n\tdata: gexp,\n\txName:'name',\n\tyName:'value',\n//\taxisLabels: {xAxis: 'Gene', yAxis: 'Values'},\n\tselector:\"#gexp-chart-distro1\",\n\tsvg:\"gexp-chart-distro1-svg\", \n\tchartSize:{height:height, width:width},\n\tmargin:margin,\n\tconstrainExtremes:true});\n chart1.renderBoxPlot();\n chart1.renderDataPlots();\n chart1.renderNotchBoxes({showNotchBox:false});\n chart1.renderViolinPlot({showViolinPlot:false});\n\n var pt = document.getElementById(\"gexp_plottype\").value;\n if(pt == \"box_plot\") {\n\tchart1.boxPlots.show({reset:true});chart1.violinPlots.hide();chart1.notchBoxes.hide();chart1.dataPlots.change({showPlot:false,showBeanLines:false})\n }\n if(pt == \"notched_box_plot\") {\n\tchart1.notchBoxes.show({reset:true});chart1.boxPlots.show({reset:true, showBox:false,showOutliers:true,boxWidth:20,scatterOutliers:true});chart1.violinPlots.hide();chart1.dataPlots.change({showPlot:false,showBeanLines:false})\n }\n if(pt == \"violin_plot\") {\t \n\tchart1.violinPlots.show({reset:true, resolution:12});chart1.boxPlots.show({reset:true, showWhiskers:false,showOutliers:false,boxWidth:10,lineWidth:15,colors:['#555']});chart1.notchBoxes.hide();chart1.dataPlots.change({showPlot:false,showBeanLines:false})\n }\n if(pt == \"bean_plot\") {\t \n\tchart1.violinPlots.show({reset:true, width:100, resolution:12});chart1.dataPlots.show({showBeanLines:true,beanWidth:15,showPlot:false,colors:['#555']});chart1.boxPlots.hide();chart1.notchBoxes.hide()\n }\n if(pt == \"beeswam_plot\") {\t \t \n\tchart1.dataPlots.show({showPlot:true, plotType:'beeswarm',showBeanLines:false, colors:null});chart1.violinPlots.hide();chart1.notchBoxes.hide();chart1.boxPlots.hide();\n }\n if(pt == \"scatter_plot\") {\t \n\tchart1.dataPlots.show({showPlot:true, plotType:40, showBeanLines:false,colors:null});chart1.violinPlots.hide();chart1.notchBoxes.hide();chart1.boxPlots.hide();\n }\n}",
"function optionChanged(subjectid) {\n barPlot(subjectid);\n bubblePlot(subjectid);\n updateinfo(subjectid);\n gaugeplot(subjectid);\n \n}",
"function confettiAnimation() {\n\nvar confettiSettings = {\n target: 'confetti-canvas'\n};\nvar confetti = new ConfettiGenerator(confettiSettings);\nconfetti.render();\n}",
"async renderCarView(req, res) {\n const carData = await HmkitServices.getData(req.session);\n const [diagnosticsResponse, doorsResponse] = carData.multiStates;\n const diagnostics = diagnosticsResponse.data.diagnostics;\n const doorsData = doorsResponse.data.doors;\n\n const tires = diagnostics.tirePressures ? diagnostics.tirePressures.map(tirePressure => {\n const location = tirePressure.data.location;\n const pressure = tirePressure.data.pressure;\n\n const tireTemperatureResponse = diagnostics.tireTemperatures && diagnostics.tireTemperatures.find(\n tempData => tempData.data.location.value === location.value\n );\n const wheelRpmResponse = diagnostics.wheelRPMs && diagnostics.wheelRPMs.find(\n rpmData => rpmData.data.location.value === location.value\n );\n\n const temperature = tireTemperatureResponse ? tireTemperatureResponse.data.temperature : {};\n const RPM = wheelRpmResponse ? wheelRpmResponse.data.RPM : {};\n\n return {\n location,\n pressure,\n temperature,\n RPM\n };\n }) : [];\n \n const doors = doorsData.positions ? doorsData.positions.filter(pos => {\n return !(pos && pos.data.location.value === 'all')\n }).map(doorData => {\n const location = doorData.data.location;\n const position = doorData.data.position;\n const currentLock = doorsData.locks.find(lock => lock.data.location.value === location.value);\n\n return {\n location,\n position,\n lock: currentLock ? currentLock.data.lockState : null\n };\n }) : [];\n\n res.render('pages/car.ejs', { diagnostics, doors, tires });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
setTimeout( next, ACTION_INTERVAL ) | function next () {
var a = actions.shift()
if ( a ) {
a( function ( err ) {
if ( err ) throw err
// setTimeout( next, ACTION_INTERVAL )
} )
} else {
setTimeout( finish, ACTION_INTERVAL )
}
} | [
"function schedule(action, delay=200) {\n cb.setTimeout(action, delay)\n}",
"continue(){\n\t\tthis.timeout = setTimeout( this.onTimeout.bind( this ), this.timer )\n\t}",
"function doAction(name, duration, next = null) {\n const now = new Date();\n\n // Check the time in milliseconds when something runs\n console.log(`${now.getTime() - start}: Starting ${name}`);\n\n // Defines anon function, schedules cb, executes it at 'duration' milliseconds in the future, the cb then runs at that scheduled time\n setTimeout( () => {\n const then = new Date();\n console.log(`${then.getTime() - start}: Ending ${name}`);\n // Direct comparison as a conditional, run next() if it exists\n if (null !== next) {\n next();\n }\n }, duration );\n}",
"function play(){\n next();\n timeout_id = setTimeout(\"play()\",1000/persec)\n}",
"function afterTimeout(){\n console.log(next_button.attr('href'));\n window.location = next_button.attr('href');\n }",
"function resetOwnActionTimer() {\n actionTimer = new Date()\n }",
"function processAllActions() {\r\n\t\r\n\tshowWriting();\r\n\t\r\n\tvar time = 500;\r\n\tvar na = botAction.next;\r\n\t\t\r\n\tvar fn = function(v,end){\r\n\t\treturn function(){\r\n\t\t\thideWriting();\r\n\t\t\tif(doAction(v)){\r\n\t\t\t\tshowWriting();\r\n\t\t\t} else {\r\n\t\t\t\tinputState(true);\r\n\t\t\t\tbotAction.last = botAction.next;\r\n\t\t\t\tbotAction.next = [];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tvar i = 0;\r\n\tfor (i=0;i<na.length;i++){\r\n\t\t\r\n\t\tvar b = (i == na.length-1)\r\n\t\t\r\n\t\ttime += na[i].text ? na[i].text.length*10 : 200;\r\n\t\tif (na[i].delay)\r\n\t\t\ttime += na[i].delay;\r\n\t\t\r\n\t\tsetTimeout(fn(i,b),time);\r\n\t}\r\n}",
"onTimeout(){\n\t\tthis.callback.apply(null, this.args)\n\t\tthis.continue()\n\t}",
"onTimeOut() {\n if (this.exhausted) {\n this.stop();\n return;\n }\n\n this.roll();\n }",
"nextActionWithoutRetry() {\n this._actionRetryStatus = false;\n }",
"function resetTimeout() {\n\t\tclearTimeout(timeOut);\n\t\ttimeOut = setTimeout(function() {publicNext();}, timeAutoSlice);\n\t}",
"function startTimer() {\n setInterval(displayNextImage, 3000);\n}",
"function triggerActions(count) {\n const queue = [];\n\n const cb = (msg) => {\n // console.log(msg);\n const node = document.createElement(\"div\");\n node.innerHTML = `<div>${msg}</div>`;\n document.getElementById(\"app\").appendChild(node);\n const next = queue.shift();\n if (next) next();\n };\n\n for (let i = 1; i <= count; i++) {\n queue.push(() => processAction(i, cb));\n }\n queue.shift()();\n}",
"function sleep (until) {\n\t\t\twhile (position !== length && next() !== until) {} \n \t}",
"function setTimer() {\r\n \t\t\tif (options.autoplay && timer === -1 && windowFocus) {\r\n \t\t\t\ttimer = window.setInterval(function () {\r\n \t\t\t\t\tshowNext();\r\n \t\t\t\t}, options.interval);\r\n \t\t\t}\r\n \t\t}",
"function runAfterDelay(delay,callback){\n console.log('(Exercise 7).Wait for '+delay+' secs....'); \n callback(delay);\n }",
"sendQueuedRequests() {\n this._startTimer();\n }",
"function i(e){var t,n=this,i={},\n// Allows the plugin to call a string callback method.\no=e?f.fn:f,\n// Any additional arguments will be passed to the callback.\nr=arguments,a=4,s=r[1],l=r[2],u=r[3];\n// Clean up when necessary.\nfunction c(){e?t.removeData(e):s&&delete p[s]}\n// Yes, there actually is a setTimeout call in here!\nfunction d(){i.id=setTimeout(function(){i.fn()},l)}if(\"string\"!=typeof s&&(a--,s=e=0,l=r[1],u=r[2]),\n// If id is passed, store a data reference either as .data on the first\n// element in a jQuery collection, or in the internal cache.\ne?(// Note: key is 'doTimeout' + id\n// Get id-object from the first element's data, otherwise initialize it to {}.\nt=n.eq(0)).data(e,i=t.data(e)||{}):s&&(\n// Get id-object from the cache, otherwise initialize it to {}.\ni=p[s]||(p[s]={})),\n// Clear any existing timeout for this id.\ni.id&&clearTimeout(i.id),delete i.id,u)\n// A callback (and delay) were specified. Store the callback reference for\n// possible later use, and then setTimeout.\ni.fn=function(e){\n// If the callback value is a string, it is assumed to be the name of a\n// method on $ or $.fn depending on where doTimeout was executed.\n\"string\"==typeof u&&(u=o[u]),(!0!==u.apply(n,h.call(r,a))||e?c:d)()},\n// Set that timeout!\nd();else{if(i.fn)\n// No callback passed. If force_mode (delay) is true, execute the data.fn\n// callback immediately, continuing any callback return-true polling loop.\n// If force_mode is false, execute the data.fn callback immediately but do\n// NOT continue a callback return-true polling loop. If force_mode is\n// undefined, simply clean up. Since data.fn was still defined, whatever\n// was supposed to happen hadn't yet, so return true.\nreturn void 0===l?c():i.fn(!1===l),!0;\n// Since no callback was passed, and data.fn isn't defined, it looks like\n// whatever was supposed to happen already did. Clean up and quit!\nc()}}",
"timeoutHandler()\n {\n if (typeof this.config.postTimeout === 'function') {\n this.config.postTimeout();\n }\n\n this.timer = window.setInterval(this.retry.bind(this), this.config.attemptInterval);\n\n return;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to check if a punishment must be applied, returns true if one has been applied, works in severity stages. More can be added, items can be changed, etc. | function PunishmentCheck() {
// We check if a restraint is invalid
for (let i = cursedConfig.punishmentRestraints.length - 1; i >= 0; i--) {
if (!Asset.find(A => A.Name === cursedConfig.punishmentRestraints[i].name && A.Group.Name === cursedConfig.punishmentRestraints[i].group)) {
delete cursedConfig.punishmentRestraints[i];
popChatSilent({ Tag: "ErrorInvalidPunishment"}, "System");
}
}
cursedConfig.punishmentRestraints = cursedConfig.punishmentRestraints.filter(PR => PR);
// Check if we need to punish
const difference = cursedConfig.strikes - cursedConfig.lastPunishmentAmount;
const stageFactor = cursedConfig.strictness * 15;
let r = false;
if (difference > stageFactor && !cursedConfig.punishmentsDisabled) {
//More restraints per stages, resets every week
cursedConfig.punishmentRestraints.forEach(PR => {
r = WearPunishment(PR.stage, PR.name, PR.group) || r;
});
if (r) {
TryPopTip(41);
SendChat({ Tag: "PunishmentTriggered"});
}
cursedConfig.lastPunishmentAmount = cursedConfig.strikes;
}
return r;
} | [
"_isModify(orgUnit) {\n return Object.keys(orgUnit).length > 0;\n }",
"function isPvP() {\n return !!(parent.is_pvp || get_map().pvp);\n}",
"isPermitted(user_id) {\n if (!user_id) return false;\n for(var permitted in this.permitted) {\n if ( permitted == user_id ) return this.permitted[permitted] != null;\n if ( botStuff.userHasRole(this.server_id, user_id, permitted)) return this.permitted[permitted] != null;\n }\n return false;\n }",
"checkItemNarrative(target) {\n return false;\n }",
"isAssignedToManage(document) {\r\n if (typeof document === 'string') {\r\n if ([\r\n 'product',\r\n 'role',\r\n 'employee'\r\n ].indexOf(document) > -1) {\r\n // Doesn't belong to client\r\n return true\r\n }\r\n\r\n /**\r\n * We have countries assigned to us.\r\n */\r\n if (this.assignedCountries.length || this.assignAllCountries) {\r\n return true\r\n }\r\n\r\n /**\r\n * We have clients assigned to us.\r\n */\r\n if (this.assignedClients.length || this.assignAllClients) {\r\n return true\r\n }\r\n\r\n /**\r\n * We don't have anything assigned, that means we can't do shit.\r\n */\r\n return false\r\n } else {\r\n if (document instanceof Vendor) {\r\n if (!(document instanceof Vendor) && typeof document.vendor === 'undefined') {\r\n // Doesn't belong to vendor\r\n return true\r\n }\r\n\r\n if (this.assignAllCountries) {\r\n // Can manage vendors from any country\r\n return true\r\n }\r\n\r\n const countryId = document instanceof Vendor\r\n ? document.country\r\n ? document.country.id\r\n : null\r\n : document.vendor.country\r\n ? document.vendor.country.id\r\n : null\r\n\r\n if (!countryId) {\r\n // Vendor has no country set, it can be accessed by anyone\r\n return true\r\n }\r\n\r\n if (this.assignedCountries.indexOf(countryId) < 0) {\r\n // Cant manage country of this vendor\r\n return false\r\n }\r\n\r\n // All good\r\n return true\r\n } else {\r\n if (!(document instanceof Client) && typeof document.client === 'undefined') {\r\n // Doesn't belong to client\r\n return true\r\n }\r\n\r\n const clientUuid = document instanceof Client ? document.uuid : document.client.uuid\r\n\r\n if (this.assignAllClients) {\r\n // Can manage all clients\r\n return true\r\n } else if (this.assignedClients.indexOf(clientUuid) < 0) {\r\n // Can't manage client of this document, forfeit\r\n return false\r\n }\r\n\r\n // Countries doesn't matter for direct document management\r\n return true\r\n }\r\n }\r\n }",
"needsAnyAttention() {\n if (this.json_.hasOwnProperty(\"attention_set\")) {\n return Object.keys(this.json_.attention_set).length > 0;\n }\n return false\n }",
"checkPartecipants(){\n \n }",
"mutateStatCheck() {\n if (!this.levelInfos.has(this.curLevelNum)) {\n console.error('Tried to mutate stat but Bookkeeper does not have current level?');\n return false;\n }\n return true;\n }",
"_hasDamage(type) {\n if (type === \"weapon\") {return true};\n // if (!this.data.data.causeDamage) {return false};\n if (type === \"power\" && this.data.data.causeDamage === true) {return true};\n return false;\n }",
"function can_city_build_unit_now(pcity, punittype)\n{ \n return (pcity != null && pcity['can_build_unit'] != null \n && pcity['can_build_unit'][punittype['id']] == \"1\"); \n}",
"function validateParry (data, command) {\n // no additional validation necessary\n return true;\n }",
"_isPassable(pos)\n {\n let passable;\n if ((passable = this._grid.getAttr(pos, 'passable')) !== undefined) {\n return passable === true;\n } else if (this._callbacks['isPassable']) {\n return this._callbacks['isPassable'](pos, this._pos, this._path, this._steps);\n } else {\n throw new Error(\"can't determine passability\"+` of ${this._grid.get(pos)} at ${pos}`);\n }\n }",
"cartHasUnAvailibleItems() {\n const itemAvailibility = Object.keys(this.state.itemsAvailible).map(\n itemId => this.state.itemsAvailible[itemId],\n );\n return !itemAvailibility.every(itemAvailible => itemAvailible === true);\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}",
"canLevelUp(message, cache) {\n\t\tconst element = cache.get(message.member.id);\n\t\tconst exp = element.occupations.get('Painter').experience;\n\t\tconst level = element.occupations.get('Painter').level;\n\n\t\tconst requirements = [];\n\n\t\tif ((level < 9) && (exp >= this.exp_levels[level].exp)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tmessage.channel.send(new RichEmbed({\n\t\t\tcolor: colors.darkblue,\n\t\t\ttitle: 'Bottleneck Ahoy!',\n\t\t\tdescription: `${message.member.displayName}, you've reached a bottleneck in your progression along the path of the Painter. The requirements to pass the bottleneck are:`,\n\t\t}).addField('Requirements', requirements.join('\\n'), true));\n\t\treturn false;\n\t}",
"validate () {\n if (typeof this.intent !== 'string') {\n return false\n }\n\n if (!Array.isArray(this.dependencies) || !Array.isArray(this.notions)) {\n return false\n }\n\n const dependenciesValidity = this.dependencies.every(dep => {\n if (typeof dep.isMissing !== 'object') {\n return false\n }\n\n if (!Array.isArray(dep.actions)) {\n return false\n }\n\n return dep.actions.every(a => typeof a === 'string')\n })\n\n if (!dependenciesValidity) {\n return false\n }\n\n const notionsValidity = this.notions.every(n => {\n if (typeof n.isMissing !== 'object') {\n return false\n }\n\n if (!Array.isArray(n.entities)) {\n return false\n }\n\n return n.entities.every(e => typeof e === 'object' && typeof e.entity === 'string' && typeof e.alias === 'string')\n })\n\n if (!notionsValidity) {\n return false\n }\n\n const requiresItself = this.dependencies.some(dependency => dependency.actions.some(a => a === this.name()))\n\n if (this.dependencies.length > 0 && requiresItself) {\n return false\n }\n\n return true\n }",
"isLockedWork() {\n let userId = userService.getLoggedId();\n let attendance = attendanceService.getAttendance(workToEdit.idAttendance);\n if(!attendance || !attendance.approved)\n return false;\n return true;\n }",
"function adjustWill (luckySign, luckModifier) {\n var adjust = 0;\n if (luckySign.luckySign != undefined && (luckySign.luckySign === \"Luck sign\" || luckySign.luckySign === \"Resisted temptation\")){\n adjust = luckModifier;\n }\n\treturn adjust;\n}",
"departmentUnvalidity() {\n if ($scope.view.establishments.department.length >= 2) {\n // If the department isn't equal to one of the department that are in fact strings in STRING_DEPARTMENTS\n if (STRING_DEPARTMENTS.indexOf($scope.view.establishments.department) !== -1) {\n return false;\n }\n\n // If the department is in the list of french departments\n if (Number.isInteger(Number($scope.view.establishments.department))) {\n const integerDepartment = Number($scope.view.establishments.department);\n if ((integerDepartment > 0 && integerDepartment < 96) || (integerDepartment > 970 && integerDepartment < 977)) {\n return false;\n }\n }\n }\n\n $scope.view.errorMsg = 'Veuillez rentrer un departement français valide';\n return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
buffer the findUserStream by retrieving associated video refs | function bufferStream(){
var temp = new Array();
for(var i = 0; i< userStream.length; i++){
if(userStream[i].refs === undefined){
userStream[i].refs = null;
temp.push(userStream[i].FbId);
//R.request('getVideoRefs',{FromFbId: userStream[i].FbId,Type:"findUsers"});
}
}
if(temp.length > 0){
R.request('getVideoRefs',{FromFbId: temp ,Type:"findUsers"});
}
} | [
"function bufferLikers(){\r\n\t\tvar temp = new Array();\r\n\t\tfor(var i = 0; i< that.likers.length; i++){\r\n\t\t\tif(that.likers[i].refs === undefined){\r\n\t\t\t\tthat.likers[i].refs = null;\r\n\t\t\t\ttemp.push(that.likers[i].FbId);\r\n\t\t\t\t//R.request('getVideoRefs',{FromFbId:that.likers[i].FbId,Type:\"findWhoLikedMe\"});\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(temp.length > 0)\r\n\t\t\tR.request('getVideoRefs',{FromFbId:temp,Type:\"findWhoLikedMe\"});\r\n\t}",
"function getUserStream(){\r\n const user = document.createElement(\"video\");\r\n user.muted = true;\r\n navigator.mediaDevices.getUserMedia({\r\n audio: true,\r\n video: true\r\n }).then((stream) => {\r\n userStream = stream;\r\n addUserStream(user, userStream);\r\n });\r\n}",
"function bufferMyLikes(){\r\n\t\tvar temp = new Array();\r\n\t\tfor(var i = 0; i< that.myLikes.length; i++){\r\n\t\t\tif(that.myLikes[i].refs === undefined){\r\n\t\t\t\tthat.myLikes[i].refs = null;\r\n\t\t\t\t//R.request('getVideoRefs',{FromFbId:that.myLikes[i].FbId,Type:\"findWhoILike\"});\r\n\t\t\t\ttemp.push(that.myLikes[i].FbId);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(temp.length > 0)\r\n\t\t\tR.request('getVideoRefs',{FromFbId:temp,Type:\"findWhoILike\"})\r\n\t}",
"function onReceiveStream(stream, elementID){\n var video = $('#' + elementID + ' video')[0];\n console.log(video);\n video.src = window.URL.createObjectURL(stream);\n }",
"static getUserVideo(userId,res) {\n Media.find({})\n }",
"function currentStream(callback) {\n chrome.storage.sync.get(\"streamSource\", function(result){\n saved = result.streamSource;\n document.getElementById(\"currentStream\").innerHTML = \"Current Stream: \" + saved;\n });\n}",
"function loadVideoStream (url) {\n\tvar outputVideo = '';\n\t$('#stream').click(function(e){\n\t\te.preventDefault();\n\t\t$.getJSON( url + '/main_page/build_video_stream', function(data){\n\t\t\tif (data.result != false) {\n\t\t\t\t$.each(data, function(){\n\t\t\t\t\t$.each(this, function(key, value){\n\t\t\t\t\t\t// console.log(value);\n\t\t\t\t\t\toutputVideo += generateVideoTags(value);\n\t\t\t\t\t})\n\t\t\t\t});\n\t\t\t\t// var element = document.getElementById('list_video');\n\t\t\t\t// element.innerHTML = outputVideo;\n\t\t\t\t$(\"#list_video\").html(outputVideo);\n\t\t\t\t// $('#ul').show().html\n\t\t\t};\n\t\t\t// console.log(outputVideo);\n\t\t\t// console.log(data);\n\t\t})\n\t})\n}",
"buildPlayer() {\n if (this.player || !this.props.stream) {\n // do not build the player if it already exists or\n // if the stream hasn't been fetched yet\n return;\n }\n\n const { id } = this.props.match.params;\n this.player = flv.createPlayer({\n type: 'flv',\n // the stream name does not necessarily have to be the id of the stream\n // the name should match to the key-name we provide in OBS\n url: `http://localhost:8000/live/${id}.flv`\n });\n this.player.attachMediaElement(this.videoRef.current);\n this.player.load();\n }",
"function remoteStreamCallback(e) \n {\n scope.remoteStream = e.stream;\n if(scope.onRemoteStream)\n {\n scope.onRemoteStream(scope.remoteStream);\n }\n }",
"async buffer(source, opts = {}) {\n const [res] = await this.capture(source, _.merge(opts, {\n type: 'buffer'\n }));\n return res;\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 }",
"function serveUsersQueue() {\n\tif (network.usersQueue.length > 0) {\n\t\tvar batch = []\n\t\tfor (var i=0; i < 100 && network.usersQueue.length > 0; i++) {\n\t\t\tbatch.push(network.usersQueue.shift());\n\t\t}\n\t\tauthenticator.cb.__call('users_lookup', {'user_id':batch.join(',')},\n\t\tfunction (reply) {\n\t\t\tconsole.log('retrieved user objects:');\n\t\t\tconsole.log(reply);\n\t\t\tfor (var i=0; i < reply.length; i++) {\n\t\t\t\t// fill the data recieved into the user objects\n\t\t\t\tnetwork.users[reply[i].id].setData(reply[i]);\n\t\t\t\t// update the depth flag, incase it increased unexpectedly\n\t\t\t\tnetwork.users[reply[i].id].setDepth(network.usersAwaiting[reply[i].id]);\n\t\t\t\t// remove user from awaiting\n\t\t\t\tdelete network.usersAwaiting[reply[i].id];\n\t\t\t}\n\t\t});\n\t}\n}",
"function sendCurrentVideo()\n {\n var curVidIndex;\n var source;\n \n if (!videoIsStream)\n {\n curVidIndex = indexById(currentVideo);\n source = videoList[curVidIndex].source;\n }\n else\n {\n source = streamSource;\n }\n \n io.sockets.emit('videoSync', currentVideo, source);\n }",
"function callParticipant(userId, stream, screen) {\n const call = presenterPeer.call(userId, stream, {\n metadata: { scn: screen },\n });\n const audio = document.createElement(\"audio\");\n\n call.on(\"stream\", (userAudioStream) => {\n addAudioStream(audio, stream, userId);\n });\n\n call.on(\"close\", () => {\n audio.remove();\n });\n\n audiences[userId] = call;\n}",
"function getWatchlistedMoviesOfUsersFriends(userId) {\n\n let watchlistedMovies = []\n\n getUserFriends(userId).map(friendId => {\n watchlistedMovies = [...watchlistedMovies, ...getWatchlistedMoviesOfUsers(friendId)]\n })\n\n return watchlistedMovies\n}",
"recordVideo() {\n this.refs.buttonCancel.style.display = 'none';\n this.refs.buttonRecord.style.display= 'none';\n this.refs.buttonStop.style.display= 'initial';\n var self = this;\n\n \n\n navigator.getUserMedia(\n\n // Constraints\n self.state.mediaConstraints,\n\n // Success Callback\n function(stream) {\n //RecordRTC part - recording of the video\n\n // Get a reference to the video element on the page.\n var video = document.getElementById('camera-stream');\n video.src = window.URL.createObjectURL(stream);\n\n var options = {\n mimeType: 'video/webm',\n bitsPerSecond: 1200000,\n bufferSize: 16384,\n sampleRate: 96000\n };\n var recordRTC = RecordRTC(stream, options);\n self.saveRecordRTC(recordRTC);\n self.state.recordRTC.startRecording();\n self.stopVideoCapture();\n self.updateStream(stream);\n },\n\n // Error Callback\n function(err) {\n // Log the error to the console.\n console.log('The following error occurred when trying to use getUserMedia: ' + err);\n }\n ); \n }",
"function addStreamToVideo(video, stream) {\n video.srcObject = stream\n video.addEventListener(\"loadedmetadata\", () => {\n video.play()\n })\n videoGrid.append(video)\n}",
"createStream (callback) {\n\t\tlet data = {\n\t\t\ttype: 'channel',\n\t\t\tname: RandomString.generate(10),\n\t\t\tteamId: this.team.id,\n\t\t\tmemberIds: [this.userData[1].user.id]\n\t\t};\n\t\tthis.apiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'post',\n\t\t\t\tpath: '/streams',\n\t\t\t\tdata: data,\n\t\t\t\ttoken: this.userData[0].accessToken\t// first user creates the team\n\t\t\t},\n\t\t\t(error, response) => {\n\t\t\t\tif (error) { return callback(error); }\n\t\t\t\tthis.stream = response.stream;\n\t\t\t\tcallback();\n\t\t\t}\n\t\t);\n\t}",
"getUserData() {\n api.stream.userData({ auth: this.auth }, cb => this.$userData.next(cb))\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.