query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
SERVICE to delete a Flight | async deleteFlight(req, res) {
const { flightId } = req.params;
try {
await Flight.findByIdAndDelete(flightId);
return res.status(204);
} catch (error) {
return res
.status(400)
.json({ message: "Flight with that id does not exist" });
}
} | [
"function deleteOneFlight(req, res, next) {\n var query = `\n DELETE FROM itineraryflight\n WHERE itinerary_id = :i_id\n AND route_id = :r_id\n `;\n let i_id = req.params.i_id;\n let r_id = req.params.r_id;\n const binds = [i_id, r_id];\n\n oracledb.getConnection({\n user : credentials.user,\n password : credentials.password,\n connectString : credentials.connectString\n }, function(err, connection) {\n if (err) {\n console.log(err);\n } else {\n connection.execute(query, binds, function(err, result) {\n if (err) {console.log(err);}\n else {\n res.json(result.rows)\n }\n });\n }\n });\n}",
"function deleteFlightFromServer(id) {\n try {\n // create the flight that need to delete\n let url = baseURL + \"/api/Flights/\" + id;\n $.ajax({\n url: url,\n type: 'DELETE',\n success: function () {\n\n }\n });\n }\n catch (err) {\n console.log('deleteFlightFromServer PROBLEM!' + err.message);\n errorHandle('deleteFlightFromServer error: ', err.message);\n }\n}",
"function serviceDeleteActuator(req, resp) {\n\t\tlogger.info(\"<Service> DeleteActuator.\");\n\t\tvar getData = parseRequest(req, ['id']);\n\t\t\n\t\twriteHeaders(resp);\n\t\tdeleteActuator(getData.id, function (err, bool) {\n\t\t\tif (err) { error(2, resp, err); return; }\n\t\t\tif (!bool) error(2, resp);\n\t\t\telse resp.end(JSON.stringify({ status: 'ok' })); \n\t\t});\n\t}",
"async delete (request, response) {\n const { id } = request.params;\n const airline_id = request.headers.authorization;\n\n const flight = await connection('flights').where('id', id).select('airline_id').first();\n\n if(flight.airline_id !== airline_id){\n return response.status(401).json({ error: 'Operation not permited' });\n }\n\n await connection('flights').where('id', id).delete();\n\n return response.status(204).send();\n }",
"async DeleteSingleDoctorService(req,res) {\n\n }",
"function serviceDeleteSensor(req, resp) {\n\t\tlogger.info(\"<Service> DeleteSensor.\");\n\t\tvar getData = parseRequest(req, ['id']);\n\t\t\n\t\twriteHeaders(resp);\n\t\tdeleteSensor(getData.id, function (err, bool) {\n\t\t\tif (err) { error(2, resp, err); return; }\n\t\t\tif (!bool) error(2, resp);\n\t\t\telse resp.end(JSON.stringify({ status: 'ok' })); \n\t\t});\n\t}",
"function deleteFlight()\n{\n\tfor(var i=0;i<allFlights.length;i++){\n\t\tif(currentSeg[\"lblFlightNumber\"]==allFlights[i][\"flightNumber\"]){\n\t\t\tallFlights.splice(i,1);\t\n\t\t\tupdateFlightsData();\n\t\t}\n\t}\n\tfrmAdd.show();\n}",
"function deleteNRf(req, res) {\n\n nrfService.delete(req.body)\n .then(function () {\n res.sendStatus(200);\n })\n .catch(function (err) {\n res.status(400).send(err);\n });\n}",
"deleteFromDefinition (featureServiceUrl, definition, layerId, portalOpts) {\n const url = getServiceAdminUrl(featureServiceUrl, 'deleteFromDefinition', layerId);\n // since the fs has it's own url we use the requestUrl method\n return this.requestUrl(url, {\n method: 'POST',\n data: {\n deleteFromDefinition: JSON.stringify(definition)\n }\n }, portalOpts);\n }",
"function deleteServiceOrder(req, res) {\n serviceOrder.findOneAndUpdate({ _id: req.body.orderId }, { deleted: true }, function (err, estimatedetail) {\n if (err) {\n res.json({ code: Constant.ERROR_CODE, message: err });\n } else {\n res.json({ code: Constant.SUCCESS_CODE, message: Constant.SERVICE_DELETED_SUCCESS, data: estimatedetail });\n }\n });\n}",
"function notifyDelete(flightID) {\n let url = \"/api/Flights/\" + flightID;\n $.ajax({ url: url, type: 'DELETE' })\n .fail(function (data) {\n raiseError(\"Fail deleting from the server: \" + data.status)\n })\n\n}",
"function deleteApartment(req, res) {\n res.status(200).send(apartmentService.getById(req.params.apartmentId));\n}",
"async deleteservice({\n view,\n request,\n session,\n response\n }) {\n if (request.ajax()) {\n const id = request.input('id')\n const service = await Service.find(id)\n await service.delete()\n\n response.send({\n status: 'success'\n })\n } else {\n return 'Bad request Type...';\n }\n\n }",
"function serviceDeleteModel(req, resp) {\n\t\tlogger.info(\"<Service> DeleteModel.\");\n\t\tvar getData = parseRequest(req, ['id']);\n\t\t\n\t\twriteHeaders(resp);\n\t\tdeleteModel(getData.id, function (err, status) {\n\t\t\tif (err) error(2, resp);\n\t\t\telse resp.end(JSON.stringify({ status: status })); \n\t\t});\n\t}",
"function serviceDeleteRule(req, resp) {\n\t\tlogger.info(\"<Service> DeleteRule.\");\n\t\tvar getData = parseRequest(req, ['id']);\n\t\t\n\t\twriteHeaders(resp);\n\t\tdeleteRule(getData.id, function (err, bool) {\n\t\t\tif (err) { error(2, resp, err); return; }\n\t\t\tif (!bool) error(2, resp);\n\t\t\telse resp.end(JSON.stringify({ status: 'ok' })); \n\t\t});\n\t}",
"removeService(intent,ip,port){\n const key = intent+ip+port;\n delete this.service[key];\n }",
"function serviceDeleteSensorRule(req, resp) {\n\t\tlogger.info(\"<Service> DeleteSensorRule.\");\n\t\tvar getData = parseRequest(req, ['id']);\n\t\t\n\t\twriteHeaders(resp);\n\t\tdeleteSensorRule(getData.id, function (err, bool) {\n\t\t\tif (err) { error(2, resp, err); return; }\n\t\t\tif (!bool) error(2, resp);\n\t\t\telse resp.end(JSON.stringify({ status: 'ok' })); \n\t\t});\n\t}",
"function serviceDeleteFile(req, resp) {\n\t\tlogger.info(\"<Service> DeleteFile.\");\n\t\tvar getData = parseRequest(req, ['id']);\n\t\t\n\t\twriteHeaders(resp);\n\t\tdeleteFile(getData.id, function (err, user) {\n\t\t\tif (err) error(2, resp);\n\t\t\telse resp.end(JSON.stringify({ status: status })); \n\t\t});\n\t}",
"deleteFood(id, success, fail) {\n api.shared().delete('/foods/' + id)\n .then(function (response) {\n success(response.data);\n })\n .catch(function (error) {\n console.log(error.response)\n if (error.response != undefined) {\n fail(error.response.data);\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
alt :: Alt f => (f a, f a) > f a . . Function wrapper for [`fantasyland/alt`][]. . . `fantasyland/alt` implementations are provided for the following . builtin types: Array and Object. . . ```javascript . > alt([1, 2, 3], [4, 5, 6]) . [1, 2, 3, 4, 5, 6] . . > alt(Nothing, Nothing) . Nothing . . > alt(Nothing, Just(1)) . Just(1) . . > alt(Just(2), Just(3)) . Just(2) . ``` | function alt(x, y) {
return Alt.methods.alt(x)(y);
} | [
"function alt(x, y) {\n return Alt.methods.alt (x) (y);\n }",
"function alt(m, x) {\n if(!(isAlt(m) && isSameType(m, x))) {\n throw new TypeError('alt: Both arguments must be Alts of the same type')\n }\n\n return x.alt(m)\n}",
"alt (alternative) {\n if (Either.isEither(alternative)) {\n return this.isRight ? this : alternative\n }\n throw new Error('Either#alt expects an Either as an argument')\n }",
"function alt(y) {\n return function(x) {\n return Z.alt (x, y);\n };\n }",
"function alt() {\n\t\t\tbH.testPoint = h.tP = function (tf, vec) {\n\t\t\t\treturn this.TestPoint(tf, vec)\n\t\t\t}\n\t\t\tbH.TP = function (x, y) {\n\t\t\t\treturn this.TestPoint(x, y)\n\t\t\t}\n\t\t\tbH.tPt = bH.tP = function (x, y) {\n\t\t\t\tvar bH = this\n\t\t\t\talert('bH.tPt tP')\n\t\t\t\treturn bH.TP(x / 30, y / 30)\n\t\t\t}\n\t\t}",
"function Left$prototype$alt(other) {\n return other;\n }",
"function graffiti(noAlt)\n{\n let len = noAlt.length\n // for loop runs through the array and adds alt text to each image\n for (let i = 0; i < len; i++)\n {\n noAlt[i].alt = \"graffiti image\"\n }\n}",
"function alt(first, second) {\n return new AlternateEdit(first, second);\n }",
"setAltitude(alt = 10) {\n //this._sendCommandLong(alt, 0, 0, 0, 0, 0, 0, 186, 1);\n this._set_position_target_global_int(0, 1, 0, 0, alt);\n }",
"function alt(a, b) {\n return function(e, k) {\n var action = !e.altKey ? a : b\n return resolve(action, e, k);\n }\n }",
"alt(o) {\n\t\treturn o;\n\t}",
"function alt(a, b) {\n return function(e, k) {\n var action = !e.altKey ? a : b;\n return resolve(action, e, k);\n };\n }",
"function Nothing$prototype$alt(other) {\n return other;\n }",
"getAltSet() {\n\t\tconst alts = new Set$3();\n\t\tif (this.configs !== null) {\n\t\t\tfor (let i = 0; i < this.configs.length; i++) {\n\t\t\t\tconst c = this.configs[i];\n\t\t\t\talts.add(c.alt);\n\t\t\t}\n\t\t}\n\t\tif (alts.length === 0) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn alts;\n\t\t}\n\t}",
"function mxImageBundle(alt)\n{\n\tthis.images = [];\n\tthis.alt = (alt != null) ? alt : false;\n}",
"setAlternativeImages(alias, alternativeAlias){\n this.imageRawAlternative[alias] = alternativeAlias;\n }",
"function assignUniqueIndexAlt() {\nimgEl1.alt = Product.allProducts[Product.lastDisplayedIndex[0]].altTag\nimgEl2.alt = Product.allProducts[Product.lastDisplayedIndex[1]].altTag\nimgEl3.alt = Product.allProducts[Product.lastDisplayedIndex[2]].altTag\n}",
"function update_alt ()\n{\n\n\t//read values from sliders\n\taltitude = document.sliders.altitude.value * 1.0;\n\tpressure = document.sliders.pressure.value * 1.0;\n\tsubscale = document.sliders.subscale.value * 1.0;\n\t\n\t//show values to user\n\t$('#altitude_value').html('<b>Altitude:</b> ' + parseInt(altitude) + ' ft');\n\t$('#pressure_value').html('<b>Pressure:</b> ' + parseInt(pressure) + ' mb');\n\t$('#subscale_value').html('<b>Subscale:</b> ' + subscale + ' mb');\n\t\n\t//show subscale\n\tshow_subscale(subscale);\n\t\n\t//calculate indicated altitude and dispplay on instrument\n\tshow_altitude();\n\t\n}",
"getAltSet() {\n\t\tconst alts = new HashSet();\n\t\tif (this.configs !== null) {\n\t\t\tfor (let i = 0; i < this.configs.length; i++) {\n\t\t\t\tconst c = this.configs[i];\n\t\t\t\talts.add(c.alt);\n\t\t\t}\n\t\t}\n\t\tif (alts.length === 0) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn alts;\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set this to true if the record is saying that the procedure was NOT performed. | get notPerformed() {
return this.__notPerformed;
} | [
"get doNotPerform() {\n\t\treturn this.__doNotPerform;\n\t}",
"rsvpFalse() {\n this.rsvp(false);\n }",
"get not() {\n this.negation = true;\n return this;\n }",
"get IsPed() {\n return !!IsModelAPed(this.hash);\n }",
"get disableButton() {\n return !this.noRecords;\n }",
"get prokaryote(){\n return !this._trueNucleus;\n}",
"get noRecordsToDisplay(){\n if(this.recordToDisplay == ''){\n return true;\n }\n }",
"function isNotRunning()/*:Boolean*/ {\n return this.notRunning$kBK$;\n }",
"_not(val) {\n if (arguments.length === 1) {\n this._notFlag = val;\n return this;\n }\n const ret = this._notFlag;\n this._notFlag = false;\n return ret;\n }",
"get isUnanswered() {\r\n return this.hasFlag(DialogFlag.UNANSWERED);\r\n }",
"SetProceduralBoolean() {}",
"isFalse() {\n return (this.value === Value.FALSE);\n }",
"function returnFalse() {\n return false;\n }",
"function returnFalse(){\n return false;\n }",
"function isNotStarted()/*:Boolean*/ {\n return this === ProcessState.NOT_STARTED;\n }",
"get not () {\n this.isAntiExample = !this.isAntiExample;\n return this;\n }",
"get none() {\r\n return this.primitiveType === PrimitiveType.None;\r\n }",
"cleanedPoop() {\n this.poop = false;\n }",
"function False () {\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens Upgrade to Pro link in AIOSEOP menu as new tab. | function upgrade_link_aioseop_menu_new_tab() {
$('#toplevel_page_all-in-one-seo-pack-aioseop_class ul li').last().find('a').attr('target','_blank');
} | [
"function openStorePageTab() {\n var createProperties = {\n url: targetProduct.url\n }\n chrome.tabs.create(createProperties, function(tab) {});\n}",
"openWebAssessor() {\n window.open(\n 'https://www.webassessor.com/salesforce',\n '_blank' // <- This is what makes it open in a new window.\n );\n }",
"function handleOpenInBrowser()/*:void*/ {\n var previewUrl/*:String*/ = AS3.getBindable(this,\"urlValueExpression\").getValue();\n if (previewUrl) {\n window.open(previewUrl);\n } else {\n // TODO Ext6 API\n this.openInBrowserButton$lMam['showMenu']();\n }\n }",
"function openPolicyInNewPage(policyNo) {\r\n var url = getAppPath() + \"/policymgr/maintainPolicy.do?policyNo=\" + policyNo;\r\n window.open(url, \"\", \"location=yes,menubar=yes,toolbar=yes,scrollbars=yes,directories=no,resizable=yes,opyhistory=no\");\r\n}",
"function openPrinterFriendly(URL) {\n if (AccesspluslinksWin!=null && AccesspluslinksWin!=\"undefined\" && !AccesspluslinksWin.closed){\n\t AccesspluslinksWin.close();\n\t\tAccesspluslinksWin=null;\n\t}\n \tAccesspluslinksWin=window.open(URL + \"?APLS_PrinterFriendly=Y\",\"Accesspluslinks\",\"alwaysRaised=yes,scrollbars=no,toolbar=no,directories=no,menubar=yes,resizable=yes,status=no,titlebar=no\");\n\tAccesspluslinksWin.focus();\n }",
"function supply_and_demand_menu_onclick() {\n\t// Make the previously active menu tab if any to normal (not in use) status.\n\tif(activeMenuTab != \"\") {\n\t\tdocument.getElementById(activeMenuTab).className = \"a\";\n\t}\n\t\n\t// Set the supply & demand navigation option as an active (in use) one.\n\tdocument.getElementById(\"supplyAndDemand\").className = \"active\";\n\tactiveMenuTab = \"supplyAndDemand\";\n\n\t// Following Javascript API will give us the protocol://host:port.\n\tvar url = window.location.origin + \"/viz/supply-and-demand.html\";\n\n\tdocument.getElementById(\"main\").innerHTML = '<object type=\"text/html\"' +\n\t\t'data=\"' + url + '\"' + 'height=\"700\" width=\"1200\"></object>';\t\n}",
"function open_website_install() {\n\tchrome.tabs.create({url:\"http://www.tabteamext.com/install\"});\n}",
"function pocketBookmarkBarOpenPocketCommand(event) {\n openTabWithUrl('https://getpocket.com/a/', true);\n }",
"function openCart( page ) \n{\n window.open(page);\n\n}",
"function openBuyNow(url) {\n\tvar newWin = window.open(url,\"\",\"\");\n\treturn;\n}",
"function openOptionPage () {\r\n if (chrome.runtime.openOptionsPage) {\r\n chrome.runtime.openOptionsPage();\r\n } else {\r\n window.open(chrome.runtime.getURL('options.html'));\r\n }\r\n }",
"function openUpdateLink(){\n extension.tabs.create({\n \"url\": \"https://addons.mozilla.org/en-US/firefox/addon/stack-counter/?src=search\"\n });\n}",
"function openTab(url){if(typeof GM_openInTab !='undefined'){GM_openInTab(url);}else if(typeof PRO_openInTab !='undefined'){PRO_openInTab(url,2);}else{window.open(url);}}",
"function openElpha(){\n window.open(\"https://elpha.com/\", \"_blank\");\n }",
"function add_irealpro_link(song, chords) {\n\n var couldHaveIrealPro = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);\n if (couldHaveIrealPro && (chords.length > 0)) {\n var url = irealProFromAbc(song, chords);\n var link = document.getElementById(\"iRealPro\");\n if (link !== null) {\n link.href = url;\n } else {\n var link = document.createElement(\"A\");\n link.innerHTML = \" | irealpro\";\n link.href = url\n link.target = \"_blank\";\n link.id = \"iRealPro\";\n var menu = document.getElementById(\"sheetmenu\");\n menu.appendChild(link);\n }\n }\n}",
"_showGitHubPage() {\n window.open('https://github.com/chromeos/pwa-play-billing', '_blank');\n }",
"onClickOpenUpgradeMenu() {\n this.scene.start(\"UpgradeMenu\");\n }",
"open_newsHub_OpinionTab(){\n this.newsHub_OpinionTab.waitForExist();\n this.newsHub_OpinionTab.click();\n }",
"function openHowToPurchaseWindow()\n{\t\n\tNewWindow = window.open('how_To_Purchase.html','What is cvv','width=850,height=700,resizable=no,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,colyhistory=no'); \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
12 Return the count of passengers by gender. | function getPassengersByGender(data, gender) {
const sexOfPassengerCount = data.filter(passenger => passenger.fields.sex === gender)
console.log(`${gender.toUpperCase()} COUNT: ${sexOfPassengerCount.length}`)
return sexOfPassengerCount.length
} | [
"function getPassengersByGender(data, gender) {\n\tconst pGender = data.filter( p => p.fields.sex == (gender))\n\treturn pGender.length\n}",
"function getPassengersByGender(data, gender) {\n\treturn data\n .filter(p => p.fields.sex === gender)\n .length\n}",
"function getPassengersByGender(data, gender) {\n\treturn data.filter(p => p.fields.sex === gender).length\n}",
"function countGenders() {\n let males = 0,\n females = 0,\n result;\n people.forEach(element => {\n if (element.gender == 'm' || element.gender == 'M') {\n males++;\n } else {\n females++;\n }\n });\n document.getElementById('countGenders').innerHTML = `There ${males} males and ${females} females.`\n}",
"function numFemales(){\n for (let i = 0; i < customers.length; i++) {\n if (customers[i].gender === \"female\"){\n summaryStatistics.numFemales.value++;\n };\n }\n }",
"function numOfMales(){\n for (let i = 0; i < customers.length; i++) {\n if (customers[i].gender === \"male\"){\n summaryStatistics.numMales.value++;\n };\n }\n }",
"function nbOfMale(classmates) {\n\tvar numMales = 0;\n\tfor (var i = 0; i < classmates.length; i++) {\n\t\tif(classmates[i].gender === 'male') {\n\t\t\tnumMales ++ ;\n\t\t}\n\t\t\n\t}\n\treturn numMales\n}",
"function nOfmale(classmate){\n\t\tvar count=0;\n\t\tfor (var i = classmate.length - 1; i >= 0; i--) {\n\t\t\t\n\t\t\t\tif(classmates[i].gender === \"male\"){\n\t\t\t\t\tcount++\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\treturn \"number of males =\"+count\n\t}",
"function nbOfMale(mates)\n{\n\tvar count = 0;\n\n\tfor(var i =0; i< mates.length; i++)\n\t{\n\t\tif(mates[i].gender === \"male\")\n\t\t\tcount++;\n\t}\n\treturn count;\n}",
"function genderBreakdown(people){\n var genders = {};\n _.reduce(people, function(total, nextInLine, i){\n if (!genders.hasOwnProperty(people[i][\"gender\"])){\n return genders[people[i][\"gender\"]] = 1;\n } else if (genders.hasOwnProperty(people[i][\"gender\"])){ \n return genders[people[i][\"gender\"]] += 1;\n } else {return total;\n }}\n , 0)\n \n \n return genders;\n \n}",
"function nbOfMale (classMate){\n\t\tvar result = 0\n\t\tfor(var i = 0; classMate.length > i; i++){\n\t\t\tif(classMate[i].gender === \"male\"){\n\t\t\t\tresult = result + 1;\n\t\t\t}\n\t\t}\n\t\t\treturn result\n\t}",
"function getNumberOfFemales(arr){\n let count = 0;\n for(let i = 0; i < arr.length; i++){\n if(arr[i].gender == 'female'){\n count++;\n }\n }\n return count;\n}",
"function getSurvivorsByGender(data, gender) {\n\treturn data\n .filter(p => p.fields.sex === gender && p.fields.survived === 'Yes').length\n}",
"function getNumberOfMales(arr){\n let count = 0;\n for(let i = 0; i < arr.length; i++){\n if(arr[i].gender == 'male'){\n count++;\n }\n }\n return count;\n}",
"function numberOfMaleFriends ( array ) {\n\t\tvar acc = 0;\n\tfor ( var i = 0; i < array.length; i++ ) {\n\t\tif (array[i].age === \"male\") {\n\t\t\tacc ++;\n\t\t}\n\t}\n\treturn acc\n\t}",
"function nbOfMale(matesArray){\n\tvar result=0;\n\tfor (var i = 0; i < matesArray.length; i++) {\n\t\tif (matesArray[i].gender===\"male\"){\n\t\t\tresult++\n\t\t}\n\t}\n\treturn \"Number of Male mates is:\"+ result;\n}",
"function femaleCount() {\n femaleAges = {\"11200\": 0, \"11300\": 0, \"11400\": 0, \"11500\": 0, \"11600\": 0, \"11700\": 0, \"99 \": 0, \"0 \": 0};\n $(femaleData).each(function(nr, value) {\n if (value[fireworkCrime] !== null) {\n femaleAges[value[Age]] += value[fireworkCrime];\n }\n });\n graphData();\n}",
"function printGenderCount() {\n document.write(\"Total Males: \" + maleCount\n + \"\\nTotal Females: \" + femaleCount);\n}",
"function nbOfMale (){\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays user records to the table. | function displayUsers(users = []) {
var userCount = users.length;
for (var i = 0; i < userCount; i++) {
var user = users[i];
var userRow = createUserRow(user);
if (user !== null) {
tableBody.append(userRow);
}
}
} | [
"function displayInfo() {\r\n $( \"#tableData\" ).html('');\r\n users.forEach(function(user){\r\n $( \"#tableData\" ).append( `\r\n <tr id=\"user${user.id}\" class=\"user\" data-id=\"${user.id}\">\r\n <td>${user.id}</td>\r\n <td>${user.first_name}</td>\r\n <td>${user.surname}</td>\r\n <td>${user.dob}</td>\r\n <td>${user.email}</td>\r\n <td>${user.phone}</td>\r\n </tr>` );\r\n });\r\n}",
"function showTable(user) {\r\n\r\n // //Create Table reference\r\n // var dvTable = document.getElementById('userInfo'); // Nothing: we don't need it bruv\r\n // dvTable.innerHTML = \"\";\r\n \r\n //Create Table\r\n var table = document.createElement(\"TABLE\");\r\n table.border=1;\r\n\r\n //Init Header Row\r\n var columns = [];\r\n columns.push(\"Username\",\"Firstname\",\"Lastname\",\"Email\");\r\n var row = table.insertRow(-1);//-1: indicates it is the last row, index\r\n\r\n //Fill out Header Row\r\n for (var i =0; i<columns.length; i++) {\r\n var headerCell = document.createElement(\"TH\");\r\n headerCell.innerHTML = columns[i];\r\n row.appendChild(headerCell);\r\n }\r\n\r\n //User Row\r\n row = table.insertRow(-1);\r\n\r\n var cell1 = row.insertCell(-1);\r\n cell1.innerHTML = user['username'];\r\n var cell2 = row.insertCell(-1);\r\n cell2.innerHTML = user['firstname'];\r\n var cell3 = row.insertCell(-1);\r\n cell3.innerHTML = user['lastname'];\r\n var cell4 = row.insertCell(-1);\r\n cell4.innerHTML = user['email'];\r\n \r\n userInfo.appendChild(table); // could also write dvTable\r\n}",
"function display(user) {\n // Rank starting at 1.\n let rank = 1;\n for (let i = 0; i < user.length; i++) {\n // Get id to table in Leaderboards.php\n var table = byId(\"generateTable\");\n let tr = newElement(\"tr\");\n\n // Does not add if user' scrore is null.\n if (user[i].score === undefined) {\n tr.append(newTd(null));\n } else {\n // Append <td> to <tr>\n tr.append(newTd(rank));\n tr.append(newTd(user[i].username));\n tr.append(newTd(user[i].score));\n rank++;\n }\n\n // This method is used to remove duplication of data from table.\n for (var j = table.rows.length - 1; j > 0; j--) {\n table.deleteRow(j);\n }\n\n // Append <tr> to <tbody> with id=\"generateTable\".\n table.appendChild(tr);\n }\n}",
"function viewAllUsers() {\n var data = [],\n output,\n config;\n\n config = {\n columns: {\n }\n };\n data[0] = [\"User ID\".cyan, \"Full Name\".cyan, \"Username\".cyan, \"User Type\".cyan];\n let queryStr = \"users\";\n let columns = \"user_id, full_name, username, user_type\";\n\n myConnection.readFunction(columns, queryStr, function (res) {\n console.log(\"\\n Users\".magenta);\n for (let i = 0; i < res.length; i++) {\n data[i + 1] = [res[i].user_id.toString().yellow, res[i].full_name, res[i].username, res[i].user_type];\n }\n output = table.table(data, config);\n console.log(output);\n myConnection.goBack(\"Supervisor\", bamazonSupervisor.runBamazonSupervisor);\n });\n}",
"function displayAllUsers(users) {\n const table = document.createElement('table');\n const tbody = document.createElement('tbody');\n const headerRow = table.insertRow(0);\n const userNameHeader = document.createElement('th');\n const screenNameHeader = document.createElement('th');\n userNameHeader.innerHTML = \"User Name\";\n screenNameHeader.innerHTML = \"Screen Name\";\n userNameHeader.className = \"table--id\";\n screenNameHeader.className = \"table--id\";\n\n headerRow.appendChild(userNameHeader);\n headerRow.appendChild(screenNameHeader);\n\n users.forEach(function (user) {\n let tRow = tbody.insertRow(-1);\n let tScreenName = tRow.insertCell(0);\n let tUserName = tRow.insertCell(0);\n tUserName.innerHTML = user.name;\n tScreenName.innerHTML = `\n <span class='btn--link'>\n <a onClick='openRequest(TYPE_OF_REQUEST.USER_BY_SCREEN_NAME, \"${user.screen_name}\");'>\n ${user.screen_name}\n </a>\n </span>`;\n });\n // append generated table body to table\n table.appendChild(tbody);\n\n // clear old table (if exists) and attach new table\n document.getElementById('json-return').innerHTML = '';\n document.getElementById('json-return').appendChild(table);\n}",
"function show_user_table() {\n\tif (user_token == false) {\n\t\tconsole.log(\"No user Token\");\n\t\treturn false;\n\t}\n\t//TODO: Error Handling\n\tvar table = new SAPO.Communication.JsonP(\n\t\t\t\"https://services.sapo.pt/Codebits/users?callback=build_user_table&token=\" + user_token, {\n\t\t\tevalJS : 'force',\n\t\t\tonComplete : function (data) {\n\t\t\t\t\n\t\t\t\t//console.log(data);\n\t\t\t},\n\t\t});\n}",
"function printUsers() {\r\n\ttableBody.innerHTML = \"\";\r\n\tfor (let i = 0; i < users.length; i++) {\r\n\t\tconst row =\r\n\t\t\t\"<tr><td>\" +\r\n\t\t\tusers[i].name +\r\n\t\t\t\"</td><td>\" +\r\n\t\t\tusers[i].email +\r\n\t\t\t\"</td><td>\" +\r\n\t\t\tusers[i].age +\r\n\t\t\t\"</td></tr>\";\r\n\t\ttableBody.innerHTML += row;\r\n\t}\r\n}",
"function printUsers() {\n for(let i = 0; i < users.length; i++) {\n const row = '<tr><td>'+users[i].name+'</td><td>' + users[i].email + '</td></tr>'\n tableBody.innerHTML += row;\n }\n}",
"function showUsers(users) {\n var tbl = [];\n for(var i=0; i<users.length; i++) {\n tbl.push(\"<tr><td>\");\n tbl.push(users[i].id);\n tbl.push(\"</td><td>\")\n tbl.push(users[i].firstName);\n tbl.push(\"</td><td>\")\n tbl.push(users[i].lastName);\n tbl.push(\"</td><td>\")\n tbl.push(users[i].todoCount);\n tbl.push(\"</td><td><i class='ico icoEdit' onclick='_frameworkEditUser(\\\"\" + users[i].id + \"\\\")'>✎</i> \");\n tbl.push(\"<i class='ico icoDelete' onclick='_frameworkDeleteUser(\\\"\" + users[i].id + \"\\\")'>ⓧ</i></td></tr>\");\n }\n _framework.userTable.innerHTML = tbl.join('');\n _framework.userList.classList.remove(\"hide\");\n}",
"function displayUserInformation() {\r\n \r\n // We are looping through all our registered users and pick the loggedInUser by comparing it with his unique userID\r\n for (i=0; i < users.length; i++){\r\n if(users[i].userId == localStorage.getItem('loggedInUser')){\r\n\r\n // We are storing this information in the variable activeUser\r\n var activeUser = users[i]\r\n\r\n // Calling the function \"showTable\" with the information of the activeUser (=loggedInUser)\r\n showTable(activeUser);\r\n\r\n } \r\n } \r\n }",
"function renderUserListElement(user) {\n var table = document.getElementById('user_list');\n var row = table.insertRow(-1);\n\n var username = row.insertCell(0);\n var name = row.insertCell(1);\n username.innerHTML = user.username;\n name.innerHTML = user.name;\n\n row.addEventListener('click', function(e) {\n window.location.href = basePath + 'user/edit.html?user_id=' + user.user_id;\n });\n}",
"function displayTable()\r\n{\t\r\n\t// Package a JSON payload to deliver to the DisplayTable Endpoint with\r\n\t// the UserID in order to display their contacts.\r\n var jsonPayload = \r\n \t'{\"UserID\" : \"' + userId + '\"}';\r\n\tvar url = urlBase + '/DisplayTable.' + extension;\r\n\tvar xhr = new XMLHttpRequest();\r\n\t\r\n\txhr.open(\"POST\", url, false);\r\n\txhr.setRequestHeader(\"Content-type\", \"application/json; charset=UTF-8\");\r\n\t\r\n\t// Basic try and catch to ensure that any server code errors are \r\n\t// handled properly. \r\n\ttry\r\n\t{\r\n\t\txhr.onreadystatechange = function()\r\n\t\t{\r\n\t\t\tif (this.readyState == 4 && this.status == 200)\r\n\t\t\t\tconsole.log(\"Success in displayTable()\");\r\n\t\t};\r\n\t\txhr.send(jsonPayload);\r\n\t}\r\n\tcatch(err)\r\n\t{\r\n\t\tconsole.log(\"Failure in displayTable()\");\r\n\t}\r\n\r\n\tvar contactList = JSON.parse(xhr.responseText);\r\n\r\n\t// For each contact in the JSON array, the contact's\r\n\t// information will be added to the table.\r\n\tfor (var i in contactList)\r\n {\r\n \taddRow(contactList[i]);\r\n }\r\n}",
"function displayTable() {\n // select table data to send to CLI\n let query = \"SELECT * FROM allemployees;\";\n connection.query(query, function(err, res) {\n if (err) console.log(err);\n // Sent stringified results to the CLI after a couple blank lines.\n console.log(\"\\n\\n\");\n console.table(JSON.parse(JSON.stringify(res)));\n });\n} // end of displaytable",
"function printUsers() {\n tableBody.innerHTML = '';\n // for(let i = 0; i < users.length; i++) {\n // const row = '<tr><td>'+ users[i].name +'</td><td>' + users[i].age + '</td><td>' + users[i].email + '</td><td>' + users[i].gender + '</td></tr>';\n // tableBody.innerHTML += row;\n // }\n //const usuarios = users.map(user => '<tr><td>'+ user.name +'</td><td>' + user.age + '</td><td>' + user.email + '</td><td>' + user.gender + '</td></tr>');\n users.forEach(user => {\n const row = `<tr>\n <td>${user.name}</td>\n <td>${user.age}</td>\n <td>${user.email}</td>\n <td>${user.gender}</td>\n </tr>`;\n tableBody.innerHTML += row; \n })\n}",
"function usersDisplayGenerator(){\n msg3 = \"<br/>\";\n if(theUsers != null){\n msg3 = msg3 + \"<b>Here is the display of the users</b><br/>\";\n msg3 = msg3 + \"<table><tr><th>Ord.No</th><th>Username</th><th>email</th></tr>\";\n var count = Object.keys(theUsers).length;\n for(x=0; x<count; x++){\n //console.log(\"Checking user:\" + theUsers[x].username);\n msg3 = msg3 + \"<tr><td>\" + x + \"</td><td>\" + theUsers[x].username + \"</td><td>\" \n + theUsers[x].email + \"</td></tr>\";\n }\n msg3 = msg3 + \"</table>\";\n } else {\n msg3 = msg3 + \"<h3>Remember!</h3><br/>\";\n msg3 = msg3 + \"Treating the users fairly is important!<br/>\";\n msg3 = msg3 + \"Click Refresh to see the users:<br/>\";\n }\n \n msg3 = msg3 + '|<a href=\"/adminpanel.html\">Refresh!</a>|<br/>';\n return msg3;\n}",
"static displayUsers() {\n const users = Storage.getUsers();\n users.forEach(user => UI.createUser(user));\n }",
"function mostrarUsers(){\n\t\n\t\tvar resultado = $(\"#resultado1A\");\n\t\tvar users = ejer1.usuario;\n\t\tvar resultados = tablaUsers(users);\n\t\t\n\t\tresultado.html(resultados);\n\t}",
"function displayStudents() {\n const students = fetchStudents();\n for (const student of students) {\n addStudentToTable(student);\n }\n}",
"function renderUsers(users) {\n allUsers.empty();\n allUsers.append(users.join('<br>'))\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Interviewer: Phillip for tenwei problem: remove letter if it proceeds a hash tag return string without hash tag "ab" => "a" "ab" => "" "aab" => "b" "ababb" => "ab" high level solution: create an array iterate through the string if i = array.pop else array.push return array.join("") | function removeHashTag(array) {
const arr = []
for (let i = 0; i < array.length; i++) {
if (array[i] === "#") {
arr.pop
} else {
arr.push(array[i])
}
}
return arr.join("")
} | [
"function stripHashtags(arr) {\n for(var i = 0; i < arr.length; i++) {\n if(arr[i].charAt(0) == \"#\") {\n arr[i] = arr[i].substr(1);\n }\n }\n return arr;\n}",
"function cleanUp(string) {\n let alphebets = \"abcdefghijklmnopqrstuvwxyz\";\n let result = \"\";\n \n\n for (index = 0; index < string.length; index += 1) {\n let char = string[index] ;\n let prevChar = string[index - 1];\n\n if (alphebets.includes(char)) {\n result += string[index];\n } else if (index === 0 || alphebets.includes(prevChar)) {\n result += \" \";\n } \n }\n\n return result;\n}",
"function generateHashtag (str) {\nconsole.log(str);\n if (str == \"\" || /^\\s*$/.test(str)){\n \treturn false\n } else {\n\nvar arr = str.trim().split(' ');\nvar arr1 = [];\n\narr.forEach(word => {\n\tlet arr1word = word.charAt(0).toUpperCase() + word.slice(1);\n\tarr1.push(arr1word);\n\n});\n\nvar hash = \"#\" + arr1.join('');\nif(hash.length > 140 ){\nreturn false;\n}else{ return hash;}\n\n}\n\n}",
"function makeHashTag(str) {\n const str_words = str.split(/ |\\B(?=[A-Z])/);\n\n for (let i = 0; i < str_words.length; i++) {\n str_words[i] = '#' + str_words[i][0].toUpperCase() + str_words[i].substr(1);\n }\n return str_words.join()\n }",
"function removedHashTag() {\n for (i = 0; i <= arrayHoursId.length - 1; i++) {\n NotHashHours[i] = arrayHoursId[i].split(\"#\").pop();\n }\n }",
"function remove(str,arr){\n //create new string\n let result = '';\n for(let i=0;i < str.length;i++){\n if(arr[0] !== i){\n result += str[i]\n }else{\n arr.shift()\n }\n\n }\n return result;\n}",
"function hipsterfy(sentence){\n\n var vowels = ['a', 'e', 'i', 'o', 'u'];\n\n var sentArr = sentence.split(' ');\n//iterate through the array:\n for(var i = 0; i < sentArr.length; i++){\n var word = sentArr[i];\n // console.log(word);\n //iterate through the element itself:\n // for(var j = 0; j < word.length; j++)\n\n //reverse forloop, start from the back of string:\n // j >=0, you want to get to index 0 by iterating\n //from largest index position to lowest.\n for(var j = word.length - 1; j >= 0; j--){\n // console.log(word[j]);\n if(vowels.indexOf(word[j]) !== -1){\n // console.log(word[j]);\n // word.replace(word.substring(j, j+1), \"\");\n sentArr[i] = word.slice(0, j) + word.slice(j+1);\n console.log(word);\n break;\n }\n }\n\n }\n return sentArr.join(' ');\n}",
"function generateHashtag(s) {\n console.log(s);\n // first I need to split the string into the individual words\n let eachWord = s.split(' ');\n // next create an array that will hold the individual words\n let words = ['#'];\n for (let word of eachWord) {\n // the extra spaces will return 'undefined' so ignoring those...\n if (word[0] !== undefined) {\n // console.log(word[0]);\n // add the word with the first letter capital\n words.push(word.replace(word[0], word[0].toUpperCase()));\n }\n }\n // console.log(words);\n // if answer only has the # (it is empty) return 'false'\n if (words.length === 1) {\n return false;\n } else {\n // join the array together back into a single word\n let answer = words.join('');\n if (answer.length > 140) {\n return false;\n } else {\n console.log(answer);\n return answer;\n }\n }\n}",
"function dedupe(str) {\n let newStr = \"\";\n for (let letter of str) {\n // console.log(letter)\n if (!newStr.includes(letter)){\n newStr += letter\n }\n }\n return newStr;\n}",
"function dupeRemove(str){\n // use hash\n\n // check for valid input\n if(typeof str !== 'string' || !str){\n return \"invalid input, please provide a valid string\"\n }\n\n // instantiate hash map\n var allChars = {};\n\n // instantiate str\n var noDupes = \"\";\n\n // split string into array of letters\n var letters = str.split(\"\");\n\n\n for (var i = 0; i < letters.length; i++){\n // add key if not already there\n if(!allChars[letters[i]]){\n allChars[letters[i]] = 1;\n }\n // if dupe, do nothing\n else{}\n }\n\n // for each key in hash map, add to new string\n for (var key in allChars){\n // add letter to string \n noDupes += key;\n }\n\n return noDupes;\n}",
"function superReducedString(s) {\n let arr = s.split('')\n for(let i = 0; i < arr.length - 1;){\n if(arr[i] === arr[i + 1]){\n arr.splice(i, 2)\n i = 0 \n }else{\n i++\n }\n }\n\n if(!arr.join(\"\")){\n return 'Empty String'\n }else{\n return arr.join('')\n }\n \n \n\n\n}",
"function getStrings(hash) {\n\tlet results = [];\n\tif(hash === 7) {\n\t\treturn [''];\n\t}\n\telse if(hash < 7*37) {\n\t\treturn [];\n\t}\n\telse {\n\t\tlet options = getPreviousHashOptions(hash);\n\n\t\tfor(let i=0; i<options.length; i++) {\n\t\t\tlet strings = getStrings(options[i].hash);\n\t\t\tfor(let j=0; j<strings.length; j++) {\n\t\t\t\tresults.push(strings[j] + options[i].letter);\n\t\t\t}\n\t\t}\n\t}\n\treturn results;\n}",
"function removeDuplicateChars3(str) {\n if (!str) return null;\n if (str.length < 2 ) return str;\n var hit = new Array(256);\n for (let i = 0; i < 256; i++) {\n hit[i] = false;\n }\n hit[str[0]] = true;\n let found = 1;\n\n for (var i = 1; i < str.length; ++i) {\n //console.log(str, i, found, str.slice(0, found), str[i]);\n //console.log(i, str, str[i]);\n if (!hit[str[i]]) {\n str = str.slice(0, found) + str[i] + str.slice(found + 2);\n //console.log(str);\n found++;\n hit[str[i]] = true;\n i--;\n }\n //console.log(i, str, str[i]);\n }\n return str.slice(0, found);\n}",
"function alphabetSoup(str){\n return str.split('').sort().join('');\n}",
"function superReducedString(str) {\n \n for (var i = 1; i < str.length; i++) {\n if (str[i] == str[i-1]) {\n str = str.substring(0, i-1) + str.substring(i+1);\n i = 0;\n }\n }\n if (str.length == 0) {\n return \"Empty String\";\n } else {\n return str;\n }\n\n\n}",
"function chop(str) {\n//Converting the string to an array using .split('').\n let strArr = str.split('');\n/*On each iteration of the for of loop, the letter being iterated over is removed\nand the string is reformed without that letter and stored in let word and\nthe letter that was removed is stored in the ltrs array. The resulting string (stored\nin word) is then checked via pdromeCheck to see if a palindrome can be formed. If so,\nthen then the loop stops running.*/\n for(let [i,char] of strArr.entries()) {\n \t let firstHalf = strArr.slice(0,i);\n \t let secondHalf = strArr.slice(i+1);\n \t let word = ([...firstHalf,...secondHalf]).join('');\n \t ltrs = [strArr[i]];\n \t pdromeCheck(word);\n\t\t if(pass) return;\n }\n/*If a palindrome can't be formed by removing one letter, then chop() will check\nand see if one can be formed by removing two letters. First, we'll run the same\nfor of loop as above only this time a nested loop will be run on each iteration to\ncheck and see if removing a second letter will form a palindrome.*/\n for(let [i,char] of strArr.entries()) {\n let firstHalf = strArr.slice(0,i);\n let secondHalf = strArr.slice(i+1);\n let word = ([...firstHalf,...secondHalf]).join('');\n ltrs = [strArr[i]];\n pdromeCheck(word);\n\n if(pass) {\n break;\n } else {\n/*The nested loop is similar to the outter loop only it is iterating over the word\nvariable instead of strArr.*/\n for(let[i,char] of (word.split('')).entries()) {\n firstHalf = word.slice(0,i);\n secondHalf = word.slice(i+1);\n let wordTwo = ([...firstHalf,...secondHalf]).join('');\n pdromeCheck(wordTwo);\n/*If a palindrome is formed by removal of the letter of the current iteration, then\nthat letter is pushed to the ltrs array which already contains the letter of the\ncurrent iteration of the outer loop. The inner & outer loops are then stopped and\nthe two letters that are now stored in ltrs are the letters that can be removed\nto form a palindrome.*/\n if(pass) {\n ltrs.push(word[i]);\n return;\n }}}}}",
"function ubahHuruf(kata) {\n\tvar kamus = 'abcdefghijklmnopqrstuvwxyz';\n\tvar indexHuruf;\n\tvar result = [];\n\n\tfor (var i = 0; i < kata.length; i++) {\n\t\tfor (var j = 0; j < kamus.length; j++) {\n\t\t\tif (kata[i] === kamus[j]) {\n\t\t\t\tif (kata[i] === 'z') {\n\t\t\t\t\tresult.push(kamus[0]);\n\t\t\t\t} else {\n\t\t\t\t\tindexHuruf = j;\n\t\t\t\t\tresult.push(kamus[indexHuruf+1]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvar fix_result = result.join('');\n\treturn fix_result;\t\n}",
"function removeDuplicates(string){\n var endString = [];\n var letterCounted = {};\n //set initial letter object values to false\n for (i = 0; i < string.length; i++){ \n letterCounted[string[i]] = false;\n }\n for (i = 0; i < string.length; i++){\n //skip if its a space\n if (string[i] === \" \"){\n endString.push(string[i]);\n }\n else {\n // console.log(string[i])\n if (letterCounted[string[i]] === false){\n letterCounted[string[i]] = true;\n endString.push(string[i]);\n }\n }\n }\n return endString;\n}",
"function remDupesOneLoop(str) {\n\n var asciiArr = [],\n arr = str.split(''),\n cc,\n prevEntry;\n\n for(var i=0, len=str.length; i<len; i++) {\n cc = str.charCodeAt(i);\n if( typeof asciiArr[cc] !== 'undefined' ) {\n //this char has been seen before\n prevEntry = asciiArr[cc];\n if( typeof prevEntry === 'number' ) {\n //get it's last position in string and make it ''\n arr[prevEntry] = ''; //if you want to keep only instance of char comment this line\n arr[i] = '';\n //from here we simply store a boolean to indicate that this charCode has occured before in string\n asciiArr[cc] = true;\n } else {\n //we found a boolean which means this character is a duplicate\n arr[i] = '';\n }\n } else {\n //if this is the first time with this char store it's index in array\n asciiArr[cc] = i;\n }\n }\n\n console.log(arr.join(''));\n return arr.join();\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Map WRAM into address space | map_wram(bank_start, bank_end, addr_start, addr_end) {
let offset = 0;
for (let c = bank_start; c <= bank_end; c++) {
for (let i = addr_start; i <= addr_end; i += 0x1000) {
let b = (c << 4) | (i >>> 12);
this.readmap[b].kind = this.writemap[b].kind = MAP_TI.RAM;
this.readmap[b].offset = this.writemap[b].offset = offset;
this.block_is_ROM[b] = false;
this.block_is_RAM[b] = true;
offset += 0x1000;
}
}
} | [
"setup_mem_map_lorom() {\n\t\tthis.clear_map();\n\t\tthis.map_system();\n\n\t\tthis.map_lorom(0x00, 0x3F, 0x8000, 0xFFFF);\n\t\tthis.map_lorom(0x40, 0x7F, 0x8000, 0xFFFF);\n\t\tthis.map_lorom(0x80, 0xBF, 0x8000, 0xFFFF);\n\t\tthis.map_lorom(0xC0, 0xFF, 0x8000, 0xFFFF);\n\n\t\tthis.map_lorom_sram();\n\t\tthis.map_loram(0x00, 0x3F, 0x0000, 0x1FFF, 0);\n\t\tthis.map_loram(0x80, 0xBF, 0x0000, 0x1FFF, 0);\n\t\tthis.map_wram(0x7E, 0x7F, 0x0000, 0xFFFF);\n\t}",
"map_sram(bank_start, bank_end, addr_start, addr_end) {\n\t\tlet offset = 0;\n\t\tfor (let c = bank_start; c <= bank_end; c++) {\n\t\t\tfor (let i = addr_start; i <= addr_end; i += 0x1000) {\n\t\t\t\tlet b = (c << 4) | (i >>> 12);\n\t\t\t\tthis.readmap[b].kind = this.writemap[b].kind = MAP_TI.SRAM;\n\t\t\t\tthis.readmap[b].offset = this.writemap[b].offset = offset;\n\t\t\t\tthis.block_is_ROM[b] = false;\n\t\t\t\tthis.block_is_RAM[b] = false;\n\t\t\t\toffset += 0x1000;\n\t\t\t\t//if (offset > this.SRAMSize) return;\n\t\t\t\tif (offset > this.SRAMSize) offset = 0;\n\t\t\t}\n\t\t}\n\t}",
"map_lorom_sram() {\n\t\tlet hi;\n\t\tif (this.ROMSizebit > 11 || this.SRAMSizebit > 5)\n\t\t\thi = 0x7FFF;\n\t\telse\n\t\t\thi = 0xFFFF;\n\n\t\t// HMMM...\n\t\thi = 0x7FFF;\n\t\tthis.map_sram(0x70, 0x7D, 0x0000, hi);\n\t\tthis.map_sram(0xF0, 0xFF, 0x0000, hi);\n\t}",
"map_system() {\n\t\t// First 8K of RAM\n\t\tthis.map_loram(0x00, 0x3F, 0x0000, 0x1FFF, 0);\n\t\t// PPU regs\n\t\tthis.map_kind(0x00, 0x3F, 0x2000, 0x3FFF, 0x2000, MAP_TI.PPU);\n\t\t// CPU regs\n\t\tthis.map_kind(0x00, 0x3F, 0x4000, 0x5FFF, 0x4000, MAP_TI.CPU);\n\t\t// All of this mirrored again at 0x80\n\t\tthis.map_loram(0x80, 0xBF, 0x00, 0x1FFF, 0);\n\t\tthis.map_kind(0x80, 0xBF, 0x2000, 0x3FFF, 0x2000, MAP_TI.PPU);\n\t\tthis.map_kind(0x80, 0xBF, 0x4000, 0x5FFF, 0x4000, MAP_TI.CPU);\n\t}",
"map_lorom(bank_start, bank_end, addr_start, addr_end) {\n\t\tlet offset = 0;\n\t\tfor (let c = bank_start; c <= bank_end; c++) {\n\t\t\tfor (let i = addr_start; i <= addr_end; i += 0x1000) {\n\t\t\t\tlet b = (c << 4) | (i >>> 12);\n\t\t\t\t//console.log('MAPPING ROM', hex0x6(b << 12), 'offset', hex0x6(offset));\n\t\t\t\tthis.readmap[b].kind = MAP_TI.ROM;\n\t\t\t\tthis.writemap[b].kind = MAP_TI.OPEN_BUS;\n\t\t\t\tthis.readmap[b].offset = offset;\n\t\t\t\tthis.writemap[b].offset = 0;\n\t\t\t\tthis.block_is_ROM[b] = true;\n\t\t\t\tthis.block_is_RAM[b] = false;\n\t\t\t\toffset += 0x1000;\n\t\t\t\tif (offset > this.ROMSize) offset = 0;\n\t\t\t}\n\t\t}\n\t}",
"setup_mem_map_hirom() {\n\t\talert('No HIROM!');\n\t}",
"loadMapsFromMemory(){\n let self = this.reader;\n let type = self.isFRLG() === true ? 1 : 0;\n let header_map = self.memoryOffsets.map_header;\n\t\tlet total_banks = self.getTableSize(header_map);\n\t\tthis.banks = new Array(total_banks);\n\t\tfor(let b = 0; b < total_banks; b++){\n\t\t\tlet bank_offset = self.getOffset(header_map + b * 4);\n\t\t\tlet next_bank_offset \t= self.getOffset(header_map + (b + 1) * 4);\n let bank = this.banks[b] = new Bank(bank_offset);\n if(next_bank_offset < bank_offset) next_bank_offset = header_map;\n\t\t\tfor(let m = bank_offset; m < next_bank_offset; m += 4){\n let map_index = (m - bank_offset) / 4;\n\t\t\t\tlet header_pointer = self.getOffset(m);\n\t\t\t\tlet map_pointer = self.getOffset(header_pointer);\n let map = new Map(b, map_index);\n map.setHeaderOffset(header_pointer);\n map.setMapOffset(map_pointer);\n let name_displacement = 4 * ((2 - type) * (self.getByte(header_pointer + 20) - 88 * type) + 1 - type);\n let name_pointer = self.getOffset(self.memoryOffsets[`map_name_${type}`] + name_displacement);\n map.setMapNameOffset(name_pointer);\n map.setMapName(self.getTextByOffset(self.getDictionary(\"Text\"), name_pointer));\n map.setMapNameEffect(self.getByte(header_pointer + 21));\n map.setScriptOffset(self.getOffset(header_pointer + 8));\n map.setMusic(self.getShort(header_pointer + 16));\n map.setWeather(self.getByte(header_pointer + 22));\n map.setMapType(self.getByte(header_pointer + 23));\n map.setPokemonOffset(self.getByte(header_pointer + 27)); // ?? Offset not Byte\n map.setBorderOffset(self.getOffset(map_pointer + 8));\n //border_width: self.getByte(map + 24), // (??)\n //border_height: self.getByte(map + 25), // (??)\n //title: self.getByte(header_pointer + 26), // (??)\n //index: self.getShort(header_pointer + 18), // Name table index (??)\n\n\t\t\t\t/* Creating map blocks structure. */\n\t\t\t\tlet wmap = self.getShort(map_pointer);\n\t\t\t\tlet hmap = self.getShort(map_pointer + 4);\n if(wmap * hmap > 0){\n \t\t\t\tlet structOffset = self.getOffset(map_pointer + 12);\n map.resize(wmap, hmap);\n map.setStructureOffset(structOffset);\n \t\t\t\tfor(let j = 0; j < hmap; j++){\n \t\t\t\t\tfor(let i = 0; i < wmap; i++){\n \t\t\t\t\t\tmap.setBlock(i, j, self.getShort(structOffset + (i + j * wmap) * 2));\n \t\t\t\t\t}\n \t\t\t\t}\n }\n\t\t\t\t// Reading and Adding all Connections to buffer\n\t\t\t\tlet connection = self.getOffset(header_pointer + 12);\n if(self.isROMOffset(connection)){\n map.setConnectionOffset(connection);\n \t\t\t\tlet firstConnection = self.getOffset(connection + 4);\n \t\t\t\tlet lastConnection = firstConnection + self.getByte(connection) * 12;\n \t\t\t\tfor(let c = firstConnection; c < lastConnection; c += 12){\n let connection = new Connection(self.getByte(c), self.getShort(c + 4)|(self.getShort(c + 6)<<16), self.getByte(c + 8), self.getByte(c + 9));\n \t\t\t\t\tmap.setConnection((c - firstConnection) / 12, connection);\n \t\t\t\t}\n }\n\t\t\t\t// Events in map\n\t\t\t\tlet pointer_events = self.getOffset(header_pointer + 4);\n if(self.isROMOffset(header_pointer)){\n // Adding Overworlds\n \t\t\t\tlet firstperson = self.getOffset(pointer_events + 4);\n if(self.isROMOffset(firstperson)){\n map.setEntityOffset(0, firstperson);\n \t\t\t\tlet lastperson = firstperson + self.getByte(pointer_events) * 24;\n \t\t\t\tfor(let i = firstperson; i < lastperson; i += 24){\n let overworld_index = self.getByte(i)-1;\n let overworld = new Overworld(self.getShort(i + 4), self.getShort(i + 6), self.getByte(i + 8), overworld_index+1);\n overworld.setSpriteIndex(self.getByte(i + 1));\n overworld.setMovement(self.getByte(i + 9));\n overworld.setMovementRadius(self.getByte(i + 10));\n overworld.setTrainer(self.getByte(i + 12));\n overworld.setRangeVision(self.getShort(i + 14));\n overworld.setScriptOffset(self.getOffset(i + 16));\n overworld.setStatus(self.getShort(i + 20));\n map.setEntity(0, overworld_index, overworld);\n \t\t\t\t}\n }\n \t\t\t\t// Adding Warps\n \t\t\t\tlet firstwarp = self.getOffset(pointer_events + 8);\n if(self.isROMOffset(firstwarp)){\n map.setEntityOffset(1, firstwarp);\n let lastwarp = firstwarp + self.getByte(pointer_events + 1) * 8;\n \t\t\t\tfor(let i = firstwarp; i < lastwarp; i += 8){\n let warp_index = (i - firstwarp) / 8;\n let warp = new Warp(self.getShort(i), self.getShort(i + 2), self.getShort(i + 4), warp_index+1);\n warp.setWarpIndex(self.getByte(i + 5));\n warp.setMapIndex(self.getByte(i + 6));\n warp.setBankIndex(self.getByte(i + 7));\n map.setEntity(1, warp_index, warp);\n \t\t\t\t}\n }\n // Adding Scripts\n \t\t\t\tlet firstscript = self.getOffset(pointer_events + 12);\n if(self.isROMOffset(firstscript)){\n map.setEntityOffset(2, firstscript);\n \t\t\t\tlet lastscript = firstscript + self.getByte(pointer_events + 2) * 16;\n \t\t\t\tfor(let i = firstscript; i < lastscript; i += 16){\n let script_index = (i - firstscript) / 16;\n let script = new Script(self.getShort(i), self.getShort(i + 2), self.getByte(i + 4), script_index+1);\n script.setNumber(self.getShort(i + 6));\n script.setValue(self.getByte(i + 8));\n script.setScriptOffset(self.getOffset(i + 12));\n map.setEntity(2, script_index, script);\n \t\t\t\t}\n }\n // Adding signpost\n \t\t\t\tlet firstsignpost = self.getOffset(pointer_events + 16);\n if(self.isROMOffset(firstsignpost)){\n map.setEntityOffset(3, firstsignpost);\n \t\t\t\tlet lastsignpost = firstsignpost + self.getByte(pointer_events + 3) * 12;\n \t\t\t\tfor(let i = firstsignpost; i < lastsignpost; i += 12){\n let signpost_index = (i - firstsignpost) / 12;\n let signpost = new Signpost(self.getShort(i), self.getShort(i + 2), self.getByte(i + 4), signpost_index+1);\n signpost.setSpecial(self.getOffset(i + 8));\n map.setEntity(3, signpost_index, signpost);\n \t\t\t\t}\n }\n }\n\t\t\t\t// There are two tilesets in each map.\n\t\t\t\tfor(let i = 0; i < 2; i++){\n\t\t\t\t\tlet offset = self.getOffset(map_pointer + 16 + 4 * i);\n\n\t\t\t\t\t/* Obtaning the palettes from the tilesets. */\n\t\t\t\t\tlet primary = self.getByte(offset + 1); /* Primary tileset [Byte] */\n\t\t\t\t\tlet palette_offset = self.getOffset(offset + 8) + 0x20 * (6 + self.isFRLG()) * primary;\n let palette_index = this.getPaletteIndex(palette_offset);\n\t\t\t\t\tif(palette_index === -1){\n palette_index = this.palette_buffer.length;\n\t\t\t\t\t\tthis.palette_buffer.push({offset: palette_offset, memory: this.getTilesetPalettes(palette_offset, primary), primary: !!primary});\n\t\t\t\t\t}\n map.setPalettesIndex(i, palette_index);\n\n\t\t\t\t\t/* Obtaning blocks. */\n\t\t\t\t\tlet block_offset = self.getOffset(offset + 12);\n\t\t\t\t\tlet last_block_offset\t= type ? self.getOffset(offset + 20) : self.getOffset(offset + 16);\n let block_index = this.getBlockIndex(block_offset);\n\t\t\t\t\tif(block_index === -1){\n let used_blocks \t= (last_block_offset - block_offset) >> 4;\n\t\t\t\t\t\tlet total_blocks = Math.max(0x200, used_blocks);\n\t\t\t\t\t\tlet data_blocks = new Array(total_blocks);\n\t\t\t\t\t\tfor(let b = 0; b < total_blocks; b++){\n\t\t\t\t\t\t\tdata_blocks[b] = new Array(8);\n\t\t\t\t\t\t\tfor(let o = 0; o < 8; o++){\n\t\t\t\t\t\t\t\tdata_blocks[b][o] = self.getShort(block_offset + b * 16 + o * 2);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n block_index = this.block_buffer.length;\n\t\t\t\t\t\tthis.block_buffer.push({offset: block_offset, memory: data_blocks, totalBlocks: used_blocks, images: []});\n\t\t\t\t\t}\n map.setBlocksIndex(i, block_index);\n\n\t\t\t\t\t/* Creating tile blocks. */\n\t\t\t\t\tlet tileset_offset = self.getOffset(offset + 4);\n let tileset_index = this.getTilesetIndex(tileset_offset);\n\t\t\t\t\tif(tileset_index === -1){\n\t\t\t\t\t\tlet tileset_decompress;\n let compressed = self.getByte(tileset_offset);\n\t\t\t\t\t\tif(compressed){\n\t\t\t\t\t\t\tlet totalunCompressed = self.getByte(tileset_offset + 1)<<1|self.getByte(tileset_offset + 2)<<9|self.getByte(tileset_offset + 3)<<17;\n\t\t\t\t\t\t\ttileset_decompress = Decompressor.LZSS_Decompress(self.ReadOnlyMemory.slice(tileset_offset + 4, tileset_offset + 4 + totalunCompressed), 0x8000);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\ttileset_decompress = Decompressor.GBA_Decompress(self.ReadOnlyMemory.slice(tileset_offset, tileset_offset + 0x4000));\n\t\t\t\t\t\t}\n\n let tileset_canvas = document.createElement(\"canvas\");\n let tileset_ctx = tileset_canvas.getContext(\"2d\");\n let tileset_width = tileset_canvas.width = 128;\n let tileset_height = tileset_canvas.height = 256;\n let tilset_image = tileset_ctx.getImageData(0, 0, tileset_width, tileset_height);\n\n // Draw tilesetsheet\n let block_size = 8, p = 0;\n for(let h = 0; h < tileset_height; h += block_size){\n for(let w = 0; w < tileset_width; w += block_size){\n for(let m = 0; m < block_size; m++){\n for(let n = 0; n < block_size; n++){\n let px = tileset_decompress[p++] * 16;\n let id = (w + n) + (h + m) * tileset_width, idx = id * 4;\n tilset_image.data[idx + 0] = px;\n tilset_image.data[idx + 1] = px;\n tilset_image.data[idx + 2] = px;\n tilset_image.data[idx + 3] = 255;\n }\n }\n }\n }\n tileset_ctx.putImageData(tilset_image, 0, 0);\n tileset_index = this.tileset_buffer.length;\n\t\t\t\t\t\tthis.tileset_buffer.push(new Tileset(tileset_offset, tileset_decompress, tileset_canvas, compressed));\n\t\t\t\t\t}\n map.setTilesetsIndex(i, tileset_index);\n\t\t\t\t}\n bank.setMap(map_index, map);\n\t\t\t}\n\t\t}\n\t}",
"function compileMemoryDMA0ReadDispatch(readUnused, readExternalWRAM, readInternalWRAM, readIODispatch, readVRAM, readBIOS) {\n var code = 'address = address | 0;var data = 0;switch (address >> 24) {';\n /*\n Decoder for the nibble at bits 24-27\n (Top 4 bits of the address falls through to default (unused),\n so the next nibble down is used for dispatch.):\n */\n /*\n BIOS Area (00000000-00003FFF)\n Unused (00004000-01FFFFFF)\n */\n code += 'case 0:{data = this.' + readBIOS + '(address | 0) | 0;break};';\n /*\n Unused (00004000-01FFFFFF)\n */\n /*\n WRAM - On-board Work RAM (02000000-0203FFFF)\n Unused (02040000-02FFFFFF)\n */\n if (readExternalWRAM.slice(0, 10) != 'readUnused') {\n code += 'case 0x2:';\n if (readExternalWRAM.slice(0, 12) != 'readInternal') {\n code += '{data = this.' + readExternalWRAM + '(address | 0) | 0;break};';\n }\n }\n /*\n WRAM - In-Chip Work RAM (03000000-03007FFF)\n Unused (03008000-03FFFFFF)\n */\n if (readInternalWRAM.slice(0, 10) != 'readUnused') {\n code += 'case 0x3:{data = this.' + readInternalWRAM + '(address | 0) | 0;break};';\n }\n /*\n I/O Registers (04000000-040003FE)\n Unused (04000400-04FFFFFF)\n */\n code += 'case 0x4:{data = this.' + readIODispatch + '(address | 0) | 0;break};';\n /*\n BG/OBJ Palette RAM (05000000-050003FF)\n Unused (05000400-05FFFFFF)\n */\n code += 'case 0x5:';\n /*\n VRAM - Video RAM (06000000-06017FFF)\n Unused (06018000-06FFFFFF)\n */\n code += 'case 0x6:';\n /*\n OAM - OBJ Attributes (07000000-070003FF)\n Unused (07000400-07FFFFFF)\n */\n code += 'case 0x7:{data = this.' + readVRAM + '(address | 0) | 0;break};';\n /*\n Unused, DMA 0 cannot read past 07FFFFFF:\n */\n code += 'default:{data = this.' + readUnused + '(' + (readUnused.slice(0, 12) == 'readUnused32' ? '' : 'address | 0') + ') | 0};';\n //Generate the function:\n code += '}return data | 0;';\n return Function('address', code);\n }",
"function loadRegisterFromMemory(cpu, registerName, location) {\n //cpu.memory.get_location(location);\n}",
"loadProgramIntoMemory(program)\r\n {\r\n for (let i = 0; i < program.length; i++)\r\n {\r\n this.memory[0x200 + i] = program[i];\r\n }\r\n }",
"MEMLOAD() {\n // set membus address\n this.membus.ADDR = this.reg.MAR;\n // instruct memory to read\n this.membus.READ();\n // set MDR\n this.reg.MDR = this.membus.DATA();\n // this.reg.MDR = this.mem[this.reg.MAR];\n }",
"MEMSTORE() {\n // Set memory address\n this.membus.ADDR = this.reg.MAR;\n // Set memory write value\n this.membus.ADDRVAL = this.reg.MDR;\n // instruct memory to write\n this.membus.WRITE();\n // this.mem[this.reg.MAR] = this.reg.MDR;\n }",
"function mapVirtualToPhysical(virtualAddress, accessMask) {\n \"use strict\";\n var page, pdr, physicalAddress, errorMask;\n //var CPU = window.CPU;\n CPU.displayAddress = virtualAddress & 0xffff; // Remember the 16b virtual address for display purposes\n if (!(accessMask & CPU.mmuEnable)) { // This access does not require the MMU\n physicalAddress = virtualAddress & 0xffff; // virtual address without MMU is 16 bit (no I&D)\n CPU.mmuLastPage = 0; // Data light off for no mapping\n if (physicalAddress >= IOBASE_VIRT) {\n physicalAddress |= IOBASE_22BIT;\n } else { // no max_memory check in 16 bit mode\n if ((physicalAddress & 1) && !(accessMask & MMU_BYTE)) { // odd address check\n CPU.displayPhysical = -1; // Set ADRS ERR light\n CPU.CPU_Error |= 0x40;\n return trap(4, 22);\n }\n }\n } else { // This access is mapped by the MMU\n if (!(CPU.MMR3 & (4 / (CPU.mmuMode + 1)))) { // Use I space unless D space is enabled\n virtualAddress &= 0xffff;\n }\n page = (CPU.mmuMode << 4) | (virtualAddress >>> 13);\n physicalAddress = (CPU.mmuPAR[page] + (virtualAddress & 0x1fff)) & 0x3fffff;\n if (!(CPU.MMR3 & 0x10)) { // 18 bit mapping needs extra trimming\n physicalAddress &= 0x3ffff;\n if (physicalAddress >= IOBASE_18BIT) {\n physicalAddress |= IOBASE_22BIT;\n }\n }\n if (physicalAddress < MAX_MEMORY) { // Ordinary memory space only needs an odd address check\n if ((physicalAddress & 1) && !(accessMask & MMU_BYTE)) {\n CPU.displayPhysical = -1; // Set ADRS ERR light\n CPU.CPU_Error |= 0x40;\n return trap(4, 26);\n }\n CPU.mmuLastPage = page;\n } else { // Higher addresses may require unibus mapping and a check if non-existent\n if (physicalAddress < IOBASE_22BIT) {\n if (physicalAddress >= IOBASE_UNIBUS) {\n physicalAddress = mapUnibus(physicalAddress & 0x3ffff); // 18bit unibus space\n if (physicalAddress >= MAX_MEMORY && physicalAddress < IOBASE_22BIT) {\n CPU.displayPhysical = -1; // Set ADRS ERR light\n CPU.CPU_Error |= 0x10; // Unibus timeout\n return trap(4, 24); // KB11-EM does this after ABORT handling - KB11-CM before\n }\n } else {\n CPU.displayPhysical = -1; // Set ADRS ERR light\n CPU.CPU_Error |= 0x20; // Non-existent main memory\n return trap(4, 24);\n }\n }\n if (CPU.mmuMode || (physicalAddress !== 0x3fff7a)) { // MMR0 is 017777572 and doesn't affect MMR0 bits\n CPU.mmuLastPage = page;\n }\n }\n errorMask = 0;\n pdr = CPU.mmuPDR[page];\n switch (pdr & 0x7) { // Check the Access Control Field (ACF) - really a page type\n case 1: // read-only with trap\n errorMask = 0x1000; // MMU trap - then fall thru\n case 2: // read-only\n CPU.mmuPDR[page] |= 0x80; // Set A bit\n if (accessMask & MMU_WRITE) {\n errorMask = 0x2000; // read-only abort\n }\n break;\n case 4: // read-write with read-write trap\n errorMask = 0x1000; // MMU trap - then fall thru\n case 5: // read-write with write trap\n if (accessMask & MMU_WRITE) {\n errorMask = 0x1000; // MMU trap - then fall thru\n }\n case 6: // read-write\n CPU.mmuPDR[page] |= ((accessMask & MMU_WRITE) ? 0xc0 : 0x80); // Set A & W bits\n break;\n default:\n errorMask = 0x8000; // non-resident abort\n break;\n }\n if (pdr & 0x8) { // Page expands downwards\n if ((pdr &= 0x7f00)) { // If a length to check\n if (((virtualAddress << 2) & 0x7f00) < pdr) {\n errorMask |= 0x4000; // page length error abort\n }\n }\n } else { // Page expand upwards\n if ((pdr &= 0x7f00) !== 0x7f00) { // If length not maximum check it\n if (((virtualAddress << 2) & 0x7f00) > pdr) {\n errorMask |= 0x4000; // page length error abort\n }\n }\n }\n // aborts and traps: log FIRST trap and MOST RECENT abort\n if (errorMask) {\n if (errorMask & 0xe000) {\n if (CPU.trapPSW >= 0) {\n errorMask |= 0x80; // Instruction complete\n }\n if (!(CPU.MMR0 & 0xe000)) {\n CPU.MMR0 |= errorMask | (CPU.mmuLastPage << 1);\n }\n CPU.displayPhysical = -1; // Set ADRS ERR light\n return trap(0xa8, 28); // 0250\n }\n if (!(CPU.MMR0 & 0xf000)) {\n if (physicalAddress < 0x3ff480 || physicalAddress > 0x3fffbf) { // 017772200 - 017777677\n CPU.MMR0 |= 0x1000; // MMU trap flag\n if (CPU.MMR0 & 0x0200) {\n CPU.trapMask |= 2; // MMU trap\n }\n }\n }\n }\n }\n return (CPU.displayPhysical = physicalAddress);\n}",
"function mapUnibus(unibusAddress) {\r\n \"use strict\";\r\n var idx = (unibusAddress >>> 13) & 0x1f;\r\n if (idx < 31) {\r\n if (CPU.MMR3 & 0x20) {\r\n unibusAddress = (CPU.unibusMap[idx] + (unibusAddress & 0x1fff)) & 0x3fffff;\r\n }\r\n } else {\r\n unibusAddress |= IOBASE_22BIT; // top page always maps to unibus i/o page - apparently.\r\n }\r\n return unibusAddress;\r\n}",
"function resetMemoryState(rom) {\n // RAM Array\n ram = new Array(0x800).fill(0);\n\n // Mapper detection & cartridge space function mapping\n if(mappers[rom.header.mapper])\n mappers[rom.header.mapper].init(rom);\n else\n throw `ROM uses unimplemented mapper $${rom.header.mapper.toString(16).padStart(2,0)}`;\n}",
"function compileMemoryReadDispatch(\n readUnused,\n readExternalWRAM,\n readInternalWRAM,\n readIODispatch,\n readVRAM,\n readROM,\n readROM2,\n readSRAM,\n readBIOS\n ) {\n var code = 'address = address | 0;var data = 0;switch (address >> 24) {';\n /*\n Decoder for the nibble at bits 24-27\n (Top 4 bits of the address falls through to default (unused),\n so the next nibble down is used for dispatch.):\n */\n /*\n BIOS Area (00000000-00003FFF)\n Unused (00004000-01FFFFFF)\n */\n code += 'case 0:{data = this.' + readBIOS + '(address | 0) | 0;break};';\n /*\n Unused (00004000-01FFFFFF)\n */\n /*\n WRAM - On-board Work RAM (02000000-0203FFFF)\n Unused (02040000-02FFFFFF)\n */\n if (readExternalWRAM.slice(0, 10) != 'readUnused') {\n code += 'case 0x2:';\n if (readExternalWRAM.slice(0, 12) != 'readInternal') {\n code += '{data = this.' + readExternalWRAM + '(address | 0) | 0;break};';\n }\n }\n /*\n WRAM - In-Chip Work RAM (03000000-03007FFF)\n Unused (03008000-03FFFFFF)\n */\n if (readInternalWRAM.slice(0, 10) != 'readUnused') {\n code += 'case 0x3:{data = this.' + readInternalWRAM + '(address | 0) | 0;break};';\n }\n /*\n I/O Registers (04000000-040003FE)\n Unused (04000400-04FFFFFF)\n */\n code += 'case 0x4:{data = this.' + readIODispatch + '(address | 0) | 0;break};';\n /*\n BG/OBJ Palette RAM (05000000-050003FF)\n Unused (05000400-05FFFFFF)\n */\n code += 'case 0x5:';\n /*\n VRAM - Video RAM (06000000-06017FFF)\n Unused (06018000-06FFFFFF)\n */\n code += 'case 0x6:';\n /*\n OAM - OBJ Attributes (07000000-070003FF)\n Unused (07000400-07FFFFFF)\n */\n code += 'case 0x7:{data = this.' + readVRAM + '(address | 0) | 0;break};';\n /*\n Game Pak ROM (max 16MB) - Wait State 0 (08000000-08FFFFFF)\n */\n code += 'case 0x8:';\n /*\n Game Pak ROM/FlashROM (max 16MB) - Wait State 0 (09000000-09FFFFFF)\n */\n code += 'case 0x9:';\n /*\n Game Pak ROM (max 16MB) - Wait State 1 (0A000000-0AFFFFFF)\n */\n code += 'case 0xA:';\n /*\n Game Pak ROM/FlashROM (max 16MB) - Wait State 1 (0B000000-0BFFFFFF)\n */\n code += 'case 0xB:{data = this.' + readROM + '(address | 0) | 0;break};';\n /*\n Game Pak ROM (max 16MB) - Wait State 2 (0C000000-0CFFFFFF)\n */\n code += 'case 0xC:';\n /*\n Game Pak ROM/FlashROM (max 16MB) - Wait State 2 (0D000000-0DFFFFFF)\n */\n code += 'case 0xD:{data = this.' + readROM2 + '(address | 0) | 0;break};';\n /*\n Game Pak SRAM (max 64 KBytes) - 8bit Bus width (0E000000-0E00FFFF)\n */\n code += 'case 0xE:';\n /*\n Game Pak SRAM (max 64 KBytes) - 8bit Bus width (0E000000-0E00FFFF)\n Mirrored up to 0FFFFFFF\n */\n code += 'case 0xF:{data = this.' + readSRAM + '(address | 0) | 0;break};';\n /*\n Unused (10000000-FFFFFFFF)\n */\n code += 'default:{data = this.' + readUnused + '(' + (readUnused.slice(0, 12) == 'readUnused32' ? '' : 'address | 0') + ') | 0};';\n //Generate the function:\n code += '}return data | 0;';\n return Function('address', code);\n }",
"function Mmu(size) { // ./common/mmu.js:12\n //member cpu , to save space i wont make a setter. its set by the emu object // ./common/mmu.js:13\n this.physicalMemory = new OctetBuffer(size); // ./common/mmu.js:14\n // structure of tlb, each tlb entry = 4 array entries, 2 tag entry (1 for page mask) + 2 data entries // ./common/mmu.js:15\n this.tlb = new Uint32Array(4*16); // ./common/mmu.js:16\n for(i = 0; i < 48; i++) // ./common/mmu.js:17\n { // ./common/mmu.js:18\n this.tlb[i] = 0; // ./common/mmu.js:19\n } // ./common/mmu.js:20\n // ./common/mmu.js:21\n this.uart = new UART_16550(); // ./common/mmu.js:22\n // ./common/mmu.js:23\n this.writeTLBEntry = function(index, entrylo0, entrylo1, entryhi, pagemask) // ./common/mmu.js:24\n { // ./common/mmu.js:25\n var tlb = this.tlb; // ./common/mmu.js:26\n var g = ((entrylo0 & entrylo1) >>> 0) & 0x1; // ./common/mmu.js:27\n var pfn0 = (entrylo0 >>> 6) & 0xfffff; // ./common/mmu.js:28\n var entrylo0low = ((entrylo0) & 0x3e) >>> 1; // ./common/mmu.js:29\n var pfn1 = (entrylo1 >>> 6) & 0xfffff; // ./common/mmu.js:30\n var entrylo1low = ((entrylo1) & 0x3e) >>> 1; // ./common/mmu.js:31\n var vpn2 = (entryhi >>> 13); // ./common/mmu.js:32\n var asid = (entryhi & 0xff) >>> 0; // ./common/mmu.js:33\n // ./common/mmu.js:34\n tlb[index*4] = pagemask;//(pagemask >>> 13) & 0xfff; // ./common/mmu.js:35\n tlb[index*4+1] = ((vpn2 << 9) | (g << 8) | asid) >>> 0; // ./common/mmu.js:36\n tlb[index*4+2] = (pfn0 << 5) | entrylo0low; // ./common/mmu.js:37\n tlb[index*4+3] = (pfn1 << 5) | entrylo1low; // ./common/mmu.js:38\n // ./common/mmu.js:39\n //console.log(\"Writing tlb, index: \" + index + \", pagemask: \" + tlb[index*4].toString(16) + \", tag: \" + tlb[index*4+1].toString(16) + \", data0: \" + tlb[index*4+2].toString(16) + \", data1: \" + tlb[index*4+3].toString(16)); // ./common/mmu.js:40\n } // ./common/mmu.js:41\n // ./common/mmu.js:42\n this.tlbProbe = function(entryhi) // ./common/mmu.js:43\n { // ./common/mmu.js:44\n var tlb = this.tlb; // ./common/mmu.js:45\n var vpn2 = (entryhi >>> 13); // ./common/mmu.js:46\n var asid = (entryhi & 0xff) >>> 0; // ./common/mmu.js:47\n // ./common/mmu.js:48\n for(i = 0; i < 64; i+=4) // ./common/mmu.js:49\n { // ./common/mmu.js:50\n var tlbEntry = tlb[i+1]; // ./common/mmu.js:51\n var entry_vpn2 = (tlbEntry >>> 9) & 0x7ffff; // ./common/mmu.js:52\n var entry_asid = (tlbEntry & 0xff); // ./common/mmu.js:53\n if((entry_vpn2 == vpn2) && (entry_asid == asid)) // ./common/mmu.js:54\n { // ./common/mmu.js:55\n return i; // ./common/mmu.js:56\n } // ./common/mmu.js:57\n } // ./common/mmu.js:58\n // ./common/mmu.js:59\n return -1; // ./common/mmu.js:60\n } // ./common/mmu.js:61\n // ./common/mmu.js:62\n this.readTLBEntry = function(index) // ./common/mmu.js:63\n { // ./common/mmu.js:64\n var ret = new Array[4]; // ./common/mmu.js:65\n var tlb = this.tlb; // ./common/mmu.js:66\n // ./common/mmu.js:67\n var pagemask_raw = tlb[index]; // ./common/mmu.js:68\n var pagemask = Math.pow(2,pagemask_raw*2)-1; // ./common/mmu.js:69\n // ./common/mmu.js:70\n var tlbTag1 = tlb[index+1]; // ./common/mmu.js:71\n // ./common/mmu.js:72\n var vpn2 = tlbTag1 >>> 9; // ./common/mmu.js:73\n var g = (tlbTag1 >>> 8) & 0x1; // ./common/mmu.js:74\n var asid = (tlbTag1 & 0xff); // ./common/mmu.js:75\n // ./common/mmu.js:76\n var tlbEntry0 = tlb[index+2]; // ./common/mmu.js:77\n // ./common/mmu.js:78\n var pfn0 = (tlbEntry0 >>> 5) & 0xfffff; // ./common/mmu.js:79\n var entrylo0low = tlbEntry0 & 0x3f; // ./common/mmu.js:80\n // ./common/mmu.js:81\n var tlbEntry1 = tlb[index+3]; // ./common/mmu.js:82\n // ./common/mmu.js:83\n var pfn1 = (tlbEntry1 >>> 5) & 0xfffff; // ./common/mmu.js:84\n var entrylo1low = tlbEntry1 & 0x3f; // ./common/mmu.js:85\n // ./common/mmu.js:86\n var entrylo0 = entrylo0low | (pfn0 << 6); // ./common/mmu.js:87\n var entrylo1 = entrylo1low | (pfn1 << 6); // ./common/mmu.js:88\n // ./common/mmu.js:89\n var entryhi = (asid | (vpn2 << 13)) >>> 0; // ./common/mmu.js:90\n // ./common/mmu.js:91\n ret[0] = entrylo0low; // ./common/mmu.js:92\n ret[1] = entrylo1low; // ./common/mmu.js:93\n ret[2] = entryhi; // ./common/mmu.js:94\n ret[3] = pagemask; // ./common/mmu.js:95\n return ret; // ./common/mmu.js:96\n } // ./common/mmu.js:97\n // ./common/mmu.js:98\n this.tlbLookup = function (addr, write) { // ./common/mmu.js:99\n //console.log(\"TLB lookup of addr: \" + addr.toString(16)); // ./common/mmu.js:100\n var asid = this.cpu.entryHiReg.ASID; // ./common/mmu.js:101\n var vpn2 = addr >>> 13; // ./common/mmu.js:102\n var tlb = this.tlb; // ./common/mmu.js:103\n var invalidCount = 0; // ./common/mmu.js:104\n // ./common/mmu.js:105\n //console.log(\"Lookup ASID: \" + asid + \", VPN2: \" + vpn2); // ./common/mmu.js:106\n // ./common/mmu.js:107\n for(var i = 0; i < 64; i+= 4) // ./common/mmu.js:108\n { // ./common/mmu.js:109\n var tlbentry = tlb[i+1]; // ./common/mmu.js:110\n //console.log(i); // ./common/mmu.js:111\n //console.log(\"Entry ASID: \" + (tlbentry & 0xff)); // ./common/mmu.js:112\n var globalBit = (tlbentry >>> 8) & 0x1; // ./common/mmu.js:113\n // ./common/mmu.js:114\n //console.log(\"Global: \" + globalBit); // ./common/mmu.js:115\n // ./common/mmu.js:116\n if(((tlbentry & 0xff) == asid) | (globalBit == 0)) // ./common/mmu.js:117\n { // ./common/mmu.js:118\n var pagemask_raw = tlb[i]; // ./common/mmu.js:119\n var pagemask = Math.pow(2,pagemask_raw*2)-1; // ./common/mmu.js:120\n var pagemask_n = (~(pagemask) & 0xfff) >>> 0; // ./common/mmu.js:121\n var vpn2entry = (tlbentry >>> 9) & pagemask_n ; // ./common/mmu.js:122\n var vpn2comp = (vpn2 & pagemask_n); // ./common/mmu.js:123\n // ./common/mmu.js:124\n //console.log(\"VPN2Entry: \" + vpn2entry.toString(16) + \", VPN2Comp: \" + vpn2comp.toString(16)); // ./common/mmu.js:125\n if(vpn2entry == vpn2comp) // ./common/mmu.js:126\n { // ./common/mmu.js:127\n //console.log(\"TLB match at index: \" + i); // ./common/mmu.js:128\n var evenoddbit = 12 + pagemask_raw*2; // ./common/mmu.js:129\n //console.log(\"evenoddbit: \" + evenoddbit); // ./common/mmu.js:130\n var evenoddbitVal = (addr >>> evenoddbit) & 0x1; // ./common/mmu.js:131\n //console.log(\"evenoddbitVal: \" + evenoddbitVal.toString(16)); // ./common/mmu.js:132\n var dataEntry = tlb[i+2+evenoddbitVal]; // ./common/mmu.js:133\n //console.log(\"dataEntry: \" + dataEntry.toString(16)); // ./common/mmu.js:134\n var validBit = dataEntry & 0x1; // ./common/mmu.js:135\n var dirtyBit = (dataEntry >>> 1) & 0x1; // ./common/mmu.js:136\n // ./common/mmu.js:137\n if(!validBit) // ./common/mmu.js:138\n { // ./common/mmu.js:139\n invalidCount = invalidCount + 1; // ./common/mmu.js:140\n continue; // ./common/mmu.js:141\n } // ./common/mmu.js:142\n // ./common/mmu.js:143\n if(write && !dirtyBit) // ./common/mmu.js:144\n { // ./common/mmu.js:145\n INFO(\"tlb modified exception\"); // ./common/mmu.js:146\n this.cpu.entryHiReg.VPN2 = vpn2; // ./common/mmu.js:147\n //this.cpu.entryHiReg.ASID = // ./common/mmu.js:148\n this.cpu.C0Registers[8].putUInt32(addr); // ./common/mmu.js:149\n this.cpu.C0Registers[4].BadVPN2 = vpn2; // ./common/mmu.js:150\n // TLB modified exception // ./common/mmu.js:151\n this.cpu.triggerException(11, 1); // excCode = Mod // ./common/mmu.js:152\n throw 1337; // ./common/mmu.js:153\n //return addr; // ./common/mmu.js:154\n } // ./common/mmu.js:155\n // ./common/mmu.js:156\n var pagemask_lsb = pagemask & 0x1; // ./common/mmu.js:157\n var pagemask_n_lsb = pagemask_n & 0x1; // ./common/mmu.js:158\n // ./common/mmu.js:159\n var offset_mask = 4095 | (pagemask_lsb * 4096) | (pagemask * 8192); // (2^12-1) | (pagemask_lsb << 12) | (pagemask << 13) // ./common/mmu.js:160\n var pa_mask = pagemask_n_lsb + (pagemask_n << 1) + 1040384; // (0b1111111 << 13) | pagemask_n << 1 | pagemask_n_lsb // ./common/mmu.js:161\n var pfn = (dataEntry >>> 5) & pa_mask; // ./common/mmu.js:162\n var pa = (pfn << 12) | (addr & offset_mask); // ./common/mmu.js:163\n //DEBUG(\"pfn: \" + pfn.toString(16) + \", pa: \" + pa.toString(16)); // ./common/mmu.js:164\n return pa; // ./common/mmu.js:165\n } // ./common/mmu.js:166\n } // ./common/mmu.js:167\n // ./common/mmu.js:168\n } // ./common/mmu.js:169\n // ./common/mmu.js:170\n this.cpu.entryHiReg.VPN2 = vpn2; // ./common/mmu.js:171\n this.cpu.C0Registers[4].BadVPN2 = vpn2; // ./common/mmu.js:172\n this.cpu.C0Registers[8].putUInt32(addr); // ./common/mmu.js:173\n // ./common/mmu.js:174\n if(invalidCount > 0) // ./common/mmu.js:175\n { // ./common/mmu.js:176\n this.cpu.entryHiReg.VPN2 = vpn2; // ./common/mmu.js:177\n this.cpu.C0Registers[8].putUInt32(addr); // ./common/mmu.js:178\n this.cpu.C0Registers[4].BadVPN2 = vpn2; // ./common/mmu.js:179\n // TLB invalid exception // ./common/mmu.js:180\n INFO(\"invalid tlb entry, va: \" + addr.toString(16)); // ./common/mmu.js:181\n //console.log(\"invalid tlb entry\"); // ./common/mmu.js:182\n if(write == 1) // ./common/mmu.js:183\n { // ./common/mmu.js:184\n this.cpu.triggerException(12,3); // excCode = TLBS // ./common/mmu.js:185\n } // ./common/mmu.js:186\n else // ./common/mmu.js:187\n { // ./common/mmu.js:188\n this.cpu.triggerException(12,2); // excCode = TLBL // ./common/mmu.js:189\n } // ./common/mmu.js:190\n // ./common/mmu.js:191\n throw 1337; // ./common/mmu.js:192\n //return addr; // ./common/mmu.js:193\n } // ./common/mmu.js:194\n // ./common/mmu.js:195\n // ./common/mmu.js:196\n // TLB refill exception // ./common/mmu.js:197\n if(write == 1) // ./common/mmu.js:198\n { // ./common/mmu.js:199\n this.cpu.triggerException(11,3); // excCode = TLBS // ./common/mmu.js:200\n } // ./common/mmu.js:201\n else // ./common/mmu.js:202\n { // ./common/mmu.js:203\n this.cpu.triggerException(11,2); // excCode = TLBL // ./common/mmu.js:204\n } // ./common/mmu.js:205\n // ./common/mmu.js:206\n INFO(\"TLB miss! va: \" + addr.toString(16)); // ./common/mmu.js:207\n throw 1337; // ./common/mmu.js:208\n } // ./common/mmu.js:209\n // ./common/mmu.js:210\n this.addressTranslation = function(va, write) { // ./common/mmu.js:211\n if(this.cpu.isKernelMode()) // ./common/mmu.js:212\n { // ./common/mmu.js:213\n var top3 = va >>> 29; // ./common/mmu.js:214\n // ./common/mmu.js:215\n // kseg0 // ./common/mmu.js:216\n if(top3 == 0x4) // ./common/mmu.js:217\n { // ./common/mmu.js:218\n return (va - 0x80000000); // ./common/mmu.js:219\n } // ./common/mmu.js:220\n // kseg1 // ./common/mmu.js:221\n else if(top3 == 5) // ./common/mmu.js:222\n { // ./common/mmu.js:223\n return (va - 0xa0000000); // ./common/mmu.js:224\n } // ./common/mmu.js:225\n // kuseg when ERL = 1 // ./common/mmu.js:226\n else if((top3 == 0x6) & (this.cpu.statusRegister.ERL == 1)) // ./common/mmu.js:227\n { // ./common/mmu.js:228\n return va; // ./common/mmu.js:229\n } // ./common/mmu.js:230\n else if((top3 == 0x0) & (this.cpu.statusRegister.ERL == 1)) // ./common/mmu.js:231\n { // ./common/mmu.js:232\n return va; // ./common/mmu.js:233\n } // ./common/mmu.js:234\n // kseg3 in debug mode // ./common/mmu.js:235\n // TODO // ./common/mmu.js:236\n // kuseg (ERL=0), kseg2 and kseg3 // ./common/mmu.js:237\n else // ./common/mmu.js:238\n { // ./common/mmu.js:239\n return this.tlbLookup(va,write); // ./common/mmu.js:240\n } // ./common/mmu.js:241\n } // ./common/mmu.js:242\n else // ./common/mmu.js:243\n { // ./common/mmu.js:244\n if((va >>> 31) == 0) // ./common/mmu.js:245\n { // ./common/mmu.js:246\n return this.tlbLookup(va,write); // ./common/mmu.js:247\n } // ./common/mmu.js:248\n else // ./common/mmu.js:249\n { // ./common/mmu.js:250\n // trigger address error exception // ./common/mmu.js:251\n } // ./common/mmu.js:252\n } // ./common/mmu.js:253\n } // ./common/mmu.js:254\n // ./common/mmu.js:255\n\tthis.readHalfWord = function(address) // ./common/mmu.js:256\n\t{ // ./common/mmu.js:257\n //if(address >= 0xbfd00000) // ./common/mmu.js:258\n //{ // ./common/mmu.js:259\n // INFO(\"IO Reg readHalfWord: \" + address.toString(16)); // ./common/mmu.js:260\n // return 0; // ./common/mmu.js:261\n //} // ./common/mmu.js:262\n\t\treturn this.physicalMemory.getUInt16BE(this.addressTranslation(address,0)); // ./common/mmu.js:263\n\t} // ./common/mmu.js:264\n // ./common/mmu.js:265\n this.writeHalfWord = function(address, val) // ./common/mmu.js:266\n { // ./common/mmu.js:267\n //if(address >= 0xbfd00000) // ./common/mmu.js:268\n //{ // ./common/mmu.js:269\n // INFO(\"IO Reg writeHalfWord: \" + address.toString(16) + \", val: \" + val.toString(16)); // ./common/mmu.js:270\n // return; // ./common/mmu.js:271\n // } // ./common/mmu.js:272\n this.physicalMemory.putUInt16BE(this.addressTranslation(address,1), val); // ./common/mmu.js:273\n } // ./common/mmu.js:274\n // ./common/mmu.js:275\n this.readByte = function(address_in) // ./common/mmu.js:276\n { // ./common/mmu.js:277\n\t\taddress = this.addressTranslation(address_in, 0); // ./common/mmu.js:278\n // ./common/mmu.js:279\n //if(address >= 0xbfd00000) // ./common/mmu.js:280\n //{ // ./common/mmu.js:281\n // INFO(\"IO Reg readByte: \" + address.toString(16)); // ./common/mmu.js:282\n // return 0; // ./common/mmu.js:283\n //} // ./common/mmu.js:284\n if((address >= this.uart.baseAddr) && (address <= this.uart.endAddr)) // ./common/mmu.js:285\n { // ./common/mmu.js:286\n return this.uart.readByte(address); // ./common/mmu.js:287\n } // ./common/mmu.js:288\n else // ./common/mmu.js:289\n { // ./common/mmu.js:290\n return this.physicalMemory.getByte(address); // ./common/mmu.js:291\n } // ./common/mmu.js:292\n } // ./common/mmu.js:293\n // ./common/mmu.js:294\n this.writeByte = function(address_in, val) // ./common/mmu.js:295\n { // ./common/mmu.js:296\n\t\taddress = this.addressTranslation(address_in,1); // ./common/mmu.js:297\n // ./common/mmu.js:298\n //if(address >= 0xbfd00000) // ./common/mmu.js:299\n //{ // ./common/mmu.js:300\n // INFO(\"IO Reg writeByte: \" + address.toString(16) + \", val: \" + val.toString(16)); // ./common/mmu.js:301\n // return; // ./common/mmu.js:302\n //} // ./common/mmu.js:303\n if((address >= this.uart.baseAddr) && (address <= this.uart.endAddr)) // ./common/mmu.js:304\n { // ./common/mmu.js:305\n this.uart.writeByte(address,val); // ./common/mmu.js:306\n } // ./common/mmu.js:307\n else // ./common/mmu.js:308\n { // ./common/mmu.js:309\n this.physicalMemory.putByte(address, val); // ./common/mmu.js:310\n } // ./common/mmu.js:311\n } // ./common/mmu.js:312\n // ./common/mmu.js:313\n\tthis.readWord = function(address) // ./common/mmu.js:314\n\t{ // ./common/mmu.js:315\n //if(address >= 0xbfd00000) // ./common/mmu.js:316\n //{ // ./common/mmu.js:317\n // INFO(\"IO Reg readWord: \" + address.toString(16)); // ./common/mmu.js:318\n // return 0; // ./common/mmu.js:319\n //} // ./common/mmu.js:320\n var addr = this.addressTranslation(address,0); // ./common/mmu.js:321\n // ./common/mmu.js:322\n if((addr >= this.uart.baseAddr) && (addr <= this.uart.endAddr)) // ./common/mmu.js:323\n { // ./common/mmu.js:324\n return this.uart.readWord(addr); // ./common/mmu.js:325\n } // ./common/mmu.js:326\n // ./common/mmu.js:327\n // ./common/mmu.js:328\n\t\tif(this.cpu.getEndianness() == 0) // ./common/mmu.js:329\n\t\t{ // ./common/mmu.js:330\n\t\t\treturn this.physicalMemory.getUInt32LE(addr); // ./common/mmu.js:331\n\t\t} // ./common/mmu.js:332\n\t\telse // ./common/mmu.js:333\n\t\t{ // ./common/mmu.js:334\n\t\t\treturn this.physicalMemory.getUInt32BE(addr); // ./common/mmu.js:335\n\t\t} // ./common/mmu.js:336\n\t} // ./common/mmu.js:337\n // ./common/mmu.js:338\n\tthis.writeWord = function(address, value) // ./common/mmu.js:339\n\t{ // ./common/mmu.js:340\n //if(address >= 0xbfd00000) // ./common/mmu.js:341\n //{ // ./common/mmu.js:342\n // INFO(\"IO Reg writeWord: \" + address.toString(16) + \", val: \" + val.toString(16)); // ./common/mmu.js:343\n // return; // ./common/mmu.js:344\n //} // ./common/mmu.js:345\n //console.log(\"VA: \" + address.toString(16)); // ./common/mmu.js:346\n var addr = this.addressTranslation(address,1); // ./common/mmu.js:347\n // ./common/mmu.js:348\n if((addr >= this.uart.baseAddr) && (addr <= this.uart.endAddr)) // ./common/mmu.js:349\n { // ./common/mmu.js:350\n this.uart.writeWord(addr,val); // ./common/mmu.js:351\n return; // ./common/mmu.js:352\n } // ./common/mmu.js:353\n // ./common/mmu.js:354\n //console.log(\"PA: \" + addr.toString(16)); // ./common/mmu.js:355\n\t\tif(this.cpu.getEndianness() == 0) // ./common/mmu.js:356\n\t\t{ // ./common/mmu.js:357\n\t\t\treturn this.physicalMemory.putUInt32LE(addr, value >>> 0); // ./common/mmu.js:358\n\t\t} // ./common/mmu.js:359\n\t\telse // ./common/mmu.js:360\n\t\t{ // ./common/mmu.js:361\n\t\t\treturn this.physicalMemory.putUInt32BE(addr, value >>> 0); // ./common/mmu.js:362\n\t\t} // ./common/mmu.js:363\n\t} // ./common/mmu.js:364\n // ./common/mmu.js:365\n this.loadSREC = function(srecString, setEntry) // ./common/mmu.js:366\n { // ./common/mmu.js:367\n var srecLines = srecString.split(\"\\n\"); // ./common/mmu.js:368\n // ./common/mmu.js:369\n for(i = 0; i < srecLines.length; i++) // ./common/mmu.js:370\n { // ./common/mmu.js:371\n if(srecLines[i] == \"\") // ./common/mmu.js:372\n { // ./common/mmu.js:373\n continue; // ./common/mmu.js:374\n } // ./common/mmu.js:375\n // ./common/mmu.js:376\n var l = srecLines[i]; // ./common/mmu.js:377\n l = l.replace(\"\\r\",\"\"); // ./common/mmu.js:378\n var t = l[1]; // ./common/mmu.js:379\n // ./common/mmu.js:380\n if(l[0] != 'S') // ./common/mmu.js:381\n { // ./common/mmu.js:382\n ERROR(\"Invalid srec record!\"); // ./common/mmu.js:383\n throw \"Bad srecord\"; // ./common/mmu.js:384\n } // ./common/mmu.js:385\n // ./common/mmu.js:386\n var count = l.substring(2,4); // ./common/mmu.js:387\n var addr = \"\"; // ./common/mmu.js:388\n var data = \"\"; // ./common/mmu.js:389\n var dataEnd = l.length-2; // ./common/mmu.js:390\n // ./common/mmu.js:391\n if(t == '0') // ./common/mmu.js:392\n { // ./common/mmu.js:393\n //DEBUG(\"Ignoring SREC header\"); // ./common/mmu.js:394\n } // ./common/mmu.js:395\n else if(t == '1') // ./common/mmu.js:396\n { // ./common/mmu.js:397\n addr = l.substring(4,8); // ./common/mmu.js:398\n data = l.substring(8, dataEnd); // ./common/mmu.js:399\n //DEBUG(\"data 1 srec \" + addr + \" \" + data); // ./common/mmu.js:400\n } // ./common/mmu.js:401\n else if(t == '2') // ./common/mmu.js:402\n { // ./common/mmu.js:403\n addr = l.substring(4,10); // ./common/mmu.js:404\n data = l.substring(10, dataEnd); // ./common/mmu.js:405\n //DEBUG(\"data 2 srec \" + addr + \" \" + data); // ./common/mmu.js:406\n } // ./common/mmu.js:407\n else if(t == '3') // ./common/mmu.js:408\n { // ./common/mmu.js:409\n addr = l.substring(4,12); // ./common/mmu.js:410\n data = l.substring(12, dataEnd); // ./common/mmu.js:411\n //DEBUG(\"data 3 srec \" + addr + \" \" + data); // ./common/mmu.js:412\n } // ./common/mmu.js:413\n else if(t == '5') // ./common/mmu.js:414\n { // ./common/mmu.js:415\n //DEBUG(\"Ignoring SREC record count field.\"); // ./common/mmu.js:416\n } // ./common/mmu.js:417\n else if((t == '7') | (t == '8') | (t == '9')) // ./common/mmu.js:418\n { // ./common/mmu.js:419\n count = parseInt(count,16)*2 -2; // ./common/mmu.js:420\n addr = l.substring(4,4+count); // ./common/mmu.js:421\n DEBUG(\"Entry point srec: \" + addr); // ./common/mmu.js:422\n // ./common/mmu.js:423\n if(setEntry == 1) // ./common/mmu.js:424\n { // ./common/mmu.js:425\n this.cpu.PC.putUInt32(parseInt(addr,16)); // ./common/mmu.js:426\n } // ./common/mmu.js:427\n } // ./common/mmu.js:428\n else // ./common/mmu.js:429\n { // ./common/mmu.js:430\n ERROR(\"Unknown SREC type: \" + t); // ./common/mmu.js:431\n throw \"Bad srecord\"; // ./common/mmu.js:432\n return; // ./common/mmu.js:433\n } // ./common/mmu.js:434\n // ./common/mmu.js:435\n if((t == '1') | (t == '2') | (t == '3')) // ./common/mmu.js:436\n { // ./common/mmu.js:437\n if((data.length % 2) != 0) // ./common/mmu.js:438\n { // ./common/mmu.js:439\n ERROR(\"Length of data in SREC record is not valid: \" + data.length); // ./common/mmu.js:440\n throw \"Bad srecord\"; // ./common/mmu.js:441\n } // ./common/mmu.js:442\n // ./common/mmu.js:443\n addr = parseInt(addr, 16); // ./common/mmu.js:444\n // ./common/mmu.js:445\n for(j = 0; j < data.length; j+= 2) // ./common/mmu.js:446\n { // ./common/mmu.js:447\n var dataByteStr = data.substring(j,j+2); // ./common/mmu.js:448\n var b = parseInt(dataByteStr,16); // ./common/mmu.js:449\n var offset = j/2; // ./common/mmu.js:450\n this.writeByte(addr + offset, b); // ./common/mmu.js:451\n } // ./common/mmu.js:452\n } // ./common/mmu.js:453\n } // ./common/mmu.js:454\n } // ./common/mmu.js:455\n} // ./common/mmu.js:456",
"function wasm_alloc(instance, size) {\n return syscall(instance, /* mmap */ 192, [0, size]);\n}",
"write_memory(offset, buffer) {\n this.memory.set(buffer, utils.toNum(offset));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checkDbPageContent check content of the page, search list of DBs. Check for certain DB if required Call:res = checkDbPageContent(content,db); Where:res result: true or false. content page content db db we are looking for | function checkDbPageContent(content,db) {
var re = new RegExp(FINDDB_REGEXP_START + (db == 'ANY' ? '[^<]+' : db) + FINDDB_REGEXP_END);
//var res = content.match(re);
//if (res) {
// console.log("MATCH!!\n" + JSON.stringify(res,undefined," "));
//}
//else {
// console.log("Check DB failed");
//}
return re.test(content);
} | [
"function checkForDB(db, database, next){\n\t\tdb.admin().listDatabases(function(err, dbs){\n\t\t\tif(err){\n\t\t\t\tconsole.log(err);\n\t\t\t\tnext(err);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvar found = false;\n\t\t\t\tfor(var i=0;i<dbs.databases.length;i++){\n\t\t\t\t\tif(dbs.databases[i].name == settings.db && !dbs.databases[i].empty){\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tnext(undefined, found);\n\t\t\t}\n\t\t});\n\t}",
"function checkDBs()\n{\n var sCookieText = '';\n var sDatabaseCookie = '';\n var count = document.wfform.Databases.length;\n var noneSelected = true;\n var missing = 1;\n var temp = '';\n\n if (document.wfform.wf_term1.value.length > 0)\n {\n missing = 0;\n }\n if (document.wfform.wf_term2)\n {\n if (document.wfform.wf_term2.value.length > 0)\n {\n missing = 0;\n }\n }\n if (document.wfform.wf_term3)\n {\n if (document.wfform.wf_term3.value.length > 0)\n {\n missing = 0;\n }\n }\n\n if (missing == 1)\n {\n\talert('Please enter a search term!');\n \treturn false;\n }\n\n\n if (document.wfform.wf_field1.value != 'wf_keyword')\n {\n sCookieText += document.wfform.wf_field1.options[document.wfform.wf_field1.selectedIndex].value + \"):(\";\n sCookieText += document.wfform.wf_term1.value + \"):(\";\n }\n else\n {\n sCookieText += \"wf_keyword):(\";\n sCookieText += document.wfform.wf_term1.value + \"):(\";\n }\n if (document.wfform.wf_term2)\n {\n sCookieText += document.wfform.wf_op2.options[document.wfform.wf_op2.selectedIndex].value + \"):(\";\n sCookieText += document.wfform.wf_field2.options[document.wfform.wf_field2.selectedIndex].value + \"):(\";\n sCookieText += document.wfform.wf_term2.value + \"):(\";\n }\n else\n {\n sCookieText += '):():():(';\n }\n if (document.wfform.wf_term3)\n {\n sCookieText += document.wfform.wf_op3.options[document.wfform.wf_op3.selectedIndex].value + \"):(\";\n sCookieText += document.wfform.wf_field3.options[document.wfform.wf_field3.selectedIndex].value + \"):(\";\n sCookieText += document.wfform.wf_term3.value + \"):(\";\n }\n else\n {\n sCookieText += '):():():(';\n }\n \n if (document.wfform.wf_all_years)\n {\n if (document.wfform.wf_all_years.value != null)\n {\n sCookieText += document.wfform.wf_all_years.value + '):(0):(0):(';\n }\n else\n {\n if (document.wfform.wf_all_years[0].checked == true)\n {\n sCookieText += 'yes):(0):(0):(';\n }\n else\n {\n sCookieText += document.wfform.wf_all_years[1].value + '):(';\n sCookieText += document.wfform.wf_from_year.selectedIndex + '):(';\n sCookieText += document.wfform.wf_to_year.selectedIndex + '):(';\n }\n }\n }\n if (document.wfform.wf_ftonly)\n {\n sCookieText += document.wfform.wf_ftonly.checked + '):(';\n }\n if (document.wfform.wf_peeronly)\n {\n sCookieText += document.wfform.wf_peeronly.checked + '):(';\n }\n\n sCookieText = sCookieText.substr(0, sCookieText.length - 3);\n document.cookie = 'wf_search_structure=' + sCookieText + '; Path=/';\n\n if (document.wfform.Databases.value != null)\n {\n sDatabaseCookie += document.wfform.Databases.value;\n document.cookie = 'wf_selected_databases=' + sDatabaseCookie + '; Path=/';\n return true;\n }\n else\n {\n if (document.wfform.Databases.length == null)\n {\n // Only one checkbox present\n if (document.wfform.Databases.checked == true)\n noneSelected = false;\n }\n else\n {\n noneSelected = true;\n for (i=0; i< document.wfform.Databases.length; i++)\n {\n if (document.wfform.Databases[i].checked == true)\n {\n noneSelected = false;\n sDatabaseCookie += document.wfform.Databases[i].value + ',';\n //break;\n }\n }//end of for\n }//end of else\n if (noneSelected == true)\n { \n alert('Please select at least one database!');\n return false;\n }\n else\n {\n sDatabaseCookie = sDatabaseCookie.substr(0, sDatabaseCookie.length - 1);\n document.cookie = 'wf_selected_databases=' + sDatabaseCookie + '; Path=/';\n return true;\n }\n }\n}",
"function chkContentAttached() {\n var temp = true;\n var pgType = \"\";\n if (isRequriedAttachLA == true) {\n for (i = 0; i < getTotalPageInObject(SeqID) ; i++) {\n\n if ((objType == \"content object\" || objType == \"contentobject\") && getPageByIndex(i).type == \"page\") {\n\t\t\t \n pgType = getPageByIndex(i).Qtype.toLowerCase();\n } else {\n pgType = getPageByIndex(i).type.toLowerCase();\n }\n if (pgType == \"longanswer\") {\n if (getPageByIndex(i).filename == undefined || getPageByIndex(i).filename == \"undefined\" || getPageByIndex(i).filename == \"\")\n temp = false;\n }\n }\n }\n return temp;\n}",
"function checkPageLoaded(content) {\n//console.log(\"Check page load for \" + INPUT['type'] + \": \" + PAGECONTENT_REGEXP[INPUT['type']]);\n var re = new RegExp(PAGECONTENT_REGEXP[INPUT['type']]);\n// var res = content.match(re);\n//if (res) {\n// console.log(\"MATCH!!\\n\" + JSON.stringify(res,undefined,\" \"));\n//}\n return re.test(content);\n}",
"function getPage(_page,_list){\n var len,row,tmp,d;\n if(getLicentia(\"Pages\",\"View\")===false){notice(\"<strong class='text-error'>You do not have permission to view the content pages</strong>\",true,0);return false;}\n var mensula=_list?\"system\":false;\n recHistory(_page,mensula,false,false,false,true);\n if(_list){\n $('.system1').tab('show');\n }\n $DB(\"SELECT id,title,content,modified,jesua FROM pages WHERE title=?\",[_page],\"Found page \"+_page,function(results){\n len=results.rows.length;row=[];\n if(len){row=results.rows.item(0);$('footer').data('Tau','deLta');$('footer').data('iota',row['jesua']);}\n else {row['title']=_page;row['content']=\"Click here to add new content\";row['modified']=getToday();$('footer').data('Tau','Alpha');$('footer').data('iota',null);}\n $(\"#body article\").empty();tmp=row['modified'];d=(tmp.search('0000-00-00')!=-1)?getToday():tmp;\n var d1 = new Date(d);d=null;tmp=null;\n var contentEditable=getLicentia(\"Pages\",\"Edit\");\n $anima(\"#body article\",\"section\").vita(\"header\",{},true).vita(\"h1\",{\"id\":\"page_title\",\"contenteditable\":contentEditable},false,row['title']).vita('h3',{},true).vita(\"time\",{\"datetime\":d1.format(\"isoDateTime\")},false,'Last modified'+d1.format(dynamis.get(\"SITE_DATE\",true)));\n $anima(\"#body article\",\"section\",{\"id\":\"page_content\",\"contenteditable\":contentEditable}).father.innerHTML=row['content'];\n load_async(\"js/libs/CKEditorCus/ckeditor.js\",true,'end',false);\n //@solve:prevents bug of CKEDITOR not existing.\n if(typeof CKEDITOR!==\"undefined\"&&contentEditable){var titleEditor = CKEDITOR.inline(document.getElementById('page_title'));\n var pageEditor = CKEDITOR.inline(document.getElementById('page_content'));}\n });\n}",
"function getPage(_page,_list){\n var len,row,tmp,d;\n if(getLicentia(\"Pages\",\"View\")===false){notice(\"<strong class='text-error'>You do not have permission to view the content pages</strong>\",true,0);return false;}\n var mensula=_list?\"system\":false;\n recHistory(_page,mensula,false,false,false,true);\n if(_list){\n $('.system1').tab('show');\n }\n $DB(\"SELECT id,title,content,modified,jesua FROM pages WHERE title=?\",[_page],\"Found page \"+_page,function(results){\n len=results.rows.length;row=[];\n if(len){row=results.rows.item(0);$('footer').data('Tau','deLta');$('footer').data('iota',row['jesua']);}\n else {row['title']=_page;row['content']=\"Click here to add new content\";row['modified']=getToday();$('footer').data('Tau','Alpha');$('footer').data('iota',null);}\n $(\"#body article\").empty();tmp=row['modified'];d=(tmp.search('0000-00-00')!=-1)?getToday():tmp;\n var d1 = new Date(d);d=null;tmp=null;\n var contentEditable=getLicentia(\"Pages\",\"Edit\");\n $anima(\"#body article\",\"section\").vita(\"header\",{},true).vita(\"h1\",{\"id\":\"page_title\",\"contenteditable\":contentEditable},false,row['title']).vita('h3',{},true).vita(\"time\",{\"datetime\":d1.format(\"isoDateTime\")},false,'Last modified'+d1.format(dynamisGet(\"SITE_DATE\",true)));\n $anima(\"#body article\",\"section\",{\"id\":\"page_content\",\"contenteditable\":contentEditable}).father.innerHTML=row['content'];\n load_async(\"js/libs/CKEditorCus/ckeditor.js\",true,'end',false);\n //@solve:prevents bug of CKEDITOR not existing.\n if(typeof CKEDITOR!==\"undefined\"&&contentEditable){var titleEditor = CKEDITOR.inline(document.getElementById('page_title'));\n var pageEditor = CKEDITOR.inline(document.getElementById('page_content'));}\n });\n}",
"function check_db() {\n do_print(\"Checking DB sanity...\");\n var dbfile = gProfD.clone();\n dbfile.append(\"extensions.sqlite\");\n var db = Services.storage.openDatabase(dbfile);\n\n do_print(\"Checking locale_strings references rows in locale correctly...\");\n let localeStringsStmt = db.createStatement(\"SELECT * FROM locale_strings\");\n let localeStmt = db.createStatement(\"SELECT COUNT(*) AS count FROM locale WHERE id=:locale_id\");\n let i = 0;\n while (localeStringsStmt.executeStep()) {\n i++;\n localeStmt.params.locale_id = localeStringsStmt.row.locale_id;\n do_check_true(localeStmt.executeStep());\n do_check_eq(localeStmt.row.count, 1);\n localeStmt.reset();\n }\n localeStmt.finalize();\n localeStringsStmt.finalize();\n do_print(\"Done. \" + i + \" rows in locale_strings checked.\");\n\n\n do_print(\"Checking locale references rows in addon_locale and addon correctly...\");\n localeStmt = db.createStatement(\"SELECT * FROM locale\");\n let addonLocaleStmt = db.createStatement(\"SELECT COUNT(*) AS count FROM addon_locale WHERE locale_id=:locale_id\");\n let addonStmt = db.createStatement(\"SELECT COUNT(*) AS count FROM addon WHERE defaultLocale=:locale_id\");\n i = 0;\n while (localeStmt.executeStep()) {\n i++;\n addonLocaleStmt.params.locale_id = localeStmt.row.id;\n do_check_true(addonLocaleStmt.executeStep());\n if (addonLocaleStmt.row.count == 0) {\n addonStmt.params.locale_id = localeStmt.row.id;\n do_check_true(addonStmt.executeStep());\n do_check_eq(addonStmt.row.count, 1);\n } else {\n do_check_eq(addonLocaleStmt.row.count, 1);\n }\n addonLocaleStmt.reset();\n addonStmt.reset();\n }\n addonLocaleStmt.finalize();\n localeStmt.finalize();\n addonStmt.finalize();\n do_print(\"Done. \" + i + \" rows in locale checked.\");\n\n\n do_print(\"Checking addon_locale references rows in locale correctly...\");\n addonLocaleStmt = db.createStatement(\"SELECT * FROM addon_locale\");\n localeStmt = db.createStatement(\"SELECT COUNT(*) AS count FROM locale WHERE id=:locale_id\");\n i = 0;\n while (addonLocaleStmt.executeStep()) {\n i++;\n localeStmt.params.locale_id = addonLocaleStmt.row.locale_id;\n do_check_true(localeStmt.executeStep());\n do_check_eq(localeStmt.row.count, 1);\n localeStmt.reset();\n }\n addonLocaleStmt.finalize();\n localeStmt.finalize();\n do_print(\"Done. \" + i + \" rows in addon_locale checked.\");\n\n\n do_print(\"Checking addon_locale references rows in addon correctly...\");\n addonLocaleStmt = db.createStatement(\"SELECT * FROM addon_locale\");\n addonStmt = db.createStatement(\"SELECT COUNT(*) AS count FROM addon WHERE internal_id=:addon_internal_id\");\n i = 0;\n while (addonLocaleStmt.executeStep()) {\n i++;\n addonStmt.params.addon_internal_id = addonLocaleStmt.row.addon_internal_id;\n do_check_true(addonStmt.executeStep());\n do_check_eq(addonStmt.row.count, 1);\n addonStmt.reset();\n }\n addonLocaleStmt.finalize();\n addonStmt.finalize();\n do_print(\"Done. \" + i + \" rows in addon_locale checked.\");\n\n\n do_print(\"Checking addon references rows in locale correctly...\");\n addonStmt = db.createStatement(\"SELECT * FROM addon\");\n localeStmt = db.createStatement(\"SELECT COUNT(*) AS count FROM locale WHERE id=:defaultLocale\");\n i = 0;\n while (addonStmt.executeStep()) {\n i++;\n localeStmt.params.defaultLocale = addonStmt.row.defaultLocale;\n do_check_true(localeStmt.executeStep());\n do_check_eq(localeStmt.row.count, 1);\n localeStmt.reset();\n }\n addonStmt.finalize();\n localeStmt.finalize();\n do_print(\"Done. \" + i + \" rows in addon checked.\");\n\n\n do_print(\"Checking targetApplication references rows in addon correctly...\");\n let targetAppStmt = db.createStatement(\"SELECT * FROM targetApplication\");\n addonStmt = db.createStatement(\"SELECT COUNT(*) AS count FROM addon WHERE internal_id=:addon_internal_id\");\n i = 0;\n while (targetAppStmt.executeStep()) {\n i++;\n addonStmt.params.addon_internal_id = targetAppStmt.row.addon_internal_id;\n do_check_true(addonStmt.executeStep());\n do_check_eq(addonStmt.row.count, 1);\n addonStmt.reset();\n }\n targetAppStmt.finalize();\n addonStmt.finalize();\n do_print(\"Done. \" + i + \" rows in targetApplication checked.\");\n\n\n do_print(\"Checking targetPlatform references rows in addon correctly...\");\n let targetPlatformStmt = db.createStatement(\"SELECT * FROM targetPlatform\");\n addonStmt = db.createStatement(\"SELECT COUNT(*) AS count FROM addon WHERE internal_id=:addon_internal_id\");\n i = 0;\n while (targetPlatformStmt.executeStep()) {\n i++;\n addonStmt.params.addon_internal_id = targetPlatformStmt.row.addon_internal_id;\n do_check_true(addonStmt.executeStep());\n do_check_eq(addonStmt.row.count, 1);\n addonStmt.reset();\n }\n targetPlatformStmt.finalize();\n addonStmt.finalize();\n do_print(\"Done. \" + i + \" rows in targetPlatform checked.\");\n\n\n db.close();\n do_print(\"Done checking DB sanity.\");\n}",
"function checkPage() {\n console.log('CHECK PAGE RUN');\n let page = window.location.pathname.split('/')[6];\n\n switch (page) {\n case '8f003a39e5':\n getStoryContent();\n break;\n case '97cc350c5e':\n console.log('RUN SHIPPING FUNCTION TO GET MDE CONTENT');\n getShippingContent();\n break;\n case 'ed8c8f347e':\n console.log('RUN RETURNS FUNCTION TO GET MDE CONTENT');\n getReturnsContent();\n break;\n case '5d4b314e6d':\n console.log('RUN PAYMENTS FUNCTION TO GET MDE CONTENT');\n getPaymentsContent();\n break;\n case '649b879831':\n console.log('RUN ORDERS FUNCTION TO GET MDE CONTENT');\n getOrdersContent();\n break;\n case 'e7b6d56e22':\n console.log('RUN TERMS & COND FUNCTION TO GET MDE CONTENT');\n getTermscondContent();\n break;\n case 'b77bf5106e':\n console.log('RUN PRIVACY POLICY FUNCTION TO GET MDE CONTENT');\n getPrivacypolContent();\n break;\n default:\n\n }\n }",
"function conditionalSearch(db) {\n console.timeEnd('connectMongo');\n // console.time(\"conditionalSearch\");\n console.log('# conditionalSearch');\n\n console.log('>>> databaseName:', db.databaseName);\n // console.log('>>> conditions:', conditions);\n\n return new Promise(function (resolve, reject) {\n if (db.databaseName === 'kerker') {\n // mock search result\n resolve({\n text: '[正妹] PTT20週年-正妹奶特祭'\n });\n } else { \n reject({ err: new Error('conditionalSearch failed') });\n }\n });\n}",
"function loadContentFromDB(defer){\n DBContentItems.all()\n .then(function(data){\n console.log(\"Loading \" + data.length + \" entries from db \");\n for(var i = 0; i < data.length; i++){\n self.content.push(data[i]);\n }\n defer.resolve(self.content);\n },function(error){\n defer.reject(error);\n });\n }",
"function checkIfReady() {\n\tvar dom = dw.getActiveWindow();\n\t\n\t// no internet connection//\n\tif (!dw.isConnectedToInternet()){\n var message = dw.loadString('bc/infomessage/noConnection');\n showRetryPage(message, true);\n\t\treturn false;\n } \n\t\n // no document opened//\n if (dom == null) {\n var message = dw.loadString('bc/infomessage/docNotOpen');\n showInfoPage(message, true);\n\t\treturn false;\n } else {\n\t\t\n\t\t// not a html document//\n\t\tif (dw.getDocumentDOM() && dw.getDocumentDOM().getParseMode() != \"html\"){\n\t\t\tvar message = dw.loadString('bc/infomessage/docNotInBCMessage');\n\t\t\tshowInfoPage(message, true);\n\t\t\t\n\t\t\tMM.BC.HINTS.resetAllCodeHintsMenu();\n\t\t\t\t\t\n\t\t\treturn false;\n\t\t} \n\t\t\n\t\t\n\t\t\t\n\t\t\tvar siteID = MM.BC.SITE.getSiteID(dom);\n\t\t\t\n\t\t\tif (MM.BC_CACHE && MM.BC_CACHE.SITES_LIST) {\n\t\t\t\t\n\t\t\t\t// not a BC site//\n\t\t\t\tif (!siteID) {\n\t\t\t\t\tMM.BC.HINTS.resetAllCodeHintsMenu();\n\t\t\t\t\tvar message = dw.loadString('bc/infomessage/docNotInBCMessage');\n\t\t\t\t\tshowInfoPage(message);\n\t\t\t\t\treturn false;\n\t\t\t\t} else {\n\t\t\t\n\t\t\t\t// if we are in the process of refresing the site list//\n\t\t\t\tif (MM.BC.SITE.doubleCheckedSiteList(siteID) && !MM.BC.SITE.haveLastUserSiteList()){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\tif (!MM.BC.SITE.isACurrentUserSite(siteID)) {\n\t\t\t\t\t if (!MM.BC.SITE.doubleCheckedSiteList(siteID)) {\n\t\t\t\t\t\tif (!MM.BC.CACHE.CHECKED_SITES_LIST) MM.BC.CACHE.CHECKED_SITES_LIST = {};\n\t\t\t\t\t\tMM.BC.CACHE.CHECKED_SITES_LIST[siteID] = true;\n\t\t\t\t\t\t MM.BC.SITE.resetLastUserSiteList();\n\t\t\t\t\t\tMM.BC.activeSite = -1;\n\t\t\t\t\t\t\tselectionChanged();\n\t\t\t\t\t\t return false;\n\t\t\t\t \t }\n\t\t\t\t\t\tMM.BC.HINTS.resetAllCodeHintsMenu();\n\t\t\t\t\t\tvar message = dw.loadString('bc/infomessage/siteNotAvailableForUser');\n\t\t\t\t\t\tshowInfoPage(message);\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\n }\n\t\n\treturn true;\n}",
"function checkDB(path,callback2,params) {\n\tif ( typeof (db) != 'undefined') {\n\t\tconsole.log(\"existing database is used\");\n\t\tcallback2(params);\n\t} else {\n\t\tconsole.log(\"load database\");\n\t\t//builds an HttpRequest on 'theUrl' and runs the 'callback' function with the content of the HttpRequest response\n\t\tfunction httpGetAsync(theUrl, callback) {\n\t\t\tvar xmlHttp = new XMLHttpRequest();\n\t\t\txmlHttp.responseType = 'arraybuffer';\n\n\t\t\txmlHttp.onreadystatechange = function() {\n\t\t\t\t//if the XMLHttpRequest was successful run the callback function with the response\n\t\t\t\tif (xmlHttp.readyState == 4 && xmlHttp.status == 200) {\n\t\t\t\t\tcallback(xmlHttp.response);\n\t\t\t\t}\n\t\t\t};\n\t\t\txmlHttp.open(\"GET\", theUrl, true);\n\t\t\t// true bedeutet, dass onreadystate in neuem thread aufgerufen wird\n\t\t\txmlHttp.send(null);\n\t\t}\n\n\t\t//constructs the callback function and runs the HttpRequest\n\t\tfunction start() {\n\t\t\tvar callback = function(str) {\n\t\t\t\tvar uInt8Array = new Uint8Array(str);\n\t\t\t\t// do not use a 'var' here! So the database is saved as an global document. attribute\n\t\t\t\tdb = new SQL.Database(uInt8Array);\n\t\t\t\tconsole.log(\"database-loading finished\");\n\t\t\t\tcallback2(params);\n\t\t\t};\n\t\t\thttpGetAsync(path, callback);\n\t\t\t\n\t\t}\n\n\t\tstart();\n\t}\n}",
"function dblist() {\n var dbi, dblist_text = '', dbparts, i, sdbi, timer;\n\n server = $('[name=server]').val();\n i = server.indexOf('?');\n if (i > 0) {\n\tserver_flags = '&' + server.substring(i + 1);\n\tserver = server.substring(0, i);\n }\n else {\n\tserver_flags = '';\n }\n\n scribe = $('[name=scribe]').val();\n $('#dblist').html('<td colspan=2>Loading list of databases ...</td>');\n url = server + '?action=dblist' + server_flags;\n timer = setTimeout(alert_server_error, 10000);\n show_status(true);\n get_jsonp(url, function(data) {\n\tclearTimeout(timer);\n\tif (data && data.database && data.database.length > 0) {\n\t dblist_text = '<td align=right>Database:</td>' +\n\t\t'<td colspan=2><select name=\\\"db\\\" id=\\\"db\\\">\\n' +\n\t\t'<option value=\\\"\\\" selected>--Choose one--</option>\\n';\n\t for (i = 0; i < data.database.length; i++) {\n \t\tdbi = data.database[i].name;\n \t\tdbparts = dbi.split('/');\n\t dblist_text += '<option value=\\\"' + dbi +\n\t\t '\\\">' + data.database[i].desc + ' (' + dbi + ')</option>\\n';\n\t }\n\t dblist_text += '</select></td>\\n';\n\t $('#dblist').html(dblist_text);\n\t $('#sversion').html(\"version \" + data.version);\n\t $('#db').on(\"change\", newdb); // invoke newdb when db changes\n\t}\n\telse { alert_server_error(); }\n\tshow_status(false);\n });\n}",
"function insertLandingPage(db, content) {\n return new Promise((resolve, reject) => {\n checkSlugDup(db, content.slug)\n .then((res) => {\n if (res.length > 0) {\n reject({errors:\"Duplicate\"});\n }\n const collection = db.collection(COLLECTION);\n collection.insert(content, function(err, result) {\n if (!err) {\n resolve(result);\n } else {\n reject(err);\n }\n });\n }).catch((err) => {\n reject(err);\n })\n });\n}",
"function getAllLandingPages(db) {\n return new Promise((resolve, reject) => {\n const collection = db.collection(COLLECTION);\n collection.find({}).toArray(function(err, docs) {\n if (!err) {\n resolve(docs);\n } else {\n reject(err);\n }\n });\n });\n}",
"async function gCheckPandaDB() {\n new Promise( resolve => {\n let counting = 0;\n checkDBs = () => {\n counting++;\n if (myHistory.db && myPanda.db) return true; else if (counting > 50) return false; else setTimeout( checkDBs(), 20 );\n }\n resolve(checkDBs());\n });\n}",
"function showContent() {\n\tvar params = request.httpParameterMap;\n var blogAssets = null;\n var Search = app.getModel('Search');\n var productSearchModel = Search.initializeProductSearchModel(params);\n var contentSearchModel = Search.initializeContentSearchModel(params);\n\n var searchedFolderId = params.fdid.submitted ? dw.content.ContentMgr.getFolder(params.fdid.value) : '';\n var renderBlogPages = false;\n if (searchedFolderId != null && !empty(searchedFolderId)) {\n var blogRootFolder = dw.system.Site.getCurrent().getCustomPreferenceValue('blogRootFolder');\n if (blogRootFolder === searchedFolderId.ID ||\n (!empty(searchedFolderId.parent) && blogRootFolder === searchedFolderId.parent.ID) ||\n (!empty(searchedFolderId.parent.parent) && blogRootFolder === searchedFolderId.parent.parent.ID)) {\n contentSearchModel.setSortingCondition('weight', dw.catalog.SearchModel.SORT_DIRECTION_DESCENDING);\n contentSearchModel.setSortingCondition('creationDate', dw.catalog.SearchModel.SORT_DIRECTION_DESCENDING);\n renderBlogPages = true;\n\n if (searchedFolderId.custom.content_search_term != null && !empty(searchedFolderId.custom.content_search_term)) {\n contentSearchModel.setSearchPhrase(searchedFolderId.custom.content_search_term);\n }\n }\n }\n\n\n // Executes the product search.\n productSearchModel.search();\n contentSearchModel.search();\n\n if (productSearchModel.emptyQuery && contentSearchModel.emptyQuery) {\n response.redirect(URLUtils.abs('Home-Show'));\n } else if (contentSearchModel.count > 0 || renderBlogPages) {\n\n \t// RPS-441\n \tif (contentSearchModel.folder) {\n \t meta.update(contentSearchModel.folder);\n \t}\n \tmeta.updatePageMetaData();\n\n var contentPagingModel = new PagingModel(contentSearchModel.content, contentSearchModel.count);\n contentPagingModel.setPageSize(16);\n var blogAssets = contentSearchModel.getContent().asList();\n if (renderBlogPages) {\n blogAssets.sort(function(a,b){return new Date(a.creationDate).getTime() < new Date(b.creationDate).getTime() ? 1 : -1;});\n }\n if (params.start.submitted) {\n contentPagingModel.setStart(params.start.intValue);\n }\n\n if ((renderBlogPages && contentSearchModel.folder.template) || contentSearchModel.folderSearch && !contentSearchModel.refinedFolderSearch && contentSearchModel.folder.template) {\n // Renders a dynamic template\n app.getView({\n ProductSearchResult: productSearchModel,\n ContentSearchResult: contentSearchModel,\n ContentPagingModel: contentPagingModel,\n ContentSearchResultSorted: blogAssets\n }).render(contentSearchModel.folder.template);\n } else {\n app.getView({\n ProductSearchResult: productSearchModel,\n ContentSearchResult: contentSearchModel,\n ContentPagingModel: contentPagingModel\n }).render('rendering/folder/foldercontenthits');\n }\n } else {\n app.getView({\n ProductSearchResult: productSearchModel,\n ContentSearchResult: contentSearchModel\n }).render('search/nohits');\n }\n}",
"function CouchDatabasePage() {\n var urlParts = location.search.substr(1).split(\"/\");\n var dbName = decodeURIComponent(urlParts.shift());\n var viewName = (urlParts.length > 0) ? urlParts.join(\"/\") : null;\n if (viewName) {\n viewName = decodeURIComponent(viewName);\n $.cookies.set(dbName + \".view\", viewName);\n } else {\n viewName = $.cookies.get(dbName + \".view\") || \"\";\n }\n var db = $.couch.db(dbName);\n\n this.dbName = dbName;\n this.viewName = viewName;\n this.db = db;\n this.isDirty = false;\n page = this;\n\n this.addDocument = function() {\n $.showDialog(\"_create_document.html\", {\n submit: function(data, callback) {\n db.saveDoc(data.docid ? {_id: data.docid} : {}, {\n error: function(status, error, reason) {\n callback({docid: reason});\n },\n success: function(resp) {\n location.href = \"document.html?\" + encodeURIComponent(dbName) +\n \"/\" + encodeURIComponent(resp.id);\n }\n });\n }\n });\n }\n\n this.compactDatabase = function() {\n $.showDialog(\"_compact_database.html\", {\n submit: function(data, callback) {\n db.compact({\n success: function(resp) {\n callback();\n }\n });\n }\n });\n }\n\n this.deleteDatabase = function() {\n $.showDialog(\"_delete_database.html\", {\n submit: function(data, callback) {\n db.drop({\n success: function(resp) {\n callback();\n location.href = \"index.html\";\n if (window !== null) {\n parent.$(\"#dbs li\").filter(function(index) {\n return $(\"a\", this).text() == dbName;\n }).remove();\n }\n }\n });\n }\n });\n }\n\n this.populateViewEditor = function() {\n if (viewName.match(/^_design\\//)) {\n page.revertViewChanges(function() {\n var dirtyTimeout = null;\n function updateDirtyState() {\n clearTimeout(dirtyTimeout);\n dirtyTimeout = setTimeout(function() {\n var buttons = $(\"#viewcode button.save, #viewcode button.revert\");\n page.isDirty = ($(\"#viewcode_map\").val() != page.storedViewCode.map)\n || ($(\"#viewcode_reduce\").val() != page.storedViewCode.reduce);\n if (page.isDirty) {\n buttons.removeAttr(\"disabled\");\n } else {\n buttons.attr(\"disabled\", \"disabled\");\n }\n }, 100);\n }\n $(\"#viewcode textarea\").bind(\"input\", updateDirtyState);\n if ($.browser.msie) { // sorry, browser detection\n $(\"#viewcode textarea\").get(0).onpropertychange = updateDirtyState\n } else if ($.browser.safari) {\n $(\"#viewcode textarea\").bind(\"paste\", updateDirtyState)\n .bind(\"change\", updateDirtyState)\n .bind(\"keydown\", updateDirtyState)\n .bind(\"keypress\", updateDirtyState)\n .bind(\"keyup\", updateDirtyState)\n .bind(\"textInput\", updateDirtyState);\n }\n });\n }\n }\n\n this.populateViewsMenu = function() {\n var select = $(\"#switch select\");\n db.allDocs({startkey: \"_design/\", endkey: \"_design/ZZZ\",\n success: function(resp) {\n select[0].options.length = 3;\n for (var i = 0; i < resp.rows.length; i++) {\n db.openDoc(resp.rows[i].id, {\n success: function(doc) {\n var optGroup = $(\"<optgroup></optgroup>\").attr(\"label\", doc._id.substr(8));\n var optGroup = $(document.createElement(\"optgroup\"))\n .attr(\"label\", doc._id.substr(8));\n for (var name in doc.views) {\n if (!doc.views.hasOwnProperty(name)) continue;\n var option = $(document.createElement(\"option\"))\n .attr(\"value\", doc._id + \"/\" + name).text(name)\n .appendTo(optGroup);\n if (doc._id + \"/\" + name == viewName) {\n option[0].selected = true;\n }\n }\n optGroup.appendTo(select);\n }\n });\n }\n }\n });\n if (!viewName.match(/^_design\\//)) {\n $.each([\"_all_docs\", \"_design_docs\", \"_temp_view\"], function(idx, name) {\n if (viewName == name) {\n select[0].options[idx].selected = true;\n }\n });\n }\n }\n\n this.revertViewChanges = function(callback) {\n if (!page.storedViewCode) {\n var viewNameParts = viewName.split(\"/\");\n var designDocId = viewNameParts[1];\n var localViewName = viewNameParts[2];\n db.openDoc([\"_design\", designDocId].join(\"/\"), {\n error: function(status, error, reason) {\n if (status == 404) {\n $.cookies.remove(dbName + \".view\");\n location.reload();\n }\n },\n success: function(resp) {\n var viewCode = resp.views[localViewName];\n $(\"#viewcode_map\").val(viewCode.map);\n $(\"#viewcode_reduce\").val(viewCode.reduce || \"\");\n var lines = Math.max(viewCode.map.split(\"\\n\").length,\n (viewCode.reduce ? viewCode.reduce.split(\"\\n\").length : 1));\n $(\"#viewcode textarea\").attr(\"rows\", Math.min(15, Math.max(3, lines)));\n $(\"#viewcode button.revert, #viewcode button.save\").attr(\"disabled\", \"disabled\");\n page.storedViewCode = viewCode;\n if (callback) callback();\n }\n });\n } else {\n $(\"#viewcode_map\").val(page.storedViewCode.map);\n $(\"#viewcode_reduce\").val(page.storedViewCode.reduce || \"\");\n page.isDirty = false;\n $(\"#viewcode button.revert, #viewcode button.save\").attr(\"disabled\", \"disabled\");\n if (callback) callback();\n }\n }\n\n this.saveViewAs = function() {\n if (viewName && /^_design/.test(viewName)) {\n var viewNameParts = viewName.split(\"/\");\n var designDocId = viewNameParts[1];\n var localViewName = viewNameParts[2];\n } else {\n var designDocId = \"\", localViewName = \"\"\n }\n $.showDialog(\"_save_view_as.html\", {\n load: function(elem) {\n $(\"#input_docid\", elem).val(designDocId).suggest(function(text, callback) {\n db.allDocs({\n count: 10, startkey: \"_design/\" + text,\n endkey: \"_design/\" + text + \"ZZZZ\",\n success: function(docs) {\n var matches = [];\n for (var i = 0; i < docs.rows.length; i++) {\n matches[i] = docs.rows[i].id.substr(8);\n }\n callback(matches);\n }\n });\n });\n $(\"#input_name\", elem).val(localViewName).suggest(function(text, callback) {\n db.openDoc(\"_design/\" + $(\"#input_docid\").val(), {\n error: function() {}, // ignore\n success: function(doc) {\n var matches = [];\n if (!doc.views) return;\n for (var viewName in doc.views) {\n if (!doc.views.hasOwnProperty(viewName) || !viewName.match(\"^\" + text)) {\n continue;\n }\n matches.push(viewName);\n }\n callback(matches);\n }\n });\n });\n },\n submit: function(data, callback) {\n if (!data.docid || !data.name) {\n var errors = {};\n if (!data.docid) errors.docid = \"Please enter a document ID\";\n if (!data.name) errors.name = \"Please enter a view name\";\n callback(errors);\n } else {\n var viewCode = {\n map: $(\"#viewcode_map\").val(),\n reduce: $(\"#viewcode_reduce\").val() || undefined\n };\n var docId = [\"_design\", data.docid].join(\"/\");\n function save(doc) {\n if (!doc) doc = {_id: docId, language: \"javascript\"};\n if (doc.views === undefined) doc.views = {};\n doc.views[data.name] = viewCode;\n db.saveDoc(doc, {\n success: function(resp) {\n callback();\n page.isDirty = false;\n location.href = \"database.html?\" + encodeURIComponent(dbName) +\n \"/\" + encodeURIComponent(doc._id) +\n \"/\" + encodeURIComponent(data.name);\n }\n });\n }\n db.openDoc(docId, {\n error: function(status, error, reason) {\n if (status == 404) save(null);\n else alert(reason);\n },\n success: function(doc) {\n save(doc);\n }\n });\n }\n }\n });\n }\n\n this.saveViewChanges = function() {\n var viewNameParts = viewName.split(\"/\");\n var designDocId = viewNameParts[1];\n var localViewName = viewNameParts[2];\n $(document.body).addClass(\"loading\");\n db.openDoc([\"_design\", designDocId].join(\"/\"), {\n success: function(doc) {\n var viewDef = doc.views[localViewName];\n viewDef.map = $(\"#viewcode_map\").val();\n viewDef.reduce = $(\"#viewcode_reduce\").val() || undefined;\n db.saveDoc(doc, {\n success: function(resp) {\n page.isDirty = false;\n $(\"#viewcode button.revert, #viewcode button.save\")\n .attr(\"disabled\", \"disabled\");\n $(document.body).removeClass(\"loading\");\n }\n });\n }\n });\n }\n\n this.updateDesignDocLink = function() {\n if (viewName && /^_design/.test(viewName)) {\n var docId = \"_design/\" + viewName.split(\"/\")[1];\n $(\"#designdoc-link\").attr(\"href\", \"document.html?\" +\n encodeURIComponent(dbName) + \"/\" + encodeURIComponent(docId)).text(docId);\n } else {\n $(\"#designdoc-link\").removeAttr(\"href\").text(\"\");\n }\n }\n\n this.updateDocumentListing = function(options) {\n $(document.body).addClass(\"loading\");\n if (options === undefined) options = {};\n if (options.count === undefined) {\n options.count = parseInt($(\"#perpage\").val(), 10);\n }\n if (options.group === undefined) {\n options.group = true;\n }\n if ($(\"#documents thead th.key\").is(\".desc\")) {\n options.descending = true;\n $.cookies.set(dbName + \".desc\", \"1\");\n } else {\n if (options.descending !== undefined) delete options.descending;\n $.cookies.remove(dbName + \".desc\");\n }\n $(\"#paging a\").unbind();\n $(\"#documents tbody.content\").empty();\n this.updateDesignDocLink();\n\n options.success = function(resp) {\n if (resp.offset === undefined) {\n resp.offset = 0;\n }\n if (resp.rows !== null && resp.offset > 0) {\n $(\"#paging a.prev\").attr(\"href\", \"#\" + (resp.offset - options.count)).click(function() {\n var firstDoc = resp.rows[0];\n page.updateDocumentListing({\n startkey: firstDoc.key !== undefined ? firstDoc.key : null,\n startkey_docid: firstDoc.id,\n skip: 1,\n count: -options.count\n });\n return false;\n });\n } else {\n $(\"#paging a.prev\").removeAttr(\"href\");\n }\n if (resp.rows !== null && resp.total_rows - resp.offset > options.count) {\n $(\"#paging a.next\").attr(\"href\", \"#\" + (resp.offset + options.count)).click(function() {\n var lastDoc = resp.rows[resp.rows.length - 1];\n page.updateDocumentListing({\n startkey: lastDoc.key !== undefined ? lastDoc.key : null,\n startkey_docid: lastDoc.id,\n skip: 1,\n count: options.count\n });\n return false;\n });\n } else {\n $(\"#paging a.next\").removeAttr(\"href\");\n }\n\n for (var i = 0; i < resp.rows.length; i++) {\n var row = resp.rows[i];\n var tr = $(\"<tr></tr>\");\n var key = row.key;\n if (row.id) {\n $(\"<td class='key'><a href='document.html?\" + encodeURIComponent(db.name) +\n \"/\" + encodeURIComponent(row.id) + \"'><strong></strong><br>\" +\n \"<span class='docid'>ID: \" + row.id + \"</span></a></td>\")\n .find(\"strong\").text(key !== null ? prettyPrintJSON(key, 0, \"\") : \"null\").end()\n .appendTo(tr);\n } else {\n $(\"<td class='key'><strong></strong></td>\")\n .find(\"strong\").text(key !== null ? prettyPrintJSON(key, 0, \"\") : \"null\").end()\n .appendTo(tr);\n }\n var value = row.value;\n $(\"<td class='value'></td>\").text(\n value !== null ? prettyPrintJSON(value, 0, \"\") : \"null\"\n ).appendTo(tr).dblclick(function() {\n location.href = this.previousSibling.firstChild.href;\n });\n tr.appendTo(\"#documents tbody.content\");\n }\n var firstNum = 1;\n var lastNum = totalNum = resp.rows.length;\n if (resp.total_rows != null) {\n firstNum = Math.min(resp.total_rows, resp.offset + 1);\n lastNum = firstNum + resp.rows.length - 1;\n totalNum = resp.total_rows;\n $(\"#paging\").show();\n } else {\n $(\"#paging\").hide();\n }\n $(\"#documents tbody.footer td span\").text(\n \"Showing \" + firstNum + \"-\" + lastNum + \" of \" + totalNum +\n \" row\" + (firstNum != lastNum ? \"s\" : \"\"));\n $(\"#documents tbody tr:odd\").addClass(\"odd\");\n $(document.body).removeClass(\"loading\");\n }\n options.error = function(status, error, reason) {\n alert(\"Error: \" + error + \"\\n\\n\" + reason);\n $(document.body).removeClass(\"loading\");\n }\n\n if (!viewName) {\n $(\"#switch select\").get(0).selectedIndex = 0;\n db.allDocs(options);\n } else {\n if (viewName == \"_temp_view\") {\n $(\"#viewcode\").show().removeClass(\"collapsed\");\n var mapFun = $(\"#viewcode_map\").val();\n $.cookies.set(db.name + \".map\", mapFun);\n var reduceFun = $(\"#viewcode_reduce\").val() || null;\n if (reduceFun != null) {\n $.cookies.set(db.name + \".reduce\", reduceFun);\n } else {\n $.cookies.remove(db.name + \".reduce\");\n }\n db.query(mapFun, reduceFun, null, options);\n } else if (viewName == \"_design_docs\") {\n options.startkey = options.descending ? \"_design/ZZZZ\" : \"_design/\";\n options.endkey = options.descending ? \"_design/\" : \"_design/ZZZZ\";\n db.allDocs(options);\n } else {\n $(\"#viewcode\").show();\n var currentMapCode = $(\"#viewcode_map\").val();\n var currentReduceCode = $(\"#viewcode_reduce\").val() || null;\n if (page.isDirty) {\n db.query(currentMapCode, currentReduceCode, null, options);\n } else {\n db.view(viewName.substr(8), options);\n }\n }\n }\n }\n\n window.onbeforeunload = function() {\n $(\"#switch select\").val(viewName);\n if (page.isDirty) {\n return \"You've made changes to the view code that have not been \" +\n \"saved yet.\";\n }\n }\n\n}",
"function checkDB(url, db, res){\n \n var collection = db.collection('shortUrls');\n \n collection.findOne({\n \"short_url\": url\n }, function(err, result){\n if(err) throw \"checkDB() findOne() ERROR: \"+ err;\n \n if(result){\n res.redirect(result.original_url);\n }else {\n res.send({\n \"error\": \"This url is not in the database.\"\n });\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generateCourseData: takes in parameters, generates node for course that can be used in makegraph.js | function generateCourseNode(courseCode, courseName, courseDesc, courseLevel, courseSeasons, coursePrereq) {
const courseDescription = courseCode + " (" + courseName + ")\n"
+ "--------------------------------" + "\n"
+ stringParse(courseDesc);
const courseTitle = (courseCode === "HS") ? courseCode : courseCode + " " + courseSeasons;
var courseNode = {
id: courseCode,
label: courseTitle,
title: courseDescription,
level: courseLevel,
labelHighLightBold: true,
borderWidth: 1.5,
// color: {
// border: 'green',
// },
font: {
face: 'Lato',
size: 16,
multi: 'html',
},
nodes: {
},
shapeProperties: {
borderRadius: 2.5,
}
}
let updateCourseNode = function (courseNode, properties) {
return { ...courseNode, ...properties };
}
let courseSubject = courseCode.split(" ")[0];
let colorShapeProperties = {};
// console.log(courseSubject);
if (courseSubject === "MATH") { // green
colorShapeProperties = {
color: {
background: '#169131',
border: 'black',
highlight: {
background: '#81f087',
border: 'black',
}
},
shape: 'diamond',
size: 15,
};
}
else if (courseSubject === "STAT") { // yellow
colorShapeProperties = {
color: {
background: '#d5db16',
border: 'black',
highlight: {
background: '#f7fa8c',
border: 'black',
}
},
shape: 'hexagon',
size: 15,
}
}
else if (courseSubject === "CS") { // orange
colorShapeProperties = {
color: {
background: '#eb7c28',
border: 'black',
highlight: {
background: '#edb68c',
border: 'black',
}
},
shape: 'star',
size: 15,
};
}
else if (courseSubject === "CO") { // aqua
colorShapeProperties = {
color: {
background: '#0ebfc2',
border: 'black',
highlight: {
background: '#63e8eb',
border: 'black',
}
},
shape: 'triangleDown',
size: 12,
};
}
else if (courseSubject === "PMATH") { // pink
colorShapeProperties = {
color: {
background: '#d40dc0',
border: 'black',
highlight: {
background: '#f294e9',
border: 'black',
}
},
shape: 'dot',
size: 12,
}
}
else if (courseSubject === "HS") { // blue
colorShapeProperties = {
color: {
background: 'blue',
border: 'black',
},
shape: 'dot',
size: 8,
fixed: true,
}
}
else if (courseSubject === "SPCOM" || courseSubject === "ENGL") { // purple
colorShapeProperties = {
color: {
background: '#661499',
border: 'black',
highlight: {
background: '#c578f5',
border: 'black',
}
},
shape: 'triangle',
size: 12,
}
}
else { // red
colorShapeProperties = {
color: {
background: '#a30b2c',
border: 'black',
highlight: {
background: '#e66e88',
border: 'black',
}
},
shape: 'square',
size: 12,
};
}
courseNode = updateCourseNode(courseNode, colorShapeProperties);
return courseNode;
} | [
"function buildData() {\n buildCourseData();\n}",
"addCourse(courseData) {\n let courseObject = new CourseObject(\n courseData,\n {\n x: this.x,\n y: this.courses.length*this.courseHeight + this.headerHeight,\n width: width,\n height: height,\n thickness: 12\n },\n this\n );\n courseObject.data.lp = this.lp;\n this.courses.push(courseObject);\n\n // Add all generated KCs to this timestamp.\n courseObject.data.Developed.forEach((value) => {\n let dockingPoint = courseObject.addOutGoingDockingPoint(value);\n\n // This function will only create A KC if no docking point exist already.\n this.timestamp.addKCSource(value,dockingPoint);\n });\n return courseObject;\n }",
"parseCourseNode(node, myCourses) {\n const { subject, catalogNumber, title, choose, children } = node;\n const id = `${subject}${catalogNumber}_${generateRandomId()}`;\n const courseNode = {\n subject,\n catalogNumber,\n title,\n choose,\n name: `${subject} ${catalogNumber}`,\n id,\n taken: hasTakenCourse(subject, catalogNumber, myCourses),\n isOpen: true,\n isLeaf: false,\n textProps: {\n onMouseEnter: () => this.setState({ title }),\n onMouseLeave: () => this.setState({ title: '' }),\n },\n gProps: {},\n };\n\n // Set canBeSimplified to true if a course has been taken\n if (!this.state.canBeSimplified && courseNode.taken) {\n this.setState({ canBeSimplified: true });\n }\n\n // Has children\n if (children != null && children.length > 0) {\n // Attach open/close click listener\n courseNode.gProps.onClick = this.toggleNode.bind(this, courseNode);\n\n // Have to take all prereqs of this course\n if (!choose) {\n courseNode.children = children.map((child) => this.parseNodes(child, myCourses));\n } else {\n // i.e. Only need x number of children to fulfill prereqs\n // We need a Choose node in the middle\n const chooseNode = { choose, children };\n const parsedChooseNode = this.parseChooseNode(chooseNode, myCourses);\n courseNode.children = [parsedChooseNode];\n }\n } else {\n // Leaf node\n courseNode.isOpen = false;\n courseNode.isLeaf = true;\n courseNode.gProps.className = 'leaf';\n }\n\n setTakenClass(courseNode);\n\n return courseNode;\n }",
"function generatecourses(data, year) {\n\t\n if (data != null && data.length>0) {\n var h = \"\";\n\t\tvar s = data[0].Semester, n = false;\n\n for (i = 0; i < data.length; i++) {\n\n if (i == 0) {\n\t\t\t\t\t//h += '<div id=\"panel'+(i+1)+'\" class=\"tabs-panel is-active\" role=\"tabpanel\" aria-labelledby=\"panel1-label\">';\n\t\t\t\t\t\th += '<div class=\"col-md-6\">';\n\t\t\t\t\t\t\th += '<h4 class=\"mt30\">' + ((data[i].Semester % 2 == 0) ? \"Spring Term\" : \"Autumn Term\")+\"</h4>\";\n\t\t\t\t\t\t\th += '<p>' +((data[i].Semester % 2 == 0) ? \"Spring Term is the second/even semester of an academic session/year.\" : \"Autumn Term is the first/odd semester of an academic session/year.\") + '</p>';\n }\n\n if (i > 0) {\n if (data[i].Semester != data[i - 1].Semester) {\n h += '</div>';\n h += '<div class=\"col-md-6\">';\n h += '<h4 class=\"mt30\">' + ((data[i].Semester % 2 == 0) ? \"Spring Term\" : \"Autumn Term\")+\"</h4>\";\n h += '<p>' + ((data[i].Semester % 2 == 0) ? \"Spring Term is the second/even semester of an academic session/year.\" : \"Autumn Term is the first/odd semester of an academic session/year.\") + '</p>';\n n = true;\n }\n }\n\t\t\n\t\t\t\th += '<div class=\"toggle toggle-border\">';\n\t\t\t\t\n\t\t\t\t\th += '<div class=\"togglet\">';\n\t\t\t\t\t\th += '<div>' + data[i].CourseName+\"</div>\";\n\t\t\t\t\t\th += '<i class=\"toggle-closed fa fa-chevron-down\"></i>';\n\t\t\t\t\t\th += '<i class=\"toggle-open fa fa-chevron-up\" aria-hidden=\"true\"></i>';\n\t\t\t\t\th += '</div>';\n\t\t\t\n\t\t\t\t\th += '<div class=\"togglec\" style=\"display: none;\">';\n\t\t\t\t\t\th += data[i].CourseDesc;\n\t\t\t\t\th += '</div>';\n\t\t\t\t\t\n\t\t\t\th += '</div>';\n\t\t\t\n\t\t\t\n n = false;\n }\n\n h += '</div>';\n\t\t//h += '</div>'; //closed panel\n\t\t\n\t\t$(\"#corecourse .tabs-panel\").removeClass('is-active');\n\t\t$(\"#year\"+year).html(h);\n\t\t$(\"#year\"+year).addClass('is-active');\n\n\t\t//set the toggles\n\t\t$( '#curr.mtoggle .toggle .togglet').click( function () {\n\t\t\tif ( $( this ).hasClass( 'togglet' ) ) {\n\t\t\t\t$( \".togglet\" ).each( function () {\n\t\t\t\t\t$(this).removeClass('toggleta');\n\t\t\t\t});\n\t\t\t\t$( this ).addClass('toggleta');\n\t\t\t\t$( '.togglec' ).not( $( this ).next( '.togglec' ) ).hide();\n\t\t\t\t$(this).next('.togglec').toggle();\n\t\t\t}\n\t\t});\n\t\t$( '#curr.mtoggle .toggle .togglet' ).click( function () {\n\t\t\t$( '.togglec' ).not( $( this ).next( '.togglec' ) ).hide();\n\t\t});\n\t\t\n $(\"#msgapply\").html('Note: The Curriculum is subject to changes and/or review as and when prescribed by the University');\n }\n}",
"function startCourse() {\n resetCourse();\n inProgressNode = getStartNode();\n addInProgressNodeToPath();\n var nodeInDiagram = myDiagram.findNodeForData(inProgressNode);\n addChildrenToFrontier(inProgressNode);\n setAllNodeColors();\n}",
"function genLinks(courses){\n //TODO: cleaner code\n links = [];\n courses.forEach((course)=>{\n course.prerequisites.forEach((pre)=>{\n links.push({\"source\": pre, \"target\": course.id});\n });\n });\n\n return links;\n}",
"function genLinks(courses){\n //TODO: cleaner code\n let links = [];\n courses.forEach((course)=>{\n course.prerequisites.forEach((pre)=>{\n links.push({\"source\": pre, \"target\": course.id});\n });\n });\n\n return links;\n}",
"function nodePositioningPerSubject(data, yCoordOffset) {\n const NODE_X_COORD_SPACING = 400\n const NODE_BASE_Y_COORD_SPACING = 100\n\n // Partition the courses into columns based on level and whether they have dependencies\n let partitionedCourses = {};\n for (let course of data) {\n const partitionKey = \"L\" + course.code.substring(4,5) + (course.prereq.length > 0 ? \"D\" : \"\");\n if (partitionKey in partitionedCourses) {\n partitionedCourses[partitionKey].push(course);\n } else {\n partitionedCourses[partitionKey] = [course];\n }\n }\n console.log(\"Initial partition\", partitionedCourses);\n\n // Calculate the max vertical spacing\n const maxPartitionSize = Object.values(partitionedCourses).map(x => x.length).reduce((acc, curr) => Math.max(acc, curr), 0);\n const maxHeight = (maxPartitionSize - 1) * NODE_BASE_Y_COORD_SPACING;\n\n let nodes = [];\n const sortedPartitionKeys = Object.keys(partitionedCourses).sort((a, b) => { return a > b ? 1 : -1 });\n console.log(\"Partition keys\", sortedPartitionKeys);\n let xCoord = 0;\n\n for (const partitionKey of sortedPartitionKeys) {\n const courses = partitionedCourses[partitionKey];\n\n // Calculate vertical spacing based on the number of nodes in the partition\n let yCoord;\n let nodeGapHeight;\n if (courses.length === maxPartitionSize) {\n nodeGapHeight = NODE_BASE_Y_COORD_SPACING;\n yCoord = 0;\n } else {\n nodeGapHeight = maxHeight / (courses.length + 1);\n yCoord = nodeGapHeight;\n }\n console.log(\"Node height for: \" + partitionKey + \" = \" + nodeGapHeight);\n\n for (const course of courses) {\n const position = { x: xCoord, y: (yCoord + yCoordOffset) };\n const type = getNodeType(course);\n nodes.push(createGraphNode(course.code, position, type));\n yCoord += nodeGapHeight;\n }\n\n xCoord += NODE_X_COORD_SPACING;\n }\n\n console.log(\"Final nodes\", nodes);\n\n return nodes;\n}",
"async function buildVisSubjectAreaNetwork(courses, _subjectArea, depth){\r\n visNodes = new vis.DataSet();\r\n visEdges = new vis.DataSet();\r\n\r\n courses.courses.forEach(async function(course){\r\n await _addCourseToVisNetwork(course, 0);\r\n });\r\n\r\n courses.courses.forEach( async function(course){\r\n await _addVisChildNodes(course, _subjectArea, 1)\r\n });\r\n\r\n\r\n //if we are in single node mode, add connections out to the specified depth\r\n\r\n/* visNodes.forEach(async function(n){ ///FIXME\r\n\r\n if(n.type != NODE_TYPES.BRANCH.NAME && n.depth == i){\r\n var courseAtDepth = await getCourseDataAjax(_subjectArea, n.id);\r\n for(var c in courseAtDepth.courses){\r\n var course = courseAtDepth.courses[c];\r\n\r\n await _addVisChildNodes(course, _subjectArea, i + 1);\r\n }\r\n }\r\n\r\n });\r\n*/\r\n\r\n\r\n\r\n visData = {nodes:visNodes, edges:visEdges}\r\n\r\n //compute custom layout for large networks. Use default Kamada Kawai for smaller networks\r\n computeLayout()\r\n\r\n //render the network\r\n visNetwork = new vis.Network(document.getElementById(\"myNetwork\"), visData, _getVisOptions())\r\n\r\n //add event listenders for the vis network\r\n visAddEventListeners();\r\n}",
"function updateCourseNodes() {\n var size = 2 * courseRadius;\n\n var course = hypergraph.selectAll(\".course-node\")\n .data(data, d => d.ID);\n\n var courseEnter = course.enter()\n .append(\"svg\")\n .attr(\"height\", size)\n .attr(\"width\", size)\n .classed(\"node course-node\", true)\n .classed(\"not-interested\", switchInterested.property(\"checked\"))\n .classed(\"extra-course-node\", d => extraData.includes(d))\n .style(\"display\", function (d) {\n if (extraData.includes(d) && !optionChosen) {\n return \"none\";\n }\n })\n .on(\"mouseover\", function (d) {\n showTooltip(d);\n toggleMouseoverCourse(d);\n })\n .on(\"mouseout\", function (d) {\n hideTooltip();\n toggleMouseoverCourse(d);\n })\n .on(\"click\", function () {\n courseClicked(d3.select(this));\n });\n\n var courseG = courseEnter.append(\"g\")\n .attr(\"transform\", \"translate(\" + (size / 2) + \",\" + (size / 2) + \")\");\n\n // pie chart voor elk vak\n courseG.selectAll(\"course-piece\")\n .data(function (d) {\n var nbOptions = optionNames.length;\n var values = d3.values(d)\n .splice(indexFirstOption, nbOptions)\n .map(e => (e > 0) ? 1 : 0);\n // trick: the last integer indicates whether the course should be totally gray\n var sum = d3.sum(values);\n if (sum == nbOptions || sum == 0) {\n values = values.map(d => 0);\n values.push(1);\n }\n return d3.pie()(values);\n })\n .enter()\n .append(\"path\")\n .attr(\"class\", \"course-piece\")\n .attr(\"d\", function (d) {\n var arc = d3.arc().innerRadius(0).outerRadius(courseRadius);\n return arc(d);\n })\n .attr(\"fill\", (d, i) => (i < optionNames.length) ? colors[i] : defaultGray);\n\n // extra doorzichtige pie chart die de pie chart voor verplichte vakken afschermt\n courseG.selectAll(\"course-compulsory-piece\")\n .data(function (d) {\n var nbOptions = optionNames.length;\n var values = d3.values(d)\n .splice(indexFirstOption, nbOptions);\n // trick: the last integer indicates whether the course should be totally gray\n var sum = d3.sum(values.map(e => (e > 0) ? 1 : 0));\n if (sum == nbOptions || d[extraOptionNames[0]] > 0 || d[extraOptionNames[1]] > 0) {\n values = values.map(d => 0);\n values.push(1);\n }\n return d3.pie().value(d => (d > 1) ? 1 : d)(values);\n })\n .enter()\n .append(\"path\")\n .classed(\"course-compulsory-piece\", true)\n .classed(\"compulsory\", d => d.data == 1)\n .attr(\"d\", function (d) {\n var arc = d3.arc().innerRadius(0).outerRadius(courseRadius - courseBandWidth);\n return arc(d);\n })\n .attr(\"fill\", (d, i) => (i < optionNames.length) ? colors[i] : defaultGray);\n\n course.exit().remove();\n }",
"function _getCourseData() {\n var courses = [];\n\n $('tr.item').each(function() {\n $this = $(this);\n\n var capacity = $this.find('.capacity').val();\n var offered = $this.find('.checkbox').is('checked') ? 1 : 2;\n var courseId = $this.find('.course-id').html();\n\n var fallTerm, springTerm, summerTerm, availability;\n\n fallTerm = 0;\n springTerm = 0;\n summerTerm = 0;\n \n if(offered) {\n switch (semester) {\n case 1:\n fallTerm = 1;\n availability = 'Fall Only';\n break;\n case 2:\n springTerm = 1;\n availability = 'Spring Only';\n break;\n case 3:\n summerTerm = 1;\n availability = 'Summer Only';\n break;\n }\n }\n\n var course = {\n capacity: capacity,\n availability: availability,\n id: courseId,\n fallTerm: fallTerm,\n springTerm: springTerm,\n summerTerm: summerTerm\n \n };\n\n courses.push(course);\n });\n\n _saveCourseData(courses, _runGurobi);\n}",
"function readDataCourse(course) {\r\n const infocourse = {\r\n image: course.querySelector('img').src,\r\n title: course.querySelector('h4').textContent,\r\n price: course.querySelector('.discount').textContent,\r\n id: course.querySelector('a').getAttribute('data-id')\r\n }\r\n insertincart(infocourse);\r\n}",
"function processCourse(course, courses) {\n var stars = getRandomInt(0, 5);\n course.voteStars = stars ? 'stars_' + stars : 'no_stars';\n course.messagesQty = getRandomInt(1, 9);\n course.date = getRandomInt(1, 28) + '.' + getRandomInt(1, 12) + '.' + getRandomInt(10, 12);\n if (courses) {\n courses.push(course);\n }\n else {\n return course;\n }\n}",
"function getCourses(courses) {\n\tvar course_list = [];\n\t//iterate over all of the courses in the list of type\n\tfor (var i = 0; i < courses.length; i++) {\n\t\tif (courses[i].id == \"000004\") {\n\t\t\tcontinue;\n\t\t}\n\t\t//add its attributes to the string representation\n\t\tvar course = \"<b>Course ID:</b> \" + courses[i].id + \"<br />\";\n\t\tcourse += \"<b>Credits:</b> \" + courses[i].credits + \"<br />\";\n\t\tcourse += \"<b>Required:</b> \" + courses[i].required + \"<br />\";\n\t\tcourse += \"<b>Senior:</b> \" + courses[i].senior + \"<br />\";\n\t\tcourse += \"<b>Course Name:</b> \" + courses[i].name + \"<br />\";\n\t\tcourse += \"<b>Course Description:</b><br />\" + courses[i].desc + \"<br />\";\n\n\t\t//add all of the names of its prerequisites\n\t\tcourse += \"<b>Prerequisites:</b><br />\";\n\t\tvar prereqs = courses[i].prereqs;\n\t\t//no prerequisites\n\t\tif (prereqs.length == 0) {\n\t\t\tcourse += \" None<br />\";\n\t\t//has prerequisites\n\t\t} else {\n\t\t\t//get the course name of the prerequisite using its course id\n\t\t\tfor (var j = 0; j < prereqs.length; j++) {\n\t\t\t\tvar prereq = findCourse(courses, prereqs[j].id);\n\t\t\t\tcourse += \" \" + prereq.name + \"<br />\";\n\t\t\t}\t\t\t\n\t\t}\n\n\t\tcourse_list.push(course);\n\t}\n\n\treturn course_list;\n}",
"function getCourses() {\r\n try {\r\n var requirements = majorCatalog[chosenMajor].major.singular;\r\n // If the major chosen is not found in json file, print a message\r\n } catch (error) {\r\n var warning = document.createElement(\"p\");\r\n var node = document.createTextNode(\r\n \"Missing information of major \" + chosenMajor\r\n );\r\n warning.appendChild(node);\r\n\r\n displayInfo(warning);\r\n return;\r\n }\r\n\r\n // Create the courseBlocks, and store them\r\n for (var i = 0; i < requirements.length; i++) {\r\n var course = document.createElement(\"div\");\r\n var courseName = requirements[i];\r\n course.innerHTML = courseName;\r\n course.className =\r\n \"courseBlock ui-widget-content \" + courseName.split(\" \").join(\"\");\r\n course.style.top = \"15px\";\r\n course.style.left = \"\" + (i + 1) * 50 + \"px\";\r\n $(pathwayContent).append(course);\r\n course.style.display = \"block\";\r\n\r\n var courseInfo = { location: null, type: \"singular\" };\r\n storeEdits(-1, courseName, courseInfo); // Eventually change this so that the courses appear in correct order.\r\n }\r\n\r\n makeDraggable();\r\n getPaths();\r\n}",
"createCourse(course) {\n return http.post('/courses', course);\n }",
"function callD2lScrape(course, cb) {\n d2lScrape.getCourseInfo(course.ou, function (err, data) {\n if (err){\n cb(err, null);\n return;\n }\n console.log(data.Path);\n course.path = data.Path;\n cb(null, null);\n });\n}",
"function getCourseData() {\n\n\n // d3.csv(\"/results/MissRiver_golf_details.csv\").then(function(data) {\n courseSet = courseData;\n addMarkers();\n // });\n }",
"function createCourse () {\n // Create course section\n let courseSection = document.createElement('section')\n courseSection.classList.add('course')\n\n // Add delete course button\n let delCourseBtn = createCourseBtn()\n courseSection.appendChild(delCourseBtn)\n\n // Add course bar\n let courseBar = createCourseBar()\n courseSection.appendChild(courseBar)\n\n return courseSection\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
API test for 'AddEtherIpId', Add EtherIP ID setting | function Test_AddEtherIpId() {
return __awaiter(this, void 0, void 0, function () {
var in_etherip_id, out_etherip_id;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
console.log("Begin: Test_AddEtherIpId");
in_etherip_id = new VPN.VpnEtherIpId({
Id_str: "testid",
HubName_str: hub_name,
UserName_str: "nekosan",
Password_str: "torisan"
});
return [4 /*yield*/, api.AddEtherIpId(in_etherip_id)];
case 1:
out_etherip_id = _a.sent();
console.log(out_etherip_id);
console.log("End: Test_AddEtherIpId");
console.log("-----");
console.log();
return [2 /*return*/];
}
});
});
} | [
"function newEthAddress(){\n\trequest.post('https://api.blockcypher.com/v1/beth/test/addrs', { json: true }, (err, res, body) => {\n\t\tif (err) { return console.log(err); }\n\t\ttry{\n\t\t\tconsole.log(\"\\n\\n-----\\n\\nSuccess! Ethereum address created. Please be sure to save your private key in a safe location. \\n\\n\")\n\t \t\tconsole.log(body);\n\t\t} catch(e){\n\t \t\tconsole.log(\"Something has went wrong with the APIs endpoint. Please try again later.\");\n\t\t}\n\t});\n}",
"function Test_GetEtherIpId(id) {\n return __awaiter(this, void 0, void 0, function () {\n var in_etherip_id, out_etherip_id;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n console.log(\"Begin: Test_GetEtherIpId\");\n in_etherip_id = new VPN.VpnEtherIpId({\n Id_str: id\n });\n return [4 /*yield*/, api.GetEtherIpId(in_etherip_id)];\n case 1:\n out_etherip_id = _a.sent();\n console.log(out_etherip_id);\n console.log(\"End: Test_GetEtherIpId\");\n console.log(\"-----\");\n console.log();\n return [2 /*return*/];\n }\n });\n });\n}",
"function Test_EnumEtherIpId() {\n return __awaiter(this, void 0, void 0, function () {\n var out_rpc_enum_etherip_id;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n console.log(\"Begin: Test_EnumEtherIpId\");\n return [4 /*yield*/, api.EnumEtherIpId()];\n case 1:\n out_rpc_enum_etherip_id = _a.sent();\n console.log(out_rpc_enum_etherip_id);\n console.log(\"End: Test_EnumEtherIpId\");\n console.log(\"-----\");\n console.log();\n return [2 /*return*/, out_rpc_enum_etherip_id];\n }\n });\n });\n}",
"function setAddID(packet , id) {\r\n\tvar rootHelper = new ASNPathHelper(packet);\r\n\r\n\tvar eUTRANcellIdentifier = \trootHelper.search('InitiatingMessage.value.opentype.protocolIEs.element0.value.opentype.element0.servedCellInfo.cellId.eUTRANcellIdentifier').object;// it's a bitstring\r\n\tsetBitString(eUTRANcellIdentifier,id);\r\n\t\r\n\tvar pci = rootHelper.search('InitiatingMessage.value.opentype.protocolIEs.element0.value.opentype.element0.servedCellInfo.pCI').object;// it's an integer\r\n\tpci.setValue( calculatePCI(id)) ;\r\n\t\r\n\tvar earfcn = rootHelper.search('InitiatingMessage.value.opentype.protocolIEs.element0.value.opentype.element0.servedCellInfo.eUTRA-Mode-Info.TDD-Info.eARFCN').object;// it's an integer\r\n\tearfcn.setValue(calculateEARFCN(id));\r\n}",
"function e368_SetIP(ipString, devIndx)\n{\n if((e368info[devIndx]).isOld)\n {\n Out.Printf(Out.PriNormal, \"Error: IP cannot be set on old e368 boards\\n\\n\");\n return; // Call old boards N/A since they have no IP function\n } \n else {\n var read = new Array;\n e368_SendCommand( (\"setip \" + ipString), read, devIndx );\n // Split the line of reply, delimited by spaces:\n var retLine = (read[1]).split(/\\s/g);\n // Make sure response is what we're looking for- 1st word should be \"Saved\"\n if((retLine[0]).search(\"Saved\") != -1)\n {\n Out.Printf(Out.PriNormal, \"IP successfully set!\\n\");\n }\n else {\n Out.Printf(Out.PriNormal, \"Error saving IP Address. Line read:\\n%s\\n\",read[1]);\n }\n }\n return;\n}",
"function setSetupID(packet , id) {\r\n\tvar rootHelper = new ASNPathHelper(packet);\r\n\t//print(rootHelper.printSubtree());\r\n\tvar eNB_ID = \t\t\t\trootHelper.search('InitiatingMessage.value.opentype.protocolIEs.element0.value.opentype.eNB-ID.BIT STRING').object; // it's a bitstring\r\n\tsetBitString(eNB_ID,id);\r\n\tvar eUTRANcellIdentifier = \trootHelper.search('InitiatingMessage.value.opentype.protocolIEs.element1.value.opentype.element0.servedCellInfo.cellId.eUTRANcellIdentifier').object;// it's a bitstring\r\n\tsetBitString(eUTRANcellIdentifier,id);\r\n\tvar pci = rootHelper.search('InitiatingMessage.value.opentype.protocolIEs.element1.value.opentype.element0.servedCellInfo.pCI').object;// it's an integer\r\n\tpci.setValue( calculatePCI(id)) ;\r\n\tvar earfcn = rootHelper.search('InitiatingMessage.value.opentype.protocolIEs.element1.value.opentype.element0.servedCellInfo.eUTRA-Mode-Info.TDD-Info.eARFCN').object;// it's an integer\r\n\tearfcn.setValue(calculateEARFCN(id));\r\n}",
"function Test_DeleteEtherIpId(id) {\n return __awaiter(this, void 0, void 0, function () {\n var in_etherip_id, out_etherip_id;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n console.log(\"Begin: Test_DeleteEtherIpId\");\n in_etherip_id = new VPN.VpnEtherIpId({\n Id_str: id\n });\n return [4 /*yield*/, api.DeleteEtherIpId(in_etherip_id)];\n case 1:\n out_etherip_id = _a.sent();\n console.log(out_etherip_id);\n console.log(\"End: Test_DeleteEtherIpId\");\n console.log(\"-----\");\n console.log();\n return [2 /*return*/];\n }\n });\n });\n}",
"fetchIpAddress(ip) {\n console.log(ip)\n }",
"setDeviceNetwork () {\n const subnet = Math.round(Math.random() * this.subnetsCount).toString()\n this.client.service('/api/devices')\n .create({\n _id: this.id.toString(),\n os_hostname: 'PC' + this.id.toString(),\n net_ip4: '172.20.' + subnet + '.' + Math.round(Math.random() * 200).toString(),\n net_ip4_subnet: '172.20.' + subnet + '.255/24',\n net_gatewayV4: '172.20.' + subnet + '.254'\n })\n .catch(() => {\n this.client.service('/api/devices')\n .patch(\n this.id.toString(),\n {\n os_hostname: 'PC' + this.id.toString(),\n net_ip4: '172.20.' + subnet + '.' + Math.round(Math.random() * 200).toString(),\n net_ip4_subnet: '172.20.' + subnet + '.17/24',\n net_gatewayV4: '172.20.' + subnet + '.1'\n }\n )\n })\n }",
"actionAssignPrivateIpAddressesPost(incomingOptions, cb) {\n const AmazonEc2 = require(\"./dist\");\n let defaultClient = AmazonEc2.ApiClient.instance;\n // Configure API key authorization: hmac\n let hmac = defaultClient.authentications[\"hmac\"];\n hmac.apiKey = incomingOptions.apiKey;\n // Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n //hmac.apiKeyPrefix = 'Token';\n\n let apiInstance = new AmazonEc2.DefaultApi(); // String | The ID of the network interface.\n /*let networkInterfaceId = \"networkInterfaceId_example\";*/ let opts = {\n // 'xAmzContentSha256': \"xAmzContentSha256_example\", // String |\n // 'xAmzDate': \"xAmzDate_example\", // String |\n // 'xAmzAlgorithm': \"xAmzAlgorithm_example\", // String |\n // 'xAmzCredential': \"xAmzCredential_example\", // String |\n // 'xAmzSecurityToken': \"xAmzSecurityToken_example\", // String |\n // 'xAmzSignature': \"xAmzSignature_example\", // String |\n // 'xAmzSignedHeaders': \"xAmzSignedHeaders_example\", // String |\n // 'action': \"action_example\", // String |\n version: \"'2016-11-15'\", // String |\n allowReassignment: true, // Boolean | Indicates whether to allow an IP address that is already assigned to another network interface or instance to be reassigned to the specified network interface.\n // 'privateIpAddress': \"privateIpAddress_example\", // [String] | <p>One or more IP addresses to be assigned as a secondary private IP address to the network interface. You can't specify this parameter when also specifying a number of secondary IP addresses.</p> <p>If you don't specify an IP address, Amazon EC2 automatically selects an IP address within the subnet range.</p>\n secondaryPrivateIpAddressCount: 56 // Number | The number of secondary IP addresses to assign to the network interface. You can't specify this parameter when also specifying private IP addresses.\n };\n\n if (!incomingOptions.opts) delete incomingOptions.opts;\n incomingOptions.opts = Object.assign(opts, incomingOptions.opts);\n\n apiInstance.actionAssignPrivateIpAddressesPost(\n incomingOptions.networkInterfaceId,\n incomingOptions.opts,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data, response);\n }\n }\n );\n }",
"function addPrivateIP() {\n // Add a private ip address for this Linode,\n forEachLinode(working, hosts_to_build, (host, hostob) => {\n return {\n call: {\n action: 'linode.ip.addprivate',\n params: {\n LinodeID: hostob.LinodeID,\n }\n },\n result: (data) => {\n hostob.private_ipv4 = data.IPADDRESS;\n }\n };\n }, queryIPs );\n }",
"function ConnectToIECBrowser(deviceIPAdd)\n{\n //Step1. Click on connect button on tool bar\n AssertClass.IsTrue(IECBrowserPage.ConnectDevice(),\"Clicked on connect button at toolbar of IECbrowser\")\n \n //Step2. Set IP address in IP address text box\n AssertClass.IsTrue(IECBrowserPage.SetIPAddress(deviceIPAdd),\"IP address set as iedevice IP\")\n \n //Step3. Click on connect button\n AssertClass.IsTrue(IECBrowserPage.ClickOnConnectButton(),\"Clicked on connect button\")\n \n aqUtils.Delay(3*Referesh_time)\n}",
"_addOneToAddress() {\n this._transportParameters.targetAddress = intToAddress(addressToInt(this._transportParameters.targetAddress) + 1);\n this._debug(`New address for DFU target: ${this._transportParameters.targetAddress}`);\n return this._transportParameters.targetAddress;\n }",
"function findEniId() {\n ecs.describeTasks(paramsForDescribeTask, function (err, data) {\n if (err) console.log(err, err.stack); // an error occurred\n console.log(data.tasks[0].attachments[0].details[1].value); // successful response\n eniId = data.tasks[0].attachments[0].details[1].value;\n paramsForGetPublicIp = {\n NetworkInterfaceIds: [\n eniId\n ]\n\n }\n findPublicIp();\n\n });\n}",
"function setSetupResponseID(packet , id) {\r\n\tvar rootHelper = new ASNPathHelper(packet);\r\n\tvar eNB_ID = \t\t\t\trootHelper.search('SuccessfulOutcome.value.opentype.protocolIEs.element0.value.opentype.eNB-ID.BIT STRING').object; // it's a bitstring\r\n\tsetBitString(eNB_ID,id);\r\n\tvar eUTRANcellIdentifier = \trootHelper.search('SuccessfulOutcome.value.opentype.protocolIEs.element1.value.opentype.element0.servedCellInfo.cellId.eUTRANcellIdentifier').object;// it's a bitstring\r\n\tsetBitString(eUTRANcellIdentifier,id);\r\n\tvar pci = rootHelper.search('SuccessfulOutcome.value.opentype.protocolIEs.element1.value.opentype.element0.servedCellInfo.pCI').object;// it's an integer\r\n\tpci.setValue( calculatePCI(id)) ;\r\n\tvar earfcn = rootHelper.search('SuccessfulOutcome.value.opentype.protocolIEs.element1.value.opentype.element0.servedCellInfo.eUTRA-Mode-Info.TDD-Info.eARFCN').object;// it's an integer\r\n\tearfcn.setValue(calculateEARFCN(id));\r\n}",
"function setNetworkIpAddress(ipAddrId, snetMaskId){\n var nwAddrOct1, nwAddrOct2, nwAddrOct3, nwAddrOct4;\n var networkAddrObj = document.getElementById(ipAddrId);\n if (!networkAddrObj) {\n //alert(\"Network Ip object does not exist.\"); \n return;\n }\n var objArr = networkAddrObj.value.split(\".\");\n if (!objArr.length) {\n alert(\"Please enter valid network address.\");\n return false;\n }\n var ipOct1 = parseInt(objArr[0], 10);\n var ipOct2 = parseInt(objArr[1], 10);\n var ipOct3 = parseInt(objArr[2], 10);\n var ipOct4 = parseInt(objArr[3], 10);\n var networkSubnetMaskObj = document.getElementById(snetMaskId);\n if (!networkSubnetMaskObj) {\n //alert(\"Subnet mask object does not exist\");\n return;\n }\n var objArr = networkSubnetMaskObj.value.split(\".\");\n if (!objArr.length) {\n alert(\"Please enter valid subnet mask.\");\n return false;\n }\n var snetOct1 = parseInt(objArr[0], 10);\n var snetOct2 = parseInt(objArr[1], 10);\n var snetOct3 = parseInt(objArr[2], 10);\n var snetOct4 = parseInt(objArr[3], 10);\n \n /* Anding each octate of Ip address and Subnet mask */\n nwAddrOct1 = ipOct1 & snetOct1;\n nwAddrOct2 = ipOct2 & snetOct2;\n nwAddrOct3 = ipOct3 & snetOct3;\n nwAddrOct4 = ipOct4 & snetOct4;\n \n var nwAddr = nwAddrOct1 + \".\" + nwAddrOct2 + \".\" + nwAddrOct3 + \".\" + nwAddrOct4;\n \n /* Assigning the network address to he network address field */\n \n networkAddrObj.value = nwAddr;\n return true;\n}",
"setIP(ip) {\n if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/.test(ip)) { \n global.backendIP = ip;\n }\n }",
"add() {\n // Create a network\n let buffer = execSync( WPA_USER_PREFIX + '\"wpa_cli add_network\"' );\n this.id = buffer.toString(\"utf-8\").split(\"\\n\")[1];\n\n // Enter the ssid\n execSync( WPA_USER_PREFIX + '\"wpa_cli set_network ' + this.id + ' ssid \\'\\\\\\\"' + this.ssid + '\\\\\\\"\\'\"' );\n // Enter the password if there is one\n if( this.password ) {\n execSync( WPA_USER_PREFIX + '\"wpa_cli set_network ' + this.id + ' psk \\'\\\\\\\"' + this.password + '\\\\\\\"\\'\"' );\n // Enter the identity if there is one\n if( this.identity ) {\n execSync( WPA_USER_PREFIX + '\"wpa_cli set_network ' + this.id + ' identity \\'\\\\\\\"' + this.identity + '\\\\\\\"\\'\"' );\n }\n }\n else {\n // If there is no password, we have to explicity say we have no security\n execSync( WPA_USER_PREFIX + '\"wpa_cli set_network ' + this.id + ' key_mgmt NONE' );\n }\n }",
"addElasticIpAddress(id, eip, props = {}) {\n return new EndpointConfiguration(this, id, {\n endpointId: eip.attrAllocationId,\n endpointGroup: this,\n ...props,\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
replace common battle Statistics | function replaceBattleStatistics(obj) {
obj.innerHTML=obj.innerHTML.replace(/(Recent)/g,"正在输出的");
obj.innerHTML=obj.innerHTML.replace(/(defenders:)/,"防守者:");
obj.innerHTML=obj.innerHTML.replace(/(attackers:)/,"进攻者:");
obj.innerHTML=obj.innerHTML.replace(/(Current round statistics)/,"本回合战斗统计信息");
obj.innerHTML=obj.innerHTML.replace(/(Defenders' total damage:)/,"防守方伤害累计:");
obj.innerHTML=obj.innerHTML.replace(/(Attackers' total damage:)/,"进攻方伤害累计:");
obj.innerHTML=obj.innerHTML.replace(/(Your damage:)/,"个人伤害累计:");
obj.innerHTML=obj.innerHTML.replace(/(Top defending countries:)/,"防守方国家累计伤害排行榜:");
obj.innerHTML=obj.innerHTML.replace(/(Top attacking countries:)/,"进攻方国家累计伤害排行榜:");
obj.innerHTML=obj.innerHTML.replace(/(Top defending military units:)/,"防守方军团累计伤害 TOP 5:");
obj.innerHTML=obj.innerHTML.replace(/(Top attacking military units:)/,"进攻方军团累计伤害 TOP 5:");
} | [
"function replaceBattleStatistics(obj) {\r\n\tobj.innerHTML=obj.innerHTML.replace(/(Recent)/g,\"Derniers\");\r\n\tobj.innerHTML=obj.innerHTML.replace(/(defenders:)/,\"défenseurs:\");\r\n\tobj.innerHTML=obj.innerHTML.replace(/(attackers:)/,\"attaquants:\");\r\n\tobj.innerHTML=obj.innerHTML.replace(/(Current round statistics)/,\"Statistiques du round en cours\");\r\n\tobj.innerHTML=obj.innerHTML.replace(/(Defenders' total damage:)/,\"Dommages infligés par la défense:\");\r\n\tobj.innerHTML=obj.innerHTML.replace(/(Attackers' total damage:)/,\"Dommages infligés par l'attaque:\");\r\n\tobj.innerHTML=obj.innerHTML.replace(/(Your damage:)/,\"Vos dommages:\");\r\n\tobj.innerHTML=obj.innerHTML.replace(/(Top defending countries:)/,\"Classement pays en défense:\");\r\n\tobj.innerHTML=obj.innerHTML.replace(/(Top attacking countries:)/,\"Classement pays en attaque:\");\r\n\tobj.innerHTML=obj.innerHTML.replace(/(Top defending military units:)/,\" Top military units en défense:\");\r\n\tobj.innerHTML=obj.innerHTML.replace(/(Top attacking military units:)/,\"Top military units en attaque\");\r\n}",
"function doBattleMUStatistics() {\r\n\tvar allElements;\r\n\tallElements = document.getElementById('contentRow').children[1];\r\n\t\r\n\tvar tmp;\r\n\ttmp = allElements.children[0];\r\n\treplaceBattleInfo(tmp);\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(started by)/,\"comenzada por\");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Round )(\\d*)/,\"Ronda $2 \");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Rounds won by defender)/,\"Rondas ganadas por el defensor \");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Rounds won by attacker)/,\"Rondas ganadas por el atacante \");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Back to battle)/,\"Volver a la batalla\");\r\n\r\n\ttmp = allElements.children[3];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Supporting military units/,\"Apoyo de las unidades militares\");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Defender's supporters)/,\"Partidarios del defensor\");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Attacker's supporters)/,\"Partidarios del atacante\");\r\n}",
"function doBattleMUStatistics() {\r\n\tvar allElements;\r\n\tallElements = document.getElementById('contentRow').children[1];\r\n\t\r\n\tvar tmp;\r\n\ttmp = allElements.children[0];\r\n\treplaceBattleInfo(tmp);\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(started by)/,\"התחיל את המרד\");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Round )(\\d*)/,\"סיבוב $2 \");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Rounds won by defender)/,\"בסיבוב זה נצחו המגנים \");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Rounds won by attacker)/,\"בסיבוב זה נצחו התוקפים \");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Back to battle)/,\"חזרה לקרב\");\r\n\r\n\ttmp = allElements.children[3];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Supporting military units/,\"היחידות התומכות\");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Defender's supporters)/,\"תומכים בהגנה\");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Attacker's supporters)/,\"תומכים בהתקפה\");\r\n}",
"function doBattleMUStatistics() {\r\n\tvar allElements;\r\n\tallElements = document.getElementById('contentRow').children[1];\r\n\t\r\n\tvar tmp;\r\n\ttmp = allElements.children[0];\r\n\treplaceBattleInfo(tmp);\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(started by)/,\"començada por\");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Round )(\\d*)/,\"$2ª rodada\");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Rounds won by defender)/,\"Rodadas ganhas pelo defensor\");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Rounds won by attacker)/,\"Rodadas ganhas pelo atacante\");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Back to battle)/,\"Voltar para a guerra\");\r\n\r\n\ttmp = allElements.children[3];\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/Supporting military units/,\"Apoio das unidades militares\");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Defender's supporters)/,\"Apoiantes do defensor\");\r\n\ttmp.innerHTML=tmp.innerHTML.replace(/(Attacker's supporters)/,\"Apoiantes do atacante\");\r\n}",
"updateAllStatsValues()\n {\n // Fix values : equipment influence etc\n let level = this.getCurrentLevel();\n let statistics = RPM.datasGame.battleSystem.statistics;\n let statisticsProgression = this.character.getStatisticsProgression();\n let nonFixStatistics = new Array;\n let i, l;\n for (i = 1, l = statistics.length; i < l; i++)\n {\n this[statistics[i].getBeforeAbbreviation()] = undefined;\n }\n let j, m, statistic, statisticProgression;\n for (i = 1, l = statistics.length; i < l; i++)\n {\n statistic = statistics[i];\n if (i !== RPM.datasGame.battleSystem.idLevelStatistic & i !== RPM\n .datasGame.battleSystem.idExpStatistic)\n {\n for (j = 0, m = statisticsProgression.length; j < m; j++)\n {\n statisticProgression = statisticsProgression[j];\n if (statisticProgression.id === i)\n {\n if (!statisticProgression.isFix)\n {\n nonFixStatistics.push(statisticProgression);\n } else {\n this.updateStatValue(statistic, statisticProgression\n .getValueAtLevel(level, this));\n }\n break;\n }\n }\n }\n }\n\n // Update formulas statistics\n for (i = 0, l = nonFixStatistics.length; i < l; i++)\n {\n for (j = 0; j < l; j++)\n {\n statisticProgression = nonFixStatistics[j];\n statistic = statistics[statisticProgression.id];\n this.updateStatValue(statistic, statisticProgression\n .getValueAtLevel(level, this));\n }\n }\n\n this.updateEquipmentStats();\n }",
"function replaceBattleInfo(obj) {\r\n\t// no allies \r\n\tobj.innerHTML=obj.innerHTML.replace(/(no allies)/g,\"无同盟\");\r\n\t//12 allies\r\n\tobj.innerHTML=obj.innerHTML.replace(/(\\d*)( allies)/g,\"$1 同盟\");\r\n\t//Resistance war\r\n\tobj.innerHTML=obj.innerHTML.replace(/(Resistance war)/g,\"起义战斗\");\r\n\t//Subsidies:\r\n\tobj.innerHTML=obj.innerHTML.replace(/(Subsidies:)/g,\"赏金:\");\r\n//\t//: none\r\n//\tallElements.innerHTML=allElements.innerHTML.replace(/(: none)/g,\":无\");\r\n//\t//: 0.02 USD for 1.000 dmg\r\n//\tallElements.innerHTML=allElements.innerHTML.replace(/(: )([0-9.]+) (\\w*)( for )/g,\":$2 $3\" 每);\r\n}",
"function replaceBattleInfo(obj) {\r\n // no allies \r\n obj.innerHTML=obj.innerHTML.replace(/(no allies)/g,\"Pas d'alliés\");\r\n //12 allies\r\n obj.innerHTML=obj.innerHTML.replace(/(\\d*)( allies)/g,\"$1 alliés\");\r\n //Resistance war\r\n obj.innerHTML=obj.innerHTML.replace(/(Resistance war)/g,\"Guerre de résistance\");\r\n //Subsidies:\r\n obj.innerHTML=obj.innerHTML.replace(/(Subsidies:)/g,\"Subventions:\");\r\n// //: none\r\n// allElements.innerHTML=allElements.innerHTML.replace(/(: none)/g,\":?\");\r\n// //: 0.02 USD for 1.000 dmg\r\n// allElements.innerHTML=allElements.innerHTML.replace(/(: )([0-9.]+) (\\w*)( for )/g,\":$2 $3\" ?);\r\n}",
"function updatePreviousStats(battle){\n\tfor(let i in battle.player.team){\n\t\tbattle.player.team[i].stats.hp[2] = battle.player.team[i].stats.hp[0];\n\t\tbattle.player.team[i].stats.wp[2] = battle.player.team[i].stats.wp[0];\n\t}\n\tfor(let i in battle.enemy.team){\n\t\tbattle.enemy.team[i].stats.hp[2] = battle.enemy.team[i].stats.hp[0];\n\t\tbattle.enemy.team[i].stats.wp[2] = battle.enemy.team[i].stats.wp[0];\n\t}\n}",
"function replaceBattleInfo(obj) {\r\n\t// no allies \r\n\tobj.innerHTML=obj.innerHTML.replace(/(no allies)/g,\"Pas d'alliés\");\r\n\t//12 allies\r\n\tobj.innerHTML=obj.innerHTML.replace(/(\\d*)( allies)/g,\"$1 allié(s)\");\r\n\t//Resistance war\r\n\tobj.innerHTML=obj.innerHTML.replace(/(Resistance war)/g,\"Guerre de résistance\");\r\n\t//Subsidies:\r\n\tobj.innerHTML=obj.innerHTML.replace(/(Subsidies:)/g,\"Subventions:\");\r\n//\t//: none\r\n//\tallElements.innerHTML=allElements.innerHTML.replace(/(: none)/g,\":none\");\r\n//\t//: 0.02 USD for 1.000 dmg\r\n//\tallElements.innerHTML=allElements.innerHTML.replace(/(: )([0-9.]+) (\\w*)( for )/g,\":$2 $3\" ?);\r\n}",
"static fix20170405(battle) {\n if (battle.time >= 1491372000000)\n return battle\n for (const packet of battle.packet) {\n for (const k of ['api_ship_ke', 'api_ship_ke_combined']) {\n if (packet[k] != null)\n packet[k] = packet[k].map(n => n > 500 ? n + 1000 : n)\n }\n }\n return battle\n }",
"updateAllStatsValues() {\n // Fix values : equipment influence etc\n let level = this.getCurrentLevel();\n let statistics = Datas.BattleSystems.statisticsOrder;\n let statisticsProgression = this.system.getStatisticsProgression(this\n .changedClass);\n let nonFixStatistics = new Array;\n let i, l;\n for (i = 0, l = statistics.length; i < l; i++) {\n this[Datas.BattleSystems.getStatistic(statistics[i])\n .getBeforeAbbreviation()] = undefined;\n }\n let j, m, statistic, statisticProgression;\n for (i = 0, l = statistics.length; i < l; i++) {\n let id = statistics[i];\n statistic = Datas.BattleSystems.getStatistic(id);\n if (id !== Datas.BattleSystems.idLevelStatistic && id !== Datas\n .BattleSystems.idExpStatistic) {\n for (j = 0, m = statisticsProgression.length; j < m; j++) {\n statisticProgression = statisticsProgression[j];\n if (statisticProgression.id === id) {\n if (!statisticProgression.isFix) {\n nonFixStatistics.push(statisticProgression);\n }\n else {\n this.updateStatValue(statistic, statisticProgression\n .getValueAtLevel(level, this));\n }\n break;\n }\n }\n }\n }\n // Update formulas statistics\n for (i = 0, l = nonFixStatistics.length; i < l; i++) {\n for (j = 0; j < l; j++) {\n statisticProgression = nonFixStatistics[j];\n statistic = Datas.BattleSystems.getStatistic(statisticProgression.id);\n this.updateStatValue(statistic, statisticProgression\n .getValueAtLevel(level, this));\n }\n }\n // Update equipment stats + characteristics\n this.statusRes = [];\n this.updateEquipmentStats();\n }",
"function updatePrimaryStats() {\n\tvar c = character;\n\tvar strTotal = (c.strength + c.all_attributes + (c.level-1)*c.strength_per_level);\n\tvar dexTotal = (c.dexterity + c.all_attributes + (c.level-1)*c.dexterity_per_level);\n\tvar vitTotal = (c.vitality + c.all_attributes + (c.level-1)*c.vitality_per_level);\n\tvar energyTotal = (c.energy + c.all_attributes)*(1+c.max_energy/100);\n\t\n\tvar life_addon = (vitTotal-c.starting_vitality)*c.life_per_vitality;\n\tvar stamina_addon = (vitTotal-c.starting_vitality)*c.stamina_per_vitality;\n\tvar mana_addon = (energyTotal-c.starting_energy)*c.mana_per_energy;\n\t\n\tvar item_def = 0;\n\tfor (group in corruptsEquipped) {\n\t\tif (typeof(equipped[group].base_defense) != 'undefined') { if (equipped[group].base_defense != unequipped.base_defense) {\n\t\t\tvar multEth = 1;\n\t\t\tvar multED = 1;\n\t\t\tif (typeof(equipped[group][\"ethereal\"]) != 'undefined') { if (equipped[group][\"ethereal\"] == 1) { multEth = 1.5; } }\n\t\t\tif (typeof(equipped[group][\"e_def\"]) != 'undefined') { multED += (equipped[group][\"e_def\"]/100) }\n\t\t\tif (typeof(corruptsEquipped[group][\"e_def\"]) != 'undefined') { multED += (corruptsEquipped[group][\"e_def\"]/100) }\n\t\t\tif (group == \"helm\" || group == \"armor\" || group == \"weapon\" || group == \"offhand\") { if (typeof(socketed[group].totals[\"e_def\"]) != 'undefined') { multED += (socketed[group].totals[\"e_def\"]/100) } }\n\t\t\tif (typeof(equipped[group].set_bonuses) != 'undefined') {\n\t\t\t\tfor (let i = 2; i < equipped[group].set_bonuses.length; i++) { if (i <= character[equipped[group].set_bonuses[0]]) {\n\t\t\t\t\tfor (affix in equipped[group].set_bonuses[i]) { if (affix == \"e_def\") { multED += equipped[group].set_bonuses[i][affix]/100 } }\n\t\t\t\t} }\n\t\t\t}\n\t\t\tequipped[group].item_defense = Math.ceil(multEth*multED*equipped[group].base_defense)// + ~~equipped[group].defense + Math.floor(~~equipped[group].defense_per_level*c.level)\n\t\t\titem_def += equipped[group].item_defense\n\t\t\t// TODO: Incorporate other defense affixes so item_defense can be referenced in the tooltip for total defense?\n\t\t} } else {\n\t\t\t//equipped[group].item_defense = ~~equipped[group].defense + Math.floor(~~equipped[group].defense_per_level*c.level)\n\t\t}\n\t}\n\tvar def = (item_def + c.defense + c.level*c.defense_per_level + Math.floor(dexTotal/4)) * (1 + (c.defense_bonus + c.defense_skillup)/100);\n\tvar ar = ((dexTotal - 7) * 5 + c.ar + c.level*c.ar_per_level + c.ar_const + (c.ar_per_socketed*socketed.offhand.socketsFilled)) * (1+(c.ar_skillup + c.ar_skillup2 + c.ar_bonus + c.level*c.ar_bonus_per_level)/100) * (1+c.ar_shrine_bonus/100);\n\t\n/*\t// Poison Calculation Testing\n\tvar pDamage = c.pDamage_all;\n\tvar pDuration = c.pDamage_duration;\n\tvar pFrames = pDuration*25;\n\tvar pAmount = Math.floor(pDamage*256/pFrames + (pFrames-1)/pFrames);\n\tvar pBite = pAmount*pFrames;\n\tvar pTotal_duration = Math.floor(pFrames / c.pDamage_duration);\t// sum\n\tvar pTotal_damage = Math.round(pAmount * pTotal_duration);\t// sum\n\tdocument.getElementById(\"f4\").innerHTML = c.pDamage_all+\" over \"+c.pDamage_duration+\"s = \"+Math.round(pTotal_damage/((256/25)*pDuration))+\" \"+pBite/pFrames\n\tdocument.getElementById(\"c4\").innerHTML = pAmount+\" \"+pTotal_duration+\" \"+Math.round(pTotal_damage/(pDamage/pDuration))\n*/\n\tvar physDamage = getWeaponDamage(strTotal,dexTotal,\"weapon\",0);\n\tvar dmg = getNonPhysWeaponDamage(\"weapon\");\n\tvar basic_min = Math.floor(physDamage[0]*physDamage[2] + dmg.fMin + dmg.cMin + dmg.lMin + dmg.pMin + dmg.mMin);\n\tvar basic_max = Math.floor(physDamage[1]*physDamage[2] + dmg.fMax + dmg.cMax + dmg.lMax + dmg.pMax + dmg.mMax);\n\tif (basic_min > 0 || basic_max > 0) { document.getElementById(\"basic_attack\").innerHTML = basic_min + \"-\" + basic_max + \" {\"+Math.ceil((basic_min+basic_max)/2)+\"}\"}\n\telse { document.getElementById(\"basic_attack\").innerHTML = \"\" }\n\tif (offhandType == \"weapon\") {\n\t\tvar ohd = getNonPhysWeaponDamage(\"offhand\");\n\t\tvar physDamage_offhand = getWeaponDamage(strTotal,dexTotal,\"offhand\",0);\n\t\tvar basic_min_offhand = Math.floor(physDamage_offhand[0]*physDamage_offhand[2] + ohd.fMin + ohd.cMin + ohd.lMin + ohd.pMin + ohd.mMin);\n\t\tvar basic_max_offhand = Math.floor(physDamage_offhand[1]*physDamage_offhand[2] + ohd.fMax + ohd.cMax + ohd.lMax + ohd.pMax + ohd.mMax);\n\t\tif (equipped.weapon.name != \"none\") {\n\t\t\tif (basic_min_offhand > 0 || basic_max_offhand > 0) { document.getElementById(\"offhand_basic_damage\").innerHTML = basic_min_offhand + \"-\" + basic_max_offhand + \" {\"+Math.ceil((basic_min_offhand+basic_max_offhand)/2)+\"}\"}\n\t\t\telse { document.getElementById(\"offhand_basic_damage\").innerHTML = \"\" }\n\t\t} else {\n\t\t\tif (basic_min_offhand > 0 || basic_max_offhand > 0) { document.getElementById(\"basic_attack\").innerHTML = basic_min_offhand + \"-\" + basic_max_offhand + \" {\"+Math.ceil((basic_min_offhand+basic_max_offhand)/2)+\"}\"; document.getElementById(\"offhand_basic\").style.display = \"none\"; }\n\t\t}\n\t}\n\t\n\tvar block_shield = c.block;\n\tif (c.class_name == \"Amazon\" || c.class_name == \"Assassin\" || c.class_name == \"Barbarian\") { block_shield -= 5 }\n\tif (c.class_name == \"Druid\" || (c.class_name == \"Necromancer\" && equipped.offhand.only != \"necromancer\") || c.class_name == \"Sorceress\") { block_shield -= 10 }\n\tvar block = (Math.max(0,block_shield) + c.ibc)*(dexTotal-15)/(c.level*2)\n\tif (c.block_skillup > 0) { block = Math.min((c.block_skillup*(dexTotal-15)/(c.level*2)),c.block_skillup) }\n\tif (c.running > 0) { block = Math.min(25,block/3) }\n\tif (c.block > 0 || c.block_skillup > 0) {\n\t\tdocument.getElementById(\"block_label\").style.visibility = \"visible\"\n\t\tdocument.getElementById(\"block\").innerHTML = Math.floor(Math.min(75,block))+\"%\"\n\t} else {\n\t\tdocument.getElementById(\"block_label\").style.visibility = \"hidden\"\n\t\tdocument.getElementById(\"block\").innerHTML = \"\"\n\t}\n\t\n\t//var enemy_lvl = ~~MonStats[monsterID][4+c.difficulty];\n\tvar enemy_lvl = Math.min(~~c.level,89);\t// temp, sets 'area level' at the character's level (or as close as possible if the area level isn't available in the selected difficulty)\n\tif (c.difficulty == 1) { enemy_lvl = Math.min(43,enemy_lvl) }\n\telse if (c.difficulty == 2) { enemy_lvl = Math.max(36,Math.min(66,enemy_lvl)) }\n\telse if (c.difficulty == 3) { enemy_lvl = Math.max(67,enemy_lvl) }\n\tvar enemy_def = (MonStats[monsterID][8] * MonLevel[enemy_lvl][c.difficulty])/100;\n\tenemy_def = Math.max(0,enemy_def + enemy_def*(c.enemy_defense+c.target_defense)/100+c.enemy_defense_flat)\n\tvar hit_chance = Math.round(Math.max(5,Math.min(95,(100 * ar / (ar + enemy_def)) * (2 * c.level / (c.level + enemy_lvl)))));\n\n\tdocument.getElementById(\"strength\").innerHTML = Math.floor(strTotal)\n\tdocument.getElementById(\"dexterity\").innerHTML = Math.floor(dexTotal)\n\tdocument.getElementById(\"vitality\").innerHTML = Math.floor(vitTotal)\n\tdocument.getElementById(\"energy\").innerHTML = Math.floor(energyTotal)\n\tdocument.getElementById(\"strength2\").innerHTML = Math.floor(strTotal)\n\tdocument.getElementById(\"dexterity2\").innerHTML = Math.floor(dexTotal)\n\tdocument.getElementById(\"vitality2\").innerHTML = Math.floor(vitTotal)\n\tdocument.getElementById(\"energy2\").innerHTML = Math.floor(energyTotal)\n\tdocument.getElementById(\"defense\").innerHTML = Math.floor(def + c.melee_defense)\n\tif ((c.missile_defense-c.melee_defense) > 0) { document.getElementById(\"defense\").innerHTML += \" (+\" + (c.missile_defense) + \")\" }\t// add difference when missile & melee defense are both present?\n\tif (c.running > 0) { document.getElementById(\"defense\").style.color = \"brown\" }\n\telse { document.getElementById(\"defense\").style.color = \"gray\" }\n\tdocument.getElementById(\"ar\").innerHTML = Math.floor(ar)+\" (\"+hit_chance+\"%)\"\n\tdocument.getElementById(\"stamina\").innerHTML = Math.floor((c.stamina + (c.level-1)*c.stamina_per_level + stamina_addon) * (1+c.stamina_skillup/100) * (1+c.max_stamina/100))\n\tvar lifeTotal = Math.floor((c.life + (c.level-1)*c.life_per_level + life_addon) * (1 + c.max_life/100));\n\tdocument.getElementById(\"life\").innerHTML = lifeTotal\n\tdocument.getElementById(\"mana\").innerHTML = Math.floor((c.mana + (c.level-1)*c.mana_per_level + mana_addon) * (1 + c.max_mana/100))\n\tdocument.getElementById(\"level\").innerHTML = c.level\n\tdocument.getElementById(\"class_name\").innerHTML = c.class_name\n\tdocument.getElementById(\"remainingstats\").innerHTML = c.statpoints\n\tdocument.getElementById(\"remainingskills\").innerHTML = c.skillpoints\n\tdocument.getElementById(\"fres\").innerHTML = (c.fRes + c.all_res - c.fRes_penalty + c.resistance_skillup) + \" / \" + Math.min(RES_CAP,(c.fRes_max_base + c.fRes_max + c.fRes_skillup)) + \"%\"\n\tdocument.getElementById(\"cres\").innerHTML = (c.cRes + c.all_res - c.cRes_penalty + c.resistance_skillup) + \" / \" + Math.min(RES_CAP,(c.cRes_max_base + c.cRes_max + c.cRes_skillup)) + \"%\"\n\tdocument.getElementById(\"lres\").innerHTML = (c.lRes + c.all_res - c.lRes_penalty + c.resistance_skillup) + \" / \" + Math.min(RES_CAP,(c.lRes_max_base + c.lRes_max + c.lRes_skillup)) + \"%\"\n\tdocument.getElementById(\"pres\").innerHTML = (c.pRes + c.all_res - c.pRes_penalty + c.resistance_skillup) + \" / \" + Math.min(RES_CAP,(c.pRes_max_base + c.pRes_max + c.pRes_skillup)) + \"%\"\n\tvar magicRes = (c.mRes - c.mRes_penalty)+\"%\";\n\tif (c.mDamage_reduced > 0) { magicRes += (\" +\"+c.mDamage_reduced) }\n\tdocument.getElementById(\"mres\").innerHTML = magicRes\n\t\n\tvar ias = c.ias + Math.floor(dexTotal/8)*c.ias_per_8_dexterity;\n\tif (offhandType == \"weapon\" && typeof(equipped.offhand.ias) != 'undefined') { ias -= equipped.offhand.ias }\n\tvar ias_total = ias + c.ias_skill;\n\tdocument.getElementById(\"ias\").innerHTML = ias_total; if (ias_total > 0) { document.getElementById(\"ias\").innerHTML += \"%\" }\n\tif (equipped.weapon.type != \"\" && equipped.weapon.special != 1) {\n\t\tvar weaponType = equipped.weapon.type;\n\t\tvar eIAS = Math.floor(120*ias/(120+ias));\n\t\tvar weaponFrames = 0;\n\t\tvar weaponSpeedModifier = c.baseSpeed - ~~equipped.offhand.baseSpeed;\n\t\tvar anim_speed = 256;\n\t\tif (weaponType != \"\") {\n\t\t\t// TODO: Add fpa/aps to skills (many skills attack multiple times at different speeds, or interact with IAS differently (e.g. +30 WSM for throwing skills))\n\t\t\tif (weaponType == \"club\" || weaponType == \"hammer\") { weaponType = \"mace\" }\n\t\t\tweaponFrames = c.weapon_frames[weaponType];\n\t\t\tif (typeof(effects[\"Werewolf\"]) != 'undefined') { if (effects[\"Werewolf\"].info.enabled == 1) { weaponFrames = character_druid.wereform_frames[weaponType]; anim_speed = 256; } }\n\t\t\tif (typeof(effects[\"Werebear\"]) != 'undefined') { if (effects[\"Werebear\"].info.enabled == 1) { weaponFrames = character_druid.wereform_frames[weaponType]; anim_speed = 224; } }\n\t\t\tif (weaponType == \"sword\" || weaponType == \"axe\" || weaponType == \"mace\") { if (equipped.weapon.twoHanded == 1) { weaponFrames = weaponFrames[1]; } else { weaponFrames = weaponFrames[0]; } }\n\t\t\tif (weaponType == \"thrown\") { if (equipped.weapon.subtype == \"dagger\") { weaponFrames = weaponFrames[1]; } else { weaponFrames = weaponFrames[0]; } }\n\t\t\tif (weaponType == \"claw\") { anim_speed = 208 }\t// can't interact with werewolf/werebear frames due to itemization\n\t\t}\n\t\tweaponFrames += 1\n\t\tvar combined_ias = Math.min(175,Math.max(15,(100 + c.ias_skill + eIAS - weaponSpeedModifier)));\n\t\tvar frames_per_attack = Math.ceil((weaponFrames*256)/Math.floor(anim_speed * combined_ias / 100)) - 1;\n\t\t/*\n\t\t// TODO: implement wereform IAS frame info\n\t\tif (typeof(effects[\"Werewolf\"]) != 'undefined' || typeof(effects[\"Werebear\"]) != 'undefined') {\tif (effects[\"Werewolf\"].info.enabled == 1 || effects[\"Werebear\"].info.enabled == 1) {\n\t\t\tvar wereFrames = 0;\n\t\t\tvar frames_neutral = 0;\n\t\t\tvar frames_char = frames_per_attack;\n\t\t\tif (typeof(effects[\"Werewolf\"]) != 'undefined') { if (effects[\"Werewolf\"].info.enabled == 1) { wereFrames = 12; frames_neutral = 9; } }\n\t\t\tif (typeof(effects[\"Werebear\"]) != 'undefined') { if (effects[\"Werebear\"].info.enabled == 1) { wereFrames = 13; frames_neutral = 10; } }\n\t\t\tif (weaponType == \"sword\") { if (equipped.weapon.twoHanded == 1) { frames_char = wereFrames } }\n\t\t\tanim_speed = Math.floor(256*frames_neutral/Math.floor(256*frames_char/Math.floor((100+~~equipped.weapon.ias - weaponSpeedModifier)*256/100)))\n\t\t\tframes_per_attack = Math.ceil((wereFrames*256)/Math.floor(anim_speed * (100 + c.ias_skill + eIAS - weaponSpeedModifier) / 100)) - 1;\n\t\t} }\n\t\t*/\n\t\t// TODO: implement basic IAS breakpoints for dual-wielding\n\t\tif (offhandType != \"weapon\") {\n\t\t\tdocument.getElementById(\"ias\").innerHTML += \" (\"+frames_per_attack+\" fpa)\"\n\t\t}\n\t}\n\tif (c.flamme > 0) { document.getElementById(\"flamme\").innerHTML = \"Righteous Fire deals \"+Math.floor((c.flamme/100*lifeTotal)*(1+c.fDamage/100))+\" damage per second<br>\" } else { document.getElementById(\"flamme\").innerHTML = \"\" }\n}",
"function badDefense(data) {\n let uniqueCountries = [];\n let badCountry = \"\";\n let badGoals = 0;\n \n data.forEach(function(teams) {\n if(uniqueCountries.length > 0) {\n let homeCountry = false;\n let awayCountry = false;\n for(let i = 0; i < uniqueCountries.length; i++) {\n if(uniqueCountries[i] === teams['Home Team Name']) homeCountry = true;\n if(uniqueCountries[i] === teams['Away Team Name']) awayCountry = true;\n }\n if(!homeCountry) {\n uniqueCountries.push(teams['Home Team Name']);\n }\n if(!awayCountry) {\n uniqueCountries.push(teams['Away Team Name']);\n }\n } else {\n uniqueCountries.push(teams['Home Team Name']);\n uniqueCountries.push(teams['Away Team Name']);\n }\n });\n // I should now have an array of Unique Country names\n \n for(let country = 0; country < uniqueCountries.length; country++) {\n let gamesTeamPlayed = 0;\n let goalsCounted = data.reduce(function(accumulatedGoals, currentGoals) {\n if(uniqueCountries[country] === currentGoals['Home Team Name']) {\n gamesTeamPlayed++;\n return accumulatedGoals + currentGoals['Away Team Goals'];\n } else if(uniqueCountries[country] === currentGoals['Away Team Name']) {\n gamesTeamPlayed++;\n return accumulatedGoals + currentGoals['Home Team Goals'];\n } else {\n return accumulatedGoals + 0;\n }\n }, 0);\n // I should have total Goals and total games played at this point\n if((goalsCounted / gamesTeamPlayed) > badGoals) {\n // New Record! Update variables\n badCountry = uniqueCountries[country];\n badGoals = Number(Math.round((goalsCounted / gamesTeamPlayed)+'e2')+'e-2');\n }\n }\n \n return \"\" + badCountry + \" is the country with the highest average points scored against them per game at \" + badGoals + \" points.\";\n}",
"function updateHourlyStats() {\r\n//Planned data package order: [0]Hour of the Day |\r\n// [1]NY Fight Exp | [2]NY Fight Win Count | [3]NY Fight Loss Count | [4]NY Fight $ Won | [5]NY Fight $Lost |\r\n// [6]NY Rob Exp | [7]NY Rob Success Count | [8]NY Rob Fail Count | [9]NY Rob $Won | [10]NY Rob $Lost |\r\n// [11]NY Fight Loss Crit Hit Count | [12]NY Fight Loss Bodyguard Count | [13]NY Fight Loss Too Strong Count |\r\n// Variables below not yet created\r\n// [x]NY Capo $US | [x]NY Assist Exp | [x]NY Assist $US |\r\n// [x]NY Attacked Exp(net after deaths) | [x]NY Attacked $Won | [x]NY Attacked $Lost |\r\n// [x]NY Robbed Exp | [x]NY Robbed $Won | [x]NY Robbed $Lost |\r\n// [x]NY Job Count | [x]NY Job Exp | [x]NY Job $Made |\r\n// >>> BEGIN CUBA <<<\r\n// [x]Cuba Fight Exp | [x]Cuba Fight Win Count | [x]Cuba Fight Loss Count | [x]Cuba Fight $C Won | [x]Cuba Fight $C Lost |\r\n// [x]Cuba Fight Loss Crit Hit Count | [x]Cuba Fight Loss Bodyguard Count | [x]Cuba Fight Loss Too Strong Count |\r\n// [x]Cuba Capo $C | [x]Cuba Assist Exp | [x]Cuba Assist $C |\r\n// [x]Cuba Attacked Exp(net after deaths) | [x]Cuba Attacked $C Won | [x]Cuba Attacked $C Lost |\r\n// [x]Cuba Robbed Exp | [x]Cuba Robbed $C Won | [x]Cuba Robbed $C Lost |\r\n// [x]Cuba Job Count | [x]Cuba Job Exp | [x]Cuba Job $C Made\r\n\r\n// Max potential storage 41 * 24 = 984 elements\r\n\r\n var i, currentTime = new Date();\r\n var currentHour = currentTime.getHours();\r\n\r\n var hrDataPack = \"\";\r\n hrDataPack = currentHour + '|' + GM_getValue('fightExpNY', 0) + '|' + GM_getValue('fightWinsNY', 0) + '|' +\r\n GM_getValue('fightLossesNY', 0) + '|' + GM_getValue('fightWin$NY', 0) + '|' + GM_getValue('fightLoss$NY', 0) + '|' +\r\n GM_getValue('fightLossCHNY', 0) + '|' + GM_getValue('fightLossBGCHNY', 0) + '|'+ GM_getValue('fightLossStrongNY', 0);\r\n\r\n if (GM_getValue('hourlyStats', '0') == '0') {\r\n GM_setValue('hourlyStats', hrDataPack);\r\n } else {\r\n //pull existing stored hourly stats\r\n var splitValues = GM_getValue('hourlyStats', '').split(',');\r\n if (splitValues.length < 24) {\r\n splitValues.push(currentHour + '|0|0|0|0|0|0|0|0');\r\n }else {\r\n if ((GM_getValue('hourOfDay')*1 == 23 && currentHour != 0 )|| currentHour -1 != GM_getValue('hourOfDay')*1 && GM_getValue('hourOfDay') != isNaN(GM_getValue('hourOfDay'))){\r\n //We missed some hours so we need to carry the last good values forward\r\n var tempHour;\r\n if (GM_getValue('hourOfDay')*1 > currentHour){\r\n tempHour = currentHour + 24;\r\n }else{\r\n tempHour = currentHour;\r\n }\r\n\r\n for (i = GM_getValue('hourOfDay')*1 + 1; i < GM_getValue('hourOfDay')*1 + (tempHour - GM_getValue('hourOfDay')*1); i++){\r\n var valString = splitValues[GM_getValue('hourOfDay')];\r\n valString = valString.substring(valString.indexOf('|'), valString.length);\r\n if (i > 23){\r\n splitValues.push(String(i-24) + valString);\r\n }else {\r\n splitValues.push(i + valString);\r\n }\r\n }\r\n }\r\n }\r\n //create temp arrays\r\n var hourlyFightExpNY = new Array(24); //position [1]\r\n var hourlyFightWinsNY = new Array(24); //position [2]\r\n var hourlyFightLossesNY = new Array(24); //position [3]\r\n var hourlyFightWin$NY = new Array(24); //position [4]\r\n var hourlyFightLoss$NY = new Array(24); //position [5]\r\n var hourlyLossCrHitNY = new Array(24); //position [6]\r\n var hourlyLossBgCrHitNY = new Array(24); //position [7]\r\n var hourlyLossStrongNY = new Array(24); //position [8]\r\n\r\n // Organize Hourly stat data into ordered sets\r\n for (i = 0; i < splitValues.length; i++){\r\n //check length of each datapack to ensure it is the right size and fills missing with zeroes\r\n //this addresses issues when adding new metrics to the datapackage\r\n if (splitValues[i].split('|').length < 9) {\r\n for (var n = splitValues[i].split('|').length; n < 9; n++){\r\n splitValues[i] += '|0';\r\n }\r\n }\r\n if (splitValues[i].split('|')[0] == currentHour) {\r\n //pull data from same time day prior for \"25th\" hour\r\n var fightExpNY25 = splitValues[i].split('|')[1]*1;\r\n var fightWinsNY25 = splitValues[i].split('|')[2]*1;\r\n var fightLossesNY25 = splitValues[i].split('|')[3]*1;\r\n var fightWin$NY25 = splitValues[i].split('|')[4]*1;\r\n var fightLoss$NY25 = splitValues[i].split('|')[5]*1;\r\n var fightLossCrHitNY25 = splitValues[i].split('|')[6];\r\n var fightLossBgCrHitNY25 = splitValues[i].split('|')[7];\r\n var fightLossStrongNY25 = splitValues[i].split('|')[8];\r\n //Insert current hour values\r\n hourlyFightExpNY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[1]*1;\r\n hourlyFightWinsNY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[2]*1;\r\n hourlyFightLossesNY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[3]*1;\r\n hourlyFightWin$NY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[4]*1;\r\n hourlyFightLoss$NY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[5]*1;\r\n hourlyLossCrHitNY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[6]*1;\r\n hourlyLossBgCrHitNY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[7]*1;\r\n hourlyLossStrongNY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[8]*1;\r\n } else {\r\n //populate other hourly data\r\n hourlyFightExpNY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[1]*1;\r\n hourlyFightWinsNY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[2]*1;\r\n hourlyFightLossesNY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[3]*1;\r\n hourlyFightWin$NY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[4]*1;\r\n hourlyFightLoss$NY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[5]*1;\r\n hourlyLossCrHitNY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[6]*1;\r\n hourlyLossBgCrHitNY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[7]*1;\r\n hourlyLossStrongNY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[8]*1;\r\n }\r\n }\r\n\r\n//Prep Arrays for hourly graphing\r\n var fightExpNY = prepStatsArray(hourlyFightExpNY, currentHour);\r\n var fightWinsNY = prepStatsArray(hourlyFightWinsNY, currentHour);\r\n var fightLossesNY = prepStatsArray(hourlyFightLossesNY, currentHour);\r\n var fightWin$NY = prepStatsArray(hourlyFightWin$NY, currentHour);\r\n var fightLoss$NY = prepStatsArray(hourlyFightLoss$NY, currentHour);\r\n var fightLossCHNY = prepStatsArray(hourlyLossCrHitNY, currentHour);\r\n var fightLossBGCHNY = prepStatsArray(hourlyLossBgCrHitNY, currentHour);\r\n var fightLossStrongNY = prepStatsArray(hourlyLossStrongNY, currentHour);\r\n\r\n//Add 25th hour data to beginning of graphing arrays\r\n fightExpNY.unshift(fightExpNY25);\r\n fightWinsNY.unshift(fightWinsNY25);\r\n fightLossesNY.unshift(fightLossesNY25);\r\n fightWin$NY.unshift(fightWin$NY25);\r\n fightLoss$NY.unshift(fightLoss$NY25);\r\n fightLossCHNY.unshift(fightLossCrHitNY25);\r\n fightLossBGCHNY.unshift(fightLossBgCrHitNY25);\r\n fightLossStrongNY.unshift(fightLossStrongNY25);\r\n\r\n//create hour labels based on current hour\r\n var hourLabels = \"\";\r\n for (i = 0; i < 24; i += 2) {\r\n var ind;\r\n var hrdisp;\r\n ind = (currentHour *1) - i;\r\n if (ind < 0) {ind = 24 + ind;}\r\n if (ind > 11) {hrdisp = String((12 - ind) * -1) + 'p';} else {hrdisp = String(ind) + 'a';}\r\n hrdisp = (hrdisp == '0a') ? '12a' : hrdisp;\r\n hrdisp = (hrdisp == '0p') ? '12p' : hrdisp;\r\n hourLabels = '|' + hrdisp + hourLabels;\r\n }\r\n hourLabels = '|' + hourLabels.split('|')[12] + hourLabels;\r\n\r\n//lets make some graphs!\r\n //statSpecs Array Format: [0]Min, [1]Max. [2]Avg [3]Sum [4]Valid Data Count\r\n var statSpecsArrayA = [];\r\n var statSpecsArrayB = [];\r\n\r\n var graphOutput = \"\";\r\n\r\n //Gain rate per hour\r\n gainRateNY = [];\r\n for (i = 0; i < fightWinsNY.length; i++) {\r\n gainRateNY[i] = fightExpNY[i]/(fightWinsNY[i] + fightLossesNY[i]);\r\n if (isNaN(gainRateNY[i])) { gainRateNY[i] = 0; }\r\n gainRateNY[i] = Math.round(gainRateNY[i] * Math.pow(10,2))/Math.pow(10,2);\r\n }\r\n statSpecsArrayA = getStatSpecs(gainRateNY, 0);\r\n graphOutput = '<IMG SRC=\"' + 'http://chart.apis.google.com/chart?cht=ls&chf=bg,s,111111&chts=BCD2EA,12&chtt=NY+Fight+Gain+Rate+per+Hr+of+Day|Min.+=+' + String(statSpecsArrayA[0]) + '+++Max.+=+' +String(statSpecsArrayA[1]) + '+++Avg+=+' + String(statSpecsArrayA[2]) + '/hr&chs=315x150&chxt=x,y&chxl=0:' + hourLabels + '&chxtc=0,10|1,-300&chxr=1,' + statSpecsArrayA[0] + ',' + statSpecsArrayA[1] + '&chds=' + statSpecsArrayA[0] + ',' + statSpecsArrayA[1] + '&chm=D,04B4AE,0,0,4|o,05E6DE,0,-1.0,6&chd=t:' + String(gainRateNY) + '\"/>';\r\n\r\n //NY Fight XP gains per hour\r\n var diffArrayA = getArrayDiffs(fightExpNY);\r\n statSpecsArrayA = getStatSpecs(diffArrayA, 0);\r\n graphOutput += '<br><br>' + '<IMG SRC=\"' + 'http://chart.apis.google.com/chart?cht=ls&chf=bg,s,111111&chts=BCD2EA,12&chtt=Total+NY+Fight+XP+Gained+per+Hr+of+Day|Min.+=+' + String(statSpecsArrayA[0]) + '+++Max.+=+' +String(statSpecsArrayA[1]) + '+++Avg+=+' + String(statSpecsArrayA[2]) + '/hr&chs=315x150&chxt=x,y&chxl=0:' + hourLabels + '&chxtc=0,10|1,-300&chxr=1,' + statSpecsArrayA[0] + ',' + statSpecsArrayA[1] + '&chds=' + statSpecsArrayA[0] + ',' + statSpecsArrayA[1] + '&chm=D,92ED97,0,0,4|o,25DA2E,0,-1.0,6&chd=t:' + String(diffArrayA) + '\"/>';\r\n\r\n //NY Fight Wins/Losses since reset chart\r\n var NYfightWinPct = (GM_getValue('fightWinsNY', 0)/(GM_getValue('fightWinsNY', 0) + GM_getValue('fightLossesNY', 0)))*100;\r\n if (isNaN(NYfightWinPct)){NYfightWinPct = 0;} else {NYfightWinPct = Math.round(NYfightWinPct * Math.pow(10, 1))/Math.pow(10, 1);}\r\n var NYfightLosePct = (GM_getValue('fightLossesNY', 0)/(GM_getValue('fightWinsNY', 0) + GM_getValue('fightLossesNY', 0)))*100;\r\n if (isNaN(NYfightLosePct)) {NYfightLosePct = 0; } else {NYfightLosePct = Math.round(NYfightLosePct * Math.pow(10, 1))/Math.pow(10, 1);}\r\n\r\n //NY Fight Loss Type breakdown pie\r\n var NYStrongLossPct = (GM_getValue('fightLossStrongNY', 0)/GM_getValue('fightLossesNY', 0))*100;\r\n if (isNaN(NYStrongLossPct)){NYStrongLossPct = 0;}else{NYStrongLossPct = Math.round(NYStrongLossPct * Math.pow(10, 1))/Math.pow(10, 1);}\r\n var NYCHLossPct = (GM_getValue('fightLossCHNY', 0)/GM_getValue('fightLossesNY', 0))*100;\r\n if (isNaN(NYCHLossPct)){NYCHLossPct = 0;}else{NYCHLossPct = Math.round(NYCHLossPct * Math.pow(10, 1))/Math.pow(10, 1);}\r\n var NYBGCHLossPct = (GM_getValue('fightLossBGCHNY', 0)/GM_getValue('fightLossesNY', 0))*100;\r\n if (isNaN(NYBGCHLossPct)){NYBGCHLossPct = 0;}else{NYBGCHLossPct = Math.round(NYBGCHLossPct * Math.pow(10, 1))/Math.pow(10, 1);}\r\n\r\n graphOutput += '<br><br>' + '<IMG SRC=\"' + 'http://chart.apis.google.com/chart?cht=p3&chf=bg,s,111111&chts=BCD2EA,12&chco=52E259|EC2D2D&chdl=' + String(NYfightWinPct) + '%|'+ String(NYfightLosePct) + '%&chdlp=t&chtt=NY+Fight+Wins+vs+Losses|since+stats+reset&chs=157x150&chd=t:' + String(NYfightWinPct) + ',' + String(NYfightLosePct) + '\"/>' +\r\n '<IMG SRC=\"' + 'http://chart.apis.google.com/chart?cht=p3&chf=bg,s,111111&chts=BCD2EA,12&chco=EC2D2D&chdl=CH:' + String(NYCHLossPct) + '%|BG:'+ String(NYBGCHLossPct) + '%|TS:'+ String(NYStrongLossPct) + '%&chdlp=t&chtt=NY+Fight+Losses+by+Type&chs=157x150&chd=t:' + String(NYCHLossPct) + ',' + String(NYBGCHLossPct) + ',' + String(NYStrongLossPct) + '\"/><br>' +\r\n '<span style=\"color:#888888;\">CH = Critical Hit ¦ BG = Bodyguard Critical Hit ¦ TS = Too Strong</span>';\r\n\r\n //NY Fight $ Won/lost line graph\r\n statSpecsArrayA = getStatSpecs(fightWin$NY, 0);\r\n statSpecsArrayB = getStatSpecs(fightLoss$NY, 0);\r\n if (statSpecsArrayB[0]*1 < statSpecsArrayA[0]*1) {\r\n statSpecsArrayA[0] = statSpecsArrayB[0];\r\n }\r\n if (statSpecsArrayB[1]*1 > statSpecsArrayA[1]*1) {\r\n statSpecsArrayA[1] = statSpecsArrayB[1];\r\n }\r\n graphOutput += '<br><br>' + '<IMG SRC=\"' + 'http://chart.apis.google.com/chart?cht=ls&chf=bg,s,111111&chts=BCD2EA,12&chtt=Total+NY+Fight+$+Won+vs.+Lost+by+Hr+of+Day&chs=315x150&chxt=x,y&chxl=0:' + hourLabels + '&chxtc=0,10|1,-300&chxr=1,' + statSpecsArrayA[0] + ',' + statSpecsArrayA[1] + '&chds=' + statSpecsArrayA[0] + ',' + statSpecsArrayA[1] + '&chm=D,92ED97,0,0,4|o,25DA2E,0,-1.0,6|D,F05C5C,1,0,4|o,D21414,1,-1.0,6&chd=t:' + String(fightWin$NY) + '|' + String(fightLoss$NY) + '\"/>';\r\n\r\n //addToLog('info Icon', graphOutput);\r\n graphOutput = '<span style=\"color:#669999;\">Stats as of: ' + currentTime.toLocaleString() + '</span><br>' + graphOutput;\r\n GM_setValue('graphBox', graphOutput);\r\n\r\n//re-pack hourly stats and save to GM variable\r\n hrDataPack = [];\r\n for (i = 0; i < 24; i++){\r\n hrDataPack[i]= i + '|' + hourlyFightExpNY[i] + '|' + hourlyFightWinsNY[i] + '|' + hourlyFightLossesNY[i] + '|' +\r\n hourlyFightWin$NY[i] + '|' + hourlyFightLoss$NY[i] + '|' + hourlyLossCrHitNY[i] + '|' + hourlyLossBgCrHitNY[i] +\r\n '|' + hourlyLossStrongNY[i];\r\n }\r\n GM_setValue('hourlyStats', String(hrDataPack));\r\n\r\n }\r\n GM_setValue('hourOfDay', String(currentHour));\r\n}",
"function updateStats(countriestoUpdate){\n\n let i = 0;\n var jsonCountries = JSON.parse(countriestoUpdate)\n var newTotStats = totalCounter(jsonCountries)\n totalStatComparison(previousWorldStats,newTotStats); //calls function to compare old stats to new stats\n\n\n for (let[updateCountry, value] of Object.entries(jsonCountries)){\n i++;\n if(i>48){\n break;\n }\n for (let[key, value2] of Object.entries(value)){\n let getID = '#' + key + updateCountry.replace(\" \",'');\n let standOut = '#' + updateCountry.replace(\" \",'');\n if (key == 'Cases'){\n if(parseInt($(getID).text().replace(\",\",''))<parseInt(value2.replace(\",\",''))){\n let arrowSpan = document.createElement(\"span\")\n arrowSpan.className = \"arrow\"\n arrowSpan.innerHTML = \"⤴\"\n arrowSpan.style.fontSize = \"16px\"\n $(getID).html(value2).addClass(\"text-warning\");\n $(getID).append(arrowSpan);\n $(standOut).css(\"border\",\"10px solid #ffffff\");\n }\n }else if (key == 'Recovered'){\n if(parseInt($(getID).text().replace(\",\",''))<parseInt(value2.replace(\",\",''))){\n let arrowSpan = document.createElement(\"span\")\n arrowSpan.className = \"arrow\"\n arrowSpan.innerHTML = \"⤴\"\n arrowSpan.style.fontSize = \"16px\"\n $(getID).html(value2).addClass(\"text-success\");\n $(getID).append(arrowSpan);\n $(standOut).css(\"border\",\"10px solid #ffffff\");\n }\n }else if (key == 'Deaths'){\n if(parseInt($(getID).text().replace(\",\",''))<parseInt(value2.replace(\",\",''))){\n let arrowSpan = document.createElement(\"span\")\n arrowSpan.className = \"arrow\"\n arrowSpan.innerHTML = \"⤴\"\n arrowSpan.style.fontSize = \"16px\"\n $(getID).html(value2).addClass(\"text-danger\");\n $(getID).append(arrowSpan);\n $(standOut).css(\"border\",\"10px solid #ffffff\");\n }\n }\n \n };\n };\n var wait = ms => new Promise((r, j)=>setTimeout(r, ms))\n var prom = wait(15000);\n prom.then(restoreNormal);\n}",
"function updateStats() {\r\n //$('#mass_stat_exp_per_sta').text(fightStats.exp_per_sta());\r\n //$('.bossfight_current_health_med').attr('style', 'width: ' + fightStats.healthpercent() + '%;');\r\n //$('#mass_stat_cash').html(fightStats.cash());\r\n //\r\n //for (f in fightStats) {\r\n // var stat = fightStats[f];\r\n // var elem = e$('#mass_stat_' + f.toLowerCase());\r\n // if (elem !== null && typeof(stat) == 'number') {\r\n // elem.text(stat);\r\n // }\r\n //}\r\n }",
"function addBattleInfo() {\r\n\t\r\n\t\t//get all the tables that hold military information for each player\r\n\t\tvar tables = document.getElementById('lmid2').getElementsByTagName('table')[0].getElementsByTagName('table');\r\n\t\tvar totalResLosses;\r\n\t\tvar totalBounty;\r\n\t\tvar attackersBounty = 0; //holds info about how much resources the attacker got, this is later added to first defenders losses\r\n\t\t\r\n\t\t//transform each table\r\n\t\tfor (var i=0;i<tables.length;i++) {\r\n\t\r\n\t\t\t//get tribe data, used to calculate troop information later\r\n\t\t\tvar tribe = getTribeBySettlerImage(i);\r\n\t\r\n\t\t\t//add the transformations\r\n\t\t\tif (tables[i].rows.length>3) {\r\n\t\t\t\ttransformBattleReport_addSurvivors(tables[i]);\r\n\t\t\t\ttotalBounty = transformBattleReport_addBountySums(tables[i], tribe);\r\n\t\t\t\tif (i==0) attackersBounty=totalBounty;\r\n\t\t\t\ttotalResLosses = transformBattleReport_addLostUnitsCost(tables[i], tribe);\r\n\t\t\t\ttransformBattleReport_addTotals(tables[i], tribe, totalResLosses, totalBounty,(i==1)?attackersBounty:0, i==0);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\r\n\t\t}",
"function reset_inning_stats( player )\n{\n// BOWLER\n\tplayer.bowler_innings.wickets_left = 10;\n\tplayer.bowler_innings.wickets_taken = 0;\n\tplayer.bowler_innings.wickets = \n\t\t[\n\t\t\t{\n\t\t\t\twicket: 1,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 2,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 3,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 4,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 5,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 6,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 7,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 8,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 9,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 10,\n\t\t\t\tscore: ''\n\t\t\t}\n\t\t];\n\tplayer.bowler_innings.first_dart = 0;\n\tplayer.bowler_innings.second_dart = 0;\n\tplayer.bowler_innings.third_dart = 0;\n\tplayer.bowler_innings.scores = [];\n\tplayer.bowler_innings.scores_text = [];\n\tplayer.bowler_innings.turn_score = 0;\n\tplayer.bowler_innings.turn_scores = [];\n\tplayer.bowler_innings.outer_bulls = 0;\n\tplayer.bowler_innings.bullseyes = 0;\n\tplayer.bowler_innings.wides = 0;\n\tplayer.bowler_innings.runs_given = [];\n\tplayer.bowler_innings.total_given = 0;\n\tplayer.bowler_innings.darts_missed = 0;\n\tplayer.bowler_innings.num_darts = 0;\n\tplayer.bowler_innings.runs_conceded = 0;\n\t\n// BATSMAN\n\tplayer.batsman_innings.wickets_left = 10;\n\tplayer.batsman_innings.wickets_fallen = 0;\n\tplayer.batsman_innings.wickets =\n\t\t[\n\t\t\t{\n\t\t\t\twicket: 1,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 2,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 3,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 4,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 5,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 6,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 7,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 8,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 9,\n\t\t\t\tscore: ''\n\t\t\t},\n\t\t\t{\n\t\t\t\twicket: 10,\n\t\t\t\tscore: ''\n\t\t\t}\n\t\t];\t\t\t\n\tplayer.batsman_innings.first_dart = 0;\n\tplayer.batsman_innings.second_dart = 0;\n\tplayer.batsman_innings.third_dart = 0;\n\tplayer.batsman_innings.scores = [];\n\tplayer.batsman_innings.scores_text = [];\n\tplayer.batsman_innings.turn_score = 0;\n\tplayer.batsman_innings.turn_scores = [];\n\tplayer.batsman_innings.runs_scored = 0;\n\tplayer.batsman_innings.turn_runs = [];\n\tplayer.batsman_innings.over_forty_one = 0;\n\tplayer.batsman_innings.under_forty_one = 0;\n\tplayer.batsman_innings.run_outs = 0;\n\tplayer.batsman_innings.darts_missed = 0;\n\tplayer.batsman_innings.num_darts = 0;\n\tplayer.batsman_innings.total_scored = 0;\n}",
"function updateHourlyStats() {\n\t//Planned data package order: [0]Hour of the Day |\n\t// [1]NY Fight Exp | [2]NY Fight Win Count | [3]NY Fight Loss Count | [4]NY Fight $ Won | [5]NY Fight $Lost |\n\t// [6]NY Rob Exp | [7]NY Rob Success Count | [8]NY Rob Fail Count | [9]NY Rob $Won | [10]NY Rob $Lost |\n\t// [11]NY Fight Loss Crit Hit Count | [12]NY Fight Loss Bodyguard Count | [13]NY Fight Loss Too Strong Count |\n\t// Variables below not yet created\n\t// [x]NY Capo $US | [x]NY Assist Exp | [x]NY Assist $US |\n\t// [x]NY Attacked Exp(net after deaths) | [x]NY Attacked $Won | [x]NY Attacked $Lost |\n\t// [x]NY Robbed Exp | [x]NY Robbed $Won | [x]NY Robbed $Lost |\n\t// [x]NY Job Count | [x]NY Job Exp | [x]NY Job $Made |\n\t// >>> BEGIN CUBA <<<\n\t// [x]Cuba Fight Exp | [x]Cuba Fight Win Count | [x]Cuba Fight Loss Count | [x]Cuba Fight $C Won | [x]Cuba Fight $C Lost |\n\t// [x]Cuba Fight Loss Crit Hit Count | [x]Cuba Fight Loss Bodyguard Count | [x]Cuba Fight Loss Too Strong Count |\n\t// [x]Cuba Capo $C | [x]Cuba Assist Exp | [x]Cuba Assist $C |\n\t// [x]Cuba Attacked Exp(net after deaths) | [x]Cuba Attacked $C Won | [x]Cuba Attacked $C Lost |\n\t// [x]Cuba Robbed Exp | [x]Cuba Robbed $C Won | [x]Cuba Robbed $C Lost |\n\t// [x]Cuba Job Count | [x]Cuba Job Exp | [x]Cuba Job $C Made\n\t\n\t// Max potential storage 41 * 24 = 984 elements\n\t\n\t var i, currentTime = new Date();\n\t var currentHour = currentTime.getHours();\n\t\n\t var hrDataPack = \"\";\n\t hrDataPack = currentHour + '|' + GM_getValue('fightExpNY', 0) + '|' + GM_getValue('fightWinsNY', 0) + '|' +\n\t GM_getValue('fightLossesNY', 0) + '|' + GM_getValue('fightWin$NY', 0) + '|' + GM_getValue('fightLoss$NY', 0) + '|' +\n\t GM_getValue('fightLossCHNY', 0) + '|' + GM_getValue('fightLossBGCHNY', 0) + '|'+ GM_getValue('fightLossStrongNY', 0);\n\t\n\t if (GM_getValue('hourlyStats', '0') == '0') {\n\t GM_setValue('hourlyStats', hrDataPack);\n\t } else {\n\t //pull existing stored hourly stats\n\t var splitValues = GM_getValue('hourlyStats', '').split(',');\n\t if (splitValues.length < 24) {\n\t splitValues.push(currentHour + '|0|0|0|0|0|0|0|0');\n\t }else {\n\t if ((GM_getValue('hourOfDay')*1 == 23 && currentHour != 0 )|| currentHour -1 != GM_getValue('hourOfDay')*1 && GM_getValue('hourOfDay') != isNaN(GM_getValue('hourOfDay'))){\n\t //We missed some hours so we need to carry the last good values forward\n\t var tempHour;\n\t if (GM_getValue('hourOfDay')*1 > currentHour){\n\t tempHour = currentHour + 24;\n\t }else{\n\t tempHour = currentHour;\n\t }\n\t\n\t for (i = GM_getValue('hourOfDay')*1 + 1; i < GM_getValue('hourOfDay')*1 + (tempHour - GM_getValue('hourOfDay')*1); i++){\n\t var valString = splitValues[GM_getValue('hourOfDay')];\n\t valString = valString.substring(valString.indexOf('|'), valString.length);\n\t if (i > 23){\n\t splitValues.push(String(i-24) + valString);\n\t }else {\n\t splitValues.push(i + valString);\n\t }\n\t }\n\t }\n\t }\n\t //create temp arrays\n\t var hourlyFightExpNY = new Array(24); //position [1]\n\t var hourlyFightWinsNY = new Array(24); //position [2]\n\t var hourlyFightLossesNY = new Array(24); //position [3]\n\t var hourlyFightWin$NY = new Array(24); //position [4]\n\t var hourlyFightLoss$NY = new Array(24); //position [5]\n\t var hourlyLossCrHitNY = new Array(24); //position [6]\n\t var hourlyLossBgCrHitNY = new Array(24); //position [7]\n\t var hourlyLossStrongNY = new Array(24); //position [8]\n\t\n\t // Organize Hourly stat data into ordered sets\n\t for (i = 0; i < splitValues.length; i++){\n\t //check length of each datapack to ensure it is the right size and fills missing with zeroes\n\t //this addresses issues when adding new metrics to the datapackage\n\t if (splitValues[i].split('|').length < 9) {\n\t for (var n = splitValues[i].split('|').length; n < 9; n++){\n\t splitValues[i] += '|0';\n\t }\n\t }\n\t if (splitValues[i].split('|')[0] == currentHour) {\n\t //pull data from same time day prior for \"25th\" hour\n\t var fightExpNY25 = splitValues[i].split('|')[1]*1;\n\t var fightWinsNY25 = splitValues[i].split('|')[2]*1;\n\t var fightLossesNY25 = splitValues[i].split('|')[3]*1;\n\t var fightWin$NY25 = splitValues[i].split('|')[4]*1;\n\t var fightLoss$NY25 = splitValues[i].split('|')[5]*1;\n\t var fightLossCrHitNY25 = splitValues[i].split('|')[6];\n\t var fightLossBgCrHitNY25 = splitValues[i].split('|')[7];\n\t var fightLossStrongNY25 = splitValues[i].split('|')[8];\n\t //Insert current hour values\n\t hourlyFightExpNY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[1]*1;\n\t hourlyFightWinsNY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[2]*1;\n\t hourlyFightLossesNY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[3]*1;\n\t hourlyFightWin$NY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[4]*1;\n\t hourlyFightLoss$NY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[5]*1;\n\t hourlyLossCrHitNY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[6]*1;\n\t hourlyLossBgCrHitNY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[7]*1;\n\t hourlyLossStrongNY[splitValues[i].split('|')[0]] = hrDataPack.split('|')[8]*1;\n\t } else {\n\t //populate other hourly data\n\t hourlyFightExpNY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[1]*1;\n\t hourlyFightWinsNY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[2]*1;\n\t hourlyFightLossesNY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[3]*1;\n\t hourlyFightWin$NY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[4]*1;\n\t hourlyFightLoss$NY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[5]*1;\n\t hourlyLossCrHitNY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[6]*1;\n\t hourlyLossBgCrHitNY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[7]*1;\n\t hourlyLossStrongNY[splitValues[i].split('|')[0]] = splitValues[i].split('|')[8]*1;\n\t }\n\t }\n\t\n\t //Prep Arrays for hourly graphing\n\t var fightExpNY = prepStatsArray(hourlyFightExpNY, currentHour);\n\t var fightWinsNY = prepStatsArray(hourlyFightWinsNY, currentHour);\n\t var fightLossesNY = prepStatsArray(hourlyFightLossesNY, currentHour);\n\t var fightWin$NY = prepStatsArray(hourlyFightWin$NY, currentHour);\n\t var fightLoss$NY = prepStatsArray(hourlyFightLoss$NY, currentHour);\n\t var fightLossCHNY = prepStatsArray(hourlyLossCrHitNY, currentHour);\n\t var fightLossBGCHNY = prepStatsArray(hourlyLossBgCrHitNY, currentHour);\n\t var fightLossStrongNY = prepStatsArray(hourlyLossStrongNY, currentHour);\n\t\n\t //Add 25th hour data to beginning of graphing arrays\n\t fightExpNY.unshift(fightExpNY25);\n\t fightWinsNY.unshift(fightWinsNY25);\n\t fightLossesNY.unshift(fightLossesNY25);\n\t fightWin$NY.unshift(fightWin$NY25);\n\t fightLoss$NY.unshift(fightLoss$NY25);\n\t fightLossCHNY.unshift(fightLossCrHitNY25);\n\t fightLossBGCHNY.unshift(fightLossBgCrHitNY25);\n\t fightLossStrongNY.unshift(fightLossStrongNY25);\n\t\n\t //create hour labels based on current hour\n\t var hourLabels = \"\";\n\t for (i = 0; i < 24; i += 2) {\n\t var ind;\n\t var hrdisp;\n\t ind = (currentHour *1) - i;\n\t if (ind < 0) {ind = 24 + ind;}\n\t if (ind > 11) {hrdisp = String((12 - ind) * -1) + 'p';} else {hrdisp = String(ind) + 'a';}\n\t hrdisp = (hrdisp == '0a') ? '12a' : hrdisp;\n\t hrdisp = (hrdisp == '0p') ? '12p' : hrdisp;\n\t hourLabels = '|' + hrdisp + hourLabels;\n\t }\n\t hourLabels = '|' + hourLabels.split('|')[12] + hourLabels;\n\t\n\t //lets make some graphs!\n\t //statSpecs Array Format: [0]Min, [1]Max. [2]Avg [3]Sum [4]Valid Data Count\n\t var statSpecsArrayA = [];\n\t var statSpecsArrayB = [];\n\t\n\t var graphOutput = \"\";\n\t\n\t //Gain rate per hour\n\t gainRateNY = [];\n\t for (i = 0; i < fightWinsNY.length; i++) {\n\t gainRateNY[i] = fightExpNY[i]/(fightWinsNY[i] + fightLossesNY[i]);\n\t if (isNaN(gainRateNY[i])) { gainRateNY[i] = 0; }\n\t gainRateNY[i] = Math.round(gainRateNY[i] * Math.pow(10,2))/Math.pow(10,2);\n\t }\n\t statSpecsArrayA = getStatSpecs(gainRateNY, 0);\n\t graphOutput = '<IMG SRC=\"' + 'http://chart.apis.google.com/chart?cht=ls&chf=bg,s,111111&chts=BCD2EA,12&chtt=NY+Fight+Gain+Rate+per+Hr+of+Day|Min.+=+' + String(statSpecsArrayA[0]) + '+++Max.+=+' +String(statSpecsArrayA[1]) + '+++Avg+=+' + String(statSpecsArrayA[2]) + '/hr&chs=315x150&chxt=x,y&chxl=0:' + hourLabels + '&chxtc=0,10|1,-300&chxr=1,' + statSpecsArrayA[0] + ',' + statSpecsArrayA[1] + '&chds=' + statSpecsArrayA[0] + ',' + statSpecsArrayA[1] + '&chm=D,04B4AE,0,0,4|o,05E6DE,0,-1.0,6&chd=t:' + String(gainRateNY) + '\"/>';\n\t\n\t //NY Fight XP gains per hour\n\t var diffArrayA = getArrayDiffs(fightExpNY);\n\t statSpecsArrayA = getStatSpecs(diffArrayA, 0);\n\t graphOutput += '<br><br>' + '<IMG SRC=\"' + 'http://chart.apis.google.com/chart?cht=ls&chf=bg,s,111111&chts=BCD2EA,12&chtt=Total+NY+Fight+XP+Gained+per+Hr+of+Day|Min.+=+' + String(statSpecsArrayA[0]) + '+++Max.+=+' +String(statSpecsArrayA[1]) + '+++Avg+=+' + String(statSpecsArrayA[2]) + '/hr&chs=315x150&chxt=x,y&chxl=0:' + hourLabels + '&chxtc=0,10|1,-300&chxr=1,' + statSpecsArrayA[0] + ',' + statSpecsArrayA[1] + '&chds=' + statSpecsArrayA[0] + ',' + statSpecsArrayA[1] + '&chm=D,92ED97,0,0,4|o,25DA2E,0,-1.0,6&chd=t:' + String(diffArrayA) + '\"/>';\n\t\n\t //NY Fight Wins/Losses since reset chart\n\t var NYfightWinPct = (GM_getValue('fightWinsNY', 0)/(GM_getValue('fightWinsNY', 0) + GM_getValue('fightLossesNY', 0)))*100;\n\t if (isNaN(NYfightWinPct)){NYfightWinPct = 0;} else {NYfightWinPct = Math.round(NYfightWinPct * Math.pow(10, 1))/Math.pow(10, 1);}\n\t var NYfightLosePct = (GM_getValue('fightLossesNY', 0)/(GM_getValue('fightWinsNY', 0) + GM_getValue('fightLossesNY', 0)))*100;\n\t if (isNaN(NYfightLosePct)) {NYfightLosePct = 0; } else {NYfightLosePct = Math.round(NYfightLosePct * Math.pow(10, 1))/Math.pow(10, 1);}\n\t\n\t //NY Fight Loss Type breakdown pie\n\t var NYStrongLossPct = (GM_getValue('fightLossStrongNY', 0)/GM_getValue('fightLossesNY', 0))*100;\n\t if (isNaN(NYStrongLossPct)){NYStrongLossPct = 0;}else{NYStrongLossPct = Math.round(NYStrongLossPct * Math.pow(10, 1))/Math.pow(10, 1);}\n\t var NYCHLossPct = (GM_getValue('fightLossCHNY', 0)/GM_getValue('fightLossesNY', 0))*100;\n\t if (isNaN(NYCHLossPct)){NYCHLossPct = 0;}else{NYCHLossPct = Math.round(NYCHLossPct * Math.pow(10, 1))/Math.pow(10, 1);}\n\t var NYBGCHLossPct = (GM_getValue('fightLossBGCHNY', 0)/GM_getValue('fightLossesNY', 0))*100;\n\t if (isNaN(NYBGCHLossPct)){NYBGCHLossPct = 0;}else{NYBGCHLossPct = Math.round(NYBGCHLossPct * Math.pow(10, 1))/Math.pow(10, 1);}\n\t\n\t graphOutput += '<br><br>' + '<IMG SRC=\"' + 'http://chart.apis.google.com/chart?cht=p3&chf=bg,s,111111&chts=BCD2EA,12&chco=52E259|EC2D2D&chdl=' + String(NYfightWinPct) + '%|'+ String(NYfightLosePct) + '%&chdlp=t&chtt=NY+Fight+Wins+vs+Losses|since+stats+reset&chs=157x150&chd=t:' + String(NYfightWinPct) + ',' + String(NYfightLosePct) + '\"/>' +\n\t '<IMG SRC=\"' + 'http://chart.apis.google.com/chart?cht=p3&chf=bg,s,111111&chts=BCD2EA,12&chco=EC2D2D&chdl=CH:' + String(NYCHLossPct) + '%|BG:'+ String(NYBGCHLossPct) + '%|TS:'+ String(NYStrongLossPct) + '%&chdlp=t&chtt=NY+Fight+Losses+by+Type&chs=157x150&chd=t:' + String(NYCHLossPct) + ',' + String(NYBGCHLossPct) + ',' + String(NYStrongLossPct) + '\"/><br>' +\n\t '<span style=\"color:#888888;\">CH = Critical Hit ¦ BG = Bodyguard Critical Hit ¦ TS = Too Strong</span>';\n\t\n\t //NY Fight $ Won/lost line graph\n\t statSpecsArrayA = getStatSpecs(fightWin$NY, 0);\n\t statSpecsArrayB = getStatSpecs(fightLoss$NY, 0);\n\t if (statSpecsArrayB[0]*1 < statSpecsArrayA[0]*1) {\n\t statSpecsArrayA[0] = statSpecsArrayB[0];\n\t }\n\t if (statSpecsArrayB[1]*1 > statSpecsArrayA[1]*1) {\n\t statSpecsArrayA[1] = statSpecsArrayB[1];\n\t }\n\t graphOutput += '<br><br>' + '<IMG SRC=\"' + 'http://chart.apis.google.com/chart?cht=ls&chf=bg,s,111111&chts=BCD2EA,12&chtt=Total+NY+Fight+$+Won+vs.+Lost+by+Hr+of+Day&chs=315x150&chxt=x,y&chxl=0:' + hourLabels + '&chxtc=0,10|1,-300&chxr=1,' + statSpecsArrayA[0] + ',' + statSpecsArrayA[1] + '&chds=' + statSpecsArrayA[0] + ',' + statSpecsArrayA[1] + '&chm=D,92ED97,0,0,4|o,25DA2E,0,-1.0,6|D,F05C5C,1,0,4|o,D21414,1,-1.0,6&chd=t:' + String(fightWin$NY) + '|' + String(fightLoss$NY) + '\"/>';\n\t\n\t //addToLog('info Icon', graphOutput);\n\t graphOutput = '<span style=\"color:#669999;\">Stats as of: ' + currentTime.toLocaleString() + '</span><br>' + graphOutput;\n\t GM_setValue('graphBox', graphOutput);\n\t\n\t //re-pack hourly stats and save to GM variable\n\t hrDataPack = [];\n\t for (i = 0; i < 24; i++){\n\t hrDataPack[i]= i + '|' + hourlyFightExpNY[i] + '|' + hourlyFightWinsNY[i] + '|' + hourlyFightLossesNY[i] + '|' +\n\t hourlyFightWin$NY[i] + '|' + hourlyFightLoss$NY[i] + '|' + hourlyLossCrHitNY[i] + '|' + hourlyLossBgCrHitNY[i] +\n\t '|' + hourlyLossStrongNY[i];\n\t }\n\t GM_setValue('hourlyStats', String(hrDataPack));\n\t\n\t }\n\t GM_setValue('hourOfDay', String(currentHour));\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
send feedback to control page | function feedback(message, guid){
// var pid = getPidForUser(guid);
var session = getSessionForUser(guid);
var originalguid = getFirstGuid(guid);
// send to session pages - control page can display
io.to(session).emit('feedback', {"message": message, "user": originalguid});
} | [
"sendFeedback() {\r\n shell.openExternal(ApplicationConstants.FEEDBACK_URL);\r\n }",
"function sendFeedback() {\n\t// Make sure there's feedback text first\n\tif (!$.trim($(\"#feedbackTextArea\").val())) {\n\t\t$(\"#feedbackEmptyAlert\").removeClass(\"hidden\").hide().slideDown(\"fast\");\n\t\treturn;\n\t}\n\tvar feedbackText = $(\"#feedbackTextArea\").val() + \"\\n---\\n Sent from \" + window.location.href + \"\\n\" + navigator.userAgent;\n\tvar feedbackType = $(\"#feedbackTypeSelector\").val();\n\t$(\"#feedbackSpinner\").removeClass(\"hidden\");\n\t$(\"#feedbackForm\").slideUp();\n\t$.post(\"../feedback/submit\", {\"feedbackType\":feedbackType,\"feedback\":feedbackText}, function(data) {\n\t\t$(\"#feedbackResult\").removeClass(\"hidden\").text(data);\n\t\t$(\"#feedbackSpinner\").addClass(\"hidden\");\n\t});\n}",
"submitConfused() {\n\t\tlet data = {\n\t\t\tid: this.props.for,\n\t\t\tuserID: getUserData().id,\n\t\t\ttype: 'confused'\n\t\t};\n\t\tthis.showFeedbackResponse( 'confused' );\n\t\t// sendData( data, config );\n\t}",
"function setFeedback(msg) {\n\t\t$(\"#feedback\").text(msg);\n\t}",
"function sendFeedback() {\n const feedback = getFeedbackData();\n\n server.sendFeedback(feedback)\n .then(() => mediator.publish('onFeedbackSave'));\n }",
"function feedback() {\n alert(\"Your feedback is submitted.\");\n}",
"function gTYLS() {\n //prevent errors and mishaps\n if (!ls.enabled) {return; }\n if (url.pathname.indexOf(\"thank\") < 0) {return; }\n console.log('thankyou');\n //code here\n }",
"function submit(){\n\t\tstop();\n\t\tcheckAnswers();\n\t\tshowResults();\t\n\t}",
"function sendControl(request)\n{\n\tvar cc = request.payload.cc_number;\n\tvar value = request.payload.value;\n\tsendMessage(176, cc, value);\n request.reply('Control message sent. CC = ' + cc + ', value = ' + value);\n}",
"function displayFeedback(feedback) {\n\t$(\"#feedback\").text(feedback);\n}",
"function enableFeedbackURL() {\n\tif (lessonMode == LESSON_PILOTTESTING_MODE && isCongratsLastPageSet) {\n\t\tif (parent.frames.frame_b.document.getElementById(\"divFeedback\")) {\n\t\t\tdocument.getElementById('divFeedback').innerHTML = \"<a href=\\\"javascript:parent.frames.frame_a.OpenLink('FEEDBACK')\\\">Feedback</a>\"\n\t\t\tdocument.getElementById('divFeedback').style.cursor = \"pointer\";\n\t\t\tdocument.getElementById('divFeedback').style.display = \"\";\n\t\t\tisCongratsLastPageSet = false;\n\t\t}\n\t\telse {\n\t\t\tisFeedbackURLResponseSet = true;\n\t\t}\n\t}\n}",
"function changeFeedback(feedback) {\n\t\t$('#feedback').text(feedback);\n\t}",
"static sendUserFeedback(feedback) {\n\t\tTestFairyBridge.sendUserFeedback(feedback);\n\t}",
"function GUI(){\n\t\"use strict\";\n\t//var fbBar, //true if feedbackBar is shown\n\t//\tpage, //true if page is shown\n\t//\tfeedbackTimeout,\n\t\t//headerEl, feedbackEl, pageEl, confirmEl, alertEl, $form,\n\t\t//browserSupport = {'offline-launch':false, 'local-storage':false, 'fancy-visuals':false},\n\t\t//updateEditStatus,\n\t\t//_this=this;\n\t\t//$form = $('form.jr:eq(0)');\n}",
"function sendFeedback() {\n var message = {\n requestFeedback: true,\n feedbackInfo: {\n description: '',\n systemInformation: [\n {\n key: 'version',\n value: remoting.app.getExtensionInfo()\n },\n {\n key: 'consoleErrors',\n value: JSON.stringify(\n remoting.ConsoleWrapper.getInstance().getHistory())\n }\n ]\n }\n };\n var kFeedbackExtensionId = 'gfdkimpbcpahaombhbimeihdjnejgicl';\n chrome.runtime.sendMessage(kFeedbackExtensionId, message, function() {});\n}",
"function feedback() {\n \t\tif(guess == secretNumber){\n \t\t\t$(\"#feedback\").text(\"You are correct!\");\n \t\t} else if(Math.abs(guess - secretNumber) < 50) {\n \t\t\t\t$(\"#feedback\").text(\"Cool!\");\n \t\t\t\tif(Math.abs(guess - secretNumber) < 25) {\n \t\t\t\t\t$(\"#feedback\").text(\"Warm!\");\n \t\t\t\t\tif(Math.abs(guess - secretNumber) < 10) {\n \t\t\t\t\t\t$(\"#feedback\").text(\"Hot!\");\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t} else {\n \t\t\t$(\"#feedback\").text(\"Cold!\");\n \t\t}\n \t}",
"function ifUserisWrong(){\n generateWrongFeedback();\n}",
"function successMessage() {\n setSubmitButtonMessage(\"Cocktail Saved!\");\n }",
"submitUnderstood() {\n\t\tlet data = {\n\t\t\tid: this.props.for,\n\t\t\tuserID: getUserData().id,\n\t\t\ttype: 'understood'\n\t\t};\n\t\tthis.showFeedbackResponse( 'understood' );\n\t\t// sendData( data, config );\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parsing the json message. The type of message is identified by 'flag' node value flag can be self, new, message, exit | function parseMessage(message) {
var jObj = $.parseJSON(message);
// if the flag is 'self' message contains the session id
if (jObj.flag == 'self') {
sessionId = jObj.sessionId;
} else if (jObj.flag == 'new') {
// if the flag is 'new', a client joined grid
var new_name = 'You';
// number of people online
var online_count = jObj.onlineCount - 1;
$('p.online_count').html(
'Hello, <span class="green">' + name + '</span>. <b>'
+ online_count + '</b> devices online right now')
.fadeIn();
if (jObj.sessionId != sessionId) {
new_name = jObj.name;
var index = devicesArray.indexOf(new_name);
if (index < 0) {
devicesArray.push(new_name);
}
}
var li = '<li class="new" tabindex="1"><span class="name">' + new_name
+ '</span> ' + jObj.message + '</li>';
$('#messages').append(li);
$('#input_message').val('');
} else if (jObj.flag == 'message') {
if (jObj.sessionId == sessionId) {
var li = '<li tabindex="1">' + jObj.message + '</li>';
// appending the job to sent list
appendSentJob(li);
} else {
var li = '<li tabindex="1"><span class="name">' + jObj.name
+ '</span> ' + jObj.message + '</li>';
// appending the chat message to list
appendChatMessage(li);
var info = jObj.message.split(":");
if (devicesInfo[jObj.name] == null) {
devicesInfo[jObj.name] = {
benchmark : null,
battery : null,
jobs : 0,
totalJobs : 0
};
}
var trimmedInfo = info[0].trim();
if (trimmedInfo == "BogoMIPS" || trimmedInfo == "processor count") {
var mips = 0.0;
var processors = 1;
for (var i = 0, j = info.length; i < j; i++) {
if (info[i].trim().split("\n")[0] == "BogoMIPS"
|| info[i].trim().split("\n")[1] == "BogoMIPS") {
var currentMips = parseFloat(info[i + 1].trim().split(
"\n")[0]);
mips += currentMips;
}
}
devicesInfo[jObj.name]["benchmark"] = mips;
} else if (info[0] == "battery") {
var batteryData = devicesInfo[jObj.name]["battery"];
if (batteryData) {
if (batteryData.newCharge - info[1] != 0) {
batteryData.oldCharge = batteryData.newCharge;
batteryData.oldTime = batteryData.newTime;
batteryData.newCharge = info[1];
batteryData.newTime = new Date().getTime();
var dischargeRate = (batteryData.newTime - batteryData.oldTime)
/ (batteryData.oldCharge - batteryData.newCharge);
var estimatedUptime = batteryData.newTime
- batteryData.startTime + batteryData.newCharge
* dischargeRate;
batteryData.previousEstimations.push(estimatedUptime);
var newEstimatedUptime = getAverage(batteryData.previousEstimations)
- (batteryData.newTime - batteryData.startTime);
// Save new estimated uptime
if (newEstimatedUptime < 0) {
console.log("Estimated uptime remaining is NEGATIVE!!");
}
batteryData.estimatedUptime = newEstimatedUptime;
}
} else {
devicesInfo[jObj.name].battery = {
oldCharge : null,
newCharge : info[1],
oldTime : null,
newTime : new Date().getTime(),
startTime : new Date().getTime(),
previousEstimations : [],
estimatedUptime : null
}
}
} else { // it's a result
// update jobs counter on the device
var devicePendingJobs = jObj.message.split("/")[1].split(":")[1]
.trim();
devicePendingJobs = parseInt(devicePendingJobs);
if (devicesInfo[jObj.name]) {
devicesInfo[jObj.name].jobs = devicePendingJobs;
devicesInfo[jObj.name].totalJobs = devicesInfo[jObj.name].totalJobs + 1;
// console.log(jObj.name + " jobs executed: "
// + devicesInfo[jObj.name].totalJobs);
}
totalResultsReceived++;
$('p.total_results').html(
'Resultados recibidos: ' + totalResultsReceived)
.fadeIn();
// console.log("Results Received: " + totalResultsReceived);
}
}
} else if (jObj.flag == 'exit') {
var theTime = new Date();
var minutes = theTime.getMinutes() < 10 ? "0" + theTime.getMinutes()
: theTime.getMinutes();
var disconnectTime = theTime.getHours() + ":" + minutes;
// if the json flag is 'exit', it means somebody left the grid
var li = '<li class="exit" tabindex="1"><span class="name red">'
+ jObj.name + '</span> ' + jObj.message + ' at '
+ disconnectTime + '</li>';
// number of people online
var online_count = jObj.onlineCount - 1;
$('p.online_count').html(
'Hello, <span class="green">' + name + '</span>. <b>'
+ online_count + '</b> devices online right now')
.fadeIn();
var index = devicesArray.indexOf(jObj.name);
if (index > -1) {
devicesArray.splice(index, 1);
}
appendChatMessage(li);
console.log(jObj.name + " disconnected at " + disconnectTime);
if (devicesInfo[jObj.name]) {
console.log(jObj.name + " executed jobs: "
+ devicesInfo[jObj.name].totalJobs);
}
if (devicesInfo[jObj.name] && devicesInfo[jObj.name].battery
&& devicesInfo[jObj.name].battery.estimatedUptime
&& devicesInfo[jObj.name].benchmark) {
var score = devicesInfo[jObj.name].battery.estimatedUptime
* devicesInfo[jObj.name].benchmark
/ (devicesInfo[jObj.name].jobs + 1)
console.log(jObj.name + " current SEAS score: " + score);
}
}
} | [
"function parseMessage(message) {\n\tvar jObj = $.parseJSON(message);\n\n\t// if the flag is 'self' message contains the session id\n\tif (jObj.flag == 'self') {\n\n\t\tsessionId = jObj.sessionId;\n\t\tvar chatObj = $.parseJSON(jObj.chat);\n\t\tfor (var i = 0; i < chatObj.messages.length; i++) {\n\t\t\tvar from_name = 'You';\n\t\t\t// if (key.sender != null) {\n\t\t\t// from_name = jObj.name;\n\t\t\t// }\n\t\t\tvar lidate = '<li class=\"date\"><span >'\n\t\t\t\t\t+ chatObj.messages[i].date.replace('\"', '')\n\t\t\t\t\t\t\t.replace('\"', '') + '</span></li>';\n\t\t\tvar li = '<li><span class=\"name\">' + from_name + '</span> '\n\t\t\t\t\t+ chatObj.messages[i].text + '</li>';\n\n\t\t\t// appending the chat message to list\n\t\t\tappendChatMessage(lidate);\n\t\t\tappendChatMessage(li);\n\n\t\t}\n\t\t;\n\n\t} else if (jObj.flag == 'new') {\n\t\t// if the flag is 'new', a client joined the chat room\n\t\tvar new_name = 'You';\n\n\t\t// number of people online\n\t\tvar online_count = jObj.onlineCount;\n\t\tif (online_count == 1) {\n\t\t\t$('p.online_count').html(\n\t\t\t\t\t'<b>' + online_count + '</b> person online right now')\n\t\t\t\t\t.fadeIn();\n\t\t} else {\n\t\t$('p.online_count').html(\n\t\t\t\t'<b>' + online_count + '</b> people online right now')\n\t\t\t\t.fadeIn();\n\t\t}\n\t\tif (jObj.sessionId != sessionId) {\n\t\t\tnew_name = jObj.name;\n\t\t}\n\t\tvar li = '<li class=\"new\"><span class=\"name\">' + new_name.replace(\"&\", \" \") + '</span> '\n\t\t\t\t+ jObj.message + '</li>';\n\t\t$('#messages').append(li);\n\n\t\t$('#input_message').val('');\n\n\t} else if (jObj.flag == 'message') {\n\t\t// if the json flag is 'message', it means somebody sent the chat\n\t\t// message\n\n\t\tvar from_name = 'You';\n\n\t\tif (jObj.sessionId != sessionId) {\n\t\t\tfrom_name = jObj.name.replace('&', ' ');\n\t\t}\n\t\tvar jmessage = $.parseJSON(jObj.message);\n\t\tvar lidate = '<li class=\"date\"><span >'\n\t\t\t\t+ jmessage.date.replace('\"', '').replace('\"', '')\n\t\t\t\t+ '</span></li>';\n\t\tvar li = '<li><span class=\"name\">' + from_name + '</span> '\n\t\t\t\t+ jmessage.text + '</li>';\n\n\t\t// appending the chat message to list\n\t\tappendChatMessage(lidate);\n\t\tappendChatMessage(li);\n\n\t\tif (jObj.sessionId == sessionId) {\n\t\t\t$('#input_message').val('');\n\t\t}\n\n\t} else if (jObj.flag == 'exit') {\n\t\t// if the json flag is 'exit', it means somebody left the chat room\n\t\tvar li = '<li class=\"exit\"><span class=\"name red\">' + jObj.name.replace(\"&\", \" \")\n\t\t\t\t+ '</span> ' + jObj.message + '</li>';\n\n\t\tvar online_count = jObj.onlineCount;\n\t\tif (online_count == 1) {\n\t\t$('p.online_count').html(\n\t\t\t\t'<b>' + online_count + '</b> person online right now');\n\t\t} else {\n\t\t\t$('p.online_count').html(\n\t\t\t\t\t'<b>' + online_count + '</b> people online right now');\n\t\t}\n\t\tappendChatMessage(li);\n\n\t} else if (jObj.flag == \"auth\") {\n\t\tif (jObj.success == \"true\") {\n\t\t\tsetUser($.parseJSON(jObj.user));\n\t\t} else {\n\t\t\t$(\"#qrcode\").html('Unable to login');\n\t\t}\n\t\tcloseSocket();\n\t}\n}",
"function parseMessage(message) {\n\tvar jObj = $.parseJSON(message);\n\n\t// if the flag is 'self' message contains the session id\n\tif (jObj.flag == 'self') {\n\n\t\tsessionId = jObj.sessionId;\n\n\t} else if (jObj.flag == 'new') {\n\t\t// if the flag is 'new', a client joined the chat room\n\t\tvar new_name = 'You';\n\n\t\t// number of people online\n\t\tvar online_count = jObj.onlineCount;\n\n\t\t$('p.online_count').html('Hello, <span class=\"green\">' \n\t\t\t\t+ name + '</span>. <b>'\n\t\t\t\t+ online_count + '</b> people online right now')\n\t\t\t\t.fadeIn();\n\n\t\tif (jObj.sessionId != sessionId) {\n\t\t\tnew_name = jObj.name;\n\t\t}\n\n\t\tvar li = '<li class=\"new\"><span class=\"name\" style=\"color: '+jObj.color+';\">' \n\t\t\t\t+ new_name + '</span> '\n\t\t\t\t+ jObj.message + '</li>';\n\t\tappendChatMessage(li);\n\n\t} else if (jObj.flag == 'message') {\n\t\t// if the json flag is 'message', it means somebody sent the chat\n\t\t// message\n\n\t\tvar from_name = 'You';\n\n\t\tif (jObj.sessionId != sessionId) {\n\t\t\tfrom_name = jObj.name;\n\t\t}\n\n\t\tvar $messageId = new Date().getTime();\n\t\tvar li = '<li id='+$messageId+' class=\"name\" style=\"border-color: '+jObj.color+';\">'\n\t\t\t\t+ '<span class=\"name\" style=\"color: '+jObj.color+';\" rel=\"popover\">' + from_name + '</span> '\n\t\t\t\t+ '<span id=\"popover-content\" style=\"display: none;\">'\n\t\t\t\t\t+ jObj.message\n\t\t\t\t\t+ '<span class=\"timestamp\">'+jObj.time+'</span>'\n\t\t\t\t+ '</span>'\n\t\t\t\t+ '</li>';\n\n\t\t// appending the chat message to list\n\t\tappendChatMessage(li, $messageId);\n\n\t\t// notification\n\t\tnotifyMe(jObj.sessionId == sessionId, jObj);\n\n\t} else if (jObj.flag == 'exit') {\n\t\t// if the json flag is 'exit', it means somebody left the chat room\n\t\tvar li = '<li class=\"exit\"><span class=\"name red\">' \n\t\t\t\t+ jObj.name + '</span> ' \n\t\t\t\t+ jObj.message + '</li>';\n\n\t\tvar online_count = jObj.onlineCount;\n\n\t\t$('p.online_count').html(\n\t\t\t\t'Hello, <span class=\"green\">' \n\t\t\t\t+ name + '</span>. <b>'\n\t\t\t\t+ online_count + '</b> people online right now');\n\n\t\tappendChatMessage(li);\n\t}\n\trefreshChatUsers(jObj);\n}",
"function msgHandleJson(message) {\n\tvar messageObject = JSON.parse(message);\n\tvar tempChannelLabel = messageObject.label;\n\n\tswitch (messageObject.type) {\n\n\t\t// statistics\n\t\tcase 'statistics':\n\t\t\tbreak;\n\n\t\t\t// timestamp - echo timestamp to sender\n\t\tcase 'timestamp':\n\t\t\tmsgHandlePing(messageObject);\n\t\t\tbreak;\n\n\t\t\t// timestampEcho - measure RTT\n\t\tcase 'timestampEcho':\n\t\t\tmsgHandlePingEcho(messageObject);\n\t\t\tbreak;\n\n\t\tcase 'reset':\n\t\t\tmsgHandleReset();\n\t\t\tbreak;\n\n\t\t\t// trigger to collect statistics\n\t\tcase 'collectStats':\n\t\t\tstatsCollectInit(messageObject);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\talert('Unknown messagetype!!');\n\t\t\tbreak;\n\t}\n}",
"function parsePythonMessage(msg) {\n \tvar obj = JSON.parse(msg);\n \tvar _type = obj[\"type\"];\n\n\tswitch(_type) {\n\t\tcase \"progress-message\":\n\t\t\tcurrRun.statusMessage = obj[\"content\"];\n\t\t\tbreak;\n\t\tcase \"progress\":\n\t\t\tcurrRun.total = parseInt(obj[\"content\"]);\n\t\t\tbreak;\n\t} \t\n }",
"function parse (message) {\n if (isString(message)) {\n try {\n message = JSON.parse(message)\n } catch (error) {\n if (error instanceof SyntaxError) {\n throw new InvalidJson()\n }\n\n throw error\n }\n }\n\n // Properly handle array of requests.\n if (isArray(message)) {\n return map(message, parse)\n }\n\n if (message.jsonrpc !== '2.0') {\n // Use the same errors for all JSON-RPC messages (requests,\n // responses and notifications).\n throw new InvalidRequest()\n }\n\n if (isString(message.method)) {\n // Notification or request.\n\n var params = message.params\n if (\n !isUndefined(params) &&\n !isArray(params) &&\n !isObject(params)\n ) {\n throw new InvalidRequest()\n }\n\n var id = message.id\n if (isUndefined(id)) {\n setMessageType(message, 'notification')\n } else if (\n isNull(id) ||\n isNumber(id) ||\n isString(id)\n ) {\n setMessageType(message, 'request')\n } else {\n throw new InvalidRequest()\n }\n } else {\n // Response.\n\n var error\n if (!xor(\n has(message, 'result'),\n (\n has(message, 'error') &&\n isInteger((error = message.error).code) &&\n isString(error.message)\n )\n )) {\n throw new InvalidRequest()\n }\n\n setMessageType(message, 'response')\n }\n\n return message\n}",
"function parseMessage(msg) {\n // Add the message to unconsumed.\n _unconsumed += msg.toString().trim();\n // Create an array for the newly parsed commands.\n var parsedCommands = [];\n \n while (_unconsumed != '') {\n // Get the message-length to read.\n var verbStart = _unconsumed.indexOf('\\n');\n var msgLen = parseInt(_unconsumed.substr(0, verbStart));\n // Cut off the message length header from unconsumed.\n _unconsumed = _unconsumed.substr(verbStart+1);\n // Figure out how many bytes we have left to consume.\n var bytesLeft = Buffer.byteLength(_unconsumed, 'utf8');\n // Do not process anything if we do not have enough bytes.\n if (bytesLeft < msgLen) {\n break;\n }\n // Isolate the message we are actually handling.\n var unconsumedBuffer = new Buffer(_unconsumed);\n msg = unconsumedBuffer.slice(0, msgLen).toString();\n // Store remaining stuff in unconsumed.\n _unconsumed = unconsumedBuffer.slice(msgLen).toString();\n // Go process this single message.\n console.log('Got message:');\n console.log(msg);\n var type = '';\n var data = {};\n var index = msg.indexOf(' {');\n if (index >= 0) { // If a body was supplied\n type = msg.substr(0, index);\n try {\n var toParse = msg.substr(index+1);\n data = JSON.parse(toParse);\n }\n catch(err) {\n console.error('Malformed message 01');\n sendMessage(cli, \"MSG_MALFORMED \\n\" + err);\n return;\n }\n } else { // No body was supplied\n type = msg;\n }\n \n parsedCommands.push({type: type, data: data});\n }\n return parsedCommands;\n}",
"msg_handler(message){\n let msg = message.content.data;\n if(msg.type == \"ERROR\"){this.createNotification(msg.body,'error')}\n if(msg.type == \"POSTERIOR\"){this.updateNodes(msg.body,'info')}\n if(msg.type == \"LOAD_GRAPH\"){this.load_graph(msg.body,'info')}\n }",
"function parseMessage(data) {\r\n\t switch (data.topic) {\r\n\t // https://dev.twitch.tv/docs/PubSub/bits/\r\n\t case 'channel-bitsevents.' + state.id:\r\n\t bits();\r\n\t break;\r\n\t // https://discuss.dev.twitch.tv/t/in-line-broadcaster-chat-mod-logs/7281/12\r\n\t case 'chat_moderator_actions.' + state.id + '.' + state.id:\r\n\t moderation();\r\n\t break;\r\n\t default:\r\n\t break;\r\n\t }\r\n\t function bits() {\r\n\t const username = data.message.user_name;\r\n\t const note = data.message.chat_message;\r\n\t const bits = data.message.bits_used;\r\n\t const totalBits = data.message.total_bits_used;\r\n\t _event('bits', {username, note, bits, totalBits});\r\n\t }\r\n\t function moderation() {\r\n\t const action = data.message.moderation_action;\r\n\t const username = data.message.created_by;\r\n\t const args = data.message.args;\r\n\t _event('moderation', {username, action, args});\r\n\t }\r\n\t }",
"parseObject(message, type) {\n const t = new type();\n let trimmed = message;\n if (trimmed.startsWith(\"@\")) {\n trimmed = trimmed.substring(1); // shift @\n }\n // sample data\n // @broadcaster-lang=;emote-only=0;followers-only=-1;mercury=0;r9k=0;rituals=0;\n // room-id=134286305;slow=0;subs-only=0\n if (trimmed.indexOf(\":tmi\") > -1) {\n trimmed = trimmed.substring(0, trimmed.indexOf(\":tmi\") - 1); // do not include tmi.twitch.tv\n }\n const splitted = trimmed.split(\";\"); // split at ';'\n splitted.forEach((element) => {\n const pair = this.getPair(element); // get pair\n const key = convertCase(pair[0]);\n if (typeof t[key] === \"boolean\") {\n t[key] = Boolean(pair[1]);\n }\n else if (typeof t[key] === \"number\") {\n t[key] = parseInt(pair[1], 10);\n }\n else {\n t[key] = pair[1];\n }\n });\n return t;\n }",
"function process_message(message) {\n\tvar json = JSON.parse(message.data);\n\tconsole.log(json);\n\t\n\tswitch(json.response) {\n\t\tcase \"FetchUserSettings\":\n\t\t\twindow.user_json = json.settings;\n\t\t\tbreak;\n\t\tcase \"FetchWashingProgram\":\n\t\t\twindow.page_json = json.programs;\n\t\t\tconsole.log(window.page_json);\n\t\t\tpopulate_wasprogrammas();\n\t\t\tbreak;\n\t\tcase \"UpdateAvailable\":\n\t\t\t\n\t\t\tbreak;\n\t\tcase \"UpdateUser\":\n\t\t\tconsole.log(\"User settings are saved\");\n\t\t\tbreak;\n\t\tcase \"StartWashingProgram\":\n\t\tcase \"StopWashingProgram\":\n\t\t\t// Change state\n\t\t\tjson = {\"request\" : \"Status\"};\n\t\t\twindow.socket.send(JSON.stringify(json));\n\t\t\tbreak;\n\t\tcase \"Status\":\n\t\t\tif (json.status) {\n\t\t\t\tstate.innerHTML = \"Er is momenteel een wastaak bezig\";\n\n\t\t\t\ttime.innerHTML = json.time.toHHMMSS();\n\t\t\t\ttemp.innerHTML = json.temp + \"°C\";\n\t\t\t} else {\n\t\t\t\tstate.innerHTML = \"Er is momenteel geen wastaak bezig\";\n\n\t\t\t\ttime.innerHTML = \"00:00:00\";\n\t\t\t\ttemp.innerHTML = \"0°C\";\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault: \n\t\t\tconsole.log(\"Warning: Unknown message received: \" + message);\n\t\t\tbreak;\n\t}\n}",
"function parseMessage(data) {\n switch (data.topic) {\n // https://dev.twitch.tv/docs/v5/guides/PubSub/\n case 'channel-bits-events-v1.' + state.channel_id:\n bits();\n break;\n // https://discuss.dev.twitch.tv/t/in-line-broadcaster-chat-mod-logs/7281/12\n case 'chat_moderator_actions.' + state.id + '.' + state.id:\n moderation();\n break;\n case 'whispers.' + state.id:\n whisper();\n break;\n // case 'channel-subscribe-events-v1.' + state.channel_id:\n // sub();\n // break;\n default:\n break;\n }\n\n function bits() {\n let bits = JSON.parse(data.message);\n _event('bits', bits);\n }\n\n function moderation() {\n let moderation = JSON.parse(data.message).data;\n _event('moderation', moderation);\n }\n\n function whisper() {\n let message = JSON.parse(data.message).data_object;\n // TODO: figure out why some whispers are dropped...\n // _event('whisper', message);\n }\n\n // function sub() {\n // // TODO: https://discuss.dev.twitch.tv/t/subscriptions-beta-changes/10023\n // }\n\n }",
"function _parse(message) {\n //Message content which will be logged into browser console\n var messageInfo = \"IDE \";\n\n //Iterate through all the message attributes\n for (var key in message) {\n\n //Get attribute\n var value = message[key];\n\n //Apend attribute name and its value\n messageInfo += \"| \" + key + \": \" + value + \" \";\n }\n\n //Add the message info into browser console\n console.log(messageInfo);\n }",
"function process( messages ) {\n\t\n\tif ( typeof messages === 'string' ) {\n\t\tvar content = require( 'fs' ).readFileSync( messages );\n\t\t// replace inline comments\n\t\tcontent = content.replace( /\\/\\/.*$/g, '' );\n\t\t// replace multiline comments\n\t\tcontent = content.replace( /\\/\\*.*\\*\\//g, '' );\n\t\tconsole.log( 'file read: ' + messages );\n\t\tconsole.log( content );\n\t\t// transform to object\n\t\tmessages = JSON.parse( content );\n\t}\n\t\n\t\n\tObject.keys( messages ).forEach( function (messageName) {\n\t\tvar message = messages[ messageName ];\n\t\t\n\t\tObject.keys( message ).forEach( function ( num ) {\n\t\t\t\n\t\t\t// match a number \n\t\t\tif( /^\\d+$/.test( num ) ) {\n\t\t\t\tvar parsed = message[num].split( /\\s+/);\n\t\t\t\tvar packed = /\\[\\s*packed\\s*=\\s*true\\s*\\]/.test( message[num] );\n\t\t\t\tif ( parsed.length !== 3 ) {\n\t\t\t\t\tthrow new Error( 'invalid field defiintion. Message: ' + messageName + ' field: ' + num );\t\n\t\t\t\t}\n\t\t\t\t// the key is the field number\n\t\t\t\tmessage[num] = parseField( parsed );\n\t\t\t\tmessage[num].packed = packed;\n\t\t\t\tvar name = parsed[2];\n\t\t\t\t// the key is the field name\n\t\t\t\tmessage[ name ] = parseField( parsed );\n\t\t\t\tmessage[ name ].num = num;\n\t\t\t\tmessage[ name ].packed = packed;\n\t\t\t\tdelete message[ name ].name;\n\t\t\t\t\n\t\t\t} else if ( num === '_enums') {\n\t\t\t\t// reverse key -> value \n\t\t\t\tObject.keys( message[num] ).forEach( function (enumName) {\n\t\t\t\t\tvar enume = message[num][enumName];\n\t\t\t\t\tObject.keys( enume ).forEach( function (k) {\n\t\t\t\t\t\tvar v = enume[k];\n\t\t\t\t\t\tenume[v] = k;\n\t\t\t\t\t} );\n\t\t\t\t\t\n\t\t\t\t} );\n\t\t\t}\n\t\t\t\n\t\t} );\n\t} );\n\t\t\n}",
"function parseMessage(msg = '', typeMatch) {\n\n let p = msg.indexOf(':'), type = '', data = '';\n\n if (p > 0 && p < msg.length) {\n type = msg.slice(0, p);\n\n if (!typeMatch || type === typeMatch) {\n\n try { data = JSON.parse(msg.slice(p+1)); }\n catch (e) { console.log(e, msg); }\n\n }\n }\n\n return { type, data };\n\n}",
"function parseMessages(jsonStr){\n\tvar obj = JSON.parse(jsonStr);\n\treturn obj;\n}",
"function parse(message)\n {\n //Message content which will be logged into browser console\n var messageInfo = \"IDE \";\n\n //Iterate through all the message attributes\n for(var key in message) {\n\n //Get attribute\n var value = message[key];\n\n //Apend attribute name and its value\n messageInfo += \"| \" + key + \": \" + value + \" \";\n }\n\n //Add the message info into browser console\n console.log(messageInfo);\n }",
"function parseJson(jsonMessage, requestType) {\n try {\n return JSON.parse(jsonMessage);\n } catch (ex) {\n console.log(\"ERROR: parsing JSON message of type \" + requestType + \": \", jsonMessage);\n }\n}",
"receive_message(message) {\n message.event = message.event || \"\";\n switch (message.event) {\n case \"webRequest\":\n addRequest(message);\n break;\n case \"webNavigation\":\n addNavigation(message);\n break;\n case \"settings\":\n loadSettings(message.data, true);\n break;\n default:\n this.send_message(\"Unknown message type\", message);\n break;\n }\n }",
"static decode(message) {\n return JSON.parse(message.toString());\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resets the signal level and frequency to their default values. | function reset() {
signalLevel = 1;
signalFrequency = 1000;
} | [
"function reset() {\n vm.level = 1;\n vm.frequency = 1000;\n }",
"function reset_signal() {\n if (sigselected !== '' && mag[sigselected] !== 1) {\n\tmag[sigselected] = 1.1;\n\tshow_plot();\n }\n}",
"function resetFrequencies() {\n angular.forEach(chart.frequencies, function(frequency) {\n frequency.active = false;\n });\n }",
"function reset() {\n\t\tsounds = genNotes();\n\t\t$('#level').text(\"Level: 0\");\n\t\tplayerSounds = [];\n\t\tstep = 0;\n\t\tlevel = 0;\n\t}",
"function setFrequency() {\n radio.frequency = (radio.range.low + radio.range.high)/2;\n}",
"function setFrequency() {\n radio.frequency=(radio.range.low + radio.range.high) / 2;\n}",
"reset() {\n for (const sensor of this.activeSensors_.values()) {\n sensor.reset();\n }\n this.activeSensors_.clear();\n this.resolveFuncs_.clear();\n this.getSensorShouldFail_.clear();\n this.permissionsDenied_.clear();\n this.maxFrequency_ = 60;\n this.minFrequency_ = 1;\n this.receiver_.$.close();\n this.interceptor_.stop();\n }",
"function reset() {\n\t\tfor (let key in defaultValues) {\n\t\t\tsetSetting(key, getDefaultValue(key));\n\t\t}\n\t}",
"function reset() {\r\n\t\tfor (let key in defaultValues) {\r\n\t\t\tsetSetting(key, getDefaultValue(key));\r\n\t\t}\r\n\t}",
"reset(){\n \t\tthis.channel=1;\n \t\tthis.volume=50;\n \t}",
"function reset() {\n time = 0.0;\n totalT = 0.0;\n totalP = 0.0;\n sampleCount = 0;\n lastSampleTime = 0.0;\n lastAutoRecordTime = 0.0;\n showStats();\n}",
"function reset() {\n t = 0;\n d = 0;\n start = 1; // So that refreshWave() will stop it no matter what\n refreshWave(); // Stop the wave\n\n // Reset parameters\n document.getElementById('amp1').value = document.getElementById('amp2').value = 50;\n document.getElementById('prd1').value = document.getElementById('prd2').value = 1;\n document.getElementById('vel').value = 150;\n document.getElementById('fun').selectedIndex = 0;\n fun = sin;\n\n clrscr();\n initscr();\n calcWaves(1,150);\n drawWave();\n}",
"function setFrequency(){\n radio.frequency = (radio.range.low + radio.range.high)/2\n}",
"function reset() {\n settings = _UtilsJs2['default'].clone(defaultSettings);\n }",
"function reset$1() {\n mergeOptions(globalOptions, defaultOptions);\n}",
"function resetOptionsToDefault(){\n\n\tupdateFormOptions(defaultOptions);\n}",
"reset() {\n this.setDefaults();\n }",
"resetSilentRecordingCount(state) {\n state.recState.silentRecordingCount = 0;\n }",
"function gml_Script_SS_SetSoundFreq(_inst, _other) {\n return 0;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return all asset names in the AssetBundle. | GetAllAssetNames() {} | [
"get assetNames() {}",
"get assetBundleName() {}",
"function getAssetNames (patterns = []) {\n let matched = []\n patterns.forEach(pattern => {\n matched = glob.readdirSync(pattern)\n })\n return matched.map(file => path.basename(file))\n}",
"function getAllAssets(){\n //get all assets\n ModulesService.getAllModuleDocs('assets').then(function(assets){ \n //store to array\n $scope.assets = assets;\n })\n .catch(function(error){\n FlashService.Error(error);\n }).finally(function() {\n\t\t\t\t$scope.loading = false;\n\t\t\t});\n }",
"function getAssetList() {\r\n let url = API_URL + 'assets/' + '?key=' + API_KEY;\r\n return fetchAssets(url);\r\n}",
"assetsInStage(stage) {\n const assets = new Map();\n for (const stack of stage.stacks) {\n for (const asset of stack.assets) {\n assets.set(asset.assetSelector, asset);\n }\n }\n return Array.from(assets.values());\n }",
"function getAssets() { return _assets; }",
"getAssetFiles (assets) {\n const files = _.uniq(Object.keys(assets).filter(assetType => assetType !== 'chunks' && assets[assetType]).reduce((files, assetType) => files.concat(assets[assetType]), []));\n files.sort();\n return files;\n }",
"static get assetGUIDs() {}",
"function listAllAssetPacks() {\n return Object.keys(setup.AssetPacks || {});\n}",
"get Assets() {}",
"LoadAllAssets() {}",
"set assetBundleName(value) {}",
"names() {\n if (!validateIfDestroyed(context) || !validateIfReady(context, 'names')) {\n return [];\n }\n return splits.getKeys();\n }",
"getAssetFiles(assets) {\n const files = _.uniq(Object.keys(assets).filter(assetType => assetType !== 'chunks' && assets[assetType])\n .reduce((files, assetType) => {\n if (['entryId', 'entryFile'].includes(assetType)) return files;\n let asset = assets[assetType];\n return files.concat(Array.isArray(asset) ? asset.map(v => v.file || '') : asset);\n }, []));\n files.sort();\n return files;\n }",
"all() {\n let names = [];\n util.each(sizes, name => {\n names.push(name);\n });\n return names;\n }",
"function getTagNames() {\n return currentTags.getTags().map(tag => tag.getTag());\n }",
"function FnGetAssetsList(){\n\t\tvar VarUrl = GblAppContextPath+'/ajax' + VarListAssetsUrl;\n\t\tvar VarMainParam = {\n\t\t\t\"domain\": {\n\t\t\t\t\"domainName\": VarCurrentTenantInfo.tenantDomain\n\t\t\t},\t\"entityTemplate\": {\n\t\t\t\t\"entityTemplateName\": \"Asset\"\n\t\t\t}\n\t\t};\n\t\t//FnMakeAsyncAjaxRequest(VarUrl, 'POST', JSON.stringify(VarMainParam), 'application/json; charset=utf-8', 'json', FnResAssetList);\n\t\tFnMakeAsyncAjaxRequest(VarUrl, 'POST', JSON.stringify(VarMainParam), 'application/json; charset=utf-8', 'json', FnResAssetList);\n\t}",
"function collectScriptNames() {\n var scripts = document.querySelectorAll('script[type=\"text/javascript\"]');\n var result = [];\n for (var i = 0; i < scripts.length; i++) {\n var script = scripts[i];\n var testName = script.dataset[\"tests\"];\n var src = script.getAttribute(\"src\");\n var regex = /\\.(\\S+)$/;\n\n if (src)\n result.push(src);\n\n if (!testName && src && src.match(regex)) {\n testName = src.replace(regex, \".test.$1\");\n }\n if (testName)\n result.push(testName);\n }\n return result;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
'project link' command implementation. Creates a new project in the current directory by linking it to the specified Device Group. If the specified Device Group does not exist, a user is informed and the operation is stopped. Parameters: options : Options impt options of 'project link' command Returns: Nothing | link(options) {
this._checkExistingProject(options, this._link.bind(this)).
then(() => this._info()).
then(info => {
UserInteractor.printInfo(UserInteractor.MESSAGES.PROJECT_LINKED);
UserInteractor.printResultWithStatus(info);
}).
catch(error => UserInteractor.processError(error));
} | [
"_link(options) {\n return this._initDeviceGroup(options).\n then(() => this._linkToDeviceGroup()).\n then(() => this._processSourceFiles(options)).\n then(() => {\n this._projectConfig.endpoint = this._helper.authConfig.endpoint;\n if(options && options.account) {\n this._projectConfig.accountID = options.account;\n } else {\n this._projectConfig.accountID = this._helper.authConfig.accountID;\n }\n\n if(options[UserInteractor.CHOICE] === 1) {\n var configJSON = this._projectConfig.getJSON();\n if(configJSON) {\n for (var deviceGroup in configJSON[\"deviceGroups\"]) {\n if(configJSON[\"deviceGroups\"][deviceGroup].isDefault){\n delete configJSON[\"deviceGroups\"][deviceGroup].isDefault;\n }\n }\n }\n this._projectConfig.isDefault = true;\n }\n this._saveProjectConfig()\n });\n }",
"_create(options) {\n return this._findOrCreateProduct(options).\n then(() => this._createDeviceGroup(options)).\n then(() => this._processSourceFiles(options)).\n then(() => {\n this._projectConfig.endpoint = this._helper.authConfig.endpoint;\n if(options && options.account) {\n this._projectConfig.accountID = options.account;\n } else {\n this._projectConfig.accountID = this._helper.authConfig.accountID;\n }\n\n if(options[UserInteractor.CHOICE] === 1) {\n var configJSON = this._projectConfig.getJSON();\n if(configJSON) {\n for (var deviceGroup in configJSON[\"deviceGroups\"]) {\n if(configJSON[\"deviceGroups\"][deviceGroup].isDefault){\n delete configJSON[\"deviceGroups\"][deviceGroup].isDefault;\n }\n }\n }\n this._projectConfig.isDefault = true;\n }\n this._saveProjectConfig()\n });\n }",
"_linkToDeviceGroup() {\n if (this._deviceGroup.type === DeviceGroups.TYPE_DEVELOPMENT ||\n this._deviceGroup.type === DeviceGroups.TYPE_PRE_FACTORY_FIXTURE) {\n this._projectConfig.deviceGroupId = this._deviceGroup.id;\n return Promise.resolve();\n }\n else {\n return Promise.reject(new Errors.ImptError(\n UserInteractor.ERRORS.PROJECT_LINK_WRONG_DG_TYPE,\n Options.getDeviceGroupTypeName(this._deviceGroup.type),\n Options.getDeviceGroupTypeName(DeviceGroups.TYPE_DEVELOPMENT),\n Options.getDeviceGroupTypeName(DeviceGroups.TYPE_PRE_FACTORY_FIXTURE)));\n }\n }",
"run(options) {\n if(options.all) {\n const deviceGroups = this._projectConfig.getJSON()[\"deviceGroups\"];\n for (var deviceGroup in deviceGroups) {\n Shell.exec(`impt build run --ac ${deviceGroups[deviceGroup][\"accountID\"]} --dg ${deviceGroup}`)\n }\n } else {\n const deviceGroup = new DeviceGroup(options);\n this._deploy(options).\n then(() => {\n return deviceGroup._restart(options);\n }).\n then(() => {\n if (options.log && deviceGroup._assignedDevices && deviceGroup._assignedDevices.length > 0) {\n UserInteractor.printInfo(UserInteractor.MESSAGES.BUILD_RUN, this.identifierInfo);\n new Log()._stream(deviceGroup._assignedDevices);\n }\n else {\n UserInteractor.printResultWithStatus();\n }\n }).\n catch(error => UserInteractor.processError(error));\n }\n }",
"function initProject(options) {\r\n // var connection = new\r\n // JSCR.Implementation.Memory.WorkspaceConnection(options);\r\n var connection = new JSCR.Implementation.Git.WorkspaceConnection(options);\r\n return connection.connect()\r\n // Create a project\r\n .then(function(workspace) {\r\n return workspace.loadProject(options.name, {\r\n create : true\r\n });\r\n })\r\n}",
"function compileProject(options){\n\n//The 'compileProject' function will load and compile the main Module of a project.\n//The compilation of the main module will trigger import and compilation of all its \"child\" modules\n//(dependency tree is constructed by `import`/`require` between modules)\n\n//The main module is the root of the module dependency tree, and can reference\n//another modules via import|require.\n\n//Create a 'Project' to hold the main module and dependant modules\n\n //#since \"options\" come from a external source, it can be anything\n //options = prepareOptions(options)\n options = prepareOptions(options);\n\n //console.time 'Total Compile Project'\n console.time('Total Compile Project');\n\n //var project = new Project(options)\n var project = new Project(options);\n\n //project.compile\n project.compile();\n\n //if options.perf\n if (options.perf) {\n \n //console.timeEnd 'Total Compile Project'\n console.timeEnd('Total Compile Project');\n };\n\n //return project\n return project;\n }",
"create(options) {\n this._checkExistingProject(options, this._create.bind(this)).\n then(() => this._info()).\n then(info => {\n UserInteractor.printInfo(UserInteractor.MESSAGES.ENTITY_CREATED, this.entityType);\n UserInteractor.printResultWithStatus(info);\n }).\n catch(error => UserInteractor.processError(error));\n }",
"deploy(options) {\n if(options.all) {\n const deviceGroups = this._projectConfig.getJSON()[\"deviceGroups\"];\n for (var deviceGroup in deviceGroups) {\n Shell.exec(`impt build deploy --ac ${deviceGroups[deviceGroup][\"accountID\"]} --dg ${deviceGroup}`)\n }\n } else {\n this._deploy(options).\n then(() => this._collectShortListData()).\n then(() => UserInteractor.printResultWithStatus(this._displayData)).\n catch(error => UserInteractor.processError(error));\n }\n }",
"static createHardLink(options) {\n FileSystem._wrapException(() => {\n return FileSystem._handleLink(() => {\n return fsx.linkSync(options.linkTargetPath, options.newLinkPath);\n }, Object.assign(Object.assign({}, options), { linkTargetMustExist: true }));\n });\n }",
"constructor() { \n \n ProjectGroupLink.initialize(this);\n }",
"function linkCommandToProj(command_id, project_id) {\n return db(\"command_cat\").insert({ command_id, project_id });\n}",
"function newProject () {\n ADX.getTemplateList('adc', function (err, adcTemplates) {\n if (err) throw err;\n ADX.getTemplateList('adp', function (err, adpTemplates) {\n if (err) throw err;\n showModalDialog({\n type : 'newADXProject',\n buttonText : {\n ok : 'Create project'\n },\n adcTemplates : adcTemplates,\n adpTemplates : adpTemplates,\n defaultRootDir : app.getPath('documents')\n }, 'main-create-new-project');\n });\n });\n}",
"async link() {\n this._createOutputDirectory(this.binaryDirectory);\n let linkCommand = null;\n if (this.buildOutput === 'executable') {\n linkCommand = this.compilerProfile.executableLinkCommand(\n this.objectFiles,\n this.target,\n {\n libraryPaths: this.libraryPaths,\n linkLibraryFlags: this.linkLibraryFlags\n }\n );\n } else if (this.buildOutput === 'shared-library') {\n linkCommand = this.compilerProfile.dynamicLinkCommand(\n this.objectFiles,\n this.target,\n {\n libraryPaths: this.libraryPaths,\n linkLibraryFlags: this.linkLibraryFlags\n }\n );\n } else if (this.buildOutput === 'static-library') {\n linkCommand = this.compilerProfile.staticLinkCommand(\n this.objectFiles,\n this.target\n );\n } else {\n throw new Error(\n `Invalid build output for project '${this.projectName}'!`\n );\n }\n\n await spawn(linkCommand.program, linkCommand.args);\n }",
"function setCreateNewProjectDialog() {\n dialog\n .onDirIconMouseup()\n .onDirIconDblClick()\n .onChangeAddress()\n .onClickCancel()\n .onClickOK(function (inputTextElement) {\n var dirname = inputTextElement.val().trim();\n if (!dirname || !ClientUtility.isValidDirectoryName(dirname)) {\n inputTextElement.borderInvalid();\n return;\n }\n var directoryPath = \"\" + dialog.getLastSelectDirectory() + dirname;\n createNewProjectSocket.emit(directoryPath, function (rootFilePath) {\n if (!rootFilePath) {\n inputTextElement.borderInvalid();\n return;\n }\n else {\n ClientUtility.moveWorkflowLink(rootFilePath);\n }\n });\n });\n }",
"function createNewProject() {\r\n\tvar requestData = '{'\r\n\t\t\t+ '\"command\" : \"createProject\",'\r\n\t\t\t+ '\"arguments\" : {'\r\n\t\t\t+ '\"project\" : \"' + $('#new-project-name').val() + '\"'\r\n\t\t\t+ '}'\r\n\t\t\t+ '}';\r\n\tmakeAsynchronousPostRequest(requestData, refresh, null);\t// Defined in \"/olive/scripts/master.js\".\r\n}",
"function onClickNewProject(e) {\r\n window.pmApi.createProject();\r\n console.log(\"project created...\");\r\n displayProjects();\r\n}",
"_initDeviceGroup(options, isInfo = false) {\n this._deviceGroup = new DeviceGroup(options);\n return this._deviceGroup.getEntity(isInfo);\n }",
"function createProject() {\n var tempProjectName = new_project_name_input.val().toString();\n var tempProjectConsole;\n\n switch (console_select.selectedIndex) {\n case 1:\n tempProjectConsole = consoleList[0];\n break;\n default:\n console.error(\"What how did you get here? No console is selected.\")\n break;\n }\n\n var tempProject = new project(tempProjectName, tempProjectConsole);\n console.log(tempProject);\n closeHeader();\n workingProject = tempProject;\n workingDirectory = null;\n addColorPalette();\n trifold_holder.css(\"pointerEvents\", \"all\");\n console.log(workingProject);\n}",
"function createProject() {\n const projectName = app.getArgument('projectName');\n app.askForConfirmation(`Are you sure you want to create a project with the name ${projectName}?`);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hardhat env set up | function hardhatSetupEnv(mocha) {
const mockwd = path.join(process.cwd(), temp);
previousCWD = process.cwd();
process.chdir(mockwd);
mocha.env = require("hardhat");
mocha.env.config.logger = testLogger
mocha.logger = testLogger
} | [
"setupEnvironment() {}",
"function setupEnvironments() {\n console.log();\n setupEnvironment(repositories = Object.keys(repos), function() {\n console.log(\"setting AWS credentials.\");\n setupAWS(repositories = Object.keys(repos), function() {\n console.log(\"\\nInstallation complete.\");\n progressive.finish();\n process.exit(0);\n });\n });\n }",
"function hardhatTearDownEnv() {\n resetHardhatContext();\n process.chdir(previousCWD); // remove?\n}",
"static setupEnvVariables() {\n console.error('Start setup');\n if (envVal === ENV_TYPE.LOCAL_AGAINST_REMOTE) {\n process.env.HOSTNAME = process.env.GEN3_COMMONS_HOSTNAME;\n } else if (envVal === ENV_TYPE.JENKINS || envVal === ENV_TYPE.LOCAL_AGAINST_GEN3_K8S) {\n process.env.HOSTNAME = process.env.GEN3_COMMONS_HOSTNAME || `${Env.getSubDomain()}.planx-pla.net`;\n console.error(`NAMESPACE: ${process.env.NAMESPACE}`);\n } else {\n process.env.HOSTNAME = 'localhost';\n }\n console.error(`HOSTNAME: ${process.env.HOSTNAME}`);\n }",
"function setup (t) {\n if (existsSync(tmp)) rmSync(tmp, { recursive: true, force: true, maxRetries: 10 })\n mkdirSync(tmp, { recursive: true })\n t.ok(existsSync(tmp), 'Created tmp dir')\n process.env.ARC_ENV = 'testing'\n process.env.ARC_SANDBOX = JSON.stringify({ ports: { events: eventsPort }, version: '5.0.0' })\n}",
"async function setupAllRubyEnvironments() {\n core.startGroup(\"Setup for all Ruby Environments\")\n\n // http://blog.headius.com/2019/09/jruby-startup-time-exploration.html\n core.exportVariable('JRUBY_OPTS', '--dev')\n\n core.endGroup()\n}",
"function initEnvironment() {\n console.log('Creating environment...');\n return new Promise(function(resolve, reject) {\n copyDir.sync(process.cwd(), './tmp');\n try {\n process.chdir('./tmp');\n resolve();\n }\n catch (err) {\n reject();\n }\n });\n}",
"setupEnvironment () {\n // FIXME: Ignore this until embeddable python is figured out\n app.emit('python-env-ready')\n return\n // const hasPythonEnvironment = fs.existsSync(this.getVersionFilePath())\n // const isSameVersion = this.getEnvVersionTag() === app.getVersion()\n // if (!hasPythonEnvironment || !isSameVersion) {\n // console.log('Updating app python environment')\n // this.copyAndDecompressEnvironment(\n // this.getPackedEnvPath(),\n // this.getEnvAppDataDirPath()\n // )\n // this.writeEnvVersionTag()\n // } else {\n // app.emit('python-env-ready')\n // }\n }",
"configureDevelopment () {}",
"function setupEnvironment() {\n if (typeof child.execSync !== 'function') {\n console.log('ERROR: node v0.12 is required.');\n return process.exit(-1);\n }\n\n if (!process.env.HOME || !process.env.NODE_PATH) {\n console.log('==================================================');\n console.log('ERROR: Expected variables missing from ENV.');\n console.log('HOME [%s] and NODE_PATH [%s] were expected.', process.env.HOME, process.env.NODE_PATH);\n console.log('==================================================');\n return process.exit(-1);\n }\n \n var magicDir = process.env.HOME + '/.node-anywhere';\n\n if (!fs.existsSync(magicDir)) {\n fs.mkdirSync(magicDir);\n }\n\n if (!fs.existsSync(magicDir + '/node_modules')) {\n fs.mkdirSync(magicDir + '/node_modules');\n }\n\n try {\n fs.accessSync(magicDir + '/node_modules');\n } catch(e) {\n console.log('==================================================');\n console.log('ERROR: node-anywhere does not have permission to write to its module cache (%s)', magicDir);\n console.log('Error Message Thrown:', e);\n console.log('==================================================');\n return process.exit(-1);\n }\n\n return magicDir;\n}",
"async runAppSetup () {\n return Execa('node', ['craft', 'setup', `--name=${this.appName}`], {\n stdin: 'inherit',\n stdout: 'inherit',\n cwd: this.appPath\n })\n }",
"function setEnv(env){\n if (env === \"dev\"){\n plug.environments.current(dev);\n } else if (env === \"dist\"){\n plug.environments.current(dist);\n }\n}",
"async function prepareAppFixture() {\n await cloneDirectory(path.join(__dirname, 'app'), exports.INTEG_TEST_DIR);\n await shell(['npm', 'install',\n '@aws-cdk/core',\n '@aws-cdk/aws-sns',\n '@aws-cdk/aws-iam',\n '@aws-cdk/aws-lambda',\n '@aws-cdk/aws-ssm',\n '@aws-cdk/aws-ecr-assets',\n '@aws-cdk/aws-cloudformation',\n '@aws-cdk/aws-ec2'], {\n cwd: exports.INTEG_TEST_DIR,\n });\n}",
"function buildHardhat() {\n // cd into packages/hardhat-core\n shell.cd(hardhatCoreDir);\n\n // build and pack the project\n if (isYarn) {\n shell.exec(\"yarn build\");\n shell.exec(\"yarn pack\");\n } else {\n shell.exec(\"npm run build\");\n shell.exec(\"npm pack\");\n }\n\n // get the path to the tgz file\n const { version } = fsExtra.readJsonSync(\n path.join(hardhatCoreDir, \"package.json\")\n );\n\n let hardhatPackageName;\n if (isYarn) {\n hardhatPackageName = `hardhat-v${version}.tgz`;\n } else {\n hardhatPackageName = `hardhat-${version}.tgz`;\n }\n\n // We rename the tgz file to a unique name because apparently yarn uses the\n // path to a tgz to cache it, but we don't want it to ever be cached when we\n // are working on the e2e tests locally.\n //\n // To err on the side of safety, we always do this, even if it's only needed\n // for yarn.\n const newHardhatPackageName = `hardhat-${Date.now()}.tgz`;\n shell.mv(\n path.join(hardhatCoreDir, hardhatPackageName),\n path.join(hardhatCoreDir, newHardhatPackageName)\n );\n\n return path.join(hardhatCoreDir, newHardhatPackageName);\n}",
"setEnvironment() {\n // load project package.js\n const projectPath = path.dirname(require.main.filename);\n const PROJECT_PACKAGE = require(projectPath + `/package.json`);\n // each package in the mono repo has the same version\n const MODULE_PACKAGE = require(`../package.json`);\n // update ENV\n this.ENVIRONMENT.frameworkVersion = MODULE_PACKAGE.version;\n this.ENVIRONMENT.NODE_ENV = process.env.NODE_ENV;\n this.ENVIRONMENT.name = PROJECT_PACKAGE.name;\n this.ENVIRONMENT.version = PROJECT_PACKAGE.version;\n this.ENVIRONMENT.path = projectPath;\n // unique instance ID (6 char)\n this.ENVIRONMENT.nodeId = crypto_1.randomBytes(20).toString('hex').substr(5, 6);\n // wait until core config is set\n if (this.config.core != null) {\n this.ENVIRONMENT.namespace = this.config.core.namespace;\n }\n // wait until server config is set\n if (this.config.server != null) {\n this.ENVIRONMENT.port = this.config.server.port;\n }\n // put config into DI\n di_1.Container.set('ENVIRONMENT', this.ENVIRONMENT);\n }",
"function setup(){\n var defaults = JSON.stringify( require('pelias-config').defaults, null, 2 );\n fs.writeFileSync('/tmp/tmpPelias.json', defaults, { encoding: 'utf8' });\n process.env.PELIAS_CONFIG = '/tmp/tmpPelias.json';\n}",
"function lisp_make_kernel_env() {\n var env = lisp_make_env(null);\n /* Basics */\n lisp_export(env, \"$vau\", lisp_make_instance(Lisp_Vau));\n lisp_export(env, \"$begin\", lisp_make_instance(Lisp_Begin));\n lisp_export(env, \"$define!\", lisp_make_instance(Lisp_Define));\n lisp_export(env, \"$set!\", lisp_make_instance(Lisp_Set));\n lisp_export(env, \"$if\", lisp_make_instance(Lisp_If));\n lisp_export(env, \"$loop\", lisp_make_instance(Lisp_Loop));\n lisp_export(env, \"$unwind-protect\", lisp_make_instance(Lisp_Unwind_Protect));\n lisp_export(env, \"$js-try\", lisp_make_instance(Lisp_JS_Try));\n lisp_export(env, \"js-throw\", lisp_make_wrapped_native(lisp_lib_throw, 1, 1));\n lisp_export(env, \"eq?\", lisp_make_wrapped_native(lisp_lib_eq, 2, 2));\n lisp_export(env, \"make-environment\", lisp_make_wrapped_native(lisp_lib_make_env, 0, 1));\n lisp_export(env, \"eval\", lisp_make_wrapped_native(lisp_eval, 2, 2));\n lisp_export(env, \"wrap\", lisp_make_wrapped_native(lisp_wrap, 1, 1));\n lisp_export(env, \"unwrap\", lisp_make_wrapped_native(lisp_unwrap, 1, 1));\n lisp_export(env, \"cons\", lisp_make_wrapped_native(lisp_cons, 2, 2));\n lisp_export(env, \"car\", lisp_make_wrapped_native(lisp_car, 1, 1));\n lisp_export(env, \"cdr\", lisp_make_wrapped_native(lisp_cdr, 1, 1));\n lisp_export(env, \"null?\", lisp_make_wrapped_native(lisp_lib_null, 1, 1));\n lisp_export(env, \"intern\", lisp_make_wrapped_native(lisp_intern, 1, 1));\n lisp_export(env, \"symbol-name\", lisp_make_wrapped_native(lisp_symbol_name, 1, 1));\n lisp_export(env, \"#t\", lisp_t);\n lisp_export(env, \"#f\", lisp_f);\n lisp_export(env, \"#ignore\", lisp_ignore);\n lisp_export(env, \"#void\", lisp_void);\n /* Objects */\n lisp_export(env, \"make-class\", lisp_make_wrapped_native(lisp_lib_make_class, 2, 2));\n lisp_export(env, \"add-superclass!\", lisp_make_wrapped_native(lisp_add_superclass, 2, 2));\n lisp_export(env, \"make-instance\", lisp_make_wrapped_native(lisp_make_instance, 1, 1));\n lisp_export(env, \"class-of\", lisp_make_wrapped_native(lisp_class_of, 1, 1));\n lisp_export(env, \"superclasses-of\", lisp_make_wrapped_native(lisp_lib_superclasses_of, 1, 1));\n lisp_export(env, \"instance?\", lisp_make_wrapped_native(lisp_is_instance, 2, 2));\n lisp_export(env, \"subclass?\", lisp_make_wrapped_native(lisp_is_subclass, 2, 2));\n lisp_export(env, \"get-slot\", lisp_make_wrapped_native(lisp_lib_get_slot, 2, 2));\n lisp_export(env, \"has-slot?\", lisp_make_wrapped_native(lisp_lib_has_slot, 2, 2));\n lisp_export(env, \"set-slot!\", lisp_make_wrapped_native(lisp_lib_set_slot, 3, 3));\n lisp_export(env, \"slot-names\", lisp_make_wrapped_native(lisp_lib_slot_names, 1, 1));\n lisp_export(env, \"put-method!\", lisp_make_wrapped_native(lisp_lib_put_method, 3, 3));\n lisp_export(env, \"send\", lisp_make_wrapped_native(lisp_lib_send, 3, 3));\n /* Classes */\n lisp_export(env, \"Object\", Lisp_Object);\n lisp_export(env, \"User-Object\", Lisp_User_Object);\n lisp_export(env, \"Class\", Lisp_Class);\n lisp_export(env, \"Environment\", Lisp_Env);\n lisp_export(env, \"Symbol\", Lisp_Symbol);\n lisp_export(env, \"Pair\", Lisp_Pair);\n lisp_export(env, \"Nil\", Lisp_Nil);\n lisp_export(env, \"Array\", Lisp_Array);\n lisp_export(env, \"String\", Lisp_String);\n lisp_export(env, \"Number\", Lisp_Number);\n lisp_export(env, \"Boolean\", Lisp_Boolean);\n lisp_export(env, \"Ignore\", Lisp_Ignore);\n lisp_export(env, \"Void\", Lisp_Void);\n lisp_export(env, \"Undefined\", Lisp_Undefined);\n lisp_export(env, \"Combiner\", Lisp_Combiner);\n lisp_export(env, \"Compound-Combiner\", Lisp_Compound_Combiner);\n lisp_export(env, \"Wrapper\", Lisp_Wrapper);\n lisp_export(env, \"Native-Combiner\", Lisp_Native_Combiner);\n /* Misc */\n lisp_export(env, \"read-from-string\", lisp_make_wrapped_native(lisp_read_from_string, 1, 1));\n lisp_export(env, \"anything-to-string\", lisp_make_wrapped_native(lisp_to_string, 1, 1));\n /* JS interop */\n lisp_export(env, \"js-global\", lisp_make_wrapped_native(lisp_js_global, 1, 1));\n lisp_export(env, \"set-js-global!\", lisp_make_wrapped_native(lisp_set_js_global, 2, 2));\n lisp_export(env, \"js-call\", lisp_make_wrapped_native(lisp_js_call, 2));\n lisp_export(env, \"js-function\", lisp_make_wrapped_native(lisp_js_function, 1, 1));\n lisp_export(env, \"js-binop\", lisp_make_wrapped_native(lisp_js_binop, 1, 1));\n lisp_export(env, \"js-object\", lisp_make_wrapped_native(lisp_js_object, 0, 1));\n lisp_export(env, \"js-array\", lisp_make_wrapped_native(lisp_js_array, 0, 0));\n /* Debugging */\n lisp_export(env, \"stack-frame\", lisp_make_wrapped_native(lisp_stack_frame, 0, 0));\n lisp_export(env, \"Stack-Frame\", Lisp_Stack_Frame);\n return env;\n}",
"function setEnv() {\n var options = getStartEnvOptions(),\n lazoPath = path.dirname(module.filename);\n\n process.env['BASE_PATH'] = lazoPath;\n process.env['BASE_REPO_DIR'] = path.join(lazoPath, 'base');\n process.env['LAZO_VERSION'] = getVersion();\n process.env['FILE_REPO_DIR'] = getFileRepoDir();\n process.env['PORT'] = options.port;\n\n for (var key in options) {\n process.env[key.toUpperCase()] = options[key];\n }\n}",
"setEnvironment(env){\n process.argv.ENVIRONMENT = env;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
grab a valid array choice | function getArray(array) { // takes in an array of booleans length 4
// returns a value between 0-3 based on the user's initial input choices
var value = -1;
var temp = -1;
while (value === -1) {
temp = getRandomInt(4);
// if array was selected by user
if (array[temp] === true) {
// return generic value indicating the randomly selected array
value = temp;
}
}
return value;
} | [
"function answerCheck(selection, currArray) {\n\n }",
"function getMcSelectNonArrayValueError() {\n return Error('Value must be an array in multiple-selection mode.');\n}",
"function getMatSelectNonArrayValueError() {\n return Error('Value must be an array in multiple-selection mode.');\n }",
"function getMatSelectNonArrayValueError() {\n return Error('Value must be an array in multiple-selection mode.');\n}",
"static choice(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n }",
"function getMatSelectNonArrayValueError() {\n return Error('Value must be an array in multiple-selection mode.');\n}",
"static choice(arr){\n return arr[Math.floor(Math.random() * arr.length)];\n }",
"function createSelectionTypeArray()\n {\n for (let m = 0; m < FormItPlugins.GenerateStringLights.arrays.typeArray.length; m++)\n {\n if (FormItPlugins.GenerateStringLights.arrays.typeArray[m] === validType)\n {\n FormItPlugins.GenerateStringLights.arrays.bIsEdgeTypeArray.push(true);\n }\n else \n {\n FormItPlugins.GenerateStringLights.arrays.bIsEdgeTypeArray.push(false);\n }\n }\n //console.log(\"Is valid array: \" + deanstein.GenerateStringLights.arrays.bIsEdgeTypeArray);\n }",
"function createSelectionTypeArray()\n {\n for (var m = 0; m < deanstein.GenerateStringLights.arrays.typeArray.length; m++)\n {\n if (deanstein.GenerateStringLights.arrays.typeArray[m] === validType)\n {\n deanstein.GenerateStringLights.arrays.bIsEdgeTypeArray.push(true);\n }\n else \n {\n deanstein.GenerateStringLights.arrays.bIsEdgeTypeArray.push(false);\n }\n }\n //console.log(\"Is valid array: \" + deanstein.GenerateStringLights.arrays.bIsEdgeTypeArray);\n }",
"function validBSOptions(array) {\n return array.length > 0 && array[0];\n }",
"function storeChoices(a, array){\n\n\t $('#'+a+' .inp1').one('click',function(){\n\t\t\tvar choice = $('#'+a+' .inp1').val();\n\t\t\tchoice = choice.toString()\n\t\t\tvar sol = questions[a].correctOp.toString();\n\t\t\tarray.push(choice);\n\t\t\t});\n\t \t$('#'+a+' .inp2').one('click',function(){\n\t\t\tvar choice = $('#'+a+' .inp2').val();\n\t\t\tchoice = choice.toString()\n\t\t\tvar sol = questions[a].correctOp.toString();\n\t\t\tarray.push(choice);\n\t\t\t\n\t\t\t});\n\t\t\t$('#'+a+' .inp3').one('click',function(){\n\t\t\tvar choice = $('#'+a+' .inp3').val();\n\t\t\tchoice = choice.toString()\n\t\t\tvar sol = questions[a].correctOp.toString();\n\t\t\tarray.push(choice);\n\t\t\t});\n\t\t\t$('#'+a+' .inp4').one('click',function(){\n\t\t\tvar choice = $('#'+a+' .inp4').val();\n\t\t\tchoice = choice.toString()\n\t\t\tvar sol = questions[a].correctOp.toString();\n\t\t\tarray.push(choice);\n\t\t\t});\n\t \t\treturn array; \n\t\t}",
"function random_choice(arr){\n\treturn arr[Math.floor(Math.random() * arr.length)];\n}",
"function makeArr() {\n\n if (hasNums) {\n for (let i = 0; i < numbers.length; i++) {\n userChoice[userChoice.length] = numbers[i];\n }\n }\n\n if (hasLower) {\n for (let j = 0; j < letters.length; j++) {\n userChoice[userChoice.length] = letters[j];\n }\n }\n\n if (hasUpper) {\n for (let k = 0; k < letters.length; k++) {\n userChoice[userChoice.length] = letters[k].toUpperCase();\n }\n }\n\n if (hasChars) {\n for (let l = 0; l < specials.length; l++) {\n userChoice[userChoice.length] = specials[l];\n }\n }\n return userChoice\n }",
"choice(...args)\r\n{\r\n if (args.length === 0) return undefined;\r\n if (args.length === 1)\r\n {\r\n if (!Array.isArray(args[0])) return args[0];\r\n else return args[0][Math.floor(Math.random() * args[0].length)]\r\n }\r\n else return args[Math.floor(Math.random() * args.length)]\r\n}",
"static validateArray(array) {\n return Array.isArray(array);\n }",
"function pickFromArray(choices) {\n return choices[Math.floor(Math.random() * choices.length)];\n}",
"function ensureArray(option) {\n return (option.length === undefined) ? [option] : option;\n}",
"function validateArray(label, arr, schema) {\n var isUndefined,\n arrLen;\n\n setDefaultValueForSchema(schema);\n\n isUndefined = typeof arr === 'undefined';\n\n if (schema.isRequired && isUndefined) {\n error(label, 'is required');\n }\n\n if (isUndefined) {\n return arr;\n }\n\n if (!_.isArray(arr)) {\n error(label, 'needs to be an array');\n }\n\n arrLen = arr.length;\n\n if (!(schema.min <= arrLen && arrLen <= schema.max)) {\n error(label, 'is not in the defined range');\n }\n\n arr = _.map(arr, function (item) {\n return select(label, item, schema.content);\n });\n\n return arr;\n}",
"function CheckArrayCmd( szValue )\r\n{\r\n EnterFunction( arguments );\r\n\r\n if( \"\" != g_oVariables.szIsaArray )\r\n {\r\n return false;\r\n }\r\n g_oVariables.szIsaArray = szValue;\r\n return true;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this method is run whenever the mouse moves anywhere over the video player on the first move, the controls will appear and it will set a timer to hide the controls in 3 seconds if the mouse hasn't moved afterwards. if it is still moving before the timer ends, the timer is reset | showControls() {
const { started, paused, mouseMoving } = this.state;
clearTimeout(this.awayTimer);
if (mouseMoving) {
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
this._hideControls();
if (started && paused) {
this.awayTimer = setTimeout(() => {
if (this._isMounted && started) this.setState({ away: true });
}, 3000);
}
}, 3000);
} else if (started && this._isMounted) {
this.setState({ mouseMoving: true, hidden: false });
this.timeout = setTimeout(() => {
this._hideControls();
if (paused) {
this.awayTimer = setTimeout(() => {
if (this._isMounted) this.setState({ away: true });
}, 3000);
}
}, 3000);
}
} | [
"function fadeControls() {\n\t\t\t\t// initial loop to hide controls if no movement\n\t\t\t\ttimer = setTimeout(function() { \n\t\t\t\t\t$vcontrols_container.fadeOut('slow');\n\t\t\t\t\t$vplayer.css('cursor', 'none');\n\t\t\t\t}, 3000);\n\t\t\t\tif ($video.attr('fs') == \"true\") {\n\t\t\t\t\t$overlay.mousemove(mouseMoveFn)\n\t\t\t\t\t$video.mousemove(mouseMoveFn)\n\t\t\t\t\t// hover function for fullscreen controls\n\t\t\t\t\t$vcontrols_container.hover(function() {\n\t\t\t\t\t\tif (timer) {\n\t\t\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\t\t\ttimer = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$vcontrols_container.fadeIn('slow');\n\t\t\t\t\t\t$vplayer.css('cursor', 'default');\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}",
"function navAutoHide(){\n var timeout=null;\n\n //Execute after 2 seconds to hide the nav\n timeout=setTimeout(function(){\n $(\".videoControls.watchNav\").fadeOut();\n },2000)\n\n //If mouse moved restart timer\n $(document).on(\"mousemove\",function(){\n console.log(\"mouse moved timer reset..\")\n clearTimeout(timeout)\n $(\".videoControls.watchNav\").fadeIn();\n\n timeout=setTimeout(function(){\n $(\".videoControls.watchNav\").fadeOut();\n },2000)\n })\n\n}",
"function show_controls() {\r\n\r\n //Let the mouse movement lister know that the controls are no longer hidden.\r\n controls_hidden = false;\r\n\r\n //Stop any animations that the control bar might have from the hide_controls function.\r\n $(\"#control_container\").stop();\r\n\r\n //Reset the cursor to the default.\r\n $(document.body).css(\"cursor\", \"default\");\r\n\r\n //Set the control bar to full opacity.\r\n $(\"#control_container\").css(\"opacity\", \"1\");\r\n\r\n }",
"function showControlsHover(){\n if (!video.paused && isFullScreenEnabled === false){\n buttonControls.style.display = \"block\";\n buttonBar.style.bottom = \"13px\";\n progressBar.style.opacity = \"1\";\n }\n}",
"function showPlayerControls() {\n\tif(!controlsVisible) {\n\t\t$(\".playerArea\").show(200, \"swing\");\n\t\tcontrolsVisible = true;\n\t}\n}",
"function editorControl()\r\n{\r\n if(!EditorMode)\r\n {\r\n CheckerInterVal = setInterval(VideoPosChecker,timeCheck)\r\n if(isQuickView)\r\n {\r\n Video.removeAttribute(\"controls\");\r\n StartQuickView();\r\n }\r\n }\r\n}",
"setControlTimeout() {\n this.player.controlTimeout = setTimeout(() => {\n this.props.shouldToggleControls && this._hideControls();\n }, this.player.controlTimeoutDelay);\n }",
"function overVideoControl() {\n showVideoControl()\n }",
"function startHideTimer(){\n var timeout = null;\n\n $(document).on(\"mousemove\", function(){\n clearTimeout(timeout); //it is javascript function\n $(\".watchNav\").fadeIn();\n \n timeout = setTimeout(function(){\n $(\".watchNav\").fadeOut();\n },2000);\n })\n}",
"function hide_controls() {\r\n\r\n //Let the mouse movement lister know that the controls are now hidden.\r\n controls_hidden = true;\r\n\r\n //Hide the cursor on the body.\r\n $(document.body).css(\"cursor\", \"none\");\r\n\r\n //Fade out the control bar over 1500ms using opacity.\r\n $(\"#control_container\").animate({ opacity: 0 }, 1500);\r\n\r\n }",
"function scrollControl () {\n\n\t\tvideo_placement = pageContainer.getBoundingClientRect();\n\t\tvar video_from_top = window.innerHeight - video_placement.top;\n\n\t\t//console.log(video_placement.top);\n\n\t\tif(!videoPlayerVisible) {\n\n\t\t\t//console.log('video player invisible');\n\n\t\t\t//console.log(video_placement.top);\n\n\t\t\tif ( video_placement.top < ( window.innerHeight - (video_dimensions.height / 2)) ) {\n\n\t\t\t\tshowVideo();\n\t\t\t}\n\n\t\t}else{\n\n\t\t\tif (video_placement.top <= (video_dimensions.height / 2) * -1 ) {\n\n\t\t\t\tvideoPlayer.pause();\n\n\t\t\t\treturn;\n\n\t\t\t}else{\n\n\t\t\t\tif( (window.innerHeight - video_placement.top) < (video_dimensions.height / 2)) {\n\n\n\t\t\t\t\tvideoPlayer.pause();\n\n\t\t\t\t\treturn;\n\n\t\t\t\t}else{\n\n\t\t\t\t\tplayVideo ()\n\n\t\t\t\t\treturn;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}",
"setControlTimeout() {\n this.player.controlTimeout = setTimeout(() => {\n this._hideControls();\n // This triggers channel Avatar Channel & Follow Button [Landscape View]\n this.props.streamLandscapeStore.isShadowOverlayOn = false;\n\n }, this.player.controlTimeoutDelay);\n }",
"function hidePlayerControls() {\n\tif(controlsVisible) {\n\t\t$(\".playerArea\").hide(200, \"swing\");\n\t\tcontrolsVisible = false;\n\t}\n}",
"function videoControlInit(){\n \n camera = document.getElementById(\"camera\");\n //camera.addEventListener(\"ended\", resetVid, false);\n camera.addEventListener(\"play\", playPause, false);\n camera.addEventListener(\"pause\", playPause, false);\n //camera.addEventListener(\"ended\", function(){isEnded=true;}, false);\n \n map = document.getElementById(\"map\");\n map.muted = true;\n \n playPauseButton = document.getElementById(\"playPauseButton\");\n //playPauseButton.innerHTML = ' > ';\n \n speedLabel = document.getElementById(\"speedLabel\");\n speedLabel.innerHTML = \"1 \";\n \n //timer2= setInterval(timeCountdown(isPlay), 1);\n \n //camera.addEventListener(\"play\", timer2 = self.setInterval(timeCountdown(), 1000/600));\n //camera.addEventListener(\"pause\", timer2 = window.clearInterval(timer2));\n \n //speedTrackBar = document.getElementById(\"speedTrackBar\");\n //speedTrackBar.addEventListener(\"input\", speedChange, false);\n \n //cameraTrackBar = document.getElementById(\"cameraTrackBar\");\n //cameraTrackBar.addEventListener(\"input\", trackBarChange, false);\n //cameraTrackBar.value = 0;\n}",
"function showWhenReady() {\n var seconds = self.video.time();\n if (parseFloat(seconds) > startPoint) {\n $loading.remove();\n self.show(callback);\n self.video.removeEvent(\"playback\", showWhenReady);\n }\n }",
"function timeupdateHandler(evt) {\n // ...\n // myPlayer.off('timeupdate', timeupdateHandler);\n// console.log('timeupdate ' + evt);\n// console.log(player.currentTime());\n if (player.currentTime() > 0.5) {\n // player.pause();\n // window.location.href = gamesList[document.location.pathname.split('/')[2]].url;\n // we only want to do this once, so unload the listener\n// player.off('timeupdate', timeupdateHandler);\n // hide the player controls\n // player.addClass('hide-controls');\n// window.location.href = gamesList[document.location.pathname.split('/')[2]].url;\n\n }\n}",
"function showControls() {\n if(currentPosition == numOfSlides) {\n $next.addClass('hidden');\n } else {\n $next.removeClass('hidden');\n }\n if(currentPosition == 1) {\n $previous.addClass('hidden');\n } else {\n $previous.removeClass('hidden');\n }\n }",
"function checkAndShowControls(noAnimation){\n\t\t\n\t\tif(g_options.slider_controls_always_on == true)\n\t\t\tshowControls(noAnimation);\t\t\n\t}",
"function hoverFunc() {\n \"use strict\";\n\n // function setTimer() {\n // return timer = window.setTimeout(function () {\n // optionTabText.fadeOut('fast', function () {\n // optionTab.animate({\n // 'width': '18px', 'margin-left': 0\n // });\n // });\n // }, 5000);\n // }\n\n var controls = $('#controls'),\n optionTab = $('#optionTab'),\n optionTabText = $('#optionTabText'),\n timer;\n\n // set timer when mouse moves for first time on new page\n // setTimer();\n\n optionTab\n .mouseenter(function () {\n if (optionTab.css('width') === '44px' &&\n optionTabText.css('display') === 'block') {\n optionTabText.fadeOut({\n 'queue': false,\n 'duration': 'fast',\n 'complete': function () {\n optionTab.animate({\n 'width': '243px',\n 'height': '266px',\n 'margin-top': '-133px',\n 'margin-left': '-225px'\n }, {\n 'duration': 600,\n 'queue': false,\n 'complete': function () {\n controls.fadeIn();\n // window.clearTimeout(timer);\n }\n })\n }\n });\n }\n })\n .mouseleave(function () {\n if (optionTab.css('width') === '243px' &&\n optionTabText.css('display') === 'none') {\n optionTabText.stop(true, true);\n optionTab.stop();\n controls.fadeOut('fast', function () {\n optionTab.animate({\n 'width': '44px',\n 'height': '94px',\n 'margin-top': '-47px',\n 'margin-left': '-26px'\n }, {\n 'duration': 600,\n 'queue': false,\n 'complete': function () {\n optionTabText.fadeIn('fast');\n // setTimer();\n }\n });\n });\n }\n });\n\n // $(document).mousemove(function () {\n // window.clearTimeout(timer);\n // \n // if (optionTab.css('width') !== '243px') {\n // setTimer();\n // \n // if (optionTab.css('width') === '18px') {\n // optionTab.animate({\n // 'width': '44px',\n // 'margin-left': '-26px'\n // }, function () {\n // optionTabText.fadeIn();\n // });\n // }\n // }\n // });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the background view. | get backgroundView() {
if (!this._backgroundView) {
this._backgroundView = BrowserHelper.getBackgroundPage();
}
return this._backgroundView;
} | [
"getBackgroundStage () {\n return this._background;\n }",
"function getBackground(){\n\t\treturn background;\n\t}",
"get background() {\n return this._data.background;\n }",
"get backgroundRenderer () {\n return this._backgroundRenderer = (this._backgroundRenderer || BackgroundRendererModel.parse({\n session: this\n }))\n }",
"get backgroundMesh() {\n return this.m_bgMesh;\n }",
"getBackgroundStyle() {\n return this.backgroundStyle;\n }",
"getBackgroundImage(){return this.__background.image}",
"function getBackgroundElement() {\n return document.getElementById('modal-snap-background');\n}",
"function getBackgroundPage() {\n if (chrome.extension) {\n return chrome.extension.getBackgroundPage()\n }\n return null\n}",
"getBackgroundColor() {\n switch (this.config.background) {\n case Config_1.Background.BLACK:\n return exports.BLACK_BACKGROUND;\n case Config_1.Background.AUTHENTIC:\n default:\n return exports.AUTHENTIC_BACKGROUND;\n }\n }",
"static makeBackground() {\n\n var background = new DisplayObjectNode(\"Background\", \"EmptyBleachers.png\");\n\n background.setPosition({x: 0, y: 0});\n background.setPivotPoint({x: 0, y: 0});\n\n return background;\n }",
"getBackgroundColor() {\n switch (this.config.background) {\n case Background.BLACK:\n return BLACK_BACKGROUND;\n case Background.AUTHENTIC:\n default:\n return AUTHENTIC_BACKGROUND;\n }\n }",
"function getBackground() {\n if ( $( 'body' ).css( 'backgroundImage' ) ) {\n return $( 'body' ).css( 'backgroundImage' ).replace( /url\\(\"?(.*?)\"?\\)/i, '$1' );\n }\n }",
"function getBackground() {\r\n if ( $( 'body' ).css( 'backgroundImage' ) ) {\r\n return $( 'body' ).css( 'backgroundImage' ).replace( /url\\(\"?(.*?)\"?\\)/i, '$1' );\r\n }\r\n }",
"function getBackground() {\n\t\tif ( $( 'body' ).css( 'backgroundImage' ) ) {\n\t\t\treturn $( 'body' ).css( 'backgroundImage' ).replace( /url\\(\"?(.*?)\"?\\)/i, '$1' );\n\t\t}\n\t}",
"function getBackground() {\n $('body').addClass(getBackgroundClass(icons[icon]));\n }",
"function setBackground() {\n var bgSurface = new Surface({\n properties: {\n backgroundColor: 'black',\n size: [window.innerWidth,window.innerHeight]\n }\n });\n mainView.add(bgSurface);\n }",
"getBackgroundColor() {}",
"function createBackgroundElement() {\n return new Rectangle(\n /* x= */ kPickerOffsetX,\n /* y= */ kPickerOffsetY,\n /* width= */ kPickerWidth,\n /* height= */ kPickerHeight,\n /* color= */ kPickerBackgroundColor);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls a function on the latest client. Use this with caution, it's meant as in "internal" helper so we don't need to expose every possible function in the shim. It is not guaranteed that the client actually implements the function. | function _callOnClient(method) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
callOnHub.apply(void 0, Object(tslib_es6["e" /* __spread */])(['_invokeClient', method], args));
} | [
"function _callOnClient(method) {\n\t var args = [];\n\t for (var _i = 1; _i < arguments.length; _i++) {\n\t args[_i - 1] = arguments[_i];\n\t }\n\t callOnHub.apply(void 0, tslib_es6.__spread(['invokeClient', method], args));\n\t}",
"function _callOnClient(method) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n callOnHub.apply(void 0, Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__spread\"])(['_invokeClient', method], args));\n}",
"function _callOnClient(method) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n callOnHub.apply(void 0, tslib_es6[\"d\" /* __spread */](['_invokeClient', method], args));\n}",
"function _callOnClient(method) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n invokeClient.apply(void 0, __spread([method], args));\n}",
"function _callOnClient(method) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n callOnHub.apply(void 0, tslib_1.__spread(['invokeClient', method], args));\n}",
"function _callOnClient(method) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n callOnHub.apply(void 0, tslib_tslib_es6_spread(['_invokeClient', method], args));\n}",
"function invokeClient(method) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n var top = getOrCreateShim().getStackTop();\n if (top && top.client && top.client[method]) {\n (_a = top.client)[method].apply(_a, __spread(args, [top.scope]));\n }\n var _a;\n}",
"function _callOnClient(method) {\n var args = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n\n callOnHub.apply(void 0, (0, _tslib.__spread)(['_invokeClient', method], args));\n}",
"getClientCalls() {\n\n }",
"function getCurrentClient() {\n return getOrCreateShim().getCurrentClient();\n}",
"get remotelyCallable() { return [\"clientRequestForServer\"] }",
"function patchClient() {\n const plugin = this;\n return (original) => {\n plugin._logger.debug('patching client');\n return function makeClientConstructor(methods, serviceName, options) {\n const client = original.call(this, methods, serviceName, options);\n shimmer.massWrap(client.prototype, utils_1.getMethodsToWrap.call(plugin, client, methods), utils_1.getPatchedClientMethods.call(plugin));\n return client;\n };\n };\n}",
"ClientFunction(fn, options) {\n return ClientFunction(fn, { ...options, boundTestRun: this.t });\n }",
"GetClientVersion(empty, callback) {\n this.client.getClientVersion(empty, function (err, response) {\n if (err) {\n callback(err)\n } else {\n callback(null, response)\n }\n })\n }",
"function invokeClientAsync(method, callback) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n var top = getOrCreateShim().getStackTop();\n if (top && top.client && top.client[method]) {\n (_a = top.client)[method].apply(_a, __spread(args, [top.scope])).then(function (value) {\n callback(undefined, value);\n })\n .catch(function (err) {\n callback(err);\n });\n }\n var _a;\n}",
"function _call_upgrade() {\n return rpc_client.upgrade.upgrade_cluster()\n .catch(err => {\n if (err.rpc_code === 'NO_SUCH_RPC_SERVICE') {\n console.log('Failed using upgrade.upgrade_cluster, using cluster_internal.upgrade_cluster', err.rpc_code);\n return rpc_client.cluster_internal.upgrade_cluster();\n } else {\n throw err;\n }\n });\n}",
"function callFrontMethod (method) {\n return function () {\n // If there's no target or client on this actor facade,\n // abort silently -- this occurs in tests when polling occurs\n // after the test ends, when tests do not wait for toolbox destruction\n // (which will destroy the actor facade, turning off the polling).\n if (!this._target || !this._target.client) {\n return;\n }\n return this._front[method].apply(this._front, arguments);\n };\n}",
"function wrapClient(client, user, conn) {\n var wrapper = {}\n conn.user = user\n Object.defineProperty(wrapper, 'client', {value: client})\n client.on('message', function(from, to, text) {\n if (to === client.nick || [client.nick].concat(user.highlights).some(function(highlight) {\n return ~text.indexOf(highlight)\n })) {\n client.emit('important-message', from, to, text)\n }\n })\n Object.keys(IRC_METHODS).forEach(function(methodName) {\n var realFn = client[methodName]\n var requiredArgs = IRC_METHODS[methodName]\n wrapper[methodName] = function() {\n var args = [].slice.call(arguments)\n // silently stop execution on error\n // FIXME tell the client\n if (requiredArgs.some(function(type, i) {\n var arg = args[i]\n switch (type) {\n case 'message': return typeof arg !== 'string'\n case 'channel': return typeof arg !== 'string' || arg.length < 2 || arg[0] !== '#' || arg.indexOf(':') > -1\n case 'chanOrNick': return typeof arg !== 'string'\n case 'nick': return typeof arg !== 'string' || arg.length === 0 || arg[0] === '#'\n default: throw new Error('cant wrap stuff of type \"'+type+'\"')\n }\n })) return\n // Note: We don't update the in-memory state for this stuff because it\n // should represent the current state anyway.\n if (methodName === 'join') {\n couch.db.alter(user._id, function(user) {\n if (user.channels.indexOf(args[0]) === -1)\n user.channels.push(args[0])\n return user\n }, dummyCb)\n } else if (methodName === 'part') {\n couch.db.alter(user._id, function(user) {\n var index = user.channels.indexOf(args[0])\n if (index !== -1)\n user.channels.splice(index, 1)\n return user\n }, dummyCb)\n }\n realFn.apply(client, arguments)\n }\n })\n // when the browser disconnects, its listeners should be removed\n wrapper.on = function(type, listener) {\n if (typeof type !== 'string' || typeof listener !== 'function')\n throw new Error('invalid args')\n client.on(type, listener)\n this.conn.on('end', function() {\n client.removeListener(type, listener)\n })\n }\n // we don't want disconnects or so to kill the process\n client.on('error', function(){})\n return wrapper\n}",
"function clientCode(facade) {\n console.log(facade.operation());\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
routes to "/", "/new", "/:postId" either renders PostList, NewPostForm, or PostDetail | render() {
return (
<div className="Routes">
<Switch>
<Route exact path="/"
render={() =>
<PostList />} />
<Route exact path="/new"
render={(rtProps) =>
<NewPostForm { ...rtProps } />} />
<Route exact path="/:postId"
render={(rtProps) =>
<PostDetail { ...rtProps }
postId = { rtProps.match.params.postId }/>} />
<Redirect to="/" />
</Switch>
</div>
);
} | [
"function new_post_page(path, title, posts, url){\n router.get('/'+path, function(req, res, next) {\n res.render('dynamic', {\n\t\t\tTitle: title,\n\t\t\tPosts: posts,\n\t\t\tURL: url\n\t\t});\n });\n}",
"static jumpToPost(id) {\n Router.jumpTo(`${Constant.route.post}/${id}`);\n }",
"createPost() {\n this.$router.push({ name: \"create-post\" });\n }",
"async getPostForm(req, res, next){\n res.render('forum/new', { title: 'Create Post' });\n}",
"function createPost() {\n\n\tlet postForm = viewSwitch(constructPost());\n\t$('.viewWrapper').replaceWith(postForm);\n}",
"function addNewPost() {\n postService.savePost(\n $scope.newPost\n ).then(function(){\n $location.path('/posts').replace();\n });\n $scope.newPost = {};\n }",
"render() {\n return (\n <Switch>\n <Route exact path=\"/\" component={CategoryView} />\n <Route exact path=\"/newpost\" component={NewPost} />\n <Route exact path=\"/:category\" component={CategoryView} />\n <Route exact path=\"/edit/:post_id\" component={EditPost}/>\n <Route exact path=\"/:category/:post_id\" component={PostDetail}/>\n\n </Switch>\n );\n }",
"handleSubmit(post, postId) {\n this.props.editPostApi(post, postId);\n this.props.history.push('/');\n }",
"function showDetails(postId){\n\t\t\t$state.go('tab.post-details/:id', {id:postId});\n\t\t}",
"submitPost(e) {\n e.preventDefault();\n\n if(this.props.router.match.params.postId != null)\n Meteor.call('post.update', this.props.router.match.params.postId, this.state, (err, results) => {\n if(err){\n console.log(err)\n }else{\n\n }\n });\n else\n Meteor.call('posts.insert', this.state, (err, results) => {\n if(err)\n console.log(err)\n });\n\n this.props.router.history.push(\"/\");\n }",
"async function newPost() {\n let newPost = formatResults(await submitPost())[0];\n id(\"home\").prepend(generateCard(newPost));\n setTimeout(showHomeView, DELAY);\n }",
"addPostRoutes() {\n this._addVerb('post');\n }",
"function NewPost() {\n\n const dispatch = useDispatch();\n\n function submitForm(data, id) {\n dispatch(addPost(id, data));\n }\n\n return (\n <div className=\"NewPost\">\n <h1>New Post</h1>\n <PostForm submitForm={submitForm}/>\n </div>\n );\n}",
"function handleExistingPost() {\n\n // get the part of the url with username and title\n const title = extractTitleDate(url)\n // get the post by username and title\n\n // render the post\n renderPost(postData)\n\n}",
"function createPost(post){\n console.log(post);\n $http.post(`${server}/posts`, {post: post})\n .then(function(res){\n console.log(res);\n\n $state.go('index')\n });\n }",
"function submitPost() {\n const newPost = {\n title: ui.titleInput.value,\n body: ui.bodyInput.value,\n }\n\n if (newPost.title === '' || newPost.body === '') {\n return;\n } else {\n if (ui.idInput.value === '') {\n //Create post\n http.post('http://localhost:3000/posts', newPost)\n .then(data => {\n getPosts();\n ui.clearFormFields();\n })\n .catch(err => console.log(err));\n } else {\n // Update post\n http.put(`http://localhost:3000/posts/${ui.idInput.value}`, newPost)\n .then(data => {\n ui.clearFormFields();\n ui.changeFormState('add');\n getPosts();\n })\n .catch(err => console.log(err));\n }\n }\n}",
"function newTodo (req, res){\n res.render(`todos/new`)\n}",
"function handlePostEdit() {\n var currentPost = $(this)\n .parent()\n .parent()\n .data(\"post\");\n window.location.href = \"/landing\" + currentPost.id;\n }",
"function edit_posting() {\r\n\tvar postid = req.data.postid\r\n\tvar data = {};\r\n\tdata.post = null;\r\n\tif (postid != null) {\r\n\t\tdata.post = app.getObjects(\"Post\",{_id:postid})[0];\r\n\t}\r\n\treturn this.manage_wrap( { content:this.manage_edit_posting_view(data) } );\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
REGRESSION Takes market data and calculates yintercept, slope and takes an arg of x in this.Regression to calculate the y of any x in relation to the target market slope. | function Regression(arr) {
var N = arr.length,
XY = [],
XX = [],
EX = 0,
EY = 0,
EXY = 0,
EXX = 0;
for (var i = 0; i < N; i++) {
var y = arr[i].price;
var x = arr[i].miles;
XY.push(x * y);
XX.push(x * x);
EX += x;
EY += y;
EXY += x * y;
EXX += x * x;
}
this.Slope = ((N * EXY) - (EX * EY)) / ((N * EXX) - (EX * EX));
this.Intercept = (EY - (this.Slope * EX)) / N;
this.getY = function(x) {
return this.Slope * x + this.Intercept;
};
this.RegressionY = function(x) {
return this.Intercept + (this.Slope * x);
};
this.RegressionX = function(y) {
return (y - this.Intercept) / this.Slope;
};
} | [
"function linearRegression(y,x){\n\n var lr = {};\n var n = y.length;\n var sum_x = 0;\n var sum_y = 0;\n var sum_xy = 0;\n var sum_xx = 0;\n var sum_yy = 0;\n\n for (var i = 0; i < y.length; i++) {\n\n sum_x += x[i];\n sum_y += y[i];\n sum_xy += (x[i]*y[i]);\n sum_xx += (x[i]*x[i]);\n sum_yy += (y[i]*y[i]);\n }\n\n lr['slope'] = (n * sum_xy - sum_x * sum_y) / (n*sum_xx - sum_x * sum_x);\n lr['intercept'] = (sum_y - lr.slope * sum_x)/n;\n lr['r2'] = Math.pow((n*sum_xy - sum_x*sum_y)/Math.sqrt((n*sum_xx-sum_x*sum_x)*(n*sum_yy-sum_y*sum_y)),2);\n\n return lr;\n\n}",
"function linearRegression(y, x) {\n var lr = {};\n var n = y.length;\n var sum_x = 0;\n var sum_y = 0;\n var sum_xy = 0;\n var sum_xx = 0;\n var sum_yy = 0;\n\n for (var i = 0; i < y.length; i++) {\n\n sum_x += x[i];\n sum_y += y[i];\n sum_xy += (x[i] * y[i]);\n sum_xx += (x[i] * x[i]);\n sum_yy += (y[i] * y[i]);\n }\n\n lr['slope'] = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x);\n lr['intercept'] = (sum_y - lr.slope * sum_x) / n;\n lr['r2'] = Math.pow((n * sum_xy - sum_x * sum_y) / Math.sqrt((n * sum_xx - sum_x * sum_x) * (n * sum_yy - sum_y * sum_y)), 2);\n\n return lr;\n}",
"function linearRegression(y,x){\n var lr = {};\n var n = y.length;\n var sum_x = 0;\n var sum_y = 0;\n var sum_xy = 0;\n var sum_xx = 0;\n var sum_yy = 0;\n\n for (var i = 0; i < y.length; i++) {\n\n sum_x += x[i];\n sum_y += y[i];\n sum_xy += (x[i]*y[i]);\n sum_xx += (x[i]*x[i]);\n sum_yy += (y[i]*y[i]);\n } \n\n lr['slope'] = (n * sum_xy - sum_x * sum_y) / (n*sum_xx - sum_x * sum_x);\n lr['intercept'] = (sum_y - lr.slope * sum_x)/n;\n lr['r2'] = Math.pow((n*sum_xy - sum_x*sum_y)/Math.sqrt((n*sum_xx-sum_x*sum_x)*(n*sum_yy-sum_y*sum_y)),2);\n\n return lr;\n}",
"function linear_regression(x_cord_data, y_cord_data) {\n var data_matrix = [];//array init\n $(x_cord_data).each(function(index, val) {\n //merge data sets to form single array\n data_matrix.push([x_cord_data[index], y_cord_data[index]]);\n });\n //perform linear regression\n var result = regression('linear', data_matrix);\n //round up the values\n var slope = Math.round(result.equation[0] * 100) / 100;\n var yintercept = Math.round(result.equation[1] * 100) / 100;\n var trendpoints = [];//array init\n //retur array back\n return trendpoints = [slope, yintercept];\n}",
"function regressionIntercept (coefficient,data){\n\t\t\treturn mean(data, function(d) {return d.y;})-coefficient*mean(data, function(d) {return d.x;});\n}",
"function linearRegressionWithOrdinaryLeastSqures() {\n // Calculate the sum of all x and y\n var xSum = 0;\n var ySum = 0;\n for (var i = 0; i < data.length; i++) {\n xSum += data[i].x; // Temperature\n ySum += data[i].y; // sales count\n }\n \n // calculate the mean(average) of x and y\n var xMean = xSum / data.length;\n var yMean = ySum / data.length;\n\n // find numerator and denominator\n var numerator = 0;\n var denominator = 0;\n for (var i = 0; i < data.length; i++) {\n var x = data[i].x;\n var y = data[i].y;\n numerator += (x - xMean) * (y - yMean);\n denominator += (x - xMean) * (x - xMean);\n }\n\n if (denominator != 0) {\n slop = numerator / denominator; // slop is the m variable in the formula - y = mx + b\n yIntercept = yMean - slop * xMean; // yIntercept is the b variable in the formula - y = mx + b\n }\n refreshAIModel();\n}",
"function linear_regression() {\n var linreg = {},\n data = [];\n\n // Assign data to the model. Data is assumed to be an array.\n linreg.data = function(x) {\n if (!arguments.length) return data;\n data = x.slice();\n return linreg;\n };\n\n // Calculate the slope and y-intercept of the regression line\n // by calculating the least sum of squares\n linreg.mb = function() {\n var m, b;\n\n //if there's only one point, arbitrarily choose a slope of 0\n //and a y-intercept of whatever the y of the initial point is\n if (data.length == 1) {\n m = 0;\n b = data[0][1];\n } else {\n // Initialize our sums and scope the `m` and `b`\n // variables that define the line.\n var sum_x = 0, sum_y = 0,\n sum_xx = 0, sum_xy = 0;\n\n // Gather the sum of all x values, the sum of all\n // y values, and the sum of x^2 and (x*y) for each\n // value.\n //\n // In math notation, these would be SS_x, SS_y, SS_xx, and SS_xy\n for (var i = 0; i < data.length; i++) {\n sum_x += data[i][0];\n sum_y += data[i][1];\n\n sum_xx += data[i][0] * data[i][0];\n sum_xy += data[i][0] * data[i][1];\n }\n\n // `m` is the slope of the regression line\n m = ((data.length * sum_xy) - (sum_x * sum_y)) /\n ((data.length * sum_xx) - (sum_x * sum_x));\n\n // `b` is the y-intercept of the line.\n b = (sum_y / data.length) - ((m * sum_x) / data.length);\n }\n\n // Return both values as an object.\n return { m: m, b: b };\n };\n\n // a shortcut for simply getting the slope of the regression line\n linreg.m = function() {\n return linreg.mb().m;\n };\n\n // a shortcut for simply getting the y-intercept of the regression\n // line.\n linreg.b = function() {\n return linreg.mb().b;\n };\n\n // ## Fitting The Regression Line\n //\n // This is called after `.data()` and returns the\n // equation `y = f(x)` which gives the position\n // of the regression line at each point in `x`.\n linreg.line = function() {\n\n // Get the slope, `m`, and y-intercept, `b`, of the line.\n var mb = linreg.mb(),\n m = mb.m,\n b = mb.b;\n\n // Return a function that computes a `y` value for each\n // x value it is given, based on the values of `b` and `a`\n // that we just computed.\n return function(x) {\n return b + (m * x);\n };\n };\n\n return linreg;\n }",
"function linear_regression() {\n var linreg = {},\n data = [];\n\n // Assign data to the model. Data is assumed to be an array.\n linreg.data = function(x) {\n if (!arguments.length) return data;\n data = x.slice();\n return linreg;\n };\n\n // Calculate the slope and y-intercept of the regression line\n // by calculating the least sum of squares\n linreg.mb = function() {\n var m, b;\n\n // Store data length in a local variable to reduce\n // repeated object property lookups\n var data_length = data.length;\n\n //if there's only one point, arbitrarily choose a slope of 0\n //and a y-intercept of whatever the y of the initial point is\n if (data_length === 1) {\n m = 0;\n b = data[0][1];\n } else {\n // Initialize our sums and scope the `m` and `b`\n // variables that define the line.\n var sum_x = 0, sum_y = 0,\n sum_xx = 0, sum_xy = 0;\n\n // Use local variables to grab point values\n // with minimal object property lookups\n var point, x, y;\n\n // Gather the sum of all x values, the sum of all\n // y values, and the sum of x^2 and (x*y) for each\n // value.\n //\n // In math notation, these would be SS_x, SS_y, SS_xx, and SS_xy\n for (var i = 0; i < data_length; i++) {\n point = data[i];\n x = point[0];\n y = point[1];\n\n sum_x += x;\n sum_y += y;\n\n sum_xx += x * x;\n sum_xy += x * y;\n }\n\n // `m` is the slope of the regression line\n m = ((data_length * sum_xy) - (sum_x * sum_y)) /\n ((data_length * sum_xx) - (sum_x * sum_x));\n\n // `b` is the y-intercept of the line.\n b = (sum_y / data_length) - ((m * sum_x) / data_length);\n }\n\n // Return both values as an object.\n return { m: m, b: b };\n };\n\n // a shortcut for simply getting the slope of the regression line\n linreg.m = function() {\n return linreg.mb().m;\n };\n\n // a shortcut for simply getting the y-intercept of the regression\n // line.\n linreg.b = function() {\n return linreg.mb().b;\n };\n\n // ## Fitting The Regression Line\n //\n // This is called after `.data()` and returns the\n // equation `y = f(x)` which gives the position\n // of the regression line at each point in `x`.\n linreg.line = function() {\n\n // Get the slope, `m`, and y-intercept, `b`, of the line.\n var mb = linreg.mb(),\n m = mb.m,\n b = mb.b;\n\n // Return a function that computes a `y` value for each\n // x value it is given, based on the values of `b` and `a`\n // that we just computed.\n return function(x) {\n return b + (m * x);\n };\n };\n\n return linreg;\n }",
"function linearRegression(data, xname, x, yname, y) {\n\n // Calculate the x-value mean\n var xMean = d3.mean(data, function (d) {\n return d[xname][x];\n });\n\n // Calculate the y-value mean\n var yMean = d3.mean(data, function (d) {\n return d[yname][y];\n });\n\n var numerator = 0;\n var denominator = 0;\n\n\n data.forEach(function (d) {\n var num = (d[xname][x] - xMean) * (d[yname][y] - yMean);\n var den = (d[xname][x] - xMean) * (d[xname][x] - xMean);\n numerator += num;\n denominator += den;\n });\n\n // Solve for these variables\n var B1 = numerator.toFixed(5) / denominator.toFixed(5);\n var B0 = yMean - B1 * xMean;\n\n return [B1, B0];\n\n}",
"function calcLinear(data, x, y, minX, minY, maxX, maxY) {\n // Let n = the number of data points\n let Yx = linearRegressionUI(\"y\", sumRow.avgSumY, sumRow.avgSumX, sumRow.avgSumX);\n let Xy = linearRegressionUI(\"x\", sumRow.avgSumX, sumRow.avgSumY, sumRow.avgSumY);\n\n console.log(Yx);\n console.log(Xy);\n\n // Print the equation below the chart\n document.getElementsByClassName(\"equation\")[0].innerHTML = \"Yx = \" + Yx;\n document.getElementsByClassName(\"equation\")[1].innerHTML = \"Xy = \" + Xy;\n\n console.log(maxY);\n let x2 = linearRegression(\"x\", sumRow.avgSumX, sumRow.avgSumY, maxY);\n\n // return an object of two points\n // each point is an object with an x and y coordinate\n return {\n ptA: {\n x: 0,\n y: linearRegression(\"y\", sumRow.avgSumY, sumRow.avgSumX, 0),\n },\n ptB: {\n x: maxX,\n y: linearRegression(\"y\", sumRow.avgSumY, sumRow.avgSumX, maxX),\n },\n ptA1: {\n x: linearRegression(\"x\", sumRow.avgSumX, sumRow.avgSumY, 0),\n y: 0,\n },\n ptB1: {\n x: linearRegression(\"x\", sumRow.avgSumX, sumRow.avgSumY, maxY),\n y: maxY\n }\n }\n}",
"function calculateTrendlineCoordinates (data) {\n\t\t\tslope = data[1][0];\n\t\t\tintercept = data[1][1];\n\t\t\ty1 = slope * 2006 + intercept;\n\t\t\ty2 = slope * 2016 + intercept;\n\t\t}",
"function getYIntercept(point, slope) {\n return point.y - slope * point.x;\n}",
"function getYIntercept(point, slope) {\n return point.y - slope * point.x;\n }",
"function generateSavingsRegression (data) {\n const accumulateReducer = (accumulator, current) => {\n let newTotal;\n if (accumulator.length > 0) {\n newTotal = accumulator[accumulator.length - 1] + current.total;\n return accumulator.concat([newTotal]);\n }\n else {\n return accumulator.concat([current.total]);\n }\n };\n const cumulativeSavings = data.reduce(accumulateReducer, [0.0])\n const dataForRegression = cumulativeSavings.map((item, index) => {\n return [index, item]\n });\n const result = regression.linear(dataForRegression);\n return result;\n}",
"function CalcolateRegressionLine(){\n var xS = 0;\n var yS = 0;\n n = array_x.length;\n var mx;\n var my;\n var qx;\n var a;\n var b;\n var Cy;\n var coxy = 0;\n var cox = 0;\n var coy = 0;\n\n/*\n Calcolo media\n*/\n\n for(i = 0; i < n; i++) {\n xS += array_x[i];\n yS += array_y[i];\n }\n\n xM = xS / n;\n yM = yS / n;\n\n/*\n Calcolo il coefficiente angolare m (rispetto alle ascisse e ordinate) con il metodo dei minimi quadrati\n*/\n\n for(i = 0; i < n; i++) {\n coxy += (array_x[i] - xM) * (array_y[i] - yM);\n cox += Math.pow(array_x[i] - xM, 2);\n coy += Math.pow(array_y[i] - yM, 2);\n }\n\n mx = coxy / cox;\n my = coxy / coy;\n qx = yM - mx * xM;\n \n/*\n Trovo le coordinate di n punti con ascissa dei dati inseriti per cui la retta di regressione passa\n*/\n\n for(i = 0; i < n; i++) {\n Cy = mx * array_x[i] + qx;\n arrayRegX_x.push(array_x[i]);\n arrayRegX_y.push(Cy);\n }\n\n/*\n Calcolo il coefficiente di Bravais-Pearson\n*/\n\n r = Math.sqrt(mx * my);\n\n console.log(\"Array dei dati\");\n console.log(\"X: \" + array_x);\n console.log(\"Y: \" + array_y);\n console.log(\"\");\n console.log(\"Array punto medio\");\n console.log(\"X: \" + xM);\n console.log(\"Y: \" + yM);\n console.log(\"\");\n console.log(\"Array dei punti della retta\");\n console.log(\"X: \" + arrayRegX_x);\n console.log(\"Y: \" + arrayRegX_y);\n console.log(\"\");\n console.log(\"Coefficiente angolare\");\n console.log(\"m: \" + mx);\n console.log(\"\");\n console.log(\"Intercetta\");\n console.log(\"q: \" + qx);\n console.log(\"\");\n console.log(\"Coefficiente di correlazione lineare\");\n console.log(\"r: \" + r);\n\n mx = mx.toFixed(3);\n qx = qx.toFixed(3);\n my = my.toFixed(3);\n r = r.toFixed(3);\n\n if(mx == 0){\n a = \"\";\n }else if(mx > 0 || mx < 0){\n a = mx + \"x\";\n }else if(mx == -1){\n a = \"-x\";\n }\n else if(mx == 1){\n a = \"x\";\n }\n\n if(qx == 0){\n b = \"\";\n }else if(qx > 0){\n b = \" + \" + qx;\n }else if(qx < 0){\n b = \" - \" + qx * (-1);\n }\n\n func = \"y\" + \" = \" + a + b; \n cor = \"r\" + \" = \" + r;\n\n if(r > 0.5 || r < -0.5){\n corText = \"Abbastanza affidabile\";\n if(r > 0.75 || r < -0.75){\n corText = \"Molto affidabile\";\n if(r == 1 || r == -1){\n corText = \"Massima affidabilità\";\n }\n }\n }else if(r < 0.5 || r > -0.5){\n corText = \"Scarsamente affidabile\"\n if(r < 0.75 || r > -0.75){\n corText = \"Poco affidabile\"\n if(r == 0){\n corText = \"Non esiste\"\n }\n }\n }\n}",
"function linear (xData, yData, periods) {\n\n\t\tvar\t\tlineData = [],\n\t\t\t\tstep1,\n\t\t\t\tstep2 = 0,\n\t\t\t\tstep3 = 0,\n\t\t\t\tstep3a = 0,\n\t\t\t\tstep3b = 0,\n\t\t\t\tstep4 = 0,\n\t\t\t\tstep5 = 0,\n\t\t\t\tstep5a = 0,\n\t\t\t\tstep6 = 0,\n\t\t\t\tstep7 = 0,\n\t\t\t\tstep8 = 0,\n\t\t\t\tstep9 = 0;\n\n\n\t\t// Step 1: The number of data points.\n\t\tstep1 = xData.length;\n\n\t\t// Step 2: \"step1\" times the summation of all x-values multiplied by their corresponding y-values.\n\t\t// Step 3: Sum of all x-values times the sum of all y-values. 3a and b are used for storing data.\n\t\t// Step 4: \"step1\" times the sum of all squared x-values.\n\t\t// Step 5: The squared sum of all x-values. 5a stores data.\n\t\t// Step 6: Equation to calculate the slope of the regression line.\n\t\t// Step 7: The sum of all y-values.\n\t\t// Step 8: \"step6\" times the sum of all x-values (step5).\n\t\t// Step 9: The equation for the y-intercept of the trendline.\n\t\tfor ( var i = 0; i < step1; i++) {\n\t\t\tstep2 = (step2 + (xData[i] * yData[i]));\n\t\t\tstep3a = (step3a + xData[i]);\n\t\t\tstep3b = (step3b + yData[i]);\n\t\t\tstep4 = (step4 + Math.pow(xData[i], 2));\n\t\t\tstep5a = (step5a + xData[i]);\n\t\t\tstep7 = (step7 + yData[i]);\n\t\t}\n\t\tstep2 = (step1 * step2);\n\t\tstep3 = (step3a * step3b);\n\t\tstep4 = (step1 * step4);\n\t\tstep5 = (Math.pow(step5a, 2));\n\t\tstep6 = ((step2 - step3) / (step4 - step5));\n\t\tstep8 = (step6 * step5a);\n\t\tstep9 = ((step7 - step8) / step1);\n\n\t\t// Step 10: Plotting the trendline. Only two points are calulated.\n\t\t// The starting point.\n\t\t// This point will have values equal to the first X and Y value in the original dataset.\n\t\tlineData.push([xData[0] , yData[0]]);\n\n\t\t// Calculating the ending point.\n\t\t// The point X is equal the X in the original dataset.\n\t\t// The point Y is calculated using the function of a straight line and our variables found.\n\t\tstep10 = ( ( step6 * xData[step1 - 1] ) + step9 );\n\t\tlineData.push([ ( xData[step1 - 1] ), step10 ]);\n\n\t\treturn lineData;\n\t}",
"function getRegressionChartData(slope, y, decimal_dates, chart_data) {\n var data = [];\n var first_date = chart_data[0][0];\n var first_reg_displacement = slope * decimal_dates[0] + y;\n var last_date = chart_data[chart_data.length - 1][0];\n var last_reg_displacement = slope * decimal_dates[decimal_dates.length - 1] + y;\n data.push([first_date, first_reg_displacement]);\n data.push([last_date, last_reg_displacement]);\n return data;\n}",
"function calcLinearRegression(displacements, decimal_dates) {\n data = [];\n for (i = 0; i < decimal_dates.length; i++) {\n // data.push([displacements[i], decimal_dates[i]]);\n data.push([decimal_dates[i], displacements[i]]);\n }\n var result = regression('linear', data);\n return result;\n}",
"function RegressionLineExtension() {\n var _this;\n\n _this = _ComponentInterface.call(this) || this;\n _this._config = {\n regressionPoints: []\n };\n _this.regressionLine = [];\n return _this;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search a BookmarkNode and its children for inclusion of a given BN Returns Boolean, true if searched BN is included | function BN_includes (BN, sBN) {
let found = Object.is(BN, sBN);
if (!found && (BN.type == "folder")) {
let children = BN.children;
let len;
if ((children != undefined) && ((len = children.length) > 0)) {
for (let i=0 ; i<len ; i++) {
if (BN_includes(children[i], sBN)) {
found = true;
break;
}
}
}
}
return (found);
} | [
"function contains(a, b){\n if(a === b){\n return true;\n }\n if(a.children) {\n var n, i=0;\n while(n = a.children[i++]){\n if( contains(n, b) ) {\n return true;\n }\n }\n }\n return false;\n}",
"function contains(a, b) {\n // Return true if node a contains node b.\n while (b.parentNode) {\n b = b.parentNode;\n if (b == a) {\n return true;\n }\n }\n return false;\n}",
"function contains(a, b)\n{\n\tif(!b) return true;\n\twhile(b.parentNode)\n\t\tif((b = b.parentNode) == a) return true;\n\treturn false;\n}",
"contains(value) {\n // if the tree value matches the value passed in\n // return true\n // else\n // loop through all the children\n // call the contains method located on each child (pass the value in)\n\n // return false if not found at all\n }",
"contains(value) {\n // if the tree value matches the value passed in\n // return true\n // else\n // loop through all the children\n // call the contains method located on each child (pass the value in)\n // return false if not found at all\n }",
"function contains(a, b) {\n\twhile(a != b && (b = b.parentNode) != null);\n\treturn a == b;\n}",
"contains(value) {\n let result = false;\n const traverse = (node) => {\n if (node.value === value) result = true;\n for (let i = 0; i < node.children.length; i++) {\n traverse(node.children[i]);\n }\n };\n traverse(this);\n return result;\n }",
"function isBook() {\n var elems = document.getElementsByTagName(\"b\");\n var j = 0;\n var k = 0;\n var isBook = false;\n\n while (!isBook && j < elems.length) {\n var price = elems[j];\n k = 0;\n while (!isBook && k < price.childNodes.length) {\n var currNode = price.childNodes[k];\n if (currNode.nodeType == 3) {\n if (currNode.nodeValue == \"ISBN-10:\") {\n isBook = true;\n }\n }\n k++;\n }\n j++;\n }\n\n return isBook;\n }",
"function scanBNTree (BN, faviconWorker, doStats = true) {\r\n let type = BN.type;\r\n if (type == \"folder\") {\r\n\tlet bnId = BN.id;\r\n\tif (bnId != Root) { // Do not count Root (not visible)\r\n\t let url = BN.url;\r\n\t if (url == undefined) { // Do not count folders with url (\"place:\" special folders),\r\n\t\t\t\t\t\t\t // they are to be counted as bookmarks\r\n\t\tif (doStats)\r\n\t\t countFolders++;\r\n\t\tif (BN.title == BSP2TrashName) {\r\n\t\t bsp2TrashFldrBNId = bnId;\r\n\t\t bsp2TrashFldrBN = BN;\r\n\t\t}\r\n\t }\r\n\t else if (url.startsWith(\"place:\")) { // Remember pointers at special folders ..\r\n//BN.type = \"bookmark\";\r\n\t\tif (doStats)\r\n\t\t countBookmarks++;\r\n\t\tif (url.includes(RecentBkmkSort)) {\r\n\t\t recentBkmkBNId = bnId;\r\n\t\t recentBkmkBN = BN;\r\n\t\t}\r\n\t\telse if (url.includes(MostVisitedSort)) {\r\n\t\t mostVisitedBNId = bnId;\r\n\t\t mostVisitedBN = BN;\r\n\t\t}\r\n\t\telse if (url.includes(RecentTagSort)) {\r\n\t\t recentTagBNId = bnId;\r\n\t\t recentTagBN = BN;\r\n\t\t}\r\n\t }\r\n\t}\r\n\tlet children = BN.children;\r\n \tif (children != undefined) {\r\n\t let len = children.length;\r\n\t for (let i=0 ; i<len ;i++) {\r\n \t\tscanBNTree(children[i], faviconWorker, doStats);\r\n \t }\r\n\t}\r\n }\r\n else if (type == \"separator\") {\r\n\tif (doStats)\r\n\t countSeparators++;\r\n }\r\n else { // Presumably a bookmark\r\n\tlet bnId = BN.id;\r\n\tif (type == \"bookmark\") {\r\n\t if (bnId.startsWith(\"place:\")) { // Do not count special bookmarks under special place: folders\r\n\t\t\t\t\t\t\t\t\t // tagged with \"place:\" before their id when inserted\r\n\t\tif (!bnId.startsWith(\"place:mostVisited_\")) { \r\n\t\t // If one of recently bookmarked, try to avoid any un-needed fetches\r\n\t\t // by getting the uri directly from the original bookmark\r\n\t\t let origBnId = bnId.substring(6); // Remove \"place:\"\r\n\t\t let origBN = curBNList[origBnId];\r\n\t\t if (origBN != undefined) {\r\n\t\t\tBN.faviconUri = origBN.faviconUri;\r\n\t\t }\r\n\t\t}\r\n\t } else {\r\n\t\tif (doStats)\r\n\t\t countBookmarks++;\r\n\t }\r\n\t}\r\n\telse {\r\n\t trace(\"Odd bookmark type: \"+type);\r\n\t if (doStats)\r\n\t\tcountOddities++;\r\n\t}\r\n\tlet url = BN.url;\r\n\tif ((url == undefined) || url.startsWith(\"file:\")) { // Change nothing\r\n\t}\r\n\telse if (url.startsWith(\"about:\")) { // Change nothing also, except if protect is set unduly\r\n\t BN.protect = bnId.startsWith(\"place:\"); \r\n\t}\r\n\telse if (migration_spfldr && url.startsWith(\"place:\")) { // Change nothing also, but transform (and remember pointers) ..\r\n\t // These are now special folders, still counted as bookmarks\r\n\t BN.type = \"folder\";\r\n\t BN.fetchedUri = true; // Tell to use special favicon instead of standard folder favicon\r\n\t if (url.includes(MostVisitedSort)) {\r\n\t\tmostVisitedBNId = bnId;\r\n\t\tmostVisitedBN = BN;\r\n\t }\r\n\t else if (url.includes(RecentTagSort)) {\r\n\t\trecentTagBNId = bnId;\r\n\t\trecentTagBN = BN;\r\n\t }\r\n\t else if (url.includes(RecentBkmkSort)) {\r\n\t\trecentBkmkBNId = bnId;\r\n\t\trecentBkmkBN = BN;\r\n\t }\r\n\t}\r\n\telse if (options.disableFavicons) {\r\n\t BN.faviconUri = undefined;\r\n\t BN.fetchedUri = false;\r\n\t}\r\n\telse {\r\n\t let triggerFetch;\r\n\t let uri = BN.faviconUri;\r\n\t if ((uri == undefined) || (uri == \"/icons/waiting.gif\")) {\r\n\t\tBN.faviconUri = \"/icons/nofavicontmp.png\";\r\n\t\tBN.fetchedUri = false;\r\n\t\ttriggerFetch = true;\r\n\t\tif (doStats) {\r\n\t\t countFetchFav++;\r\n//console.log(\"countFetchFav 2: \"+countFetchFav+\" bnId: \"+bnId);\r\n\t\t}\r\n\t }\r\n\t else if (uri == \"/icons/nofavicontmp.png\") {\r\n\t\tBN.fetchedUri = false;\r\n\t\ttriggerFetch = true;\r\n\t\tif (doStats) {\r\n\t\t countFetchFav++;\r\n//console.log(\"countFetchFav 3: \"+countFetchFav+\" bnId: \"+bnId);\r\n\t\t}\r\n\t }\r\n\t else if ((url.toLowerCase().endsWith(\".pdf\")) && (uri == \"/icons/nofavicon.png\")) {\r\n\t\ttriggerFetch = false;\r\n\t\tBN.faviconUri = \"/icons/pdffavicon.png\";\r\n\t\tif (countNoFavicon > 0)\r\n\t\t countNoFavicon--;\r\n\t }\r\n\t else {\r\n\t\ttriggerFetch = false;\r\n\t\tif (uri == \"/icons/nofavicon.png\")\r\n\t\t countNoFavicon++;\r\n\t }\r\n\r\n\t if (triggerFetch && !options.pauseFavicons) { // Trigger favicon fetch, except if paused\r\n\t\t// This is a bookmark, so here no need for cloneBN(), there is no tree below\r\n//\t\tfaviconWorker.postMessage([\"get\", BN.id, BN.url, options.enableCookies]);\r\n\t\tfaviconWorker({data: [\"get\", bnId, url, options.enableCookies]});\r\n\t }\r\n\t}\r\n }\r\n}",
"function isBookmark(n) {\n return n && n.nodeType === 1 && n.classList.contains('rangySelectionBoundary');\n }",
"function isInside(childDOMnode,jDOMnode) {\n\t// early exit if invalid arguments\n\tif(!jDOMnode || !jDOMnode.length || !childDOMnode)\n\t return false;\n\t// being inside includes the case when child is at the root of the DOM tree\n\tif (jDOMnode[0] === childDOMnode)\n\t return true;\n\t// for all other cases, use parent of the root as reference\n\tvar reference = jDOMnode.parent()[0];\n\t// linear search through parent chain of child, returning true iff a parent matches our reference\n\tfor(var p = $(childDOMnode).parents(), i = 0, n = p.length, thisParent; p && n > 0 && i < n && (thisParent = p[i]); i++) {\n\t if (thisParent === reference)\n\t return true;\n\t}\n\treturn false;\n }",
"static allBookmarksAreInFolder(folderId, bookmarks) {\n let result = true;\n const filtered = bookmarks.filter(\n bookmark =>\n !Object.prototype.hasOwnProperty.call(bookmark, 'parentId') ||\n bookmark.parentId !== folderId,\n );\n if (filtered.length > 0) result = false;\n return result;\n }",
"function contains_child(parent_node, child_node_type) {\r\n\t// not yet implemented\t\r\n}",
"contains(item){\n if (item instanceof LinkItem){\n let contains = false;\n this.forEach((node) => {\n contains |= (node === item)\n })\n return contains\n }else if(item instanceof LinkList){\n let contains = false;\n item.forEach((node) => {\n contains |= this.contains(node)\n })\n return contains\n }else{\n throw `Error calling contains:\\nThe item given is not a LinkItem`\n return false\n }\n }",
"contains(value) {\n // check that node\n let containsValue = false;\n if (this.value === value) return containsValue = true;\n // check if that node has any children\n const search = (nextChildren) => {\n nextChildren.forEach((child) => {\n if (child.value === value) return containsValue = true;\n if (child.children.length) search(child.children);\n });\n };\n search(this.children);\n return containsValue;\n // if so, check those nodes\n }",
"function containsNode(_x,_x2){var _again=true;_function: while(_again) {var outerNode=_x,innerNode=_x2;_again = false;if(!outerNode || !innerNode){return false;}else if(outerNode === innerNode){return true;}else if(isTextNode(outerNode)){return false;}else if(isTextNode(innerNode)){_x = outerNode;_x2 = innerNode.parentNode;_again = true;continue _function;}else if('contains' in outerNode){return outerNode.contains(innerNode);}else if(outerNode.compareDocumentPosition){return !!(outerNode.compareDocumentPosition(innerNode) & 16);}else {return false;}}}",
"function isChildren(node, queryNode)\n {\n var parent = queryNode.parent()[0];\n while(parent)\n {\n if (parent.id() == node.id()) {\n return true;\n }\n parent = parent.parent()[0];\n }\n return false;\n }",
"function withinExcluded(node) {\n while (node) {\n if (isExcluded(node)) {\n return true;\n }\n node = node.parentNode;\n }\n}",
"contains(value) {\n let doesContain = false;\n this.children.forEach((child) => {\n // for every child, if the value is the same as the passed in\n if (child.value === value) {\n doesContain = true;\n }\n // if that node's value isn't the same as the one passed in\n // check if that child contains that value\n if (child.contains(value)) {\n doesContain = true;\n }\n });\n return doesContain;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
emptys history state of the page (window path) | function emptyState(){
history.pushState(" "," ","/");
} | [
"function clear() {\n history.length = 0;\n }",
"function clearHistory() {\n\tlinkedIn.clearHistory();\n\trender();\n}",
"function clearHistory () {\n localStorage.removeItem('palettes');\n // remove the palettes from the page\n historyMarkupDelete();\n loadHistory();\n }",
"function clearHistory() {\n chrome.storage.local.set({ viewedItems: [] }, function () {});\n chrome.storage.local.set({ searchHistory: [] }, function () {});\n clearHistoryUI();\n}",
"function clearAllEventHandler(){\n //Update URL parameters\n window.history.replaceState(null, '', '/');\n}",
"clearHistory() {\n\t\tthis.history = [];\n\t}",
"function clear_game_stack () {\n //var game_cursor = pop_story_cursor();\n //while (game_cursor > 0) {\n //game_cursor = pop_story_cursor();\n //}\n\t// Back button functionality: this function has to clear the hash now, as that is where we're keeping our game stack.\n\thistory.pushState({}, \"\", \"\");\n\tlocalStorage.setItem('save_point', \"\");\n}",
"_clearUrlState() {\n this.props.history.replace(\"/reports/app\", {data: []});\n this.props.history.state = {data: [], additionalInfo: {}};\n }",
"function resetHistory() {\n\tdoc.activeHistoryState = doc.historyStates[history];\n}",
"function clearHistory() {\n for (var i = document.getElementById(\"history-selector\").options.length - 1; i >= 0; i--) {\n document.getElementById(\"history-selector\").remove(i);\n }\n historyList = [];\n localStorage.setItem(\"history\", JSON.stringify(historyList));\n }",
"function history_clear()\n{\n\n if (local_storage)\n {\n console.log(LOG_INFORMATION + \"Clearing user search history.\");\n local_storage.clear();\n\n history_update();\n }\n}",
"clearHistory(){\n this.historyZoom.Clear();\n this.historyPalette.Clear();\n\n this.elmZoomHistoryInfo.textContent = \"0\";\n }",
"function reset() {\n history.current = history.current.slice(0, 1)\n setIndex(0)\n }",
"function history_clear()\n{\n\t// Ensure that HTML5 Local Storage is available before using it.\n\tif (local_storage)\n\t{\n\t\tconsole.log(LOG_INFORMATION + \"Clearing user search history.\");\n\t\tlocal_storage.clear();\n\n\t\t// Update user history list.\n\t\thistory_update();\n\t}\n}",
"function removeAllHistory(){\n\tindexHistory = [];\n\thistoryArray = [];\n}",
"function clearStorage(){\n localStorage.removeItem(\"local_history\")\n local_history = []\n}",
"function clearChangeHistory() {\n changeHistory = [];\n historyPosition = 0;\n }",
"function removeHash(){\r\n history.replaceState('', document.title, window.location.origin + window.location.pathname + window.location.search);\r\n }",
"function removeHash(){\n\t\thistory.pushState('', document.title, window.location.pathname);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a rectangular room with door at input.row/input.col and room in direction input.dir | rectRoom(input) {
const ROW = input.row;
const COL = input.col;
const DIR = input.dir;
} | [
"function generateRoom() {\n // If currentRoom is undefined, generate the first room\n if(currentRoom == undefined) {\n addRows(2);\n var r = new room(startRoomTypes[rndi(0,startRoomTypes.length)], 0, 0);\n roomLayout[0][0] = r;\n return r;\n }\n // Otherwise, find exit of current room and spawn a room with a corresponding entrance\n var exit = roomTypes[currentRoom.type].exit;\n if (currentRoom.row >= roomLayout.length - 2) {\n addRows(2);\n }\n var targetPosition;\n var requiredOrientation;\n var requiredHalf;\n var requiredEntrance;\n var requiredExit;\n var acceptableRoomOrientations = [\"1x1\"];\n\n switch(exit) {\n case \"north\": \n requiredEntrance = \"south\";\n targetPosition = vec(currentRoom.row + 1, currentRoom.col);\n // Add acceptable orientations\n acceptableRoomOrientations.push(\"1x2\");\n // Randomly choose an acceptable orientation\n requiredOrientation = acceptableRoomOrientations[rndi(0, acceptableRoomOrientations.length)];\n switch (requiredOrientation) {\n case \"1x1\":\n if (targetPosition.y == 0) {\n requiredExit = \"east\";\n } else {\n requiredExit = \"west\";\n }\n requiredHalf = undefined;\n break;\n case \"1x2\":\n if (targetPosition.y == 0) {\n requiredExit = \"east\";\n requiredHalf = \"left\";\n } else {\n requiredExit = \"west\";\n requiredHalf = \"right\";\n }\n break;\n }\n break;\n case \"west\":\n requiredEntrance = \"east\";\n targetPosition = vec(currentRoom.row, currentRoom.col - 1);\n // Test for acceptable orientations\n if (targetPosition.y == 1) {\n acceptableRoomOrientations.push(\"1x2\");\n } else if (targetPosition.y == 0) {\n acceptableRoomOrientations.push(\"2x1\");\n }\n // Randomly choose an acceptable orientation\n requiredOrientation = acceptableRoomOrientations[rndi(0, acceptableRoomOrientations.length)];\n switch (requiredOrientation) {\n case \"1x1\":\n if (targetPosition.y > 0) {\n requiredExit = \"west\";\n } else {\n requiredExit = \"north\";\n }\n requiredHalf = undefined;\n break;\n case \"1x2\":\n requiredExit = \"north\";\n requiredHalf = \"right\";\n break;\n case \"2x1\":\n requiredExit = \"east\";\n requiredHalf = \"bottom\";\n break;\n }\n break;\n case \"east\":\n requiredEntrance = \"west\";\n targetPosition = vec(currentRoom.row, currentRoom.col + 1);\n // Test for acceptable orientations\n if(targetPosition.y == SETTINGS.LAYOUT_WIDTH - 2) {\n acceptableRoomOrientations.push(\"1x2\");\n } else if (targetPosition.y == SETTINGS.LAYOUT_WIDTH - 1) {\n acceptableRoomOrientations.push(\"2x1\");\n }\n // Randomly choose an acceptable orientation\n requiredOrientation = acceptableRoomOrientations[rndi(0,acceptableRoomOrientations.length)];\n switch (requiredOrientation) {\n case \"1x1\":\n if (targetPosition.y < SETTINGS.LAYOUT_WIDTH - 1) {\n requiredExit = \"east\";\n } else {\n requiredExit = \"north\";\n }\n requiredHalf = undefined;\n break;\n case \"1x2\":\n requiredExit = \"north\";\n requiredHalf = \"left\";\n break;\n case \"2x1\":\n requiredExit = \"west\";\n requiredHalf = \"bottom\";\n break;\n }\n break;\n }\n\n // Adds all eligible room types to a list that we can choose from\n var eligibleRoomTypes = [];\n for(var i = 0; i < roomTypes.length; i++) {\n if (roomTypes[i].orientation == requiredOrientation && roomTypes[i].half == requiredHalf && roomTypes[i].entrance == requiredEntrance && roomTypes[i].exit == requiredExit) {\n eligibleRoomTypes.push(i);\n }\n }\n if(eligibleRoomTypes.length == 0) {\n console.log(\"Not enough eligible room types to generate room:\");\n console.log(\"Required orientation: \" + requiredOrientation);\n console.log(\"Required half: \" + requiredHalf);\n console.log(\"Required entrance: \" + requiredEntrance);\n console.log(\"Required exit: \" + requiredExit);\n return undefined;\n }\n \n // Randomly select type and fill in roomLayout\n var selectedType = eligibleRoomTypes[rndi(0, eligibleRoomTypes.length)];\n switch(roomTypes[selectedType].half) {\n case undefined:\n var r = new room(selectedType, targetPosition.x, targetPosition.y);\n roomLayout[targetPosition.x][targetPosition.y] = r;\n return r;\n case \"bottom\":\n var r = new room(selectedType, targetPosition.x, targetPosition.y);\n roomLayout[targetPosition.x][targetPosition.y] = r;\n r = new room(selectedType + 1, targetPosition.x + 1, targetPosition.y);\n roomLayout[targetPosition.x + 1][targetPosition.y] = r;\n return r;\n case \"left\":\n var r = new room(selectedType, targetPosition.x, targetPosition.y);\n roomLayout[targetPosition.x][targetPosition.y] = r;\n r = new room(selectedType + 1, targetPosition.x, targetPosition.y + 1);\n roomLayout[targetPosition.x][targetPosition.y + 1] = r;\n return r;\n case \"right\":\n var r = new room(selectedType, targetPosition.x, targetPosition.y);\n roomLayout[targetPosition.x][targetPosition.y] = r;\n r = new room(selectedType - 1, targetPosition.x, targetPosition.y - 1);\n roomLayout[targetPosition.x][targetPosition.y - 1] = r;\n return r;\n case \"top\":\n console.log(\"Should not be reachable\");\n return undefined;\n }\n \n}",
"function door(room, rowsAndCols) {\n this.char = \"D\";\n this.locations = rowsAndCols;\n this.room = room;\n this.opened = false;\n for (var i = 0; i < rowsAndCols.length; i+=2) {\n room.arr[rowsAndCols[i]][rowsAndCols[i + 1]] = this;\n }\n // opens the door, takes the room it is currently in as a parameter\n this.open = function() {\n if (!this.opened) {\n this.opened = true;\n for (var i = 0; i < this.locations.length; i+=2) {\n room.arr[this.locations[i]][this.locations[i + 1]] = null;\n }\n if (this.opposite != null) {\n this.opposite.open();\n }\n }\n }\n}",
"function generateRoom(pill) {\n // Clear the pillar array\n grphState.pillarArray = [];\n\n // If the number of requested pillars is less than the maximum calcPillarStart is used to calculate where the first pillar should be relative to the center of the screen\n if (pill < grphState.pillarNum) {\n grphState.pillarStart = calcPillarStart(pill);\n }\n\n // Otherwise they are drawn from the far left side\n else {\n grphState.pillarStart = 105;\n }\n\n // Calculating pillar coordinates for number of pillars\n for (let i = 0; i < pill; i++) {\n grphState.pillarArray.push(grphState.pillarStart + grphState.pillarWGapW * i);\n }\n\n // The location of the right hand wall is then calculated\n grphState.rWallX = calcrWallX(pill);\n}",
"placeRoom(){\n this.potentialRoom();\n\n if (this.spotEmpty() === true){\n for (let y = this.roomY; y !== this.roomY + this.roomYChange*this.currentRoomHeight; y += this.roomYChange){\n for (let x = this.roomX; x !== this.roomX + this.roomXChange*this.currentRoomWidth; x += this.roomXChange){\n this.map[y][x] = \".\";\n }\n }\n \n }\n else {\n this.pickCorridorDirectionAndLength();\n this.addCorridor();\n }\n \n }",
"createRoom(x, y, width, height) {\n for (let i = -1; i <= width; i++) {\n for (let j = -1; j <= height; j++) {\n //if i == -1 || i == width - create boundary\n if(i == -1 || i == width) {\n //if we are at the topwest corner\n if(j == -1 && i == -1) {\n this.setTile(0, x+i, y+j, 3);\n } \n //if we are at the topeast corner\n else if (i == width && j == -1) {\n this.setTile(0, x+i, y+j, 5);\n }\n //if we are at either of the vertical areas (not corners)\n else if (j >= 0 && j < height) {\n this.setTile(0, x+i, y+j, 6);\n } \n //if we are at the bottomwest corner\n else if (i == -1 && j == height) {\n this.setTile(0, x+i, y+j, 7);\n } \n //if we are at the bottomeast corner\n else if (i == width && j == height) {\n this.setTile(0, x+i, y+j, 8);\n }\n\n //set collision tile\n this.setTile(1, x+i, y+j, 1);\n }\n //if we inside the room (x-wise)\n else if (i >= 0 && i < width) {\n //if we are at the y bottom\n if (j == height) {\n this.setTile(0, x+i, y+j, 4);\n this.setTile(1, x+i, y+j, 1);\n }\n //if we are at the y top\n else if(j == -1) {\n this.setTile(0, x+i, y+j, 4);\n this.setTile(1, x+i, y+j, 1);\n } \n //else create floor\n else {\n this.setTile(0, x+i, y+j, 1);\n }\n }\n }\n }\n }",
"function createBuilding(x, y, l, w, doorWall, doorDist) {\n for (let i = 1; i < l; i++) {\n if (doorWall !== DIR_UP || doorDist !== i) {\n createWall(x + TILE_SIZE * i, y, DIR_UP, 10);\n }\n if (doorWall !== DIR_DOWN || doorDist !== i) {\n createWall(x + TILE_SIZE * i, y + TILE_SIZE * w, DIR_DOWN, 10);\n }\n }\n for (let j = 0; j <= w; j++) {\n if (doorWall !== DIR_LEFT || doorDist !== j) {\n createWall(x, y + TILE_SIZE * j, DIR_LEFT, 10);\n }\n if (doorWall !== DIR_RIGHT || doorDist !== j) {\n createWall(x + TILE_SIZE * l, y + TILE_SIZE * j, DIR_RIGHT, 10);\n }\n }\n}",
"function makeRooms(originDirection, originRoom, map) {\n // select one door direction at random for the boss room\n let directions = [];\n let newMap = [];\n let tempMap = [];\n let tileType = TILE_ROOM;\n\n var numberOfRoomBranches = 1;\n let roomCount = 0;\n if (originDirection !== null) {\n // select a random number 2-3 of room branches off each room not including orgin direction\n numberOfRoomBranches = 3;\n\n if (originDirection === NORTH) {\n directions = [EAST, SOUTH, WEST];\n } else if (originDirection === EAST) {\n directions = [WEST, SOUTH, NORTH];\n } else if (originDirection === SOUTH) {\n directions = [WEST, EAST, NORTH];\n } else if (originDirection === WEST) {\n directions = [EAST, SOUTH, NORTH];\n }\n\n } else {\n directions = [...DIRECTIONS];\n }\n\n // repeat for the number of room branches off each room\n while (roomCount < numberOfRoomBranches) {\n\n\n if (directions.length === 0) {\n return;\n }\n let randomNum = Math.floor(Math.random() * directions.length);\n var randomDirection = directions.splice(randomNum, 1)[0];\n\n\n // will hold the position object for the new room\n var newRoom = {};\n\n // new rooms will be created 11 spaces away depending on direction.\n // 1 space will be reserved for the connecting hallway\n const newRoomHeight = Math.floor(Math.random() * 10) + 10;\n const newRoomWidth = Math.floor(Math.random() * 10) + 10;\n if (randomDirection === NORTH) {\n newRoom = {\n row: originRoom.row - newRoomHeight - 1,\n col: originRoom.col,\n height: newRoomHeight,\n width: newRoomWidth\n }\n } else if (randomDirection === EAST) {\n newRoom = {\n row: originRoom.row,\n col: originRoom.col + originRoom.width + 1,\n height: newRoomHeight,\n width: newRoomWidth\n }\n } else if (randomDirection === SOUTH) {\n newRoom = {\n row: originRoom.row + originRoom.height + 1,\n col: originRoom.col,\n height: newRoomHeight,\n width: newRoomWidth\n }\n } else if (randomDirection === WEST) {\n newRoom = {\n row: originRoom.row,\n col: originRoom.col - newRoomWidth - 1,\n height: newRoomHeight,\n width: newRoomWidth,\n }\n //\n }\n\n // repeat if hollowRoom returns false\n tempMap = hollowRoom(newRoom, tileType, map);\n // if room creation is successful\n if (tempMap) {\n tempMap = attachDoor(randomDirection, originRoom, newRoom, tempMap);\n\n newMap = tempMap;\n\n makeRooms(randomDirection, newRoom, newMap);\n }\n\n roomCount++;\n\n}\n\n return newMap;\n}",
"function CreateRandomRoom()\n{\n\n var FinalXWidth;\n var FinalyHeight;\n\n var finalX;\n var finalY;\n\n var dimensionsSet = false;\n\n var FinalRoom;\n\n // we want to continue generating dimensions until we find an acceptable one\n while (!dimensionsSet)\n {\n\n // get the random location\n var x = Math.floor(Math.random()*(gridWidth - maxRoomSpace) + 1);\n\n var y = Math.floor(Math.random()*(gridHeight - maxRoomSpace) + 1);\n\n\n // we need to find out how far the room is away from the edge of the map, in both x and y directions,\n // as there has to be at least 1 tile between the walls of the room and the edge of the map\n\n var maxXValue = gridWidth - x - 1;\n var maxYValue = gridHeight - y - 1;\n\n // check if there is enough room in the x and y directions to spawn a room.\n // we also want to make sure \n if ( maxXValue >= minRoomSpace && maxYValue >= minRoomSpace)\n {\n // there is enough space here to make a 'legal' room\n // make sure we don't go above the maximum height/width of a room\n if (maxXValue > maxRoomSpace)\n {\n maxXValue = maxRoomSpace;\n }\n\n if (maxYValue > maxRoomSpace)\n {\n maxYValue = maxRoomSpace;\n }\n\n\n // determine width and height\n var width = Math.floor(Math.random()*(maxXValue - minRoomSpace + 1) + minRoomSpace);\n var height = Math.floor(Math.random()*(maxYValue - minRoomSpace + 1) + minRoomSpace);\n\n // create the room an break out of the loop\n FinalRoom = new Room(x,y,width,height);\n\n dimensionsSet = true;\n\n }\n\n\n \n\n }\n // return it!\n return FinalRoom;\n \n}",
"function expandRoom(rm){\n\t\tlet xMin = randInt(-1,0);\n\t\tlet xMax = randInt(1,2);\n\t\tlet yMin = randInt(-1,0);\n\t\tlet yMax = randInt(1,2);\n\t\tfor (let n = xMin; n < xMax; n++){\n\t\t\tfor (let p = yMin; p<yMax;p++){\n\t\t\t\tdungeon[rm.x+n][rm.y+p] = roomNum;\n\t\t\t}\n\t\t}\n\t\troomNum++;\n\t}",
"function createDoorEntrances(room, roomBoard, gameBoard, size, fakePaths) {\n let doorEntrances = [];\n\n // exits: {north: [], south: [], etc}\n if (room.exits.north) {\n let doorCoordinates = [null, null];\n //get the north room and check if it's been visited\n let foundRoom = gameBoard[room.coordinates[0] - 1][room.coordinates[1]];\n if (foundRoom.visited) {\n //exits: [{\"south\": [0,1]}]\n //for north, we want the col value, index 1\n //we want to coordinate of the first spot below the door\n doorCoordinates[0] = 0;\n doorCoordinates[1] = foundRoom.exits.south[1];\n } else {\n doorCoordinates[0] = 0;\n doorCoordinates[1] = Math.floor(Math.random() * (size - 2) + 1);\n }\n\n //add door coordinates to this room's exits\n room.exits.north = doorCoordinates;\n\n //when we change the board, we want the actual cell of the door\n roomBoard[doorCoordinates[0]][doorCoordinates[1]] = \"Door\";\n //add 1 to row for entrance below north door\n doorEntrances.push([doorCoordinates[0] + 1, doorCoordinates[1]]);\n }\n\n if (room.exits.south) {\n let doorCoordinates = [null, null];\n //get the north room and check if it's been visited\n let foundRoom = gameBoard[room.coordinates[0] + 1][room.coordinates[1]];\n if (foundRoom.visited) {\n //exits: [{\"north\": [0,1]}]\n //for north, we want the col value, index 1\n //we want to coordinate of the first spot above the door\n doorCoordinates[0] = size - 1;\n doorCoordinates[1] = foundRoom.exits.north[1];\n } else {\n doorCoordinates[0] = size - 1;\n doorCoordinates[1] = Math.floor(Math.random() * (size - 2) + 1);\n }\n\n //add door coordinates to this room's exits\n room.exits.south = doorCoordinates;\n\n roomBoard[doorCoordinates[0]][doorCoordinates[1]] = \"Door\";\n //row - 1 to have the entrance be above the door\n doorEntrances.push([doorCoordinates[0] - 1, doorCoordinates[1]]);\n }\n\n if (room.exits.east) {\n let doorCoordinates = [null, null];\n //get the north room and check if it's been visited\n let foundRoom = gameBoard[room.coordinates[0]][room.coordinates[1] + 1];\n if (foundRoom.visited) {\n //exits: [{\"west\": [0,1]}]\n //for west, we want the col value, index 1\n //we want to coordinate of the first spot left of the door\n doorCoordinates[0] = foundRoom.exits.west[0];\n doorCoordinates[1] = size - 1;\n } else {\n doorCoordinates[0] = Math.floor(Math.random() * (size - 2) + 1);\n doorCoordinates[1] = size - 1;\n }\n\n //add door coordinates to this room's exits\n room.exits.east = doorCoordinates;\n\n roomBoard[doorCoordinates[0]][doorCoordinates[1]] = \"Door\";\n //the entrance will be to the left, so col - 1\n doorEntrances.push([doorCoordinates[0], doorCoordinates[1] - 1]);\n }\n\n if (room.exits.west) {\n let doorCoordinates = [null, null];\n //get the north room and check if it's been visited\n let foundRoom = gameBoard[room.coordinates[0]][room.coordinates[1] - 1];\n if (foundRoom.visited) {\n //exits: [{\"east\": [0,1]}]\n //for east, we want the col value, index 1\n //we want to coordinate of the first spot right of the door\n doorCoordinates[0] = foundRoom.exits.east[0];\n doorCoordinates[1] = 0;\n } else {\n doorCoordinates[0] = Math.floor(Math.random() * (size - 2) + 1);\n doorCoordinates[1] = 0;\n }\n\n //add door coordinates to this room's exits\n room.exits.west = doorCoordinates;\n\n roomBoard[doorCoordinates[0]][doorCoordinates[1]] = \"Door\";\n //an entrance should be in the col + 1\n doorEntrances.push([doorCoordinates[0], doorCoordinates[1] + 1]);\n }\n\n //We are adding/subtacting 1 on doors in door array to make starting cell directing in fron to the door\n\n //always add two random fake doors, so there is more space\n while (fakePaths > 0) {\n //random between 1 and size - 1 for both indices\n let randomRow = Math.floor(Math.random() * (size - 2)) + 1;\n let randomCol = Math.floor(Math.random() * (size - 2)) + 1;\n\n doorEntrances.push([randomRow, randomCol]);\n fakePaths--;\n }\n\n return doorEntrances;\n}",
"makeMap() {\n\tlet rooms = [];\n\n\tfor (let r = 0; r < MAX_ROOMS; ++r) {\n\t // random width and height\n\t let w = this.randomInt(ROOM_MIN_SIZE, ROOM_MAX_SIZE);\n\t let h = this.randomInt(ROOM_MIN_SIZE, ROOM_MAX_SIZE);\n\n\t // random position without going outside the map boundaries\n\t let x = this.randomInt(0, MAP_WIDTH - w - 1);\n\t let y = this.randomInt(0, MAP_HEIGHT - h - 1);\n\n\t // create a new rectangle\n\t const newRoom = new Rectangle(x, y, w, h);\n\n\t // check for intersection with other rooms\n\t let didIntersect = false;\n\t for (let i = 0, l = rooms.length; i < l; ++i) {\n\t\tif (newRoom.intersect(rooms[i])) {\n\t\t didIntersect = true;\n\t\t break\n\t\t}\n\t }\n\n\t if (!didIntersect) {\n\t\tthis.createRoom(newRoom);\n\t\tconst [newX, newY] = newRoom.center();\n\t\t\n\t\tif (rooms.length === 0) {\n\t\t // player will start in first room\n\t\t this.levelStart = { x: newX, y: newY };\n\t\t } else {\n\t\t // connect to previous room with a tunnel\n\n\t\t // center of prev room\n\t\t const [prevX, prevY] = rooms[rooms.length - 1].center();\n\n\t\t if (this.randomInt(0, 1) === 1) {\n\t\t\t// first horizontal, then vertical\n\t\t\tthis.createHorizontalTunnel(prevX, newX, prevY);\n\t\t\tthis.createVerticalTunnel(prevY, newY, newX);\n\t\t } else {\n\t\t\t// first vertical, then horizontal\n\t\t\tthis.createVerticalTunnel(prevY, newY, prevX);\n\t\t\tthis.createHorizontalTunnel(prevX, newX, newY);\n\t\t }\n\t\t}\n\n\t\trooms.push(newRoom);\n\t }\n\t}\n }",
"function RandomRoomSpot(room)\n{\n\n var FinalX = 0;\n var FinalY = 0;\n\n var DoorX = 0;\n var DoorY = 0;\n\n var AlongXAxis = Math.round(Math.random());\n var AlongYAxis = Math.round(Math.random());\n\n // this one to see whther the location is in the \"first\" wall (left on the x axis) or \"second\" wall (top on the y axis)\n var WallPlacement = Math.round(Math.random()); \n // first off, see if we are going to create the door along the top/bottom or left/right wall of the room\n if (AlongXAxis)\n {\n // get a random x value along the rooms width \n FinalX = Math.floor(Math.random()*((room.x + room.width - 1) - (room.x + 1)) + (room.x + 1));\n\n // see if it's on the first or second wall\n \n if (WallPlacement)\n {\n DoorY = room.y;\n FinalY = room.y -1;\n \n }\n else\n {\n DoorY = room.y + room.height - 1;\n FinalY = room.y + room.height;\n }\n\n // also, while we are here, might as well place the door tile\n Tiles[FinalX][DoorY] = new DoorTile(FinalX,DoorY);\n \n }\n else\n {\n // get a random y value along the rooms height\n FinalY = Math.floor(Math.random()*((room.y + room.height - 1) - (room.y + 1)) + (room.y + 1));\n\n // see if it's on the first or second wall\n \n if (WallPlacement)\n {\n DoorX = room.x;\n FinalX = room.x -1;\n \n }\n else\n {\n DoorX = room.x + room.width - 1;\n FinalX = room.x + room.width;\n }\n\n // also, while we are here, might as well place the door tile\n Tiles[DoorX][FinalY] = new DoorTile(DoorX,FinalY);\n\n }\n\n /*\n // get a random x and y value from the room\n // we offset the maximum x and y values by +1, so the node is located inside the actual room, not in a wall\n var x = Math.floor(Math.random()*((room.x + room.width - 1) - (room.x + 1)) + (room.x + 1));\n var y = Math.floor(Math.random()*((room.y + room.height - 1) - (room.y + 1)) + (room.y + 1));\n*/\n // create the node that we will return\n var NewNode = new Node(FinalX,FinalY);\n \n\n return NewNode;\n}",
"function placeRooms(){\n dungeonRooms = [];\n //Constants for max/min room sizes\n const maxRooms = dungeonWidth * dungeonHeight;\n const minSize = 3;\n const maxSize = 8;\n //Attempt to create and add a new room to the dungeon\n for(let i = 0; i < maxRooms; i++){\n //Give random dimensions within limits to new room\n const w = Math.floor(Math.random() * (maxSize - minSize + 1) + minSize);\n const h = Math.floor(Math.random() * (maxSize - minSize + 1) + minSize);\n const x = Math.floor(Math.random() * (dungeonWidth - w - 1) + 1);\n const y = Math.floor(Math.random() * (dungeonHeight - h - 1) + 1);\n\n // Create new room\n let room = new Room(x, y, w, h);\n let fail = false;\n //Check if room overlaps other rooms. If it does break out of loop and attempt a new room\n for(let j = 0; j < dungeonRooms.length; j++){\n if(room.overlaps(dungeonRooms[j])){\n fail = true;\n break;\n }\n }\n //If passes, Add room to free space in dungeon\n if(!fail){\n for(let i=room.y1; i<room.y2; i++){\n for(let j=room.x1; j<room.x2; j++){\n dungeon[i][j] = 1;\n }\n }\n //Store center values to allow corridor creation between rooms\n if(dungeonRooms.length !== 0){\n let center = room.center;\n let prevCenter = dungeonRooms[dungeonRooms.length-1].center;\n vertCorridor(prevCenter.y, center.y, center.x);\n hozCorridor(prevCenter.x, center.x, prevCenter.y);\n }\n dungeonRooms.push(room)\n }\n }\n}",
"function drawRoom() {\n // Draw floor\n\n ctx.fillStyle = \"Wheat\";\n ctx.strokeStyle = \"Tan\";\n ctx.lineWidth = 3;\n ctx.fillRect(0, 0, 1000, 600);\n ctx.strokeRect(0, 0, 200, 100);\n ctx.strokeRect(200, 0, 200, 100);\n ctx.strokeRect(400, 0, 200, 100);\n ctx.strokeRect(600, 0, 200, 100);\n ctx.strokeRect(800, 0, 200, 100);\n\n ctx.strokeRect(-100, 000, 200, 100);\n ctx.strokeRect(100, 000, 200, 100);\n ctx.strokeRect(300, 000, 200, 100);\n ctx.strokeRect(500, 000, 200, 100);\n ctx.strokeRect(700, 000, 200, 100);\n ctx.strokeRect(900, 000, 200, 100);\n\n ctx.strokeRect(-100, 100, 200, 100);\n ctx.strokeRect(100, 100, 200, 100);\n ctx.strokeRect(300, 100, 200, 100);\n ctx.strokeRect(500, 100, 200, 100);\n ctx.strokeRect(700, 100, 200, 100);\n ctx.strokeRect(900, 100, 200, 100);\n\n ctx.strokeRect(0, 200, 200, 100);\n ctx.strokeRect(200, 200, 200, 100);\n ctx.strokeRect(400, 200, 200, 100);\n ctx.strokeRect(600, 200, 200, 100);\n ctx.strokeRect(800, 200, 200, 100);\n\n ctx.strokeRect(-100, 200, 200, 100);\n ctx.strokeRect(100, 200, 200, 100);\n ctx.strokeRect(300, 200, 200, 100);\n ctx.strokeRect(500, 200, 200, 100);\n ctx.strokeRect(700, 200, 200, 100);\n ctx.strokeRect(900, 200, 200, 100);\n\n ctx.strokeRect(-100, 300, 200, 100);\n ctx.strokeRect(100, 300, 200, 100);\n ctx.strokeRect(300, 300, 200, 100);\n ctx.strokeRect(500, 300, 200, 100);\n ctx.strokeRect(700, 300, 200, 100);\n ctx.strokeRect(900, 300, 200, 100);\n\n ctx.strokeRect(0, 400, 200, 100);\n ctx.strokeRect(200, 400, 200, 100);\n ctx.strokeRect(400, 400, 200, 100);\n ctx.strokeRect(600, 400, 200, 100);\n ctx.strokeRect(800, 400, 200, 100);\n\n ctx.strokeRect(-100, 400, 200, 100);\n ctx.strokeRect(100, 400, 200, 100);\n ctx.strokeRect(300, 400, 200, 100);\n ctx.strokeRect(500, 400, 200, 100);\n ctx.strokeRect(700, 400, 200, 100);\n ctx.strokeRect(900, 400, 200, 100);\n\n ctx.strokeRect(-100, 500, 200, 100);\n ctx.strokeRect(100, 500, 200, 100);\n ctx.strokeRect(300, 500, 200, 100);\n ctx.strokeRect(500, 500, 200, 100);\n ctx.strokeRect(700, 500, 200, 100);\n ctx.strokeRect(900, 500, 200, 100);\n\n // Draw languges names :\n\n ctx.font = \"20px arial\";\n\n ctx.fillStyle = \"tomato\";\n ctx.fillText(\"<= JS\", 350, 120);\n ctx.fillStyle = \"blue\";\n ctx.fillText(\"<= HTML\", 350, 320);\n ctx.fillStyle = \"limegreen\";\n ctx.fillText(\"<= CSS\", 350, 520);\n\n ctx.fillStyle = \"indogo\";\n ctx.fillText(\"Canvas =>\", 650, 120);\n ctx.fillStyle = \"darkgreen\";\n ctx.fillText(\"jQuery =>\", 650, 320);\n ctx.fillStyle = \"hotpink\";\n ctx.fillText(\"DOM =>\", 650, 520);\n\n // --Draw walls :\n ctx.fillStyle = \"maroon\";\n ctx.strokeStyle = \"brown\";\n ctx.lineWidth = 3;\n\n // Upper walls\n ctx.strokeRect(0, 0, 1000, 15);\n ctx.fillRect(0, 0, 1000, 15);\n ctx.strokeRect(0, 15, 1000, 15);\n ctx.fillRect(0, 15, 1000, 15);\n ctx.strokeRect(0, 30, 1000, 15);\n ctx.fillRect(0, 30, 1000, 15);\n\n //Downer walls\n ctx.strokeRect(0, 585, 1000, 15);\n ctx.fillRect(0, 585, 1000, 15);\n ctx.strokeRect(0, 570, 1000, 15);\n ctx.fillRect(0, 570, 1000, 15);\n ctx.strokeRect(0, 555, 1000, 15);\n ctx.fillRect(0, 555, 1000, 15);\n\n // left walls\n ctx.strokeRect(0, 0, 15, 600);\n ctx.fillRect(0, 0, 15, 600);\n ctx.strokeRect(15, 0, 15, 600);\n ctx.fillRect(15, 0, 15, 600);\n ctx.strokeRect(30, 0, 15, 600);\n ctx.fillRect(30, 0, 15, 600);\n\n // right walls\n ctx.strokeRect(985, 0, 15, 600);\n ctx.fillRect(985, 0, 15, 600);\n ctx.strokeRect(970, 0, 15, 600);\n ctx.fillRect(970, 0, 15, 600);\n ctx.strokeRect(955, 0, 15, 600);\n ctx.fillRect(955, 0, 15, 600);\n\n // draw screen\n\n ctx.fillStyle = \"DarkSlateGrey\";\n ctx.strokeStyle = \"silver\";\n ctx.lineWidth = 3;\n\n ctx.strokeRect(380, 10, 240, 95);\n ctx.fillRect(380, 10, 240, 95);\n\n ctx.fillStyle = \"black\";\n ctx.strokeStyle = \"silver\";\n ctx.strokeRect(400, 20, 200, 75);\n ctx.fillRect(400, 20, 200, 75);\n\n // Draw transfo\n\n // left\n\n ctx.fillStyle = \"DarkSlateGrey\";\n ctx.strokeStyle = \"silver\";\n ctx.lineWidth = 3;\n\n ctx.strokeRect(220, 20, 75, 30);\n ctx.fillRect(220, 20, 75, 30);\n ctx.strokeRect(220, 10, 75, 10);\n ctx.fillRect(220, 10, 75, 10);\n\n ctx.fillStyle = \"tomato\";\n ctx.fillRect(222, 12, 6, 6);\n ctx.fillStyle = \"chartreuse\";\n ctx.fillRect(230, 12, 6, 6);\n ctx.fillStyle = \"blue\";\n ctx.fillRect(238, 12, 6, 6);\n\n // rigth\n\n ctx.fillStyle = \"DarkSlateGrey\";\n ctx.strokeStyle = \"silver\";\n ctx.lineWidth = 3;\n\n ctx.strokeRect(710, 20, 75, 30);\n ctx.fillRect(710, 20, 75, 30);\n ctx.strokeRect(710, 10, 75, 10);\n ctx.fillRect(710, 10, 75, 10);\n\n ctx.fillStyle = \"chartreuse\";\n ctx.fillRect(712, 12, 6, 6);\n ctx.fillStyle = \"blue\";\n ctx.fillRect(770, 12, 6, 6);\n ctx.fillStyle = \"red\";\n ctx.fillRect(778, 12, 6, 6);\n\n // draw wires\n ctx.fillStyle = \"black\";\n ctx.strokeStyle = \"white\";\n ctx.lineWidth = 3;\n\n //left side brain\n\n ctx.strokeRect(270, 45, 5, 70);\n ctx.fillRect(270, 45, 5, 70);\n ctx.strokeRect(145, 110, 130, 5);\n ctx.fillRect(145, 110, 130, 5);\n\n ctx.strokeRect(240, 45, 5, 270);\n ctx.fillRect(240, 45, 5, 270);\n ctx.strokeRect(145, 310, 100, 5);\n ctx.fillRect(145, 310, 100, 5);\n\n ctx.strokeRect(255, 45, 5, 470);\n ctx.fillRect(255, 45, 5, 470);\n ctx.strokeRect(145, 510, 115, 5);\n ctx.fillRect(145, 510, 115, 5);\n\n //right side brain\n\n ctx.strokeRect(760, 45, 5, 70);\n ctx.fillRect(760, 45, 5, 70);\n ctx.strokeRect(760, 110, 130, 5);\n ctx.fillRect(760, 110, 130, 5);\n\n ctx.strokeRect(730, 45, 5, 270);\n ctx.fillRect(730, 45, 5, 270);\n ctx.strokeRect(730, 310, 150, 5);\n ctx.fillRect(730, 310, 150, 5);\n\n ctx.strokeRect(745, 45, 5, 470);\n ctx.fillRect(745, 45, 5, 470);\n ctx.strokeRect(745, 510, 115, 5);\n ctx.fillRect(745, 510, 115, 5);\n\n // boxes background\n\n ctx.fillStyle = \"DarkSlateGrey\";\n ctx.strokeStyle = \"white\";\n ctx.lineWidth = 3;\n\n ctx.strokeRect(50, 50, 100, 100);\n ctx.fillRect(50, 50, 100, 100);\n\n ctx.strokeRect(50, 250, 100, 100);\n ctx.fillRect(50, 250, 100, 100);\n\n ctx.strokeRect(50, 450, 100, 100);\n ctx.fillRect(50, 450, 100, 100);\n\n ctx.strokeRect(850, 50, 100, 100);\n ctx.fillRect(850, 50, 100, 100);\n\n ctx.strokeRect(850, 250, 100, 100);\n ctx.fillRect(850, 250, 100, 100);\n\n ctx.strokeRect(850, 450, 100, 100);\n ctx.fillRect(850, 450, 100, 100);\n\n // inner rects\n ctx.fillStyle = \"black\";\n ctx.strokeStyle = \"silver\";\n ctx.lineWidth = 3;\n\n // - box 1\n ctx.strokeRect(70, 70, 60, 15);\n ctx.fillRect(70, 70, 60, 15);\n ctx.strokeRect(70, 85, 60, 15);\n ctx.fillRect(70, 85, 60, 15);\n ctx.strokeRect(70, 100, 60, 15);\n ctx.fillRect(70, 100, 60, 15);\n ctx.strokeRect(70, 115, 60, 15);\n ctx.fillRect(70, 115, 60, 15);\n\n // - box 2\n ctx.strokeRect(70, 270, 60, 15);\n ctx.fillRect(70, 270, 60, 15);\n ctx.strokeRect(70, 285, 60, 15);\n ctx.fillRect(70, 285, 60, 15);\n ctx.strokeRect(70, 300, 60, 15);\n ctx.fillRect(70, 300, 60, 15);\n ctx.strokeRect(70, 315, 60, 15);\n ctx.fillRect(70, 315, 60, 15);\n\n // - box 3\n ctx.strokeRect(70, 470, 60, 15);\n ctx.fillRect(70, 470, 60, 15);\n ctx.strokeRect(70, 485, 60, 15);\n ctx.fillRect(70, 485, 60, 15);\n ctx.strokeRect(70, 500, 60, 15);\n ctx.fillRect(70, 500, 60, 15);\n ctx.strokeRect(70, 515, 60, 15);\n ctx.fillRect(70, 515, 60, 15);\n\n // - box 4\n ctx.strokeRect(870, 70, 60, 15);\n ctx.fillRect(870, 70, 60, 15);\n ctx.strokeRect(870, 85, 60, 15);\n ctx.fillRect(870, 85, 60, 15);\n ctx.strokeRect(870, 100, 60, 15);\n ctx.fillRect(870, 100, 60, 15);\n ctx.strokeRect(870, 115, 60, 15);\n ctx.fillRect(870, 115, 60, 15);\n\n // - box 5\n ctx.strokeRect(870, 270, 60, 15);\n ctx.fillRect(870, 270, 60, 15);\n ctx.strokeRect(870, 285, 60, 15);\n ctx.fillRect(870, 285, 60, 15);\n ctx.strokeRect(870, 300, 60, 15);\n ctx.fillRect(870, 300, 60, 15);\n ctx.strokeRect(870, 315, 60, 15);\n ctx.fillRect(870, 315, 60, 15);\n\n // - box 6\n ctx.strokeRect(870, 470, 60, 15);\n ctx.fillRect(870, 470, 60, 15);\n ctx.strokeRect(870, 485, 60, 15);\n ctx.fillRect(870, 485, 60, 15);\n ctx.strokeRect(870, 500, 60, 15);\n ctx.fillRect(870, 500, 60, 15);\n ctx.strokeRect(870, 515, 60, 15);\n ctx.fillRect(870, 515, 60, 15);\n}",
"function attachDoor(direction, originRoom, newRoom, map) {\n let newMap = [...map];\n let isDoorLocked = newMap[originRoom.row][originRoom.col] === TILE_BOSS_ROOM\n ? true\n : false;\n\n // all position on map where a door between the two rooms can exist\n let commonBorders = [];\n if (direction === NORTH) {\n for (let i = 0; i < originRoom.width; i++) {\n if (newMap[originRoom.row - 2][originRoom.col + i] === TILE_ROOM) {\n commonBorders.push({row: originRoom.row - 1, col: originRoom.col + i});\n }\n }\n } else if (direction === EAST) {\n for (let i = 0; i < originRoom.height; i++) {\n if (newMap[originRoom.row + i][originRoom.col + originRoom.width + 1] === TILE_ROOM) {\n commonBorders.push({row: originRoom.row + i, col: originRoom.col + originRoom.width});\n }\n }\n\n } else if (direction === SOUTH) {\n for (let i = 0; i < originRoom.width; i++) {\n if (newMap[originRoom.row + originRoom.height + 1][originRoom.col + i] === TILE_ROOM) {\n commonBorders.push({row: originRoom.row + originRoom.height, col: originRoom.col + i});\n }\n }\n\n } else if (direction === WEST) {\n for (let i = 0; i < originRoom.height; i++) {\n if (newMap[originRoom.row + i][originRoom.col - 2] === TILE_ROOM) {\n commonBorders.push({row: originRoom.row + i, col: originRoom.col - 1});\n }\n }\n }\n\n\n\n // select random location along common border to place door\n const randomLocation = commonBorders[Math.floor(Math.random() * commonBorders.length)];\n if (direction === EAST) {\n }\n if (isDoorLocked) {\n newMap[randomLocation.row][randomLocation.col] = TILE_LOCKED_DOOR;\n } else {\n newMap[randomLocation.row][randomLocation.col] = TILE_DOOR;\n }\n\n\nreturn map;\n\n}",
"function check(room, door, wall){\n var cellCount = 0;\n var x = room.x;\n var y = room.y;\n var dx = door.x;\n var dy = door.y;\n var isDoorOk = true;\n var isWallGood = true;\n var floorLoc = fillRoom(room, 'check');\n // console.log('x' + x);\n // console.log('y' + y);\n // console.log('room:');\n // console.log(room);\n // console.log('room.height ' + room.height);\n // console.log('room.width ' + room.width);\n // console.log('door.y ' + door.y);\n // console.log('door.x ' + door.x);\n // console.log('target wall ' + wall);\n \n // check where a door is being placed\n // this checks if a wall is blocking a door\n // hopefully :/\n switch (wall) {\n case '_top':\n dy--;\n if (map.grid[dy][dx].type === 'wall') {\n isDoorOk = false;\n }\n // console.log(map.grid[dy][dx].type);\n break;\n case '_bottom':\n dy++;\n if (map.grid[dy][dx].type === 'wall') {\n isDoorOk = false;\n }\n // console.log(map.grid[dy][dx].type);\n break;\n case '_left':\n dx--;\n if (map.grid[dy][dx].type === 'wall') {\n isDoorOk = false;\n }\n // console.log(map.grid[dy][dx].type);\n break;\n case '_right':\n dx++;\n if (map.grid[dy][dx].type === 'wall') {\n isDoorOk = false;\n }\n // console.log(map.grid[dy][dx].type);\n break;\n }\n // check to see if the door will be placed on a floor\n // it should only be placed in a wall\n var myDoor = dx + '-' + dy;\n if (floorLoc.indexOf(myDoor) === -1) {\n isDoorOk = false;\n }\n // x = room.x;\n // y = room.y;\n // room.isPlaced = true;\n var wallTotal = ((room.height - 2) * 2) + ((room.width) * 2);\n // console.log('wall total: ' + wallTotal);\n var xStop = x + room.width;\n var yStop = y + room.height;\n // console.log('xStop: ' + xStop);\n // console.log('yStop: ' + yStop);\n // console.log(map);\n // start is x,y coordinates\n var j, i, count = 0, top = 0, bottom = 0, left = 0, right = 0;\n for (i = y; i < yStop; i++) {\n // cellCount++;\n // console.log('y: ' + i);\n // console.log(count);\n for (j = x; j < xStop; j++) {\n // console.log('x' + map.grid[i][j].xloc + 'y' + map.grid[i][j].yloc);\n // console.log('i' + i);\n // console.log('j' + j);\n // debug\n if (map.grid[i][j] === undefined) {\n // console.log('j: ' + j);\n // console.log('i: ' + i);\n continue;\n }\n if (map.grid[i][j].type === 'door') {\n isWallGood = false;\n // console.log('hit a door');\n }\n if (map.grid[i][j].type === 'empty'){\n \n // console.log('EMPTY');\n if (i === y) {\n // top wall\n cellCount++;\n top++;\n // console.log('top');\n // console.log('x' + map.grid[i][j].xloc + 'y' + map.grid[i][j].yloc);\n }\n if (i === yStop - 1) {\n // bottom wall\n cellCount++;\n bottom++;\n // console.log('bottom');\n // console.log('x' + map.grid[i][j].xloc + 'y' + map.grid[i][j].yloc);\n }\n if (j === x && i > y && i < yStop - 1) {\n // left wall\n cellCount++;\n left++;\n // console.log('left');\n // console.log('x' + map.grid[i][j].xloc + 'y' + map.grid[i][j].yloc);\n }\n if (j === xStop - 1 && i > y && i < yStop - 1) {\n // right wall\n cellCount++;\n right++;\n // console.log('right');\n // console.log('x' + map.grid[i][j].xloc + 'y' + map.grid[i][j].yloc);\n }\n }\n }\n // count++;\n // console.log('count' + count);\n }\n // console.log('top ' + top);\n // console.log('bottom ' + bottom);\n // console.log('left ' + left);\n // console.log('right ' + right);\n // console.log('total placed ' + (top + bottom + left + right));\n // console.log('isDoorOk ' + isDoorOk);\n // console.log('isWallGood ' + isWallGood);\n var total = (cellCount/wallTotal);\n // console.log('% of room placed ' + total);\n \n if (total < 0.6){\n return false;\n } else {\n return true;\n }\n }",
"function CreateDungeon() {\n\n \n \n var numAttempts = 100; // the number of attempts that can happen. Each attempt is a potential room\n var totalAttempts = 0;\n\n // in order to generate paths in between the rooms, keep the previously created room on hand \n var previousRoom = null;\n\n for (attempts = 0; attempts < numAttempts; attempts++) { \n \n // first, create a random room at a random location\n var CurrentRoom = CreateRandomRoom();\n\n // now, check if our room overlaps with any other rooms previously created;\n var DoesOverlap = CheckIfRoomOverlaps(CurrentRoom);\n\n if (!DoesOverlap)\n {\n // the room is safe to add the the dungeon, add it to the RoomList\n RoomList.push(CurrentRoom);\n\n // add it to the grid\n RoomToGrid(CurrentRoom);\n }\n\n \n\n totalAttempts += 1;\n }\n\n // ALL the rooms had to be created first, before we created the hallways\n // otherwise, the rooms might spawn over hallways, essentially cutting them off\n // now that the rooms are created, go over each room and connect it to a previous one.\n // this will generally lead to somewhat (appearing) random and winding hallways. It's a simple method, may replace it with a better one later\n\n\n\n // first, generate the tiles neighbours\n GenerateTileNeighbours();\n\n // we create the hallways now\n RoomList.forEach(function(currentRoom) {\n // connect a passageway from this room to the previous room\n if (previousRoom != null)\n {\n CreateHallwayFromNodes(RandomRoomSpot(currentRoom),RandomRoomSpot(previousRoom));\n }\n\n previousRoom = currentRoom;\n });\n\n DrawGrid();\n\n c.stroke();\n}",
"function RoomGenerator(mat, column, row, operation){\n\n let tmpCol = column;\n let tmpRow = row;\n let axis = 0;\n let sum = 0;\n let escape = false;\n\n while(axis != 4){\n try{\n if (operation == 0){\n\n if (row === tmpRow && column === tmpCol && escape === true){\n sum = sum - 1;\n }\n if (mat[tmpCol][tmpRow] === 0 && mat[column][row] === 0)\n {\n sum = sum + 1;\n escape = true;\n }\n else\n {\n axis = axis + 1;\n tmpCol = column;\n tmpRow = row;\n }\n }\n else if (operation == 1){\n \n mat[column][row] = \"*\";\n \n if (mat[tmpCol][tmpRow] === 0 || mat[tmpCol][tmpRow] === \"*\" || mat[tmpCol][tmpRow] === \"-\") {\n mat[tmpCol][tmpRow] = \"-\";\n }\n else {\n axis = axis + 1;\n tmpCol = column;\n tmpRow = row;\n }\n }\n \n }\n catch (e) {\n axis = axis + 1;\n tmpCol = column;\n tmpRow = row;\n }\n if (axis == 0){\n tmpCol = tmpCol - 1;\n }\n else if (axis == 1){\n tmpCol = tmpCol + 1;\n }\n else if (axis == 2)\n {\n tmpRow = tmpRow - 1;\n }\n else if (axis == 3){\n tmpRow = tmpRow + 1;\n }\n else if (axis == 4)\n {\n break;\n }\n }\n if (operation == 0) {\n \n return sum;\n }else if (operation === 1) {\n return mat;\n }\n\n}",
"function createWalls(map, currentTile, roomNum) {\r\n // if n(up) does NOT have door, check if it needs a wall\r\n if (map[currentTile.x][currentTile.y].boundary.n != doorBound) {\r\n\t\t\t\t//if n is out of bounds OR it's roomnumber doesn't match {make wall}\r\n if (currentTile.y === 0 || map[currentTile.x][currentTile.y-1].roomNum != roomNum) {\r\n\t\t\t\t\t\t//make wall\r\n map[currentTile.x][currentTile.y].boundary.n = wallBound;\r\n\t\t\t\t//if it's NOT a door and shouldn't be a wall, it's open\r\n } else {\r\n\t\t\t\t\t\t//make it 'open'\r\n map[currentTile.x][currentTile.y].boundary.n = openBound;\r\n }\r\n }\r\n\t\t// if e(right) does NOT have door, check if it needs a wall\r\n if (map[currentTile.x][currentTile.y].boundary.e != doorBound) {\r\n\t\t\t//if e is out of bounds OR it's roomnumber doesn't match {make wall}\r\n if (currentTile.x >= widthCanvas-1 || map[currentTile.x+1][currentTile.y].roomNum != roomNum) {\r\n\t\t\t\t\t\t//make wall\r\n map[currentTile.x][currentTile.y].boundary.e = wallBound;\r\n\t\t\t\t//if it's NOT a door and shouldn't be a wall, it's open\r\n } else {\r\n\t\t\t\t\t\t//make it 'open'\r\n map[currentTile.x][currentTile.y].boundary.e = openBound;\r\n }\r\n }\r\n\t\t// if s(down) does NOT have door, check if it needs a wall\r\n if (map[currentTile.x][currentTile.y].boundary.s != doorBound) {\r\n\t\t\t//if s is out of bounds OR it's roomnumber doesn't match {make wall}\r\n if (currentTile.y >= heightCanvas-1 || map[currentTile.x][currentTile.y+1].roomNum != roomNum) {\r\n\t\t\t\t\t\t//make wall\r\n map[currentTile.x][currentTile.y].boundary.s = wallBound;\r\n\t\t\t\t//if it's NOT a door and shouldn't be a wall, it's open\r\n } else {\r\n\t\t\t\t\t\t//make it 'open'\r\n map[currentTile.x][currentTile.y].boundary.s = openBound;\r\n }\r\n }\r\n\t\t// if w(left) does NOT have door, check if it needs a wall\r\n if (map[currentTile.x][currentTile.y].boundary.w != doorBound) {\r\n\t\t\t//if w is out of bounds OR it's roomnumber doesn't match {make wall}\r\n if (currentTile.x === 0 || map[currentTile.x-1][currentTile.y].roomNum != roomNum) {\r\n\t\t\t\t\t\t//make wall\r\n map[currentTile.x][currentTile.y].boundary.w = wallBound;\r\n\t\t\t\t//if it's NOT a door and shouldn't be a wall, it's open\r\n } else {\r\n\t\t\t\t\t\t//make it 'open'\r\n map[currentTile.x][currentTile.y].boundary.w = openBound;\r\n }\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an MatCalendarCell for the given month. | _createCellForMonth(month, monthName) {
const date = this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), month, 1);
const ariaLabel = this._dateAdapter.format(date, this._dateFormats.display.monthYearA11yLabel);
const cellClasses = this.dateClass ? this.dateClass(date, 'year') : undefined;
return new MatCalendarCell(month, monthName.toLocaleUpperCase(), ariaLabel, this._shouldEnableMonth(month), cellClasses);
} | [
"createCalendarTable(year, month) {\n // prepare data for calendar\n this._prepareDataForCalendar(year, month);\n\n // render calendar\n this._renderCalendar();\n }",
"function MonthView(year, month, calendar) {\n this.element = document.createElement('div');\n this.element.className = 'cal-month';\n this.element.setAttribute('data-month', year + '-' + month);\n this.dayCells = [];\n\n var table = document.createElement('table');\n var part = document.createElement('thead');\n var row = document.createElement('tr');\n var cell = document.createElement('th');\n var d, i, day, className, wd;\n var cellSpan;\n\n var date = new Date(year, month - 1, 1);\n var startDay = date.getDay() - calendar.startOfWeek;\n var numDays = Calendar.getNumDays(year, month);\n\n this.startWeek = Calendar.getWeekNumber(year, month, 1);\n this.endWeek = this.startWeek + Math.ceil((numDays + startDay) / 7) - 1;\n\n var prevMonth = month - 1;\n var prevYear = year;\n if (prevMonth < 1) {\n prevMonth = 12;\n prevYear--;\n }\n var nextMonth = month + 1;\n var nextYear = year;\n if (nextMonth > 12) {\n nextMonth = 1;\n nextYear++;\n }\n var numDaysPrev = Calendar.getNumDays(year, prevMonth);\n\n if (startDay < 0) {\n startDay += 7;\n }\n\n cell.setAttribute('colspan', 7);\n cell.innerHTML = '<span class=\"cal-month-name\">' + calendar.monthSymbols[month] + '</span> <span>' + year + '</span>';\n row.appendChild(cell);\n part.appendChild(row);\n table.appendChild(part);\n\n row = document.createElement('tr');\n part.appendChild(row);\n\n for (i = 0; i < 7; i++) {\n cell = document.createElement('th');\n cell.innerHTML = calendar.shortDaySymbols[(i+calendar.startOfWeek)%7];\n row.appendChild(cell);\n }\n\n part = document.createElement('tbody');\n table.appendChild(part);\n row = null;\n\n for (day = startDay; day > 0; day--) {\n if (!row) {\n row = document.createElement('tr');\n part.appendChild(row);\n }\n cell = document.createElement('td');\n cell.innerHTML = '<span class=\"cal-day cal-day-othermonth\" id=\"cal-day-' + prevYear + '-' + (prevMonth < 10 ? '0' : '') + prevMonth + '-' + (1 + numDaysPrev - day) + '\">' + (1 + numDaysPrev - day) + '</span>';\n\n row.appendChild(cell);\n }\n\n for (day = 1; day <= numDays; day++) {\n d = (startDay + day - 1) % 7;\n\n if (d == 0) {\n row = document.createElement('tr');\n part.appendChild(row);\n }\n cell = document.createElement('td');\n className = 'cal-day';\n wd = (d + calendar.startOfWeek)%7;\n if (wd == 0 || wd == 6) {\n className += ' cal-day-weekend';\n }\n cellSpan = document.createElement('span');\n cellSpan.className = className;\n cellSpan.setAttribute('id', 'cal-day-' + year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day);\n cellSpan.innerHTML = day;\n cell.appendChild(cellSpan);\n this.dayCells.push(cellSpan);\n // cell.innerHTML = '<span class=\"' + className + '\" id=\"cal-day-' + year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day + '\">' + day + '</span>';\n row.appendChild(cell);\n }\n\n if (row) {\n d++;\n for (i = d; i < 7; i++) {\n cell = document.createElement('td');\n // cell.innerHTML = ' ';\n cell.innerHTML = '<span class=\"cal-day cal-day-othermonth\" id=\"cal-day-' + nextYear + '-' + (nextMonth < 10 ? '0' : '') + nextMonth + '-' + (1 + i - d) + '\">' + (1 + i - d) + '</span>';\n row.appendChild(cell);\n }\n }\n\n this.element.appendChild(table);\n }",
"setMonth(month) {\n return new CandyDate(Object(date_fns__WEBPACK_IMPORTED_MODULE_0__[\"setMonth\"])(this.nativeDate, month));\n }",
"function drawMonthView(month) {\n\t\t\t\t\tvar week,\n\t\t\t\t\t\tdayCur,\n\t\t\t\t\t\tday;\n\n\t\t\t\t\tcurMonth = month;\n\t\t\t\t\tdates = _h.calendarGenerator(month);\n\t\t\t\t\tdatesSplit = (dates.length === 42) ? _h.splitArr(dates, 6) : (dates.length === 28) ? _h.splitArr(dates, 4) : _h.splitArr(dates, 5);\n\n\t\t\t\t\tif (calGrid.firstChild) {\n\t\t\t\t\t\tcalGrid.innerHTML = '';\n\t\t\t\t\t}\n\n\t\t\t\t\tdates.forEach(function (itm, idx) {\n\t\t\t\t\t\t// Weeks\n\t\t\t\t\t\tif (idx === 0 || idx % 7 === 0) {\n\t\t\t\t\t\t\tweek = _h.createElem('div', 'week');\n\t\t\t\t\t\t\tcalGrid.appendChild(week);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Days\n\t\t\t\t\t\tday = _h.createElem('div', 'day', itm.getDate());\n\n\t\t\t\t\t\tif (!_h.compareMonths(itm, month)) {\n\t\t\t\t\t\t\tday.classList.add('day__out');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (_h.areDatesEqual(itm, curDay)) {\n\t\t\t\t\t\t\tday.classList.add('day__current');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (_h.isGreaterThan(itm, curDay)) {\n\t\t\t\t\t\t\tday.classList.add('sm-nodata-day');\n\t\t\t\t\t\t}\n\t\t\t\t\t\tweek.appendChild(day);\n\t\t\t\t\t});\n\n\t\t\t\t\tdayCur = calGrid.querySelector('.day__current');\n\t\t\t\t\tif (dayCur && initial) {\n\t\t\t\t\t\tdayCur.parentElement.classList.add('week__current');\n\t\t\t\t\t\tindexObj.weekIdx = _h.getIndex(calGrid.querySelectorAll('.week'), calGrid.querySelector('.week__current'));\n\t\t\t\t\t\tcurWeekSave = indexObj.weekIdx;\n\t\t\t\t\t\tinitial = !initial;\n\t\t\t\t\t}\n\t\t\t\t\tdrawMonthSlider(month);\n\t\t\t\t}",
"function createMonthGrid() {\n let monthContainer = document.createElement('div');\n monthContainer.classList.add('month-container');\n for (let i = 0; i < 42; i++) {\n let dayOfMonth = document.createElement('div');\n let numberOfDayContainer = document.createElement('div');\n let eventContainer = document.createElement('div');\n dayOfMonth.classList.add('day_box');\n numberOfDayContainer.classList.add('month_day_number');\n eventContainer.classList.add('event-container');\n dayOfMonth.appendChild(numberOfDayContainer);\n dayOfMonth.appendChild(eventContainer);\n monthContainer.appendChild(dayOfMonth);\n }\n monthSection.appendChild(monthContainer)\n }",
"function renderMonthsCal() {\n // Setup variables\n var rowCounter = 1,\n colCounter = 0,\n today = new Date(),\n dateModeHeader;\n\n // Set the calender header to the current year\n dateModeHeader = elem(\"#date-mode-header_\" + pickerCurrentPickerID);\n dateModeHeader.innerHTML = currentYear;\n\n // Loop 12 times\n for (var i = 0; i < 12; i++) {\n var currentCoords = rowCounter + \"-\" + colCounter,\n currentCalGridElem = elem(\"#months-\" + currentCoords + \"_\" + pickerCurrentPickerID);\n\n // Remove classes and set an onclick attribute\n currentCalGridElem.classList.remove(\"cal-grid-month-today\");\n currentCalGridElem.classList.remove(\"cal-grid-month-selected\");\n currentCalGridElem.setAttribute(\"onClick\", \"dateTimePicker.selectCalMonth(\" + i + \")\");\n\n // Check to see if the current month is the current selected month\n if ((i === selectedMonth) && (currentYear === selectedYear)) {\n currentCalGridElem.classList.add(\"cal-grid-month-selected\");\n }\n\n // Check to see if the current month is todays month\n if(today.getFullYear() === currentYear && today.getMonth() === i) {\n currentCalGridElem.classList.add(\"cal-grid-month-today\");\n }\n\n // Increment the row and col counters\n rowCounter = colCounter === 3 ? rowCounter += 1 : rowCounter;\n colCounter = colCounter === 3 ? colCounter = 0 : colCounter += 1;\n }\n }",
"function populateMonth(month) {\n const numberOfDay = document.querySelectorAll('.month_day_number');\n let day = 1\n for (let i = 0; i < numberOfDay.length; i++) {\n if (i < (getFirstMonthDay(year,month) - 1)) {\n numberOfDay[i].innerHTML = ''\n } else if (day <= getMonthDays(year,month)) {\n numberOfDay[i].innerHTML = day;\n\n idMonth = month + 1;\n idDay = day;\n if(idMonth < 10){\n idMonth = '0' + idMonth\n }\n if(idDay < 10){\n idDay = '0' + idDay;\n }\n\n numberOfDay[i].setAttribute('id',year + '/' + idMonth + '/' + idDay);\n let fullDateId = formatDate(new Date(`${year}/${idMonth}/${idDay}`));\n numberOfDay[i].parentNode.addEventListener('click', (event) => {\n if (event.target.classList.contains('event-container')\n || event.target.classList.contains('event-text')) return;\n showModalWithDay(fullDateId);\n });\n day++\n }\n }\n }",
"get monthView() {\n const view = RenderView.MONTH;\n const currentYear = toDateSegment(this.view).year;\n const columnCount = MONTH_VIEW.columnCount;\n const monthCount = 12;\n const totalCount = MONTH_VIEW.totalCount;\n const monthsNames = this.monthsNames;\n const before = (totalCount - monthCount) / 2;\n const startIdx = monthCount - before % monthCount;\n const after = before + monthCount;\n const months = [];\n const rows = [];\n let cell;\n let cells = [];\n for (let i = 0; i < totalCount; i += 1) {\n if (i % columnCount === 0) {\n cells = [];\n rows.push({\n cells\n });\n }\n const month = (startIdx + i) % monthCount; /* 0 for Jan, 11 for Dev */\n const year = currentYear + Math.floor((i - before) / monthCount);\n const segment = { year, month, day: 1 };\n const value = utcFormat(segment, DateFormat.yyyyMMdd);\n const idle = i < before || i >= after;\n cell = Object.assign({ view, text: monthsNames[month], value: utcFormat(segment, DateFormat.yyyyMM), idle, now: isThisMonth(value) }, this.getCellSelection(value, isSameMonth));\n cells.push(cell);\n months.push(cell);\n }\n months[0].firstDate = true;\n months[months.length - 1].lastDate = true;\n return html `${this.renderRows(rows)}`;\n }",
"function createMonths(json, month) {\n\t\tlet calendar = document.getElementById(\"calendar\");\n\t\t\t\n\t\t// Create a div for the month.\n\t\tlet monthDiv = document.createElement(\"div\");\n\t\tmonthDiv.className = \"days\";\n\n\t\t// Get info for the month.\n\t\tlet months = json.months;\n\t\tlet currMonth = months[month - 1];\n\t\tlet startDay = parseInt(currMonth[\"startDay\"]);\n\t\tlet numDays = parseInt(currMonth[\"numDays\"]);\n\t\tmonthDiv.name = \"2019 \" + currMonth[\"name\"];\n\t\tmonthDiv.id = currMonth[\"month\"];\n\n\t\t// Add preceding non-month days.\n\t\tfor (let i = 0; i < startDay; i++) {\n\t\t\tlet div = document.createElement(\"div\");\n\t\t\tmonthDiv.appendChild(div);\n\t\t}\n\t\t// Add month days.\n\t\tfor (let i = startDay; i < numDays + startDay; i++) {\n\t\t\tlet div = document.createElement(\"div\");\n\t\t\tlet num = document.createElement(\"div\");\n\t\t\tlet info = document.createElement(\"div\");\n\t\t\tnum.className = \"num\";\n\t\t\tinfo.className = \"info\";\n\t\t\tnum.innerHTML = i - startDay + 1;\n\t\t\tdiv.name = i - startDay + 1;\n\t\t\tdiv.appendChild(num);\n\t\t\tdiv.appendChild(info);\n\t\t\tdiv.onmouseover = hover;\n\t\t\tdiv.onmouseout = noHover;\n\t\t\tif (((i + startDay - 1) < day && viewMonth == month) || viewMonth > month) {\n\t\t\t\tdiv.className = \"pastDay\";\n\t\t\t} else if ((i + startDay - 1) == day && viewMonth == month) {\n\t\t\t\tdiv.className = \"today\";\n\t\t\t\tnum.className = \"numToday\";\n\t\t\t} else {\n\t\t\t\tdiv.className = \"day\";\n\t\t\t}\n\t\t\tmonthDiv.appendChild(div);\n\t\t}\n\t\tcalendar.appendChild(monthDiv);\n\t}",
"_init_month(year, month, data, dates) {\n let offset = (new Date(year, month-1, 1, 0, 0).getDay()+6-this.config.week_start)%7;\n let month_elem = this._create_elem({type: 'div', class: 'month offset-'+offset});\n if (year===dates.first_year && month<dates.first_month) month_elem.classList.add('no-data');\n let label = this._create_elem({type: 'div', class: 'month-label', child: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][month-1]});\n let days = this._create_elem({type: 'div', class: 'days'});\n let days_in_month = this._get_days_in_month(year, month);\n for (let day=1; day<=days_in_month; day++) {\n days.append(this._init_day(year, month, day, data, dates));\n }\n month_elem.append(label, days);\n return month_elem;\n }",
"createMonth() {\n // Set boundaries of month and render <Day /> components\n let startOfMonth = Moment( this.state.currentMonth + ' ' + this.state.currentYear, 'MMMM YYYY' );\n let endOfMonth = this.getEndOfMonth( this.state.currentMonth, this.state.currentYear );\n let daysInMonth = startOfMonth.daysInMonth();\n let currentDayOffset = this.state.dayOffset[startOfMonth.format( 'dddd' )];\n let previousMonth = Moment( this.state.currentMonth + ' ' + this.state.currentYear, 'MMMM YYYY' ).subtract( 1, 'months' );\n let nextMonth = Moment( this.state.currentMonth + ' ' + this.state.currentYear, 'MMMM YYYY' ).add( 1, 'months' );\n\n this.setState({\n startOfMonth: startOfMonth,\n endOfMonth: endOfMonth,\n daysInMonth: daysInMonth,\n currentDayOffset: currentDayOffset,\n previousMonth: previousMonth,\n nextMonth: nextMonth,\n }, function() {\n this.createDays();\n });\n }",
"function setCalendarMonth(month, year) {\n let calendarHeading = document.getElementById(\"monthYear\");\n calendarHeading.innerHTML = \"\";\n let text = document.createTextNode(`${monthsList[month]} ${year}`);\n calendarHeading.appendChild(text);\n}",
"function createMonthTableBody(year, month, forMiniCalendar) {\n var body = '',\n testDate = new Date(year, month, 1),\n dayOfWeek = dtfDayOfWeek[testDate.getDay()],\n endDate = new Date(year, month + 1, 1),\n endDay = dtfDayOfWeek[endDate.getDay()],\n currentRow = '',\n rowCount = 0,\n isCurrentMonth = false,\n drawnTdCount = 0,\n maxTdCount = 42;\n\n // set the end date\n if (endDay != 0)\n endDate.setDate(endDate.getDate() + (6 - endDay) + 1);\n\n // set the start date\n if (dayOfWeek != 0)\n testDate.setDate(testDate.getDate() - dayOfWeek);\n\n // render this month\n while (drawnTdCount < maxTdCount) {\n dayOfWeek = dtfDayOfWeek[testDate.getDay()];\n if (dayOfWeek == 0) {\n if (currentRow)\n body += currentRow + '</tr>';\n rowCount++;\n currentRow = '<tr>';\n }\n currentRow += '<td';\n var testMonth = testDate.getMonth();\n if (testMonth == month || forMiniCalendar) {\n if (forMiniCalendar && testMonth != month) {\n\n if (!(month == 11 && testMonth == 0) && ((month == 0 && testMonth == 11) || testMonth < month))\n currentRow += ' class=\"app-prev-month\"';\n else\n currentRow += ' class=\"app-next-month\"';\n }\n else if (currentDay.setHours(0, 0, 0, 0) == testDate.setHours(0, 0, 0, 0))\n currentRow += ' class=\"app-current-day\"';\n if (forMiniCalendar)\n currentRow += String.format(' data-cal-year=\"{0}\" data-cal-month=\"{1}\" data-cal-day=\"{2}\"', testDate.getFullYear(), testDate.getMonth(), testDate.getDate());\n currentRow += String.format('>{0}', testDate.getDate());\n }\n else\n currentRow += '> ';\n\n currentRow += '</td>';\n testDate.setDate(testDate.getDate() + 1);\n drawnTdCount++;\n if (!forMiniCalendar)\n if (testDate >= endDate)\n break;\n }\n body += currentRow;\n // flesh out rows\n while (rowCount < 6) {\n rowCount++;\n body += '<tr><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>';\n }\n return body + '';\n }",
"gotoMonth(month) {\n if (!isNaN(month)) {\n this.calendars[0].month = parseInt(month, 10);\n this.adjustCalendars();\n }\n }",
"function renderMonthlyCalendar() {\n renderControls('monthly');\n var firstDay = GetDayNameIndex(selectedYear, selectedMonth - 1, 1);\n var daysInPreviousMonth = new Date(selectedYear, selectedMonth - 1, 0).getDate();\n var daysInSelectedMonth = new Date(selectedYear, selectedMonth, 0).getDate();\n var currentDay = 1;\n var i = 0;\n var j = 0;\n for (i = 0; i < 6; i++) {\n var days;\n var row = '<tr class=\"pCalendar-bodyRow\">';\n for (j = i * 7; j < (i + 1) * 7; j++) {\n if (j < firstDay) {\n row += '<td class=\"pCalendar-disabled\"><span class=\"pCalendar-dayNumber\">' + (daysInPreviousMonth - firstDay + j + 1) + '</span></td>';\n }\n else if (currentDay > daysInSelectedMonth) {\n row += '<td class=\"pCalendar-disabled\"><span class=\"pCalendar-dayNumber\">' + (j - daysInSelectedMonth - firstDay + 1) + '</span></td>';\n }\n else {\n row += '<td class=\"pCalendar-active\" data-CellID=\"' + currentDay + '\">' +\n '<span class=\"pCalendar-dayNumber\">' + currentDay + '</span>' +\n '<div class=\"pCalendar-eventInfo\">' +\n GetCalendarEvents(new Date(selectedYear, selectedMonth - 1, currentDay)) +\n '</div>' +\n '</td>';\n currentDay++;\n }\n }\n $(divName + ' .pCalendar-Main').append(row + '</tr>');\n $('span[data-toggle=\"tooltip\"]').tooltip();\n }\n }",
"function mdCalendarMonthDirective() {\n return {\n require: ['^^mdCalendar', 'mdCalendarMonth'],\n scope: {offset: '=mdMonthOffset'},\n controller: CalendarMonthCtrl,\n controllerAs: 'mdMonthCtrl',\n bindToController: true,\n link: function(scope, element, attrs, controllers) {\n var calendarCtrl = controllers[0];\n var monthCtrl = controllers[1];\n\n monthCtrl.calendarCtrl = calendarCtrl;\n monthCtrl.generateContent();\n\n // The virtual-repeat re-uses the same DOM elements, so there are only a limited number\n // of repeated items that are linked, and then those elements have their bindings updataed.\n // Since the months are not generated by bindings, we simply regenerate the entire thing\n // when the binding (offset) changes.\n scope.$watch(function() { return monthCtrl.offset; }, function(offset, oldOffset) {\n if (offset != oldOffset) {\n monthCtrl.generateContent();\n }\n });\n }\n };\n }",
"function createMonthButton (month, year) {\r\n var d = new Date(year, month - 1);\r\n var m = d.getMonth() + 1;\r\n var y = d.getFullYear();\r\n var newButton = document.createElement('button');\r\n \r\n newButton.setAttribute('onclick', 'loadMonth(' + m + ', ' + y + ')');\r\n \r\n return newButton;\r\n}",
"function CalendarMonthCtrl($element,$scope,$animate,$q,$$mdDateUtil,$mdDateLocale){/** @final {!angular.JQLite} */this.$element=$element;/** @final {!angular.Scope} */this.$scope=$scope;/** @final {!angular.$animate} */this.$animate=$animate;/** @final {!angular.$q} */this.$q=$q;/** @final */this.dateUtil=$$mdDateUtil;/** @final */this.dateLocale=$mdDateLocale;/** @final {HTMLElement} */this.calendarScroller=$element[0].querySelector('.md-virtual-repeat-scroller');/** @type {Date} */this.firstRenderableDate=null;/** @type {boolean} */this.isInitialized=false;/** @type {boolean} */this.isMonthTransitionInProgress=false;var self=this;/**\n\t * Handles a click event on a date cell.\n\t * Created here so that every cell can use the same function instance.\n\t * @this {HTMLTableCellElement} The cell that was clicked.\n\t */this.cellClickHandler=function(){var timestamp=$$mdDateUtil.getTimestampFromNode(this);self.$scope.$apply(function(){self.calendarCtrl.setNgModelValue(timestamp);});};/**\n\t * Handles click events on the month headers. Switches\n\t * the calendar to the year view.\n\t * @this {HTMLTableCellElement} The cell that was clicked.\n\t */this.headerClickHandler=function(){self.calendarCtrl.setCurrentView('year',$$mdDateUtil.getTimestampFromNode(this));};}",
"function mdCalendarMonthDirective() {\n return {\n require: ['^^mdCalendar', 'mdCalendarMonth'],\n scope: {\n offset: '=mdMonthOffset'\n },\n controller: CalendarMonthCtrl,\n controllerAs: 'mdMonthCtrl',\n bindToController: true,\n link: function(scope, element, attrs, controllers) {\n var calendarCtrl = controllers[0];\n var monthCtrl = controllers[1];\n\n monthCtrl.calendarCtrl = calendarCtrl;\n monthCtrl.generateContent();\n\n // The virtual-repeat re-uses the same DOM elements, so there are only a limited number\n // of repeated items that are linked, and then those elements have their bindings updataed.\n // Since the months are not generated by bindings, we simply regenerate the entire thing\n // when the binding (offset) changes.\n scope.$watch(function() {\n return monthCtrl.offset;\n }, function(offset, oldOffset) {\n if (offset != oldOffset) {\n monthCtrl.generateContent();\n }\n });\n }\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ArrayRemoveRange Given an array and the start and end indices, remove values in that index range. e.g., given ([10, 20, 30, 40, 50, 60, 70], 2,4), return [10, 20, 60, 70]. Work inplace Assume the arguments passed are an array and two integers | function removeRange(arr, start, end){
// Make sure the start index is lower than the end index
[start, end] = (start > end) ? [end, start] : [start, end]
// Make sure the index range provided is valid
if ((start < 0) || (end > arr.length - 1)){
return null
} else {
for(let j = start; j <= end; j++){
for(let i = start; i < arr.length - 1; i++){
arr[i] = arr[i + 1]
}
arr.pop()
}
return arr
}
} | [
"function removeRange(arr, start, end){\n\n}",
"function remove_range(arr, idx0, idx1)\n{\n\t// this step was necessary during the loop that uses pop. using pop messed up the \n\t// array counter variable\n\tvar leng = arr.length;\n\t// idx1-idx0-1 is the number of elements to keep\n\t// shift those elements to the beginning\n\tfor(i=0; i<(idx1-idx0+1); i++) \n\t\t{arr[0+i] = arr[idx0+i];}\n\t// remove the remaining number of elements from the end of the array\n\tfor(i=idx1-idx0+1; i<leng; i++)\n\t\t{arr.pop();}\n}",
"function removeVals(array, start, end) {\n\t// let itemsTobeRemoved = [];\n\tlet newArray = [];\n\t//loop\n\tfor (let i = 0; i < start; i++) {\n\t\tnewArray.push(array[i]);\n\t}\n\tfor (let i = end + 1; i < array.length; i++) {\n\t\tnewArray.push(array[i]);\n\t}\n\tarray = newArray;\n\treturn array;\n}",
"function removeVals (arr, start, end) {\n var range = (end - start) + 1;\n arr.splice(start, range);\n return arr;\n}",
"function removeVals(arr, start, end) {\n var newArr = [];\n for (var i = 0; i < arr.length; i++) {\n if (start > i || end < i) {\n newArr.push(arr[i]);\n }\n }\n return newArr;\n}",
"function removeVals(arr, start, end) {\n\tlet newArr = [];\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tif (start > i || end < i) {\n\t\t\tnewArr.push(arr[i]);\n\t\t}\n\t}\n\treturn newArr;\n}",
"function removeVals(arr, start, end) {\n\tvar newArr = [];\n\tfor (var i = 0; i < arr.length; i++) {\n\t\tif (i < start || i > end) {\n\t\t\tnewArr.push(arr[i]);\n\t\t}\n\t}\n\treturn (newArr);\n}",
"function removeVals(arr, start, end){\n for(var i = 0; i < (arr.length - end +1); i++){\n arr[start] = arr[end +1];\n }\n for(var i = 0; i < (end - start +1); i++){\n arr.pop();\n }\n}",
"function removeVals(arr, start, end){\n for (i=0; i < (arr.length-end - 1); i++){\n arr[start +i ] = arr[end+1+i];\n }\n return arr;\n}",
"function removeVals(arr, start, end) {\n arr.splice(start, end-1 )\n return arr;\n }",
"function removeVals(arr, start, end) {\n var numpop = end - start + 1;\n for (var i = end + 1; i < arr.length; ++i) {\n var j = start;\n arr[j] = arr[i];\n ++j;\n }\n for (var num_pop = 0; num_pop < numpop; ++num_pop) {\n arr.pop();\n }\n return arr;\n}",
"function removeVals(arr, start, end) {\n for (let i = 0; i <= (end-start); ++i) {\n if (start+i < arr.length) arr[start+i] = arr[arr.length-1];\n arr.pop();\n }\n return arr;\n}",
"function filterRange(arr, min, max){\n // store array length - needed later on for decrementing array length\n var arrLength = arr.length;\n // move values between arr[min] and arr[max] to beginning of array\n for(var i = min+1, j = 0; i < max; i++, j++){\n arr[j] = arr[i];\n }\n // remove remaining values at end of array by decrementing length\n for(var j = 0; j < arrLength - (max-min-1); j++){\n arr.length--;\n }\n return arr;\n}",
"function filterRangeInPlace(){\n return function(arr, a, b){\n var len = arr.length,\n i;\n for(i = 0; i < len; i += 1){\n if( arr[i] < a || arr[i] > b){\n arr.splice(i,1);\n }\n }\n }\n }",
"remove(range) { \n for(let i = range[0]; i <= range[1]; i++){\n let position = this.rangesList.indexOf(i);\n if ( ~position ) this.rangesList.splice(position, 1);\n } \n }",
"remove(range) {\n // this.list.reduce((acc, [start, fin]) => {\n // if (range[0] < start && range[1] > fin) {\n // return acc;\n // }\n // // return acc;\n // }, []);\n this.list = this.list.reduce((acc, [start, end]) => {\n if (range[0] < start && range[1] > end) {\n return acc;\n }\n if (start < range[0] && range[1] < end) {\n acc.push([start, range[0] - 1]);\n acc.push([range[1] + 1, end]);\n } else if (range[0] <= start) {\n acc.push([range[1] + 1, end]);\n } else if (range[0] <= end) {\n acc.push([start, range[0] - 1]);\n } else {\n acc.push([start, end]);\n }\n return acc;\n }, []);\n }",
"function trimArray(array, range) {\n let newArray = [];\n for (let i = 0; i < range.length/2; i++) {\n newArray.push(array[i]);\n }\n return newArray;\n}",
"function filterRange(arr, max, min){\n for(let i=arr.length-1; i>=0; i--){\n if(arr[i] > max || arr[i] < min){\n for(let j=i; j<arr.length-1; j++){\n let temp = arr[j];\n arr[j] = arr[j+1];\n arr[j+1] = temp;\n }\n arr.pop();\n }\n }\n return arr\n}",
"function filterRange(arr,min,max){\n var i=0;\n while (i < arr.length){\n if (arr[i] > min && arr[i] < max){\n for (var j = i; j < arr.length-1; j++){\n arr[j] = arr[j+1];\n }\n i--;\n arr.length--;\n }\n i++;\n }\n return arr\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Separate subject, catalog number, and title from course string | function parseCourse(courseStr) {
// Get title
let title = null;
let index = courseStr.indexOf('-');
if (index !== -1) {
title = courseStr.slice(index + 1).trim();
courseStr = courseStr.slice(0, index).trim();
}
// Remove unnecessary whitespace
courseStr = courseStr.replace(/\s/g, '');
// Search for numbers
index = courseStr.search(/[0-9]/);
if (index === -1)
return {
subject: courseStr.toUpperCase(),
catalogNumber: '',
};
const subject = courseStr.slice(0, index).toUpperCase();
const catalogNumber = courseStr.slice(index);
return {
subject,
catalogNumber,
title,
};
} | [
"function getCourseHeader(course) {\n return course.split(' ')[0].toUpperCase()\n}",
"function getCourseName(course) {\n return course.replace(course.split(' ')[0], '').trim()\n}",
"function cleanCourse(oldCourse) {\n\t//don't use string.substr() here, because the string is much longer as expected (xml nodeValue??)\n\t//remove the \":\"\n\tvar array = oldCourse.split(\":\");\n\t\n\t//if it is a course (not a community subject..) remove the code of the course\n\tif(array[1].indexOf(\"[\") > 0) {\n\t\tarray = array[1].split(\"[\");\n\t\treturn array[0];\n\t} else {\n\t\treturn array[1];\n\t\t\n\t}\n\t\t\n}",
"function getCourseDetailsStr(ciTitle, ciSubTitle) {\n // The max amount of chars for the column.\n var maxStrLen = 80;\n var description = '';\n var subTitle = '';\n // If the CI has a subtitle and it is not the same as the title,\n // use the remaining amount of chars to create the subtitle that will be appended to the title.\n if (ciSubTitle && ciSubTitle.toLowerCase() != ciTitle.toLowerCase()) {\n description = truncateStrBeyondLen(ciTitle, 40);\n var remainingChars = maxStrLen - description.length;\n subTitle += ': ' + truncateStrBeyondLen(ciSubTitle, remainingChars);\n } else {\n description = truncateStrBeyondLen(ciTitle, maxStrLen);\n }\n return description + subTitle;\n }",
"function getCourseDescription(subject, catalogNumber, callback) {\n uwclient.get(`/courses/${subject}/${catalogNumber}.json`, function (err, res) {\n if (err) {\n console.error(err);\n return callback(err, null);\n }\n if (!Object.keys(res.data).length) return callback('No course found.', null);\n const { title, description } = res.data;\n callback(null, { subject, catalogNumber, title, description });\n });\n}",
"static cleanupCourseSlugComponents(course) {\n const cleanedCourse = { ...course };\n cleanedCourse.title = course.title.trim().split(/\\s+/).join(' ');\n cleanedCourse.school = course.school.trim().split(/\\s+/).join(' ');\n cleanedCourse.term = course.term.trim().split(/\\s+/).join(' ');\n return cleanedCourse;\n }",
"function parseSubject(subject){\n var subjectSplit = subject.indexOf(':');\n var description = subject;\n var amount = null;\n if(subjectSplit !== -1){\n amount = subject.slice(0, subjectSplit);\n description = subject.slice(subjectSplit + 1);\n }\n return {\n amount:amount,\n description: description,\n };\n}",
"function getCourseKey(str) {\n const courseName = str.match(/\\w+-\\d+-\\w+/i);\n const courseYearMatch = str.match(/(Fall|Spring|Summer) (\\d{4})/i);\n let courseKey = undefined;\n if (courseName != undefined && courseYearMatch != undefined) {\n courseKey = `${courseName}-${courseYearMatch[1]}-${courseYearMatch[2]}`;\n }\n if (courseKey == undefined) {\n // Example: Submissions for COMP 1213 (COMP-1213-Spring-2021) M01 Activity 01 (max 10 submits) -> COMP-1213-001-Fall-2021\n const courseKeyMatch = str.match(/\\w+-\\d+-\\w+-(?:Fall|Spring|Summer)-\\d{4}/i);\n if (courseKeyMatch != undefined) {\n courseKey = courseKeyMatch[0];\n }\n }\n return courseKey;\n}",
"function _getPostfix(courseName){\n return courseName.split(\" \")[1];\n}",
"function titleToIdent(title) {\n\n // Filter out unnecessory characters\n title = title.replace(/Chapter\\s*\\d*\\s*/, '');\n title = title.replace(/\\d+\\.\\d+\\.?\\d?\\s*/, '');\n title = title.replace(/-/g, ' ');\n title = title.replace(/[,\\/\\?\"']/g, '');\n\n // Convert title words to camelcase identifier\n return _.reduce(title.split(' '), function (ident, word, i) {\n return ident + (i ? word.substr(0, 1).toUpperCase() +\n word.substr(1).toLowerCase() : word.toLowerCase());\n }, '');\n }",
"function parse(url) {\n var l = url.split(\"/\");\n var start = l.indexOf(\"courses\");\n // url formats are of the form /courses/course_id/page_type/page_id\n\n var _l$slice = l.slice(start + 1, start + 3),\n _l$slice2 = _slicedToArray(_l$slice, 2),\n courseid = _l$slice2[0],\n pagetype = _l$slice2[1];\n\n return [courseid, pagetype];\n }",
"function splitStandardCourseFileName(filename) {\n a = filename.split('_');\n return {semesterCode:a[0], courseCode:a[1], sectionFullName:a[2], courseName:a[3]};\n}",
"function infoFromCourseName(courseName) {\n\n if (prtPosition != -1) {\n var prtPosition = courseName.search(\"PRT\");\n if (prtPosition == -1) prtPosition = courseName.search(\"prt\");\n\n var prtLetter = courseName.slice((prtPosition + 4), (prtPosition + 5));\n prtLetter = prtLetter.toUpperCase();\n if (prtLetter != \"A\" && prtLetter != \"B\") prtLetter = null;\n } else prtLetter = null;\n\n var lunchPosition = courseName.search(\"Lunch\");\n if (lunchPosition == -1) lunchPosition = courseName.search(\"lunch\");\n if (lunchPosition == -1) lunchPosition = courseName.search(\"LUNCH\");\n\n if (lunchPosition != -1) {\n var lunchLetter = courseName.slice((lunchPosition + 6), (lunchPosition + 7));\n lunchLetter = lunchLetter.toUpperCase();\n if (lunchLetter != \"A\" && lunchLetter != \"B\" && lunchLetter != \"C\") lunchLetter = null;\n } else lunchLetter = null;\n\n var periodPosition = courseName.search(\"Period \");\n var len = 7;\n if (periodPosition == -1) {\n periodPosition = courseName.search(\"period \");\n len = 7;\n };\n if (periodPosition == -1) {\n periodPosition = courseName.search(\"Per \");\n len = 4;\n };\n if (periodPosition == -1) {\n periodPosition = courseName.search(\"per \");\n len = 4;\n };\n if (periodPosition == -1) {\n periodPosition = courseName.search(/Per\\u002e/);\n len = 5;\n };\n if (periodPosition == -1) {\n periodPosition = courseName.search(/per\\u002e/);\n len = 5;\n };\n if (periodPosition == -1) {\n periodPosition = courseName.search(/P\\u002e/);\n len = 3;\n };\n if (periodPosition == -1) {\n periodPosition = courseName.search(/p\\u002e/);\n len = 3;\n };\n \n if (periodPosition !== -1) {\n var periodNum = courseName.slice((periodPosition + len), (periodPosition + len + 1));\n if (periodNum == NaN || periodNum == \" \" || periodNum == null) periodNum = null;\n else {\n periodNum = parseInt(periodNum, 10);\n if (periodNum < 1 || periodNum > 8) periodNum = null;\n }\n } else periodNum = null;\n\n \n var courseInfo = new Subject(courseName, periodNum, prtLetter, lunchLetter);\n return courseInfo;\n}",
"function formatSubject(subject) {\n assert.string(subject, 'subject');\n\n subject = subject\n .split(/ Reviewed by: .*/)[0]\n .split(/ Approved by: .*/)[0];\n\n if (subject.length > SUBJECT_MAX_LENGTH) {\n subject = subject.substr(0, SUBJECT_MAX_LENGTH - 3) + '...';\n }\n\n return subject;\n}",
"verifyCoursesTitleAndDescription() {\r\n\t\tcy.verifyCourseTitleAndDescription(\r\n\t\t\t\"hemanth course ( only content without vm)\",\r\n\t\t\t\"hemanth course to test data of a normal course\"\r\n\t\t);\r\n\r\n\t\tcy.verifyCourseTitleAndDescription(\r\n\t\t\t\"container course hr\",\r\n\t\t\t\"container course\"\r\n\t\t);\r\n\r\n\t\tcy.verifyCourseTitleAndDescription(\r\n\t\t\t\"Pankaj course 1\",\r\n\t\t\t\"This course is all about docker foundation\"\r\n\t\t);\r\n\r\n\t\tcy.verifyCourseTitleAndDescription(\r\n\t\t\t\"Multiple choice question course\",\r\n\t\t\t\"Multiple choice question course description\"\r\n\t\t);\r\n\r\n\t\tcy.verifyCourseTitleAndDescription(\r\n\t\t\t\"CKA/CKAD Mock Exam 2 {staging}\",\r\n\t\t\t\"CKA/CKAD Mock Exam 2 description\"\r\n\t\t);\r\n\t}",
"function getCourses(courses) {\n\tvar course_list = [];\n\t//iterate over all of the courses in the list of type\n\tfor (var i = 0; i < courses.length; i++) {\n\t\tif (courses[i].id == \"000004\") {\n\t\t\tcontinue;\n\t\t}\n\t\t//add its attributes to the string representation\n\t\tvar course = \"<b>Course ID:</b> \" + courses[i].id + \"<br />\";\n\t\tcourse += \"<b>Credits:</b> \" + courses[i].credits + \"<br />\";\n\t\tcourse += \"<b>Required:</b> \" + courses[i].required + \"<br />\";\n\t\tcourse += \"<b>Senior:</b> \" + courses[i].senior + \"<br />\";\n\t\tcourse += \"<b>Course Name:</b> \" + courses[i].name + \"<br />\";\n\t\tcourse += \"<b>Course Description:</b><br />\" + courses[i].desc + \"<br />\";\n\n\t\t//add all of the names of its prerequisites\n\t\tcourse += \"<b>Prerequisites:</b><br />\";\n\t\tvar prereqs = courses[i].prereqs;\n\t\t//no prerequisites\n\t\tif (prereqs.length == 0) {\n\t\t\tcourse += \" None<br />\";\n\t\t//has prerequisites\n\t\t} else {\n\t\t\t//get the course name of the prerequisite using its course id\n\t\t\tfor (var j = 0; j < prereqs.length; j++) {\n\t\t\t\tvar prereq = findCourse(courses, prereqs[j].id);\n\t\t\t\tcourse += \" \" + prereq.name + \"<br />\";\n\t\t\t}\t\t\t\n\t\t}\n\n\t\tcourse_list.push(course);\n\t}\n\n\treturn course_list;\n}",
"function getFullCourseName(courseName) {\r\n return courseName.concat(\" \", capitalise(getCourseType())).trim();\r\n}",
"function getCourseInfo(windowURL){\n var partialURL = getAssetURL(windowURL, 'partial');\n var courseInfo = {};\n \n // get the part from the colon to the first +\n partialURL = partialURL.split(':')[1];\n courseInfo.institution = partialURL.split('+')[0];\n courseInfo.id = partialURL.split('+')[1];\n courseInfo.run = partialURL.split('+')[2];\n \n return courseInfo;\n\n }",
"function getCourseInfo(course) {\n const courseInfo = {\n image: course.querySelector('img').src,\n title: course.querySelector('h4').textContent,\n price: course.querySelector('.price span').textContent,\n id: course.querySelector('a').getAttribute('data-id')\n }\n\n //Insert course info object into shopping cart\n addIntoCart(courseInfo);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function para criar o lembrete | function criarLembrete(){
var conteudoTextArea = document.getElementById("texto").value;
if(!textoValido(conteudoTextArea)){
mostrarError();
}
limparError();
// criar as variaveis para tempo
var referencia = new Date();
var id = referencia.getTime();
var data = referencia.toLocaleDateString();
var texto = conteudoTextArea;
//JSON
var recordatorio = {"id": id, "data": data,"texto": texto};
//função para comprovar se existe lembrete
comprovarRecordatorio(recordatorio);
} | [
"function Literature(title, filename, txt) {\n this.title = title;\n this.fn = filename;\n this.txt = txt;\n}",
"function ajouterLacune() {\n\n\t// Déterminer l'éditeur\n\ted = $('#item_solution').tinymce();\n\t\n\t// Obtenir le contenu sélectionné\n\tlacuneTexte = ed.selection.getContent({format : 'text'});\n\t\n\t// Si du texte est sélectionné, action... sinon on ne fait rien\n\tif (lacuneTexte != \"\") {\n\n\t\t// Obtenir le html de la lacune\n\t\tlacune = ed.selection.getContent({format : 'text'});\n\t\tjournaliser(\"ajouterLacune() sélection : '\" + lacune + \"'\");\n\n\t\t// Déterminer la lacune en cours de modification\n\t\tjournaliser(\"ajouterLacune() lacuneOuverteDansEditeur : '\" + lacuneOuverteDansEditeur + \"'\");\n\t\t\n\t\t// Obtenir l'id de la lacune, au besoin créer un nouvel id\n\t\tif (lacuneOuverteDansEditeur == \"\" || lacuneOuverteDansEditeur == \"0\") {\n\t\t\t\n\t\t\t// Obtenir le prochain id\n\t\t\tnoLacune = nbLacunes + 1;\n\t\t\tidLacune = \"lacune_\" + noLacune; \n\t\t\tjournaliser(\"ajouterLacune() Générer un nouveau id lacune : '\" + idLacune + \"'\");\n\t\t\t\n\t\t} else {\n\t\t\tidLacune = lacuneOuverteDansEditeur;\n\t\t\tjournaliser(\"ajouterLacune() Utiliser la lacune ouverte dans l'éditeur : '\" + idLacune + \"'\");\n\t\t}\n\t\t\n\t\t// Noter comme la lacune ouverte dans l'éditeur\n\t\tlacuneOuverteDansEditeur = idLacune;\n\t\t\n\t\t// Créer la lacune\n\t\tjournaliser(\"ajouterLacune() Utiliser la lacune suivante pour créer le span : '\" + idLacune + \"'\");\n\t\tlacuneHTML = \"<span id='lacune_9999' class='lacune-glisser-deposer'>\" + lacune + \"</span>\"; \n\t\t\n\t // Récupérer le node\n\t\tif (lacune != \"\") {\n\t\t\t// 1. Via sélection si possible\n\t\t\tjournaliser(\"ajouterLacune() Obtenir le node via selection\");\n\t\t\tnode = ed.selection.getNode();\t\n\t\t} else {\n\t\t\t// 2. Sinon via le DOM\n\t\t\tnode = obtenirNodeEditeur(idLacune);\n\t\t\tjournaliser(\"ajouterLacune() Obtenir le node via DOM\");\n\t\t}\n\n\t\t// Ajouter le HTML\n\t\ted.selection.setContent(lacuneHTML);\n\t\t\n\t\t// Envoi du formulaire au serveur\n\t\tflagModifications = false;\n\t\tdocument.frm.lacune_texte.value = lacune;\n\t\tdocument.frm.lacune.value = idLacune\n\t\tdocument.frm.demande.value = \"item_ajouter_lacune\";\n\t\tdocument.frm.submit();\n\t}\n}",
"function startNewWord() {\n\t\tif(word.parts.length > 0) {\n\t\t\tword.spacesBefore = (line.words.length > 0) ? 1 : 0;\n\t\t\tline.words.push(word);\n\t\t\tword = new CCUI.RichWord();\n\t\t}\n\t}",
"static wordlist() {\n if (wordlist == null) {\n wordlist = new LangEn();\n }\n return wordlist;\n }",
"function createWord(word,title){\n words.push({\n 'word' : word,\n 'title' : title\n });\n }",
"function startNewMode(mode, lexeme) {\n var node\n\n if (mode.className) {\n node = build(mode.className, [])\n }\n\n if (mode.returnBegin) {\n modeBuffer = ''\n } else if (mode.excludeBegin) {\n addText(lexeme, currentChildren)\n\n modeBuffer = ''\n } else {\n modeBuffer = lexeme\n }\n\n /* Enter a new mode. */\n if (node) {\n currentChildren.push(node)\n stack.push(currentChildren)\n currentChildren = node.children\n }\n\n top = Object.create(mode, {parent: {value: top}})\n }",
"function startNewMode(mode, lexeme) {\n var node\n\n if (mode.className) {\n node = build(mode.className, [])\n }\n\n if (mode.returnBegin) {\n modeBuffer = ''\n } else if (mode.excludeBegin) {\n addText(lexeme, currentChildren)\n\n modeBuffer = ''\n } else {\n modeBuffer = lexeme\n }\n\n // Enter a new mode.\n if (node) {\n currentChildren.push(node)\n stack.push(currentChildren)\n currentChildren = node.children\n }\n\n top = Object.create(mode, {parent: {value: top}})\n }",
"function startNewMode(mode, lexeme) {\n var node;\n\n if (mode.className) {\n node = build(mode.className, []);\n }\n\n if (mode.returnBegin) {\n modeBuffer = EMPTY;\n } else if (mode.excludeBegin) {\n addText(lexeme, currentChildren);\n\n modeBuffer = EMPTY;\n } else {\n modeBuffer = lexeme;\n }\n\n /* Enter a new mode. */\n if (node) {\n currentChildren.push(node);\n stack.push(currentChildren);\n currentChildren = node.children;\n }\n\n top = Object.create(mode, {parent: {value: top}});\n }",
"function createStory() {\n individualStory = document.createElement(\"li\");\n individualStory.className = \"item\";\n}",
"function startNewMode(mode, lexeme) {\n\t var node;\n\t\n\t if (mode.className) {\n\t node = build(mode.className, []);\n\t }\n\t\n\t if (mode.returnBegin) {\n\t modeBuffer = EMPTY;\n\t } else if (mode.excludeBegin) {\n\t addText(lexeme, currentChildren);\n\t\n\t modeBuffer = EMPTY;\n\t } else {\n\t modeBuffer = lexeme;\n\t }\n\t\n\t /* Enter a new mode. */\n\t if (node) {\n\t currentChildren.push(node);\n\t stack.push(currentChildren);\n\t currentChildren = node.children;\n\t }\n\t\n\t top = Object.create(mode, {parent: {value: top}});\n\t }",
"function createWordConverterArguments(nodes) {\n return {\n nodes: nodes,\n currentIndex: 0,\n lists: {},\n listItems: [],\n currentListIdsByLevels: [LevelLists_1.createLevelLists()],\n lastProcessedItem: null,\n };\n}",
"function createWordConverter() {\n return {\n nextUniqueId: 1,\n numBulletsConverted: 0,\n numNumberedConverted: 0,\n wordConverterArgs: null,\n customData: CustomData_1.createCustomData(),\n };\n}",
"addWord(word_string, x, y, horizontal, label, clue_string, entrytime, player) {\n let word = new Word(word_string, x, y, label, horizontal, clue_string, entrytime, player);\n //console.log(word);\n this.words.push(word);\n this.update();\n // console.log(label, horizontal?'across':'down',':', clue_string);\n // console.log('total words:', this.words.length);\n return word;\n }",
"static wordlist() {\n if (wordlist == null) {\n wordlist = new LangPt();\n }\n return wordlist;\n }",
"function initLesson(){\n // Opening Lessons Database\n openDataBaseAndCreateTable('lessons');\n}",
"function newWord() {\n wordToGuess = compChoices();\n myInstrument = new Word(wordToGuess);\n}",
"function createLecture(req, res) {\n\t// The id of the note to transform, needs to be changed to real variable later with param\n\tvar paramId = req.param('guid');\n\tif(paramId) {\t\n\t\tconsole.log('paramID: ');\n\t\tconsole.log(paramId);\n\t\tNote.find({id: paramId}, function (err, notes) {\n\t\t\tif (err) return console.error(err);\n\t\t \t\n\t\t \tvar note = notes[0];\n\t\t\tvar parsedContent = parser.noteToLecture(note.content); \t// Parsed content. See parser.js\n\t\t\t\n\t\t\tvar dbLecture = new Lecture(); \t\t\t// Lecture to be saved in DB\n\t\t\t\n\t\t\tdbLecture.title = note.title;\n\t\t\tdbLecture.authors.push(note.author);\t// Add note author to list of authors\n\t\t\t\n\t\t\tfor (var i = 0; i < parsedContent.length; i++) {\n\t\t\t\tvar nodeContent = parsedContent[i];\n\t\t\t\tvar node = {\n\t\t\t\t\tcontent : nodeContent,\n\t\t\t\t\tscore \t: 0,\n\t\t\t\t\tauthor \t: note.author\n\t\t\t\t}\n\t\t\t\tdbLecture.sections.push(node);\n\t\t\t}\n\t\t\t\n\t\t\tvar userId = req.session.edamUserId;\n\t\t\tmongo.saveLecture(dbLecture, userId, function() {\n\t\t\t\tconsole.log('dbLecture');\n\t\t\t\tconsole.log(dbLecture);\n\t\t\t\tres.json(dbLecture._id);\n\t\t\t});\n\t\t});\n\t}\n\telse\n\t\tres.json('error: please specify guid in url request');\n}",
"'creationListe'(texte, idUtilisateur){\n check(texte, String);\n check(idUtilisateur, String);\n let ajout = Listes.insert({\n text: texte,\n createur: idUtilisateur\n });\n return ajout\n }",
"function createGrammar(){\n for (var i = 1; i < 6; i++) {\n //pushing 100 words for each syllable type in the grammar\n for (var j = 0; j < 100; j++) {\n grammarJSON[\"<\"+i+\">\"].push(RiTa.randomWord(i))\n }\n }\n rg = new RiGrammar()\n rg.load(grammarJSON)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Floating Bar End Floating Bar Start | function upload_floatingbar(floatingbar,top_button,bottom_button, h)
{
if($(floatingbar))
{
$(document).scroll(function() {
if($(top_button).position())
{
if(parseFloat($(top_button).position().top) < parseFloat($(window).scrollTop()))
{
$(floatingbar).css({height: 0}).animate({ height: h}, 40);
}
else
{
$(floatingbar).animate({ height: 0}, 40);
}
}
});
}
} | [
"floatDrawer() {\n this.__isFloating = true;\n }",
"function updateFloatingBar(floatingBar){\n var floatingBarTop = $(floatingBar).offset().top;\n var floatingBarHeight = $(floatingBar).outerHeight();\n monthBarsStat = updateMonthBarsStat();\n monthBarsTop = monthBarsStat[0];\n monthBarsContent = monthBarsStat[1];\n\n // show floatingbar when it is below monthbar1\n if (floatingBarTop >= monthBarsTop[0]){\n $(floatingBar).css({'z-index': 10});\n }else{\n $(floatingBar).css({'z-index': -1});\n }\n\n // change floatingbar content accordingly\n console.log('floatingBarTop: %f, monthBarstop: [%s]', floatingBarTop, monthBarsTop.toString());\n for(var i = monthBarsTop.length - 1; i >= 0; i--){\n if(floatingBarTop >= monthBarsTop[i] - floatingBarHeight){\n console.log('%f in [%f, %f]', floatingBarTop, monthBarsTop[i], monthBarsTop[i + 1]);\n $(floatingBar).html(monthBarsContent[i]);\n break;\n }\n }\n}",
"function barShow(){\n let barX = bgLeft + 800;\n fill(127);\n noStroke();\n rectMode(CORNER);\n\n for(let i = 0; i < 9; i++){\n rect(barX, bar.y, bar.sizeX, bar.sizeY);\n barTouch(barX,bar.sizeY,bar.y);\n barX += 600;\n\n }\n if(bar.sizeY <= bottom && bar.sizeY > cieling){\n shouldGrow();\n }\n\n else if(bar.sizeY <= cieling && bar.sizeY < bottom){\n shouldShrink();\n }\n else if(bar.sizeY == 0){\n cieling = -496;\n }\n}",
"function addBar(){\n\tcreateBar()\n\n\tif(!started){\n\t\tstartNextBar()\n\t}\n\n}",
"barShow(){\n let x = this.bgLeft + 800;\n let y = this.y;\n for (let i = 0; i < metalBars.length; i++){\n let bar = metalBars[i];\n bar.display(x,y, bar.width, bar.height);\n bar.barTouch(stealer);\n x += 600;\n if(bar.height <= bottom && bar.height > cieling){\n bar.grow();\n }\n else if(bar.height <= cieling && bar.height < bottom){\n bar.shrink();\n }\n else if(bar.height == 0){\n cieling = -496;\n }\n }\n }",
"toggleBar() {\n if (this.isOverflown(this.ctn)) {\n this.bar.style.display = 'block';\n } else {\n this.bar.style.display = 'none';\n }\n }",
"drawBar(){\n noStroke();\n fill(this.eColor);\n rect(-5, this.y, 820, 70);\n\n\n }",
"function updateFg(){\n var length = (self.data.value - self.data.min + 0.01) / (self.data.max - self.data.min) * self.data.length;\n fg.setAttribute(\"width\", length);\n\n if(fg.anchor == \"l\"|| fg.anchor == \"left\"){\n let x = length/2 - self.data.length/2;\n fg.setAttribute(\"position\", x + \" 0 0.003\");\n }\n else if(fg.anchor == \"r\"|| fg.anchor == \"right\"){\n let x = self.data.length/2 - length/2;\n fg.setAttribute(\"position\", x + \" 0 0.003\");\n }\n }",
"function addBar() {\n taskBarView();\n appMenuView();\n taskBarLogic();\n }",
"function handleScrollBar(){\n gsap.to(bar , { y: distance , opacity:1 , ease : 'power2' })\n}",
"updateFuelBar() {\n this.fuelBar.mask.x -= this.fuelDrain;\n if (this.fuelBar.mask.x <= -47) {\n this.scrollSpeed -= 20;\n }\n }",
"function fbar() { \n\tvar aux=barText.split(\";\");\n\tfor (var i=0;i<aux.length;i++) {\n\t bar[i]=aux[i].split(\",\");\n\t _xbar=Math.min(_xbar,bar[i][0],bar[i][2]);\n\t xbar_=Math.max(xbar_,bar[i][0],bar[i][2]);\n\t _ybar=Math.min(_ybar,bar[i][1],bar[i][3]);\n\t ybar_=Math.max(ybar_,bar[i][1],bar[i][3]);\n\t}\n\t\n }",
"checkIfNeedsLastBar() {\n\t\tif (this.cell !== 15)\n\t\t\treturn;\n\t\tif (!this.closebar)\n\t\t\treturn;\n\t\tlet curCell = this.cells[this.cell];\n\t\tvar bar = document.createElement(\"irr-rbar\");\n\t\tbar.classList.add(\"Single-Barline\");\n\t\tcurCell.insertBefore(bar, curCell.firstChild);\t// must insert, not append, for correct positioning\n\t}",
"function openNumberBar() {\r\n\t\t\tnrBarHeight = innerBar.offsetHeight;\r\n\t\t\tnrBar.style.marginTop = -nrBarHeight + 'px';\r\n\r\n\t\t\t// Check whether the bar is opened or not and perform show/hide action\r\n\t\t\tif (aUtils.hasClass(nrBar, 'rj-bar-hidden')) {\t\r\n\t\t\t\tnrBar.style.marginTop = 0;\r\n\t\t\t\taUtils.removeClass(nrBar, 'rj-bar-hidden');\r\n\t\t\t} else if (!aUtils.hasClass(nrBar, 'rj-bar-hidden')) {\r\n\t\t\t\tnrBar.style.marginTop = -nrBarHeight + 'px';\r\n\t\t\t\taUtils.addClass(nrBar, 'rj-bar-hidden');\r\n\t\t\t}\r\n\t\t}",
"function rightSideBarIn(){\n inVal += 0.035;\n let val = (21.333)*Math.sin(inVal )+(62);\n let val1 = 83.3333333333 - val;\n document.getElementById('MAP_MARKERS').style.width = val+\"%\";\n document.getElementById('STEPS').style.width = val+\"%\";\n document.getElementById('hide').style.width = val1+\"%\";\n if(val >= 83.1){\n inVal =0;\n document.getElementById('MAP_MARKERS').style.width = \"83.3333333333%\";\n document.getElementById('overlay').style.width = \"83.3333333333%\";\n document.getElementById('STEPS').style.width = \"83.3333333333%\";\n document.getElementById('hide').style.width = \"0%\";\n clearInterval(rightSideBarTimerIn);\n rightSideBarTimerIn = undefined;\n }\n }",
"function ShowBars() {\n var lifeRemaining = 100 - (getPercentage(age, lifeExpectancy) +\n getPercentage(effLifeRemaining, lifeExpectancy));\n\n //show bar 1 (green) - use callbacks to stop synchrnous filling of bars\n function ShowBar1(callback) {\n var x1 = 0;\n var y1;\n progressBar2.setAttribute(\"style\", \"width: 0%\");\n progressBar3.setAttribute(\"style\", \"width: 0%\");\n //use SetInterval to fill bar\n var test = setInterval(function() {\n x1 += 1;\n y1 = \"width: \" + x1.toString() + \"%\";\n progressBar1.setAttribute(\"style\", y1);\n progressTxt1.textContent = x1.toString() +\n \"%\";//show percentage\n if (x1 === getPercentage(age,\n lifeExpectancy)) {\n clearInterval(test);//bar stops filling\n callback();\n }\n }, 50);//fill bar in 50 ms\n }\n //show bar 2 then show bar 3, utilise setInterval and callbacks\n function ShowBar2() {\n var x2 = 0;\n var y2;\n var test2 = setInterval(function() {\n x2 += 1;\n y2 = \"width: \" + x2.toString() + \"%\";\n progressBar2.setAttribute(\"style\", y2);\n progressTxt2.textContent = x2.toString() +\n \"%\";\n if (x2 === getPercentage(effLifeRemaining,\n lifeExpectancy)) {\n clearInterval(test2);\n var x3 = 0;\n var y3;\n var test3 = setInterval(function() {\n x3 += 1;\n y3 = \"width: \" + x3.toString() +\"%\";\n progressBar3.setAttribute(\"style\", y3);\n progressTxt3.textContent =\n x3.toString() + \"%\";\n if (x3 == lifeRemaining) {\n clearInterval(test3);\n }\n }, 50);\n }\n }, 50);\n }\n ShowBar1(ShowBar2); //callback - show bar 2 after bar 1\n }",
"makeBar() {\r\n const percentage = this.timeLeft / this.MAX_TIME;\r\n const progress = Math.round((this.BAR_SIZE * percentage));\r\n const emptyProgress = this.BAR_SIZE - progress;\r\n const progressText = '▇'.repeat(progress);\r\n const emptyProgressText = ' '.repeat(emptyProgress);\r\n const bar = '```' + this.DISP_TEXT + '\\n' + progressText + emptyProgressText + '```';\r\n return bar;\r\n }",
"getStartFaade() {\n return (this.props.horizontal ?\n <LinearGradient\n start={{ x: this.props.isRtl ? 0 : 1, y: 0 }} end={{ x: this.props.isRtl ? 1 : 0, y: 0 }}\n style={[{ position: 'absolute', start: 0, width: this.props.fadeSize, height: '100%' }, this.props.startFadeStyle]}\n colors={this.props.fadeColors}\n pointerEvents={'none'}\n /> :\n <LinearGradient\n start={{ x: 0, y: 1 }} end={{ x: 0, y: 0 }}\n style={[{ position: 'absolute', top: 0, width: '100%', height: this.props.fadeSize }, this.props.startFadeStyle]}\n colors={this.props.fadeColors}\n pointerEvents={'none'}\n />\n )\n }",
"static EndVertical() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update numReplies for the parent post's codemark, if any | async updateParentCodemark () {
if (!this.parentPost.get('codemarkId')) {
return;
}
const codemark = await this.request.data.codemarks.getById(this.parentPost.get('codemarkId'));
if (!codemark) { return; }
const now = Date.now();
const op = {
$set: {
numReplies: (codemark.get('numReplies') || 0) + 1,
lastReplyAt: now,
lastActivityAt: now,
modifiedAt: now
}
};
// handle any followers that need to be added to the codemark, as needed
await this.handleFollowers(codemark, op);
this.transforms.updatedCodemarks = this.transforms.updatedCodemarks || [];
const codemarkUpdate = await new ModelSaver({
request: this.request,
collection: this.data.codemarks,
id: codemark.id
}).save(op);
this.transforms.updatedCodemarks.push(codemarkUpdate);
} | [
"async updateGrandParentPost () {\n\t\tif (!this.grandParentPost) { return; }\n\t\tconst op = { \n\t\t\t$set: {\n\t\t\t\tnumReplies: (this.grandParentPost.get('numReplies') || 0) + 1,\n\t\t\t\tmodifiedAt: Date.now()\n\t\t\t} \n\t\t};\n\t\tthis.transforms.grandParentPostUpdate = await new ModelSaver({\n\t\t\trequest: this.request,\n\t\t\tcollection: this.data.posts,\n\t\t\tid: this.grandParentPost.id\n\t\t}).save(op);\n\t}",
"async updateParentPost () {\n\t\tconst op = { \n\t\t\t$set: {\n\t\t\t\tnumReplies: (this.parentPost.get('numReplies') || 0) + 1,\n\t\t\t\tmodifiedAt: Date.now()\n\t\t\t} \n\t\t};\n\t\tthis.transforms.postUpdate = await new ModelSaver({\n\t\t\trequest: this.request,\n\t\t\tcollection: this.data.posts,\n\t\t\tid: this.parentPost.id\n\t\t}).save(op);\n\t}",
"function updateCount(appDirectory,openerObj,parentOIDs){\n\t\tvar objectIds = getObjectsToBeModified(openerObj,parentOIDs);\n\t\t var objectIdArray = Object.keys(objectIds);\n\t\t for (var i = objectIdArray.length-1; i >= 0; i--) {\n\t\t\t var updatedLabel = getUpdatedLabel(appDirectory,objectIdArray[i],openerObj);\n\t\t\t \n\t\t\t openerObj.changeObjectLabelInTree(objectIdArray[i], updatedLabel, true, false, false);\n\t\t }\n\t}",
"async updateParentCodeError () {\n\t\tif (!this.codeError) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst now = Date.now();\n\t\tconst op = { \n\t\t\t$set: {\n\t\t\t\tnumReplies: (this.codeError.get('numReplies') || 0) + 1,\n\t\t\t\tlastReplyAt: now,\n\t\t\t\tlastActivityAt: now,\n\t\t\t\tmodifiedAt: now\n\t\t\t}\n\t\t};\n\n\t\t// handle any followers that need to be added to the code error, as needed\n\t\tawait this.handleFollowers(this.codeError, op, { ignorePreferences: true });\n\n\t\tthis.transforms.updatedCodeErrors = this.transforms.updatedCodeErrors || [];\n\t\tconst codeErrorUpdate = await new ModelSaver({\n\t\t\trequest: this.request,\n\t\t\tcollection: this.data.codeErrors,\n\t\t\tid: this.codeError.id\n\t\t}).save(op);\n\t\tthis.transforms.updatedCodeErrors.push(codeErrorUpdate);\n\t}",
"updateTotalReplies(state, reply) {\n if (reply && !!reply.commentId) {\n const commentIndex = state.comments.findIndex(comment => comment.id === reply.commentId)\n if (commentIndex > -1) {\n state.comments.splice(commentIndex, 1, { ...state.comments[commentIndex], totalReplies: (state.comments[commentIndex].totalReplies || 0) + 1 })\n }\n }\n }",
"function updateReplyCounter(e){\n\t\tvar commentReplyOriginal = e.target.parentNode.parentNode.parentNode.parentNode.previousSibling.previousSibling.childNodes[3].innerHTML;\n\t\tvar splitString = commentReplyOriginal.split(\" \");\n\t\tif (splitString[0] === \"Reply\"){\n\t\t\tvar addedReplyNum = 1\n\t\t\treturn addedReplyNum\n\t\t}\n\t\telse {\n\t\t\tvar replyNum = parseInt(splitString[0]);\n\t\t\tvar addedReplyNum = replyNum + 1;\n\t\t\treturn addedReplyNum;\n\t\t}\n\t}",
"function updateComments(){\n \n let numberOfComments = 0;\n\n for (let index = 0; index < posts.length; index++) {\n const post = posts[index];\n \n for (let j = 0; j < post['comments'].length; j++) {\n const element = post['comments'];\n numberOfComments += 1; \n }\n }\n\n document.getElementById('badge').innerText = numberOfComments;\n}",
"checkParentPost (callback) {\n\t\tthis.doApiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'get',\n\t\t\t\tpath: '/posts/' + this.nrCommentResponse.post.id,\n\t\t\t\ttoken: this.token\n\t\t\t},\n\t\t\t(error, response) => {\n\t\t\t\tif (error) { return callback(error); }\n\t\t\t\t// confirm the numReplies attribute has been incremented\n\t\t\t\tAssert.equal(response.post.numReplies, 1, 'numReplies is not set to 1');\n\t\t\t\tcallback();\n\t\t\t}\n\t\t);\n\t}",
"function update_reply_indicator($parent) {\n var reply_txt = $parent.find('.reply_count').first(), // first() avoids nested tweets.\n count = reply_txt.data('count') - 1;\n reply_txt.addClass('you');\n if (count === 0) {\n reply_txt.text(gettext('You replied'));\n } else if (count === 1) {\n reply_txt.text(gettext('You and 1 other replied'));\n } else {\n reply_txt.text(interpolate('You and %s others replied',\n [count]));\n }\n }",
"async updateParentReview () {\n\t\tif (!this.parentPost.get('reviewId') && !this.grandParentPost) {\n\t\t\treturn;\n\t\t}\n\t\tconst reviewId = this.parentPost.get('reviewId') || this.grandParentPost.get('reviewId');\n\t\tconst review = await this.request.data.reviews.getById(reviewId, { excludeFields: ['reviewDiffs', 'checkpointReviewDiffs'] });\n\t\tif (!review) { return; }\n\n\t\tconst now = Date.now();\n\t\tconst op = { \n\t\t\t$set: {\n\t\t\t\tnumReplies: (review.get('numReplies') || 0) + 1,\n\t\t\t\tlastReplyAt: now,\n\t\t\t\tlastActivityAt: now,\n\t\t\t\tmodifiedAt: now\n\t\t\t}\n\t\t};\n\n\t\t// handle any followers that need to be added to the review, as needed\n\t\tawait this.handleFollowers(review, op);\n\n\t\tthis.transforms.updatedReviews = this.transforms.updatedReviews || [];\n\t\tconst reviewUpdate = await new ModelSaver({\n\t\t\trequest: this.request,\n\t\t\tcollection: this.data.reviews,\n\t\t\tid: review.id\n\t\t}).save(op);\n\t\tthis.transforms.updatedReviews.push(reviewUpdate);\n\t}",
"addReplies(postIds) {\n postIds.forEach(postId => {\n let post = qs(`[id='${postId}'] span.Footer-left-size`);\n ++post.innerHTML;\n });\n }",
"incrementCurrentParentItemCount () {\n this.currentParents[this.currentParents.length - 1][1] =\n (this.getCurrentParentItemCount()) + 1;\n }",
"function refreshLineCount() {\r\n\t\tvar innerTable;\r\n\t\tfor (var i = 0; i < codeTable.rows.length; i++) {\r\n\t\t\tinnerTable = codeTable.rows[i].cells[0].children[0];\r\n\t\t\tif (i < 9) innerTable.rows[0].cells[0].innerHTML = i + 1 + \" \";\r\n\t\t\telse innerTable.rows[0].cells[0].textContent = i+1;\r\n\t\t}\r\n\t}",
"function whereToAddReply(reply_count, new_count){\n\tif (Object.is(NaN, new_count)){\n\t\tif (reply_count.textContent == \"Reply\"){ reply_count.textContent = \"1 replies\"; }\n\t\telse{ countComments(); };\n\t}\n\telse{\n\t\treply_count.textContent = new_count + \" replies\";\n\t};\n}",
"checkParentPost (callback) {\n\t\tthis.doApiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'get',\n\t\t\t\tpath: '/posts/' + this.postData[0].post.id,\n\t\t\t\ttoken: this.token\n\t\t\t},\n\t\t\t(error, response) => {\n\t\t\t\tif (error) { return callback(error); }\n\t\t\t\t// confirm the numReplies attribute has been incremented\n\t\t\t\tAssert.equal(response.post.numReplies, 1, 'numReplies is not set to 1');\n\t\t\t\tcallback();\n\t\t\t}\n\t\t);\n\t}",
"function incrementReps() {\n repsCount = repsCount + 1;\n updateReps();\n}",
"function updateCommentsCount(post_id) {\n // update comments quant\n db.q(\"UPDATE blog \\\n SET comments_cnt=( \\\n SELECT COUNT(*) \\\n FROM comments \\\n WHERE post_id=?) \\\n WHERE blog_id=?\",\n [\n post_id,\n post_id\n ]);\n}",
"addPRE() { this.totalPREs.value++; this.updateStatNav(this.totalPREs); }",
"function updateStarCount(postElement, nbStart) {\n postElement.getElementsByClassName('star-count')[0].innerText = nbStart;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
accepts a timing function, returns the transformed variant | function makeEaseOut(timing) {
return function (timeFraction) {
return 1 - timing(1 - timeFraction);
}
} | [
"function wrapWithTiming(fn) {\n return function() {\n const startAt = +new Date();\n fn(arguments); // call or apply or bind or just 'fn'\n console.log(+new Date() - startAt);\n }\n}",
"function timeFunction(fn) {\n const startTime = Date.now();\n const result = fn();\n const elapsed = Date.now() - startTime;\n return {result, elapsed};\n}",
"function modifyDelay(f) {\n return self => modifyDelay_(self, f);\n}",
"static ease(f) {\n return (t, b, c, d) => (c * f(t / d) + b);\n }",
"function transform (fn, duration, then) {\n \n var tStart = Date.now();\n var end = 1;\n \n//\n// The parameters `duration` and `then` are both optional.\n//\n duration = typeof duration === \"number\" ? duration : DEFAULT_DURATION;\n then = typeof duration === \"function\" ? duration : then;\n then = typeof then === \"function\" ? then : function () {};\n \n function loop () {\n \n var tCurrent = Date.now() - tStart;\n var value = end * ((tCurrent / (duration / 100)) / 100);\n \n value = value > end ? end : value;\n \n if (tCurrent > duration || value === end) {\n fn(end);\n then();\n return;\n }\n \n fn(value);\n \n requestAnimationFrame(loop);\n }\n \n loop();\n}",
"function timingDecorator (func, time) {\n return function() {\n var start = performance.now();\n var result = func.apply(this, arguments); //forward call\n if (!timers[time]) {\n timers[time] = 0;\n }\n timers[time] = performance.now() - start;\n return result;\n }\n}",
"function slow(time) {\n return function (target, propertyKey) {\n if (arguments.length === 1) {\n target[slowSymbol] = time;\n }\n else {\n target[propertyKey][slowSymbol] = time;\n }\n };\n}",
"function timeFunction(func) {\n var before = new Date();\n\n var val = func.apply(this, Array.prototype.slice.call(arguments, 1));\n var elapsed = (new Date() - before);\n\n if (elapsed > 500) {\n log(func.toString().substring(0, func.toString().indexOf(\"{\")) + \": \" + elapsed);\n }\n\n return val;\n }",
"function wrapTimer(fn) {\n if (config.NODE_ENV !== 'development') return fn\n else\n return function*() {\n var start = Date.now()\n var result = yield fn.apply(this, arguments)\n var diff = Date.now() - start\n debug('[%s] Executed in %sms', fn.name, diff)\n return result\n }\n}",
"function wrapTimer(fn) {\n if (config.NODE_ENV !== 'development')\n return fn;\n else\n return function*() {\n var start = Date.now();\n var result = yield fn.apply(this, arguments);\n var diff = Date.now() - start;\n debug('[%s] Executed in %sms', fn.name, diff);\n return result;\n };\n}",
"transformedValue(value) {\n var precise = value.precise,\n transforms = value.transforms || [],\n added = 0,\n l = transforms.length;\n\n while (l--) {\n added += (Date.now() + value.latency - value.started) * transforms[l][1];\n }\n return precise + added;\n }",
"function delay(f, ms) {\n return new Proxy(f, {\n apply(target, thisArg, args) {\n setTimeout(() => target.apply(thisArg, args), ms);\n }\n });\n }",
"function TimeLogic(v,t){\n\n /*\n Time Units\n\n All unit values are conversions of S (Seconds) at the value of 1 converted into each unit.\n */\n var l = {\n AS:1e18,\t\t\t//Attoseconds\n C:1/31536e5,\t\t//Centuries\n D:1/864e2,\t\t\t//Days\n DE:1/31536e4,\t\t//Decades\n FS:1e15,\t\t\t//Femtoseconds\n FN:1/1209600.0,\t\t//Fortnight\n GY:1/31556952.00001,//Gregorian Years\n H:1/36e2,\t\t\t//Hours\n JY:1/31557600.0,\t//Julian Years\n LY:1/31622400.0,\t//Leap Years\n MUS:1e6,\t\t\t//Microseconds\n M:1/31536e6,\t\t//Millenniums\n MS:1e3,\t\t\t\t//Milliseconds\n MIN:1/60.0,\t\t\t//Minutes\n MON:1/2628000.0,\t//Months\n NS:1e9,\t\t\t\t//Nanoseconds\n PS:1e12,\t\t\t//Picoseconds\n S:1,\t\t\t\t//Seconds\n WK:1/604800.0,\t\t//Weeks\n Y:1/31536e3 \t\t//Years\n };\n\n /*\n Function to perform all conversions within Time function.\n All \"to\" functions within Time use this function.\n */\n function c(z){\n return k(v,z,l[t],true);\n }\n\n /*\n \"to\" Functions\n\n Ex 1: var bar = foo.toHours; //Variable \"bar\" being of type UnitOf.Time with \"from\" value already assigned\n Ex 2: var foobar = UnitOf.Time.fromMinutes(1.25).toHours; //One line conversion from 1.25 Minutes to Hours\n */\n return {\n getValuePassed:v,\n getTypeConstantPassed:t,\n toAttoseconds:c(l.AS),\n toCenturies:c(l.C),\n toDays:c(l.D),\n toDecades:c(l.DE),\n toFemtoseconds:c(l.FS),\n toFortnights:c(l.FN),\n toGregorianYears:c(l.GY),\n toHours:c(l.H),\n toJulianYears:c(l.JY),\n toLeapYears:c(l.LY),\n toMicroseconds:c(l.MUS),\n toMillenniums:c(l.M),\n toMilliseconds:c(l.MS),\n toMinutes:c(l.MIN),\n toMonths:c(l.MON),\n toNanoseconds:c(l.NS),\n toPicoseconds:c(l.PS),\n toSeconds:c(l.S),\n toWeeks:c(l.WK),\n toYears:c(l.Y)\n }\n }",
"set transform(f) { this._transform = f || (x => x); }",
"function onceTimeDecorator (f) {\r\n\tvar functions = {};\r\n\treturn function () {\r\n\t\tif (functions[f]) {\r\n\t\t\treturn new Function;\r\n\t\t} else {\r\n\t\t\tfunctions[f] = true;\r\n\t\t\treturn f.apply(this, arguments);\r\n\t\t};\r\n\t}\r\n}",
"function Transform() {}",
"function executeFunc(time, func) {}",
"function delay(f) {\n return () => {\n f.x = f.x;\n if (typeof f.x === 'undefined') {\n f.x = f();\n }\n return f.x;\n }\n}",
"scale(timeScale){if(timeScale!==1.0){const times=this.times;for(let i=0,n=times.length;i!==n;++i){times[i]*=timeScale;}}return this;}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Post json string to Elasticsearch | function postToES(json_str, endpoint, region, context) {
var req = new AWS.HttpRequest(endpoint);
req.method = 'POST';
req.path = '/_bulk';
req.region = region;
req.headers['presigned-expires'] = false;
req.headers['Host'] = endpoint.host;
req.body = json_str;
var signer = new AWS.Signers.V4(req , 'es'); // es: service code
signer.addAuthorization(creds, new Date());
var send = new AWS.NodeHttpClient();
send.handleRequest(req, null, function(httpResp) {
var respBody = '';
httpResp.on('data', function (chunk) {
respBody += chunk;
});
httpResp.on('end', function (chunk) {
console.log('Response: ' + respBody);
context.succeed('sent json: ' + json_str);
});
}, function(err) {
console.log('Error: ' + err);
context.fail('failed with error ' + err);
});
} | [
"function postToES(json_str, endpoint, region, context) {\n var req = new AWS.HttpRequest(endpoint);\n var creds = new AWS.EnvironmentCredentials('AWS');\n\n req.method = 'POST';\n req.path = '/_bulk';\n req.region = region;\n req.headers['presigned-expires'] = false;\n req.headers['Host'] = endpoint.host;\n req.body = json_str;\n\n var signer = new AWS.Signers.V4(req , 'es'); // es: service code\n signer.addAuthorization(creds, new Date());\n\n var send = new AWS.NodeHttpClient();\n send.handleRequest(req, null, function(httpResp) {\n var respBody = '';\n httpResp.on('data', function (chunk) {\n respBody += chunk;\n });\n httpResp.on('end', function (chunk) {\n context.succeed('sent json: ' + json_str);\n });\n }, function(err) {\n context.fail('failed with error ' + err);\n });\n }",
"function postToES(json_str, endpoint, region, context) {\n var req = new AWS.HttpRequest(endpoint);\n\n req.method = 'POST';\n req.path = '/_bulk';\n req.region = region;\n req.headers['presigned-expires'] = false;\n req.headers['Host'] = endpoint.host;\n req.body = json_str;\n\n var signer = new AWS.Signers.V4(req , 'es'); // es: service code\n signer.addAuthorization(creds, new Date());\n\n var send = new AWS.NodeHttpClient();\n send.handleRequest(req, null, function(httpResp) {\n var respBody = '';\n httpResp.on('data', function (chunk) {\n respBody += chunk;\n });\n httpResp.on('end', function (chunk) {\n console.log('Response: ' + respBody);\n context.succeed('sent json: ' + json_str);\n });\n }, function(err) {\n console.log('Error: ' + err);\n context.fail('failed with error ' + err);\n });\n}",
"static elasticPost(index,type,metadata)\n {\n return Elastic.elastic(index,type,\"POST\",metadata);\n }",
"function postToES(doc, context, index) {\n var req = new AWS.HttpRequest(endpoint);\n\n req.method = \"POST\";\n req.path = path.join(\"/\", index, esDomain.doctype);\n req.region = esDomain.region;\n req.headers[\"presigned-expires\"] = false;\n req.headers[\"Host\"] = endpoint.host;\n req.headers[\"Content-Type\"] = \"application/json\";\n req.body = doc;\n\n var signer = new AWS.Signers.V4(req, \"es\"); // es: service code\n signer.addAuthorization(creds, new Date());\n\n var send = new AWS.NodeHttpClient();\n send.handleRequest(\n req,\n null,\n function(httpResp) {\n var respBody = \"\";\n httpResp.on(\"data\", function(chunk) {\n respBody += chunk;\n });\n httpResp.on(\"end\", function(chunk) {\n console.log(\"Response: \" + respBody);\n context.succeed(\"Lambda added document \" + doc);\n });\n },\n function(err) {\n console.log(\"Error: \" + err);\n context.fail(\"Lambda failed with error \" + err);\n }\n );\n}",
"function postToES(doc, index) {\n log.debug('postToES(doc):', doc);\n\n return new Promise((resolve, reject) => {\n const req = new AWS.HttpRequest(endpoint);\n\n req.method = 'POST';\n req.path =\n path.join('/', esDomain.index, 'doc', hash(doc, 'hex'));\n req.region = esDomain.region;\n req.headers['presigned-expires'] = false;\n req.headers.Host = endpoint.host;\n req.headers['Content-Type'] = 'application/json';\n req.body = doc;\n\n const signer = new AWS.Signers.V4(req, 'es'); // es: service code\n signer.addAuthorization(creds, new Date());\n\n const nodeHttpClient = new AWS.NodeHttpClient();\n nodeHttpClient.handleRequest(req, null, (httpResp) => {\n let respBody = '';\n httpResp.on('data', (chunk) => {\n respBody += chunk;\n });\n httpResp.on('end', () => {\n log.debug('response:', respBody);\n // context.succeed('Lambda added document ' + doc);\n resolve(respBody);\n });\n }, reject);\n });\n }",
"function _postJSON(json, couchdbName) {\n // add the path in to the post options\n // based on the database name\n _postOptions.path = \"/\" + couchdbName + \"/_bulk_docs\";\n // make the request\n var req = http_1.request(_postOptions, function (httpResult) {\n // set utf8 encoding\n httpResult.setEncoding(\"utf8\");\n // callback to push data to Observable (via Subject)\n httpResult.on(\"data\", function (httpResultbody) {\n // it comes out as type string | buffer\n // so cast it to a string for TS happiness\n _stream.next(httpResultbody);\n });\n });\n // write data to request body\n // note the addition of docs: to the JSON string to\n // make it compatible with couchDB bulk_docs upload\n req.write('{\"docs\": ' + JSON.stringify(json) + \"}\", \"utf8\");\n // close connection\n req.end();\n // error handling\n req.on(\"error\", function (e) {\n _stream.next(JSON.stringify(e));\n });\n}",
"function update_elastic(api_url, json_obj) {\n\t// console.log(JSON.stringify(json_obj))\n\tauth = \"Basic \" + new Buffer.from(elastic_username + \":\" + elastic_password).toString(\"base64\");\n\n\tvar response = request('PUT', api_url, {\n\t\tjson: json_obj,\n\t\theaders: {\n\t\t\t\"content-type\": \"application/json\",\n\t\t\t\"kbn-xsrf\": true,\n\t\t\t\"Authorization\": auth\n\t\t}\n\t});\n\n\ttry {\n\t\tvar body = response.getBody('utf8');\n\t} catch(err) {\n\t\tconsole.log(err)\n\t\tprocess.exit(19)\n\t}\n\n\ttry {\n\t\tvar body_obj = JSON.parse(body)\n\t} catch(err) {\n\t\tconsole.log(err)\n\t\tprocess.exit(20)\n\t}\n\n\tconsole.log(body_obj)\n}",
"function postDocumentToES(doc, context) {\n var req = new AWS.HttpRequest(endpoint);\n\n req.method = 'POST';\n req.path = path.join('/', esDomain.index, esDomain.doctype);\n req.region = esDomain.region;\n req.body = doc;\n req.headers['presigned-expires'] = false;\n req.headers['Host'] = endpoint.host;\n\n // Sign the request (Sigv4)\n var signer = new AWS.Signers.V4(req, 'es');\n signer.addAuthorization(creds, new Date());\n\n // Post document to ES\n var send = new AWS.NodeHttpClient();\n send.handleRequest(req, null, function(httpResp) {\n var body = '';\n httpResp.on('data', function (chunk) {\n body += chunk;\n });\n httpResp.on('end', function (chunk) {\n numDocsAdded ++;\n if (numDocsAdded === totLogLines) {\n // Mark lambda success. If not done so, it will be retried.\n console.log('All ' + numDocsAdded + ' log records added to ES.');\n context.succeed();\n }\n });\n }, function(err) {\n console.log('Error: ' + err);\n console.log(numDocsAdded + 'of ' + totLogLines + ' log records added to ES.');\n context.fail();\n });\n}",
"function AddTodo(req, res){\n client.create({\n index: 'todo',\n type: 'todo',\n id: req.swagger.params.todo.value.todo_id,\n body: req.swagger.params.todo.value\n //2. take response from elasticsearch and send to node\n }, function(error,response){\n res.header('Content-Type', 'application/json');\n if(error){\n console.log(error);\n res.statusCode = 409;\n res.end(JSON.stringify(error));\n }else{\n req.swagger.params.todo.value.datecreated = new Date();\n console.log(`Todo ${req.swagger.params.todo.value.todo_id} added to Elasticsearch`);\n res.end();\n }\n });\n}",
"async function updateEsTypeMapping() {\n await client.indices.putMapping({\n index: esIndex,\n type: esType,\n body: {\n properties: {\n id: {type: \"text\"},\n title: {type: \"text\"},\n serviceId: {type: \"text\"},\n tags: {\n type: \"nested\",\n properties: {\n value: {\n \"type\": \"keyword\",\n \"index\": true,\n },\n score: {\n \"type\": \"float\",\n },\n },\n },\n },\n },\n });\n}",
"function postToES(doc, context) {\n console.log('Came into postToES')\n var req = new AWS.HttpRequest(endpoint);\n \n req.method = 'POST';\n req.path = path.join('/', esDomain.index, esDomain.doctype);\n req.region = esDomain.region;\n req.headers['presigned-expires'] = false;\n req.headers['Host'] = endpoint.host;\n req.headers['Content-Type'] = 'application/json';\n req.body = doc;\n\n var signer = new AWS.Signers.V4(req , 'es'); // es: service code\n signer.addAuthorization(creds, new Date());\n\n var send = new AWS.NodeHttpClient();\n\n // Making the actual call to the ES\n send.handleRequest(req, null, function(httpResp) {\n console.log('Into handle request');\n \n var respBody = '';\n httpResp.on('data', function (chunk) {\n respBody += chunk;\n JSON.stringify(respBody);\n });\n httpResp.on('end', function (chunk) {\n console.log('Response: ' + respBody);\n context.succeed('Lambda added document ' + doc);\n });\n }, function(err) {\n console.log('Error: ' + err);\n context.fail('Lambda failed with error ' + err);\n });\n}",
"function saveInEs(tweet) {\n console.log(\"Saving in elasticsearch\");\n var id = indexEs+1;\n indexEs=indexEs+1;\n es.index({\n index: 'tweets',\n type: 'tweet',\n id: id,\n body: tweet\n }, function(err, resp) {\n if (!err) {\n console.info(resp);\n }\n });\n}",
"function postToES(doc, callback) {\n var req = new AWS.HttpRequest(endpoint);\n\n req.method = 'POST';\n req.path = path.join('/', esDomain.index, esDomain.doctype);\n req.region = esDomain.region;\n req.headers['presigned-expires'] = false;\n req.headers['Host'] = endpoint.host;\n req.body = doc;\n\n var signer = new AWS.Signers.V4(req , 'es'); // es: service code\n signer.addAuthorization(creds, new Date());\n\n var send = new AWS.NodeHttpClient();\n send.handleRequest(req, null, function(httpResp) {\n var respBody = '';\n httpResp.on('data', function (chunk) {\n respBody += chunk;\n });\n httpResp.on('end', function (chunk) {\n console.log('Response: ' + respBody);\n callback(null, 'Lambda added document ' + doc);\n });\n }, function(err) {\n console.log('Error: ' + err);\n callback(err, 'Lambda failed with error ' + err);\n });\n}",
"function postToES(doc, context) {\n console.log(\"Posting document...\");\n console.log(doc);\n var req = new AWS.HttpRequest(endpoint);\n\n req.method = 'POST';\n req.path = path.join('/', esDomain.index, esDomain.doctype);\n req.region = esDomain.region;\n req.headers['presigned-expires'] = false;\n req.headers['Host'] = endpoint.host;\n req.body = doc;\n\n var signer = new AWS.Signers.V4(req , 'es'); // es: service code\n signer.addAuthorization(creds, new Date());\n\n var send = new AWS.NodeHttpClient();\n send.handleRequest(req, null, function(httpResp) {\n var respBody = '';\n httpResp.on('data', function (chunk) {\n respBody += chunk;\n });\n httpResp.on('end', function (chunk) {\n console.log('Response: ' + respBody);\n context.succeed('Lambda added document ' + doc);\n });\n }, function(err) {\n console.log('Error: ' + err);\n context.fail('Lambda failed with error ' + err);\n });\n}",
"function saveToElastic(fileName, body, callback) {\n\n // Get date from filename, if possible\n var date = fileName.match(/\\d{4}-\\d{1,2}-\\d{1,2}/);\n date = date ? new Date(date[0]) : null;\n\n // Get issue number from filename, if possible\n var issue = fileName.match(/\\b\\d{3}\\b/);\n issue = issue ? parseInt(issue) : null;\n\n // Get supplement from filename, if possible\n var supplement = fileName.match(/Supl/);\n supplement = supplement ? true : false;\n\n client.create({\n index: index,\n type: type,\n body: {\n name: 'JORAM',\n series: 'IV',\n issue: issue,\n supplement: supplement,\n date: date,\n file: fileName,\n body: body\n }\n }, function (error) {\n\n if (error) throw error;\n\n console.log('Inserted document ' + fileName + ' to ElasticSearch');\n callback();\n });\n}",
"function createIndex() {\n var query = {\n 'settings': {\n 'number_of_shards': 1,\n 'analysis': {\n 'filter': {\n 'autocomplete_filter': {\n 'type': 'edge_ngram',\n 'min_gram': 1,\n 'max_gram': 20\n }\n },\n 'analyzer': {\n 'autocomplete': {\n 'type': 'custom',\n 'tokenizer': 'standard',\n 'filter': [\n 'lowercase',\n 'autocomplete_filter'\n ]\n }\n }\n }\n }\n };\n\n return esClient.post('busbud', query);\n}",
"async function pushToElasticSearch(fileData) { \n\n\tlet count = {};\n\n\ttry\n\t{\n\t\tcount = await client.count({\n\t\tindex: 'user_data'\n\t\t});\n\t}\n\t\n\tcatch(err)\n\t{\n\t\tconsole.save(err);\n\t\tcount.count = 0;\n\t}\n\n\tvar obj = {\n\t\tindex: 'user_data',\n\t\ttype: 'user',\n\t\tid: count.count + 1\n\t};\n\n\tobj.body = fileData;\n\tclient.create(obj, function(error) {\n\t\tif (error) {\n\t\t\tconsole.save('Error boi');\n\t\t} else {\n\t\t\tconsole.save('All is well boi');\n\t\t}\n\t});\n}",
"async function putMappingForSmartTV() {\n\n /*\n const ret = {\n \"id\": id, \n \"modelname\":modelname,\n \"modelnumber\": modelnumber,\n \"brand\": brand, \n \"productname\" :productname, \n \"shortlabel\":shortlabel, \n \"longdescription\":longdescription\n };\n */\n /*\n const schema = {\n id: { type: 'text' },\n modelname: { type: 'text' },\n modelnumber: { type: 'text' },\n brand: { type: 'text' },\n productname: { type: 'text' },\n shortlabel: { type: 'text' },\n longdescription: { type: 'text' },\n currentprice: { type: 'text' }\n \n }\n */\n /*\n const schema = {\n brand: { type: 'text' } \n }\n */\n\n const schema = {\n \"id\": { type: 'keyword' },\n \"modelname\": { type: 'keyword' },\n \"modelnumber\": { type: 'keyword' },\n \"brand\": { type: 'keyword' },\n \"productname\": {\n type: 'text',\n \"copy_to\": \"product_suggest\"\n },\n \"product_suggest\": {\n \"type\": \"completion\"\n },\n \"shortlabel\": { type: 'text',\n \"copy_to\": \"product_suggest\"\n },\n \"displayname\": {\n type: 'text',\n \"copy_to\": \"product_suggest\"\n },\n \"ean\": { type: 'keyword' },\n \"currentprice\": { type: 'float' },\n \"customerrating\": { type: 'float' },\n \"category_list\": {\n \"type\": \"nested\",\n \"properties\": {\n \"categoryName\": { \"type\": \"keyword\" }\n }\n },\n \"categories\": {\n \"type\": 'text',\n \"analyzer\": \"my_analyzer\"\n },\n \"text\": { type: 'text' }\n };\n\n return client.indices.putMapping({ index, type, body: { properties: schema } })\n}",
"function saveToElastic(filePath, body, callback) {\n\n client.create({\n index,\n type,\n body: {\n filePath,\n body\n }\n },\n error => {\n\n if (error) throw error;\n\n console.log(`Inserted document ${filePath} to ElasticSearch`);\n callback();\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
End output loading Start > Load approver filter data | function loadApproverFilterData(){
if($('#reportingId').val() != "" && $('#strategicPillarId').val() != "" && $('#themeId').val() != "" && $('#outcomeId').val() != "" && $('#outputId').val() != "")
{
$('#approverDiv').hide();
$('#filter-btn').hide();
$('#reset').show();
$('#filter-btn-show').show();
var projectId=1;
var statusId = $('#statusId').val();
var filterHierForReviewer={};
filterHierForReviewer={
"reportingperiodId" : $('#reportingId').val(),
"strategicPillar" : $('#strategicPillarId').val(),
"theme" : $('#themeId').val(),
"outcome" : $('#outcomeId').val(),
"output" : $('#outputId').val()
};
$.ajax({
url : '/ndcmp/api/loadApproverData',
data : {
projectId : projectId,
reviewerFilter : JSON.stringify(filterHierForReviewer),
statusId : statusId
},
type : 'GET',
async : false,
dataType : 'json',
success : function(data) {
var modalBody = '<div class="panel-group accordion" id="collapseOne">';
for(var i = 0;i < data.length; i++){
if (i == 0) {
modalBody += '<div class="panel panel-default template">'
+ '<div class="panel-heading" style="background-color: #4D5B69;">'
+ '<h4 class="panel-title">'
+ '<a class="accordion-toggle" data-toggle="collapse" data-parent="#collapseOne" href="#collapseOutput_'+ data[i].id +'">'
+ '<span><b>'+data[i].sequenceNumber+' '+ data[i].keyActivity +' </b></span></a></h4></div>'
+ '<div id="collapseOutput_'+ data[i].id +'" class="panel-collapse collapse in">'
+ '<div class="panel-body">'
+ '<div class="panel-group accordion" id="collapseTwo'+ data[i].id +'">';
} else {
modalBody += '<div class="panel panel-default template">'
+ '<div class="panel-heading" style="background-color: #4D5B69;">'
+ '<h4 class="panel-title">'
+ '<a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#collapseOne" href="#collapseOutput_'+ data[i].id +'">'
+ '<span><b>'+data[i].sequenceNumber+' '+ data[i].keyActivity +' </b></span></a></h4></div>'
+ '<div id="collapseOutput_'+ data[i].id +'" class="panel-collapse collapse">'
+ '<div class="panel-body">'
+ '<div class="panel-group accordion" id="collapseTwo'+ data[i].id +'">';
}
subActivities = data[i].subActivities;
for(var j =0;j < subActivities.length;j++){
// if(subActivities[j].approveORCompleteStatus == true){
// modalBody += '<div style="height:35px;border: 1px solid #e4d6d6;background-color: #f3bcb7;padding: 5px;">'
// + '<span style="color:#ce1115;">'+subActivities[j].sequenceNumber+' '+ subActivities[j].subActivity +'</span><br></div>';
// if(subActivities[j].carryOverStatus == true){
//
// }
//
// }else if(subActivities[j].carryOverStatus == true){
// modalBody += '<div style="height:35px;border: 1px solid #e4d6d6;background-color: #CE7173;padding: 5px;">'
// + '<span>'+subActivities[j].sequenceNumber+' '+ subActivities[j].subActivity +'</span><br></div>';
// }else{
// modalBody += '<div style="height:35px;border: 1px solid #e4d6d6;background-color: #f3bcb7;padding: 5px;">'
// + '<span >'+subActivities[j].sequenceNumber+' '+ subActivities[j].subActivity +'</span><br></div>';
// }
//
if(subActivities[j].approveORCompleteStatus == true){
if(subActivities[j].carryOverStatus == true){
modalBody += '<div style="height:35px;border: 1px solid #e4d6d6;background-color: #CE7173;padding: 5px;">'
+ '<span style="color:#801e7f;">'+subActivities[j].sequenceNumber+' '+ subActivities[j].subActivity +'</span><br></div>';
}else{
modalBody += '<div style="height:35px;border: 1px solid #e4d6d6;background-color: #f3bcb7;padding: 5px;">'
+ '<span style="color:#801e7f;">'+subActivities[j].sequenceNumber+' '+ subActivities[j].subActivity +'</span><br></div>';
}
}else{
if(subActivities[j].carryOverStatus == true){
modalBody += '<div style="height:35px;border: 1px solid #e4d6d6;background-color: #CE7173;padding: 5px;">'
+ '<span>'+subActivities[j].sequenceNumber+' '+ subActivities[j].subActivity +'</span><br></div>';
}else{
modalBody += '<div style="height:35px;border: 1px solid #e4d6d6;background-color: #f3bcb7;padding: 5px;">'
+ '<span>'+subActivities[j].sequenceNumber+' '+ subActivities[j].subActivity +'</span><br></div>';
}
}
var partnerAgencies = subActivities[j].agencyDTOs;
for(var k =0;k < partnerAgencies.length; k++){
modalBody += '<div title="Click to view" onclick="getStatusReviewer('+ partnerAgencies[k].userId +','+ subActivities[j].id +', this, \''+ partnerAgencies[k].agency +'\', \''+partnerAgencies[k].userName+'\')" style="height:35px;border: 1px solid #e4d6d6;background-color: #FBDEDB;cursor: pointer;padding: 5px;">'
+ '<span style="margin-left: 20px;">'+"by"+' '+partnerAgencies[k].agency+' ('+partnerAgencies[k].userName+')<div class="pull-right" style="width:20px; height:20px;border-radius: 5px; border: 1px solid; margin-right:15px; background-color: '+ partnerAgencies[k].colorCode +'"></div>'
+ '<span class="pull-right" style="width:20px;height: 20px;margin-right:5px;text-align: center;"><i style="margin-top:5px;" class="'+ partnerAgencies[k].statusIcon +'"></i></span>'
+ '</span><br></div>';
}
}
modalBody += '</div></div></div></div>';
}
modalBody += '</div>';
$('#approverDetails').html(modalBody);
$('#approverDetails').show();
$('#approver_all-btn').show();
}
});
return true;
}else{
var reportID = $('#reportingId').val();
var statusID = $('#statusId').val();
var stragicID = $('#strategicPillarId').val();
var themeID = $('#themeId').val();
var outcomeID = $('#outcomeId').val();
var outputID = $('#outputId').val();
if(reportID == ""){
$('#reportingValidationErrorMsg').show();
$('#validationErrorModelWindow').modal('show');
return false;
}else{
$('#reportingValidationErrorMsg').hide();
}
if (statusID == "") {
$('#statusValidationErrorMsg').show();
$('#validationErrorModelWindow').modal('show');
return false;
}else{
$('#statusValidationErrorMsg').hide();
}
if (stragicID == "") {
$('#strategicValidationErrorMsg').show();
$('#validationErrorModelWindow').modal('show');
return false;
}else{
$('#strategicValidationErrorMsg').hide();
}
if (themeID == "") {
$('#themeValidationErrorMsg').show();
$('#validationErrorModelWindow').modal('show');
return false;
}else{
$('#themeValidationErrorMsg').hide();
}
if (outcomeID == "") {
$('#outcomeValidationErrorMsg').show();
$('#validationErrorModelWindow').modal('show');
return false;
}else{
$('#outcomeValidationErrorMsg').hide();
}
if (outputID == "") {
$('#outputValidationErrorMsg').show();
$('#validationErrorModelWindow').modal('show');
return false;
}else{
$('#outputValidationErrorMsg').hide();
}
//$('#validationErrorModelWindow').modal('show');
}
} | [
"function finishRenderFilters() {\n $window.UnicalApiBehaviors.filterToggle();\n }",
"function _loadGSAdata() {\n // This is going to load the GSA data\n $.getJSON('/api/opportunities/?format=json')\n .done(function (d) {\n d[\"agency\"] = \"gsa\";\n _loadFilterOptions(d);\n\n $(\"#loading\").remove();\n var options = {\n page: 100,\n item: 'opportunity-row',\n valueNames: ['description','office','naics']\n };\n var listObj = new List('results', options, d);\n data = d;\n // Create Filter events\n _createFilterEvents(['award_status','naics','place_of_performance_state'],\n listObj);\n\n // _initDetails(listObj);\n\n _loadOtherAgencies(['state','ed'], listObj);\n\n }).then(function () {\n fullResults = $(\"#opportunities\").clone()\n })\n}",
"handleLoadFiltersData() {\n /**\n * Genres.\n */\n getGenres().then((genres) => {\n // eslint-disable-next-line no-underscore-dangle\n this.setGenres(genres.__type.enumValues.map(({ name }) => ({\n id: name,\n name,\n })));\n }).catch((error) => {\n console.log('Error', error);\n });\n\n /**\n * Providers.\n */\n getProviders().then((providers) => {\n this.setProviders(providers.organisationSet.pageResults);\n }).catch((error) => {\n console.log('Error', error);\n });\n }",
"function dataRequestFromFilters(filtObj){\n $(\"#filters\").on(\"change\", \"select\", function() {\n $(\".mdl-spinner\").addClass(\"is-active\");\n $.get(filtObj.url, function(data) {\n \n outputFilteredRows(data);\n })\n .always(function() {\n $(\".mdl-spinner\").removeClass(\"is-active\");\n });\n });\n}",
"function applyFilter() {\n // apply filter to source list\n _players.forEach(_applyFilterToPlayer);\n // clear out old display list\n vm.players = [];\n if(vm.filter === 'defensive') {\n $teams.getTeams()\n .then(function(teams) {\n vm.players = teams;\n vm.playerMsg = vm.players.length == 0 ? 'No players are available for selection.' : '';\n });\n } else {\n // add in next batch of players to display\n showMorePlayers();\n }\n }",
"function onClickLoadData(btn) {\n\n var sFilter = '';\n\n if ((comboCols.getValue() == '') && (comboOp.getValue() == '') && (searchCr.getValue() == '' )) {\n sFilter = '';\n } else if ((comboCols.getValue() == '') || (comboOp.getValue() == '') || (searchCr.getValue() == '' )) {\n Ext.Msg.alert('Status', 'Invalid criteria');\n return; \n } else {\n sFilter = '{\"' + comboCols.getValue() + '__' + comboOp.getValue() + '\" : \"' + searchCr.getValue() + '\",}';\n }\n\n protoMasterStore.clearFilter();\n protoMasterStore.baseParams.protoFilter = sFilter;\n protoMasterStore.baseParams.modelLoad = '0';\n protoMasterStore.load();\n\n }",
"function loadData() {\n\t\tvar requestData = UtilitiesService.getRequestData();\n\t\t//Getting the widget which is selected\n\t\trequestData['groupBy'] = sharedProperties.getSubGroupBy();\n\t\tvar cacheKey = \"BITrend\" + JSON.stringify(requestData);\n\t\tvar func = $scope.success;\n\t\tif (arguments[1]) {\n\t\t\tif (arguments[1].key == cacheKey) {\n\t\t\t\tfunc = null;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif(sharedProperties.getSubGroupBy() != null){\n\t\t\t//Data service call for BI Trend\n\t\t\tDataService.getBusinessImpactTrendData(requestData, func, $scope.fail);\n\t\t}\n\t}",
"function loadData() {\n\n //TO DO: iterate through all clips in the bucket and append to \"clips\"\n\n //TO DO: read in all of the user tags and append to \"tags\" \n\n //TO DO: read in sortedIds (output of search.js) and assign to \"preFiltered\"\n\n}",
"function handleFilterChange(flag) {\n\n // The following function removes active class from subpopulation list view.\n removeActiveClassFromLists();\n\n showSPView();\n\n showSPlistView();\n\n hideSPDetailView();\n\n let planType = genotypes = treatment = cirrhosis = tenureValue = fdaCompliant = '';\n\n planType = getPlanTypeFromFilters();\n genotypes = getGenotypeFromFiltters();\n treatment = getTreatmentFromFilters();\n cirrhosis = getCirrhosisFromFilters();\n rebateDiscount = getRebatePriceValue();\n rebateDb = getRebateDatasetName();\n\n /**\n * @author: pramveer\n * @date:21st feb 2017 \n * @desc:removed years field from filters \n */\n //tenureValue = getLastYearValue();\n fdaCompliant = getFdaComplaintCheck();\n headerparams['genotypes'] = genotypes.join(',');\n headerparams['cirrhosis'] = cirrhosis ? (cirrhosis.length > 1 ? 'All' : cirrhosis[0]) : 'All';\n headerparams['treatment'] = treatment ? (treatment.length > 1 ? 'All' : treatment[0]) : 'All';\n headerparams['planType'] = planType;\n\n /**\n * @author: pramveer\n * @date:21st feb 2017 \n * @desc:removed years field from filters \n */\n // headerparams['tenureValue'] = tenureValue;\n\n setPayerHeaderTabData(headerparams);\n\n //set genotypes for profile filters\n setGenotypeComboForProfileSection(genotypes, cirrhosis, treatment, planType, tenureValue, fdaCompliant);\n\n // set flag1 for all data\n var flag1 = '';\n //if no genotype and plan is selected then show all drugs info flag1 is to all and genotype value is passed\n if (genotypes[0].toLowerCase() == 'all' && $('.treatedInsurancePlanSelect').val() == 'all' && $('.treatedTreatment').val() == 'all' && $('.treatedCirrhosis').val() == 'all') {\n flag1 = 'all';\n }\n\n //if all is selected in the genotype Combo.\n if (genotypes[0].toLowerCase() == 'all') {\n genotypes = [];\n for (var i = 0; i < GenotypeList.length; i++) {\n genotypes.push(GenotypeList[i].hcv_genotype);\n }\n }\n\n // // if ALL is selected in the insurance Plan Select box\n // if (planType === 'all') {\n // var allPlans = [];\n // ClaimsInsurancePlan.forEach(function(rec) {\n // allPlans.push(rec['claims_insurancePlan']);\n // });\n // allPlans = allPlans.join(',');\n // planType = allPlans.replace(',', '\",\"');\n // }\n\n\n //put the data into json object\n var categoryData = {\n genotypes: genotypes,\n treatment: treatment,\n cirrhosis: cirrhosis,\n fdaCompliant: fdaCompliant,\n planType: planType,\n flag: flag1,\n rebateDiscount: rebateDiscount,\n rebateDb: rebateDb\n };\n\n //set filters\n currentTabFilters = categoryData;\n\n //get the category id list and category name\n // var category_data = payerUtils.getPossibleCatCombination(categoryData);\n // var id_list = category_data;\n\n //call template function to get patients data\n //initilizing variable to get medication list id passed\n var filter_med_list = [];\n //if filter is applied and flag is not set to all then medication list is set medication list passed\n if (isComparitiveFilter && flag != undefined && flag != 'all') {\n filter_med_list = flag;\n } else {\n filter_med_list = getCurrentPopulationFilters().medicationArray;\n }\n\n //call the helper function get filtered data\n var dbParams = categoryData;\n dbParams['plans'] = planType;\n dbParams['duration'] = getCurrentPopulationFilters().duration;\n dbParams['patientsType'] = 'treated';\n dbParams['fdaCompliant'] = fdaCompliant;\n dbParams['filteredMedications'] = filter_med_list;\n //dbParams['showPreactingAntivirals'] = getCurrentPopulationFilters().showPreactingAntivirals;\n dbParams['showPreactingAntivirals'] = getPreactingAntiviralValue();\n\n payerUtils.storeFitersData('treated', categoryData, planType);\n fetchAndRenderData(dbParams, null, { renderTabView: true });\n\n}",
"function getFilterData(apiUrl) {\n $.get(apiUrl, function(data, status){\n //console.log(\"data\" + data + \"status : \" + status)\n //data = JSON.parse(data)\n setCompanies(data.company)\n setClients(data.client)\n setAcm(data.acm)\n })\n}",
"async startActiveFilter() {\n this.activeFilter.activeFilterData()\n }",
"function filterData() {\n state.unpackedData = state.unpackedData.filter(d=>d.entry_type === \"new_entry\");\n state.selectedPolicies = Object.values(state.unpackedData.map(d=>d.policy_id));\n}",
"function filterWhenChange() {\n var url = link + '?page=' + page + getFilter();\n getData(url);\n}",
"function addDataProcess() {\r\n\r\n\t\tbrunel.dataPreProcess(function (data) {\r\n\t\t\treturn data.filter(filterHandler.makeFilterStatement(data))\r\n\t\t});\r\n\t}",
"function onFilter() {\r\n let filteredDataBuffer = _.cloneDeep(completeData)\r\n const selectedDatasourcesNames = _.map(selectedDatasources, (datasourceObj) => datasourceObj.value)\r\n const selectedCampaignsNames = _.map(selectedCampaigns, (campaignObj) => campaignObj.value)\r\n if (selectedDatasourcesNames && selectedDatasourcesNames.length) {\r\n filteredDataBuffer = _.filter(filteredDataBuffer, (dataObj) => {\r\n return _.includes(selectedDatasourcesNames, dataObj.Datasource)\r\n })\r\n }\r\n if (selectedCampaignsNames && selectedCampaignsNames.length) {\r\n filteredDataBuffer = _.filter(filteredDataBuffer, (dataObj) => {\r\n return _.includes(selectedCampaignsNames, dataObj.Campaign)\r\n })\r\n }\r\n setFilteredData(filteredDataBuffer)\r\n }",
"function setupFilters(mainPath) {\n var url = mainPath + \"filteredData\";\n\n url = \"serviceVisitsData.php?table=filteredData\";\n var filtObj = {};\n filtObj[\"type\"] = \"\";\n filtObj[\"brand\"] = \"\";\n filtObj[\"browser\"] = \"\";\n filtObj[\"referrer\"] = \"\";\n filtObj[\"operatingSys\"] = \"\";\n filtObj[\"country\"] = \"\";\n \n filtObj[\"url\"] = url + \"&type=\" + filtObj[\"type\"] + \"&brand=\" + filtObj[\"brand\"] \n + \"&browser=\" + filtObj[\"browser\"] + \"&referrer=\"+filtObj[\"referrer\"] \n + \"&operatingSys=\"+ filtObj[\"operatingSys\"] + \"&country=\" +filtObj[\"country\"];\n \n var updatedObj= {};\n \n updatedObj = addEventToFilters(\"type\", filtObj);\n updatedObj = addEventToFilters(\"brand\", filtObj);\n updatedObj = addEventToFilters(\"browser\", filtObj);\n updatedObj = addEventToFilters(\"referrer\", filtObj);\n updatedObj = addEventToFilters(\"operatingSys\", filtObj);\n //deal with textbox\n updatedObj = autocompleteCountries(\"country\", filtObj);\n dataRequestFromFilters(filtObj);\n}",
"doneFiltering() {\n filtered = false\n }",
"function _fetchData() {\n $scope.loading = true;\n\n // Common parameters for count and data query\n var commonParameters = {\n where: SocketHelperService.getWhere($scope.filters)\n };\n\n if($scope.filters && $scope.filters.holderId) {\n commonParameters.where = _.merge(\n {}, \n commonParameters.where, \n {holder: $scope.filters.holderId}\n );\n }\n\n if($scope.filters && $scope.filters.attributeLinkId) {\n // TODO: look for all territories with said attribute,\n // Add list of territory ids to where query\n }\n\n // Data query specified parameters\n var parameters = {\n populate: ['holder', 'territoryHolderHistory', 'territoryLinkAttribute'],\n limit: $scope.itemsPerPage,\n skip: ($scope.currentPage - 1) * $scope.itemsPerPage,\n sort: $scope.sort.column + ' ' + ($scope.sort.direction ? 'ASC' : 'DESC')\n };\n\n // Fetch data count\n var count = TerritoryModel\n .count(commonParameters)\n .then(\n function onSuccess(response) {\n $scope.itemCount = response.count;\n }\n )\n ;\n\n console.log(_.merge({}, commonParameters, parameters));\n\n // Fetch actual data\n var load = TerritoryModel\n .load(_.merge({}, commonParameters, parameters))\n .then(\n function onSuccess(response) {\n $scope.items = response;\n }\n )\n ;\n\n // And wrap those all to promise loading\n $q\n .all([count, load])\n .finally(\n function onFinally() {\n $scope.loaded = true;\n $scope.loading = false;\n }\n )\n ;\n }",
"function load() {\n loadFacets();\n loadFacetValues();\n updatePreviewResultSize();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
turns a name into a URI depending on type, e.g. name: UNDP, type: Organisation > if the input is already a URL (starting with " simply returns it | function makeURI(name, type){
if (name.indexOf("http://") != 0){
var fragment = name.replace(/\s+/g, '_'); // replace whitespaces
name = "http://hxl.carsten.io/"+type.toLowerCase()+"/" + fragment.toLowerCase();
}
return name;
} | [
"function typeToUrl(type) {\r\n if (type == \"movie\") {\r\n return urlMovies;\r\n } else if (type == \"tv\") {\r\n return urlTV;\r\n }\r\n }",
"function getFullName(type) {\n\t if (type) {\n\t type = type.toLowerCase();\n\t switch (type) {\n\t case 'q':\n\t case QUANTITATIVE:\n\t return 'quantitative';\n\t case 't':\n\t case TEMPORAL:\n\t return 'temporal';\n\t case 'o':\n\t case ORDINAL:\n\t return 'ordinal';\n\t case 'n':\n\t case NOMINAL:\n\t return 'nominal';\n\t case GEOJSON:\n\t return 'geojson';\n\t }\n\t }\n\t // If we get invalid input, return undefined type.\n\t return undefined;\n\t}",
"function getFullName(type) {\n if (type) {\n type = type.toLowerCase();\n switch (type) {\n case 'q':\n case QUANTITATIVE:\n return 'quantitative';\n case 't':\n case TEMPORAL:\n return 'temporal';\n case 'o':\n case ORDINAL:\n return 'ordinal';\n case 'n':\n case NOMINAL:\n return 'nominal';\n case GEOJSON:\n return 'geojson';\n }\n }\n // If we get invalid input, return undefined type.\n return undefined;\n}",
"function nameToUrl(name) {\n var url = name,\n special = /[!@\\#\\$%\\^&\\*\\(\\)\\-\\=\\_\\+\\?\\\\\\[\\]/.{}<>~`;,\"']/g;\n // remove special charaters\n url = url.replace(special, '');\n // remove spaces trailing and preceding\n url = url.trim();\n // to lowercase\n url = url.toLowerCase();\n // spaces to -\n url = url.replace(/\\s+/g, '-');\n return url;\n}",
"function getFullName(type) {\n if (type) {\n type = type.toLowerCase();\n switch (type) {\n case 'q':\n case QUANTITATIVE:\n return 'quantitative';\n case 't':\n case TEMPORAL:\n return 'temporal';\n case 'o':\n case ORDINAL:\n return 'ordinal';\n case 'n':\n case NOMINAL:\n return 'nominal';\n case GEOJSON:\n return 'geojson';\n }\n }\n // If we get invalid input, return undefined type.\n return undefined;\n }",
"function getFullName(type) {\n if (type) {\n type = type.toLowerCase();\n switch (type) {\n case 'q':\n case QUANTITATIVE:\n return 'quantitative';\n case 't':\n case TEMPORAL:\n return 'temporal';\n case 'o':\n case ORDINAL:\n return 'ordinal';\n case 'n':\n case NOMINAL:\n return 'nominal';\n case Type.LATITUDE:\n return 'latitude';\n case Type.LONGITUDE:\n return 'longitude';\n case GEOJSON:\n return 'geojson';\n }\n }\n // If we get invalid input, return undefined type.\n return undefined;\n }",
"function getResourceName(type) {\n var elements = type.split('/');\n return elements.pop();\n}",
"function nameToURL(sName) {\n /* replace any spaces and turn backslahes into forward slashes */\n sName = sName.replace('%20', ' ');\n sName = sName.replace('\\\\', '\\/');\n\n /* see if this looks like a full URL */\n if (!(sName.match(/^(http|https|file):\\/\\/[A-Za-z0-9-]+\\.[A-Za-z0-9]+/))) {\n /* it does not, put the baseref of this page in front of the name */\n var sWinURL = window.location.href;\n var sBaseRef = sWinURL.substring(0, sWinURL.lastIndexOf('/'));\n sName = sBaseRef + '/' + sName;\n }\n return sName;\n}",
"function natureNameToURL(natureName) {\n switch (natureName) {\n case \"Waterfall\":\n return browser.extension.getURL(\"nature/waterfall.jpg\");\n case \"Snow\":\n return browser.extension.getURL(\"nature/snow.jpg\");\n case \"Nightfall\":\n return browser.extension.getURL(\"nature/nightfall.jpg\");\n }\n }",
"function parseType(typeUri) {\n return typeUri === null || typeUri === undefined ? \"(No type)\" :\n typeUri.\n // Remove everything up to the last \"/\"\n replace(/.*\\//gi, \"\").\n // Insert spaces before capitals, e.g., \"SomeType\" -> \"Some Type\"\n replace(/([A-Z])/g, '$1');\n}",
"function urlConverter(nombre){\n return \"https//www.\" + nombre + \".com\"\n}",
"function typeName(type) {\n switch (type) {\n case \"BB\":\n return \"Battleship\";\n case \"CV\":\n return \"Carrier\";\n case \"CL\":\n return \"Light Cruiser\";\n case \"CVL\":\n return \"Light Carrier\";\n }\n return \"Cruiser\";\n}",
"importUri(type) {\r\n // StaticSymbol\r\n if (typeof type === 'object' && type['filePath']) {\r\n return type['filePath'];\r\n }\r\n // Runtime type\r\n return `./${stringify(type)}`;\r\n }",
"importUri(type) {\n // StaticSymbol\n if (typeof type === 'object' && type['filePath']) {\n return type['filePath'];\n } // Runtime type\n\n\n return `./${stringify(type)}`;\n }",
"importUri(type) {\n // StaticSymbol\n if (typeof type === 'object' && type['filePath']) {\n return type['filePath'];\n }\n // Runtime type\n return `./${stringify(type)}`;\n }",
"function getUrlType(fragURL) {\n var type;\n var types = {\n \"live\": \"https:\\/\\/www.canada.ca\\/(.*?).html\",\n \"preview\": \"https:\\/\\/canada-preview.adobecqms.net\\/(.*?).html\",\n \"editor\": \"https:\\/\\/author-canada-prod.adobecqms.net\\/editor.html(.*?).html\",\n \"aemUrl\": \"https:\\/\\/author-canada-prod.adobecqms.net\\/sites.html(.*?)\\s\"\n };\n $.each(types, function(key, value) {\n var testingForType = fragURL.match(value);\n if (testingForType != null) {\n type = key;\n }\n });\n if (type == null) type = \"type is not defined\";\n return type;\n }",
"function nameFromURL(url)\n{\n var match = url.match(/redd\\.it\\/([A-Za-z0-9]+)/i); // Shortened\n if (match) {\n return match[1].toLowerCase();\n }\n match = url.match(/r\\/HFY\\/comments\\/([A-Za-z0-9]+)(?:\\/\\w*(\\/[A-Za-z0-9]+))?/i);\n if (match) {\n var name = match[1].toLowerCase();\n if (match[2]) {\n name += \"/\" + match[2].toLowerCase(); // This is a nested name referring to a comment.\n }\n return name;\n }\n return undefined;\n}",
"getPath2Check(type) {\n if (typeof (_ADM_Channel) !== 'undefined' && _ADM_Channel !== '') { // eslint-disable-line no-undef,camelcase\n return decodeURIComponent(_ADM_Channel); // eslint-disable-line no-undef,camelcase\n }\n const url = document.URL;\n const ref = document.referrer;\n let http = (type === 'Site:Pageurl') ? url.replace(/\\?i=([0-9]+)&bz=([0-9]+)&z=([0-9]+)#([0-9_0-9]+)/g, '') : ref.replace(/\\?i=([0-9]+)&bz=([0-9]+)&z=([0-9]+)#([0-9_0-9]+)/g, '');\n const arrUrlReg = http.match(/([^|]+)/i);\n if (arrUrlReg) {\n http = `${arrUrlReg[0]}`;\n }\n return http.toLowerCase();\n }",
"function githubUrlForType(type) {\n return `https://raw.githubusercontent.com/afram/AnApiOfIceAndFire/master/AnApiOfIceAndFire.Data.Feeder/Data/${type}.json`;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a function `addToObject` that takes an object, a key, and an array as arguments and adds the array to the object as the value of the given key. The changes should be made directly to the argument and should change the object without any reassignment | function addToObject(obj, key, arr) {
// -------------------- Your Code Here --------------------
obj[key] = arr;
// --------------------- End Code Area --------------------
} | [
"function addArrayProperty(obj, key, arr) {\n\t// object at the key reassign value to arr\n\tobj[key] = arr;\n\t// return arr\n\treturn obj;\n}",
"function addValue(obj, key, value) {\n if (obj.hasOwnProperty(key)) {\n obj[key].push(value);\n } else {\n obj[key] = [value];\n }\n}",
"function addKeyAndValue(arr, key, value) {\n arr.forEach(obj => obj[key] = value);\n return arr;\n}",
"function addKeyAndValue(arr, key, value) {\n\tarr.forEach(function(obj){\n\t\tobj[key] = value;\n\t})\n\treturn arr;\n}",
"function addKeyAndValue(array, key, value) {\n\tarray.forEach(function(val) {\n\t\tval[key] = value;\n\t})\n}",
"function addKeyAndValue(arr, key, value) {\n\tarr.forEach(function(val) {\n\t\tval[key] = value;\n\t});\n\treturn arr;\n}",
"function push_set(obj, key, value) {\n if (obj[key]) {\n obj[key].push(value);\n } else {\n obj[key] = [value];\n }\n}",
"function addKeyAndValue(arr,key,value){\n arr.forEach((i) =>{\n i[key] = value;\n })\n return arr;\n}",
"function addKeyAndValue(arr, key, value) {\n arr.forEach(ele => {\n ele[key] = value;\n });\n return arr;\n}",
"function addKeyAndValue(array, key, value) {\n\treturn array.reduce(function(acc, val) {\n\t\tval[key] = value;\n\t\treturn array;\n\t}, array)\n}",
"function addKeyAndValue(arr, key, value){\nreturn arr.reduce(function(accm, next, idx){\naccm[idx] [key] = value;\nreturn accm;\n},arr)\n}",
"function addKeyValuePairToObject(object, key, value) {\n return { ...object, [key]: value };\n}",
"function updateObjectWithKeyAndValue(object, key, value) {\n object[key]=value;\n return object;\n}",
"function updateObject(object, key, newValue){\n // if(object[key] === key){ //if the object has the key property already\n // object[key] = newValue;\n // } else { //if the object does not have the key\n // object[key] = newValue; //creating a key holding newValue\n // }\n //the above code works, but let's try something simpler //\n object[key] = newValue;\n return object;\n}",
"function addprop(obj, key, val) {\n if(obj[key]) {\n if(isArray(obj[key])) {\n obj[key].push(val);\n } else {\n obj[key] = [obj[key], val];\n }\n } else {\n obj[key] = val;\n }\n}",
"function append (desiredKey, masterObject, singleObject){\n\t\n\tmasterObject[desiredKey] = singleObject; //writing to the master object, under specified key\n}",
"function addKeyandValue(arrObjs, key, value) {\n\n arrObjs.forEach(function(oneObj){\n\n oneObj[key] = value;\n\n })\n return arrObjs;\n}",
"function addKeyAndValue(arr, key, value) {\n\treturn arr.reduce(function(acc, next, idx){\n\t\tacc[idx][key] = value;\n\t}, arr);\n}",
"function addKeyAndValue(arr, key, value) {\n\t\treturn arr.reduce(function(acc, next, idx) {\n\t\t acc[idx][key] = value;\n\t\t return acc;\n\t\t}, arr)\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the AWS CloudFormation properties of an `AWS::IoTEvents::AlarmModel.AcknowledgeFlow` resource | function cfnAlarmModelAcknowledgeFlowPropertyToCloudFormation(properties) {
if (!cdk.canInspect(properties)) {
return properties;
}
CfnAlarmModel_AcknowledgeFlowPropertyValidator(properties).assertSuccess();
return {
Enabled: cdk.booleanToCloudFormation(properties.enabled),
};
} | [
"renderAlarmRule() {\n return `ALARM(${this.alarmArn})`;\n }",
"renderAlarmRule() {\n return `ALARM(\"${this.alarmArn}\")`;\n }",
"function CfnAlarmModel_AcknowledgeFlowPropertyValidator(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('enabled', cdk.validateBoolean)(properties.enabled));\n return errors.wrap('supplied properties not correct for \"AcknowledgeFlowProperty\"');\n}",
"function cfnAlarmModelAlarmCapabilitiesPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAlarmModel_AlarmCapabilitiesPropertyValidator(properties).assertSuccess();\n return {\n AcknowledgeFlow: cfnAlarmModelAcknowledgeFlowPropertyToCloudFormation(properties.acknowledgeFlow),\n InitializationConfiguration: cfnAlarmModelInitializationConfigurationPropertyToCloudFormation(properties.initializationConfiguration),\n };\n}",
"function cfnAlarmModelAlarmActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAlarmModel_AlarmActionPropertyValidator(properties).assertSuccess();\n return {\n DynamoDB: cfnAlarmModelDynamoDBPropertyToCloudFormation(properties.dynamoDb),\n DynamoDBv2: cfnAlarmModelDynamoDBv2PropertyToCloudFormation(properties.dynamoDBv2),\n Firehose: cfnAlarmModelFirehosePropertyToCloudFormation(properties.firehose),\n IotEvents: cfnAlarmModelIotEventsPropertyToCloudFormation(properties.iotEvents),\n IotSiteWise: cfnAlarmModelIotSiteWisePropertyToCloudFormation(properties.iotSiteWise),\n IotTopicPublish: cfnAlarmModelIotTopicPublishPropertyToCloudFormation(properties.iotTopicPublish),\n Lambda: cfnAlarmModelLambdaPropertyToCloudFormation(properties.lambda),\n Sns: cfnAlarmModelSnsPropertyToCloudFormation(properties.sns),\n Sqs: cfnAlarmModelSqsPropertyToCloudFormation(properties.sqs),\n };\n}",
"_renderTask() {\n return {\n Resource: (0, task_utils_1.integrationResourceArn)('events', 'putEvents', this.integrationPattern),\n Parameters: sfn.FieldUtils.renderObject({\n Entries: this.renderEntries(),\n }),\n };\n }",
"function cfnApplicationAlarmPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnApplication_AlarmPropertyValidator(properties).assertSuccess();\n return {\n AlarmName: cdk.stringToCloudFormation(properties.alarmName),\n Severity: cdk.stringToCloudFormation(properties.severity),\n };\n}",
"function cfnCompositeAlarmPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnCompositeAlarmPropsValidator(properties).assertSuccess();\n return {\n AlarmRule: cdk.stringToCloudFormation(properties.alarmRule),\n ActionsEnabled: cdk.booleanToCloudFormation(properties.actionsEnabled),\n ActionsSuppressor: cdk.stringToCloudFormation(properties.actionsSuppressor),\n ActionsSuppressorExtensionPeriod: cdk.numberToCloudFormation(properties.actionsSuppressorExtensionPeriod),\n ActionsSuppressorWaitPeriod: cdk.numberToCloudFormation(properties.actionsSuppressorWaitPeriod),\n AlarmActions: cdk.listMapper(cdk.stringToCloudFormation)(properties.alarmActions),\n AlarmDescription: cdk.stringToCloudFormation(properties.alarmDescription),\n AlarmName: cdk.stringToCloudFormation(properties.alarmName),\n InsufficientDataActions: cdk.listMapper(cdk.stringToCloudFormation)(properties.insufficientDataActions),\n OKActions: cdk.listMapper(cdk.stringToCloudFormation)(properties.okActions),\n };\n}",
"function cfnCompositeAlarmPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnCompositeAlarmPropsValidator(properties).assertSuccess();\n return {\n AlarmName: cdk.stringToCloudFormation(properties.alarmName),\n AlarmRule: cdk.stringToCloudFormation(properties.alarmRule),\n ActionsEnabled: cdk.booleanToCloudFormation(properties.actionsEnabled),\n AlarmActions: cdk.listMapper(cdk.stringToCloudFormation)(properties.alarmActions),\n AlarmDescription: cdk.stringToCloudFormation(properties.alarmDescription),\n InsufficientDataActions: cdk.listMapper(cdk.stringToCloudFormation)(properties.insufficientDataActions),\n OKActions: cdk.listMapper(cdk.stringToCloudFormation)(properties.okActions),\n };\n}",
"function cfnTopicRuleCloudwatchAlarmActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnTopicRule_CloudwatchAlarmActionPropertyValidator(properties).assertSuccess();\n return {\n AlarmName: cdk.stringToCloudFormation(properties.alarmName),\n RoleArn: cdk.stringToCloudFormation(properties.roleArn),\n StateReason: cdk.stringToCloudFormation(properties.stateReason),\n StateValue: cdk.stringToCloudFormation(properties.stateValue),\n };\n}",
"function cfnPortalAlarmsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnPortal_AlarmsPropertyValidator(properties).assertSuccess();\n return {\n AlarmRoleArn: cdk.stringToCloudFormation(properties.alarmRoleArn),\n NotificationLambdaArn: cdk.stringToCloudFormation(properties.notificationLambdaArn),\n };\n}",
"function cfnAlarmModelIotEventsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAlarmModel_IotEventsPropertyValidator(properties).assertSuccess();\n return {\n InputName: cdk.stringToCloudFormation(properties.inputName),\n Payload: cfnAlarmModelPayloadPropertyToCloudFormation(properties.payload),\n };\n}",
"function cfnAlarmPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAlarmPropsValidator(properties).assertSuccess();\n return {\n ComparisonOperator: cdk.stringToCloudFormation(properties.comparisonOperator),\n EvaluationPeriods: cdk.numberToCloudFormation(properties.evaluationPeriods),\n ActionsEnabled: cdk.booleanToCloudFormation(properties.actionsEnabled),\n AlarmActions: cdk.listMapper(cdk.stringToCloudFormation)(properties.alarmActions),\n AlarmDescription: cdk.stringToCloudFormation(properties.alarmDescription),\n AlarmName: cdk.stringToCloudFormation(properties.alarmName),\n DatapointsToAlarm: cdk.numberToCloudFormation(properties.datapointsToAlarm),\n Dimensions: cdk.listMapper(cfnAlarmDimensionPropertyToCloudFormation)(properties.dimensions),\n EvaluateLowSampleCountPercentile: cdk.stringToCloudFormation(properties.evaluateLowSampleCountPercentile),\n ExtendedStatistic: cdk.stringToCloudFormation(properties.extendedStatistic),\n InsufficientDataActions: cdk.listMapper(cdk.stringToCloudFormation)(properties.insufficientDataActions),\n MetricName: cdk.stringToCloudFormation(properties.metricName),\n Metrics: cdk.listMapper(cfnAlarmMetricDataQueryPropertyToCloudFormation)(properties.metrics),\n Namespace: cdk.stringToCloudFormation(properties.namespace),\n OKActions: cdk.listMapper(cdk.stringToCloudFormation)(properties.okActions),\n Period: cdk.numberToCloudFormation(properties.period),\n Statistic: cdk.stringToCloudFormation(properties.statistic),\n Threshold: cdk.numberToCloudFormation(properties.threshold),\n ThresholdMetricId: cdk.stringToCloudFormation(properties.thresholdMetricId),\n TreatMissingData: cdk.stringToCloudFormation(properties.treatMissingData),\n Unit: cdk.stringToCloudFormation(properties.unit),\n };\n}",
"function cfnAlarmModelAlarmEventActionsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAlarmModel_AlarmEventActionsPropertyValidator(properties).assertSuccess();\n return {\n AlarmActions: cdk.listMapper(cfnAlarmModelAlarmActionPropertyToCloudFormation)(properties.alarmActions),\n };\n}",
"function cfnAlarmModelPayloadPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAlarmModel_PayloadPropertyValidator(properties).assertSuccess();\n return {\n ContentExpression: cdk.stringToCloudFormation(properties.contentExpression),\n Type: cdk.stringToCloudFormation(properties.type),\n };\n}",
"function cfnAlarmModelFirehosePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAlarmModel_FirehosePropertyValidator(properties).assertSuccess();\n return {\n DeliveryStreamName: cdk.stringToCloudFormation(properties.deliveryStreamName),\n Payload: cfnAlarmModelPayloadPropertyToCloudFormation(properties.payload),\n Separator: cdk.stringToCloudFormation(properties.separator),\n };\n}",
"renderProperties(x) { return ui.divText(`Properties for ${x.name}`); }",
"function cfnAlarmModelSqsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAlarmModel_SqsPropertyValidator(properties).assertSuccess();\n return {\n Payload: cfnAlarmModelPayloadPropertyToCloudFormation(properties.payload),\n QueueUrl: cdk.stringToCloudFormation(properties.queueUrl),\n UseBase64: cdk.booleanToCloudFormation(properties.useBase64),\n };\n}",
"function cfnApplicationAlarmMetricPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnApplication_AlarmMetricPropertyValidator(properties).assertSuccess();\n return {\n AlarmMetricName: cdk.stringToCloudFormation(properties.alarmMetricName),\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
for getting url after applying sorting | function finalurl() {
var url = new URL(window.location.href);
var search_params = url.searchParams;
search_params.set('sorting', document.getElementById("sort-list").value);
url.search = search_params.toString();
var new_url = url.toString();
return new_url
} | [
"function SortByColor()\r\n{\r\n var URL = ''; \r\n URL = document.location.href;\r\n var ArrKeys = URL.toQueryParams();\r\n var sSort = ArrKeys[\"sort\"];\r\n switch(sSort)\r\n {\r\n case \"IntColor\"://Interior Color\r\n sSort =\"Color\";\r\n break;\r\n case \"Color\":\r\n sSort =\"IntColor\"//Interior Color \r\n break; \r\n default:\r\n sSort =\"Color\";\r\n break; \r\n }\r\n var str1 ,str2; \r\n var index = URL.indexOf(\"sort=\");\r\n if (index > 0)\r\n {\r\n if(URL.charAt(index +5) != \"&\" ){\r\n str1 = URL.substring(0,index +5);\r\n str2 = URL.substring(str1.length ,URL.length);\r\n if(str2.indexOf (\"&\") > 0)\r\n {URL = str2.substring (str2.indexOf (\"&\"),str2.length );}\r\n else {URL = \"\";}\r\n }\r\n document.location.href=str1 + sSort + URL;\r\n } \r\n}",
"function SortByAuctionDateLaneLrun(){\r\n var URL = ''; \r\n URL = document.location.href;\r\n var ArrKeys = URL.toQueryParams();\r\n var sSort = ArrKeys[\"sort\"];\r\n switch(sSort)\r\n {\r\n case \"AtDtLnRn\":\r\n sSort =\"DtAtLnRn\";\r\n break;\r\n case \"DtAtLnRn\":\r\n sSort =\"AtDtLnRn\";\r\n break; \r\n default:\r\n sSort =\"AtDtLnRn\";\r\n break; \r\n }\r\n var str1 ,str2; \r\n var index = URL.indexOf(\"sort=\");\r\n if (index > 0)\r\n {\r\n if(URL.charAt(index +5) != \"&\" ){\r\n str1 = URL.substring(0,index +5);\r\n str2 = URL.substring(str1.length ,URL.length);\r\n if(str2.indexOf (\"&\") > 0)\r\n {URL = str2.substring (str2.indexOf (\"&\"),str2.length );}\r\n else {URL = \"\";}\r\n }\r\n document.location.href=str1 + sSort + URL;\r\n } \r\n}",
"function getVisibleSorting() {\n\tvar split = window.location.href.split(/[/#/?]/);\n\tfor (var i = 0; i < split.length; i++) {\n\t\tif (split[i].startsWith(\"sort=\")) {\n\t\t\treturn split[i].substring(5);\n\t\t}\n\t}\n\treturn \"\";\n}",
"updateUrl(){void 0===this.sortKey||Object.keys(this.schema.get('schema').properties).includes(this.sortKey)||(console.warn('sortKey is invalid, as sortKey will be set \"id\" key.'),this.sortKey='id'),void 0===this.sortOrder||'asc'===this.sortOrder||'desc'===this.sortOrder||(console.warn('sortOrder should be asc or desc, as sortOrder will be set \"asc\".'),this.sortOrder='asc');let l='',m='',n='?';for(let o in this.filters)this.filters.hasOwnProperty(o)&&(l+='&'+o+'='+this.filters[o]);0!==this.pageLimit&&(m='&limit='+this.pageLimit+'&offset='+this.offset),this.baseUrl.includes('?')&&(n='&'),this.url=this.baseUrl+n+'sort_key='+this.sortKey+'&sort_order='+this.sortOrder+m+l}",
"function sortLinks(ob1,ob2) {\n if (ob1.source_name > ob2.source_name) {\n return 1;\n } else if (ob1.source_name < ob2.source_name) { \n return -1;\n }\n\n // Else go to the 2nd item\n if (ob1.target_name < ob2.target_name) { \n return -1;\n } else if (ob1.target_name > ob2.target_name) {\n return 1\n } else { // nothing to split them\n return 0;\n }\n}",
"updateUrl() {\n if (this.sortKey !== undefined && !Object.keys(this.schema.get('schema').properties).includes(this.sortKey)) {\n console.warn('sortKey is invalid, as sortKey will be set \"id\" key.');\n this.sortKey = 'id';\n }\n\n if (this.sortOrder !== undefined && !(this.sortOrder === 'asc' || this.sortOrder === 'desc')) {\n console.warn('sortOrder should be asc or desc, as sortOrder will be set \"asc\".');\n this.sortOrder = 'asc';\n }\n let filter = '';\n let pagination = '';\n let queryExtension = '?';\n\n for (let key in this.filters) {\n if (this.filters.hasOwnProperty(key)) {\n filter += '&' + key + '=' + this.filters[key];\n }\n }\n\n if (this.pageLimit !== 0) {\n pagination = '&limit=' + this.pageLimit + '&offset=' + this.offset;\n }\n if (this.baseUrl.includes('?')) {\n queryExtension = '&';\n }\n\n this.url = this.baseUrl + queryExtension + 'sort_key=' + this.sortKey + '&sort_order=' + this.sortOrder +\n pagination + filter;\n }",
"function getSort() {\n var search = window.location.search;\n var sort = '';\n if(search.length){\n res = search.slice(1).split('&');\n for(var i = 0; i<res.length; i++){\n var arr = res[i].split('=');\n if(arr[0] == 'sort') {\n sort +='&sort=' + arr[1];\n }\n if(arr[0] == 'order') {\n sort +='&order=' + arr[1];\n }\n }\n }\n return sort;\n}",
"function buildUrl(base)\n\t{\n\tvar url = parseUrl(base);\n\tvar args = url.args\n\targs.method=sortMethod;\n\targs.direction = sortDirection;\n\treturn (url.base+'?'+$.param(args));\n\t}",
"function sortBySeedsDescending() {\n var url = window.location.href,\n searchPattern = /(\\/[0-9]+\\/)(99)(\\/[0-9])+/,\n browsePattern = /browse\\/[0-9]+$/;\n if (url.match(searchPattern)) {\n var newUrl = url.replace(searchPattern, \"$17$3\");\n window.location.replace(newUrl);\n } else if (url.match(browsePattern)) {\n var newUrl = url + \"/0/7/0\";\n window.location.replace(newUrl);\n }\n }",
"function SortByBidTimeLeft(){\r\n var URL = ''; \r\n URL = document.location.href;\r\n var ArrKeys = URL.toQueryParams();\r\n var sSort = ArrKeys[\"sort\"];\r\n switch(sSort)\r\n {\r\n case \"BTAsc\":\r\n sSort =\"BTDes\";\r\n break;\r\n case \"BTDes\":\r\n sSort =\"BTAsc\"; \r\n break; \r\n default:\r\n sSort =\"BTAsc\";\r\n break; \r\n }\r\n var str1 ,str2; \r\n var index = URL.indexOf(\"sort=\");\r\n if (index >0)\r\n {\r\n if(URL.charAt(index +5) != \"&\" ){\r\n str1 = URL.substring(0,index +5);\r\n str2 = URL.substring(str1.length ,URL.length);\r\n if(str2.indexOf (\"&\") > 0)\r\n {URL = str2.substring (str2.indexOf (\"&\"),str2.length );}\r\n else {URL = \"\";}\r\n }\r\n document.location.href=str1 + sSort + URL;\r\n }\r\n }",
"function sortBy(sortType) {\n var currentPath = window.location.href;\n var basePath = currentPath.split('&');\n var siteIndexVal = basePath[0].indexOf('site=');\n var urlQuery = siteIndexVal > 0 ? basePath[0] + '&' + basePath[1] : basePath[0];\n window.location.href = urlQuery + '&sort=' + sortType;\n }",
"function _CheckMySortFromURL(){\n\n\t// -- Check from Filter Array\n\tvar i=0;\n\tvar filterNumb=0;\n\twhile(i<_$filterObjects.length){\n\t\tif(window.location.hash.replace(\"#/\", \"\") === _$filterObjects[i].nameid){\n\t\t\t_SortProjectByFilter( _$filterObjects[i] );\n\t\t\tfilterNumb ++;\n\t\t\ti = _$filterObjects.length;\n\t\t} else {\n\t\t\ti++;\n\t\t}\n\t}\n\t\n\t// -- If the page is at top level\n if (_$currentPageType == \"top\") {\n \t// -- If filter is applied, skip\n \tif(filterNumb > 0 || window.location.hash.replace(\"#/\", \"\") === \"all\"){\n \t_GRID_OpenImmediately();\n \t}else{\n \t// Check if it is number and if so to slide\n \tvar m = 0;\n \twhile(m <= _$heroCount){\n \t\tif (parseInt(window.location.hash.replace(\"#/\", \"\")) === m) {\n \t\t\t_$heroCounter = m - 1;\n\t\t\t\t\t_HERO_AdjustProject();\n \t\t\tm = _$heroCount;\n \t\t}\n \t\tm++;\n \t}\n\n }\n }\n\n}",
"function checkURL() {\n // Try URL first\n var param = loc.search;\n\n if (param) {\n // Most Recent: ?sk=h_chr\n // Top Stories: ?sk=h_nor\n\n // Not currently sorted by most recent\n if (param.indexOf('sk=h_chr') === -1) {\n changeSort();\n }\n\n // Successfully determined sort\n return true;\n }\n else {\n param = loc.pathname.replace(/^\\//, '');\n\n if (param && param.length) {\n // We're not on the home page, so sorting is not applicable\n return true;\n }\n }\n\n // Failed to determine sort via URL\n return false;\n }",
"function sortLinks()\n { \n data.links.sort(function(a,b) {\n if (a.source > b.source) \n {\n return 1;\n }\n else if (a.source < b.source) \n {\n return -1;\n }\n else \n {\n if (a.target > b.target) \n {\n return 1;\n }\n if (a.target < b.target) \n {\n return -1;\n }\n else \n {\n return 0;\n }\n }\n });\n }",
"function sortLinks()\n { \n data.links.sort(function(a,b) {\n if (a.source > b.source) \n {\n return 1;\n }\n else if (a.source < b.source) \n {\n return -1;\n }\n else \n {\n if (a.target > b.target) \n {\n return 1;\n }\n if (a.target < b.target) \n {\n return -1;\n }\n else \n {\n return 0;\n }\n }\n });\n }",
"_urlfilter (curPage, href) {\n //console.log(href)\n //return !!_getLocation(href) && ( _getLocation(href).main == _getLocation(curPage).main )\n return href.match(/^http[s]*\\:\\/\\/waimai.meituan.com\\/restaurant\\/(\\d+)$/);\n }",
"function historyListSearchUrl (hl, id) {\r\n let record;\r\n let url = undefined;\r\n let hnList = hl.hnList;\r\n for (let i=hnList.length-1 ; i>= 0 ; i--) {\r\n\trecord = hnList[i];\r\n\tif ((record.id == id)\r\n\t\t&& (((url = record.toUrl) != undefined) || ((url = record.url) != undefined))\r\n\t ) {\r\n\t break;\r\n\t}\r\n }\r\n return(url);\r\n}",
"function checkUrl(){\n if(href!= undefined ){\n href = href.replace('index.html', ''); // for remove index.html\n href = href.replace('index.htm', ''); // for remove index.htm\n }\n\t if(href!= undefined && href.substr(-1) == '/') {\n\t\thref = href.substring(0,href.length - 1); // for remove \"/\" from string \"30-04-15\"\n\t }\n //console.log(finalMenuJsonArray);\n\t \n // for remove # from url\n hashName='';\n\t if(href.indexOf(\"#\") != -1){\n\t var hrefArray = href.split(\"#\"); \n\t url=hrefArray['0']?hrefArray['0']:'';\n\t hashName=hrefArray['1']?hrefArray['1']:'';\n is_hashUrl=true;\n\t}\n\t hashUrl=\"\";\n\t for (i=0;i<finalMenuJsonArray.length;i++){\n\t if(finalMenuJsonArray[i].name==hashName){\n\t\t\t\t hashUrl=finalMenuJsonArray[i].url;\n\t\t\t\t getListJson(hashUrl); \n\t\t\t\t } \n\t } \n\t \t \n}",
"async function pushURL(option) { \n if (option && option == \"latestFilter\") {\n history.replaceState(null, \"\", \"/?\" + currentFilter + \"&sort=date_desc\");\n }\n else {\n history.replaceState(null, \"\", \"/?\" + currentFilter + \"&sort=\" + currentSort + \"_\" + currentSortOrder); \n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update list after sync deleted catalog rule price | updateListAfterSyncDeletedCatalogRulePrice(ids = []) {
if (ids && ids.length) {
let items = ProductListService.prepareItemsToUpdateListAfterSyncDeletedCatalogRulePrice(
ids, this.state.items
);
if (items !== false) {
this.addItems(items);
}
this.props.actions.resetSyncActionDeletedCatalogRulePrice();
}
} | [
"updateListAfterSyncCatalogRulePrice(catalogrule_prices = []) {\n if (catalogrule_prices && catalogrule_prices.length) {\n let items = ProductListService.prepareItemsToUpdateListAfterSyncCatalogRulePrice(\n catalogrule_prices, this.state.items\n );\n if (items !== false) {\n this.addItems(items);\n }\n this.props.actions.resetSyncActionUpdateCatalogRulePrice();\n }\n }",
"updatePrice() { }",
"updatePrice() {\n\t\treturn this.products.map((product) => {\n\t\t\tproduct.updatePrice();\n\t\t\tproduct.updateSellInDays();\n\t\t\treturn product;\n\t\t});\n\t}",
"function updatePriceList() {\n\tnajax(\"https://api.csgofast.com/price/all\", \n\t\t(data) => {\n\t\t\ttry {\n\t\t\t\tpriceList = JSON.parse(data);\n\t\t\t\tconsole.log(\"Pricelist Loaded.\")\n\t\t\t} catch(e) {\n\t\t\t\tconsole.log(\"Pricelist failed to load with error \" + e);\n\t\t\t\tconsole.log(data);\n\t\t\t\tconsole.log(\"Retrying in 5 seconds...\");\n\t\t\t\tsetTimeout(updatePriceList, 5000);\n\t\t\t}\n\t\t}\n\t)\n}",
"function update() {\nvar po = [];\nvar totalItemsPrice = 0.00;\n$options.each( function() {\nvar $option = $(this);\nvar pOption = new ProductOptions();\npOption.id = $option.get(0).id;\npOption.title = fixQuotIssue($option.data('title'));\npOption.type = $option.data('type');\nswitch( $option.data('type') ) {\ncase 'color':\nvar $color = $option.find('.p-o-color.selected');\nif ( $color.length === 0 ) return;\npOption.item.id = $color.get(0).id\npOption.item.title = fixQuotIssue($color.attr('title'));\npOption.item.price = $color.data('price');\nbreak;\ncase 'list':\nvar $list = $option.find('.p-o-list');\nvar $listSelectedOpt = $list.find('option:selected');\nif ( $list.find('option').length === 0 ) return;\npOption.item.id = $listSelectedOpt.get(0).id;\npOption.item.title = fixQuotIssue($list.val());\npOption.item.price = $listSelectedOpt.data('price');\nbreak;\n}\ntotalItemsPrice += parseFloat(pOption.item.price);\npo.push(pOption);\n});\n$('#productOptions').html(JSON.stringify(po));\naddItemsPrice(totalItemsPrice);\n}",
"function changePriceInProduct() {\n productList.forEach(pr => {\n if (valuta === 'eur') {\n pr.price = (pr.price / EUR_RSD).toFixed(2);\n } else {\n pr.price = (pr.price * EUR_RSD).toFixed(0);\n }\n });\n updatePricesTextOnCurrencyChange();\n}",
"depreciateStock() {\n // For every item that is above its base price, reduce its price.\n for (let i = 0; i < this.stock.length; i += 1) {\n const item = this.stock[i];\n if (item.price > item.basePrice) {\n item.price -= 5;\n // Make sure it doesn't go below the base price.\n if (item.price < item.basePrice) {\n item.price = item.basePrice;\n }\n // Update the price list.\n this.prices[i] = item.price;\n }\n }\n }",
"function updatePriceList(){\n\t\t$(\"#customerPriceListContainer\").load(\"customerprice?listfragment\", function() {\n\t\t\tKPS.data.locations.setupLocationNameHover();\n\t\t});\n\t}",
"@api\n addStock(removedProducts){\n for (var i in this.products) {\n for (var removedProduct of removedProducts) {\n if (this.products[i].productId == removedProduct[\"productId\"]) {\n let productTotal = (parseInt(removedProduct[\"quantityNeeded\"], 10) + this.products[i].productStock);\n this.products[i].productStock = productTotal;\n break; \n }\n } \n } \n this.reloadProducts();\n }",
"function PriceListBySKUReceived() {\n var pSql = \"DELETE FROM PRICE_LIST_BY_SKU\";\n window.gInsertsInitialRoute.push(pSql);\n}",
"function priceRefresh()\n{\n for(let i=0; i<events.length; i++)\n {\n events[i].price = priceCalculation(events[i].id);\n }\n}",
"_updateAutomaticDiscounts() {\n if (!this._eligibleForDiscount()) return;\n\n let discounts = this.get('host.membershipDiscounts');\n let items = this.get('orderLineItems');\n let activeDiscounts = items.filterBy('lineItem.isADiscount');\n let activeNonDiscounts = items.filterBy('lineItem.isADiscount', false);\n\n // let activeDiscounts = items.any((item, i, e) => {\n // return item.get('lineItem.isADiscount');\n // });\n\n if (activeNonDiscounts.get('length') > 0) {\n discounts.forEach((discount, i, e) => {\n // only check discounts for lessons for now\n if (discount.get('appliesTo').indexOf('Lesson') !== -1) {\n let numberOfLessons = 0;\n activeNonDiscounts.forEach((orderLineItem, i, e) => {\n if (orderLineItem.get('lineItem.isLesson')) {\n // apply the discount\n let quantity = orderLineItem.get('quantity');\n\n numberOfLessons += quantity;\n }\n });\n\n if (numberOfLessons > 0) {\n this.addLineItem(discount, numberOfLessons);\n }\n }\n });\n } else {\n // we can't have just discounts -- remove everything\n activeDiscounts.forEach((discount, i, e) => {\n this.removeOrderLineItem(discount);\n });\n }\n }",
"function refreshPrice(p) {\n p.price = caculatePrice(p.sizePrice, p.toppingPrice, p.crustPrice, p.tax);\n setPizzaContent(p);\n}",
"function updateProductQtd(list, product) {\n let newList = list.map(item => {\n if (item.id == product.id) {\n\n item.qtd = product.qtd;\n return item;\n }\n\n return item;\n });\n\n storageHelper.save('cartProducts', newList);\n return newList;\n }",
"updatePriceFromPricing () {\n this.config.display.amount = this.pricing.totalNow;\n this.config.display.currency = this.pricing.currencyCode;\n }",
"function update_projects_items_prices() {\n var items_projet = items_ranges[\"projets\"].getValues();\n Logger.log(\"update_projects_items_prices() : items_projet = \" + items_projet);\n var new_item_list = update_tracked_items_list(items_projet);\n}",
"function updateAllPrices() {\n\t//debugMe(newPrices[0]+','+newPrices[1]+','+newPrices[2]+','+newPrices[3]); \n\t$('#price-1').updatePrice(window.prices[0]);\n\t$('#price-2').updatePrice(window.prices[1]);\n\t$('#price-3').updatePrice(window.prices[2]);\n\t$('#price-4').updatePrice(window.prices[3]);\n}",
"_deleteLocalList() {\n delete this.autoNumericLocalList;\n }",
"function updateProducts(){\n $('.cart-products > li').each(function(){\n var $transformed = $(this);\n var $original = $('#' + $transformed.attr('data-id')).closest('tr');\n if ($original.length) {\n\n // Update quantity, price\n $transformed.find('.qty-stepper input').val($original.find('[id^=\"qty_\"]').val());\n $transformed.find('.price').text($original.find('.each .price').first().text());\n\n // Update promo information\n var promo = $original.next('tr');\n if (promo.length) {\n promo = parsePromo(promo);\n }\n if (promo.discount) {\n $transformed.find('.promo').addClass('active');\n $transformed.find('.promo .discount').text(promo.discount);\n $transformed.find('.promo .value').text(promo.value);\n } else {\n $transformed.find('.promo').removeClass('active');\n }\n\n } else {\n $transformed.remove();\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Should further reducers need to be utilized, we can combine them here in the Root Reducer. Asis, we only have 'accounts'. | function rootReducer() {
return combineReducers({
accounts: accountReducer,
})
} | [
"combine() {\n this.shared.combined = {}\n for (var id in this.shared.rules) {\n for (var r in this.shared.rules[id]) {\n this.shared.combined[r] =\n this.shared.rules[id][r]\n }\n }\n }",
"function getRootReducer(appName) {\n var appReducers;\n\n if (LIMIT_REDUCERS) {\n // only load the reducer for the appropriate app\n switch (appName) {\n case _config__WEBPACK_IMPORTED_MODULE_3__[/* APP_TOPIC_MAPPER */ \"d\"]:\n appReducers = {\n topics: _topics_topics__WEBPACK_IMPORTED_MODULE_6__[/* default */ \"a\"]\n };\n break;\n\n case _config__WEBPACK_IMPORTED_MODULE_3__[/* APP_SOURCE_MANAGER */ \"b\"]:\n appReducers = {\n sources: _sources_sources__WEBPACK_IMPORTED_MODULE_8__[/* default */ \"a\"]\n };\n break;\n\n case _config__WEBPACK_IMPORTED_MODULE_3__[/* APP_EXPLORER */ \"a\"]:\n appReducers = {\n explorer: _explorer_explorer__WEBPACK_IMPORTED_MODULE_7__[/* default */ \"a\"]\n };\n break;\n\n case _config__WEBPACK_IMPORTED_MODULE_3__[/* APP_TOOLS */ \"c\"]:\n default:\n appReducers = {};\n break;\n }\n } else {\n appReducers = {\n topics: _topics_topics__WEBPACK_IMPORTED_MODULE_6__[/* default */ \"a\"],\n sources: _sources_sources__WEBPACK_IMPORTED_MODULE_8__[/* default */ \"a\"],\n explorer: _explorer_explorer__WEBPACK_IMPORTED_MODULE_7__[/* default */ \"a\"]\n };\n }\n\n var defaultReducers = {\n app: _app__WEBPACK_IMPORTED_MODULE_4__[/* default */ \"a\"],\n user: _user__WEBPACK_IMPORTED_MODULE_5__[/* default */ \"a\"],\n system: _system_system__WEBPACK_IMPORTED_MODULE_9__[/* default */ \"a\"],\n form: redux_form__WEBPACK_IMPORTED_MODULE_1__[/* default */ \"a\"],\n routing: react_router_redux__WEBPACK_IMPORTED_MODULE_0__[\"routerReducer\"],\n story: _story_story__WEBPACK_IMPORTED_MODULE_10__[/* default */ \"a\"],\n platforms: _platforms_platforms__WEBPACK_IMPORTED_MODULE_11__[/* default */ \"a\"]\n };\n\n var reducers = _objectSpread({}, appReducers);\n\n reducers = _extends(reducers, defaultReducers);\n var rootReducer = Object(redux__WEBPACK_IMPORTED_MODULE_2__[/* combineReducers */ \"c\"])(reducers);\n return rootReducer;\n}",
"render() {\n let AppAccount = (\n <div className=\"app\">\n <Typography variant=\"display3\" color=\"primary\" align=\"center\">\n LotterEth\n </Typography>\n <Account web3={this.web3}/>\n <Lottery web3={this.web3}/>\n </div>);\n let AppNoAccount = (\n <div className=\"app\">\n <Typography variant=\"display3\" color=\"primary\" align=\"center\">\n LotterEth\n </Typography>\n <Account web3={this.web3}/>\n <Lottery web3={this.web3}/>\n </div>);\n\n\n // Only render account info if we are using MetaMask\n if (this.renderAccount) {\n return AppAccount;\n }\n return AppNoAccount;\n }",
"function accountMapper(account) {\n\n}",
"function coreReducer() {\n return combineReducers({\n user: UserReducer,\n menu: MenuReducer,\n topProgress: TopProgressReducer,\n statusBar: StatusBarReducer\n // Export new reducer here\n\n // End export\n });\n}",
"get Accounts() {\n\t\tthis.utils.logger.debug({description: 'Account Action called.', action: new AccountsAction(), func: 'users', obj: 'Grout'});\n\t\treturn new AccountsAction();\n\t}",
"async function getAllAccounts(account) {\n let subAccounts = await canvas.get(`/api/v1/accounts/${account.id}/sub_accounts`);\n // if there are subaccounts in the just-fetched account, then recurse again throught its subaccounts\n if (subAccounts.length > 0) {\n // send the accounts through the myMap function to only save the data we care about\n account.subAccounts = subAccounts.map(myMap);\n // for each of the subaccounts, recurse through them checking if they have subaccounts as well\n for (let i = 0; i < subAccounts.length; i++) {\n await getAllAccounts(account.subAccounts[i]);\n }\n }\n }",
"function persistCombineReducers(config,reducers){config.stateReconciler=config.stateReconciler===undefined?_stateReconciler_autoMergeLevel2__WEBPACK_IMPORTED_MODULE_2__[\"default\"]:config.stateReconciler;return Object(_persistReducer__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(config,Object(redux__WEBPACK_IMPORTED_MODULE_0__[\"combineReducers\"])(reducers));}",
"function recreateReducers () {\n combinedReducers = {}\n function recreate(node) {\n if (isPlainObject(node)) {\n const newReducers = {}\n Object.keys(node).forEach(key => {\n const reducer = recreate(node[key])\n if (reducer) {\n newReducers[key] = reducer\n }\n })\n return combineReducers(newReducers)\n } else {\n return node\n }\n }\n combinedReducers = recreate(rawReducers)\n if (store) {\n store.replaceReducer(combinedReducers)\n }\n }",
"function getAlliesOfUser(fullAccount){\n return (dispatch, getState) => {\n const state = getState();\n\n if(fullAccount){\n return state.account.contractInstance.tokensOfOwner.call(state.account.publicEthKey).then((tokens)=>{\n const tokenPositions = tokens.map((token) =>{\n return token.toNumber();\n });\n \n const allies = [];\n const tokenPromises = tokenPositions.map((tp) => {\n return state.account.contractInstance.getEcoAlly(tp);\n });\n Promise.all(tokenPromises).then((values) =>{\n values.forEach((ally,i)=>{\n let allyDnaString = ally[0].toString();\n if(allyDnaString.length === 15){\n allyDnaString = '0' + allyDnaString;\n }\n allies.push({dna : allyDnaString, id : ally[1].toNumber()});\n });\n dispatch(setAllies(allies));\n }).catch(error => { \n dispatch(setAlert({type : 'error', message : metamaskError}));\n });\n });\n }else{\n fetchSimpleTokens(state.account.email)\n .then((data) =>{\n dispatch(setAllies(data.tokenArray));\n });\n }\n }\n}",
"async function recursiveAccounts(access_token, accountArray, accounts){\n if (accounts[\"link\"][\"next\"] != null){\n var url = \"http://localhost:3000\" + accounts[\"link\"][\"next\"];\n var myHeaders = new Headers();\n myHeaders.set('content-type', \"application/json\");\n myHeaders.set('Authorization', 'Bearer ' + access_token);\n var otherParam = {\n headers:myHeaders,\n method:\"GET\"\n };\n var response = await fetch(url, otherParam);\n var the_accounts = await response.json();\n\n for (var account of the_accounts[\"account\"]){\n var alreadyExists = false;\n for (var item of accountArray){\n if (item[\"acc_number\"] == account[\"acc_number\"]){\n alreadyExists = true;\n }\n }\n if (!alreadyExists){\n accountArray.push({acc_number: account[\"acc_number\"], amount:account[\"amount\"]})\n }\n }\n return recursiveAccounts(access_token, accountArray, the_accounts);\n }\n else {\n return accountArray;\n }\n}",
"renderAccount(account) {\n // always set \"key\" property on those components that are part of an array\n // each key should be unique and constant for given component that they identify\n // see more on key in React documentation - https://facebook.github.io/react/docs/multiple-components.html#dynamic-children\n return (\n <Account key={ 'key_' + account.accno } account={ account } />\n );\n }",
"static async getActiveAccounts(req, res) {\n if (req.user.type === 'user') {\n return res.status(403).json({\n status: 403,\n error: 'Only Admin and cashier can view accounts',\n });\n }\n\n const ActiveAccounts = await db.fetchAccountsByStatus(req.query);\n if (!ActiveAccounts.rows[0]) {\n return res.status(404).json({\n status: 404,\n error: 'No account found',\n });\n }\n\n const foundActiveAccounts = [];\n ActiveAccounts.rows.forEach((row) => {\n const active = {\n createdOn: row.createdon,\n accountNumber: row.accountnumber,\n ownerEmail: row.email,\n type: row.type,\n status: row.status,\n balance: row.balance,\n };\n foundActiveAccounts.push(active);\n });\n return res.status(200).json({\n status: 200,\n data: foundActiveAccounts,\n });\n }",
"function createReducer() {\n return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_redux__[\"combineReducers\"])({\n env: __WEBPACK_IMPORTED_MODULE_1__modules_app_reducers_env__[\"a\" /* default */],\n blockchain: __WEBPACK_IMPORTED_MODULE_2__modules_app_reducers_blockchain__[\"a\" /* default */],\n branch: __WEBPACK_IMPORTED_MODULE_3__modules_branch_reducers_branch__[\"a\" /* default */],\n connection: __WEBPACK_IMPORTED_MODULE_4__modules_app_reducers_connection__[\"a\" /* default */],\n url: __WEBPACK_IMPORTED_MODULE_5__modules_link_reducers_url__[\"a\" /* default */],\n\n isMobile: __WEBPACK_IMPORTED_MODULE_6__modules_app_reducers_is_mobile__[\"a\" /* default */],\n headerHeight: __WEBPACK_IMPORTED_MODULE_7__modules_app_reducers_header_height__[\"a\" /* default */],\n footerHeight: __WEBPACK_IMPORTED_MODULE_8__modules_app_reducers_footer_height__[\"a\" /* default */],\n\n auth: __WEBPACK_IMPORTED_MODULE_9__modules_auth_reducers_auth__[\"a\" /* default */],\n loginAccount: __WEBPACK_IMPORTED_MODULE_10__modules_auth_reducers_login_account__[\"a\" /* default */],\n accountName: __WEBPACK_IMPORTED_MODULE_11__modules_account_reducers_account_name__[\"a\" /* default */],\n activeView: __WEBPACK_IMPORTED_MODULE_12__modules_app_reducers_active_view__[\"a\" /* default */],\n\n newMarket: __WEBPACK_IMPORTED_MODULE_13__modules_create_market_reducers_new_market__[\"a\" /* default */],\n\n marketsData: __WEBPACK_IMPORTED_MODULE_14__modules_markets_reducers_markets_data__[\"a\" /* default */],\n marketLoading: __WEBPACK_IMPORTED_MODULE_15__modules_market_reducers_market_loading__[\"a\" /* default */],\n hasLoadedMarkets: __WEBPACK_IMPORTED_MODULE_16__modules_markets_reducers_has_loaded_markets__[\"a\" /* default */],\n outcomesData: __WEBPACK_IMPORTED_MODULE_17__modules_markets_reducers_outcomes_data__[\"a\" /* default */],\n eventMarketsMap: __WEBPACK_IMPORTED_MODULE_18__modules_markets_reducers_event_markets_map__[\"a\" /* default */],\n favorites: __WEBPACK_IMPORTED_MODULE_19__modules_markets_reducers_favorites__[\"a\" /* default */],\n pagination: __WEBPACK_IMPORTED_MODULE_20__modules_markets_reducers_pagination__[\"a\" /* default */],\n\n reports: __WEBPACK_IMPORTED_MODULE_21__modules_reports_reducers_reports__[\"a\" /* default */],\n eventsWithAccountReport: __WEBPACK_IMPORTED_MODULE_22__modules_my_reports_reducers_events_with_account_report__[\"a\" /* default */],\n\n selectedMarketID: __WEBPACK_IMPORTED_MODULE_38__modules_markets_reducers_selected_market_id__[\"a\" /* default */],\n selectedMarketsSubset: __WEBPACK_IMPORTED_MODULE_40__modules_markets_reducers_selectedMarketsSubset__[\"a\" /* default */],\n selectedMarketsHeader: __WEBPACK_IMPORTED_MODULE_39__modules_markets_reducers_selected_markets_header__[\"a\" /* default */],\n keywords: __WEBPACK_IMPORTED_MODULE_47__modules_markets_reducers_keywords__[\"a\" /* default */],\n topics: __WEBPACK_IMPORTED_MODULE_35__modules_topics_reducers_topics_data__[\"a\" /* default */],\n hasLoadedTopic: __WEBPACK_IMPORTED_MODULE_36__modules_topics_reducers_has_loaded_topic__[\"a\" /* default */],\n selectedTopic: __WEBPACK_IMPORTED_MODULE_37__modules_topics_reducers_selected_topic__[\"a\" /* default */],\n selectedTags: __WEBPACK_IMPORTED_MODULE_48__modules_markets_reducers_selected_tags__[\"a\" /* default */],\n selectedFilterSort: __WEBPACK_IMPORTED_MODULE_49__modules_markets_reducers_selected_filter_sort__[\"a\" /* default */],\n priceHistory: __WEBPACK_IMPORTED_MODULE_50__modules_markets_reducers_price_history__[\"a\" /* default */],\n\n tradesInProgress: __WEBPACK_IMPORTED_MODULE_41__modules_trade_reducers_trades_in_progress__[\"a\" /* default */],\n tradeCommitLock: __WEBPACK_IMPORTED_MODULE_42__modules_trade_reducers_trade_commit_lock__[\"a\" /* default */],\n reportCommitLock: __WEBPACK_IMPORTED_MODULE_43__modules_reports_reducers_report_commit_lock__[\"a\" /* default */],\n tradeCommitment: __WEBPACK_IMPORTED_MODULE_44__modules_trade_reducers_trade_commitment__[\"a\" /* default */],\n sellCompleteSetsLock: __WEBPACK_IMPORTED_MODULE_45__modules_my_positions_reducers_sell_complete_sets_lock__[\"a\" /* default */],\n smallestPositions: __WEBPACK_IMPORTED_MODULE_46__modules_my_positions_reducers_smallest_positions__[\"a\" /* default */],\n\n orderBooks: __WEBPACK_IMPORTED_MODULE_23__modules_bids_asks_reducers_order_books__[\"a\" /* default */],\n orderCancellation: __WEBPACK_IMPORTED_MODULE_24__modules_bids_asks_reducers_order_cancellation__[\"a\" /* default */],\n marketTrades: __WEBPACK_IMPORTED_MODULE_25__modules_portfolio_reducers_market_trades__[\"a\" /* default */],\n accountTrades: __WEBPACK_IMPORTED_MODULE_26__modules_my_positions_reducers_account_trades__[\"a\" /* default */],\n accountPositions: __WEBPACK_IMPORTED_MODULE_27__modules_my_positions_reducers_account_positions__[\"a\" /* default */],\n completeSetsBought: __WEBPACK_IMPORTED_MODULE_28__modules_my_positions_reducers_complete_sets_bought__[\"a\" /* default */],\n netEffectiveTrades: __WEBPACK_IMPORTED_MODULE_29__modules_my_positions_reducers_net_effective_trades__[\"a\" /* default */],\n transactionsData: __WEBPACK_IMPORTED_MODULE_30__modules_transactions_reducers_transactions_data__[\"a\" /* default */],\n transactionsOldestLoadedBlock: __WEBPACK_IMPORTED_MODULE_31__modules_transactions_reducers_transactions_oldest_loaded_block__[\"a\" /* default */],\n transactionsLoading: __WEBPACK_IMPORTED_MODULE_32__modules_transactions_reducers_transactions_loading__[\"a\" /* default */],\n scalarMarketsShareDenomination: __WEBPACK_IMPORTED_MODULE_33__modules_market_reducers_scalar_markets_share_denomination__[\"a\" /* default */],\n closePositionTradeGroups: __WEBPACK_IMPORTED_MODULE_34__modules_my_positions_reducers_close_position_trade_groups__[\"a\" /* default */],\n\n chatMessages: __WEBPACK_IMPORTED_MODULE_51__modules_chat_reducers_chat_messages__[\"a\" /* default */],\n\n marketCreatorFees: __WEBPACK_IMPORTED_MODULE_52__modules_my_markets_reducers_market_creator_fees__[\"a\" /* default */],\n\n contractAddresses: __WEBPACK_IMPORTED_MODULE_53__modules_contracts_reducers_contract_addresses__[\"a\" /* default */],\n functionsAPI: __WEBPACK_IMPORTED_MODULE_54__modules_contracts_reducers_functions_api__[\"a\" /* default */],\n eventsAPI: __WEBPACK_IMPORTED_MODULE_55__modules_contracts_reducers_events_api__[\"a\" /* default */],\n notifications: __WEBPACK_IMPORTED_MODULE_56__modules_notifications_reducers_notifications__[\"a\" /* default */]\n });\n}",
"useReducers(action = { type: '' }, curState = {}) {\n const newState = {};\n for (let key in this.reducers) {\n let reducer = this.reducers[key];\n newState[key] = reducer(curState[key], action);\n }\n return newState;\n }",
"static filterAccounts(accounts) {\n let oldAccounts = [];\n let newAccounts = [];\n\n accounts.map(account => {\n if (Accounts.findOne({ acctNum: account.acctNum })) {\n oldAccounts.push(account);\n } else {\n account.state = stateEnum.ARCHIVED;\n account.substate = Substates.SELF_RETURNED;\n newAccounts.push(account);\n }\n });\n return [oldAccounts, newAccounts];\n }",
"listOfUnfinishedApplicants() {\n let i = 0;\n const returnValues = [];\n for (i; i < this.props.accounts.length; i++) {\n // eslint-disable-next-line no-loop-func\n const db1 = this.props.db1.find(mydb => mydb.owner === this.props.accounts[i].username);\n // eslint-disable-next-line no-loop-func\n const db2 = this.props.db2.find(mydb => mydb.owner === this.props.accounts[i].username);\n // eslint-disable-next-line no-loop-func\n const db6 = this.props.db6.find(mydb => mydb.owner === this.props.accounts[i].username);\n // eslint-disable-next-line no-loop-func\n const db7 = this.props.db7.find(mydb => mydb.owner === this.props.accounts[i].username);\n // eslint-disable-next-line no-loop-func\n const db8 = this.props.db8.find(mydb => mydb.owner === this.props.accounts[i].username);\n // eslint-disable-next-line no-loop-func\n const db9 = this.props.db9.find(mydb => mydb.owner === this.props.accounts[i].username);\n // eslint-disable-next-line no-loop-func\n const db0 = this.props.dbauthorization.find(mydb => mydb.owner === this.props.accounts[i].username);\n\n if (!(db1 && db2 && db6 && db7 && db8 && db9 && db0)) {\n const ownerEmail = this.props.accounts[i].username;\n returnValues.push(\n <List.Item key={ownerEmail}>\n <Checkbox\n label={ownerEmail}\n onChange={this.checkboxChangeHandler}\n />\n </List.Item>,\n );\n }\n }\n return returnValues;\n }",
"getReducers() {\n return { ...this._reducers };\n }",
"chainReducers(/*reducers list*/) {\n const reducers = Array.prototype.slice.call(arguments);\n return function (state, action) {\n const mergeReducerStates = !Utils.isDefined(state); //useful to define initial state part in every reducer\n let nextState = state || {};\n reducers.forEach((reducer => {\n if (mergeReducerStates) {\n nextState = Utils.merge(nextState, reducer(state, action))\n } else { //use result state from previous reducer as input for next reducer\n nextState = reducer(nextState, action)\n }\n }));\n return nextState;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show the loading spinner before the content loaded | function showLoadingView() {
$loader.css("display", "block");
} | [
"function showLoadingSpinner(){\n loader.hidden = false;\n quoteContainer.hidden = true;\n}",
"showLoadingScreen() {\n this.setUIStep(AssistantUIState.LOADING);\n this.$.loading.onShow();\n }",
"function displayLoadingState() {\n LEXUS.loadingAnimation.start();\n\n hideDrillDown();\n $(\"#resultsLoader\").addClass(\"show\");\n\n $(\".trim-selector-drawer\").hide();\n $(\".dimmer\").unbind(\"click\").addClass(\"on\").css({\n opacity: 0.6\n });\n }",
"function showLoading() {\n _updateState(hotelStates.SHOW_LOADING);\n }",
"showPageLoadingIndicator() {\n\t\tgetComponentElementById(this,\"DataListLoading\").html('<div class=\"dx-loading\"></div>').show();\n\t}",
"function showLoader() {\n\n loader.show();\n }",
"function displayLoadingScreen(){\r\n updateContent( getLoadingContent() );\r\n}",
"function showLoader()\n {\n\t\t$('.loader-container').show();\n $('.loader-back').show();\n }",
"function loading() {\r\n loader.hidden = false;\r\n quoteContainer.hidden = true;\r\n}",
"function showLoadingOverlay() {\n toggleHidden(getLoadingOverlay(), false);\n }",
"function showArticleLoading() {\n articleLoading.classList.add(\"show\");\n }",
"function showLoadingMessage() {}",
"function showPageLoader(){\n $('.loader').show();\n}",
"function loading(){\r\n loader.hidden = false; // This will display loader\r\n quoteContainer.hidden = true; // This will hide quote container\r\n}",
"showSpinner() {\n this.isLoading = true;\n }",
"function showLoader()\n {\n\t\t$('.loader-container').show();\n $('.loader-container').preloader({\n zIndex: 1000,\n setRelative: false\n });\n $('.loader-back').show();\n }",
"function showLoading() {\n if(jQuery(\"#unical-calendar-loading\").length == 0) {\n var loader = jQuery(\"<div>\", {id: \"unical-calendar-loading\", \"class\": \"loading\"});\n jQuery(\"body\").append(loader);\n } else {\n jQuery('#unical-calendar-loading').show();\n }\n }",
"loading() {\n return `<div class=\"selectivity-loading\">${Locale.loading}</div>`;\n }",
"_setLoadingIndicatorVisibility() {\n const that = this;\n\n if (that.displayLoadingIndicator) {\n that.$.loadingIndicatorContainer.classList.remove('jqx-visibility-hidden');\n return;\n }\n\n that.$.loadingIndicatorContainer.classList.add('jqx-visibility-hidden');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
hexKeyPressed() This function is called when the user presses any key when the hexpad is open. It only reacts when the user presses a hex digit (09, A F, a f). It works for both lowercase and upper case. | function hexKeyPressed(event) {
var code = event.keyCode || event.which; // grab the key code
if (code == 13) { // 13 is enter
var input = document.getElementById("numpadInput" + thisID);
callback(input.value); // call the callback function with the input box value
$( "#numpadDialog" + thisID).dialog('close'); // close the dialog
window.onkeypress = null;
window.onkeydown = null;
}
else if (code >= 97 && code <= 102) hexKeyClick(String.fromCharCode(code-32)); // if its 97 - 102, it's the lower case a - f; convert it to its upper case ASCII character representation (subtract 32)
else if (code >= 65 && code <= 70) hexKeyClick(String.fromCharCode(code)); // if its 65 - 70, it's the upper case A - F; convert it to its ASCII character representation
else if (code >= 48 && code <= 57) numberKeyClick(code-48); // if its 48 - 57, it's a 0 - 9; convert it to its ASCII representation by subtracting 48
} | [
"function keyPressed() {}",
"function keyPress(code, char) { }",
"function keyPress(event) {\n\tdocument.getElementById(\"displayLetter\").innerHTML += String.fromCharCode(event.charCode);\n// console.log(event) allows for the key that you are pressing to be viewed in the console\n// as well as the h1 element will match the key pressed in the console.\n\tconsole.log(event);\n}",
"function isHexChar(c) {\n if ((c >= 'A' && c <= 'F') ||\n (c >= 'a' && c <= 'f') ||\n (c >= '0' && c <= '9')) {\n return 1;\n }\n return 0;\n}",
"function keyPressed(event, charCode)\n{\n\tvar keyPressed = false;\n if (getKeyCharCode(event) == charCode)\n {\n \tkeyPressed = true;\n }\n\n\treturn keyPressed;\n}",
"function isHexChar(c) {\n if ((c >= 'A' && c <= 'F') ||\n (c >= 'a' && c <= 'f') ||\n (c >= '0' && c <= '9')) {\n return 1;\n }\n return 0;\n}",
"function keyPressed(){\n\tswitch(key){\n\t\tcase \"1\":\n\t\tfill(random(255));\n\t\ttext(key,50,50);\n\t\tbreak;\n\t\tcase \"2\":\n\t\tfill(random(255));\n\t\ttext(key,150,50);\n\t\tbreak;\n\t\tcase \"3\":\n\t\tfill(random(255));\n\t\ttext(key,250,50);\n\t\tbreak;\n\t\tdefault:\n\t\tbreak;\n\t}\n}",
"function hexKeyClick(value) {\n\t\tvar input = document.getElementById(\"numpadInput\" + thisID);\n\t\t\n\t\tif (boundsCheck(input.value + value) == true) {\t\t// if its within bounds, add it\n\t\t\tif (input.value == \"0\") input.value = value;\t// if only a zero is in the input box, overwrite it\n\t\t\telse input.value += value;\n\t\t}\n\t}",
"function hexToAscii(hex) {\n text = \"\";\n hex = reSplit(hex, 2);\n hex.forEach((pair) => {\n text += String.fromCharCode(parseInt(pair, 16));\n });\n finalTitle = \"hex\";\n finalText = text;\n selectState(\"found\");\n}",
"function isPrintableCharacter(event){var key=event.key;return key.length===1||key.length>1&&/[^a-zA-Z0-9]/.test(key);}",
"function hex_num_only(evt)\n{\n\tif (navigator.appName == 'Netscape')\n\t{\n\t\tif (evt.which == 8) return true;\t/* TAB */\n\t\tif (evt.which == 0) return true;\n\t\tif (evt.which >= 48 && evt.which <= 57) return true;\n\t\tif (evt.which > 64 && evt.which < 71) return true;\n\t\tif (evt.which > 96 && evt.which < 103) return true;\n\t}\n\telse\n\t{\n\t\tif (evt.keyCode == 8) return true;\t/* TAB */\n\t\tif (evt.keyCode == 0) return true;\n\t\tif (evt.keyCode >= 48 && evt.keyCode <= 57) return true;\n\t\tif (evt.keyCode > 64 && evt.keyCode < 71) return true;\n\t\tif (evt.keyCode > 96 && evt.keyCode < 103) return true;\n\t}\n\treturn false;\n}",
"function keyPressed() {\n}",
"function DialogKeyDown() {\n\tif (((KeyPress == 65) || (KeyPress == 83) || (KeyPress == 97) || (KeyPress == 115)) && (DialogProgress >= 0)) {\n\t\tDialogStruggle((DialogProgressLastKeyPress == KeyPress));\n\t\tDialogProgressLastKeyPress = KeyPress;\n\t}\n}",
"function hexClicked(sprite, pointer) {\n\tif(myTurn && sprite.key == 'hex_border') {\n\t sprite.loadTexture('hex_red');\n\t sprite.key = 'hex_red';\n\t console.log('clicked hexagon '+sprite.i+' '+sprite.j);\n\t eurecaServer.makeMove(sprite.i,sprite.j);\n\t myTurn = false;\n\t you_tween.pause();\n\t opponent_tween.resume();\n\t}\n}",
"function keyPressed() {\n if (key == 0) {\n serial.write(0);\n }\n if (key == 1) {\n serial.write(1);\n }\n if (key == 2) {\n serial.write(2);\n }\n if (key == 3) {\n serial.write(3);\n }\n if (key == 4) {\n serial.write(4);\n }\n if (key == 5) {\n serial.write(5);\n }\n if (key == 6) {\n serial.write(6);\n }\n}",
"keyDown(_keycode) {}",
"keyDown(keyCode) {\n\n }",
"function keyPressed(e){\n\n}",
"function isHex(code) {\n return isNumber(code) || isAlpha(code, 65, 70); // A-F\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
MakeGeomCritPnts: make the three.js geometry for the critical points | function MakeGeomCritPnts ()
{
ComputeCriticalPointPositions ();
/* Either use spheres or points.
const grpCritPnts = new THREE.Group ();
for (var i = 0; i < 3; i++)
{
const geometry = new THREE.SphereGeometry (1, 7, 7);
const material = new THREE.MeshBasicMaterial ({ color: _CriticalPntColour });
const sphere = new THREE.Mesh (geometry, material);
sphere.position.set (_CriticalPntPositions[i][0], _CriticalPntPositions[i][1], _CriticalPntPositions[i][2]);
grpCritPnts.add (sphere);
}
return grpCritPnts;*/
const vertices = [];
for (var i = 0; i < 9; i++)
vertices.push ( _CriticalPntPositions[ Math.floor(i/3) ][ i % 3 ] );
var geometry = new THREE.BufferGeometry ();
geometry.setAttribute ('position', new THREE.Float32BufferAttribute (vertices, 3) );
const material = new THREE.PointsMaterial ( { color: _CriticalPntColour, size: 1 } );
return new THREE.Points (geometry, material);
} | [
"function MakeGeomCritPnts ()\n{\n ComputeCriticalPointPositions ();\n\n const vertices = [];\n for (var i = 0; i < 9; i++)\n vertices.push ( _CriticalPntPositions[ Math.floor(i/3) ][ i % 3 ] );\n\n var geometry = new THREE.BufferGeometry ();\n geometry.setAttribute ('position', new THREE.Float32BufferAttribute (vertices, 3) );\n\n const material = new THREE.PointsMaterial ( { color: _CriticalPntColour, size: 1 } );\n\n return new THREE.Points (geometry, material);\n}",
"function ComputeCriticalPointPositions (updateGeom=false)\n{\n // Note that (0, 0, 0) is always a fixed point so no need to recompute it\n \n // compute this once...\n var val = Math.sqrt ( _dBeta * (_dRho[_nCurrRho] - 1) );\n\n _CriticalPntPositions [1][0] = val;\n _CriticalPntPositions [1][1] = val;\n _CriticalPntPositions [1][2] = _dRho[_nCurrRho] - 1;\n\n _CriticalPntPositions [2][0] = -1 * val;\n _CriticalPntPositions [2][1] = -1 * val;\n _CriticalPntPositions [2][2] = _dRho[_nCurrRho] - 1;\n\n if (updateGeom)\n {\n // in case spheres were used\n //_geomCritPnts.children[1].position.set (val, val, _dRho[_nCurrRho] - 1);\n //_geomCritPnts.children[2].position.set (-1*val, -1*val, _dRho[_nCurrRho] - 1);\n\n var positions = _geomCritPnts.geometry.attributes.position.array;\n\n for (var i = 3; i < 9; i++)\n positions [ i ] = _CriticalPntPositions [ Math.floor(i/3) ][ i % 3 ];\n\n _geomCritPnts.material.size = (_MaxCritPntSize - _MinCritPntSize) / (_dRho[5] - _dRho[0]) \n * (_dRho[_nCurrRho] - _dRho[0]) + _MinCritPntSize;\n _geomCritPnts.geometry.attributes.position.needsUpdate = true;\n }\n}",
"function DrawCritter_000(context, critterData)\n{\n var up = Math.PI / 2.0;\n var down = up * 3;\n var left = Math.PI;\n var right = 0.00;\n \n c = new Point();\n c.x = critterData.bodyPosition.x;\n c.y = critterData.bodyPosition.y;\n \n a = new Point();\n a.x = critterData.bodyPosition.x - (critterData.bodyWidth / 2);\n a.y = critterData.bodyPosition.y - (critterData.bodyHeight) + (critterData.headAngle * 20);\n \n b = new Point();\n b.x = critterData.bodyPosition.x + (critterData.bodyWidth / 2);\n b.y = critterData.bodyPosition.y - (critter.bodyHeight) - (critterData.headAngle * 20);\n \n mid_ab = new Point();\n mid_ab = getMidPoint(a, b);\n \n d = new Point();\n d.x = critterData.bodyPosition.x - (critterData.waistWidth / 2);\n d.y = critterData.bodyPosition.y;\n \n e = new Point();\n e.x = critterData.bodyPosition.x + (critterData.waistWidth / 2);\n e.y = critterData.bodyPosition.y;\n \n mid_ad = new Point();\n mid_ad = getMidPoint(a, d);\n \n mid_be = new Point();\n mid_be = getMidPoint(b, e);\n \n mid_dc = new Point();\n mid_dc = getMidPoint(d, c);\n \n mid_ce = new Point();\n mid_ce = getMidPoint(c, e);\n \n j = new Point();\n j.x = mid_ab.x + Math.cos(up + critterData.headAngle) * critterData.headHeight;\n j.y = mid_ab.y + Math.sin(up + critterData.headAngle) * critterData.headHeight;\n \n f = new Point();\n f.x = mid_dc.x + Math.cos(down + critterData.leftLegAngle) * critterData.leftLegLength;\n f.y = mid_dc.y + Math.sin(down + critterData.leftLegAngle) * critterData.leftLegLength;\n \n g = new Point();\n g.x = mid_ce.x + Math.cos(down + critterData.rightLegAngle) * critterData.rightLegLength;\n g.y = mid_ce.y + Math.sin(down + critterData.rightLegAngle) * critterData.rightLegLength;\n \n h = new Point();\n h.x = mid_ad.x + Math.cos(left + critterData.leftArmAngle) * critterData.leftArmLength;\n h.y = mid_ad.y + Math.sin(left + critterData.leftArmAngle) * critterData.leftArmLength;\n\n i = new Point();\n i.x = mid_be.x + Math.cos(right + critterData.rightArmAngle) * critterData.rightArmLength;\n i.y = mid_be.y + Math.sin(right + critterData.rightArmAngle) * critterData.rightArmLength;\n \n //draw the body\n context.beginPath();\n context.moveTo(j.x, j.y);\n context.lineTo(b.x, b.y);\n context.lineTo(i.x, i.y);\n context.lineTo(e.x, e.y);\n context.lineTo(g.x, g.y);\n context.lineTo(c.x, c.y);\n context.lineTo(f.x, f.y);\n context.lineTo(d.x, d.y);\n context.lineTo(h.x, h.y);\n context.lineTo(a.x, a.y);\n context.closePath();\n context.fillStyle = critterData.foreColour;\n context.strokeStyle = critterData.backColour;\n context.stroke();\n context.fill();\n}",
"function MakeGeomSolPnts ()\n{\n var solutionPoints = [];\n\n for (var j = 0; j < _nMaxCurves; j++)\n {\n var vertices = [];\n for (var i = 0; i < 3; i++)\n vertices.push ( _InitPosBase[i] ); \n\n var geometry = new THREE.BufferGeometry ();\n geometry.setAttribute ('position', new THREE.Float32BufferAttribute (vertices, 3) );\n\n // Will be updated later\n const material = new THREE.PointsMaterial ( { color: _PntColours[ j ], size: 1 } );\n\n solutionPoints.push (new THREE.Points (geometry, material));\n }\n\n return solutionPoints;\n}",
"function createGeometry() {\n const { alphaTest, particleSize, startIndex } = sceneParams;\n const parentObject = scene;\n\n // get data for points (position, nearest-neighbour, and distance to origin)\n // console.log('points:');\n // console.log(pointData);\n const vertices = getPositions(mapType, pointData); // .slice(startIndex * 3);\n // console.log('vertices:');\n // console.log(vertices);\n\n const nearestNeighbours = getNearestNeighbours(mapType, pointData).slice(startIndex);\n distances = getDistances(mapType, pointData); // .slice(startIndex);\n // console.log('distances:');\n // console.log(distances);\n\n // build color lookup table (LUT)\n const lut = getColorLookupTable(\n colorPalettes7[colorThemeIndex],\n mapInfo[mapType].distanceLimit\n );\n\n // calculate which points are assigned to each image\n spriteIndexData = assignImagesToPoints(imageTextures, nearestNeighbours);\n\n // a loop counter, one entry for each material/geometry (1:1)\n let matGeoCount = 0;\n\n // loop through each galaxy group (spiral, elliptical, lenticular) and create particle groups\n Object.keys(spriteIndexData).forEach((group) => {\n // in each group, loop through the assigned galaxy images\n spriteIndexData[group].forEach((image) => {\n // for each galaxy image, create the point cloud from the assigned points array\n const points = image.assignedPoints;\n const subVertices = [];\n points.forEach((value) => {\n subVertices.push(vertices[value * 3], vertices[value * 3 + 1], vertices[value * 3 + 2]);\n });\n\n // create geometry\n geometry[matGeoCount] = new THREE.BufferGeometry();\n geometry[matGeoCount].addAttribute(\n 'position',\n new THREE.Float32BufferAttribute(subVertices, 3)\n );\n\n // build color lookup table (default is NN coloring for now...)\n const lutColors = assignNNColors(lut, points, nearestNeighbours);\n\n geometry[matGeoCount].addAttribute('color', new THREE.Float32BufferAttribute(lutColors, 3));\n\n // create materials\n materials[matGeoCount] = new THREE.PointsMaterial({\n alphaTest,\n blending: THREE.NormalBlending,\n color: null,\n vertexColors: isUsingColorLUT ? THREE.VertexColors : THREE.NoColors,\n depthTest: true,\n map: imageTextures[image.imageIndex],\n size: particleSize,\n transparent: true\n });\n\n const particles = new THREE.Points(geometry[matGeoCount], materials[matGeoCount]);\n particles.visible = false;\n\n // add the point cloud to the scene\n parentObject.add(particles);\n\n matGeoCount += 1;\n });\n });\n }",
"function drawCourt()\n{\n //left side\n drawCourtHelper(new THREE.Vector3(leftSinglesLineX,0,nearBaselineZ),new THREE.Vector3(leftSinglesLineX,0,farBaselineZ))\n drawCourtHelper(new THREE.Vector3(leftDoublesLineX,0,nearBaselineZ),new THREE.Vector3(leftDoublesLineX,0,farBaselineZ))\n\n //right side\n drawCourtHelper(new THREE.Vector3(rightSinglesLineX,0,nearBaselineZ),new THREE.Vector3(rightSinglesLineX,0,farBaselineZ))\n drawCourtHelper(new THREE.Vector3(rightDoublesLineX,0,nearBaselineZ),new THREE.Vector3(rightDoublesLineX,0,farBaselineZ))\n\n //far side baseline\n drawCourtHelper(new THREE.Vector3(leftDoublesLineX,0,farBaselineZ),new THREE.Vector3(rightDoublesLineX,0,farBaselineZ))\n\n //near side baseline\n drawCourtHelper(new THREE.Vector3(leftDoublesLineX,0,nearBaselineZ),new THREE.Vector3(rightDoublesLineX,0,nearBaselineZ))\n\n //far side service box\n drawCourtHelper(new THREE.Vector3(leftSinglesLineX,0,farServiceBoxZ),new THREE.Vector3(rightSinglesLineX,0,farServiceBoxZ))\n\n //near side service box\n drawCourtHelper(new THREE.Vector3(leftSinglesLineX,0,nearServiceBoxZ),new THREE.Vector3(rightSinglesLineX,0,nearServiceBoxZ))\n\n //middle line vertical\n drawCourtHelper(new THREE.Vector3(midLineX,0,farServiceBoxZ),new THREE.Vector3(midLineX,0,nearServiceBoxZ))\n\n //far side mid tip\n drawCourtHelper(new THREE.Vector3(midLineX,0,farBaselineZ),new THREE.Vector3(midLineX,0,farBaselineZ+1))\n\n //near side mid tip\n drawCourtHelper(new THREE.Vector3(midLineX,0,nearBaselineZ),new THREE.Vector3(midLineX,0,nearBaselineZ-1))\n}",
"get points_geometry() {\r\n\t\t// Create an empty geometry\r\n\t\tlet geometry = new THREE.Geometry();\r\n\t\t// Add the vertices\r\n\t\tgeometry.vertices.push(...this.vertices3.map(e => new THREE.Vector3(...e.pos)));\r\n\t\treturn geometry;\r\n\t}",
"function generateGeometry() {\n let areas = [];\n let clips = clipRects_.slice();\n\n _.each(clips, (clip)=> {\n areas.push(clip.min);\n areas.push(clip.max);\n });\n\n\n areas.sort((a, b)=> {\n return a - b;\n });\n\n areas.unshift(-width_ * 0.5);\n areas.push(width_ * 0.5);\n\n vertices_ = [];\n indices_ = [];\n normal_ = [];\n uvs_ = [];\n let aLength = areas.length;\n _.times(aLength * 2, (i)=> {\n vertices_[i * 3] = areas[i % aLength];\n vertices_[i * 3 + 1] = i < aLength ? -height_ * 0.5 : height_ * 0.5;\n vertices_[i * 3 + 2] = 0;\n\n normal_[i * 3] = 0;\n normal_[i * 3 + 1] = 0;\n normal_[i * 3 + 2] = 1;\n\n uvs_[i * 2] = (areas[i % aLength] + width_ * 0.5) / width_;\n uvs_[i * 2 + 1] = i < aLength ? 0 : 1;\n });\n\n _.times(aLength * 0.5, (i)=> {\n indices_.push(i * 2);\n indices_.push(i * 2 + 1);\n indices_.push(i * 2 + aLength);\n\n indices_.push(i * 2 + 1);\n indices_.push(i * 2 + aLength + 1);\n indices_.push(i * 2 + aLength);\n });\n\n setAttributes();\n }",
"function regularPolygonGeometry(n, innerColor, outerColor) {\n // I started working on this assignment by writing a loop that would calculate the each vertex using sine/cosine functions\n // but quickly realized that the CircleGeometry actually draws a circle by drawing n triangles with a given radius, which is\n // centered at the origin and lies in the xy plane (textbook what I needed)\n // so I started with a CircleGeometry of radius 2 and n segments, and modified its faces to have vertex colors\n\n var geom = new THREE.CircleGeometry(2, n);\n for(var i = 0; i < geom.faces.length; i++) {\n geom.faces[i].vertexColors.push(outerColor);\n geom.faces[i].vertexColors.push(outerColor);\n geom.faces[i].vertexColors.push(innerColor);\n }\n return geom;\n}",
"function makeTiePoints(num_sides, num_ends, cx, cy, radius) {\n\n const p = makePolygonPoints(num_sides, cx, cy, radius);\n\n let verts = [];\n if (num_ends == 1) {\n for (let i=0; i<num_sides; i++) {\n const j = (i+1)%num_sides;\n verts.push([(p[i][0] + p[j][0])/2, (p[i][1] + p[j][1])/2]);\n }\n } else if (num_ends == 2) {\n for (let i=0; i<num_sides; i++) {\n const j = (i+1)%num_sides;\n verts.push([( p[i][0] + 2*p[j][0])/3, ( p[i][1] + 2*p[j][1])/3]);\n verts.push([(2*p[i][0] + p[j][0])/3, (2*p[i][1] + p[j][1])/3]);\n }\n } else if (num_ends == 3) {\n for (let i=0; i<num_sides; i++) {\n const j = (i+1)%num_sides;\n verts.push([( p[i][0] + 3*p[j][0])/4, ( p[i][1] + 3*p[j][1])/4]);\n verts.push([( p[i][0] + p[j][0])/2, ( p[i][1] + p[j][1])/2]);\n verts.push([(3*p[i][0] + p[j][0])/4, (3*p[i][1] + p[j][1])/4]);\n }\n }\n return verts;\n}",
"function remakeCatmullObj() { \n\n var catmullVertices = [ [7, 0],\n [1.5, 2],\n [.75, 4],\n [.75, 6],\n [.75, sceneParams.standHeight] ];\n\n var mat = new THREE.MeshPhongMaterial({color: sceneParams.metalColor,\n specular: sceneParams.metalSpecular,\n shininess: sceneParams.metalShininess});\n curve = new THREE.CatmullRomCurve3 ( makeVertices(catmullVertices) );\n var geom = new THREE.Geometry();\n geom.vertices = curve.getPoints(5);\n catmullObj = new THREE.Line( geom, new THREE.LineBasicMaterial( { linewidth: 3, color: 0x00ff00 }) );\n catmullObj.name = \"catmull\";\n\n return catmullObj;\n}",
"customer_geometry(ncust) {\n var temp_customer_geom = new THREE.BufferGeometry()\n var init_pos = new Array(this.ncust*3).fill(0.0);\n var init_zeros = new Array(this.ncust ).fill(0.0);\n // force the bounding box to avoid recomputing each frame\n init_pos.push(this.box.min['x'], this.box.min['y'], 0)\n init_pos.push(this.box.max['x'], this.box.max['y'], 0)\n // fill zeros to the correct size\n init_zeros.push(0.0, 0.0)\n temp_customer_geom.addAttribute('position',new THREE.Float32BufferAttribute(init_pos, 3))\n temp_customer_geom.addAttribute('size', new THREE.Float32BufferAttribute(init_zeros, 1))\n return temp_customer_geom\n }",
"function genCoilPoints (gl, g_points, n, u_ModelMatrix, modelMatrix, a_Position)\r\n{\r\n /////////////////////////////////////////////////////////\r\n // Generate 3D points for parametric curve.\r\n /////////////////////////////////////////////////////////\r\n var theta = 0.0;\r\n var x;\r\n var y;\r\n var z;\r\n var n; // number of vertices\r\n var Npoints = 800;\r\n var dtheta = 10.0 * Math.PI / Npoints;\r\n var TwoPI = 2.0 * Math.PI;\r\n //clear the g_points array\r\n g_points = [];\r\n\r\n ////////////////////////////////////////////////\r\n // Main loop for generating 3D points.\r\n ////////////////////////////////////////////////\r\n while (theta < 10.0 * Math.PI) {\r\n //parametric equation for coil\r\n x = Math.cos(theta);\r\n y = Math.sin(theta);\r\n z = theta;\r\n \r\n \r\n // Adjust to fit into (-1,-1,-1), (1,1,1).\r\n z = z / 16.0 - 1.0;\r\n // console.log(x);\r\n g_points.push(x);\r\n g_points.push(y);\r\n g_points.push(z);\r\n theta = theta + dtheta;\r\n }\r\n // get the length of the array of vertices\r\n var len = g_points.length;\r\n var n = len / 3; // account for x,y, and z \r\n //initialize the vertex buffers\r\n initVertexBuffers(gl, n, u_ModelMatrix, modelMatrix, a_Position, g_points);\r\n return n;\r\n}// end genCoilPoints",
"function GemstoneBufferGeometry(contour, width, height, depth) {\n\n\n\t/*\n\tScaling of the contour and the tip to match the passed\n\tx and y values.\n\t*/\n\n\tlet tip = new THREE.Vector3(0, 0, 0);\n\tlet xContour = 0 ;\n\tlet userData = {\n\t\twidth: width,\n\t\theight: height,\n\t\tdepth: depth\n\t};\n\n\tfor (i=0 ; i<contour.length ; i++) {\n\n\t\tlet compare = contour[i][\"x\"];\n\t\tif ( xContour < compare ) { xContour = compare };\n\t};\n\n\n\n\tlet zContour = 0 ;\n\n\tfor (i=0 ; i<contour.length ; i++) {\n\n\t\tlet compare = contour[i][\"z\"];\n\t\tif ( zContour < compare ) { zContour = compare };\n\t};\n\n\tlet xScaleFactor = (width / 2) / xContour;\n\tlet zScaleFactor = (depth / 2) / zContour;\n\n\tlet xPlane = new THREE.Plane(new THREE.Vector3(1,0,0));\n\tlet zPlane = new THREE.Plane(new THREE.Vector3(0,0,1));\n\n\tplaneScale(contour, xPlane, xScaleFactor);\n\tplaneScale(contour, zPlane, zScaleFactor);\n\n\n\n\t// offsets\n\n\t/*\n\tThis part creates different offset of the contour at different height,\n\tin order to get all the vertices needed to create the faces of the stone.\n\t*/\n\n\tfor (i=0 ; i<contour.length ; i++) {\n\t\tcontour[i][\"y\"] = height;\n\t};\n\n\tlet distanceOffsetTable = ( (width + depth) / 2 ) / 5.5 ;\n\n\tlet tableContour = ClosedPolylineOffset(contour, distanceOffsetTable);\n\tuserData.tableContour = tableContour;\n\n\tlet crownHeigth = height / 5;\n\n\tfor (i=0 ; i<contour.length ; i++) {\n\t\tcontour[i][\"y\"] -= crownHeigth;\n\t};\n\n\tlet midCrown = ClosedPolylineOffset(contour, distanceOffsetTable / 2);\n\n\tfor (i=0 ; i<midCrown.length ; i++) {\n\t\tmidCrown[i][\"y\"] += crownHeigth / 1.6;\n\t};\n\n\tlet midCrownMiddlePoints = [];\n\n\tfor (i=0 ; i<midCrown.length ; i++) {\n\n\t\tlet line = new THREE.Line3(midCrown[i], midCrown[(i + 1) % midCrown.length]);\n\n\t\tmidCrownMiddlePoints.push( line.getCenter(new THREE.Vector3()) );\n\t}\n\n\tlet bottomGirdle = [];\n\tuserData.bottomGirdle = bottomGirdle;\n\n\tfor (i=0 ; i<contour.length ; i++) {\n\n\t\tbottomGirdle.push( new THREE.Vector3().copy(contour[i]) );\n\t\tbottomGirdle[i][\"y\"] -= 0.5 ;\n\t};\n\n\tlet distanceOffsetMidPavilion = ( (width + depth) / 2 ) / 7 ;\n\tlet midPavilion = ClosedPolylineOffset(bottomGirdle, distanceOffsetMidPavilion);\n\n\tfor (i=0 ; i<midPavilion.length ; i++) {\n\t\tmidPavilion[i][\"y\"] = height / 3.5 ;\n\t};\n\n\tlet midPavilionMiddlePoints = [];\n\n\tfor (i=0 ; i<midPavilion.length ; i++) {\n\n\t\tlet line = new THREE.Line3(midPavilion[i], midPavilion[(i + 1) % midPavilion.length]);\n\n\t\tmidPavilionMiddlePoints.push( line.getCenter(new THREE.Vector3()) );\n\t}\n\n\n\n\t// drawing\n\n\t/*\n\tas BufferGeometry doesn't take Vector3 nor Face3 in argument, these coordinates\n\tare extracted from the vector3 arrays\n\t*/\n\n\tlet geometry = new THREE.BufferGeometry();\n\tgeometry.userData = userData;\n\tlet l = contour.length;\n\tlet vertices = [];\n\tlet indices = [];\n\n\t\t// geometry's array of vertices\n\n\tfunction pushVerticesFromVector3(array, vector3) {\n\t\tlet [x, y, z] = [ vector3['x'], vector3['y'], vector3['z'] ];\n\t\tarray.push(x, y, z);\n\t};\n\n\tfor (i=0 ; i<l ; i++) {\n\t\tpushVerticesFromVector3(vertices, contour[i])\n\t};\n\n\tfor (i=0 ; i<l ; i++) {\n\t\tpushVerticesFromVector3(vertices, midCrownMiddlePoints[i])\n\t};\n\t\n\tfor (i=0 ; i<l ; i++) {\n\t\tpushVerticesFromVector3(vertices, tableContour[i])\n\t};\n\n\tfor (i=0 ; i<l ; i++) {\n\t\tpushVerticesFromVector3(vertices, bottomGirdle[i])\n\t};\n\n\tfor (i=0 ; i<l ; i++) {\n\t\tpushVerticesFromVector3(vertices, midPavilionMiddlePoints[i])\n\t};\n\n\tvertices.push(tip['x'], tip['y'], tip['z']);\n\n\t\n\n\t\t// geometry's array of faces\n\n\t\t// first raw of facets up to the girdle\n\tfor (i=0 ; i<l ; i++) {\n\n\t\tindices.push(\n\t\t\ti,\n\t\t\ti + l,\n\t\t\t(i + 1) % l\n\t\t\t);\n\t}\n\n\t\t// first raw of vertical facet of the crown\n\tfor (i=0 ; i<l ; i++) {\n\n\t\tindices.push(\n\t\t\t(2 * l) + ((i + 1) % l),\n\t\t\tl + ((i + 1) % l),\n\t\t\t(i + 1) % l\n\t\t\t);\n\t}\n\n\t\t// second raw of vertical facet of the crown\n\tfor (i=0 ; i<l ; i++) {\n\n\t\tindices.push(\n\t\t\t(2 * l) + ((i + 1) % l),\n\t\t\t(i + 1) % l,\n\t\t\tl + (i % l)\n\t\t\t);\n\t}\n\n\t\t// top raw of facets of the crown\n\tfor (i=0 ; i<l ; i++) {\n\n\t\tindices.push(\n\t\t\ti + l,\n\t\t\ti + (2 * l),\n\t\t\t(2 * l) + ((i + 1) % l)\n\t\t\t);\n\t}\n\n\t\t// table\n\tfor (i=0 ; i < l-2 ; i++) {\n\n\t\tindices.push(\n\t\t\tl * 2,\n\t\t\t((l * 2) + i + 2) % (l * 3),\n\t\t\t((l * 2) + i + 1) % ((l * 3) - 1)\n\t\t\t);\n\t}\n\n\t\t// girdle 1\n\tfor (i=0 ; i<l ; i++) {\n\n\t\tindices.push(\n\t\t\ti,\n\t\t\t(i + 1) % l,\n\t\t\ti + (3 * l)\n\t\t\t);\n\t}\n\n\t\t// girdle 2\n\tfor (i=0 ; i<l ; i++) {\n\n\t\tindices.push(\n\t\t\t(i + 1) % l,\n\t\t\t((i + 1) % l) + (3 * l),\n\t\t\ti + (3 * l)\n\t\t\t);\n\t}\n\n\t\t// top pavilion\n\tfor (i=0 ; i<l ; i++) {\n\n\t\tindices.push(\n\t\t\t((i + 1) % l) + (3 * l),\n\t\t\ti + (4 * l),\n\t\t\ti + (3 * l)\n\t\t\t);\n\t}\n\n\t\t// mid pavilion\n\tfor (i=0 ; i<l ; i++) {\n\n\t\tindices.push(\n\t\t\t((i + 1) % l) + (3 * l),\n\t\t\t((i + 1) % l) + (4 * l),\n\t\t\ti + (4 * l)\n\t\t\t);\n\t}\n\n\t\t// tip\n\tfor (i=0 ; i<l ; i++) {\n\n\t\tindices.push(\n\t\t\t((i + 1) % l) + (4 * l),\n\t\t\t(l * 5),\n\t\t\ti + (4 * l)\n\t\t\t);\n\t}\n\t\n\tgeometry.setIndex( indices );\n\tgeometry.addAttribute('position', new THREE.Float32BufferAttribute( vertices, 3 ));\n\n\tgeometry.computeVertexNormals();\n\n\treturn geometry ;\n\n}",
"function createCompositeParticles() {\n\tvar NXYZ = arguments[0];\n\tvar D = arguments[1];\n\tvar m = arguments[2];\n\tvar r = arguments[3];\n\tvar v = arguments[4];\n\tvar scenario = arguments[5];\n\t\n\tif(scenario < 4) {\n\t\t// Get number of particles\n\t\tvar Nx = NXYZ.x;\n\t\tvar Ny = NXYZ.y * 0 + 1;\n\t\tvar Nz = NXYZ.z;\n\t\t\n\t\t// Create particles in grid\n\t\tfor(var ix = 0; ix < Nx; ix++) {\n\t\t\tfor(var iy = 0; iy < Ny; iy++) {\n\t\t\t\tfor(var iz = 0; iz < Nz; iz++) {\n\t\t\t\t\toi = new Grain();\n\t\t\t\t\toi.m = m;\n\t\t\t\t\toi.q = 0;\n\t\t\t\t\toi.D = D;\n\t\t\t\t\t\n\t\t\t\t\tvar rndx = 0.01 * D * Math.random() * 1;\n\t\t\t\t\tvar rndy = 0.00 * D * Math.random() * 1;\n\t\t\t\t\tvar rndz = 0.01 * D * Math.random() * 1;\n\t\t\t\t\t\n\t\t\t\t\tvar x = D * (ix - 0.5 * (Nx - 1)) * (1 + rndx);\n\t\t\t\t\tvar y = D * (iy - 0.5 * (Ny - 1)) * (1 + rndy);\n\t\t\t\t\tvar z = D * (iz - 0.5 * (Nz - 1)) * (1 + rndz);\n\t\t\t\t\toi.r = Vect3.add(r, new Vect3(x, y, z));\n\t\t\t\t\toi.v = v;\n\t\t\t\t\toi.c = [\"#aaa\", \"#fafafa\"];\n\t\t\t\t\to.push(oi);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Creat composite particles\n\tvar D0 = D;\n\tvar D1 = D0 * Math.sqrt(2);\n\tvar D2 = 2 * D0;\n\t\n\tpartID = [];\n\tneighID = [];\n\tneighLN = [];\n\t\n\tif(scenario == 1) {\n\t\tpartID = [\n\t\t\t// S-Family\n\t\t\t00, 01, 10, 11, 04, 05, 14, 15, 08, 09, 18, 19,\n\t\t];\n\t\tneighID = [\n\t\t\t// S-family\n\t\t\t[10, 11, 01], [00, 10, 11], [00, 01, 11], [10, 00, 01],\n\t\t\t[14, 15, 05], [04, 14, 15], [04, 05, 15], [14, 04, 05],\n\t\t\t[18, 19, 09], [08, 18, 19], [08, 09, 19], [18, 08, 09],\n\t\t];\n\t\tneighLN = [\n\t\t\t// S-family\n\t\t\t[D0, D1, D0], [D0, D1, D0], [D0, D1, D0], [D0, D1, D0],\n\t\t\t[D0, D1, D0], [D0, D1, D0], [D0, D1, D0], [D0, D1, D0],\n\t\t\t[D0, D1, D0], [D0, D1, D0], [D0, D1, D0], [D0, D1, D0],\n\t\t];\n\t\t// S-family\n\t\to[00].c = [\"#f44\", \"#fcc\"];\n\t\to[01].c = [\"#f44\", \"#fcc\"];\n\t\to[10].c = [\"#f44\", \"#fcc\"];\n\t\to[11].c = [\"#f44\", \"#fcc\"];\n\t\to[04].c = [\"#f44\", \"#fcc\"];\n\t\to[05].c = [\"#f44\", \"#fcc\"];\n\t\to[14].c = [\"#f44\", \"#fcc\"];\n\t\to[15].c = [\"#f44\", \"#fcc\"];\n\t\to[08].c = [\"#f44\", \"#fcc\"];\n\t\to[09].c = [\"#f44\", \"#fcc\"];\n\t\to[18].c = [\"#f44\", \"#fcc\"];\n\t\to[19].c = [\"#f44\", \"#fcc\"];\t\t\n\t} else if(scenario == 2) {\n\t\tpartID = [\n\t\t\t// H-Family\n\t\t\t80, 81, 90, 91, 84, 85, 94, 95, 88, 89, 98, 99,\n\t\t];\n\t\tneighID = [\n\t\t\t// H-Family\n\t\t\t[90, 81], [80, 91], [80, 91], [90, 81],\n\t\t\t[94, 85], [84, 95], [84, 95], [94, 85],\n\t\t\t[98, 89], [88, 99], [88, 99], [98, 89],\n\t\t];\n\t\tneighLN = [\n\t\t\t// H-family\n\t\t\t[D0, D0], [D0, D0], [D0, D0], [D0, D0],\n\t\t\t[D0, D0], [D0, D0], [D0, D0], [D0, D0],\n\t\t\t[D0, D0], [D0, D0], [D0, D0], [D0, D0],\n\t\t];\n\t\t\n\t\t// H-family\n\t\to[80].c = [\"#44f\", \"#ccf\"];\n\t\to[81].c = [\"#44f\", \"#ccf\"];\n\t\to[90].c = [\"#44f\", \"#ccf\"];\n\t\to[91].c = [\"#44f\", \"#ccf\"];\n\t\to[84].c = [\"#44f\", \"#ccf\"];\n\t\to[85].c = [\"#44f\", \"#ccf\"];\n\t\to[94].c = [\"#44f\", \"#ccf\"];\n\t\to[95].c = [\"#44f\", \"#ccf\"];\n\t\to[88].c = [\"#44f\", \"#ccf\"];\n\t\to[89].c = [\"#44f\", \"#ccf\"];\n\t\to[98].c = [\"#44f\", \"#ccf\"];\n\t\to[99].c = [\"#44f\", \"#ccf\"];\n\t} else if(scenario == 3) {\n\t\tpartID = [\n\t\t\t// S-Family\n\t\t\t00, 01, 10, 11, 04, 05, 14, 15, 08, 09, 18, 19,\n\t\t\t// H-Family\n\t\t\t80, 81, 90, 91, 84, 85, 94, 95, 88, 89, 98, 99,\n\t\t];\n\t\tneighID = [\n\t\t\t// S-family\n\t\t\t[10, 11, 01], [00, 10, 11], [00, 01, 11], [10, 00, 01],\n\t\t\t[14, 15, 05], [04, 14, 15], [04, 05, 15], [14, 04, 05],\n\t\t\t[18, 19, 09], [08, 18, 19], [08, 09, 19], [18, 08, 09],\n\t\t\t// H-Family\n\t\t\t[90, 81], [80, 91], [80, 91], [90, 81],\n\t\t\t[94, 85], [84, 95], [84, 95], [94, 85],\n\t\t\t[98, 89], [88, 99], [88, 99], [98, 89],\n\t\t];\n\t\tneighLN = [\n\t\t\t// S-family\n\t\t\t[D0, D1, D0], [D0, D1, D0], [D0, D1, D0], [D0, D1, D0],\n\t\t\t[D0, D1, D0], [D0, D1, D0], [D0, D1, D0], [D0, D1, D0],\n\t\t\t[D0, D1, D0], [D0, D1, D0], [D0, D1, D0], [D0, D1, D0],\n\t\t\t// H-family\n\t\t\t[D0, D0], [D0, D0], [D0, D0], [D0, D0],\n\t\t\t[D0, D0], [D0, D0], [D0, D0], [D0, D0],\n\t\t\t[D0, D0], [D0, D0], [D0, D0], [D0, D0],\n\t\t];\n\t\t\n\t\t// S-family\n\t\to[00].c = [\"#f44\", \"#fcc\"];\n\t\to[01].c = [\"#f44\", \"#fcc\"];\n\t\to[10].c = [\"#f44\", \"#fcc\"];\n\t\to[11].c = [\"#f44\", \"#fcc\"];\n\t\to[04].c = [\"#f44\", \"#fcc\"];\n\t\to[05].c = [\"#f44\", \"#fcc\"];\n\t\to[14].c = [\"#f44\", \"#fcc\"];\n\t\to[15].c = [\"#f44\", \"#fcc\"];\n\t\to[08].c = [\"#f44\", \"#fcc\"];\n\t\to[09].c = [\"#f44\", \"#fcc\"];\n\t\to[18].c = [\"#f44\", \"#fcc\"];\n\t\to[19].c = [\"#f44\", \"#fcc\"];\n\t\t\n\t\t// H-family\n\t\to[80].c = [\"#44f\", \"#ccf\"];\n\t\to[81].c = [\"#44f\", \"#ccf\"];\n\t\to[90].c = [\"#44f\", \"#ccf\"];\n\t\to[91].c = [\"#44f\", \"#ccf\"];\n\t\to[84].c = [\"#44f\", \"#ccf\"];\n\t\to[85].c = [\"#44f\", \"#ccf\"];\n\t\to[94].c = [\"#44f\", \"#ccf\"];\n\t\to[95].c = [\"#44f\", \"#ccf\"];\n\t\to[88].c = [\"#44f\", \"#ccf\"];\n\t\to[89].c = [\"#44f\", \"#ccf\"];\n\t\to[98].c = [\"#44f\", \"#ccf\"];\n\t\to[99].c = [\"#44f\", \"#ccf\"];\n\t}\n\t\n\tif(scenario == 2 || scenario == 3) {\n\t\to[81].r.x += 0.5 * D0;\n\t\to[91].r.x += 0.5 * D0;\n\t\to[81].r.z += -0.1 * D0;\n\t\to[91].r.z += -0.1 * D0;\n\t\t\n\t\to[85].r.x += 0.5 * D0;\n\t\to[95].r.x += 0.5 * D0;\n\t\to[85].r.z += -0.1 * D0;\n\t\to[95].r.z += -0.1 * D0;\n\t\t\n\t\to[89].r.x += 0.5 * D0;\n\t\to[99].r.x += 0.5 * D0;\n\t\to[89].r.z += -0.1 * D0;\n\t\to[99].r.z += -0.1 * D0;\t\n\t}\n\t\n\t/*\n\tc = [\"#aaa\", \"#fafafa\"];\n\tc = [\"#f44\", \"#fcc\"];\n\tc = [\"#44f\", \"#ccf\"];\n\tc = [\"#4f4\", \"#cfc\"];\n\t*/\n\t\n\tif(scenario == 4) {\n\t\t// Left composite particle -- lock\n\t\tcreateParticle(-4 * D, 0, -1 * D);\n\t\tcreateParticle(-5 * D, 0, -1 * D);\n\t\tcreateParticle(-5 * D, 0, 0 * D);\n\t\tcreateParticle(-5 * D, 0, 1 * D);\n\t\tcreateParticle(-4 * D, 0, 1 * D);\n\t\t\n\t\t// Right composite particle -- key\n\t\tcreateParticle( 5 * D, 0, -1 * D);\n\t\tcreateParticle( 5 * D, 0, 0 * D);\n\t\tcreateParticle( 4 * D, 0, 0 * D);\n\t\tcreateParticle( 5 * D, 0, 1 * D);\n\t\t\n\t\t// Design binding network\n\t\tpartID = [\n\t\t\t// S-Family\n\t\t\t00, 01, 02, 03, 04,\n\t\t\t05, 06, 07, 08,\n\t\t];\n\t\tneighID = [\n\t\t\t// S-family\n\t\t\t[01, 02, 04], [00, 02], [00, 01, 03, 04], [02, 04], [02, 03, 00],\n\t\t\t[06, 07], [05, 07, 08], [05, 06, 08], [06, 07],\n\t\t];\n\t\tneighLN = [\n\t\t\t// S-family\n\t\t\t[D0, D1, D2], [D0, D0], [D1, D0, D0, D1], [D0, D0], [D1, D0, D2],\n\t\t\t[D0, D1], [D0, D0, D0], [D1, D0, D1], [D0, D1],\n\t\t];\n\t}\n\t\n\tif(scenario == 5) {\n\t\t// Left composite particle -- lock\n\t\tcreateParticle(-4 * D, 0, -1 * D);\n\t\tcreateParticle(-5 * D, 0, -1 * D);\n\t\tcreateParticle(-5 * D, 0, 0 * D);\n\t\tcreateParticle(-5 * D, 0, 1 * D);\n\t\tcreateParticle(-4 * D, 0, 1 * D);\n\t\t\n\t\t// Right composite particle -- key\n\t\tcreateParticle( 5 * D, 0, 1 * D);\n\t\tcreateParticle( 5 * D, 0, 2 * D);\n\t\tcreateParticle( 4 * D, 0, 2 * D);\n\t\tcreateParticle( 5 * D, 0, 3 * D);\n\t\t\n\t\t// Design binding network\n\t\tpartID = [\n\t\t\t// S-Family\n\t\t\t00, 01, 02, 03, 04,\n\t\t\t05, 06, 07, 08,\n\t\t];\n\t\tneighID = [\n\t\t\t// S-family\n\t\t\t[01, 02, 04], [00, 02], [00, 01, 03, 04], [02, 04], [02, 03, 00],\n\t\t\t[06, 07], [05, 07, 08], [05, 06, 08], [06, 07],\n\t\t];\n\t\tneighLN = [\n\t\t\t// S-family\n\t\t\t[D0, D1, D2], [D0, D0], [D1, D0, D0, D1], [D0, D0], [D1, D0, D2],\n\t\t\t[D0, D1], [D0, D0, D0], [D1, D0, D1], [D0, D1],\n\t\t];\n\t}\n\t\t\n\tif(scenario == 6) {\n\t\t// Left composite particle -- lock\n\t\tcreateParticle(-4 * D, 0, -1 * D);\n\t\tcreateParticle(-5 * D, 0, -1 * D);\n\t\tcreateParticle(-5 * D, 0, 0 * D);\n\t\tcreateParticle(-5 * D, 0, 1 * D);\n\t\tcreateParticle(-4 * D, 0, 1 * D);\n\t\t\n\t\t// Right composite particle -- key\n\t\tcreateParticle( 3 * D, 0, -4 * D);\n\t\tcreateParticle( 4 * D, 0, -4 * D);\n\t\tcreateParticle( 4 * D, 0, -3 * D);\n\t\tcreateParticle( 5 * D, 0, -4 * D);\n\t\t\n\t\t// Design binding network\n\t\tpartID = [\n\t\t\t// S-Family\n\t\t\t00, 01, 02, 03, 04,\n\t\t\t05, 06, 07, 08,\n\t\t];\n\t\tneighID = [\n\t\t\t// S-family\n\t\t\t[01, 02, 04], [00, 02], [00, 01, 03, 04], [02, 04], [02, 03, 00],\n\t\t\t[06, 07], [05, 07, 08], [05, 06, 08], [06, 07],\n\t\t];\n\t\tneighLN = [\n\t\t\t// S-family\n\t\t\t[D0, D1, D2], [D0, D0], [D1, D0, D0, D1], [D0, D0], [D1, D0, D2],\n\t\t\t[D0, D1], [D0, D0, D0], [D1, D0, D1], [D0, D1],\n\t\t];\n\t}\n\t\t\n\tif(scenario == 7) {\n\t\t// Left composite particle -- lock\n\t\tcreateParticle(-4 * D, 0, -1 * D);\n\t\tcreateParticle(-5 * D, 0, -1 * D);\n\t\tcreateParticle(-5 * D, 0, 0 * D);\n\t\tcreateParticle(-5 * D, 0, 1 * D);\n\t\tcreateParticle(-4 * D, 0, 1 * D);\n\t\t\n\t\t// Right composite particle -- key\n\t\tcreateParticle( 3 * D, 0, -3 * D);\n\t\tcreateParticle( 4 * D, 0, -3 * D);\n\t\tcreateParticle( 4 * D, 0, -2 * D);\n\t\tcreateParticle( 5 * D, 0, -3 * D);\n\t\t\n\t\t// Design binding network\n\t\tpartID = [\n\t\t\t// S-Family\n\t\t\t00, 01, 02, 03, 04,\n\t\t\t05, 06, 07, 08,\n\t\t];\n\t\tneighID = [\n\t\t\t// S-family\n\t\t\t[01, 02, 04], [00, 02], [00, 01, 03, 04], [02, 04], [02, 03, 00],\n\t\t\t[06, 07], [05, 07, 08], [05, 06, 08], [06, 07],\n\t\t];\n\t\tneighLN = [\n\t\t\t// S-family\n\t\t\t[D0, D1, D2], [D0, D0], [D1, D0, D0, D1], [D0, D0], [D1, D0, D2],\n\t\t\t[D0, D1], [D0, D0, D0], [D1, D0, D1], [D0, D1],\n\t\t];\n\t}\n\t\t\n\tif(scenario == 8) {\n\t\t// Left composite particle -- lock\n\t\tcreateParticle(-4 * D, 0, -1 * D);\n\t\tcreateParticle(-5 * D, 0, -1 * D);\n\t\tcreateParticle(-5 * D, 0, 0 * D);\n\t\tcreateParticle(-5 * D, 0, 1 * D);\n\t\tcreateParticle(-4 * D, 0, 1 * D);\n\t\t\n\t\t// Right composite particle -- key\n\t\tcreateParticle( 4 * D, 0, 1 * D);\n\t\tcreateParticle( 4 * D, 0, 0 * D);\n\t\tcreateParticle( 5 * D, 0, 0 * D);\n\t\tcreateParticle( 4 * D, 0, -1 * D);\n\t\t\n\t\t// Design binding network\n\t\tpartID = [\n\t\t\t// S-Family\n\t\t\t00, 01, 02, 03, 04,\n\t\t\t05, 06, 07, 08,\n\t\t];\n\t\tneighID = [\n\t\t\t// S-family\n\t\t\t[01, 02, 04], [00, 02], [00, 01, 03, 04], [02, 04], [02, 03, 00],\n\t\t\t[06, 07], [05, 07, 08], [05, 06, 08], [06, 07],\n\t\t];\n\t\tneighLN = [\n\t\t\t// S-family\n\t\t\t[D0, D1, D2], [D0, D0], [D1, D0, D0, D1], [D0, D0], [D1, D0, D2],\n\t\t\t[D0, D1], [D0, D0, D0], [D1, D0, D1], [D0, D1],\n\t\t];\n\t}\n\t\t\n\tif(scenario == 9) {\n\t\t// Left composite particle -- lock\n\t\tcreateParticle(-4 * D, 0, -1 * D);\n\t\tcreateParticle(-5 * D, 0, -1 * D);\n\t\tcreateParticle(-5 * D, 0, 0 * D);\n\t\tcreateParticle(-5 * D, 0, 1 * D);\n\t\tcreateParticle(-4 * D, 0, 1 * D);\n\t\t\n\t\t// Right composite particle -- key\n\t\tcreateParticle( 4 * D, 0, 2 * D);\n\t\tcreateParticle( 4 * D, 0, 1 * D);\n\t\tcreateParticle( 5 * D, 0, 1 * D);\n\t\tcreateParticle( 4 * D, 0, 0 * D);\n\t\t\n\t\t// Design binding network\n\t\tpartID = [\n\t\t\t// S-Family\n\t\t\t00, 01, 02, 03, 04,\n\t\t\t05, 06, 07, 08,\n\t\t];\n\t\tneighID = [\n\t\t\t// S-family\n\t\t\t[01, 02, 04], [00, 02], [00, 01, 03, 04], [02, 04], [02, 03, 00],\n\t\t\t[06, 07], [05, 07, 08], [05, 06, 08], [06, 07],\n\t\t];\n\t\tneighLN = [\n\t\t\t// S-family\n\t\t\t[D0, D1, D2], [D0, D0], [D1, D0, D0, D1], [D0, D0], [D1, D0, D2],\n\t\t\t[D0, D1], [D0, D0, D0], [D1, D0, D1], [D0, D1],\n\t\t];\n\t}\n\t\t\n\tfunction createParticle(dx, dy, dz) {\n\t\tvar oi = new Grain();\n\t\toi.m = m; oi.q = 0; oi.D = D; oi.v = v;\n\t\toi.r = Vect3.add(r, new Vect3(dx, dy, dz));\n\t\toi.c = [\"#f44\", \"#fcc\"];\n\t\toi.id = o.length;\n\t\t\n\t\to.push(oi);\n\t}\n}",
"function createPoints(){\n\n var geometry = new THREE.Geometry();\n\n for(var i=0; i<1000; i++){\n var star = new THREE.Vector3();\n star.x = THREE.Math.randFloatSpread(100);\n star.y = THREE.Math.randFloatSpread(100);\n star.z = THREE.Math.randFloatSpread(100);\n geometry.vertices.push(star);\n }\n\n var material = new THREE.PointsMaterial({\n color:'red'\n });\n\n var cube = new THREE.Points(geometry, material);\n scene.add(cube);\n\n}",
"generateVertices() {\n var sp = this.props.shapeParams;\n\n var vertexes = [];\n var factor = 1.05;\n\n DEBUG && console.log(\"[Convex]: Generating convex points (\"+this.props.vertexCount+\").\");\n\n for(var i = 0; i < this.props.vertexCount; i++){\n var x = (Math.random() - 0.5) * sp.boundingBox.x * factor;\n var y = (Math.random() - 0.5) * sp.boundingBox.y * factor;\n var z = (Math.random() - 0.5) * sp.boundingBox.z * factor;\n\n // Check if points comply to shape equation.\n if( sp.equation( x, y, z ) )\n vertexes.push( new THREE.Vector3( x, y, z ) );\n }\n\n DEBUG && console.log( \"[Convex]: Generation ended. Final point count: \"+vertexes.length );\n return vertexes;\n}",
"function drawObject(vertarr, pgons, scale_factor, rotation_angle, x_amt, y_amt, z_amt,\n color_id=255, color_mode=0) {\n\n //console.log(pgons);\n\n var triarr = [];\n var trinorms = [];\n var which_poly = 0;\n\n var transform_mat = new Matrix4();\n var view_mat = new Matrix4();\n var normal_rotation_mat = new Matrix4();\n\n\n\n // set our scaling limits\n scale_factor = Math.max(scale_factor, .1);\n scale_factor = Math.min(scale_factor, 2.0);\n\n // build up triarr (break up the polygons into triangles)\n for (var pgon = 1; pgon < pgons.length; pgon++) {\n // my algorithm for making polygons into triangles\n for (var vert = pgons[pgon].length - 2; vert >= 1; vert--) {\n triarr.push(vertarr[pgons[pgon][vert]][0]);\n triarr.push(vertarr[pgons[pgon][vert]][1]);\n triarr.push(vertarr[pgons[pgon][vert]][2]);\n\n triarr.push(vertarr[pgons[pgon][vert + 1]][0]);\n triarr.push(vertarr[pgons[pgon][vert + 1]][1]);\n triarr.push(vertarr[pgons[pgon][vert + 1]][2]);\n\n triarr.push(vertarr[pgons[pgon][0]][0]);\n triarr.push(vertarr[pgons[pgon][0]][1]);\n triarr.push(vertarr[pgons[pgon][0]][2]);\n\n triarr.push(which_poly); // keep track of which polygon the tri belongs\n // so that we know what normal to use for flat shading\n };\n which_poly++;\n };\n //console.log(triarr);\n //console.log(triarr.length);\n\n //console.log(pgons);\n\n\n // get an array of polygon normals for flat shading\n var polynorms = getpolynorms(vertarr, pgons);\n // console.log(polynorms);\n\n // get a normal of vertex normals for smooth shading\n var vertnorms = getvertnorms(vertarr, pgons);\n\n // get an array of trianle norms for flat shading\n var trinorms = get_trinorms(pgons, vertnorms);\n\n //console.log(\"pnorms\", polynorms);\n //console.log(\"vnorms\", vertnorms);\n //console.log(\"trinorms\", trinorms);\n\n\n //get_trinorms();\n\n // get the centroid of the object so that we can translate object to origin\n var cent = get_centroid(vertarr);\n //console.log(\"cent\", cent);\n\n // set our bounding box to around the +-1 around the origin\n transform_mat.setOrtho(-1, 1, -1, 1, -1, 1);\n\n\n // get our camera set up\n view_mat.setPerspective(FOV, 1, 1, 200);\n\n view_mat.lookAt(cam_x_amt, cam_y_amt, cam_z_amt, // LookFrom\n cam_x_amt + yaw, cam_y_amt - pitch, cam_z_amt - 3, // LookAt\n 0, 1, 0); // Up Vector\n\n\n var maxdiff = get_maxdiff(vertarr);\n //console.log(maxdiff);\n\n // store all of our object transformations into a matrix\n\n transform_mat.setScale(scale_factor / maxdiff, scale_factor / maxdiff, scale_factor /maxdiff);\n\n transform_mat.rotate(rotation_angle, 0, 1, 0);\n\n // try putting this before scale\n transform_mat.translate(-cent[0]*scale_factor, -cent[1]*scale_factor, -cent[2]*scale_factor);\n\n transform_mat.translate(x_amt, -y_amt, z_amt);\n\n\n // rotate our normals along with our vertices\n normal_rotation_mat.setInverseOf(transform_mat).transpose();\n\n // send everything to the shaders\n\n // send transformation matrix to shaders\n var matloc = gl.getUniformLocation(gl.program, \"mymatrix\");\n gl.uniformMatrix4fv(matloc, gl.FALSE, transform_mat.elements);\n\n var transnormloc = gl.getUniformLocation(gl.program, \"trans_norm\");\n gl.uniformMatrix4fv(transnormloc, gl.FALSE, normal_rotation_mat.elements);\n\n // send normal rotation matrix to shaders\n var mat_norm_loc = gl.getUniformLocation(gl.program, \"norm_matrix\");\n gl.uniformMatrix4fv(mat_norm_loc, gl.FALSE, normal_rotation_mat.elements);\n\n //send perspective view matrix to shaders\n var view_loc = gl.getUniformLocation(gl.program, 'view_matrix');\n gl.uniformMatrix4fv(view_loc, gl.false, view_mat.elements);\n\n // are we flat shading or smooth shading?\n var boolloc = gl.getUniformLocation(gl.program, \"flat_shade\");\n gl.uniform1i(boolloc, flatshade);\n\n var isShinyLoc = gl.getUniformLocation(gl.program, \"is_shiny\");\n gl.uniform1i(isShinyLoc, isShiny);\n\n var isShinyVertLoc = gl.getUniformLocation(gl.program, \"is_vert_shiny\");\n gl.uniform1i(isShinyVertLoc, isShiny);\n\n // is this ortho or perspective?\n var isOrtho_loc = gl.getUniformLocation(gl.program, \"is_ortho\");\n gl.uniform1i(isOrtho_loc, isOrtho);\n\n // what is the color of our object?\n var isBlue_loc = gl.getUniformLocation(gl.program, \"is_blue\");\n gl.uniform1i(isBlue_loc, /*isBlue*/ 1);\n\n var color_mode_loc = gl.getUniformLocation(gl.program, \"color_mode\");\n gl.uniform1i(color_mode_loc, color_mode);\n\n var isTextured_loc = gl.getUniformLocation(gl.program, \"is_textured\");\n gl.uniform1i(isTextured_loc, isTextured);\n\n var u_isTextured_loc = gl.getUniformLocation(gl.program, \"u_is_textured\");\n gl.uniform1i(u_isTextured_loc, isTextured);\n\n var colorloc = gl.getUniformLocation(gl.program, \"mycolor\");\n gl.uniform3fv(colorloc, [0, 0, color_id / 255]);\n\n //console.log([listOfObjs[0][\"x_amt\"], -listOfObjs[0][\"y_amt\"], 0, 1]);\n var light_pos_loc = gl.getUniformLocation(gl.program, \"light_pos\");\n gl.uniform4fv(light_pos_loc, [listOfObjs[0][\"x_amt\"], -listOfObjs[0][\"y_amt\"], 0, 1]);\n\n var cam_pos = [0, 0, -1];\n if (!isOrtho) {\n cam_pos = [cam_x_amt / 50, cam_y_amt / 50, cam_z_amt];\n };\n\n var cam_pos_loc = gl.getUniformLocation(gl.program, \"cam_pos\");\n gl.uniform3fv(cam_pos_loc, cam_pos);\n\n var v_cam_pos_loc = gl.getUniformLocation(gl.program, \"cam_position\");\n gl.uniform4fv(v_cam_pos_loc, [cam_pos[0], cam_pos[1], cam_pos[2], 1]);\n\n var light_position_loc = gl.getUniformLocation(gl.program, \"light_position\");\n gl.uniform4fv(light_position_loc, [listOfObjs[0][\"x_amt\"], -listOfObjs[0][\"y_amt\"], 0, 1]);\n\n var gloss_loc = gl.getUniformLocation(gl.program, \"gloss\");\n gl.uniform1f(gloss_loc, shininess);\n\n var glossiness_loc = gl.getUniformLocation(gl.program, \"glossiness\");\n gl.uniform1f(glossiness_loc, shininess);\n\n /*if (isTextured == 1) {\n gl.uniform1i(gl.getUniformLocation(gl.program, \"u_sampler\"), 0);\n };*/\n\n if (shouldClear) {\n //clear drawings each time we render\n gl.clear(gl.COLOR_BUFFER_BIT);\n };\n\n // pass one triangle at a time to shaders\n // AKA pass 9 vertices, and 3 normals\n //console.log(triarr);\n for (var i = 0; i < triarr.length; i += 10 /*10 bcs polygon identifier*/) {\n\n //console.log(i);\n // [x, y, z, n1x, n1y, n1z...]\n var stridedarr = new Float32Array([\n triarr[i], triarr[i+1], triarr[i+2], // vert 1\n\n trinorms[i], trinorms[i+1], trinorms[i+2], // vertnorm 1\n\n triarr[i+3], triarr[i+4], triarr[i+5], // vert 2\n\n trinorms[i+3], trinorms[i+4], trinorms[i+5], // vertnorm 2\n\n triarr[i+6], triarr[i+7], triarr[i+8],\n\n trinorms[i+6], trinorms[i+7], trinorms[i+8]\n ]);\n\n var vertexBuffer = gl.createBuffer();\n\n // Bind the buffer object to target\n gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);\n // Write data into the buffer object\n gl.bufferData(gl.ARRAY_BUFFER, stridedarr, gl.DYNAMIC_DRAW);\n\n //pass uniforms and attributes to shaders\n\n //send polygon normal for flat shading\n var normloc = gl.getUniformLocation(gl.program, \"norm\");\n gl.uniform3fv(normloc, [polynorms[triarr[i+9]][0], polynorms[triarr[i+9]][1], polynorms[triarr[i+9]][2]]);\n\n var a_Position = gl.getAttribLocation(gl.program, 'a_Position');\n\n // Assign the buffer object to a_Position variable\n gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, 24, 0);\n\n // Enable the assignment to a_Position variable\n gl.enableVertexAttribArray(a_Position);\n\n var a_normal = gl.getAttribLocation(gl.program, 'a_normal');\n\n // Assign the buffer object to a_normal variable\n gl.vertexAttribPointer(a_normal, 3, gl.FLOAT, false, 24, 12);\n\n // Enable the assignment to a_normal variable\n gl.enableVertexAttribArray(a_normal);\n\n // draw the triangle!\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n };\n\n}",
"function Crust(parameters) {\n\tthis.grid = parameters['grid'] || stop('missing parameter: \"grid\"');\n\n\tvar length = this.grid.vertices.length;\n\n var buffer = parameters['buffer'] || new ArrayBuffer(8 * Float32Array.BYTES_PER_ELEMENT * length);\n this.buffer = buffer;\n\n this.sediment \t\t\t= new Float32Array(buffer, 0 * Float32Array.BYTES_PER_ELEMENT * length, length);\n this.sedimentary\t\t= new Float32Array(buffer, 1 * Float32Array.BYTES_PER_ELEMENT * length, length);\n this.metamorphic\t\t= new Float32Array(buffer, 2 * Float32Array.BYTES_PER_ELEMENT * length, length);\n this.felsic_plutonic \t= new Float32Array(buffer, 3 * Float32Array.BYTES_PER_ELEMENT * length, length);\n this.felsic_volcanic \t= new Float32Array(buffer, 4 * Float32Array.BYTES_PER_ELEMENT * length, length);\n this.mafic_volcanic \t= new Float32Array(buffer, 5 * Float32Array.BYTES_PER_ELEMENT * length, length);\n this.mafic_plutonic \t= new Float32Array(buffer, 6 * Float32Array.BYTES_PER_ELEMENT * length, length);\n this.age \t\t\t\t= new Float32Array(buffer, 7 * Float32Array.BYTES_PER_ELEMENT * length, length);\n\n this.conserved_array \t= new Float32Array(buffer, 0, 5 * length);\n this.mass_array \t\t= new Float32Array(buffer, 0, 7 * length);\n this.everything \t\t= new Float32Array(buffer);\n\n this.all_pools = [ \n \tthis.sediment,\n\t\tthis.sedimentary,\n\t\tthis.metamorphic,\n\t\tthis.felsic_plutonic,\n\t\tthis.felsic_volcanic,\n\t\tthis.mafic_volcanic,\n\t\tthis.mafic_plutonic,\n\t\tthis.age,\n\t];\n\n\tthis.mass_pools = [ \n \tthis.sediment,\n\t\tthis.sedimentary,\n\t\tthis.metamorphic,\n\t\tthis.felsic_plutonic,\n\t\tthis.felsic_volcanic,\n\t\tthis.mafic_volcanic,\n\t\tthis.mafic_plutonic,\n\t];\n\n\tthis.conserved_pools = [ \n \tthis.sediment,\n\t\tthis.sedimentary,\n\t\tthis.metamorphic,\n\t\tthis.felsic_plutonic,\n\t\tthis.felsic_volcanic,\n\t];\n\n\tthis.nonconserved_pools = [ \n\t\tthis.mafic_volcanic,\n\t\tthis.mafic_plutonic,\n\t\tthis.age,\n\t];\n\n\t// The following are the most fundamental fields to the tectonics model:\n\t//\n\t// \"felsic\" is the mass of the buoyant, unsubductable igneous component of the crust\n\t// AKA \"sial\", or \"continental\" crust\n\t// \n\t// \"sediment\", \"sedimentary\", and \"metamorphic\" are forms of felsic rock that have been converted by weathering, lithification, or metamorphosis\n\t// together with felsic, they form a conserved quantity - felsic type rock is never created or destroyed without our explicit say-so\n\t// This is done to provide our model with a way to check for errors\n\t//\n\t// \"mafic\" is the mass of the denser, subductable igneous component of the crust\n\t// AKA \"sima\", or \"oceanic\" crust\n\t// mafic never undergoes conversion to the other rock types (sediment, sedimentary, or metamorphic)\n\t// this is due to a few reasons:\n\t// 1.) it's not performant\n\t// 2.) mafic is not conserved, so it's not as important to get right\n\t// 3.) mafic remains underwater most of the time so it isn't very noticeable\n\t//\n\t// \"volcanic\" rock is rock that was created by volcanic resurfacing\n\t// \"plutonic\" rock is rock that has \n\t// by tracking plutonic/volcanic rock, we can identify the specific kind of rock that's in a region:\n\t// \n\t// \t\t\tvolcanic \tplutonic\n\t// \tfelsic \trhyolite \tgranite\n\t// \tmafic \tbasalt \t\tgabbro\n\t// \n\t//\n\t// \"age\" is the age of the subductable, mafic component of the crust\n\t// we don't track the age of unsubductable crust because it doesn't affect model behavior\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether or not we have a querystring. | function hasQueryString() {
return location.href.indexOf("?") !== -1;
} | [
"function hasQueryString() {\n\n\t\tvar url = this.parseURI();\n\n\t\tif ( url.search !== null ) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}",
"function hasQueryString() {\n return location.href.indexOf(\"?\") !== -1;\n}",
"function hasQuery(url) {\n return (url.indexOf(\"?\") === -1);\n }",
"function hasQueryString(key) {\n return window.location.search.substr(1).split(\"&\").some(function(item) {\n if (key == item.split(\"=\")[0]) {\n return true;\n }\n });\n }",
"function is_param_exist() {\n if(document.URL.indexOf('?') != -1){\n return true;\n }\n return false;\n }",
"function checkUrlQueryString( string ) {\n\tvar url = window.location.href,\n\t\tresult = false;\n\tif ( -1 !== url.indexOf( `?log=${ string }` ) || -1 !== url.indexOf( `&log=${ string }` ) ||\n\t\t-1 !== url.indexOf( `?log[]=${ string }` ) || -1 !== url.indexOf( `&log[]=${ string }` ) ) {\n\t\tresult = true;\n\t}\n\treturn result;\n}",
"static getQuery() {\n let pieces = window.location.href.split('?');\n if (pieces.length == 2) {\n return pieces[1];\n } else {\n return false;\n }\n }",
"function isSetURLParameter(name, ie_path) {\n\t\t\tif (ie_path === undefined || ie_path == 'undefined' || ie_path == null) {\n\t\t\t\treturn (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)', 'i').exec(location.search) !== null);\n\t\t\t} else {\n\t\t\t\treturn (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)', 'i').exec(ie_path) !== null);\n\t\t\t}\n\t\t}",
"function urlContainsParameters() {\n return containsParameters(window.location.search);\n}",
"hasQueryParameters() {\n if (this.queryParameters && Object.keys(this.queryParameters).length > 0) {\n return true\n } else {\n return false\n }\n }",
"function hasUrlParameters(url) {\r\n\tif(url.lastIndexOf(\"?\") > -1) return true;\r\n\treturn false;\r\n}",
"function checkQueryString() {\n\tif (jobListing.queryFlag) {\n\t\t// convert query string to array of values\n\t\tvar query = convertQueryToObject(jobListing.query);\n\t\t// check if display = detail...otherwise assume search\n\t\tif (query.hasOwnProperty('display') && query.display[0] === 'details') {\n\t\t\tif (!query.hasOwnProperty('j') || !query['j'][0].length) return;\n\t\t\tgetAjaxDetail(query);\n\t\t} else {\n\t\t\t// set the form inputs based on the query string\n\t\t\tconvertQueryToForm(query);\n\t\t\t// and submit \n\t\t\t\tvar args = jQuery( '#jl-job-search' ).serializeArray();\n\t\t\t\tjlAjaxLoadJobs( args );\n\t\t}\n\t}\n}",
"function checkURLParam ( term ) {\r\n var url = window.location.href;\r\n\r\n if( url.indexOf('?' + term) != -1 )\r\n return true;\r\n else if( url.indexOf('&' + term) != -1 )\r\n return true;\r\n\r\n return false\r\n }",
"CheckURLParams(tag, url){\n if(url.searchParams.has(tag)){\n return true;\n }else{\n return false;\n }\n }",
"function hasUrlParameters() {\n return countUrlParameters() > 0;\n}",
"function isUrlSearchParams(value) {\n return typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams;\n}",
"function paramExists(param) {\n var url = window.location.href;\n if (url.indexOf('?' + param + '=') != -1)\n return true;\n else if (url.indexOf('&' + param + '=') != -1)\n return true;\n return false;\n}",
"function validateQueryStringParams(urlParams) {\n if (urlParams.client_id == null) return false;\n if (urlParams.code_challenge == null) return false;\n if (urlParams.code_challenge_method != 'S256') return false;\n if (urlParams.redirect_uri == null) return false;\n if (urlParams.response_type != 'code') return false;\n if (urlParams.state == null) return false;\n \n return true;\n}",
"function isUrlSearchParams(value) {\n return typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create 7 clientproperties commands foreach publisher in order to change the titles' fontsize this affects on lineheight, maxsize, height and branding lineheight | function change_titles_size(new_font_size, new_line_height) {
for (var i = 0; i < jsonData.length ; i++) {
console.log("------ "+i+" ------");
var needChange = false;
var newCustom = "";
var oldCustom = "";
var mode = jsonData[i];
console.log(mode['mode_name']);
// edit FONT-SIZE client-properties
commands += "\nclient-properties-new set " + mode['name'] + " default " + mode['mode_name'] + " \".syndicatedItem .video-title/font-size\" \"" + new_font_size + ".0px\"\n";
commands += "\nclient-properties-new set " + mode['name'] + " default " + mode['mode_name'] + " \".video-title/font-size\" \"" + new_font_size + ".0px\"\n";
// edit LINE-HEIGHT client-properties
commands += "\nclient-properties-new set " + mode['name'] + " default " + mode['mode_name'] + " \".syndicatedItem .video-title/line-height\" \"" + new_line_height + ".0px\"\n";
commands += "\nclient-properties-new set " + mode['name'] + " default " + mode['mode_name'] + " \".video-title/line-height\" \"" + new_line_height + ".0px\"\n";
// calculate the number of ROWS
var rows = parseInt(mode['.syndicatedItem .video-title/max-height'])/parseInt(mode['.syndicatedItem .video-title/line-height']);
console.log("number of rows: " + rows);
// edit MAX-HEIGHT client-properties
commands += "\nclient-properties-new set " + mode['name'] + " default " + mode['mode_name'] + " \".syndicatedItem .video-title/max-height\" \"" + rows*new_line_height + ".0px\"\n";
commands += "\nclient-properties-new set " + mode['name'] + " default " + mode['mode_name'] + " \".video-title/max-height\" \"" + (rows+1)*new_line_height + ".0px\"\n";
// SET HEIGHT IN CUSTOM-CSS
oldCustom = mode['mode-custom-css'];
if (mode['mode_name'].indexOf('text-links') > -1) {
var selectors = "." + mode['mode_name'] + " .videoCube .video-label-box";
var index = oldCustom.indexOf(selectors);
// video-label-box height selector was found
if (index > -1) {
// PART 1 OF CUSTOM
var custom_part1 = oldCustom.substring(0, index);
var temp = oldCustom.substring(index);
temp = temp.substring(0, temp.indexOf('}')+1);
// PART 3 OF CUSTOM
var custom_part3 = oldCustom.substring(index+temp.length);
// working on temp part (custom_part2)
var heightIndex = temp.indexOf('min-height:');
if (heightIndex > -1) {
var oldHeight = temp.substring(heightIndex+11);
oldHeight = oldHeight.substring(0, oldHeight.indexOf(';'));
temp = temp.replace(oldHeight, " " + (new_line_height) + ".0px" );
newCustom = custom_part1.concat("\n").concat(temp).concat("\n").concat(custom_part3);
needChange = true;
}
}
else {
// video-label-box selector was not found
console.log("video-label-box selector was not found");
}
}
else {
if (mode['mode_name'].indexOf('autosized') > -1) {
console.log("autosized");
var selectors = "." + mode['mode_name'] + " .videoCube .video-label-box";
}
else { // not autosize and not text-links
console.log("not autosized");
var selectors = ".trc_elastic ." + mode['mode_name'] + " .video-label-box";
}
var index = oldCustom.indexOf(selectors);
// video-label-box height selector was found
if (index > -1) {
// PART 1 OF CUSTOM
var custom_part1 = oldCustom.substring(0, index);
var temp = oldCustom.substring(index);
temp = temp.substring(0, temp.indexOf('}')+1);
// PART 3 OF CUSTOM
var custom_part3 = oldCustom.substring(index+temp.length);
// working on temp part (custom_part2)
var heightIndex = temp.indexOf('height:');
if (heightIndex > -1) {
var oldHeight = temp.substring(heightIndex+7);
oldHeight = oldHeight.substring(0, oldHeight.indexOf(';'));
temp = temp.replace(oldHeight, " " + ((rows+1)*new_line_height) + ".0px" );
newCustom = custom_part1.concat("\n").concat(temp).concat("\n").concat(custom_part3);
//console.log("newCustom: " + newCustom);
needChange = true;
}
}
else { // video-label-box selector was not found
console.log("video-label-box selector was not found");
}
}
if (newCustom.length === 0) {
console.log("newCustom is NOT DEFINED");
var newCustom = oldCustom;
}
// SET BRANDING LINE-HEIGHT IN CUSTOM-CSS
var selectors = "." + mode['mode_name'] + " .syndicatedItem .branding";
var index = newCustom.indexOf(selectors);
// video-label-box line-height of branding selector was found
if (index > -1) {
// PART 1 OF CUSTOM
var custom_part1 = newCustom.substring(0, index);
var temp = newCustom.substring(index);
temp = temp.substring(0, temp.indexOf('}')+1);
console.log(temp);
// PART 3 OF CUSTOM
var custom_part3 = newCustom.substring(index+temp.length);
// working on temp part (custom_part2)
var heightIndex = temp.indexOf('line-height:');
//console.log(temp);
//console.log(heightIndex);
if (heightIndex > -1) {
var oldHeight = temp.substring(heightIndex+12);
oldHeight = oldHeight.substring(0, oldHeight.indexOf(';'));
temp = temp.replace(oldHeight, " " + new_line_height + ".0px" );
var newCustom = custom_part1.concat("\n").concat(temp).concat("\n").concat(custom_part3);
needChange = true;
}
else
console.log("line-height was NOT found");
}
else
// line-height was not found!
console.log(".syndicatedItem .branding selector was not found");
if (newCustom.length > 0 && needChange) {
commands += "\nclient-properties-new set " + mode['name'] + " default " + mode['mode_name'] + " mode-custom-css " + '\"' + newCustom + '\"' + "\n";
console.log("added new command");
console.log("\nclient-properties-new set " + mode['name'] + " default " + mode['mode_name'] + " mode-custom-css " + '\"' + newCustom + '\"' + "\n");
}
}
} | [
"function setMemesFontSize(){ //not in use font size taken from modal\r\n var meme = getGMeme();\r\n meme.lines.forEach((line ,index,array) => { \r\n line.fontSize = gFontSize;\r\n });\r\n}",
"function createBodyProperties ( objOptions ) {\r\n\t\t\tvar bodyProperties = '<a:bodyPr';\r\n\r\n\t\t\tif ( objOptions && objOptions.bodyProp ) {\r\n\t\t\t\t// Set anchorPoints bottom, center or top:\r\n\t\t\t\tif ( objOptions.bodyProp.anchor ) {\r\n\t\t\t\t\tbodyProperties += ' anchor=\"' + objOptions.bodyProp.anchor + '\"';\r\n\t\t\t\t} // Endif.\r\n\r\n\t\t\t\tif ( objOptions.bodyProp.anchorCtr ) {\r\n\t\t\t\t\tbodyProperties += ' anchorCtr=\"' + objOptions.bodyProp.anchorCtr + '\"';\r\n\t\t\t\t} // Endif.\r\n\r\n\t\t\t\t// Enable or disable textwrapping none or square:\r\n\t\t\t\tif ( objOptions.bodyProp.wrap ) {\r\n\t\t\t\t\tbodyProperties += ' wrap=\"' + objOptions.bodyProp.wrap + '\"';\r\n\r\n\t\t\t\t} else {\r\n\t\t\t\t\tbodyProperties += ' wrap=\"square\"';\r\n\t\t\t\t} // Endif.\r\n\r\n\t\t\t\t// Box margins(padding):\r\n\t\t\t\t// BMK_TODO: I should pass a better value as the auto_val parameter of parseSmartNumber().\r\n\t\t\t\tif ( objOptions.bodyProp.bIns ) {\r\n\t\t\t\t\tbodyProperties += ' bIns=\"' + parseSmartNumber ( objOptions.bodyProp.bIns, 6858000, 369332, 6858000, 10000 ) + '\"';\r\n\t\t\t\t} // Endif.\r\n\r\n\t\t\t\tif ( objOptions.bodyProp.lIns ) {\r\n\t\t\t\t\tbodyProperties += ' lIns=\"' + parseSmartNumber ( objOptions.bodyProp.lIns, 9144000, 2819400, 9144000, 10000 ) + '\"';\r\n\t\t\t\t} // Endif.\r\n\r\n\t\t\t\tif ( objOptions.bodyProp.rIns ) {\r\n\t\t\t\t\tbodyProperties += ' rIns=\"' + parseSmartNumber ( objOptions.bodyProp.rIns, 9144000, 2819400, 9144000, 10000 ) + '\"';\r\n\t\t\t\t} // Endif.\r\n\r\n\t\t\t\tif ( objOptions.bodyProp.tIns ) {\r\n\t\t\t\t\tbodyProperties += ' tIns=\"' + parseSmartNumber ( objOptions.bodyProp.tIns, 6858000, 369332, 6858000, 10000 ) + '\"';\r\n\t\t\t\t} // Endif.\r\n\r\n\t\t\t\tbodyProperties += ' rtlCol=\"0\">';\r\n\r\n\t\t\t\tif ( objOptions.bodyProp.autoFit !== false ) {\r\n\t\t\t\t\tbodyProperties += '<a:spAutoFit/>';\r\n\t\t\t\t} // Endif.\r\n\r\n\t\t\t\tbodyProperties += '</a:bodyPr>';\r\n\r\n\t\t\t// Default:\r\n\t\t\t} else {\r\n\t\t\t\tbodyProperties += ' wrap=\"square\" rtlCol=\"0\"></a:bodyPr>';\r\n\t\t\t} // Endif.\r\n\r\n\t\t\treturn bodyProperties;\r\n\t\t}",
"function createBodyProperties ( objOptions ) {\n\t\tvar bodyProperties = '<a:bodyPr';\n\n\t\tif ( objOptions && objOptions.bodyProp ) {\n\t\t\t// Set anchorPoints bottom, center or top:\n\t\t\tif ( objOptions.bodyProp.anchor ) {\n\t\t\t\tbodyProperties += ' anchor=\"' + objOptions.bodyProp.anchor + '\"';\n\t\t\t} // Endif.\n\n\t\t\tif ( objOptions.bodyProp.anchorCtr ) {\n\t\t\t\tbodyProperties += ' anchorCtr=\"' + objOptions.bodyProp.anchorCtr + '\"';\n\t\t\t} // Endif.\n\n\t\t\t// Enable or disable textwrapping none or square:\n\t\t\tif ( objOptions.bodyProp.wrap ) {\n\t\t\t\tbodyProperties += ' wrap=\"' + objOptions.bodyProp.wrap + '\"';\n\n\t\t\t} else {\n\t\t\t\tbodyProperties += ' wrap=\"square\"';\n\t\t\t} // Endif.\n\n\t\t\t// Box margins(padding):\n\t\t\t// BMK_TODO: I should pass a better value as the auto_val parameter of parseSmartNumber().\n\t\t\tif ( objOptions.bodyProp.bIns ) {\n\t\t\t\tbodyProperties += ' bIns=\"' + parseSmartNumber ( objOptions.bodyProp.bIns, gen_private.type.pptx.pptHeight, 369332, gen_private.type.pptx.pptHeight, 10000 ) + '\"';\n\t\t\t} // Endif.\n\n\t\t\tif ( objOptions.bodyProp.lIns ) {\n\t\t\t\tbodyProperties += ' lIns=\"' + parseSmartNumber ( objOptions.bodyProp.lIns, gen_private.type.pptx.pptWidth, 2819400, gen_private.type.pptx.pptWidth, 10000 ) + '\"';\n\t\t\t} // Endif.\n\n\t\t\tif ( objOptions.bodyProp.rIns ) {\n\t\t\t\tbodyProperties += ' rIns=\"' + parseSmartNumber ( objOptions.bodyProp.rIns, gen_private.type.pptx.pptWidth, 2819400, gen_private.type.pptx.pptWidth, 10000 ) + '\"';\n\t\t\t} // Endif.\n\n\t\t\tif ( objOptions.bodyProp.tIns ) {\n\t\t\t\tbodyProperties += ' tIns=\"' + parseSmartNumber ( objOptions.bodyProp.tIns, gen_private.type.pptx.pptHeight, 369332, gen_private.type.pptx.pptHeight, 10000 ) + '\"';\n\t\t\t} // Endif.\n\n\t\t\tbodyProperties += ' rtlCol=\"0\">';\n\n\t\t\tif ( objOptions.bodyProp.autoFit !== false ) {\n\t\t\t\tbodyProperties += '<a:spAutoFit/>';\n\t\t\t} // Endif.\n\n\t\t\tbodyProperties += '</a:bodyPr>';\n\n\t\t// Default:\n\t\t} else {\n\t\t\tbodyProperties += ' wrap=\"square\" rtlCol=\"0\"></a:bodyPr>';\n\t\t} // Endif.\n\n\t\treturn bodyProperties;\n\t}",
"function createBodyProperties(objOptions) {\n var bodyProperties = '<a:bodyPr'\n\n if (objOptions && objOptions.bodyProp) {\n // Set anchorPoints bottom, center or top:\n if (objOptions.bodyProp.anchor) {\n bodyProperties += ' anchor=\"' + objOptions.bodyProp.anchor + '\"'\n } // Endif.\n\n if (objOptions.bodyProp.anchorCtr) {\n bodyProperties += ' anchorCtr=\"' + objOptions.bodyProp.anchorCtr + '\"'\n } // Endif.\n\n // Enable or disable textwrapping none or square:\n if (objOptions.bodyProp.wrap) {\n bodyProperties += ' wrap=\"' + objOptions.bodyProp.wrap + '\"'\n } else {\n bodyProperties += ' wrap=\"square\"'\n } // Endif.\n\n // Box margins(padding):\n // BMK_TODO: I should pass a better value as the auto_val parameter of parseSmartNumber().\n if (objOptions.bodyProp.bIns) {\n bodyProperties +=\n ' bIns=\"' +\n parseSmartNumber(\n objOptions.bodyProp.bIns,\n gen_private.type.pptx.pptHeight,\n 369332,\n gen_private.type.pptx.pptHeight,\n 10000\n ) +\n '\"'\n } // Endif.\n\n if (objOptions.bodyProp.lIns) {\n bodyProperties +=\n ' lIns=\"' +\n parseSmartNumber(\n objOptions.bodyProp.lIns,\n gen_private.type.pptx.pptWidth,\n 2819400,\n gen_private.type.pptx.pptWidth,\n 10000\n ) +\n '\"'\n } // Endif.\n\n if (objOptions.bodyProp.rIns) {\n bodyProperties +=\n ' rIns=\"' +\n parseSmartNumber(\n objOptions.bodyProp.rIns,\n gen_private.type.pptx.pptWidth,\n 2819400,\n gen_private.type.pptx.pptWidth,\n 10000\n ) +\n '\"'\n } // Endif.\n\n if (objOptions.bodyProp.tIns) {\n bodyProperties +=\n ' tIns=\"' +\n parseSmartNumber(\n objOptions.bodyProp.tIns,\n gen_private.type.pptx.pptHeight,\n 369332,\n gen_private.type.pptx.pptHeight,\n 10000\n ) +\n '\"'\n } // Endif.\n\n bodyProperties += ' rtlCol=\"0\">'\n\n if (objOptions.bodyProp.noAutofit) {\n bodyProperties += '<a:noAutofit/>'\n } else if (\n objOptions.bodyProp.normAutofit &&\n objOptions.bodyProp.normAutofitRed\n ) {\n bodyProperties +=\n '<a:normAutofit fontScale=\"' +\n objOptions.bodyProp.normAutofit +\n '\" lnSpcReduction=\"' +\n objOptions.bodyProp.normAutofitRed +\n '\"/>'\n } else if (objOptions.bodyProp.normAutofit) {\n bodyProperties +=\n '<a:normAutofit fontScale=\"' + objOptions.bodyProp.normAutofit + '\"/>'\n } else if (objOptions.bodyProp.autoFit !== false) {\n bodyProperties += '<a:spAutoFit/>'\n } // Endif.\n\n bodyProperties += '</a:bodyPr>'\n\n // Default:\n } else {\n bodyProperties += ' wrap=\"square\" rtlCol=\"0\"></a:bodyPr>'\n } // Endif.\n\n return bodyProperties\n }",
"getTitleStyles() {\n return {\n color:'black',\n opacity:'0.35',\n fontSize:'40px',\n textAlign:'center',\n fontFamily:'Marmelad',\n }\n }",
"_drawPropertiesWindow(propertiesWindow, graphics) {\n var width = propertiesWindow.width;\n var H1Size = graphics.getH1Size(this.game.getString(\"common/properties\"));\n var H1X = propertiesWindow.x + width/2 - H1Size.width/2;\n var H1Y = propertiesWindow.y + H1Size.height;\n this.remove = H1Y;\n this.divide = H1Size.height + 5;\n \n if(propertiesWindow.getHeight() == 0)\n propertiesWindow.setHeight(H1Y + (H1Size.height + 5)*(propertiesWindow.actor.properties.size + 1) - propertiesWindow.y);\n \n graphics.drawRoundedSquare(propertiesWindow.x, propertiesWindow.y, propertiesWindow.width, propertiesWindow.height, \"#ECE63D\");\n graphics.drawH1(H1X, H1Y, this.game.getString(\"common/properties\"));\n\n var x = H1X;\n var y = H1Y;\n\n propertiesWindow.actor.properties.forEach(function(value, key, map) {\n y += H1Size.height + 5;\n graphics.drawH2(x, y, key + \":\");\n graphics.drawParagraph(x + width/2, y, value);\n });\n }",
"subgraphAttrs() {\n this.command(`color=\"${Colors.groupBorder}\"`);\n this.command(`fontcolor=\"${Colors.groupLabel}\"`);\n }",
"[MUTATIONS.SET_DESCRIPTION_FONT_SIZE] (state, payload) {\n state.currentSlide.description.fontSize = payload\n state.isCurrentSlideDirty = true\n }",
"updated(changedProperties) {\n changedProperties.forEach((oldValue, propName) => {\n if (propName === \"type\" && this[propName] === \"science\") {\n this.icon = \"beaker\";\n this.accentColor = \"green\";\n }\n if (propName === 'type' && this[propName] === 'objective') {\n this.icon = 'lightbulb';\n this.accentColor = \"red\";\n }\n if (propName === 'type' && this[propName] === 'question') {\n this.icon = 'question';\n this.accentColor = \"blue\";\n }\n this.style.setProperty(\"--heading-font-size\", this.fontSize);\n });\n }",
"function makeSpecialTitlesBigger() {\n let specialItems = document.getElementsByClassName('special-title');\n for (let i = 0; i < specialItems.length; i++) {\n specialItems[i].style.fontSize = '2rem';\n }\n }",
"function recalculateProperties() {\n document.getElementById(\"properties\").innerHTML = propertiesOf(relation, kConfig.domainSize, kConfig.relationTypes);\n}",
"changePriceFontSize() {\n this.changeFontSize('price');\n }",
"function calculateFonts() {\n //title font size calculations\n titleFont.fontSize =\n allDimensions.titleBarHeight * titleFont.fontSizeFactor\n\n //bottom font size calculations\n bottomFont.fontSize =\n allDimensions.bottomBarHeight / 3 * bottomFont.fontSizeFactor\n}",
"function setHtmlObjectsProperties(){\n\t\t \n\t\t\tvar optionWidth = g_functions.getCssSizeParam(g_options.gallery_width);\n\t\t\t\n\t\t //set size\t\t\n\t\t var objCss = {\n\t\t\t\t //\"width\":optionWidth,\t\t//make it work within tabs\n\t\t\t\t \"max-width\":optionWidth,\n\t\t\t\t\t\"min-width\":g_functions.getCssSizeParam(g_options.gallery_min_width)\n\t\t\t};\n\t\t \n\t\t if(g_temp.isFreestyleMode == false){\n\t\t\t \n\t\t\t var galleryHeight = g_functions.getCssSizeParam(g_options.gallery_height);\n\t\t\t objCss[\"height\"] = galleryHeight;\n\t\t \n\t\t }else{\n\t\t\t objCss[\"overflow\"] = \"visible\";\t\t\t \n\t\t }\n\t\t \n\t\t //set background color\n\t\t if(g_options.gallery_background_color)\n\t\t\t objCss[\"background-color\"] = g_options.gallery_background_color;\n\t\t \n\t\t \n\t\t g_objWrapper.css(objCss);\n\t\t \n\t}",
"setFont(font)\n{\n this.titleFont = font;\n this.xAxisFont = font;\n this.yAxisFont = font;\n this.xLabelsFont = font;\n this.yLabelsFont = font;\n this.refLineFont = font;\n}",
"set fontSize(value) {}",
"function changeSize(c){\r\n\tfor(var i=0; i < allArticles.length; i++){ allArticles[i].style.fontSize = c; }\r\n}",
"set resizeTextMinSize(value) {}",
"function resizeTitle(fontSize) {\n\t\t\t\t\ttitle.style('font-size', fontSize + 'em');\n\t\t\t\t\towid.svgSetWrappedText(title, titleStr, boundsForText.width, { lineHeight: 1.1 });\t\t\t\t\n\t\t\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
takes ANOTHER FUNCTION as an arg will call the arg function, passing it "world" | function doWorld(aFunction) {
aFunction("world");
} | [
"function doWorld(aFunction) {\n aFunction(\"world\");\n}",
"function makeWorldMain(transition){\n\t// Since its name is being dynamically generated, always ensure your function actually exists\n\tif (typeof(window[function_prepWorld]) === \"function\") {\n\t\tconsole.log(window[function_prepWorld]);\n\t\twindow[function_prepWorld](transition);\n\t}\n\telse if (pages && typeof(pages[function_prepWorld]) === \"function\") {\n\t\tconsole.log(pages[function_prepWorld]);\n\t\tpages[function_prepWorld](transition);\n\t}\n else\n throw(\"Error. Function \" + function_prepWorld + \" does not exist.\");\n}",
"function runFunction(anotherFunction){\r\n anotherFunction();\r\n}",
"function someRunner(anyFunction){ console.log(2+2); \n\tanyFunction(); }",
"function boo(aFunction) {\n aFunction(\"boo\");\n}",
"function exec(func, arg){\n func(arg);\n}",
"function xyz(abc) {\n abc();\n}",
"function demoFunctionPass(str, passFunction) {\n console.log(passFunction(str));\n}",
"function parameterAsFun(func){\nfunc();\n}",
"function fun(echo) {\n //prints hello boo and reference to the function\n console.log(echo);\n}",
"function main(func) {\n // arg is the template function\n //Step 3: Have the function return a function.\n //Append the template argument(s) (a = future arg to be appended)\n return function (a) {\n //STEP 4: Have your new function actually return the template function.\n //Apply the template argument(s) and integrate your new function argument(s)\n return func('hate', 'wild', a);\n };\n}",
"function saySomething(string){\n var words = function(){\n\t alert(string);\n\t };\n words(string)\n}",
"function callWithArgs(fn) {\n\n}",
"function sayHelloToSomeoneElse() {\n console.log(bar.sayHello(strName).toLowerCase());\n }",
"function exec(ctx, name) {\n var context = getContext(ctx, name),\n result;\n if (context) {\n result = context[name].apply(context, Array.prototype.slice.call(arguments, 2));\n } else {\n console.log('no function: ' + name);\n }\n return result;\n }",
"function handleTheThing(num, str, func) {\n console.log(\"handleTheThing\");\n // this will invoke the function that was passed in, passing \"num + str\" as the argument\n func(num + str);\n}",
"spellHitWorldCallback(obj1, obj2) {\n let spell = obj1;\n spell.onHit(obj2);\n spell.onWorldHit(obj2);\n }",
"function hoo(funFoo, funGoo, paramAForFunGoo) {\n // call foo() using variable funFoo\n funFoo()\n\n // call goo() using variables funGoo and the paramAForFunGoo\n funGoo(paramAForFunGoo)\n}",
"function run(func, args){\n console.log(func);\n if(typeof window[func] === 'function')\n window[func](args);\n else {\n (getProp(\n window[func.substr(0, func.indexOf('.'))],\n func.substr(func.indexOf('.') + 1)\n ))(args);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
In order to stay true to the latest spec, RGB values must be clamped between 0 and 255. If we don't do this, weird things happen. | static clampRGB (val) {
if (val < 0) {
return 0
}
if (val > 255) {
return 255
}
return val
} | [
"static clampRGB(val) {\n if (val < 0) { return 0; }\n if (val > 255) { return 255; }\n return val;\n }",
"function constrain_rgb(r, g, b)\n{\n var w;\n\n /* Amount of white needed is w = - min(0, *r, *g, *b) */\n\n w = (0 < r) ? 0 : r;\n w = (w < g) ? w : g;\n w = (w < b) ? w : b;\n w = -w;\n\n /* Add just enough white to make r, g, b all positive. */\n\n if (w > 0) {\n r += w; g += w; b += w;\n /*return 1;*/ /* Colour modified to fit RGB gamut */\n }\n\n return [r,g,b]; /* Colour within RGB gamut */\n}",
"function checkRGBBoundary(val) {\n\t\tif (val < 0) {\n\t\t\treturn 0;\n\t\t} else if (val > 255) {\n\t\t\treturn 255;\n\t\t} else {\n\t\t\treturn val;\n\t\t}\n\t}",
"function colorValLimit(color) {\n if (color >= 255) {\n color = 255;\n }\n\n if (color <= 0) {\n color = 0;\n }\n\n return Math.round(color);\n}",
"function checkBounds(value) { return ( value >= 0 && value <= 255 ) }",
"validateColorRange(value) {\n const that = this.context;\n\n return Math.min(Math.max(value, that.min), that.max);\n }",
"function clamp(r)\n{\n\t r[3] &= 15;\n r[7] &= 15;\n r[11] &= 15;\n r[15] &= 15;\n r[4] &= 252;\n r[8] &= 252;\n r[12] &= 252;\n return r;\n}",
"function fixRgbNull(event) {\n if (!event.target.value || event.target.value < 0) {\n event.target.value = 0;\n return event.target.value;\n }\n}",
"function correctRGB(color) {\n return {\n r: (0,_clamp__WEBPACK_IMPORTED_MODULE_0__.clamp)(color.r, _consts__WEBPACK_IMPORTED_MODULE_1__.MAX_COLOR_RGB),\n g: (0,_clamp__WEBPACK_IMPORTED_MODULE_0__.clamp)(color.g, _consts__WEBPACK_IMPORTED_MODULE_1__.MAX_COLOR_RGB),\n b: (0,_clamp__WEBPACK_IMPORTED_MODULE_0__.clamp)(color.b, _consts__WEBPACK_IMPORTED_MODULE_1__.MAX_COLOR_RGB),\n a: typeof color.a === 'number' ? (0,_clamp__WEBPACK_IMPORTED_MODULE_0__.clamp)(color.a, _consts__WEBPACK_IMPORTED_MODULE_1__.MAX_COLOR_ALPHA) : color.a,\n };\n}",
"function clamp(val) {\n return val < 0 ? 0 : (val > 1 ? 1 : val);\n}",
"fixColor() {\n if ( this.r < 0 )\n this.r = 0;\n if ( this.g < 0 )\n this.g = 0;\n if ( this.b < 0 )\n this.b = 0;\n if ( this.r > 255 )\n this.r = 255;\n if ( this.g > 255 )\n this.g = 255;\n if ( this.b > 255 )\n this.b = 255;\n }",
"function correctRGB(color) {\n return {\n r: Object(_clamp__WEBPACK_IMPORTED_MODULE_1__[\"clamp\"])(color.r, _consts__WEBPACK_IMPORTED_MODULE_0__[\"MAX_COLOR_RGB\"]),\n g: Object(_clamp__WEBPACK_IMPORTED_MODULE_1__[\"clamp\"])(color.g, _consts__WEBPACK_IMPORTED_MODULE_0__[\"MAX_COLOR_RGB\"]),\n b: Object(_clamp__WEBPACK_IMPORTED_MODULE_1__[\"clamp\"])(color.b, _consts__WEBPACK_IMPORTED_MODULE_0__[\"MAX_COLOR_RGB\"]),\n a: typeof color.a === 'number' ? Object(_clamp__WEBPACK_IMPORTED_MODULE_1__[\"clamp\"])(color.a, _consts__WEBPACK_IMPORTED_MODULE_0__[\"MAX_COLOR_ALPHA\"]) : color.a,\n };\n}",
"function clamp(value){return $window.Math.max(0,$window.Math.min(value||0,100));}",
"clipped() {\n \t const { r, g, b } = this;\n \t return !(0 <= r && r <= 255 && (0 <= g && g <= 255) && (0 <= b && b <= 255));\n \t }",
"validateColorRange(value) {\n const that = this.context;\n\n if (that._wordLengthNumber < 64) {\n return super.validateColorRange(value);\n }\n\n if (that.mode === 'numeric') {\n value = new JQX.Utilities.BigNumber(value);\n }\n else {\n value = JQX.Utilities.DateTime.validateDate(value);\n value = value.getTimeStamp();\n }\n\n const bigMin = new JQX.Utilities.BigNumber(that.min),\n bigMax = new JQX.Utilities.BigNumber(that.max);\n\n if (value.compare(bigMin) === -1) {\n value = bigMin;\n }\n\n if (value.compare(bigMax) === 1) {\n value = bigMax;\n }\n\n return value;\n }",
"constructor(red, green, blue) {\n this.red = math_1.clamp(red, 0, 1);\n this.green = math_1.clamp(green, 0, 1);\n this.blue = math_1.clamp(blue, 0, 1);\n }",
"normalize(value) {\n let r2, g2, b2, a2;\n if ((typeof value == \"number\" || value instanceof Number) && value >= 0 && value <= 16777215) {\n const int = value;\n r2 = (int >> 16 & 255) / 255, g2 = (int >> 8 & 255) / 255, b2 = (int & 255) / 255, a2 = 1;\n } else if ((Array.isArray(value) || value instanceof Float32Array) && value.length >= 3 && value.length <= 4)\n value = this._clamp(value), [r2, g2, b2, a2 = 1] = value;\n else if ((value instanceof Uint8Array || value instanceof Uint8ClampedArray) && value.length >= 3 && value.length <= 4)\n value = this._clamp(value, 0, 255), [r2, g2, b2, a2 = 255] = value, r2 /= 255, g2 /= 255, b2 /= 255, a2 /= 255;\n else if (typeof value == \"string\" || typeof value == \"object\") {\n if (typeof value == \"string\") {\n const match = _Color2.HEX_PATTERN.exec(value);\n match && (value = `#${match[2]}`);\n }\n const color = w(value);\n color.isValid() && ({ r: r2, g: g2, b: b2, a: a2 } = color.rgba, r2 /= 255, g2 /= 255, b2 /= 255);\n }\n if (r2 !== void 0)\n this._components[0] = r2, this._components[1] = g2, this._components[2] = b2, this._components[3] = a2, this.refreshInt();\n else\n throw new Error(`Unable to convert color ${value}`);\n }",
"adjustHighAndLow() {\n if (this.red + this.green > 510 - MAX_DATABITS) {\n this.red = 255 - (MAX_DATABITS >>> 1)\n this.green = 255 - (MAX_DATABITS - (MAX_DATABITS >>> 1))\n } else if (this.red + this.green < MAX_DATABITS) {\n this.red = MAX_DATABITS >>> 1\n this.green = MAX_DATABITS - (MAX_DATABITS >>> 1)\n }\n }",
"function clip(value) {\n return Math.min(255, Math.max(0, value));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process compensation tiles for any bonus tiles received during the initial deal. Not that this may also include _new_ bonus tiles, which need to be moved out and compensated for again, handled in 'checkDealBonus'. | processDealBonusTiles(tiles) {
this.tiles = this.tiles.concat(tiles);
this.checkDealBonus();
} | [
"checkDealBonus() {\n var bonus = this.tiles.map(v => parseInt(v)).filter(t => t >= Constants.PLAYTILES);\n if (bonus.length > 0) {\n this.bonus = this.bonus.concat(bonus);\n this.tiles = this.tiles.map(v => parseInt(v)).filter(t => t < Constants.PLAYTILES);\n this.log('requesting compensation for bonus tiles ${bonus}');\n }\n this.connector.publish('deal-bonus-request', { tiles: this.bonus });\n }",
"processUpTiles() {\n\t\t// Is the maximum number of up tiles needed for a match reached yet?\n\t\tif (this.maxUpTilesNeededForMatchReached) {\n\t\t\tif (this.upTilesAreMatching()) {\n\t\t\t\tthis.processMatch()\n\t\t\t}\n\t\t}\n\t\tif (this.maxUpTilesNeededForMatchExceeded) {\n\t\t\tthis.processMismatch() // Old tiles still lying around, so they were mismatched.\n\t\t}\n\t}",
"processMismatch() {\n\t\tfor (let remaining = this.upTiles.length - 1; remaining > 0; remaining--) {\n\t\t\tthis.upTiles.shift().changeToDown()\n\t\t}\n\t}",
"takePickup(currentPlayer, landedCell) {\n if (landedCell.classList.contains('pickup-attack')) {\n landedCell.classList.remove('pickup-attack');\n this.players[currentPlayer].attack = this.pickups[1].effect;\n\n this.getPlayerDashboard(currentPlayer)\n .querySelector('#attack')\n .classList.add('updateStats');\n setTimeout(() => {\n this.getPlayerDashboard(currentPlayer)\n .querySelector('#attack')\n .classList.remove('updateStats');\n }, 1000);\n this.updateStats();\n\n } else if (landedCell.classList.contains('pickup-defense')) {\n landedCell.classList.remove('pickup-defense');\n this.players[currentPlayer].shield += this.pickups[0].effect;\n\n this.getPlayerDashboard(currentPlayer)\n .querySelector('#shield')\n .classList.add('updateStats');\n setTimeout(() => {\n this.getPlayerDashboard(currentPlayer)\n .querySelector('#shield')\n .classList.remove('updateStats');\n }, 1000);\n this.updateStats();\n\n } else if (landedCell.classList.contains('pickup-health')) {\n landedCell.classList.remove('pickup-health');\n this.players[currentPlayer].health += this.pickups[2].effect;\n this.getPlayerDashboard(currentPlayer)\n .querySelector('#health')\n .classList.add('updateStats');\n setTimeout(() => {\n this.getPlayerDashboard(currentPlayer)\n .querySelector('#health')\n .classList.remove('updateStats');\n }, 1000);\n this.updateStats();\n\n } else if (landedCell.classList.contains('pickup-attack-super')) {\n landedCell.classList.remove('pickup-attack-super');\n this.players[currentPlayer].attack = this.pickups[3].effect;\n\n this.getPlayerDashboard(currentPlayer)\n .querySelector('#attack')\n .classList.add('updateStats');\n setTimeout(() => {\n this.getPlayerDashboard(currentPlayer)\n .querySelector('#attack')\n .classList.remove('updateStats');\n }, 1000);\n this.updateStats();\n\n } else if (landedCell.classList.contains('pickup-speed')) {\n landedCell.classList.remove('pickup-speed');\n this.players[currentPlayer].speed = this.pickups[4].effect;\n }\n }",
"processFrame(){\n\t\tlet bulletActions = {};\n\t\t// collision map before moving\n\t\tthis.applyTankActions();\n\t\tObject.map(this.tanks, (tank, id) => {\n\t\t\tlet collisionMap = this.generateCollisionMap(id, false);\n\t\t\tlet didCollide = this.checkTankCollisions(tank, collisionMap);\n\n\t\t\tif(didCollide) {\n\t\t\t\tthis.tanks[id].revertAction(this.currentTankActions[id]);\n\t\t\t\tdelete this.currentTankActions[id];\n\t\t\t}\n\t\t});\n\n\t\t// update collision map\n\t\tbulletActions = this.applyBulletActions();\n\t\tObject.map(this.bullets, (bullet, id) => {\n\t\t\t// bullet can be destroyed by another bullet\n\t\t\tif(!bullet)\n\t\t\t\treturn;\n\n\t\t\tlet collisionMap = this.generateCollisionMap(id, true);\n\t\t\tlet collision = this.checkBulletCollisions(bullet, collisionMap);\n\n\t\t\tif(collision) {\n\t\t\t\tif(this.tanks[collision]) {\n\t\t\t\t\tlet damage = this.tanks[bullet.tankID].stats.damage;\n\t\t\t\t\tthis.tanks[collision].takeDamage(damage);\n\t\t\t\t\tthis.currentTankActions[collision].health = this.tanks[collision].stats.health;\n\t\t\t\t}\n\n\t\t\t\tif(this.bullets[collision]) {\n\t\t\t\t\tbulletActions[collision] = {\n\t\t\t\t\t\ttype: \"destroy\",\n\t\t\t\t\t\tid: collision\n\t\t\t\t\t};\n\t\t\t\t\tdelete this.bullets[collision];\n\t\t\t\t}\n\t\t\t\tbulletActions[id] = {\n\t\t\t\t\ttype: \"destroy\",\n\t\t\t\t\tid: id\n\t\t\t\t};\n\n\t\t\t\tdelete this.bullets[id];\n\t\t\t}\n\t\t});\n\n\t\tlet actions = Object.values(this.currentTankActions);\n\t\tfor(let bulletAction of Object.values(bulletActions)) {\n\t\t\tactions.push(bulletAction);\n\t\t}\n\n\t\t// Show some debug output in the server console, but ignore spamming (noop actions)\n\t\tthis.frame++;\n\t\t// console.log(\"----- Frame: \"+ this.frame +\" ---------\");\n\t\t// for(let action of actions){\n\t\t// \tif(action.type != \"noop\")\n\t\t// \t\tconsole.log(action);\n\t\t// }\n\n\t\tthis.currentTankActions = {};\n\t\treturn actions;\n\t}",
"handleTentacleCollision(ship, stackedTentacle) {\n // variables for easier reading\n var shipTop = ship.y;\n var shipRight = ship.x + ship.width;\n var shipLeft = ship.x;\n\n var stackedTentacleLeft = stackedTentacle.x;\n var stackedTentacleRight = stackedTentacle.x + stackedTentacle.width;\n var stackedTentacleTop = stackedTentacle.y;\n\n // checks in variables for easier reading\n var crossTentacleFromLeft =\n shipRight > stackedTentacleLeft && shipRight < stackedTentacleRight;\n var crossTentacleFromRight =\n shipLeft < stackedTentacleRight && shipLeft > stackedTentacleLeft;\n\n // below 'if' is to check stacked tentacles only for the the height each ship is moving in\n // +/- 30 is to consider small discrepancies in the heigth\n if (\n shipTop < stackedTentacleTop + 30 &&\n shipTop > stackedTentacleTop - 30\n ) {\n // if (shipTop === stackedTentacleTop) {\n\n // collision check\n if (crossTentacleFromLeft) {\n ship.direction = ship.direction * -1;\n } else if (crossTentacleFromRight) {\n ship.direction = ship.direction * -1;\n }\n }\n }",
"handleCollTile(obj, tileRow, tileCol) {\n let tileCollValue = this.collisionMap[tileRow][tileCol];\n let tileX = tileCol * this.tileSize;\n let tileY = tileRow * this.tileSize;\n\n switch(tileCollValue) {\n \n case 1: return this.handleCollTop (obj, tileY );\n case 2: return this.handleCollRight (obj, tileX + this.tileSize );\n case 3: return (this.handleCollTop (obj, tileY) ||\n this.handleCollRight (obj, tileX + this.tileSize) );\n case 4: return this.handleCollBottom (obj, tileY + this.tileSize );\n case 5: return (this.handleCollTop (obj, tileY) ||\n this.handleCollBottom (obj, tileY + this.tileSize) );\n case 6: return (this.handleCollRight (obj, tileX + this.tileSize) ||\n this.handleCollBottom (obj, tileY + this.tileSize) );\n case 7: return (this.handleCollTop (obj, tileY) ||\n this.handleCollBottom (obj, tileY + this.tileSize) ||\n this.handleCollRight (obj, tileX + this.tileSize) );\n case 8: return this.handleCollLeft (obj, tileX );\n case 9: return (this.handleCollTop (obj, tileY) ||\n this.handleCollLeft (obj, tileX) );\n case 10: return (this.handleCollLeft (obj, tileX) ||\n this.handleCollRight (obj, tileX + this.tileSize) );\n case 11: return (this.handleCollTop (obj, tileY) ||\n this.handleCollLeft (obj, tileX) ||\n this.handleCollRight (obj, tileX + this.tileSize) );\n case 12: return (this.handleCollBottom (obj, tileY + this.tileSize) ||\n this.handleCollLeft (obj, tileX) );\n case 13: return (this.handleCollTop (obj, tileY) ||\n this.handleCollBottom (obj, tileY + this.tileSize) ||\n this.handleCollLeft (obj, tileX) );\n case 14: return (this.handleCollBottom (obj, tileY + this.tileSize) ||\n this.handleCollLeft (obj, tileX) ||\n this.handleCollRight (obj, tileX + this.tileSize) );\n case 15: return (this.handleCollTop (obj, tileY) ||\n this.handleCollBottom (obj, tileY + this.tileSize) ||\n this.handleCollLeft (obj, tileX) ||\n this.handleCollRight (obj, tileX + this.tileSize) );\n default: return false; // Fail-safe, should never happen.\n \n }\n }",
"processDamage() {\n\t\tvar action = this.nextAction;\n\t\tvar reaction = this.target.nextAction;\n\t\tgame.actionData[action].actionEffect(this, this.target);\n\t\tgame.actionData[reaction].reactionEffect(this.target, this);\n\t\tthis.target.checkDeath(this);\n\t\tthis.checkDeath(this.target);\n\t}",
"updateInterpreters() {\n // Index of all the finished parallel reactions\n let endingReactions = new Array;\n // Updating blocking hero\n ReactionInterpreter.blockingHero = false;\n let reaction;\n ReactionInterpreter;\n for (reaction of this.reactionInterpreters) {\n if (reaction.currentReaction.blockingHero) {\n ReactionInterpreter.blockingHero = true;\n break;\n }\n }\n // Updating all reactions\n let effectIndex, i, l;\n for (i = 0, l = this.reactionInterpreters.length; i < l; i++) {\n reaction = this.reactionInterpreters[i];\n reaction.update();\n if (reaction.isFinished()) {\n reaction.updateFinish();\n endingReactions.push(i);\n effectIndex = this.reactionInterpretersEffects.indexOf(reaction);\n if (effectIndex !== -1) {\n this.reactionInterpretersEffects.splice(effectIndex, 1);\n }\n }\n // If changed map, STOP\n if (!Scene.Map.current || Manager.Stack.top.loading) {\n break;\n }\n }\n // Deleting finished reactions\n for (i = endingReactions.length - 1; i >= 0; i--) {\n this.reactionInterpreters.splice(endingReactions[i], 1);\n }\n }",
"function afterCombatEffects(battleInfo, charClass, poison, poisonSource, recoil, recoilSource, heal, healSource) {\n\t\"use strict\";\n\n\tvar oldHP = battleInfo[charClass].currHP;\n\tif (battleInfo[charClass].sealData.hasOwnProperty(\"null_dmg\")) {\n\t\tbattleInfo[charClass].currHP = Math.min(oldHP + heal, battleInfo[charClass].hp);\n\n\t\tif (poison > 0) {\n\t\t\tbattleInfo.logMsg += \"<li class='battle-interaction'><span class='\" + charClass + \"'><strong>\" + battleInfo[charClass].name + \"</strong></span> nullifies after-combat damage [\" + poisonSource + \", \" + battleInfo[charClass].seal + \"]. \";\n\t\t\tbattleInfo.logMsg += recoil > 0 ? \"Self-inflicted damage is nullified [\" + recoilSource + \", \" + battleInfo[charClass].seal + \"]. \" : \"\";\n\t\t\tbattleInfo.logMsg += heal > 0 ? \"Health is restored [\" + healSource + \"]. \" : \"\";\n\t\t} else if (recoil > 0) {\n\t\t\tbattleInfo.logMsg += \"<li class='battle-interaction'><span class='\" + charClass + \"'><strong>\" + battleInfo[charClass].name + \"</strong></span> nullifies self-inflicted damage [\" + recoilSource + \", \" + battleInfo[charClass].seal + \"]. \";\n\t\t\tbattleInfo.logMsg += heal > 0 ? \"Health is restored [\" + healSource + \"]. \" : \"\";\n\t\t} else if (heal > 0) {\n\t\t\tbattleInfo.logMsg += \"<li class='battle-interaction'><span class='\" + charClass + \"'><strong>\" + battleInfo[charClass].name + \"</strong></span> recovers HP after combat [\" + healSource + \"]. \";\n\t\t}\n\n\t\tif (heal > 0) {\n\t\t\tbattleInfo.logMsg += \"<span class='dmg'><strong>\" + heal.toString() + \" health restored.</strong></span><br><span class='\" + charClass + \"'><strong>\" + battleInfo[charClass].name + \" HP:</strong> \" + oldHP.toString() + \" → \" + battleInfo[charClass].currHP.toString() + \"</span></li>\";\n\t\t} else if (poison + recoil > 0) {\n\t\t\tbattleInfo.logMsg += \"<span class='dmg'><strong>0 damage dealt.</strong></span><br><span class='\" + charClass + \"'><strong>\" + battleInfo[charClass].name + \" HP:</strong> \" + oldHP.toString() + \" → \" + battleInfo[charClass].currHP.toString() + \"</span></li>\";\n\t\t}\n\t} else {\n\t\tvar opponentClass = (charClass === \"attacker\") ? \"defender\" : \"attacker\";\n\t\tif (poison > 0 && (poison + recoil > heal)) {\n\t\t\tbattleInfo[charClass].currHP = Math.max(oldHP - poison - recoil + heal, 1);\n\t\t\tbattleInfo[opponentClass].damageDealt += poison - heal;\n\t\t\tbattleInfo.logMsg += \"<li class='battle-interaction'><span class='\" + opponentClass + \"'><strong>\" + battleInfo[opponentClass].name + \"</strong></span> inflicts after-combat damage [\" + poisonSource + \"]. \";\n\t\t\tbattleInfo.logMsg += (recoil > 0) ? \"Oppenent takes additional after-combat damage [\" + recoilSource + \"]. \" : \"\";\n\t\t\tbattleInfo.logMsg += (heal > 0) ? \"Oppenent reduces damage taken due to healing effect [\" + healSource + \"]. \" : \"\";\n\t\t\tbattleInfo.logMsg += \"<span class='dmg'><strong>\" + (poison + recoil - heal).toString() + \" damage dealt.</strong></span><br><span class='\" + charClass + \"'><strong>\" + battleInfo[charClass].name + \" HP:</strong> \" + oldHP.toString() + \" → \" + battleInfo[charClass].currHP.toString() + \"</span></li>\";\n\t\t} else if (recoil > 0 && recoil > heal) {\n\t\t\tbattleInfo[charClass].currHP = Math.max(oldHP - recoil + heal, 1);\n\t\t\tbattleInfo.logMsg += \"<li class='battle-interaction'><span class='\" + charClass + \"'><strong>\" + battleInfo[charClass].name + \"</strong></span> takes damage after combat [\" + recoilSource + \"]. \";\n\t\t\tbattleInfo.logMsg += (heal > 0) ? \"Damage taken is reduced due to healing effect [\" + healSource + \"]. \" : \"\";\n\t\t\tbattleInfo.logMsg += \"<span class='dmg'><strong>\" + (recoil - heal).toString() + \" damage dealt.</strong></span><br><span class='\" + charClass + \"'><strong>\" + battleInfo[charClass].name + \" HP:</strong> \" + oldHP.toString() + \" → \" + battleInfo[charClass].currHP.toString() + \"</span></li>\";\n\t\t} else if (heal > 0) {\n\t\t\tbattleInfo[charClass].currHP = Math.min(oldHP + heal - poison - recoil, battleInfo[charClass].hp);\n\t\t\tbattleInfo.logMsg += \"<li class='battle-interaction'><span class='\" + charClass + \"'><strong>\" + battleInfo[charClass].name + \"</strong></span> recovers HP after combat [\" + healSource + \"]. \";\n\t\t\tbattleInfo.logMsg += (poison > 0) ? \"Opponent reduces health gained by inflicting after combat damage [\" + poisonSource + \"]. \" : \"\";\n\t\t\tbattleInfo.logMsg += (recoil > 0) ? \"Health recovery reduced due to self-inflicted damage [\" + recoilSource + \"]. \" : \"\";\n\t\t\tbattleInfo.logMsg += \"<span class='dmg'><strong>\" + (heal - poison - recoil).toString() + \" health restored.</strong></span><br><span class='\" + charClass + \"'><strong>\" + battleInfo[charClass].name + \" HP:</strong> \" + oldHP.toString() + \" → \" + battleInfo[charClass].currHP.toString() + \"</span></li>\";\n\t\t}\n\t}\n\n\treturn battleInfo;\n}",
"function calculateBonus() {\r\n \r\n var pos = $( \".testDivblue\" ).eq(2);\r\n var plate = $( \"#stats\" ).parent();\r\n var currentLocation = plate.find( \"a[href^='region']\" ).attr( \"href\" ).split( \"?id=\" );\r\n if( currentLocation.length > 1 ) { currentLocation = currentLocation[1] }\r\n \r\n var divBattleLocation = $( \".testDivwhite\" ).find( \"a[href^='region']\" );\r\n if ( divBattleLocation.length ) {\r\n \tvar battleLocation = divBattleLocation.attr( \"href\" ).split( \"?id=\" );\r\n \tif( battleLocation.length > 1 ) { battleLocation = battleLocation[1] }\r\n\t\t\t\t}\r\n \r\n var bonusMU = 0;\r\n var muSide = \"\";\r\n if( GetValue( \"MUSavedBattle\" ) ) {\r\n muSide = GetValue( \"MUSavedBattle\" ).split( \"?id=\" );\r\n if( muSide.length > 1 ) { muSide = muSide[1] }\r\n }\r\n \r\n var battleID = getUrlVars()[ \"id\" ];\r\n \r\n var products = $( \".productList\" );\r\n var numberLocation = 0;\r\n var bonusSD = 0;\r\n // Get if SD is on battle\r\n if( products.length > 0 ) {\r\n products.find( \"img\" ).each( function() {\r\n if( $(this).attr( \"src\" ) == IMGDS ) {\r\n var str = $(this).next().attr( \"src\" );\r\n str = str.replace( IMGQUALITY, \"\" ).substring(0, 1);\r\n bonusSD = parseInt( str ) * 5;\r\n }\r\n });\r\n }\r\n var divBattleLocation = $( \".testDivwhite\" ).find( \"a[href^='region']\" );\r\n var isRW = (divBattleLocation.parent().text().indexOf( \"Resistance war\", 0 ) > -1);\r\n if( isRW ) {\r\n \r\n if( currentLocation == battleLocation ) { numberLocation = 20; }\r\n \r\n var leftMU = 0;\r\n var rightMU = 0;\r\n var sides = pos.find( \".bigFlag\" );\r\n if( battleID == muSide ) { // Correct battle\r\n if( sides.length == 2 ) {\r\n // Left defender\r\n if( sides.eq(0).attr( \"src\" ) == GetValue( \"MUSide\" ) ) {\r\n leftMU = GetValue( \"MURank\" );\r\n \r\n } else if( sides.eq(1).attr( \"src\" ) == GetValue( \"MUSide\" ) ) {\r\n rightMU = GetValue( \"MURank\" );\r\n }\r\n }\r\n }\r\n \r\n var leftBlock = createBlockBonus( numberLocation, leftMU, bonusSD );\r\n leftBlock.attr( \"id\", \"leftBlockBonus\" );\r\n leftBlock.css({ \"margin-top\" : \"3px\", \"margin-left\" : \"2px\" });\r\n leftBlock.insertBefore( pos );\r\n \r\n // Only defensive SD\r\n var rightBlock = createBlockBonus( numberLocation, rightMU, 0 );\r\n rightBlock.attr( \"id\", \"rightBlockBonus\" );\r\n rightBlock.css({ \"margin-top\" : \"3px\", \"margin-left\" : (pos.width()-14)+\"px\" });\r\n rightBlock.insertBefore( pos );\r\n \r\n } else {\r\n \r\n var yourSide = pos.find( \".bigFlag\" ).attr( \"src\" );\r\n var flags = $( \".testDivwhite\" ).find( \".bigFlag\" );\r\n if( flags.length == 2 ) {\r\n var defender = flags.eq(0).attr( \"src\" );\r\n var attacker = flags.eq(1).attr( \"src\" );\r\n \r\n bonusMU = 0;\r\n if( yourSide == attacker ) {\r\n if( battleID == muSide ) {\r\n if( yourSide == GetValue( \"MUSide\" ) ) { bonusMU = GetValue( \"MURank\" ); }\r\n }\t\r\n \r\n var neighbours = getRegionAPI( battleLocation, currentLocation );\r\n numberLocation = (neighbours.indexOf( parseInt(currentLocation) ) != -1) ? 20 : 0;\r\n \r\n var rightBlock = createBlockBonus( numberLocation, bonusMU, 0 );\r\n rightBlock.attr( \"id\", \"rightBlockBonus\" );\r\n rightBlock.css({ \"margin-top\" : \"3px\", \"margin-left\" : (pos.width()-14)+\"px\" });\r\n rightBlock.insertBefore( pos );\r\n \r\n } else if( yourSide == defender ) {\r\n if( battleID == muSide ) {\r\n if( yourSide == GetValue( \"MUSide\" ) ) { bonusMU = GetValue( \"MURank\" ); }\r\n }\r\n if( currentLocation == battleLocation ) { numberLocation = 20; }\r\n \r\n var leftBlock = createBlockBonus( numberLocation, bonusMU, bonusSD );\r\n leftBlock.attr( \"id\", \"leftBlockBonus\" );\r\n leftBlock.css({ \"margin-top\" : \"3px\", \"margin-left\" : \"2px\" });\r\n leftBlock.insertBefore( pos );\r\n }\r\n }\r\n }\r\n }",
"function prepareSitThenSit() {\n // Set the value of head to hips distance\n // If avatar deviates outside of the minimum and maximum, the avatar will pop out of the chair\n setHeadToHipsDistance();\n calculateSeatCenterPositionForPinningAvatarHips();\n\n sitDownAndPinAvatar();\n }",
"function swapBonusClasses(r1, c1, r2, c2) {\n // the actual swapping function, do the code gets DRYer\n function swapElementsAndClasses(e1, e2) {\n const tempElemClass = $(elem1).hasClass(\"bonus\") ? \"bonus\" : \"\",\n tempElemClone = $(elem1).children();\n\n $(elem1)\n .removeClass(\"bonus\")\n .addClass($(elem2).hasClass(\"bonus\") ? \"bonus\" : \"\")\n .empty()\n .append($(elem2)\n .children());\n\n $(elem2)\n .removeClass(\"bonus\")\n .addClass(tempElemClass)\n .empty()\n .append(tempElemClone);\n\n } // end of swapElementsAndClasses\n\n const elem1 = $(`#r${r1}c${c1}-pic`),\n elem2 = $(`#r${r2}c${c2}-pic`),\n elemHasBonus = (el) => el.hasClass(\"bonus\");\n\n // get out of function if NONE has BONUS or DIAMOND\n if (!elemHasBonus(elem1) && !elemHasBonus(elem2) &&\n app.board[r1][c1] !== \"*\" && app.board[r2][c2] !== \"*\") return void (0);\n\n\n // BOTH DIAMONDS\n // two diamonds clear all the fruits, and get extreme points \n if (app.board[r1][c1] === \"*\" && app.board[r2][c2] === \"*\") {\n const matches = [];\n app.board.map((row, rowInd) => {\n row.forEach((cell, cellInd) => {\n // clear cell if fruit\n if (\"123456789\".split(\"\").some(fr => fr === cell)) {\n // add explosion animation to element\n $(`r${rowInd}c${cellInd}-pic`).addClass(\"explosion\");\n\n // fill up matches with all the fruits available on board\n matches.push(\n {\n \"patternName\": \"DD\",\n \"sample\": app.board[rowInd][cellInd],\n \"coords\": [[rowInd, cellInd]]\n } // end of match obj\n ); // end of push\n\n app.game_matches = matches;\n app.board[rowInd][cellInd] = \"X\";\n $(`#r${rowInd}c${cellInd}-pic`).addClass(\"explosion\");\n } // end of if cell is fruit\n }); // end of cell iteration\n }); // end of forEach row\n\n // distroy diamonds\n app.board[r1][c1] = app.board[r2][c2] = \"X\";\n\n animateExplosions(matches);\n return true; // escape out of function\n } // end of if both diamonds\n\n // if ONE is DIAMOND\n // explose all fruits the same type it was swapped with\n if (app.board[r1][c1] === \"*\" || app.board[r2][c2] === \"*\") {\n // get the type of the fruit, which of the two is unknown though\n const fruit = app.board[r1][c1] === \"*\" ? app.board[r2][c2] : app.board[r1][c1],\n matches = [];\n\n // if the element being swapped with diamond is a fruit explose, else return\n if (\"123456789\".split(\"\").some(fr => fr === fruit)) {\n app.board.forEach((row, rowInd) => {\n row.forEach((cell, cellInd) => {\n if (cell === fruit) {\n // add explosion animation to element\n $(`r${rowInd}c${cellInd}-pic`).addClass(\"explosion\");\n\n // fill up the matches with the corrisponding fruit\n matches.push(\n {\n \"patternName\": \"D\",\n \"sample\": app.board[rowInd][cellInd],\n \"coords\": [[rowInd, cellInd]]\n } // end of match obj\n ); // end of matches push\n\n app.game_matches = matches;\n app.board[rowInd][cellInd] = \"X\";\n $(`#r${rowInd}c${cellInd}-pic`).addClass(\"explosion\");\n } // end of if cell the fruit to be destroyed\n }); // end of cell iteration\n }); // end of row iteration\n\n // destroy the diamond, we don't know which one is diamond\n app.board[r1][c1] === \"*\" ? app.board[r1][c1] = \"X\" : app.board[r2][c2] = \"X\";\n animateExplosions(matches);\n return true; // escape out of function\n } // end of if the one being swapped is a fruit\n else return void (0);\n } // end of if one is diamond\n\n\n // if BOTH has BONUS, do both elements' explosion\n if (elemHasBonus(elem1) && elemHasBonus(elem2)) {\n swapElementsAndClasses(elem1, elem2);\n // add explosion animation to element\n $(`r${r1}c${c1}-pic`).addClass(\"explosion\");\n $(`r${r2}c${c2}-pic`).addClass(\"explosion\");\n\n // fill matches with the two elements being swapped\n const matches = [\n {\n \"patternName\": \"BB\",\n \"sample\": app.board[r1][c1],\n \"coords\": [[r1, c1]]\n }, // end of match obj1\n {\n \"patternName\": \"BB\",\n \"sample\": app.board[r2][c2],\n \"coords\": [[r2, c2]]\n } // end of match obj2\n ]; // end of matches\n\n app.game_matches = matches;\n app.board[r1][c1] = app.board[r2][c2] = \"X\";\n $(`#r${r1}c${c1}-pic`).addClass(\"explosion\");\n $(`#r${r2}c${c2}-pic`).addClass(\"explosion\");\n animateExplosions(matches);\n return true; // escape out of function\n } // end of both bonus\n\n\n // the remaining option is, if ONE has BONUS swap its classes an children\n // otherwise the execution is already out of this function\n\n swapElementsAndClasses(elem1, elem2);\n } // end of swapBonusClasses",
"survivorAttack() {\n var affectedTiles = []; //An array of tiles affected by the attack.\n var SurvivorTile = this.Survivor.getCurrentTile(); //Survivor's tile.\n var upTile = this.gameBoard[SurvivorTile.getTileX()][SurvivorTile.getTileY() - 1]; //Tile north of survivor.\n var DownTile = this.gameBoard[SurvivorTile.getTileX()][SurvivorTile.getTileY() + 1]; //Tile south of survivor.\n affectedTiles.push(upTile, DownTile); //Add north/south tiles to affected tiles.\n\n //If the survivor is facing right, add the right tile to the array. If not, add the left tile.\n if (this.Survivor.getFacingRight()) {\n var rightTile = this.gameBoard[SurvivorTile.getTileX() + 1][SurvivorTile.getTileY()];\n affectedTiles.push(rightTile);\n } else {\n var leftTile = this.gameBoard[SurvivorTile.getTileX() - 1][SurvivorTile.getTileY()];\n affectedTiles.push(leftTile);\n }\n\n //Have all tiles take damage, if they *can* be damaged.\n for (const t of affectedTiles) {\n t.takeDamage();\n }\n //Have all zombies that may be in those tiles take damage.\n for (const z of this.activeZombies) {\n for (const t of affectedTiles) {\n if (z.getCurrentTile() == t && z.isZombieAlive() === true) {\n this.killZombie(z);\n this.playerScore += 25;\n this.updateUI();\n }\n }\n }\n }",
"discardTile(cleandeal) {\n // wins are automatic for now.\n if (this.rules.checkCoverage(this.tiles, this.bonus, this.revealed)) {\n return this.connector.publish('discard-tile', { tile: Constants.NOTILE, selfdrawn: true });\n }\n var tile = this.ai.determineDiscard();\n this.processTileDiscardChoice(tile);\n }",
"function ProcessEffects () {\n\tfor (var i = 0; i < effectList.length; i++)\n\t{\n\t\tvar effect = effectList[i];\n\t\teffect.delay --;\n\t\tif (effect.delay <= 0)\n\t\t{\n\t\t\teffect.delay = effect.MAX_DELAY;\n\t\t\teffect.imageList.shift();\n\t\t\tif (effect.imageList.length == 0)\n\t\t\t{\n\t\t\t\t//layerList[effect.z].eNeedsUpdate = true;\n\t\t\t\t//layerList[effect.z].effects.splice(layerList[effect.z].effects.indexOf(effect), 1);\n\t\t\t\tvar tile = effect.GetTile();\n\t\t\t\ttile.effects.splice(tile.effects.indexOf(effect), 1);\n\t\t\t\teffectList.splice(i, 1);\n\t\t\t\ti--;\n\t\t\t\t//RenderTile(tile);\n\t\t\t\tDrawTileContent(tile);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tDrawTileContent(effect.GetTile())\n\t\t\t\t//layerList[effect.z].eNeedsUpdate = true;\n\t\t\t}\n\t\t}\n\t}\n\treturn;\n}",
"function latch() {\n\tif (hitChain.length > 0 && nextMove !== '') {\n\t\tvar nextTargetedCell = nextMove;\n\t\tif (pBoard.isAHit(nextTargetedCell)) { // nextTargetedCell is a hit\n\t\t\t$('#p'+nextTargetedCell).addClass('hit');\n\t\t\tpBoard.hitCells.push(nextTargetedCell);\n\t\t\tpBoard.uncheckedCells = pBoard.uncheckedCells.without(nextTargetedCell);\n\t\t\thitChain.unshift(nextTargetedCell);\n\t\t\tnextMove = getNextMoveFromChain();\n\t\t}\n\t\telse { // nextTargetedCell is a miss\n\t\t\t$('#p'+nextTargetedCell).addClass('miss');\n\t\t\tpBoard.uncheckedCells = pBoard.uncheckedCells.without(nextTargetedCell);\n\t\t\tif (hitChain.length > 1) {\n\t\t\t\tnextMove = getNextMoveFromChain();\n\t\t\t}\n\t\t\telse if (hitChain.length === 1) {\n\t\t\t\tvar surroundingCells = getAdjacentCells(hitChain[0]);\n\t\t\t\tif (surroundingCells.length > 0) {\n\t\t\t\t\tnextMove = surroundingCells.getRandomElem();\n\t\t\t\t} else clearTargetingData();\n\t\t\t}\n\t\t}\n\t}\n\telse hunt();\n}",
"processPredator() {\n\n //iterate trough the predator and move & find survivors\n for (var i = 0; i < this.predatorsInfo.length; i++) {\n\n //Look for food\n this.predatorsInfo[i].findSurvivors(this.survivorsInfo);\n\n //check for border colission and change direction\n this.predatorsInfo[i].setDirection(this.predatorsInfo[i].sprite.handleBorderCollition());\n\n let PredatorEating = this.b.hit(\n this.predatorsInfo[i].sprite, this.survivorsInfo.map(a => a.sprite), false, false, false,\n function(collision, dude) {\n let survivor = this.survivorsInfo.find(o => o.uid == dude.uid);\n //survivor.isDead = true;\n\n if (survivor.isHumanControlled && survivor.isCurrentlyControlledByHuman) {\n this.swapControlToChildren(survivor);\n }\n\n this.removeKilledChildren(survivor); //remove son from their parents\n this.killSurvivor(survivor);\n //logger.log(\"world.js - processPredator()\", \"survivor #\" + dude.uid + \" is dead (eaten)\");\n\n //TODO: FIX this, this.survivorsInfo is not discounting\n this.predatorsInfo[i].eat();\n }.bind(this)\n );\n\n //Move (apply direction / angle / speed values)\n this.predatorsInfo[i].move();\n\n }\n }",
"function commitMilitary() {\n\t\tfor (var i = 0; i < nationsArr.length; i++) {\n\t\t\tvar nation = nationsArr[i];\n\t\t\tupdateTotalThreat(nation);\n\n\t\t\t// Commit military based on relative threat.\n\t\t\tfor (var j = 0; j < nation.threats.length; j++) {\n\t\t\t\t// Will be zero if no threat (no border).\n\t\t\t\tnation.committedMilitary[j] = \n\t\t\t\t\tnation.military * nation.threats[j] / nation.totalThreat;\n\t\t\t}\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
lowtech reformatting of perfect HTML | function reformatHtml (html) {
if(!html) return html;
// break up HTML into tags and text
var hh = [],
h = html;
while (h) {
var i = h.indexOf('<');
if (i === -1) {
hh.push(h);
break;
} else if (i > 0) {
hh.push(h.substring(0, i));
h = h.substring(i);
} else {
var j = h.indexOf('>');
hh.push(h.substring(0, j + 1));
h = h.substring(j + 1);
}
}
// combine common elements together
var hhh = [],
k = 0,
len = hh.length;
while (k < len) {
hhk = hh[k];
// text
if (hhk.charAt(0) !== '<' || hhk.substr(0, 2) === '</') {
hhh.push(hhk);
k += 1;
continue;
}
// <li ...><a ...>text</a></li>
if (k < len - 5 && hh[k].substr(0, 3) === '<li' &&
hh[k+1].substr(0, 2) === '<a' && hh[k+2].charAt(0) !== '<' &&
hh[k+3] === '</a>' && hh[k+4] === '</li>') {
hhh.push('~' + hhk + hh[k+1] + hh[k+2] + hh[k+3] + hh[k+4]);
k += 5;
continue;
}
i = hhk.indexOf(' ');
j = hhk.indexOf('>');
var tag = hhk.substr(0, Math.min(i !== -1 ? i : 9999, j !== -1 ? j : 9999)),
endTag = '</' + tag.substr(1) + '>';
// <tag ...>text</tag>
if (k < len - 3 && hh[k+1].charAt(0) !== '<' && hh[k+2] === endTag) {
hhh.push('~' + hhk + hh[k+1] + hh[k+2]);
k += 3;
continue;
}
// <tag ...></tag>
if (k < len - 2 && hh[k+1] === endTag) {
hhh.push('~' + hhk + hh[k+1]);
k += 2;
continue;
}
hhh.push(hhk);
k += 1;
}
// reassemble HTML
var lead = 0,
str = '';
for (k = 0, len = hhh.length; k < len; k += 1) {
var hhk = hhh[k];
if (hhk.charAt(0) === '~') {
str += '\n' + indent(lead + 1) + hhk.substr(1);
} else if (hhk.charAt(0) !== '<') {
str += '\n' + indent(lead) + hhk;
} else if (hhk.substr(0, 2) === '</') {
str += '\n' + indent(lead) + hhk;
lead -= 1;
} else {
lead += 1;
str += '\n' + indent(lead) + hhk;
}
}
return str;
function indent (lead) { return new Array(lead * 3 - 2).join(' '); }
} | [
"function format_html_output() {\r\n var text = String(this);\r\n text = text.tidy_xhtml();\r\n\r\n if (Prototype.Browser.WebKit) {\r\n text = text.replace(/(<div>)+/g, \"\\n\");\r\n text = text.replace(/(<\\/div>)+/g, \"\");\r\n\r\n text = text.replace(/<p>\\s*<\\/p>/g, \"\");\r\n\r\n text = text.replace(/<br \\/>(\\n)*/g, \"\\n\");\r\n } else if (Prototype.Browser.Gecko) {\r\n text = text.replace(/<p>/g, \"\");\r\n text = text.replace(/<\\/p>(\\n)?/g, \"\\n\");\r\n\r\n text = text.replace(/<br \\/>(\\n)*/g, \"\\n\");\r\n } else if (Prototype.Browser.IE || Prototype.Browser.Opera) {\r\n text = text.replace(/<p>( | |\\s)<\\/p>/g, \"<p></p>\");\r\n\r\n text = text.replace(/<br \\/>/g, \"\");\r\n\r\n text = text.replace(/<p>/g, '');\r\n\r\n text = text.replace(/ /g, '');\r\n\r\n text = text.replace(/<\\/p>(\\n)?/g, \"\\n\");\r\n\r\n text = text.gsub(/^<p>/, '');\r\n text = text.gsub(/<\\/p>$/, '');\r\n }\r\n\r\n text = text.gsub(/<b>/, \"<strong>\");\r\n text = text.gsub(/<\\/b>/, \"</strong>\");\r\n\r\n text = text.gsub(/<i>/, \"<em>\");\r\n text = text.gsub(/<\\/i>/, \"</em>\");\r\n\r\n text = text.replace(/\\n\\n+/g, \"</p>\\n\\n<p>\");\r\n\r\n text = text.gsub(/(([^\\n])(\\n))(?=([^\\n]))/, \"#{2}<br />\\n\");\r\n\r\n text = '<p>' + text + '</p>';\r\n\r\n text = text.replace(/<p>\\s*/g, \"<p>\");\r\n text = text.replace(/\\s*<\\/p>/g, \"</p>\");\r\n\r\n var element = Element(\"body\");\r\n element.innerHTML = text;\r\n\r\n if (Prototype.Browser.WebKit || Prototype.Browser.Gecko) {\r\n var replaced;\r\n do {\r\n replaced = false;\r\n element.select('span').each(function(span) {\r\n if (span.hasClassName('Apple-style-span')) {\r\n span.removeClassName('Apple-style-span');\r\n if (span.className == '')\r\n span.removeAttribute('class');\r\n replaced = true;\r\n } else if (span.getStyle('fontWeight') == 'bold') {\r\n span.setStyle({fontWeight: ''});\r\n if (span.style.length == 0)\r\n span.removeAttribute('style');\r\n span.update('<strong>' + span.innerHTML + '</strong>');\r\n replaced = true;\r\n } else if (span.getStyle('fontStyle') == 'italic') {\r\n span.setStyle({fontStyle: ''});\r\n if (span.style.length == 0)\r\n span.removeAttribute('style');\r\n span.update('<em>' + span.innerHTML + '</em>');\r\n replaced = true;\r\n } else if (span.getStyle('textDecoration') == 'underline') {\r\n span.setStyle({textDecoration: ''});\r\n if (span.style.length == 0)\r\n span.removeAttribute('style');\r\n span.update('<u>' + span.innerHTML + '</u>');\r\n replaced = true;\r\n } else if (span.attributes.length == 0) {\r\n span.replace(span.innerHTML);\r\n replaced = true;\r\n }\r\n });\r\n } while (replaced);\r\n\r\n }\r\n\r\n for (var i = 0; i < element.descendants().length; i++) {\r\n var node = element.descendants()[i];\r\n if (node.innerHTML.blank() && node.nodeName != 'BR' && node.id != 'bookmark')\r\n node.remove();\r\n }\r\n\r\n text = element.innerHTML;\r\n text = text.tidy_xhtml();\r\n\r\n text = text.replace(/<br \\/>(\\n)*/g, \"<br />\\n\");\r\n text = text.replace(/<\\/p>\\n<p>/g, \"</p>\\n\\n<p>\");\r\n\r\n text = text.replace(/<p>\\s*<\\/p>/g, \"\");\r\n\r\n text = text.replace(/\\s*$/g, \"\");\r\n\r\n return text;\r\n }",
"function clean_up_html_to_show( t )\n{\n\tif ( t == \"\" || t == 'undefined' )\n\t{\n\t\treturn t;\n\t}\n\t\n\t//-------------------------------\n\t// Sort out BR tags\n\t//-------------------------------\n\t\n\tt = t.replace( /<br>/ig, \"<br />\");\n\t\n\t//-------------------------------\n\t// Remove empty <p> tags\n\t//-------------------------------\n\t\n\tt = t.replace( /<p>(\\s+?)?<\\/p>/ig, \"\");\n\t\n\t//-------------------------------\n\t// HR issues\n\t//-------------------------------\n\t\n\tt = t.replace( /<p><hr \\/><\\/p>/ig , \"<hr />\"); \n\tt = t.replace( /<p> <\\/p><hr \\/><p> <\\/p>/ig, \"<hr />\");\n\t\n\t//-------------------------------\n\t// Attempt to fix some formatting\n\t// issues....\n\t//-------------------------------\n\t\n\tt = t.replace( /<(p|div)([^&]*)>/ig , \"<br /><$1$2><br />\" );\n\tt = t.replace( /<\\/(p|div)([^&]*)>/ig , \"<br /></$1$2><br />\");\n\tt = t.replace( /<br \\/>(?!<\\/td)/ig , \"<br /><br />\" );\n\t\n\t//-------------------------------\n\t// And some table issues...\n\t//-------------------------------\n\t\n\tt = t.replace( /<\\/(td|tr|tbody|table)>/ig , \"</$1><br />\");\n\tt = t.replace( /<(tr|tbody|table(.+?)?)>/ig , \"<$1><br />\" );\n\tt = t.replace( /<(td(.+?)?)>/ig , \" <$1>\" );\n\t\n\t//-------------------------------\n\t// Newlines\n\t//-------------------------------\n\t\n\tt = t.replace( /<p> <\\/p>/ig , \"<br />\");\n\t\n\treturn t;\n}",
"function prepareHTML(html) {\n\n // Clean\n html = html\n .replace(/[ ]{2,}/g, \"\") // Remove multiple spaces\n .replace(/<!--(.|\\s)*?-->/g, \"\") // Replace comments\n .replace(/([\\\\'])/g, \"\\\\$1\") // Replace values with token\n .replace(/[\\r\\t\\n]/g, \" \") // Replace line endings to spaces\n .replace(/{> /g, \"{> \") // Replace {> with {> (for children)\n .replace(/\\\\{/g, \"#lcb#\") // Replace left curly bracket break\n .replace(/\\\\}/g, \"#rcb#\"); // Replace right currly bracket break\n\n // Convert to jQuery\n html = $(html);\n\n // Convert attributes to markup\n convertAttrToMarkup(html, \"go-any\", \"?\");\n convertAttrToMarkup(html, \"go-none\", \"!\");\n convertAttrToMarkup(html, \"go-if\", \"?\");\n convertAttrToMarkup(html, \"go-each\", \"~\");\n convertAttrToMarkup(html, \"go-with\", \"^\");\n\n // Get HTML output\n html = html[0].outerHTML;\n\n // Remove host from href attributes\n // JQuery auto-inserts these values\n var base = location.protocol + \"//\" + location.host + \"/\";\n var regex = new RegExp(\"href=[\\\"|']\" + base, \"g\");\n html = html.replace(regex, \"href=\\\"\");\n\n //Regex Replacements\n html = html\n\t\t\t.replace(/[\\r\\t\\n]/g, \" \") // Replace line endings to spaces\n .replace(/{> /g, \"{> \") // Replace {> with {> (for children)\n .replace(/%7B#/g, \"{#\") // Replace %7B# with {#\n .replace(/\\{\\?\\}/g, \"{? this}\") // Replace {?} with {? this}\n .replace(/\\{\\~\\}/g, \"{~ this}\") // Replace {~} with {~ this}\n .replace(/\\{\\.\\}/g, \"{= this}\") // Replace {.} with {this}\n .replace(/\\{(([^\\/\\*\\?\\$\\^\\*\\.\\+\\-\\!@%&~#:>=]{1})([^{}]*))\\}/g, \"{= $1}\"); // Replace {expression} with {= expression}\n\n return html;\n }",
"function format_html_input() {\r\n var text = String(this);\r\n\r\n var element = Element(\"body\");\r\n element.innerHTML = text;\r\n\r\n if (Prototype.Browser.Gecko || Prototype.Browser.WebKit) {\r\n element.select('strong').each(function(element) {\r\n element.replace('<span style=\"font-weight: bold;\">' + element.innerHTML + '</span>');\r\n });\r\n element.select('em').each(function(element) {\r\n element.replace('<span style=\"font-style: italic;\">' + element.innerHTML + '</span>');\r\n });\r\n element.select('u').each(function(element) {\r\n element.replace('<span style=\"text-decoration: underline;\">' + element.innerHTML + '</span>');\r\n });\r\n }\r\n\r\n if (Prototype.Browser.WebKit)\r\n element.select('span').each(function(span) {\r\n if (span.getStyle('fontWeight') == 'bold')\r\n span.addClassName('Apple-style-span');\r\n\r\n if (span.getStyle('fontStyle') == 'italic')\r\n span.addClassName('Apple-style-span');\r\n\r\n if (span.getStyle('textDecoration') == 'underline')\r\n span.addClassName('Apple-style-span');\r\n });\r\n\r\n text = element.innerHTML;\r\n text = text.tidy_xhtml();\r\n\r\n text = text.replace(/<\\/p>(\\n)*<p>/g, \"\\n\\n\");\r\n\r\n text = text.replace(/(\\n)?<br( \\/)?>(\\n)?/g, \"\\n\");\r\n\r\n text = text.replace(/^<p>/g, '');\r\n text = text.replace(/<\\/p>$/g, '');\r\n\r\n if (Prototype.Browser.Gecko) {\r\n text = text.replace(/\\n/g, \"<br>\");\r\n text = text + '<br>';\r\n } else if (Prototype.Browser.WebKit) {\r\n text = text.replace(/\\n/g, \"</div><div>\");\r\n text = '<div>' + text + '</div>';\r\n text = text.replace(/<div><\\/div>/g, \"<div><br></div>\");\r\n } else if (Prototype.Browser.IE || Prototype.Browser.Opera) {\r\n text = text.replace(/\\n/g, \"</p>\\n<p>\");\r\n text = '<p>' + text + '</p>';\r\n text = text.replace(/<p><\\/p>/g, \"<p> </p>\");\r\n text = text.replace(/(<p> <\\/p>)+$/g, \"\");\r\n }\r\n\r\n return text;\r\n }",
"formatHTML (html) {\n const markup = html.replace(/\\n/g, '<br />')\n return new DOMParser().parseFromString(markup, \"text/html\").documentElement.innerHTML;\n }",
"function prettifyHTML(html) {\n function parse(html, tab = 0) {\n var tab;\n var html = $.parseHTML(html);\n var formatHtml = new String(); \n\n function setTabs () {\n var tabs = new String();\n\n for (i=0; i < tab; i++){\n tabs += ' ';\n }\n return tabs; \n };\n\n\n $.each( html, function( i, el ) {\n if (el.nodeName == '#text') {\n if (($(el).text().trim()).length) {\n formatHtml += setTabs() + $(el).text().trim() + '\\n';\n } \n } else {\n // this condition was an attempt to exclude the contents of <pre> tags from processing but it turns out the innerHTML of the tag \n // is already stripped from the newlines and whitespace.. and I don't really know what to do about it so I'll temporarily\n // just disable the whole prettifying function and won't process the document with it at all (except for the new TOC)\n if (el.nodeName != 'PRE') {\n var innerHTML = $(el).html().trim();\n $(el).html(innerHTML.replace('\\n', '').replace(/ +(?= )/g, ''));\n \n\n if ($(el).children().length) {\n $(el).html('\\n' + parse(innerHTML, (tab + 1)) + setTabs());\n var outerHTML = $(el).prop('outerHTML').trim();\n formatHtml += setTabs() + outerHTML + '\\n'; \n\n } else {\n var outerHTML = $(el).prop('outerHTML').trim();\n formatHtml += setTabs() + outerHTML + '\\n';\n } \n } \n else {\n var innerHTML = el.innerHTML;\n // var outerHTML = $(el).prop('outerHTML');\n formatHtml += innerHTML + '\\n';\n }\n }\n });\n\n return formatHtml;\n }; \n \n return parse(html.replace(/(\\r\\n|\\n|\\r)/gm,\" \").replace(/ +(?= )/g,''));\n}",
"function TML2HTML() {\n \n /* Constants */\n var startww = \"(^|\\\\s|\\\\()\";\n var endww = \"($|(?=[\\\\s\\\\,\\\\.\\\\;\\\\:\\\\!\\\\?\\\\)]))\";\n var PLINGWW =\n new RegExp(startww+\"!([\\\\w*=])\", \"gm\");\n var TWIKIVAR =\n new RegExp(\"^%(<nop(?:result| *\\\\/)?>)?([A-Z0-9_:]+)({.*})?$\", \"\");\n var MARKER =\n new RegExp(\"\\u0001([0-9]+)\\u0001\", \"\");\n var protocol = \"(file|ftp|gopher|https|http|irc|news|nntp|telnet|mailto)\";\n var ISLINK =\n new RegExp(\"^\"+protocol+\":|/\");\n var HEADINGDA =\n new RegExp('^---+(\\\\++|#+)(.*)$', \"m\");\n var HEADINGHT =\n new RegExp('^<h([1-6])>(.+?)</h\\\\1>', \"i\");\n var HEADINGNOTOC =\n new RegExp('(!!+|%NOTOC%)');\n var wikiword = \"[A-Z]+[a-z0-9]+[A-Z]+[a-zA-Z0-9]*\";\n var WIKIWORD =\n new RegExp(wikiword);\n var webname = \"[A-Z]+[A-Za-z0-9_]*(?:(?:[\\\\./][A-Z]+[A-Za-z0-9_]*)+)*\";\n var WEBNAME =\n new RegExp(webname);\n var anchor = \"#[A-Za-z_]+\";\n var ANCHOR =\n new RegExp(anchor);\n var abbrev = \"[A-Z]{3,}s?\\\\b\";\n var ABBREV =\n new RegExp(abbrev);\n var ISWIKILINK =\n new RegExp( \"^(?:(\"+webname+\")\\\\.)?(\"+wikiword+\")(\"+anchor+\")?\");\n var WW =\n new RegExp(startww+\"((?:(\"+webname+\")\\\\.)?(\"+wikiword+\"))\", \"gm\");\n var ITALICODE =\n new RegExp(startww+\"==(\\\\S+?|\\\\S[^\\\\n]*?\\\\S)==\"+endww, \"gm\");\n var BOLDI =\n new RegExp(startww+\"__(\\\\S+?|\\\\S[^\\\\n]*?\\\\S)__\"+endww, \"gm\");\n var CODE =\n new RegExp(startww+\"\\\\=(\\\\S+?|\\\\S[^\\\\n]*?\\\\S)\\\\=\"+endww, \"gm\");\n var ITALIC =\n new RegExp(startww+\"\\\\_(\\\\S+?|\\\\S[^\\\\n]*?\\\\S)\\\\_\"+endww, \"gm\");\n var BOLD =\n new RegExp(startww+\"\\\\*(\\\\S+?|\\\\S[^\\\\n]*?\\\\S)\\\\*\"+endww, \"gm\");\n var NOPWW =\n new RegExp(\"<nop(?: *\\/)?>(\"+wikiword+\"|\"+abbrev+\")\", \"g\");\n var URI =\n new RegExp(\"(^|[-*\\\\s(])(\"+protocol+\":([^\\\\s<>\\\"]+[^\\s*.,!?;:)<]))\");\n\n /*\n * Main entry point, and only external function. 'options' is an object\n * that must provide the following method:\n * getViewUrl(web,topic) -> url (where topic may include an anchor)\n * and may optionally provide\n * expandVarsInURL(url, options) -> url\n * getViewUrl must generate a URL for the given web and topic.\n * expandVarsinURL gives an opportunity for a caller to expand selected\n * Macros embedded in URLs\n */\n this.convert = function(content, options) {\n this.opts = options;\n\n content = content.replace(/\\\\\\n/g, \" \");\n \n content = content.replace(/\\u0000/g, \"!\");\t\n content = content.replace(/\\u0001/g, \"!\");\t\n content = content.replace(/\\u0002/g, \"!\");\t\n \n this.refs = new Array();\n\n // Render TML constructs to tagged HTML\n return this._getRenderedVersion(content);\n };\n \n this._liftOut = function(text) {\n index = '\\u0001' + this.refs.length + '\\u0001';\n this.refs.push(text);\n return index;\n }\n \n this._dropBack = function(text) {\n var match;\n \n while (match = MARKER.exec(text)) {\n var newtext = this.refs[match[1]];\n if (newtext != match[0]) {\n var i = match.index;\n var l = match[0].length;\n text = text.substr(0, match.index) +\n newtext +\n text.substr(match.index + match[0].length);\n }\n MARKER.lastIndex = 0;\n }\n return text;\n };\n \n // Parse twiki variables.\n //for InlineEdit, would like to not nest them, and to surround entire html entities where needed\n this._processTags = function(text) {\n \n var queue = text.split(/%/);\n var stack = new Array();\n var stackTop = '';\n var prev = '';\n \n while (queue.length) {\n var token = queue.shift();\n if (stackTop.substring(-1) == '}') {\n while (stack.length && !TWIKIVAR.match(stackTop)) {\n stackTop = stack.pop() + stackTop;\n }\n }\n \n var match = TWIKIVAR.exec(stackTop);\n if (match) {\n var nop = match[1];\n var args = match[3];\n if (!args)\n args = '';\n // You can always replace the %'s here with a construct e.g.\n // html spans; however be very careful of variables that are\n // used in the context of parameters to HTML tags e.g.\n // <img src=\"%ATTACHURL%...\">\n var tag = '%' + match[2] + args + '%';\n if (nop) {\n nop = nop.replace(/[<>]/g, '');\n tag = \"<span class='TML'\"+nop+\">\"+tag+\"</span>\";\n }\n stackTop = stack.pop() + this._liftOut(tag) + token;\n } else {\n stack.push(stackTop);\n stackTop = prev + token;\n }\n prev = '%';\n }\n // Run out of input. Gather up everything in the stack.\n while (stack.length) {\n stackTop = stack.pop(stack) + stackTop;\n }\n \n return stackTop;\n };\n \n this._makeLink = function(url, text) {\n if (!text || text == '')\n text = url;\n url = this._liftOut(url);\n return \"<a href='\"+url+\"'>\" + text + \"</a>\";\n };\n \n this._expandRef = function(ref) {\n if (this.opts['expandVarsInURL']) {\n var origtxt = this.refs[ref];\n var newtxt = this.opts['expandVarsInURL'](origtxt, this.opts);\n if (newTxt != origTxt)\n return newtxt;\n }\n return '\\u0001'+ref+'\\u0001';\n };\n \n this._expandURL = function(url) {\n if (this.opts['expandVarsInURL'])\n return this.opts['expandVarsInURL'](url, this.opts);\n return url;\n };\n \n this._makeSquab = function(url, text) {\n url = _sg(MARKER, url, function(match) {\n this._expandRef(match[1]);\n }, this);\n \n if (url.test(/[<>\\\"\\x00-\\x1f]/)) {\n // we didn't manage to expand some variables in the url\n // path. Give up.\n // If we can't completely expand the URL, then don't expand\n // *any* of it (hence save)\n return text ? \"[[save][text]]\" : \"[[save]]\";\n }\n \n if (!text) {\n // forced link [[Word]] or [[url]]\n text = url;\n if (url.test(ISLINK)) {\n var wurl = url;\n wurl.replace(/(^|)(.)/g,$2.toUpperCase());\n var match = wurl.exec(ISWEB);\n if (match) {\n url = this.opts['getViewUrl'](match[1], match[2] + match[3]);\n } else {\n url = this.opts['getViewUrl'](null, wurl);\n }\n }\n } else if (match = url.exec(ISWIKILINK)) {\n // Valid wikiword expression\n url = this.optsgetViewUrl(match[1], match[2]) + match[3];\n }\n \n text.replace(WW, \"$1<nop>$2\");\n \n return this._makeLink(url, text);\n };\n \n // Lifted straight out of DevelopBranch Render.pm\n this._getRenderedVersion = function(text, refs) {\n if (!text)\n return '';\n \n this.LIST = new Array();\n this.refs = new Array();\n \n // Initial cleanup\n text = text.replace(/\\r/g, \"\");\n text = text.replace(/^\\n+/, \"\");\n text = text.replace(/\\n+$/, \"\");\n\n var removed = new BlockSafe();\n \n text = removed.takeOut(text, 'verbatim', true);\n\n // Remove PRE to prevent TML interpretation of text inside it\n text = removed.takeOut(text, 'pre', false);\n \n // change !%XXX to %<nop>XXX\n text = text.replace(/!%([A-Za-z_]+(\\{|%))/g, \"%<nop>$1\");\n\n // change <nop>%XXX to %<nopresult>XXX. A nop before th % indicates\n // that the result of the tag expansion is to be nopped\n text = text.replace(/<nop>%(?=[A-Z]+(\\{|%))/g, \"%<nopresult>\");\n \n // Pull comments\n text = _sg(/(<!--.*?-->)/, text,\n function(match) {\n this._liftOut(match[1]);\n }, this);\n \n // Remove TML pseudo-tags so they don't get protected like HTML tags\n text = text.replace(/<(.?(noautolink|nop|nopresult).*?)>/gi,\n \"\\u0001($1)\\u0001\");\n \n // Expand selected TWiki variables in IMG tags so that images appear in the\n // editor as images\n text = _sg(/(<img [^>]*src=)([\\\"\\'])(.*?)\\2/i, text,\n function(match) {\n return match[1]+match[2]+this._expandURL(match[3])+match[2];\n }, this);\n \n // protect HTML tags by pulling them out\n text = _sg(/(<\\/?[a-z]+(\\s[^>]*)?>)/i, text,\n function(match) {\n return this._liftOut(match[1]);\n }, this);\n \n var pseud = new RegExp(\"\\u0001\\((.*?)\\)\\u0001\", \"g\");\n // Replace TML pseudo-tags\n text = text.replace(pseud, \"<$1>\");\n \n // Convert TWiki tags to spans outside parameters\n text = this._processTags(text);\n \n // Change ' !AnyWord' to ' <nop>AnyWord',\n text = text.replace(PLINGWW, \"$1<nop>$2\");\n \n text = text.replace(/\\\\\\n/g, \"\"); // Join lines ending in '\\'\n \n // Blockquoted email (indented with '> ')\n text = text.replace(/^>(.*?)/gm,\n '><cite class=TMLcite>$1<br /></cite>');\n \n // locate isolated < and > and translate to entities\n // Protect isolated <!-- and -->\n text = text.replace(/<!--/g, \"\\u0000{!--\");\n text = text.replace(/-->/g, \"--}\\u0000\");\n // SMELL: this next fragment is a frightful hack, to handle the\n // case where simple HTML tags (i.e. without values) are embedded\n // in the values provided to other tags. The only way to do this\n // correctly (i.e. handle HTML tags with values as well) is to\n // parse the HTML (bleagh!)\n text = text.replace(/<(\\/[A-Za-z]+)>/g, \"{\\u0000$1}\\u0000\");\n text = text.replace(/<([A-Za-z]+(\\s+\\/)?)>/g, \"{\\u0000$1}\\u0000\");\n text = text.replace(/<(\\S.*?)>/g, \"{\\u0000$1}\\u0000\");\n // entitify lone < and >, praying that we haven't screwed up :-(\n text = text.replace(/</g, \"<\");\n text = text.replace(/>/g, \">\");\n text = text.replace(/{\\u0000/g, \"<\");\n text = text.replace(/}\\u0000/g, \">\");\n \n // standard URI\n text = _sg(URI, text,\n function(match) {\n return match[1] + this._makeLink(match[2],match[2]);\n }, this);\n \n // Headings\n // '----+++++++' rule\n text = _sg(HEADINGDA, text, function(match) {\n return this._makeHeading(match[2],match[1].length);\n }, this);\n \n // Horizontal rule\n var hr = \"<hr class='TMLhr' />\";\n text = text.replace(/^---+/gm, hr);\n \n // Now we really _do_ need a line loop, to process TML\n // line-oriented stuff.\n var isList = false;\t\t// True when within a list\n var insideTABLE = false;\n this.result = new Array();\n\n var lines = text.split(/\\n/);\n for (var i in lines) {\n var line = lines[i];\n // Table: | cell | cell |\n // allow trailing white space after the last |\n if (line.match(/^(\\s*\\|.*\\|\\s*)/)) {\n if (!insideTABLE) {\n result.push(\"<table border=1 cellpadding=0 cellspacing=1>\");\n }\n result.push(this._emitTR(match[1]));\n insideTABLE = true;\n continue;\n } else if (insideTABLE) {\n result.push(\"</table>\");\n insideTABLE = false;\n }\n // Lists and paragraphs\n if (line.match(/^\\s*$/)) {\n isList = false;\n line = \"<p />\";\n }\n else if (line.match(/^\\S+?/)) {\n isList = false;\n }\n else if (line.match(/^(\\t| )+\\S/)) {\n var match;\n if (match = line.match(/^((\\t| )+)\\$\\s(([^:]+|:[^\\s]+)+?):\\s(.*)$/)) {\n // Definition list\n line = \"<dt> \"+match[3]+\" </dt><dd> \"+match[5];\n this._addListItem('dl', 'dd', match[1]);\n isList = true;\n }\n else if (match = line.match(/^((\\t| )+)(\\S+?):\\s(.*)$/)) {\n // Definition list\n line = \"<dt> \"+match[3]+\" </dt><dd> \"+match[4];\n this._addListItem('dl', 'dd', match[1]);\n isList = true;\n }\n else if (match = line.match(/^((\\t| )+)\\* (.*)$/)) {\n // Unnumbered list\n line = \"<li> \"+match[3];\n this._addListItem('ul', 'li', match[1]);\n isList = true;\n }\n else if (match = line.match(/^((\\t| )+)([1AaIi]\\.|\\d+\\.?) ?/)) {\n // Numbered list\n var ot = $3;\n ot = ot.replace(/^(.).*/, \"$1\");\n if (!ot.match(/^\\d/)) {\n ot = ' type=\"'+ot+'\"';\n } else {\n ot = '';\n }\n line.replace(/^((\\t| )+)([1AaIi]\\.|\\d+\\.?) ?/,\n \"<li\"+ot+\"> \");\n this._addListItem('ol', 'li', match[1]);\n isList = true;\n }\n } else {\n isList = false;\n }\n \n // Finish the list\n if (!isList) {\n this._addListItem('', '', '');\n }\n \n this.result.push(line);\n }\n \n if (insideTABLE) {\n this.result.push('</table>');\n }\n this._addListItem('', '', '');\n \n text = this.result.join(\"\\n\");\n text = text.replace(ITALICODE, \"$1<b><code>$2</code></b>\")\n text = text.replace(BOLDI, \"$1<b><i>$2</i></b>\");\n text = text.replace(BOLD, \"$1<b>$2</b>\")\n text = text.replace(ITALIC, \"$1<i>$2</i>\")\n text = text.replace(CODE, \"$1<code>$2</code>\");\n \n // Handle [[][] and [[]] links\n text = text.replace(/(^|\\s)\\!\\[\\[/gm, \"$1[<nop>[\");\n \n // We _not_ support [[http://link text]] syntax\n \n // detect and escape nopped [[][]]\n text = text.replace(/\\[<nop(?: *\\/)?>(\\[.*?\\](?:\\[.*?\\])?)\\]/g,\n '[<span class=\"TMLnop\">$1</span>]');\n text.replace(/!\\[(\\[.*?\\])(\\[.*?\\])?\\]/g,\n '[<span class=\"TMLnop\">$1$2</span>]');\n \n // Spaced-out Wiki words with alternative link text\n // i.e. [[1][3]]\n\n text = _sg(/\\[\\[([^\\]]*)\\](?:\\[([^\\]]+)\\])?\\]/, text,\n function(match) {\n return this._makeSquab(match[1],match[2]);\n }, this);\n \n // Handle WikiWords\n text = removed.takeOut(text, 'noautolink', true);\n \n text = text.replace(NOPWW, '<span class=\"TMLnop\">$1</span>');\n \n text = _sg(WW, text,\n function(match) {\n var url = this.opts['getViewUrl'](match[3], match[4]);\n if (match[5])\n url += match[5];\n return match[1]+this._makeLink(url, match[2]);\n }, this);\n\n text = removed.putBack(text, 'noautolink', 'div');\n \n text = removed.putBack(text, 'pre');\n \n // replace verbatim with pre in the final output\n text = removed.putBack(text, 'verbatim', 'pre',\n function(text) {\n // use escape to URL encode, then JS encode\n return HTMLEncode(text);\n });\n \n // There shouldn't be any lingering <nopresult>s, but just\n // in case there are, convert them to <nop>s so they get removed.\n text = text.replace(/<nopresult>/g, \"<nop>\");\n \n return this._dropBack(text);\n }\n \n // Make the html for a heading\n this._makeHeading = function(heading, level) {\n var notoc = '';\n if (heading.match(HEADINGNOTOC)) {\n heading = heading.substring(0, match.index) +\n heading.substring(match.index + match[0].length);\n notoc = ' notoc';\n }\n return \"<h\"+level+\" class='TML\"+notoc+\"'>\"+heading+\"</h\"+level+\">\";\n };\n\n\n this._addListItem = function(type, tag, indent) {\n indent = indent.replace(/\\t/g, \" \");\n var depth = indent.length / 3;\n var size = this.LIST.length;\n\n if (size < depth) {\n var firstTime = true;\n while (size < depth) {\n var obj = new Object();\n obj['type'] = type;\n obj['tag'] = tag;\n this.LIST.push(obj);\n if (!firstTime)\n this.result.push(\"<\"+tag+\">\");\n this.result.push(\"<\"+type+\">\");\n firstTime = false;\n size++;\n }\n } else {\n while (size > depth) {\n var types = this.LIST.pop();\n this.result.push(\"</\"+types['tag']+\">\");\n this.result.push(\"</\"+types['type']+\">\");\n size--;\n }\n if (size) {\n this.result.push(\"</this.{LIST}.[size-1].{element}>\");\n }\n }\n \n if (size) {\n var oldt = this.LIST[size-1];\n if (oldt['type'] != type) {\n this.result.push(\"</\"+oldt['type']+\">\\n<type>\");\n this.LIST.pop();\n var obj = new Object();\n obj['type'] = type;\n obj['tag'] = tag;\n this.LIST.push(obj);\n }\n }\n }\n \n this._emitTR = function(row) {\n \n row.replace(/^(\\s*)\\|/, \"\");\n var pre = 1;\n \n var tr = new Array();\n \n while (match = row.match(/^(.*?)\\|/)) {\n row = row.substring(match[0].length);\n var cell = 1;\n \n if (cell == '') {\n cell = '%SPAN%';\n }\n \n var attr = new Attrs();\n \n my (left, right) = (0, 0);\n if (cell.match(/^(\\s*).*?(\\s*)/)) {\n left = length (1);\n right = length (2);\n }\n \n if (left > right) {\n attr.set('class', 'align-right');\n attr.set('style', 'text-align: right');\n } else if (left < right) {\n attr.set('class', 'align-left');\n attr.set('style', 'text-align: left');\n } else if (left > 1) {\n attr.set('class', 'align-center');\n attr.set('style', 'text-align: center');\n }\n \n // make sure there's something there in empty cells. Otherwise\n // the editor will compress it to (visual) nothing.\n cell.replace(/^\\s*/g, \" \");\n \n // Removed TH to avoid problems with handling table headers. TWiki\n // allows TH anywhere, but Kupu assumes top row only, mostly.\n // See Item1185\n tr.push(\"<td \"+attr+\"> \"+cell+\" </td>\");\n }\n return pre+\"<tr>\" + tr.join('')+\"</tr>\";\n }\n}",
"toBareHTML () {\n return this.raws.reduce((html, raw) => {\n return `${html}${raw.html}`\n }, '')\n }",
"function buildHTML() {\r\n\t\treturn;\r\n\t}",
"formatOutput(){\n this.content = beautifyHtml(this.content, this.options.htmlBeautify);\n }",
"function autoEdHTMLtoWikitext(str) {\n // <b>, <strong>, <i>, and <em> tags\n str = str.replace(/<(B|STRONG)[ ]*>((?:[^<>]|<[a-z][^<>]*\\/>|<([a-z]+)(?:| [^<>]*)>[^<>]*<\\/\\3>)*?)<\\/\\1[ ]*>/gi, \"'''$2'''\");\n str = str.replace(/<(I|EM)[ ]*>((?:[^<>]|<[a-z][^<>]*\\/>|<([a-z]+)(?:| [^<>]*)>[^<>]*<\\/\\3>)*?)<\\/\\1[ ]*>/gi, \"''$2''\");\n // </br>, <\\br>, <br\\>, <BR />, ...\n str = str.replace(/<[\\\\\\/]+BR[\\\\\\/\\s]*>/gim, '<br />');\n str = str.replace(/<[\\\\\\/\\s]*BR[\\s]*[\\\\\\/]+[\\s]*>/gim, '<br />');\n // <.br>, <br.>, <Br>, ...\n str = str.replace(/<[\\s\\.]*BR[\\s\\.]*>/gim, '<br>');\n // <br>>, <<br />, <<br >> ...\n str = str.replace(/<[\\s]*(<br[\\s\\/]*>)/gim, '$1');\n str = str.replace(/(<br[\\s\\/]*>)[\\s]*>/gim, '$1');\n // <hr>\n str = str.replace(/([\\r\\n])[\\t ]*<[\\\\\\/\\. ]*HR[\\\\\\/\\. ]*>/gi, '$1----');\n str = str.replace(/(.)<[\\\\\\/\\. ]*HR[\\\\\\/\\. ]*>/gi, '$1\\n----');\n // Not really an HTML-to-wikitext fix, but close enough\n str = str.replace(/<[\\\\\\/\\s]*REFERENCES[\\\\\\/\\s]*>/gim, '<references />');\n // Repeated references tag\n str = str.replace(/(<references \\/>)[\\s]*\\1/gim, '$1');\n // Make sure <H1>, ..., <H6> is after a newline\n str = str.replace(/([^\\r\\n ])[\\t ]*(<H[1-6][^<>]*>)/gim, '$1\\n$2');\n // Make sure </H1>, ..., </H6> is before a newline\n str = str.replace(/(<\\/H[1-6][^<>]*>)[\\t ]*([^\\r\\n ])/gim, '$1\\n$2');\n // Remove newlines from inside <H1>, ..., <H6>\n var loopcount = 0;\n while( str.search( /<H([1-6])[^<>]*>(?:[^<>]|<\\/?[^\\/h\\r\\n][^<>]*>)*?<\\/H\\1[^<>]*>/gim ) >= 0 && loopcount <= 10 ) {\n str = str.replace(/(<H)([1-6])([^<>]*>(?:[^<>]|<\\/?[^\\/h\\r\\n][^<>]*>)*?)[\\r\\n]((?:[^<>]|<\\/?[^\\/h\\r\\n][^<>]*>)*?<\\/H)\\2([^<>]*>)/gim, '$1$2$3 $4$2$5');\n loopcount++;\n }\n // Replace <H1>, ..., <H6> with wikified section headings\n str = str.replace(/(^|[\\r\\n])[\\t ]*<H1[^<>]*>([^\\r\\n]*?)<\\/H1[\\r\\n\\t ]*>[\\t ]*([\\r\\n]|$)/gim, '$1= $2 =$3');\n str = str.replace(/(^|[\\r\\n])[\\t ]*<H2[^<>]*>([^\\r\\n]*?)<\\/H2[\\r\\n\\t ]*>[\\t ]*([\\r\\n]|$)/gim, '$1== $2 ==$3');\n str = str.replace(/(^|[\\r\\n])[\\t ]*<H3[^<>]*>([^\\r\\n]*?)<\\/H3[\\r\\n\\t ]*>[\\t ]*([\\r\\n]|$)/gim, '$1=== $2 ===$3');\n str = str.replace(/(^|[\\r\\n])[\\t ]*<H4[^<>]*>([^\\r\\n]*?)<\\/H4[\\r\\n\\t ]*>[\\t ]*([\\r\\n]|$)/gim, '$1==== $2 ====$3');\n str = str.replace(/(^|[\\r\\n])[\\t ]*<H5[^<>]*>([^\\r\\n]*?)<\\/H5[\\r\\n\\t ]*>[\\t ]*([\\r\\n]|$)/gim, '$1===== $2 =====$3');\n str = str.replace(/(^|[\\r\\n])[\\t ]*<H6[^<>]*>([^\\r\\n]*?)<\\/H6[\\r\\n\\t ]*>[\\t ]*([\\r\\n]|$)/gim, '$1====== $2 ======$3');\n \n return str;\n}",
"function autoEdTablestoWikitext(str) { //MAIN FUNCTION describes list of fixes\n \n // Remove newlines from inside table specific tags\n var loopcount = 0;\n while( str.search(/(?:<\\/?table|<\\/?tr|<\\/?td|<\\/?th)[^<>]*[\\r\\n]/gi) >= 0 && loopcount <= 10 ) {\n str.replace(/((?:<\\/?table|<\\/?tr|<\\/?td|<\\/?th)[^<>]*)[\\r\\n]/gi, '$1 ')\n loopcount++;\n }\n // Remove extra whitespace from inside table specific tags\n str=str.replace(/(<table|<tr|<td|<th)([^<>]*?)[\\s]+(>)/gim, '$1$2$3');\n str=str.replace(/(<table|<tr|<td|<th)([^<>]*?)[\\s][\\s]+/gim, '$1$2 ');\n // Remove any extra junk </tr>, </td>, </th>, </table>\n str=str.replace(/(<\\/table|<\\/tr|<\\/td|<\\/th)[^<>]+(>)/gim, '$1$2');\n // Remove space whitespace after </tr>, </td>, </th>, <table>\n str=str.replace(/(<\\/tr>|<\\/td>|<\\/th>|<table[^<>]*>)[\\s]+/gim, '$1');\n // Remove space before <tr>, <td>, <th>, </table>\n str=str.replace(/[\\s]+(<\\/table>|<tr[^<>]*>|<td[^<>]*>|<th[^<>]*>)/gim, '$1');\n // Replace '<table stuff>' with '{| stuff'\n str=str.replace(/<table( [^<>]*|)>[\\s]*/gim, '{|$1\\n');\n // Replace '</table>' with '|}'\n str=str.replace(/[\\s]*<\\/table>/gi, '\\n|}');\n // Replace '</td><td>' with '||'\n str=str.replace(/<\\/td[\\s]*>[\\s]*<td[\\s]*>/gim, '||');\n str=str.replace(/<\\/td[\\s]*>[\\s]*<td ([^<>]+)>/gim, '|| $1 |');\n // Replace '</th><th>' with '!!'\n str=str.replace(/<\\/th[\\s]*>[\\s]*<th[\\s]*>/gim, '!!');\n str=str.replace(/<\\/th[\\s]*>[\\s]*<th ([^<>]+)>/gim, '!! $1 |');\n // Replace '</td></tr>' and '</th></tr>' with EOL\n str=str.replace(/<\\/(?:td|th)>[\\s]*<\\/tr>[\\s]/gim, '\\n');\n // Replace '</td>', '</th>', '</tr>' with EOL\n str=str.replace(/<\\/(?:td|th|tr)>[\\s]*/gim, '\\n');\n // Replace '<tr>' with '|-'\n str=str.replace(/[\\s]*<tr>[\\s]*/gim, '\\n|-\\n');\n str=str.replace(/[\\s]*<tr ([^<>]*)>[\\s]*/gim, '\\n|- $1\\n');\n // Replace '<td>' with '|'\n str=str.replace(/[\\s]*<td>([^\\s])/gim, '\\n| $1');\n str=str.replace(/[\\s]*<td>([\\s])/gim, '\\n|$1');\n str=str.replace(/[\\s]*<td[\\s]*([^<>]*?)[\\s]*>([^\\s])/gim, '\\n| $1 | $2');\n str=str.replace(/[\\s]*<td[\\s]*([^<>]*?)[\\s]*>([\\s])/gim, '\\n| $1 |$2');\n // Replace '<th>' with '!'\n str=str.replace(/[\\s]*<th>([^\\s])/gim, '\\n! $1');\n str=str.replace(/[\\s]*<th>([\\s])/gim, '\\n!$1');\n str=str.replace(/[\\s]*<th[\\s]*([^<>]*?)[\\s]*>([^\\s])/gim, '\\n! $1 | $2');\n str=str.replace(/[\\s]*<th[\\s]*([^<>]*?)[\\s]*>([^\\s])/gim, '\\n! $1 |$2');\n \n return str;\n}",
"function rm_space_after_open(html_str) {\n\tlet edited_html_str = html_str.replaceAll(/<p( [^>]*)*> */g, \"<p$1>\");\n\tedited_html_str = edited_html_str.replaceAll(/<li( [^>]*)*> */g, \"<li$1>\");\n\tedited_html_str = edited_html_str.replaceAll(/<th( [^>]*)*> */g, \"<th$1>\");\n\tedited_html_str = edited_html_str.replaceAll(/<td( [^>]*)*> */g, \"<td$1>\");\n\tedited_html_str = edited_html_str.replaceAll(/<h([0-9]+)( [^>]*)*> */g, \"<h$1$2>\");\n\treturn edited_html_str;\n}",
"function html2Xml(html) {\n\n\t\t// -> Add closure to <img> tags\n\t\tvar xml = html.replace(/<(img [^>]*?[^\\/])>/g, \"<$1/>\");\n\n\t\t// -> Add closure to <br> tags\n\t\txml = xml.replace(\"<br>\", \"<br />\");\n\n\t\t// -> Re-inject CDATA blocks\n\t\t_.each(cdatas, function (cdata,i) {\n\t\t\txml = xml.replace(\"CDATA_\" + i, cdata);\n\t\t});\n\n\t\treturn xml;\t\n\t}",
"function convert_to_HTML(data){\n var python_lines = data.split(\"\\n\");\n var python_line, i;\n var final_python_code = [];\n var skip_flag = false;\n var start_flag = false;\n for (i = 0; i < python_lines.length; i++){\n python_line = python_lines[i];\n if (python_line == \"#START#\"){\n start_flag = true;\n continue;\n }\n if (!start_flag){\n continue;\n }\n if (skip_flag){\n skip_flag = false;\n continue;\n }\n if (python_line == \"#END#\"){\n break;\n }\n if (python_line.trim().substring(0, 3) == \"#<a\"){\n final_python_code.push(python_line.replace(\"#\", \"\"));\n skip_flag = true;\n } else {\n final_python_code.push(python_line);\n }\n }\n return final_python_code.join(\"\\n\");\n}",
"function tidy_xhtml() {\r\n var text = String(this);\r\n\r\n text = text.gsub(/\\r\\n?/, \"\\n\");\r\n\r\n text = text.gsub(/<([A-Z]+)([^>]*)>/, function(match) {\r\n return '<' + match[1].toLowerCase() + match[2] + '>';\r\n });\r\n\r\n text = text.gsub(/<\\/([A-Z]+)>/, function(match) {\r\n return '</' + match[1].toLowerCase() + '>';\r\n });\r\n\r\n text = text.replace(/<br>/g, \"<br />\");\r\n\r\n return text;\r\n }",
"function fixHTML(html) { return html.replace(/ /g, \" \").replace(/’/g, \"'\").replace(/-/g,\"‑\"); }",
"function formatSource()\n{\n var root = dreamweaver.getDocumentDOM(\"document\");\n\n // make sure we're synched before we get length or do the format\n root.synchronizeDocument();\n\n var htmlTag = root.documentElement;\n\n htmlTag.innerHTML = htmlTag.innerHTML + \"\";\n\n return; \n}",
"function normalise(html) {\n var document = parse5.parse(html, {locationInfo: false});\n return parse5.serialize(document);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
============================================================================= Other functions SIGINT handler | function HandleSigInt()
{
console.log(''); // (for linefeed after CTRL-C)
Log('Exiting on SIGINT');
Cleanup();
// exit after giving time to log last message
setTimeout(function() { process.exit(); }, 10);
} | [
"function sigint() {\n\tcleanup( onCleanup( SIGINT ) );\n}",
"_hookSIG(){\n\t\tprocess.on('SIGINT',this.exit.bind(this));\n\t}",
"function sigterm() {\n\tcleanup( onCleanup( SIGTERM ) );\n}",
"function sigHandle() {\n if (child) {\n child.kill('SIGINT');\n }\n}",
"function onHandleSignal(signal) {\n console.log(`\\nHandling Interrupt: ${signal}`);\n server.close(() => {\n console.log('Orderly Shutdown...');\n process.exit(0);\n });\n }",
"Interrupt() {\n\n }",
"function handleSignal(signal) {\n\t\tswitch(signal) {\n\t\t\tcase \"reset\":\n\t\t\t\tblocking_input = true;\n\t\t\t\trequire(\"child_process\").spawn(process.argv.shift(), process.argv, {\n\t\t\t\t\tcwd: process.cwd(),\n\t\t\t\t\tdetached : true,\n\t\t\t\t\tstdio: \"inherit\",\n\t\t\t\t});\n\t\t\t\tprocess.exit();\n\t\t\t\tbreak;\n\n\t\t\tcase \"reload_commands\":\n\t\t\t\treloadCommands();\n\t\t\t\tbreak;\n\n\t\t\tcase \"reload_parsers\":\n\t\t\t\treloadParsers();\n\t\t\t\tbreak;\n\n\t\t\tcase \"quit\":\n\t\t\t\tblocking_input = true;\n\t\t\t\tsetTimeout(process.exit, 1500);\n\t\t\t\tbreak;\n\n\t\t}\n\t}",
"function interrupt() {\n if (interrupted) {\n console.log('\\nGot multiple interrupts, exiting immediately!');\n return process.exit(1);\n }\n interrupted = true;\n close().then(() => process.exit(0), (error) => {\n error = error || 'cleankill interrupt handler failed without a message';\n console.error(error.stack || error.message || error);\n process.exit(2);\n });\n console.log('\\nShutting down. Press ctrl-c again to kill immediately.');\n}",
"function _safely_install_sigint_listener() {\n\n const listeners = process.listeners(SIGINT);\n const existingListeners = [];\n for (let i = 0, length = listeners.length; i < length; i++) {\n const lstnr = listeners[i];\n /* istanbul ignore else */\n if (lstnr.name === '_tmp$sigint_listener') {\n existingListeners.push(lstnr);\n process.removeListener(SIGINT, lstnr);\n }\n }\n process.on(SIGINT, function _tmp$sigint_listener(doExit) {\n for (let i = 0, length = existingListeners.length; i < length; i++) {\n // let the existing listener do the garbage collection (e.g. jest sandbox)\n try {\n existingListeners[i](false);\n } catch (err) {\n // ignore\n }\n }\n try {\n // force the garbage collector even it is called again in the exit listener\n _garbageCollector();\n } finally {\n if (!!doExit) {\n process.exit(0);\n }\n }\n });\n}",
"handleExits() {\r\n process.on('SIGINT', () => {\r\n logger.info('Shutting down gracefully...');\r\n this.server.close(() => {\r\n logger.info(colors.red('Web server closed'));\r\n process.exit();\r\n });\r\n });\r\n }",
"interrupted(/* motions */) {\n }",
"kill(signal = \"SIGINT\") {\n if (running) {\n child.kill(signal);\n }\n if (unreffable) {\n unreffable.unref();\n }\n }",
"onTtsInterrupted() {}",
"function Signal() {}",
"installSIGTERMHandler() {\n process.on(\"SIGTERM\", () => {\n this.closeConnections({ log: true });\n });\n }",
"function unix_sigpending() { unix_ll(\"unix_sigpending\", arguments); }",
"exit(){\n\t\tthis.logger.info('SIGINT received, ready to exit, current working jobs: %d', this.jobs.size);\n\t\tthis._w.readyReset = this.readyToExit = true;// set ready to reset to tell worker do not send GRAB_JOB any more.\n\t\tthis._tryExit();\n\t}",
"function exitHandler(furby) {\n\tprocess.on(\"SIGINT\", function () {\n\t\twinston.info(\"\\nClosing connection...\");\n\t\tfurby.disconnect(function(error) {\n\t\t\tif (error)\n\t\t\t\twinston.error(\"Error while disconnecting: \" + error);\n\t\t\telse\n\t\t\t\twinston.info(\"Disconnected, exiting.\");\n\n\t\t\t// TODO: This does not work with multiple furbies connect\n\t\t\tprocess.exit();\n\t\t});\n\t});\n}",
"function abortSignal(signal) {\n if (abortedFlags.get(signal) !== false) {\n return;\n }\n abortedFlags.set(signal, true);\n signal.dispatchEvent({ type: \"abort\" });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves a block as successfully run. This method requires that the block was added to the blockchain. | async _saveBlockAsSuccessfullyRun(block, runBlockResult) {
const receipts = output_1.getRpcReceiptOutputsFromLocalBlockExecution(block, runBlockResult, output_1.shouldShowTransactionTypeForHardfork(this._vm._common));
this._blockchain.addTransactionReceipts(receipts);
const td = await this.getBlockTotalDifficulty(block);
const rpcLogs = [];
for (const receipt of receipts) {
rpcLogs.push(...receipt.logs);
}
this._filters.forEach((filter, key) => {
if (filter.deadline.valueOf() < new Date().valueOf()) {
this._filters.delete(key);
}
switch (filter.type) {
case filter_1.Type.BLOCK_SUBSCRIPTION:
const hash = block.hash();
if (filter.subscription) {
this._emitEthEvent(filter.id, output_1.getRpcBlock(block, td, output_1.shouldShowTransactionTypeForHardfork(this._vm._common), false));
return;
}
filter.hashes.push(ethereumjs_util_1.bufferToHex(hash));
break;
case filter_1.Type.LOGS_SUBSCRIPTION:
if (filter_1.bloomFilter(new bloom_1.default(block.header.bloom), filter.criteria.addresses, filter.criteria.normalizedTopics)) {
const logs = filter_1.filterLogs(rpcLogs, filter.criteria);
if (logs.length === 0) {
return;
}
if (filter.subscription) {
logs.forEach((rpcLog) => {
this._emitEthEvent(filter.id, rpcLog);
});
return;
}
filter.logs.push(...logs);
}
break;
}
});
} | [
"saveBlock(block)\n\t{\n\t}",
"async function save_block(block) {\n newblock = await block.save();\n console.log(\"Block \" + newblock.height + \" saved.\");\n return newblock;\n}",
"function saveDoneBlock() {\n\n let blockAlreadyInserted = false;\n for (let i = 0; i < playerLevelEnvironment.listOfBlocksInThePlayingArea.length; i++) {\n if (playerLevelEnvironment.listOfBlocksInThePlayingArea[i].blockCounter === playerLevelEnvironment.blockCounter) {\n blockAlreadyInserted = true;\n }\n }\n\n if (blockAlreadyInserted === false) {\n try {\n playerLevelEnvironment.listOfBlocksInThePlayingArea.push({\n blockMap: blockMap[playerLevelEnvironment.blockIndex][playerLevelEnvironment.rotationIndex][playerLevelEnvironment.rotationIndex],\n blockIndex: playerLevelEnvironment.blockIndex,\n blockX: Math.floor(playerLevelEnvironment.xPlayArea / gameLevelEnvironment.pixelSize),\n blockY: Math.floor(playerLevelEnvironment.yPlayArea / gameLevelEnvironment.pixelSize) - 1,\n blockCounter: playerLevelEnvironment.blockCounter,\n wasChecked: false\n });\n } catch(error) {\n }\n }\n }",
"saveBlock(seriesCb) {\n modules.blocks.lastBlock.set(block);\n\n if (saveBlock) {\n // DATABASE: write\n self.saveBlock(block, (err) => {\n if (err) {\n // Fatal error, memory tables will be inconsistent\n library.logger.error('Failed to save block...', err);\n library.logger.error('Block', block);\n\n return process.exit(0);\n }\n\n library.logger.debug(`Block applied correctly with ${block.transactions.length} transactions`);\n library.bus.message('newBlock', block, broadcast);\n\n // DATABASE write. Update delegates accounts\n modules.rounds.tick(block, seriesCb);\n });\n } else {\n library.bus.message('newBlock', block, broadcast);\n\n // DATABASE write. Update delegates accounts\n modules.rounds.tick(block, seriesCb);\n }\n }",
"function saveNewBlock(newBlock){\n\n\t// Save new block\n\tnewBlock.save().then(function(data) {\n\n\t\t// Bind to new block\n\t\tresetBlockClickEvents();\n\n\t\t// After we get the ID add it to the page and save that\n\t\tApp.Store.find( 'page', CurrentPageId ).then(function(page) {\n\t\t\tpage.get('blocks').pushObject(newBlock);\n\t\t\tpage.save().then(function(data) {\n\t\t\t\t\t\n\t\t\t\t\tsaveBlockData();\n\n\t\t\t\t\tvar width = newBlock.get('dSizeX');\n\t\t\t\t\tvar height = newBlock.get('dSizeY');\n\t\t\t\t\tvar row = newBlock.get('dRow');\n\t\t\t\t\tvar col = newBlock.get('dCol');\n\n\t\t\t\t\t// gridster.add_widget( generatePreviewCodeForBlock(newBlock), width, height, col, row);\n\t\t\t\t\t\n\t\t\t\t\t// if (newBlock.get('image')){\n\n\t\t\t\t\t// }\n\n\t\t\t\t\tdrawNewBlockFromEmberHelper( newBlock, page.get('id') );\n\n\t\t\t\t}, function(resp) {\n\t\t\t\t\tpage.save(); // Save didn't work, try again\n\t\t\t\t});\n\t\t});\n\n\t}, function(resp) {\n\t\tif (resp.responseJSON) {\n\t\t\talert('Save didnt work: ', resp.responseJSON );\n\t\t} \n\t\t// Save didn't work\n\t});\n\n}",
"function saveBlock(block, tx) {\n block.tx.forEach(element => {\n if (element.type === \"ContractTransaction\") {\n tx.push(element);\n }\n });\n console.log(tx);\n let newBlock = new blockData({\n block_number: block.index,\n transactions: tx,\n block_hash: block.hash\n });\n newBlock\n .save()\n .then(res => {\n console.log(\"Saved in the database\");\n setTimeout(getBlockData, 3000);\n })\n .catch(err => {\n console.log(err);\n setTimeout(getBlockData, 3000);\n });\n}",
"function submitBlock(block) {\n if(!config.poolServer.submitDuplicateBlockHeight && submittedBlocks.includes(block.height)) {\n\t log(\"warn\", logSystem, \"Block already found at height %s, ignoring...\", [block.height]);\n } else {\n\t client.write(JSON.stringify({\"id\":block.height, \"method\":\"miner-submit\",\"params\":[block]})+\"\\n\");\n\t log(\"info\", logSystem, \"Submitted Block at height %s successfully to daemon\", [block.height]);\n // remember this block height\n submittedBlocks.push(block.height);\n // trim off from submitted block list\n while(submittedBlocks.length > 10) {\n submittedBlocks.shift();\n }\n }\n }",
"async addBlockToDatabase(block) {\n try {\n // console.log(\"\\n\\n\\naddBlockToDatabase body==\", block);\n return await this.blockchain.addBlock(new BlockClass.Block(block));\n } catch (error) {\n console.log(\"error in adding block\");\n return \"Internal error to add block\";\n }\n }",
"saveBlock(block) {\n let newBlock = new blockChainModel(block);\n newBlock.save((err) => {\n if (err)\n return console.log(chalk.red(\"Cannot save Block to DB \", err.message));\n console.log(chalk.green(\"Block Saved on the DB\"));\n });\n //Add to Chain\n this\n .chain\n .push(block);\n this.curr_votes = [];\n return block;\n }",
"function runBlock(cb) {\n self\n .runBlock({\n block: block,\n root: parentState,\n })\n .then(function () {\n // set as new head block\n headBlock = block;\n cb();\n })\n .catch(function (err) {\n // remove invalid block\n blockchain.delBlock(block.header.hash(), function () {\n cb(err);\n });\n });\n }",
"async updateBlock(block) {\n if (this.onMainBranchSync(block.hash)) {\n await this.store.writeBlock(block);\n }\n\n this.emit('update', block, this.getHeadBlockIdSync());\n // resolve nothing when success\n // reject with error when error\n }",
"addBlockLevel(newBlock) {\n\t\t this.getBlockHeightLevel().then((height) => {\t\n\t\t\tlet newBlock_string = JSON.stringify(newBlock).toString(); //turn block array to string\n\t\t\tlet internal_key = newBlock.height;\n\t\t\tconsole.log('Adding Block', + internal_key);\n\t\t\tdb.put(internal_key,newBlock_string, function(err) {\n\t\t\tif (err) return console.log('Block ' + internal_key + 'submission failed', err);\n\t\t}) //places string verable into level database\n\t\t\t\n\t\t\t\n\t\t}).catch(error => {\n\t\t\tconsole.log('Error in testy');\n\t\t})\n\t\t\n\t}",
"function runBlock(cb) {\n self.runBlock({\n block: block,\n root: parentState\n }, function (err, results) {\n if (err) {\n // remove invalid block\n console.log('Invalid block error:', err);\n blockchain.delBlock(block.header.hash(), cb);\n } else {\n // set as new head block\n headBlock = block;\n cb();\n }\n });\n }",
"commit(winningBlockID) {\n // **FIXME** Handle case where block is not available.\n\n this.nextBlock = this.proposedBlocks[winningBlockID];\n\n this.log(`Committing to block ${winningBlockID}`);\n\n let vote = Vote.makeVote(this, StakeBlockchain.COMMIT, winningBlockID);\n this.net.broadcast(StakeBlockchain.COMMIT, vote);\n\n setTimeout(() => this.finalizeCommit(), this.round*StakeBlockchain.DELTA);\n }",
"function runBlock (cb) {\n self.runBlock({\n block: block,\n root: parentState\n }, function (err, results) {\n if (err) {\n // remove invalid block\n console.log('Invalid block error:', err)\n self.blockchain.delBlock(block.header.hash(), cb)\n } else {\n // set as new head block\n headBlock = block\n cb()\n }\n })\n }",
"function submitblock( b ) {\n\n // Run a batch file to submit the block to bitcoin core over RPC\n const commandline = blockSubmitCommandTemplate.replace( \"${block}\" , b.toString(\"hex\") );\n console.log(\"Submitting block command:\"+commandline);\n\n\n}",
"function runBlock(cb) {\n self.runBlock({\n block: block,\n root: parentState\n }, function (err, results) {\n if (err) {\n // remove invalid block\n console.log('Invalid block error:', err);\n self.stateManager.blockchain.delBlock(block.header.hash(), cb);\n } else {\n // set as new head block\n headBlock = block;\n cb();\n }\n });\n }",
"function runBlock(cb) {\n self.runBlock({\n block: block,\n root: parentState\n }, function (err, results) {\n if (err) {\n // remove invalid block\n blockchain.delBlock(block.header.hash(), function () {\n cb(err);\n });\n } else {\n // set as new head block\n headBlock = block;\n cb();\n }\n });\n }",
"function runBlock (cb) {\n self.runBlock({\n block: block,\n root: parentState\n }, function (err, results) {\n if (err) {\n // remove invalid block\n self.stateManager.blockchain.delBlock(block, cb)\n } else {\n // set as new head block\n headBlock = block\n cb()\n }\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
lastNodeOf This function gets passed a URL and returns the last node of same. | function lastNodeOf(e)
{
var expr = "" + e;
var to = expr.indexOf("?");
if( to !== -1) {
var path = expr.substring(0,to);
var pieces = path.split("/");
return pieces[pieces.length -1];
} else {
var pos = expr.lastIndexOf("/");
if( (pos != -1) && (pos+1 != expr.length) ) {
return expr.substr(pos+1);
} else {
return expr;
}
}
} | [
"getLastNode(){\n\t\tlet pointer = this.head;\n\t\tfor(; pointer.next; pointer = pointer.next){\n\t\t\tcontinue;\n\t\t}\n\t\treturn pointer;\n\t}",
"findLastNode() {\n return this.findNodes().reverse()[0];\n }",
"getLast () {\n\t\tlet lastNode = this.head;\n\t\t\n\t\tif (lastNode) {\n\t\t\twhile (lastNode.next) {\n\t\t\t\tlastNode = lastNode.next;\n\t\t\t}\n\t\t}\n\n\t\treturn lastNode;\n\t}",
"getLast() {\n\t\tlet lastNode = this.head;\n\n\t\tif (lastNode) {\n\t\t\twhile (lastNode.next) {\n\t\t\t\tlastNode = lastNode.next;\n\t\t\t}\n\t\t}\n\n\t\treturn lastNode;\n\t}",
"getLast(){\n //Look out for case where linkedlist has no nodes associated with it. \n if(!this.head){\n return null;\n }\n //Iterate through linked list and get the last node. Can identify the lasdt node by the null property. \n let node = this.head;\n while(node){\n //if not defined, return next node\n if(!node.next){\n return node;\n }\n node = node.next;\n }\n }",
"function getLastPartOfUrl(url){\n let parts = url.split('/');\n let lastPart = parts[parts.length-1];\n\n return lastPart;\n}",
"function getLastNum(url) {\n let end = url.lastIndexOf('/')\n let start = end - 2\n if (url.charAt(start) === '/') {\n start++\n }\n return url.slice(start, end)\n}",
"function lastPart(url) {\n return removeTrailingSlash(url).split('/').pop();\n}",
"function getLastContent() {\n var doc = getContentDocument();\n var last = doc.getElementById('always_last_node');\n if(!last && doc.body && doc.body.lastChild) {\n last = doc.body.lastChild;\n }\n\n return last;\n}",
"lastNode(list) {\r\n\t\t\t\t\tif (list.length === 0) {\r\n\t\t\t\t\t\treturn null;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\treturn list[list.length - 1];\r\n\t\t\t\t\t}\r\n\t\t\t\t}",
"lastNode(list) {\n if (list.length === 0) {\n return null;\n } else {\n return list[list.length - 1];\n }\n }",
"getLast() {\n if (!this.head) {\n return null;\n }\n\n let node = this.head;\n while(node) {\n if (!node.next) {\n return node;\n }\n node = node.next;\n }\n }",
"getLastButOneNode() {\n\t\tlet pointer = this.head,\n\t\t\tprev = this.head;\n\t\tfor(;pointer.next; prev = pointer, pointer = pointer.next) {\n\t\t\tcontinue;\n\t\t}\n\t\treturn prev;\n\t}",
"function last_child( par )\r\n{\r\n var res=par.lastChild;\r\n while (res) {\r\n if (!is_ignorable(res)) return res;\r\n res = res.previousSibling;\r\n }\r\n return null;\r\n}",
"function lastNode(nodeList) {\r\n\r\n if (nodeList.length == 0) return null;\r\n \r\n return nodeList[ nodeList.length - 1 ];\r\n}",
"function getLastTile(){\n\t\t\n\t\treturn g_objInner.children(\".ug-thumb-wrapper\").last();\t\t\n\t}",
"function lastNode(nodeList) {\n\n if (nodeList.length == 0) return null;\n \n return nodeList[ nodeList.length - 1 ];\n}",
"getLast(){\n if(!this.head){\n return null;\n }\n \n let node = this.head;\n while(node){\n if(!node.next){\n return node;\n }\n node = node.next;\n }\n }",
"function getLastSelectedNode() {\r\n return lastSelectedNode;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks if the settings for the cipher are invalid (ex. NaN). However, if there are no settings given (ie blank settings), then it will NOT be considered invalid. Parameters: settings the settings to check for validity | hasInvalidSettings(settings){} | [
"function checkSettings(){\n\tlog(\"commencing settings check\");\n\tvar errors = new Array();\n\tif (settings.cols % 1 != 0 || settings.cols < 1){\n\t\terrors.push(\"cols settings incorrect. cols: \"+ settings.cols +\" (settings.cols % 1 != 0 || settings.cols < 1\");\n\t}\n\tif (settings.rows % 1 != 0 || settings.rows < 1){\n\t\terrors.push(\"rows settings incorrect. rows: \"+ settings.rows +\" (settings.rows % 1 != 0 || settings.rows < 1)\");\n\t}\n\tif (settings.mines % 1 != 0 || settings.mines < 1 || (settings.mines >= settings.rows * settings.cols) ){\n\t\terrors.push(\"mines settings incorrect. mines: \"+ settings.mines +\" (settings.mines % 1 != 0 || settings.mines < 1 || (settings.mines >= settings.rows * settings.cols)\");\n\t}\n\t// to-do: check difficulty\n\t// to-do: only check rows, cols, mines if no difficulty is set and vice versa\n\tif (errors.length > 0) {\n\t\tif (settings.debug == true) {\n\t\t\tlog(\"Settings check failed!\",\"error\");\n\t\t\tfor (e in errors){\n\t\t\t\tlog(errors[e],\"error\");\n\t\t\t}\n\t\t}\n\t\treturn errors;\n\t}\n\telse {\n\t\tlog(\"Settings check successful\");\n\t\treturn true;\n\t}\n}",
"function validate_settings(settings, options) {\n console.log(\"Validating device settings\");\n var missing = [];\n for (var idx in options) {\n if (settings[options[idx]] === undefined) missing.push(options[idx]);\n }\n if (missing.length > 0) {\n // app is terminated if settings are missing\n throw new Error('Required settings ' + (missing.join(', ')) + ' missing.');\n }\n}",
"function validate_settings (settings) {\n\tif (['POST', 'GET', 'PATCH', 'DELETE', 'PUT'].includes(settings.method) === false) {\n\t\tthrow new Error('method must be one of [\\'POST\\', \\'GET\\', \\'PATCH\\', \\'DELETE\\', \\'PUT\\']');\n\t}\n\n\tif (typeof settings.path !== 'string') {\n\t\tthrow new Error('path must be a string');\n\t}\n\n\tif (['JSON', 'XML', 'HTML'].includes(settings.response) === false) {\n\t\tthrow new Error('response must be JSON or XML or HTML');\n\t}\n\n\tif (['URL', 'FORM', undefined].includes(settings.format) === false) {\n\t\tthrow new Error('format must be URL or FORM or undefined');\n\t}\n\n\tif (['object', 'undefined'].includes(typeof settings.data) === false) {\n\t\tthrow new Error('data must be an object or undefined');\n\t}\n\n\tif (typeof this.useragent !== 'string') {\n\t\tthrow new Error('useragent must be a string');\n\t}\n\n\tif (settings.authenticate === true) {\n\t\t// If authenticating, then both username and api_key must be present\n\t\tif (typeof this.username !== 'string') {\n\t\t\tthrow new Error('useragent must be a string');\n\t\t} else if (typeof this.api_key !== 'string') {\n\t\t\tthrow new Error('api_key must be a string');\n\t\t}\n\t}\n}",
"invalidate(someSettings) {\n const invalidated = super.invalidate(someSettings);\n if (invalidated instanceof Error) {\n return invalidated;\n }\n const settings = { ...this.values, ...someSettings, ...invalidated };\n // <<-- Creer-Merge: invalidate -->>\n // Write logic here to check the values in `settings`. If there is a\n // problem with the values a player sent, return an error with a string\n // describing why their value(s) are wrong\n // <<-- /Creer-Merge: invalidate -->>\n return settings;\n }",
"function settingsValidation() {\n\n if (settings.get(\"OPTION_ID\") && settings.get(\"MAIN_TABLE\") && settings.get(\"MAIN_PK_FIELD\") && settings.get(\"SPC_TABLE\") && settings.get(\"SPC_PK_FIELD\")) {\n return true;\n } else {\n eventEmmitter.emit(\"message\", \"Unable to Process Action Due to Settings Configuration Incomplete. Please Launch Settings.\");\n \n return false;\n }\n\n}",
"function checkSettings(theSettings, samplingRate) {\n\t\tvalidatedSettings = {};\n\t\tcompatibilityIssues = {};\n\t\t\n\t\tfor (var c = 0; c < 4; c++) {\n\t\t\tchannel = \"abcd\".charAt(c);\n\t\t\tif (theSettings[channel] != undefined) {\n\t\t\t\tvalidatedSettings[channel] = [];\n\t\t\t\tcompatibilityIssues[channel] = [];\n\t\t\t\t\n\t\t\t\tfor (var f = 0; f < theSettings[channel].length; f++) {\n\t\t\t\t\tfilter = theSettings[channel][f];\n\t\t\t\t\t\n\t\t\t\t\tif (filter.a1 != undefined &&\n\t\t\t\t\t\tfilter.a2 != undefined &&\n\t\t\t\t\t\tfilter.b0 != undefined &&\n\t\t\t\t\t\tfilter.b1 != undefined &&\n\t\t\t\t\t\tfilter.b2 != undefined) {\n\t\t\t\t\t\t// We have coefficients. Expects A0 to always be 1.\n\t\t\t\t\t\tif (filter.samplingRate) {\n\t\t\t\t\t\t\tcompatibility = 0;\n\t\t\t\t\t\t} else if (samplingRate) {\n\t\t\t\t\t\t\tfilter.samplingRate = samplingRate;\n\t\t\t\t\t\t\tcompatibility = 0;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcompatibility = 2;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (filter.type != undefined) {\n\t\t\t\t\t\tswitch (filter.type) {\n\t\t\t\t\t\t\tcase \"peak\":\n\t\t\t\t\t\t\t\tif (filter.frequency != undefined &&\n\t\t\t\t\t\t\t\t \tfilter.Q != undefined && \n\t\t\t\t\t\t\t\t \tfilter.gain != undefined) {\n\t\t\t\t\t\t\t\t\tcompatibility = 0;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tcompatibility = 2;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"lowShelf\":\n\t\t\t\t\t\t\t\tif (filter.frequency != undefined &&\n\t\t\t\t\t\t\t\t \tfilter.Q != undefined && \n\t\t\t\t\t\t\t\t \tfilter.gain != undefined) {\n\t\t\t\t\t\t\t\t\tcompatibility = 0;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tcompatibility = 2;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"highShelf\":\n\t\t\t\t\t\t\t\tif (filter.frequency != undefined &&\n\t\t\t\t\t\t\t\t \tfilter.Q != undefined && \n\t\t\t\t\t\t\t\t \tfilter.gain != undefined) {\n\t\t\t\t\t\t\t\t\tcompatibility = 0;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tcompatibility = 2;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"lowPass\":\n\t\t\t\t\t\t\t\tif (filter.frequency != undefined) {\n\t\t\t\t\t\t\t\t\tcompatibility = 0;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tcompatibility = 2;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"highPass\":\n\t\t\t\t\t\t\t\tif (filter.frequency != undefined) {\n\t\t\t\t\t\t\t\t\tcompatibility = 0;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tcompatibility = 2;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tcompatibility = 2;\n\t\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\n\t\t\t\t\tif (compatibility == 0) {\n\t\t\t\t\t\tif (f+1 > canControlEqualiser[channel]) compatibility = 4;\n\t\t\t\t\t\tvalidatedSettings[channel].push(filter);\n\t\t\t\t\t} else if (compatibility == 2) {\n\t\t\t\t\t\t// Unsupported filters can be left out.\n\t\t\t\t\t\t//validatedSettings[channel].push(false);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tcompatibilityIssues[channel].push(compatibility);\n\t\t\t\t}\n\t\t\t\tif (canControlEqualiser[channel] == 0) {\n\t\t\t\t\tcompatibilityIssues[channel] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn {compatibilityIssues: compatibilityIssues, validatedSettings: validatedSettings, previewProcessor: \"equaliser.generateSettingsPreview\"};\n\t}",
"_validateKey(settingsKey, settingsValue) {\n if (!settingsKey) return false;\n // debug.log(`Validating ${settingsValue}...`);\n const passValidation = (\n settingsKey.type === 'array' && Array.isArray(settingsValue)\n || ['float', 'integer', 'number'].includes(settingsKey.type) && typeof(settingsValue) === 'number'\n || typeof(settingsValue) === settingsKey.type\n ) ? true : false;\n // debug.log(passValidation);\n return passValidation;\n }",
"function checkSettings (settings) {\n if (!settings.script) {\n throw Error(\"camel-harness: No 'script' is defined!\");\n }\n}",
"function validate_settings(settings, options) {\n console.log(\"Reading settings from config file\");\n var missing = [];\n for (var idx in options) {\n if (settings[options[idx]] === undefined) missing.push(options[idx]);\n }\n if (missing.length > 0) {\n // app is terminated if settings are missing\n throw new Error('Required settings ' + (missing.join(', ')) + ' missing.');\n }\n}",
"function checkSettings() {\r\n var errors = [];\r\n for (var key in settings) {\r\n if (!settings[key]) {\r\n errors.push(settings[key]);\r\n }\r\n }\r\n ieVersion() && errors.push(\"NO IE 7\");\r\n return errors;\r\n }",
"function checkSettings() {\n if (typeof(settings)==\"undefined\") return false;\n return (settings.version == expected_settings_version);\n}",
"function CheckSettings(number, value)\n{\n var check = false;\n \n switch (number)\n {\n case 1 : // Check XBMC Connection\n check = true;\n break;\n \n case 2 : // Check XBMC Port\n check = isDecimal(value);\n break;\n \n case 3 : // Set XBMC Username\n check = true;\n break;\n \n case 4 : // Check XBMC Password\n check = true;\n break; \n \n case 6 : // Check Fargo Username\n check = true;\n break;\n \n case 7 : // Check Fargo Password\n check = true;\n break; \n \n case 9 : // Check Timer\n if (value > 299 && value <= 3000) {\n check = true;\n } \n break; \n }\n \n return check;\n}",
"function checkSettings (settings) {\n if (!settings.executable) {\n throw Error(\"executable-harness: No 'executable' is defined!\");\n }\n}",
"checkLinkSettings($link, settings)\n {\n // go through each setting, if any fail, then it cannot pass!\n for(var i in settings)\n {\n var option = settings[i],\n attr = `data-xivdb-${option}`;\n\n // IF the settings are false, then pass is false\n if (XIVDBTooltips.getOption(option) === false) {\n return false;\n }\n\n // IF the attribute is not undefined\n // AND the attribute is false\n if (typeof $link.attr(attr) !== 'undefined' && ($link.attr(attr) == '0' || $link.attr(attr).toLowerCase() == 'false')) {\n return false;\n }\n }\n\n return true;\n }",
"function validateSettings(options) {\n if (!options) {\n throw new Error('No options specified.');\n }\n\n if (!options.host) {\n throw new Error('The CPPM host must be set.');\n }\n\n if (!options.token) {\n if (!options.clientId) {\n throw new Error('The CPPM API Client ID (clientId) must be specified.');\n }\n\n if (!options.clientSecret) {\n throw new Error('The CPPM API Client Secret or a valid Token must be specified.');\n }\n }\n}",
"function validate_timer_setting(){\n for(let key1 in timer_setting){\n for(let key2 in timer_setting[key1]){\n if(timer_setting[key1][key2]==0){\n return 1;\n }\n }\n }\n}",
"function checkSettings() {\n var ui = SpreadsheetApp.getUi() // Grab UI for alerts\n \n if (settingsArray[2][0] == \"TRUE\" || settingsArray[8][0] == \"TRUE\") { // If email is checked\n if (settingsArray[2][1] == \"\" || settingsArray[2][2] == \"\" || settingsArray[2][3] == \"\" || settingsArray[6][2] == \"\" || settingsArray[6][3] == \"\") { // If slots are empty\n var result = ui.alert( // Alert\n 'Error',\n 'Email settings are incomplete. Please verify email settings and links.',\n ui.ButtonSet.OK\n ) \n return false\n }\n }\n \n if (settingsArray[3][0] == \"TRUE\") { // If Twitter is checked\n if (settingsArray[3][1] == \"\" || settingsArray[3][2] == \"\" || settingsArray[3][3] == \"\" || settingsArray[3][4] == \"\") {\n var result = ui.alert(\n 'Error',\n 'Twitter settings are incomplete. Please verify Twitter settings.',\n ui.ButtonSet.OK\n ) \n return false \n }\n }\n \n if (settingsArray[4][0] == \"TRUE\") { // If Slides is checked\n if (settingsArray[4][1] == \"\" || settingsArray[4][2] == \"\") {\n var result = ui.alert(\n 'Error',\n 'Slides settings are incomplete. Please verify Slides settings and links.',\n ui.ButtonSet.OK\n ) \n return false \n }\n }\n \n if (settingsArray[5][0] == \"TRUE\") { // If image is checked\n if (settingsArray[5][1] == \"\" || settingsArray[6][2] == \"\" || settingsArray[6][3] == \"\") {\n var result = ui.alert(\n 'Error',\n 'Image settings are incomplete. Please verify image settings and links.',\n ui.ButtonSet.OK\n ) \n return false \n }\n }\n \n \n return true\n}",
"isInvalidGenerationSettings() {\n\t\treturn this.state.numEasyBots === 0 && this.state.numMedBots === 0 && this.state.numHardBots === 0;\n\t}",
"function isPgSettingValid(pgSetting) {\n const supportedSettingTypes = ['string', 'number'];\n if (supportedSettingTypes.indexOf(typeof pgSetting) >= 0) {\n return true;\n }\n if (pgSetting === undefined || pgSetting === null) {\n return false;\n }\n throw new Error(`Error converting pgSetting: ${typeof pgSetting} needs to be of type ${supportedSettingTypes.join(' or ')}.`);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replaces instruction text and handles button opacity to indicate whether user is at first/last step | function replaceStep(){
d3.select('#step_instructions').text(recipe.instructions[currStepId].text);
//Determine button opacity
if (currStepId == recipe.instructions.length-1){
d3.select('#next')
.style('opacity', '.2');
} else if (currStepId == 0){
d3.select('#back')
.style('opacity', '.2');
d3.select('#next')
.style('opacity', '1');
} else if (currStepId == 1){
d3.select('#back')
.style('opacity', '1');
} else if (currStepId == recipe.instructions.length-2){
d3.select('#next')
.style('opacity', '1');
}
} | [
"function displayInstructions() {\n instructions.html('Click once for eraser. Click again for pen.');\n}",
"function changeStepText(){\n\t$('.step-counter').text('Step: ' + (stepNumber + 1));\t//Show current step number above drawing area\n\t\n\tif (stepNumber == 0){\n\t\t$('.btn-prev').css('visibility', 'hidden');\n\t} else{\n\t\t$('.btn-prev').css('visibility','visible')\t//View/hide previous button\n\t}\n\n\tif (stepNumber == drawingArray.length - 1){\n\t\t$('.btn-next').css('visibility', 'hidden');\n\t} else {\n\t\t$('.btn-next').css('visibility','visible')\t//View/hide next button\n\t}\n}",
"function instruct(ev){\n instructButton.animate({transform: \"s2.0\"},100,\"linear\"); //Added animation to make the start become bigger to show instructions\n instructText.hide();\n instructions.show();\n okButton.show();\n okText.show();\n }",
"displayInstructions() {\n //wait a few seconds for the instruction button to appear\n if (this.instructionsCurrentTimer < this.instructionsAppearanceTime && frameCount % 60 === 0) {\n this.instructionsCurrentTimer++\n }\n\n //when the timer has passed, instructions button will appear\n if (this.instructionsCurrentTimer >= this.instructionsAppearanceTime) {\n\n ////button\n //If you hover over the instructions, the background button will appear gradually, otherwise it will disappear gradually (max alpha of 255, minimum of 0)\n if (mouseX > this.instructionsPositionX - this.instructionsButtonWidth / 2 &&\n mouseX < this.instructionsPositionX + this.instructionsButtonWidth / 2 &&\n mouseY > this.instructionsPositionY - this.instructionsButtonHeight / 2 &&\n mouseY < this.instructionsPositionY + this.instructionsButtonHeight / 2) {\n if (this.instructionsButtonColor.a < this.buttonMaximumAlpha) {\n this.instructionsButtonColor.a += this.buttonModifiedAlphaValue\n }\n } else {\n if (!this.instructionsButtonOpened) {\n if (this.instructionsButtonColor.a > this.buttonMinimumAlpha) {\n this.instructionsButtonColor.a -= this.buttonModifiedAlphaValue\n }\n }\n }\n //Display button\n push();\n rectMode(CORNERS);\n noStroke();\n fill(this.instructionsButtonColor.r, this.instructionsButtonColor.g, this.instructionsButtonColor.b, this.instructionsButtonColor.a);\n rect(this.instructionsButtonUpperCornerX, this.instructionsButtonUpperCornerY, this.instructionsButtonBottomCornerX, this.instructionsButtonBottomCornerY, this.instructionsButtonRoundedCorner)\n pop();\n\n ////string\n //display the string\n push();\n // textFont(this.instructionsFont);\n fill(this.instructionsFill.r, this.instructionsFill.g, this.instructionsFill.b);\n textAlign(CENTER, CENTER);\n textSize(this.instructionsTextSize);\n text(this.instructionsString, this.instructionsPositionX, this.instructionsPositionY)\n pop();\n }\n }",
"function displayInstruction1()\n{\n\tvar text = new PIXI.Text('The switches have to be in the right sequence to leave the room.'\n\t\t\t\t\t\t,{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'});\n\t\t\t\t\t\t\n\ttitleScreen.visible = false;\n\t\n\tcreditsScreen.visible = false;\n\t\n\tgame.visible = false;\n\t\n\tendScreen.visible = false;\n\t\n\tpuzzleRoom1.visible = false;\n\t\n\tinstruciton1.addChild(backBtnRoom1);\n\t\n\tinstruciton1.addChild(text);\n\t\n\tinstruciton1.visible = true;\n}",
"function displayInstruction() {\n background(255, 0, 0);\n}",
"function updateDemoText() {\n $(\".explanation-section\").fadeOut(100).promise().done(function() {\n $(\".explanation-section[data-step='\" + step + \"']\").fadeIn(500);\n });\n\n // $(\"#explanation-\" + step).show();\n $(\"#step\").html(step);\n }",
"function displayInstruction() {\n\n\n // text instruction will be displayed for 10s;\n if (time < 600) {\n instruction(190, 140);\n time++;\n\n }\n\n // text fade out 1: after 10s fade the color of the text and the background\n // this stays on screen for about 3s.\n if (time >= 600 && time < 800) {\n instruction(180, 145);\n time++;\n\n }\n\n // text fade out 2: after 13s fade the color of the text and the background a bit more\n // this stays on screen for about another 3s. \n // Then the instruction disappears.\n if (time >= 800 && time < 1000) {\n instruction(170, 150);\n time++;\n\n }\n\n}",
"showHideInstructions(){\n\t\t//console.log(this.instructionPanel);\n\t\t\n\t\tthis.clickSound.play();\n\t\t\n\t\tif(this.instructionPanel.alpha == 0.0){\n\t\t\tthis.instructionPanel.alpha = 1.0;\n\t\t\tthis.instructionText.alpha = 1.0;\n\t\t}\n\t\telse {\n\t\t\tthis.instructionPanel.alpha = 0.0;\n\t\t\tthis.instructionText.alpha = 0.0;\n\t\t}\n\t}",
"function enableSteps() {\n $(\"#plusButtons\").css(\"opacity\",1);\n $(\"#plusSwish\").css(\"opacity\",1);\n $(\"#step2\").css(\"opacity\",1);\n $(\"#step3\").css(\"opacity\",1);\n $(\"#plusButtons span.button\").css(\"cursor\",\"pointer\");\n $(\"swish-QR\").removeAttr(\"src\");\n}",
"function updateNextEnablementAndText() {\n if(vm.currentWizardStep === \"wizard-select-tables\") {\n updateFirstPageEnablement();\n } else if(vm.currentWizardStep === \"wizard-view-definition\") {\n vm.nextButtonTitle = $translate.instant('shared.Finish');\n } else if(vm.currentWizardStep === \"wizard-join-definition\") {\n vm.nextButtonTitle = $translate.instant('shared.Next');\n } else if(vm.currentWizardStep === \"wizard-join-criteria\") {\n vm.nextButtonTitle = $translate.instant('shared.Finish');\n }\n }",
"function updateNextEnablementAndText() {\n if(vm.currentWizardStep === \"wizard-select-connection\") {\n updateFirstPageEnablementAndMessage();\n } else if(vm.currentWizardStep === \"wizard-jdbc-filter-options\") {\n vm.nextButtonTitle = $translate.instant('shared.Finish');\n }\n }",
"function modify_instructions(){\n if (hidden_text){\n $('#instruction_set').show(instruction_speed);\n document.getElementById('instruction_button').text = 'Hide Instructions';\n hidden_text = false;\n } else {\n $('#instruction_set').hide(instruction_speed);\n document.getElementById('instruction_button').text = 'Show Instructions';\n hidden_text = true;\n }\n}",
"function instructionPageState() {\n checkBackButtonPressed();\n instructionPage.displayInstructionPopUp();\n instructionPage.displayBackButton();\n}",
"function renderStep(){\n\t\tbackButton.removeAttr(\"disabled\");\n\t\tnextButton.val(settings.textNext);\n\n\t\t\tif(previousStep != undefined){\n\t\t\t\tsteps.eq(previousStep).hide()\n\t\t\t\t\t.find(\":input\")\n\t\t\t\t\t.attr(\"disabled\",\"disabled\");\n\t\t\t}\n\n\t\t\tsteps.eq(currentStep)\n\t\t\t.fadeIn()\n\t\t\t.find(\":input\")\n\t\t\t.removeAttr(\"disabled\");\n\n\t\tif(isLastStep){\n\t\t\tfor(var i = 0; i < activatedSteps.length; i++){\n\t\t\t\tsteps.eq(activatedSteps[i]).find(\":input\").removeAttr(\"disabled\");\n\t\t\t}\n\t\t\tnextButton.val(settings.textSubmit);\n\t\t}else if(currentStep == 0){\n\t\t\tbackButton.attr(\"disabled\",\"disabled\");\n\t\t}\n\t}",
"function updateCurrentStep() {\ncurrent_step_text.innerHTML = recipe[current_step];\n}",
"static hostBtnSingleStep_click(btn) {\n /// Must do this first so the text label updates properly\n _SingleStepMode = !_SingleStepMode;\n /// Single Step Mode active\n if (_SingleStepMode) {\n /// Enable the \"Next Step\" button\n document.getElementById(\"btnNextStep\").disabled = false;\n document.getElementById(\"btnNextStep\").style.backgroundColor = \"#007acc\";\n /// Show user that single step mode is ON\n document.getElementById(\"btnSingleStepMode\").value = \"Single Step OFF\";\n } /// if\n /// Single Step Mode \n else {\n /// Enable the \"Next Step\" button\n document.getElementById(\"btnNextStep\").disabled = true;\n document.getElementById(\"btnNextStep\").style.backgroundColor = '#143e6c';\n /// Visually show user that single step mode is OFF\n document.getElementById(\"btnSingleStepMode\").value = \"Single Step ON\";\n } /// else\n _KernelInterruptPriorityQueue.enqueueInterruptOrPcb(new TSOS.Interrupt(SINGLE_STEP_IRQ, []));\n }",
"function greyOutBtn() {\r\n $('.undoButton').css({ 'opacity': '1.0' });\r\n $('.redoButton').css({ 'opacity': '1.0' });\r\n if (undoStack.length < 1) {\r\n $('.undoButton').css({ 'opacity': '0.4' });\r\n }\r\n if (redoStack.length < 1) {\r\n $('.redoButton').css({ 'opacity': '0.4' });\r\n }\r\n }",
"setStatusLine(text) {\n _loader().default.setTextAndRestart(text);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
determin if all properties has empty values in an object | static isObjectPropertyAllHasEmptyValue(object) {
if (lodash.isObject(object)) {
for (var key in object) {
if (
object[key] !== "" &&
!this.isEmptyArray(object[key]) &&
!this.isEmpty(object[key])
) {
return false;
}
}
}
return true;
} | [
"function isAllKeysAreEmpty(obj) {\n\n\tif (isEmpty(obj)) {\n\t\tconsole.log('Obbject is empty');\n\t\treturn true;\n\t}\n\n\tfor(var key in obj) {\n\t\tif ((obj[key] != null) && (obj[key].trim().length>0)) {\n\t\t\t// Does it have some value, then return true\n\t\t\treturn false;\n\t\t}\n\t}\t\t\t\n\t// If we are here all keys are either null or spaces\n\treturn true;\n}",
"function isEmptyProperties( props ) {\n for (var k in props) {\n if (!props.hasOwnProperty(k)) {\n continue;\n }\n return false;\n }\n return true;\n}",
"isEmpty (obj) {\n return Object.keys(obj).length === 0 && obj.constructor === Object\n }",
"function checkEmptyObject(obj) {\n return Object.keys(obj).length <= 0;\n }",
"function isEmpty() {\n return Object.keys(this.value()).length === 0;\n}",
"function nonEmptyObject (data) {\n return object(data) && Object.keys(data).length > 0;\n }",
"function nonEmptyObject(data) {\n return object(data) && Object.keys(data).length > 0;\n }",
"function object_isEmpty( obj )\n{\n if ( !obj )\n return true ;\n else\n return (Object.keys(obj).length == 0);\n}",
"function isEmpty(ob) {\n for (var prop in ob)\n return false;\n return true;\n}",
"function emptyObject (data) {\n\t return object(data) && Object.keys(data).length === 0;\n\t }",
"function emptyObject (data) {\n return object(data) && Object.keys(data).length === 0;\n }",
"function emptyObject (data) {\n return object(data) && Object.keys(data).length === 0;\n }",
"function _isEmptyObject(v) {\n return _isObject(v) && Object.keys(v).length === 0;\n}",
"function checkPropsAreNull(obj) {\n for(var key in obj) {\n if (obj[key]) return false;\n }\n return true;\n}",
"static isEmptyObject(variable) {\n return Object.keys(variable).length === 0;\n }",
"_emptyProp (propName) {\n return !this[propName] || (typeof this[propName] === 'object' && Object.keys(this[propName]).length === 0)\n }",
"is_empty(value) {\n return (\n (value == undefined) ||\n (value == null) ||\n (value.hasOwnProperty('length') && value.length === 0) ||\n (value.constructor === Object && Object.keys(value).length === 0)\n )\n }",
"function allPropertiesTrue(obj) {\n var allTrue = true;\n for (var property in obj) {\n if (obj.hasOwnProperty(property) && !obj[property]) {\n allTrue = false;\n break;\n }\n }\n return allTrue;\n }",
"function isEmptyObject(obj) {\n return obj.constructor === Object && Object.keys(obj).length === 0;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change header and squares to the color picked (Display) | function correctColorDisplay(){
header.style.backgroundColor = colorPicked;
for(var x=0; x<squares.length; x++){
squares[x].style.backgroundColor = colorPicked;
squares[x].style.opacity = "1";
}
} | [
"function ColorSelection() {\n\n selectedColor = color(`rgba(${c.map((dat) => dat)})`);\n hueVarr = Math.round(hue(selectedColor));\n\n //h % 180\n fill(color(`rgba(${c.map((dat) => dat)})`));\n push();\n fill(100,0,100);\n textSize(12);\n text(\"Primary Secondary\", width/4 * 3, height/20, 120, 25);\n fill(255, 255, 255, 51);\n pop();\n rect(width/4 * 3, height/10, 50, 50);\n\n fill(hueVarr > 180 ? hueVarr / 2 : hueVarr * 2, 100, 100)\n rect(width/4 * 3 + 50, height/10, 50, 50);\n\n bColorsPicked = true;\n //PaintButton.show();\n}",
"function squareColoring(){\r\n\t\t\tfor(var i = 0; i < squares.length; i++){\r\n\t\t\t\t\t\r\n\t\t\t\tsquares[i].style.backgroundColor = colors[i];\r\n\t\t\t}\r\n\t\t\th1.style.backgroundColor = \"steelblue\";\r\n\t\t\tresetButton.textContent = \"New Colors\";\r\n\t\t}",
"function changeColors(color){\n for(var i =0; i<squares.length; i++){\n squares[i].style.backgroundColor = color;\n header.style.backgroundColor = color;\n }\n}",
"function changeColors(rgb) {\n for (var i = 0; i < mode; i++) {\n squares[i].style.backgroundColor = rgb;\n }\n h1.style.backgroundColor = rgb;\n}",
"function changeColor() {\n squares.forEach(function(box) {\n box.style.backgroundColor = pickedColor;\n });\n headingBackground.style.backgroundColor = pickedColor;\n}",
"function setMatchColor() {\n bigHeader.style.backgroundColor = \"\";\n matchColor.textContent = getRandomColorNmb(); // Overall function\n return;}",
"function changeColor() {\n var randomColor = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' +\n (Math.floor(Math.random() * 256)) + ',' +\n (Math.floor(Math.random() * 256)) + ')';\n header.animate({ color: randomColor }, 2500);\n changeColor();\n }",
"function changeColors(rgb) {\n if(rgb === winningColor) {\n h1.style.background = `${winningColor}`;\n for( let i = 0; i < squares.length; i++) {\n squares[i].style.background = `${winningColor}`;\n }\n }\n}",
"function changeHeader() {\n let headerColor = makeRandomColor();\n document.getElementById('headerColor').style.color = headerColor;\n}",
"set mainColor(value) {}",
"function displayColor(color)\n{\n\tfor(var i=0;i<squares.length;i++)\n\t{\n \t\tsquares[i].style.background=color;\n\t}\n}",
"function titleColor(activeFrame) {\n $('#name').css('color', `${mountainLeftColors[activeFrame]}`);\n $('#portfolio').css('color', `${mountainRightColors[activeFrame]}`);\n}",
"function setMatchColor() {\n bigHeader.style.backgroundColor = \"\";\n matchColor.textContent = getRandomColorNmb(); // Overall function\n}",
"function generateMainColors(){\n for(var i = 0; i < mode; i++){\n colorDisplay[i].style.backgroundColor = rgbColorGenerator();\n }\n }",
"function changeColorOfHeader(desiredColor) {\n console.log(`Attempting to Change Color...`)\n var colorTag = document.createElement(\"style\");\n function colorToRGBA(color) {\n // Returns the color as an array of [r, g, b, a] -- all range from 0 - 255\n // color must be a valid canvas fillStyle. This will cover most anything\n // you'd want to use.\n // Examples:\n // colorToRGBA('red') # [255, 0, 0, 255]\n // colorToRGBA('#f00') # [255, 0, 0, 255]\n var cvs, ctx;\n cvs = document.createElement('canvas');\n cvs.height = 1;\n cvs.width = 1;\n ctx = cvs.getContext('2d');\n ctx.fillStyle = color;\n ctx.fillRect(0, 0, 1, 1);\n return ctx.getImageData(0, 0, 1, 1).data;\n }\n\n function byteToHex(num) {\n // Turns a number (0-255) into a 2-character hex number (00-ff)\n return ('0'+num.toString(16)).slice(-2);\n }\n\n function colorToHex(color) {\n // Convert any CSS color to a hex representation\n // Examples:\n // colorToHex('red') # '#ff0000'\n // colorToHex('rgb(255, 0, 0)') # '#ff0000'\n var rgba, hex;\n rgba = colorToRGBA(color);\n hex = [0,1,2].map(\n function(idx) { return byteToHex(rgba[idx]); }\n ).join('');\n return \"#\"+hex;\n }\n\n function shadeColor(color, percent) {\n //I found this online. I have no idea how it works, but you just need to put the color in as a Hex code (by using the conversion functions above), and the percent as a decimal between -1 and 1 (-.2 is darkening 20%, .5 is lightening 50%, etc.)\n //It outputs a Hex string. If you input a nonsense Hex color or a percentage out of the range, it will still run, but it will output a nonsense Hex color.\n var f=parseInt(color.slice(1),16),t=percent<0?0:255,p=percent<0?percent*-1:percent,R=f>>16,G=f>>8&0x00FF,B=f&0x0000FF;\n return \"#\"+(0x1000000+(Math.round((t-R)*p)+R)*0x10000+(Math.round((t-G)*p)+G)*0x100+(Math.round((t-B)*p)+B)).toString(16).slice(1);\n }\n function changeColor(){\n //Finds the header element and actually executes the color change by changing the header element's background color. desiredColor pulls from the parent function; the color change will work with all valid HTML color names or with Hex codes.\n //There are some manually translated colors in here (like an \"if\" statement for \"red\") because the default HTML color looks stupid. You can also add custom extra colors to be recognized like gradients, however the outlines will be black for gradients.\n console.log(`Changing header`); //For debug purposes. If this prints in console, it means the function was run.\n //var headerElementID = document.getElementsByClassName(\"_2t-a _26aw _5rmj _50ti _2s1y\")[0].id;\n //var headerElement = document.getElementById(headerElementID);\n var headerElement = document.querySelector(`[role = \"banner\"],[data-sigil = \"MTopBlueBarHeader\"]`);\n //This finds Facebook's header element based on it's role and data-sigil characteristics. Facebook sometimes changes characteristics of its web elements\n //so if that happens, you may need to update this with better, or more accurate characteristics so the add-on can find it.\n if (desiredColor === \"red\") { //default HTML red looks dumb. This makes it a darker, more professional red. Courtesy of Elder Berrett.\n desiredColor = \"#dd3b3b\";\n }\n else if (desiredColor === \"blue\") {//same thing for blue. This makes it look like \"Facebook Blue\" which is the default color\n desiredColor = \"#4267b2\";\n }\n else if (desiredColor === \"green\") {\n desiredColor = \"#28a13f\";\n }\n else if (desiredColor === \"yellow\") {\n desiredColor = \"#ead600\";\n } else if (desiredColor === \"rainbow\"){ //This is adding a custom color (or colors). We are manually setting the input \"rainbow\" to be accepted, and then to return a custom gradient.\n desiredColor = \"linear-gradient(to left, #dd3b3b,orange,#ead600,#28a13f,#4267b2,indigo,violet)\";\n }\n headerElement.style.background = desiredColor; //This actually sets the headerElement as the color we want based on the HTML color word or the hex value based on the if/then statements right before this.\n }\n function changeBorderColor(){ //When we change the header color, the border looks really dumb because it stays dark blue by default. This changes the border (of the header bar and the search bar inside the header bar) to a\n //darkened version of the color that we're changing the header too.\n console.log(`Changing border`); //This is printed out in the console so we know that the function ran. Used for debugging.\n var outlineElement = document.querySelector(`[role = \"banner\"],[data-sigil = \"MTopBlueBarHeader\"]`); //This selects the header bar and designates it as \"outlineElement\"\n var searchElement = document.querySelector(`[role = \"search\"], [data-testid = \"facebar_root\"]`); //This selects the search bar and designates it as \"searchElement\"\n var popOver = document.querySelector(`.popoverOpen`);\n var desiredBorderColor = \"#29487d\"; //This makes the default\n if (desiredColor === \"blue\") {\n desiredBorderColor = \"#29487d\"\n }\n else {\n //console.log(\"I'm line 106\");\n desiredBorderColor = colorToHex(desiredColor);\n //console.log(desiredBorderColor);\n desiredBorderColor = shadeColor(desiredBorderColor, -0.2);\n //console.log(desiredBorderColor);\n //console.log(\"I'm going to try to spit out popOver:\");\n //console.log(popOver);\n //if(popOver){\n // popOver.style.background = desiredBorderColor;\n //}\n\t colorTag.innerHTML = `.popoverOpen > a {background : ${desiredBorderColor}}`;\n\t document.head.appendChild(colorTag);\n outlineElement.style.borderBottom = `1px solid ${desiredBorderColor}`;\n searchElement.style.border = `1px solid ${desiredBorderColor}`;\n searchElement.style.borderBottom = `1px solid ${desiredBorderColor}`;\n }\n }\n if (document.readyState === \"loading\") { //Occasionally, it'll try to load before the page has loaded the Document Object Model (DOM). This is an issue. This checks if it's loaded or not.\n document.addEventListener(\"DOMContentLoaded\", changeColor); //Once the DOM is loaded, it will then fire the main function.\n document.addEventListener(\"DOMContentLoaded\", changeBorderColor); //Once the DOM is loaded, it will then fire the main function.\n document.addEventListener(\"DOMContentLoaded\", function(){setTimeout(changeBorderColor, 3000)});\n } else { // `DOMContentLoaded` already fired, so the DOM has been loaded.\n console.log(desiredColor); //debug\n changeColor(); //Run that puppy.\n console.log(desiredColor);\n changeBorderColor(); //debug\n console.log(desiredColor); //debug\n }\n}",
"function displayColor(){\n textSize(35);\n if(colorState === 1){\n fill(\"red\");\n text(\"Red\", 1225, 360);\n }\n if(colorState === 2){\n fill(\"blue\");\n text(\"Blue\", 1225, 360);\n }\n if(colorState === 3){\n fill(\"green\");\n text(\"Green\", 1225, 360);\n }\n if(colorState === 4){\n fill(\"orange\");\n text(\"Orange\", 1225, 360);\n }\n if(colorState === 5){\n fill(\"black\");\n text(\"Black\", 1225, 360);\n }\n if(colorState === 6){\n fill(\"white\");\n text(\"White\", 1225, 360);\n }\n}",
"function repeat(){\n color = generateRandomColors(numSquares);\n pick = pickedColor();\n //change display color to picked color\n displayColor.textContent = pick;\n for(var i = 0 ; i < square.length ; i++)\n {\n if(color[i])\n {\n square[i].style.display = \"block\";\n square[i].style.backgroundColor = color[i];\n }\n else{\n square[i].style.display = \"none\";\n }\n \n }\n \n h1.style.backgroundColor = \"steelblue\";\n newColors.textContent = \"New Colors\";\n displayFeedback.textContent = \"\";\n\n\n\n}",
"function changeHeaderColor(){\r\n var color = getRandomColor()\r\n header.style.color = color \r\n}",
"function squareColor() {\n //Color the squares according to user choice\n var color1 = $(\"#color1\").spectrum(\"get\");\n var color2 = $(\"#color2\").spectrum(\"get\");\n for (let i = 0; i < square.length; i++) {\n if (square[i].hasAttribute(\"data-owner\")) {\n var owner = square[i].getAttribute(\"data-owner\");\n if (owner == 1) {\n $(square[i]).css(\"background-color\", color1);\n }\n else if (owner == 2) {\n $(square[i]).css(\"background-color\", color2);\n };\n };\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an array of all worker of a country in relation the the whole data set. The array don't check the worker type. | createWorkerSeries() {
const arr = this.state.whitelistEvents
const result = Object.values(
arr.reduce((c, { country }) => {
c[country] = c[country] || {
label: country,
value: 0,
colorIndex: COUNTRIES[country].color
}
c[country].value++
return c
}, {})
)
return result
} | [
"function createAvailabilityByWorker(nworkers, availabilityByDay) {\n var result = [];\n var ndays = availabilityByDay.length;\n for (let iworker = 0; iworker < nworkers; iworker++) {\n result.push([]); //make new array for that worker\n for (let iday = 0; iday < ndays; iday++) {\n if (availabilityByDay[iday].includes(iworker)) {\n result[iworker].push(iday); //if assigned, push to worker's array\n }\n }\n }\n return result;\n}",
"function createAssignmentsByWorker(nworkers, assignmentsByDay) {\n var result = [];\n var ndays = assignmentsByDay.length;\n for (let iworker = 0; iworker < nworkers; iworker++) {\n result.push([]); //make new array for that worker\n for (let iday = 0; iday < ndays; iday++) {\n if (assignmentsByDay[iday] == iworker) {\n result[iworker].push(iday); //if assigned, push to worker's array\n }\n }\n }\n return result;\n}",
"getCountries() {\n for (let i = 2; i < this.originData.length; i++) {\n this.countries.push(this.originData[i][1]);\n }\n }",
"getCountries() {\n for (let i = 2; i < this.originData.length; i++) {\n this.countries.push(this.originData[i][1]);\n }\n }",
"function createArrayFromAllCountries(countriesData) {\r\n let v = new Array();\r\n for (let i=0; i<countriesData.length; i++) {\r\n v.push(countriesData[i]);\r\n }\r\n createCountriesOnScreen(v); \r\n}",
"function fillCountriesArray(country,continent) {\n const countryObj = {\n name: country.name.common,\n code: country.cca2,\n }\n world[continent].countriesArray.push(countryObj);\n}",
"async function allCountriesData(proxy) {\n\n let countryByname = [];\n let continent = {};\n\n const countrySrc = `${proxy}https://restcountries.herokuapp.com/api/v1`;\n const getdata = await fetch(countrySrc);\n let allCountries = await getdata.json();\n // console.log(allCountries);\n\n for (country of allCountries) {\n countryByname.push([country.name.common, country.cca2, country.region]);\n }\n\n for (country of countryByname) {\n if (country[2] in continent) {\n continent[country[2]].push([country[0], country[1]]);\n }\n else {\n continent[country[2]] = [[country[0], country[1]]];\n }\n }\n // console.log(countryByname);\n // console.log(continent);\n return [countryByname, continent];\n}",
"get associatedWorkers() {\n if (this._workerEntities) {\n return Object.keys(this._workerEntities);\n } else {\n return [];\n }\n }",
"function GetWeeklyCountAllCountriesArray(countries) {\n var countriesArrary = [];\n var i = 0;\n for (var countrykey in countries) {\n\n if (GetTotalCountOfWeekDays(countries[countrykey].RecentHistory.WeeklyHistory) != 0) {\n countriesArrary[i] = countries[countrykey];\n i++;\n\n }\n }\n return countriesArrary;\n}",
"function filteredWorkerFn(arr) {\n const filteredArr = arr.reduce((acc, current) => {\n const x = acc.find(item => item.workerId === current.workerId);\n if (!x) {\n return acc.concat([current]);\n } else {\n return acc;\n }\n }, []);\n return filteredArr;\n}",
"static async getCountries() {\n let countries = [];\n try {\n countries = await salaryData.distinct(\"Country\");\n return countries;\n } catch (e) {\n console.error(`Unable to get countries, ${e}`);\n return countries;\n }\n }",
"async loadWorkerTypes() {\n // Here we load a list of objects which are the worker types. make it a list of objects\n // so we can use map and filter nicely\n }",
"getTripData (arr, type) {\n const returnArr = []\n for (const trip of arr) {\n returnArr.push(this.tripFetch[type](trip))\n }\n return returnArr\n }",
"async function getContinentData(type) {\n const info = await getDataOfCountryInContinent();\n continentData = [];\n info.forEach(country => {\n if (country.region != \"\") {\n continentData.push(country[type])\n }\n })\n currentChartData.dataArr = continentData;\n myChart.data.datasets[0].data = currentChartData.dataArr;\n}",
"async function continetAnalize(countries) {\n\n let continentData = [];\n for (const [key, value] of Object.entries(countries)) {\n let continent = {};\n continent.name = key;\n continent.cases = 0;\n continent.death = 0;\n continent.recovered = 0;\n continent.critical = 0;\n continent.countries = [];\n\n for (ele of value) {\n if (ele[1] != \"XK\") {\n let src = `https://corona-api.com/countries/${ele[1]}`;\n const getdata = await fetch(src);\n let allData = await getdata.json();\n\n let cases = allData.data.latest_data.confirmed;\n let death = allData.data.latest_data.deaths;\n let recovered = allData.data.latest_data.recovered;\n let critical = allData.data.latest_data.critical;\n\n let country = {};\n country.name = `${ele[0]}`;\n country.cases = cases;\n country.death = death;\n country.recovered = recovered;\n country.critical = critical;\n\n continent.countries.push(country);\n\n continent.cases += cases;\n continent.death += death;\n continent.recovered += recovered;\n continent.critical += critical;\n\n }\n }\n continentData.push(continent);\n }\n console.log(`finished!`);\n return continentData;\n}",
"deliveries() {\n let deliveries = []\n this.employees().forEach(employee =>{\n deliveries.push(employee.deliveries())\n })\n return [].concat.apply([], deliveries)\n\n }",
"function buildCountriesArray()\n{\n COUNTRIES_ARRAY = new Array(N_COUNTRIES);\n for (var i = 0; i < N_COUNTRIES; ++i)\n {\n COUNTRIES_ARRAY[i] = new Array(2); // Contents: 'countryID', 'countryName'.\n\n COUNTRIES_ARRAY[i]['countryID' ] = Number(getNextWordFromCodedData());\n eatWhiteSpaceFromCodedData();\n COUNTRIES_ARRAY[i]['countryName'] = getRemainingLineFromCodedData();\n }\n}",
"deliveries() {\n let allDeliveries = this.employees().map((employee) => employee.deliveries())\n return [].concat.apply([], allDeliveries);\n }",
"getCountries_urban_rural(){\n var datas=this.readFile(this.csv4);\n\n\n\n\n\nconst countries=new Set(); /* the reason to use set is it will not hold \n repetive value; since we have a dataset which \n loops over repetetive names alot.\n */\n\n datas.map(country=>{\n countries.add(country.Entity);\n })\n\n return Array.from(countries);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getY :: Cell > Integer | function getY(cell) {
return cell[1];
} | [
"function getCellno(x, y) {\n\treturn x*50 + y\n}",
"getY(index) {\n return this.xy[index * 2 + 1];\n }",
"function _getY() {\r\n\t\t\tvar sortedTiles = self.tiles.sort(function (a, b) {\r\n\t\t\t\tif (a.y != b.y)\r\n\t\t\t\t\treturn a.y - b.y;\r\n\t\t\t\treturn a.x - b.x;\r\n\t\t\t});\r\n\t\t\treturn self.isOneColumnView() ? 4 * sortedTiles.indexOf(self.tile) : self.tile.y;\r\n\t\t}",
"getY(index) {\n return this.xy[index * 2 + 1];\n }",
"function getY() {\n return this.y;\n }",
"function getScrollYCell () {\n var scrollY = document.getElementById(\"scrollbar\").scrollTop;\n return ~~(scrollY / defaultCellHeight)+1; \n}",
"function yForRow(row: number, height: number=style.READ_HEIGHT, spacing: number=style.READ_SPACING): number {\n return (row * (height + spacing));\n}",
"getY() {\n\t\treturn ( 800 - this.ty ) * 32 + terrain.getYOffset( game.tyoff );\n\t}",
"function getY(tileId){\n\treturn (tileId - (tileId % 8)) / 8;\n}",
"function getCell(x,y){\n return $('.grid-cell[data-coord=\"' + y + '-' + x + '\"]');\n }",
"function boardY (y) { return (y - 1) * 2 }",
"getAt(x, y) {\n this.checkBounds(x, y);\n return this.cells[y * this.width + x];\n }",
"function getCell (x,y) {\n\treturn gridArray[y][x];\n}",
"function getCellHeight(yCoord) {\n //return (yCoord%10)+15;\n if (yCoord == 10) return 2*defaultCellHeight;\n return defaultCellHeight;\n}",
"function getCell(x, y)\n{\n if(x >= BOARD_ROW_LENGTH) { x = 0; }\n if(y >= BOARD_COL_LENGTH) { y = 0; }\n if(x < 0) { x = BOARD_ROW_LENGTH -1; }\n if(y < 0) { y = BOARD_COL_LENGTH -1; }\n\n return $(cells[y * BOARD_COL_LENGTH + x]);\n}",
"getY(x) {\n let y = ((((x - this.x1) * (this.y2 - this.y1)) / (this.x2 - this.x1)) + this.y1).trim(9);\n if (isNaN(y) || y.isBetween(this.y1, this.y2)) return y;\n }",
"function _getY(annotation) {\n\t\n\t if (annotation.rectangles) {\n\t return annotation.rectangles[0].y;\n\t } else if (annotation.y1) {\n\t return annotation.y1;\n\t } else {\n\t return annotation.y;\n\t }\n\t}",
"valueAt(x, y){\n return this.ticTacToeGameBoard[x][y];\n }",
"function _getY(annotation) {\n\n if (annotation.rectangles) {\n return annotation.rectangles[0].y;\n\n } else if (annotation.y1) {\n return annotation.y1;\n\n } else {\n return annotation.y;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets all row data in the inventory sheet, stores cell data as Object (eg. items[U603]['description'] = "Uni Foam Air Filter") returns string (JSON.stringify(Object)) | function getInvData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Master Inventory');
var lastColumn = sheet.getLastColumn();
var range = sheet.getRange(firstBarcodeRow,firstBarcodeColumn,masterLastRow,lastColumn);
var invData = range.getValues();
var headers = getHeaders(sheet,range,1);
Logger.log("headers = " + headers)
var items = {};
for (var m in invData) {
// We want to rename the object properties for columns not likely to change.
// We want to dynamically add all location column headers.
// Because these new column headers aren't constants, we'll need to add them separately using a for loop
var item = {};
item['description'] = invData[m][0];
item['partNumber'] = invData[m][1];
items['locationsList'] = {};
// Location columns will change over time, this adds ALL column headers after column 5 (headers[4], "Location") to the new item Object
for (var i = firstLocationIndex; i < headers.length; ++i) {
item[headers[i]] = invData[m][i];
//Create location properties from the headers. Used in the html scripts to check if the barcode entered is a location or a part
items['locationsList'][headers[i]] = "";
}
items[item.partNumber] = item; // assign this info to an object key = Part Number (eg. items['MX2030']['description'] = "12.5:1 Piston Kit")
}
return JSON.stringify(items)
} | [
"function soldItems() {\n const table = document.getElementById('sale');\n const rows = table.rows;\n const data = [];\n for (let r = 2; r < rows.length; r++) {\n const row = rows[r];\n const product = {\n prod_name: row.cells[0].innerHTML,\n quantity: parseInt(row.cells[1].innerHTML),\n };\n data.push(product);\n }\n return data;\n}",
"function getInventory()\n {\n var userData = getUserData();\n\n return userData.inventory;\n }",
"function node_get_all_inventory_data() {\n node_do_query('SELECT * from inventory');\n}",
"getAllItems() {\n return this.inventory.flattenInventory();\n }",
"function convertRowsToObjects(itemRows){var items = [];itemRows.map(function(o){var row=o,item={};o.Cells.results.map(function(a){item[a.Key]=item[a.Value]});items.push(item)});return items;}",
"function get_json() {\n try{\n no_of_VMs_to_be_created = columns_to_fetch_data.length\n var columnKeys = {B: 'key'}\n var i=1\n columns_to_fetch_data.forEach(key => {\n columnKeys[key] = `value${i}`\n i=i+1\n }); \n var JSON = excelToJson({\n source: fs.readFileSync(excel_file),\n header:{ rows: 1 },\n sheets: [sheet_name],\n range: 'A1:L34',\n columnToKey: columnKeys\n });\n result = JSON[sheet_name]\n }catch(err){\n console.log('Error occurred while getting JSON of VM sheet')\n console.log('Error: ',err)\n } \n}",
"function printInventory(id) {\n if (!charSheets[id]) {\n console.log(\"no such sheet with id \" + id + \" to print inventory\");\n return null;\n }\n var outputString = \"\";\n var invItems = charSheets[id].inventory.items;\n for (var item in invItems) {\n outputString = outputString + item + \":\\n\";\n for (var stat in invItems[item]) {\n outputString += \"\\t\" + stat + \": \" + invItems[item][stat] + \"\\n\";\n }\n }\n return outputString;\n}",
"function displayInventory() {\n for (var i = 0; i < currentInventory.length; i++) {\n console.log(currentInventory[i].item_id + \" | \" + currentInventory[i].product_name + \" | \" + currentInventory[i].department_name + \" | \" + currentInventory[i].price + \" | \" + currentInventory[i].stock_quantity);\n }\n}",
"get rows() {\n\t\treturn this.get('rows').toJSON();\n\t}",
"function mapInventoryToString(items) {\n return items.map((item) => {\n return `${item.name} $${item.price}`\n })\n}",
"function getInventory() {\n\n\tconnection.query(\"SELECT * FROM `products`\", function (err, results, fields) {\n\t\tif (err) throw err;\n\t\t\n\t\t// set global variable to the # of records in the db for validation later with user prompts\n\t\tnumProducts = results.length;\n\n\t\tconsole.log(\"\");\n\t\tconsole.log(\" ID Product Name Price \".yellow);\n\t\tconsole.log(\"----------------------------------------------\");\n\t\t\n\t\t// loop through the results from the select query on the products table\n\t\tfor (var i = 0; i < results.length; i++) {\n\t\t\tconsole.log(formatTableData(results[i].item_id, results[i].product_name, results[i].price));\n\t\t}\n\n\t\tconsole.log(\"----------------------------------------------\");\n\t\t\n\t\tpromptUserID();\n\n\t});\n\n}",
"function workbookToJson() {\n var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();\n var output = {};\n _.each(sheets, function(sheet, sheetIdx) {\n var outSheet = {};\n var sheetArrays = sheet.getDataRange().getValues();\n var columnHeaders = sheetArrays[0];\n _.each(columnHeaders, function(columnHeader) {\n if (columnHeader === '_rowNum') {\n throw new Error(\"_rowNum is not a valid column header.\");\n }\n });\n var outSheet = _.map(sheetArrays.slice(1), function(row, rowIdx) {\n //_rowNum is added to support better error messages.\n var outRow = {}; //Object.create({ __rowNum__ : (rowIdx + 1) });\n outRow.prototype = {\n __rowNum__: (rowIdx + 1)\n };\n _.each(row, function(val, valIdx) {\n outRow[columnHeaders[valIdx]] = val;\n });\n return outRow;\n });\n output[sheet.getName()] = outSheet;\n });\n return output;\n}",
"get rowData() {\n if (this.inEditMode) {\n return lodash_mergewith__WEBPACK_IMPORTED_MODULE_6___default()(cloneValue(this._rowData), this.grid.transactions.getAggregatedValue(this.rowID, false), (objValue, srcValue) => {\n if (Array.isArray(srcValue)) {\n return objValue = srcValue;\n }\n });\n }\n return this._rowData;\n }",
"function itemItemToRow(item) {\n var row =\n \"<tr><td><label>Item Name</label></td><td><label>\" + item.name + \"</label></td></tr>\"+\n \"<tr><td><label>University</label></td><td><label>\" + item.university + \"</label></td></tr>\"+\n \"<tr><td><label>Location</label></td><td><label>\" + item.location + \"</label></td></tr>\"+\n \"<tr><td><label>Price</label></td><td><label>$\" + item.price + \"</label></td></tr>\"+\n \"<tr><td><label>Quantity</label></td><td><label>\" + item.quantity + \"</label></td></tr>\"+\n \"<tr><td><label>Condition</label></td><td><label>\" + item.condition + \"</label></td></tr>\"+\n \"<tr><td><label>Description</label></td><td><label>\" + item.description + \"</label></td></tr><tr></tr><tr></tr>\";\n return row;\n }",
"function displayInventory() {\n\tqueryStr = 'SELECT * FROM bamazondb.products';\n\tconnection.query(queryStr, function(err, data) {\n\t\tif(err) throw err;\n\n\t\tconsole.log(\"Current Inventory: \");\n\t\tconsole.log(\"...........................................................................................................\\n\");\n\n\t\tvar strOut = '';\n\t\tfor (var i = 0; i < data.length; i++) {\n\t\t\tstrOut = '';\n\t\t\tstrOut = 'Item ID: ' + data[i].item_id + ' // ';\n\t\t\tstrOut += 'Product Name: ' + data[i].product_name + ' // ';\n\t\t\tstrOut += 'Department: ' + data[i].department_name + ' // ';\n\t\t\tstrOut += 'Price: $' + data[i].customer_price + ' // ';\n\t\t\tstrOut += 'Quantity: ' + data[i].stock_quantity + '\\n';\n\n\t\t\tconsole.log(strOut);\n\t\t}\n\n\t\tconsole.log(\"-----------------------------------------------------------------------------------------------------------\\n\");\n\t\tpromptUserPurchase();\n\t})\n}",
"function itemInventoryTable() { }",
"function displayInventory() {\n let invString = \"Inventory: [\"\n for (let i = 0; i < inventory.length; i++) {\n invString += inventory[i].itemString()\n if(i != inventory.length-1)\n invString += \", \"\n }\n invString += \"]\"\n document.getElementById(\"inventory\").innerText = invString\n}",
"static async getAllRows() {\n return (await sheet).sheetsByIndex[0].getRows();\n }",
"function handleGetInventory(err, iv){\n if(err) throw err;\n pokemon = iv.inventory_delta.inventory_items.map(function(item){\n return item.inventory_item_data.pokemon\n });\n fs.writeFileSync(FILENAME, JSON.stringify(pokemon));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a ImplementationGuideDependency resource | static get __resourceType() {
return 'ImplementationGuideDependency';
} | [
"fixDependsOn(dependency, igs) {\n // Clone it so we don't mutate the original\n const dependsOn = lodash_1.cloneDeep(dependency);\n if (dependsOn.version == null) {\n // No need for the detailed log message since we already logged one in the package loader.\n utils_1.logger.error(`Failed to add ${dependency.packageId} to ImplementationGuide instance because no ` +\n `version was specified in your ${this.configName}.`);\n return;\n }\n if (dependsOn.uri == null) {\n // Need to find the URI from the IG in the FHIR cache\n const dependencyIG = igs.find(ig => ig.packageId === dependsOn.packageId &&\n (ig.version === dependsOn.version ||\n 'current' === dependsOn.version ||\n 'dev' === dependsOn.version));\n dependsOn.uri = dependencyIG === null || dependencyIG === void 0 ? void 0 : dependencyIG.url;\n if (dependsOn.uri == null) {\n utils_1.logger.error(`Failed to add ${dependsOn.packageId}:${dependsOn.version} to ` +\n 'ImplementationGuide instance because SUSHI could not find the IG URL in the ' +\n `dependency IG. To specify the IG URL in your ${this.configName}, use the dependency ` +\n 'details format:\\n\\n' +\n 'dependencies:\\n' +\n ` ${dependsOn.packageId}:\\n` +\n ' uri: http://my-fhir-ig.org/ImplementationGuide/123\\n' +\n ` version: ${dependsOn.version}`);\n return;\n }\n }\n if (dependsOn.id == null) {\n // packageId should be \"a..z, A..Z, 0..9, and _ and it must start with a..z | A..Z\" per\n // https://chat.fhir.org/#narrow/stream/215610-shorthand/topic/SUSHI.200.2E12.2E7/near/199193333\n // depId should be [A-Za-z0-9\\-\\.]{1,64}, so we replace . and - with _ and prepend \"id_\" if it does not start w/ a-z|A-Z\n dependsOn.id = /[A-Za-z]/.test(dependsOn.packageId[0])\n ? dependsOn.packageId.replace(/\\.|-/g, '_')\n : 'id_' + dependsOn.packageId.replace(/\\.|-/g, '_');\n }\n return dependsOn;\n }",
"get implementationGuide () {\n\t\treturn this._implementationGuide;\n\t}",
"static get __resourceType() {\n\t\treturn 'ImplementationGuidePackageResource';\n\t}",
"function Dependency(Class, minVersion, maxVersion) {\n /// <summary>\n /// The public class.\n /// </summary>\n this.Class = \"\";\n /// <summary>\n /// The public minimum version.\n /// </summary>\n this.minVersion = \"\";\n /// <summary>\n /// The public maximum version.\n /// </summary>\n this.maxVersion = \"\";\n this.Class = Class;\n this.minVersion = minVersion;\n this.maxVersion = maxVersion;\n }",
"addDependency(resource) {\n const customResource = this.customResource.node.tryFindChild('Default');\n if (customResource && cfn_resource_1.CfnResource.isCfnResource(customResource)) {\n customResource.addDependsOn(resource);\n }\n }",
"depend() {\n if ( Dep.target ) {\n Dep.target.addDep( this );\n }\n }",
"function getImplementationGuide() {\n return require(`${BASE_DIR}/ig-new.json`);\n}",
"function Dep () {\n\t this.subs = []\n\t}",
"get dependencies() {\n return [];\n }",
"function Dep () {\n\t\t this.subs = []\n\t\t}",
"addDependency(spec) {\n this.project.deps.addDependency(spec, deps_1.DependencyType.RUNTIME);\n }",
"constructor(dependency, afterCreateCb = () => {}) {\n this.id = dependency.id;\n this.title = dependency.title;\n this.authors = dependency.authors;\n this.year = dependency.year;\n this.url = dependency.url;\n\n afterCreateCb(this);\n\n this.dependencies = buildDependencies(dependency.dependencies);\n }",
"function depend () {\n\tvar args = Array.prototype.slice.call(arguments, 0);\n\tvar comp = args.shift();\n\tcomponents[comp] = {\n\t\tdependencies: args\n\t}\n\tprettyLog('info','COMPONENT ' + comp + ' DEFINED WITH DEPENDENCIES ' + (args.length ? args.join(', ') : '-NONE-'));\n\t\n}",
"injectIntoDependence () {\n const dependence = new Dependence(this.module || this.name)\n if (!this.module) dependence.resolved = false\n dependence.addChild(this.name)\n\n return dependence\n }",
"constructor() {\n /**\n *\n * @member {Array.<module:models/ProductReferenceOCC>} references\n */\n this.references = undefined\n }",
"addDependsOn(serviceName) {\n this.dependsOn.push(serviceName);\n }",
"function DependsOnContainer(Container) {\n this.container = Container;\n}",
"getDataGuide() {\n errors.throwNotImplemented(\"getting the data guide for the collection\");\n }",
"static get __resourceType() {\n\t\treturn 'ImplementationGuideGlobal';\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
onPageInit (run only once) | function onPageInit(e){
} | [
"function onPageInit(e){\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t}",
"function initPage() {\n checkAndSetTheme();\n initSelectedPage();\n}",
"function pageBeforeInit(pageData) {\n // todo\n\n } // end pageInit",
"function init() {\r\n // page load init function\r\n}",
"function init () {\n if (!isHomePage) return\n bindUIEvents()\n }",
"function init() {\n if ($('.scheduled-page').length > 0) {\n setPageUrl();\n bindEvents();\n renderSwitcher();\n renderActions();\n switchPage(data.currentView);\n }\n }",
"function initLandingPage() {\n\n}",
"function init() {\n if ($('.scheduled-page').length > 0) {\n setPageUrl();\n bindEvents();\n renderSwitcher();\n renderActions();\n switchPage(scheduled.currentView);\n }\n }",
"function initPage() { \n if(getAllowance() <= 0) {\n add();\n }\n }",
"function init() {\n if (Enabler.isPageLoaded()) {\n startAnim();\n } else {\n Enabler.addEventListener(studio.events.StudioEvent.PAGE_LOADED, startAnim);\n }\n}",
"function onPageLoad() {\n\n\t\t// load some code\n\n\t}",
"function onPageLoad() {\n\n\n\n\t}",
"function initPage() {\n\tset_hidden_elements();\n}",
"function initializePage() {\n pageComponents.tv.css('margin-left', '8.4%');\n pageComponents.body.css('overflow', 'hidden');\n pageComponents.body.css(\"background\", \"white\");\n pageComponents.header.hide();\n }",
"function initPage() {\n\n // 1. Select control\n // nothing to do - no options in index.html\n\n // 2. Demographic info card\n // nothing to do - its spans are empty in index.html\n\n // 3. Horizontal Bar Chart\n initHBar();\n\n // 4. Gauge\n initGauge();\n\n //5. Bubble chart\n initBubble();\n\n}",
"function onPageLoad()\n\t{\n\t\t//Set page size\n\t\tSetSize();\n\t\t//Persist page settings\n\t\tloadPreferences();\n\t}",
"function onPageEnter(){\n onEnterInit();\n}",
"static init_first_page() {\n\n if (!PageController.items.length) { PageController.new_page() }\n else { PageController.on_click_page(PageController.items[0].id) }\n }",
"function init() {\n if ($('.detail-page').length > 0) {\n renderLoader();\n setArticleParams();\n getArticle();\n bindEvents();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Easy 1838 239 Add to List Share An image is represented by a 2D array of integers, each integer representing the pixel value of the image (from 0 to 65535). Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image. To perform a "flood fill", consider the starting pixel, plus any pixels connected 4directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor. At the end, return the modified image. Example 1: Input: image = [[1,1,1],[1,1,0],[1,0,1]] sr = 1, sc = 1, newColor = 2 Output: [[2,2,2],[2,2,0],[2,0,1]] Explanation: From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected by a path of the same color as the starting pixel are colored with the new color. Note the bottom corner is not colored 2, because it is not 4directionally connected to the starting pixel. | function s(
image = [
[1, 1, 1],
[1, 1, 0],
[1, 0, 1],
],
sr = 1,
sc = 1,
newColor = 2
) {
const originalColor = image[sr][sc];
helper(sr, sc, 1);
return image;
function helper(r, c) {
console.log({ r, c });
if (
r < 0 ||
r > image.length - 1 ||
c < 0 ||
c > image[r].length - 1 ||
image[r][c] !== originalColor
)
return;
image[r][c] = newColor;
helper(r + 1, c);
helper(r, c + 1);
helper(r - 1, c);
helper(r, c - 1);
}
} | [
"function flood_fill(image_data, canvas_width, canvas_height, x, y, color) {\n\n var components = 4; //rgba\n\n // unpack values\n var fillColorR = color[0];\n var fillColorG = color[1];\n var fillColorB = color[2];\n\n // get start point\n var pixel_pos = (y*canvas_width + x) * components;\n var startR = image_data[pixel_pos];\n var startG = image_data[pixel_pos + 1];\n var startB = image_data[pixel_pos + 2];\n\n function matchStartColor(pixel_pos) {\n return startR == image_data[pixel_pos] &&\n startG == image_data[pixel_pos+1] &&\n startB == image_data[pixel_pos+2];\n }\n\n function colorPixel(pixel_pos) {\n image_data[pixel_pos] = fillColorR;\n image_data[pixel_pos+1] = fillColorG;\n image_data[pixel_pos+2] = fillColorB;\n image_data[pixel_pos+3] = 255;\n }\n\n var pixelStack = [[x, y]];\n\n while(pixelStack.length)\n {\n var newPos, x, y, pixel_pos, reachLeft, reachRight;\n newPos = pixelStack.pop();\n x = newPos[0];\n y = newPos[1];\n\n pixel_pos = (y*canvas_width + x) * components;\n while(y-- >= 0 && matchStartColor(pixel_pos))\n {\n pixel_pos -= canvas_width * components;\n }\n pixel_pos += canvas_width * components;\n ++y;\n\n var sides = [];\n sides[-1] = false;\n sides[1] = false;\n\n function trace(dir) {\n if(matchStartColor(pixel_pos + dir*components)) {\n if(!sides[dir]) {\n pixelStack.push([x + dir, y]);\n sides[dir]= true;\n }\n }\n else if(sides[dir]) {\n sides[dir]= false;\n }\n }\n\n while(y++ < canvas_height-1 && matchStartColor(pixel_pos)) {\n colorPixel(pixel_pos);\n\n // left side\n if(x > 0) {\n trace(-1);\n }\n\n // right side\n if(x < canvas_width-1) {\n trace(1);\n }\n pixel_pos += canvas_width * components;\n\n }\n }\n}",
"function floodFill(imageDataTemp, canvas, x0,y0, toFlood, color) \r\n {let tumpukan= [];\r\n tumpukan.push({x : x0, y : y0});\r\n while(tumpukan.length> 0) \r\n {var titikSkrg= tumpukan.shift();\r\n var indexSkrg= 4 * (titikSkrg.x+ titikSkrg.y* canvas.width);\r\n var r1 = imageDataTemp.data[indexSkrg+ 0];\r\n var g1 = imageDataTemp.data[indexSkrg+ 1];\r\n var b1 = imageDataTemp.data[indexSkrg+ 2];\r\n \r\n if((r1 == toFlood.r) && (g1 == toFlood.g) && (b1 == toFlood.b)) \r\n {imageDataTemp.data[indexSkrg+ 0] = color.r;\r\n imageDataTemp.data[indexSkrg+ 1] = color.g;\r\n imageDataTemp.data[indexSkrg+ 2] = color.b;\r\n imageDataTemp.data[indexSkrg+ 3] = 255;\r\n \r\n tumpukan.push({x:titikSkrg.x+1, y:titikSkrg.y});\r\n tumpukan.push({x:titikSkrg.x-1, y:titikSkrg.y});\r\n tumpukan.push({x:titikSkrg.x, y:titikSkrg.y+1});\r\n tumpukan.push({x:titikSkrg.x, y:titikSkrg.y-1});\r\n }}}",
"function floodfill(e){\n //directions to move in floodfill\n const xDirections = [0,0,1,-1];\n const yDirections = [1,-1,0,0];\n\n imgData = ctx.getImageData(0,0,canv.width, canv.height);\n\n const startCoords = getMousePos(canv, e, scale);\n const startX = Math.floor(startCoords.x);\n const startY = Math.floor(startCoords.y);\n let idx = ((startY * canv.width) + startX)* 4;\n let startColor;\n\n if(!matchColor(imgData.data[idx], imgData.data[idx+1],imgData.data[idx + 2],[0,0,0])){\n startColor = [imgData.data[idx], imgData.data[idx+1],imgData.data[idx + 2]];\n }else{\n return;\n }\n if(arrayEquals(startColor,curColor)){\n return;\n }\n\n let stack = [[startY, startX]];\n let currPos;\n let newX, newY;\n while(stack.length > 0){\n currPos = stack.pop();\n for(let i = 0; i < 4;i++){\n newY = currPos[0] + yDirections[i];\n newX = currPos[1] + xDirections[i];\n idx = ((newY * canv.width) + newX)* 4;\n if(coordsValid(newX, newY, canv)){\n //check if pixel color is same as starting color\n if(matchColor(imgData.data[idx], imgData.data[idx+1],imgData.data[idx + 2],startColor)){\n stack.push([newY, newX]);\n colorPixel((newY * canv.width + newX)* 4, curColor[0],curColor[1],curColor[2], imgData);\n }\n }\n }\n }\n ctx.putImageData(imgData, 0,0);\n }",
"floodFill(startI, startJ, color) {\n // this is a list of painted coordinates\n const coordinates = [];\n // this is a queue for the algorithm\n const queue = [[startI, startJ]];\n let index = 0; // starting index of queue\n\n // go through the flood coordinates, tacking on new points to coordinates.\n const totalPoints = this.rows * this.cols;\n for (let protectIndex = 0; protectIndex < totalPoints; protectIndex++) {\n // if we're at the end of the array-queue, we're finished.\n if (index == queue.length)\n break;\n\n // if already flooded, move on.\n const I = queue[index][0], J = queue[index][1];\n if (this.board[I][J] == -1) {\n index++;\n continue;\n }\n\n // set initial point to be flooded\n this.board[I][J] = -1;\n coordinates.push([I, J]);\n\n // expand north and south, filling out nodes between north and south\n let n = I, s = I;\n while (n > 0) {\n if (this.board[n - 1][J] == color) {\n this.board[n - 1][J] = -1;\n coordinates.push([n - 1, J]);\n }\n else\n break;\n\n n--;\n }\n while (s < this.rows - 1) {\n if (this.board[s + 1][J] == color) {\n this.board[s + 1][J] = -1;\n coordinates.push([s + 1, J]);\n }\n else\n break;\n\n s++;\n }\n\n // add nodes to the left and right to the end of the array-queue if necessary.\n for (let i = n; i <= s; i++) {\n if (J > 0 && this.board[i][J - 1] == color) {\n queue.push([i, J - 1]);\n }\n if (J < this.cols - 1 && this.board[i][J + 1] == color) {\n queue.push([i, J + 1]);\n }\n }\n\n // move on to the next part of the queue\n index++;\n }\n\n return coordinates;\n }",
"function floodFill4(image, pixel, fillColor) {\r\n\r\n // TODO 2.2a) Perform the flood fill algorithm,\r\n // taking into account only the four \r\n // direct neighbours of the pixel. The\r\n // variable \"fillColor\" denotes the color\r\n // for both the area and the border.\r\n\r\n // get the color at pixel location, use getPixel()\r\nvar color=getPixel(image,pixel);\r\n\r\n\r\n\r\n // base case \r\n // - color channels of the current color are equal to the color channels of the fillColor\r\n // - pixel position is out of range?\r\nif(color==null||color.r==fillColor.r&&color.g==fillColor.g&&color.b==fillColor.b){return;}\r\n\r\n\r\n // set pixel color\r\nvar x=pixel.x;\r\nvar y=pixel.y;\r\n\tsetPixel(image,pixel,fillColor);\r\n\tvar pixelxr=new Point(x+1,y);\r\n\tvar pixelxl=new Point(x-1,y);\r\n\tvar pixelyr=new Point(x,y+1);\r\n\tvar pixelyl=new Point(x,y-1);\r\n\r\n\r\n // start recursion (4 neighboring pixels)\r\nfloodFill4(image,pixelxr,fillColor);\r\nfloodFill4(image,pixelxl,fillColor);\r\nfloodFill4(image,pixelyl,fillColor);\r\nfloodFill4(image,pixelyr,fillColor);\r\n\r\n\r\n}",
"function paintFill(image, point, newColor, oldColor) {\n if (!oldColor) oldColor = image[point[0]][point[1]];\n image[point[0]][point[1]] = newColor;\n if (image[point[0]-1] && image[point[0]-1][point[1]] === oldColor) paintFill(image, [point[0]-1, point[1]], newColor, oldColor);\n if (image[point[0]+1] && image[point[0]+1][point[1]] === oldColor) paintFill(image, [point[0]+1, point[1]], newColor, oldColor);\n if (image[point[0]][point[1]-1] === oldColor) paintFill(image, [point[0], point[1]-1], newColor, oldColor);\n if (image[point[0]][point[1]+1] === oldColor) paintFill(image, [point[0], point[1]+1], newColor, oldColor);\n}",
"function floodFill(x,y,selectedColor,colorToReplace){\n if(x==undefined || y == undefined || selectedColor==undefined){ //keine farbe gesetzt\n return;\n }\n\n if(x<0 || x >= 16 || y<0 || y >= 16){ //wenn out of bounds\n return;\n }\n\n var pixel = document.getElementById(\"pixel-\"+x+\"-\"+y); //den pixel wo es hin soll\n if(pixel.style.backgroundColor==colorToReplace){ //wenn selbe farbe wie der erste gewählte Pixel\n pixel.style.backgroundColor = selectedColor; //setze die farbe\n //und nun rekursive aufrufe\n floodFill(x-1,y,selectedColor,colorToReplace); //links\n floodFill(x+1,y,selectedColor,colorToReplace); //rechts\n floodFill(x,y-1,selectedColor,colorToReplace); //unten\n floodFill(x,y+1,selectedColor,colorToReplace); //oben\n }\n}",
"function floodFill(event, canvas, floodColor) {\r\n // make a promise so that we can enforce synchronous order to events\r\n let startPromise = new Promise((resolve, reject) => {\r\n document.body.style.cursor = \"progress\"; // change cursor to loading\r\n\r\n setTimeout(() => resolve(), 100); // setTimeout forces the CSS batch of changes to update (usually it would wait til the end)\r\n });\r\n startPromise\r\n .then(() => { // once the promise is done (changing cursor), do floodfill\r\n let canvasPos = canvas.getBoundingClientRect();\r\n let startX = event.clientX - canvasPos.left;\r\n let startY = event.clientY - canvasPos.top;\r\n\r\n let context = canvas.getContext(\"2d\");\r\n let clickedColor = context.getImageData(startX, startY, 1, 1).data;\r\n\r\n let pixelStack = [[startX, startY]];\r\n\r\n let matchStartColor = (x, y) => {\r\n let thisColor = context.getImageData(x, y, 1, 1).data;\r\n return thisColor.every((e, i) => e === clickedColor[i]);\r\n };\r\n\r\n let colorPixel = (x, y) => {\r\n let valStr = floodColor.substring(floodColor.indexOf(\"(\") + 1, floodColor.length - 1).split(\", \");\r\n let vals = valStr.map(e => parseInt(e, 10));\r\n vals.push(255);\r\n context.putImageData(new ImageData(new Uint8ClampedArray(vals), 1, 1), x, y);\r\n };\r\n\r\n while (pixelStack.length) {\r\n let newPos = pixelStack.pop();\r\n let x = newPos[0];\r\n let y = newPos[1];\r\n\r\n while(y >= 0 && matchStartColor(x, y)) {\r\n y--;\r\n }\r\n\r\n y++;\r\n let reachLeft = false;\r\n let reachRight = false;\r\n while (y < canvas.height - 2 && matchStartColor(x, y)) {\r\n colorPixel(x, y)\r\n\r\n if (x > 0) {\r\n if (matchStartColor(x-1, y)) {\r\n if (!reachLeft) {\r\n pixelStack.push([x - 1, y]);\r\n reachLeft = true;\r\n }\r\n }\r\n else if (reachLeft) {\r\n reachLeft = false;\r\n }\r\n }\r\n\r\n if (x < canvas.width - 2) {\r\n if (matchStartColor(x+1, y)) {\r\n if (!reachRight) {\r\n pixelStack.push([x + 1, y]);\r\n reachRight = true;\r\n }\r\n }\r\n else if (reachRight) {\r\n reachRight = false;\r\n }\r\n }\r\n\r\n y++;\r\n }\r\n }\r\n })\r\n .finally(() => {document.body.style.cursor = \"default\";}); // when floodfill finally ends, change the cursor back\r\n}",
"function floodFill(canvas, start, color){\n up_and_down = start[0]\n left_and_right = start[1]\n console.log(canvas[up_and_down][left_and_right], \"This is the current color\");\n console.log(color, \"This is the new color\");\n if(canvas[up_and_down][left_and_right] !== color){\n canvas[up_and_down][left_and_right] = color;\n }\n if(canvas[up_and_down][left_and_right + 1] !== color && left_and_right + 1 < canvas[up_and_down].length){\n return floodFill(canvas, [up_and_down, left_and_right + 1], color)\n }\n if(canvas[up_and_down][left_and_right - 1] !== color && left_and_right - 1 >= 0){\n return floodFill(canvas, [up_and_down, left_and_right - 1], color)\n }\n if(canvas[up_and_down - 1][left_and_right] !== color && up_and_down - 1 > 0){\n return floodFill(canvas, [up_and_down - 1, left_and_right], color)\n }\n if(canvas[up_and_down + 1][left_and_right] !== color && up_and_down + 1 < canvas.length){\n return floodFill(canvas, [up_and_down + 1, left_and_right], color)\n }\n return canvas\n}",
"function recolorImage(image, colorFunc) {\n var length = image.data.length; //pixel count * 4\n for (var i = 0; i < length; i += 4) {\n if (image.data[i+3] < 255) {\n continue;\n }\n if (image.data[i] === 0) {\n var idx = image.data[i+1] * 0x100 + image.data[i+2];\n var clr = colorFunc(idx);\n if (defined(clr)) {\n for (var j = 0; j < 4; j++) {\n image.data[i+j] = clr[j];\n }\n }\n else {\n image.data[i+3] = 0;\n }\n }\n }\n return image;\n}",
"function floodFill(data,node,targetColor,replacementColor){\n//1. If target-color is equal to replacement-color, return.\n if(targetColor==replacementColor) return;\n//2. Set Q to the empty queue.\n var q=[];var hash={};\n//3. Add node to the end of Q.\n q.push(node);\n//4. While Q is not empty:\n while(q.length){\n //5. Set n equal to the first element of Q.\n var n = q[0];\n //6. Remove first element from Q.\n q.shift();\n //7. If the color of n is equal to target-color:\n if(color(data,n)==targetColor){\n //8. Set the color of n to replacement-color and mark \"n\" as processed.\n setColor(data,n,replacementColor);\n hash[n]=1;\n //9. Add west node to end of Q if west has not been processed yet.\n if(hash[n-4]==undefined){q.push(n-4)}\n //10. Add east node to end of Q if east has not been processed yet.\n if(hash[n+4]==undefined){q.push(n+4)}\n //11. Add north node to end of Q if north has not been processed yet.\n if(hash[n-2000]==undefined){q.push(n-2000)}\n //12. Add south node to end of Q if south has not been processed yet.\n if(hash[n+2000]==undefined){q.push(n+2000)}\n }\n\n }\n//13. Return.\n return;\n}",
"calcFill() {\n let imagePiece = marlon.get(this.left, this.top, this.w, this.h);\n imagePiece.loadPixels();\n\n let r = 0, g = 0, b = 0;\n\n for (let i = 0; i < imagePiece.pixels.length; i += 4) {\n r += imagePiece.pixels[i];\n g += imagePiece.pixels[i + 1]; \n b += imagePiece.pixels[i + 2]; \n }\n r /= (imagePiece.pixels.length / 4);\n g /= (imagePiece.pixels.length / 4);\n b /= (imagePiece.pixels.length / 4);\n\n return color(r, g, b);\n }",
"function fillpixel(event) {\n\n var m = event.target.id.match(/pixel-([0-9]+)-([0-9]+)/i); // matchgroups m[1] and m[2] contain coordinates\n if (m) { // if we clicked a pixel\n\n // val is a number 0 <= val <= 255, return an object with properties x and y for coordinates\n function to_coords(val) {\n return {'x': val % 16,\n 'y': Math.floor(val/16) };\n }\n\n // take coordinates and return a number 0 <= val <= 255 to represent coordinates as an integer\n function from_coords(x,y) {\n return x + y*16;\n }\n\n // return color at given pixel\n function color_at(x,y) {\n console.log(\"x=\"+x+\", y=\"+y+\", id=pixel-\"+x+\"-\"+y);\n return document.getElementById(\"pixel-\"+x+\"-\"+y).style.backgroundColor;\n }\n\n var visited=[]; // list of pixels we already finished looking at\n var tovisit=[]; // list of pixel that we have to look at yet\n var current_color = document.getElementById(\"current-color\").style.backgroundColor;// current color element contains color\n var x = parseInt(m[1]); // must be explicitly converted, otherwise x+w in for loop would be concatenated string\n var y = parseInt(m[2]);\n var color = color_at(x,y); // the color the pixel to be filled had before - we look for connected cells with this color\n\n tovisit.push(from_coords(x,y));\n\n while (tovisit.length) { // while there are still pixels to look at\n var cur = tovisit.shift(); // pick the first pixel\n visited.push(cur); // add it to the visited list (never visit again)\n var curx = to_coords(cur).x;\n var cury = to_coords(cur).y;\n if (color_at(curx, cury) == color) {\n // if this pixel has the same color as the first pixel clicked:\n // 1. we fill ist\n // 2. we add its neighbors to the tovisit list\n document.getElementById(\"pixel-\" + curx + \"-\" + cury).style.backgroundColor = current_color; // fill it\n // each cell has 4 neighbors: left, right, up, down\n var new_coords = [];\n if (curx>0) new_coords.push(from_coords(curx-1,cury));\n if (curx<15) new_coords.push(from_coords(curx+1, cury));\n if (cury<15) new_coords.push(from_coords(curx, cury+1));\n if (cury>0) new_coords.push(from_coords(curx, cury-1));\n\n // we check for each neighbor if it is in bounds and not visited yet -> add to tovisit list.\n for (var i = 0; i < new_coords.length; i++) {\n var c = to_coords(new_coords[i]);\n if (visited.indexOf(new_coords[i]) == -1 && tovisit.indexOf(new_coords[i]) == -1) {\n tovisit.push(new_coords[i]);\n }\n }\n }\n }\n }\n return preview(); // update preview\n}",
"floodBoardWithPassedColor(playedFloodBoard, color, originColor) {\n let result = playedFloodBoard;\n originColor.forEach(index => {\n result[index[0]][index[1]] = color;\n });\n return result;\n }",
"function fillHoles(image, iterations, callback) {\n iterations--;\n new Jimp(image.bitmap.width, image.bitmap.height, white, (err, newImage) => {\n image.scan(0, 0, image.bitmap.width, image.bitmap.height, function (x, y, idx) {\n var color = image.getPixelColor(x, y);\n\n if (color == white) {\n var l = image.getPixelColor(x - 1, y);\n var r = image.getPixelColor(x + 1, y);\n var t = image.getPixelColor(x, y + 1);\n var b = image.getPixelColor(x, y - 1);\n\n var lb = image.getPixelColor(x - 1, y - 1);\n var lt = image.getPixelColor(x - 1, y + 1);\n var rt = image.getPixelColor(x + 1, y + 1);\n var rb = image.getPixelColor(x + 1, y - 1);\n\n var colorCnt = 0;\n if (l != white) {\n colorCnt++;\n }\n if (r != white) {\n colorCnt++;\n }\n if (t != white) {\n colorCnt++;\n }\n if (b != white) {\n colorCnt++;\n }\n if (lb != white) {\n colorCnt++;\n }\n if (lt != white) {\n colorCnt++;\n }\n if (rt != white) {\n colorCnt++;\n }\n if (rb != white) {\n colorCnt++;\n }\n\n if (colorCnt >= 4) {\n newImage.setPixelColor(black, x, y);\n }\n } else {\n newImage.setPixelColor(color, x, y);\n }\n\n if (x == image.bitmap.width - 1 && y == image.bitmap.height - 1) {\n if (iterations <= 0) {\n callback(newImage);\n } else {\n fillHoles(newImage, iterations, callback);\n }\n }\n })\n });\n}",
"function floodfill(map, start, newval){\n\t// map is 2d array we are working on, .length = X\n\t// start is [x,y]\n\t// newval is the val we are changing to\n\t// so check a pixel's value, if we change it, call 'fill' on it?\n\n\t// easy reads\n\tvar x = start[0];\n\tvar y = start [1];\n\t// what we are replacing\n\tvar base_val = map[x][y];\n\t// check the neighbors\n\t// above\n\tif (map[x][y] == base_val){\n\t\tfloodfill(map, [map[x],map[y + 1]], newval);\n\t}\n\t// right\n\tif (map[x][y] == base_val){\n\t\tfloodfill(map, [map[x + 1],map[y]], newval);\n\t}\n\t\t// below\n\tif (map[x][y] == base_val){\n\t\tfloodfill(map, [map[x],map[y - 1]], newval);\n\t}\n\t\t// left\n\tif (map[x][y] == base_val){\n\t\tfloodfill(map, [map[x - 1],map[y]], newval);\n\t}\n\t// fill current\n\tmap[x][y] = newval;\n}",
"function paintFill(screenArr, row, column, newColor) {}",
"floodFill (stack, {channel = 0, threshold = 255}) {\n let pt\n let x\n let y\n let x1\n let spanAbove\n let spanBelow\n const d = this.terr.data\n const w = this.w\n const h = this.h\n\n while (stack.length > 0) {\n pt = stack.pop()\n x = pt[0]\n y = pt[1]\n x1 = x\n while (x1 >= 0 && d[(x1 + y * w) * 4] < threshold) { x1-- }\n x1++\n spanAbove = 0\n spanBelow = 0\n while (x1 < w && d[(x1 + y * w) * 4] < threshold) {\n d[(x1 + y * w) * 4] = 255\n d[channel + (x1 + y * w) * 4] = 255\n if (!spanAbove && y > 0 && d[(x1 + (y - 1) * w) * 4] < threshold) {\n stack.push([\n x1, y - 1\n ])\n spanAbove = 1\n } else if (spanAbove && y > 0 && d[(x1 + (y - 1) * w) * 4] >= threshold) {\n spanAbove = 0\n }\n if (!spanBelow && y < h - 1 && d[(x1 + (y + 1) * w) * 4] < threshold) {\n stack.push([\n x1, y + 1\n ])\n spanBelow = 1\n } else if (spanBelow && y < h - 1 && d[(x1 + (y + 1) * w) * 4] >= threshold) {\n spanBelow = 0\n }\n x1++\n }\n }\n }",
"function floodfill(map, x, y, colorToReplace, colorToUse) {\r\n if (x < 0 || x >= map.width) return;\r\n if (y < 0 || y >= map.height) return;\r\n var tileColor = map.getTileColor(x, y);\r\n if (tileColor === colorToUse) return;\r\n if (tileColor !== colorToReplace) return;\r\n map.setTileColor(x, y, colorToUse);\r\n floodfill(map, x, y - 1, colorToReplace, colorToUse); //floodfill tile to North\r\n floodfill(map, x - 1, y, colorToReplace, colorToUse); //floodfill tile to the West\r\n floodfill(map, x + 1, y, colorToReplace, colorToUse); //floodfill tile to the East\r\n floodfill(map, x, y + 1, colorToReplace, colorToUse); //floodfill tile to the South \r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets or Sets the first line indent for selected paragraphs. | get firstLineIndent() {
return this.firstLineIndentIn;
} | [
"set firstLineIndent(value) {\n if (value === this.firstLineIndentIn) {\n return;\n }\n this.firstLineIndentIn = value;\n this.notifyPropertyChanged('firstLineIndent');\n }",
"getLineStartLeft(widget) {\n let left = widget.paragraph.x;\n let paragraphFormat = widget.paragraph.paragraphFormat;\n if (this.isParagraphFirstLine(widget) && !paragraphFormat.bidi) {\n left += HelperMethods.convertPointToPixel(paragraphFormat.firstLineIndent);\n }\n if (widget.children.length > 0) {\n left += widget.children[0].margin.left;\n }\n return left;\n }",
"isSelectionOnFirstLine() {\n return this.getLineIndex(this.start) === 0;\n }",
"indent() {\n var session = this.session;\n var range = this.getSelectionRange();\n\n if (range.start.row < range.end.row) {\n var rows = this.$getSelectedRows();\n session.indentRows(rows.first, rows.last, \"\\t\");\n return;\n } else if (range.start.column < range.end.column) {\n var text = session.getTextRange(range);\n if (!/^\\s+$/.test(text)) {\n var rows = this.$getSelectedRows();\n session.indentRows(rows.first, rows.last, \"\\t\");\n return;\n }\n }\n \n var line = session.getLine(range.start.row);\n var position = range.start;\n var size = session.getTabSize();\n var column = session.documentToScreenColumn(position.row, position.column);\n\n if (this.session.getUseSoftTabs()) {\n var count = (size - column % size);\n var indentString = lang.stringRepeat(\" \", count);\n } else {\n var count = column % size;\n while (line[range.start.column - 1] == \" \" && count) {\n range.start.column--;\n count--;\n }\n this.selection.setSelectionRange(range);\n indentString = \"\\t\";\n }\n return this.insert(indentString);\n }",
"set leftIndent(value) {\n if (value === this.leftIndentIn) {\n return;\n }\n this.leftIndentIn = value;\n this.notifyPropertyChanged('leftIndent');\n }",
"get baseIndent() {\n let line = this.state.doc.lineAt(this.node.start);\n // Skip line starts that are covered by a sibling (or cousin, etc)\n for (;;) {\n let atBreak = this.node.resolve(line.start);\n while (atBreak.parent && atBreak.parent.start == atBreak.start)\n atBreak = atBreak.parent;\n if (isParent(atBreak, this.node))\n break;\n line = this.state.doc.lineAt(atBreak.start);\n }\n return this.lineIndent(line);\n }",
"get baseIndent() {\n let line = this.state.doc.lineAt(this.node.from);\n // Skip line starts that are covered by a sibling (or cousin, etc)\n for (;;) {\n let atBreak = this.node.resolve(line.from);\n while (atBreak.parent && atBreak.parent.from == atBreak.from)\n atBreak = atBreak.parent;\n if (isParent(atBreak, this.node))\n break;\n line = this.state.doc.lineAt(atBreak.from);\n }\n return this.lineIndent(line.from);\n }",
"lineIndent(line) {\n var _a;\n let override = (_a = this.options) === null || _a === void 0 ? void 0 : _a.overrideIndentation;\n if (override) {\n let overriden = override(line.from);\n if (overriden > -1)\n return overriden;\n }\n return this.countColumn(line.text, line.text.search(/\\S/));\n }",
"lineIndent(line) {\n var _a;\n let override = (_a = this.options) === null || _a === void 0 ? void 0 : _a.overrideIndentation;\n if (override) {\n let overriden = override(line.from);\n if (overriden > -1)\n return overriden;\n }\n return this.countColumn(line.text, line.text.search(/\\S/));\n }",
"get firstLine(){\n return this.linePane.firstChild;\n }",
"get baseIndent() {\n let line = this.state.doc.lineAt(this.node.from);\n // Skip line starts that are covered by a sibling (or cousin, etc)\n for (;;) {\n let atBreak = this.node.resolve(line.from);\n while (atBreak.parent && atBreak.parent.from == atBreak.from)\n atBreak = atBreak.parent;\n if (isParent(atBreak, this.node))\n break;\n line = this.state.doc.lineAt(atBreak.from);\n }\n return this.lineIndent(line);\n }",
"get baseIndent() {\n let line = this.state.doc.lineAt(this.node.start); // Skip line starts that are covered by a sibling (or cousin, etc)\n\n for (;;) {\n let atBreak = this.node.resolve(line.from);\n\n while (atBreak.parent && atBreak.parent.start == atBreak.start) atBreak = atBreak.parent;\n\n if (isParent(atBreak, this.node)) break;\n line = this.state.doc.lineAt(atBreak.start);\n }\n\n return this.lineIndent(line);\n }",
"get selectionStart() {\n return this.i.selectionStart;\n }",
"get leftIndent() {\n return this.leftIndentIn;\n }",
"function lineIndent(editor, line) {\n const lineStr = editor.getLine(line);\n const indent = lineStr.match(/^\\s+/);\n return indent ? indent[0] : '';\n }",
"getIndentation(point) {\n if (this.getCurrentBufferLine(point) != undefined) {\n\n if (this.getCurrentBufferLine(point)[0] != \"\" && this.getCurrentBufferLine(point)[0] == ' ') {\n return this.getIntentLevel(this.getCurrentBufferLine(point), 1);\n } else if (this.getCurrentBufferLine(newPoint)[0] == \"\") {\n return 'Empty';\n } else {\n return 0;\n }\n }\n }",
"getFirstLine() {\n return (this.lines[1] === undefined ? this.lines[0] : this.lines[0].replace(\"\\n\", \" \") + this.lines[1]);\n }",
"function indentOneSpace() {\n utilitymanager_1.um.utilityManager({\n utilType: utilitymanager_1.um.TIXUtilityType.utLineUtility,\n sp: utilitymanager_1.um.TIXSelPolicy.All,\n }, function (up) { return ' ' + up.intext; });\n }",
"function indentOneSpace() {\n utilitymanager_1.um.utilityManager({\n utilType: utilitymanager_1.um.TIXUtilityType.utLineUtility,\n sp: utilitymanager_1.um.TIXSelPolicy.All,\n }, function (up) { return ' ' + up.intext; });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function for opacity based on magnitude | function markerOpacity(magnitude) {
if (magnitude > 6) {
return 1
} else if (magnitude > 5) {
return .90
} else if (magnitude > 4) {
return .80
} else if (magnitude > 3) {
return .70
} else if (magnitude > 2) {
return .60
} else if (magnitude > 1) {
return .50
} else {
return .40
}
} | [
"function markerOpacity(magnitude) {\n if (magnitude > 6) {\n return .99\n } else if (magnitude > 5) {\n return .80\n } else if (magnitude > 4) {\n return .70\n } else if (magnitude > 3) {\n return .60\n } else if (magnitude > 2) {\n return .50\n } else if (magnitude > 1) {\n return .40\n } else {\n return .30\n }\n}",
"get opacity() { return this.alpha * 255; }",
"function markerOpacity(magnitude) {\n return magnitude * .15;\n}",
"function circleOpacityLevel(magnitude) {\r\n var circleOpacity = \"\";\r\n\r\n if (magnitude < 2) {\r\n circleOpacity = 1;\r\n }\r\n else if ((magnitude >= 2) && (magnitude < 3)) {\r\n circleOpacity = .93;\r\n }\r\n else if ((magnitude >= 3) && (magnitude < 4)) {\r\n circleOpacity = .86;\r\n }\r\n else if ((magnitude >= 4) && (magnitude < 5)) {\r\n circleOpacity = .80;\r\n }\r\n else if ((magnitude >= 5) && (magnitude < 6)) {\r\n circleOpacity = .74;\r\n }\r\n else if ((magnitude >= 6) && (magnitude < 7)) {\r\n circleOpacity = .68;\r\n }\r\n else if ((magnitude >= 7) && (magnitude < 8)) {\r\n circleOpacity = .60;\r\n }\r\n else if ((magnitude >= 8) && (magnitude < 9)) {\r\n circleOpacity = .52;\r\n }\r\n else if ((magnitude >= 9) && (magnitude < 10)) {\r\n circleOpacity = .44;\r\n }\r\n else if (magnitude >= 10) {\r\n circleOpacity = .35;\r\n }\r\n\r\n return circleOpacity;\r\n } // end circleOpacityLevel()",
"function opacityBonus() {\n opacity = (parseInt(opacity, 16)-6).toString(16);\n if (parseInt(opacity, 16)<0) { stopOpacity(); loadCar(); }\n else refreshScreen();\n}",
"updateOpacity() {\n // to be overridden by plugins\n }",
"get opacity() {\n return this._opacity * 100;\n }",
"modulate() {\n this.opacity += Math.PI / 100;\n let mod0 = (Math.sin(this.opacity) + 1) / 2;\n let mod1 = (Math.sin(this.opacity * 0.99) + 1) / 2;\n let mod2 = (Math.cos(this.opacity * 0.66) + 1) / 2;\n let mod3 = (Math.cos(this.opacity * 0.33) + 1) / 2;\n this.distortedClassroom0.alpha = mod0;\n this.distortedClassroom1.alpha = mod1;\n this.distortedClassroom2.alpha = mod2;\n this.distortedClassroom3.alpha = mod3;\n }",
"getOpacity() {\n return this.color.alpha;\n }",
"getFogOpacity(minCount, minPosition) {\n let highestOpacity = 200;\n for (let fogInterval of this.fogTimes) {\n let start = fogInterval[0];\n let end = fogInterval[1];\n if (minCount > start && minCount < end) {\n return highestOpacity;\n } else if (minCount === start) {\n return highestOpacity * minPosition / this.framesPerMin;\n } else if (minCount === end) {\n return highestOpacity - (highestOpacity * minPosition / this.framesPerMin);\n }\n }\n return 0;\n }",
"function filterMag(value) {\n g.selectAll(\"circle\").attr(\"opacity\", (d) => {\n return (value < d.properties.mag) ? 1 : 0;\n });\n }",
"opacityMap(value) { \n\t\treturn (value < this.min || this.max < value) ? 0 : 1;\n\t}",
"function controlOpacity(pointCoord,color){\n if(Math.abs(pointCoord[0]) <= fireworkRadius/2 && Math.abs(pointCoord[1]) <= fireworkRadius/2){\n color[3]= 1 - fireworkRadius - Math.abs(pointCoord[0]) - Math.abs(pointCoord[1]);\n }\n else{\n color[3]= 0.3 - fireworkRadius + Math.abs(pointCoord[0]) + Math.abs(pointCoord[1]);\n }\n return vec4(color[0],color[1],color[2],color[3]);\n}",
"get opacity() {\n return this.material.uniforms.opacity.value;\n }",
"getOpacity() {\n let fillOpacity = 255;\n let smallestDistanceToEdge = Math.min(this.x - this.leftMostPoint, this.rightMostPoint - (this.x + this.w));\n if (smallestDistanceToEdge < 70) {\n fillOpacity = map(smallestDistanceToEdge, 70, 20, 200, 0);\n }\n\n return fillOpacity;\n\n }",
"function lowerOpacity() {\n\toverlay_opacity *= gamma;\n\tdocument.getElementById(\"overlay\").style.opacity = overlay_opacity;\n}",
"function updateOpacity(value) {$('.leaflet-imagery-pane').css(\"opacity\", value)}",
"alpha()\n\t{\n\t\treturn Math.round(this.a * 255);\n\t}",
"function getOpacity(opModLoc){\n return map(opModLoc, 400, 570, 255, 1)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get all conversations for a specific user | getUsersConversations(db, user_id) {
return db
.from('conversation AS con')
.select(
'con.id',
'con.user_1',
'con.user_2',
'con.date_created',
'con.is_active',
'con.user_1_turn',
'con.user_2_turn',
)
.where({
'con.user_1': user_id,
'con.is_active': true
})
.orWhere({
'con.user_2': user_id,
'con.is_active': true
})
} | [
"function getUserConvos(user) {\n\n\tvar userObj = getUser(user);\n\tvar convos_ids = userObj.convos;\n\n\tvar convos = [];\n\n\t// for all conversation objects\n\tfor (var i = 0; i < data.convos.length; i++) {\n\n\t\t// if the conversation is in the users list of convos,\n\t\t// add to convos array\n\t\tif (convos_ids.indexOf(data.convos[i].id) > -1) {\n\t\t\tconvos.push(data.convos[i]);\n\t\t}\n\t}\n\n\treturn convos;\n\n}",
"getConversations() {\n return this.firestore.doc('accounts/' + this.getCurrentUserId()).collection('conversations');\n // return this.afdb.list('/accounts/' + this.afAuth.currentUser.uid + '/conversations');\n }",
"async function getConversations() {\n let conversations = await fb.api(`${FACEBOOK_PAGE_ID}/conversations`,\n {limit: LIMIT});\n return pushAllPages(conversations);\n}",
"getUserConversations() {\n return Vue.http.get(`/api/conversations`)\n .then((response) => Promise.resolve(response.body))\n .catch((error) => Promise.reject(error));\n }",
"async getUserConversations(token) {\n\t\ttry {\n\t\t\t// verify the sending user token and extract his id\n\t\t\treturn jwtUtils\n\t\t\t\t.verifyToken(token)\n\t\t\t\t.then(async (authData) => {\n\t\t\t\t\tconst conversations = await ConversationSchema.find({participants: authData.id});\n\n\t\t\t\t\treturn Promise.all(\n\t\t\t\t\t\tconversations.map(async (conv) => {\n\t\t\t\t\t\t\t/**\n\t\t\t\t\t\t\t * for each conversation check if group\n\t\t\t\t\t\t\t * if not, change name and image to the\n\t\t\t\t\t\t\t * other user's username and profile image\n\t\t\t\t\t\t\t */\n\t\t\t\t\t\t\tif (!conv.isGroup) {\n\t\t\t\t\t\t\t\tif (conv.participants.length === 2) {\n\t\t\t\t\t\t\t\t\t// find whom of the users are not\n\t\t\t\t\t\t\t\t\t// the requesting user\n\t\t\t\t\t\t\t\t\tconst otherIndex = conv.participants[0] == authData.id ? 1 : 0;\n\t\t\t\t\t\t\t\t\t// get user document\n\t\t\t\t\t\t\t\t\tconst user = await userController.getUserById(conv.participants[otherIndex]);\n\t\t\t\t\t\t\t\t\t// set the conversation values.\n\t\t\t\t\t\t\t\t\tconv.convName = user.username;\n\t\t\t\t\t\t\t\t\tconv.profileImg = user.profileImage;\n\t\t\t\t\t\t\t\t\treturn conv;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn conv;\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tthrow new Error(err);\n\t\t\t\t});\n\t\t} catch (err) {\n\t\t\tconsole.error(err);\n\t\t\tthrow new Error(err.message);\n\t\t}\n\t}",
"async function getConversations(db, userId) {\n // need try/catch error handling here\n const conversations = await db.collection('conversations').find().toArray()\n return { conversations }\n}",
"getConversationsChats() { \n\n\t\treturn this.apiClient.callApi(\n\t\t\t'/api/v2/conversations/chats', \n\t\t\t'GET', \n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\tnull, \n\t\t\t['PureCloud OAuth'], \n\t\t\t['application/json'],\n\t\t\t['application/json']\n\t\t);\n\t}",
"function showAllConvos() {\n const url = \"/messages?user=\" + parameterUsername;\n fetch(url)\n .then(response => {\n return response.json();\n })\n .then(messages => {\n const convosContainer = document.getElementById(\"message-container\");\n if (messages.length == 0) {\n convosContainer.innerHTML = \"<p>You have no conversations</p>\";\n } else {\n convosContainer.innerHTML = \"\";\n }\n var convos = new Set();\n messages.forEach(message => {\n convoWith = message.user;\n convos.add(convoWith)\n });\n convos.forEach(convoWith => {\n convoWith = convoWith;\n const convoDiv = buildConvoDiv(convoWith);\n convosContainer.appendChild(convoDiv);\n });\n });\n}",
"async function getAllConversationsGeneric(requesterId) {\n let results = await convRep.getAllConversationsFor(requesterId);\n let conversations = [];\n if(results.body.hits.total.value === 0) { return conversations; }\n for (let conversation of results.body.hits.hits) {\n conversations.push(conversation._source);\n }\n\n for (let conversation of conversations) {\n sortMessagesByDate(conversation);\n conversation.messages = getLastMessage(conversation);\n if (parseInt(conversation.user1) === requesterId) {\n conversation.user2 = await usersHandler.getUserByIdGeneric(conversation.user2);\n } else {\n conversation.user2 = await usersHandler.getUserByIdGeneric(conversation.user1);\n }\n conversation.user1 = await usersHandler.getUserByIdGeneric(requesterId);\n }\n return conversations;\n}",
"getConversationsMessages() { \n\n\t\treturn this.apiClient.callApi(\n\t\t\t'/api/v2/conversations/messages', \n\t\t\t'GET', \n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\tnull, \n\t\t\t['PureCloud OAuth'], \n\t\t\t['application/json'],\n\t\t\t['application/json']\n\t\t);\n\t}",
"async function getChatboxes({ userId }) {\n try {\n // Check if the user exists\n const existedUser = await users.findOne({\n cognito_id: userId,\n });\n if (!existedUser) {\n throw 'User does not exist';\n }\n\n // Fetching all chatboxes for the user\n const response = await chatboxes\n .find({\n $or: [\n { 'user_one.cognito_id': userId },\n { 'user_two.cognito_id': userId },\n ],\n })\n .toArray();\n\n return response;\n } catch (error) {\n throw error;\n }\n }",
"async function getMessagesByConversation(conversations) {\n return Promise.all(conversations.map(async (c) => {\n let conversation = await fb.api(c.id, {\n fields: 'messages{from, created_time, message, ' +\n 'shares{name, description, link}}, participants',\n limit: LIMIT,\n });\n let participantName = getParticipantName(conversation);\n /* Ignore the fact that shares are paged separately so we don't exceed our\n * Graph API rate limit.\n */\n let messages = await pushAllPages(conversation.messages);\n /* The Graph API returns messages in reverse chronological order. */\n messages.reverse();\n return [participantName, messages];\n }));\n}",
"function getChatsForAUser() {\n\n // Send GET request to mongoDB to get all chats associated with a specific userId\n chatFactory.getChatsForAUser(vm.userId).then(\n\n function(response) {\n \n // Zero out the # of channels and direct messages\n $rootScope.numberOfChannels = 0;\n $rootScope.numberOfDirectMessages = 0;\n\n // Display chatgroup names on the view \n $rootScope.chatGroups = response;\n \n // Determine how many chat channels and direct messages the user is subscribed to\n for (var i = 0; i < response.length; i++) {\n if (response[i].groupType !== \"direct\") {\n $rootScope.numberOfChannels++;\n } else {\n $rootScope.numberOfDirectMessages++;\n }\n }\n\n // Send socket.io server the full list of chat rooms the user is subscribed to\n chatFactory.emit('add user', {chatGroups: $rootScope.chatGroups, userid: vm.userId});\n\n // Jump to calendar state\n $state.go('main.calendar');\n },\n\n function(error) {\n\n // Jump to calendar state\n $state.go('main.calendar'); \n\n });\n\n }",
"list_channels(user)\n {\n let result = []\n for (let guild of this.client.guilds.cache)\n {\n for (let channel of guild[1].channels.cache)\n {\n for (let member of channel[1].members)\n {\n if (member[1].id == user.id)\n {\n result.push(channel[1]);\n }\n }\n }\n }\n return result;\n }",
"function getConversations() {\n $scope.conversations = [];\n Conversation.get()\n .then(function (response) {\n var allConversations = response.data;\n for(var i = 0; i < allConversations.length; i++) {\n if(allConversations[i].providers.indexOf($scope.profile._id) !== -1 && allConversations[i].patient.length > 0){\n $scope.conversations.push(allConversations[i]);\n }\n }\n }, function (error) {\n $scope.status = 'Unable to load patient data: ' + error.message;\n });\n console.log($scope.conversations);\n }",
"function filterConversations() {\n // Only include conversations the session user is in\n conversationsList(conversationsList().filter(isSessionUserIncluded));\n\n function isSessionUserIncluded(conversation) {\n\n // Check if user is a part of the conversation\n var results = $.grep(conversation.ConversationUsers(), isSessionUser);\n\n function isSessionUser(convoUser) {\n return convoUser.UserId() === session.sessionUser().Id();\n }\n\n // If the session user was part of the conversation return true\n return results.length > 0;\n }\n }",
"async function getConversations()\n {\n\n try\n {\n let response = await axios.get(\"https://messagesapp1.herokuapp.com/api/conversations/UserConversations/\" +sessionStorage[\"id\"],config);\n let ConversationsList = response.data.map((conversation) =>\n {\n let UpdatedConversation= conversation\n\n /*if this is a private conversation, and the name and picture saved as this user name, \n update the conversation to other user name and picture*/\n if (!conversation.isGroup && conversation.Name === sessionStorage['name'])\n UpdatedConversation = { ...UpdatedConversation,Name: conversation.Participants[0].name,ConversationImage:conversation.Participants[0].imageName}\n\n\n //update the current shown on screen conversation\n if(selectedConversation)\n {\n if(selectedConversation._id === UpdatedConversation._id)\n setSelectedConversation(UpdatedConversation)\n }\n\n return UpdatedConversation;\n\n })\n\n return ConversationsList \n\n } catch (err) {console.log(err);}\n\n }",
"get conversations() {\r\n return new Conversations(this);\r\n }",
"async getAllUserMessages() {\n try {\n const channels = await this.getAllChannels()\n const users = {}\n\n await async.eachSeries(channels, async (channel) => {\n await delay(250)\n await async.retry(\n {\n times: 5,\n interval: (retryCount) => 500 * Math.pow(2, retryCount)\n },\n async () => {\n const msgs = await this.getUserMessages(channel.id)\n console.log('* pulled msgs', channel.name, msgs.length)\n msgs.forEach(async (msg) => {\n if (!(msg.user in users)) {\n users[msg.user] = []\n }\n users[msg.user].push(msg)\n })\n }\n )\n })\n const entries = []\n await async.eachOf(users, async (messages, userId) => {\n messages = _.orderBy(messages, ['timestamp'], ['desc'])\n const entry = {\n userId,\n messages\n }\n if (messages && messages.length) {\n entry.lastActive = messages[0].timestamp\n entry.firstActive = messages[messages.length - 1].timestamp\n entries.push(entry)\n }\n })\n return entries\n } catch (err) {\n console.error(err.message)\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a promise to retrieve the page content from MW API mobileview | function pageContentForMainPagePromise(logger, domain, title) {
return mwapi.getAllSections(logger, domain, title)
.then(function (response) {
var page = response.body.mobileview;
var sections = page.sections;
var section;
// transform all sections
for (var idx = 0; idx < sections.length; idx++) {
section = sections[idx];
section.text = transforms.runMainPageDomTransforms(section.text);
}
page.sections = sections;
return page;
});
} | [
"function pageContentForMainPagePromise(req) {\n return mwapi.getAllSections(app, req)\n .then((response) => {\n const page = response.body.mobileview;\n const sections = page.sections;\n let section;\n\n // transform all sections\n for (let idx = 0; idx < sections.length; idx++) {\n section = sections[idx];\n section.text = transforms.runMainPageDomTransforms(section.text);\n }\n\n page.sections = sections;\n return page;\n });\n}",
"function pageMetadataPromise(req) {\n return mwapi.getMetadata(app, req)\n .then((response) => {\n return response.body.mobileview;\n });\n}",
"async getPage() {\n const res = await fetch(this.endpoint)\n return res.text()\n }",
"function getPageContent(url) {\n return new Promise((resolve, reject) => {\n request(url, (err, res, body) => {\n if (!err) {\n resolve(body);\n } else {\n reject(err);\n }\n });\n });\n}",
"async fetchMainPage() {\n const url = 'https://www.athmovil.com/web/mainMenu.htm';\n const response = await axios.get(url, globalConfig.axios);\n return response;\n }",
"async getPageData() {\n\t\treturn this.#browser.execute(function() {\n\t\t\tconst assets = Array.from(document.querySelectorAll('*[src], link[rel=\"shortcut icon\"], link[rel=stylesheet], *[href][download]')).map(el => el.src || el.href);\n\t\t\tconst links = Array.from(document.querySelectorAll('a[href]:not(a[download]), area[href]:not(area[download])')).map(el => el.href).filter(link => {\n\t\t\t\tconst m = new URL(link).pathname.match(/\\.[a-z0-9]+$|^\\/biblio\\/export\\/|^\\/blog\\/([0-9]+\\/)?feed$|^\\/taxonomy\\/term\\/[0-9]+\\/feed$/);\n\t\t\t\tif(m) {\n\t\t\t\t\tassets.push(link);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn !link.match(/\\/event\\/(day|week|month)\\/.*$/);\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\thtml: (document.doctype ? new XMLSerializer().serializeToString(document.doctype) : '') + document.documentElement.outerHTML,\n\t\t\t\tassets,\n\t\t\t\tlinks\n\t\t\t}\n\t\t});\n\t}",
"async function getHomePage() {\n return prismicClient.getSingle(\"homepage\")\n .then(document => {\n const data = document.data;\n return {\n status: \"ok\",\n title: RichText.asText(data.title),\n description: RichText.asText(data.description),\n reactjsLogo: data.reactjs_logo,\n prismicLogo: data.prismic_logo,\n featuresIntro: RichText.asText(data.features_intro),\n features: data.body.map(slice => ({\n name: RichText.asText(slice.primary.feature_name),\n description: RichText.asText(slice.primary.feature_description)\n }))\n };\n })\n .catch(error => buildErrorObject(error));\n}",
"function fetchPageContent (url) {\n if (!url) {\n throw new Error('url-not-present');\n }\n\n return parseMercury(url).then(function (response) {\n const data = response.data;\n\n if (data && data.content) {\n const parsedContent = parseText(data.content);\n response.data.textContent = parsedContent;\n }\n\n return response.data;\n });\n}",
"function get(pageId) {\n if (typeof pageId !== 'number') {\n throw new Error('Expecting a valid page id');\n }\n\n var deferred = Q.defer();\n\n $http.get(config.CONTENT_API_URL + pageId.toString())\n .then(function (response) { deferred.resolve(response.data)}),\n deferred.reject.bind(deferred);\n\n return deferred.promise;\n }",
"function getContentPage() {\n return new Promise((reserve, reject) => {\n const xhr = new XMLHttpRequest();\n\n xhr.open('GET', 'http://127.0.0.1:5500/js/16/cart.html');\n\n xhr.onreadystatechange = function () {\n if (this.readyState == 4 && this.status == 200) {\n reserve(xhr.response);\n }\n }\n\n xhr.onerror = () => {\n reject(`Error. Status code: ${xhr.status}`);\n }\n\n xhr.send();\n })\n}",
"function getMainNavigationContent() {\n mainNavSrv.getNavigationContents().then(function (result) {\n \n });\n }",
"function loadPageContent(page){\n\n}",
"async function getUnitContent(id){\n try{\n let url = '/api/weekContent';\n url += '?unitId=' + encodeURIComponent(id);\n const response = await fetch(url);\n\n if (!response.ok) throw response;\n let content = await response.json();\n return content;\n } catch (e) {\n console.error('error getting content details', e);\n }\n}",
"async function findPageInCPanel() {\n\t\tlet url = `${domain}/_cpanel/url`\n\t\tlet queries = {\n\t\t\t\"_ftr_request_url\": `^${truncated_path}`\n\t\t}\n\t\tlet selector = \"#ajax-content-pl table tbody tr:first-of-type td:nth-of-type(2) a\"\n\t\tlet storedDomain = `${domain}|${truncated_path}`\n\t\tgetPage(url, queries)\n\t\t\t.then(\n\t\t\t\ttext => {\n\t\t\t\t\tlet parser = new DOMParser()\n\t\t\t\t\tlet link = parser.parseFromString(text, \"text/html\").querySelector(selector);\n\t\t\t\t\tconsole.log(\"parse link\");\n\t\t\t\t\tconsole.log(parser.parseFromString(text, \"text/html\"));\n\t\t\t\t\tconsole.log(link);\n\t\t\t\t\tlink\n\t\t\t\t\t\t? storeData(storedDomain, link.getAttribute('href'))\n\t\t\t\t\t\t: storeData(storedDomain, \"NO RESULTS\")\n\t\t\t\t}\n\t\t\t)\n\t\t\t.catch(\n\t\t\t\tresult => {\n\t\t\t\t\tconsole.log('Error');\n\t\t\t\t\tconsole.log(result);\n\t\t\t\t\tstoreData(storedDomain, \"NO RESULTS\");\n\t\t\t\t}\n\t\t\t)\n\t}",
"function mainPage() { //Fetch from Web service and get Json data with Fetch\n\n fetch(DATA.showUrl.url).then( (response)=> {//Response is Promise object\n return response.json();\n }).then(function (myJson) {\n const shows = DATA.createShow(myJson); //Create Shows\n UI.createMainPage(shows) //Append show to Page\n }).catch((myJsonError)=>{\n alert(\"Your request failed\",myJsonError);\n });\n }",
"async function loadPages() {\n\n\n var data = await api.getJson(CONST_API_URL + 'admin-pages-api.php');\n\n pages = data;\n _render();\n\n }",
"function _getWebPartDataFromPage(props) {\n // tslint:disable-next-line:max-line-length\n var pageRelativeUrl = props.pageRelativeUrl, webPartInstanceId = props.webPartInstanceId, componentName = props.componentName, webPartAlias = props.webPartAlias, defaultWebPartData = props.defaultWebPartData, serviceScope = props.serviceScope, processWebPartDataCallback = props.processWebPartDataCallback;\n var qosMonitor = new _ms_sp_telemetry__WEBPACK_IMPORTED_MODULE_0__[\"_QosMonitor\"](componentName + \".ParseWebPartDataFromPage\");\n var dataProviderOptions = { serviceScope: serviceScope };\n var pageDataProvider = _PageMetadataProviderLoader__WEBPACK_IMPORTED_MODULE_1__[\"PageMetadataProviderLoader\"].load(dataProviderOptions);\n // tslint:disable-next-line:max-line-length\n return pageDataProvider.then(function (dataProvider) {\n return dataProvider.requestData({ pageRelativeUrl: pageRelativeUrl });\n }).then(function (response) {\n var firstResponse = response[0];\n var legacyResponseKey = 'CanvasJson1';\n var jsonToParse = firstResponse[legacyResponseKey] || firstResponse;\n if (!jsonToParse) {\n _handleStockContent(qosMonitor, webPartAlias);\n }\n // Having ICanvasControl here, limits the option of using\n // sp-dataproviders, using any for now.\n // @todo Link to the bug: https://onedrive.visualstudio.com/CSI/_workitems/edit/794727\n return JSON.parse(jsonToParse); // tslint:disable-line:no-any\n }).then(function (canvasControls) {\n return _getWebPartByUniqueId(webPartInstanceId, canvasControls);\n }).then(function (control) {\n var webPartData;\n if (control) {\n webPartData = control.webPartData; // tslint:disable-line:no-any\n }\n if (webPartData) {\n webPartData.instanceId = webPartInstanceId;\n if (processWebPartDataCallback) {\n webPartData = processWebPartDataCallback(webPartData);\n }\n qosMonitor.writeSuccess(_logData(webPartAlias));\n }\n else {\n var noInstanceError = new Error('NoInstanceDataFound');\n qosMonitor.writeUnexpectedFailure(noInstanceError.message, noInstanceError, _logData(webPartAlias));\n throw noInstanceError;\n }\n return webPartData;\n }).catch(function (ex) {\n if (!qosMonitor.hasEnded) {\n qosMonitor.writeUnexpectedFailure('FailedToParse', ex, _logData(webPartAlias));\n }\n _ms_sp_telemetry__WEBPACK_IMPORTED_MODULE_0__[\"_EngagementLogger\"].logEvent(componentName + \".LoadDefaultWebPartData\");\n return defaultWebPartData;\n }).then(function (webPartData) { return webPartData; });\n}",
"async getContentBySectionId(id){\n let metadata = await http({\n url: `sections/${id}`,\n method: \"get\",\n token: this.props.loggedInUser ? this.props.loggedInUser.token : null\n });\n let page = 1;\n let totalPages = Math.ceil(metadata.contentUnitCount/20);\n let contents = [];\n\n while(page <= totalPages){\n contents.push(\n new Promise(reject => {\n http({\n url: `sections/${id}/content_units?per_page=20&page=${page}`,\n method: \"get\",\n token: this.props.loggedInUser ? this.props.loggedInUser.token : null\n });\n })\n )\n page++;\n }\n\n contents = await Promise.all(contents).catch((err) => { console.log(err); });;\n console.log(\"contents\", contents)\n\n // concat all content strings together into 1\n let content = '';\n contents.forEach(contentPage => {\n contentPage.forEach(contentUnit => {\n content += contentUnit.content;\n })\n })\n\n return content;\n }",
"async index ({ request, response, view }) {\n const rawContent = await RawContent.query().fetch()\n return rawContent\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tennis Set In tennis, the winner of a set is based on how many games each player wins. The first player to win 6 games is declared the winner unless their opponent had already won 5 games, in which case the set continues until one of the players has won 7 games. Given two integers score1 and score2, your task is to determine if it is possible for a tennis set to be finished with a final score of score1 : score2. Example 1 For score1 = 3 and score2 = 6, the output should be tennisSet(score1, score2) = true. Since player 1 hadn't reached 5 wins, the set ends once player 2 has won 6 games. Example 2 For score1 = 8 and score2 = 5, the output should be tennisSet(score1, score2) = false. Since both players won at least 5 games, the set would've ended once one of them won the 7th one. Exapmle 3 For score1 = 6 and score2 = 5, the output should be tennisSet(score1, score2) = false. This set will continue until one of these players wins their 7th game, so this can't be the final score really we are just checking if it is a valid ending score | function tennisSet(score1, score2) {
if (score1 < 5 && score2 < 5) {
return false
}
if ((score1 - score2 <= 3 || score2 - score1 <= 3) &&(score1 - score2 > 0 || score2 - score1 > 0)&& (score1 >= 5 && score2 >= 5)) {
console.log("RETRY here")
return true
}
if(score1 >= 5 || score2 >= 5){
if(score1 - score2 == 3 || score2 - score1 == 3){
console.log("return here")
return true
}
}
return false
} | [
"function tennisSet(score1, score2) {\n if(score1 == 7 && score2 < 7){\n if( score2 == 2){\n return false;\n } else {\n return true;\n }\n }\n if(score1 == score2 ){\n return false;\n } \n if(score1 >= 6 ){\n if(score2 < 5){\n return true;\n } else if (score2 >= 5){\n return false;\n }\n } \n if(score2 >= 6 ){\n if(score1 < 5){\n return true;\n } else if (score1 >= 5){\n return false;\n }\n }\n}",
"function tennisSet(score1, score2) {\n if(score1 > 4 && score2 > 4 && score1 <7 && score2 < 7) return false;\n if(score1 > 4 && score2 > 4 && (score1 ==7 && score2 != score1 || score2 == 7 && score1 != score2)) return true;\n if((score1 < 5 || score2 < 5)&&(score1 == 6 || score2 == 6)) return true;\n return false;\n\n}",
"function tennisSet(score1, score2) {\n if(score1 == 7 && score2>=5 && score2!=7 || score2 == 7 && score1>=5 && score1!=7|| score1 == 6 &&\n score2<5 || score2 == 6 && score1<5){\n return true;\n } else if (score1 == 5 && score2 == 5){\n return true;\n }\n return false;\n}",
"function tennisSet(score1, score2) {\n //if one is 5 and the other is less than 5\n //if one is 7 and the other is > 5\n if (score1 != score2 && score1 <= 7 && score2 <= 7) {\n // we are not equal\n // we are not greater than 7\n if (score1 < 5 && score2 == 6) {\n //5 and less than 5\n return true;\n } else if (score2 < 5 && score1 == 6) {\n //5 and less than 5\n return true;\n } else if (score1 < 7 && score2 == 7 && score1 >= 5) {\n return true;\n } else if (score2 < 7 && score1 == 7 && score2 >= 5) {\n return true;\n }\n }\n return false;\n}",
"function checkTennisScore(currentScore){\n currentScore = currentScore.replace(/ /g, '');\n currentScore = currentScore.toLowerCase();\n currentScore = currentScore.replace(/adv/g, '50');\n\n var bracketsPositions = [currentScore.indexOf(\"(\"), currentScore.indexOf(\")\")];\n if (bracketsPositions[0] < 0 || bracketsPositions[1] < 0){\n return false;\n }\n\n var sets = currentScore.substring(bracketsPositions[0] + 1, bracketsPositions[1]).split(\",\");\n if (sets.length < 2) {\n return false;\n }\n\n\n if (sets.length == 2 ){\n var firstSetVinner = parseInt(sets[0].split(\"-\")[0]) > parseInt(sets[0].split(\"-\")[1]) ? 0 : 1;\n var firstSetLooser = firstSetVinner == 0 ? 1 : 0;\n\n if (parseInt(sets[1].split(\"-\")[firstSetLooser]) >= parseInt(sets[1].split(\"-\")[firstSetVinner])){\n return false;\n }\n }\n\n\n var currentSet = sets.length-1;\n var currentPoints = currentScore.substring(bracketsPositions[1]+1).split(\":\");\n var currentSetLeader = parseInt(sets[currentSet].split('-')[0]) > parseInt(sets[currentSet].split('-')[1]) ? 0 : 1;\n var currentSetLooser = currentSetLeader == 0 ? 1 : 0;\n\n if(sets[currentSet][0] == sets[currentSet][1]){\n return false;\n }\n\n if (parseInt(sets[currentSet].split(\"-\")[currentSetLeader]) - parseInt(sets[currentSet].split(\"-\")[currentSetLooser]) == 2 &&\n parseInt(currentPoints[currentSetLeader]) > parseInt(currentPoints[currentSetLooser]) && parseInt(currentPoints[currentSetLeader]) > 15) {\n return true;\n }\n\n if (parseInt(sets[currentSet].split(\"-\")[currentSetLeader]) - parseInt(sets[currentSet].split(\"-\")[currentSetLooser]) > 2){\n return true;\n }\n\n if ( (parseInt(sets[currentSet].split(\"-\")[0]) +\n parseInt(sets[currentSet].split(\"-\")[1])) < 6 ){\n return false;\n }\n\n if (parseInt(currentPoints[currentSetLeader]) - parseInt(currentPoints[currentSetLooser]) > 15) {\n return true;\n }\n\n\n return false;\n}",
"function decodeSet(set, data) {\n var score = [0, 0];\n while(data.length > 0) {\n var game = new Game();\n game.tieBreak = (score[0] == 6 && score[1] == 6) ? 'yes' : 'no';\n if (!decodeGame(game, data)) {\n return false;\n }\n togglePlayer = 1 - togglePlayer;\n // Store the set and the score before the win.\n set.games.push([[score[0], score[1]], game]);\n score[game.winner]++;\n if (Math.abs(score[0] - score[1]) >= 2) {\n if (score[0] >= 6 || score[1] >= 6) {\n set.winner = game.winner;\n return true;\n }\n } else {\n if (score[0] >= 7 || score[1] >= 7) {\n set.winner = game.winner;\n return true;\n }\n }\n }\n return true;\n}",
"function checkForSet() {\n\t\tnbrOfSets = 0;\n\t\t\n\t\tvar slots = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];\n\t\tvar combinations = slots.combinate(3);\n\t\t\n\t\tfor (var i = 0; i < combinations.length; i++) {\n\t\t\tvar cards = combinations[i];\n\t\t\tisSetOnTable(activeCards[cards[0]], activeCards[cards[1]], activeCards[cards[2]]);\n\t\t}\n\t\tconsole.log(\"SET i kort: \" + nbrOfSets);\n\t}",
"winningMoves(playerMoves) {\n let testResult;\n if (playerMoves.size > 1) {\n const firstMove = Array.from(playerMoves)[0];\n const possibleSubsets = this.wins[firstMove];\n // the below test\n testResult = possibleSubsets.filter((eachSet) => {\n for (let x of eachSet) {\n if (!playerMoves.has(x)) {\n return false;\n }\n }\n return true;\n });\n if (testResult.length >= 1) {\n return true;\n }\n return false;\n }\n return false;\n }",
"getSetScoreGroup(t) {\n let isValidGroup = true;\n \n if (t.length > Constants.NUMBER_OF_TILE_SUITS && !Constants.ALLOW_DUPLICATE_SUITS_IN_GROUP) {\n return 0;\n }\n\n let firstTileRank = null;\n let suits = [];\n for (let i = 0; i < t.length; i++) {\n if (!TileHelper.isJoker(t[i])) {\n let tileRank = TileHelper.getTileRankFromId(t[i]);\n if (firstTileRank === null) {\n firstTileRank = tileRank;\n }\n else if (tileRank !== firstTileRank) {\n isValidGroup = false; //rank mismatch\n break;\n }\n if (!Constants.ALLOW_DUPLICATE_SUITS_IN_GROUP) {\n let tileColour = TileHelper.getTileSuitFromId(t[i]);\n if (suits[tileColour] === undefined) {\n suits[tileColour] = i;\n }\n else {\n isValidGroup = false; //more than one duplicate tile of same suit (colour)\n break;\n }\n }\n }\n }\n\n if (isValidGroup) {\n return firstTileRank * t.length;\n }\n return 0;\n }",
"function checkIfOwnsSet(currentPlayer) {\n //sets holds how many of each set the player owns\n var sets = [0, 0, 0, 0, 0, 0, 0, 0];\n $(\"#addHouseBrown\").hide();\n $(\"#addHouseBlue\").hide();\n $(\"#addHousePurple\").hide();\n $(\"#addHouseOrange\").hide();\n $(\"#addHouseRed\").hide();\n $(\"#addHouseYellow\").hide();\n $(\"#addHouseGreen\").hide();\n $(\"#addHouseDarkBlue\").hide();\n for (i = 0; i < tiles2.length; i++) {\n if (tiles2[i].ownedBy == currentPlayer) {\n\n if (tiles2[i].group == \"Brown\") {\n sets[0]++;\n var brownNo = tiles2[i].setAmmout;\n } else if (tiles2[i].group == \"Blue\") {\n sets[1]++;\n var blueNo = tiles2[i].setAmmout;\n } else if (tiles2[i].group == \"Purple\") {\n sets[2]++;\n var purpleNo = tiles2[i].setAmmout;\n } else if (tiles2[i].group == \"Orange\") {\n sets[3]++;\n var orangeNo = tiles2[i].setAmmout;\n } else if (tiles2[i].group == \"Red\") {\n sets[4]++;\n var redNo = tiles2[i].setAmmout;\n } else if (tiles2[i].group == \"Yellow\") {\n sets[5]++;\n var yellowNo = tiles2[i].setAmmout;\n } else if (tiles2[i].group == \"Green\") {\n sets[6]++;\n var greenNo = tiles2[i].setAmmout;\n } else if (tiles2[i].group == \"DarkBlue\") {\n sets[7]++;\n var darkBlueNo = tiles2[i].setAmmout;\n }\n }\n }\n\n if (sets[0] == brownNo) {\n //alert(\"You have brown set\");\n $(\"#addHouseBrown\").show();\n }\n if (sets[1] == blueNo) {\n //alert(\"You have blue set\");\n $(\"#addHouseBlue\").show();\n }\n if (sets[2] == purpleNo) {\n //alert(\"You have purple set\");\n $(\"#addHousePurple\").show();\n }\n if (sets[3] == orangeNo) {\n //alert(\"You have ornage set\");\n $(\"#addHouseOrange\").show();\n }\n if (sets[4] == redNo) {\n //alert(\"You have red set\");\n $(\"#addHouseRed\").show();\n }\n if (sets[5] == yellowNo) {\n //alert(\"You have yellow set\");\n $(\"#addHouseYellow\").show();\n }\n if (sets[6] == greenNo) {\n //alert(\"You have green set\");\n $(\"#addHouseGreen\").show();\n }\n if (sets[7] == darkBlueNo) {\n //alert(\"You have dark blue set\");\n $(\"#addHouseDarkBlue\").show();\n }\n\n\n //tiles2[1].setAmmout;\n\n}",
"function checkDone(){\n var done=true;\n\t\tvar currentCards=[];\n\t\tfor (var j=1;j<7;j++){\n\t\t\tfor (var i=1;i<4;i++){\n\t\t\t\tif (cardsOnBoard[j][i]!=null){\n\t\t\t\t\tcurrentCards.push(cardsOnBoard[j][i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvar numCardsOnBoard=currentCards.length;\n\t\t//brute force all possible sets\n\t\tfor (var i=0; i<numCardsOnBoard; i++){\n\t\t\tfor (var j=i; j<numCardsOnBoard-1; j++){\n\t\t\t\tfor (var k=j; k<numCardsOnBoard-2; k++){\n\t\t\t\t\tif (i!=j && j!=k && i!=k && checkSet(currentCards[i],currentCards[j],currentCards[k])){\n\t\t\t\t\t\t//if there is a set, you aren't done\n\t\t\t\t\t\tdone=false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn done;\n }",
"function checkIfWon() {\n\n if (scores[\"player1\"] == 3) {\n markAsWinner(1)\n return true\n } else if (scores[\"player2\"] == 3) {\n markAsWinner(2)\n return true\n }\n\n return false\n}",
"findSet() { \n for (let i = 0; i < this.currentBoard.length-3; i++) {\n for (let j = i +1; j < this.currentBoard.length-2; j++) {\n for (let k = j+1; k < this.currentBoard.length-1;k++) {\n let potenSet = [i, j, k];\n let foundSet = this.checkUserMatch(potenSet);\n if (foundSet) {\n return potenSet;\n }\n }\n }\n }\n return [-1];\n }",
"function runTennisMatch() {\n /**\n * Runs a single step of the match, then recall itself (asynchronously) when their is no winner yet.\n * @param {*} currentState The current state of the match\n */\n function runTennisMatch_stepper(currentState) {\n getPlayerWhoScored(function(playerWhoScoredAPoint) {\n const nextState = computeNextSetState(\n currentState,\n playerWhoScoredAPoint\n );\n displayScore(nextState);\n if (nextState.winner !== undefined) {\n console.log(`Player ${nextState.winner} has won the game 🎉`);\n } else {\n runTennisMatch_stepper(nextState);\n }\n });\n }\n\n const initialState = {\n gameState: {\n scores: [0, 0]\n },\n scores: [0, 0]\n };\n runTennisMatch_stepper(initialState);\n}",
"static set_available(cards_array){\n\n var possible_set = false;\n\n\n for (var i = 0; i < cards_array.length; i++){\n\n if (cards_array[i][0] != \"\"){\n\n for (var k = 0; k < cards_array.length; k++){\n\n if (cards_array[k][0] != \"\"){\n\n if (k != i){\n\n for (var m = 0; m < cards_array.length; m++){\n\n if (cards_array[m][0] != \"\"){\n\n if (m != k && m != i) {\n\n if (!(cards_array[i][0] == null) && !(cards_array[k][0] == null) && !(cards_array[m][0] == null)){\n\n if (cards_array[i][0].isSet(cards_array[k][0], cards_array[m][0])) {\n possible_set = true\n console.log(cards_array[i][0]);\n console.log(cards_array[k][0]);\n console.log(cards_array[m][0]);\n return possible_set\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n return possible_set\n }",
"checker() {\n //assume we have a winner\n this.finish = true;\n\n //worst case: every hand is equal, both decks exhausted, there is no winner\n if(!this.deck1.length && !this.deck2.length) {\n this.winner = 'no winner';\n }\n //if deck1 empty, winner is player2\n else if(!this.deck1.length) {\n this.winner = 'Player 2';\n //if deck2 empty, winner is player1\n } else if(!this.deck2.length) {\n this.winner = 'Player 1';\n } else {\n //continue game\n this.finish = false;\n }\n }",
"function find_winner() {\n for (var i = 0; i < winning_sequences.length; i++) {\n for (var j = 0; j < 3; j++) {\n if (list_of_boxes_player1_has.includes(winning_sequences[i][j])\n && list_of_boxes_player1_has.includes(winning_sequences[i][j + 1])\n && list_of_boxes_player1_has.includes(winning_sequences[i][j + 2])\n ) {\n win1 = true;\n win2 = false;\n }\n if (list_of_boxes_player2_has.includes(winning_sequences[i][j])\n && list_of_boxes_player2_has.includes(winning_sequences[i][j + 1])\n && list_of_boxes_player2_has.includes(winning_sequences[i][j + 2])\n ) {\n win2 = true;\n win1 = false;\n }\n }\n if (win1 == true) {\n return 1\n }\n else if (win2 == true) {\n return 2\n }\n }\n return 0\n}",
"function teamWon(lastScore, newScore) {\n return lastScore == 15 && newScore == 0;\n}",
"function checkScores() {\n if ((playerOne.donutsEaten >= winScore) || (playerTwo.donutsEaten >= winScore)) {\n console.log(\"game is over\");\n if (playerOne.donutsEaten >= winScore) {\n winner = \"Player One\";\n } else {\n winner = \"Player Two\";\n }\n return true;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replaces defined variables in the given value | function replaceVariables( value ) {
return value.replace( options.variableRegex, function( match, key ) {
if ( options.variables[ key ] === undefined ) {
grunt.log.warn( "No variable definition found for: " + key );
return "";
}
return options.variables[ key ];
} );
} | [
"function __replaceValues(){\n\t\tvar result = expression;\n\t\tvar key;\n\t\tvar regex;\n\t\t//substitute variable values\n\t\tfor(key in variableValues){\n\t\t\tregex = new RegExp(\"\\\\b\"+key+\"\\\\b\", \"g\");\n\t\t\tresult = result.replace(regex, variableValues[key]);\n\t\t}\n\t\t//substitute constant values\n\t\tfor(key in CONSTANTS){\n\t\t\tregex = new RegExp(\"\\\\b\"+key+\"\\\\b\", \"g\");\n\t\t\tresult = result.replace(regex, CONSTANTS[key]);\n\t\t}\n\t\treturn result;\n\t}",
"function __replaceValues(){\n\t\tvar result = expression;\n\t\t//substitute variable values\n\t\tfor(var key in variableValues){\n\t\t\tvar regex = new RegExp(\"\\\\b\"+key+\"\\\\b\", \"g\");\n\t\t\tresult = result.replace(regex, variableValues[key]);\n\t\t}\n\t\t//substitute constant values\n\t\tfor(var key in CONSTANTS){\n\t\t\tvar regex = new RegExp(\"\\\\b\"+key+\"\\\\b\", \"g\");\n\t\t\tresult = result.replace(regex, CONSTANTS[key]);\n\t\t}\n\t\treturn result;\n\t}",
"function updateEnvValue (node, variables) {\n\t// get the value of a css function as a string\n\tvar value = getFnValue(node);\n\n\tif (typeof value === 'string') {\n\t\treplaceWithWord(node, variables[value]);\n\t}\n}",
"replaceArgVariable(varName, replacement) {\n const args = this.args;\n for (let i = 0; i < args.length; i++) {\n let arg = args[i];\n let changed;\n do {\n changed = false;\n const pos = arg.indexOf(varName);\n if (pos >= 0) {\n arg = arg.substr(0, pos) + replacement + arg.substr(pos + varName.length);\n changed = true;\n }\n } while (changed);\n args[i] = arg;\n }\n }",
"function performSubstitutions(input) {\n return input.replace(/!([\\w\\-]+)/g, function(orig, name){\n return data.variables[name] || orig\n })\n .replace(/\\{(.*?)\\}/g, function(_, js){\n with (data.variables){ return eval(js) }\n })\n }",
"function injectValue(string, variable, value){\n\treturn string.replace(new RegExp(\"(\"+variable+\")\", \"g\"), value);\n}",
"function replaceWikiVars( text ) {\n\tvar re = /\\{\\{\\{([^\\}]+)\\}\\}\\}/g,\n\t\twikiVarMatch;\n\twhile ( ( wikiVarMatch = re.exec( text ) ) !== null ) {\n\t\tif ( GlobalBannerSettings[ wikiVarMatch[ 1 ] ] ) {\n\t\t\ttext = text.replace( wikiVarMatch[ 0 ], GlobalBannerSettings[ wikiVarMatch[ 1 ] ] );\n\t\t} else {\n\t\t\ttext = text.replace( wikiVarMatch[ 0 ], '' );\n\t\t}\n\t}\n\treturn text;\n}",
"function substitute(val) {\n if (typeof val == 'string') {\n val = val.replace(/\\$\\{(.*?)\\}/g, (match, name) => {\n const rep = replacement(name);\n // If there's no replacement available, keep the placeholder.\n return (rep === null) ? match : rep;\n });\n }\n else if (Array.isArray(val))\n val = val.map((x) => substitute(x));\n else if (typeof val == 'object') {\n // Substitute values but not keys, so we don't deal with collisions.\n const result = {};\n for (let [k, v] of Object.entries(val))\n result[k] = substitute(v);\n val = result;\n }\n return val;\n}",
"function substituteReqVar(val,reqParams){\n\t if(_.isArray(val)){\n\t val = _.map(val,function(singleVal){\n\t return substituteReqVar(singleVal,reqParams);\n\t })\n\t } else if(_.isObject(val)){\n\t var newVal = {};\n\t _.each(val,function(singleVal,key){\n\t newVal[key] = substituteReqVar(singleVal,reqParams);\n\t })\n\t val = newVal;\n\t } else{\n\t var regex = /\\$\\{(.*?)\\}/;\n\t while(regex.test(val)){\n\t var prop = regex.exec(val).pop();\n\t val = val.replace(regex, reqParams[prop]);\n\t }\n\t }\n\t return val;\n }",
"processVariableDefs() {\n for (let code in this.protos) {\n if (this.protos[code].definition) {\n this.protos[code].definition = this.replaceVariableDefs(this.protos[code].definition);\n }\n }\n }",
"updatetriggerVariablePlaceholder(data, key, value) {\n /* eslint-disable */\n const regexp = /\\%(.*)\\%/;\n /* eslint-enable */\n const found = value.match(regexp);\n if(found) {\n const placeholder = found[1];\n const param = this.triggerVariables[placeholder];\n if(param) {\n data[key] = param;\n }\n return true;\n }\n return false;\n }",
"function replaceVarsInText(string) {\n let s = string.split(\"{\");\n let vars = [];\n if (s.length > 1) {\n for (let i = 1 ; i < s.length ; i++) {\n vars.push(s[i].split(\"}\")[0]);\n }\n }\n for (let j = 0 ; j < vars.length ; j++) {\n string = string.replace(\"{\" + vars[j] + \"}\", userData[vars[j]]);\n }\n return string;\n }",
"setVariablesAndReplaceColor(){\n var variables = [];\n this._replacedInput = this._input;\n\n Object.keys(this._colorAsVariable).forEach((color) => {\n var variable = this._colorAsVariable[color];\n variables.push(variable + ': ' + color + ';');\n color = color.replace('\\(', '\\\\\\(').replace('\\)', '\\\\\\)');\n console.log(color);\n this._replacedInput = this._replacedInput.replace(new RegExp(color, 'g'), variable);\n this._replacedInput = this._replacedInput.replace(new RegExp(color.toUpperCase(), 'g'), variable);\n });\n\n this._variableDeclarations = variables.join(\"\\n\");\n }",
"function replace(input, searchValue, replaceValue) {}",
"function replaceVariables(string, inserts) {\n\t\tif($.type(string) === 'string' && $.type(inserts) === 'object') {\n\t\t\t$.each(inserts, function(index, value) {\n\t\t\t\tstring = string.replace('{$' + index + '}', value);\n\t\t\t});\n\t\t}\n\t\treturn string;\n\t}",
"function replaceVariables (string, variables) {\n\tif (!string) return '';\n\tif (variables) {\n\t\tfor (let varName in variables) {\n\t\t\tstring = string.replace(new RegExp('%' + varName + '%', 'g'), variables[varName]);\n\t\t}\n\t\tstring = string.replace(/ /g, ' ');\n\t}\n\treturn string;\n}",
"replaceVariables(str) {\n const matches = str.match(/\\$[\\w'-]+/gi);\n if (matches) {\n matches.forEach(match => {\n const re = new RegExp(match.replace(\"$\", \"\\\\$\"), \"i\");\n\n if (!this.yamlVariables[match]) {\n this.outputError(`The variable [${match}] was referenced in the YAML file before it was defined`);\n }\n /* eslint-disable-next-line */\n str = str.replace(re, this.yamlVariables[match]);\n });\n }\n return str;\n }",
"function updateVariable(body, variable, value){\n if(Globals.loading) return;\n var keyframe = (Globals.keyframe !== false)? Globals.keyframe: lastKF(); \n \n if(isNaN(value))\n Globals.variableMap[keyframe][bIndex(body)][variable] = \"?\";\n else {\n Globals.variableMap[keyframe][bIndex(body)][variable] = value;\n \n // Swap direction for y-velocity/acceleration (position is dealt with by caller)\n if(variable == \"vely\")\n Globals.variableMap[keyframe][bIndex(body)][variable] = -value;\n if(variable == \"accy\")\n Globals.variableMap[keyframe][bIndex(body)][variable] = -value;\n }\n \n}",
"function substituteBuildVars(file, buildVars) {\n var contents = fs.readFileSync(file, FILE_ENCODING);\n contents = contents.replace(/%%build:([^%]+)%%/g, function(matched, buildVarName) {\n return buildVars[buildVarName];\n });\n fs.writeFileSync(file, contents, FILE_ENCODING);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the selected state on all of the options and emits an event if anything changed. | _setAllOptionsSelected(isSelected, skipDisabled, isUserInput) {
// Keep track of whether anything changed, because we only want to
// emit the changed event when something actually changed.
const changedOptions = [];
this.options.forEach(option => {
if ((!skipDisabled || !option.disabled) && option._setSelected(isSelected)) {
changedOptions.push(option);
}
});
if (changedOptions.length) {
this._reportValueChange();
if (isUserInput) {
this._emitChangeEvent(changedOptions);
}
}
} | [
"_watchForSelectionChange() {\n this.selectedOptions.changed.pipe(takeUntil(this._destroyed)).subscribe(event => {\n // Sync external changes to the model back to the options.\n for (let item of event.added) {\n item.selected = true;\n }\n for (let item of event.removed) {\n item.selected = false;\n }\n if (!this._containsFocus()) {\n this._resetActiveOption();\n }\n });\n }",
"selectAll() {\n this._setAllOptionsSelected(true);\n }",
"function handleSelectionChange(selections) {\n setSelected(selections);\n }",
"updateSelectEvents() {\n this.updateEventsContainer('select');\n }",
"onMultipleSelect(selected) {\n this.$set(this.action, 'selected', selected)\n }",
"function news_storiesextblock_selectAllOptions(selectElement, selected)\r\n{\r\n if (selected == null) {\r\n selected = true;\r\n }\r\n for (var i = 0; i < selectElement.options.length; i++) {\r\n selectElement.options[i].selected = selected;\r\n }\r\n}",
"set selected(state) {\n this.updatePropertyState('selected', state);\n }",
"function selectChangeHandler(selectedOptions) {\n selectedTags = selectedOptions;\n }",
"function wui_select_observer(selected) {\n var elem = mySelect[0],\n options = elem.options,\n option_length = options.length,\n option,\n i = option_length;\n \n // Mutations have occurred on the select\n if (me.target && option_length != me.total) {\n // So reload the data\n me.setData(Wui.parseSelect(me.target));\n \n // Ensure the newly created options have the get/set listener\n while(i--) {\n option = options[i];\n if (!Wui.isset(option._selected)) {\n modifyOptionSelect(option);\n }\n }\n }\n \n // Observer count keeps track of how many times the option.select:set has been run\n if (Wui.isset(elem.observer_count)) {\n elem.observer_count++;\n }\n else {\n elem.observer_count = 1;\n }\n \n // Mark that a selected element exists\n if (selected === true) {\n elem.hasSelected = true;\n }\n \n if (elem.observer_count == option_length) {\n // Only fire the change event if at least one option is selected.\n if (elem.hasSelected === true) {\n // setTimeout necessary for operating after mutations on the select have occured.\n setTimeout(function() {\n // Setting selectedIndex is VITAL to the value being set properly on the\n // select tag. When only setting the attribute on the option tag, the value\n // doesn't always follow.\n i = option_length;\n while(i--) {\n option = options[i];\n if (option._selected) {\n elem.selectedIndex = i;\n }\n }\n\n mySelect.trigger('change');\n }, 0);\n }\n else {\n // jQuery documentation says this helps browsers behave consistently when no\n // options are selected.\n elem.selectedIndex = -1;\n }\n \n elem.observer_count = 0;\n elem.hasSelected = false;\n }\n }",
"function updateSelected(e, value) {\n setSelected(value)\n updateSize(e)\n }",
"select()\n\t{\n\t\tthis.units.forEach((u) => u.selected.value = true);\n\t}",
"select(...values) {\n this._verifyValueAssignment(values);\n\n values.forEach(value => this._markSelected(value));\n\n this._emitChangeEvent();\n }",
"_onChange() {\n const selectedIx = this.$el.prop('selectedIndex');\n this.trigger('selected', this.collection.models[selectedIx]);\n }",
"toggleSelectedForAllCheckedOptions() {\n const enabledCheckedOptions = this.checkedOptions.filter(o => !o.disabled);\n const force = !enabledCheckedOptions.every(o => o.selected);\n enabledCheckedOptions.forEach(o => o.selected = force);\n this.selectedIndex = this.options.indexOf(enabledCheckedOptions[enabledCheckedOptions.length - 1]);\n this.setSelectedOptions();\n }",
"function setItemsSelected(aComponent) {\n\n for (var i=0; i<aComponent.options.length; i++)\n aComponent.options[i].selected = true;\n}",
"onChange(selectedItems){}",
"_addSelectedToSelection(e) {\n let selectedOptions =\n this.props.selectedOptions.concat(getItemsByProp(this.state.filteredOptions,\n this.props.valueProp,\n this.state.selectedValues))\n this.setState({selectedValues: []}, () => {\n this.props.onChange(selectedOptions)\n })\n }",
"_setSelectedValues() {\n let self = this;\n self.set('_selectedValues', [...self.value]);\n }",
"function selectAllItems() {\n selectedItems = []\n Object.keys(allItemNames).forEach(itemName => {\n selectItem(itemName)\n })\n updateSelectedItemComponents()\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is used to update the scheme details of an existing scheme in the database | async function postSchUpdt(mfscheme) {
debugger;
try {
let schemes
// var _id = new mongoose.Types.ObjectId();
schemes = await mfschemesModel.update({
"scode": mfscheme.scode
}, {
$set: {
"sname": mfscheme.sname
}
});
return schemes;
} catch (err) {
return err;
// var operation = err.getOperation();
// var errflag = true;
// var parseResult = helpers.parseOutput(errflag, err, operation);
}
} | [
"function updateScheme(updatedScheme) {\n for (var i = 0; i < schemes.length; i++) {\n var oldScheme = schemes[i];\n if (oldScheme.data.id == updatedScheme.data.id) {\n schemes[i] = updatedScheme;\n }\n }\n}",
"function updateScheme(req,res) {\n // console.log(req.body);\n \n var id = req.body.scheme_id;\n var name = req.body.name;\n var amount = req.body.Amount;\n var r_asset = req.body.r_asset;\n var no_installment = req.body.instl;\n var duration = req.body.Duration;\n // \"scheme\": req.body.scheme,\n\n\n con.query(`UPDATE scheme SET name = '${name}', amount = '${amount}', r_asset = '${r_asset}', no_installment = '${no_installment}', duration = '${duration}' WHERE scheme_id = ${id}`, function (error, results) {\n if (error) throw res.send(error);\n res.redirect(\"/view_scheme\");\n })\n \n}",
"function add(scheme) {\n return db('schemes')\n .insert(scheme)\n .then(ids => {\n return findById(ids[0]) // returns posted new scheme\n })\n}",
"function add(scheme) {\n return db('schemes').insert(scheme); \n}",
"function add(scheme) {\n return db('schemes')\n .insert(scheme)\n .then(newScheme => findById(newScheme[0].id));\n}",
"function saveScheme(name, gender, fromage, toage,fromincome,toform){\n var newSchemeRef = schemesRef.push();\n newSchemeRef.set({\n name: name,\n \n gender:gender,\n fromage:fromage,\n toage:toage,\n fromincome:fromincome,\n toform:toform\n \n });\n}",
"setScheme(scheme) {\n if (!scheme) {\n this._scheme = undefined;\n }\n else {\n this.set(scheme, \"SCHEME\");\n }\n }",
"function add(scheme) {\n return db('schemes').insert(scheme)\n .then(ids => {\n return findById(ids[0]);\n });\n}",
"function startUpdatingScheme() {\n scheme.updateData(mainApi, function (success) {\n if (!success) {\n console.error(\"Error updating scheme data\");\n showErrorBadge();\n }\n\n setTimeout(startUpdatingScheme, schemeOptions.refreshRate);\n });\n}",
"setScheme(scheme) {\n return this.native.setScheme(scheme);\n }",
"function add(schema) {\n return db('schemes')\n .insert(schema)\n .then(ids => findById(ids[0]));\n}",
"function add(scheme) {\n // Ensure valid ID\n if (!scheme || !scheme.id || typeof scheme.id !== 'string') {\n throw new Error('Cannot add invalid scheme. Requires at least an ID');\n }\n // Unique schemes\n if (schemes[scheme.id]) {\n throw new Error('Scheme ' + schemeId + ' already exists');\n }\n // Check default\n if (scheme.isDefault) {\n if (_default) {\n console.warn('Default scheme already exists');\n } else {\n _default = scheme.id;\n }\n }\n\n schemes[scheme.id] = scheme;\n }",
"updateSchema(schema) {\n // to avoid cyclic reference error, use flatted string.\n const schemaFlatted = (0, _flatted.stringify)(schema);\n this.run((0, _http.POST)(this.ws_url + '/schema/', schemaFlatted, 'text/plain')).then(data => {\n console.log(\"collab server's schema updated\"); // [FS] IRAD-1040 2020-09-08\n\n this.schema = schema;\n this.start();\n }, err => {\n this.report.failure('error');\n });\n }",
"function editEyelashScheme() {\n\n\t// Unlock eyelash scheme name textarea\n\t$('#eyelashSchemeName').toggleClass('schemeInfoArea lockedSchemeInfoArea').prop('readonly', false);\n\n\t// Remove icon 'delete'\n\t$('.iconDelete').remove();\n\n\t// Replace the icon 'save' with the icon 'edit'\n\t$('.iconEdit').replaceWith(\"<img class='iconSave' role='button' onclick='saveEditedEyelashScheme();' src='images/save.png'>\");\n\n\t// Show eyelash scheme editing elements\n\t$('.numOfAreasContainer, .parametersAreaContainer').show();\n\n\t// Create listeners of name area\n\t$('#eyelashSchemeName').bind('input propertychange', function() {\n\t\t$('#eyelashSchemeName').val($('#eyelashSchemeName').val().replace(/[^а-яёa-z0-9 ]/gi, ''));\n\t});\n}",
"function add(scheme) {\n return db('schemes')\n .insert(scheme, 'id')\n .then(ids => {\n const [id] = ids;\n return findById(id);\n });\n}",
"replaceSchemeWithPath(path) {\n return path.replace(SCHEME_MATCHER, (_, scheme) => this.schemeMap[scheme.toLowerCase()] || '');\n }",
"function change_swagger_urls(scheme, host, basePath){\n\t\tconsole.log('scheme:', scheme, ', host:', host, ', basePath:', basePath);\n\t\tif(!scheme || !host || !basePath){\n\t\t\treturn false;\n\t\t}\n\t\tfor(var i in window.swaggerUi.api){\n\t\t\tif(window.swaggerUi.api[i] && window.swaggerUi.api[i].apis){\n\t\t\t\tfor(var x in window.swaggerUi.api[i].apis){\n\t\t\t\t\twindow.swaggerUi.api[i].apis[x].scheme = scheme;\n\t\t\t\t\twindow.swaggerUi.api[i].apis[x].host = host;\n\t\t\t\t\twindow.swaggerUi.api[i].apis[x].basePath = basePath;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function wsDeleteScheme (wsio, data) {\n\tgetSchemeFromDb(function(result) {\n\t\tif (result.success) {\n\t\t\tconst newSchemes = result.data\n\t\t\t_.remove(newSchemes, (item) => {\n\t\t\t\treturn item.id === data.id\n\t\t\t})\n\t\t\tsetSchemeToDb(newSchemes, function() {\n\t\t\t\tbroadcastScheme()\n\t\t\t\twsio.emit(\"schemeDeleted\", data.name)\n\t\t\t})\n\t\t}\n\t})\n}",
"dsUpdateSchema(schema, what) {\n switch (what) {\n case \"import\":\n let schemaImported = lodash.cloneDeep(schema);\n // schemaImported.kpis.length = 0;\n // schemaImported.counters.length = 0;\n this.gMap.schemas.set(schema.id, schemaImported);\n break\n case \"add\":\n this.gMap.schemas.set(schema.id, lodash.cloneDeep(schema));\n break\n case \"clone\":\n let schemaCopy = lodash.cloneDeep(schema);\n schemaCopy.kpis = [];\n schemaCopy.counters = [];\n this.gMap.schemas.set(schema.id, schemaCopy);\n\n break\n case \"update\":\n let oldSchema = this.gMap.schemas.get(schema.id);\n oldSchema.schema_id = schema.schema_id;\n oldSchema.schema_zhname = schema.schema_zhname;\n oldSchema.vendor_id = schema.vendor_id;\n oldSchema.object_class = schema.object_class;\n oldSchema.sub_class = schema.sub_class;\n oldSchema.interval_flag = schema.interval_flag;\n oldSchema.counter_tab_name = schema.counter_tab_name;\n\n this.gMap.schemas.get(schema.id).kpis.forEach((kid) => {\n let kpi = this.gMap.kpis.get(kid);\n let newKpi = new TadKpi();\n\n newKpi.id = kid;\n newKpi.kpi_id = schema.schema_id.replace(/260/, \"\") + kpi.kpi_id.substr(kpi.kpi_id.length - 2, 2);\n\n this.doUpdateKpi(newKpi);\n })\n break\n case \"delete\":\n this.gMap.schemas.delete(schema.id);\n break\n default:\n break;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
do x=xyRi mod n for bigInts x,y,n, where Ri = 2(knbpe) mod n, and kn is the number of elements in the n array, not counting leading zeros. x array must have at least as many elemnts as the n array It's OK if x and y are the same variable. must have: x,y < n n is odd np = (n^(1)) mod radix | function mont_(x,y,n,np) {
var i,j,c,ui,t,t2,ks;
var kn=n.length;
var ky=y.length;
if (sa.length!=kn)
sa=new Array(kn);
copyInt_(sa,0);
for (;kn>0 && n[kn-1]==0;kn--); //ignore leading zeros of n
for (;ky>0 && y[ky-1]==0;ky--); //ignore leading zeros of y
ks=sa.length-1; //sa will never have more than this many nonzero elements.
//the following loop consumes 95% of the runtime for randTruePrime_() and powMod_() for large numbers
for (i=0; i<kn; i++) {
t=sa[0]+x[i]*y[0];
ui=((t & mask) * np) & mask; //the inner "& mask" was needed on Safari (but not MSIE) at one time
c=(t+ui*n[0]);
c = (c - (c & mask)) / radix;
t=x[i];
//do sa=(sa+x[i]*y+ui*n)/b where b=2**bpe. Loop is unrolled 5-fold for speed
j=1;
for (;j<ky-4;) {
c+=sa[j]+ui*n[j]+t*y[j]; t2=sa[j-1]=c & mask; c=(c-t2)/radix; j++;
c+=sa[j]+ui*n[j]+t*y[j]; t2=sa[j-1]=c & mask; c=(c-t2)/radix; j++;
c+=sa[j]+ui*n[j]+t*y[j]; t2=sa[j-1]=c & mask; c=(c-t2)/radix; j++;
c+=sa[j]+ui*n[j]+t*y[j]; t2=sa[j-1]=c & mask; c=(c-t2)/radix; j++;
c+=sa[j]+ui*n[j]+t*y[j]; t2=sa[j-1]=c & mask; c=(c-t2)/radix; j++;
}
for (;j<ky;) {
c+=sa[j]+ui*n[j]+t*y[j]; t2=sa[j-1]=c & mask; c=(c-t2)/radix; j++;
}
for (;j<kn-4;) {
c+=sa[j]+ui*n[j]; t2=sa[j-1]=c & mask; c=(c-t2)/radix; j++;
c+=sa[j]+ui*n[j]; t2=sa[j-1]=c & mask; c=(c-t2)/radix; j++;
c+=sa[j]+ui*n[j]; t2=sa[j-1]=c & mask; c=(c-t2)/radix; j++;
c+=sa[j]+ui*n[j]; t2=sa[j-1]=c & mask; c=(c-t2)/radix; j++;
c+=sa[j]+ui*n[j]; t2=sa[j-1]=c & mask; c=(c-t2)/radix; j++;
}
for (;j<kn;) {
c+=sa[j]+ui*n[j]; t2=sa[j-1]=c & mask; c=(c-t2)/radix; j++;
}
for (;j<ks;) {
c+=sa[j]; t2=sa[j-1]=c & mask; c=(c-t2)/radix; j++;
}
sa[j-1]=c & mask;
}
if (!greater(n,sa))
sub_(sa,n);
copy_(x,sa);
} | [
"function arrayOperation(x, y, n) {\n const r = [];\n for (let i = x; i <= y; i++) {\n if (i % n === 0) r.push(i);\n }\n return r;\n}",
"function mont_(x,y,n,np) {\n var i,j,c,ui,t,ks;\n var kn=n.length;\n var ky=y.length;\n\n if (sa.length!=kn)\n sa=new Array(kn);\n \n copyInt_(sa,0);\n\n for (;kn>0 && n[kn-1]==0;kn--); //ignore leading zeros of n\n for (;ky>0 && y[ky-1]==0;ky--); //ignore leading zeros of y\n ks=sa.length-1; //sa will never have more than this many nonzero elements. \n\n //the following loop consumes 95% of the runtime for randTruePrime_() and powMod_() for large numbers\n for (i=0; i<kn; i++) {\n t=sa[0]+x[i]*y[0];\n ui=((t & mask) * np) & mask; //the inner \"& mask\" was needed on Safari (but not MSIE) at one time\n c=(t+ui*n[0]) >> bpe;\n t=x[i];\n \n //do sa=(sa+x[i]*y+ui*n)/b where b=2**bpe. Loop is unrolled 5-fold for speed\n j=1;\n for (;j<ky-4;) { c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++; } \n for (;j<ky;) { c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++; }\n for (;j<kn-4;) { c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++; } \n for (;j<kn;) { c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++; } \n for (;j<ks;) { c+=sa[j]; sa[j-1]=c & mask; c>>=bpe; j++; } \n sa[j-1]=c & mask;\n }\n\n if (!greater(n,sa))\n sub_(sa,n);\n copy_(x,sa);\n }",
"function mont_(x, y, n, np) {\n var i, j, c, ui, t;\n var kn = n.length;\n var ky = y.length;\n\n if (sa.length != kn) {\n sa = new Array(kn);\n }\n\n for (; kn > 0 && n[kn - 1] == 0; kn--) {\n ;\n } //ignore leading zeros of n\n\n\n for (; ky > 0 && y[ky - 1] == 0; ky--) {\n ;\n } //ignore leading zeros of y\n\n\n copyInt_(sa, 0); //the following loop consumes 95% of the runtime for randTruePrime_() and powMod_() for large keys\n\n for (i = 0; i < kn; i++) {\n t = sa[0] + x[i] * y[0];\n ui = (t & mask) * np & mask; //the inner \"& mask\" is needed on Macintosh MSIE, but not windows MSIE\n\n c = t + ui * n[0] >> bpe;\n t = x[i]; //do sa=(sa+x[i]*y+ui*n)/b where b=2**bpe\n\n for (j = 1; j < ky; j++) {\n c += sa[j] + t * y[j] + ui * n[j];\n sa[j - 1] = c & mask;\n c >>= bpe;\n }\n\n for (; j < kn; j++) {\n c += sa[j] + ui * n[j];\n sa[j - 1] = c & mask;\n c >>= bpe;\n }\n\n sa[j - 1] = c & mask;\n }\n\n if (!greater(n, sa)) {\n sub_(sa, n);\n }\n\n copy_(x, sa);\n }",
"function mont_(x,y,n,np) {\n var i,j,c,ui,t,ks;\n var kn=n.length;\n var ky=y.length;\n\n if (sa.length!=kn)\n sa=new Array(kn);\n\n copyInt_(sa,0);\n\n for (;kn>0 && n[kn-1]==0;kn--); //ignore leading zeros of n\n for (;ky>0 && y[ky-1]==0;ky--); //ignore leading zeros of y\n ks=sa.length-1; //sa will never have more than this many nonzero elements.\n\n //the following loop consumes 95% of the runtime for randTruePrime_() and powMod_() for large numbers\n for (i=0; i<kn; i++) {\n t=sa[0]+x[i]*y[0];\n ui=((t & mask) * np) & mask; //the inner \"& mask\" was needed on Safari (but not MSIE) at one time\n c=(t+ui*n[0]) >> bpe;\n t=x[i];\n\n //do sa=(sa+x[i]*y+ui*n)/b where b=2**bpe. Loop is unrolled 5-fold for speed\n j=1;\n for (;j<ky-4;) { c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++; }\n for (;j<ky;) { c+=sa[j]+ui*n[j]+t*y[j]; sa[j-1]=c & mask; c>>=bpe; j++; }\n for (;j<kn-4;) { c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++;\n c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++; }\n for (;j<kn;) { c+=sa[j]+ui*n[j]; sa[j-1]=c & mask; c>>=bpe; j++; }\n for (;j<ks;) { c+=sa[j]; sa[j-1]=c & mask; c>>=bpe; j++; }\n sa[j-1]=c & mask;\n }\n\n if (!greater(n,sa))\n sub_(sa,n);\n copy_(x,sa);\n}",
"function multMod_(x,y,n) {\n var i;\n if (s0.length!=2*x.length)\n s0=new Array(2*x.length);\n copyInt_(s0,0);\n for (i=0;i<y.length;i++)\n if (y[i])\n linCombShift_(s0,x,y[i],i); //s0=1*s0+y[i]*(x<<(i*bpe))\n mod_(s0,n);\n copy_(x,s0);\n }",
"function multMod_(x, y, n) {\n var i;\n if (s0.length != 2 * x.length) s0 = new Array(2 * x.length);\n copyInt_(s0, 0);\n for (i = 0; i < y.length; i++) if (y[i]) linCombShift_(s0, x, y[i], i); //s0=1*s0+y[i]*(x<<(i*bpe))\n mod_(s0, n);\n copy_(x, s0);\n}",
"function generateNumbers() {\n for (var i = 0; 624 > i; ++i) {\n var y = (MT[i] & 0x80000000) | (MT[(i+1) % 624] & 0x7fffffff);\n y=y>>>0;\n var xA = (y/2) & 0x7fffffff;\n xA=xA>>>0;\n if((y % 2) != 0){ xA = xA ^ 0x9908b0df; }\n xA=xA>>>0;\n MT[i]=MT[(i+397)%624] ^ xA;\n MT[i]=MT[i]>>>0;\n }\n}",
"function countBy(x, n) {\n var z = [];\n var y = x * n;\n for(let i = 1; i <= y ; i++){\n if(i % x === 0) z.push(i)\n }\n return z;\n }",
"function powMod(x,y,n) {\n var ans=expand(x,n.length); \n powMod_(ans,trim(y,2),trim(n,2),0); //this should work without the trim, but doesn't\n return trim(ans,1);\n }",
"function multiples(m, n) {\n return Array.from(Array(m), (_v, i) => (i + 1) * n);\n}",
"function powMod(x,y,n) {\n var ans=expand(x,n.length);\n powMod_(ans,trim(y,2),trim(n,2),0); //this should work without the trim, but doesn't\n return trim(ans,1);\n }",
"function euler(N) {\n var n, e, k;\n var bheuler = function(limit) {\n var tmp;\n var j, k, N;\n var e;\n\n N = limit + 1;\n\n if (N < STATIC_EULER_ARRAY_SIZE) {\n //console.log(\"Cache hit:\" + N);\n return MP_OKAY;\n }\n // calculate the first one hundred to fill the cache\n // because Euler numbers almost always come in hordes.\n if (STATIC_EULER_ARRAY_SIZE == 0 && N <\n STATIC_EULER_ARRAY_PREFILL) {\n N = STATIC_EULER_ARRAY_PREFILL;\n }\n /* For sake of simplicity */\n //euler_array = malloc(sizeof(mp_int)*N+2);\n STATIC_EULER_ARRAY = new Array(N + 2);\n STATIC_EULER_ARRAY[0] = new Bigint(1);\n for (k = 1; k <= N; k++) {\n STATIC_EULER_ARRAY[k] = STATIC_EULER_ARRAY[k - 1].mulInt(k);\n }\n STATIC_EULER_ARRAY[k] = new Bigint(0);\n\n for (k = 1; k < N; k++) {\n for (j = k + 1; j < N; j++) {\n /* euler_array[j] = (j-k)*euler_array[j-1] + (j-k+1)*euler_array[j] */\n /* tmp = (j-k)*euler_array[j-1] */\n tmp = STATIC_EULER_ARRAY[j - 1].mulInt(j - k);\n /* euler_array[j] = (j-k+1)*euler_array[j] */\n STATIC_EULER_ARRAY[j] = STATIC_EULER_ARRAY[j].mulInt(j -\n k + 1);\n\n /* euler_array[j] = euler_array[j] + tmp*/\n STATIC_EULER_ARRAY[j] = STATIC_EULER_ARRAY[j].add(tmp);\n }\n }\n for (k = 0; k < N; k++) {\n /* Even Euler numbers (if indexed by even n) are negative */\n if (k & 0x1) {\n STATIC_EULER_ARRAY[k].sign = MP_NEG;\n }\n }\n STATIC_EULER_ARRAY_SIZE = N;\n return MP_OKAY;\n };\n\n n = N;\n\n /* all odd Euler numbers are zero */\n if ((n & 0x1) && n != 1) {\n return new Bigint(0);\n }\n if ((e = bheuler(Math.floor(n / 2))) != MP_OKAY) {\n return e;\n }\n k = Math.floor(n / 2);\n return STATIC_EULER_ARRAY[k];\n}",
"function mulSubset(nx1, n0, n) {\n\tconst r = [];\n\tlet step = n0*4;\n\tlet t = 0;\n\tlet max;\n\tlet cap;\n\tfor (let i = n0+1; i <= n; i++) {\n\t\tstep += 4;\n\t\tt = 0;\n\t\tfor (let j = i-1; j < n; j += step) {\n\t\t\tmax = j+i;\n\t\t\tcap = max > n ? n : max;\n\t\t\tfor (let k = j; k < cap; k++) {\n\t\t\t\tt += nx1[k-n0];\n\t\t\t}\n\t\t\tmax += i+i;\n\t\t\tcap = max > n ? n : max;\n\t\t\tfor (let k2 = j+i+i; k2 < cap; k2++) {\n\t\t\t\tt -= nx1[k2-n0];\n\t\t\t}\n\t\t}\n\t\tr[i-1] = Math.abs(t % 10);\n\t}\n\treturn r;\n}",
"function powMod(x, y, n) {\n var ans = expand(x, n.length);\n powMod_(ans, trim(y, 2), trim(n, 2), 0); //this should work without the trim, but doesn't\n return trim(ans, 1);\n }",
"function powMod(x, y, n) {\n var ans = expand(x, n.length);\n powMod_(ans, trim(y, 2), trim(n, 2), 0); //this should work without the trim, but doesn't\n return trim(ans, 1);\n }",
"function dynamicArray(n, queries) {\r\n // Write your code here\r\n // Initialize returned array\r\n let arr=[];\r\n for(let i = 0; i < n; i++){\r\n arr[i]=[];\r\n }\r\n \r\n //Run through the queries\r\n let queryType=1;\r\n let x;\r\n let y;\r\n let lastAnswer=0;\r\n let arrayToUpdate=[];\r\n let intArray=[];\r\n for(let i = 0; i < queries.length; i++){\r\n queryType=queries[i][0];\r\n x = queries[i][1];\r\n y = queries[i][2];\r\n arrayToUpdate = arr[(x ^ lastAnswer) % n];\r\n \r\n if(queryType == 1){\r\n arrayToUpdate.push(y);\r\n }\r\n else{\r\n lastAnswer = arrayToUpdate[y % arrayToUpdate.length];\r\n intArray.push(lastAnswer);\r\n }\r\n } \r\n \r\n return intArray;\r\n}",
"function bigmod(n, m) {\n\t let c = 1, r = 0;\n\n\t for(let i = 0; i < n.length; ++i) {\n\t\t\t// ab % m = ((a % m) * (b % m)) % m\n\t\t\t// a = digit, b = base\n\t\t\tr = (((n[i]%m)*(c%m))%m + r)%m;\n\t\t\tc = (256*c)%m;\n\t }\n\n\t return r;\n\t}",
"function modInt(x,n) {\n var i,c=0;\n for (i=x.length-1; i>=0; i--)\n c=(c*radix+x[i])%n;\n return c;\n }",
"function modInt(x,n) {\n var i,c=0;\n for (i=x.length-1; i>=0; i--)\n c=(c*radix+x[i])%n;\n return c;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=================================================================== from functions/maths/ComplexParts.java =================================================================== Needed early: Builtin Needed late: Complex Pair | function ComplexParts() {
} | [
"function EBX_ComplexList() {}",
"function EBX_ComplexList() {\n}",
"function Complex() {\n this._chains = [];\n this._components = [];\n this._helices = [];\n this._sheets = [];\n this.structures = [];\n\n this._residueTypes = Object.create(ResidueType.StandardTypes);\n this._atoms = []; // TODO: preallocate\n this._residues = []; // TODO: preallocate\n this._bonds = []; // TODO: preallocate\n this._sgroups = [];\n this._molecules = [];\n this._maskNeedsUpdate = false;\n\n this.metadata = {};\n\n this.symmetry = [];\n this.units = [new BiologicalUnit(this)];\n this._currentUnit = 0; // default biological unit is the asymmetric unit\n}",
"function Complex() {\n this._chains = [];\n this._components = [];\n this._helices = [];\n this._sheets = [];\n this._residueTypes = Object.create(ResidueType.StandardTypes);\n this._atoms = [];\n // TODO: preallocate\n this._residues = [];\n // TODO: preallocate\n this._bonds = [];\n // TODO: preallocate\n this._sgroups = [];\n this._aSelOutOfDate = false;\n this._rSelOutOfDate = false;\n this.metadata = {};\n this.boundingBox = new THREE.Box3();\n this.boundingSphere = new THREE.Sphere();\n }",
"function Complex() {\n this._chains = [];\n this._components = [];\n this._helices = [];\n this._sheets = [];\n\n this._residueTypes = Object.create(ResidueType.StandardTypes);\n this._atoms = []; // TODO: preallocate\n this._residues = []; // TODO: preallocate\n this._bonds = []; // TODO: preallocate\n this._sgroups = [];\n this._molecules = [];\n this._maskNeedsUpdate = false;\n\n this.metadata = {};\n\n this.symmetry = [];\n this.structures = [new BioStructure(this)];\n this._currentStructure = 0; // default biological structure is the asymmetric unit\n}",
"function createComplex(real, imag) {\n return {\n real: real,\n imag: imag\n };\n }",
"function complexMultiply(a, b){\n return [(a[0] * b[0] - a[1] * b[1]), \n (a[0] * b[1] + a[1] * b[0])];\n }",
"function createComplexNumber (real, imaginary) {\n//create a complexNumberPrototype object\n let complexObj = Object.create(complexNumberPrototype);\n //send the real number parameter to the realValue property in the complexNumberPrototype\n complexObj.realValue = real;\n //send the imaginary number parameter to the imaginaryValue property in the complexNumberPrototype\n complexObj.imaginaryValue = imaginary;\n //return the object with the given values based on the complexNumberPrototype\n return complexObj;\n}",
"_parseComplexNumber(base) {\n const a = this._parseRealNumber(base);\n const c = this.txt[this.i];\n if (c == \"@\") {\n this.i++;\n return this._parsePolarComplexNumber(a, base);\n } else if (c == \"+\" || c == \"-\") {\n this.i--; // Unget the sign\n return this._parseOrthoComplexNumber(a, base);\n } else {\n // Was not a complex number.\n return a;\n }\n }",
"function createComplex(real, imag) {\n return {\n real: real,\n imag: imag\n };\n}",
"function ComplexNumber2(real, im) {\n this.real = real;\n this.im = im;\n this.print = () => {\n console.log(`${this.real}+${this.im}i`);\n }\n //The add method destructures the real and imaginary component from the passed complex number object into variables real and\n //im. Then the destructured variables are simply added to the real and imaginary compoenents of the complex number the\n //method was called on.\n this.add = (complexTwo) => {\n let {real, im} = complexTwo;\n let newReal = this.real + real;\n let newIm = this.im + im;\n return new ComplexNumber2(newReal, newIm);\n }\n //Subtract works the same way as add but simply subtracts the destructured variables instad of adding them to the real and\n //imaginary components of the the complex number the method was called on.\n this.subtract = (complexTwo) => {\n let {real, im} = complexTwo;\n let newReal = this.real - real;\n let newIm = this.im - im;\n return new ComplexNumber2(newReal, newIm);\n }\n //Divide works by multiplying the numerator and the denominator (the object and the argument respectively) by the complex\n //conjugate of the denominator. This removes the imaginary part from the denominator and allows the complex number to be\n //written in the format \"{real}+{im}i\".\n this.divide = (complexTwo) => {\n let {real, im} = complexTwo;\n let denominator = Math.pow(real, 2) + Math.pow(im, 2);\n let currentReal = this.real;\n let currentIm = this.im;\n let newReal = ((currentReal * real) + (currentIm * im)) / denominator;\n let newIm = ((currentReal * im) - (currentIm * real)) / denominator;\n return new ComplexNumber2(newReal, newIm);\n }\n //Multiply works by implementing FOIL multiplication of the real and imaginary components. Ex. (3+2i)(1+4i) = 3*1 + 3*4i +\n //2i*1 + 2i*4i = (3-8) + (12 + 2)i = -5 + 14i.\n this.multiply = (complexTwo) => {\n let {real, im} = complexTwo;\n let currentReal = this.real;\n let currentIm = this.im;\n let newReal = (currentReal * real) - (currentIm * im);\n let newIm = (currentReal * im) + (currentIm * real);\n return new ComplexNumber2(newReal, newIm);\n }\n}",
"conjugate() {\n return new Complex(this.realPart, -this.imaginaryPart);\n }",
"add(complex) {\n\n let newRealPart = this.realPart + complex.realPart;\n let newImaginaryPart = this.imaginaryPart + complex.imaginaryPart;\n\n return new Complex(newRealPart, newImaginaryPart);\n }",
"function multComplex(real1, imag1, real2, imag2) {\n var real = (real1 * real2) - (imag1 * imag2);\n var imag = (real1 * imag2) + (imag1 * real2);\n return [real, imag];\n\n }",
"function Complex(real, imaginary) {\n this.x = real; // The real part of the number\n this.y = imaginary; // The imaginary part of the number\n}",
"function ComplexNumber(real, img)\n{\n\tthis.real = real;\n\tthis.img = img;\n}",
"function magnitude(complex) {\n complex.forEach((pair, index) => {\n complex[index] = Math.sqrt(Math.pow(pair[0], 2) + Math.pow(pair[1], 2))\n })\n return complex\n}",
"function complexeMod(x,y){\n return Math.sqrt(x*x+y*y);\n}",
"function complexify(x){return typeof x==='number'?new Z(x,0):x instanceof Z?x:domainError()}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if user matches the given ruleset | function checkRules(options) {
/* istanbul ignore else */
if (options.rules) {
const time = new Date(options.time);
const recurr = options.recurr_end ? new Date(options.recurr_end) : new Date();
const count = Object.keys(options.rules).length;
let matches = 0;
for (const key of Object.keys(options.rules)) {
let counter = 0;
const condition = options.rules[key] instanceof Array
? options.rules[key]
: [options.rules[key]];
switch (key) {
// case 'groups':
// /* istanbul ignore else */
// if (options.user && options.user.groups) {
// counter = 0;
// condition.forEach((i) =>
// options.user.groups.find((j) => j === i) ? counter++ : null
// );
// /* istanbul ignore else */
// if (counter > 0) {
// matches++;
// }
// }
// break;
// case 'locations':
// /* istanbul ignore else */
// if (options.user && options.user.location) {
// counter = 0;
// condition.forEach((i) =>
// (options.user.last_location.name || '').indexOf(i) >= 0
// ? counter++
// : null
// );
// /* istanbul ignore else */
// if (counter >= options.rules[key].length) {
// matches++;
// }
// }
// break;
case 'is_before':
/* istanbul ignore else */
if (options.time) {
const duration = stringToMinutes(condition[0]);
const check = Object(date_fns__WEBPACK_IMPORTED_MODULE_1__["add"])(new Date(), { minutes: duration });
let match = Object(date_fns__WEBPACK_IMPORTED_MODULE_1__["isBefore"])(time, check);
/* istanbul ignore else */
if (recurr) {
match = match && Object(date_fns__WEBPACK_IMPORTED_MODULE_1__["isBefore"])(recurr, check);
}
matches += match ? 1 : 0;
}
break;
case 'is_after':
/* istanbul ignore else */
if (options.time) {
const duration = stringToMinutes(condition[0]);
const check = Object(date_fns__WEBPACK_IMPORTED_MODULE_1__["add"])(new Date(), { minutes: duration });
if (Object(date_fns__WEBPACK_IMPORTED_MODULE_1__["isAfter"])(time, check)) {
matches++;
}
}
break;
case 'min_length':
/* istanbul ignore else */
if (options.duration &&
durationGreaterThanOrEqual(options.duration, condition[0])) {
matches++;
}
break;
case 'max_length':
/* istanbul ignore else */
if (options.duration &&
durationGreaterThanOrEqual(condition[0], options.duration)) {
matches++;
}
break;
}
}
return matches >= count;
}
return false;
} | [
"static async testUser(user, rule, ctx = null) {\n return this.testUserAny(user, rule, ctx);\n }",
"function matchSchemaAgainstRuleSet(ruleSet, schema) {\n var rejectCount = 0;\n var acceptCount = 0;\n var acceptRules = ruleSet['accept'];\n if (Array.isArray(acceptRules)) {\n if (ruleSet.accept.some(function (rule) { return matchSchemaAgainstRule(rule, schema); })) {\n acceptCount++;\n }\n }\n else if (typeof acceptRules === 'string') {\n if (matchSchemaAgainstRule(acceptRules, schema)) {\n acceptCount++;\n }\n }\n var rejectRules = ruleSet['reject'];\n if (Array.isArray(rejectRules)) {\n if (ruleSet.reject.some(function (rule) { return matchSchemaAgainstRule(rule, schema); })) {\n rejectCount++;\n }\n }\n else if (typeof rejectRules === 'string') {\n if (matchSchemaAgainstRule(rejectRules, schema)) {\n rejectCount++;\n }\n }\n if (acceptCount > 0 && rejectCount === 0) {\n return true;\n }\n else if (acceptCount === 0 && rejectCount > 0) {\n return false;\n }\n return false;\n}",
"function playedRequiredMatches(user) {\n if ((user.aboveUser != null) && (user.aboveResult == \"\"))\n return false;\n if ((user.belowUser != null) && (user.belowResult == \"\"))\n return false;\n return true;;\n}",
"function checkRules(options) {\n if (options.rules) {\n const time = dayjs__WEBPACK_IMPORTED_MODULE_4__(options.time);\n const count = Object.keys(options.rules).length;\n let matches = 0;\n for (const key of Object.keys(options.rules)) {\n let counter = 0;\n const condition = options.rules[key] instanceof Array\n ? options.rules[key]\n : [options.rules[key]];\n switch (key) {\n case 'group':\n case 'groups':\n if (options.user && options.user.groups) {\n counter = 0;\n condition.forEach((i) => options.user.groups.find((j) => j === i) ? counter++ : null);\n if (counter > 0) {\n matches++;\n }\n }\n break;\n case 'location':\n case 'locations':\n // if (options.user && options.user.location) {\n // counter = 0;\n // condition.forEach(i =>\n // (options.user.last_location.name || '').indexOf(i) >= 0\n // ? counter++\n // : null\n // );\n // if (counter >= options.rules[key].length) {\n // matches++;\n // }\n // }\n break;\n case 'is_before':\n if (options.time) {\n const duration = stringToMinutes(condition[0]);\n const check = dayjs__WEBPACK_IMPORTED_MODULE_4__().add(duration, 'm');\n let match = time.isBefore(check, 'm');\n matches += match ? 1 : 0;\n }\n break;\n case 'is_after':\n if (options.time) {\n const [amount, unit] = condition[0].split(' ');\n const check = dayjs__WEBPACK_IMPORTED_MODULE_4__().add(+amount, unit);\n time.isAfter(check, unit) ? matches++ : '';\n }\n break;\n case 'from_time':\n const after_time = dayjs__WEBPACK_IMPORTED_MODULE_4__(condition[0], 'HH:mm');\n if (dayjs__WEBPACK_IMPORTED_MODULE_4__().isAfter(after_time, 'm')) {\n matches++;\n }\n break;\n case 'min_length':\n if (options.duration) {\n durationGreaterThanOrEqual(options.duration, condition[0]) ? matches++ : '';\n }\n break;\n case 'max_length':\n if (options.duration) {\n durationGreaterThanOrEqual(condition[0], options.duration) ? matches++ : '';\n }\n break;\n case 'visitor_types':\n if (options.visitor_type) {\n counter = 0;\n condition.forEach((i) => (i === options.visitor_type ? counter++ : null));\n if (counter > 0) {\n matches++;\n }\n }\n break;\n }\n }\n return matches >= count;\n }\n return false;\n}",
"function isRuleSet(input) {\n var ruleSet = input;\n var ruleCount = 0;\n if (input != null && typeof input === 'object' && !Array.isArray(input)) {\n if (Object.prototype.hasOwnProperty.call(ruleSet, 'accept')) {\n if (isValidRuleSetArg(ruleSet['accept'])) {\n ruleCount += 1;\n }\n else {\n return false;\n }\n }\n if (Object.prototype.hasOwnProperty.call(ruleSet, 'reject')) {\n if (isValidRuleSetArg(ruleSet['reject'])) {\n ruleCount += 1;\n }\n else {\n return false;\n }\n }\n // if either 'reject' or 'accept' or both exists,\n // we have a valid ruleset\n return ruleCount > 0 && ruleCount <= 2;\n }\n return false;\n}",
"function addingUserRuleToUserRule_StartsWithAndUserRule_EndsWithArrays () {\r\n\r\n // get the user rule selected\r\n const userRule = rulesInput.options[rulesInput.selectedIndex].value\r\n\r\n // if rule starts With is selected then push that value into the \r\n // userRule_StartsWith array\r\n if (userRule == 1) {\r\n // check if numberEnteredInput already exists to avoid duplicates\r\n if (!userRuleStartsWith.includes(numberEnteredInput.value)) {\r\n // final check to not allow any empty values to be pushed to the array\r\n if (numberEnteredInput.value !== '') {\r\n userRuleStartsWith.push(numberEnteredInput.value)\r\n return true\r\n }\r\n }\r\n }\r\n\r\n // if rule ends With is selected then push that value into the userRule_EndsWith array\r\n if (userRule == 2) {\r\n // check if numberEnteredInput already exists to avoid duplicates\r\n if (!userRuleEndsWith.includes(numberEnteredInput.value)) {\r\n // final check to not allow any empty values to be pushed to the array\r\n if (numberEnteredInput.value !== '') {\r\n userRuleEndsWith.push(numberEnteredInput.value)\r\n return true\r\n }\r\n }\r\n }\r\n\r\n return false\r\n}",
"function checkRules(post, rules) {\n var ok = true;\n if (rules) {\n Object.keys(rules).forEach(function(key) {\n var rule = rules[key];\n switch (rule.type) {\n case \"not_u\":\n if (post.uid == rule.value) {\n ok = false;\n }\n break;\n case \"no_string\":\n if (post.content.indexOf(rule.value) !== -1) {\n ok = false;\n }\n break;\n }\n });\n }\n if (ok) {\n return true;\n } else {\n return false;\n }\n}",
"function match(patterns, usr) {\n /* If email exist but not match return false. */\n if (patterns.email && usr.email.indexOf(patterns.email) == -1) {\n return false;\n }\n\n /* If age exist but not match return false. */\n if (patterns.age && patterns.age != getAge(usr.birthday)) {\n return false;\n }\n\n /* If phone exist but not match return false. */\n if (patterns.phone && patterns.phone.replace(\"-\",\"\") != usr.phone.replace(\"-\",\"\")) {\n return false;\n }\n\n // TODO: find patterns for city, street, country (with pre-processing dictionaries for example).\n\n /* All other treats as name. */\n for (var i=0 ; i < patterns.free.length ; i++) {\n if (usr.name.toLowerCase().indexOf(patterns.free[i]) == -1)\n return false;\n }\n\n return true;\n}",
"every(obj) { return this.rules.every(rule => rule.match(obj)) }",
"function find_rule_local(gender, name, ruleset, match_whole_word, tags) {\n for (var i = 0; i < ruleset.length; i++) {\n var rule = ruleset[i];\n if (rule.tags) {\n var common_tags = [];\n for (var j = 0; j < rule.tags.length; j++) {\n var tag = rule.tags[j];\n if (!contains(tags, tag)) common_tags.push(tag);\n }\n if (!common_tags.length) continue;\n }\n if (rule.gender !== 'androgynous' && gender !== rule.gender)\n continue;\n\n name = name.toLowerCase();\n for (var j = 0; j < rule.test.length; j++) {\n if (match_sample(match_whole_word, name, rule.test[j])) return rule;\n }\n }\n return false;\n }",
"function matchAllRules(rules, date, start) {\n let i, len, rule, type\n\n for (i = 0, len = rules.length; i < len; i++) {\n rule = rules[i]\n type = ruleTypes[rule.measure]\n\n if (type === \"interval\") {\n if (!Interval.match(rule.measure, rule.units, start, date)) {\n return false\n }\n } else if (type === \"calendar\") {\n if (!Calendar.match(rule.measure, rule.units, date)) {\n return false\n }\n } else {\n return false\n }\n }\n\n return true\n}",
"function setPasswordRules() {\n var userInput;\n var passwordRules = [];\n\n userInput = confirm(\"Should password contain LOWERCASE letters?\");\n if (userInput) {\n passwordRules.push(lowerCaseLetters);\n }\n userInput = confirm(\"Should password contain UPPERCASE letters?\");\n if (userInput) {\n passwordRules.push(upperCaseLetters);\n }\n userInput = confirm(\"Should password contain NUMBERS?\");\n if (userInput) {\n passwordRules.push(numbers);\n }\n userInput = confirm(\"Should password contain SPECIAL CHARACTERS?\");\n if (userInput) {\n passwordRules.push(specialChars);\n }\n if (passwordRules.length === 0) {\n alert(\n \"At least one rule needs to be applied, please try again from the beginning\"\n );\n return;\n }\n return passwordRules;\n}",
"function matchAllRules(rules, date, start) {\n var i,\n len,\n rule,\n type;\n\n for (i = 0, len = rules.length; i < len; i++) {\n rule = rules[i];\n type = ruleTypes[rule.measure];\n\n if (type === 'interval') {\n if (!Interval.match(rule.measure, rule.units, start, date)) {\n return false;\n }\n } else if (type === 'calendar') {\n if (!Calendar.match(rule.measure, rule.units, date)) {\n return false;\n }\n } else {\n return false;\n }\n }\n\n return true;\n }",
"function setRule(chosenRule) {\n chosenRule = chosenRule.toLowerCase();\n if (rules.includes(chosenRule)) {\n rule = chosenRule;\n return true;\n } else {\n return false;\n }\n}",
"function ruleLoader(username) {\n\t// Get a list of groups the user is a part of\n\t\n\tvar checklist = [username];\n\tvar nGroups = Rules.ruleSet[0].length;\n\tfor (var i = 0; i < nGroups; i++) {\n\t\tvar inGroup = $.inArray(username, Rules.ruleSet[0][i][1]);\n\t\tif (inGroup > -1) {\n\t\t\tchecklist.push(Rules.ruleSet[0][i][0]);\n\t\t}\n\t}\n\t// Check each repo against the checklist\n\tvar nRepos = Rules.ruleSet[2].length;\n\tvar nChecklist = checklist.length;\n\tvar perms = []; // perms[i][0] is all the repos with permissions\n\tfor (var i = 0; i < nRepos; i++) {\n\t\tvar nRules = Rules.ruleSet[2][i][1].length;\n\t\tvar repoPerms = [];\n\t\tfor (var j = 0; j < nRules; j++) {\n\t\t\t// Check to see if all, *, has permissions\n\t\t\tif (Rules.ruleSet[2][i][1][j][0] == [\"*\"] && Rules.ruleSet[2][i][1][j][1] != \"\") {\n\t\t\t\trepoPerms.push(Rules.ruleSet[2][i][1][j]);\n\t\t\t}\n\t\t\t// Check the checklist against repo rules\n\t\t\tfor ( var k = 0; k < nChecklist; k++) {\n\t\t\t\tif (checklist[k] == Rules.ruleSet[2][i][1][j][0]) {\n\t\t\t\t\trepoPerms.push([Rules.ruleSet[2][i][1][j][1], Rules.ruleSet[2][i][1][j][0]]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Add the repo perms to perms list\n\t\tif (repoPerms.length != 0) {\n\t\t\tperms.push([Rules.ruleSet[2][i][0], repoPerms]);\n\t\t}\n\t}\n\treturn perms;\n}",
"function findMatchingRules(currentUrl, ruleSetsCallback, callIfNone) {\n chrome.storage.local.get('testofill.rules', function(items) {\n if (typeof chrome.runtime.lastError !== \"undefined\") {\n console.log(\"ERROR Run.js: Rules loading failed\", chrome.runtime.lastError);\n return;\n }\n\n var rules = items['testofill.rules'];\n var matchFound = false;\n\n if (typeof rules !== 'undefined' && typeof rules.forms !== 'undefined') {\n for (var urlRE in rules.forms) {\n if (currentUrl.match(new RegExp(urlRE))) {\n matchFound = true;\n ruleSetsCallback(rules.forms[urlRE]);\n }\n }\n }\n\n if (callIfNone && !matchFound) {\n ruleSetsCallback([]);\n }\n });\n}",
"function verify(candidate, rules = [isDefined]) {\n for (let rule of rules) {\n if (!rule(candidate)) return false;\n }\n\n return true;\n}",
"function rulesForSpace(options) {\n if (!options) {\n throw Error('Options are needed to check for rule matches');\n }\n const space_rules_for_user = {\n auto_approve: true,\n hide: false,\n };\n if (options.space) {\n for (const type of Object.keys(options.rules || {})) {\n if (options.rules.hasOwnProperty(type) &&\n options.rules[type] instanceof Array &&\n (options.space.zones || []).find((i) => i === type)) {\n space_rules_for_user.hide = true;\n for (const rule_block of options.rules[type]) {\n if (checkRules({\n user: options.user,\n space: options.space,\n time: options.time,\n visitor_type: options.visitor_type,\n duration: options.duration,\n rules: rule_block.conditions,\n })) {\n const ruleset = rule_block.rules;\n const conditions = rule_block.conditions;\n space_rules_for_user.hide = false;\n if (conditions.max_length) {\n space_rules_for_user.max_length = stringToMinutes(conditions.max_length);\n }\n if (conditions.min_length) {\n space_rules_for_user.min_length = stringToMinutes(conditions.min_length);\n }\n // NOTE: use max_length in conditions instead of book_length in rules\n // if (ruleset.book_length) {\n // space_rules_for_user.max_length = stringToMinutes(ruleset.book_length as string);\n // }\n if (ruleset.auto_approve !== undefined) {\n space_rules_for_user.auto_approve = ruleset.auto_approve;\n }\n if (ruleset.room_type !== undefined) {\n space_rules_for_user.room_type = ruleset.room_type;\n }\n break;\n }\n }\n if (!space_rules_for_user.hide) {\n break;\n }\n }\n }\n }\n return space_rules_for_user;\n}",
"isValid(){\n var is_valid = true;\n //iterates every rule insided the set and checks if it is valid\n this.Rules.forEach(element => {\n if(!element.valid){\n is_valid = false;\n return false;\n }\n });\n \n return is_valid;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
AuthCtrl manages the authentification feature and manages templates/login.html.erb Uses angulardevise module | function AuthCtrl($state,Auth){
/* jshint validthis: true */
var authCtrl = this;
authCtrl.login = login;
authCtrl.register = register;
/**
* Called when logging in
*/
function login() {
Auth.login(authCtrl.user).then(function(){
$state.go('home');
});
}
/**
* Called when registering a new user
* Deactivated by default in the template
*/
function register() {
Auth.register(authCtrl.user).then(function(){
$state.go('home');
});
}
} | [
"function LoginController ($rootScope, $state, authorizationService, $log){\r\n\r\n var self = this;\r\n self.formData = {};\r\n self.isLoginFormActive = true;\r\n self.authorization = authorizationService;\r\n\r\n self.doLogin = doLogin;\r\n self.resetPassword = resetPassword;\r\n\r\n function doLogin (path) {\r\n self.authorization.login({\r\n path: path,\r\n formData: self.formData\r\n });\r\n }\r\n\r\n function resetPassword (path){\r\n self.authorization.resetPassword({\r\n path: path,\r\n formData: self.formData\r\n })\r\n }\r\n\r\n // set sidebar closed and body solid layout mode\r\n $rootScope.settings.layout.pageSidebarClosed = false;\r\n\r\n }",
"function login() {\n var userData = { \"username\": vm.username, \"password\": vm.password };\n $scope.indexCtrl.login(userData);\n }",
"function login(){\r\n auth.signin(\r\n {},\r\n function(profile, token){\r\n store.set('profile', profile);\r\n store.set('id_token', token);\r\n $location.path('/home');\r\n },\r\n function(error){\r\n console.log(error);\r\n }\r\n );\r\n }",
"function LogInCtrl (agentService, $window, $state, $ionicLoading, $ionicPlatform, $ionicPopup, $timeout) {\n this.agentService = agentService;\n this.$state = $state;\n this.$timeout = $timeout;\n this.$window = $window;\n this.$ionicLoading = $ionicLoading;\n this.$ioicPlatform = $ionicPlatform;\n this.$ionicPopup = $ionicPopup;\n var self = this;\n\n\n //Checks to see if the user has already been authenticated in the past\n if ($window.localStorage['configObj']) {\n this.agentService.configObj = JSON.parse($window.localStorage.getItem('configObj'));\n this.agentService.getInitialInformation().then(function(results) {\n self.agentService.routeMe();\n }, function(err) {\n err = err || \"\";\n $window.localStorage.clear();\n self.showAlert('Sorry something went wrong. Please try logging in again', err.statusText);\n });\n }\n\n this.logInField = {\n email : '',\n password: ''\n };\n}",
"function LoginController(OAuth, Auth, appname, $state) {\n var scope = this;\n\n // Services\n scope.OAuthSvc_ = OAuth;\n scope.AuthSvc_ = Auth;\n scope.StateSvc_ = $state;\n scope.AppName_ = appname;\n\n // Variables\n scope.invalidCredentials = undefined;\n scope.credentials = {\n userName: undefined,\n password: undefined\n };\n scope.isAuthenticated = false;\n\n // Custom Behaviors\n scope.login = function () {\n scope.isAuthenticated = false;\n\n if (angular.isDefined(scope.credentials.userName) && angular.isDefined(scope.credentials.password)) {\n scope.AuthSvc_.removeToken(scope.AppName_);\n scope.OAuthSvc_.login(scope.credentials).then(function(data) {\n var token = scope.AuthSvc_.getToken();\n if (angular.isDefined(token)) {\n scope.isAuthenticated = scope.AuthSvc_.isAuthenticated();\n scope.StateSvc_.go('home');\n }\n }).catch(function (ex) {\n console.log(ex);\n scope.invalidCredentials = ex.statusText;\n scope.isAuthenticated = false;\n });\n }\n };\n}",
"function authentication($auth, $state, _, Restangular, $rootScope, authEvents) {\n\n var auth = {\n resetPassword: resetPassword,\n login: login,\n verifyEmail: verifyEmail,\n verifyPassword: verifyPassword,\n logout: logout,\n disableOnLoggedIn: disableOnLoggedIn,\n };\n\n return auth;\n\n /**\n * Call to reset your password. The email listed will have a new email sent\n * to it.\n *\n * @param {string} email Email to send new password to.\n */\n function resetPassword(email) {\n if (verifyEmail(email)) {\n Restangular.one('users', email).customGET('reset-password');\n }\n }\n\n /**\n * Log the user into the yourAppName server using an email and password.\n * If the login is successful, forward the user to the log.dashboard page.\n *\n * @param {string} email Email of the current user\n * @param {string} password Password of the current user\n */\n function login(email, password) {\n if (verifyEmail(email) && verifyPassword(password)) {\n $auth.login({\n email: email,\n password: password,\n }).then(function(res) {\n if (res.status === 200) {\n $rootScope.$broadcast(authEvents.LOGIN);\n $state.go('log.dashboard');\n }\n });\n }\n }\n\n /**\n * Check if the user is currently logged in. If they are, forward them to\n * the dashboard. If they are not logged in, they can remain on the page.\n *\n * To use this, place this in the controller of the desired page.\n */\n function disableOnLoggedIn() {\n if ($auth.isAuthenticated()) {\n $state.go('log.dashboard');\n }\n }\n\n /**\n * Log out of the app, using the satellizer logout auth service, and redirect\n * the user to the login page.\n */\n function logout() {\n $auth.logout();\n $state.go('login');\n }\n\n /**\n * Check that the email passed through in login has both an @ sign and\n * a .\n *\n * @param {string} email Email passed through at login\n * @return {bool} Was the email a valid email.\n */\n function verifyEmail(email) {\n if (_.isUndefined(email)) {\n return false;\n }\n\n var atSign = _.any(email, function(letter) {\n return letter === '@';\n });\n\n var dot = _.any(email, function(letter) {\n return letter === '.';\n });\n\n return atSign && dot;\n }\n\n /**\n * Verify that the password follows the listed criteria:\n * 1. Has atleast one upper case letter\n * 2. Has atleast one lower case letter\n * 3. Has atleast one number character\n * 4. Is atleast 4 characters long\n * 5. Is max 22 characters long\n *\n * @param {string} pass Password to compare against\n * @return {bool} Is the password use the correct standards.\n */\n function verifyPassword(pass) {\n if (_.isUndefined(pass)) {\n return false;\n }\n\n var upperCase = _.any(pass, function(char) {\n return _.isNaN(parseInt(char)) ? char === char.toUpperCase() : false;\n });\n\n var lowerCase = _.any(pass, function(char) {\n return _.isNaN(parseInt(char)) ? char === char.toLowerCase() : false;\n });\n\n var numberCase = _.any(pass, function(char) {\n return _.isNumber(parseInt(char));\n });\n\n var length = pass.length >= 4 && pass.length <= 22;\n\n return upperCase && lowerCase && numberCase && length;\n }\n}",
"function LoginController() {}",
"function LoginController($scope, $rootScope, $location, $cookieStore, $http, $resource, OCRoles, tmhDynamicLocale,LoginSrv,FieldService,OCInfraConfig,OCMetadata) {\n $rootScope.screenId = 'login';\n var metamodelLocation = $rootScope.metamodelPath;\n OCMetadata.load($scope,metamodelLocation);\n\n\n $scope.checkvisible = function(field) {\n return FieldService.checkVisibility(field, $scope); \n };\n $rootScope.showHeader = false;\t\n $scope.doaction = function(method, subsections, action, actionURL, nextScreenId) {\n if (method === 'submit'){\n $scope.submit(nextScreenId);\n }\n };\n $scope.submit= function (nextScreenId){\n\t var FormID = $('form').attr('id');\t\t\n\t validateLogin(FormID); \n\t if ($('#' + FormID).valid()) {\n if (!navigator.onLine) {\n growl.error($rootScope.locale.NETWORK_UNAVAILABLE, '30');\n } else {\n\t\t\t\tLoginSrv.runLogin($scope, nextScreenId);\n }\n }\n };\n}",
"function clientLoginController(){\n return {\n restrict: 'E',\n scope: {},\n templateUrl: 'app/client/clientLogin/client-login.html',\n controller: 'initLoginController',\n controllerAs: 'loginCtrl'\n };\n }",
"function loginCtrl($scope, $location, adminAuthentication){\n \n //console.log(\"Login Controller is envoked\");\n $scope.adminLogin = function(admin){\n //console.log(\"login credentials are : \" + admin.adminName, admin.password);\n $scope.formError = \"\";\n if (! $scope.admin.adminName || !$scope.admin.password) {\n $scope.formError = \"All fields required, please try again\";\n return false;\n }\n adminAuthentication.adminLogin(admin).then(function(){\n console.log(\"Admin Login Successful\");\n $location.path(\"/admin/adminDashboard\");\n });\n $scope.adminName= \"\";\n $scope.password = \"\";\n };\n\n }",
"login() {\n this.get('auth0').authorize();\n }",
"function LoginCtrl($scope, $q, AuthService, $state, $ionicLoading, localStorageService) {\n \t$scope.onLogin = onLogin;\n $scope.invalidUser = false;\n $scope.invalidForm = false;\n $scope.login = {\n username:\"\",\n password: \"\"\n }\n $scope.cleanErrors = function (){\n $scope.invalidUser = false;\n $scope.invalidForm = false;\n }\n \t\n function onLogin(){\n if (!$scope.login.username || !$scope.login.password){\n $scope.invalidForm = true; \n return false;\n }\n $ionicLoading.show({});\n AuthService.onLogin($scope.login.username, $scope.login.password)\n .success(function(data) {\n $ionicLoading.hide();\n if(data.token)\n { \n localStorageService.set('access_token', data.token);\n localStorageService.set('user_data', data);\n if(data.doctor == null){\n $state.go('patient');\n }\n else if(data.patient == null){\n $state.go('doctor');\n \n }\n else{\n $state.go('dashboad');\n }\n }\n else{\n $ionicLoading.hide();\n $scope.invalidUser = true;\n }\n }).error(function(data) {\n $ionicLoading.hide();\n $scope.invalidUser = true;\n });\n }\n\t}",
"function Controller($window, LoginService, FlashService) {\n var vm = this; // Allows you to interact with the page. Think of it as $scope, but less chance of conflict.\n\n vm.user = null; // You can set fields with vm and use them on the page\n vm.login = login; // Links the checkAvail function defined here with checkAvail on the page through vm.\n\t\tvm.register = register; //redirects to Register page\n vm.forgotPass = forgotPass;\n\t\t\n initController();\n\n function initController() {\n // What you like to do upon page load? \n // For example, get the user that's logged.\n }\n\n function login() {\n LoginService.Authenticate(vm.user)\n .then(function(token) { \t\t\n FlashService.Success(\"Logged in\");\n\t\t\t\t$window.location = '/app';\t\n \n })\n .catch(function(error) {\n FlashService.Error(error);\n });\n }\n\t\tfunction register() {\n\t\t\tlocation.href = \"/login/#/register\";\n\t\t}\n\n function forgotPass() {\n\t\t\tlocation.href = \"/login/#/forgotPass\";\n\t\t}\n\t\t\n\t\t\n }",
"login(){\n\t\tvar that = this;\n\n\t\t$.post(\"/api/login\", \n\t\t\tthis.credentials\n\t\t\t, function(data) {\n\t\t\t\tif(data.auth.error){\n\t\t\t\t\tthat.loginerror = data.auth.error;\n\t\t\t\t}else{\n\t\t\t\t\tthat.$cookies.put('authtoken', data.auth.uid);\n\t\t\t\t\tthat.$cookies.put('username', data.auth.name);\n\t\t\t\t\tthat.$window.location.href = '/#';\n\t\t\t\t}\n\t\t\t\t\n\t\t}).fail(function(error){\n\t\t\tthat.loginerror = error.responseText;\n\t\t\tthat.$scope.$apply();\n\t\t\t\n\t\t}).done(function( data ) {\n\t\t\tif(data.auth.error){\n\t\t\t\talert( \"Login Failed with error: \" + data.auth.error );\n\t\t\t} \n\t\t});\t\n\t}",
"function login(){\n\t\t\tauth.signin({}, function(profile, token) {\n\t\t\t\tstore.set('profile', profile); \n\t\t\t\tstore.set('id_token', token);\n\t\t\t\t$state.go('intro')\n\t\t\t\t.then(function(){\n\t\t\t\t\t// refresh so user's data will be retrieved\n\t\t\t\t\t$window.location.reload();\n\t\t\t\t});\n\t\t\t}, function (error){\n\t\t\t\tconsole.log(error);\n\t\t\t});\n\t\t}",
"function showAuthPanel() {\n if (view && view.destroy) {\n view.destroy();\n }\n\n view = new alt.WebView(url);\n view.on('auth:Try', tryAuthPanel);\n view.on('auth:Ready', readyAuthPanel);\n view.focus()\n showCursor(true);\n alt.toggleGameControls(false);\n}",
"function showAuthPanel() {\n if (webview && webview.destroy) {\n webview.destroy();\n }\n\n webview = new alt.WebView(url);\n webview.focus()\n webview.on('auth:Try', tryAuthPanel);\n webview.on('auth:Ready', readyAuthPanel);\n \n alt.showCursor(true);\n alt.toggleGameControls(false);\n}",
"function navbarController(authService) {\n\n\t\tvar vm = this;\n\n\t\t//now can reference vm.auth in html to point to authService\n\t\tvm.auth = authService;\n\t}",
"function login() {\n \tUserService.login(vm.user.username, vm.user.password)\n .then(function(response){\n if(response.data) {\n $rootScope.currentUser = response.data;\n $location.url(\"/profile\");\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to split text input into an array and return length of array. Checks for empty array items and does not include in the total item count. | function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator);
var arrayLength = 0;
for(var i=0;i<arrayOfStrings.length;i++)
if(arrayOfStrings[i].length > 0){
arrayLength = arrayLength+1;
console.log(arrayLength)
}
return arrayLength;
} | [
"function countItems(input) {\n var count = 0;\n var inputSplit = input.split(',');\n for(var i = 0; i < inputSplit.length; i++) {\n if(inputSplit[i].trim() !== '') {\n count++;\n }\n }\n return count;\n }",
"function splitString(string) {\n var arrayOfStrings = string.split(',');\n var outArray = [];\n var count = 0;\n for(var i = 0; i < arrayOfStrings.length; i++) {\n if(arrayOfStrings[i] === \"\") {\n console.log(\"found empty\");\n emptyFieldFound = true;\n } else {\n console.log(\"Adding \" + arrayOfStrings[i] + \" to outArray\");\n outArray[count++] = arrayOfStrings[i];\n }\n }\n console.log(outArray.length);\n return outArray.length;\n }",
"function checkNumItems(){\n\t //Get the lunch menu and trim it\n\t var lunchmenu = $scope.lunchMenu.trim();\n\n\t //In case the lunchmenu is blank\n\t if(lunchmenu == ''){\n\t\treturn -1;\n\t }\n\t \n\t //Explode the string\n\t var items = lunchmenu.split(\",\");\n\n\t //Set numItems counter to 0\n\t var numItems = 0;\n\n\t //Iterate through all the items in the exploded string\n\t //Check to see if there are blank\n\t //If item is not blank, count as an item\n\t \n\t for(var num in items){\n\t\tif(items[num].trim()!=''){\n\t\t numItems++;\n\t\t}\n\t }\n\n\t //Return the number of items\n\t return numItems;\n\t}",
"function wordCount(textArr) {\n return textArr.length;\n}",
"function get_nNonEmptyLines(txt) {\n let nNonEmptyLines_result = 0;\n let lines = get_arrOfWordsLines(txt);\n for (let i = 0; i < lines.length; i++) {\n lines[i] = lines[i].replace(/\\s/g, \"\");\n lines[i] = lines[i].replace(/\\t/g, \"\");\n if (lines[i] !== \"\") {\n nNonEmptyLines_result++;\n }\n }\n return nNonEmptyLines_result;\n }",
"function countItems () {\n var num_items = 0;\n\n if ($scope.lunchItems.length > 0) {\n var items = $scope.lunchItems.split(\",\");\n\n // remove empty items from the list\n // do NOT consider and empty item, i.e. \", , ,\" as an item towards the count\n items = items.filter(function (item) {\n return item.trim() != \"\";\n });\n\n num_items = items.length;\n }\n\n return num_items;\n }",
"function count(arr){\r\n\t\t\tvar counter = 0;\r\n\t\t\tfor(var i=0;i<arr.length;i++){\r\n\t\t\t\tif(arr[i].trim().length > 0) counter++;\r\n\t\t\t}\r\n\t\t\treturn counter;\r\n\t\t}",
"function processData(input) {\n //Enter your code here\n cnt = 0;\n // number_of_integers = input\n // console.log('input', input);\n array1 = input.split(\"\\n\");\n\n lengthOfArray = array1[0];\n // console.log('lengthOfArray', lengthOfArray);\n\n elements = array1[1].split(\" \");\n\n for (i = 0; i < lengthOfArray; i++) {\n if (Number(elements[i]) < 0) {\n cnt += 1;\n }\n }\n\n console.log(cnt);\n}",
"function countItems() {\n // initialize counter and build list of lunch items\n var counter = 0;\n var lunchList = $scope.lunch.split(',');\n\n // loop through lunch items\n for (var i=0; i<lunchList.length; i++) {\n // if it's not empty, add item to count of valid lunch items\n if (lunchList[i].trim() != \"\") {\n counter ++;\n }\n }\n\n // return count of lunch items\n return counter;\n }",
"function arrayItemCount(item) {\n return item.length;\n}",
"function getLinesFromText() {\n // Get the value of the text input\n let text = document.getElementById('textInput').value;\n\n // Return an *array* containing the length of each word\n}",
"function nLines(){\r\n var lines = input_txt.split(/\\r\\n|\\r|\\n/).length;\r\n return lines;\r\n}",
"function get_nLines(txt) {\r\n return (txt === \"\") ? 0 : txt.split(/\\n/).length;\r\n}",
"function get_nNonemptyLines(txt) {\r\n let lines = txt.split(/\\n/);\r\n for(let i=0;i<lines.length;i++)\r\n lines[i] = lines[i].replace(/[\\s\\t]+/g, \"\");\r\n return lines.filter(function(i) {\r\n return i!==\"\";\r\n }).length;\r\n}",
"countBigWords(input) {\n // code goes here\n //split the input in each character\n let words = input.split(\" \");\n //count characters in each word\n let bigWords=[];\n //put all the words longer than 6 in an array\n for (let i=0; i < words.length; i++ ) {\n \n if (words[i].length > 6) {\n bigWords.push(words[i]);\n }\n }\n //make an array\n //count lenght of the array\n return bigWords.length;\n }",
"function wordCount(enteredText) {\n var words = wordsOnly(enteredText).replace(/\\s/g, ',').trim().split(',');\n count = 0;\n for (i = 0; i < words.length; i++) {\n if (words[i] !== \"\") {\n count += 1;\n }\n }\n return count;\n}",
"function calculateNumLunchItems(lunchItems) {\r\n var lunchItemsArray = lunchItems.split(\",\");\r\n var count = 0;\r\n for(var i = 0 ; i < lunchItemsArray.length ; i++) {\r\n if(!isEmptyLunchItem(lunchItemsArray[i])) count++;\r\n }\r\n return count;\r\n }",
"function arrayLength(x) {\n return x.length\n}",
"function wordCountFunc(arr) {\n var wordTotal = arr.length\n return wordTotal;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
escape a single character ch: single character string return value: printable string representing ch | function escapedChar(ch) {
// get the unicode character code number
var code = ch.charCodeAt(0)
if (code < minPrinted || code > maxPrinted || code == quoteCode) {
// the character needs escaping
// single-character escapes
var escape = characterEscapeSequences[ch]
if (escape) ch = escape
else {
// construct a unicode escape sequence \u1234
escape = code.toString(16)
ch = '\\u' + (escape.length < 4 ?
'0000'.slice(-4 + escape.length) + escape :
escape)
}
}
return ch
} | [
"function escape(ch) {\n var charCode = ch.charCodeAt(0);\n var escapeChar;\n var length;\n\n if (charCode <= 0xFF) {\n escapeChar = 'x';\n length = 2;\n } else {\n escapeChar = 'u';\n length = 4;\n }\n\n return '\\\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length);\n}",
"function escapeChar(c) {\n if (c === \"&\") return \"&\";\n if (c === \"<\") return \"<\";\n if (c === \">\") return \">\";\n else return c;\n}",
"function escapeChar(c) {\n var e = ESCAPE_CHARS[c];\n if (e) {\n return e;\n }\n return c;\n}",
"function readEscapedChar() {\n\t var ch = input.charCodeAt(++tokPos);\n\t var octal = /^[0-7]+/.exec(input.slice(tokPos, tokPos + 3));\n\t if (octal) octal = octal[0];\n\t while (octal && parseInt(octal, 8) > 255) octal = octal.slice(0, -1);\n\t if (octal === \"0\") octal = null;\n\t ++tokPos;\n\t if (octal) {\n\t if (strict) raise(tokPos - 2, \"Octal literal in strict mode\");\n\t tokPos += octal.length - 1;\n\t return String.fromCharCode(parseInt(octal, 8));\n\t } else {\n\t switch (ch) {\n\t case 110: return \"\\n\"; // 'n' -> '\\n'\n\t case 114: return \"\\r\"; // 'r' -> '\\r'\n\t case 120: return String.fromCharCode(readHexChar(2)); // 'x'\n\t case 117: return readCodePoint(); // 'u'\n\t case 116: return \"\\t\"; // 't' -> '\\t'\n\t case 98: return \"\\b\"; // 'b' -> '\\b'\n\t case 118: return \"\\u000b\"; // 'v' -> '\\u000b'\n\t case 102: return \"\\f\"; // 'f' -> '\\f'\n\t case 48: return \"\\0\"; // 0 -> '\\0'\n\t case 13: if (input.charCodeAt(tokPos) === 10) ++tokPos; // '\\r\\n'\n\t case 10: // ' \\n'\n\t if (options.locations) { tokLineStart = tokPos; ++tokCurLine; }\n\t return \"\";\n\t default: return String.fromCharCode(ch);\n\t }\n\t }\n\t }",
"function readEscapedChar() {\n var ch = input.charCodeAt(++tokPos);\n var octal = /^[0-7]+/.exec(input.slice(tokPos, tokPos + 3));\n if (octal) octal = octal[0];\n while (octal && parseInt(octal, 8) > 255) octal = octal.slice(0, -1);\n if (octal === \"0\") octal = null;\n ++tokPos;\n if (octal) {\n if (strict) raise(tokPos - 2, \"Octal literal in strict mode\");\n tokPos += octal.length - 1;\n return String.fromCharCode(parseInt(octal, 8));\n } else {\n switch (ch) {\n case 110: return \"\\n\"; // 'n' -> '\\n'\n case 114: return \"\\r\"; // 'r' -> '\\r'\n case 120: return String.fromCharCode(readHexChar(2)); // 'x'\n case 117: return readCodePoint(); // 'u'\n case 116: return \"\\t\"; // 't' -> '\\t'\n case 98: return \"\\b\"; // 'b' -> '\\b'\n case 118: return \"\\u000b\"; // 'v' -> '\\u000b'\n case 102: return \"\\f\"; // 'f' -> '\\f'\n case 48: return \"\\0\"; // 0 -> '\\0'\n case 13: if (input.charCodeAt(tokPos) === 10) ++tokPos; // '\\r\\n'\n case 10: // ' \\n'\n if (options.locations) { tokLineStart = tokPos; ++tokCurLine; }\n return \"\";\n default: return String.fromCharCode(ch);\n }\n }\n }",
"function escapeCssStrChar(ch) {\n return cssStrChars[ch]\n || (cssStrChars[ch] = '\\\\' + ch.charCodeAt(0).toString(16) + ' ');\n }",
"function specialCharEscape(val, method, esc_chars) {\n var len = val.length;\n var i = 0;\n var newStr = \"\";\n\n if (typeof method === 'undefined') {\n method = 'e'; // default method\n }\n if (typeof esc_chars === 'undefined') {\n // default characters to be escaped\n esc_chars = method == 'e' ? \"\\\"'&<>\" : \"\\\"'\\\\\";\n }\n\n for ( i = 0; i < len; i++ ) {\n var nextChar = val.substring(i,i+1);\n if (esc_chars.indexOf(nextChar) == -1) {\n newStr = newStr + nextChar;\n } else {\n newStr = newStr + (method == 'e' ? convertCharToEntity(nextChar) :\n convertCharToAscii(nextChar));\n }\n }\n return newStr;\n}",
"function EscapeSpecialChar(str) {\r\n\tvar outStr = str.toString();\r\n\r\n\toutStr = outStr.replace(/'/g, \"''\");\r\n\toutStr = outStr.replace(/\"/g, '\\\\\"');\r\n\toutStr = outStr.replace(/_/g, '\\\\_');\r\n\toutStr = outStr.replace(/%/g, '\\\\%');\r\n\r\n\treturn outStr;\r\n}",
"function toStr(ch) {\n return String.fromCharCode(ch);\n}",
"function encodeCharacter (chr) {\n var\n result = '',\n octets = utf8.encode(chr),\n octet,\n index;\n for (index = 0; index < octets.length; index += 1) {\n octet = octets.charCodeAt(index);\n result += '%' + (octet < 0x10 ? '0' : '') + octet.toString(16).toUpperCase();\n }\n return result;\n }",
"function escape(text){return String(text).replace(ESCAPE_REGEX,function(match){return ESCAPE_LOOKUP[match];});}",
"function escaped() {\n const chars = [0x00, 0xff, 0x100, 0xd8ff, 0xffff, 0x10000, 0xffffffff];\n const buf = converter.encode('ESCAPED', chars);\n const str = buf.toString('ascii');\n console.log(`escaped: ${str}`);\n console.log('apg-conv-api: test suite: escaped: OK');\n }",
"function readEscapedChar () {\r\n let ch = source.charCodeAt(++acornPos);\r\n ++acornPos;\r\n switch (ch) {\r\n case 110: return '\\n'; // 'n' -> '\\n'\r\n case 114: return '\\r'; // 'r' -> '\\r'\r\n case 120: return String.fromCharCode(readHexChar(2)); // 'x'\r\n case 117: return readCodePointToString(); // 'u'\r\n case 116: return '\\t'; // 't' -> '\\t'\r\n case 98: return '\\b'; // 'b' -> '\\b'\r\n case 118: return '\\u000b'; // 'v' -> '\\u000b'\r\n case 102: return '\\f'; // 'f' -> '\\f'\r\n case 13: if (source.charCodeAt(acornPos) === 10) ++acornPos; // '\\r\\n'\r\n case 10: // ' \\n'\r\n return '';\r\n case 56:\r\n case 57:\r\n syntaxError();\r\n default:\r\n if (ch >= 48 && ch <= 55) {\r\n let octalStr = source.substr(acornPos - 1, 3).match(/^[0-7]+/)[0];\r\n let octal = parseInt(octalStr, 8);\r\n if (octal > 255) {\r\n octalStr = octalStr.slice(0, -1);\r\n octal = parseInt(octalStr, 8);\r\n }\r\n acornPos += octalStr.length - 1;\r\n ch = source.charCodeAt(acornPos);\r\n if (octalStr !== '0' || ch === 56 || ch === 57)\r\n syntaxError();\r\n return String.fromCharCode(octal);\r\n }\r\n if (isBr(ch)) {\r\n // Unicode new line characters after \\ get removed from output in both\r\n // template literals and strings\r\n return '';\r\n }\r\n return String.fromCharCode(ch);\r\n }\r\n }",
"function escapeSpecialChar(str){\n var tmp = str.replace(/&/g, \"&\").replace(/\"/g, \""\").replace(/'/g, \"'\").replace(/</g, \"<\").replace(/>/g, \">\").replace(/{/g, \"{\").replace(/}/g, \"}\");\n return tmp;\n}",
"function escapeChar(s, open, close, char) {\n var depth = 0;\n\n return s.replace(new RegExp('[\\\\' + open + '\\\\' + close + ']', 'g'), function (a) {\n if (a === open)\n depth++;\n\n if (a === open) {\n return a + repeat(char, depth);\n } else {\n return repeat(char, depth--) + a;\n }\n })\n}",
"function My_Escape(s){\n\n answer=\"\";\n\n for(i=0;i<s.length;i++){\n x=s.substring(i,i+1);\n if( x== '\\'' )\n answer=answer+\"\\\\\";\n answer=answer+x;\n }\n return answer;\n}",
"function readEscapedChar () {\n let ch = source.charCodeAt(++acornPos);\n ++acornPos;\n switch (ch) {\n case 110: return '\\n'; // 'n' -> '\\n'\n case 114: return '\\r'; // 'r' -> '\\r'\n case 120: return String.fromCharCode(readHexChar(2)); // 'x'\n case 117: return readCodePointToString(); // 'u'\n case 116: return '\\t'; // 't' -> '\\t'\n case 98: return '\\b'; // 'b' -> '\\b'\n case 118: return '\\u000b'; // 'v' -> '\\u000b'\n case 102: return '\\f'; // 'f' -> '\\f'\n case 13: if (source.charCodeAt(acornPos) === 10) ++acornPos; // '\\r\\n'\n case 10: // ' \\n'\n return '';\n case 56:\n case 57:\n syntaxError();\n default:\n if (ch >= 48 && ch <= 55) {\n let octalStr = source.substr(acornPos - 1, 3).match(/^[0-7]+/)[0];\n let octal = parseInt(octalStr, 8);\n if (octal > 255) {\n octalStr = octalStr.slice(0, -1);\n octal = parseInt(octalStr, 8);\n }\n acornPos += octalStr.length - 1;\n ch = source.charCodeAt(acornPos);\n if (octalStr !== '0' || ch === 56 || ch === 57)\n syntaxError();\n return String.fromCharCode(octal);\n }\n if (isBr(ch)) {\n // Unicode new line characters after \\ get removed from output in both\n // template literals and strings\n return '';\n }\n return String.fromCharCode(ch);\n }\n}",
"function encodeChar(b, sb, special)\n {\n switch(b)\n {\n case 92: // '\\\\'\n {\n sb.push(\"\\\\\\\\\");\n break;\n }\n case 39: // '\\''\n {\n sb.push(\"\\\\'\");\n break;\n }\n case 34: // '\"'\n {\n sb.push(\"\\\\\\\"\");\n break;\n }\n case 8: // '\\b'\n {\n sb.push(\"\\\\b\");\n break;\n }\n case 12: // '\\f'\n {\n sb.push(\"\\\\f\");\n break;\n }\n case 10: // '\\n'\n {\n sb.push(\"\\\\n\");\n break;\n }\n case 13: // '\\r'\n {\n sb.push(\"\\\\r\");\n break;\n }\n case 9: // '\\t'\n {\n sb.push(\"\\\\t\");\n break;\n }\n default:\n {\n if(!(b >= 32 && b <= 126))\n {\n sb.push('\\\\');\n var octal = b.toString(8);\n //\n // Add leading zeroes so that we avoid problems during\n // decoding. For example, consider the encoded string\n // \\0013 (i.e., a character with value 1 followed by\n // the character '3'). If the leading zeroes were omitted,\n // the result would be incorrectly interpreted by the\n // decoder as a single character with value 11.\n //\n for(var j = octal.length; j < 3; j++)\n {\n sb.push('0');\n }\n sb.push(octal);\n }\n else\n {\n var c = String.fromCharCode(b);\n if(special !== null && special.indexOf(c) !== -1)\n {\n sb.push('\\\\');\n sb.push(c);\n }\n else\n {\n sb.push(c);\n }\n }\n }\n }\n }",
"function characterReplacer(character){// Replace a single character by its escaped version\nvar result=escapedCharacters[character];if(result===undefined){// Replace a single character with its 4-bit unicode escape sequence\nif(character.length===1){result=character.charCodeAt(0).toString(16);result=\"\\\\u0000\".substr(0,6-result.length)+result;}// Replace a surrogate pair with its 8-bit unicode escape sequence\nelse{result=((character.charCodeAt(0)-0xD800)*0x400+character.charCodeAt(1)+0x2400).toString(16);result=\"\\\\U00000000\".substr(0,10-result.length)+result;}}return result;}// ## Exports"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The Extraction Object: Input : isAsync : if this extraction should use Promises reject : The function to run when an error occurs str : The string that this extraction is parsing bracket : The Brackets object that this Extraction is based on | function Extraction( isAsync, reject, str, brackets ){
//initialize some values from the input
this.isAsync = isAsync;
this.reject = reject;
this.remainingString = str;
this.WordBoundaryManager = brackets.wordBoundaryManager;
//initialize other arguments
this.Location = buildLocation();
this.Nest = new Nest( brackets, this );
} | [
"parseAsync(text,extra){\r\n\t\treturn new Promise(function(ok,err){\r\n\t\t\t/**\r\n\t\t\t * Pseudo-labels\r\n\t\t\t**/\r\n\t\t\tconst $DOC_TEXT=1,\r\n\t\t\t\t$TAG=2,$TAG_COLON=3,$TAG_KEY=4,\r\n\t\t\t\t$VALUE_TEXT=5,$VALUE_TAG=6,$VALUE_ERR=7,\r\n\t\t\t\t$SEC_START=8,$SEC_BODY=9;\r\n\t\t\t\r\n\t\t\tfunction innerParseAsync(next,text,ps,extra){\r\n\t\t\t\t//Avoid redefining this all over the place\r\n\t\t\t\tlet m;\r\n\t\t\t\t\r\n\t\t\t\tswitch(next){\r\n\t\t\t\t\tcase $DOC_TEXT:\r\n\t\t\t\t\t\tif(ps.val){\r\n\t\t\t\t\t\t\tps.doc.push(ps.val);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\tif(ps.pos>=text.length){\r\n\t\t\t\t\t\t\t\tok(new Document(ps.doc,1,0));\r\n\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif((m=maybe(text,ps,DOC_TEXT)) && m[0]){\r\n\t\t\t\t\t\t\tps.doc.push(new Text(\r\n\t\t\t\t\t\t\t\tm[0].replace(DOC_REPL,normalize),\r\n\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tps.callstack.push($DOC_TEXT);\r\n\t\t\t\t\t\t//next=$TAG;break;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $TAG:\r\n\t\t\t\t\t\tps.val=null;\r\n\t\t\t\t\t\tif(text[ps.pos]!=\"{\"){\r\n\t\t\t\t\t\t\t//\"return\" null\r\n\t\t\t\t\t\t\tnext=ps.callstack.pop();\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tps.tagstack.push(\r\n\t\t\t\t\t\t\tps.toptag={\r\n\t\t\t\t\t\t\t\tkeys:[],vals:[],pos:[],\r\n\t\t\t\t\t\t\t\tline:ps.line,col:ps.col++,p:ps.pos++\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t/*\r\n\t\t\t\t\t\tEither TAG or TAG_COLON can fall through to \r\n\t\t\t\t\t\t TAG_KEY, but TAG_COLON can be \"called\" more than\r\n\t\t\t\t\t\t once per tag parsing circuit, and thus can be\r\n\t\t\t\t\t\t potentially more efficient. TAG is only more\r\n\t\t\t\t\t\t efficient for tags like {tag}\r\n\t\t\t\t\t\t*/\r\n\t\t\t\t\t\tnext=$TAG_KEY;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $TAG_COLON:\r\n\t\t\t\t\t\tmaybe(text,ps,SPACE);\r\n\t\t\t\t\t\tif(text[ps.pos]==\":\"){\r\n\t\t\t\t\t\t\tif(index(ps.toptag.keys,ps.val)!==null){\r\n\t\t\t\t\t\t\t\terr(new ParseError(DUPLICATE,ps.line,ps.col));\r\n\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tps.toptag.keys.push(ps.val);\r\n\t\t\t\t\t\t\t++ps.pos;\r\n\t\t\t\t\t\t\t++ps.col;\r\n\t\t\t\t\t\t\tmaybe(text,ps,SPACE);\r\n\t\t\t\t\t\t\tps.callstack.push($TAG_KEY);\r\n\t\t\t\t\t\t\tnext=$VALUE_TEXT;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tps.toptag.pos.push(ps.val);\r\n\t\t\t\t\t\tps.val=null;\r\n\t\t\t\t\t\t//next=$TAG_KEY;break;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $TAG_KEY:\r\n\t\t\t\t\t\tif(ps.val){\r\n\t\t\t\t\t\t\tps.toptag.vals.push(ps.val);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tmaybe(text,ps,SPACE);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t//No need to check for pos<=tl because VALUE_* will\r\n\t\t\t\t\t\t// catch any in-tag EOF error\r\n\t\t\t\t\t\tif(text[ps.pos]==\"}\"){\r\n\t\t\t\t\t\t\t++ps.pos;\r\n\t\t\t\t\t\t\t++ps.col;\r\n\t\t\t\t\t\t\tconst tag=ps.tagstack.pop();\r\n\t\t\t\t\t\t\tps.toptag=ps.tagstack[ps.tagstack.length-1];\r\n\t\t\t\t\t\t\tps.val=ps.build(\r\n\t\t\t\t\t\t\t\ttag.keys,tag.vals,tag.pos,\r\n\t\t\t\t\t\t\t\ttag.line,tag.col,tag.p,\r\n\t\t\t\t\t\t\t\textra\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\tnext=ps.callstack.pop();\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t//Once the value is determined, goto TAG_COLON\r\n\t\t\t\t\t\tps.callstack.push($TAG_COLON);\r\n\t\t\t\t\t\t//next=$VALUE_TEXT;break;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $VALUE_TEXT:\r\n\t\t\t\t\t\tif(m=maybe(text,ps,QUOTED_TEXT)){\r\n\t\t\t\t\t\t\tlet tr,qr;\r\n\t\t\t\t\t\t\tif(m[1]){\r\n\t\t\t\t\t\t\t\ttr=m[1];\r\n\t\t\t\t\t\t\t\tqr=DQ_REPL;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if(m[2]){\r\n\t\t\t\t\t\t\t\ttr=m[2];\r\n\t\t\t\t\t\t\t\tqr=SQ_REPL;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse if(m[3]){\r\n\t\t\t\t\t\t\t\ttr=m[3];\r\n\t\t\t\t\t\t\t\tqr=BQ_REPL;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tps.val=new Text(\r\n\t\t\t\t\t\t\t\ttr.replace(qr,normalize),\r\n\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if(m=maybe(text,ps,UNQUOTED_TEXT)){\r\n\t\t\t\t\t\t\tps.val=new Text(\r\n\t\t\t\t\t\t\t\tm[0].replace(UNQ_REPL,normalize),\r\n\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\tps.callstack.push($VALUE_TAG);\r\n\t\t\t\t\t\t\tnext=$TAG;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t//Successful, return to next block\r\n\t\t\t\t\t\tnext=ps.callstack.pop();\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $VALUE_TAG:\r\n\t\t\t\t\t\tif(ps.val){\r\n\t\t\t\t\t\t\t//Successful, return to next block\r\n\t\t\t\t\t\t\tnext=ps.callstack.pop();\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t//next=$SEC_START;break;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $SEC_START:\r\n\t\t\t\t\t\t//Sections are the last checked value - if it's not\r\n\t\t\t\t\t\t// there, it MUST be an error\r\n\t\t\t\t\t\tif(text[ps.pos]!='['){\r\n\t\t\t\t\t\t\t/*\r\n\t\t\t\t\t\t\tSnow errors are very predictable, so check for\r\n\t\t\t\t\t\t\tcommon mistakes. By this point, we know the next\r\n\t\t\t\t\t\t\tcharacter is one of the start of quoted text, ],\r\n\t\t\t\t\t\t\t}, EOF, or whitespace. Whitespace is an error in\r\n\t\t\t\t\t\t\tthe parsing logic, but is predictable. If it's\r\n\t\t\t\t\t\t\tnot any of these, it's completely unknown what's\r\n\t\t\t\t\t\t\twrong.\r\n\t\t\t\t\t\t\t*/\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t//check for EOF\r\n\t\t\t\t\t\t\tif(ps.pos>=text.length){\r\n\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\tUNCLOSED_TAG,\r\n\t\t\t\t\t\t\t\t\tps.toptag.line,ps.toptag.col\r\n\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tconst c=text[ps.pos];\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tswitch(c){\r\n\t\t\t\t\t\t\t\tcase '\"':\r\n\t\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\tUNCLOSED_DQ,\r\n\t\t\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\tcase \"'\":\r\n\t\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\tUNCLOSED_SQ,\r\n\t\t\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\tcase '`':\r\n\t\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\tUNCLOSED_BQ,\r\n\t\t\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\tcase ']':\r\n\t\t\t\t\t\t\t\t\tconst p=ps.secstack.pop();\r\n\t\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\tMIXED,\r\n\t\t\t\t\t\t\t\t\t\tp.line,p.col-1\r\n\t\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\tcase \"}\":\r\n\t\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\tNO_VALUE,\r\n\t\t\t\t\t\t\t\t\t\tps.coloncol,ps.colonline\r\n\t\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\tcase \":\":\r\n\t\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\tCOLON,\r\n\t\t\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tif(/\\s/m.test(c)){\r\n\t\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t\t\"Expected a value, found whitespace. \"+\r\n\t\t\t\t\t\t\t\t\t\"There's a problem with the API's \"+\r\n\t\t\t\t\t\t\t\t\t\"parser code.\",ps.line,ps.col\r\n\t\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t//reserved for cosmic ray errors\r\n\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\t'Something went horribly wrong. '+\r\n\t\t\t\t\t\t\t\t'Expected value, got \"'+(\r\n\t\t\t\t\t\t\t\t\ttext.slice(ps.pos,ps.pos+8)+\r\n\t\t\t\t\t\t\t\t\t(ps.pos+8>=text.length)?\"\":\"...\"\r\n\t\t\t\t\t\t\t\t)+'\"',ps.line,ps.col\r\n\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t++ps.pos;\r\n\t\t\t\t\t\t++ps.col;\r\n\t\t\t\t\t\tps.secstack.push([]);\r\n\t\t\t\t\t\t//next=$SEC_BODY;break;\r\n\t\t\t\t\t\r\n\t\t\t\t\tcase $SEC_BODY:\r\n\t\t\t\t\t\tconst ss=ps.secstack[ps.secstack.length-1];\r\n\t\t\t\t\t\tif(ps.val!==null){\r\n\t\t\t\t\t\t\tss.push(ps.val);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif((m=maybe(text,ps,SEC_TEXT)) && m[0]){\r\n\t\t\t\t\t\t\tss.push(new Text(\r\n\t\t\t\t\t\t\t\tm[0].replace(SEC_REPL,normalize),\r\n\t\t\t\t\t\t\t\tps.line,ps.col\r\n\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif(ps.pos>=text.length){\r\n\t\t\t\t\t\t\terr(new ParseError(\r\n\t\t\t\t\t\t\t\tUNCLOSED_SECTION,ps.line,ps.col\r\n\t\t\t\t\t\t\t));\r\n\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif(text[ps.pos]==']'){\r\n\t\t\t\t\t\t\t++ps.pos;\r\n\t\t\t\t\t\t\t++ps.col;\r\n\t\t\t\t\t\t\tps.val=new Section(ss,ps.line,ps.col,ps.pos);\r\n\t\t\t\t\t\t\t//sections must come from the value circuit\r\n\t\t\t\t\t\t\tnext=ps.callstack.pop();\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tps.callstack.push($SEC_BODY);\r\n\t\t\t\t\t\tnext=$TAG;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tnextTick(function(){\r\n\t\t\t\t\tinnerParseAsync(next,text,ps,extra);\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tconst bom=(text.length>0 && text[0]==\"\\ufeff\")|0;\r\n\t\t\tnextTick(function(){\r\n\t\t\t\tinnerParseAsync($DOC_TEXT,text,{\r\n\t\t\t\t\tpos:bom,\r\n\t\t\t\t\tline:1,\r\n\t\t\t\t\tcol:bom,\r\n\t\t\t\t\tcolonline:1,\r\n\t\t\t\t\tcoloncol:0,\r\n\t\t\t\t\tdoc:[],tagstack:[],secstack:[],toptag:null,\r\n\t\t\t\t\tval:null,callstack:[]\r\n\t\t\t\t},extra);\r\n\t\t\t});\r\n\t\t});\r\n\t}",
"static readEx2(expression,callback){let s=new Symbol(expression),destroy=s.readEx((function(data){Symbol.isIServerReadResultObject(data)?TcHmi.Callback.callSafeEx(callback,null,{error:data.error,value:data.value,response:data.response,details:data.details}):TcHmi.Callback.callSafeEx(callback,null,{error:data.error,value:data.value,details:data.details}),s&&s.destroy(),s=null}));return()=>{destroy&&destroy(),s&&s.destroy(),s=null}}",
"function parse_Stream(\n data_Chunk//: str\n //>>> main data accumulator <<<//\n //,extracted_Content//: (obj | dictionary) | list of (obj | dictionary)\n ,parser_State//: obj | dictionary\n ,boundary//: str\n ,is_Debug_Mode//: bool <- optional\n) {//: => Promise(obj) <- parse state\n \"use strict\";\n\n const CRLF = '\\r\\n';\n const HEADERS_END = CRLF + CRLF;\n const OPEN_TAG = '--' + boundary + CRLF;\n const CLOSE_TAG = '--' + boundary + '--';\n const ENCODINGS = ['ascii', 'utf8', 'utf16le', 'base64', 'binary', 'hex'];\n var result_Obj = {\n // states: empty -> (undefined | \"\") | partial -> \"--\" | complete -> \"-- ... \\r\\n\"\n //> 'ascii' - for 7-bit ASCII data\n \"open_Tag\": '--' + boundary + CRLF//------WebKitFormBoundaryRlQf1oHVfylrtnOJ\\r\\n\n //> 'ascii' - for 7-bit ASCII data\n ,\"content_Headers\": \"Content-Disposition: form-data; ...\"\n //> 'ascii' - for 7-bit ASCII data\n ,\"headers_End\": 2 * CRLF// <- 2-nd CRLF\n // chars after 'CRLF' and before \"close_Tag\"\n //> encoding method ? 'ascii' ? 'utf8' ? 'utf16le' ? 'base64' ? 'binary' ? 'hex' ?\n ,\"extracted_Content\": \" ... \"// <- may be incomplete\n //> 'ascii' - for 7-bit ASCII data\n ,\"close_Tag\": '--' + boundary + \"--\"// <- may never being completed\n };\n var str_Item_Index = 0;\n var i = 0;\n var chunk_Length = data_Chunk.length;\n var boundary_Length = boundary.length;\n var open_Tag_Length = OPEN_TAG.length;\n var headers_End_Length = HEADERS_END.length;\n var close_Tag_Length = CLOSE_TAG.length;\n var current_Char = \"\";\n //>>> parser's state <<<///\n var open_Tag = \"\";\n var content_Headers = \"\";\n var headers_End = \"\";\n // ? Buffer ?\n // For octet streams in the context of TCP streams & file system operations\n // Buffer.concat([buf1, buf2, buf3], totalLength == buf1.length + buf2.length + buf3.length);\n // Buffer.from('this is a tést');\n // Buffer.from('7468697320697320612074c3a97374', 'hex');\n // new Buffer('7468697320697320612074c3a97374', 'hex');\n // TODO how to get / set file content encoding ?\n //> attempt to create Buffer.empty(<any>)\n //buf = Buffer.from([]);//> buf.length -> 0\n var file_Buffer;// = Buffer.from('', 'utf8');//> buf.length -> 0\n var extracted_Content = '';\n var char_Buffer = Buffer.from('', 'utf8');\n var close_Tag = \"\";\n var file_Length = 0;\n\n //*** defaults ***//\n //if (is_Debug_Mode) {console.log(\"defaults:\");}\n //if (is_Debug_Mode) {console.log(\"OPEN_TAG:\", OPEN_TAG);}\n //if (is_Debug_Mode) {console.log(\"CLOSE_TAG:\", CLOSE_TAG);}\n //*** defaults end ***//\n\n //*** initialization ***//\n if (is_Debug_Mode) {console.log(\"new parse step initialization ...\");}\n //if (is_Debug_Mode) {console.log(\"parser_State:\", parser_State);}\n if (\n parser_State &&\n parser_State.open_Tag\n ) { // is not null | undefined & is a proper object\n //>>> ? guard ? <<<///\n /*if (close_Tag == CLOSE_TAG) {\n\n\n return parser_State;\n }*/\n //>>> set <<<//\n open_Tag = parser_State.open_Tag;\n content_Headers = parser_State.content_Headers;\n headers_End = parser_State.headers_End;\n file_Buffer = parser_State.file_Buffer;\n /*\n extracted_Content = parser_State.extracted_Content;\n if (\n extracted_Content &&\n //typeof(extracted_Content) == 'object' &&\n extracted_Content.hasOwnProperty(\"length\")\n ) {\n if (is_Debug_Mode) {console.log(\"extracted_Content.length:\", extracted_Content.length);}\n } else {\n if (is_Debug_Mode) {console.log(\"extracted_Content was / is empty:\", extracted_Content);}\n //extracted_Content = Buffer.from('', 'utf8');\n extracted_Content = '';\n }\n */\n //if (parser_State.file_Buffer) {file_Buffer = parser_State.file_Buffer;}\n close_Tag = parser_State.close_Tag;\n file_Length = parser_State.file_Length;\n } else {\n }\n if (is_Debug_Mode) {console.log(\"open_Tag:\", open_Tag);}\n if (is_Debug_Mode) {console.log(\"content_Headers:\", content_Headers);}\n if (is_Debug_Mode) {console.log(\"headers_End:\", headers_End);}\n if (is_Debug_Mode) {console.log(\"file_Length:\", file_Length);}\n //*** initialization end ***//\n\n //buf.toString([encoding[, start[, end]]])\n //Buffer.isEncoding(encoding)\n //> it works, but how this is helpful / how to use that info ?\n /*if (data_Chunk instanceof Buffer) {\n for (let value of ENCODINGS) {\n if (\n //data_Chunk\n Buffer.isEncoding(value)\n ) {\n console.log(\"data_Chunk encoding:\", value);\n }\n }\n }*/\n\n if (is_Debug_Mode) { console.log(\"data_Chunk:\\n\", data_Chunk);}\n //buf.values()\n //for (var value of buf.values()) {\n // or just\n //for (var value of buf) {\n for (;i < chunk_Length;i++) {\n\n current_Char = data_Chunk[i];\n if (current_Char == '\\r') {\n if (is_Debug_Mode) { console.log(\"'Carriage Return' detected:\", data_Chunk.slice(i + 1 - 5 > 0 ? i+1-5 : 0, i+1));}\n }\n\n if (\n open_Tag === \"\" ||\n open_Tag.length < open_Tag_Length ||\n open_Tag != OPEN_TAG\n ) {\n //>>> slide window\n open_Tag = (open_Tag + current_Char).slice(-open_Tag_Length);\n //>>> post check <<<//\n if (current_Char == '\\n' && open_Tag == OPEN_TAG) {\n //>>> guard / margin / delimiter / skip char flag <<<//\n if (is_Debug_Mode) { console.log(\"open_Tag completed:\", open_Tag);}\n current_Char = undefined;\n }\n }\n if (\n current_Char &&\n open_Tag == OPEN_TAG &&\n headers_End != HEADERS_END\n ) {\n content_Headers += current_Char;\n //>>> slide window\n headers_End = content_Headers.slice(-headers_End_Length);\n //>>> post check <<<//\n if (\n current_Char == '\\n' &&\n content_Headers !== \"\" &&\n //content_Headers.slice(-2) == CRLF\n headers_End == HEADERS_END\n ) {\n //headers_End = CRLF;\n content_Headers = content_Headers.slice(0, -headers_End_Length);\n if (is_Debug_Mode) { console.log(\"content_Headers extracted:\", content_Headers);}\n // to prevent further chunk processing\n current_Char = undefined;\n } else {\n }\n }\n if (\n current_Char &&\n headers_End == HEADERS_END &&\n (close_Tag.length < close_Tag_Length ||\n close_Tag != CLOSE_TAG)\n ) {\n\n //> StringDecoder decodes a buffer to a string\n //char_Buffer = current_Char;\n //TypeError('\"value\" argument must not be a number')\n //char_Buffer = Buffer.from(current_Char, 'utf8');\n char_Buffer = Buffer.from([current_Char], 'utf8');\n //RangeError: toString() radix argument must be between 2 and 36\n //current_Char = current_Char.toString(2);\n //current_Char = current_Char.toString(8);\n //current_Char = current_Char.toString(16);\n //RangeError: Invalid code point NaN\n //current_Char = String.fromCodePoint(current_Char);\n //>>> slide window\n //> implicit type conversion: buff => str via '+' (str concat operator)\n close_Tag = (close_Tag + current_Char).slice(-close_Tag_Length);\n //>>> post check <<<//\n if (\n current_Char == '-' &&\n //extracted_Content.length > 0 &&\n //\"abc\".endsWith(\"bc\") -> true\n close_Tag == CLOSE_TAG\n ) {\n if (is_Debug_Mode) { console.log(\"extracted_Content extracted:\");}\n //if (is_Debug_Mode) { console.log(\"close_Tag:\", close_Tag, \"== CLOSE_TAG:\", CLOSE_TAG);}\n //extracted_Content = extracted_Content.slice(0, -close_Tag_Length);\n //if (is_Debug_Mode) { console.log(\"extracted_Content.length:\", extracted_Content.length);}\n if (is_Debug_Mode) { console.log(\"file_Buffer.length:\", file_Buffer.length);}\n if (is_Debug_Mode) { console.log(\"file_Buffer:\", file_Buffer);}\n ///>>>*** !!! WARN !!! may be too big for (to use) standard output ***<<<///\n //if (is_Debug_Mode) { console.log(\"file_Buffer.toString():\", file_Buffer.toString());}\n //Buffer.byteLength(string[, encoding])\n if (is_Debug_Mode) { console.log(\"Buffer.byteLength(of utf8 str):\", Buffer.byteLength(file_Buffer.toString(), 'utf8'));}\n if (is_Debug_Mode) { console.log(\"Buffer.byteLength(of utf8 buf):\", Buffer.byteLength(file_Buffer, 'utf8'));}\n if (is_Debug_Mode) { console.log(\"Buffer.byteLength(of hex str):\", Buffer.byteLength(file_Buffer.toString(), 'hex'));}\n if (is_Debug_Mode) { console.log(\"Buffer.byteLength(of hex buf):\", Buffer.byteLength(file_Buffer, 'hex'));}\n if (is_Debug_Mode) { console.log(\"Buffer.byteLength(of ascii str):\", Buffer.byteLength(file_Buffer.toString(), 'ascii'));}\n if (is_Debug_Mode) { console.log(\"Buffer.byteLength(of ascii buf):\", Buffer.byteLength(file_Buffer, 'ascii'));}\n if (is_Debug_Mode) { console.log(\"Buffer.byteLength(of base64 str):\", Buffer.byteLength(file_Buffer.toString(), 'base64'));}\n if (is_Debug_Mode) { console.log(\"Buffer.byteLength(of base64 buf):\", Buffer.byteLength(file_Buffer, 'base64'));}\n if (is_Debug_Mode) { console.log(\"Buffer.byteLength(of binary str):\", Buffer.byteLength(file_Buffer.toString(), 'binary'));}\n if (is_Debug_Mode) { console.log(\"Buffer.byteLength(of binary buf):\", Buffer.byteLength(file_Buffer, 'binary'));}\n } else {\n //TypeError('\"value\" argument must not be a number')\n //char_Buffer = Buffer.from(String(current_Char), 'utf8');\n //char_Buffer = Buffer.from([current_Char], 'utf8');\n //char_Buffer = Buffer(char_Buffer);\n //extracted_Content += current_Char;\n if (file_Buffer) {\n file_Buffer = Buffer\n .concat(\n [file_Buffer, char_Buffer]\n ,file_Buffer.length + char_Buffer.length);\n } else {\n file_Buffer = char_Buffer;\n }\n\n if (file_Length) {\n file_Length += char_Buffer.length;\n } else {\n file_Length = char_Buffer.length;\n }\n }\n }\n }\n //>>> result <<<//\n //if (is_Debug_Mode) {console.log(\"parse step return value:\");}\n //return Promise\n // .resolve(\n return {\n //\"extracted_Content\": extracted_Content\n //\"parser_State\": {\n \"open_Tag\": open_Tag\n ,\"content_Headers\": content_Headers\n ,\"headers_End\": headers_End\n ,\"extracted_Content\": extracted_Content\n ,\"file_Buffer\": file_Buffer\n ,\"close_Tag\": close_Tag\n ,\"file_Length\": file_Length\n //}\n }\n // )\n ;\n}",
"parseBravaScript(code) {\n //console.log(code + '\\n Parse operation complete');\n const processedArray = {};\n const params = {};\n const steps = {};\n let currentStep = '';\n let prevStep = '';\n \n // Regexes\n const stripSpaces = /\"[^\"]*\"|\\S+/gm; // Strips spaces\n code = code.replace(/:/g,''); // Strips colons\n\n let rawCodeArray = code.match(stripSpaces);\n //console.log(rawCodeArray);\n //this.setState({parsed: processedArray.join('\\n')});\n var heaterArray = [];\n var whenArray = [];\n\n rawCodeArray.forEach((element, index) => {\n //console.log(`${element} at ${index}`);\n\n switch (element) {\n case 'param':\n // Retrieve parameters\n params[rawCodeArray[this.getChild(index)]] = rawCodeArray[this.getGrandchild(index)];\n break;\n\n case 'step':\n // Get the steps\n currentStep = rawCodeArray[this.getChild(index)];\n steps[currentStep] = {};\n\n if (prevStep !== currentStep) {\n whenArray = [];\n heaterArray = [];\n }\n \n break;\n\n case 'when':\n // Get the exit conditions\n var exitConditionParams = (this.formatSeconds(rawCodeArray[index+3])) ? \n {timeSpent : (this.formatSeconds(rawCodeArray[index+3]))} : \n {probeTemp : rawCodeArray[index+3]};\n\n exitConditionParams.then = rawCodeArray[index+5];\n\n whenArray.push(exitConditionParams); \n steps[currentStep].when = whenArray;\n break;\n\n case 'then':\n // Get the exit step\n break;\n\n case 'heater':\n // Get the heater arrays\n var lampArray = [];\n\n if (rawCodeArray[index+1] !== \"off\") {\n lampArray = [\n parseInt(rawCodeArray[index+1]),\n parseInt(rawCodeArray[index+2]),\n parseInt(rawCodeArray[index+3]),\n parseInt(rawCodeArray[index+4]),\n parseInt(rawCodeArray[index+5]),\n parseInt(rawCodeArray[index+6]),\n parseInt(rawCodeArray[index+8].split('s',1)) ? parseInt(rawCodeArray[index+8].split('s',1)) : 0\n ];\n } else {\n lampArray = [0,0,0,0,0,0,\n parseInt(rawCodeArray[index+3].split('s',1)) ? parseInt(rawCodeArray[index+3].split('s',1)) : 0\n ]\n }\n\n heaterArray.push(lampArray);\n steps[currentStep].heaters = heaterArray;\n break;\n\n case 'for':\n // Get the heater timings\n break;\n\n default:\n break;\n }\n prevStep = currentStep;\n \n });\n\n processedArray.params = params;\n processedArray.steps = steps;\n \n // Convert the JS object into JSON, display the results\n var jsonString = JSON.stringify(processedArray, undefined, 4);\n var syntaxJsonString = this.syntaxHighlight(jsonString);\n this.setState({parsed: syntaxJsonString});\n this.setState({procedureObject: processedArray});\n }",
"function inner_buzz_promise_then(result) {\n console.log(\"Done inner_buzz_promise, result=\"+JSON.stringify(result));\n my_query.buzzfile_url=result.buzzfile_url;\n var promise=MTP.create_promise(my_query.buzzfile_url,AggParser.parse_buzzfile,parse_buzzfile_then);\n }",
"function parseArtistJson(inputText){\n // var len = \"\\\"\"extract\\\":\\\"\".length;\n var text = inputText.substring(inputText.indexOf(\"\\\"extract\\\":\\\"\")+11, inputText.indexOf(\"\\\\n\\\\n\"));\n // var text = inputText.substring(0, inputText.indexOf(\"\\\\n\\\\n\"));\n return text;\n}",
"function BOT_rawStringExtraction(s) {\r\n\tvar res = s ;\r\n\tres = res.replace(/ +$/g, \"\"); // deletewhitespaces at end\r\n\t\r\n\t// javascript expression following words compute|calculate|evaluate|comp|calc and placed AT END\r\n\tBOT_theReqJavascript = res; \r\n\tres = res.replace(/(.*) (compute|calculate|evaluate|comp|calc) (.*)/g, \"$1 compute\");\r\n\tBOT_theReqJavascript = BOT_theReqJavascript.replace(/(.*) (compute|calculate|evaluate|comp|calc) (.*)/g, \"$3\");\r\n\r\n\t// strong stressers double at end\r\n\tres = res.replace(/(.*)\\!\\!$/g, \"$1 _harsh\");\r\n\tres = res.replace(/(.*)\\?\\?$/g, \"$1 _surprise\");\r\n\tres = res.replace(/(.*)\\*\\*$/g, \"$1 _begging\");\r\n\tres = res.replace(/(.*)\\@\\@$/g, \"$1 _apology\");\r\n\tres = res.replace(/(.*)\\&\\&$/g, \"$1 _counterstatement\");\r\n\t\r\n\t// light stressers single at end\r\n\tres = res.replace(/(.*)\\!$/g, \"$1 _strong\");\r\n\tres = res.replace(/(.*)\\?$/g, \"$1 _interrogation\");\r\n\tres = res.replace(/(.*)\\*$/g, \"$1 please\"); // _please below\r\n\tres = res.replace(/(.*)\\@$/g, \"$1 _sorry\");\r\n\tres = res.replace(/(.*)\\&$/g, \"$1 _irony\");\r\n\t\r\n\tres = \" \"+res+\" \"; ;\r\n\t\r\n\t// please\r\n\tres = res.replace(/(.*)please(.*)/g, \"$1 $2 _please\");\r\n\t\r\n\t// possibility -- TO DO: impossible unavailable\r\n\t/*\r\n\tvar t = [\"can i\",\"is it possible to\",\"is it authorized to\",\"is it authorised to\",\"possible\",\"possibility\", \r\n\t\t\t\"available\",\"availability\",\"authorized\",\"authorised\",\"authorization\",\"authorisation\"];\r\n\r\n\tvar rex;\r\n\tfor (var i in t) {\r\n\t\t\trex = new RegExp(eval(\"/(.*) \" + t[i] + \" (.*)/g\"));\r\n\t\t\tres = res.replace(rex, \"$1 $2 _possibility\");\r\n\t\t}\r\n\tres = res.replace(/^ [\\?p] ?(\\w) (.*)/g, \"$1 $2 _possibility\"); // pa | p a | ?a | ? a at begin \r\n\t\r\n\t// is|are at begin\r\n\tres = res.replace(/^( is | are )(.*)/g, \" v $2\");\r\n\t*/\r\n\treturn res\r\n}",
"async function parseSimFileNames(fileType) {\n return new Promise(async function(res,rej) {\n new JSZip.external.Promise(function (resolve, reject) {\n zipFile_fn = 'data/ref_filenames.zip';\n if (fileType == \"example\") \n zipFile_fn = 'https://cvbp-secondary.z19.web.core.windows.net/html_demo/data/ref_filenames.zip';\n JSZipUtils.getBinaryContent(zipFile_fn, function(err, data) {\n if (err) {\n reject(err);\n } else {\n resolve(data);\n }\n });\n }).then(function (data) {\n return JSZip.loadAsync(data);\n }).then(function (zip) {\n if (zip.file(\"../visualize/data/ref_filenames.txt\")) {\n return zip.file(\"../visualize/data/ref_filenames.txt\").async(\"string\");\n } else {\n return zip.file(\"ref_filenames.txt\").async(\"string\");\n }\n }).then(function (text) {\n if (fileType == \"example\") \n fn_array_ex = JSON.parse(text);\n else \n fn_array = JSON.parse(text);\n res();\n });\n })\n \n}",
"function parseAwait() {\n parseMaybeUnary();\n}",
"function extract_main(htmlResponse){\n if(htmlResponse != undefined){\n console.log(\"Started Extraction...\");\n console.log(typeof(htmlResponse))\n var limit;\n limit = get_card_limit(htmlResponse)\n var obj = {}\n // Now we have the limit for the cards so we can make a loop easily\n for(let i = 0; i <= limit; i++) {\n // console.log(\"propertyCard-\"+i)\n // Checking the index of propertyCard-#\n var index = htmlResponse.search('data-test=\"propertyCard-'+i+'\"')\n // console.log(htmlResponse.length)\n propertyString = htmlResponse.substr(index, 10000)\n if( index < 1){\n console.log(\"Nothing found...\")\n }else{\n obj[\"data_\"+i] = {}\n // Now we will check the property details (Name, address, price)\n propertyName = get_property_name(propertyString)\n propertyAddress = get_property_address(propertyString)\n propertyPrice = get_property_price(propertyString)\n propertylink = get_property_link(propertyString)\n\n obj[\"data_\"+i][\"Name\"] = propertyName\n obj[\"data_\"+i][\"Address\"] = propertyAddress\n obj[\"data_\"+i][\"Price\"] = propertyPrice\n obj[\"data_\"+i][\"link\"] = propertylink\n }\n }\n return obj\n }else{\n console.log(\"Waiting for response...\");\n return -1\n }\n\n}",
"function extractText (response) {\n console.log('The AJAX request finished. I am the callback from the first Promise object.')\n return response.text() // <-- returns a new Promise object\n }",
"function qaParser(str){\n\n\n str = str.trim();\n\n /* cuts metadata from input str and removes unnecessary beginning \" */\n let meta = str.slice(str.indexOf('|'), str.lastIndexOf('|') + 1);\n\n /* cuts text string from input str and removes unnecessary ending \" */\n let string = str.slice(str.lastIndexOf('|') + 1, -1);\n\n\n let aReg = /\\|Q(\\d*):(\\d):Q(\\d*)\\|/i;\n let qReg = /\\|Q(\\d*)\\|/i;\n let qfReg = /\\|Q(\\d*)\\?(\\w*)\\|/i;\n\n let question = {\n text : \"\",\n answers : [],\n stepID : 0\n };\n\n let answer = {\n text : \"\",\n questionID : 0,\n answerID : 0,\n stepID : 0\n };\n\n\n if(meta.match(qReg)){\n question.text = string;\n question.stepID = qReg.exec(meta)[1];\n nodes[0].push(question);\n // return question;\n }\n\n if(meta.match(qfReg)){\n let opt = qfReg.exec(meta)\n question.text = string;\n question.stepID = opt[1];\n question.final = opt[2] == 'FT';\n delete question.answers;\n nodes[0].push(question);\n // return answer;\n }\n\n if(meta.match(aReg)){\n let opt = aReg.exec(meta);\n answer.text = string;\n answer.questionID = opt[1];\n answer.answerID = opt[2];\n answer.stepID = opt[3];\n nodes[1].push(answer);\n // return answer;\n }\n\n // return null;\n}",
"function parseToAsync(expression, options) {\n var parsedExpression = parse(expression, options);\n return function (path, basename, siblingsFn) {\n var result = parsedExpression(path, basename, siblingsFn);\n return result instanceof winjs_base_1.TPromise ? result : winjs_base_1.TPromise.as(result);\n };\n }",
"async getFileString(currFile) {\n try {\n const response = await axios.get(currFile.raw_url, headers);\n let data = response.data;\n return {\n 'string_file': data,\n 'pull_number': currFile.pull_number\n };\n } catch (error) {\n console.log(error);\n console.log(\"Error: getFileString()\")\n\n }\n }",
"async function proccess(fileName) {\n const [result] = await client.textDetection(fileName);\n const detections = result.textAnnotations;\n let content = 'content';\n // console.log('result:'+ JSON.stringify(result));\n detections.forEach((text, index) => {\n if(index === 0){\n content = text.description; \n return {content, json: result}\n }\n \n return {content, json: result}\n });\n return {content, json: result}\n}",
"function extractrequire(string) {\n let parseArray = string.split(' ');\n //console.log(parseArray);\n if ((parseArray[0] == 'let' || parseArray[0] == 'const') && parseArray[2] == '=' && parseArray[3].startsWith(\"require(\")) {\n let reqArray = parseArray[3].split('(');\n reqArray = reqArray.slice(1, reqArray.length);\n reqArray.forEach((req) => {\n let firstquote = req.search('\"');\n if (firstquote == -1) firstquote = req.search(\"'\");\n firstquote++;\n let secondquote = firstquote;\n while (req[secondquote] != \"'\" && req[secondquote] != '\"' && secondquote < req.length) {\n secondquote++;\n }\n if (firstquote != secondquote && req.search('./') == -1) {\n req = req.slice(firstquote,secondquote);\n tally(req);\n }\n });\n }\n}",
"function runFn( str, fn, returnHandle, args, isAsync, reject, brackets ){\n\t\t\tvar result,\n\t\t\t\t//custom resolve handle which updates the result variable to the resolved value\n\t\t\t\tresolveHandle = function( val ){\n\t\t\t\t\tresult = val;\n\t\t\t\t},\n\t\t\t\thasError = false,\n\t\t\t\t//custom reject handle to run the initial reject function and set hasError to true\n\t\t\t\trejectHandle = function( err ){\n\t\t\t\t\treject( err );\n\t\t\t\t\thasError = true;\n\t\t\t\t};\n\t\t\t\n\t\t\t//To run the given function with the given resolve and reject handles\n\t\t\tfunction run( resolve, reject ){\n\t\t\t\tvar close,\n\t\t\t\t\t//create a new extraction\n\t\t\t\t\tX = new Extraction( isAsync, reject, str, brackets );\n\t\t\t\t\n\t\t\t\t/*\n\t\t\t\tTo finish and resolve using the return handle\n\t\t\t\t\tInput :\n\t\t\t\t\t\t- content : handle string\n\t\t\t\t*/\n\t\t\t\tfunction finish( content ){\n\t\t\t\t\t//the nest is the Extraction base nest (or an empty nest if there is an error)\n\t\t\t\t\tvar nest = hasError ? new Nest() : X.Nest.public,\n\t\t\t\t\t\t//get the return value by running the returnHandle in the context of the nest with the handled string as the input argument\n\t\t\t\t\t\tvalue = returnHandle.call( nest, content);\n\t\t\t\t\t\t\n\t\t\t\t\t//resolve with the return value\n\t\t\t\t\tresolve( value );\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//run the given function with the given arguments\n\t\t\t\tfn.apply( X, args );\n\t\t\t\t\n\t\t\t\t//try to close the Extraction\n\t\t\t\tclose = X.tryClose();\n\t\t\t\t\n\t\t\t\t//if Async, then 'close' is a Promise, so run the finish function when resolved\n\t\t\t\tif( isAsync ) close.then(finish,reject);\n\t\t\t\t//otherwise, finish using 'close' as the input argument\n\t\t\t\telse finish( close );\n\t\t\t}\n\t\t\n\t\t\t//if in async mode, then run the function inside a Promise\n\t\t\tif( isAsync ) return new Promise( run )\n\t\t\t//otherwise, run the function using the custom resolve and reject handles\n\t\t\trun( resolveHandle, rejectHandle );\n\t\t\t//and return the result\n\t\t\treturn result; \n\t\t}",
"fulfillString(str) {\n return str.replace(/{{([^}]+)}}/g, (match, group) => {\n if (this.hasSlot(group)) {\n return this.slot(group);\n }\n if (this.hasRequestAttr(group)) {\n return this.getRequestAttr(group);\n }\n if (this.hasSessionAttr(group)) {\n return this.getSessionAttr(group);\n }\n if (this.hasPersistentAttr(group)) {\n return this.getPersistentAttr(group);\n }\n return match;\n });\n }",
"parseQuotedString(startIndex, urlChars, tokenIndex, token) {\n let i = startIndex + 1; // look for closing '\"' from the next index\n while (i < urlChars.length) {\n const curChar = urlChars[i];\n if (curChar == EXT_DOUBLE_QT) {\n // Got the \" which ends the quoted block, so break the loop\n // Return the new indices, caller would resume from this new indices.\n return [i, tokenIndex];\n } else {\n token[tokenIndex++] = curChar;\n }\n i++;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the neterror information that's sent to us as part of the documentURI and return an error object. The error object will contain the following attributes: e Type of error (eg. 'netOffline'). u URL that generated the error. m Manifest URI of the application that generated the error. c Character set for default gecko error message (eg. 'UTF8'). d Default gecko error message. f The frame type ("regular", "browser", "app") | function getErrorFromURI() {
var error = {},
uri = document.documentURI;
// Quick check to ensure it's the URI format we're expecting.
if (!uri.startsWith('about:neterror?')) {
// A blank error will generate the default error message (no network).
return error;
}
// Small hack to get the URL object to parse the URI correctly.
var url = new URL(uri.replace('about:', 'http://'));
// Set the error attributes.
['e', 'u', 'm', 'c', 'd', 'f'].forEach(
function(v) {
error[v] = url.searchParams.get(v);
}
);
switch (error.e) {
case 'connectionFailure':
case 'netInterrupt':
case 'netTimeout':
case 'netReset':
error.e = 'connectionFailed';
break;
case 'unknownSocketType':
case 'unknownProtocolFound':
case 'cspFrameAncestorBlocked':
error.e = 'invalidConnection';
break;
}
return error;
} | [
"function getErrorFromURI() {\n var error = {};\n var uri = document.documentURI;\n\n // Quick check to ensure it's the URI format we're expecting.\n if (!uri.startsWith('about:neterror?')) {\n // A blank error will generate the default error message (no network).\n return error;\n }\n\n // Small hack to get the URL object to parse the URI correctly.\n var url = new URL(uri.replace('about:', 'http://'));\n\n // Set the error attributes.\n ['e', 'u', 'm', 'c', 'd'].forEach(\n function(v) {\n error[v] = url.searchParams.get(v);\n }\n );\n\n return error;\n }",
"function parseError(error) {\n const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;\n const errorString = isFirefox ? error.toString() + \" \" + error.stack : error.stack;\n const regex =/(\\b(https?|ftp|file):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/ig;\n const errorNoURL = errorString.replace(regex, url => '<i>' + last(url.split(\"/\")) + '</i>');\n const errorParsed = errorNoURL.replace(/at /ig, \"<br> at \");\n return errorParsed;\n}",
"function errorstr(aError) {\r\n let error;\r\n\r\n let intErr=0;\t//next free: 20\r\n if (typeof aError == 'string') {\r\n let err=Number(aError);\r\n if (!isNaN(err)) aError=err;\r\n }\r\n //Errorcodes:\r\n // xpcom/base/nsError.h\r\n // netwerk/base/public/nsNetError.h\r\ndebug('original Error: '+aError);\r\n switch(aError){\r\n // internal errors\r\n case -1:\r\n intErr=1;\r\n error=strings['unexperr']; // 'unexpected initialization error';\r\n break;\r\n case -2:\r\n intErr=2;\r\n error=strings['localreaderr']; // 'local mab file read error'; //access denied (also gives unhandled exception), does not exist\r\n break;\r\n case -3:\r\n intErr=3;\r\n error=strings['illimap'];\r\n break;\r\n //Thunderbird network error, see netwerk/base/public/nsNetError.h\r\n case 0x804b000d:\r\n //NS_ERROR_CONNECTION_REFUSED 13\r\n //The connection attempt failed, for example, because no server was listening\r\n //at specified host:port.\r\n intErr=4;\r\n error=strings['protnotavail']; // 'protocol not available';\r\n break;\r\n case 0x804b000e:\r\n //NS_ERROR_NET_TIMEOUT 14\r\n //The connection was lost due to a timeout error.\r\n intErr=12;\r\n error=strings['timeout']; // 'timeout';\r\n break;\r\n case 0x804b0011:\r\n //NS_ERROR_NO_CONTENT 17\r\n intErr=16;\r\n error='No content';\r\n // used, when Firefox is set as 'network.protocol-handler.app.ftp'\r\n // for FTP. The addressbook is shown in Firefox!\r\n break;\r\n case 0x804b0012:\r\n //NS_ERROR_UNKNOWN_PROTOCOL 18\r\n // The URI scheme corresponds to an unknown protocol handler.\r\n intErr=17;\r\n error='Unknown protocol handler';\r\n // happens after removing application-handler after NS_ERROR_NO_CONTENT\r\n break;\r\n case 0x804b0014:\r\n //NS_ERROR_NET_RESET 20\r\n intErr=19;\r\n error=\"Network reset\"; // i.e. Service not available\r\n break;\r\n//ftp is obsolete since TB90\r\n case 0x804b0015:\r\n //NS_ERROR_FTP_LOGIN 21\r\n intErr=10;\r\n error=strings['illcred']; // illegal credentials';\r\n break;\r\n case 0x804b0016:\r\n //NS_ERROR_FTP_CWD 22\r\n intErr=15;\r\n error=strings['nofile'];\r\n break;\r\n//NS_ERROR_FTP_PASV 23\r\n//NS_ERROR_FTP_PWD 24\r\n//NS_ERROR_FTP_LIST 25\r\n case 0x804b001e:\r\n //NS_ERROR_UNKNOWN_HOST 30\r\n intErr=5;\r\n error=strings['hostnotfound']; // 'host not found';\r\n break;\r\n case 0x804b002a:\r\n //NS_ERROR_UNKNOWN_PROXY_HOST 42\r\n intErr=13;\r\n error=strings['proxynotfound']; // 'proxy not found';\r\n break;\r\n case 0x804b0048:\r\n //NS_ERROR_PROXY_CONNECTION_REFUSED 72\r\n intErr=14;\r\n error=strings['proxyerr']; // 'proxy error';\r\n break;\r\n //external errors (server error, windows error)\r\n case 0x80004002:\r\n /* NS_ERROR_NO_INTERFACE: Returned when a given interface is not supported. */\r\n intErr=18;\r\n error='External application handler set';\r\n //This happens on ftp upload when an external handler is set\r\n break;\r\n case 0x80004005:\r\n /* NS_ERROR_FAILURE: Returned when a function fails */\r\n intErr=6;\r\n error=strings['permdenied']; // früher 'fileunavail', file unavailable\r\n //??? (with FTP: Error 550: File unavailable (e.g., file not found, no access).\r\n //(with IMAP: wenn der alte Upload mit 'CopyFileMessage' verwendet wird)\r\n break;\r\n case 405:\r\n intErr=7;\r\n error=strings['methodnotallowed']; // method not allowed'; //method is something like PUT,POST or GET\r\n break;\r\n case 404:\r\n intErr=8;\r\n error=strings['notfound']; // not found';\r\n break;\r\n case 403:\r\n intErr=9;\r\n error=strings['permdenied']; // permission denied';\r\n break;\r\n case 401:\r\n intErr=11;\r\n error=strings['illcred']; // illegal credentials';\r\n break;\r\n case 0:\r\n case 201:\r\n case 204:\r\n error=strings['ok'];\r\n break;\r\n default:\r\n let sError;\r\n if (aError&0xffff0000) {\r\n if ((aError>>>16)==0x804b) //TB Netzwerk errors, see xpcom\\base\\ErrorList.py\r\n\t\t\t\t\t\t\t\t\t\t\t//or https://searchfox.org/mozilla-central/source/__GENERATED__/xpcom/base/ErrorList.h\r\n sError='TB-'+(aError&0xffff).toString(10);\r\n else\r\n sError='0x'+aError.toString(16);\r\n } else\r\n sError=aError;\r\n error='Error '+sError;\r\n break;\r\n }\r\n if (intErr) error+=' ('+intErr+')';\r\n return error;\r\n}",
"parseError(aStanza) {\n if (aStanza.attributes.type != \"error\") {\n return undefined;\n }\n\n let retval = { stanza: aStanza };\n let error = aStanza.getElement([\"error\"]);\n\n // RFC 6120 Section 8.3.2: Type must be one of\n // auth -- retry after providing credentials\n // cancel -- do not retry (the error cannot be remedied)\n // continue -- proceed (the condition was only a warning)\n // modify -- retry after changing the data sent\n // wait -- retry after waiting (the error is temporary).\n retval.type = error.attributes.type;\n\n // RFC 6120 Section 8.3.3.\n const kDefinedConditions = [\n \"bad-request\",\n \"conflict\",\n \"feature-not-implemented\",\n \"forbidden\",\n \"gone\",\n \"internal-server-error\",\n \"item-not-found\",\n \"jid-malformed\",\n \"not-acceptable\",\n \"not-allowed\",\n \"not-authorized\",\n \"policy-violation\",\n \"recipient-unavailable\",\n \"redirect\",\n \"registration-required\",\n \"remote-server-not-found\",\n \"remote-server-timeout\",\n \"resource-constraint\",\n \"service-unavailable\",\n \"subscription-required\",\n \"undefined-condition\",\n \"unexpected-request\",\n ];\n let condition = kDefinedConditions.find(c => error.getElement([c]));\n if (!condition) {\n // RFC 6120 Section 8.3.2.\n this.WARN(\n \"Nonstandard or missing defined-condition element in error stanza.\"\n );\n condition = \"undefined-condition\";\n }\n retval.condition = condition;\n\n let errortext = error.getElement([\"text\"]);\n if (errortext) {\n retval.text = errortext.innerText;\n }\n\n return retval;\n }",
"parseErrorMessage(err) {\n if (err.name === 'HTTPError') {\n const { body } = err.response;\n if (typeof body === 'string' && body.startsWith('<!')) {\n const heading = /<h1>([^<]+)<\\/h1>/i.exec(body);\n const message = /<p>([^<]+)<\\/p>/i.exec(body);\n return new CoverArtArchiveError(\n `${heading ? heading[1] + ': ' : ''}${message ? message[1] : ''}`,\n err.response\n );\n }\n }\n return super.parseErrorMessage(err);\n }",
"function populateFrameMessages() {\n var title = document.getElementById('error-title');\n var message = document.getElementById('error-message');\n\n var error = getErrorFromURI();\n switch (error.e) {\n case 'dnsNotFound': {\n localizeElement(title, 'server-not-found');\n localizeElement(message, 'server-not-found-error', {\n name: location.host\n });\n }\n break;\n\n case 'netOffline': {\n localizeElement(title, 'unable-to-connect');\n localizeElement(message, 'tap-to-retry');\n }\n break;\n\n default: {\n localizeElement(title, 'unable-to-connect');\n localizeElement(message, 'tap-to-retry');\n }\n }\n }",
"function handleFeedParsingFailed(error) {\n setFeedTitle(unknownName);\n\n // The tests always expect an IFRAME, so add one showing the error.\n var html = \"<body><span id=\\\"error\\\" class=\\\"item_desc\\\">\" + error +\n \"</span></body>\";\n if (window.domAutomationController) {\n html += \"<script src='\" + chrome.extension.getURL(\"test_send_error.js\") +\n \"'></\" + \"script>\";\n }\n\n var error_frame = createFrame('error', html);\n var itemsTag = document.getElementById('items');\n itemsTag.appendChild(error_frame);\n}",
"function getLocError(err) {\n\n $$.ajax({\n url: 'http://ip-api.com/json/',\n type: 'POST',\n dataType: 'jsonp',\n success: function(loc) {\n var geoip = JSON.parse(loc);\n console.log(\"geoip location=>\", geoip);\n location = {\n latitude: geoip.lat,\n longitude: geoip.lon,\n accuracy: 500\n }\n data.location = location;\n submit();\n },\n error: function(err) {\n console.log(\"get html5 LocError!\");\n\n var lon = getCookie(\"lon\");\n var lat = getCookie(\"lat\");\n location = {\n latitude: lat,\n longitude: lon\n }\n data.location = location;\n submit();\n // if get geoip's data failed then give a default loaciotn from user setting.\n }\n }); // end ajax\n\n } // end error",
"function getLocError(err) {\n\n $$.ajax({\n url: 'http://ip-api.com/json/',\n type: 'POST',\n dataType: 'jsonp',\n success: function(loc) {\n var geoip = JSON.parse(loc);\n console.log(\"geoip location=>\", geoip);\n location = {\n latitude: geoip.lat,\n longitude: geoip.lon,\n accuracy: 500\n }\n data.location = location;\n submit();\n },\n error: function(err) {\n console.log(\"get html5 LocError!\");\n\n var lon = getCookie(\"lon\");\n var lat = getCookie(\"lat\");\n location = {\n latitude: lat,\n longitude: lon\n }\n data.location = location;\n $$(\"#finishStep\").removeAttr('disabled');\n submit();\n // if get geoip's data failed then give a default loaciotn from user setting.\n }\n }); // end ajax\n\n } // end error",
"function parseRequestError(data, default_message) {\n let error_message = null;\n try {\n error_message = $(data.responseText).find('.traceback').text();\n } catch(error) {\n error_message = default_message;\n }\n\n return error_message\n }",
"function get_error_html(err, url){\n var status_code = \"\";\n var err_message = \"\";\n if(err.hasOwnProperty(\"status\")){ status_code = err.status; }\n if(err.hasOwnProperty(\"responseJSON\") && err.responseJSON.hasOwnProperty(\"error\")){\n err_message = err.responseJSON.error;\n }else if(err.hasOwnProperty(\"statusText\")){\n err_message = err.statusText;\n }else{\n err_message = \"An unexpected error occurred.\"\n }\n if(aci_app && (status_code == 400 || status_code == 403)){\n err_message+=\"<br><br>This error generally indicates a session timeout on the APIC\"\n }\n if(typeof url == 'undefined'){ url = \"\"; }\n else{\n url = \" <span class=\\\"label label-info\\\">url: \"+url+\"</span>\"\n } \n code = \"<span class=\\\"label label-danger\\\"><strong>Error \"+status_code+\"</strong></span>\"\n return \"<p>\"+code+url+\"</p><p>\"+err_message+\"</p>\";\n}",
"function networkError(response, error) {\n\tvar content = {\n\t\tsuccess: false,\n\t\tstatus_code: error.code || '4000',\n\t\terror_type: ErrorType.network\n\t};\n\n\tif (error.msg) {\n\t\tcontent.message = error.msg;\n\t}\n\n\tlogger.error('[res], network error', JSON.stringify(content), error.code);\n\n\tsend(response, content, StatusCode.ok);\n}",
"function 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}",
"function requestError()\n{\n throw new Error(\"Something went wrong. Ensure you have entered a valid url and you are connected to the internet.\");\n}",
"function FileGetErrorMessage(e) {\r\n var msg = \"\";\r\n\r\n if (e.code) {\r\n switch (e.code) {\r\n case 5: //ENCODING_ERR\r\n msg = \"URL incompleto o non valido (code: ENCODING_ERR)\";\r\n break;\r\n case FileError.INVALID_MODIFICATION_ERR:\r\n msg = \"La modifica richiesta non e' consentita (code: INVALID_MODIFICATION_ERR)\";\r\n break;\r\n case FileError.INVALID_STATE_ERR:\r\n msg = \"L'operazione richiesta non può essere effettuata nello stato corrente dell'oggetto di interfaccia (code: INVALID_STATE_ERR)\";\r\n break;\r\n case 6: //NO_MODIFICATION_ALLOWED_ERR\r\n msg = \"Lo stato della file system in uso non consente la scrittura di file o directory (code: NO_MODIFICATION_ALLOWED_ERR)\";\r\n break;\r\n case FileError.NOT_FOUND_ERR:\r\n msg = \"Il file richiesto non e' stato trovato (code: NOT_FOUND_ERR)\";\r\n break;\r\n case 4: //NOT_READABLE_ERR\r\n msg = \"Il file non può essere letto, potrebbe essere un problema di permessi (code: NOT_READABLE_ERR)\";\r\n break;\r\n case 12: //PATH_EXISTS_ERR\r\n msg = \"Esiste gia' un file o directory con il percorso specificato (code: PATH_EXISTS_ERR)\";\r\n break;\r\n case FileError.QUOTA_EXCEEDED_ERR:\r\n msg = \"Lo spazio di memorizzazione non e' sufficiente (code: QUOTA_EXCEEDED_ERR)\";\r\n break;\r\n case FileError.SECURITY_ERR:\r\n msg = \"L'accesso al file e' negato (code: SECURITY_ERR)\";\r\n break;\r\n default:\r\n msg = 'Errore sconosciuto (code: ' + e.code.toString() + ')';\r\n break;\r\n };\r\n } else {\r\n //errore std js\r\n msg = e.message;\r\n }\r\n\r\n return msg;\r\n}",
"function getError(recv) {\r\n var obj = {};\r\n try {\r\n obj = JSON.parse(recv);\r\n } catch (e) {\r\n obj = recv;\r\n }\r\n if (!obj || obj.errno === undefined || obj.errno == 0)\r\n return null;\r\n else\r\n return obj.msg;\r\n}",
"function extractDefaultErrorMessage(request)\n {\n var buff = \"\";\n if(request == null || typeof(request) == 'undefined')\n \treturn \"\";\n //Handle responses from cross domain requests\n if(typeof(request.responseText) == 'undefined' && typeof(request.message) != 'undefined')\n {\n request[\"responseText\"] = request.message;\t\n }\n if(request.responseText == null || request.responseText.length == 0)\n return \"\";\n var error = null;\n try\n { \n error = JSON.parse(request.responseText);\n //IE handles this differently from all other browsers, of course\n if($.browser.msie && !error && typeof(request.responseText) == 'string' && request.responseText.length > 0)\n {\n return request.responseText;\n }\n }\n catch(e){}\n\n if(error != null && error.Errors)\n {\n var def = \"\";\n if(typeof(error.defaultMessage) != 'undefined')\n {\n def = error.defaultMessage;\n }\n else if(typeof(error.Errors.globalError.defaultMessage) != 'undefined')\n {\n def = error.Errors.globalError.defaultMessage;\n }\n else if(typeof(error.Errors.localizedMessage) != 'undefined')\n {\n def = error.Errors.localizedMessage;\n }\n else if(typeof(error.Errors.globalError.code) != 'undefined')\n {\n var prefix = request.status == 500 ? \"Server Error: \" : \"\";\n def = prefix + error.Errors.globalError.code;\n }\n buff += def; \n }\n else if (error != null && error.ValidationErrors != undefined)\n {\n var verrors = error.ValidationErrors;\n if (verrors.fieldErrors != undefined)\n {\n buff += objectErrorToString(verrors.fieldErrors);\n }\n else if (verrors.globalErrors != undefined)\n {\n buff += objectErrorToString(verrors.globalErrors);\n }\n else if (verrors.globalError != undefined)\n {\n buff += objectErrorToString(verrors.globalError);\n }\n }\n \n //XML section. for the moment just parse validation errors\n var xmlResponse;\n if (typeof(request.responseText) != 'undefined' && request.responseText.indexOf('<?xml') != -1) {\n xmlResponse = $(request.responseText);\n }\n else if (typeof(request) == 'string' && request.indexOf('<?xml') != -1){\n xmlResponse = $(request);\n }\n if (typeof(xmlResponse) != 'undefined' && xmlResponse.is('ValidationErrors'))\n {\n if (xmlResponse.find('globalErrors').find('defaultMessage').text() != \"\")\n {\n buff += xmlResponse.find('globalErrors').find('defaultMessage').text();\n }\n else if (xmlResponse.find('globalError').find('defaultMessage').text() != \"\")\n {\n buff += xmlResponse.find('globalError').find('defaultMessage').text() != \"\";\n }\n else if(xmlResponse.next('defaultMessage'))\n {\n buff += xmlResponse.next('defaultMessage')[0].nextSibling.nodeValue;\n }\n }\n if (buff == \"\"){ buff = request.responseText;}\n return buff; \n }",
"function checkForError(doc) {\n var win = goog.dom.getWindow(doc);\n var text = doc.body.textContent || doc.body.innerText || '';\n var gseError = text.match(/([^\\n]+)\\nError ([0-9]{3})/);\n if (gseError) {\n return '(Error ' + gseError[2] + ') ' + gseError[1];\n } else if (win.gmail_error) {\n return win.gmail_error + 700;\n } else if (win.rc) {\n return 600 + win.rc % 100;\n } else {\n return null;\n }\n}",
"function _parserFirefox(error){\n\t\t// start parse the error stack string\n\t\tvar lines\t= error.stack.split(\"\\n\").slice(0, -1);\n\t\tvar stacktrace\t= [];\n\t\tlines.forEach(function(line){\n\t\t\tvar matches\t= line.match(/^(.*)@(.+):(\\d+)$/);\n\t\t\tstacktrace.push(new Stacktrace.Frame({\n\t\t\t\tfct\t: matches[1] === '' ? '<anonymous>' : matches[1],\n\t\t\t\turl\t: matches[2],\n\t\t\t\tline\t: parseInt(matches[3], 10),\n\t\t\t\tcolumn\t: 1\n\t\t\t}));\n\t\t});\n\t\treturn stacktrace;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Note: the hook is passed as the `this` argument to allow proxying the arguments without requiring a full array allocation to do so. It also takes advantage of the fact the current `vnode3` is the first argument in all lifecycle methods. | function callHook(vnode3) {
var original = vnode3.state
try {
return this.apply(original, arguments)
} finally {
checkState(vnode3, original)
}
} | [
"function callHook(vnode) {\n \t\tvar original = vnode.state;\n \t\ttry {\n \t\t\treturn this.apply(original, arguments)\n \t\t} finally {\n \t\t\tcheckState(vnode, original);\n \t\t}\n \t}",
"function callHook(vnode) {\n\t\tvar original = vnode.state;\n\t\ttry {\n\t\t\treturn this.apply(original, arguments)\n\t\t} finally {\n\t\t\tcheckState(vnode, original);\n\t\t}\n\t}",
"function callHook(vnode) {\n\t\tvar original = vnode.state\n\t\ttry {\n\t\t\treturn this.apply(original, arguments)\n\t\t} finally {\n\t\t\tcheckState(vnode, original)\n\t\t}\n\t}",
"function callHook(vnode) {\n var original = vnode.state\n try {\n return this.apply(original, arguments)\n } finally {\n checkState(vnode, original)\n }\n }",
"function transformVNodeArgs(transformer){vnodeArgsTransformer=transformer;}",
"function $9c2aaba23466b352$export$c7b2cbe3552a0d05() {\n for (var _len2 = arguments.length, refs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n refs[_key2] = arguments[_key2];\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return $dJwbH$react.useCallback($9c2aaba23466b352$export$43e446d32b3d21af(...refs), refs);\n}",
"__patch(target, vnode) {\n this.__owl__.vnode = patch(target, vnode);\n }",
"function transformVNodeArgs(transformer) {\r\n vnodeArgsTransformer = transformer;\r\n}",
"function transformVNodeArgs(transformer) {\n vnodeArgsTransformer = transformer;\n}",
"function transformVNodeArgs(transformer) {\n vnodeArgsTransformer = transformer;\n}",
"didUpdateArguments() {\n /* no op, for subclassing */\n }",
"function __transrateVNode(...args) {\r\n return wrapWithDeps(context => {\r\n let ret;\r\n const _context = context;\r\n try {\r\n _context.processor = processor;\r\n ret = translate(_context, ...args);\r\n }\r\n finally {\r\n _context.processor = null;\r\n }\r\n return ret;\r\n }, () => parseTranslateArgs(...args)[0], 'translate', \r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val));\r\n }",
"function VirtualElementPass(tag, attrs, renderer) {\n return _super.call(this, tag, attrs, [], renderer || undefined) || this;\n }",
"function VirtualElementPass(tag, attrs, renderer) {\n return _super.call(this, tag, attrs, [], renderer || undefined) || this;\n }",
"add3(arg1, arg2, arg3, impl) {\r\n this.variants.push({\r\n args: [arg1, arg2, arg3],\r\n varargs: false,\r\n impl: (c, ...rest) => impl(rest[0], rest[1], rest[2], c),\r\n });\r\n return this;\r\n }",
"bindHooks() {\n //\n }",
"function transrateVNode(...args) {\r\n return wrapWithDeps(context => {\r\n let ret;\r\n const _context = context;\r\n try {\r\n _context.processor = processor;\r\n ret = coreBase.translate(_context, ...args);\r\n }\r\n finally {\r\n _context.processor = null;\r\n }\r\n return ret;\r\n }, () => coreBase.parseTranslateArgs(...args), 'translate', \r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n root => root[TransrateVNodeSymbol](...args), key => [vue.createVNode(vue.Text, null, key, 0)], val => shared.isArray(val));\r\n }",
"_getBuiltInCallbacks() {\n const callbacks = {\n updateProperty: function (prop, value, shouldRender) {\n this.fireAction(prop + 'Changed', { value: value, previousValue: this.props[prop], updatedFrom: 'internal' });\n }.bind(this),\n queueRender: function (element) {\n // TODO: Use busy state abstraction once JET-29316 is implemented\n if (!this._busyStateCallbackForRender && !this.isPatching()) {\n var busyContext = Context.getContext(element).getBusyContext();\n this._busyStateCallbackForRender = busyContext.addBusyState({\n description: this.props.id + ' is waiting to render.'\n });\n window.requestAnimationFrame(function () {\n try {\n // We are not passing the other two parameters for uncontrolled root props since the\n // VComponent queueRender case is only called by updateState for the VComponent-first case which would\n // not have any effect on uncontrolled properties.\n this.patch(this.props);\n }\n catch (error) {\n throw error;\n }\n finally {\n this._busyStateCallbackForRender();\n this._busyStateCallbackForRender = null;\n }\n }.bind(this));\n }\n }.bind(this),\n fireAction: function (type, detail) {\n // look for an action listener and call it directly\n const listenerProp = oj.__AttributeUtils.eventTypeToEventListenerProperty(type);\n const listener = this.props[listenerProp];\n if (listener) {\n listener({ type: type, detail: detail });\n }\n }.bind(this),\n storeUnslottedNodes: function (slotMap) {\n // No storage node for VComponent-first cases so we don't need to worry about moving\n // any unslotted nodes to the storage node.\n }\n };\n callbacks['_vcomp'] = true;\n return callbacks;\n }",
"async hookView(hookName, viewName, args = {}, params = {}) {\n //console.log(params);\n if (Array.isArray(viewName)) {\n let viewParams = viewName;\n viewName = viewParams.shift();\n await this.addView(viewName, viewParams);\n }\n let view = this.view(viewName);\n if (!view) {\n (await this.logger).warn('Invalid view name: ' + viewName);\n return this;\n }\n let p = {};\n if (!('alias' in params)) {\n p['alias'] = viewName;\n }\n //console.log(p);\n await this.hook(hookName, view, args, p);\n return this;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provides more expired events information formatted as and elements | getMoreExpired(){
this._numCurrent = 1;
let output = _formatEventsIntoHTML(this._schedule[1].slice(this._numExpired - 1, this._numExpired + 9));
this._numExpired += 10;
return output;
} | [
"get expired() {\n return this.invokedAt + 1000 * 60 * 15 < Date.now();\n }",
"getFullSchedule(){\n let schedule = this._accountManager.viewSignedUpEvents(this._username);\n this._numCurrent = 1;\n this._numExpired = 1;\n\n let current = Object.keys(schedule[0]);\n let expired = Object.keys(schedule[1]);\n\n for (let i = 0; i < current.length; i++){\n current[i] = this._eventManager.getEvent(current[i]);\n }\n for (let i = 0; i < expired.length; i++){\n expired[i] = this._eventManager.getEvent(expired[i]);\n }\n this._schedule = [current, expired];\n }",
"renderUpcomingEvents() {\n var text = [];\n var email = Profiles.findOne({ accountId: Meteor.user()._id }).email.toString();\n let postsToDisplay = Posts.find({ type: { $in: ['SailingEvent'] } });\n var today = new Date();\n return postsToDisplay.map((post) => {\n var dayMonthYear = post.date.split('/');\n var postDate = new Date(dayMonthYear[2], dayMonthYear[0] - 1, dayMonthYear[1], 0, 0);\n postDate.setDate(postDate.getDate() + 1);\n //Check if the event is in the past\n if (postDate.getTime() >= today.getTime()) {\n return (\n <span>\n <Post key={ post._id } post= { post } role= { Profiles.findOne({ accountId: Meteor.user()._id }).member } />\n <br />\n </span>\n //</ul >\n\n );\n }\n else {\n //don't show event if the date and time has passed\n }\n });\n }",
"function showCurrentEvents () {\n // remove current elements and listeners\n [...eventFeed.children].forEach(elm => elm = null);\n let html = '';\n\n const events = state.get('events'),\n date = state.get('day'),\n today = events.singles[date],\n weekly = events.weekly[getDayOfWeek(date)],\n monthly = events.monthly[date.substring(5,7)],\n annually = events.annually[date.substring(5)],\n listItem = (type, label, i) => (`<li class='event-list-item' data-index='${type}-${i}'>${label}</li>`);\n\n console.log({ today, weekly, monthly, annually })\n\n if (today) today.forEach((event, i) => html += listItem('singles', event.name, i));\n if (annually) annually.forEach((event, i) => html += listItem('annually', event.name, i));\n if (weekly) weekly.forEach((event, i) => html += listItem('weekly', event.name, i));\n if (monthly) monthly.forEach((event, i) => html += listItem('monthly', event.name, i));\n\n eventFeed.innerHTML = html;\n clickEach([...eventFeed.getElementsByClassName('event-list-item')], getEventDetails, {capture: true})\n }",
"numberOfEvents(){\n let upComing = 0;\n let expired = 0;\n for (const [key, value] of Object.entries(this._schedule)){\n if (value[0] > new Date().getTime()){\n upComing++;\n }else {\n expired++;\n }\n }\n return [upComing, expired];\n }",
"function overview() {\n var eventsDB = Db.shared.get('events');\n \n // getting the times, starting by most recent time\n var times = Object.keys(eventsDB);\n times.reverse();\n \n // and render for each day the time\n Dom.div(function () {\n Dom.style({\n textAlign: 'center',\n marginTop: '1em'\n });\n \n times.forEach(function (time) {\n // show what day it is\n timeMessage(timeString(time));\n \n // display the events\n var events = eventsDB[time];\n events.reverse();\n events.forEach(renderEvent);\n });\n });\n }",
"static expiresOn( alert ) {\n var ex_date = new Date(alert.expiration_date);\n var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'};\n if (alert.expiration_date != null) {\n // Get that expiration date and display that expiration date\n return 'Expires On: ' + ex_date.toLocaleDateString(navigator.language, options);\n //else return no exipration date added\n }else{\n return 'No expiration date added '\n }\n}",
"isExpired() {\n return this.expirationTime < msalCommon.TimeUtils.nowSeconds();\n }",
"get expirationDate() {\n return this.getStringAttribute('expiration_date');\n }",
"createExpirationTimeDisplay(feed) {\n return this.createTimeDisplay(feed, mv.COMMITMENT_MAX_WAIT_FACTOR)\n }",
"hasNotExpired(now,entry){return !isNaN(now)&&!isNaN(entry.lastFetchTime)&&now-entry.lastFetchTime<RECORD_EDIT_ACTIONS_TTL;}",
"get expiration() {\n return this.getStringAttribute('expiration');\n }",
"function getTaggedEvents() {\n $scope.countdown = [];\n var todayDate = new Date(Date.now() + getFutureDay(dayCount));\n todayDate.setHours(0,0,0,0);\n if(dayCount < 0){\n var currDate = new Date();\n currDate.setHours(0,0,0,0)\n }\n else {\n currDate = todayDate\n }\n var hr = new Date().getHours();\n var eventList = gapi.client.calendar.events.list({\n 'calendarId': 'primary',\n 'timeMin': currDate.toISOString(),\n 'q': '[reminder]',\n 'showDeleted': false,\n 'singleEvents': true,\n 'orderBy': 'startTime'\n });\n eventList.execute(function(resp) {\n var events = resp.items;\n supersonic.logger.log(events);\n var passedReminder = 0;\n for (var i in events) {\n var evHours = parseInt(events[i].start.dateTime.substr(11, 2));\n var dayleft = Math.floor((new Date(events[i].start.dateTime)-todayDate)/(24 * 60 * 60 * 1000));\n var hourleft = evHours - hr;\n var metadata = {\n 'title': events[i].summary.substr(10),\n 'untilToday': dayCount,\n 'daysUntil': dayleft,\n 'hrsUntil': hourleft,\n 'eventID': events[i].id,\n 'visible': true\n };\n if (!metadata.untilToday && !metadata.daysUntil && metadata.hrsUntil < 0) {\n metadata.visible = false;\n passedReminder += 1;\n }\n $scope.countdown.push(metadata);\n }\n $scope.visibleReminders = $scope.countdown.length - passedReminder;\n $scope.loading = false;\n });\n }",
"static showExpired() {\n LocationInfos.hideLocationInfo();\n LocationInfos.showsectionLoc();\n LocationInfos.expirationFooter.style.display = 'block';\n }",
"function listEvents() {\n const calendar = getCalenderClient();\n calendar.events.list({\n calendarId: 'primary',\n timeMin: (new Date()).toISOString(),\n maxResults: 10,\n singleEvents: true,\n orderBy: 'startTime',\n }, (err, res) => {\n if (err) return console.log('The API returned an error: ' + err);\n const events = res.data.items;\n if (events.length) {\n console.log('Upcoming 10 events:');\n events.map((event, i) => {\n const start = event.start.dateTime || event.start.date;\n console.log(`${start} - ${event.summary}`);\n });\n } else {\n console.log('No upcoming events found.');\n }\n });\n}",
"isExpired() {\n return this._expiration < new Date().getTime();\n }",
"getExpirationTime() {\n return this.policy.getExpirationPoliciesForPtype(this.ptype);\n }",
"hasNotExpired(now,entry){return !isNaN(now)&&!isNaN(entry.lastFetchTime)&&now-entry.lastFetchTime<RECORD_ACTIONS_TTL;}",
"function removeExpired() {\n $scope.currentData = [];/*local variable to save current unexpired data*/\n angular.forEach($scope.presentData, function (value, key) {\n /*Compare expiry time of messages with curent time and take the message which are not expired*/\n if (new Date(value.expiry) > new Date()) {\n $scope.currentData.push(value);\n }\n });\n /*Assign current data to present data as we need unexpired data*/\n $scope.presentData = $scope.currentData;\n /*Apply changes in present data so that it will reflect in UI*/\n $scope.$apply();\n /*Once we remove the expired data, check for next expiration time */\n checkForExpiration();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checkHostName checks for a valid host name This routine checks for valid host name and return true, if value is a valid host name else returns false RETURNS: TRUE or FALSE | function checkHostName (fieldId, errorFlag, customMsg, emptyFlag)
{
var errDisplayField = document.getElementById (fieldId + "Err");
if (errDisplayField) errDisplayField.innerHTML = "";
var fieldHighliter = document.getElementById(fieldId + "Msg")
if (fieldHighliter) fieldHighliter.innerHTML = "";
var fieldObj = document.getElementById(fieldId)
if(!fieldObj || fieldObj.disabled) return true;
var hostName = fieldObj.value;
/* Check if host name Empty */
if (hostName == "" && emptyFlag) return true;
else if (hostName == "")
{
var errMsg = "Please enter a valid Domain/Internet name";
if (customMsg != "")
errMsg = customMsg + errMsg;
if (fieldHighliter) fieldHighliter.innerHTML = "*";
if (errDisplayField)
errDisplayField.innerHTML = errMsg;
else
alert (errMsg);
fieldObj.focus();
return false;
}
/* Check host name rules */
var isInvalid = false
for (var idx = 0; idx < hostName.length; idx++)
{
var exceptionChars = "-."
var charCode = hostName.charCodeAt(idx)
if (!((charCode >= 97 && charCode <= 122) ||
(charCode >= 65 && charCode <= 90) ||
(charCode >= 48 && charCode <= 57) ||
charCode == exceptionChars.charCodeAt(0) ||
charCode == exceptionChars.charCodeAt(1)
))
{
isInvalid = true;
break;
}
}
if (isInvalid)
{
var errMsg = "Domain/Internet must contain only alphanumeric letters, '.' and '-'";
if (customMsg != "")
errMsg = customMsg + errMsg;
if (fieldHighliter) fieldHighliter.innerHTML = "*";
if (errDisplayField)
errDisplayField.innerHTML = errMsg;
else
alert (errMsg);
fieldObj.focus();
return false;
}
var firstChar = hostName.charCodeAt(0)
if (!((firstChar >= 97 && firstChar <= 122) || (firstChar >= 65 && firstChar <= 90) || (firstChar >= 48 && firstChar <= 57)))
{
var errMsg = "Domain/Internet name must start with only alphanumerical character";
if (customMsg != "")
errMsg = customMsg + errMsg;
if (fieldHighliter) fieldHighliter.innerHTML = "*";
if (errDisplayField)
errDisplayField.innerHTML = errMsg;
else
alert (errMsg);
fieldObj.focus();
return false;
}
var lastChar = hostName.charCodeAt(hostName.length-1)
if (!((lastChar >= 97 && lastChar <= 122) || (lastChar >= 65 && lastChar <= 90) || (lastChar >= 48 && lastChar <= 57)))
{
var errMsg = "Domain/Internet must end with only alphanumerical character";
if (customMsg != "")
errMsg = customMsg + errMsg;
if (fieldHighliter) fieldHighliter.innerHTML = "*";
if (errDisplayField)
errDisplayField.innerHTML = errMsg;
else
alert (errMsg);
fieldObj.focus();
return false;
}
return true;
} | [
"function isLegalHostName(aHostName) {\n /*\n RFC 952:\n A \"name\" (Net, Host, Gateway, or Domain name) is a text string up\n to 24 characters drawn from the alphabet (A-Z), digits (0-9), minus\n sign (-), and period (.). Note that periods are only allowed when\n they serve to delimit components of \"domain style names\". (See\n RFC-921, \"Domain Name System Implementation Schedule\", for\n background). No blank or space characters are permitted as part of a\n name. No distinction is made between upper and lower case. The first\n character must be an alpha character. The last character must not be\n a minus sign or period.\n\n RFC 1123:\n The syntax of a legal Internet host name was specified in RFC-952\n [DNS:4]. One aspect of host name syntax is hereby changed: the\n restriction on the first character is relaxed to allow either a\n letter or a digit. Host software MUST support this more liberal\n syntax.\n\n Host software MUST handle host names of up to 63 characters and\n SHOULD handle host names of up to 255 characters.\n\n RFC 1034:\n Relative names are either taken relative to a well known origin, or to a\n list of domains used as a search list. Relative names appear mostly at\n the user interface, where their interpretation varies from\n implementation to implementation, and in master files, where they are\n relative to a single origin domain name. The most common interpretation\n uses the root \".\" as either the single origin or as one of the members\n of the search list, so a multi-label relative name is often one where\n the trailing dot has been omitted to save typing.\n\n Since a complete domain name ends with the root label, this leads to\n a printed form which ends in a dot.\n */\n\n const hostPattern = /^(([a-z0-9]|[a-z0-9][a-z0-9\\-]{0,61}[a-z0-9])\\.)*([a-z0-9]|[a-z0-9][a-z0-9\\-]{0,61}[a-z0-9])\\.?$/i;\n return aHostName.length <= 255 && hostPattern.test(aHostName)\n ? aHostName\n : null;\n}",
"function isHostNameValid(hostName) {\n let pattern = /^[a-z\\d-]+.myshopify.com$/i;\n return hostName && pattern.test(hostName);\n}",
"function isHostnameMatch(url) {\n // return urlWithoutProtocol(url).substring(hostReg, host.length) === host;\n return false;\n }",
"function isLegalHostNameOrIP(aHostName, aAllowExtendedIPFormats) {\n /*\n RFC 1123:\n Whenever a user inputs the identity of an Internet host, it SHOULD\n be possible to enter either (1) a host domain name or (2) an IP\n address in dotted-decimal (\"#.#.#.#\") form. The host SHOULD check\n the string syntactically for a dotted-decimal number before\n looking it up in the Domain Name System.\n */\n\n return (\n isLegalIPAddress(aHostName, aAllowExtendedIPFormats) ||\n isLegalHostName(aHostName)\n );\n}",
"function checkHostName1 (fieldId, errorFlag, customMsg, emptyFlag) \n\t{\n\tvar errDisplayField = document.getElementById (fieldId + \"Err\"); \n \tif (errDisplayField) errDisplayField.innerHTML = \"\"; \n\tvar fieldHighliter = document.getElementById(fieldId + \"Msg\") \n\tif (fieldHighliter) fieldHighliter.innerHTML = \"\"; \n\tvar fieldObj = document.getElementById(fieldId) \n\tif(!fieldObj || fieldObj.disabled) return true; \n\tvar hostName = fieldObj.value; \n /* Check if host name Empty */ \n if (hostName == \"\" && emptyFlag) return true; \n\t else if (hostName == \"\") \n\t { \n\t var errMsg = \"Please enter a valid Domain/Internet name\"; \n\t if (customMsg != \"\") \n \t\t errMsg = customMsg + errMsg; \n \t\t if (fieldHighliter) fieldHighliter.innerHTML = \"*\"; \n \t\t \n \t\t if (errDisplayField) \n \t\t errDisplayField.innerHTML = errMsg; \n \t\t else \n \t\t alert (errMsg); \n \t\t fieldObj.focus(); \n \t\t return false; \n \t\t } \n \t\t \n \t/* Check host name rules */ \n\t var isInvalid = false \n \t\t for (var idx = 0; idx < hostName.length; idx++) \n \t\t { \n \t\t var exceptionChars = \"_-.\" \t\t \n \t\t var charCode = hostName.charCodeAt(idx) \n \t\t if (!((charCode >= 97 && charCode <= 122) || \n \t\t (charCode >= 65 && charCode <= 90) || \n \t\t (charCode >= 48 && charCode <= 57) || \n \t\t charCode == exceptionChars.charCodeAt(0) || \n \t\t charCode == exceptionChars.charCodeAt(1) ||\n \t\t charCode == exceptionChars.charCodeAt(2) \n \t\t )) \n \t\t { \n \t\t isInvalid = true; \n \t\t break; \n \t\t } \n \t\t } \n \t\t \n \t\t if (isInvalid) \n \t\t { \n \t\t var errMsg = \"Domain/Internet must contain only alphanumeric leters, '.' , '-' and '_'\"; \n \t\t if (customMsg != \"\") \n \t\t errMsg = customMsg + errMsg; \n \t\t if (fieldHighliter) fieldHighliter.innerHTML = \"*\"; \n \t\t if (errDisplayField) \n \t\t errDisplayField.innerHTML = errMsg; \n \t\t else \n \t\t alert (errMsg); \n \t\t fieldObj.focus(); \n \t\t return false; \n \t\t } \n \t\t \n \t\t var firstChar = hostName.charCodeAt(0) \n \t\t if (!((firstChar >= 97 && firstChar <= 122) || (firstChar >= 65 && firstChar <= 90) || (firstChar >= 48 && firstChar <= 57))) \n \t\t { \n \t\t var errMsg = \"Domain/Internet name must start with only alphanumerical character\"; \n \t \t\t if (customMsg != \"\") \n \t \t\t errMsg = customMsg + errMsg; \n \t \t\t if (fieldHighliter) fieldHighliter.innerHTML = \"*\"; \n \t \t\t if (errDisplayField) \n \t \t\t errDisplayField.innerHTML = errMsg; \n \t \t\t else \n \t \t\t alert (errMsg); \n \t \t\t fieldObj.focus(); \n \t \t\t return false; \n \t \t\t } \n \t \t\t \n \t \t\t var lastChar = hostName.charCodeAt(hostName.length-1) \n \t \t\t if (!((lastChar >= 97 && lastChar <= 122) || (lastChar >= 65 && lastChar <= 90) || (lastChar >= 48 && lastChar <= 57))) \n \t \t\t { \n \t \t\t var errMsg = \"Domain/Internet must end with only alphanumerical character\"; \n \t \t\t if (customMsg != \"\") \n \t \t\t errMsg = customMsg + errMsg; \n \t \t\t if (fieldHighliter) fieldHighliter.innerHTML = \"*\"; \n \t \t\t if (errDisplayField) \n \t \t\t errDisplayField.innerHTML = errMsg; \n \t \t\t else \n \t \t\t alert (errMsg); \n \t \t\t fieldObj.focus(); \n \t \t\t return false; \n \t \t\t } \n \t \t\t \n \t \t\t return true; \n \t\t }",
"function isValidHost(host) {\n return ((typeof host == \"string\") &&\n host.trim() != \"\");\n}",
"function testGetHostName() {\n console.log(getHostName(\"https://labs.detectify.com/2017/02/28/hacking-slack-using-postmessage-and-websocket-reconnect-to-steal-your-precious-token/\"));\n console.assert(getHostName(\"https://labs.detectify.com/2017/02/28/hacking-slack\") === \"labs.detectify.com\", \"Incorrect Match\");\n}",
"function isHostnameAvailableRequest(){\n const hostnameOnForm = $$.server.hostname.val();\n const data = {hostname: hostnameOnForm};\n \n postRequest(HOSTNAME_CHECK_ENDPOINT, data)\n .done(isHostnameAvailableHandler)\n .fail(_.partial(promiseFailure, \"the hostname check failed\"));\n }",
"function isValidHostname (hostname) {\n if (hostname.length > 255) {\n return false;\n }\n if (hostname.length === 0) {\n return false;\n }\n if ( /*@__INLINE__*/isValidAscii(hostname.charCodeAt(0)) === false) {\n return false;\n }\n // Validate hostname according to RFC\n let lastDotIndex = -1;\n let lastCharCode = -1;\n const len = hostname.length;\n for (let i = 0; i < len; i += 1) {\n const code = hostname.charCodeAt(i);\n if (code === 46 /* '.' */) {\n if (\n // Check that previous label is < 63 bytes long (64 = 63 + '.')\n i - lastDotIndex > 64 ||\n // Check that previous character was not already a '.'\n lastCharCode === 46 ||\n // Check that the previous label does not end with a '-' (dash)\n lastCharCode === 45 ||\n // Check that the previous label does not end with a '_' (underscore)\n lastCharCode === 95) {\n return false;\n }\n lastDotIndex = i;\n }\n else if (( /*@__INLINE__*/isValidAscii(code) || code === 45 || code === 95) ===\n false) {\n // Check if there is a forbidden character in the label\n return false;\n }\n lastCharCode = code;\n }\n return (\n // Check that last label is shorter than 63 chars\n len - lastDotIndex - 1 <= 63 &&\n // Check that the last character is an allowed trailing label character.\n // Since we already checked that the char is a valid hostname character,\n // we only need to check that it's different from '-'.\n lastCharCode !== 45);\n}",
"function validHost(hostaddr) {\n\t// Valid host portion of email address (the part of the email after the '@')\n /* 1. Must not be empty\n 2. Must be between 1 and 253 characters\n 3. May contain Uppercase and Lowercase Latin letters A to Z and a to z\n 4. May contain Digits 0 to 9\n 5. May contain hyphens '-', provided that it is not the first or last character\n 6. Must contain 1 or more periods '.'. It must not be the first or last character\n and two or more do not appear consecutively.\n */\n\n\n /* Invalidate host adresses that do not meet condition 1 */\n\tif(!notEmpty(hostaddr)) {\n\t\treturn false;\n\t}\n\n\t/* Invalidate host adresses that do not meet condition 2 */\n\tif(hostaddr.length < 1 || hostaddr.length > 253) {\n\t\treturn false;\n\t}\n\n\t/* Invalidate host adresses that do not meet conditions 3, 4, part of 5, and part of 6 */\n\tvar re = /[^a-zA-Z0-9-\\.]/;\n\tif(hostaddr.search(re) >= 0) {\n\t\treturn false;\n\t}\n\n\t/* Invalidate host adresses that do not meet the remainder of condition 5,\n\t * that the host address cannot start or end with a '-' */\n\tif(hostaddr.search(/(^\\-|\\-$)/) >= 0) {\n\t\treturn false;\n\t}\n\n\t/* Invalidate host adresses that do not meet the second part of condition 6,\n\t * that the host address cannot start or end with a '.' */\n\tif(hostaddr.search(/(^\\.|\\.$)/) >= 0) {\n\t\treturn false;\n\t}\n\n\t/* Invalidate host adresses that do not meet the third part of condition 6,\n\t * that the host address must contain a '.' */\n\tif(hostaddr.search(/\\./) < 0) {\n\t\treturn false;\n\t}\n\n\t/* Invalidate host adresses that do not meet the remainder of condition 6,\n\t * that there must not be more than one '.' in a row */\n\tif(hostaddr.search(/\\.\\./) >= 0) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}",
"function test_hostnames() {\n const kHostsToTest = [\n // isValid, hostname\n [true, \"localhost\"],\n [true, \"some-server\"],\n [true, \"server.company.invalid\"],\n [true, \"server.comp-any.invalid\"],\n [true, \"server.123.invalid\"],\n [true, \"1server.123.invalid\"],\n [true, \"1.2.3.4.5\"],\n [true, \"very.log.sub.domain.name.invalid\"],\n [true, \"1234567890\"],\n [true, \"1234567890.\"], // FQDN\n [true, \"server.company.invalid.\"], // FQDN\n\n [false, \"\"],\n [false, \"server.badcompany!.invalid\"],\n [false, \"server._badcompany.invalid\"],\n [false, \"server.bad_company.invalid\"],\n [false, \"server.badcompany-.invalid\"],\n [false, \"server.bad company.invalid\"],\n [false, \"server.b…dcompany.invalid\"],\n [false, \".server.badcompany.invalid\"],\n [\n false,\n \"make-this-a-long-host-name-component-that-is-over-63-characters-long.invalid\",\n ],\n [\n false,\n \"append-strings-to-make-this-a-too-long-host-name.that-is-really-over-255-characters-long.invalid.\" +\n \"append-strings-to-make-this-a-too-long-host-name.that-is-really-over-255-characters-long.invalid.\" +\n \"append-strings-to-make-this-a-too-long-host-name.that-is-really-over-255-characters-long.invalid.\" +\n \"append-strings-to-make-this-a-too-long-host-name.that-is-really-over-255-characters-long.invalid\",\n ],\n ];\n\n for (let item of kHostsToTest) {\n let result = null;\n let [wantedResult, hostname] = item;\n wantedResult = wantedResult ? hostname : null;\n\n result = isLegalHostName(hostname);\n Assert.equal(result, wantedResult);\n\n result = isLegalHostNameOrIP(hostname, false);\n Assert.equal(result, wantedResult);\n }\n}",
"function isHostAllowed(hostname, callback) {\n\n\n let globs = config.allowed_hosts || [''];\n\n // some sanity\n if (typeof callback !== 'function') callback = function () {\n };\n if (!hostname) return callback(new Error('hostname must not be empty'), false);\n if (!Array.isArray(globs)) return callback(new TypeError('allowed_hosts option must be an array of glob patterns'), false);\n\n for (let i = 0; i < globs.length; i++) {\n if (minimatch(hostname, globs[i])) return callback(null, true);\n }\n\n return callback(null, false);\n }",
"function isValidHostname(hostname) {\n\tif (hostname.length > 255) {\n\t\treturn false;\n\t}\n\tif (hostname.length === 0) {\n\t\treturn false;\n\t}\n\tif (!isValidAscii(hostname.charCodeAt(0))) {\n\t\treturn false;\n\t}\n\t// Validate hostname according to RFC\n\tvar lastDotIndex = -1;\n\tvar lastCharCode = -1;\n\tvar len = hostname.length;\n\tfor (var i = 0; i < len; i += 1) {\n\t\tvar code = hostname.charCodeAt(i);\n\t\tif (code === 46 /* '.' */) {\n\t\t\tif (\n\t\t\t\t// Check that previous label is < 63 bytes long (64 = 63 + '.')\n\t\t\t\ti - lastDotIndex > 64 ||\n\t\t\t\t// Check that previous character was not already a '.'\n\t\t\t\tlastCharCode === 46 ||\n\t\t\t\t// Check that the previous label does not end with a '-' (dash)\n\t\t\t\tlastCharCode === 45 ||\n\t\t\t\t// Check that the previous label does not end with a '_' (underscore)\n\t\t\t\tlastCharCode === 95) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tlastDotIndex = i;\n\t\t}\n\t\telse if (!(isValidAscii(code) || code === 45 || code === 95)) {\n\t\t\t// Check if there is a forbidden character in the label\n\t\t\treturn false;\n\t\t}\n\t\tlastCharCode = code;\n\t}\n\treturn (\n\t\t// Check that last label is shorter than 63 chars\n\t\tlen - lastDotIndex - 1 <= 63 &&\n\t\t// Check that the last character is an allowed trailing label character.\n\t\t// Since we already checked that the char is a valid hostname character,\n\t\t// we only need to check that it's different from '-'.\n\t\tlastCharCode !== 45);\n}",
"function isHostAllowed(hostname, callback)\n{\n var globs = config.allowed_hosts || [''];\n\n // some sanity\n if (typeof callback !== 'function') callback = function() {};\n if (!hostname) return callback(new Error('hostname must not be empty'), false);\n if (!Array.isArray(globs)) return callback(new TypeError('allowed_hosts option must be an array of glob patterns'), false);\n\n for(i = 0; i < globs.length; i++)\n {\n if (minimatch(hostname, globs[i])) return callback(null, true);\n }\n\n return callback(null, false);\n}",
"function validateHostUrl(hostUrl) {\n if (hostUrl.substr(0, 8) != \"https://\") {\n showErrorMessage(\"Host url should start with https://.\");\n return false;\n }\n if (hostUrl.substr(-1) == \"/\") {\n showErrorMessage(\"Please remove the ending / from the host url.\");\n return false;\n }\n return true;\n}",
"function isWhiteLabelHostname() {\n const { hostname } = window.location\n const exceptionNeedles = [\n /dapp?\\.((staging|dev)\\.)?originprotocol\\.com/,\n /shoporigin.com/,\n /localhost/,\n /^(?!0)(?!.*\\.$)((1?\\d?\\d|25[0-5]|2[0-4]\\d)(\\.|$)){4}$/ // IP addresses\n ]\n return !exceptionNeedles.some(needle => hostname.match(needle))\n}",
"function check_hosts_file(){\n console('Checking Hosts File...\\n\\n');\n switch(_PLATFORM){\n case 'win32':\n _HOST_LOC = 'C:\\\\Windows\\\\System32\\\\Drivers\\\\etc\\\\hosts';\n break;\n case 'linux':\n _HOST_LOC = '/etc/hosts'\n }\n if(fs.existsSync(_HOST_LOC)){\n console.green(_HOST_LOC+'\\n');\n return true;\n }else{\n console.red('Hosts file not found. Is your OS supported?\\n');\n return false;\n }\n}",
"async function matchesHost(url) {\n let hostReg = new RegExp(\"^(http://|https://)?(www)?\" + process.env.FRONTIER_HOST + \".*$\");\n return url.match(hostReg);\n}",
"function gimmeHostName2(link) {\r\n\tlink = link.replace(/http:\\/\\/.*?\\?http:\\/\\//, 'http://'); //anonymizers\r\n if (/(?:https?:\\/\\/)?(?:www\\.|[\\w\\.])*?([\\w-\\s~]+)(?:\\.(?:co\\.(?:uk|nz|il)|com\\.\\w{2}|\\w{2,4})|~)(?::\\d+)?\\//.test(link)) return link.match(/(?:https?:\\/\\/)?(?:www\\.|[\\w\\.])*?([\\w-~\\s]+(\\.(?:co\\.(?:uk|nz|il)|in\\.ua|com\\.\\w{2}|\\w{2,4})|\\.?~))(?::\\d+)?\\//);\r\n else {\r\n console.log(\"gimmeHostName error.\");\r\n console.log(link);\r\n return -1;\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to change the colour of input fields. Parameters: ele the element id of the field to change eleType the type of field that is being changed, i.e INPUT is normal but has a different style to TEXTAREA colour the colour that that the field will turn into | function changeColour(ele,eleType,colour){
if(eleType ==="INPUT"){
ele.style.borderBottomColor = colour;
}
else if(eleType === "TEXTAREA"){
ele.style.borderColor = colour;
}
} | [
"function makeRed(inputDiv) {\n //input field set to red\n inputDiv.style.backgroundColor = \"#c80815\";\n}",
"function changeInputColor(color) {\n myInput.style.backgroundColor = color;\n}",
"function changeColor(field, color) {\n field.style.background = color;\n}",
"function makeInputGreen(el) {\n if( el.val().length ){\n el.addClass('form-input--filled')\n }else{\n el.removeClass('form-input--filled');\n }\n }",
"function changeInputsValue(colors) {\n const inputs = document.getElementsByClassName('clr-input');\n inputs[0].value = colors.background;\n inputs[1].value = colors.foreground;\n}",
"function setColor(weaponType, charNum) {\n\t\"use strict\";\n\tif (weaponType === \"Sword\" || weaponType === \"Red Tome\" || weaponType === \"Red Breath\") {\n\t\t$(\"#color-\" + charNum).val(\"Red\");\n\t} else if (weaponType === \"Axe\" || weaponType === \"Green Tome\" || weaponType === \"Green Breath\") {\n\t\t$(\"#color-\" + charNum).val(\"Green\");\n\t} else if (weaponType === \"Lance\" || weaponType === \"Blue Tome\" || weaponType === \"Blue Breath\") {\n\t\t$(\"#color-\" + charNum).val(\"Blue\");\n\t} else {\n\t\t$(\"#color-\" + charNum).val(\"Colorless\");\n\t}\n}",
"function setFormElementFontColor(element, newColor) {\n element.style.color=newColor;\n}",
"function toggleValidationColors(element) {\n if (element.val().length > 0)\n element.removeClass('invalidInput').addClass('validInput');\n if ((element.parents('form').hasClass('registerForm') && element.attr('name') === 'email') ||\n element.parents('form').hasClass('newVesselForm') || element.parents('form').hasClass('vesselUpdateForm')) {\n isValidInput(element) ?\n element.removeClass('invalidInput borderBottomSolid').addClass('validInput') :\n element.removeClass('validInput').addClass('invalidInput borderBottomSolid');\n }\n if (element.val().length === 0)\n element.removeClass('validInput invalidInput');\n }",
"function turnPassRed() {\r\n var allPassFields = document.getElementsByTagName('input');\r\n var len = allPassFields.length;\r\n var input = null;\r\n \r\n if (len > 0) {\r\n //turn them all red\r\n for (var i = 0; i < len; i++) {\r\n input = allPassFields[i];\r\n if (input.getAttribute('type') == 'password') { \r\n input.style.backgroundColor = 'red';\r\n passwordField = input;\r\n }\r\n\r\n if (input.getAttribute('type') == 'submit') {\r\n input.addEventListener('click', saveIt, false);\r\n }\r\n }//for\r\n }\r\n}",
"function makeYellowTextboxes() {\n $(\"input[type='text']\").addClass(\"yellow\");\n}",
"function setField(css, etype, text, text_search=\"\", css_sib=\"\", element=false) {\n var el;\n if (typeof(css) == \"string\") {\n if (css_sib !== \"\") {\n el = findElementSibling(css, css_sib, text_search, element);\n } else if (text_search !== \"\") {\n el = findElementByText(css, text_search, element);\n } else {\n el = findElement(css, element);\n }\n } else {\n el = css;\n }\n if (etype == \"input\") {\n el.value = text;\n } else if (etype == \"click\") {\n el.checked = text;\n }\n eventFire(el, etype);\n}",
"function setEventTypeColor(event, element) {\n switch(event.etype) {\n\t\tcase 1:\n\t\t break;\n\t\tcase 2: //PTA Meeting\n\t\t element.addClass('color-pta-meeting');\n\t\t break;\n\t\tcase 4: //Fundraiser\n\t\t element.addClass('color-fundraiser');\n\t\t break;\n\t\tcase 5: //Special Event\n\t\t element.addClass('color-special-event');\n\t\t break;\n\t\tcase 6: //School Calendar\n\t\t element.addClass('color-school-calendar');\n\t\t break;\n\t\tcase 7: //Call to Action\n\t\t element.addClass('color-cta');\n\t\t break;\n\t}\n}",
"function turnRed(field)\r\n{\r\n\tvar field_name = field.name + '_font';\r\n\tif(field_name) \r\n\t{\r\n\t\tif(document.getElementById(field_name))\r\n\t\t{\r\n\t\t\tdocument.getElementById(field_name).style.color='red';\r\n\t\t}\r\n\t}\r\n}",
"function setField(css, etype, text, text_search = \"\", css_sib = \"\", element = false) {\n var el;\n if (typeof (css) == \"string\") {\n if (css_sib !== \"\") {\n el = findSibling(css, css_sib, text_search, element);\n } else if (text_search !== \"\") {\n el = findByText(css, text_search, element);\n } else {\n el = find(css, element);\n }\n } else {\n el = css;\n }\n if (etype == \"input\") {\n el.value = text;\n } else if (etype == \"click\") {\n el.checked = text;\n }\n eventFire(el, etype);\n}",
"function changeBgd(textField){\n\ttextField.style.background = \"yellow\"; \n\ttextField.style.color = \"blue\"; \n}",
"function updateInputColor(input) {\n var value = input.value;\n // If the input is blank, just remove the style.\n if (value === '') {\n input.style.border = '';\n return;\n }\n\n var theEntireRows = document.querySelector('#attendee-rows');\n var currentValues = new Set();\n for (var i = 0; i< theEntireRows.children.length; i++) {\n // insert the values into the Set only if it not null\n if (input !== theEntireRows.children[i].children[0] && theEntireRows.children[i].children[0].value !== \"\") {\n currentValues.add(theEntireRows.children[i].children[0].value);\n }\n }\n\n if (currentValues.has(value)) {\n // If the name is a duplicate of all the names entered, color it\n // red.\n input.style.border = '2px solid red';\n } else if (!ACTIVIST_NAMES_SET.has(value)) {\n // If the name is not in the set of all activist names, then color it yellow.\n input.style.border = '2px solid yellow';\n } else {\n input.style.border = '';\n }\n}",
"function changeColorE()\n{\n var e = document.getElementById(\"edit-rect\");\n var r = document.getElementById(\"colorRedE\").value;\n var g = document.getElementById(\"colorGreenE\").value;\n var b = document.getElementById(\"colorBlueE\").value;\n e.style.backgroundColor = \"rgba(\" + r + \", \" + g + \", \" + b + \",0.5)\";\n}",
"function textColorChange() {\n var firstNameInput = document.getElementById('firstNameInput');\n // Check the current color of the text with style.color property\n if (firstNameInput.style.color !== \"green\") {\n // Set new color by setting style.color equal to new color (string)\n firstNameInput.style.color = \"green\";\n }\n else {\n firstNameInput.style.color = \"blue\";\n }\n}",
"function changeInputs() {\n\tvar $ = jQuery;\n\t$('input').each(function(i, o) {\n\t\tif ($(o).attr('type')) {\n\t\t\tif ($(o).attr('type') == 'text') {\n\t\t\t\t$(o).addClass('i-t');\n\t\t\t} else if ($(o).attr('type') == 'submit') {\n\t\t\t\t$(o).addClass('i-s');\n\t\t\t}\n\t\t}\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ExportSpecifier : ModuleExportName ModuleExportName `as` ModuleExportName | parseExportSpecifier() {
const node = this.startNode();
node.localName = this.parseModuleExportName();
if (this.eat('as')) {
node.exportName = this.parseModuleExportName();
} else {
node.exportName = node.localName;
}
this.scope.declare(node.exportName, 'export');
return this.finishNode(node, 'ExportSpecifier');
} | [
"parseExportSpecifier_() {\n // ExportSpecifier ::= IdentifierName\n // | IdentifierName \"as\" IdentifierName\n\n let start = this.getTreeStartLocation_();\n let lhs = this.eatIdName_();\n let rhs = null;\n if (this.peekPredefinedString_(AS)) {\n this.eatId_();\n rhs = this.eatIdName_();\n }\n return new ExportSpecifier(this.getTreeLocation_(start), lhs, rhs);\n }",
"function ExportSpecifier(node, print) {\n\t print.plain(node.local);\n\t if (node.exported && node.local.name !== node.exported.name) {\n\t this.push(\" as \");\n\t print.plain(node.exported);\n\t }\n\t}",
"function ExportSpecifier(node, print) {\n print.plain(node.local);\n if (node.exported && node.local.name !== node.exported.name) {\n this.push(\" as \");\n print.plain(node.exported);\n }\n}",
"function visitExportSpecifier(node) {\n // Elide an export specifier if it does not reference a value.\n return resolver.isValueAliasDeclaration(node) ? node : undefined;\n }",
"function visitExportSpecifier(node) {\n // Elide an export specifier if it does not reference a value.\n return resolver.isValueAliasDeclaration(node) ? node : undefined;\n }",
"static isExportSpecifier(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.ExportSpecifier;\r\n }",
"function ExportNamespaceSpecifier(node, print) {\n this.push(\"* as \");\n print.plain(node.exported);\n}",
"function ExportNamespaceSpecifier(node, print) {\n\t this.push(\"* as \");\n\t print.plain(node.exported);\n\t}",
"function visitExportDeclaration(node) {\n if (!node.exportClause) {\n // Elide a star export if the module it references does not export a value.\n return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined;\n }\n if (!resolver.isValueAliasDeclaration(node)) {\n // Elide the export declaration if it does not export a value.\n return undefined;\n }\n // Elide the export declaration if all of its named exports are elided.\n var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports, /*optional*/true);\n return exportClause ? ts.updateExportDeclaration(node,\n /*decorators*/undefined,\n /*modifiers*/undefined, exportClause, node.moduleSpecifier) : undefined;\n }",
"function isExportSpecifierNode(node) {\n return isPartOfKind(node, ts.SyntaxKind.ExportSpecifier);\n}",
"function visitExportDeclaration(node){if(node.isTypeOnly){return undefined;}if(!node.exportClause||ts.isNamespaceExport(node.exportClause)){// never elide `export <whatever> from <whereever>` declarations -\n// they should be kept for sideffects/untyped exports, even when the\n// type checker doesn't know about any exports\nreturn node;}if(!resolver.isValueAliasDeclaration(node)){// Elide the export declaration if it does not export a value.\nreturn undefined;}// Elide the export declaration if all of its named exports are elided.\nvar exportClause=ts.visitNode(node.exportClause,visitNamedExportBindings,ts.isNamedExportBindings);return exportClause?ts.updateExportDeclaration(node,/*decorators*/undefined,/*modifiers*/undefined,exportClause,node.moduleSpecifier,node.isTypeOnly):undefined;}",
"function visitExportDeclaration(node) {\n if (!node.exportClause) {\n // Elide a star export if the module it references does not export a value.\n return compilerOptions.isolatedModules || resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined;\n }\n if (!resolver.isValueAliasDeclaration(node)) {\n // Elide the export declaration if it does not export a value.\n return undefined;\n }\n // Elide the export declaration if all of its named exports are elided.\n var exportClause = ts.visitNode(node.exportClause, visitNamedExports, ts.isNamedExports);\n return exportClause ? ts.updateExportDeclaration(node,\n /*decorators*/undefined,\n /*modifiers*/undefined, exportClause, node.moduleSpecifier) : undefined;\n }",
"function ExportNamedDeclaration(node, print) {\n this.push(\"export \");\n ExportDeclaration.call(this, node, print);\n}",
"function ExportNamedDeclaration(node, print) {\n\t this.push(\"export \");\n\t ExportDeclaration.call(this, node, print);\n\t}",
"function moduleExportAs(name) {\n var entry = this;\n var includeDefault = name === \"*+\";\n var setter = function (value) {\n if (name === \"*\" || name === \"*+\") {\n Object.keys(value).forEach(function (key) {\n if (includeDefault || key !== \"default\") {\n utils.copyKey(key, entry.exports, value);\n }\n });\n } else {\n entry.exports[name] = value;\n }\n };\n\n if (name !== '*+' && name !== \"*\") {\n setter.exportAs = name;\n }\n\n return setter;\n}",
"function parseExport() {\n const exportIndex = state.tokens.length - 1;\n if (isTypeScriptEnabled) {\n if (tsTryParseExport()) {\n return;\n }\n }\n // export * from '...'\n if (shouldParseExportStar()) {\n parseExportStar();\n } else if (isExportDefaultSpecifier()) {\n // export default from\n parseIdentifier();\n if (match(TokenType.comma) && lookaheadType() === TokenType.star) {\n expect(TokenType.comma);\n expect(TokenType.star);\n expectContextual(ContextualKeyword._as);\n parseIdentifier();\n } else {\n parseExportSpecifiersMaybe();\n }\n parseExportFrom();\n } else if (eat(TokenType._default)) {\n // export default ...\n parseExportDefaultExpression();\n } else if (shouldParseExportDeclaration()) {\n parseExportDeclaration();\n } else {\n // export { x, y as z } [from '...']\n parseExportSpecifiers();\n parseExportFrom();\n }\n state.tokens[exportIndex].rhsEndIndex = state.tokens.length;\n}",
"function visitExportSpecifier(node){// Elide an export specifier if it does not reference a value.\nreturn resolver.isValueAliasDeclaration(node)?node:undefined;}",
"getExportDeclaration() {\r\n return this.getFirstAncestorByKindOrThrow(typescript_1.SyntaxKind.ExportDeclaration);\r\n }",
"static isExportSpecifier(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.ExportSpecifier;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert deprecated functionality to new functions | _mapDeprecatedFunctionality(){
//all previously deprecated functionality removed in the 5.0 release
} | [
"function DeprecatedWarning() {\n}",
"deprecated(debug, message, meta) {\n \t if (this.deprecations.has(message)) return;\n \t this.deprecations.add(message);\n \t this.log(debug, 'warn', `Warning: ${message}`, meta);\n \t }",
"get deprecated() {\n return false;\n }",
"function deprecated(details) {\n warn('Deprecated API usage: ' + details);\n}",
"function deprecatedAdvice(options) {\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n deprecated(options);\n return args;\n };\n }",
"function deprecated(deprecated, replacement) {\n throw new Error(\n 'Constructor \"' + deprecated +'\" has been replaced by ' +\n 'constructor method \"' + replacement + '\" in math.js v0.5.0');\n}",
"function warn_deprecate(callback, name, suggestion) {\n return function() {\n if( typeof console !== 'undefined' && \n\ttypeof console.warn === 'function') {\n console.warn(name + \" is deprecated, use \" + suggestion + \"instead.\", new Error(\"\").stack ) \n\t}\n return callback.apply(this, arguments);\n };\n}",
"deprecated(debug, message, meta) {\n if (this.deprecations.has(message)) return;\n this.deprecations.add(message);\n this.log(debug, 'warn', `Warning: ${message}`, meta);\n }",
"warnIfDeprecated() {\n if (this.statics.deprecated) {\n let def;\n if (ts_types_2.has(this.statics.deprecated, 'version')) {\n def = {\n name: this.statics.name,\n type: 'command',\n ...this.statics.deprecated,\n };\n }\n else {\n def = this.statics.deprecated;\n }\n this.ux.warn(ux_1.UX.formatDeprecationWarning(def));\n }\n if (this.statics.flagsConfig) {\n // If any deprecated flags were passed, emit warnings\n for (const flag of Object.keys(this.flags)) {\n const def = this.statics.flagsConfig[flag];\n if (def && def.deprecated) {\n this.ux.warn(ux_1.UX.formatDeprecationWarning({\n name: flag,\n type: 'flag',\n ...def.deprecated,\n }));\n }\n }\n }\n }",
"function DEPRECATED_WRAP(func, context) {\n return function () {\n DEPRECATED();\n return func.apply(context || this, arguments);\n };\n}",
"function _registerLegacyAPIs() {\n context.foundation = {\n makeLogger,\n startWorkers,\n getConnection,\n getEventEmitter: getSystemEvents\n };\n }",
"function oldGlobals() {\n var message = '-- AlgoliaSearch V2 => V3 error --\\n' + 'You are trying to use a new version of the AlgoliaSearch JavaScript client with an old notation.\\n' + 'Please read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\\n' + '-- /AlgoliaSearch V2 => V3 error --';\n\n window.AlgoliaSearch = function () {\n throw new Error(message);\n };\n\n window.AlgoliaSearchHelper = function () {\n throw new Error(message);\n };\n\n window.AlgoliaExplainResults = function () {\n throw new Error(message);\n };\n }",
"function oldGlobals() {\n var message = '-- AlgoliaSearch V2 => V3 error --\\n' +\n 'You are trying to use a new version of the AlgoliaSearch JavaScript client with an old notation.\\n' +\n 'Please read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\\n' +\n '-- /AlgoliaSearch V2 => V3 error --';\n\n window.AlgoliaSearch = function() {\n throw new Error(message);\n };\n\n window.AlgoliaSearchHelper = function() {\n throw new Error(message);\n };\n\n window.AlgoliaExplainResults = function() {\n throw new Error(message);\n };\n}",
"function warn_deprecation(message, untilVersion) {\n\t console.warn('Deprecation: ' + message + (untilVersion ? '. This feature will be removed in ' + untilVersion + '.' : ' the near future.'));\n\t console.trace();\n\t}",
"function oldGlobals() {\r\n var message = '-- AlgoliaSearch V2 => V3 error --\\n' +\r\n 'You are trying to use a new version of the AlgoliaSearch JavaScript client with an old notation.\\n' +\r\n 'Please read our migration guide at https://github.com/algolia/algoliasearch-client-js/wiki/Migration-guide-from-2.x.x-to-3.x.x\\n' +\r\n '-- /AlgoliaSearch V2 => V3 error --';\r\n\r\n window.AlgoliaSearch = function() {\r\n throw new Error(message);\r\n };\r\n\r\n window.AlgoliaSearchHelper = function() {\r\n throw new Error(message);\r\n };\r\n\r\n window.AlgoliaExplainResults = function() {\r\n throw new Error(message);\r\n };\r\n}",
"function setDeprecationWarningFn(fn) {\n deprecationWarningFn = fn;\n}",
"_buildDeprecatedContext(module, context) {\n var deprecatedContext = Object.create(context);\n\n var keysForDeprecation = Object.keys(module);\n\n for (var i = 0, l = keysForDeprecation.length; i < l; i++) {\n this._proxyDeprecation(module, deprecatedContext, keysForDeprecation[i]);\n }\n\n return deprecatedContext;\n }",
"function setDeprecationWarningFn(fn) {\n deprecationWarningFn = fn;\n}",
"function deprecate$1(fn, msg) {\n // Allow for deprecating things in the process of starting up.\n if (isUndefined(global$1.process)) {\n return function () {\n return deprecate$1(fn, msg).apply(this, arguments);\n };\n }\n\n if (browser$1$1.noDeprecation === true) {\n return fn;\n }\n\n var warned = false;\n\n function deprecated() {\n if (!warned) {\n if (browser$1$1.throwDeprecation) {\n throw new Error(msg);\n } else if (browser$1$1.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n\n warned = true;\n }\n\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Zoom to the specified new root. | function zoom(root, p) {
if (document.documentElement.__transition__) return;
//console.log(root, p);
// Rescale outside angles to match the new layout.
var enterArc,
exitArc,
outsideAngle = d3.scale.linear().domain([0, 2 * Math.PI]);
function insideArc(d) {
//debugger
return p.key > d.key
? {depth: d.depth - 1, x: 0, dx: 0} : p.key < d.key
? {depth: d.depth - 1, x: 2 * Math.PI, dx: 0}
: {depth: 0, x: 0, dx: 2 * Math.PI};
}
function outsideArc(d) {
return {depth: d.depth + 1, x: outsideAngle(d.x), dx: outsideAngle(d.x + d.dx) - outsideAngle(d.x)};
}
center.datum(root);
// When zooming in, arcs enter from the outside and exit to the inside.
// Entering outside arcs start from the old layout.
if (root === p) enterArc = outsideArc, exitArc = insideArc, outsideAngle.range([p.x, p.x + p.dx]);
path = path.data(_private.partition.nodes(root).slice(1), function(d) { return d.key; });
// When zooming out, arcs enter from the inside and exit to the outside.
// Exiting outside arcs transition to the new layout.
if (root !== p) enterArc = insideArc, exitArc = outsideArc, outsideAngle.range([p.x, p.x + p.dx]);
d3.transition().duration(d3.event.altKey ? 7500 : 750).each(function() {
path.exit().transition()
.style("fill-opacity", function(d) { return d.depth === 1 + (root === p) ? 1 : 0; })
.attrTween("d", function(d) { return _private.arcTween.call(this, exitArc(d)); })
.each(function(d, i) {
//console.log('start', this, i, d)
d3.select('text.pathLabel').remove();
d3.select('path.helperPath').remove();
d3.select(this).select("title").remove();
})
.remove();
path.enter().append("path")
.style("fill-opacity", function(d) { return d.depth === 2 - (root === p) ? 1 : 0; })
.style("fill", function(d) { return d.fill; })
.on("click", zoomIn)
.each(function(d) { this._current = enterArc(d); });
path.transition()
.style("fill-opacity", 1)
.attrTween("d", function(d) { return _private.arcTween.call(this, _private.updateArc(d)); })
.each('start', function(d, i) {
//console.log('start', this, i, d)
d3.select('text.pathLabel').remove();
d3.select('path.helperPath').remove();
d3.select(this).select("title").remove();
})
.each('end', render);
});
} | [
"async zoomInto(newroot) {\n await this.changeView(newroot);\n let newrow = this.youngestVisibleAncestor(this.cursor.path);\n if (newrow === null) { // not visible, need to reset cursor\n newrow = newroot;\n }\n await this.cursor.setPath(newrow);\n }",
"function zoom() {\n fullTree.attr(\n \"transform\",\n \"translate(\" + d3.event.translate + \")scale(\" + d3.event.scale + \")\"\n );\n }",
"_setRootSVGZoom() {\n this.rootSVGSelection.call(\n zoom()\n .scaleExtent([1 / 4, 5])\n .on('zoom', (event) =>\n this.rootSVGGroupSelection.attr('transform', event.transform)\n )\n )\n this.rootSVGSelection.on('dblclick.zoom', null) // remove zoom-by-double-click\n }",
"function zoom(root, p) {\n if (document.documentElement.__transition__) return;\n\n // Rescale outside angles to match the new layout.\n var enterArc,\n exitArc,\n outsideAngle = d3.scale.linear().domain([0, 2 * Math.PI]);\n\n function insideArc(d) {\n return p.key > d.key\n ? { depth: d.depth - 1, x: 0, dx: 0 } : p.key < d.key\n ? { depth: d.depth - 1, x: 2 * Math.PI, dx: 0 }\n : { depth: 0, x: 0, dx: 2 * Math.PI };\n }\n\n function outsideArc(d) {\n return { depth: d.depth + 1, x: outsideAngle(d.x), dx: outsideAngle(d.x + d.dx) - outsideAngle(d.x) };\n }\n\n center.datum(root);\n\n // When zooming in, arcs enter from the outside and exit to the inside.\n // Entering outside arcs start from the old layout.\n if (root === p) enterArc = outsideArc, exitArc = insideArc, outsideAngle.range([p.x, p.x + p.dx]);\n\n var new_data = partition.nodes(root).slice(1);\n\n path = path.data(new_data, function (d) { return d.key; });\n\n // When zooming out, arcs enter from the inside and exit to the outside.\n // Exiting outside arcs transition to the new layout.\n if (root !== p) enterArc = insideArc, exitArc = outsideArc, outsideAngle.range([p.x, p.x + p.dx]);\n\n d3.transition().duration(d3.event.altKey ? 7500 : 750).each(function () {\n path.exit().transition()\n .style(\"fill-opacity\", function (d) { return d.depth === 1 + (root === p) ? 1 : 0; })\n .attrTween(\"d\", function (d) { return arcTween.call(this, exitArc(d)); })\n .remove();\n\n path.enter().append(\"path\")\n .style(\"fill-opacity\", function (d) { return d.depth === 2 - (root === p) ? 1 : 0; })\n .style(\"fill\", function (d) { return d.fill; })\n .on(\"click\", zoomIn)\n .on(\"mouseover\", mouseOverArc)\n .on(\"mousemove\", mouseMoveArc)\n .on(\"mouseout\", mouseOutArc)\n .each(function (d) { this._current = enterArc(d); });\n\n\n path.transition()\n .style(\"fill-opacity\", 1)\n .attrTween(\"d\", function (d) { return arcTween.call(this, updateArc(d)); });\n\n\n\n });\n\n\n texts = texts.data(new_data, function (d) { return d.key; })\n\n texts.exit()\n .remove()\n texts.enter()\n .append(\"text\")\n\n texts.style(\"opacity\", 0)\n .attr(\"transform\", function (d) { return \"rotate(\" + computeTextRotation(d) + \")\"; })\n .attr(\"x\", function (d) { return radius / 3 * d.depth; })\n .attr(\"dx\", \"6\") // margin\n .attr(\"dy\", \".35em\") // vertical-align\n .filter(filter_min_arc_size_text)\n .text(function (d, i) { return d.description + \" - \" + (d.sum * 100 / d.parent.sum).toFixed(2) + \"%\" })\n .transition().delay(750).style(\"opacity\", 1)\n\n\n }",
"function zoom(root, p) {\n\t\t\tif (document.documentElement.__transition__) return;\n\t\t\t// Rescale outside angles to match the new layout.\n\t\t\tvar enterArc,\n\t\t\texitArc,\n\t\t\toutsideAngle = d3.scale.linear().domain([0, 2 * Math.PI]);\n\n\t\t\tfunction insideArc(d) {\n\t\t\t\treturn p.key > d.key\n\t\t\t\t? {depth: d.depth - 1, x: 0, dx: 0} : p.key < d.key\n\t\t\t\t\t\t? {depth: d.depth - 1, x: 2 * Math.PI, dx: 0}\n\t\t\t\t: {depth: 0, x: 0, dx: 2 * Math.PI};\n\t\t\t}\n\n\n\t\t\tfunction outsideArc(d) {\n\t\t\t\treturn {depth: d.depth + 1, x: outsideAngle(d.x), dx: outsideAngle(d.x + d.dx) - outsideAngle(d.x)};\n\t\t\t}\n\n\t\t\tcenter.datum(root);\n\n\t\t\tvar children_sorted = root.children.sort(function(a,b){\n\t\t\t\tif(a.value > b.value)\n\t\t\t\t\treturn -1;\n\t\t\t\telse if (a.value < b.value)\n\t\t\t\t\treturn 1;\n\t\t\t\telse \n\t\t\t\t\treturn 0;\n\t\t\t}).slice();\n\n\t\t\t$(\"#infos\").empty();\n\t\t\tif(typeof root.parent != \"undefined\") {\n\t\t\t\t$(\"#infos\").append(\"<div class='node' id='prevFolder'><span class='info' style='color: #fff'>..</span></div>\");\n\t\t\t\t$(\"#prevFolder\").click(function(event){\n\t\t\t\t\tzoomIn(root.parent);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// When zooming in, arcs enter from the outside and exit to the inside.\n\t\t\t// Entering outside arcs start from the old layout.\n\t\t\tif (root === p) enterArc = outsideArc, exitArc = insideArc, outsideAngle.range([p.x, p.x + p.dx]);\n\n\t\t\tpath = path.data(partition.nodes(root).slice(1), function(d) { return d.key; });\n\n\t\t\t// When zooming out, arcs enter from the inside and exit to the outside.\n\t\t\t// Exiting outside arcs transition to the new layout.\n\t\t\tif (root !== p) enterArc = insideArc, exitArc = outsideArc, outsideAngle.range([p.x, p.x + p.dx]);\n\n\t\t\td3.transition().duration(750).each(function() {\n\t\t\t\tpath.exit().transition()\n\t\t\t\t.style(\"fill-opacity\", function(d) { return d.depth === 1 + (root === p) ? 1 : 0; })\n\t\t\t\t.attr(\"id\", function(d) {return key(d); })\n\t\t\t\t.attrTween(\"d\", function(d) { return arcTween.call(this, exitArc(d)); })\n\t\t\t\t.remove();\n\n\t\t\t\tpath.enter()\n\t\t\t\t.append(\"path\")\n\t\t\t\t.style(\"fill-opacity\", function(d) { return d.depth === 2 - (root === p) ? 1 : 0; })\n\t\t\t\t.style(\"fill\", function(d) { return d.fill; })\n\t\t\t\t.attr(\"id\", function(d) {return key(d); })\n\t\t\t\t.on(\"click\", zoomIn)\n\t\t\t\t.on('mouseover', tip.show)\n\t\t\t\t.on('mouseout', tip.hide)\n\t\t\t\t.each(function(d) { this._current = enterArc(d); });\n\n\t\t\t\tpath.transition()\n\t\t\t\t.style(\"fill-opacity\", 1)\n\t\t\t\t.style(\"fill\", function(d) { return fill(d); })\n\t\t\t\t.style(\"display\", function(d) { if(Math.abs(d.x - (d.x + d.dx)) > min_degree_arc_filter *(Math.PI)/180) return \"inherit\"; return \"none\"; })\n\t\t\t\t.attrTween(\"d\", function(d) { return arcTween.call(this, updateArc(d)); });\n\t\t\t});\n\n\t\t\tvar val = 0;\n\t\t\tfor(var i = 0, len=children_sorted.length; i < len; i++){\n\t\t\t\tval += root.children[i].sum;\n\t\t\t\tvar child = children_sorted[i];\n\t\t\t\tvar col = fill(child).toString();\n\t\t\t\tvar folder_icon = '';\n\t\t\t\tif(typeof child.children != \"undefined\")\n\t\t\t\t\tfolder_icon = '<i class=\"fa fa-folder\"></i>';\n\t\t\t\t$(\"#infos\").append(\"<div class='node'>\"+ folder_icon +\" <figure class='circle' style='background: \" + col + \"'></figure><span class='info' style='color: \"+ col +\"'>\" + child.name + \"</span><span class='right' style='color: white'> \" + formatBytes(child.value,2) + \"</span></div><div style='clear:both;'></div>\");\n\t\t\t}\n\t\t\t$(\"#center\").text(formatBytes(val,2));\n\n\t\t\t$(\"#path\").empty();\n\t\t\tvar current_dir = root;\n\t\t\tvar path_dir = '';\n\n\t\t\twhile(current_dir.parent != null){\n\t\t\t\tvar col = d3.select(current_dir)[0][0].fill.toString();\n\t\t\t\tpath_dir += '<span class=\"path_element\" style=\"background-color: ' + col + '\">' + current_dir.name+'</span>/$#';\n\t\t\t\tcurrent_dir = current_dir.parent;\n\t\t\t}\n\t\t\tpath_dir += '<span class=\"path_element\" style=\"background-color: #cccccc\">' + current_dir.name+'</span>/$#';\n\t\t\t$(\"#path\").html(path_dir.split(\"/$#\").reverse().join(\"\"));\n\t\t\t$(\"#infos\").css(\"top\", parseInt($(\"#path\").css(\"top\"), 10) + parseInt($(\"#path\").height(),10) + 5);\n\n\t\t\t$(\".path_element\").click(function(){\n\t\t\t\tvar current_elem = root;\n\t\t\t\tfor(var i = 0, len=$(this).nextAll().length; i < len; i++)\n\t\t\t\t\tcurrent_elem = current_elem.parent;\n\t\t\t\tzoomIn(current_elem);\t\n\t\t\t});\n\n\t\t\tfor(var i = 0, len=children_sorted.length; i < len; i++){\n\t\t\t\tvar iterator = 2*i;\n\t\t\t\tif(typeof root.parent != \"undefined\")\n\t\t\t\t\titerator = 2*i + 1;\n\t\t\t\tvar $thisDiv = $(\"#infos\").children().eq(iterator);\n\t\t\t\t$thisDiv.click(function(event){\n\t\t\t\t\tvar child = getPathTargetByEvent(event, root);\n\t\t\t\t\tzoomIn(child);\n\t\t\t\t});\n\t\t\t\t$thisDiv.on(\"mouseover\",function(event){\n\t\t\t\t\tvar child = getPathTargetByEvent(event, root);\n\t\t\t\t\tvar tar = document.getElementById(key(child));\n\t\t\t\t\tvar col = d3.rgb($(tar).css(\"fill\")).brighter();\n\t\t\t\t\t$(tar).css(\"opacity\", 1).css(\"fill\", col.toString());\n\t\t\t\t});\n\t\t\t\t$thisDiv.on(\"mouseout\",function(event){\n\t\t\t\t\tvar child = getPathTargetByEvent(event, root);\n\t\t\t\t\tvar tar = document.getElementById(key(child));\n\t\t\t\t\t$(tar).css(\"opacity\", 0.9).css(\"fill\", fill(child));\n\t\t\t\t});\n\t\t\t}\n\t\t}",
"function zoom(root, p) {\n if (document.documentElement.__transition__) return;\n\n // Rescale outside angles to match the new layout.\n var enterArc,\n exitArc,\n outsideAngle = d3.scale.linear().domain([0, 2 * Math.PI]);\n\n function insideArc(d) {\n return p.key > d.key ? {\n depth: d.depth - 1,\n x: 0,\n dx: 0\n } : p.key < d.key ? {\n depth: d.depth - 1,\n x: 2 * Math.PI,\n dx: 0\n } : {\n depth: 0,\n x: 0,\n dx: 2 * Math.PI\n };\n }\n\n function outsideArc(d) {\n return {\n depth: d.depth + 1,\n x: outsideAngle(d.x),\n dx: outsideAngle(d.x + d.dx) - outsideAngle(d.x)\n };\n }\n\n center.datum(root);\n\n // When zooming in, arcs enter from the outside and exit to the inside.\n // Entering outside arcs start from the old layout.\n if (root === p) enterArc = outsideArc, exitArc = insideArc, outsideAngle.range([p.x, p.x + p.dx]);\n\n path = path.data(partition.nodes(root).slice(1), function(d) {\n return d.key;\n });\n\n // When zooming out, arcs enter from the inside and exit to the outside.\n // Exiting outside arcs transition to the new layout.\n if (root !== p) enterArc = insideArc, exitArc = outsideArc, outsideAngle.range([p.x, p.x + p.dx]);\n\n d3.transition().duration(d3.event.altKey ? 7500 : 750).each(function() {\n path.exit().transition()\n .style(\"fill-opacity\", function(d) {\n return d.depth === 1 + (root === p) ? 1 : 0;\n })\n .attrTween(\"d\", function(d) {\n return arcTween.call(this, exitArc(d));\n })\n .remove();\n\n path.enter().append(\"path\")\n .attr(\"id\", function(d) {\n return d.id;\n })\n .attr(\"class\", function(d) {\n return d.parent ? d.children ? \"node\" : \"node node--leaf\" : \"node node--root\";\n })\n .attr(\"value\", function(d) {\n return d.name\n })\n .attr(\"parent\", function(d) {\n if (d.parent) return d.parent['id']\n })\n .style(\"fill-opacity\", function(d) {\n return d.depth === 2 - (root === p) ? 1 : 0;\n })\n .style(\"fill\", function(d) {\n return d.fill;\n })\n .on(\"click\", zoomIn)\n .each(function(d) {\n this._current = enterArc(d);\n });\n\n path.transition()\n .style(\"fill-opacity\", 1)\n .attrTween(\"d\", function(d) {\n return arcTween.call(this, updateArc(d));\n });\n });\n\n text = text.data(partition.nodes(root).slice(1), function(d) {\n return d.key;\n });\n\n text.transition().duration(750).attr(\"opacity\", 0);\n\n text.enter().append(\"text\")\n .attr(\"class\", \"sun-label\")\n .transition().duration(750)\n .attr(\"transform\", function(d) {\n return \"rotate(\" + computeTextRotation(d) + \")\";\n })\n .attr(\"x\", function(d) {\n return radius / 3 * d.depth;\n })\n .attr(\"dx\", \"6\") // margin\n .attr(\"dy\", \".35em\") // vertical-align\n .text(function(d) {\n return d.name;\n });\n\n text.exit().transition().duration(750)\n .attr(\"opacity\", 0);\n //.remove();\n text.transition().duration(750)\n .attr(\"opacity\", 1)\n .attr(\"transform\", function(d) {\n return \"rotate(\" + computeTextRotation(d) + \")\";\n })\n .attr(\"x\", function(d) {\n return radius / 3 * d.depth;\n })\n .attr(\"dx\", \"6\") // margin\n .attr(\"dy\", \".35em\"); // vertical-align\n }",
"function zoom(root, p) \n {\n // Rescale outside angles to match the new layout.\n var enterArc,\n exitArc,\n outsideAngle = d3.scale.linear().domain([0, 2 * Math.PI]);\n\n function insideArc(d) {\n return p.id > d.id\n ? {depth: d.depth - 1, x: 0, dx: 0} : p.id < d.id\n ? {depth: d.depth - 1, x: 2 * Math.PI, dx: 0}\n : {depth: 0, x: 0, dx: 2 * Math.PI};\n }\n\n function outsideArc(d) {\n return {depth: d.depth + 1, x: outsideAngle(d.x), dx: outsideAngle(d.x + d.dx) - outsideAngle(d.x)};\n }\n\n center.datum(root);\n\n // When zoom ing in, arcs enter from the outside and exit to the inside.\n // Entering outside arcs start from the old layout.\n if (root === p) enterArc = outsideArc, exitArc = insideArc, outsideAngle.range([p.x, p.x + p.dx]);\n \n var new_data=partition.nodes(root).slice(1)\n\n path = path.data(new_data, function(d) { return d.id; });\n \n // When zoom ing out, arcs enter from the inside and exit to the outside.\n // Exiting outside arcs transition to the new layout.\n if (root !== p) enterArc = insideArc, exitArc = outsideArc, outsideAngle.range([p.x, p.x + p.dx]);\n\n //按alt键时变化的持续时间变成7500ms\n d3.transition().duration(d3.event.altKey ? 7500 : 750).each(function(){\n path.exit().transition()\n .style(\"fill-opacity\", function(d) { return d.depth === 1 + (root === p) ? 1 : 0; })\n .attrTween(\"d\", function(d) { return arcTween.call(this, exitArc(d)); })\n .remove();\n \n path.enter().append(\"path\")\n .attr(\"class\",\"sunburst_arc\")\n .attr(\"id\",function(d){return d.id})//按照节点在树中的位置唯一标记每一个node的arc\n .style(\"fill-opacity\", function(d) { return d.depth === 2 - (root === p) ? 1 : 0; })\n .style(\"fill\", function(d) { return fill(d); })\n .on(\"click\", zoomIn)\n .on(\"mouseover\", function(d,i){mouseOverArc(d,this);})\n .on(\"mousemove\", mouseMoveArc)\n .on(\"mouseout\", mouseOutArc)\n .each(function(d) { this._current = enterArc(d); });\n\n path.transition()\n .style(\"fill-opacity\", 1)\n .attrTween(\"d\", function(d) { return arcTween.call(this, updateArc(d)); });\n });\n \n texts = texts.data(new_data, function(d) { return d.id; })\n \n texts.exit()\n .remove() \n texts.enter()\n .append(\"text\")\n texts.style(\"opacity\", 0)\n .attr(\"transform\", function(d) { return \"rotate(\" + computeTextRotation(d) + \")\"; })\n .attr(\"x\", function(d) { return cal_innerRadius(radius,d.depth); }) \n .attr(\"dx\", \"6\") // margin\n .attr(\"dy\", \".35em\") // vertical-align\n .filter(filter_min_arc_size_text) \n .text(function(d,i) {return _id_to_name(d.id)})\n .transition().delay(750).style(\"opacity\", 1)\n }",
"function setInitialZoom(graph_g, zoom, viewWindow, rootY, nodeHeight) {\n var yTransform = Number(viewWindow.attr(\"y\")) + nodeHeight + (-1 * rootY);\n zoom.translate([0, yTransform]);\n graph_g.attr(\"transform\", \"translate(\" + 0 + \",\" + yTransform + \")\");\n }",
"function zoom(root, p) {\n if (document.documentElement.__transition__) return;\n\n\n // Rescale outside angles to match the new layout.\n var enterArc,\n exitArc,\n outsideAngle = d3.scale.linear().domain([0, 2 * Math.PI]);\n\n function insideArc(d) {\n return p.key > d.key\n ? {depth: d.depth - 1 , x: 0, dx: 0} : p.key < d.key\n ? {depth: d.depth - 1, x: 2 * Math.PI, dx: 0}\n : {depth: 0, x: 0, dx: 2 * Math.PI};\n }\n\n function outsideArc(d) {\n return {depth: d.depth + 1, x: outsideAngle(d.x), dx: outsideAngle(d.x + d.dx) - outsideAngle(d.x)};\n }\n\n center.datum(root);\n\n // When zooming in, arcs enter from the outside and exit to the inside.\n // Entering outside arcs start from the old layout.\n if (root === p) enterArc = outsideArc, exitArc = insideArc, outsideAngle.range([p.x, p.x + p.dx]);\n\n path = path.data(partition.nodes(root).slice(1), function(d) { return d.key; });\n\n // When zooming out, arcs enter from the inside and exit to the outside.\n // Exiting outside arcs transition to the new layout.\n if (root !== p) enterArc = insideArc, exitArc = outsideArc, outsideAngle.range([p.x, p.x + p.dx]);\n\n addOuterLabelLines(partition.nodes(root).slice(1)\n .filter(function(d){return d.depth >= 2}));\n addInnerLabelLines(partition.nodes(root).slice(1)\n .filter(function(d){return ((d.sum/d.parent.sum)*100) > 10})\n .filter(function(d){return d.depth === 1}));\n\n var textp = svg.select(\".center\").selectAll(\"text\")\n .data([root]);\n\n textp.enter().append(\"text\")\n .attr(\"text-anchor\", \"middle\")\n .text(function(d) {\n return d.name;\n });\n\n textp.exit().remove();\n textp.transition().style(\"fill-opacity\", 1)\n .attr(\"text-anchor\", \"middle\")\n .text(function(d) {\n return d.name;\n });\n\n addOuterLabel(partition.nodes(root).slice(1));\n addPercentages(partition.nodes(root).slice(1));\n\n d3.transition().duration(d3.event.altKey ? 7500 : 750).each(function() {\n path.exit().transition()\n .style(\"fill-opacity\", function(d) { return d.depth === 1 + (root === p) ? 1 : 0; })\n .attrTween(\"d\", function(d) { return arcTween.call(this, exitArc(d)); })\n .remove();\n\n path.enter().append(\"path\")\n .style(\"fill-opacity\", function(d) { return d.depth === 2 - (root === p) ? 1 : 0; })\n .style(\"fill\", function(d) { return d.fill; })\n .on(\"mouseover\",update_legend)\n .on(\"mouseout\",remove_legend)\n .on(\"click\", zoomIn)\n .each(function(d) { this._current = enterArc(d); });\n\n path.transition()\n .style(\"fill-opacity\", 1)\n .attrTween(\"d\", function(d) { return arcTween.call(this, updateArc(d)); });\n });\n fixOverlap();\n }",
"function zoom(rootNode, zoomNode, activeNode, isZoomIn, isInitial) {\n\t\n\t // update selection\n\t var oldRootNode = root._rootNode;\n\t var oldActiveNode = root._activeNode;\n\t root._rootNode = rootNode;\n\t root._activeNode = activeNode;\n\t var speed = oldRootNode === rootNode ? 100 : 400;\n\t \n\t // check if selection changed\n\t if (oldRootNode === rootNode &&\n\t \toldActiveNode === activeNode) {\n\t \t\n\t \tvar flashEase = function(t) {\n\t \t\tif (t <= 0.5) {\n\t \t\t\tvar used = 1.0 - t*2;\n\t\t \t\treturn Math.sqrt(1.0 - used*used);\n\t \t\t} else if (t <= 1.0) {\n\t \t\t\tvar used = (t - 0.5)*2;\n\t\t \t\treturn Math.sqrt(1.0 - used*used);\n\t \t\t} else {\n\t \t\t\treturn 0.0;\n\t \t\t}\n\t \t};\n\t \t\n\t \tif (isZoomIn) {\n\t \t\n\t \t\tvar activePath = gPathTop.select(\"path\");\n\t \t\tif (activePath.size() == 1) {\n\t \t\t\n\t \t\t\t// need to set data after select\n\t\t \t\tactivePath.datum(activeNode);\n\t\t \t\t\n\t\t \t\t// highlight\n\t\t \t\tvar oldFill = activePath.style(\"fill\");\n\t\t \t\tactivePath\n\t\t \t\t\t.transition()\n\t\t\t\t\t\t.duration(speed)\n\t\t\t\t\t\t.ease(flashEase)\n\t\t\t\t\t .style(\"fill\", par.backFlashColor);\n\t\t\t\t}\n\n\t \t} else {\n\t \t\t\n\t \t\tvar oldFill = circle.style(\"fill\");\n\t\t\t\tcircle\n\t\t\t\t\t.transition()\n\t\t\t\t\t.duration(speed)\n\t\t\t\t\t.ease(flashEase)\n\t\t\t\t .style(\"fill\", par.backFlashColor);\n\t \t}\n\t \t\n\t \treturn;\n\t }\n\t \n\t if (!isInitial && onZoom) {\n\t\t\tonZoom(activeNode);\n\t\t}\n\t\n\t // Stash the original root dimensions for transitions.\n\t var rootScale = d3.scale.linear()\n\t\t\t.domain([0, 2 * Math.PI])\n\t\t\t.range([rootNode.x, rootNode.x + rootNode.dx]);\n\t\n\t function insideArc(d) {\n\t \treturn zoomNode.key > d.key \n\t \t\t? {\n\t \t\t\tdepth: d.depth - 1, \n\t \t\t\tx: 0, \n\t \t\t\tdx: 0, \n\t \t\t\tactive: (root._activeNode === d ? 1.0 : 0.0) \n\t \t\t} \n\t \t\t: zoomNode.key < d.key \n\t \t\t? {\n\t \t\t\tdepth: d.depth - 1, \n\t \t\t\tx: 2 * Math.PI, \n\t \t\t\tdx: 0, \n\t \t\t\tactive: (root._activeNode === d ? 1.0 : 0.0) \n\t \t\t} \n\t \t\t: {\n\t \t\t\tdepth: 0, \n\t \t\t\tx: 0, \n\t \t\t\tdx: 2 * Math.PI, \n\t \t\t\tactive: (root._activeNode === d ? 1.0 : 0.0) \n\t \t\t};\n\t }\n\t\n\t function outsideArc(d) {\n\t\t\treturn {\n\t\t\t\tdepth: d.depth + 1, \n\t\t\t\tx: rootScale(d.x), \n\t\t\t\tdx: rootScale(d.x + d.dx) - rootScale(d.x), \n\t\t\t\tactive: (root._activeNode === d ? 1.0 : 0.0) \n\t\t\t};\n\t }\n\t\n\t // When zooming in, arcs enter from the outside and exit to the inside.\n\t // When zooming out, arcs enter from the inside and exit to the outside.\n\t var enterArc = rootNode === zoomNode ? outsideArc : insideArc,\n\t exitArc = rootNode === zoomNode ? insideArc : outsideArc;\n\n\t // when starting, appear from inside\n\t if (oldRootNode === null) {\n\t \tenterArc = insideArc;\n\t }\n\n\t\t// transition everything\n\t d3.transition().duration(speed).each(function() {\n\t \n\t \t// move top elements to back\n\t \tgPathTop.selectAll(\"*\").each(function() {\n\t \t\tgPath[0][0].appendChild(this);\n\t \t});\n\t \tgTextTop.selectAll(\"*\").each(function() {\n\t \t\tgText[0][0].appendChild(this);\n\t \t});\n\t\t\n\t\t\t// update circle\n\t\t\tcircle.datum(rootNode)\n\t\t\t\t.transition()\n\t\t\t\t.style(\"fill\", nodeFill)\n\t\t\t\t.style(\"opacity\", 1);\n\n\t\t\t// partition from new root\n\t\t\tnodes = partition.nodes(rootNode).slice(1);\n\t\t\t\n\t\t\t// update paths\n\t\t\tpath = path.data(nodes, function(d) { return d.key; });\n\t\t\tpath.transition()\n\t\t\t\t.style(\"fill\", nodeFill)\n\t\t\t\t.attrTween(\"d\", function(d) { return pathTween.call(this, updateArc(d)); });\n\n\t\t\t// udpate texts\t\n\t\t\ttext = text.data(nodes, function(d) { return d.key; });\n\t\t\ttextRoot = textRoot.data([rootNode], function(d) { return d.key; });\n\t\t\ttext.transition()\n\t\t\t\t.attrTween(\"transform\", function(d) { return textTween.call(this, updateArc(d)); })\n\t\t\t\t.style(\"font-size\", nodeTextSize)\n\t\t\t\t.style(\"fill\", nodeTextColor);\n\t\t\ttextRoot.transition()\n\t\t\t\t.style(\"font-size\", nodeTextSize)\n\t\t\t\t.style(\"fill\", nodeTextColor);\n\t\t\t\n\t\t\t// enter paths\n\t\t\tpath.enter().append(\"path\")\n\t\t\t\t.style(\"stroke\", par.pathStrokeColor)\n\t\t\t\t.style(\"opacity\", 0)\n\t\t\t\t.style(\"fill\", nodeFill)\n\t\t\t\t.on(\"click\", zoomIn)\n\t\t\t\t.each(function(d) { this._current = enterArc(d); })\n\t\t\t.transition()\n\t\t\t\t.style(\"opacity\", 1)\n\t\t\t\t.attrTween(\"d\", function(d) { return pathTween.call(this, updateArc(d)); });\n\n\t\t\t// enter texts\n\t\t\ttext.enter()\n\t\t\t\t.append(\"text\")\n\t\t\t\t\t.attr(\"class\", \"sector noSelect\")\n\t\t\t\t\t.style(\"opacity\", 0)\n\t\t\t\t\t.attr(\"dy\", \"8\")\n\t\t\t\t\t.attr(\"text-anchor\", \"middle\")\n\t\t\t\t\t.text(function(d) { return d.name; })\n\t\t\t\t\t.on(\"click\", zoomIn)\n\t\t\t\t\t.each(function(d) { this._current = enterArc(d); })\n\t\t\t\t.transition()\n\t\t\t\t\t.style(\"opacity\", 1)\n\t\t\t\t\t.attrTween(\"transform\", function(d) { return textTween.call(this, updateArc(d)); })\n\t\t\t\t\t.style(\"font-size\", nodeTextSize)\n\t\t\t\t\t.style(\"fill\", nodeTextColor);\n\t\t\ttextRoot.enter()\n\t\t\t\t.append(\"text\")\n\t\t\t\t\t.attr(\"class\", \"root noSelect\")\n\t\t\t\t\t.attr(\"x\", 0)\n\t\t\t\t\t.attr(\"y\", 0)\n\t\t\t\t\t.attr(\"dy\", \"8\")\n\t\t\t\t\t.style(\"opacity\", 0)\n\t\t\t\t\t.attr(\"text-anchor\", \"middle\")\n\t\t\t\t\t.text(function(d) { return d.name; })\n\t\t\t\t\t.on(\"click\", zoomOut)\n\t\t\t\t.transition()\n\t\t\t\t\t.style(\"opacity\", 1)\n\t\t\t\t\t.style(\"font-size\", nodeTextSize)\n\t\t\t\t\t.style(\"fill\", nodeTextColor);\n\n\t\t\t// after enter,\n\t\t\t// bring to front\n\t\t\t// active node path\n\t\t\tpath.each(function(d) {\n\t\t\t\tif (root._activeNode === d) {\n\t\t\t\t\tgPathTop[0][0].appendChild(this);\n\t\t\t\t}\n\t\t\t});\n\t\t\ttext.each(function(d) {\n\t\t\t\tif (root._activeNode === d) {\n\t\t\t\t\tgTextTop[0][0].appendChild(this);\n\t\t\t\t}\n\t\t\t});\n\t\t\ttextRoot.each(function(d) {\n\t\t\t\tif (root._activeNode === d) {\n\t\t\t\t\tgTextTop[0][0].appendChild(this);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// exit paths\n\t\t\tpath.exit().transition()\n\t\t\t\t.style(\"opacity\", 0)\n\t\t\t\t.attrTween(\"d\", function(d) { return pathTween.call(this, exitArc(d)); })\n\t\t\t\t.remove();\n\t\t\t\t\n\t\t\t// exit texts\n\t\t\ttext.exit().transition()\n\t\t\t\t.style(\"opacity\", 0)\n\t\t\t\t.attrTween(\"transform\", function(d) { return textTween.call(this, exitArc(d)); })\n\t\t\t\t.remove();\n\t\t\ttextRoot.exit().transition()\n\t\t\t\t.style(\"opacity\", 0)\n\t\t\t\t.remove();\n\n\t\t}); // end transition\n\n\t} // end zoom",
"function setZoom() {\n zoom = 2.0;\n}",
"function setZoom() {\r\n zoom = 2.0;\r\n}",
"resetZoom () {\n paper.view.zoom = 1\n paper.view.center = new paper.Point(paper.view.viewSize.width / 2, paper.view.viewSize.height / 2)\n }",
"shiftCenterAndZoom () {\n this.flyAndZoomTo(...offsetCenter, initZoom)\n }",
"_setSVGZoom() {\n this.zoom = zoom().on('zoom', (event) =>\n this.rootSVGGroupSelection.attr('transform', event.transform)\n )\n this.rootSVGSelection.call(this.zoom)\n this._setInitialZoom()\n }",
"function zoomIn(p) {\n if (p.depth > 1) p = p.parent;\n if (!p.children) return;\n if (typeof root.name == \"string\") {\n centerNode = \"\\n\\n\" + p.name;\n }\n zoom(p, p);\n }",
"function setZoom() {\r\n console.log();\r\n\r\n \r\n setNormal();\r\n\r\n zoom=2.0;\r\n\r\n }",
"resetCenterAndZoom () {\n this.flyAndZoomTo(...initCenter, initZoom)\n }",
"refreshZoom() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initialize the emotion window | function initEmotionWindow() {
$("emotionArea").hide();
$("emotionArea").hidden = false;
$("emotionBtn").observe("click", function (event) {
if (isEmotionWindowOpened == false) {
// set the location of the emotion window
var total = $("emotionBtn").offsetTop - parseInt($("emotionArea").getStyle("height"));
$("emotionArea").style.top = total + "px";
// show the emotion window
$("emotionArea").grow();
isEmotionWindowOpened = true;
} else {
// close the emotion window
$("emotionArea").shrink();
isEmotionWindowOpened = false;
}
});
var emotions = $$(".emotion");
for (var i = 0; i < emotions.length; i++) {
var emotion = emotions[i];
emotion.observe("click", function (event) {
// user selects an emotion
// the emotion will be inserted in the edit window
// and close the emotion window
$("emotionArea").shrink();
isEmotionWindowOpened = false;
// insert the emotion to the current cursor position
$("editwindow").contentDocument.execCommand(
"InsertHTML", false, this.innerHTML);
$("editwindow").focus();
});
}
} | [
"function initialise()\n{\n\tinitCanvas();\n\t\n\tthis.popup = new PopupBox(0,0);\n\tthis.popupVisible = false;\n}",
"_buildWindow()\n\t{\n\t\tthis.window = new MotionTrackerWindow();\n\t\tthis.currentCanvasPosition = MotionTracker.CONFIG.canvasZIndex;\n\t\tthis.currentUseHighDPI = MotionTracker.CONFIG.useHighDPI;\n\t}",
"function initColorWindow() {\n $(\"colorArea\").hide();\n $(\"colorArea\").hidden = false;\n $(\"colorBtn\").observe(\"click\", function (event) {\n if (isColorBarOpened == false) {\n // set the location of the emotion window\n var total = $(\"colorBtn\").offsetTop - parseInt($(\"colorArea\").getStyle(\"height\"));\n $(\"colorArea\").style.top = total + \"px\";\n $(\"colorArea\").style.left = $(\"colorBtn\").offsetLeft + \"px\";\n // show the emotion window\n $(\"colorArea\").slideDown({\n duration: 0.4\n });\n isColorBarOpened = true;\n } else {\n // press again to close the emotion window\n // and set the color of the text\n $(\"colorArea\").slideUp({\n duration: 0.4\n });\n isColorBarOpened = false;\n $(\"editwindow\").contentDocument.execCommand(\n \"ForeColor\", false, $$(\"#colorArea .color\")[0].value);\n $(\"editwindow\").focus();\n }\n });\n}",
"function initEnviro(){\n pushRender();\n windowSize();\n initScene();\n initCameras();\n initFog();\n initLight();\n}",
"function Window_Ammo() {\n this.initialize.apply(this, arguments);\n}",
"init() {\n const windowScrollAndSize = { ...getWindowSize(), ...getWindowScroll() };\n this.elementsWithEffectsMap = this.getElementsWithEffects();\n this.initDocument();\n this.propagateScroll(windowScrollAndSize);\n this.registerNextAF();\n }",
"static initScreen()\n\t{\n\t\t// Some css appearance items\n\t\t$(\"html\").css(\"height\", \"100%)\");\n\t $(\"body\").css(\"color\", \"#d0d0d0\");\n\t $(\"body\").css(\"width\", \"100%\");\n\t $(\"body\").css(\"height\", \"100%\");\n\t $('.Copyright a').css(\"color\", \"white\"); \n\t $('.Copyright a:visited').css(\"color\", \"white\"); \n\t $('.Copyright p').css(\"color\", \"white\"); \n\n\t $(\"body\").css(\"background-repeat\", \"no-repeat\");\n\t $(\"body\").css(\"background-size\", \"cover\");\n\t $(\"body\").css(\"background-image\", \"url('iNeed2_Resources/control_panel_1b.jpeg')\");\n\n\t // Set Input Field Weight values\n\t $('#u_setting_input_l').val(taskList.getUrgencyWeight());\n\t $('#i_setting_input_l').val(taskList.getImportanceWeight());\n\t $('#e_setting_input_l').val(taskList.getEffortWeight());\n\t $('#c_setting_input_l').val(taskList.getCompletionWeight());\n\n\t // Set Slider Weight values\n\t $('#myUrgency').val(taskList.getUrgencyWeight());\n\t $('#myImportance').val(taskList.getImportanceWeight());\n\t $('#myEffort').val(taskList.getEffortWeight());\n\t $('#myCompletion').val(taskList.getCompletionWeight());\n\t}",
"function init() {\n resetGame();\n window.addEventListener('keydown', handleKey);\n optionsScreen.style.display = 'none';\n startScreen.style.display = 'grid';\n}",
"function initChildWindow () {\n registerProtocolHandlers()\n hideCursor()\n moveWindowBounce()\n setupFollowWindow()\n startVideo()\n detectWindowClose()\n triggerFileDownload()\n speak()\n rainbowThemeColor()\n animateUrlWithEmojis()\n\n interceptUserInput(event => {\n if (interactionCount === 1) {\n startAlertInterval()\n }\n })\n}",
"function Window_HUD() { this.initialize.apply(this, arguments); }",
"function init_screen(){\n //get frame & dimensions\n frame.toggleClass('colcarou-frame');\n frame_width = frame.width();\n if(opts.fullscreen) {\n frame_height = window_height;\n }\n else {\n frame_height = opts.slide_height;\n }\n frame.height(frame_height);\n //name all the items\n nameItems();\n screen_resize();\n screen_switchPanel();\n $('.colcarou-item.inactive').bind('click',clickHandler);\n }",
"function init() {\r\n //$(document).off();\r\n root.css({ // TODO STYL\r\n \"background-color\": \"rgb(219,217,204)\",\r\n \"color\": \"black\",\r\n \"width\": \"100%\",\r\n \"height\": \"100%\"\r\n });\r\n mainPanel.css({ // TODO JADE/STYL\r\n width: '100%',\r\n height: (100 - topbarHeight) + '%'\r\n }).addClass(\"mainPanel\");\r\n\r\n //creates deep zoom image\r\n if (artwork) {\r\n \r\n annotatedImage = new TAG.AnnotatedImage({\r\n root: root,\r\n doq: artwork,\r\n callback: function () {\r\n\r\n if (!(annotatedImage.openArtwork(artwork))) { // if artwork load is unsuccessful...\r\n var popup = TAG.Util.UI.popUpMessage(function () {\r\n TAG.Authoring.SettingsView(\"Artworks\", function (settingsView) {\r\n TAG.Util.UI.slidePageRight(settingsView.getRoot());\r\n }, null, artwork.Identifier);\r\n }, \"There was an error loading the image.\", \"Go Back\", true);\r\n root.append(popup);\r\n $(popup).show();\r\n }\r\n initUI();\r\n },\r\n noMedia: true\r\n });\r\n } else {\r\n initUI();\r\n }\r\n }",
"initialize() {\n // add light box to dom\n this.createBox();\n // add click listener/keypress\n this.createClickTriggers();\n }",
"onReady() {\n SmartCrawlerMenu.set();\n this.createWindow();\n }",
"function init() {\n setupModeButtons();\n setupSquares();\n resetGame();\n}",
"function init() {\n // get a referene to the target <canvas> element.\n if (!(canvas = document.getElementById(\"game-canvas\"))) {\n throw Error(\"Unable to find the required canvas element.\");\n }\n\n // resize the canvas based on the available browser available draw size.\n // this ensures that a full screen window can contain the whole game view.\n canvas.height = (window.screen.availHeight - 100);\n canvas.width = (canvas.height * 0.8);\n\n // get a reference to the 2D drawing context.\n if (!(ctx = canvas.getContext(\"2d\"))) {\n throw Error(\"Unable to get 2D draw context from the canvas.\");\n }\n\n // specify global draw definitions.\n ctx.fillStyle = \"white\";\n ctx.textAlign = \"center\";\n\n // set the welcome scene as the initial scene.\n setScene(welcomeScene);\n }",
"function init(){\n //Mode Buttons\n setupModeButtons();\n //Squares Colors and Listeners\n setupSquares();\n reset();\n}",
"function initParentWindow () {\n showHelloMessage()\n blockBackButton()\n fillHistory()\n startInvisiblePictureInPictureVideo()\n\n interceptUserInput(event => {\n // Only run these on the first interaction\n if (interactionCount === 1) {\n registerProtocolHandlers()\n attemptToTakeoverReferrerWindow()\n hideCursor()\n startVideo()\n startAlertInterval()\n superLogout()\n removeHelloMessage()\n rainbowThemeColor()\n animateUrlWithEmojis()\n speak('That was a mistake')\n }\n })\n}",
"function launchCreatureEditor(){\n\n creatureEditorScreen.init();\n\n}//end launchCreatureEditor()"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to publish payload to IoT topic | function publishToIoTTopic(topic, payload) {
// Publish to specified IoT topic using device object that you created
device.publish(topic, payload);
} | [
"function publishMessage(topic, payload, eventCallback){\r\n\r\n\tvar params = {\r\n\t\ttopic: topic, /* required */\r\n\t\t//payload: new Buffer('...') || payload,\r\n\t\tpayload: payload,\r\n\t\tqos: 1\r\n\t};\r\n\t\tiotdata.publish(params, function(err, data) {\r\n\t\tif (err) console.log(err, err.stack); // an error occurred\r\n\t\telse console.log(data); \r\n\t\t\r\n\t\teventCallback(data); \r\n\t});\r\n\r\n\r\n}",
"publish (topic, message) {\n\n this.send({\n action: 'publish',\n payload: {\n topic: topic,\n message: message,\n },\n })\n\n }",
"function publish (topic, data) {\n\n }",
"function MQTT_Publish(topic, paramValue, system) {\r\n //CF.log(\"Publishing to : \"+topic+\" Value: \"+paramValue);\r\n\t// Calculate message length: 2 bytes for topic lenght byte + topic length + payload length\r\n\tvar message_length = 2 + topic.length + paramValue.length;\r\n\t//CF.log(\"Message length is : \"+ message_length);\r\n\t// Send Publish message 0x31 by assembling: 0x31 + Message Length + 0x00 + Length of topic + Value\r\n\tvar message = binaryString([0x31, message_length, 0x00, topic.length, topic, paramValue]);\r\n\tCF.send(system, message);\r\n\t//CF.log(\"Message sent \" + message);\r\n}",
"function sendFunction(data){\n console.log(\"Message from socket: \" + data);\n\n payload = data;\n client.publish('/nyu-ima-topic1/', String(payload), function() {\n console.log(\"Pushed to MQTT: \" + payload);\n //client.end(); // Close the connection when published\n });\n\t}",
"publish (payload) {\n // get default Redis channel\n let channel = this.api.config.general.channel\n\n // publish redis message\n this.clients.client.publish(channel, JSON.stringify(payload))\n }",
"publish (topic, message) {\n this.client.publish(topic, message)\n }",
"publish(payload) {\n // get default Redis channel\n let channel = this.api.config.general.channel;\n\n // publish redis message\n this.clients.client.publish(channel, JSON.stringify(payload));\n }",
"publish (data, endpoint = this.url) {\r\n cubic.log.verbose('Core | Sending data to publish for ' + endpoint)\r\n this.api.connection.client.send(JSON.stringify({\r\n action: 'PUBLISH',\r\n endpoint,\r\n data\r\n }))\r\n }",
"sendMessage(message) {\n this.mqttClient.publish('mytopic', message);\n }",
"static publish(queue, event, payload) {\n let q = io.connect(`${SERVER}`);\n let message = {queue,event,payload};\n q.emit('publish', message, (ret) => {\n q.disconnect();\n });\n }",
"function publish(topic, message) {\n log(\"publish: \" + topic + \" message \" + message); \n WebApp.publish(topic, message);\n}",
"handlePublishMessageToClientId (topic, message, clientId, method) {\n \n this.send(clientId, {\n action: 'publish',\n payload: {\n topic: topic,\n method: method,\n message: message,\n },\n })\n \n\n }",
"function mqttWrite(wr, cmd, topic, payload) {\n var l = topic.length+payload.length;\n //console.log(\"MQwr:\", typeof(payload), l, 0x80+(l&0x7f), l>>7, payload);\n wr(l < 128 ? sfcc(cmd, l) : sfcc(cmd, 0x80+(l&0x7f), l>>7));\n wr(topic);\n wr(payload);\n}",
"sendMessage(message) {\n this.mqttClient.publish('/ujangsprr@gmail.com/mytopic', message);\n }",
"function postMQTT(data)\n {\n let td = data['data']['current']['weather'];\n msg = 'send_mqtt?';\n msg += 'topic=Weather';\n msg += '&'\n msg += 'message=' + td.ts;\n console.log(msg)\n fetch(msg, {method: 'POST'})\n }",
"function publish() {\n var _data = {\"sensors\":{\"temp\":\"\",\"sound\":\"\",\"flow\":\"\"}};\n for (var i = 0; i < data.length; i++) {\n _data.sensors[convert(data[i].type)] = data[i].value;\n }\n board.info(\"LEGACY\", JSON.stringify(_data));\n rest.post(SBS_ENDPOINT+\"data\", {\n data: JSON.stringify(_data),\n headers: { \"Content-Type\": \"application/json\",\n \"x-api-key\": API_KEY }\n }).on('complete', function(data, response) {\n board.info(\"BOARD\",data);\n });\n }",
"function authorizePublish(client, topic, payload, callback) {\n\n if(!client.skynetDevice){\n return callback(hyGaError(401,'Unauthorized'));\n }\n if(client.skynetDevice.uuid === 'skynet'){\n callback(null, true);\n }else if(_.contains(skynetTopics, topic)){\n var payload = payload.toString();\n try{\n var payloadObj = JSON.parse(payload);\n payloadObj.fromUuid = client.skynetDevice.uuid;\n callback(null, new Buffer(JSON.stringify(payloadObj)));\n }catch(exp){\n callback(hyGaError(400,'Invalid payload'));\n }\n }else{\n callback(hyGaError(400,'Invalid topic'));\n }\n\n }",
"function __publish(arn, payload, callback) {\n console.log('Publishing SNS', JSON.stringify({arn, payload}))\n sns.publish({\n TopicArn: arn,\n Message: JSON.stringify(payload)\n },\n function _published(err, result) {\n if (err) throw err\n callback(null, result)\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get URL for the top suggestion | function getTopSuggestionUrl(data, text) {
var suggestions = getSuggestions(data, text);
if (suggestions.length) {
var topSuggestion = suggestions.reverse().pop();
return topSuggestion.url;
} else if (String(text).match(/^https?:\/\//)) {
return text;
}
return false;
} | [
"get suggestionURL() { return namespace(this).suggestionURL; }",
"function findLargestUrl(callback) {\n Url.find().sort({ shortUrl:-1 }).limit(1)\n .exec(function(err, data) {\n if (err) return callback(err, null); \n return callback(null, data[0].shortUrl);\n });\n }",
"get randomSearchURL() {\n const searchTerms = [\n \"kanopy\",\n \"history\",\n \"psycinfo\",\n \"new york times\",\n \"bible\",\n \"loeb classical library\"\n ];\n const searchTerm = searchTerms[Math.floor(Math.random() * searchTerms.length)];\n return this.searchURL(searchTerm);\n }",
"function computeAutocompleteURL() {\n var settings = $(input).data(\"settings\");\n return typeof settings.autocompleteUrl === 'function' ? settings.autocompleteUrl.call(settings) : settings.autocompleteUrl;\n }",
"function suggestDisplayTitle(url) {\r\n let title;\r\n\r\n // Try constructing the title using the URI\r\n try {\r\n\tlet urlObj = new URL (url);\r\n\tlet host = urlObj.host;\r\n\tlet pathname = urlObj.pathname;\r\n\tlet search = urlObj.search;\r\n\tlet hash = urlObj.hash;\r\n\r\n\ttitle = decodeURI(host + pathname + search + hash);\r\n } \r\n catch (e) {\r\n\t// Use (no title) for non-valid/standard URIs\r\n\ttitle = \"(no title)\"; // TODO : move to _locales/en/messages.json\r\n }\r\n\r\n return(title);\r\n}",
"getFirstResultUrl() {\n return this.ResultUrl.first();\n }",
"function getNearestQueryUrl(){\n\n\tvar queryUrl = config.NEARESTSTATIONURL + config.APIKEY +'&location=' + testConstants.LOCATION + '&ev_network='+ testConstants.EVNETWORK;\t \n\treturn queryUrl;\n}",
"function getURLSearch() {\n return window.location.search.substring(1);\n}",
"function getUrlTalents() {\n return $location.search().talents;\n }",
"getURL()\n {\n // Search\n const searchOrig = decodeURI(this.getArg('q') || '');\n if (!searchOrig) {\n return '/'; // Just go to home\n }\n\n const search = searchOrig.replace('()', '').replace('$', '');\n const searchParts = search.split(/(::|\\->)/);\n const searchConfig = {};\n if (searchParts.length == 2) {\n searchConfig['class'] = searchParts[0];\n searchConfig.property = searchParts[1];\n searchConfig.type = searchOrig.match('()') ? 'method' : 'property';\n } else {\n searchConfig['class'] = search;\n searchConfig.property = '';\n searchConfig.type = 'class';\n }\n return this.getURLForClass(searchConfig);\n }",
"function searchSuggestion() {\n fetch(\n `https://api.giphy.com/v1/trending/searches?api_key=${_giphyApiKey}`,\n {\n mode: \"cors\",\n }\n )\n .then((data) => {\n return data.json();\n })\n .then((data) => {\n search.placeholder = `${\n data.data[Math.floor(Math.random() * data.data.length)]\n }...`;\n })\n .catch((err) => {\n throw new Error(err);\n });\n}",
"function topSuggestionsForNode(bn, query, force_search, cb) {\n var node = hierarchy.getTreeNodeById(bn.BrowseNodeId);\n if (!node) {\n cb(new Error(\"Couldn't find browse node \" + bn.BrowseNodeId), null, null);\n return;\n }\n\n // By default, we omit overly general browse nodes...must be at least N deep in hierarchy\n // but not when browse node name matches query name, eg. for 'Shopping'\n // TODO make this variable, based on average ancestor depth\n if (force_search || node.depth > 2 || query.toLowerCase() === bn.Name.toLowerCase()) {\n console.log('getting the top suggestions for', bn.Name);\n giftSuggestionsForNode(bn, function(err, items) {\n if (err) {\n cb(err, null, node.depth);\n return;\n }\n cb(null, items, node.depth);\n });\n }\n else {\n console.log('omitting', bn.Name);\n cb(null, null, null);\n }\n}",
"function get_query_url() {\n var newSortField = sort_field;\n if (newSortField === \"relevance\") {\n newSortField = \"\"\n }\n ;\n\n var ebeye_url = query_urls.ebeye_search.replace('{QUERY}', query).replace('{START}', start).replace('{PAGESIZE}', page_size).replace('{SORTFIELD}', newSortField).replace('{ORDER}', sort_order);\n console.log(ebeye_url);\n // var url = query_urls.proxy.replace('{EBEYE_URL}', encodeURIComponent(ebeye_url));\n // return url;\n return ebeye_url;\n }",
"function getCurrentUrlRecipeIndex() {\n\trecipeIndexToShow = 0;\n\tvar query_string = window.location.href;\n\ttokens=query_string.split(\"#recipe_\");\n\tif (tokens.length > 1) {\n\t\trecipeIndexToShow=tokens[1];\n\t}\n\treturn recipeIndexToShow;\t\n}",
"function getShortenFromURL(url){\n return url.split('index.html?o=')[1];\n }",
"function getTopicUrl(){\r\n\t\t\tvar el = $(\".pager td[align='right'] option[selected]\");\r\n\t\t\tif (el && el[0]) {\r\n\t\t\t\treturn el[0].value;\r\n\t\t\t} else {\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t}",
"getURL(topic){\n if(!this.list.includes(topic) && topic != url_trending){\n this.append(topic);\n this.redrawTopics();\n }\n let url = this.query_url + 'q=' + topic + this.api_key;\n return url;\n }",
"function afo_browsenav2_compile_search_url() {\n\t\tvar searchTerms = new Array('type', 'op', 'sort', 'tags', 'regions', 'textsearch', 'textsearchtype');\n\t\tvar url = new Array();\n\t\t\n\t\tfor(var s in searchTerms) {\n\t\t\tvar args = Drupal.settings.afo_browsenav2.search[searchTerms[s]].getarg();\n\t\t\tif(args !== null) {\n\t\t\t\turl.push(args);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(url.length > 0) return url.join('/');\n\t\telse return null;\n\t}",
"function Suggests()\n{\n // \"Private\" member variables\n var suggestsXOffset = 20;\n var inputTimeoutId = null;\n var inputTimeoutDelay = _getTimeoutDelaySetting();\n var maxHeight = 0; // maximum height of suggest list\n var urlSearchHeight = 0;\n var urlSnippetId;\n var urlHasFoucus = false; // URL edit field focus flag\n\n // Orbit UI has a different URL snippet.\n if (app.layoutType() == \"tenone\") {\n urlSnippetId = \"TitleUrlId\";\n }\n else {\n urlSnippetId = \"UrlSearchChromeId\";\n }\n \n // \"Private\" methods\n\n //! Calculates the maximum height for the suggest list.\n //! If not all suggest items can fit in list, only half an item should be\n //! visible the end when scrolled to the top. This is to indicate more items.\n function _setMaxHeight()\n {\n // Calculate height of available space for suggest list.\n var statusbarHeight = (snippets.StatusBarChromeId != undefined && snippets.StatusBarChromeId.visible) ? snippets.StatusBarChromeId.getGeometry().height : 0; \n // The Orbit UI doesn't have a status bar.\n var statusbarHeight = ((app.ui() == \"orbit_ui\") || (app.ui() == \"maemo5_ui\")) ? 0 : statusbarSz.height;\n var urlSearchSz = snippets[urlSnippetId].getGeometry();\n var toolbarSz = snippets.WebViewToolbarId.getGeometry();\n // leave some space between suggest and toolbar (~10% of display height)\n var bufferHeight = Math.ceil(chrome.displaySize.height / 10);\n var availableHeight = chrome.displaySize.height -\n (statusbarHeight + urlSearchSz.height + toolbarSz.height + bufferHeight);\n // Calculate number of elements that can fit in available space.\n var elementHeight = 70; // set in suggests.css\n var numElements = Math.floor(availableHeight / elementHeight);\n\n // in order to make room for 1/2 entry at end of list we may\n // need to sacrifice 1 full element.\n if ((availableHeight % elementHeight) < (elementHeight / 2)) {\n numElements -= 1;\n }\n numElements += 0.5; // half of final visible entry\n // max suggest list height in pixels\n maxHeight = Math.floor(numElements * elementHeight);\n }\n\n //! Temporary substitute for settings function to get the delay for\n //! displaying the URL suggests list.\n function _getTimeoutDelaySetting()\n {\n // no setting stored for this currently\n return (1000); // 1 second\n }\n\n //! Displays and updates suggest list.\n function _showSuggests()\n {\n // make sure the input is the latest\n var input = snippets[urlSnippetId].url;\n\n // only display suggestions if there is input\n if (input.length != 0) {\n _updateSuggestList(input);\n this.updateSuggestsSize();\n\n if (!snippets.SuggestsChromeId.visible && pageController.editMode) {\n window.scrollTo(0, 0);\n // Disable the content view, leave the URL serach bar and status bar enabled.\n views.WebView.enabled = false;\n views.WebView.freeze();\n snippets.SuggestsChromeId.show(false);\n }\n } else {\n // no user input so hide suggestions\n _hideSuggests();\n }\n }\n\n //! Updates the suggestion list based on the specified input.\n /*!\n \\param input the current URL box text\n */\n function _updateSuggestList(input)\n {\n var recenturl;\n var recenttitle = window.localeDelegate.translateText(\"txt_browser_chrome_suggests_search_for\");\n var snippetId = document.getElementById('SuggestsId');\n var suggests = window.bookmarksController.suggestSimilar(input);\n var suggestUL = document.createElement('ul');\n var suggestLI = document.createElement('li');\n var pattern = new RegExp(input, \"ig\");\n\n snippetId.innerHTML = \"\"; // clear previous results\n suggestUL.id = 'suggestUlId';\n suggestLI.id = \"searchLiId\";\n\n // always provide an option to search for user entry\n recenttitle = recenttitle.replace(/%1/, \"<b>\" + input + \"</b>\");\n\n suggestLI.innerHTML = '<a href=\"#\" onclick=\"searchSuggests.searchUrlValue(\\''+input+'\\');'+\n 'return false;\">'+\n '<div class=\"SuggestElement\">'+'<span class=\"aTitle\">'+recenttitle+'</span>'+'</div></a>';\n suggestUL.appendChild(suggestLI);\n\n // add each search suggestion to unordered list\n for (i=0; i < suggests.length; i++) {\n \trecenturl = suggests[i].url1;\n recenttitle = suggests[i].title1;\n suggestLI = document.createElement('li');\n suggestLI.id = \"suggestsLiId\";\n\n // bold search text\n recenttitle = recenttitle.replace(pattern, \"<b>$&</b>\");\n recenturl = recenturl.replace(pattern, \"<b>$&</b>\");\n\n suggestLI.innerHTML = '<a href=\"#\" onclick=\"searchSuggests.gotoUrl(\\''+suggests[i].url1+'\\');' +\n ' return false;\">'+\n '<div class=\"SuggestElement\">'+\n '<span class=\"aTitle\">'+recenttitle+'</span><br/>'+\n '<span class=\"aUrl\">'+recenturl+'</span></div></a>';\n suggestUL.appendChild(suggestLI);\n }\n\n snippetId.appendChild(suggestUL);\n }\n\n //! Hides suggests list and support items.\n function _hideSuggests()\n {\n clearTimeout(inputTimeoutId);\n window.snippets.SuggestsChromeId.hide(false);\n views.WebView.enabled = true;\n views.WebView.unfreeze();\n }\n\n // Public Functions\n\n //! Handler for onload javascript event.\n this.loadComplete = function()\n {\n var urlSearchSz = snippets[urlSnippetId].getGeometry();\n\n urlSearchHeight = urlSearchSz.height;\n snippets.SuggestsChromeId.anchorTo(urlSnippetId, suggestsXOffset, urlSearchHeight);\n snippets.SuggestsChromeId.zValue = 10;\n\n _setMaxHeight(); // calculate max suggest list height\n\n // hide suggests on external mouse events\n snippets.SuggestsChromeId.externalMouseEvent.connect(this.handleExternalMouseEvent);\n // need to resize suggest page snippet on geometry change\n chrome.prepareForGeometryChange.connect(createDelegate(this, this.handleGeometryChange));\n }\n\n //! Updates the size of the suggests window depending on the size of the\n //! main DIV -- which changes as the number of items changes.\n this.updateSuggestsSize = function()\n {\n if (snippets.SuggestsChromeId != undefined) {\n var totalW = chrome.displaySize.width;\n var divHeight = document.getElementById(\"SuggestsId\").clientHeight + 2;\n var displayHeight = Math.min(maxHeight, divHeight);\n var displayWidth = totalW - (2 * suggestsXOffset);\n\n // reset snippet height\n snippets.SuggestsChromeId.setSize(displayWidth, displayHeight);\n }\n }\n\n //! Handles the geometry change signal. Need to re-calculate max height\n //! and then update suggest page height.\n this.handleGeometryChange = function()\n {\n _setMaxHeight(); // max height is based on display height\n this.updateSuggestsSize();\n }\n\n //! Loads google search page for search string.\n /*!\n \\param input value to search for\n */\n this.searchUrlValue = function(input)\n {\n var searchurl = window.pageController.searchUrl(input);\n\n _hideSuggests();\n\n window.pageController.currentLoad(searchurl);\n window.pageController.urlTextChanged(searchurl);\n }\n\n //! Hides suggests list and loads specified page.\n /*!\n \\param url address of page to load\n */\n this.gotoUrl = function(url)\n {\n _hideSuggests();\n url = window.pageController.guessUrlFromString(url);\n window.pageController.currentLoad(url);\n window.pageController.urlTextChanged(url);\n }\n\n //! Handles external mouse events - dismisses suggests list.\n /*!\n \\param type the type of event\n \\param name the name of event\n \\param description event description\n */\n this.handleExternalMouseEvent = function(type, name, description)\n {\n // external mouse event received on VKB mouse clicks and \n // suggest list mouse clicks both of which should be ignored\n if ((name == \"MouseClick\") && !urlHasFoucus \n && !snippets.SuggestsChromeId.hasFocus) {\n _hideSuggests();\n }\n }\n\n //! Updates the user input for suggestion list.\n /*!\n \\param input the current user input\n */\n this.updateUserInput = function()\n {\n // user still editing URL - don't show/update suggests yet\n clearTimeout(inputTimeoutId);\n inputTimeoutId = setTimeout(_showSuggests.bind(this), inputTimeoutDelay);\n }\n\n //! Called when load state changes. Suggests should only be called when\n //! the load state is editing.\n this.updateLoadState = function()\n {\n if (!pageController.editMode) {\n // not in editing mode - suggests not allowed\n _hideSuggests(); // ensure suggests are hidden\n }\n }\n\n //! Called when URL search bar focus changes. The external mouse event\n //! handler deals with most cases where the suggestion list should be\n //! dismissed but we don't get those events when the list isn't visible\n //! so this handler is needed to cancel the timer in those cases.\n this.urlSearchFocusChanged = function(focusIn)\n {\n urlHasFoucus = focusIn;\n // if visible user may be scrolling suggestion page so ignore focus change\n if (!focusIn && !snippets.SuggestsChromeId.visible) {\n // prevent suggestion list from being displayed until URL edited again\n clearTimeout(inputTimeoutId);\n }\n }\n\n //! Sets the user input URL suggest delay.\n /*!\n \\param to the new delay time.\n */\n this.setSuggestTimeout = function(to)\n {\n inputTimeoutDelay = to;\n }\n \n //! Hides suggests list and support items.\n this.hideSuggests = function()\n {\n _hideSuggests();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modifica el ancho del tooltips sobre 22 caracteres | function tooltip(){
try{
var tooltips = document.getElementsByClassName("inew-tooltiptext");
for (var i = tooltips.length - 1; i >= 0; --i) {
var tooltipCount = tooltips[i].innerHTML.length;
if (tooltipCount > 22){
tooltips[i].className = "inew-tooltiptext inew-tooltipLarge";
}
}
}catch (e){}
} | [
"function tt_FormatTip()\n{\n\tvar fn = \"[tooltip.js tt_FormatTip] \";\n\tvar css, w, h, pad = tt_aV[PADDING], padT, wBrd = tt_aV[BORDERWIDTH],\n\tiOffY, iOffSh, iAdd = (pad + wBrd) << 1;\n\n\t//--------- Title DIV ----------\n\tif(tt_aV[TITLE].length)\n\t{\n\t\tpadT = tt_aV[TITLEPADDING];\n\t\tcss = tt_aElt[1].style;\n\t\tcss.background = tt_aV[TITLEBGCOLOR];\n\t\tcss.paddingTop = css.paddingBottom = padT + \"px\";\n\t\tcss.paddingLeft = css.paddingRight = (padT + 2) + \"px\";\n\t\tcss = tt_aElt[3].style;\n\t\tcss.color = tt_aV[TITLEFONTCOLOR];\n\t\tif(tt_aV[WIDTH] == -1)\n\t\t\tcss.whiteSpace = \"nowrap\";\n\t\tcss.fontFamily = tt_aV[TITLEFONTFACE];\n\t\tcss.fontSize = tt_aV[TITLEFONTSIZE];\n\t\tcss.fontWeight = \"bold\";\n\t\tcss.textAlign = tt_aV[TITLEALIGN];\n\t\t// Close button DIV\n\t\tif(tt_aElt[4])\n\t\t{\n\t\t\tcss = tt_aElt[4].style;\n\t\t\tcss.background = tt_aV[CLOSEBTNCOLORS][0];\n\t\t\tcss.color = tt_aV[CLOSEBTNCOLORS][1];\n\t\t\tcss.fontFamily = tt_aV[TITLEFONTFACE];\n\t\t\tcss.fontSize = tt_aV[TITLEFONTSIZE];\n\t\t\tcss.fontWeight = \"bold\";\n\t\t}\n\t\tif(tt_aV[WIDTH] > 0)\n\t\t\ttt_w = tt_aV[WIDTH];\n\t\telse\n\t\t{\n\t\t\ttt_w = tt_GetDivW(tt_aElt[3]) + tt_GetDivW(tt_aElt[4]);\n\t\t\t// Some spacing between title DIV and closebutton\n\t\t\tif(tt_aElt[4])\n\t\t\t\ttt_w += pad;\n\t\t\t// Restrict auto width to max width\n\t\t\tif(tt_aV[WIDTH] < -1 && tt_w > -tt_aV[WIDTH])\n\t\t\t\ttt_w = -tt_aV[WIDTH];\n\t\t}\n\t\t// Ensure the top border of the body DIV be covered by the title DIV\n\t\tiOffY = -wBrd;\n\t}\n\telse\n\t{\n\t\ttt_w = 0;\n\t\tiOffY = 0;\n\t}\n\n\t//-------- Body DIV ------------\n\tcss = tt_aElt[5].style;\n\tcss.top = iOffY + \"px\";\n\tif(wBrd)\n\t{\n\t\tcss.borderColor = tt_aV[BORDERCOLOR];\n\t\tcss.borderStyle = tt_aV[BORDERSTYLE];\n\t\tcss.borderWidth = wBrd + \"px\";\n\t}\n\tif(tt_aV[BGCOLOR].length)\n\t\tcss.background = tt_aV[BGCOLOR];\n\tif(tt_aV[BGIMG].length)\n\t\tcss.backgroundImage = \"url(\" + tt_aV[BGIMG] + \")\";\n\tcss.padding = pad + \"px\";\n\tcss.textAlign = tt_aV[TEXTALIGN];\n\tif(tt_aV[HEIGHT])\n\t{\n\t\tcss.overflow = \"auto\";\n\t\tif(tt_aV[HEIGHT] > 0)\n\t\t\tcss.height = (tt_aV[HEIGHT] + iAdd) + \"px\";\n\t\telse\n\t\t\ttt_h = iAdd - tt_aV[HEIGHT];\n\t}\n\t// TD inside body DIV\n\tcss = tt_aElt[6].style;\n\tcss.color = tt_aV[FONTCOLOR];\n\tcss.fontFamily = tt_aV[FONTFACE];\n\tcss.fontSize = tt_aV[FONTSIZE];\n\tcss.fontWeight = tt_aV[FONTWEIGHT];\n\tcss.textAlign = tt_aV[TEXTALIGN];\n\tif(tt_aV[WIDTH] > 0)\n\t\tw = tt_aV[WIDTH];\n\t// Width like title (if existent)\n\telse if(tt_aV[WIDTH] == -1 && tt_w)\n\t\tw = tt_w;\n\telse\n\t{\n\t\t// Measure width of the body's inner TD, as some browsers would expand\n\t\t// the container and outer body DIV to 100%\n\t\tw = tt_GetDivW(tt_aElt[6]);\n\t\t// Restrict auto width to max width\n\t\tif(tt_aV[WIDTH] < -1 && w > -tt_aV[WIDTH])\n\t\t\tw = -tt_aV[WIDTH];\n\t}\n\tif(w > tt_w)\n\t\ttt_w = w;\n\ttt_w += iAdd;\n\n\t//--------- Shadow DIVs ------------\n\tif(tt_aV[SHADOW])\n\t{\n\t\ttt_w += tt_aV[SHADOWWIDTH];\n\t\tiOffSh = Math.floor((tt_aV[SHADOWWIDTH] * 4) / 3);\n\t\t// Bottom shadow\n\t\tcss = tt_aElt[7].style;\n\t\tcss.top = iOffY + \"px\";\n\t\tcss.left = iOffSh + \"px\";\n\t\tcss.width = (tt_w - iOffSh - tt_aV[SHADOWWIDTH]) + \"px\";\n\t\tcss.height = tt_aV[SHADOWWIDTH] + \"px\";\n\t\tcss.background = tt_aV[SHADOWCOLOR];\n\t\t// Right shadow\n\t\tcss = tt_aElt[8].style;\n\t\tcss.top = iOffSh + \"px\";\n\t\tcss.left = (tt_w - tt_aV[SHADOWWIDTH]) + \"px\";\n\t\tcss.width = tt_aV[SHADOWWIDTH] + \"px\";\n\t\tcss.background = tt_aV[SHADOWCOLOR];\n\t}\n\telse\n\t\tiOffSh = 0;\n\n\t//-------- Container DIV -------\n\ttt_SetTipOpa(tt_aV[FADEIN] ? 0 : tt_aV[OPACITY]);\n\ttt_FixSize(iOffY, iOffSh);\n}",
"toolTipTitle(tooltipItems, data){\t\t\n\t\treturn \"\";\n\t}",
"function add_nucleotide_tooltips() {\n svg.selectAll(\"tspan\").each(function(d) {\n var tspan = d3.select(this),\n title = '',\n nucleotide = tspan.text();\n if (nucleotide === 'R') {\n nucleotide = 'G or A';\n } else if (nucleotide === 'Y') {\n nucleotide = 'C or U';\n }\n if (tspan.attr('fill') == '#d90000') {\n title = nucleotide + \" present >97%\";\n } else if (tspan.attr('fill') == '#000000') {\n if (nucleotide != \"5'\") {\n title = nucleotide + \" present 90-97%\";\n }\n } else if (tspan.attr('fill') == '#807b88') {\n title = nucleotide + \" present 75-90%\";\n } else if (tspan.attr('fill') == '#ffffff') {\n title = nucleotide + \" present 50-75%\";\n }\n\n if (title) {\n tspan.on(\"mouseover\", function(d) {\n tooltip.transition()\n .duration(200)\n .style(\"opacity\", .9);\n tooltip.html(title)\n .style(\"left\", (d3.event.pageX) + \"px\")\n .style(\"top\", (d3.event.pageY - 28) + \"px\");\n }).on(\"mouseout\", function(d) {\n tooltip.transition()\n .duration(500)\n .style(\"opacity\", 0);\n });\n }\n });\n }",
"setNMoreTooltiptext(addresses) {\n if (addresses.length == 0) {\n return;\n }\n\n let tttArray = [];\n for (let i = 0; i < addresses.length && i < this.tooltipLength; i++) {\n tttArray.push(addresses[i].fullAddress);\n }\n let ttText = tttArray.join(\", \");\n\n let remainingAddresses = addresses.length - tttArray.length;\n // Not all missing addresses fit in the tooltip.\n if (remainingAddresses > 0) {\n // Figure out the right plural for the language we're using,\n let words = document\n .getElementById(\"bundle_messenger\")\n .getString(\"headerMoreAddrsTooltip\");\n let moreForm = PluralForm.get(remainingAddresses, words).replace(\n \"#1\",\n remainingAddresses\n );\n ttText += moreForm;\n }\n this.more.setAttribute(\"tooltiptext\", ttText);\n }",
"function addToolTips() {\n addToolTipStyle();\n\n buildUseString('cantaken');\n buildUseString('exttaken');\n buildUseString('kettaken');\n buildUseString('lsdtaken');\n buildUseString('opitaken');\n buildUseString('shrtaken');\n buildUseString('spetaken');\n buildUseString('pcptaken');\n buildUseString('xantaken');\n buildUseString('victaken');\n }",
"function toolTipTxtformater(stringVal) {\n if (stringVal === \"poverty\"){\n return \"%\"\n } else {\n return \"\"\n }\n}",
"function tooltipString(company,value) {\n return \"<b>\" + company + \":</b> \" + value + \"%\"\n}",
"function updateToolTip(charData) {\n h = charData[\"name\"] + \"<br>\"\n + charData['title'] + \"<br>\"\n + charData['composure'] + \"<br>\"\n return h\n}",
"toolTipLabels(tooltipItems, data){\t\n\t\treturn data.labels[tooltipItems.index] + \" : \" + data.datasets[0]['data'][tooltipItems.index];\n\t}",
"get tooltip() {}",
"function getSelectedSiteTooltip(self, title) {\n\n return [\n '<b>Site: </b>'+ self.point.name,\n '<b>Age: </b>' + self.x + ' Ma',\n '<b>' + title + ': </b>' + self.y.toFixed(2) + '°'\n ].join(\"<br>\");\n\n}",
"get showToolTip() {\n return this.i.a8;\n }",
"get short_text () {\n return new IconData(0xe261, {fontFamily: 'MaterialIcons', matchTextDirection: true});\n }",
"registerTooltip_() {\n const countTasks = this.ok ?\n `OK (${this.taskCount})` :\n `erred: ${this.taskErrorCount} out of ${this.taskCount}`;\n const tooltipContent = `<b>${this.testId}</b><br>` +\n `${this.avgRumtimeMs.toFixed(1)} ms, ` +\n `${(this.avgMaxrssKb / 1024.0).toFixed(1)} MB<br>` +\n `${countTasks}`;\n utils.registerTooltipOn(this, tooltipContent, {dX: 0, dY: 35});\n }",
"function tooltip_check(phrase, id) {\n\tif (phrase) {\n return phrase;\n } else {\n return 'Mod rank';\n }\n}",
"function positionFmt(pos, id) {\n return `<div data-toggle=\"tooltip\" data-placement=\"right\" title=\"${id}\">${pos}</div>`\n}",
"function program2Tooltip(self) {\r\n\tvar color = [\"#DDDDDD\", \"#DDDDDD\", \"#DDDDDD\", \"#DDDDDD\"]\r\n\tcolor[minigames[11].vars.program_2] = \"#96E5FF\";\r\n\t\r\n\ttooltip(self, 5, 16, 'Program 2', '<span style=\"color:'+color[1]+'\">1. Grants <span style=\"color:#00db0a;\">20</span> seconds worth of production.</span><br><span style=\"color:'+color[2]+'\">2. Removes <span style=\"color:#ff1e2d;\">15</span> seconds worth of production.</span><br><span style=\"color:'+color[3]+'\">3. <span style=\"color:#00db0a;\">Doubles</span> the value from clicks for 1 minute.</span><br><span style=\"color:'+color[4]+'\">4. <span style=\"color:#ff1e2d;\">Halves</span> the value from clicks for 1 minute.</span><br><span style = \\\"font-size:10px;float:right\\\";>Hotkey: ' + hotkeys.activate_building_2.toUpperCase() + ' </span>', function () {}, true);\r\n}",
"function program1Tooltip(self) {\r\n\tvar color = [\"#DDDDDD\", \"#DDDDDD\", \"#DDDDDD\", \"#DDDDDD\"]\r\n\tcolor[minigames[11].vars.program_1] = \"#96E5FF\";\r\n\t\r\n\ttooltip(self, 5, 16, 'Program 1', '<span style=\"color:'+color[1]+'\">1. Increases production by <span style=\"color:#00db0a;\">20%</span> for 1 minute.</span><br><span style=\"color:'+color[2]+'\">2. Decreases production by <span style=\"color:#ff1e2d;\">20%</span> for 1 minute.</span><br><span style=\"color:'+color[3]+'\">3. <span style=\"color:#00db0a;\">Autoclicks</span> once per second for 1 minute.</span><br><span style=\"color:'+color[4]+'\">4. Removes <span style=\"color:#ff1e2d;\">10</span> seconds worth of time.</span><br><span style = \\\"font-size:10px;float:right\\\";>Hotkey: ' + hotkeys.activate_building_1.toUpperCase() + ' </span>', function () {}, true);\r\n}",
"function program3Tooltip(self) {\r\n\tvar color = [\"#DDDDDD\", \"#DDDDDD\", \"#DDDDDD\", \"#DDDDDD\"]\r\n\tcolor[minigames[11].vars.program_3] = \"#96E5FF\";\r\n\t\r\n\ttooltip(self, 5, 16, 'Program 3', '<span style=\"color:'+color[1]+'\">1. Grants <span style=\"color:#00db0a;\">15</span> seconds worth of time.</span><br><span style=\"color:'+color[2]+'\">2. Decreases production by <span style=\"color:#ff1e2d;\">25%</span> for 1 minute.</span><br><span style=\"color:'+color[3]+'\">3. Increases production by <span style=\"color:#00db0a;\">15%</span> for 1 minute.</span><br><span style=\"color:'+color[4]+'\">4. Removes <span style=\"color:#ff1e2d;\">5</span> seconds worth of time.</span><br><span style = \\\"font-size:10px;float:right\\\";>Hotkey: ' + hotkeys.activate_building_3.toUpperCase() + ' </span>', function () {}, true);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/ Add the plarform's gear | function addGear(){
gear = game.add.sprite(400, 500, 'gear');
gear.anchor.set(0.5);
gear.scale.set(1.3);
gear.animations.add('right', [0, 1, 2, 3, 4, 5, 6], 6);
gear.animations.add('left', [6, 5, 4, 3, 2, 1, 0], 6);
} | [
"function addToolboxGear(newGear){\n\t\tvar previousGear = toolFigures[toolFigures.length - 1];\n\t\tif(previousGear != null)\n\t\t\tnewGear.setXPos(previousGear.getXPos() + previousGear.getInnerRadius() + previousGear.getOuterRadius() + 35);\n\t\telse\n\t\t\tnewGear.setXPos(50);\n\t\tnewGear.setYPos(35);\n\t\ttoolFigures[toolFigures.length] = newGear;\n\t\ttoolCanvasPaintManager.addBasePaintableObject(toolCanvasPaintManager.createPaintableObject(newGear, 0, 0, toolCanvas.width, toolCanvas.height));\n\t\ttoolCanvasPaintManager.repaint();\n\t}",
"function fnAddPallets() {\r\n\t\t\t\r\n\t\tif (properties.inventoryDataMap) {\r\n\t\t\t\r\n\t\t\tvar edgeColor = fnGetBackGroundColorInvert(); \r\n\t\t\tvar edgeMaterial = new THREE.LineBasicMaterial( { color: edgeColor, transparent: true, opacity: 0.2} ); // 0xffffff Can't control linewidth: https://threejs.org/docs/index.html#api/materials/LineBasicMaterial.linewidth\t\t\t\t\r\n\t\t\t\r\n\t\t\t//properties.warehouseGroup.getObjectByName(location) is too expensive resource wise...so iterate through warehousegroup 1 by 1\r\n\t\t\tfor (var locationIndex = 0; locationIndex < properties.warehouseGroup.children.length; locationIndex++){\t\r\n\t\t\t\t\r\n\t\t\t\tif (properties.warehouseGroup.children[locationIndex].userData.type == \"slot\"){\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar slot = properties.warehouseGroup.children[locationIndex];\r\n\t\t\t\t\tvar location = slot.name;\t\r\n\t\t\t\t\tvar layoutData = properties.layoutData[properties.layoutDataMap.get(location)];\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar pallets = properties.inventoryDataMap.get(location); //undefined means empty slot\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (pallets){ //Inventory pallets exist\r\n\r\n\t\t\t\t\t\tvar numSlotPallets = slot.userData.numPallets;\r\n\t\t\t\t\t\tvar numInventoryPallets = pallets.length;\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif (numSlotPallets === numInventoryPallets && numSlotPallets == 1 ){ //Get to re-use the existing pallet(s)\r\n\t\t\t\t\t\t\t\tvar pallet = slot.children[1]; //slot edge plus pallet\r\n\t\t\t\t\t\t\t\tpallet.name = properties.inventoryData[pallets[0]].PALLET;\t//pallets[i] is the index into the inventory data stored with inventoryDataMap\t\t\t\t\t\r\n\t\t\t\t\t\t} //if\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t//Remove previously built pallets\r\n\t\t\t\t\t\t\tfor(var i = slot.children.length-1; i >=1 ; i--){ //First child is the edge of the slot\r\n\t\t\t\t\t\t\t\t\tslot.remove(slot.children[i]);\r\n\t\t\t\t\t\t\t};\t\t\t\t\r\n\r\n\t\t\t\t\t\t\tvar palletHeight = properties.schema.sceneHeight(layoutData) / pallets.length;\r\n\t\t\t\t\t\t\tvar palletGeometry = new THREE.BoxGeometry(\tproperties.schema.sceneWidth(layoutData),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpalletHeight, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tproperties.schema.sceneDepth(layoutData)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\tvar edgeGeometry = \t new THREE.EdgesGeometry( palletGeometry ); // https://stackoverflow.com/questions/31539130/display-wireframe-and-solid-color/31541369#31541369\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tfor (var i=0; i < pallets.length; i++){\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tvar edge = new THREE.LineSegments( edgeGeometry, edgeMaterial ); // Can't control linewidth: https://threejs.org/docs/index.html#api/materials/LineBasicMaterial.linewidth\r\n\t\t\t\t\t\t\t\tedge.renderOrder = 0; //https://threejs.org/docs/index.html#api/en/core/Object3D.renderOrder\r\n\t\t\t\t\t\t\t\tedge.userData.type = \"edge\";\r\n\t\t\t\t\t\t\t\tedge.userData.opacity = edge.material.opacity;\r\n\t\t\t\t\t\t\t\tedge.userData.color = edge.material.color;\r\n\t\t\t\t\t\t\t\tedge.userData.palletNum = 0;\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tvar cubeMaterial = new THREE.MeshBasicMaterial( {transparent: true, wireframe: false});\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tvar pallet = new THREE.Mesh(palletGeometry, cubeMaterial);\r\n\t\t\t\t\t\t\t\tpallet.renderOrder = 1;\r\n\t\t\t\t\t\t\t\tpallet.userData.type = \"pallet\";\r\n\t\t\t\t\t\t\t\tpallet.userData.selected = false;\r\n\t\t\t\t\t\t\t\tpallet.userData.palletNum = i;\r\n\t\t\t\t\t\t\t\tpallet.name = properties.inventoryData[pallets[i]].PALLET;\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tslot.add(pallet);\r\n\t\t\t\t\t\t\t\tslot.add(edge);\r\n\r\n\r\n\t\t\t\t\t\t\t\tvar yBase = 0 - (properties.schema.sceneHeight(layoutData) / 2); //The base of the slot\r\n\t\t\t\t\t\t\t\tpallet.position.y = yBase + ( i * palletHeight) + (palletHeight/2) ;\r\n\t\t\t\t\t\t\t\tedge.position.y = yBase + ( i * palletHeight) + (palletHeight/2) ;\r\n\r\n\t\t\t\t\t\t\t} //for\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tslot.userData.numPallets = numInventoryPallets;\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t} //else\r\n\t\t\t\t\t\r\n\t\t\t\t\t} //if\r\n\t\t\t\t\telse { //Empty the slot\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tif (slot.children.length == 2){ //Just 1 pallet\r\n\t\t\t\t\t\t\tslot.children[1].name = location;\r\n\t\t\t\t\t\t} //if\r\n\t\t\t\t\t\telse { //Remove all pallets and put a single empty pallet\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t//Remove previously built pallets, if any\r\n\t\t\t\t\t\t\tfor(var i = slot.children.length-1; i >=1 ; i--){ //First child is the edge of the slot\r\n\t\t\t\t\t\t\t\t\tslot.remove(slot.children[i]);\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\tvar palletGeometry = new THREE.BoxGeometry(\tproperties.schema.sceneWidth(layoutData),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tproperties.schema.sceneHeight(layoutData), \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tproperties.schema.sceneDepth(layoutData)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\tvar edgeGeometry = \t new THREE.EdgesGeometry( palletGeometry ); // https://stackoverflow.com/questions/31539130/display-wireframe-and-solid-color/31541369#31541369\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\r\n\t\t\t\t\t\t\tvar edge = new THREE.LineSegments( edgeGeometry, edgeMaterial ); // Can't control linewidth: https://threejs.org/docs/index.html#api/materials/LineBasicMaterial.linewidth\r\n\t\t\t\t\t\t\tedge.renderOrder = 0; //https://threejs.org/docs/index.html#api/en/core/Object3D.renderOrder\r\n\t\t\t\t\t\t\tedge.userData.type = \"edge\";\r\n\t\t\t\t\t\t\tedge.userData.opacity = edge.material.opacity;\r\n\t\t\t\t\t\t\tedge.userData.color = edge.material.color;\r\n\t\t\t\t\t\t\tedge.userData.palletNum = 0;\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tvar pallet = new THREE.Mesh(palletGeometry, cubeMaterial);\r\n\t\t\t\t\t\t\tpallet.renderOrder = 1;\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tpallet.material.opacity = 0;\r\n\t\t\t\t\t\t\tpallet.userData.opacity = 0;\t\t\t\t\t\r\n\t\t\t\t\t\t\tpallet.userData.palletNum = 0;\t\t\t\t\t\r\n\t\t\t\t\t\t\tpallet.userData.type = \"pallet\";\r\n\t\t\t\t\t\t\tpallet.userData.selected = false;\r\n\t\t\t\t\t\t\tpallet.name = location;\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tslot.add(edge);\t\t\t//child[0]\t\t\r\n\t\t\t\t\t\t\tslot.add(pallet);\t\t//child[1]\t\r\n\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t} //else\r\n\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t} //else\r\n\t\t\t\t\t\t\r\n\t\t\t\t} //if\t\t\r\n\t\t\t\t\r\n\t\t\t} //for\r\n\t\t} //if\t\r\n\r\n\t} // fnAddPallets\t\t",
"function addGem() {\n var gem = getRandomGem();\n var row = getRandomRow();\n var col = getRandomColumn();\n\n //adding 55 to the row position and 10 to the column position since the gem image has been resized\n var newGem = new Gem(gem.sprite, gem.points, gem.keep, col[0]+5, row[0]+55, col[1], row[1]);\n allGems.push(newGem);\n}",
"function addSolarSystem(solarsystem){\n\tGame.solarsystems.push(solarsystem);\n}",
"function calculateGear() {\n\tlet transmission = getElementByID(\"modelsGears\").value,\n\t\tspur = getElementByID(\"spur\").value,\n\t\tpinion = getElementByID(\"pinion\").value,\n\t\ttire = getElementByID(\"tire\").value;\n\tsetTextByID(\"final\",\"---\");\n\tsetTextByID(\"rollout\",\"---\");\n\tif (validateNumber([spur, pinion])) {\n\t\tlet finalGear = (spur / pinion) * transmission;\n\t\tsetTextByID(\"final\",round(finalGear, 3));\n\t\tif (validateNumber([tire])) setTextByID(\"rollout\",round((tire * 3.1415) / finalGear, 3));\n\t}\n}",
"function addLeg(clown, params, side){\n var legTopRadius = params.legTopRadius;\n var legBottomRadius = params.legBottomRadius;\n var legLength = params.legLength;\n var segments = params.cylinderDetail;\n var legMaterial = params.legMaterial;\n var leg = createLimb(legTopRadius, legBottomRadius, legLength, segments, legMaterial);\n var legPositiony = legLength/2;\n leg.position.set(side/2*params.hipWidth, legPositiony, 0);\n // right when side == 1, left when side == -1\n leg.name = (side == 1 ? \"right leg\": \"left leg\");\n clown.add(leg);\n // now add the corresponding foot\n addFoot(clown, params, side);\n}",
"function SetGearVariables() {\n\tif (minVer) return;\n\t//make a menu array for all the packs\n\tGearMenus.packs = [];\n\tvar packArray = [];\n\tfor (var key in PacksList) {\n\t\tif (testSource(key, PacksList[key], \"gearExcl\")) continue;\n\t\tpackArray.push(key);\n\t};\n\tpackArray.sort();\n\tfor (var i = 0; i < packArray.length; i++) {\n\t\tGearMenus.packs.push({\n\t\t\tcName : PacksList[packArray[i]].name,\n\t\t\tcReturn : \"pack#\" + packArray[i]\n\t\t});\n\t};\n\n\t//make a menu array for all the gear\n\tGearMenus.gear = [];\n\tvar gearArray = [];\n\tfor (var key in GearList) {\n\t\tif (testSource(key, GearList[key], \"gearExcl\")) continue;\n\t\tgearArray.push(key);\n\t};\n\tgearArray.sort();\n\tfor (var i = 0; i < gearArray.length; i++) {\n\t\tvar theGear = GearList[gearArray[i]];\n\t\tGearMenus.gear.push({\n\t\t\tcName : theGear.infoname,\n\t\t\tcReturn : !theGear.name || theGear.name === \"-\" ? null : \"gear#\" + gearArray[i]\n\t\t});\n\t};\n\n\t//make a menu array for all the tools\n\tGearMenus.tools = [];\n\tvar toolsArray = [];\n\tfor (var key in ToolsList) {\n\t\tif (testSource(key, ToolsList[key], \"gearExcl\")) continue;\n\t\ttoolsArray.push(key);\n\t};\n\ttoolsArray.sort();\n\tfor (var i = 0; i < toolsArray.length; i++) {\n\t\tvar theTool = ToolsList[toolsArray[i]];\n\t\tGearMenus.tools.push({\n\t\t\tcName : theTool.infoname,\n\t\t\tcReturn : !theTool.name || theTool.name === \"-\" ? null : \"tool#\" + toolsArray[i]\n\t\t});\n\t};\n}",
"function addCreeps()\r\n{\r\n // add a creep in all the start/spawn positions\r\nfor (var a = 0 ; a < MAP_INFO.start.length ; a++)\r\n {\r\n var position = MAP_INFO.start[ a ];\r\n\r\n var creep = new Creep({\r\n column: position.column,\r\n line: position.line,\r\n health: CREEP_HEALTH,\r\n category: CATEGORIES.creep\r\n });\r\n CREEPS_CONTAINER.addChild( creep );\r\n }\r\n\r\n // increase the creeps health\r\nCREEP_HEALTH += 15;\r\n}",
"addplant(plant) {\n this.plants.push(plant);\n }",
"addHearthToInventory(brand, item) {\n this.inventory.push({ brand, item });\n }",
"function SetCarriedLocations() {\n\tvar type = event.target.name.substring(0,10) === \"Extra.Gear\" ? \"Extra.Gear \" : \"Adventuring Gear \";\n\tvar row = parseFloat(event.target.name.slice(-2));\n\tvar total = type === \"Extra.Gear \" ? FieldNumbers.extragear : FieldNumbers.gear;\n\tvar theEvent = clean(event.target.value, \" \");\n\tvar locationList = [];\n\tvar locationTestList = [];\n\t//loop through all the fields and add any found locations to the array\n\tfor (var i = 1; i <= total; i++) {\n\t\tvar theLoc = clean(What(type + \"Location.Row \" + i), \" \");\n\t\tif (i !== row && theLoc !== \"\" && locationTestList.indexOf(theLoc.toLowerCase()) === -1) {\n\t\t\tlocationList.push(theLoc);\n\t\t\tlocationTestList.push(theLoc.toLowerCase());\n\t\t} else if (i === row && theEvent !== \"\" && locationTestList.indexOf(theEvent.toLowerCase()) === -1) {\n\t\t\tlocationList.push(theEvent);\n\t\t\tlocationTestList.push(theEvent.toLowerCase());\n\t\t}\n\t}\n\tlocationList.sort();\n\t//loop through the list of locations and add the first 6 found to the subtotal fields\n\tvar locationFields = type === \"Extra.Gear \" || !typePF ? 6 : 9;\n\tfor (var i = 0; i < locationFields; i++) {\n\t\tvar aLoc = locationList[i] ? locationList[i] : \"\";\n\t\tValue(type + \"Location.SubtotalName \" + (i + 1), aLoc);\n\t}\n}",
"addPlate(state, plateObj) {\n state.cart.push(plateObj);\n }",
"function GearSet(name,bodyarmor,backpack,mask,gloves,kneepads,holster) {\r\n this.name = name;\r\n\t\r\n this.bodyarmor = bodyarmor;\r\n\tthis.backpack = backpack;\r\n\t\r\n this.mask = mask;\r\n this.gloves = gloves;\r\n\t\r\n\tthis.kneepads = kneepads;\r\n\tthis.holster = holster;\r\n\tthis.type = \"gearset\";\r\n\t\r\n\t\r\n}",
"function addGem(){\n if(allGems.length < 3){ \n var x = Math.floor(Math.random()*5)*ctx.cellWidth +30;\n var y = (Math.floor(Math.random()*5+1)*ctx.cellHeight) + 60;\n // prevent put 2 gem in the same position\n allGems.forEach(function(gem) {\n if(gem.x === x && gem.y === y)\n addGem();\n return;\n });\n allGems.push(new Gem(x,y,\n Gem.spirites[Math.floor(Math.random()*3)]));\n }\n}",
"addFuel(){\n console.log(\"Fuel added\")\n }",
"function addPlanet() {\r\n \r\n var newOrbit = $('<div>')\r\n .addClass(`orbit device-orbit orb${count}`)\r\n .attr('data-itemid', count);\r\n \r\n var newPlanet = $('<div>')\r\n .addClass('planet device-planet')\r\n .attr('data-itemid', count);\r\n \r\n $(newPlanet).append($('<text>').text(count));\r\n \r\n \r\n \r\n var speed = Math.floor(Math.random() * 10) + 20;\r\n \r\n $(newOrbit).css('animation', `spin-right ${speed}s linear infinite`)\r\n .css('margin', `${margin}px 0 0 ${margin}px`)\r\n .css('width', `${size}px`)\r\n .css('height', `${size}px`)\r\n .css('z-index', `${zindex}`);\r\n \r\n $(newOrbit).append(newPlanet);\r\n $('.system').append(newOrbit);\r\n \r\n var name = items[count].name;\r\n var sig = items[count].signal;\r\n var infoText = $('<text>').text(`${count}. ${name} (${sig})`);\r\n $(infoText).addClass(`info-text info-text-${count}`);\r\n $(infoText).attr('data-itemid', count);\r\n $('.side-nav').append(infoText);\r\n \r\n size += 100;\r\n margin -= 50;\r\n count += 1;\r\n zindex -= 1;\r\n}",
"initMap(planets, rocketDef) {\n this.planets = planets;\n _.each(planets, this.addShape.bind(this));\n\n let rocket = new Rocket(_.merge(rocketDef, {\n smokeImg: this.images['cloud.png'],\n img: this.images['rocket.png'],\n width: ROCKET.WIDTH * ROCKET.FACTOR, height: ROCKET.HEIGHT * ROCKET.FACTOR,\n\n regX: ROCKET.WIDTH * (ROCKET.FACTOR / 2),\n // Adding five so it looks like the approx central mass point\n regY: (ROCKET.HEIGHT / 4) + ROCKET.H_OFFSET\n }));\n\n this.rocket = rocket;\n this.addShape(rocket);\n }",
"addToBackpack(item) {\n\t\t// TODO #3-5: practice TDD and code this in parts as you write tests\n\t\tif (item.location === \"front pocket\") {\n\t\t\tthis.frontPocket.push(item);\n\t\t} else if (item.location === \"side pocket\") {\n\t\t\tthis.sidePocket = item;\n\t\t} else {\n\t\t\titem.location = \"main compartment\";\n\t\t\tthis.main.push(item);\n\t\t}\n\t}",
"function setupGarlic() {\n garlicVX = 1;\n garlicVY = 1;\n garlicSize = 20;\n garlicX = int(random(0, width-garlicSize));\n garlicY = int(random(height/8, height-garlicSize));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that calculates the points for the upper table (Ones to Sixes). Does it by checking each element in the dice_values array and multiplies them by the index i.e If there are 5x threes it will multiply the element (5) by the index number (3) and return 15. | upperTablePoints(){
let pointsArray = [0, 0, 0, 0, 0, 0, 0];
//[0, 2, 1, 0, 0, 2, 0] -> 2*1 + 1*2 + 2*5 = 14
// pointsArray = [0, 2, 2, 0, 0, 10, 0]
this.dice_values.forEach((element,index)=>{
pointsArray[index] = element * index;
})
return pointsArray;
} | [
"function numRollsToTarget (d, f, t) {\n let dp = [...Array(d + 1)].map(() => Array(t + 1).fill(0));\n dp[0][0] = 1;//each index corresponds to the number of ways you can get to that position\n for (let i=1; i <= d; i++)//number of dice\n for (let j=1; j <= t; j++)//amount\n for (let k=1; k <= f; k++)//number of sides\n if (j - k >= 0)//current amount has to be greater than or equal to the number on current side\n dp[i][j] = (dp[i][j] + dp[i - 1][j - k]) % (1e9 + 7);//how many ways witht he previous die could you reach this amount before adding the current die\n console.log(dp);\n return dp[d][t];\n}",
"function points(dice) {\n let newDice = dice.split('').sort((a,b)=> a - b);\n \n if(newDice.filter(x => x == newDice[0]).length == 5){\n return 50;\n };\n \n if(newDice.filter(x => x == newDice[0]).length == 4 || newDice.filter(x => x == newDice[dice.length - 1]).length == 4){\n return 40;\n };\n \n if(newDice.filter(x => x == newDice[0]).length == 3 && newDice.filter(x => x == newDice[dice.length - 1]).length == 2 || \n newDice.filter(x => x == newDice[0]).length == 2 && newDice.filter(x => x == newDice[dice.length - 1]).length == 3){\n return 30;\n };\n \n if(newDice.join('') == '12345' || newDice.join('') == '23456' || newDice.join('') == '13456'){\n return 20;\n };\n \n return 0;\n}",
"function dice( ){\n var out = []; result = [];\n var dices = arguments[0], value = arguments[1], success = arguments[2];\n if ( value.constructor === Array ) {\n for (var j = 0; j < value.length; j++) {\n for (var i = 0; i < dices; i++) {\n out[j] += Math.floor( Math.random() * 6 ) + 1;\n }\n }\n }else{\n // Single throw\n out = 0; result = 0;\n var dicesum = 0;\n for (var h = 0; h < dices; h++) {\n out += Math.floor( Math.random() * 6 ) + 1;\n }\n switch (success) {\n\n case 1: // or more\n if ( out >= value ) return 1; else return 0;\n break;\n\n case -1: // or less\n if ( out <= value ) return 1; else return 0;\n break;\n\n case 0: // exactly\n if ( out == value ) return 1; else return 0;\n break;\n }\n }\n return out;\n}",
"function score(dice) {\n\n let result = 0;\n let newArr = [];\n for (let i=1; i<=6; i++){\n newArr.push(dice.filter((num) => num === i))\n }\n\n console.log(newArr);\n\n switch (newArr[0].length){\n case 0:\n break;\n\n case 1:\n result += 100;\n break;\n\n case 2:\n result += 200;\n break;\n\n case 3:\n result += 1000;\n break;\n\n case 4:\n result += 1100;\n break;\n\n case 5:\n result += 1200;\n break;\n }\n\n switch (newArr[4].length){\n case 0:\n break;\n\n case 1:\n result += 50;\n break;\n\n case 2:\n result += 100;\n break;\n\n case 4:\n result += 50;\n break;\n\n case 5:\n result += 100;\n break;\n }\n\n\n let score = 600;\n for (let i=5; i>0; i--){\n if (newArr[i].length >= 3){\n result += score;\n }\n score -= 100;\n }\n\n\nreturn result;\n\n \n \n}",
"function score( dice ) {\n var counts = [0,0,0,0,0,0];\n var tripletScores = [1000,200,300,400,500,600];\n var singleScores = [100,0,0,0,50,0];\n dice.forEach(function(rolledNumber){ counts[rolledNumber-1]++; }); // count of each number rolled\n return counts.reduce(function(sum,rolledNumber,i){ \n return sum + (rolledNumber >= 3? tripletScores[i] : 0) + singleScores[i]*(rolledNumber % 3);\n },0);\n}",
"function chancePoints() {\n let sum = 0;\n for (let i = 0; i < dice.length; i++) {\n sum += dice[i].value;\n }\n return sum;\n}",
"function calcChance(diceCount){\r\n let rest=5; //Use only 5 (largest) dice \r\n let sum=0; \r\n for(let i=d2i(maxDice);i>=d2i(minDice) && rest>0; i--)\r\n for(let j=0;j<diceCount[i] && rest>0; j++){\r\n sum += i2d(i);\r\n rest--;\r\n }\r\n return sum;\r\n}",
"function findAverage(dieValueArray) {\r\n\r\n // Reset all counters before loop starts\r\n ones = 0;\r\n twos = 0;\r\n threes = 0;\r\n fours = 0;\r\n fives = 0;\r\n sixes = 0;\r\n\r\n // loop will run through array and increment counters based on die values in the array\r\n for( var j=0; j < dieValueArray.length; j++ ) {\r\n switch(dieValueArray[j]) {\r\n case 1:\r\n ones++;\r\n break;\r\n case 2:\r\n twos++;\r\n break;\r\n case 3:\r\n threes++;\r\n break;\r\n case 4:\r\n fours++;\r\n break;\r\n case 5:\r\n fives++;\r\n break;\r\n case 6:\r\n sixes++;\r\n break;\r\n default:\r\n \"Nothing to increment\"\r\n break;\r\n }\r\n }\r\n\r\n // Calculate percentage on roll values\r\n var onesPercentage = (ones / dieValueArray.length) * 100;\r\n var twosPercentage = (twos / dieValueArray.length) * 100;\r\n var threesPercentage = (threes / dieValueArray.length) * 100;\r\n var foursPercentage = (fours / dieValueArray.length) * 100;\r\n var fivesPercentage = (fives / dieValueArray.length) * 100;\r\n var sixesPercentage = (sixes / dieValueArray.length) * 100;\r\n\r\n // Output the percentage values to the screen\r\n document.getElementById(\"percentageValue\").innerHTML = \"Number of Die Rolls so far: \" + dieValueArray.length + \"<br><br>\" +\r\n \"Percentage of 1s Rolled: \" + onesPercentage.toFixed(2) + \"%<br>\" +\r\n \"Percentage of 2s Rolled: \" + twosPercentage.toFixed(2) + \"%<br>\" +\r\n \"Percentage of 3s Rolled: \" + threesPercentage.toFixed(2) + \"%<br>\" +\r\n \"Percentage of 4s Rolled: \" + foursPercentage.toFixed(2) + \"%<br>\" +\r\n \"Percentage of 5s Rolled: \" + fivesPercentage.toFixed(2) + \"%<br>\" +\r\n \"Percentage of 6s Rolled: \" + sixesPercentage.toFixed(2) + \"%<br>\";\r\n}",
"function roll4d6Scores() {\n let rawScores = [];\n\n for (let i = 0; i < 4; i += 1) {\n rawScores.push(diceRoll(1, 6));\n }\n rawScores.sort().shift();\n rawScores = rawScores.reduce((a, b) => a + b, 0);\n return rawScores;\n}",
"function score( dice ) {\r\n \r\n let score = 0;\r\n let ones = 0, twos = 0 , threes = 0, fours = 0 , fives = 0, sixes = 0;\r\n\r\n for ( let i = 0; i < dice.length; i++) {\r\n if ( dice[i] == 1) ones++;\r\n if ( dice[i] == 2) twos++;\r\n if ( dice[i] == 3) threes++;\r\n if ( dice[i] == 4) fours++;\r\n if ( dice[i] == 5) fives++;\r\n if ( dice[i] == 6) sixes++;\r\n \r\n }\r\n \r\n if ( ones >= 3) {\r\n score+=1000;\r\n ones-=3;\r\n }\r\n if ( ones < 3 ) {\r\n score+=ones*100;\r\n }\r\n if ( twos >= 3) {\r\n score+=200;\r\n }\r\n if ( threes >= 3) {\r\n score+=300;\r\n }\r\n if ( fours >= 3) {\r\n score+=400;\r\n }\r\n if ( fives >= 3) {\r\n score+=500;\r\n fives-3\r\n }\r\n if ( fives < 3 ) {\r\n score+=fives*50;\r\n}\r\n if ( sixes >= 3) {\r\n score+=600;\r\n }\r\n\r\n return score;\r\n }",
"function calculateRollScore() {\n\ttempScore = 0;\n\t$(\"#roll-score\").text(addCommas(tempScore));\n\tvar ones = [];\n\tvar twos = [];\n\tvar threes = [];\n\tvar fours = [];\n\tvar fives = [];\n\tvar sixes = [];\n\tvar scoreArray = [];\n\tfor (var i = 0; i < 6; i++) {\t\t\t\t\t\t\t//test out totals, etc.\n\t\tif (diceArray[i].state === 1) {\n\t\t\tswitch (diceArray[i].value) {\n\t\t\t\tcase 1: ones.push(1);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\tcase 2: twos.push(2);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\tcase 3: threes.push(3);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\tcase 4: fours.push(4);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\tcase 5: fives.push(5);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\tcase 6: sixes.push(6);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tswitch (ones.length) {\n\t\tcase 1: scoreArray[0] = 100; break;\n\t\tcase 2: scoreArray[0] = 200; break;\n\t\tcase 3: scoreArray[0] = 1000; break;\n\t\tcase 4: scoreArray[0] = 2000; break;\n\t\tcase 5: scoreArray[0] = 3000; break;\n\t\tcase 6: scoreArray[0] = 4000; break;\n\t\tdefault: scoreArray[0] = 0;\n\t}\n\tswitch (twos.length) {\n\t\tcase 3: scoreArray[1] = 200; break;\n\t\tcase 4: scoreArray[1] = 400; break;\n\t\tcase 5: scoreArray[1] = 600; break;\n\t\tcase 6: scoreArray[1] = 800; break;\n\t\tdefault: scoreArray[1] = 0;\n\t}\n\tswitch (threes.length) {\n\t\tcase 3: scoreArray[2] = 300; break;\n\t\tcase 4: scoreArray[2] = 600; break;\n\t\tcase 5: scoreArray[2] = 900; break;\n\t\tcase 6: scoreArray[2] = 1200; break;\n\t\tdefault: scoreArray[2] = 0;\n\t}\n\tswitch (fours.length) {\n\t\tcase 3: scoreArray[3] = 400; break;\n\t\tcase 4: scoreArray[3] = 800; break;\n\t\tcase 5: scoreArray[3] = 1200; break;\n\t\tcase 6: scoreArray[3] = 1600; break;\n\t\tdefault: scoreArray[3] = 0;\n\t}\n\tswitch (fives.length) {\n\t\tcase 1: scoreArray[4] = 50; break;\n\t\tcase 2: scoreArray[4] = 100; break;\n\t\tcase 3: scoreArray[4] = 500; break;\n\t\tcase 4: scoreArray[4] = 1000; break;\n\t\tcase 5: scoreArray[4] = 1500; break;\n\t\tcase 6: scoreArray[4] = 2000; break;\n\t\tdefault: scoreArray[4] = 0;\n\t}\n\tswitch (sixes.length) {\n\t\tcase 3: scoreArray[5] = 600; break;\n\t\tcase 4: scoreArray[5] = 1200; break;\n\t\tcase 5: scoreArray[5] = 1800; break;\n\t\tcase 6: scoreArray[5] = 2400; break;\n\t\tdefault: scoreArray[5] = 0;\n\t}\n\ttempScore = scoreArray[0] + scoreArray[1] + scoreArray[2] + scoreArray[3] + scoreArray[4] + scoreArray[5];\n\t$(\"#roll-score\").text(addCommas(tempScore));\n\tif(player1.turn === true) {\n\t\t$(\"#player1-roll\").text(addCommas(tempScore));\n\t\ttempRoundScore = roundScore + tempScore;\n\t\t$(\"#player1-round\").text(addCommas(tempRoundScore));\n\t} else {\n\t\t$(\"#player2-roll\").text(addCommas(tempScore));\n\t\ttempRoundScore = roundScore + tempScore;\n\t\t$(\"#player2-round\").text(addCommas(tempRoundScore));\n\t}\n}",
"function calcTwoPairs(diceCount){\r\n let found=0;\r\n let pair=[];\r\n for(let i=d2i(maxDice);i>=d2i(minDice) && found <2; i--)\r\n if(diceCount[i]>=2){ \r\n pair[found]= i2d(i)*2;\r\n found++;\r\n }\r\n if(found===2) \r\n return pair[0]+pair[1];\r\n else \r\n return 0;\r\n}",
"function generateDiceVals(desertIdx) {\n var newDiceValues = []; // Updated dice values in regular order\n \n // Values of dice in normal order\n var diceValues = [6, 5, 9, 4, 3, 8, 10, 6, 5, 9, 12, 3, 2, 10, 11, 11, 4, 8];\n \n // Indices into diceValues in spiral order\n var spiralHexIdxs = [0, 3, 7, 12, 16, 17, 18, 15, 11, 6, 2, 1, 4, 8, 13, 14, 10, 5, 9];\n \n // Dice values in spiral order omitting the desert dice value \n var spiralDiceValues = [6, 4, 6, 3, 11, 4, 8, 11, 12, 10, 9, 5, 3, 5, 2, 10, 9, 8];\n \n // Add the \"desert\" dice value at the index of the \"desert\" hex\n spiralDiceValues.splice(spiralHexIdxs.indexOf(desertIdx), 0, 7);\n \n // Translate spiral dice values into normal order\n for (var i = 0; i < spiralHexIdxs.length; i++) {\n newDiceValues.push(spiralDiceValues[spiralHexIdxs.indexOf(i)]);\n }\n return newDiceValues;\n\n}",
"calculateDiceValues(){\n this.dice.map(current_value => {\n this.dice_values[current_value.value]++;\n })\n }",
"function yatzyPoints() {\n let freq = frequency();\n for (let i = 1; i < freq.length; i++) {\n if (freq[i] == 5) {\n return 50;\n\n }\n }\n return 0;\n}",
"function drawDiceOnTable() {\n\tdieIndexHolder = [0,1,2,3,4]; // Reset die index holder\n\n\tfor (let i = diceOnTable.length - 1; i >= 0; i--) {\n\t\tdrawDieOnTable(diceOnTable[i], dieIndexHolder[i]);\n\t}\n\n\t// Assign new indices for dice left over from the last roll (so they don't get placed on top of the new dice when de-selected)\n\tupdateSelectedDiceElements();\n\tif (selectedDiceElements) {\n\t\tfor (let j = 0; j < selectedDiceElements.length; j++) {\n\t\t\tselectedDiceElements[j].setAttribute('die-index', diceOnTable.length + j);\n\t\t}\n\t}\n}",
"function checkForStraights(noOfPlayers, noOfCards, playerArrayValue, playerHandsValues) {\n let straightCounter\n let numberToCheck\n let largerNumberToCheck\n for (let h = 0; h < noOfPlayers; h += 1) {\n straightCounter = 0;\n for (let i = 0; i < (noOfCards - 1); i += 1) {\n numberToCheck = playerArrayValue[h][i];\n largerNumberToCheck = playerArrayValue[h][i + 1];\n if (largerNumberToCheck - numberToCheck === 1) {\n straightCounter += 1;\n }\n }\n if (straightCounter === 5) {\n playerHandsValues[h] += 40;\n }\n }\n return playerHandsValues\n }",
"function returnSixNumbers() {\n var abilityScores = [];\n\n for (let i = 0; i < 6; i++) {\n abilityScores.push(roll4D6RemoveLowestAndSum());\n }\n\n return abilityScores;\n}",
"function displayScore()\n{\n //Array for basic totals of die rolls ==> sub\n var basicScoreCount = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0};\n var basicScoreTally= {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0};\n //Array for complex totals of die rolls ==> sub2\n var complexScoreTally = [0, 0, 0, 0, 0, 0, 0];\n\n //Bonus only available if sub >= 63\n var bonus = 0;\n\n //Array for all the dice\n var diceArray = getDiceValues();\n for (var i = 0; i < 5; i++)\n {\n basicScoreCount[diceArray[i]] += diceArray[i];\n }\n\n //Clear the previous temporary scores from the roll\n resetBoard();\n\n //Display the basic score combos (left hand side scoring)\n for (var i = 1; i <= 6; i++)\n {\n if(basicScoreCount[i] == 0)\n {\n continue;\n }\n switch (i){\n case 1:\n changeElement(\"ones\", basicScoreCount[1], \"red\");\n break;\n case 2:\n changeElement(\"twos\", basicScoreCount[2], \"red\");\n break;\n case 3:\n changeElement(\"threes\", basicScoreCount[3], \"red\");\n break;\n case 4:\n changeElement(\"fours\", basicScoreCount[4], \"red\");\n break;\n case 5:\n changeElement(\"fives\", basicScoreCount[5], \"red\");\n break;\n case 6:\n changeElement(\"sixes\", basicScoreCount[6], \"red\");\n break;\n }//end switch\n\n }//end for\n\n //Begin work on right-hand side of board\n diceArray.sort();\n diceArray = diceArray.join(\"\");\n\n //Use regular expressions to find possible scores\n\n /***************** RULES FOR RIGHT HAND SIDE SCORING *****************\n * 3 Of A Kind --> At least 3 of the same value, add total of all dice\n * 4 Of A Kind --> At least 4 of the same value, add total of all dice\n * Small Straight --> 4 consecutive dice values. 30 points.\n * Large Straight --> 5 consecutive dice values. 40 points.\n * Full House --> 3 of a kind and 2 of a kind. 25 points.\n * Yahtzee --> 5 of a kind. 50 points.\n * Chance --> Sum of all dice values. No special rules.\n **********************************************************************/\n //if 3 of a kind\n if (/(.)\\1{2}/.test(diceArray))\n {\n changeElement(\"3kind\", getTotalValues(), \"red\");\n }\n //if 4 of a kind\n if (/(.)\\1{3}/.test(diceArray))\n {\n changeElement(\"4kind\", getTotalValues(), \"red\");\n }\n //if small straight\n if (/1234|2345|3456|12234|12334|23345|23445|34456|34556/.test(diceArray))\n {\n changeElement(\"smallStraight\", 30, \"red\");\n }\n //if large straight\n if (/12345|23456/.test(diceArray))\n {\n changeElement(\"largeStraight\", 40, \"red\");\n }\n //if full house\n if (/(.)\\1{2}(.)\\2|(.)\\3(.)\\4{2}/.test(diceArray))\n {\n changeElement(\"fullHouse\", 25, \"red\");\n }\n //if yahtzee\n if (/(.)\\1{4}/.test(diceArray))\n {\n changeElement(\"yahtzee\", 50, \"red\");\n }\n\n //Chance\n changeElement(\"chance\", getTotalValues(), \"red\");\n\n //Loop through and display zeros for all remaining score elements\n var scoreArray = document.getElementsByName(\"scoring\");\n\n for (var i = 0; i < scoreArray.length - 1; i++)\n {\n if (document.getElementById(scoreArray[i].id).innerHTML == \"\"\n || document.getElementById(scoreArray[i].id).innerHTML == null)\n {\n changeElement(scoreArray[i].id, 0, \"red\");\n }\n }//end for\n}//end function"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the position from the spherical coordinates | function calcPos() {
// Current coordinates
var coords = sphoords.getCoordinates();
var coords_deg = sphoords.getCoordinatesInDegrees();
// Corresponding position on the sphere
return {
x: radius * Math.cos(coords.latitude) * Math.sin(coords.longitude),
y: radius * Math.cos(coords.latitude) * Math.cos(coords.longitude),
z: radius * Math.sin(coords.latitude),
long: coords_deg.longitude,
lat: coords_deg.latitude,
orientation: sphoords.getScreenOrientation()
};
} | [
"function sphericalCoords (ev) {\n var point = TAGGER.graphics.eventCoords(ev);\n return TAGGER.orientation.sCoords(point);\n }",
"function sphericalX(r, theta, phi) {\n return r * sin(theta) * cos(phi);\n}",
"static get spherical() {\n return geometry;\n }",
"function spherical(cartesian) {\n return [Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"g\" /* atan2 */])(cartesian[1], cartesian[0]) * __WEBPACK_IMPORTED_MODULE_1__math__[\"j\" /* degrees */], Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"e\" /* asin */])(Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"q\" /* max */])(-1, Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"r\" /* min */])(1, cartesian[2]))) * __WEBPACK_IMPORTED_MODULE_1__math__[\"j\" /* degrees */]];\n}",
"function SphericalPoint(radius = 0.0, theta = 0.0, phi = 0.0, normalization = 1.0) {\n var newTheta = convertPolarAngle(theta);\n var newPhi = convertAxialAngle(phi);\n Point.call(this, radius, newTheta, newPhi, normalization);\n}",
"function spherical(cartesian) {\n return [atan2(cartesian[1], cartesian[0]) * degrees, asin(max(-1, min(1, cartesian[2]))) * degrees];\n }",
"computeCoords() {\n this.distanceFromEarthCenter = bv3.length(this.position)\n this.distanceFromEarthSurface = this.distanceFromEarthCenter - 6378\n\n this.lat = radians2degrees(Math.asin(-this.position[1] / this.distanceFromEarthCenter))\n\n\n const posAtEquator = [this.position[0], 0, this.position[2]]\n\n\n const distanceFromEarthCenterAtEquator = bv3.length(posAtEquator)\n const l90 = radians2degrees(Math.asin(-this.position[0] / distanceFromEarthCenterAtEquator))\n\n\n if (this.position[0] > 0 != this.position[2] > 0) {\n if (this.position[0] > 0) {\n //CCconsole.log(\"c1\")\n this.lon = l90;\n } else {\n //CCconsole.log(\"c2\")\n this.lon = 180 - l90;\n }\n } else {\n if (this.position[0] > 0) {\n //CCconsole.log(\"c3\")\n this.lon = -180 - l90;\n } else {\n //CCconsole.log(\"c4\")\n this.lon = l90;\n }\n }\n\n \n }",
"function get_sphere_coordinates( x, y )\n\t{\n\t\treturn new Vector(\n\t\t\t-x,\n\t\t\ty,\n\t\t\tMath.sqrt( radius * radius - x * x - y * y )\n\t\t);\n\t}",
"function spherical(cartesian) {\n return [\n Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"g\" /* atan2 */])(cartesian[1], cartesian[0]) * __WEBPACK_IMPORTED_MODULE_1__math__[\"j\" /* degrees */],\n Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"e\" /* asin */])(Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"q\" /* max */])(-1, Object(__WEBPACK_IMPORTED_MODULE_1__math__[\"r\" /* min */])(1, cartesian[2]))) * __WEBPACK_IMPORTED_MODULE_1__math__[\"j\" /* degrees */]\n ];\n}",
"function spherical(cartesian) {\n return [\n Object(_math_js__WEBPACK_IMPORTED_MODULE_1__[\"atan2\"])(cartesian[1], cartesian[0]) * _math_js__WEBPACK_IMPORTED_MODULE_1__[\"degrees\"],\n Object(_math_js__WEBPACK_IMPORTED_MODULE_1__[\"asin\"])(Object(_math_js__WEBPACK_IMPORTED_MODULE_1__[\"max\"])(-1, Object(_math_js__WEBPACK_IMPORTED_MODULE_1__[\"min\"])(1, cartesian[2]))) * _math_js__WEBPACK_IMPORTED_MODULE_1__[\"degrees\"]\n ];\n}",
"function spherical(cartesian) {\n return [\n __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__math_js__[\"h\" /* atan2 */])(cartesian[1], cartesian[0]) * __WEBPACK_IMPORTED_MODULE_1__math_js__[\"p\" /* degrees */],\n __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__math_js__[\"i\" /* asin */])(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__math_js__[\"m\" /* max */])(-1, __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__math_js__[\"n\" /* min */])(1, cartesian[2]))) * __WEBPACK_IMPORTED_MODULE_1__math_js__[\"p\" /* degrees */]\n ];\n}",
"function sphericalDistance(a, b) {\n\t var x = lonToMeters(a[0] - b[0], (a[1] + b[1]) / 2),\n\t y = latToMeters(a[1] - b[1]);\n\t return Math.sqrt((x * x) + (y * y));\n\t}",
"function sphericalDistance(a, b) {\n var x = lonToMeters(a[0] - b[0], (a[1] + b[1]) / 2),\n y = latToMeters(a[1] - b[1]);\n return Math.sqrt((x * x) + (y * y));\n }",
"function spherical(cartesian) {\n return [\n Math.atan2(cartesian[1], cartesian[0]) * degrees,\n Math.asin(Math.max(-1, Math.min(1, cartesian[2]))) * degrees\n ];\n}",
"static findAngleSpherical( s1, s2 ) {\n\n\t\tvar dphi = s2.phi - s1.phi;\n\t\tvar dtheta = s2.theta - s1.theta;\n\n\t\treturn Math.atan2( dphi, Math.sin( s1.phi ) * dtheta );\n\n\t}",
"galLat(){\n let gpRA = 3.366; // Galactic pole RA (radians)\n let gpDec = 0.4734; // Galactic pole Dec(radians)\n let d = sin(gpDec) * sin(this.y) + cos(gpDec) *\n cos(this.y) * cos(this.x-gpRA);\n return asin(d)/toRadians;\n }",
"function geoSphericalDistance(a, b) {\n var x = geoLonToMeters(a[0] - b[0], (a[1] + b[1]) / 2);\n var y = geoLatToMeters(a[1] - b[1]);\n return Math.sqrt((x * x) + (y * y));\n }",
"function spherical2cartesian( radius, theta, phi )\n{\n return vec3( radius * Math.sin(theta) * Math.cos(phi),\n radius * Math.sin(theta) * Math.sin(phi),\n radius * Math.cos(theta) );\n}",
"function sphericalToCartesian(r,θ,ϕ){\n θ=θ*TAU/360;\n ϕ=ϕ*TAU/360;\n x=r*Math.sin(ϕ)*Math.cos(θ);\n y=r*Math.sin(ϕ)*Math.sin(θ);\n z=r*Math.cos(ϕ);\n let cord=[x,y,z];\n return cord;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a link to the tree view version of this view | function linkToTreeView() {
var answer = null;
if ($scope.contextId) {
var node = null;
var tab = null;
if ($scope.endpointPath) {
tab = "browseEndpoint";
node = workspace.findMBeanWithProperties(Camel.jmxDomain, {
context: $scope.contextId,
type: "endpoints",
name: $scope.endpointPath
});
}
else if ($scope.routeId) {
tab = "routes";
node = workspace.findMBeanWithProperties(Camel.jmxDomain, {
context: $scope.contextId,
type: "routes",
name: $scope.routeId
});
}
var key = node ? node["key"] : null;
if (key && tab) {
answer = "#/camel/" + tab + "?tab=camel&nid=" + key;
}
}
return answer;
} | [
"function TreeView() {\n this.anchor = '';\n this.collapsible = true;\n this.initiallyCollapsed = true;\n this.icons = {};\n this.icons.dirOpen = 'fa fa-folder-open';\n this.icons.dirClosed = 'fa fa-folder';\n this.icons.file = 'fa fa-file';\n this.icons.active = true;\n this.ommit = [];\n}",
"function SFAbstractTreeView() {\n\n}",
"createCatTree() {\n //tree wrapper: \n const wrapper = eHtml({ class: 'catTreeWrapper' });\n //tree links container\n const container = eHtml({ class: 'catTreeContainer', container: wrapper });\n //home link\n const home = eHtml({ class: 'body-nav', html: '<a href=' + this.links.home + '>Home</a>', container: container });\n //slash\n const slash = eHtml({ class: 'body-nav body-nav-slash', text: '/', container: container });\n //categories link\n const categories = eHtml({ class: 'body-nav', html: '<a href=' + this.links.categoriesLink + '>Categories</a>', container: container });\n //loop throw each parent: \n this.catTree.reverse().forEach((cat) => {\n //append slash\n container.append(slash.clone(true));\n //create cat container: \n const cContainer = eHtml({\n class: 'body-nav-cat body-nav',\n html: '<a href=' + this.catLink + cat._id + '>' + cat.title + '</a>',\n container: container\n });\n })\n return wrapper;\n }",
"function setupTreeView() {\n var tree = new blacksmith.tree();\n tree.anchor = '#tree-view';\n tree.ommit = ['.git', '.sass-cache', 'node_modules', 'vendor'];\n tree.render().setFileClickEvent(function() {\n openFile($(this).attr('data-path'));\n resizeTabs();\n });\n}",
"clone() {\n return this.type.getView(new persistent_merkle_tree_1.Tree(this.node));\n }",
"function TreeItemView() {\n\tvar $dom = $(\"<div class='tree-item' />\");\n\tvar $content = $(\"<div class='tree-item-content' />\").appendTo($dom);\n\tvar $children = $(\"<div class='tree-item-children' />\").appendTo($dom);\n\n\tvar children = [];\n\n\tvar self = smokesignals.convert({\n\t\t$dom: $dom,\n\t\t$content: $content,\n\t\t$children: $children,\n\t\tappend: function (itemView) {\n\t\t\tchildren.push(itemView);\n\t\t\t$children.append(itemView.$dom);\n\t\t},\n\t\tremove: function () {\n\t\t\tthis.$dom.detach();\n\t\t\tself.emit(\"removed\", self);\n\t\t}\n\t});\n\n\treturn self;\n}",
"function onTreeviewClick(){\n View.controllers.get('abScDefPost').curTreeNode = View.panels.get(\"abScDefPostTree\").lastNodeClicked;\n}",
"function getTreeUrl() {\n return url_1.URLExt.join(getBaseUrl(), getOption('treeUrl'));\n }",
"function makeTreeDataViews() {\n var $div = $('#template > .dataTreeViewRow' ).clone();\n $div.find( \".treeViewClass\" ).attr( \"id\", \"treeview\" );\n $div.find( \".dataViewClass\" ).attr( \"id\", \"dataview\" );\n $div.show();\n return $div;\n}",
"tree() {\n return 'Menu Tree\\n' + responderTree(this._responder);\n }",
"createTreeItem() {\n var item = new latte.TreeItem();\n item.tag = this;\n this._treeItem = item;\n this.syncUI();\n return item;\n }",
"function TreeView( styleBorder, icoRacine, txtRacine, style, styleOnOver, funOnClick )\n{\n\t// chaine contenant l'icone de la racine\n\tthis.icone = icoRacine\n\n\t// chaine contenant le texte situé à côté de l'icone\n\tthis.texte = txtRacine\n\n\t// chaine contenant la classe de style du texte\n\tthis.style = style\n\n\t// chaine contenant la classe de style lorsque le curseur est dessus\n\tthis.styleOnOver = styleOnOver\n\n\t// chaine contenant la fonction à appeler lors d'un clique sur le texte\n\tthis.onClick = funOnClick\n\n\t// Chaine contenant l'index (unique) du noeud\n\tthis.index = \"0\"\n\n\t// entier contenant la taille horizontale (en pixel) du cadre de la treeview\n\tthis.styleBorder = styleBorder\n\n\t// Nom de la table qui contient le noeud\n\tthis.table = \"TABLE_\" + this.index\n\n\t// tableau contenant les noeuds fils de la racine\n\tthis.tableauEnfants = new Array\n\n\t// méthodes de la classe\n\tthis.Start = TreeView_Start\n\tthis.Add = TreeView_Add\n\tthis.Contient = TreeView_Contient\n\tthis.Noeuds = TreeView_Noeuds\n}",
"addUrlNode() {\n let jstreeSelectedNodesRight = this.get('jstreeSelectedNodesRight');\n if (jstreeSelectedNodesRight.length === 0) {\n return;\n }\n\n let selectedNodes = jstreeSelectedNodesRight[0].original.get('copyChildren');\n let urlIndex = findFreeNodeTreeNameIndex('NewUrl', '', selectedNodes, 'text');\n let urlId = findFreeNodeTreeID('NU', 0, this.get('jstreeObjectRight'));\n\n let urlValue = FdAppStructTree.create({\n text: 'NewUrl' + urlIndex,\n type: 'url',\n id: 'NU' + urlId,\n caption: 'NewUrl' + urlIndex,\n description: '',\n url: '',\n a_attr: { title: 'url' }\n });\n\n selectedNodes.pushObject(urlValue);\n\n // Restoration tree.\n this._updateTreeData();\n this.get('jstreeActionReceiverRight').send('openNode', jstreeSelectedNodesRight[0]);\n }",
"function expand_node_view(node) {\n}",
"render() {\n return _react.default.createElement(TreeMenuLinkStyle, _extends({}, this.props, {\n selected: this.props.selected\n }), this.props.children);\n }",
"function BasicOView()\n{\n this.tree = null;\n}",
"_addTreeOnPage() {\n this.des.innerHTML = this._buildTreeDom(this.arr);\n }",
"function tree(label, accessKey, parent, children, thumbnail, background, type, style) {\n\tthis.label = label;\n\tthis.accessKey = accessKey;\n\tthis.parent = parent;\n\tthis.children = children;\n\tthis.thumbnail = thumbnail;\n\tthis.background = background;\n\tthis.type = type;\n\tthis.style = style;\n}",
"_createView({ isForce, protoView, isHidden } = {}) {\n\n // destroy any former view that existed in this path\n if (ViewAbstraction.exists(this)) {\n\n if (!isForce) {\n\n return;\n\n }\n\n this.destroy();\n }\n\n if (ViewAbstraction.exists(protoView)) {\n utils.cp((new ViewAbstraction(protoView)).getRoot(), this.configTRef, true);\n }\n\n // create new view\n const fields = {\n title: this.configTRef,\n id: utils.genUUID(), // maybe useful for future purposes…\n };\n\n if (!isHidden) {\n fields[$tm.field.viewMarker] = true;\n }\n\n $tw.wiki.addTiddler(new $tw.Tiddler(\n utils.getTiddler(this.configTRef), // in case we cloned the view\n fields\n ));\n\n this.setEdgeTypeFilter(env.filter.defaultEdgeTypeFilter);\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter Range Alan is good at breaking secret codes. One method is to eliminate values that lie outside of a specific known range. Given arr and values min and max, retain only the array values between min and max. Work inplace: return the array you are given, with values in original order. No builtin array functions. [8,2,6,3,4], min = 3, max = 5; [2,3,4] | function filterRange(arr, minVal, maxVal){
/*
loop through the Array
IF value not between min and max:
move all values after current idx to the left one
and short the length of array
ELSE move on the next idx
*/
for(var i = 0; i < arr.length; i++){
if(arr[i] < minVal || arr[i] > maxVal){
// move everthing coming afterwars to the left one idx
for(var l = i+1; l < arr.length; l++){
arr[l-1] = arr[l];
}
arr.length--; // Decreases length of arr by one like pop()
i--; // cancel i++ operation effectively
}
}
} | [
"function filterRange(arr, min, max){\n // store array length - needed later on for decrementing array length\n var arrLength = arr.length;\n // move values between arr[min] and arr[max] to beginning of array\n for(var i = min+1, j = 0; i < max; i++, j++){\n arr[j] = arr[i];\n }\n // remove remaining values at end of array by decrementing length\n for(var j = 0; j < arrLength - (max-min-1); j++){\n arr.length--;\n }\n return arr;\n}",
"function filterRange(arr,min,max){\n // create index variable to replace values from the beginning with our arr values that fall within min & max\n let index = 0\n\n // iterate over arr\n for (i=0; i<arr.length; i++){\n // check if arr @ index i falls between our min & max constraints\n if (arr[i] <= max && arr[i] >= min){\n // if it does, replace arr @ the value in our index variable with arr @ i\n arr[index] = arr[i]\n // increment index variable so we don't overwrite any values we've changed\n index++\n }\n }\n // shorten our arr length to whatever our index value got up to\n arr.length = index\n return arr\n}",
"function filterRange(arr,min,max){\n var i=0;\n while (i < arr.length){\n if (arr[i] > min && arr[i] < max){\n for (var j = i; j < arr.length-1; j++){\n arr[j] = arr[j+1];\n }\n i--;\n arr.length--;\n }\n i++;\n }\n return arr\n}",
"function filterRange(arr, min, max) {\n let idx = 0;\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] >= min && arr[i] <= max) {\n arr[idx] = arr[i];\n idx++;\n }\n }\n arr.length = idx;\n return arr;\n}",
"function filterRange(arr,min,max)\n{\n var final = 0;\n for (i=0;i<arr.length;i++)\n {\n if(arr[i]<min || arr[i]>max)\n {\n arr[final++] = arr[i];\n }\n }\n arr.length = final;\n return arr;\n}",
"function filterRange(array, min, max) {\n //loop for searching items between min and max in array\n for (var i = 0; i < array.length; i++) {\n //checking items and saving items between min and max in newArray\n if (array[i] >= min && array[i] <= max) newArray[i] = array[i];\n }\n //returning newArray\n return newArray;\n}",
"function filterRange(arr, max, min){\n for(let i=arr.length-1; i>=0; i--){\n if(arr[i] > max || arr[i] < min){\n for(let j=i; j<arr.length-1; j++){\n let temp = arr[j];\n arr[j] = arr[j+1];\n arr[j+1] = temp;\n }\n arr.pop();\n }\n }\n return arr\n}",
"function filterRange1(arr,min,max) {\n for(ind=0; ind <= (max-min); ind++) {\n arr[ind] = arr[min+ind]\n }\n arr.length = (max-min+1)\n return arr\n}",
"function filterBetween(array, min, max) {\n\n}",
"function filterRange(arr, a, b){\r\n const newArr = [];\r\n for(let i = 0; i < arr.length; ++i){\r\n if(arr[i] >= a && arr[i] <= b) newArr.push(arr[i]);\r\n }\r\n return newArr;\r\n}",
"function filterRange(arr, min, max) {\n for (let i=0; i<arr.length; i++) {\n if (arr[i] < min || arr[i] > max) {\n for (let x=i; x<arr.length-1; x++) {\n arr[x] = arr[x+1];\n // console.log(arr[x]);\n }\n arr.length--;\n i--;\n } \n }\n return arr\n}",
"function filterRange(){\n return function(arr, a, b){\n return arr.filter(function(value){\n return value >= a && value <= b;\n });\n }\n }",
"function _filterBetween(values, min, max) {\n let start = 0;\n let end = values.length;\n while (start < end && values[start] < min) {\n start++;\n }\n while (end > start && values[end - 1] > max) {\n end--;\n }\n return start > 0 || end < values.length ? values.slice(start, end) : values;\n}",
"function _filterBetween(values, min, max) {\n var start = 0;\n var end = values.length;\n while (start < end && values[start] < min) {\n start++;\n }\n while (end > start && values[end - 1] > max) {\n end--;\n }\n return start > 0 || end < values.length ? values.slice(start, end) : values;\n }",
"function filterArray(arr, min, max) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] > min && arr[i] < max) {\n removeAt(arr, i);\n i--;\n }\n }\n }",
"function removeVals(arr, start, end) {\n var newArr = [];\n for (var i = 0; i < arr.length; i++) {\n if (start > i || end < i) {\n newArr.push(arr[i]);\n }\n }\n return newArr;\n}",
"function filterRange(arr, a, b) {\n return arr.filter(range => (a <= range && range <= b));\n}",
"function filterRange(arr, a, b) {\n const newArr = arr.filter(item => item >= a && item <= b);\n return newArr;\n}",
"function removeVals(arr, start, end) {\n\tlet newArr = [];\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tif (start > i || end < i) {\n\t\t\tnewArr.push(arr[i]);\n\t\t}\n\t}\n\treturn newArr;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns true if any open order or false | async function haveOpenOrders() {
await traderBot.api('OpenOrders')
.then((res) => result = !helpers.isEmptyObject(res.open))
.catch((rej) => console.log('Грешка!'));
return result;
} | [
"function hasOrder() {\n return this.orders.length > 0;\n }",
"function allOrdersAreComplete(){\r\n\tfor(var i=0; i<orderQueueOrders.length; i++ ){\r\n\t\tif(!orderQueueOrders[i].allOrderItemsComplete){\r\n\t\t\treturn false;\r\n\t\t}\r\n\t} \r\n\treturn true;\r\n}",
"static isOrderDelivered(order) {\n if (order.items == null) return false\n\n const packages = packagify(order)\n if (packages == null || packages.length === 0) return false\n\n return packages.every(item => {\n const { package: pkg } = item\n if (pkg == null || pkg.courierStatus == null) return false\n\n const { courierStatus } = pkg\n const isCourierFinished = courierStatus.finished === true\n\n return isCourierFinished\n })\n }",
"static async getOpenOrders() {\n try {\n return await shopdb.po.findAll({ where: {status: { [Op.ne]: \"CLOSED\"} } });\n } catch (error) {\n throw error;\n }\n }",
"hasOpenIssues() {\n return this._openIssueCount > 0;\n }",
"async OrderExists(ctx, id) {\n const OrderJSON = await ctx.stub.getState(id);\n return OrderJSON && OrderJSON.length > 0;\n }",
"function checkActiveOrders(orders) {\n // TODO if cllosed - close\n if (!tradingIsClosed) {\n orders = JSON.parse(orders);\n let isNoOrders = _.isEmpty(orders);\n \n let sellOrders = _.filter(orders[CURRENCY_PAIR], { type: 'sell' });\n let buyOrders = _.filter(orders[CURRENCY_PAIR], { type: 'buy' });\n \n // To check active orders\n if (!isNoOrders && _.has(orders, CURRENCY_PAIR)) {\n processExistingOrders(sellOrders, buyOrders);\n } else {\n logger.info('No active orders. Need to sell or buy.');\n // to get conts of currency_1 and currency_2\n TRADE.api_query('user_info', {}, sellBuyCallback);\n }\n }\n else {\n logger.info('Trading closed by user.');\n }\n}",
"function isOpen() {\n return STATE.OPEN === this.state;\n }",
"function getOrderIsCompleted() {\n // If no jobId is set, the order cannot be done.\n if (jobId === null) {\n return false;\n }\n // If the order is loading, we are not done...\n if (orderIsLoading) {\n return false;\n }\n // Otherwise, the order should be completed.\n return true;\n }",
"havePackage(order) {\n var canFill = (this.pack.includes(order.package) && this.model.includes(order.model));\n console.log('canFill through ACME', canFill);\n return canFill;\n }",
"isOpen()\n {\n return (this.entryCount < this.entryCapacity);\n }",
"isOpen () {\n return _.contains([ StatusReportStates.assigned, StatusReportStates.inProgress ], this.state)\n }",
"doesClosetHaveOpenDrawers() {\n let closetDrawers=this.closet.getProducts(ProductTypeEnum.DRAWER);\n for(let closetDrawer of closetDrawers)\n if(closetDrawer.isOpen())\n return true;\n return false;\n }",
"isOpen() {\n const result = this.link && this.link.isOpen();\n receiverLogger.verbose(\"%s Receiver for sessionId '%s' is open? -> %s\", this.logPrefix, this.sessionId, result);\n return result;\n }",
"function isClosed(id) {\n\treturn searchOrders(id).isclosed;\n}",
"function canExport() {\n\t\t\treturn self.budget.order_company_id && self.budget.order_status_id == self.internal.orderStatusValues.open;\n\t\t}",
"verifySimpleOrders(){\n if(this.validatePrivileges()){\n this.orders.forEach(order => {\n this.total += order.product.price\n this.skus.push(order.product.productId)\n });\n return true\n }\n return false\n }",
"isOpen() {\n const result = this.link == null ? false : this.link.isOpen();\n senderLogger.verbose(\"%s Sender '%s' with address '%s' is open? -> %s\", this.logPrefix, this.name, this.address, result);\n return result;\n }",
"isPickInStoreSelected() {\n const pickupInStore = this.props.orderItems.filter(item => item.shipModeCode === 'PickupInStore');\n if (pickupInStore.length) {\n return true;\n }\n return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This sample demonstrates how to Creates or updates a workspace active directory admin | async function createOrUpdateWorkspaceActiveDirectoryAdmin() {
const subscriptionId =
process.env["SYNAPSE_SUBSCRIPTION_ID"] || "00000000-1111-2222-3333-444444444444";
const resourceGroupName = process.env["SYNAPSE_RESOURCE_GROUP"] || "resourceGroup1";
const workspaceName = "workspace1";
const aadAdminInfo = {
administratorType: "ActiveDirectory",
login: "bob@contoso.com",
sid: "c6b82b90-a647-49cb-8a62-0d2d3cb7ac7c",
tenantId: "c6b82b90-a647-49cb-8a62-0d2d3cb7ac7c",
};
const credential = new DefaultAzureCredential();
const client = new SynapseManagementClient(credential, subscriptionId);
const result = await client.workspaceAadAdmins.beginCreateOrUpdateAndWait(
resourceGroupName,
workspaceName,
aadAdminInfo
);
console.log(result);
} | [
"function addNewAdmin() {\n console.log(\"Add New Admin\");\n}",
"async createAdmin(ctx, args) {\n\n args = JSON.parse(args);\n //create a new admin\n let newAdmin = await new Admin(args.firstName, args.lastName, args.email);\n \n // update the world state\n await ctx.stub.putState(newAdmin.email, Buffer.from(JSON.stringify(newAdmin)));\n return newAdmin;\n\n }",
"async function workspaceCreate() {\n const subscriptionId = \"00000000-0000-0000-0000-000000000000\";\n const resourceGroupName = \"myResourceGroup\";\n const workspaceName = \"testworkspace\";\n const parameters = {\n location: \"West Europe\",\n ownerEmail: \"abc@microsoft.com\",\n sku: { name: \"Enterprise\", tier: \"Enterprise\" },\n tags: { tagKey1: \"TagValue1\" },\n userStorageAccountId:\n \"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Storage/storageAccounts/teststorage\",\n };\n const credential = new DefaultAzureCredential();\n const client = new MachineLearningWorkspacesManagementClient(credential, subscriptionId);\n const result = await client.workspaces.createOrUpdate(\n resourceGroupName,\n workspaceName,\n parameters\n );\n console.log(result);\n}",
"function createAdmin(email, password, success, failure) {\n if (!self.currentOrganization) {\n failure();\n }\n apiRequest(\"POST\", \"/management/organizations/\" + self.currentOrganization + \"/users\", null, JSON.stringify({\n email: email,\n password: password\n }), success, failure);\n }",
"function createAdmin(itemData){\n return oh.api.admin.hackathon.administrator.post({\n body: itemData,\n header: {\n hackathon_name: currentHackathon\n }\n }, function(data) {\n if(data.error){\n alert(data.error.message)\n }else{\n }\n });\n }",
"function createPortalAdmin(username, password) {\n var newUser = new GlideRecord('sys_user');\n newUser.initialize();\n newUser.user_password.setDisplayValue(password);\n newUser.first_name = \"Portal\";\n newUser.last_name = \"User\";\n newUser.user_name = username;\n return newUser.insert();\n}",
"function updateAdministration() {\n\n\n\n\t}",
"function createAdminUser() {\n User\n .findOne({ username: 'admin' })\n .then((user) => {\n if (!user) {\n const newUserObject = {\n username: 'admin',\n name: 'admin',\n given_name: 'admin',\n family_name: 'admin',\n nickname: 'admin',\n password: 'admin',\n };\n\n DbManager.addUser(newUserObject);\n }\n });\n}",
"createWorkspace() {\n let workspace = this.factory.workspace;\n //set factory attribute:\n workspace.attributes.factoryId = this.factory.id;\n workspace.name = this.getWorkspaceName(workspace.name);\n\n //TODO: fix account when ready:\n let creationPromise = this.cheAPI.getWorkspace().createWorkspaceFromConfig(null, workspace);\n creationPromise.then((data) => {\n this.$timeout(() => {this.startWorkspace(data); }, 1000);\n }, (error) => {\n this.handleError(error);\n });\n }",
"function updateAdmin(itemData){\n return oh.api.admin.hackathon.administrator.put({\n body: itemData,\n header: {\n hackathon_name: currentHackathon\n }\n }, function(data) {\n if(data.error){\n alert(data.error.message)\n }else{\n }\n });\n }",
"function showAdmin(){\n addTemplate(\"admin\");\n userAdmin();\n}",
"function makeAdmin(id) {\n return db.User.update({\n admin: true,\n }, {\n where: {\n id,\n },\n }).then(updated => console.log(updated));\n}",
"async createSuperAdmin(ctx, args) {\n\n args = JSON.parse(args);\n //create a new super admin\n let newSuperAdmin = await new SuperAdmin(args.firstName, args.lastName, args.email, args.password);\n \n // update the world state\n await ctx.stub.putState(newSuperAdmin.email, Buffer.from(JSON.stringify(newSuperAdmin)));\n return newSuperAdmin;\n\n }",
"function _eFapsCreateAllUpdatePassword() {\n print(\"\");\n print(\"Update Administrator Password\");\n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\");\n\n try {\n Shell.transactionManager.begin();\n\n var c = Context.newThreadContext(Shell.transactionManager.getTransaction(), \"Administrator\");\n Shell.setContext(c);\n c.getPerson().setPassword(c, \"Administrator\");\n print(\" - Done\");\n Shell.transactionManager.commit();\n c.close();\n } catch (e) {\n print(\" - Error:\"+e);\n try {\n Shell.transactionManager.rollback();\n c.close();\n } catch (e) {\n }\n }\n}",
"async initAdmin() {\n const { ctx } = this;\n let initGroup, initUser\n try {\n // init group\n let doGroup = await ctx.service.group.getGroupByName('admin')\n if (!doGroup) {\n initGroup = await ctx.service.group.createGroup('admin')\n }\n \n // init user\n let doUser = await ctx.service.user.getUserByName('admin');\n if(!doUser) {\n let res = await ctx.service.group.getGroupByName('admin')\n initUser = await ctx.service.user.createUser('admin', 'admin', res.id)\n }\n\n if (initUser && initGroup) {\n ctx.body = {\n msg: 'Init Admin successfully.',\n status: 200\n }\n } else if (initUser && (initGroup === undefined)) {\n ctx.body = {\n msg: 'Init AdminUser successfully.',\n status: 201\n }\n } else if (initGroup && (initUser === undefined)) {\n ctx.body = {\n msg: 'Init AdminGroup successfully.',\n status: 201\n }\n } else {\n ctx.body = {\n msg: 'Admin exists.',\n status: 400\n }\n }\n } catch (error) {\n ctx.body = {\n msg: 'Server error',\n status: 501\n }\n }\n }",
"function ensureAdminAccess(cb) {\n\tAdmins.find({'appname':appname}, function(err, docs) {\n\t\tif (err) throw err;\n\t\tif (! docs.length) {\n\t\t\tvar thisadm = new Admins();\n\t\t\tthisadm.login = thisadm.passwd = thisadm.name = 'admin';\n\t\t\tthisadm.appname = appname;\n\n\t\t\tthisadm.save(function(err){\n\t\t\t\tif (err) {\n\tconsole.log('ERROR creating default admin for ' + appname);\n\tconsole.log(err);\n\t\t\t\t\tthrow err;\n\t\t\t\t} else {\n\t\t\t\t\tif (cb) cb();\n\t\t\t\t}\n\t\t\t});\n\t\t} else cb();\n\t});\n}",
"function add_admin()\n{\n var users = DATABASE('users');\n var data = {id: CONFIG('admin-id'), password: CONFIG('admin-password'), wallet: CONFIG('admin-wallet'), role: 'admin'};\n users.findOne(data, function(err, result) {\n if (err) throw err;\n\n if (result == null) {\n users.insert(data);\n } else {\n console.log('there is the admin.');\n }\n });\n}",
"async function createFirstAdmin() {\n try {\n const username = Config.SYS_ADMIN\n const password = hashPassword(Config.SYS_ADMIN_PASSWORD)\n\n const { total } = await db.collection(Constants.cn.admins).count()\n if (total > 0) {\n console.log('admin already exists')\n return\n }\n\n await sys_accessor.db.collection(Constants.cn.admins).createIndex('username', { unique: true })\n\n const { data } = await db.collection(Constants.cn.roles).get()\n const roles = data.map(it => it.name)\n\n const r_add = await db.collection(Constants.cn.admins).add({\n username,\n avatar: \"https://static.dingtalk.com/media/lALPDe7szaMXyv3NAr3NApw_668_701.png\",\n name: 'Admin',\n roles,\n created_at: Date.now(),\n updated_at: Date.now()\n })\n assert(r_add.ok, 'add admin occurs error')\n\n await db.collection(Constants.cn.password).add({\n uid: r_add.id,\n password,\n type: 'login',\n created_at: Date.now(),\n updated_at: Date.now()\n })\n\n return r_add.id\n } catch (error) {\n console.error(error.message)\n }\n}",
"function addAdminUser() {\n try{\n db.getData(`${rootKeys.USER}/${id}`)\n } catch(error) {\n const username = 'pervez'\n const password = 'pervez'\n const id = 'pervez'\n db.push(`${rootKeys.USER}/${id}`, {\n id,\n username,\n password,\n role:['superAdminUser']\n })\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate that option value is valid nonempty string | function validateOptionString(options, key) {
if (!R.is(String, options[key])) {
throw ('Must be a string.');
}
if (R.isEmpty(options[key].trim())) {
throw ('Value must not be empty.');
}
} | [
"requireOptionString(opt /*:OptionDeclaration*/) {\n if (opt.value == undefined || opt.value == \"\") {\n const key = this.findDeclarationKey(opt)\n color.logErr(`required --${key}`)\n process.exit(1)\n }\n }",
"function nonEmptyStringValidator(value) {\n\treturn _.isString(value) && value.length > 0\n}",
"function isOptionLikeValue(value) {\n if (value == null) return false;\n\n return value.length > 1 && StringPrototypeCharAt(value, 0) === '-';\n}",
"requiredSelect(val) {\n const typeOfValue = typeof val;\n let value;\n switch (typeOfValue) {\n case 'string':\n value = val.replace(/^\\s+|\\s+$/g, '');\n return !(value === '-1' || value === '');\n\n case 'number':\n return val !== -1;\n\n default:\n return false;\n }\n }",
"function validatorStrNotEmpty(data, options) {\n var val = String(data),\n ok = data != null && (!options.strict || gc.util.isString(data)) && data.length > 0;\n\n return {\n data: val,\n valid: ok\n };\n }",
"function emptyOrMinLength_validate($this){\n\t\tif ($this.val().trim().length > 0 && $this.val().trim().length <= _settings.emptyOrMinLength)\n\t\t\tappend_msg($this, _settings.msg_emptyOrMinLength + _settings.emptyOrMinLength);\n\t\telse\n\t\t\tremove_msg($this);\n\t}",
"function filterEmpty(opt) {\n return opt.option !== '';\n }",
"function validateSelect(select) {\n var selectedValue = getSelectedValue(select);\n return (typeof(selectedValue) == 'string' && selectedValue != '') ? true : false;\n}",
"function ValidateNotEmpty(strSwitch, strValue, fReportViolations)\n{\n // A value must be specified with this switch\n if (!strValue || \"\" == strValue)\n return SyntaxViolated(\"Switch was specified without a value: \" + strSwitch, !fReportViolations);\n return 0;\n}",
"function validate_empty(param) {\t\n\treturn (!param || !param.length) ? true : false;\n}",
"function isUnemptyString (thing) {\n return isString(thing) && thing !== '';\n }",
"function notEmpty(value) {\n\treturn isDefined(value) && value.toString().trim().length > 0;\n}",
"function isNotEmptyString(value) {\n return value === \"\";\n}",
"function checkOptionValue(args, option) {\n if (args.length === 0) {\n print(\"Error: no value specified for \\\"\" + option + \"\\\" option\");\n quit();\n }\n}",
"function checkEmptyOrDash(inputValue){\r\n\t\tif (inputValue == \"\") {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\telse if(inputValue.search(\"---\") != -1){\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}",
"function hasSelectedValue(object, value)\n{\n\tvalue = trim(value);\n\tif ((value.length == 0) || (value == '-136'))\n\t\treturn false;\n\n\treturn true;\n}",
"function IsEmptyddlCheck(val)\n{\n if((val == '0') || (val == '')||(val == null))\n {\n return false;\n }\n else\n {\n return true;\n } \n}",
"function validateInput(input) {\n if (input == \"\") {\n return false;\n } else {\n return true;\n }\n}",
"function noempty(input_value, default_value)\n{\n if (!input_value)\n {\n return default_value;\n }\n if (input_value.length==0)\n {\n return default_value;\n }\n return input_value;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
close loading when async callback, after callback the max timeout is 100ms | function closeLoading() {
setTimeout(function () {
layer.closeAll('loading');
}, 100);
} | [
"closeLoading() {\n if (this.progressBar) {\n clearInterval(this.progressTimer);\n this.progressTimer = null;\n this.progressBar.destroy();\n this.progressBar = null;\n }\n }",
"function setTimeoutLoader(){\n $timeout(function () {\n hideLoader();\n }, 30000);\n }",
"function imageDownloadTimeout_handler() \n\t{ \n\t\tstoppedDownloading = true;\n\t\timageLoadedCompleteHandler(); \n\t}",
"function endLoading() {\n clearTimeout(timeout);\n _.delay(function() {\n $loading.removeClass('active');\n }, 400);\n stick.custom({\n 'window.performance.timing.fragment.loaded':\n (new Date()).getTime() - loadTimer\n });\n }",
"onLoadingTimeout() {\n this.browserProxy_.timeout();\n this.onErrorOccurred();\n }",
"function onTimeout() {\n\t\tcb();\n\t}",
"function waitTillAsyncApiLoaded(callback) {\n if (!Object.prototype.hasOwnProperty.call(window, 'mixpanel') || (window.mixpanel.__loaded === undefined)) {\n setTimeout(function () {\n waitTillAsyncApiLoaded(callback);\n }, 200);\n }\n else {\n callback();\n }\n }",
"function completeLoad() {\r\n loadTimeout = setTimeout(showPage, 3000);\r\n}",
"function loadingAutoClose(second, obj) {\n var msg = Layer_AutoClose_Warn\n var loadtype = Layer_AutoLoadType\n if (!second) second = Layer_AutoClose_Second\n if (obj && typeof(obj) === \"object\") {\n if(obj.hasOwnProperty(\"msg\")) {\n msg = obj.msg\n }\n if (obj.hasOwnProperty(\"load_type\")){\n loadtype = obj.load_type\n }\n }\n var id = Math.round(Math.random() * 10)\n id = 'myLayerID_' + id\n var layer_load_index = layer.load(loadtype, {id:id})\n setTimeout(function () {\n var obj = document.getElementById(id)\n if (null !== obj){\n layer.close(layer_load_index)\n layer.msg(msg)\n }\n }, parseInt(second) * 1000)\n\n return layer_load_index\n}",
"__startLoadTimeoutRace() {\n if (this.__timeoutHandle !== null) {\n timeOut.cancel(this.__timeoutHandle);\n }\n this.__timeoutHandle =\n timeOut.run(this.__boundFontyFrameLoadTimeout, this.timeout);\n }",
"function _closeHandler() {\n logger.debug('remaining count' + buffer.length);\n return deferred.resolve('data load complete');\n }",
"function closeLoading() {\n cloga(\"closeLoading\", null, \"waitingOnPar=\" + waitingOnPar);\n if (waitingOnPar == 0) {\n if (session.ro) {\n doc.innerHTML = copyDoc(true);\n } else {\n onChangesLoop(questions);\n }\n clog('the big one');\n doc.style.visibility = \"\";\n applyCustomShows();\n Pop.Working.close();\n //cloga(\"total isSel count=\" + isct);\n if (actions.bad.length > 0 && ! ignoreActionErrors) {\n setHtml(\"pop-aerr-errors\", actions.bad.join(\"<br>\"));\n Pop.show(\"pop-aerr\");\n }\n showingLoading = false;\n actions.autoapplying = false;\n //sendGetParRequest('2631');\n }\n //alert((new Date() - timer) / 1000);\n //setTimeout(\"renderTemplateMap()\", 1);\n}",
"cleanUp_() {\n this.generalizedLoadRejection_ = null;\n this.timeout_.stop();\n goog.dispose(this.timeout_);\n }",
"_timeout(){\n this._processResults({complete: false, data:null});\n }",
"onTimeout_() {\n if (goog.isFunction(this.generalizedLoadRejection_)) {\n this.generalizedLoadRejection_('Font loading timed out');\n this.generalizedLoadRejection_ = null;\n }\n }",
"onLoadingTimeOut_() {\n if (Oobe.getInstance().currentScreen.id != 'gaia-signin') {\n return;\n }\n this.clearLoadingTimer_();\n chrome.send('showLoadingTimeoutError');\n }",
"function mediauploader_Close() {\n\t\tsetTimeout(refreshLibPage, 500);\n\t}",
"function closeLoaderFile() {\n // reset the loader after closing the panel\n stepper.reset().start();\n stateManager.setActive('mainToc');\n\n // there is a bug with Firefox and Safari on a Mac. They don't focus back to add layer when close\n $timeout(function () {\n $rootElement.find('.rv-loader-add').first().rvFocus();\n }, 0);\n }",
"waitLoad(callback){\n if(this.checkLoad()){\n console.log(\"Files loaded!\");\n callback(this.renderEngine, this.loadShaderObj, this.loadModelObj, this.loadTextureObj);\n } else {\n setTimeout(function() {\n this.waitLoad(callback);\n }.bind(this), 100);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.