query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Function containing Launch Library API call | function launchLibrary(year, date) {
//console.log(date);
var launchLibraryURL = 'https://launchlibrary.net/1.3/launch?mode=verbose&';
var targetDate = date.split('-');
var startDate = 'startdate=' + year[0] + '-' + targetDate + '-01';
var endDate = '&enddate=' + year[0] + '-' + targetDate + '-31';
$.ajax(
{
url: launchLibraryURL + startDate + endDate,
method: "GET",
tryCount: 0,
retries: 3,
success: function (response, textStatus, jqXHR) {
console.log(response);
console.log(textStatus);
console.log(jqXHR);
var launches = response.launches;
//console.log(launches);
var closestDate = launches[getClosestDate(launches, targetDate[1])];
console.log(closestDate);
publishLaunch(closestDate);
},
error: function (jqXHR, exception) {
//alert("Launch library error: " + jqXHR.status + exception);
if (jqXHR.status == 404 && tryCount <= retries) {
tryCount++;
setTimeout(() => { $.ajax(this) }, 1000);
}
}
});
} | [
"function target_launch_app() {\n var http = new XMLHttpRequest();\n http.open(\"GET\", \"./boa_launch.py\");\n http.onreadystatechange = function() {\n\tif (http.readyState == XMLHttpRequest.DONE) {\n\t if (http.status != 200) {\n\t\talert(\"target_launch_app()\\nError \" + http.status + \"\\n\" + http.statusText);\n\t } else\n\t\t// app has been launched.\n\t\t// try to connect\n\t\ttarget_connect(false);\n\t }\n }\n http.send();\n}",
"function GADGET_GEN_Launch()\n{\t\n\tSystem.Gadget.Settings.write(\"URL\", URL.Site);\n\tShell.Run(URL.Site);\n}",
"function init_sdk() {\n\tvar branch = get_url_parameter(\"b\",\"master\");\n\tvar url = get_url_parameter(\"baseUrl\",(branch==\"develop\"?\"https://dev-api.wialon.com\":\"https://hst-api.wialon.com\"));\n\tif (!url)\n\t\turl = get_url_parameter(\"hostUrl\",\"https://hosting.wialon.com\");\n\tif (!url)\n\t\treturn;\n\n\tvar user = get_url_parameter(\"user\") || \"\";\n\tvar sid = get_url_parameter(\"sid\");\n\tvar authHash = get_url_parameter(\"authHash\");\n\n\twialon.core.Session.getInstance().initSession(url, \"gapp_eco_driving\");\n\tif (authHash) {\n\t\twialon.core.Session.getInstance().loginAuthHash(authHash, login);\n\t} else if (sid) {\n\t\twialon.core.Session.getInstance().duplicate(sid, user, true, login);\n\t}\n}",
"function startApp(adviseLaunchInfo) {\n \n $simjq.when(checkServantURLValidity(adviseLaunchInfo))\n .then(function(token){\n\t\t\tif (token.length > 0){\n \n if(!adviseLaunchInfo.noServant){\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_READING_DATA'),\n setStationNameToSplash(adviseLaunchInfo));\n }\n else{\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_LOAD_LITE'));\n }\n \n $simjq('#widgetframe').attr('src', \"../webapps/SMAAnalyticsUI/smaResultsAnalyticsLaunched.html\").load(function(){\n var widgetWindow = window.frames['widgetframe'];\n if(!widgetWindow.setServantFromParent) {\n widgetWindow = widgetWindow.contentWindow; // needed for FF\n }\n if(widgetWindow.setServantFromParent) {\n $simjq('.embeddedWidget').show();\n if(!adviseLaunchInfo.noServant){\n widgetWindow.setServantFromParent(adviseLaunchInfo);\n }\n } else {\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_PAGE_LOAD_ERROR'));\n adviseGoBack(adviseLaunchInfo.translator.translate('LAUNCH_PAGE_LOAD_ERROR'));\n }\n });\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tadviseGoBack(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_ERROR'));\n\t\t\t}\n\n });\n}",
"function listClick2Call() {\n api.send('apps.get_list', [false])\n .success((apps) => {\n for (let a of apps) {\n if (a.package.type === 'CLICKTOCALL')\n console.log(`hash: ${a.hash} - name: ${a.name}, type: ${a.package.type}`);\n }\n })\n .error(error);\n}",
"InstallApplication(string, string, int, string, string, string) {\n\n }",
"getLibrary() {\n let libraryPath = path.join(this.userLibraryDir, 'library.json')\n return new Promise((resolve, reject) => {\n fs.readFile(libraryPath, 'utf8', (err, data) => {\n /* istanbul ignore next */\n if (err) reject(err)\n else resolve(JSON.parse(data))\n })\n })\n }",
"async function executeMain() {\n try {\n await main();\n } catch (e) {\n let body = e.response && e.response.body;\n if (body) {\n // DocuSign API problem\n console.log (`\\nAPI problem: Status code ${e.response.status}, message body:\n${JSON.stringify(body, null, 4)}\\n\\n`); \n } else {\n // Not an API problem\n throw e;\n }\n }\n}",
"async function fnStartRemoteAPI(){\n if (fs.existsSync(\"/share/config.json\") !== true && fs.existsSync(\"/share/config.gen.js\") !== true && fs.existsSync(\"/share/remote-api.json\")){\n try {\n if (fs.existsSync(\"/startup/remote-api.started\") !== true || fnIsRunning(\"node /startup/remote-api/index.js\") !== true){\n console.log(`[LOG] EasySamba Remote API is enabled and is starting...`);\n fnKill(\"node /startup/remote-api/index.js\");\n fnDeleteFile(\"/startup/remote-api.started\");\n fnSpawn(\"node\", [\"/startup/remote-api/index.js\"]);\n await fnSleep(2000);\n if (fs.existsSync(\"/startup/remote-api.started\")){\n console.log(`[LOG] EasySamba Remote API started successfully.\\n`);\n }\n else {\n console.log(`[ERROR] EasySamba Remote API could not be started.\\n`);\n }\n }\n }\n catch (error){\n if (fnIsRunning(\"node /startup/remote-api/index.js\") !== true){\n fnDeleteFile(\"/startup/remote-api.started\");\n console.log(`[ERROR] EasySamba Remote API could not be started.\\n`);\n }\n }\n }\n else {\n if (fs.existsSync(\"/startup/remote-api.started\") || fnIsRunning(\"node /startup/remote-api/index.js\")){\n console.log(`[LOG] EasySamba Remote API is not enabled and won't be started.\\n`);\n fnKill(\"node /startup/remote-api/index.js\");\n fnDeleteFile(\"/startup/remote-api.started\");\n }\n }\n}",
"function doLMSInitialize()\n{ \n var api = getAPIHandle();\n if (api == null)\n {\n messageAlert(\"Unable to locate the LMS's API Implementation.\\nLMSInitialize was not successful.\");\n return \"false\";\n }\n\n var result = api.LMSInitialize(\"\");\n\n if (result.toString() != \"true\")\n {\n\n var err = ErrorHandler();\n }\n\n return result.toString();\n}",
"function makeRunAdviseJob(adviseLaunchInfo) {\n \n var resourceCredentials = adviseLaunchInfo.resourceCredentials,\n eedURL = adviseLaunchInfo.eedURL,\n eedTicket = adviseLaunchInfo.eedTicket,\n decodeJobXML = htmlUnescape(adviseLaunchInfo.encodedJobXML),\n runInfo = adviseLaunchInfo.runInfo,\n affinity = null;\n \n if(typeof adviseLaunchInfo.stationName !== 'undefined' && adviseLaunchInfo.stationName !== null\n && adviseLaunchInfo.stationName !== ''){\n affinity = adviseLaunchInfo.stationName;\n } else if (typeof adviseLaunchInfo.localStationName !== 'undefined' && adviseLaunchInfo.localStationName !== null\n && adviseLaunchInfo.localStationName !== ''){\n affinity = adviseLaunchInfo.localStationName;\n }\n \n decodeJobXML = unescape(encodeURIComponent(decodeJobXML));\n // Private Secure station takes precedence\n if(adviseLaunchInfo.secureStation) {\n \t// Set the affinity to localHost\n affinity = \"{localhost}\";\n // Set the HasLocalHost value to AppData\n var appDataXML = UTILS.loadXml(decodeJobXML);\n var lHostNode = appDataXML.getElementsByTagName('Application')[0].appendChild(\n \t\tappDataXML.createElement('HasLocalHost'));\n lHostNode.appendChild(appDataXML.createTextNode('true'));\n decodeJobXML = UTILS.xmlToString(appDataXML);\n }\n\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_START_SERVANT'),\n setStationNameToSplash(adviseLaunchInfo));\n \n var proxyServerURL = adviseLaunchInfo.proxyServer;\n if(typeof proxyServerURL === 'undefined' || proxyServerURL === null){\n proxyServerURL = '';\n }\n if(proxyServerURL.indexOf('http') !== 0){\n proxyServerURL = '';\n }\n \n var modelxml = \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\"\n + \"<fiper_Model version=\\\"6.216.0\\\" majorFormat=\\\"1\\\" timestamp=\\\"6/5/14\\\" rootComponentId=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519\\\">\"\n + \"<Properties modelId=\\\"6a53ba4c-811e-11e2-ae82-e9ce6b18c519\\\" modelName=\\\"AdviseServant\\\" modelVersion=\\\"6.216.0\\\" />\"\n + \"<Component id=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519\\\" name=\\\"AdviseServant\\\" type=\\\"com.dassault_systemes.smacomponent.adviseservant\\\">\";\n\n // client\n modelxml += \"<Variable type=\\\"com.engineous.datatype.String\\\" id=\\\"bb27e8af-811e-11e2-ae82-e9ce6b18c519\\\" name=\\\"host\\\" role=\\\"Parameter\\\" structure=\\\"Scalar\\\" mode=\\\"Input\\\" dispName=\\\"host\\\" saveToDB=\\\"true\\\" parentId=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519\\\">\"\n + \"<Value><![CDATA[\"+window.location.protocol+'//'+window.location.host+\"]]></Value>\"\n + \"</Variable>\";\n\n // csrf\n modelxml += \"<Variable type=\\\"com.engineous.datatype.String\\\" id=\\\"bc27e8af-811e-11e2-ae82-e9ce6b18c519\\\" name=\\\"token\\\" role=\\\"Parameter\\\" structure=\\\"Scalar\\\" mode=\\\"Input\\\" dispName=\\\"token\\\" saveToDB=\\\"true\\\" parentId=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519\\\">\"\n + \"<Value><![CDATA[\"+adviseLaunchInfo.token+\"]]></Value>\"\n + \"</Variable>\";\n \n \n // if a local station was found or if user chose a station, assign affinity to the AdviseServant component\n if(affinity){\n modelxml = modelxml\n + \"<Variable id=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519:affinities\\\" name=\\\"affinities\\\" role=\\\"Property\\\" structure=\\\"Aggregate\\\" mode=\\\"Local\\\" parentId=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519\\\">\" \n + \"<Variable type=\\\"com.engineous.datatype.String\\\" typeWrittenVersion=\\\"2.0.0\\\" id=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519:Host\\\" name=\\\"Host\\\" role=\\\"Property\\\" structure=\\\"Scalar\\\" mode=\\\"Local\\\" parentId=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519:affinities\\\">\"\n + \"<Value>\"+affinity+\"</Value>\"\n + \"</Variable>\"\n + \"</Variable>\";\n }\n \n /**\n * This variable sets tells the servant if the data should be \n * saved and read in Essentials format.\n */\n try {\n \tvar essOn = false;\n \tif (localStorage.getItem('_ESSENTIALS_MODE_ON_') === true) {\n \t\tessOn = true;\t\n \t}\n \tmodelxml += \"<Variable type=\\\"com.engineous.datatype.Bool\\\" id=\\\"be27e8af-811e-11e2-ae82-e9ce6b18c519\\\" name=\\\"_ESSENTIALS_MODE_ON_\\\" role=\\\"Parameter\\\" structure=\\\"Scalar\\\" mode=\\\"Input\\\" dispName=\\\"_ESSENTIALS_MODE_ON_\\\" saveToDB=\\\"true\\\" parentId=\\\"812da46e-811e-11e2-ae82-e9ce6b18c519\\\">\"\n\t\t\t+ \"<Value>\" + essOn + \"</Value>\"\n\t\t\t+ \"</Variable>\";\n } catch(ex){}\n \n modelxml = modelxml \n + \"</Component>\"\n + \"<Component id=\\\"6a5a22ed-811e-11e2-ae82-e9ce6b18c519\\\" name=\\\"Task1\\\" type=\\\"com.dassault_systemes.sma.adapter.Task\\\">\" + \"</Component>\" + \"</fiper_Model>\";\n \n // sd4: used to be \"/execution/run/workflow\"\n var eedRunUrl = eedURL + '/execution/run';\n \n jQuery.support.cors = true;\n jQuery.ajax({ \n url : eedRunUrl,\n type : \"POST\",\n beforeSend : function(request) {\n request.setRequestHeader(\"EEDTicket\", eedTicket);\n request.setRequestHeader(\"Credentials\", \"\");\n\n \n request.setRequestHeader(\"RunInfo\", runInfo);\n \n\n request.setRequestHeader(\"ApplicationData\", decodeJobXML);\n resourceCredentials = resourceCredentials.trim();\n\n request.setRequestHeader(\"ResourceCredentials\", resourceCredentials);\n },\n data : modelxml,\n contentType : \"text/plain\",\n success : function(returndata, status, xhr) {\n var jobIdTxt = $simjq(returndata).find(\"JobID\").text().trim();\n adviseLaunchInfo.jobID = jobIdTxt;\n \n if(adviseLaunchInfo.secureStation) {\n \n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_NOTIFY_SEC_STATION'));\n \n jQuery.ajax({\n url: adviseLaunchInfo.stationAccess+\"/claim?jobids=\"+jobIdTxt,\n type: \"POST\",\n cache:false,\n success: function (returndata, status, xhr) {\n waitForServantStartup(adviseLaunchInfo);\n },\n error: function(jqXHR, textStatus, errorThrown){\n console.error(textStatus);\n console.error(errorThrown);\n //waitForServantStartup(adviseLaunchInfo);\n\t\t\t\t\t\tshowLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_EXEC_ERROR'));\n\t\t\t\t\t\tadviseGoBack(\n\t\t\t\t\t\t\t\tadviseLaunchInfo.translator.translate('LAUNCH_SERVANT_EXEC_ERROR') + '<br\\>' + err\n\t\t\t\t\t\t);\n }\n });\n } else {\n waitForServantStartup(adviseLaunchInfo);\n }\n },\n error : function(jqXHR, textStatus, err) {\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_EXEC_ERROR'));\n adviseGoBack(\n adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_EXEC_ERROR') + '<br\\>' + err\n );\n }\n });\n}",
"function app_bridge(fx, param) {\n console.log(\"Calling bridge function \" + fx + \" with param \" + param);\n\n if (typeof window.Android !== \"undefined\" && window.Android !== null) {\n try {\n if (typeof(param) == \"undefined\") {\n window.Android[fx]();\n } else {\n window.Android[fx](param);\n }\n } catch (e) {\n void(0);\n }\n } else if (typeof window.webkit !== \"undefined\" && typeof window.webkit.messageHandlers !== \"undefined\" && window.webkit.messageHandlers !== null) {\n try {\n if (typeof(param) == \"undefined\") {\n window.webkit.messageHandlers.bridge.postMessage(fx + \":\");\n } else {\n window.webkit.messageHandlers.bridge.postMessage(fx + \":\" + param);\n }\n } catch (e) {\n void(0);\n }\n\n } else {\n try {\n if (typeof(param) == \"undefined\") {\n window[fx]();\n } else {\n window[fx](param);\n }\n } catch (e) {\n void(0);\n }\n }\n\n\n}",
"function tryTolaunchAdviseClient(adviseLaunchInfo, timer) {\n \n var jobIdTxt = adviseLaunchInfo.jobID;\n var eedURL = adviseLaunchInfo.eedURL;\n var eedTicket = adviseLaunchInfo.eedTicket;\n \n launchCount++;\n if (launchCount > launchLimit) {\n // sd4 - IR-297707-3DEXPERIENCER2015x - adding a confirmation message \n // to wait longer in order to allow downloading a large file\n createLaunchPopOver({\n 'message': adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_TIMER_XTND'),\n 'confirm-mode': true,\n 'ok-callback': function(){\n launchCount = 0;\n launchLimit = 150; // 5 minutes\n return;\n },\n 'close-callback': function(){\n clearInterval(timer);\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_TIMER_XTND'),\n setStationNameToSplash(adviseLaunchInfo));\n cancelJob(adviseLaunchInfo, adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_TIMEOUT'));\n }\n });\n }\n \n // Configure AJAX call to the EED for reading bulletin board messages\n var eedURLMonitor = eedURL + \"/job/\" + jobIdTxt + \"/monitor\";\n \n jQuery.support.cors = true;\n \n monitorForError(eedURLMonitor, eedTicket);\n \n // AJAX call to read EED bulletin board\n jQuery.ajax({\n url : eedURLMonitor,\n data : { 'Topic' : messageTopic,\n 'TimeStamp' : 0 },\n type : \"GET\",\n beforeSend : function(request) {\n request.setRequestHeader(\"EEDTicket\", eedTicket);\n request.setRequestHeader(\"Credentials\", \"\");\n },\n success : function(returndata, status, xhr){\n \n var adviseMessage = $simjq(returndata).find(\"Message\").text() || '';\n // sd4 - I keep getting this error when i try to launch \n var localTopic = $simjq(returndata).find(\"MessageList\").attr(\"topic\");\n if(localTopic && localTopic.length>4) {\n \tlocalTopic = localTopic.trim();\n }\n if (adviseMessage.length > 4) {\n // First message topic that we expect - before downloading the data\n // file on the servant (done by component BEFORE launching advise servant\n if (localTopic == \"ResultsServantDowloadingFile\") {\n \n showLoadingMessage(adviseLaunchInfo.translator.translate(adviseMessage) + \"...\",\n setStationNameToSplash(adviseLaunchInfo));\n \n // Next message topic that we expect - URL for advise - posted\n // after Advise servant is fully functional\n messageTopic = \"ResultsServantURL\";\n \n // Reset the timout to 30 mins - in case of downloading a very\n // large file over a slow network\n launchCount = 0;\n launchLimit = 900;\n jobRunning = true;\n }\n else {\n\t clearInterval(timer);\n\t \n\t // Retrieve the servant url(s)\n\t deriveServantURL(adviseLaunchInfo, adviseMessage);\n\t \n\t if ((adviseLaunchInfo['stationDisplayName']).length === 0){\n\t\n\t \t// The display name would be empty only if\n\t \t// affinity is not set and the station is not\n\t \t// a secure station.\n\t \t\n\t \tvar servantIP = '';\n\t \tif (adviseMessage.indexOf('http') === 0){\n\t \t\t// Unproxified url\n\t \t\tvar parser = document.createElement('a');\n\t parser.href = adviseMessage;\n\t servantIP = parser.hostname;\n\t \t} else {\n\t \t\t// Proxy exists, and the message format is\n\t \t\t// 192.178.106.25/8090/Advise\n\t \t\tservantIP = adviseMessage.split('/')[0];\n\t \t}\n\t \tif (servantIP.length > 0){\n\t \t\tfor(var i=0; i<adviseLaunchInfo.stationList.length; i++) {\n\t \t\tvar stationInfo = adviseLaunchInfo.stationList[i];\n\t \t\tif (servantIP ===\n\t \t\t\tstationInfo.GeneralInfo['@hostIP'].trim()){\n\t \t\t\tadviseLaunchInfo.stationIP = servantIP;\n\t \t\t\tadviseLaunchInfo.stationName = stationInfo['@name'];\n\t \t\t\tadviseLaunchInfo.stationDisplayName = stationInfo['@name'];\n\t \t\t}\n\t \t}\n\t \t\t\n\t \t\tif ((adviseLaunchInfo['stationDisplayName']).length === 0){\n\t \t\t\tadviseLaunchInfo.stationDisplayName = window.location.host\n\t \t\t}\n\t \t}\n\t }\n\t \n\t //startJobLogHeartbeat(jobIdTxt);\n\t \n\t var startWaitTimer = setInterval(function() {\n\t clearInterval(startWaitTimer);\n\t removeLoadingMessage();\n\t // FIXME: Why is the servant url set here ?\n\t // adviseLaunchInfo.servantURL = adviseMessage + '/';\n\t startApp(adviseLaunchInfo);\n\t }, 2000);\n }\n } else {\n \n var messageElem = $simjq(returndata).find(\"MonitoringMessages\");\n var status = messageElem.attr(\"status\");\n if (status == \"Running\" && !jobRunning) {\n // Reset the wait timer for the Executor to post the message\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_WAIT_FOR_SERVANT'),\n setStationNameToSplash(adviseLaunchInfo));\n \n launchCount = 0;\n jobRunning = true;\n } else if (status == \"Done\") {\n clearInterval(timer);\n \n // We don't need this message when the job is cancelled.\n if (! JOB_CANCELLED){\n var errorThrown = adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_ERROR');\n showLoadingMessage(errorThrown, setStationNameToSplash(adviseLaunchInfo));\n adviseGoBack(errorThrown);\n }\n }\n }\n }, // End of success callback\n error: function(jqXHR, textStatus, errorThrown){\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_STATUS_ERROR'));\n adviseGoBack(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_STATUS_ERROR') + '<br/>' +\n adviseLaunchInfo.translator.translate('LAUNCH_BB_ERROR'));\n return;\n }\n });\n}",
"function launchAutolinkConfig(){\n\t\n\t\n\t\n\t\n}",
"function createSnippet(config) {\n var curl_snippet = '\\n\\\ncurl -N https://'+config.username+':'+config.password+'@scalr.api.appbase.io/'+config.appname+'/'+config.type+'/response?stream=true';\n var javascript_snippet = '\\n\\\n// Instantiate\\n\\\nvar appbaseRef = new Appbase({\\n\\\n url: \"https://'+config.username+':'+config.password+'@scalr.api.appbase.io\",\\n\\\n appname: \"'+config.appname+'\"\\n\\\n});\\n\\\n// Listen to streaming updates\\n\\\nappbaseRef.getStream({type: \"'+config.type+'\", id: \"response\"}).on(\"data\", function(stream) {\\n\\\n console.log(\"streaming update: \", stream)\\n\\\n});';\n return {\n curl: curl_snippet,\n js: javascript_snippet\n };\n }",
"function WDIToolkit(){}",
"function url_build () {\n return spawn('python',\n ['./lib/python/change_url.py', 'build'], {stdio: 'inherit'})\n}",
"function libraryChannel(){\n var pushstream = new PushStream({\n host: window.location.hostname,\n port: window.location.port,\n modes: GUI.mode\n });\n pushstream.onmessage = libraryHome;\n pushstream.addChannel('library');\n pushstream.connect();\n}",
"function initAPI() {\n\t//window.alert(\"start\")\n\tif (g_initAPIcnt < MAX_TIME_INTERVAL && !g_strAPIInitialized) {\n\t\tif(APIOK()) {\n\t\t\tclearInterval(g_varInterval);\n\t\t\tvar err = initializeSCO();\n\t\t\t//alert(err)\n\t\t} else {\n\t\t\tg_objAPI = GetApi();\n\t\t}\n\t} else {\n\t\tg_objAPI = null;\n\t\tclearInterval(g_varInterval);\n\t}\n\tg_initAPIcnt++;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Populates the stock data table node with cells for all the stock data about a company. | function populateStockDataTable(stockData) {
const tableBody = document.querySelector('#stockDataTable tbody');
tableBody.innerHTML = "";
for (let data of stockData) {
let row = document.createElement('tr'); // each piece of 'data' will be a single row in the table
let dateCell = document.createElement('td'); // creating table cell nodes
let openCell = document.createElement('td');
let closeCell = document.createElement('td');
let lowCell = document.createElement('td');
let highCell = document.createElement('td');
let volumeCell = document.createElement('td');
dateCell.textContent = data.date; // populating created cell nodes with their respective data
openCell.textContent = currency(data.open);
closeCell.textContent = currency(data.close);
lowCell.textContent = currency(data.low);
highCell.textContent = currency(data.high);
volumeCell.textContent = currency(data.volume);
row.appendChild(dateCell); // adding created cells to the row
row.appendChild(openCell);
row.appendChild(closeCell);
row.appendChild(lowCell);
row.appendChild(highCell);
row.appendChild(volumeCell);
tableBody.appendChild(row); // adding the completed row to the table
}
populateStockSummaryTable(stockData);
} | [
"function populateStockSummaryTable(stockData) {\n const openData = stockData.map(stock => stock.open); // creating arrays for each type of stock data\n const closeData = stockData.map(stock => stock.close);\n const lowData = stockData.map(stock => stock.low);\n const highData = stockData.map(stock => stock.high);\n const volumeData = stockData.map(stock => stock.volume);\n \n document.querySelector('#openAvgCell').textContent = currency(average(openData)); // populating averages\n document.querySelector('#closeAvgCell').textContent = currency(average(closeData));\n document.querySelector('#lowAvgCell').textContent = currency(average(lowData));\n document.querySelector('#highAvgCell').textContent = currency(average(highData));\n document.querySelector('#volumeAvgCell').textContent = currency(average(volumeData));\n\n document.querySelector('#openMinCell').textContent = currency(minimum(openData)); // populating minimums\n document.querySelector('#closeMinCell').textContent = currency(minimum(closeData));\n document.querySelector('#lowMinCell').textContent = currency(minimum(lowData));\n document.querySelector('#highMinCell').textContent = currency(minimum(highData));\n document.querySelector('#volumeMinCell').textContent = currency(minimum(volumeData));\n\n document.querySelector('#openMaxCell').textContent = currency(maximum(openData)); // populating maximums\n document.querySelector('#closeMaxCell').textContent = currency(maximum(closeData));\n document.querySelector('#lowMaxCell').textContent = currency(maximum(lowData));\n document.querySelector('#highMaxCell').textContent = currency(maximum(highData));\n document.querySelector('#volumeMaxCell').textContent = currency(maximum(volumeData));\n }",
"function setCompanyList(companies) {\n const tableLoadingAnimation = document.querySelector('#stockDataLoadingAnimation');\n for (let company of companies) {\n let element = document.createElement('li');\n element.textContent = company.name;\n element.addEventListener('click', async function() {\n // On company click, fetch stock data about that company.\n tableLoadingAnimation.style.display = 'block';\n const response = await fetch(stockDataAPI + company.symbol);\n const stockData = await response.json();\n tableLoadingAnimation.style.display = 'none';\n\n if (company.financials == null) { // Some companies in the API are missing financial data. In those cases, the panels simply indicate as such.\n document.querySelector('#charts').innerHTML = \"No financial data found.\";\n document.querySelector('#financials').innerHTML = \"No financial data found.\";\n } else { // If companies do have financial data, the affected HTML panels are reset to their default state so they can be modified properly.\n document.querySelector('#charts').innerHTML = defaultChartHTML;\n document.querySelector('#financials').innerHTML = defaultFinancialHTML;\n }\n\n // Building each panel based on the clicked company.\n setCompanyInfo(company);\n setMap(company);\n setStockData(stockData);\n\n setChartCompanyInfo(company);\n setCharts(company, stockData);\n setFinancials(company);\n });\n htmlCompanyList.append(element); // appending the created element to the unordered list\n }\n }",
"renderTableData() {\n window.$(\"#expenses\").find(\"tr:gt(0)\").remove();\n let table = document.getElementById(\"expenses\");\n for (let i = 0; i<exps.length; i++) {\n let row = table.insertRow();\n let cell0 = row.insertCell(0);\n let cell1 = row.insertCell(1);\n let cell2 = row.insertCell(2);\n cell0.innerHTML = exps[i].name;\n cell1.innerHTML = exps[i].cost;\n cell2.innerHTML = exps[i].category;\n }\n }",
"getStock(stockSymbol) {\n stockService.data(stockSymbol, (err, data) => {\n if (err) return this.handleError(err);\n\n const stock = JSON.parse(data);\n let stockData = stock.data.reverse().map(info => {\n return [\n (new Date(info[0])).getTime(),\n info[1]\n ]\n });\n\n // update chart with new data\n this.addStockToChart(stockSymbol, stockData);\n\n this.addStockToStockTable(stock.company, stock.symbol);\n });\n }",
"function displayStock(newCompany) {\n\n\n var proxy = \"https://cors-anywhere.herokuapp.com/\"\n var queryURL = proxy + [\"https://autoc.finance.yahoo.com/autoc?query=\" + newCompany + \"®ion=EU&lang=en-GB&x=NYSE\"];\n\n $.ajax({\n url: queryURL,\n method: \"GET\",\n crossDomain: true,\n }).done(function(response){\n console.log(response);\n \n var stockarry = [];\n\n \n if (response.ResultSet.Result.length === 0) {\n \n var nope = $(\"<p>\").text(\"No Stock Found\");\n\n $(\"#instructions\").addClass(\"hidden\");\n $(\"#stocktickers\").empty();\n $(\"#stocktickers\").append(nope);\n\n }else{\n for (i = 0; i < response.ResultSet.Result.length; i++) {\n if (response.ResultSet.Result[i].exchDisp === \"NYSE\") {\n stockarry.push(response.ResultSet.Result[i]);\n\n console.log(stockarry);\n\n var stockticker1 = stockarry[0].symbol;\n var stockname1 = stockarry[0].name;\n\n var stk1 = $(\"<p>\").text(stockname1 + \": \" + stockticker1);\n\n $(\"#instructions\").addClass(\"hidden\");\n $(\"#stocktickers\").empty();\n $(\"#stocktickers\").append(stk1)\n\n }else if (response.ResultSet.Result[i].exchDisp === \"NASDAQ\") {\n stockarry.push(response.ResultSet.Result[i]);\n\n console.log(stockarry);\n\n var stockticker1 = stockarry[0].symbol;\n var stockname1 = stockarry[0].name;\n\n var stk1 = $(\"<p>\").text(stockname1 + \": \" + stockticker1);\n\n $(\"#instructions\").addClass(\"hidden\");\n $(\"#stocktickers\").empty();\n $(\"#stocktickers\").append(stk1)\n\n }\n }\n }\n //stock ticker search function ends\n \n\n\n \n \n })\n }",
"function setFinancials(company) {\n const years = company.financials.years;\n const revenues = company.financials.revenue;\n const earnings = company.financials.earnings;\n const assets = company.financials.assets;\n const liabilities = company.financials.liabilities;\n \n /* The 'years' array stores year numbers at each index - 0 is 2019, 1 is 2018, and 2 is 2017. The arrays for each\n * type of financial data also follow this pattern (revenues[0] is the revenue for 2019, revenues[1] is 2018, etc).\n * This means that the index of a 'year' will be the same index of whichever financial data for that year.\n */\n for (let year of years) {\n document.querySelector(`#rev${year}`).textContent = currency(revenues[years.indexOf(year)]);\n document.querySelector(`#earn${year}`).textContent = currency(earnings[years.indexOf(year)]);\n document.querySelector(`#asset${year}`).textContent = currency(assets[years.indexOf(year)]);\n document.querySelector(`#lia${year}`).textContent = currency(liabilities[years.indexOf(year)]);\n }\n }",
"function populateTable(results){\n let current_table = document.getElementById(\"price_links\");\n let new_table = document.createElement('tbody');\n new_table.setAttribute(\"id\", \"price_links\");\n for(var i=0; i < results.length; i++){\n let row = new_table.insertRow();\n let vendor = row.insertCell(0);\n vendor.innerHTML = results[i][\"Vendor\"];\n let price = row.insertCell(1);\n price.innerHTML = results[i][\"Price\"];\n let link = row.insertCell(2);\n if(results[i][\"Link\"].length > 1){\n let link_element = document.createElement(\"a\");\n link_element.href = results[i][\"Link\"];\n link_element.innerHTML = \"Link\";\n link.appendChild(link_element);\n } else {\n link.innerHTML = results[i][\"Link\"];\n }\n }\n current_table.parentNode.replaceChild(new_table, current_table)\n}",
"function populateTable() {\t\n var table = $(\"#hiscore_table tr\");\n $.get(\"/hiscores\", function (data) {\n var hiscores = JSON.parse(data);\n hiscores.forEach(function (hiscore) {\n var html = createTableRow(hiscore.name, hiscore.score, hiscore.date);\n table.last().after(html);\t\t\n });\n });\t\n}",
"function renderTable() {date\r\n $tbody.innerHTML = \"\";\r\n for (var i = 0; i < datetime.length; i++) {\r\n // Get get the current datetime object and its fields\r\n var date = datetime[i];\r\n var fields = Object.keys(date)\r\n // Create a new row in the tbody, set the index to be i + startingIndex\r\n var $row = $tbody.insertRow(i);\r\n for (var j = 0; j < fields.length; j++) {\r\n // For every field in the address object, create a new cell at set its inner text to be the current value at the current address's field\r\n var field = fields[j];\r\n var $cell = $row.insertCell(j);\r\n $cell.innerText = date[field];\r\n }\r\n }\r\n}",
"loadStocks() {\n stockService.get((err, data) => {\n if (err) return this.handleError(err);\n\n // the latest list of stocks on database\n const stocks = JSON.parse(data);\n\n // the list of stock symbols's currently on chart\n const chartedStockSymbols = this.stockChart.series.map((series) => {\n return series.name;\n });\n\n stocks.forEach((stock) => {\n // only get the pricing data of not-charted stock symbols\n if (chartedStockSymbols.indexOf(stock) == -1) {\n this.getStock(stock.symbol);\n }\n });\n\n this.stockSocket.start();\n });\n }",
"function createCompaniesTable(){\n dynamodb.createTable(paramsCreateCompanies, function(err, data) {\n if (err) {\n console.error(\"Unable to create table. Error JSON:\", JSON.stringify(err, null, 2));\n } else {\n console.log(\"Created table. Table description JSON:\", JSON.stringify(data, null, 2));\n }\n });\n}",
"function displayStockList(filter, refresh) {\n if (!!document.getElementById(\"listPlaceholder\")) {\n const newlist = document.createElement('div');\n newlist.innerHTML = ' <div class=\"stock-selection-sect vertical_height margin-top\" id=\"stockHeader\"></div>';\n document.getElementById('listPlaceholder').parentNode.replaceChild(newlist, document.getElementById('listPlaceholder'));\n }\n\n var stockHeader = document.getElementById('stockHeader');\n var boxControl = \"\";\n var index = 0;\n var dataSet = (getIsETFActive()) ? getETFsInPortfolio(filter) : getStocksInPortfolio(filter);\n console.log(\"Displaying Asset List\");\n dataSet.forEach(stock => {\n var cssType;\n if (stock.priceChangeFromPreviousDay < 0) {\n cssType = \"\\\"box red detail-label-small\\\"\"\n }\n else if (stock.priceChangeFromPreviousDay >= 0) {\n cssType = \"\\\"box green detail-label-small\\\"\"\n }\n boxControl +=\n \"<div onclick = handleChartDisplay(event)>\" +\n \" <div name=\\\"stockSummary\\\" class=\\\"stock-selection-summary\\\" id=\\\"outer-\" + stock.label + \"\\\">\" +\n \" <div class=\\\"stock-selection-left\\\" id=\\\"left-\" + stock.label + \"\\\">\" +\n \" <div class=\\\"stock-selection-summary-stock-name\\\"id=\\\"divName-\" + stock.label + \"\\\">\" +\n \" <label class=\\\"detail-label\\\" id=\\\"fullName-\" + stock.label + \"\\\">\" + stock.name + \"</label>\" +\n \" </div>\" +\n \" <div class=\\\"stock-selection-summary-short-name\\\" id=\\\"ticker-\" + stock.label + \"\\\">\" +\n \" <label class=\\\"detail-label-small\\\" id=\\\"shortName-\" + stock.label + \"\\\">\" + stock.label + \"</label>\" +\n \" </div>\" +\n \" </div>\" +\n \" <div class=\\\"stock-selection-right\\\" id=\\\"right-\" + stock.label + \"\\\">\" +\n \" <div class=\\\"stock-selection-summary-price\\\" id=\\\"price-\" + stock.label + \"\\\">\" +\n \" <label class=\\\"detail-label-price\\\" id=\\\"labelPrice-\" + stock.label + \"\\\">$\" + stock.price + \"</label>\" +\n \" </div>\" +\n \" <div class=\\\".stock-selection-change-value\\\" id=\\\"change-\" + stock.label + \"\\\">\" +\n \" <label class= \" + cssType + \" id=\\\"labelChange-\" + stock.label + \"\\\">\" + stock.priceChangeFromPreviousDay + \"%</label>\" +\n \" </div>\" +\n \" </div>\" +\n \" </div>\" +\n \"</div>\";\n\n index++;\n });\n\n boxControl += \"<div onclick = handleUpdateStockList(event)>\" +\n \" <div class=\\\"padding\\\">\" +\n \" <label class= \\\"load-more-label\\\" id=\\\"load-more\\\">Load more</label>\" +\n \" </div>\" +\n \"</div>\";\n\n stockHeader.innerHTML = boxControl;\n if (refresh)\n getAssetDataByTicker(getActiveStockTicker(), false, displayStockChart);\n\n stockHeader.style.maxHeight = String(window.innerHeight - 187) + \"px\";\n}",
"getData(base, date) {\n this.currencies = [];\n \n fetch(`https://api.exchangeratesapi.io/${date}?base=${base}`)\n .then(response => response.json())\n .then(json => {\n // console.log(json);\n for (const currency in json.rates) {\n this.currencies.push(new Currency(currency));\n }\n\n // Loop through currencies and set 'buy' to 5% less than conversion.\n // Loop through currencies and set 'sell' to 5% more than conversion.\n \n this.currencies.forEach(currency => {\n currency.buy = (json.rates[currency.name] * 0.95).toFixed(4);\n currency.sell = (json.rates[currency.name] * 1.05).toFixed(4);\n });\n\n // If page is being loaded for first time, table mounts.\n // Otherwise table updates with new base of alphabet order.\n \n if (this.table.mounted === false) {\n this.table.mount(container, this.currencies);\n } else {\n this.table.updateHTML(this.currencies, this.base);\n }\n });\n }",
"function getStockDisplay(stockName, sharePrice, pointChange, percentageChange) {\n var stockTable = $(\"<table class='centered table-no-format'><tbody><tr>\" +\n \"<td><p class='stock-name'></p></td><td>\" +\n \"<p class='stock-performance'><i class='stock-icon material-icons'></i>\" +\n \"<span class='stock-info-shareprice tooltipped' data-position='bottom' data-delay='50'></span><span class='stock-currency'>GBP</span>\" +\n \"<span class='stock-info-pointchange tooltipped' data-position='bottom' data-delay='50'></span>\" +\n \"<span class='stock-info-percentagechange tooltipped' data-position='bottom' data-delay='50'></span></p></td></tr></tbody></table>\");\n\n if (pointChange > 0) { //Stock is rising.\n stockTable.find(\".stock-performance\").addClass(\"stock-rise\").find(\".stock-icon\").text(\"keyboard_arrow_up\");\n }\n else if (pointChange < 0) { //Stock is falling.\n stockTable.find(\".stock-performance\").addClass(\"stock-fall\").find(\".stock-icon\").text(\"keyboard_arrow_down\");\n }\n else { //Stock is neutral.\n stockTable.find(\".stock-performance\").addClass(\"stock-flat\").find(\".stock-icon\").text(\"remove\");\n }\n\n //Includes stock information.\n stockTable.find(\".stock-name\").text(stockName); //Include stock name.\n stockTable.find(\".stock-info-shareprice\").text(sharePrice).attr(\"data-tooltip\", \"Share Price\");\n stockTable.find(\".stock-info-pointchange\").text(pointChange).attr(\"data-tooltip\", \"Point Change\");\n stockTable.find(\".stock-info-percentagechange\").text(\" (\" + percentageChange + \")\").attr(\"data-tooltip\", \"Percentage Change\");\n stockTable.find(\".tooltipped\").tooltip({delay: 50});\n return stockTable; //Return the jQuery object to be included in the chat window.\n }",
"function gen_data_rows () {\n // loop over rows of data\n for (var i = 0; i < rep_data.data.length; i++) {\n // create a html row for representing the data\n var data_row = document.createElement (\"tr\");\n // loop over elements in the data row, add the data\n for (var j = 0; j < rep_data.data [i].length; j++) {\n // create td element for the data\n var td = document.createElement (\"td\");\n // set value in the td\n td.innerHTML = rep_data.data [i][j];\n // append td to the row\n data_row.appendChild (td);\n }\n // add the row to rep_table\n rep_table.appendChild (data_row);\n }\n}",
"function get_daily_data() {\n //erase previous data in the table and make the first row with the legend\n var table = document.getElementById(\"output_table\");\n reset_table(table);\n\n //get all the data elemtents from the different files\n var cases = casesXML.getElementsByTagName('data');\n var testing = testingXML.getElementsByTagName('data');\n var hospital = hospitalXML.getElementsByTagName('data');\n\n //add code here to handle the extra data from the casesXML file\n\n\n //create a new row and insert the appropriate data into it\n for (i=0; i+3<cases.length; i++) {\n var row = table.insertRow(-1);\n var date_col = row.insertCell(0);\n date_col.innerHTML = cases[i+3].getElementsByTagName('date').item(0).innerHTML;\n var cases_col = row.insertCell(1);\n cases_col.innerHTML = cases[i+3].getElementsByTagName('newCasesByPublishDate').item(0).innerHTML;\n var tests_done_col = row.insertCell(2);\n tests_done_col.innerHTML = testing[i] != undefined ? testing[i].getElementsByTagName('newPCRTestsByPublishDate').item(0).innerHTML : \"\";\n var tests_planned_col = row.insertCell(3);\n tests_planned_col.innerHTML = testing[i] != undefined ? testing[i].getElementsByTagName('plannedPCRCapacityByPublishDate').item(0).innerHTML : \"\";\n var patients_in_hospital_col = row.insertCell(4);\n patients_in_hospital_col.innerHTML = hospital[i] != undefined ? hospital[i].getElementsByTagName('hospitalCases').item(0).innerHTML : \"\";\n }\n\n }",
"function buildHtmlTable() {\n\tvar columns = addAllColumnHeaders(myList);\n\n\tfor ( var i = 0; i < myList.length; i++) {\n\t\tvar row$ = $('<tr/>');\n\t\tfor ( var colIndex = 0; colIndex < columns.length; colIndex++) {\n\t\t\tvar cellValue = myList[i][columns[colIndex]];\n\n\t\t\tif (cellValue == null) {\n\t\t\t\tcellValue = \"\";\n\t\t\t}\n\n\t\t\trow$.append($('<td/>').html(cellValue));\n\t\t}\n\t\t$(\"#excelDataTable\").append(row$);\n\t}\n}",
"function renderJobsTable()\n{\n var data = globalJobList;\n var node = document.getElementById(\"jobs-table-body\");\n var tablenode = node.parentNode;\n tablenode.removeChild(node);\n\n // clear table\n {\n var n = node.firstElementChild;\n while (n != null)\n {\n var cn = n.nextElementSibling;\n node.removeChild(n)\n n = cn;\n }\n }\n\n if (data.length > 0)\n {\n for (var i = 0; i < data.length; ++i)\n {\n addJobRowAt(node,i);\n }\n }\n else\n {\n var tr = document.createElement(\"tr\");\n var td = document.createElement(\"td\"); td.setAttribute(\"colspan\",\"8\");\n var div = document.createElement(\"div\"); div.setAttribute(\"style\",\"margin : 10px 0px 10px 0px; text-align : center;\");\n div.appendChild(document.createTextNode(\"No entries\"));\n td.appendChild(div);\n tr.appendChild(td);\n node.appendChild(tr);\n\n rerenderSelection(node);\n }\n\n tablenode.appendChild(node);\n}",
"refreshStockIssueHistoryTable() {\n if (this.selectedStockItem != null) {\n this.params = 'employee/' + \"0/\" + this.selectedStockItem.id;\n this.employeeStockIssueHistoryListComponent.loadData(this.params);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CMS \\ Checks that the filename suffix in el is in allowed array | function checkFile(el,allowed) {
var suffix = $(el).val().split(".")[$(el).val().split(".").length-1].toUpperCase();
if (!(allowed.indexOf(suffix) !== -1)) {
alert("File type not allowed,\nAllowed files: *."+allowed.join(",*."));
$(el).val("");
}
} | [
"function gfnFileExtCheck(obj, arr){\n\tif( $(obj).val() != \"\" ){\n var ext = $(obj).val().split('.').pop().toLowerCase();\n\t\tif($.inArray(ext, arr) == -1) {\n\t\t\talert(arr+' 파일만 업로드 할 수 있습니다.');\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\treturn null;\n}",
"function fileExtension(str){\n\n // code goes here\n var result = \"\" || false;\n function each(collection, callback){\n \n if(typeof collection === \"string\"){\n \n for(var i = 0; i < collection.length; i++){\n \n callback(collection[i], i, collection);\n \n }\n \n }\n \n }\n \n each(n, function(item, index){\n \n if(item === \".\"){\n \n result = n.slice(index+1);\n \n }\n \n });\n \n return result;\n\n}",
"function fileTypeValidate(fileName,fileType){\r\n\r\n\t//get file name and extention name\r\n\t//var fileName=$(\"PB__FileInput\").value;\r\n\tvar fileExName=getFileExName(fileName);\r\n\tfileExName=fileExName.toLowerCase();\r\n\t\r\n\t//define file type list\r\n\t//image file list\r\n\tvar imageList=new Array(\"jpg\",\"gif\",\"jpeg\",\"bmp\",\"png\");\r\n\r\n\r\n\t//text file list\r\n\tvar textList=new Array(\"txt\",\"log\",\"text\",\"csv\");\r\n\r\n\t\r\n\t//binary file list\r\n\tvar binList=new Array(\"exe\",\"swf\",\"zip\",\"rar\");\r\n\t\r\n\t//other file list\r\n\tvar oList=new Array(\"doc\",\"docx\",\"xls\",\"xlsx\",\"ppt\",\"pptx\",\"pdf\",\"odt\",\"ods\",\"odp\",\"zip\",\"rar\");\r\n\t\r\n\t//image file validate\r\n\tif(fileType==\"IMAGE\"){\r\n\t\tfor(var i=0;i<imageList.length;i++){\r\n\t\t\tif(imageList[i].toString()==fileExName){\r\n\t\t\t\treturn true;\r\n\r\n\t\t\t}\r\n\t\t}\r\n\t//text file validate\r\n\t}else if(fileType==\"TEXT_FILE\"){\r\n\t\tfor(var i=0;i<textList.length;i++){\r\n\t\t\tif(textList[i].toString()==fileExName){\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t//binary file validate\r\n\t}else if(fileType==\"BINARY_FILE\"){\r\n\t\tfor(var i=0;i<textList.length;i++){\r\n\t\t\tif(textList[i].toString()==fileExName){\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\t}else if(fileType==\"PRODUCT_BROCHURE\" || fileType==\"ASSEMBLY_LIST\" || fileType==\"QUALITY_ASSURANCE\" ){\r\n\t\tfor(var i=0;i<oList.length;i++){\r\n\t\t\tif(oList[i].toString()==fileExName){\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\t\r\n\t}\r\n\t\r\n\treturn false;\r\n}",
"static matchFilename(descs, filename) {\n for (let d of descs)\n if (d.filename && d.filename.test(filename)) return d\n let ext = /\\.([^.]+)$/.exec(filename)\n if (ext)\n for (let d of descs) if (d.extensions.indexOf(ext[1]) > -1) return d\n return null\n }",
"function validateSuffixes(list) {\n list.forEach((bp) => {\n if (!bp.suffix) {\n bp.suffix = camelCase(bp.alias); // create Suffix value based on alias\n bp.overlapping = !!bp.overlapping; // ensure default value\n }\n });\n return list;\n}",
"function cs_contains_invalid_file_types(files, accepted_file_types){\r\n\t\r\n\tvar uploaded_files = files;\r\n\t\r\n\tvar invalid_file_types = 0;\r\n\t\r\n\tfor(var i = 0; i < uploaded_files.length; i++){\r\n\t\tif(!cs_validate_file_type(uploaded_files[i], accepted_file_types))\r\n\t\t\tinvalid_file_types++;\r\n\t}\r\n\t\r\n\treturn (invalid_file_types > 0) ? true : false;\r\n\t\r\n}",
"function has_sub_extension(e) {\n\t//if(process.env.DEBUG_MVC) {\n\t//\tdebug.log('has_sub_extension(', e, ')');\n\t//}\n\tdebug.assert(e).is('string');\n\treturn function has_sub_extension_2(p) {\n\t\tvar name = PATH.basename(p, PATH.extname(p));\n\t\treturn PATH.extname(name) === e;\n\t};\n}",
"function validVideoFileSet(files) {\r\n if (files.length) {\r\n var prefixname = \"\";\r\n var filenos = [];\r\n for (var i=0; i<files.length; i++) {\r\n var file = files[i];\r\n var fileparts = file.name.split(\".\");\r\n var fileno = parseInt(fileparts[fileparts.length-2], 10);\r\n var dateparts = fileparts[0].split(\"_\");\r\n // create prefix portion\r\n var prefix = \"\";\r\n for (var j=0; j<dateparts.length-2; j++) {\r\n prefix = prefix + dateparts[j];\r\n }\r\n if (prefixname === \"\") {\r\n prefixname = prefix;\r\n } else if (prefix != prefixname) {\r\n // multiple prefixes not allowed in multi-select\r\n return false;\r\n }\r\n var datepart = dateparts[dateparts.length-2];\r\n var datepart1 = dateparts[dateparts.length-1];\r\n var timepart = datepart1.substring(0, 2) + \":\" + datepart1.substring(2, 4);\r\n if (!validDate(datepart) || !validTime(timepart)) {\r\n // not a valid date & time suffix\r\n return false;\r\n }\r\n\r\n // Track the file indexes. Fail if the index is already in the array.\r\n if (filenos.indexOf(fileno) == -1) {\r\n filenos.push(fileno);\r\n } else {\r\n return false;\r\n }\r\n }\r\n } else {\r\n // no valid files\r\n return false;\r\n }\r\n // make sure the file indexes are contiguous. Fail if there are any gaps.\r\n filenos.sort(function(a, b){return a-b;});\r\n\r\n var index = filenos[0];\r\n for (i=1; i<filenos.length; i++) {\r\n if (filenos[i] != (index + 1)) {\r\n return false;\r\n }\r\n index = filenos[i];\r\n }\r\n\r\n // sort the files by title descending\r\n var sortedFiles = [].slice.call(files); // convert to sortable array\r\n sortedFiles.sort(function(a,b) {\r\n if ( a.name < b.name )\r\n return -1;\r\n if ( a.name > b.name )\r\n return 1;\r\n return 0;\r\n });\r\n return sortedFiles;\r\n}",
"function GruntFilesArrayExt ()\n{}",
"function FileName(evt) //Alphabates and .\n{\n var charCode = (evt.which) ? evt.which : event.keyCode\n if ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || (charCode == 32) || (charCode == 46) || (charCode == 40 || charCode == 41) || (charCode == 59) || (charCode == 46) || (charCode >= 48 && charCode <= 57))\n return true;\n else\n return false;\n}",
"function validateFileName(fname,path) {\n\tif ( fname == \"\" ) {\n return 1;\n } else {\n var isinvalid = 0;\n if (/^disk[0-2]|disk$/.test(path) == true || /^slot[0-1]$/.test(path) == true || /^NVRAM$/.test(path) == true || /^bootflash$/.test(path) == true || /^flash[0-1]|flash$/.test(path) == true) {\n if (/^[a-z|A-Z|0-9][0-9|a-z|\\-|\\_|A-Z|\\.]+$/.test(fname) == false) {\n if (/^[\\/][0-9|a-z|\\-|\\_|A-Z|\\.]+$/.test(fname) == false) {\n isinvalid = 1;\n }\n }\n } else if (/^[a-z|A-Z|0-9][0-9|a-z|\\-|\\_|A-Z|\\.]+$/.test(fname) == false) {\n isinvalid = 1;\n }\n return isinvalid;\n }\n}",
"function checkFileIsJDLFile(file) {\n if (file.slice(file.length - 3, file.length) !== '.jh'\n && file.slice(file.length - 4, file.length) !== '.jdl') {\n throw new Error(`The passed file '${file}' must end with '.jh' or '.jdl' to be valid.`);\n }\n}",
"function formatExtensions() {\n\n if (opt.properties.validExtensions !== \"\") {\n var extensionList = opt.properties.validExtensions.replaceAll(\"*\", \"\");\n extensionList = extensionList.replaceAll(\";\", \",\");\n\n opt.properties.processedFileExtension = extensionList;\n }\n }",
"function txtExtension(fileName) {\n var c = fileName.indexOf(\".\");\n var w = fileName.substring(c + 1, fileName.length);\n if (w != \"txt\") return false;\n return true;\n}",
"function has_extension(e) {\n\t//if(process.env.DEBUG_MVC) {\n\t//\tdebug.log('has_extension(', e, ')');\n\t//}\n\tdebug.assert(e).is('string');\n\treturn function has_extension_2(p) {\n\t\treturn PATH.extname(p) === e;\n\t};\n}",
"function namesToCheckAgainst( nameToCheck, fn) {\n validNames.forEach( name => fn(name, nameToCheck) );\n}",
"function validarFormatoImagen() {\n var extensionImagenes = /(.jpg|.jpeg|.png)$/i;\n var imagen = document.getElementById(\"img_area\");\n var archivo = imagen.value;\n if (!extensionImagenes.test(archivo)) {\n console.log(archivo);\n alert(\"El formato de la imagen no es válido.\");\n document.getElementById(\"img_area\").value = \"\"; \n }\n}",
"function w3_ext_param_array_match_str(arr, s, func)\n{\n var found = false;\n arr.forEach(function(a_el, i) {\n var el = a_el.toString().toLowerCase();\n //console.log('w3_ext_param_array_match_str CONSIDER '+ i +' '+ el +' '+ s);\n if (!found && el.startsWith(s)) {\n //console.log('w3_ext_param_array_match_str MATCH '+ i);\n if (func) func(i, a_el.toString());\n found = true;\n }\n });\n return found;\n}",
"function extension (expectedExtension, filename) {\n\t verify(low.unemptyString(expectedExtension), 'missing expected extension', expectedExtension)\n\t verify(low.unemptyString(filename), 'missing filename', filename)\n\t var reg = new RegExp('.' + expectedExtension + '$')\n\t return reg.test(filename)\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to update orbs position and calculate intersection points for all rays | update(x,y){
if (x > 0 & x < width){
if(y > 0 & y < height/2){
//if(!this.nearWall()){
this.pos.x= x;
this.pos.y= y;
for (var i = 0; i < this.rays.length;i++) {
this.rays[i].update(this.pos)
let rmagold = Infinity;
for(let bound of bounds){
let rmag = bound.intersect(this.rays[i].pos,this.rays[i].dir);
if(rmag < rmagold) rmagold = rmag;
}
this.rays[i].mag = rmagold;
}
//}
}
}
} | [
"intersection () {\n var tan = this.vector.y / this.vector.x,\n _this = this,\n from, to,\n cursorDegree = -Math.atan2(-this.vector.y, -this.vector.x) * 180/Math.PI + 180;\n\n\n for (var i= 0, max = this.cache.length; i < max; i++) {\n var item = _this.cache[i];\n\n from = item.range[0];\n to = item.range[1];\n\n // If one of item's sides area is on the edge state. For example\n // when we have item which 'from' begins from 157 and ends to -157, when all\n // 'cursorDegree' values are appear hear. To not let this happen, we compare\n // 'from' and 'to' and reverse comparing operations.\n if (from > to) {\n if (cursorDegree <= from && cursorDegree <= to || cursorDegree >= from && cursorDegree >= to) {\n _this.activate(item);\n }\n } else {\n if (cursorDegree >= from && cursorDegree <= to) {\n _this.activate(item);\n }\n }\n }\n this.cache.forEach(function (item) {\n\n })\n }",
"compute(pointer1, pointer2, partialSelect) {\n\n // build 4 rays to project the 4 corners\n // of the selection window\n\n const xMin = Math.min(pointer1.clientX, pointer2.clientX);\n const xMax = Math.max(pointer1.clientX, pointer2.clientX);\n\n const yMin = Math.min(pointer1.clientY, pointer2.clientY);\n const yMax = Math.max(pointer1.clientY, pointer2.clientY);\n\n const ray1 = this.pointerToRay({\n clientX: xMin,\n clientY: yMin\n })\n\n const ray2 = this.pointerToRay({\n clientX: xMax,\n clientY: yMin\n })\n\n const ray3 = this.pointerToRay({\n clientX: xMax,\n clientY: yMax\n })\n\n const ray4 = this.pointerToRay({\n clientX: xMin,\n clientY: yMax\n })\n\n // first we compute the top of the pyramid\n const top = new THREE.Vector3(0, 0, 0)\n\n top.add(ray1.origin)\n top.add(ray2.origin)\n top.add(ray3.origin)\n top.add(ray4.origin)\n\n top.multiplyScalar(0.25)\n\n // we use the bounding sphere to determine\n // the height of the pyramid\n const {center, radius} = this.boundingSphere\n\n // compute distance from pyramid top to center\n // of bounding sphere\n\n const dist = new THREE.Vector3(\n top.x - center.x,\n top.y - center.y,\n top.z - center.z)\n\n // compute height of the pyramid:\n // to make sure we go far enough,\n // we add the radius of the bounding sphere\n\n const height = radius + dist.length()\n\n // compute the length of the side edges\n\n const angle = ray1.direction.angleTo(\n ray2.direction)\n\n const length = height / Math.cos(angle * 0.5)\n\n // compute bottom vertices\n\n const v1 = new THREE.Vector3(\n ray1.origin.x + ray1.direction.x * length,\n ray1.origin.y + ray1.direction.y * length,\n ray1.origin.z + ray1.direction.z * length)\n\n const v2 = new THREE.Vector3(\n ray2.origin.x + ray2.direction.x * length,\n ray2.origin.y + ray2.direction.y * length,\n ray2.origin.z + ray2.direction.z * length)\n\n const v3 = new THREE.Vector3(\n ray3.origin.x + ray3.direction.x * length,\n ray3.origin.y + ray3.direction.y * length,\n ray3.origin.z + ray3.direction.z * length)\n\n const v4 = new THREE.Vector3(\n ray4.origin.x + ray4.direction.x * length,\n ray4.origin.y + ray4.direction.y * length,\n ray4.origin.z + ray4.direction.z * length)\n\n // create planes\n\n const plane1 = new THREE.Plane()\n const plane2 = new THREE.Plane()\n const plane3 = new THREE.Plane()\n const plane4 = new THREE.Plane()\n const plane5 = new THREE.Plane()\n\n plane1.setFromCoplanarPoints(top, v1, v2)\n plane2.setFromCoplanarPoints(top, v2, v3)\n plane3.setFromCoplanarPoints(top, v3, v4)\n plane4.setFromCoplanarPoints(top, v4, v1)\n plane5.setFromCoplanarPoints(v3, v2, v1)\n\n const planes = [\n plane1, plane2,\n plane3, plane4,\n plane5\n ]\n\n const vertices = [\n v1, v2, v3, v4, top\n ]\n\n // filter all bounding boxes to determine\n // if inside, outside or intersect\n\n const result = this.filterBoundingBoxes(\n planes, vertices, partialSelect)\n\n // all inside bboxes need to be part of the selection\n\n const dbIdsInside = result.inside.map((bboxInfo) => {\n\n return bboxInfo.dbId\n })\n\n // if partialSelect = true\n // we need to return the intersect bboxes\n\n if (partialSelect) {\n\n const dbIdsIntersect = result.intersect.map((bboxInfo) => {\n\n return bboxInfo.dbId\n })\n\n // At this point perform a finer analysis\n // to determine if the any of the mesh vertices are inside\n // or outside the selection window but it would\n // be a much more expensive computation\n\n //const dbIdsIntersectAccurate =\n // dbIdsIntersect.filter((dbId) => {\n //\n // const geometry =\n // Toolkit.buildComponentGeometry(\n // this.viewer, this.viewer.model, dbId)\n //\n // return this.containsVertex(\n // planes, geometry.vertices)\n // })\n\n return [...dbIdsInside, ...dbIdsIntersect]\n }\n\n return dbIdsInside\n }",
"calcCorners() {\n\n let degR = this.rotation*Math.PI/180;\n\n this.corners[0] = new Vector(\n this.position.x + this.length*Math.cos(degR) - this.width*Math.sin(degR),\n this.position.y + this.length*Math.sin(degR) + this.width*Math.cos(degR)\n );\n\n this.corners[1] = new Vector(\n this.position.x + this.length*Math.cos(degR) + this.width*Math.sin(degR),\n this.position.y + this.length*Math.sin(degR) - this.width*Math.cos(degR)\n );\n\n this.corners[2] = new Vector(\n this.position.x - this.length*Math.cos(degR) + this.width*Math.sin(degR),\n this.position.y - this.length*Math.sin(degR) - this.width*Math.cos(degR)\n );\n\n this.corners[3] = new Vector(\n this.position.x - this.length*Math.cos(degR) - this.width*Math.sin(degR),\n this.position.y - this.length*Math.sin(degR) + this.width*Math.cos(degR)\n );\n\n this.hitboxLines[0].setStartEnd(this.corners[0], this.corners[1]);\n this.hitboxLines[1].setStartEnd(this.corners[1], this.corners[2]);\n this.hitboxLines[2].setStartEnd(this.corners[2], this.corners[3]);\n this.hitboxLines[3].setStartEnd(this.corners[3], this.corners[0]);\n\n this.areCornersCorrect = true;\n }",
"function rayTriangleMollerTrumbore(rayOrigin, rayDirection, v0, v1, v2)\r\n{\r\n let epsilon = 0.000001;\r\n let edge1 = new THREE.Vector3()\r\n let edge2 = new THREE.Vector3()\r\n let h = new THREE.Vector3()\r\n let s = new THREE.Vector3()\r\n let q = new THREE.Vector3()\r\n\r\n let a, f, u, v\r\n //float a,f,u,v;\r\n edge1.subVectors(v1, v0)\r\n edge2.subVectors(v2, v0);\r\n h.crossVectors(rayDirection, edge2);\r\n a = edge1.dot(h);\r\n if (a > -epsilon && a < epsilon) return false; // Le rayon est parallèle au triangle.\r\n\r\n f = 1.0/a;\r\n s.subVectors(rayOrigin, v0);\r\n u = f * s.dot(h);\r\n if (u < 0.0 || u > 1.0) return false;\r\n q.crossVectors(s, edge1);\r\n v = f * rayDirection.dot(q);\r\n if (v < 0.0 || u + v > 1.0) return false;\r\n\r\n // On calcule t pour savoir ou le point d'intersection se situe sur la ligne.\r\n let t = f * edge2.dot(q);\r\n if (t > epsilon) // Intersection avec le rayon\r\n {\r\n let retret = new THREE.Vector3()\r\n retret = rayOrigin.clone()\r\n retret.addScaledVector(rayDirection, t)\r\n return retret;\r\n }else return false;\r\n}",
"function intersector(event){\n\t \tvar vector = new THREE.Vector3(\n\t ( event.offsetX / scene.width ) * 2 - 1,\n\t - ( event.offsetY / scene.height ) * 2 + 1,\n\t \t.5\n\t );\n\t \tcontroller.projector.unprojectVector( vector, camera );\n\t var ray = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());\n\t \tray.precision = 0.001;\n\t return ray;\n\t}",
"function RayHelper(ray){this.ray=ray;}",
"function obstructedBy(curX, curY, tarX, tarY) {\n\tobj = null;\n\tside = null;\n\tstep = 1;\n\t//the y part is wrong because we measure from the top left not the bottom left\n\tm = (tarY - curY)/(tarX - curX); //calculate the gradient of the line between the 2 positions\n\t//loop through every x coordinate between the current x value and the target x value\n\t//find out which way the target is\n\tif (tarX > curX) {\n\t\tfor (i = 0; i < tarX - curX; i = i + step) {\n\t\t\tx = curX + i; //calculate x value along the line\n\t\t\ty = curY + m * i; //calculate y value along the line\n\t\t\tfor (j = 0; j < collideObjs.length; j++) {\n\t\t\t\t//check if the coordinate is in the object\n\t\t\t\tif (isColliding(x, y, j)) {\n\t\t\t\t\tobj = collideObjs[j]; //return the first object in the way\n\t\t\t\t\tside = getSide(curX, curY, tarX, tarY, j);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (obj != null) {\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else if (tarX < curX) {\n\t\tfor (i = 0; i > tarX - curX; i = i - step) {\n\t\t\tx = curX + i; //calculate x value along the line\n\t\t\ty = curY + m * i; //calculate y value along the line\n\t\t\tfor (j = 0; j < collideObjs.length; j++) {\n\t\t\t\t//check if the coordinate is in the object\n\t\t\t\tif (isColliding(x, y, j)) {\n\t\t\t\t\tobj = collideObjs[j]; //return the first object in the way\n\t\t\t\t\tside = getSide(curX, curY, tarX, tarY, j);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (obj != null) {\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else if (tarX == curX) {\n\t\tif (tarY > curY) {\n\t\t\tfor (i = 0; i < tarY - curY; i = i + step) {\n\t\t\t\tx = curX; //calculate x value along the line\n\t\t\t\ty = curY + i; //calculate y value along the line\n\t\t\t\tfor (j = 0; j < collideObjs.length; j++) {\n\t\t\t\t\t//check if the coordinate is in the object\n\t\t\t\t\tif (isColliding(x, y, j)) {\n\t\t\t\t\t\tobj = collideObjs[j]; //return the first object in the way\n\t\t\t\t\t\tside = getSide(curX, curY, tarX, tarY, j);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (obj != null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (tarY < curY) {\n\t\t\tfor (i = 0; i < curY - tarY; i = i + step) {\n\t\t\t\tx = curX; //calculate x value along the line\n\t\t\t\ty = curY - i; //calculate y value along the line\n\t\t\t\tfor (j = 0; j < collideObjs.length; j++) {\n\t\t\t\t\t//check if the coordinate is in the object\n\t\t\t\t\tif (isColliding(x, y, j)) {\n\t\t\t\t\t\tobj = collideObjs[j]; //return the first object in the way\n\t\t\t\t\t\tside = getSide(curX, curY, tarX, tarY, j);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (obj != null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tretr = {\n\t\tobj: obj,\n\t\tside: side\n\t}\n\treturn retr;\n}",
"assign(centrs) {\n\n let APoints = [],\n BPoints = [];\n\nlet points = this.points;\n points.forEach((val, i) => {\n\n let zerox = points[i].x - centrs[0].x; // distance to 1st centroid\n let zeroy = points[i].y - centrs[0].y;\n let onex = points[i].x - centrs[1].x; // distance to 2nd centroid\n let oney = points[i].y - centrs[1].y;\n\n\n // get posititive of each point from each centroid\n let sqzerox = Math.sqrt(zerox * zerox);\n let sqzeroy = Math.sqrt(zeroy * zeroy);\n let sqonex = Math.sqrt(onex * onex);\n let sqoney = Math.sqrt(oney * oney);\n\n // if the point is within the range (all points have less distance than 110 px to all points) push it to according array\n let ranges = this.getRanges();\n (sqzerox || sqzeroy) < ranges.xrange / 3 ? APoints.push(points[i]) : 0;\n (sqonex || sqoney) < ranges.xrange / 3 ? BPoints.push(points[i]) : 0;\n });\n\n return {\n AP: APoints,\n BP: BPoints\n };\n }",
"intersectionRayMesh(mesh, vNearOrig, vFarOrig) {\n // resest picking\n this._mesh = null;\n this._pickedFace = -1;\n // resest picking\n vec3.copy(_TMP_NEAR, vNearOrig);\n vec3.copy(_TMP_FAR, vFarOrig);\n // apply symmetry\n if (this._xSym) {\n var ptPlane = mesh.getSymmetryOrigin();\n var nPlane = mesh.getSymmetryNormal();\n Geometry.mirrorPoint(_TMP_NEAR, ptPlane, nPlane);\n Geometry.mirrorPoint(_TMP_FAR, ptPlane, nPlane);\n }\n var vAr = mesh.getVertices();\n var fAr = mesh.getFaces();\n // compute eye direction\n var eyeDir = this.getEyeDirection();\n vec3.sub(eyeDir, _TMP_FAR, _TMP_NEAR);\n vec3.normalize(eyeDir, eyeDir);\n var iFacesCandidates = mesh.intersectRay(_TMP_NEAR, eyeDir);\n var distance = Infinity;\n var nbFacesCandidates = iFacesCandidates.length;\n for (var i = 0; i < nbFacesCandidates; ++i) {\n var indFace = iFacesCandidates[i] * 4;\n var ind1 = fAr[indFace] * 3;\n var ind2 = fAr[indFace + 1] * 3;\n var ind3 = fAr[indFace + 2] * 3;\n _TMP_V1[0] = vAr[ind1];\n _TMP_V1[1] = vAr[ind1 + 1];\n _TMP_V1[2] = vAr[ind1 + 2];\n _TMP_V2[0] = vAr[ind2];\n _TMP_V2[1] = vAr[ind2 + 1];\n _TMP_V2[2] = vAr[ind2 + 2];\n _TMP_V3[0] = vAr[ind3];\n _TMP_V3[1] = vAr[ind3 + 1];\n _TMP_V3[2] = vAr[ind3 + 2];\n var hitDist = Geometry.intersectionRayTriangle(_TMP_NEAR, eyeDir, _TMP_V1, _TMP_V2, _TMP_V3, _TMP_INTER);\n if (hitDist < 0.0) {\n ind2 = fAr[indFace + 3];\n if (ind2 !== Utils.TRI_INDEX) {\n ind2 *= 3;\n _TMP_V2[0] = vAr[ind2];\n _TMP_V2[1] = vAr[ind2 + 1];\n _TMP_V2[2] = vAr[ind2 + 2];\n hitDist = Geometry.intersectionRayTriangle(_TMP_NEAR, eyeDir, _TMP_V1, _TMP_V3, _TMP_V2, _TMP_INTER);\n }\n }\n if (hitDist >= 0.0 && hitDist < distance) {\n distance = hitDist;\n vec3.copy(this._interPoint, _TMP_INTER);\n this._pickedFace = iFacesCandidates[i];\n }\n }\n if (this._pickedFace !== -1) {\n this._mesh = mesh;\n this.updateLocalAndWorldRadius2();\n return true;\n }\n this._rLocal2 = 0.0;\n return false;\n }",
"update(){\n // verifica daca particula se afla inca in canvas\n if(this.x > canvas.width || this.x < 0){\n this.directionX = -this.directionX;\n }\n if(this.y > canvas.height || this.y < 0){\n this.directionY = -this.directionY;\n }\n\n // verifica collision detection cu cursorul\n let dx = mouse.x - this.x;\n let dy = mouse.y - this.y;\n let distance = Math.sqrt(dx*dx + dy*dy);\n if(distance < mouse.radius + this.size){\n //trebuie sa verificam din ce directie vine cursorul si sa ne asiguram ca particula se afla inca in canvas,\n //pentru ca coliziunea cu cercul care inconjoara cursorul sa aiba efect, iar buffer area intre canvas si particula este de 10 ori dimensiunea sa\n if(mouse.x < this.x && this.x < canvas.width - this.size * 10){\n this.x += 10;\n }\n if(mouse.x > this.x && this.x > this.size * 10){\n this.x -= 10;\n }\n if(mouse.y < this.y && this.y < canvas.height - this.size * 10){\n this.y += 10;\n }\n if(mouse.y > this.y && this.y > this.size * 10){\n this.y -= 10;\n }\n }\n // pentru formula asta, m-a ajutat foarte mult documentatia celor de la MDN https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection\n \n\n // codul de mai jos asigura ca particulele se vor misca in permanenta, pe axele lor, asta pana in momentul in care este intalnita coliziunea\n this.x += this.directionX;\n this.y += this.directionY;\n this.draw();\n }",
"intersectionMouseMeshes(meshes = this._main.getMeshes(), mouseX = this._main._mouseX, mouseY = this._main._mouseY) {\n var cray = WEBVR.controllerRay(1);\n var vNear = cray[0];\n var vFar = cray[1];\n var nearDistance = Infinity;\n var nearMesh = null;\n var nearFace = -1;\n\n for (var i = 0, nbMeshes = meshes.length; i < nbMeshes; ++i) {\n var mesh = meshes[i];\n mat4.invert(_TMP_INV, mesh.getMatrix());\n vec3.transformMat4(_TMP_NEAR_1, vNear, _TMP_INV);\n vec3.transformMat4(_TMP_FAR, vFar, _TMP_INV);\n if (!this.intersectionRayMesh(mesh, _TMP_NEAR_1, _TMP_FAR))\n continue;\n\n var interTest = this.getIntersectionPoint();\n var testDistance = vec3.dist(_TMP_NEAR_1, interTest) * mesh.getScale();\n if (testDistance < nearDistance) {\n nearDistance = testDistance;\n nearMesh = mesh;\n vec3.copy(_TMP_INTER_1, interTest);\n nearFace = this.getPickedFace();\n }\n }\n\n this._mesh = nearMesh;\n vec3.copy(this._interPoint, _TMP_INTER_1);\n this._pickedFace = nearFace;\n if (nearFace !== -1)\n this.updateLocalAndWorldRadius2();\n return !!nearMesh;\n }",
"function intersection(ray, objects, tMin) {\n let closest = null;\n for (let k = 0; k < objects.length; k++) {\n const t = objects[k].intersects(ray);\n // intersects, not behind the eye, and the closest\n if (t != null && t > 0 && t < tMin) {\n closest = objects[k];\n tMin = t;\n }\n }\n return { obj: closest, tVal: tMin };\n}",
"function refract(rayDirection, normal, ior) {\n let cosi = vec3.dot(rayDirection, normal);\n let etaOut = 1;\n let etaIn = ior;\n if (cosi < 0) {\n cosi = -cosi;\n } else { // ray hits from inside the object\n [etaOut, etaIn] = [etaIn, etaOut]; // swap etaOut and etaIn\n vec3.negate(normal, normal);\n }\n const eta = etaOut / etaIn;\n\n const determinant = 1 - eta * eta * (1 - cosi * cosi);\n if (determinant < 0) { // total internal reflection\n return vec3.create(); // no ray is generated; TODO: right?\n }\n return vec3.add(vec3.create(), vec3.scale(vec3.create(), rayDirection, eta),\n vec3.scale(vec3.create(), normal, eta * cosi - Math.sqrt(determinant)));\n}",
"pickVerticesInSphereTopological(rLocal2) {\n var mesh = this._mesh;\n var nbVertices = mesh.getNbVertices();\n var vAr = mesh.getVertices();\n var fAr = mesh.getFaces();\n\n var vrvStartCount = mesh.getVerticesRingVertStartCount();\n var vertRingVert = mesh.getVerticesRingVert();\n var ringVerts = vertRingVert instanceof Array ? vertRingVert : null;\n\n var vertSculptFlags = mesh.getVerticesSculptFlags();\n var vertTagFlags = mesh.getVerticesTagFlags();\n\n var sculptFlag = ++Utils.SCULPT_FLAG;\n var tagFlag = ++Utils.TAG_FLAG;\n\n var inter = this.getIntersectionPoint();\n var itx = inter[0];\n var ity = inter[1];\n var itz = inter[2];\n\n var pickedVertices = new Uint32Array(Utils.getMemory(4 * nbVertices), 0, nbVertices);\n var idf = this.getPickedFace() * 4;\n var acc = 1;\n\n if (this._isInsideSphere(fAr[idf], inter, rLocal2)) pickedVertices[0] = fAr[idf];\n else if (this._isInsideSphere(fAr[idf + 1], inter, rLocal2)) pickedVertices[0] = fAr[idf + 1];\n else if (this._isInsideSphere(fAr[idf + 2], inter, rLocal2)) pickedVertices[0] = fAr[idf + 2];\n else if (this._isInsideSphere(fAr[idf + 3], inter, rLocal2)) pickedVertices[0] = fAr[idf + 3];\n else acc = 0;\n\n if (acc === 1) {\n vertSculptFlags[pickedVertices[0]] = sculptFlag;\n vertTagFlags[pickedVertices[0]] = tagFlag;\n }\n\n for (var i = 0; i < acc; ++i) {\n var id = pickedVertices[i];\n var start, end;\n if (ringVerts) {\n vertRingVert = ringVerts[id];\n start = 0;\n end = vertRingVert.length;\n } else {\n start = vrvStartCount[id * 2];\n end = start + vrvStartCount[id * 2 + 1];\n }\n\n for (var j = start; j < end; ++j) {\n var idv = vertRingVert[j];\n if (vertTagFlags[idv] === tagFlag)\n continue;\n vertTagFlags[idv] = tagFlag;\n\n var id3 = idv * 3;\n var dx = itx - vAr[id3];\n var dy = ity - vAr[id3 + 1];\n var dz = itz - vAr[id3 + 2];\n if ((dx * dx + dy * dy + dz * dz) > rLocal2)\n continue;\n\n vertSculptFlags[idv] = sculptFlag;\n pickedVertices[acc++] = idv;\n }\n }\n\n this._pickedVertices = new Uint32Array(pickedVertices.subarray(0, acc));\n return this._pickedVertices;\n }",
"function rayXline(rx, ry, dx, dy, x1, y1, x2, y2, infinite){\n\t\n\tvar lx, ly, d, nx, ny, a, b;\n\tlx = x2 - x1;\n\tly = y2 - y1;\n\td = Math.sqrt(lx * lx + ly * ly);\n\tnx = ly / d;\n\tny = -lx / d;\n\t\n\ta = dx * nx + dy * ny;\n\tb = (x1 - rx) * nx + ( y1 - ry ) * ny;\n\n\tif( a != 0 && ( a > 0 ^ b < 0 ) ){//Check if there is an intersection with the inifinite line\n\t\n\t\tl = b / a;\n\t\tif( infinite )\n\t\t\treturn l;\n\t\telse {\n\t\t\tvar xx = rx + dx * l;\n\t\t\tvar yy = ry + dy * l;\n\t\t\tvar g = ((xx - x1) * lx + (yy - y1) * ly) / (lx * lx + ly * ly);\n\t\t\tif( g >= 0 && g <= 1)\n\t\t\t\treturn l;\n\t\t\telse return null;\n\t\t\t\n\t\t}\n\t} else return null;\n}",
"function intersection(pos1, vec1, pos2, vec2){\n //This function is based on this math:\n //https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect\n // pos1 == p\n // vec1 == r\n // pos2 == q\n // vec2 == s\n\n let denom = crossProduct(vec1, vec2); //(r × s)\n let num1 = crossProduct(subVectors(pos2, pos1) , vec2); //(q − p) × s\n let num2 = crossProduct(subVectors(pos2, pos1) , vec1); //(q − p) × r\n\n if(denom == 0) //don't really care if they're parallel for my purposes.\n return null;\n\n let t = num1 / denom;\n let u = num2 / denom;\n\n if(t > 0 && t < 1 && u > 0 && u < 1) {\n let offset = new Vector(vec1.x, vec1.y);\n multVector(offset, t);\n return addVectors(pos1, offset);\n }\n\n return null;\n}",
"align(boid) {\r\n\t\tconst alignCo = 0.05;\r\n\t\tlet dx = 0;\r\n\t\tlet dy = 0;\r\n\t\tlet count = 0;\r\n\r\n\t\tfor (var i = 0; i < boid.length; i++) {\r\n\t\t\tif (boid[i].id !== this.id) {\r\n\t\t\t\tif (this.distance(this.x, this.y, boid[i].x, boid[i].y) < visualRange) {\r\n\t\t\t\t\tdx += boid[i].vx;\r\n\t\t\t\t\tdy += boid[i].vy;\r\n\t\t\t\t\tcount++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (count) {\r\n\t\t\tdx = dx / count;\r\n\t\t\tdy = dy / count;\r\n\t\t\tthis.vx += (dx - this.vx) * alignCo * Align;\r\n\t\t\tthis.vy += (dy - this.vy) * alignCo * Align;\r\n\t\t}\r\n\t}",
"function lineIntersectCircle(pointa, pointb, center, radius) {\n var result = {};\n var a = (pointb.x - pointa.x) * (pointb.x - pointa.x) + (pointb.y - pointa.y) * (pointb.y - pointa.y);\n var b = 2 * ((pointb.x - pointa.x) * (pointa.x - center.x) + (pointb.y - pointa.y) * (pointa.y - center.y));\n var cc = center.x * center.x + center.y * center.y + pointa.x * pointa.x + pointa.y * pointa.y -\n 2 * (center.x * pointa.x + center.y * pointa.y) - radius * radius;\n var deter = b * b - 4 * a * cc;\n\n function interpolate(p1, p2, d) {\n return {\n x: p1.x + (p2.x - p1.x) * d,\n y: p1.y + (p2.y - p1.y) * d\n };\n }\n if (deter <= 0) {\n result.inside = false;\n } else {\n var e = Math.sqrt(deter);\n var u1 = (-b + e) / (2 * a);\n var u2 = (-b - e) / (2 * a);\n if ((u1 < 0 || u1 > 1) && (u2 < 0 || u2 > 1)) {\n if ((u1 < 0 && u2 < 0) || (u1 > 1 && u2 > 1)) {\n result.inside = false;\n } else {\n result.inside = true;\n }\n } else {\n if (0 <= u2 && u2 <= 1) {\n result.enter = interpolate(pointa, pointb, u2);\n }\n if (0 <= u1 && u1 <= 1) {\n result.exit = interpolate(pointa, pointb, u1);\n }\n result.intersects = true;\n }\n }\n return result;\n }",
"function cullIntersections() {\n function toLines(pts) {\n let lns = [];\n for (let i=0, il=pts.length; i<il; i += 2) {\n lns.push({a: pts[i], b: pts[i+1], l: pts[i].distTo2D(pts[i+1])});\n }\n return lns;\n }\n let aOa = [...arguments].filter(t => t);\n if (aOa.length < 1) return;\n let aa = toLines(aOa.shift());\n while (aOa.length) {\n let bb = toLines(aOa.shift());\n loop: for (let i=0, il=aa.length; i<il; i++) {\n let al = aa[i];\n if (al.del) {\n continue;\n }\n for (let j=0, jl=bb.length; j<jl; j++) {\n let bl = bb[j];\n if (bl.del) {\n continue;\n }\n if (base.util.intersect(al.a, al.b, bl.a, bl.b, base.key.SEGINT)) {\n if (al.l < bl.l) {\n bl.del = true;\n } else {\n al.del = true;\n }\n continue;\n }\n }\n }\n aa = aa.filter(l => !l.del).concat(bb.filter(l => !l.del));\n }\n let good = [];\n for (let i=0, il=aa.length; i<il; i++) {\n let al = aa[i];\n good.push(al.a);\n good.push(al.b);\n }\n return good.length > 2 ? good : [];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
show bulk sms transfer modal box | function showSmsMultiModal()
{
//alert($('#leadsCount').val());
var count = parseInt($('#leadsCount').val());
if(count)
{
var leadCountTxt = (count>1)?count+" Leads":count+" Lead";
//alert('showTransferMultiModal');
$(".leadCountTxt").text(leadCountTxt);
$("#smsMultiModal").modal('show');
$.post(base_url+'plugins/get_sms_list',
function(msg){
$('#smsTemplates').html(msg);
});
}
else
{
alert("Select a record to transfer.");
}
} | [
"function showSMSDialog() {\n var SMS = require('ti.sms');\n \n var SMSDialog = SMS.createSMSDialog({\n barColor: \"black\",\n toRecipients: [\"1234567890\", \"0987654321\"],\n subject: \"What's up?\",\n messageBody: \"Titanium rocks! 🔥\"\n });\n \n if (!SMS.canSendText()) {\n Ti.API.error(\"Device cannot send SMS!\");\n return;\n }\n \n if (!SMS.canSendSubject()) {\n Ti.API.error(\"Device cannot send subject!\");\n return;\n }\n \n if (!SMS.canSendAttachments()) {\n Ti.API.error(\"Device cannot send attachments!\");\n return;\n } else {\n SMSDialog.addAttachments([Ti.Filesystem.getFile(Ti.Filesystem.getResourcesDirectory(), \"KS_nav_ui.png\").read()])\n }\n\n SMSDialog.addEventListener('complete', function(e) {\n if (e.success) {\n alert('SMS sent!');\n } else {\n switch (e.result) {\n case SMS.CANCELLED:\n alert('User cancelled SMS!');\n break;\n case SMS.FAILED:\n default:\n alert(e.error);\n }\n }\n });\n\n SMSDialog.open({\n animated: true\n });\n}",
"function showStatusMultimodal()\n {\n //alert($('#leadsCount').val());\n var count = parseInt($('#leadsCount').val());\n if(count)\n {\n var leadCountTxt = (count>1)?count+\" Leads\":count+\" Lead\";\n //alert('showTransferMultiModal');\n $(\".leadCountTxt\").text(leadCountTxt);\n $(\"#show_status_multimodal\").modal('show');\n\n $.post(base_url+'plugins/get_status_list',\n function(msg){\n $('#statusId').html(msg);\n });\n }\n else\n {\n alert(\"Select a record to transfer.\");\n }\n }",
"function progressPatient(queue) {\n setShow('send');\n }",
"function bSmsTwitterAllCon(senderId,broadCast_name,broadCast_message,x)\n{\n\t$('#takeOneAction').val('false');\n\tvar rEmail=0;var rTts=0;var rSms=1;var rTwitter=1;\n\t//checks of validations\n\tsmsCntVal(senderId);\n\tgeneralValidations(broadCast_name,broadCast_message);\n\tconsole.log(\"sms twitter to all contacts\");\n\t//checks for validations\n\tvar res = calculateRecipients(rEmail,rTts,rSms,rTwitter);\n\tvar Valueofcheckboxtwtvo=res[3];\n\tvar Valueofcheckboxmob=res[1];\n\trecipientVal(res[4]);\n\tbroadCast_message = broadCast_message.split('\"').join('');\n\tbroadCast_message = broadCast_message.split('\\n').join('');\n\t//setting JSON\n\tdatasinfo = '{\"senderName\":\"'+senderId+'\",\"message\":\"'+broadCast_message+'\",\"broadcastName\":\"'+broadCast_name+'\",'+Valueofcheckboxmob+','+Valueofcheckboxtwtvo+'}}';\n\tif(broadCast_name!=''&&broadCast_message!=''&&broadCast_message!=' '&&res[4]!=0&&senderId!='')\n\t\t{\n\t\t\tconsole.log('sending');\n\t\t\t$(\"#main\").css({\"opacity\": \"0.3\"});\n\t\t\tbroadcastFunc(datasinfo,x);\n\t\t}\n}",
"displayMessages() {\n\t\tfor(var i = 0; i < this.messages.length; i++) {\n\t\t\t$(\"#newRecordModalDiv\").append('<p style=\"font-size:large\">' + this.messages[i] + '<p><br/>');\n\t\t}\n\t\t$(\"#recordScoreModal\").modal('show');\n\t}",
"function writeNewMessage(){\r\n $( 'body' ).on( 'click', 'button.write-new-message', function () {\r\n $( 'div#sm-send-new-message' ).show(1);\r\n $( 'div#sm-send-new-message' ).addClass( 'sidemodal-showing' );\r\n $( 'body' ).addClass( 'bsm-active' );\r\n });\r\n $( 'body' ).on( 'click', 'div#sm-send-new-message a.btn-smclose', function () {\r\n $( 'div#check-discard-message' ).show(1);\r\n $( 'div#check-discard-message' ).addClass( 'receiptmodal-showing' );\r\n $( 'body' ).addClass('brm-active');\r\n // $( 'div#sm-send-new-message' ).removeClass( 'sidemodal-showing' );\r\n // $( 'body' ).removeClass( 'bsm-active' );\r\n });\r\n}",
"function bTtsSmsTwitterAllCon(senderId,broadCast_name,broadCast_message,lCode,x)\n{\n\t$('#takeOneAction').val('false');\n\tvar rEmail=0;var rTts=1;var rSms=1;var rTwitter=1;\n\t//checks of validations\n\tsmsCntVal(senderId);\n\tgeneralValidations(broadCast_name,broadCast_message);\n\tconsole.log(\"voice and email and sms twitter to all contacts\");\n\t//checks for validations\n\tvar res = calculateRecipients(rEmail,rTts,rSms,rTwitter);\n\tvar Valueofcheckboxtwtvo=res[3];\n\tvar Valueofcheckboxmobvo=res[2];\n\tvar Valueofcheckboxmob=res[1];\n\trecipientVal(res[4]);\n\tbroadCast_message = broadCast_message.split('\"').join('');\n\tbroadCast_message = broadCast_message.split('\\n').join('');\n\tlCode=$('#ldId').val();\n\t//setting JSON\n\tdatasinfo = '{\"senderName\":\"'+senderId+'\",\"message\":\"'+broadCast_message+'\",\"broadcastName\":\"'+broadCast_name+'\",\"audio\": \"null\",'+Valueofcheckboxmob+','+Valueofcheckboxmobvo+','+Valueofcheckboxtwtvo+'},\"language\": \"'+lCode+'\"}';\n\tif(broadCast_name!=''&&broadCast_message!=''&&broadCast_message!=' '&&res[4]!=0&&senderId!='')\n\t\t{\n\t\t\tconsole.log('sending');\n\t\t\t$(\"#main\").css({\"opacity\": \"0.3\"});\n\t\t\tbroadcastFunc(datasinfo,x);\n\t\t\t$('#ldId').val(\"nl-nl\").attr(\"selected\", \"selected\");\n\t\t}\n}",
"function bEmailSmsTwitterAllCon(senderId,broadCast_sender_email,broadCast_name,broadCast_sender_name,broadCast_message,broadCast_email_subject,x)\n{\n\t$('#takeOneAction').val('false');\n\tvar rEmail=1;var rTts=0;var rSms=1;var rTwitter=1;\n\t//checks of validations\n\tsmsCntVal(senderId);\n\tgeneralValidations(broadCast_name,broadCast_message);\n\tvar isvalid = emailCntVal(broadCast_sender_email,broadCast_sender_name);\n\tconsole.log(\"voice and email and sms twitter to all contacts\");\n\t//checks for validations\n\tvar res = calculateRecipients(rEmail,rTts,rSms,rTwitter);\n\tvar Valueofcheckboxtwtvo=res[3];\n\tvar Valueofcheckboxmob=res[1];\n\tValueofcheckbox=res[0];\n\trecipientVal(res[4]);\n\tbroadCast_message = broadCast_message.split('\"').join('');\n\tbroadCast_message = broadCast_message.split('\\n').join('');\n\t//setting JSON\n\tdatasinfo = '{\"senderName\":\"'+senderId+'\",\"message\":\"'+broadCast_message+'\",\"emailSubject\":\"'+broadCast_email_subject+'\",\"broadcastName\":\"'+broadCast_name+'\",'+Valueofcheckbox+','+Valueofcheckboxmob+','+Valueofcheckboxtwtvo+'}}';\n\tif(broadCast_name!=''&&broadCast_message!=''&&broadCast_message!=' '&&broadCast_sender_name!=''&&broadCast_sender_email!=''&&res[4]!=0&&isvalid&&senderId!='')\n\t\t{\n\t\t\tconsole.log('sending');\n\t\t\t$(\"#main\").css({\"opacity\": \"0.3\"});\n\t\t\tbroadcastFunc(datasinfo,x);\n\t\t}\n}",
"function showSendMail(selected) {\n\tif (selected.indexOf(\"YES\") > -1) {\n\t\tdocument.getElementById(\"sendMailButton\").disabled = false;\n\t} else {\n\t\tdocument.getElementById(\"sendMailButton\").disabled = true;\n\t}\n}",
"function addOutboxSMS(date,number,message,sourceAddress)\n{\n if(document.getElementById(number))\n {\n $('#outbox_'+number).dataTable().fnAddData( [\n date,\n sourceAddress,\n escapeHTML(message)\n ] );\n }\n}",
"function transfert_message_service(){\n\tvar texte = document.getElementById(\"message\").value;\n\tdocument.getElementById(\"text_service\").value = texte;\n}",
"function modalBox(msg) {\n\t\tvar boxCSS = \"position:absolute;width:300px;height:150px;padding:10px;background-color:#000000;color:#ffffff;z-index:30;font-family:'Arial';font-size:12px;display:none;\";\n\t\t$(\"#aspnetForm\").parent().append(\"<div id='SPServices_msgBox' style=\" + boxCSS + \">\" + msg);\n\t\tvar height = $(\"#SPServices_msgBox\").height();\n\t\tvar width = $(\"#SPServices_msgBox\").width();\n\t\tvar leftVal = ($(window).width() / 2) - (width / 2) + \"px\";\n\t\tvar topVal = ($(window).height() / 2) - (height / 2) - 100 + \"px\";\n\t\t$(\"#SPServices_msgBox\").css({border:'5px #C02000 solid', left:leftVal, top:topVal}).show().fadeTo(\"slow\", 0.75).click(function () {\n\t\t\t$(this).fadeOut(\"3000\", function () {\n\t\t\t\t$(this).remove();\n\t\t\t});\n\t\t});\n\t} // End of function modalBox",
"function showSaveMessage() {\n $(\"#saveMessage\").show();\n setTimeout(function () {\n $(\"#saveMessage\").hide();\n }, 2000);\n}",
"function onTradeOfferSent (tradeofferid)\n{\n TradeOfferID = tradeofferid;\n\n showModal();\n checkTradeOffer();\n}",
"function showDialog(){\n debug('Action');\n\n master.show(new Array({name: \"Child\", data:childrenList},\n {name: \"Action\", data:actions},\n {name: 'Shape', data:iceCreamShapes},\n {name: 'Taste', data:iceCreamTastes})\n , onComplete);\n\n document.getElementById('content').style.display = 'none';\n master._container.style.display = 'block';\n}",
"function displayGetFreeRequests(callbackWhenLoaded){\n referralLink = \"https://www.synchronise.io/?referral=\"+Synchronise.User.current().id;\n var modal = new Modal();\n modal.title(\"Free requests\");\n var string = \"<div class='col-lg-6'><legend>Invite your friends <img src='/images/emojiFriend.png' style='height: 20px;'/></legend><h4 style='text-align:center'>10,000 requests</h4>Get <b>10,000</b> requests everytime a friends signup. There is no limit on the amount of friend you can invite.<div style='text-align:center; margin-top: 10px'><a class='btn btn-block btn-social shareOnMessenger' style='background: white; box-shadow: none; border: 1px solid darkgray'><span class='fa'><img src='/images/messenger.png' style='width: 30px; height: 30px'/></span> Send via Messenger</a><a href='https://twitter.com/intent/tweet?text=Stop reinventing the wheel! Reusable cloud components are there.&url=\" + referralLink + \"&hashtags=cloud,app&via=synchroniseio' class='btn btn-block btn-social btn-twitter' style='border: 0px; box-shadow: none;'><span class='fa fa-twitter'></span> Post a Tweet</a><input type='text' class='form-control' value='\" + referralLink + \"'></div></div>\";\n string+= \"<div class='col-lg-6'><legend>Add a payment method <img src='/images/emojiPaymentMethod.png' style='width: 25px'/></legend><h4 style='text-align:center'>20,000 requests</h4>Add a payment method and we'll give you an extra <b>20,000</b> requests and you <b>won't</b> be charged, ever, until you decide to switch to a payed plan. <br/><br/>Why? When you save a payment method you give us a strong sign that you believe in our platform and that means a lot to us. This is our way of saying thank you for your support. <div style='text-align:center; margin-top: 10px'><a class='btn btn-primary' href='/billing?tab=paymentMethods'>Add payment method</a></div></div>\";\n\n modal.content(string);\n modal.show();\n callbackWhenLoaded();\n }",
"function open_export_dialog(event) {\n var id = this.dom.table.id + \"-export-dialog\";\n var modal = $(\"#\" + id);\n var amount = $(\".active\", this.dom.table).length;\n\n if (amount === 0) {\n // No rows selected: we're exporting all items.\n amount = $(this.dom.table).DataTable().page.info().recordsTotal;\n }\n\n $(\"[name=page_size]\", modal).attr(\"max\", amount).val(amount);\n $(\".num_items\", modal).text(amount);\n\n var data = {\n format: $(\"[name=format]\", modal),\n page_size: $(\"[name=page_size]\", modal),\n filename: $(\"[name=filename]\", modal),\n task: false,\n modal: modal,\n table: $(this.dom.table)\n };\n\n $(\"[name=export]\", modal).unbind().click(export_clicked.bind(data));\n $(\"select\", modal).unbind().change(function () {\n if (this.options[this.selectedIndex].value === \"spss\") {\n $(\".spss-warning\").removeClass(\"hide\");\n } else {\n $(\".spss-warning\").addClass(\"hide\");\n }\n });\n\n modal.modal();\n }",
"function shareScreen() {\n console.log(\"SHARING SCREEN \" + isSharingScreen);\n document.getElementById(\"share\").disabled = true;\n document.getElementById(\"unshare\").disabled = false;\n document.getElementById(\"share\").style.display = \"none\";\n document.getElementById(\"unshare\").style.display = \"block\";\n leaveChannel();\n setTimeout(function() { \n joinChannel(channel_name, true); \n }, 1000);\n}",
"function showok(message){\n\t$.messager.show({\n\t\ttitle:'消息',\n\t\tmsg:message == null ? '操作成功!' : message,\n\t\tshowType:'show',\n\t\ttimeout:3000,\n\t\tstyle:{\n\t\t\tright:'',\n\t\t\ttop:document.body.scrollTop + document.documentElement.scrollTop,\n\t\t\tbottom:''\n\t\t}\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select previous panel, when in singlepanel mode. | selectPrevious () {
if (this._isNavigable) {
this.currentPanel -= 1;
}
} | [
"selectPrevious () {\n // if current tab is the first tab\n if (this.currentTab === 0) {\n // select last\n this.currentTab = (this.tabs.length - 1);\n } else {\n // select previous\n this.currentTab -= 1;\n }\n this.tabs[this.currentTab].focus();\n }",
"goToPreviousSlide() {\n this._goToSlide(this.previousSlideIndex, false, false);\n }",
"selectPrevious() {\n\n // select the previous, or if it is the first entry select the last again\n if (this.selected <= 0) {\n this.selected = this.sequence.length -1;\n }\n else {\n this.selected--;\n }\n\n // highlight the selected entry\n this.highlightSelected();\n\n }",
"function showPreviousPreview()\r\n {\r\n if ($label == null)\r\n return;\r\n\r\n log(\"Preview.showPreviousPreview()\");\r\n\r\n // get current label\r\n var prevIndex = $previews.index($label) - 1;\r\n if (prevIndex >= 0)\r\n showPreview(prevIndex);\r\n }",
"function previousSlide(step) {\n pos = Math.max(pos - step, -(slideCount - 1));\n setTransform();\n }",
"function prev() {\n const prev = position === 0 ? gallery.length - 1 : position - 1;\n setPosition(prev);\n }",
"_focusPreviousTab () {\n this.tabs[this.previousTabIndex]\n ? this.tabs[this.previousTabIndex].focus()\n : this.tabs[this.tabs.length - 1].focus()\n }",
"prev() {\n\t\tconst prev = this.disabled.previousElementSibling || this.nav.lastElementChild;\n\t\tthis.current = this.navButtons.indexOf(prev);\n\t}",
"prev() {\n\t\t\tif (this.currPage > 1) {\n\t\t\t\tthis.currPage--;\n\t\t\t\tthis._loadPage();\n\t\t\t}\n\t\t}",
"function previousClicked() {\n if (currentFeed && currentItemIndex > 0) {\n currentItemIndex--;\n displayCurrentItem();\n }\n }",
"function onPrevButtonClick() {\n\t\tgotoPrevSlide()\n\t}",
"function setPrevItemActive() {\n var items = getItems();\n\n var activeItem = document.getElementsByClassName(\"active\")[0];\n var prevElement = activeItem.previousElementSibling;\n\n if (!prevElement) {\n prevElement = items[items.length - 1];\n }\n\n changeActiveState(activeItem, prevElement);\n}",
"function previousQuestion(QuestionID){\n\n\t\tif (!inaction) {\n var currentID = QuestionID.substring(1);\n var nextID = currentID--;\n nextID--;\n\n //Check if next question is answered\n // if ($('#q' + currentID).find('input').hasClass('checked')) {\n // activateNextButton();\n // }else {\n // deactivateNextButton();\n // }\n\n if (nextID <= 1) {\n \tdeactivatePreviousButton();\n } \n \n slideFeature('#' + QuestionID, '#q' + nextID, 500); \n }\n\t}",
"function runPrevKeyDownEvent() {\n /*\n Check to see if the current playlist has been set\n or null and set the previous song.\n */\n if (config.active_playlist == \"\" || config.active_playlist == null) {\n AudioNavigation.setPrevious();\n } else {\n AudioNavigation.setPreviousPlaylist(config.active_playlist);\n }\n }",
"skipPrevious() {\n const { selectedSongIdx } = this.state\n const songIdx = selectedSongIdx < 1 ? (this.countTracks() - 1)\n : selectedSongIdx -1\n\n this.selectSong(songIdx)\n this.play(songIdx)\n }",
"function goToPreviousImage() {\n clearInterval(automaticSlideInstance);\n var oldIndex = currentIndex;\n var oldDot = carouselNavigationContainer[oldIndex];\n\n currentIndex = currentIndex === 0 ? numberOfImages - 1 : currentIndex - 1;\n var currentDot = carouselNavigationContainer[currentIndex];\n\n changeNavigationDot(oldDot, currentDot);\n animateSlide(oldIndex, currentIndex);\n\n setTimeout(automaticSlide, 0);\n}",
"slideBack() {\n this.slideBy(-this.getSingleStep());\n }",
"function privatePrevious() {\n\t \timageCurrent--;\n\t \tif (imageCurrent < 0) {\n\t \t\timageCurrent = image.length - 1;\n\t \t\tcontainer.animate({left: \"-=\" + (sliceWidth * image.length - sliceWidth)}, speedSlice);\n\t \t} else {\n\t \t\tcontainer.animate({left: \"+=\" + sliceWidth}, speedSlice);\n\t \t}\n\t }",
"function setPreviousCanvas(windowId) {\n return function (dispatch, getState) {\n var state = getState();\n var newGroup = (0, _selectors.getPreviousCanvasGrouping)(state, {\n windowId: windowId\n });\n var ids = (newGroup || []).map(function (c) {\n return c.id;\n });\n newGroup && dispatch(setCanvas(windowId, ids[0], ids));\n };\n}",
"function previous(previous_view_id, current_view_id) {\n //Hiding the current view\n $(current_view_id).hide();\n //Making the previous view appear with a animation\n $(previous_view_id).slideUpShow();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a field from the collection by title | getByTitle(title) {
return Field(this, `getByTitle('${title}')`);
} | [
"function findFormByTitle(title){\n for (var i in forms) {\n if (forms[i].title === title) {\n return forms[i];\n }\n }\n return null;\n }",
"getByTitle(title) {\n return View(this, `getByTitle('${encodePath(title)}')`);\n }",
"getByTitle(title) {\n return List(this, `getByTitle('${encodePath(title)}')`);\n }",
"function findLayerByTitle(title) {\n return view.map.allLayers.find(function (layer) {\n return layer.title === title;\n });\n }",
"getRelatedField(fieldId) {\n const fields = this.getTableFields(this.props);\n const field = _.find(fields, fld => fld.id === fieldId);\n return field || null;\n }",
"function extract(item, field) {\n if (item[field]) {\n return item[field];\n } else if (typeof item == \"string\" || typeof item == \"number\") {\n return item;\n }\n // intentionally don't return anything\n }",
"loadPostTitle(id) {\n let title = '';\n\n for(let item of this.state.list) {\n if(item.id === id) {\n return item.title;\n }\n }\n\n return title;\n }",
"function getResource(title) {\n\t\t\tvar resource = resources.filter(function(resource) {\n\t\t\t\treturn resource.title === title;\n\t\t\t});\n\n\t\t\treturn $q.when(resource[0]);\n\t\t}",
"get titles() {\n return issues.map(obj => obj.title);\n }",
"async function getId(title) {\n const result = await\n db.query(\"SELECT id FROM jobs WHERE title = $1\", [title]);\n return result.rows[0].id;\n}",
"function findDefaultField() {\n if (0 == fields.length) {\n return null;\n }\n \n var field = _.find(fields, { 'id': true });\n if (field == null) {\n field = fields[0];\n }\n\n return field;\n }",
"get fieldValue(){}",
"get title()\n\t{\n\t\t//dump(\"get title: title:\"+this._calEvent.title);\n\t\tif (this._newTitle) {\n\t\t\treturn this._newTitle;\n\t\t}\n\n\t\tif (this._title) {\n\t\t\treturn this._title;\n\t\t}\n\n\t\treturn this._calEvent.title;\n\t}",
"function findById(id) {\n return _.find(fields, { '_id': id });\n }",
"async getTitle() {\n const titleEl = await this._title();\n return titleEl ? titleEl.text() : null;\n }",
"static getFieldInfoByName(field_name){\n\t}",
"function getTitleInfo(){\r\n var titleStr='';\r\n for (var i=0; i<obj['subfield'].length; i++){\r\n if (obj['subfield'][i][parserPrefix]['code']=='a') {\r\n titleStr = obj['subfield'][i]['_'];\r\n var exp = new RegExp(/ :$/); // if there is a colon, move to a logical place: no space\r\n titleStr = titleStr.replace(exp,': ');\r\n }\r\n else if (obj['subfield'][i][parserPrefix]['code']=='b') {\r\n titleStr += obj['subfield'][i]['_'];\r\n }\r\n }\r\n \r\n exp = new RegExp(/ \\/$/); // strip trailing ' /' from title\r\n titleStr = titleStr.replace(exp,'');\r\n book['title']=titleStr;\r\n if (debug) console.log(util.inspect(book, showHidden=true, depth=6, colorize=true));\r\n}",
"get fields() {\n return tag.configure(SharePointQueryableCollection(this, \"fields\"), \"ct.fields\");\n }",
"async function getTodoByName() {\n const answer = await inquirer.prompt([\n {name: 'title', message: 'Enter a title: '},\n ]);\n const searchTerm = answer.title;\n // fetch list and search by title\n try {\n const { data: { listTodos : { items } } } = await API.graphql(graphqlOperation(listTodos, {filter: {name: {eq: searchTerm}}}));\n const result = items[0];\n\n if (!result) {\n console.warn(`No Todo named ${searchTerm}`);\n }\n return result;\n } catch (err) {\n console.log(\"filter operation failed\", err);\n }\n return null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the "kind" of value. (e.g. "String", "Number", etc) | function kindOf(val) {
return Object.prototype.toString.call(val).slice(8, -1);
} | [
"function classify(value) {\n if (value == null) {\n return null;\n }\n else if (value instanceof HTMLElement) {\n return 'primitive';\n }\n else if (value instanceof Array) {\n return 'array';\n }\n else if (value instanceof Date) {\n return 'primitive';\n }\n else if (typeof value === 'object' && value.constructor === Object) {\n return 'object';\n }\n else if (typeof value === 'function') {\n return 'function';\n }\n else if (typeof value === 'object' && value.constructor != null) {\n return 'class-instance';\n }\n return 'primitive';\n}",
"valueMatchesType(value) {\n return typeof value === this.valueType\n }",
"function getPostfixForTypeWarning(value) {\n var type = getPreciseType(value);\n switch (type) {\n case \"array\":\n case \"object\":\n return \"an \" + type;\n\n case \"boolean\":\n case \"date\":\n case \"regexp\":\n return \"a \" + type;\n\n default:\n return type;\n }\n }",
"function guessTypeOfValue(tval) {\n if (tval['ctype'] === 'boolean') {\n return type.bool;\n } else if (tval['ctype'] === 'number') {\n let z = tval['value'];\n if (Math.abs(z['imag']) < 1e-5) { //eps test. for some reasons sin(1) might have some imag part of order e-17\n if ((z['real'] | 0) === z['real']) {\n return type.int;\n } else {\n return type.float;\n }\n } else {\n return type.complex;\n }\n } else if (tval['ctype'] === 'list') {\n let l = tval['value'];\n if (l.length === 3) {\n if (tval[\"usage\"] === \"Point\")\n return type.point;\n else if (tval[\"usage\"] === \"Line\")\n return type.line\n }\n if (l.length > 0) {\n let ctype = guessTypeOfValue(l[0]);\n for (let i = 1; i < l.length; i++) {\n ctype = lca(ctype, guessTypeOfValue(l[i]));\n }\n if (ctype) return {\n type: 'list',\n length: l.length,\n parameters: ctype\n };\n }\n } else if (tval['ctype'] === 'string' || tval['ctype'] === 'image') {\n return type.image;\n } else if (tval['ctype'] === 'geo' && tval['value']['kind'] === 'L') {\n return type.line;\n }\n console.error(`Cannot guess type of the following type:`);\n console.log(tval);\n return false;\n}",
"static getType(val) {\n\n if (val instanceof Node) {\n return \"NODE\";\n }\n\n if (typeof(val) === \"string\") {\n return \"STRING\";\n }\n\n if (val instanceof _Node_main_js__WEBPACK_IMPORTED_MODULE_2__.default) {\n return \"YNGWIE\";\n }\n\n return undefined;\n\n }",
"function typeOfFunction(value) {\r\n const x = (typeof value);\r\n \r\n return \"The value of \" + value + \" is a type of : \" + x;\r\n}",
"typeSpec() {\n const token = this.currentToken;\n if (this.currentToken.type === tokens.INTEGER) {\n this.eat(tokens.INTEGER);\n } else if (this.currentToken.type === tokens.REAL) {\n this.eat(tokens.REAL);\n }\n return new Type(token);\n }",
"function chewValue(optionalName, valueThing, ctx) {\n var kind = null;\n\n switch (typeof(valueThing)) {\n case \"string\":\n kind = \"String\";\n break;\n case \"boolean\":\n kind = \"Boolean\";\n break;\n case \"number\":\n kind = \"Number\";\n break;\n case \"object\":\n if (valueThing instanceof Identifier) {\n switch (valueThing.identifier) {\n case \"true\":\n kind = \"Boolean\";\n valueThing = true;\n break;\n case \"false\":\n kind = \"Boolean\";\n valueThing = false;\n break;\n // otherwise it probably is a type reference/global that needs\n // resolution.\n }\n }\n }\n if (kind) {\n return new $typerep.NamedValue(optionalName, valueThing, kind,\n new $typerep.LifeStory());\n }\n // just use chewType for everything else.\n return chewType(optionalName, valueThing, ctx);\n}",
"function arrayOrObject(value) {\n if(Array.isArray(value)) return \"array\";\n return \"object\";\n}",
"get dtype() {\n return this.dtypes[0];\n }",
"getType () {\n\t\tlet type = this.definition.type;\n\n\t\t// if it's not a relationship or fetched property, it's an attribute\n\t\t// NOTE: Probably need to separate this out into different classes\n\t\ttype !== 'relationship' && type !== 'fetched' && (type = 'attribute');\n\n\t\treturn type;\n\t}",
"getType() {\n return this.type\n }",
"static getKindSingular(kind) {\n if (kind in GroupPlugin_1.SINGULARS) {\n return GroupPlugin_1.SINGULARS[kind];\n }\n else {\n return GroupPlugin_1.getKindString(kind);\n }\n }",
"encodeType(name) {\n const result = this.#fullTypes.get(name);\n (0, index_js_4.assertArgument)(result, `unknown type: ${JSON.stringify(name)}`, \"name\", name);\n return result;\n }",
"function ISTEXT(value) {\n return 'string' === typeof value;\n}",
"function getHumanValueFromPage(fName, dataType) {\n switch (dataType) {\n case 'radio': return radioRef(fName).value;\n case 'color': return el(fName).value.toLowerCase();\n // translate true/false BACK to Y/N in this case:\n case 'yn': return el(fName)?.checked ? 'Y' : 'N';\n case 'list':\n case 'text':\n return el(fName).value;\n // All remaining types are numeric:\n default: return Number(el(fName).value);\n }\n}",
"get rdfaDatatype() {\n if (this.args.datatype) {\n return this.args.datatype;\n }\n\n return this.normalizedRdfaBindings[this.args.prop]?.datatype;\n }",
"function $type(obj){\n\tif (!obj) return false;\n\tvar type = false;\n\tif (obj instanceof Function) type = 'function';\n\telse if (obj.nodeName){\n\t\tif (obj.nodeType == 3 && !/\\S/.test(obj.nodeValue)) type = 'textnode';\n\t\telse if (obj.nodeType == 1) type = 'element';\n\t}\n\telse if (obj instanceof Array) type = 'array';\n\telse if (typeof obj == 'object') type = 'object';\n\telse if (typeof obj == 'string') type = 'string';\n\telse if (typeof obj == 'number' && isFinite(obj)) type = 'number';\n\treturn type;\n}",
"function $value(value) {\n\t\t\t\t/*jshint validthis: true */\n\t\t\t\treturn isDefined(value) ? this.type.decode(value) : $UrlMatcherFactory.$$getDefaultValue(this);\n\t\t\t}",
"function resolveKind(id) {\n \t\t\t\t var k=resolveKindFromSymbolTable(id);\n \t\t\t\t\t\tif (!k) {\n \t\t\t\t\t\t\tif (resolveTypeFromSchemaForClass(id)) {\n \t\t\t\t\t\t\t k=\"CLASS_NAME\";\n \t\t\t\t\t\t } else if (resolveTypeFromSchemaForAttributeAndLink(id)) {\n \t\t\t\t\t\t\t\t k=\"PROPERTY_NAME\";\n \t\t\t\t\t\t\t}\n \t\t\t\t\t }\n \t\t\t\treturn k;\n \t\t }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
slider disabled v2 Extends mxShape. | function mxShapeGmdlSliderDisabled2(bounds, fill, stroke, strokewidth)
{
mxShape.call(this);
this.bounds = bounds;
this.fill = fill;
this.stroke = stroke;
this.strokewidth = (strokewidth != null) ? strokewidth : 1;
} | [
"function disableSizeSlider(){\r\n document.querySelector(\"#arr_sz\").disabled = true;\r\n}",
"disable() {\r\n this.enableMove(false);\r\n this.enableResize(false);\r\n this._triggerEvent('disable');\r\n return this;\r\n }",
"function disableHighLow( id ) {\n $(id).find(\".highlow\").each( function() { \n $(this).data(\"frozen\", \"true\");\n //$(this).slider(\"disable\");\n });\n}",
"function disableML( id ) {\n $(id).find(\".ml\").each( function() {\n $(this).slider( \"disable\" );\n $(this).addClass(\" vis-hide\");\n });\n}",
"drawSlider() {\n let c = color(255, 255, 255);\n fill(c);\n noStroke();\n rect(this.x, this.y + this.topPadding + this.lateralPadding, this.width, this.height, 1, 1, 1, 1);\n }",
"disable() {\n this.clearSelection();\n this._removeMouseDownListeners();\n this._enabled = false;\n }",
"function disableSlideDropPredicate(item) {\n return !item.data.isSlide;\n}",
"function disable_draw() {\n drawing_tools.setShape(null);\n}",
"function sliderDefaults() {\n $(\".product-slider\").each( function(index, value) {\n $(this).children().children(\".slide-wrapper\").children().children().first().addClass(\"active\");\n $(this).children().children(\".lead\").children().children(\".left\").addClass(\"disabled\");\n $(this).children().children(\".slide-wrapper\").attr(\"data-shift-amount\", \"0\");\n\n var slideNumber = $(this).children().children(\".slide-wrapper\").children().children(\".slide\").length;\n\n if(slideNumber <= 1){\n $(this).children().children(\".lead\").children(\".controls\").hide();\n }\n });\n }",
"sliderBounce() {\n this.directionX = -this.directionX;\n }",
"onDisabled() {\n this.updateInvalid();\n }",
"set disabled(value) {\n const isDisabled = Boolean(value);\n if (this._disabled == isDisabled)\n return;\n this._disabled = isDisabled;\n this._safelySetAttribute('disabled', isDisabled);\n this.setAttribute('aria-disabled', isDisabled);\n // The `tabindex` attribute does not provide a way to fully remove\n // focusability from an element.\n // Elements with `tabindex=-1` can still be focused with\n // a mouse or by calling `focus()`.\n // To make sure an element is disabled and not focusable, remove the\n // `tabindex` attribute.\n if (isDisabled) {\n this.removeAttribute('tabindex');\n // If the focus is currently on this element, unfocus it by\n // calling the `HTMLElement.blur()` method.\n if (document.activeElement === this)\n this.blur();\n } else {\n this.setAttribute('tabindex', '0');\n }\n }",
"updateHandleVisibility() {\n if (!this.slider.target) {\n return;\n }\n\n const handle = this.slider.target.getElementsByClassName('noUi-origin');\n\n if (this.state.current >= this.state.start && this.state.current <= this.state.end) {\n handle[0].classList.remove('is-off-timeline');\n this.slider.set(this.state.current);\n } else {\n handle[0].classList.add('is-off-timeline');\n }\n }",
"function disableme() {\n\tvar itms = getDisabledItems();\n\tfor(i=0; i< itms.length; i++) \n\t{\n\t\titms[i].readOnly = true;\n }\n}",
"function Collider() {}",
"function disableFieldDropPredicate(item) {\n if (!item.data.isSlide) {\n return false;\n }\n return true;\n}",
"disable_style() {\n this.enabledStyles.pop();\n }",
"stop() {\n this.song_.stop();\n this.bitDepthSlider_.disable();\n this.reductionSlider_.disable();\n }",
"function mouseDragged(){\n if(dist(mouseX,mouseY,ball.x,ball.y) <= 1.5*ball.r){\n\tball.drag();\n }\n//use the slider control\n if(dist(mouseX,mouseY,slider.x,slider.y) <= 30){\n \tslider.drag();\n slider.control();\n }\n}",
"testFocusNotOnSliderAfterClickIfFocusElementOnSliderDragFalse() {\n oneThumbSlider.setFocusElementOnSliderDrag(false);\n const sliderElement = oneThumbSlider.getElement();\n const coords = style.getClientPosition(sliderElement);\n testingEvents.fireClickSequence(\n sliderElement, /* opt_button */ undefined, coords);\n\n const activeElement = oneThumbSlider.getDomHelper().getActiveElement();\n assertNotEquals(sliderElement, activeElement);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Putting x's from the interval in the array Computing y's with this formula: k1 = f(x[i1], y[i1]) k2 = f(x[i1] + h/2, y[i1] + hk1/2) k3 = f(x[i1] + h/2, y[i1] + hk2/2) k4 = f(x[i1], y[i1] + hk3) y[i] = y[i1] + h/6(k1+2k2+2k3+k4) | function RungeKutta() {
xRungeKutta.length = 0;
yRungeKutta.length = 0;
yRungeKuttaErrorGlobal.length = 0;
yRungeKutta.push(+y0);
for (let i = x0; i <= X; i+=h) {
xRungeKutta.push(+i);
}
for (let i = 1; i < xRungeKutta.length; i++) {
var k1 = equation(+xImprovedEuler[i-1], +yImprovedEuler[i-1]);
var k2 = equation(+xImprovedEuler[i-1] + h/2, +yImprovedEuler[i-1] + h*k1/2);
var k3 = equation(+xImprovedEuler[i-1] + h/2, +yImprovedEuler[i-1] + h*k2/2);
var k4 = equation(+xImprovedEuler[i-1] + h, +yImprovedEuler[i-1] + h*k3);
yRungeKutta.push(+yImprovedEuler[i-1] + (h/6)*(k1+2*k2+2*k3+k4));
}
for (let i = 0; i < xRungeKutta.length; i++) {
yRungeKuttaErrorGlobal.push(+yExact[i] - yRungeKutta[i]);
yRungeKuttaErrorGlobal2.push(Math.abs(+yExact[i] - yRungeKutta[i]));
//yRungeKuttaErrorLocal.push(partialExactSolution(xExact[i+1]) - partialExactSolution(xExact[i]) - (h/6)*(k1+2*k2+2*k3+k4));
}
} | [
"function computeEachPoint(min, max, fx)\n{\n let xData = [];\n let yData = [];\n const step = 0.1;\n\n for(let i = min;i <= max; i += step)\n {\n xData.push(i);\n let y = fx(i);\n yData.push(y);\n }\n\n return [xData, yData];\n}",
"function val2between({\n xy, //function y(x) set as pairs in array [e1,e2]\n x, //\"anchor\" value of x,\n //By default y=e1, x=e2,\n inv, //inverse pairs, means x=e2, y=e1,\n }){\n var xy = xy;\n var alen = xy.length;\n var alen1 = xy.length-1;\n var indMax = alen - 1;\n var indMin = 0;\n\n var frDim = inv ? 1 : 0;\n var depDim = frDim ? 0 : 1;\n\n var xMax = xy[ alen-1 ][frDim];\n var xMin = xy[ 0 ][frDim];\n //virtual direction\n var xDir = xMax - xMin > 0;\n\n if( xDir === 0 ) {\n return { x, y : xy[0][depDim], indMin : 0, indMax : 0, xMin, xMax, };\n }\n var xDir = xDir > 0 ? 1 : -1;\n\n if( ( xMax - x ) * xDir < 0 ) {\n return { x, y : xy[alen1][depDim], indMin : alen1, indMax : alen1, xMin, xMax, };\n }\n if( ( xMin - x ) * xDir > 0 ) {\n return { x, y : xy[0][depDim], indMin : 0, indMax : 0, xMin, xMax, };\n }\n\n var count = 0; //todom remove this protector\n while( indMax-indMin > 1 ) {\n\n /*\n //*********************************************\n // //\\\\ interpolating algo\n //=============================================\n //this is an alternative to binary division algo,\n //for y = x^5, this ago takes 230 steps vs binary which has only 14\n var frMa = xy[ indMax ][1];\n var frMi = xy[ indMin ][1];\n var scaleY = ( frMa - frMi ) / ( indMax - indMin );\n var indMiddle = scaleY === 0 ? indMin : ( y - frMi ) / scaleY + indMin;\n var { indMin, indMax } = findsContaningInterval(\n indMiddle, indMin, indMax, xy );\n if( count++ > 300 ) {\n throw new Error( 'divergent algo' );\n }\n //=============================================\n // \\\\// interpolating algo\n //*********************************************\n */\n\n //*********************************************\n // //\\\\ binary division algo\n //=============================================\n //this is an alternative to interpolating algo\n var binaryMiddle = ( indMax + indMin ) / 2;\n var { indMin, indMax } = findsContaningInterval(\n binaryMiddle, indMin, indMax, xy, frDim );\n if( count++ > 200 ) {\n throw new Error( 'divergent algo?' );\n }\n //=============================================\n // //\\\\ binary division algo\n //*********************************************\n\n //ccc( { indMin, indMax, count } );\n }\n\n //final result:\n var frMa = xy[ indMax ][frDim];\n var frMi = xy[ indMin ][frDim];\n if( indMax === indMin || Math.abs( scaleY ) < 1e-100 ) {\n var y = xy[ indMin ][depDim];\n var indMiddle = indMin;\n } else {\n var scaleY = ( frMa - frMi ) / ( indMax - indMin );\n if( Math.abs( scaleY ) < 1e-100 ) {\n var y = xy[ indMin ][depDim];\n var indMiddle = indMin;\n } else {\n var yMa = xy[ indMax ][depDim];\n var yMi = xy[ indMin ][depDim];\n var scaleX = ( yMa - yMi ) / ( indMax - indMin );\n var y = scaleX * ( x - frMi ) / scaleY + yMi;\n var indMiddle = ( indMax - indMin ) * ( x - frMi ) / scaleY + indMin;\n }\n }\n return { x, y, indMin, indMax, xMin, xMax, indMiddle, count };\n\n\n\n\n function findsContaningInterval(\n indMiddle, //proposed new position of interval boundary\n indMin, //current\n indMax, //current\n xy, //main array\n frDim,\n ){\n var newMin = Math.floor( indMiddle );\n var newMax = Math.ceil( indMiddle );\n if( ( x - xy[ newMin ][frDim] ) * xDir < 0 ) {\n ////new Min is above x, take it as max\n indMax = newMin;\n } else if( ( x - xy[ newMax ][frDim] ) * xDir > 0 ) {\n ////new Max is below x, take it as min\n indMin = newMax;\n } else {\n ////x is in between grid cell, it can be newMin === newMax,\n indMin = newMin;\n indMax = newMax;\n }\n return { indMin, indMax };\n }\n\n }",
"function derive(){ // Fills Arrays of 1sd Derivative Coordinates\n\tvar m = 0; // Slope!\n\t\n\t//console.clear(); // For Debug.\n\t//console.log(\"Derivative Points:\"); // For Debug.\n\t// Find the Slope at Every Point of the Function\n\tfor(i=0;i<xPoints.length;i++) {\n\t\tm =(yPoints[i+1]-yPoints[i])/(xPoints[i+1]-xPoints[i]); // Calculate Slope\n\t\t//console.log(\"M: \"+m); // Debug\n\t\t/* if(xPoints[i]>0.5&&xPoints[i]<1)\n\t\t\tconsole.log(xPoints[i]+\", \"+m.toFixed(4)); */\n\n\t\tif(!isNaN(m)&&m!=Infinity&&!(Math.abs(m)>hLines/2*gScale)&&i>0){\n\t\t\t\t\n\t\t\t\n\t\t\tderX[i]=xPoints[i].toFixed(4);\n\t\t\tderY[i]=m.toFixed(4);\n\t\t\tif(functionInput.value.includes(\"abs\")&&derY[i]>0&&derY[i-1]<0||derY[i]<0&&derY[i-1]>0||derY[i]>0&&derY[i-1]==0||derY[i]<0&&derY[i-1]==0){\n\t\t\t\tderY[i]=NaN;\n\t\t\t}\n\t\t\t//if(derX[i]>-0.5&&derX[i]<0.5)\n\t\t\t\t//console.log(derX[i],derY[i]); // Debug\n\t\t}\n\t}\n}",
"function initPointsBySection(xlower, xhigher, ylower, yhigher, widthPoints, heightPoints, split, splitindex) {\n let w = xhigher - xlower;\n let h = yhigher - ylower;\n let winterval = w / widthPoints;\n let hinterval = h / heightPoints;\n\n let pointArray = [];\n\n //split is the number of sections to divide the picture into.\n // splitindex [0..n] is the section number we are calculating\n // only create pointArray for the section we are looking at\n // need t figure out ycount, yhigher and where to stop\n var sectionSize = Math.floor(heightPoints / split);\n //log('split ',heightPoints,' into ',split,' of ',sectionSize,' with ',sectionSize*widthPoints);\n var ycount = splitindex * sectionSize;\n // need to take into account that sectionSize may be rounded down, so last section needs\n // to mop up the last remaining rows\n var yupper;\n if (split - 1 == splitindex) {\n // we are processing the last section\n yupper = heightPoints;\n } else {\n yupper = ycount + sectionSize;\n }\n\n var j = yhigher - ycount * hinterval;\n\n for (; ycount < yupper; j -= hinterval, ycount++) {\n for (var i = xlower, xcount = 0; xcount < widthPoints; i += winterval, xcount++) {\n pointArray.push(new Point(i, j));\n }\n }\n return pointArray;\n}",
"function xmm( x , y )\n {\n\n let i = undefined ;\n let j = undefined ;\n let k = undefined ;\n let a = undefined ;\n let b = undefined ;\n let c = undefined ;\n let d = undefined ;\n\n let e = [ 1 , 2 , 2 , 1 , 2 , 0 , 0 , 2 , 0 , 1 , 1 , 0 ] ;\n\n for( j = 0; j < this.nc; ++j )\n\n for( i = k = 0 , a = 0 , b = 1 , c = 2 , d = 3; k < e.length; ++i , a += 4 , b += 4 , c += 4 , d += 4 , k += 4 )\n\n if( (this.idx( i , j ) < this.nv) && (x.idx( e[a] , j ) < x.nv) && (y.idx( e[b] , j ) < y.nv) && (x.idx( e[c] , j ) < x.nv) && (y.idx( e[d] , j ) < y.nv) )\n {\n\n console.log( i , j , e[a] , e[b] , e[c] , e[d] ) ;\n\n this.v[ this.idx( i , j ) ] = ( (x.v[ x.idx( e[a] , j ) ] * y.v[ y.idx( e[b] , j ) ]) - (x.v[ x.idx( e[c] , j ) ] * y.v[ y.idx( e[d] , j ) ]) );\n\n }\n\n return ;\n\n }",
"function interpolate(x, xl, xh, yl, yh) {\n var r = 0;\n if ( x >= xh ) {\n r = yh;\n } else if ( x <= xl ) {\n r = yl;\n } else if ( (xh - xl) < 1.0E-8 ) {\n r = yl+(yh-yl)*((x-xl)/1.0E-8);\n } else {\n r = yl+(yh-yl)*((x-xl)/(xh-xl));\n }\n return r;\n }",
"interpolateY(x) { // input x (real-number)\n var index = this.bisection(x);\n \n if(this.arySrcX[index] === x)\n return this.arySrcY[index];\n else\n return this.doCubicSpline(x, index);\n }",
"function getSurroundCells(y,x) {\n var arr1 = [[y-1,x-1],[y-1,x],[y-1,x+1],[y,x-1],[y,x+1],[y+1,x-1],[y+1,x],[y+1,x+1]];\n var arr2 = [];\n for (ai=0; ai<arr1.length; ai++) {\n if (arr1[ai][0]<height && arr1[ai][1]<width && 0<=arr1[ai][0] && 0<=arr1[ai][1]) {\n arr2.push(arr1[ai]);\n }\n }\n return arr2;\n}",
"function applyFunction(x1, x2, f){\n var data = [];\n for (var i = 0, x; i <= 100; ++i) {\n x = x1 + i * (x2 - x1) / 100;\n data.push([x, f(x)]);\n }\n\n return data;\n}",
"function arcIntersections(cx, cy, r, startAngle, endAngle, counterClockwise, x1, y1, x2, y2) {\n // Solving the quadratic equation:\n // 1. y = k * x + y0\n // 2. (x - cx)^2 + (y - cy)^2 = r^2\n var k = (y2 - y1) / (x2 - x1);\n var y0 = y1 - k * x1;\n var a = Math.pow(k, 2) + 1;\n var b = 2 * (k * (y0 - cy) - cx);\n var c = Math.pow(cx, 2) + Math.pow(y0 - cy, 2) - Math.pow(r, 2);\n var d = Math.pow(b, 2) - 4 * a * c;\n if (d < 0) {\n return [];\n }\n var i1x = (-b + Math.sqrt(d)) / 2 / a;\n var i2x = (-b - Math.sqrt(d)) / 2 / a;\n var intersections = [];\n [i1x, i2x].forEach(function (x) {\n var isXInsideLine = x >= Math.min(x1, x2) && x <= Math.max(x1, x2);\n if (!isXInsideLine) {\n return;\n }\n var y = k * x;\n var a1 = normalizeAngle360(counterClockwise ? endAngle : startAngle);\n var a2 = normalizeAngle360(counterClockwise ? startAngle : endAngle);\n var intersectionAngle = normalizeAngle360(Math.atan2(y, x));\n // Order angles clockwise after the start angle\n // (end angle if counter-clockwise)\n if (a2 <= a1) {\n a2 += 2 * Math.PI;\n }\n if (intersectionAngle < a1) {\n intersectionAngle += 2 * Math.PI;\n }\n if (intersectionAngle >= a1 && intersectionAngle <= a2) {\n intersections.push({ x: x, y: y });\n }\n });\n return intersections;\n}",
"function solveEquation(params, x, y) {\n\n\n console.log(\"Solving equation\");\n //gets x values from global\n\n decaycurve = function(x, P) {\n\n return x.map(\n function(xi) {\n return getPareto(xi, P[0], P[1])\n }\n\n )\n };\n\n\n //Parms=fminsearch(fun,[100,30,10,5000],x,y);\n // Returns an array of coeffcients\n Parms = fminsearch(decaycurve, [.1, .1], x, y, {\n maxIter: 10000,\n display: true\n });\n\n\n //Math.round(original*100)/100 \n\n ra1 = Parms[0];\n ra2 = Parms[1];\n //rb1 = Parms[2];\n a1 = Math.round(Parms[0] * 1000) / 1000;\n a2 = Math.round(Parms[1] * 1000) / 1000;\n //b1 = Math.round(Parms[2]*1000)/1000;\n\n /*\n for (i = 0; i < x.length; i++) {\n roascurve.push(getPareto(x[i], Parms[0], Parms[1]));\n\n }\n*/\n return Parms; // Returns Array of Co-Efficients\n\n\n}",
"function sumaEliptica(x, y, a, b){\n\tvar resultado = [];\n\n\tif(x[0] == y[0] && x[1] == -y[1]){\n\t\treturn null;\n\t}\n\n\tif(x[0] == y[0] && x[1] == y[1]){\n\t\tvar lambda = (3*Math.pow(x[0],2)+a)/(2*y[0]);\n\t}else{\n\t\tvar lambda = (y[1]-y[0])/(x[1]-x[0]);\n\t}\n\n\tresultado[0] = Math.pow(lambda,2)-x[0]-y[0];\n\tresultado[1] = lambda*(x[0]-resultado[0])-x[1]\n\n\treturn resultado;\n}",
"bisection(ab) { // x-axis value\n var ju = this.numKnots-1;\t\t\t\t\t\t\t\t\t\t\t // upper limit\n var jl = 0;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // lower limit\n var jm;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // midpoint\n\n while (ju - jl > 1)\t\t\t\t\t\t\t\n {\n jm = Math.round((ju + jl)/2);\t\t\t\t\t\t\t\t\t// midpoint formula\n\n if (ab > this.arySrcX[jm])\n jl = jm;\n else\n ju = jm;\n }\n return jl;\t\t\n }",
"function cal_kb(xy_points){\n\t/*\n\t// formula for k and b\n\tk =( n(x1y1+x2y2+...+xnyn)-(x1+...+x2)(y1+...+yn) ) / ( n(x1^2+x2^2+...+xn^2) - (x1+...+x2)^2 )\n\tb = (y1+...+yn)/n - k*(x1+...+x2)/n\n\t*/\n\tvar n = xy_points.length;\n\tvar xy_sum = 0,x2_sum = 0,y2_sum = 0;\n\tvar x_sum = 0,y_sum = 0;\n\t\n\tfor(var i=0;i<n;i++){\n\t\txy_sum += xy_points[i].x * xy_points[i].y;\n\t\tx2_sum += xy_points[i].x * xy_points[i].x;\n\t\ty2_sum += xy_points[i].y * xy_points[i].y;\n\t\t\n\t\tx_sum += xy_points[i].x;\n\t\ty_sum += xy_points[i].y;\n\t}\n\t\n\tvar k = (n*xy_sum - x_sum*y_sum)/(n*x2_sum - x_sum*x_sum);\n\tvar b = y_sum/n - k* x_sum/n;\n\treturn {k:k,b:b};\n}",
"function merge(x, y, len_x) {\n // cnt is number of out of order triples\n // res is the new sorted array(each element is tri)\n // x and y are going to be combined\n // len_x is number of elements that have not been added to the new array\n // used_y is number of elements that have been added to the new array\n function helper(cnt, res, x, y, len_x, used_y) {\n if(is_empty_list(x) && is_empty_list(y)) {\n return pair(cnt, res);\n } else if(is_empty_list(x)) {\n const yy = head(y);\n const num_y = head(yy);\n const lf_y = head(tail(yy));\n const rt_y = tail(tail(yy));\n return helper(cnt, append(res, list(tri(num_y,\n lf_y,\n rt_y))), \n x, tail(y), len_x, used_y + 1);\n } else if(is_empty_list(y)) {\n const xx = head(x);\n const num_x = head(xx);\n const lf_x = head(tail(xx));\n const rt_x = tail(tail(xx));\n return helper(cnt + lf_x * used_y, \n append(res, list(tri(num_x, \n lf_x,\n rt_x + used_y))), \n tail(x), y, len_x - 1, used_y);\n } else {\n const xx = head(x);\n const yy = head(y);\n const num_x = head(xx);\n const num_y = head(yy);\n const lf_x = head(tail(xx));\n const rt_x = tail(tail(xx));\n const lf_y = head(tail(yy));\n const rt_y = tail(tail(yy));\n if(num_x <= num_y) {\n return helper(cnt + lf_x * used_y, \n append(res, list(tri(num_x, \n lf_x,\n rt_x + used_y))), \n tail(x), y, len_x - 1, used_y);\n } else {\n return helper(cnt + len_x * rt_y,\n append(res, list(tri(num_y,\n len_x + lf_y,\n rt_y))), \n x, tail(y), len_x, used_y + 1);\n }\n }\n }\n return helper(0, [], x, y, len_x, 0);\n }",
"function smooth(y_values, nx, nz){\r\n y_grid = y_values;\r\n\r\n var total = 0;\r\n var count = 0;\r\n for(i=0; i < nx ; i++){\r\n for (j=0; j < nz ; j++){\r\n var toprow = i > 0;\r\n var leftcol = j > 0;\r\n var botrow = i < nx-1;\r\n var rightcol = j < nz-1;\r\n\r\n if (toprow){\r\n total += (y_values[i-1][j]);\r\n count++;\r\n }\r\n\r\n if(leftcol){\r\n total += (y_values[i][j-1]);\r\n count++;\r\n }\r\n\r\n if(botrow){\r\n total += (y_values[i+1][j]);\r\n count++;\r\n }\r\n\r\n if(rightcol){\r\n total += (y_values[i][j+1])\r\n count++;\r\n }\r\n\r\n if(toprow && leftcol){\r\n total += (y_values[i-1][j-1]);\r\n count++;\r\n }\r\n\r\n if(toprow && rightcol){\r\n total += (y_values[i-1][j+1]);\r\n count++;\r\n }\r\n\r\n if(botrow && leftcol){\r\n total += (y_values[i+1][j-1]);\r\n count++;\r\n }\r\n\r\n if(botrow && rightcol){\r\n total += (y_values[i+1][j+1]);\r\n count++;\r\n }\r\n\r\n //find the average\r\n y_grid[i][j] = y_values[i][j]*0.65 + (total/count)*0.35;\r\n total = 0;\r\n count = 0;\r\n }\r\n }\r\n return y_grid;\r\n}",
"function compute_interference() {\n\n // compute boundaries in old funny slider units.\n // TODO: fix this shit.\n let fc = - 0.5 + (sig.freq - sig.freq_plot_min)/(\n sig.freq_plot_max - sig.freq_plot_min);\n let bw = 0.1 + 0.8*(sig.bw - sig.bw_min)/(sig.bw_max - sig.bw_min);\n\n // TODO: interferer values from old code. gn_int = -200 to turn\n // it off.\n let bw_int = 0.05, fc_int = 0.35, gn_int = -200;\n\n\n let f_lower = fc - 0.5*bw, f_upper = fc + 0.5*bw;\n let i_lower = fc_int - 0.5*bw_int, i_upper = fc_int + 0.5*bw_int;\n\n // check for no overlap\n if ((f_lower > i_upper || f_upper < i_lower)) \n\t { return 0; }\n\n // partial or full overlap, compensating gain for interference bandwidth\n let f0 = Math.max(i_lower, f_lower);\n let f1 = Math.min(i_upper, f_upper);\n //return (f1-f0)*Math.pow(10.,gn_int/10.)/bw_int;\n return 0;\n }",
"assign(centrs) {\n\n let APoints = [],\n BPoints = [];\n\nlet points = this.points;\n points.forEach((val, i) => {\n\n let zerox = points[i].x - centrs[0].x; // distance to 1st centroid\n let zeroy = points[i].y - centrs[0].y;\n let onex = points[i].x - centrs[1].x; // distance to 2nd centroid\n let oney = points[i].y - centrs[1].y;\n\n\n // get posititive of each point from each centroid\n let sqzerox = Math.sqrt(zerox * zerox);\n let sqzeroy = Math.sqrt(zeroy * zeroy);\n let sqonex = Math.sqrt(onex * onex);\n let sqoney = Math.sqrt(oney * oney);\n\n // if the point is within the range (all points have less distance than 110 px to all points) push it to according array\n let ranges = this.getRanges();\n (sqzerox || sqzeroy) < ranges.xrange / 3 ? APoints.push(points[i]) : 0;\n (sqonex || sqoney) < ranges.xrange / 3 ? BPoints.push(points[i]) : 0;\n });\n\n return {\n AP: APoints,\n BP: BPoints\n };\n }",
"function linear_interpolate(x, x0, x1, y0, y1){\n return y0 + ((y1 - y0)*((x-x0) / (x1-x0)));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a post object and fetches the current revision for that post. If the revision doesn't exist null will be passed back. | function fetchCurrentRevision (post, next) {
RevisionModel.findById (post.currentRevision, function (error, revision) {
if (!error) {
next (revision);
}
else {
console.log ('Erorr occured while retrieving current revision: ' + error);
next (null);
}
});
} | [
"function updatePost (user, post, fileName, title, datePublished, content, commitId) {\n var newRevision = new RevisionModel ({\n author : user,\n commitId : commitId,\n revisionDate : datePublished,\n content : content,\n });\n\n\n fetchRevisionsByIds (post.revisions, function (revisions) {\n if (revisions != null) {\n // check through the revisions to make sure the commitId doesn't already exist.\n for (key in revisions) {\n if (revisions[key].commitId == commitId) {\n console.log ('This revision already exists');\n return; \n }\n }\n\n // create a new revision for the post\n newRevision.save (function (error) {\n if (!error) {\n post.revisions.push (newRevision);\n post.currentRevision = newRevision;\n post.save (function (error) {\n if (!error) {\n user.revisions.push (newRevision);\n user.save (function (error) {\n if (!error) {\n console.log (\"A new revision was saved\"); \n }\n else {\n console.log (\"A new revision wasn't saved to a user\");\n }\n });\n }\n else {\n console.log (\"A revision was saved but not attributed to the post\");\n }\n });\n }\n else {\n console.log ('an error occured while saving a new revision: ' + error);\n }\n });\n\n }\n else {\n console.log (\"Trying to update a post that doesn't have any revisions\");\n }\n });\n}",
"function getOrigAndPostToParsoid(revision, contentName, updateMode) {\n return self._getOriginalContent(restbase, req, revision)\n .then(function(res) {\n var body = {\n update: updateMode\n };\n body[contentName] = res;\n return restbase.post({\n uri: pageBundleUri,\n headers: {\n 'content-type': 'application/json'\n },\n body: body\n });\n })\n .catch(function(e) {\n // Fall back to plain GET\n return restbase.get({ uri: pageBundleUri });\n });\n }",
"async function getLatestRevision() {\n const result = await getFileRevision({ accessToken, path });\n return result;\n }",
"function navigateToPost() {\n history.push(`${match.url}preview/`);\n }",
"function getRevisionReducer(org) {\n return (promise, itemname) =>\n promise .then( accumulator =>\n org.proxies.get({ name: itemname })\n .then( ({revision}) => {\n if (opt.options.latestrevisionnumber) {\n revision = [revision.pop()];\n }\n return [ ...accumulator, {itemname, revision} ];\n }));\n}",
"function iglooRevision () {\n\t// Content detail\n\tthis.user = ''; // the user who made this revision\n\tthis.page = ''; // the page title that this revision belongs to\n\tthis.pageTitle = ''; // also the page title that this revision belongs to\n\tthis.namespace = 0;\n\tthis.revId = 0; // the ID of this revision (the diff is between this and oldId)\n\tthis.oldId = 0; // the ID of the revision from which this was created\n\tthis.type = 'edit';\n\t\n\tthis.revisionContent = ''; // the content of the revision\n\tthis.diffContent = ''; // the HTML content of the diff\n\tthis.revisionRequest = null; // the content request for this revision.\n\tthis.diffRequest = null; // the diff request for this revision\n\tthis.revisionLoaded = false; // there is content stored for this revision\n\tthis.diffLoaded = false; // there is content stored for this diff\n\t\n\tthis.displayRequest = false; // diff should be displayed when its content next changes\n\tthis.page = null; // the iglooPage object to which this revision belongs\n\t\n\t// Constructor\n\tif (arguments[0]) {\n\t\tthis.setMetaData(arguments[0]);\n\t}\n}",
"function LocalRevision(key, getValue, setValue){\n this.getValue = getValue;\n this.setValue = setValue;\n this.key = key;\n }",
"updatePost(post, fields) {\n fields.post_id = post.id;\n\n let request = this.api.postReview(fields);\n\n return request.then(result => {\n this.setState(previousState => {\n const newState = { ...previousState };\n\n newState.posts[post.id].status = fields.status;\n\n return newState;\n });\n });\n }",
"function showEditor(post){\n\t\t\n\t\t$('#newpostBtn').hide();\n\t\t$('#editpostBtn').hide();\n\t\t$('#savepostBtn').show();\n\t\t$('#deletepostBtn').hide();\n\t\t$('#backBtn').show();\n\t\t\n\t\t$('#editordiv').show();\n\t\t$('#postdiv').hide();\n\t\t$('#postlistdiv').hide();\n\t\t\n\t\t//if we edit an existing post we fill in the form\n\t\tif(post!=null){\n\t\t\t$('#edittitle').val(post.title);\n\t\t\t$('#edittext').val(post.text);\n\t\t\t$('#postid').val(post.id);\n\t\t//if we create a new post we empty the fields\t\n\t\t}else{\n\t\t\t$('#edittitle').val('');\n\t\t\t$('#edittext').val('');\n\t\t\t$('#postid').val('');\n\t\t}\n\t\t\n\t}",
"function focusOnSingularPost() {\n getAppContext().addEventListener(\"click\", function() {\n if (event.target.classList.contains(\"edit-post__submit\")) {\n const postId = event.target.parentElement.querySelector(\n \".delete-post__id\"\n ).value;\n console.log(postId);\n const postsRef = getDatabaseItemContext(postId);\n postsRef.get().then(post => {\n getAppContext().innerHTML = Post(post);\n });\n }\n });\n}",
"function EditPost() {\n if (post.user._id === \"60af83bbbe9b150015506e18\") {\n setEdited(!edited);\n } else {\n alert(\"You can't Edit someone's post!!!\");\n }\n }",
"function displayEditPost(post){\r\n\t\t\t$(\"form#edit-form input#title\").val(post.title);\r\n\t\t\t$(\"form#edit-form textarea#content\").val(post.body);\r\n\t\t}",
"function Post(tistoryObj) {\r\n this.parser = tistoryObj.parser;\r\n this.baseurl = tistoryObj.baseurl;\r\n this.params = {\r\n access_token: tistoryObj.access_token,\r\n format: tistoryObj.format\r\n }\r\n\r\n this._requiredParams = {\r\n 'write': ['title'],\r\n 'modify': ['title', 'postId'],\r\n 'read': ['postId'],\r\n 'attach': ['uploadedfile'],\r\n 'delete': ['postId']\r\n }\r\n}",
"getEntry(t, e) {\n this.assertNotApplied();\n const n = this.changes.get(e);\n return void 0 !== n ? Ks.resolve(n.document) : this.getFromCache(t, e);\n }",
"GetCommentStack( postdata, callback )\n\t{\n\t\tValidation.NOT_EMPTY( postdata, \"id\" );\n\n\t\tModel.Comment.findById( postdata.id, ( e, data ) => {\n\t\t\tif( this.__dbErr( e, callback ) ) return;\n\n\t\t\tif( !data )\n\t\t\t{\n\t\t\t\tcallback( this.App.JsonError( Locale.Error.NO_SUCH_TARGET, postdata.id ) );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.utils.use( \"object\" );\n\t\t\tvar saneData = this.utils.refObj(\n\t\t\t\tdata\n\t\t\t\t, \"_id\", \"ref_script\", \"enc\"\n\t\t\t\t, \"date_created\", \"date_modified\"\n\t\t\t);\n\n\t\t\tsaneData.content = data.enabled ? data.content : data.remarks;\n\t\t\tsaneData.author = data.author\n\t\t\t\t? { _id: data.author._id, name: data.author.profile.display_name }\n\t\t\t\t: null;\n\n\n\t\t\tthis.GetComments(\n\t\t\t\t{ target: \"comment\", id: postdata.id }\n\t\t\t\t, ( e ) => {\n\t\t\t\t\tsaneData.replies = e.data;\n\t\t\t\t\tcallback( this.App.JsonSuccess([ saneData ]) );\n\t\t\t\t}\n\t\t\t\t, 5\n\t\t\t);\n\n\t\t} ).populate( \"author\" );\n\t}",
"findBySlug(req, res) {\n\n let slug = req.param(\"slug\");\n\n Post.where(\"slug\", slug).findOne()\n .populate(\"categories\")\n .populate(\"tags\")\n .populate(\"user\")\n .populate(\"media\")\n .populate({\n path: 'author',\n populate: {\n path: 'image'\n }\n })\n .exec((error, post) => {\n\n if (error) return res.serverError(error);\n if (!post) return res.notFound(req.lang(\"post.errors.post_not_found\"));\n\n post.getContent((error, content) => {\n if (error) return res.serverError(error);\n post.content = content;\n return res.ok(res.attachPolicies(post, \"post\"));\n });\n });\n }",
"function getOldestPostStoredInFirebase() {\n var token = ScriptApp.getOAuthToken();\n var fb = FirebaseApp.getDatabaseByUrl(FIREBASE_DB_URL, token);\n var oldestPost = fb.getData('posts', {orderBy:\"published\", limitToFirst: 1});\n Logger.log(oldestPost);\n throw \"The oldest post retrieved was published on \" + oldestPost[Object.keys(oldestPost)[0]].published;\n}",
"function checkPost(post, options, searchRequest) {\n // The url for accessing a particular post.\n let postAuth = localStorage.getItem(\"api\") + \"/post/?id=\" + post;\n fetch(postAuth, options)\n .then(response => response.json())\n .then(data => {\n let ul = document.getElementById(\"feed\");\n // Checks if any of the contents of the post contain the search\n // request.\n if (data.text.includes(searchRequest)\n || data.title.includes(searchRequest)\n || data.meta.author.includes(searchRequest)\n || data.meta.subseddit.includes(searchRequest)) {\n\n // If search request is in text.\n let post = genFeed(\"returnPost\", data);\n ul.appendChild(post);\n }\n });\n}",
"function getPost(req, res) {\n const pid = parseInt(req.params.pid, 10);\n shared.verifyPID(req, res, () => {\n res.json(db.posts.feed[pid]);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Silver Bullet code file originated Sept 2017 Major restructure: August 2019 KILL EMPTY GROUPS IN LAYER Called from processSibyl to do final check through all layers, deleting empty groups | function killEmptyGroupsInLayer(theLayer) {
var gCount = theLayer.groupItems.length;
for (var gNo = gCount - 1; gNo >= 0; gNo--) {
var thisGroup = theLayer.groupItems[gNo];
if (thisGroup.pageItems.length === 0) {
thisGroup.remove();
}
}
} | [
"deselectAll() {\n\n if (this.currentTab === 'supergroups') {\n for (let sg in this.supergroups) {\n if (this.supergroups.hasOwnProperty(sg)) {\n this.supergroups[sg].visible = false;\n }\n }\n this.checkedSupergroups = [];\n }\n else if (this.currentTab === 'groups') {\n for (let g in this.groups) {\n if (this.groups.hasOwnProperty(g)) {\n this.groups[g].visible = false;\n }\n }\n this.checkedGroups = [];\n }\n\n MapLayers.nuts3.renderLayer();\n\n }",
"function processSibyl(myDoc) {\r\n\t// Basic restructuring sets up the document with:\r\n\t//\t\tbackground layer, containing\r\n\t//\t\t\tbackground shapes and strings\r\n\t//\t\tone or more content (panel) layes, so far containing panel rects and headers (if any)\r\n\r\n\t// All these elements have been converted\r\n if (!restructureDoc(myDoc)) {\r\n alert(\"Initial document restructure failed. Sorry...\");\r\n return;\r\n }\r\n \r\n\t// Now sort out the SVG content groups (in Content)\r\n\tif (!processContentGroups(myDoc)) {\r\n alert(\"Failed to process main group of chart-specific content...\");\r\n\t\treturn false;\r\n\t}\r\n \r\n // LEGENDS\r\n if (!processLegends(myDoc)) {\r\n alert(\"Failed to process legends...\");\r\n return false;\r\n }\r\n\r\n\t// Finally, kill the original default SVG layer\r\n\t// No: done in loop below\r\n\t// try {\r\n\t// \tmyDoc.layers[c_itsLayer1].remove();\r\n\t// }\r\n\t// catch (e) {}\r\n\r\n\t// Layer tidying\r\n\tvar lCount = myDoc.layers.length;\r\n\tfor (var lNo = lCount - 1; lNo >= 0; lNo--) {\r\n\t\tvar theLayer = myDoc.layers[lNo];\r\n\t\tif (theLayer.name === c_itsLayer1) {\r\n\t\t\t// Kill original SVG default layer\r\n\t\t\ttheLayer.remove();\r\n\t\t} else {\t\r\n\t\t\t// Kill any empty groups in surviving layers. Actually,\r\n\t\t\t// this is a bit weird. It looks to me as though Illy\r\n\t\t\t// auto-removes empty groups... but not necessarily\r\n\t\t\t// in time before I finish processing and save the\r\n\t\t\t// file out. So kill anything we can still find...\r\n\t\t\tkillEmptyGroupsInLayer(theLayer);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\treturn true;\r\n}",
"function remove_group() {\n // Enable the remove animation\n remove_animation = true;\n\n // refresh the score\n set_stat(stat_types.score, gamer.score + map.single_score * group.length);\n\n // refresh tha available planets\n gamer.available_planets -= group.length;\n\n // set every planet as assigned to remove\n for (var i = group.length - 1; i >= 0; i--) {\n group[i].assigned = true;\n }\n\n reset_checked_planets();\n\n // play explosion sound effect\n effects.explosion.play();\n }",
"function remove_floating_group() {\n // Enable the remove animation\n remove_animation = true;\n\n // refresh the score\n set_stat(stat_types.score, gamer.score + map.floating_score * group.length);\n\n for (var i = group.length - 1; i >= 0; i--) {\n // refresh the available planets\n gamer.available_planets -= group[i].length;\n // set every planet in the inner array as assigned\n for (var j = group[i].length - 1; j >= 0; j--) {\n group[i][j].assigned = true;\n }\n }\n\n reset_checked_planets();\n\n // play explosion sound effect\n effects.explosion.play();\n }",
"function DeleteLastLayer(){\r\n\t/**\r\n * deleting the last layer from metwork.\r\n *\r\n */\r\n\tif(counter>1)\r\n\t{\r\n\tremoveLayer(counter);\r\n\tcounter--;\r\n\tlayerslist.pop();\r\n\t}\r\n}",
"function fixLineSeriesGroupStructure(cGroup) {\r\n // Loop, looking for the group\r\n\tvar gLen = cGroup.groupItems.length;\r\n\tfor (var gNo = gLen - 1; gNo >= 0; gNo--) {\r\n // Hunt through the content group\r\n\t\tvar thisGroup = cGroup.groupItems[gNo];\r\n\t\tif (thisGroup.name === c_itsAllLineSeriesOuterGroup) {\r\n\t\t\t// This 'all-series' group should contain 2 inner groups:\r\n // line-series-group:line\r\n // line-series-group:points\r\n // debugger;\r\n var g2Len = thisGroup.groupItems.length - 1;\r\n for (var g2No = g2Len; g2No >= 0; g2No--) {\r\n var innerGroup = thisGroup.groupItems[g2No];\r\n if (\r\n innerGroup.name.search(':points') > 0 ||\r\n innerGroup.name.search(':line') > 0\r\n ) {\r\n // Target group of individual line or points series groups\r\n // If these have contents, move them up a level\r\n // debugger;\r\n if (innerGroup.groupItems.length > 0) {\r\n innerGroup.move(cGroup, ElementPlacement.PLACEATEND);\r\n } else {\r\n thisGroup.remove();\r\n }\r\n }\r\n }\r\n\t\t}\r\n\t}\r\n}",
"dropEmptyBlocks() {\n Object.keys(this.emptyMap).forEach((parentBlockId) => {\n const node = this.emptyMap[parentBlockId];\n if (node.updateReference !== this.updateReference) {\n node.parent.removeChild(node);\n delete this.emptyMap[parentBlockId];\n }\n });\n }",
"removeAllMarkers() {\n if (this.markerGroup) this.markerGroup.clearLayers();\n }",
"function GetAllActiveLeaves(){\n var LeavesGO = GameObject.FindGameObjectWithTag(\"Leaves\"); \n LeavesActiveInScene = LeavesGO.GetComponentsInChildren.<Collider2D>(); \n LeavesActiveInSceneGO = new Array();\n for (var a : int = 0; a < LeavesActiveInScene.Length; a++)\n { \n if (LeavesActiveInScene[a].gameObject.tag == \"Untagged\"){\n if(frogLeaf.name != LeavesActiveInScene[a].gameObject.name){\n if (targetLeaf.name != LeavesActiveInScene[a].gameObject.name){\n LeavesActiveInSceneGO.Push(LeavesActiveInScene[a].gameObject);\n //Debug.Log(LeavesActiveInScene[a].gameObject.name);\n }\n }\n }\n}\nDebug.Log(\"length of Ativ \"+ LeavesActiveInScene.Length+\" \"+LeavesActiveInSceneGO.length);\n\n// Remove target leaf\n for (a = 0; a < LeavesActiveInSceneGO.length; a++){\n if (targetLeaf.name == LeavesActiveInScene[a].gameObject.name){\n LeavesActiveInSceneGO.RemoveAt(a);\n a = LeavesActiveInSceneGO.length + 10;\n break;\n }\n }\n\n// Remove target 2 leaf\nif (targetLeaf2 != null){ \n for (a = 0; a < LeavesActiveInSceneGO.length; a++){\n if (targetLeaf2.name == LeavesActiveInScene[a].gameObject.name){\n LeavesActiveInSceneGO.RemoveAt(a);\n a = LeavesActiveInSceneGO.length + 10;\n break;\n }\n }\n}\n\n// Remove target 3 leaf\nif (targetLeaf3 != null){ \n for (a = 0; a < LeavesActiveInSceneGO.length; a++){\n if (targetLeaf3.name == LeavesActiveInScene[a].gameObject.name){\n LeavesActiveInSceneGO.RemoveAt(a);\n a = LeavesActiveInSceneGO.length + 10;\n break;\n }\n }\n}\n\n// Remove target 4 leaf\nif (targetLeaf4 != null){ \n for (a = 0; a < LeavesActiveInSceneGO.length; a++){\n if (targetLeaf4.name == LeavesActiveInScene[a].gameObject.name){\n LeavesActiveInSceneGO.RemoveAt(a);\n a = LeavesActiveInSceneGO.length + 10;\n break;\n }\n }\n}\n\n// Remove target 5 leaf\nif (targetLeaf5 != null){ \n for (a = 0; a < LeavesActiveInSceneGO.length; a++){\n if (targetLeaf5.name == LeavesActiveInScene[a].gameObject.name){\n LeavesActiveInSceneGO.RemoveAt(a);\n a = LeavesActiveInSceneGO.length + 10;\n break;\n }\n }\n}\n\n// Remove Frog Leaf\nif (frogLeaf != null){\n for (a = 0; a < LeavesActiveInSceneGO.length; a++){\n if (frogLeaf.name == LeavesActiveInScene[a].gameObject.name){\n LeavesActiveInSceneGO.RemoveAt(a);\n a = LeavesActiveInSceneGO.length + 10;\n break;\n }\n }\n}\n\n// Remove Frog 2 Leaf\nif (frog2Leaf != null){\n for (a = 0; a < LeavesActiveInSceneGO.length; a++){\n if (frog2Leaf.name == LeavesActiveInScene[a].gameObject.name){\n LeavesActiveInSceneGO.RemoveAt(a);\n a = LeavesActiveInSceneGO.length + 10;\n break;\n }\n }\n}\n\n// Remove Frog 3 Leaf\nif (frog3Leaf != null){\n for (a = 0; a < LeavesActiveInSceneGO.length; a++){\n if (frog3Leaf.name == LeavesActiveInScene[a].gameObject.name){\n LeavesActiveInSceneGO.RemoveAt(a);\n a = LeavesActiveInSceneGO.length + 10;\n break;\n }\n }\n}\n\n// remove Stars StarsLeaf;\nDebug.Log(\"star length \"+StarsLeaf.Count);\nfor(var s = 0; s < StarsLeaf.Count; s++ ){\n for (a = 0; a < LeavesActiveInSceneGO.length; a++){\n if (StarsLeaf[s].gameObject.name == LeavesActiveInScene[a].gameObject.name){\n LeavesActiveInSceneGO.RemoveAt(a);\n Debug.Log(\"Removed Star leaf at \"+StarsLeaf[s].gameObject.name);\n a = LeavesActiveInSceneGO.length + 10;\n break;\n }\n }\n}\n\n}",
"initGroup(){\n if(!this._shapeGroup){\n this.#createGroup();\n }\n }",
"removeAllComponents() {\n var size = this.closet_drawers_ids.length;\n for (let i = 0; i < size; i++) {\n this.closet.removeDrawer();\n var closet_drawer_face_id = this.closet_drawers_ids.pop();\n this.group.remove(this.group.getObjectById(closet_drawer_face_id));\n }\n\n size = this.closet_modules_ids.length;\n for (let i = 0; i < size; i++) {\n this.closet.removeModule();\n var closet_module_face_id = this.closet_modules_ids.pop();\n this.group.remove(this.group.getObjectById(closet_module_face_id));\n }\n\n size = this.closet_hinged_doors_ids.length;\n for (let i = 0; i < size; i++) {\n this.closet.removeHingedDoor();\n var closet_hinged_door_face_id = this.closet_hinged_doors_ids.pop();\n this.group.remove(this.group.getObjectById(closet_hinged_door_face_id));\n }\n\n size = this.closet_sliding_doors_ids.length;\n for (let i = 0; i < size; i++) {\n this.removeSlidingDoor();\n }\n\n size = this.closet_shelves_ids.length;\n for (let i = 0; i < size; i++) {\n this.closet.removeShelf();\n var closet_shelf_face_id = this.closet_shelves_ids.pop();\n this.group.remove(this.group.getObjectById(closet_shelf_face_id));\n }\n\n size = this.closet_poles_ids.length;\n for (let i = 0; i < size; i++) {\n this.closet.removePole();\n var closet_poles_id = this.closet_poles_ids.pop();\n this.group.remove(this.group.getObjectById(closet_poles_id));\n }\n\n store.dispatch(SET_COMPONENT_TO_REMOVE);\n this.selected_component = null;\n this.controls.enabled = true;\n\n this.updateClosetGV();\n }",
"function loadGroups(that) {\r\n if (that.config.groups !== undefined) {\r\n $.each(that.config.groups, function (index, value) {\r\n //Group reducing function by Size\r\n if (that.config.groups[index].context === \"context:reduce\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group().reduce(\r\n function (p, v) {\r\n ++p.count;\r\n p.AvgSize = v.AvgSize;\r\n p.sumAvgSize += v[that.config.groups[index].datafield];\r\n p.avgAvgSize = p.sumAvgSize / p.count;\r\n p.fluctuation += v[that.config.groups[index].datafield] - p.lastAvgSize;\r\n p.lastAvgSize = v[that.config.groups[index].datafield];\r\n \t\t\t if(p.avgAvgSize == 0){\r\n \t\t\t\tp.fluctuationPercentage = (Math.abs(p.fluctuation) / 1) * 100;\r\n \t\t\t }\r\n \t\t\t else{\r\n \tp.fluctuationPercentage = (Math.abs(p.fluctuation) / p.avgAvgSize) * 100;\r\n }\r\n return p;\r\n },\r\n function (p, v) {\r\n --p.count;\r\n p.AvgSize = v.AvgSize;\r\n p.sumAvgSize -= v[that.config.groups[index].datafield];\r\n p.avgAvgSize = p.sumAvgSize / p.count;\r\n p.fluctuation -= v[that.config.groups[index].datafield] - p.lastAvgSize;\r\n p.lastAvgSize = v[that.config.groups[index].datafield];\r\n if(p.avgAvgSize == 0){\r\n \t\t\t\tp.fluctuationPercentage = (Math.abs(p.fluctuation) / 1) * 100;\r\n \t\t\t }\r\n \t\t\t else{\r\n \t\t\t\t p.fluctuationPercentage = (Math.abs(p.fluctuation) / p.avgAvgSize) * 100;\r\n \t\t\t }\r\n return p;\r\n },\r\n function () {\r\n return { count: 0, AvgSize: 0, sumAvgSize: 0, avgAvgSize: 0, fluctuation: 0, lastAvgSize: 0, fluctuationPercentage: 0 };\r\n }\r\n );\r\n }\r\n\r\n //Group function\r\n if (that.config.groups[index].context === \"context:groupkey\") {\r\n //that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group(function(d){return d[that.config.groups[index].datafield];});\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group(function(d){\r\n console.log(d[that.config.groups[index].datafield]);\r\n return d[that.config.groups[index].datafield];\r\n });\r\n }\r\n\r\n //Group function\r\n if (that.config.groups[index].context === \"context:group\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group();\r\n }\r\n\r\n //Group Reduce Count function\r\n if (that.config.groups[index].context === \"context:reducecount\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group().reduceCount(function (d) {\r\n return d3.time.month(d.dd);\r\n });\r\n }\r\n\r\n //Group Reduce Count function\r\n if (that.config.groups[index].context === \"context:reducecountkey\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group().reduceCount();\r\n }\r\n\r\n //Group Reduce Sum function\r\n if (that.config.groups[index].context === \"context:reducesum\") {\r\n that.idxGroup[index] = that.idxDimension[that.config.groups[index].dimensionid].group().reduceSum(function (d) {\r\n return d[that.config.groups[index].datafield];\r\n });\r\n }\r\n });\r\n }\r\n }",
"function clearMap(retainSampleCombo, retainMapMatchedGroups){\n\t\troadGroups.forEach(function (val, idx){\n\t\t\tval.removeAll();\n\t\t});\n\t\troutingGroup.removeAll();\n\t\troadGroups = [];\n\t\troadShapes = [];\n\t\troadEdits = [];\n\t\tif(overlayGroup) overlayGroup.removeAll();\n\t\tdocument.getElementById(\"overlay-def-container\").innerHTML = \"\"\n\t\tdocument.getElementById(\"feedbackTxt\").innerHTML = \"\";\n\t\tif(!retainSampleCombo){\n\t\t\tdocument.getElementById(\"sampleSelector\").selectedIndex = 0;\n\t\t}\n\t\t\n\t\t// remove all road selector items added\n\t\tvar selectobject = document.getElementById(\"roadSelector\");\n\t\tselectobject.selectedIndex = 0;\n\t\t\n\t\tfor (var i=selectobject.length-1; i>0; i--){\n\t\t\tif (i > 0){\n\t\t\t\tselectobject.remove(i);\n\t\t\t}\n\t\t}\n\n\t\tif (retainMapMatchedGroups){ //remove all the groups which display the map matching points/links\n\n\t\t\tif (mapMatchedRoadGroups){\n\t\t\t\tfor (var m=0; m<mapMatchedRoadGroups.length; m++){\n\t\t\t\t\tmapMatchedRoadGroups[m].removeAll();\n\t\t\t\t}\n\t\t\t\tmapMatchedRoadGroups = [];\n\t\t\t\tmapMatchedRoadShapes = [];\n\t\t\t}\n\n\t\t}\n\n\t}",
"function removeAllGBeaconComposite(){\n for(i in COMPOSITE.items){\n if(COMPOSITE.items[i] != null){\n ge.getFeatures().removeChild(COMPOSITE.items[i].dopplerMarker.marker);\n COMPOSITE.items[i].dopplerMarker.marker.release();\n if(COMPOSITE.items[i].gpsMarker){\n ge.getFeatures().removeChild(COMPOSITE.items[i].gpsMarker.marker);\n COMPOSITE.items[i].gpsMarker.marker.release();\n }\n }\n }\n COMPOSITE.clear();\n}",
"function validateGroupReferences() {\n\n\n\t//data element group membership\n\tvar item, group, grouped = {}, unGrouped = [], found = false, validMembers;\n\tfor (var i = 0; metaData.dataElementGroups && i < metaData.dataElementGroups.length; i++) {\n\t\tvalidMembers = [];\n\t\tgroup = metaData.dataElementGroups[i];\n\t\tfor (var j = 0; j < group.dataElements.length; j++) {\n\t\t\titem = group.dataElements[j];\n\t\t\tfound = false;\n\t\t\tfor (var k = 0; !found && metaData.dataElements && k < metaData.dataElements.length; k++) {\n\t\t\t\tif (item.id === metaData.dataElements[k].id) {\n\t\t\t\t\tfound = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found) {\n\t\t\t\tvalidMembers.push(item);\n\t\t\t\tgrouped[item.id] = true;\n\t\t\t}\n\t\t}\n\t\tmetaData.dataElementGroups[i].dataElements = validMembers;\n\t\tdelete metaData.dataElementGroups[i].dataElementGroupSet;\n\t}\n\tfor (var i = 0; metaData.dataElements && i < metaData.dataElements.length; i++) {\n\t\tif (!grouped.hasOwnProperty(metaData.dataElements[i].id)) {\n\t\t\tunGrouped.push({\n\t\t\t\t\"id\": metaData.dataElements[i].id,\n\t\t\t\t\"name\": metaData.dataElements[i].shortName,\n\t\t\t\t\"type\": \"dataElements\"\n\t\t\t});\n\t\t}\n\t}\n\n\n\t//indicator group membership\n\tgrouped = {};\n\tfor (var i = 0; metaData.indicatorGroups && i < metaData.indicatorGroups.length; i++) {\n\t\tvalidMembers = [];\n\t\tgroup = metaData.indicatorGroups[i];\n\n\t\tfor (var j = 0; j < group.indicators.length; j++) {\n\t\t\titem = group.indicators[j];\n\t\t\tfound = false;\n\t\t\tfor (var k = 0; !found && metaData.indicators && k < metaData.indicators.length; k++) {\n\t\t\t\tif (item.id === metaData.indicators[k].id) {\n\t\t\t\t\tfound = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (found) {\n\t\t\t\tvalidMembers.push(item);\n\t\t\t\tgrouped[item.id] = true;\n\t\t\t}\n\t\t}\n\t\tmetaData.indicatorGroups[i].indicators = validMembers;\n\t\tdelete metaData.indicatorGroups[i].indicatorGroupSet;\n\t}\n\n\tfor (var i = 0; metaData.indicators && i < metaData.indicators.length; i++) {\n\t\tif (!grouped.hasOwnProperty(metaData.indicators[i].id)) {\n\t\t\tunGrouped.push({\n\t\t\t\t\"id\": metaData.indicators[i].id,\n\t\t\t\t\"name\": metaData.indicators[i].shortName,\n\t\t\t\t\"type\": \"indicators\"\n\t\t\t});\n\t\t}\n\t}\n\n\n\t//catetory option group membership\n\tfor (var i = 0; metaData.hasOwnProperty(\"categoryOptionGroups\") && i < metaData.categoryOptionGroups.length; i++) {\n\t\tvar group = metaData.categoryOptionGroups[i];\n\t\tvar validOptions = [];\n\t\tfor (var j = 0; group.hasOwnProperty(\"categoryOptions\") && j < group.categoryOptions.length; j++) {\n\t\t\tvar option = group.categoryOptions[j];\n\n\t\t\t//Check if the option referenced is part if the category options\n\t\t\tif (objectExists(\"categoryOptions\", option.id)) {\n\t\t\t\tvalidOptions.push(option);\n\t\t\t}\n\t\t}\n\t\tmetaData.categoryOptionGroups[i].categoryOptions = validOptions;\n\t}\n\n\t\n\tif (unGrouped.length > 0) {\n\t\tconsole.log(\"\\nERROR | Data elements/indicators referenced, but not in any groups:\");\n\t\tfor (var issue of unGrouped) {\n\t\t\tconsole.log(issue.type + \" - \" + issue.id + \" - \" \n\t\t\t\t+ issue.name);\n\t\t}\n\t}\n\telse return true;\n}",
"function cleanMap() {\n\n\t// Disable position selection by mouse click.\n\tdisablePositionSelect();\n\n\t// Remove existing nearby stations layer.\n\tif (map.getLayersByName(\"Nearby Docking Stations\")[0] != null)\n\t\tmap.removeLayer(map.getLayersByName(\"Nearby Docking Stations\")[0]);\n\t\t\n\t// Reset select controls.\n\tif (selectControl !=null) {\n\t\tselectControl.unselectAll();\n\t\tselectControl.deactivate();\n\t}\n \tif (selIncControl !=null) {\n\t\tselIncControl.unselectAll();\n\t\tselIncControl.deactivate();\n\t}\n \tif (voteControl !=null) {\n\t\tvoteControl.unselectAll();\n\t\tvoteControl.deactivate();\n\t} \n\tif (selectDockControl != null) {\n\t\tselectDockControl.unselectAll();\n\t\tselectDockControl.deactivate();\n\t}\n\n\tif (distr_stats != null)\n\t\tmap.removeLayer(distr_stats);\n}",
"function clearEmptyGames() {\n\n }",
"onTableGroupRemove (groupName) {\n if (this.tablesRetain.length <= 0) return // retain tables list already empty\n if (!groupName) {\n console.warn('Unable to remove table group from retain list, group name is empty')\n return\n }\n this.$q.notify({ type: 'info', message: this.$t('Suppress group of output tables') + ': ' + groupName })\n\n // remove tables group from the list\n const gt = this.groupTableLeafs[groupName]\n if (gt) {\n this.tablesRetain = this.tablesRetain.filter(tn => !gt?.leafs[tn])\n this.refreshTableTreeTickle = !this.refreshTableTreeTickle\n }\n }",
"updateLayers() {\n // NOTE: For now, even if only some layer has changed, we update all layers\n // to ensure that layer id maps etc remain consistent even if different\n // sublayers are rendered\n const reason = this.needsUpdate();\n\n if (reason) {\n this.setNeedsRedraw(`updating layers: ${reason}`); // Force a full update\n\n this.setLayers(this._nextLayers || this._lastRenderedLayers, reason);\n } // Updated, clear the backlog\n\n\n this._nextLayers = null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collapsible sidebar portlets Source: ============================================================ | function foldingPortlets() {
var portlets = getElementsByClassName(document.getElementById('column-one'), 'div', 'portlet');
var portskip = ['p-personal', 'p-cactions', 'p-logo', 'ads-top-left', 'p-search', 'p-tbx', 'p-wikicities-nav', 'p-lang'];
var num = 0;
for (var i = 0; i < portlets.length; i++) {
if (portskip.join(' ').indexOf(portlets[i].id) == -1) {
var pd = portlets[i].getElementsByTagName('div')[0];
var ph = portlets[i].getElementsByTagName('h5')[0];
ph.className = 'portletCollapsible';
pd.setAttribute('id', 'pbody-' + i);
pd.style.display = 'none';
var link = document.createElement('a');
var head = getAllText(ph);
while (ph.firstChild) {
ph.removeChild(ph.firstChild);
}
link.appendChild(document.createTextNode(head));
link.setAttribute('href', 'javascript:showPortlet(\'' + i + '\');');
link.setAttribute('id', 'plink-'+i);
link.className = 'portletClosed';
ph.appendChild(link);
if (num++ < 3) {
showPortlet(i);
}
}
}
} | [
"function switchToCollapsibleLayout() {\n layout = \"collapsible\";\n var sidebarFull = $(\".left-sidebar-toplevel\").detach();\n $(\".sidebar-target-collapsible\").prepend(sidebarFull);\n $(\".left-sidebar-toplevel\").addClass(\"left-sidebar-collapsible\");\n $(\".left-sidebar-toplevel\").removeClass(\"left-sidebar-fixed col-4 col-lg-4 col-xl-3 \");\n $(\".left-sidebar-togglebutton\").removeClass(\"hide\");\n $(\".center-content\").removeClass(\"col-8\");\n $(\".center-content\").addClass(\"col-12\");\n\t}",
"function showSidebarBrowser()\n{\n $(\".sidebar-browser\").show();\n hideBrowserTemplatesInUse();\n}",
"function onOpen() \n{\n SpreadsheetApp.getUi()\n .createMenu('Custom Menu')\n .addItem('Open Export Sidebar', 'showSidebar')\n .addToUi();\n}",
"getSidebar( context, options ) {\n\n // Initialize the sidebar section data.\n const sections = [];\n\n // Initialize a helper for generating a new section.\n class Section {\n constructor( options = {} ) {\n this.content = _.compact([...(options.content || [])]);\n this.button = _.isPlainObject(options.button) ? options.button : null;\n this.links = _.compact([...(options.links || [])]);\n this.icon = options.icon || false;\n this.title = options.title || null;\n }\n }\n\n // Extract contact information from the context for the first section.\n if( context.phone || context.fax || context.libcal ) sections.push(new Section({\n title: 'Contact Information',\n content: [\n context.phone ? `P: ${formats.formatPhone(context.phone, '000-000-0000')}` : null,\n context.fax ? `F: ${formats.formatPhone(context.fax, '000-000-0000')}` : null,\n ],\n button: context.libcal ? {\n href: context.libcal,\n label: 'Schedule an Appointment'\n } : null\n }));\n\n // Extract mailing address information from the context for the next section.\n if( context.address ) sections.push(new Section({\n title: 'Mailing Address',\n content: [\n context.address.name,\n context.address.street,\n (context.address.city ? `${context.address.city}, ` : '') +\n (context.address.state ? `${context.address.state} ` : '') +\n (context.address.zip ? `${context.address.zip}` : '')\n ]\n }));\n\n // Extract subject area information from the context for the next section.\n if( context.subjects ) sections.push(new Section({\n title: 'Areas of Expertise',\n links: _.map(context.subjects, (subject) => ({\n href: `/services/subject-librarians?subject=${_.replace(subject, ' ', '+')}`,\n label: subject\n }))\n }));\n\n // Extract research guides information from the context for the next section.\n if( context.guides ) sections.push(new Section({\n title: 'Research Help',\n links: [{\n href: context.guides,\n label: 'View Research Guides'\n }]\n }));\n\n // Extract download links information from the context for the last section.\n if( context.cv ) sections.push(new Section({\n title: 'Related Downloads',\n links: [{\n href: context.cv,\n label: 'Curriculum Vitae (CV)',\n icon: 'material-picture_as_pdf'\n }]\n }));\n\n // Return the sections data.\n return sections;\n\n }",
"function displayDataAsSidebar() {\n var html = HtmlService.createTemplateFromFile('DummyData'); \n SpreadsheetApp.getUi() \n .showSidebar(html.evaluate());\n}",
"toggleSidebarFolded() {\n this._yqSidebarService.getSidebar('navbar').toggleFold();\n }",
"function renderToSidebar(template, title) {\n ui.showSidebar(HtmlService\n .createTemplateFromFile(template)\n .evaluate()\n .setTitle(title)\n .setWidth(300)\n .setSandboxMode(HtmlService.SandboxMode.IFRAME));\n}",
"function i2uiToggleNavarea(name)\r\n{\r\n if (document.layers)\r\n return;\r\n var item = document.getElementById(name);\r\n if (item != null)\r\n {\r\n if (item.tagName == \"IFRAME\" ||\r\n item.tagName == \"DIV\")\r\n {\r\n if (item.style.display == \"none\")\r\n {\r\n item.style.display = \"\";\r\n item.style.visibility = \"visible\";\r\n }\r\n else\r\n {\r\n item.style.display = \"none\";\r\n }\r\n }\r\n else\r\n if (item.tagName == \"FRAME\")\r\n {\r\n // split owning frameset into array of frame widths\r\n var colarray = item.parentElement.cols.split(\",\");\r\n\r\n // build new frameset definition\r\n var result = \"\";\r\n for (var i=0; i<item.parentElement.children.length; i++)\r\n {\r\n // if located desired frame\r\n if (item.parentElement.children[i].name == name)\r\n {\r\n if (item.style.display == \"none\")\r\n {\r\n item.style.display = \"\";\r\n item.style.visibility = \"visible\";\r\n colarray[i] = 170;\r\n }\r\n else\r\n {\r\n item.style.display = \"none\";\r\n colarray[i] = 0;\r\n }\r\n }\r\n if (i > 0)\r\n result += \",\";\r\n result += colarray[i];\r\n }\r\n\r\n // write new framset definition\r\n item.parentElement.cols = result;\r\n }\r\n }\r\n}",
"function updateSidebar() {\n var currentScrollY = document.body.scrollTop;\n var topSideOffset = 120;\n\n var activeHash;\n for (var i = 0; i < allLinks.length; i++) {\n var h = allLinks[i];\n var hash = h.getElementsByTagName(\"a\")[0].hash;\n\n if (h.offsetTop - topSideOffset > currentScrollY) {\n if (!activeHash) {\n activeHash = hash;\n break;\n }\n } else {\n activeHash = hash;\n }\n }\n\n if (activeHash) {\n setActiveSubTopic(activeHash);\n }\n }",
"function Sidebar() {\n if (!(this instanceof Sidebar)) {\n return new Sidebar();\n };\n\n this.el = render.dom(template);\n}",
"function mySnippet(){\n\t//The local-independent name (aka \"key string\") for the \n\t//Layout context menu is \"$ID/RtMouseLayout\".\n\tvar myLayoutContextMenu = app.menus.item(\"$ID/RtMouseLayout\");\n\t//Create the event handler for the \"beforeDisplay\" event of the Layout context menu.\n\tvar myBeforeDisplayListener = myLayoutContextMenu.addEventListener(\"beforeDisplay\", myBeforeDisplayHandler, false);\n\t//This event handler checks the type of the selection.\n\t//If a graphic is selected, the event handler adds the script menu action to the menu.\n\tfunction myBeforeDisplayHandler(myEvent){\n\t\t//Check for open documents is a basic sanity check--\n\t\t//it should never be needed, as this menu won't be\n\t\t//displayed unless an item is selected. But it's best\n\t\t//to err on the side of safety.\n\t\tif(app.documents.length != 0){\n\t\t\tif(app.selection.length > 0){\n\t\t\t\tvar myObjectList = new Array;\n\t\t\t\t//Does the selection contain any graphics?\n\t\t\t\tfor(var myCounter = 0; myCounter < app.selection.length; myCounter ++){\n\t\t\t\t\tswitch(app.selection[myCounter].constructor.name){\n\t\t\t\t\t\tcase \"PDF\":\n\t\t\t\t\t\tcase \"EPS\":\n\t\t\t\t\t\tcase \"Image\":\n\t\t\t\t\t\t\tmyObjectList.push(app.selection[myCounter]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"Rectangle\":\n\t\t\t\t\t\tcase \"Oval\":\n\t\t\t\t\t\tcase \"Polygon\":\n\t\t\t\t\t\t\tif(app.selection[myCounter].graphics.length != 0){\n\t\t\t\t\t\t\t\tmyObjectList.push(app.selection[myCounter].graphics.item(0));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(myObjectList.length > 0){\n\t\t\t\t\t//Add the menu item if it does not already exist.\n\t\t\t\t\tif(myCheckForMenuItem(myLayoutContextMenu, \"Create Graphic Label\") == false){\n\t\t\t\t\t\tmyMakeLabelGraphicMenuItem();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t//Remove the menu item, if it exists.\n\t\t\t\t\tif(myCheckForMenuItem(myLayoutContextMenu, \"Create Graphic Label\") == true){\n\t\t\t\t\t\tmyLayoutContextMenu.menuItems.item(\"Create Graphic Label\").remove();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfunction myCheckForMenuItem(myMenu, myString){\n\t\t\tvar myResult = false;\n\t\t\ttry{\n\t\t\t\tvar myMenuItem = myMenu.menuItems.item(myString);\n\t\t\t\tmyMenuItem.name;\n\t\t\t\tmyResult = true\n\t\t\t}\n\t\t\tcatch(myError){}\n\t\t\treturn myResult;\n\t\t}\n\t\tfunction myCheckForScriptMenuItem(myString){\n\t\t\tvar myResult = false;\n\t\t\ttry{\n\t\t\t\tvar myScriptMenuAction = app.scriptMenuActions.item(myString);\n\t\t\t\tmyScriptMenuAction.name;\n\t\t\t\tmyResult = true\n\t\t\t}\n\t\t\tcatch(myError){}\n\t\t\treturn myResult;\t\t\t\n\t\t}\n\t\tfunction myMakeLabelGraphicMenuItem(){\n\t\t\tif(myCheckForScriptMenuItem(\"Create Graphic Label\") == false){\n\t\t\t\tvar myLabelGraphicMenuAction = app.scriptMenuActions.add(\"Create Graphic Label\");\n\t\t\t\tvar myLabelGraphicEventListener = myLabelGraphicMenuAction.eventListeners.add(\"onInvoke\", myLabelGraphicEventHandler, false);\n\t\t\t}\n\t\t\tvar myLabelGraphicMenuItem = app.menus.item(\"$ID/RtMouseLayout\").menuItems.add(app.scriptMenuActions.item(\"Create Graphic Label\"));\n\t\t\tfunction myLabelGraphicEventHandler(myEvent){\n\t\t\t\tif(app.selection.length > 0){\n\t\t\t\t\tvar myObjectList = new Array;\n\t\t\t\t\t//Does the selection contain any graphics?\n\t\t\t\t\tfor(var myCounter = 0; myCounter < app.selection.length; myCounter ++){\n\t\t\t\t\t\tswitch(app.selection[myCounter].constructor.name){\n\t\t\t\t\t\t\tcase \"PDF\":\n\t\t\t\t\t\t\tcase \"EPS\":\n\t\t\t\t\t\t\tcase \"Image\":\n\t\t\t\t\t\t\t\t\tmyObjectList.push(app.selection[myCounter]);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"Rectangle\":\n\t\t\t\t\t\t\tcase \"Oval\":\n\t\t\t\t\t\t\tcase \"Polygon\":\n\t\t\t\t\t\t\t\tif(app.selection[myCounter].graphics.length != 0){\n\t\t\t\t\t\t\t\t\tmyObjectList.push(app.selection[myCounter].graphics.item(0));\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:\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(myObjectList.length > 0){\n\t\t\t\t\t\tmyDisplayDialog(myObjectList);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//Function that adds the label.\n\t\t\t\tfunction myAddLabel(myGraphic, myLabelType, myLabelHeight, myLabelOffset, myLabelStyleName, myLayerName){\n\t\t\t\t\tvar myLabelLayer;\n\t\t\t\t\tvar myDocument = app.documents.item(0);\n\t\t\t\t\tvar myLabel;\n\t\t\t\t\tmyLabelStyle = myDocument.paragraphStyles.item(myLabelStyleName);\n\t\t\t\t\tvar myLink = myGraphic.itemLink;\n\t\t\t\t\ttry{\n\t\t\t\t\t\tmyLabelLayer = myDocument.layers.item(myLayerName);\n\t\t\t\t\t\t//If the layer does not exist, trying to get the layer name will cause an error.\n\t\t\t\t\t\tmyLabelLayer.name;\n\t\t\t\t\t}\n\t\t\t\t\tcatch (myError){\n\t\t\t\t\t\tmyLabelLayer = myDocument.layers.add(myLayerName); \n\t\t\t\t\t} \n\t\t\t\t\t//Label type defines the text that goes in the label.\n\t\t\t\t\tswitch(myLabelType){\n\t\t\t\t\t\t//File name\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\tmyLabel = myLink.name;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t//File path\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tmyLabel = myLink.filePath;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t//XMP description\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\ttry{\n\t\t\t\t\t\t\t\tmyLabel = myLink.linkXmp.description;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcatch(myError){\n\t\t\t\t\t\t\t\tmyLabel = \"No description available.\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t//XMP author\n\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t\ttry{\n\t\t\t\t\t\t\t\tmyLabel = myLink.linkXmp.author\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcatch(myError){\n\t\t\t\t\t\t\t\tmyLabel = \"No author available.\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tvar myFrame = myGraphic.parent;\n\t\t\t\t\tvar myX1 = myFrame.geometricBounds[1]; \n\t\t\t\t\tvar myY1 = myFrame.geometricBounds[2] + myLabelOffset; \n\t\t\t\t\tvar myX2 = myFrame.geometricBounds[3]; \n\t\t\t\t\tvar myY2 = myY1 + myLabelHeight;\n\t\t\t\t\tvar myTextFrame = myFrame.parent.textFrames.add(myLabelLayer, undefined, undefined,{geometricBounds:[myY1, myX1, myY2, myX2], contents:myLabel}); \n\t\t\t\t\tmyTextFrame.textFramePreferences.firstBaselineOffset = FirstBaseline.leadingOffset; \n\t\t\t\t\tmyTextFrame.paragraphs.item(0).appliedParagraphStyle = myLabelStyle;\t\t\t\t\n\t\t\t\t}\n\t\t\t\tfunction myDisplayDialog(myObjectList){\n\t\t\t\t\tvar myLabelWidth = 100;\n\t\t\t\t\tvar myStyleNames = myGetParagraphStyleNames(app.documents.item(0));\n\t\t\t\t\tvar myLayerNames = myGetLayerNames(app.documents.item(0));\n\t\t\t\t\tvar myDialog = app.dialogs.add({name:\"LabelGraphics\"});\n\t\t\t\t\twith(myDialog.dialogColumns.add()){\n\t\t\t\t\t\t//Label type\n\t\t\t\t\t\twith(dialogRows.add()){\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tstaticTexts.add({staticLabel:\"Label Type\", minWidth:myLabelWidth});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tvar myLabelTypeDropdown = dropdowns.add({stringList:[\"File name\", \"File path\", \"XMP description\", \"XMP author\"], selectedIndex:0});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Text frame height\n\t\t\t\t\t\twith(dialogRows.add()){\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tstaticTexts.add({staticLabel:\"Label Height\", minWidth:myLabelWidth});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tvar myLabelHeightField = measurementEditboxes.add({editValue:24, editUnits:MeasurementUnits.points});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Text frame offset\n\t\t\t\t\t\twith(dialogRows.add()){\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tstaticTexts.add({staticLabel:\"Label Offset\", minWidth:myLabelWidth});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tvar myLabelOffsetField = measurementEditboxes.add({editValue:0, editUnits:MeasurementUnits.points});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Style to apply\n\t\t\t\t\t\twith(dialogRows.add()){\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tstaticTexts.add({staticLabel:\"Label Style\", minWidth:myLabelWidth});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tvar myLabelStyleDropdown = dropdowns.add({stringList:myStyleNames, selectedIndex:0});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Layer\n\t\t\t\t\t\twith(dialogRows.add()){\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tstaticTexts.add({staticLabel:\"Layer:\", minWidth:myLabelWidth});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twith(dialogColumns.add()){\n\t\t\t\t\t\t\t\tvar myLayerDropdown = dropdowns.add({stringList:myLayerNames, selectedIndex:0});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tvar myResult = myDialog.show();\n\t\t\t\t\tif(myResult == true){\n\t\t\t\t\t\tvar myLabelType = myLabelTypeDropdown.selectedIndex;\n\t\t\t\t\t\tvar myLabelHeight = myLabelHeightField.editValue;\n\t\t\t\t\t\tvar myLabelOffset = myLabelOffsetField.editValue;\n\t\t\t\t\t\tvar myLabelStyle = myStyleNames[myLabelStyleDropdown.selectedIndex];\n\t\t\t\t\t\tvar myLayerName = myLayerNames[myLayerDropdown.selectedIndex];\n\t\t\t\t\t\tmyDialog.destroy();\n\t\t\t\t\t\tvar myOldXUnits = app.documents.item(0).viewPreferences.horizontalMeasurementUnits;\n\t\t\t\t\t\tvar myOldYUnits = app.documents.item(0).viewPreferences.verticalMeasurementUnits;\n\t\t\t\t\t\tapp.documents.item(0).viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points;\n\t\t\t\t\t\tapp.documents.item(0).viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;\n\t\t\t\t\t\tfor(var myCounter = 0; myCounter < myObjectList.length; myCounter++){\n\t\t\t\t\t\t\tvar myGraphic = myObjectList[myCounter];\n\t\t\t\t\t\t\tmyAddLabel(myGraphic, myLabelType, myLabelHeight, myLabelOffset, myLabelStyle, myLayerName);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tapp.documents.item(0).viewPreferences.horizontalMeasurementUnits = myOldXUnits;\n\t\t\t\t\t\tapp.documents.item(0).viewPreferences.verticalMeasurementUnits = myOldYUnits;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tmyDialog.destroy();\n\t\t\t\t\t}\n\t\t\t\t\tfunction myGetParagraphStyleNames(myDocument){\n\t\t\t\t\t\tvar myStyleNames = myDocument.paragraphStyles.everyItem().name;\n\t\t\t\t\t\treturn myStyleNames;\n\t\t\t\t\t}\n\t\t\t\t\tfunction myGetLayerNames(myDocument){\n\t\t\t\t\t\tvar myLayerNames = new Array;\n\t\t\t\t\t\tvar myAddLabelLayer = true;\n\t\t\t\t\t\tfor(var myCounter = 0; myCounter<myDocument.layers.length; myCounter++){\n\t\t\t\t\t\t\tmyLayerNames.push(myDocument.layers.item(myCounter).name);\n\t\t\t\t\t\t\tif (myDocument.layers.item(myCounter).name == \"Labels\"){\n\t\t\t\t\t\t\t\tmyAddLabelLayer = false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(myAddLabelLayer == true){\n\t\t\t\t\t\t\tmyLayerNames.push(\"Labels\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn myLayerNames;\n\t\t\t\t\t}\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n}",
"function showCollapsable(showThisOne){\r\n\t\tvar toggledCollapsable = showThisOne;\r\n\r\n\t\t\t\r\n\t\tif(toggledCollapsable == 1){\r\n\t\t\tcontent = content1;\r\n\t\t\t// content[0].style.height = \"500px\";\r\n\t\t}else if(toggledCollapsable == 2){\r\n\t\t\tcontent = content2;\r\n\t\t}else if(toggledCollapsable == 3){\r\n\t\t\tcontent = content3;\r\n\t\t}else if(toggledCollapsable == 4){\r\n\t\t\tcontent = content4;\r\n\t\t}else{\r\n\t\t\tcontent = content5;\r\n\t\t}\r\n\r\n\t\tif(content.style.maxHeight){\r\n\t\t\tcontent.style.maxHeight = null;\r\n\t\t}else{\r\n\t\t\tcontent.style.maxHeight = content.scrollHeight + \"px\";\r\n\t\t\t$('#chimchom2-descriptive').animate({scrollTop: jQuery(content).offset().top}, 200);\r\n\t\t}\r\n\r\n\t\tif(currentOpen !== null && currentOpen !== content){\r\n\t\tcurrentOpen.style.maxHeight = null;\r\n\t\t}\r\n\t}",
"function w3_close() {\n mySidebar.style.display = \"none\";\n }",
"collapsableId(){\n return Template.thought_panel.fn.collapsableId();\n }",
"function rerenderSidebar() {\n $.LoadingOverlay('show');\n\n setTimeout(function() {\n\n IBRSDK.renderAndCreateSidebar(\n Dashboard.ibrObject,\n document.getElementById('mainCanvas'),\n document.getElementById('layerList'),\n Dashboard.floorsToSave);\n if (document.getElementById('dwn-btn').getAttribute('listener')\n !== 'true') {\n document.getElementById('dwn-btn')\n .addEventListener('click', function() {\n download(\n document.getElementById('filename').value,\n Dashboard.ibrObject,\n Dashboard.floorsToSave);\n });\n document.getElementById('dwn-btn').setAttribute('listener', 'true');\n }\n }, 500);\n\n if (document.getElementById('mode').checked) {\n document.getElementById('dwn-btn').style.display = 'block';\n document.getElementById('filename').style.display = 'block';\n document.getElementById('export-inst').style.display = 'block';\n } else {\n document.getElementById('dwn-btn').style.display = 'none';\n document.getElementById('filename').style.display = 'none';\n document.getElementById('export-inst').style.display = 'none';\n }\n\n $.LoadingOverlay('hide');\n }",
"function open_sidebar() {\n if (mySidebar.style.display === 'block') {\n mySidebar.style.display = 'none';\n overlayBg.style.display = \"none\";\n } else {\n mySidebar.style.display = 'block';\n overlayBg.style.display = \"block\";\n }\n}",
"isSelfPaced() {\n return this.state.courseSidebar.self_paced\n }",
"function switchToFixedLayout() {\n layout = \"fixed\";\n var sidebarFull = $(\".left-sidebar-toplevel\").detach();\n $(\".sidebar-target-fixed\").prepend(sidebarFull);\n $(\".left-sidebar-toplevel\").removeClass(\"left-sidebar-collapsible\");\n $(\".left-sidebar-toplevel\").addClass(\"left-sidebar-fixed col-4 col-lg-4 col-xl-3 \");\n $(\".left-sidebar-togglebutton\").addClass(\"hide\");\n $(\".center-content\").addClass(\"col-8\");\n\t\t$(\".main-container-fixed\").css(\"margin-left\",\"auto\");\n\t\t$(\".center-content\").removeClass(\"col-12\");\n\t}",
"function collapsibleBlockTreeProcessor () {\n this.process((doc) => {\n for (const block of doc.findBy({ context: 'example' }, (candidate) => candidate.isOption('collapsible'))) {\n idAttr = block.getId() ? ` id=\"${block.getId()}\"` : ''\n classAttr = block.isRole() ? ` class=\"${block.getRole()}\"` : ''\n source_lines = []\n source_lines.push(`<details${idAttr}${classAttr}>`)\n if (block.hasTitle()) source_lines.push(`<summary class=\"title\">${block.getTitle()}</summary>`)\n source_lines.push('<div class=\"content\">')\n source_lines.push(block.getContent().split('\\n'))\n source_lines.push('</div>')\n source_lines.push('</details>')\n siblings = block.getParent().getBlocks()\n siblings[siblings.indexOf(block)] = this.createBlock(block.getParent(), 'pass', source_lines)\n }\n return doc\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays games based on specified platform | function output_sort_platform(result, platform){
window.scrollTo(0, 0);
let length = result.length;
let i = 0;
if(platform == "pc"){
platform = "PC (Windows)";
}
else{
platform = "Web Browser";
}
document.querySelector("main").innerHTML = "";
document.querySelector("main").style.display = "grid";
while(i < length){
if(platform == result[i].platform){
display_game(result[i]);
}
i += 1;
}
} | [
"function renderplat(){\n ctx.fillStyle = \"#8C158E\";\n platforms.forEach((platform) => {\n ctx.fillRect(platform.x, platform.y, platform.width, platform.height);\n })\n}",
"function renderplat(){\n for(var i=0; i<platforms.length;i++){\n ctx.fillStyle = platforms[i].color;\n ctx.fillRect(platforms[i].x, platforms[i].y, platforms[i].width, platforms[i].height);\n }\n}",
"function handlePlatforms() {\n\n for (var i = platforms.length - 1; i >= 0; i--) {\n\t\t// loop through platforms backward\n if (platforms[i].onScreen) {\n platforms[i].draw(player.loc.y);\n\t\t\tif (platforms[i] instanceof Doodler)\n\t\t\t\tplatforms[i].update(); // update Doodlers\n if (platforms[i].collidesWith(player)) {\n player.jump();\n if (platforms[i] instanceof Doodler) {\n\t\t\t\t\t// it's not a platform, but a doodler!\n points += 100;\n platforms.splice(i, 1); // remove from array\n }\n }\n } else {\n\n /* no longer on-screen, delete previous platforms */\n platforms.splice(i, 1);\n\t\t\t/* push new platform */\n var x = noise(player.maxA, frameCount) * width;\n var y = player.maxA + height;\n if (random() < 0.9) {\n\t\t\t\t// 90% chance of being a regular platform\n platforms.push(new Platform(x, y));\n } else {\n if (random() > 0.5) {\n\t\t\t\t\t// 5% chance of being a doodler\n\t\t\t\t\tplatforms.push(new Doodler(x, y, true));\n\t\t\t\t}\n\t\t\t\t// 5% chance of not regenerating\n }\n }\n }\n}",
"function output_games(result){\n let i = 0;\n let short_description = \"\";\n let title_length = 0;\n let j = 0;\n let font_size = \"28px\";\n window.scrollTo(0, 0);\n \n document.querySelector(\"main\").innerHTML = \"\";\n while(i < 50){\n \tdisplay_game(result[i]);\n i += 1;\n }\n}",
"function displayGameScreen()\n{\n\t\n\tdisplayResourceElement();\n\t\t\t\n\tdisplayInfoElement();\n\t\n\tdisplayMapElement();\n\t\n\tjoinGame();\n\t\n\tif(player.onTurn == true)\n\t{\n\t\tdisplayEndTurnElement(\"salmon\");\n\t\t\n\t\tdisplayTurnCounterElement(\"lightGreen\");\n\t}\n\telse\n\t{\n\t\tdisplayEndTurnElement(\"lightSlateGrey\");\n\t\n\t\tdisplayTurnCounterElement(\"salmon\");\n\t}\n\t\n\tgameStarted = true;\n\t\n\tstage.update();\n}",
"function renderGame() {\r\n\r\n // IF the lantern is not on, and not in a location with a light source, then player only sees the black!\r\n if (!bLanternInUse && mapLocation != 6 && mapLocation != 2 && mapLocation != 0) {\r\n screenImage.src = TheDark;\r\n gameMessage = \"It is pitch black. You can't see anything.\";\r\n console.log(\"in dark if. screenImage.src is: \" + screenImage.src);\r\n }\r\n else // lantern is on\r\n {\r\n // You can see! show image and discription\r\n screenImage.src = locationImages[mapLocation];\r\n output.innerHTML = map[mapLocation];\r\n\r\n\r\n var i = 0;\r\n //show items if they are there at this location\r\n for (i = 0; i < itemsInWorld.length; i++) {\r\n if (mapLocation === itemLocations[i]) {\r\n // display item\r\n output.innerHTML += \"<br> You see a <strong>\" + itemsInWorld[i] + \"</strong> here.\";\r\n }\r\n }// end for i\r\n }// end else lantern IS on\r\n\r\n // display game message \r\n output.innerHTML += \"<br> <em> \" + gameMessage + \" </em> \";\r\n\r\n\r\n // finally show players backpack contents:\r\n if (backpack.length != 0) {\r\n output.innerHTML += \"<br> You are carrying: \" + backpack.join(\",\");\r\n }\r\n\r\n console.log(\"at end of render. screenImage.src is: \" + screenImage.src);\r\n}// end renderGame",
"function displayGameplay() {\n image(backgroundImg, width / 2, height / 2, 1500, 800);\n\n // Handle input for the player\n player.handleInput();\n\n // Move all the supplies\n player.move();\n for (let i = 0; i < supply.length; i++) {\n supply[i].move();\n // Handle the bee eating any of the supply\n player.handleEating(supply[i]);\n supply[i].display();\n }\n\n //Display firstAid kit\n firstAid.move();\n firstAid.display();\n\n //Display battery\n battery.move();\n battery.display();\n\n // Handle the player collecting any of the supply\n player.handleEating(water);\n player.handleEating(food);\n player.handleCharging(battery);\n player.handleHealing(firstAid);\n\n //Check if the player is dead and to end game\n player.endGame();\n // Display the player\n player.display();\n\n //display the flashlight\n flashlight.display();\n\n // display health (health bar)\n healthBar.updateHealth(player.health);\n healthBar.display();\n\n //display flashlight battery (battery bar)\n batteryBar.updateBattery(player.batteryLevel);\n batteryBar.display();\n}",
"function init(game) {\n let createPlatform = platform.create;\n\n ////////////////////////////////////////////////////////////////////////\n // ALL YOUR CODE GOES BELOW HERE ///////////////////////////////////////\n \n /*\n * ground : here, we create a floor. Given the width of of the platform \n * asset, giving it a scaleX and scaleY of 2 will stretch it across the \n * bottom of the game.\n */\n createPlatform(0, game.world.height - 32, 3, 2); // DO NOT DELETE\n\n // example:\n createPlatform(100, 210, 0.6);\n createPlatform(100, 230, 0.6);\n createPlatform(100, 250, 0.6);\n createPlatform(100, 270, 0.6);\n createPlatform(100, 290, 0.6);\n createPlatform(100, 310, 0.6);\n createPlatform(100, 330, 0.6);\n createPlatform(100, 350, 0.6);\n createPlatform(100, 370, 0.6);\n createPlatform(100, 390, 0.6);\n createPlatform(100, 410, 0.6);\n createPlatform(100, 430, 0.6);\n createPlatform(100, 460, 0.6);\n createPlatform(100, 490, 0.6);\n createPlatform(100, 520, 0.6);\n createPlatform(100, 540, 0.6);\n createPlatform(100, 570, 0.9);\n createPlatform(100, 600, 0.6);\n createPlatform(100, 630, 0.6);\n createPlatform(100, 660, 0.6);\n\n createPlatform(300, 210, 0.6);\n createPlatform(300, 230, 0.6);\n createPlatform(300, 250, 0.6);\n createPlatform(300, 270, 0.6);\n createPlatform(300, 290, 0.6);\n createPlatform(300, 310, 0.6);\n createPlatform(300, 330, 0.6);\n createPlatform(300, 350, 0.6);\n createPlatform(300, 370, 0.6);\n createPlatform(300, 390, 0.6);\n createPlatform(300, 410, 0.6);\n createPlatform(300, 430, 0.6);\n createPlatform(300, 460, 0.6);\n createPlatform(300, 490, 0.6);\n createPlatform(300, 520, 0.6);\n createPlatform(300, 540, 0.6);\n createPlatform(300, 570, 0.9);\n createPlatform(300, 600, 0.6);\n createPlatform(300, 630, 0.6);\n createPlatform(300, 660, 0.6);\n\n createPlatform(500, 210, 0.6);\n createPlatform(500, 230, 0.6);\n createPlatform(500, 250, 0.6);\n createPlatform(500, 270, 0.6);\n createPlatform(500, 290, 0.6);\n createPlatform(500, 310, 0.6);\n createPlatform(500, 330, 0.6);\n createPlatform(500, 350, 0.6);\n createPlatform(500, 370, 0.6);\n createPlatform(500, 390, 0.6);\n createPlatform(500, 410, 0.6);\n createPlatform(500, 430, 0.6);\n createPlatform(500, 460, 0.6);\n createPlatform(500, 490, 0.6);\n createPlatform(500, 520, 0.6);\n createPlatform(500, 540, 0.6);\n createPlatform(500, 570, 0.9);\n createPlatform(500, 600, 0.6);\n createPlatform(500, 630, 0.6);\n createPlatform(500, 660, 0.6);\n\n createPlatform(700, 210, 0.6);\n createPlatform(700, 230, 0.6);\n createPlatform(700, 250, 0.6);\n createPlatform(700, 270, 0.6);\n createPlatform(700, 290, 0.6);\n createPlatform(700, 310, 0.6);\n createPlatform(700, 330, 0.6);\n createPlatform(700, 350, 0.6);\n createPlatform(700, 370, 0.6);\n createPlatform(700, 390, 0.6);\n createPlatform(700, 410, 0.6);\n createPlatform(700, 430, 0.6);\n createPlatform(700, 460, 0.6);\n createPlatform(700, 490, 0.6);\n createPlatform(700, 520, 0.6);\n createPlatform(700, 540, 0.6);\n createPlatform(700, 570, 0.9);\n createPlatform(700, 600, 0.6);\n createPlatform(700, 630, 0.6);\n createPlatform(700, 660, 0.6);\n // ALL YOUR CODe GOES ABOVE HERE ///////////////////////////////////////\n ///////////////////////////////////////////////////////////////////////\n }",
"render() {\n const results = this.state.regionalResults;\n\n if (results.errors === 0 && results.games.length) {\n return this._renderGames(results);\n } else if (results.errors) {\n return this._renderError();\n } else {\n return this._renderNothing();\n }\n }",
"function gameManager() {\n switch (game.gameMode) {\n case \"Classic\":\n {\n classic();\n break;\n }\n case \"Survival\":\n {\n survival();\n break;\n }\n case \"TimeAttack\":\n {\n ui.showUI(\"TimeAttackUI\");\n timeAttack();\n break;\n }\n }\n}",
"function displayWin (condition) {\n if (condition < 2) {\n boardScreen.style.display = 'none';\n winScreen.style.display = '';\n winScreen.classList.remove('screen-win-one');\n winScreen.classList.remove('screen-win-two');\n winScreen.classList.remove('screen-win-tie');\n if (condition === 1) {\n winScreen.classList.add('screen-win-one');\n message.textContent = `Player 1: ${game1.player1} Wins!`\n } else if (condition === -1) {\n winScreen.classList.add('screen-win-two');\n message.textContent = `Player 2: ${game1.player2} Wins!`\n } else {\n winScreen.classList.add('screen-win-tie');\n message.textContent = `Tie Game!`\n }\n }\n }",
"function platform_init() {\r\n\tplatform.push(new Platform(0, 400, 400, 0, 0));\r\n\t\tvar plat_num = 0;\r\n\t\tvar plat_y = 400;\r\n\t\tvar plat_x = Math.floor(Math.random()*300);\r\n\t\twhile (plat_num < 10) {\r\n\t\t\tvar next_plat_y = Math.floor(Math.random()*35) + 50;\r\n\t\t\tplat_y -= next_plat_y;\r\n horiz = Math.min(canvas.width - (plat_x + 200), Math.min(plat_x, Math.random() * 300));\r\n if (horiz < 5) {\r\n horiz = 0;\r\n }\r\n\t\t\tplatform.push(new Platform(plat_x, plat_y, 100, horiz, 0));\r\n\t\t\tvar next_plat_x = Math.floor(Math.random()*150);\r\n\t\t\tif(plat_num % 2 === 1)\r\n\t\t\t\tnext_plat_x += 150;\r\n\t\t\tplat_x = next_plat_x;\r\n\t\t\tif (plat_x > 300 || plat_x < 0)\r\n\t\t\t\tplat_x = Math.floor(Math.random()*200) + Math.floor(Math.random()*100);\r\n\t\t\tplat_num++;\r\n\t\t}\r\n}",
"function createGamePage() {\n var gamePage = document.createElement('main');\n gamePage.classList.add('game-board');\n gamePage.innerHTML = getGamePageStructure();\n body.appendChild(gamePage);\n showRecentGames(deck.player.name, '.win-game-list-one');\n}",
"static show()\n {\n let aeComputers = Component.getElementsByClass(document, PCx86.APPCLASS, \"computer\");\n for (let iComputer = 0; iComputer < aeComputers.length; iComputer++) {\n let eComputer = aeComputers[iComputer];\n let parmsComputer = Component.getComponentParms(eComputer);\n let computer = /** @type {Computer} */ (Component.getComponentByType(\"Computer\", parmsComputer['id']));\n if (computer) {\n\n /*\n * Clear new flag that Component functions (eg, notice()) should check before alerting the user.\n */\n computer.flags.unloading = false;\n\n if (DEBUG) computer.printf(\"onShow(%b,%b)\\n\", computer.flags.initDone, computer.flags.powered);\n\n if (computer.flags.initDone && !computer.flags.powered) {\n /*\n * Repower the computer, notifying every component to continue running as-is.\n */\n computer.powerOn(Computer.RESUME_REPOWER);\n }\n }\n }\n }",
"function buildLayout(mode) {\n if (mode === \"Portuguese\") {\n document.getElementById(\"language\").innerHTML = '<p><img src=\"assets/images/portugal.png\" alt=\"Portugal\"> <br> Portuguese</p>';\n } else if (mode === \"Swedish\") {\n document.getElementById(\"language\").innerHTML = '<p><img src=\"assets/images/sweden.png\" alt=\"Sweden\"> <br> Swedish</p>';\n } else if (mode === \"French\") {\n document.getElementById(\"language\").innerHTML = '<p><img src=\"assets/images/france.png\" alt=\"France\"> <br>French</p>';\n } else if (mode === \"German\") {\n document.getElementById(\"language\").innerHTML = '<p><img src=\"assets/images/germany.png\" alt=\"Germany\"> <br> German</p>';\n } else if (mode === \"Random\") {\n document.getElementById(\"language\").innerHTML = '<p><img src=\"assets/images/globe.png\" alt=\"world\"> <br> Random</p>';\n }\n fetchWords();\n}",
"function createplat(){\n platforms.push(\n {\n x: 0,\n y: 200,\n width: 200,\n height: 15\n },\n {\n x: 100,\n y: 300,\n width: 200,\n height: 15\n },\n {\n x: 300,\n y: 200,\n width: 200,\n height: 15\n },\n {\n x: 550,\n y: 300,\n width: 200,\n height: 15\n },\n {\n x: 700,\n y: 250,\n width: 270,\n height: 15\n }\n );\n\n }",
"updateHostList() {\n\t\tlet joinableGames = new Map();\n\t\tfor (var [socketID, game] of this.games) {\n\t\t\tif (game && !game.isPlaying && game.players.length < Game.maxPlayers) {\n\t\t\t\tjoinableGames.set(game.id, game.getInfo());\n\t\t\t}\n\t\t}\n\t\tthis.io.to('lobby').emit(ActionNames.UPDATE_HOST_LIST, [...joinableGames.values()].sort((a, b) => {\n\t\t\treturn a.id - b.id;\n\t\t}));\n\t}",
"function playGame() {\n\tcomputerSelect();\n\tif (humanSelect == \"paper\" || humanSelect == \"scissors\" || humanSelect == \"rock\") {\n\t\tplay(humanSelect,computerSelection);\n\t\t$('#bot').attr('src','images/' + computerSelection + '.png');\n\t\t// the bot selection image doesn't show tried use delay so you would see it for a bit\n\t\t// before showing the score\n\t\t$('#outcome').text(result);\n\t\t$('#score').text(\"Score is: \" + humanScore + \" to \" + computerScore);\n\t\t}\n\t}",
"function displayGame(){\n gameType.style.display ='none';\n gamePlay.style.display ='block';\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the exchange isMeeting of this event readonly attribute boolean isMeeting; | get isMeeting()
{
return this._isMeeting;
} | [
"get meetingRequestWasSent()\n\t{\n\t\treturn this._meetingRequestWasSent;\n\t}",
"get reminderIsSet()\n\t{\n\t\treturn this._reminderIsSet;\n\t}",
"function setAlarm(employed, vacation){\n return !vacation && employed ? true : false;\n}",
"get meetingTimeZone()\n\t{\n\t\treturn this._meetingTimeZone;\n\t}",
"isLockedWork() {\n let userId = userService.getLoggedId();\n let attendance = attendanceService.getAttendance(workToEdit.idAttendance);\n if(!attendance || !attendance.approved)\n return false;\n return true;\n }",
"function shouldShowEvent(event) {\n\n // Hack to remove canceled Office 365 events.\n if (event.title.startsWith(\"Canceled:\")) {\n return false\n }\n\n // If it's an all-day event, only show if the setting is active.\n if (event.isAllDay) {\n return showAllDay\n }\n\n // Otherwise, return the event if it's in the future.\n return (event.startDate.getTime() > date.getTime())\n}",
"get allowNewTimeProposal()\n\t{\n\t\treturn this._allowNewTimeProposal;\n\t}",
"function isEventEditable(event) {\n if (!event || !event.calendarId) {\n return;\n }\n\n findEventOrganizer(event);\n\n var calendarsManager = enyo.application.calendarsManager,\n isWriteable = !calendarsManager.isCalendarReadOnly(event.calendarId),\n attendees = getActiveAttendees(event),\n numAttendees = attendees && attendees.length,\n organizer = numAttendees && event.organizer,\n accountUserName = numAttendees && calendarsManager.getCalAccountUser(event.calendarId),\n organizerEmail = organizer && organizer.email && organizer.email.toLowerCase(),\n youAreOrganizer = organizerEmail && accountUserName && organizerEmail == accountUserName.toLowerCase();\n\n return isWriteable && (!numAttendees || youAreOrganizer);\n }",
"get atWork () {\n return this.room.name === this._mem.rooms.work;\n }",
"function Meeting(xmlObj, day) {\r\n this.day = day;\r\n this.starttime = new Time(xmlObj.getAttribute(\"StartTime\"));\r\n this.endtime = new Time(xmlObj.getAttribute(\"EndTime\"));\r\n this.site = xmlObj.getAttribute(\"Site\"); // This may be unnecessary\r\n this.building = xmlObj.getAttribute(\"Building\");\r\n this.room = xmlObj.getAttribute(\"Room\");\r\n this.activity = xmlObj.getAttribute(\"Activity\");\r\n\r\n this.checkConflict = function (otherMeeting) {\r\n if (otherMeeting.day !== this.day || otherMeeting.starttime.hour === null) {\r\n return false;\r\n }\r\n if (otherMeeting.starttime.compareTo(this.starttime) >= 0 &&\r\n this.endtime.compareTo(otherMeeting.starttime) >= 0) {\r\n return true;\r\n }\r\n if (this.starttime.compareTo(otherMeeting.starttime) >= 0 &&\r\n otherMeeting.endtime.compareTo(this.starttime) >= 0) {\r\n return true;\r\n }\r\n return false;\r\n };\r\n }",
"isTakeoff() {\n return this.flightPhase === FLIGHT_PHASE.TAKEOFF;\n }",
"isElementShowing(e) {\n return this.props.time >= e.start_time &&\n this.props.time <= e.end_time;\n }",
"get isMutable()\n\t{\n\t\t//dump(\"get isMutable: title:\"+this.title+\", value:\"+this._calEvent.isMutable);\n\t\treturn this._isMutable;\n\t}",
"function ServerBehavior_getIsIncomplete()\n{\n return this.incomplete;\n}",
"async sync() {\n // Update event on meetup if it is published and\n if (!this.draft && !this.internal) {\n if (this.meetupId) {\n // Update it on Meetup.com if it exists\n await meetup.update(this)\n } else {\n // Create on Meetup.com\n const id = await meetup.create(this)\n //this.save({ meetupId: id })\n }\n }\n }",
"function checkEvent(element) {\n if (new Date(element.attr('seminar-date')) >= currentDate) {\n upcomingSeminar = true;\n } else {\n previousSeminar = true;\n }\n }",
"function _checkIfAnyEventsOnDate(date) {\r\n var fullCalEvents = $fullCal.fullCalendar(\"clientEvents\");\r\n for (var i=0; i<fullCalEvents.length; i++) {\r\n var start = moment(fullCalEvents[i].start);\r\n var eventDate = start.format(DATE_FORMAT);\r\n if (date == eventDate && !fullCalEvents[i].isNote) { return true; }\r\n }\r\n return false;\r\n }",
"function getProtoEligibles(event) {\r\n var date = event.data.date;\r\n var $scheduleClicked = $(\".fc-event-clicked\");\r\n // Ensure a day has been clicked and no schedule currently clicked\r\n if (date && !$scheduleClicked.length) {\r\n var startTime = $(\"#start-timepicker\").val();\r\n var endTime = $(\"#end-timepicker\").val();\r\n $.get(\"get_proto_schedule_info\",\r\n {add_date: date, department: calDepartment, start_time: startTime, end_time: endTime},\r\n displayProtoEligables);\r\n }\r\n }",
"isLocalOnHold() {\n if (this.state !== CallState.Connected) return false;\n if (this.unholdingRemote) return false;\n let callOnHold = true; // We consider a call to be on hold only if *all* the tracks are on hold\n // (is this the right thing to do?)\n\n for (const tranceiver of this.peerConn.getTransceivers()) {\n const trackOnHold = ['inactive', 'recvonly'].includes(tranceiver.currentDirection);\n if (!trackOnHold) callOnHold = false;\n }\n\n return callOnHold;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decreases the given `interval` to match the last possible time that coincides with the unit of the given interval, if any. Like if the interval is an exact number of days, this yields the milliseconds until some next day (local time), and when called just before midnight the returned interval might be quite small. Likewise this detects multiples of hours, 30 minutes, 15 minutes, 10 minutes, 5 minutes, 1 minute, 30 seconds, 15 seconds, 10 seconds, 5 seconds and a single second. If no unit is detected, this just returns the given interval. But as, e.g., 11 minutes will be matched as a multiple of 1 minute, and 62 seconds as a multiple of 1 second, such will only happen when explicitly passing an interval that cannot be rounded to a second. | _minimizeInterval(interval) {
const unit = [24 * 3600, 3600, 30 * 60, 15 * 60, 10 * 60, 5 * 60, 60, 30, 15, 10, 5, 1].find(s => interval % (s * 1000) === 0) * 1000;
if (!unit) {
return interval;
}
const utc = new Date();
// Ensure daily reports start at midnight in the local timezone
const now = utc.getTime() - (utc.getTimezoneOffset() * 60 * 1000);
const next = Math.floor((now + interval) / unit) * unit;
return next - now;
} | [
"_firstTick(interval, tickPeriod) {\n const time = interval.start;\n var period = tickPeriod.value;\n var unit = tickPeriod.unit;\n\n var roundedTime = time.clone().startOf(unit);\n if (!roundedTime.isSame(time)) {\n roundedTime.add(1, unit);\n }\n if (unit === 'h' || unit === 'M') {\n return roundedTime.set(unit, \n Math.ceil(roundedTime.get(unit) / period) * period);\n } else {\n let offset = roundedTime.diff(this._tickReferenceTime, unit) % period;\n if (offset < 0) {\n offset += period;\n }\n if (offset === 0) {\n return roundedTime;\n }\n return roundedTime.add(period - offset, unit);\n }\n }",
"function getIntervalNote(note, interval) {\n\tvar relative = getNote(note);\n\tvar octave = getOctave(note);\n\trelative += interval - 1;\n\twhile (relative >= 8) {\n\t\trelative -= 7;\n\t\toctave += 1;\n\t}\n\n\treturn toNote(relative, octave);\n\n}",
"function getFirstIntervalDelay () {\n\t\tvar now = Date.now();\n\t\tvar queryInterval = queryForecastFreqHrs * 60 * 60 * 1000;\n\t\tvar sinceLastInterval = now % queryInterval;\n\t\treturn (queryInterval - sinceLastInterval + (config.queryDelaySecs * 1000));\t\t\n\t}",
"getTimeIntervalInfo(fromValue, toValue) {\n // Get and parse from and to\n // using ISO_8601 time intervals\n // https://en.wikipedia.org/wiki/ISO_8601#Time_intervals\n\n let from = null;\n let to = null;\n\n let currentTimeMs = Date.now();\n to = currentTimeMs; // Current time by default\n let toStr = toValue;\n if (toStr !== 'now') {\n let parsedTo = parseInt(toStr);\n if (!Number.isNaN(parsedTo)) {\n to = parsedTo;\n }\n }\n\n let fromStr = fromValue;\n let dms = 5 * 60 * 1000;\n if (fromStr.startsWith('P')) {\n // Attempt to process as ISO_8601 time interval\n let d = moment.duration(fromStr);\n if (d.isValid()) {\n dms = d.asMilliseconds();\n }\n from = to - dms;\n } else {\n let parsedFrom = parseInt(fromStr);\n from = Number.isNaN(parsedFrom) ? to - dms : parsedFrom;\n }\n\n let duration = to - from;\n return { tiFrom: from, tiTo: to, tiDuration: duration };\n }",
"function calcTarget(duration, interval, vehicles, capacity) {\r\r\n var time = 60 * 60;\r\r\n var runTime = duration + interval;\r\r\n var full = capacity * vehicles;\r\r\n var target = Math.floor(time / runTime * full);\r\r\n return target;\r\r\n}",
"function setIntervalReal() {\r\n intervalReal = (1 / speed) * interval;\r\n }",
"callDurationCalculator(duration){\n let totalSeconds = parseInt(duration); \n let minute = 0;\n if(totalSeconds < 60){\n return duration+' seconds';\n }else{\n while(totalSeconds > 60){\n minute += 1; \n totalSeconds -= 60\n }\n\n let _duration = minute+':'+totalSeconds+ ' seconds';\n return(_duration);\n }\n }",
"function captureMetrics(endpoint, interval, metadata) {\n console.log('Streaming metrics to: ' + endpoint + ' every ' + interval + ' ms'); //eslint-disable-line no-console\n\n const endpoint_client = client.create(endpoint);\n let last_fork = 0;\n\n // The idea here is that we want to segment all of time into intervals,\n // each with a duration of 'interval' in milliseconds, so that we can\n // pick any moment in time and assign it to an interval. If multiple\n // machines are using the same interval size and their clocks are\n // synchronized, segment time in the exact same way.\n //\n // Each time we receive a new metric, if we have not already done so,\n // we schedule a collection event for the end of the current interval.\n return metrics_target => {\n const now = Date.now();\n const start = getIntervalStart(now,interval);\n const end = getIntervalEnd(now,interval);\n const in_future = end - now;\n\n if( start <= last_fork )\n return Promise.resolve();\n\n // everything below this line is running at most once every 'interval' milliseconds\n\n last_fork = start;\n\n // Now we run on a delay, scheduling for the end of this interval.\n delay(in_future)\n .then(() => metrics_target.clear())\n .then(summary => {\n if( summary )\n return endpoint_client.postMetrics({ data : summary, metadata : Object.assign({}, metadata, { min_timestamp : start, max_timestamp : end }) });\n }).then(() => {}).catch(err => {\n console.error('problem reporting metrics ' + err); //eslint-disable-line no-console\n return {};\n });\n };\n}",
"function clear_interval(t) {\n\tvar interval = parseInt(t.data(\"interval\"));\n\tif (interval > 0) {\n\t\tclearInterval(interval);\n\t\tt.data(\"interval\", \"\");\n\t}\n}",
"function getLastCompatibleExternalDrawable( interval ) {\n const firstDrawable = interval.drawableAfter;\n\n if ( firstDrawable ) {\n const renderer = firstDrawable.renderer;\n\n // we stop our search before we reach this (null is acceptable), ensuring we don't go into the next change interval\n const cutoffDrawable = interval.nextChangeInterval ? interval.nextChangeInterval.drawableBefore.nextDrawable : null;\n\n let drawable = firstDrawable;\n\n while ( true ) { // eslint-disable-line no-constant-condition\n const nextDrawable = drawable.nextDrawable;\n\n // first comparison also does null check when necessary\n if ( nextDrawable !== cutoffDrawable && nextDrawable.renderer === renderer ) {\n drawable = nextDrawable;\n }\n else {\n break;\n }\n }\n\n return drawable;\n }\n else {\n return null; // with no drawableAfter, we don't have any external drawables after our interval\n }\n}",
"function get_time_allowed_msec(){\n var fpscript = document.getElementById('__fp_bp_is');\n var interval_sec = TIME_ALLOWED_SEC;\n\n if (fpscript){\n if (fpscript.dataset.interval_sec){\n interval_sec = fpscript.dataset.interval_sec;\n }\n }\n console.log(\"=> interval_sec=\", interval_sec);\n\n var interval_msec = (interval_sec * 1000);\n return interval_msec;\n }",
"_ticks(interval) {\n // We use the first interval passed to the XAxis object to initialize\n // this._timeZone and this._tickReferenceTime, to avoid needing to pass a\n // timeZone to the constructor.\n if (!this._timeZone) {\n this._timeZone = interval.start.tz();\n this._tickReferenceTime = interval.start.clone().startOf('year');\n }\n\n var tickOpts = this._tickOptions();\n var ticks = [];\n var tick = this._firstTick(interval, tickOpts.period);\n while (tick.isSameOrBefore(interval.end)) {\n ticks.push(+tick);\n if (tickOpts.period.unit === 'h' && tickOpts.period.value > 1) {\n var hours = tick.hours();\n hours += tickOpts.period.value;\n if (hours >= 24) tick.add(1, 'd');\n tick.hours(hours % 24);\n } else {\n tick.add(tickOpts.duration);\n }\n }\n return {\n params: tickOpts,\n ticks: ticks,\n };\n }",
"function startInterval(){\n /* Run the interval every seconde */\n var interval = setInterval(fn60sec,1000);\n /* Run the interval every minute */\n //interval = setInterval(fn60sec, 60 * 1000);\n }",
"function limitedInterval(callback, waitTime, limitTime){\n let checkTime = 0;\n setInterval(() => {\n checkTime += waitTime;\n if(checkTime < limitTime){ \n callback();\n } else {\n clearInterval();\n }\n }, waitTime);\n}",
"static calculateDuration (duration) {\n let seconds = duration * 15\n let days = Math.floor(seconds / (3600 * 24))\n seconds -= days * 3600 * 24\n let hrs = Math.floor(seconds / 3600)\n seconds -= hrs * 3600\n let mnts = Math.floor(seconds / 60)\n seconds -= mnts * 60\n const response = days + ' days, ' + hrs + ' Hrs, ' + mnts + ' Minutes, ' + seconds + ' Seconds'\n return response\n }",
"function addIntervalToDate(due, count, unit) {\n let days = 0;\n let months = 0;\n switch (unit) {\n case \"b\":\n // add \"mul\" business days, defined as not Sat or Sun\n {\n let incr = (count >= 0)? 1: -1;\n let bdays_left = count * incr;\n let millisec_due = due.getTime();\n let day_of_week = due.getDay(); // 0=Sunday, 1..5 weekday, 6=Saturday\n while (bdays_left > 0) {\n millisec_due += 1000 * 60 * 60 * 24 * incr; // add a day to time\n if (incr > 0) {\n day_of_week = (day_of_week < 6 ? day_of_week + incr : 0);\n } else {\n day_of_week = (day_of_week > 0 ? day_of_week + incr : 6);\n }\n if (day_of_week > 0 && day_of_week < 6) {\n bdays_left--; // one business day step accounted for!\n }\n }\n return new Date(millisec_due);\n }\n case \"d\":\n days = 1;\n break;\n case \"w\":\n days = 7;\n break;\n case \"m\":\n months = 1;\n break;\n case \"y\":\n months = 12;\n break;\n }\n if (months > 0) {\n let due_month = due.getMonth() + count * months;\n let due_year = due.getFullYear() + Math.floor(due_month/12);\n due_month = due_month % 12;\n let monthlen = new Date(due_year, due_month+1, 0).getDate();\n let due_day = Math.min(due.getDate(), monthlen);\n return new Date(due_year, due_month, due_day);\n }\n due = due.getTime();\n due += 1000 * 60 * 60 * 24 * count * days;\n return new Date(due);\n}",
"updateIntervals(prevProps){\n const {\n intervalCurrentTime,\n intervalDuration,\n intervalSecondsLoaded\n } = this.props;\n\n // Update interval of current time\n if (typeof this.handleCurrentTime === 'undefined' ||\n prevProps.intervalCurrentTime !== intervalCurrentTime){\n clearInterval(this.handleCurrentTime);\n this.handleCurrentTime = setInterval(\n this.updateCurrentTime,\n intervalCurrentTime\n );\n }\n if (typeof this.handleDuration === 'undefined' ||\n prevProps.intervalDuration !== intervalDuration){\n clearInterval(this.handleDuration);\n this.handleDuration = setInterval(\n this.updateDuration,\n intervalDuration\n );\n }\n if (typeof this.handleSecondsLoaded === 'undefined' ||\n prevProps.intervalSecondsLoaded !== intervalSecondsLoaded){\n clearInterval(this.handleSecondsLoaded);\n this.handleSecondsLoaded = setInterval(\n this.updateSecondsLoaded,\n intervalSecondsLoaded\n );\n }\n }",
"getNextTime (step, time) {\n\t\tlet ret = this.getStepTime(step);\n\t\tlet totalTime = this.getTotalInterval() * 60 * 1000;\n\t\twhile (ret < time)\n\t\t\tret += totalTime;\n\t\treturn ret;\n\t}",
"function validInterval ( interval_name )\n {\n\tif ( typeof interval_name != \"string\" )\n\t return false;\n\t\n\tif ( api_data.interval[interval_name.toLowerCase()] )\n\t return true;\n\t\n\telse\n\t return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
related to: eventManager makeEventManager() > eventManager Makes an event manager. The manager creates and references event lists (see [[makeEventList]]) based on a name. | function makeEventManager() {
var manager = {};
var list = {};
/**
* eventManager.get(name) -> eventList
* - name (String): Name of the event list.
*
* Gets an [[eventList]] for the given `name`. If there is no
* [[eventList]] for that `name`, one is created.
*
* var manager = makeEventManager();
* manager.get("one"); // -> eventList "one"
* manager.get("one"); // -> eventList "one" again
* manager.get("two"); // -> eventList "two"
*
**/
function get(name) {
if (!list[name]) {
list[name] = makeEventList();
}
return list[name];
}
util.Object.assign(manager, {
get: get
});
return Object.freeze(manager);
} | [
"function get(name) {\n\n if (!list[name]) {\n list[name] = makeEventList();\n }\n\n return list[name];\n\n }",
"async function createManager() {\n const newManager = await new Manager();\n await newManager.getOfficeNumber();\n await manager.push(newManager);\n await generatorQs();\n}",
"addEventListener(evtName, callback) {\n //lazily create the listener collections\n this.__listeners = this.__listeners || {};\n this.__listeners[evtName] = this.__listeners[evtName] || [];\n if (!this.__listeners[evtName].includes(callback))\n this.__listeners[evtName].push(callback);\n return this;\n }",
"createCommandManager() {\n this.commandManager = new CommandManager({\n editor: this,\n });\n }",
"function CommandOutputManager() {\n this._event = createEvent('CommandOutputManager');\n}",
"runEvent(name) {\n let event = this._events[name];\n if (event) {\n event();\n }\n }",
"registerEvents() {\n\t\t\tthis.container = this.getContainer();\n\t\t\tthis.registerListEvents();\n\t\t\tthis.registerForm();\n\t\t}",
"static getInstance(emitterName = \"\") {\r\n if (!AriEventEmitter.instances[emitterName])\r\n AriEventEmitter.instances[emitterName] = new AriEventEmitter();\r\n return AriEventEmitter.instances[emitterName];\r\n }",
"function menuEvents () {\n\n\t\tvar chooseLibrary = document.getElementById('choose-library');\n\t\tvar viewArtists = document.getElementById('view-artists');\n\t\tvar viewAlbums = document.getElementById('view-albums');\n\t\tvar viewSongs = document.getElementById('view-songs');\n\n\t\tchooseLibrary.addEventListener('click', emitEvent('menu: choose-lib'));\n\t\tviewArtists.addEventListener('click', emitEvent('menu: artists'));\n\t\tviewAlbums.addEventListener('click', emitEvent('menu: albums'));\n\t\tviewSongs.addEventListener('click', emitEvent('menu: songs'));\n\n\t}",
"function SceneManager()\n {\n EventEmitter.call(this);\n this.meshes = {};\n } // end SceneManager",
"_initEvent() {\n this.eventManager.listen('hide', this.hide.bind(this));\n this.eventManager.listen('show', this.show.bind(this));\n }",
"function createNewManager (data, managerData) {\n var myNewManager = new Manager(data.id, data.name, data.email, managerData.officeNumber);\n productionTeam.push(myNewManager);\n console.log('Production Team', productionTeam);\n // prompts add another question function to see whether they want to add another or stop\n addAnother();\n}",
"_createEvents(prefix, events) {\n for(let eventName in events) {\n events[eventName] = new Event(prefix + '_' + eventName, this);\n }\n }",
"function updateEvents(eventsNames) {\n\t\t\tfor (var i=0; i<events.length; i++) {\n\t\t if ( hasEvent(eventsNames, events[i].name)) {\n\t\t markEvent(i);\n\t\t }\n\t\t else {\n\t\t fadeEvent(i);\n\t\t }\n\t\t }\n\t\t}",
"createEvents() {\n this.slider.addEventListener(this.deviceEvents.down, this.eventStartAll);\n window.addEventListener('resize', this.eventResize);\n }",
"function iglooDropdownManager () {\n\tthis.dropdowns = [];\n\n\tthis.add = function (dropdown) {\n\t\tthis.dropdowns.push(dropdown);\n\t};\n\n\tthis.opened = function (name) {\n\t\tvar drops = this.dropdowns;\n\n\t\tfor (var i = 0; i < drops.length; i++) {\n\t\t\tif (drops[i].name !== name) drops[i].close();\n\t\t}\n\t};\n}",
"initDomEvents() {\n const me = this;\n\n // Set thisObj and element of the configured listener specs.\n me.scheduledBarEvents.element = me.schedulerEvents.element = me.timeAxisSubGridElement;\n me.scheduledBarEvents.thisObj = me.schedulerEvents.thisObj = me;\n\n // same listener used for different events\n EventHelper.on(me.scheduledBarEvents);\n EventHelper.on(me.schedulerEvents);\n }",
"function WindowManager() {\n if (window_manager_ == null) {\n window_manager_ = new WindowManagerImpl(document.getElementById(\"data_windows\"),\n document.getElementById(\"window_menu\"));\n }\n return window_manager_;\n}",
"createPlayerManagers() {\n dg(`creating 4 player managers`, 'debug')\n for (let i = 0; i < 4; i++) {\n let player = new PlayerManager(i, this)\n player.init()\n this._playerManagers.push(player)\n this._playerManagers[0].isTurn = true\n }\n dg('player managers created', 'debug')\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove entity attribute from microdata list | onAttrRemove (attrName, entName) {
if (this.entityAttrsUse.length <= 0) return // microdata list already empty
if (!attrName || !entName) {
console.warn('Unable to remove from microdata list, attribute or entity name is empty:', attrName, entName)
return
}
const name = entName + '.' + attrName
this.$q.notify({ type: 'info', message: this.$t('Exclude from microdata') + ': ' + name })
this.entityAttrsUse = this.entityAttrsUse.filter(ean => ean !== name)
this.refreshEntityTreeTickle = !this.refreshEntityTreeTickle
} | [
"function removeCustomAttribute(customAttribute) {\n if (!(customAttribute in customQualificationData)) {\n return;\n }\n delete customQualificationData[customAttribute];\n displayCustomAttributes();\n}",
"function remove () {\n for (let key in currAttrs) {\n if (!nextAttrs[key]) {\n dom.removeAttribute(key);\n delete dom.__attrs[key]\n }\n }\n }",
"remove() {\n const ownerElement = this.node.ownerElement\n if(ownerElement) {\n ownerElement.removeAttribute(this.name)\n }\n }",
"function removeAttributeOfElement(attributeName,ElementXpath)\n {\n var alltags = document.evaluate(ElementXpath,document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);\n for (i=0; i<alltags.snapshotLength; i++)\n alltags.snapshotItem(i).removeAttribute(attributeName); \n }",
"onAttrAdd (attrName, entName, isAllowHidden) {\n if (this.entityAttrsUse.length >= this.entityAttrCount) return // all attributes already in microdata list\n if (!attrName || !entName) {\n console.warn('Unable to add microdata, attribute or entity name is empty:', attrName, entName)\n return\n }\n\n // add into microdata list if entity.attribute not in the list already\n const name = entName + '.' + attrName\n let isAdded = false\n if (this.entityAttrsUse.indexOf(name) < 0) {\n this.entityAttrsUse.push(name)\n isAdded = true\n }\n\n if (isAdded) {\n this.$q.notify({\n type: 'info',\n message: this.entityAttrsUse.length < this.entityAttrCount ? this.$t('Add to microdata') + ': ' + name : this.$t('All entity attributes included into microdata')\n })\n this.refreshEntityTreeTickle = !this.refreshEntityTreeTickle\n }\n }",
"function removeItemPropeties (data) {\n\tdelete data.name;\n\tdelete data.type;\n\tdelete data.external_id;\n\n\tfor (var key in data) {\n\t\tif (key.startsWith('sitemap_locations')) {\n\t\t\tdelete data[key];\n\t\t} \n\t}\n\n\treturn data;\n}",
"onEntityAdd (entName, parts, isAllowHidden) {\n if (this.entityAttrsUse.length >= this.entityAttrCount) return // all attributes already in microdata list\n if (!entName) {\n console.warn('Unable to add microdata, entity name is empty:', entName)\n return\n }\n\n // add each attribute of the entity into microdata if not already in the list\n const ent = Mdf.entityTextByName(this.theModel, entName)\n let isAdded = false\n\n if (Mdf.isNotEmptyEntityText(ent)) {\n for (const ea of ent.EntityAttrTxt) {\n if (!isAllowHidden && ea.Attr.IsInternal) continue // internal attributes disabled\n\n const name = entName + '.' + ea.Attr.Name\n if (this.entityAttrsUse.indexOf(name) < 0) {\n this.entityAttrsUse.push(name)\n isAdded = true\n }\n }\n }\n\n if (isAdded) {\n this.$q.notify({\n type: 'info',\n message: (this.entityAttrsUse.length < this.entityAttrCount) ? this.$t('Add to microdata') + ': ' + entName : this.$t('All entity attributes included into microdata')\n })\n this.refreshEntityTreeTickle = !this.refreshEntityTreeTickle\n }\n }",
"function cleanup(a) {\n return _.filter(a, function (a) {\n var field = a[0];\n return attr[field];\n });\n }",
"function removeFields(feature,fields) {\n if (typeof(fields) != \"undefined\" && fields != \"\" && feature.attributes) {\n var fieldsarr = fields.split(\",\");\n var remFlds = [];//array to hold fields to remove from object\n for (var n in feature.attributes) {\n if (fieldsarr.indexOf(n) == -1) remFlds.push(n);\n }\n for (var m = 0; m < remFlds.length; m++) feature.attributes[remFlds[m]] = null;\n }\n}",
"[_delistFromMeta] () {\n const top = this.top\n const root = this.root\n\n root.inventory.delete(this)\n if (root.meta)\n root.meta.delete(this.path)\n\n // need to also remove from the top meta if that's set. but, we only do\n // that if the top is not the same as the root, or else we'll remove it\n // twice unnecessarily. If the top and this have different roots, then\n // that means we're in the process of changing this.parent, which sets the\n // internal _parent reference BEFORE setting the root node, because paths\n // need to be set up before assigning root. In that case, don't delist,\n // or else we'll delete the metadata before we have a chance to apply it.\n if (top.meta && top !== root && top.root === this.root)\n top.meta.delete(this.path)\n }",
"removeUserAttribute(key) {\n if (!key || typeof key !== 'string')\n throw new TypeError('Invalid param, Expected String');\n Instabug.removeUserAttribute(key);\n }",
"removeNonEnTags(){\r\n\t\tif (this.data.hasOwnProperty(\"tags\")){\r\n\t\t\tvar tagsStr = \"\";\r\n\t\t\tvar tagsArray = this.data.tags.tags;\r\n\t\t\tfor (var i = 0; i < tagsArray.length; i++){\r\n\t\t\t\tif(tagsArray[i].hasOwnProperty(\"translation\")){\r\n\t\t\t\t\tif(tagsArray[i].translation.hasOwnProperty(\"en\")){\r\n\t\t\t\t\t\ttagsStr = tagsStr.concat(\"(\" + tagsArray[i].translation.en + \")\");\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tconsole.log(tagsStr);\r\n\t\t\tthis.macro.tags = tagsStr;\r\n\t\t} else {\r\n\t\t\tthis.macro.tags = \"\";\r\n\t\t}\r\n\t}",
"function dataCleanUp(data,type){\n\t\tif(type == 'places'){\n\t\t\tfor (var i = 0; i < data.features.length; i++) { /*[1]*/\n\t\t\t\tvar feature = data.features[i];\n\t\t\t\tif(feature.properties.tags.constructor !== Array){/*[2]*/\n\t\t\t\t\tvar tagsAarray = feature.properties.tags.split(',');\n\t\t\t\t\tfeature.properties.tags = tagsAarray;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn data;\n\t}",
"function cleanElementData(field, key) {\n if (field) {\n var dataField = \"data-tworeceipt-\" + field + \"-search\";\n if (key) {\n dataField += \"='\" + key + \"'\";\n }\n var elements = $(\"[\" + dataField + \"]\");\n for (var index = 0; index < elements.length; index++) {\n elements.eq(index).removeAttr(dataField);\n }\n delete searchTerms[field];\n\n } else {\n var keys = Object.keys(searchTerms);\n for (var i = 0; i < keys.length; i++) {\n var field = keys[i];\n\n var dataField = \"data-tworeceipt-\" + field + \"-search\";\n var elements = $(\"[\" + dataField + \"]\");\n for (var index = 0; index < elements.length; index++) {\n elements.eq(index).removeAttr(dataField);\n }\n }\n searchTerms = {};\n }\n}",
"remove() {\n this.floor.itemSprites.removeChild(this.sprite);\n }",
"removeTexture(texture) {\n // remove from our textures array\n this.textures = this.textures.filter(element => element.uuid !== texture.uuid);\n }",
"clearAllUserAttributes() {\n Instabug.clearAllUserAttributes();\n }",
"remove(element) {\n this.set.splice(this.set.indexOf(element), 1);\n console.log(\"element removed successfully\");\n }",
"function removeSceneTagFromSelection() {\n var rep = this.rep;\n var documentAttributeManager = this.documentAttributeManager;\n if (!(rep.selStart && rep.selEnd)) {\n return;\n }\n\n var firstLine = rep.selStart[0];\n var lastLine = Math.max(firstLine, rep.selEnd[0] - ((rep.selEnd[1] === 0) ? 1 : 0));\n\n _(_.range(firstLine, lastLine + 1)).each(function(line) { // for each line on selected range\n _.each(sceneTag, function(attribute) { // for each scene mark attribute\n documentAttributeManager.removeAttributeOnLine(line, attribute);\n });\n });\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns list of flagged quotes if logged in | function returnFlaggedQuotes( queryObj, response, sessionObj, onFinish )
{
//if the user is not logged in then stop them from getting the flagged quotes
if ( sessionObj.data.user === undefined )
{
var errorList = [ { "name" : "user" , "problem" : "not logged in" } ];
outputErrorAsJson( errorList, queryObj, response, sessionObj, onFinish );
return;
}
//if the user is not an admin then stop them from getting the flagged quotes
if ( sessionObj.data.role !== Constants.ROLE_USER_ADMIN )
{
var errorList = [ { "name" : "user" , "problem" : "not admin" } ];
outputErrorAsJson( errorList, queryObj, response, sessionObj, onFinish );
return;
}
dataAPI.getQuotesByFlag( function( results )
{
response.writeHead(200, {'Content-Type': 'text/json'});
response.write( JSON.stringify( results ) );
onFinish( sessionObj );
}
, true, queryObj.creator );
} | [
"function processQuotes(context) {\n hidePostsByDataAttribute(\n context.querySelectorAll('[data-ipsquote-userid]'),\n 'ipsquoteUserid'\n )\n }",
"static getSelectedSongs() {\n return SongManager.songList.filter(s => s.element.hasAttribute(\"selectedsong\"));\n }",
"function generateQuotes(data) { \n if (quotesArray.length === quoteSize) {\n quotesArray = [];\n }\n if (!quotesArray.includes(data[0])) {\n quotesArray.push(data[0]);\n quoteEl.textContent = data[0];\n } else {\n getQuote();\n }\n }",
"function showQuotes() {\n\n // create a new array of all the authors of the quotes to use for the user prompt\n var authors = [];\n for (var i = 0; i < quotes.length; i++) {\n authors.push(i + \") \" + quotes[i].author);\n }\n \n // ask the user to choose which author's quote they want to see\n inquirer.prompt([\n {\n type: \"list\",\n name: \"authorChoice\",\n message: \"Which author do you want to see a quote from? \",\n choices: authors\n }\n ]).then(function(userChoice) {\n\n // find the quote by the chosen author and display it\n var authorIndex = authors.indexOf(userChoice.authorChoice);\n console.log(quotes[authorIndex].quote, \"\\n\");\n displayMenu();\n })\n}",
"function showLocalStorage(){\n if(localStorage.getItem(\"quote\") !== null)\n showStoredQuote()\n }",
"get allowCredentials() {\n return this.getBooleanAttribute('allow_credentials');\n }",
"function getActiveSpells(mode) {\n const active = []\n\n // Loops through all spells if true add to active\n for (const s in spells) {\n const val = spells[s]\n\n if (val) active.push(s)\n }\n\n return active;\n}",
"ListOfOVHAccountsTheLoggedAccountHas() {\n let url = `/me/ovhAccount`;\n return this.client.request('GET', url);\n }",
"function allListings() {\n return itemListings.once('value')\n .then(data => data.val())\n .then(itemListings => {\n let items = Object.keys(itemListings)\n return items.filter(\n listingID => itemListings[listingID].forSale === true\n )\n })\n}",
"function getQuotes(){\n\tsetInterval(getQuote, 60000);\n\tgetQuote();\n}",
"function saveQuoteLocalStorage() {\n let quote = `${quoteText.innerText} - ${authorText.innerText}`;\n const quotes = getQuoteLocalStorage(); \n //Add the quote into the array\n quotes.push(quote);\n //Convert array into a string and add into local storage\n localStorage.setItem( 'quotes', JSON.stringify(quotes) );\n}",
"getMeteorData() {\n return { isLoggedIn: !!Meteor.user() };\n }",
"function cookieFromFilterpanel(){\n var ch = [];\n if ($j('.shop-filter-panel .filter-toggle').hasClass(\"open\")){\n ch.push(true);\n }\n\n $j.cookie(\"filterpanelCookie\", ch.join(','));\n}",
"async getSignedAgentForListing(listing_id) {\n let listings = await this.getListingsWithId(listing_id);\n let listing = listings[0];\n //console.log(listing);\n if(listing.listing_status != 'Signed') {\n console.log(`dbAccess getAgentForListing: the named listing with id ${listing_id} is not signed, which means there is no agent to return.`);\n return [];\n }\n\n let query = 'SELECT DISTINCT users.first_name, users.last_name, users.display_name, users.email, agents.id, agents.title, agents.phone, agents.web_site from (((agents inner join bids on agents.id = bids.agent_id AND bids.bid_status=\"Signed\") INNER JOIN listings ON bids.listing_id = ?) INNER JOIN users on users.agent_id = agents.id)';\n let args = [listing_id];\n const rows = await this.connection.query(query, args);\n return rows;\n }",
"grantPrivileges() {\n const result = [];\n Object.keys(this._config.grantPrivileges).forEach((privilege) => {\n if (this.hasPrivilege(privilege)) {\n result.push(privilege);\n }\n });\n return result;\n }",
"function doctorsAvailable(){\n\tvar doctors = []\n\tfor (i=0; i<visual.doctors.length; i++){\n\t\tif (visual.doctors[i].state == IDLE){\n\t\t\tdoctors.push(i)\n\t\t}\n\t}\n\treturn doctors;\n}",
"function createAuthorsArray(){\n\t\t\tlet authorsArray = [];\n\t\t\tfor (quoteIndex in quotes){\n\t\t\t\tif (authorsArray.includes(quotes[quoteIndex].author)){\n\t\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\tauthorsArray.push(quotes[quoteIndex].author);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn authorsArray;\n\t\t}",
"function getRandomQuote () {\n randomNumber = Math.floor(Math.random() * quotes.length); // Generate a random number from 0 to the 'quotes' array length\n randomQuote = quotes[randomNumber]; // Select the random quote using the random number as index\n return randomQuote; // Return the selected quote object\n}",
"getLogs() {\n if (this.auth()) {\n if (this.currentUser.type === \"admin\") {\n console.log(\"Saved logs: \");\n for (let i = 0; i < this.logs.length; i++) {\n console.log(this.logs[i]);\n }\n } else console.log('Access is denied')\n } else console.log('authorization required');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove all stored sessions for given identifier. | async clearSessions(identifier) {
if (!this.storage) {
throw new Error('Unable to clear sessions: No storage adapter configured');
}
for (const auth of await this.listSessions(identifier)) {
await this.removeSession(identifier, auth);
}
} | [
"static async destroy(id) {\n db.del(`session:${id}`)\n }",
"function destroyExpiredSessions() {\n // httpd sessions\n var httpSessions = this.getSessions(\"http\");\n for (var i = 0; i < httpSessions.length; i++) {\n var session = httpSessions[i];\n if ((Date.now() - session.lastActive) > this.timeout) {\n this.destroy(session);\n }\n }\n // socket.io sessions\n var socketIOSessions = this.getSessions(\"socket.io\");\n for (var i = 0; i < socketIOSessions.length; i++) {\n var session = socketIOSessions[i];\n if (session.socket == null) {\n this.destroy(session);\n }\n }\n\n }",
"_evictIdleSessions() {\n const {maxIdle, min} = this.options;\n const size = this.size;\n const idle = this._getIdleSessions();\n\n let count = idle.length;\n let evicted = 0;\n\n while (count-- > maxIdle && size - evicted++ > min) {\n let session = idle.pop();\n let type = session.type;\n let index = this._inventory[type].indexOf(session);\n\n this._inventory[type].splice(index, 1);\n this._destroy(session);\n }\n }",
"clearSession() {\n ['accessToken', 'expiresAt', 'idToken'].forEach(key => {\n sessionStorage.removeItem(key);\n });\n\n this.accessToken = '';\n this.idToken = '';\n this.expiresAt = '';\n }",
"clearExpired () {\n\t\t\tthis.all ((error, sessions) => {\n\t\t\t\t//do nothing\n\t\t\t});\n\t\t}",
"function _clear() {\n\n\t// Delete from localStorage\n\tdelete localStorage['_session'];\n\n\t// Delete the cookie\n\tCookies.remove('_session', '.' + window.location.hostname, '/');\n}",
"function clearIdToken() {\n localStorage.removeItem(ID_TOKEN_KEY);\n}",
"function clearStorage() {\n Object.keys(localStorage).filter(function (key) {\n return key.startsWith(options.name);\n }).forEach(function (key) {\n return localStorage.removeItem(key);\n });\n}",
"destroy(launchId) {\n const session = this.sessions.get(launchId);\n session === null || session === void 0 ? void 0 : session.dispose();\n this.sessions.delete(launchId);\n }",
"function logout() {\n sessionStorage.removeItem(\"userId\");\n sessionStorage.removeItem(\"jwt\");\n }",
"function filterSessions(){\n var now = Date.now();\n for(let key of sessions.keys()){\n time = sessions.get(key);\n if(MAX_LOGIN_TIME + time < now){\n console.log(key + \"'s session expired\");\n sessions.delete(key);\n }\n }\n}",
"function removeFromSession(key) {\n if (sessionStorage) {\n if (sessionStorage[key]) {\n delete sessionStorage[key];\n }\n }\n else {\n throw Error(\"Session storage not supported\");\n }\n}",
"purge() {\n\t\tthis.clear();\n\t\tthis.stateStorage.update(Watch.constants.WATCH_STORE, []);\n\t\tchannel.appendLocalisedInfo('purged_all_watchers');\n\t}",
"function sessiongc() {\n\tsessionmgr.sessiongc();\n}",
"static delete_all() {\n this.#users.remove({},{},function(err,num) {\n if (!err) {\n console.log(\"Deleted\",num,\"users\");\n }\n })\n }",
"unload(modelName, id) {\n let modelClass = this._store._modelFor(modelName);\n let relationshipsByName = get(modelClass, 'relationshipsByName');\n relationshipsByName.forEach((_, relationshipName) => {\n let relationshipPayloads = this._getRelationshipPayloads(modelName, relationshipName, modelClass, relationshipsByName, false);\n if (relationshipPayloads) {\n relationshipPayloads.unload(modelName, id, relationshipName);\n }\n });\n }",
"function clearHighScoreTable() {\n var highScoreTable = getHighScoreTable();\n for (var i = 0; i < highScoreTable.length; i++) {\n var name = \"player\" + i;\n deleteCookie(name);\n }\n}",
"function cleaAllCaches(){\n\n self.addEventListener('activate', function(event) {\n event.waitUntil(\n caches.keys().then(function(cacheNames) {\n return Promise.all(\n cacheNames.filter(function(cacheName) {\n // Return true if you want to remove this cache,\n // but remember that caches are shared across\n // the whole origin\n\n return true;\n\n }).map(function(cacheName) {\n return caches.delete(cacheName);\n })\n );\n })\n );\n });\n\n}",
"function τSST_clear_logs() {\n for (var item in localStorage) {\n if (item.startsWith(storage_key_prefix + 'stat_logs_') ||\n item.startsWith(storage_key_prefix + \"stats_\")) {\n console.log('τSST_clear_logs(): Removing localStorage item: ' + item);\n localStorage.removeItem(item);\n }\n }\n\n // Also clear internal data that affects logging.\n stats = {};\n stat_logs = {};\n nodes.stats_collection.text(\"\");\n\n is_storage_initialized = false;\n }",
"function findAndRemoveProxyStore(tabID){\n let arr = proxyStores.filter((store, idx) => {\n if(store.tabID === tabID){\n store.unsubscribe();\n }\n return store.tabID !== tabID; \n });\n return arr;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GOES THROUGH ALL OF MY POSTS AND RENDERS THEM TO THE "MYPOST" MODAL | function renderMyPostsLinks(posts) {
posts.forEach(function (post) {
const postElement = createMyPostHTML(post);
$(".modal-body").append(postElement);
});
} | [
"function renderPosts(posts){\n\n //jQuery ima each metodo s katero loop-amo\n\n $.each(posts, function (i, post) {\n\n\n //kot spremenljivke sem shranila te 4 elemente\n\n var $postContainer = $('<div>', {class:'post-container'});\n var $postTitle = $('<h1>', {class:'post-title', text:post.title + '/' +post.id});\n var $postContent = $('<div>', {class:'post-content', text:post.body});\n var $postLink = $('<a>', {href:'/article/'+post.id, text:'Read more ...'});\n var $hr = $('<hr/>');\n var $br = $('<br>');\n\n //tukaj v container vstavimo vse 3 spremenljivke\n //zaporednje je pomembno, ker se po tem zaporednju vstavijo v HTML\n\n $postContainer.append($postTitle, $postContent, $br , $postLink, $hr); \n\n //postContainer vstavimo v posts-container\n $('.posts-container').append($postContainer);\n\n });\n\n}",
"function MakePost(text){\nreturn {\n\ttext: text,\n\tdate: new Date()\n}\n}// this function will display posts in the posts div",
"loadBlogPosts() {\n var posts = model.getPostsByType('posts'),\n postsSection = document.createElement('section'),\n primaryContentEL = h.getPrimaryContentEl();\n\n postsSection.id = 'blogPosts';\n // Get markup for each post\n //console.log( posts );\n _.each(posts, post => {\n postsSection.appendChild(h.createPostMarkup(post));\n });\n // Append posts to page\n primaryContentEL.appendChild(postsSection);\n }",
"function appendPosts(posts) {\n let htmlTemplate = \"\";\n for (let post of posts) {\n console.log(post);\n htmlTemplate += `\n <article class=\"wp-posts\">\n <div class=\"divider\"> \n <h3>${post.title.rendered}</h3>\n <div class=\"flex-box\">\n <img src=\"${post.acf.image.url}\">\n <div>\n <p><b>Alder:</b> ${post.acf.age} år</p>\n <p><b>Afstand til nærmeste hospital:</b> ${post.acf.distance} km</p>\n <p><b>Type af amputaion:</b> ${post.acf.amputation}</p>\n </div>\n </div>\n </div>\n\n </article>\n `;\n }\n document.querySelector('#content').innerHTML = htmlTemplate;\n}",
"function reloadPost(post) {\n const tag = document.createElement(\"p\");\n const strong = document.createElement(\"strong\");\n const divPost = document.createElement(\"div\");\n divPost.className = \"col-lg-4 col-sm-12 my-col file\";\n //const divNewPost = document.createElement(\"div\");\n //divNewPost.textContent = \"Post:\";\n //divPost.appendChild(divNewPost);\n\n const divCountry = document.createElement(\"div\");\n divCountry.textContent = \"Country: \" + post.country;\n strong.appendChild(divCountry);\n divPost.appendChild(strong);\n //divPost.appendChild(divCountry);\n const divName = document.createElement(\"div\");\n divName.textContent = \"Created By: \" + post.name;\n divPost.appendChild(divName);\n\n const divStory = document.createElement(\"div\");\n divStory.textContent = \"Post: \" + post.post;\n divPost.appendChild(divStory);\n divPost.style.display = \"inline-block\";\n tag.appendChild(divPost);\n //divPost.style.cssText = \"border: solid;\";\n divPost.style.backgroundColor = \"#dedede\";\n\n divPosts.append(tag);\n\n console.log(divPosts);\n}",
"function renderUserFeed(userPosts, mainDiv) {\n userPosts.sort(function (a, b) {\n return b.meta.published - a.meta.published;\n });\n for (let i = 0; i < userPosts.length; i++) {\n let section = document.createElement('section');\n section.setAttribute('id', userPosts[i].id + '-post');\n section.setAttribute('class', 'post');\n let h2 = document.createElement('h2');\n h2.textContent = userPosts[i].meta.author;\n h2.setAttribute('id', userPosts[i].id + '-post-title');\n h2.setAttribute('class', 'post-title');\n section.appendChild(h2);\n let date = new Date(userPosts[i].meta.published * 1000);\n let dateStr = date.toString();\n let datestr = document.createElement('p');\n datestr.textContent = dateStr.substring(0, 24);\n datestr.setAttribute('id', userPosts[i].id + '-post-published');\n datestr.setAttribute('class', 'post-published');\n section.appendChild(datestr);\n let img = document.createElement('img');\n img.setAttribute('id', userPosts[i].id + '-post-image');\n img.setAttribute('src', 'data:image/png;base64,' + userPosts[i].src);\n img.setAttribute('alt', userPosts[i].meta.description_text);\n img.setAttribute('class', 'post-image');\n section.appendChild(img);\n let post_description = document.createElement('p');\n post_description.textContent = userPosts[i].meta.description_text;\n post_description.setAttribute('id', userPosts[i].id + '-post-description_text');\n post_description.setAttribute('class', 'post-description_text');\n section.appendChild(post_description)\n let like = document.createElement('span');\n like.textContent = '❤ ' + userPosts[i].meta.likes.length;\n like.setAttribute('id', userPosts[i].id + '-post-like');\n like.setAttribute('class', 'post-likes');\n section.appendChild(like)\n let comment = document.createElement('span');\n comment.textContent = '💬 ' + userPosts[i].comments.length;\n comment.setAttribute('id', userPosts[i].id + '-post-comment-count');\n comment.setAttribute('class', 'post-comments-count');\n section.appendChild(comment)\n if (userPosts[i].comments.length > 0) {\n let show_comment = document.createElement('span');\n show_comment.textContent = '+';\n show_comment.setAttribute('id', userPosts[i].id + '-post-show-comment');\n show_comment.setAttribute('class', 'post-show-comments');\n section.appendChild(show_comment)\n } else {\n let show_comments = document.createElement('span');\n show_comments.textContent = '+';\n show_comments.setAttribute('id', userPosts[i].id + '-post-show-comment');\n show_comments.setAttribute('class', 'post-show-comments');\n show_comments.style.display = 'none';\n section.appendChild(show_comments);\n }\n let hide = document.createElement('span');\n hide.textContent = '-';\n hide.setAttribute('id', userPosts[i].id + '-post-hide-comment');\n hide.setAttribute('class', 'post-hide-comments');\n hide.style.display = 'none';\n section.appendChild(hide);\n mainDiv.appendChild(section);\n }\n}",
"function displayJsonData(json)\n{\n var posts = json;\n $(\".blog-main\").remove();\n var currentUser = $(\"h1.blog-title\").first().text().trim();\n \n for(var i=0; i < posts.length; i++)\n {\n var id = posts[i][\"guid\"];\n \n var postMainDiv = makePostDiv(id, currentUser, posts[i]);\n \n $(\"#post_wall_container\").append(postMainDiv);\n }\n postButtonClickEvent();\n}",
"function render(items) {\n // LOOP\n // var item = ...\n // $(\"div#target\").append(\"<p>\" + item.message + \"</p>\")\n //\n }",
"function displayAllPosts() {\n \n $.ajax({\n \"url\": \"services/allPosts.php\",\n \"success\": function(jsonResponse) {\n \n $(jsonResponse).each(function(index, element) {\n \n var postId = element.id;\n var postTitle = element.title;\n var postDescription = element.description;\n var postCreated = element.created;\n var postUserId = element.user_id;\n \n var aPost = formatPost(postTitle, postDescription, postCreated,\n postUserId, postId);\n \n $(\"#allPostsContainer\").prepend(aPost);\n \n //Add comments section\n addCommentSection(postId);\n \n //Display all post comments\n displayCommentsByPostId(postId);\n\n })\n \n },\n \"error\":function() {\n\n $(\"#actionUnsuccessful\").dialog({\n \"modal\": true,\n \"buttons\": {\n \"Ok\": function() {\n\t\t\t$( this ).dialog( \"close\" );\n }\n }\n });\n \n }, \n \"dataType\":\"json\"\n }) \n }",
"function New() {\n\tconst dispatch = useDispatch();\n\tconst newPost = useSelector(selectPostPreview);\n\n\tconst subreddit = 'funny+programmerhumor+softwaregore';\n\tconst link = 'new';\n\n\tuseEffect(() => {\n\t\tdispatch(loadAllPostsPreview({ subreddit, link }));\n\t}, [dispatch]);\n\n\treturn (\n\t\t<div className='post-preview-container'>\n\t\t\t{newPost.map((post) => (\n\t\t\t\t<div key={post.data.id}>\n\t\t\t\t\t<PostListItem post={post} />\n\t\t\t\t</div>\n\t\t\t))}\n\t\t</div>\n\t);\n}",
"function PostCard(props){\n return <div>\n <div className=\"card fluid\" id={\"post_\"+nextPostId()}>\n <img className=\"section media\" src={props.image} alt=\"\" style={randomColor()}/>\n <div className=\"section\">\n <p className=\"post-text\">{props.text+'.'}</p>\n </div>\n <div className=\"section\">\n <p className=\"posted-by\"> <SvgUser /> Posted by {users[props.userId].login.username}</p>\n </div>\n </div>\n </div>;\n}",
"function displayEditPost(post){\r\n\t\t\t$(\"form#edit-form input#title\").val(post.title);\r\n\t\t\t$(\"form#edit-form textarea#content\").val(post.body);\r\n\t\t}",
"function renderIndThreadView(id, state) {\n var postIdArr = [];\n\n var thread = $.grep(state.movieThreads, function (elem, ind) {\n return elem._id == id;\n });\n\n hideAllViews();\n $('.js-btn-edit-thread').remove();\n\n // Add Thread ID to Section id\n $('.thread.view').attr('id', thread[0]._id);\n\n // Clear Posts\n $('.thread-view-title-posts').empty();\n\n // Fill in Thread Title Info\n $('.thread-view-title').text(thread[0].title);\n $('.thread-view-content').text(thread[0].content);\n $('.thread-creator').html('Thread Created by: <span class=\"js-thread-title-author\">' + thread[0].author + '</span>');\n $('.thread-created').text('' + new Date(thread[0].date).toLocaleString());\n if (thread[0].author === state.user) {\n $('.add-post-wrapper').append('<button type=\"button\" class=\"btn-add-post js-btn-edit-thread\">Edit</button>');\n } else {\n //\n }\n \n showView('thread');\n\n // Load Thread Posts\n if(thread[0].posts.length){\n thread[0].posts.forEach(function (post, index) {\n $('.thread-view-title-posts').append('<article class=\"post-wrapper\" id=' + post._id + '>\\n\\n <span class=\"post-content-date\"><span class=\"js-pc-user\">' + post.user.slice(0, 1) + '</span> <span class=\"js-pc-full-user\">' + post.user + '</span> ' + new Date(post.created).toLocaleString() + '</span>\\n <div class=\"post-content-wrapper\">\\n \\n <div class=\"post-content\">' + post.content + '</div>\\n\\n <div class=\"post-meta\">\\n <button class=\"likes\"> <span class=\"thumb\">👍</span> </button>\\n <span class=\"likes\">' + post.likes.count + '</span>\\n <span class=\"btn-comment\" id=\"btn-comment\">Comment</span> \\n </div> \\n </div> \\n </article> \\n ');\n\n // Add divider between Posts\n $('.thread-view-title-posts').append('<div class=\"js-separate\"></div>');\n\n // Check to see if current user liked post then change thumbs up class.\n var match = false;\n post.likes.users.forEach(function (user) {\n if (user.trim() === state.user.trim()) {\n $('#' + post._id).find('.thumb').addClass('thumb-liked');\n }\n });\n\n if (post.user === state.user) {\n var btn_render = '<span class=\"btn-comment\" id=\"btn-delete\">Delete</span><span class=\"btn-post\" id=\"btn-edit-post\">Edit</span>';\n $('.post-meta')[index].innerHTML += btn_render;\n }\n\n if (post.comments.length) {\n post.comments.forEach(function (comment) {\n $('#' + post._id).append('\\n\\n\\n\\n\\n\\n\\n<div class=\"js-comment\">\\n' + comment.comment + '\\n<p class=\"js-comment-user\"><span class=\"by\">by:</span> ' + comment.user + '</p>\\n</div>\\n');\n });\n }\n });\n }\n // End Posts\n showView('thread');\n}",
"update() {\n view.updateTitle(view.currentPost.title);\n view.updateContent(view.currentPost.content);\n\n view.removeBlogPosts();\n if (view.currentPost.slug === 'blog') {\n // Append blog posts to blog page\n view.loadBlogPosts();\n }\n }",
"_renderPostBody(){\n\t\tif(!this.state.hasBody){\n\t\t\treturn (\n\t\t\t\t<div onClick={this.addText} className=\"uk-button uk-button-primary uk-width-1-4\" style={{marginLeft:10, marginBottom:5}}>\n\t\t\t\t\tAdd Text\n\t\t\t\t</div>\n\t\t\t)\n\t\t} else if(!this.state.isSelected) {\n\t\t\treturn ( \n\t\t\t\t<div onClick={this.inputChange}>\n\t\t\t\t\t{this._renderBody()}\n\t\t\t\t</div>\n\t\t\t\t)\n\t\t} else if (this.state.isSelected) {\n\t\t\treturn( \n\t\t\t\t<form onSubmit={this.onSubmit} className=\"uk-panel uk-panel-box uk-form\">\n\t\t\t\t\t<div className=\"uk-form-row\">\n\t\t\t\t\t\t<input ref=\"postInput\" className=\"uk-width-1-1\" type=\"text\" placeholder={this.props.body} />\n\t\t\t\t\t</div>\n\t\t\t\t</form> \n\t\t\t)\n\t\t}\n\t}",
"function outputBlogPosts() {\n var htmlOutput = \"\"\n for(let i=0; i<blogs.length; i++) {\n htmlOutput += \"<div id=\\\"test\\\"><h2>\" + blogs[i].title + \"</h2><div>\" + blogs[i].author + \"/\" + blogs[i].created + \"</div><div>\" + blogs[i].content + \"</div></div>\" \n }\n $(\"#blogs\").html(htmlOutput)\n}",
"function updatePost(posts, index) {\n\t\tvar contents = \"\";\n\n\t\tcontents += \"<h2 class=\\\"blog-post-title\\\">\" + posts[index].heading + \"</h2>\";\n\t\tcontents += \"<p class=\\\"blog-post-meta\\\">\" + posts[index].date + \" by <a href=\\\"about.php\\\">\" + posts[index].author + \"</a></p>\";\n\t\tcontents += \"<img class=\\\"blog-img\\\" src=\\\"\" + posts[index].image + \"\\\" alt=\\\"\" + posts[index].alt + \"\\\">\";\n\t\tcontents += \"<p>\" + posts[index].text + \"</p>\";\n\n\t\t$(\"#blog_section\").html(contents);\n\t}",
"renderList() {\n return this.props.posts.map((post) => {\n return (\n <div className='item' key={post.id}>\n <i className='large middle aligned icon user' />\n <div className='content'>\n <div className='description'>\n <h2>{post.title}</h2>\n <p>{post.body}</p>\n </div>\n <UserHeader userId={post.userId} />\n </div>\n </div>\n )\n })\n }",
"renderBlogs(blogs) {\n var blogsHTML = \"\";\n for (var i = 0; i < blogs.length; i++) {\n blogsHTML = '<div class=\"blogContainer\" name=\"'+ blogs[i].Id +'\">\\n'\n +'<div class=\"blogHeader\">\\n'\n + '<h2 class=\"header pull-left\">' + blogs[i].Title + '</h2>\\n</div>'\n + '<div class=\"blogDate pull-right\">' + blogs[i].Date + '</div>'\n + '<div class=\"blogBody pull-left\">\\n'\n + blogs[i].Body\n + '</div>\\n</div>' + blogsHTML;\n }\n $(\"#blogEntriesContainer\").html($.parseHTML(blogsHTML));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the text body returned by the server from a batch request | function parseResponse(body) {
const responses = [];
const header = "--batchresponse_";
// Ex. "HTTP/1.1 500 Internal Server Error"
const statusRegExp = new RegExp("^HTTP/[0-9.]+ +([0-9]+) +(.*)", "i");
const lines = body.split("\n");
let state = "batch";
let status;
let statusText;
let headers = {};
const bodyReader = [];
for (let i = 0; i < lines.length; ++i) {
let line = lines[i];
switch (state) {
case "batch":
if (line.substring(0, header.length) === header) {
state = "batchHeaders";
}
else {
if (line.trim() !== "") {
throw Error(`Invalid response, line ${i}`);
}
}
break;
case "batchHeaders":
if (line.trim() === "") {
state = "status";
}
break;
case "status": {
const parts = statusRegExp.exec(line);
if (parts.length !== 3) {
throw Error(`Invalid status, line ${i}`);
}
status = parseInt(parts[1], 10);
statusText = parts[2];
state = "statusHeaders";
break;
}
case "statusHeaders":
if (line.trim() === "") {
state = "body";
}
else {
const headerParts = line.split(":");
if ((headerParts === null || headerParts === void 0 ? void 0 : headerParts.length) === 2) {
headers[headerParts[0].trim()] = headerParts[1].trim();
}
}
break;
case "body":
// reset the body reader
bodyReader.length = 0;
// this allows us to capture batch bodies that are returned as multi-line (renderListDataAsStream, #2454)
while (line.substring(0, header.length) !== header) {
bodyReader.push(line);
line = lines[++i];
}
// because we have read the closing --batchresponse_ line, we need to move the line pointer back one
// so that the logic works as expected either to get the next result or end processing
i--;
responses.push(new Response(status === 204 ? null : bodyReader.join(""), { status, statusText, headers }));
state = "batch";
headers = {};
break;
}
}
if (state !== "status") {
throw Error("Unexpected end of input");
}
return responses;
} | [
"_bufferParse(response)\n {\n return new Promise((resolve, reject) => {\n response.on('error', reject);\n\n let dataBuffer = [];\n\n response.on('data', (data) => {\n dataBuffer.push(data);\n });\n\n response.on('end', () => resolve(dataBuffer));\n });\n }",
"parseResponse(response, platform) {\n const sendRegex = /<send>/g;\n const regex = {\n image: /\\^image\\(\"(.*?)\"\\)/g,\n imageForSplit: /\\^image\\(\".*\"\\)/g,\n template: /\\^template\\(([\\s\\S]*?)\\)/g,\n templateForSplit: /\\^template\\(([\\s\\S]*)\\)/g,\n templateStrings: /`([\\s\\S]*?)`/g,\n sms: /<sms>([\\s\\S]*?)<\\/sms>/g,\n fb: /<fb>([\\s\\S]*?)<\\/fb>/g,\n nonwhitespaceChars: /\\S/,\n };\n if (platform === constants.FB) {\n response = response.replace(regex.sms, '');\n response = response.replace(regex.fb, '$1');\n } else if (platform === constants.SMS) {\n response = response.replace(regex.fb, '');\n response = response.replace(regex.sms, '$1');\n }\n const messages = response.split(sendRegex);\n const finalMessages = [];\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n const messageType = this.getMessageType(message, regex);\n if (messageType === 'text') {\n this.prepareTextMessage(finalMessages, message);\n } else if (messageType === 'image') {\n this.prepareImageMessage(finalMessages, message, regex);\n } else if (messageType === 'template') {\n this.prepareTemplateMessage(finalMessages, message, regex);\n }\n }\n return finalMessages;\n }",
"parseCreateResponse(responseText) {\n return halfred.parse(responseText);\n }",
"function parseElko(buffer) {\n var parsedMessages = [];\n var messages = buffer.toString().split('\\n');\n for (var i in messages) {\n if (messages[i].length == 0) {\n continue;\n }\n try {\n var parsedMessage = JSON.parse(messages[i]);\n parsedMessages.push(parsedMessage);\n } catch (e) {\n log.warn(\"Unable to parse: \" + buffer + \"\\n\\n\" + JSON.stringify(e, null, 2));\n }\n }\n return parsedMessages;\n}",
"function processResponse(str) {\n\tvar data = JSON.parse(str);\n\t\n\t\n\t// We only use this portion of the return from google\n\t// Need to figure out how to tell google to not send us the \n\t// rest of it\n\tvar textAnnotations = data.responses[0].textAnnotations;\n\n\tvar imageTopY = textAnnotations[0].boundingPoly.vertices[0].y;\n\n\tvar imageBottomY = textAnnotations[0].boundingPoly.vertices[2].y;\n\tvar imageLeftX = textAnnotations[0].boundingPoly.vertices[0].x;\n\tvar imageRightX = textAnnotations[0].boundingPoly.vertices[2].x;\n\n\tvar imageWidth = imageRightX - imageLeftX;\n\tvar imageHeight = imageBottomY - imageTopY;\n\n\tvar arrayOfLines = new Array();\n\n\t// Skip the first block (was for the entire image)\n\t// Make the Image();\n\tvar previousMidY;\n\tvar bufferWidth;\n\tvar currLine = new Array(); // Array of Block objects, not a Line object\n\tvar lineList = new Array();\n\n\tfor (var i = 1; i < textAnnotations.length; i++) {\n\t\tlet unprocessedBlock = textAnnotations[i];\n\t\tlet currString = unprocessedBlock.description;\n\t\tlet blockTopY = unprocessedBlock.boundingPoly.vertices[0].y;\n\t\tlet blockLeftX = unprocessedBlock.boundingPoly.vertices[0].x;\n\t\tlet blockRightX = unprocessedBlock.boundingPoly.vertices[2].x;\n\t\tlet blockBottomY = unprocessedBlock.boundingPoly.vertices[2].y;\n\n\t\t// Averages\n\t\tlet blockMidX = (blockLeftX + blockRightX) / 2;\n\t\tlet blockMidY = (blockTopY + blockBottomY) / 2;\n\n\t\t// W&H\n\t\tlet blockWidth = blockRightX - blockLeftX;\n\t\tlet blockHeight = blockBottomY - blockTopY;\n\n\t\tvar block = new Block(currString, blockMidX, blockMidY, blockTopY, blockBottomY, blockLeftX, blockRightX, blockWidth, blockHeight);\n\n\t\t// Just starting out\n\t\tif (previousMidY == undefined) {\n\t\t\tcurrLine.push(block);\n\t\t\tpreviousMidY = blockMidY;\n\t\t\tbufferWidth = blockHeight / 2;\n\t\t} else {\n\t\t\t// Add current Line to lineList if that Line is finished, and make a new Line with the current Block\n\t\t\t// Otherwise, add the current Block to the lineList\n\t\t\t// console.log(currString + \" => block.MidY: \" + blockMidY + \", previousMidY: \" + previousMidY + \", bufferWidth: \" + bufferWidth);\n\t\t\tif (blockMidY < previousMidY + bufferWidth && blockMidY > previousMidY - bufferWidth ) {\n\t\t\t\t// line is not finished\n\t\t\t\tcurrLine.push(block);\n\t\t\t\tpreviousMidY = blockMidY;\n\t\t\t\tbufferWidth = blockHeight / 2;\n\t\t\t} else {\n\t\t\t\t// Line is finished\n\n\t\t\t\tvar completedLine = new Line(sortBlocksBasedOnX(currLine));\n\t\t\t\tlineList.push(completedLine);\n\t\t\t\tcurrLine = new Array();\n\t\t\t\tcurrLine.push(block);\n\t\t\t\tpreviousMidY = blockMidY;\n\t\t\t\tbufferWidth = blockHeight / 2;\n\t\t\t}\n\t\t}\n\t}\n\n\tvar image = new Image(lineList, imageTopY, imageBottomY, imageLeftX, imageRightX);\n\tconsole.log(\"############ MADE IMAGE ###############\");\n\tconsole.log(image.toString());\n\tconsole.log(\"############ DONE IMAGE ###############\");\n\n\tvar returnString = processImageByStoreName(image);\n\n\tdebug(\"Done processing\");\n\tconsole.log(returnString);\n}",
"_feed(chars) {\n\n var delimiter_pos;\n this._buffer = Buffer.concat([this._buffer, chars]);\n\n while((delimiter_pos = this._buffer.indexOf(DELIMITER)) != -1) {\n // Read until delimiter\n var buff = this._buffer.slice(0, delimiter_pos);\n this._buffer = this._buffer.slice(delimiter_pos + 1);\n\n // Check data are json\n var data = null;\n try {\n data = JSON.parse(buff.toString());\n } catch(e) {\n log.info(\"Bad data, not json\", buff, \"<raw>\", buff.toString(), \"</raw>\");\n continue;\n }\n\n // Send to client\n if(data)\n this.emit(\"transport_message\", data).catch(log.error);\n }\n }",
"function IAjaxBatchRequest() {}",
"function getTotalObjects(cb) {\n var xhr = new XMLHttpRequest();\n var apiAll = apiMetObject.substring(0, apiMetObject.length - 1);\n xhr.open(\"GET\", apiAll);\n xhr.send();\n xhr.onreadystatechange = function () {\n if (this.readyState == 4 && this.status == 200) {\n cb(JSON.parse(this.responseText));\n console.log(\n \"******** JSON response text \" + JSON.parse(this.responseText)\n );\n }\n };\n}",
"assembleBatchData(event, response) {\n const batchData = [];\n const batchJsapiApp = event.opts.get_batch_data.batch_config.jsapi_app;\n const batchJsapiEnv = event.opts.get_batch_data.batch_config.jsapi_env;\n const batchApi = event.opts.get_batch_data.batch_config.api;\n const batchFunction = event.opts.get_batch_data.batch_config.function;\n const propMaps = event.opts.get_batch_data.batch_config.data_prop_maps;\n\n // build an array of batch data based on the response\n response.content.forEach(jsapiThing => {\n let batchOpts = event.opts.get_batch_data.batch_config.opts;\n // need to build the opts\n // for some opts properties, we need data from the get_batch_data response\n // using npm get-data & set-data packages to allow us to access nested properties\n // via string representation of dot notation.\n // Like if this actually would work -> jsapiThing['user.id'];\n // if res_prop is null, then set the whole jsapiThing to the batch_opts_prop\n // https://www.npmjs.com/package/get-value\n // https://www.npmjs.com/package/set-value\n propMaps.forEach(propMap => {\n // if res_prop exists, but is null, then put the entire jsapi data\n // into batch_data_prop\n if (!propMap.res_prop) {\n set(batchOpts, propMap.batch_data_prop, jsapiThing);\n }\n // if res_prop exists and is not null, copy its value\n // into the batch_data_prop\n else {\n const responseData = get(jsapiThing, propMap.res_prop);\n set(batchOpts, propMap.batch_data_prop, responseData);\n }\n });\n\n let dataItem = {\n jsapi_app: batchJsapiApp,\n jsapi_env: batchJsapiEnv,\n api: batchApi,\n function: batchFunction,\n opts: _.cloneDeep(batchOpts)\n };\n batchData.push(dataItem);\n });\n console.log(`Running ${batchData.length} batch calls`);\n return batchData;\n }",
"function processJSONBody(req, controller, methodName) {\n let body = [];\n req.on('data', chunk => {\n body.push(chunk);\n }).on('end', () => {\n try {\n // we assume that the data is in the JSON format\n if (req.headers['content-type'] === \"application/json\") {\n controller[methodName](JSON.parse(body));\n }\n else \n response.unsupported();\n } catch(error){\n console.log(error);\n response.unprocessable();\n }\n });\n }",
"async function fsrv_prodParser(err, data, pool) {\n let result;\n parser.parseString(data, async function (err, output) {\n result = output;\n });\n let completedNum = 0;\n let bulkContent = [];\n let bulkContentSpot = 0;\n let curProdArray = [];\n let selectedProduct = \"\";\n let fundListNum = result.FundSetup.FundList.length;\n let currMgmtCode = \"\";\n let currCutOffTime = \"\";\n let effDate = result.FundSetup.Date[0];\n effDate = effDate.substring(0, 4) + \"-\" + effDate.substring(4, 6) + \"-\"\n + effDate.substring(6, 8);\n for (let a = 0; a < fundListNum; a++) {\n currMgmtCode = result.FundSetup.FundList[a].MgmtCode[0];\n let investProductNum = result.FundSetup.FundList[a].InvstProduct.length;\n for (let b = 0; b < investProductNum; b++) {\n selectedProduct = result.FundSetup.FundList[a].InvstProduct[b];\n curProdArray[0] = currMgmtCode;\n curProdArray[1] = effDate;\n curProdArray[2] = selectedProduct.FundID[0];\n curProdArray[3] = selectedProduct.FundLinkID[0];\n currCutOffTime = selectedProduct.CutoffTime[0];\n curProdArray[4] = currCutOffTime.substring(0, 2) +\n \":\" + currCutOffTime.substring(2, 4) + \":\" +\n currCutOffTime.substring(4, 6);\n curProdArray[5] = selectedProduct.MgmtCoBrandNm[0];\n curProdArray[6] = selectedProduct.FundName[0].EngName[0].ShortName[0];\n curProdArray[7] = selectedProduct.FundName[0].EngName[0].LongName[0];\n curProdArray[8] = selectedProduct.FundName[0].FreName[0].ShortName[0];\n curProdArray[9] = selectedProduct.FundName[0].FreName[0].LongName[0];\n curProdArray[10] = selectedProduct.Properties[0].ProductType[0];\n curProdArray[11] = selectedProduct.Properties[0].Currency[0];\n curProdArray[12] = selectedProduct.Properties[0].LoadType[0];\n if (selectedProduct.Properties[0].Classification) {\n curProdArray[13] = selectedProduct.Properties[0].Classification[0];\n } else {\n curProdArray[13] = null;\n }\n curProdArray[14] = selectedProduct.Properties[0].TaxStructure[0];\n curProdArray[15] = selectedProduct.Properties[0].MoneyMrktFlg[0];\n curProdArray[16] = selectedProduct.Properties[0].BareTrusteeFlg[0];\n curProdArray[17] = selectedProduct.Properties[0].RiskClass[0];\n curProdArray[18] = parseFloat(selectedProduct.Properties[0].FeeComm[0].AcctSetupFee[0]);\n curProdArray[19] = parseFloat(selectedProduct.Properties[0].FeeComm[0].ServFee[0].ServFeeRate[0]);\n curProdArray[20] = selectedProduct.Properties[0].FeeComm[0].ServFee[0].ServFeeFreq[0];\n curProdArray[21] = parseFloat(selectedProduct.Properties[0].FeeComm[0].MaxComm[0]);\n curProdArray[22] = parseFloat(selectedProduct.Properties[0].FeeComm[0].MaxSwitchComm[0]);\n if (selectedProduct.Properties[0].Series) {\n curProdArray[23] = selectedProduct.Properties[0].Series[0];\n } else {\n curProdArray[23] = null;\n }\n if (selectedProduct.Properties[0].Class) {\n curProdArray[24] = selectedProduct.Properties[0].Class[0];\n } else {\n curProdArray[24] = null;\n }\n curProdArray[25] = selectedProduct.Properties[0].RegDocType[0];\n curProdArray[26] = selectedProduct.Eligible[0].EligUS[0];\n curProdArray[27] = selectedProduct.Eligible[0].EligOffshore[0];\n curProdArray[28] = selectedProduct.Eligible[0].EligPAC[0];\n curProdArray[29] = selectedProduct.Eligible[0].EligSWP[0];\n if (selectedProduct.CUSIP) {\n curProdArray[30] = selectedProduct.CUSIP[0];\n } else {\n curProdArray[30] = null;\n }\n if (selectedProduct.Properties[0].DiscBrokerOnly) {\n curProdArray[31] = selectedProduct.Properties[0].DiscBrokerOnly[0];\n } else {\n curProdArray[31] = null;\n }\n if (selectedProduct.Properties[0].Brand) {\n curProdArray[32] = selectedProduct.Properties[0].Brand[0];\n } else {\n curProdArray[32] = null;\n }\n if (selectedProduct.Properties[0].FeeComm[0].DSCSchedule) {\n curProdArray[33] = selectedProduct.Properties[0].FeeComm[0].DSCSchedule[0].DSC[0];\n curProdArray[34] = selectedProduct.Properties[0].FeeComm[0].DSCSchedule[0].DSCDuration[0];\n } else {\n curProdArray[33] = null;\n curProdArray[34] = null;\n }\n if (selectedProduct.Properties[0].EligFeeAcct) {\n curProdArray[35] = selectedProduct.Properties[0].EligFeeAcct[0];\n } else {\n curProdArray[35] = null;\n }\n if (selectedProduct.ISIN) {\n curProdArray[36] = selectedProduct.ISIN[0];\n } else {\n curProdArray[36] = null;\n }\n if (selectedProduct.Properties[0].NegotiateFee) {\n curProdArray[37] = selectedProduct.Properties[0].NegotiateFee[0];\n } else {\n curProdArray[37] = null;\n }\n if (selectedProduct.Properties[0].NegotiateTrail) {\n curProdArray[38] = selectedProduct.Properties[0].NegotiateTrail[0];\n } else {\n curProdArray[38] = null;\n }\n if (selectedProduct.Properties[0].SerClassSeq) {\n curProdArray[39] = selectedProduct.Properties[0].SerClassSeq[0];\n } else {\n curProdArray[39] = null;\n }\n completedNum++;\n bulkContent[bulkContentSpot] = curProdArray;\n bulkContentSpot++;\n if (completedNum == 1000) {\n await bulkInsert(pool, bulkContent, \"INSERT INTO fsrv_prod(MGMT_CODE, EFF_DT, FUND_ID, FUND_LINK_ID,\" +\n \" CUT_OFF_TIME, MGMT_CO_BRAND_NM, ENG_SHORT_NM, ENG_LONG_NM, FRE_SHORT_NM, FRE_LONG_NM, PROD_TYPE,\" +\n \" CURR, LOAD_TYPE, CLASSIFICATION, TAX_STRUCT, MM_FLAG, BARE_TRUSTEE_FLAG, RISK_CLASS, ACCT_SETUP_FEE,\" +\n \" SERV_FEE_RATE, SERV_FEE_FREQ, MAX_COMM, MAX_SW_COMM, SERIES, CLASS, REG_DOC_TYPE, ELIG_US,\" +\n \" ELIG_OFFSHORE, ELIG_PAC, ELIG_SWP, CUSIP, DISC_BROKER_ONLY, BRAND, DSC, DSC_DURATION,\" +\n \" FEE_BASED_ELIG, ISIN, NEGOT_FEE, NEGOT_TRAILER, SER_CLASS_SEQ_IN_NAME)\" +\n \" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\");\n bulkContentSpot = 0;\n bulkContent = [];\n completedNum = 0;\n }\n curProdArray = [];\n }\n }\n if (bulkContent[0] != null) {\n await bulkInsert(pool, bulkContent, \"INSERT INTO fsrv_prod(MGMT_CODE, EFF_DT, FUND_ID, FUND_LINK_ID,\" +\n \" CUT_OFF_TIME, MGMT_CO_BRAND_NM, ENG_SHORT_NM, ENG_LONG_NM, FRE_SHORT_NM, FRE_LONG_NM, PROD_TYPE,\" +\n \" CURR, LOAD_TYPE, CLASSIFICATION, TAX_STRUCT, MM_FLAG, BARE_TRUSTEE_FLAG, RISK_CLASS, ACCT_SETUP_FEE,\" +\n \" SERV_FEE_RATE, SERV_FEE_FREQ, MAX_COMM, MAX_SW_COMM, SERIES, CLASS, REG_DOC_TYPE, ELIG_US,\" +\n \" ELIG_OFFSHORE, ELIG_PAC, ELIG_SWP, CUSIP, DISC_BROKER_ONLY, BRAND, DSC, DSC_DURATION,\" +\n \" FEE_BASED_ELIG, ISIN, NEGOT_FEE, NEGOT_TRAILER, SER_CLASS_SEQ_IN_NAME)\" +\n \" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\");\n }\n //console.log(bulkContent);\n return true;\n}",
"function parseLBRequest(arr) {\n let charName = arr[0];\n let lbTier = arr[1];\n let charID = getCharacterID(charName);\n if (charID === -1) {\n return Promise.reject(new Error(`${charName} is not a valid character name`));\n }\n else if (lbTier === 'lb') {\n let objLBTier = { tierID: 0 };\n return getTierLBsForCharID(charID, objLBTier, arr);\n }\n else if (lbTier.match(lbRegex)) { //contains specific character name and tier\n let objLBTier = filterLBTier(lbTier); //filter the tier info to pass to getting the soul breaks\n return getTierLBsForCharID(charID, objLBTier, arr);\n }\n else {\n return Promise.reject(new Error(`${charName} ${lbTier} is not a valid request`));\n }\n}",
"function processData(data) {\n if (data.length === 0) return;\n var idxCRLF = null, literalInfo, curReq;\n\n // - Accumulate data until newlines when not in a literal\n if (self._state.curExpected === null) {\n // no newline, append and bail\n if ((idxCRLF = bufferIndexOfCRLF(data, 0)) === -1) {\n if (self._state.curData)\n self._state.curData = bufferAppend(self._state.curData, data);\n else\n self._state.curData = data;\n return;\n }\n // yes newline, use the buffered up data and new data\n // (note: data may now contain more than one line's worth of data!)\n if (self._state.curData && self._state.curData.length) {\n data = bufferAppend(self._state.curData, data);\n self._state.curData = null;\n }\n }\n\n // -- Literal\n // Don't mess with incoming data if it's part of a literal\n if (self._state.curExpected !== null) {\n curReq = curReq || self._state.requests[0];\n\n if (!curReq._done) {\n var chunk = data;\n self._state.curXferred += data.length;\n if (self._state.curXferred > self._state.curExpected) {\n var pos = data.length\n - (self._state.curXferred - self._state.curExpected),\n extra = data.slice(pos);\n if (pos > 0)\n chunk = data.slice(0, pos);\n else\n chunk = undefined;\n data = extra;\n curReq._done = 1;\n }\n\n if (chunk && chunk.length) {\n if (self._LOG) self._LOG.data(chunk.length, chunk);\n if (curReq._msgtype === 'headers') {\n chunk.copy(self._state.curData, curReq.curPos, 0);\n curReq.curPos += chunk.length;\n }\n else\n curReq._msg.emit('data', chunk);\n }\n }\n\n if (curReq._done) {\n var restDesc;\n if (curReq._done === 1) {\n if (curReq._msgtype === 'headers')\n curReq._headers = self._state.curData.toString('ascii');\n self._state.curData = null;\n curReq._done = true;\n }\n\n if (self._state.curData)\n self._state.curData = bufferAppend(self._state.curData, data);\n else\n self._state.curData = data;\n\n idxCRLF = bufferIndexOfCRLF(self._state.curData);\n if (idxCRLF && self._state.curData[idxCRLF - 1] === CHARCODE_RPAREN) {\n if (idxCRLF > 1) {\n // eat up to, but not including, the right paren\n restDesc = self._state.curData.toString('ascii', 0, idxCRLF - 1)\n .trim();\n if (restDesc.length)\n curReq._desc += ' ' + restDesc;\n }\n parseFetch(curReq._desc, curReq._headers, curReq._msg);\n data = self._state.curData.slice(idxCRLF + 2);\n curReq._done = false;\n self._state.curXferred = 0;\n self._state.curExpected = null;\n self._state.curData = null;\n curReq._msg.emit('end', curReq._msg);\n // XXX we could just change the next else to not be an else, and then\n // this conditional is not required and we can just fall out. (The\n // expected check === 0 may need to be reinstated, however.)\n if (data.length && data[0] === CHARCODE_ASTERISK) {\n self._unprocessed.unshift(data);\n return;\n }\n } else // ??? no right-paren, keep accumulating data? this seems wrong.\n return;\n } else // not done, keep accumulating data\n return;\n }\n // -- Fetch w/literal\n // (More specifically, we were not in a literal, let's see if this line is\n // a fetch result line that starts a literal. We want to minimize\n // conversion to a string, as there used to be a naive conversion here that\n // chewed up a lot of processor by converting all of data rather than\n // just the current line.)\n else if (data[0] === CHARCODE_ASTERISK) {\n var strdata;\n idxCRLF = bufferIndexOfCRLF(data, 0);\n if (data[idxCRLF - 1] === CHARCODE_RBRACE &&\n (literalInfo =\n (strdata = data.toString('ascii', 0, idxCRLF)).match(reFetch))) {\n self._state.curExpected = parseInt(literalInfo[2], 10);\n\n var desc = strdata.substring(strdata.indexOf('(')+1).trim();\n var type = /BODY\\[(.*)\\](?:\\<\\d+\\>)?/.exec(strdata)[1];\n var uid = reUid.exec(desc)[1];\n\n // figure out which request this belongs to. If its not assigned to a\n // specific uid then send it to the first pending request...\n curReq = self._findFetchRequest(uid, type) || self._state.requests[0];\n var msg = new ImapMessage();\n\n // because we push data onto the unprocessed queue for any literals and\n // processData lacks any context, we need to reorder the request to be\n // first if it is not already first. (Storing the request along-side\n // the data in insufficient because if the literal data is fragmented\n // at all, the context will be lost.)\n if (self._state.requests[0] !== curReq) {\n self._state.requests.splice(self._state.requests.indexOf(curReq), 1);\n self._state.requests.unshift(curReq);\n }\n\n msg.seqno = parseInt(literalInfo[1], 10);\n curReq._desc = desc;\n curReq._msg = msg;\n msg.size = self._state.curExpected;\n\n curReq._fetcher.emit('message', msg);\n\n curReq._msgtype = (type.indexOf('HEADER') === 0 ? 'headers' : 'body');\n // This library buffers headers, so allocate a buffer to hold the literal.\n if (curReq._msgtype === 'headers') {\n self._state.curData = new Buffer(self._state.curExpected);\n curReq.curPos = 0;\n }\n if (self._LOG) self._LOG.data(strdata.length, strdata);\n // (If it's not headers, then it's body, and we generate 'data' events.)\n self._unprocessed.unshift(data.slice(idxCRLF + 2));\n return;\n }\n }\n\n if (data.length === 0)\n return;\n\n data = customBufferSplitCRLF(data);\n var response = data.shift().toString('ascii');\n // queue the remaining buffer chunks up for processing at the head of the queue\n self._unprocessed = data.concat(self._unprocessed);\n\n if (self._LOG) self._LOG.data(response.length, response);\n processResponse(stringExplode(response, ' ', 3));\n }",
"function splitDocument(bodyStr) {\n\tlet azureOrgArray = [];\n\tlet azurePersonArray = [];\n\n\t// Replacing white space and html\n\tbodyStr = bodyStr.replace(/<[^>]*>?/gm, '');\n\tbodyStr = bodyStr.replace(/\\s\\s+/g, ' ');\n\n\tdocLength = bodyStr.length;\n\t// Calculating number of documents needed to send\n\tnumSplits = Math.floor(docLength / 5100);\n\treturn new Promise(async function(resolve, reject) {\n\t\t// If Document needs to be split, break up into 5100 char chunks and send to azureResponse()\n\t\tif(numSplits == 0) {\n\t\t\tlet termArr = await azureResponse(bodyStr);\n\t\t\ttermArr[0].forEach(function(term) {\n\t\t\t\tazurePersonArray.push(term);\n\t\t\t});\n\t\t\ttermArr[1].forEach(function(term) {\n\t\t\t\tazureOrgArray.push(term);\n\t\t\t});\n\t\t} else {\n\t\t\tconsole.log(\"Document too long at \" + docLength + \" chars\");\n\t\t\tconsole.log(\"Number of subDocs: \" + numSplits);\n\t\t\tfor(let i = 0; i <= numSplits; i++) {\n\t\t\t\tlet subDoc;\n\t\t\t\tif(i == numSplits) {\n\t\t\t\t\tsubDoc = bodyStr.substring(i*5100);\n\t\t\t\t} else {\n\t\t\t\t\tsubDoc = bodyStr.substring(i*5100,5100*(i+1));\n\t\t\t\t}\n\t\t\t\tlet termArr = await azureResponse(subDoc);\n\t\t\t\ttermArr[0].forEach(function(term) {\n\t\t\t\t\tazurePersonArray.push(term);\n\t\t\t\t});\n\t\t\t\ttermArr[1].forEach(function(term) {\n\t\t\t\t\tazureOrgArray.push(term);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tresolve([azurePersonArray,azureOrgArray]);\n\t});\n}",
"function Batch() {\n this.seq = 0;\n this.state = 'start';\n this.changes = [];\n this.docs = [];\n}",
"function get_tray_info(rid) {\n var url = 'http://foodbot.ordr.in:8000/TextSearch?rid='+rid+'&target=pizza pie';\n request({\n url: url,\n json: true\n }, function (error, response, body) {\n if (!error && response.statusCode === 200) {\n for(var i=0; i<body.length; i++){\n if(body[i].tray){\n tray = body[i].tray;\n price = body[i].price;\n place_pizza_order(rid,tray,price);\n break;\n }\n }\n }\n else{\n console.log(error);\n }\n });\n\n}",
"entityContentResponse(entity, keyword, responseMessages) {\n\t\tlet moreInfoOpening;\n\t\tconst contents = entity.content\n\t\tfor( let i = 0; i < contents.length; i++ ){\n\t\t\tlet content = contents[i].fields\n\t\t\tif ( content.type === keyword ) {\n\t\t\t\tcontent.content.forEach( function( description ) {\n\t\t\t\t\tdescription = description.fields\n\t\t\t\t\tif( description.body ) {\n\t\t\t\t\t\tresponseMessages.push( new ResponseMessage(0, {speech: description.body} ) );\n\t\t\t\t\t}\n\t\t\t\t\tif( description.media ) {\n\t\t\t\t\t\tresponseMessages.push( new ResponseMessage(3, {imageUrl: \"https:\" + description.media[Math.floor(description.media.length * Math.random())].fields.file.url} ) );\n\t\t\t\t\t}\n\t\t\t\t} )\n\t\t\t}\n\t\t}\n\t\t// si Description et est une collection, montrer les images\n\t\tif( keyword === \"Description\" && entity.isACollection ){\n\t\t\tresponseMessages = this.entityImageResponse( entity, responseMessages )\n\t\t}\n\t\tconsole.log(\"this content for AdditionalContent\", contents);\n\n\t\tfor( let i = 0; i < contents.length; i++ ){\n\t\t\tconsole.log(contents[i].fields.type, keyword);\n\t\t\tif ( keyword !== \"AdditionalContent\" && contents[i].fields.type == \"AdditionalContent\" ) {\n\t\t\t\t moreInfoOpening = this.moreInfosOpeningResponse( entity )\n\t\t\t\t responseMessages.push(moreInfoOpening)\n\t\t\t\t break;\n\t\t\t}\n\t\t}\n\n\t\tconsole.log(\"ENTITY CONTENT RESPONSE\", responseMessages);\n\n\t\treturn responseMessages\n\t}",
"async function fsrv_elig_trxnParser(err, data, pool) {\n let result;\n parser.parseString(data, async function (err, output) {\n result = output;\n });\n let completedNum = 0;\n let bulkContent = [];\n let bulkContentSpot = 0;\n let currentSEQ_ID = 0;\n let curProdArray = [];\n let selectedProduct = \"\";\n let sql = \"\";\n let fundListNum = result.FundSetup.FundList.length;\n for (let a = 0; a < fundListNum; a++) {\n let investProductNum = result.FundSetup.FundList[a].InvstProduct.length;\n for (let b = 0; b < investProductNum; b++) {\n selectedProduct = result.FundSetup.FundList[a].InvstProduct[b];\n sql = \"SELECT FSRV_ID FROM fsrv_prod WHERE (MGMT_CODE='\" +\n result.FundSetup.FundList[a].MgmtCode[0] + \"') AND (FUND_ID='\" +\n selectedProduct.FundID[0] + \"')\";\n currentSEQ_ID = await selectQuery(pool, sql);\n //Adding eligible transactions to the bulk content\n currentObject = selectedProduct.Eligible[0].EligTrxn[0];\n currentKeys = Object.keys(currentObject);\n for (let i = 0; i < currentKeys.length; i++) {\n currentSubObject = currentObject[currentKeys[i]];\n curProdArray = [];\n curProdArray[0] = currentSEQ_ID;\n switch (i) {\n case (0):\n curProdArray[1] = \"B\";\n break;\n case (1):\n curProdArray[1] = \"CR\";\n break;\n case (2):\n curProdArray[1] = \"SI\";\n break;\n case (3):\n curProdArray[1] = \"SO\";\n break;\n case (4):\n curProdArray[1] = \"S\";\n break;\n case (5):\n curProdArray[1] = \"II\";\n break;\n case (6):\n curProdArray[1] = \"IO\";\n break;\n case (7):\n curProdArray[1] = \"EI\";\n break;\n case (8):\n curProdArray[1] = \"EO\";\n break;\n case (9):\n curProdArray[1] = \"LI\";\n break;\n case (10):\n curProdArray[1] = \"LO\";\n break;\n case (11):\n curProdArray[1] = \"F\";\n break;\n case (12):\n curProdArray[1] = \"R\";\n break;\n case (13):\n curProdArray[1] = \"CI\";\n break;\n case (14):\n curProdArray[1] = \"CO\";\n break;\n case (15):\n curProdArray[1] = \"SM\";\n break;\n }\n curProdArray[2] = currentSubObject[0];\n bulkContent[bulkContentSpot] = curProdArray;\n bulkContentSpot++;\n completedNum++;\n }\n if (completedNum >= 1000) {\n await bulkInsert(pool, bulkContent, \"INSERT INTO fsrv_elig_trxn(SEQ_ID, TRXN_TYPE, TRXN_STATUS) values (?,?,?)\");\n bulkContentSpot = 0;\n bulkContent = [];\n completedNum = 0;\n }\n }\n }\n if (bulkContent[0] != null) {\n await bulkInsert(pool, bulkContent, \"INSERT INTO fsrv_elig_trxn(SEQ_ID, TRXN_TYPE, TRXN_STATUS) values (?,?,?)\");\n }\n //console.log(bulkContent);\n return true;\n}",
"function loadBatches(){\n let batch_data = fs.readFileSync('./batches.txt');\n batches = JSON.parse(batch_data);\n //console.log(batches);\n}",
"function readParagraphs() \n{\n if ((xhrContent.readyState === 4) && (xhrContent.status === 200)) \n {\n let MyContent = JSON.parse(xhrContent.responseText);\n let paragraphs = MyContent.paragraphs;\n paragraphs.forEach(function (paragraph) \n {\n let paragraphElements = document.getElementById(paragraph.id);\n //Searches element ids and aligns them with suitable paragraphs in the html\n if(paragraphElements) \n {\n paragraphElements.innerHTML = paragraph.content;\n } \n }, this);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
//Update Meta Data//// ////////////////////// Update to file data. Name update is only triggered on blur event (due to async file to write functionality) The rest is called immediately. TODO: Need to compact DB at some point. TODO: Should refractor the data that's being passed. | function updateFileData(data) {
if (data.field === 'name') {
data.newObj.path = uploadPath + data.newObj.name + data.file.extension;
dbSrvc.update(fileCollection, data);
renameFileToSystem(data.file.path, data.newObj.path);
} else {
dbSrvc.update(fileCollection, data);
}
} | [
"function updateDbEntryAndMove(sFileNameOld, sFileNameNew, fCallback) {\n\t// update database entry\n\tvar sSql = esc(\"UPDATE datasets SET file_name = %Q WHERE file_name = %Q;\",\n\tsFileNameNew, sFileNameOld);\n\t\t\n\tpostgres.query(sSql, function(oErr, oResult) {\n\t\tif(oErr) {fCallback(oErr);}\n\t\t\t\n\t\t// move old file to the archive\n\t\tfs.rename(\n\t\t\tpath.join(config.app.dataset_root_path, sFileNameOld),\n\t\t\tpath.join(config.app.dataset_root_path, \"A\", sFileNameOld),\n\t\tfunction(oErr) {\n\t\t\tif(oErr) {fCalllback(oErr);}\n\t\t\tfCallback();\n\t\t});\n\t});\n}",
"updatePersistedMetadata() {\n this.addon.sourceURI = this.sourceURI.spec;\n\n if (this.releaseNotesURI) {\n this.addon.releaseNotesURI = this.releaseNotesURI.spec;\n }\n\n if (this.installTelemetryInfo) {\n this.addon.installTelemetryInfo = this.installTelemetryInfo;\n }\n }",
"function updateData(){\n\tdataDict.clear();\n\tdataDict.setparse(\"NAMESPACES\", JSON.stringify(namespaces));\n\tdataDict.setparse(\"TRACKS\", tracksDict.stringify());\n\n\tupdateDef();\n}",
"function updateDef(){\n\tinstDef.setparse(\"METADATA\", metaDict.stringify());\n\tinstDef.setparse(\"DATA\", dataDict.stringify());\n}",
"async function updateVidPosition(data) {\n let dir = data[0];\n let file = data[1];\n let hash = data[2];\n let position = data[3];\n // Build and write custom metadata\n if (fs.existsSync(metaPath + dir + '.json')) {\n let rawMetaData = await fsw.readFile(metaPath + dir + '.json', 'utf8');\n var metaData = JSON.parse(rawMetaData);\n } else {\n var metaData = {};\n }\n let metaUpdate = {};\n metaUpdate[hash] = {};\n metaUpdate[hash].video_position = position;\n metaData = merge(metaData, metaUpdate);\n await fsw.writeFile(metaPath + dir + '.json', JSON.stringify(metaData, null, 2));\n getRomData([dir, file]);\n }",
"function updateData() {\n\tPapa.parse('/data/vatsim-data.txt', {\n\t\tdownload: true,\n\t\tdelimiter: ':',\n\t\tcomments: ';',\n\t\tfastMode: true,\n\t\tcomplete: parseData\n\t});\n}",
"function storeMetaData(metaData, file) {\n\tvar json\n\t\t, stream;\n\n\ttry {\n\t\tjson = JSON.stringify(metaData);\n\t\tconsole.log(\"write start:\" + file + \" length:\" + json.length);\n\t\tstream = fs.createWriteStream(file);\n //console.log(file, json);\n\t\tstream.write(json, function(){\n\t\t\tconsole.log(\"write finished:\" + file + \" length:\" + json.length);\n\t\t});\n\t\tstream.end(function(){\n\t\t\tconsole.log(\"stream finished:\" + file + \" length:\" + json.length);\n\t\t});\n\t} catch(e) {\n\t\tconsole.error('Could not save meta data for ' + file);\n\t}\n}",
"function uppdatMemberInAppData(e){\n\n const originalName =e.target.closest('.member-in-list').querySelector('.memebr-name').textContent;\n\n const newList = {\n name:e.target.closest('.member-in-list').querySelector('.new-member-name').value\n };\n\n appData.members.forEach((member)=>{\n if(member.name===originalName){\n member.name=newList.name;\n }\n })\n\n}",
"function saveChangesInFile() {\n var fileId = $(this).attr(\"data-id\");\n var editedText = $(\"textarea.editFile\").val();\n var fileAndParent = fileSystem.findElementAndParentById(fileId);\n var file = fileAndParent.element;\n file.content = editedText;\n var parent = fileAndParent.parent;\n if (parent != null) {\n showFolderOrFileContentById(parent.id);\n }\n }",
"function update_meta_data(form_selector, source_collection, source_node, source_id, source_address, current_address, state, tip) {\n // get form by form selector\n target_collection_selector = form_selector.concat(' .meta-data p.source_collection');\n target_node_selector = form_selector.concat(' .meta-data p.source_node');\n target_ID_selector = form_selector.concat(' .meta-data p.source_id');\n target_address_selector = form_selector.concat(' .meta-data p.source_address');\n target_cc_address_selector = form_selector.concat(' .meta-data p.current_address');\n target_state_selector = form_selector.concat(' .meta-data p.state');\n\n if (source_collection != 'default') {\n $(target_collection_selector).text(source_collection);\n\n }\n if (source_node != 'default') {\n $(target_node_selector).text(source_node);\n\n }\n if (source_id != 'default') {\n $(target_ID_selector).text(source_id);\n\n }\n\n if (source_address != 'default') {\n $(target_address_selector).text(source_address);\n\n }\n\n if (current_address != 'default') {\n $(target_cc_address_selector).text(current_address);\n\n }\n\n\n if (state != 'default') {\n $(target_state_selector).text(StateColor.get_state_name(state));\n text_color = 'text-'.concat(state);\n $(target_state_selector).removeClass(\"text-success text-info text-warning text-danger text-secondary\");\n $(target_state_selector).addClass(text_color);\n }\n\n}",
"function updateData(){\n //Re draw the data\n drawDataOptions();\n\n //Fill in data element values when clicking on a data element in select box.\n $('.data-elements option').click( function(e){\n\n $('input.dataKey').attr('disabled','disabled');\n $('input.dataKey').val($(this).attr(\"dataKey\"));\n $('input.dataValue').val($(this).attr(\"dataValue\"));\n $('button.add-data').text(i18n.gettext('Edit Data'));\n e.stopPropagation();\n\n });\n }",
"function updateInstitutionOwner() \n{\n\tvar dataObjTemp = $('#sensorTagConfigForm').serializeJSON();\n\tvar newMetadata = {}\n\tnewMetadata.institution = dataObjTemp.institution\n\tnewMetadata.owner = dataObjTemp.owner\n\t\n\treadSensorTagConfigFile(updateSensorTagConfigFileMetadata, newMetadata);\n\t\n\talert(\"SensorTag Mapping file updated\")\n}",
"async setBookingFile(event) {\n if (!(bookingTempStore.bookingFile === 'booking/' + event.target.id)) {\n bookingTempStore.bookingFile = 'booking/' + event.target.id;\n bookingTempStore.bookingFileHasChanged = true;\n bookingTempStore.save();\n }\n }",
"function FileInfo(init) {\n init = init || {};\n\n if (init.dir) {\n console.log(\"Creating new file info for \" + init.dir);\n }\n\n /**\n * Private Data\n */\n\n /**\n * The current directory\n */\n var dir = init.dir || '';\n\n /**\n * The current file\n */\n var currFile = init.currFile || undefined;\n\n /**\n * An array of the current files in the directory\n */\n var dirFiles = init.dirFiles || [];\n\n /**\n * Metadata for all the files in the current directory\n */\n var metadata = init.metadata || {};\n\n /**\n * A regular expression containing the types of file extensions that are considered valid for display (i.e .jpg, .gif)\n */\n var validFileTypes = init.validFileTypes || /\\.*/i;\n\n /**\n * The base filename for file info\n */\n var filename = init.filename || 'fileInfo';\n\n /**\n * The file info extension\n */\n var ext = init.ext || '.txt';\n\n /**\n * The path to where file info is stored\n */\n var path = init.path || './data';\n\n /**\n * The index into dirFiles of the current file\n */\n var currFileIndex = -1;\n\n /**\n * A unique identifier for this file info\n */\n if (init.identifier) {\n fastForwardToId(init.identifier);\n }\n\n var identifier = init.identifier || getNextFileId();\n\n /**\n * Private Methods\n */\n \n /**\n * Gets the next available file from the file set.\n * returns true if getNextFile can be called again, false otherwise (i.e. is at the end of the file set)\n */\n var getNextFile = function() {\n if (currFileIndex < dirFiles.length - 1) {\n currFileIndex += 1;\n currFile = dirFiles[currFileIndex];\n return true;\n }\n\n return false;\n }\n\n /**\n * Gets the previous available file from the file set.\n * returns true if getPrevFile can be called again, false otherwise (i.e. is at the beginning of the file set)\n */\n var getPrevFile = function() {\n if (currFileIndex > 0) {\n currFileIndex -= 1;\n currFile = dirFiles[currFileIndex];\n return true;\n }\n\n return false;\n }\n\n /**\n * Uses an array of functions to try and find the next valid file\n *\n * @param {Object[]} funcArr : an array of functions with signature (fileInfo) => bool \n * each function in the array will be called until either the function returns false\n * or the function sets a valid file for fileInfo.\n *\n * @param {string} currFunc : the index into funcArr which indicates the function being called\n *\n * returns : true if getValidFile can be called again, false if it is at the end of the file set\n */\n var getValidFile = function(funcArr, currFunc) {\n currFunc = currFunc || 0;\n var foundValidFileWithFirstFunc = false;\n\n if (currFunc < funcArr.length) {\n // use the current method until it returns false or a valid file\n // type is returned\n do {\n var res = funcArr[currFunc]();\n foundValidFileWithFirstFunc = isValidFile();\n }\n while (res && !foundValidFileWithFirstFunc);\n\n if (!foundValidFileWithFirstFunc) {\n // call the next function to try and find a file\n getValidFile(funcArr, ++currFunc);\n }\n }\n\n return res;\n }\n\n /**\n * Determines if the given file is a valid file type. Uses the current file if\n * filename is null or undefined.\n * @param {string} filename - The filename, if undefined/null the current file is used\n * @returns {boolean} true if the file is a valid type, false otherwise\n */\n var isValidFile = function(filename) {\n filename = (filename || currFile) + \"\";\n return filename.match(validFileTypes) && metadata[filename];\n }\n\n /**\n * Initializes the file meta data, deleting old metadata of non-existant files and reindexing to the current directory\n */\n var initializeMetadata = function() {\n console.log(\"Initializing metadata for directory: \" + dir);\n\n for (var key in metadata) {\n if (metadata.hasOwnProperty(key)) {\n\n // make into a real metadata object\n metadata[key] = fileMetadata(metadata[key]);\n metadata[key].touch = false;\n }\n }\n\n dirFiles = fs.readdirSync(dir);\n\n // make sure we're at the start..\n while (getPrevFile());\n\n // build meta data\n while (getNextFile()) {\n console.log(\"Building metadata for \" + currFile + \" at index \" + currFileIndex + \"\\n\");\n if (!metadata.hasOwnProperty(currFile)) {\n metadata[currFile] = fileMetadata({\n filename: currFile,\n path: dir,\n keep: false,\n index: currFileIndex,\n })\n\n metadata[currFile].touch = true;\n }\n else {\n // update the index\n metadata[currFile].index = currFileIndex;\n metadata[currFile].path = dir;\n metadata[currFile].touch = true;\n }\n }\n\n for (var key in metadata) {\n if (metadata.hasOwnProperty(key)) {\n if (!metadata[key].touch) {\n delete metadata[key];\n }\n else {\n delete metadata[key].touch;\n }\n }\n }\n\n console.log(\"Metadata initialized\");\n console.log(metadata);\n }\n\n /**\n * Return a new object instance\n */\n return {\n\n /**\n * Gets the base directory for this fileInfo object\n */\n getSrcDir: function() {\n return dir;\n },\n\n /**\n * Gets the next valid file from the file set\n *\n * @returns {boolean} true if a valid file was found, false otherwise\n */\n getNextValidFile: function() {\n return getValidFile([getNextFile, getPrevFile]);\n },\n\n /**\n * Gets the previous valid file from the file set\n *\n * @returns {boolean} true if a valid file was found, false otherwise\n */\n getPrevValidFile: function() {\n return getValidFile([getPrevFile, getNextFile]);\n },\n\n /**\n * Retrieves a list of files and sets the next valid file\n */\n initialize: function() {\n try {\n initializeMetadata();\n }\n catch (e) {\n console.log(e)\n return false;\n }\n\n // move to start\n while (getPrevFile());\n\n // move to first valid file\n if (!isValidFile()) {\n this.getNextValidFile();\n }\n\n return true;\n },\n\n /**\n * Determines if the given file is a valid file type.\n * \n * @param {string} filename - the filename to check. Uses the current file if\n * filename is null or undefined.\n */\n isValidFile: function(filename) {\n return isValidFile(filename);\n },\n\n /**\n * Gets the file meta data for the given filename or the current file if filename is undefined or null\n *\n * @param {string} filename - the filename to get meta data for or undefined/null if the current file is to be used\n */\n getFileMetadata: function(filename) {\n filename = filename || currFile;\n console.log(\"Getting metadata for \" + filename);\n return metadata[filename];\n },\n\n /**\n * Updates the metadata for a given filename\n *\n * @param {string} filename - the name of the metadata to update or if undefined/null the current file is used\n * @param {any} updateMeta - an object representing the properties of the metadata to update\n */\n updateFileMetadata: function(filename, updateMeta) {\n filename = filename || currFile;\n console.log(\"Updating metadata for \" + filename);\n\n var myMeta = this.getFileMetadata(filename);\n if (myMeta) {\n console.log(\"Found matching meta \" + myMeta.filename);\n\n for (var key in updateMeta) {\n if (myMeta.hasOwnProperty(key)) {\n myMeta.updateProperty(key, updateMeta[key]);\n }\n }\n }\n },\n\n /**\n * Delete a metadata object from metadata and dirFiles.. not sure what side effects this has..\n */\n deleteFileMetadata: function(deleteMeta) {\n if (deleteMeta) {\n var matchingMeta = metadata[deleteMeta.filename];\n if (matchingMeta) {\n console.log(\"Deleting metadata \" + deleteMeta.filename);\n delete metadata[deleteMeta.filename];\n dirFiles.splice(deleteMeta.index, 1);\n }\n }\n },\n\n /**\n * Saves the file info to a specified location\n * sync: whether to the file is written synchronously (true) or not (false)\n */\n saveFileInfo: function(sync) {\n var content = JSON.stringify({\n \"dir\": dir,\n \"identifier\": identifier,\n \"metadata\": metadata,\n });\n\n var path = this.getPath();\n if (sync) {\n fs.writeFileSync(path, content);\n }\n else {\n fs.writeFile(path, content, function(err) {\n if (err) throw err;\n console.log('Saved fileinfo');\n })\n }\n },\n\n /** \n * Adds a tag to the file's metadata\n */\n addTag: function(filename, tag) {\n var filedata = this.getFileMetadata(filename);\n if (filedata) {\n var index = filedata.tags.indexOf(tag);\n // Only add if it doesn't exist already\n if (index == -1) {\n console.log(\"Adding tag \" + tag + \" for file \" + filedata.filename);\n filedata.tags.push(tag);\n }\n }\n },\n\n /**\n * Removes a tag from the file's metadata\n */\n removeTag: function(filename, tag) {\n var filedata = this.getFileMetadata(filename);\n if (filedata) {\n var index = filedata.tags.indexOf(tag);\n if (index > -1) {\n console.log(\"Removing tag \" + tag + \" for file \" + filedata.filename);\n filedata.tags.splice(index, 1);\n }\n }\n },\n\n /**\n * Gets the path to the file info data\n */\n getPath: function() {\n return path + pathModule.sep + filename + \"_\" + identifier + ext;\n },\n\n /**\n * Gets the path to the given file name so that it can be located on disk.\n */\n getFilePath: function(filename) {\n var meta = this.getFileMetadata(filename);\n return meta.getPath();\n },\n\n /**\n * Returns an array of filtered metadata\n */\n getFilteredMetadata: function(filter) {\n var result = [];\n\n for (var i = 0; i < dirFiles.length; i++) {\n var meta = this.getFileMetadata(dirFiles[i]);\n if (filter(meta)) {\n // pushes a copy\n result.push(fileMetadata(meta));\n }\n }\n\n return result;\n },\n };\n}",
"addFormMetadata() {\n if (this.evidence.metadata) {\n for (let key in this.metadata) {\n let idx = this.evidence.metadata.findIndex(obj => obj.name === key);\n if (idx >= 0) {\n this.evidence.metadata[idx].value += this.metadata.key;\n } else {\n this.evidence.metadata.push(\n {\n 'name' : key,\n 'value': this.metadata[key]\n });\n }\n }\n }\n }",
"function fillFileInfo() {\n /**\n * AJAX for getting the JSON of a calendar, also fills the empty table cells with the info\n */\n $.ajax( {\n type: 'get',\n url: '/fileToJSon',\n success: function(data) {\n var fileTable = document.getElementById(\"FileLogTable\");\n var obj, version, prodID, numEvents, numProps;\n for(var i = 0; i < data.length; i++) {\n obj = JSON.parse(data[i]);\n version = obj.version;\n prodID = obj.prodID;\n numEvents = obj.numEvents;\n numProps = obj.numProps;\n fileTable.rows[i + 1].cells[1].innerHTML = version;\n fileTable.rows[i + 1].cells[2].innerHTML = prodID;\n fileTable.rows[i + 1].cells[3].innerHTML = numEvents;\n fileTable.rows[i + 1].cells[4].innerHTML = numProps;\n }\n populateCalList();\n },\n fail: function() {\n console.log(\"Error!\");\n }\n });\n }",
"update() {\r\n this.updateHeader();\r\n }",
"static update(id, xmlData = null, version = null){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.xmlData = xmlData;\n\t\tkparams.version = version;\n\t\treturn new kaltura.RequestBuilder('metadata_metadata', 'update', kparams);\n\t}",
"function update(params) {\n\t\tvar r = \"\";\t\t\n\t\tif (params) {\n\t\t\tr += \"\\nAtualizando \" + params;\n\t\t\tAPI.loader.downloadPkg(\"custom.\" + params);\n\t\t} else {\n\t\t\tr = \"Erro. Faltou indicar o nome do pacote.\";\n\t\t}\n\t\treturn r;\t\t\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This extracts the vassal array from the GM_value | function getVassals(){
g_vassals = [];
var v = GM_getValue(vassal_key, '').split("||");
if (v=='') return;
for (var i=0; i < v.length; i++){
g_vassals[i] = makeVassal(v[i]);
g_paid[v[i]] = [];
}
} | [
"getValues() {\n return this.getValuesFromElement(this.element);\n }",
"function declaracionArrayCTV(ele, mod, ambi) {\n var encontreError = false;\n //BUSCANDO VECTOR EN LOS AMBITOS SI NO ESTA SE REALIZA DECLARACION\n if (!buscarVariable(ele.identificador)) {\n //VERIFICAR EXPRESIONES\n var v = [];\n //console.log(ele);\n //VERIFICANDO TAMAñO DE VECTOR DE VALORES PARA SABER SI ES NECESARIO ASIGNAR VALORES\n if (ele.valor.length > 0) {\n //console.log(\"traigo valores\");\n //AGREGANDO VALORES\n for (var e of ele.valor) {\n var exp = leerExp(e);\n if (e.tipo != \"Error Semantico\") {\n if (ele.tipoDato == exp.tipo) {\n v.push(exp.valor);\n } else {\n encontreError = true;\n errorSemantico.push({\n tipo: \"Error Semantico\",\n Error:\n \"Problema al insertar valores que no coinciden con tipo de vector \" +\n exp.valor,\n Fila: ele.fila,\n Columna: 0,\n });\n break;\n }\n } else {\n encontreError = true;\n errorSemantico.push(exp);\n break;\n }\n }\n //SI NO SE ENCONTRO UN ERROR SE HACE LA CREACION DE LA VARIABLE\n if (encontreError == false) {\n insertarAmbito({\n tipo: ele.tipo,\n ambito: rNomAmbito(),\n modificador: mod,\n identificador: ele.identificador,\n tipoDato: ele.tipoDato,\n valor: v,\n fila: ele.fila,\n });\n } else {\n errorSemantico.push({\n tipo: \"Error Semantico\",\n Error:\n \"Problema al declarar vector con valores no validos -> \" +\n ele.identificador,\n Fila: ele.fila,\n Columna: 0,\n });\n }\n } else {\n //SI NO ES NECESARIO AGREGAR VALORES\n //console.log(\"no traigo valores\");\n insertarAmbito({\n tipo: ele.tipo,\n ambito: rNomAmbito(),\n modificador: mod,\n identificador: ele.identificador,\n tipoDato: ele.tipoDato,\n valor: v,\n fila: ele.fila,\n });\n }\n } else {\n //SI HAY UNA VARIABLE DECLARADA CON EL MISMO NOMBRE SE REPORTA ERROR\n errorSemantico.push({\n tipo: \"Error Semantico\",\n Error: \"variable ya declarada -> \" + ele.identificador,\n Fila: ele.fila,\n Columna: 0,\n });\n }\n}",
"function obtainChartValues(arg)\r\n{\r\n var script = atob(arg);\r\n var chartId = script.split(\"'\")[1];\r\n var temp = \"\";\r\n var values = new Array();\r\n values[0] = chartId;\r\n \r\n if(chartId == \"ch_cr\" || chartId == \"ch_recycle\" || chartId == \"ch_extensions_all\" || chartId == \"ch_autopay\" || chartId == \"ch_cliques\" || chartId == \"ch_cdd\")\r\n {\r\n temp = script.split(\"data:[\")[1];\r\n temp = temp.substring(0,temp.indexOf(']')).split(',');\r\n }\r\n\r\n return values.concat(temp);\r\n}",
"castToArray(value) {\n if (typeof value === 'number') {\n value = String(value);\n }\n if (typeof value === 'string') {\n return value.split(',').filter((prop) => prop.trim());\n }\n if (Array.isArray(value)) {\n /**\n * This will also convert numeric values to a string. The behavior\n * is same as string flag type.\n */\n return value.map((prop) => String(prop));\n }\n return undefined;\n }",
"function getValues(hm){\n\t//initialize resulting array\n\tvar res = [];\n\t//loop thru keys of associative array\n\tfor( var tmpKey in hm ){\n\t\t//get value\n\t\tvar tmpVal = hm[tmpKey];\n\t\t//make sure that acquired value is not a function\n\t\tif( typeof tmpVal != \"function\" ){\n\t\t\t//add value to resulting array of hashmap values\n\t\t\tres.push(tmpVal);\n\t\t}\t//end if value is not a function\n\t}\t//end loop thru keys of associative array\n\treturn res;\n}",
"get allMillennialVampires() {\n let convertedVamp = [];\n\n if (this.yearConverted > 1980) {\n convertedVamp.push(this);\n }\n\n for (const child of this.offspring) {\n const converted = child.allMillennialVampires;\n convertedVamp = convertedVamp.concat(converted);\n }\n\n return convertedVamp;\n }",
"function getValues()\n{\n X = parseFloat($(\"#XValor\").val());\n fieldData.splice(0);\n let tempArray = [];\n $(body_wrapper).find(\"input\").each( function(a,b,c) {\n tempArray.push($(this).val());\n });\n\n for(let i=0; i < tempArray.length; i++)\n {\n if(tempArray[i].startsWith(\"[log10]\"))\n {\n let valor = Math.log10(parseFloat(tempArray[i].split(\" \").join(\"\").substr(tempArray[i].indexOf(\"]\")+1)));\n fieldData.push( [parseFloat(valor), parseFloat(tempArray[++i])] );\n }else\n {\n fieldData.push( [parseFloat(tempArray[i]), parseFloat(tempArray[++i])] );\n }\n\n } \n}",
"static getCryptoValueArray() {\n var coinArray = [];\n for(var i = 0; i < CryptoExchanger.cryptoExchangerArray.length; i++) {\n coinArray.push({\n name: CryptoExchanger.cryptoExchangerArray[i].getCoinName(),\n population: CryptoExchanger.cryptoExchangerArray[i].getCurrentValue(),\n });\n }\n return coinArray;\n }",
"function pullGVizJSON(gQueryResp) {\r\n var googleRespRegex = /setResponse\\((.*)\\);/g;\r\n var cleanJSON = googleRespRegex.exec(gQueryResp);\r\n jsonResp = JSON.parse(cleanJSON[1], function(key, value) {\r\n return value == null \r\n ? \"\" \r\n : value;\r\n });\r\n return jsonResp;\r\n}",
"get evidence() {\n if (!this._evidence) return [];\n return this._evidence.map((e) => {\n return e.value;\n });\n }",
"array () {\r\n var track = this.track();\r\n\r\n return track ? track.array() : null\r\n }",
"messagesToArray(){\n return Array.from(this.messages.values())\n }",
"getSelectedValues() {\n return this._options.filter(option => option.selected).map(option => option.value);\n }",
"get allMillennialVampires() {\n let vampires = [];\n if (this.yearConverted > 1980) {\n vampires.push(this);\n }\n for (let child of this.offspring) {\n vampires = vampires.concat(child.allMillennialVampires);\n }\n return vampires;\n }",
"function SysFmtStringToArray(){}",
"function InitMvvLva() {\n\tvar Attacker;\n\tvar Victim;\n\t\n\tfor(Attacker = PIECES.wP; Attacker <= PIECES.bK; ++Attacker) {\n\t\tfor(Victim = PIECES.wP; Victim <= PIECES.bK; ++Victim) {\n\t\t\tMvvLvaScores[Victim * 14 + Attacker] = MvvLvaValue[Victim] + 6 - (MvvLvaValue[Attacker]/100); // Gives a higher score the lower the attackers value is\n\t\t}\n\t}\n}",
"static array(v, dynamic) {\n throw new Error(\"not implemented yet\");\n return new Typed(_gaurd, \"array\", v, dynamic);\n }",
"function $GP(v, d, f) {\n var i = 0, p = [];\n while (i < v.length) {\n p[i] = v[i] ? (f[i] ? f[i](v[i]) : v[i]) : d[i];\n i += 1;\n }\n while (i < d.length) {\n p[i] = d[i];\n i += 1;\n }\n return p;\n }",
"values (obj) {\n\t\tlet values = [];\n\t\tfor (let key in obj) {\n\t\t\tvalues.push(obj[key]);\n\t\t}\n\t\treturn values;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Render dc.js elements The makeGraphs function renders all the graphs and crossfilters the returned data from the loadDoc function. This function is called from the loadDoc function. | function makeGraphs(data) {
var ndx = crossfilter(data);
has_website(ndx);
pieChart(ndx);
barChart(ndx);
table(ndx, 10);
dc.renderAll();
$(".dc-select-menu").addClass("custom-select");
} | [
"function draw() {\n\t\tvar nodes = _layoutEngine.getNodes();\n\t\tvar links = _layoutEngine.getLinks();\n\n\t\tvar svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n\t\tsvg.setAttribute('height', _height);\n\t\tsvg.setAttribute('width', _width);\n\n\t\t_container.appendChild(svg);\n\n\t\t_visualization = Visualization;\n\n\t\t_visualization.start({\n\t\t\tpaper: new Snap(svg),\n\t\t\tnodes: nodes,\n\t\t\tlinks: links,\n\t\t\tnormalize: _normalize,\n\t\t\tthreshold: _threshold\n\t\t});\n\t}",
"function renderQueryGraph(dataSourceInfo,resultData){\n \t\n \tvar width = 650;\n var height = 175;\n var cx=0;var cy=0;\n \tvar tmpGY=0,tmpFY=0;\n //Testing Purpose\n Graph.Layout.Fixed = function(graph) {\n this.graph = graph;\n this.layout();\n };\n Graph.Layout.Fixed.prototype = {\n layout: function() {\n this.layoutPrepare();\n this.layoutCalcBounds();\n },\n\n layoutPrepare: function() {\n for (i in this.graph.nodes) {\n var node = this.graph.nodes[i];\n if (node.x) {\n node.layoutPosX = node.x;\n } else {\n node.layoutPosX = 0;\n }\n if (node.y) {\n node.layoutPosY = node.y;\n } else {\n node.layoutPosY = 0;\n }\n }\n },\n\n layoutCalcBounds: function() {\n var minx = Infinity, maxx = -Infinity, miny = Infinity, maxy = -Infinity;\n\n for (i in this.graph.nodes) {\n var x = this.graph.nodes[i].layoutPosX;\n var y = this.graph.nodes[i].layoutPosY;\n \n if(x > maxx) maxx = x;\n if(y > maxy) maxy = y;\n if(y < miny) miny = y;\n if(x < minx) minx = x;\n }\n //minx=20;\n this.graph.layoutMinX = minx;\n this.graph.layoutMaxX = maxx;\n\n this.graph.layoutMinY = miny;\n this.graph.layoutMaxY = maxy;\n }\n };\n //Testing Purpose\t\n var g = new Graph();\n g.edgeFactory.template.style.directed = true;\n\n var render = function(r, n) {\n var label = r.text(0, 30, n.label).attr({opacity:0});\n var yourSet=r.set();\n //the Raphael set is obligatory, containing all you want to display \n var set = r.set().push(\n r.rect(-30, -13, 52, 26)\n .attr({\"fill\": \"#fa8\",\n \"stroke-width\": 2\n , r : 5}))\n .push(r.text(-5, 0, n.label).attr({\"fill\": \"#000000\"}));\n return set;\n \t\t};\n\n \t$.each(datasourceList , function() {\n\t\t// Label Name to Make \"START\"\n\t\tif(this.label==\"DS0\")\n\t\t{\n\t\t\tlabelName=\"START\";\n\t\t\tcx= 0;cy=250;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(this.type==\"Filter\")\n\t\t\t{\n\t\t\t\tcx=50;\n\t\t\t\ttmpFY=tmpFY+75;\n\t\t\t\tcy=tmpFY;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcx=100;\n\t\t\t\ttmpGY=tmpGY+75;\n\t\t\t\tcy=tmpGY;\n\t\t\t}\n\t\t\tlabelName=this.label;\t\n\t\t}\n\t\t// Adding the Node\n\t\tg.addNode(this.label,{x:cx, y:cy, label : labelName, render : render});\n\t\tif (this.edge.length > 0) {\n\t\t\tfor (j=0;j<this.edge.length;j++) {\t\n\t\t\t\t//To make a connection between two nodes\n\t\t\t\tg.addEdge(this.edge[j][0],this.edge[j][1],{stroke : this.color});\n\t\t\t}\n\t\t}\n });\n\t// to make a connection between Result and other Nodes\n\tif(resultData.length>0)\n\t{\n\t\tg.addNode(\"RESULT\",{x:170,y:250,label:\"RESULT\",directed : false, render : render})\n\t\tfor(var k=0; k< resultData.length;k++)\n\t\t{\n\t\t\tg.addEdge(resultData[k],\"RESULT\",{stroke:\"black\"});\t\n\t\t}\n\t}\n\t//Empty the Query Graph Area\t\n $(\"#canvas\").html(\" \");\n //Generating a Query Graph\n //var layouter = new Graph.Layout.Ordered(g, topological_sort(g));\n //Testing Purpose\n var layouter = new Graph.Layout.Fixed(g, topological_sort(g));\n var renderer = new Graph.Renderer.Raphael('canvas', g, width, height);\n}",
"createGraph (){\n let selector = document.getElementById('container-graph');\n let html = '';\n let array = this.arrayDataObjects;\n for (let key in array) {\n this.createElementGraph(selector, `chart-${key}`);\n let title = array[key].title;\n let total = array[key].total;\n let items = array[key].items;\n for (let i in items) {\n this.labels.push(items[i].name);\n this.data.push(items[i].quantity);\n this.colors.push(items[i].color);\n this.createElementInfo(document.getElementById(`container-chart-${key}`), items[i].name, items[i].quantity, items[i].percent, items[i].color);\n }\n this.canvasGraph(this.labels, this.data, `chart-${key}`, this.colors);\n this.labels = [];\n this.data = [];\n this.colors = [];\n }\n\n }",
"function drawGroups(){\nd3.select('div.viz')\n\t//.append('g').attr('id','recessions')\n\t.selectAll('div')\n\t.data(rec)\n\t.enter()\n\t.append('div')\n\t.attr('class','rBox');\t\n\t}//CLOSE drawGroups",
"function generateCharts () {\n\tgenerateTemperatureChart();\n\tgenerateQPFChart();\n\tgenerateDailyWeatherChart($('#weatherChartDays'), 1, 7); //Also reused by zone available water\n\tgenerateProgramsChart();\n\tbindChartsSyncToolTipEvents();\n}",
"function renderNetworkGraph(id, path, collection_type, urlParams) {\n var api = (collection_type == 'symbol' ? 'getSymbolLinks' : 'getDieLinks'); \n\n //alert(urlParams);\n $('#' + id).removeClass('hidden');\n $('#' + id).height(600);\n \n $.get(path + 'apis/' + api, $.param(urlParams, true),\n function (data) {\n var nodeArray = data[ 'nodes'];\n var edgeArray = data[ 'edges'];\n \n const network = new d3plus.Network().config({\n links: edgeArray,\n linkSize: function (edge) {\n return edge.weight;\n },\n nodes: nodeArray,\n groupBy: function (node) {\n return node.side;\n },\n label: function (node) {\n if (node.hasOwnProperty('image')) {\n return node.label + ' <img src=\"' + node.image + '\" style=\"width:16px\"/>';\n } else {\n return node.label;\n }\n \n },\n color: function (node) {\n if (node.side == 'obv' || node.side == 'altSymbol') {\n return '#282f6b'\n } else if (node.side == 'rev') {\n return '#b22200';\n } else if (node.side == 'both') {\n return '#7e12cc';\n } else {\n return '#a8a8a8';\n }\n }\n }).on(\"click\", function (node) {\n window.location.href = node.uri;\n }).select('#' + id).render();\n });\n}",
"function generate3WComponent(config,data,geom){ \n \n $('#title').html(config.title);\n $('#description').html(config.description);\n\n var whoChart = dc.rowChart('#hdx-3W-who');\n var whatChart = dc.rowChart('#hdx-3W-what');\n var whereChart = dc.leafletChoroplethChart('#hdx-3W-where');\n var whereChart2 = dc.leafletChoroplethChart('#hdx-3W-where2');\n var statusChart = dc.rowChart('#hdx-3W-status');\n\n var cf = crossfilter(data);\n\n var whoDimension = cf.dimension(function(d){ return d[config.whoFieldName]; });\n var whatDimension = cf.dimension(function(d){ return d[config.whatFieldName]; });\n var whereDimension = cf.dimension(function(d){ return d[config.whereFieldName]; });\n var whereDimension2 = cf.dimension(function(d){ return d[config.whereFieldName2]; });\n var statusDimension = cf.dimension(function(d){ return d[config.statusFieldName]; });\n\n var whoGroup = whoDimension.group().reduceSum(function(d) {return d.Nov_Change ;});\n var whatGroup = whatDimension.group();\n var whereGroup = whereDimension.group().reduceSum(function(d) {return d.Nov_Change ;});\n var whereGroup2 = whereDimension2.group().reduceSum(function(d) {return d.Nov_Change ;});\n var statusGroup = statusDimension.group().reduceSum(function(d) {return d.Nov_Change ;});\n var all = cf.groupAll();\n\n whoChart.width($('#hdx-3W-who').width()).height(200)\n .dimension(whoDimension)\n .group(whoGroup)\n .elasticX(true)\n .data(function(group) {\n return group.top(5);\n })\n .labelOffsetY(13)\n .colors(config.colors)\n .colorDomain([0,7])\n .colorAccessor(function(d, i){return 2;})\n .xAxis().ticks(5);\n\n whatChart.width($('#hdx-3W-what').width()).height(250)\n .dimension(whatDimension)\n .group(whatGroup)\n .elasticX(true)\n .data(function(group) {\n return group.top(15);\n })\n .labelOffsetY(13)\n .colors(config.colors)\n .colorDomain([0,7])\n .colorAccessor(function(d, i){return 0;})\n .xAxis().ticks(5);\n \n statusChart.width($('#hdx-3W-status').width()).height(200)\n .dimension(statusDimension)\n .group(statusGroup)\n .elasticX(true)\n .data(function(group) {\n return group.top(5);\n }) \n .labelOffsetY(13)\n .colors(config.colors)\n .colorDomain([0,7])\n .colorAccessor(function(d, i){return 6;})\n .xAxis().ticks(5); \n\n dc.dataCount('#count-info')\n .dimension(cf)\n .group(all);\n \n \n whereChart2.width($('#hxd-3W-where2').width()).height(100)\n .dimension(whereDimension2)\n .group(whereGroup2)\n .center([35.8, 38])\n .zoom(7) \n .geojson(geom)\n .colors(['#CCCCCC', config.colors[0],config.colors[1], config.colors[2], config.colors[3]])\n .colorDomain([0, 1, 2, 3, 4])\n .colorAccessor(function (d) {\n if(d>10000){\n return 4;\n } else if (d>3000) {\n return 3;\n } else if (d>1000) {\n return 2;\n } else if (d>1) {\n return 1;\n }\n else {\n return 0;\n }\n }) \n .featureKeyAccessor(function(feature){\n return feature.properties[config.joinAttribute];\n });\n \n whereChart.width($('#hxd-3W-where').width()).height(100)\n .dimension(whereDimension)\n .group(whereGroup)\n .center([35.8, 38])\n .zoom(7) \n .geojson(geom)\n .colors(['#CCCCCC', config.colors[4],config.colors[5], config.colors[6], config.colors[7]])\n .colorDomain([0, 1, 2, 3, 4])\n .colorAccessor(function (d) {\n if(d>4000){\n return 4;\n } else if (d>1000) {\n return 3;\n } else if (d>500) {\n return 2;\n }\n else if (d>1) {\n return 1;\n }\n else {\n return 0;\n }\n }) \n .featureKeyAccessor(function(feature){\n return feature.properties[config.joinAttribute];\n });\n \n \n dc.renderAll();\n \n var g = d3.selectAll('#hdx-3W-who').select('svg').append('g');\n \n g.append('text')\n .attr('class', 'x-axis-label')\n .attr('text-anchor', 'middle')\n .attr('x', $('#hdx-3W-who').width()/2)\n .attr('y', 510)\n .text('XXX1');\n\n var g = d3.selectAll('#hdx-3W-what').select('svg').append('g');\n \n g.append('text')\n .attr('class', 'x-axis-label')\n .attr('text-anchor', 'middle')\n .attr('x', $('#hdx-3W-what').width()/2)\n .attr('y', 250)\n .text('XXX2');\n\n var g = d3.selectAll('#hdx-3W-status').select('svg').append('g');\n\n g.append('text')\n .attr('class', 'x-axis-label')\n .attr('text-anchor', 'middle')\n .attr('x', $('#hdx-3W-status').width()/2)\n .attr('y', 160)\n .text(''); \n\n}",
"function renderChart() {\n requestAnimationFrame(renderChart);\n\n analyser.getByteFrequencyData(frequencyData);\n\n if(colorToggle == 1){\n //Transition the hexagon colors\n svg.selectAll(\".hexagon\")\n .style(\"fill\", function (d,i) { return colorScaleRainbow(colorInterpolateRainbow(frequencyData[i])); })\n }\n\n if(colorToggle == 2){\n //Transition the hexagon colors\n svg.selectAll(\".hexagon\")\n .style(\"fill\", function (d,i) { return colorScaleGray(colorInterpolateGray(frequencyData[i])); })\n }\n }",
"function buildDiagram(ontologyData){\n\n var ontologyData = ontologyData\n // Create the input graph\n var g = new dagreD3.graphlib.Graph({compound:true})\n .setGraph({edgesep: 10, ranksep: 100, nodesep: 50, rankdir: 'LR'})\n .setDefaultEdgeLabel(function() { return {}; });\n\n var CSS_COLOR_NAMES = ['#ff5656', '#ff7d56', '#ff9956', '#ffbb56','#ffda56','#fffc56','#d7ff56','#b0ff56','#7dff56','#56ffc1','#56ffeb','#56e5ff','#56bbff','#5680ff','#a256ff','#cf56ff','#f356ff','#ff56cc', '#ff569f']\n var takenColorId = 5\n var typeColors = {}\n\n ontologyData.entities.forEach(function(e){\n g.setNode(getNameOfUri(e.type), {style:'fill:none;opacity:0;border:none;stroke:none'})\n views.forEach(function(v){\n e.supertypes.forEach(function(s){\n if(s.includes(v)){\n if(!g.nodes().includes(v))\n g.setNode(v, {label: v + ' view', style: 'fill:' + ONTOLOGY_COLORS[v] + ';stroke:' + ONTOLOGY_COLORS[v] , clusterLabelPos: 'top'})\n g.setParent(getNameOfUri(e.type), v)\n }\n }) \n })\n })\n ontologyData.entities.forEach(function(e){\n Object.keys(ontologyCategories).forEach(function(oc){\n e.supertypes.forEach(function(s){\n ontologyCategories[oc].forEach(function(type){\n if(s.includes(type)){\n if(!g.nodes().includes(oc)){\n g.setNode(oc, {label: oc, id:oc, style: 'fill:' + ONTOLOGY_COLORS[oc] + ';stroke:' + ONTOLOGY_COLORS[oc], clusterLabelPos: 'top'})\n }\n parent = g.parent(getNameOfUri(e.type))\n if(parent && parent != oc){\n g.setParent(parent, oc)\n } else {\n g.setParent(getNameOfUri(e.type), oc)\n }\n }\n })\n })\n })\n })\n\n ontologyData.entities.forEach(function(e){ \n g.setNode(getNameOfUri(e.uri), {id: getNameOfUri(e.uri), label: getNameOfEntity(e), style: 'fill:' + getEntityColor(e)})\n g.setParent(getNameOfUri(e.uri), getNameOfUri(e.type))\n })\n\n ontologyData.relations.forEach(function(r){\n g.setEdge(getNameOfUri(r.source), getNameOfUri(r.target), {class:'in-' + getNameOfUri(r.target) + ' out-' + getNameOfUri(r.source), label: r.name, \n style: \"stroke-dasharray: 5,5;\",\n arrowheadStyle: \"fill: #bec6d8; stroke-width:0\", curve: d3.curveBasis})\n })\n\n g.nodes().forEach(function(v) {\n var node = g.node(v);\n node.rx = 5\n node.ry = 5\n });\n\n // Create the renderer\n var render = new dagreD3.render();\n\n // Set up an SVG group so that we can translate the final graph.\n var svg = d3.select(\"#interactive_diagram_svg\"),\n svgGroup = svg.append(\"g\");\n\n // Set up zoom support\n var zoom = d3.zoom()\n .on(\"zoom\", function() {\n svgGroup.attr(\"transform\", d3.event.transform);\n });\n svg.call(zoom).on(\"dblclick.zoom\", null);\n\n // Run the renderer. This is what draws the final graph.\n render(d3.select(\"svg g\"), g);\n\n //Make ontology layers to be positioned behind everything\n Object.keys(ontologyCategories).forEach(function(oc){\n clusters = document.getElementsByClassName('clusters')[0]\n cluster = document.getElementById(oc)\n if(cluster){\n clusters.insertBefore(cluster, clusters.firstChild)\n }\n })\n\n //Lighten the colors a bit\n d3.selectAll('rect').each(function(){\n color = d3.select(this).style('fill')\n recursiveLighten(d3.select(this))\n })\n\n // Lighten clusters\n lightenClusters(0.9)\n\n // Scale the diagram to fit the screen\n scaleDiagram()\n\n // Add nodepath highlight logic\n var toggleOn = ''\n selectedNodeColor = {id:'', color:''}\n highlightNodepathsOnclick()\n\n // Position clusters\n positionClusters()\n\n // Give nodes title and tooltips on hover\n setTitleToNodes()\n tippy('.nodeRect')\n\n // Create dropdown logic for the arrow button beside the node\n setNodeDropdownLogic()\n\n //--------------------------------------------------------------------\n // HELPERS\n //--------------------------------------------------------------------\n\n function lightenClusters(targetL){\n //Lighten the clusters\n d3.selectAll('.cluster')\n .select('rect')\n .each(function(){\n color = d3.select(this).style('fill')\n newColor = tinycolor(color).toHsl()\n newColor.l = targetL\n\n newColorFill = tinycolor(newColor).toHex().toString()\n \n newColor.l = targetL - 0.1\n newColorStroke = tinycolor(newColor).toHex().toString()\n\n d3.select(this).style('fill', newColorFill)\n d3.select(this).style('stroke', newColorStroke)\n })\n }\n\n function recursiveLighten(rect){\n color = rect.style('fill')\n if(tinycolor(rect.style('fill')).isDark()){\n rect.style('fill', tinycolor(color).lighten(10).toString())\n recursiveLighten(rect)\n }\n }\n\n function scaleDiagram(){\n svgBCR = d3.select('#interactive_diagram_svg').node().getBoundingClientRect()\n gBBox = d3.select('.output').node().getBBox()\n abswidth = Math.abs(svgBCR.width - gBBox.width)\n absheight = Math.abs(svgBCR.height - gBBox.height)\n\n if(absheight < abswidth){\n widthScale = svgBCR.width / gBBox.width\n d3.select('.output')\n .style('transform','scale(' + widthScale + ')')\n }else{\n heightScale = svgBCR.height / gBBox.height\n d3.select('.output')\n .style('transform','scale(' + heightScale + ')')\n }\n }\n\n // Helpers for building the graph\n function getRandomColor(){\n takenColorId = (takenColorId+1)%CSS_COLOR_NAMES.length\n return CSS_COLOR_NAMES[takenColorId]\n }\n\n function getNameOfEntity(entity){\n if(entity.label){\n return entity.label\n }else{\n return getNameOfUri(entity.uri)\n }\n }\n\n function getPrettyName(string){\n name = ''\n for(i in string){\n if(i > 0 && string[i] == string[i].toUpperCase()){\n name += ' ' + string[i].toLowerCase()\n }else if (i == 0 && string[i] == string[i].toLowerCase()){\n name += string[i].toUpperCase()\n }else{\n name += string[i]\n }\n }\n return name\n }\n\n function getSubTree(startEntityUri, list, forward){\n startEntityUri = getNameOfUri(startEntityUri)\n ontologyData.relations.forEach(function(rel){\n if(forward) {\n if(getNameOfUri(rel.source) == startEntityUri){\n getSubTree(rel.target, list, true)\n list.push(rel)\n }\n }else{\n if(getNameOfUri(rel.target) == startEntityUri){\n getSubTree(rel.source, list, false)\n list.push(rel)\n }\n }\n })\n return list\n }\n\n // Helpers for making the graph pretty\n function setTitleToNodes(){\n ontologyData.entities.forEach(function(e){\n d3.select('#' + getNameOfUri(e.uri))\n .select('.nodeRect')\n .attr('title', formatToolTip(e))\n })\n }\n\n function formatToolTip(entity){\n description = entity.dataTypeProperties[0]\n if(description && getNameOfUri(description[0]).includes('Description')){\n description = description[1]\n } else {\n description = ''\n }\n if(description.length > 200){\n description = description.substring(0,200) + '...'\n }\n tooltip='<p><b>Type: </b>' + getPrettyName(getNameOfUri(entity.type)) + '</p>' +\n '<p><b>Name: </b>' + getNameOfEntity(entity) + '</p>' +\n '<p>' + description + '</p>'\n return tooltip\n }\n\n function highlightRelations(entityName){ \n relations = getSubTree(entityName, [], true)\n Array.prototype.push.apply(relations, getSubTree(entityName, [], false))\n\n relations.forEach(function(rel){\n inClass = '.in-' + getNameOfUri(rel.target)\n outClass = '.out-' + getNameOfUri(rel.source)\n\n d3.select(inClass + outClass)\n .select('path.path')\n .transition()\n .duration(250)\n .style(\"stroke\", \"#ff5b5b\")\n .style(\"stroke-dasharray\", \"\")\n\n d3.select(inClass + outClass)\n .select('marker')\n .select('path')\n .transition()\n .duration(250)\n .style(\"fill\", \"#ff5b5b\") \n })\n }\n\n function unlightRelations(){\n d3.selectAll('.edgePath')\n .select('path.path')\n .transition()\n .duration(200)\n .style(\"stroke-dasharray\", \"5, 5\")\n .duration(200)\n .style(\"stroke\", \"#929db5\")\n\n d3.selectAll('.edgePath')\n .select('marker')\n .select('path')\n .transition()\n .duration(200)\n .style(\"fill\", \"#929db5\") \n }\n\n function positionClusters(){\n largestYtop = 0\n largestYbot = 0\n \n d3.selectAll('.cluster').each(function(){\n currentBBox = d3.select(this).node().getBBox()\n if(currentBBox.y < largestYtop){\n largestYtop = currentBBox.y\n }\n if(currentBBox.height + Math.abs(currentBBox.y) > largestYbot){\n largestYbot = currentBBox.height + Math.abs(currentBBox.y)\n }\n })\n largestYbot = largestYbot - Math.abs(largestYtop) + 100\n \n clusterTransform = d3.select('.cluster')\n .attr('transform')\n .replace('translate(', '')\n .replace(')','')\n .split(',')\n clusterTransformY = parseFloat(clusterTransform[1])\n \n d3.selectAll('.cluster').each(function(){ \n currentTransform = d3.select(this)\n .attr('transform')\n .replace(/,\\d+\\.*\\d+/, ',' + clusterTransformY) \n\n d3.select(this)\n .attr('transform', currentTransform)\n \n // Make cluster rects wider\n d3.select(this)\n .select('rect')\n .attr('x', (parseFloat(d3.select(this)\n .select('rect')\n .attr('x')) - 25) + 'px')\n\n d3.select(this)\n .select('rect')\n .attr('width', (parseFloat(d3.select(this)\n .select('rect')\n .attr('width')) + 50) + 'px')\n })\n \n d3.selectAll('.cluster')\n .select('rect').attr('y', largestYtop - 50)\n .attr('height',largestYbot)\n\n\n //Make ontology category clusters bigger\n Object.keys(ontologyCategories).forEach(function(oc){\n cluster = d3.select('#' + oc)\n heightDelta = 150\n if(!cluster.empty()){\n console.log(cluster)\n clusterHeight = parseFloat(cluster.select('rect').attr('height'))\n clusterY = parseFloat(cluster.select('rect').attr('y'))\n cluster.select('rect')\n .attr('height', clusterHeight + heightDelta) \n .attr('y', clusterY - heightDelta/2) \n }\n })\n\n // Style labels\n d3.selectAll('.cluster')\n .each(function(c){\n clusterBBox = d3.select(this).node().getBBox()\n labelBBox = d3.select(this).select('.label').node().getBBox()\n\n // Center labels in cluster\n d3.select(this)\n .select('.label')\n .select('g')\n .attr('transform', 'translate(' + labelBBox.x + ',' + (clusterBBox.y + 10) + ')')\n \n // Set color of label\n color = d3.select(this).select('rect').style('stroke')\n d3.select(this)\n .select('text')\n .style('fill', tinycolor(color).darken(25).toString())\n })\n\n //Label onclick\n d3.selectAll('.cluster')\n .select('.label')\n .on('click', function(){\n rect = d3.select(this.parentNode).select('rect')\n parent = d3.select(this.parentNode)\n\n if(parent.classed('selected')){\n d3.select(this.parentNode)\n .classed('selected', false)\n .classed('unselected', true)\n\n }else{\n d3.selectAll('.selected')\n .each(function(){\n d3.select(this).classed('selected', false)\n d3.select(this).classed('unselected', true)\n \n })\n\n parent\n .classed('unselected', false)\n .classed('selected', true)\n }\n })\n\n d3.selectAll('.cluster')\n .select('rect')\n .attr('rx',50)\n .attr('ry',50)\n }\n\n //Creating the logic for node actions\n function highlightNodepathsOnclick(){\n //ADD ACTIONS THE NODE RECTANGLES\n d3.selectAll('.node')\n .select('rect')\n .attr('class', 'nodeRect')\n .on('click', function(){\n thisClass = d3.select(this.parentNode).attr('id')\n\n if(thisClass == toggleOn){\n unlightRelations()\n toggleOn = ''\n }else{\n toggleOn = thisClass\n unlightRelations()\n highlightRelations(thisClass)\n }\n\n style = d3.select(this)\n .attr('style')\n if(style != 'fill:#ffef68'){\n if (selectedNodeColor['id']){\n d3.select('#' + selectedNodeColor['id'])\n .select('rect')\n .attr('style', 'fill:' + selectedNodeColor['color'])\n }\n selectedNodeColor['color'] = style.substring(5, style.length)\n selectedNodeColor['id'] = d3.select(this.parentNode)\n .attr('id')\n d3.select(this)\n .attr('style', 'fill:#ffef68')\n \n }else{\n d3.select('#' + selectedNodeColor['id'])\n .select('rect')\n .attr('style', 'fill:' + selectedNodeColor['color'])\n selectedNodeColor['color'] = ''\n selectedNodeColor['id'] = ''\n }\n })\n }\n\n function setNodeDropdownLogic(){\n d3.selectAll('.node').each(function(node){\n //CREATE DROP-DOWN BUTTON FOR NODES\n nodeWidth = parseFloat(\n d3.select(this)\n .select('rect')\n .attr('width'))\n nodeHeight = parseFloat(\n d3.select(this)\n .select('rect')\n .attr('height'))\n rectColor = d3.select(this)\n .select('rect')\n .style('fill')\n \n d3.select(this)\n .select('rect')\n .attr('width', nodeWidth + nodeHeight)\n\n d3.select(this)\n .append(\"rect\")\n .attr('class', 'nodeButton')\n .attr('width', nodeHeight)\n .attr('height', nodeHeight)\n .attr('x', nodeWidth/2)\n .attr('y', -nodeHeight/2)\n .attr('rx', '5')\n .attr('ry', '5')\n .style('stroke', 'none')\n .style('cursor', 'pointer')\n .style('opacity', '0')\n .on('mouseover', function(){\n d3.select(this)\n .style('fill','white')\n .transition()\n .duration(200)\n .style('opacity','0.7')\n }).on('mouseout', function(){\n d3.select(this)\n .transition()\n .duration(200)\n .style('opacity','0')\n }).on('click', function(){\n nodeWidth = parseFloat(\n d3.select(this.parentNode)\n .select('.nodeRect')\n .attr('width'))\n nodeHeight = parseFloat(\n d3.select(this.parentNode)\n .select('.nodeRect')\n .attr('height'))\n \n //CREATE DROPDOWN RECTANGLE\n //Put the node first in the list to avoid overlapping\n this.parentNode.parentNode.appendChild(this.parentNode)\n\n function hideDropdown(){\n d3.selectAll('.node_dropdown')\n .transition()\n .duration(200)\n .attr('height', '1')\n .transition()\n .duration(200)\n .attr('width','0')\n .remove()\n \n d3.selectAll('.drop-down_arrow')\n .transition()\n .duration(100)\n .style('fill', '#2c4c66')\n .style('stroke', '#2c4c66')\n\n d3.selectAll('.drop-down_item')\n .remove()\n\n d3.selectAll('.drop-down_item_text')\n .remove()\n }\n\n if(d3.select(this.parentNode).select('.node_dropdown').empty()){\n\n hideDropdown()\n //Create drop-down box\n d3.select(this.parentNode)\n .append('rect')\n .attr('class', 'node_dropdown')\n .attr('x', (nodeWidth/2+nodeHeight/2)+20)\n .attr('y', -nodeHeight/2)\n .attr('width', '0')\n .attr('height', '1')\n .transition()\n .duration(200)\n .attr('width', '160px')\n .transition()\n .duration(200)\n .attr('height', nodeHeight*3)\n .attr('rx','5')\n .attr('ry','5')\n .style('stroke', '#424242')\n .style('fill', '#424242')\n \n //Drop-down arrow change to white\n d3.select(this.parentNode)\n .select('.drop-down_arrow')\n .transition()\n .duration(250)\n .style('fill', 'white')\n .style('stroke', 'white')\n\n //Create drop-down items\n item_counter = 0\n function addDropdownItem(parent, name){\n d3.select(parent.parentNode)\n .append('rect')\n .attr('class', 'drop-down_item')\n .attr('id', 'drop_down_item' + item_counter)\n .attr('x', (nodeWidth/2+nodeHeight/2)+20)\n .attr('y', (-nodeHeight/2 + nodeHeight*item_counter))\n .attr('width', '160px')\n .attr('height', nodeHeight)\n .attr('rx', 5)\n .attr('ry', 5)\n .style('stroke', 'none')\n .style('fill', 'gray')\n .attr('opacity', '0')\n .on('mouseover', function(){\n d3.select(this)\n .transition()\n .duration(200)\n .style('opacity', '1')\n })\n .on('mouseout', function(){\n d3.select(this)\n .transition()\n .duration(200)\n .style('opacity', '0')\n })\n .on('click', function(){\n createPopup()\n })\n\n d3.select(parent.parentNode)\n .insert('text')\n .attr('class', 'drop-down_item_text')\n .attr('id', 'drop-down_item_text' + item_counter)\n .attr('x', (9 + nodeWidth/2+nodeHeight/2)+20)\n .attr('y', (6 + nodeHeight*item_counter))\n .style('font-size','14px')\n .style('fill','white')\n .style('stroke','none')\n .style('opacity', '0')\n .transition()\n .delay(300)\n .duration(200)\n .style('opacity', '1')\n \n d3.select(parent.parentNode)\n .select('#drop-down_item_text' + item_counter)\n .html(name)\n\n item_counter++\n }\n\n addDropdownItem(this, 'View diagrams')\n addDropdownItem(this, 'Explain entity')\n addDropdownItem(this, 'Explain relations')\n\n }else{\n hideDropdown() \n }\n\n })\n \n // CREATE SVG ARROW\n x = parseFloat(\n d3.select(this)\n .select('.nodeButton')\n .attr('x'))\n y = parseFloat(\n d3.select(this)\n .select('.nodeButton')\n .attr('y'))\n width = parseFloat(\n d3.select(this)\n .select('.nodeButton')\n .attr('width'))\n points = (x + width/2) + ',' + (y + 5 + nodeHeight/2) + ' ' + (x + width/2) + ',' + (y - 5 + nodeHeight/2) + ' ' + (x + 5 + width/2) + ',' + (y + nodeHeight/2)\n \n d3.select(this)\n .append(\"polygon\")\n .attr('class', 'drop-down_arrow')\n .attr('points', points)\n .style('fill','#2c4c66')\n .style('stroke-width', '1px')\n .style('stroke', '#2c4c66')\n .style('pointer-events', 'none')\n })\n\n }\n\n function createPopup(){\n width = 80\n height = 90\n d3.select('body')\n .append('div')\n .attr('id', 'popup-background')\n .attr('class', 'popup')\n .style('width', '100%')\n .style('height', '100%')\n .style('opacity','0.3')\n .style('position', 'absolute')\n .style('background-color','black')\n \n d3.select('#popup-background')\n .on('click', function(){\n d3.selectAll('.popup')\n .remove()\n })\n\n d3.select('body')\n .append('div')\n .attr('id', 'popup-view')\n .attr('class','w3-light-gray w3-border w3-border-indigo popup')\n .style('position','absolute')\n .style('left', '50%')\n .style('bottom', '50%')\n .style('transform', 'translate(-50%,50%)')\n .style('width', width + \"%\")\n .style('height', height + \"%\")\n \n\n d3.select('#popup-view')\n .html(getPopup())\n\n var s = document.createElement('script')\n s.src = 'static/popup-graph.js'\n\n document.getElementById('popup-view').appendChild(s)\n\n d3.select('#close_popup')\n .on('click', function(){\n d3.selectAll('.popup')\n .remove()\n })\n }\n\n function getPopup(){\n string = \n \"<button class='w3-white w3-button w3-border-right roundedTopCorners' style='height:5%;float:left;font-size:13px'>Figure 3_10</button>\" +\n \"<button class='w3-button w3-light-grey w3-border-right roundedTopCorners' style='height:5%;background-color:#b8dced;float:left;font-size:13px'>Figure_3_4</button>\" +\n \"<button class='w3-button w3-light-grey w3-border-right roundedTopCorners' style='height:5%;background-color:#b8dced;float:left;font-size:13px'>Figure_3_2</button>\" +\n \"<button id='close_popup' class='w3-light-grey w3-button w3-text-indigo roundedTopCorners w3-border-right w3-border-top' style='height:5%;margin:0;float:right'><b>X</b></button>\" +\n \"<a href='popup-window.html' class='w3-button roundedTopCorners w3-border-right' target='_blank' style='height:5%;margin:0;float:right'>Open in new window</a>\" +\n \"<div class='w3-white w3-border-bottom' style='width:100%;height:5%;font-size:13px'></div> \" +\n \"<div id ='diagram_image_div' class='w3-white w3-border-right' style='width:65%;height:95%;float:left;position:relative'> \" +\n \" <svg id='diagram_image' height='100%' width='100%'></svg>\"+\n \"</div>\" +\n \"<div style='height:95%;padding-top:16px;padding-bottom:16px;'>\" +\n \"<div class='w3-container w3-light-gray' style='overflow-y:scroll;width:33.7%;height:95%;float:left;'>\" +\n \" <h2>View diagrams</h2>\" +\n \" <hr>\" +\n \" <h3>Figure 3.10: Class diagram of the system</h3>\" +\n \" <p>\" +\n \" The conceptual model of this project revolves around the cart concept, while all other system elements are there to provide the required information to the cart, as seen in the class diagram below (Figure 3.10). Products are related to carts as a list of product variants, forming line items. Variant is a concept to define the part of the product that contains the particular characteristics of it, such as color or size, even having sometimes a different price. Therefore every product has at least one variant, each one with different price or attributes. Similarly, a cart can be associated with one of the shipping methods available in the system, resulting in a shipping item, necessary to manage taxes. \" +\n \" </p>\" +\n \" <p>\" +\n \" Both products and shipping methods have a particular tax category, that can be variable for products and fixed in the case of shipping. When one of these elements are added to the cart, a tax rate is assigned to the item according to this tax category and the shipping address of the cart. As mentioned above carts can have a shipping address, but can have as well a billing address. \" +\n \" </p>\" +\n \" <p>\" +\n \" A cart can belong to a registered customer, otherwise it is considered to have an anonymous customer. Once the checkout is finished a cart becomes an order, with information about the current payment, shipping and order status. If the customer was not anonymous, this order will be associated with that customer, along with any of his previous orders. Every customer can also have a list of addresses comprising the address book.\" +\n \" </p>\" +\n \" <p>Products, addresses and shipping methods can change or disappear over time, but the orders associated with them must stay in the system for an indefinite period of time, having exactly 44 the original information. To solve this issue, cart is not related to the original instances, but to instances that were created exclusively for this particular cart as a snapshot of those original instances. </p>\" +\n \" <p>While the current cart may optionally have associated information, this information is mandatory in an order instance. For simplicity, the conceptual model only accepts product and shipping prices that do not include taxes. Allowing taxes in prices can be achieved by simply adding a boolean attribute indicating whether the price in question has taxes included or not. So assuming that taxes are not included, the net total price in the cart must be the sum of all the line item prices (i.e. the quantity in each line item multiplied by the corresponding variant price) associated with it, plus the price of the shipping method selected. In order to calculate the gross total price, taxes must be added up to this resulting net price. Taxes are calculated multiplying the price of each shipping or line item by its corresponding tax rate. </p>\" +\n \" <p>Lastly when the shipping address is set in the cart, all tax rates from shipping and line items are calculated. Only those products that include a tax category corresponding to the zone (e.g. state, country) of the shipping address can be part of the cart. Missing the tax category means that the price cannot be calculated, thus the product is not available in that zone.</p>\" +\n \"</div>\" +\n \"</div>\" +\n \"</div>\" \n return string\n }\n\n}",
"function buildCharts(formatedData) {\n buildRevenueChart(formatedData);\n buildGenderChart(formatedData);\n} // END: bulidCharts",
"function createChart(element_selector, params)\n{\n title_position = 0;\n // Анализируем входные параметры\n //--------------------------------------------------------------------------\n // 1. Формируем параметры запросов\n requestParams.instrument_id = params.histo.instrument_id;\n requestParams.price_id = params.id;\n //--------------------------------------------------------------------------\n dim = {\n width: 640, height: 480,\n margin: { top: 20, right: 50, bottom: 30, left: 50 },\n ohlc: { height: 305 },\n indicator: { height: 65, padding: 5 }\n };\n\n // Подключаемся к DIV\n // и берем размеры у него\n // Высоты графиков:\n // *candle - 74%\n // *macd - 13%\n // *rsi - 13%\n div = d3.select(element_selector);\n dim.width = parseInt(div.style(\"width\"));\n dim.height = parseInt(div.style(\"height\"));\n dim.ohlc.height = dim.height - (dim.indicator.height*2) - (dim.margin.top*2) - (dim.indicator.padding);\n\n dim.plot = {\n width: dim.width - dim.margin.left - dim.margin.right,\n height: dim.height - dim.margin.top - dim.margin.bottom\n };\n dim.indicator.top = dim.ohlc.height+dim.indicator.padding;\n dim.indicator.bottom = dim.indicator.top+dim.indicator.height+dim.indicator.padding;\n\n // Рисуем график по всей высоте\n if ((chartOptions.macdVisible == false) && (chartOptions.rsiVisible == false))\n {\n dim.ohlc.height = dim.height - (dim.margin.top*2) - (dim.indicator.padding);\n } else\n if (((chartOptions.macdVisible == true) && (chartOptions.rsiVisible == false)) ||\n ((chartOptions.macdVisible == false) && (chartOptions.rsiVisible == true)))\n {\n dim.indicator.height = dim.indicator.height*2;\n }\n\n indicatorTop = d3.scaleLinear()\n .range([dim.indicator.top, dim.indicator.bottom]);\n\n// parseDate = d3.timeParse(\"%d-%b-%y\");\n // Преобразование даты и времени из формата\n // \"YYYYMMDDHHMM\" в нужный формат для графика\n// parseDate = d3.timeParse(\"%Y%m%d%H%M%Z\");\n\n zoom = d3.zoom()\n .on(\"zoom\", zoomed);\n\n x = techan.scale.financetime()\n .range([0, dim.plot.width]);\n\n y = d3.scaleLinear()\n .range([dim.ohlc.height, 0]);\n\n\n yPercent = y.copy(); // Same as y at this stage, will get a different domain later\n\n yVolume = d3.scaleLinear()\n .range([y(0), y(0.2)]);\n\n // Настраиваем тип графика(OHLC, Candle, ...)\n switch(chartOptions.type)\n {\n case 0:\n candlestick = techan.plot.ohlc()\n .xScale(x)\n .yScale(y);\n break;\n case 1:\n candlestick = techan.plot.candlestick()\n .xScale(x)\n .yScale(y);\n break;\n case 2:\n candlestick = techan.plot.close()\n .xScale(x)\n .yScale(y);\n }\n/* candlestick = techan.plot.candlestick()\n .xScale(x)\n .yScale(y);\n*/\n sma0 = techan.plot.sma()\n .xScale(x)\n .yScale(y);\n\n sma1 = techan.plot.sma()\n .xScale(x)\n .yScale(y);\n\n ema2 = techan.plot.ema()\n .xScale(x)\n .yScale(y);\n\n volume = techan.plot.volume()\n .accessor(candlestick.accessor()) // Set the accessor to a ohlc accessor so we get highlighted bars\n .xScale(x)\n .yScale(yVolume);\n\n trendline = techan.plot.trendline()\n .xScale(x)\n .yScale(y);\n\n supstance = techan.plot.supstance()\n .xScale(x)\n .yScale(y);\n\n xAxis = d3.axisBottom(x);\n\n // Курсор по оси OX (текст)\n timeAnnotation = techan.plot.axisannotation()\n .axis(xAxis)\n .orient('bottom')\n .format(d3.timeFormat('%Y-%m-%d'))\n .width(65)\n .translate([0, dim.ohlc.height]);\n\n yAxis = d3.axisRight(y);\n\n ohlcAnnotation = techan.plot.axisannotation()\n .axis(yAxis)\n .orient('right')\n .format(d3.format(',.2f'))\n .translate([x(1), 0]);\n\n closeAnnotation = techan.plot.axisannotation()\n .axis(yAxis)\n .orient('right')\n .accessor(candlestick.accessor())\n .format(d3.format(',.2f'))\n .translate([x(1), 0]);\n\n percentAxis = d3.axisLeft(yPercent)\n .tickFormat(d3.format(\"+.1%\"));\n\n\n percentAnnotation = techan.plot.axisannotation()\n .axis(percentAxis)\n .orient('left');\n\n volumeAxis = d3.axisRight(yVolume)\n .ticks(3)\n .tickFormat(d3.format(\",.3s\"));\n\n volumeAnnotation = techan.plot.axisannotation()\n .axis(volumeAxis)\n .orient(\"right\")\n .width(35);\n//------------------------------------------------------------------------------\nvar index=0;\n// 1. Включены оба графика\nif ((chartOptions.macdVisible == true) && (chartOptions.rsiVisible == true))\n{\n index = 1;\n} else\n// 2. Выключен график RSI\nif ((chartOptions.macdVisible == true) && (chartOptions.rsiVisible == false))\n{\n index = 1;\n} else\n// 3. Выключен график MACD\nif ((chartOptions.macdVisible == false) && (chartOptions.rsiVisible == true))\n{\n index = 0;\n} else\n// 4. Выключены оба графика\nif ((chartOptions.macdVisible == false) && (chartOptions.rsiVisible == false))\n{\n index = 1;\n}\n macdScale = d3.scaleLinear()\n .range([indicatorTop(0)+dim.indicator.height, indicatorTop(0)]);\n\n rsiScale = d3.scaleLinear()//macdScale.copy()\n .range([indicatorTop(index)+dim.indicator.height, indicatorTop(index)]);\n//------------------------------------------------------------------------------\n/* macdScale = d3.scaleLinear()\n .range([indicatorTop(0)+dim.indicator.height, indicatorTop(0)]);\n\n rsiScale = d3.scaleLinear()\n .range([indicatorTop(0)+dim.indicator.height, indicatorTop(0)]);\n*/\n macd = techan.plot.macd()\n .xScale(x)\n .yScale(macdScale);\n\n macdAxis = d3.axisRight(macdScale)\n .ticks(3);\n\n macdAnnotation = techan.plot.axisannotation()\n .axis(macdAxis)\n .orient(\"right\")\n .format(d3.format(',.2f'))\n .translate([x(1), 0]);\n\n macdAxisLeft = d3.axisLeft(macdScale)\n .ticks(3);\n\n macdAnnotationLeft = techan.plot.axisannotation()\n .axis(macdAxisLeft)\n .orient(\"left\")\n .format(d3.format(',.2f'));\n\n rsi = techan.plot.rsi()\n .xScale(x)\n .yScale(rsiScale);\n\n rsiAxis = d3.axisRight(rsiScale)\n .ticks(3);\n\n rsiAnnotation = techan.plot.axisannotation()\n .axis(rsiAxis)\n .orient(\"right\")\n .format(d3.format(',.2f'))\n .translate([x(1), 0]);\n\n rsiAxisLeft = d3.axisLeft(rsiScale)\n .ticks(3);\n\n rsiAnnotationLeft = techan.plot.axisannotation()\n .axis(rsiAxisLeft)\n .orient(\"left\")\n .format(d3.format(',.2f'));\n\n ohlcCrosshair = techan.plot.crosshair()\n .xScale(timeAnnotation.axis().scale())\n .yScale(ohlcAnnotation.axis().scale())\n .xAnnotation(timeAnnotation)\n .yAnnotation([ohlcAnnotation, volumeAnnotation])\n// .yAnnotation([ohlcAnnotation, percentAnnotation, volumeAnnotation])\n .verticalWireRange([0, dim.plot.height]);\n\n macdCrosshair = techan.plot.crosshair()\n .xScale(timeAnnotation.axis().scale())\n .yScale(macdAnnotation.axis().scale())\n .xAnnotation(timeAnnotation)\n .yAnnotation([macdAnnotation, macdAnnotationLeft])\n .verticalWireRange([0, dim.plot.height]);\n\n rsiCrosshair = techan.plot.crosshair()\n .xScale(timeAnnotation.axis().scale())\n .yScale(rsiAnnotation.axis().scale())\n .xAnnotation(timeAnnotation)\n .yAnnotation([rsiAnnotation, rsiAnnotationLeft])\n .verticalWireRange([0, dim.plot.height]);\n\n svg = div.append(\"svg\")\n .attr(\"width\", dim.width)\n .attr(\"height\", dim.height);\n\n draw_percent_bar(pbar_value);\n\n defs = svg.append(\"defs\");\n\n//-----------------------------------------------------------------------------------\n defs.append(\"clipPath\")\n .attr(\"id\", \"ohlcClip\")\n .append(\"rect\")\n .attr(\"x\", 0)\n .attr(\"y\", 0)\n .attr(\"width\", dim.plot.width)\n .attr(\"height\", dim.ohlc.height);\n//------------------------------------------------------------------------------\n// 1. Включены оба графика\nif ((chartOptions.macdVisible == true) && (chartOptions.rsiVisible == true))\n{\n defs.selectAll(\"indicatorClip\").data([0, 1])\n .enter()\n .append(\"clipPath\")\n .attr(\"id\", function(d, i) { return \"indicatorClip-\" + i; })\n .append(\"rect\")\n .attr(\"x\", 0)\n .attr(\"y\", function(d, i) { return indicatorTop(i); })\n .attr(\"width\", dim.plot.width)\n .attr(\"height\", dim.indicator.height);\n} else\n// 2. Выключен график RSI\nif ((chartOptions.macdVisible == true) && (chartOptions.rsiVisible == false))\n{\n defs.selectAll(\"indicatorClip\").data([0, 1])\n .enter()\n .append(\"clipPath\")\n .attr(\"id\", function(d, i) { return \"indicatorClip-\" + i; })\n .append(\"rect\")\n .attr(\"x\", 0)\n .attr(\"y\", function(d, i) { return indicatorTop(i); })\n .attr(\"width\", dim.plot.width)\n .attr(\"height\", dim.indicator.height);\n} else\n// 3. Выключен график MACD\nif ((chartOptions.macdVisible == false) && (chartOptions.rsiVisible == true))\n{\n defs.selectAll(\"indicatorClip\").data([0, 1])\n .enter()\n .append(\"clipPath\")\n .attr(\"id\", function(d, i) { return \"indicatorClip-\" + i; })\n .append(\"rect\")\n .attr(\"x\", 0)\n .attr(\"y\", function(d, i) { return indicatorTop(0); })\n .attr(\"width\", dim.plot.width)\n .attr(\"height\", dim.indicator.height);\n} else\n// 4. Выключены оба графика\nif ((chartOptions.macdVisible == false) && (chartOptions.rsiVisible == false))\n{\n defs.selectAll(\"indicatorClip\").data([0, 1])\n .enter()\n .append(\"clipPath\")\n .attr(\"id\", function(d, i) { return \"indicatorClip-\" + i; })\n .append(\"rect\")\n .attr(\"x\", 0)\n .attr(\"y\", function(d, i) { return indicatorTop(i); })\n .attr(\"width\", dim.plot.width)\n .attr(\"height\", dim.indicator.height);\n}\n\n\n//------------------------------------------------------------------------------\n svg = svg.append(\"g\")\n .attr(\"transform\", \"translate(\" + dim.margin.left + \",\" + dim.margin.top + \")\");\n\n // Формируем название графика\n draw_title();\n // Рисуем горизонтальную сетку\n for (var i=1; i<(dim.ohlc.height/chartOptions.grid_x_step); i++)\n {\n svg.append('line')\n .attr(\"class\", \"grid\")\n .attr(\"x1\", 0)\n .attr(\"y1\", (i*chartOptions.grid_x_step + 0.5))\n .attr(\"x2\", (dim.width - 100))\n .attr(\"y2\", (i*chartOptions.grid_x_step + 0.5));\n }\n\n // Рисуем вертикальную сетку\n for (var i=0; i<((dim.width-100)/chartOptions.grid_y_step); i++)\n {\n svg.append('line')\n .attr(\"class\", \"grid\")\n .attr(\"x1\", (i*chartOptions.grid_y_step))\n .attr(\"y1\", 0)\n .attr(\"x2\", (i*chartOptions.grid_y_step))\n .attr(\"y2\", dim.ohlc.height);\n }\n\n // Рисуем ось OX(Дата и время)\n svg.append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", \"translate(0,\" + dim.ohlc.height + \")\");\n\n ohlcSelection = svg.append(\"g\")\n .attr(\"class\", \"ohlc\")\n .attr(\"transform\", \"translate(0,0)\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"axis\")\n .attr(\"transform\", \"translate(\" + x(1) + \",0)\")\n .append(\"text\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", -12)\n .attr(\"dy\", \".71em\")\n .style(\"text-anchor\", \"end\")\n .text(chartOptions.title_y);\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"close annotation up\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"volume\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"candlestick\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"indicator sma ma-0\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"indicator sma ma-1\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"indicator ema ma-2\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"percent axis\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"volume axis\");\n\n indicatorSelection = svg.selectAll(\"svg > g.indicator\").data([\"macd\", \"rsi\"]).enter()\n .append(\"g\")\n .attr(\"class\", function(d) { return d + \" indicator\"; });\n\n indicatorSelection.append(\"g\")\n .attr(\"class\", \"axis right\")\n .attr(\"transform\", \"translate(\" + x(1) + \",0)\");\n\n indicatorSelection.append(\"g\")\n .attr(\"class\", \"axis left\")\n .attr(\"transform\", \"translate(\" + x(0) + \",0)\");\n\n indicatorSelection.append(\"g\")\n .attr(\"class\", \"indicator-plot\")\n .attr(\"clip-path\", function(d, i) { return \"url(#indicatorClip-\" + i + \")\"; });\n\n // Add trendlines and other interactions last to be above zoom pane\n svg.append('g')\n .attr(\"class\", \"crosshair ohlc\");\n/*\n svg.append(\"g\")\n .attr(\"class\", \"tradearrow\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n*/\n svg.append('g')\n .attr(\"class\", \"crosshair macd\");\n\n svg.append('g')\n .attr(\"class\", \"crosshair rsi\");\n\n svg.append(\"g\")\n .attr(\"class\", \"trendlines analysis\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n/* svg.append(\"g\")\n .attr(\"class\", \"supstances analysis\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");*/\n\n// d3.select(\"button\").on(\"click\", reset);\n}",
"function showLandingGraph(ndx, element, width, height) {\n var selector = document.getElementById(\"landingSelect\");\n var selectorValue = selector.options[selector.selectedIndex].value;\n\n var regionDim = ndx.dimension(dc.pluck(\"Region\"));\n var landingSelection = regionDim.group().reduceSum(dc.pluck(selectorValue));\n //Making chart responsive for table/mobile users\n var newWidth;\n var newHeight;\n //If height is larger than width it must scale differently\n if(height > width){\n newHeight = height / 2.3;\n newWidth = width / 1.05;\n } else {\n //Keeping same size for laptop and desktop\n newWidth = 800;\n newHeight = 500;\n }\n dc.barChart(element)\n .width(newWidth)\n .height(newHeight)\n .margins({ top: 10, right: 50, bottom: 100, left: 80 })\n .dimension(regionDim)\n .group(landingSelection)\n .transitionDuration(1000)\n .ordinalColors([\"#31FFAB\"])\n .x(d3.scale.ordinal())\n .xUnits(dc.units.ordinal)\n .elasticX(true)\n .elasticY(true)\n .yAxisLabel(getYAxisLabel(selectorValue))\n .yAxis().ticks(4);\n}",
"function renderAll()\n\t {\n\t \t// Sorting filters arrays.\n\t \tsortFilterArrays();\n\n\t \t// Rendering filters\n\t \trenderFilters();\n\n\t\t// Rendering publications\n\t\trenderPublications();\n\t}",
"function filterDataSets() {\n \t//the array that will contain the graph lines we want to display\n \tvar dataToDisplay = [];\n\n \t//get all the data sets\n \tvar dataSets = thisGrapher.globalDataSets;\n\n \tif(graphCheckBoxesDiv.length == 0) {\n \t\t//we could not find the checkboxes div so we will just display all the graph lines\n \t\tdataToDisplay = dataSets;\n \t} else {\n \t\t//we found the checkboxes div so we will filter graph lines\n \t\t\n \t\t//get all the check boxes that were checked\n \tgraphCheckBoxesDiv.find(\"input:checked\").each(function() {\n \t\t//get the name of the graph line\n \t\tvar index = $(this).attr(\"name\");\n \t\t\n \t\t//make sure that graph line exists\n \t\tif(index && dataSets[index]) {\n \t\t\t//put the graph line into the array to display\n \t\t\tdataToDisplay.push(dataSets[index]);\n \t\t}\n \t});\t\n \t}\n\n \t//display the graph lines that we want to display\n \tthisGrapher.globalPlot = $.plot($(\"#\" + thisGrapher.graphDivId), dataToDisplay, graphParams);\n \t\n \t//delete all the annotation tool tips form the UI\n \tthisGrapher.removeAllAnnotationToolTips();\n \t\n \t//highlight the points that have annotations\n \tthisGrapher.highlightAnnotationPoints(null, null, dataToDisplay);\n }",
"function draw(year){\n\n // filter the data for the corresponding day\n // filter the data to return only the three countries with most medals\n\n\n //TODO append data to draw circles\n // var circles = ...;\n\n //enter the data\n\n\n //exit\n\n //update\n\n\n //TODO append data for texts\n // var text = ...\n\n\n\n }",
"function drawGraphic()\n\t{\n\t\t\t\n\t\tvar w = window.innerWidth;\n\t\tvar h = window.innerHeight;\t\n\t\t\n\t\t\t\n\t\t// clear out existing graphics and footer\n\t\tgraphic.empty();\n\t\tdeadspace.empty();\n\t\tfooter.empty();\n\t\t\t\t\t\t\t\t\n\t\t//var requiredResolution = 'thunderbolt';\n/*\n\t\tgraphSpace = {\n\t\t\t\t\t\twidth:screenResolution[requiredResolution].width ,\n\t\t\t\t\t\theight:screenResolution[requiredResolution].height*0.75\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\tdeadSpace= {\n\t\t\t\t\t\twidth:screenResolution[requiredResolution].width ,\n\t\t\t\t\t\theight:screenResolution[requiredResolution].height*0.0\n\t\t\t\t\t}\n*/\n\n\t\tvar aspectRatio = [ 16, 9 ];\n\n\t\tgraphSpace = {\n\t\t\t\t\t\twidth : graphic.width() ,\n\t\t\t\t\t\theight : Math.ceil(((graphic.width() - margin.top.left - margin.top.right) * aspectRatio[1]) / aspectRatio[0]) - margin.top.top - margin.top.bottom\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\tdeadSpace= {\n\t\t\t\t\t\twidth:graphic.width() ,\n\t\t\t\t\t\theight:0.0\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\tconsole.log(graphSpace.width + \" : \" + graphSpace.height);\n\t\t\n\t\t\n\t\t/* TOP BAR CHART */\n\t\t\n\t\td3.select(\"#graphic\").append(\"h1\").attr(\"id\" , \"viewCounter\").style(\"text-align\" , \"center\").text(titles[viewCounter]);\n\t\t\n\t\t\n\t\tsvg = d3.select(\"#graphic\")\n\t\t\t.append(\"svg\")\n\t\t\t.attr(\"class\" , \"svg\")\n\t\t\t.attr(\"id\" , \"svg\")\n\t\t\t.attr(\"width\" , graphSpace.width )\n\t\t\t.attr(\"height\" , graphSpace.height*ratios.topRatio )\n\t\t\t.attr(\"x\" , 0 )\n\t\t\t.attr(\"y\" , 0 );\n\t\t\t\n\t\t\n\t\t\t\t\t\t\t\t \n\t\t// define and construct y axis domain and ranges\n\t\tvis.yTop = d3.scale.linear().domain([yAxisRanges.top.minimum , yAxisRanges.top.maximum]).range([ ((graphSpace.height*ratios.topRatio)-margin.top.top-margin.top.bottom) , margin.top.top ]);\n\t\tvis.yAxisTop = d3.svg.axis().scale(vis.yTop).orient(\"left\").ticks(10).tickFormat(d3.format(\",.1f\"));\t\t\t\t\t\t\n\t\td3.select(\"#svg\")\n\t\t\t.append(\"g\")\n\t\t\t.attr(\"class\", \"y axis\")\n\t\t\t.attr(\"id\", \"topYAxis\")\n\t\t\t.attr(\"transform\", \"translate(\" + margin.top.left + \",\" + margin.top.top + \")\")\n\t\t\t.call(vis.yAxisTop);\n\t\t\t\n\t\tvis.yticksTop = svg.selectAll('#topYAxis').selectAll('.tick');\t\t\t\t\t \n\t\tvis.yticksTop.append('svg:line')\n\t\t\t.attr( 'id' , \"yAxisTicksTop\" )\n\t\t\t.attr( 'y0' , 0 )\n\t\t\t.attr( 'y1' , 0 )\n\t\t\t.attr( 'x1' , 0 )\n\t\t\t.attr( 'x2', graphSpace.width-margin.bottom.left*2)\n\t\t\t.style(\"opacity\" , 0.15);\n\t\t\t\t\t\t\t\t\t\t\t \n\t\t// define and construct y axis domain and ranges\t\t\t\t\n\t\tvis.xTop = d3.time.scale().range([margin.top.left, (graphSpace.width - margin.top.left/* - margin.top.right*/)]);\n\t\tvis.xTop.domain(d3.extent(view1, function(d) { return d.formattedDate; }));\n\t\tvis.xAxisTop = d3.svg.axis().scale(vis.xTop).orient(\"bottom\");\t\n\t\t\t\n/*\t\t\t\t\t\t\n\t\tvis.xAxisTop = d3.svg.axis()\n\t\t\t.scale(vis.xTop)\n\t\t\t.orient(\"bottom\")\n\t\t\t.tickFormat(function(d,i) {\n\t\t\t\tvar fmt = d3.time.format(\"%m/%Y\");\n\t\t\t\tstr = fmt(d);\n\t\t\t\treturnstr;\n\t\t\t})\n\t\t\t.tickPadding(5);\t\t\t\t\t\n*/\n\n\t\t\n\t\td3.select(\"#svg\")\n\t\t\t.append(\"text\")\n\t\t\t.attr( \"class\" , \"yAxisLabels\")\n\t\t\t.attr( \"id\" , function(d,i){ return \"yAxisLabel\"; })\n\t\t\t.attr(\"x\" , margin.top.left)\n\t\t\t.attr(\"y\" , 25)\n\t\t\t.style(\"font-size\" , \"1.0em\")\n\t\t\t.style(\"fill\" , \"white\")\n\t\t\t.text(\"Sentiment\");\n\t\t\t\t \n\t\tvar dots = svg.selectAll(\".dots\")\n\t\t\t.data(View2_dots['sentiment'])\n\t\t\t.enter()\n\t\t\t.append(\"circle\");\n\t\t\t\n\t\tvar circleAttributes = dots\n\t\t\t.attr(\"class\", function (d,i) {\n\t\t\t\tvar classStr = \"dots article_index\"+d.article_index;\n\t\t\t\tif ( d.callout_flag == 1 ) { classStr = classStr + \" view0\"; }\n\t\t\t\treturn classStr/*\"dots article_index\"+d.article_index*/;\n\t\t\t})\n\t\t\t.attr(\"id\", function (d,i) { return \"dot-\" + d.index; })\n\t\t\t.attr(\"cx\", function (d,i) { return vis.xTop(d.formattedDate); })\n\t\t\t.attr(\"cy\", function (d,i) { return margin.top.top+vis.yTop(d.sentiment); })\n\t\t\t.attr(\"r\", function (d,i) { return 5; })\n\t\t\t.style(\"opacity\", function(d,i) { return 1.0; })\n\t\t\t.style(\"fill\" , \"#888888\")\n\t\t\t.style(\"stroke\" , function(d,i){\n\t\t\t\tif ( calloutIndexes[0].indexOf(+d.index) != -1 ) { return \"#FFFFFF\"; }\n\t\t\t\telse { return \"#888888\"; }\n\t\t\t})\n\t\t\t.style(\"stroke-width\" , \"2px\")\n\t\t\t.style(\"fill-opacity\" , 0.75);\n\t\t\t\n\t\t\n\t\t\t\n\t\t\t\n\t\tvar dots2 = svg.selectAll(\".dots2\")\n\t\t\t.data(View5_dots['index'])\n\t\t\t.enter()\n\t\t\t.append(\"circle\");\n\t\n\t\tvar circleAttributes2 = dots2\n\t\t\t.attr(\"class\", function (d,i) {\n\t\t\t\tvar classStr = \"dots2 article_index\"+d.article_index;\n\t\t\t\tif ( d.callout_flag == 1 ) { classStr = classStr + \" view1\"; }\n\t\t\t\t\n\t\t\t\tif ( calloutIndexes[3].indexOf(d.index) != -1 ) {\n\t\t\t\t\tclassStr = classStr + \" pulse\";\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn classStr;\n\t\t\t})\n\t\t\t.attr(\"id\", function (d,i) {\t\t\n\t\t\t\treturn \"dot2-\" + d.index;\n\t\t\t})\n\t\t\t.attr(\"cx\", function (d,i) { return vis.xTop(d.formattedDate); })\n\t\t\t.attr(\"cy\", function (d,i) { return margin.top.top+vis.yTop(d.sentiment_score); })\n\t\t\t.attr(\"r\", function (d,i) { return 0; })\n\t\t\t.style(\"fill\" , \"#005DA2\")\n\t\t\t.style(\"stroke\" , \"#005DA2\")\n\t\t\t.style(\"stroke-width\" , \"2px\")\n\t\t\t.style(\"fill-opacity\" , 0.00);\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\tvar dots2a = svg.selectAll(\".dots2a\")\n\t\t\t.data(View5a_dots['index'])\n\t\t\t.enter()\n\t\t\t.append(\"circle\");\n\t\n\t\tvar circleAttributes2a = dots2a\n\t\t\t.attr(\"class\", function (d,i) {\n\t\t\t\tvar classStr = \"dots2a article_index\"+d.article_index;\n\t\t\t\treturn classStr;\n\t\t\t})\n\t\t\t.attr(\"id\", function (d,i) { return \"dot2a-\" + d.index; })\n\t\t\t.attr(\"cx\", function (d,i) { return vis.xTop(d.formattedDate); })\n\t\t\t.attr(\"cy\", function (d,i) { return margin.top.top+vis.yTop(d.sentiment_score); })\n\t\t\t.attr(\"r\", function (d,i) { return 0; })\n\t\t\t.style(\"fill\" , \"#005DA2\")\n\t\t\t.style(\"stroke\" , \"#005DA2\")\n\t\t\t.style(\"stroke-width\" , \"2px\")\n\t\t\t.style(\"fill-opacity\" , 1.00);\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\tvar dots3a = svg.selectAll(\".dots3a\")\n\t\t\t.data(View6a_dots['index'])\n\t\t\t.enter()\n\t\t\t.append(\"circle\");\n\t\n\t\tvar circleAttributes3a = dots3a\n\t\t\t.attr(\"class\", function (d,i){\n\t\t\t\tvar classStr = \"dots3a article_index\"+d.article_index;\n\t\t\t\tif ( d.callout_flag == 1 ) { classStr = classStr + \" view2\"; }\n\t\t\t\treturn classStr ;\n\t\t\t})\n\t\t\t.attr(\"id\", function (d,i) { return \"dot3a-\" + d.index; })\n\t\t\t.attr(\"cx\", function (d,i) { return vis.xTop(d.formattedDate); })\n\t\t\t.attr(\"cy\", function (d,i) { return margin.top.top+vis.yTop(d.sentiment_score); })\n\t\t\t.attr(\"r\", function (d,i) { return 0; })\n\t\t\t.style(\"fill\" , \"#005DA2\")\n\t\t\t.style(\"stroke\" , \"#005DA2\")\n\t\t\t.style(\"stroke-width\" , \"2px\")\n\t\t\t.style(\"fill-opacity\" , 0.00);\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\tvar dots3 = svg.selectAll(\".dots3\")\n\t\t\t.data(View6_dots['index'])\n\t\t\t.enter()\n\t\t\t.append(\"circle\");\n\t\n\t\tvar circleAttributes3 = dots3\n\t\t\t.attr(\"class\", function (d,i){\n\t\t\t\tvar classStr = \"dots3 article_index\"+d.article_index;\n\t\t\t\tif ( d.callout_flag == 1 ) { classStr = classStr + \" view2\"; }\n\t\t\t\treturn classStr ;\n\t\t\t})\n\t\t\t.attr(\"id\", function (d,i) { return \"dot3-\" + d.index; })\n\t\t\t.attr(\"cx\", function (d,i) { return vis.xTop(d.formattedDate); })\n\t\t\t.attr(\"cy\", function (d,i) { return margin.top.top+vis.yTop(d.sentiment_score); })\n\t\t\t.attr(\"r\", function (d,i) { return 0; })\n\t\t\t.style(\"fill\" , \"#005DA2\")\n\t\t\t.style(\"stroke\" , \"#005DA2\")\n\t\t\t.style(\"stroke-width\" , \"2px\")\n\t\t\t.style(\"fill-opacity\" , 0.00);\n\t\t\t \n\t\t\t\n\t\t\t\n\t\t\t\n/*\n\t\tvar dots4 = svg.selectAll(\".dots4\")\n\t\t\t.data(View7_dots['index'])\n\t\t\t.enter()\n\t\t\t.append(\"circle\");\n\t\n\t\tvar circleAttributes4 = dots4\n\t\t\t.attr(\"class\", function (d,i) {\n\t\t\t\tvar classStr = \"dots4 article_index\"+d.article_index;\n\t\t\t\tif ( d.callout_flag == 1 ) { classStr = classStr + \" view3\"; }\n\t\t\t\treturn classStr;\n\t\t\t})\n\t\t\t.attr(\"id\", function (d,i) { return \"dot4-\" + d.index; })\n\t\t\t.attr(\"cx\", function (d,i) { return vis.xTop(d.formattedDate); })\n\t\t\t.attr(\"cy\", function (d,i) { return margin.top.top+vis.yTop(d.sentiment_score); })\n\t\t\t.attr(\"r\", function (d,i) { return 0; })\n\t\t\t.style(\"fill\" , \"#005DA2\")\n\t\t\t.style(\"stroke\" , \"#005DA2\")\n\t\t\t.style(\"stroke-width\" , \"2px\")\n\t\t\t.style(\"fill-opacity\" , 0.00);\n*/\n\n\t\t//create x axis\n\t\td3.select(\"#svg\")\n\t\t\t.append('g')\n\t\t\t.attr('class', 'x axis')\n\t\t\t.attr('id', 'topXAxis')\n\t\t\t.attr('transform', function(d, i){ return \"translate(\" + (0) + \",\" + (margin.top.top + vis.yTop(0)) + \")\"; })\n\t\t\t.call(vis.xAxisTop);\n\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\n\t\t\n\t\t/* BOTTOM BAR CHART */\n\t\t\t\n\t\tsvgBottom = d3.select(\"#graphic\")\n\t\t\t.append(\"svg\")\n\t\t\t.attr(\"class\" , \"svg\")\n\t\t\t.attr(\"id\" , \"svgBottom\")\n\t\t\t.attr(\"width\" , graphSpace.width )\n\t\t\t.attr(\"height\" , graphSpace.height*ratios.bottomRatio )\n\t\t\t.attr(\"x\" , 0 )\n\t\t\t.attr(\"y\" , 0 ); \n\t\t\t\n\t\t\n\n\n\t\t\n\t\t// define clipPath around scatter plot frame\n\t\tsvgBottom.append(\"defs\").append(\"clipPath\")\n\t\t\t.attr(\"id\", \"clip\")\n\t\t\t.append(\"rect\")\n\t\t\t.attr(\"x\", margin.bottom.left )\n\t\t\t.attr(\"y\", 0 )\n\t\t\t.attr(\"width\", graphSpace.width - margin.bottom.left*2 )\n\t\t\t.attr(\"height\", graphSpace.height*ratios.bottomRatio );\n\t\t\t\n\t\t\t\t\t\t\n\t\tvis.xBottom = d3.time.scale().range([margin.top.left, (graphSpace.width - margin.top.left/* - margin.top.right*/)]);\n\t\tvis.xBottom.domain(d3.extent(view1, function(d) { return d.formattedDate; }));\n\t\tvis.xAxisBottom = d3.svg.axis().scale(vis.xBottom).orient(\"bottom\");\t\n\t\t\n\t\t\t\t\n/*\n\t\tvis.xAxisBottom = d3.svg.axis()\n\t\t\t.scale(vis.xBottom)\n\t\t\t.orient(\"bottom\")\n\t\t\t.tickFormat(function(d,i) {\n\t\t\t\tvar fmt = d3.time.format(\"%m/%Y\");\n\t\t\t\tstr = fmt(d);\n\t\t\t\treturn str;\n\t\t\t})\n\t\t\t.tickPadding(5);\n*/\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \n\t\t// define and construct y axis domain and ranges\n\t\tvis.yBottom = d3.scale.linear().domain([yAxisRanges.bottom.minimum , yAxisRanges.bottom.maximum]).range([ ((graphSpace.height*ratios.bottomRatio)-margin.bottom.top/*-margin.bottom.bottom*/) , margin.bottom.top ]);\n\t\tvis.yAxisBottom = d3.svg.axis().scale(vis.yBottom).orient(\"left\").ticks(5).tickFormat(d3.format(\",.0f\"));\t\n\t\t\n\t\t\t\t\t\t\t\t\n\t\t\n\t\tvar bars = svgBottom.selectAll(\"rect\")\n\t\t\t.data(View1_bars['number_of_articles_per_date'])\n\t\t\t.enter()\n\t\t\t.append(\"rect\");\n\t\t\t\n\t\tvar numberDates = View1_bars['date'].length;\n\t\tcoloumnWidth = ((vis.xBottom.range()[1] - vis.xBottom.range()[0])/numberDates)/2;\n\t\n\t\tvar barAttributes = bars\n\t\t\t.attr(\"class\", function (d,i) { return \"bars\"; })\n\t\t\t.attr(\"id\", function (d,i) { return \"bar-\" + i; })\t\t\t\t\n\t\t\t.attr(\"x\", function(d) { return vis.xBottom(d.formattedDate) - coloumnWidth/2; })\n\t\t\t.attr(\"y\", function(d) { return vis.yBottom(+d.number_of_articles_per_date); })\n\t\t\t.attr(\"width\", coloumnWidth )\n\t\t\t.attr(\"height\", function(d) { return vis.yBottom(0) - vis.yBottom(+d.number_of_articles_per_date); })\n\t\t\t.style(\"fill\" , \"#005DA2\")\n\t\t\t.style(\"stroke\" , \"#005DA2\" )\n\t\t\t.style(\"stroke-width\" , \"1px\")\n\t\t\t.style(\"fill-opacity\" , 0.75)\n\t\t\t.attr(\"clip-path\", \"url(#clip)\");\t\n\t\t\t\t\t\t\t\t\t\n\t\td3.select(\"#svgBottom\")\n\t\t\t.append(\"g\")\n\t\t\t.attr(\"class\", \"y axis\")\n\t\t\t.attr(\"id\", \"bottomYAxis\")\n\t\t\t.attr(\"transform\", \"translate(\" + margin.bottom.left + \",\" + (0) + \")\")\n\t\t\t.call(vis.yAxisBottom);\n\t\n\t\td3.select(\"#svgBottom\")\n\t\t\t.append(\"text\")\n\t\t\t.attr( \"class\" , \"yAxisLabels\")\n\t\t\t.attr( \"id\" , function(d,i){ return \"yAxisLabel\"; })\n\t\t\t.attr(\"x\" , margin.bottom.left)\n\t\t\t.attr(\"y\" , 20)\n\t\t\t.style(\"font-size\" , \"1.0em\")\n\t\t\t.style(\"fill\" , \"white\")\n\t\t\t.text(\"Number of articles per day\");\n\t\t\t\n\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t// draw tick grid lines extending from y-axis ticks on axis across scatter graph\n\t\t\t\n\t\tvis.yticksBottom = svgBottom.selectAll('#bottomYAxis').selectAll('.tick');\t\t\t\t\t \n\t\tvis.yticksBottom.append('svg:line')\n\t\t\t.attr( 'id' , \"yAxisTicksBottom\" )\n\t\t\t.attr( 'y0' , 0 )\n\t\t\t.attr( 'y1' , 0 )\n\t\t\t.attr( 'x1' , 0 )\n\t\t\t.attr( 'x2', graphSpace.width-margin.bottom.left*2)\n\t\t\t.style(\"opacity\" , 0.15);\n\t\t\t\n\t\t//create brush x axis\n\t\td3.select(\"#svgBottom\")\n\t\t\t.append('g')\n\t\t\t.attr('class', 'x axis')\n\t\t\t.attr('id', 'bottomXAxis')\n\t\t\t.attr('transform', function(d, i){ return \"translate(\" + (0) + \",\" + ( + vis.yBottom(0)) + \")\"; })\n\t\t\t.call(vis.xAxisBottom);\t\n\t\t\t\n\t\tsvgDeadSpace = d3.select(\"#deadspace\")\n\t\t\t.append(\"svg\")\n\t\t\t.attr(\"class\" , \"svg\")\n\t\t\t.attr(\"id\" , \"svgDeadSpace\")\n\t\t\t.attr(\"width\" , deadSpace.width )\n\t\t\t.attr(\"height\" , deadSpace.height )\n\t\t\t.attr(\"x\" , 0 )\n\t\t\t.attr(\"y\" , 0 ); \t\t\t\n\t\t\t \n\t\td3.select(\"#footer\")\n\t\t\t.append(\"a\")\n\t\t\t .attr(\"href\", \"http://innovation.thomsonreuters.com/en/labs.html\")\n\t\t\t .attr(\"target\" , \"_blank\")\n\t\t\t .html(\"</br>Data visualisation by Thomson Reuters Labs\");\n\t\t \n\t\t var sel = d3.selectAll(\".dots.view0\");\n\t\t sel.moveToFront();\n\t\t\t\n\t\tcallOuts();\n\t\tdrawLegend();\n\t\t\n\t\tif ( auto == true ){\n\t\t\t\n\t\t myInterval = setInterval(function () {\n\t\t\t \n\t\t\t\ttransitionData();\n\t\t\t\tviewCounter++;\n\t\t\t\tif (viewCounter === 5) {\n\t\t\t\t\tclearInterval(myInterval);\n\t\t\t\t}\n\t\t\t}, 5000);\n\t\t}\n\t\t\t \n\t\t//use pym to calculate chart dimensions\t\n\t\tif (pymChild) { pymChild.sendHeight(); }\n\n\t\treturn;\n\n\t}",
"draw(ctx) {\r\n if (this.isDistanced) {\r\n this.distanceGraph();\r\n }\r\n // draw all nodes and store them in grid array\r\n this.nodeList.forEach(node => {\r\n node.draw(ctx);\r\n storeNodeAt(node, node.x, node.y);\r\n });\r\n\r\n // draw all edges\r\n this.edgeList.forEach(edge => {\r\n edge.draw(ctx);\r\n });\r\n\r\n\r\n }",
"function renderViz() {\n\n // Define variables for viz\n var mainVizDiv = $(\"#tableauViz\");\n var mainVizOptions = {\n hideTabs: true,\n hideToolbar: true,\n //toolbarPositon: top, // (or \"bottom\")\n width: 850,\n height: 860,\n onFirstInteractive: function () {\n mainWorkbook = mainViz.getWorkbook();\n }\n };\n // Create viz\n mainViz = new tableauSoftware.Viz(mainVizDiv[0], url, mainVizOptions);\n}",
"function drawTermDatesGraph() {\n // Get the elements we need\n var graphContainer = $('.term_dates_graph');\n var tableContainer = $('.term_dates_table');\n if (graphContainer.length === 0 || tableContainer.length === 0)\n return;\n\n var results = $.parseJSON(window.json_data);\n\n // Make a DataTable object\n var data = new google.visualization.DataTable();\n var rows = results.data;\n\n data.addColumn('number', results.year_header);\n data.addColumn('number', results.value_header);\n data.addRows(rows);\n\n // Make the line chart object\n var w = $(window).width();\n if (w > 750) {\n w = 750;\n }\n\n var h;\n if (w > 480) {\n h = 480;\n } else {\n h = w;\n }\n\n var options = { width: w, height: h,\n legend: { position: 'none' },\n hAxis: { format: '####',\n title: results.year_header },\n vAxis: { title: results.value_header },\n pointSize: 3 };\n\n var chart = new google.visualization.LineChart(graphContainer[0]);\n chart.draw(data, options);\n\n graphContainer.trigger('updatelayout');\n\n // Make a pretty table object\n var table = new google.visualization.Table(tableContainer[0]);\n table.draw(data, { page: 'enable', pageSize: 20, sortColumn: 0,\n width: '20em' });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function will get a valid letter guess | function getValidLetterGuess() {
//this helper function is used to determine if letter guess is valid
function guessIsValid(letter) {
//use regex to determine if letter is in the alphabet and ignore case sensitivty
const validEntries = /[a-z]/i;
//if the letter is in the alphabet and the length of the letter is 1
if (validEntries.test(letter) && letter.length === 1) {
return letter;
} else {
return false;
}
}
//declare a variable named letter and assign it a falsy value to start off
let letter = "";
//while the letter is falsy
while (!letter) {
//program will stop to get user input
let input = readline.question("\nGuess a letter: ");
if (guessIsValid(input)) {
letter = input;
} else {
console.log("Please enter a valid letter");
}
}
return letter.toLowerCase();
} | [
"function guessIsValid(letter) {\n //use regex to determine if letter is in the alphabet and ignore case sensitivty\n const validEntries = /[a-z]/i;\n //if the letter is in the alphabet and the length of the letter is 1\n if (validEntries.test(letter) && letter.length === 1) {\n return letter;\n } else {\n return false;\n }\n }",
"function Guess(letter) {\n if (RemainingGuesses > 0) {\n // Make sure we didn't use this letter yet\n if (GuessedLetters.indexOf(letter) === -1) {\n GuessedLetters.push(letter);\n CheckGuess(letter);\n }\n }\n \n}",
"function checkForLetter(letter) {\n // Create local var to be used for non correct keys\n let foundLetter = false;\n\n // For loop for correct letters\n for (let i = 0, x = nameToMatch.length; i < x; i++) {\n if (letter === nameToMatch[i]) {\n guessingName[i] = letter;\n foundLetter = true;\n\n // Increment wins and update screen\n if (guessingName.join('') === nameToMatch) {\n const element = document.getElementById('pokemonImg');\n element.classList.add('pokemonShow');\n wins++;\n setTimeout(resetPokemon, 3000);\n }\n }\n updateScreen();\n }\n\n // If wrong letter, decrement remaining guesses\n if (!foundLetter) {\n if (!guessedLetters.includes(letter)) {\n guessedLetters.push(letter);\n numGuesses--;\n }\n\n // If remaining guesses equals 0, increment losses and update screen\n if (numGuesses === 0) {\n guessingName = nameToMatch.split();\n losses++;\n setTimeout(resetPokemon, 3000);\n }\n }\n updateScreen();\n}",
"checkLetter(input) {\r\n return this.phrase\r\n .split(\"\")\r\n .some(letter => letter == input);\r\n }",
"function testLetter() {\n\t// create new Letter objects\n\tl1 = new Letter('a');\n\tl2 = new Letter('b');\n\n\t// test constructur\n\tt1 = l1.displayLetter() === '_';\n\tt2 = l2.displayLetter() === '_';\t\n\n\tl1.checkGuess('c');\n\tt3 = l1.displayLetter() === '_';\n\tl1.checkGuess('a');\n\tt4 = l1.displayLetter() === 'a';\n\n\t// if tests pass display success message, otherwise display error message\n\tif (t1 && t2 && t3 && t4) {\n\t\tconsole.log('Tests passed! Letter constructor is functioning correctly.');\n\t} else {\n\t\tconsole.log('Tests failed. Check Letter constructor code.');\n\t}\n}",
"function isLetter(str) {\n if (str.length == 1 && str.match(/[a-zA-Z]/i)) {\n document.getElementById(\"messages\").innerHTML = \"\";\n currentLetter = str.toLowerCase();\n return true;\n } else if (str !== 'Shift' && str !== 'CapsLock' && str !== 'F5') {\n document.getElementById(\"messages\").innerHTML = \"Please input letters only!\";\n return false;\n }\n}",
"function checkLetter(ltr) {\n if (currentWord.indexOf(ltr) !== -1 || playerWord.indexOf(ltr) !== -1) {\n for (var i = 0; i < currentWord.length; i++) {\n if (currentWord[i] === ltr) {\n playerWord[i] = ltr;\n currentWord[i] = \"\";\n lettersLeft--;\n }\n }\n } else {\n if (pastLetters.indexOf(ltr) == -1) {\n decGuesses();\n pastLetters.push(ltr);\n }\n }\n}",
"guess(guessedLetter) {\n this.letters.forEach(letter => letter.guessLetter(guessedLetter))\n }",
"function wrongLetter(letter) {\n guessesLeft--;\n guessesLetters.push(letter);\n }",
"function fearNotLetter(str) {\n for (var i = 0; i < str.length - 1; i++) {\n if (str.charCodeAt(i + 1) == str.charCodeAt(i) + 1) {\n console.log(\"next char is next in alphabet\");\n }\n else {\n return String.fromCharCode(str.charCodeAt(i) + 1);\n }\n }\n //return undefined\n}",
"function wordCheck(userGuess) {\n if (gameFinished === true) {\n resetFunction();\n return;\n }\n var isItLetter = false;\n var alphabetArray = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"];\n for (i = 0; i < alphabetArray.length; i++) {\n if (userGuess === alphabetArray[i]) {\n isItLetter = true;\n }\n }\n if (isItLetter === false) {\n alert(\"I'm having a crap attack! That wasn't a letter!\");\n return;\n }\n var doesItMatch = false;\n for (i = 0; i < wordChoice.length; i++) {\n if (userGuess === wordChoice[i]) {\n doesItMatch = true;\n playSpace[i] = userGuess;\n }\n }\n var didWeWin = true;\n for (i = 0; i < wordChoice.length; i++) {\n if (playSpace[i] != wordChoice[i]) {\n didWeWin = false;\n }\n }\n if (didWeWin === true) {\n winnerFunction();\n return;\n }\n for (i = 0; i < alreadyGuessed.length; i++) {\n if (userGuess === alreadyGuessed[i]) {\n return;\n }\n }\n if (!doesItMatch) {\n guessesRemaining--;\n guessesRemainingFunction();\n alreadyGuessed.push(userGuess);\n alreadyGuessedFunction();\n }\n if (guessesRemaining === 0) {\n loserFunction();\n return;\n }\n }",
"function charPos(secretWord, letterGuess) {\n \t\t\t\treturn secretWord.toLowerCase()\n \t\t.split(\"\").map(function (letter, i) { if (letter == letterGuess) return i;})\n \t\t.filter(function (v) { return v >= 0; });\n\t\t\t}",
"function isLetterCorrect(userInput, currentLetter) {\n if (userInput === currentLetter) {\n message.innerHTML = \"Correct\";\n\n correctKeystrokes++;\n return true;\n } else {\n message.innerHTML = \"Incorrect\";\n incorrectKeystrokes++;\n return false;\n }\n}",
"function promptUser(){\n\tconsole.log(\"\");\n\n\tif(game.guessesRemaining > 0){\n\t\tinquirer.prompt([\n\t\t{\n\t\t\ttype: \"value\",\n\t\t\tname: \"letter\",\n\t\t\tmessage: \"Pick a letter: \"\n\t\t}\n\t]).then(function(userInput){\n\n\t\t// in case shift or keylock is pressed, this takes input and converts to lower case\n\t\tvar inputLetter = userInput.letter.toLowerCase();\n\n\t\t// test to see if input is a valid letter\n\t\tif(alphabet.indexOf(inputLetter) === -1){\n\t\t\tconsole.log(inputLetter + \" is not a letter. Try again...\");\n\t\t\tconsole.log(\"Guesses remaining: \" + game.guessesRemaining);\n\t\t\tconsole.log(\"Letters guessed: \" + lettersGuessed);\n\t\t\tconsole.log(\"\\n--------------------------------------\");\n\t\t\tpromptUser();\n\t\t// otherwise, test to see is input is in the alphabet and is in letters already guessed\n\t\t// if both true, then user needs to guess again\n\t\t} else if(alphabet.indexOf(inputLetter) != -1 && lettersGuessed.indexOf(inputLetter) != -1){\n\t\t\tconsole.log(\"You already guessed \" + inputLetter + \". Try again...\");\n\t\t\tconsole.log(\"Guesses remaining: \" + game.guessesRemaining);\n\t\t\tconsole.log(\"Letters guessed: \" + lettersGuessed);\n\t\t\tconsole.log(\"\\n--------------------------------------\");\n\t\t\tpromptUser();\t\n\t\t// this is the final condition; if input is valid and not already-guess; this\n\t\t// path pushes the input/guess to the \"lettersGuessed\" and if the letter is in the\n\t\t// word, it will push to the \"lettersCorrect\" array, and then calls\n\t\t// parseDisplay method to display the new hangman object/word to the screen\n\t\t} else {\n\t\t\tlettersGuessed.push(inputLetter);\n\t\t\tvar letterInWord = checkLetter(inputLetter, game.currentWord);\n\n\t\t\tif(letterInWord){\n\t\t\t\tlettersCorrect.push(inputLetter);\n\n\t\t\t\tdisplayHangman = new lettersToDisplay(game.currentWord, lettersCorrect);\n\t\t\t\tdisplayHangman.parseDisplay();\n\n\t\t\t\tif(displayHangman.winner){\n\t\t\t\t\tconsole.log(\"You won!!! Nice work!!\");\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\"Guesses remaining: \" + game.guessesRemaining);\n\t\t\t\t\tconsole.log(\"Letters guessed: \" + lettersGuessed);\n\t\t\t\t\tconsole.log(\"\\n--------------------------------------\");\n\t\t\t\t\tpromptUser();\t\t\t\n\t\t\t\t}\n\n\t\t// if the letter wsn't guessed, but incorrect, it subtracts a guess from\n\t\t// guesses remaining and asks the user for another input\n\t\t} else {\n\t\t\tgame.guessesRemaining--;\n\n\t\t\tdisplayHangman.parseDisplay();\n\t\t\tconsole.log(\"Guesses remaining: \" + game.guessesRemaining);\n\t\t\tconsole.log(\"Letters guessed: \" + lettersGuessed);\n\t\t\tconsole.log(\"\\n--------------------------------------\");\n\t\t\tpromptUser();\t\t\t\t\t\t\n\t\t\t}\n\t\t}\t\n\t\n\t});\n\n// if guessesremaing reaches 0, then the game over message appears along with the \n// current word, so the user can see which word was chosen.\n} else {\n\n\tconsole.log(\"Sorry! You ran out of guesses...\");\n\tconsole.log(\"The word you were trying to uncover was: \" + game.currentWord + \".\");\n\tconsole.log(\"\\n--------------------------------------\");\n}\n\n}",
"function Word (wordPicked, letterPicked) {\n\n\tthis.word = wordPicked;\n\tthis.letter = letterPicked;\n\tthis.letterArr = this.word.split(\"\");\n\tthis.letterGuessed = [];\n\tthis.alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S','T', 'U', 'V', 'W', 'X', 'Y', 'Z'];\n\n\tthis.checkLetters = function() {\n\n\t\tif(this.letterGuessed.indexOf(this.letter) > -1) {\n\t\t\tconsole.log(\"Letter already guessed!\");\n\t\t\treturn;\n\t\t}\n\n\t\telse {\n\t\t\tconsole.log(\"Letter Available to Pick\")\n\n\t\t\tfor (i = 0; i < this.letterArr.length; i++) {\n\t\t\t\tconsole.log(this.letterArr[i]);\n\n\t\t\t\tif (this.letterArr[i] === this.letter) {\n\t\t\t\tconsole.log(\"this is a word\");\n\t\t\t\tthis.trueOrfalse = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\tthis.letterGuessed.push(this.letter);\n\n\t\t}\n\t}\n\n}",
"function getLetterChoice(title = 'Let\\s Play!', text = 'Choose your letter') {\r\n\r\n // user modal letter choice\r\n let pickedLetter = '';\r\n\r\n // misc messages to diplay at game start\r\n const startMessages = [\r\n 'Let\\'s Play',\r\n 'Let\\'s Dance',\r\n 'Let\\'s Tango',\r\n 'Let\\'s Waltz',\r\n 'Let\\'s Do This',\r\n 'Let\\'s Rendevous'\r\n ];\r\n\r\n const titleMessage = startMessages[Math.floor(Math.random() * startMessages.length)];\r\n\r\n // sweet alert to determine player letters\r\n swal({\r\n title: titleMessage,\r\n text: text,\r\n type: 'success',\r\n showCancelButton: true,\r\n confirmButtonColor: 'grey',\r\n confirmButtonText: 'X',\r\n cancelButtonText: 'O',\r\n closeOnConfirm: true,\r\n closeOnCancel: true\r\n }, function(isConfirm) {\r\n if (isConfirm) {\r\n pickedLetter = 'X';\r\n } else {\r\n pickedLetter = 'O';\r\n }\r\n // apply the appropriate letter(s) to players\r\n applyPlayerLetters(pickedLetter);\r\n // initialize the game board\r\n\r\n // show gameboard\r\n $gameBoard.removeClass('hidden').animateCss('pulse');\r\n $difficulty.animateCss('flash');\r\n\r\n refreshBoard();\r\n });\r\n\r\n }",
"function makeChar() {\n\tvar probability=points(0,\"\")/hardness;//according to hardness of game\n\tif(typeof alphabets === 'undefined' || alphabets === \"\"){\n\t\tvar index=Math.floor(Math.random() * 5)+2;\n\t\talphabets=words[index][Math.floor(Math.random() * words[index].length)];\n\t\tif(points(0,\"\")===0){\n\t\t\t//showing Hint only for new players\n\t\t\tif(typeof(Storage) !== \"undefined\") {\n\t\t\t\tif(localStorage.getItem(\"score\")===null){\n\t\t\t\t\thint(alphabets);//help player to learn game\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\thint(alphabets);//help player to learn game\n\t\t\t}\n\t\t}\n\t\ttext = alphabets.charAt(0);\n\t\talphabets = alphabets.slice(1);\t\n\t}else if(points(0,\"\") >=bombPoint){\n\t\t\ttext = 'B';\n\t\t\tbombPoint*=3;\n\t}else if(points(0,\"\") >=blockPoint){\n\t\t\ttext = 'N';\n\t\t\tblockPoint*=3;\n\t}else{\n\t\tif(Math.random() <= probability){\n\t\t\t//if propability goes up, game gets harder\n\t\t\ttext = randomChar();\n\t\t}else{\n\t\t\ttext = alphabets.charAt(0);\n\t\t\talphabets = alphabets.slice(1);\n\t\t}\n\t}\n\treturn text;\n}",
"function generateHints(guess) {\n var guessArray = guess.split('');// split the strings to arrays \n\tvar solutionArray = solution.split('');// split the strings to arrays \n\tvar correctPlacement = 0; // create a variable for correctPlacement\n\t// create for loop that checks each items in the solution array against guess array\n\tfor (var i = 0; i < solutionArray.length; i++) {\n\t// if there is a match, set the location to null\n\t\tif (solutionArray[i] === guessArray[i]) {\n\t\t\tcorrectPlacement++; \n\t\t\tsolutionArray[i] = null;\n\t\t}\n\t}\n\tvar correctLetter = 0; // create a variable for correctLetter\n\t// create for loop that checks indexOf each items in the guess array against solution array\n\t// note: indexOf automatically returns -1 if there are no instances\n // if there is a match it signifies correctLetter\n\tfor (var i = 0; i < solutionArray.length; i++\t) {\n\t\tvar targetIndex = solutionArray.indexOf(guessArray[i]);\n\t\tif (targetIndex > -1) {\n\t\t\tcorrectLetter++;\n\t\t\tsolutionArray[targetIndex] = null;\n\t\t}\n}\nreturn colors.red(correctPlacement + ' - ' + correctLetter);\n}",
"function isLetter(c) {\n return c.charCodeAt(0) >= 65 && c.charCodeAt(0) <= 90 ; \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Route handler To fetch product chooser Page | function chooseProductPage(req, res) {
return res.render('product-switcher.html');
} | [
"function productPage (itm, cst) {\n pref.product = {item: itm, cost: cst};\n storePref();\n window.location.href = '../pages/product.html';\n}",
"function Show() {\n var CurrentHttpParameterMap = request.httpParameterMap;\n var CurrentForms = session.forms;\n\n CurrentForms.giftregistry.clearFormElement();\n\n\n var ProductListID = CurrentHttpParameterMap.ID.stringValue;\n\n var ProductList = null;\n var Status = null;\n\n if (typeof(ProductListID) !== 'undefined' && ProductListID !== null) {\n var GetProductListResult = new Pipelet('GetProductList', {\n Create: false\n }).execute({\n ProductListID: ProductListID\n });\n if (GetProductListResult.result === PIPELET_ERROR) {\n Status = new dw.system.Status(dw.system.Status.ERROR, 'notfound');\n } else {\n ProductList = GetProductListResult.ProductList;\n\n if (ProductList.public) {\n CurrentForms.giftregistry.items.copyFrom(ProductList.publicItems);\n CurrentForms.giftregistry.event.copyFrom(ProductList);\n } else {\n Status = new dw.system.Status(dw.system.Status.ERROR, 'private');\n ProductList = null;\n }\n }\n } else {\n Status = new dw.system.Status(dw.system.Status.ERROR, 'notfound');\n }\n\n\n ISML.renderTemplate('', {\n ProductList: ProductList,\n Status: Status\n });\n}",
"function getProduct(e) {\n const href = this.getAttribute(\"href\");\n const ele = document.querySelector(\"a[href='\" + href + \"']\");\n const image = ele.querySelector('figure img').src;\n const eledata = ele.querySelector('.results__data');\n const title = eledata.querySelector('h4').textContent;\n const date = eledata.querySelector('p.results__date').textContent;\n const author = eledata.querySelector('p.results__author').textContent;\n const description = eledata.querySelector('p.results__description').textContent;\n renderSearchResult(image, title, date, author, description);\n}",
"function renderProductShow(id) {\n Products.show(id).then(product => {\n // console.log(`${product.id} - ${product.title}`)\n const showPage = document.querySelector('.page#product-show')\n const showPageHTML = `\n <h2>${product.title}</h2>\n <p>${product.description}</p>\n `\n showPage.innerHTML = showPageHTML;\n navigateTo('product-show')\n })\n}",
"function viewProducts() {\n console.log(chalk.green(\"\\n\\nBamazon - Manager View\\n\"));\n connection.query(\"SELECT * FROM products\\n\", function (err, res) {\n if (err) throw err;\n // called the function for the goods to be displayed\n createTable(res);\n });\n connection.end();\n}",
"function viewProductCatalogue(){\n let sqlQuery = \"SELECT * FROM product\";\n connection.query(sqlQuery, function (err, response) {\n if (err) {\n console.log(\"Error displaying products: \" + err);\n connection.end();\n } else {\n console.log(\"------------------------------\");\n // A console log to verify that the createChoicesArray returns the appropriate values.\n // console.log(createChoicesArray(response));\n // Iterate over the response to draw the table that will be displayed to the user.\n for (var i = 0; i < response.length; i++)\n console.log(response[i].product_id + \" : \" + response[i].product_name + \" : \" + response[i].department_id + \" : \" + response[i].stock_quantity + \" : \" + response[i].product_sales); \n console.log(\"------------------------------\");\n }\n });\n}",
"function renderSingleProductPage(index, data) {\n var page = $('.single-product'),\n container = $('.preview-large');\n\n // Find the wanted product by iterating the data object and searching for the chosen index.\n if (data.length) {\n data.forEach(function(item) {\n if (item.id == index) {\n // Populate '.preview-large' with the chosen product's data.\n container.find('h3').text(item.title);\n container.find('img').attr('src', item.thumbnail);\n container.find('p').text(item.title);\n container.find('#li1').text(item.condition);\n container.find('#li2').text(item.available_quantity);\n container.find('#li3').text(item.address.state_name);\n container.find('#li4').text(`${item.price}$`);\n container.find('a').attr('precio', item.price);\n container.find('a').attr('titulo', item.title);\n // class=\"waves-effect waves-light btn deep-purple darken-4 producto\"\n // precio=\"${item.price}\" titulo=\"${item.price}\" ><i class=\"material-icons right\">add_shopping_cart</i>Añadir`);\n }\n });\n }\n\n // Show the page.\n page.addClass('visible');\n}",
"async show({ params }) {\n return Product.findProduct(params);\n }",
"function onRowClickSegProducts()\n{\n\tkony.print(\"LOG : onRowClickSegProducts - START\");\n\tkony.print(frmProductsList.segProducts.selectedItems[0]);\n\tfetchProductDetails(frmProductsList.segProducts.selectedItems[0][\"hProductId\"],frmProductsList.segProducts.selectedItems[0][\"hIsNewProduct\"]);\n}",
"function redirectToProductList() {\n document.location = location.origin + '/Product';\n}",
"function viewProducts(){\n\tconnection.query('SELECT * FROM products', function(err,res){\n\t\tif (err) throw err;\n\t\tfor (var i = 0; i < res.length; i++) {\n\t\t\tconsole.log('ID: ' + res[i].id + '| sku: ' + res[i].sku +' | name: ' + res[i].product_name + \" | Price: $\" + res[i].price + \" | Quantity: \" + res[i].stock_quantity);\n\t\t};\n\t\tconsole.log('\\n');\n\t\tmanagerView();\n\t});\n}",
"async showOneProduct (req, res) {\n\t\tlet {sku} = req.params;\n\t\ttry {\n\t\t\tconst oneProduct = await products.findOne({SKU:sku});\n\t\t\tres.send(oneProduct);\n\t\t}\n\t\tcatch(e){\n\t\t\tres.send({e});\n\t\t}\n\t}",
"handleClicVerPromociones() {\n this[NavigationMixin.Navigate]({\n type: \"standard__objectPage\",\n attributes: {\n objectApiName: \"Promocion__c\",\n actionName: \"list\"\n }\n });\n }",
"function show_supplier_selector(product_id)\n{\n\n\n}",
"toRestaurant() {\n this.props.handleChangePage('Restaurant', this.props.rest.restId);\n }",
"function loadAllProductInShop() {\n Product.getProductLive({ SearchText: '' })\n .then(function (res) {\n $scope.products = res.data;\n });\n }",
"function continueShopping() {\n getProducts();\n }",
"function renderSingleProductPage (index, data) {\n var page = $('.single-product'),\n c = $('.single-product .preview-large');\n\n data.forEach(function (item) {\n if (parseInt(index, 10) === parseInt(item.id, 10)) {\n c.find('h3').text(item.title);\n c.find('img').attr('src', 'http://farm7.staticflickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_z.jpg');\n }\n });\n page.addClass('visible');\n }",
"function onProductChange(id_product, id_category) \n{\n\tloadAjaxPage(\"index.php?module=products&page=product_page&product_id=\" + id_product + \"&category_id=\" + id_category);\n\treturn false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set attributes to a d3 selection. | function setAttrs(select, attrs) {
var key;
for (key in attrs) {
if (attrs.hasOwnProperty(key)) {
select.attr(key, attrs[key]);
}
}
} | [
"function createAttributeSelect() {\n var attrSelect = $(\"#attr-select\");\n var prevDatasetId = queryParameters.dataset;\n if(attrSelect.length > 0 && attrSelect.data(\"datasetid\") !== prevDatasetId){\n attrSelect.parent().remove();\n attrSelect = $(\"#attr-select\");\n }\n if (attrSelect.length <= 0) {\n var builder = [\"<span> Attribute: \"];\n builder.push(\"<select id='attr-select'>\");\n var arr = getAttributes();\n for (var i = arr.length - 1; i >= 0; i--) {\n var x = arr[i];\n var selected = Powerset.colorByAttribute === x.name;\n builder.push(\"<option value='\" + x.name + \"' + selected='\" + selected + \"'>\" + x.name + \" </option>\");\n }\n builder.push(\"</select>\");\n builder.push(\"</span>\");\n $(\".header-container\").append(builder.join(\"\"));\n var sel = $(\"#attr-select\");\n sel.data(\"datasetid\",queryParameters.dataset);\n sel.on(\"change\",setColorByAttribute);\n }\n }",
"selectData(val) {\n if (this._interpolation === \"attr_style_range\") {\n this._selectedData = val;\n for (const canvasData of this._multiCanvas) {\n this._updateCanvas(canvasData.typeId);\n }\n }\n }",
"function changeSlicerAttrib(id, attrib, value) {\n\t$('.' + id + '-volume-x').attr(attrib, value);\n\t$('.' + id + '-volume-y').attr(attrib, value);\n\t$('.' + id + '-volume-z').attr(attrib, value);\n}",
"function listAttributes(data, selectedItem) {\n let _items = _.keys(data[0])\n let dropDown = d3.select(\"#attributes\");\n let options = dropDown.selectAll(\"a\")\n .data(_items)\n .enter()\n .append(\"a\")\n .attr(\"class\", \"waves-effect waves-light btn btn-block\")\n .attr(\"id\", _attr => _attr)\n .attr(\"href\", \"#\")\n .on('click', _attribute => {\n handleAttributeClick(_attribute, data);\n })\n .text(_d => {\n return _.truncate(_d, {length: 10})\n });\n d3.select(`#${selectedItem}`)\n .classed(\"disabled\", true)\n}",
"set (...args) {\n let arity = args.length;\n let mutators = this.mutators();\n let defaults = [v=>v];\n\n let assign = (value, attr) => {\n let [set] = mutators[attr] || defaults;\n this.attrs[attr] = set(value);\n };\n\n if (arity < 1) {\n throw new Error('expected at least one argument');\n }\n if (arity > 2) {\n throw new Error('expected no more than two arguments');\n }\n\n if (arity === 1) {\n each(args[0], assign);\n return;\n }\n\n let [attr, value] = args;\n assign(value, attr);\n }",
"function attrFunction() {\n\t var x = value.apply(this, arguments);\n\t if (x == null) this.removeAttribute(name);\n\t else this.setAttribute(name, x);\n\t }",
"redrawInputAttributes () {\n const inputAttributes = this.get( 'inputAttributes' );\n const control = this._domControl;\n for ( const property in inputAttributes ) {\n control.set( property, inputAttributes[ property ] );\n }\n }",
"function setSrc(element,attribute){element.setAttribute(attribute,element.getAttribute('data-'+attribute));element.removeAttribute('data-'+attribute);}",
"updateHasSelectionAttribute() {\n this.choicesInstance.containerInner.element.setAttribute(\n \"data-has-selection\",\n this.hasSelection\n );\n }",
"function buildSVGAttrs(state, _a, options, transformTemplate) {\n var attrX = _a.attrX, attrY = _a.attrY, originX = _a.originX, originY = _a.originY, pathLength = _a.pathLength, _b = _a.pathSpacing, pathSpacing = _b === void 0 ? 1 : _b, _c = _a.pathOffset, pathOffset = _c === void 0 ? 0 : _c, \n // This is object creation, which we try to avoid per-frame.\n latest = __rest(_a, [\"attrX\", \"attrY\", \"originX\", \"originY\", \"pathLength\", \"pathSpacing\", \"pathOffset\"]);\n buildHTMLStyles(state, latest, options, transformTemplate);\n state.attrs = state.style;\n state.style = {};\n var attrs = state.attrs, style = state.style, dimensions = state.dimensions, totalPathLength = state.totalPathLength;\n /**\n * However, we apply transforms as CSS transforms. So if we detect a transform we take it from attrs\n * and copy it into style.\n */\n if (attrs.transform) {\n if (dimensions)\n style.transform = attrs.transform;\n delete attrs.transform;\n }\n // Parse transformOrigin\n if (dimensions &&\n (originX !== undefined || originY !== undefined || style.transform)) {\n style.transformOrigin = calcSVGTransformOrigin(dimensions, originX !== undefined ? originX : 0.5, originY !== undefined ? originY : 0.5);\n }\n // Treat x/y not as shortcuts but as actual attributes\n if (attrX !== undefined)\n attrs.x = attrX;\n if (attrY !== undefined)\n attrs.y = attrY;\n // Build SVG path if one has been measured\n if (totalPathLength !== undefined && pathLength !== undefined) {\n buildSVGPath(attrs, totalPathLength, pathLength, pathSpacing, pathOffset, false);\n }\n}",
"function setRectAttr(rectEl, x, y, width, height) {\n rectEl.each(function () {\n $(this).attr({\n x: roundTo(x,2),\n y: roundTo(y,2),\n width: roundTo(width,2),\n height: roundTo(height,2),\n });\n });\n }",
"updateAttributes(newCoords, newDims) {\n let newX, newY, newW, newH;\n if (newCoords) {\n newX = newCoords[0];\n newY = newCoords[1];\n this.setCoordinates(newX, newY);\n }\n if (newDims) {\n newW = newDims[0];\n newH = newDims[1];\n this.setDimensions(newW, newH);\n }\n }",
"updateSelectable(data, svgGroup) {\n\t\tlet self = this;\n\t\tlet heightScale = d3.scaleLinear().domain([0, 100]).range([this.buttonMenuHeight, this.buttonMenuHeight + this.barGroupHeight]);\n\t\tlet widthScale = d3.scaleLinear().domain([0, 100]).range([0, this.barGroupWidth]);\n\t\tlet dataLenInv = 1 / data.length; \n \n /* Temporarily deselect the selected row, if selected. */\n d3.select(\".row-overlay.active\").classed(\"active\", false);\n\n svgGroup.append(\"rect\").classed(\".bar\", true);\n\t\tlet rects = svgGroup.selectAll(\".bar\").data(data);\n\t\trects.exit().remove();\n\t\tlet enterRects = rects.enter().append(\"rect\");\n\n\t\tenterRects\n\t\t\t.attr(\"x\", 0)\n\t\t\t.attr(\"width\", widthScale(100))\n\t\t\t.style(\"stroke-width\", 0);\n\n\t\tlet allRects = enterRects.merge(rects);\n\t\tallRects.attr(\"y\", (d, i) => {return heightScale((i * dataLenInv) * 100)})\n\t\t\t.attr(\"height\", dataLenInv * this.barGroupHeight)\n\t\t\t.classed(\"row-overlay\", true)\n\t\t\t.classed(\"active\", (d,i) => { return (d.x == self.selectedx && d.y == self.selectedy);})\n\t\t\t.on(\"mouseover\", function(d,i) {\n\t\t\t\td3.select(this).classed(\"hover\", true);\n\t\t\t\tif (self.imageview != null)\n \t\t\tself.imageview.hoverPixel(d.x, d.y);\n\t\t\t})\n \t.on(\"mouseout\", function(d,i) {\n \t\td3.select(this).classed(\"hover\", false);\n \t\tif (self.imageview != null)\n \t\t\tself.imageview.hoverPixel(-1000, -1000);\n \t})\n \t.on(\"click\", function(d,i) {\n \t\tself.selectedx = d.x;\n \t\tself.selectedy = d.y;\n \t\td3.select(\".row-overlay.active\").classed(\"active\", false);\n \t\td3.select(this).classed(\"active\", true);\n \t\tif (self.imageview != null)\n \t\t\tself.imageview.selectPixel(d.x, d.y);\n \t\tif (self.raytreeview != null)\n\t\t\t\t\tself.raytreeview.selectPixel(d.x, d.y);\n\n \t\t/* TODO: update tree view */\n \t});\n\n\t\treturn allRects;\n\t}",
"_updateAttributes() {\n const attributeManager = this.getAttributeManager();\n\n if (!attributeManager) {\n return;\n }\n\n const props = this.props; // Figure out data length\n\n const numInstances = this.getNumInstances();\n const startIndices = this.getStartIndices();\n attributeManager.update({\n data: props.data,\n numInstances,\n startIndices,\n props,\n transitions: props.transitions,\n // @ts-ignore (TS2339) property attribute is not present on some acceptable data types\n buffers: props.data.attributes,\n context: this\n });\n const changedAttributes = attributeManager.getChangedAttributes({\n clearChangedFlags: true\n });\n this.updateAttributes(changedAttributes);\n }",
"function setSelectionNamespaces(oXmlDom) {\n\n\tvar sNamespaces = \"\";\n\n\tfor (var i = 0; i < oXmlDom.documentElement.attributes.length; i++) {\n\t\tvar oAttrib = oXmlDom.documentElement.attributes(i);\n\t\tif (oAttrib.nodeName.indexOf(\"xmlns\") != -1) {\n\t\t\tif (oAttrib.nodeName == \"xmlns\") {\n\t\t\t\tsNamespaces += \"xmlns:dflt='\" + oAttrib.nodeValue + \"' \";\n\t\t\t} else {\n\t\t\t\tsNamespaces += oAttrib.nodeName + \"='\" + oAttrib.nodeValue + \"' \";\n\t\t\t}\n\t\t}\n\t}\n\n\t// Set the property\n\toXmlDom.setProperty(\"SelectionNamespaces\", sNamespaces);\n}",
"function addAttributes(node, attrs) {\n for (var name in attrs) {\n var mode = attrModeTable[name];\n if (mode === IS_PROPERTY || mode === IS_EVENT) {\n node[name] = attrs[name];\n }\n else if (mode === IS_ATTRIBUTE) {\n node.setAttribute(name.toLowerCase(), attrs[name]);\n }\n else if (dataRegex.test(name)) {\n node.setAttribute(name, attrs[name]);\n }\n }\n var inlineStyles = attrs.style;\n if (!inlineStyles) {\n return;\n }\n var style = node.style;\n for (var name in inlineStyles) {\n style[name] = inlineStyles[name];\n }\n }",
"cloneAttributes(target, source) {\n [...source.attributes].forEach( attr => { target.setAttribute(attr.nodeName === \"id\" ? 'data-id' : attr.nodeName ,attr.nodeValue) })\n }",
"function colorChange(selectObj, dataname) {\n var idx = selectObj.selectedIndex;\n var color = selectObj.options[idx].value;\n\n d3.select(\"#\" + dataname)\n .attr(\"style\", \"stroke: \" + color)}",
"function setTorq (someClass){\n done = (d3.selectAll(someClass)\n .transition()\n .style('opacity', 1)\n .duration(1500)\n .style(\"fill\", \"turquoise\")\n +\n d3.selectAll(someClass + \"Obj\")\n .transition()\n .style('opacity', 1)\n .duration(1500)\n .style(\"stroke\", \"turquoise\"));\n return done\n }",
"_updateSVG() {\n this.SVGInteractor.updateView(this.currentXRange, this.currentYRange, this.width, this.height);\n this.SVGInteractor.updateSelectView(this._currentSelectionPoints);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a function called triple that takes a number as an argument and returns the result of that number multiplied by 3. | function triple(number) {
return number * 3
} | [
"function multiplysNum(n1, n2, n3){\n alert (n1 * n2 * n3)\n}",
"function multiplicationNum (num1, num2, num3) {\n totalMultipication = num1 * num2 * num3;\n return totalMultipication;\n}",
"function sumOfThree(x) \n {\n return x[0] + x[1] + x[2];\n }",
"function multiOf(num , num2 ,num3)\n {\n\n \tif(num3 != 0)\n \t{\n \t\treturn num2*multiOf(num , num2 , num3-1);\n \t}\n return num;\n\n }",
"static length3sq(it) { return (it.x*it.x)+(it.y*it.y)+(it.z*it.z); }",
"function multiply(a, b, c) {\n const result = multiply_curried(a)(b)(c);\n return result;\n}",
"function doubleThird(array){\r\n\t//Generating a copy of the array parameter\r\n\tvar array_copy = new Array();\r\n\t//Steps through the array that was the parameter\r\n\tfor(var i =0; i<array.length; i++){\r\n\t\t//Tests if the current location is a multiple of 3 or i+1 for zero indexes\r\n\t\tif((i+1)%3==0){\r\n\t\t\t//If the test passes, double the original into the new location \r\n\t\t\tarray_copy[i]=array[i]*2;\r\n\t\t//Passes all array locations that are not divisible by 3\r\n\t\t}else{\r\n\t\t\t//Copying the old array into the new one\r\n\t\t\tarray_copy[i]=array[i];\r\n\t\t}\r\n\t}\r\n\t//Returns the adjusted copy of the array parameter\r\n\treturn array_copy;\r\n}",
"static length3(it) { return Math.sqrt( (it.x*it.x)+(it.y*it.y)+(it.z*it.z) ); }",
"function tuple3Of(a, b, c) {\n var self = getInstance(this, tuple3Of);\n self.types = rest(arguments);\n return self;\n}",
"multiplyByFloats(x, y, z) {\n return new Vector3(this.x * x, this.y * y, this.z * z);\n }",
"function multiFourAndReturn(n1,n2,n3,n4){\n return n1*n2*n3*n4\n}",
"function avg(num1, num2, num3){\n return (num1 + num2 + num3)/3;\n}",
"function highestProductOf3(array) {\n //check that array has at least 3 elements\n if (array.length < 3) {throw new Error('Less than 3 items!')}\n\n // start at the 3rd item (index 2)\n // so pre-populate highest and lowest based on\n // the first 2 items\n\n let highest = Math.max(array[0], array[1]);\n let lowest = Math.min(array[0], array[1]);\n\n let highestProductOf2 = array[0] * array[1];\n let lowestProductOf2 = array[0] * array[1];\n\n let highestProductOf3 = array[0] * array[1] * array[2];\n\n //walk thorugh the items, starting at index 2\n for (let i = 2; i < array.length ; i++) {\n let current = array[i]\n\n //do we have a highest product of 3?\n // it's either the current highest,\n // or the current times the highest prod of 2\n // or the current times the lowest prod of 2\n highestProductOf3 = Math.max(\n highestProductOf3,\n current * highestProductOf2,\n current * lowestProductOf2\n );\n\n // do we have a new highest product of two?\n highestProductOf2 = Math.max(\n highestProductOf2,\n current * highest,\n current * lowest\n );\n\n lowestProductOf2 = Math.min(\n lowestProductOf2,\n current * highest,\n current * lowest\n )\n\n // do we have a new highest?\n highest = Math.max(highest, current);\n\n //do we have a new lowest?\n lowest = Math.min(lowest, current);\n }\n return highestProductOf3;\n}",
"function piSum3(a, b) {\n return sum(\n x => 1.0 / (x * (x + 2)), //piTerm\n a,\n x => x + 4, //piNext\n b\n );\n}",
"function curry3$3(f) {\n function curried(a, b, c) {\n // eslint-disable-line complexity\n switch (arguments.length) {\n case 0:\n return curried;\n case 1:\n return curry2$3(function (b, c) {\n return f(a, b, c);\n });\n case 2:\n return function (c) {\n return f(a, b, c);\n };\n default:\n return f(a, b, c);\n }\n }\n return curried;\n }",
"function multiplyBy2(item) {\n console.log(item * 2);\n}",
"function creerMultiplicateur2(n){\n\n\tif (arguments.length === 2) {\n\t\tvar x = arguments[1];\n\t\treturn n * x;\n\n\t}else if (arguments.length === 1 ){\n\t\treturn (x) => x * n;\n\t}\n\n}",
"function product (a, b){\n return a*b;\n}",
"function multiplizieren(a,b) {\r\n return a * b ;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Synchronously perform change detection on a root view and its components. | function detectChangesInRootView(lView) {
tickRootContext(lView[CONTEXT]);
} | [
"function notifyObservers() {\n _.each(views, function (aView) {\n aView.update();\n });\n } // notifyObservers",
"function walkViewTree(rootView, fn) {\n let visit_ = view => {\n fn(view);\n\n let nsArray = view.subviews();\n let count = nsArray.count();\n for (let i = 0; i < count; i++) {\n visit_(nsArray.objectAtIndex(i));\n }\n };\n\n visit_(rootView);\n}",
"updateView() {\n if (!this.view) {\n this.initDialog();\n }\n\n this.view.updateView();\n }",
"function test_view_update_depth_logic() {\n let viewWrapper = make_view_wrapper();\n\n // create an instance-specific dummy method that counts calls t\n // _applyViewChanges\n let applyViewCount = 0;\n viewWrapper._applyViewChanges = function() {\n applyViewCount++;\n };\n\n // - view update depth basics\n Assert.equal(viewWrapper._viewUpdateDepth, 0);\n viewWrapper.beginViewUpdate();\n Assert.equal(viewWrapper._viewUpdateDepth, 1);\n viewWrapper.beginViewUpdate();\n Assert.equal(viewWrapper._viewUpdateDepth, 2);\n viewWrapper.endViewUpdate();\n Assert.equal(applyViewCount, 0);\n Assert.equal(viewWrapper._viewUpdateDepth, 1);\n viewWrapper.endViewUpdate();\n Assert.equal(applyViewCount, 1);\n Assert.equal(viewWrapper._viewUpdateDepth, 0);\n\n // - don't go below zero! (and don't trigger.)\n applyViewCount = 0;\n viewWrapper.endViewUpdate();\n Assert.equal(applyViewCount, 0);\n Assert.equal(viewWrapper._viewUpdateDepth, 0);\n\n // - depth zeroed on clear\n viewWrapper.beginViewUpdate();\n viewWrapper.close(); // this does little else because there is nothing open\n Assert.equal(viewWrapper._viewUpdateDepth, 0);\n}",
"install() {\n\t\t// this preamble is copied from the base implementation to make sure that we can run install\n\t\tconsole.assert(this.getStatus()!=States.NoLongerCompatile, `PolyfillObjectMixin '${this.name}' can not be installed because the target Atom code has changed since it was written`);\n\t\tif (this.getStatus()!=States.Uninstalled) return;\n\n\t\tdeps.changeStart(this);\n\n\t\t// save the old tree-view.autoReveal value and then get rid of its schema\n\t\tconst oldValue = atom.config.get('tree-view.autoReveal');\n\t\tatom.config.removeSchema('tree-view.autoReveal');\n\t\tthis.origAutorevealSchema = atom.config.getSchema('tree-view.autoReveal');\n\n\t\t// do the normal polyfill install\n\t\tsuper.install();\n\n\t\t// find and replace the handler that TreeView registers with the workspace center object\n\t\tconst handlers = atom.workspace.getCenter().paneContainer.emitter.handlersByEventName[\"did-change-active-pane-item\"];\n\t\tfor (let i=0; i<handlers.length; i++) {\n\t\t\tif (/tree-view.autoReveal/.test(handlers[i])) {\n\t\t\t\tthis.prevHandler = handlers[i];\n\t\t\t\thandlers[i] = (...p)=>{this.target.repondToActiveEditorFocusChange(...p)}\n\t\t\t}\n\t\t}\n\n\t\t// if the user had it set to the non-default value, then set it in its new place\n\t\tif (oldValue)\n\t\t\tatom.config.set('tree-view.autoTrackActivePane.autoReveal', true);\n\n\t\tdeps.changeEnd(this);\n\t}",
"repaintViews() {\n\n for (let viewport of this.viewports) {\n if (viewport.isVisible()) {\n viewport.repaint()\n }\n }\n\n if (typeof this.track.paintAxis === 'function') {\n this.paintAxis()\n }\n\n this.repaintSampleInfo()\n\n this.repaintSamples()\n }",
"childrenChanged() {\n if (true === this.adjustGroupWhenChildrenChange) {\n this.adjustChildrenVertically();\n this.adjustChildrenHorizontally();\n }\n }",
"function refreshFields(view,focus,changes,path,iserror) {\n // to improve: find scroll parent better.\n var fields = getRefreshFields(view.form.children,changes,path,iserror);\n if (fields.length) {\n var callback = makeCountCallback(fields.length,function(){\n restoreFocus(view,focus);\n });\n fields.forEach(function(el){\n adaptChildrenLength(el,changes[el.propertyId]);\n el.setValue(changes[el.propertyId]);\n el.refresh(callback);\n });\n }\n }",
"updateView() {\r\n if (ViewportService.isDesktop != this.state.isDesktopView){\r\n this.setState({ isDesktopView: ViewportService.isDesktop});\r\n }\r\n }",
"setRoot(root) {\n if (this._root != root) {\n this._root = root\n this.observer.setWindow(\n (root.nodeType == 9 ? root : root.ownerDocument).defaultView ||\n window\n )\n this.mountStyles()\n }\n }",
"watch() {\n if (this.shouldUpdate()) {\n this.trigger('change', this.rect);\n }\n\n if(!this.shouldStop){\n window.requestAnimationFrame(() => this.watch());\n }\n }",
"projectChanged() {\n const oldSI = this.getSimulationInterface();\n this.checkForDepositLibrary();\n this.treeController.reloadTree();\n this.workspaceController.resetEditors();\n const newSI = this.getSimulationInterface();\n oldSI.transferCallbacks(newSI);\n }",
"function updateUI() {\n showFolderOrFileContentById(navigationHistory.getCurrentId(), true);\n var treeState = getExplorerState();\n showFoldersTree(treeState);\n }",
"async [notifyProject]() {\n this.dispatchEvent(new CustomEvent('projectschange'));\n await this.requestUpdate();\n // @ts-ignore\n if (this.notifyResize) {\n // @ts-ignore\n this.notifyResize();\n }\n }",
"onMailViewChanged() {\n // only do this if we're currently active. no need to queue it because we\n // always update the mail view whenever we are made active.\n if (this.active) {\n // you cannot cancel a view change!\n window.dispatchEvent(\n new Event(\"MailViewChanged\", { bubbles: false, cancelable: false })\n );\n }\n }",
"_handleModelNodesChanged(event) {\n event.changes.keys.forEach( (value, key) => {\n if (value.action === 'add') {\n let syncedModelNode = event.currentTarget.get(key);// event.object.get(key);\n let modelNodeElement = this._addModelNode(syncedModelNode);\n\n // check if the node was created locally\n if (this._lastLocallyCreatedElementId === syncedModelNode.id) {\n // check if we have children to sync\n let childrenArray = modelNodeElement.getChildrenArray();\n childrenArray.forEach(item => {\n if (this._syncedModelNodes.get(item.id) === undefined) {\n //let sharedState = this.direwolfSpace.sharedStates.set(item.id, Y.Map);\n //item.sharedState = sharedState;\n this._syncedModelNodes.set(item.id, item);\n }\n });\n\n // activate manipulators\n this._activateNodeManipulators(modelNodeElement.element.node);\n modelNodeElement.element.node.classList.add('animated');\n modelNodeElement.element.node.classList.add('fadeIn');\n }\n } else if (value.action === 'delete') {\n // delete\n let modelNode = this._modelNodes[key];\n //TODO: add animation\n modelNode.element.remove();\n delete this._modelNodes[key];\n this._modelNodesDataTree = this._calculateModelNodesDataTree();\n // hide manipulators\n this._modelManipulators.setAttribute('visibility', 'hidden');\n this._elementPropertiesPanel.elementProperties = {};\n this._elementPropertiesPanel.hidden = true;\n this._htmlBindingPropertiesPanel.elementProperties = {};\n this._htmlBindingPropertiesPanel.hidden = true;\n this._deleteButton.disabled = true;\n this._selectedElementTitle = '';\n }\n });\n }",
"async init() {\n this.handleEventHandlers()\n await this.model.load().then(\n res => {\n if (res) {\n this.setupView(res)\n }\n }\n )\n }",
"function HandleChangeHook(rootComponent, payloadPath) {\n this.rootComponent = rootComponent;\n this.payloadPath = payloadPath;\n}",
"changed() {\n ++this.revision_;\n this.dispatchEvent(EventType.CHANGE);\n }",
"function updateLoaded() {\n $scope.loaded = $scope.nodeHasLoaded && $scope.managersHaveLoaded;\n if ($scope.loaded) {\n updateInterfaces();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Define small collection of default pagelets, this prevents code duplication. | function Pagelets() {
this.navigation = require('./pagelets/navigation');
this.footer = contour.footer;
this.analytics = contour.analytics.extend({
data: {
domain: 'browsenpm.org',
key: 'gikqh9ctxn',
type: 'segment'
}
});
} | [
"addDefaultParameters() {\n // for (let parameterData of[{ name: 'page_count', type: Parameter.type.number, eval: false, editable: false, showOnlyNameType: true }, { name: 'page_number', type: Parameter.type.number, eval: false, editable: false, showOnlyNameType: true }]) {\n // let parameter = new Parameter(this.getUniqueId(), parameterData, this);\n // let parentPanel = this.mainPanel.getParametersItem();\n // let panelItem = new MainPanelItem(\n // 'parameter', parentPanel, parameter, { hasChildren: false, showAdd: false, showDelete: false, draggable: false }, this);\n // parameter.setPanelItem(panelItem);\n // parentPanel.appendChild(panelItem);\n // parameter.setup();\n // this.addParameter(parameter);\n // }\n }",
"function initPaging() {\n vm.pageLinks = [\n {text: \"Prev\", val: vm.pageIndex - 1},\n {text: \"Next\", val: vm.pageIndex + 1}\n ];\n vm.prevPageLink = {text: \"Prev\", val: vm.pageIndex - 1};\n vm.nextPageLink = {text: \"Next\", val: vm.pageIndex + 1};\n }",
"function appendPages(pages) {\r\n var menuTemplate = \"\";\r\n for (let page of pages) {\r\n addMenuItem(page);\r\n addPage(page);\r\n }\r\n setDefaultPage(pages[0].slug); // selecting the first page in the array of pages\r\n getPersons();\r\n getTeachers();\r\n}",
"mapDefaultNav(length, currentSlide) {\n let defaultNav = [];\n for (var i = 0; i < length; i++) {\n var className = `dot ${i === currentSlide ? \"dot-active\" : \"\"}`;\n defaultNav.push(<div key={`navItem-${i}`} className={className} />);\n }\n return defaultNav;\n }",
"function load_core_htmls(){\n switch(user['type'])\n {\n case 0:\n get_client(1);\n break;\n case 1:\n get_clients(1);\n break;\n case 2:\n get_agg(1);\n break;\n default:\n break;\n }\n}",
"function appendPages(pages) {\n var menuTemplate = \"\";\n for (let page of pages) {\n addMenuItem(page);\n addPage(page);\n }\n setDefaultPage(pages[0].slug); // selecting the first page in the array of\n getBoeger();\n getKrystaller();\n getMaetter();\n setTimeout(function() {\n showLoader(false);\n }, 500);\n}",
"addDefaultRenderers() {\r\n this.addRenderer(new FlowRendererText(this.settings));\r\n this.addRenderer(new FlowRendererImage(this.settings));\r\n this.addRenderer(new FlowRendererHero(this.settings));\r\n this.addRenderer(new FlowRendererThumbnail(this.settings));\r\n this.addRenderer(new FlowRendererCarousel(this.settings));\r\n this.addRenderer(new FlowRendererList(this.settings));\r\n this.addRenderer(new FlowRendererPrompt(this.settings));\r\n this.addRenderer(new FlowRendererReceipt(this.settings));\r\n }",
"get useDefaultComponents() { return true }",
"function setupDomElements() {\n\tconst DEFAULT_RENDER_SPEC = {\n\t\tplayer1: 'player1',\n\t\tplayer1ctrl: 'player1Ctrl',\n\t\tplayer2: 'player2',\n\t\tplayer2ctrl: 'player2Ctrl',\n\t\tmessages: 'messages',\n\t\trounds: 'roundIndicator'\n\t};\n\tlet key;\n\tfor (key in DEFAULT_RENDER_SPEC) {\n\t\tlet el = document.createElement('div');\n\t\tel.setAttribute('id', DEFAULT_RENDER_SPEC[key]);\n\t\tdocument.body.appendChild(el);\n\t}\n}",
"function indexPages(header) {\n var map = {};\n u.each(generator.pages, function(page) {\n u.each(u.getaVals(page, header), function(val) {\n map[val] = page._href;\n });\n });\n // inject redirect for trailing slash on editorPrefix (TODO - logic for other pages)\n if (header === 'redirect' && opts.editor) {\n map[opts.editorPrefix] = opts.editorPrefix + '/';\n if (opts.editorPrefix !== '/pub') {\n map['/pub'] = map['/pub/'] = opts.editorPrefix + '/';\n }\n }\n return map;\n }",
"function initAll(handler){\r\n let overrideProxy=new Proxy({},{\r\n has:function(target,prop){\r\n return true\r\n },\r\n get:function(target,prop){\r\n return newElementHolderProxy()[prop](handler)\r\n }\r\n }\r\n )\r\n return newElementHolderProxy(undefined,overrideProxy)\r\n }",
"function Pager(){\n\tthis.routes = {};\n\n\tthis.ctx = new PageContext();\n\n\tthis.start();\n\n\tbindEvents();\n}",
"function initPage(){\r\n\t\t//add head class\r\n\t\t$(\"#headAssemblyLi\").addClass(\"active\");\r\n\t\t$(\"#leftNodeSelectLi\").addClass(\"active\");\r\n\t\tresetPage();\r\n\t\t$(\"#messageAlert, #messageLane\").hide();\r\n\t}",
"function createDefaultSetupButtons () {\n\t//Removes all buttons\n\t$(\".newButton\").remove();\n\t//Creates Names (if statement changes name of buttons)\n\tvar setupIds = {\n\t\t\"button_human\": \"Human\",\n\t\t\"button_elf\": \"Elf\",\n\t\t\"button_dwarf\": \"Dwarf\"\n\t}\n\t//This is what to edit if you want to add more shared params to the set of buttons that's being created\n\tcreateAndAddSetOfButtons(\".button_stack\", {classes: \"newButton\", mouseleave:mousePreviewLeave, mouseenter:mousePreviewEnter, click:chooseRace}, setupIds);\n}",
"createPageChain(pages) {\n\t\t/* eslint-disable no-loop-func */\n\n\t\t// This will be our return value.\n\t\t//\n\t\t// This `Object.create()` call creates a new empty object\n\t\t// (`{}`) with `PAGE_CHAIN_PROTOTYPE` as its prototype.\n\t\t//\n\t\tvar pageChain = Object.create(PAGE_CHAIN_PROTOTYPE);\n\n\t\t// Make sure all page classes have been augmented with the\n\t\t// methods provided by `PAGE_MIXIN`.\n\t\tpages.forEach(lazyMixinPageUtilMethods);\n\n\t\t// Wire up the chained methods.\n\t\tfor (var method in PAGE_METHODS){\n\n\t\t\tif (!PAGE_METHODS.hasOwnProperty(method)) continue;\n\n\t\t\tvar [defaultImpl, standardize] = PAGE_METHODS[method];\n\n\t\t\t// Take bound methods for each page/middleware that\n\t\t\t// implements (plus the default implementation), and\n\t\t\t// chain them together so that each receives as an\n\t\t\t// argument the rest of the chain in the form of an\n\t\t\t// arity-zero function.\n\t\t\t//\n\t\t\t// The `next` argument in the reduction here is the\n\t\t\t// accumulated chain. It is what each implementation\n\t\t\t// will receive as _its_ `next` argument.\n\t\t\t//\n\t\t\tpageChain[method] = logInvocation(method, pages\n\t\t\t\t.filter (page => page[method])\n\t\t\t\t.map (page => page[method].bind(page))\n\t\t\t\t.concat ([defaultImpl])\n\t\t\t\t.map (makeStandard.bind(null, standardize))\n\t\t\t\t.reduceRight ((next, cur) => cur.bind(null, next))\n\t\t\t);\n\t\t}\n\n\t\t// Wire up the un-chained methods.\n\t\tObject.keys(PAGE_HOOKS).forEach(method => {\n\n\t\t\t// Grab a list of pages that implement this method.\n\t\t\tvar implementors = pages.filter(page => page[method]);\n\n\t\t\t// The resulting function calls each implementor's\n\t\t\t// method in turn and returns an array containing in\n\t\t\t// their return values.\n\t\t\tpageChain[method] = logInvocation(method, function(){\n\n\t\t\t\t// The `arguments` object isn't a real array.\n\t\t\t\t// Pre-es5 `Function.apply()` required a real\n\t\t\t\t// array. This `[].slice.call(arguments)`\n\t\t\t\t// idiom creates a real array with the elements\n\t\t\t\t// of the `arguments` object.\n\t\t\t\t//\n\t\t\t\t// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice\n\t\t\t\t//\n\t\t\t\tvar args = [].slice.call(arguments);\n\n\t\t\t\treturn implementors.map(\n\t\t\t\t\tpage => page[method].apply(page, args)\n\t\t\t\t)\n\t\t\t});\n\t\t});\n\n\t\treturn pageChain;\n\t\t/* eslint-enable no-loop-func */\n\t}",
"function Help_initialiseAll(){\n\t\n\t// object holding all help class instances\n\tHelp_All = new Object();\n\t\n\t// ids of all main help divs\n\tvar $helpDivs = $('.hapi-help');\n\t\n\t$.each($helpDivs, function(index, $helpDiv){\n\t\t\n\t\t// id\n\t\tvar divId = $helpDiv.id; \n\t\t\n\t\t// create a new instance\n\t\tHelp_All[divId] = new Help(divId);\n\t\n\t});\t\n\t\n}",
"function default_webpack_assets() {\n\tvar webpack_assets = {\n\t\tjavascript: {},\n\t\tstyles: {}\n\t};\n\n\treturn webpack_assets;\n}",
"function combineMenuAndPage() {\n Object.keys(menuTopDownDom).forEach(function(nav) {\n var menu = menuTopDownDom[nav];\n var page = pageTopDownDom[nav];\n Object.keys(menu).forEach(function(header) {\n menu[header].forEach(function(item) {\n var pane = item+'c';\n if(page){\n page[pane].forEach(function(container) {\n createTopDownDOM(nav, header, item, pane, container);\n createDownTopDOM(nav, header, item, pane, container);\n }) } }) }) }) }",
"static registerDefaultComponent(component) {\n BeastController.basicComponents.push(component);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
See description above for Modifier constructor for details, same technique Painter % (func: Function(ctx, data[ctx, t, dt])[, type: C.PNT_]) | function Painter(func, type) {
func.id = guid();
func.type = type || C.PNT_USER;
func[C.MARKERS.PAINTER_MARKER] = true;
return func;
} | [
"function Modifier(func, type) {\n func.id = guid();\n func.type = type || C.MOD_USER;\n func.$data = null;\n func.$band = func.$band || null; // either band or time is specified\n func.$time = is.defined(func.$time) ? func.$time : null; // either band or time is specified\n func.$easing = func.$easing || null;\n func.relative = is.defined(func.relative) ? func.relative : false; // is time or band are specified relatively to element\n func.is_tween = (func.is_tween || (func.type == C.MOD_TWEEN) || false); // should modifier receive relative time or not (like tweens)\n // TODO: may these properties interfere with something? they are assigned to function instances\n func[C.MARKERS.MODIFIER_MARKER] = true;\n func.band = function(start, stop) { if (!is.defined(start)) return func.$band;\n // FIXME: array bands should not pass\n if (is.arr(start)) {\n stop = start[1];\n start = start[0];\n }\n if (!is.defined(stop)) { stop = Infinity; }\n func.$band = [ start, stop ];\n return func; }\n func.time = function(value) { if (!is.defined(value)) return func.$time;\n func.$time = value;\n return func; }\n func.easing = function(f, data) { if (!f) return func.$easing;\n func.$easing = convertEasing(f, data,\n func.relative || func.is_tween);\n return func; }\n func.data = function(data) { if (!is.defined(data)) return func.$data;\n func.$data = data;\n return func; }\n return func;\n}",
"enterPropertyModifier(ctx) {\n\t}",
"enterParameterModifier(ctx) {\n\t}",
"enterTypeParameterModifier(ctx) {\n\t}",
"enterMethodModifier(ctx) {\n\t}",
"enterFunctionModifier(ctx) {\n\t}",
"function addParticleType(func) {\r\n\t disParticleTypes.push(func);\r\n\t}",
"createProperty(obj, name, value, post = null, priority = 0, transform = null, isPoly = false) {\n obj['__' + name] = {\n value,\n isProperty: true,\n sequencers: [],\n tidals: [],\n mods: [],\n name,\n type: obj.type,\n __owner: obj,\n\n fade(from = 0, to = 1, time = 4, delay = 0) {\n Gibber[obj.type].createFade(from, to, time, obj, name, delay);\n return obj;\n }\n\n };\n Gibber.addSequencing(obj, name, priority, value, '__');\n Object.defineProperty(obj, name, {\n configurable: true,\n get: Gibber[obj.type].createGetter(obj, name),\n set: Gibber[obj.type].createSetter(obj, name, post, transform, isPoly)\n });\n }",
"_createPako() {\n const params = {\n raw: true,\n level: this._pakoOptions.level || -1 // default compression\n };\n this._pako = this._pakoAction === 'Deflate' ? new Deflate(params) : new Inflate(params);\n this._pako.onData = (data) => {\n this.push({\n data: data,\n meta: this.meta\n });\n };\n }",
"constructor(paramToTween, startVal, endVal, time) {\r\n this.param = paramToTween;\r\n this.startVal = startVal;\r\n this.endVal = endVal;\r\n this.time = time;\r\n this.elapsedTime = 0;\r\n }",
"visitModifier_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function Bubble(x, y, p) {\n this.x = x;\n this.y = y;\n this.degree = p;\n\n // Dtermines the distance from mouse location.\n this.distX = 0;\n this.distY = 0;\n this.isPressed = false;\n\n // Determines the velocity of the note (range: [0,1]).\n // The diameter is the size of the bubble as used in\n // drawning an p5 ellipse.\n this.vel = VELOCITY;\n this.diam = DIAMETER;\n\n // Determines the coloring starting point.\n this.col = randomColor();\n\n this.display = function() {\n stroke(255);\n fill(this.col);\n ellipse(this.x, this.y, this.diam);\n }\n\n this.pressed = function() {\n let d = dist(mouseX, mouseY, this.x, this.y);\n if (d < this.diam / 2) {\n triggerAttack(this.degree, this.vel);\n this.isPressed = true;\n }\n }\n\n this.released = function () {\n let d = dist(mouseX, mouseY, this.x, this.y);\n if (d < this.diam) {\n this.brighten();\n triggerRelease(this.degree);\n this.isPressed = false;\n }\n }\n\n this.brighten = function () {\n this.col.setAlpha(alpha(this.col) + 1);\n }\n\n this.move = function() {\n this.x = this.x + random(-0.5, 0.5);\n this.y = this.y + random(-0.5, 0.5);\n }\n}",
"static defineModifier() {\n let mod = new Modifier()\n return (tag) => {\n if (tag.modified.indexOf(mod) > -1) return tag\n return Modifier.get(\n tag.base || tag,\n tag.modified.concat(mod).sort((a, b) => a.id - b.id)\n )\n }\n }",
"constructor(dataentry) {\n this.dataentry = dataentry;\n // default to tooltips if not specified otherwise\n this.markStyle = dataentry ? (dataentry.options.markStyle || TOOLTIPS) : TOOLTIPS;\n this.options = _.extend({}, DomDecorator.defaults, dataentry && dataentry.options ? dataentry.options.decoratorOptions : {});\n this._elements = [];\n }",
"enterFieldModifier(ctx) {\n\t}",
"enterClassModifier(ctx) {\n\t}",
"toothPose(n) {\n return { x: 0, y:0, alpha: 0};\n }",
"function modifierVisiteAnnuelle(){\n\t\n}",
"function SeqObjectiveMap() \r\n{\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test: .size should return dimensions for element with margin | function sizeShouldReturnDimensionsForElementWithMargin() {
const data = element.size(fixture.el.querySelector(".size"))
expect(data)
.toEqual({
width: 100,
height: 100
})
} | [
"function measure(element, maxSize) {\n var horizontalMargin = element.margin.left + element.margin.right;\n var verticalMargin = element.margin.top + element.margin.bottom;\n if (element.width && element.width < maxSize.x) { maxSize.x = element.width; }\n if (element.height && element.height < maxSize.y) { maxSize.y = element.height; }\n maxSize.x = Math.max(maxSize.x - element.margin.left - element.margin.right, 0);\n maxSize.y = Math.max(maxSize.y - element.margin.top - element.margin.bottom, 0);\n var size = element.measure(maxSize);\n // element size should be greater or equal to (width, height) if they're set\n if (element.width && size.x < element.width) { size.x = element.width; }\n if (element.height && size.y < element.height) { size.y = element.height; }\n element.size = size;\n if (element.height) { element.size.y = maxSize.y; }\n return vector(size.x + horizontalMargin, size.y + verticalMargin);\n }",
"function getExpectedDimensions(chocolat) {\n var imgWidth = chocolat\n .api()\n .getElem('img')\n .width()\n var imgHeight = chocolat\n .api()\n .getElem('img')\n .height()\n\n var containerWidth = $(chocolat.api().get('container')).width()\n var containerHeight = $(chocolat.api().get('container')).height()\n\n var containerOutMarginH =\n chocolat\n .api()\n .getElem('top')\n .outerHeight(true) +\n chocolat\n .api()\n .getElem('bottom')\n .outerHeight(true)\n var containerOutMarginW =\n chocolat\n .api()\n .getElem('left')\n .outerWidth(true) +\n chocolat\n .api()\n .getElem('right')\n .outerWidth(true)\n\n var containerPaddedWidth = containerWidth - containerOutMarginW\n var containerPaddedHeight = containerHeight - containerOutMarginH\n\n var imgRatio = imgHeight / imgWidth\n var containerRatio = containerHeight / containerWidth\n var containerPaddedRatio = containerPaddedHeight / containerPaddedWidth\n\n return {\n imgWidth: imgWidth,\n imgHeight: imgHeight,\n containerWidth: containerWidth,\n containerHeight: containerHeight,\n containerOutMarginH: containerOutMarginH,\n containerOutMarginW: containerOutMarginW,\n containerPaddedWidth: containerPaddedWidth,\n containerPaddedHeight: containerPaddedHeight,\n imgRatio: imgRatio,\n containerRatio: containerRatio,\n containerPaddedRatio: containerPaddedRatio,\n }\n}",
"function canvasSize({\n textStyle = 0,\n size = 300,\n primaryText = \"\",\n secondaryText = \"\",\n displaySize = false,\n }) {\n let scale = size / 300;\n let scaledWidth = 890;\n let scaledHeight = 300;\n\n switch (textStyle) {\n case 1:\n scaledWidth = Math.max(getTextWidth(primaryText, \"bold 120px Metropolis,Arial\"), getTextWidth(secondaryText, \"bold 120px Metropolis,Arial\"));\n if (scaledWidth < 800) {\n scaledWidth = 800;\n }\n if (secondaryText === \"\") {\n scaledHeight = 450;\n } else {\n scaledHeight = 600;\n }\n break;\n\n default:\n scaledWidth = 800;\n scaledHeight = 300;\n }\n\n let width = Math.round(scaledWidth * scale);\n let height = Math.round(scaledHeight * scale);\n if (width % 2 !== 0) {\n width += 1;\n }\n if (height % 2 !== 0) {\n height += 1;\n }\n\n if (displaySize) {\n let dimension_icon = document.getElementById('dimensions-icon');\n dimension_icon.textContent = \"(Size: \" + size + \"x\" + size + \") \";\n\n let dimension_symbol = document.getElementById('dimensions-symbol');\n dimension_symbol.textContent += \"(Size: \" + height + \"x\" + width + \") \";\n }\n\n return [height, width]\n}",
"static _calcDisplaySize(containerElements) {\n for (const locale of cred.locale) {\n const elemSize = cred.svglayout_internal.htmlElementSize(\n containerElements.get(locale)\n );\n if (elemSize.w > 0 || elemSize.h > 0) {\n return elemSize;\n }\n }\n return new geom.Size(0, 0);\n }",
"function setnhdrwrapsizerReducedSizePX(){\r\nvar gseaInitSize = document.getElementById('gsea').offsetHeight;\r\nvar addstuffBarInitSize = document.getElementById('addstuff').offsetHeight;\r\n\r\nvar nhdrwrapsizerReducedSize = gseaInitSize - addstuffBarInitSize;\r\nreturn nhdrwrapsizerReducedSize+\"px\";\r\n}",
"function GetItemRectSize(out = new ImVec2()) {\r\n return bind.GetItemRectSize(out);\r\n }",
"function offsetShouldReturnOffsetsForElementWithMargin() {\n const data = element.offset(fixture.el.querySelector(\".offset\"))\n expect(data)\n .toEqual({\n top: 10,\n right: 10,\n bottom: 10,\n left: 10\n })\n}",
"function sizeShouldThrowOnInvalidElement() {\n expect(() => {\n element.size(\"invalid\")\n }).toThrow(\n new TypeError(\"Invalid element: 'invalid'\"))\n}",
"getRectSize() {\n\t\treturn {\n\t\t\t'width':this.rectArea.width / this.horizontalPeriod.count - this.rectMargin / 2,\n\t\t\t'height':this.rectArea.height / this.verticalPeriod.count - this.rectMargin / 2\n\t\t}\n\t}",
"function find_dimensions()\n{\n numColsToCut= parseInt(NumberofColumns);\n numRowsToCut= parseInt(NumberofRows);\n \n widthOfOnePiece=Target_width/numColsToCut;\n heightOfOnePiece=Target_height/numRowsToCut; \n}",
"get tileSize() {}",
"havingSize(size) {\n if (this.size === size && this.textSize === size) {\n return this;\n } else {\n return this.extend({\n style: this.style.text(),\n size: size,\n textSize: size,\n sizeMultiplier: sizeMultipliers[size - 1]\n });\n }\n }",
"function get_item_size() {\n var sz = 220;\n return sz;\n}",
"getDimensions() {\n return {\n length: this.topLeft.lat - this.bottomLeft.lat,\n width: Math.abs(this.topLeft.long) - Math.abs(this.topRight.long)\n }\n }",
"function getDimensions(element) {\n if (element === window) {\n return {\n height: typeof window.innerHeight === \"number\" ? window.innerHeight : 0,\n width: typeof window.innerWidth === \"number\" ? window.innerWidth : 0\n };\n }\n\n var _element$getBoundingC = element.getBoundingClientRect(),\n width = _element$getBoundingC.width,\n height = _element$getBoundingC.height;\n\n return { width: width, height: height };\n}",
"function getFontSize(relativeSize) {\n return canvas.width * 0.001 * relativeSize;\n}",
"function getDependencySize(dependencyDump) {\n var numeric = dependencyDump.numerics[SIZE_NUMERIC_NAME];\n if (numeric === undefined)\n return 0;\n shouldDefineSize = true;\n return numeric.value;\n }",
"function Size(width,height){this.width=width;this.height=height;}",
"#getParentSize() {\n const comp_style = window.getComputedStyle(this.#canvas.parentNode);\n\n this.#parent_width = parseInt(comp_style.width.slice(0, -2));\n this.#parent_height = parseInt(comp_style.height.slice(0, -2));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks if there are any images for the selected foot param footIndex: 0 => left foot, 1 => right foot returns true if there are any images for the selected foot in the database | existsAnyImages_for_selectedFoot(footIndex) {
try {
if (this.state.toeData.feet[footIndex].toes !== undefined) {
for (let i = 0; i < 5; i++) {//5 toes
if (this.state.toeData.feet[footIndex].toes[i].images.length > 0)
return true;
}
}
} catch {
return false;
}
return false;
} | [
"function checkSlide(e) {\n images.forEach(img => {\n // console.group('image ',img.id)\n const imageMidpoint = (img.offsetTop+(img.clientHeight/2));\n const isInView = (imageMidpoint < window.scrollY+window.innerHeight);\n // console.log('isInView: ', isInView);\n const isOutOfView = (imageMidpoint < window.scrollY);\n // console.log('isOutOfView: ', isOutOfView);\n if (isInView && !isOutOfView) {\n // show when in view AND not out of view\n img.classList.add('active');\n } else {\n // hide when NOT in view\n img.classList.remove('active');\n }\n // console.groupEnd();\n });\n}",
"_computeHasImage(fields) {\n if (\n fields &&\n typeof fields.images !== typeof undefined &&\n typeof fields.images[0] !== typeof undefined &&\n typeof fields.images[0].src !== typeof undefined\n ) {\n return true;\n }\n return false;\n }",
"function checkIndex(imageIndexCheck,previousIndex)\n{\n for(let x=0;x<3;x++){\n \n if(imageIndexCheck==previousImages[previousIndex][x]){\n \n return true;}\n else {\n continue;}\n\n \n }\nreturn false;\n}",
"checkFormulaImageFields() {\n if (this.formulaImageFields) {\n this.columns.forEach((col) => {\n if (this.formulaImageFields.indexOf(col.fieldName) !== -1) {\n col.type = 'image';\n }\n });\n }\n }",
"function checkFoot() {\n\n var foot = document.getElementById('scanFooter');\n if (typeof(foot) !== 'undefined' && foot !== null) {\n return checkFooter = true;\n }\n else {\n return checkFooter = false;\n }\n}",
"function updatePictureFooter() {\n\t$(\"#picture_footer\").html(pictureFound ? \"<center>\" + listOfPicture.length + \" pictures</center>\" : \"<center>No Pictures</center>\");\n}",
"function checkHit() {\r\n \"use strict\";\r\n // if torp left and top fall within the ufo image, its a hit!\r\n let ymin = ufo.y;\r\n let ymax = ufo.y + 65;\r\n let xmin = ufo.x;\r\n let xmax = ufo.x + 100;\r\n\r\n\r\n console.log(\"torp top and left \" + torpedo.y + \", \" + torpedo.x);\r\n console.log(\"ymin: \" + ymin + \"ymax: \" + ymax);\r\n console.log(\"xmin: \" + xmin + \"xmax: \" + xmax);\r\n console.log(ufo);\r\n\r\n if (!bUfoExplode) {\r\n // not exploded yet. Check for hit...\r\n if ((torpedo.y >= ymin && torpedo.y <= ymax) && (torpedo.x >= xmin && torpedo.x <= xmax)) {\r\n // we have a hit.\r\n console.log(\" hit is true\");\r\n\r\n bUfoExplode = true; // set flag to show we have exploded.\r\n }// end if we hit\r\n\r\n }// end if not exploded yet\r\n\r\n // reset fired torp flag\r\n bTorpFired = false;\r\n\r\n // call render to update.\r\n render();\r\n\r\n}// end check hit",
"function isGenomeSelected(tbl) {\n var nRows = 0;\n if (tbl == \"\") { //Not YUI table\n\tvar chkTaxons = document.getElementsByName(\"taxon_filter_oid\");\n\tif (chkTaxons != undefined) {\n\t for (var i=0; i < chkTaxons.length; i++) {\n\t\tif (chkTaxons[i].checked)\n\t\t nRows++;\n\t }\n\t}\n } else { //checkboxes are in a YUI table\n\tnRows = eval(\"oIMGTable_\" + tbl + \".rows\");\n }\n if (nRows < 1 ) {\n alert (\"No genomes were selected.\\n\\n\" +\n\t \"Please select one or more genomes and try again.\");\n return false;\n } else {\n return true;\n }\n}",
"function hasImage(attId) {\n var yes;\n var url = getBaseUrl() + \"colorswatch/index/isdir/\";\n jQuery.ajax(url, {\n async: false,\n method: \"post\",\n data: {\n dir: attId,\n },\n success: function (data) {\n yes = JSON.parse(data).yes;\n },\n });\n return yes;\n}",
"function handlecheckBox() {\n // This will give us the selected Box (parent node, to delete the whole canvasBox) (\"count-xx\")\n var selectedBox = this.parentNode.id;\n\n // Now see if you need to add/or remove selectedBox to imageSelected array\n if (this.checked === true) {\n // If it's checked, then add to imageSelected\n imageSelected.push(selectedBox);\n } else {\n // If not selected, then remove ID from imageSelected\n var boxIndex = imageSelected.indexOf(selectedBox);\n imageSelected.splice(boxIndex, 1);\n }\n}",
"function getMoreImages() {\n\t\t// Return 0 if fetched all images, 1 if enough to fill screen and >1 otherwise\n\t\tvar uncovered_px = $box.height()+$box.offset().top - ($(document).scrollTop()+window.innerHeight),\n\t\t\tuncovered_rows = uncovered_px / settings.row_height;\n\n\t\tif (unloaded) {\n\t\t\t// Don't load more than if not all have loaded (think: slow connections!)\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (!fetched_all) {\n\t\t\tif (uncovered_rows < 2) {\n\t\t\t\tif (!loading_images && settings.getImages) {\n\t\t\t\t\tloading_images = true;\n\t\t\t\t\tsettings.getImages(addNew);\n\t\t\t\t}\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t}",
"is_image() {\n if (\n this.file_type == \"jpg\" ||\n this.file_type == \"png\" ||\n this.file_type == \"gif\"\n ) {\n return true;\n }\n return false;\n }",
"function switch_search_images()\r\n{\r\n search_images = !search_images;\r\n drawControl();\r\n}",
"function checkEndOfPage(firstFill){\r\n\tfirstFill = firstFill || 0;\r\n\tvar endOfPage = document.getElementById('photoGallery').clientHeight;\r\n var lastDiv = document.querySelector(\"#photoBlock > div:last-child\");\r\n var lastDivOffset = lastDiv.offsetTop + lastDiv.clientHeight;\r\n var pageOffset = window.pageYOffset + window.innerHeight;\r\n if(firstFill == 0){\t\r\n\t \tif(Math.round(pageOffset) >= endOfPage){\r\n\t \t\tshowLoading();\r\n\t \t\tgetPhotos(per_page = 5, page = 1, function(data){createNewPhotoBlock(data)});\r\n\t \t}\r\n }\r\n \telse if(lastDivOffset < window.innerHeight){\r\n \tpage++;\r\n\t \tshowLoading();\r\n \t\tgetPhotos(per_page = 5, page, function(data){ createNewPhotoBlock(data, firstFill = 1) });\r\n \t}\r\n\t// \"page++\" variable page here makes the scroll down shows older images, with \"page = 1\" in the function getPhotos, \r\n\t// scroll down shows the newest images in flickr. \r\n\t//The method \"getRecents\" dont verify if the images are duplicated\r\n}",
"function pasarFoto() {\r\n if(posicionActual >= IMAGENES.length - 1) {\r\n posicionActual = 0;\r\n } else {\r\n posicionActual++;\r\n }\r\n renderizarImagen();\r\n }",
"function isBottomRow(clickedIndex){\n if(parseInt(clickedIndex) > $tileArray.length - (row_length+1)) {\n return true;\n } else {\n return false;\n }\n }",
"function tileIsDone(_fb_tile_id) {\n var tile_instance = fb.child(fb_collage_id).child('Tile').child(_fb_tile_id);\n tile_instance.once('value', function(snap) {\n var tile = snap.val(); // dictionary\n console.log(tile);\n if (tile.filled) { // if tile is filled\n return true;\n } else {\n return false;\n }\n })\n}",
"function checkButtons(){\n let listSize = lista.children.length;\n if(listSize == 0){ //If there are no items, all buttons are disabled\n disableButton(butCrop);\n disableButton(butSet);\n disableButton(butGen);\n } else if(listSize == 1){ //If there is only 1 item, it could be used for a new sample or cropper. but is made reference by default.\n enableButton(butGen);\n enableButton(butCrop);\n disableButton(butFind);\n console.log('butFind', butFind);\n if(croppingMode){\n console.log('croppingMode', croppingMode);\n disableButton(butGen);\n disableButton(butFind);\n disableButton(butSet);\n butSet.innerHTML = \"Set\";\n }\n } else if(listSize >= 2){ //With two items is possible to execute the program. \n\n /*/\n FIX THIS PART AS SOON AS YOU FIX THE dispImgInfo array with the promises or callbacks \n /*/\n //if(!dispImgInfo.reference){ //Check whether the selected item is NOT set as reference, in which case activates butSet. \n // enableButton(butSet);\n //}\n\n enableButton(butFind);\n }\n\n}",
"function prevPhoto() {\n\tstoryIndex--; // <-- decrement index\n\n\t// if we've moved before alloted array indices...\n\tif (storyIndex < 0) {\n\t\tstoryIndex++; // <-- increment index to stay in-bounds\n\n\t\t// if a prior story-piece is available...\n\t} else {\n\t\ttextAreaEl.value = storyParts[storyIndex]; // <-- change textArea to new dialogue\n\t\timgEl.src = \"pup_imgs/\" + imgParts[storyIndex] + \".jpg\"; // <-- update image\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
global functions clear the totals and tosserTotals arrays with a zero at each time | function clearTotals() {
for (var i = 0; i < numOpenHours; i++){
totals[i] = 0;
tosserTotals[i] = 0;
}
} | [
"function clearCalculation() {\n calculation = [];\n displayCalculation();\n }",
"reset() {\n /**\n * The overall error.\n */\n this.globalError = 0;\n /**\n * The size of a set.\n */\n this.setSize = 0;\n\n this.sum = 0;\n }",
"function resetCalculations() {\n calculatedBogoMips = null;\n clientEffectsLevel = null;\n calculateJsBogoMips();\n }",
"resetStats() {\n\t\tthis.gameDataList = [];\n\t\tthis.curGameData = null;\n\t}",
"function emptyCompare(){\n productsCompare = [];\n computeCompareProducts();\n updateCounter();\n}",
"function cleansCounters() {\n\tn = 0;\n\tmachinePlay = [];\n\tuserPlay = [];\n\tcount = 0;\n\tcounter = 0;\n\tuserCount = 0;\n}",
"function emptyTotaalKosten(){\n OverigeKosten = 0;\n OpenbaarVervoer = 0;\n AutoKM = 0;\n AutoEuro = 0;\n Totaal = 0;\n}",
"function resetResults() {\n correct = 0;\n incorrect = 0;\n unanswered = 0;\n }",
"updateReconciledTotals() {\n\t\tconst decimalPlaces = 2;\n\n\t\t// Target is the closing balance, minus the opening balance\n\t\tthis.reconcileTarget = Number((this.closingBalance - this.openingBalance).toFixed(decimalPlaces));\n\n\t\t// Cleared total is the sum of all transaction amounts that are cleared\n\t\tthis.clearedTotal = this.transactions.reduce((clearedAmount, transaction) => {\n\t\t\tlet clearedTotal = clearedAmount;\n\n\t\t\tif (\"Cleared\" === transaction.status) {\n\t\t\t\tclearedTotal += transaction.amount * (\"inflow\" === transaction.direction ? 1 : -1);\n\t\t\t}\n\n\t\t\treturn Number(clearedTotal.toFixed(decimalPlaces));\n\t\t}, 0);\n\n\t\t// Uncleared total is the target less the cleared total\n\t\tthis.unclearedTotal = Number((this.reconcileTarget - this.clearedTotal).toFixed(decimalPlaces));\n\t}",
"function clear() {\n\t\tgenerations = [];\n\t\tfittest = [];\n\t}",
"function clearAll() {\n\t\t}",
"clearAll() {\n //geklikt resultaat\n if (this._clickedResult) {\n this._clickedResult.unsubscribe(this);\n this._clickedResult = undefined;\n }\n\n //geklikte cluster\n if(this._clickedCluster){\n this._clickedCluster.unsubscribe(this);\n this._clickedCluster = undefined;\n }\n\n //gezochte resultaten\n this._results.forEach(res => {\n res.unsubscribe(this);\n });\n this._results = [];\n\n //rechts gezochte resultaten.\n this._rightClickedResults.forEach(res => {\n res.unsubscribe(this);\n });\n this._rightClickedResults = [];\n\n this.updateSubscribers();\n }",
"function clear() {\n clearCalculation();\n clearEntry();\n resetVariables();\n operation = null;\n }",
"clearResults() {\n testResults = [];\n }",
"resetCount() {\n this.setStatistics({\n fetchedDocuments: 0,\n migratedDocuments: 0,\n totalDocuments: 0,\n ignoredDocuments: 0,\n });\n }",
"reset() {\r\n\t\tthis.number = this.props.index + 1\r\n\t\tthis.counters = {\r\n\t\t\tfigure: 0\r\n\t\t}\r\n\t\t// TODO: Incorporate equation numbers.\r\n\t}",
"recalculateTotals(inventories) {\n this.filteredInventories = inventories.inventories;\n Service.get(this).calculateTotals(1, inventories.inventories);\n }",
"function resetVars() {\n\t\tidArrays = [];\n\t\tdeathArrays = [];\n\t\tfollowUpArrays = [];\n\t\tdataType = \"number\";\n\t\tsources = 0;\n\t\tNs = [];\n\t\thaveFollowUp = false;\n\t\tdataName = \"\";\n\t\tdragZone = {'left':-1, 'top':-1, 'right':-1, 'bottom':-1, 'name':\"\", 'ID':\"\"};\n\t\tlimits = {'minX':0, 'maxX':0, 'minY':0, 'maxY':0};\n\t\tunique = 0; // number of data points with non-null values\n\t\tNULLs = 0;\n\t\tlocalSelections = []; // the data to send to the parent\n\t}",
"function resetThresholds() {\n \taccumDiff = 0;\n \taccumAmp = 0;\n \tsampleReadRemaining = sampleDecisionThreshold;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Formats the given money. | format (money) {
return `${this.formatSign(money)}${
this.currency.symbol
}${this.commaPeriodSetting.format(
Math.floor(Math.abs(money.amount))
)}${this.formatMoneyFractionPart(money)}`
} | [
"function formatMoney(number){\n return '₹ '+number.toFixed(2).replace(/\\d(?=(\\d{3})+\\.)/g, '$&,');\n}",
"function getMoneyFormatted(val){\n return val.toFixed(2);\n }",
"function formatCurrency(num, addDollarSign) {\n\tvar resultStr = \"\";\n\tvar Str = \"\";\n\n\t// Return immediately if a null value was passed in\n\tif (num == null) return \"0\"\n\n\t// Return immediately if a NaN value was passed in\n\tif (isNaN(num)) return num; // return unchanged\n\n\tif (num < 0) resultStr = \"-\"\n\n\tif (addDollarSign == true) resultStr += \"$\"\t\n\n\t// convert the argument to a string\n\tStr = \"\" + num; \n\tif (Str.charAt(0) == \"-\") {\n\t\tStr = Str.substring(1,Str.length)\n\t}\n\n\t// Get the index of any decimal point.\n\t// If there is a decimal point, strip it\n\tidx = Str.indexOf(\".\");\t\n\tif (idx >= 0)\n\t\tStr = Str.substring(0, idx);\n\n\t// Format output string - insert commas\n\tif (Str.length > 3) {\n\t\tvar x = Str.length % 3 //length of first chunck\n\t\tif (x > 0) resultStr += Str.substring(0, x) + \",\"\n\t\tStr = Str.substring(x, Str.length)\n\t\twhile (Str.length > 3) {\n\t\t\tresultStr += Str.substring(0, 3) + \",\"\n\t\t\tStr = Str.substring(3, Str.length)\n\t\t}\n\t}\n\tresultStr += Str\n\treturn resultStr;\n}",
"function currencyFormat(x) {\n return x.toString().replace(/\\B(?<!\\.\\d*)(?=(\\d{3})+(?!\\d))/g, \".\");\n}",
"function formatTableCurrency(num) {\n var resultStr = \"\";\n var Str = \"\";\n var paddedZero = ' 0 '\n\n // Return immediately if a null value was passed in\n if (num == null) return paddedZero;\n\n // Return immediately if a NaN value was passed in\n if (isNaN(num)) return num; // return unchanged\n\n if (num < 0) resultStr = \"-\"\n\n // convert the argument to a string\n Str = \"\" + num;\n if (Str.charAt(0) == \"-\") {\n Str = Str.substring(1, Str.length)\n }\n\n // Get the index of any decimal point.\n // If there is a decimal point, strip it\n idx = Str.indexOf(\".\");\n if (idx >= 0)\n Str = Str.substring(0, idx);\n\n // Format output string - insert commas\n if (Str.length > 3) {\n var x = Str.length % 3 //length of first chunck\n if (x > 0) resultStr += Str.substring(0, x) + \",\"\n Str = Str.substring(x, Str.length)\n while (Str.length > 3) {\n resultStr += Str.substring(0, 3) + \",\"\n Str = Str.substring(3, Str.length)\n }\n }\n resultStr += Str\n if (resultStr === \"0\") return paddedZero;\n return resultStr;\n}",
"_formatBalance(balance) {\n return parseFloat(balance, 10).toFixed(0).toString();\n }",
"callback(value) { return ynabToolKit.shared.formatCurrency(value); }",
"formatMoneyFractionPart (money) {\n if (this.currency.ratioToMinimumCurrency <= 1) {\n // If the minimum currency ratio is less than or equal to 1\n // Then the fraction part does not exist. e.g. JPY, KRW\n return ''\n }\n\n const digits = Math.log10(this.currency.ratioToMinimumCurrency)\n\n let fraction = money.amount - Math.floor(money.amount)\n fraction = Math.round(this.currency.ratioToMinimumCurrency * fraction)\n fraction = (Array(digits).join('0') + fraction).substr(-digits, digits)\n\n return `${this.commaPeriodSetting.decimalPoint}${fraction}`\n }",
"function converter(number){\n return number.toLocaleString('USD', {style: 'currency',\n currency: 'USD',\n minimumFractionDigits: 2,\n maximumFractionDigits: 2});\n}",
"function formatBTC(x) {\n return formatSymbol(x, symbol_btc);\n}",
"toFixedWithSymbol (field, amount, currency=mCoinSymbol, spaceAfterSymbol=false) {\n return (\n (amount >= 0 ? '' : '-') +\n this.getCurrencySymbol(currency) +\n (spaceAfterSymbol ? ' ' : '') +\n this.toFixed(field, Math.abs(amount), currency)\n );\n }",
"function formatValore(field)\n{\n\tformatDecimal(field,9,6,true);\n}",
"function formatValue(value, isPositive){\n\n var text = \"\";\n if (isPositive === 1) { text += \"+ \"; } else { text += \"- \"; }\n text += value.toFixed(2) + \" €\";\n return text;\n}",
"function getDollarAmount(amount) {\r\n return Math.round(amount).toString();\r\n}",
"function getCurrency(amount) {\n\tvar fmtAmount;\n\tvar opts = {MinimumFractionDigits: 2, maximumFractionDigits: 2};\n\tif (selectedCurrency === \"CAD\") {\n\t\tfmtAmount = \"CAD $\" + amount.toLocaleString(undefined, opts);\n\t} else if (selectedCurrency === \"USD\") {\n\t\tfmtAmount = \"USD $\" + (amount * currencyRates.USD).toLocaleString(undefined, opts);\n\t} else if (selectedCurrency === \"MXN\") {\n\t\tfmtAmount = \"MXN ₱\" + (amount * currencyRates.MXN).toLocaleString(undefined, opts);\n\t} else {\n\t\tthrow \"Unknown currency code: this shouldn't have happened.\";\n\t}\n\treturn fmtAmount;\n}",
"function flowFmt(num){\n // --- set number of decimal places for reporting flow values\n if ( FlowUnits == MGD || FlowUnits == CMS ) {\n return num.toFixed(3).padStart(9);\n }\n else {\n return num.toFixed(2).padStart(9);\n }\n}",
"static amountPriceParser(amount) {\n //delete decimals\n let amountWithoutDecimals = parseInt(amount);\n let amountString = amountWithoutDecimals.toString();\n const regx = /(\\d+)(\\d{3})/;\n while (regx.test(amountString)) {\n amountString = amountString.replace(regx, `$1.$2`);\n }\n return amountString;\n }",
"function formatCurrency(value, options={}) {\n\n if (value == null) {\n return null;\n }\n\n let maxDigits = options.digits || global_settings.PRICING_DECIMAL_PLACES || 6;\n let minDigits = options.minDigits || global_settings.PRICING_DECIMAL_PLACES_MIN || 0;\n\n // Extract default currency information\n let currency = options.currency || global_settings.INVENTREE_DEFAULT_CURRENCY || 'USD';\n\n // Extract locale information\n let locale = options.locale || navigator.language || 'en-US';\n\n let formatter = new Intl.NumberFormat(\n locale,\n {\n style: 'currency',\n currency: currency,\n maximumFractionDigits: maxDigits,\n minimumFractionDigits: minDigits,\n }\n );\n\n return formatter.format(value);\n}",
"formatFee(leveledScore) {\n return Math.round(leveledScore.fee*100)/100;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate HTML for a given wallet | function genWalletHtml(viewModel, index, wallet) {
var walletHtml = jQuery([
'<div id="wallet-' + index + '" class="col-sm-12 col-md-6 col-lg-6 col-xl-4">',
'<div class="card text-light">',
'<div class="card-header bg-flat-color-5">',
'<div class="col-10 pl-0">',
'<h4 class="mb-0 no-wrap">',
wallet.name,
'</h4>',
'</div>',
'<div>',
'<a id="editWallet-' + index + '" class="float-right" href="#"> <i class="text-light fa fa-pencil-square-o"></i></a>',
'</div>',
'</div>',
'<div class="card-body pb-0 text-muted">',
'<table class="table mb-0">',
'<tbody class="mt-0">',
'<tr>',
'<th class="short-table-item" scope="row">' + wallet.currency + '</th>',
'<td class="long-table-item">' + wallet.balance + '</td>',
'<td class="shorter-table-item"></td>',
'</tr>',
'<tr >',
'<th class="short-table-item" scope="row">' + viewModel.selectedExchange +'</th>',
'<td class="dollarValue long-table-item">Pending...</td>',
'<td class="shorter-table-item"><small>est.</small></td>',
'</tr>',
'</tbody>',
'</table>',
'</div>',
'</div>',
'</div>'
].join("\n"));
return walletHtml;
} | [
"function updateWalletHtml(viewModel) {\n jQuery(\"#wallets\").empty();\n\n var walletCount = 0;\n jQuery.each(viewModel.wallets, function(index, element) {\n walletCount++;\n var walletHtml = genWalletHtml(viewModel, index, element);\n\n jQuery(\"#wallets\").append(walletHtml);\n\n // Add the edit button event listener\n jQuery(\"#editWallet-\" + index).click(function (e) {\n e.preventDefault();\n openEditWindow(viewModel, index);\n });\n });\n\n jQuery(\"#loadingMessage\").fadeOut('fast', function(x = walletCount) {\n if (x == 0) {\n jQuery(\"#noWalletsMessage\").hide().removeAttr(\"hidden\").fadeIn();\n } else {\n jQuery(\"#wallets\").fadeIn();\n }\n });\n}",
"static generateWallet() {\n const wallet = EthereumJsWallet.generate();\n\n AnalyticsUtils.trackEvent('Generate wallet', {\n walletAddress: wallet.getAddressString(),\n });\n\n return this.storeWallet(wallet);\n }",
"function generateInternHTML(Intern) {\n return `\n <div class=\"card mb-4\" style=\"width: 18rem;\">\n <div class=\"card-header text-white bg-primary\">\n Intern </br>\n ${Intern.getName()}\n </div>\n <ul class=\"list-group list-group-flush\">\n <li class=\"list-group-item\">ID: ${Intern.getId()}</li>\n <li class=\"list-group-item\">Email: <a href = \"mailto: ${Intern.getEmail()}\">${Intern.getEmail()}<a></li>\n <li class=\"list-group-item\">School: ${Intern.getSchool()}</li>\n </ul>\n </div>\n ` \n }",
"function updateCurrencyExchangeHtml(viewModel) {\n jQuery.each(viewModel.wallets, function(index, wallet) {\n var price = viewModel.cryptoCurrencies[wallet.currency][viewModel.selectedExchange].price;\n var val = (wallet.balance * price).toFixed(2);\n wallet.val = val;\n jQuery(\"#wallet-\" + index).find(\".dollarValue\").hide().html(\"$\" + val).fadeIn('fast');\n });\n\n jQuery(\"#exchangeRates\").hide();\n jQuery(\"#exchangeRates\").empty();\n var exchangeHtml = \"\";\n jQuery.each(viewModel.cryptoCurrencies, function(cryptoCurrency, cryptoData) {\n jQuery(\"#exchangeRates\").append(genCurrencyExchangeHtml(viewModel, cryptoCurrency, cryptoData));\n });\n jQuery(\"#exchangeRates\").fadeIn('fast');\n}",
"function goWalletConsole() {\r\n window.open('walletConsole.html');\r\n window.close();\r\n}",
"function generateHTML()\r\n{\r\n\tlet html = \"\";\r\n \r\n\tlet buckets = roomUsageList.aggregateBy(function(roomUsage){\r\n\t\tlet hour24 = roomUsage.timeChecked.getHours();\r\n\t\tlet hour12 = (hour24 % 12) || 12;\r\n\t\tlet ampm = hour24 < 12 ? \" am\":\" pm\";\r\n\t\tlet hour_str = hour12+ampm;\r\n\t\treturn hour_str;\r\n\t});\r\n\tfor(let i = 0;i<11;i++)\r\n\t{\r\n\t\tlet key = (i+8)%12 || 12;\r\n\t\tkey = key + (i < 4 ? \" am\":\" pm\");\r\n\t\tif(buckets.hasOwnProperty(key))\r\n\t\t{\r\n\t\t\thtml+=generateBucketHTML(key,buckets[key]);\r\n\t\t}\r\n\t}\r\n if(html===\"\")\r\n {\r\n\r\n html = `<div class=\"mdl-cell mdl-cell--4-col\">\r\n <table class=\"mdl-data-table mdl-js-data-table mdl-shadow--2dp\">\r\n <tbody>\r\n <tr><td class=\"mdl-data-table__cell--non-numeric\">No entries</td></tr>\r\n </tbody>\r\n </table>\r\n </div>`;\r\n return html;\r\n }\r\n\treturn html;\r\n}",
"function genCurrencyExchangeHtml(viewModel, cryptoCurrency, cryptoData) {\n var change = cryptoData[viewModel.selectedExchange].change;\n var exchangeRateHtml;\n if (change > 0) {\n exchangeRateHtml = \"<i class='fa fa-arrow-circle-up text-success'></i> +\" + change.toFixed(2) + \"%\";\n } else if (change < 0) {\n exchangeRateHtml = \"<i class='fa fa-arrow-circle-down text-danger'></i> \" + change.toFixed(2) + \"%\";\n } else {\n exchangeRateHtml = \"<i class='fa fa-arrow-circle-right text-warning'></i>\";\n }\n\n var priceHtml = \"</br>$\" + cryptoData[viewModel.selectedExchange].price + \" \" + viewModel.selectedExchange + \" \";\n\n var cryptoExchangeHtml = jQuery([\n \"<li>\",\n \"<a><span class='text-light'>\" + cryptoCurrency + \"<span class='text-muted'> \" + exchangeRateHtml + priceHtml + \"</span></span></a>\",\n \"</li>\"\n ].join(\"\\n\"));\n\n return cryptoExchangeHtml;\n}",
"function generateInternHtml (profiles) {\n const intHtml = [];\n console.log(profiles)\n for (i=0; i< profiles.length; i++) {\n intHtml.push(internHtml(profiles[i]));\n \n }\n return intHtml.join(\"\")\n}",
"function generateStationCardHTML(station) {\n\tvar stationPriceBadgeHTML = \"<h4 class='stationPriceBadge'>\" + station.price.toString() + \"</h4>\";\n\tvar resourcesHTML = \"<p id='stationUpkeep'>Resources Needed : \" +station.upkeepResource + \" x\" + station.upkeepCost.toString() + \"</p>\"\n\tvar productionHTML = \"<p id='stationProduction'>Production : \" +station.production.toString() + \"</p>\"\n\n\tvar html = \" \\\n\t\t<div class='col-sm-6 col-md-3'>\\\n\t\t\t<div class='thumbnail'>\\\n\t\"\n\t+ stationPriceBadgeHTML +\n\t\"\\\n\t\t\t\t<img style='width: 100%; height: 200px; padding-left: 10px; padding-right: 10px;'>\\\n\t\t\t\t<div class='caption'>\\\n\t\"\n\t+ resourcesHTML + productionHTML +\n\t\"\\\n\t\t\t\t\t<p>\\\n\t\t\t\t\t\t<button class='btn btn-primary stationCardButton' onclick='startAuction(\" + station.id.toString() + \")'>Choose</button>\\\n\t\t\t\t\t</p>\\\n\t\t\t\t</div>\\\n\t\t\t</div>\\\n\t\t</div>\\\n\t\";\n\n\treturn html;\n}",
"function sendTest() {\n web3.eth.sendTransaction({\n from: web3.eth.coinbase,\n to: '',\n value: web3.toWei(document.getElementById(\"amount\").value, 'ether')\n }, function(error, result) {\n if (!error) {\n document.getElementById('response').innerHTML = 'Success: <a href=\"https://ropsten.etherscan.io/tx/' + result + '\"> View Transaction </a>'\n } else {\n document.getElementById('response').innerHTML = '<pre>' + error + '</pre>'\n }\n })\n}",
"async function main(wallet) {\n\n // Account discovery\n const enabled = await wallet.enable({network: 'testnet-v1.0'});\n const from = enabled.accounts[0];\n\n // Querying\n const algodv2 = await wallet.getAlgodv2();\n const suggestedParams = await algodv2.getTransactionParams().do();\n const txns = makeTxns(from, suggestedParams);\n\n // Sign and post txns\n const res = await wallet.signAndPost(txns);\n console.log(res);\n\n}",
"function output_license_html ()\n {\n\t\tvar output = get_comment_code() + '<a rel=\"license\" href=\"' + license_array['url'] + '\"><img alt=\"Creative Commons License\" border=\"0\" src=\"' + license_array['img'] + '\" class=\"cc-button\"/></a><div class=\"cc-info\">' + license_array['text'] + '</div>';\n\n try {\n if ( $F('using_myspace') )\n {\n\t\t output = '<style type=\"text/css\">body { padding-bottom: 50px;} div.cc-bar { width:100%; height: 40px; ' + position() + ' bottom: 0px; left: 0px; background:url(http://mirrors.creativecommons.org/myspace/'+ style() +') repeat-x; } img.cc-button { float: left; border:0; margin: 5px 0 0 15px; } div.cc-info { float: right; padding: 0.3%; width: 400px; margin: auto; vertical-align: middle; font-size: 90%;} </style> <div class=\"cc-bar\">' + output + '</div>';\n } else if ( $F('using_youtube') ) {\n output = license_array['url'];\n }\n\n } catch (err) {}\n\n insert_html( warning_text + output, 'license_example');\n return output;\n\t}",
"function generateEngineerHTML(Engineer){\n return `\n <div class=\"card mb-4\" style=\"width: 18rem;\">\n <div class=\"card-header text-white bg-primary\">\n Engineer </br>\n ${Engineer.getName()}\n </div>\n <ul class=\"list-group list-group-flush\">\n <li class=\"list-group-item\">ID: ${Engineer.getId()}</li>\n <li class=\"list-group-item\">Email: <a href = \"mailto: ${Engineer.getEmail()}\">${Engineer.getEmail()}<a></li>\n <li class=\"list-group-item\">Github: <a href=\"https://github.com/${Engineer.getGithub()}\" target=\"_blank\">${Engineer.getGithub()}</a></li>\n </ul>\n </div>\n ` \n }",
"function createAnimalTradingCardHTML(animal) {\n const cardHTML = `<div class=\"card\">\n <h3 class=\"name\"> ${animal.name} </h3>\n <img src=\" ${animal.name}.jpg\" alt=\" ${animal.name}\" class=\"picture\">\n <div class=\"description\">\n <p class=\"fact\"> ${animal.fact} </p>\n <ul class=\"details\">\n <li><span class=\"bold\">Scientific Name</span>: ${animal.scientificName}</li>\n <li><span class=\"bold\">Average Lifespan</span>: ${animal.lifespan}</li>\n <li><span class=\"bold\">Average Speed</span>: ${animal.speed}</li>\n <li><span class=\"bold\">Diet</span>: ${animal.diet}</li>\n </ul>\n <p class=\"brief\">${animal.summary}</p>\n </div>\n </div>`;\n\n return cardHTML;\n }",
"function generateEngHtml (profiles) {\n //empty array to push each profile into\n const engHtml = [];\n console.log(profiles)\n for (i=0; i< profiles.length; i++) {\n engHtml.push(engineerHtml(profiles[i]));\n \n }\n //joins each item in the array\n return engHtml.join()\n}",
"function generateRoomHTML(roomUsage)\r\n{\t\r\n\tlet address_str = roomUsage.address.split(\",\")[0] + \"; \" +roomUsage.roomNumber;\r\n\r\n\tlet occupancy_pct = roomUsage.seatsUsed/roomUsage.seatsTotal*100;\r\n\tlet occupancy_str = occupancy_pct.toFixed(1).toString();\r\n\r\n\tlet heatingCooling_str = \"\";\r\n\tif(roomUsage.heatingCoolingOn)\r\n\t{\r\n\t\theatingCooling_str = \"On\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\theatingCooling_str = \"Off\";\r\n\t}\r\n\r\n\tlet lights_str = \"\";\r\n\tif(roomUsage.lightsOn)\r\n\t{\r\n\t\tlights_str = \"On\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlights_str = \"Off\";\r\n\t}\r\n\r\n\tlet time_str = \"\";\r\n\ttime_str += (roomUsage.timeChecked.getDate()<10?\"0\"+roomUsage.timeChecked.getDate():roomUsage.timeChecked.getDate()) +\"/\"+\r\n\t\t\t\t((roomUsage.timeChecked.getMonth()+1)<10?\"0\"+(roomUsage.timeChecked.getMonth()+1):(roomUsage.timeChecked.getMonth()+1)) +\"/\"+\r\n\t\t\t\troomUsage.timeChecked.getFullYear()+\", \"+\r\n\t\t\t\t(roomUsage.timeChecked.getHours()<10?\"0\"+roomUsage.timeChecked.getHours():roomUsage.timeChecked.getHours()) +\":\"+\r\n\t\t\t\t(roomUsage.timeChecked.getMinutes()<10?\"0\"+roomUsage.timeChecked.getMinutes():roomUsage.timeChecked.getMinutes()) +\":\"+\r\n\t\t\t\t(roomUsage.timeChecked.getSeconds()<10?\"0\"+roomUsage.timeChecked.getSeconds():roomUsage.timeChecked.getSeconds());\r\n\r\n\r\n\r\n\r\n\tlet html = `<tr><td class=\"mdl-data-table__cell--non-numeric\">\r\n <div><b>`+address_str+`</b></div>\r\n <div>Occupancy: `+occupancy_str+`%</div>\r\n <div>Heating/cooling: `+heatingCooling_str+`</div>\r\n <div>Lights: `+lights_str+`</div>\r\n <div><font color=\"grey\">\r\n <i>`+time_str+`</i>\r\n </font></div>\r\n </td></tr>`;\r\n return html;\r\n}",
"function createAnimalTradingCardHTML(animal) {\n const cardHTML = '<div class=\"card\">' +\n '<h3 class=\"name\">' + animal.name + '</h3>' +\n '<img src=\"' + animal.name + '.jpg\" alt=\"' + animal.name + '\" class=\"picture\">' +\n '<div class=\"description\">' +\n '<p class=\"fact\">' + animal.fact + '</p>' +\n '<ul class=\"details\">' +\n '<li><span class=\"bold\">Scientific Name</span>: ' + animal.scientificName + '</li>' +\n '<li><span class=\"bold\">Average Lifespan</span>: ' + animal.lifespan + '</li>' +\n '<li><span class=\"bold\">Average Speed</span>: ' + animal.speed + '</li>' +\n '<li><span class=\"bold\">Diet</span>: ' + animal.diet + '</li>' +\n '</ul>' +\n '<p class=\"brief\">' + animal.summary + '</p>' +\n '</div>' +\n '</div>';\n\n return cardHTML;\n}",
"function makeHTML() {\n profileData = {\n name: profileName,\n color: themeColor,\n imageURL: userInfo.avatar_url,\n username: userInfo.login,\n location: userInfo.location,\n profileLink: userInfo.html_url,\n blog: userInfo.blog,\n bio: userInfo.bio,\n repos: userInfo.public_repos,\n followers: userInfo.followers,\n stars: numStars,\n following: userInfo.following\n }\n\n // deconstruct profileData object\n const { name, color, imageURL, username, location, profileLink, blog, bio, repos, followers, stars, following } = profileData;\n\n // HTML to write to PDF\n profileHTML = \n `<!DOCTYPE html>\n <html lang=\"en\">\n <head><meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Developer Profile</title>\n\n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\">\n \n <style>\n img { \n height: 200px;\n width: 200px;\n }\n </style>\n </head>\n\n <body>\n <div class=\"jumbotron jumbotron-fluid bg-white pt-5 pb-2\">\n <div class=\"container text-center\">\n <h1 class=\"display-4\">${name}</h1>\n <p class=\"lead\">GitHub username: ${username}</p>\n <img src=\"${imageURL}\" alt=\"GitHub profile image\" class=\"border border-${color} rounded\">\n </div>\n </div>\n\n <div class=\"container text-center\">\n <div class=\"row py-2\">\n <div class=\"col\">\n Location: \n <a href=https://www.google.com/maps/place/${location}>${location}</a>\n </div>\n </div>\n <div class=\"row py-2\">\n <div class=\"col\">\n GitHub profile:\n <a href=${profileLink}>${profileLink}</a>\n </div>\n <div class=\"col\">\n Blog:\n <a href=https://${blog}>https://${blog}</a>\n </div>\n </div>\n </div>\n\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col-12\">\n <div class=\"card my-4\">\n <div class=\"card-body\">\n <h4 class=\"card-title\">Bio:</h4>\n <p class=\"card-text\">${bio}</p>\n </div>\n </div>\n </div>\n </div>\n </div>\n \n <div class=\"container text-center\">\n <div class=\"row\">\n <div class=\"col-6\">\n <div class=\"card text-white bg-${color} mb-3\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">Public repositories:</h5>\n <p class=\"card-text\">${repos}</p>\n </div>\n </div>\n </div>\n <div class=\"col-6\">\n <div class=\"card text-white bg-${color} mb-3\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">GitHub stars:</h5>\n <p class=\"card-text\">${stars}</p>\n </div>\n </div>\n </div>\n </div>\n <div class=\"row\">\n <div class=\"col-6\">\n <div class=\"card text-white bg-${color} mb-3\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">Followers:</h5>\n <p class=\"card-text\">${followers}</p>\n </div>\n </div>\n </div>\n <div class=\"col-6\">\n <div class=\"card text-white bg-${color} mb-3\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">Following:</h5>\n <p class=\"card-text\">${following}</p>\n </div>\n </div>\n </div>\n </div>\n </div>\n \n <script src='index.js'></script>\n </body>\n \n </html>`;\n}",
"function internCard(internObj) {\n var name = internObj.getName();\n var id = internObj.getID();\n var email = internObj.getEmail();\n var school = internObj.getSchool();\n var role = internObj.getRole();\n\n var html = `<div class=\"card\">\n <h4 class=\"card-header\" id=\"name\">`+ name + `</h4>\n <h4 class=\"card-header\" id=\"name\">`+ `<i class=\"fas fa-user-graduate\"></i>` + role + `</h4>\n <div class=\"card-body\">\n <p class=\"card-text\">ID : `+ id + `</p>\n <p class=\"card-text\">Email : <a href=\"mailto:`+email+`\">`+ email +`</a></p>\n <p class=\"card-text\">School : `+ school + `</p>\n </div>\n </div>`;\n return html;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set ``testFile`` to kind. | _$kind() {
this._value.kind = 'testFile';
} | [
"setOutputFileType(fileType) {\n this.outputType = 'audio/' + fileType + '; codecs=opus';\n }",
"function setCurrentFile(file) {\n data.currentFile = file;\n }",
"resetFileThumb() {\n const fileThumb = this.dom.querySelector(\".file-details-thumbnail\");\n fileThumb.src = require(\"../static/images/file-128x128.png\");\n }",
"function testFile(filename, done) {\n async.eachSeries(['ast', 'refract'], testSerialization.bind(this, filename), done);\n}",
"function verifyMimeType(execptedMimeType, test) {\n return function (err, file) {\n test.expect(2);\n if (err) {\n throw err;\n }\n var stream = fs.createReadStream(file);\n magic(stream, function (err, mime, output) {\n if (err) {\n throw err;\n }\n test.equal(mime.type, execptedMimeType);\n var targetFile = path.join(tempfile, path.basename(file));\n var writeStream = fs.createWriteStream(targetFile);\n output.pipe(writeStream);\n writeStream.on(\"finish\", function () {\n var source = fs.readFileSync(file);\n var target = fs.readFileSync(targetFile);\n test.ok(source.equals(target), \"Source and target file contents must match.\");\n test.done();\n });\n });\n }\n}",
"function test_can_cancel_upload() {\n const kFilename = \"testFile1\";\n gServer.setupUser();\n let provider = gServer.getPreparedBackend(\"someNewAccount\");\n let file = getFile(\"./data/\" + kFilename, __file__);\n gServer.planForUploadFile(kFilename, 2000);\n assert_can_cancel_uploads(mc, provider, [file]);\n}",
"set contentType(aValue) {\n this._logService.debug(\"gsDiggThumbnailDTO.contentType[set]\");\n this._contentType = aValue;\n }",
"set files(a) { throw \"readonly property\"; }",
"it(label, f, testTag = null) {\n const tag = this.tag || testTag;\n this.testCases.push({ describeLabel: this.describeLabel, label, f, tag });\n }",
"addFile(fileName, fileType) {\n if (fileType == \"js\" || fileType == \"html\" || fileType == \"css\") {\n this.files.push({ name: fileName, type: fileType });\n } else {\n alert(`${fileName} cannot be added`);\n }\n }",
"set(file) {\n this.cache.set(file.path, file);\n }",
"set fileURL(a) { throw \"readonly property\"; }",
"set resolutionMode(value) {}",
"['@kind']() {\n super['@kind']();\n if (this._value.kind) return;\n\n this._value.kind = 'variable';\n }",
"function addSelectedSpecIFZFile() {\n let path = $(this).val().replace(/\\\\/g, \"/\");\n if (path) $('#clear-ffi').css(\"display\", \"block\");\n else $('#clear-ffi').css(\"display\", \"none\");\n if (!path) return;\n validatePath(path);\n $(this).parent().attr(\"data-ffi-value\", path.substr(path.lastIndexOf(\"/\") + 1))\n }",
"function addFile(file) {\n files.set(file._template, file);\n fileView.appendChild(file.getTemplate());\n}",
"renderFileThumb() {\n if (!this.renderPreview) {\n this.resetFileThumb();\n return;\n }\n const fileThumb = this.dom.querySelector(\".file-details-thumbnail\");\n const fileType = this.dom.querySelector(\".file-details-type\");\n const fileBuffer = new Uint8Array(this.buffer);\n const type = isImage(fileBuffer);\n\n if (type && type !== \"image/tiff\" && fileBuffer.byteLength <= 512000) {\n // Most browsers don't support displaying TIFFs, so ignore them\n // Don't render images over 512,000 bytes\n const blob = new Blob([fileBuffer], {type: type}),\n url = URL.createObjectURL(blob);\n fileThumb.src = url;\n } else {\n this.resetFileThumb();\n }\n fileType.textContent = type ? type : detectFileType(fileBuffer)[0]?.mime ?? \"unknown\";\n }",
"function setMediaType( url ) {\n _mediaType = findMediaType( url );\n return _mediaType;\n }",
"fake(disk) {\n disk = disk || this.getDefaultMappingName();\n if (!this.fakes.has(disk)) {\n this.logger.trace({ disk: disk }, 'drive faking disk');\n this.fakes.set(disk, this.fakeCallback(this, disk, this.getMappingConfig(disk)));\n }\n }",
"function cargarFile(event) {\r\n var file = event.target.files[0];\r\n\r\n if (file.type.match('video.*')) {\r\n var fileURL = URL.createObjectURL(file);\r\n video.src = fileURL;\r\n cargando.classList.remove(\"ocultar\");\r\n } else {\r\n fileSelector.value = \"\";\r\n alert(\"Error: Tipo de fichero incorrecto\");\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implements a EBNF grammar using the Myna parsing library See | function CreateEbnfGrammar(myna) {
// Setup a shorthand for the Myna parsing library object
let m = myna;
let g = new function() {
// comment and whitespace
this.comment = m.seq("/*", m.advanceUntilPast("*/"));
this.ws = m.char(" \t").or(m.seq(m.choice('\n','\r\n'), m.char(" \t"))).or(this.comment).zeroOrMore;
// char class
this.rangChar = m.letter.or(m.digit);
this.charRange = m.seq(this.rangChar, '-', this.rangChar);
this.hashChar = m.seq('#x', m.hexDigit.oneOrMore);
this.hashRange = m.seq('#', this.hashChar, '-', this.hashChar);
this.rangeSeq = m.choice(this.hashRange, this.charRange).oneOrMore;
this.charSeq = m.notChar('-]');
this.includeChar = m.choice(this.rangeSeq, this.charSeq).ast;
this.excludeChar = m.seq('^', m.choice(this.hashRange, this.charRange, this.charSeq)).ast;
this.charClass = m.seq("[", m.choice(this.excludeChar, this.includeChar), "]");
// literal string
this.singleQuoteStr = m.singleQuoted(m.notChar("'").oneOrMore);
this.doubleQuoteStr = m.doubleQuoted(m.notChar('"').oneOrMore);
this.string = m.choice(this.singleQuoteStr, this.doubleQuoteStr).ast;
this.identifier = m.seq(m.letter, m.choice(m.letter, '_', '-', m.digit).oneOrMore).ast;
// patterns
let _this = this;
this.group = m.seq('(', this.ws, m.delay(function() { return _this.pattern; }), ')'); // using a lazy evaluation rule to allow recursive rule definitions
this.term = m.choice(this.identifier, this.group, this.string, this.charClass);
this.repeatOp = m.char('?+*').ast;
this.repeat = m.seq(this.term, this.repeatOp.opt, this.ws);
this.concat = this.repeat.oneOrMore;
this.altOp = m.choice('|','-').ast;
this.alternate = m.seq(this.altOp, this.ws, this.concat); // precedence of exclusion '-' not clear in XML spec, we make it same as '|', to make the tree more flat
this.pattern = m.seq(this.concat, this.alternate.zeroOrMore).ast;
this.defined_as = m.choice("::=", ":=", "=").ast;
this.rule = m.seq(this.identifier, this.ws, this.defined_as, this.ws, this.pattern, m.newLine).ast; // end each rule with newLine, makes the syntax more orthogonal/robust/simpler
this.grammar = m.choice(this.rule, m.seq(this.ws, m.newLine)).oneOrMore.ast;
};
// Register the grammar, providing a name and the default parse rule
return m.registerGrammar("ebnf", g, g.grammar);
} | [
"function CreateGrammar(myna) {\r\n // Setup a shorthand for the Myna parsing library object\r\n let m = myna; \r\n\r\n let g = new function() {\r\n // comment and whitespace \r\n this.comment \t= m.choice(m.seq(\"/*\", m.advanceUntilPast(\"*/\")), m.seq('//', m.advanceUntilPast(\"\\n\")));\r\n this.ws = m.choice(m.char(\" \\t\\r\\n\"), this.comment).zeroOrMore;\r\n\t\t\r\n\t\t// char class\r\n\t\tthis.escape\t\t\t= m.seq('\\\\', m.choice(m.char('\\\\trn\\'\"'), m.seq('u', m.hexDigit, m.hexDigit, m.hexDigit, m.hexDigit)));\r\n\t\tthis.string \t\t= m.singleQuoted(m.choice(this.escape, m.notChar(\"\\\\'\")).oneOrMore).ast;\r\n\t\tthis.charRange\t\t= m.seq('(', this.string, '..', this.string, ')');\r\n\t\tthis.identifier\t\t= m.seq(m.letter, m.choice(m.letter, '_', '-', m.digit).oneOrMore).ast;\r\n\t\t\r\n\t\t// patterns \r\n let _this = this;\r\n this.group \t\t\t= m.seq('(', this.ws, m.delay(function() { return _this.pattern; }), ')'); // using a lazy evaluation rule to allow recursive rule definitions \r\n\t\tthis.term\t\t\t= m.choice(this.identifier, this.group, this.string, this.charRange);\r\n\t\tthis.repeatOp\t\t= m.char('?+*').ast;\r\n\t\tthis.repeat\t\t\t= m.seq(this.term, this.repeatOp.opt, this.ws);\r\n\t\tthis.concat\t\t\t= this.repeat.oneOrMore;\r\n\t\tthis.altOp\t\t\t= '|'; // m.choice('|','-').ast;\r\n\t\tthis.alternate\t\t= m.seq(this.altOp, this.ws, this.concat);\r\n\t\tthis.pattern \t\t= m.seq(this.concat, this.alternate.zeroOrMore).ast;\r\n\t\t\r\n\t\tthis.defined_as = \":\";\r\n\t\tthis.rule \t\t\t= m.seq(this.ws, this.identifier, this.ws, this.defined_as, this.ws, this.pattern, this.ws, ';', this.ws,).ast; // end each rule with newLine, makes the syntax more orthogonal/robust/simpler\r\n\t\tthis.grammar\t\t= this.rule.oneOrMore.ast;\r\n };\r\n\r\n // Register the grammar, providing a name and the default parse rule\r\n return m.registerGrammar(\"antla\", g, g.grammar);\r\n}",
"function CreateJsonGrammar(myna) \n{\n // Setup a shorthand for the Myna parsing library object\n let m = myna; \n\n let g = new function() \n {\n // These are helper rules, they do not create nodes in the parse tree. \n this.escapedChar = m.seq('\\\\', m.char('\\\\/bfnrt\"'));\n this.escapedUnicode = m.seq('\\\\u', m.hexDigit.repeat(4)); \n this.quoteChar = m.choice(this.escapedChar, this.escapedUnicode, m.charExcept('\"'));\n this.fraction = m.seq(\".\", m.digit.zeroOrMore); \n this.plusOrMinus = m.char(\"+-\");\n this.exponent = m.seq(m.char(\"eE\"), this.plusOrMinus.opt, m.digits); \n this.comma = m.text(\",\").ws; \n\n // The following rules create nodes in the abstract syntax tree \n \n // Using a lazy evaluation rule to allow recursive rule definitions \n let _this = this; \n this.value = m.delay(function() { \n return m.choice(_this.string, _this.number, _this.object, _this.array, _this.bool, _this.null); \n }).ast;\n\n this.string = m.doubleQuoted(this.quoteChar.zeroOrMore).ast;\n this.null = m.keyword(\"null\").ast;\n this.bool = m.keywords(\"true\", \"false\").ast;\n this.number = m.seq(this.plusOrMinus.opt, m.integer, this.fraction.opt, this.exponent.opt).ast;\n this.array = m.bracketed(m.delimited(this.value.ws, this.comma)).ast;\n this.pair = m.seq(this.string, m.ws, \":\", m.ws, this.value.ws).ast;\n this.object = m.braced(m.delimited(this.pair.ws, this.comma)).ast;\n };\n\n return m.registerGrammar(\"json\", g);\n}",
"function ExpressionParser() {\n \t\tthis.parse = function() {\n\t \t\treturn Statement(); \n\t \t}\n \t\t\n//\t\tStatement := Assignment | Expr\t\n\t\tthis.Statement=function() {return Statement();}\n\t \tfunction Statement() {\n\t \t\tdebugMsg(\"ExpressionParser : Statement\");\n\t\n \t var ast;\n \t // Expressin or Assignment ??\n \t if (lexer.skipLookAhead().type==\"assignmentOperator\") {\n \t \tast = Assignment(); \n \t } else {\n \t \tast = Expr();\n \t }\n \t return ast;\n\t \t}\n\t \t\n//\t\tAssignment := IdentSequence \"=\" Expr \n//\t\tAST: \"=\": l:target, r:source\n \t\tthis.Assignment = function() {return Assignment();}\n \t\tfunction Assignment() {\n \t\t\tdebugMsg(\"ExpressionParser : Assignment\");\n \t\t\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) return false;\n \t\t\n \t\t\tcheck(\"=\"); // Return if it's not an Assignment\n \t\t\n \t\t\tvar expr=Expr();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"=\",ident,expr);\n\t \t}\n \t\t\n\n//\t\tExpr := And {\"|\" And} \t\n//\t\tAST: \"|\": \"left\":And \"right\":And\n \t\tthis.Expr = function () {return Expr();}\t\n \t\tfunction Expr() {\n \t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\n \t\t\tvar ast=And();\n \t\t\tif (!ast) return false;\n \t\t\t\t\t\n \t\t\n \t\t\twhile (test(\"|\") && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"|\",ast,And());\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n \t\n//\t\tAnd := Comparison {\"&\" Comparison}\n//\t\tAST: \"&\": \"left\":Comparasion \"right\":Comparasion\t\n\t\tfunction And() {\n \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\tvar ast=Comparasion();\n \t\t\tif (!ast) return false;\n \t\t\t\t\n \t\t\twhile (test(\"&\") && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"&\",ast,Comparasion());\n\t \t\t}\n\t \t\treturn ast;\n\t \t}\n\t \t \t\n// \t\tComparison := Sum {(\"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" | \"in\") Sum}\n//\t\tAST: \"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" : \"left\":Sum \"right\":Sum\n\t\tfunction Comparasion() {\n \t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\tvar ast=Sum();\n\t\t\tif (!ast) return false;\n\t\t\n\t\t\twhile ((test(\"==\") ||\n\t\t\t\t\ttest(\"!=\") ||\n\t\t\t\t\ttest(\"<=\") ||\n\t\t\t\t\ttest(\">=\") ||\n\t\t\t\t\ttest(\"<\") ||\n\t\t\t\t\ttest(\">\")) ||\n\t\t\t\t\ttest(\"in\") &&\n\t\t\t\t\t!eof())\n\t\t\t{\n \t\t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\t\tvar symbol=lexer.current.content;\n\t\t\t\tlexer.next();\n\t \t\t\tast=new ASTBinaryNode(symbol,ast,Sum());\n\t\t\t} \t\n\t\t\treturn ast;\t\n\t \t}\n\t \t\n//\t\tSum := [\"+\" | \"-\"] Product {(\"+\" | \"-\") Product}\n//\t\tAST: \"+1\" | \"-1\" : l:Product\n//\t\tAST: \"+\" | \"-\" : l:Product | r:Product \n \t\tfunction Sum() {\n \t\t\tdebugMsg(\"ExpressionParser : Sum\");\n\t\t\n\t\t\tvar ast;\n\t\t\t// Handle Leading Sign\n\t\t\tif (test(\"+\") || test(\"-\")) {\n\t\t\t\tvar sign=lexer.current.content+\"1\";\n\t\t\t\tlexer.next();\n\t\t\t\tast=new ASTUnaryNode(sign,Product());\t\n\t \t\t} else {\n\t \t\t\tast=Product();\n\t \t\t} \n \t\t\t\n \t\t\twhile ((test(\"+\") || test(\"-\")) && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Sum\");\n \t\t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Product());\t\t\n \t\t\t} \t\n \t\t\treturn ast;\n \t\t}\n\n//\t\tProduct := Factor {(\"*\" | \"/\" | \"%\") Factor} \t\n\t \tfunction Product() {\n\t \t\tdebugMsg(\"ExpressionParser : Product\");\n\n \t\t\tvar ast=Factor();\n \t\t\n\t \t\twhile ((test(\"*\") || test(\"/\") || test(\"%\")) && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : Product\");\n\n\t \t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Factor());\n \t\t\t} \n\t \t\treturn ast;\n \t\t}\n \t\t\n// \t Factor := \t\t[(\"this\" | \"super\") \".\"]IdentSequence [\"(\" [Expr {\",\" Expr}] \")\"]\n//\t\t\t\t\t | \"!\" Expr \n//\t\t\t\t\t | \"(\" Expr \")\" \n//\t\t\t\t\t | Array \n//\t\t\t\t\t | Boolean\n//\t\t\t\t\t | Integer\n//\t\t\t\t\t | Number\n//\t\t\t\t\t | Character\n//\t\t\t\t\t | String \n \t\tfunction Factor() {\n \t\t\tdebugMsg(\"ExpressionParser : Factor\"+lexer.current.type);\n\n\t \t\tvar ast;\n \t\t\n\t \t\tswitch (lexer.current.type) {\n\t \t\t\t\n\t \t\t\tcase \"token\"\t:\n\t\t\t\t//\tAST: \"functionCall\": l:Ident(Name) r: [0..x]{Params}\n\t\t\t\t\tswitch (lexer.current.content) {\n\t\t\t\t\t\tcase \"new\": \n\t\t\t\t\t\t\tlexer.next();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar ident=Ident(true);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcheck(\"(\");\n\t\t\t\t\t\t\n \t\t\t\t\t\t\tvar param=[];\n \t\t\t\t\t\t\tif(!test(\")\")){\n \t\t\t\t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\t\t\tparam[i]=Expr();\n \t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t}\t \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\t\t\t\t\tast=new ASTBinaryNode(\"new\",ident,param);\n \t\t\t\t\t\tbreak;\n \t\t\t\t\t\tcase \"this\":\n \t\t\t\t\t\tcase \"super\":\n\t\t\t\t\t\tcase \"constructor\": return IdentSequence();\n \t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n//\t\t\t\tFactor :=\tIdentSequence \t\t\t\t\n \t\t\t\tcase \"ident\":\n \t\t\t\t return IdentSequence();\n \t\t\t\tbreak;\n \t\t\t\t\n// \t\t\tFactor:= \"!\" Expr\t\t\t\n \t\t\t\tcase \"operator\": \n\t \t\t\t\tif (!test(\"!\")) {\n\t \t\t\t\t\terror.expressionExpected();\n\t \t\t\t\t\treturn false;\n \t\t\t\t\t}\n \t\t\t\t\tlexer.next();\n \t\t\t\t\n\t \t\t\t\tvar expr=Expr();\n \t\t\t\t\tast=new ASTUnaryNode(\"!\",expr);\n\t \t\t\tbreak;\n \t\t\t\t\n//\t\t\t\tFactor:= \"(\" Expr \")\" | Array \t\t\t\n \t\t\t\tcase \"brace\"\t:\n \t\t\t\t\tswitch (lexer.current.content) {\n \t\t\t\t\t\t\n// \t\t\t\t\t \"(\" Expr \")\"\n \t\t\t\t\t\tcase \"(\":\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\tast=Expr();\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\tbreak;\n \t\n \t\t\t\t\t\n \t\t\t\t\t\tdefault:\n \t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t \treturn false;\n\t \t\t\t\t\tbreak;\n\t \t\t\t\t}\n\t \t\t\tbreak;\n \t\t\t\n//\t\t\t\tFactor:= Boolean | Integer | Number | Character | String\n//\t\t\t\tAST: \"literal\": l: \"bool\" | \"int\" | \"float\" | \"string\" | \"char\": content: Value \n\t \t\t\tcase \"_$boolean\" \t\t:\t\t\t\n\t \t\t\tcase \"_$integer\" \t\t:\n\t \t\t\tcase \"_$number\" \t\t:\n\t \t\t\tcase \"_$string\"\t\t\t:\t\t\n\t\t\t\tcase \"_$character\"\t\t:\n\t\t\t\tcase \"null\"\t\t\t\t:\n\t\t\t\t\t\t\t\t\t\t\tast=new ASTUnaryNode(\"literal\",lexer.current);\n \t\t\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\tbreak;\n\t\t\t\t\n//\t\t\t\tNot A Factor \t\t\t\t \t\t\t\t\n \t\t\t\tdefault: \terror.expressionExpected();\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\treturn false;\n\t \t\t\t\t\t\tbreak;\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n\n \n//\t\tIdentSequence := (\"this\" | \"super\") | [(\"this\" | \"super\") \".\"] (\"constructor\" \"(\" [Expr {\",\" Expr}] \")\" | Ident {{ArrayIndex} | \".\" Ident } [\"(\" [Expr {\",\" Expr}] \")\"]);\n//\t\tAST: \"identSequence\": l: [0..x][\"_$this\"|\"_$super\"](\"constructor\" | Ident{Ident | ArrayIndex})\n// \t\tor AST: \"functionCall\": l:AST IdentSequence(Name), r: [0..x]{Params}\n\t\tthis.IdentSequence=function () {return IdentSequence();};\n \t\tfunction IdentSequence() {\n \t\t\tdebugMsg(\"ExpressionParser:IdentSequence()\");\n \t\t\t\n \t\t\tvar ast=new ASTListNode(\"identSequence\");\n \t\t\tif (test(\"this\") || test(\"super\")) {\n \t\t\t\tast.add({\"type\":\"ident\",\"content\":\"_$\"+lexer.current.content,\"line\":lexer.current.line,\"column\":lexer.current.column});\n \t\t\t\tlexer.next();\n \t\t\t\tif (!(test(\".\"))) return ast;\n \t\t\t\tlexer.next();\n \t\t\t}\n\n\t\t\tvar functionCall=false;\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tast.add({\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column});\n\t\t\t\tlexer.next();\n\t\t\t\tcheck(\"(\");\n\t\t\t\tfunctionCall=true;\n\t\t\t} else {\n \t\t\t\tvar ident=Ident(true);\n \t\t\t\n \t\t\t\tast.add(ident);\n \t\t\t\n \t\t\t\tvar index;\n \t\t\t\twhile((test(\".\") || test(\"[\")) && !eof()) {\n \t\t\t\t\t if (test(\".\")) {\n \t\t\t\t\t \tlexer.next();\n \t\t\t\t\t\tast.add(Ident(true));\n \t\t\t\t\t} else ast.add(ArrayIndex());\n \t\t\t\t}\n \t\t\t\tif (test(\"(\")) {\n \t\t\t\t\tfunctionCall=true;\n \t\t\t\t\tlexer.next();\n \t\t\t\t}\n \t\t\t}\n \t\n \t\t\tif (functionCall) {\t\n\t\t\t\tvar param=[];\n\t\t\t\tif(!test(\")\")){\n \t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\tparam[i]=Expr();\t\t\t\t\t\t\t\n \t\t\t\t\t}\n \t\t\t\t}\t \t\t\t\t\t\t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\tast=new ASTBinaryNode(\"functionCall\",ast,param);\n \t\t\t} \n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tArrayIndex:=\"[\" Expr \"]\"\n //\t\tAST: \"arrayIndex\": l: Expr\n \t\tfunction ArrayIndex(){\n \t\t\tdebugMsg(\"ExpressionParser : ArrayIndex\");\n \t\t\tcheck(\"[\");\n \t\t\t \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\"]\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"arrayIndex\",expr);\n \t\t}\n\n//\t\tIdent := Letter {Letter | Digit | \"_\"}\n//\t\tAST: \"ident\", \"content\":Ident\n\t \tthis.Ident=function(forced) {return Ident(forced);}\n \t\tfunction Ident(forced) {\n \t\t\tdebugMsg(\"ExpressionParser:Ident(\"+forced+\")\");\n \t\t\tif (testType(\"ident\")) {\n \t\t\t\tvar ast=lexer.current;\n \t\t\t\tlexer.next();\n \t\t\t\treturn ast;\n \t\t\t} else {\n \t\t\t\tif (!forced) return false; \n \t\t\t\telse { \n \t\t\t\t\terror.identifierExpected();\n\t\t\t\t\treturn SystemIdentifier();\n\t\t\t\t}\n\t\t\t} \t\n \t\t}\n \t}",
"function ProgramParser() {\n \t\t\n \t\t this.parse = function(kind) {\n \t\t \tswitch (kind) { \t\n \t\t \t\tcase \"declaration\": return Declaration();\n \t\t \t\tbreak;\n\t \t\t\tdefault: return Program();\n\t \t\t}\n\t \t}\n \t\t\n \t\t// Import Methods from the expression Parser\n \t\tfunction Assignment() {return expressionParser.Assignment();}\n \t\tfunction Expr() {return expressionParser.Expr();}\n \t\tfunction IdentSequence() {return expressionParser.IdentSequence();}\n \t\tfunction Ident(forced) {return expressionParser.Ident(forced);}\t\t\n \t\tfunction EPStatement() {return expressionParser.Statement();}\n\n\n\t\tfunction whatNext() {\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"class\"\t\t: \n \t\t\t\tcase \"function\"\t \t: \n \t\t\t\tcase \"structure\"\t:\n \t\t\t\tcase \"constant\" \t:\n \t\t\t\tcase \"variable\" \t:\n \t\t\t\tcase \"array\"\t\t: \treturn lexer.current.content;\t\n \t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\tdefault\t\t\t\t:\treturn lexer.lookAhead().content;\n \t\t\t}\n\t\t}\n\n// \t\tDeclaration\t:= {Class | Function | VarDecl | Statement} \n\t\tfunction Declaration() {\n\t\t\tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"class\"\t: return Class();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\" : return Function();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"structure\" : return StructDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"array\"\t: return ArrayDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"constant\" :\n \t\t\t\t\tcase \"variable\" : return VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: return false;\n \t\t\t }\n\t\t}\n\n// \t\tProgram\t:= {Class | Function | VarDecl | Structure | Array | Statement} \n//\t\tAST: \"program\": l: {\"function\" | \"variable\" ... | Statement} indexed from 0...x\n\t\tthis.Program=function() {return Program()};\n \t\tfunction Program() {\n \t\t\tdebugMsg(\"ProgramParser : Program\");\n \t\t\tvar current;\n \t\t\tvar ast=new ASTListNode(\"program\");\n \t\t\t\n \t\t\tfor (;!eof();) {\n \t\t\t\t\n \t\t\t\tif (!(current=Declaration())) current=Statement();\n \t\t\t\t\n \t\t\t\tif (!current) break;\n \t\t\t\t\n \t\t\t\tast.add(current);\t\n \t\t\t} \t\t\t\n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tClass:= \"class\" Ident [\"extends\" Ident] \"{\" [\"constructor\" \"(\" Ident Ident \")\"] CodeBlock {VarDecl | Function}\"}\"\n//\t\tAST: \"class\" : l: name:Identifier,extends: ( undefined | Identifier),fields:VarDecl[0..i], methods:Function[0...i]\n\t\tfunction Class() {\n\t\t\tdebugMsg(\"ProgramParser : Class\");\n\t\t\tlexer.next();\n\n\t\t\tvar name=Ident(true);\t\t\t\n\t\t\t\n\t\t\tvar extend={\"content\":undefined};\n\t\t\tif(test(\"extends\")) {\n\t\t\t\tlexer.next();\n\t\t\t\textend=Ident(true);\n\t\t\t}\n\t\t\t\n\t\t\tcheck (\"{\");\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\t\n\t\t\tvar methods=[];\n\t\t\tvar fields=[];\n\t\t\t\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tlexer.next();\n\t\t \t\t//var retType={\"type\":\"ident\",\"content\":\"_$any\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tvar constructName={\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tmethods.push(FunctionBody(name,constructName));\n\t\t\t}\n\t\t\t\n\t\t\tvar current=true;\n\t\t\twhile(!test(\"}\") && current && !eof()) {\n\t\t\t\t \t\n\t\t \tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\"\t: methods.push(Function()); \n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\" : fields.push(VarDecl(true));\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: current=false;\n \t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tcheck(\"}\");\n\t\t\t\n\t\t\tmode.terminatorOff();\n\n\t\t\tsymbolTable.closeScope();\n\t\t\tsymbolTable.addClass(name.content,extend.content,scope);\n\t\t\t\n\t\t\treturn new ASTUnaryNode(\"class\",{\"name\":name,\"extends\":extend,\"scope\":scope,\"methods\":methods,\"fields\":fields});\n\t\t}\n\t\t\n //\t\tStructDecl := \"structure\" Ident \"{\" VarDecl {VarDecl} \"}\"\n //\t\tAST: \"structure\" : l: \"name\":Ident, \"decl\":[VarDecl], \"scope\":symbolTable\n \t\tfunction StructDecl() {\n \t\t\tdebugMsg(\"ProgramParser : StructDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true); \n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\tmode.terminatorOn();\n \t\t\t\n \t\t\tvar decl=[];\n \t\t\t\n \t\t\tvar scope=symbolTable.openScope();\t\n \t\t\tdo {\t\t\t\t\n \t\t\t\tdecl.push(VarDecl(true));\n \t\t\t} while(!test(\"}\") && !eof());\n \t\t\t\n \t\t\tmode.terminatorOff();\n \t\t\tcheck (\"}\");\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\tsymbolTable.addStruct(name.content,scope);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"structure\",{\"name\":name,\"decl\":decl,\"scope\":scope});\n \t\t} \n \t\t\n //\tarrayDecl := \"array\" Ident \"[\"Ident\"]\" \"contains\" Ident\n //\t\tAST: \"array\" : l: \"name\":Ident, \"elemType\":Ident, \"indexTypes\":[Ident]\n \t\tfunction ArrayDecl() {\n \t\t\tdebugMsg(\"ProgramParser : ArrayDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\tcheck(\"[\");\n \t\t\t\t\n \t\t\tvar ident=Ident(!mode.any);\n \t\t\tif (!ident) ident=lexer.anyLiteral();\n \t\t\t\t\n \t\t\tvar indexType=ident;\n \t\t\t\t\n \t\t\tvar bound=ident.content;\n \t\t\t\t\n \t\t\tcheck(\"]\");\n \t\t\t\t\n \t\t\tvar elemType; \t\n \t\t\tif (mode.any) {\n \t\t\t\tif (test(\"contains\")) {\n \t\t\t\t\tlexer.next();\n \t\t\t\t\telemType=Ident(true);\n \t\t\t\t}\n \t\t\t\telse elemType=lexer.anyLiteral();\n \t\t\t} else {\n \t\t\t\tcheck(\"contains\");\n \t\t\t\telemType=Ident(true);\n \t\t\t}\n \t\t\t\n \t\t\tcheck (\";\");\n \t\t\tsymbolTable.addArray(name.content,elemType.content,bound);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"array\",{\"name\":name,\"elemType\":elemType,\"indexType\":indexType});\n \t\t} \n \t\t\n//\t\tFunction := Ident \"function\" Ident \"(\" [Ident Ident {\"[\"\"]\"} {\",\" Ident Ident {\"[\"\"]\"}) } \")\" CodeBlock\n//\t\tAST: \"function\":\tl: returnType: (Ident | \"_$\"), name:name, scope:SymbolTable, param:{name:Ident,type:Ident}0..x, code:CodeBlock \n\t\tthis.Function=function() {return Function();}\n \t\tfunction Function() {\n \t\t\tdebugMsg(\"ProgramParser : Function\");\n \t\t\n \t\t\tvar retType;\n \t\t\tif (mode.decl) retType=Ident(!(mode.any));\n \t\t\tif (!retType) retType=lexer.anyLiteral();\n \t\t\t\n \t\t\tcheck(\"function\");\n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\treturn FunctionBody(retType,name);\n \t\t}\n \t\t\n \n \t\t// The Body of a function, so it is consistent with constructor\n \t\tfunction FunctionBody(retType,name)\t{\n \t\t\tvar scope=symbolTable.openScope();\n \t\t\t\n \t\t\tif (!test(\"(\")) error.expected(\"(\");\n \t\t\n var paramList=[];\n var paramType=[];\n var paramExpected=false; //Indicates wether a parameter is expected (false in the first loop, then true)\n do {\n \t\t\tlexer.next();\n \t\t\t\n \t\t\t/* Parameter */\n \t\t\tvar pName,type;\n \t\t\tvar ident=Ident(paramExpected);\t// Get an Identifier\n \t\t\tparamExpected= true;\n \t\t\t\n \t\t\t// An Identifier is found\n \t\t\tif (ident) {\n \t\t\t\t\n \t\t\t\t// When declaration is possible\n \t\t\t\tif (mode.decl) {\n \t\t\t\t\t\n \t\t\t\t\t// One Identifier found ==> No Type specified ==> indent specifies Param Name\n \t\t\t\t\tif (!(pName=Ident(!(mode.any)))) {\n \t\t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\t\tpName=ident;\n \t\t\t\t\t} else type=ident; // 2 Identifier found\n \t\t\t\t} else {\t// Declaration not possible\n \t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\tpName=ident;\n \t\t\t\t}\t\n\n\t\t\t\t\t// Store Parameter\n\t\t\t\t\tparamType.push(type); \n \t\tparamList.push({\"name\":pName,\"type\":type});\n \t\t \n \t\t \tsymbolTable.addVar(pName.content,type.content);\n \t\t} \n \t\t} while (test(\",\") && !eof());\n\n \tcheck(\")\");\n \t\t\t \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\t\n \t\t\tsymbolTable.addFunction(name.content,retType.content,paramType);\n \t\t\treturn new ASTUnaryNode(\"function\",{\"name\":name,\"scope\":scope,\"param\":paramList,\"returnType\":retType,\"code\":code});\n \t\t}\n \t\t\t\n\t\t\n //\t\tVarDecl := Ident (\"variable\" | \"constant\") Ident [\"=\" Expr] \";\" \n //\t\tAST: \"variable\"|\"constant\": l : type:type, name:name, expr:[expr]\n \t\tthis.VarDecl = function() {return VarDecl();}\n \t\tfunction VarDecl(noInit) {\n \t\t\tdebugMsg(\"ProgramParser : VariableDeclaration\");\n \t\t\tvar line=lexer.current.line;\n \t\t\tvar type=Ident(!mode.any);\n \t\t\tif (!type) type=lexer.anyLiteral();\n \t\t\t\n \t\t\tvar constant=false;\n \t\t\tvar nodeName=\"variable\";\n \t\t\tif (test(\"constant\")) {\n \t\t\t\tconstant=true; \n \t\t\t\tnodeName=\"constant\";\n \t\t\t\tlexer.next();\n \t\t\t}\n \t\t\telse check(\"variable\"); \n \t\t\t \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\tsymbolTable.addVar(name.content,type.content,constant);\n\n\t\t\tvar expr=null;\n\t\t\tif(noInit==undefined){\n\t\t\t\tif (test(\"=\")) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\texpr=Expr();\n\t\t\t\t\tif (!expr) expr=null;\n\t\t\t\t}\n\t\t\t} \n\t\n\t\t\tcheck(\";\");\n\t\t\tvar ast=new ASTUnaryNode(nodeName,{\"type\":type,\"name\":name,\"expr\":expr});\n\t\t\tast.line=line;\n\t\t\treturn ast;\n \t\t}\n \t\t\t\t\n//\t\tCodeBlock := \"{\" {VarDecl | Statement} \"}\" \n//\t\tCodeblock can take a newSymbolTable as argument, this is needed for functions that they can create an scope\n//\t\tcontaining the parameters.\n//\t\tIf newSymbolTable is not specified it will be generated automatical\n// At the End of Codeblock the scope newSymbolTable will be closed again\t\t\n//\t\tAST: \"codeBlock\" : l: \"scope\":symbolTable,\"code\": code:[0..x] {code}\n \t\tfunction CodeBlock() {\n \t\t\tdebugMsg(\"ProgramParser : CodeBlock\");\n\t\t\t\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\tvar begin=lexer.current.line;\n\t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar code=[];\n \t\t\tvar current;\n\n \t\t\twhile(!test(\"}\") && !eof()) {\n \t\t\t\tswitch (whatNext()) {\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\": current=VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault: current=Statement();\t\t\t\t\t\n \t\t\t\t}\n\n \t\t\t\tif(current) {\n \t\t\t\t\tcode.push(current);\n \t\t\t\t} else {\n \t\t\t\t\terror.expected(\"VarDecl or Statement\"); break;\n \t\t\t\t}\n \t\t\t}\t\n \t\t\t\n \t\t\tvar end=lexer.current.line;\n \t\t\tcheck(\"}\");\n \t\t\tsymbolTable.closeScope();\n \t\t\treturn new ASTUnaryNode(\"codeBlock\",{\"scope\":scope,\"code\":code,\"begin\":begin,\"end\":end});\n \t\t}\n \t\t\n//\t\tStatement\t:= If | For | Do | While | Switch | JavaScript | (Return | Expr | Assignment) \";\"\n \t\tfunction Statement() {\n \t\t\tdebugMsg(\"ProgramParser : Statement\");\n \t\t\tvar ast;\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"if\"\t \t\t: ast=If(); \n\t \t\t\tbreak;\n \t\t\t\tcase \"do\"\t \t\t: ast=Do(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"while\" \t\t: ast=While(); \t\t\n \t\t\t\tbreak;\n \t\t\t\tcase \"for\"\t\t\t: ast=For();\n \t\t\t\tbreak;\n \t\t\t\tcase \"switch\"\t\t: ast=Switch(); \t\n \t\t\t\tbreak;\n \t\t\t\tcase \"javascript\"\t: ast=JavaScript(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"return\"\t\t: ast=Return(); \n \t\t\t\t\t\t\t\t\t\t check(\";\");\n \t\t\t\tbreak;\n \t\t\t\tdefault\t\t\t\t: ast=EPStatement(); \n \t\t\t\t\t check(\";\");\n \t\t\t}\n \t\t\tast.line=line;\n \t\t\tast.comment=lexer.getComment();\n \t\t\tlexer.clearComment(); \t\t\t\n \t\t\treturn ast;\t\n \t\t}\n \t\t\n//\t\tIf := \"if\" \"(\" Expr \")\" CodeBlock [\"else\" CodeBlock]\n//\t\tAST : \"if\": l: cond:Expr, code:codeBlock, elseBlock:(null | codeBlock)\n \t\tfunction If() {\n \t\t\tdebugMsg(\"ProgramParser : If\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tvar elseCode;\n \t\t\tif (test(\"else\")) {\n \t\t\t\tlexer.next();\n \t\t\t\telseCode=CodeBlock();\n \t\t\t}\n \t\t\treturn new ASTUnaryNode(\"if\",{\"cond\":expr,\"code\":code,\"elseBlock\":elseCode});\n \t\t}\n \t\t\n// \t\tDo := \"do\" CodeBlock \"while\" \"(\" Expr \")\" \n//\t\tAST: \"do\": l:Expr, r:CodeBlock \n \t\tfunction Do() {\t\n \t\t\tdebugMsg(\"ProgramParser : Do\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tcheck(\"while\");\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\t\n \t\t\tcheck(\";\");\n\n \t\t\treturn new ASTBinaryNode(\"do\",expr,code);\n \t\t}\n \t\t\n// \t\tWhile := \"while\" \"(\" Expr \")\" \"{\" {Statement} \"}\" \n//\t\tAST: \"while\": l:Expr, r:codeBlock\n \t\tfunction While(){ \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : While\");\n \t\t\t\n \t\t\t//if do is allowed, but while isn't allowed gotta check keyword in parser\n \t\t\tif (preventWhile) error.reservedWord(\"while\",lexer.current.line);\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code = CodeBlock();\n \t\t\t\t \t\t\t\n \t\t\treturn new ASTBinaryNode(\"while\",expr,code);\n \t\t}\n \t\t\n//\t\tFor := \"for\" \"(\"(\"each\" Ident \"in\" Ident | Ident Assignment \";\" Expr \";\" Assignment )\")\"CodeBlock\n//\t\tAST: \"foreach\": l: elem:Ident, array:Ident, code:CodeBlock \n//\t\tAST: \"for\": l: init:Assignment, cond:Expr,inc:Assignment, code:CodeBlock\n \t\tfunction For() { \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : For\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tif (test(\"each\")) {\n \t\t\t\tlexer.next();\n \t\t\t\tvar elem=IdentSequence();\n \t\t\t\tcheck(\"in\");\n \t\t\t\tvar arr=IdentSequence();\n \t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\t\n \t\t\t\tvar code=CodeBlock();\n \t\t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"foreach\",{\"elem\":elem,\"array\":arr,\"code\":code});\n \t\t\t\t\n \t\t\t} else {\n \t\t\t\tvar init=Assignment();\n \t\t\t\tif (!init) error.assignmentExpected();\n \t\t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\t\n \t\t\t\tvar cond=Expr();\n \t\t\t\n \t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\n \t\t\t\tvar increment=Assignment();\n \t\t\t\tif (!increment) error.assignmentExpected();\n \t\t\t \n \t\t\t\tcheck(\")\");\n \t\t\t\tvar code=CodeBlock();\t\n \t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"for\",{\"init\":init,\"cond\":cond,\"inc\":increment,\"code\":code});\n \t\t\t}\t\n \t\t}\n \t\t\n//\t\tSwitch := \"switch\" \"(\" Ident \")\" \"{\" {Option} [\"default\" \":\" CodeBlock] \"}\"\t\n// AST: \"switch\" : l \"ident\":IdentSequence,option:[0..x]{Option}, default:CodeBlock\n \t\tfunction Switch() {\t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Switch\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) error.identifierExpected();\n \t\t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar option=[];\n \t\t\tvar current=true;\n \t\t\tfor (var i=0;current && !eof();i++) {\n \t\t\t\tcurrent=Option();\n \t\t\t\tif (current) {\n \t\t\t\t\toption[i]=current;\n \t\t\t\t}\n \t\t\t}\n \t\t\tcheck(\"default\");\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar defBlock=CodeBlock();\n \t\t \t\t\t\n \t\t\tcheck(\"}\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"switch\", {\"ident\":ident,\"option\":option,\"defBlock\":defBlock});\n \t\t}\n \t\t\n//\t\tOption := \"case\" Expr {\",\" Expr} \":\" CodeBlock\n// AST: \"case\" : l: [0..x]{Expr}, r:CodeBlock\n \t\tfunction Option() {\n \t\t\tif (!test(\"case\")) return false;\n \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Option\");\n \t\t\t\n \t\t\tvar exprList=[];\n \t\t\tvar i=0;\n \t\t\tdo {\n \t\t\t\tlexer.next();\n \t\t\t\t\n \t\t\t\texprList[i]=Expr();\n \t\t\t\ti++; \n \t\t\t\t\n \t\t\t} while (test(\",\") && !eof());\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"case\",exprList,code);\n \t\t}\n \t\t\n// JavaScript := \"javascript\" {Letter | Digit | Symbol} \"javascript\"\n//\t\tAST: \"javascript\": l: String(JavascriptCode)\n \t\tfunction JavaScript() {\n \t\t\tdebugMsg(\"ProgramParser : JavaScript\");\n\t\t\tcheck(\"javascript\");\n\t\t\tcheck(\"(\")\n\t\t\tvar param=[];\n\t\t\tvar p=Ident(false);\n\t\t\tif (p) {\n\t\t\t\tparam.push(p)\n\t\t\t\twhile (test(\",\") && !eof()) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\tparam.push(Ident(true));\n\t\t\t\t}\t\n\t\t\t}\n \t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\tvar js=lexer.current.content;\n \t\t\tcheckType(\"javascript\");\n \t\t\t\t\t\t\n \t\t\treturn new ASTUnaryNode(\"javascript\",{\"param\":param,\"js\":js});\n \t\t}\n \t\t\n// \t\tReturn := \"return\" [Expr] \n//\t\tAST: \"return\" : [\"expr\": Expr] \n \t\tfunction Return() {\n \t\t\tdebugMsg(\"ProgramParser : Return\");\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tvar ast=new ASTUnaryNode(\"return\",expr);\n \t\t\tast.line=line;\n \t\t\treturn ast;\n \t\t}\n\t}",
"function parseExpression() {\n let expr;\n //lookahead = lex();\n // if (!lookahead) { //significa que es white o undefined\n // lookahead = lex();\n // }\n if (lookahead.type == \"REGEXP\") {\n expr = new Regexp({type: \"regex\", regex: lookahead.value, flags: null});\n lookahead = lex();\n return expr;\n } else if (lookahead.type == \"STRING\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"NUMBER\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"WORD\") {\n const lookAheadValue = lookahead;\n lookahead = lex();\n if (lookahead.type == 'COMMA' && lookahead.value == ':') {\n expr = new Value({type: \"value\", value: '\"' + lookAheadValue.value + '\"'});\n return expr;\n }\n if (lookahead.type == 'DOT') {\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n }\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n } else if (lookahead.type == \"ERROR\") {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${lookahead.value}`);\n } else {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${program.slice(offset, offset + 10)}`);\n }\n}",
"function ShapeGrammar(axiom, scene, iterations, \n\t\t\t\t\t\torigin, noise, g1, g2) {\n\tgeo1 = g1;\n\tgeo2 = g2;\n\tthis.axiom = axiom;\n\tthis.grammar = [];\n\tthis.iterations = iterations;\n\tthis.scene = scene;\n\tthis.height = 2.0 * noise;\n\tthis.material;\n\t\n\t// cosine palate input values\n\tvar a = new THREE.Vector3(-3.142, -0.162, 0.688);\n\tvar b = new THREE.Vector3(1.068, 0.500, 0.500);\n\tvar c = new THREE.Vector3(3.138, 0.688, 0.500);\n\tvar d = new THREE.Vector3(0.000, 0.667, 0.500);\n\tvar t = this.height - Math.floor(this.height);\n\n\t// set material color to the pallete result\n\tvar result = palleteColor(a, b, c, t, d);\n\tthis.material = new THREE.MeshLambertMaterial({ color: result });\n\tthis.material.color.setRGB(result.r, result.g, result.b);\n\tthis.material.color.addScalar(0.95);\n\t\n\t// Init grammar for shapes\n\tfor (var i = 0; i < this.axiom.length; i++) {\n\t\tvar node = new SymbolNode(axiom.charAt(i), new THREE.BoxGeometry(1, 1, 1));\n\t\tnode.scale = new THREE.Vector3(1, this.height, 1);\n\t\tnode.position = new THREE.Vector3(origin.x, -0.02, origin.y);\n\t\tnode.material = this.material;\n\n\t\t// add the node to the grammar\n\t\tthis.grammar[i] = node;\n\t} \n\n\t// Function to compute shape grammar for a number of iterations\n\t// Swaps out characters for their grammar rule value\n\tthis.compute = function() {\n\t\t// Repeats for number of iterations\n\t\tfor (var k = 0; k < this.iterations; k++) {\n\t\t\t\n\t\t\t/*\n\t\t\t * Adds children instances to a resulting array \n\t\t\t * and replaces grammar with new list\n\t\t\t */\n\t\t\tvar newArr = [];\n\t\t\tfor (var i = 0; i < this.grammar.length; i++) {\n\t\t\t\tvar symbolNode = this.grammar[i];\n\t\t\t\t// Subdivide rule\n\t\t\t\tif (symbolNode.symbol == 'A') {\n\t\t\t\t\tthis.grammar.splice(i, 1);\n\t\t\t\t\tvar newSymbols = subdivideX(symbolNode);\n\t\t\t\t\t\n\t\t\t\t\t// Add new symbols to the grammar\n\t\t\t\t\tfor (var j = 0; j < newSymbols.length; j++) {\n\t\t\t\t\t\tnewArr.push(newSymbols[j]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Self rule\n\t\t\t\telse if (symbolNode.symbol == 'B') {\n\t\t\t\t\tthis.grammar.splice(i, 1);\n\t\t\t\t\tvar newSymbols = noTrans(symbolNode);\n\t\t\t\t\t\n\t\t\t\t\t// Add new symbols to the grammar\n\t\t\t\t\tfor (var j = 0; j < newSymbols.length; j++) {\n\t\t\t\t\t\tnewArr.push(newSymbols[j]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (symbolNode.symbol == 'C') {\n\t\t\t\t\tthis.grammar.splice(i, 1);\n\t\t\t\t\tvar newSymbols = stack(symbolNode);\n\t\t\t\t\t\n\t\t\t\t\t// Add new symbols to the grammar\n\t\t\t\t\tfor (var j = 0; j < newSymbols.length; j++) {\n\t\t\t\t\t\tnewArr.push(newSymbols[j]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (symbolNode.symbol == 'D') {\n\t\t\t\t\tthis.grammar.splice(i, 1);\n\t\t\t\t\tvar newSymbols = buildBaseOrBridge(symbolNode);\n\t\t\t\t\t\n\t\t\t\t\t// Add new symbols to the grammar\n\t\t\t\t\tfor (var j = 0; j < newSymbols.length; j++) {\n\t\t\t\t\t\tnewArr.push(newSymbols[j]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (var j = 0; j < newArr.length; j++) {\n\t\t\t\tthis.grammar.push(newArr[j]);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Function to render resulting shape grammar\n\t// Uses node data from shape grammar to create a mesh\n\tthis.render = function() {\n\t\tthis.compute();\n\n\t\tfor (var i = 0; i < this.grammar.length; i++) {\n\t\t\tvar node = this.grammar[i];\n\n\t\t\t// create mesh for building\n\t\t\tvar mesh = new THREE.Mesh(node.geometry, this.material);\n\t\t\t\n\t\t\t// set color of buildings to be the color stored in this instance\n\t\t\tvar mat = new THREE.LineBasicMaterial( { color: 0xffffff, linewidth: 2 } );\n\t\t\tmat.color = this.material.color.clone();\n\t\t\t\n\n\t\t\t// create geometry for wireframe\n\t\t\tvar geo = new THREE.EdgesGeometry( node.geometry );\n\n\t\t\t// add mesh outlines\n\t\t\tvar wireframe = new THREE.LineSegments( geo, mat );\n\t\t\tmesh.add(wireframe);\n\t\t\t\n\t\t\t// set position\n\t\t\tvar p = node.position.clone();\n\t\t\tvar r = node.rotation.clone();\n\n\t\t\t// set rotation\n\t\t\tmesh.position.set(p.x, p.y, p.z);\n\t\t\tmesh.rotation.set(r.x, r.y, r.z);\n\n\t\t\t// set scale\n\t\t\tvar m = new THREE.Vector3().multiplyVectors(node.geomScale, node.scale);\n\t\t\tmesh.scale.set(m.x, m.y, m.z);\n\n\t\t\tmesh.updateMatrix();\n\t\t\tthis.scene.add(mesh);\n\t\t}\n\t}\n}",
"parseTerm() {\n const startPos = this.tok.pos;\n // Parse groups and elements\n let items = [];\n let electron = false;\n let next;\n while (true) {\n next = this.tok.peek();\n if (next == \"(\")\n items.push(this.parseGroup());\n else if (next == \"e\") {\n this.tok.consume(next);\n electron = true;\n }\n else if (next !== null && /^[A-Z][a-z]*$/.test(next))\n items.push(this.parseElement());\n else if (next !== null && /^[0-9]+$/.test(next))\n throw new ParseError(\"Invalid term - number not expected\", this.tok.pos);\n else\n break;\n }\n // Parse optional charge\n let charge = null;\n if (next == \"^\") {\n this.tok.consume(next);\n next = this.tok.peek();\n if (next === null)\n throw new ParseError(\"Number or sign expected\", this.tok.pos);\n else {\n charge = this.parseOptionalNumber();\n next = this.tok.peek();\n }\n if (next == \"+\")\n charge = +charge; // No-op\n else if (next == \"-\")\n charge = -charge;\n else\n throw new ParseError(\"Sign expected\", this.tok.pos);\n this.tok.take(); // Consume the sign\n }\n // Check and postprocess term\n if (electron) {\n if (items.length > 0)\n throw new ParseError(\"Invalid term - electron needs to stand alone\", startPos, this.tok.pos);\n if (charge === null) // Allow omitting the charge\n charge = -1;\n if (charge != -1)\n throw new ParseError(\"Invalid term - invalid charge for electron\", startPos, this.tok.pos);\n }\n else {\n if (items.length == 0)\n throw new ParseError(\"Invalid term - empty\", startPos, this.tok.pos);\n if (charge === null)\n charge = 0;\n }\n return new Term(items, charge);\n }",
"function InlineParser() {\n this.preEmphasis = \" \\t\\\\('\\\"\";\n this.postEmphasis = \"- \\t.,:!?;'\\\"\\\\)\";\n this.borderForbidden = \" \\t\\r\\n,\\\"'\";\n this.bodyRegexp = \"[\\\\s\\\\S]*?\";\n this.markers = \"*/_=~+\";\n\n this.emphasisPattern = this.buildEmphasisPattern();\n this.linkPattern = /\\[\\[([^\\]]*)\\](?:\\[([^\\]]*)\\])?\\]/g; // \\1 => link, \\2 => text\n\n // this.clockLinePattern =/^\\s*CLOCK:\\s*\\[[-0-9]+\\s+.*\\d:\\d\\d\\]/;\n // NOTE: this is a weak pattern. does not enforce lookahead of opening bracket type!\n this.timestampPattern =/([\\[<])(\\d{4}-\\d{2}-\\d{2})(?:\\s*([A-Za-z]+)\\s*)(\\d{2}:\\d{2})?([\\]>])/g;\n this.macroPattern = /{{{([A-Za-z]\\w*)\\(([^})]*?)\\)}}}/g;\n }",
"parseEquation() {\n let lhs = [this.parseTerm()];\n while (true) {\n const next = this.tok.peek();\n if (next == \"+\") {\n this.tok.consume(next);\n lhs.push(this.parseTerm());\n }\n else if (next == \"=\") {\n this.tok.consume(next);\n break;\n }\n else\n throw new ParseError(\"Plus or equal sign expected\", this.tok.pos);\n }\n let rhs = [this.parseTerm()];\n while (true) {\n const next = this.tok.peek();\n if (next === null)\n break;\n else if (next == \"+\") {\n this.tok.consume(next);\n rhs.push(this.parseTerm());\n }\n else\n throw new ParseError(\"Plus or end expected\", this.tok.pos);\n }\n return new Equation(lhs, rhs);\n }",
"function WordParser () {}",
"cfg2ast (cfg) {\n /* establish abstract syntax tree (AST) node generator */\n let asty = new ASTY()\n const AST = (type, ref) => {\n let ast = asty.create(type)\n if (typeof ref === \"object\" && ref instanceof Array && ref.length > 0)\n ref = ref[0]\n if (typeof ref === \"object\" && ref instanceof Tokenizr.Token)\n ast.pos(ref.line, ref.column, ref.pos)\n else if (typeof ref === \"object\" && asty.isA(ref))\n ast.pos(ref.pos().line, ref.pos().column, ref.pos().offset)\n return ast\n }\n\n /* establish lexical scanner */\n let lexer = new Tokenizr()\n lexer.rule(/[a-zA-Z_][a-zA-Z0-9_]*/, (ctx, m) => {\n ctx.accept(\"id\")\n })\n lexer.rule(/[+-]?[0-9]+/, (ctx, m) => {\n ctx.accept(\"number\", parseInt(m[0]))\n })\n lexer.rule(/\"((?:\\\\\\\"|[^\\r\\n]+)+)\"/, (ctx, m) => {\n ctx.accept(\"string\", m[1].replace(/\\\\\"/g, \"\\\"\"))\n })\n lexer.rule(/\\/\\/[^\\r\\n]+\\r?\\n/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/[ \\t\\r\\n]+/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/./, (ctx, m) => {\n ctx.accept(\"char\")\n })\n\n /* establish recursive descent parser */\n let parser = {\n parseCfg () {\n let block = this.parseBlock()\n lexer.consume(\"EOF\")\n return AST(\"Section\", block).set({ ns: \"\" }).add(block)\n },\n parseBlock () {\n let items = []\n for (;;) {\n let item = lexer.alternatives(\n this.parseProperty.bind(this),\n this.parseSection.bind(this),\n this.parseEmpty.bind(this))\n if (item === undefined)\n break\n items.push(item)\n }\n return items\n },\n parseProperty () {\n let key = this.parseId()\n lexer.consume(\"char\", \"=\")\n let value = lexer.alternatives(\n this.parseNumber.bind(this),\n this.parseString.bind(this))\n return AST(\"Property\", value).set({ key: key.value, val: value.value })\n },\n parseSection () {\n let ns = this.parseId()\n lexer.consume(\"char\", \"{\")\n let block = this.parseBlock()\n lexer.consume(\"char\", \"}\")\n return AST(\"Section\", ns).set({ ns: ns.value }).add(block)\n },\n parseId () {\n return lexer.consume(\"id\")\n },\n parseNumber () {\n return lexer.consume(\"number\")\n },\n parseString () {\n return lexer.consume(\"string\")\n },\n parseEmpty () {\n return undefined\n }\n }\n\n /* parse syntax character string into abstract syntax tree (AST) */\n let ast\n try {\n lexer.input(cfg)\n ast = parser.parseCfg()\n }\n catch (ex) {\n console.log(ex.toString())\n process.exit(0)\n }\n return ast\n }",
"function lce_read_expr(input)\n{\n\tif (typeof input != 'string')\n\t{\n\t\treturn undefined;\n\t}\n\n\tvar i,j;\n\tvar current = undefined;\n\tvar temp;\n\tvar stack = [];\n\tvar MODE_EXPR = 0; // main mode, determines all type for all other expressions\n\tvar MODE_VARLIST = 1; // handles the function abstraction type, which has a restricted character set(meta-meanings)\n\tvar mode = MODE_EXPR;\n\tvar varstart = 0;\n\t\n\tfor (i = 0; i < input.length; i++)\n\t{\n\t\tif (mode == MODE_EXPR)\n\t\t{\n\t\t//recursively handle any parenthesis\n\t\t\tif (input[i] == '(')\n\t\t\t{\n\t\t\t\tj = findCloseBalance(input, i);\n\t\t\t\tif (j == -1)\n\t\t\t\t{\n\t\t\t\t\talert(\"Error: imbalance of parenthesis.\");\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\ttemp = lce_read_expr(input.substr(i+1, j-i-1));\n\t\t\t\tif (current == undefined)\n\t\t\t\t{\n\t\t\t\t\tcurrent = temp;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcurrent = new lce_expr_app(current, temp);\n\t\t\t\t}\n\t\t\t\ti = j;\n\t\t\t\tvarstart = i + 1;\n\t\t\t}\n\t\t\t// detect the beginning of a functional abstraction\n\t\t\telse if (input[i] == '\\\\')\n\t\t\t{\n\t\t\t\tif (input.substr(i+1,6) == 'lambda')\n\t\t\t\t{\n\t\t\t\t\ti += 7;\n\t\t\t\t\tstack.push(new stack_pair(mode, current));\n\t\t\t\t\tmode = MODE_VARLIST;\n\t\t\t\t\tcurrent = new lce_expr_abs();\n\t\t\t\t\tvarstart = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// look for variable names and applications\n\t\t\telse if ((input[i].match(/\\s/) && strip_ws(input.substr(varstart,i+1-varstart)) != \"\")\n\t\t\t\t|| (i + 1 == input.length && strip_ws(input.substr(varstart,i+1-varstart)) != \"\"))\n\t\t\t{\n\t\t\t\tif (current == undefined)\n\t\t\t\t{\n\t\t\t\t\tcurrent = new lce_expr_var(input.substr(varstart,i+1-varstart));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcurrent = new lce_expr_app(current, new lce_expr_var(input.substr(varstart,i+1-varstart)));\n\t\t\t\t}\n\t\t\t\tvarstart = i;\n\t\t\t}\n\t\t}\n\t\telse if (mode == MODE_VARLIST)\n\t\t{\n\t\t\t//detect the end of the variable list\n\t\t\tif (input[i] == '.')\n\t\t\t{\n\t\t\t\tif (current.varlist.length == 0)\n\t\t\t\t{\n\t\t\t\t\talert(\"Error: lambda without any bound variables.\");\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\tstack.push(new stack_pair(mode, current));\n\t\t\t\tmode = MODE_EXPR;\n\t\t\t\tcurrent = undefined;\n\t\t\t\tvarstart = i + 1;\n\t\t\t}\n\t\t\t// detect illegal characters\n\t\t\telse if (input[i] == '\\\\' || input[i] == '(' || input[i] == ')')\n\t\t\t{\n\t\t\t\talert(\"Error: Illegal character, '\\\\', '(', ')' in variable list.\");\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\t// detect variable names and add to list\n\t\t\telse if ((input[i].match(/\\s/) && strip_ws(input.substr(varstart,i+1-varstart)) != \"\")\n\t\t\t\t|| ((i + 1 == input.length || input[i + 1] == '.') && strip_ws(input.substr(varstart,i+1-varstart)) != \"\"))\n\t\t\t{\n\t\t\t\tcurrent.addVar(input.substr(varstart,i+1-varstart));\n\t\t\t\tvarstart = i;\n\t\t\t}\n\t\t}\n\t}\n\n\t// unstack all stored partial results and combine into final result\n\twhile (stack.length > 0)\n\t{\n\t\tif (stack[stack.length - 1].mode == MODE_EXPR)\n\t\t{\n\t\t\tif (stack[stack.length - 1].expr != undefined)\n\t\t\t{\n\t\t\t\tif (current == undefined)\n\t\t\t\t{\n\t\t\t\t\tcurrent = stack[stack.length - 1].expr;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcurrent = new lce_expr_app(stack[stack.length - 1].expr, current);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (stack[stack.length - 1].mode == MODE_VARLIST)\n\t\t{\n\t\t\tif (current == undefined)\n\t\t\t{\n\t\t\t\talert(\"Error: abstraction without sub-expression.\");\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tstack[stack.length - 1].expr.subexpr = current;\n\t\t\tcurrent = stack[stack.length - 1].expr;\n\t\t}\n\t\tstack.pop();\n\t}\n\t\n\treturn current;\n}",
"function GrammarError(message) {\n\t this.name = \"GrammarError\";\n\t this.message = message;\n\t}",
"function parse() {\n var action;\n\n stackTop = 0;\n stateStack[0] = 0;\n stack[0] = null;\n lexicalToken = parserElement(true);\n state = 0;\n errorFlag = 0;\n errorCount = 0;\n\n if (isVerbose()) {\n console.log(\"Starting to parse\");\n parserPrintStack();\n }\n\n while(2 != 1) { // forever with break and return below\n action = parserAction(state, lexicalToken);\n if (action == ACCEPT) {\n if (isVerbose()) {\n console.log(\"Program Accepted\");\n }\n return 1;\n }\n\n if (action > 0) {\n if(parserShift(lexicalToken, action) == 0) {\n return 0;\n }\n lexicalToken = parserElement(false);\n if(errorFlag > 0) {\n errorFlag--; // properly recovering from error\n }\n } else if(action < 0) {\n if (parserReduce(lexicalToken, -action) == 0) {\n if(errorFlag == -1) {\n if(parserRecover() == 0) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n } else if(action == 0) {\n if (parserRecover() == 0) {\n return 0;\n }\n }\n }\n }",
"function getGrammar() {\n if($ctrl.grammar === \"intellicheck\"){\n return new IntellicheckGrammar($ctrl.tvFields);\n }else if($ctrl.grammar === \"task\"){\n return new TaskGrammar();\n }else{\n return new DefaultGrammar();\n }\n }",
"rulesLoad(filename) {\n var fp = new File(filename, \"r\");\n if(!fp.open)\n error(\"fatal\", \"Unable to open grammar file \\\"\" + filename + \"\\\" for reading.\", \"SimpleGrammar.rulesLoad\");\n var tmp = fp.read();\n tmp = tmp.split(/\\n+/);\n var lines = [ ];\n while(tmp.length) {\n var line = tmp.shift().replace(/\\/\\/.*/g, \"\").trim();\n if(line.length)\n lines.push(line);\n }\n\n var nonterminal = /^\\[([^\\]]+)\\]/;\n var replacement = /^(([0-9]+):)?\\s*(.*)/;\n\n var currentNonterminal = null;\n var currentReplacements = [ ];\n\n for(var i = 0, match; i < lines.length; i++) {\n if(match = lines[i].match(nonterminal)) {\n if(currentNonterminal !== null && currentReplacements.length)\n this.ruleSet(currentNonterminal, currentReplacements);\n currentNonterminal = match[1];\n currentReplacements = [ ];\n\n } else if((match = lines[i].match(replacement)) && currentNonterminal !== null) {\n var weight = match[2] === undefined ? 1 : parseInt(match[2]);\n var str = this.textParse(match[3]);\n\n if(isNaN(weight) || weight < 1)\n error(\"fatal\", \"Invalid weight: \" + lines[i], \"SimpleGrammar.rulesLoad\");\n\n currentReplacements.push([str, weight]);\n }\n }\n if(currentNonterminal !== null && currentReplacements.length)\n this.ruleSet(currentNonterminal, currentReplacements);\n }",
"function parseExpression(program) {\n program = skipSpace(program);\n let match, expr;\n // using 3 regex to spot either strings, #s or words\n if (match = /^\"([^\"]*)\"/.exec(program)) {\n expr = {type: \"value\", value: match[1]};\n } else if (match = /^\\d+\\b/.exec(program)) {\n expr = {type: \"value\", value: Number(match[0])};\n } else if (match = /^[^\\s(),#\"]+/.exec(program)) {\n expr = {type: \"word\", name: match[0]};\n } else {\n // if the input does not match any of the above 3 forms, it's not a valid expression\n // throw an error, specifically Syntax Error\n throw new SyntaxError(\"Unexpected syntax: \" + program);\n }\n// return what is matched and pass it along w/ the object for the expression to parseApply\n return parseApply(expr, program.slice(match[0].length));\n}",
"function DFAState(stateNumber, configs) {\n if (stateNumber === null) {\n stateNumber = -1;\n }\n if (configs === null) {\n configs = new ATNConfigSet();\n }\n this.stateNumber = stateNumber;\n this.configs = configs;\n // {@code edges[symbol]} points to target of symbol. Shift up by 1 so (-1)\n // {@link Token//EOF} maps to {@code edges[0]}.\n this.edges = null;\n this.isAcceptState = false;\n // if accept state, what ttype do we match or alt do we predict?\n // This is set to {@link ATN//INVALID_ALT_NUMBER} when {@link\n // //predicates}{@code !=null} or\n // {@link //requiresFullContext}.\n this.prediction = 0;\n this.lexerActionExecutor = null;\n // Indicates that this state was created during SLL prediction that\n // discovered a conflict between the configurations in the state. Future\n // {@link ParserATNSimulator//execATN} invocations immediately jumped doing\n // full context prediction if this field is true.\n this.requiresFullContext = false;\n // During SLL parsing, this is a list of predicates associated with the\n // ATN configurations of the DFA state. When we have predicates,\n // {@link //requiresFullContext} is {@code false} since full context\n // prediction evaluates predicates\n // on-the-fly. If this is not null, then {@link //prediction} is\n // {@link ATN//INVALID_ALT_NUMBER}.\n //\n // <p>We only use these for non-{@link //requiresFullContext} but\n // conflicting states. That\n // means we know from the context (it's $ or we don't dip into outer\n // context) that it's an ambiguity not a conflict.</p>\n //\n // <p>This list is computed by {@link\n // ParserATNSimulator//predicateDFAState}.</p>\n this.predicates = null;\n return this;\n}",
"function RegexGrapher(regex, nfa) {\n this.nfa = nfa;\n var p = regex.rtype;\n\n if(p == 'p') { // Primitive\n this.start = new Node(\"\");\n this.end = new Node(\"\");\n nfa.add_node(this.start);\n nfa.add_node(this.end);\n this.start.add_next_edge(new Edge(this.start, regex.c, this.end));\n }\n else if(p == 's') { // Sequence\n var first = new RegexGrapher(regex.first, nfa);\n var second = new RegexGrapher(regex.second, nfa);\n this.start = first.start;\n this.end = second.end;\n var edgesToUpdate = second.start.nextEdges;\n for (var i = edgesToUpdate.length - 1; i >= 0; i--) {\n // Update outgoing edges to start at first.end\n edgesToUpdate[i].prev_node = first.end;\n };\n // Replace outgoing edges at first.end\n // (There should be none to begin with)\n first.end.nextEdges = edgesToUpdate;\n // Remove the extra node from the graph\n nfa.nodes.splice(nfa.nodes.indexOf(second.start), 1);\n }\n else if(p == 'c') { // Choice\n var thisOne = new RegexGrapher(regex.thisOne, nfa);\n var thatOne = new RegexGrapher(regex.thatOne, nfa);\n this.start = new Node(\"\");\n this.end = new Node(\"\");\n nfa.add_node(this.start);\n nfa.add_node(this.end);\n this.start.add_next_edge(new Edge(this.start, \"eps\", thisOne.start));\n this.start.add_next_edge(new Edge(this.start, \"eps\", thatOne.start));\n thisOne.end.add_next_edge(new Edge(thisOne.end, \"eps\", this.end));\n thatOne.end.add_next_edge(new Edge(thatOne.end, \"eps\", this.end));\n }\n else if(p == 'r') { // Repetition\n var internal = new RegexGrapher(regex.internal, nfa);\n this.start = new Node(\"\");\n this.end = new Node(\"\");\n nfa.add_node(this.start);\n nfa.add_node(this.end);\n this.start.add_next_edge(new Edge(this.start, \"eps\", internal.start));\n this.start.add_next_edge(new Edge(this.start, \"eps\", this.end));\n internal.end.add_next_edge(new Edge(internal.end, \"eps\", internal.start));\n internal.end.add_next_edge(new Edge(internal.end, \"eps\", this.end));\n }\n else throw \"Regex type not found\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return location of firefox.exe file for a given Firefox directory (available: "Mozilla Firefox", "Aurora", "Nightly"). | function getFirefoxExe(firefoxDirName){
if (process.platform !== 'win32') {
return null;
}
var prefix;
var prefixes = [process.env.PROGRAMFILES, process.env['PROGRAMFILES(X86)']];
var suffix = '\\'+ firefoxDirName + '\\firefox.exe';
for (var i = 0; i < prefixes.length; i++) {
prefix = prefixes[i];
if (fs.existsSync(prefix + suffix)) {
return prefix + suffix;
}
}
return 'C:\\Program Files' + suffix;
} | [
"function isFirefox()\n{\n var m = navigator.userAgent.match(/Firefox\\/(\\d\\.\\d+)/);\n if(m)\n {\n return true;\n }\n}",
"function getExecutablePath () {\n let possiblePaths = [\n '/Applications/Guild Wars 2.app',\n 'C:\\\\Program Files\\\\Guild Wars 2\\\\Gw2.exe',\n 'C:\\\\Program Files (x86)\\\\Guild Wars 2\\\\Gw2.exe'\n ]\n\n // Load the previously saved path at the first spot\n let savedPath = config.get('executablePath')\n if (savedPath) {\n possiblePaths.unshift(savedPath)\n }\n\n // Go through all the paths and filter the ones out that are existing\n // (This also checks if the path the user chose still exists)\n possiblePaths = possiblePaths.filter(path => {\n try {\n fs.statSync(path)\n return true\n } catch (noop) {\n return false\n }\n })\n\n // The user will have to choose his launcher path\n if (possiblePaths.length === 0) {\n config.delete('executablePath')\n return false\n }\n\n // Save the first existing path as our path\n config.set('executablePath', possiblePaths[0])\n return true\n}",
"function isFirefox() {\n return navigator\n && /firefox/i.test(\n navigator.userAgent || navigator.vendor || ''\n );\n }",
"function getFilePath() {\n let lastExecCommand = execSync('tail ' + getHistoryPath() + ' | grep imgcat | tail -n 1').toString();\n let home = execSync('echo $HOME | tr -d \"\\n\"').toString() + '/';\n let commands = lastExecCommand.split('imgcat');\n let absolutePath = commands.pop().replace('~/', home);\n return absolutePath;\n}",
"function installFirefoxOSApp(e) {\n e.preventDefault();\n $('#firefoxinstallheader').addClass(\"loading\");\n var manifest_url = location.origin + '/manifest.webapp';\n var installLocFind = navigator.mozApps.install(manifest_url);\n installLocFind.onsuccess = function(data) {\n $('#firefoxinstallheader').html(\"<p>SuccessWhale App installed! You should now see an icon on your homescreen.</p>\");\n };\n installLocFind.onerror = function() {\n $('#firefoxinstallheader').removeClass(\"loading\");\n alert(\"Installation failed. Please report this error: \" + installLocFind.error.name);\n };\n}",
"function getCurrentDirectory() {\r\n\treturn File.GetAbsolutePathName(\".\");\r\n}",
"dir() {\n if (this.program.dir) {\n if (Path.isAbsolute(this.program.dir)) {\n return this.program.dir;\n }\n return Path.resolve(process.cwd(), this.program.dir);\n }\n return process.cwd();\n }",
"function getFilePath(fileName) {\n return os.userInfo().homedir + \"\\\\AppData\\\\Roaming\\\\.minecraft\\\\mcpipy\\\\\" + fileName + \".py\";\n}",
"function absPath(path)\r\n{\r\n expandedPath = WshShell.ExpandEnvironmentStrings(path);\r\n fso = WScript.CreateObject(\"Scripting.FileSystemObject\");\r\n return fso.GetAbsolutePathName(expandedPath);\r\n}",
"_getWorkingDirectory() {\n const activeItem = atom.workspace.getActivePaneItem();\n if (activeItem\n && activeItem.buffer\n && activeItem.buffer.file\n && activeItem.buffer.file.path) {\n return atom.project.relativizePath(activeItem.buffer.file.path)[0];\n } else {\n const projectPaths = atom.project.getPaths();\n let cwd;\n if (projectPaths.length > 0) {\n cwd = projectPaths[0];\n } else {\n cwd = process.env.HOME;\n }\n return path.resolve(cwd);\n }\n }",
"function getChromeDir(resolvedURI) {\n\n var fileHandler = Components.classes[\"@mozilla.org/network/protocol;1?name=file\"].\n getService(Components.interfaces.nsIFileProtocolHandler);\n var chromeDir = fileHandler.getFileFromURLSpec(resolvedURI.spec);\n return chromeDir.parent.QueryInterface(Components.interfaces.nsILocalFile);\n}",
"function createFirefoxProfile(profile_name, callback) {\n\tlog(\"Creating firefox profile \" + profile_name);\n\tvar proc = spawn_dbg('firefox', ['-CreateProfile',\n\t\tprofile_name + \" \" + config.external.firefox_profile_dir + profile_name, '-new-instance']);\n\tproc.on('exit', function (code) {\n\t\tif (code == 0) {\n\t\t\tcallback(null);\n\t\t} else {\n\t\t\tcallback('firefox -CreateProfile returns code ' + code);\n\t\t}\n\t});\n}",
"function getHistoryPath() {\n let shell = execSync('echo $SHELL').toString();\n if (new RegExp('zsh').test(shell)) {\n return '~/.zsh_history';\n } else if (new RegExp('bash').test(shell)) {\n return '~/.bash_history';\n } else if (new RegExp('fish').test(shell)) {\n return '~/.local/share/fish/fish_history';\n }\n}",
"function getQbExecutablePath() {\n var path = require( \"path\" );\n var modulePath = path.dirname( module.filename );\n var qbPath = path.resolve( modulePath + \"/../qb/bin/Release/qb.exe\" );\n return qbPath;\n}",
"function utils_isNavegadorFirefox2()\n\t{\n\t\tif(window.isNavegadorFF2==\"undefined\" || window.isNavegadorFF2==undefined || window.isNavegadorFF2==\"null\" || window.isNavegadorFF2==null){\n\t\t\tvar agente=navigator.userAgent;\n\t\t\tif(agente.indexOf(\"Firefox/\")!=-1){\n\t\t\t\tvar version=agente.substring(agente.indexOf(\"Firefox/\")+\"Firefox/\".length,agente.indexOf(\"Firefox/\")+\"Firefox/\".length+1);\n\t\t\t\tif(version!=null && version!=undefined && version=='2'){\n\t\t\t\t\twindow.isNavegadorFF2=true;\n\t\t\t\t\treturn true;\n\t\t\t\t}else{\n\t\t\t\t\twindow.isNavegadorFF2=false;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tif(agente.indexOf(\"BonEcho/\")!=-1){\n\t\t\t\t\tvar versionLinux=agente.substring(agente.indexOf(\"BonEcho/\")+\"BonEcho/\".length,agente.indexOf(\"BonEcho/\")+\"BonEcho/\".length+1);\n\t\t\t\t\tif(versionLinux!=null && versionLinux!=undefined && versionLinux=='2'){\n\t\t\t\t\t\twindow.isNavegadorFF2=true;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}else{\n\t\t\t\t\t\twindow.isNavegadorFF2=false;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tif(agente.indexOf(\"rv:\")!=-1){\n\t\t\t\t\t\tvar versionWindows=agente.substring(agente.indexOf(\"rv:\")+\"rv:\".length,agente.indexOf(\"rv:\")+\"rv:\".length+3);\n\t\t\t\t\t\tif(versionWindows!=null && versionWindows!=undefined && versionWindows=='1.8'){\n\t\t\t\t\t\t\twindow.isNavegadorFF2=true;\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\twindow.isNavegadorFF2=false;\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}else{\n\t\t\t\t\t\twindow.isNavegadorFF2=false;\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\t}else{\n\t\t\tif(window.isNavegadorFF2==true)\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}else{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}",
"function simulateWinFirefox() {\n userAgent.MAC = false;\n userAgent.WINDOWS = true;\n userAgent.LINUX = false;\n userAgent.IE = false;\n userAgent.EDGE = false;\n userAgent.EDGE_OR_IE = false;\n userAgent.GECKO = true;\n userAgent.WEBKIT = false;\n}",
"static get defaultLocation() {\n return Toxen.updatePlatform == \"win\" ? process.env.APPDATA + \"\\\\ToxenData\\\\data\\\\stats.json\" : process.env.HOME + \"/.toxendata/data/stats.json\";\n }",
"function simulateLinuxFirefox() {\n userAgent.MAC = false;\n userAgent.WINDOWS = false;\n userAgent.LINUX = true;\n userAgent.IE = false;\n userAgent.EDGE = false;\n userAgent.EDGE_OR_IE = false;\n userAgent.GECKO = true;\n userAgent.WEBKIT = false;\n}",
"function imdbHome () {\n var homeDir = execSync (\"echo $IMDB_HOME\").toString ().trim ()\n console.log(\"1 homeDir\",homeDir)\n if (!homeDir || homeDir === \"\") {\n homeDir = execSync (\"echo $HOME\").toString ().trim ()\n console.log(\"2 homeDir\",homeDir)\n }\n return homeDir\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instantiate a new multi render target texture. A multi render target, like a render target provides the ability to render to a texture. Unlike the render target, it can render to several draw buffers in one draw. This is specially interesting in deferred rendering or for any effects requiring more than just one color from a single pass. | function MultiRenderTarget(name,size,count,scene,options){var _this=this;var generateMipMaps=options&&options.generateMipMaps?options.generateMipMaps:false;var generateDepthTexture=options&&options.generateDepthTexture?options.generateDepthTexture:false;var doNotChangeAspectRatio=!options||options.doNotChangeAspectRatio===undefined?true:options.doNotChangeAspectRatio;_this=_super.call(this,name,size,scene,generateMipMaps,doNotChangeAspectRatio)||this;_this._engine=scene.getEngine();if(!_this.isSupported){_this.dispose();return;}var types=[];var samplingModes=[];for(var i=0;i<count;i++){if(options&&options.types&&options.types[i]!==undefined){types.push(options.types[i]);}else{types.push(options&&options.defaultType?options.defaultType:BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);}if(options&&options.samplingModes&&options.samplingModes[i]!==undefined){samplingModes.push(options.samplingModes[i]);}else{samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);}}var generateDepthBuffer=!options||options.generateDepthBuffer===undefined?true:options.generateDepthBuffer;var generateStencilBuffer=!options||options.generateStencilBuffer===undefined?false:options.generateStencilBuffer;_this._size=size;_this._multiRenderTargetOptions={samplingModes:samplingModes,generateMipMaps:generateMipMaps,generateDepthBuffer:generateDepthBuffer,generateStencilBuffer:generateStencilBuffer,generateDepthTexture:generateDepthTexture,types:types,textureCount:count};_this._createInternalTextures();_this._createTextures();return _this;} | [
"function SpriteMultiple(sprites, render) {\n var sources = render.source[2];\n this.sprites = sprites;\n this.direction = render.source[1];\n if (this.direction === \"vertical\" || this.direction === \"corners\") {\n this.topheight = sources.topheight | 0;\n this.bottomheight = sources.bottomheight | 0;\n }\n if (this.direction === \"horizontal\" || this.direction === \"corners\") {\n this.rightwidth = sources.rightwidth | 0;\n this.leftwidth = sources.leftwidth | 0;\n }\n this.middleStretch = sources.middleStretch || false;\n }",
"function MultiSprite(_id) {\n\t// class constructor\n\tif (_id) this.id = _id;\n}",
"function mTexture() {\n texture(...[...arguments]);\n}",
"function MultiMaterial(name,scene){var _this=_super.call(this,name,scene,true)||this;scene.multiMaterials.push(_this);_this.subMaterials=new Array();_this.storeEffectOnSubMeshes=true;// multimaterial is considered like a push material\nreturn _this;}",
"function create3DTarget(target) {\n let loader = new THREE.TextureLoader();\n let planetSize = .5;\n loader.load(`./assets/img/targets/${target.name}.jpg`, (texture) => {\n let geom = new THREE.SphereGeometry(planetSize, 30, 30);\n let mat = (target.name == 'Sun') ? new THREE.MeshBasicMaterial({map: texture}) : new THREE.MeshLambertMaterial({map: texture});\n let planet = new THREE.Mesh(geom, mat);\n planet.name = target.name; planet.targetIndex = targets.indexOf(target);\n // Positioning\n let targetCartesian = Math.cartesian(target.az, target.el, gridRadius);\n planet.position.x = -targetCartesian.x;\n planet.position.z = -targetCartesian.z;\n planet.position.y = targetCartesian.y;\n planet.lookAt(0, 0, 0); planet.rotateY(Math.radians(target.az));\n // Target specific features\n if (planet.name == 'Saturn') {\n loader.load(`./assets/img/targets/SaturnRing.png`, (texture) => {\n geom = new THREE.RingGeometry(planetSize * 1.116086235489221, planetSize * 2.326699834162521, 84, 1);\n for(var yi = 0; yi < geom.parameters.phiSegments; yi++) {\n var u0 = yi / geom.parameters.phiSegments;\n var u1=(yi + 1) / geom.parameters.phiSegments;\n for(var xi = 0; xi < geom.parameters.thetaSegments; xi++) {\n \t\tvar fi = 2 * (xi + geom.parameters.thetaSegments * yi);\n var v0 = xi / geom.parameters.thetaSegments;\n var v1 = (xi + 1) / geom.parameters.thetaSegments;\n geom.faceVertexUvs[0][fi][0].x = u0; geom.faceVertexUvs[0][fi][0].y = v0;\n geom.faceVertexUvs[0][fi][1].x = u1; geom.faceVertexUvs[0][fi][1].y = v0;\n geom.faceVertexUvs[0][fi][2].x = u0; geom.faceVertexUvs[0][fi][2].y = v1;\n fi++;\n geom.faceVertexUvs[0][fi][0].x = u1; geom.faceVertexUvs[0][fi][0].y = v0;\n geom.faceVertexUvs[0][fi][1].x = u1; geom.faceVertexUvs[0][fi][1].y = v1;\n geom.faceVertexUvs[0][fi][2].x = u0; geom.faceVertexUvs[0][fi][2].y = v1;\n }\n }\n mat = new THREE.MeshLambertMaterial( { map: texture, side: THREE.DoubleSide, transparent: true } );\n let ring = new THREE.Mesh(geom, mat);\n ring.rotateX(27);\n planet.add(ring);\n });\n } else if (target.name == 'Sun') {\n const light = new THREE.PointLight('#d4caba', 1, 500, 0 );\n let lightCartesian = Math.cartesian(target.az, target.el, gridRadius - .5);\n light.position.x = -lightCartesian.x;\n light.position.y = lightCartesian.y;\n light.position.z = -lightCartesian.z;\n scene.add(light);\n }\n // planet.add(new THREE.AxesHelper(5));\n scene.add(planet);\n });\n}",
"function createDepthTarget(sw, sh, format, type, colorTarget) {\n\t\t\tvar depthTarget = new THREE.WebGLRenderTarget(sw, sh, {\n\t\t\t\tminFilter: THREE.NearestFilter,\n\t\t\t\tmagFilter: THREE.NearestFilter,\n\t\t\t\tformat: format,\n\t\t\t\ttype: type,\n\t\t\t\tstencilBuffer: _hasStencil\n\t\t\t});\n\t\t\tif(colorTarget) {\n\t\t\t\tdepthTarget.shareDepthFrom = colorTarget;\n\t\t\t}\n\t\t\tdepthTarget.name = \"depthTarget\";\n\t\t\treturn depthTarget;\n\t\t}",
"function addTargetsToDOM(){\n\t//add left target\n\tvar matrix = new THREE.Matrix4();\n\tmatrix.set(0.001, 0.000, 0.000, -0.175,0.000, 0.001, 0.000, 0.000,0.000, 0.000, 0.001, 0.000,0.000, 0.000, 0.000, 1.000);\n\tvar position = new THREE.Vector3();\n\tvar quaternion = new THREE.Quaternion();\n\tvar scale = new THREE.Vector3();\n\n\tmatrix.decompose( position, quaternion, scale );\n\tposition.multiplyScalar(scaling);\n\n\tposition.add(sceneOffset);\n\tvar targetL = document.createElement(\"a-sphere\");\n\ttargetL.setAttribute(\"position\",position);\n\ttargetL.setAttribute(\"radius\",0.03)\n\t\n\tscene.appendChild(targetL);\n\t\n\t//add right target\n\tmatrix = new THREE.Matrix4();\n\tmatrix.set(0.001, 0.000, 0.000, 0.175,0.000, 0.001, 0.000, 0.000,0.000, 0.000, 0.001, 0.000,0.000, 0.000, 0.000, 1.000);\n\n\tposition = new THREE.Vector3();\n\tquaternion = new THREE.Quaternion();\n\tscale = new THREE.Vector3();\n\tmatrix.decompose( position, quaternion, scale );\n\tposition.multiplyScalar(scaling);\n\n\tposition.add(sceneOffset);\n\tvar targetR = document.createElement(\"a-sphere\");\n\ttargetR.setAttribute(\"position\",position);\n\ttargetR.setAttribute(\"radius\",0.03)\n\t\n\tscene.appendChild(targetR);\n\t\n}",
"function ProceduralTexture(name,size,fragment,scene,fallbackTexture,generateMipMaps,isCube){if(fallbackTexture===void 0){fallbackTexture=null;}if(generateMipMaps===void 0){generateMipMaps=true;}if(isCube===void 0){isCube=false;}var _this=_super.call(this,null,scene,!generateMipMaps)||this;_this.isCube=isCube;/**\n * Define if the texture is enabled or not (disabled texture will not render)\n */_this.isEnabled=true;/**\n * Define if the texture must be cleared before rendering (default is true)\n */_this.autoClear=true;/**\n * Event raised when the texture is generated\n */_this.onGeneratedObservable=new BABYLON.Observable();/** @hidden */_this._textures={};_this._currentRefreshId=-1;_this._refreshRate=1;_this._vertexBuffers={};_this._uniforms=new Array();_this._samplers=new Array();_this._floats={};_this._ints={};_this._floatsArrays={};_this._colors3={};_this._colors4={};_this._vectors2={};_this._vectors3={};_this._matrices={};_this._fallbackTextureUsed=false;_this._cachedDefines=\"\";_this._contentUpdateId=-1;scene=_this.getScene();var component=scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);if(!component){component=new BABYLON.ProceduralTextureSceneComponent(scene);scene._addComponent(component);}scene.proceduralTextures.push(_this);_this._engine=scene.getEngine();_this.name=name;_this.isRenderTarget=true;_this._size=size;_this._generateMipMaps=generateMipMaps;_this.setFragment(fragment);_this._fallbackTexture=fallbackTexture;if(isCube){_this._texture=_this._engine.createRenderTargetCubeTexture(size,{generateMipMaps:generateMipMaps,generateDepthBuffer:false,generateStencilBuffer:false});_this.setFloat(\"face\",0);}else{_this._texture=_this._engine.createRenderTargetTexture(size,{generateMipMaps:generateMipMaps,generateDepthBuffer:false,generateStencilBuffer:false});}// VBO\nvar vertices=[];vertices.push(1,1);vertices.push(-1,1);vertices.push(-1,-1);vertices.push(1,-1);_this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]=new BABYLON.VertexBuffer(_this._engine,vertices,BABYLON.VertexBuffer.PositionKind,false,false,2);_this._createIndexBuffer();return _this;}",
"function RenderFrameContext( o )\r\n{\r\n\tthis.width = 0; //0 means the same size as the viewport, negative numbers mean reducing the texture in half N times\r\n\tthis.height = 0; //0 means the same size as the viewport\r\n\tthis.precision = RenderFrameContext.DEFAULT_PRECISION; //LOW_PRECISION uses a byte, MEDIUM uses a half_float, HIGH uses a float, or directly the texture type (p.e gl.UNSIGNED_SHORT_4_4_4_4 )\r\n\tthis.filter_texture = true; //magFilter: in case the texture is shown, do you want to see it pixelated?\r\n\tthis.format = GL.RGB; //how many color channels, or directly the texture internalformat \r\n\tthis.use_depth_texture = true; //store the depth in a texture\r\n\tthis.use_stencil_buffer = false; //add an stencil buffer (cannot be read as a texture in webgl)\r\n\tthis.num_extra_textures = 0; //number of extra textures in case we want to render to several buffers\r\n\tthis.name = null; //if a name is provided all the textures will be stored in the ONE.ResourcesManager\r\n\r\n\tthis.generate_mipmaps = false; //try to generate mipmaps if possible (only when the texture is power of two)\r\n\tthis.adjust_aspect = false; //when the size doesnt match the canvas size it could look distorted, settings this to true will fix the problem\r\n\tthis.clone_after_unbind = false; //clones the textures after unbinding it. Used when the texture will be in the 3D scene\r\n\r\n\tthis._fbo = null;\r\n\tthis._color_texture = null;\r\n\tthis._depth_texture = null;\r\n\tthis._textures = []; //all color textures (the first will be _color_texture)\r\n\tthis._cloned_textures = null; //in case we set the clone_after_unbind to true\r\n\tthis._cloned_depth_texture = null;\r\n\r\n\tthis._version = 1; //to detect changes\r\n\tthis._minFilter = gl.NEAREST;\r\n\r\n\tif(o)\r\n\t\tthis.configure(o);\r\n}",
"function MorphTargetManager(scene){if(scene===void 0){scene=null;}this._targets=new Array();this._targetInfluenceChangedObservers=new Array();this._targetDataLayoutChangedObservers=new Array();this._activeTargets=new BABYLON.SmartArray(16);this._supportsNormals=false;this._supportsTangents=false;this._vertexCount=0;this._uniqueId=0;this._tempInfluences=new Array();if(!scene){scene=BABYLON.Engine.LastCreatedScene;}this._scene=scene;if(this._scene){this._scene.morphTargetManagers.push(this);this._uniqueId=this._scene.getUniqueId();}}",
"function createTextureArray(gl, array) {\n var dtype = array.dtype\n var shape = array.shape.slice()\n var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)\n if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) {\n throw new Error('gl-texture2d: Invalid texture size')\n }\n var packed = isPacked(shape, array.stride.slice())\n var type = 0\n if(dtype === 'float32') {\n type = gl.FLOAT\n } else if(dtype === 'float64') {\n type = gl.FLOAT\n packed = false\n dtype = 'float32'\n } else if(dtype === 'uint8') {\n type = gl.UNSIGNED_BYTE\n } else {\n type = gl.UNSIGNED_BYTE\n packed = false\n dtype = 'uint8'\n }\n var format = 0\n if(shape.length === 2) {\n format = gl.LUMINANCE\n shape = [shape[0], shape[1], 1]\n array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset)\n } else if(shape.length === 3) {\n if(shape[2] === 1) {\n format = gl.ALPHA\n } else if(shape[2] === 2) {\n format = gl.LUMINANCE_ALPHA\n } else if(shape[2] === 3) {\n format = gl.RGB\n } else if(shape[2] === 4) {\n format = gl.RGBA\n } else {\n throw new Error('gl-texture2d: Invalid shape for pixel coords')\n }\n } else {\n throw new Error('gl-texture2d: Invalid shape for texture')\n }\n if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) {\n type = gl.UNSIGNED_BYTE\n packed = false\n }\n var buffer, buf_store\n var size = array.size\n if(!packed) {\n var stride = [shape[2], shape[2]*shape[0], 1]\n buf_store = pool.malloc(size, dtype)\n var buf_array = ndarray(buf_store, shape, stride, 0)\n if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) {\n convertFloatToUint8(buf_array, array)\n } else {\n ops.assign(buf_array, array)\n }\n buffer = buf_store.subarray(0, size)\n } else if (array.offset === 0 && array.data.length === size) {\n buffer = array.data\n } else {\n buffer = array.data.subarray(array.offset, array.offset + size)\n }\n var tex = initTexture(gl)\n gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer)\n if(!packed) {\n pool.free(buf_store)\n }\n return new Texture2D(gl, tex, shape[0], shape[1], format, type)\n }",
"function activateTextures()\n{\n\t\tfor(var i=0;i<textureImages.length;i+=2){\n\t\t\t\tif(i==0){\n\t\t\t\t\t\tgl.activeTexture(gl.TEXTURE0)\n\t\t\t\t}else if(i==2){\n\t\t\t\t\t\tgl.activeTexture(gl.TEXTURE1);\n\t\t\t\t}else if(i==4){\n\t\t\t\t\t\tgl.activeTexture(gl.TEXTURE2);\n\t\t\t\t}else if(i==6){\n\t\t\t\t\t\tgl.activeTexture(gl.TEXTURE3);\n\t\t\t\t\t\t// Above 6 is \n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// If index is 0 to 4 it is ordinary 2d texture \n\t\t\t\t// if index is 6 or higher it is a cube map\n\t\t\t\tif(i>=0 && i<=4){\n\t\t\t\t\t\tgl.bindTexture(gl.TEXTURE_2D, Textures[i/2]);\n\t\t\t\t\t\tgl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);\n\t\t\t\t\t\tgl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);\n\t\t\t\t\t\tgl.uniform1i(gl.getUniformLocation(shaderProgram, textureImages[i+1]), i/2); \t// Texture ID\n\t\t\t\t}else if(i==6){\n\t\t\t\t\t\tgl.bindTexture(gl.TEXTURE_CUBE_MAP, Textures[i/2]);\n\t\t\t\t\t\tgl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n\t\t\t\t\t\tgl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\t\t\t\t\t\tgl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n\t\t\t\t\t\tgl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n\t\t\t\t\t\tgl.uniform1i(gl.getUniformLocation(shaderProgram, textureImages[i+1]), i/2); \t// Texture Cube\n\t\t\t\t}\n\t\t\t\t\n\t\t}\n}",
"function MorphTarget(/** defines the name of the target */name,influence,scene){if(influence===void 0){influence=0;}if(scene===void 0){scene=null;}this.name=name;/**\n * Gets or sets the list of animations\n */this.animations=new Array();this._positions=null;this._normals=null;this._tangents=null;/**\n * Observable raised when the influence changes\n */this.onInfluenceChanged=new BABYLON.Observable();/** @hidden */this._onDataLayoutChanged=new BABYLON.Observable();this._animationPropertiesOverride=null;this._scene=scene||BABYLON.Engine.LastCreatedScene;this.influence=influence;}",
"function updateForTextures(_ref) {\n var vs = _ref.vs,\n sourceTextureMap = _ref.sourceTextureMap,\n targetTextureVarying = _ref.targetTextureVarying,\n targetTexture = _ref.targetTexture;\n var texAttributeNames = Object.keys(sourceTextureMap);\n var sourceCount = texAttributeNames.length;\n var targetTextureType = null;\n var samplerTextureMap = {};\n var updatedVs = vs;\n var finalInject = {};\n\n if (sourceCount > 0 || targetTextureVarying) {\n var vsLines = updatedVs.split('\\n');\n var updateVsLines = vsLines.slice();\n vsLines.forEach(function (line, index, lines) {\n // TODO add early exit\n if (sourceCount > 0) {\n var updated = processAttributeDefinition(line, sourceTextureMap);\n\n if (updated) {\n var updatedLine = updated.updatedLine,\n inject = updated.inject;\n updateVsLines[index] = updatedLine; // sampleInstructions.push(sampleInstruction);\n\n finalInject = (0, _src.combineInjects)([finalInject, inject]);\n Object.assign(samplerTextureMap, updated.samplerTextureMap);\n sourceCount--;\n }\n }\n\n if (targetTextureVarying && !targetTextureType) {\n targetTextureType = getVaryingType(line, targetTextureVarying);\n }\n });\n\n if (targetTextureVarying) {\n (0, _assert.default)(targetTexture);\n var sizeName = \"\".concat(SIZE_UNIFORM_PREFIX).concat(targetTextureVarying);\n var uniformDeclaration = \"uniform vec2 \".concat(sizeName, \";\\n\");\n var posInstructions = \" vec2 \".concat(VS_POS_VARIABLE, \" = transform_getPos(\").concat(sizeName, \");\\n gl_Position = vec4(\").concat(VS_POS_VARIABLE, \", 0, 1.);\\n\");\n var inject = {\n 'vs:#decl': uniformDeclaration,\n 'vs:#main-start': posInstructions\n };\n finalInject = (0, _src.combineInjects)([finalInject, inject]);\n }\n\n updatedVs = updateVsLines.join('\\n');\n }\n\n return {\n // updated vertex shader (commented texture attribute definition)\n vs: updatedVs,\n // type (float, vec2, vec3 of vec4) target texture varying\n targetTextureType: targetTextureType,\n // required vertex and fragment shader injects\n inject: finalInject,\n // map of sampler name to texture name, can be used to set attributes\n // usefull when swapping textures, as source and destination texture change when swap is called.\n samplerTextureMap: samplerTextureMap\n };\n} // builds and returns an object contaning size uniform for each texture",
"createTexCoordBuffer () {\n\t\tif (this.texCoordArray === null) {\n\t\t\tconsole.log(\"texCoordArray uninitialized\");\n\t\t}\n\n\t\tconst gl = this.gl;\n\t\tthis.texCoordBuffer = gl.createBuffer();\n\t\tgl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);\n\t\tgl.bufferData(gl.ARRAY_BUFFER,\n \t\tnew Float32Array(this.texCoordArray),\n \t\tgl.STATIC_DRAW);\n\t}",
"function createDataTexture(gl, floatArray) {\n var width = floatArray.length / 4, // R,G,B,A\n height = 1,\n texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D,\n 0, gl.RGBA, width, height, 0, gl.RGBA, gl.FLOAT, floatArray);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n return texture;\n }",
"createTargetsLayer() {\n this.layers.targets = this.document.createElement('div');\n\n this.layers.targets.setAttribute('style', [\n 'position: absolute',\n 'left: 0px',\n 'top: 0px',\n 'height: 100',\n 'pointer-events: none', // Disable pointer events so on hover on points works.\n 'width: 100%',\n 'z-index: 1'\n ].join(';'));\n\n this.layers.targets.setAttribute('class', this.createPrefixedIdentifier('targets'));\n this.holder.appendChild(this.layers.targets);\n }",
"function TextureCube() {\n\n TextureBase.call(this);\n\n this.textureType = WEBGL_TEXTURE_TYPE.TEXTURE_CUBE_MAP;\n\n /**\n * Images data for this texture.\n * @member {HTMLImageElement[]}\n * @default []\n */\n this.images = [];\n\n /**\n * @default false\n */\n this.flipY = false;\n}",
"function initTextures() {\n floorTexture = gl.createTexture();\n floorTexture.image = new Image();\n floorTexture.image.onload = function () {\n handleTextureLoaded(floorTexture)\n }\n floorTexture.image.src = \"./assets/grass1.jpg\";\n\n cubeTexture = gl.createTexture();\n cubeTexture.image = new Image();\n cubeTexture.image.onload = function() {\n handleTextureLoaded(cubeTexture);\n }; // async loading\n cubeTexture.image.src = \"./assets/gifft.jpg\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the AWS CloudFormation properties of an `AWS::AppMesh::Route.GrpcRouteMatch` resource | function cfnRouteGrpcRouteMatchPropertyToCloudFormation(properties) {
if (!cdk.canInspect(properties)) {
return properties;
}
CfnRoute_GrpcRouteMatchPropertyValidator(properties).assertSuccess();
return {
Metadata: cdk.listMapper(cfnRouteGrpcRouteMetadataPropertyToCloudFormation)(properties.metadata),
MethodName: cdk.stringToCloudFormation(properties.methodName),
Port: cdk.numberToCloudFormation(properties.port),
ServiceName: cdk.stringToCloudFormation(properties.serviceName),
};
} | [
"function cfnRouteGrpcRoutePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_GrpcRoutePropertyValidator(properties).assertSuccess();\n return {\n Action: cfnRouteGrpcRouteActionPropertyToCloudFormation(properties.action),\n Match: cfnRouteGrpcRouteMatchPropertyToCloudFormation(properties.match),\n RetryPolicy: cfnRouteGrpcRetryPolicyPropertyToCloudFormation(properties.retryPolicy),\n Timeout: cfnRouteGrpcTimeoutPropertyToCloudFormation(properties.timeout),\n };\n}",
"function cfnGatewayRouteGrpcGatewayRoutePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRoutePropertyValidator(properties).assertSuccess();\n return {\n Action: cfnGatewayRouteGrpcGatewayRouteActionPropertyToCloudFormation(properties.action),\n Match: cfnGatewayRouteGrpcGatewayRouteMatchPropertyToCloudFormation(properties.match),\n };\n}",
"function cfnGatewayRouteGrpcGatewayRouteMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRouteMatchPropertyValidator(properties).assertSuccess();\n return {\n Hostname: cfnGatewayRouteGatewayRouteHostnameMatchPropertyToCloudFormation(properties.hostname),\n Metadata: cdk.listMapper(cfnGatewayRouteGrpcGatewayRouteMetadataPropertyToCloudFormation)(properties.metadata),\n Port: cdk.numberToCloudFormation(properties.port),\n ServiceName: cdk.stringToCloudFormation(properties.serviceName),\n };\n}",
"function cfnRouteGrpcRouteMetadataPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_GrpcRouteMetadataPropertyValidator(properties).assertSuccess();\n return {\n Invert: cdk.booleanToCloudFormation(properties.invert),\n Match: cfnRouteGrpcRouteMetadataMatchMethodPropertyToCloudFormation(properties.match),\n Name: cdk.stringToCloudFormation(properties.name),\n };\n}",
"function cfnGatewayRouteGrpcGatewayRouteMetadataPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRouteMetadataPropertyValidator(properties).assertSuccess();\n return {\n Invert: cdk.booleanToCloudFormation(properties.invert),\n Match: cfnGatewayRouteGatewayRouteMetadataMatchPropertyToCloudFormation(properties.match),\n Name: cdk.stringToCloudFormation(properties.name),\n };\n}",
"function cfnRouteGrpcRouteActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_GrpcRouteActionPropertyValidator(properties).assertSuccess();\n return {\n WeightedTargets: cdk.listMapper(cfnRouteWeightedTargetPropertyToCloudFormation)(properties.weightedTargets),\n };\n}",
"function cfnRouteGrpcRouteMetadataMatchMethodPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_GrpcRouteMetadataMatchMethodPropertyValidator(properties).assertSuccess();\n return {\n Exact: cdk.stringToCloudFormation(properties.exact),\n Prefix: cdk.stringToCloudFormation(properties.prefix),\n Range: cfnRouteMatchRangePropertyToCloudFormation(properties.range),\n Regex: cdk.stringToCloudFormation(properties.regex),\n Suffix: cdk.stringToCloudFormation(properties.suffix),\n };\n}",
"function cfnGatewayRouteGrpcGatewayRouteActionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRouteActionPropertyValidator(properties).assertSuccess();\n return {\n Rewrite: cfnGatewayRouteGrpcGatewayRouteRewritePropertyToCloudFormation(properties.rewrite),\n Target: cfnGatewayRouteGatewayRouteTargetPropertyToCloudFormation(properties.target),\n };\n}",
"function cfnGatewayRouteGrpcGatewayRouteRewritePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GrpcGatewayRouteRewritePropertyValidator(properties).assertSuccess();\n return {\n Hostname: cfnGatewayRouteGatewayRouteHostnameRewritePropertyToCloudFormation(properties.hostname),\n };\n}",
"function cfnGatewayRouteGatewayRouteSpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GatewayRouteSpecPropertyValidator(properties).assertSuccess();\n return {\n GrpcRoute: cfnGatewayRouteGrpcGatewayRoutePropertyToCloudFormation(properties.grpcRoute),\n Http2Route: cfnGatewayRouteHttpGatewayRoutePropertyToCloudFormation(properties.http2Route),\n HttpRoute: cfnGatewayRouteHttpGatewayRoutePropertyToCloudFormation(properties.httpRoute),\n Priority: cdk.numberToCloudFormation(properties.priority),\n };\n}",
"function cfnRouteRouteSpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_RouteSpecPropertyValidator(properties).assertSuccess();\n return {\n GrpcRoute: cfnRouteGrpcRoutePropertyToCloudFormation(properties.grpcRoute),\n Http2Route: cfnRouteHttpRoutePropertyToCloudFormation(properties.http2Route),\n HttpRoute: cfnRouteHttpRoutePropertyToCloudFormation(properties.httpRoute),\n Priority: cdk.numberToCloudFormation(properties.priority),\n TcpRoute: cfnRouteTcpRoutePropertyToCloudFormation(properties.tcpRoute),\n };\n}",
"function cfnGatewayRouteHttpGatewayRouteMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRouteMatchPropertyValidator(properties).assertSuccess();\n return {\n Headers: cdk.listMapper(cfnGatewayRouteHttpGatewayRouteHeaderPropertyToCloudFormation)(properties.headers),\n Hostname: cfnGatewayRouteGatewayRouteHostnameMatchPropertyToCloudFormation(properties.hostname),\n Method: cdk.stringToCloudFormation(properties.method),\n Path: cfnGatewayRouteHttpPathMatchPropertyToCloudFormation(properties.path),\n Port: cdk.numberToCloudFormation(properties.port),\n Prefix: cdk.stringToCloudFormation(properties.prefix),\n QueryParameters: cdk.listMapper(cfnGatewayRouteQueryParameterPropertyToCloudFormation)(properties.queryParameters),\n };\n}",
"function cfnRouteGrpcTimeoutPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_GrpcTimeoutPropertyValidator(properties).assertSuccess();\n return {\n Idle: cfnRouteDurationPropertyToCloudFormation(properties.idle),\n PerRequest: cfnRouteDurationPropertyToCloudFormation(properties.perRequest),\n };\n}",
"function cfnGatewayRouteHttpGatewayRoutePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpGatewayRoutePropertyValidator(properties).assertSuccess();\n return {\n Action: cfnGatewayRouteHttpGatewayRouteActionPropertyToCloudFormation(properties.action),\n Match: cfnGatewayRouteHttpGatewayRouteMatchPropertyToCloudFormation(properties.match),\n };\n}",
"function cfnRouteMatchRangePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_MatchRangePropertyValidator(properties).assertSuccess();\n return {\n End: cdk.numberToCloudFormation(properties.end),\n Start: cdk.numberToCloudFormation(properties.start),\n };\n}",
"function CfnGatewayRoute_GrpcGatewayRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('hostname', CfnGatewayRoute_GatewayRouteHostnameMatchPropertyValidator)(properties.hostname));\n errors.collect(cdk.propertyValidator('metadata', cdk.listValidator(CfnGatewayRoute_GrpcGatewayRouteMetadataPropertyValidator))(properties.metadata));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));\n return errors.wrap('supplied properties not correct for \"GrpcGatewayRouteMatchProperty\"');\n}",
"function cfnRouteHttpRoutePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_HttpRoutePropertyValidator(properties).assertSuccess();\n return {\n Action: cfnRouteHttpRouteActionPropertyToCloudFormation(properties.action),\n Match: cfnRouteHttpRouteMatchPropertyToCloudFormation(properties.match),\n RetryPolicy: cfnRouteHttpRetryPolicyPropertyToCloudFormation(properties.retryPolicy),\n Timeout: cfnRouteHttpTimeoutPropertyToCloudFormation(properties.timeout),\n };\n}",
"function CfnRoute_GrpcRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('metadata', cdk.listValidator(CfnRoute_GrpcRouteMetadataPropertyValidator))(properties.metadata));\n errors.collect(cdk.propertyValidator('methodName', cdk.validateString)(properties.methodName));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));\n return errors.wrap('supplied properties not correct for \"GrpcRouteMatchProperty\"');\n}",
"function cfnGatewayRouteGatewayRouteRangeMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_GatewayRouteRangeMatchPropertyValidator(properties).assertSuccess();\n return {\n End: cdk.numberToCloudFormation(properties.end),\n Start: cdk.numberToCloudFormation(properties.start),\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to stop/delete graph | function stop()
{
//get choosen location
var locations = document.getElementById("location");
var loc = locations.options[locations.selectedIndex].value;
//go through array of already set up graphs
for(var i = 0; i < array.length; i++)
{
//check graph position
if(array[i][0]==loc)
{
//then delete it
delete array[i];
array = array.filter(function(n){ return n != undefined });
$("#" + loc).empty();
plot.destroy();
}
}
} | [
"function chartStop(chart_id) {\n // Drop the config\n clearInterval(chart_id);\n}",
"delete() {\n\t\t// Remove all edge relate to vertex\n\t\tthis.vertexMgmt.edgeMgmt.removeAllEdgeConnectToVertex(this)\n\n\t\t// Remove from DOM\n\t\td3.select(`#${this.id}`).remove()\n\t\t// Remove from data container\n\t\t_.remove(this.dataContainer.vertex, (e) => {\n\t\t\treturn e.id === this.id\n\t\t})\n\t}",
"stopGC() {\n if (this.currentParams.pointList.length > 1) {\n this.drawTurtle.CreateExtrudeShape(\"tube\" + (this.drawTurtle.graphicElems.length + 1).toString(), { shape: this.currentParams.shapeSection, path: this.currentParams.pointList, sideOrientation: BABYLON.Mesh.DOUBLESIDE, radius: 0.075 }, this.drawTurtle.materialTextures[0]);\n this.currentParams.pointList = [];\n }\n this.currentParams.generalizedCylinder = false;\n this.currentParams.customId = SHAPE_NOID;\n this.currentParams.customParentId = SHAPE_NOID;\n }",
"function restart() {\n\t\t\t\t\t\n\t\t\t\t\tlink = link.data(graph.links);\n\t\t\t\t\tlink.exit().remove();\n\t\t\t\t\tlink.enter().insert(\"line\", \".node\").attr(\"class\", \"link\");\n\t\t\t\t\tnode = node.data(graph.nodes);\n\t\t\t\t\tnode.enter().insert(\"circle\", \".cursor\").attr(\"class\", \"node\").attr(\"r\", 5).call(force.drag)\n\t\t\t\t\t.on('mouseover', tip.show) //Added\n\t\t\t\t\t.on('mouseout', tip.hide);\n\t\t\t\t\tforce.start();\n\t\t\t\t}",
"disconnect() {\n\t\t\tthis.connected = false;\n\t\t\t// Emitting event 'disconnect', 'exit' and finally 'close' to make it similar to Node's childproc & cluster\n\t\t\tthis._emitLocally('disconnect');\n\t\t}",
"removeEdge() {\n this.graph[fromNode] = true;\n this.graph[toNode] = true;\n }",
"function stopVisualization(){\n\t\twindow.cancelAnimationFrame(request_animation);\n\t\tamplitude_container.innerHTML = '';\n\t}",
"_destroy() {\n\t\tthis.workspaces_settings.disconnect(this.workspaces_names_changed);\n\t\tWM.disconnect(this._ws_number_changed);\n\t\tglobal.display.disconnect(this._restacked);\n\t\tglobal.display.disconnect(this._window_left_monitor);\n\t\tthis.ws_bar.destroy();\n\t\tsuper.destroy();\n\t}",
"_terminate() {\n console.log(\"terminate\");\n /*if (this.state !== or === ? GameStates.Terminating) {\n return; //error\n }*/\n\n this.state = GameStates.Terminating;\n clearTimeout(this.tick);\n this._clearTurn();\n this.destroy();\n }",
"removeNode(node) {\n if (this.graph[node]) {\n delete this.graph[node]\n }\n }",
"disposeChart() {\n if (this.chart) {\n this.chart.dispose();\n this.chart = null;\n logger.debug(`TimelinePlot: disposed of chart`);\n }\n }",
"destroy(callback) {\n const connections = Object.keys(this.namespace.connected);\n\n\n let self = this;\n this.print(`Disconnecting all sockets`);\n connections.forEach((socketID) => {\n this.print(`Disconnecting socket: ${socketID}`);\n self.namespace.connected[socketID].disconnect();\n });\n\n this.print(`Removing listeners`);\n this.namespace.removeAllListeners();\n callback(this.endpoint);\n }",
"stop() {\n if (!this.isStarted()) {\n throw new Error('cannot stop backend: not started yet');\n }\n this.started = false;\n this.logWriter.writeLine(`stopping backend for ${this.previewUriScheme}:// at port ${this.serverPort}`);\n this.server.stop();\n }",
"function clearChart() {\r\n\td3.select('#chartDiv').selectAll('svg').remove();\r\n}",
"onShutdown() {\n this.particleSystems.forEach( e => e.dispose() );\n this.particleSystems.clear();\n }",
"function stop() {\n testTransport.removeListener(\"close\", find);\n testTransport.close();\n }",
"deleteAllNodesWithLabel(label){\n let task = session.run(`MATCH (N:${label}) DETACH DELETE N`);\n return task;\n }",
"clearInterval() {\n if (this.handle === undefined) {\n throw new Error('The interval must be running for it to be stoppped');\n }\n cancelAnimationFrame(this.handle);\n //clearInterval(this.handle)\n this.handle = undefined;\n }",
"function stop(key) {\n data[key] = undefined;\n delete data[key];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set up common IComponentValidator script for an editor that has minimum, maximum, and current value properties. | function setupCommonRangeCheckingValidation(prototype, noun, nouns,
minProperty, maxProperty, valueProperty, converter) {
setupCommonAndMaxLengthRangeCheckingValidation(prototype, noun, nouns,
minProperty, maxProperty, valueProperty, converter, null);
} | [
"function setupCommonAndMaxLengthRangeCheckingValidation(prototype, noun, nouns,\r\n\t\tminProperty, maxProperty, valueProperty, converter, maxLengthProperty) {\r\n\r\n\tif (converter == null)\r\n\t\tconverter = function(value) { return value; };\r\n\r\n\t\t\t// note that laf will be null if a display model was not created\r\n\tprototype.validate = function(instance, laf) {\r\n\r\n\t\tvar properties = instance.properties;\r\n\t\tvar messages = new java.util.ArrayList();\r\n\r\n\t\tvar min = converter(properties[minProperty]);\r\n\t\tvar max = converter(properties[maxProperty]);\r\n\t\tvar value = converter(properties[valueProperty]);\r\n\r\n\t\tif (converter(properties[maxLengthProperty])!= null) {\r\n\t\t\tvar maxLength = converter(properties[maxLengthProperty]);\r\n\t\t\tif ( maxLength < 3 || maxLength > 32 ){\r\n\t\t\t\tmessages.add(createSimpleModelError(instance, maxLengthProperty, \r\n\t\t\t\timplLibraryStrings.getString(\"maxLengthValueError\"), \r\n\t\t\t\t[ maxLength ]));\r\n\t\t\t} else {\r\n\t\t\t\tvar textValue = value.toString();\r\n\t\t\t\tif (textValue.length > maxLength){\r\n\t\t\t\t\tmessages.add(createSimpleModelError(instance, valueProperty,\r\n\t\t\t\t\timplLibraryStrings.getString(\"maxLengthConstraint\"), \r\n\t\t\t\t\t[noun, maxLength ]));\r\n\t\t\t\t}\t\r\n\t\t\t}\r\n\t\t} \r\n\t\t\r\n\t\tif (min > max) {\r\n\t\t\tmessages.add(createSimpleModelError(instance, \r\n\t\t\t\tminProperty, \r\n\t\t\t\timplLibraryStrings.getString(\"minMaxValueError\"), \r\n\t\t\t\t[ noun, nouns, instance.name, min, max ]));\r\n\t\t} \r\n\t\tif (value < min || value > max ) {\r\n\t\t\tmessages.add(createSimpleModelError(instance, \r\n\t\t\t\tvalueProperty, \r\n\t\t\t\timplLibraryStrings.getString(\"valueRangeError\"), \r\n\t\t\t\t[ noun, nouns, instance.name, min, max, value ]));\r\n\t\t}\t\r\n\t\treturn messages;\r\n\t}\r\n\t\r\n\t\t// note that laf will be null if a display model was not created\r\n\tprototype.queryPropertyChange = function(instance, propertyPath,\r\n\t\t\t\t\tnewVal, laf) {\r\n\t\tvar properties = instance.properties;\r\n\t\tvar message = null;\r\n\r\n\t\tnewValue = converter(newVal);\r\n\t\tif (propertyPath == minProperty) {\r\n\t\t\tif (newValue > converter(properties[valueProperty]) ||\r\n\t\t\t\tnewValue >= converter(properties[maxProperty])) {\r\n\t\t\t\tmessage = formatString(implLibraryStrings.getString(\"minValueConstraint\"), noun, nouns );\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (propertyPath == valueProperty) {\r\n\t\t\tif (newValue < converter(properties[minProperty]) ||\r\n\t\t\t newValue > converter(properties[maxProperty])) {\r\n\t\t\t\tmessage = formatString(implLibraryStrings.getString(\"valueConstraint\"), noun, nouns );\r\n\t\t\t}else {\r\n\t\t\t\tif (converter(properties[maxLengthProperty])!= null){\r\n\t\t\t\t\tif (newValue.toString().length() > converter(properties[maxLengthProperty])) {\r\n\t\t\t\t\t\tmessage = formatString(implLibraryStrings.getString(\"maxLengthConstraint\"), noun );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (propertyPath == maxProperty) {\r\n\t\t\tif (newValue <= converter(properties[minProperty]) ||\r\n\t\t\t\tnewValue < converter(properties[valueProperty]))\r\n\t\t\t\tmessage = formatString(implLibraryStrings.getString(\"maxValueConstraint\"), noun, nouns );\r\n\t\t}\r\n\t\treturn message;\t\t\r\n\t}\r\n\r\n}",
"minMaxConditionsHandler() {\n if (\n (this.min || this.min === 0) &&\n (this.value < this.min || this._previousValue < this.min)\n ) {\n this._value = this.min;\n }\n if (\n this.max &&\n (this.value > this.max || this._previousValue > this.max)\n ) {\n this._value = this.max;\n }\n }",
"function initHardcodedValidators() {\n // MemverExpression.property can either be an expression or an identifier\n // This depends on the context and is not visible in NODE_FIELDS\n // So we hardcode it for now\n lpe_babel.types.NODE_FIELDS.MemberExpression.property.validate.oneOfNodeTypes = [\n \"Expression\",\n \"Identifier\"\n ];\n \n lpe_babel.types.NODE_FIELDS.ClassMethod.key.validate.oneOfNodeTypes = [\n \"Expression\",\n \"Identifier\",\n \"StringLiteral\",\n \"NumericLiteral\"\n ];\n}",
"function minMaxSet() {\n min = parseInt(minRange.value);\n max = parseInt(maxRange.value);\n}",
"function Validator(config) {\n this.config = config;\n }",
"function createInterface(diy, editor) {\n let nameField = textField();\n diy.nameField = nameField;\n\n // The bindings object links the controls in the component\n // to the setting names we have selected for them: when the\n // user changes a control, the setting is updated; when the\n // component is opened, the state of the settings is copied\n // to the controls.\n let bindings = new Bindings(editor, diy);\n\n // Background panel\n let bkgPanel = new Grid('', '[min:pref][0:pref,grow,fill][0:pref][0:pref]', '');\n bkgPanel.setTitle(@tal_content);\n bkgPanel.place(@tal_title, '', nameField, 'growx, span, wrap');\n\n let alignmentCombo = createAlignmentCombo();\n bindings.add('Alignment', alignmentCombo, [0]);\n\n let startCombo = createStartCombo();\n bindings.add('Start', startCombo, [0]);\n\n bkgPanel.place(@tal_start, '', startCombo, 'width pref+16lp, growx', @tal_alignment, 'gap unrel', alignmentCombo, 'width pref+16lp, wrap');\n\n // Character base\n let baseCombo = createBaseCombo();\n bkgPanel.place(@tal_char_base, '', baseCombo, 'width pref+16lp, wrap para');\n bindings.add('Base', baseCombo, [0]);\n\n // Statistics panel\n // Create a grid that will be centered within the panel overall,\n // and controls in each of the four columns will be centered in the column\n let statsPanel = new Grid('center, fillx, insets 0', '[center][center][center][center]');\n statsPanel.place(\n noteLabel(@tal_strength), 'gap unrel', noteLabel(@tal_craft), 'gap unrel',\n noteLabel(@tal_life), 'gap unrel', noteLabel(@tal_fate), 'gap unrel, wrap 1px'\n );\n // the $Settings to store the stats in\n let statSettings = ['Strength', 'Craft', 'Life', 'Fate'];\n // the range of possible values for each stat\n let statItems = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '-'];\n for (let i = 0; i < 4; ++i) {\n let combo = comboBox(statItems);\n statsPanel.place(combo, 'growx, width pref+16lp, gap unrel' + (i == 3 ? ', wrap' : ''));\n bindings.add(statSettings[i], combo, [0]);\n }\n // add the --- Stats --- divider and panel\n bkgPanel.place(separator(), 'span, split 3, growx', @tal_stats, 'span, split 2', separator(), 'growx, wrap rel');\n bkgPanel.place(statsPanel, 'span, growx, wrap rel');\n bkgPanel.place(separator(), 'span, growx, wrap para');\n\n // Special Abilities\n let specialTextField = textArea('', 17, 15, true);\n bkgPanel.place(@tal_abilities, 'span, wrap');\n bkgPanel.place(specialTextField, 'span, gap para, growx, wrap');\n bindings.add('SpecialText', specialTextField, [0]);\n\n bkgPanel.addToEditor(editor, @tal_content, null, null, 0);\n bindings.bind();\n\n // Set up custom clip stencil for the portrait panels:\n // The portrait clip stencil is what defines the shape\n // of the portrait area in the portrait panel. It is an\n // image the same size as the portrait's clip region,\n // and the opacity (alpha) of its pixels determines where\n // in the clip region the portrait shows through and where\n // it is covered by other content. The default system \n // assumes that the card template has a hole in it for\n // the portrait, and that you draw the portrait and then\n // draw the template over it. If you do something different\n // then you may need to customize the clip stencil. In this\n // case, we are using the portrait clip stencil to define\n // the ideal size for portraits, but we allow the portrait\n // to escape from this area (i.e. portrait clipping is\n // disabled). In addition, the portraits are transparent\n // so the card background shows through them. To account for\n // this we need to do two things:\n //\n // 1. Change the size of the clip stencil region. By default,\n // this is the same as the portrait clip region. Since we\n // don't clip to that region, we need to set the clip stencil\n // region to the area that we *do* clip to. Otherwise, the\n // area where the portrait shows through in the portrait panel\n // will be the wrong size.\n // 2. In the case of the main portrait, we need to use a different\n // clip stencil. The default clip stencil is created by taking\n // the portion of the template image that fits within the\n // portrait clip region (or the custom clip stencil region if\n // we set one). In our case, the template image does not have\n // a transparent area where the portrait is, because the portrait\n // gets drawn overtop of it. Instead, we need to use the\n // 'front overlay' image, which does have a hole for the portrait\n // and which gets stamped overtop of the portrait so that the\n // portrait can't cover up certain decorations.\n //\n // There is a function defined in the Talisman named object for\n // customizing a component's portraits, and we call that below.\n // However, the function is a bit hard to follow because it handles\n // multiple cases, so I have also included a straightforward translation\n // for each call just below that line\n //\n\n // customize the main portrait stencil to use the front overlay and true clip\n Talisman.customizePortraitStencil(diy, ImageUtils.get($char_front_overlay), R('portrait-true-clip'));\n /*\n // Equivalent code:\n let stencil = ImageUtils.get( $char_front_overlay );\n let region = R('portrait-true-clip');\n stencil = AbstractPortrait.createStencil( stencil, region );\n diy.setPortraitClipStencil( stencil );\n diy.setPortraitClipStencilRegion( region );\n */\n\n // customize the marker portrait to use the true clip\n // (see also the paintMarker function, below)\n Talisman.customizePortraitStencil(diy, null, R('marker-true-clip'), true);\n\n /*\n // Equivalent code:\n diy.setMarkerClipStencilRegion( R('marker-true-clip') );\n */\n}",
"function geneBaseBounds(gn, min, max) {\n var gd = genedefs[gn];\n var gg = guigenes[gn];\n if (gd === undefined) return;\n if (gd.basemin === gd.min) {\n gd.min = min;\n gg.minEle.value = min;\n gg.sliderEle.min = min;\n }\n gd.basemin = min;\n if (gd.basemax === gd.max) {\n gd.max = max;\n gg.maxEle.value = max;\n gg.sliderEle.max = max;\n }\n gd.basemax = max;\n\n gg.deltaEle.value = gd.delta;\n gg.stepEle.value = gd.step;\n}",
"function setSliderMinMaxDates(range) {\n $scope.layoutEndTimeMS = range.max;\n $scope.layoutStartTimeMS = range.min;\n $scope.currentDate = range.min;\n $scope.layoutCurTimeMS = range.min;\n }",
"SetCompatibleWithEditor() {}",
"function _initEditor() {\n\n var modules;\n\n if(cl.editorType === cl.EditorType.GameEditor) {\n modules = [\n \"cocos2d-js/frameworks/cocos2d-html5/CCBoot\",\n \n \"hack/hackBrackets\",\n \"hack/hackCocos\",\n\n \"core/ObjectManager\",\n \"core/Hierarchy\",\n \"core/Inspector\",\n \"core/Undo\",\n \"core/ComponentManager\",\n \"core/Selector\",\n \"core/Project\",\n \"core/MenusManager\",\n \"core/GameEditor\",\n \"core/CopyManager\",\n \n \"thirdparty/vue\",\n \"thirdparty/colorpicker/js/bootstrap-colorpicker\",\n \"thirdparty/webui-popover/jquery.webui-popover\",\n \"thirdparty/jquery-ui\",\n\n \"editor/EditorManager\",\n \"editor/SceneEditor\",\n \"editor/MeshEditor\",\n \"editor/Control2D\",\n \"editor/Simulator\",\n \"editor/PhysicsEditor\",\n \"editor/CanvasControl\"];\n\n _initNodeDomain();\n }\n else if(cl.editorType === cl.EditorType.IDE) {\n modules = [\"ide/ide\",\n \"ide/ChromeConnect\"];\n }\n\n modules.push(\"common\");\n\n require(modules);\n }",
"function validateRange(field, min, max) {\r\n var value=document.getElementById(field).value\r\n if (value=='' || (!isNaN(value) && value >= min && value <= max))\r\n return\r\n var elementId='validateRange_'+field\r\n if (document.getElementById(elementId)) {\r\n var focusField='#'+field\r\n $('#'+elementId).keydown(function(event) {\r\n if(event.keyCode == 13) { // prevent ENTER from closing modal\r\n event.preventDefault()\r\n return false\r\n }\r\n }) // %V substitution\r\n var message=$('#modal-body_'+field).text()\r\n message=message.replace('%V',value)\r\n $('#modal-body_'+field).text(message)\r\n $('#'+elementId).modal()\r\n $('#'+elementId).on('hidden.bs.modal', function () {\r\n // wait for modal to terminate...\r\n $(focusField).focus() // ...and then set focus to field...\r\n $('#'+elementId).off() // ...and then remove all handlers.\r\n message=message.replace(value,'%V')\r\n $('#modal-body_'+field).text(message)\r\n }) // on error, clear field value\r\n document.getElementById(field).value=''\r\n CURR_VALUE=''\r\n }\r\n else {\r\n alert(\"INVALID RANGE DETECTED. PLEASE RE-ENTER.\\n\\nMODAL NOT FOUND.\")\r\n }\r\n return false\r\n}",
"function SelectConditionEditor(args) {\n var $select;\n var defaultValue;\n var scope = this;\n var current_cond_text = args.item.CONDITION;\n var current_cond_id = args.item.CONDITION_ID;\n var current_group_id = args.item.GROUPID;\n this.init = function () {\n if (0 == current_cond_id) {\n option_str = '<option selected=\"selected\" value=0> ' + i18n.rlimport.NONE + '</option>';\n }\n else {\n option_str = '<option value=0> ' + i18n.rlimport.NONE + '</option>';\n }\n var condition_height = 30;\n \n for (var cidx = 0, len = pageCriteria.CRITERION.DEF.length; cidx < len; cidx++) {\n // for (var cidx = 0; cidx < pageCriteria.CRITERION.DEF.length; cidx++) {\n if (pageCriteria.CRITERION.DEF[cidx].DEF_TYPE == 2) {\n condition_height += 26;\n if (pageCriteria.CRITERION.DEF[cidx].DEF_ID == current_cond_id) {\n option_str += '<option selected=\"selected\" value=\"' + pageCriteria.CRITERION.DEF[cidx].DEF_ID + '\">' + pageCriteria.CRITERION.DEF[cidx].DEF_DISP + '</option>';\n }\n else {\n option_str += '<option value=\"' + pageCriteria.CRITERION.DEF[cidx].DEF_ID + '\">' + pageCriteria.CRITERION.DEF[cidx].DEF_DISP + '</option>';\n }\n }\n }\n if (condition_height > 180) { condition_height = 180; }\n $select = $('<SELECT tabIndex=\"0\" id=\"conditiongrid\" multiple=\"multiple\">' + option_str + \"</SELECT>\");\n $select.appendTo(args.container);\n var parentWidth = $(\"#conditiongrid\").parents('.slick-cell').width()\n $(\"#conditiongrid\").css(\"width\", parentWidth)\n $(\"#conditiongrid\").multiselect({\n height: condition_height,\n header: false,\n multiple: false,\n minWidth: \"50\",\n classes: \"mp_dcp_import_select_box_grid\",\n noneSelectedText: \"\",\n selectedList: 1,\n position: {\n my: \"top\",\n at: \"bottom\",\n collision: \"flip\"\n }\n });\n $(\"#conditiongrid\").on(\"multiselectclick\", function (event, ui) {\n scope.loadValue(args.item)\n scope.applyValue(args.item, ui.value)\n });\n if (args.item.IGNORE_IND != 0) {\n //$select.attr(\"disabled\",\"disabled\")\n $(\"#conditiongrid\").multiselect(\"disable\")\n }\n else {\n $(\"#conditiongrid\").multiselect(\"open\")\n }\n };\n this.destroy = function () {\n $select.remove();\n };\n this.focus = function () {\n $select.focus();\n };\n this.loadValue = function (item) {\n $select.val(defaultValue = item[args.column.field]);\n };\n this.serializeValue = function () {\n return ($select.val());\n };\n this.applyValue = function (item, state) {\n //Check to see if the value selected was none, not an actual condition loaded in the criterion object\n if (state != null) {\n if (state == 0) {\n item[args.column.field] = \"NONE\";\n //item[args.column.field] = newConditiondisp.DEF_DISP;\n }\n else {\n //look up the corresponding condition display for the selected condition ID to correctly populate the condition display\n var newConditiondisp = findInObject(pageCriteria.CRITERION.DEF, { DEF_ID: state }, true);\n item[args.column.field] = newConditiondisp.DEF_DISP;\n }\n //update the CONDITION_ID in the array to the newly selected condition_id\n var rowRemoved = 0;\n if (args.item[\"MATCH_PERSON_ID\"] > 0) {\n args.item[\"GROUPID\"] = 0;\n var PersonMatchObjs = findInObject(displayData, { MATCH_PERSON_ID: args.item[\"MATCH_PERSON_ID\"] }, false);\n if (PersonMatchObjs.length > 0) {\n var DuplicateObj = findInObject(PersonMatchObjs, { CONDITION_ID: parseFloat(state) }, false);\n if (DuplicateObj.length > 0) {\n dataView.deleteItem(item.id);\n rowRemoved = 1;\n if (current_group_id == 0) {\n mp_import_success_data_cnt -= 1;\n $('#mp-dcp-import-success-cnt').text(mp_import_success_data_cnt);\n } else {\n mp_import_dirty_data_cnt -= 1;\n $('#mp-dcp-import-failure-cnt').text(mp_import_dirty_data_cnt);\n }\n mp_import_patient_cnt -= 1\n $('#mp-dcp-import-patient-cnt').text(mp_import_patient_cnt);\n grid.invalidate();\n }\n else {\n if (current_cond_id < 0) {\n mp_import_success_data_cnt += 1;\n $('#mp-dcp-import-success-cnt').text(mp_import_success_data_cnt);\n mp_import_dirty_data_cnt -= 1;\n $('#mp-dcp-import-failure-cnt').text(mp_import_dirty_data_cnt);\n }\n args.item[\"CONDITION_ID\"] = parseFloat(state);\n }\n }\n else {\n if (current_cond_id < 0) {\n mp_import_success_data_cnt += 1;\n $('#mp-dcp-import-success-cnt').text(mp_import_success_data_cnt);\n mp_import_dirty_data_cnt -= 1;\n $('#mp-dcp-import-failure-cnt').text(mp_import_dirty_data_cnt);\n }\n args.item[\"CONDITION_ID\"] = parseFloat(state);\n }\n\n if (set_Organization != 0 && mp_dcp_import_set_registry != 0 && mp_import_dirty_data_cnt == 0) {\n $('#mp_dcp_import_status_commit_button button').removeAttr(\"disabled\")\n }\n }\n else {\n args.item[\"CONDITION_ID\"] = parseFloat(state);\n }\n if (rowRemoved == 0) {\n dataView.updateItem(item.id, item);\n grid.render();\n }\n grid.navigateNext();\n }\n };\n this.isValueChanged = function () {\n return ($select.val() != defaultValue);\n };\n this.validate = function () {\n return {\n valid: true,\n msg: null\n };\n };\n this.init();\n }",
"function initialSliderValues() {\n\t// set initial values for config\n\tupdateSliderValue('cannyConfigThreshold1Slider',\n\t\t\t'cannyConfigThreshold1Textbox');\n\tupdateSliderValue('cannyConfigThreshold2Slider',\n\t\t\t'cannyConfigThreshold2Textbox');\n\tupdateSliderValue('houghConfigRhoSlider', 'houghConfigRhoTextbox');\n\tupdateSliderValue('houghConfigThetaSlider', 'houghConfigThetaTextbox');\n\tupdateSliderValue('houghConfigThresholdSlider',\n\t\t\t'houghConfigThresholdTextbox');\n\tupdateSliderValue('houghConfigMinLineLengthSlider',\n\t\t\t'houghConfigMinLineLengthTextbox');\n\tupdateSliderValue('houghConfigMaxLineGapSlider',\n\t\t\t'houghConfigMaxLineGapTextbox');\n\tupdateSliderValue('houghConfigMaxLineGapSlider',\n\t\t\t'houghConfigMaxLineGapTextbox');\n\n\t// set initial values for cam config\n\tupdateSliderValue('camEcSlider', 'camEcTextbox');\n\tupdateSliderValue('camBrSlider', 'camBrTextbox');\n\tupdateSliderValue('camSaSlider', 'camSaTextbox');\n}",
"function PresentationValidationUtility() {}",
"function enable_image_compare() {\n const image_compares = document.querySelectorAll(\"div.image-compare\");\n for (const img_cmp of image_compares) {\n // insert the input only when js is running\n let style = window.getComputedStyle(img_cmp);\n const slider = document.createElement('input');\n slider.type = \"range\";\n slider.min = style.getPropertyValue('--slider-min').replace('%', '');\n slider.max = style.getPropertyValue('--slider-max').replace('%', '');\n slider.value = style.getPropertyValue('--slider-value').replace('%', '');\n img_cmp.appendChild(slider);\n // setup callback\n slider.addEventListener(\"input\", (event) => {\n img_cmp.style.setProperty('--slider-value', clamp(slider.value, slider.min, slider.max) + \"%\");\n });\n }\n}",
"function initValues() {\n\tNAME.value = \"\";\n\t\n\t// FROM\n\tACTION.value = \"\";\n\tTARGET.setIndex(0);\n\tMETHOD.setIndex(0);\n\tENCTYPE.setIndex(0);\n\n\tFORMAT.pickValue('');\n\tSTYLE.value = '';\n\tSKIN.pickValue('');\n\tPRESERVEDATA.pickValue('');\n\tSCRIPTSRC.value = '';\n\tARCHIVE.value = ''\n\tHEIGHT.value = '';\n\tWIDTH.value = '';\n}",
"function createSlider() {\n\n //the value that we'll give the slider - if it's a range, we store our value as a comma separated val but this slider expects an array\n var sliderVal = null;\n\n //configure the model value based on if range is enabled or not\n if ($scope.model.config.enableRange == true) {\n //If no value saved yet - then use default value\n //If it contains a single value - then also create a new array value\n if (!$scope.model.value || $scope.model.value.indexOf(\",\") == -1) {\n var i1 = parseFloat($scope.model.config.initVal1);\n var i2 = parseFloat($scope.model.config.initVal2);\n sliderVal = [\n isNaN(i1) ? $scope.model.config.minVal : (i1 >= $scope.model.config.minVal ? i1 : $scope.model.config.minVal),\n isNaN(i2) ? $scope.model.config.maxVal : (i2 > i1 ? (i2 <= $scope.model.config.maxVal ? i2 : $scope.model.config.maxVal) : $scope.model.config.maxVal)\n ];\n }\n else {\n //this will mean it's a delimited value stored in the db, convert it to an array\n sliderVal = _.map($scope.model.value.split(','), function (item) {\n return parseFloat(item);\n });\n }\n }\n else {\n //If no value saved yet - then use default value\n if ($scope.model.value) {\n sliderVal = parseFloat($scope.model.value);\n }\n else {\n sliderVal = $scope.model.config.initVal1;\n }\n }\n\n // Initialise model value if not set\n if (!$scope.model.value) {\n setModelValueFromSlider(sliderVal);\n }\n\n //initiate slider, add event handler and get the instance reference (stored in data)\n var slider = $element.find('.slider-item').bootstrapSlider({\n max: $scope.model.config.maxVal,\n min: $scope.model.config.minVal,\n orientation: $scope.model.config.orientation,\n selection: $scope.model.config.reversed ? \"after\" : \"before\",\n step: $scope.model.config.step,\n precision: $scope.model.config.precision,\n tooltip: $scope.model.config.tooltip,\n tooltip_split: $scope.model.config.tooltipSplit,\n tooltip_position: $scope.model.config.tooltipPosition,\n handle: $scope.model.config.handle,\n reversed: $scope.model.config.reversed,\n ticks: $scope.model.config.ticks,\n ticks_positions: $scope.model.config.ticksPositions,\n ticks_labels: $scope.model.config.ticksLabels,\n ticks_snap_bounds: $scope.model.config.ticksSnapBounds,\n formatter: $scope.model.config.formatter,\n range: $scope.model.config.enableRange,\n //set the slider val - we cannot do this with data- attributes when using ranges\n value: sliderVal\n }).on('slideStop', function (e) {\n var value = e.value;\n angularHelper.safeApply($scope, function () {\n setModelValueFromSlider(value);\n });\n }).data('slider');\n }",
"function minEleonchange(evt) {\n var uig = getg(this);\n uig.sliderEle.min = this.value*1;\n genedefs[uig.name].min = this.value*1;\n}",
"function getDateComponent()\n{\n function DateComp() {}\n\n //\n // [ICellEditorComp]: init?(params: ICellEditorParams): void\n // Gets called once after the editor is created\n //\n DateComp.prototype.init = function(params)\n {\n // Cache the editor parameters\n this.editorParams = params;\n\n // Set up the date control and set this up as the editor's root\n this.dateControl = getDateControl();\n this.root = this.dateControl.root;\n };\n\n //\n // [ICellEditorComp]: afterGuiAttached?(): void\n // Gets called once after GUI is attached to DOM.\n //\n // Focuses on the date input so that editing can be done.\n // To be consistent with other ag-grid editors, if editing was launched by\n // pressing Enter, the existing date should be selected.\n //\n DateComp.prototype.afterGuiAttached = function()\n {\n this.dateControl.dateInput.focus();\n\n if (this.editorParams.keyPress == NPC_CR)\n {\n this.dateControl.dateInput.select();\n }\n };\n\n //\n // [ICellEditorComp]: getGui(): HTMLElement\n // Returns the DOM element of the editor: what the grid puts into the DOM\n //\n DateComp.prototype.getGui = function()\n {\n return this.root;\n };\n\n //\n // [ICellEditorComp]: getValue(): any\n // Returns the final value to the grid, the result of editing\n //\n DateComp.prototype.getValue = function()\n {\n return this.dateControl.getDate();\n }\n\n //\n // [ICellEditorComp]: destroy?(): void\n // Gets called once by grid after editing is finished;\n // any cleanup should be done here\n //\n DateComp.prototype.destroy = function()\n {\n // Nothing to do\n };\n\n //\n // [ICellEditorComp]: isPopup?(): boolean;\n // Gets called once after initialised.\n // If you return true, the editor will appear in a popup\n //\n // Using a popup ensures the entire editor is visible during editing\n //\n DateComp.prototype.isPopup = function()\n {\n return true;\n }\n\n //\n // [ICellEditorComp]: getPopupPosition?(): string;\n // Gets called once, only if isPopup() returns true.\n // Return \"over\" (default) if the popup should cover the cell, or\n // \"under\" if it should be positioned below leaving the cell value visible.\n //\n DateComp.prototype.getPopupPosition = function()\n {\n return \"under\";\n }\n\n //\n // [ICellEditorComp]: isCancelBeforeStart?(): boolean;\n // Gets called once before editing starts, to give editor a chance to\n // cancel the editing before it even starts.\n //\n // Abort editing if a non-numerical character was entered.\n // Otherwise initialise the date appropriately.\n //\n DateComp.prototype.isCancelBeforeStart = function()\n {\n let initialDate = this.editorParams.formatValue(this.editorParams.value);\n let initialCharString = this.editorParams.charPress;\n if (initialCharString)\n {\n if (isNaN(initialCharString))\n {\n return true;\n }\n else\n {\n initialDate = initialCharString;\n }\n }\n\n this.dateControl.setDate(initialDate);\n return false;\n }\n\n //\n // [ICellEditorComp]: isCancelAfterEnd?(): boolean;\n // Gets called once when editing is finished (e.g. if enter is pressed).\n // If you return true, then the result of the edit will be ignored.\n //\n // Cancel the edit if the string entered isn't a date string.\n //\n DateComp.prototype.isCancelAfterEnd = function()\n {\n return (!isDateString(this.dateControl.getDate()));\n }\n\n //\n // Other ICellEditorComp optional methods (not implemented)\n //\n // focusIn?(): boolean;\n // If doing full row edit, then gets called when tabbing into the cell.\n //\n // focusOut?(): boolean;\n // If doing full row edit, then gets called when tabbing out of the cell.\n //\n\n return DateComp;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
works even when old_elt is the only elt in its parent. | function insert_elt_after(new_elt, old_elt){
old_elt.parentNode.insertBefore(new_elt, old_elt.nextSibling);
} | [
"function diffComponent (path, entityId, prev, next, el) {\n if (next.type !== prev.type) {\n return replaceElement(entityId, path, el, next)\n } else {\n var targetId = children[entityId][path]\n\n // This is a hack for now\n if (targetId) {\n updateEntityProps(targetId, assign({ children: next.children }, next.attributes))\n }\n\n return el\n }\n }",
"function rebuildPersonItem(elem, parent) {\n var text = elem.childNodes[0];\n elem.innerHTML = \"\";\n var droppedPosition = new TablePosition(parent.parentElement.cellIndex, parent.parentElement.parentElement.rowIndex);\n\n //TODO - Add placeholder while data is loading\n $.get(\"/tree/rebuild?data=\" + text.data + \"&id=\" + elem.id + \"&position=\" + JSON.stringify(droppedPosition), function (response) {\n if (response.statusCode !== 200) {\n return;\n }\n\n elem.innerHTML = response.content.item;\n\n var list = document.querySelector(\".table\");\n var draggableList = new DraggableList(list, elem);\n\n draggableList.onDraggingItemMouseEnter = function (item) {\n addClass(item.element, \"ghost-over\");\n };\n\n draggableList.onDraggingItemMouseLeave = function (item) {\n removeClass(item.element, \"ghost-over\");\n };\n\n draggableList.onItemConnected = function (item, dot) {\n detectConnections(item, dot);\n };\n\n parent.appendChild(elem);\n });\n}",
"_compareAndCopy(newJst, topNode, jstComponent, forceUpdate, level) {\n let oldIndex = 0;\n let newIndex = 0;\n let itemsToDelete = [];\n let indicesToRemove = [];\n\n // console.log(\"CAC>\" + \" \".repeat(level*2), this.tag + this.id, newJst.tag+newJst.id);\n\n // Check to see if this the old and new node are the same\n if (this.id == newJst.id) {\n return false;\n }\n\n // First check the attributes, props and events\n // But only if we aren't the topNode\n if (!topNode) {\n if (forceUpdate || this.opts.forceUpdate || this.tag !== newJst.tag) {\n return true;\n }\n\n // Blindly copy the JST options\n this.opts = newJst.opts;\n \n // Just fix all the attributes inline\n for (let attrName of Object.keys(this.attrs)) {\n if (!newJst.attrs[attrName]) {\n delete this.attrs[attrName];\n if (this.isDomified) {\n this.el.removeAttribute(attrName);\n }\n }\n else if (newJst.attrs[attrName] !== this.attrs[attrName]) {\n this.attrs[attrName] = newJst.attrs[attrName];\n if (this.isDomified) {\n //refactor\n let val = newJst.attrs[attrName];\n if (this.jstComponent && (attrName === \"class\" || attrName === \"id\") &&\n val.match(/(^|\\s)-/)) {\n // Add scoping for IDs and Class names\n val = val.replace(/(^|\\s)(--?)/g,\n (m, p1, p2) => p1 + (p2 === \"-\" ?\n this.jstComponent.getClassPrefix() :\n this.jstComponent.getFullPrefix()));\n }\n this.el.setAttribute(attrName, val);\n }\n }\n }\n for (let attrName of Object.keys(newJst.attrs)) {\n if (!this.attrs[attrName]) {\n this.attrs[attrName] = newJst.attrs[attrName];\n if (this.isDomified) {\n //refactor\n let val = newJst.attrs[attrName];\n if (this.jstComponent && (attrName === \"class\" || attrName === \"id\") &&\n val.match(/(^|\\s)-/)) {\n // Add scoping for IDs and Class names\n val = val.replace(/(^|\\s)(--?)/g,\n (m, p1, p2) => p1 + (p2 === \"-\" ?\n this.jstComponent.getClassPrefix() :\n this.jstComponent.getFullPrefix()));\n }\n this.el.setAttribute(attrName, val);\n }\n }\n }\n\n if (this.props.length || newJst.props.length) {\n let fixProps = false;\n \n // Just compare them in order - if they happen to be the same,\n // but in a different order, we will do a bit more work than necessary\n // but it should be very unlikely that that would happen\n if (this.props.length != newJst.props.length) {\n fixProps = true;\n }\n else {\n for (let i = 0; i < this.props.length; i++) {\n if (this.props[i] !== newJst.props[i]) {\n fixProps = true;\n break;\n }\n }\n }\n \n if (fixProps) {\n if (this.isDomified) {\n for (let prop of this.props) {\n delete this.el[prop];\n }\n for (let prop of newJst.props) {\n this.el[prop] = true;\n }\n }\n this.props = newJst.props;\n }\n }\n \n // Fix all the events\n for (let eventName of Object.keys(this.events)) {\n if (!newJst.events[eventName]) {\n if (this.isDomified) {\n this.el.removeEventListener(eventName, this.events[eventName].listener);\n }\n delete this.events[eventName];\n }\n else if (newJst.events[eventName].listener !== this.events[eventName].listener) {\n if (this.isDomified) {\n this.el.removeEventListener(eventName, this.events[eventName].listener);\n this.el.addEventListener(eventName, newJst.events[eventName].listener);\n }\n this.events[eventName] = newJst.events[eventName];\n }\n }\n for (let eventName of Object.keys(newJst.events)) {\n if (!this.events[eventName]) {\n this.events[eventName] = newJst.events[eventName];\n if (this.isDomified) {\n this.el.addEventListener(eventName, newJst.events[eventName].listener);\n }\n }\n }\n \n }\n\n if (!forceUpdate && !this.opts.forceUpdate) {\n // First a shortcut in the case where all\n // contents are removed\n\n // TODO - can clear the DOM in one action, but\n // need to take care of the components so that they\n // aren't still thinking they are in the DOM\n // if (this.contents.length && !newJst.contents.length) {\n // if (this.el) {\n // this.el.textContent = \"\";\n // //this.contents = [];\n // //return false;\n // }\n // }\n \n \n // Loop through the contents of this element and compare\n // to the contents of the newly created element\n while (true) {\n let oldItem = this.contents[oldIndex];\n let newItem = newJst.contents[newIndex];\n\n if (!oldItem || !newItem) {\n break;\n }\n\n // Types of items in the contents must match or don't continue\n if (oldItem.type !== newItem.type) {\n break;\n }\n\n if (oldItem.type === JstElementType.JST_ELEMENT) {\n\n // This detects items that are being replaced by pre-existing items\n // They are too complicated to try to do in place replacements\n if (oldItem.value.id !== newItem.value.id && newItem.value._refCount > 1) {\n break;\n }\n \n // Descend into the JstElement and compare them and possibly copy their\n // content in place\n let doReplace = oldItem.value._compareAndCopy(newItem.value, false,\n jstComponent, undefined, level+1);\n if (doReplace) {\n break;\n }\n\n // Need to decrement the ref counts for items that didn't change\n if (oldItem.value.id === newItem.value.id) {\n this._deleteItem(newItem);\n }\n \n }\n else if (oldItem.type === JstElementType.JST_COMPONENT) {\n // If the tags are the same, then we must descend and compare\n if (oldItem.value._jstId !== newItem.value._jstId) {\n\n // Small optimization since often a list is modified with a\n // single add or remove\n\n let nextOldItem = this.contents[oldIndex+1];\n let nextNewItem = newJst.contents[newIndex+1];\n\n if (!nextOldItem || !nextNewItem) {\n // no value of optimizing when we are at the end of the list\n break;\n }\n\n if (nextNewItem.type === JstElementType.JST_COMPONENT &&\n oldItem.value._jstId === nextNewItem.value._jstId) {\n // We have added a single item - TBD\n let nextEl = oldItem.value._jstEl._getFirstEl();\n this._moveOrRenderInDom(newItem, jstComponent, nextEl);\n this.contents.splice(oldIndex, 0, newItem);\n newIndex++;\n oldIndex++;\n newItem = nextNewItem;\n }\n else if (nextOldItem.type === JstElementType.JST_COMPONENT &&\n nextOldItem.value._jstId === newItem.value._jstId) {\n // We have deleted a single item\n this.contents.splice(oldIndex, 1);\n itemsToDelete.push(oldItem);\n }\n else if (nextOldItem.type === JstElementType.JST_COMPONENT &&\n nextNewItem.type === JstElementType.JST_COMPONENT &&\n nextOldItem.value._jstId === nextNewItem.value._jstId) {\n // We have swapped in an item\n let nextEl = nextOldItem.value._jstEl._getFirstEl();\n this._moveOrRenderInDom(newItem, jstComponent, nextEl);\n this.contents[oldIndex] = newItem;\n oldIndex++;\n newIndex++;\n newItem = nextNewItem;\n itemsToDelete.push(oldItem);\n }\n else {\n break;\n }\n\n }\n\n // Don't bother descending into JstComponents - they take care of themselves\n \n }\n else if (oldItem.type === JstElementType.TEXTNODE) {\n\n if (oldItem.value !== newItem.value) {\n\n // For textnodes, we just fix them inline\n if (oldItem.el) {\n oldItem.el.textContent = newItem.value;\n }\n oldItem.value = newItem.value;\n }\n }\n\n oldIndex++;\n newIndex++;\n \n if (newItem.type === JstElementType.JST_COMPONENT) {\n // Unhook this reference\n newItem.value._unrender();\n }\n }\n }\n\n // Need to copy stuff - first delete all the old contents\n let oldStartIndex = oldIndex;\n let oldItem = this.contents[oldIndex];\n\n while (oldItem) {\n // console.log(\"CAC> \" + \" \".repeat(level*2), \"deleting old item :\", oldItem.value.tag, oldItem.value.id);\n itemsToDelete.push(oldItem);\n oldIndex++;\n oldItem = this.contents[oldIndex];\n }\n\n // Remove unneeded items from the contents list\n this.contents.splice(oldStartIndex, oldIndex - oldStartIndex);\n\n if (newJst.contents[newIndex]) {\n\n // Get list of new items that will be inserted\n let newItems = newJst.contents.splice(newIndex, newJst.contents.length - newIndex);\n\n //console.log(\"CAC> \" + \" \".repeat(level*2), \"new items being added:\", newItems);\n \n newItems.forEach(item => {\n if (item.type === JstElementType.JST_ELEMENT) {\n if (item.value.el && item.value.el.parentNode) {\n item.value.el.parentNode.removeChild(item.value.el);\n if (this.el) {\n this.el.appendChild(item.value.el);\n }\n else {\n delete(this.el);\n }\n }\n else if (this.el) {\n // Need to add it\n this.el.appendChild(item.value.dom(jstComponent));\n }\n else if (jstComponent && jstComponent.parentEl) {\n jstComponent.parentEl.appendChild(item.value.dom(jstComponent));\n }\n else {\n console.warn(\"Not adding an element to the DOM\", item.value.tag, item, this, jstComponent);\n }\n }\n else if (item.type === JstElementType.TEXTNODE) {\n if (this.el) {\n // Need to add it\n if (item.el) {\n if (item.el.parentNode) {\n item.el.parentNode.removeChild(item.el);\n }\n this.el.appendChild(item.el);\n }\n else {\n item.el = document.createTextNode(item.value);\n this.el.appendChild(item.el);\n }\n }\n else if (jstComponent && jstComponent.parentEl) {\n item.el = document.createTextNode(item.value);\n jstComponent.parentEl.appendChild(item.el);\n }\n else {\n console.warn(\"Not adding an element to the DOM\", item.value.tag, item, this, jstComponent);\n }\n }\n else if (item.type === JstElementType.JST_COMPONENT) {\n this._moveOrRenderInDom(item, jstComponent);\n }\n });\n this.contents.splice(oldStartIndex, 0, ...newItems);\n }\n\n for (let itemToDelete of itemsToDelete) {\n this._deleteItem(itemToDelete); \n } \n \n // console.log(\"CAC>\" + \" \".repeat(level*2), \"/\" + this.tag+this.id);\n return false;\n \n }",
"function makeCurrent(elt)\n{\n /* assert(elt) */\n if (curslide != elt) {\n hideSlide();\n curslide = elt;\n displaySlide();\n }\n}",
"changeIndexTo(element, indexOrDelta, relative) {\n if (element.parent != this) return ;\n\n var newIndex = indexOrDelta;\n if (relative || false) {\n newIndex = index + indexOrDelta;\n }\n\n if (newIndex < 0)\n newIndex = 0;\n if (newIndex >= this._children.length)\n newIndex = this._children.length - 1;\n\n var index = this._children.indexOf(element);\n if (newIndex == index) {\n return ;\n }\n var event = new events.ElementIndexChanged(element, index, newIndex);\n if (this.validateBefore(event.name, event) != false &&\n element.validateBefore(event.name, event) != false) {\n this._children.splice(index, 1);\n this._children.splice(newIndex, 0, element);\n this.triggerOn(event.name, event);\n element.triggerOn(event.name, event);\n }\n }",
"function resolveDuplicatedEntityReferenceProperties(oldSubtreeRoot, oldEntity, newEntity, duplicatedIdsMap) {\n var i, len;\n\n if (oldEntity instanceof Entity) {\n var components = oldEntity.c;\n\n // Handle component properties\n for (var componentName in components) {\n var component = components[componentName];\n var entityProperties = component.system.getPropertiesOfType('entity');\n\n for (i = 0, len = entityProperties.length; i < len; i++) {\n var propertyDescriptor = entityProperties[i];\n var propertyName = propertyDescriptor.name;\n var oldEntityReferenceId = component[propertyName];\n var entityIsWithinOldSubtree = !!oldSubtreeRoot.findByGuid(oldEntityReferenceId);\n\n if (entityIsWithinOldSubtree) {\n var newEntityReferenceId = duplicatedIdsMap[oldEntityReferenceId].getGuid();\n\n if (newEntityReferenceId) {\n newEntity.c[componentName][propertyName] = newEntityReferenceId;\n } else {\n console.warn('Could not find corresponding entity id when resolving duplicated entity references');\n }\n }\n }\n }\n\n // Handle entity script attributes\n if (components.script && ! newEntity._app.useLegacyScriptAttributeCloning) {\n newEntity.script.resolveDuplicatedEntityReferenceProperties(components.script, duplicatedIdsMap);\n }\n\n // Recurse into children. Note that we continue to pass in the same `oldSubtreeRoot`,\n // in order to correctly handle cases where a child has an entity reference\n // field that points to a parent or other ancestor that is still within the\n // duplicated subtree.\n var _old = oldEntity.children.filter(function (e) {\n return (e instanceof Entity);\n });\n var _new = newEntity.children.filter(function (e) {\n return (e instanceof Entity);\n });\n\n for (i = 0, len = _old.length; i < len; i++) {\n resolveDuplicatedEntityReferenceProperties(oldSubtreeRoot, _old[i], _new[i], duplicatedIdsMap);\n }\n }\n}",
"previous() {\n let tmp = this.currentNode.previous();\n if (!tmp.done) {\n this.currentNode = tmp.value;\n this.currentNode.clearChildren();\n //this.currentNode.children.forEach((child) => child.clearChildren());\n console.log(\" ================ PREV ================ \");\n this.ptree();\n }\n return tmp;\n }",
"function extUtils_setEditableToParent(node)\n{\n if (typeof node == \"object\" && node.nodeType == Node.ELEMENT_NODE &&\n node.tagName == \"MMTINSTANCE:EDITABLE\")\n {\n\t return node.parentNode;\n }\n return node;\n\n}",
"function previousElement(element)\r\n{\r\n\twhile (element = element.previousSibling)\r\n\t{\r\n\t\tif (element.nodeType == 1) return element;\r\n\t}\r\n\treturn null;\r\n}",
"set parent (parent) {\n const oldParent = this[_parent]\n\n // link nodes can't contain children directly.\n // children go under the link target.\n if (parent) {\n if (parent.isLink)\n parent = parent.target\n\n if (oldParent === parent)\n return\n }\n\n // ok now we know something is actually changing, and parent is not a link\n\n // check to see if the location is going to change.\n // we can skip some of the inventory/meta stuff if not.\n const newPath = parent ? resolve(parent.path, 'node_modules', this.name)\n : this.path\n const pathChange = newPath !== this.path\n const newTop = parent ? parent.top : this\n const topChange = newTop !== this.top\n const newRoot = parent ? parent.root : null\n const rootChange = newRoot !== this.root\n\n // if the path, top, or root are changing, then we need to delist\n // from metadata and inventory where this module (and its children)\n // are currently tracked. Need to do this BEFORE updating the\n // path and setting node.root. We don't have to do this for node.target,\n // because its path isn't changing, so everything we need will happen\n // safely when we set this.root = parent.root.\n if (this.path && (pathChange || topChange || rootChange)) {\n this[_delistFromMeta]()\n // delisting method doesn't walk children by default, since it would\n // be excessive to do so when changing the root reference, as a\n // root change walks children changing root as well. But in this case,\n // we are about to change the parent, and thus the top, so we have\n // to delist from the metadata now to ensure we remove it from the\n // proper top node metadata if it isn't the root.\n this.children.forEach(c => c[_delistFromMeta]())\n this.fsChildren.forEach(c => c[_delistFromMeta]())\n }\n\n // remove from former parent.\n if (oldParent)\n oldParent.children.delete(this.name)\n\n // update internal link. at this point, the node is actually in\n // the new location in the tree, but the paths are not updated yet.\n this[_parent] = parent\n\n // remove former child. calls back into this setter to unlist\n if (parent) {\n const oldChild = parent.children.get(this.name)\n if (oldChild)\n oldChild.parent = null\n\n parent.children.set(this.name, this)\n }\n\n // this is the point of no return. this.location is no longer valid,\n // and this.path is no longer going to reference this node in the\n // inventory or shrinkwrap metadata.\n if (parent)\n this[_refreshPath](parent, oldParent && oldParent.path)\n\n // call the root setter. this updates this.location, and sets the\n // root on all children, and this.target if this is a link.\n // if the root isn't changing, then this is a no-op.\n // the root setter is a no-op if the root didn't change, so we have\n // to manually call the method to update location and metadata\n if (this.root === newRoot)\n this[_refreshLocation]()\n else\n this.root = newRoot\n\n // if the new top is not the root, and it has meta, then we're updating\n // nodes within a link target's folder. update it now.\n if (newTop !== newRoot && newTop.meta)\n this[_refreshTopMeta]()\n\n // refresh dep links\n // note that this is _also_ done when a node is removed from the\n // tree by setting parent=null, so deduplication is covered.\n this.edgesIn.forEach(edge => edge.reload())\n this.edgesOut.forEach(edge => edge.reload())\n\n // in case any of the parent's other descendants were resolving to\n // a different instance of this package, walk the tree from that point\n // reloading edges by this name. This only walks until it stops finding\n // changes, so if there's a portion of the tree blocked by a different\n // instance, or already updated by the previous in/out reloading, it won't\n // needlessly re-resolve deps that won't need to be changed.\n if (parent) {\n parent[_reloadNamedEdges](this.name, true)\n }\n // since loading a parent can add *or change* resolutions, we also\n // walk the tree from this point reloading all edges.\n this[_reloadEdges](e => true)\n }",
"function prevParentTextNode(e) {\n\t\tconst elem = e.first()[0],\n\t\t\tparent = e.parent();\n\t\t/*\n\t\t\tQuit early if there's no parent.\n\t\t*/\n\t\tif (!parent.length) {\n\t\t\treturn null;\n\t\t}\n\t\t/*\n\t\t\tGet the parent's text nodes, and obtain only the last one which is\n\t\t\tearlier (or later, depending on positionBitmask) than this element.\n\t\t*/\n\t\tlet textNodes = parent.textNodes().filter((e) => {\n\t\t\tconst pos = e.compareDocumentPosition(elem);\n\t\t\treturn pos & 4 && !(pos & 8);\n\t\t});\n\t\ttextNodes = textNodes[textNodes.length-1];\n\t\t/*\n\t\t\tIf no text nodes were found, look higher up the tree, to the grandparent.\n\t\t*/\n\t\treturn !textNodes ? prevParentTextNode(parent) : textNodes;\n\t}",
"replace (element) {\r\n element = makeInstance(element);\r\n this.node.parentNode.replaceChild(element.node, this.node);\r\n return element\r\n }",
"getValidItem(el){\n while (el !== this.$el){\n if (el.__vue__){\n return this.getItem(el.__vue__)\n }else{\n el = el.parentElement\n }\n }\n return null\n }",
"function getOriginalDomRefs( reference, relation, offset ) {\n\t\tvar refNodeFound = false,\n\t\t\tprevSib;\n\n\t\tif( relation === \"prev-sib\" ) {\n\t\t\toffset += reference.innerHTML.length;\n\t\t}\n\t\telse if( relation === \"parent\" || relation === \"none\" ) {\n\t\t\trelation = \"prev-sib\";\n\t\t}\n\n\t\tprevSib = reference.previousSibling;\n\t\twhile( prevSib ) { // look for prev sibling != <h-l> and calc offset for it\n\t\t\tif( prevSib.nodeType === 1 ) {\n\t\t\t\tif( prevSib.nodeName.toLowerCase() !== \"h-l\" ) {\n\t\t\t\t\treference = prevSib;\n\t\t\t\t\trefNodeFound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\toffset += prevSib.innerHTML.length;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse { // text-node\n\t\t\t\toffset += prevSib.nodeValue.length;\n\t\t\t}\n\t\t\tprevSib = prevSib.previousSibling;\n\t\t}\n\n\t\tif( !refNodeFound ) { // fallback on parent node and calc offset for it\n\t\t\treference = reference.parentNode;\n\t\t\trelation = \"parent\";\n\t\t}\t\t\n\n\t\treturn new Location( reference, relation, offset );\n\t}",
"visitPartition_name_old(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function hc_nodereplacechildnodeancestor() {\n var success;\n var doc;\n var newChild;\n var elementList;\n var employeeNode;\n var childList;\n var oldChild;\n var replacedNode;\n doc = load(\"hc_staff\");\n newChild = doc.documentElement;\n\n elementList = doc.getElementsByTagName(\"p\");\n employeeNode = elementList.item(1);\n childList = employeeNode.childNodes;\n\n oldChild = childList.item(0);\n \n\t{\n\t\tsuccess = false;\n\t\ttry {\n replacedNode = employeeNode.replaceChild(newChild,oldChild);\n }\n\t\tcatch(ex) {\n success = (typeof(ex.code) != 'undefined' && ex.code == 3);\n\t\t}\n\t\tassertTrue(\"throw_HIERARCHY_REQUEST_ERR\",success);\n\t}\n\n}",
"function preserveWrapperATag(newMarkup) {\r\n var range = scope.editor.getRange();\r\n var anchor = getAnchorElement(range);\r\n if (anchor) {\r\n $(anchor).html(newMarkup);\r\n return anchor.outerHTML;\r\n }\r\n else {\r\n return newMarkup;\r\n }\r\n }",
"patch() {\n\t\tif (!this.component_.element && this.parent_) {\n\t\t\t// If the component has no content but was rendered from another component,\n\t\t\t// we'll need to patch this parent to make sure that any new content will\n\t\t\t// be added in the right place.\n\t\t\tthis.parent_.getRenderer().patch();\n\t\t\treturn;\n\t\t}\n\n\t\tvar tempParent = this.guaranteeParent_();\n\t\tif (tempParent) {\n\t\t\tIncrementalDOM.patch(tempParent, this.renderInsidePatchDontSkip_);\n\t\t\tdom.exitDocument(this.component_.element);\n\t\t\tif (this.component_.element && this.component_.inDocument) {\n\t\t\t\tthis.component_.renderElement_(\n\t\t\t\t\tthis.attachData_.parent,\n\t\t\t\t\tthis.attachData_.sibling\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\tvar element = this.component_.element;\n\t\t\tIncrementalDOM.patchOuter(element, this.renderInsidePatchDontSkip_);\n\t\t\tif (!this.component_.element) {\n\t\t\t\tdom.exitDocument(element);\n\t\t\t}\n\t\t}\n\t}",
"function keepIf(el, property) {\n var binding = this\n , parent = el.parentNode\n\n binding.change(function() {\n var value = binding.value(property)\n if (!value && el.parentNode) {\n el.parentNode.removeChild(el)\n } else if (value && !el.parentNode) {\n parent.appendChild(el)\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
giniIndex: calculate entropy with respect to variable, return | function giniIndex(obj, target_var, input_var){
rootEnt = rootNode(obj,target_var);
//Variable breakage
if(typeof(obj[input_var]=="number")){
console.log("it's a number!");
x = unique(obj,input_var).sort();
console.log(x);
//Count aboves and belows
info_gain = [];
for(var k = 0; k < x.length; k++){ //use x-vals as thresholds
var pos_above = 0;
var neg_above = 0;
var pos_below = 0;
var neg_below = 0;
var n_above = 0;
var n_below = 0;
for(var i = 0; i < obj.length; i++){ // go through each row
if(obj[i][input_var] >= x[k]){
n_above = n_above + 1;
if(obj[i][target_var]>0){
pos_above = pos_above + 1;
} else{
neg_above = neg_above + 1;
}
} else {
n_below = n_below + 1;
if(obj[i][target_var]>0){
pos_below = pos_below + 1
} else{
neg_below = neg_below + 1
}
}
//Calculate weighted entropy
n = n_above + n_below;
pos1 = Math.log2(pos_above/n_above)*pos_above/n_above;
neg1 = Math.log2(neg_above/n_above)*neg_above/n_above;
pos2 = Math.log2(pos_below/n_below)*pos_below/n_below;
neg2 = Math.log2(neg_below/n_below)*neg_below/n_below;
//Check for NaN or Infine Errors
if(isNaN(pos1) || !isFinite(pos1)){
pos1 = 0;
}
if(isNaN(pos2) || !isFinite(pos2)){
pos2 = 0;
}
if(isNaN(neg2) || !isFinite(neg2)){
neg2 = 0;
}
if(isNaN(neg1) || !isFinite(neg1)){
neg1 = 0;
}
}
gini= rootEnt - (n_above/n)*(pos1 + neg1) - (n_below/n)*(pos2 + neg2) ;
console.log(gini);
info_gain.push(gini);
}
//Returns value
return {"var_name":input_var,"optimal": x[info_gain.indexOf(min(info_gain))], "info_gain":min(info_gain)} ;
}
} | [
"function logEntropy(s) {\n console.log('Entropy of \"' + s + '\" in bits per symbol:', shannon.entropy(s));\n}",
"calcFitness(target) {\n let score = 0;\n\n for (let i = 0; i < this.genes.length; i++) {\n if (this.genes[i] == target.charAt(i)) {\n score++;\n }\n }\n\n this.fitness = score / target.length;\n }",
"hormonic(n) {\n var value = 0;\n\n while (n > 0) {\n value = value + (1 / n);\n n--\n }\n console.log(' this is the final hormonic value ' + value)\n }",
"normalizeFitness() {\n let sum = 0;\n this.chromosomes.forEach(chromosome => (sum += chromosome.fitness));\n this.chromosomes.forEach(chromosome => (chromosome.fitness /= sum));\n }",
"mutate() {\n this._genes.forEach((gene, idx) => {\n if (probability(this._mutationRate)) {\n if (idx) {\n this._genes[idx] = randomInArray(alphabet);\n } else {\n this._genes[0] = Math.random() * 10;\n }\n }\n });\n }",
"calcAggregatedIgnorance() {\n if (this.debug) console.log(\"\\nCALC Aggregated Ignorance - PROJECT - >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n var data = this.data;\n data.Ignorance = data.MdashH / (1 - data.MlH);\n if (this.debug) console.log(\"data.Ignorance: \" + data.Ignorance);\n\n // Calculate and save distributed ignorance divided by number of alternatives\n // For Distributed Ignorance table\n data.IgnoranceSplit = data.Ignorance/data.alternatives.length;\n }",
"function indexedExponentials(numbers) {\n //create new array\n var poweredToIndex = [];\n //loop through numbers array with each()\n each(numbers, function(el,i){\n //push raised ele to power of index\n poweredToIndex.push(Math.pow(el, i));\n });\n //return new array\n return poweredToIndex;\n}",
"function incgene(gn, steps, evt) {\n if (evt) {\n steps *= evt.shiftKey ? 10 : 1;\n steps *= evt.ctrlKey ? 0.1 : 1;\n }\n const step = genedefs[gn].step;\n let v = currentGenes[gn] + step * steps;\n v = +(v.toFixed(10)); // stop silly values from rounding, eg 4.10000000001\n setvalf(gn, v);\n}",
"calculateAverageFitness(gen) {\n const x = gen.generation;\n let pop = gen.individuals;\n const y = (pop.reduce((acc, cur) => acc + parseFloat(cur.fitness), 0) / pop.length).toFixed(1); // find average\n return {\n x: x,\n y: y,\n };\n }",
"activate(node){\t\n\t\tnode.value = 0\t//reset\n\n\t\tfor (var i = 0; i < this.genes.length; i++){\n\t\t\tif (this.genes[i] != null && this.genes[i].enabled && this.genes[i].outputNode == node){\n\t\t\t\t//leads to this node so we add it\n\t\t\t\tnode.value += this.genes[i].inputNode.value * this.genes[i].weight\n\t\t\t}\n\t\t}\n\n\t\tnode.value = sigmoid(node.value)\n\t}",
"function invDocFreq(term) {\n if (corpus == null){\n return -1;\n } else {\n //N = corpus.length;\n let docFreq = 0;\n for (let i in N){\n for (let j in corpus[i]) {\n if (corpus[i][j] == term.toLowerCase()){\n docFreq++;\n break;\n }\n }\n }\n let idf = Math.log((N) / (docFreq + 1)) + 1;\n return idf;\n }\n }",
"function unegyptian(array) {\n let total = 1 / array[0];\n for (let index = 1; index < array.length; index++) {\n total += (1 / array[index]);\n }\n\n return total;\n}",
"getRandomGene() {\n return this.genes[Math.floor(Math.random() * this.genes.length)];\n }",
"function narcissistic(value) {\n //split value\n const values = value\n .toString()\n .split(\"\")\n .map(Number);\n //raise each value by the length of array\n //add the values together\n const solution = values\n .map(value => Math.pow(value, values.length))\n .reduce((total, curr) => {\n total += curr;\n return total;\n }, 0);\n //compare added values to input value\n if (value === solution) return true;\n else return false;\n}",
"getVariable (index, isGlobal) {\n if (isGlobal) {\n return this.op(\"get_global\").varuint(index, \"global_index\");\n } else {\n return this.op(\"get_local\").varuint(index, \"local_index\");\n }\n }",
"function automatedReadabilityIndex(letters, numbers, words, sentences) {\n return (4.71 * ((letters + numbers) / words))\n + (0.5 * (words / sentences))\n - 21.43;\n}",
"function evj( x , ne , en )\n {\n\n const evc = ( this.nc - 1 ) ;\n\n if( ! en ) en = 1.0e-8 ;\n if( ! ne ) ne = 100 ;\n\n let se = undefined ;\n\n let i = undefined ;\n let j = undefined ;\n let k = undefined ;\n let n = undefined ;\n\n let lij = undefined ;\n let p = undefined ;\n let sp = undefined ;\n let ps = undefined ;\n\n let ip = undefined ;\n let jq = undefined ;\n\n let c = undefined ;\n let s = undefined ;\n\n let w = undefined ;\n let t = undefined ;\n let tt = undefined ;\n\n let vipk = undefined ;\n let vjqk = undefined ;\n\n let xipip = undefined ;\n let xjqjq = undefined ;\n let xipjq = undefined ;\n\n let xipk = undefined ;\n let xjqk = undefined ;\n \n let evn = undefined ;\n \n let evv = new Array( x.nv ) ;\n\n\n for( i = 0; i < x.nv; evv[ i ] = x.v[ i++ ] ) ;\n\n\n if( ! this.nd )\n\n for( i = 0; i < this.nr; this.v[ this.idx( i , i++ ) ] = 1 )\n \n for( j = 0; j < this.nr; this.v[ this.idx( i , j++ ) ] = 0 ) ;\n\n\n for( se = 1 , n = 0; (n < ne) && (Math.abs( se ) > en); ++n )\n {\n\n for( ip = 0; (ip < (x.nr - 1)); ++ip )\n\n for( jq = (ip + 1); (jq < x.nr); ++jq )\n {\n\n xipip = evv[ x.idx( ip , ip ) ] ;\n xjqjq = evv[ x.idx( jq , jq ) ] ;\n xipjq = evv[ x.idx( ip , jq ) ] ;\n\n if( xipjq )\n {\n\n w = ( (xjqjq - xipip) / (2 * xipjq) ) ;\n\n [ t , s , tt , c ] = srt( (2 * w) , (- 1) ) ;\n\n if( Math.abs( t ) > Math.abs( tt ) ) t = tt ;\n\n\n tt = ( t * t );\n\n s = ( t / Math.sqrt( 1 + tt ) ) ;\n\n c = ( 1 / Math.sqrt( 1 + tt ) );\n\n tt = ( s / (1 + c) ) ;\n\n\n evv[ x.idx( ip , ip ) ] = ( xipip - (t * xipjq) ) ;\n\n evv[ x.idx( jq , jq ) ] = ( xjqjq + (t * xipjq) ) ;\n\n evv[ x.idx( ip , jq ) ] = 0 ;\n\n evv[ x.idx( jq , ip ) ] = 0 ;\n\n\n if( ! x.d )\n {\n\n \n for( k = 0; k < x.nc; ++k )\n {\n\n if( (k != ip) && (k != jq) )\n {\n\n xipk = evv[ x.idx( ip , k ) ] ;\n\n xjqk = evv[ x.idx( jq , k ) ] ;\n\n evv[ x.idx( ip , k ) ] = ( xipk - (s * (xjqk + (tt * xipk))) ) ;\n\n evv[ x.idx( jq , k ) ] = ( xjqk + (s * (xipk - (tt * xjqk))) ) ;\n\n } ; // end if{} -\n\n\n } ; // end for()\n\n\n for( k = 0; k < x.nr; ++k )\n {\n\n if( (k != ip) && (k != jq) )\n {\n\n xipk = evv[ x.idx( k , ip ) ] ;\n\n xjqk = evv[ x.idx( k , jq ) ] ;\n\n evv[ x.idx( k , ip ) ] = ( xipk - (s * (xjqk + (tt * xipk))) ) ;\n\n evv[ x.idx( k , jq ) ] = ( xjqk + (s * (xipk - (tt * xjqk))) ) ;\n\n } ; // end if{} -\n\n\n } ; // end for()\n\n\n } ; // end if{} -\n\n\n if( ! this.nd )\n\n for( k = 0; k < this.nr; ++k )\n { \n\n vipk = this.v[ this.idx( ip , k ) ] ;\n\n vjqk = this.v[ this.idx( jq , k ) ] ;\n\n this.v[ this.idx( ip , k ) ] = ( (c * vipk) - (s * vjqk) ) ;\n\n this.v[ this.idx( jq , k ) ] = ( (s * vipk) + (c * vjqk) ) ;\n\n } ; // end if{}-\n\n\n } ; // end if{} -\n\n\n // console.log( 'n=' , n , 'ip=' , ip , 'jq=' , jq , 'evv=' , evv ) ;\n\n\n } ; // end for()\n\n\n for( se = 0 , i = 0; i < x.nr; ++i )\n\n for( j = (i + 1); j < x.nc; se += Math.abs( evv[ x.idx( i , j++ ) ] ) ) ;\n\n\n for( i = 0; i < this.nr; ++i )\n\n this.v[ this.idx( i , evc ) ] = evv[ x.idx( i , i ) ] ;\n\n\n } ; // end for()\n\n\n return( n ) ;\n\n\n }",
"function getIndexAndK(w,data) {\n var hiWavelength = 0;\n var hiIndex = 0;\n var loWavelength = 0; \n var loIndex = 0;\n var hiExtinction = 0;\n\tvar loExtinction = 0;\n\t\t\t\t\n for (j = 0; j < data.Indices.length; j++) {\n \n if (data.Indices[j].lambda <= w && (loWavelength === 0 || loWavelength < data.Indices[j].lambda)) {\n loWavelength = data.Indices[j].lambda;\n loIndex = data.Indices[j].n;\n loExtinction = data.Indices[j].k;\t\t\n\t }\n\n if (data.Indices[j].lambda >= w && (hiWavelength === 0 || hiWavelength > data.Indices[j].lambda)) {\n hiWavelength = data.Indices[j].lambda;\n hiIndex = data.Indices[j].n;\n hiExtinction = data.Indices[j].k;\t\t\t\t\n }\n };\n\n\t// Closer data point is the wavelength, higher proportion used.\n\t// But if LoWavelength is the highest number, It's proportion should be 1. \n\tif (hiIndex == 0) {\n loWavelength = w;\n\t}\n\t\n if (loIndex == 0) {\n hiWavelength = w;\n }\n\t\n\tvar diff = hiWavelength - loWavelength;\n\t// if difference is 0 (i.e. loWavelength = hiWavelength). We can just\n\t// take either hiIndex or loIndex as the final Index\n if (diff != 0) {\n var Index1 = (1 - (( w - loWavelength ) / diff)) * loIndex;\n var Extinction1 = ((loWavelength/ w) * loExtinction);\n var Index2 = (1 - (( hiWavelength - w ) / diff)) * hiIndex;\n var Extinction2 = ((1-(loWavelength/ w)) * hiExtinction);\n var Index = Index1 + Index2;\n var Extinction = Math.round((Extinction1 + Extinction2)*1000000)/1000000;\n \t \n } else {\n var Index = hiIndex;\n var Extinction = hiExtinction;\n } \n return [Index, Extinction];\n}",
"function mostFavorableGrid(){\r\n var bestGrid = 0;\r\n var index = 0;\r\n for(var i = 0; i < fitness.length; i++){\r\n if(fitness[i] > bestGrid){\r\n bestGrid = fitness[i];\r\n index = i;\r\n }\r\n }\r\n //console.log(\"Most favorable grid is grid:\" + index);\r\n\tdocument.getElementById(\"favGrid\").innerHTML = \"Grid #\" + index;\r\n return index;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provides all fetchers currently on the page. Useful for layouts and parent routes that need to provide pending/optimistic UI regarding the fetch. | function useFetchers() {
let state = dist_useDataRouterState(dist_DataRouterStateHook.UseFetchers);
return [...state.fetchers.values()];
} | [
"function fetchSites() {\n fetch(BASE_URL + SITES)\n .then(function(response) {\n return response.json();\n })\n .then(function(json) {\n json.forEach(site => {\n document.getElementById(\"loading\").style.display = \"none\";\n document\n .getElementById(\"sites_div\")\n .prepend(renderSite(site));\n });\n });\n }",
"function getOfflineStreamers() {\r\n clearElements();\r\n getStreamData(\"offline\");\r\n }",
"_fetchState() {\n this._fetchLeagues();\n this._fetchSeasons();\n this._fetchRallies();\n this._fetchDrivers();\n }",
"getTeachers() {\n return getAllTeachers(this._code);\n }",
"function fetchAllToys() {\n fetch(`http://localhost:3000/toys`, {method: 'GET'})\n .then(responseObject => responseObject.json())\n .then(data => toyCollectionDiv.innerHTML = renderAllToys(data))\n}",
"fetchAPIs (){\n\t\t//these api call calls up\n\t\tthis.fetchLocation.call();\n\t\tthis.fetchWeatherData.call();\n\t\tthis.fetchForecastData.call();\n\t\tthis.fetchTflData.call();\n\t\t// this.fetchBus.call();\n\t}",
"function fetchArticles() {\n\treturn (dispatch) => {\n\t\tresource(\"GET\", \"articles\")\n\t\t.then(r => dispatch({type: 'articles', \n\t\t\tarticles: sortArticles(r.articles)}))\n\t}\n}",
"function getAllStreamers() {\r\n clearElements();\r\n getStreamData(\"all\");\r\n }",
"getAllDisplays() {\r\n return eltr.screen.getAllDisplays();\r\n }",
"function fetchBurgers(){\n fetch(\"http://localhost:3000/burgers\")\n .then(r=>r.json())\n .then(burgers => renderAllBurgers(burgers))\n}",
"function _GET_AllThreads() {\n\n $.ajax({\n dataType: \"json\",\n // headers: { \"Authorization\": \"Basic \" + btoa(state.user + \":\" + state.password) },\n url: \"/threads\",\n success: function success(data) {\n state.movieThreads = data.movieThreads;\n saveToStorage(state); // persist\n renderMovieThreads(state);\n },\n type: \"GET\"\n });\n}",
"function getNavigators() {\n return new Promise(resolve => {\n xapi.Status.Peripherals.ConnectedDevice.get().then(async devices => {\n var data = devices.filter(device => device.Name.toLowerCase().includes(\"navigator\") && device.Type.toLowerCase().includes(\"touchpanel\"));\n resolve(data);\n });\n });\n}",
"topReferrersTable() {\n const id = 'top-referrers-table-container';\n this.setLoading(id);\n const queryData = {\n 'metrics': 'ga:pageviews',\n 'dimensions': 'ga:fullReferrer',\n 'sort': '-ga:pageviews',\n 'max-results': 25\n };\n\n this.getQuery(queryData).then(results => {\n this.data['referrers'] = results.rows;\n $(this.export_btn).prop('disabled', false);\n $(this.export_btn).removeClass('button-longrunning-active');\n\n const table = createTable(['Source', 'Views'], results.rows);\n const pager = paginateTable(table);\n const container = document.getElementById(id);\n container.innerHTML = '';\n container.appendChild(table);\n $(container).append(pager);\n });\n }",
"fetchData() {\n\t\thelpers.getUser().listProjects().then(projects => {\n\t\t\tvar projectEntries = projects.entities.map(project => helpers.getUser().getDataTable(project.id).listCells())\n\t\t\tPromise.all(projectEntries).then(projectEntries => {\n\t\t\t\tvar cells = projectEntries.map(cell => cell.entities)\n\t\t\t\tthis.setState({cells: cells, authenticated: true, projects: projects.entities})\n\t\t\t})\n\t\t})\n\t}",
"function fetchData() {\n // Wait for any ongoing sync to finish. We won't sync a SCORM while it's being played.\n return $mmaModScormSync.waitForSync(scorm.id).then(function() {\n // Get attempts data.\n return $mmaModScorm.getAttemptCount(scorm.id).then(function(attemptsData) {\n return determineAttemptAndMode(attemptsData).then(function() {\n // Fetch TOC and get user data.\n var promises = [];\n promises.push(fetchToc());\n promises.push($mmaModScorm.getScormUserData(scorm.id, attempt, offline).then(function(data) {\n userData = data;\n }));\n\n return $q.all(promises);\n });\n }).catch(showError);\n });\n }",
"function getAllStreamersData(streamerList, onOfforAll) {\n streamerList.forEach(function(streamer) {\n var url = \"https://wind-bow.glitch.me/twitch-api/streams/\" + streamer;\n var request = new XMLHttpRequest();\n request.onload = function () {\n if (request.status == 200) {\n resultsObject = JSON.parse(request.responseText);\n if (resultsObject.stream == null && onOfforAll != \"onlineOnly\") {\n displayOfflineUsers(resultsObject, streamer);\n } else if (onOfforAll != \"offlineOnly\") {\n displayOnlineStreamers(resultsObject);\n }\n }\n };\n request.open(\"GET\", url);\n request.send(null);\n });\n}",
"function getBeers() {\n //\n //\n //beers.list(); listBeer\n //\n var req = gapi.client.birra.beers.list();\n req.execute(function(data) {\n $(\"#results\").html('');\n showList(data); \n });\n}",
"static GetImporters() {}",
"function initialDisplay(){\r\n fetch(`${api.baseUrl}weather?q=Bucharest&units=metric&APPID=${api.key}`)\r\n .then(function(weather){return weather.json(); })\r\n .then(initialDisplayNext);\r\n}",
"function showAll() {\r\n getData().then( (eps) => { \r\n getDisplayHTML(eps); \r\n });\r\n clearAll();\r\n showDisplay(); \r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch school results from the REST API which is run locally. Get the results in JSON format. Set the state with the obtained results. | componentDidMount() {
fetch('http://localhost:3000/schools?gradeRange=6-8&gradeRange=K-8&gradeRange=7-12')
.then(results => results.json())
.then((data) => {this.setState({middleSchools: data});
//console.log('the retreived data is: ' + JSON.stringify(data));
});
} | [
"_fetchState() {\n this._fetchLeagues();\n this._fetchSeasons();\n this._fetchRallies();\n this._fetchDrivers();\n }",
"getSpecies() {\n return axios.get(\"http://swapi.co/api/species\", {crossDomain: true})\n .then((response) => {\n this.setState({species: response.data.results})\n })\n }",
"getAssignments(schoolID) {\n return _get('/api/assignments', {school_id: schoolID});\n }",
"function getSchoolsByName(schoolName) {\n const conditions = {\n schoolType: getTypeTerm(),\n state: getStateTerm()\n };\n return $.post(\"/api/schools/name/\" + schoolName, conditions);\n}",
"function fetchSites() {\n fetch(BASE_URL + SITES)\n .then(function(response) {\n return response.json();\n })\n .then(function(json) {\n json.forEach(site => {\n document.getElementById(\"loading\").style.display = \"none\";\n document\n .getElementById(\"sites_div\")\n .prepend(renderSite(site));\n });\n });\n }",
"getPeople() {\n return axios.get(\"http://swapi.co/api/people\", {crossDomain: true})\n .then((response) => {\n this.setState({people: response.data.results})\n })\n }",
"async fetchAgrDemandSchedule(direction) {\n // for debug\n //console.log(`[Before] JSON.stringify(this.state.demandSchedule) = ${JSON.stringify(this.state.demandSchedule)}`);\n\n const directionString = (direction === SCHOOL) ? 'school' : 'home';\n\n // GET the own demand schedule\n try {\n let agrDemandResponse = await fetch(`https://inori.work/demand/aggregate/${directionString}`);\n\n // If succeeded to GET the own demand schedule,\n if (parseInt(agrDemandResponse.status / 100, 10) === 2) {\n let agrDemandResponseJson = await agrDemandResponse.json();\n\n // for debug\n //console.log(`JSON.stringify(agrDemandResponseJson) = ${JSON.stringify(agrDemandResponseJson)}`);\n\n const todayId = new Date().getDay();\n\n let schoolDayId;\n let homeDayId;\n switch (todayId) {\n case FRI:\n schoolDayId = MON;\n homeDayId = FRI;\n break;\n\n case SAT:\n case SUN:\n schoolDayId = MON;\n homeDayId = MON;\n break;\n\n default:\n schoolDayId = todayId + 1;\n homeDayId = todayId;\n break;\n }\n\n if (direction === SCHOOL) {\n const demandScheduleSchool = this.state.demandSchedule.school[0];\n demandScheduleSchool.data.forEach((item, index) => {\n if (item.x === DUMMY) {\n demandScheduleSchool.data[index].y = 0;\n } else {\n const timeId = this.timeString2Id(item.x);\n demandScheduleSchool.data[index].y = agrDemandResponseJson.days[schoolDayId][timeId];\n }\n });\n\n this.setState({\n schoolDayId,\n homeDayId,\n demandSchedule: {\n ...this.state.demandSchedule,\n school: [demandScheduleSchool]\n }\n });\n } else if (direction === HOME) {\n const demandScheduleHome = this.state.demandSchedule.home[0];\n demandScheduleHome.data.forEach((item, index) => {\n if (item.x === DUMMY) {\n demandScheduleHome.data[index].y = 0;\n } else {\n const timeId = this.timeString2Id(item.x);\n demandScheduleHome.data[index].y = agrDemandResponseJson.days[homeDayId][timeId];\n }\n });\n\n this.setState({\n schoolDayId,\n homeDayId,\n demandSchedule: {\n ...this.state.demandSchedule,\n home: [demandScheduleHome]\n }\n });\n }\n\n // for debug\n //console.log(`[After] JSON.stringify(this.state.demandSchedule) = ${JSON.stringify(this.state.demandSchedule)}`);\n\n // If failed to GET the own demand schedule,\n } else if (parseInt(agrDemandResponse.status / 100, 10) === 4 ||\n parseInt(agrDemandResponse.status / 100, 10) === 5) {\n console.log('Failed to GET the demand schedule...');\n\n Alert.alert(\n 'グラフデータを取得することができませんでした。',\n '電波の良いところで後ほどお試しください。相乗りオファーを出すことは可能です。',\n [{ text: 'OK' }]\n );\n }\n\n // If cannot access demand api,\n } catch (error) {\n console.error(error);\n console.log('Cannot access demand api...');\n\n Alert.alert(\n 'グラフデータを取得することができませんでした。',\n '電波の良いところで後ほどお試しください。相乗りオファーを出すことは可能です。',\n [{ text: 'OK' }]\n );\n }\n }",
"function getSchools(hardRefresh) {\n var def = $.Deferred();\n schools = JSON.parse(localStorage.getItem('schools'));\n if (schools == null || hardRefresh) {\n $.getJSON(\"https://peachjar-finder.s3-us-west-2.amazonaws.com/schools.json\", function(data) {\n localStorage.setItem('schools', JSON.stringify(data));\n schools = data;\n def.resolve(schools);\n });\n } else {\n def.resolve(schools);\n }\n return def;\n}",
"async setResults(data){\n const url1 = 'https://f1ml.herokuapp.com/res';\n const raceRequest = {\n data:{\n race: data\n },\n headers:{\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Origin': '*'\n },\n responseType: 'json',\n url: url1\n };\n\n axios.post(url1, raceRequest).then(response => {\n //await this.setState({resultData: response.data.data, race:data});\n return response.data.data\n \n }).catch(function(error){\n alert(\"Failed to connect to server:\" + error);\n });\n }",
"apisCall() {\n // Reset the variables other then the name and department in order to start a new research\n $scope.view.establishments.tooMuchResults = false;\n $scope.view.establishments.searchSuccess = false;\n $scope.view.establishments.resultsBeforeFiltering = 0;\n $scope.view.establishments.resultsTable = [];\n\n // Call the getEstablishments() function of the getEstablishmentsSrv service\n // Use what the stringNormalize() function of the stringFormatingSrv service returns as the establishment's name\n\n EstablishmentSrv.getAllEstablishments($scope.view.establishments.name, $scope.view.establishments.department)\n .then(\n (response) => {\n $scope.view.establishments.tooMuchResults = response.tooMuchResults;\n $scope.view.establishments.resultsTable = response.resultsTable;\n $scope.view.establishments.resultsBeforeFiltering = response.resultsBeforeFiltering;\n $scope.view.establishments.searchSuccess = true;\n },\n (error) => {\n $scope.view.errorMsg = error;\n $scope.view.establishments.searchSuccess = true;\n $scope.view.establishments.resultsTable = [];\n },\n );\n }",
"function ResultsController($scope, $http, $filter, $state, refstackApiUrl) {\n var ctrl = this;\n\n ctrl.update = update;\n ctrl.open = open;\n ctrl.clearFilters = clearFilters;\n\n /** Initial page to be on. */\n ctrl.currentPage = 1;\n\n /**\n * How many results should display on each page. Since pagination\n * is server-side implemented, this value should match the\n * 'results_per_page' configuration of the Refstack server which\n * defaults to 20.\n */\n ctrl.itemsPerPage = 20;\n\n /**\n * How many page buttons should be displayed at max before adding\n * the '...' button.\n */\n ctrl.maxSize = 5;\n\n /** The upload date lower limit to be used in filtering results. */\n ctrl.startDate = '';\n\n /** The upload date upper limit to be used in filtering results. */\n ctrl.endDate = '';\n\n /** The date format for the date picker. */\n ctrl.format = 'yyyy-MM-dd';\n\n /** Check to see if this page should display user-specific results. */\n ctrl.isUserResults = $state.current.name === 'userResults';\n\n // Should only be on user-results-page if authenticated.\n if (ctrl.isUserResults && !$scope.auth.isAuthenticated) {\n $state.go('home');\n }\n\n ctrl.pageHeader = ctrl.isUserResults ?\n 'Private test results' : 'Community test results';\n\n if (ctrl.isUserResults) {\n ctrl.authRequest = $scope.auth.doSignCheck()\n .then(ctrl.update);\n } else {\n ctrl.update();\n }\n\n /**\n * This will contact the Refstack API to get a listing of test run\n * results.\n */\n function update() {\n ctrl.showError = false;\n // Construct the API URL based on user-specified filters.\n var content_url = refstackApiUrl + '/results' +\n '?page=' + ctrl.currentPage;\n var start = $filter('date')(ctrl.startDate, 'yyyy-MM-dd');\n if (start) {\n content_url =\n content_url + '&start_date=' + start + ' 00:00:00';\n }\n var end = $filter('date')(ctrl.endDate, 'yyyy-MM-dd');\n if (end) {\n content_url = content_url + '&end_date=' + end + ' 23:59:59';\n }\n if (ctrl.isUserResults) {\n content_url = content_url + '&signed';\n }\n ctrl.resultsRequest =\n $http.get(content_url).success(function (data) {\n ctrl.data = data;\n ctrl.totalItems = ctrl.data.pagination.total_pages *\n ctrl.itemsPerPage;\n ctrl.currentPage = ctrl.data.pagination.current_page;\n }).error(function (error) {\n ctrl.data = null;\n ctrl.totalItems = 0;\n ctrl.showError = true;\n ctrl.error =\n 'Error retrieving results listing from server: ' +\n angular.toJson(error);\n });\n }\n\n /**\n * This is called when the date filter calendar is opened. It\n * does some event handling, and sets a scope variable so the UI\n * knows which calendar was opened.\n * @param {Object} $event - The Event object\n * @param {String} openVar - Tells which calendar was opened\n */\n function open($event, openVar) {\n $event.preventDefault();\n $event.stopPropagation();\n ctrl[openVar] = true;\n }\n\n /**\n * This function will clear all filters and update the results\n * listing.\n */\n function clearFilters() {\n ctrl.startDate = null;\n ctrl.endDate = null;\n ctrl.update();\n }\n }",
"function fetchrestaurants() {\n var data;\n $.ajax({\n url: 'https://api.foursquare.com/v2/venues/search',\n dataType: 'json',\n data: 'client_id=LEX5UAPSLDFGAG0CAARCTPRC4KUQ0LZ1GZSB4JE0GSSGQW3A&client_secret=0QUGSWLF4DJG5TM2KO3YCUXUB2IJUCHDNSZC0FUUA3PKV0MY&v=20170101&ll=28.613939,77.209021&query=restaurant',\n async: true,\n }).done(function (response) {\n data = response.response.venues;\n data.forEach(function (restaurant) {\n var foursquare = new Foursquare(restaurant, map);\n self.restaurantList.push(foursquare);\n });\n self.restaurantList().forEach(function (restaurant) {\n if (restaurant.map_location()) {\n google.maps.event.addListener(restaurant.marker, 'click', function () {\n self.selectrestaurant(restaurant);\n });\n }\n });\n }).fail(function (response, status, error) {\n\t\t\tself.queryResult('restaurant\\'s could not load...');\n });\n }",
"function getResults() {\n var url = '/results/';\n var program = $(\"#programSelect option:selected\").text();\n var year = $(\"#yearSelect option:selected\").text();\n url += program + '/' + year;\n\n // reloads only that HTML fragment\n $(\"#results\").load(encodeURI(url),\n function () {\n $('#results-table').DataTable(); // reload sorting on table\n }\n );\n}",
"fetchSchoolYear(context, id) {\n return new Promise((resolve, reject) => {\n ApiService.init()\n ApiService.get(`/api/school-year/${id}/show`, {}).then(\n response => {\n resolve(response)\n },\n error => {\n reject(error)\n }\n )\n })\n }",
"function getTeam(query) {\n $.ajax({\n url: `http://nflarrest.com/api/v1/team/search/?term=${query}`,\n method: 'GET',\n success: function successHandler(returnedTeam) {\n $(\"#teamCityGoesHere\").text(returnedTeam[0].city);\n $(\"#teamNameGoesHere\").text(returnedTeam[0].teams_full_name);\n var teamToSearch = returnedTeam[0].team_code;\n console.log(teamToSearch);\n getData(teamToSearch);\n },\n });\n }",
"componentDidMount () {\n fetch('http://api.sweet-travels.appspot.com/api/states/' + this.state.id)\n .then((response) => response.json())\n .then((responseJson) => {\n this.setState({\n data: responseJson\n });\n })\n .catch(() => {\n this.setState({nothingFound: true});\n });\n }",
"function click_hospitalSearch(event) {\n\n var state = $(\"#hospital_search_state\").val();\n console.log(\"the user wants us to search for\", state);\n\n // construct query\n\n var queryUrl = 'api/hospitals/' + state + '.json';\n console.log(\"(fingers crossed) going to request\", queryUrl);\n\n $.ajax({\n url: queryUrl,\n method: \"GET\",\n crossDomain: true,\n // dataType: 'jsonp',\n headers: {\n 'Access-Control-Allow-Origin': '*'\n }\n }).then(function (hospitals) {\n \n console.log(\"we found\", hospitals.length, \"hospital(s) in the great state of\", state);\n $(\"#discoverer\").html(\n `Discover Our Hospitals in ${state} with total number of hospitals as ${hospitals.length}`\n );\n renderHospitalCards(hospitals);\n updateMap(hospitals, state, 5);\n });\n}",
"function fetchBooks() {\n fetch('https://anapioficeandfire.com/api/books').then(respfrombooks => respfrombooks.json()).then(respfrombooksjson => renderBooks(respfrombooksjson))\n}",
"readStudentData(){\r\n let url=\"https://maeyler.github.io/JS/data/Students.txt\";\r\n fetch(url)\r\n .then(res => res.text())\r\n .then(res => this.addStudentsToMap(res,this.students));\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exit a parse tree produced by Java9ParserinterfaceBody. | exitInterfaceBody(ctx) {
} | [
"exitNormalInterfaceDeclaration(ctx) {\n\t}",
"exitControlStructureBody(ctx) {\n\t}",
"visitExit_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"exitInterfaceModifier(ctx) {\n\t}",
"endIf() {\n return this._endBlockNode(If, Else)\n }",
"exitStatementWithoutTrailingSubstatement(ctx) {\n\t}",
"exitMethodDeclarator(ctx) {\n\t}",
"exitOrdinaryCompilation(ctx) {\n\t}",
"exitUnannInterfaceType(ctx) {\n\t}",
"exitNormalClassDeclaration(ctx) {\n\t}",
"exitConstructorBody(ctx) {\n\t}",
"exitBlockLevelExpression(ctx) {\n\t}",
"exitTopLevelObject(ctx) {\n\t}",
"exitJumpExpression(ctx) {\n\t}",
"exitUnannClassOrInterfaceType(ctx) {\n\t}",
"exitInterfaceTypeList(ctx) {\n\t}",
"exitBasicForStatement(ctx) {\n\t}",
"visitType_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"exitAnnotationTypeMemberDeclaration(ctx) {\n\t}",
"exitInterfaceType_lf_classOrInterfaceType(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
assign the global group items to remove | function remove_group() {
// Enable the remove animation
remove_animation = true;
// refresh the score
set_stat(stat_types.score, gamer.score + map.single_score * group.length);
// refresh tha available planets
gamer.available_planets -= group.length;
// set every planet as assigned to remove
for (var i = group.length - 1; i >= 0; i--) {
group[i].assigned = true;
}
reset_checked_planets();
// play explosion sound effect
effects.explosion.play();
} | [
"function remove_floating_group() {\n // Enable the remove animation\n remove_animation = true;\n\n // refresh the score\n set_stat(stat_types.score, gamer.score + map.floating_score * group.length);\n\n for (var i = group.length - 1; i >= 0; i--) {\n // refresh the available planets\n gamer.available_planets -= group[i].length;\n // set every planet in the inner array as assigned\n for (var j = group[i].length - 1; j >= 0; j--) {\n group[i][j].assigned = true;\n }\n }\n\n reset_checked_planets();\n\n // play explosion sound effect\n effects.explosion.play();\n }",
"removeNeededItems() {\n this.neededItems = [];\n }",
"deselectAll() {\n\n if (this.currentTab === 'supergroups') {\n for (let sg in this.supergroups) {\n if (this.supergroups.hasOwnProperty(sg)) {\n this.supergroups[sg].visible = false;\n }\n }\n this.checkedSupergroups = [];\n }\n else if (this.currentTab === 'groups') {\n for (let g in this.groups) {\n if (this.groups.hasOwnProperty(g)) {\n this.groups[g].visible = false;\n }\n }\n this.checkedGroups = [];\n }\n\n MapLayers.nuts3.renderLayer();\n\n }",
"function killEmptyGroupsInLayer(theLayer) {\r\n\tvar gCount = theLayer.groupItems.length;\r\n\tfor (var gNo = gCount - 1; gNo >= 0; gNo--) {\r\n\t\tvar thisGroup = theLayer.groupItems[gNo];\r\n\t\tif (thisGroup.pageItems.length === 0) {\r\n\t\t\tthisGroup.remove();\r\n\t\t}\r\n\t}\r\n}",
"deleteItemsEventsEtc() {\n let items_buffer = getReferencesOfType('AGItem');\n items_buffer.forEach(function (buffer) {\n deleteItem(buffer);\n });\n let conditions_buffer = getReferencesOfType('AGCondition');\n conditions_buffer.forEach(function (buffer) {\n deleteCondition(buffer);\n });\n let glevents_buffer = getReferencesOfType('GlobalEvent');\n glevents_buffer.forEach(function (buffer) {\n getReferenceById(getReferencesOfType(\"AGEventHandler\")[0]).removeGlobalEventByID(parseInt(buffer));\n });\n let events_buffer = getReferencesOfType('Event');\n events_buffer.forEach(function (buffer) {\n getReferenceById(getReferencesOfType(\"AGEventHandler\")[0]).removeEventByID(parseInt(buffer));\n });\n\n this.listItems();\n this.listEvents();\n this.refreshItemSelect();\n this.listGlobalEvents();\n this.listConditions();\n }",
"function remove(items){items=getList(items);for(var i=0;i<items.length;i++){var item=items[i];if(item&&item.parentElement){item.parentNode.removeChild(item);}}}",
"function removeAllGBeaconComposite(){\n for(i in COMPOSITE.items){\n if(COMPOSITE.items[i] != null){\n ge.getFeatures().removeChild(COMPOSITE.items[i].dopplerMarker.marker);\n COMPOSITE.items[i].dopplerMarker.marker.release();\n if(COMPOSITE.items[i].gpsMarker){\n ge.getFeatures().removeChild(COMPOSITE.items[i].gpsMarker.marker);\n COMPOSITE.items[i].gpsMarker.marker.release();\n }\n }\n }\n COMPOSITE.clear();\n}",
"function removeSocketFromGroups() {\n var i, len, groupId, member;\n\n for (groupId in groups) {\n for (i = 0, len = groups[groupId].length; i < len; i++) {\n member = groups[groupId][i];\n if (member === socket) {\n\n /* remove the member from the group */\n groups[groupId].splice(i, 1);\n printableGroups[groupId].splice(i, 1);\n\n /* remove the group if it is now empty */\n if (groups[groupId].length === 0) {\n delete groups[groupId];\n delete printableGroups[groupId];\n }\n break;\n }\n }\n }\n\n console.log('groupDel: ' + JSON.stringify(printableGroups));\n }",
"function cleanGroupMembers () {\n // first create the group if it doesnt exist\n var group = ContactsApp.getContactGroup(GROUP_NAME);\n \n // delete everyone on it\n if (group) {\n group.getContacts().forEach(function(d) {\n d.deleteContact();\n });\n \n // delete the group\n group.deleteGroup();\n }\n \n}",
"onTableGroupRemove (groupName) {\n if (this.tablesRetain.length <= 0) return // retain tables list already empty\n if (!groupName) {\n console.warn('Unable to remove table group from retain list, group name is empty')\n return\n }\n this.$q.notify({ type: 'info', message: this.$t('Suppress group of output tables') + ': ' + groupName })\n\n // remove tables group from the list\n const gt = this.groupTableLeafs[groupName]\n if (gt) {\n this.tablesRetain = this.tablesRetain.filter(tn => !gt?.leafs[tn])\n this.refreshTableTreeTickle = !this.refreshTableTreeTickle\n }\n }",
"removeKeys () {\n this._eachPackages(function (_pack) {\n _pack.remove()\n })\n }",
"function DDLightbarMenu_RemoveAllItemHotkeys()\n{\n\tfor (var i = 0; i < this.items.length; ++i)\n\t\tthis.items[i].hotkeys = \"\";\n}",
"function clearables(){\n //remove moveable...\n _$showcase.find('.moveable').removeClass('moveable');\n \n //remove clippingable...\n _$showcase.find('.clippingable').removeClass('clippingable');\n \n //remove contextmenu...\n _$showcase.find('.contextmenu').remove();\n \n \n }",
"removeAllMarkers() {\n if (this.markerGroup) this.markerGroup.clearLayers();\n }",
"function removeItemPropeties (data) {\n\tdelete data.name;\n\tdelete data.type;\n\tdelete data.external_id;\n\n\tfor (var key in data) {\n\t\tif (key.startsWith('sitemap_locations')) {\n\t\t\tdelete data[key];\n\t\t} \n\t}\n\n\treturn data;\n}",
"function clearOrgunitAssignment() {\n\tfor (var i = 0; metaData.dataSets && i < metaData.dataSets.length; i++) {\n\t\tmetaData.dataSets[i].organisationUnits = [];\n\t}\n\n\tfor (var i = 0; metaData.programs && i < metaData.programs.length; i++) {\n\t\tmetaData.programs[i].organisationUnits = [];\n\t}\n\n\tfor (var i = 0; metaData.users && i < metaData.users.length; i++) {\n\t\tmetaData.users[i].organisationUnits = [];\n\t\tmetaData.users[i].dataViewOrganisationUnits = [];\n\t\tmetaData.users[i].teiSearchOrganisationUnits = [];\n\t}\n\n\n\tfor (var i = 0; metaData.hasOwnProperty(\"predictors\") && i < metaData.predictors.length; i++) {\n\t\tmetaData.predictors[i].organisationUnitLevels = [];\n\t}\n\t\n}",
"get removedItems() {\n if (this._removedItems === null) {\n let coll = new IgrGridSelectedItemsCollection();\n let innerColl = this.i.removedItems;\n if (!innerColl) {\n innerColl = new GridSelectedItemsCollection_internal();\n }\n this._removedItems = coll._fromInner(innerColl);\n this.i.removedItems = innerColl;\n }\n return this._removedItems;\n }",
"function UnspawnAll(){\n\t\tfor(var i = 0; i < all.Count; i++){\n\t\t\tvar obj : GameObject = all[i] as GameObject;\n\t\t\tif(obj.active)\n\t\t\t\tUnspawn(obj);\n\t\t}\n\t}",
"resetEverything() {\n this.resetLoader();\n this.remove(0, Infinity);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove all right and wrong style classes from all answer buttons. | function resetAnswerButtons() {
for(var i = 1; i <= 4; i++) {
$("#divAnswer" + i).removeClass(
"classAnswerCorrect classAnswerEliminated");
}
} | [
"function prepareAnswerClasses(){\n\n for (let i =0; i<answerchildren.length; i++){\n answerchildren[i].classList.remove('hiddenAnswer');\n answerchildren[i].classList.add('basicAnswer');\n }\n document.getElementById(\"answers\").classList.remove('unclickable');\n}",
"function resetForm() {\n\t//Reset body to hue-neutral till next qestion in answered\n\tclearStatusClass(document.body);\n\tnextQuestionBtn.classList.add('hide');\n\twhile (solutionButtonsElement.firstChild) {\n\t\tsolutionButtonsElement.removeChild(solutionButtonsElement.firstChild);\n\t}\n}",
"function clearButtons() {\n const div = document.querySelector('.question__div');\n while (div.firstChild) {\n div.removeChild(div.firstChild);\n }\n }",
"function guessClearResetButtonsOff() {\n guessButton.disabled = false;\n clearButton.disabled = false;\n resetButton.disabled = false;\n }",
"function resetState(){\n nextButton.classList.add('hide')\n while (answerElement.firstChild) {\n answerElement.removeChild\n (answerElement.firstChild)\n }\n }",
"function setAsUnworked(classSelector) {\n $(\".button.\" + classSelector).addClass(\"unworkedClass\")\n }",
"function resetButtons() {\n hitButton.disabled = true;\n standButton.disabled = true;\n continueButton.disabled = false;\n }",
"function buttonsRed() {\n for (let i = 0; i < all_buttons.length; i++) {\n all_buttons[i].classList.remove(all_buttons[i].classList[1]);\n all_buttons[i].classList.add('btn-danger');\n }\n}",
"convertButtons() {\n\t\t\t// if on the small design, or on the large design + white background\n\t\t\t// replace white buttons by blue ones\n\t\t\tif (\n\t\t\t\twindow.matchMedia('(max-width: 64rem)').matches ||\n\t\t\t\t(window.matchMedia('(min-width: 64rem)').matches &&\n\t\t\t\t\tthis.design === 'bow')\n\t\t\t)\n\t\t\t\tthis.querySelectorAll('.a-button--secondary--white').forEach(e => {\n\t\t\t\t\te.classList.replace(\n\t\t\t\t\t\t'a-button--secondary--white',\n\t\t\t\t\t\t'a-button--secondary'\n\t\t\t\t\t)\n\t\t\t\t})\n\n\t\t\t// if on large design + blue background, replace secondary blue by white buttons\n\t\t\tif (\n\t\t\t\twindow.matchMedia('(min-width: 64rem)').matches &&\n\t\t\t\tthis.design === 'wob'\n\t\t\t)\n\t\t\t\tthis.querySelectorAll('.a-button--secondary').forEach(e => {\n\t\t\t\t\te.classList.replace(\n\t\t\t\t\t\t'a-button--secondary',\n\t\t\t\t\t\t'a-button--secondary--white'\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t}",
"function reset() {\n\t\t// go to next question\n\t\tgame.qIndex++;\n\n\t\tif (game.qIndex < game.qArray.length) {\n\t\t\t//remove classes for styling answers\n\t\t\t$(\".answerArea\").find(\".correct\").toggleClass(\"correct\");\n\t\t\t$(\".answerArea\").find(\".selected\").toggleClass(\"selected\");\n\t\t\t//reset time\n\t\t\tgame.timeLeft = 8;\n\t\t\t//reset answer\n\t\t\tgame.currentAnswer = \"\";\n\t\t\t//go to next question\n\t\t\t// game.qIndex++;\n\t\t\t//toggle clock back onto page\n\t\t\t$(\".top-middle\").toggleClass(\"hide\")\n\t\t\t//hide right and wrong divs\n\t\t\t$(\".right\").addClass(\"hide\");\n\t\t\t$(\".wrong\").addClass(\"hide\");\n\t\t\tnewQ();\n\t\t} else {\n\t\t\tgameOver()\n\t\t}\n\t}",
"function reform() {\n ex1.classList.remove(\"chcolor\");\n}",
"function removeAcceptedUserInputHint() {\n var activeLabels = document.querySelectorAll(\".active\");\n activeLabels.forEach((ele) => {\n ele.classList.remove(\"active\");\n });\n}",
"function renderAnswerButtons(messageContent, messageId, question) {\n if (question.canManageQuestionState) {\n var helpfulCount = question.numHelpful;\n var maxHelpfulCount = question.totalNumHelpful;\n var helpfulCountRemaining = maxHelpfulCount-helpfulCount;\n var $parentHeader = $j(messageContent).closest('.j-thread-post').find('header');\n var $dotted = $parentHeader.find('.j-dotted-star');\n var button = $j(messageContent).find('.jive-thread-reply-btn');\n\n if ($parentHeader.find('.j-dotted-star').length == 0)\n $parentHeader.append('<span class=\"j-dotted-star j-ui-elem\"/>');\n\n if (button.length == 0) {\n $j(messageContent.append($j(\"<div>\").addClass('jive-thread-reply-btn')));\n button = $j(messageContent).find('.jive-thread-reply-btn');\n }\n\n var $helpfulStar = $parentHeader.find('.j-helpful-star');\n button.empty();\n $dotted.unbind();\n // First two conditionals: answer already marked.\n if (question.correctAnswer && messageId == question.correctAnswer.ID) {\n button.append(jive.discussions.soy.qUnmarkAsCorrect({question:question, i18n:i18n}));\n button.find('.jive-thread-reply-btn-correct-unmark').click(function() {\n questionSourceCallback.unMarkAsCorrect(messageId, that.renderAll);\n return false;\n });\n }\n else if (question.helpfulAnswers && (containsAnswer(question.helpfulAnswers, messageId))) {\n button.append(jive.discussions.soy.qUnmarkAsHelpful({question:question, i18n:i18n}));\n button.find('.jive-thread-reply-btn-helpful-unmark').click(function() {\n questionSourceCallback.unMarkAsHelpful(messageId, that.unMarkAsHelpful.bind(that, $j(button)));\n return false;\n });\n $helpfulStar.click(function(e) {\n questionSourceCallback.markAsCorrect(messageId, that.renderAll);\n e.preventDefault();\n })\n }\n // Answer not marked.\n else {\n if (question.questionState!='resolved' &&\n !(question.helpfulAnswers && (containsAnswer(question.helpfulAnswers, messageId)))) {\n button.append(jive.discussions.soy.qMarkAsCorrect({question:question, i18n:i18n}));\n button.find('.jive-thread-reply-btn-correct').add($helpfulStar).click(function() {\n questionSourceCallback.markAsCorrect(messageId, function(question) {\n that.renderAll(question);\n jive.dispatcher.dispatch(\"trial.updatePercentComplete\");\n });\n return false;\n });\n }\n if (helpfulCountRemaining>0) {\n button.append(jive.discussions.soy.qMarkAsHelpful({question:question, i18n:i18n}));\n button.find('.jive-thread-reply-btn-helpful').add($dotted).click(function() {\n questionSourceCallback.markAsHelpful(messageId, that.markAsHelpful.bind(that, $j(button)));\n return false;\n });\n\n }\n }\n\n\n\n\n\n }\n }",
"function disableMainPageButtons() {\n\t\t\tevents.forEach( ev => { \n\t\t\t\tev.button.mouseEnabled = false;\n\t\t\t\tev.button.cursor = \"default\";\n\t\t\t});\n\t\t\n\t\t\tcultures.forEach( cu => { \n\t\t\t\tcu.button.mouseEnabled = false;\n\t\t\t\tcu.button.cursor = \"default\";\n\t\t\t});\n\t\t\n\t\t\tself.aboutUsBtn.mouseEnabled = false;\n\t\t\tself.aboutUsBtn.cursor = \"default\";\n\t\t\n\t\t\tself.returnBtn.mouseEnabled = false;\n\t\t\tself.returnBtn.cursor = \"default\";\n\t\t}",
"function resetForms(){\r\n $('.user-col form').attr('data-mode', 'working');\r\n // $('.user-col fieldset, .user-col textarea').addClass('untouched');\r\n $('.pairwise-decision, .pairwise-guidelines').addClass('untouched');\r\n // $('.pairwise-reasoning').removeClass('untouched')\r\n $('.user-col input').prop('checked', false);\r\n $('.user-col textarea').val('');\r\n}",
"function removeUnderscores() {\n for (i = 0; i < 4; i++) {\n var catBtnText = $(\"#categoryBtn-\" + i).text();\n var formattedText = catBtnText.replace(/_/g, \" \");\n $(\"#categoryBtn-\" + i).text(formattedText);\n }\n }",
"function resetRightPanel() {\n //Get the question container\n var element = document.getElementsByClassName('questionElement');\n\n //Reset the dialog box with content suggesting to name the item displayed\n //correctly\n document.getElementsByClassName('tdialogue-box-text')[0].innerHTML =\n 'Give the correct name of the item dispalyed in the input box! Use the' +\n 'keypad on left side!';\n\n //Clear the previous item\n element[0].innerHTML = \"\";\n\n //Creating a question with new item\n createQuestion(element[0]);\n}",
"function resetSpellChecker()\r\n{\r\n\twith(currObj);\r\n\tcurrObj.resetAction();\r\n\t\r\n\tcurrObj.objToCheck.value = \"\";\r\n\tcurrObj.objToCheck.style.display = \"block\";\r\n\tcurrObj.objToCheck.disabled = false;\r\n\t\r\n\tif(currObj.spellingResultsDiv)\r\n\t{\r\n\t\tcurrObj.spellingResultsDiv.parentNode.removeChild(currObj.spellingResultsDiv);\r\n\t\tcurrObj.spellingResultsDiv = null;\r\n\t}\r\n\tif(spellingSuggestionsDiv)\r\n\t{\r\n\t\tspellingSuggestionsDiv.parentNode.removeChild(spellingSuggestionsDiv);\r\n\t\tspellingSuggestionsDiv = null;\r\n\t}\r\n\tcurrObj.statusSpan.style.display = \"none\";\r\n\t\r\n}",
"function closeOtherReplyForms() {\n var reply_forms = document.getElementsByClassName('reply-form');\n var i;\n for (i = 0; i <reply_forms.length; i++) {\n reply_forms[i].innerHTML = \"\";\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`_readBlankNodeTail` reads the end of a blank node | _readBlankNodeTail(token) {
if (token.type !== ']') return this._readBlankNodePunctuation(token); // Store blank node quad
if (this._subject !== null) this._emit(this._subject, this._predicate, this._object, this._graph); // Restore the parent context containing this blank node
const empty = this._predicate === null;
this._restoreContext(); // If the blank node was the subject, continue reading the predicate
if (this._object === null) // If the blank node was empty, it could be a named graph label
return empty ? this._readPredicateOrNamedGraph : this._readPredicateAfterBlank; // If the blank node was the object, restore previous context and read punctuation
else return this._getContextEndReader();
} | [
"function NilNode() {\n}",
"_readRDFStarTail(token) {\n if (token.type !== '>>') return this._error(`Expected >> but got ${token.type}`, token); // Read the quad and restore the previous context\n\n const quad = this._quad(this._subject, this._predicate, this._object, this._graph || this.DEFAULTGRAPH);\n\n this._restoreContext(); // If the triple was the subject, continue by reading the predicate.\n\n\n if (this._subject === null) {\n this._subject = quad;\n return this._readPredicate;\n } // If the triple was the object, read context end.\n else {\n this._object = quad;\n return this._getContextEndReader();\n }\n }",
"function is_node_empty(node, regardBrAsEmpty) {\n if (regardBrAsEmpty === void 0) { regardBrAsEmpty = true; }\n if (!node)\n return false;\n return (node.nodeType == Node.TEXT_NODE && /^[\\s\\r\\n]*$/.test(node.nodeValue)) ||\n (node.nodeType == Node.COMMENT_NODE) ||\n (regardBrAsEmpty && node.nodeName == \"BR\");\n }",
"lesx_parseEmptyExpression() {\n var node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc);\n return this.finishNodeAt(node, 'LesxEmptyExpression', this.start, this.startLoc);\n }",
"tail() {\n return null;\n }",
"function paddingBlankHTML(node){if(!isVoid(node)&&!nodeLength(node)){node.innerHTML=blankHTML;}}",
"function TermTail() {\n var node = new Node('TermTail');\n p.child.push(node);\n p = node;\n if (word == '*' || word == '/') {\n p.operator = word;\n word = nextWord();\n if (!Factor()) {\n return false;\n } else {\n p = node;\n return TermTail();\n }\n }\n return true;\n }",
"_readRDFStarTailOrGraph(token) {\n if (token.type !== '>>') {\n // An entity means this is a quad (only allowed if not already inside a graph)\n if (this._supportsQuads && this._graph === null && (this._graph = this._readEntity(token)) !== undefined) return this._readRDFStarTail;\n return this._error(`Expected >> to follow \"${this._object.id}\"`, token);\n }\n\n return this._readRDFStarTail(token);\n }",
"function hc_nodelistindexgetlengthofemptylist() {\n var success;\n var doc;\n var emList;\n var emNode;\n var textNode;\n var textList;\n var length;\n doc = load(\"hc_staff\");\n emList = doc.getElementsByTagName(\"em\");\n emNode = emList.item(2);\n textNode = emNode.firstChild;\n\n textList = textNode.childNodes;\n\n length = textList.length;\n\n assertEquals(\"length\",0,length);\n \n}",
"function MODIFIER_NO_TAIL$static_(){LinkListBEMEntities.MODIFIER_NO_TAIL=( LinkListBEMEntities.BLOCK.createModifier(\"no-tail\"));}",
"eof() {\n return this.index >= this.tokens.length;\n }",
"function ELEMENT_TAIL$static_(){LinkListBEMEntities.ELEMENT_TAIL=( LinkListBEMEntities.BLOCK.createElement(\"tail\"));}",
"getTail() {\n return this._tail;\n }",
"function checkEmpty(node) {\n\n if (node.value === \"\") {\n\n node.style.borderColor = \"red\";\n\n } else {valid++};\n\n}",
"function ExprTail() {\n var node = new Node('ExprTail');\n p.child.push(node);\n p = node;\n if (word == '+' || word == '-') {\n p.operator = word;\n word = nextWord();\n if (!Term()) {\n return false;\n } else {\n p = node;\n return ExprTail();\n }\n }\n return true;\n }",
"function readNode( lines, firstline, list ) {\n\n\t\t\tvar node = { name: '', type: '', frames: [] };\n\t\t\tlist.push( node );\n\n\t\t\t// parse node type and name\n\n\t\t\tvar tokens = firstline.split( /[\\s]+/ );\n\n\t\t\tif ( tokens[ 0 ].toUpperCase() === 'END' && tokens[ 1 ].toUpperCase() === 'SITE' ) {\n\n\t\t\t\tnode.type = 'ENDSITE';\n\t\t\t\tnode.name = 'ENDSITE'; // bvh end sites have no name\n\n\t\t\t} else {\n\n\t\t\t\tnode.name = tokens[ 1 ];\n\t\t\t\tnode.type = tokens[ 0 ].toUpperCase();\n\n\t\t\t}\n\n\t\t\tif ( nextLine( lines ) !== '{' ) {\n\n\t\t\t\tconsole.error( 'THREE.BVHLoader: Expected opening { after type & name' );\n\n\t\t\t}\n\n\t\t\t// parse OFFSET\n\n\t\t\ttokens = nextLine( lines ).split( /[\\s]+/ );\n\n\t\t\tif ( tokens[ 0 ] !== 'OFFSET' ) {\n\n\t\t\t\tconsole.error( 'THREE.BVHLoader: Expected OFFSET but got: ' + tokens[ 0 ] );\n\n\t\t\t}\n\n\t\t\tif ( tokens.length !== 4 ) {\n\n\t\t\t\tconsole.error( 'THREE.BVHLoader: Invalid number of values for OFFSET.' );\n\n\t\t\t}\n\n\t\t\tvar offset = new THREE.Vector3(\n\t\t\t\tparseFloat( tokens[ 1 ] ),\n\t\t\t\tparseFloat( tokens[ 2 ] ),\n\t\t\t\tparseFloat( tokens[ 3 ] )\n\t\t\t);\n\n\t\t\tif ( isNaN( offset.x ) || isNaN( offset.y ) || isNaN( offset.z ) ) {\n\n\t\t\t\tconsole.error( 'THREE.BVHLoader: Invalid values of OFFSET.' );\n\n\t\t\t}\n\n\t\t\tnode.offset = offset;\n\n\t\t\t// parse CHANNELS definitions\n\n\t\t\tif ( node.type !== 'ENDSITE' ) {\n\n\t\t\t\ttokens = nextLine( lines ).split( /[\\s]+/ );\n\n\t\t\t\tif ( tokens[ 0 ] !== 'CHANNELS' ) {\n\n\t\t\t\t\tconsole.error( 'THREE.BVHLoader: Expected CHANNELS definition.' );\n\n\t\t\t\t}\n\n\t\t\t\tvar numChannels = parseInt( tokens[ 1 ] );\n\t\t\t\tnode.channels = tokens.splice( 2, numChannels );\n\t\t\t\tnode.children = [];\n\n\t\t\t}\n\n\t\t\t// read children\n\n\t\t\twhile ( true ) {\n\n\t\t\t\tvar line = nextLine( lines );\n\n\t\t\t\tif ( line === '}' ) {\n\n\t\t\t\t\treturn node;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tnode.children.push( readNode( lines, line, list ) );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}",
"getLast() {\n if (!this.head) {\n return null;\n }\n let node = this.head;\n while (node) {\n // If next is null, then we are at the last node\n if (!node.next) {\n return node;\n }\n node = node.next;\n }\n }",
"function fill_missing_child_nodes_right_sibling(node)\n{\n if (node === null) \n {\n return;\n }\n \n var numberOfChildren = node.children.length;\n var lastNodeIndex = numberOfChildren - 1;\n \n if (lastNodeIndex >= 0)\n {\n if (node.children[lastNodeIndex].right === null)\n {\n node.children[lastNodeIndex].right = find_right_sibling(node);\n }\n for (var i=0; i < numberOfChildren; i++)\n {\n fill_missing_child_nodes_right_sibling(node.children[i]); \n }\n }\n}",
"function blank() {\n putstr(padding_left(seperator, seperator, sndWidth));\n putstr(\"\\n\");\n }",
"parseUnknown(tokenizer) {\n const start = tokenizer.advance();\n let end;\n if (start === null) {\n return null;\n }\n while (tokenizer.currentToken &&\n tokenizer.currentToken.is(token_1.Token.type.boundary)) {\n end = tokenizer.advance();\n }\n return this.nodeFactory.discarded(tokenizer.slice(start, end), tokenizer.getRange(start, end));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Selector caching. See for more details | function Selector_Cache() {
var collection = {};
function get_from_cache( selector ) {
if ( undefined === collection[ selector ] ) {
collection[ selector ] = $( selector );
}
return collection[ selector ];
};
return { get: get_from_cache };
} | [
"_getOptionSelector(widgetInstance){\n return this.cache.selector[widgetInstance.id] = this.cache.selector[widgetInstance.id] || widgetInstance._getOptionSelector({ enableCaching: true });\n }",
"function createSelector() {\n for (var _len7 = arguments.length, args = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {\n args[_key7] = arguments[_key7];\n }\n\n var selector = _reselect.createSelector.apply(undefined, args);\n selector.$$factory = function () {\n return _reselect.createSelector.apply(undefined, args);\n };\n return selector;\n}",
"function get_selector(){\n var selector = '';\n\n $.each(fundamental_vars.filteredSelector,function(key,value){\n selector += value;\n });\n\n return selector;\n}",
"function computeSelector(id, css) {\n var selectoPlaceholderRegexp = /__jsx-style-dynamic-selector/g; // Sanitize SSR-ed CSS.\n // Client side code doesn't need to be sanitized since we use\n // document.createTextNode (dev) and the CSSOM api sheet.insertRule (prod).\n\n if (typeof window === 'undefined') {\n css = sanitize(css);\n }\n\n var idcss = id + css;\n\n if (!cache[idcss]) {\n cache[idcss] = css.replace(selectoPlaceholderRegexp, id);\n }\n\n return cache[idcss];\n}",
"function Selector() {\n\t\tthis.rules = {};\n\t}",
"function $Q(selector) {\n\n //declare events:\n\n console.log(selector);\n\n var query = [];\n\n //handle selector / selection of objects:\n\n if (typeof selector !== 'string') {\n\n if (selector instanceof Array) {\n\n } else {\n\n\n }\n\n } else {\n\n\n if (selector && selector !== '*') {\n\n var s = selector || '';\n\n console.info('selector:' + s);\n\n\n var mainSelector = $Q.before('[', s).trim(),\n msfChar = mainSelector.substring(0, 1);\n\n var __targetClassName = \"*\";\n\n var output = [];\n\n var cleanSelectorString = function(str) {\n return str.replace(\",\", \"\");\n };\n\n switch (msfChar.toLowerCase()) {\n case \".\":\n\n console.info('Selecting by \".\" or class');\n\n __targetClassName = cleanSelectorString($Q.after('.', mainSelector));\n\n console.info('Target class is:' + __targetClassName);\n\n break;\n\n case \"*\":\n\n console.info('Selecting by \"*\" or ANY object in the library instance');\n\n __targetClassName = \"*\";\n\n break;\n\n }\n\n var criterion = $Q.between('[', ']', s),\n cparts = criterion.split('=');\n\n var __targetGroup = \"*\",\n __targetName = \"*\";\n\n var getParts = function() {\n\n if (cparts.length >= 2) {\n\n switch (cparts[0].toLowerCase()) {\n\n case \"name\":\n\n //get all objects according to name=name\n\n console.log('Q():Detected parts in selector:' + jstr(cparts));\n\n __targetName = cleanSelectorString(cparts[1]);\n\n break;\n\n case \"group\":\n\n console.log('Q():Detected parts in selector:' + jstr(cparts));\n\n __targetGroup = cleanSelectorString(cparts[1]);\n\n break;\n\n }\n\n }\n\n if (cparts.length >= 4) {\n\n cparts[2] = cparts[2].replace(\",\", \"\");\n\n switch (cparts[2].toLowerCase()) {\n\n case \"name\":\n\n //get all objects according to name=name\n\n console.log('Q():Detected parts in selector:' + jstr(cparts));\n\n __targetName = cleanSelectorString(cparts[3]);\n\n break;\n\n case \"group\":\n\n console.log('Q():Detected parts in selector:' + jstr(cparts));\n\n __targetGroup = cleanSelectorString(cparts[3]);\n\n break;\n\n }\n\n }\n\n };\n\n getParts(cparts);\n\n query = Gamelab.select(__targetClassName, __targetName, __targetGroup);\n\n } else if (selector == '*') {\n\n query = Gamelab.all();\n\n }\n\n }\n\n\n query.each = function(callback) {\n\n var objects = [];\n\n for (var x = 0; x < this.length; x++) {\n if (typeof x == 'number') {\n\n callback(x, this[x]);\n }\n\n }\n\n\n };\n\n query.on = function(evt_key, selectorObject, controller_ix, callback) //handle each event such as on('collide') OR on('stick_left_0') << first controller stick_left\n {\n\n if (typeof evt_key == 'function' && typeof selectorObject == 'function') {\n //this is a special pattern of if(f() == true){ runFunction(); };\n\n var boolTrigger = evt_key,\n boolCall = selectorObject,\n\n boolEvent = new Gamelab.BoolEvent().On(boolTrigger).Call(boolCall);\n\n }\n\n\n var criterion = $Q.between('[', ']', evt_key);\n\n if (criterion.indexOf('===') >= 0) {\n criterion = criterion.replace('===', '=');\n }\n\n if (criterion.indexOf('==') >= 0) {\n criterion = criterion.replace('==', '=').replace('==', 0);\n }\n\n var cparts = criterion.split('=');\n\n var __targetGroup = \"*\",\n __targetName = \"*\";\n\n if (evt_key.indexOf('[') >= 0) {\n evt_key = $Q.before('[', evt_key).trim();\n\n }\n\n\n var padding = 0;\n\n //if controller_ix is function, and callback not present, then controller_ix is the callback aka optional argument\n\n if (controller_ix && typeof controller_ix == 'function' && !callback) {\n callback = controller_ix;\n controller_ix = 0;\n }\n\n //optional argument: if controller_ix is function, and callback not present, then callback is selectorObject\n\n if (selectorObject && typeof selectorObject == 'function' && !callback) {\n\n callback = selectorObject;\n\n selectorObject = $Q('*');\n\n controller_ix = 0;\n };\n\n var evt_profile = {};\n\n //which controller?\n\n evt_profile.cix = controller_ix;\n\n //Need the control key: 'left_stick', 'button_0', etc..\n\n evt_profile.evt_key = evt_key;\n\n if ($Q.contains_any(['stick', 'button', 'click', 'key'], evt_profile.evt_key)) {\n\n var button_mode = evt_profile.evt_key.indexOf('button') >= 0;\n\n Gamelab.GamepadAdapter.on(evt_profile.evt_key, 0, function(x, y) {\n\n callback(x, y);\n\n });\n\n console.info('detected input event key in:' + evt_profile.evt_key);\n\n console.info('TODO: rig events');\n\n }\n\n //TODO: test collision events:\n else if ($Q.contains_any(['collide', 'collision', 'hit', 'touch'], evt_profile.evt_key)) {\n\n // console.info('Rigging a collision event');\n\n // console.info('detected collision event key in:' + evt_profile.evt_key);\n\n // console.info('TODO: rig collision events');\n\n this.each(function(ix, item1) {\n\n // console.info('Collision Processing 1:' + item1.name);\n // console.info('Collision Processing 1:' + item1.type);\n\n selectorObject.each(function(iy, item2) {\n\n // console.info('Collision Processing 2:' + item2.name);\n // console.info('Collision Processing 2:' + item2.type);\n\n if (typeof(item1.onUpdate) == 'function') {\n\n var update = function(sprite) {\n\n console.log('Box collide::' + jstr([this, item2]));\n\n if (this.hasBoxCollision(item2, padding)) {\n\n callback(this, item2);\n\n };\n\n };\n\n item1.onUpdate(update);\n\n }\n\n\n });\n\n });\n\n\n } else {\n console.info('Rigging a property event');\n\n //TODO: test property-watch events:\n\n console.info('detected property threshhold event key in:' + evt_profile.evt_key);\n\n console.info('TODO: rig property events');\n\n var condition = \"_\",\n key = criterion || evt_profile.evt_key;\n\n if (key.indexOf('[') >= 0 || key.indexOf(']') >= 0) {\n key = $Q.between('[', ']', key);\n\n }\n\n var evt_parts = [];\n\n var run = function() {\n console.error('Sprite property check was not set correctly');\n\n };\n\n if (key.indexOf('>=') >= 0) {\n condition = \">=\";\n\n\n } else if (key.indexOf('<=') >= 0) {\n condition = \"<=\";\n } else if (key.indexOf('>') >= 0) {\n condition = \">\";\n } else if (key.indexOf('<') >= 0) {\n condition = \"<\";\n } else if (key.indexOf('=') >= 0) {\n condition = \"=\";\n }\n\n evt_parts = key.split(condition);\n\n for (var x = 0; x < evt_parts.length; x++) {\n evt_parts[x] = evt_parts[x].replace('=', '').replace('=', '').trim(); //remove any trailing equals and trim()\n\n }\n\n var mykey, number;\n\n // alert(evt_parts[0]);\n\n try {\n\n mykey = evt_parts[0];\n\n number = parseFloat(evt_parts[1]);\n\n } catch (e) {\n console.log(e);\n }\n\n console.info('Gamelab:Processing condition with:' + condition);\n\n switch (condition) {\n\n case \">=\":\n\n\n run = function(obj, key) {\n if (obj[key] >= number) {\n callback();\n }\n };\n\n break;\n\n case \"<=\":\n\n run = function(obj, key) {\n if (obj[key] <= number) {\n callback();\n }\n };\n\n break;\n\n\n case \">\":\n\n run = function(obj, key) {\n if (obj[key] > number) {\n callback();\n }\n };\n\n break;\n\n case \"<\":\n\n run = function(obj, key) {\n if (obj[key] < number) {\n callback();\n }\n };\n\n break;\n\n case \"=\":\n\n run = function(obj, key) {\n if (obj[key] == number) {\n callback();\n }\n };\n\n break;\n\n }\n\n\n /************\n * Attach update to each member\n *\n * **************/\n\n var keys = mykey.split('.'),\n propkey = \"\";\n\n this.each(function(ix, item) {\n\n var object = {};\n\n if (keys.length == 1) {\n object = item;\n\n propkey = mykey;\n\n } else if (keys.length == 2) {\n object = item[keys[0]];\n\n propkey = keys[1];\n\n\n } else if (keys.length == 3) {\n object = item[keys[0]][keys[1]];\n\n propkey = keys[2];\n\n } else {\n console.error(\":length of '.' notation out of range. We use max length of 3 or prop.prop.key.\");\n\n }\n\n if (typeof item.onUpdate == 'function') {\n\n\n var spr = item;\n\n item.onUpdate(function(sprite) {\n\n run(object, propkey);\n\n });\n\n }\n\n });\n\n }\n\n };\n\n\n return query;\n\n}",
"createSelector() {\n\t\t// Add a selector icon and scales it\n\t\tthis.selector = this.add.image(32, 32, 'selector');\n\t\tthis.selector.alpha = 0;\n\n\t\t// Listen to mouse movement\n\t\tthis.input.on('pointermove', function (pointer) {\n\t\t\t// Grabs mouse position & divide by 64 (To get index of array)\n\t\t\tlet mouseY = Math.floor(pointer.y / 64);\n\t\t\tlet mouseX = Math.floor(pointer.x / 64);\n\n\t\t\t// Check if position available\n\t\t\tif (this.checkPosition(mouseY, mouseX)) {\n\t\t\t\t// If true, update cursor position (32 to center)\n\t\t\t\tthis.selector.setPosition(mouseX * 64 + 32, mouseY * 64 + 32);\n\t\t\t\tthis.selector.alpha = 0.9;\n\t\t\t} else {\n\t\t\t\t// If false\n\t\t\t\tthis.selector.alpha = 0;\n\t\t\t}\n\t\t}.bind(this));\n\t}",
"_initSelectors () {\n this.tabAttribute = 'data-rvt-tab'\n this.panelAttribute = 'data-rvt-tab-panel'\n\n this.tabSelector = `[${this.tabAttribute}]`\n this.panelSelector = `[${this.panelAttribute}]`\n this.tablistSelector = '[data-rvt-tablist]'\n this.initialTabSelector = '[data-rvt-tab-init]'\n }",
"getSelectors() {\n var selectors = []\n\n // First check that the ruleset exists and there are selectors in it\n if (this.state.rulesets.length > 0 && this.state.rulesets[this.state.currentRuleset]) {\n var i = -1\n\n // Iterate through each selector in the ruleset\n for (var selector of this.state.rulesets[this.state.currentRuleset]) {\n i++\n\n if (selector != \"placeholder\") { // If its not a placeholder selector then display\n\n var parameters = this.getSelectorParameters(selector, i) // Get the JSX for the parameters in the selector\n \n var rules = this.getRules(selector, i) // Get the JSX for the rules in the selector\n \n // Condition to check if adding a new selector would overflow the rule selector window\n var allowAdding = this.state.rulesets[this.state.currentRuleset][i].parameters.length <= Math.floor((window.innerWidth*0.7 - 350) / 100) && this.state.rulesets[this.state.currentRuleset][i].parameters[0] != \"all\"\n \n selectors.push( // Format the selector component\n <div>\n <button class=\"accordionSelector\" onClick={this.showPanel}>\n <div class=\"selectorSection1\">\n <span class=\"selectText\">Select</span>\n <select id=\"select\" value={selector.select} id={i} onChange={this.selectorSelectChange} class=\"selectorParameter\">\n <option value=\"\" selected disabled hidden></option>\n <option value=\"type\">Type</option>\n <option value=\"day\">Day</option>\n </select>\n </div>\n <div class=\"selectorSection2\">\n {parameters}\n <span class=\"addParameter\" onClick={this.addSelectorParameter} id={i} style={allowAdding ? {color: \"green\"} : {color: \"gray\"}}>+</span>\n <span class=\"removeParameter\" onClick={this.removeSelectorParameter} id={i} style={parameters.length > 1 ? {color: \"red\"} : {color: \"gray\"}}>-</span>\n </div>\n <span class=\"xicon\" id={i} onClick={this.removeSelector}>✕</span>\n </button>\n <div class=\"panel\" style={{\"padding-left\": \"0px\"}}>{rules}</div>\n </div>\n )\n }\n }\n }\n\n if (selectors.length == 0) { // If there are no selectors just add text saying that\n selectors.push(\n <div id=\"noIngredients\">\n <i style={{color: \"#ccc\"}}>There are no selectors here. Click \"Add Selectors\" to make new rules.</i>\n </div>\n )\n }\n\n return selectors\n }",
"function startLoad() {\n selector = new Selector();\n}",
"function selectorsFromGlobalMetadata(selectors, outputCtx) {\n if (selectors.length > 1 || (selectors.length == 1 && selectors[0].value)) {\n const selectorStrings = selectors.map(value => value.value);\n selectorStrings.some(value => !value) &&\n error('Found a type among the string selectors expected');\n return outputCtx.constantPool.getConstLiteral(o.literalArr(selectorStrings.map(value => o.literal(value))));\n }\n if (selectors.length == 1) {\n const first = selectors[0];\n if (first.identifier) {\n return outputCtx.importExpr(first.identifier.reference);\n }\n }\n error('Unexpected query form');\n return o.NULL_EXPR;\n}",
"function getSanitizedSelector (selector) {\n return selector\n .replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); })\n .replace(/\\[|]/g, \"\");\n }",
"function selectorFactory(dispatch, mapStateToProps, mapDispatchToProps) {\n //cache the DIRECT INPUT for the selector\n //the store state\n let state\n //the container's own props\n let ownProps\n\n //cache the itermediate results from mapping functions\n //the derived props from the state\n let stateProps\n //cache the derived props from the store.dispatch\n let dispatchProps\n\n //cache the output\n //the return merged props(stateProps + dispatchProps + ownProps) to be injected to wrappedComponent\n let mergedProps\n\n // the source selector is memorizable.\n return function selector(nextState, nextOwnProps) {\n //before running the actual mapping function, compare its arguments with the previous one\n const propsChanged = !shallowEqual(nextOwnProps, ownProps)\n const stateChanged = !strictEqual(nextState, state)\n\n state = nextState\n ownProps = nextOwnProps\n \n //calculate the return mergedProps based on different scenarios \n //to MINIMIZE the call to actual mapping functions\n //notice: the mapping function itself can be optimized by Reselect, but it is not the concern here\n \n //case 1: both state in redux and own props change\n if (propsChanged && stateChanged) {\n //derive new props based on state\n stateProps = mapStateToProps(state, ownProps)\n //since the ownProps change, update dispatch callback if it depends on props\n if (mapDispatchToProps.length !== 1) dispatchProps = mapDispatchToProps(dispatch, ownProps)\n //merge the props\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps)\n return mergedProps\n }\n\n //case 2: only own props changes\n if (propsChanged) {\n //only update stateProps and dispatchProps if they rely on ownProps\n if (mapStateToProps.length !== 1) stateProps = mapStateToProps(state, ownProps) //it just call the mapping function\n if (mapDispatchToProps.length !== 1) dispatchProps = mapDispatchToProps(dispatch, ownProps)\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps)\n return mergedProps\n }\n\n //case 3: only store state changes\n // 1.since stateProps depends on state so must run mapStateToProps again\n // 2.for dispatch, since store.dispatch and ownProps remain the same, no need to update\n if (stateChanged) {\n const nextStateProps = mapStateToProps(state, ownProps)\n const statePropsChanged = !shallowEqual(nextStateProps, stateProps)\n stateProps = nextStateProps\n //if stateProps changed, update mergedProps by calling the mergeProps function\n if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps)\n return mergedProps\n }\n\n //case 4: no change, return the cached result if no change in input\n return mergedProps;\n }\n}",
"function computeSelector(element) {\n // If the element has an id and is the first element to have this ID,\n // Use the id instead of xpath.\n if (element.id && document.getElementById(element.id) == element) {\n return \"#\" + element.id;\n }\n // Same thing for class name\n if (element.className) {\n let selector = element.tagName + \".\" +element.className.replace(/ /g, \".\");\n if (document.querySelector(selector) == element) {\n return selector;\n }\n }\n let list = [];\n while(element.parentNode && element.parentNode.nodeType == document.ELEMENT_NODE) {\n let parent = element.parentNode;\n let idx = Array.indexOf(parent.children, element) + 1;\n let tagName = element.tagName.toLowerCase();\n if (idx > 1) {\n list.push(tagName + \":nth-child(\" + idx + \")\");\n } else {\n list.push(tagName);\n }\n element = parent;\n }\n return list.reverse().join(\">\");\n}",
"function query(selector) {\n return Array.prototype.slice.call(document.querySelectorAll(selector));\n }",
"function $$(cssSelector) {\n return $(cssSelector, gamesolverDriver);\n }",
"function ninjaBabySelector() {\n var babyNinja = $('#baby-ninja');\n return babyNinja;\n // return $('#baby-ninja');;\n}",
"setSelector(selectorText){\n if (typeof selectorText !== \"string\") throw new TypeError(\"Your selectorText is not a string\");\n let head = super.getHead();\n\n this.patch({\n action: VirtualActions.PATCH_REPLACE,\n start: head.startOffset,\n end: head.endOffset,\n value: selectorText,\n patchDelta: selectorText.length - head.endOffset\n })\n }",
"function escapeSelector(sel) {\n return sel.replace(/[/$]/g, '\\\\$&');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a map from a type of attention to the CLs that needs that attention from the user. | getCategoryMap() {
var result = new utils.Map();
var user = this.getAccount();
var onlyAttentionSet = this.options_.onlyAttentionSet;
this.data_.forEach(function(cl) {
var attention
if (onlyAttentionSet !== config.OPTION_DISABLED) {
attention = cl.getCategoryFromAttentionSet(user);
} else {
attention = cl.getCategory(user);
}
if (!result.has(attention)) {
result.put(attention, []);
}
var cls = result.get(attention);
if (!cls.includes(cl)) {
cls.push(cl);
}
});
return result;
} | [
"get_user_input() {\n return new Map();\n }",
"fetchAttributes() {\n let result = {};\n Object.values(this.attributes).map(attribute => {\n result[attribute.type] = Utility.getInstance().clone(attribute);\n })\n this.traits.map(trait => {\n Object.values(trait.fetchAttributes()).map(attribute => {\n result[attribute.type].add(attribute.get());\n })\n });\n return result;\n }",
"function createMap(actor_list, actor, actors_map) {\n var actorListWithout = actor_list.filter(function (item) {\n return item !== actor;\n });\n if (actors_map[actor] !== undefined) {\n for (var y = 0; y < actorListWithout.length; y++) {\n if (!mapping_actors(actors_map, actor, actorListWithout[y])) {\n actors_map[actor].push(actorListWithout[y]);\n }\n }\n }\n else {\n actors_map[actor] = actorListWithout;\n }\n return {actorListWithout: actorListWithout, y: y};\n}",
"function discoverTypes () {\n // rdf:type properties of subjects, indexed by URI for the type.\n\n const types = {}\n\n // Get a list of statements that match: ? rdfs:type ?\n // From this we can get a list of subjects and types.\n\n const subjectList = kb.statementsMatching(\n undefined,\n UI.ns.rdf('type'),\n tableClass, // can be undefined OR\n sourceDocument\n ) // can be undefined\n\n // Subjects for later lookup. This is a mapping of type URIs to\n // lists of subjects (it is necessary to record the type of\n // a subject).\n\n const subjects = {}\n\n for (let i = 0; i < subjectList.length; ++i) {\n const type = subjectList[i].object\n\n if (type.termType !== 'NamedNode') {\n // @@ no bnodes?\n continue\n }\n\n const typeObj = getTypeForObject(types, type)\n\n if (!(type.uri in subjects)) {\n subjects[type.uri] = []\n }\n\n subjects[type.uri].push(subjectList[i].subject)\n typeObj.addUse()\n }\n\n return [subjects, types]\n }",
"allNotions () {\n return _.flatten(this.notions.map(c => c.entities))\n }",
"get renderedSuggestions() {\n const keys = [];\n this.suggestionMap.forEach((value, key) => {\n keys.push(key);\n });\n if (this.moreResults && this.moreResultsItem) {\n keys.push(this.moreResultsItem);\n }\n return keys;\n }",
"function create_supp_sec_search_parameter_MAP() {\n var map = {};\n var glblSearchEl = document.getElementById('globalsearch');\n var glblSearchInputEls = glblSearchEl.querySelectorAll('input');\n for (var i = 0; i < glblSearchInputEls.length; i++) {\n\n if (glblSearchInputEls[i].getAttribute('type') == 'hidden') {\n var map_key = glblSearchInputEls[i].getAttribute('name');\n var map_value = glblSearchInputEls[i].value;\n map[map_key] = map_value;\n }\n };\n return map;\n }",
"function get_map_of_context_values(context_map){\n contextVariableMap = new Map();\n if(context_map.length != 0){\n for(var i = 0; i < context_map.length; i++){\n var context_text = context_map[i];\n var temp = context_text.split(\"=\");\n if(temp.length == 2){\n contextVariableMap.set(temp[0].trim(), temp[1].trim());\n }\n }\n }\n}",
"function getPatientKnnAttributeDomains() {\r\n let knnAttributeDomains = {};\r\n\r\n for (let attribute of App.patientKnnAttributes) {\r\n knnAttributeDomains[attribute] = self.axes[attribute].domain;\r\n }\r\n\r\n return knnAttributeDomains;\r\n }",
"function extractMnemonics(allMaps) {\r\n\t\t\r\n\t\tvar mnemonics = {};\r\n\r\n\t\tfunction extract(maps) {\r\n\t\t\tvar name, map, i, j, b;\r\n\t\t\t\r\n\t\t\tfor (name in maps)\r\n\t\t\t\tif (maps.hasOwnProperty(name)) {\r\n\t\t\t\t\tmap = maps[name];\r\n\r\n\t\t\t\t\tfor (i = 0; i < map.length; ++i) {\r\n\t\t\t\t\t\tb = map[i];\r\n\t\t\t\t\t\tif (b !== null) {\r\n\r\n\t\t\t\t\t\t\tif (b.hasOwnProperty('m'))\r\n\t\t\t\t\t\t\t\tmnemonics[b.m] = true;\r\n\r\n\t\t\t\t\t\t\telse if (isArray(b))\r\n\t\t\t\t\t\t\t\tfor (j = 0; j < b.length; ++j)\r\n\t\t\t\t\t\t\t\t\tmnemonics[b[j].m] = true;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t}\r\n\r\n\t\textract(allMaps.maps);\r\n\t\textract(allMaps.groups);\r\n\t\t\r\n\t\tfor (var k in allMaps.x87_maps)\r\n\t\t\tif (allMaps.x87_maps.hasOwnProperty(k))\r\n\t\t\t\textract(allMaps.x87_maps[k]);\r\n\r\n\t\treturn mnemonics;\r\n\t}",
"function buildMap(sheet) {\n var z = new zipFetch(sheet,[\"Category\",\"Description Match\"]);\n if( !z ) return;\n\n var tempCategoryHash = {};\n var map = [];\n var briefs = {};\n //var debug = '';\n for( var row=z.rowStart ; row < z.cache.length; ++row ) {\n var v = z.cache[row];\n if( !v[z.category] || v[z.category]=='' ) {\n break;\n }\n var descriptionMatchRaw = ''+v[z.descriptionMatch];\n var descriptionMatch = '';\n var descriptionReplace = null;\n if( descriptionMatchRaw ) {\n var descPairs = descriptionMatchRaw.replace(/\\\\,/g,\"CoMmA\").split(',');\n var descRegex = [];\n for( var i=0 ; i<descPairs.length ; ++i ) {\n var pair = descPairs[i].replace(/CoMmA/g,\",\").split('->');\n pair[0] = pair[0].trim();\n // This may seem weird, but we are escaping the description so that the later regex check finds only literally what the user typed. It does not accept actual regex in the description match.\n descRegex.push(regexEscape(pair[0]));\n descriptionReplace = descriptionReplace || {};\n descriptionReplace[pair[0].replace(/^/g,'').toLowerCase()] = pair[1] || pair[0]; \n }\n descriptionMatch = new RegExp( '('+descRegex.join('|')+')', 'i' );\n }\n // It is IMPORTANT that every category be represented, even if empty, so that the list of all categories created later will be complete.\n var record = {\"category\": v[z.category], \"descriptionMatch\": descriptionMatch, \"descriptionReplace\": descriptionReplace };\n tempCategoryHash[record.category] = record;\n map.push(record);\n }\n \n // This is a nasty hack to try to accomodate PayPal's habit of putting the words \"id:someCategory\" into their descriptions\n map.unshift(tempCategoryHash[\"Transfer\"]);\n \n return map;\n }",
"withInclinata(notes) {\n var staffPosition = notes[0].staffPosition,\n prevStaffPosition = notes[0].staffPosition;\n\n // it is important to advance by the width of the inclinatum glyph itself\n // rather than by individual note widths, so that any liquescents are spaced\n // the same as non-liquscents\n var advanceWidth =\n Glyphs.PunctumInclinatum.bounds.width * this.ctxt.glyphScaling;\n\n // now add all the punctum inclinatum\n for (var i = 0; i < notes.length; i++, prevStaffPosition = staffPosition) {\n var note = notes[i];\n\n if (note.liquescent & LiquescentType.Small)\n note.setGlyph(this.ctxt, GlyphCode.PunctumInclinatumLiquescent);\n else if (note.liquescent & LiquescentType.Large)\n // fixme: is the large inclinatum liquescent the same as the apostropha?\n note.setGlyph(this.ctxt, GlyphCode.Stropha);\n // fixme: some climaci in the new chant books end with a punctum quadratum\n // (see, for example, the antiphon \"Sancta Maria\" for October 7).\n else note.setGlyph(this.ctxt, GlyphCode.PunctumInclinatum);\n\n staffPosition = note.staffPosition;\n\n var multiple = Math.abs(prevStaffPosition - staffPosition);\n switch (multiple) {\n case 0:\n multiple = 1.1;\n break;\n default:\n multiple *= 2 / 3;\n break;\n }\n\n if (i > 0) this.x += advanceWidth * multiple;\n\n note.bounds.x = this.x;\n\n this.neume.addVisualizer(note);\n }\n\n return this;\n }",
"getLeaderModifiers() {\n const modList = [];\n m.LEADER_BONUS.availableCharacteristics.forEach((c) => {\n const mod = this.modifiers.getModifier(m.LEADER_BONUS, c);\n if (mod) modList.push(mod);\n });\n return modList;\n }",
"get listExperienceMap() {\n const result = [];\n for (let experience in ListExperience_1.ListExperience) {\n if (typeof ListExperience_1.ListExperience[experience] === 'number') {\n result.push(experience);\n }\n }\n return result;\n }",
"function calculateIndexOfCoincidences(letters) {\n const iocs = [];\n for (let i=1; i<=20; i++) {\n let freqs = getIthLetterFrequencies(letters, i);\n freqs = freqs.map((freq) => indexOfCoincidence(freq)); // Calculate ioc for each set of text\n iocs.push(freqs.reduce((accum, currentVal) => accum + currentVal)/i); // Push Average\n }\n return iocs;\n }",
"function buildWhitelistMap(context, whitelist) {\n var props = getPropertyNameMap(context);\n for (var i = 0; i < whitelist.length; i++) {\n props[whitelist[i]] = WHITELISTED;\n }\n return props;\n}",
"function KeyboardInfoPre(/**\n * Defines the type of event (BABYLON.KeyboardEventTypes)\n */type,/**\n * Defines the related dom event\n */event){var _this=_super.call(this,type,event)||this;_this.type=type;_this.event=event;_this.skipOnPointerObservable=false;return _this;}",
"function createTxMap(txs){\n\tvar map = new Map();\n\n\ttxs.forEach(function(tx){\n\t\t\tif (!map.has(tx.from)){\n\t\t\t\tmap.set(tx.from, 1);\n\t\t\t} else {\n\t\t\t\tmap.set(tx.from, map.get(tx.from)+1);\n\t\t\t}\n\t});\n\treturn map;\n}",
"static get observedAttributes() {\n // note: piggy backing on this to ensure we're finalized.\n this.finalize();\n const attributes = [];\n // Use forEach so this works even if for/of loops are compiled to for loops\n // expecting arrays\n this._classProperties.forEach((v, p) => {\n const attr = this._attributeNameForProperty(p, v);\n if (attr !== undefined) {\n this._attributeToPropertyMap.set(attr, p);\n attributes.push(attr);\n }\n });\n return attributes;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check the length of item name and add 3 dots if too long | checkName(item) {
var name = item.name;
if(name.length > 28) {
return name.substr(0,28)+'...';
} else {
return name;
}
} | [
"function shortenName(name){\n var split, partA, partB, finalName;\n\n if($.getSizeClassification('medium_up') && name.length > 35){\n split = Math.floor((name.length - 1) / 4);\n partA = name.substring(0,split);\n partB = name.substring(name.length-split);\n finalName = partA + '...' + partB;\n }else if($.getSizeClassification('small') && name.length > 20){\n split = Math.floor((name.length - 1) / 8);\n partA = name.substring(0,split + 2 );\n partB = name.substring(name.length - (split + 1));\n finalName = partA + '...' + partB;\n }else{\n finalName = name;\n }\n return finalName;\n}",
"function stringLimitDots(input,length){\n\tif(input!=undefined){\n\t\tif(input.length>length)\n\t\t\treturn input.substring(0,length)+'...';\n\t\treturn input;\n\t}\n\telse return '';\n}",
"function trimSongName(name) {\n if (name.length > 20) {\n return name.slice(0, 17).concat(\"...\");\n }\n else {\n return name;\n }\n}",
"function truncated(input) {\n\tif (input.length > 100) {\n\t\treturn input.substring(0, 100) + \"...\";\n\t}\n\treturn input;\n}",
"function limitLengthEmptyTitle() {\n if (toDoTitle.value.length > 45 || toDoTitle.value.length === 0) {\n toDoTitle.className = `input is-danger`;\n titleAlert.className = `help is-danger`;\n titleAlert.innerText = \"Title cannot be too long or empty\";\n toDoTitle.parentElement.children[1].childNodes[1].className = \"fa fa-times-circle\";\n } else {\n toDoTitle.className = `input is-primary`;\n titleAlert.className = `help is-hidden`;\n\n // add task created alert box top :) // Done\n createSuccessMessage(\"create\");\n output();\n }\n}",
"function shortenUrl ( url , length ) {\n\n if( !Ember.isBlank( url ) && url.length > length) {\n url = url.substr( 0 , length ) + \"...\";\n }\n\n return url;\n}",
"generateSmallDescription(text){\r\n\t if(text){\r\n\t\tif(text.length > 120){\r\n\t\t text= text.slice(0,120) + '...';\r\n\t\t return text;\r\n\t\t}\r\n\t\telse{\r\n\t\t return text;\r\n\t\t}\r\n\t }\r\n\t}",
"function shortQuote(quote) {\n if(quote.length>250) {\n quote = quote.slice(0,280);\n return quote + \"...\";\n } else return quote;\n}",
"function shorten(string) {\n \n // MAX CHARACTER LIMIT\n var max_length = 25;\n \n // CHECK IF THE STRING IS LONGER THAN 22 CHARACTERS\n if (string.length > max_length) {\n\n // ALLOW THE FIRST 20 CHARACTERS AND TAG ON THE TRIPLEDOT\n string = string.substring(0, (max_length - 3));\n string += '...';\n }\n\n return string;\n}",
"function limitWidth(string, len) {\n var lines = string.split('\\n');\n len = (typeof len === 'number') ? len : 80;\n var chars;\n for (var i = 0; i < lines.length; i++) {\n if (lines[i].length > len) {\n chars = lines[i].split('');\n lines[i] = lines[i].slice(0, len - 1);\n lines.splice(i + 1, 0, chars.slice(len - 1).join(''));\n }\n }\n return lines.join('\\n');\n}",
"function trimStringToMaxLength(string) {\n return string.length > config.maxlength ?\n string.substring(0, config.maxlength - 3) + \"...\" :\n string;\n}",
"function truncateString(str, length) {\n if(length >= str.length) return str\n else if(length <= 3) return str.slice(0, length) + '...'\n return str.slice(0, length - 3) + '...'\n}",
"function checkFieldLength(input) {\n if (input.value.length > 2) {\n input.value = input.value.slice(0, 2);\n }\n return;\n}",
"function checkLength(len, ele) {\n var fieldLength = ele.value.length;\n if(fieldLength <= len){\n return true;\n }\n else\n {\n var str = ele.value;\n str = str.substring(0, str.length - 1);\n ele.value = str;\n }\n}",
"function makeStr(str) {\n\tif(str.length <= 35){\n\t\treturn str;\n\t} else {\n\t\tvar index = 35;\n\t\twhile(index >= 0) {\n\t\t\tif(str.charAt(index) === \" \") {\n\t\t\t\treturn str.substr(0, index+1) + \"...\";\n\t\t\t} else {\n\t\t\t\tindex--;\n\t\t\t}\n\t\t}\n\t\treturn str.substr(0, 36) + \" ...\";\n\t}\n}",
"function truncateIfLongerThanthis(inputString,length){\n if(inputString.length>length){\n return inputString.substr(0,length);\n }\n return inputString;\n\n}",
"function truncateNames(arr, originalList, strAdded){\n originalList.forEach(function(item, i){\n\n var myStr = item;\n if(myStr != null){\n myStr = myStr.substring(0, myStr.indexOf(\" \"))+strAdded;\n } \n arr.push(myStr);\n } );\n\n }",
"function limitText(){\n\t\tvar str = primaryOutput.innerHTML;\n\t\tvar textLimit = 17;\n\t\tstr.split(\"\");\n\t\t\n\t\t//If text exceeds limit and is less than 4 extra, reduce font size\n\t\t//If text exceeds limit between 5 and 9 characters reduce font size more\n\t\t//If text exceeds limit by more than 9 characters print message to screen\n\t\tif (str.length > textLimit && str.length <= (textLimit + 3)){\n\t\t\tprimaryOutput.style.fontSize = \".9em\";\n\t\t} else if (str.length > (textLimit + 3) && str.length <= (textLimit + 8)){\n\t\t\tprimaryOutput.style.fontSize = \".7em\";\n\t\t} else if (str.length > (textLimit + 8)){\n\t\t\tprimaryOutput.innerHTML = \"Exceeded limit\";\n\t\t}\n\t}",
"function itemTextDisplayableLen(pText, pAmpersandHotkeysInItems)\n{\n\tvar textLen = console.strlen(pText);\n\t// If pAmpersandHotkeysInItems is true, look for ampersands immediately\n\t// before a non-space and if found, don't count those.\n\tif (pAmpersandHotkeysInItems)\n\t{\n\t\tvar startIdx = 0;\n\t\tvar ampersandIndex = pText.indexOf(\"&\", startIdx);\n\t\twhile (ampersandIndex > -1)\n\t\t{\n\t\t\t// See if the next character is a space character. If not, then\n\t\t\t// don't count it in the length.\n\t\t\tif (pText.length > ampersandIndex+1)\n\t\t\t{\n\t\t\t\tvar nextChar = pText.substr(ampersandIndex+1, 1);\n\t\t\t\tif (nextChar != \" \")\n\t\t\t\t\t--textLen;\n\t\t\t}\n\t\t\tstartIdx = ampersandIndex+1;\n\t\t\tampersandIndex = pText.indexOf(\"&\", startIdx);\n\t\t}\n\t}\n\treturn textLen;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
4. Pure assertion tests whether a value is truthy, as determined by !!guard. assert.ok(guard, message_opt); This statement is equivalent to assert.equal(true, guard, message_opt);. To test strictly for the value true, use assert.strictEqual(true, guard, message_opt);. | function ok(value, message) {
if (!!!value) fail(value, true, message, '==', assert.ok);
} | [
"function assertIsTruthy(a){\n return a_is_truthy(a);\n }",
"function assertion(value) {\n return expression.test(value)\n }",
"confirmAssertion () {\n this._asserted = true;\n }",
"function mustBeTrue (boo) {\n if (boo === true) {\n return true;\n }\n}",
"function mustBeTrue (boo){\n\tif (boo === true){\n\t\treturn true;\n\t}\n}",
"static bool(v) { return new Typed(_gaurd, \"bool\", !!v); }",
"function assertIsFalse(a){\n return a_equals_false(a);\n }",
"function testAssertFalseTrueLiteral()\n{\n\tthis.message += \" test pass true to assertFalse()\\n\";\n\n\tvar test = new Test_TestCase();\n\n\ttest.assertFalse( true, new Error() );\n\n\tthis.assertTrue( test.getTestsCount () === 1, \"test.getTestsCount () wasn't 1\" + test.getTestsCount () )\n\tthis.assertTrue( test.getTestsPassedCount() === 0, \"test.getTestsPassedCount() wasn't 0\" + test.getTestsPassedCount() )\n\tthis.assertTrue( test.getTestsFailedCount() === 1, \"test.getTestsFailedCount() wasn't 1\" + test.getTestsFailedCount() )\n}",
"function assertNever(theValue) {\n throw new Error(\"Unhandled case for value: '\".concat(theValue, \"'\"));\n }",
"static isSimpleAssertion(assertion) {\n let casted = assertion;\n return casted.apexAssertion !== undefined && typeof casted.apexAssertion === 'string';\n }",
"function NOT(value) {\n return value !== true && value !== false && value !== 1 && value !== 0 ? error$2.value : !value;\n}",
"function falsy_QMRK_(a) {\n return ((a === null) || (a === false));\n}",
"isBool(expression) {\n doCheck(\n this.typesAreEquivalent(expression.type, BoolType),\n \"Not a boolean\"\n );\n }",
"function bool(i) /* (i : int) -> bool */ {\n return $std_core._int_ne(i,0);\n}",
"function assert$c(value, struct) {\n const result = validate(value, struct);\n\n if (result[0]) {\n throw result[0];\n }\n}",
"function testAssertFalseFalseLiteral()\n{\n\tthis.message += \" test pass false to assertFalse()\\n\";\n\n\tvar test = new Test_TestCase();\n\n\ttest.assertFalse( false, new Error() );\n\n\tthis.assertTrue( test.getTestsCount () === 1, \"test.getTestsCount () wasn't 1\" + test.getTestsCount () )\n\tthis.assertTrue( test.getTestsPassedCount() === 1, \"test.getTestsPassedCount() wasn't 1\" + test.getTestsPassedCount() )\n\tthis.assertTrue( test.getTestsFailedCount() === 0, \"test.getTestsFailedCount() wasn't 0\" + test.getTestsFailedCount() )\n}",
"function assertEqual(a, b){\n return a_equals_b(a, b);\n }",
"function assert_ques_(exception_info) /* (exception-info : exception-info) -> bool */ {\n return (exception_info._tag === _tag_Assert);\n}",
"function isTrue(cond) {\n return ([true, \"true\", \"yes\"].indexOf(cond) >= 0);\n}",
"function testAssert() {\n for each (var test in TEST_DATA) {\n let message = \"assert.\" + test.fun + \" for [\" +\n test.params.join(\", \") + \"]\";\n\n if (test.result === true) {\n expect.doesNotThrow(function () {\n assert[test.fun].apply(assert, test.params);\n }, Error, message);\n }\n else {\n assert.throws(function () {\n assert[test.fun].apply(assert, test.params);\n }, test.throws, message);\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sells quantity of itemid, returns the amount of money made from the sale, or false if some error | sell(itemid, quantity)
{
var func = "Inventory.sell";
if(!this.has(itemid))
{
console.warn(func + ": cannot sell an item (" + itemid + ") we don't have.");
return false; // TODO test
}
var value = this.get(itemid);
if(quantity > value)
{
console.warn(func + ": tried to sell " + quantity + " " + itemid + ", but only have " + value + "."); // TODO test
return false;
}
this.set(itemid, this.get(itemid) - quantity);
var profit = quantity * itemDict.get(itemid).price
console.info("Sold " + quantity + " " + itemid + " for " + profit + "c.");
return profit;
} | [
"function sellSpecificItem(someItem) {\n someItem.shopDivI.style.display = 'block';\n someItem.inventoryDivI.style.display = 'none';\n money = money + someItem.sellI();\n prestige = prestige - someItem.owningI;\n someItem.boughtI = false;\n updateStats();\n message(msgSell + someItem.nameI + ' for ' + someItem.sellI() + '$');\n someItem.usageCountI = 0;\n}",
"function qtyMath(qty, id) {\n var tst = connection.query(\n \"SELECT * FROM products WHERE ?\", [{\n item_id: id\n }],\n function (err, res) {\n let qtyLeft = (res[0].stock_quantity - qty);\n let total = (res[0].price * qty);\n if (qtyLeft < 0) {\n console.log(\"***quantity exceeds stock available, please try again!***\");\n start();\n } else {\n updateTable(qtyLeft, id, total);\n }\n });\n }",
"function get_quantity(itemID,nu)\n{\n\tvar idx = array_search(itemID,qty_itemIDs);\n\tif (idx > -1)\n\t{\n\t\tvar qnew = qty_new_orig[idx];\n\t\tvar qused = qty_used_orig[idx];\n\n\t\tif (nu == ITEM_NEW) { return qnew; }\n\t\telse { return qused; }\n\t}\n\telse { return -1; }\n}",
"getTotalItemsById(itemId){\n return this.items[itemId].quntity;\n }",
"addItem(itemId, quntity){\n if (itemId in this.items){\n this.items[itemId].quntity += quntity;\n return true;\n }else if (itemId in productList){\n var itemInfo = productList[itemId];\n this.items[itemId] = {unitPrice: itemInfo.unitPrice,\n quntity: quntity};\n return true;\n } else{\n return false;\n }\n\n }",
"function reduceItems(item, quantity) {\n\tconnection.query(\"UPDATE products SET quantity = quantity -\"+quantity+\" WHERE id = \"+item, function(err,res) {\n\tif (err) throw err;\n\t})\n}",
"function searchInventory(id, quantity) {\n var query = 'SELECT * FROM products';\n connection.query(query,\n function (err, res) {\n if (err) throw err;\n var itemId = parseInt(id);\n var quantityItem = parseInt(quantity);\n var pickedItem;\n for (var i = 0; i < res.length; i++) {\n if (res[i].item_id === itemId) {\n pickedItem = res[i];\n }\n }\n //If there isn't enough quantity it will tell them to start over\n if (pickedItem.stock_quantity < quantityItem) {\n console.log('We do not have enough of those in stock!')\n userPrompt();\n } else {\n submitOrder(pickedItem, quantityItem);\n }\n });\n}",
"remove(itemid, quantity)\n {\n var func = \"Inventory.remove\";\n\n if (!itemid || !quantity)\n {\n console.warn(func + \": must provide both itemid and quantity.\");\n return false;\n }\n\n if (!this.get(itemid)) {\n console.warn(func + \": could not find any item with id \" + itemid + \" in this inventory.\");\n return false;\n }\n if (quantity < 0) {\n console.warn(func + \": quantity cannot be negative.\");\n return false;\n }\n\n if (this.get(itemid) < quantity)\n {\n // not enough\n console.warn(func + \": cannot remove. Asked to remove \" + quantity + \", only have \" + this.get(itemid) + \".\");\n return false;\n }\n else if(this.get(itemid) == quantity)\n {\n // exactly enough, delete entry\n this.delete(itemid);\n }\n else\n {\n this.set(itemid, this.get(itemid) - quantity);\n }\n return true;\n }",
"isItemAvailableOnFavoriteStore (skuId, quantity) {\n this.store.dispatch(getSetSuggestedStoresActn(EMPTY_ARRAY)); // clear previous search results\n let storeState = this.store.getState();\n let preferredStore = storesStoreView.getDefaultStore(storeState);\n let {coordinates} = preferredStore.basicInfo;\n let currentCountry = sitesAndCountriesStoreView.getCurrentCountry(storeState);\n\n return this.tcpStoresAbstractor.getStoresPlusInventorybyLatLng(skuId, quantity, 25, coordinates.lat, coordinates.long, currentCountry).then((searchResults) => {\n let store = searchResults.find((storeDetails) => storeDetails.basicInfo.id === preferredStore.basicInfo.id);\n return store && store.productAvailability.status !== BOPIS_ITEM_AVAILABILITY.UNAVAILABLE;\n }).catch(() => {\n // assume not available\n return false;\n });\n }",
"function calculateFinalPrice(product, unitPrice, quantity) {\n const productObj = newSlab.PRODUCTS.find(p => p.products.indexOf(product.toUpperCase()) > -1);\n if (productObj) {\n const gstApplicable = calculateGST(productObj.gstId, unitPrice, quantity);\n return (quantity * unitPrice) + gstApplicable;\n }\n else {\n throw (\"Product not found\");\n }\n\n}",
"function purchaseItems() {\n\t// check for atleast one sessionStorage object\n\tif (sessionStorage.itemName) {\n\t\tlet openModal = document.getElementsByClassName('modal')[0]\n\t\topenModal.style.display = 'block'\n\t\tgrandTotal()\n\t} else {\n\t\talert('Please Add An Item To Your Cart.')\n\t\twindow.location.href = '../html/store.html'\n\t}\n}",
"function total() \n{\n // create var to store total\n var total = 0\n \n // check if there are items in the cart:\n if(cart.length > 0)\n {\n \n // check the cart prices\n for(let i = 0; i < cart.length; i++)\n {\n // tally it up!\n total += cart[i].itemPrice\n }\n }\n // return what has been summed up\n return total\n}",
"function functionToBuy() {\n buySpecificItem(someItemFromShop);\n }",
"function basket_add(produkt_id){\n var found = false;\n if (!basket_increase_amount(produkt_id, 1)){\n var item = {\n productId: produkt_id,\n amount: 1,\n stock: 10,\n customerId: gkid,\n };\n basket.push(item);\n basket_update();\n }\n}",
"function Item(name, price, stock, calorieCount, type) {\n this.name = name;\n this.price = price;\n this.stock = stock;\n this.calorieCount = calorieCount;\n this.type = type;\n\n \n //we want a function to give an item description\n // name, cost, stock, caloriecount and type \n this.describe = function() {\n const description = `${this.name}: £${this.price.toFixed(2)} ${this.calorieCount}kcal ${this.type} - ${this.stock}`\n console.log(description);\n } \n \n \n //we want a function to be able to sell an item \n // check stock levels are enough for quantity\n // if not enough handle situation\n // give away stock \n // take in money = price *quantity\n //\n \n this.sell = function(quantity){\n if (this.stock < quantity){\n console.log(`we don't have ${quantity} x ${this.name} right now, choose less`)\n return;\n }\n this.stock -= quantity;\n const cost = this.price * quantity;\n balance += cost;\n }\n}",
"function purchasedItem(item) {\n try {\n purchasedItems[item] = 1;\n } catch (e) {\n logger.log(\"Purchase update failed with error:\", e);\n }\n}",
"function updateQuantity () {\n connection.query(\"UPDATE products SET ? WHERE ?\",\n [\n {\n stock_quantity: newStockNum\n },\n {\n item_id: itemSelected\n }\n ], function (err, results) {\n if (err) {\n throw err;\n };\n console.log(`\\n${product_name} received ${addedStock} units for a total of ${newStockNum}`);\n }\n );\n connection.end();\n}",
"function validation(){\r\n \r\n if (validateItem() && validateQty()) {\r\n return true; \r\n }\r\n \r\n return false;\r\n \r\n }",
"function Decrease() {\n if (quantity > 0) {\n quantity--;\n if (quantity === 0) {\n totalPrice = 0;\n }\n totalPrice = price * quantity;\n }\n totalPrice < 99\n ? (document.getElementById(\"totalPrice\").innerHTML =\n totalPrice + ShippingCost)\n : (document.getElementById(\"totalPrice\").innerHTML = totalPrice);\n document.getElementById(\"result\").innerHTML = quantity;\n document.getElementById(\"quantity\").innerHTML = quantity;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the given properties match those of a `HttpGatewayRouteRewriteProperty` | function CfnGatewayRoute_HttpGatewayRouteRewritePropertyValidator(properties) {
if (!cdk.canInspect(properties)) {
return cdk.VALIDATION_SUCCESS;
}
const errors = new cdk.ValidationResults();
if (typeof properties !== 'object') {
errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));
}
errors.collect(cdk.propertyValidator('hostname', CfnGatewayRoute_GatewayRouteHostnameRewritePropertyValidator)(properties.hostname));
errors.collect(cdk.propertyValidator('path', CfnGatewayRoute_HttpGatewayRoutePathRewritePropertyValidator)(properties.path));
errors.collect(cdk.propertyValidator('prefix', CfnGatewayRoute_HttpGatewayRoutePrefixRewritePropertyValidator)(properties.prefix));
return errors.wrap('supplied properties not correct for "HttpGatewayRouteRewriteProperty"');
} | [
"function CfnGatewayRoute_HttpGatewayRoutePathRewritePropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n return errors.wrap('supplied properties not correct for \"HttpGatewayRoutePathRewriteProperty\"');\n}",
"function CfnGatewayRoute_HttpGatewayRouteHeaderMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnGatewayRoute_GatewayRouteRangeMatchPropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"HttpGatewayRouteHeaderMatchProperty\"');\n}",
"function CfnGatewayRoute_HttpPathMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n return errors.wrap('supplied properties not correct for \"HttpPathMatchProperty\"');\n}",
"function CfnRoute_HttpPathMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n return errors.wrap('supplied properties not correct for \"HttpPathMatchProperty\"');\n}",
"function CfnRoute_HttpRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('headers', cdk.listValidator(CfnRoute_HttpRouteHeaderPropertyValidator))(properties.headers));\n errors.collect(cdk.propertyValidator('method', cdk.validateString)(properties.method));\n errors.collect(cdk.propertyValidator('path', CfnRoute_HttpPathMatchPropertyValidator)(properties.path));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('queryParameters', cdk.listValidator(CfnRoute_QueryParameterPropertyValidator))(properties.queryParameters));\n errors.collect(cdk.propertyValidator('scheme', cdk.validateString)(properties.scheme));\n return errors.wrap('supplied properties not correct for \"HttpRouteMatchProperty\"');\n}",
"function CfnGatewayRoute_GrpcGatewayRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('hostname', CfnGatewayRoute_GatewayRouteHostnameMatchPropertyValidator)(properties.hostname));\n errors.collect(cdk.propertyValidator('metadata', cdk.listValidator(CfnGatewayRoute_GrpcGatewayRouteMetadataPropertyValidator))(properties.metadata));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));\n return errors.wrap('supplied properties not correct for \"GrpcGatewayRouteMatchProperty\"');\n}",
"function CfnGatewayRoute_HttpQueryParameterMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n return errors.wrap('supplied properties not correct for \"HttpQueryParameterMatchProperty\"');\n}",
"function CfnRoute_HttpQueryParameterMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n return errors.wrap('supplied properties not correct for \"HttpQueryParameterMatchProperty\"');\n}",
"function CfnGatewayRoute_GatewayRouteMetadataMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnGatewayRoute_GatewayRouteRangeMatchPropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GatewayRouteMetadataMatchProperty\"');\n}",
"function CfnGatewayRoute_HttpGatewayRoutePrefixRewritePropertyValidator(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('defaultPrefix', cdk.validateString)(properties.defaultPrefix));\n errors.collect(cdk.propertyValidator('value', cdk.validateString)(properties.value));\n return errors.wrap('supplied properties not correct for \"HttpGatewayRoutePrefixRewriteProperty\"');\n}",
"function CfnGatewayRoute_HttpGatewayRouteHeaderPropertyValidator(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('invert', cdk.validateBoolean)(properties.invert));\n errors.collect(cdk.propertyValidator('match', CfnGatewayRoute_HttpGatewayRouteHeaderMatchPropertyValidator)(properties.match));\n errors.collect(cdk.propertyValidator('name', cdk.requiredValidator)(properties.name));\n errors.collect(cdk.propertyValidator('name', cdk.validateString)(properties.name));\n return errors.wrap('supplied properties not correct for \"HttpGatewayRouteHeaderProperty\"');\n}",
"function CfnRoute_GrpcRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('metadata', cdk.listValidator(CfnRoute_GrpcRouteMetadataPropertyValidator))(properties.metadata));\n errors.collect(cdk.propertyValidator('methodName', cdk.validateString)(properties.methodName));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));\n return errors.wrap('supplied properties not correct for \"GrpcRouteMatchProperty\"');\n}",
"function CfnGatewayRoute_HttpGatewayRouteActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('rewrite', CfnGatewayRoute_HttpGatewayRouteRewritePropertyValidator)(properties.rewrite));\n errors.collect(cdk.propertyValidator('target', cdk.requiredValidator)(properties.target));\n errors.collect(cdk.propertyValidator('target', CfnGatewayRoute_GatewayRouteTargetPropertyValidator)(properties.target));\n return errors.wrap('supplied properties not correct for \"HttpGatewayRouteActionProperty\"');\n}",
"function CfnGatewayRoute_GatewayRouteHostnameMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GatewayRouteHostnameMatchProperty\"');\n}",
"function CfnRoute_GrpcRouteMetadataMatchMethodPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnRoute_MatchRangePropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GrpcRouteMetadataMatchMethodProperty\"');\n}",
"function CfnRoute_HttpRouteActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('weightedTargets', cdk.requiredValidator)(properties.weightedTargets));\n errors.collect(cdk.propertyValidator('weightedTargets', cdk.listValidator(CfnRoute_WeightedTargetPropertyValidator))(properties.weightedTargets));\n return errors.wrap('supplied properties not correct for \"HttpRouteActionProperty\"');\n}",
"function CfnGatewayRoute_GatewayRouteHostnameRewritePropertyValidator(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('defaultTargetHostname', cdk.validateString)(properties.defaultTargetHostname));\n return errors.wrap('supplied properties not correct for \"GatewayRouteHostnameRewriteProperty\"');\n}",
"function CfnGatewayRoute_GrpcGatewayRouteActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('rewrite', CfnGatewayRoute_GrpcGatewayRouteRewritePropertyValidator)(properties.rewrite));\n errors.collect(cdk.propertyValidator('target', cdk.requiredValidator)(properties.target));\n errors.collect(cdk.propertyValidator('target', CfnGatewayRoute_GatewayRouteTargetPropertyValidator)(properties.target));\n return errors.wrap('supplied properties not correct for \"GrpcGatewayRouteActionProperty\"');\n}",
"function cfnGatewayRouteHttpPathMatchPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnGatewayRoute_HttpPathMatchPropertyValidator(properties).assertSuccess();\n return {\n Exact: cdk.stringToCloudFormation(properties.exact),\n Regex: cdk.stringToCloudFormation(properties.regex),\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function returns the device orientation in angles | function getOrientation() {
return window.screen.orientation.angle;
} | [
"@computed\n get sideCenterAngles() {\n const sideSum = this.windowDimensions.width + this.windowDimensions.height;\n const topBottom = this.windowDimensions.width / sideSum * Math.PI;\n const leftRigth = Math.abs(topBottom - Math.PI);\n return { topBottom, leftRigth };\n }",
"calculateRotation() {\n const extentFeature = this._extentFeature;\n const coords = extentFeature.getGeometry().getCoordinates()[0];\n const p1 = coords[0];\n const p2 = coords[3];\n const rotation = Math.atan2(p2[1] - p1[1], p2[0] - p1[0]) * 180 / Math.PI;\n\n return -rotation;\n }",
"function convertDeviceOrientationToDegrees(orientation) {\n switch (orientation) {\n case SimpleOrientation.rotated90DegreesCounterclockwise:\n return 90;\n case SimpleOrientation.rotated180DegreesCounterclockwise:\n return 180;\n case SimpleOrientation.rotated270DegreesCounterclockwise:\n return 270;\n case SimpleOrientation.notRotated:\n default:\n return 0;\n }\n}",
"function getCameraOrientation() {\n if (externalCamera) {\n // Cameras that are not attached to the device do not rotate along with it, so apply no rotation\n return SimpleOrientation.notRotated;\n }\n\n var result = oDeviceOrientation;\n\n // Account for the fact that, on portrait-first devices, the camera sensor is mounted at a 90 degree offset to the native orientation\n if (oDisplayInformation.nativeOrientation === DisplayOrientations.portrait) {\n switch (result) {\n case SimpleOrientation.rotated90DegreesCounterclockwise:\n result = SimpleOrientation.notRotated;\n break;\n case SimpleOrientation.rotated180DegreesCounterclockwise:\n result = SimpleOrientation.rotated90DegreesCounterclockwise;\n break;\n case SimpleOrientation.rotated270DegreesCounterclockwise:\n result = SimpleOrientation.rotated180DegreesCounterclockwise;\n break;\n case SimpleOrientation.notRotated:\n default:\n result = SimpleOrientation.rotated270DegreesCounterclockwise;\n break;\n }\n }\n\n return result;\n}",
"degrees() {\n return (this._radians * 180.0) / Math.PI;\n }",
"get eulerAngles() { return new Graphic_1.GL.Euler().setFromQuaternion(this).toVector3(); }",
"initScreenAngle() {\n\n // Check for API.\n let angle = _.get(window, 'screen.orientation.angle')\n this.hasScreenAngleAPI = _.isNumber(angle);\n\n this.setScreenAngle();\n\n }",
"get rulerBearing() {\n let dx = this.mRulerGeom.vertices[1].x - this.rulerStart.x;\n let dy = this.mRulerGeom.vertices[1].y - this.rulerStart.y;\n if (dy === 0)\n return dx < 0 ? 270 : 90;\n let quad = (dx > 0) ? ((dy > 0) ? 0 : 180) : ((dy > 0) ? 360 : 180);\n return Math.round(quad + 180 * Math.atan(dx / dy) / Math.PI);\n }",
"angle(v) {\n let d = this.dot(v);\n let m = this.mag() * v.mag();\n return Math.acos(d/m);\n }",
"function getDegreeValue() {\r\n var transformValue = ballStyle.transform;\r\n var values = transformValue.split('(')[1].split(')')[0].split(',');\r\n var a = values[0];\r\n var b = values[1];\r\n var c = values[2];\r\n var d = values[3];\r\n\r\n var scale = Math.sqrt(a * a + b * b);\r\n var sin = b / scale;\r\n return angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));\r\n }",
"function deviceOrientationHandler (eventData) {\n\tvar info, xyz = \"[X, Y, Z]\";\n\n\t// Update the provided HTML file to give visual feedback (optional, nice to have during development)\n\n\t// Grab the acceleration from the results\n\tinfo = xyz.replace(\"X\", eventData.alpha && eventData.alpha.toFixed(3));\n\tinfo = info.replace(\"Y\", eventData.beta && eventData.beta.toFixed(3));\n\tinfo = info.replace(\"Z\", eventData.gamma && eventData.gamma.toFixed(3));\n\tdocument.getElementById(\"devOrientation\").innerHTML = info;\n\n\t// this variable will be set on every orientation data set arrival and is used in the motion capture functions bellow;\n\t// ATTENTION: Values are not floats, and NEED to be parsed as such for the motion capture functions to work;\n\t// in this example, this parsing is done INSIDE the motion capture functions....\n\t// could've had this the easy way, but did not see my error in time.\n\tdeviceOrientation = [eventData.alpha, eventData.beta, eventData.gamma];\n\n}",
"calcularAngulo(punto){\n return this.angulo = Math.atan2(punto.y - this.y, punto.x - this.x);\n }",
"function compassDir(degrees) {\n if (degrees == 360) {\n return 'N';\n } else if (degrees >= 337.5) {\n return 'NNW';\n } else if (degrees >= 315) {\n return 'NW';\n } else if (degrees >= 292.5) {\n return 'WNW';\n } else if (degrees >= 270) {\n return 'W';\n } else if (degrees >= 247.5) {\n return 'WSW'\n } else if (degrees >= 225) {\n return 'SW';\n } else if (degrees >= 202.5) {\n return 'SSW';\n } else if (degrees >= 160) {\n return 'S';\n } else if (degrees >= 157.5) {\n return 'SSE';\n } else if (degrees >= 135) {\n return 'SE';\n } else if (degrees >= 112.5) {\n return 'ESE';\n } else if (degrees >= 90) {\n return 'E';\n } else if (degrees >= 67.5) {\n return 'ENE';\n } else if (degrees >= 45) {\n return 'NE';\n } else if (degrees >= 22.5) {\n return 'NNE';\n } else {\n return 'N';\n }\n}",
"function getOrientationsXYZ(tabCamera) {\n return tabCamera.slice(6, 9);\n}",
"function face_target_deltas_rad(dx, dy) {\n\tvar rad_angle = Math.atan(Math.abs(dy)/(Math.abs(dx)==0?0.00001:Math.abs(dx)) ); // !DIV0\n\tif (dx<0) rad_angle=Math.PI-rad_angle;\n\tif (dy<0) rad_angle=2*Math.PI-rad_angle;\n\treturn rad_angle;\n}",
"function findAngle(object, unit, directions) {\n// var dy = (object.y) - (unit.y);\n// var dx = (object.x) - (unit.x);\n var direction;\n if (object.x > unit.x) {\n if (object.y > unit.y) {\n direction = 3;\n } else if (object.y < unit.y) {\n direction = 1;\n } else {\n direction = 2;\n }\n } else if (object.x < unit.x) {\n if (object.y > unit.y) {\n direction = 5;\n } else if (object.y < unit.y) {\n direction = 7;\n } else {\n direction = 6;\n }\n } else if (object.y > unit.y) {\n direction = 4;\n } else if (object.x == unit.x\n && object.y == unit.y) {\n direction = unit.newDirection;\n } else {\n direction = 0;\n }\n return direction;\n //Convert Arctan to value between (0 - directions)\n\n\n// var angle = wrapDirection(directions/2-(Math.atan2(dx,dy)*directions/(2*Math.PI)),directions);//console.log(angle);\n// return angle;\n}",
"setRotations() {\n this.r3a1_exitDoor.angle = 270;\n }",
"function ang(t) {\n return {\n x: cos(t),\n y: sin(t),\n };\n }",
"function angularCoord(x, y)\n {\n var phi = 0.0;\n\n if (x > 0 && y >= 0) {\n phi = Math.atan(y / x);\n }\n if (x > 0 && y < 0) {\n phi = Math.atan(y / x) + 2 * Math.PI;\n }\n if (x < 0) {\n phi = Math.atan(y / x) + Math.PI;\n }\n if (x = 0 && y > 0) {\n phi = Math.PI / 2;\n }\n if (x = 0 && y < 0) {\n phi = 3 * Math.PI / 2;\n }\n\n return phi;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalize `position` to add an `indent`. | function normalize(position) {
var offsets = ctx.offset
var line = position.line
var result = []
while (++line) {
if (!(line in offsets)) {
break
}
result.push((offsets[line] || 0) + 1)
}
return {start: position, indent: result}
} | [
"function syntaxIndentation(cx, ast, pos) {\n return indentFrom(\n ast.resolveInner(pos).enterUnfinishedNodesBefore(pos),\n pos,\n cx\n )\n }",
"assignPosition(node, position) {\n node.position = position \n if (node.children.length){\n for (let child_node of node.children){\n position = this.assignPosition(child_node, position)\n }\n }else{\n position++;\n }\n return position\n }",
"function index_after_formatting(position) {\n\t var start = position === 0 ? 0 : position - 1;\n\t var command_len = $.terminal.length(command);\n\t for (var i = start; i < command_len - 1; ++i) {\n\t var substr = $.terminal.substring(command, 0, i);\n\t var next_substr = $.terminal.substring(command, 0, i + 1);\n\t var formatted_substr = formatting(substr);\n\t var formatted_next = formatting(next_substr);\n\t var substr_len = length(formatted_substr);\n\t var next_len = length(formatted_next);\n\t var test_diff = Math.abs(next_len - substr_len);\n\t if (test_diff > 1) {\n\t return i;\n\t }\n\t }\n\t }",
"assignPosition(node, position) {\n this.spot = Math.max(this.spot, position);\n node.position = position;\n if (node.children.length > 0) {\n this.assignPosition(node.children[0], position);\n }\n for (let i = 1; i < node.children.length; i++) {\n if (this.spot > position) {\n this.assignPosition(node.children[i], this.spot+1);\n } else {\n this.assignPosition(node.children[i], position+1);\n }\n }\n }",
"function indentRange(state, from, to) {\n let updated = Object.create(null)\n let context = new IndentContext(state, {\n overrideIndentation: (start) => {\n var _a\n return (_a = updated[start]) !== null && _a !== void 0 ? _a : -1\n }\n })\n let changes = []\n for (let pos = from; pos <= to; ) {\n let line = state.doc.lineAt(pos)\n pos = line.to + 1\n let indent = getIndentation(context, line.from)\n if (indent == null) continue\n if (!/\\S/.test(line.text)) indent = 0\n let cur = /^\\s*/.exec(line.text)[0]\n let norm = indentString(state, indent)\n if (cur != norm) {\n updated[line.from] = indent\n changes.push({\n from: line.from,\n to: line.from + cur.length,\n insert: norm\n })\n }\n }\n return state.changes(changes)\n }",
"function indentOnInput() {\n return dist_EditorState.transactionFilter.of(tr => {\n if (!tr.docChanged || tr.annotation(Transaction.userEvent) != \"input\")\n return tr;\n let rules = tr.startState.languageDataAt(\"indentOnInput\", tr.startState.selection.primary.head);\n if (!rules.length)\n return tr;\n let doc = tr.newDoc, { head } = tr.newSelection.primary, line = doc.lineAt(head);\n if (head > line.from + DontIndentBeyond)\n return tr;\n let lineStart = doc.sliceString(line.from, head);\n if (!rules.some(r => r.test(lineStart)))\n return tr;\n let { state } = tr, last = -1, changes = [];\n for (let { head } of state.selection.ranges) {\n let line = state.doc.lineAt(head);\n if (line.from == last)\n continue;\n last = line.from;\n let indent = Math.max(...state.facet(dist_EditorState.indentation).map(f => f(new dist_IndentContext(state), line.from)));\n if (indent < 0)\n continue;\n let cur = /^\\s*/.exec(line.slice(0, Math.min(line.length, DontIndentBeyond)))[0];\n let norm = state.indentString(indent);\n if (cur != norm)\n changes.push({ from: line.from, to: line.from + cur.length, insert: norm });\n }\n return changes.length ? [tr, { changes }] : tr;\n });\n}",
"buildHighlightPosition (position, linenum, text) {\n var remainingCharacters = position;\n let lines = text.split(\"\\n\");\n\n // Iterate until we get to the position of the character we need, and then build\n // a relative vscode.Position.\n for (var i = 0; i < lines.length; i++) {\n let charactersInLine = lines[i].length + 1; // +1 for the newline.\n\n if (remainingCharacters - charactersInLine < 0) {\n return new vscode.Position(linenum - 1, remainingCharacters);\n }\n\n remainingCharacters = remainingCharacters - charactersInLine;\n }\n\n // If we get here, there's probaly a buffer mismatch.\n return undefined;\n }",
"textAfterPos(pos) {\n var _a, _b;\n let sim = (_a = this.options) === null || _a === void 0 ? void 0 : _a.simulateBreak;\n if (pos == sim && ((_b = this.options) === null || _b === void 0 ? void 0 : _b.simulateDoubleBreak))\n return \"\";\n return this.state.sliceDoc(pos, Math.min(pos + 100, sim != null && sim > pos ? sim : 1e9, this.state.doc.lineAt(pos).to));\n }",
"function indentOnInput() {\n return EditorState.transactionFilter.of((tr) => {\n if (\n !tr.docChanged ||\n (!tr.isUserEvent('input.type') && !tr.isUserEvent('input.complete'))\n )\n return tr\n let rules = tr.startState.languageDataAt(\n 'indentOnInput',\n tr.startState.selection.main.head\n )\n if (!rules.length) return tr\n let doc = tr.newDoc,\n { head } = tr.newSelection.main,\n line = doc.lineAt(head)\n if (head > line.from + DontIndentBeyond) return tr\n let lineStart = doc.sliceString(line.from, head)\n if (!rules.some((r) => r.test(lineStart))) return tr\n let { state } = tr,\n last = -1,\n changes = []\n for (let { head } of state.selection.ranges) {\n let line = state.doc.lineAt(head)\n if (line.from == last) continue\n last = line.from\n let indent = getIndentation(state, line.from)\n if (indent == null) continue\n let cur = /^\\s*/.exec(line.text)[0]\n let norm = indentString(state, indent)\n if (cur != norm)\n changes.push({\n from: line.from,\n to: line.from + cur.length,\n insert: norm\n })\n }\n return changes.length ? [tr, { changes, sequential: true }] : tr\n })\n }",
"onIndent() {\n $(this.table)\n .find('.tabledrag-cell > .js-indentation')\n .each((index, indentToMove) => {\n const $indentToMove = $(indentToMove);\n const $cellContent = $indentToMove.siblings(\n '.tabledrag-cell-content',\n );\n $indentToMove.prependTo($cellContent);\n });\n }",
"_translateDimension( dim, position ) {\n // Quick check equality i.e. this dimension has not moved\n if ( this.lastPos[ dim ] === this.pos[ dim ] ) {\n return position\n }\n\n // Set magnitude to move star by, if this dimension is still contained\n // within bounds then set to 0\n let mag = dim === 'x' ? this.bounds.width : this.bounds.height\n\n if ( dim === 'x' ) {\n if ( position >= this.bounds.x && position < this.bounds.x + this.bounds.width ) {\n mag = 0\n }\n }\n\n if ( dim === 'y' ) {\n if ( position >= this.bounds.y && position < this.bounds.y + this.bounds.height ) {\n mag = 0\n }\n }\n\n\n // Translate forward or backward by bounding width based on direction moved\n return this.lastPos[ dim ] > this.pos[ dim ]\n ? position -= mag\n : position += mag\n }",
"*positions(editor) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var {\n at = editor.selection,\n unit = 'offset',\n reverse: reverse$1 = false\n } = options;\n\n if (!at) {\n return;\n }\n\n var range = Editor.range(editor, at);\n var [start, end] = Range.edges(range);\n var first = reverse$1 ? end : start;\n var string = '';\n var available = 0;\n var offset = 0;\n var distance = null;\n var isNewBlock = false;\n\n var advance = () => {\n if (distance == null) {\n if (unit === 'character') {\n distance = getCharacterDistance(string);\n } else if (unit === 'word') {\n distance = getWordDistance(string);\n } else if (unit === 'line' || unit === 'block') {\n distance = string.length;\n } else {\n distance = 1;\n }\n\n string = string.slice(distance);\n } // Add or substract the offset.\n\n\n offset = reverse$1 ? offset - distance : offset + distance; // Subtract the distance traveled from the available text.\n\n available = available - distance; // If the available had room to spare, reset the distance so that it will\n // advance again next time. Otherwise, set it to the overflow amount.\n\n distance = available >= 0 ? null : 0 - available;\n };\n\n for (var [node, path] of Editor.nodes(editor, {\n at,\n reverse: reverse$1\n })) {\n if (Element.isElement(node)) {\n // Void nodes are a special case, since we don't want to iterate over\n // their content. We instead always just yield their first point.\n if (editor.isVoid(node)) {\n yield Editor.start(editor, path);\n continue;\n }\n\n if (editor.isInline(node)) {\n continue;\n }\n\n if (Editor.hasInlines(editor, node)) {\n var e = Path.isAncestor(path, end.path) ? end : Editor.end(editor, path);\n var s = Path.isAncestor(path, start.path) ? start : Editor.start(editor, path);\n var text = Editor.string(editor, {\n anchor: s,\n focus: e\n });\n string = reverse$1 ? esrever.reverse(text) : text;\n isNewBlock = true;\n }\n }\n\n if (Text.isText(node)) {\n var isFirst = Path.equals(path, first.path);\n available = node.text.length;\n offset = reverse$1 ? available : 0;\n\n if (isFirst) {\n available = reverse$1 ? first.offset : available - first.offset;\n offset = first.offset;\n }\n\n if (isFirst || isNewBlock || unit === 'offset') {\n yield {\n path,\n offset\n };\n }\n\n while (true) {\n // If there's no more string, continue to the next block.\n if (string === '') {\n break;\n } else {\n advance();\n } // If the available space hasn't overflow, we have another point to\n // yield in the current text node.\n\n\n if (available >= 0) {\n yield {\n path,\n offset\n };\n } else {\n break;\n }\n }\n\n isNewBlock = false;\n }\n }\n }",
"function getOffset() {\n var indentation = [];\n var pos = line + 1;\n\n /* Done. Called when the last character is\n * eaten to retrieve the range’s offsets. */\n return function () {\n var last = line + 1;\n\n while (pos < last) {\n indentation.push((offset[pos] || 0) + 1);\n\n pos++;\n }\n\n return indentation;\n };\n }",
"function returnWithIndent() {\r\n // Selection DOM object\r\n const dSel = ta;\r\n\r\n // How many spaces will be put before the first non-space?\r\n var space = 0;\r\n\r\n if (dSel.selectionStart || dSel.selectionStart == '0') {\r\n var startPos = dSel.selectionStart;\r\n var endPos = dSel.selectionEnd;\r\n var scrollTop = dSel.scrollTop;\r\n var before = dSel.value.substring(0, startPos);\r\n var after = dSel.value.substring(endPos,dSel.value.length);\r\n var split = before.split(\"\\n\");\r\n\r\n // What is the last line before the caret?\r\n var last = split[split.length-1];\r\n\r\n for(var i=0; i<last.length; i++) {\r\n if(last.charAt(i) != ' ') {\r\n break;\r\n }\r\n\r\n space++;\r\n }\r\n\r\n // Create the return\r\n var myValue = \"\\n\";\r\n for(i=0; i<space; i++) {\r\n myValue += ' ';\r\n }\r\n\r\n insertText(dSel, myValue);\r\n dSel.selectionStart = startPos + myValue.length;\r\n dSel.selectionEnd = startPos + myValue.length;\r\n } else {\r\n dSel.value += \"\\n\";\r\n dSel.focus();\r\n }\r\n\r\n return space > 0;\r\n }",
"function moveToContain(position) {\r\n\t\tvar distanceFromCenter = position[api.orientation] - center[api.orientation];\r\n\t\tif (distanceFromCenter > api.size / 2) {\r\n\t\t\tcenter[api.orientation] += distanceFromCenter - (api.size / 2);\r\n\t\t} else if (distanceFromCenter < api.size / -2) {\r\n\t\t\tcenter[api.orientation] += distanceFromCenter + (api.size / 2);\r\n\t\t}\r\n\t}",
"setStartPosition() {\n this.position = [Math.floor(pixelAmount / 2), Math.floor(pixelAmount / 2)];\n }",
"function indentOutdent(indentType) \n{ \n // Get the DOM\n var theDOM = dw.getDocumentDOM();\n \n if (theDOM == null)\n\treturn;\n\t\n if (indentType == \"indent\")\n theDOM.source.indentTextView();\n else if(indentType == \"outdent\")\n theDOM.source.outdentTextView();\n}",
"lineAt(pos, bias = 1) {\n let line = this.state.doc.lineAt(pos)\n let { simulateBreak, simulateDoubleBreak } = this.options\n if (\n simulateBreak != null &&\n simulateBreak >= line.from &&\n simulateBreak <= line.to\n ) {\n if (simulateDoubleBreak && simulateBreak == pos)\n return { text: '', from: pos }\n else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos)\n return {\n text: line.text.slice(simulateBreak - line.from),\n from: simulateBreak\n }\n else\n return {\n text: line.text.slice(0, simulateBreak - line.from),\n from: line.from\n }\n }\n return line\n }",
"setMenuItemsPosition (pos) {\n var step = Math.PI*2 / this.opts.items.length,\n angle = Math.PI/2,\n opts = this.opts,\n range,\n _this = this,\n position;\n\n\n\n Array.prototype.forEach.call(this.$items, function ($item, i) {\n position = _this.getItemPosition($item, angle);\n\n if (!pos) {\n $item.style.left = position.x + 'px';\n $item.style.top = position.y + 'px';\n } else {\n $item.style.left = position.fromX + 'px';\n $item.style.top = position.fromY + 'px';\n }\n\n if (!_this.cacheInited) {\n _this.cache.push({\n item: $item,\n correctedX: position.x,\n correctedY: position.y,\n x: position.originalX,\n y: position.originalY,\n fromX: position.fromX,\n fromY: position.fromY,\n range: position.range\n });\n }\n\n angle -= step;\n });\n\n this.cacheInited = true;\n }",
"continue() {\n let parent = this.node.parent\n return parent ? indentFrom(parent, this.pos, this.base) : 0\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines whether this block type is active; uses the this.blocks property if the block is being tracked, otherwise defaults to false | has_block(type) { return (this.tracking_block(type)) ? this.blocks[type] : false; } | [
"tracking_block(type) { return this.blocks[type] !== undefined; }",
"function isBlockType(name) {\n return !!blockTypes[name];\n }",
"function getBlockType(name) {\n return blockTypes[name] || false;\n }",
"function atTopLevel() {\n return Object.is(topBlock,currentBlock);\n }",
"hasBlockAt(position) {\n\t\tconst xVals = this.blocks.get(position.y);\n\t\treturn (xVals && xVals.has(position.x)) || false;\n\t}",
"isLocalOnHold() {\n if (this.state !== CallState.Connected) return false;\n if (this.unholdingRemote) return false;\n let callOnHold = true; // We consider a call to be on hold only if *all* the tracks are on hold\n // (is this the right thing to do?)\n\n for (const tranceiver of this.peerConn.getTransceivers()) {\n const trackOnHold = ['inactive', 'recvonly'].includes(tranceiver.currentDirection);\n if (!trackOnHold) callOnHold = false;\n }\n\n return callOnHold;\n }",
"get busy() {\n\t\treturn this.state == Constants.STATE.BUSY;\n\t}",
"function isBusy(busyBlocks, time) {\n var i;\n\n for (i = 0; i < busyBlocks.length; i++) {\n if (busyBlocks[i].isBusy(time)) {\n return true;\n }\n }\n\n return false;\n}",
"isBlock(editor, value) {\n return Element$1.isElement(value) && !editor.isInline(value);\n }",
"function isBuildingBlock(x, z) {\n\treturn buildingMap[x][z];\n }",
"function detect() {\n // Get the active content\n const active = getActive(data, settings);\n\n // if there's no active content, deactivate and bail\n if (!active) {\n if (current) {\n deactivate(current, settings);\n current = null;\n }\n return;\n }\n\n // If the active content is the one currently active, do nothing\n if (current && active.content === current.content) return;\n\n // Deactivate the current content and activate the new content\n deactivate(current, settings);\n activate(active, settings);\n\n // Update the currently active content\n current = active;\n }",
"function isNewBlock(props) {\n return !props.attributes.id;\n }",
"isUseCurrentAsBaseRun () {\n return this.isCompletedRunCurrent && (!this.isReadonlyWorksetCurrent || this.isPartialWorkset())\n }",
"function underLevel(name) {\n for (var blo of blockStack) {\n if (blo.getLabel() == name)\n return true;\n }\n return currentBlock.getLabel() == name;\n }",
"isEnabled() {\n //Override.\n return $gameMessage.currentWindow === this.SETTINGS.UNIQUE_ID;\n }",
"standingBlock() {\n\t\tthis.updateState(KEN_SPRITE_POSITION.standingBlock, KEN_IDLE_ANIMATION_TIME, false);\n\t}",
"function IsItemActivated() { return bind.IsItemActivated(); }",
"get isTextblock() { return false }",
"function isBlockContainer(node) {\n return Boolean(acceptedBlocks(node));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
oBA compute the amount of dissolved oBA, in mg, for a specific hop addition | function compute_oBA_dis_mg(ibu, hopIdx, currVolume) {
var oBA_addition = 0.0;
var oBA_percent = 0.0;
oBA_percent = 1.0 - ibu.add[hopIdx].freshnessFactor.value;
oBA_addition = oBA_percent * SMPH.oBA_boilFactor *
(ibu.add[hopIdx].BA.value / 100.0) *
ibu.add[hopIdx].weight.value * 1000.0;
// note: solubility limit of oBA is large enough that all is dissolved
ibu.add[hopIdx].oBA_dis_mg = oBA_addition;
if (SMPH.verbose > 4) {
console.log(" hop addition " + hopIdx + ": [oBA] = " +
(ibu.add[hopIdx].oBA_dis_mg/currVolume).toFixed(4) +
" ppm from (" + oBA_percent.toFixed(4) + " * " +
SMPH.oBA_boilFactor +
" * " + (ibu.add[hopIdx].BA.value/100.0).toFixed(4) + " * " +
ibu.add[hopIdx].weight.value.toFixed(3) + " * 1000.0 / " +
currVolume.toFixed(4));
}
return;
} | [
"function compute_oAA_dis_mg(ibu, hopIdx, currVolume) {\n var AAloss_percent = 0.0;\n var k = 0.0;\n var oAA_addition = 0.0;\n var oAA_fresh = 0.0;\n var oAA_percent_boilFactor = 0.0;\n var oAA_percent_init = 0.0;\n var oAA_percent = 0.0;\n var ratio = 0.0;\n var relativeAA = 0.0;\n\n // The oAA_percent_init is for cones; the value for pellets is probably\n // higher (because more surface area), but this (hopefully) rarely comes\n // into play because oAA_boil for pellets is much larger. So, just use the\n // cones value even if we have pellets.\n\n // 'k' is from Garetz\n ratio = 1.0 - (ibu.add[hopIdx].percentLoss.value / 100.0);\n k = Math.log(1.0 / ratio) / (365.0 / 2.0);\n if (SMPH.verbose > 5) {\n console.log(\" %loss = \" +\n ibu.add[hopIdx].percentLoss.value.toFixed(2) +\n \" and so k = \" + k.toFixed(6));\n }\n\n // oAA_fresh modeled as 3.5 days decay at 20'C, which is then multiplied\n // by AA rating. For Maye paper, average AA of Zeus is 15.75% and SF = 50%,\n // so 1-(1/exp(0.003798*1*1*3.5) * 0.1575 = 0.002 = 0.2% of weight of hops.\n // where 0.003798 is k for SF 50%.\n oAA_fresh = 1.0 - (1.0 / Math.exp(k * 1.0 * 1.0 * 3.5));\n\n AAloss_percent = 1.0 - ibu.add[hopIdx].freshnessFactor.value;\n oAA_percent_init = (AAloss_percent * SMPH.oAA_storageFactor) + oAA_fresh;\n if (SMPH.verbose > 4) {\n console.log(\" [oAA] storage factors: fresh=\" + oAA_fresh.toFixed(5) +\n \" + (loss=\" + AAloss_percent.toFixed(5) +\n \" * storage=\" + SMPH.oAA_storageFactor.toFixed(4) +\n \"): %init=\" + oAA_percent_init.toFixed(5));\n }\n\n // the AA available for oxidation is affected by the AA solubility limit;\n // figure out the relative impact of this solubility limit\n relativeAA = 1.0;\n if (ibu.add[hopIdx].AA_init > 0.0 && currVolume > 0.0) {\n relativeAA = ibu.add[hopIdx].AA_dis_mg/(ibu.add[hopIdx].AA_init*currVolume);\n }\n\n // console.log(\"AA: added= \"+(ibu.add[hopIdx].AA_init*currVolume).toFixed(3) +\n // \"mg , dissolved = \" + ibu.add[hopIdx].AA_dis_mg.toFixed(3) +\n // \"mg, relative = \" + relativeAA.toFixed(3));\n // the AA solubility limit only applies to the oAA produced during the boil\n oAA_percent_boilFactor = ibu.add[hopIdx].freshnessFactor.value *\n SMPH.oAA_boilFactor * relativeAA;\n\n // if using pellets, the boil factor is increased\n if (ibu.add[hopIdx].hopForm.value == \"pellets\") {\n oAA_percent_boilFactor *= ibu.add[hopIdx].pelletFactor.value;\n }\n\n if (SMPH.verbose > 4) {\n console.log(\" [oAA] boil factor: \"+ oAA_percent_boilFactor.toFixed(5) +\n \" from fresh=\" + ibu.add[hopIdx].freshnessFactor.value.toFixed(5) +\n \", boil=\" + SMPH.oAA_boilFactor.toFixed(5) +\n \", relAA=\" + relativeAA.toFixed(5),\n \", pelletFactor=\" + ibu.add[hopIdx].pelletFactor.value);\n }\n // oAA_addition is oAA added to wort, in mg\n\n // boiling has no effect on AA that have oxidized prior to boil (FV exp #74)\n oAA_percent = oAA_percent_boilFactor;\n if (oAA_percent_init > oAA_percent_boilFactor) {\n oAA_percent = oAA_percent_init;\n }\n oAA_addition = oAA_percent * (ibu.add[hopIdx].AA.value/100.0) *\n ibu.add[hopIdx].weight.value * 1000.0;\n\n // note: solubility limit of oAA is large enough so that all are dissolved\n ibu.add[hopIdx].oAA_dis_mg = oAA_addition;\n if (SMPH.verbose > 3) {\n console.log(\" hop addition \" + hopIdx + \": [oAA] = \" +\n (ibu.add[hopIdx].oAA_dis_mg/currVolume).toFixed(4) +\n \" ppm from (\" + oAA_percent_init.toFixed(4) + \" + \" +\n oAA_percent_boilFactor.toFixed(4) +\n \") * \" + (ibu.add[hopIdx].AA.value/100.0).toFixed(4) + \" * \" +\n ibu.add[hopIdx].weight.value.toFixed(3) + \" * 1000.0 / \" +\n currVolume.toFixed(4));\n }\n\n return;\n}",
"function compute_LF_oBA(ibu, hopIdx) {\n var LF_oBA = 0.0;\n\n LF_oBA = compute_LF_ferment(ibu) *\n compute_LF_nonIAA_krausen(ibu) *\n compute_LF_finings(ibu) *\n compute_LF_filtering(ibu) *\n compute_LF_age(ibu);\n if (SMPH.verbose > 5) {\n console.log(\"oBA LOSS FACTOR = \" + LF_oBA +\n \" from ferment=\" + compute_LF_ferment(ibu) + \", krausen=\" +\n compute_LF_nonIAA_krausen(ibu) + \", finings=\" +\n compute_LF_finings(ibu) + \", filtering=\" +\n compute_LF_filtering(ibu) + \", age=\" +\n compute_LF_age(ibu));\n }\n\n return(LF_oBA);\n}",
"function compute_concent_wort(ibu) {\n var AA_dis = 0.0; // concentration of dissolved AA, in ppm\n var AA_dis_mg = 0.0; // dissolved AA, in mg\n var AA_init = 0.0; // [AA]_0, in ppm\n var AA_init_mg = 0.0; // initial amount of AA added, in mg\n var AA_limit_func_A = 0.0; // AA solubility limit, function parameter A\n var AA_limit_func_B = 0.0; // AA solubility limit, function parameter A\n var AA_limit_minLimit = 0.0; // AA solubility limit, minimum solubility\n var AA_limit_minLimit_orig = SMPH.AA_limit_minLimit;\n var AA_limit_maxLimit = 0.0; // AA solubility limit, maximum solubility\n var AA_limit_maxLimit_orig = SMPH.AA_limit_maxLimit;\n var AA_noLimit = 0.0; // [AA] if there is no solubility limit\n var AA_noLimit_mg = 0.0; // dissolved AA, in mg, if no solubility limit\n var AA_percent = 0.0; // the percent of alpha acids added to wort\n var AA_xfer_mg = 0.0; // amount of AA (mg) transferred w/ counterflow\n var additionTime = 0.0; // the time of a hop addition\n var boilK = 0.0; // the temperature at boiling, in Kelvin\n var boilTime = ibu.boilTime.value; // the total boil time\n var coolingMethod = ibu.forcedDecayType.value; // the cooling method\n var currVolume = 0.0; // the current volume of wort at time t\n var dAA_dis_mg = 0.0; // the change in dissolved AA at time t, in mg\n var decayRate = 0.0; // the exponential decay factor for wort cooling\n var dIAA_dis_mg = 0.0; // the change in dissolved IAA at time t, in mg\n var doneHoldTemp = false; // are we done with holding temperature?\n var expParamC_Kelvin = 0.0; // exponential decay parameter C, in Kelvin\n var FCT = 0.0; // amount of time spent in forced cooling\n var finalVolume = 0.0; // final volume after wort loss and added water\n var finished = false; // are we finished with modeling IAA over time?\n var holdTemp = ibu.holdTemp.value; // the temperature at which to hold wort\n var holdTempCheckbox = ibu.holdTempCheckbox.value; // do we hold temp?\n var holdTempCounter = 0.0; // the time that we've held the temperature\n var holdTempK = 0.0; // the temperature that we hold wort, in Kelvin\n var hopIdx = 0; // index into array of hop additions\n var IAA_dis_mg = 0.0; // dissolved IAA, in mg\n var IAA_xfer_mg = 0.0; // amount of IAA (mg) transferred w/ counterflow\n var initVolume = 0.0; // initial (start of boil) volume\n var integrationTime = 0.0; // time interval for approximating integration\n var integTimePrecision = 0; // precision of the value of 'integrationTime'\n var isTempDecayLinear = 0; // is post-boil temperature decay linear?\n var k1 = 0.0; // M. Malowicki's isomerization rate constant 1\n var k2 = 0.0; // M. Malowicki's isomerization rate constant 2\n var newAA_mg = 0.0; // amount of AA remaining after xfer at time t\n var newIAA_mg = 0.0; // amount of IAA remaining after xfer at time t\n var origWhirlpoolTime = 0.0; // user-specified time for whirlpool\n var postBoilTime = 0.0; // current amount of time after stopping boil\n var postBoilVolume = 0.0; // volume at the end of the boil, in the kettle\n var preAdd_AA_mg = 0.0; // AA (in mg) in wort before a hop addition\n var evapRateAtBoil = 0.0; // rough estimate of evaporation rate at boiling\n var evapRateAtTemp = 0.0; // same estimate of evap. rate at current temp\n var relativeTemp = 0.0; // relative temp. to get effectiveSteepTime\n var RF_IAA = 0.0; // isomerization rate factor for IAA\n var roomTempK = 20.0+273.15; // room temperature, in Kelvin\n var slope = 0.0; // slope for solubility limit as func. of temp.\n var subBoilEvapRate = 0.0; // evaporation rate, maybe at below-boiling temp\n var t = 0.0; // current time, in minutes\n var tempC = 0.0; // current wort temperature, in degrees Celsius\n var tempK = 0.0; // current wort temperature, in degrees Kelvin\n var tempNoBase = 0.0; // temperature minus 'base' temp in temp decay\n var totalXferTime = 0.0; // total amount of time spent transferring wort\n var useSolubilityLimit = ibu.applySolubilityLimitCheckbox.value;\n var volumeChange = 0.0; // the change in volume at each integrationTime\n var whirlpoolTime = 0.0; // actual whirlpool time, includes forced cool.\n var xferRate = 0.0; // transfer rate (liter/min) using counterflow\n\n // ---------------------------------------------------------------------------\n // INITIALIZATION\n\n integrationTime = 0.01; // just in case SMPH.integrationTime is not defined\n if (SMPH.integrationTime) {\n integrationTime = SMPH.integrationTime; // minutes\n }\n integTimePrecision = common.getPrecision(\"\" + integrationTime);\n if (SMPH.verbose > 4) {\n console.log(\"integration time = \" + integrationTime +\n \" with precision \" + integTimePrecision);\n }\n\n //---------------------------------------------------------\n // initialization for temperature decay and forced cooling\n\n // determine temperature decay type\n if (ibu.tempDecayType.value == \"tempDecayLinear\") {\n isTempDecayLinear = 1;\n } else if (ibu.tempDecayType.value == \"tempDecayExponential\") {\n isTempDecayLinear = 0;\n } else {\n console.log(\"ERROR: unknown temp decay type: \" + ibu.tempDecayType.value);\n isTempDecayLinear = 0;\n }\n\n // get forced cooling function decay rate or transfer rate\n if (coolingMethod == \"forcedDecayCounterflow\") {\n xferRate = ibu.counterflowRate.value;\n if (SMPH.verbose > 4)\n console.log(\"cooling method = \" + coolingMethod + \", rate = \" + xferRate);\n } else if (coolingMethod == \"forcedDecayImmersion\") {\n decayRate = ibu.immersionDecayFactor.value;\n if (SMPH.verbose > 4)\n console.log(\"cooling method = \" + coolingMethod + \", rate = \" +decayRate);\n } else if (coolingMethod == \"forcedDecayIcebath\") {\n decayRate = ibu.icebathDecayFactor.value;\n if (SMPH.verbose > 4)\n console.log(\"cooling method = \" + coolingMethod + \", rate = \" +decayRate);\n }\n\n // if counterflow chiller, but we're holding a temperature during whirlpool,\n // use immersion chiller decay rate for initial cooling.\n if (coolingMethod == \"forcedDecayCounterflow\" && holdTempCheckbox) {\n decayRate = ibu.immersionDecayFactor.value;\n }\n\n volumeChange = xferRate * integrationTime; // for counterflow chiller\n expParamC_Kelvin = common.convertCelsiusToKelvin(ibu.tempExpParamC.value);\n\n\n // print info for debugging\n if (SMPH.verbose > 4) {\n if (!isTempDecayLinear) {\n console.log(\"exponential decay: A=\" + ibu.tempExpParamA.value + \", B=\" +\n ibu.tempExpParamB.value + \", C=\" + ibu.tempExpParamC.value);\n } else {\n console.log(\"linear temp decay: A=\" + ibu.tempLinParamA.value + \", B=\" +\n ibu.tempLinParamB.value);\n }\n console.log(\"hold temp during hop stand? \" + holdTempCheckbox +\n \". hold temp is \" + holdTemp.toFixed(3));\n }\n\n //---------------------------------------------------------\n // other initialization\n\n // get post-boil volume; if zero, then set results to zero and return\n postBoilVolume = ibu.getPostBoilVolume();\n if (postBoilVolume <= 0.0) {\n for (hopIdx = 0; hopIdx < ibu.add.length; hopIdx++) {\n ibu.add[hopIdx].IAA_wort = 0.0;\n ibu.add[hopIdx].oAA_wort = 0.0;\n ibu.add[hopIdx].oBA_wort = 0.0;\n ibu.add[hopIdx].hopPP_wort = 0.0;\n }\n ibu.AA = 0.0;\n ibu.IAA = 0.0;\n ibu.U = 0.0;\n ibu.IAApercent = 0.0;\n ibu.oAA = 0.0;\n ibu.oBA = 0.0;\n ibu.hopPP = 0.0;\n ibu.maltPP = 0.0;\n ibu.FCT = 0.0;\n ibu.IBU = 0.0;\n return 0.0;\n }\n\n // get initial volume from post-boil volume, evaporation rate, and boil time\n initVolume = postBoilVolume + (ibu.evaporationRate.value/60.0 * boilTime);\n if (SMPH.verbose > 3) {\n console.log(\"volume at start of boil = \" +\n postBoilVolume.toFixed(3) + \" + (\" +\n ibu.evaporationRate.value.toFixed(3) +\n \"/60.0 * \" + boilTime + \") = \" + initVolume.toFixed(3));\n }\n\n // initialize some variables\n tempK = ibu.boilTemp.value + 273.15;\n tempC = common.convertKelvinToCelsius(tempK);\n k1 = 7.9*Math.pow(10.0,11.0)*Math.exp(-11858.0/tempK);\n k2 = 4.1*Math.pow(10.0,12.0)*Math.exp(-12994.0/tempK);\n if (SMPH.verbose > 3) {\n console.log(\"at temp \" + tempC.toFixed(2)+ \": rate constant k1 = \" +\n k1.toFixed(5) + \", k2 = \" + k2.toFixed(5));\n }\n\n holdTempK = common.convertCelsiusToKelvin(holdTemp);\n if (!holdTempCheckbox) holdTempK = 0.0; // 'Kelvin\n\n // make sure that boil time doesn't have higher precision than integ. time\n if (common.getPrecision(\"\" + boilTime) > integTimePrecision) {\n boilTime = Number(boilTime.toFixed(integTimePrecision));\n }\n\n // ---------------------------------------------------------------------------\n // PROCESS EACH TIME POINT\n\n // loop over each time point, from maximum time down until no more utilization\n // first, set initial values at start of boil\n finished = false;\n currVolume = initVolume;\n holdTempCounter = 0.0;\n whirlpoolTime = ibu.whirlpoolTime.value;\n origWhirlpoolTime = whirlpoolTime; // wpTime might be modified; keep a copy\n totalXferTime = 0.0;\n AA_dis_mg = 0.0; // mg of AA dissolved, not ppm to account for volume changes\n IAA_dis_mg= 0.0; // mg of IAA dissolved, not ppm to account for volume changes\n AA_xfer_mg = 0.0; // mg of AA transferred (and cooled) via counterflow\n IAA_xfer_mg = 0.0; // mg of IAA transferred via counterflow\n\n if (SMPH.verbose > 1) {\n console.log(\"\\nStarting processing of each time point:\");\n }\n for (t = boilTime; finished == false; t = t - integrationTime) {\n\n // -------------------------------------------------------------------------\n // adjust (as needed) temperature, whirlpool time, and volume during\n // counterflow. Also, check if done yet based on temp, time, and volume.\n\n // if post boil (t <= 0), then adjust temperature and degree of utilization\n // and if counterflow chiller and doing whirlpool, reduce volume of wort\n if (t <= 0) {\n postBoilTime = t * -1.0;\n if (postBoilTime == ibu.whirlpoolTime.value && SMPH.verbose > 1) {\n console.log(\"---- at \" + t + \", starting use of \" +\n coolingMethod + \" chiller ---\");\n }\n\n // if counterflow or not yet done with whirlpool, get temp from cooling fn\n if ((coolingMethod == \"forcedDecayCounterflow\" ||\n postBoilTime < whirlpoolTime) &&\n (!holdTempCheckbox || (holdTempCheckbox && doneHoldTemp))) {\n if (!isTempDecayLinear) {\n tempNoBase = tempK - expParamC_Kelvin;\n tempNoBase = tempNoBase +\n (-1.0*ibu.tempExpParamB.value*tempNoBase*integrationTime);\n tempK = tempNoBase + expParamC_Kelvin;\n } else {\n tempK = tempK + (ibu.tempLinParamA.value * integrationTime);\n }\n }\n\n // if immersion or icebath AND done with whirlpool, adjust\n // temp with new function\n if (coolingMethod == \"forcedDecayImmersion\" &&\n postBoilTime >= whirlpoolTime) {\n tempNoBase = tempK - SMPH.immersionChillerBaseTemp;\n tempNoBase = tempNoBase + (-1.0*decayRate*tempNoBase*integrationTime);\n tempK = tempNoBase + SMPH.immersionChillerBaseTemp;\n }\n if (coolingMethod == \"forcedDecayIcebath\" &&\n postBoilTime >= whirlpoolTime) {\n tempNoBase = tempK - SMPH.icebathBaseTemp;\n tempNoBase = tempNoBase + (-1.0*decayRate*tempNoBase*integrationTime);\n tempK = tempNoBase + SMPH.icebathBaseTemp;\n }\n\n // prevent numerical errors at <= 0 Kelvin\n if (tempK <= 1.0) tempK = 1.0;\n\n // if hold temperature during hop stand, see if need to cool to target\n if (holdTempCheckbox && tempK > holdTempK && !doneHoldTemp) {\n // if cool to target, use immersion chiller decay factor\n // regardless of the post-whirlpool cooling method\n tempNoBase = tempK - SMPH.immersionChillerBaseTemp;\n tempNoBase = tempNoBase + (-1.0*decayRate*tempNoBase*integrationTime);\n tempK = tempNoBase + SMPH.immersionChillerBaseTemp;\n // however, if tempExpParamA = 0 and C < holdTemp('C), this\n // means to instantaneously cool the wort to the target temperature\n if (ibu.tempExpParamA.value==0 && ibu.tempExpParamC.value < holdTemp) {\n tempK = holdTempK;\n }\n whirlpoolTime += integrationTime;\n whirlpoolTime = Number(whirlpoolTime.toFixed(4));\n // console.log(\"POST-BOIL quickly cool to target \" +\n // (holdTempK-273.15).toFixed(2) +\n // \", current temp = \" + (tempK-273.15).toFixed(2) +\n // \", WP time now \" + whirlpoolTime.toFixed(2));\n }\n\n // if hold temperature during hop stand, and reached target temp, hold it\n if (holdTempCheckbox && tempK <= holdTempK && !doneHoldTemp) {\n holdTempCounter += integrationTime;\n tempK = holdTempK;\n if (holdTempCounter > origWhirlpoolTime) {\n doneHoldTemp = true;\n if (SMPH.verbose > 1) {\n console.log(\"Done with post-boil whirlpool; whirlpool time = \" +\n whirlpoolTime);\n }\n }\n }\n\n // stop modeling if temperature is less than minimum for isomerization\n tempC = common.convertKelvinToCelsius(tempK);\n if (tempC < SMPH.immersionMinTempC) {\n finished = true;\n }\n\n // limit to whirlpool time plus two hours, just to prevent infinite loop\n // (after 2 hours, almost no increase in utilization anyway)\n if (postBoilTime > whirlpoolTime + 120.0) {\n finished = true;\n }\n\n // if using counterflow chiller and we've finished whirlpool/stand time,\n // do transfer and reduce volume of wort. Check if volume reduced to 0,\n // in which case we're done.\n if (coolingMethod == \"forcedDecayCounterflow\" &&\n postBoilTime >= whirlpoolTime) {\n // keep concentration the same as the wort transfers. therefore,\n // AA_(t-1) / volume_(t-1) = AA_t / volume_t, so\n // AA_t = (AA_(t-1) / volume_(t-1)) * volume_t\n // AA_t = (AA_(t-1) / currVolume) * (currVolume-volumeChange)\n newAA_mg = (AA_dis_mg / currVolume) * (currVolume - volumeChange);\n AA_xfer_mg += AA_dis_mg - newAA_mg;\n AA_dis_mg = newAA_mg;\n\n newIAA_mg = (IAA_dis_mg / currVolume) * (currVolume - volumeChange);\n IAA_xfer_mg += IAA_dis_mg - newIAA_mg;\n IAA_dis_mg = newIAA_mg;\n\n if (AA_dis_mg < 0.0) AA_dis_mg = 0.0;\n if (IAA_dis_mg < 0.0) IAA_dis_mg = 0.0;\n\n // adjust AA and IAA levels of each separate addition\n for (hopIdx = 0; hopIdx < ibu.add.length; hopIdx++) {\n newAA_mg = (ibu.add[hopIdx].AA_dis_mg / currVolume) *\n (currVolume - volumeChange);\n ibu.add[hopIdx].AA_xfer_mg += ibu.add[hopIdx].AA_dis_mg - newAA_mg;\n ibu.add[hopIdx].AA_dis_mg = newAA_mg;\n\n newIAA_mg = (ibu.add[hopIdx].IAA_dis_mg / currVolume) *\n (currVolume - volumeChange);\n ibu.add[hopIdx].IAA_xfer_mg += ibu.add[hopIdx].IAA_dis_mg - newIAA_mg;\n ibu.add[hopIdx].IAA_dis_mg = newIAA_mg;\n\n if (ibu.add[hopIdx].AA_dis_mg < 0.0)\n ibu.add[hopIdx].AA_dis_mg = 0.0;\n if (ibu.add[hopIdx].IAA_dis_mg < 0.0)\n ibu.add[hopIdx].IAA_dis_mg= 0.0;\n }\n\n // decrease the volume; check if we're done\n currVolume = currVolume - volumeChange;\n totalXferTime = totalXferTime + integrationTime;\n if (currVolume <= 0.0) {\n currVolume = 0.0;\n finished = true;\n }\n }\n }\n\n\n // -------------------------------------------------------------------------\n // add hops, as needed\n\n // Check to see if add any hops should be added at this time point.\n // Apply AA saturation limit, if needed.\n for (hopIdx = 0; hopIdx < ibu.add.length; hopIdx++) {\n additionTime = ibu.add[hopIdx].boilTime.value;\n // make sure that addition time doesn't have higher precision than integ.\n if (common.getPrecision(\"\" + additionTime) > integTimePrecision) {\n additionTime = Number(additionTime.toFixed(integTimePrecision));\n }\n if (Math.round(t * 1000) == Math.round(additionTime * 1000)) {\n AA_percent = (ibu.add[hopIdx].AA.value / 100.0) *\n ibu.add[hopIdx].freshnessFactor.value;\n AA_init_mg = AA_percent * ibu.add[hopIdx].weight.value * 1000.0;\n AA_init = AA_init_mg / currVolume;\n ibu.add[hopIdx].AA_init = AA_init;\n ibu.add[hopIdx].AA_dis_mg = AA_init_mg;\n ibu.add[hopIdx].effectiveSteepTime = 0.0;\n ibu.add[hopIdx].AA_added_mg = AA_init_mg;\n\n if (SMPH.verbose > 1) {\n console.log(\"ADDING HOPS ADDITION \" + hopIdx + \" at \" + t + \"min :\");\n console.log(\" AA=\" + ibu.add[hopIdx].AA.value + \"%, weight=\" +\n ibu.add[hopIdx].weight.value.toFixed(3) + \" grams \" +\n \" and [AA]_init = \" + AA_init.toFixed(2));\n console.log(\" at time \" + t.toFixed(2) +\n \" with volume \" + currVolume.toFixed(3) +\n \", adding AA \" + AA_init_mg.toFixed(3) +\n \" (mg) to existing AA = \" + AA_dis_mg.toFixed(3) + \" (mg)\");\n }\n\n // get the current total of dissolved AA (in mg), before current add\n preAdd_AA_mg = AA_dis_mg;\n\n // if use solubility limit, see if we need to change AA concentration\n if (useSolubilityLimit) {\n AA_limit_minLimit = AA_limit_minLimit_orig;\n AA_limit_maxLimit = AA_limit_maxLimit_orig;\n // if add hops at below boiling, lower the solubility limit\n if (tempK < 373.15) {\n // change AA_limit_minLimit, AA_limit_maxLimit based on temperature\n boilK = ibu.boilTemp.value + 273.15;\n slope = (SMPH.AA_limit_minLimit - SMPH.AA_limit_min_roomTemp) /\n (boilK - roomTempK);\n AA_limit_minLimit = slope * (tempK - roomTempK) +\n SMPH.AA_limit_min_roomTemp;\n slope = (SMPH.AA_limit_maxLimit - SMPH.AA_limit_max_roomTemp) /\n (boilK - roomTempK);\n AA_limit_maxLimit = slope * (tempK - roomTempK) +\n SMPH.AA_limit_max_roomTemp;\n if (SMPH.verbose > 2) {\n console.log(\" change due to low temp \" + tempK.toFixed(4) +\n \": AA_limit_maxLimit = \" + AA_limit_minLimit.toFixed(4) +\n \", AA_limit_minLimit = \" + AA_limit_maxLimit.toFixed(4));\n }\n }\n if (AA_limit_maxLimit <= AA_limit_minLimit) {\n AA_limit_maxLimit = AA_limit_minLimit + 0.0001; // prevent log(<=0)\n }\n AA_limit_func_A = AA_limit_maxLimit;\n AA_limit_func_B =\n -1.0* Math.log(1.0 - (AA_limit_minLimit/AA_limit_maxLimit)) /\n AA_limit_minLimit;\n if (SMPH.verbose > 3) {\n console.log(\" AA_limit_func_A = \" + AA_limit_func_A.toFixed(4) +\n \", AA_limit_func_B = \" + AA_limit_func_B.toFixed(6));\n }\n\n // if pre-addition [AA] is above threshold, find out what [AA] would\n // be at this point in time if there was no solubility limit\n AA_dis = AA_dis_mg / currVolume;\n if (AA_dis > AA_limit_minLimit) {\n AA_noLimit = -1.0*Math.log(1.0 - (AA_dis/AA_limit_func_A)) /\n AA_limit_func_B;\n } else {\n AA_noLimit = AA_dis;\n }\n if (SMPH.verbose > 3) {\n console.log(\" [AA] before addition, without limits = \" +\n AA_noLimit.toFixed(4) + \" ppm\");\n console.log(\" adding \" + AA_init.toFixed(4) + \" ppm of AA\");\n }\n\n // make the new AA addition to current AA *without* solubility limit\n AA_noLimit = AA_noLimit + AA_init;\n AA_noLimit_mg = AA_noLimit * currVolume;\n\n // and (re-)apply solubility limit, if necessary\n if (AA_noLimit > AA_limit_minLimit) {\n AA_dis = AA_limit_func_A *\n (1.0 - Math.exp(-1.0 * AA_limit_func_B * AA_noLimit));\n } else {\n AA_dis = AA_noLimit;\n }\n AA_dis_mg = AA_dis * currVolume;\n\n if (SMPH.verbose > 2) {\n console.log(\" final [AA]_dissolved = \" + AA_dis.toFixed(4) +\n \" ppm = \" + AA_dis_mg.toFixed(4) + \" / \" + currVolume.toFixed(4));\n }\n\n // get dissolved AA in mg for this addition of hops\n ibu.add[hopIdx].AA_dis_mg = AA_dis_mg - preAdd_AA_mg;\n } else {\n // don't use solubility limit, just accumulate AA\n AA_dis_mg += AA_init_mg;\n }\n\n // compute mg of oAA added with this hop addition\n compute_oAA_dis_mg(ibu, hopIdx, currVolume);\n\n // compute mg of oBA added with this hop addition\n compute_oBA_dis_mg(ibu, hopIdx, currVolume);\n\n // compute mg of PP added with this hop addition\n compute_hopPP_dis_mg(ibu, hopIdx, currVolume);\n\n } // check for hop addition at this time\n } // evaluate all hop additions\n\n\n // -------------------------------------------------------------------------\n // change concentrations of dissolved AA and dissolved IAA\n\n // adjust isomerization rate constants based on current temperature\n k1 = 7.9*Math.pow(10.0,11.0)*Math.exp(-11858.0/tempK);\n k2 = 4.1*Math.pow(10.0,12.0)*Math.exp(-12994.0/tempK);\n\n // decrease levels of dissolved AA via conversion to IAA\n dAA_dis_mg = -1.0 * k1 * AA_dis_mg;\n AA_dis_mg = AA_dis_mg + (dAA_dis_mg * integrationTime);\n if (AA_dis_mg < 0.0) AA_dis_mg = 0.0;\n\n // change levels of dissolved IAA via conversion to degradation products\n dIAA_dis_mg = (k1 * AA_dis_mg) - (k2 * IAA_dis_mg);\n IAA_dis_mg = IAA_dis_mg + (dIAA_dis_mg * integrationTime);\n if (IAA_dis_mg < 0.0) IAA_dis_mg = 0.0;\n\n // compute AA and IAA levels for each separate addition\n for (hopIdx = 0; hopIdx < ibu.add.length; hopIdx++) {\n dAA_dis_mg = -1.0 * k1 * ibu.add[hopIdx].AA_dis_mg;\n ibu.add[hopIdx].AA_dis_mg += dAA_dis_mg * integrationTime;\n if (ibu.add[hopIdx].AA_dis_mg < 0.0) ibu.add[hopIdx].AA_dis_mg = 0.0;\n\n dIAA_dis_mg = (k1 * ibu.add[hopIdx].AA_dis_mg) -\n (k2 * ibu.add[hopIdx].IAA_dis_mg);\n ibu.add[hopIdx].IAA_dis_mg += dIAA_dis_mg * integrationTime;\n if (ibu.add[hopIdx].IAA_dis_mg < 0.0) ibu.add[hopIdx].IAA_dis_mg = 0.0;\n\n // use IAA relative temp as proxy for everything happening at each temp.\n relativeTemp = 2.39 * Math.pow(10.0,11) * Math.exp(-9773.0/tempK);\n if (relativeTemp > 1.0) relativeTemp = 1.0;\n if (relativeTemp < 0.0) relativeTemp = 0.0;\n ibu.add[hopIdx].effectiveSteepTime += integrationTime * relativeTemp;\n }\n\n // every 5 minutes, print out some information to the console\n if (SMPH.verbose > 3 && Math.round(t * 1000) % 5000 == 0) {\n AA_dis = AA_dis_mg / currVolume;\n dAA_dis_mg = -1.0 * k1 * AA_dis_mg;\n dIAA_dis_mg = (k1 * AA_dis_mg) - (k2 * IAA_dis_mg);\n console.log(\"time = \" + t.toFixed(3));\n console.log(\" temp = \" + tempC.toFixed(2));\n console.log(\" volume = \" + currVolume.toFixed(4));\n console.log(\" AA = \" + AA_dis.toFixed(4) + \" ppm \" +\n \"with delta \" + dAA_dis_mg.toFixed(6) + \" mg/min\");\n console.log(\" IAA = \" + (IAA_dis_mg/currVolume).toFixed(4)+\" ppm \" +\n \"with delta \" + dIAA_dis_mg.toFixed(6) + \" mg/min\");\n if (t == 0) {\n console.log(\" -------- end of boil --------\");\n }\n }\n\n\n // adjust current volume due to evaporation\n if (t >= 0) {\n // if boiling, use evaporation rate\n currVolume -= ibu.evaporationRate.value/60.0 * integrationTime;\n } else {\n // if sub-boiling, estimate evaporation rate\n // from exponential fit to 20 = 0.0, 80 = 1.36, 100 = 3.672\n evapRateAtTemp = 0.0243 * Math.exp(0.0502 * tempC); // liters/hr\n evapRateAtBoil = 3.679294682; // 0.0243 * Math.exp(0.0502*100.0); // l/hr\n if (evapRateAtTemp > evapRateAtBoil) evapRateAtTemp = evapRateAtBoil;\n subBoilEvapRate = ibu.evaporationRate.value*evapRateAtTemp/evapRateAtBoil;\n currVolume -= subBoilEvapRate/60.0 * integrationTime;\n }\n\n // prevent floating-point drift in 'time' variable\n t = Number(t.toFixed(4));\n }\n\n // ---------------------------------------------------------------------------\n // FINALIZE\n\n // adjust IAA based on IAA rate factor\n RF_IAA = compute_RF_IAA(ibu);\n IAA_dis_mg *= RF_IAA;\n IAA_xfer_mg *= RF_IAA;\n for (hopIdx = 0; hopIdx < ibu.add.length; hopIdx++) {\n ibu.add[hopIdx].IAA_dis_mg *= RF_IAA;\n ibu.add[hopIdx].IAA_xfer_mg *= RF_IAA;\n }\n\n // compute forced cooling time (FCT)\n FCT = (-1.0 * t) - ibu.whirlpoolTime.value;\n\n // adjust amount of dissolved material based on wort/trub loss and\n // topoff volume added\n finalVolume = postBoilVolume;\n if (ibu.wortLossVolume.value > 0) {\n // if wort loss after boil, adjust final volume and final mg of IAA,\n // oAA, oBA, PP, keeping overall concentrations the same\n finalVolume = postBoilVolume - ibu.wortLossVolume.value;\n if (finalVolume < 0.0) finalVolume = 0.0;\n IAA_dis_mg *= 1.0 - (ibu.wortLossVolume.value / postBoilVolume);\n if (IAA_dis_mg < 0.0) IAA_dis_mg = 0.0;\n if (SMPH.verbose > 1) {\n console.log(\"FINAL VOL = \" + postBoilVolume.toFixed(4) + \" minus loss \" +\n ibu.wortLossVolume.value.toFixed(4));\n }\n for (hopIdx = 0; hopIdx < ibu.add.length; hopIdx++) {\n ibu.add[hopIdx].IAA_dis_mg *=\n 1.0 - (ibu.wortLossVolume.value / postBoilVolume);\n ibu.add[hopIdx].oAA_dis_mg *=\n 1.0 - (ibu.wortLossVolume.value / postBoilVolume);\n ibu.add[hopIdx].oBA_dis_mg *=\n 1.0 - (ibu.wortLossVolume.value / postBoilVolume);\n ibu.add[hopIdx].hopPP_dis_mg *=\n 1.0 - (ibu.wortLossVolume.value / postBoilVolume);\n }\n }\n\n finalVolume += ibu.topoffVolume.value;\n if (finalVolume == 0) {\n finalVolume = 0.01; // prevent division by zero\n }\n\n // for each addition, compute IAA concentration in wort that includes\n // both IAA dissolved in the wort in the kettle and IAA that were\n // transferred out of the kettle. Then normalize by final volume.\n for (hopIdx = 0; hopIdx < ibu.add.length; hopIdx++) {\n ibu.add[hopIdx].IAA_wort_mg =\n (ibu.add[hopIdx].IAA_dis_mg + ibu.add[hopIdx].IAA_xfer_mg);\n ibu.add[hopIdx].IAA_wort =\n (ibu.add[hopIdx].IAA_dis_mg + ibu.add[hopIdx].IAA_xfer_mg)/finalVolume;\n ibu.add[hopIdx].oAA_wort = ibu.add[hopIdx].oAA_dis_mg / finalVolume;\n ibu.add[hopIdx].oBA_wort = ibu.add[hopIdx].oBA_dis_mg / finalVolume;\n ibu.add[hopIdx].hopPP_wort = ibu.add[hopIdx].hopPP_dis_mg / finalVolume;\n if (SMPH.verbose > 0) {\n console.log(\" hop addition \" + hopIdx + \" has vol=\" +\n finalVolume.toFixed(4) + \" liters, [IAA]=\" +\n ibu.add[hopIdx].IAA_wort.toFixed(4) + \" ppm, [oAA]=\" +\n ibu.add[hopIdx].oAA_wort.toFixed(4) + \" ppm, [oBA]=\" +\n ibu.add[hopIdx].oBA_wort.toFixed(4) + \" ppm, [PP]=\" +\n ibu.add[hopIdx].hopPP_wort.toFixed(4));\n }\n }\n\n\n // print out summary information to console when done\n if (SMPH.verbose > 2) {\n console.log(\" >> forced cooling time = \" + FCT.toFixed(2) + \" minutes\");\n console.log(\" >> temperature at end = \" + tempC.toFixed(2) + \"'C after \");\n if (coolingMethod == \"forcedDecayCounterflow\") {\n console.log(\" transfer time \" + totalXferTime.toFixed(2) + \" min\");\n } else {\n console.log(\" \" + (-1*t).toFixed(3) + \" minutes after flameout \" +\n \" (whirlpool = \" + whirlpoolTime +\n \" min, chilling time \" + (-1*(t+whirlpoolTime)).toFixed(2) +\n \" min)\");\n }\n console.log(\">>> IAA in wort = \" +\n ((IAA_dis_mg + IAA_xfer_mg)/finalVolume).toFixed(4) + \" ppm\");\n }\n\n return FCT;\n}",
"function hireaddbal() {\n sum = 0;\n master.hireitems.forEach(function (item) {\n sum += Math.floor(item.multi * item.quan * master.imp.balmulti);\n });\n addbal(sum);\n}",
"function compute_LF_oAA_pH(ibu) {\n var LF_pH = 1.0;\n var pH = ibu.pH.value;\n var preBoilpH = 0.0;\n var preOrPostBoilpH = ibu.preOrPostBoilpH.value;\n\n if (ibu.pHCheckbox.value) {\n // If pre-boil pH, estimate the post-boil pH which is the\n // one we want to base losses on.\n if (preOrPostBoilpH == \"preBoilpH\") {\n preBoilpH = pH;\n pH = compute_postBoil_pH(preBoilpH);\n }\n\n // formula from blog post 'The Effect of pH on Utilization and IBUs'\n LF_pH = (1.178506 * pH) - 5.776411\n if (SMPH.verbose > 5) {\n console.log(\"pH = \" + pH + \", LF for nonIAA = \" + LF_pH.toFixed(4));\n }\n }\n\n return LF_pH;\n}",
"function countHcoverHwiMinus() {\n\t\t\tif(instantObj.noOfHcoverHWI > 0) {\n\t\t\t\tinstantObj.noOfHcoverHWI = instantObj.noOfHcoverHWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}",
"function compute_LF_oAA(ibu, hopIdx) {\n var LF_oAA = 0.0;\n var oAA_LF_boil = 0.0;\n\n // enforce that oAA_LF_boil is same as IAA loss factor\n oAA_LF_boil = SMPH.IAA_LF_boil;\n\n LF_oAA = oAA_LF_boil *\n compute_LF_OG_SMPH(ibu, hopIdx) *\n compute_LF_oAA_pH(ibu) *\n compute_LF_ferment(ibu) *\n compute_LF_nonIAA_krausen(ibu) *\n compute_LF_finings(ibu) *\n compute_LF_filtering(ibu) *\n compute_LF_age(ibu);\n if (SMPH.verbose > 5) {\n console.log(\" LF oAA \" + LF_oAA.toFixed(4));\n console.log(\" from \" + oAA_LF_boil + \", \" +\n compute_LF_oAA_pH(ibu) + \", \" +\n compute_LF_OG_SMPH(ibu, hopIdx) + \", \" +\n compute_LF_ferment(ibu) + \", \" +\n compute_LF_nonIAA_krausen(ibu) + \", \" +\n compute_LF_finings(ibu) + \", \" +\n compute_LF_filtering(ibu) + \", \" +\n compute_LF_age(ibu));\n }\n return(LF_oAA);\n}",
"function countHcoverHwiPlus() {\n\t\t\tinstantObj.noOfHcoverHWI = instantObj.noOfHcoverHWI + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"function countLungiDhotiMwiMinus() {\n\t\t\tif(instantObj.noOfLungiDhotiMWI > 0) {\n\t\t\t\tinstantObj.noOfLungiDhotiMWI = instantObj.noOfLungiDhotiMWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}",
"function countLungiDhotiMwiPlus() {\n\t\t\tinstantObj.noOfLungiDhotiMWI = instantObj.noOfLungiDhotiMWI + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"function countSuitsBlazerMwiPlus() {\n\t\t\tinstantObj.noOfSuitsBlazerMWI = instantObj.noOfSuitsBlazerMWI + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"function countLcoverHwiPlus() {\n\t\t\tinstantObj.noOfLcoverHWI = instantObj.noOfLcoverHWI + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"function countSuitsBlazerWwiPlus() {\n\t\t\tinstantObj.noOfSuitsBlazerWWI = instantObj.noOfSuitsBlazerWWI + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"function compute_LF_IAA_pH(ibu) {\n var LF_pH = 1.0;\n var pH = ibu.pH.value;\n var preBoilpH = 0.0;\n var preOrPostBoilpH = ibu.preOrPostBoilpH.value;\n\n if (ibu.pHCheckbox.value) {\n // If pre-boil pH, estimate the post-boil pH which is the\n // one we want to base losses on.\n if (preOrPostBoilpH == \"preBoilpH\") {\n preBoilpH = pH;\n pH = compute_postBoil_pH(preBoilpH);\n }\n\n // formula from blog post 'The Effect of pH on Utilization and IBUs'\n LF_pH = (0.071 * pH) + 0.592;\n if (SMPH.verbose > 5) {\n console.log(\"pH = \" + pH + \", LF for IAA = \" + LF_pH.toFixed(4));\n }\n }\n\n return LF_pH;\n}",
"calcAggregatedIgnorance() {\n if (this.debug) console.log(\"\\nCALC Aggregated Ignorance - PROJECT - >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n var data = this.data;\n data.Ignorance = data.MdashH / (1 - data.MlH);\n if (this.debug) console.log(\"data.Ignorance: \" + data.Ignorance);\n\n // Calculate and save distributed ignorance divided by number of alternatives\n // For Distributed Ignorance table\n data.IgnoranceSplit = data.Ignorance/data.alternatives.length;\n }",
"function compute_LF_hopPP(ibu) {\n var LF_hopPP = 0.0;\n\n // Assume krausen, finings, filtering affect hop PP the same as other nonIAA.\n LF_hopPP = SMPH.LF_hopPP *\n SMPH.ferment_hopPP *\n compute_LF_nonIAA_krausen(ibu) *\n compute_LF_finings(ibu) *\n compute_LF_filtering(ibu);\n\n return(LF_hopPP);\n}",
"calcularImpuesto() {\r\n return (this._impuesto._monto_bruto_anual - this._impuesto._deducciones) * 0.21\r\n }",
"function calcSuper(gSal) {\r\n return (gSal * .095)\r\n}",
"function exe7(total, elemento) {\n return total - elemento\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
select and analyze GranD dam | function analyzeGranD() {
var zoomLevel = 12
var dam = getDamAfter2000()
//Map.centerObject(dam, zoomLevel)
var bounds = ee.Geometry(Map.getBounds(true))
var images = analyzeDamsAfter2000(bounds)
var beforeConstruction = images[0]
var afterConstruction = images[1]
var percentiles = [10, 20, 30, 40, 50, 60, 70, 80, 90]
var percentileImages = addPercentileImages(l8, percentiles)
var useRealImage = true;
if(useRealImage) {
var image = afterConstruction;
var cloudscore = ee.Image(1).subtract(image.select('cloudscore'))
var vegetationscore = image.select('vegetationscore');
} else {
var image = percentileImages[0]
var cloudscore = ee.Image(0)
var vegetationscore = vegetationScore(image);
}
addDemScaledToBounds(bounds)
analyzeCloudsAndWater(bounds, image)
} | [
"function main () {\n\n pg_handler.pool_query_db(pg_pool, query_text, [], function(query_result) {\n if (query_result.rows && query_result.rows.length) {\n const scenes_by_dataset = usgs_helpers.sort_scene_records_by_dataset(query_result.rows)\n var dataset_names = usgs_constants.LANDSAT_DATASETS.slice()\n usgs_helpers.process_scenes_by_dataset(\n dataset_names, scenes_by_dataset, process_scenes_for_dataset\n )\n } else {\n logger.log(\n logger.LEVEL_INFO,\n 'INFO select query returned no rows to process.'\n )\n }\n })\n\n}",
"function selectHouses() {\n console.log(\"got to selecthouses\");\n // If no further limits have been entered, just make the finalGroup array equal to the areaGroup\n // array — we don't want to filter the houses further — then run updateDisplay().\n if ( builtTarget.value == \"anyyearbuilt\" && accessTarget.value == \"anyaccessibility\" ) {\n //console.log(\"no further filter\");\n finalGroup = areaGroup;\n //console.log(\"final group\", finalGroup);\n updateDisplay();\n } else if ( builtTarget.value == \"anyyearbuilt\" ) {\n // ONLY LIMIT BY ACCESS\n //console.log(\"access filter\");\n for( let i = 0; i < areaGroup.length ; i++ ) {\n if( areaGroup[i].accessible == accessTarget.value ) {\n finalGroup.push(areaGroup[i]);\n }\n }\n updateDisplay();\n } else if ( accessTarget.value == \"anyaccessibility\" ) {\n // ONLY LIMIT BY BUILT\n //console.log(\"built filter\");\n for( let i = 0; i < areaGroup.length ; i++ ) {\n let range = (builtTarget.value).split(\"-\");\n let min = range[0];\n let max = range[1];\n if( areaGroup[i].built >= min && areaGroup[i].built <= max ) {\n finalGroup.push(areaGroup[i]);\n }\n }\n updateDisplay();\n } else {\n // LIMIT BY BOTH\n //console.log(\"both filter\");\n for( let i = 0; i < areaGroup.length ; i++ ) {\n let range = (builtTarget.value).split(\"-\");\n let min = range[0];\n let max = range[1];\n if( areaGroup[i].built >= min && areaGroup[i].built <= max && areaGroup[i].accessible == accessTarget.value ) {\n finalGroup.push(areaGroup[i]);\n }\n }\n updateDisplay();\n }\n\n }",
"function analyze() {\n raf = requestAnimationFrame(analyze);\n var stream = audioAnalyzer.getFrequencyAnalysis();\n\n if(false === stream) {\n onEnd();\n return;\n }\n\n var a = utils.average(stream),\n id;\n // Glitch on clap\n if (a > 100.5 && a < 102.5) {\n if(Date.now() - lastGlitch < 500) {\n // Don't replay glitch before 0.5s\n return;\n }\n // Play glitch scene\n SM.play(0);\n lastSwitch = lastGlitch = Date.now();\n\n return;\n }\n // Change scene on specific frequency\n if(a > 78 && a < 88) {\n if(Date.now() - lastSwitch < 300) {\n // Don't change scene before 0.3s\n return;\n }\n\n playRandomScene();\n if (false === rendering) {\n SM.render();\n TweenMax.set(render, {autoAlpha: 1, display: 'block'});\n rendering = true;\n }\n lastSwitch = Date.now();\n }\n}",
"compute(filtered = false) {\n let countDownFiles = 0;\n let datasetCount = 0;\n let sumExistenceDate = 0; //exda - Average\n let sumExistenceDiscovery = 0; //exdi Average\n let sumExistenceContact = 0; //exco BOOLEAN MAX\n let sumConformanceLicense = 0; //coli BOOLEAN\n let sumConformanceDateFormat = 0;//coda NUMBER\n let sumConformanceAccess = 0; //coac BOOLEAN\n let sumOpendataOpenFormat = 0;//opfo NUMBER\n let sumOpendataMachineRead = 0; //opma NUMBER\n\n\n const dirPath = `./dados/${this._snapshot}/${this._portalId}/${filtered ? 'filter' : ''}`;\n fs.readdir(dirPath, function (e, files) {\n if (e) {\n console.error(colors.red(e));\n global.log.error(e);\n } else {\n countDownFiles = files.length;\n files.forEach(function (f) {\n if (fs.statSync(path.join(dirPath, f)).isFile()) {\n const regEx = /^datasets-[A-z]+-(.*?).json$/;\n const match = regEx.exec(f);\n if (match != null) {\n datasetCount++;\n fs.readFile(path.join(`./dados/${this._snapshot}/${this._portalId}/metrics/`, `${match[1]}.json`), 'UTF-8', function (e, data) {\n if (e) {\n console.error(`Leitura de ${path.join(dirPath, f)}`, colors.red(e));\n global.log.error(e);\n throw e;\n }\n let metrics = JSON.parse(data);\n sumExistenceDate += metrics.exda;\n sumExistenceDiscovery += metrics.exdi;\n sumExistenceContact += metrics.exco ? 1 : 0;\n sumConformanceLicense += metrics.coli ? 1 : 0;\n sumConformanceDateFormat += metrics.coda;\n sumConformanceAccess += metrics.coac ? 1 : 0;\n sumOpendataOpenFormat += metrics.opfo;\n sumOpendataMachineRead += metrics.opma;\n\n countDownFiles--;\n if (countDownFiles == 0) {\n this._existenceDate = sumExistenceDate / datasetCount;\n this._existenceDiscovery = sumExistenceDiscovery / datasetCount;\n this._existenceContact = sumExistenceContact / datasetCount;\n this._conformanceLicense = sumConformanceLicense / datasetCount;\n this._conformanceDateFormat = sumConformanceDateFormat / datasetCount;\n this._conformanceAccess = sumConformanceAccess / datasetCount;\n this._opendataOpenFormat = sumOpendataOpenFormat / datasetCount;\n this._opendataMachineRead = sumOpendataMachineRead / datasetCount;\n console.log(colors.yellow(this._portalId), `${filtered ? '(filtrado)'.yellow : ''}:`, datasetCount);\n console.log('Existence Date: ', this._existenceDate);\n console.log('Existence Discovery: ', this._existenceDiscovery);\n console.log('Existence Contact: ', this._existenceContact);\n console.log('Conformance License: ', this._conformanceLicense);\n console.log('Conformance Date Format: ', this._conformanceDateFormat);\n console.log('Conformance Access: ', this._conformanceAccess);\n console.log('Opendata Open Format: ', this._opendataOpenFormat);\n console.log('Opendata Machine Read: ', this._opendataMachineRead);\n }\n }.bind(this));\n }\n } else {\n countDownFiles--;\n }\n }.bind(this))\n\n }\n }.bind(this))\n }",
"function analyze(args){\n let passData = {};\n passData.date = new Date();\n \n if(args.hasArg('date')){\n passData.date = new Date(args.getArg('date'));\n }\n \n if(args.hasArg('groupby')){\n passData.groupby = args.getArg('groupby');\n if(args.hasArg('and')){\n passData.and = args.getArg('and');\n }\n }\n\n var data = model.analyze(passData);\n if(_.isEmpty(data)){\n console.log(\"There are no timers for this date\");\n }else{\n\n console.log(columnify(data, {config: { description: {maxWidth: 30}}}));\n }\n }",
"function summarize() {\n\n\tsetSummarySelection(); // fill selection.network, selection.summarization, selection.seed];\n\n\tdeleteNetwork(selection.network.id, 1); // delete selected network in SVG1\n\t\n\trelevance();\n\tconnectivity();\n\tif (selection.connections > 0) extendConnections();\n\t\n\tif (selection.maxNodes != 1000) { // 1000 = return all\n\t\tsaliency();\n\t\tpushSalient(); // copy salient nodes and links from summary arrays to SVG1 arrays\n\t} \n\telse {\n\t\tpushSummarized(); // copy nodes and links from summary arrays to SVG1 arrays\n\t}\n\n\n\t// anchor = highest degree node\n\tsetDegree(nodes);\n\n\tvar Anchor = setAnchor(selection.network.id);\n\tcreateAnchorGradient(Anchor);\n\n\tstart();\n\n\tresetPredCheckboxes();\n\tresetSemGroupCheckboxes();\n\t\n\tfreezeNetwork(true); // unfreeze all networks\n\n\t// fade in\n\tsvg1.style(\"opacity\", function(){return 1e-6;})\n\t\t.transition()\n\t\t.duration(2000)\n\t\t.style(\"opacity\", function(){return 1;});\n}",
"function analyze() {\n var highest = 0,\n lowest = 1000000000,\n averageQA = 0,\n averageAuton = 0,\n averageFouls = 0,\n totalNulls = 0,\n averagePlayoff = 0,\n totalPlayoffs = 0;\n\n for (var matchNum = 0; matchNum < matches.length; matchNum++) {\n\n var currentMatch = matches[matchNum];\n var currentMatchAlliances = currentMatch.alliances;\n var alliance = \"\";\n\n if (currentMatchAlliances.red.teams.indexOf(teamNumber) >= 0) {\n alliance = \"red\";\n } else {\n alliance = \"blue\";\n }\n\n if (currentMatchAlliances[alliance].score >= 0) {\n if (currentMatchAlliances[alliance].score > highest) {\n highest = currentMatchAlliances[alliance].score;\n }\n\n if (currentMatchAlliances[alliance].score < lowest) {\n lowest = currentMatchAlliances[alliance].score;\n }\n\n if (currentMatch.comp_level === 'qm') {\n averageQA += currentMatchAlliances[alliance].score;\n } else {\n averagePlayoff += currentMatchAlliances[alliance].score;\n totalPlayoffs++;\n }\n\n averageAuton += matches[matchNum].score_breakdown[alliance].atuo;\n\n averageFouls += matches[matchNum].score_breakdown[alliance].foul;\n\n } else {\n totalNulls++;\n }\n }\n\n if (totalPlayoffs !== 0) {\n averagePlayoff /= totalPlayoffs;\n }\n\n averageQA /= matches.length - totalNulls - totalPlayoffs;\n averageFouls /= matches.length - totalNulls;\n averageAuton /= matches.length - totalNulls;\n\n console.log('Analytics');\n console.log('Team Name: ' + teamName);\n console.log(\"Highest Number of points: \" + highest);\n console.log(\"Lowest Number of points: \" + lowest);\n console.log(\"Average QA: \" + averageQA);\n console.log(\"Average Playoff Points (If Applicable): \" + averagePlayoff);\n console.log(\"Average Auton points: \" + averageAuton);\n console.log(\"Average Foul points: \" + averageFouls);\n}",
"function changeMeasAtt(object){\r\n\r\n//1. Cambiamos el valor del input hidAttMeasName\r\n\tvar type = object.options[object.selectedIndex].getAttribute(\"attType\");\r\n\tvar father = object.parentNode;\r\n\twhile(father.tagName!=\"TR\"){\r\n\t\tfather=father.parentNode;\r\n\t}\r\n\tvar cells = father.cells;\r\n\tvar inputName = cells[1].getElementsByTagName(\"INPUT\")[1]; //input oculto que contiene el name\r\n\tvar inputType=cells[1].getElementsByTagName(\"INPUT\")[0]; //input oculto que contiene el type\r\n\t\r\n\tinputName.value=object.options[object.selectedIndex].text;//nombre del atributo\r\n\tinputType.value=type;\r\n\t\r\n//2. Filtramos los agregadores según el tipo de atributo\r\n\t //Si es numerico --> SUM, AVG, COUNT, MIN , MAX, DIST COUNT\r\n\t //Si es string --> COUNT, DIST COUNT\r\n\t //Si es date --> COUNT, DIST COUNT (MIN Y MAX? probar)\r\n\t\r\n\tvar selAgregator=cells[4].getElementsByTagName(\"SELECT\")[0];\r\n\twhile(selAgregator.options.length>0){\r\n\t\tselAgregator.removeChild(selAgregator.options[0]);\r\n\t}\r\n\tif (\"S\" == type){ //Atributo de tipo String\r\n\t \tvar opt1=document.createElement(\"OPTION\");\r\n\t \topt1.innerHTML=\"COUNT\";\r\n\t \topt1.value=\"2\";\r\n\t \tvar opt2=document.createElement(\"OPTION\");\r\n\t \topt2.innerHTML=\"DIST. COUNT\";\r\n\t \topt2.value=\"5\";\r\n\t \tselAgregator.appendChild(opt1);\r\n\t \tselAgregator.appendChild(opt2);\r\n\t }else if (\"D\" == type){//Atributo de tipo Date\r\n\t \tvar opt1=document.createElement(\"OPTION\");\r\n\t \topt1.innerHTML=\"COUNT\";\r\n\t \topt1.value=\"2\";\r\n\t \tvar opt2=document.createElement(\"OPTION\");\r\n\t \topt2.innerHTML=\"DIST. COUNT\";\r\n\t \topt2.value=\"5\";\r\n\t \tselAgregator.appendChild(opt1);\r\n\t \tselAgregator.appendChild(opt2);\r\n\t }else { //Atributo de tipo Numerico\r\n\t var opt0=document.createElement(\"OPTION\");\r\n\t \topt0.innerHTML=\"SUM\";\r\n\t \topt0.value=\"0\";\r\n\t \t\r\n\t var opt1=document.createElement(\"OPTION\");\r\n\t \topt1.innerHTML=\"AVG\";\r\n\t \topt1.value=\"1\";\r\n\t \t\r\n\t \tvar opt2=document.createElement(\"OPTION\");\r\n\t \topt2.innerHTML=\"COUNT\";\r\n\t \topt2.value=\"2\";\r\n\t \t\r\n\t \tvar opt3=document.createElement(\"OPTION\");\r\n\t \topt3.innerHTML=\"MIN\";\r\n\t \topt3.value=\"3\";\r\n\t \t\r\n\t \tvar opt4=document.createElement(\"OPTION\");\r\n\t \topt4.innerHTML=\"MAX\";\r\n\t \topt4.value=\"4\";\r\n\t \t\r\n\t \tvar opt5=document.createElement(\"OPTION\");\r\n\t \topt5.innerHTML=\"DIST. COUNT\";\r\n\t \topt5.value=\"5\";\r\n\t \t\r\n\t \tselAgregator.appendChild(opt0);\r\n\t \tselAgregator.appendChild(opt1);\r\n\t \tselAgregator.appendChild(opt2);\r\n\t \tselAgregator.appendChild(opt3);\r\n\t \tselAgregator.appendChild(opt4);\r\n\t \tselAgregator.appendChild(opt5);\r\n\t }\r\n}",
"function loadData(terror) {\r\n //console.log(terror)\r\n terror_filtered = terror.filter(d => {\r\n const { iyear, country, city, latitude, longitude, gname } = d;\r\n //data filtering \r\n if (!latitude || !longitude || !iyear) {\r\n return false;\r\n }\r\n return true;\r\n })\r\n\r\n max_cluster = Math.pow(2,ZOOM_LEVELS-1)\r\n clusters[0] = clusterRawData(terror_filtered, 0);\r\n clusters[max_cluster] = clusterRawData(terror_filtered, Number.MAX_SAFE_INTEGER)\r\n clusters[max_cluster*2] = clusterRawData(terror_filtered, Number.MAX_SAFE_INTEGER)\r\n let zoom = ZOOM_LEVELS\r\n for (let clustersIndex = 1; clustersIndex < max_cluster; clustersIndex*=2) {\r\n const modulo = (zoomLevelToClusterLevel(zoom))\r\n const cluster = clusterRawData(terror_filtered, modulo)\r\n clusters[clustersIndex] = cluster\r\n zoom--;\r\n }\r\n\r\n const groups = {}\r\n terror_filtered.forEach(t => {\r\n if (groups.hasOwnProperty(t.gname) == false) {\r\n groups[t.gname] = { g: t.gname, count: 0 }\r\n }\r\n groups[t.gname].count += 1;\r\n });\r\n\r\n let tempData = Object.keys(groups).map(c => {\r\n return groups[c];\r\n })\r\n tempData.sort((a, b) => b.count - a.count)\r\n tempData = tempData.slice(1,20)\r\n\r\n const unique_groups = {}\r\n //unique_groups = terror_filtered.filter( onlyUnique )\r\n tempData.forEach(d => {\r\n if(unique_groups.hasOwnProperty(d.g) == false) {\r\n unique_groups[d.g] = {}\r\n }\r\n })\r\n\r\n //$(\"#group_selection\").val(Object.keys(unique_groups));\r\n\r\n $.each(Object.keys(unique_groups), function(key, value) { \r\n $('#groups')\r\n .append($(\"<option></option>\")\r\n .attr(\"value\",value)\r\n .text(value)); \r\n\r\n });\r\n \r\n console.timeEnd('loadData')\r\n console.time('addMarkers')\r\n addMarkers();\r\n console.timeEnd('addMarkers')\r\n console.log(\"Marker load complete\")\r\n\r\n google.maps.event.addListener(map, 'bounds_changed', function () {\r\n //window.clearTimeout(bounds_check_freq);\r\n //bounds_check_freq = window.setTimeout(function () {\r\n addMarkers();\r\n //}, 20);\r\n });\r\n console.log(\"Cluster load complete\")\r\n}",
"function harvest(){\n nutrients += nutrientsPerClick;\n updateLabels();\n}",
"function estat(){}",
"function sithSelect() {\n\tfor (var l = 0; l < siths.length; l++) {\n\t\tif (siths[l].Eliminated === false) {\n\t\t\tsith_vs.Name(siths[l].Name);\n\t\t\tsith_vs.Health(siths[l].Health);\n\t\t\tsith_vs.Attack(siths[l].Attack);\n\t\t\tsith_vs.Counter(siths[l].Counter);\n\t\t\tsith_vs.Image(siths[l].Image);\n\n\t\t\t// Set the character in the array that is fighting\n\t\t\tsithVsChar = l;\n\n\t\t\t// play a lightsaber start-up sound effect\n\t\t\taudio1 = new Audio(\"assets/audio/saber_engage.wav\");\n\t\t\taudio1.play();\n\n\t\t\t// exit the loop once a Sith has been set\n\t\t\treturn;\n\t\t}\n\t}\n}",
"dftraverse(){ //callback is a function to be used when you either reached the last node, or exhaust all the previous \r\n (function recurse(currentnode,alpha,beta){\r\n //apply aplha beta pruning here.\r\n /**\r\n * alpha for white, beta for black\r\n */\r\n\r\n if(!currentnode) return;\r\n var effscore = currentnode.score;\r\n //console.log(currentnode.playercolor + \",\" + currentnode.effectivescore);\r\n for(var i = 0; i < currentnode.children.length; i++){\r\n recurse(currentnode.children[i],alpha,beta);\r\n //onsole.log(currentnode.children[i].playercolor + \" \" + currentnode.children[i].effectivescore);\r\n if(currentnode.playercolor == \"W\"){ //maximiser\r\n //get higher score;\r\n effscore = Math.max(effscore, currentnode.children[i].effectivescore);\r\n alpha = Math.max(alpha,effscore);\r\n if(alpha >= beta) break;\r\n }\r\n else{ //minimiser\r\n //get lower score;\r\n effscore = Math.min(effscore, currentnode.children[i].effectivescore);\r\n beta = Math.min(beta,effscore);\r\n if(beta <= alpha) break;\r\n }\r\n //add code to get score here.\r\n }\r\n currentnode.effectivescore = effscore;\r\n //console.log(currentnode.playercolor + \",\" + currentnode.effectivescore);\r\n })(this,Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);\r\n }",
"function ProbeTrack(gsvg, data, trackClass, label, additionalOptions) {\n var that = Track(gsvg, data, trackClass, label);\n\n //console.log(\"creating probe track options:\"+additionalOptions);\n var opts = new String(additionalOptions).split(\",\");\n if (opts.length > 0) {\n that.density = opts[0];\n if (typeof that.density === 'string') {\n that.density = parseInt(that.density);\n }\n if (opts.length > 1) {\n that.colorSelect = opts[1];\n } else {\n that.colorSelect = \"annot\";\n }\n if (opts.length > 2) {\n that.tissues = opts[2].split(\":\");\n\n } else {\n that.tissues = [\"Brain\"];\n if (organism == \"Rn\") {\n that.tissues = [\"Brain\", \"BrownAdipose\", \"Heart\", \"Liver\"];\n }\n }\n } else {\n that.density = 3;\n that.colorSelect = \"annot\";\n that.tissues = [\"Brain\"];\n if (organism == \"Rn\") {\n that.tissues = [\"Brain\", \"BrownAdipose\", \"Heart\", \"Liver\"];\n }\n }\n if (that.gsvg.xScale.domain()[1] - that.gsvg.xScale.domain()[0] > 1000000) {\n that.density = 1;\n }\n\n that.tissuesAll = [\"Brain\"];\n if (organism == \"Rn\") {\n that.tissuesAll = [\"Brain\", \"BrownAdipose\", \"Heart\", \"Liver\"];\n }\n that.xPadding = 1;\n /*if(that.gsvg.xScale.domain()[1]-that.gsvg.xScale.domain()[0]>2000000){\n that.xPadding=0.5;\n }*/\n\n that.scanBackYLines = 75;\n that.curColor = that.colorSelect;\n //console.log(\"start Probes\");\n //console.log(\"density:\"+that.density);\n //console.log(\"colorSelect:\"+that.colorSelect);\n //console.log(\"curColor:\"+that.curColor);\n //console.log(that.tissues);\n\n that.ttTrackList = new Array();\n that.ttTrackList.push(\"ensemblcoding\");\n that.ttTrackList.push(\"braincoding\");\n that.ttTrackList.push(\"liverTotal\");\n that.ttTrackList.push(\"heartTotal\");\n that.ttTrackList.push(\"mergedTotal\");\n that.ttTrackList.push(\"ensemblnoncoding\");\n that.ttTrackList.push(\"brainnoncoding\");\n that.ttTrackList.push(\"repeatMask\");\n //that.ttTrackList.push(\"ensemblsmallnc\");\n //that.ttTrackList.push(\"brainsmallnc\");\n\n that.color = function (d, tissue) {\n var color = d3.rgb(\"#000000\");\n if (that.colorSelect == \"annot\") {\n color = that.colorAnnotation(d);\n } else if (that.colorSelect == \"herit\") {\n var value = getFirstChildByName(d, \"herit\").getAttribute(tissue);\n var cval = Math.floor(value * 255);\n color = d3.rgb(cval, 0, 0);\n } else if (that.colorSelect == \"dabg\") {\n var value = getFirstChildByName(d, \"dabg\").getAttribute(tissue);\n var cval = Math.floor(value * 2.55);\n color = d3.rgb(0, cval, 0);\n }\n return color;\n };\n\n that.colorAnnotation = function (d) {\n var color = d3.rgb(\"#000000\");\n if (d.getAttribute(\"type\") == \"core\") {\n color = d3.rgb(255, 0, 0);\n } else if (d.getAttribute(\"type\") == \"extended\") {\n color = d3.rgb(0, 0, 255);\n } else if (d.getAttribute(\"type\") == \"full\") {\n color = d3.rgb(0, 100, 0);\n } else if (d.getAttribute(\"type\") == \"ambiguous\") {\n color = d3.rgb(0, 0, 0);\n }\n return color;\n };\n\n that.pieColor = function (d, i) {\n var color = d3.rgb(\"#000000\");\n var tmpName = new String(d.data.names);\n if (tmpName == \"Core\") {\n color = d3.rgb(255, 0, 0);\n } else if (tmpName == \"Extended\") {\n color = d3.rgb(0, 0, 255);\n } else if (tmpName == \"Full\") {\n color = d3.rgb(0, 100, 0);\n } else if (tmpName == \"Ambiguous\") {\n color = d3.rgb(0, 0, 0);\n }\n return color;\n };\n\n that.createToolTip = function (d) {\n var strand = \".\";\n if (d.getAttribute(\"strand\") == 1) {\n strand = \"+\";\n } else if (d.getAttribute(\"strand\") == -1) {\n strand = \"-\";\n }\n var len = parseInt(d.getAttribute(\"stop\"), 10) - parseInt(d.getAttribute(\"start\"), 10);\n var tooltiptext = \"<BR><div id=\\\"ttSVG\\\" style=\\\"background:#FFFFFF;\\\"></div><BR>Affy Probe Set ID: \" + d.getAttribute(\"ID\") + \"<BR>Strand: \" + strand + \"<BR>Location: \" + d.getAttribute(\"chromosome\") + \":\" + numberWithCommas(d.getAttribute(\"start\")) + \"-\" + numberWithCommas(d.getAttribute(\"stop\")) + \" (\" + len + \"bp)<BR>\";\n tooltiptext = tooltiptext + \"Type: \" + d.getAttribute(\"type\") + \"<BR><BR>\";\n //var tissues=$(\".settingsLevel\"+that.gsvg.levelNumber+\" input[name=\\\"tissuecbx\\\"]:checked\");\n var herit = getFirstChildByName(d, \"herit\");\n var dabg = getFirstChildByName(d, \"dabg\");\n tooltiptext = tooltiptext + \"<table class=\\\"tooltipTable\\\" width=\\\"100%\\\" colSpace=\\\"0\\\"><tr><TH>Tissue</TH><TH>Heritability</TH><TH>DABG</TH></TR>\";\n if (that.tissues.length < that.tissuesAll.length) {\n tooltiptext = tooltiptext + \"<TR><TD colspan=\\\"3\\\">Displayed Tissues:</TD></TR>\";\n }\n var displayed = {};\n for (var t = 0; t < that.tissues.length; t++) {\n var tissue = new String(that.tissues[t]);\n if (tissue.indexOf(\"Affy\") > -1) {\n tissue = tissue.substr(0, tissue.indexOf(\"Affy\"));\n }\n displayed[tissue] = 1;\n var hval = Math.floor(herit.getAttribute(tissue) * 255);\n var hcol = d3.rgb(hval, 0, 0);\n var dval = Math.floor(dabg.getAttribute(tissue) * 2.55);\n var dcol = d3.rgb(0, dval, 0);\n tooltiptext = tooltiptext + \"<TR><TD>\" + tissue + \"</TD><TD style=\\\"background:\" + hcol + \";color:white;\\\">\" + herit.getAttribute(tissue) + \"</TD><TD style=\\\"background:\" + dcol + \";color:white;\\\">\" + dabg.getAttribute(tissue) + \"%</TD></TR>\";\n }\n if (that.tissues.length < that.tissuesAll.length) {\n tooltiptext = tooltiptext + \"<TR><TD colspan=\\\"3\\\">Other Tissues:</TD></TR>\";\n for (var t = 0; t < that.tissuesAll.length; t++) {\n var tissue = new String(that.tissuesAll[t]);\n if (tissue.indexOf(\"Affy\") > -1) {\n tissue = tissue.substr(0, tissue.indexOf(\"Affy\"));\n }\n if (displayed[tissue] != 1) {\n var hval = Math.floor(herit.getAttribute(tissue) * 255);\n var hcol = d3.rgb(hval, 0, 0);\n var dval = Math.floor(dabg.getAttribute(tissue) * 2.55);\n var dcol = d3.rgb(0, dval, 0);\n tooltiptext = tooltiptext + \"<TR><TD>\" + tissue + \"</TD><TD style=\\\"background:\" + hcol + \";color:white;\\\">\" + herit.getAttribute(tissue) + \"</TD><TD style=\\\"background:\" + dcol + \";color:white;\\\">\" + dabg.getAttribute(tissue) + \"%</TD></TR>\";\n }\n }\n }\n tooltiptext = tooltiptext + \"</table>\";\n return tooltiptext;\n };\n\n that.updateSettingsFromUI = function () {\n if ($(\"#\" + that.trackClass + \"Dense\" + that.level + \"Select\").length > 0) {\n that.density = $(\"#\" + that.trackClass + \"Dense\" + that.level + \"Select\").val();\n } else if (!that.density) {\n that.density = 1;\n }\n that.curColor = that.colorSelect;\n if ($(\"#\" + that.trackClass + that.level + \"colorSelect\").length > 0) {\n that.curColor = $(\"#\" + that.trackClass + that.level + \"colorSelect\").val();\n } else if (!that.curColor) {\n that.curColor = \"annot\";\n }\n var count = 0;\n if ($(\"#affyTissues\" + that.level + \" input[name=\\\"tissuecbx\\\"]\").length > 0) {\n that.tissues = [];\n var tis = $(\"#affyTissues\" + that.level + \" input[name=\\\"tissuecbx\\\"]:checked\");\n for (var t = 0; t < tis.length; t++) {\n var tissue = new String(tis[t].id);\n tissue = tissue.substr(0, tissue.indexOf(\"Affy\"));\n that.tissues[count] = tissue;\n count++;\n }\n }\n };\n\n that.savePrevious = function () {\n that.prevSetting = {};\n that.prevSetting.density = that.density;\n that.prevSetting.curColor = that.curColor;\n that.prevSetting.tissues = that.tissues;\n };\n\n that.revertPrevious = function () {\n that.density = that.prevSetting.density;\n that.curColor = that.prevSetting.curColor;\n that.tissues = that.prevSetting.tissues;\n };\n\n //Pack method does perform additional packing above the default method in track.\n //May be slightly slower but avoids the waterfall like non optimal packing that occurs with the sorted features.\n that.calcY = function (start, end, i, idLen) {\n var tmpY = 0;\n var idPix = idLen * 8 + 5;\n if (that.density === 3 || that.density === '3') {\n if ((start >= that.xScale.domain()[0] && start <= that.xScale.domain()[1]) ||\n (end >= that.xScale.domain()[0] && end <= that.xScale.domain()[1]) ||\n (start <= that.xScale.domain()[0] && end >= that.xScale.domain()[1])) {\n var pStart = Math.round(that.xScale(start));\n if (pStart < 0) {\n pStart = 0;\n }\n var pEnd = Math.round(that.xScale(end));\n if (pEnd >= that.gsvg.width) {\n pEnd = that.gsvg.width - 1;\n }\n var pixStart = pStart - that.xPadding;\n if (pixStart < 0) {\n pixStart = 0;\n }\n var pixEnd = pEnd + that.xPadding;\n if (pixEnd >= that.gsvg.width) {\n pixEnd = that.gsvg.width - 1;\n }\n\n //add space for ID\n if ((pixEnd + idPix) < that.gsvg.width) {\n pixEnd = pixEnd + idPix;\n pEnd = pEnd + idPix;\n } else if ((pixStart - idPix) > 0) {\n pixStart = pixStart - idPix;\n pStart = pStart - idPix;\n }\n\n //find yMax that is clear this is highest line that is clear\n var yMax = 0;\n for (var pix = pixStart; pix <= pixEnd; pix++) {\n if (that.yMaxArr[pix] > yMax) {\n yMax = that.yMaxArr[pix];\n }\n }\n yMax++;\n //may need to extend yArr for a new line\n var addLine = yMax;\n if (that.yArr.length <= yMax) {\n that.yArr[addLine] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yArr[addLine][j] = 0;\n }\n }\n //check a couple lines back to see if it can be squeezed in\n var startLine = yMax - that.scanBackYLines;\n if (startLine < 1) {\n startLine = 1;\n }\n var prevLine = -1;\n var stop = 0;\n for (var scanLine = startLine; scanLine < yMax && stop == 0; scanLine++) {\n var available = 0;\n for (var pix = pixStart; pix <= pixEnd && available == 0; pix++) {\n if (that.yArr[scanLine][pix] > available) {\n available = 1;\n }\n }\n if (available == 0) {\n yMax = scanLine;\n stop = 1;\n }\n }\n if (yMax > that.trackYMax) {\n that.trackYMax = yMax;\n }\n for (var pix = pStart; pix <= pEnd; pix++) {\n if (that.yMaxArr[pix] < yMax) {\n that.yMaxArr[pix] = yMax;\n }\n that.yArr[yMax][pix] = 1;\n }\n tmpY = yMax * 15;\n } else {\n tmpY = 15;\n }\n } else if (that.density === 2 || that.density === '2') {\n tmpY = (i + 1) * 15;\n } else {\n tmpY = 15;\n }\n if (that.trackYMax < (tmpY / 15)) {\n that.trackYMax = (tmpY / 15);\n }\n return tmpY;\n };\n\n that.redraw = function () {\n var tissueLen = that.tissues.length;\n if (that.curColor != that.colorSelect || ((that.colorSelect === \"herit\" || that.colorSelect === \"dabg\") && tissueLen != that.tissueLen)) {\n that.tissueLen = tissueLen;\n that.draw(that.data);\n } else {\n that.trackYMax = 0;\n that.yMaxArr = new Array();\n that.yArr = new Array();\n that.yArr[0] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yMaxArr[j] = 0;\n that.yArr[0][j] = 0;\n }\n that.colorSelect = that.curColor;\n that.tissueLen = tissueLen;\n if (that.colorSelect == \"dabg\" || that.colorSelect == \"herit\") {\n if (that.colorSelect == \"dabg\") {\n that.drawScaleLegend(\"0%\", \"100%\", \"of Samples DABG\", \"#000000\", \"#00FF00\", 0);\n } else if (that.colorSelect == \"herit\") {\n that.drawScaleLegend(\"0\", \"1.0\", \"Probeset Heritability\", \"#000000\", \"#FF0000\", 0);\n }\n var totalYMax = 1;\n for (var t = 0; t < that.tissues.length; t++) {\n var tissue = new String(that.tissues[t]);\n //tissue=tissue.substr(0,tissue.indexOf(\"Affy\"));\n that.trackYMax = 0;\n that.yMaxArr = new Array();\n that.yArr = new Array();\n that.yArr[0] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yMaxArr[j] = 0;\n that.yArr[0][j] = 0;\n }\n totalYMax++;\n that.svg.select(\"text.\" + tissue).attr(\"y\", totalYMax * 15);\n that.svg.selectAll(\"g.probe.\" + tissue)\n .attr(\"transform\", function (d, i) {\n var st = that.gsvg.xScale(d.getAttribute(\"start\"));\n var y = that.calcY(parseInt(d.getAttribute(\"start\"), 10), parseInt(d.getAttribute(\"stop\"), 10), i, d.getAttribute(\"ID\").length) + totalYMax * 15 - 10;\n return \"translate(\" + st + \",\" + y + \")\";\n })\n .each(function (d) {\n var tmpD = d;\n var d3This = d3.select(this);\n var wX = 1;\n if (that.gsvg.xScale(tmpD.getAttribute(\"stop\")) - that.gsvg.xScale(tmpD.getAttribute(\"start\")) > 1) {\n wX = that.gsvg.xScale(tmpD.getAttribute(\"stop\")) - that.gsvg.xScale(tmpD.getAttribute(\"start\"));\n }\n //Set probe rect width,etc\n d3This.selectAll(\"rect\")\n .attr(\"width\", wX)\n .attr(\"fill\", that.color(tmpD, tissue));\n //change text to indicate strandedness\n var strChar = \">\";\n if (d.getAttribute(\"strand\") == \"-1\") {\n strChar = \"<\";\n }\n var fullChar = \"\";\n var rectW = wX;\n if (rectW >= 7.5 && rectW <= 15) {\n fullChar = strChar;\n } else if (rectW > 15) {\n rectW = rectW - 7.5;\n while (rectW > 7.5) {\n fullChar = fullChar + strChar;\n rectW = rectW - 7.5;\n }\n }\n d3This.select(\"text#strand\").text(fullChar);\n //update position and add labels if needed\n if (that.density == 2 || that.density == 3) {\n var curLbl = d.getAttribute(\"ID\");\n if (d3This.select(\"text#lblTxt\").size() === 0) {\n d3This.append(\"svg:text\").attr(\"dx\", function () {\n var xpos = that.xScale(d.getAttribute(\"stop\")) + curLbl.length * 8 + 5;\n var finalXpos = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) + 5;\n if (xpos > that.gsvg.width) {\n finalXpos = -1 * curLbl.length * 8;\n }\n return finalXpos;\n })\n .attr(\"dy\", 10)\n .attr(\"id\", \"lblTxt\")\n //.attr(\"fill\",that.colorAnnotation(d))\n .text(curLbl);\n } else {\n\n d3This.select(\"text#lblTxt\").attr(\"dx\", function () {\n var xpos = that.xScale(d.getAttribute(\"stop\")) + curLbl.length * 8 + 5;\n var finalXpos = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) + 5;\n if (xpos > that.gsvg.width) {\n finalXpos = -1 * curLbl.length * 8;\n }\n return finalXpos;\n });\n }\n } else {\n d3This.selectAll(\"text#lblTxt\").remove();\n }\n });\n totalYMax = totalYMax + that.trackYMax;\n }\n that.trackYMax = totalYMax * 15;\n that.svg.attr(\"height\", that.trackYMax);\n } else if (that.colorSelect === \"annot\") {\n var legend = [{color: \"#FF0000\", label: \"Core\"}, {color: \"#0000FF\", label: \"Extended\"}, {color: \"#006400\", label: \"Full\"}, {\n color: \"#000000\",\n label: \"Ambiguous\"\n }];\n that.drawLegend(legend);\n that.trackYMax = 0;\n that.yMaxArr = new Array();\n that.yArr = new Array();\n that.yArr[0] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yMaxArr[j] = 0;\n that.yArr[0][j] = 0;\n }\n\n that.svg.selectAll(\"g.probe\")\n .attr(\"transform\", function (d, i) {\n var st = that.xScale(d.getAttribute(\"start\"));\n return \"translate(\" + st + \",\" + that.calcY(parseInt(d.getAttribute(\"start\"), 10), parseInt(d.getAttribute(\"stop\"), 10), i, d.getAttribute(\"ID\").length) + \")\";\n //return \"translate(\"+st+\",\"+that.calcY(d.getAttribute(\"start\"),d.getAttribute(\"stop\"),that.density,i,2)+\")\";\n });\n that.svg.selectAll(\"g.probe rect\")\n .attr(\"width\", function (d) {\n var wX = 1;\n if (that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) > 1) {\n wX = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\"));\n }\n return wX;\n })\n .attr(\"fill\", function (d) {\n return that.color(d, \"\");\n });\n that.svg.selectAll(\"g.probe\").each(function (d) {\n var d3This = d3.select(this);\n var strChar = \">\";\n if (d.getAttribute(\"strand\") == \"-1\") {\n strChar = \"<\";\n }\n var fullChar = \"\";\n var rectW = d3This.select(\"rect\").attr(\"width\");\n if (rectW >= 7.5 && rectW <= 15) {\n fullChar = strChar;\n } else if (rectW > 15) {\n rectW = rectW - 7.5;\n while (rectW > 7.5) {\n fullChar = fullChar + strChar;\n rectW = rectW - 7.5;\n }\n }\n d3This.select(\"text\").text(fullChar);\n if (that.density == 2 || that.density == 3) {\n var curLbl = d.getAttribute(\"ID\");\n if (d3This.select(\"text#lblTxt\").size() === 0) {\n d3This.append(\"svg:text\").attr(\"dx\", function () {\n var xpos = that.xScale(d.getAttribute(\"stop\")) + curLbl.length * 8 + 5;\n var finalXpos = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) + 5;\n if (xpos > that.gsvg.width) {\n finalXpos = -1 * curLbl.length * 8;\n }\n return finalXpos;\n })\n .attr(\"dy\", 10)\n .attr(\"id\", \"lblTxt\")\n //.attr(\"fill\",that.colorAnnotation(d))\n .text(curLbl);\n } else {\n d3This.select(\"text#lblTxt\").attr(\"dx\", function () {\n var xpos = that.xScale(d.getAttribute(\"stop\")) + curLbl.length * 8 + 5;\n var finalXpos = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) + 5;\n if (xpos > that.gsvg.width) {\n finalXpos = -1 * curLbl.length * 8;\n }\n return finalXpos;\n });\n }\n } else {\n d3This.selectAll(\"text#lblTxt\").remove();\n }\n });\n if (that.density == 1) {\n that.svg.attr(\"height\", 30);\n } else if (that.density == 2) {\n that.svg.attr(\"height\", (that.trackYMax + 1) * 15);\n } else if (that.density == 3) {\n that.svg.attr(\"height\", (that.trackYMax + 1) * 15);\n }\n }\n }\n that.redrawSelectedArea();\n };\n\n that.update = function (d) {\n that.redraw();\n };\n\n that.updateData = function (retry) {\n var tag = \"probe\";\n var path = dataPrefix + \"tmpData/browserCache/\" + genomeVer + \"/regionData/\" + that.gsvg.folderName + \"/probe.xml\";\n d3.xml(path, function (error, d) {\n if (error) {\n if (retry < 3) {//wait before trying again\n var time = 5000;\n if (retry == 1) {\n time = 10000;\n }\n setTimeout(function () {\n that.updateData(retry + 1);\n }, time);\n } else if (retry >= 3) {\n d3.select(\"#Level\" + that.levelNumber + that.trackClass).select(\"#trkLbl\").text(\"An errror occurred loading Track:\" + that.trackClass);\n d3.select(\"#Level\" + that.levelNumber + that.trackClass).attr(\"height\", 15);\n that.gsvg.addTrackErrorRemove(that.svg, \"#Level\" + that.gsvg.levelNumber + that.trackClass);\n }\n } else if (d) {\n var probe = d.documentElement.getElementsByTagName(tag);\n var mergeddata = new Array();\n var checkName = new Array();\n var curInd = 0;\n for (var l = 0; l < that.data.length; l++) {\n if (typeof that.data[l] !== 'undefined') {\n mergeddata[curInd] = that.data[l];\n checkName[that.data[l].getAttribute(\"ID\")] = 1;\n curInd++;\n }\n }\n for (var l = 0; l < probe.length; l++) {\n if (typeof probe[l] !== 'undefined' && typeof checkName[probe[l].getAttribute(\"ID\")] === 'undefined') {\n mergeddata[curInd] = probe[l];\n curInd++;\n }\n }\n\n that.draw(mergeddata);\n that.hideLoading();\n } else {\n //shouldn't need this\n //that.draw(that.data);\n that.hideLoading();\n }\n });\n };\n\n that.draw = function (data) {\n that.data = data;\n\n that.colorSelect = that.curColor;\n that.trackYMax = 0;\n that.yMaxArr = new Array();\n that.yArr = new Array();\n that.yArr[0] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yMaxArr[j] = 0;\n that.yArr[0][j] = 0;\n }\n if (that.colorSelect == \"dabg\" || that.colorSelect == \"herit\") {\n if (that.colorSelect == \"dabg\") {\n that.drawScaleLegend(\"0%\", \"100%\", \"of Samples DABG\", \"#000000\", \"#00FF00\", 0);\n } else if (that.colorSelect == \"herit\") {\n that.drawScaleLegend(\"0\", \"1.0\", \"Probeset Heritability\", \"#000000\", \"#FF0000\", 0);\n }\n that.svg.selectAll(\".probe\").remove();\n that.svg.selectAll(\".tissueLbl\").remove();\n that.tissueLen = that.tissues.length;\n var totalYMax = 1;\n for (var t = 0; t < that.tissues.length; t++) {\n var tissue = new String(that.tissues[t]);\n if (tissue.indexOf(\";\") > 0) {\n tissue = tissue.substr(0, tissue.indexOf(\";\"));\n }\n if (tissue.indexOf(\":\") > 0) {\n tissue = tissue.substr(0, tissue.indexOf(\":\"));\n }\n //tissue=tissue.substr(0,tissue.indexOf(\"Affy\"));\n that.trackYMax = 0;\n that.yMaxArr = new Array();\n that.yArr = new Array();\n that.yArr[0] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yMaxArr[j] = 0;\n that.yArr[0][j] = 0;\n }\n var dispTissue = tissue;\n if (dispTissue == \"BrownAdipose\") {\n dispTissue = \"Brown Adipose\";\n } else if (dispTissue == \"Brain\") {\n dispTissue = \"Whole Brain\";\n }\n var tisLbl = new String(\"Tissue: \" + dispTissue);\n totalYMax++;\n that.svg.append(\"text\").attr(\"class\", \"tissueLbl \" + tissue).attr(\"x\", that.gsvg.width / 2 - (tisLbl.length / 2) * 7.5).attr(\"y\", totalYMax * 15).text(tisLbl);\n\n //console.log(\";.probe.\"+tissue+\";\");\n //update\n if (data.length > 0) {\n var probes = that.svg.selectAll(\".probe.\" + tissue)\n .data(data, function (d) {\n return keyTissue(d, tissue);\n })\n .attr(\"transform\", function (d, i) {\n return \"translate(\" + that.xScale(d.getAttribute(\"start\")) + \",\" + (that.calcY(parseInt(d.getAttribute(\"start\"), 10), parseInt(d.getAttribute(\"stop\"), 10), i, d.getAttribute(\"ID\").length) + totalYMax * 15 - 10) + \")\";\n });\n //add new\n probes.enter().append(\"g\")\n .attr(\"class\", \"probe \" + tissue)\n .attr(\"transform\", function (d, i) {\n return \"translate(\" + that.xScale(d.getAttribute(\"start\")) + \",\" + (that.calcY(parseInt(d.getAttribute(\"start\"), 10), parseInt(d.getAttribute(\"stop\"), 10), i, d.getAttribute(\"ID\").length) + totalYMax * 15 - 10) + \")\";\n })\n .append(\"rect\")\n //.attr(\"class\",tissue)\n .attr(\"height\", 10)\n .attr(\"rx\", 1)\n .attr(\"ry\", 1)\n .attr(\"width\", function (d) {\n var wX = 1;\n if (that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) > 1) {\n wX = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\"));\n }\n return wX;\n })\n .attr(\"id\", function (d) {\n return d.getAttribute(\"ID\") + tissue;\n })\n .style(\"fill\", function (d) {\n return that.color(d, tissue);\n })\n .style(\"cursor\", \"pointer\")\n .on(\"dblclick\", that.zoomToFeature)\n .on(\"mouseover\", function (d) {\n if (that.gsvg.isToolTip == 0) {\n overSelectable = 1;\n $(\"#mouseHelp\").html(\"<B>Double Click</B> to zoom in on this feature.\");\n var thisD3 = d3.select(this);\n that.curTTColor = thisD3.style(\"fill\");\n if (thisD3.style(\"opacity\") > 0) {\n thisD3.style(\"fill\", \"green\");\n tt.transition()\n .duration(200)\n .style(\"opacity\", 1);\n tt.html(that.createToolTip(d))\n .style(\"left\", function () {\n return that.positionTTLeft(d3.event.pageX);\n })\n .style(\"top\", function () {\n return that.positionTTTop(d3.event.pageY);\n });\n //Setup Tooltip SVG\n that.setupToolTipSVG(d, 0.2);\n }\n }\n })\n .on(\"mouseout\", function (d) {\n overSelectable = 0;\n $(\"#mouseHelp\").html(\"Navigation Hints: Hold mouse over areas of the image for available actions.\");\n var thisD3 = d3.select(this);\n if (thisD3.style(\"opacity\") > 0) {\n thisD3.style(\"fill\", that.curTTColor);\n tt.transition()\n .delay(500)\n .duration(200)\n .style(\"opacity\", 0);\n }\n });\n that.svg.selectAll(\"g.probe.\" + tissue).each(function (d) {\n var d3This = d3.select(this);\n var strChar = \">\";\n if (d.getAttribute(\"strand\") == \"-1\") {\n strChar = \"<\";\n }\n var fullChar = strChar;\n var rectW = d3This.select(\"rect\").attr(\"width\");\n if (rectW < 7.5) {\n fullChar = \"\";\n } else {\n rectW = rectW - 7.5;\n while (rectW > 8.5) {\n fullChar = fullChar + strChar;\n rectW = rectW - 7.5;\n }\n }\n d3This.append(\"svg:text\").attr(\"dx\", \"1\").attr(\"id\", \"strand\").attr(\"dy\", \"10\").style(\"pointer-events\", \"none\").style(\"fill\", \"white\").text(fullChar);\n if (that.density == 2 || that.density == 3) {\n var curLbl = d.getAttribute(\"ID\");\n d3This.append(\"svg:text\").attr(\"dx\", function () {\n var xpos = that.xScale(d.getAttribute(\"stop\")) + curLbl.length * 8 + 5;\n var finalXpos = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) + 5;\n if (xpos > that.gsvg.width) {\n finalXpos = -1 * curLbl.length * 8;\n }\n return finalXpos;\n })\n .attr(\"dy\", 10)\n .attr(\"id\", \"lblTxt\")\n //.attr(\"fill\",that.colorAnnotation(d))\n .text(curLbl);\n\n } else {\n d3This.selectAll(\"text#lblTxt\").remove();\n }\n });\n totalYMax = totalYMax + that.trackYMax + 1;\n }\n }\n //probes.exit().remove();\n that.trackYMax = totalYMax;\n that.svg.attr(\"height\", totalYMax * 15 + 45);\n } else if (that.colorSelect == \"annot\") {\n var legend = [{color: \"#FF0000\", label: \"Core\"}, {color: \"#0000FF\", label: \"Extended\"}, {color: \"#006400\", label: \"Full\"}, {\n color: \"#000000\",\n label: \"Ambiguous\"\n }];\n that.drawLegend(legend);\n that.trackYMax = 0;\n that.yMaxArr = new Array();\n that.yArr = new Array();\n that.yArr[0] = new Array();\n for (var j = 0; j < that.gsvg.width; j++) {\n that.yMaxArr[j] = 0;\n that.yArr[0][j] = 0;\n }\n that.svg.selectAll(\".probe\").remove();\n that.svg.selectAll(\".tissueLbl\").remove();\n //update\n var probes = that.svg.selectAll(\".probe.annot\")\n .data(data, key)\n //.attr(\"transform\",function(d,i){ return \"translate(\"+that.xScale(d.getAttribute(\"start\"))+\",\"+that.calcY(d.getAttribute(\"start\"),d.getAttribute(\"stop\"),that.density,i,2)+\")\";})\n .attr(\"transform\", function (d, i) {\n return \"translate(\" + that.xScale(d.getAttribute(\"start\")) + \",\" + that.calcY(parseInt(d.getAttribute(\"start\"), 10), parseInt(d.getAttribute(\"stop\"), 10), i, d.getAttribute(\"ID\").length) + \")\";\n });\n\n //add new\n probes.enter().append(\"g\")\n .attr(\"class\", \"probe annot\")\n //.attr(\"transform\",function(d,i){ return \"translate(\"+that.xScale(d.getAttribute(\"start\"))+\",\"+that.calcY(d.getAttribute(\"start\"),d.getAttribute(\"stop\"),that.density,i,2)+\")\";})\n .attr(\"transform\", function (d, i) {\n return \"translate(\" + that.xScale(d.getAttribute(\"start\")) + \",\" + that.calcY(parseInt(d.getAttribute(\"start\"), 10), parseInt(d.getAttribute(\"stop\"), 10), i, d.getAttribute(\"ID\").length) + \")\";\n })\n .append(\"rect\")\n .attr(\"height\", 10)\n .attr(\"rx\", 1)\n .attr(\"ry\", 1)\n .attr(\"width\", function (d) {\n var wX = 1;\n if (that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) > 1) {\n wX = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\"));\n }\n return wX;\n })\n .attr(\"id\", function (d) {\n return d.getAttribute(\"ID\");\n })\n .style(\"fill\", function (d) {\n return that.color(d, \"\");\n })\n .style(\"cursor\", \"pointer\")\n .on(\"dblclick\", that.zoomToFeature)\n .on(\"mouseover\", function (d) {\n if (that.gsvg.isToolTip == 0) {\n overSelectable = 1;\n $(\"#mouseHelp\").html(\"<B>Double Click</B> to zoom in on this feature.\");\n var thisD3 = d3.select(this);\n if (thisD3.style(\"opacity\") > 0) {\n thisD3.style(\"fill\", \"green\");\n tt.transition()\n .duration(200)\n .style(\"opacity\", 1);\n tt.html(that.createToolTip(d))\n .style(\"left\", function () {\n return that.positionTTLeft(d3.event.pageX);\n })\n .style(\"top\", function () {\n return that.positionTTTop(d3.event.pageY);\n });\n //Setup Tooltip SVG\n that.setupToolTipSVG(d, 0.2);\n }\n }\n })\n .on(\"mouseout\", function (d) {\n overSelectable = 0;\n $(\"#mouseHelp\").html(\"Navigation Hints: Hold mouse over areas of the image for available actions.\");\n var thisD3 = d3.select(this);\n if (thisD3.style(\"opacity\") > 0) {\n thisD3.style(\"fill\", that.color);\n tt.transition()\n .delay(500)\n .duration(200)\n .style(\"opacity\", 0);\n }\n });\n that.svg.selectAll(\"g.probe\").each(function (d) {\n var d3This = d3.select(this);\n var strChar = \">\";\n if (d.getAttribute(\"strand\") == \"-1\") {\n strChar = \"<\";\n }\n var fullChar = strChar;\n var rectW = d3This.select(\"rect\").attr(\"width\");\n if (rectW < 7.5) {\n fullChar = \"\";\n } else {\n rectW = rectW - 7.5;\n while (rectW > 15) {\n fullChar = fullChar + strChar;\n rectW = rectW - 7.5;\n }\n }\n d3This.append(\"svg:text\").attr(\"dx\", \"1\").attr(\"dy\", \"10\").style(\"pointer-events\", \"none\").style(\"fill\", \"white\").text(fullChar);\n\n if (that.density == 2 || that.density == 3) {\n var curLbl = d.getAttribute(\"ID\");\n d3This.append(\"svg:text\").attr(\"dx\", function () {\n /*var xpos=that.xScale(d.getAttribute(\"start\"));\n\t\t\t\t\t\t\t\tif(xpos<($(window).width()/2)){\n\t\t\t\t\t\t\t\t\txpos=that.xScale(d.getAttribute(\"stop\"))-that.xScale(d.getAttribute(\"start\"))+5;\n\t\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\t\txpos=-1*curLbl.length*9;;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn xpos;*/\n var xpos = that.xScale(d.getAttribute(\"stop\")) + curLbl.length * 8 + 5;\n var finalXpos = that.xScale(d.getAttribute(\"stop\")) - that.xScale(d.getAttribute(\"start\")) + 5;\n if (xpos > that.gsvg.width) {\n finalXpos = -1 * curLbl.length * 8;\n }\n return finalXpos;\n })\n .attr(\"dy\", 10)\n .attr(\"id\", \"lblTxt\")\n //.attr(\"fill\",that.colorAnnotation(d))\n .text(curLbl);\n\n } else {\n d3This.select(\"text#lblTxt\").remove();\n }\n });\n\n\n //probes.exit().remove();\n if (that.density == 1) {\n that.svg.attr(\"height\", 30);\n } else if (that.density == 2) {\n //that.svg.attr(\"height\", (d3.select(\"#Level\"+that.gsvg.levelNumber+that.trackClass).selectAll(\"g.probe\").length+1)*15);\n that.svg.attr(\"height\", (that.trackYMax + 1) * 15);\n } else if (that.density == 3) {\n that.svg.attr(\"height\", (that.trackYMax + 1) * 15);\n }\n }\n that.redrawSelectedArea();\n };\n\n that.getDisplayedData = function () {\n var dataElem = d3.select(\"#Level\" + that.gsvg.levelNumber + that.trackClass).selectAll(\"g.probe\");\n that.counts = [{value: 0, names: \"Core\"}, {value: 0, names: \"Extended\"}, {value: 0, names: \"Full\"}, {value: 0, names: \"Ambiguous\"}];\n var tmpDat = dataElem[0];\n var dispData = new Array();\n var dispDataCount = 0;\n dataElem.each(function (d) {\n var start = that.xScale(d.getAttribute(\"start\"));\n var stop = that.xScale(d.getAttribute(\"stop\"));\n if ((0 <= start && start <= that.gsvg.width) || (0 <= stop && stop <= that.gsvg.width)) {\n if (d.getAttribute(\"type\") == \"core\") {\n that.counts[0].value++;\n } else if (d.getAttribute(\"type\") == \"extended\") {\n that.counts[1].value++;\n } else if (d.getAttribute(\"type\") == \"full\") {\n that.counts[2].value++;\n } else if (d.getAttribute(\"type\") == \"ambiguous\") {\n that.counts[3].value++;\n }\n dispData[dispDataCount] = d;\n dispDataCount++;\n }\n });\n if (dataElem.size() === 0) {\n that.counts = [];\n }\n return dispData;\n };\n\n that.generateSettingsDiv = function (topLevelSelector) {\n var d = trackInfo[that.trackClass];\n that.savePrevious();\n //console.log(trackInfo);\n //console.log(d);\n d3.select(topLevelSelector).select(\"table\").select(\"tbody\").html(\"\");\n if (typeof d !== 'undefined' && typeof d.Controls !== 'undefined' && d.Controls != \"null\" && d.Controls.length > 0) {\n var controls = new String(d.Controls).split(\",\");\n var table = d3.select(topLevelSelector).select(\"table\").select(\"tbody\");\n table.append(\"tr\").append(\"td\").style(\"font-weight\", \"bold\").html(\"Track Settings: \" + d.Name);\n for (var c = 0; c < controls.length; c++) {\n if (typeof controls[c] !== 'undefined' && controls[c] != \"\") {\n var params = controls[c].split(\";\");\n\n var div = table.append(\"tr\").append(\"td\");\n var lbl = params[0].substr(5);\n\n var def = \"\";\n if (params.length > 3 && params[3].indexOf(\"Default=\") == 0) {\n def = params[3].substr(8);\n }\n if (params[1].toLowerCase().indexOf(\"select\") == 0) {\n div.append(\"text\").text(lbl + \": \");\n var selClass = params[1].split(\":\");\n var opts = params[2].split(\"}\");\n var id = that.trackClass + \"Dense\" + that.level + \"Select\";\n if (selClass[1] == \"colorSelect\") {\n id = that.trackClass + that.level + \"colorSelect\";\n }\n var sel = div.append(\"select\").attr(\"id\", id)\n .attr(\"name\", selClass[1]);\n for (var o = 0; o < opts.length; o++) {\n var option = opts[o].substr(1).split(\":\");\n if (option.length == 2) {\n var tmpOpt = sel.append(\"option\").attr(\"value\", option[1]).text(option[0]);\n if (selClass[1] == \"colorSelect\" && option[1] == that.curColor) {\n tmpOpt.attr(\"selected\", \"selected\");\n } else if (option[1] == that.density) {\n tmpOpt.attr(\"selected\", \"selected\");\n }\n }\n }\n d3.select(\"select#\" + id).on(\"change\", function () {\n if ($(this).val() == \"dabg\" || $(this).val() == \"herit\") {\n $(\"div#affyTissues\" + that.level).show();\n } else {\n $(\"div#affyTissues\" + that.level).hide();\n }\n that.updateSettingsFromUI();\n that.redraw();\n });\n } else if (params[1].toLowerCase().indexOf(\"cbx\") == 0) {\n div = div.append(\"div\").attr(\"id\", \"affyTissues\" + that.level).style(\"display\", \"none\");\n div.append(\"text\").text(lbl + \": \");\n var selClass = params[1].split(\":\");\n var opts = params[2].split(\"}\");\n\n for (var o = 0; o < opts.length; o++) {\n var option = opts[o].substr(1).split(\":\");\n if (option.length == 2) {\n var span = div.append(\"div\").style(\"display\", \"inline-block\");\n var sel = span.append(\"input\").attr(\"type\", \"checkbox\").attr(\"id\", option[1] + \"CBX\" + that.level)\n .attr(\"name\", selClass[1])\n .style(\"margin-left\", \"5px\");\n span.append(\"text\").text(option[0]);\n //console.log(def+\"::\"+option[1]);\n\n d3.select(\"input#\" + option[1] + \"CBX\" + that.level).on(\"change\", function () {\n that.updateSettingsFromUI();\n that.redraw();\n });\n }\n }\n }\n }\n }\n if (that.curColor == \"dabg\" || that.curColor == \"herit\") {\n $(\"div#affyTissues\" + that.level).show();\n } else {\n $(\"div#affyTissues\" + that.level).hide();\n }\n for (var p = 0; p < that.tissues.length; p++) {\n //console.log(\"#\"+that.tissues[p]+\"AffyCBX\"+that.level);\n $(\"#\" + that.tissues[p] + \"AffyCBX\" + that.level).prop('checked', true);\n }\n var buttonDiv = table.append(\"tr\").append(\"td\");\n buttonDiv.append(\"input\").attr(\"type\", \"button\").attr(\"value\", \"Remove Track\").style(\"float\", \"left\").style(\"margin-left\", \"5px\").on(\"click\", function () {\n $('#trackSettingDialog').fadeOut(\"fast\");\n that.gsvg.removeTrack(that.trackClass);\n var viewID = svgList[that.gsvg.levelNumber].currentView.ViewID;\n var track = viewMenu[that.gsvg.levelNumber].findTrackByClass(that.trackClass, viewID);\n var indx = viewMenu[that.gsvg.levelNumber].findTrackIndexWithViewID(track.TrackID, viewID);\n viewMenu[that.gsvg.levelNumber].removeTrackWithIDIdx(indx, viewID);\n });\n buttonDiv.append(\"input\").attr(\"type\", \"button\").attr(\"value\", \"Apply\").style(\"float\", \"right\").style(\"margin-left\", \"5px\").on(\"click\", function () {\n $('#trackSettingDialog').fadeOut(\"fast\");\n if (that.density != that.prevSetting.density || that.curColor != that.prevSetting.curColor || that.tissues != that.prevSetting.tissues) {\n that.gsvg.setCurrentViewModified();\n }\n });\n buttonDiv.append(\"input\").attr(\"type\", \"button\").attr(\"value\", \"Cancel\").style(\"float\", \"right\").style(\"margin-left\", \"5px\").on(\"click\", function () {\n that.revertPrevious();\n that.draw(that.data);\n $('#trackSettingDialog').fadeOut(\"fast\");\n });\n } else {\n var table = d3.select(topLevelSelector).select(\"table\").select(\"tbody\");\n table.append(\"tr\").append(\"td\").style(\"font-weight\", \"bold\").html(\"Track Settings: \" + d.Name);\n table.append(\"tr\").append(\"td\").html(\"Sorry no settings for this track.\");\n var buttonDiv = table.append(\"tr\").append(\"td\");\n buttonDiv.append(\"input\").attr(\"type\", \"button\").attr(\"value\", \"Remove Track\").style(\"float\", \"left\").style(\"margin-left\", \"5px\").on(\"click\", function () {\n $('#trackSettingDialog').fadeOut(\"fast\");\n });\n buttonDiv.append(\"input\").attr(\"type\", \"button\").attr(\"value\", \"Cancel\").style(\"float\", \"right\").style(\"margin-left\", \"5px\").on(\"click\", function () {\n $('#trackSettingDialog').fadeOut(\"fast\");\n });\n }\n };\n\n that.generateTrackSettingString = function () {\n var tissueStr = \"\";\n for (var k = 0; k < that.tissues.length; k++) {\n if (k > 0) {\n tissueStr = tissueStr + \":\";\n }\n tissueStr = tissueStr + that.tissues[k];\n /*if(k<(that.tissues.length-1)){\n\t\t\t\ttissueStr=tissueStr+\":\";\n\t\t\t}*/\n }\n return that.trackClass + \",\" + that.density + \",\" + that.curColor + \",\" + tissueStr + \";\";\n };\n\n that.draw(data);\n return that;\n}",
"function switchCostPerVisit(package) {\n var cost;\n switch (package) {\n case \"Basic\":\n cost = 120;\n break;\n case \"Basic Extra\":\n cost = 130;\n break;\n case \"Extensive\":\n cost = 160;\n break;\n default:\n cost = 0;\n }\n return cost;\n}",
"function doDamage() {\n let newGroup = {}\n let deadGuys = 0;\n\n if (props.secondGroup) \n newGroup = JSON.parse(JSON.stringify(props.secondGroup))\n else\n newGroup = JSON.parse(JSON.stringify(props.group))\n\n props.changePrevState(JSON.parse(JSON.stringify(newGroup)))\n\n \n //Make an array of keys with the values that are above 0\n let nonzeros = []\n if (props.selection) {\n newGroup.creatures.forEach((element, index) => {\n if (element > 0 && props.selectedCreatures.includes(index) ) \n nonzeros.push(index) \n })\n }\n else {\n newGroup.creatures.forEach((element, index) => {\n if( element > 0 ) \n nonzeros.push(index)\n })\n }\n\n switch(props.targetType) {\n case \"lowest\":\n nonzeros.sort(function(a, b){return newGroup.creatures[a]-newGroup.creatures[b]});\n break;\n case \"highest\":\n nonzeros.sort(function(a,b){return newGroup.creatures[b]-newGroup.creatures[a]})\n break;\n default: \n nonzeros = SmallFunctions.shuffle(nonzeros)\n break;\n }\n\n \n let targets = props.numTargets;\n let rollResults = []\n let finalResults = []\n let damage = null;\n \n\n if (!props.aoe && !props.secondGroup) { //If doing single target damage\n let remainder = props.damage;\n if (props.bleedthrough) targets += 1;\n\n while (nonzeros.length > 0 && targets > 0 && remainder > 0) {\n\n if(newGroup.creatures[nonzeros[0]] > remainder){\n newGroup.creatures[nonzeros[0]] -= remainder\n remainder = 0;\n }\n else if (newGroup.creatures[nonzeros[0]] === remainder) {\n remainder = 0;\n deadGuys += 1;\n newGroup.creatures[nonzeros[0]] = 0;\n }\n else{\n remainder -= newGroup.creatures[nonzeros[0]]\n newGroup.creatures[nonzeros[0]] = 0\n deadGuys += 1;\n }\n nonzeros.splice(0, 1)\n targets -= 1; \n console.log(\"loop\") \n } \n \n }\n else {\n if (props.saveRule === \"None\") \n rollResults = []\n else if (props.aoe)\n rollResults = SmallFunctions.rollDice(props.rolltype, props.numTargets )\n else //If it is an attack group action\n rollResults = SmallFunctions.rollDice(props.rolltype, props.numAttackers )\n\n \n\n if(props.aoe) { //if aoe effect\n while (targets > 0 && nonzeros.length > 0) {\n if (props.saveRule === \"None\" || rollResults[0] + newGroup.Saves[props.saveType]< props.saveDC ) \n damage = props.damage\n \n else if (props.saveRule === \"Half\")\n damage = Math.floor(props.damage / 2)\n \n else \n damage = 0;\n \n newGroup.creatures[nonzeros[0]] = Math.max( 0 , newGroup.creatures[nonzeros[0]] - (damage))\n if (newGroup.creatures[nonzeros[0]] === 0) deadGuys += 1;\n finalResults.push([rollResults[0], damage, false])\n rollResults.splice(0,1)\n nonzeros.splice(0,1)\n targets -= 1;\n }\n \n\n }\n else { //if group attack\n nonzeros = nonzeros.splice(0, targets)\n while (rollResults.length > 0 && nonzeros.length > 0) {\n let newDamage = props.selectedAttack.damBonus\n let victim = Math.floor(Math.random()*nonzeros.length)\n finalResults.push([rollResults[0]])\n for (let i = 0; i < props.selectedAttack.numDie; i++) {\n newDamage += Math.floor(Math.random() * props.selectedAttack.damDie) + 1\n }\n if(props.selectedAttack.saving) {\n if(rollResults[0] + newGroup.Saves[props.selectedAttack.savingType] < props.selectedAttack.DC ) {\n newGroup.creatures[nonzeros[victim]] = Math.max(0, newGroup.creatures[nonzeros[victim]] - newDamage)\n finalResults[finalResults.length-1].push(newDamage)\n finalResults[finalResults.length-1].push(false)\n }\n else {\n finalResults[finalResults.length-1].push(0)\n finalResults[finalResults.length-1].push(false) \n }\n }\n else {\n if( rollResults[0] + props.selectedAttack.bonus >= newGroup.armorClass ) {\n newGroup.creatures[nonzeros[victim]] = Math.max(0, newGroup.creatures[nonzeros[victim]] - newDamage)\n finalResults[finalResults.length-1].push(newDamage)\n finalResults[finalResults.length-1].push(true)\n }\n else {\n finalResults[finalResults.length-1].push(0)\n finalResults[finalResults.length-1].push(true)\n }\n }\n\n if(newGroup.creatures[nonzeros[victim]] === 0) {\n nonzeros.splice(victim, 1)\n deadGuys += 1\n }\n rollResults.splice(0,1) \n\n } \n }\n }\n\n \n if(props.saveRule === \"None\")\n props.changeRollResults([])\n else\n props.changeRollResults(finalResults)\n props.updateGroup(newGroup) \n props.changeDeadGuys(deadGuys) \n }",
"function findSuperHero() {\n let n = Object.keys(data).length;\n calculatePermutation(data, 0, [], n);\n if (!selectedHero.length) {\n setError('No Super Hero Code Matched !!');\n setTimeout(() => {\n setError(null);\n },5000);\n }\n }",
"function scan(config){\n cli.info(\"NETWORK FULL SCAN STARTED\\n\");\n _.each(_.keys(SPTree) , function(fromLan){\n _.each(_.keys(SPTree[fromLan]) , function(toLan){\n if (fromLan != toLan){\n doPathMeasures(fromLan , toLan);\n }\n })\n });\n}",
"partitionAnalysis() {\n this.setWaypointFields();\n this.partSizes();\n this.calculatePartBdryStats();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Redact some text / required params properties / inputText : string : the text to have redaction performed on it. / phrases : array of strings : the text strings to match and replace / optional params properties / replacementChar : character : the replacement character : defaults to 'X' / caseSensitive : boolean : defaults to true Return: returns a promise that resolves the string, just in case it takes a long time it wont block | redact(parameters) {
// Converted to a promise now
let promise = this.$q((resolve, reject) => {
// Setup and defaults
let replacementChar = parameters.replacementChar || 'X';
// Here is a little example of type checking variables and defaulting if it isn't as expected.
let caseSensitive =
typeof parameters.caseSensitive === typeof true
? parameters.caseSensitive
: true;
if (parameters.phrases === undefined || parameters.phrases.length === 0) {
return parameters.inputText;
}
let phrases = parameters.phrases;
let searchText = parameters.inputText;
if (!caseSensitive) {
phrases = parameters.phrases.map(p => p.toLowerCase());
searchText = parameters.inputText.toLowerCase();
}
// loop through the phrases array
let indicies = [];
phrases.map(p => {
// should just use for loop here now
let pos = -1;
do {
pos = searchText.indexOf(p, pos + 1); // use the start index to reduce search time on subsequent searches
if (pos === -1) break; // No more matches, abandon ship!
// Track the starting index and length of the redacted area
indicies.push({ index: pos, length: p.length });
} while (pos != -1);
});
// Ok now go replace everything in the original text.
// Overlapping phrases should be handled properly now.
// we really need a splice method for strings
// quick google search and guess what? There is an underscore string library ... neat! Now I don't have to write one.
let redactedText = parameters.inputText;
for (let i = 0, len = indicies.length; i < len; i++) {
redactedText = _string.splice(
redactedText,
indicies[i].index,
indicies[i].length,
this.buildReplacement(replacementChar, indicies[i].length)
);
}
// Go home strings, you're drunk
resolve(redactedText);
});
return promise;
} | [
"async function replaceAsync(str, regex, replacerAsync) {\n const promises = [];\n str.replace(regex, (match, ...args) => {\n const promise = replacerAsync(match, ...args);\n promises.push(promise);\n return \"\";\n });\n const data = await Promise.all(promises);\n return str.replace(regex, () => data.shift());\n}",
"function lemmatize($text) {\n\tvar text = $text;\n\tvar doc = nlp($text);\n\tvar verbs = doc.verbs().json();\n\tvar nouns = doc.nouns().json();\n\tvar nouns_ori = doc.nouns().toSingular().json();\n\n\t// verb\n\tverbs.forEach(obj => {\n\t\tlet now = obj.text;\n\t\tlet to = obj.conjugations.Infinitive;\n\n\t\t// do not change\n\t\tif (now === to) return;\n\t\tif (now === '') return;\t\t// e.g. there's will cause one empty entry\n\t\tif (now.indexOf(\"'\") >= 0) return;\t// e.g. didn't => not didn't\n\n\t\t// replace\n\t\tlet re = new RegExp(now, 'g');\n\t\ttext = text.replace(re, to);\n\t});\n\n\t// noun\n\tnouns.forEach((obj, i) => {\n\t\tlet now = obj.text;\n\t\tlet to = nouns_ori[i].text;\n\n\t\t// do not change\n\t\tif (now === to) return;\n\n\t\t// replace\n\t\tlet re = new RegExp(now, 'g');\n\t\ttext = text.replace(re, to);\n\t});\n\n\treturn text;\n}",
"function replaceAll(str, term, replacement) {\n return str.replace(new RegExp(escapeRegExp(term), 'g'), replacement);\n }",
"function strReplace(text,toBeReplaced,toReplace,substituteFirst)\n{\n\tvar newToBeReplaced=\"\";\n\t\n\tfor(var i=0;i<toBeReplaced.length;i++)\n\t{\n\t\t// Elabora caratteri riservati dell'oggetto RegExp\n\t\tswitch (toBeReplaced.substr(i,1))\n\t\t{\n\t\t\tcase \"^\":\n\t\t\tcase \"$\":\n\t\t\tcase \"*\":\n\t\t\tcase \"+\":\n\t\t\tcase \"?\":\n\t\t\tcase \"[\":\n\t\t\tcase \"]\":\n\t\t\tcase \"(\":\n\t\t\tcase \")\":\n\t\t\tcase \"|\": \n\t\t\t\tnewToBeReplaced+=\"\\\\\"+toBeReplaced.substr(i,1);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\texcape=/\\\\/g;\n\t\t\t\tnewToBeReplaced=toBeReplaced.replace(excape,\"\\\\\\\\\");\t\n\t\t}\t\n\t}\n\t\n\tif (newToBeReplaced==\"\")\n\t\tnewToBeReplaced=toBeReplaced;\n\t\n\tif (substituteFirst)\n\t\trg=new RegExp(newToBeReplaced)\n\telse\n\t\trg=new RegExp(newToBeReplaced,\"g\");\n\t\n\treturn text.replace(rg,toReplace);\n}",
"regexAll (text, array) {\n for (const i in array) {\n let regex = array[i][0]\n const flags = (typeof regex === 'string') ? 'g' : undefined\n regex = new RegExp (regex, flags)\n text = text.replace (regex, array[i][1])\n }\n return text\n }",
"function highlight_word(searchpara) {\n\tlet text=document.getElementById(\"search_text\").value;\n\tif (text) {\n\t\tlet pattern = new RegExp(\"(\"+text+\")\", \"gi\");\n\t\tlet new_text = searchpara.replace(pattern, \"<span class='highlight'>\"+text+\"</span>\");\n\t\tdocument.getElementById(\"search_para\").innerHTML=new_text;\n\t}\n}",
"function replaceApici(text,charToSubst)\n{\n\t/*if (!charToSubst) return text;\n\t// Trasforma \" in ''\n\tif (charToSubst==\"\\\"\")\n\t\treturn strReplace(text,\"\\\"\",\"''\");\n\t// Trasforma ' in \"\n\telse\n\t\treturn strReplace(text,\"'\",\"\\\"\");*/\n\t\t\n\tif (!charToSubst) return text;\n\t// Trasforma \" in ''\n\tif (charToSubst==\"\\\"\")\n\t\treturn strReplace(text,\"\\\"\",\"''\");\n\t// Trasforma ' in \"\n\telse\n\t\treturn strReplace(text,\"'\",\"''\");\n\t\n\n\t\t\n\t\t\n}",
"function switchText_cb(new_string)\r\n{\r\n\twith(currObj);\r\n\tnew_string = new_string.replace(/~~~/gi, \"\\n\");\r\n\r\n\t// Remove the prefixed asterisk that was added in switchText().\r\n\tnew_string = new_string.substr(1);\r\n\tcurrObj.objToCheck.style.display = \"none\";\r\n\tcurrObj.objToCheck.value = new_string;\r\n\tcurrObj.objToCheck.disabled = false;\r\n\tif(currObj.spellingResultsDiv)\r\n\t{\r\n\t\tcurrObj.spellingResultsDiv.parentNode.removeChild(currObj.spellingResultsDiv);\r\n\t\tcurrObj.spellingResultsDiv = null;\r\n\t}\r\n\tcurrObj.objToCheck.style.display = \"block\";\r\n\tcurrObj.resetAction();\r\n}",
"function SUBSTITUTE(text, old_text, new_text, occurrence) {\n if (!text || !old_text || !new_text) {\n return text;\n } else if (occurrence === undefined) {\n return text.replace(new RegExp(old_text, 'g'), new_text);\n } else {\n var index = 0;\n var i = 0;\n while (text.indexOf(old_text, index) > 0) {\n index = text.indexOf(old_text, index + 1);\n i++;\n if (i === occurrence) {\n return text.substring(0, index) + new_text + text.substring(index + old_text.length);\n }\n }\n }\n}",
"function Simplification() {\r\n var regEx = document.getElementsByClassName(\"simpli\")[0].value;\r\n var text = document.getElementsByClassName(\"simpli\")[1].value;\r\n\r\n var re = new RegExp(regEx);\r\n\r\n var reponse = re.exec(text);\r\n document.getElementById(\"testSimpli\").value = reponse;\r\n\r\n}",
"function SearchAndReplace(arr,oldWord,newWord) {\n var t = '';\n var text = arr.split(' ');\n for (let i = 0; i < text.length; i++) {\n if (text[i] == oldWord) {\n t = text[i].charAt(0);\n if (t == text[i].charAt(0).toUpperCase()) {\n t = newWord.charAt(0).toUpperCase()\n t += newWord.slice(1)\n }else{\n t = newWord.charAt(0).toLowerCase()\n t += newWord.slice(1)\n }\n text[i] = t\n }\n }\n return text.join(' ')\n}",
"function translate(text, dictionary){\n\t// TODO: implementați funcția\n\t// TODO: implement the function\n\t\n\t\n\t\tif (typeof text !== 'string'){\n\t\t\tthrow new Error(\"InvalidType\")\n\t\t}\n\t\tif (typeof dictionary !== 'object' || !dictionary){\n\t\t\tthrow new Error(\"InvalidType\")\n\t\t}\n\t\t// for (let prop in dictionary){\n\t\t// if (typeof dictionary[prop] !== 'string'){\n\t\t// \tthrow new Error('InvalidType')\n\t\t// }\n\t\t// }\n\t\tfor(let i =0;i<dictionary.length;i++){\n\t\t\tif(typeof dictionary[i] !== 'string'){\n\t\t\t\tthrow new Error(\"InvalidType\")\n\t\t\t}\n\t\t}\n\t\t\n\t\n\tlet value = text.split(' ')\n\n\tfor (let index in dictionary){\n\t\tlet position = value.indexOf(index)\n\t\tif (position !== -1){\n\t\t\tvalue[position] = dictionary[index]\n\t\t}\t\n\t}\n\treturn value.join(' ')\n}",
"function textInputRule(config) {\n return new InputRule({\n find: config.find,\n handler: ({ state, range, match }) => {\n let insert = config.replace;\n let start = range.from;\n const end = range.to;\n if (match[1]) {\n const offset = match[0].lastIndexOf(match[1]);\n insert += match[0].slice(offset + match[1].length);\n start += offset;\n const cutOff = start - end;\n if (cutOff > 0) {\n insert = match[0].slice(offset - cutOff, offset) + insert;\n start = end;\n }\n }\n state.tr.insertText(insert, start, end);\n },\n });\n}",
"phrase(phrase, ...insert) {\n for (let map of this.facet(EditorState.phrases))\n if (Object.prototype.hasOwnProperty.call(map, phrase)) {\n phrase = map[phrase]\n break\n }\n if (insert.length)\n phrase = phrase.replace(/\\$(\\$|\\d*)/g, (m, i) => {\n if (i == '$') return '$'\n let n = +(i || 1)\n return !n || n > insert.length ? m : insert[n - 1]\n })\n return phrase\n }",
"async function tokenizing (text) {\n let split = text.split(/[\\[\\]<>.,\\/#!$%\\^&\\*;:{}=_()?@\\s\\'\\-\\\"]/g);\n let newSplit = sw.removeStopwords(split);\n let newText = \"\";\n let count = 0;\n for( let tmp of newSplit){\n let word = tmp.replace(/[\\d+]/g,\"\"); // remove digits\n if(word.length==0){\n continue;\n }\n try {\n if(spellChecker.isMisspelled(word)){\n let arr = await spellChecker.getCorrectionsForMisspelling(word);\n if(arr.length>0){\n word = arr[0];\n }\n }\n } catch (error) {\n console.log(error)\n }\n word = stemmer(word); // stem words\n word = word.toLowerCase();\n newText = newText+ word+' ';\n count++;\n }\n\n if(count<3){ // index elimination\n return \"\";\n }\n return newText;\n}",
"function srQuery(container, search, replace, caseSensitive, wholeWord) {\r if (search) {\r var args = getArgs(caseSensitive, wholeWord);\r rng = document.body.createTextRange();\r rng.moveToElementText(container);\r clearUndoBuffer();\r while (rng.findText(search, 10000, args)) {\r rng.select();\r rng.scrollIntoView();\r if (confirm(\"Replace?\")) {\r rng.text = replace;\r pushUndoNew(rng, search, replace);\r }\r rng.collapse(false) ;\r } \r }\r}",
"function translate (phrase) {\n var newPhrase = \" \";\n for (var count = 0; count < phrase.length; count++) {\n var letter = phrase[count];\n if (cleanerIsVowel(letter) || letter === \" \") {\n newPhrase += letter;\n } else {\n newPhrase += letter + \"o\" + letter;\n }\n return newPhrase;\n}\n\n translate(\"these are some words\");\n}",
"function gather(regex, replacement) {\n\ttext = String(this);\n\tmatches = [ ];\n\twhile ((match = regex.exec(text)) !== null) {\n\t\ttext = text.substring(0, match.index) + replacement + text.substring(match.index + match[0].length);\n\t\tmatches.push(match.slice(1).filter(x => x != undefined)[0]);\n\t}\n\treturn [ matches, text ];\n}",
"function construct_phrase()\n{\n\tif (!arguments || arguments.length < 1 || !is_regexp)\n\t{\n\t\treturn false;\n\t}\n\n\tvar args = arguments;\n\tvar str = args[0];\n\tvar re;\n\n\tfor (var i = 1; i < args.length; i++)\n\t{\n\t\tre = new RegExp(\"%\" + i + \"\\\\$s\", \"gi\");\n\t\tstr = str.replace(re, args[i]);\n\t}\n\treturn str;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
trains a given model with the given syllables | function train(model, syllables) {
console.log('train')
let x = syllables.map(extract)
let y = syllables.map(({ tone }) => tone)
// const data = model.name === 'LogisticRegression' ? [
// new Matrix(x),
// Matrix.columnVector(y)
// ] : [x, y]
const data = [new Matrix(x), Matrix.columnVector(y)]
model.train(...data)
return model
} | [
"function bindLabels(data) {\n $scope.langproLables = data.labels;\n }",
"function TLabel(){}",
"function translateResourceLabel(terms){\n var name = terms[0].terms[0].predicate;\n var label = terms[1].predicate;\n var readWriteValue = \"private\"\n if(terms[2] !== undefined){\n //if it has a read write value\n readWriteValue = terms[2].predicate;\n }\n return {\"l\": [name], \"relation\":\"has_label\", \"r\":[label], \"readWrite\" : readWriteValue}\n //return translateSimpleTriple(\"has_label\",terms);\n }",
"_label(label) {\n return `${label}${label && this.required ? '*' : ''}`;\n }",
"function refine(sentences, generate) {\n console.log('refine')\n return sentences.reduce((syllables, sentence, i) => {\n return syllables.concat(generate(sentence).syllables.map(syllable => ({ ...syllable, sentence: i })))\n }, [])\n}",
"static get wordWrappedMiniLabel() {}",
"function getSyllableSequence() {\n \n var sInd = 0; rInd = 0; tInd = 0;\n testwords[0] = \"boat.jpg\";\n testwords[1] = \"tree.jpg\";\n testwords[2] = \"doll.jpg\";\n testwords[3] = \"koala.jpg\";\n testwords[4] = \"lady.jpg\";\n\n for (var i=0; i<wordseq.length; i++) {\n if (wordseq[i] < 900) {\n for (var j=0; j<3; j++) {\n syllseq[sInd] = words[wordseq[i]][j];\n sInd = sInd+1;\n }\n } else {\n if (debugging) {\n syllseq[sInd] = \"shoe.jpg\";\n } else {\n syllseq[sInd] = testwords[tInd];\n tInd = tInd+1;\n } \n sInd = sInd+1;\n }\n }\n}",
"function TKR_prepLabelAC() {\n var i = 0;\n while ($('label'+i)) {\n TKR_validateLabel($('label'+i));\n i++;\n }\n}",
"static set wordWrappedMiniLabel(value) {}",
"function lite(Obj, lite)\n{\n\tconsole.log(\"TODO: fired LabelLite log\");\n\t//return all styles to normal on all the labels\n\tvar allLabels = \n\t\td3.selectAll(\"#\" + Obj.labels.id).selectAll(\".descLabel\");\n\t//TODO what I need is a better way to know which collection\n\t//of labels to turn off. Doing it by class seems lame.\n\tallLabels\n\t.style(\"color\",null)\n\t//setting a style to null removes the special\n\t//style property from the tag entirely.\n\t//TODO: make the lit and unlit classes\n\t.style(\"font-weight\",null)\n\t.style(\"background-color\",\"\");\n\tvar allBullets = \n\t\td3.selectAll(\"#\" + Obj.labels.id);\n\t//turn all the text back to white, and circles to black\n\tallBullets.selectAll(\"text\").style(\"fill\",\"white\");\n\tallBullets.selectAll(\"circle\").attr(\"class\",\"steps\")\n\t\t;\n\t\t\n\t//highlight the selected label(s)\n\t\n\tvar setLabels = d3.selectAll(\"#\" + Obj.labels.id + lite);\n\tif(setLabels) \n\t\t{\n\t\tsetLabels.selectAll(\"circle\")\n\t\t.attr(\"class\",\"stepsLit\");\n\t\t//highlight the one selected circle and any others\n\t\t//with the same lite index\n\t\tsetLabels.selectAll(\"text\").style(\"fill\",\"#1d95ae\");\n\t\tsetLabels.selectAll(\".descLabel\")\n\t\t//.transition().duration(100)\n\t\t// this renders badly from Chrome refresh bug\n\t\t//we'll have to figure out how to get transitions\n\t\t//back in - maybe just foreign objects?\n\t\t.style(\"color\", \"#1d95ae\")\n\t\t.style(\"font-weight\", \"600\")\n\t\t.style(\"background-color\", \"#e3effe\");\n\t\n\t\t} \n\telse {\n\tconsole.log(\"Invalid key. No label \" + liteKey);\n\t\t}\n}",
"label(attributeName) {\n const arg = this.args[attributeName];\n return arg ? arg.label : null;\n }",
"async setModel(model) {\n\n this.model = model;\n const instanceTree = model.getData().instanceTree;\n const rootId = instanceTree.getRootId();\n\n const bbox =\n await this.getComponentBoundingBox(\n model, rootId);\n\n this.boundingSphere = bbox.getBoundingSphere()\n\n const leafIds = await _BoxSelection_Toolkit.getLeafNodes(model)\n\n this.boundingBoxInfo = leafIds.map((dbId) => {\n\n const bbox = this.getLeafComponentBoundingBox(\n model, dbId)\n\n return {\n bbox,\n dbId\n }\n })\n ZhiUTech_MsgCenter.L_SendMsg(\"警告\",\"框选需要修正的地方\");\n }",
"static set whiteLabel(value) {}",
"function createIssueLabel(labelName , projName){\n return {\n labelName : labelName,\n projname : projName\n }\n}",
"label(text, size = -1) {\n //TODO\n }",
"constructor() {\n super('update labels', 'core.rosie.action.update-labels')\n }",
"function createFormControlLabels() {\n let sectionLabels = [\n 'arts', 'automobiles', 'books', 'business', 'fashion', 'food', 'health', 'home', 'insider', 'magazine', \n 'movies', 'ny region', 'obituaries', 'opinion', 'politics', 'real estate', 'science', 'sports', 'sunday review', \n 'technology', 'theater', 't-magazine', 'travel', 'upshot', 'us', 'world'\n ]\n\n const sectionValues = sectionLabels.map(section => {\n const sectionArr = section.split(' ');\n if (sectionArr.length > 1) {\n section = sectionArr.join('');\n console.log('joining section:', section);\n }\n return section;\n })\n\n /** capitalize each word in selction lables */\n sectionLabels = sectionLabels.map( section => {\n // debugger;\n section = section.split(' ');\n let updatedSection = section.map( item => {\n let firstLetter = item.charAt(0).toUpperCase();\n let remainder = item.slice(1);\n item = firstLetter + remainder;\n return item;\n })\n updatedSection = updatedSection.join(' ');\n return updatedSection;\n })\n\n /** Creating the form labels */\n const formLabels = sectionValues.map( (section, index) => (\n <FormControlLabel\n key={section}\n value={section}\n control={<Radio />}\n label={sectionLabels[index]}\n />\n ))\n\n return formLabels;\n }",
"function LAppModel()\n{\n //L2DBaseModel.apply(this, arguments);\n L2DBaseModel.prototype.constructor.call(this);\n \n this.modelHomeDir = \"\";\n this.modelSetting = null;\n this.tmpMatrix = [];\n}",
"static set boldLabel(value) {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`readSlice()` reads until the first occurrence of `delim` in the input, returning a slice pointing at the bytes in the buffer. The bytes stop being valid at the next read. If `readSlice()` encounters an error before finding a delimiter, or the buffer fills without finding a delimiter, it throws an error with a `partial` property that contains the entire buffer. If `readSlice()` encounters the end of the underlying stream and there are any bytes left in the buffer, the rest of the buffer is returned. In other words, EOF is always treated as a delimiter. Once the buffer is empty, it returns `EOF`. Because the data returned from `readSlice()` will be overwritten by the next I/O operation, most clients should use `readString()` instead. | async readSlice(delim) {
let s = 0; // search start index
let slice;
while (true) {
// Search buffer.
let i = this.buf.subarray(this.r + s, this.w).indexOf(delim);
if (i >= 0) {
i += s;
slice = this.buf.subarray(this.r, this.r + i + 1);
this.r += i + 1;
break;
}
// EOF?
if (this.eof) {
if (this.r === this.w) {
return Deno.EOF;
}
slice = this.buf.subarray(this.r, this.w);
this.r = this.w;
break;
}
// Buffer full?
if (this.buffered() >= this.buf.byteLength) {
this.r = this.w;
throw new BufferFullError(this.buf);
}
s = this.w - this.r; // do not rescan area we scanned before
// Buffer is not full.
try {
await this._fill();
}
catch (err) {
err.partial = slice;
throw err;
}
}
// Handle last byte, if any.
// const i = slice.byteLength - 1;
// if (i >= 0) {
// this.lastByte = slice[i];
// this.lastCharSize = -1
// }
return slice;
} | [
"async readString(delim) {\n if (delim.length !== 1)\n throw new Error(\"Delimiter should be a single character\");\n const buffer = await this.readSlice(delim.charCodeAt(0));\n if (buffer == Deno.EOF)\n return Deno.EOF;\n return new TextDecoder().decode(buffer);\n }",
"async readLine() {\n let line;\n try {\n line = await this.readSlice(LF);\n }\n catch (err) {\n let { partial } = err;\n asserts_ts_1.assert(partial instanceof Uint8Array, \"bufio: caught error from `readSlice()` without `partial` property\");\n // Don't throw if `readSlice()` failed with `BufferFullError`, instead we\n // just return whatever is available and set the `more` flag.\n if (!(err instanceof BufferFullError)) {\n throw err;\n }\n // Handle the case where \"\\r\\n\" straddles the buffer.\n if (!this.eof &&\n partial.byteLength > 0 &&\n partial[partial.byteLength - 1] === CR) {\n // Put the '\\r' back on buf and drop it from line.\n // Let the next call to ReadLine check for \"\\r\\n\".\n asserts_ts_1.assert(this.r > 0, \"bufio: tried to rewind past start of buffer\");\n this.r--;\n partial = partial.subarray(0, partial.byteLength - 1);\n }\n return { line: partial, more: !this.eof };\n }\n if (line === Deno.EOF) {\n return Deno.EOF;\n }\n if (line.byteLength === 0) {\n return { line, more: false };\n }\n if (line[line.byteLength - 1] == LF) {\n let drop = 1;\n if (line.byteLength > 1 && line[line.byteLength - 2] === CR) {\n drop = 2;\n }\n line = line.subarray(0, line.byteLength - drop);\n }\n return { line, more: false };\n }",
"read(size)\n\t{\n\t\tif (this.pos+size > this.input.length)\n\t\t\tsize = this.input.length-this.pos;\n\t\tlet result = this.input.substring(this.pos, this.pos+size);\n\t\tthis.pos += size;\n\t\treturn result;\n\t}",
"async readFull(p) {\n let bytesRead = 0;\n while (bytesRead < p.length) {\n try {\n const rr = await this.read(p.subarray(bytesRead));\n if (rr === Deno.EOF) {\n if (bytesRead === 0) {\n return Deno.EOF;\n }\n else {\n throw new UnexpectedEOFError();\n }\n }\n bytesRead += rr;\n }\n catch (err) {\n err.partial = p.subarray(0, bytesRead);\n throw err;\n }\n }\n return p;\n }",
"substring(offsetIn, length) {\n if (offsetIn < 0 || offsetIn + length > this.length) {\n throw new Error(`Substring (#{offsetIn}-#{offsetIn+length} outside rope (length #{this.length})`);\n }\n\n let [e, offset] = this.seek(offsetIn)\n\n const strings = []\n if (e.str == null) e = e.nexts[0]\n\n while (e && length > 0) {\n let s = e.str.slice(offset, offset + length)\n strings.push(s)\n offset = 0\n length -= s.length\n e = e.nexts[0]\n }\n return strings.join('')\n }",
"function _sslice_advance( slice, count ) {\r\n if (count===0) return slice;\r\n var idx = slice.start;\r\n var end = slice.start + slice.len; \r\n var slicecount = _sslice_count(slice); // todo: optimize by caching the character count?\r\n if (count > 0) {\r\n var extra = 0;\r\n _char_iter(slice.str, idx, function(c,i,nexti) {\r\n extra++;\r\n idx = nexti;\r\n return (extra >= count);\r\n }); \r\n if (extra < slicecount && idx < end) { // optimize\r\n return _sslice_extend({ str: slice.str, start: idx, len: end-idx }, extra);\r\n }\r\n }\r\n else {\r\n var extra = 0;\r\n _char_reviter(slice.str, idx-1, function(c,i,nexti) {\r\n extra++;\r\n idx = i;\r\n return (extra >= -count);\r\n });\r\n if (extra < slicecount && idx < slice.start) { // optimize\r\n return _sslice_extend({ str: slice.str, start: idx, len: slice.start-idx }, slicecount - extra);\r\n }\r\n }\r\n return _sslice_extend( { str: slice.str, start: idx, len: 0 }, slicecount );\r\n}",
"sliceString(){\n this.beg = this.post.value.substring(0, this.state.start);\n this.end = this.post.value.substring(this.state.end, this.post.value.lenght);\n this.selection = this.post.value.substring(this.state.start, this.state.end);\n }",
"async readLine() {\n const s = await this.readLineSlice();\n if (s === Deno.EOF)\n return Deno.EOF;\n return str(s);\n }",
"async read(p) {\n let rr = p.byteLength;\n if (p.byteLength === 0)\n return rr;\n if (this.r === this.w) {\n if (p.byteLength >= this.buf.byteLength) {\n // Large read, empty buffer.\n // Read directly into p to avoid copy.\n const rr = await this.rd.read(p);\n const nread = rr === Deno.EOF ? 0 : rr;\n asserts_ts_1.assert(nread >= 0, \"negative read\");\n // if (rr.nread > 0) {\n // this.lastByte = p[rr.nread - 1];\n // this.lastCharSize = -1;\n // }\n return rr;\n }\n // One read.\n // Do not use this.fill, which will loop.\n this.r = 0;\n this.w = 0;\n rr = await this.rd.read(this.buf);\n if (rr === 0 || rr === Deno.EOF)\n return rr;\n asserts_ts_1.assert(rr >= 0, \"negative read\");\n this.w += rr;\n }\n // copy as much as we can\n const copied = util_ts_1.copyBytes(p, this.buf.subarray(this.r, this.w), 0);\n this.r += copied;\n // this.lastByte = this.buf[this.r - 1];\n // this.lastCharSize = -1;\n return copied;\n }",
"function loadSliceMesh( slices ) {\n\tvar ret = new Array()\n\t\n\tfor( s = 0; s < N_SLICES; s++ ) {\n\t\tvar verts = gl.createBuffer()\n\t\tgl.bindBuffer( gl.ARRAY_BUFFER, verts )\n\t\t\n\t\tvar indis = gl.createBuffer()\n\t\tgl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indis )\n\t\t\n\t\tvar tex = genTex2d();\n\t\t\n\t\tgl.vertexAttribPointer( positionLoc2d, 3, gl.FLOAT, false, vertSize, 0 )\n\t\tgl.vertexAttribPointer( uvLoc2d, 2, gl.FLOAT, false, vertSize, 16 )\n\t\tnIndis = genMesh2dSlice( texData, slices[s], verts, indis, tex );\n\t\t\n\t\tret[s] = [verts, indis, tex];\n\t\t//sliceMesh.push( [ verts, indis, tex ] )\n\t}\n\t\n\treturn ret\n}",
"function stringSlice(str,start,end){\n if(end === undefined || end > str.length){end = str.length}\n var newStr = \"\";\n if(start < 0){start += str.length}\n for(var i = start; i < end; i++){\n newStr+=str[i];\n }\n return newStr;\n}",
"function testSlice() {\n checkSlice();\n}",
"function _sslice_extend( slice, count ) {\r\n if (count===0) return slice;\r\n var idx = slice.start + slice.len;\r\n if (count > 0) {\r\n _char_iter(slice.str, idx, function(c,i,nexti) {\r\n count--;\r\n idx = nexti;\r\n return (count <= 0);\r\n });\r\n }\r\n else {\r\n _char_reviter(slice.str, idx-1, function(c,i,nexti) {\r\n count++;\r\n idx = i;\r\n return (count >= 0 || idx <= slice.start);\r\n });\r\n }\r\n return { str: slice.str, start: slice.start, len: (idx > slice.start ? idx - slice.start : 0) };\r\n}",
"_feed(chars) {\n\n var delimiter_pos;\n this._buffer = Buffer.concat([this._buffer, chars]);\n\n while((delimiter_pos = this._buffer.indexOf(DELIMITER)) != -1) {\n // Read until delimiter\n var buff = this._buffer.slice(0, delimiter_pos);\n this._buffer = this._buffer.slice(delimiter_pos + 1);\n\n // Check data are json\n var data = null;\n try {\n data = JSON.parse(buff.toString());\n } catch(e) {\n log.info(\"Bad data, not json\", buff, \"<raw>\", buff.toString(), \"</raw>\");\n continue;\n }\n\n // Send to client\n if(data)\n this.emit(\"transport_message\", data).catch(log.error);\n }\n }",
"function solution(read4) {\n let storage = [];\n\n return function(buf, n){\n let readChars = 0;\n\n while(n > 0){\n if(storage.length === 0){\n if(read4(storage) === 0){\n return readChars;\n }\n }\n\n buf.push(storage.shift());\n readChars ++;\n n --;\n }\n\n return readChars;\n }\n}",
"function getuntil(line, delimiter) {\n let ret = \"\"\n // Remove first line if empty\n if (line.trim() == \"\")\n line = getline().replace(/\\t/g, \" \") \n\n while (true) {\n if (line.includes(delimiter)) {\n while (line.includes(delimiter))\n line = line.replace(delimiter, '')\n ret += line;\n return ret // ------>\n } else\n ret += line + \"\\n\"\n if (n >= output.length)\n return ret // ------>;\n line = getline().replace(/\\t/g, \" \")\n }\n }",
"_read() {\n if (this.index <= this.array.length) {\n //getting a chunk of data\n const chunk = {\n data: this.array[this.index],\n index: this.index\n };\n //we want to push chunks of data into the stream\n this.push(chunk);\n this.index += 1;\n } else {\n //pushing null wil signal to stream its done\n this.push(null);\n }\n }",
"async peek(n) {\n if (n < 0) {\n throw Error(\"negative count\");\n }\n let avail = this.w - this.r;\n while (avail < n && avail < this.buf.byteLength && !this.eof) {\n try {\n await this._fill();\n }\n catch (err) {\n err.partial = this.buf.subarray(this.r, this.w);\n throw err;\n }\n avail = this.w - this.r;\n }\n if (avail === 0 && this.eof) {\n return Deno.EOF;\n }\n else if (avail < n && this.eof) {\n return this.buf.subarray(this.r, this.r + avail);\n }\n else if (avail < n) {\n throw new BufferFullError(this.buf.subarray(this.r, this.w));\n }\n return this.buf.subarray(this.r, this.r + n);\n }",
"function split(str, delimiter)\n{\n let arr = [], n = 0\n , esc = -99\n , s = ''\n\n for (let i=0; i<str.length; i++) {\n switch(str[i]) {\n case delimiter :\n if (esc !== (i-1)) {\n arr[n++] = s\n s = ''\n } else s += str[i]\n break\n case '\\\\' :\n // Escaping a backslash\n if (esc == (i-1)) {\n esc = -99\n s += str[i-1] + str[i]\n } else \n esc = i\n break\n default :\n if (esc == (i-1))\n s += str[i-1]\n s += str[i]\n }\n }\n arr[n++] = s\n return arr\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
| | Webpack Server Config | | function webpackServerConfig() {
let config = webpackBaseConfig.call(this, 'server');
// env object defined in nuxt.config.js
let env = {};
_.each(this.options.env, (value, key) => {
env['process.env.' + key] = ['boolean', 'number'].indexOf(typeof value) !== -1 ? value : JSON.stringify(value);
});
config = Object.assign(config, {
target: 'node',
node: false,
devtool: 'source-map',
entry: path.resolve(this.options.buildDir, 'server.js'),
output: Object.assign({}, config.output, {
filename: 'server-bundle.js',
libraryTarget: 'commonjs2'
}),
performance: {
hints: false,
maxAssetSize: Infinity
},
externals: [],
plugins: (config.plugins || []).concat([new VueSSRServerPlugin({
filename: 'server-bundle.json'
}), new webpack.DefinePlugin(Object.assign(env, {
'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV || (this.options.dev ? 'development' : 'production')),
'process.env.VUE_ENV': JSON.stringify('server'),
'process.mode': JSON.stringify(this.options.mode),
'process.browser': false,
'process.client': false,
'process.server': true,
'process.static': this.isStatic
}))])
});
// https://webpack.js.org/configuration/externals/#externals
// https://github.com/liady/webpack-node-externals
this.options.modulesDir.forEach(dir => {
if (fs.existsSync(dir)) {
config.externals.push(nodeExternals({
// load non-javascript files with extensions, presumably via loaders
whitelist: [/es6-promise|\.(?!(?:js|json)$).{1,5}$/i],
modulesDir: dir
}));
}
});
// --------------------------------------
// Production specific config
// --------------------------------------
if (!this.options.dev) {}
// Extend config
if (typeof this.options.build.extend === 'function') {
const isDev = this.options.dev;
const extendedConfig = this.options.build.extend.call(this, config, {
get dev() {
console.warn('dev has been deprecated in build.extend(), please use isDev'); // eslint-disable-line no-console
return isDev;
},
isDev,
isServer: true
});
// Only overwrite config when something is returned for backwards compatibility
if (extendedConfig !== undefined) {
config = extendedConfig;
}
}
return config;
} | [
"prepareWebpackConfig() {\r\n this.clientConfig = createClientConfig(this.context).toConfig()\r\n this.serverConfig = createServerConfig(this.context).toConfig()\r\n\r\n const userConfig = this.context.siteConfig.configureWebpack\r\n if (userConfig) {\r\n this.clientConfig = applyUserWebpackConfig(\r\n userConfig,\r\n this.clientConfig,\r\n false\r\n )\r\n this.serverConfig = applyUserWebpackConfig(\r\n userConfig,\r\n this.serverConfig,\r\n true\r\n )\r\n }\r\n }",
"function webpackPluginServe(_a) {\n var _this = this;\n var staticPaths = _a.staticPaths, historyApiFallback = _a.historyApiFallback, options = tslib_1.__rest(_a, [\"staticPaths\", \"historyApiFallback\"]);\n if (process.env.STORYBOOK) {\n return {};\n }\n var historyFallback = !!historyApiFallback;\n // You can speed up execution by 20-30% by enabling ramdisk. It's\n // not used as it's possible it runs out of memory on default settings.\n return {\n plugins: [\n new webpack_plugin_serve_1.WebpackPluginServe(tslib_1.__assign({ hmr: \"refresh-on-failure\", progress: \"minimal\", historyFallback: historyFallback, middleware: function (app) {\n return app.use(function (ctx, next) { return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n ctx.set(\"Access-Control-Allow-Origin\", \"*\");\n return [4 /*yield*/, next()];\n case 1:\n _a.sent();\n return [2 /*return*/];\n }\n });\n }); });\n }, static: staticPaths, waitForBuild: true }, options)),\n ],\n watch: true,\n };\n}",
"getEntry() {\n // First destructure away the stuff we need\n const {\n name,\n entry\n } = this.file; // We intend to pass the entry directly to webpack,\n // but, we need to add the hot-middleware client to the entry\n // else it will simply not work\n\n const normalizedEntry = {}; // Loop over all user defined entries and add to the normalizedEntry\n\n Object.keys(entry).forEach(key => {\n // We have to break and take the value in a separate\n // variable, otherwise typescript says all the weird\n // thing 😢\n const entryPoint = entry[key];\n normalizedEntry[key] = Array.isArray(entryPoint) ? // maybe we can go a step futher and put an entry point which takes\n // care of the __webpack_public_path__\n // like `@wpackio/publicpath?outputPath=${this.config.outputPath}&appName=${this.config.appName}`\n entryPoint : [entryPoint];\n }); // Now, if in dev mode, then add the hot middleware client\n\n if (this.isDev) {\n // Custom overlay and it's styling\n const overlayStyles = {\n zIndex: 999999999,\n fontSize: '14px',\n fontFamily: 'Dank Mono, Operator Mono SSm, Operator Mono, Menlo, Consolas, monospace',\n padding: '32px 16px'\n }; // Define the hot client string\n // Here we need\n // 1. dynamicPublicPath - Because we intend to use __webpack_public_path__\n // we can not know if user is going to use it in development too, but maybe it doesn't need to be?\n // 2. overlay and overlayStypes - To enable overlay on errors, we don't need warnings here\n // 3. path - The output path, We need to make sure both server and client has the same value.\n // 4. name - Because it could be multicompiler\n\n const webpackHotClient = `webpack-hot-middleware/client?path=__wpackio&name=${name}&dynamicPublicPath=true${this.config.errorOverlay ? '&overlay=true' : ''}&reload=true&overlayStyles=${encodeURIComponent(JSON.stringify(overlayStyles))}`; // Now add to each of the entries\n // We don't know if user want to specifically disable for some, but let's\n // not think ahead of ourselves\n\n Object.keys(normalizedEntry).forEach(key => {\n normalizedEntry[key] = [...normalizedEntry[key], // put webpack hot client in the entry\n webpackHotClient];\n });\n } else {\n // Put the publicPath entry point\n Object.keys(normalizedEntry).forEach(key => {\n normalizedEntry[key] = [// We need it before any other entrypoint, otherwise it won't\n `@wpackio/entrypoint/lib/index`, ...normalizedEntry[key]];\n });\n }\n\n return normalizedEntry;\n }",
"function appConfigPlugin(server) {\n server.ext(\"onRequest\", (request, h) => {\n request.app.config = server.app.config;\n return h.continue;\n });\n}",
"function getWebpackConfig(\n options = {\n /**\n * Whether we're compiling any CSS: if so, will add the loaders\n * and plugins needed\n */\n hasCss: true,\n /** Whether we're compiling with source maps (usually for non-production) */\n useSourceMaps: false,\n /** Whether we're compiling with CSS source maps (usually for non-production) */\n useCssSourceMaps: false,\n /** Whether to minimize/uglify (usually for production) */\n minimize: false,\n /** Whether we're building for production (for the Webpack mode) */\n production: false,\n /** Whether to code-split; if false, will limit to single chunk */\n splitChunks: false,\n /**\n * Whether to emit loadable-stats.json for use for server-side rendering after\n * code-splitting\n */\n emitLoadable: false,\n },\n /** Extra configuration keys (e.g., entry, output) to merge */\n extraConfigToMerge = {},\n) {\n const {\n hasCss,\n useSourceMaps,\n useCssSourceMaps,\n minimize,\n production,\n splitChunks,\n emitLoadable,\n } = options;\n\n const commonCssLoaders = [\n { loader: MiniCssExtractPlugin.loader },\n {\n loader: 'css-loader',\n options: {\n importLoaders: 2, // Indicates both post-css and sass-loaders are used before this\n sourceMap: useSourceMaps,\n },\n },\n {\n loader: 'postcss-loader',\n options: {\n ident: 'postcss',\n plugins: [autoprefixer({ browsers: browsersListBrowsers })],\n sourceMap: useSourceMaps,\n map: { inline: true },\n },\n },\n ];\n\n /**\n * Building for browsers requires a slightly different babelrc\n * compared to for node.js\n */\n const buildClientBabelOpts = getBabelRc({\n transformModules: false,\n isBabelRc: false,\n isClient: true,\n });\n\n const webpackConfig = {\n mode: production ? 'production' : 'development',\n ...extraConfigToMerge,\n devtool: useSourceMaps ? 'cheap-module-eval-source-map' : false,\n resolve: {\n extensions: ['.wasm', '.mjs', '.js', '.json', '.ts', '.tsx'],\n },\n node: {\n fs: 'empty',\n },\n module: {\n rules: [\n {\n test: /\\.(js|jsx|mjs|ts|tsx)$/,\n // These libraries uses some ES6 syntax\n exclude: /node_modules\\/(?!quill|copy-text-to-clipboard)/,\n use: [\n {\n loader: 'babel-loader',\n options: {\n ...buildClientBabelOpts,\n cacheDirectory: true,\n },\n },\n ],\n },\n ].concat(\n hasCss\n ? [\n {\n test: /\\.s?css$/,\n use: commonCssLoaders.concat([\n {\n loader: 'sass-loader',\n options: { sourceMap: useSourceMaps },\n },\n ]),\n },\n {\n test: /\\.less$/,\n use: commonCssLoaders.concat([\n {\n loader: 'less-loader',\n options: {\n javascriptEnabled: true,\n sourceMap: useSourceMaps,\n },\n },\n ]),\n },\n ]\n : [],\n ),\n },\n plugins: [\n new webpack.IgnorePlugin(/^\\.\\/locale$/, /moment$/),\n ...(emitLoadable ? [new LoadablePlugin()] : []),\n ],\n optimization: {\n // For mysterious reasons, concatenateModules results in the error\n // \"Object(...) is not a function\" or\n // \"__webpack_require__(...) is not a function\" (pre-minification)\n // as mentioned here: https://github.com/webpack/webpack/issues/6544\n concatenateModules: false,\n minimizer: minimize\n ? [\n new TerserPlugin({\n cache: true,\n parallel: true,\n sourceMap: true,\n }),\n ...(hasCss ? [new OptimizeCSSAssetsPlugin({})] : []),\n ]\n : undefined,\n },\n devServer: {\n /** Enables proxying the root \"/\" path */\n index: '',\n port: 7001,\n /**\n * All compiled .js and .css files are served at this path. Defaults to\n * root (\"/\").\n */\n publicPath: extraConfigToMerge.output.publicPath\n ? extraConfigToMerge.output.publicPath\n : undefined,\n proxy: [\n {\n context: () => true, // Redirect all requests we can't serve\n target: `http://localhost:60987`,\n },\n {\n context: () => true, // Redirect all requests we can't serve\n target: 'ws://localhost:60987',\n ws: true,\n },\n ],\n },\n };\n\n if (hasCss) {\n webpackConfig.plugins.push(\n new MiniCssExtractPlugin({\n filename: '[name].css',\n chunkFilename: '[name]-[id].css',\n sourcemap: false,\n }),\n );\n }\n\n // We don't really use sourcemaps on mobile\n if (useCssSourceMaps && hasCss) {\n // This is to generate sourcemaps for CSS files; workaround from\n // https://github.com/webpack-contrib/mini-css-extract-plugin/issues/29#issuecomment-382424129\n webpackConfig.plugins.push(\n new webpack.SourceMapDevToolPlugin({\n filename: '[file].map',\n exclude: ['/vendor/'],\n }),\n );\n }\n\n if (!splitChunks) {\n webpackConfig.plugins.push(\n new webpack.optimize.LimitChunkCountPlugin({\n maxChunks: 1,\n }),\n );\n }\n\n return webpackConfig;\n}",
"function generateWebpackConfigForCanister(name, info) {\n if (typeof info.frontend !== 'object') {\n return;\n }\n const outputRoot = path.join(__dirname, output, name);\n const inputRoot = __dirname;\n const entry = path.join(inputRoot, info.frontend.entrypoint);\n return {\n mode: \"production\",\n entry,\n devtool: \"source-map\",\n optimization: {\n minimize: true,\n minimizer: [new TerserPlugin()],\n },\n resolve: {\n alias: aliases,\n },\n module: {\n rules: [\n { test: /\\.(js|ts)x?$/, loader: \"ts-loader\" }\n ]\n }, \n output: {\n filename: \"index.js\",\n path: path.join(outputRoot, \"assets\"),\n },\n plugins: [\n ],\n };\n}",
"function startDistServer() {\n server.init({\n notify: false,\n port,\n server: {\n baseDir: 'dist',\n middleware: [ compress() ],\n routes: {\n '/node_modules': 'node_modules'\n }\n }\n });\n}",
"function serve() {\n const express = require('express');\n const helmet = require('helmet');\n const compression = require('compression');\n\n const app = express();\n app.use(helmet());\n app.use(compression());\n app.use(express.static(config.PUBLIC_PATH));\n\n // Redirect 404s\n app.get('*', (request, reply) => {\n reply.redirect('/');\n });\n\n // Start the server\n const port = process.env.PORT || 3000;\n let listener = app.listen(port, () => {\n console.log(chalk.bold.green(`Listening on port ${port}`));\n });\n\n // Enable auto restarting in development\n if (process.env.NODE_ENV !== 'production') {\n const enableDestroy = require('server-destroy');\n enableDestroy(listener);\n\n // Recompile on changes to anything\n [config.POSTS_PATH, config.TEMPLATES_PATH].forEach(path => {\n fs.watch(path, { recursive: true }, async (event, filename) => {\n // Recompile posts\n await compile();\n\n // Purge all connections and close the server\n listener.destroy();\n listener = app.listen(port);\n\n // Set up connection tracking so that we can destroy the server when a file changes\n enableDestroy(listener);\n });\n });\n }\n}",
"function build_localServer() {\n console.log(\"BrowserSync setting up the server in port 4000\");\n browserSync.init({\n port: 4000,\n server: {\n baseDir: \"./_site/\",\n },\n });\n}",
"$registerHttpServer() {\n this.$container.singleton('Adonis/Core/Server', () => {\n const Logger = this.$container.use('Adonis/Core/Logger');\n const Profiler = this.$container.use('Adonis/Core/Profiler');\n const Config = this.$container.use('Adonis/Core/Config');\n const Encryption = this.$container.use('Adonis/Core/Encryption');\n const config = Object.assign({ secret: Config.get('app.appKey') }, Config.get('app.http', {}));\n return new Server_1.Server(this.$container, Logger, Profiler, Encryption, config);\n });\n }",
"function configureWebpack(config, options) {\n let { transpile } = options;\n let globs = getEntryFileGlobs(options);\n util_1.addPlugin(config, \"karma-webpack\");\n for (let glob of globs) {\n config.preprocessors = util_1.mergeConfig(config.preprocessors, {\n [glob]: [\"webpack\"],\n });\n }\n config.webpack = util_1.mergeConfig(config.webpack, {\n mode: \"development\",\n devtool: \"inline-source-map\",\n });\n config.webpack.module = util_1.mergeConfig(config.webpack.module, {\n rules: [],\n });\n if (transpile && !util_1.hasWebpackLoader(config.webpack.module.rules, \"babel-loader\")) {\n config.webpack.module.rules.push({\n test: /\\.(js|jsx|mjs)$/,\n use: {\n loader: \"babel-loader\",\n options: {\n presets: [\"@babel/preset-env\"]\n }\n }\n });\n }\n return config;\n}",
"getOutput() {\n // Assuming it is production\n const output = {\n // Here we create a directory inside the user provided outputPath\n // The name of the directory is the sluggified verion of `name`\n // of this configuration object.\n // Also here we assume, user has passed in the correct `relative`\n // path for `outputPath`. Otherwise this will break.\n // We do not use path.resolve, because we expect outputPath to be\n // relative. @todo: create a test here\n path: this.outputPath,\n filename: `${this.appDir}/${this.isDev ? '[name]' : '[name]-[contenthash:8]'}.js`,\n // leave blank because we would handle with free variable\n // __webpack_public_path__ in runtime.\n publicPath: '',\n // we need different jsonpFunction, it has to\n // be unique for every webpack config, otherwise\n // the later will override the previous\n // having combination of appName and file.name\n // kind of ensures that billions of devs, don't\n // override each other!!!!\n jsonpFunction: `wpackio${this.config.appName}${this.file.name}Jsonp`\n }; // Add the publicPath if it is in devMode\n\n if (this.isDev) {\n // This is calculated by CreateWebpackConfig\n // taking into consideration user's own value.\n // So, if WordPress defaults are changed, then\n // depending on wpackio.server.js, it will still\n // point to the right location. It only makes\n // dynamic import and some on-demand split-chunk\n // work.\n output.publicPath = this.config.publicPathUrl;\n }\n\n return output;\n }",
"function createWebpackConfigStatic(\n batfishConfig: BatfishConfiguration\n): Promise<webpack$Configuration> {\n return createWebpackConfigBase(batfishConfig).then(baseConfig => {\n const staticConfig: webpack$Configuration = {\n entry: {\n static: path.join(__dirname, '../webpack/static-render-pages.js')\n },\n output: {\n filename: './static-render-pages.js',\n libraryTarget: 'commonjs2'\n },\n target: 'node',\n externals: {\n // These modules are required by static-render-pages and don't play\n // nice when Webpack tries to compile them, or we know they can be\n // loaded in Node.\n 'uglify-js': 'uglify-js',\n mkdirp: 'mkdirp',\n react: 'react',\n 'react-dom': 'react-dom'\n },\n plugins: [\n // Ensure that all files will be grouped into one file,\n // even if they would otherwise be split into separate chunks.\n // Separate chunks serve no purpose in the static build: we need all\n // the information at once.\n new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 })\n ],\n devtool: 'source-map',\n node: {\n console: false,\n global: false,\n process: false,\n __filename: false,\n __dirname: false,\n Buffer: false,\n setImmediate: false\n }\n };\n\n if (batfishConfig.webpackStaticIgnore) {\n _.set(staticConfig, 'module.rules[0]', {\n test: batfishConfig.webpackStaticIgnore,\n loader: 'ignore-loader'\n });\n }\n\n let config = webpackMerge(baseConfig, staticConfig);\n if (batfishConfig.webpackConfigStaticTransform) {\n config = batfishConfig.webpackConfigStaticTransform(config);\n }\n return config;\n });\n}",
"_addStaticRoutes() {\n const app = this._app;\n\n if (Deployment.shouldServeClientCode()) {\n // Map Quill files into `/static/quill`. This is used for CSS files but\n // not for the JS code; the JS code is included in the overall JS bundle\n // file.\n app.use('/static/quill',\n express.static(path.resolve(Dirs.theOne.CLIENT_DIR, 'node_modules/quill/dist')));\n\n // Use the client bundler (which uses Webpack) to serve JS bundles. The\n // `:name` parameter gets interpreted by the client bundler to select\n // which bundle to serve.\n app.get('/static/js/:name.bundle.js', new ClientBundle().requestHandler);\n }\n\n // Use the configuration point to determine which directories to serve\n // HTML files and other static assets from. This includes (but is not\n // necessarily limited to) the top-level `index.html` and `favicon` files,\n // as well as stuff explicitly under `static/`.\n for (const dir of Deployment.ASSET_DIRS) {\n app.use('/', express.static(dir));\n }\n }",
"makeServer() {\n this.server = http.Server(this.app);\n }",
"function compileServer() {\n return gulp.src(PATHS.server)\n .pipe(coffee({bare: true}))\n .pipe(rename({ extname: '.js' }))\n .pipe(gulp.dest(PATHS.dist.server));\n}",
"cb(config) {\n //you have access to the gulp config here for\n //any extra customization after merging => don't forget to return config\n return merge(config, serverConfig);\n }",
"listen() {\n console.log('--- Listening on localhost:8000 ---');\n this.server.listen(8000);\n }",
"function build () {\n console.log(`\\x1b[33mBuilding webpack in production mode...\\n\\x1b[0m`)\n\n const buildProcess = exec('npm run build:prod')\n\n buildProcess.stdout.on('data', data => console.log(data))\n buildProcess.stderr.on('data', data => console.error(data))\n buildProcess.on('exit', code => pack())\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the albums displayed within the album list to the albums contained in the specified feed. | function setAlbums(albumFeed) {
for (var i = 0; i < albumFeed.feed.entry.length; i++) {
renderAlbum(this, albumFeed.feed.entry[i]);
}
} | [
"function populateAlbums (albums, list) {\n\n\t\tfor (var album of albums) {\n\n\t\t\tvar albumTemplate = importTemplate('artist-album-template');\n\n\t\t\tvar albumName = albumTemplate.querySelector('.artist-album-name');\n\t\t\talbumName.textContent = album.name;\n\n\t\t\tvar viewAlbum = emitEvent('view-album', album.name);\n\t\t\talbumName.addEventListener('click', viewAlbum);\n\n\t\t\tvar songList = albumTemplate.querySelector('.album-songs');\n\t\t\tpopulateSongs(album.songs, songList);\n\n\t\t\tlist.appendChild(albumTemplate);\n\n\t\t}\n\n\t}",
"function getFeedItems(feed) {\n\t\t$.ajax({\n\t\t url: urlBase + 'articles/' + encodeURIComponent(feed.feed),\n\t\t\tdataType: \"json\",\n\t\t\tsuccess: function (data) {\n\t\t\t\tko.utils.arrayForEach(data, function(item) {\n\t\t\t\t\tvm.displayedItems.push( new Item(feed, item) );\n\t\t\t\t\t\n\t\t\t\t\tvar bool = containsId(vm.bookmarkedArray(), vm.displayedItems()[vm.displayedItems().length-1]);\n\t\t\t\t\t\n\t\t\t\t\tif(vm.displayedItems()[vm.displayedItems().length-1].favorite() == 'fav-icon' && bool)\n\t\t\t\t\t\tvm.bookmarkedArray.push(vm.displayedItems()[vm.displayedItems().length-1]);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}",
"function hideAndShowAlbums() {\r\n //console.log('hideAndShowAlbums: ' + albumSelected);\r\n for (var i = 0; i < albumSelectors.length; i++) {\r\n var selector = albumSelectors[i];\r\n if (i === albumSelected) {\r\n $(selector).show();\r\n\r\n } else {\r\n $(selector).hide();\r\n }\r\n }\r\n }",
"function zoto_dual_list_albums(options){\n\toptions = merge({'key': \"album_id\"}, options);\n\tthis.$uber(options);\n}",
"function refreshRss() {\n\trss.loadRssFeed({\n\t\tsuccess: function(data) {\n\t\t\tvar rows = [];\n\t\t\t_.each(data, function(item) {\n\t\t\t\trows.push(Alloy.createController('row', {\n\t\t\t\t\tarticleUrl: item.link,\n\t\t\t\t\timage: item.image,\n\t\t\t\t\ttitle: item.title,\n\t\t\t\t\tdate: item.pubDate\n\t\t\t\t}).getView());\n\t\t\t});\n\t\t\t$.fb_table_albums.setData(rows);\n\t\t}\n\t});\n}",
"function fetchFeedItems(url, from, count, callback) {\n\t\tfrom = from || 0;\n\t\tcount = count || 20;\n\t\t\n\t\tvar feed = new google.feeds.Feed(FEED_URL);\n\t\tfeed.setResultFormat(google.feeds.Feed.JSON_FORMAT);\n\t\tfeed.setNumEntries(from + count);\n\t\tfeed.includeHistoricalEntries();\n\t\tlog('From ' + from + ' to ' + (from + count) + '\\n');\n\t\tfeed.load(function(result) {\n\t\t\tif (result.error) {\n\t\t\t\tret = false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Set title\n\t\t\t\theader = '<a href=\"' + result.feed.link + '\" rel=\"external\" target=\"_blank\"><h1>' + result.feed.title + '</h1></a>';\n\t\t\t header += '<h2><small>' + result.feed.description + '</small></h2>';\n\t\t\t header += '<hr class=\"soften\">'; \n\t\t\t $('body > div.container-fluid > .title-wrapper').html(header);\n\t\t\t\t\n\t\t\t\tvar max = (count > result['feed'].entries.length) ? count : result['feed'].entries.length;\n\t\t\t\titems = [];\n\t\t\t\tfor (var i = from; i < max; i++) {\n\t\t\t\t\titem = result['feed'].entries[i];\n\t\t\t\t\titem.eid = i;\n\t\t\t\t\tENTRIES[i] = item;\n\t\t\t\t\titems.push(item);\n\t\t\t\t}\n\t\t\t\tret = items;\t\n\t\t\t}\t\n\t\t\t\n\t\t\tif (callback && $.isFunction(callback)) {\n\t\t\t\tcallback(ret);\n\t\t\t}\n\t\t});\n\t}",
"loadAlbumsDetails() {\n this._ApiFactory.getAlbumDetails(this.albumId).query({}, (response) => {\n\n this.album = {\n name: response.name,\n images: response.images\n }\n }, (response) => {\n if (response.status === 401 || response.status === 403 || response.status === 419 || response.status === 440)\n this._JWT.login();\n });\n }",
"loadAlbumTracks() {\n this._ApiFactory.getAlbumsTracks(this.albumId).query({}, (response) => {\n\n const tracks = [];\n response.items.forEach((i) => {\n const track = {\n name: i.name,\n images: i.images,\n duration: this.convertToMinutesSeconds(i.duration_ms)\n }\n tracks.push(track);\n });\n this.tracks = tracks;\n\n }, (response) => {\n if (response.status === 401 || response.status === 403 || response.status === 419 || response.status === 440)\n this._JWT.login();\n });\n }",
"function initializeArticleFeed() {\n\tvar feeds = document.querySelectorAll('[data-content-type=\\'cdp-article-feed\\']');\n\tforEach(feeds, function (index, feed) {\n\t\trenderArticleFeed(feed);\n\t});\n}",
"function updateAndRebuildFeed()\n {\n $loading.show();\n FeedAPI.get().done((results) => {\n cache = results;\n\n buildFeed(currentFeed);\n $loading.delay(200).hide(0);\n }).fail(() => {\n options();\n });\n }",
"static getAlbums() {\n let albums;\n if (localStorage.getItem('albums') === null) {\n albums = [];\n } else {\n albums = JSON.parse(localStorage.getItem('albums'));\n }\n\n return albums;\n }",
"function GetAlbumsSortedBy(id, sortMode, sortOverride) {\n $('#loading_anim_albums').show();\n var sortModes = ['DATE ADDED', 'A TO Z', 'RELEASE YEAR', 'ARTIST'];\n\n leftListId = id;\n\n if (id !== null && id.startsWith(\"albumartists\")) {\n //remove the artist because we do not need to display it when showing albums for an artist\n sortModes.splice(3, 1);\n }\n var theSortMode;\n\n if (sortOverride === false) {\n var idx = sortModes.indexOf(sortMode);\n if (idx == sortModes.length - 1) {\n theSortMode = sortModes[0];\n }\n else {\n theSortMode = sortModes[idx + 1];\n }\n }\n else {\n theSortMode = sortMode;\n }\n\t\n\t//todo: remove hardcoded album width values and get real values\n\tvar xAlbums = Math.floor($(\"#albums\").width() / 130);\n\tvar yAlbums = Math.ceil($(\"#albums\").height() / 161)\n\t//+ 1 row to prevent the div from scrolling while albums are loading\n\tvar numAlbsToGet = xAlbums * yAlbums + xAlbums;\n\t\n\tif(theSortMode === 'ARTIST'){\n\t\tnumAlbsToGet = yAlbums;\n\t}\n\n switch (theSortMode) {\n case \"DATE ADDED\":\n QueryAlbumsSortedByDateAdded(id, 0,numAlbsToGet, function (result) {\n if (id !== null && id.length > 0) {\n UpdateView(CreateAlbumObjectsWithNoHeaderingsForArtists(result, 'DATE ADDED', id));\n }\n else {\n UpdateView(CreateAlbumObjectsWithNoHeaderings(result, 'DATE ADDED'));\n }\n });\n break;\n case \"A TO Z\":\n QueryAlbumsSortedByAlbumTitle(id, 0,numAlbsToGet, function (result) {\n if (id !== null && id.length > 0) {\n UpdateView(CreateAlbumObjectsWithNoHeaderingsForArtists(result, 'A TO Z', id));\n }\n else {\n UpdateView(CreateAlbumObjectsWithNoHeaderings(result, 'A TO Z'));\n }\n });\n break;\n case \"RELEASE YEAR\":\n QueryAlbumsSortedByReleaseYear(id, 0, numAlbsToGet, function (result) {\n if (id !== null && id.length > 0) {\n if (id.startsWith('albumartists')) {\n UpdateView(CreateAlbumObjectsWithNoHeaderingsForArtists(result, 'RELEASE YEAR', id));\n }\n else {\n UpdateView(CreateAlbumObjectsWithYearHeadersForGenres(id, result, 'RELEASE YEAR'));\n }\n }\n else {\n UpdateView(CreateAlbumObjectsWithYearHeaders(result, 'RELEASE YEAR'));\n }\n });\n break;\n case \"ARTIST\":\n QueryAlbumsSortedByArtist(id, 0,numAlbsToGet, function (result) {\n if (id !== null && id.length > 0) {\n //just for genres\n UpdateView(CreateAlbumObjectsWithArtistHeadersForGenres(id, result, 'ARTIST', id));\n }\n else {\n UpdateView(CreateAlbumObjectsWithArtistHeaders(result, 'ARTIST'));\n }\n });\n }\n\n function UpdateView(result) {\n\t\t//render header\n\t\t$(\"#middle_header\").remove();\n $(\"#content\").append(\"#tmpl_albums_container\", result);\n\t\t\n\t\t$(\"#albums > .inner\").empty();\n\t\t//render results\n\t\t$.each(result.AlbumsOrHeaders,function(idx,value){\n\t\t\tif(value.IsContent === false){\n\t\t\t\t$(\"#albums > .inner\").append(\"#tmpl_album_header\",value);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tRenderAlbumToView($(\"#albums > .inner\"),value.Content);\n\t\t\t}\n\t\t});\n\t\t\n\t\t//for the first row of albums we need to remove the top padding\n\t\t\n\t\t//infinite scroll\n\t\tvar elem = $('#albums')\n elem.scroll(function () {\n\t\t\tif (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) {\n\t\t\t\tconsole.log(\"getting more albums...\");\n\t\t\t\tGetMoreAlbums(leftListId);\n\t\t\t}\n });\n\n\t\t\n $('#loading_anim_albums').hide();\n }\n}",
"getBoughtAlbums () {\n return music.getBoughtAlbums().then((response) => {\n return response.data\n })\n }",
"function renderAlbum(album) {\n var html = albumsTemplate(album);\n $('#albums').prepend(html);\n}",
"function _retrieve () {\n api.retrieveAlbums().then(_success).catch(_error);\n }",
"setFolders(state, folders) {\n state.list = folders\n }",
"setArtwork(playlist_tracks) {\n debugger;\n var artCollection = [];\n if (playlist_tracks != undefined) {\n artCollection = Object.values(playlist_tracks).map(track => {\n return track.album_art;\n });\n }\n return this.createArtwork(artCollection);\n }",
"function populateSongs (songs, list) {\n\n\t\tfor (var song of songs) {\n\n\t\t\tvar songTemplate = importTemplate('album-song-template');\n\n\t\t\tsongTemplate.querySelector('.song-name').textContent = song.name;\n\t\t\tsongTemplate.querySelector('.album-song').value = song.number;\n\n\t\t\tvar addButton = songTemplate.querySelector('.add-song');\n\t\t\taddButton.addEventListener('click', emitEvent('add-song', song));\n\n\t\t\tlist.appendChild(songTemplate);\n\n\t\t}\n\n\t}",
"function _getNewFeeds() {\n\n let query = {\n tag: 'steemovie',\n limit: 21,\n };\n\n steem.api.getDiscussionsByCreated(query, function (err, result) {\n app.feeds = result;\n\n // Rendering process of image image\n renderingImagePaths(result)\n });\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A Codec is one of the three Transformer kinds. Codecs are a pair of functions that serialize Types into bytes (or abritrary representations), and deserialize back. There MUST be no information loss in Codecs; they're simply representing a Type in different ways. E.g. json, unixtime, isodate They're like a Conversion, but specifically handles transforming from binary to js objects and back. Hence encoding/decoding. | function Codec(src, encode, decode) {
if (src instanceof Codec)
return src;
if (!(this instanceof Codec))
return new Codec(src, code, decode);
src = Object(src, codec_defaults);
this.src = src;
this.encode = encode || identity;
this.decode = decode || identity;
} | [
"encodeData(type, value) {\n return this.getEncoder(type)(value);\n }",
"function srs_publiser_get_codec(\n vcodec, acodec,\n sl_cameras, sl_microphones, sl_vcodec, sl_profile, sl_level, sl_gop, sl_size, sl_fps, sl_bitrate,\n sl_acodec\n) {\n acodec.codec = $(sl_acodec).val();\n acodec.device_code = $(sl_microphones).val();\n acodec.device_name = $(sl_microphones).text();\n \n vcodec.device_code = $(sl_cameras).find(\"option:selected\").val();\n vcodec.device_name = $(sl_cameras).find(\"option:selected\").text();\n \n vcodec.codec = $(sl_vcodec).find(\"option:selected\").val();\n vcodec.profile = $(sl_profile).find(\"option:selected\").val();\n vcodec.level = $(sl_level).find(\"option:selected\").val();\n vcodec.fps = $(sl_fps).find(\"option:selected\").val();\n vcodec.gop = $(sl_gop).find(\"option:selected\").val();\n vcodec.size = $(sl_size).find(\"option:selected\").val();\n vcodec.bitrate = $(sl_bitrate).find(\"option:selected\").val();\n}",
"constructor(name /*: string*/, decoder /*: Decoder<mixed, a>*/) {\n this.name = name\n this.decoder = decoder\n }",
"getEncoder(type) {\n let encoder = this.#encoderCache.get(type);\n if (!encoder) {\n encoder = this.#getEncoder(type);\n this.#encoderCache.set(type, encoder);\n }\n return encoder;\n }",
"_encodeBlob(blob = iCrypto.pRequired(\"_encodeBlob\"),\n encoding = iCrypto.pRequired(\"_encodeBlob\")){\n let self = this;\n if (!this.encoders.hasOwnProperty(encoding)){\n throw \"_encodeBlob: Invalid encoding: \" + encoding;\n }\n return self.encoders[encoding](blob)\n }",
"static encode(domain, types, value) {\n return (0, index_js_4.concat)([\n \"0x1901\",\n TypedDataEncoder.hashDomain(domain),\n TypedDataEncoder.from(types).hash(value)\n ]);\n }",
"static from(types) {\n return new TypedDataEncoder(types);\n }",
"constructor(left /*: Decoder<mixed, a>*/, right /*: Decoder<mixed, b>*/) {\n this.left = left\n this.right = right\n }",
"function decode(content, encoding, decoder = \"text\") {\n if (encoding) {\n content = Buffer.from(content, encoding).toString();\n }\n switch (decoder) {\n case \"json\":\n try {\n return JSON.parse(content);\n } catch (e) {\n return undefined;\n }\n default:\n return content;\n }\n}",
"constructor(index /*: number*/, decoder /*: Decoder<mixed, a>*/) {\n this.index = index\n this.decoder = decoder\n }",
"ConvertAssemblyToTypeLib() {\n\n }",
"serialize(obj) {\n if (!obj.constructor || typeof obj.constructor.encode !== \"function\" || !obj.constructor.$type) {\n throw new Error(\"Object \" + JSON.stringify(obj) +\n \" is not a protobuf object, and hence can't be dynamically serialized. Try passing the object to the \" +\n \"protobuf classes create function.\")\n }\n return Any.create({\n type_url: \"type.googleapis.com/\" + AnySupport.fullNameOf(obj.constructor.$type),\n value: obj.constructor.encode(obj).finish()\n });\n }",
"InitializeEncode(RequestClientInfoClientId, string, string, string) {\n\n }",
"function ReedSolomonEncoder(field){this.field=field;this.cachedGenerators=[];this.cachedGenerators.push(new GenericGFPoly(field,Int32Array.from([1])));}",
"static getConceptMapTargetAsCoding(conceptMap, sourceCode) {\n var _a, _b;\n if (((_a = conceptMap.group) === null || _a === void 0 ? void 0 : _a.length) && conceptMap.group[0].element.length) {\n const conceptMapGroupElement = conceptMap.group[0].element.find(element => element.code === sourceCode);\n if ((_b = conceptMapGroupElement === null || conceptMapGroupElement === void 0 ? void 0 : conceptMapGroupElement.target) === null || _b === void 0 ? void 0 : _b.length) {\n const conceptMapGroupElementTarget = conceptMapGroupElement.target[0];\n return data_type_factory_1.DataTypeFactory.createCoding({\n code: conceptMapGroupElementTarget.code,\n display: conceptMapGroupElementTarget.display,\n system: conceptMap.group[0].target\n }).toJSON();\n }\n else\n return null;\n }\n else\n return null;\n }",
"function mapCode(code) {\n const _source = code._source;\n return {\n organization: _source.organization.organization,\n origin: _source.origin,\n project_name: _source.project_name,\n language: _source.language,\n metrics: _source.metrics,\n updatedAt: _source.updated_at,\n id: code._id,\n };\n}",
"setOutputFileType(fileType) {\n this.outputType = 'audio/' + fileType + '; codecs=opus';\n }",
"function getMessageEncoding( msg )\n{\n\tlet enc = new TextEncoder();\n\treturn enc.encode( msg );\n}",
"encodeType(name) {\n const result = this.#fullTypes.get(name);\n (0, index_js_4.assertArgument)(result, `unknown type: ${JSON.stringify(name)}`, \"name\", name);\n return result;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the sum of the digits of a number. | function getSumOfDigits(num) {
var num = num;
sum = 0;
while (num) {
sum += num % 10;
num = Math.floor(num / 10);
}
return sum;
} | [
"function getDigitsSum(inputNumber) {\n inputNumber += '';\n let sumOfDigits = 0;\n const inputNumberLength = inputNumber.length;\n \n for (let index = 0; index < inputNumberLength; index += 1) {\n sumOfDigits += parseInt(inputNumber[index]);\n }\n \n return sumOfDigits;\n}",
"function digitalSum(n){\n if (n < 10){\n return n;\n }\n return (n % 10) + digitalSum(Math.floor(n / 10));\n}",
"function count_digits(i) /* (i : int) -> int */ {\n return _int_count_digits(i);\n}",
"function sumDigits(a, b) {\n\tconst x = [];\n\tfor (let i = a; i <= b; i++) {\n\t\tx.push(i);\n\t}\n\treturn x.map(x => x.toString().split(\"\")).flat().reduce((x, y) => Number(x) + Number(y));\n}",
"function grabNumberSum(s) {\n\treturn s.replace(/\\D/g, \" \").split(\" \").reduce((x, i) => x + +i, 0);\n}",
"function numOfDigits(n) {\n return n.toString().\n replace(\".\", \"\").\n replace(\"-\", \"\").length\n}",
"function DigitsInArry (number) \n{ \n let arryOfdigits = [];\n while (number !== 0) \n {\n let units = number % 10;\n arryOfdigits.unshift(units);\n number = Math.floor(number / 10)\n }\n return arryOfdigits;\n}",
"function totalDigitRekursif(angka) {\r\n var str = angka.toString()\r\n if(str.length === 1) return Number(str)\r\n return Number(str[0]) + totalDigitRekursif(str.slice(1))\r\n}",
"function NumberAddition(str) { \n//search for all the digits in str (returns an array)\nvar nums = str.match(/(\\d)+/g); \n\nif (!nums) {return 0;} //stop if there are no numbers\nelse {\n //convert array elements to numbers using .map()\n //then add all elements together using .reduce()\n return nums.map(function(element, index, array){\n return +element;\n }).reduce(function(previous, current, index, array){\n return previous + current;\n });\n}\n}",
"function getDigit(num, i) {\n return Math.floor(Math.abs(num) / Math.pow(10, i) % 10);\n}",
"function digitDistance(num1, num2) {\n\tconst a = [];\n\tfor (let i = 0; i < num1.toString().length; i++) {\n\t\ta.push(Math.abs(num1.toString()[i] - num2.toString()[i]));\n\t}\n\treturn a.reduce((x, i) => x + i);\n}",
"function summation(num){\n if (num >= 1) return ( (num * (num + 1)) / 2);\n else return 0;\n }",
"function largest_length(num)\n {\n count = 0;\n while(num > 0)\n {\n num = Math.floor(num/10);\n count++;\n }\n return count;\n }",
"function splitNumber(number){\n\t\n\tvar digits = [];\n\t\n\twhile (number > 0){\n\t\t\n\t\tdigits.push(number % 10);\n\t\tnumber = parseInt(number / 10);\n\t\t\n\t}\n\t\n\tdigits.reverse();\n\treturn digits;\n\n}",
"function CSng(num) {\n var dec=7;\n var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);\n return result;\n}",
"function sumOfSums(numberArray) {\n return numberArray.map(function (number, idx) {\n return numberArray.slice(0, idx + 1).reduce(function (sum, digit) {\n return sum + digit;\n });\n }).reduce(function (sum, partialSum) {\n return sum + partialSum;\n });\n}",
"computeSummation(num){\n if (num >= 1) return ( (num * (num + 1)) / 2);\n else return 0;\n }",
"function INT(x) { return Math.floor(x) }",
"function plusOne(digits) {\n // loop backwards\n\n for(let i = digits.length - 1; i >= 0; i--) {\n if( digits[i] >= 9) {\n digits[i] = 0\n } else {\n digits[i]++;\n return digits;\n }\n }\n\n // now if we had increased a 9 to a 10 then\n // we add one a the beginning of the array\n return [1, ...digits];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
IMGUI_API bool InputInt3(const char label, int v[3], ImGuiInputTextFlags extra_flags = 0); | function InputInt3(label, v, extra_flags = 0) {
const _v = import_Vector3(v);
const ret = bind.InputInt3(label, _v, extra_flags);
export_Vector3(_v, v);
return ret;
} | [
"function InputInt(label, v, step = 1, step_fast = 100, extra_flags = 0) {\r\n const _v = import_Scalar(v);\r\n const ret = bind.InputInt(label, _v, step, step_fast, extra_flags);\r\n export_Scalar(_v, v);\r\n return ret;\r\n }",
"function InputInt2(label, v, extra_flags = 0) {\r\n const _v = import_Vector2(v);\r\n const ret = bind.InputInt2(label, _v, extra_flags);\r\n export_Vector2(_v, v);\r\n return ret;\r\n }",
"function SliderInt3(label, v, v_min, v_max, format = \"%d\") {\r\n const _v = import_Vector3(v);\r\n const ret = bind.SliderInt3(label, _v, v_min, v_max, format);\r\n export_Vector3(_v, v);\r\n return ret;\r\n }",
"function InputInt4(label, v, extra_flags = 0) {\r\n const _v = import_Vector4(v);\r\n const ret = bind.InputInt4(label, _v, extra_flags);\r\n export_Vector4(_v, v);\r\n return ret;\r\n }",
"function InputScalar(label, v, step = null, step_fast = null, format = null, extra_flags = 0) {\r\n if (v instanceof Int8Array) {\r\n return bind.InputScalar(label, ImGuiDataType.S8, v, step, step_fast, format, extra_flags);\r\n }\r\n if (v instanceof Uint8Array) {\r\n return bind.InputScalar(label, ImGuiDataType.U8, v, step, step_fast, format, extra_flags);\r\n }\r\n if (v instanceof Int16Array) {\r\n return bind.InputScalar(label, ImGuiDataType.S16, v, step, step_fast, format, extra_flags);\r\n }\r\n if (v instanceof Uint16Array) {\r\n return bind.InputScalar(label, ImGuiDataType.U16, v, step, step_fast, format, extra_flags);\r\n }\r\n if (v instanceof Int32Array) {\r\n return bind.InputScalar(label, ImGuiDataType.S32, v, step, step_fast, format, extra_flags);\r\n }\r\n if (v instanceof Uint32Array) {\r\n return bind.InputScalar(label, ImGuiDataType.U32, v, step, step_fast, format, extra_flags);\r\n }\r\n // if (v instanceof Int64Array) { return bind.InputScalar(label, ImGuiDataType.S64, v, step, step_fast, format, extra_flags); }\r\n // if (v instanceof Uint64Array) { return bind.InputScalar(label, ImGuiDataType.U64, v, step, step_fast, format, extra_flags); }\r\n if (v instanceof Float32Array) {\r\n return bind.InputScalar(label, ImGuiDataType.Float, v, step, step_fast, format, extra_flags);\r\n }\r\n if (v instanceof Float64Array) {\r\n return bind.InputScalar(label, ImGuiDataType.Double, v, step, step_fast, format, extra_flags);\r\n }\r\n throw new Error();\r\n }",
"function DragInt3(label, v, v_speed = 1.0, v_min = 0, v_max = 0, format = \"%d\") {\r\n const _v = import_Vector3(v);\r\n const ret = bind.DragInt3(label, _v, v_speed, v_min, v_max, format);\r\n export_Vector3(_v, v);\r\n return ret;\r\n }",
"function InputFloat3(label, v, format = \"%.3f\", extra_flags = 0) {\r\n const _v = import_Vector3(v);\r\n const ret = bind.InputFloat3(label, _v, format, extra_flags);\r\n export_Vector3(_v, v);\r\n return ret;\r\n }",
"function w3_input(psa, label, path, val, cb, placeholder)\n{\n\tvar id = path? ('id-'+ path) : '';\n\tcb = cb || '';\n\tvar phold = placeholder? (' placeholder=\"'+ placeholder +'\"') : '';\n\tvar onchange = path? (' onchange=\"w3_input_change('+ sq(path) +', '+ sq(cb) +')\" onkeydown=\"w3int_input_key(event, '+ sq(path) +', '+ sq(cb) +')\"') : '';\n\tvar val = ' value='+ dq(w3_esc_dq(val) || '');\n\tvar inline = psa.includes('w3-label-inline');\n\tvar bold = !psa.includes('w3-label-not-bold');\n\tvar spacing = (label != '' && inline)? ' w3int-margin-input' : '';\n\n\t// type=\"password\" in no good because it forces the submit to be https which we don't support\n\tvar type = 'type='+ (psa.includes('w3-password')? '\"password\"' : '\"text\"');\n\n var psa3 = w3_psa3(psa);\n var psa_outer = w3_psa(psa3.left, inline? 'w3-show-inline-new':'');\n var psa_label = w3_psa_mix(psa3.middle, (label != '' && bold)? 'w3-bold':'');\n\tvar psa_inner = w3_psa(psa3.right, 'w3-input w3-border w3-hover-shadow '+ id + spacing, '', type + phold);\n\n\tvar s =\n\t '<div '+ psa_outer +'>' +\n w3_label(psa_label, label, path) +\n\t\t // NB: include id in an id= for benefit of keyboard shortcut field detection\n '<input id='+ dq(id) +' '+ psa_inner + val + onchange +'>' +\n '</div>';\n\t//if (path == 'Title') console.log(s);\n\t//w3int_input_set_id(id);\n\treturn s;\n}",
"function GetInputValue(inputV , row , col) {\r\n mat [row] [col] = parseInt(inputV); \r\n}",
"function VSliderInt(label, size, v, v_min, v_max, format = \"%d\") {\r\n const _v = import_Scalar(v);\r\n const ret = bind.VSliderInt(label, size, _v, v_min, v_max, format);\r\n export_Scalar(_v, v);\r\n return ret;\r\n }",
"function InputText(label, buf, buf_size = buf instanceof ImStringBuffer ? buf.size : ImGuiInputTextDefaultSize, flags = 0, callback = null, user_data = null) {\r\n const _callback = callback && ((data) => callback(new ImGuiInputTextCallbackData(data, user_data))) || null;\r\n if (Array.isArray(buf)) {\r\n return bind.InputText(label, buf, buf_size, flags, _callback, null);\r\n }\r\n else if (buf instanceof ImStringBuffer) {\r\n const ref_buf = [buf.buffer];\r\n const _buf_size = Math.min(buf_size, buf.size);\r\n const ret = bind.InputText(label, ref_buf, _buf_size, flags, _callback, null);\r\n buf.buffer = ref_buf[0];\r\n return ret;\r\n }\r\n else {\r\n const ref_buf = [buf()];\r\n const ret = bind.InputText(label, ref_buf, buf_size, flags, _callback, null);\r\n buf(ref_buf[0]);\r\n return ret;\r\n }\r\n }",
"function input(event_type) {\r\n\tinput_keyboard_options_with_one_state(0, event_type, \"lowercase_alphabet\"); //virtual_keyboard option 0; alphabet\r\n\tinput_keyboard_options_with_two_states(1, event_type, \"lowercase_accent_characters_one\", 8, 9); //virtual_keyboard option 1; accent characters one\r\n\tinput_keyboard_options_with_two_states(2, event_type, \"lowercase_accent_characters_two\", 10, 11); //virtual_keyboard option 2; accent characters two\r\n\tinput_keyboard_options_with_one_state(3, event_type, \"lowercase_accent_characters_three\"); //virtual_keyboard option 3; accent characters three\r\n\tinput_keyboard_options_with_one_state(4, event_type, \"lowercase_accent_characters_four\"); //virtual_keyboard option 4; accent characters four\r\n\tinput_keyboard_options_with_two_states(5, event_type, \"punctuation_numbers_one\", 4, 5); //virtual_keyboard option 5; punctuation and numbers\r\n\tinput_keyboard_options_with_two_states(6, event_type, \"punctuation_numbers_two\", 6, 7); //virtual_keyboard option 6; punctuation\r\n\r\n\tinput_editing_keys(7, event_type, delete_function, \"Delete\"); //delete \r\n\tinput_character_keys(8, event_type, 0, \"KeyQ\") //q (113), Q (81), 1 (49)\r\n\tinput_character_keys(9, event_type, 1, \"KeyW\"); //w (119), W (87), 2 (50)\r\n\tinput_character_keys(10, event_type, 2, \"KeyE\"); //e (101), E (69), 3 (51)\r\n\tinput_character_keys(11, event_type, 3, \"KeyR\"); //r (114), R (82), 4 (52)\r\n\tinput_character_keys(12, event_type, 4, \"KeyT\"); //t (116), T (84), 5 (53)\r\n\tinput_character_keys(13, event_type, 5, \"KeyY\"); //y (121), Y (89), 6 (54)\r\n\tinput_character_keys(14, event_type, 6, \"KeyU\"); //u (117), U (85), 7 (55)\r\n\tinput_character_keys(15, event_type, 7, \"KeyI\"); //i (105), I (73), 8 (56)\r\n\tinput_character_keys(16, event_type, 8, \"KeyO\"); //o (111), O (79), 9 (57)\r\n\tinput_character_keys(17, event_type, 9, \"KeyP\"); //p (112), P (80), 0 (48)\r\n\tinput_editing_keys(18, event_type, backspace_function, \"Backspace\") //backspace\r\n\t\r\n\tinput_whitespace_keys(19, event_type, 9, \"Tab\"); //horizonal tab (9)\r\n\tinput_character_keys(20, event_type, 10, \"KeyA\"); //a (97), A (65), @ (64)\r\n\tinput_character_keys(21, event_type, 11, \"KeyS\"); //s (115), S (83), # (35)\r\n\tinput_character_keys(22, event_type, 12, \"KeyD\"); //d (100), D (68), $ (36)\r\n\tinput_character_keys(23, event_type, 13, \"KeyF\"); //f (102), F (70), & (38)\r\n\tinput_character_keys(24, event_type, 14, \"KeyG\"); //g (103), G (71), * (42)\r\n\tinput_character_keys(25, event_type, 15, \"KeyH\"); //h (104), H (72), ( (40)\r\n\tinput_character_keys(26, event_type, 16, \"KeyJ\"); //j (106), J (74), ) (41)\r\n\tinput_character_keys(27, event_type, 17, \"KeyK\"); //k (107), K (75),' (39)\r\n\tinput_character_keys(28, event_type, 18, \"KeyL\"); //l (108), L (76), \" (34)\r\n\tinput_whitespace_keys(29, event_type, 13, \"Enter\") //enter (13)\r\n\r\n\tinput_caps_lock(30, event_type, 0, 1, 2, 3, \"CapsLock\"); //left caps lock\r\n\tinput_character_keys(31, event_type, 19, \"KeyZ\"); //z (122), Z (90), % (37)\r\n\tinput_character_keys(32, event_type, 20, \"KeyX\"); //x (120), X (88), - (45)\r\n\tinput_character_keys(33, event_type, 21, \"KeyC\"); //c (99), C (67), + (43)\r\n\tinput_character_keys(34, event_type, 22, \"KeyV\"); //v (118), V (86), = (61)\r\n\tinput_character_keys(35, event_type, 23, \"KeyB\"); //b (98), B (66), / (47)\r\n\tinput_character_keys(36, event_type, 24, \"KeyN\"); //n (110), N (78), semicolon (59)\r\n\tinput_character_keys(37, event_type, 25, \"KeyM\"); //m (109), M (77), colon (59)\r\n\tinput_character_keys(38, event_type, 26, \"Comma\"); //comma (44), exclamtion mark (33)\r\n\tinput_character_keys(39, event_type, 27, \"Period\"); //full stop (46), question mark (63)\r\n\tinput_caps_lock(40, event_type, 0, 1, 2, 3, \"CapsLock\"); //right caps lock\r\n\r\n\tinput_keyboard_options_with_two_states(41, event_type, \"punctuation_numbers_one\", 4, 5); // punctuation numbers \r\n\tinput_keyboard_options_with_two_states(42, event_type, \"punctuation_numbers_two\", 6, 7);//punctuation 2\r\n\tinput_whitespace_keys(43, event_type, 32, \"Space\"); //space (32)\r\n\tinput_keyboard_options_with_two_states(44, event_type, \"lowercase_accent_characters_one\", 8, 9); //accent chars\r\n\tinput_keyboard_options_with_two_states(45, event_type, \"lowercase_accent_characters_two\", 10, 11); //accent chars 2\t\r\n}",
"Draw(label = \"Filter (inc,-exc)\", width = 0.0) {\r\n if (width !== 0.0)\r\n bind.PushItemWidth(width);\r\n const value_changed = InputText(label, this.InputBuf, IM_ARRAYSIZE(this.InputBuf));\r\n if (width !== 0.0)\r\n bind.PopItemWidth();\r\n if (value_changed)\r\n this.Build();\r\n return value_changed;\r\n }",
"function inputValue() {\n //*1 Get clicked numpad value\n const value = getNumpadValue();\n\n //*2 if a digit has been clicked\n if (value !== 0 && !isNaN(value)) {\n setCellValue(value);\n } else if (value === \"clear\") {\n setCellValue(\"\");\n } else return;\n resetNumpad();\n}",
"function SliderInt2(label, v, v_min, v_max, format = \"%d\") {\r\n const _v = import_Vector2(v);\r\n const ret = bind.SliderInt2(label, _v, v_min, v_max, format);\r\n export_Vector2(_v, v);\r\n return ret;\r\n }",
"function inputvalue(){\n return input.value\n}",
"function sliderInputListener(event) {\n if (event.target.id === 'row-slider') {\n rowOutput.innerText = event.target.value;\n num_rows = event.target.valueAsNumber;\n }\n if (event.target.id === 'col-slider') {\n colOutput.innerText = event.target.value;\n num_cols = event.target.valueAsNumber;\n }\n newGame();\n}",
"function SliderFloat3(label, v, v_min, v_max, format = \"%.3f\", power = 1.0) {\r\n const _v = import_Vector3(v);\r\n const ret = bind.SliderFloat3(label, _v, v_min, v_max, format, power);\r\n export_Vector3(_v, v);\r\n return ret;\r\n }",
"function InputTextWithHint(label, hint, buf, buf_size = buf instanceof ImStringBuffer ? buf.size : ImGuiInputTextDefaultSize, flags = 0, callback = null, user_data = null) {\r\n const _callback = callback && ((data) => callback(new ImGuiInputTextCallbackData(data, user_data))) || null;\r\n if (Array.isArray(buf)) {\r\n return bind.InputTextWithHint(label, hint, buf, buf_size, flags, _callback, null);\r\n }\r\n else if (buf instanceof ImStringBuffer) {\r\n const ref_buf = [buf.buffer];\r\n const _buf_size = Math.min(buf_size, buf.size);\r\n const ret = bind.InputTextWithHint(label, hint, ref_buf, _buf_size, flags, _callback, null);\r\n buf.buffer = ref_buf[0];\r\n return ret;\r\n }\r\n else {\r\n const ref_buf = [buf()];\r\n const ret = bind.InputTextWithHint(label, hint, ref_buf, buf_size, flags, _callback, null);\r\n buf(ref_buf[0]);\r\n return ret;\r\n }\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if a survey cookie exists. Call optionally with a type. | function CookieUtilities_surveyCookieExists(cookieType)
{
var t = '';
if (cookieType) t = cookieType;
return (document.cookie.indexOf(SiteRecruit_Config.cookieName + '=' + t) != -1)
} | [
"function userHasConsented() {\n return typeof Cookies.get(\"cookieConsent\") !== \"undefined\";\n}",
"function cookieExists() {\n return typeof $.cookie(cookie) !== 'undefined';\n }",
"function cookieExists() {\n if (typeof $.cookie('accessToken') === 'undefined') {\n return false;\n }\n return true;\n }",
"function getCheckCookie() {\r\n\treturn $.cookies.test();\r\n}",
"function noCookieFound()\n{\n\treturn document.cookie == \"\" || document.cookie == null;\n}",
"isNewUserCheck() {\n let userCookie = this.helper.getCookieInfo('userName');\n\n // If cookie exists, it means that user visited site earlier.\n if (userCookie.cookieExists) {\n this.userCookie = userCookie.value;\n }\n\n return !userCookie.cookieExists;\n }",
"_typeExists(name) {\n\t\tlet self = this;\n\t\tif (_.isString(name) && self._cache.types.hasOwnProperty(name)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn do_select(self, NoPg.Type, name).then(function(types) {\n\t\t\treturn (types.length >= 1) ? true : false;\n\t\t});\n\t}",
"function testPersistentCookie () {\nwritePersistentCookie (\"testPersistentCookie\", \"Enabled\", \"minutes\", 1);\nif (getCookieValue (\"testPersistentCookie\")==\"Enabled\")\nreturn true \nelse \nreturn false;\n}",
"function isValideNationalCookie()\n{\n\tvar result = false;\n\tvar aaacookie = getCookieValue('zipcode');\n\tvar AAA_IDX = 1;\n\tvar NAT_ZIP_IDX = 0;\n\t\n\tif (aaacookie != null)\n\t{\n\t\tvar cookieparts = aaacookie.split('|');\n\t\t\n\t\tif (cookieparts != null && cookieparts.length == 3)\n\t\t{\n\t\t\tresult = ((cookieparts[NAT_ZIP_IDX].length == 5) && (cookieparts[AAA_IDX] == 'AAA'));\n\t\t}//if (parts != null && parts.length > 0)\n\t}//if (acecookie != null)\n\t\n\treturn result;\n\t\n}//function isValideNationalCookie(",
"function cookieFileExists() {\n log(\"cookie file exists.\");\n storage.readFile(COOKIE_FILE_NAME, function(filedata) {\n var data;\n function bailOut() {\n log(\"cookie file is not valid.\");\n storage.killFile(COOKIE_FILE_NAME, initiateHandshake);\n }\n try {data = JSON.parse(filedata);}\n catch (e) {return bailOut();}\n if (!data) return bailOut();\n if (!('expires' in data)) return bailOut();\n if (data.expires < myClock.originalClock()) return bailOut();\n token = data;\n haveToken();\n });\n }",
"function CookieUtilities_getSurveyCookie()\n {\n return this.getCookieValue(SiteRecruit_Config.cookieName);\n }",
"isValidType() {\n return Menu.getPizzaTypesSet().has(this.type.toLowerCase());\n }",
"function hasForm(atypes) {\n var hasQuanti = false;\n var hasQuali = false; \n \n //set hasQuanti/hasQuali truth value depending on atypes entries\n for(i = 0; i < atypes.length; i++) {\n if(atypes[i] === '1') hasQuanti = true;\n else if (atypes[i] === '2') hasQuali = true;\n }\n \n if(hasQuali && hasQuanti) return 3; //if atypes array has quali(2) and quanti(1), return 3\n else if(hasQuali) return 2; //else if atypes array has quali(2) only, return 2\n else if(hasQuanti) return 1; //else if atypes array has quanti(1) only, return 1\n else return null;\n}",
"function objectExists(type, id) {\n\tif (!metaData.hasOwnProperty(type)) return false;\n\t\n\tfor (var obj of metaData[type]) {\n\t\tif (obj && obj.hasOwnProperty(\"id\") && obj.id === id) return true;\n\t}\n\t\n\treturn false;\n}",
"function isFavorite(story) {\n // start with an empty set of favorite story ids\n let favoriteStoryIds = new Set();\n\n if (currentUser) {\n favoriteStoryIds = new Set(\n currentUser.favorites.map((story) => story.storyId)\n );\n }\n isFave = favoriteStoryIds.has(story.storyId);\n // return true or false\n return isFave;\n }",
"async function hasSessionSet(netid) {\n return new Promise((resolve, reject) => {\n sessionStore.all(function (err, sessions) {\n if (err) {\n console.error(err)\n reject(err);\n }\n\n // iterate over session id -> sess mapping\n for (const [_sid, sess] of Object.entries(sessions)) {\n if (sess.netid == netid) {\n resolve(true)\n }\n }\n resolve(false)\n });\n });\n}",
"function questionPresent(uid,id){\n let found = false\n questions.forEach(function (question){\n if (question.id === id && question.uid === uid){\n found = true;\n }\n })\n return found;\n}",
"function domainCheck(domain){\n\t\t// if it is, proceed\n\t\tif (domain.substring(0, 20) == \"http://www.quora.com\"){\n\t\t\tconsole.log(domain);\n\t\t\t$(\"#ifNotQuora\").hide();\n\t\t\t$(\"#ifQuora\").show();\n\t\t}\t\t\n\t\t// otherwise, this is not Quora. Show a link when the extension opens\n\t\telse {\n\t\t\t$(\"#ifNotQuora\").show();\n\t\t\t$(\"#ifQuora\").hide();\n\t\t\t// activate Go to Quora button\n\t\t\t$('#go-to-quora').click(function() {\n\t\t\t\t\tchrome.tabs.create({url: \"http://www.quora.com/\", active:true});\n\t\t\t\t\tconsole.log(\"new tab\");\n\t\t\t\t\twindow.close();\n\t\t\t});\n\t\t}\n\t}// end of domainCheck()",
"function initializeCookieBanner() {\n let isCookieAccepted = localStorage.getItem(\"cc_isCookieAccepted\");\n if (isCookieAccepted === null) {\n localStorage.clear();\n localStorage.setItem(\"cc_isCookieAccepted\", \"false\");\n showCookieBanner();\n }\n if (isCookieAccepted === \"false\") {\n showCookieBanner();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders three lines of texts to indicate the study status. | function setStatusText(text1, text2, text3) {
svg.select(".studyStatusText1").text(text1);
svg.select(".studyStatusText2").text(text2);
svg.select(".studyStatusText3").text(text3);
} | [
"function changeStatus() {\n var text = \"Time Range Bar: <b>\" + boolToOnOff(mainfocus)\n + \"</b>, Time Range Filter: <b>\" + boolToOnOff(timeBarFilter)\n + \"</b>, Normalised: <b>\" + boolToOnOff(isMainNormalised)\n + \"</b>, Night Mode: <b>\" + boolToOnOff(backgroundcolour)\n + \"</b>, High Quality: <b>\" + boolToOnOff((d3.select('#' + 'fancyvis').property('className').indexOf('btn-info') >= 0));\n if (mainfocus) text += \"</b>, Year Range: <b>\" + timeBarIndexes[0] + ':' + timeBarIndexes[1];\n d3.select(\"#\" + 'mainstatus').attr('text-anchor', 'middle').html(text);\n}",
"#setBioStatisticsAndStyle() {\n\n this.#stats.totalBioLines = this.#bioLines.length;\n\n if (this.#stats.bioIsMarkedUnsourced) {\n this.#messages.sectionMessages.push('Profile is marked unsourced');\n }\n if (this.#stats.bioIsUndated) {\n this.#messages.sectionMessages.push('Profile has no dates');\n this.#style.bioHasStyleIssues = true;\n }\n if (this.#style.bioCategoryNotAtStart) {\n this.#messages.styleMessages.push('Category not at start of biography');\n this.#style.bioHasStyleIssues = true;\n }\n if (this.#biographyIndex < 0) {\n this.#style.bioHasStyleIssues = true;\n this.#style.bioIsMissingBiographyHeading = true;\n this.#messages.sectionMessages.push('Missing Biography heading');\n } else {\n if (this.#unexpectedLines.length > 0) {\n this.#style.bioHasStyleIssues = true;\n this.#style.bioHasNonCategoryTextBeforeBiographyHeading = true; \n let i = 0;\n while (i < this.#unexpectedLines.length) {\n this.#messages.styleMessages.push('Unexpected line before Biography ' + this.#unexpectedLines[i]);\n i++\n if (i > 5) {\n i = this.#unexpectedLines.length + 1;\n this.#messages.styleMessages.push('Unexpected line ... more lines follow ...');\n }\n }\n }\n }\n if (this.#sourcesIndex < 0) {\n this.#style.bioHasStyleIssues = true;\n this.#style.bioIsMissingSourcesHeading = true;\n this.#messages.sectionMessages.push('Missing Sources heading');\n }\n if (this.#referencesIndex < 0) {\n this.#style.bioHasStyleIssues = true;\n this.#style.bioIsMissingReferencesTag = true;\n this.#messages.sectionMessages.push('Missing <references /> tag');\n }\n if (this.#style.bioHasMultipleReferencesTags) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.sectionMessages.push('Multiple <references /> tag');\n }\n if (this.#style.misplacedLineCount < 0) {\n this.#style.misplacedLineCount = 0;\n }\n if (this.#style.misplacedLineCount > 0) {\n this.#style.bioHasStyleIssues = true;\n let msg = this.#style.misplacedLineCount + ' line';\n if (this.#style.misplacedLineCount > 1) {\n msg += 's';\n }\n msg += ' between Sources and <references />';\n this.#messages.sectionMessages.push(msg);\n }\n this.#stats.inlineReferencesCount = this.#refStringList.length + this.#namedRefStringList.length;\n\n this.#stats.possibleSourcesLineCount = this.#acknowledgementsIndex - 1;\n if (this.#stats.possibleSourcesLineCount < 0) {\n this.#stats.possibleSourcesLineCount = this.#bioLines.length;\n }\n this.#stats.possibleSourcesLineCount =\n this.#stats.possibleSourcesLineCount - this.#referencesIndex + 1 +\n this.#style.misplacedLineCount;\n\n if (this.#style.hasRefWithoutEnd) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.sectionMessages.push('Inline <ref> tag with no ending </ref> tag');\n }\n if (this.#style.bioHasRefAfterReferences) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.sectionMessages.push('Inline <ref> tag after <references >');\n }\n if (this.#style.bioHasSpanWithoutEndingSpan) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.sectionMessages.push('Span with no ending span');\n }\n if (this.#style.bioHasMultipleBioHeadings) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.sectionMessages.push('Multiple Biography headings');\n }\n if (this.#style.bioHeadingWithNoLinesFollowing) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.styleMessages.push('Empty Biography section');\n }\n if (this.#style.bioHasMultipleSourceHeadings) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.sectionMessages.push('Multiple Sources headings');\n }\n if (this.#style.sourcesHeadingHasExtraEqual) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.sectionMessages.push('Sources subsection instead of section');\n }\n if (this.#style.bioHasUnknownSectionHeadings) {\n this.#style.bioHasStyleIssues = true;\n for (let i=0; i < this.#wrongLevelHeadings.length; i++) {\n let str = this.#wrongLevelHeadings[i];\n if (str.length > 60) {\n str = str.substring(0, 60) + \"...\";\n }\n this.#messages.styleMessages.push('Wrong level heading == ' + str + ' ==');\n }\n }\n if (this.#style.acknowledgementsHeadingHasExtraEqual) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.sectionMessages.push('Acknowledgements subsection instead of section');\n }\n if (this.#style.bioHasAcknowledgementsBeforeSources) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.sectionMessages.push('Acknowledgements before Sources');\n }\n if (this.#style.advanceDirectiveHeadingHasExtraEqual) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.sectionMessages.push('Advance Directive subsection instead of section');\n }\n if (this.#style.bioHasSectionAfterAdvanceDirective) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.sectionMessages.push('Advance Directive is not at end of profile'); \n }\n if (this.#style.advanceDirectiveOnNonMemberProfile) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.styleMessages.push('Advance Directive on a non member profile');\n }\n\n if (this.#style.bioMissingResearchNoteBox) {\n this.#style.bioHasStyleIssues = true;\n for (let i=0; i < this.#missingRnb.length; i++) {\n this.#messages.styleMessages.push('Missing Research Note box for: ' + this.#missingRnb[i]);\n }\n }\n if (this.#style.bioMightHaveEmail) {\n this.#style.bioHasStyleIssues = true;\n this.#messages.styleMessages.push('Biography may contain email address');\n }\n }",
"#statusContent() {\n var driverID = this.serverKey + '_driver';\n var stateID = this.serverKey + '_state';\n var experimentID = this.serverKey + '_experiment';\n var numCompletedID = this.serverKey + '_numCompleted';\n var numQueuedID = this.serverKey + '_numQueued';\n var dateTimeID = this.serverKey + '_dateTime';\n var topContent = '<p>Driver: <span id=\"'+driverID+'\">[driver name]</span> | Queue State: <span id=\"'+stateID+'\">[state]</span> | Experiment: <span id=\"'+experimentID+'\">[experiment]</span> | Completed: <span id=\"'+numCompletedID+'\">[#]</span> | Queue: <span id=\"'+numQueuedID+'\">[#]</span> | Time: <span id=\"'+dateTimeID+'\">[time] [date]</span></p>';\n\n var driverStatusID = this.serverKey + '_driverStatus';\n var bottomContent = '<p><span id=\"'+driverStatusID+'\"></span></p>';\n var content = topContent + '<hr>' + bottomContent;\n\n return content;\n }",
"function appendStatus(text) {\n var status = document.getElementById('status');\n status.innerHTML += text + '<br>';\n}",
"function prepareText(section) {\r\n for (let i = 0; i < heirarchy.tree[0].sections.length; i++) {\r\n d3.select(\"#text_container\").append(\"div\")\r\n .attr(\"id\", \"text-h1-\" + i)\r\n .attr(\"class\", \"text-h1\")\r\n .style(\"display\", \"none\")\r\n .html(heirarchy.tree[0].sections[i].text);\r\n }\r\n d3.select(\"#text-h1-\" + section.split(\".\")[1]).style(\"display\", \"block\");\r\n\r\n refreshHighlightTip();\r\n setupTooltips();\r\n\r\n}",
"function success(text){\n return SUCCESS_COLOUR + BRIGHT + 'Complete! : ' + RESET_COLOUR + SUCCESS_COLOUR + text + RESET_COLOUR;\n}",
"function countTexts(frameX, objectStyle) {\r\n if(objectStyle === \"National Title\") {\r\n totalST++;\r\n panelST++;\r\n\r\n } else if(objectStyle === \"Veterans Title\") {\r\n totalTT++;\r\n panelTT++;\r\n }\r\n}",
"function TfLLineStatusList(props) {\n const lines = props.lineStatuses;\n const lineStatusItems = lines.map((status, index) =>\n <div key={index}>\n <h4>{status.statusSeverityDescription}</h4>\n <p>{status.reason}</p>\n <hr/>\n </div>\n );\n\n return (\n <ListGroup>{lineStatusItems}</ListGroup>\n );\n}",
"renderSaveSuccessful()\n\t{\n\n\t\tif(this.state.isSaveSuccessful)\n\t\t{\n\n\t\t\treturn(<Message positive>\n\t\t\t\t\t\t<Message.Header>Successfully added an edit to the corpus!</Message.Header>\n\t\t\t\t </Message>)\n\n\t\t}\n\n\t}",
"function setDisplayText() {\n if (totalNumberOfGames <= numberOfGamesFetched) {\n footerViewText.setText(Alloy.Globals.PHRASES.showningMatchesTxt + ': ' + totalNumberOfGames + '/' + totalNumberOfGames + \" \");\n } else {\n footerViewText.setText(Alloy.Globals.PHRASES.showningMatchesTxt + ': ' + numberOfGamesFetched + '/' + totalNumberOfGames + \" \");\n }\n}",
"displayDificalty(diff) {\n difficulty = diff;\n textSize(15);\n if (difficulty == 5) {\n text(\"Inside joke:\", 19, 273);\n } else if (difficulty == 4) {\n text(\"Phrase:\", 19, 273);\n\n } else if (difficulty == 2) {\n text(\"Moderate phrase:\", 19, 273);\n\n } else if (difficulty == 3) {\n text(\"Hard phrase:\", 19, 273);\n\n } else if (difficulty == 1) {\n text(\"Easy phrase:\", 19, 273);\n } else {\n text(\"Your phrase:\", 19, 273);\n }\n }",
"draw_ready_message() {\r\n\r\n if (this.game_data.message_count > 0) {\r\n\r\n this.data.game.set_text_font('30pt Impact');\r\n this.data.game.set_text_color('#ffffff');\r\n //this.data.game.text_write(self.game_data.message, 200, 444); \r\n this.data.game.text_write('Ready!', 330, 414); \r\n this.game_data.message_count --;\r\n \r\n }\r\n }",
"renderStatus (options) {\n\t\treturn Utils.renderReviewStatus(options);\n\t}",
"function writeTextview(article_title, ocr_text) {\n\t// Replace HTML entities\n\tvar article_text = ocr_text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\t// Replace line feeds\n\tarticle_text = article_text.replace(/\\n\\n/g, \"</br></br>\");\n\n\tdojo.byId(\"record_text\").innerHTML = \"<h1>\" + article_title + \"</h1><p id='article-text'>\" + wrapWords(article_text) + \"</p>\";\n\taddTooltips();\n}",
"function displayText(message) {\n push();\n fill(255);\n textSize(32);\n textAlign(CENTER, CENTER);\n text(message, width / 2, height / 2);\n pop();\n}",
"function summaryLinkedContentWording()\n{\n var linked = '';\n var isSurvey = getOlasConfigValue('linkedType') == 'SV';\n \n // linked survey wording\n if( isSurvey )\n linked = congratulationHeader = congratulationLinkedSurveyHeader;\n \n // linked assessment wording\n else\n linked = congratulationHeader = congratulationLinkedAssessmentHeader;\n \n linked = linked.toLowerCase();\n endButton.text = endButton.label = endMessageAssessment.replace( /%linked%/g, linked );\n congratulationText = congratulationLinkedAssessmentText.replace( /%linked%/g, linked );\n \n return isSurvey; \n}",
"status(title, status) {\n const statusString = status === false ? symbols.error : symbols.success;\n console.log(Log.fill(`\n [${chalk.yellow(title)}] [FILL] [${statusString}]\n `));\n }",
"function displayInstructions() {\n textAlign(CENTER);\n textSize(12);\n textFont('Georgia');\n \n fill(\"white\");\n text(\"DIG FOR TREASURE! PRESS 'T' TO SWITCH TOOLS - FIND ALL TREASURE BEFORE YOU RUN OUT OF ENERGY\", width/2, height - 30);\n}",
"renderNoStudentsInfo() {\n return `<div class=\"sak-banner-info\">${this.tr(\"no_student_info\")}</div>`;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`_readBaseIRI` reads the IRI of a base declaration | _readBaseIRI(token) {
const iri = token.type === 'IRI' && this._resolveIRI(token.value);
if (!iri)
return this._error('Expected valid IRI to follow base declaration', token);
this._setBase(iri);
return this._readDeclarationPunctuation;
} | [
"_readBaseIRI(token) {\n const iri = token.type === 'IRI' && this._resolveIRI(token.value);\n\n if (!iri) return this._error('Expected valid IRI to follow base declaration', token);\n\n this._setBase(iri);\n\n return this._readDeclarationPunctuation;\n }",
"_setBase(baseIRI) {\n if (!baseIRI) {\n this._base = '';\n this._basePath = '';\n }\n else {\n // Remove fragment if present\n const fragmentPos = baseIRI.indexOf('#');\n if (fragmentPos >= 0)\n baseIRI = baseIRI.substr(0, fragmentPos);\n // Set base IRI and its components\n this._base = baseIRI;\n this._basePath = baseIRI.indexOf('/') < 0 ? baseIRI :\n baseIRI.replace(/[^\\/?]*(?:\\?.*)?$/, '');\n baseIRI = baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\\/\\/[^\\/]*)?/i);\n this._baseRoot = baseIRI[0];\n this._baseScheme = baseIRI[1];\n }\n }",
"function IRIReference(iri) {\n IRI.call(this);\n /*\n * IRIREF is defined here:\n * http://www.w3.org/TR/2013/REC-sparql11-query-20130321/#rIRIREF\n */\n if (!/^[^<>\"{}|^`\\\\\\u0000-\\u0020]*$/.test(iri)) {\n throw new Error('Invalid IRI: ' + iri);\n }\n this.iri = iri;\n}",
"parse_base_expr() {\n let values = [];\n let done = false;\n while(this.peek() != tk.EOF && !done){\n let sym = this.peek();\n switch (sym.symbol) {\n case tk.LITERAL:\n values.push(this.advance());\n break;\n case tk.NUMBER:\n values.push(this.parse_number());\n break;\n case tk.HASH:\n case tk.AT:\n case tk.DOLLAR:\n values.push(this.parse_rvalue());\n break;\n case tk.BANG:\n values.push(this.parse_function_expr());\n break;\n case tk.EQUALS:\n this.error(\"Found an unexpected character in base expression (are you missing a semicolon?) \");\n done = true;\n break;\n default:\n done = true;\n break;\n }\n }\n if(values.length == 0){\n this.error(\"Base expression not found\");\n }\n return Ex(pr.Base, values);\n }",
"function getBookBase(auction){\n let lore = auction.item_lore;\n let base_name = lore.split(\"\\n\")[0]; //Take the first line of the item lore\n base_name = base_name.replace(/(§.)+/,''); //removes all incidences of color codes\n \n return base_name;\n}",
"_readPrefixIRI(token) {\n if (token.type !== 'IRI') return this._error(`Expected IRI to follow prefix \"${this._prefix}:\"`, token);\n\n const prefixNode = this._readEntity(token);\n\n this._prefixes[this._prefix] = prefixNode.value;\n\n this._prefixCallback(this._prefix, prefixNode);\n\n return this._readDeclarationPunctuation;\n }",
"function getBaseItem(item_name,auction){\n let tiers = baseItems.tiers;\n let reforges = baseItems.reforges;\n let bases = baseItems.bases;\n\n //Step 0: If this is an enchanted book, handle it with getBookBase()\n if(item_name === \"Enchanted Book\"){\n return getBookBase(auction);\n }\n\n let curr_name = item_name;\n //Step 1: Change format of stars so that they can be processed without removing or ignoring them\n curr_name = convertStars(curr_name);\n \n //Step 2: Remove Tiers from Perfect Armor (i.e. Perfect Armor - Tier IV)\n for(let i = 0; i<tiers.length; i++){\n curr_name = curr_name.replace(tiers[i],\"\");\n }\n\n //Step 3: Remove reforges left to right, comparing the item against the valid bases at each iteration.\n //There exist valid base item names that contain words used in reforges, which is why this is necessary.\n let old_name = \"\";\n while(old_name != curr_name){\n old_name = curr_name;\n for(let i = 0; i<reforges.length; i++){\n let short = curr_name.replace(reforges[i],\"\").trim();\n if(short != curr_name){\n if(bases.includes(short)){\n return curr_name;\n }\n else{\n curr_name = short;\n }\n }\n }\n }\n return curr_name;\n }",
"function urnTypeAndName(urn) {\n const parts = urn.split(\"::\");\n const typeParts = parts[2].split(\"$\");\n return {\n name: parts[3],\n type: typeParts[typeParts.length - 1],\n };\n}",
"static get __resourceType() {\n\t\treturn 'DocumentReference';\n\t}",
"async getSchemaModelBase() {\n if (this.useModelAsBase && this.isNewFile) {\n const modelFilesFullPath = await getFilePathToAllFilesInDir(this.ctx.modelDir);\n const modelFileNames = modelFilesFullPath.map((item) => item.replace(this.ctx.modelDir, ''));\n let matchInput;\n if (this.options.name) {\n matchInput = modelFileNames.find((item) => {\n const name = item.replace('.js', '').replace('/', '');\n if (this.options.name === name) {\n return true;\n }\n return false;\n });\n }\n const ask = {\n type: 'list',\n name: 'baseModel',\n message: 'What model to base schema on?',\n choices: modelFileNames,\n };\n\n if (matchInput) {\n ask.default = matchInput;\n }\n\n this.modelAsk = await this.prompt([ask]);\n this.modelBasePath = path.join(this.ctx.modelDir, this.modelAsk.baseModel);\n }\n }",
"function resolveType(aResource,RDF,BMDS)\n{\n\tvar type = getProperty(aResource,\"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\",RDF,BMDS);\n\tif (type != \"\")\n\t\ttype = type.split(\"#\")[1];\n\n\tif (type==\"\")\n\t\ttype=\"Immutable\";\n\treturn type;\n}",
"function isAbsoluteIri(value) {\n if (!isIri(value)) return false;\n\n const [scheme, ihierPart] = value.split(':');\n\n return schemeRegex.test(scheme) && ihierPart.includes('/');\n}",
"function convertToBase64(info) {\n var readMe = new FileReader();\n readMe.readAsDataURL(info);\n readMe.onload = function () {\n $(\"#base\").val(readMe.result)\n };\n readMe.onerror = function (error) {\n return \"There was an error with your file\"\n };\n }",
"function ContentURI( scheme, baseContentRef, path, lastIdx, baseURI ) {\n if( lastIdx == undefined ) {\n lastIdx = path.length - 1;\n }\n if( !baseURI ) {\n baseURI = lastIdx > -1 && new ContentURI( scheme, baseContentRef, path, lastIdx - 1 );\n }\n this.scheme = scheme;\n this.baseContentRef = baseContentRef;\n this.path = lastIdx > -1 ? pathToString( path, lastIdx ) : '';\n this.nextOp = lastIdx > -1 ? path[lastIdx] : false;\n this.baseURI = baseURI;\n}",
"function getRid(fid, node) {\r\n var regx = /^.*_.*/; //? f\\d{4,6}_\\d{2}/;\r\n/*? \r\n var rid = \"\";\r\n if (regx.test(fid)) {\r\n rid = (fid+fidgrd).split(fidgrd)[0]; //? '-').split('-')[0];\r\n rid = (rid+fidrid).split(fidrid)[1]; //?'_').split('_')[1];\r\n }\r\n else {\r\n rid = node.parents(\"[rid]\").attr(\"rid\");\r\n }\r\n?*/\r\n return rid;\r\n}",
"getBase(statEnum){\n verifyType(statEnum, TYPES.number);\n return this.stats.get(statEnum).getBase();\n }",
"_createBase() {\n this.base = new qm.Base({\n mode: 'createClean',\n schemaPath: __dirname + '/schema.json'\n });\n }",
"function getResource() {\n var v = \"custom:(uuid,encounterDatetime,patient:(uuid,uuid),form:(uuid,name),location:ref\";\n v += \",encounterType:ref,provider:ref,obs:(uuid,concept:ref,value:ref,groupMembers))\";\n r = $resource(OpenmrsSettings.getContext() + \"/ws/rest/v1/encounter/:uuid\",\n {uuid: '@uuid', v: v},\n {query: {method: \"GET\", isArray: false}}\n );\n return new dataMgr.ExtendedResource(r,true,resourceName,true,\"uuid\",null);\n }",
"function getIidDoc() {\n const deferred = q.defer();\n const filename = '/shared/vadc/aws/iid-document';\n\n fs.stat(filename, (fsStatErr) => {\n if (fsStatErr && fsStatErr.code === 'ENOENT') {\n logger.debug('No iid doc found');\n deferred.resolve({});\n } else if (fsStatErr) {\n const message = `Error reading iid doc: ${fsStatErr.code}`;\n logger.info(message);\n deferred.reject(new Error(message));\n } else {\n fs.readFile(filename, (err, data) => {\n if (err) {\n deferred.reject(err);\n } else {\n deferred.resolve(JSON.parse(data.toString()));\n }\n });\n }\n });\n\n return deferred.promise;\n}",
"function getResource(map, base, internal, path, callback, addLineHints) {\n\t\tvar\n\t\t\treduced = reduce(map, path),\n\t\t\treducedMap = reduced.map,\n\t\t\treducedMapType = nodeType(reducedMap),\n\t\t\treducedPrefix = reduced.prefix,\n\t\t\treducedSuffix = reduced.suffix,\n\t\t\tfirstChar = path.charAt(0),\n\t\t\ttemporary = firstChar === '~',\n\t\t\tliteral = firstChar === '='\n\t\t;\n\n\t\tif (isURL(path)) {\n\t\t\twget(path, callback);\n\n\t\t} else if (literal) {\n\t\t\tcallback(null, new Buffer(path.substr(1) + '\\n'));\n\n\t\t} else if (temporary && !internal) {\n\t\t\t// External request for a temporary resource.\n\t\t\tcallback({ code: 403, message: 'Forbidden' });\n\n\t\t} else if (reducedSuffix) {\n\t\t\t// We did NOT find an exact match in the map.\n\n\t\t\tif (!reducedPrefix && internal) {\n\t\t\t\tgetFile(base, path, callback, addLineHints);\n\t\t\t} else if (reducedMapType === 'string') {\n\t\t\t\tgetFile(base, reducedMap + '/' + reducedSuffix, callback, addLineHints);\n\t\t\t} else {\n\t\t\t\tcallback({ code: 404, message: 'Not Found' });\n\t\t\t}\n\n\t\t} else {\n\t\t\t// We found an exact match in the map.\n\n\t\t\tif (reducedMap === reducedPrefix) {\n\t\t\t\t// This is just a local file/dir to expose.\n\t\t\t\tgetFile(base, reducedPrefix, callback, addLineHints);\n\n\t\t\t} else if (reducedMapType === 'string') {\n\t\t\t\t// A string value may be a web URL.\n\t\t\t\tif (isURL(reducedMap)) {\n\t\t\t\t\twget(reducedMap, callback);\n\t\t\t\t} else {\n\t\t\t\t\t// Otherwise, it's another resource path.\n\t\t\t\t\tgetResource(map, base, true, reducedMap, callback, addLineHints);\n\t\t\t\t}\n\n\t\t\t} else if (reducedMapType === 'array') {\n\t\t\t\t// An array is a list of resources to get packed together.\n\t\t\t\tpackResources(map, base, reducedMap, callback);\n\n\t\t\t//} else if (reducedMapType === 'object') {\n\t\t\t\t// An object is a directory. We could return a listing...\n\t\t\t\t// TODO: Do we really want to support listings?\n\n\t\t\t} else {\n\t\t\t\tcallback({ code: 500, message: 'Unable to read gravity.map.' });\n\t\t\t}\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and attach the MDC Foundation to the instance | createFoundation() {
if (this.mdcFoundation !== undefined) {
this.mdcFoundation.destroy();
}
if (this.mdcFoundationClass) {
this.mdcFoundation = new this.mdcFoundationClass(this.createAdapter());
this.mdcFoundation.init();
}
} | [
"init(actor) {\n this.host = actor\n }",
"static init()\n {\n let aeFDC = Component.getElementsByClass(document, PCx86.APPCLASS, \"fdc\");\n for (let iFDC = 0; iFDC < aeFDC.length; iFDC++) {\n let eFDC = aeFDC[iFDC];\n let parmsFDC = Component.getComponentParms(eFDC);\n let fdc = new FDC(parmsFDC);\n Component.bindComponentControls(fdc, eFDC, PCx86.APPCLASS);\n }\n }",
"async created() {\n this.broker.createService(metadata);\n this.broker.createService(packages);\n this.broker.createService(apps);\n this.broker.createService(objects);\n this.broker.createService(layouts);\n this.broker.createService(permissionsets);\n this.broker.createService(tabs);\n this.broker.createService(translations);\n this.broker.createService(triggers);\n this.broker.createService(queriesService);\n this.broker.createService(chartsService);\n this.broker.createService(pagesService);\n this.broker.createService(shareRulesService);\n this.broker.createService(restrictionRulesService);\n this.broker.createService(permissionFieldsService);\n this.broker.createService(processService);\n this.broker.createService(processTriggerService);\n this.broker.createService(objectTriggerService);\n this.broker.createService(permissionTabsService);\n this.broker.createService(importService);\n }",
"function demoInitialize() {\n document.title = \"Visia\"\n // create the demo instance\n var demo = new Demo()\n demo.init()\n // register the callback that is called when all module contexts are created\n MLABApp.setModuleContextsReadyCallback(demo.moduleContextsReady)\n}",
"function createSwarmDiscovery() {\n swarm = hyperdiscovery(feed);\n swarm.on('connection', (peer, info) => {\n logger.info('SWARM', 'New peer connection')\n peer.on('close', () => logger.warning('SWARM', 'Peer disconnected') );\n });\n}",
"async componentDidMount() {\n // create the server chooser\n const chooser = new DefaultServerChooser();\n chooser.add(`ws://${HOST}:${PORT}/amps/json`);\n\n // create the AMPS HA client object\n const client = new Client('view-server');\n client.serverChooser(chooser);\n client.subscriptionManager(new DefaultSubscriptionManager());\n\n // now we can establish connection \n await client.connect();\n\n // update the state\n this.setState({ client });\n }",
"createFrontendManager(socket) {\n let manager = new FrontendManager(socket)\n this._frontendManagers.push(manager)\n dg('frontend added', 'debug')\n }",
"addDevice() {\n const device = {\n deviceId: '',\n kind: 'videoinput',\n label: '',\n groupId: '',\n };\n device.__proto__ = MediaDeviceInfo.prototype;\n this.devices_.push(device);\n if (this.deviceChangeListener_) {\n this.deviceChangeListener_();\n }\n }",
"constructor() {\r\n ObjectManager.instance = this;\r\n\r\n }",
"function init() {\n\t\tid = utilities.UUID('toastify');\n\t\tvar root = document.querySelector(settings.root);\n\t\tvar toastifyEl = document.createElement('div');\n\t\t// Sets attributes and classes of toastify element.\n\t\ttoastifyEl.setAttribute('id', id);\n\t\ttoastifyEl.classList.add('toastify');\n\t\ttoastifyEl.classList.add('toastify--' + settings.position.horizontal);\n\t\ttoastifyEl.classList.add('toastify--' + settings.position.vertical);\n\t\troot.appendChild(toastifyEl);\n\t}",
"attach( opts ) {\n opts = Object.assign({\n as: 'logger'\n }, opts || {} )\n\n const logger = this\n\n return async function( ctx, next ) {\n if ( ctx[ opts.as ] ) {\n console.warn( 'ctx.logger already exists' )\n await next()\n return\n }\n\n ctx[ opts.as ] = logger\n\n await next()\n }\n }",
"function initializeAddLive() {\n ADLT.initializeAddLiveQuick(onPlatformReady,\n {applicationId:ADLT.APP_ID});\n }",
"function dce_attach_canvas(cid, ccid) {\n\n\tctx = null;\n\tcanvas = null;\n\tcanvas_container = null;\n\n\tcanvas = document.getElementById(cid);\n\tif(canvas == null) {\n\t\tthrow new Error(\"No canvas with id:\\\"\" + cid + \"\\\".\");\n\t}\n\n\tcanvas_container = document.getElementById(id);\n\tif(canvas == null) {\n\t\tthrow new Error(\"No canvas with id:\\\"\" + id + \"\\\".\");\n\t}\n\n\tctx = canvas.getContext(\"2d\");\n\n}",
"static init()\n {\n let aeDbg = Component.getElementsByClass(document, PCx86.APPCLASS, \"debugger\");\n for (let iDbg = 0; iDbg < aeDbg.length; iDbg++) {\n let eDbg = aeDbg[iDbg];\n let parmsDbg = Component.getComponentParms(eDbg);\n let dbg = new DebuggerX86(parmsDbg);\n Component.bindComponentControls(dbg, eDbg, PCx86.APPCLASS);\n }\n }",
"startDiscovery() {}",
"function onReady() {\n if (isDevelopment()) {\n installDevExtensions()\n }\n //setupGolem()\n createWindow()\n tray = createTray(win)\n\n ipcHandler(app, tray, win, createPreviewWindow, APP_WIDTH, APP_HEIGHT)\n}",
"createChannel() {\n\t\tlet depends = this.props.depends ? this.props.depends : {};\n\t\tvar channelObj = manager.create(depends);\n\n\t}",
"init() {\n // Get permission to use connected MIDI devices\n navigator\n .requestMIDIAccess({ sysex: this.sysex })\n .then(\n // Success\n this.connectSuccess.bind(this),\n // Failure\n this.connectFailure.bind(this)\n );\n }",
"_initSessionWatchdogs() {\n // test messages\n\n this._sessionTestMessagesWatchdog = new Watchdog();\n this._sessionTestMessagesWatchdog.debug = this.debug;\n this._sessionTestMessagesWatchdog.name = 'test-messages';\n this._sessionTestMessagesWatchdog.timeout =\n this.extraTestTimeout + parseFloat(this._impTestFile.values.timeout);\n\n this._sessionTestMessagesWatchdog.on('timeout', () => {\n this._onError(new Errors.SesstionTestMessagesTimeoutError());\n this._session.stop = this._stopSession;\n });\n\n // session start\n\n this._sessionStartWatchdog = new Watchdog();\n this._sessionStartWatchdog.debug = this.debug;\n this._sessionStartWatchdog.name = 'session-start';\n this._sessionStartWatchdog.timeout = this.sessionStartTimeout;\n\n this._sessionStartWatchdog.on('timeout', () => {\n this._onError(new Errors.SessionStartTimeoutError());\n this._session.stop = this._stopSession;\n });\n\n this._sessionStartWatchdog.start();\n }",
"function start () {\n let node = process.execPath\n let daemonFile = path.join(__dirname, '../daemon')\n let daemonLog = path.resolve(untildify('~/.hotel/daemon.log'))\n\n debug(`creating ${startupFile}`)\n startup.create('hotel', node, [daemonFile], daemonLog)\n\n console.log(` Started http://localhost:${conf.port}`)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
On main panel, show the user panel | function showUserPanel() {
lcSendValueAndCallbackHtmlAfterErrorCheckPreserveMessage("/user/index",
"#userDiv", "#userDiv", null);
} | [
"function openUserEditor(){\n\n\t$('.content-panel').hide();\n\n\t$('#editUserPanel').show();\n\n}",
"function showUser(){\n\t\t\tdocument.getElementById('user-div').style.display = 'block';\n\t\t\tdocument.getElementById('user-btn').style.backgroundColor = 'white';\n\t\t\tdocument.getElementById('user-btn').style.color = 'black';\n\t\t\tdocument.getElementById('owner-div').style.display = 'none';\n\t\t\tdocument.getElementById('agent-div').style.display = 'none';\n\t\t\t\n\t\t\tgsap.from(\"#u-name\",0.4,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\tgsap.from(\"#u-phone\",0.8,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\tgsap.from(\"#u-email\",1.2,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\t\n\t\t\tdocument.getElementById('agent-btn').style.backgroundColor = 'rgba(0,0,0,0.1)';\n\t\t\tdocument.getElementById('agent-btn').style.color = 'white';\n\t\t\tdocument.getElementById('owner-btn').style.backgroundColor = 'rgba(0,0,0,0.1)';\n\t\t\tdocument.getElementById('owner-btn').style.color = 'white';\n\t\t}",
"function shower(){\n $(document).ready(function(){\n $(\"#username\").show();\n $(\"#password\").show();\n $(\"#login_btn\").show();\n $(\"#logout_btn\").hide();\n $(\"#new_username\").show();\n $(\"#new_password\").show();\n $(\"#register_btn\").show();\n $(\"#newusermessage\").show();\n $(\"#delete_btn\").hide();\n $(\"#eventid\").hide();\n $(\"#delete_btn\").hide();\n $(\"#instructions\").hide();\n $(\"#panel\").hide();\n $(\"#panel2\").hide();\n $(\"#instr\").hide();\n });\n}",
"function showLoggedInMenu(){\n\t\t$('#signup, #login').hide();\n\t\t$('#logout').show();\n\t}",
"function showPlayer() {\r\n setBlockVis(\"player\", \"block\");\r\n setBlockVis(\"annotations\", \"block\");\r\n if (hideSegmentControls == true) { setBlockVis(\"segmentation\", \"none\"); }\r\n\r\n // Only display the Annotation button if the user is logged in (where ohp.myUserId > 0)...\r\n if (ohp.myUserId > 0) { setBlockVis(\"btnAnnotate\", \"inline-block\");}\r\n}",
"function userLoggedIn() {\n let username = sessionStorage.getItem('username');\n $('#spanMenuLoggedInUser').text(`Welcome, ` + username + '!');\n $('#viewUserHomeHeading').text(`Welcome, ` + username + '!');\n $('.anonymous').hide();\n $('.useronly').show();\n showView('UserHome')\n }",
"function displayUserTab() {\n\n}",
"function happycol_presentation_theShow(args){\n\tif(args.stageManager==true){\n\t\thappycol_stageManager(args);\n\t}\n}",
"function showUser(user)\n{\n\tuser.promiseData(['path'])\n\t .then(function()\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar panel = new PathlinesPanel(user, true);\n\t\t\t\tpanel.pathtree.setUser(user.path());\n\t\t\t\tpanel.showLeft().then(unblockClick);\n\t\t\t}\n\t\t\tcatch(err)\n\t\t\t{\n\t\t\t\tcr.syncFail(err);\n\t\t\t}\n\t\t},\n\t\tcr.syncFail);\n}",
"function displayrpsStatsPanel() {}",
"function showOtherUser(){\n removeFollowList();\n removeSearchArea();\n var userId = this.dataset.user; // get the user of the clicked name or image\n showedUser = userId;\n removeWritenFields();\n removeErrorSuccesFields();\n document.getElementById(\"profileSection\").style.display = \"block\";\n document.getElementById(\"messagesSection\").style.display = \"none\";\n hideAllProfileSection();\n document.getElementById(\"showProfile\").style.display = \"block\";\n\n getOtherProfile(userId);\n}",
"_onProfileBtnClick() {\n // toggle the visibility of authedUser component\n this._componenets.authedUser.hidden = !this._componenets.authedUser.hidden\n }",
"function showConfigUser() {\n\n\tdocument.getElementById('sel_editor_font_size').value = v_editor_font_size;\n\tdocument.getElementById('sel_editor_theme').value = v_theme_id;\n\n\tdocument.getElementById('txt_confirm_new_pwd').value = '';\n\tdocument.getElementById('txt_new_pwd').value = '';\n\n\t$('#div_config_user').show();\n\n}",
"function showOwner(){\n\t\t\tdocument.getElementById('owner-div').style.display = 'block';\n\t\t\tdocument.getElementById('owner-btn').style.backgroundColor = 'white';\n\t\t\tdocument.getElementById('owner-btn').style.color = 'black';\n\t\t\tdocument.getElementById('user-div').style.display = 'none';\n\t\t\tdocument.getElementById('agent-div').style.display = 'none';\n\n\t\t\tgsap.from(\"#o-name\",0.4,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\tgsap.from(\"#o-phone\",0.8,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\tgsap.from(\"#o-email\",1.2,{opacity:0,ease:Power2.easeInOut,x:-400})\n\t\t\tgsap.from(\"#o-address\",1.6,{opacity:0,ease:Power2.easeInOut,x:-400})\n\n\t\t\tdocument.getElementById('user-btn').style.backgroundColor = 'rgba(0,0,0,0.1)';\n\t\t\tdocument.getElementById('user-btn').style.color = 'white';\n\t\t\tdocument.getElementById('agent-btn').style.backgroundColor = 'rgba(0,0,0,0.1)';\n\t\t\tdocument.getElementById('agent-btn').style.color = 'white';\n\t\t}",
"function displayUsername() {\n $navWelcome.children('#nav-user-profile').text(currentUser.username);\n $navWelcome.show();\n }",
"updateView() {\n const isLoggedIn = login.isLoggedIn();\n this.shadowRoot.getElementById(\"notloggedin\").hidden = isLoggedIn;\n this.shadowRoot.getElementById(\"loggedin\").hidden = !isLoggedIn;\n\n // Show username when logged in\n if(isLoggedIn) {\n const credentials = login.getCredentials();\n this.shadowRoot.getElementById(\"username\").innerText = credentials.username;\n }\n }",
"function show() {\n if (settings.shown) return;\n win.show();\n settings.shown = true;\n }",
"function userOnload(){\n checkLoginAndSetUp(); \n sidebar();\n fetchOUs();\n}",
"function signUp() {\n $('#main-header').text(\"B-Day List\");\n $('#login-container').hide();\n $('#logout-btn').removeClass('hide');\n $('#add-btn').removeClass('hide');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert to a string from a charCode | function toStr(ch) {
return String.fromCharCode(ch);
} | [
"function string(c) /* (c : char) -> string */ {\n return _char_to_string(c);\n}",
"function getLetterFromCode(num){\n return String.fromCharCode(num+96);\n}",
"function getCodeFromLetter(str){\n return str.charCodeAt(0)-96;\n}",
"_aec(code) {\n return String.fromCharCode(27) + \"[\" + code;\n }",
"function encode_digit(d, flag) {\n return d + 22 + 75 * (d < 26) - ((flag != 0) << 5);\n // 0..25 map to ASCII a..z or A..Z \n // 26..35 map to ASCII 0..9 \n }",
"function show_char(c) /* (c : char) -> string */ {\n var _x24 = (((c < 0x0020)) || ((c > 0x007E)));\n if (_x24) {\n if ((c === 0x000A)) {\n return \"\\\\n\";\n }\n else {\n if ((c === 0x000D)) {\n return \"\\\\r\";\n }\n else {\n if ((c === 0x0009)) {\n return \"\\\\t\";\n }\n else {\n var _x25 = $std_core._int_le(c,255);\n if (_x25) {\n return ((\"\\\\x\") + (show_hex(c, 2, undefined, \"\")));\n }\n else {\n var _x26 = $std_core._int_le(c,65535);\n if (_x26) {\n return ((\"\\\\u\") + (show_hex(c, 4, undefined, \"\")));\n }\n else {\n return ((\"\\\\U\") + (show_hex(c, 6, undefined, \"\")));\n }\n }\n }\n }\n }\n }\n else {\n if ((c === 0x0027)) {\n return \"\\\\\\'\";\n }\n else {\n if ((c === 0x0022)) {\n return \"\\\\\\\"\";\n }\n else {\n return ((c === 0x005C)) ? \"\\\\\\\\\" : string(c);\n }\n }\n }\n}",
"function decode(r) {\n let num = parseInt(r), arr = r.match(/[a-z]/g).map(x=>x.charCodeAt(0)-97), str= \"\";\n for(let code of arr){\n let orig = \"\";\n for(let i = 0;i < 26; i++){\n if( (i * num) %26===code){\n if(orig!==\"\")\n return \"Impossible to decode\";\n orig=i;\n str+=String.fromCharCode(97+i);\n }\n }\n }\n return str;\n}",
"function hexAsciiToStr(hexAscii)\n{\n\t// Force conversion of hexAscii to string\n\tvar hex = hexAscii.toString();\n\tvar str = '';\n\tfor (var i = 0; i < hex.length; i=i+2)\n\t\tstr += String.fromCharCode(parseInt(hex.substr(i, 2), 16));\n\treturn str;\n}",
"function unicodeToChar(text) {\n return text.replace(/\\\\u[\\dA-F]{4}/gi,\n function (match) {\n return String.fromCharCode(parseInt(match.replace(/\\\\u/g, ''), 16));\n });\n}",
"static bytes26(v) { return b(v, 26); }",
"function CODE() {\n var text = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];\n var index = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1];\n\n if (index < 1) return error$2.na;\n if (text.length < index) return error$2.value;\n return text.charCodeAt(index - 1);\n}",
"static bytes27(v) { return b(v, 27); }",
"function escapeChar(ch) {\n\tlet charCode = ch.charCodeAt(0);\n\tif(charCode <= 0xFF) {\n\t\treturn '\\\\x' + pad(charCode.toString(16).toUpperCase());\n\t} else {\n\t\treturn '\\\\u' + pad(charCode.toString(16).toUpperCase(),4);\n\t}\n}",
"function bit_to_ascii(array) {\n var num = 0;\n var n;\n for (n = 0; n < 8; n++) {\n if (array[n] == '1') {\n num += Math.pow(2, 7 - n);\n console.log(num);\n }\n }\n return String.fromCharCode(num);\n}",
"function siiB(e) {\r\n\treturn Math.round(parseInt(e)).toString(36);\r\n}",
"function genChar(arr){\n\n var rand = Math.random()\n var l = arr.length;\n var i = Math.floor(l * rand); //generate random index\n var char = arr[i]; //select random character from array\n var c = char.toString()\n\n return c\n }",
"function Charat(){\n\tvar kata = 'saya belajar di pasar';\n\tconsole.log(kata.charAt(4));\n}",
"function decode_digit(cp) {\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n }",
"function messageFromBinaryCode(code) {\n // we can split the string in the params every 8 characters to have an array to work with.\n let binaryArr = code.match(/.{8}/g)\n // we can have a variable that holds the string being decipher from the binary code\n let message = ''\n // we would then iterate over the arr and use our helper to convert the binary code to decimal numbers, then refer to the ascii code to determine what character represents, and lastly we want to concatenate the ascii character found to the string.\n for(let binary in binaryArr){\n let character = String.fromCharCode(binaryToDecimal(binaryArr[binary]))\n message += character\n }\n\n return message\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
3. Which of the top 20 horror movies have no spoken language besides English? | function filterSpokenLanguage(movieObject){
//console.log(movieObject)
let englishOnly = movieObject.filter(object => object.spoken_languages.length == 1 && object.spoken_languages[0].iso_639_1=="en")
.map(object => object.title)
console.log("3. Which of the top 20 horror movies have no spoken language besides English?",englishOnly)
} | [
"relevance(that){cov_25grm4ggn6.f[9]++;let total=(cov_25grm4ggn6.s[47]++,0);let words=(cov_25grm4ggn6.s[48]++,Object.keys(this.count));cov_25grm4ggn6.s[49]++;words.forEach(w=>{cov_25grm4ggn6.f[10]++;cov_25grm4ggn6.s[50]++;total+=this.rank(w)*that.rank(w);});//return the average rank of my words in the other vocabulary\ncov_25grm4ggn6.s[51]++;return total/words.length;}",
"highestScoringWord() {\n let example = Scrabble.highestScoreFrom(this.plays);\n return example;\n }",
"function getFavoriteLanguage(languages) {\n let compare = '';\n let mostFrequentLanguage = '';\n languages.reduce((acc, val) => {\n if(val in acc) {\n acc[val]++;\n }\n else {\n acc[val] = 1;\n }\n if(acc[val] > compare) {\n compare = acc[val];\n mostFrequentLanguage = val;\n }\n return acc;\n }, {})\n return mostFrequentLanguage\n}",
"function percentageMatureWords() {\n\tvar wordCount = 0;\n\tvar matureWordCount = 0;\n\t\n\tvar allElements = document.body.getElementsByTagName(\"*\");\n\tfor (i = 0; i < allElements.length; i++) {\n\t\tif (allElements[i].tagName.toLowerCase() === \"script\") continue;\n\t\tif (allElements[i].childNodes.length == 1 && !allElements[i].firstChild.tagName) {\n\t\t\t//console.log(allElements[i]);\n\t\t\tvar words = allElements[i].innerHTML.trim().replace(/[^\\w\\s]/gi, '').toLowerCase().split(\" \");\n\t\t\tconsole.log(words);\n\t\t\tfor (j = 0; j < words.length; j++) {\n\t\t\t\twordCount++;\n\t\t\t\tif (binarySearch(potentiallyNSFWKeywords, words[j], 0, potentiallyNSFWKeywords.length - 1) > -1) {\n\t\t\t\t\tmatureWordCount++;\n\t\t\t\t\tconsole.log(words[j]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (wordCount === 0)\n\t\treturn;\n\t\n\tvar percentMatureWords = (matureWordCount / wordCount) * 100;\n\tif (percentMatureWords > 5)\n\t\tisBadPage();\n\t\n\tconsole.log(\"wordCount: \" + wordCount + \". matureWordCount: \" + matureWordCount + \". %: \" + percentMatureWords);\n}",
"function getRelevant(movie) {\n var result,\n SKIP_ARRAY = {\n movie: 1,\n film: 1,\n rotten: 1,\n rating: 1,\n rt: 1,\n tomatoes: 1\n },\n aMovie;\n if (movie.total > 1) {\n result = movie.movies[0];\n for (var i = 0, length = movie.movies.length; i < length; i += 1){\n aMovie = movie.movies[i];\n if (DDG.isRelevant(aMovie.title, SKIP_ARRAY)) {\n result = aMovie;\n break;\n }\n } \n } else {\n result = movie.movies[0];\n }\n return result;\n }",
"function getRandomRhymeWord(rhymingWord, maxSyllables) {\n var rhymeList = getRhymeData(rhymingWord);\n if (rhymeList == []) {\n return \"no rhymes\";\n }\n var isGoodRhyme = false;\n var maxIndex = 99;\n if (!(rhymingWord == 'blue')){\n console.log(\"Here\");\n maxIndex = rhymeList.length - 1;\n }\n console.log('INDEX HERE', maxIndex);\n console.log(!(rhymingWord == 'blue'));\n //loops through the words (up to the maxIndex) until we get something that does not have a space, is less than the given number of syllables, and has a tag for part of speech\n var iterCount = 0;\n while (isGoodRhyme == false && iterCount <= 100) {\n var randomIndex = Math.floor(Math.random() * (maxIndex));\n var randomWordObj = rhymeList[randomIndex];\n console.log(randomWordObj);\n if (!randomWordObj.hasOwnProperty('word')){\n continue;\n } //delete if mess thinged up\n var randomWord = randomWordObj['word'];\n if (!(randomWord.includes(' '))) {\n if (randomWordObj.hasOwnProperty('tags')) {\n if (randomWordObj['numSyllables'] < maxSyllables) {\n var rhymeWord = randomWord;\n var numSyllables = randomWordObj['numSyllables'];\n isGoodRhyme = true;\n }\n }\n }\n iterCount += 1;\n }\n console.log(\"RANDOMWORD\",randomWordObj);\n return randomWordObj;\n}",
"highestWordScore() {\n let highestWord = this.highestScoringWord();\n return Scrabble.score(highestWord);\n }",
"order(words){cov_25grm4ggn6.f[7]++;cov_25grm4ggn6.s[40]++;if(!words){cov_25grm4ggn6.b[15][0]++;cov_25grm4ggn6.s[41]++;return[];}else{cov_25grm4ggn6.b[15][1]++;}//ensure we have a list of individual words, not phrases, no punctuation, etc.\nlet list=(cov_25grm4ggn6.s[42]++,words.toString().match(/\\w+/g));cov_25grm4ggn6.s[43]++;if(list.length==0){cov_25grm4ggn6.b[16][0]++;cov_25grm4ggn6.s[44]++;return[];}else{cov_25grm4ggn6.b[16][1]++;}cov_25grm4ggn6.s[45]++;return list.sort((a,b)=>{cov_25grm4ggn6.f[8]++;cov_25grm4ggn6.s[46]++;return this.rank(a)<=this.rank(b)?(cov_25grm4ggn6.b[17][0]++,1):(cov_25grm4ggn6.b[17][1]++,-1);});}",
"function topWords(text) {\n let wordArray = text.split(' ');\n // ['hi', 'hello', 'hello']\n let wordCounter = {};\n \n for (let word of wordArray) {\n let lowerCaseWord = word.toLowerCase();\n\n if (!wordCounter[lowerCaseWord]) {\n wordCounter[lowerCaseWord] = 1;\n } else if (wordCounter[lowerCaseWord]) {\n wordCounter[lowerCaseWord]++;\n }\n }\n let entries = Object.entries(wordCounter);\n let sortedEntries = entries.sort((a, b) => b[1] - a[1]);\n return `${sortedEntries[0][0]} stated ${sortedEntries[0][1]} times`\n}",
"function automatedReadabilityIndex(letters, numbers, words, sentences) {\n return (4.71 * ((letters + numbers) / words))\n + (0.5 * (words / sentences))\n - 21.43;\n}",
"function getAngry(){\n var emotionAngry = [\"Action\", \"Crime\", \"Documentary\", \"History\", \"Sci-Fi\", \"Sport\", \"War\", \"Western\"]\n var movieAlreadyAdded = false;\n for(i=0;i<emotionAngry.length;i++){\n for(j=0;j<movieObject.length;j++){\n if(movieObject[j].genre.search(emotionAngry[i]) >= 0){\n for(k=0;k<angry.length;k++){\n if(angry[k] === movieObject[j]){\n movieAlreadyAdded = true;\n }\n }\n if(!movieAlreadyAdded){\n angry.push(movieObject[j])\n }else{\n movieAlreadyAdded = false;\n }\n }\n }\n }\n}",
"function mostCommonWord() {\r\n // 819\r\n var paragraph = 'a.'; //'Bob hit a ball, the hit BALL flew far after it was hit.';\r\n var banned = [];\r\n let bannedWords = new Set();\r\n for (const word of banned) {\r\n bannedWords.add(word);\r\n }\r\n\r\n paragraph = paragraph\r\n .replace(/[^a-zA-Z]/gi, ' ')\r\n .toLowerCase()\r\n .split(' ');\r\n\r\n var count = new Map();\r\n for (const word of paragraph) {\r\n if (!bannedWords.has(word) && word !== '') {\r\n if (count.has(word)) {\r\n count.set(word, count.get(word) + 1);\r\n } else {\r\n count.set(word, 1);\r\n }\r\n }\r\n }\r\n\r\n return new Map([...count.entries()].sort((a, b) => b[1] - a[1])).keys().next()\r\n .value;\r\n}",
"function well(x){\n let goodArr = x.filter(word => word === 'good')\n if(goodArr.length > 2){\n return 'I smell a series!'\n }else if (goodArr.length > 0){\n return \"Publish!\"\n }else{\n return 'Fail!'\n }\n}",
"function topThreeWords(text) {\n const words = text.toLowerCase().match(/(?:\\w|(?<=\\w)')+/g);\n if (!words) return [];\n\n const counter = {};\n for (word of words) {\n counter[word] ? (counter[word] += 1) : (counter[word] = 1);\n }\n const sortedWords = Object.entries(counter).sort((a, b) => b[1] - a[1]);\n\n return sortedWords.slice(0, 3).map(item => item[0]);\n}",
"function Similarity(){\n var u = 1;\n for (u = 1; u < TweetCount+1; u ++){\n// check if there is previous text\nconsole.log(\"last text is: \" + TweetLastText[u]);\nif (TweetLastText[u] !== \"\"){\nTweetSimilar[u] = natural.JaroWinklerDistance(TweetLastText[u],TweetText[u]);\nconsole.log(\"the words similarity is: \" + TweetSimilar[u]);\n }\n// check tweet against all others\nvar o = 1;\n for (o = 1; o < TweetCount+1; o ++){\nif (TweetText[o] !== TweetText[u]){\n console.log(natural.JaroWinklerDistance(TweetText[u],TweetText[o]));\n}\n }\n\n\n\n }\n}",
"function topThreeWords(text) {\n\n const words = text.split(/[ .,/]/);\n\n let occur = {};\n\n words.forEach(word => {\n const w = word.toLowerCase();\n if (w.match(/[a-z]/)) {\n occur[w] = (occur[w] || 0) + 1;\n }\n });\n\n let top1 = 0;\n let top2 = 0;\n let top3 = 0;\n\n let result = [];\n\n for (let key in occur) {\n const value = occur[key];\n if (value > top1) {\n top3 = top2;\n top2 = top1;\n top1 = value;\n result.unshift(key);\n } else if (value > top2) {\n top3 = top2;\n top2 = value;\n result.splice(1, 0, key);\n } else if (value > top3) {\n top3 = value;\n result.splice(2, 0, key);\n }\n }\n\n return result.slice(0, 3);\n}",
"function mostTitle(characters) {\n let count = 0;\n let name = [];\n let nameWithSameNumbers = [];\n characters.forEach(function (array) {\n if (array.titles.length > count) {\n count = array.titles.length;\n name = array.name;\n }\n });\n characters.forEach(function (array) {\n if (count === array.titles.length) {\n nameWithSameNumbers.push(array.name);\n }\n });\n // console.log(name);\n return [`Who has the most titles?: ${nameWithSameNumbers}`, `Number of titles: ${count}`];\n}",
"function printSentence() {\n if (this[\"isChallenging\"] === true && this[\"isRewarding\"] === true) {\n console.log(`Learning the programming languages: \"${this[\"languages\"].join(\", \")}\" is rewarding and challenging.`);\n } else {\n console.log(\"Hä?\")\n };\n}",
"function invDocFreq(term) {\n if (corpus == null){\n return -1;\n } else {\n //N = corpus.length;\n let docFreq = 0;\n for (let i in N){\n for (let j in corpus[i]) {\n if (corpus[i][j] == term.toLowerCase()){\n docFreq++;\n break;\n }\n }\n }\n let idf = Math.log((N) / (docFreq + 1)) + 1;\n return idf;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Params from Actions are: [Doc Link, Applicant, Attribute, Filename] | handleAddAttribute(params) {
this.applicant = params[1];
this.applicant[params[2]] = params[0];
this.applicant[`${params[2]}File`] = params[3];
} | [
"function AttachmentsAction({ files, onUpload, onDelete }) {\n return (\n <Fragment>\n <UploadAction onUpload={onUpload} />\n {files.map(file => (\n <FileAction key={file.id} onDelete={onDelete} file={file} />\n ))}\n </Fragment>\n );\n}",
"function copyDocuments(pFromCapId, pToCapId) {\r\n\r\n\t//Copies all attachments (documents) from pFromCapId to pToCapId\r\n\tvar vFromCapId = pFromCapId;\r\n\tvar vToCapId = pToCapId;\r\n\tvar categoryArray = new Array();\r\n\t\r\n\t// third optional parameter is comma delimited list of categories to copy.\r\n\tif (arguments.length > 2) {\r\n\t\tcategoryList = arguments[2];\r\n\t\tcategoryArray = categoryList.split(\",\");\r\n\t}\r\n\r\n\tvar capDocResult = aa.document.getDocumentListByEntity(capId,\"CAP\");\r\n\tif(capDocResult.getSuccess()) {\r\n\t\tif(capDocResult.getOutput().size() > 0) {\r\n\t \tfor(docInx = 0; docInx < capDocResult.getOutput().size(); docInx++) {\r\n\t \t\tvar documentObject = capDocResult.getOutput().get(docInx);\r\n\t \t\tcurrDocCat = \"\" + documentObject.getDocCategory();\r\n\t \t\tif (categoryArray.length == 0 || exists(currDocCat, categoryArray)) {\r\n\t \t\t\t// download the document content\r\n\t\t\t\t\tvar useDefaultUserPassword = true;\r\n\t\t\t\t\t//If useDefaultUserPassword = true, there is no need to set user name & password, but if useDefaultUserPassword = false, we need define EDMS user name & password.\r\n\t\t\t\t\tvar EMDSUsername = null;\r\n\t\t\t\t\tvar EMDSPassword = null;\r\n\t\t\t\t\tvar downloadResult = aa.document.downloadFile2Disk(documentObject, documentObject.getModuleName(), EMDSUsername, EMDSPassword, useDefaultUserPassword);\r\n\t\t\t\t\tif(downloadResult.getSuccess()) {\r\n\t\t\t\t\t\tvar path = downloadResult.getOutput();\r\n\t\t\t\t\t\t//logDebug(\"path=\" + path);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvar tmpEntId = vToCapId.getID1() + \"-\" + vToCapId.getID2() + \"-\" + vToCapId.getID3();\r\n\t\t\t\t\tdocumentObject.setDocumentNo(null);\r\n\t\t\t\t\tdocumentObject.setCapID(vToCapId)\r\n\t\t\t\t\tdocumentObject.setEntityID(tmpEntId);\r\n\t\r\n\t\t\t\t\t// Open and process file\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\t// put together the document content - use java.io.FileInputStream\r\n\t\t\t\t\t\tvar newContentModel = aa.document.newDocumentContentModel().getOutput();\r\n\t\t\t\t\t\tinputstream = new java.io.FileInputStream(path);\r\n\t\t\t\t\t\tnewContentModel.setDocInputStream(inputstream);\r\n\t\t\t\t\t\tdocumentObject.setDocumentContent(newContentModel);\r\n\t\t\t\t\t\tvar newDocResult = aa.document.createDocument(documentObject);\r\n\t\t\t\t\t\tif (newDocResult.getSuccess()) {\r\n\t\t\t\t\t\t\tnewDocResult.getOutput();\r\n\t\t\t\t\t\t\tlogDebug(\"Successfully copied document: \" + documentObject.getFileName());\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tlogDebug(\"Failed to copy document: \" + documentObject.getFileName());\r\n\t\t\t\t\t\t\tlogDebug(newDocResult.getErrorMessage());\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (err) {\r\n\t\t\t\t\t\tlogDebug(\"Error copying document: \" + err.message);\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t \t} // end for loop\r\n\t\t}\r\n }\r\n}",
"function fileUrl(fid, action) {\n var params = deparam(window.location.search.replace('?', ''));\n params.destination = destPath();\n return '/file/' + fid + '/' + action + '?' + $.param(params);\n }",
"function iglooActions () {\n\t//we should have things like pageTitle, user and revid\n\t//here- and the current page\n}",
"function init(){\n\n // Check to see if sourceFolder has any folders in it\n if(sourceFolder != null){\n \n // Create new array for files to be stored;\n files = new Array();\n \n // Only use file types that are illustrator files\n fileType = \"*.ai\";\n \n // Files get saved with all of the files in the sourcefolder\n files = sourceFolder.getFiles(fileType);\n\n // Check to see if there are any files in the folder\n if(files.length > 0){\n\n // Ask for destination folder.\n // destFolder = Folder.selectDialog('Select the folder you want to export files to','~');\n \n // Save to parent folder.\n destFolder = (app.activeDocument.fullName.parent.fsName).toString().replace(/\\\\/g, '/');\n\n // Loop through files\n for(var i = 0; i < files.length; i++){\n\n // Saves the open file and properties to sourceDoc\n sourceDoc = app.open(files[i]);\n\n // Sets doc to active document\n doc = app.activeDocument;\n\n // Exports all artboards\n exportArtboards();\n\n // Closes Document\n sourceDoc.close(SaveOptions.DONOTSAVECHANGES);\n }\n } else {\n alert('There is no file here')\n }\n } else {\n alert('There is no folder here')\n }\n\n}",
"function LoadDocumentBtnClicked() \n{\n\n //Initialize Viwer\n\tOnInitializeViwer();\n\t\n //get the document provided by the user\n documentId = document.getElementById(\"DocIdTB\").value;\n\n //load the document\n Autodesk.Viewing.Document.load(documentId, Autodesk.Viewing.Private.getAuthObject(), onSuccessDocumentLoadCB, onErrorDocumentLoadCB);\n //update the command line text.\n UpdateCommandLine(\"Loading document : \" + documentId);\n}",
"function DownloadGeneratorApp( data_url, is_contributor )\n{\n \"use strict\";\n \n // Initialize some private variables.\n \n var done_config1, done_config2;\n \n var params = { base_name: '', interval: '', output_metadata: 1, reftypes: 'taxonomy' };\n var param_errors = { };\n\n var visible = { };\n \n var data_type = \"occs\";\n var data_op = \"occs/list\";\n var url_op = \"occs/list\";\n\n var data_format = \".csv\";\n var ref_format = \"\";\n var non_ref_format = \".csv\";\n\n var form_mode = \"simple\";\n\n var download_path = \"\";\n var download_params = \"\";\n \n var output_section = 'none';\n var output_order = 'none';\n \n var output_full = { };\n var full_checked = { };\n \n var paleoloc_all = 0;\n var paleoloc_selected = 0;\n \n var confirm_download = 0;\n var taxon_status_save = '';\n\n var no_update = 0;\n\n // Object for holding data cached from the API\n \n var api_data = { };\n \n // Variables for handling object identifiers in the \"metadata\" section.\n \n var id_param_map = { col: \"coll_id\", clu: \"clust_id\",\n\t\t\t occ: \"occ_id\", spm: \"spec_id\" };\n var id_param_index = { col: 0, clu: 1, occ: 2, spm: 3 };\n var ref_param = { ref_id : 1, ref_title: 1, pub_title: 1, ref_primary: 1,\n\t\t ref_author: 1 };\n \n // The following regular expressions are used to validate user input.\n \n var patt_dec_num = /^[+-]?(\\d+[.]\\d*|\\d*[.]\\d+|\\d+)$/;\n var patt_dec_pos = /^(\\d+[.]\\d*|\\d*[.]\\d+|\\d+)$/;\n var patt_int_pos = /^\\d+$/;\n var patt_name = /^(.+),\\s+(.+)/;\n var patt_name2 = /^(.+)\\s+(.+)/;\n var patt_has_digit = /\\d/;\n var patt_date = /^(\\d+[mshdMY]|\\d\\d\\d\\d(-\\d\\d(-\\d\\d)?)?)$/;\n var patt_extid = /^(col|occ|clu|spm)[:]\\d+$/;\n \n // If the value of data_url starts with a slash, prefix the origin of the current page to get a full URL.\n\n var short_data_url;\n var full_data_url;\n\n // The following function initializes this application controller object. It is exported as\n // a method, so that it can be called once the web page is fully loaded. It must make two\n // API calls to get a list of country and continent codes, and geological time intervals.\n // When both of these calls complete, the \"initializing form...\" HTML floating element is hidden,\n // signaling to the user that the application is ready for use.\n \n function initApp ()\n {\n\t// Do various initialization steps\n\t\n\tno_update = 1;\n\t\n\tinitDisplayClasses();\n\tgetDBUserNames();\n\t\n\tif ( getElementValue(\"vf1\") != \"-1\" )\n\t showHideSection('f1', 'show');\n\t\n\tvar sections = { vf2: 'f2', vf3: 'f3', vf4: 'f4', vf5: 'f5', vf6: 'f6', vo1: 'o1', vo2: 'o2' };\n\tvar s;\n\t\n\tfor ( s in sections )\n\t{\n\t if ( getElementValue(s) == \"1\" )\n\t\tshowHideSection(sections[s], 'show');\n}\n\t\n\t// Make sure we have a proper URL to use for data service requests.\n\t\n\tvar origin_match;\n\n\tshort_data_url = data_url;\n\t\n\tif ( data_url.match( /^\\// ) && window.location.origin )\n\t full_data_url = window.location.origin + data_url;\n\telse\n\t full_data_url = data_url;\n\t\n\t// If the form is being reloaded and already has values entered into it, take some steps\n\t// to make sure it is properly set up.\n\t\n\ttry\n\t{\n\t var record_type = $('input[name=\"record_type\"]:checked').val();\n\t setRecordType(record_type);\n\t \n\t var form_mode = $('input[name=\"form_mode\"]:checked').val();\n\t setFormMode(form_mode);\n\t \n\t var output_format = $('input[name=\"output_format\"]:checked').val();\n\t setFormat(output_format);\n\n\t var private_url = $('input[name=\"private_url\"]:checked').val();\n\t console.log(\"private_url = \" + private_url);\n\t setPrivate(private_url);\n\t}\n\t\n\tcatch (err) { };\n\t\n\tno_update = 0;\n\t\n\t// Initiate two API calls to fetch necessary data. Each has a callback to handle the data\n\t// that comes back, and a failure callback too.\n\t\n\t$.getJSON(data_url + 'config.json?show=all&limit=all')\n\t .done(callbackConfig1)\n\t .fail(badInit);\n\t$.getJSON(data_url + 'intervals/list.json?all_records&limit=all')\n\t .done(callbackConfig2)\n\t .fail(badInit);\n }\n \n this.initApp = initApp;\n \n \n // The following function is called when the first configuration API call returns. Country\n // and continent codes and taxonomic ranks are saved as properties of the api_data object.\n // These will be used for validating user input.\n \n function callbackConfig1 (response)\n {\n\tif ( response.records )\n\t{\n\t api_data.rank_string = { };\n\t api_data.continent_name = { };\n\t api_data.continents = [ ];\n\t api_data.country_code = { };\n\t api_data.country_name = { };\n\t api_data.countries = [ ];\n\t api_data.country_names = [ ];\n\t api_data.aux_continents = [ ];\n\t api_data.lithologies = [ ];\n\t api_data.lith_types = [ ];\n\t api_data.pg_models = [ ];\n\t api_data.pg_menu = [ ];\n\t api_data.pg_desc = [ ];\n\t \n\t var lith_uniq = { };\n\t \n\t for ( var i=0; i < response.records.length; i++ )\n\t {\n\t\tvar record = response.records[i];\n\t\t\n\t\tif ( record.cfg == \"trn\" ) {\n\t\t api_data.rank_string[record.cod] = record.rnk;\n\t\t}\n\t\t\n\t\telse if ( record.cfg == \"con\" ) {\n\t\t api_data.continent_name[record.cod] = record.nam;\n\t\t api_data.continents.push(record.cod, record.nam);\n\t\t}\n\t\t\n\t\telse if ( record.cfg == \"cou\" ) {\n\t\t var key = record.nam.toLowerCase();\n\t\t api_data.country_code[key] = record.cod;\n\t\t api_data.country_name[record.cod] = record.nam;\n\t\t api_data.country_names.push(record.nam);\n\t\t}\n\t\t\n\t\telse if ( record.cfg == \"lth\" ) {\n\t\t api_data.lithologies.push( record.lth, record.lth );\n\t\t if ( ! lith_uniq[record.ltp] )\n\t\t {\n\t\t\tapi_data.lith_types.push( record.ltp, record.ltp );\n\t\t\tlith_uniq[record.ltp] = 1;\n\t\t }\n\t\t}\n\t\t\n\t\telse if ( record.cfg == \"pgm\" ) {\n\t\t api_data.pg_desc.push(record.cod, record.dsc);\n\t\t api_data.pg_models.push(record.cod);\n\t\t api_data.pg_menu.push(record.cod, record.lbl);\n\t\t}\n\t }\n\t \n\t api_data.lith_types.push( 'unknown', 'unknown' );\n\t \n\t // api_data.continents = api_data.continents.concat(api_data.aux_continents);\n\t api_data.country_names = api_data.country_names.sort();\n\t \n\t for ( i=0; i < api_data.country_names.length; i++ )\n\t {\n\t\tvar key = api_data.country_names[i].toLowerCase();\n\t\tvar code = api_data.country_code[key];\n\t\tapi_data.countries.push( code, api_data.country_names[i] + \" (\" + code + \")\" );\n\t }\n\n\t // If both API calls are complete, finish the initialization process. \n\t \n\t done_config1 = 1;\n\t if ( done_config2 ) finishInitApp();\n\t}\n\n\t// If no results were received, we're in trouble. The application can't be used if the\n\t// API is not working, so there's no point in proceeding further.\n\t\n\telse\n\t badInit();\n }\n \n \n // The following function is called when the second configuration API call returns. The names\n // of known geological intervals are saved as a property of the api_data object. These will\n // be used for validating user input.\n \n function callbackConfig2 (response)\n {\n\tif ( response.records )\n\t{\n\t api_data.interval = { };\n\t \n\t for ( var i = 0; i < response.records.length; i++ )\n\t {\n\t\tvar record = response.records[i];\n\t\tvar key = record.nam.toLowerCase();\n\t\t\n\t\tapi_data.interval[key] = record.oid;\n\t }\n\t \n\t // If both API calls are complete, finish the initialization process. \n\t \n\t done_config2 = 1;\n\t if ( done_config1 ) finishInitApp();\n\t}\n\t\n\t// If no results were received, we're in trouble. The application can't be used if the\n\t// API is not working, so there's no point in proceeding further.\n\t\n\telse\n\t badInit();\n\t\n }\n \n\n // This function is called when both configuration API calls are complete. It hides the\n // \"initializing form, please wait\" HTML floating object, and then calls updateFormState to\n // initialize the main URL and other form elements.\n \n function finishInitApp ()\n {\n\tinitFormContents();\n\t\n\tvar init_box = myGetElement(\"db_initmsg\");\n\tif ( init_box ) init_box.style.display = 'none';\n\t\n\tno_update = 1;\n\t\n\ttry {\n\t checkTaxon();\n\t checkTaxonStatus();\n\t checkInterval();\n\t checkCC();\n\t checkCoords();\n\t checkStrat();\n\t checkEnv();\n\t checkMeta('specs');\n\t checkMeta('occs');\n\t checkMeta('colls');\n\t checkMeta('taxa');\n\t checkMeta('occs');\n\t checkMeta('refs');\n\t}\n\n\tcatch (err) { };\n\t\n\tno_update = 0;\n\t\n\tupdateFormState();\n }\n \n\n // The following method can be called to reset the form back to its initial state. It is tied\n // to the \"clear form\" button in the HTML layout. The options selected in the top section of\n // the form (i.e. record type, output format) will be preserved. All others will be reset.\n \n function resetForm ()\n {\n\tvar keep_type = data_type;\n\tvar keep_format = data_format.substring(1);\n\tvar keep_private = params.private;\n\tvar keep_advanced = form_mode;\n\t\n\tvar form_elt = myGetElement(\"download_form\");\n\tif ( form_elt ) form_elt.reset();\n\t\n\tparams = { base_name: '', interval: '', output_metadata: 1, reftypes: 'taxonomy' };\n\t\n\tinitDisplayClasses();\n\n\ttry\n\t{\n\t no_update = 1;\n\t \n\t setRecordType(keep_type);\n\t $('input[name=\"record_type\"][value=\"' + keep_type + '\"]')[0].checked = 1;\n\t setFormat(keep_format);\n\t $('input[name=\"output_format\"][value=\"' + keep_format + '\"]')[0].checked = 1;\n\t setPrivate(keep_private);\n\t $('input[name=\"private\"][value=\"' + keep_private + '\"]')[0].checked = 1;\n\t setFormMode(keep_advanced);\n\t $('input[name=\"form_mode\"][value=\"' + keep_advanced + '\"]')[0].checked = 1;\t \n\t}\n\t\n\tfinally\n\t{\n\t no_update = 0;\n\t}\n\t\n\tupdateFormState();\n }\n\n this.resetForm = resetForm;\n \n \n // This function notifies the user that this application is not able to be used. It is called\n // if either of the configuration API calls fail. If the API is not working, there's no point\n // in proceeding with this application.\n \n function badInit ( )\n {\n\tvar init_box = myGetElement(\"db_initmsg\");\n\tif ( init_box ) init_box.innerHTML = \"Initialization failed! Please contact admin@paleobiodb.org\";\n }\n \n \n // Included in this application is a system to easily hide and show all HTML objects that are\n // tagged with particular CSS classes. This subroutine sets up the initial form state.\n \n function initDisplayClasses ()\n {\n\tshowByClass('type_occs');\n\tshowByClass('taxon_reso');\n\tshowByClass('advanced');\n\t\n\thideByClass('taxon_mods');\n\thideByClass('mult_cc3');\n\thideByClass('mult_cc2');\n\t\n\thideByClass('type_colls');\n\thideByClass('type_taxa');\n\thideByClass('type_ops');\n\thideByClass('type_strata');\n\thideByClass('type_refs');\n\t\n\thideByClass('help_h1');\n\thideByClass('help_h2a');\n\thideByClass('help_h2b');\n\thideByClass('help_f1');\n\thideByClass('help_f2');\n\thideByClass('help_f3');\n\thideByClass('help_f4');\n\thideByClass('help_f5');\n\thideByClass('help_f6');\n\thideByClass('help_o1');\n\thideByClass('help_o2');\n\t\n\thideByClass('buffer_rule');\n\t\n\t// If the user is currently logged in to the database, show the form element that chooses\n\t// between generating a URL that fetches private data and one that does not. The former\n\t// will only work when the user is logged in, the latter may be distributed publicly.\n\t\n\tif ( is_contributor )\n\t{\n\t showByClass('loggedin');\n\t // params.private = 1;\n\t}\n\t\n\telse\n\t hideByClass('loggedin');\n }\n \n \n // -----------------------------------------------------------------------------------------\n \n // The following functions generate some of the repetitious HTML necessary for checklists and\n // other complex controls. Doing it this way makes the lists easier to change as the API is\n // updated, and allows download_generator.html to be much smaller and simpler. These\n // functions call convenience routines such as setInnerHTML, which are defined below.\n \n function initFormContents ( )\n {\n\tvar content = \"\";\n\t\n\t// First generate the controls for selecting output blocks\n\t\n\tcontent = \"<tr><td>\\n\";\n\t\n\t// \"*full\", \"full\", \"Includes all boldface blocks (no need to check them separately)\",\n\t\n\tcontent += makeBlockControl( \"od_occs\",\n\t[\"*attribution\", \"attr\", \"Attribution (author and year) of the accepted name\",\n\t \"*classification\", \"class\", \"Taxonomic classification of the occurrence\",\n\t \"classification ext.\", \"classext\", \"Taxonomic classification including taxon ids\",\n\t \"genus\", \"genus\", \"Use instead of the above if you just want the genus\",\n\t \"subgenus\", \"subgenus\", \"Use with any of the above to include subgenus as well\",\n\t \"accepted only\", \"acconly\", \"Suppress the exact identification of the occurrence, show only accepted name\",\n\t \"ident components\", \"ident\", \"Individual components of the identification, rarely needed\",\n\t \"phylopic id\", \"img\", \"Identifier of a <a href=\\\"http://phylopic.org/\\\" target=\\\"_blank\\\">phylopic</a>\" +\n\t \"representing this taxon or the closest containing taxon\",\n\t \"*plant organs\", \"plant\", \"Plant organ(s) identified as part of this occurrence, if any\",\n\t \"*abundance\", \"abund\", \"Abundance of this occurrence in the collection\",\n\t \"*ecospace\", \"ecospace\", \"The ecological space occupied by this organism\",\n\t \"*taphonomy\", \"taphonomy\", \"Taphonomy of this organism\",\n\t \"eco/taph basis\", \"etbasis\", \"Annotation for ecospace and taphonomy as to taxonomic level\",\n\t \"*preservation\", \"pres\", \"Is this occurrence identified as a form taxon, ichnotaxon or regular taxon\",\n\t \"*collection\", \"coll\", \"The name and description of the collection in which this occurrence was found\",\n\t \"*coordinates\", \"coords\", \"Latitude and longitude of this occurrence\",\n\t \"*location\", \"loc\", \"Additional info about the geographic locality\",\n\t \"*paleolocation\", \"paleoloc\", \"Paleogeographic location of this occurrence, all models\",\n\t \"paleoloc (selected)\", \"paleoloc2\", \"Paleogeographic location using the model selected above\",\n\t \"*protection\", \"prot\", \"Indicates whether this occurrence is on protected land, i.e. a national park\",\n\t \"stratigraphy\", \"strat\", \"Basic stratigraphy of the occurrence\",\n\t \"*stratigraphy ext.\", \"stratext\", \"Extended (detailed) stratigraphy of the occurrence\",\n\t \"lithology\", \"lith\", \"Basic lithology of the occurrence\",\n\t \"*lithology ext.\", \"lithext\", \"Extended (detailed) lithology of the occurrence\",\n\t \"paleoenvironment\", \"env\", \"The paleoenvironment associated with this collection\",\n\t \"*geological context\", \"geo\", \"Additional info about the geological context (includes env)\",\n\t \"time binning\", \"timebins\", \"Lists the interval(s) from the international timescale into which each \" +\n\t \"occurrence falls\",\n\t \"time comparison\", \"timecompare\", \"Shows the time binning for all available timerules, so you can compare them\",\n\t \"*methods\", \"methods\", \"Info about the collection methods used\",\n\t \"research group\", \"resgroup\", \"The research group(s) if any associated with the collection\",\n\t \"reference\", \"ref\", \"The reference from which this occurrence was entered, as formatted text\",\n\t \"*ref attribution\", \"refattr\", \"Author(s) and publication year of the reference\",\n\t \"enterer ids\", \"ent\", \"Identifiers of the people who authorized/entered/modified each record\",\n\t \"enterer names\", \"entname\", \"Names of the people who authorized/entered/modified each record\",\n\t \"created/modified\", \"crmod\", \"Creation and modification timestamps for each record\" ]);\n\t\n\tcontent += \"</td></tr>\\n\";\n\t\n\tcontent += makeOutputHelpRow(\"occs/list\");\n\t\n\tsetInnerHTML(\"od_occs\", content);\n\t\n\tcontent = \"<tr><td>\\n\";\n\t\n\tcontent += makeBlockControl( \"od_colls\",\n\t[\"*location\", \"loc\", \"Additional info about the geographic locality\",\n\t \"*paleolocation\", \"paleoloc\", \"Paleogeographic location of this collection, all models\",\n\t \"paleoloc (selected)\", \"paleoloc2\", \"Paleogeographic location using the model selected above\",\n\t \"*protection\", \"prot\", \"Indicates whether collection is on protected land\",\n\t \"time binning\", \"timebins\", \"Lists the interval(s) from the international timescale into which each \" +\n\t \"collection falls\",\n\t \"time comparison\", \"timecompare\", \"Like the above, but shows this information for all available timerules\",\n\t \"stratigraphy\", \"strat\", \"Basic stratigraphy of the occurrence\",\n\t \"*stratigraphy ext.\", \"stratext\", \"Detailed stratigraphy of the occurrence\",\n\t \"lithology\", \"lith\", \"Basic lithology of the occurrence\",\n\t \"*lithology ext.\", \"lithext\", \"Detailed lithology of the occurrence\",\n\t \"*geological context\", \"geo\", \"Additional info about the geological context\",\n\t \"*methods\", \"methods\", \"Info about the collection methods used\",\n\t \"research group\", \"resgroup\", \"The research group(s) if any associated with this collection\",\n\t \"reference\", \"ref\", \"The primary reference associated with this collection, as formatted text\",\n\t \"*ref attribution\", \"refattr\", \"Author(s) and publication year of the reference\",\n\t \"all references\", \"secref\", \"Identifiers of all references associated with this collection\",\n\t \"enterer ids\", \"ent\", \"Identifiers of the people who authorized/entered/modified this record\",\n\t \"enterer names\", \"entname\", \"Names of the people who authorized/entered/modified this record\",\n\t \"created/modified\", \"crmod\", \"Creation and modification timestamps\" ]);\n\t\n\tcontent += \"</td></tr>\\n\";\n\t\n\tcontent += makeOutputHelpRow(\"colls/list\");\n\t\n\tsetInnerHTML(\"od_colls\", content);\n\t\n\tcontent = \"<tr><td>\\n\";\n\t\n\tcontent += makeBlockControl( \"od_specs\",\n\t[\"*attribution\", \"attr\", \"Attribution (author and year) of the accepted taxonomic name\",\n\t \"*classification\", \"class\", \"Taxonomic classification of the specimen\",\n\t \"classification ext.\", \"classext\", \"Taxonomic classification including taxon ids\",\n\t \"genus\", \"genus\", \"Use instead of the above if you just want the genus\",\n\t \"subgenus\", \"subgenus\", \"Use with any of the above to include subgenus as well\",\n\t \"*plant organs\", \"plant\", \"Plant organ(s) if any\",\n\t \"*abundance\", \"abund\", \"Abundance of the occurrence (if any) in its collection\",\n\t \"*collection\", \"coll\", \"The name and description of the collection in which the occurrence (if any) was found\",\n\t \"*coordinates\", \"coords\", \"Latitude and longitude of the occurrence (if any)\",\n\t \"*location\", \"loc\", \"Additional info about the geographic locality of the occurrence (if any)\",\n\t \"*paleolocation\", \"paleoloc\", \"Paleogeographic location of this collection, all models\",\n\t \"paleoloc (selected)\", \"paleoloc2\", \"Paleogeographic location using the model selected above\",\n\t \"*protection\", \"prot\", \"Indicates whether source of specimen was on protected land (if known)\",\n\t \"stratigraphy\", \"strat\", \"Basic stratigraphy of the occurrence (if any)\",\n\t \"*stratigraphy ext.\", \"stratext\", \"Detailed stratigraphy of the occurrence (if any)\",\n\t \"lithology\", \"lith\", \"Basic lithology of the occurrence (if any)\",\n\t \"*lithology ext.\", \"lithext\", \"Detailed lithology of the occurrence (if any)\",\n\t \"*geological context\", \"geo\", \"Additional info about the geological context (if known)\",\n\t \"*methods\", \"methods\", \"Info about the collection methods used (if known)\",\n\t \"remarks\", \"rem\", \"Additional remarks about the associated collection (if any)\",\n\t \"resgroup\", \"resgroup\", \"The research group(s) if any associated with this collection\",\n\t \"reference\", \"ref\", \"The reference from which this specimen was entered, as formatted text\",\n\t \"*ref attribution\", \"refattr\", \"Author(s) and publication year of the reference\",\n\t \"enterer ids\", \"ent\", \"Identifiers of the people who authorized/entered/modified this record\",\n\t \"enterer names\", \"entname\", \"Names of the people who authorized/entered/modified this record\",\n\t \"created/modified\", \"crmod\", \"Creation and modification timestamps\" ]);\n\t\n\tcontent += \"</td></tr>\\n\";\n\t\n\tcontent += makeOutputHelpRow(\"specs/list\");\n\t\n\tsetInnerHTML(\"od_specs\", content);\n\t\n\tcontent = \"<tr><td>\\n\";\n\t\n\tcontent += makeBlockControl( \"od_taxa\",\n\t[\"*attribution\", \"attr\", \"Attribution (author and year) of this taxonomic name\",\n\t \"*common\", \"common\", \"Common name (if any)\",\n \t \"*age range overall\", \"app\", \"Ages of first and last appearance among all occurrences in this database\",\n\t \"age range selected\", \"occapp\", \"Ages of first and last appearance among selected occurrences\",\n\t \"*parent\", \"parent\", \"Name and identifier of parent taxon\",\n\t \"immediate parent\", \"immparent\", \"Name and identifier of immediate parent taxon (may be a junior synonym)\",\n \t \"*size\", \"size\", \"Number of subtaxa\",\n\t \"*classification\", \"class\", \"Taxonomic classification: phylum, class, order, family, genus\",\n\t \"classification ext.\", \"classext\", \"Taxonomic classification including taxon ids\",\n\t \"*subtaxon counts\", \"subcounts\", \"Number of genera, families, and orders contained in this taxon\",\n\t \"*ecospace\", \"ecospace\", \"The ecological space occupied by this organism\",\n\t \"*taphonomy\", \"taphonomy\", \"Taphonomy of this organism\",\n\t \"eco/taph basis\", \"etbasis\", \"Annotation for ecospace and taphonomy as to taxonomic level\",\n\t \"*preservation\", \"pres\", \"Is this a form taxon, ichnotaxon or regular taxon\",\n\t \"sequence numbers\", \"seq\", \"The sequence numbers of this taxon in the computed tree\",\n\t \"phylopic id\", \"img\", \"Phylopic identifier\",\n\t \"reference\", \"ref\", \"The reference from which this taxonomic name was entered, as formatted text\",\n\t \"*ref attribution\", \"refattr\", \"Author(s) and publication year of the reference\",\n\t \"enterer ids\", \"ent\", \"Identifiers of the people who authorized/entered/modified this record\",\n\t \"enterer names\", \"entname\", \"Names of the people who authorized/entered/modified this record\",\n\t \"created/modified\", \"crmod\", \"Creation and modification timestamps\" ]);\n\t\n\tcontent += \"</td></tr>\\n\";\n\t\n\tcontent += makeOutputHelpRow(\"taxa/list\");\n\t\n\tsetInnerHTML(\"od_taxa\", content);\n\t\n\tcontent = \"<tr><td>\\n\";\n\t\n\tcontent += makeBlockControl( \"od_ops\",\n \t[\"*basis\", \"basis\", \"Basis of this opinion, i.e. 'stated with evidence'\",\n\t \"reference\", \"ref\", \"The reference from which this opinion was entered, as formatted text\",\n\t \"*ref attribution\", \"refattr\", \"Author(s) and publication year of the reference\",\n\t \"enterer ids\", \"ent\", \"Identifiers of the people who authorized/entered/modified this record\",\n\t \"enterer names\", \"entname\", \"Names of the people who authorized/entered/modified this record\",\n\t \"created/modified\", \"crmod\", \"Creation and modification timestamps\" ]);\n\t\n\tcontent += \"</td></tr>\\n\";\n\t\n\tcontent += makeOutputHelpRow(\"opinions/list\");\n\t\n\tsetInnerHTML(\"od_ops\", content);\n\t\n\tcontent = \"<tr><td>\\n\";\n\t\n\tcontent += makeBlockControl( \"od_strata\",\n \t[\"coordinates\", \"coords\", \"Latitude and longitude range of occurrences\"])\n\t\n\tcontent += \"</td></tr>\\n\";\n\t\n\tcontent += makeOutputHelpRow(\"strata/list\");\n\t\n\tsetInnerHTML(\"od_strata\", content);\n\t\n\tcontent = \"<tr><td>\\n\";\n\t\n\tcontent += makeBlockControl( \"od_refs\",\n\t[\"associated counts\", \"counts\", \"Counts of authorities, opinions, occurrences, \" + \n\t \"collections associated with this reference\",\n\t \"formatted\", \"formatted\", \"Return a single formatted string instead of individual fields\",\n\t \"both\", \"both\", \"Return a single formatted string AND the individual fields\",\n\t \"comments\", \"comments\", \"Comments entered about this reference, if any\",\n\t \"enterer ids\", \"ent\", \"Identifiers of the people who authorized/entered/modified this record\",\n\t \"enterer names\", \"entname\", \"Names of the people who authorized/entered/modified this record\",\n\t \"created/modified\", \"crmod\", \"Creation and modification timestamps\" ]);\n\t\n\tcontent += \"</td></tr>\\n\";\n\t\n\tcontent += makeOutputHelpRow(\"refs/list\");\n\t\n\tsetInnerHTML(\"od_refs\", content);\n\t\n\t// Then the controls for selecting output order\n\t\n\tcontent = makeOptionList( [ '--', 'default', 'earlyage', 'max_ma', 'lateage', 'min_ma',\n\t\t\t\t 'taxon', 'taxonomic hierarchy',\n\t\t\t\t 'formation', 'geological formation', 'plate', 'tectonic plate',\n\t\t\t\t 'created', 'creation date of record',\n\t\t\t\t 'modified', 'modification date of record' ] );\n\t\n\tsetInnerHTML(\"pm_occs_order\", content);\n\t\n\tsetInnerHTML(\"pm_colls_order\", content);\n\t\n\tcontent = makeOptionList( [ '--', 'default', 'hierarchy', 'taxonomic hierarchy',\n\t\t\t\t 'name', 'taxonomic name (alphabetical)', \n\t\t\t\t 'ref', 'bibliographic reference',\n\t\t\t\t 'firstapp', 'first appearance', 'lastapp', 'last appearance',\n\t\t\t\t 'n_occs', 'number of occurrences',\n\t\t\t\t 'authpub', 'author of name, year of publication',\n\t\t\t\t 'pubauth', 'year of publication, author of name',\n\t\t\t\t 'created', 'creation date of record',\n\t\t\t\t 'modified', 'modification date of record' ] );\n\t\n\tsetInnerHTML(\"pm_taxa_order\", content);\n\t\n\tcontent = makeOptionList( [ '--', 'default', 'hierarchy', 'taxonomic hierarchy',\n\t\t\t\t 'name', 'taxonomic name (alphabetical)', \n\t\t\t\t 'ref', 'bibliographic reference',\n\t\t\t\t 'authpub', 'author of opinion, year of publication',\n\t\t\t\t 'pubauth', 'year of publication, author of opinion',\n\t\t\t\t 'basis', 'basis of opinion',\n\t\t\t\t 'created', 'creation date of record',\n\t\t\t\t 'modified', 'modification date of record' ] );\n\t\n\tsetInnerHTML(\"pm_ops_order\", content);\n\t\n\tcontent = makeOptionList( [ '--', 'default', 'authpub', 'author of reference, year of publication',\n\t\t\t\t 'pubauth', 'year of publication, author of reference',\n\t\t\t\t 'reftitle', 'title of reference',\n\t\t\t\t 'pubtitle', 'title of publication',\n\t\t\t\t 'created', 'creation date of record',\n\t\t\t\t 'modified', 'modification date of record' ] );\n\t\n\tsetInnerHTML(\"pm_refs_order\", content);\n\t\n\t// Then generate various option lists. The names and codes for the continents and\n\t// countries were fetched during initialization via an API call.\n\t\n\tvar continents = api_data.continents || ['ERROR', 'Continent list is empty'];\n\t\n\tcontent = makeOptionList( [ '--', '--', '**', 'Multiple' ].concat(continents) );\n\t\n\tsetInnerHTML(\"pm_continent\", content);\n\t\n\tcontent = makeCheckList( \"pm_continents\", api_data.continents, 'dgapp.checkCC()' );\n\t\n\tsetInnerHTML(\"pd_continents\", content);\n\t\n\tvar countries = api_data.countries || ['ERROR', 'Country list is empty'];\n\t\n\tcontent = makeOptionList( ['--', '--', '**', 'Multiple'].concat(countries) );\n\t\n\tsetInnerHTML(\"pm_country\", content);\n\t\n\tcontent = makeOptionList( api_data.pg_menu );\n\t\n\tsetInnerHTML(\"pm_pg_model\", content);\n\t\n\tcontent = makeOptionList( ['', '--'].concat(api_data.pg_menu).concat(['all', 'all']) );\n\t\n\tparams.pg_model = getElementValue(\"pm_pg_model\");\n\tparams.pg_select = getElementValue(\"pm_pg_select\");\n\t \n\tsetInnerHTML(\"pm_pg_compare\", content);\n\t\n\tvar crmod_options = [ 'created_after', 'entered after',\n\t\t\t 'created_before', 'entered before',\n\t\t\t 'modified_after', 'modified after',\n\t\t\t 'modified_before', 'modified before' ];\n\t\n\tcontent = makeDefinitionList( api_data.pg_desc );\n\t\n\tsetInnerHTML(\"doc_pgm\", content);\n\t\n\tcontent = makeOptionList( crmod_options );\n\t\n\tsetInnerHTML(\"pm_specs_crmod\", content);\n\tsetInnerHTML(\"pm_occs_crmod\", content);\n\tsetInnerHTML(\"pm_colls_crmod\", content);\n\tsetInnerHTML(\"pm_taxa_crmod\", content);\n\tsetInnerHTML(\"pm_ops_crmod\", content);\n\tsetInnerHTML(\"pm_refs_crmod\", content);\n\t\n\tvar authent_options = [ 'authent_by', 'authorized/entered by',\n\t\t\t\t'authorized_by', 'authorized by',\n\t\t\t\t'entered_by', 'entered by',\n\t\t\t\t'modified_by', 'modified by',\n\t\t\t\t'touched_by', 'touched by' ];\n\t\n\tcontent = makeOptionList( authent_options );\n\t\n\tsetInnerHTML(\"pm_specs_authent\", content);\n\tsetInnerHTML(\"pm_occs_authent\", content);\n\tsetInnerHTML(\"pm_colls_authent\", content);\n\tsetInnerHTML(\"pm_taxa_authent\", content);\n\tsetInnerHTML(\"pm_ops_authent\", content);\n\tsetInnerHTML(\"pm_refs_authent\", content);\n\t\n\tcontent = makeCheckList( \"pm_lithtype\", api_data.lith_types, 'dgapp.checkLith()' );\n\t\n\tsetInnerHTML(\"pd_lithtype\", content);\n\t\n\tvar envtype_options = [ 'terr', 'terrestrial',\n\t\t\t\t'marine', 'any marine',\n\t\t\t\t'carbonate', 'carbonate',\n\t\t\t\t'silicic', 'siliciclastic',\n\t\t\t\t'unknown', 'unknown' ];\n\t\n\tcontent = makeCheckList( \"pm_envtype\", envtype_options, 'dgapp.checkEnv()' );\n\t\n\tsetInnerHTML(\"pd_envtype\", content);\n\t\n\tvar envzone_options = [ 'lacust', 'lacustrine', 'fluvial', 'fluvial',\n\t\t\t\t'karst', 'karst', 'terrother', 'terrestrial other',\n\t\t\t\t'marginal', 'marginal marine', 'reef', 'reef',\n\t\t\t\t'stshallow', 'shallow subtidal', 'stdeep', 'deep subtidal',\n\t\t\t\t'offshore', 'offshore', 'slope', 'slope/basin',\n\t\t\t\t'marindet', 'marine indet.' ];\n\t\n\tcontent = makeCheckList( \"pm_envzone\", envzone_options, 'dgapp.checkEnv()' );\n\t\n\tsetInnerHTML(\"pd_envzone\", content);\n\t\n\tvar reftypes = [ '+auth', 'authority references', '+class', 'classification references',\n\t\t\t 'ops', 'all opinion references', 'occs', 'occurrence references',\n\t\t\t 'specs', 'specimen references', 'colls', 'collection references' ];\n\t\n\tcontent = makeCheckList( \"pm_reftypes\", reftypes, 'dgapp.checkRefopts()' );\n\t\n\tsetInnerHTML(\"pd_reftypes\", content);\n\t\n\tvar taxon_mods = [ 'nm', 'no modifiers', 'ns', 'n. sp.', 'ng', 'n. (sub)gen', 'af', 'aff.', 'cf', 'cf.',\n\t\t\t 'sl', 'sensu lato', 'if', 'informal', 'eg', 'ex gr.',\n\t\t\t 'qm', '?', 'qu', '""' ];\n\t\n\tcontent = makeCheckList( \"pm_idgenmod\", taxon_mods, 'dgapp.checkTaxonMods()' );\n\t\n\tsetInnerHTML(\"pd_idgenmod\", content);\n\t\n\tcontent = makeCheckList( \"pm_idspcmod\", taxon_mods, 'dgapp.checkTaxonMods()' );\n\t\n\tsetInnerHTML(\"pd_idspcmod\", content);\n\t\n\t// We need to execute the following operation here, because the\n\t// spans to which it applies are created by the code above.\n\t\n\thideByClass('help_o1');\n }\n \n \n // The following function generates HTML code for displaying a checklist of output blocks.\n // One of these is created for every different data type. As a SIDE EFFECT, produces a \n // hash listing every boldfaced block and stores it in a property of the variable 'output_full'.\n \n function makeBlockControl ( section_name, block_list )\n {\n\tvar content = \"\";\n\t\n\toutput_full[section_name] = output_full[section_name] || { };\n\t\n\tfor ( var i = 0; i < block_list.length; i += 3 )\n\t{\n\t var block_name = block_list[i];\n\t var block_code = block_list[i+1];\n\t var block_doc = block_list[i+2];\n\t var attrs = '';\n\t var asterisked = 0;\n\t \n\t if ( block_name.indexOf('*') == 0 )\n\t {\n\t\tasterisked = 1;\n\t\tblock_name = block_name.slice(1);\n\t\toutput_full[section_name][block_code] = 1;\n\t }\n\t \n\t content = content + '<span class=\"dlBlockLabel\"><input type=\"checkbox\" name=\"' + \n\t\tsection_name + '\" value=\"' + block_code + '\" ';\n\t content = content + attrs + ' onClick=\"dgapp.updateFormState()\">';\n\t content += asterisked ? '<b>' + block_name + '</b>' : block_name;\n\t content += '</span><span class=\"vis_help_o1\">' + block_doc + \"<br/></span>\\n\";\n\t}\n\t\n\treturn content;\n }\n \n \n // The following function generates HTML code for the \"help\" row at the bottom of a checklist\n // of output blocks.\n \n function makeOutputHelpRow ( path )\n {\n\tvar content = '<tr class=\"dlHelp vis_help_o1\"><td>' + \"\\n\";\n\tcontent += \"<p>You can get more information about these output blocks and fields \";\n\tcontent += '<a target=\"_blank\" href=\"' + data_url + path + '#RESPONSE\" ';\n\tcontent += 'style=\"text-decoration: underline\">here</a>.</p>';\n\tcontent += \"\\n</td></tr>\";\n\t\n\treturn content;\n }\n\n\n // The following function generates HTML code for displaying a checklist of possible parameter\n // values.\n \n function makeCheckList ( list_name, options, ui_action )\n {\n\tvar content = '';\n\t\n\tif ( options == undefined || ! options.length )\n\t{\n\t console.log(\"ERROR: no options specified for checklist '\" + list_name + \"'\");\n\t return content;\n\t}\n\t\n\tfor ( var i=0; i < options.length / 2; i++ )\n\t{\n\t var code = options[2*i];\n\t var label = options[2*i+1];\n\t var attrs = '';\n\t var checked = false;\n\t \n\t if ( code.substr(0,1) == '+' )\n\t {\n\t\tcode = code.substr(1);\n\t\tchecked = true;\n\t }\n\t \n\t content += '<span class=\"dlCheckBox\"><input type=\"checkbox\" name=\"' + list_name + '\" value=\"' + code + '\" ';\n\t if ( checked ) content += 'checked=\"1\" ';\n\t content += attrs + 'onClick=\"' + ui_action + '\">' + label + \"</span>\\n\";\n\t}\n\t\n\treturn content;\n }\n \n \n // The following function generates HTML code for displaying a dropdown menu of possible\n // parameter values.\n \n function makeOptionList ( options )\n {\n\tvar content = '';\n\tvar i;\n\t\n\tif ( options == undefined || ! options.length )\n\t{\n\t return '<option value=\"error\">ERROR</option>';\n\t}\n\t\n\tfor ( i=0; i < options.length / 2; i++ )\n\t{\n\t var code = options[2*i];\n\t var label = options[2*i+1];\n\t \n\t content += '<option value=\"' + code + '\">' + label + \"</option>\\n\";\n\t}\n\t\n\treturn content;\n }\n \n \n // The following function generates HTML code for a definitio list.\n \n function makeDefinitionList ( options )\n {\n\tvar content = '';\n\tvar i;\n\t\n\tif ( options == undefined || ! options.length )\n\t{\n\t return '<dt>ERROR</dt>';\n\t}\n\t\n\tfor ( i=0; i < options.length / 2; i++ )\n\t{\n\t var code = options[2*i];\n\t var description = options[2*i+1];\n\t \n\t content += '<dt>' + code + '</dt><dd>' + description + '</dd>';\n\t}\n\t\n\treturn content;\n }\n \n // We don't have to query the API to get the list of database contributor names, because the\n // Classic code that generates the application's web page automatically includes the function\n // 'entererNames' which returns this list. We go through this list and stash all of the names\n // in the api_data object anyway.\n \n function getDBUserNames ( )\n {\n\tif ( api_data.user_names ) return;\n\t\n\tapi_data.user_names = entererNames();\n\tapi_data.valid_name = { };\n\tapi_data.user_match = [ ];\n\tapi_data.user_matchinit = [ ];\n\t\n\t// The names might be either in the form \"last, first\" or \"first last\". We have to check\n\t// both patterns. We add the object 'valid_name', whose properties include all of the\n\t// valid names in the form \"first last\" plus all last names.\n\t\n\tfor ( var i = 0; i < api_data.user_names.length; i++ )\n\t{\n\t var match;\n\t \n\t if ( match = api_data.user_names[i].match(patt_name) )\n\t {\n\t\tapi_data.valid_name[match[1]] = 1;\n\t\tvar rebuilt = match[2].substr(0,1) + '. ' + match[1];\n\t\tapi_data.valid_name[rebuilt] = 1;\n\t\tapi_data.user_names[i] = rebuilt;\n\t\tapi_data.user_match[i] = match[1].toLowerCase();\n\t\tapi_data.user_matchinit[i] = match[2].substr(0,1).toLowerCase();\n\t }\n\t \n\t else if ( match = api_data.user_names[i].match(patt_name2) )\n\t {\n\t\tapi_data.valid_name[match[2]] = 1;\n\t\tvar rebuilt = match[1].substr(0,1) + '. ' + match[2];\n\t\tapi_data.valid_name[rebuilt] = 1;\n\t\tapi_data.user_names[i] = rebuilt;\n\t\tapi_data.user_match[i] = match[2].toLowerCase();\n\t\tapi_data.user_matchinit[i] = match[1].substr(0,1).toLowerCase();\n\t }\n\t}\n }\n \n\n // -----------------------------------------------------------------------------\n \n // The following convenience methods manipulate DOM objects. We use the javascript object\n // 'visible' to keep track of which groups of objects are supposed to be visible and which are\n // not. The properties of this object are matched up with CSS classes whose names start with\n // 'vis_' or 'inv_'. If an object has CSS classes 'vis_x' and 'vis_y', then it is visible if\n // both visible[x] and visible[y] are true, hidden otherwise. Additionally, if an object has\n // CSS class 'inv_z', then it is hidden whenever visible[z] is true.\n \n // The following routine sets visible[classname] to false, then adjusts the visibility of all\n // DOM objects.\n \n function hideByClass ( classname )\n {\n\t// We start by setting the specified property of visible to false.\n\t\n\tvisible[classname] = 0;\n\t\n\t// All objects with class 'vis_' + classname must now be hidden, regardless of any other\n\t// classes they may also have.\n\t\n\tvar list = document.getElementsByClassName('vis_' + classname);\n\t\n\tfor ( var i = 0; i < list.length; i++ )\n\t{\n\t list[i].style.display = 'none';\n\t}\n\t\n\t// Some objects with class 'inv_' + classname may now be visible, if visible[x] is true for\n\t// each class 'vis_x' that the object has and visible[y] is false for each class 'inv_y'\n\t// that the object has.\n\t\n\tlist = document.getElementsByClassName('inv_' + classname);\n\t\n\telement:\n\tfor ( var i = 0; i < list.length; i++ )\n\t{\n\t // For each such object, check all of its classes.\n\t \n\t var classes = list[i].classList;\n\t \n\t for ( var j = 0; j < classes.length; j++ )\n\t {\n\t\tvar classprefix = classes[j].slice(0,4);\n\t\tvar rest = classes[j].substr(4);\n\t\t\n\t\t// If it has class 'vis_x' and visible[x] is not true, then setting\n\t\t// visible[classname] to false does not change its status.\n\t\t\n\t\tif ( classprefix == \"vis_\" && ! visible[rest] )\n\t\t{\n\t\t continue element;\n\t\t}\n\t\t\n\t\t// If it has class 'inv_y' and visible[y] is true, then y != classname because we\n\t\t// set visible[classname] to false at the top of this function. So this object's\n\t\t// status doesn't change either.\n\t\t\n\t\telse if ( classprefix == \"inv_\" && visible[rest] )\n\t\t{\n\t\t continue element;\n\t\t}\n\t }\n\t \n\t // If we get here then the object should be made visible.\n\t \n\t list[i].style.display = '';\n\t}\n }\n \n \n // The following routine sets visible[classname] to true, then adjusts the visibility of all\n // DOM objects.\n \n function showByClass ( classname )\n {\n\tvisible[classname] = 1;\n\t\n\t// Some objects with class 'vis_' + classname may now be visible, if visible[x] is true for\n\t// each class 'vis_x' that the object has and visible[y] is false for each class 'inv_y'\n\t// that the object has.\n\t\n\tvar list = document.getElementsByClassName('vis_' + classname);\n\t\n\telement:\n\tfor ( var i = 0; i < list.length; i++ )\n\t{\n\t // For each such object, check all of its classes.\n\t \n\t var classes = list[i].classList;\n\t \n\t for ( var j = 0; j < classes.length; j++ )\n\t {\n\t\tvar classprefix = classes[j].slice(0,4);\n\t\tvar rest = classes[j].substr(4);\n\t\t\n\t\t// If it has class 'vis_x' and visible[x] is not true, then x != classname because\n\t\t// we set visible[classname] to true at the top of this function. So this\n\t\t// object's status does not change.\n\t\t\n\t\tif ( classprefix == \"vis_\" && ! visible[rest] )\n\t\t{\n\t\t continue element;\n\t\t}\n\t\t\n\t\t// If it has class 'inv_y' and visible[y] is true, then its status does not change\n\t\t// because 'inv_' overrides 'vis_'.\n\t\t\n\t\telse if ( classprefix == \"inv_\" && visible[rest] )\n\t\t{\n\t\t continue element;\n\t\t}\n\t }\n\t \n\t // If we get here then the object should be made visible.\n\t \n\t list[i].style.display = '';\n\t}\n\t\n\t// All objects with class 'inv_' + classname must now be hidden, regardless of any other\n\t// classes they may also have.\n\t\n\tlist = document.getElementsByClassName('inv_' + classname);\n\t\n\tfor ( var i = 0; i < list.length; i++ )\n\t{\n\t list[i].style.display = 'none';\n\t}\n }\n \n \n // The following method expands or collapses the specified section of the application. If\n // the value of 'action' is 'show', then it is expanded. Otherwise, its state is\n // toggled.\n \n function showHideSection ( section_id, action )\n {\n\t// If we are forcing or toggling the section to expanded then execute the necessary steps.\n\t// The triangle marker corresponding to the section has the same name but prefixed with\n\t// 'm'.\n\t\n\tif ( ! visible[section_id] || (action && action == 'show') )\n\t{\n showElement(section_id);\n\t setElementSrc('m'+section_id, \"/JavaScripts/img/open_section.png\");\n\t setElementValue('v'+section_id, \"1\");\n\t var val = getElementValue('v'+section_id);\n\t}\n\t\n\t// Otherwise, we must be toggling it to collapsed.\n\t\n\telse\n\t{\n hideElement(section_id);\n\t setElementSrc('m'+section_id, \"/JavaScripts/img/closed_section.png\");\n\t setElementValue('v'+section_id, \"-1\");\n\t var val = getElementValue('v'+section_id);\n\t}\n\t\n\t// Update the form state to reflect the new configuration.\n\t\n\tupdateFormState();\n }\n \n this.showHideSection = showHideSection;\n \n \n // The following method should be called if the user clicks the 'help' button for one of the\n // sections. If the section is currently collapsed, it will be expanded. The help text and\n // related elements for the section will then be toggled. The event object responsible for\n // this action can be passed as the second parameter, or else it will be assumed to be the\n // currently executing event.\n \n function helpClick ( section_id, e )\n {\n\tif ( ! visible[section_id] && ! visible['help_' + section_id] )\n\t showHideSection(section_id, 'show');\n\t\n\tshowHideHelp(section_id);\n\t\n\t// Stop the event from propagating, because it has now been carried out.\n\t\n\tif ( !e ) e = window.event;\n\te.stopPropagation();\n }\n \n this.helpClick = helpClick;\n \n \n // Adjust the visiblity of the help text for the specified section of the application. If the\n // action is 'show', make it visible. If 'hide', make it invisible. Otherwise, toggle it.\n // The help button has the same name as the section, but prefixed with 'q'. The help elements\n // all have the class 'vis_help_' + the section id.\n \n function showHideHelp ( section_id, action )\n {\n\t// If the help text is visible and we're either hiding or toggling, then do so.\n\t\n\tif ( visible['help_' + section_id] && ( action == undefined || action == \"hide\" ) )\n\t{\n\t setElementSrc('q' + section_id, \"/JavaScripts/img/hidden_help.png\");\n\t hideByClass('help_' + section_id);\n\t}\n\t\n\t// If the help text is invisible and we're showing or toggling, then do so.\n\t\n\telse if ( action == undefined || action == \"show\" )\n\t{\n\t setElementSrc('q' + section_id, \"/JavaScripts/img/visible_help.png\");\n\t showByClass('help_' + section_id);\n\t}\n }\n \n \n // ------------------------------------------------------------------------------------\n \n // The following convenience routines operate on elements one at a time, rather than in\n // groups. This is an alternate mechanism for showing and hiding elements, used for elements\n // which are singular such as the \"initializing application\" floater or the elements that\n // display error messages. These routines also set the property of the 'visible' object\n // corresponding to the identifier of the element being set.\n \n // This function retrieves the DOM object with the specified id, and leaves a reasonable\n // message on the console if the program contains a typo and the requested element does not\n // exist.\n \n function myGetElement ( id )\n {\n\tvar elt = document.getElementById(id);\n\t\n\tif ( elt == undefined )\n\t{\n\t console.log(\"ERROR: unknown element '\" + id + \"'\");\n\t return undefined;\n\t}\n\t\n\telse return elt;\n }\n\n // Hide the DOM element with the specified id.\n \n function hideElement ( id )\n {\n\tvar elt = myGetElement(id);\n\t\n\tif ( elt )\n\t{\n\t elt.style.display = 'none';\n\t visible[id] = 0;\n\t}\n }\n \n \n // Show the DOM elment with the specified id.\n\n function showElement ( id )\n {\n\tvar elt = myGetElement(id);\n\t\n\tif ( elt )\n\t{\n\t elt.style.display = '';\n\t visible[id] = 1;\n\t}\n }\n \n \n // // Show one element from a list, and hide the rest. The list is given by the argument\n // // 'values', prefixed by 'prefix'. The value corresponding to 'selected' specifies which\n // // element to show; the rest are hidden.\n \n // function showOneElement ( selected, prefix, values )\n // {\n // \tfor ( var i = 0; i < values.length; i++ )\n // \t{\n // \t var name = values[i].value;\n\t \n // \t if ( name == selected )\n // \t\tshowElement(prefix + name);\n\t \n // \t else\n // \t\thideElement(prefix + name);\n // \t}\n // }\n \n \n // Set the 'innerHTML' property of the specified element. If the specified content is not a\n // string, then the property is set to the empty string.\n \n function setInnerHTML ( id, content )\n {\n\tvar elt = myGetElement(id);\n\t\n\tif ( elt )\n\t{\n\t if ( typeof(content) != \"string\" )\n\t\telt.innerHTML = \"\";\n\t else\n\t\telt.innerHTML = content;\n\t}\n }\n \n \n // Set the 'src' property of the specified element.\n \n function setElementSrc ( id, value )\n {\n\tvar elt = myGetElement(id);\n\t\n\tif ( elt && typeof(value) == \"string\" ) elt.src = value;\n }\n \n \n // Set the 'value' property of the specified element.\n \n function setElementValue ( id, value )\n {\n\tvar elt = myGetElement(id);\n\t\n\tif ( elt && typeof(value) == \"string\" ) elt.value = value;\n }\n \n \n // Set the 'innerHTML' property of the specified element to a sequence of list items derived\n // from the elements of 'messages'. The first argument should be the identifier of a DOM <ul>\n // object, and the second should be an array of strings. If the second argument is undefined\n // or empty, then the list contents are set to the empty string. This function is used to\n // display or clear lists of error messages, in order to inform the application user about\n // improper values they have entered or other error conditions.\n \n function setErrorMessage ( id, messages )\n {\n\tif ( messages == undefined || messages == \"\" || messages.length == 0 )\n\t{\n\t setInnerHTML(id, \"\");\n\t hideElement(id);\n\t}\n\n\telse if ( typeof(messages) == \"string\" )\n\t{\n\t setInnerHTML(id, \"<li>\" + messages + \"</li>\");\n\t showElement(id);\n\t}\n\t\n\telse\n\t{\n\t var err_msg = messages.join(\"</li><li>\") || \"Error\";\n\t setInnerHTML(id, \"<li>\" + err_msg + \"</li>\");\n\t showElement(id);\n\t}\n }\n \n \n // Set the 'disabled' property of the specified DOM object to true or false, according to the\n // second argument.\n \n function setDisabled ( id, disabled )\n {\n\tvar elt = myGetElement(id);\n\t\n\tif ( elt ) elt.disabled = disabled;\n }\n \n \n // If the specified DOM object is of type \"checkbox\", then return the value of its 'checked'\n // attribute. Otherwise, return the value of its 'value' attribute.\n \n function getElementValue ( id )\n {\n\tvar elt = myGetElement(id);\n\t\n\tif ( elt && elt.type && elt.type == \"checkbox\" )\n\t return elt.checked;\n\t\n\telse if ( elt )\n\t return elt.value;\n\t\n\telse\n\t return \"\";\n }\n \n\n // If the specified DOM object is of type \"checkbox\" then set its 'checked' attribute to\n // false. Otherwise, set its 'value' attribute to the empty string.\n \n function clearElementValue ( id )\n {\n\tvar elt = myGetElement(id);\n\n\tif ( elt && elt.type && elt.type == \"checkbox\" )\n\t elt.checked = 0;\n\n\telse if ( elt )\n\t elt.value = \"\";\n }\n \n \n // The following function returns a list of the values of all checked elements from among\n // those with the specified name.\n \n function getCheckList ( list_name )\n {\n\tvar elts = document.getElementsByName(list_name);\n\tvar i;\n\tvar selected = [];\n\t\n\tfor ( i=0; i < elts.length; i++ )\n\t{\n\t if ( elts[i].checked ) selected.push(elts[i].value);\n\t}\n\t\n\treturn selected.join(',');\n }\n \n \n // ---------------------------------------------------------------------------------\n \n // The following routines check various parts of the user input. They are called from the\n // HTML side of this application when various form fields are modified. These routines set\n // properties of the javascript object 'params' to indicate good parameter values that should\n // be used to generate the main URL, and properties of the javascript object 'param_errors' to\n // indicate that the main URL should not be generated because of input errors. Each of these\n // routines ends by calling updateFormState to update the main URL.\n \n // The following function is called whenever any of the form elements \"pm_base_name\",\n // \"pm_ident\", or \"pm_pres\" in the section \"Select by Taxonomy\" are changed.\n \n function checkTaxon ( )\n {\n\t// Get the current value of each element. The values for 'ident' and 'pres' come from\n\t// dropdown menus and can be stored as-is.\n\t\n\tvar base_name = getElementValue(\"pm_base_name\");\n\tparams.ident = getElementValue(\"pm_ident\");\n\tparams.pres = getElementValue(\"pm_pres\");\n\t\n\t// Filter out spurious characters from the value of 'base_name'. Turn multiple\n\t// commas/whitespace into a single comma followed by a space, multiple ^ into a single ^\n\t// preceded by a space, and take out any sequence of non-alphabetic characters at the end\n\t// of the string.\n\t\n\tbase_name = base_name.replace(/[\\s,]*,[\\s,]*/g, \", \");\n\tbase_name = base_name.replace(/\\^\\s*/g, \" ^\");\n\tbase_name = base_name.replace(/\\^[\\s^]*/g, \"^\");\n\tbase_name = base_name.replace(/[\\s^]*\\^,[\\s,]*/g, \", \");\n\tbase_name = base_name.replace(/[^a-zA-Z:]+$/, \"\");\n\n\t// If the result is the same as the stored value of this field, then just call\n\t// 'updateFormState' without changing anything.\n\t\n\tif ( base_name == params.base_name )\n\t{\n\t updateFormState();\n\t}\n\n\t// Otherwise, if the value is empty, then clear the stored value and any error messages\n\t// associated with this field.\n\t\n\telse if ( base_name == \"\" )\n\t{\n\t params.base_name = \"\";\n\t param_errors.base_name = 0;\n\t setErrorMessage(\"pe_base_name\", \"\");\n\t updateFormState();\n\t}\n\n\t// Otherwise, we need to call the API to determine if the value(s) entered in this field\n\t// are actual taxonomic names known to the database.\n\t\n\telse\n\t{\n\t params.base_name = base_name;\n\t $.getJSON(data_url + 'taxa/list.json?name=' + base_name).done(callbackBaseName);\n\t}\n }\n \n this.checkTaxon = checkTaxon;\n \n \n // This is called when the API call for a new taxonomic name completes. If the result\n // includes any error or warning messages, display them to the user and set the 'base_name'\n // property of 'param_errors' to true. Otherwise, we know that the names were good so we\n // clear any messages that were previously displayed and set the property to false.\n \n function callbackBaseName ( response )\n {\n\tif ( response.warnings )\n\t{\n\t var err_msg = response.warnings.join(\"</li><li>\") || \"There is a problem with the API\";\n\t setErrorMessage(\"pe_base_name\", err_msg);\n\t param_errors.base_name = 1;\n\t}\n\t\n\telse if ( response.errors )\n\t{\n\t var err_msg = response.errors.join(\"</li><li>\") || \"There is a problem with the API\";\n\t setErrorMessage(\"pe_base_name\", err_msg);\n\t param_errors.base_name = 1;\n\t}\n\t\n\telse\n\t{\n\t setErrorMessage(\"pe_base_name\", \"\");\n\t param_errors.base_name = 0;\n\t}\n\t\n\tupdateFormState();\n }\n \n\n // This function is called when various fields in the \"Select by taxonomy\" section are\n // modified. The parameter 'changed' indicates which one has changed.\n \n function checkTaxonStatus ( changed )\n {\n\tvar accepted_box = myGetElement(\"pm_acc_only\");\n\tvar status_selector = myGetElement(\"pm_taxon_status\");\n\tvar variant_box = myGetElement(\"pm_taxon_variants\");\n\t\n\tif ( ! accepted_box || ! status_selector || ! variant_box ) return;\n\n\t// If the checkbox \"show accepted names only\" is now checked, then save the previous value\n\t// for the 'status_selector' dropdown and set it to \"accepted names\". If it is now\n\t// unchecked, then restore the previous dropdown value.\n\t\n\tif ( changed == 'accepted' )\n\t{\n if ( accepted_box.checked )\n {\n\t\ttaxon_status_save = status_selector.value;\n\t\tstatus_selector.value = \"accepted\";\n\t\tvariant_box.checked = false;\n }\n \n else\n {\n\t\tstatus_selector.value = taxon_status_save;\n }\n\t}\n\n\t// If the 'status_selector' dropdown is set to anything but \"accepted\", or if\n\t// 'variant_box' is checked, then uncheck 'accepted_box'.\n\t\n\telse if ( changed == 'selector' )\n\t{\n taxon_status_save = status_selector.value;\n if ( status_selector.value != \"accepted\" )\n\t\taccepted_box.checked = false;\n\t}\n\t\n\telse\n\t{\n if ( variant_box.checked )\n\t\taccepted_box.checked = false;\n\t}\n\t\n\tupdateFormState();\n }\n \n this.checkTaxonStatus = checkTaxonStatus;\n \n \n // This function is called when any of the taxon modifier options are changed.\n \n function checkTaxonMods ( )\n {\n\tvar idqual = getElementValue(\"pm_idqual\");\n\t\n\tif ( idqual == 'any' )\n\t{\n\t params.idqual = '';\n\t params.idgenmod = '';\n\t params.idspcmod = '';\n\t hideByClass('taxon_mods');\n\t}\n\t\n\telse if ( idqual == 'custom' )\n\t{\n\t params.idqual = '';\n\t showByClass('taxon_mods');\n\t checkTaxonCustom();\n\t}\n\t\n\telse\n\t{\n\t params.idqual = idqual;\n\t params.idgenmod = '';\n\t params.idspcmod = '';\n\t hideByClass('taxon_mods');\n\t}\n\t\n\tupdateFormState();\n }\n \n this.checkTaxonMods = checkTaxonMods;\n \n function checkTaxonCustom ( )\n {\n\tvar idgenmod = getCheckList(\"pm_idgenmod\");\n\tvar idspcmod = getCheckList(\"pm_idspcmod\");\n\tvar gen_ex = getElementValue(\"pm_genmod_ex\");\n\tvar spc_ex = getElementValue(\"pm_spcmod_ex\");\n\t\n\tif ( gen_ex && gen_ex == \"exclude\" && idgenmod )\n\t idgenmod = \"!\" + idgenmod;\n\t\n\tif ( spc_ex && spc_ex == \"exclude\" && idspcmod )\n\t idspcmod = \"!\" + idspcmod;\n\t\n\tparams.idgenmod = idgenmod;\n\tparams.idspcmod = idspcmod;\n }\n \n // This function is called when any of the abundance options is changed.\n\n function checkAbund ( )\n {\n\tvar abund_type = getElementValue(\"pm_abund_type\");\n\tvar abund_min = getElementValue(\"pm_abund_min\");\n\t\n\tvar abund_value = '';\n\t\n\tif ( abund_type && abund_type != 'none' )\n\t{\n\t abund_value = abund_type;\n\t \n\t if ( abund_min && abund_min != '' )\n\t {\n\t\tif ( patt_int_pos.test(abund_min) )\n\t\t{\n\t\t abund_value += ':' + abund_min;\n\t\t setErrorMessage(\"pe_abund_min\", \"\");\n\t\t param_errors.abundance = 0;\n\t\t}\n\t\t\n\t\telse\n\t\t{\n\t\t setErrorMessage(\"pe_abund_min\", \"Minimum abundance must be a positive integer\");\n\t\t param_errors.abundance = 1;\n\t\t}\n\t }\n\t params.abundance = abund_value;\n\t}\n\t\n\telse\n\t{\n\t params.abundance = \"\";\n\t}\n\t\n\tif ( abund_min == \"\" )\n\t{\n\t setErrorMessage(\"pe_abund_min\", \"\");\n\t param_errors.abundance = 0;\n\t}\n\t\n\tupdateFormState();\n }\n \n this.checkAbund = checkAbund;\n \n // This function is called when either of the main text fields in the \"Select by time\" section\n // are modified. The values might either be interval names or millions of years. It is also\n // called when the value of \"pm_timerule\" or \"pm_timebuffer\" changes. The parameter 'select'\n // will be 1 if the first text field was changed, 2 if the second.\n \n function checkInterval ( select )\n {\n\tvar int_age_1 = getElementValue(\"pm_interval\");\n\tvar int_age_2 = getElementValue(\"pm_interval_2\");\n\t\n\tvar errors = [ ];\n\t\n\tparams.timerule = getElementValue(\"pm_timerule\");\n\tparams.timebuffer = getElementValue(\"pm_timebuffer\");\n\t\n\t// First check the value of the first text field. If it is empty, then clear both of the\n\t// corresponding parameter properties.\n\t\n\tif ( int_age_1 == \"\" )\n\t{\n\t params.interval = \"\";\n\t params.ma_max = \"\";\n\t}\n\n\telse\n\t{\n\t // If it is a number, then set the property 'ma_max' and clear 'interval'. If the\n\t // other text field contains an interval name, clear it.\n\t \n\t if ( patt_dec_pos.test(int_age_1) )\n\t {\n\t\tparams.ma_max = int_age_1;\n\t\tparams.interval = \"\";\n\t\t\n\t\tif ( select && select == 1 && !patt_has_digit.test(int_age_2) )\n\t\t{\n\t\t clearElementValue(\"pm_interval_2\");\n\t\t int_age_2 = \"\";\n\t\t}\n\t }\n\t \n\t // If it contains a digit but is not a number, then the value is invalid.\n\t \n\t else if ( patt_has_digit.test(int_age_1) )\n\t\terrors.push(\"The string '\" + int_age_1 + \"' is not a valid age or interval\");\n\t \n\t // If it is the name of a known geologic time interval, then set the property\n\t // 'interval' and clear 'ma_max'. If the other text field contains a number, then\n\t // clear it.\n\t \n\t else if ( validInterval(int_age_1) )\n\t {\n\t\tparams.ma_max = \"\";\n\t\tparams.interval = int_age_1;\n\t\t\n\t\tif ( select && select == 1 && patt_has_digit.test(int_age_2) )\n\t\t{\n\t\t clearElementValue(\"pm_interval_2\");\n\t\t int_age_2 = \"\";\n\t\t}\n\t }\n\t \n\t // Otherwise, the value is not valid.\n\t \n\t else\n\t\terrors.push(\"The interval '\" + int_age_1 + \"' was not found in the database\");\n\t}\n\t\n\t// Repeat this process for the second text field.\n\t\n\tif ( int_age_2 == \"\" )\n\t{\n\t params.interval2 = \"\";\n\t params.ma_min = \"\";\n\t}\n\t\n\telse\n\t{\n\t if ( patt_dec_pos.test(int_age_2) )\n\t {\n\t\tparams.ma_min = int_age_2;\n\t\tparams.interval2 = \"\";\n\t\t\n\t\tif ( select && select == 2 && !patt_has_digit.test(int_age_1) )\n\t\t{\n\t\t clearElementValue(\"pm_interval\");\n\t\t params.ma_max = \"\";\n\t\t params.interval = \"\";\n\t\t}\n\t }\n\t \n\t else if ( patt_has_digit.test(int_age_2) )\n\t\terrors.push(\"The string '\" + int_age_2 + \"' is not a valid age or interval\");\n\t \n\t else if ( validInterval(int_age_2) )\n\t {\n\t\tparams.ma_min = \"\";\n\t\tparams.interval2 = int_age_2;\n\t\t\n\t\tif ( select && select == 2 && patt_has_digit.test(int_age_1) )\n\t\t{\n\t\t clearElementValue(\"pm_interval\");\n\t\t params.ma_max = \"\";\n\t\t params.interval = \"\";\n\t\t}\n\t }\n\t \n\t else\n\t\terrors.push(\"The interval '\" + int_age_2 + \"' was not found in the database\");\n\t}\n\t\n\t// If the text field values are numbers, check to make sure they were not entered in the\n\t// wrong order.\n\t\n\tif ( params.ma_max && params.ma_min && Number(params.ma_max) < Number(params.ma_min) )\n\t{\n\t errors.push(\"You must specify the maximum age on the left and the minimum on the right\");\n\t}\n\t\n\t// If the 'timebuffer' field is visible and has a value, check to make sure that it is a number.\n\t\n\tif ( visible.advanced )\n\t{\n\t if ( params.timerule == 'buffer' && params.timebuffer != \"\" && ! patt_dec_pos.test(params.timebuffer) )\n\t\terrors.push(\"invalid value '\" + params.timebuffer + \"' for timebuffer\");\n\t}\n\t\n\t// If we have discovered any errors so far, display them and set the appropriate property\n\t// of the 'param_errors' javascript object.\n\t\n\tif ( errors.length )\n\t{\n\t param_errors.interval = 1;\n\t setErrorMessage(\"pe_interval\", errors);\n\t}\n\n\t// Otherwise, clear them both.\n\t\n\telse\n\t{\n\t param_errors.interval = 0;\n\t setErrorMessage(\"pe_interval\", \"\");\n\t}\n\t\n\t// Adjust visibility of controls\n\t\n\tif ( params.timerule == 'buffer' )\n\t showByClass('buffer_rule');\n\t\n\telse\n\t hideByClass('buffer_rule');\n\t\n\t// Update the form state\n\t\n\tupdateFormState();\n }\n \n this.checkInterval = checkInterval;\n \n \n // Check whether the specified interval name is registered as a property of the javascript\n // object 'api_data.interval', disregarding case.\n \n function validInterval ( interval_name )\n {\n\tif ( typeof interval_name != \"string\" )\n\t return false;\n\t\n\tif ( api_data.interval[interval_name.toLowerCase()] )\n\t return true;\n\t\n\telse\n\t return false;\n }\n \n \n // This function is called when any of the fields in the \"Select by location\" section other\n // than the paleocoordinate selectors are modified.\n \n function checkCC ( )\n {\n\t// Get the value of the dropdown menus for selecting continents and countries. If the\n\t// value of either is '**', then show the full set of checkboxes for continents and the\n\t// \"multiple countries\" text field for countries.\n\t\n\tvar continent_select = getElementValue(\"pm_continent\");\n\tif ( continent_select == '**' ) showByClass('mult_cc3');\n\telse hideByClass('mult_cc3');\n\t\n\tvar country_select = getElementValue(\"pm_country\");\n\t// multiple_div = document.getElementById(\"pd_countries\");\n\tif ( country_select == '**' ) showByClass('mult_cc2');\n\telse hideByClass('mult_cc2');\n\t\n\tvar continent_list = '';\n\tvar country_list = '';\n\tvar errors = [ ];\n\tvar cc_ex = getElementValue(\"pm_ccex\");\n\tvar cc_mod = getElementValue(\"pm_ccmod\");\n\t\n\t// Get the selected continent or continents, if any\n\t\n\tif ( continent_select && continent_select != '--' && continent_select != '**' )\n\t continent_list = continent_select;\n\t\n\telse if ( continent_select && continent_select == '**' )\n\t{\n\t continent_list = getCheckList(\"pm_continents\");\n\t}\n\t\n\t// Get the selected country or countries, if any. If the user selected \"minus\" for the\n\t// value of pm_ccmod, then put a ^ before each country code.\n\t\n\tif ( country_select && country_select != '--' && country_select != '**' )\n\t{\n\t country_list = country_select;\n\t \n\t if ( cc_mod == \"sub\" ) country_list = '^' + country_list;\n\t}\n\n\t// If the user selected \"Multiple\", then look at the value of the \"multiple countries\"\n\t// text field. Split this into words, ignoring commas, spaces, and ^, and check to make\n\t// sure that each word is a valid country code.\n\t\n\telse if ( country_select && country_select == '**' )\n\t{\n\t country_list = getElementValue(\"pm_countries\");\n\t \n\t if ( country_list != '' )\n\t {\n\t\tvar cc_list = [ ];\n\t\tvar values = country_list.split(/[\\s,^]+/);\n\t\t\n\t\tfor ( var i=0; i < values.length; i++ )\n\t\t{\n\t\t var canonical = values[i].toUpperCase();\n\t\t // var key = canonical.replace(/^\\^/,'');\n\t\t \n\t\t // if ( key == '' ) next;\n\t\t \n\t\t // if ( cc_mod == \"sub\" ) canonical = \"^\" + canonical;\n\t\t \n\t\t if ( api_data.country_name[canonical] )\n\t\t {\n\t\t\tif ( cc_mod == \"sub\" ) cc_list.push(\"^\" + canonical);\n\t\t\telse cc_list.push(canonical);\n\t\t }\n\t\t \n\t\t else\n\t\t\terrors.push(\"Unknown country code '\" + canonical + \"'\");\n\t\t}\n\t\t\n\t\tcountry_list = cc_list.join(',');\n\t }\n\t}\n\t\n\tparams.cc = '';\n\n\t// If we have found a valid list of continents and/or a valid list of countries, set\n\t// the \"cc\" property of the javascript object 'params' to the entire list. Add a prefix\n\t// of \"!\" if the user selected \"exclude\" instead of \"include\".\n\t\n\tif ( country_list != '' || continent_list != '' )\n\t{\n\t var prefix = '';\n\t if ( cc_ex == \"exclude\" ) prefix = '!';\n\t \n\t if ( continent_list != '' && country_list != '' )\n\t\tparams.cc = prefix + continent_list + ',' + country_list;\n\t \n\t else\n\t\tparams.cc = prefix + continent_list + country_list;\n\t}\n\t\n\t// If we have detected any errors, display them and set the 'cc' property of the 'param_errors'\n\t// object. Otherwise, clear the error indicator and property.\n\t\n\tif ( errors.length )\n\t{\n\t setErrorMessage(\"pe_cc\", errors);\n\t param_errors.cc = 1;\n\t}\n\t\n\telse\n\t{\n\t setErrorMessage(\"pe_cc\", \"\");\n\t param_errors.cc = 0;\n\t}\n\t\n\t// Check to see if the user specified any states or counties. If so, add the appropriate parameters.\n\n\tvar state_list = getElementValue(\"pm_state\");\n\tvar county_list = getElementValue(\"pm_county\");\n\n\tvar state_ex = getElementValue(\"pm_state_ex\");\n\tvar county_ex = getElementValue(\"pm_county_ex\");\n\t\n\tvar state_errors = [ ];\n\t\n\tparams.state = '';\n\tparams.county = '';\n\t\n\tif ( state_list != '' )\n\t{\n\t var prefix = '';\n\t if ( state_ex == 'exclude' ) prefix = '!';\n\t params.state = prefix + state_list.trim();\n\n\t if ( ! params.cc )\n\t {\n\t\tstate_errors.push(\"You must select a country.\");\n\t }\n\t}\n\t\n\tif ( county_list != '' )\n\t{\n\t var prefix = '';\n\t if ( county_ex == 'exclude' ) prefix = '!';\n\t params.county = prefix + county_list.trim();\n\t \n\t if ( ! params.cc )\n\t {\n\t\tstate_errors.push(\"You must select a country.\");\n\t }\n\n\t if ( ! params.state )\n\t {\n\t\tstate_errors.push(\"You must select a state.\");\n\t }\n\t}\n\n\tif ( state_errors.length )\n\t{\n\t setErrorMessage(\"pe_state\", state_errors);\n\t param_errors.state = 1;\n\t}\n\t\n\telse\n\t{\n\t setErrorMessage(\"pe_state\", \"\");\n\t param_errors.state = 0;\n\t}\n\t\n\tupdateFormState();\n }\n \n this.checkCC = checkCC;\n \n \n // This function is called whenever any of the paleocoordinate selectors in the Location\n // section is modified.\n \n function checkPGM ( )\n {\n\t// Check to see if the user specified any tectonic plates. If so, validate the list and\n\t// adjust the objects 'params' and 'param_errors' accordingly.\n\t\n\tvar plate_list = getElementValue(\"pm_plate\");\n\tvar errors = [ ];\n\t\n\tif ( plate_list != '' )\n\t{\n\t var values = plate_list.split(/[\\s,]+/);\n\t var value_list = [ ];\n\t \n\t for ( var i=0; i < values.length; i++ )\n\t {\n\t\tvar value = values[i];\n\t\tif ( value == '' ) next;\n\t\t\n\t\tif ( /^[0-9]+$/.test(value) )\n\t\t value_list.push(value);\n\t\telse\n\t\t errors.push(\"Invalid plate number '\" + value + \"'\");\n\t }\n\t \n\t if ( value_list.length )\n\t\tparams.plate = value_list.join(',');\n\t \n\t else\n\t\tparams.plate = '';\n\t}\n\t\n\telse\n\t params.plate = '';\n\t\n\tparams.pg_model = getElementValue(\"pm_pg_model\");\n\tparams.pg_select = getElementValue(\"pm_pg_select\");\n\t\n\t// If a comparison model was selected, override the parameters set immediately above.\n\t\n\tvar alt_model = getElementValue(\"pm_pg_compare\");\n\t\n\tif ( alt_model == 'all' )\n\t params.pg_model = api_data.pg_models.join(',');\n\t\n\telse if ( alt_model )\n\t params.pg_model = params.pg_model + ',' + alt_model;\n\t\n\tvar alt_select = getElementValue(\"pm_pg_selcomp\");\n\t\n\tif ( alt_select == 'all' )\n\t params.pg_select = 'early,mid,late';\n\t\n\telse if ( alt_select )\n\t params.pg_select = params.pg_select + ',' + alt_select;\n\t\n\t// If we discovered any errors, display them. Otherwise, clear any messages that were\n\t// there before.\n\t\n\tif ( errors.length )\n\t{\n\t setErrorMessage(\"pe_plate\", errors);\n\t param_errors.plate = 1;\n\t}\n\t\n\telse\n\t{\n\t setErrorMessage(\"pe_plate\", \"\");\n\t param_errors.plate = 0;\n\t}\n\t\n\tupdateFormState();\n }\n \n this.checkPGM = checkPGM;\n \n\n // This function is called when any of the latitude/longitude fields are modified.\n \n function checkCoords ( )\n {\n\tvar latmin = getElementValue('pm_latmin');\n\tvar latmax = getElementValue('pm_latmax');\n\tvar lngmin = getElementValue('pm_lngmin');\n\tvar lngmax = getElementValue('pm_lngmax');\n\tvar errors = [];\n\t\n\t// Check for valid values in the coordinate fields\n\t\n\tif ( latmin == '' || validCoord(latmin, 'ns') ) params.latmin = cleanCoord(latmin);\n\telse {\n\t params.latmin = '';\n\t errors.push(\"invalid value '\" + latmin + \"' for minimum latitude\");\n\t}\n\t\n\tif ( latmax == '' || validCoord(latmax, 'ns') ) params.latmax = cleanCoord(latmax);\n\telse {\n\t params.latmax = '';\n\t errors.push(\"invalid value '\" + latmax + \"' for maximum latitude\");\n\t}\n\t\n\tif ( lngmin == '' || validCoord(lngmin, 'ew') ) params.lngmin = cleanCoord(lngmin);\n\telse {\n\t params.lngmin = '';\n\t errors.push(\"invalid value '\" + lngmin + \"' for minimum longitude\");\n\t}\n\t\n\tif ( lngmax == '' || validCoord(lngmax, 'ew') ) params.lngmax = cleanCoord(lngmax);\n\telse {\n\t params.lngmax = '';\n\t errors.push(\"invalid value '\" + lngmax + \"' for maximum longitude\");\n\t}\n\t\n\t// If only one longitude coordinate is filled in, ignore the other one.\n\t\n\tif ( lngmin && ! lngmax || lngmax && ! lngmin )\n\t{\n\t errors.push(\"you must specify both longitude values if you specify one of them\");\n\t}\n\t\n\t// If any of the parameters are in error, display the message and flag the error condition.\n\t\n\tif ( errors.length )\n\t{\n\t setErrorMessage('pe_coords', errors);\n\t param_errors.coords = 1;\n\t}\n\telse\n\t{\n\t // If the longitude coordinates are reversed, note that fact.\n\t \n\t if ( params.lngmin != '' && params.lngmax != '' &&\n\t\t coordsAreReversed(params.lngmin, params.lngmax) )\n\t {\n\t\tmessage = [ \"Note: the longitude coordinates are reversed. \" +\n\t\t\t \"This will select a strip stretching the long way around the earth.\" ]\n\t\tsetErrorMessage('pe_coords', message );\n\t }\n\t else setErrorMessage('pe_coords', null);\n\t \n\t // Clear the error flag in any case.\n\t \n\t param_errors.coords = 0;\n\t}\n\t\n\t// Update the main URL to reflect the changed coordinates.\n\t\n\tupdateFormState();\n }\n \n this.checkCoords = checkCoords;\n\n \n // Check whether the given value is a valid coordinate. The parameter 'dir' must be one of\n // 'ns' or 'ew', specifying which direction suffixes will be accepted.\n \n function validCoord ( coord, dir )\n {\n\tif ( coord == undefined )\n\t return false;\n\t\n\tif ( patt_dec_num.test(coord) )\n\t return true;\n\t\n\tif ( dir == 'ns' && /^(\\d+[.]\\d*|\\d*[.]\\d+|\\d+)[ns]$/i.test(coord) )\n\t return true;\n\t\n\tif ( dir === 'ew' && /^(\\d+[.]\\d*|\\d*[.]\\d+|\\d+)[ew]$/i.test(coord) )\n\t return true;\n\t\n\treturn false;\n }\n\n\n // Remove directional suffix, if any, and change to a signed number.\n \n function cleanCoord ( coord )\n {\n\tif ( coord == undefined || coord == '' )\n\t return '';\n\t\n\tif ( /^[+-]?(\\d+[.]\\d*|\\d*[.]\\d+|\\d+)$/.test(coord) )\n\t return coord;\n\t\n\tif ( /^(\\d+[.]\\d*|\\d*[.]\\d+|\\d+)[sw]$/i.test(coord) )\n\t return '-' + coord.replace(/[nsew]/i, '');\n\t\n\telse\n\t return coord.replace(/[nsew]/i, '');\n }\n \n\n // Return true if the given longitude values specify a region stretching more than 180 degrees\n // around the earth.\n \n function coordsAreReversed ( min, max )\n {\n\t// First convert the coordinates into signed integers.\n\t\n\tvar imin = Number(min);\n\tvar imax = Number(max);\n\t\n\treturn ( imax - imin > 180 || ( imax - imin < 0 && imax - imin > -180 ));\n }\n \n\n // This function is called when the geological strata input field from \"Select by geological\n // context\" is modified.\n \n function checkStrat ( )\n {\n\tvar strat = getElementValue(\"pm_strat\");\n\t\n\t// If the value contains at least one letter, try to look it up using the API.\n\t\n\tif ( strat && /[a-z]/i.test(strat) )\n\t{\n\t params.strat = strat;\n\t $.getJSON(data_url + 'strata/list.json?limit=0&rowcount&name=' + strat).done(callbackStrat);\n\t}\n\t\n\t// Otherwise, clear any error messages that may have been displayed previously and clear\n\t// the parameter value. \n\t\n\telse\n\t{\n\t params.strat = \"\";\n\t param_errors.strat = 0;\n\t setErrorMessage(\"pe_strat\", \"\");\n\t updateFormState();\n\t}\n }\n \n this.checkStrat = checkStrat;\n \n \n // This function is called when the API request to look up strata names returns. If any\n // records are returned, assume that at least some of the names are okay. We currently have\n // no way to determine which names match known strata and which do not, which is an\n // unfortunate limitation.\n \n function callbackStrat ( response )\n {\n\tif ( response.records_found )\n\t{\n\t setErrorMessage(\"pe_strat\", null);\n\t param_errors.strat = 0;\n\t}\n\t\n\telse\n\t{\n\t setErrorMessage(\"pe_strat\", [ \"no matching strata were found in the database\" ]);\n\t param_errors.strat = 1;\n\t}\n\t\n\tupdateFormState();\n }\n \n \n // This function is called when any of the Lithology form elements in the \"select by\n // geological context\" section are modified.\n \n function checkLith ( )\n {\n\tvar lith_ex = getElementValue(\"pm_lithex\");\n\tvar lith_type = getCheckList(\"pm_lithtype\");\n\t\n\tif ( lith_ex && lith_ex == \"exclude\" && lith_type && lith_type != \"\" )\n\t lith_type = \"!\" + lith_type;\n\t\n\tparams.lithtype = lith_type;\n\t\n\tupdateFormState();\n }\n \n this.checkLith = checkLith;\n \n // This function is called when any of the Environment form elements in the \"Select by\n // geological context\" section are modified.\n \n function checkEnv ( )\n {\n\tvar env_ex = getElementValue(\"pm_envex\");\n\tvar env_mod = getElementValue(\"pm_envmod\");\n\tvar env_type = getCheckList(\"pm_envtype\");\n\tvar env_zone = getCheckList(\"pm_envzone\");\n\t\n\tif ( env_ex && env_ex == \"exclude\" && env_type && env_type != \"\" )\n\t env_type = \"!\" + env_type;\n\t\n\tif ( env_mod && env_mod == \"sub\" )\n\t env_zone = \"^\" + env_zone.replace(/,/g, ',^');\n\t\n\tif ( env_zone )\n\t env_type += ',' + env_zone;\n\t\n\tparams.envtype = env_type;\n\t\n\tupdateFormState();\n }\n \n this.checkEnv = checkEnv;\n \n \n // This function is called whenever the \"created after\" or \"authorized/entered by\" form\n // elements in the \"Select by metadata\" section are modified, or when the corresponding text\n // fields are modified. The parameter 'section' indicates which row was modified, because\n // there may be more than one depending upon the data type currently selected.\n \n function checkMeta ( section )\n {\n\tvar errors = [];\n\t\n\t// The value of the \"..._cmdate\" field must match the pattern 'patt_date'.\n\t\n\tvar crmod_value = getElementValue(\"pm_\" + section + \"_crmod\");\n\tvar cmdate_value = getElementValue(\"pm_\" + section + \"_cmdate\");\n\t\n\tvar datetype = section + \"_crmod\";\n\tvar datefield = section + \"_cmdate\";\n\t\n\tif ( cmdate_value && cmdate_value != '' )\n\t{\n\t params[datetype] = crmod_value;\n\t params[datefield] = cmdate_value;\n\t \n\t if ( ! patt_date.test(cmdate_value) )\n\t {\n\t\tparam_errors[datefield] = 1;\n\t\terrors.push(\"Bad value '\" + cmdate_value + \"'\");\n\t }\n\t \n\t else\n\t {\n\t\tparam_errors[datefield] = 0;\n\t }\n\t}\n\t\n\telse\n\t{\n\t params[datetype] = crmod_value;\n\t params[datefield] = \"\";\n\t param_errors[datefield] = 0;\n\t}\n\t\n\t// Now we check the value of the \"..._aename\" field.\n\t\n\tvar authent_value = getElementValue(\"pm_\" + section + \"_authent\");\n\tvar aename_value = getElementValue(\"pm_\" + section + \"_aename\").trim();\n\t\n\tvar nametype = section + \"_authent\";\n\tvar namefield = section + \"_aename\";\n\tvar rebuild = [ ];\n\tvar exclude = '';\n\t\n\tif ( aename_value && aename_value != '' )\n\t{\n\t param_errors[namefield] = 0;\n\t \n\t // If the value starts with !, we have an exclusion. Pull it\n\t // out and save for the end when we are rebuilding the value\n\t // string.\n\t \n\t var expr = aename_value.match(/^!\\s*(.*)/);\n\t if ( expr )\n\t {\n\t\taename_value = expr[1];\n\t\texclude = '!';\n\t }\n\t \n\t // Split the field value on commas, and check each individual name.\n\t \n\t var names = aename_value.split(/,\\s*/);\n\t \n\t for ( var i = 0; i < names.length; i++ )\n\t {\n\t\t// Skip empty names, i.e. repeated commas.\n\t\t\n\t\tif ( ! names[i] ) continue;\n\t\t\n\t\t// If we cannot find the name, then search through all of\n\t\t// the known names to try for a match.\n\t\t\n\t\tif ( ! api_data.valid_name[names[i]] )\n\t\t{\n\t\t var check = names[i].toLowerCase().trim();\n\t\t var init = '';\n\t\t var subs;\n\t\t \n\t\t if ( subs = names[i].match(/^(\\w)\\w*[.]\\s*(.*)/) )\n\t\t {\n\t\t\tinit = subs[1].toLowerCase();\n\t\t\tcheck = subs[2].toLowerCase();\n\t\t }\n\t\t \n\t\t var matches = [];\n\t\t \n\t\t for ( var j = 0; j < api_data.user_match.length; j++ )\n\t\t {\n\t\t\tif ( check == api_data.user_match[j].substr(0,check.length) )\n\t\t\t{\n\t\t\t if ( init == '' || init == api_data.user_matchinit[j] )\n\t\t\t\tmatches.push(j);\n\t\t\t}\n\t\t }\n\t\t \n\t\t if ( matches.length == 0 )\n\t\t {\n\t\t\tparam_errors[namefield] = 1;\n\t\t\terrors.push(\"Unknown name '\" + names[i] + \"'\");\n\t\t\trebuild.push(names[i]);\n\t\t }\n\t\t \n\t\t else if ( matches.length > 1 )\n\t\t {\n\t\t\tparam_errors[namefield] = 1;\n\t\t\t\n\t\t\tvar result = api_data.user_names[matches[0]];\n\t\t\t\n\t\t\tfor ( var k = 1; k < matches.length; k++ )\n\t\t\t{\n\t\t\t result = result + \", \" + api_data.user_names[matches[k]];\n\t\t\t}\n\t\t\t\n\t\t\terrors.push(\"Ambiguous name '\" + names[i] + \"' matches: \" + result);\n\t\t\trebuild.push(names[i]);\n\t\t }\n\t\t \n\t\t else\n\t\t {\n\t\t\trebuild.push(api_data.user_names[matches[0]]);\n\t\t }\n\t\t}\n\t\t\n\t\telse\n\t\t{\n\t\t rebuild.push(names[i]);\n\t\t}\n\t }\n\t \n\t params[nametype] = authent_value;\n\t params[namefield] = exclude + rebuild.join(',');\n\t aename_value = exclude + rebuild.join(', ');\n\t}\n\t\n\telse\n\t{\n\t params[nametype] = authent_value;\n\t params[namefield] = \"\";\n\t param_errors[namefield] = 0;\n\t}\n\t\n\t// If we detected any errors, display them. Otherwise, clear any errors that were\n\t// displayed previously.\n\t\n\tif ( errors.length ) setErrorMessage(\"pe_meta_\" + section, errors);\n\telse setErrorMessage(\"pe_meta_\" + section, \"\");\n\t\n\tupdateFormState();\n }\n \n this.checkMeta = checkMeta;\n \n \n // This function is called when one of the free-text fields (currently only 'pm_coll_re') in\n // the \"Select by metadata\" section is modified. It simply stores the value in the\n // corresponding property of the 'params' object if it is not empty.\n \n function checkMetaText ( elt_name )\n {\n\tvar elt_value = getElementValue( 'pm_' + elt_name );\n\t\n\tif ( elt_value && elt_value != '' )\n\t params[elt_name] = elt_value;\n\t\n\telse\n\t{\n\t params[elt_name] = '';\n\t param_errors[elt_name] = 0;\n\t}\n\t\n\tupdateFormState();\n }\n \n this.checkMetaText = checkMetaText;\n \n \n // This function is called when one of the fields 'pm_meta_id_list' or 'pm_meta_id_select' is\n // modified. The parameter 'selector' indicates which one. The former of the two fields is\n // expected to hold one or more PBDB object identifiers, either numeric or extended.\n \n function checkMetaId ( selector )\n {\n\tvar id_list = getElementValue( 'pm_meta_id_list' );\n\tvar id_type = getElementValue( 'pm_meta_id_select' );\n\tvar id_param = id_param_map[id_type];\n\t\n\tif ( id_type == '' )\n\t{\n\t params[\"meta_id_list\"] = '';\n\t param_errors[\"meta_id\"] = 0;\n\t setErrorMessage(\"pe_meta_id\", \"\");\n\t}\n\t\n\telse\n\t{\n\t // Split the list on commas/whitespace.\n\t \n\t var id_strings = id_list.split(/[\\s,]+/);\n\t var id_key = { };\n\t var key_list = [ ];\n\t var param_list = [ ];\n\t var errors = [ ];\n\t \n\t // Check each identifier individually.\n\t \n\t for ( var i=0; i < id_strings.length; i++ )\n\t {\n\t\t// If it is an extended identifier, keep track of all the different\n\t\t// three-character prefixes we encounter while traversing the list using the\n\t\t// object 'id_key' and array 'key_list'.\n\t\t\n\t\tif ( patt_extid.test( id_strings[i] ) )\n\t\t{\n\t\t param_list.push(id_strings[i]);\n\t\t var key = id_strings[i].substr(0,3);\n\t\t \n\t\t if ( ! id_key[key] )\n\t\t {\n\t\t\tkey_list.push(key);\n\t\t\tid_key[key] = 1;\n\t\t }\n\t\t}\n\t\t\n\t\t// If it is a numeric identifier, just add it to the parameter list.\n\t\t\n\t\telse if ( patt_int_pos.test( id_strings[i] ) )\n\t\t{\n\t\t param_list.push(id_strings[i]);\n\t\t}\n\t\t\n\t\t// Anything else is an error.\n\t\t\n\t\telse if ( id_strings[i] != '' )\n\t\t{\n\t\t errors.push(\"invalid identifier '\" + id_strings[i] + '\"');\n\t\t}\n\t }\n\t \n\t // If we found more than one different identifier prefix, that is an error.\n\t \n\t if ( key_list.length > 1 )\n\t {\n\t\terrors.push(\"You may not specify identifiers of different types\");\n\t }\n\t \n\t // If we found any errors, display them.\n\t \n\t if ( errors.length )\n\t {\n\t\tparams[\"meta_id_list\"] = '';\n\t\tparam_errors[\"meta_id\"] = 1;\n\t\tsetErrorMessage(\"pe_meta_id\", errors);\n\t }\n\t \n\t // Otherwise, construct the proper parameter value by joining all of the identifiers\n\t // we found.\n\t \n\t else\n\t {\n\t\tparams[\"meta_id_list\"] = param_list.join(',');\n\t\t\n\t\t// If we found an extended-identifier prefix, then set the \"select\" element to the\n\t\t// corresponding item.\n\t\t\n\t\tif ( key_list.length == 1 )\n\t\t{\n\t\t id_param = id_param_map[key_list[0]];\n\t\t var select_index = id_param_index[key_list[0]];\n\t\t var select_elt = myGetElement(\"pm_meta_id_select\");\n\t\t if ( select_elt )\n\t\t {\n\t\t\tselect_elt.selectedIndex = select_index;\n\t\t }\n\t\t}\n\t\t\n\t\t// The variable 'id_param' was set from the selection dropdown, at the top of this\n\t\t// function. It indicates which parameter name to use, as a function of the\n\t\t// selected identifier type. For example, if the user selected \"Occurrence\" or at\n\t\t// least one of the identifiers started with \"occ:\", then the parameter name would\n\t\t// be \"occ_id\".\n\t\t\n\t\tif ( id_param )\n\t\t{\n\t\t params[\"meta_id_param\"] = id_param;\n\t\t param_errors[\"meta_id\"] = 0;\n\t\t setErrorMessage(\"pe_meta_id\", \"\");\n\t\t}\n\t\t\n\t\t// If for some reason we haven't found a proper parameter name, then display an\n\t\t// error message.\n\t\t\n\t\telse\n\t\t{\n\t\t params[\"meta_id_param\"] = '';\n\t\t param_errors[\"meta_id\"] = 1;\n\t\t setErrorMessage(\"pe_meta_id\", [\"Unknown identifier type '\" + id_param + \"'\"]);\n\t\t}\n\t }\n\t}\n\t\n\tupdateFormState();\n }\n \n this.checkMetaId = checkMetaId;\n \n \n // This function is called when either the 'pm_ref_select' dropdown menu or the value of the\n // 'pm_ref_value' field is changed.\n \n function checkRef ( )\n {\n\tvar ref_select = getElementValue( 'pm_ref_select' );\n\tvar ref_value = getElementValue( 'pm_ref_value' );\n\t\n\t// If the dropdown menu selection is 'ref_id', then we expect one or more identifiers as a\n\t// comma-separated list.\n\t\n\tif ( ref_select && ref_select == \"ref_id\" )\n\t{\n\t // Split the list on commas/whitespace.\n\t \n\t var id_strings = ref_value.split(/[\\s,]+/);\n\t var param_list = [ ];\n\t var errors = [ ];\n\t \n\t // Check each identifier individually.\n\t \n\t for ( var i=0; i < id_strings.length; i++ )\n\t {\n\t\t// If it is an extended identifier, keep track of all the different\n\t\t// three-character prefixes we encounter while traversing the list using the\n\t\t// object 'id_key' and array 'key_list'.\n\t\t\n\t\tif ( /^ref[:]\\d+$/.test( id_strings[i] ) )\n\t\t{\n\t\t param_list.push(id_strings[i]);\n\t\t}\n\t\t\n\t\t// If it is a numeric identifier, just add it to the parameter list.\n\t\t\n\t\telse if ( patt_int_pos.test( id_strings[i] ) )\n\t\t{\n\t\t param_list.push('ref:' + id_strings[i]);\n\t\t}\n\t\t\n\t\t// Anything else is an error.\n\t\t\n\t\telse if ( id_strings[i] != '' )\n\t\t{\n\t\t errors.push(\"invalid reference identifier '\" + id_strings[i] + '\"');\n\t\t}\n\t }\n\t \n\t // If we found any errors, display them.\n\t \n\t if ( errors.length )\n\t {\n\t\tparams[\"meta_ref_value\"] = '';\n\t\tparams[\"meta_ref_select\"] = '';\n\t\tparam_errors[\"meta_ref\"] = 1;\n\t\tsetErrorMessage(\"pe_meta_ref\", errors);\n\t }\n\t \n\t // Otherwise, construct the proper parameter value by joining all of the identifiers\n\t // we found.\n\t \n\t else\n\t {\n\t\tif ( param_list.length )\n\t\t{\n\t\t params[\"meta_ref_value\"] = param_list.join(',');\n\t\t params[\"meta_ref_select\"] = 'ref_id';\n\t\t}\n\t\t\n\t\telse\n\t\t{\n\t\t params[\"meta_ref_value\"] = '';\n\t\t params[\"meta_ref_select\"] = '';\n\t\t}\n\t\t\n\t\tsetErrorMessage(\"pe_meta_ref\", \"\");\n\t\tparam_errors[\"meta_ref\"] = 0;\n\t }\n\t}\n\t\n\telse if ( ref_select && ref_param[ref_select] )\n\t{\n\t if ( ref_value != undefined && ref_value != '' )\n\t {\n\t\tparams[\"meta_ref_value\"] = ref_value;\n\t\tparams[\"meta_ref_select\"] = ref_select;\n\t }\n\n\t else\n\t {\n\t\tparams[\"meta_ref_value\"] = '';\n\t\tparams[\"meta_ref_select\"] = '';\n\t }\n\t \n\t param_errors[\"meta_ref\"] = 0;\n\t setErrorMessage(\"pe_meta_ref\", '');\n\t}\n\t\n\telse\n\t{\n\t params[\"meta_ref_select\"] = '';\n\t params[\"meta_ref_value\"] = '';\n\t param_errors[\"meta_ref\"] = 0;\n\t setErrorMessage(\"pe_meta_ref\", \"\");\n\t}\n\t\n\tupdateFormState();\n\t\n\t// var ref_select = myGetElement(\"pm_ref_select\");\n\t\n\t// if ( ref_select )\n\t// {\n\t// var selected = ref_select.value;\n\t \n\t// }\n }\n \n this.checkRef = checkRef;\n \n \n // This function is called when the \"include metadata\" checkbox in the \"Choose output options\"\n // section is modified.\n \n function checkOutputOpts ( )\n {\n\tvar metadata_elt = myGetElement(\"pm_output_metadata\");\n\tparams.output_metadata = metadata_elt.checked;\n\t\n\tupdateFormState();\n }\n \n this.checkOutputOpts = checkOutputOpts;\n \n \n // This function is called when one of the \"Output order\" dropdowns in the \"Choose output\n // options\" section is modified. The 'selection' parameter indicates which one. I'm not\n // actually sure this does anything useful at this point.\n \n function checkOrder ( selection )\n {\n\tif ( selection && selection != 'dir' )\n\t{\n\t var order_elt = myGetElement(\"pm_order_dir\");\n\t if ( order_elt ) order_elt.value = '--';\n\t}\n\t\n\tupdateFormState();\n }\n \n this.checkOrder = checkOrder;\n \n \n // This function is called if the \"include all boldfaced output blocks\" element in the \"Output\n // options\" section is modified.\n \n function checkFullOutput ( )\n {\n\tvar full_value = getElementValue(\"pm_fulloutput\");\n\tvar elts = document.getElementsByName(output_section);\n\tvar i;\n\t\n\tfull_checked[output_section] = full_value;\n\t\n\tfor ( i=0; i<elts.length; i++ )\n\t{\n\t var block_code = elts[i].value;\n\t \n\t if ( output_full[output_section][block_code] )\n\t {\n\t\tif ( full_value ) elts[i].checked = 1;\n\t\telse elts[i].checked = 0;\n\t }\n\t}\n\n\tupdateFormState();\n }\n \n this.checkFullOutput = checkFullOutput;\n \n \n // This function is called if the \"reference types\" checkboxes are modified. These are only\n // visible for certain record types.\n \n function checkRefopts ( )\n {\n \tparams.reftypes = getCheckList(\"pm_reftypes\");\n \tif ( params.reftypes == \"auth,class\" ) params.reftypes = 'taxonomy';\n \telse if ( params.reftypes == \"auth,class,ops\" ) params.reftypes = 'auth,ops';\n \telse if ( params.reftypes == \"auth,class,ops,occs,colls\" ) params.reftypes = 'all'\n \telse if ( params.reftypes == \"auth,ops,occs,colls\" ) params.reftypes = 'all'\n \tupdateFormState();\n }\n \n this.checkRefopts = checkRefopts;\n \n \n // This function is called when the \"Limit number of records\" field in the \"Choose output\n // options\" section is modified.\n \n function checkLimit ( )\n {\n\tvar limit = getElementValue(\"pm_limit\");\n\t\n\tif ( limit == \"\" )\n\t{\n\t param_errors.limit = 0;\n\t params.offset = '';\n\t params.limit = '';\n\t setErrorMessage(\"pe_limit\", \"\");\n\t updateFormState();\n\t return;\n\t}\n\t\n\t// The value can either be one number, or two separated by commas. In the second case,\n\t// the first will be taken as an offset and the second as a limit.\n\t\n\tvar matches = limit.match(/^\\s*(\\d+)(\\s*,\\s*(\\d+))?\\s*$/);\n\t\n\tif ( matches )\n\t{\n\t param_errors.limit = 0;\n\t setErrorMessage(\"pe_limit\", \"\");\n\t \n\t if ( matches[3] )\n\t {\n\t\tparams.offset = matches[1];\n\t\tparams.limit = matches[3];\n\t }\n\t \n\t else\n\t {\n\t\tparams.offset = '';\n\t\tparams.limit = matches[1];\n\t }\n\t}\n\t\n\telse\n\t{\n\t param_errors.limit = 1;\n\t params.offset = 'x';\n\t params.limit = 'x';\n\t setErrorMessage(\"pe_limit\", [\"Invalid limit '\" + limit + \"'\"]);\n\t}\n\t\n\tupdateFormState();\n }\n \n this.checkLimit = checkLimit;\n\n\n // This function is called if the \"Archive title\" field is modified, or if the archive section\n // is hidden or shown.\n \n function checkArchive ( )\n {\n\tvar title = getElementValue(\"arc_title\");\n\tvar btn = myGetElement(\"btn_download\");\n\t\n\tif ( title && visible.o2 )\n\t{\n\t btn.textContent = \"Create Archive\";\n\t btn.onclick = archiveMainURL;\n\t}\n\t\n\telse\n\t{\n\t btn.textContent = \"Download\";\n\t btn.onclick = downloadMainURL;\n\t}\n }\n \n this.checkArchive = checkArchive;\n \n // This function is called whenever some element changes that could change the overall state\n // of the application. The only thing it currently does is to update the main URL, but other\n // things could be added later.\n \n function updateFormState ( )\n {\n\tif ( ! no_update ) updateMainURL();\n }\n \n this.updateFormState = updateFormState;\n \n \n // The following function provides the core functionality for this application. It is called\n // whenever any form element changes, and updates the \"main URL\" element to reflect the\n // changes. This main URL can then be used to download data.\n \n // Many of the form elements are not queried directly. Rather, the properties of the\n // javascript object 'parameters' are updated whenever any of these elements change value, and\n // these properties are used in the function below to generate the URL. The properties of the\n // object 'param_errors' are used to indicate whether any errors were found when the values\n // were checked. Only elements requiring no interpretation or checking are queried directly.\n \n // Only the form elements in visible sections are used. Any section that is collapsed (not\n // visible) is ignored. However, if it is opened again then this function will be immediately\n // called and the values entered there will be applied to the main URL. The properties of the\n // javascript object 'visible' keep track of what is visible and what is hidden.\n \n function updateMainURL ( )\n {\n\t// The following variable keeps track of the parameters and values that make up the URL.\n\t\n\tvar param_list = [ ];\n\t\n\t// The following variable will be set to true if a \"significant parameter\" is specified.\n\t// Otherwise, the main URL will not be generated. Such parameters include the taxonomic\n\t// name, time interval, stratum, etc. In other words, some parameter that will\n\t// substantially restrict the result set. The \"select all records\" checkbox also counts,\n\t// just in case somebody really wants to download all records of a particular type.\n\t\n\tvar has_main_param = 0;\n\n\t// The following variable will be set to true if any errors are encountered in association\n\t// with a visible form element. This will prevent the main URL from being generated.\n\t\n\tvar errors_found = 0;\n\n\t// The following variables indicate that an occurrence operation or a taxon operation must\n\t// be generated instead of the default operation for the selected record type.\n\t\n\tvar occs_required = 0;\n\tvar taxon_required = 0;\n\t\n\t// The following variable indicates that an operation that takes reference parameters must\n\t// be generated instead of the default operation for the selected record type.\n\t\n\tvar refs_required = 0;\n\n\t// The following variable indicates that we should use the 'refs/list' operation instead\n\t// of 'taxa/refs'.\n\t\n\tvar use_ref_list = 0;\n\t\n\t// The following variable is set to true if certain form elements are filled in, to\n\t// indicate that the \"all_records\" parameter must be added in order to satisfy the\n\t// requirements of the API.\n\t\n\tvar all_required = 0;\n\t\n\t// If true, the parameter \"pgm\" has already been added to the list.\n\t\n\tvar need_pgm = 0;\n\t\n\t// The following variable indicates the API operation (i.e. \"occs/list\", \"taxa/list\",\n\t// etc.) to be used. It is set from the default operation for the selected record type,\n\t// but may be modified under certain circumstances.\n\t\n\tvar my_op = data_op;\n\t\n\t// If the \"Select by taxonomy\" section is visible, then go through the parameters it\n\t// contains. If the \"advanced\" parameters are visible, then check them too.\n\t\n\tif ( visible.f1 )\n\t{\n\t if ( params.base_name && params.base_name != \"\" ) {\n\t\tparam_list.push(\"base_name=\" + params.base_name);\n\t\thas_main_param = 1;\n\t\ttaxon_required = 1;\n\t }\n\t \n\t if ( param_errors.base_name ) errors_found = 1;\n\t \n\t if ( data_type == \"occs\" || data_type == \"specs\" || data_type == \"meas\" ||\n\t\t data_type == \"colls\" || data_type == \"strata\" || data_type == \"diversity\" )\n\t {\n\t\t// The \"taxonomic resolution\" parameter is different for diversity than for the\n\t\t// other data types.\n\t\t\n\t\tif ( data_type == \"diversity\" )\n\t\t{\n\t \t var taxonres = getElementValue(\"pm_div_count\");\n\t \t if ( taxonres && taxonres != \"\" )\n\t \t\tparam_list.push(\"count=\" + taxonres);\n\t\t}\n\t\t\n\t\telse\n\t\t{\n\t\t var taxonres = getElementValue(\"pm_taxon_reso\");\n\t\t if ( taxonres && taxonres != \"\" )\n\t\t\tparam_list.push(\"taxon_reso=\" + taxonres);\n\t\t}\n\t\t\n\t\t// The advanced parameters are treated the same for all of these types.\n\t\t\n\t\tif ( visible.advanced )\n\t\t{\n\t\t if ( params.ident && params.ident != 'latest' )\n\t\t\tparam_list.push(\"ident=\" + params.ident);\n\t\t \n\t\t if ( params.idqual )\n\t\t\tparam_list.push(\"idqual=\" + params.idqual);\n\t\t \n\t\t if ( params.idgenmod || params.idspcmod )\n\t\t {\n\t\t\tif ( params.idgenmod == params.idspcmod )\n\t\t\t param_list.push(\"idmod=\" + params.idgenmod);\n\t\t\t\n\t\t\telse\n\t\t\t{\n\t\t\t if ( params.idgenmod )\n\t\t\t\tparam_list.push(\"idgenmod=\" + params.idgenmod);\n\t\t\t \n\t\t\t if ( params.idspcmod )\n\t\t\t\tparam_list.push(\"idspcmod=\" + params.idspcmod);\n\t\t\t}\t\t\t\n\t\t }\n\t\t}\n\t }\n\t \n\t else if ( data_type == \"taxa\" || data_type == \"ops\" || data_type == \"refs\" )\n\t {\n\t\tvar taxon_rank = getElementValue(\"pm_taxon_rank\");\n\t\t\n\t\tif ( taxon_rank && taxon_rank != '--' )\n\t\t param_list.push(\"rank=\" + taxon_rank);\n\t\t\n\t\tvar taxon_status = getElementValue(\"pm_taxon_status\");\n\t\t\n\t\tif ( taxon_status )\n\t\t param_list.push(\"taxon_status=\" + taxon_status);\n\t\t\n\t\tvar taxon_variants = getElementValue(\"pm_taxon_variants\");\n\t\t\n\t\tif ( visible.advanced && taxon_variants )\n\t\t param_list.push(\"variant=all\");\n\t }\n\t \n\t if ( visible.advanced && params.pres && params.pres != 'all' )\n\t\tparam_list.push(\"pres=\" + params.pres);\n\t}\n\t\n\t// If the \"Select by time\" section is visible, then go through the parameters it\n\t// contains. If the \"advanced\" parameters are visible, then check them too.\n\t\n\tif ( visible.f2 )\n\t{\n\t var intervals = [ ];\n\t var has_time_param;\n\t \n\t if ( params.interval && params.interval != \"\" )\n\t\tintervals.push(params.interval);\n\t if ( params.interval2 && params.interval2 != \"\" )\n\t\tintervals.push(params.interval2);\n\t \n\t if ( intervals.length )\n\t {\n\t\tparam_list.push(\"interval=\" + intervals.join(','));\n\t\thas_main_param = 1;\n\t\thas_time_param = 1;\n\t\toccs_required = 1;\n\t }\n\t \n\t else\n\t {\n\t\tif ( params.ma_max )\n\t\t{\n\t\t param_list.push(\"max_ma=\" + params.ma_max);\n\t\t has_main_param = 1;\n\t\t has_time_param = 1;\n\t\t occs_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.ma_min )\n\t\t{\n\t\t param_list.push(\"min_ma=\" + params.ma_min);\n\t\t has_main_param = 1;\n\t\t has_time_param = 1;\n\t\t occs_required = 1;\n\t\t}\n\t }\n\t \n\t if ( param_errors.interval ) errors_found = 1;\n\t \n\t if ( data_type == 'diversity' )\n\t {\n\t\thas_time_param = 1;\n\t\t\n\t\tvar timeres = getElementValue(\"pm_div_time\");\n\t\t\n\t\tif ( timeres && timeres != \"stage\" )\n\t\t param_list.push(\"time_reso=\" + timeres);\n\t\t\n\t\tvar recent = getElementValue(\"pm_div_recent\");\n\t\tif ( recent )\n\t\t param_list.push(\"recent\");\n\t }\n\t \n\t if ( visible.advanced ) {\n\t\tif ( params.timerule && params.timerule != 'major' && has_time_param ) {\n\t\t param_list.push(\"time_rule=\" + params.timerule);\n\t\t if ( params.timebuffer && params.timerule == 'buffer' )\n\t\t\tparam_list.push(\"time_buffer=\" + params.timebuffer);\n\t\t}\n\t }\n\t}\n\n\t// If the section \"Select by location\" is visible, then go through the parameters it\n\t// contains. If the \"advanced\" parameters are visible, then check them too.\n\t\n\tif ( visible.f3 )\n\t{\n\t if ( params.cc && params.cc != \"\" )\n\t {\n\t\tparam_list.push(\"cc=\" + params.cc);\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\n\t if ( params.state && params.state != \"\" )\n\t {\n\t\tparam_list.push(\"state=\" + params.state);\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\n\t if ( params.county && params.county != \"\" )\n\t {\n\t\tparam_list.push(\"county=\" + params.county);\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\t \n\t if ( visible.advanced && params.plate && params.plate != \"\" )\n\t {\n\t\tparam_list.push(\"plate=\" + params.plate);\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t\tneed_pgm = 1;\n\t }\n\t \n\t if ( visible.advanced && (param_errors.cc || param_errors.state || param_errors.plate) )\n\t\terrors_found = 1;\n\t \n\t if ( params.latmin || params.latmax || params.lngmin || params.lngmax )\n\t {\n\t\tif ( params.lngmin ) param_list.push(\"lngmin=\" + params.lngmin);\n\t\tif ( params.lngmax ) param_list.push(\"lngmax=\" + params.lngmax);\n\t\tif ( params.latmin ) param_list.push(\"latmin=\" + params.latmin);\n\t\tif ( params.latmax ) param_list.push(\"latmax=\" + params.latmax);\n\t\t\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\t \n\t if ( param_errors.coords ) errors_found = 1;\n\t}\n\t\n\t// If the section \"Select by geological context\" is visible, then go through the\n\t// parameters it contains. If the \"advanced\" parameters are visible, then check them too.\n\t\n\tif ( visible.f4 )\n\t{\n\t if ( params.strat && params.strat != \"\" ) {\n\t\tparam_list.push(\"strat=\" + params.strat);\n\t\toccs_required = 1;\n\t\thas_main_param = 1\n\t }\n\t \n\t if ( param_errors.strat ) errors_found = 1;\n\t \n\t if ( visible.advanced && params.lithtype && params.lithtype != \"\" ) {\n\t\tparam_list.push(\"lithology=\" + params.lithtype);\n\t\toccs_required = 1;\n\t }\n\t \n\t if ( visible.advanced && params.envtype && params.envtype != \"\" ) {\n\t\tparam_list.push(\"envtype=\" + params.envtype);\n\t\toccs_required = 1;\n\t }\n\t}\n\t\n\t// If the section \"Select by specimen is visible, then go through the parameters it contains.\n\t\n\tif ( visible.f6 )\n\t{\n\t if ( params.abundance )\n\t {\n\t\tif ( param_errors.abundance ) errors_found = 1;\n\t\tparam_list.push(\"abundance=\" + params.abundance );\n\t\toccs_required = 1;\n\t }\n\t}\n\t\n\t// If the section \"Select by metadata\" is visible, then go through the parameters it\n\t// contains. Only some of the rows will be visible, depending on the selected record type.\n\t\n\tif ( visible.f5 )\n\t{\n\t if ( params.coll_re ) {\n\t\tparam_list.push(\"coll_re=\" + params.coll_re);\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\t \n\t if ( param_errors.coll_re ) errors_found = 1;\n\t \n\t if ( params.meta_id_list ) {\n\t\tparam_list.push(params.meta_id_param + \"=\" + params.meta_id_list);\n\t\toccs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\t \n\t if ( param_errors.meta_id ) errors_found = 1;\n\t \n\t if ( params.meta_ref_select ) {\n\t\tif ( param_list.length == 0 ) use_ref_list = 1;\n\t\tparam_list.push(params.meta_ref_select + '=' + params.meta_ref_value);\n\t\trefs_required = 1;\n\t\thas_main_param = 1;\n\t }\n\t \n\t if ( param_errors.meta_ref ) errors_found = 1;\n\t \n\t if ( visible.meta_specs )\n\t {\n\t\tif ( params.specs_cmdate ) {\n\t\t param_list.push(\"specs_\" + params.specs_crmod + \"=\" + params.specs_cmdate);\n\t\t occs_required = 1;\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.specs_aename ) {\n\t\t param_list.push(\"specs_\" + params.specs_authent + \"=\" + params.specs_aename);\n\t\t occs_required = 1\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( param_errors.specs_cmdate || param_errors.specs_aename ) errors_found = 1;\n\t }\n\t \n\t if ( visible.meta_occs )\n\t {\n\t\tif ( params.occs_cmdate ) {\n\t\t param_list.push(\"occs_\" + params.occs_crmod + \"=\" + params.occs_cmdate);\n\t\t occs_required = 1;\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.occs_aename ) {\n\t\t param_list.push(\"occs_\" + params.occs_authent + \"=\" + params.occs_aename);\n\t\t occs_required = 1\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( param_errors.occs_cmdate || param_errors.occs_aename ) errors_found = 1;\n\t }\n\t \n\t if ( visible.meta_colls )\n\t {\n\t\tif ( params.colls_cmdate ) {\n\t\t param_list.push(\"colls_\" + params.colls_crmod + \"=\" + params.colls_cmdate);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.colls_aename ) {\n\t\t param_list.push(\"colls_\" + params.colls_authent + \"=\" + params.colls_aename);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( param_errors.colls_cmdate || param_errors.colls_aename ) errors_found = 1;\n\t }\n\t \n\t if ( visible.meta_taxa )\n\t {\n\t\tif ( params.taxa_cmdate ) {\n\t\t param_list.push(\"taxa_\" + params.taxa_crmod + \"=\" + params.taxa_cmdate);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.taxa_aename ) {\n\t\t param_list.push(\"taxa_\" + params.taxa_authent + \"=\" + params.taxa_aename);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( param_errors.taxa_cmdate || param_errors.taxa_aename ) errors_found = 1;\n\t }\n\t \n\t if ( visible.meta_ops )\n\t {\n\t\tif ( params.ops_cmdate ) {\n\t\t param_list.push(\"ops_\" + params.ops_crmod + \"=\" + params.ops_cmdate);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.ops_aename ) {\n\t\t param_list.push(\"ops_\" + params.ops_authent + \"=\" + params.ops_aename);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( param_errors.ops_cmdate || param_errors.ops_aename ) errors_found = 1;\n\t }\n\t \n\t if ( visible.meta_refs )\n\t {\n\t\tif ( params.refs_cmdate ) {\n\t\t param_list.push(\"refs_\" + params.refs_crmod + \"=\" + params.refs_cmdate);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( params.refs_aename ) {\n\t\t param_list.push(\"refs_\" + params.refs_authent + \"=\" + params.refs_aename);\n\t\t all_required = 1;\n\t\t}\n\t\t\n\t\tif ( param_errors.refs_cmdate || param_errors.refs_aename ) errors_found = 1;\n\t }\n\t}\n\t\n\t// If the selected record type is either references or taxa selected by reference or\n\t// opinions, then add the appropriate parameter using the form element that appears just\n\t// above the\"Select by taxonomy\" section.\n\t\n\tif ( data_type == 'refs' || data_type == 'byref' )\n\t{\n\t if ( params.reftypes && params.reftypes != \"\" && ! use_ref_list ) {\n\t\tparam_list.push(\"select=\" + params.reftypes);\n\t }\n\t}\n\t\n\telse if ( data_type == \"ops\" )\n\t{\n\t var op_select = getElementValue(\"pm_op_select\");\n\t if ( op_select )\n\t\tparam_list.push(\"op_type=\" + op_select);\n\t}\n\n\t// If \"include non-public data\" is selected, add the parameter 'private'.\n\t\n\tif ( params.private && is_contributor )\n\t{\n\t param_list.push(\"private\");\n\t}\n\t\n\t// If the section \"output options\" is visible, then go through the parameters it contains.\n\t// This includes specifying which output blocks to return using the \"show\" parameter.\n\t\n\tif ( visible.o1 )\n\t{\n\t var output_list = getOutputList();\n\t \n\t if ( paleoloc_all || paleoloc_selected )\n\t {\n\t\tneed_pgm = 0;\n\t\t\n\t\tif ( paleoloc_all )\n\t\t param_list.push(\"pgm=\" + api_data.pg_models.join(','));\n\t\t\n\t\telse\n\t\t param_list.push(\"pgm=\" + params.pg_model);\n\t\t\n\t\tif ( params.pg_select != \"mid\" )\n\t\t param_list.push(\"pgs=\" + params.pg_select);\n\t }\n\t \n\t if ( ! occs_required )\n\t\toutput_list = output_list.replace(/occapp,?/, 'app,');\n\t if ( output_list ) param_list.push(\"show=\" + output_list);\n\t \n\t var order_expr = getElementValue(output_order);\n\t var order_dir = getElementValue(\"pm_order_dir\");\n\t \n\t if ( order_expr && order_expr != '--' )\n\t {\n\t\tif ( order_expr == 'authpub' )\n\t\t{\n\t\t if ( order_dir && order_dir == 'asc' )\n\t\t\tparam_list.push(\"order=author,pubyr.asc\");\n\t\t else\n\t\t\tparam_list.push(\"order=author,pubyr.desc\");\n\t\t}\n\t\t\n\t\telse if ( order_expr == 'pubauth' )\n\t\t{\n\t\t if ( order_dir && order_dir == 'asc' )\n\t\t\tparam_list.push(\"order=pubyr.asc,author\");\n\t\t else\n\t\t\tparam_list.push(\"order=pubyr.desc,author\");\n\t\t}\n\t\t\n\t\telse\n\t\t{\n\t\t if ( order_dir && order_dir != '--' )\n\t\t\torder_expr = order_expr + '.' + order_dir;\n\t\t param_list.push(\"order=\" + order_expr);\n\t\t}\n\t }\n\t \n\t if ( params.offset ) param_list.push(\"offset=\" + params.offset);\n\t if ( params.limit ) param_list.push(\"limit=\" + params.limit);\n\n\t if ( param_errors.limit ) errors_found = 1;\n\t}\n\t\n\t// Otherwise, add \"show=acconly\" if indicated by the \"accepted names only\" checkbox\n\t// in the \"Select by taxonomy\" section.\n\t\n\telse if ( (data_type == 'occs' || data_type == 'specs' ) && visible.f1)\n\t{\n\t var acc_only = myGetElement(\"pm_acc_only\");\n\t if ( acc_only && acc_only.checked )\n\t\tparam_list.push('show=acconly');\n\t}\n\t\n\t// If we still need a \"pgm=\" parameter, add it now.\n\t\n\tif ( need_pgm )\n\t param_list.push(\"pgm=\" + params.pg_model);\n\t\n\t// Now alter the operation, if necessary, based on the chosen parameters\n\t\n\tif ( occs_required )\n\t{\n\t if ( my_op == 'taxa/list' ) my_op = 'occs/taxa';\n\t else if ( my_op == 'taxa/refs' ) my_op = 'occs/refs';\n\t else if ( my_op == 'taxa/byref' ) my_op = 'occs/taxabyref';\n\t else if ( my_op == 'opinions/list' ) my_op = 'occs/opinions';\n\t}\n\t\n\telse if ( taxon_required )\n\t{\n\t if ( my_op == 'opinions/list' ) my_op = 'taxa/opinions';\n\t}\n\n\tif ( refs_required )\n\t{\n\t if ( my_op == 'occs/list' ) { my_op = 'occs/byref'; all_required = 1; }\n\t else if ( my_op == 'colls/list' ) { my_op = 'colls/byref'; all_required = 1; }\n\t else if ( my_op == 'taxa/list' ) my_op = 'taxa/byref';\n\t else if ( my_op == 'occs/taxa' ) { my_op = 'occs/taxabyref'; all_required = 1; }\n\t else if ( my_op == 'opinions/list' ) { my_op = 'taxa/opinions'; all_required = 1; }\n\t else if ( my_op == 'specs/list' ) { my_op = 'specs/byref'; all_required = 1; }\n\t else if ( my_op == 'strata/list' ) { my_op = 'occs/strata'; all_required = 1; }\n\t else if ( my_op == 'taxa/refs' && use_ref_list ) my_op = 'refs/list';\n\t}\n\t\n\t// If no \"significant\" parameter has been entered, then see if we need to add the\n\t// parameter 'all_records' in order to satisfy the requirements of the API.\n\t\n\tif ( all_required || ! has_main_param )\n\t{\n\t var all_records_elt = myGetElement(\"pm_all_records\");\n\n\t // If 'all_required' is true, then add the parameter. This flag will be true if\n\t // certain of the fields in the \"Metadata\" section are filled in.\n\t \n\t if ( all_required )\n\t {\n\t\tparam_list.push('all_records');\n\t\thas_main_param = 1;\n\t }\n\t \n\t // Do the same if the \"select all records\" box is checked. In this case,\n\t // Set the 'confirm_download' flag so that a confirmation dialog box will\n\t // be generated before a download is initiated.\n\t \n\t else if ( all_records_elt && all_records_elt.checked )\n\t {\n\t\tparam_list.push('all_records');\n\t\thas_main_param = 1;\n\t\tconfirm_download = 1;\n\t }\n\t}\n\t\n\t// Now, if any errors were found, or if no \"significant\" parameter was entered,\n\t// then display a message for the user.\n\t\n\tvar url_elt = document.getElementById('mainURL');\n\t\n\tif ( errors_found )\n\t{\n\t url_elt.textContent = \"Fix the parameter errors below to generate a download URL\";\n\t url_elt.href = \"\";\n\t}\n\t\n\telse if ( ! has_main_param )\n\t{\n\t url_elt.textContent = \"Enter one or more parameters below to generate a download URL\";\n\t url_elt.href = \"\";\n\t}\n\n\t// Otherwise, generate the URL and display it.\n\t\n\telse\n\t{\n\t \n\t var param_string = param_list.join('&');\n\t \n\t // Construct the new URL\n\t \n\t var new_url = full_data_url + my_op + data_format + '?';\n\n\t download_path = short_data_url + my_op + data_format;\n\t download_params = '';\n\t \n\t if ( params.output_metadata )\n\t\tdownload_params = 'datainfo&rowcount&';\n\n\t download_params += param_string;\n\t \n\t new_url += download_params;\n\t \n\t url_elt.textContent = new_url;\n\t url_elt.href = new_url;\n\t}\n\t\n\t// Adjust metadata subsections according to the selected operation.\n\t\n\turl_op = my_op;\n\t\n\t// switch ( my_op )\n\t// {\n\t// case 'specs/list':\n\t// selectMetaSub('pd_meta_specs');\n\t// // showElement('pd_meta_occs');\n\t// // showElement('pd_meta_colls');\n // case 'occs/list':\n // case 'occs/diversity':\n // case 'occs/taxa':\n\t// case 'occs/strata':\n \t// selectMetaSub('pd_meta_occs');\n\t// showElement('pd_meta_colls');\n \t// break;\n // case 'colls/list':\n \t// selectMetaSub('pd_meta_colls');\n\t// showElement('pd_meta_occs');\n \t// break;\n \t// case 'taxa/list':\n \t// selectMetaSub('pd_meta_taxa');\n \t// break;\n \t// case 'opinions/list':\n \t// selectMetaSub('pd_meta_ops');\n \t// break;\n // case 'taxa/opinions':\n \t// selectMetaSub('pd_meta_ops');\n\t// showElement('pd_meta_taxa');\n \t// break;\n \t// case 'refs/list':\n\t// selectMetaSub('pd_meta_refs');\n\t// break;\n \t// case 'occs/refs':\n\t// case 'occs/taxabyref':\n\t// selectMetaSub('pd_meta_occs');\n\t// showElement('pd_meta_refs');\n\t// break;\n // case 'taxa/refs':\n\t// case 'taxa/byref':\n \t// selectMetaSub('pd_meta_taxa' );\n\t// showElement('pd_meta_refs');\n \t// break;\n\t// }\n }\n\n \n // Make the named section visible, and hide the others.\n \n function selectMetaSub ( subsection )\n {\n\tvar subs = { pd_meta_occs: 1, pd_meta_colls: 1, pd_meta_taxa: 1,\n\t\t pd_meta_ops: 1, pd_meta_refs: 1, pd_meta_specs: 1 };\n\tvar s;\n\t\n\tfor ( s in subs )\n\t{\n\t if ( s == subsection )\n\t {\n\t\tshowElement(s);\n\t\tvisible[s] = 1;\n\t }\n\t else\n\t {\n\t\thideElement(s);\n\t\tvisible[s] = 0;\n\t }\n\t}\n }\n\n // Return a list of the values that should be passed to the parameter 'show' in order to get\n // the output blocks selected on this form. If the checkbox 'pm_acc_only' in the Taxonomy\n // section is checked, add 'acconly' to the list.\n \n function getOutputList ( )\n {\n\tvar elts = document.getElementsByName(output_section);\n\tvar full_value = getElementValue(\"pm_fulloutput\");\n\tvar i;\n\tvar selected = [];\n\t\n\tif ( full_value )\n\t selected.push('full');\n\t\n\tfor ( i=0; i<elts.length; i++ )\n\t{\n\t var value = elts[i].value;\n\t \n\t if ( value == \"paleoloc\" )\n\t {\n\t\tpaleoloc_all = elts[i].checked;\n\t }\n\t \n\t else if ( value == \"paleoloc2\" )\n\t {\n\t\tpaleoloc_selected = elts[i].checked;\n\t\tvalue = \"paleoloc\";\n\t\t\n\t\tif ( paleoloc_all && paleoloc_selected ) continue;\n\t }\n\t \n\t if ( elts[i].checked )\n\t {\n\t\tif ( ! ( full_value && output_full[output_section][value] ) )\n\t\t selected.push(value);\n\t }\n\t}\n\t\n\tif ( visible.f1 && (data_type == 'occs' || data_type == 'specs'))\n\t{\n\t var acc_only = myGetElement(\"pm_acc_only\");\n\t if ( acc_only && acc_only.checked )\n\t\tselected.push('acconly');\n\t}\n\t\n\treturn selected.join(',');\n }\n \n\n // Show or hide the \"advanced\" form elements.\n \n function setFormMode ( mode )\n {\n\tif ( mode == \"advanced\" )\n\t{\n\t form_mode = \"advanced\";\n\t showByClass('advanced');\n\t}\n\t\n\telse\n\t{\n\t form_mode = \"simple\";\n\t hideByClass('advanced');\n\t}\n\t\n\tupdateFormState();\n }\n \n this.setFormMode = setFormMode;\n \n\n // Set or clear the \"include non-public data\" parameter.\n \n function setPrivate ( flag )\n {\n\tif ( flag && flag != \"0\" )\n\t params.private = 1;\n\telse\n\t params.private = 0;\n\t\n\tupdateFormState(); \n }\n \n // Set it to false by default when the App is loaded.\n \n this.setPrivate = setPrivate;\n \n\n // Select the indicated record type. This specifies the type of record that will be returned\n // when a download is initiated. Depending upon the record type, various sections of the form\n // will be shown or hidden.\n \n function setRecordType ( type )\n {\n\tdata_type = type;\n\t\n\tvar record_label;\n\tvar type_sections = [ 'type_occs', 'type_colls', 'type_specs', 'type_strata',\n\t\t\t 'type_diversity', 'type_taxa', 'taxon_reso', 'taxon_range', 'div_reso',\n\t\t\t 'type_ops', 'type_refs', 'acc_only', 'meta_specs', 'meta_occs',\n\t\t\t 'meta_colls', 'meta_taxa', 'meta_ops', 'meta_refs' ];\n\tvar show_sections = { };\n\t\n\tif ( type == 'occs' )\n\t{\n\t data_op = 'occs/list';\n\t output_section = 'od_occs';\n\t output_order = 'pm_occs_order';\n\t record_label = 'occurrence records';\n\t show_sections = { type_occs: 1, taxon_reso: 1, acc_only: 1, meta_occs: 1,\n\t\t\t meta_colls: 1 };\n\t}\n\t\n\telse if ( type == 'colls' )\n\t{\n\t data_op = 'colls/list';\n\t output_section = 'od_colls';\n\t output_order = 'pm_colls_order';\n\t record_label = 'collection records';\n\t show_sections = { type_colls: 1, taxon_reso: 1, meta_occs: 1, meta_colls: 1 };\n\t}\n\t\n\telse if ( type == 'specs' )\n\t{\n\t data_op = 'specs/list';\n\t output_section = 'od_specs';\n\t output_order = 'pm_occs_order';\n\t record_label = 'specimen records';\n\t show_sections = { type_specs: 1, taxon_reso: 1, acc_only: 1, meta_occs: 1,\n\t\t\t meta_specs: 1 };\n\t}\n\t\n\telse if ( type == 'meas' )\n\t{\n\t data_op = 'specs/measurements';\n\t output_section = 'od_meas';\n\t output_order = 'pm_occs_order';\n\t record_label = 'measurement records';\n\t show_sections = { type_meas: 1, taxon_reso: 1, meta_occs: 1,\n\t\t\t meta_specs: 1 };\n\t}\n\t\n\telse if ( type == 'strata' )\n\t{\n\t data_op = 'occs/strata';\n\t output_section = 'od_strata';\n\t output_order = 'pm_strata_order';\n\t record_label = 'stratum records';\n\t show_sections = { type_strata: 1, taxon_reso: 1, meta_occs: 1, meta_colls: 1 };\n\t}\n\t\n\telse if ( type == 'diversity' )\n\t{\n\t showHideSection('f2', 'show');\n\t data_op = 'occs/diversity';\n\t output_section = 'od_diversity';\n\t output_order = 'none';\n\t record_label = 'occurrence records';\n\t show_sections = { type_diversity: 1, div_reso: 1, meta_occs: 1 };\n\t}\n\t\n\telse if ( type == 'taxa' )\n\t{\n\t data_op = 'taxa/list';\n\t output_section = 'od_taxa';\n\t output_order = 'pm_taxa_order';\n\t record_label = 'taxonomic name records';\n\t show_sections = { type_taxa: 1, taxon_range : 1, acc_only: 1, meta_taxa: 1,\n\t\t\t meta_occs: 1 };\n\t}\n\t\n\telse if ( type == 'ops' )\n\t{\n\t data_op = 'opinions/list';\n\t output_section = 'od_ops';\n\t output_order = 'pm_ops_order';\n\t record_label = 'taxonomic opinion records';\n\t show_sections = { type_ops: 1, taxon_range: 1, acc_only: 1, meta_taxa: 1,\n\t\t\t meta_ops: 1, meta_occs: 1 };\n\t}\n\t\n\telse if ( type == 'refs' )\n\t{\n\t data_op = 'taxa/refs';\n\t output_section = 'od_refs';\n\t output_order = 'pm_refs_order';\n\t record_label = 'bibliographic reference records';\n\t show_sections = { type_refs: 1, taxon_range: 1, acc_only: 1, meta_taxa: 1,\n\t\t\t meta_occs: 1, meta_refs: 1 };\n\t}\n\t\n\telse if ( type == 'byref' )\n\t{\n\t data_op = 'taxa/byref';\n\t output_section = 'od_taxa';\n\t output_order = 'pm_refs_order';\n\t record_label = 'taxonomic name records';\n\t show_sections = { type_refs: 1, taxon_range: 1, acc_only: 1, meta_taxa: 1, meta_refs: 1 };\n\t}\n\t\n\telse\n\t{\n\t alert(\"Error! (\" + type + \")\");\n\t output_section = 'none';\n\t output_order = 'none';\n\t}\n\t\n\t// Set the \"include all output blocks\" form element according to the saved value.\n\t\n\tvar full_elt = myGetElement(\"pm_fulloutput\");\n\t\n\tif ( full_checked[output_section] ) full_elt.checked = 1;\n\telse full_elt.checked = 0;\n\t\n\t// Show the proper form division(s) for this type, and hide the others.\n\t\n\tvar i;\n\t\n\tfor ( i=0; i < type_sections.length; i++ )\n\t{\n\t var name = type_sections[i];\n\t \n\t if ( show_sections[name] )\n\t\tshowByClass(name);\n\t else\n\t\thideByClass(name);\n\t}\n\t\n\t// Show the proper output control for this type, and hide the others.\n\t\n\tvar sections = document.getElementsByClassName(\"dlOutputSection\");\n\t\n\tfor ( i=0; i < sections.length; i++ )\n\t{\n\t if ( sections[i].id == output_section )\n\t\tsections[i].style.display = '';\t\n\t else\n\t\tsections[i].style.display = 'none';\n\t}\n\t\n\tsections = document.getElementsByClassName(\"dlOutputOrder\");\n\t\n\tfor ( i=0; i < sections.length; i++ )\n\t{\n\t if ( sections[i].id == output_order )\n\t\tsections[i].style.display = '';\t\n\t else\n\t\tsections[i].style.display = 'none';\n\t}\n\t\n\t// Set the label on \"select all records\"\n\t\n\ttry\n\t{\n\t setInnerHTML(\"label_all_records\", record_label);\n\t}\n\t\n\tfinally {};\n\t\n\t// Show and hide various other controls based on type\n\t\n\ttry\n\t{\n\t if ( type == 'refs' )\n\t {\n\t\tsetDisabled(\"rb.ris\", 0);\n\t\tif ( ref_format ) document.getElementById(\"rb\"+ref_format).click();\n\t }\n\t \n\t else\n\t {\n\t\tsetDisabled(\"rb.ris\", 1);\n\t\tif ( data_format == '.ris' ) document.getElementById(\"rb\"+non_ref_format).click();\n\t }\n\t \n\t} finally {};\n\t\n\t// showElement('pd_meta_coll_re');\n\t\n\t// Then store the new type, and update the main URL\n\t\n\tupdateFormState();\n }\n \n this.setRecordType = setRecordType;\n \n \n // Select the indicated output format. This is the format in which the downloaded\n // data will be expressed.\n \n function setFormat ( type )\n {\n\tdata_format = '.' + type;\n\tif ( data_type != 'refs' && type != 'ris' ) non_ref_format = data_format;\n\telse if ( data_type == 'refs' ) ref_format = data_format;\n\t\n\tupdateFormState();\n }\n \n this.setFormat = setFormat;\n \n\n // This function is called when the \"Test\" button is activated. Unless a record limit is\n // specified, a limit of 100 will be added. Also, the output format \".csv\" will be changed to\n // \".txt\", which will (in most browsers) cause the result to be displayed in the browser\n // window rather than saved to disk.\n \n function testMainURL ( )\n {\n\tvar url = document.getElementById(\"mainURL\").textContent;\n\t\n\tif ( ! url.match(/http/i) ) return;\n\t\n\tif ( data_format == '.csv' ) url = url.replace('.csv','.txt');\n\telse url += '&textresult';\n\t\n\tif ( ! params.limit && url_op != 'occs/diversity' ) url += '&limit=100';\n\t\n\twindow.open(url);\n }\n \n this.testMainURL = testMainURL;\n\n\n // This function is called when the \"Download\" button is activated. If the 'confirm_download'\n // flag is true, generate a dialog box before initiating the download.\n \n function downloadMainURL ( )\n {\n\tvar url = document.getElementById(\"mainURL\").textContent;\n\t\n\tif ( ! url.match(/http/i) ) return;\n\t\n\tif ( confirm_download )\n\t{\n\t if ( ! confirm(\"You are about to initiate a download that might exceed 100 MB. Continue?\") )\n\t\treturn;\n\t}\n\t\n\twindow.open(url);\n }\n \n this.downloadMainURL = downloadMainURL;\n\n\n // This function is called when the \"Archive\" button is activated. This button takes the\n // place of the \"Download\" button when the archive options section is visible and the archive\n // title is not empty. If the 'confirm_download' flag is true, generate a dialog box before\n // initiating the download.\n\n function archiveMainURL ( )\n {\n\tvar url = document.getElementById(\"mainURL\").textContent;\n\t\n\tif ( ! url.match(/http/i) ) return;\n\t\n\tif ( params.private )\n\t{\n\t alert(\"You must choose the 'Public data only' option in order to create a publicly available archive\");\n\t return;\n\t}\n\t\n\tif ( confirm_download )\n\t{\n\t if ( ! confirm(\"You are about to archive a dataset that might exceed 100 MB. Continue?\") )\n\t\treturn;\n\t}\n\t\n\t// Use jQuery to initiate the archive creation process.\n\n\tvar archive_title = getElementValue('arc_title');\n\tvar archive_authors = getElementValue('arc_authors');\n\tvar archive_desc = getElementValue('arc_desc');\n\n\tif ( ! archive_title ) return;\n\t\n\tvar archive_url = url + '&archive_title=' + encodeURIComponent(archive_title);\n\t\n\tif ( archive_authors )\n\t archive_url += '&archive_authors=' + encodeURIComponent(archive_authors);\n\n\tif ( archive_desc )\n\t archive_url += '&archive_desc=' + encodeURIComponent(archive_desc);\n\t\n\t// $.getJSON(...)\n\t\n\t// var archive_params = JSON.stringify({\n\t// uri_path: download_path,\n\t// uri_args: download_params,\n\t// title: getElementValue('arc_title'),\n\t// authors: getElementValue('arc_authors'),\n\t// description: getElementValue('arc_desc') });\n\n\tfunction onArchiveError(xhr, textStatus, error)\n\t{\n\t var label = xhr.status || error;\n\t \n\t if ( xhr.status == '400' )\n\t {\n\t\tif ( /E_IMMUTABLE/.test(xhr.responseText) )\n\t\t{\n\t\t window.alert('You already have an immutable archive with this title.');\n\t\t}\n\t\t\n\t\telse if ( /E_EXISTING/.test(xhr.responseText) )\n\t\t{\n\t\t var proceed = window.confirm('You have an existing archive with that title. ' +\n\t\t\t\t\t\t 'Replace its contents?');\n\t\t \n\t\t if ( proceed )\n\t\t {\n\t\t\tvar replace_url = archive_url + '&archive_replace=yes';\n\t\t\t\n\t\t\trequestArchive( replace_url, onArchiveError);\n\t\t }\n\t\t}\n\t\t\n\t\telse\n\t\t{\n\t\t window.alert('Request failed due to a parameter error.');\n\t\t console.log(\"Error '\" + label + \"' creating archive:\\n\" + xhr.responseText);\n\t\t}\n\t }\n\t \n\t else\n\t {\n\t\twindow.alert('Request failed due to a server error.');\n\t\tconsole.log(\"Error '\" + label + \"' creating archive:\\n\" + xhr.responseText);\n }\n }\n\t\n\trequestArchive( archive_url, onArchiveError );\n }\n \n this.archiveMainURL = archiveMainURL;\n \n \n function requestArchive ( request_url, error_function )\n {\n\t$.ajax({ url: request_url,\n type: 'GET',\n async: false,\n success: function(data) {\n\t\t var match = /^Created.*dar:(\\d+)/.exec(data);\n\t\t \n\t\t if ( match && match[1] )\n\t\t {\n\t\t\t window.open(\"/classic/app/archive/edit?id=\" + match[1], \"_self\");\n\t\t }\n\n\t\t else\n\t\t {\n\t\t\t window.alert(\"Bad response from server\");\n\t\t }\n },\n error: error_function\n\t });\n }\n \n}",
"function GetDocuments()\n{\n\t// specify criteria for document search\n\tvar Criteria =\n\t{\n\t\t// extensions should be fixed to image\n\t\tDocIds: [1001],\n\t\t//Extensions: new Array(\".jpg\", \".png\", \".gif\", \".bmp\"),\n\t\t//DocTypeIds: new Array(1, 2), // specify document type ids which you canget from GetDocumentTypes()\n\t\t//Titles: ['Addenda_15497_rpt_s15%.pdf', 'Addenda_10000_rpt_s15%.pdf'],\n\t\t//FolderIds: [3]\n\t ExcludeStatuses: [4,5]\n\n\t\t// specify job number\n\t\t//AttributeCriterias: {\n\t\t//\tAttributes:\t[{\n\t\t//\t\t\tValues: {\n\t\t//\t\t\t\tid: 125, // can be fixed 3 (Job No)\n\t\t//\t\t\t\tatbValue: \"15497\" // job number (00007 is a test job number)\n\t\t//\t\t\t},\n\t\t//\t\t\tUseWildCard: false\n\t\t//\t}]\n\t\t//}\n\t}\n\n\t$.ajax({\n\t\turl: action_url + 'GetDocuments/' + UserId,\n\t\ttype: \"POST\",\n\t\tcontentType: \"application/json; charset=utf-8\",\n\t\tdata: JSON.stringify(Criteria), \n\t\tsuccess: function(Result)\n\t\t{\n\t\t\t// returns multiple document infomation\n\t\t\t$.each(Result.Documents, function(index, value)\n\t\t\t{\n\t\t\t\tvar JobNo;\n\t\t\t\tvar Sheet;\n\t\t\t\tvar PhotoType;\n\n\t\t\t\tfor(var i = 0; i < value.Attrs.length; i++)\n\t\t\t\t{\n\t\t\t\t\tswitch(value.Attrs[i].id)\n\t\t\t\t\t{\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\tJobNo = value.Attrs[i].atbValueForUI;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 10:\n\t\t\t\t\t\tSheet = value.Attrs[i].atbValueForUI;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 18:\n\t\t\t\t\t\tPhotoType = value.Attrs[i].atbValueForUI;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\talert(\"Document ID: \" + value.id + \"\\n\" +\n\t\t\t\t\t \"Version ID: \" + value.id_version + \"\\n\" +\n\t\t\t\t\t \"Title: \" + value.title + \"\\n\" +\n\t\t\t\t\t \"JobNo: \" + JobNo + \"\\n\" + \n\t\t\t\t\t \"Sheet: \" + Sheet + \"\\n\" + \n\t\t\t\t\t \"Photo Type: \" + PhotoType);\n\t\t\t});\n\t\t}\n\t});\n}",
"function BADocument() { }",
"function associateFileDesc() {\n let result = {\n group: [],\n file: [],\n desc: []\n };\n PAGE.appGroups.forEach(group => {\n group.items.forEach(item => {\n result.group.push(group.group);\n result.file.push(item.file);\n result.desc.push(item.itemdesc);\n });\n });\n return result;\n}",
"fetchNowAccessibleDocuments(previous) {\r\n const permissions = this.getAllPermissions().filter((permission) => {\r\n const found = previous.getAllPermissions().find((previousPermission) => {\r\n return permission.isSame(previousPermission)\r\n })\r\n\r\n return !found\r\n }).map((permission) => {\r\n return {\r\n action: permission.action,\r\n permissible_type: permission.permissibleType,\r\n scope: permission.scope,\r\n scope_id: permission.scopeId\r\n }\r\n })\r\n\r\n /**\r\n * Fetch documents that we can access with\r\n * our new permissions if we have any.\r\n */\r\n if (permissions.length ||\r\n this.assignAllCountries !== previous.assignAllCountries ||\r\n this.assignAllClients !== previous.assignAllClients ||\r\n !_.isEqual(this.assignedCountries.slice().sort(), previous.assignedCountries.slice().sort()) ||\r\n !_.isEqual(this.assignedClients.slice().sort(), previous.assignedClients.slice().sort())\r\n ) {\r\n Api.post('documents/accessible', {\r\n permissions\r\n }).then((data) => {\r\n for (let documentType in data) {\r\n const repositoryName = getRepositoryName(documentType)\r\n\r\n store.dispatch(`documents/repositories/${repositoryName}/ADD_ITEMS`, data[documentType])\r\n }\r\n })\r\n }\r\n }",
"function uploadDocumentAttachment() {\n console.log(\"uploadDocumentAttachment() started\");\n current.requestAttachmentUpload(function(response) {\n console.log(\"uploadDocumentAttachment() response is \" + JSON.stringify(response));\n loadDocuments();\n })\n}",
"function AttributionSourceParams() {}",
"function registrationOtherInfoReferenceAction() {\n const action = {\n type: ApiConstants.API_REGISTRATION_OTHER_INFO_REFERENCE_LOAD,\n };\n return action;\n}",
"_printAerooReport(action, options) {\n framework.blockUI();\n\n action = _.clone(action);\n var evalContexts = ([session.user_context] || []).concat([action.context]);\n action.context = pyeval.eval(\"contexts\", evalContexts);\n\n var self = this;\n return $.Deferred((deferred) => {\n session.get_file({\n url: \"/web/report_aeroo\",\n data: {action: JSON.stringify(action)},\n success: deferred.resolve.bind(deferred),\n error(){\n crashManager.rpc_error.apply(crashManager, arguments);\n deferred.reject();\n },\n complete: framework.unblockUI,\n });\n });\n }",
"getFileCreateParamName(file) {\n return this.fileCreateParamName;\n }",
"function formatCitationLink(metaData, link) {\n\t\tif (link == null || (link = link.trim()) == \"\") return \"\";\n\t\tmetaData[\"citation_download_method\"] = \"POST\";\n\t\tlet myForm = new FormData();\n\t\tmyForm.append('articles',link);\n\t\tmyForm.append('ArticleAction',\"export_endnote\");\n\t\tmetaData[\"citation_download_requestbody\"] = myForm;\n\t\tlink = (metaData[\"citation_url_nopath\"] + \"/custom_tags/IB_Download_Citations.cfm\");\n\t\treturn link;\n\t}",
"function DownloadPublished(el_input) {\n console.log( \" ==== DownloadPublished ====\");\n const tblRow = t_get_tablerow_selected(el_input);\n const pk_int = get_attr_from_el_int(tblRow, \"data-pk\");\n\n const data_dict = get_mapdict_from_datamap_by_id(published_map, tblRow.id);\n const filepath = data_dict.filepath\n const filename = data_dict.filename\n console.log( \"filepath\", filepath);\n console.log( \"filename\", filename);\n\n // window.open = '/ticket?orderId=' + pk_int;\n\n // UploadChanges(upload_dict, urls.url_download_published);\n const upload_dict = { published_pk: pk_int};\n if(!isEmpty(upload_dict)) {\n const parameters = {\"upload\": JSON.stringify (upload_dict)}\n let response = \"\";\n $.ajax({\n type: \"POST\",\n url: urls.url_download_published,\n data: parameters,\n dataType:'json',\n success: function (response) {\n var a = document.createElement('a');\n var url = window.URL.createObjectURL(response);\n a.href = url;\n a.download = 'myfile.pdf';\n document.body.append(a);\n a.click();\n a.remove();\n window.URL.revokeObjectURL(url);\n },\n\n\n /*\n success: function (data) {\n //const a = document.createElement('a');\n //const url = window.URL.createObjectURL(data);\n console.log( \"data\");\n console.log( data);\n /*\n a.href = url;\n a.download = 'myfile.pdf';\n document.body.append(a);\n a.click();\n a.remove();\n window.URL.revokeObjectURL(url);\n */\n /*\n var blob = new Blob(data, { type: 'application/pdf' });\n var a = document.createElement('a');\n a.href = window.URL.createObjectURL(blob);\n a.download = filename;\n a.click();\n window.URL.revokeObjectURL(url);\n\n },\n*/\n\n error: function (xhr, msg) {\n // --- hide loader\n el_loader.classList.add(cls_visible_hide)\n console.log(msg + '\\n' + xhr.responseText);\n } // error: function (xhr, msg) {\n }); // $.ajax({\n } // if(!!row_upload)\n\n\n\n\n\n // PR2021-03-06 from https://stackoverflow.com/questions/1999607/download-and-open-pdf-file-using-ajax\n //$.ajax({\n // url: urls.url_download_published,\n // success: download.bind(true, \"<FILENAME_TO_SAVE_WITH_EXTENSION>\", \"application/pdf\")\n // });\n\n //PR2021-03-07 from https://codepen.io/chrisdpratt/pen/RKxJNo\n //This one works, the demo does at least\n /*\n $.ajax({\n url: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/172905/test.pdf',\n method: 'GET',\n xhrFields: {\n responseType: 'blob'\n },\n success: function (data) {\n var a = document.createElement('a');\n var url = window.URL.createObjectURL(data);\n a.href = url;\n a.download = 'myfile.pdf';\n document.body.append(a);\n a.click();\n a.remove();\n window.URL.revokeObjectURL(url);\n }\n });\n */\n\n }",
"function checkAttLink(model, view) {\n if (model.get('share_attachments')) {\n if (model.get('share_attachments').enable) {\n if (model.get('encrypt')) {\n showAttLink(view, false);\n }\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
' 'Title : cmdUpdateReceived_ClickCase5 'Function : 'Input : 'Output : 'Remark : ' | function cmdUpdateReceived_ClickCase5() {
console.log("cmdUpdateReceived_ClickCase5");
if (config.DefaultReceiveQty) {
if (config.skipReceiveQty) {
$scope.strparaPreScrapQty = 0;
//3 - actual receive qty WIP-td3_1
//4 completed qty
//7 OutstandingQty
document.getElementById("WIP-td5_1").innerHTML = $scope.WOGlobalWOReceivedQty;
document.getElementById("WIP-td5_2").innerHTML = getCurrentDatetime().replace("T");
document.getElementById("WIP-td9_1").innerHTML = $scope.OutstandingQty + $scope.WOGlobalWOReceivedQty + $scope.strparaPreScrapQty;
document.getElementById("WIP-td9_2").innerHTML = getCurrentDatetime().replace("T");
cmdUpdateReceived_ClickCase7();
} else {
cmdUpdateReceived_ClickCase6();
}
} else {
cmdUpdateReceived_ClickCase6();
}
} | [
"function cmdUpdateReceived_ClickCase100() {\n console.log(\"cmdUpdateReceived_ClickCase100\");\n //fetch WO summary\n GenerateWOSummary();\n //fetch WO summary - scrap + unaccountable qty\n GenerateWOSummaryScrap();\n\n if (config.BypassExecutionStart) {\n //todo: line 5619\n }\n\n\n\n }",
"function cmdUpdate_ClickCase100() {\n console.log(\"cmdUpdate_ClickCase100\");\n //fetch WO summary\n GenerateWOSummary();\n //fetch WO summary - scrap + unaccountable qty\n GenerateWOSummaryScrap();\n\n console.log(\"cmdUpdate_ClickCase100.1\", $scope.CompletedQty);\n //if ($scope.McType.toLowerCase() == \"inhouse\") {\n // ReCheck($scope.selectedWOID);\n // //CheckWOOpnStatus();\n // console.log(\"saveCompleteModal2\", $scope.CompletedQty);\n // $(\"#saveCompleteModal-current\").val($scope.CompletedQty);\n\n //} else {\n // ReCheck($scope.selectedWOID);\n // //CheckSubconWOOpnStatus();\n // console.log(\"saveCompleteModal3\", $scope.CompletedQty);\n // $(\"#saveCompleteModal-current\").val($scope.CompletedQty);\n\n //}\n\n\n }",
"function updateMsgs() {\n MsgInquiryUpdate(msg_inquiry_accumulate_page, msg_inquiry_current_sort, $('#process_prio_input').val(), $('#process_name_input').val(), (document.getElementById('SU_SD_Checkbox').checked + 0));\n}",
"function evtRoutine1( sender, parms )\n {\n var rtn = Lansa.evtRoutine( this, COM_OWNER, \"#DIYSchedule.Click\", 149 );\n\n //\n // EVTROUTINE Handling(#DIYSchedule.Click)\n //\n rtn.Line( 149 );\n {\n\n //\n // #sys_web.Navigate( \"/images/lansatools/DIY-Workshops-Schedule.pdf\" New )\n //\n rtn.Line( 152 );\n Lansa.WEB().mthNAVIGATE( \"/images/lansatools/DIY-Workshops-Schedule.pdf\", \"NEW\" );\n\n }\n\n //\n // ENDROUTINE\n //\n rtn.Line( 154 );\n rtn.end();\n }",
"function cmdQCStart_ClickCase12() {\n console.log(\"cmdQCStart_ClickCase12\");\n if (String($scope.OrderType).trim().toLocaleLowerCase() == \"assembly\") {\n //todo line3946-3970\n console.log(\"setupStartCase12 subassembly\", $scope.subAssembly);\n for (var i = 0; i < $scope.subAssembly.length; i++) {\n if (String($scope.subAssembly[i]['woStatus']).tirm().toLowerCase() != \"completed\") {\n $(\"#alertBoxContent\").text(\"Unable to proceed due to dependent Work Order is not completed.\");\n $('#alertBox').modal('show');\n //alert(\"Unable to proceed due to dependent Work Order is not completed.\");\n cmdQCStart_ClickCase50();\n }\n }\n cmdQCStart_ClickCase15();\n } else {\n cmdQCStart_ClickCase15();\n }\n\n }",
"function ActionDescription(pAction, pValue1, pValue2) {\n\n var description = \"\";\n\n if (pAction >= 1 && pAction < 52)\n description = \"Output message: '@'\".replace(\"@\", gameData.messages[pAction]);\n else if (pAction >= 102)\n description = \"Output message: '@'\".replace(\"@\", gameData.messages[pAction - 50]);\n else {\n switch (pAction) {\n\n case 52:\n description = \"Get item '@'. Checks if you can carry it first\".replace(\"@\", gameData.items[pValue1].description);\n break;\n\n case 53:\n description = \"Drops item '@'.\".replace(\"@\", gameData.items[pValue1].description);\n break;\n\n case 54:\n description = \"Moves to room @\".replace(\"@\", pValue1);\n break;\n\n case 55:\n case 59:\n description = \"Item '@' is removed from game (put in room 0)\".replace(\"@\", gameData.items[pValue1].description);\n break;\n\n case 56:\n description = \"The darkness flag is set\";\n break;\n\n case 57:\n description = \"The darkness flag is cleared\";\n break;\n\n case 58:\n description = \"Bitflag @ is set\".replace(\"@\", pValue1);\n break;\n\n case 60:\n description = \"Bitflag @ is cleared\".replace(\"@\", pValue1);\n break;\n\n case 61:\n description = \"Death. Dark flag cleared, player moved to last room\";\n break;\n\n case 62:\n description = \"Item '@' is moved to room '-#-'\".replace(\"@\", gameData.items[pValue1].description).replace(\"-#-\", pValue2);\n break;\n\n case 63:\n description = \"Game over\";\n break;\n\n case 65:\n description = \"Score\";\n break;\n\n case 66:\n description = \"Inventory\";\n break;\n\n case 67:\n description = \"Bitflag 0 is set\";\n break;\n\n case 68:\n description = \"Bitflag 0 is cleared\";\n break;\n\n case 69:\n description = \"Refill lamp\";\n break;\n\n case 70:\n description = \"Clear screen\";\n break;\n\n case 71:\n description = \"Save the game\";\n break;\n\n case 72:\n description = \"Swap item '<arg1>' and item '<arg2>' locations\".replace(\"<arg1>\", gameData.items[pValue1].description).replace(\"<arg2>\", gameData.items[pValue2].description);\n break;\n\n case 73:\n description = \"Continue with next line (the next line starts verb 0 noun 0)\";\n break;\n\n case 74:\n description = \"Take item '<arg1>' - no check is done too see if it can be carried.\".replace(\"<arg1>\", gameData.items[pValue1].description);\n break;\n\n case 76:\n case 64:\n description = \"Look\";\n break;\n\n case 77:\n description = \"Decrement current counter. Will not go below 0\";\n break;\n\n case 78:\n description = \"Print current counter value.\";\n break;\n\n case 79:\n description = \"Set current counter value to @\".replace(\"@\", pValue1);\n break;\n\n case 80:\n description = \"Swap location with current location-swap flag\";\n break;\n\n case 81:\n description = \"Select a counter. Current counter is swapped with backup counter @\".replace(\"@\", pValue1);\n break;\n\n case 82:\n description = \"Add @ to current counter value\".replace(\"@\", pValue1);\n break;\n\n case 83:\n description = \"Subtract @ from current counter value\".replace(\"@\", pValue1);\n break;\n\n case 84:\n description = \"Echo noun player typed without Carriage Return\";\n break;\n\n case 85:\n description = \"Echo the noun the player typed\";\n break;\n\n case 86:\n description = \"Carriage Return\";\n break;\n\n case 87:\n description = \"Swap current location value with backup location-swap value @\".replace(\"@\", pValue1);\n break;\n\n case 88:\n description = \"Wait 2 seconds\";\n break;\n\n case 89:\n description = \"SAGA - draw picture <n>\";\n break;\n\n default:\n description = \"*UNKOWN PARAMETER*\";\n break;\n }\n }\n\n return description;\n }",
"function idirFeedback(parms)\n{\n location = location;\n if (false)\n {\n let form = document.censusForm;\n let msg = \"\";\n for(var line in parms)\n { // loop through all matched lines\n let idir = parms[line];\n if (line.length == 1)\n line = '0' + line;\n let idirElt = form.elements['IDIR' + line];\n if (idirElt)\n idirElt.value = idir;\n else\n alert(\"CensusForm.js: idirFeedback: \" +\n \"could not find form.elements['IDIR\" + line + \"']\");\n let findButton = form.elements[\"doIdir\" + line];\n if (findButton)\n {\n while(findButton.hasChildNodes())\n { // remove contents of cell\n findButton.removeChild(findButton.firstChild);\n } // remove contents of cell\n findButton.appendChild(document.createTextNode(\"Show\"));\n }\n } // loop through all matched lines\n } // if false\n} // function idirFeedback",
"function OnOptHelp(strObjectID)\n{\n\ntry {\n\tTextBox.Text = strObjectID;\n\tMFBar.WinHelp(8, 131375, \"dvdplay.hlp\");\n}\n\ncatch(e) {\n e.description = L_ERRORHelp_TEXT;\n\tHandleError(e);\n\treturn;\n}\n\n}",
"function lableRecievedAmount(params) {\n var lableRecievedAmount = document.getElementById(\"lable_recievedAmount\");\n switch (params) {\n case \"vietnam\":\n lableRecievedAmount.innerHTML = \"Recieved Amount - VND\";\n break;\n case \"canada\":\n lableRecievedAmount.innerHTML = \"Recieved Amount - CAD\";\n break;\n case \"india\":\n lableRecievedAmount.innerHTML = \"Recieved Amount - INR\";\n break;\n case \"uk\":\n lableRecievedAmount.innerHTML = \"Recieved Amount - GBP\";\n break;\n default:\n break;\n }\n}",
"function showQuestion(){\n var lstrMessage = '';\n lstrMessageID = showQuestion.arguments[0];\n lobjField = showQuestion.arguments[1];\n lstrCaleeFunction = funcname(arguments.caller.callee);\n //Array to store Place Holder Replacement\n var larrMessage = new Array() ;\n var insertPosition ;\n var counter = 0 ;\n\n larrMessage = showQuestion.arguments[2];\n \n lstrMessage = getErrorMsg(lstrMessageID);\n \n if(larrMessage != null &&\n larrMessage.length > 0 ){\n\n while((insertPosition = lstrMessage.indexOf('#')) > -1){\n\n if(larrMessage[counter] == null ){\n larrMessage[counter] = \"\";\n }\n lstrMessage = lstrMessage.substring(0,insertPosition) +\n larrMessage[counter] +\n lstrMessage.substring(insertPosition+1,lstrMessage.length);\n counter++;\n }\n }\n\n //lstrFinalMsg = lstrMessageID + ' : ' + lstrMessage;\n lstrFinalMsg = lstrMessage;\n\n if(lobjField!=null){\n lobjField.focus();\n }\n var cnfUser = confirm(lstrFinalMsg);\n if( !cnfUser ) {\n isErrFlg = true;\n }\n if(cnfUser && lstrCaleeFunction == 'onLoad'){\n \tdisableButtons('2');\n }\n //End ADD BY SACHIN\n return cnfUser;\n}",
"function help_OnClick()\n{\n\ntry {\n\tDVDOpt.ActivateHelp();\n}\n\ncatch(e) {\n //e.description = L_ERRORHelp_TEXT;\n\t//HandleError(e);\n\treturn;\n}\n\n}",
"function editRecordDescription(description) { //optional cap id\r\n\r\n var itemCap = capId;\r\n if (arguments.length > 1) itemCap = arguments[1]; // use cap ID specified in args\r\n\r\n var coreWorkDescScriptModel = aa.cap.getCapWorkDesByPK(itemCap).getOutput();\r\n var coreWorkDescModel = coreWorkDescScriptModel.getCapWorkDesModel();\r\n coreWorkDescModel.setDescription(description);\r\n var editCoreDescResult = aa.cap.editCapWorkDes(coreWorkDescModel);\r\n if(editCoreDescResult.getSuccess()) {\r\n logDebug(\"Successfully updated core SR description: \" + description);\r\n }\r\n else {\r\n logDebug(\"Failed to update core SR description: \" + editCoreDescResult.getErrorMessage());\r\n }\r\n}",
"function _0001485874442325_10_DailyTickets_DailyTicket()\n{\nLog.AppendFolder(\"_0001485874442325_10_DailyTickets_DailyTicket\");\ntry{\n InitializationEnviornment.initiliaze();\n AppLoginLogout.login();\n //As per mail from Sinead - please use saver admission package \n // 7/11/2017\n WrapperFunction.selectKeyword(\"Daily Admission\");\n\tSelectQuantityFromHeader.selectQuantity(2);\n selectPackage(\"Date/Time\",\"Children (Ages 3-12)\");\n aqUtils.Delay(5000);\n selectQuantityFromSubWindow(1);\n selectSubPackageFromSubWindow(\"Adult\");\n selectDateFromSubWindow(CommonCalender.getTodaysDate());\n selectNextButtonFromSubWindow();\n aqUtils.Delay(3000);\n selectFinalizeOrderbutton();\n \n SelectPaymentType.selectPaymentType(\"Cash\");\n WrapperFunction.verifyBalance(labelTotal,PaymentType_BalanceLabel);\n var paymentTypeBal=WrapperFunction.getBalanceValue(PaymentType_BalanceLabel);\n WrapperFunction.setTextValue(PayamountTextBox,paymentTypeBal);\n Button.clickOnButton(applyButton);\n WrapperFunction.settlementCompleteOrder();\n WrapperFunction.validateTicket(\"Don't Validate\");\n Button.clickOnButton(NewOrder_Button);\n AppLoginLogout.logout(); \n \n }\n\ncatch(e)\n{\n merlinLogError(\"Exception occured\");\n //Runner.Stop();\n}\n}",
"function update(params) {\n\t\tvar r = \"\";\t\t\n\t\tif (params) {\n\t\t\tr += \"\\nAtualizando \" + params;\n\t\t\tAPI.loader.downloadPkg(\"custom.\" + params);\n\t\t} else {\n\t\t\tr = \"Erro. Faltou indicar o nome do pacote.\";\n\t\t}\n\t\treturn r;\t\t\n\t}",
"function executeOnPage_Book(){\r\n\tgetCallButton();\r\n\r\n\tloadValues();\r\n\r\n\tgetsCallSelects();\r\n}",
"function recordsetDialog_onClickSwitchUI(theWindow, uiAction, sbRecordset, switchCmdFilename)\r\n{\r\n\tif (uiAction < 0) {\r\n\t\talert(\"Not a valid Action\");\r\n\t\treturn;\r\n\t}\r\n\tif (!recordsetDialog.canDialogDisplayRecordset(switchCmdFilename, sbRecordset)) {\r\n\t\talert(dwscripts.sprintf(MM.MSG_SQLNotSimple, dwscripts.getRecordsetDisplayName()));\r\n\t\treturn;\r\n\t}\r\n \r\n // Set return value and close the window for the command dialog.\r\n dwscripts.setCommandReturnValue(uiAction);\r\n theWindow.close();\r\n}",
"function handleCommand2CompletionMsg(aMsg) {\n\n // Show the completion record in the relevant page fields.\n if (aMsg.Code == 'Ack'){\n divCommand2.innerHTML = aMsg.Code;\n divInfo2.innerHTML = aMsg.Info;\n divProgress2.innerHTML = 'none';\n\n } else if (aMsg.Code == 'Nak'){\n divCommand2.innerHTML = aMsg.Code;\n divInfo2.innerHTML = aMsg.Info;\n\n } else if (aMsg.Code == 'Done'){\n divCommand2.innerHTML = aMsg.Code;\n divInfo2.innerHTML = aMsg.Info;\n divProgress2.innerHTML = 'none';\n\n } else if (aMsg.Code == 'Progress'){\n divProgress2.innerHTML = aMsg.Info;\n\n } else {\n divCommand2.innerHTML = 'bad completion code';\n divInfo2.innerHTML = 'none';\n divProgress2.innerHTML = 'none';\n }\n}",
"function showChangeTracking(parentDocViewId)\r\n{\r\n\tcloseMsgBox(); \r\n\tvar htmlAreaObj = _getWorkAreaDefaultObj();\r\n \tvar objAjax = htmlAreaObj.getHTMLAjax();\r\n\tvar objHTMLData = htmlAreaObj.getHTMLDataObj();\r\n\t//alert(objHTMLData);\r\n\tif(objHTMLData && objHTMLData.hasUserModifiedData() && objHTMLData.isDataModified())\r\n {\r\n var htmlErrors = objAjax.error();\r\n htmlErrors.addError(\"confirmInfo\", szMsg_Changes, false);\r\n var saveFunc =\"\\\"Main.loadWorkAreaWithSave()\\\"\";\t \r\n var canceFunc =\"_showChangeTracking('\"+parentDocViewId+\"')\";\r\n messagingDiv(htmlErrors, saveFunc, canceFunc);\r\n } \r\n else\r\n {\r\n \t_showChangeTracking(parentDocViewId);\r\n }\r\n}",
"function cmdQCResume_ClickCase5() {\n console.log(\"cmdQCResume_ClickCase5\");\n console.log(\"setupResumeCase6\");\n if (config.strSkipWOTrackingPrompt) {\n cmdQCResume_ClickCase10();\n } else {\n var answer = false;\n $.confirm({\n title: 'Confirm!',\n content: \"Confirm to resume QC?\",\n buttons: {\n confirm: function () {\n answer = true;\n },\n cancel: function () {\n $.alert('Canceled!');\n }\n }\n });\n // var answer = confirm(\"Confirm to resume QC?\");\n //todo to implement, trackingdefault ok in model so that default button can change\n //if (config.TrackingDefaultOK) {\n // productionPauseCase20();\n //} else {\n // if (answer) {\n // productionPauseCase20();\n // }\n //}\n\n if (answer) {\n cmdQCResume_ClickCase10();\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to trigger calculation of the last route | function reCalculateRoute(){
calculateRoute(lastRouteURL);
} | [
"function calcRoute() {\n\t// Prepare the API call\n\tvar start = start_location.geometry.location;\n\tvar end = end_location.geometry.location;\n\tvar request = {\n\t\torigin: start,\n\t\tdestination: end,\n\t\ttravelMode: 'DRIVING'\n\t};\n\n\t// Call Google Maps API\n\tdirectionsService.route(request, function (result, status) {\n\t\tconsole.log(result);\n\t\tif (status == 'OK') {\n\t\t\t// Update the map to show the route\n\t\t\tdirectionsDisplay.setDirections(result);\n\n\t\t\t// List out the roads that the route includes\n\t\t\tvar routes = result.routes;\n\n\t\t\tdocument.getElementById(\"routeslist\").innerHTML = '';\n\t\t\tfor (var i = 0; i < routes[0].legs[0].steps.length; i++) {\n\t\t\t\tvar routePath = routes[0].legs[0].steps[i].path;\n\t\t\t\tvar road_location = routePath[Math.floor(routePath.length / 2)];\n\t\t\t\tvar duration = routes[0].legs[0].steps[i].duration.value;\n\t\t\t\tvar distance = routes[0].legs[0].steps[i].distance.value;\n\n\t\t\t\t// speed in miles per hour\n\t\t\t\tvar speed = distance * 0.000621371 / (duration / 3600);\n\n\t\t\t\t\n\t\t\t\t//console.log(\"Speed: \" + speed);\n\n\t\t\t\tspeed = Math.max(20, Math.round(speed/10) * 10);\n\n\t\t\t\t//console.log(\"New Speed: \" + speed);\n\t\t\t\tvar polyline = routes[0].legs[0].steps[i].polyline;\n\n\t\t\t\tprocessStep(road_location, duration, distance, speed, routePath, polyline);\n\t\t\t}\n\t\t}\n\n\n\t});\n}",
"function additionalPass(result, status) {\n\n // if Maps returns a valid response\n if (status == google.maps.DirectionsStatus.OK) {\n \n // initialize variable for checking if route needs any changes\n var needsCorrection = false;\n\n // iterate over legs of route\n for (var i = 0, n = result.routes[0].legs.length; i < n; i++) {\n\n var legLength = result.routes[0].legs[i].distance.value;\n\n // if leg is longer than range\n if (legLength > range) {\n\n // create new polyline for this leg\n var polyline = new google.maps.Polyline({ path: [] });\n\n // iterate over steps of the leg\n for (var j = 0, m = result.routes[0].legs[i].steps.length; j < m; j++) {\n\n // iterate over segments of step\n for (var k = 0, l = result.routes[0].legs[i].steps[j].path.length; k < l; k++) {\n\n // add segment to polyline\n polyline.getPath().push(result.routes[0].legs[i].steps[j].path[k]);\n }\n }\n \n // find point 75% of range along this line\n var nextPoint = polyline.GetPointAtDistance(0.75 * range);\n\n // get closest station to halfway point\n var newStation = getClosestStation(nextPoint);\n \n // create waypoint at that station\n var newWaypoint = {\n location: newStation.latlng,\n stopover: true\n }\n\n // add to waypoints array\n waypoints.push(newWaypoint);\n\n // add station to station stops array\n stationStops.push(newStation);\n\n // create invisible marker\n var marker = new google.maps.Marker({\n position: stationStops[i].latlng,\n map: map,\n icon: 'img/invisible.png',\n zIndex: 3,\n });\n\n // add to markers array\n markers.push(marker);\n\n // indicate that route needs correction\n needsCorrection = true;\n }\n }\n\n // if route needs correction\n if (needsCorrection == true) {\n\n // create new directions request\n var nextRequest = {\n origin: origin,\n destination: destination,\n travelMode: google.maps.TravelMode.DRIVING,\n unitSystem: google.maps.UnitSystem.IMPERIAL,\n waypoints: waypoints,\n optimizeWaypoints: true\n }\n\n // send new directions request\n directionsService.route(nextRequest, function(nextResult, nextStatus) {\n\n // try again\n additionalPass(nextResult, nextStatus)\n });\n }\n\n // otherwise our route is fine as is\n else {\n\n // check for legs longer than 85% of range\n warnLong(result);\n\n // create a clickable info window for each waypoint\n createInfoWindows();\n\n // display route\n directionsDisplay.setDirections(result);\n }\n }\n \n // handle errors returned by the Maps API\n else {\n \n handleErrors(status);\n }\n}",
"function timeTilNextShuttle(route, stop) {\n var t = getCurrTime();\n var day = t / 10000;\n var time = t % 10000;\n\n if (route == RouteA)\n {\n if (day < 1 || day > 5)\n return -1;\n else \n return timeDiff(routeAMF, time);\n }\n else if (route == RouteB)\n {\n if (day < 1 || day > 5)\n return -1;\n else\n return timeDiff(routeBMF, time);\n }\n else if (route == RouteAB)\n {\n if (day < 1 || day > 5) \n return timeDiff(routeABSSu, time);\n else\n return timeDiff(routeABMF, time);\n }\n else if (route == RouteC)\n {\n if (day > 4)\n return -1;\n else \n return timeDiff(routeCSuR, time);\n }\n else if (route == BakerySquareL)\n { \n if (stop == CICstop) \n {\n if (day < 1 || day > 5)\n return -1;\n else\n return timeDiff(BakerySquareLRCICMF, time);\n }\n else if (stop == BakerySquarestop)\n {\n if (day < 1 || day > 5)\n return -1;\n else \n return timeDiff(BakerySquareLRBSMF, time);\n }\n else \n return -1;\n }\n else if (route == BakerySquareS)\n {\n if (stop == CICstop) \n {\n if (day < 1 || day > 5)\n return -1;\n else\n return timeDiff(BakerySquareSRCICMF, time);\n }\n else if (stop == BakerySquarestop)\n {\n if (day < 1 || day > 5)\n return -1;\n else \n return timeDiff(BakerySquareSRBSMF, time);\n }\n else \n return -1;\n }\n else if (route == PTCroute)\n { \n if (stop == Morewoodstop) \n {\n if (day < 1 || day > 5)\n return timeDiff(PTCMorewoodSSu, time);\n else\n return timeDiff(PTCMorewoodMF, time);\n }\n else if (stop == PTCstop)\n {\n if (day < 1 || day > 5)\n return timeDiff(PTCPTCSSu, time);\n else\n return timeDiff(PTCPTCMF, time);\n }\n else\n return -1;\n }\n else \n return -1;\n}",
"async onPressEndTrip(item) {\n\n this.setState({loadingModal:true})\n let location = await Location.getCurrentPositionAsync({});\n if(location) {\n var diff =((this.state.startTime) - (new Date().getTime())) / 1000;\n diff /= (60 * 1);\n var totalTimeTaken = Math.abs(Math.round(diff));\n \n var pos = {\n latitude: location.coords.latitude,\n longitude: location.coords.longitude,\n };\n\n let startLoc = '\"'+this.state.rideDetails.pickup.lat+', '+this.state.rideDetails.pickup.lng+'\"';\n let destLoc = '\"'+pos.latitude+', '+pos.longitude+'\"';\n\n var resp = await fetch(`https://maps.googleapis.com/maps/api/directions/json?origin=${startLoc}&destination=${destLoc}&key=${ google_map_key }`)\n var respJson = await resp.json();\n //fare calculations\n var fareCalculation = farehelper(respJson.routes[0].legs[0].distance.value,totalTimeTaken,this.state.rateDetails?this.state.rateDetails:1);\n if(fareCalculation) {\n this.finalCostStore(item,fareCalculation.grandTotal,pos,respJson.routes[0].legs[0].distance.value,fareCalculation.convenience_fees)\n \n }\n }\n \n }",
"function route1Anim(){\n if(delta < 1){\n delta += 0.2;\n } else {\n visitedRoutes.push(allCoordinates[coordinate]) // Once it has arrived at its destination, add the origin as a visited location\n delta = 0;\n coordinate ++;\n drawRoute(); // Call the drawRoute to update the route\n }\n\n const latitude_origin = Number(runLocations.getString(coordinate, 'Position/LatitudeDegrees'));\n const longitude_origin = Number(runLocations.getString(coordinate, 'Position/LongitudeDegrees'));\n\n const latitude_destination = Number(runLocations.getString(coordinate +1,'Position/LatitudeDegrees'));\n const longitude_destination = Number(runLocations.getString(coordinate +1, 'Position/LongitudeDegrees'));\n origin = myMap.latLngToPixel(latitude_origin,longitude_origin);\n originVector = createVector(origin.x, origin.y);\n destination = myMap.latLngToPixel(latitude_destination,longitude_destination);\n destinationVector = createVector(destination.x, destination.y);\n\n runPosition = originVector.lerp(destinationVector, delta);\n\n noStroke(); // remove the stroke from the route\n fill(255,255,0);\n ellipse(runPosition.x, runPosition.y, 7, 7);\n}",
"function calcRoute(startLat, startLong, finishLat, finishLong){\r\n var start = new google.maps.LatLng(startLat, startLong);\r\n var end = new google.maps.LatLng(finishLat, finishLong);\r\n var directionsDisplay = new google.maps.DirectionsRenderer()\r\n var directionsService = new google.maps.DirectionsService()\r\n var request = {\r\n origin: start,\r\n destination: end,\r\n travelMode: google.maps.TravelMode.WALKING\r\n };\r\n\r\n directionsService.route(request, function(response, status) {\r\n if (status == google.maps.DirectionsStatus.OK) {\r\n directionsDisplay.setDirections(response);\r\n directionsDisplay.setMap(map1);\r\n } else {\r\n alert(\"Directions Request from \" + start.toUrlValue(6) + \" to \" + end.toUrlValue(6) + \" failed: \" + status);\r\n }\r\n });\r\n marker.setMap(null)\r\n }",
"function calculateAndDisplayRoute(directionsService, directionsDisplay, distance) {\n directionsService.route({\n origin: startValue,\n destination: endValue,\n travelMode: 'DRIVING',\n }, function(response, status) {\n // console.log(response);\n if (status === 'OK') {\n directionsDisplay.setDirections(response);\n\n } else {\n console.log(\"ERROR - \" + status);\n // window.alert('Directions request failed due to ' + status);\n }\n });\n\n distance.getDistanceMatrix({\n origins: [startValue],\n destinations: [endValue],\n travelMode: 'DRIVING',\n }, function(response, status) {\n console.log(response);\n var length = (response.rows[0].elements[0].duration.value);\n\n tripLength = length * 1000;\n console.log(response.rows[0].elements[0].duration.text);\n // console.log(msLength);\n\n });\n // Get current weather there\n getCurrentWeather();\n} // End of function to calculate directions and distance",
"_calculateTargetedAltitudeToInterceptGlidepath() {\n // GENERALIZED CODE\n // const glideDatum = this.mcp.nav1Datum;\n // const distanceFromDatum_nm = this.positionModel.distanceToPosition(glideDatum);\n // const slope = Math.tan(degreesToRadians(3));\n // const distanceFromDatum_ft = distanceFromDatum_nm * UNIT_CONVERSION_CONSTANTS.NM_FT;\n // const glideslopeAltitude = glideDatum.elevation + (slope * (distanceFromDatum_ft));\n // const altitudeToTarget = _clamp(glideslopeAltitude, glideDatum.elevation, this.altitude);\n\n if (!this.isEstablishedOnCourse()) {\n return this.mcp.altitude;\n }\n\n // ILS SPECIFIC CODE\n const glideslopeAltitude = this._calculateArrivalRunwayModelGlideslopeAltitude();\n const altitudeToTarget = Math.min(this.mcp.altitude, glideslopeAltitude);\n\n return altitudeToTarget;\n }",
"function triangular(routes) {\n try {\n // Figure out which account to take the fund\n let initialAmount = 1;\n let initialCurrency = '';\n if (STATE.ACC && STATE.ACC.current) {\n // Figure out which account to use - depend on the first route is buy or sell\n let pairParts = routes[0].split('-');\n if (ROUTES_SIDE[0] === 'buy') {\n\t\t\t\t// todo: very common to have error because the current acc doesn't have the pair available\n initialAmount = math.eval(STATE.ACC.current.acc[pairParts[1]].available) || initialAmount;\n initialCurrency = pairParts[1];\n } else {\n initialAmount = math.eval(STATE.ACC.current.acc[pairParts[0]].available) || initialAmount;\n initialCurrency = pairParts[0];\n }\n }\n\n // Only take 90% of the initial amount\n initialAmount = utils.formatCurrency(initialCurrency, math.eval(initialAmount * 0.9));\n\n // Calculate if the route is worth it by going through the chain\n let chain = math.chain(initialAmount);\n\n let outputStr = 'routes:';\n // Collect legs paramis within a trade\n let tradeLegs = [];\n // todo: calculate the transaction fee in here as well\n routes.forEach((route, index) => {\n // Use the price for now\n let size = 0;\n let side = ROUTES_SIDE[index];\n const price = STATE.PRICES[routes[index]].price;\n\n if (index === 0 && side === 'sell') {\n size = chain;\n }\n\n // Check if need to divide or multiply the prices\n // todo: maybe use the ask and bid price for quick execution\n if (side === 'buy') {\n // Size is before the calculation\n //size = chain;\n chain = chain.divide(price);\n } else {\n // Size is before the calculation\n //size = chain;\n chain = chain.multiply(price);\n }\n\n if (size === 0) {\n size = chain;\n }\n\n // Size is the current value until now\n size = utils.formatCurrencyFromSide(side, route, size.done());\n\n outputStr += ` ${side} ${size} ${route}@${price}`;\n\n // Calculate the prices and size at the route/pair\n tradeLegs.push({\n price,\n size,\n side,\n product_id: route,\n });\n });\n logToFile(outputStr, true);\n\n // Tally the end price\n // Check the time - see if there are driffs\n const amountWithoutFees = chain.done();\n\n let fees = math.eval(amountWithoutFees * (TRANSACTION_FEE / 100));\n // Predict the transaction fee\n const endPrice = math.eval(amountWithoutFees - fees);\n\n // Profit in percentage\n const profit = math.eval((endPrice - initialAmount) / initialAmount * 100);\n\n const outcomeStr = `Initial: ${initialAmount}, Outcome > W/O fees: ${math.round(amountWithoutFees, 8)}, fees: ${math.round(fees, 8)}, W/ fees: ${math.round(endPrice, 8)}, profit: ${math.round(profit, 8)}%`;\n logToFile(outcomeStr, true);\n\n\t\tconst shouldTrade = math.larger(profit, PROFIT_THRESHOLD);\n // See if make the trade or not\n // todo: Also check the profit as well\n if (math.larger(endPrice, initialAmount)) {\n if (shouldTrade) {\n logToFile('TRADE - YES!', true);\n placeTrade(tradeLegs);\n\n // Increase the trade found\n STATE.PROFITABLE_TRADES += 1;\n } else {\n logToFile('TRADE - NO! not above threshold profit', true);\n }\n } else {\n logToFile('TRADE - NOOOOOOOOOOOOOOOOOO!', true);\n }\n\n\t\tconst routesCsv = tradeLegs.map(leg => leg.price);\n\t\t// Log the data to csv for reference\n\t\tlet currentTime = new Date();\n\t\tconst ts = `${currentTime.getFullYear()}-${currentTime.getMonth() + 1}-${currentTime.getDate()} ${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}`;\n\t\tconst csvLine = `${ts},${initialAmount},${endPrice},${profit},${shouldTrade},${routesCsv.join(',')}\\n`;\n\t\t//logToFile(csvLine, true);\n\t\tfs.appendFile(DATA_FD, csvLine, () => {});\n } catch (error) {\n logToFile('Error while doing triangulation', true);\n logToFile(error);\n }\n}",
"function onPlaceChanged() {\n\n\tconsole.log(\"Start location: \" + start_location + \", destination: \" + end_location);\n\tif (start_location && end_location) {\n\t\tconsole.log(\"Calculating route between \" + start_location.name + \" and \" + end_location.name);\n\t\tcalcRoute();\n\t}\n}",
"function processStep(location, duration, distance, speed, path, polyline) {\n\tvar latLngArray = new String(location).replace(\"(\", \"\").replace(\")\", \"\").split(',', 2);\n\tvar latlng = { lat: parseFloat(latLngArray[0]), lng: parseFloat(latLngArray[1]) };\n\n\thttpGetAsync(\"https://nominatim.openstreetmap.org/reverse?format=json&lat=\" + latlng.lat + \"&lon=\" + latlng.lng + \"&zoom=18&addressdetails=1\", function (data) {\n\t\tvar road;\n\t\ttry {\n\t\t\troad = JSON.parse(data).address.road;\n\t\t} catch (err) {\n\t\t\tconsole.warn(\"Error finding road name from GPS coordinates \" + location + \" :(\");\n\t\t}\n\n\t\tif (!road) {\n\t\t\tconsole.warn(\"Error finding road name from GPS coordinates \" + location + \" :(\");\n\t\t}\n\t\telse if (!roads[road]) {\n\t\t\tvar listNode = getListNode(road, duration, distance, speed);\n\t\t\troads[road] = {\n\t\t\t\tduration: duration,\n\t\t\t\telement: listNode,\n\t\t\t\tlatitude: latlng.lat,\n\t\t\t\tlongitude: latlng.lng,\n\t\t\t\troadName: road,\n\t\t\t\tdistance: distance,\n\t\t\t\tspeed: speed,\n\t\t\t\tpaths: [path],\n\t\t\t\tpolylines: [polyline]\n\t\t\t};\n\t\t} else {\n\t\t\tvar road = roads[road];\n\t\t\troad.duration += duration;\n\t\t\troad.distance += distance;\n\t\t\troad.paths.push(path);\n\t\t\troad.polylines.push(polyline);\n\t\t}\n\t\trenderList();\n\t});\n}",
"function OnPathComplete (newPath : Path) // the newly determined path is sent over as \"newPath\" type of Path\n{\n\tif (!newPath.error)//if the newPath does not have any errors\n\t{\n\t\tpath = newPath; //set the path to this new one\n\t\tcurrentWaypoint = 0;//now that we have a new path. make sure to start at the first waypoint\n\t\t\n\t}\n}",
"function route2Anim(){\n if(delta < 1){\n delta += 0.2;\n } else {\n visitedRoutes.push(allCoordinates[coordinate]) // Once it has arrived at its destination, add the origin as a visited location\n delta = 0;\n coordinate ++;\n drawRoute(); // Call the drawRoute to update the route\n }\n\n const latitude_origin = Number(runLocations2.getString(coordinate, 'Position/LatitudeDegrees'));\n const longitude_origin = Number(runLocations2.getString(coordinate, 'Position/LongitudeDegrees'));\n\n const latitude_destination = Number(runLocations2.getString(coordinate +1,'Position/LatitudeDegrees'));\n const longitude_destination = Number(runLocations2.getString(coordinate +1, 'Position/LongitudeDegrees'));\n origin = myMap.latLngToPixel(latitude_origin,longitude_origin);\n originVector = createVector(origin.x, origin.y);\n destination = myMap.latLngToPixel(latitude_destination,longitude_destination);\n destinationVector = createVector(destination.x, destination.y);\n\n runPosition = originVector.lerp(destinationVector, delta);\n\n noStroke(); // remove the stroke from the route\n fill(255,255,0);\n ellipse(runPosition.x, runPosition.y, 7, 7);\n}",
"function getLastPath() {\n if (url.path.components.length > 0) {\n return url.path.components[url.path.components.length - 1];\n }\n }",
"function calcNextTrain() {\n\t\tvar a = snap.val().firstTrain;\n\t\tvar b = \"HH:mm\";\n\t\tvar c = moment(a, b);\n\t\n\n\t\t//current time\n\t\tvar d = moment() \t\n\n\t\tvar e = moment(moment(c).diff(d)).format('HH:mm')\n\n\t\treturn e;\n\n\t}",
"function getNextSubwayTime() {\n\t// Get the schedule information\n\t// TODO: Only update schedule info once a day\n\tgetSubwaySchedule(SUBWAY_ID).then(function (data) {\n\t\t// Get just the information for arrivals\n\t\tvar arrivals = data.data.result.arrivals;\n\n\t\t// Get current time\n\t\tvar now = moment();\n\t\tvar time = now.format(\"HH:mm:ss\");\n\n\t\t// Determine the closest subway time\n\t\tvar closest = getClosestTime(time, arrivals);\n\n\t\t// Get the next subway time\n\t\tvar time_next = getTimeTillNext(time, closest);\n\n\t\t// Render to the Pi\n\t\trenderNext(time_next);\n\t})[\"catch\"](function (err) {\n\t\trenderError(err);\n\t});\n}",
"doRouteAfter() {\n if (Routes.doAppRouteAfter) {\n Routes.doAppRouteAfter()\n }\n }",
"function calculateAndDisplayRoute(directionsService, directionsDisplay) {\n var originLoc = getOrigin();\n\n var directionsRequest = {\n origin: originLoc,\n destination: inputs.locationTo[0].geometry.location, \n travelMode: google.maps.DirectionsTravelMode.DRIVING,\n };\n\n sendData();\n\n directionsService.route(directionsRequest, function(response, status) {\n if (status === google.maps.DirectionsStatus.OK) {\n directionsDisplay.setDirections(response);\n // Box the overview path of the first route\n var path = response.routes[0].overview_path;\n var boxes = rboxer.box(path, distance);\n //drawBoxes(boxes); // draws out boxes, only for debugging\n for (var i = 0; i < boxes.length; i++) {\n var bounds = boxes[i];\n // this is where we will perform search over this bounds \n restaurant_initialize(bounds);\n }\n }\n else {\n window.alert('Directions request failed due to ' + status);\n }\n });\n}",
"function calculatePredictedFinish() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
allConfig returns a copy of the full config map. | function allConfig() {
const config = parseConfig();
return Object.assign({}, config);
} | [
"get rawConfig() {\n return this.conf || readOnly(this.defaults);\n }",
"static merge (config) {\n currentConfig = assign({}, currentConfig, config);\n }",
"getAllProjects() {\n return new Map(this.allWorkspaceProjects);\n }",
"function getConfigs() {\n\n // use embedded configurations if it's available\n if (angular.isObject(window.swaggerDocsConfiguration)) {\n assignConfigs(window.swaggerDocsConfiguration);\n return;\n }\n\n // get configuration file remotely\n $http.get('./config.json').then(\n function(resp) {\n\n if (!angular.isObject(resp.data)) {\n throw new Error('Configuration should be an object.');\n }\n\n assignConfigs(resp.data);\n },\n function() {\n throw new Error('Failed to load configurations.');\n }\n );\n }",
"function clearConfigCache() {\n config = {};\n}",
"static async findAll() {\n const settings = await this.find().sort({ triggerPath: 1 });\n\n return settings;\n }",
"get ConfigData() {\r\n const cfg_data = [];\r\n this.native.IterateConfigData((cfg) => {\r\n cfg_data.push(new ImFontConfig(cfg));\r\n });\r\n return cfg_data;\r\n }",
"async _listAll(config) {\n this.config = this.setConfig(config);\n const loadExtensions = this.config.loadExtensions;\n return Bluebird.promisify(fs.readdir, { context: fs })(\n this._absoluteConfigDir()\n )\n .bind(this)\n .then((seeds) =>\n filter(seeds, function(value) {\n const extension = path.extname(value);\n return includes(loadExtensions, extension);\n }).sort()\n );\n }",
"function read_config(){\n\tdb.each(\"SELECT * FROM settings\", \n\t\tfunction(err, row) {\n\t\t\tif(err) {\n\t\t\t\tconsole.log(\"DB error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tsettings[row.name] = row.value;\n\t\t\t//console.log(JSON.stringify(settings, null, 4));\n\t\t}\n\t);\n}",
"function getConfig() {\n var wb = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = wb.getSheetByName('configuration'); \n var configdata = getRowsData(sheet, sheet.getDataRange(), 1);\n\n config = {};\n for (i=1; i<configdata.length; i++) {\n var param = configdata[i];\n var thisparam = normalizeHeader(param.parameter)\n config[thisparam] = param.value;\n\n // special processing this script\n if (thisparam == 'open' && param.value) {\n config[thisparam] = param.value.toLowerCase();\n }\n };\n\n Logger.log( 'config = ' + Utilities.jsonStringify(config) );\n return config;\n}",
"remoteConfig() {\n const configs = Object.assign({}, Remote_1.RemoteConfig);\n configs.uri = this.apiUrl();\n return configs;\n }",
"config() {\n if (this.isBound(exports.names.APP_SERVICE_CONFIG)) {\n return this.get(exports.names.APP_SERVICE_CONFIG);\n }\n else {\n throw new Error('configuration object not yet loaded!');\n }\n }",
"function getAllEntries(){\n for(const [sourceId, logSource] of logSources.entries()){\n getEntries(sourceId, logSource);\n }\n }",
"static defaultConfig() {\r\n if (_defaultConfig == null) {\r\n _defaultConfig = new Config(\"./config/etc/config.json\");\r\n }\r\n\r\n return _defaultConfig;\r\n }",
"function applyConfig() {\n if (config !== undefined) {\n for (var key in config) {\n plugin[key] = config[key];\n }\n }\n }",
"async _getConfig() {\n const url = `${PARTNER_CONF_URL}/campaigns.json`\n const res = await fetch(url)\n if (res.status !== 200) {\n logger.error('Failed to fetch campaigns JSON')\n return\n }\n const config = await res.json()\n\n if (!config) {\n logger.error('No config - probably an error')\n return\n }\n\n this.validCodes = Object.keys(config)\n\n if (this.validCodes.length === 0) {\n logger.warn('Found 0 valid codes from campaigns.json')\n return\n }\n\n PARTNER_NAMES = {}\n PARTNER_REWARDS = {}\n\n // Get the rewards for the code\n for (const code of this.validCodes) {\n const conf = config[code]\n if (!conf) {\n logger.debug(`Code \"${code}\" has no config`)\n continue\n }\n PARTNER_REWARDS[code] = conf.reward\n PARTNER_NAMES[code] = conf.partner ? conf.partner.name : null\n }\n\n this.lastConfLoad = new Date()\n logger.info(\n `Loaded campaigns.json config at ${this.lastConfLoad.toString()}`\n )\n }",
"allPolygons() {\n let e = this.polygons.slice();\n return this.front && (e = e.concat(this.front.allPolygons())), this.back && (e = e.concat(this.back.allPolygons())), e;\n }",
"allPolygons() {\n\t\tlet polygons = this.polygons.slice();\n\t\tif (this.front) polygons = polygons.concat(this.front.allPolygons());\n\t\tif (this.back) polygons = polygons.concat(this.back.allPolygons());\n\t\treturn polygons;\n\t}",
"function loadMainConfig() {\n return $http({\n method: 'Get',\n data: {},\n url: 'config.json',\n withCredentials: false\n })\n .then(transformResponse)\n .then(conf => {\n try {\n if (conf && conf.endpoints && conf.endpoints.mdx2json) {\n MDX2JSON = conf.endpoints.mdx2json.replace(/\\//ig, '').replace(/ /g, '');\n NAMESPACE = conf.namespace.replace(/\\//ig, '').replace(/ /g, '');\n }\n } catch (e) {\n console.error('Incorrect config in file \"config.json\"');\n }\n adjustEndpoints();\n })\n }",
"get config() {\n return this._vm.$data.config\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
show disclaimer text on click of disclaimer link | function showDisclaimer() {
window.alert("The maps used do not imply the expression of any opinion on the part of the International Federation of Red Cross and Red Crescent Societies or National Societies concerning the legal status of a territory or of its authorities.");
} | [
"get disclaimer() {\n\t\treturn this.__disclaimer;\n\t}",
"function displayWarning(text) {\n\tvar warning = document.getElementById(\"warning\");\n\t\n\tif(text) warning.style.display = \"block\";\n\telse warning.style.display = \"none\";\n\t\n\twarning.innerHTML = text;\n}",
"function showRemarksActivityAdmin(self){\n\tremarks = $(self).data('actremarks');\n\t$(\"#dialog-remarks-admin\").modal({ keyboard: false });\n\tif (remarks){\n\t\t$(\"#remarks-given-admin\").html(remarks);\n\t} else {\n\t\t$(\"#remarks-given-admin\").html('No remarks specified while rejection of activity');\n\t}\n}",
"function showRemarksActivity(self){\n\tremarks = $(self).data('actremarks');\n\t$(\"#dialog-remarks\").modal({ keyboard: false });\n\tif (remarks){\n\t\t$(\"#remarks-given\").html(remarks);\n\t} else {\n\t\t$(\"#remarks-given\").html('No remarks specified while rejection of activity');\n\t}\n}",
"showButtonPageDescription(text){\n\t\tthis.buttonPageDescription.setInfoText(text);\n\t\tthis.buttonPageDescription.updatesHimself();\n\t\tthis.buttonPageDescription.showInfoText();\n\t}",
"function openDataProtectionBanner() {\n var height = document.getElementById('data-protection-banner').offsetHeight || 0;\n document.getElementById('data-protection-banner').style.display = 'block';\n document.body.style.paddingBottom = height + 'px';\n\n document.getElementById('data-protection-agree').onclick = function () {\n closeDataProtectionBanner();\n return false;\n };\n}",
"function onLearnMoreClick(){\n $('#learnmoretext').slideDown();\n $('.learnmore').hide();\n }",
"function toggleInfo() {\n\tvar state = document.getElementById('description').className;\n\tif (state == 'hide') {\n\t\t// Info anzeigen\n\t\tdocument.getElementById('description').className = '';\n\t\tdocument.getElementById('descriptionToggle').innerHTML = text[1];\n\t}\n\telse {\n\t\t// Info verstecken\n\t\tdocument.getElementById('description').className = 'hide';\n\t\tdocument.getElementById('descriptionToggle').innerHTML = text[0];\n\t}\t\n}",
"function showinfo(moduleid, infotext)\n{\n if(moduleid) {\n var moduleinfo = 'moduleinfo_' + moduleid;\n var module = 'modulecontent_' + moduleid;\n if(!Element.hasClassName(moduleinfo, 'z-hide')) {\n Element.update(moduleinfo, ' ');\n Element.addClassName(moduleinfo, 'z-hide');\n Element.removeClassName(module, 'z-hide');\n } else {\n Element.update(moduleinfo, infotext);\n Element.addClassName(module, 'z-hide');\n Element.removeClassName(moduleinfo, 'z-hide');\n }\n } else {\n $A(document.getElementsByClassName('z-moduleinfo')).each(function(moduleinfo){\n Element.update(moduleinfo, ' ');\n Element.addClassName(moduleinfo, 'z-hide');\n });\n $A(document.getElementsByClassName('modulecontent')).each(function(modulecontent){\n Element.removeClassName(modulecontent, 'z-hide');\n });\n }\n}",
"function showDownloadPageText() {\n\t\treturn \t\"<div style='width: 100%; height: 100%; color: white; background-color: black'>\" +\n\t\t\t\"<div align='center'>\" +\n\t\t\t\"<h2>Widevine Video Optimizer is not installed</h2>\" +\n\t\t\t\"<input type='button' value='Get Video Optimizer' OnClick='javascript: window.open(\\\"http://tools.google.com/dlpage/widevine\\\");'>\" +\n\t\t\t\"</div>\" +\n\t\t\t\"</div>\"\n\t}",
"function displayItemMessage(msg) {\n document.getElementById('warning-mess').innerHTML = msg;\n}",
"function Insfunc() {\n var x = document.getElementById(\"instructions\");\n // if the is no style display assign to block i.e put the text there\n if (x.style.display === \"none\") {\n x.style.display = \"block\";\n }\n // if block or anything else assign to none\n else {\n x.style.display = \"none\"\n }\n }",
"function revealLyrics(title, lyrics) {\r\n qs(\"#modal h2\").innerText = title;\r\n qs(\"#modal p\").innerText = lyrics;\r\n $(\"modal\").classList.remove(\"hidden\");\r\n }",
"addInstructionsToDisplay () {\n banner.appendChild(document.createElement('p'))\n .innerHTML = `win by guessing the phrase before losing all of your hearts`;\n }",
"function confirmerSuppression() {\n let n = new Noty({\n text: 'Confirmer la demande de suppression ',\n layout: 'center', theme: 'sunset', modal: true, type: 'info',\n animation: {\n open: 'animated lightSpeedIn',\n close: 'animated lightSpeedOut'\n },\n buttons: [\n Noty.button('Oui', 'btn btn-sm btn-success marge ', function () {\n supprimer();\n n.close();\n }),\n Noty.button('Non', 'btn btn-sm btn-danger', function () { n.close(); })\n ]\n }).show();\n}",
"function otherLoansShowFeedback() {\n \n // TO DO\n // populate feedback based on the displayed user\n \n document.getElementById('block-other-loans-show-feedback').style.display = \"\";\n \n}",
"function alertSecurity() {\n var txt;\n if (confirm(\"Are you sure to notify Security?\")) {\n alert(\"Already notified Security.\");\n } else {\n alert(\"Canceled to notify Security!\");\n }\n }",
"function hideTitle() {\n UIController.getExpandedCoupon().firstElementChild.firstElementChild.classList.remove('show');\n }",
"function showRiskAssessmentWarningDialogue() {\n showDialog({\n title: 'WARNING: Inconsistent data',\n text: 'Elements on this page need correcting: \\nThe objective weights for each category must TOTAL 100 \\nProblem groups highlighted in red.'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}",
"function onReadLessClick() {\n $('#show-this-on-click').slideUp();\n $('.readless').hide();\n $('.readmore').show();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes a plot with the given stock symbol. | removePlot(symbol) {
if (this.data.hasOwnProperty(symbol)) {
this.g.select('.plot-line-' + symbol)
.remove();
this.g.selectAll('.price-point-' + symbol)
.remove();
// Finally, add the used color back, and remove symbol data
var color = this.data[symbol].color;
this.colors.push(color);
delete this.data[symbol];
// Scale y-values with existing plots
this.minY = this.ctrl.getGlobalMinY(this.data);
this.maxY = this.ctrl.getGlobalMaxY(this.data);
this.rescaleY(this.minY, this.maxY, true);
var symbols = Object.keys(this.data);
symbols.forEach( (sym) => {
if (sym !== symbol) {
this.redrawPlot(sym);
}
});
}
else {
console.error('No symbol. Cannot remove ' + symbol);
}
} | [
"removeStockFromChart(symbol) {\n for (let i = 0, n = this.stockChart.series.length; i < n; i++) {\n const series = this.stockChart.series[i];\n if (series.name === symbol) {\n this.stockChart.series[i].remove();\n return;\n }\n }\n }",
"removeStock(stockSymbol) {\n // for best user experience, immediately remove stock from stoock table,\n // and update chart\n const stockElement = document.querySelector('.stock[data-symbol=\"' + `${stockSymbol.toLowerCase()}` + '\"]');\n this.removeStockFromStockTable(stockElement);\n\n this.removeStockFromChart(stockSymbol);\n\n // then request updating on server\n stockService.remove(stockSymbol, (err, data) => {\n // for any error occurs, check all stocks on database after 15s\n if (err) {\n setTimeout(() => {\n this.loadStocks();\n }, 15000);\n }\n });\n\n // finally, inform to server then server can broadcast to other clients about removed stock\n this.stockSocket.sendRemovalEvent(stockSymbol);\n }",
"function clearScatterPlot(){\r\n svg.selectAll(\".axis\").remove();\r\n svg.selectAll('.dot').remove();\r\n svg.selectAll('.extraTextSP').remove();\r\n }",
"function removeTrendChart() {\r\n $('.trendChartData').hide();\r\n $('#trendChartLegend').hide();\r\n $('#lineChartLegend').show();\r\n}",
"function removeInvestment (symbol) {\n portfolio = portfolio.filter(item => item.symbol !== symbol)\n // blacklist.push(symbol) //\n buying = true\n}",
"function removeFromWatchList() {\n var stockSymbol = $(this).attr(\"data-name\");\n\n console.log(\"in removeFromWatchList, remove: \" + stockSymbol);\n\n // remove row so as to not repeat stock symbol on watchlist\n $(\"#wrow-\" + stockSymbol).remove();\n\n // check if watch table is empty\n if ($(\"#watch-table\").children().length === 0) {\n $(\"#watch-table-header\").hide();\n $(\"#watchlist-caption\").hide();\n }\n }",
"function removeAmChart(id) {\n var tmp_am = getAmChart(id);\n if(tmp_am){\n tmp_am.clear();\n }\n}",
"removeSlot() {\n this.closet.removeSlot();\n var closet_slot_face_id = this.closet_slots_faces_ids.pop();\n this.group.remove(this.group.getObjectById(closet_slot_face_id));\n this.updateClosetGV();\n }",
"function removeAgeChart() {\n var ageChart = document.getElementById(\"ageChart\");\n if (ageChart) {\n ageChart.remove();\n }\n}",
"function clearHtml() {\n $(\"#searchChart\").remove();\n}",
"function clearChart() {\r\n\td3.select('#chartDiv').selectAll('svg').remove();\r\n}",
"function removeFromWatchList() {\n var stockSymbol = $(this).attr(\"data-name\");\n\n console.log(\"in removeFromWatchList, remove: \" + stockSymbol);\n appUser.removeFromWatch(stockSymbol);\n\n // remove row so as to not repeat stock symbol on watchlist\n $(\"#wrow-\" + stockSymbol).remove();\n\n // check if watch table is empty\n if ($(\"#watch-table\").children().length === 0) {\n $(\"#watch-table-header\").hide();\n $(\"#watchlist-caption\").hide();\n }\n }",
"function RemoveLines() {\n\tplot.selectAll(\"path.line\").remove()\n}",
"removeFigure(figure){\n\t\tthis.boardMatrix[figure.positionY][figure.positionX].sprite.destroy();\n\t\tthis.boardMatrix[figure.positionY][figure.positionX].figure = null;\n\t\tfigure.isAlive = false;\n\t}",
"addStockToChart(symbol, data) {\n this.stockChart.addSeries({\n name: symbol,\n data: data\n });\n }",
"function delistStock(stock, stocksArr) {\n stocksArr.splice(stocksArr.indexOf(stock), 1);\n delistArr.push(stock.symbol);\n localStorage.setItem(\"delist\", JSON.stringify(delistArr));\n }",
"function stop() \r\n {\r\n\t //get choosen location\r\n\t var locations = document.getElementById(\"location\");\r\n\t var loc = locations.options[locations.selectedIndex].value;\r\n\t\r\n\t //go through array of already set up graphs\r\n\t for(var i = 0; i < array.length; i++) \r\n\t {\r\n\t\t \t//check graph position\r\n\t\t\tif(array[i][0]==loc)\r\n\t\t\t{\r\n\t\t\t\t//then delete it\r\n\t\t delete array[i];\r\n\t\t array = array.filter(function(n){ return n != undefined }); \r\n\t\t $(\"#\" + loc).empty();\r\n\t \t plot.destroy();\r\n\t \t \r\n\t\t\t}\r\n\t}\r\n }",
"function removeBarChart(width, height) {\r\n\tdocument.getElementById(\"stacked-barchart\").innerHTML = \"\";\r\n\tdocument.getElementById(\"stacked-barchart\").setAttribute('width', width);\r\n\tdocument.getElementById(\"stacked-barchart\").setAttribute('height', height);\r\n}",
"function removeTitle() {\n clearTimeout(expClock);\n svgPath.selectAll(\".title\").remove();\n svgPath.selectAll(\".clock\").remove();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Expose the brightness API. | static availableAPI(builder) {
builder.state('brightness')
.type('percentage')
.description('The brightness of this light')
.done();
builder.event('brightness')
.type('percentage')
.description('The brightness of the light has changed')
.done();
builder.action('brightness')
.description('Get or set the brightness of this light')
.argument('change:brightness', true, 'The change in brightness or absolute brightness')
.returns('percentage', 'The brightness of the light')
.getterForState('brightness')
.done();
} | [
"function Light_2(){\n this.brightness = 0;\n this['turnon'] = function turnon (){\n this.brightness += 1 ;\n }\n this['turnoff'] = function turnoff(){\n if(this.brightness > 0){\n this.brightness -= 1;\n }\n }\n this['toggle'] = function toggle(){\n this.brightness += 2 ;\n }\n}",
"function lightStatus(brightness) {\n let result = brightness;\n\n if (brightness == 0) {\n result = \"off\";\n } else if (brightness > 0 && brightness < 200) {\n result = \"dimmed\";\n } else if (brightness >= 200) {\n result = \"on\";\n }\n\n return result;\n}",
"onShow() {\n brightness.setValue({\n value: 255,\n });\n brightness.setKeepScreenOn({\n keepScreenOn: true,\n });\n clearInterval(this.testInterval);\n\n }",
"addServices (accessory) {\n const informationService = accessory.getService(Service.AccessoryInformation); // new Service.AccessoryInformation();\n this.remote_type = this.accessory.context.light_info.remote_type;\n if (informationService) {\n informationService\n .setCharacteristic(Characteristic.Manufacturer, 'MiLight')\n .setCharacteristic(Characteristic.Model, accessory.context.light_info.remote_type)\n .setCharacteristic(Characteristic.SerialNumber, accessory.context.light_info.group_id + '/' + accessory.context.light_info.device_id)\n .setCharacteristic(Characteristic.FirmwareRevision, packageJSON.version);\n } else {\n this.log('Error: No information service found');\n }\n const lightbulbService = new Service.Lightbulb(this.name);\n lightbulbService.addCharacteristic(new Characteristic.Brightness());\n if (this.platform.rgbRemotes.includes(this.remote_type) || this.platform.rgbcctRemotes.includes(this.remote_type)) {\n lightbulbService.addCharacteristic(new Characteristic.Saturation());\n lightbulbService.addCharacteristic(new Characteristic.Hue());\n }\n if (this.platform.whiteRemotes.includes(this.remote_type) || (this.platform.rgbcctMode && this.platform.rgbcctRemotes.includes(this.remote_type))) {\n lightbulbService\n .addCharacteristic(new Characteristic.ColorTemperature())\n .updateValue(370)\n .setProps({\n maxValue: 370, // maxValue 370 = 2700K (1000000/2700)\n minValue: 153 // minValue 153 = 6500K (1000000/6500)\n });\n }\n accessory.addService(lightbulbService);\n }",
"function updateBrightness(oldContext,brightnessPercent,operateInPlace) {\n\tif (operateInPlace == null) {\n\t\toperateInPlace = false;\n\t}\n\t//copy old canvas to new canvas, if in-place operation is not desired\n\tvar newContext = operateInPlace ? oldCanvas : createContext(oldContext.canvas.width,oldContext.canvas.height,false); \n\tnewContext.drawImage(oldContext.canvas,0,0);\n\tnewContext.globalAlpha = brightnessPercent;\n\tnewContext.fillStyle = brightnessPercent >= 0 ? 'rgba(225,225,225,' + (brightnessPercent*.01) + ')' : 'rgba(0,0,0,' + (-1*(brightnessPercent*.01)) + ')';\n\tnewContext.fillRect(0,0,newContext.canvas.width,newContext.canvas.height);\n\t\n\t//set context vars back when we are done\n\tnewContext.globalAlpha = oldContext.globalAlpha;\n\tnewContext.fillStype = oldContext.fillStyle;\n\treturn newContext;\n}",
"function ledOnOff(event,x,y) {\n\t//set brightness to off (0)\n\tvar brightness = 0;\n //set current LED\n\tvar currentLED = document.getElementById('led('+x+','+y+')');\n var LEDTest = window.getComputedStyle(currentLED, null).getPropertyValue('background-color');\n //if LED off then switch on (turn red)\n if (LEDTest == 'rgb(128, 128, 128)') {\n \tcurrentLED.style.backgroundColor = 'red'; //rgb(255, 0, 0)\n //set brightness to max (9)\n brightness = 9;\n }\n //if LED not off then switch off (grey)\n if (LEDTest != 'rgb(128, 128, 128)') {\n \tcurrentLED.style.backgroundColor = 'grey'; //rgb(51, 51, 51)\n //set brightness to off (0)\n brightness = 0;\n } \n}",
"pulseLights() {\n console.log('[johnny-five] Testing lights with pulse function.');\n this.lights.pulse();\n }",
"setYellowLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet lights = this.config.getDirections()[this.getDirectionIndex()];\n\n\t\t// Set the traffic lights to green based on the direction of the traffic\n\t\tlights.map((direction) => {this.trafficLights[direction].color = TRAFFIC_LIGHT_YELLOW;});\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}",
"function brightnessFilter ( sourceImageData){\n //build imageData\n var returnImageData = ctx.createImageData(canvas.width, canvas.height);\n var imageDataArray = returnImageData.data;\n for(var i=0; i < sourceImageData.data.length; i+=4){\n imageDataArray[i] = setNewColor(sourceImageData.data[i] + brightnessValue);\n imageDataArray[i+1] = setNewColor(sourceImageData.data[i+1] + brightnessValue);\n imageDataArray[i+2] = setNewColor(sourceImageData.data[i+2] + brightnessValue);\n imageDataArray[i+3] = sourceImageData.data[i+3];\n }\n\n returnImageData.data = imageDataArray;\n\n return returnImageData;\n \n}",
"get lightsOn()\r\n\t{\r\n\t\treturn this._lightsOn;\r\n\t}",
"lightsOn() {\n console.log('[johnny-five] Lights are on.');\n this.lights.on();\n }",
"setGreenLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet lights = this.config.getDirections()[this.getDirectionIndex()];\n\n\t\t// Set the traffic lights to green based on the direction of the traffic\n\t\tlights.map((direction) => {this.trafficLights[direction].color = TRAFFIC_LIGHT_GREEN;});\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}",
"function getBrightness(palette) {\n return palette\n .map(color => {\n return rgbToHsl(color).l\n })\n .reduce((sum, val) => {\n return sum + val\n })\n /palette.length\n}",
"function drawStatusLED()\n {\n // Check faulted state\n var faultCount = Object.keys(fault_detector.getCurrentFaults()).length;\n if (faultCount > 0)\n {\n // Set LED to green\n image = document.getElementById('status_led');\n image.src = 'static/images/red_light.png';\n }\n else\n {\n image = document.getElementById('status_led');\n image.src = 'static/images/green_light.png';\n }\n }",
"setRedLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet currentGreenLights = this.config.getDirections()[this.getDirectionIndex()];\n\n // Loop through the greenLights and set the rest to red lights\n\t\tfor (let direction in this.trafficLights) {\n\t\t\tlet elementId = this.trafficLights[direction].name;\n\t\t\tif (currentGreenLights.indexOf(elementId) >= 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.trafficLights[direction].color = TRAFFIC_LIGHT_RED;\n\t\t}\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}",
"function apiShow(req, res) {\n //console.log('GET /api/breed/:name');\n // return JSON object of specified breed\n db.Breed.find({name: req.params.name}, function(err, oneBreed) {\n if (err) {\n res.send('ERROR::' + err);\n } else {\n res.json({breeds: oneBreed});\n }\n });\n}",
"function getBatteryState() {\n var batteryLevel = Math.floor(battery.level * 10),\n batteryFill = document.getElementById(\"battery-fill\");\n\n batteryLevel = batteryLevel + 1;\n batteryFill.style.width = batteryLevel + \"%\";\n }",
"function updateLeds() {\n if (led_state.Red===\"blink\") {\n GPIO.blink(pin_Red, blink_On, blink_Off);\n }else {\n GPIO.blink(pin_Red,0,0); //Turn off blinking\n let redlight=(led_state.Red==='1') ? 1:0 ; \n GPIO.write(pin_Red,redlight);\n }\n if (led_state.Blue===\"blink\") {\n GPIO.blink(pin_Blue, blink_On, blink_Off);\n }else {\n GPIO.blink(pin_Blue,0,0); //Turn off blinking\n let bluelight=(led_state.Blue==='1') ? 1:0 ; \n GPIO.write(pin_Blue,bluelight);\n }\n}",
"getTrafficLights() {\n\t\treturn this.trafficLights;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This property stores the available streams, indexed by the content identifier, and contains the stream data, the video plugin and the player, for each content identifier. | get streams() {
return this._streams;
} | [
"getSystemStreamsList () {\n if (!SystemStreamsSerializer.systemStreamsList) {\n let systemStreams = [];\n let i;\n const streamKeys = Object.keys(this.systemStreamsSettings);\n\n for (i = 0; i < streamKeys.length; i++) {\n systemStreams.push({\n name: streamKeys[i],\n id: SystemStreamsSerializer.addDotToStreamId(streamKeys[i]),\n parentId: null,\n children: buildSystemStreamsFromSettings(\n this.systemStreamsSettings[streamKeys[i]],\n [],\n SystemStreamsSerializer.addDotToStreamId(streamKeys[i])\n )\n });\n }\n SystemStreamsSerializer.systemStreamsList = systemStreams;\n }\n return SystemStreamsSerializer.systemStreamsList;\n }",
"get stream() { return ($(\"home_stream\") || $(\"pagelet_intentional_stream\") || $(\"app_stories\") || $(\"pagelet_wall\") || $(main.streamID)); }",
"function StreamList() {\n this.streamList = {};\n }",
"function setupStreams() {\n // setup communication to page and plugin\n var pageStream = new LocalMessageDuplexStream({\n name: 'nifty-contentscript',\n target: 'nifty-inpage'\n });\n var pluginPort = extension.runtime.connect({ name: 'contentscript' });\n var pluginStream = new PortStream(pluginPort);\n\n // forward communication plugin->inpage\n pump(pageStream, pluginStream, pageStream, function (err) {\n return logStreamDisconnectWarning('DefiMask Contentscript Forwarding', err);\n });\n\n // setup local multistream channels\n var mux = new ObjectMultiplex();\n mux.setMaxListeners(25);\n\n pump(mux, pageStream, mux, function (err) {\n return logStreamDisconnectWarning('DefiMask Inpage', err);\n });\n pump(mux, pluginStream, mux, function (err) {\n return logStreamDisconnectWarning('DefiMask Background', err);\n });\n\n // connect ping stream\n var pongStream = new PongStream({ objectMode: true });\n pump(mux, pongStream, mux, function (err) {\n return logStreamDisconnectWarning('DefiMask PingPongStream', err);\n });\n\n // connect phishing warning stream\n var phishingStream = mux.createStream('phishing');\n phishingStream.once('data', redirectToPhishingWarning);\n\n // ignore unused channels (handled by background, inpage)\n mux.ignoreStream('provider');\n mux.ignoreStream('publicConfig');\n}",
"loadDataStreamList() {\n this._dataStreamList = [];\n let servers = this.dataModelProxy.getUserConfig().getDashboardConfig().getServerList();\n let serverID = 0;\n for (let server in servers) {\n if (logging) console.log(\"Retrieving Datastreams from Server:\", servers[server].url);\n let sID = serverID;\n let cb = function(a) {\n this.dataStreamListAvailable(a, sID);\n };\n this.sensorThingsCommunications.getDataStreamList(servers[server].url, cb.bind(this));\n serverID++;\n }\n }",
"function getAllStreamers() {\r\n clearElements();\r\n getStreamData(\"all\");\r\n }",
"getAllSystemStreamsIds () {\n if (!SystemStreamsSerializer.allSystemStreamsIds) {\n let systemStreams = [];\n let i;\n const streamKeys = Object.keys(this.systemStreamsSettings);\n\n for (i = 0; i < streamKeys.length; i++) {\n systemStreams.push(SystemStreamsSerializer.addDotToStreamId(streamKeys[i]));\n _.merge(systemStreams,\n Object.keys(getStreamsNames(this.systemStreamsSettings[streamKeys[i]])))\n }\n SystemStreamsSerializer.allSystemStreamsIds = systemStreams;\n }\n return SystemStreamsSerializer.allSystemStreamsIds;\n }",
"getMediaplayerSettings() {\n return {\n \n stream: { src: App.getPath(`DStv_Promo_(The_Greatest_Show).mp4`) }\n }\n }",
"getStream() {\n if (this.mediaStream !== null && (typeof (this.mediaStream) !== null) && this.mediaStream !== undefined) { return this.mediaStream; }\n return null;\n }",
"_getVideoDevices() {\n return from(navigator.mediaDevices.enumerateDevices()).pipe(map(devices => devices.filter(device => device.kind === 'videoinput')));\n }",
"function currentStream(callback) {\n chrome.storage.sync.get(\"streamSource\", function(result){\n saved = result.streamSource;\n document.getElementById(\"currentStream\").innerHTML = \"Current Stream: \" + saved;\n });\n}",
"static getAllAccountStreams () {\n if (!SystemStreamsSerializer.allAccountStreams) {\n SystemStreamsSerializer.allAccountStreams = getStreamsNames(SystemStreamsSerializer.getAccountStreamsConfig(), allAccountStreams);\n }\n return SystemStreamsSerializer.allAccountStreams;\n }",
"mergeStreamInfo() {\n for(var key in this.extraStreamInfo) {\n if (!this.extraStreamInfo.hasOwnProperty(key)) {\n continue;\n }\n this.streamInfo[key] = this.extraStreamInfo[key];\n }\n }",
"function loadVideoStream (url) {\n\tvar outputVideo = '';\n\t$('#stream').click(function(e){\n\t\te.preventDefault();\n\t\t$.getJSON( url + '/main_page/build_video_stream', function(data){\n\t\t\tif (data.result != false) {\n\t\t\t\t$.each(data, function(){\n\t\t\t\t\t$.each(this, function(key, value){\n\t\t\t\t\t\t// console.log(value);\n\t\t\t\t\t\toutputVideo += generateVideoTags(value);\n\t\t\t\t\t})\n\t\t\t\t});\n\t\t\t\t// var element = document.getElementById('list_video');\n\t\t\t\t// element.innerHTML = outputVideo;\n\t\t\t\t$(\"#list_video\").html(outputVideo);\n\t\t\t\t// $('#ul').show().html\n\t\t\t};\n\t\t\t// console.log(outputVideo);\n\t\t\t// console.log(data);\n\t\t})\n\t})\n}",
"function getOfflineStreamers() {\r\n clearElements();\r\n getStreamData(\"offline\");\r\n }",
"EnumerateStreams() {\n\n }",
"function getMediaOffers() {\n /* The \"mediaOffer\" link may have the following form:\n *\n * data:multipart/alternative;charset=utf-8;boundary=e47d80f2,\n * --e47d80f2\n * Content-Type:+application/sdp\n * Content-ID:+<9544aa8a8ac9dfe08fad74893bd1095e@contoso.com>\n * Content-Disposition:+session;+handling=optional;+proxy-fallback\n *\n * v=0\n * o=-+0+0+IN+IP4+127.0.0.1\n * s=session\n * ...\n *\n * --e47d80f2\n * Content-Type:+application/sdp\n * Content-ID:+<cdfd6188fd977372c577873b03dd580d@contoso.com>\n * Content-Disposition:+session;+handling=optional\n *\n * v=0\n * o=-+0+1+IN+IP4+127.0.0.1\n * s=session\n * c=IN+IP4+127.0.0.1\n * ...\n *\n * --e47d80f2\n */\n var href, dataUri, responses;\n href = resource.relatedHref('mediaOffer');\n if (!href)\n return [];\n dataUri = DataUri(href);\n try {\n responses = parseMultipartRelatedResponse({\n status: null,\n responseText: dataUri.data,\n headers: 'Content-Type:multipart/related;boundary=' + dataUri.attributes.boundary\n });\n return map(responses, function (response) {\n var headers = HttpHeaders(response.headers);\n return {\n sdp: response.responseText,\n id: headers.get('Content-ID')\n };\n });\n }\n catch (error) {\n // if the media offer is not a multipart/alternate-encoded\n // set of SDPs, consider it as a single SDP\n return [{\n sdp: dataUri.data,\n id: ''\n }];\n }\n }",
"function _fetchVideos(){\n\t\t\t// the from value is defined by my videoList length + 1. If it isn't defined yet, its value is 1\n\t\t\tvar from = context.videoList.length ? context.videoList.length + 1 : 1;\n\t\t\tvar requestData = { sessionId: SessionIdManager.getSessionId(), skip: from };\n\n\t\t\tVideoListService.getVideoList(requestData)\n\t\t\t\t.then(function (response) {\n\t\t\t\t\t// here I map the videos from response, so each one of them ca have\n\t\t\t\t\t// a configuration to display the video, according to the videogular API\n\t\t\t\t\tresponse.data.data.map(function (item) {\n\t\t\t\t\t\titem.config = {\n\t\t\t\t\t\t\tsources: [\n\t\t\t\t\t\t\t\t{src: $sce.trustAsResourceUrl(item.url), type: \"video/mp4\"}\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t};\n\t\t\t\t\t\t// calculates the video overallRating\n\t\t\t\t\t\titem.overallRating = _getRatingOverall(item.ratings);\n\n\t\t\t\t\t\t// add to my videoList\n\t\t\t\t\t\tcontext.videoList.push(item);\n\t\t\t\t\t});\n\n\t\t\t\t\tcontext.hasVideos = response.data.data.length;\n\t\t\t\t})\n\t\t\t\t.catch(function (error) {\n\t\t\t\t\tCustomToastService.show(error.message);\n\t\t\t\t})\n\t\t}",
"static getReadableAccountStreams () {\n if (!SystemStreamsSerializer.readableAccountStreams){\n SystemStreamsSerializer.readableAccountStreams = getStreamsNames(\n SystemStreamsSerializer.getAccountStreamsConfig(),\n readable\n );\n }\n return SystemStreamsSerializer.readableAccountStreams;\n }",
"static getReadableAccountStreamsForTests () {\n if (!SystemStreamsSerializer.readableAccountStreamsForTests) {\n let streams = getStreamsNames(SystemStreamsSerializer.getAccountStreamsConfig(), readable);\n delete streams[SystemStreamsSerializer.addDotToStreamId('storageUsed')];\n SystemStreamsSerializer.readableAccountStreamsForTests = streams;\n }\n return SystemStreamsSerializer.readableAccountStreamsForTests;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
mousePressed() Checks if the player clicked on the target and if so tells them they won | function mousePressed() {
// Check if the mouse is in the x range of the target
if (mouseX > targetX - targetImage.width/2 && mouseX < targetX + targetImage.width/2) {
// Check if the mouse is also in the y range of the target
if (mouseY > targetY - targetImage.height/2 && mouseY < targetY + targetImage.height/2) {
gameOver = true;
}
}
} | [
"function mousePressed() {\n // Check if the mouse is in the x range of the target\n if (mouseX > targetX - targetImage.width/2 && mouseX < targetX + targetImage.width/2) {\n // Check if the mouse is also in the y range of the target\n if (mouseY > targetY - targetImage.height/2 && mouseY < targetY + targetImage.height/2) {\n //add in victory music\n winningSound.play();\n gameOver = true;\n }\n }\n}",
"function mousePressed() {\n if (state === `title`) {\n state = `game`;\n } else if (state === `game`) {\n checkCircleClick();\n }\n}",
"function mousePressed() {\n playing = true;\n}",
"function mousePressed() {\n shocked = true;\n}",
"function mouseReleased(){\n\n shocked = false;\n\n}",
"function mousePressed() {\n birthday();\n mouseWasPressed += 1;\n}",
"function choosePlayer() {\n if(mouse.y > 362 && mouse.y < 442) { // player1\n if(mouse.x > 15 && mouse.x < 85) {\n player.sprite = playerImages[0]; \n Demo.menu2Game();\n }\n else if(mouse.x >= 118 && mouse.x < 185) { // player2\n player.sprite = playerImages[1]; \n Demo.menu2Game();\n }\n else if(mouse.x >= 218 && mouse.x < 285) { // player3\n player.sprite = playerImages[2]; \n Demo.menu2Game();\n }\n else if(mouse.x >= 315 && mouse.x < 388) { // player4\n player.sprite = playerImages[3]; \n Demo.menu2Game();\n }\n }\n }",
"function yellowClick() {\n\tyellowLight();\n\tuserPlay.push(3);\n\tuserMovement();\t\n}",
"mouseDown() {\n if (mouseOver != 0) {\n if (this.situation === \"choose\") {\n // if the fight button is clicked, go to fight state\n if (mouseOver === \"fight\") {\n this.goToFight();\n }\n // if a player is moused over, that player character is now the front line\n else if (playersList.includes(mouseOver)) {\n frontline = mouseOver;\n // if a player's ability is moused over, then clicking selects that ability to be used\n } else if (currentChar.abilities[0].includes(mouseOver)) {\n // if this ability is not an ultimate, and if they have enough energy to use it, and it has not been used this turn then it works\n if (mouseOver.ultimate === false && currentChar.energy - mouseOver.cost >= 0 && mouseOver.used === false) {\n this.selectAbility();\n } else if (mouseOver.ultimate === true && currentChar.ultCharge === 100) {\n this.selectAbility();\n } else {\n console.log(\"not enough\");\n console.log(mouseOver.ultimate);\n console.log(currentChar.energy - mouseOver.cost)\n console.log(mouseOver.used);\n }\n }\n }\n if (this.situation === \"ability\") {\n // for each effect, happens\n for (var i = 0; i < currentAbility.effects.length; i++) {\n if (currentAbility.currentEffect.aoe === false) {\n // if this ability can target this moused over character activate ability\n if (mouseOver !== 0) {\n if (currentAbility.currentEffect.canTargetsList.includes(mouseOver)) {\n currentAbility.currentEffect.targets.push(mouseOver);\n currentAbility.user = currentChar;\n if (currentAbility.ultimate === true) {\n A_SUPPORT_ULT.play();\n currentAbility.user.ultCharge -= 100;\n } else {\n A_SUPPORT.play();\n }\n currentAbility.happens();\n this.situation = \"choose\";\n // if the cancel button is moused over, cancel the ability\n } else if (mouseOver === \"cancel\") {\n this.situation = \"choose\";\n }\n }\n } else if (currentAbility.currentEffect.aoe === true) {\n for (var i2 = 0; i2 < currentAbility.currentEffect.canTargetsList.length; i2++) {\n currentAbility.currentEffect.targets.push(currentAbility.currentEffect.canTargetsList[i2]);\n }\n currentAbility.user = currentChar;\n if (currentAbility.ultimate === true) {\n A_SUPPORT_ULT.play();\n currentAbility.user.ultCharge -= 100;\n } else {\n A_SUPPORT.play();\n }\n currentAbility.happens();\n this.situation = \"choose\";\n }\n }\n }\n }\n }",
"playerWins(){ // i2 - put inline\n\t\tif (this.player === activePlayer && playing === false) {\n\t\t\treturn true;\n\t\t}\t}",
"function mouseAction(event) { \nif((isWhite && whitePly) || (isBlack && !whitePly)) { //check player\n\n if(gameOver) { return; }\n var mouseX = event.clientX / aspectRatio;\n var mouseY = event.clientY / aspectRatio;\n var x = Math.floor(mouseX / squareSize);\n\n var y = Math.floor(mouseY / squareSize);\n if (isBlack) {\n y = 7 - y; //black's board is inverted to have black pieces at the bottom.\n x = 7 - x; // and mirrored\n\n }\n if(event.button === 0) {\n\tif(selectedSquare[0] == -1 || !isPieceSelected || boardArray[y][x] != \" \") {\n\t\tvar piece = boardArray[y][x]\n\t if(piece != \" \" && isTurn(piece)) {\n\t \t\tisPieceSelected = true;\n\t \t\tconsole.log(x);\n\t\t\tconsole.log(y);\n\t\t\tselectedSquare = [y, x];\n\t\t\tdrawPosition();\n\t\t\tlegalMoves = [];\n\t\t\tlegalMoves = findLegalMoves(y, x, true);\n\t\t\t\n\t\t\tdrawPosition();\n\t\t\t\n\t } else {\n \tmoveHandler(x,y);\n \t\n \tisPieceSelected = false;\n \tdrawPosition();\n\t }\n\t\t \n\t \n\t} else {\n\t\tmoveHandler(x, y);\n\t\t\n\t\tisPieceSelected = false;\n\t\tdrawPosition();\n\t\t\n\t}\t\t\t\t\t\t\t \n }\n} else { drawPosition(); }\n}",
"function redClick() {\n\tredLight();\n\tuserPlay.push(2);\n\tuserMovement();\t\n}",
"playButtonPressed() {\n this.setPropertyInputVisibility(false);\n this.playButton.visible = false;\n this.game.multiplayerHandler.sendStartMessage();\n }",
"function holdHandler(e){\n\te.preventDefault();\n\tif(gamePlaying)\n\t{\n\t\t//add current score to GLOBAL score\n\tscores[activePlayer] += roundScore;\n\n\t//update the current player socre\n\tdocument.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];\n\n\t//check if which player reaches the 100 points is the winner\n\tif(scores[activePlayer] >= 20){\n\t\tdocument.querySelector('#name-' + activePlayer).textContent = 'Winner!';\n\t\tgamePlaying = false;\n\t\t//hide the current player indicator and the dice image\n\t\tdocument.querySelector('.dice').style.display='none';\n\t\tdocument.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');\n\t\tdocument.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');\n\n\t}else{\n\t\t\tnextPlayer();\n\t\t}\n\t}\n\t\n\t\n}",
"function mousePressed() {\n if (mouseY < dSlider.y) { // if you clicked above the slider,\n trackColor = video.get(mouseX,mouseY); // get the color you clicked\n }\n}",
"checkIfWin(){\n\t\tconst g = this.state.grid;\n\t\tvar hits = 0;\n\n\t\tfor(var i = 0; i < this.gridSize; i++) {\n\t\t\tfor(var j = 0; j < this.gridSize; j++) {\n\t\t\t\tif (g[i][j] === \"Hit\") {\n\t\t\t\t\thits++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(hits === this.maxNumberOfShips*2){\n\t\t\tvar theWinner = \"\";\n\n\t\t\tif(this.props.id === \"gridA\"){\n\t\t\t\ttheWinner = \"PlayerB\";\n\t\t\t\tthis.props.handleWin(theWinner);\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttheWinner = \"PlayerA\";\n\t\t\t\tthis.props.handleWin(theWinner);\n\t\t\t}\n\n\t\t}\n\n\t}",
"function mousePressed(){\r\n count-=1;\r\n if(gameState===\"PLAY\" && count>0){\r\n particle=new Particle(mouseX,10,10);\r\n }\r\n}",
"function pressTheButton() {\n\tvalue = this.value;\n\tplayerInput(value);\n\tcpuInput();\n\tdetermineWinner();\n\tdisplay();\n}",
"function onHit() {\n this.classList.remove(\"active\");\n this.classList.add(\"target\");\n scoreIncrement();\n time = time - 10;\n}",
"function mousePressed(){\n if(selected === null){\n let collision = checkClick(mouseX, mouseY);\n if(collision !== null){\n selected = collision;\n }else{\n createVertex();\n }\n }else{\n let collision = checkClick(mouseX, mouseY);\n if(collision === null){\n selected = null;\n }else{\n if(lengthType.checked() || (lengthInput.value() != '' && (!isNaN(lengthInput.value())))){\n digraph.addEdge(selected, collision, lengthInput.value());\n }\n if(isNaN(lengthInput.value())){\n lengthInput.value('');\n }\n selected = null;\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
write hash entry data | function writeHashEntry(score, bestMove, depth, hashFlag) {
// init hash entry
var hashEntry = hashTable[(hashKey & 0x7fffffff) % hashEntries];
// adjust mating scores
if (score < -MATE_SCORE) score -= searchPly;
if (score > MATE_SCORE) score += searchPly;
// write hash entry data
hashEntry.hashKey = hashKey;
hashEntry.score = score;
hashEntry.flag = hashFlag;
hashEntry.depth = depth;
hashEntry.bestMove = bestMove;
} | [
"function writeToDoc(hash) {\n hash['url'] = discoverTrueUrl(hash);\n //currentUrl is now the correct URI\n var followedPost = UrlFetchApp.fetch(hash['url'], {'followRedirects': true, 'muteHttpExceptions': true});\n hash['dump'] = followedPost.getContentText();\n //companyName\tLink\trecipient\tsubmitted?\tEffort Level\tLast FollowUp\tjobTitle\tcompanyBlurb\tcompanyCity\tComment\tuseEmailAddress\temailSentDate\tfullListingContent\n var prettyDate = stringifiedCurrentDate();\n Logger.log(hash['url']);\n SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].appendRow([hash['company'], hash['url'], \"\", 1, \"Low\", prettyDate, hash['jobtitle'], \"\", hash['formattedLocation'], \"\", 0, \"\", hash['dump']]);\n}",
"write(str) {\n Files.write(nodePath.join(Files.gitletPath(), 'objects', Util.hash(str)), str);\n return Util.hash(str);\n }",
"async insert (entry) {\n try {\n console.log('entry: ', entry)\n\n // Add the entry to the Oribit DB.\n const hash = await _this.orbit.db.put(entry.key, entry.value)\n console.log('hash: ', hash)\n\n return hash\n } catch (err) {\n console.error('Error in p2wdb.js/insert()')\n throw err\n }\n }",
"function addLevelDBData(key, value) {\n //console.log(\"Current key value is \" + key)\n db.put(key, JSON.stringify(value), function(err) {\n if (err) return console.log('Block ' + key + ' submission failed', err);\n });\n}",
"set(key, value){\n //1. get hash\n const hash = this.hash(key) //creating a hash\n\n //2. make value entry\n const entry = {[key]: value};\n\n //3. set the entry to the hash value in the map\n //3.1 check to see if there is hash there, if not put a LL in\n if(!this.map[hash]){\n this.map[hash] = new LinkedList();\n }\n\n //add the entry\n this.map[hash].add(entry); //add makes add(entry) node the new head\n }",
"function storeMetaData(metaData, file) {\n\tvar json\n\t\t, stream;\n\n\ttry {\n\t\tjson = JSON.stringify(metaData);\n\t\tconsole.log(\"write start:\" + file + \" length:\" + json.length);\n\t\tstream = fs.createWriteStream(file);\n //console.log(file, json);\n\t\tstream.write(json, function(){\n\t\t\tconsole.log(\"write finished:\" + file + \" length:\" + json.length);\n\t\t});\n\t\tstream.end(function(){\n\t\t\tconsole.log(\"stream finished:\" + file + \" length:\" + json.length);\n\t\t});\n\t} catch(e) {\n\t\tconsole.error('Could not save meta data for ' + file);\n\t}\n}",
"function save (map, file) {\n // get the users as an array\n var users = Object.keys(map || {});\n // return if the map was empty or null\n if (users.length === 0) {\n return;\n }\n\n var lines = [];\n // for every user\n users.forEach(function (user) {\n var hash = map[user];\n // generate the : separated line\n var line = [user, hash].join(':');\n lines.push(line);\n });\n // and dump these lines to a file\n fs.writeFileSync(file, lines.join('\\n'), encodingOptions);\n}",
"function WriteData() {\n setCookie_e(COOKIE_NAMES.user, MyUser);\n setCookie_e(COOKIE_NAMES.password, MyPass);\n setCookie_e(COOKIE_NAMES.zoom, MyZoom);\n setCookie_e(COOKIE_NAMES.lat, wlat);\n setCookie_e(COOKIE_NAMES.lng, wlon);\n setCookie_e(COOKIE_NAMES.id, myloginid);\n setCookie_e(COOKIE_NAMES.tel, mytel);\n setCookie_e(COOKIE_NAMES.myid, myid);\n\n\t\n\tconsole.log(\"writing: \"+MyUser+ \" - \"+MyPass+ \" - \"+MyZoom+ \" - \"+wlat+ \" - \"+wlon+ \" - \"+myloginid+ \" - \"+mytel+ \" - \"+myid);\n // window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotfswrite, fail);\n}",
"function logAndWrite(entry){\n console.log(entry);\n writeHistoryEntry(entry);\n}",
"function hash(obj) {\n return JSON.stringify(obj)\n}",
"add(key, value) {\n let index = Hash.hash(key, this.sizeLimit);\n let inserted = false;\n\n if (this.hashTable[index] === undefined) {\n this.hashTable[index] = [[key, value]];\n inserted = true;\n } else {\n for (let i = 0; i < this.hashTable[index].length; i++) {\n if (this.hashTable[index][i][0] === key) {\n this.hashTable[index][i][1] = value;\n inserted = true;\n }\n }\n }\n\n if (inserted === false) {\n this.hashTable[index].push([key, value]);\n }\n }",
"function write(file, data) {\n writeFileSync(file, data);\n\n console.log(\n `✓ ${relative(__dirname + \"/../\", file)} (${bytes(statSync(file).size)})`\n );\n}",
"function writeToJSONfile(){\n const noteChanged = JSON.stringify(notesInfo, null, 2);\n fs.writeFile('./db/db.json', noteChanged, finished);\n function finished(err){\n console.log('JSON file updated!');\n }\n }",
"function hashValues(map) {\n\t\tvar vals = [];\n\t\tfor (var o in map) {\n\t\t\tvals.push(map[o]);\n\t\t}\n\t\tvar valString = vals.join('###');\n\t\tvar hash = CryptoJS.SHA256(valString).toString(CryptoJS.enc.Base64);\n\t\treturn hash;\n\t}",
"info(entry) {\n this.write(entry, 'INFO');\n }",
"function SaveHourInfo(hour, data){\n localStorage.setItem(hour, data);\n}",
"function setHashKey(obj, h) {\n\t\tif (h) {\n\t\t\tobj.$$hashKey = h;\n\t\t}\n\t\telse {\n\t\t\tdelete obj.$$hashKey;\n\t\t}\n\t}",
"saveData() {\n let jsonData = {\n lastTicket: this.lastTicket,\n today: this.today,\n tickets: this.tickets,\n lastFour: this.lastFour\n }\n\n let jsonDataString = JSON.stringify(jsonData);\n \n fs.writeFileSync('./server/data/data.json', jsonDataString);\n }",
"function hasher(data) {\n var pre_string = data.lastname + data.firstname + data.gender + data.dob + data.drug;\n var hash = '', curr_str;\n\n hash = Sha1.hash(pre_string);\n\n /**\n // Increment 5 characters at a time\n for (var i = 0, len = pre_string.length; i < len; i += 5) {\n curr_str = '';\n\n // Extract 5 characters at a time\n for (var j = 0; j < 5; j++) {\n if (pre_string[i + j]) {\n curr_str += pre_string[i + j]\n }\n }\n\n // Hash the characters and append to hash\n var temp = mini_hash(curr_str); // Get number from the string\n var fromCode = String.fromCharCode(mini_hash(curr_str));\n hash += fromCode;\n\n } */\n\n\n return hash;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
8. Write a program that calculates a number of appearances of a given number in a given array. Inputs: a = [2, 4, 7, 8, 7, 7, 1], e = 7 Result: 3 | function appear(a){
var number = 0;
var e = 7;
for (var i = 0; i < a.length; i++){
if (e === a[i]){
number++;
}
}
return number;
} | [
"function numOfAppear(a, array) {\n var i;\n var n = 0;\n for (i = 0; i < array.length; i++) {\n if (array[i] == a) {\n n++;\n }\n }\n return n;\n}",
"function countOf(array, element) {\n var x = 0;\n for (var i = 0; i < array.length; i++) {\n if (array[i] == element) {\n x++;\n }\n }\n return x;\n}",
"function countNum (array) {\n\tvar uniqueArr = [];\n\tfor (i=0; i<=uniqueNumbers.length - 1; i++){\n\t\tvar count = array.filter (function (n) {\n\t\t\treturn n === uniqueNumbers [i];\n\t\t})\n\t\tuniqueArr.push (count.length);\n\t}\n\treturn uniqueArr;\n}",
"function countNumber(arrayOfNumbers,number){\n let result = 0;\n for(let i = 0; i < arrayOfNumbers.length; i++){\n if(arrayOfNumbers[i]===number){\n result++;\n }\n }\n return result;\n}",
"function findTotalNumberOfDupes(arr) {\n var totalDupes = 0;\n let counts = {};\n\tarr.forEach(elem => {\n counts[elem] = (counts[elem] || 0) + 1;\n\t});\n for(let elem in counts){\n \tif (counts[elem] > 1) totalDupes=totalDupes+(counts[elem]-1);\n }\n return totalDupes;\n}",
"function calculatesNumberOFIntegers (array) {\n\nlet result = 0;\n for (let i = 0; i < array.length; i++) {\n\n if(isFinite(array[i]) && typeof array[i] === \"number\" && parseInt(array[i]) === array[i]) {\n\n result++;\n }\n }\n return result;\n}",
"function frequency(arr) {\n var retArr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (let elem of arr) {\n switch (elem) {\n case 0:\n retArr[0]++;\n break;\n case 1:\n retArr[1]++;\n break;\n case 2:\n retArr[2]++;\n break;\n case 3:\n retArr[3]++;\n break;\n case 4:\n retArr[4]++;\n break;\n case 5:\n retArr[5]++;\n break;\n case 6:\n retArr[6]++;\n break;\n case 7:\n retArr[7]++;\n break;\n case 8:\n retArr[8]++;\n break;\n case 9:\n retArr[9]++;\n break;\n case 10:\n retArr[10]++;\n break;\n }\n }\n return retArr;\n}",
"function how_many_even(arr){\n count = 0;\n for(i = 0; i < arr.length; i++){\n if (arr[i] % 2 == 0){\n count ++;\n }\n }\n return count;\n}",
"function mostFrequentItem(array) {\n\n let last = 0;\n let lastIndex = -1;\n for (let i = 0; i < array.length; i++) {\n let current = 0;\n for (let k = 0; k < array.length; k++) {\n if (array[k] == array[i]) {\n current++;\n }\n }\n if (current > last) {\n last = current;\n lastIndex = i;\n }\n }\n console.log(`Most frequent item: ${array[lastIndex]} -> ${last} times.`);\n}",
"function featured(number) {\n if (number > 9876543200) return false;\n let count = number + 1;\n\n\n while(true) {\n if (isOdd(count) && isMultipleOfSeven(count) && isUnique(count)) {\n return count;\n }\n count += 1;\n }\n}",
"function how_many_even(arr){\n var count = 0;\n for(var i = 0; i < arr.length; i++){\n if(arr[i] % 2 == 0){\n count++;\n }\n }\n return count;\n}",
"function countOdds(array) {\n var total = 0;\n for(var i = 0; i < array.length; i++) {\n if(array[i] % 2 != 0) {\n total++;\n }\n }\n return total;\n }",
"function countUniqueValues(array){\n let j = 1;\n let i = 0;\n while(j < array.length){\n if(array[i] === array[j]){\n j++;\n }\n else{\n i++\n array[i] = array[j] \n }\n }\n let numberOfUnique = i + 1\n return numberOfUnique\n}",
"function neighbouringElements(a) {\n var count = 0;\n for(var i = 0; i < a.length; i++){\n for(var j = 0; j < a[0].length; j++){\n if(a[i][j] == a[i][j+1]) {\n count++;\n }\n if(a[i+1]){\n if(a[i+1][j] == a[i][j]){\n count++;\n }\n }\n }\n }\n return count;\n}",
"static frequencies(arr) {\n let result = {};\n arr.forEach(e => {\n if (e in result) {\n result[e] += 1;\n } else {\n result[e] = 1;\n }\n });\n return result;\n }",
"function anagramCounter(arrayOfWords) {\n let sortedWords = arrayOfWords.map(word => word.split('').sort().join(''));\n let numberOfAnagrams = 0;\n\n sortedWords.forEach((word, theIndex) => {\n for (let i = theIndex + 1; i < sortedWords.length; i++) {\n if (word === sortedWords[i]) {\n numberOfAnagrams++\n }\n }\n })\n return numberOfAnagrams\n}",
"function countPositives(arr) {\n var count = 0;\n for (var x=0; x<arr.length; x++) {\n if (arr[x] > 0) {\n count++\n }\n }\n arr[arr.length - 1] = count\n return arr\n}",
"function countBoomerangs(arr) {\n\tlet start = 0\n\tlet end = 2\n\tlet count=0\n\t\n\twhile(end <= arr.length-1){\n\t\t\n\t\tif(arr[start]===arr[end] && arr[start+1]!== arr[start]){\n\t\t\tcount++\n\t\t}\n\t\tstart++\n\t\tend++\n\t}\n\t\n\treturn count\n}",
"static compute_page_counts(N, p) {\n let a = Math.ceil(N/p);\n let b = Math.ceil(N/a);\n let c = b - 1;\n let d = N - a * c;\n let e = a - d;\n\n return [a, b, c, d, e];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if move triggers win condition, so all of wLand is occupied by bg or all of bLand is occupied by wg | checkWin() {
if all bgWLand|| or wgBLand
} | [
"checkIfWin(){\n\t\tconst g = this.state.grid;\n\t\tvar hits = 0;\n\n\t\tfor(var i = 0; i < this.gridSize; i++) {\n\t\t\tfor(var j = 0; j < this.gridSize; j++) {\n\t\t\t\tif (g[i][j] === \"Hit\") {\n\t\t\t\t\thits++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(hits === this.maxNumberOfShips*2){\n\t\t\tvar theWinner = \"\";\n\n\t\t\tif(this.props.id === \"gridA\"){\n\t\t\t\ttheWinner = \"PlayerB\";\n\t\t\t\tthis.props.handleWin(theWinner);\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttheWinner = \"PlayerA\";\n\t\t\t\tthis.props.handleWin(theWinner);\n\t\t\t}\n\n\t\t}\n\n\t}",
"function checkBoundries() {\n if (x > 560) { // if ship is more than the right of the screen\n rightMove = false; // stop it moving\n } else if (x < 40) { // if ship is more than the left of the screen\n moveLeft = false; // stop it moving\n }\n if (y > 560) { // if ship is more than the bottom of the screen\n downmove = false; // stop it moving\n } else if (y < 30) { // if ship is more than the top of the screen\n upmove = false; // stop it moving\n }\n}",
"function checkWinStates() {\n const xtop = /XXX....../; // x top row\n const xmid = /...XXX.../; // x middle row\n const xbot = /......XXX/; // x bottom row\n const xldg = /X...X...X/; // x left to right diagonal\n const xrdg = /..X.X.X../; // x right to left diagonal\n const xlco = /X..X..X../; // x left column\n const xmco = /.X..X..X./; // x middle column\n const xrco = /..X..X..X/; // x right column\n\n const otop = /OOO....../; // o top row\n const omid = /...OOO.../; // o middle row\n const obot = /......OOO/; // o bottom row\n const oldg = /O...O...O/; // o left to right diagonal\n const ordg = /..O.O.O../; // o right to left diagonal\n const olco = /O..O..O../; // o left column\n const omco = /.O..O..O./; // o middle column\n const orco = /..O..O..O/; // o right column\n\n const empt = /E/; // there is an empty square\n\n state = '';\n for(let i=0;i<9;i++) state += boardData[currentBoard].getSquare(i).state;\n\n switch(true) {\n case xtop.test(state):\n case xmid.test(state):\n case xbot.test(state):\n case xldg.test(state):\n case xrdg.test(state):\n case xlco.test(state):\n case xmco.test(state):\n case xrco.test(state):\n boardData[currentBoard].state = X;\n globalBoardVictorySprites[currentBoard].visible = true;\n globalBoardVictorySprites[currentBoard].setTexture(resources[\"res/VictoryX.svg\"].texture);\n break;\n case otop.test(state):\n case omid.test(state):\n case obot.test(state):\n case oldg.test(state):\n case ordg.test(state):\n case olco.test(state):\n case omco.test(state):\n case orco.test(state):\n boardData[currentBoard].state = O;\n globalBoardVictorySprites[currentBoard].visible = true;\n globalBoardVictorySprites[currentBoard].setTexture(resources[\"res/VictoryO.svg\"].texture);\n break;\n case empt.test(state):\n // NO WIN CONDITION, BOARD STILL PLAYABLE\n break;\n default:\n boardData[currentBoard].state = C;\n globalBoardVictorySprites[currentBoard].visible = true;\n globalBoardVictorySprites[currentBoard].setTexture(resources[\"res/cats.svg\"].texture);\n }\n\n \n state = '';\n for(let i=0;i<9;i++) state += boardData[i].state;\n let xOffset = globalBoardVictorySprites[0].width / 2;\n let yOffset = globalBoardVictorySprites[0].height / 2;\n let x1, x2, y1, y2;\n\n switch(true) {\n case xtop.test(state):\n x1 = globalBoardVictorySprites[0].x + xOffset;\n y1 = globalBoardVictorySprites[0].y + yOffset;\n x2 = globalBoardVictorySprites[2].x + xOffset;\n y2 = globalBoardVictorySprites[2].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xmid.test(state):\n x1 = globalBoardVictorySprites[3].x + xOffset;\n y1 = globalBoardVictorySprites[3].y + yOffset;\n x2 = globalBoardVictorySprites[5].x + xOffset;\n y2 = globalBoardVictorySprites[5].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xbot.test(state):\n x1 = globalBoardVictorySprites[6].x + xOffset;\n y1 = globalBoardVictorySprites[6].y + yOffset;\n x2 = globalBoardVictorySprites[8].x + xOffset;\n y2 = globalBoardVictorySprites[8].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xldg.test(state):\n x1 = globalBoardVictorySprites[0].x + xOffset;\n y1 = globalBoardVictorySprites[0].y + yOffset;\n x2 = globalBoardVictorySprites[8].x + xOffset;\n y2 = globalBoardVictorySprites[8].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xrdg.test(state):\n x1 = globalBoardVictorySprites[2].x + xOffset;\n y1 = globalBoardVictorySprites[2].y + yOffset;\n x2 = globalBoardVictorySprites[6].x + xOffset;\n y2 = globalBoardVictorySprites[6].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xlco.test(state):\n x1 = globalBoardVictorySprites[0].x + xOffset;\n y1 = globalBoardVictorySprites[0].y + yOffset;\n x2 = globalBoardVictorySprites[6].x + xOffset;\n y2 = globalBoardVictorySprites[6].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xmco.test(state):\n x1 = globalBoardVictorySprites[1].x + xOffset;\n y1 = globalBoardVictorySprites[1].y + yOffset;\n x2 = globalBoardVictorySprites[7].x + xOffset;\n y2 = globalBoardVictorySprites[7].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case xrco.test(state):\n x1 = globalBoardVictorySprites[2].x + xOffset;\n y1 = globalBoardVictorySprites[2].y + yOffset;\n x2 = globalBoardVictorySprites[8].x + xOffset;\n y2 = globalBoardVictorySprites[8].y + yOffset;\n drawLine(x1, y1, x2, y2, 0x007BFE);\n victory = true;\n break;\n case otop.test(state):\n x1 = globalBoardVictorySprites[0].x + xOffset;\n y1 = globalBoardVictorySprites[0].y + yOffset;\n x2 = globalBoardVictorySprites[2].x + xOffset;\n y2 = globalBoardVictorySprites[2].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case omid.test(state):\n x1 = globalBoardVictorySprites[3].x + xOffset;\n y1 = globalBoardVictorySprites[3].y + yOffset;\n x2 = globalBoardVictorySprites[5].x + xOffset;\n y2 = globalBoardVictorySprites[5].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case obot.test(state):\n x1 = globalBoardVictorySprites[6].x + xOffset;\n y1 = globalBoardVictorySprites[6].y + yOffset;\n x2 = globalBoardVictorySprites[8].x + xOffset;\n y2 = globalBoardVictorySprites[8].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case oldg.test(state):\n x1 = globalBoardVictorySprites[0].x + xOffset;\n y1 = globalBoardVictorySprites[0].y + yOffset;\n x2 = globalBoardVictorySprites[8].x + xOffset;\n y2 = globalBoardVictorySprites[8].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case ordg.test(state):\n x1 = globalBoardVictorySprites[2].x + xOffset;\n y1 = globalBoardVictorySprites[2].y + yOffset;\n x2 = globalBoardVictorySprites[6].x + xOffset;\n y2 = globalBoardVictorySprites[6].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case olco.test(state):\n x1 = globalBoardVictorySprites[0].x + xOffset;\n y1 = globalBoardVictorySprites[0].y + yOffset;\n x2 = globalBoardVictorySprites[6].x + xOffset;\n y2 = globalBoardVictorySprites[6].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case omco.test(state):\n x1 = globalBoardVictorySprites[1].x + xOffset;\n y1 = globalBoardVictorySprites[1].y + yOffset;\n x2 = globalBoardVictorySprites[7].x + xOffset;\n y2 = globalBoardVictorySprites[7].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case orco.test(state):\n x1 = globalBoardVictorySprites[2].x + xOffset;\n y1 = globalBoardVictorySprites[2].y + yOffset;\n x2 = globalBoardVictorySprites[8].x + xOffset;\n y2 = globalBoardVictorySprites[8].y + yOffset;\n drawLine(x1, y1, x2, y2, 0xFF2D55);\n victory = true;\n break;\n case empt.test(state):\n // NO WIN CONDITION, PLAY CONTINUES\n break;\n default:\n let x = 0;\n let o = 0;\n for(let i=0;i<9;i++) {\n if(boardData[i].state == X) x++;\n if(boardData[i].state == O) o++;\n }\n\n if(o > x) {\n // O VICTORY\n } else if(x > o) {\n // X VICTORY\n } else {\n // CATS GAME\n }\n victory = true;\n }\n}",
"function checkWin() {\n\n var winPattern = [board[0] + board[1] + board[2], board[3] + board[4] + board[5], board[6] + board[7] + board[8], // Horizontal 0,1,2\n board[0] + board[3] + board[6], board[1] + board[4] + board[7], board[2] + board[5] + board[8], // Vertical 3,4,5,\n board[0] + board[4] + board[8], board[2] + board[4] + board[6]\n ]; // Diagonal 6,7\n\n var USER_String = USER + USER + USER; // USER_String == \"111\"\n var AI_String = AI + AI + AI; // AI_String == \"222\"\n\n for (var i = 0; i < 8; i++) {\n if (winPattern[i] == USER_String) {\n $(\"#status\").text(\"YOU WON\")\n activateWinAnimation(i);\n return USER; // User wins\t\t\t\t\n } else if (winPattern[i] == AI_String) {\n $(\"#status\").text(\"AI WON\")\n activateWinAnimation(i);\n return AI; // AI wins\t\t\t\n }\n }\n\n if (board.indexOf(\"-\") == -1) {\n $(\"#status\").text(\"IT'S A DRAW\")\n return DRAW; // Draw!\t\t\t\t\n }\n\n return 0;\n}",
"function testWinCondition(row, col) {\n let t = boardState[row][col]; //last played token\n let bs = boardState;\n\n //DOWN\n if (row<=2 && t==bs[row+1][col] && t==bs[row+2][col] && t==bs[row+3][col])\n return (true);\n \n //DIAGONAL FORWARD - POSITION 1\n else if (row>=3 && col<=3 && t==bs[row-1][col+1] && t==bs[row-2][col+2] && t==bs[row-3][col+3])\n return (true);\n //DIAGONAL FORWARD - POSITION 2\n else if (row>=2 && row<=4 && col>=1 && col<=4 && t==bs[row+1][col-1] && t==bs[row-1][col+1] && t==bs[row-2][col+2])\n return (true);\n //DIAGONAL FORWARD - POSITION 3\n else if (row>=1 && row<=3 && col>=2 && col<=5 && t==bs[row+2][col-2] && t==bs[row+1][col-1] && t==bs[row-1][col+1])\n return (true);\n //DIAGONAL FORWARD - POSITION 4\n else if (row<=2 && col>=3 && t==bs[row+3][col-3] && t==bs[row+2][col-2] && t==bs[row+1][col-1])\n return (true);\n\n //DIAGONAL BACKWARD - POSITION 1\n else if (row<=2 && col<=3 && t==bs[row+1][col+1] && t==bs[row+2][col+2] && t==bs[row+3][col+3])\n return (true);\n //DIAGONAL BACKWARD - POSITION 2\n else if (row>=1 && row<=3 && col>=1 && col<=4 && t==bs[row-1][col-1] && t==bs[row+1][col+1] && t==bs[row+2][col+2])\n return (true);\n //DIAGONAL BACKWARD - POSITION 3\n else if (row>=2 && row<=4 && col>=2 && col<=5 && t==bs[row-2][col-2] && t==bs[row-1][col-1] && t==bs[row+1][col+1])\n return (true);\n //DIAGONAL BACKWARD - POSITION 4\n else if (row>=3 && col>=3 && t==bs[row-3][col-3] && t==bs[row-2][col-2] && t==bs[row-1][col-1])\n return (true);\n \n //HORIZONTAL - POSITION 1\n else if (col<=3 && t==bs[row][col+1] && t==bs[row][col+2] && t==bs[row][col+3])\n return (true);\n //HORIZONTAL - POSITION 2\n else if (col>=1 && col<=4 && t==bs[row][col-1] && t==bs[row][col+1] && t==bs[row][col+2])\n return (true);\n //HORIZONTAL - POSITION 3\n else if (col>=2 && col<=5 && t==bs[row][col-2] && t==bs[row][col-1] && t==bs[row][col+1])\n return (true);\n //HORIZONTAL - POSITION 4\n else if (col>=3 && t==bs[row][col-3] && t==bs[row][col-2] && t==bs[row][col-1])\n return (true);\n else \n return (false);\n}",
"verifyMove(playerColor, selectedPiece, stoneColor, gnomeColor, startSpace, endSpace) {\n\n //checks if player can move selectedPiece from startSpace to endSpace validly\n //if valid, returns true\n //check if playerColor is same as the selectedPieceColor\n //find out what kind of piece selectedPiece is;\n //if selectedPiece is stone can only move to empty place, no gnomes can be occupying that startSpace with it\n //if selectedPiece is gnome, it can move to any empty adjacent stone or land\n //check if selectedEnd is bLand, wLand, wEmptyLand, bEmptyLand\n\n\n if (playerColor === selectedPieceColor) {\n return\n }\n\n\n && (turnCount >= 6) && (endSpace.empty === true) {\n endSpace = selectedPiece)\n }\n }",
"is_facing_wall_or_portal() {\n switch(this.direction){ \n case KeyboardCodeKeys.left:\n return this.maze.has_left_wall(this.row, this.col)\n || (this.col == 0);\n case KeyboardCodeKeys.right:\n return this.maze.has_right_wall(this.row, this.col)\n || (this.col == this.maze.col_count-1);\n case KeyboardCodeKeys.up:\n return this.maze.has_top_wall(this.row, this.col)\n || (this.row == 0);\n case KeyboardCodeKeys.down:\n return this.maze.has_bot_wall(this.row, this.col)\n || (this.row == this.maze.row_count-1);\n }\n }",
"function HittingTheWall(){\r\n for(let i = 0; i < curTetromino.length; i++){\r\n let newX = curTetromino[i][0] + startX;\r\n if(newX <= 0 && direction === DIRECTION.LEFT){\r\n return true;\r\n } else if(newX >= 11 && direction === DIRECTION.RIGHT){\r\n return true;\r\n } \r\n }\r\n return false;\r\n}",
"validDirections() {\r\n let row;\r\n let col;\r\n\r\n if (game.color == 'b') {\r\n row = game.blackPositions[game.piece - 1][0];\r\n col = game.blackPositions[game.piece - 1][1];\r\n }\r\n\r\n if (game.color == 'w') {\r\n row = game.whitePositions[game.piece - 1][0];\r\n col = game.whitePositions[game.piece - 1][1];\r\n }\r\n\r\n this.getPrologRequest(\"valid_moves(\" + game.board + \",\" + row + \",\" + col + \")\", this.validMovesReply);\r\n }",
"function hasWon(){\n\n //check all the lites to check if they're green. if so add one to the greentilecounter\n $tileArray.each(function (i, value) {\n if($($tileArray[i]).attr('class') === \"green\"){\n greenTileCount ++;\n }\n });\n\n tilesToGo = greenTileCount;\n\n //log valueof greentielcounter at start\n console.log(greenTileCount + \" at start of function\")\n\n // if number of green tiles = the array length then youve won.\n if(greenTileCount == $tileArray.length) {\n $('#welcome').delay(400).fadeIn();\n player1score = turnCounter;\n resetBoard();\n\n addToScoreBoard();\n\n $gridSizeSelector.hide();\n // $welcomeMsg.hide();\n $gridSizeSelector.show(); \n\n $tileArray.each(function(i, value){\n $(this).css({\"background-color\":\"rgba(41,242,44,0.8)\"});\n $(this).delay(1000).fadeOut();\n })\n $p1score.html(\"you've won, big ups! choose next level to play\");\n return true;\n }\n greenTileCount = 0;\n }",
"function isBattleThisMove()\n\t{\n\t\tif(enemyFrequency!=0)\n\t\t{\n\t\t\trandomNumber = Math.floor((Math.random()*enemyFrequency)+1);\n\t\t\tif(randomNumber == enemyFrequency)\n\t\t\t{\n\t\t\t\trandomEnemy = Math.floor((Math.random()*enemyArrayLength));\n\t\t\t\tcurrentEnemy = enemyArray[randomEnemy];\n\t\t\t\n\t\t\t\t\n\t\t\t\tinitiateBattle(randomEnemy);\n\t\t\t}\n\t\t}\n\t}",
"valid(x, y, soft, superSoft) {\n if (x > this.bounds.left + roadSize && x < this.bounds.right - roadSize && y > this.bounds.top + roadSize && y < this.bounds.bottom - roadSize) {\n return false;\n }\n if (superSoft) {\n if (x < -vehicleHeight / 2 - roadSize || x > canvas.width + vehicleHeight / 2 + roadSize || y < offset - vehicleHeight / 2 - roadSize || y > canvas.height + vehicleHeight / 2 + roadSize) {\n return false;\n }\n }\n else if (soft) {\n if (x < this.bounds.left && (y < this.bounds.top || y > this.bounds.bottom) || x > this.bounds.right && (y < this.bounds.top || y > this.bounds.bottom)) {\n return false;\n }\n else if (x > this.bounds.left + roadSize && x < this.bounds.right - roadSize && (y < this.bounds.top || y > this.bounds.bottom) || y > this.bounds.top + roadSize && y < this.bounds.bottom - roadSize && (x < this.bounds.left || x > this.bounds.right)) {\n return false;\n }\n else if ((!env.junctions[0] && y < canvas.height / 2 && (x < this.bounds.left || x > this.bounds.right)) || !env.junctions[1] && y > canvas.height / 2 && (x < this.bounds.left || x > this.bounds.right) || !env.junctions[2] && x < canvas.width / 2 && (y < this.bounds.top || y > this.bounds.bottom) || !env.junctions[3] && x > canvas.width / 2 && (y < this.bounds.top || y > this.bounds.bottom)) {\n return false;\n }\n }\n else {\n if (x < this.bounds.left || x > this.bounds.right || y < this.bounds.top || y > this.bounds.bottom) {\n return false;\n }\n }\n return true;\n }",
"function checkWin(currentClass) {\n return winningCombos.some((combination) => {\n return combination.every((index) => {\n return allCells[index].classList.contains(currentClass);\n });\n });\n}",
"function checkBorderCollision() {\r\n //Player\r\n if (player_x >= (canvas_w - player_w)) rightKey = false;\r\n if (player_x <= (0)) leftKey = false;\r\n if (player_y <= (0)) upKey = false;\r\n if (player_y >= (canvas_h - player_h)) downKey = false;\r\n\r\n //AI\r\n if (AI_x >= (canvas_w - AI_w)) rightAI = false;\r\n if (AI_x <= (0)) leftAI = false;\r\n if (AI_y <= (0)) upAI = false;\r\n if (AI_y >= (canvas_h - AI_h)) downAI = false;\r\n}",
"function checkForWinner() {\n // If it hits the left wall, player 2 wins\n if (puck.x < 0) {\n // player2Win = true;\n player1Start = true; // Set our flag to allow player 1 to start\n won = true;\n player2.score += 1;\n updateScoreboard();\n // document.getElementById(\"p2score\").innerHTML = player2.score;\n }\n // If it hits the right wall, player 1 wins\n if (puck.x > canvas.width) {\n // player1Win = true;\n player1Start = false; // Set our flag to allow player 2 to start\n won = true;\n player1.score += 1;\n updateScoreboard();\n // document.getElementById(\"p1score\").innerHTML = player1.score;\n }\n}",
"hasWallInDirection (x, y, direction) {\n return !(this.getBlockValue(x, y) & direction);\n }",
"function checkNeighbour() {\n sendToPid(CheckState.neighbour, ROOM, CHECK);\n Utility.log('Checking neighbour: ', CheckState.neighbour);\n }",
"function wallCollision(playerNextPos, walls)\n{\n\tfor(var i = 0; i < walls.length; i++)\n\t{\n\t\tif(playerNextPos[0] == walls[i][0] && playerNextPos[1] == walls[i][1])\n\t\t{\n\t\t\tconsole.log(\"hehe cx\");\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}",
"compare() {\n let result1 = this.state.gameplayOne;\n let result2 = this.state.gameplayTwo;\n let win = [...this.state.win];\n\n // Setting arrays which will be filled by true or false since a winning combination is detected in the player's game.\n let tabTrueFalse1 = [];\n let tabTrueFalse2 = [];\n // winningLine may help to know which winning combination is on the set and then have an action on it. To think.\n let winningLine = [];\n\n if (this.state.gameplayOne.length >= 3) {\n tabTrueFalse1 = win.map(elt =>\n elt.every(element => result1.includes(element))\n );\n }\n if (this.state.gameplayTwo.length >= 3) {\n tabTrueFalse2 = win.map(elt =>\n elt.every(element => result2.includes(element))\n );\n }\n\n //Launching youWon()\n tabTrueFalse1.includes(true) ? this.youWon(1) : null;\n tabTrueFalse2.includes(true) ? this.youWon(2) : null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`lasso' creates a new lasso instance, based on the `overlay' svg dom element. In addition to collecting the points selected by the user it also performs a user specified action on the start and end of lassoing. The lasso only collects the selected region, and passes it to the user. The search for any data in the graphic must be done by the plot. Lasso does provide functionality (lasso.iswithin) to check whether a particular pixel on the svg is within it. | function lasso(overlay, parentobj) {
_classCallCheck(this, lasso); // Declare the most important attributes. Note that the lasso does NOT find it's own selected data! The `selected' attribute is only a placeholder here to allow the user to store the results in it. This is to simplify the lasso code by moving the data identification out.
this.svg = overlay;
this.boundary = []; // Add behavior to the overlay.
d3.select(overlay.parentElement).on("mousemove", function () {
if (event.shiftKey) {
overlay.style.display = "block";
} else {
overlay.style.display = "none";
} // if
}); // on
var obj = this;
d3.select(overlay).call(d3.drag().on("start", function () {
// Clear previous lasso, remove graphic, remove toolbar.
obj.boundary = [];
obj.draw();
parentobj.onlassostart(obj);
}) // on
.on("drag", function () {
obj.addpoint();
obj.draw();
}) // on
.on("end", function () {
if (obj.boundary.length > 3) {
parentobj.onlassoend(obj);
} // if
obj.remove();
}) // on
); // call
} // constructor | [
"function addPlot(overlay, val, type){\n var gate = false;\n if(type == \"id\"){\n for(var i = 0; i < data.length;i++){\n var name = type + String(val);\n if(data[i].id == val){\n gate = true;\n overlay[name] = L.polygon(data[i].geometry.coordinates);\n overlay[name].bindPopup(\n \"<p class='popup'><b>Address:</b> <span>\"\n + data[i].properties.PAR_ADDR + \" \" + data[i].properties.PAR_STREET + \" \"\n + data[i].properties.PAR_SUFFIX + \"</span><br>\" +\n \"<b>City: </b><span>\" + data[i].properties.PAR_CITY + \"</span><br>\" +\n \"<b>Zip: </b><span>\" + data[i].properties.PAR_ZIP + \"</span><br>\" +\n \"<b>Parcel ID: </b><span>\" + data[i].properties.PARCEL_ID + \"</span><br>\" +\n \"<b>Type: </b><span>\" + data[i].properties.PARCEL_TYP + \"</span><br>\" +\n \"<b>Features: </b><span>\" + data[i].properties.TAX_LUC_DE + \"</span><br></p>\"\n );\n //Popup on click effects\n overlay[name].on(\"popupopen\",function(){\n overlay[name].setStyle({\n fillColor: OPENCOLOR,\n color: OPENCOLOR,\n fillOpacity: 0.8\n });\n });\n\n overlay[name].on(\"popupclose\",function(){\n overlay[name].setStyle({\n fillColor: DEFAULTCOLOR,\n color: DEFAULTCOLOR,\n fillOpacity: 0.5\n });\n });\n\n //Hover effect\n overlay[name].on(\"mouseover\",function(){\n if(!(this.getPopup().isOpen())){\n overlay[name].setStyle({\n fillColor: HOVERCOLOR,\n color: HOVERCOLOR,\n fillOpacity: 0.5\n });\n }\n });\n overlay[name].on(\"mouseout\",function(){\n if(!(this.getPopup().isOpen())){\n overlay[name].setStyle({\n fillColor: DEFAULTCOLOR,\n color: DEFAULTCOLOR,\n fillOpacity: 0.5\n });\n }\n });\n break;\n }\n }\n }else if(type ==\"json\"){\n i = val;\n name = type + String(i);\n gate = true;\n overlay[name] = L.polygon(data[i].geometry.coordinates);\n overlay[name].bindPopup(\n \"<p class='popup'><b>Address:</b> <span>\"\n + data[i].properties.PAR_ADDR + \" \" + data[i].properties.PAR_STREET + \" \"\n + data[i].properties.PAR_SUFFIX + \"</span><br>\" +\n \"<b>City: </b><span>\" + data[i].properties.PAR_CITY + \"</span><br>\" +\n \"<b>Zip: </b><span>\" + data[i].properties.PAR_ZIP + \"</span><br>\" +\n \"<b>Parcel ID: </b><span>\" + data[i].properties.PARCEL_ID + \"</span><br>\" +\n \"<b>Type: </b><span>\" + data[i].properties.PARCEL_TYP + \"</span><br>\" +\n \"<b>Features: </b><span>\" + data[i].properties.TAX_LUC_DE + \"</span><br></p>\"\n );\n //Popup on click effects\n overlay[name].on(\"popupopen\",function(){\n overlay[name].setStyle({\n fillColor: OPENCOLOR,\n color: OPENCOLOR,\n fillOpacity: 0.8\n });\n });\n\n overlay[name].on(\"popupclose\",function(){\n overlay[name].setStyle({\n fillColor: DEFAULTCOLOR,\n color: DEFAULTCOLOR,\n fillOpacity: 0.5\n });\n });\n\n //Hover effect\n overlay[name].on(\"mouseover\",function(){\n if(!(this.getPopup().isOpen())){\n overlay[name].setStyle({\n fillColor: HOVERCOLOR,\n color: HOVERCOLOR,\n fillOpacity: 0.5\n });\n }\n });\n overlay[name].on(\"mouseout\",function(){\n if(!(this.getPopup().isOpen())){\n overlay[name].setStyle({\n fillColor: DEFAULTCOLOR,\n color: DEFAULTCOLOR,\n fillOpacity: 0.5\n });\n }\n });\n }else if(type ==\"$oid\"){\n for(i = 0; i < data.length;i++){\n name = String(val);\n if(data[i]._id.$oid == val){\n gate = true;\n overlay[name] = L.polygon(data[i].geometry.coordinates);\n overlay[name].bindPopup(\n \"<p class='popup'><b>Address:</b> <span>\"\n + data[i].properties.PAR_ADDR + \" \" + data[i].properties.PAR_STREET + \" \"\n + data[i].properties.PAR_SUFFIX + \"</span><br>\" +\n \"<b>City: </b><span>\" + data[i].properties.PAR_CITY + \"</span><br>\" +\n \"<b>Zip: </b><span>\" + data[i].properties.PAR_ZIP + \"</span><br>\" +\n \"<b>Parcel ID: </b><span>\" + data[i].properties.PARCEL_ID + \"</span><br>\" +\n \"<b>Type: </b><span>\" + data[i].properties.PARCEL_TYP + \"</span><br>\" +\n \"<b>Features: </b><span>\" + data[i].properties.TAX_LUC_DE + \"</span><br></p>\"\n );\n //Popup on click effects\n overlay[name].on(\"popupopen\",function(){\n overlay[name].setStyle({\n fillColor: OPENCOLOR,\n color: OPENCOLOR,\n fillOpacity: 0.8\n });\n });\n\n overlay[name].on(\"popupclose\",function(){\n overlay[name].setStyle({\n fillColor: DEFAULTCOLOR,\n color: DEFAULTCOLOR,\n fillOpacity: 0.5\n });\n });\n\n //Hover effect\n overlay[name].on(\"mouseover\",function(){\n if(!(this.getPopup().isOpen())){\n overlay[name].setStyle({\n fillColor: HOVERCOLOR,\n color: HOVERCOLOR,\n fillOpacity: 0.5\n });\n }\n });\n overlay[name].on(\"mouseout\",function(){\n if(!(this.getPopup().isOpen())){\n overlay[name].setStyle({\n fillColor: DEFAULTCOLOR,\n color: DEFAULTCOLOR,\n fillOpacity: 0.5\n });\n }\n });\n break;\n }\n }\n }else{\n console.log(val + \" of \" + type + \" not found.\");\n }\n}//ENDADDPLOT",
"drawOverlay(updateStepDuration) {\n if (this.colorchartShown) {\n this.drawOutline()\n }\n\n // Apply new data and obtain selections\n let [enterSel, updateSel, mergeSel, exitSel] = this.D3.mkSelections(\n this.g.selectAll(\"circle\"), this.flatEvents, \"circle\")\n\n // Update visuals\n exitSel.remove()\n this.D3.invisibleCirclesCorrectLocation(enterSel, this.projection);\n\n enterSel.on('mouseover', (d) => eventOnMouseOver(d, this.tooltip))\n .on('mouseout', (d) => eventOnMouseOut(d, this.tooltip))\n .on('click', (d) => eventOnMouseClick(d, this));\n\n this.D3.pulseEntrance(enterSel, (d) => this.SELECTION.checkSelected(d), (d) => this.SELECTION.colorMapping(d),\n updateStepDuration);\n }",
"_onVaadinOverlayOpen() {\n this.__alignOverlayPosition();\n this.$.overlay.style.opacity = '';\n this.__forwardFocus();\n }",
"constructor(options, areaType, map) {\n //If certain options were not set then provide a default value for them\n options.style = options.style || ol.style.areaStyleFunction(areaType);\n options.updateWhileAnimating = options.updateWhileAnimating || false;\n options.updateWhileInteracting = options.updateWhileInteracting || false;\n options.renderMode = options.renderMode || 'image'; //'vector' is default\n options.declutter = true;\n //Get zoom range from area type\n let minZoom = areaType.zoom_min;\n let maxZoom = areaType.zoom_max;\n //Set default options (if necessary) and call vector layer constructor\n super(options, map, minZoom, maxZoom);\n this.areaType = areaType;\n //Check if labels are desired for this area type\n if (this.areaType.labels) {\n this._hasLabels = true;\n //Create label layer and add it to the map\n this.labelLayer = new ol.layer.AreaLabel({\n source: new ol.source.Vector(),\n zIndex: this.areaType.z_index + LABEL_LAYER_Z_INDEX\n }, areaType.labels, map);\n //Add label layer to map\n map.addLayer(this.labelLayer);\n }\n else {\n this._hasLabels = false;\n }\n //No highlighting yet\n this.highlightLocation = null;\n //Save reference to current scope\n let _this = this;\n //Check if area source is used\n if (!(this.getSource() instanceof ol.source.Area)) {\n return;\n }\n //Cast to area source\n let source = this.getSource();\n //Register a feature listener\n source.addFeatureListener(function (feature) {\n _this.checkFeatureForHighlight(feature);\n _this.createLabelForFeature(feature);\n });\n }",
"function highlightInsulaFromMarker(e){\n\t\tvar insulaMarker = e.target;\n\t\tvar insulaToHighlight = getInsulaFromMarker(insulaMarker);\n\t\tpompeiiInsulaLayer.eachLayer(function(layer){\n\t\t\tif(layer.feature!=undefined && interactive){\n\t\t\t\tif (layer.feature.properties.insula_id == insulaToHighlight){\n\t\t\t\t\thighlightInsula(layer);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}",
"function ProjectionOverlay() {\n }",
"function addOverlay() {\n //the graph rectangle area\n chartRect = mainChart.append('rect')\n .attr('class', 'chartOverlay')\n .attr('width', width)\n .attr('height', height)\n .on('mouseover', function () {\n mouseOverChart();\n })\n .on('mouseout', function () {\n focus.style('display', 'none');\n if (scope.menuOption.isTooltipOn) tip.style('display', 'none');\n })\n .on('mousemove', mouseMove)\n .call(zoom)\n ;\n\n //the brush overlay\n brushG = context.append(\"g\")\n .attr(\"class\", \"brush\")\n .call(brush)\n .call(brush.move, x.range()); //change the x axis range when brush area changes\n\n brushMainG = mainChart.append(\"g\")//have to do this seperately, because rect svg cannot register brush\n .attr(\"class\", \"brushMain\")\n .call(zoom)\n .on(\"mousedown.zoom\", null)\n .call(brushMain)\n .on('mouseover', function () {\n mouseOverChart();\n })\n .on('mouseout', function () {\n focus.style('display', 'none');\n if (scope.menuOption.isTooltipOn) tip.style('display', 'none');\n })\n .on('mousemove', mouseMove);\n\n if (scope.menuOption.isBrushMainOn) {\n brushMainG.attr('display', null);\n } else {\n brushMainG.attr('display', 'none');\n }\n // no wheel zoom on page load\n if (!scope.menuOption.isWheelOn) {\n chartRect.on(\"wheel.zoom\", null); // does not disable 'double-click' to zoom\n brushMainG.on(\"wheel.zoom\", null);\n }\n }",
"function addOverlay() {\n console.log('add OVERLAY');\n $('body').append('<div class=\"overlay\"></div>');\n }",
"function highlightFeature(e) {\n\tvar layer = e.target;\n\n\t// style to use on mouse over\n\tlayer.setStyle({\n\t\tweight: 2,\n\t\tcolor: '#666',\n\t\tfillOpacity: 0.7\n\t});\n\n\tif (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {\n\t\tlayer.bringToFront();\n\t}\n\n\tinfo_panel.update(layer.feature.properties)\n\tcreateDashboard(layer.feature.properties)\n}",
"function mouseClicked(){\n coll.push(new collectionLines([mouseX, mouseY],30));\n}",
"function overlay()\r\n{\r\n img[i].resize(vScale, vScale);\r\n img[i].loadPixels();\r\n loadPixels();\r\n\r\n for (var y = 0; y < img[i].height; y++) {\r\n for (var x = 0; x < img[i].width; x++) {\r\n \r\n var index = (x + y * img[i].width)*4\r\n var r = img[i].pixels[index+0];\r\n var g = img[i].pixels[index+1];\r\n var b = img[i].pixels[index+2];\r\n \r\n var bright = (r+g+b)/3;\r\n \r\n var threshold = 35;\r\n \r\n var checkIndex = x + y * cols;\r\n \r\n if (bright < threshold)\r\n {\r\n boxes[checkIndex].checked(false);\r\n } else {\r\n boxes[checkIndex].checked(true);\r\n }\r\n\r\n noStroke();\r\n rectMode(CENTER);\r\n rect(x*vScale, y*vScale, vScale, vScale);\r\n }\r\n } \r\n}",
"function addOverlay() { \n imgOverlay.setMap(map);\n}",
"function overlayPlotLines(data){\n var possibleTouchpoints = data.ChannelRanking.Touchpoints;\n var numSelectedTouchpoints = 0;\n for (var i = 0; i < possibleTouchpoints.length; i++) {\n if (possibleTouchpoints[i].Selected) {\n numSelectedTouchpoints += 1;\n }\n }\n var plotLines = [];\n for (var i = 0; i < numSelectedTouchpoints; i++) {\n plotLines.push({\n value: i + 0.5,\n color: 'white',\n width: 2,\n zIndex: 5\n })\n }\n return plotLines\n }",
"function highlightObject(object) {\n // Display a box around it\n push();\n noFill();\n stroke(230, 120, 150);\n strokeWeight(7);\n if (slider.value() > 1 && slider.value() < 6) {\n stroke(255, 0, 0);\n }\n\n if (slider.value() > 5 && slider.value() < 8) {\n stroke(0, 0);\n }\n rect(object.x + 100, object.y + 100, object.width + 100, object.height + 100);\n\n pop();\n // Display the label and confidence in the center of the box\n push();\n textFont(f, 100);\n textAlign(RIGHT, RIGHT);\n textSize(38);\n fill(230, 120, 150);\n if (slider.value() > 7) {\n textSize(46);\n if (object.label === `person`) {\n object.label = `Human`;\n text(\n `${object.confidence.toFixed(2)}`,\n object.width + 100,\n object.height\n );\n }\n }\n\n if (slider.value() > 5 && slider.value() < 8) {\n fill(0, 0);\n }\n\n if (slider.value() > 1 && slider.value() < 6) {\n fill(255, 0, 0);\n if (object.label === `person`) {\n object.label = `Consumer`;\n text(\n `${object.confidence.toFixed(2)}`,\n object.width + 100,\n object.height\n );\n } else {\n object.label = `Buy`;\n }\n }\n text(`${object.label}`, object.width, object.height);\n pop();\n}",
"function highlightIndusZones(e) {\n var layer = e.target;\n\n layer.setStyle({\n weight: 2,\n color: 'yellow',\n dashArray: '3',\n fillOpacity: 0.7,\n fillColor: '#F58723'\n });\n\n if (!L.Browser.ie && !L.Browser.opera) {\n layer.bringToFront();\n }\n\n var popupIndus = $(\"<div></div>\",{\n id:\"industrial\",\n css:{}\n });\n var contentIndus = $(\"<h4>Industrial Zones</h4><p>\"+layer.feature.properties.CODE+\"</p><p style='font-size:11px'><i><b>\"+layer.feature.properties.LOCATION+\"</b></i></p>\").appendTo(popupIndus);\n\n popupIndus.appendTo(\"#map\");\n }",
"onLayerHighlight() {}",
"function closeOnClick(event){\n //make sure the area being clicked is just the overlay\n if(event.target.id == \"overlay\"){\n closeOverlay();\n }\n\n}",
"function highlightFeature(e) {\n\tvar layer = e.target;\n\n\t// style to use on mouse over\n\tlayer.setStyle({\n\t\tweight: 2,\n\t\tcolor: '#666',\n\t\tfillOpacity: 0.7\n\t});\n\n\t\n\t\n\tinfo_panel.update(layer.feature.properties)\n\t\n\n\t\n\n\t\n\n}",
"function selectPoint (poi) {\n\tselectedPoints.push(poi);\n}",
"function showInsulaDetailsFromMarker(e){\n\t\tvar insulaMarker = e.target;\n\t\tvar insulaToHighlight = getInsulaFromMarker(insulaMarker);\n\t\tpompeiiInsulaLayer.eachLayer(function(layer){\n\t\t\tif(layer.feature!=undefined && interactive){\n\t\t\t\tif (layer.feature.properties.insula_id == insulaToHighlight){\n\t\t\t\t\tshowInsulaDetails(layer);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
delete all file and dir expert root dir by dirPath | function rmDir(dirPath) {
var files = fs.readdirSync(dirPath);
if (files.length > 0) {
for (var i = 0; i < files.length; i++) {
var filePath = path.join(dirPath, files[i]);
if (fs.statSync(filePath).isFile()) {
fs.unlinkSync(filePath);
} else {
rmDir(filePath);
}
}
}
//fs.rmdirSync(dirPath);
} | [
"function DeleteOutput (dir) {\n if(dir === \"\") {\n dir = dir_path;\n }\n\n if(fileExists (dir)) {\n var list = fs.readdirSync(dir);\n for(var i = 0; i < list.length; i++) {\n var filename = path.join(dir, list[i]);\n var stat = fs.statSync(filename);\n\n if(filename == \".\" || filename == \"..\") {\n // pass these files\n } else if(stat.isDirectory()) {\n // rmdir recursively\n DeleteOutput(filename);\n } else {\n // rm fiilename\n fs.unlinkSync(filename);\n }\n }\n //don't delete the output root\n if(dir !== dir_path) {\n fs.rmdirSync(dir);\n }\n }\n\n}",
"clearTemps() {\n fs.rmdirSync(this.temps, { recursive: true });\n }",
"function _clean_files(dir) {\n gulpUtil.log(`Removing files from ${dir}`);\n return del([dir])\n}",
"cleanUpSDKFiles() {\n this.fileOpsUtil.deleteFile(\n path.join(\n this.dispatcherConfigPath,\n Constants.CONF_D,\n Constants.AVAILABLE_VHOSTS,\n \"default.vhost\"\n )\n );\n this.fileOpsUtil.deleteFile(\n path.join(\n this.dispatcherConfigPath,\n Constants.CONF_D,\n Constants.ENABLED_VHOSTS,\n \"default.vhost\"\n )\n );\n this.fileOpsUtil.deleteFile(\n path.join(\n this.dispatcherConfigPath,\n Constants.CONF_DISPATCHER_D,\n Constants.AVAILABLE_FARMS,\n \"default.farm\"\n )\n );\n this.fileOpsUtil.deleteFile(\n path.join(\n this.dispatcherConfigPath,\n Constants.CONF_DISPATCHER_D,\n Constants.ENABLED_FARMS,\n \"default.farm\"\n )\n );\n }",
"function cleanup(dir) {\n console.log('Removing temporarily extracted zip contents ...');\n\n // cf. http://stackoverflow.com/questions/18052762/remove-directory-which-is-not-empty\n var deleteFolderRecursive = function(path) {\n if( fs.existsSync(path) ) {\n fs.readdirSync(path).forEach(function(file,index){\n var curPath = path + \"/\" + file;\n if(fs.lstatSync(curPath).isDirectory()) { // recurse\n deleteFolderRecursive(curPath);\n } else { // delete file\n fs.unlinkSync(curPath);\n }\n });\n fs.rmdirSync(path);\n }\n };\n\n deleteFolderRecursive(dir);\n return Promise.resolve();\n}",
"removeFolder(path){\n // remove the path from the array\n let updatedPaths = this._folderPaths.filter(currPath => currPath !== path);\n\n // update object\n this._folderPaths = updatedPaths;\n\n // update file \n return this.update();\n }",
"deleteFromTree({ state, commit, getters, dispatch }, directories) {\n directories.forEach((item) => {\n // find this directory in the tree\n const directoryIndex = getters.findDirectoryIndex(item.path);\n\n if (directoryIndex !== -1) {\n // add directory index to array for deleting\n commit('addToTempArray', directoryIndex);\n\n // if directory has subdirectories\n if (state.directories[directoryIndex].props.hasSubdirectories) {\n // find subDirectories\n dispatch('subDirsFinder', state.directories[directoryIndex].id);\n }\n }\n });\n\n // filter directories\n const temp = state.directories.filter((item, index) => {\n if (state.tempIndexArray.indexOf(index) === -1) {\n return item;\n }\n return false;\n });\n\n // replace directories\n commit('replaceDirectories', temp);\n\n // clear temp array\n commit('clearTempArray');\n }",
"function folderCleanUp() {\n DriveApp.getFoldersByName('test1').next().setTrashed(true);\n DriveApp.getFoldersByName('test2').next().setTrashed(true);\n}",
"removeUploadedSet(dir) {\n return removeDir(this.uploadPath + '/' + dir)\n }",
"rm(ws, project, args) {\n\t\tlet recursive = false;\n\t\tconst glob = new Glob();\n\t\targs.forEach(arg => {\n\t\t\tif (arg.startsWith('-')) {\n\t\t\t\tif (arg === '-r') recursive = true;\n\t\t\t} else {\n\t\t\t\tglob.include(arg);\n\t\t\t}\n\t\t});\n\t\tglob.match(project.root).forEach(file => {\n\t\t\tif(fs.lstatSync(file).isDirectory()) {\n\t\t\t\t// TODO impl recursive dir removal?\n\t\t\t\t/*\n\t\t\t\t// ignore for now.\n\t\t\t\tfs.rmdirSync(file, {\n\t\t\t\t\trecursive: true\n\t\t\t\t});\n\t\t\t\t*/\n\t\t\t\tconsole.log('not removing directory:', file);\n\t\t\t} else {\n\t\t\t\t//console.log('rm file:', file);\n\t\t\t\tfs.unlinkSync(file);\n\t\t\t}\n\t\t});\n\t}",
"function cleanTemp() {\n cleanFolder(uploadFolder);\n}",
"function RemoveFilesPreImport(path : String, fileName : String){\n\tDeleteFromDisk(path, fileName + \"_albedo\");\n\tDeleteFromDisk(path, fileName + \"_opacity\");\n\tDeleteFromDisk(path, fileName + \"_roughness\");\n\tDeleteFromDisk(path, fileName + \"_metallic\");\n}",
"function removeTestFileFromRootFolder() {\n var root = DriveApp.getRootFolder(),\n id = '1xIeidH1-Em-xDlm_84e70FrORfkttXFfVqYRzEv58ZA',\n file = DriveApp.getFileById(id);\n root.removeFile(file);\n}",
"function cleanBuild() {\n if (!cleaned) {\n cleaned = true;\n clearTimeout(cleanTimeout);\n if (app.config.get('auto-cleanup') !== false) {\n console.log('Removing: ' + dir);\n exec('rm -rf ' + dir, function (rerr) {\n //\n // Ignore errors removing the tmp directory\n //\n return !rerr\n ? console.log('Removed: ' + dir)\n : console.log(rerr.message);\n });\n }\n }\n }",
"function CleanUpHerokuDistFolder(){\n del.sync(`${deploymentPaths.HEROKU_DIST_FOLDER}/**`);\n}",
"function clean_assets() {\n return del([\"./assets\"]);\n}",
"function deleteFile() {\r\n\t\tif(!keepTmpFile) {\r\n\t\t\tfs.unlink(tmpFilePath, function() {});\r\n\t\t}\r\n\t}",
"function deleteImages(imgRelPathArr, callback){\n if(! Array.isArray(imgRelPathArr)) return callback(new Error(\"Array of files expected in deleteImages\"))\n\n let imgAbsPathArry = imgRelPathArr.map(relPath => uploadDirPath + '/' + relPath )\n\n async.map(\n imgAbsPathArry,\n async.reflect(\n function(f, cb){\n fs.stat(f, function(err, stats){\n if(err) return cb(err)\n\n fs.unlink(f, cb)\n })\n }\n ),\n\n function(err, results){\n if(err) return callback(err)\n\n let successDeleted = 0\n\n results.forEach(e => {\n if(e.value){\n successDeleted++\n }\n })\n\n callback(null, successDeleted)\n }\n )\n}",
"function cleanLog() {\n cleanFolder(join(submitFolder, \"Logs\"));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets last selected hero state and passes the data to parent | onChangeHero(hero) {
this.setState({lastSelectedHero: hero, nameChange: false});
this.props.hero(hero);
} | [
"function SelectHero( heroName ) {\n\t//Send the pick to the server\n\tGameEvents.SendCustomGameEventToServer( \"SelectHero\", { HeroName: heroName} );\n\n}",
"opponentSelectionDone(opponent) {\n const trainingOpponentSelection = opponent.selection;\n\n this.setState({\n mode: Modes.ShipSelection,\n settingAttack: true,\n trainingOpponent: opponent.address,\n trainingOpponentSelection,\n trainingOpponentCommander: opponent.commander,\n trainingCp: this._selectionToCp(trainingOpponentSelection),\n });\n }",
"createFinalDungeon (heroStats, heroItems) {\n this.finalDungeon = true\n this.enemies = this.createEnemies()\n this.setState({ \n gameId: this.state.gameId + 1,\n heroStats: heroStats,\n heroItems: heroItems\n })\n }",
"function updateHero(){\n\t\t// Attach a click event onto each character element to allow the player to pick one as\n\t\t// a hero.\n\t\t$(\".character\").on(\"click\", function(){\n\t\t\t\t// Load Hero Data into Hero object for use in the game\n\t\t\t\thero = { \n\t\t\t\t\tname:$(this).attr(\"data-name\"),\n\t\t\t\t\timg:$(this).attr(\"data-img\"),\n\t\t\t\t\tattackPower:parseInt($(this).attr(\"data-attack\")),\n\t\t\t\t\tcounterAttackPower:parseInt($(this).attr(\"data-counter\")),\n\t\t\t\t\thitPoints:parseInt($(this).attr(\"data-hp\")) \n\t\t\t\t};\n\t\t\t\t// Load the hero's attack into currentAttackGrowth so we can use it later to increment our hero's power.\n\t\t\t\tcurrentAttackGrowth = hero.attackPower;\n\t\t\t\t// Turn off the ability to click another hero\n\t\t\t\tchooseHero = false;\n\t\t\t\t// Turn on the ability to click an enemy\n\t\t\t\tchooseEnemy = true;\n\t\t\t\t// Update the classes on the element\n\t\t\t\t$(this).removeClass(\"character\");\n\t\t\t\t$(this).addClass(\"hero\");\n\t\t\t\t// Remove the click event from this element.\n\t\t\t\t$(this).off();\n\t\t\t\t// Update this element with the Hero information.\n\t\t\t\t$(this).html(\n\t\t\t\t\t\"<p>\" + hero.name + \"</p>\" +\n\t\t\t\t\t\"<img src='\" + hero.img + \"' >\" +\n\t\t\t\t\t\"<p> HP: \" + hero.hitPoints + \"</p>\"\n\t\t\t\t\t);\n\t\t\t\t// Append it to the hero div\n\t\t\t\t$(\"#hero\").append($(this));\n\t\t\t\t// Play sound effect\n\t\t\t\tlightsaberOn.play();\n\t\t\t\t// Update the Game Displays\n\t\t\t\t$(\"#characters\").hide();\n\t\t\t\t$(\"#game-window\").show();\n\t\t\t\t$(\"#status-window\").text(\"Select An Enemy!\");\n\t\t\t\t// Return to runGame() to finish game setup.\n\t\t\t\trunGame();\n\n\t\t\t});\n\t}",
"setBreakfastItem(state, breakfast) {\n state.selectedBreakfast[breakfast.index] = breakfast.data\n }",
"setSelected () {\n if (this.el.classList.contains(MenuItem.OVER_CLASS)) {\n this.animateSelected()\n } else {\n this.animateOnOver(() => {\n this.animateSelected(() => {\n this.setState()\n })\n })\n }\n }",
"set selectedItem(child) {\n let menuArray = this._orderedMenuElementsArray;\n\n if (!child) {\n this._selectedItem = null;\n }\n for (let node of menuArray) {\n if (node == child) {\n node.classList.add(\"selected\");\n this._selectedItem = node;\n } else {\n node.classList.remove(\"selected\");\n }\n }\n\n this.ensureElementIsVisible(this.selectedItem);\n }",
"function setMostRecentGame() {\n\n console.log(\"setting current game...\");\n\n vm.currentGame = vm.games[vm.games.length-1];\n\n\n console.log(\"current game set to: \" + vm.currentGame.rows);\n\n }",
"setSelectedClient(state, selectedClient) {\n state.selectedClient = selectedClient;\n }",
"_onOptionSelect(props) {\n props.selectOption(props.data);\n const isSelected = props.isSelected;\n if (isSelected) return;\n let parent = props.data.parent;\n while (parent) {\n let option = this._findOption(this.toggledOptions, parent);\n if (!option) {\n parent.expanded = true;\n this.toggledOptions.push(parent);\n }\n parent = option?.parent ?? parent.parent;\n }\n }",
"onDishSelect(dish){\n\t\tthis.setState({selectedDish:dish});\n\t}",
"setChosenAdventure(newAdventure){\n\t\t\tchosenAdventure = newAdventure;\n\t\t}",
"prepareNextState() {\n this.setGameBoard();\n this.gameOrchestrator.changeState(new ChoosingPieceState(this.gameOrchestrator));\n }",
"handleMenuItemClick(event) {\n const el = event.target.closest(\".option\");\n if (el) {\n this.setState(\n (st) => {\n const updatedOptionList = st.options.map((option) => {\n if (option.id === el.dataset.id) {\n return { ...option, selected: true };\n }\n return { ...option, selected: false };\n });\n return {\n options: updatedOptionList,\n menuOpened: false,\n snackBarActive: true,\n };\n },\n () => {\n setTimeout(() => {\n this.setState({ snackBarActive: false });\n }, 3000);\n }\n );\n }\n }",
"function setChosenAnswer() {\n\n\t\tif ( !input.params.isTouchScreen ) {\n\n\t\t\t// Clean all the answer of the blinking class\n\t\t\tfor ( domAnswer of domAnswersContainer.children ) {\n\t\t\t\tdomAnswer.classList.remove( 'selected-answer' );\n\t\t\t};\n\n\t\t\t// assign the blinking class to the answer newly chosen\n\t\t\tlet newDomChoice = questionTree.answers[ questionTree.currentChoice ].dom ;\n\t\t\tnewDomChoice.classList.add( 'selected-answer' );\n\n\t\t};\n\n\t}",
"function addEventToMainStateSelect(){\n if($('first_section_select_state').value === \"\"){\n } else {\n // Save the selectedState\n selectedState = $('first_section_select_state').value;\n\n //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\\\\n // EVENTS \\\\\n //------------------------------------------------------------\\\\\n // 1. Update Breadcrumbs \\\\\n // 2. Fade out \\\\\n // - first_section_select_state \\\\\n // - county_quick_search_wrapper \\\\\n // - home_page_information_container \\\\\n // 3. Create \\\\\n // - first_section_select_county \\\\\n // - first_section_back_county \\\\\n // + Update Second Section \\\\\n // - second_section_label \\\\\n // + Update Third Section \\\\\n // 4. Fade in \\\\\n // - first_section_select_county \\\\\n // - first_section_back_county \\\\\n // - second_section_wrapper \\\\\n // - third_section_state_data_vis_container \\\\\n // 5. Add Events \\\\\n // - first_section_back_county \\\\\n // - first_section_select_county \\\\\n // 6. Move window location to the second section \\\\\n //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\\\\n \n // 1. Update Breadcrumbs \\\\\n $('current_selection_label_dynamic_container').innerHTML = (\"<div class='current_selection_label_dynamic_scheme'>\" + selectedState + \"</div>\");\n\n // 2. Fade out \\\\\n // - first_section_select_state \\\\\n // - county_quick_search_wrapper \\\\\n // - home_page_information_container \\\\\n $('first_section_select_state').set('tween', { duration: 1000 }).fade('out');\n $('county_quick_search_wrapper').set('tween', { duration: 1000 }).fade('out');\n $('home_page_information_container').set('tween', { duration: 1000 }).fade('out');\n\n\n // 3. Create \\\\\n // - first_section_select_county \\\\\n // - first_section_back_county \\\\\n // + Update Second Section \\\\\n // - second_section_label \\\\\n // + Update Third Section \\\\\n $('first_section_scroll_area').innerHTML = \"\";\n placeHolder = \"\";\n placeHolder += \"<select size='20' id='first_section_select_county' name='first_section_select_county' style='opacity: 0; visibility: hidden;'>\";\n for(var i=0; i<numOfStates; i++){\n if(libraries['states'][i][0]['name'] === selectedState){\n numOfCounties = libraries['states'][i][0]['counties'].length;\n for(var j=0; j<numOfCounties; j++){\n placeHolder += (\"<option value='\" + libraries['states'][i][0]['counties'][j][0]['name'] + \"'>\" + libraries['states'][i][0]['counties'][j][0]['name'] + \"</option>\");\n }\n }\n }\n placeHolder += \"</select>\";\n placeHolder += \"<div id='first_section_back_county' class='main_search_back_button' style='opacity: 0; visbility: hidden;'>Back To State List</div>\";\n $('first_section_scroll_area').innerHTML = placeHolder;\n $('second_section_label').innerHTML = (selectedState + \" Attributes\");\n \n // 4. Fade in \\\\\n // - first_section_select_county \\\\\n // - first_section_back_county \\\\\n // - second_section_wrapper \\\\\n // - third_section_state_data_vis_container \\\\\n $('first_section_select_county').set('tween', { duration: 1100 }).fade('in');\n $('first_section_back_county').set('tween', { duration: 1100 }).fade('in');\n $('second_section_wrapper').set('tween', { duration: 1100 }).fade('in');\n $('third_section_state_data_vis_container').set('tween', { duration: 1100 }).fade('in');\n \n\n // 5. Add Events \\\\\n // - first_section_back_county \\\\\n // - first_section_select_county \\\\\n $('first_section_back_county').addEvent('click', function(){\n countyBackButton(); \n });\n $('first_section_select_county').addEvent('change', function(){\n if($('first_section_select_county').value === \"\"){\n } else {\n selectedCounty = $('first_section_select_county').value;\n numOfCounties = $('first_section_select_county').options.length;\n addEventToMainCountySelect(selectedState, selectedCounty, numOfCounties);\n }\n });\n\n // 6. Move window location to the second section \\\\\n window.location = \"#county_quick_search_container\";\n }\n }",
"training() {\n const trainingOpponentSelection = TRAINING_SELECTION;\n\n this.setState({\n mode: Modes.ShipSelection,\n trainingOpponentSelection,\n trainingOpponentCommander: 0,\n trainingCp: this._selectionToCp(trainingOpponentSelection),\n });\n }",
"onEditHobby(indexNoHobby) {\n const { hobbyTrait } = this.state;\n this.setState({\n newHobby: {\n hobby: hobbyTrait.traits.data[indexNoHobby].hobby,\n description: _.isEmpty(hobbyTrait.traits.data[indexNoHobby].description) ? '' : hobbyTrait.traits.data[indexNoHobby].description,\n },\n isHobbyEdit: true,\n indexNoHobby,\n formInvalidHobby: false,\n isSubmitHobby: false,\n });\n }",
"updateCropSelection(d, that, thisLi) {\n that.cropVis.selected_crop = d;\n that.updateCropOnMap(that);\n // Unhighlight previously selected crop and highlight selected crop\n d3.selectAll(\".clickedCropLi\").classed(\"clickedCropLi\", false);\n d3.select(thisLi).attr(\"class\", \"clickedCropLi\");\n let current_countries = [...that.cropVis.selected_countries];\n that.cropVis.selected_countries.clear();\n // that.cropVis.worldMap.clearHighlightedBoundaries();\n that.cropVis.barChart.deleteBarChart();\n that.cropVis.lineChart.deleteLineChart();\n that.cropVis.lineChart.alreadyExistingCountries.clear();\n that.cropVis.table.drawTable();\n for (let country of current_countries) {\n that.cropVis.selected_countries.add(country);\n that.cropVis.barChart.updateBarChart();\n }\n that.cropVis.lineChart.updateLineChart();\n that.cropVis.worldMap.updateAllMapTooltips(that);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the provided `args` object satisfies the `LocalProgramArgs` interface. | function isLocalProgramArgs(args) {
return args.workDir !== undefined;
} | [
"function isInlineProgramArgs(args) {\n return args.projectName !== undefined && args.program !== undefined;\n}",
"canExecute(args) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tif (args.length > 1) {\n\t\t\t\tthis.$errors.failWithoutHelp(\"This command accepts only one argument.\");\n\t\t\t}\n\n\t\t\tif (args.length) {\n\t\t\t\tresolve(true);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.$errors.failWithoutHelp(\"You should pass at least one argument to 'hello-world' command.\");\n\t\t});\n\t}",
"receivedCall(args, times) {\n const minRequired = times || 1;\n if (args.length === 0 && this.hasEmptyCalls(minRequired)) {\n return true;\n }\n const setupArgs = this.convertArgsToArguments(args);\n let matchCount = 0;\n for (const call of this.calls) {\n const isMatch = this.argumentsMatch(setupArgs, call);\n if (isMatch === true) {\n matchCount++;\n if (matchCount >= minRequired) {\n return true;\n }\n }\n }\n return false;\n }",
"hasConfiguredMethodReturn(args) {\n if (this.methodReturnSetups.length === 0) {\n return false;\n }\n const callArgs = this.convertArgsToArguments(args);\n for (const setup of this.methodReturnSetups) {\n if (this.argumentsMatch(setup.arguments, callArgs) === true) {\n return true;\n }\n }\n return false;\n }",
"function validarArgumentos(args, msg){\n if(process.argv.length !== (2+args)){\n console.log(msg);\n process.exit(2);\n }\n return true;\n}",
"emit(args, scope) {\n constants_1.debug('Emitting \"%s%s\" as bail', this.name, scope ? `:${scope}` : '');\n return Array.from(this.getListeners(scope)).some(listener => listener(...args) === false);\n }",
"function isStandaloneApp() {\n return navigator.standalone;\n }",
"function processArgs( a ){\n\t\t// If is from a standard GTM UA template tag, automatically allow hit.\n\t\tif( a[0] && a[0].substr && a[0].substr( 0, 3 ) == 'gtm' )\n\t\t\treturn true;\n\t\t// Call listener, return false only if listener returns false.\n\t\treturn callback( a ) !== false;\n\t}",
"function isLocalStation(stationIp, adviseLaunchInfo){\n\ttry {\n\t\tvar ipArr = stationIp.split(',');\n\t\t\n\t\tif (ipArr.indexOf(adviseLaunchInfo.localIP) > -1)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t\t\n\t} catch(ex){\n\t\treturn false;\n\t}\n}",
"static areIdentical(){\n let temp\n\n for(let i = 0; i < arguments.length; i++){\n let argument = arguments[i]\n\n // handle NaN\n if(isNaN(argument.h)) argument.h = argument.h.toString()\n if(isNaN(argument.m)) argument.m = argument.m.toString()\n\n // handle string input\n if(typeof argument.h === \"string\") argument.h = parseInt(argument.h)\n if(typeof argument.m === \"string\") argument.m = parseInt(argument.m)\n\n // if temp is empty -> this is the first argument, store the first temp\n if(!temp){\n temp = argument\n continue\n }\n\n // if the temp and the current argument are not identical, return false\n if(argument.h !== temp.h || argument.m !== temp.m || argument.pm !== temp.pm) return false\n\n // store the current argument as the new temp\n temp = argument\n }\n\n return true\n }",
"function areThereDuplicates(...args) {\n const frequency = {};\n for (let i = 0; i < args.length; i++) {\n if (frequency[args[i]]) {\n return true;\n } else {\n // don't assign this to 0 because 0 is falsey\n frequency[args[i]] = 1;\n }\n }\n return false;\n}",
"cliIf(cond, ...args) {\n if (isTrue(cond)) return this.cli(...args);\n }",
"function short_circuiting_predicate(predicate, args) {\n var previous = args[0];\n for(var i = 1; i < args.length; i++) {\n if(!predicate(previous, args[i])) {\n return false; // short circuit\n }\n }\n return true; // no short circuit, all true\n }",
"function isArgUsedInFunc(fcallexpr, arg) {\r\n\r\n // First find the called function object\r\n //\r\n var ind = getFuncIdByName(CurModObj, fcallexpr.str);\r\n var fO = CurModObj.allFuncs[ind];\r\n\r\n var argpos = arg + 1; // in header, 0th arg is ReturnValue \r\n var gid = fO.allSteps[FuncHeaderStepId].allGridIds[argpos];\r\n\r\n // Go thru all steps of the function and see whether this grid is used\r\n //\r\n for (var s = FuncHeaderStepId + 1; s < fO.allSteps.length; s++) {\r\n\r\n var stepO = fO.allSteps[s];\r\n\r\n for (var g = 0; g < stepO.allGridIds.length; g++) {\r\n\r\n if (stepO.allGridIds[g] == gid)\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}",
"function check_undefined(args, names) {\n names.forEach(function (name, i) {\n if (args[i] === undefined) {\n console.error('Argument is undefined: ' + names[i]);\n }\n });\n}",
"function is_predef_app(name) {\n var rule = get_predefined_rules(name);\n\n if(rule.length) {\n rule = rule.split(\"\\x02\");\n if(rule[_category] == CATEGORY_APP) {\n return true;\n }\n }\n return false;\n}",
"function isAudioContext(arg) {\n return (0, _standardizedAudioContext.isAnyAudioContext)(arg);\n}",
"function validateArgs() {\n //No arguments or any argument set including the help argument are both\n //automatically valid.\n //If -pre, -dest, -ign, -ext, -enc, or -cst were provided, -repo\n //must also have been provided.\n //The presence of -sets and -args is always optional.\n\n //Allow no arguments or any set with a -help argument.\n if (0 === aargsGiven.length || -1 !== aargsGiven.indexOf('-help')) {\n return;\n }\n\n //Otherwise, require the -repo command if -pre, -dest, -ign, -ext,\n //-enc, or -cst were provided.\n if ((-1 !== aargsGiven.indexOf('-pre') ||\n -1 !== aargsGiven.indexOf('-dest') ||\n -1 !== aargsGiven.indexOf('-ign') ||\n -1 !== aargsGiven.indexOf('-ext') ||\n -1 !== aargsGiven.indexOf('-enc') ||\n -1 !== aargsGiven.indexOf('-cst')) &&\n -1 === aargsGiven.indexOf('-repo')) {\n throw 'Invalid argument set. Must use -repo if using any other ' +\n 'command except -help, -sets, or -args.';\n }\n }",
"function args_count(){\n return arguments.length;\n}",
"function and () {\n\t var predicates = Array.prototype.slice.call(arguments, 0)\n\t if (!predicates.length) {\n\t throw new Error('empty list of arguments to or')\n\t }\n\n\t return function orCheck () {\n\t var values = Array.prototype.slice.call(arguments, 0)\n\t return predicates.every(function (predicate) {\n\t return low.fn(predicate) ? predicate.apply(null, values) : Boolean(predicate)\n\t })\n\t }\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pre: array of usernames, and boolean stating if we are adding a user Post: null Purpose: takes a list of names and if we are adding them removes them from the offline list in view, if applicable, and adds them to the online list. For removing is is the same process but in the opposite direction | function modifyUsers(userlist, add) {
let newList;
let oldList;
if (add) {
oldList = document.getElementById('offline');
newList = document.getElementById('online');
} else {
oldList = document.getElementById('online');
newList = document.getElementById('offline');
}
Array.from(oldList.getElementsByTagName('li')).forEach(user => {
userlist.forEach(username => {
if (username === user.innerText) {
oldList.removeChild(user);
}
});
});
userlist.forEach(username => {
let exists = false;
Array.from(newList.getElementsByTagName('li')).forEach(user => {
if (user.innerText === username) {
exists = true;
}
});
if (!exists) {
let li = document.createElement('li');
li.innerText = username;
newList.appendChild(li);
}
});
} | [
"function initUsers(userlist) {\n let online = document.getElementById('online');\n let offline = document.getElementById('offline');\n\n userlist.map(user => {\n let li = document.createElement('li');\n li.innerText = user.name;\n\n if (user.active) {\n online.appendChild(li);\n } else {\n offline.appendChild(li);\n }\n })\n}",
"function setOnlineUser(user) {\n onlineUsers.push(user)\n console.log(`[ ${user.username.toUpperCase()}: IS NOW ONLINE ]`)\n console.log('[ONLINE USERS:]')\n \n function allOnlineUsers(onlineUsers) {\n for (user of onlineUsers) {\n console.log(`* ${user.username}`)\n }\n }\n \n allOnlineUsers(onlineUsers)\n \n }",
"function removeUserFromList(listName, userName) {\r\n\tvar curList\t= getValue(listName,'');\r\n\r\n\t// We add a leading and trailing ;, so that when searching for ;username; to replace will find even the ones at the beginning or end of the string\r\n\tcurList\t\t= ';' + curList\r\n\r\n\t// escape the userName and then search for it; the string we have is an escaped version of the string\r\n\tuserName\t= ';' + urlencode( userName );\r\n\r\n\t// Remove the user from the list\r\n\tvar iUser\t= curList.search( userName );\r\n\tif ( iUser > -1 ) {\r\n\t\tcurList\t\t= getValue( listName, '');\r\n\t\tcurList\t\t= curList.replace( userName, \"\");\r\n\t\tsetValue( listName, curList );\r\n\t } else {\r\n\t}\r\n\r\n }",
"function removeadduser(level){\n\tif(level == \"add\"){\n\t\t$('.usernotexist').each(function(){\n\t\t\tif($(this).is(':checked')){\n\t\t\t\tvar did = $(this).attr('did');\n\t\t\t\tif (checkArray(did,userNotExistArray)){\n\t\t\t\t\tvar indx = userNotExistArray.indexOf(did);\n\t\t\t\t\tuserNotExistArray.splice(indx,1);\n\t\t\t\t}\n\t\t\t\tif (!checkArray(did,userExistArray)){\n\t\t\t\t\tuserExistArray.push(did);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}else{\n\t\t$('.userexist').each(function(){\n\t\t\tif($(this).is(':checked')){\n\t\t\t\tvar did = $(this).attr('did');\n\t\t\t\tif (checkArray(did,userExistArray)){\n\t\t\t\t\tvar indx = userExistArray.indexOf(did);\n\t\t\t\t\tuserExistArray.splice(indx,1);\n\t\t\t\t}\n\t\t\t\tif (!checkArray(did,userNotExistArray)){\n\t\t\t\t\tuserNotExistArray.push(did);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t}\n\tcreatetableforinvitation();\n}",
"function add2List(me, friends) {\n var myName = me.name.substring(0, 20).toLowerCase();\n \n for (var i=0; i<friends.length; i++) {\n if (myName === friends[i].name.substring(0,20).toLowerCase()) {\n friends[i] = me;\n return;\n } \n }\n friends.push(me);\n }",
"function addUser(user) {\n usersList.push(user);\n fs.writeFile(`${dir}/users.json`, JSON.stringify(usersList), error => {\n if (error) throw error;\n });\n}",
"function addUser(name) {\n var newUser = {\n name: name,\n seed: Math.floor(Math.random() * 1000000) + 1,\n history: []\n }\n newUser.avatarURL = genUserAvatar(name + newUser.seed);\n users.push(newUser);\n saveUsers();\n\n return users.length - 1;\n}",
"function createUsersLinkList(usersList, parent) {\n // for each user\n usersList.forEach(user => {\n // create new form element\n const newForm = document.createElement(\"form\");\n newForm.method = \"get\";\n newForm.action = \"/options\";\n newForm.className = \"usersLinkList\";\n // create new user list element with an evenet listener\n const newUser = document.createElement(\"li\");\n newUser.innerHTML = user;\n newUser.className = \"users-list-style\";\n newUser.addEventListener('click', function() {\n localStorage.setItem(\"actualUser\", user);\n newUser.parentElement.submit();\n });\n // add it to the form\n newForm.appendChild(newUser);\n // create a new hidden input element containing the username as value\n const usernameInput = document.createElement(\"input\");\n usernameInput.type = \"text\";\n usernameInput.name = \"username\";\n usernameInput.value = user;\n usernameInput.hidden = true;\n // add it to the form\n newForm.appendChild(usernameInput);\n // add the form to a parent element\n parent.appendChild(newForm);\n });\n}",
"function uppdatMemberInAppData(e){\n\n const originalName =e.target.closest('.member-in-list').querySelector('.memebr-name').textContent;\n\n const newList = {\n name:e.target.closest('.member-in-list').querySelector('.new-member-name').value\n };\n\n appData.members.forEach((member)=>{\n if(member.name===originalName){\n member.name=newList.name;\n }\n })\n\n}",
"function addToLocalList(name,id){\n var localList = JSON.parse(localStorage.getItem(\"pokemonLocalList\"));\n if (localList!= null){\n localList.push({\n id:id,\n name:name\n });\n localStorage.setItem(\"pokemonLocalList\",JSON.stringify(localList));\n }\n else {\n localStorage.setItem(\"pokemonLocalList\",JSON.stringify([{id:id,name:name}]));\n }\n }",
"hideFromUser(user1,user2){\n this.users[user1].friendsDontShow.push({name: this.users[user2].name, id: user2});\n return true;\n }",
"function muut_add_online_user(user) {\n online_user_html = get_user_avatar_html(user);\n var user_faces = widget_online_users_wrapper.find('.m-logged-users').append(online_user_html).find('.m-facelink');\n var new_user_face = user_faces[user_faces.length - 1];\n $(new_user_face).mootboost(500);\n $(new_user_face).facelinkinit();\n muut_update_online_users_widget();\n }",
"function updateCreatedByUserList() {\r\n\r\n // Null out current selected item and clear list.\r\n $scope.exportDataFormBean.createdByUserId = \"\";\r\n $scope.createdByUserList = [];\r\n\r\n // Create the request parameters we will post.\r\n var requestPayload = {};\r\n if ($scope.exportDataFormBean.showDeletedAssessmentCreators) {\r\n requestPayload = $.param({\"includeAll\": true});\r\n }\r\n else {\r\n requestPayload = $.param({\"includeAll\": false});\r\n }\r\n\r\n // Call the web service and update the model.\r\n $http({\r\n method: \"POST\",\r\n url: \"exportData/services/user/assessmentCreators\",\r\n responseType: \"json\",\r\n headers: {'Content-Type': 'application/x-www-form-urlencoded'},\r\n data: requestPayload\r\n })\r\n .success(function (data, status, headers, config) {\r\n $scope.createdByUserList = data;\r\n })\r\n .error(function (data, status) {\r\n //\r\n });\r\n }",
"typingNotify(data) {\n const { typingusers } = this.state;\n const index = typingusers.indexOf(data.user);\n if (data.typing && index === -1) {\n typingusers.push(data.user);\n this.setState({ typingusers });\n }\n else if (!data.typing && index !== -1) {\n typingusers.splice(index, 1);\n this.setState({ typingusers });\n }\n }",
"function inserToList(event) {\n event.preventDefault()\n var listItem = document.getElementsByClassName(\"userPage_input\")[0].value;\n list.push(listItem)\n document.getElementsByClassName(\"userPage_input\")[0].value = \"\";\n document.getElementsByClassName(\"userPage_list\")[0].innerHTML = sessionStorage.getItem(\"firstName\") + \" entered\"\n if (list.length > 0) {\n document.getElementsByClassName(\"userPage_list\")[0].style.display = \"block\"\n let newList =\n {\n contact_number: sessionStorage.getItem(\"contactNumber\"),\n list: list,\n }\n fetch('https://zezm09x6u5.execute-api.ap-south-1.amazonaws.com/Dev/list',\n {\n method: 'POST',\n body: JSON.stringify(newList)\n }).then(response => {\n fetch(\"https://zezm09x6u5.execute-api.ap-south-1.amazonaws.com/Dev/user?contact_number=\" + sessionStorage.getItem(\"contactNumber\"))\n .then(response => response.json())\n .then(result => {\n if (result.Count > 0) {\n for (var i = 0; i < result.Items[0].entered_list.length; i++) {\n orderedlist = \"<li>\" + result.Items[0].entered_list[i] + \"</li>\";\n document.getElementsByClassName(\"userPage_list\")[0].innerHTML += orderedlist;\n }\n }\n })\n })\n }\n\n}",
"updateBlackoutList(){\r\n this.blackoutList = [];\r\n for(var i = 0; i < this.prosumers.length; i++) {\r\n if(this.prosumers[i].blackout == true) {\r\n this.blackoutList.push(this.prosumers[i].username);\r\n }\r\n }\r\n\r\n /*for(var i = 0; i < this.consumers.length; i++) {\r\n if(this.consumers[i].blackout == true) {\r\n this.blackoutList.push(this.consumers[i].username);\r\n }\r\n }*/\r\n\r\n }",
"function setGameObject(userName, obj){\n\tvar newUsername = 'usr_' + userName;\n\tlocalStorage.setItem(newUsername, JSON.stringify(obj));\n\tif(localStorage.getItem(\"gameUsersList\") == undefined){\n\t\tvar list = new Array();\n\t\tlist[0] = userName;\n\t\tlocalStorage.setItem(\"gameUsersList\", JSON.stringify(list));\n\t}\n\telse\n\t{\n\t\tvar list = JSON.parse(localStorage.gameUsersList);\n\t\tlist.push(userName);\n\t\tlocalStorage.gameUsersList = JSON.stringify(list);\n\t}\n}",
"function onAddUsername() {\n if (self.usernameModel !== undefined) {\n //Add the username to the indexedDb database\n TransactionFactory.updateDataByKeyWithPromise(modelDatabaseObject, modelObjectStoreObject,\n modelIndecesObject, self.usernameModel)\n .then(function () {\n //Get the new list of users and repopulate the username dropdown\n Usernames.getAll(modelDatabaseObject, modelObjectStoreObject, modelIndecesObject).then(function (usernames) {\n var field;\n field = FormlyHelper.getFieldInFieldGroup(self.activeUsernameFields, 'userId');\n field.templateOptions.options = usernames;\n return usernames;\n });\n });\n }\n }",
"function populateUserList() {\r\n var editorIds = new Object();\r\n for (var seg in wazeModel.segments.objects) {\r\n var segment = wazeModel.segments.get(seg);\r\n var updatedBy = segment.attributes.updatedBy;\r\n if (editorIds[updatedBy] == null) {\r\n var user = wazeModel.users.get(updatedBy);\r\n if (user == null || user.userName.match(/^world_|^usa_/) != null) {\r\n continue;\r\n }\r\n editorIds[updatedBy] = user.userName;\r\n }\r\n }\r\n populateOption(highlightEditor.getSelectId(), editorIds);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return true if `val` has leading zeros, or a similar valid pattern. | function hasZeros(val) {
return /[^.]\.|^-*0+[0-9]/.test(val);
} | [
"function hasAZero(num){\n return num.toString().split('').some(function(num){\n return num === '0';\n })\n}",
"function test (regex, numbers) {\n const append = '8888'\n const res = true\n const rex = new RegExp('^' + regex + '(.*)$')\n\n numbers.forEach(function (n) {\n n = n.replace(/x/g, '0')\n const n1 = n + append\n let res = n1.match(rex)\n\n if (res[1] !== n || res[2] !== append) {\n console.error(n, res)\n res = false\n }\n })\n\n return res\n}",
"function cldr$compact$number$$needsFormatting(format) {\n return format.match(/[^0]/);\n }",
"function is0thSet(value) {\n return (value & 0b01);\n}",
"function checkDecimal()\n{\n let re = /^([0-9]*|[0-9]*\\.[0-9]*)$/;\n let number = this.value.trim();\n setErrorFlag(this, re.test(number) && number > 0);\n}",
"function isBetweenZeroAnd10(number) {\n return typeof 0 < number < 10;\n}",
"function matches(regexp, value) {\n var result = regexp.exec(value);\n return (result !== null && result.index === 0 && result[0].length === value.length);\n }",
"function validRule(in_rule){\n var rule = new String(in_rule);\n if(rule.length > 6 && rule != \"\" && rule.indexOf(\"\\x02\")!=-1){\n rule = rule.split(\"\\x02\");\n if(rule.length >= 5)\n return true;\n }\n\n return false;\n}",
"function isFirstDigits(num, n, incSign) {\n num = num.toString().replace(incSign ? \"\" : \"-\", \"\")\n n = n.toString().replace(incSign ? \"\" : \"-\", \"\")\n return num.slice(0, n.length) === n\n}",
"function checkSingleDigit(num) {\n return (\"0\" + num).slice(-2);\n}",
"function invalid_char(val) {\n if (val.match('^[a-zA-z0-9_]+$') == null) {\n return true\n } else {\n return false\n }\n}",
"function isAZeroMove(a) { return a.every((m) => m === 0); }",
"function check_phone(){\n\tvar phone = $(\"#current_phone\").text();\n\tif($(\"#sms\").val()==\"\") return false;\n\tif(phone == \"\") return false;\n\tvar reg = new RegExp(\"^\\\\+1[0-9]{10}$\");\n\tif(reg.test(phone)) return true;\n\treturn false;\n}",
"function zeroPad(val, width) {\n width = width || 2;\n while (String(val).length < 2) {\n val = '0' + String(val);\n }\n return val;\n }",
"function lessThanOrEqualToZero(num) {\r\n if(num <= 0){\r\n return true;\r\n } else{\r\n return false;\r\n }\r\n}",
"function isHexPrefixed(str){return str.slice(0,2)==='0x';}",
"function firstDigitIs(num, n) {\n return num.toString()[0] === n.toString()\n}",
"function isHex(value) {\n if (value.length == 0) return false;\n if (value.startsWith('0x') || value.startsWith('0X')) {\n value = value.substring(2);\n }\n let reg_exp = /^[0-9a-fA-F]+$/;\n if (reg_exp.test(value) && value.length % 2 == 0) {\n return true;\n } else {\n return false;\n }\n}",
"function validar_moneda(dato){\n const regex = /^(?!0\\.00)[1-9]\\d{0,2}(,\\d{3})*(\\.\\d\\d)?$/;\n return regex.test(dato); // true\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function gets the run number and instrument name from the UI elements. In addition the date code is obtained from the run list file | function getRunInstrumentDateAndPlot(plotFunc,awareControl) {
var startRun=getStartRunFromForm();
var plotName=getPlotNameFromForm();
var instrumentName=getInstrumentNameFromForm();
var runListFile=getRunListName(instrumentName,startRun);
function handleRunList(jsonObject) {
var gotRun=0;
for(var i=0;i<jsonObject.runList.length;i++) {
// if($('#debugContainer').is(":visible"))
// $('#debugContainer').append("<p>handleRunList... "+jsonObject.runList[i][0]+"</p>");
if(jsonObject.runList[i][0]==startRun) {
awareControl.year=jsonObject.runList[i][1];
awareControl.dateCode=jsonObject.runList[i][2]; ///RJN need to zero pad the string
gotRun=1;
plotFunc(awareControl);
break;
}
}
if(gotRun==0 ) {
var timePlotCan=$("#"+awareControl.timeCanName);
timePlotCan.empty();
timePlotCan.append("<h2>Don't have data for run "+startRun+"</h2>");
}
}
//The jquery ajax query to fetch the run list file
ajaxLoadingLog(runListFile);
$.ajax({
url: runListFile,
type: "GET",
dataType: "json",
success: handleRunList,
error: handleAjaxError
});
} | [
"onRunNameFocus (e) {\n if (typeof this.runOpts.runName !== typeof 'string' || (this.runOpts.runName || '') === '') {\n this.runOpts.runName = this.theModel.Model.Name + '_' + (this.isReadonlyWorksetCurrent ? this.worksetCurrent?.Name + '_' : '') + Mdf.dtToUnderscoreTimeStamp(new Date())\n }\n }",
"function runProject(){\r\n run = getDefaultWindow(\"project_runner_window\",800,500);\r\n run.setText(\"Gurski Browser [\"+current_project+\"]\");\r\n run.progressOn();\r\n run.center(); \r\n\r\n preview_toolbar = run.attachToolbar();\r\n preview_toolbar.setSkin(\"dhx_blue\");\r\n preview_toolbar.addButton(\"back\", 0,null, \"../images/back.png\", null);\r\n preview_toolbar.addButton(\"next\", 1,null, \"../images/next.png\", null);\r\n preview_toolbar.addText(\"labelURL\",2,\"URL:\");\r\n var path = \"../projects/\".concat(current_project.toString(), \"/\", current_project_index_file.toString());\r\n preview_toolbar.addInput(\"url\", 3,path,400);\r\n preview_toolbar.addButton(\"run\", 4,null, \"../images/run.jpg\", null);\r\n preview_toolbar.addInput(\"time\", 5,\"30\",40);\r\n preview_toolbar.addButton(\"clock\", 6,null, \"../images/clock.png\",\"../images/clockdis.png\");\r\n preview_toolbar.addButton(\"stop\", 7,null, \"../images/stop.png\", \"../images/stopdis.png\");\r\n preview_toolbar.disableItem(\"stop\");\r\n preview_toolbar.attachEvent(\"onClick\", function(id){\r\n if(id === \"run\"){\r\n run.progressOn();\r\n historyArray.push(preview_toolbar.getValue(\"url\").toString());\r\n historyNumber++;\r\n run.attachURL(preview_toolbar.getValue(\"url\").toString());\r\n setTimeout(\"run.progressOff()\",2000);\r\n }else if(id === \"next\"){\r\n historyNumber++;\r\n preview_toolbar.setValue(\"url\",historyArray[historyNumber].toString() );\r\n run.attachURL( historyArray[historyNumber].toString() );\r\n }else if(id === \"back\"){\r\n if(historyNumber > 0){\r\n historyNumber--;\r\n preview_toolbar.setValue(\"url\",historyArray[historyNumber].toString() );\r\n run.attachURL( historyArray[historyNumber].toString() );\r\n }\r\n }else if(id === \"clock\"){ \r\n interval = setInterval(\"run.attachURL('\"+preview_toolbar.getValue(\"url\").toString()+\"');\",preview_toolbar.getValue(\"time\")*1000);\r\n preview_toolbar.enableItem(\"stop\");\r\n preview_toolbar.disableItem(\"clock\");\r\n }else if(id === \"stop\"){\r\n clearInterval(interval);\r\n preview_toolbar.enableItem(\"clock\");\r\n preview_toolbar.disableItem(\"stop\");\r\n }\r\n });\r\n \r\n preview_toolbar.attachEvent(\"onEnter\", function(id){\r\n if(id === \"url\"){\r\n run.progressOn();\r\n historyArray.push(preview_toolbar.getValue(\"url\").toString());\r\n historyNumber++;\r\n run.attachURL(preview_toolbar.getValue(\"url\").toString());\r\n setTimeout(\"run.progressOff()\",2000);\r\n this.clearInterval(interval);\r\n }\r\n });\r\n\r\n\r\n run.attachURL(\"../src/Linker.class.php?action=run_project&project=\"+current_project+\"\");\r\n historyArray.push(\"../src/Linker.class.php?action=run_project&project=\"+current_project+\"\");\r\n setTimeout(\"run.progressOff()\",1500);\r\n}",
"onModelRunClick () {\n const dgst = (this.useBaseRun && this.isCompletedRunCurrent) ? this.runCurrent?.RunDigest || '' : ''\n const wsName = (this.useWorkset && this.isReadonlyWorksetCurrent) ? this.worksetCurrent?.Name || '' : ''\n\n if (!dgst && !this.runOpts.csvDir) {\n if (!wsName) {\n this.$q.notify({ type: 'warning', message: this.$t('Please use input scenario or base model run or CSV files to specifiy input parameters') })\n return\n }\n if (wsName && this.isPartialWorkset()) {\n this.$q.notify({ type: 'warning', message: this.$t('Input scenario should include all parameters otherwise model run may fail') + ': ' + wsName })\n return\n }\n }\n // else do run the model\n this.doModelRun()\n }",
"get horseProfile_Form_RaceDate() {return browser.element(\"//android.view.ViewGroup[3]/android.view.ViewGroup/android.view.ViewGroup/android.widget.TextView[2]\");}",
"function YDataRun_get_measureNames()\n {\n return this._measureNames;\n }",
"function getTelemRunFromForm() {\n return document.getElementById(\"telemRunForm\").value;\n}",
"onRunNameBlur (e) {\n const { isEntered, name } = Mdf.doFileNameClean(this.runOpts.runName)\n if (isEntered && name !== this.runOpts.runName) {\n this.$q.notify({ type: 'warning', message: this.$t('Run name should not contain any of') + ': ' + Mdf.invalidFileNameChars })\n }\n this.runOpts.runName = isEntered ? name : ''\n }",
"function monthly_json_to_programs_caption(data) {\n var scheduled_dur = 0;\n var recorded_dur = 0;\n var media_dur = 0;\n var live_dur = 0;\n var len = data.programs.length;\n for (var i = 0; i < len; i++) {\n var program = data.programs[i];\n\n scheduled_dur += program.scheduled_duration;\n recorded_dur += program.recorded_duration;\n media_dur += program.played_duration;\n live_dur += program.live_duration;\n }\n return \"Programmes - Recorded: \" + format_duration(recorded_dur) + \" - Watched: \" + format_duration(media_dur + live_dur) + \" (Media: \" + format_duration(media_dur) + \" / Live: \" + format_duration(live_dur) + \")\";\n }",
"get horseProfile_Form_RaceNo() {return browser.element(\"//android.view.ViewGroup[3]/android.view.ViewGroup/android.view.ViewGroup/android.widget.TextView[1]\");}",
"function YDataLogger_get_currentRunIndex()\n {\n if (this._cacheExpiration <= YAPI.GetTickCount()) {\n if (this.load(YAPI.defaultCacheValidity) != YAPI_SUCCESS) {\n return Y_CURRENTRUNINDEX_INVALID;\n }\n }\n return this._currentRunIndex;\n }",
"function runReport() {\n checkAnswers();\n calculateTestTime();\n calculateCheckedInputs();\n\n }",
"function getCommonEntryServices()\r\n{\r\n\tvar current = eval(\"record6\");\r\n\r\n\t//iterate through the data from the text file and store into an array\r\n\tfor(var i=0; i < record6.length; i++){\r\n\t\tcommonEntryServices[i] = current[i];\r\n\t}\r\n}//end getCommonEntryServices",
"function loadGui() {\n // Need a way to select which pose run to make this change to and pass this\n // parameter.\n const runId = currentId.value;\n const gui = new GUI();\n console.log(runs);\n let currentData = runs[runId].data;\n // On change of selected runId, update the given dataset to use;\n gui.add(currentId, 'value', Object.keys(runs)).onFinishChange(\n () => {\n currentData = runs[currentId.value].data; console.log(currentId);\n });\n\n gui.add(runIdToTransforms[currentId.value], 'rotate', 0, 360, 1)\n .onChange(() => {\n console.log('changed'); plotOrientation(currentId.value);\n })\n .onFinishChange(() => {\n console.log(currentId.value);\n plotTrajectory(currentId.value, currentData);\n })\n .name('Pose Rotation (degrees)');\n gui.add(runIdToTransforms[currentId.value], 'translateX', -10, 10, .025)\n .onChange(() => plotOrientation(currentId.value))\n .onFinishChange(() => plotTrajectory(currentId.value, currentData))\n .name('X Axis Translation');\n gui.add(runIdToTransforms[currentId.value], 'translateZ', -10, 10, .025)\n .onChange(() => plotOrientation(currentId.value))\n .onFinishChange(() => plotTrajectory(currentId.value, currentData))\n .name('Z Axis Translation');\n gui.add(runIdToTransforms[currentId.value], 'scale', .5, 2, .25)\n .onChange(() => plotOrientation(currentId.value))\n .onFinishChange(() => plotTrajectory(currentId.value, currentData))\n .name('Pose Scale Multiplier');\n}",
"getSiteDesignRunStatus(webUrl, runId) {\n return SiteDesignsCloneFactory(this, \"GetSiteDesignRunStatus\").run({ webUrl, runId });\n }",
"function sniffRunesFromInventory(runesFound) {\n if (!runesFound || (runesFound.hasOwnProperty('runes') && !runesFound.runes)) {\n $('#no-runes-found').show();\n return;\n }\n let runes = runesFound.runes.toString().split(',');\n runes = runes.map(rune => getRuneId(rune));\n runes.sort((a, b) => a - b);\n RunesInInventory = Array.from(runes);\n $('#hr-upgrade-log').text(`${RunesInInventory.length} runes found`);\n const countedRunes = getCounts(runes);\n if (settings['hide-hr-value'] === 'true') {\n $('#hr-data').hide();\n $('#rune-container').css({height: '+=30px'});\n }\n else {\n $('#hr-value').val(getTotalValue(countedRunes));\n }\n if (settings['hide-upgrade-log'] === 'true') {\n $('#hr-upgrade-log').hide();\n $('#rune-container').css({height: '+=114px'});\n }\n buildRuneInventoryTable($('#rune-table'), countedRunes);\n }",
"function run_getFileNameIdMap() {\n var fileNameIdMap = getFileNameIdMap();\n Logger.log(fileNameIdMap);\n}",
"function displayJobDesc(btnID, title, date, company) {\n\n $(\".job-text\").hide();\n\n document.getElementById(\"selected-job-title\").innerHTML = title;\n document.getElementById(\"date-worked\").innerHTML = date;\n document.getElementById(\"company-name\").innerHTML = company;\n document.getElementById(\"job-desc-points\").innerHTML = \"\";\n \n if (btnID == 0) {\n description = '<li>Maintenance and development of Carmenta Map Builder product and Carmenta Engine Geospatial SDK (C++)</li>';\n description += '<li>Implemented support for 3D map packaging in Map Builder</li>';\n description += '<li>API refactoring and migration handling at runtime</li>';\n description += '<li>Testing and troubleshooting on Windows, Linux and Android platforms</li>';\n description += '<li>Automated and manual test development</li>';\n description += '<li>.NET, C#, MVVM Architecture, NUnit</li>';\n description += '\\n';\n description += '<li style=\"margin-top:20px;\">MSc Thesis Project (01/2021 - 07/2021) on the topic of multi-objective optimization. Published online on <a href=\" http://hdl.handle.net/2077/69356\">GUPEA</a>.</li>';\n \n document.getElementById(\"job-desc-points\").innerHTML = description;\n }\n\n if (btnID == 1) {\n description = '<li>Recommend opportunities for test automation using SQL and Batch scripts to improve workflows</li>';\n description += '<li>Provide QA services across DOMO and GIS systems verifying alignment in data and accuracy</li>';\n description += '<li>Remote work environment using agile development methodologies (JIRA and Kanban)</li>';\n description += '<li>Develop document templates for test plans and set standards for QA testing</li>';\n description += '<li>Ensure top quality address level data for the Broadband Networks team</li>';\n description += '<li>QA network and address data to ensure they are enabled correctly in internal systems</li>';\n description += '<li>Coordinate with peers and key business stakeholders to problem solve solutions</li>';\n document.getElementById(\"job-desc-points\").innerHTML = description;\n }\n\n if (btnID == 2) {\n description = '<li>Design and develop mobile applications for iOS and Android platforms from start to finish</li>';\n description += '<li>Development using Unity, Vuforia, Google Tango and C# for augmented reality applications</li>';\n description += '<li>3D modelling and visualization using TinkerCAD and Meshlab</li>';\n description += '<li>Professional consultations with clients to ensure that applications fully meet project requirements</li>';\n document.getElementById(\"job-desc-points\").innerHTML = description;\n }\n\n if (btnID == 3) {\n description = '<li>Set up, program and calibrate dataloggers and meteorological instrumentation</li>';\n description += '<li>Develop web-based GIS app using ArcGIS Online</li>';\n description += '<li>Create province-wide nitrous oxide GIS model using georeferenced crop and soils data</li>';\n description += '<li>Modify MATLAB functions and run statistical analysis</li>';\n description += '<li>Assist in field experiments using lysimeters and micrometeorological methods</li>';\n document.getElementById(\"job-desc-points\").innerHTML = description;\n }\n\n if (btnID == 4) {\n description = '<li>Use ArcGIS to display georeferenced Water and Wastewater datasets and perform spatial queries and analysis</li>';\n description += '<li>Use Python, VBA, and ArcPy to update the GIS with accurate watermain capital planning data</li>';\n description += '<li>Calculate asset replacement costs, remaining life of assets, and perform risk analysis</li>';\n description += '<li>Input, organize, and analyze data from site visits using asset management software created by the Region</li>';\n description += '<li>Involved in the development of Condition Assessment protocols within the Region\\'s asset management group</li>';\n description += '<li>Nominated for the 2015 Co-op Student of the Year award for my work ethic and productivity</li>';\n document.getElementById(\"job-desc-points\").innerHTML = description;\n }\n\n if (btnID == 5) {\n description = '<li>Review Site Plan and Rezoning applications and provide environmental conditions of approval</li>';\n description += '<li>Review and evaluate Environmental Site Assessments (Phase I and II), Site Remediation reports and Geotechnical reports and provide input to Municipal Servicing Agreements</li>';\n description += '<li>Conduct professional site visits to monitor spills and to enforce the Storm Sewer Use By-law</li>';\n description += '<li>Represent the Environmental Services Section at numerous public outreach events to educate citizens about stormwater and water quality</li>';\n document.getElementById(\"job-desc-points\").innerHTML = description;\n }\n $(\".job-text\").fadeIn(\"slow\");\n }",
"function initRuns(data) {\n for(let i = 0; i < data.length; i++) {\n createRun(data[i]);\n }\n}",
"function get_daily_data() {\n //erase previous data in the table and make the first row with the legend\n var table = document.getElementById(\"output_table\");\n reset_table(table);\n\n //get all the data elemtents from the different files\n var cases = casesXML.getElementsByTagName('data');\n var testing = testingXML.getElementsByTagName('data');\n var hospital = hospitalXML.getElementsByTagName('data');\n\n //add code here to handle the extra data from the casesXML file\n\n\n //create a new row and insert the appropriate data into it\n for (i=0; i+3<cases.length; i++) {\n var row = table.insertRow(-1);\n var date_col = row.insertCell(0);\n date_col.innerHTML = cases[i+3].getElementsByTagName('date').item(0).innerHTML;\n var cases_col = row.insertCell(1);\n cases_col.innerHTML = cases[i+3].getElementsByTagName('newCasesByPublishDate').item(0).innerHTML;\n var tests_done_col = row.insertCell(2);\n tests_done_col.innerHTML = testing[i] != undefined ? testing[i].getElementsByTagName('newPCRTestsByPublishDate').item(0).innerHTML : \"\";\n var tests_planned_col = row.insertCell(3);\n tests_planned_col.innerHTML = testing[i] != undefined ? testing[i].getElementsByTagName('plannedPCRCapacityByPublishDate').item(0).innerHTML : \"\";\n var patients_in_hospital_col = row.insertCell(4);\n patients_in_hospital_col.innerHTML = hospital[i] != undefined ? hospital[i].getElementsByTagName('hospitalCases').item(0).innerHTML : \"\";\n }\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
API not exist (404) | function not_found_handler(req, res, next) {
res.status(404);
res.json({
message: 'api not exist or wrong HTTP method'
})
} | [
"function fileNotFound(req, h){\n const response = req.response\n //Preguntamos que si la response es un mensaje de boom y si el codigo es 404\n if (!req.path.startsWith('/api') && response.isBoom && response.output.statusCode === 404) {\n //Retornamos la vista de la pagina que muestra el error 404 de una forma visual mas agradable\n return h.view('404', {}, {\n layout: 'errLayout'\n }) .code(404)\n }\n\n return h.continue\n}",
"function handleNotFoundRequest(param) {\r\n const code = 404;\r\n const response = new Problem_1.Problem(code, \"/probs/resource-not-found\", \"Resource not found\", `Resource with id ${param} could not be found`);\r\n Logger_1.logger.info(JSON.stringify(response));\r\n return response;\r\n }",
"indexAction(req, res) {\n this.jsonResponse(res, 200, { 'message': 'Default API route!' });\n }",
"function API_Endpoint_Ok(url){\n // ignore the query string, it will be handled by the targeted controller\n let queryStringMarkerPos = url.indexOf('?');\n if (queryStringMarkerPos > -1)\n url = url.substr(0, queryStringMarkerPos);\n // by convention api endpoint start with /api/...\n if (url.indexOf('/api/') > -1) {\n // extract url componants, array from req.url.split(\"/\") should \n // look like ['','api','{resource name}','{id}]'\n let urlParts = url.split(\"/\");\n // do we have a resource name?\n if (urlParts.length > 2) {\n // by convention controller name -> NameController\n controllerName = capitalizeFirstLetter(urlParts[2]) + 'Controller';\n // do we have an id?\n if (urlParts.length > 3){\n if (urlParts[3] !== '') {\n id = parseInt(urlParts[3]);\n if (isNaN(id)) { \n response.badRequest();\n // bad id\n return false;\n } else\n // we have a valid id\n return true;\n\n } else\n // it is ok to have no id\n return true;\n } else\n // it is ok to have no id\n return true;\n }\n }\n // bad API endpoint\n return false;\n }",
"function testResouceNotFound(){\n var content = \"test\";\n var options = {\n path: '/check/blablablabla',\n method: 'GET',\n headers: {\n 'Content-Length': content.length\n }\n };\n testResponse(options,content, function(res) {\n console.log('not found test callback');\n console.log(res.statusCode);\n assert(res.statusCode == 404);\n console.log(\"Resource not found - test succeeded\");\n });\n}",
"function showError(path, method) {\n console.log('API failed: ' + method + ' : ' + path);\n }",
"function apiDoc(req, res) { \n //console.log('GET /api');\n res.json({\n message: 'Welcome to the stashy sheep breed list!',\n documentation_url: 'https://github.com/SpindleMonkey/project-2/api.md',\n base_url: 'http://localhost:3000',\n notes: 'If you search for a breed with more than one word in it\\'s name, use \\'%20\\' for the space between words. If you\\'re updating the infoSources field, use \\', \\' to separage multiple sources.',\n endpoints: [\n {method: 'GET', path: '/api', description: 'Describes available endpoints'},\n {method: 'GET', path: '/api/breed', description: 'Lists all sheep breeds'},\n {method: 'GET', path: '/api/breed/:name', description: 'Lists info for a single breed'},\n {method: 'GET', path: '/api/breed/all', description: 'Lists all info for all breeds'},\n {method: 'POST', path: '/api/breed', description: 'Add a new sheep breed'},\n {method: 'PUT', path: 'api/breed/:name', description: 'Update one of the breeds in the db'},\n {method: 'DELETE', path: '/api/breed/:name', description: 'Delete a sheep breed by name'}\n ]\n });\n}",
"function isApi(node) {\n\t return node.kind() == \"Api\" && node.RAMLVersion() == \"RAML08\";\n\t}",
"async getPartage(id){\n try{\n const partage = Object.assign(new Partage(), await this.partageApi.get(id));\n return partage;\n }\n catch (e) {\n if (e === 404) return null;\n if (e === 403) return 403;\n return undefined;\n }\n }",
"static async apiGetPostits(req, res, next) {\n try {\n const postits = await PostitsDAO.getPostits();\n res.json(postits);\n } catch (e) {\n console.log(`api, ${e}`);\n }\n }",
"indexAction(req, res) {\n Robot.find((err, robots) => {\n if (err)\n this.jsonResponse(res, 400, { 'error': err });\n\n this.jsonResponse(res, 200, { 'robots': robots });\n });\n }",
"getApi(){\n if (!this.props.api){\n return {};\n }\n return this.props.api;\n }",
"function NotFoundError(name) {\n Error.call(this);\n Error.captureStackTrace(this, arguments.callee);\n this.name = 'Middleware Not Found Error';\n this.message = name + ' not found in the current stack';\n}",
"function checkTitleExists(req, res, next) {\n if (!req.body.title) {\n return res.status(400).json({\n error: \"Params TITLE is required\"\n });\n }\n\n return next();\n}",
"async function load(req, res, next, id) {\n try {\n const soccerPlace = await queries.loadSoccerPlaceFromId(id)\n if(!soccerPlace) throw new Error({error: \"soccerplace not found\"})\n req.soccerPlace = soccerPlace\n next()\n } catch(e) {\n res.status(404)\n return res.json({ \"error\": \"Not found\" })\n }\n}",
"async getSnowboardByID(req, res) {\n console.log(\"getSnowboardByID()\")\n\n snowboardID = req.params.id\n\n const docs = await Snowboard.find({ id: snowboardID })\n\n if (docs) res.json(docs)\n else res.status(404).send(\"not found\")\n }",
"function build404(data) {\n var name = data.message.replace(\"Channel '\", \"\").replace(\"' does not exist\", \"\").capitalize();\n var icon = \"<div class='status-icon text-right'><i class='fa fa-times-circle fa-lg'> Error</i></div>\";\n var message = \"<p>\" + data.message + \"</p>\";\n var mainLi = \"<li class='error text-left offline'><span class='name-display'>\" + name + \"</span></a>\" + icon + message + \"</li>\";\n \n $(\"#main-list\").append(mainLi);\n }",
"createApi(apiData, cb) {\n this.request('POST', '/api/apis', apiData, cb)\n }",
"function getEndpoint(path) {\r\n\tvar script = document.createElement('script');\r\n\r\n\tscript.type = \"text/javascript\";\r\n\tscript.src = \"https://ign-apis.herokuapp.com\" + path;\r\n\r\n\tdocument.body.appendChild(script);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the playlist from uri in to list view | function loadPlaylistUri(uri)
{
if( ( uri != undefined || !uri ) && ( uri.split(":")[3] == "playlist" ) )
{
console.log("Appending " + uri );
$('#playlist-drop').hide();
$('#player-content').fadeIn();
thisPlaylist = models.Playlist.fromURI(uri);
var playlistArt = new views.Player();
playlistArt.track = thisPlaylist.get(0);
playlistArt.context = thisPlaylist;
$("#playlistDiv").append(playlistArt.node);
$("#playlistDiv").append("<h1>" + thisPlaylist.name + "</h1>");
var playlistList = new views.List(thisPlaylist);
playlistList.node.classList.add("temporary");
playlistList.node.id = "currPlaylist";
$("#playlistDiv").append(playlistList.node);
initialize();
}
else
console.log("Fail to append " + uri );
} | [
"async loadPlaylists(url) {\n\t\tlet response = await utils.apiCall(url, this.props.access_token);\n\t\tthis.setState({ playlists: response.items, nplaylists: response.total, nextURL: response.next,\n\t\t\tprevURL: response.previous });\n\n\t\tplaylists.style.display = 'block';\n\t\tsubtitle.textContent = (response.offset + 1) + '-' + (response.offset + response.items.length) +\n\t\t\t' of ' + response.total + ' playlists\\n';\n\t}",
"function getPlaylist(callback){\n if(playlists.length == 0){\n loadPlaylists(callback);\n }\n else{\n callback(playlists);\n }\n}",
"function pollPlaylist()\n{\n\tvar xhttp = new XMLHttpRequest();\n\txhttp.onreadystatechange = function()\n\t{\n\t\tif ((this.readyState === 4) && (this.status === 200))\n\t\t{\n\t\t\tvar resp\n\t\t\ttry\n\t\t\t{\n\t\t\t\tresp = JSON.parse(this.responseText);\n\t\t\t}\n\t\t\tcatch (err)\n\t\t\t{\n\t\t\t\tconsole.log(\"Parsing failed: \", err);\n\t\t\t}\n\t\t\t// console.log(\"Received response: \", resp);\n\t\t\tif (resp instanceof Array)\n\t\t\t{\n\t\t\t\tresp.forEach(addSong);\n\t\t\t}\n\t\t}\n\t};\n\txhttp.open(\"POST\", \"api/playlist\", true);\n\txhttp.setRequestHeader(\"x-SkauTan-playlist-start\", g_MaxSongIndex * 1 + 1);\n\txhttp.send();\n}",
"function get_playlist_and_play() {\n var hash = location.hash.substring( location.hash.indexOf('#')+1 );\n get_playlist( hash ? hash : 'hot' );\n}",
"function getPlaylistSongs(playlist_id){\n let currentPlaylist = getPlaylistById(playlist_id);\n let url = currentPlaylist.link + \"/tracks\";\n\n ajaxCall(url, null, function(response){populatePlaylist(response, currentPlaylist);});\n}",
"function loadPlayList(entries){\n\tupdateControls(entries.length);\n\tfillVideoList(entries, \"#playlist-list\", function(event) {\n\t\tvar data = $.toJSON(event.data.video);\n\t\tvar playBtn = {\n\t\t\tclick: function () {\n\t\t\t\tvar url = server + \"/control/play\";\n\t\t\t\t$.post(url, data, loadPlayList, \"json\");\n\t\t\t},\n\t\t\tclose: true\n\t\t};\n\t\tvar playNextBtn = {\n\t\t\tclick: function () {\n\t\t\t\tvar url = server + \"/control/playNext\";\n\t\t\t\t$.post(url, data, loadPlayList, \"json\");\n\t\t\t},\n\t\t\tclose: true\n\t\t};\n\t\tvar deleteBtn = {\n\t\t\tclick: function () {\n\t\t\t\tvar url = server + \"/playlist\";\n\t\t\t\t$.ajax({url: url, type: 'DELETE', data: data, dataType: 'json', success: loadPlayList});\n\t\t\t},\n\t\t\tclose: true\n\t\t};\n\t\tvar buttons = { 'Play': playBtn, 'Play Next': playNextBtn, 'Skip': deleteBtn };\n\t\tfor(operationKey in event.data.video.operations){\n\t\t\tvar operation = event.data.video.operations[operationKey];\n\t\t\tvar type = event.data.video.type;\n\t\t\tvar buttonClick = function(e, type, operation, data){\n\t\t\t\tvar successFunction = function(){\n\t\t\t\t\tshowNotification(operation.successMessage);\n\t\t\t\t}\n\t\t\t\tvar url = server + \"/\" + type + \"-\" + operation.name;\n\t\t\t\t$.post(url, data).done(successFunction, \"json\");\n\t\t\t}\n\t\t\tbuttons[operation.text] = {\n\t\t\t\tclick: buttonClick,\n\t\t\t\targs: new Array(type, operation, data),\n\t\t\t\tclose: true\n\t\t\t};\n\t\t}\n\t\t$(document).simpledialog2({\n\t\t\tmode: 'button',\n\t\t\theaderText: event.data.video.title,\n\t\t\theaderClose: true,\n\t\t\tbuttons : buttons\n\t\t});\n\t});\n}",
"load(data) {\n var _a;\n const { playlistId, title, thumbnail, shortBylineText, videoCount, videoCountShortText, } = data;\n this.id = playlistId;\n this.title = title.simpleText || title.runs[0].text;\n this.videoCount = common_1.stripToInt(videoCount || videoCountShortText.simpleText) || 0;\n // Thumbnail\n this.thumbnails = new _1.Thumbnails().load(((_a = data.thumbnails) === null || _a === void 0 ? void 0 : _a[0].thumbnails) || thumbnail.thumbnails);\n // Channel\n if (shortBylineText && shortBylineText.simpleText !== \"YouTube\") {\n const shortByLine = shortBylineText.runs[0];\n this.channel = new _1.ChannelCompact({\n id: shortByLine.navigationEndpoint.browseEndpoint.browseId,\n name: shortByLine.text,\n client: this.client,\n });\n }\n return this;\n }",
"function getPlaylists() {\n return axios.get(endpoints.playlist)\n}",
"function renderPlaylist(playlist){\n\tvar playlistHTML =\n\t\"<section class='playlist-bubbles'>\"+\n\t\"<div class='ball bubble' data-playlist-id='\" + playlist._id + \"' data-playlist-url='\" + playlist.playlistURL + \"'>\" +\n\t\"\t\t<div class='playlist-body'>\" +\n\t\"\t\t\t<div class='col-md-1'>\" +\n\t\"\t\t\t\t<h4 class='playlist-name'>\" + playlist.playlistName + \"</h4>\" +\n\t\"\t\t\t</div>\" +\n\t\"\t\t</div> \" +\n\t\"<button id='edit' class='btn edit-playlist data-playlist-id='\" + playlist._id + \"'>EDIT</button>\"+\n\t\"<button id='delete' class='btn delete-playlist data-playlist-id='\" + playlist._id + \"'>POP</button>\"+\n\t\"</div>\"+\n\t\"</section>\";\n\n\t$('#playlists').append(playlistHTML);\n\t// console.log($('.bubble'));\n\t$('.bubble').last().on('click', function playlistFind(e){\n\t\te.preventDefault();\n\t\tvar url = $(this).data(\"playlist-url\");\n\t\t// console.log(url);\n\t\t// console.log('test5');\n\t\tSC.Widget('test').load(url);\n\t});\n\n}",
"function Playlist(doc, program)\n{\n\tthis.doc = doc;\n\tthis.program = program;\n\tthis.index = 0;\n\tthis.fullScreenActive = false;\n\tthis.startDelay = 10;\n\tthis.smart_params = [];\t\t\t\t\t// Array of SmartParams objects created for that playlist from elements \"time\". It is empty for non-smart playlist.\n\tthis.smart_target_playlist = null;\t\t// Playlist which has to be replaced by this smart playlist during its playing.\n\tthis.smart_play_count = 0;\t\t\t\t// Remaining cont to play cycles of the smart playlist. 0 means don't stop playlist by play_count.\n\tthis.smart_stopped = false;\t\t\t\t// true if playlist is stopped by smart playlist or if it is stopped smart playlist\n\n\tvar self = this;\n\tthis.callStart = function() { self.start(); };\n\tthis.callLocalPlayListTimeout = function() { self.localPlayListTimeout(); };\n\n\tthis.localContent = new LocalContentList(this);\n\n\tvar node = doc.attributes.getNamedItem(\"name\");\n\t// if no name attribute then it can be smart play list\n\tif (!node) {\n\t\t// parent should me \"smart\"\n\t\tvar parent = doc.parentNode;\n\t\tif (parent.tagName == \"smart\") {\n\t\t\t// it must contain name in the attribute \"playlist\"\n\t\t\tvar playListName = parent.attributes.getNamedItem(\"playlist\");\n\t\t\tif (playListName) {\n\t\t\t\t// go through each \"time\" element and create SmartParams object\n\t\t\t\tvar timeElements = parent.getElementsByTagName(\"time\");\n\t\t\t\tfor (i = 0; i < timeElements.length; i++) {\n\t\t\t\t\tvar smartParamsItem = new SmartParams(timeElements[i]);\n\t\t\t\t\t// If something wrong in attributes of the element \"time\" then ignore that playlist\n\t\t\t\t\tif (smartParamsItem.start < 0)\n\t\t\t\t\t\treturn;\n\t\t\t\t\t// Otherwise remember that object.\n\t\t\t\t\tif (smartParamsItem.start >= 0)\n\t\t\t\t\t\tthis.smart_params.push(smartParamsItem);\n\t\t\t\t}\n\t\t\t\t//// if that smart playlist has at least one \"time\" element then proceed with that name\n\t\t\t\t//if (this.smart_params.length > 0)\n\t\t\t\t\tnode = playListName;\n\t\t\t}\n\t\t}\n\t}\n\tif (!node) {\n\t\treturn;\n\t}\n\n\t// if it is not smart playlist or it is smart playlist without \"time\" elements\n\tif (this.smart_params.length == 0) {\n\t\t// if any already parsed playlist targeted to the same div then ignore that playlist\n\t\tvar j;\n\t\tfor (j = 0; j < program.playlists.length; j++) {\n\t\t\tif (node.nodeValue === program.playlists[j].name)\n\t\t\t\treturn;\n\t\t}\n\t}\n\tthis.name = node.nodeValue;\n\tthis.contentList = [];\n\tthis.div0 = GetPlayListDiv(this.name);\n\tif (!this.div0) {\n\t\treturn;\n\t}\n\t// don't create containers for smart playlist. We will use them from the replacing normal playlist\n\tif (this.smart_params.length == 0) {\n\t\tthis.div0.innerHTML = \"\";\n\n\t\tthis.containerA = new Container;\n\t\tthis.div0.appendChild(this.containerA.div);\n\t\tthis.containerB = new Container;\n\t\tthis.div0.appendChild(this.containerB.div);\n\t} else {\n\t\tthis.containerA = null;\n\t\tthis.containerB = null;\n\t}\n\tthis.currentContainer = this.containerA;\n\tthis.lastContainer = this.containerB;\n\n\ttry {\n\t\tif (signageBrowserInfo.webKitVersionNumber > 0.0) {\n\t\t\tthis.transition = new Transitions(this.div0, this);\n\t\t} else {\n\t\t\tthrow \"Transitions not supported by browser\";\n\t\t}\n\t} catch (err) {\n\t\tdebug(err);\n\t\tthis.transition = new DefaultNullTransitions(this.div0, this);\n\t}\n\n\tvar now = new Date();\n\tvar m;\n\tvar re = /(\\d\\d\\d\\d)-(\\d+)-(\\d+)/;\n\tvar placeHolderCount = 0;\n\tvar contentDocs = doc.childNodes;\n\tfor (var i = 0; i < contentDocs.length; i++) {\n\t\tif (contentDocs[i].nodeType == 1) {\n\t\t\t// honor expire and start dates if present\n\t\t\tif (contentDocs[i].attributes.getNamedItem('expire')) {\n\t\t\t\tm = re.exec(contentDocs[i].attributes.getNamedItem('expire').nodeValue);\n\t\t\t\tif (m) {\n\t\t\t\t\tvar expire = new Date(m[1], m[2] - 1, m[3], 23, 59, 59);\n\t\t\t\t\tif (now > expire) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (contentDocs[i].attributes.getNamedItem('start')) {\n\t\t\t\tm = re.exec(contentDocs[i].attributes.getNamedItem('start').nodeValue);\n\t\t\t\tif (m) {\n\t\t\t\t\tvar start = new Date(m[1], m[2] - 1, m[3], 0, 0, 0);\n\t\t\t\t\tif (now < start) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar content = null;\n\t\t\tswitch (contentDocs[i].tagName) {\n\t\t\t\tcase \"video\":\n\t\t\t\t\tif (signageBrowserInfo.useVLC) {\n\t\t\t\t\t\tcontent = new VideoVLC(contentDocs[i], this);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcontent = new Video(contentDocs[i], this);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"still\":\n\t\t\t\t\tcontent = new Still(contentDocs[i], this);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"flash\":\n\t\t\t\t\tcontent = new Flash(contentDocs[i], this);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"html\":\n\t\t\t\t\tcontent = new HtmlPage(contentDocs[i], this);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"stream\":\n\t\t\t\t\tcontent = new VideoVLC(contentDocs[i], this);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"audio\":\n\t\t\t\t\tcontent = new Audio(contentDocs[i], this);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"placeholder\":\n\t\t\t\tcase \"localcontent\":\n\t\t\t\t\tcontent = new PlaceHolder(contentDocs[i], this);\n\t\t\t\t\tplaceHolderCount += 1;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthis.errorLog(\"Unknown content type: \" + contentDocs[i].tagName);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (content) {\n\t\t\t\tvar reTrue = /true|yes|on|1/i;\n\t\t\t\tcontent.fullScreenFlag = reTrue.test(getAttribute(contentDocs[i], 'fullscreen', \"false\"));\n\t\t\t\tthis.contentList.push(content);\n\t\t\t}\n\t\t}\n\t}\n\tif (this.contentList.length <= 0) {\n\t\tthis.errorLog(\"ERROR: empty playlist\");\n\t}\n\tif (placeHolderCount) {\n\t\tthis.localContent.readList();\n\t}\n}",
"function FetchAndSetPlaylistDetails(accessToken, context) {\n\n function getAllTracksForPlaylists(playlistJson) {\n let playlists = playlistJson.items;\n let trackDataPromises = playlists.map(playlist =>\n getHrefJsonPromise(accessToken, playlist.tracks.href)\n );\n let allTracksListsPromises = Promise.all(trackDataPromises);\n let playlistsPromise = allTracksListsPromises\n .then(tracksLists => {\n tracksLists.forEach((trackList, i) => {\n playlists[i].trackList =\n trackList.items.map(item => item.track);\n });\n return playlists;\n });\n return playlistsPromise;\n }\n\n function setStateData(playlistsPromise) {\n playlistsPromise.then(playlists => context.setState({\n // Populate playlist state data\n playlists: playlists.map(item => {\n return {\n name: item.name,\n id: item.id,\n imageUrl: item.images[0].url,\n songs: item.trackList.map(track => ({\n name: track.name,\n duration: track.duration_ms,\n }))\n };\n })\n }));\n }\n\n let jsonPromise = getHrefJsonPromise(accessToken,\n \"https://api.spotify.com/v1/me/playlists\");\n jsonPromise.then(dat => {\n if (dat.error)\n context.setState({error: true});\n else {\n let playlistData = getAllTracksForPlaylists(dat);\n setStateData(playlistData);\n }\n });\n}",
"function handlePlaylistRequest() {\n\t// if the actual playlist is null, there is no playlist sent during this session but it still can be one in the memory\n\tif(actPlaylist == null) {\n\t\t// is there a list in the memory?\n\t\tlist = createPlaylistFromMemory();\n\t\t\n\t\tif(list == null) {\n\t\t\t// no actual playlist is available\n\t\t\talert(\"no actual playlist available\");\n\t\t\tsendMessageToDevice(\"PLI NULL\");\n\t\t}\n\t\telse {\n\t\t\talert(\"created playlist from memory\");\n\t\t\tactPlaylist = list;\n\t\t\t\n\t\t\t// send actual playlist to device\n\t\t\tsendMessageToDevice(actPlaylist.getMessageFormat());\n\t\t}\n\t}\n\telse {\n\t\t// send actual playlist to device\n\t\tsendMessageToDevice(actPlaylist.getMessageFormat());\n\t}\n}",
"function update_playlists(pls) {\n if (playlist_cb) {\n playlist_cb(pls);\n }\n}",
"function updatePlaylist(playlist) {\n _mostRecentPlaylist = playlist;\n $('#playlistqueue').empty();\n Promise.all(retrieveAllVideoTitles()).\n then(function(jsonResponseArray) {\n for (var i = 0; i < playlist.length; i += 1) {\n var title = jsonResponseArray[i].items[0].snippet.title;\n var videoID = playlist[i].video_id;\n var entryID = playlist[i].id;\n updatePlaylistDisplay(videoID, entryID, title);\n }\n });\n}",
"function createPlaylistFromMemory() {\n\tlist = openFileAndParseXML(\"videoList.xml\");\n\talert(list);\n\n\tvar items = list.getElementsByTagName(\"item\");\n\t\n\tif(items == null) {\n\t\treturn null;\n\t}\n\t\n\t//tja+mich+CLIP+ZIB+20+DURATION+00:06:38.942\n\t//+ENTRY++TITLE+1:+Signation+URL+2012-09-26_200_tl01_ZIB-20_Signation__47674401__o\n\t//+ENTRY++TITLE+2:+Zeugenschwund+beim+U-Ausschuss+URL+2012-09-26_2000\n\t//+CLIP+ZIB+20+DURATION+00:06:38.942\n\t//+ENTRY++TITLE+1:+Signation+URL+2012-09-26_200_tl01_ZIB-20_Signation__47674401__o\n\t//+ENTRY++TITLE+2:+Zeugenschwund+beim+U-Ausschuss+URL+2012-09-26_2000\n\tvar playlistString = \"playlistFromMemory\";\n\t\t\n var videoNames = [ ];\n var videoURLs = [ ];\n var videoDurations = [ ];\n var entryTitles = [[],[]];\n\tvar entryURLs = [[],[]];\n for (var index = 0; index < items.length; index++)\n {\n var titleElement = items[index].getElementsByTagName(\"title\")[0].firstChild.data;\n var durationElement = items[index].getElementsByTagName(\"duration\")[0].firstChild.data;\n\t\tvar entries = items[index].getElementsByTagName('entry');\n\t\t\n\t\tplaylistString += \" CLIP \" + titleElement + \" DURATION \" + durationElement;\n\t\t\t\t\n\t\tvar entryTitleElement = [ ];\n\t\tvar entryURLElement = [ ]\n\t\tfor (var j = 0; j < entries.length; j++)\n\t\t{\n\t\t\tentryTitleElement[j] = entries[j].getElementsByTagName(\"title\")[0].firstChild.data;\n\t\t\tif(j == 0)\tvar linkElement = entries[j].getElementsByTagName(\"link\")[0];\n\t\t\t\tentryURLElement[j] = entries[j].getElementsByTagName(\"link\")[0].firstChild.data;\t\n\t\t\t\t\n\t\t\tplaylistString += \" ENTRY \" + entryTitleElement[j] + \" URL \" + entryURLElement[j];\n\t\t}\n\t }\n\t \n\t alert(playlistString);\n\t \n\t tmp_pli = new Playlist(playlistString);\n\t return tmp_pli;\n}",
"function initYouTubeList(){\r\n var tabUrl = window.location.href;\r\n var youTubeListId = getURLParameter(tabUrl, 'list');\r\n if (youTubeListId && youTubeListId != playlistId){\r\n playlistId = youTubeListId;\r\n extractVideosFromYouTubePlaylist(youTubeListId);\r\n }\r\n}",
"function addSongsToPlaylist (songs, playlistName, updateViewing, addToEnd) {\n var songIds = $.map(songs, function (song, i) { return { fileid: song.fileId() }; }),\n targetPos = 0;\n\n // if we're snagging, add to bottom (curretly assumes we add to active list)\n if (addToEnd) {\n targetPos = addToEnd;\n }\n\n return self.eventBus.request(\n tms.events.tt.playlist.add,\n {\n api: \"playlist.add\",\n playlist_name: playlistName,\n index: targetPos,\n song_dict: songIds\n },\n tms.events.ext.playlist.add\n )\n .done(function (data) {\n if (updateViewing) {\n var songList = self.songList(); \n self.songList([\"paused\"]);\n\n $.each(songs, function (i, song) {\n // if its a currentSongViewModel we need to convert\n if (song.upvotes) {\n var songModel = song.model.metadata.current_song;\n song = new tms.viewmodels.SongViewModel(songModel);\n } \n\n songList.push(song);\n });\n\n self.songList(songList);\n }\n\n // if the song is playing, mark the playlist\n $.each(songs, function (i, song) {\n if (song.fileId() === self.currentSong().fileId()) {\n $.each(self.playlists(), function (i, playlist) {\n if (playlist.name() === playlistName) {\n playlist.activeSongInList(true);\n return;\n }\n });\n }\n });\n\n // if we added to a non-active list, we need to reset active\n if (self.activePlaylist().name() !== playlistName) {\n self.resetActiveList();\n }\n });\n }",
"async function onLinkClicked(event) {\r\n let playlistURI;\r\n let trackURI;\r\n let target = event.target;\r\n // Trace backward to element having embeded URIs\r\n while (!playlistURI && target !== document.body) {\r\n playlistURI = target.href;\r\n trackURI = target.dataset.uri;\r\n target = target.parentNode;\r\n }\r\n\r\n if (!playlistURI || !trackURI) return;\r\n\r\n const uriObj = URI.from(playlistURI);\r\n if (!uriObj) return;\r\n\r\n const isChart = \"application\" === uriObj.type && \"chart\" === uriObj.id;\r\n if (\r\n uriObj.type === URI.Type.COLLECTION ||\r\n URI.isPlaylistV1OrV2(uriObj) ||\r\n isChart\r\n ) {\r\n let requestURI = `sp://core-playlist/v1/playlist/${playlistURI}/rows`\r\n \r\n if (!(await getPrefsValue(\"ui.show_unplayable_tracks\"))) {\r\n requestURI += \"?filter=playable%20eq%20true\"\r\n }\r\n\r\n // Search clicked track index in playlist then send message to Playlist app\r\n // to navigate to track's position.\r\n CosmosAPI.resolver.get(\r\n { url: requestURI, body: { policy: { link: true } } },\r\n (err, raw) => {\r\n if (err) return;\r\n var list = raw.getJSONBody();\r\n const index = list.rows.findIndex(item => item.link === trackURI);\r\n if (index === -1) return;\r\n ensureMessage(\"highlight-context-index\", { uri: playlistURI, index });\r\n }\r\n );\r\n return;\r\n }\r\n return;\r\n }",
"async getPlaylistBySlug(req, res, next) {\n try {\n const { playlistSlug } = req.params;\n const playlists = await playlistsModel.findOne({ slug: playlistSlug });\n res.status(200).json({ playlists });\n } catch (error) {\n next(error);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Xpath for Career 1st up | get horseProfile_Career_1stUp() {return browser.element("//android.view.ViewGroup[11]/android.view.ViewGroup/android.view.ViewGroup[9]/android.widget.TextView[1]");} | [
"get horseProfile_Career_3rdUp() {return browser.element(\"//android.view.ViewGroup[11]/android.view.ViewGroup/android.view.ViewGroup[11]/android.widget.TextView[1]\");}",
"get horseProfile_Career_2ndUp() {return browser.element(\"//android.view.ViewGroup[11]/android.view.ViewGroup/android.view.ViewGroup[10]/android.widget.TextView[1]\");}",
"get horseProfile_Career_Good() {return browser.element(\"//android.view.ViewGroup[11]/android.view.ViewGroup/android.view.ViewGroup[6]/android.widget.TextView[1]\");}",
"get horseProfile_Career_Heavy() {return browser.element(\"//android.view.ViewGroup[11]/android.view.ViewGroup/android.view.ViewGroup[8]/android.widget.TextView[1]\");}",
"get horseProfile_Career_Jumps() {return browser.element(\"//android.view.ViewGroup[11]/android.view.ViewGroup/android.view.ViewGroup[3]/android.widget.TextView[1]\");}",
"get horseProfile_Career_ThisSeason() {return browser.element(\"//android.view.ViewGroup[11]/android.view.ViewGroup/android.view.ViewGroup[1]/android.widget.TextView[1]\");}",
"get horseProfile_Career_Synth() {return browser.element(\"//android.view.ViewGroup[11]/android.view.ViewGroup/android.view.ViewGroup[4]/android.widget.TextView[1]\");}",
"async waitAndClickXpath(Selector) {\n\t\tawait page.waitForXPath(Selector);\n\t\tawait page.click(Selector);\n\t}",
"get horseProfile_Form_Condition() {return browser.element(\"//android.view.ViewGroup[3]/android.view.ViewGroup/android.view.ViewGroup[2]/android.view.ViewGroup[3]/android.widget.TextView[1]\");}",
"get horseProfile_Career_GRPListed() {return browser.element(\"//android.view.ViewGroup[11]/android.view.ViewGroup/android.view.ViewGroup[2]/android.widget.TextView[1]\");}",
"get horseProfile_Overview_TrainerName() {return browser.element(\"//android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup/android.widget.TextView[3]\");}",
"get horseProfile_Form_RaceNo() {return browser.element(\"//android.view.ViewGroup[3]/android.view.ViewGroup/android.view.ViewGroup/android.widget.TextView[1]\");}",
"function xpath(query)\n {\n var ret = new Array();\n var snap = document.evaluate(query, document, null,\n XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);\n if( snap.snapshotLength > 0){\n for (i=0; i< snap.snapshotLength; i++){\n ret[i] = snap.snapshotItem(i);\n }\n return ret;\n }\n return null;\n }",
"get horseProfile_Form_RaceDate() {return browser.element(\"//android.view.ViewGroup[3]/android.view.ViewGroup/android.view.ViewGroup/android.widget.TextView[2]\");}",
"get txnTypesRows() {\r\n return ('//div[@class=\"TransactionRow\"]//div[@class=\"cell\"][1]')\r\n }",
"clickSellOnTakealot() {\n return this\n .waitForElementVisible('@sellOnTakealot')\n .assert.visible('@sellOnTakealot')\n .click('@sellOnTakealot');\n }",
"get horseProfile_Overview_HorseName() {return browser.element(\"//android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup/android.widget.TextView[1]\");}",
"get lowestPricedItem1() {return $('#inventory_container > div > div:nth-child(6) > div.pricebar > button');}",
"selectDessert2() {\n I.waitForElement(foodObjects.hersheysCookie);\n I.tap(foodObjects.hersheysCookie);\n I.waitForElementLeaveDom(settings.config.helpers.Appium.platform, commonObjects.progressBar);\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.