query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
init wires up watchers on selections and fetches new data | function init(){
var countrySel = $('#sel-country');
var categorySel = $('#sel-category');
var genderSel = $('#sel-gender');
function updateSelections() {
var params = window.winners.params || {};
params.country = countrySel.val();
params.category = categorySel.val();
params.gender = genderSel.val();
fetchData();
}
countrySel.on('change', updateSelections);
categorySel.on('change', updateSelections);
genderSel.on('change', updateSelections);
updateSelections();
setupMapData();
} | [
"function init() {\n\n // reset any previous data\n displayReset();\n\n // read in samples from JSON file\n d3.json(\"data/samples.json\").then((data => {\n\n\n // ********** Dropdown Menu ************// \n\n // Iterate over each name in the names array to populate dropdowns with IDs\n data.names.forEach((name => {\n var option = idSelect.append(\"option\");\n option.text(name);\n })); //end of forEach loop\n\n // get the first ID from the list as a default value for chart\n var initId = idSelect.property(\"value\")\n\n // plot charts with initial ID\n displayCharts(initId);\n\n }));\n }",
"function init() {\n checkBiquadFilterQ().then(function(flag) {\n hasNewBiquadFilter = flag;\n context = new AudioContext();\n hasIIRFilter = context['createIIRFilter'] ? true : false;\n });\n\n const magStyle = document.querySelector('#mag-select');\n magStyle.addEventListener('change', (event) => {\n setPlotType(event.target.value);\n });\n\n const freqStyle = document.querySelector('#freq-select');\n freqStyle.addEventListener('change', (event) => {\n setFreqType(event.target.value);\n });\n}",
"initialize() {\n\t\tconst weekTR = {ends:{value:7,unit:'days'},starts:{value:60,unit:'minutes'}};\n\t\tconst monthTR = {ends:{value:1,unit:'months'},starts:{value:60,unit:'minutes'}};\n\t\t\n\t\tthis.models['UserElectricityNowModel'] = this.master.modelRepo.get('UserElectricityNowModel');\n\t\tthis.models['UserElectricityNowModel'].subscribe(this);\n\t\t\n\t\tthis.models['UserElectricityDayModel'] = this.master.modelRepo.get('UserElectricityDayModel');\n\t\tthis.models['UserElectricityDayModel'].subscribe(this);\n\t\t\n\t\tconst model_ElectricityWeek = new UserApartmentModel({name:'UserElectricityWeekModel',src:'data/sivakka/apartments/feeds.json',type:'energy',limit:1,range:weekTR});\n\t\tmodel_ElectricityWeek.subscribe(this);\n\t\tthis.master.modelRepo.add('UserElectricityWeekModel',model_ElectricityWeek);\n\t\tthis.models['UserElectricityWeekModel'] = model_ElectricityWeek;\n\t\t\n\t\tconst model_ElectricityMonth = new UserApartmentModel({name:'UserElectricityMonthModel',src:'data/sivakka/apartments/feeds.json',type:'energy',limit:1,range:monthTR});\n\t\tmodel_ElectricityMonth.subscribe(this);\n\t\tthis.master.modelRepo.add('UserElectricityMonthModel',model_ElectricityMonth);\n\t\tthis.models['UserElectricityMonthModel'] = model_ElectricityMonth;\n\t\t\n\t\t\n\t\tthis.models['MenuModel'] = this.master.modelRepo.get('MenuModel');\n\t\tthis.models['MenuModel'].subscribe(this);\n\t\t\n\t\tthis.view = new UserElectricityView(this);\n\t\t// If view is shown immediately and poller is used, like in this case, \n\t\t// we can just call show() and let it start fetching... \n\t\t//this.show(); // Try if this view can be shown right now!\n\t}",
"function initSelection() {\n canvas.on({\n \"selection:created\": function __listenersSelectionCreated() {\n global.console.log(\"**** selection:created\");\n setActiveObject();\n toolbar.showActiveTools();\n },\n \"before:selection:cleared\": function __listenersBeforeSelectionCleared() {\n global.console.log(\"**** before:selection:cleared\");\n },\n \"selection:cleared\": function __listenersSelectionCleared() {\n global.console.log(\"**** selection:cleared\");\n toolbar.hideActiveTools();\n },\n \"selection:updated\": function __listenersSelectionUpdated() {\n global.console.log(\"**** selection:updated\");\n setActiveObject();\n toolbar.showActiveTools();\n },\n });\n}",
"function initializeFilterComp() {\n subViews.filtersComp = new Filters($outlet.find(SEL_FILTERS).first());\n\n DataCache().get(URL_FILTERS).then(function(data) {\n subViews.filtersComp.setState(data);\n });\n }",
"function init() {\n utilsService.addDropdownOptions('from-currency', availableCurrencies);\n document.getElementById('amount').value = defaultAmount;\n getRates(selectedBase);\n}",
"function init() {\n setDate();\n setTopic();\n}",
"function init() {\n loadJSON(function(response) {\n let actual_JSON = JSON.parse(response);\n triggered(actual_JSON);\n });\n}",
"function init() {\r\n // vm.getPostedData();\r\n }",
"function startLoad() {\n selector = new Selector();\n}",
"function initialize() {\n // console.time('List init');\n if (options.optimize) {\n _knockout2.default.options.deferUpdates = true;\n }\n rows().forEach(function (row) {\n row.items().forEach(function (item) {\n item.dispose && item.dispose();\n });\n });\n rows.removeAll();\n if (data() && Array.isArray(data()) && data().length > 0) {\n data().forEach(function (item) {\n add(item, false, initial);\n });\n\n // if trackDiffChanges set to true store the original data to noticeboard\n if (node.trackDiffChanges) {\n _scalejs4.default.set(node.id, data());\n }\n } else {\n for (var i = rows().length; i < minRequiredRows; i++) {\n add(null, true, initial);\n }\n }\n initial = undefined;\n if (options.optimize) {\n _knockout2.default.options.deferUpdates = false;\n }\n // console.timeEnd('List init');\n }",
"function init() {\n createjs.Ticker.framerate = animateFps;\n Promise.all([Promise.all(initValueProviders()), Promise.all(initAnimates())]).then(() => {\n Promise.all([initWidgets()]).then(() => {\n resolveValueProviders();\n Object.entries(models).forEach(([, model]) => model.init());\n javascript.onBeforeModelRun.forEach(fn => fn());\n Object.entries(models).forEach(([, model]) => model.play());\n Object.entries(widgets).forEach(([, widget]) => widget.updateComponent());\n spinner.hide();\n });\n });\n}",
"function init() {\n var elementsArray = getAllElementsFromSelectos(inputAutocompleteSelector);\n //addEventsToElements(elementsArray, \"keydown\", disableChatOnPressReturn);\n\n for (var i = 0; i < elementsArray.length; i++) {\n addEvent(elementsArray[i], \"focus\", disableChat);\n addEvent(elementsArray[i], \"blur\", enableChat);\n }\n }",
"initAddons() {\n this.createFilterList();\n this.domUtil.createSortingOptions(e => this.sortingChangeListener(e));\n this.domUtil.createPaginationOptions();\n this.initPagination(this.products, defaultRecordsToShow);\n }",
"function init() {\n sortableEle = $('#sortable').sortable({\n start: $scope.dragStart,\n update: $scope.dragEnd\n });\n getFields();\n }",
"function initializeData(data) {\n\tvar model = data.playerData;\n\tif(typeof model !== 'undefined') {\n\t\tvar modelLength = model.length,\n\t \tcountryList = [],\n\t \tpositionList = [],\n\t \tcountryValue = [],\n\t \tpositionValue = [],\n\t \ti, obj, country, position, countryObj, positionObj;\n \tfor (i = 0; i < modelLength; i = i + 1) {\n \t\tobj = model[i],\n \t\tcountry = obj.nationality,\n \t\tposition = obj.position,\n \t\tcountryObj = {\n \t\t\ttext: country\n \t\t};\n \t\tpositionObj = {\n \t\t\ttext: position\n \t\t};\n \t\t//To create unique array list we keep the check for countryList and positionList.\n \t\tif(!countryList.filter(function(element){\n \t\t\treturn filterFunction(element, 'text', country);\n \t\t}).length) {\n \t\t\tcountryValue.push(country);\n \t\t\tcountryList.push(countryObj);\n \t\t}\n \t\tif(!positionList.filter(function(element){\n \t\t\treturn filterFunction(element, 'text', position);\n \t\t}).length) {\n \t\t\tpositionValue.push(position);\n \t\t\tpositionList.push(positionObj);\n \t\t}\n \t}\n \tCLUB.data = model;\n \tCLUB.selectedData = model;\n \tCLUB.countryList = countryList;\n \tCLUB.positionList = positionList;\n \tCLUB.countryValue = countryValue.slice();\n \tCLUB.positionValue = positionValue.slice();\n\t} else {\n\t\talert('error in data');\n\t}\n}",
"function initDropdowns() {\n $('#question-button').on('click', dropdownHandler);\n $('#question-input').on('keyup', questionFilterFunction);\n $('#myPerson').on('keyup', peopleFilterFunction);\n}",
"refreshObjectSelect() {\n let select_obj_buffer = this.prepareSelectObjects();\n $('.select_event_primary').empty().append(select_obj_buffer);\n $('#event_primary').empty().append(select_obj_buffer);\n $('#glevent_primary').empty().append(select_obj_buffer);\n //globalevent\n\n $('.select_glevent_primary').each(function (index) {\n let id_buffer = parseInt($(this).parents('tr').attr('glevent_id'));\n let event_buffer = getReferenceById(id_buffer);\n $('#glevent_' + id_buffer + ' .select_glevent_primary').val(event_buffer.object.ID);\n });\n //event\n $('.select_event_primary').each(function (index) {\n let id_buffer = parseInt($(this).parents('tr').attr('event_id'));\n let event_buffer = getReferenceById(id_buffer);\n $('#event_' + id_buffer + ' .select_event_primary').val(event_buffer.origin.ID);\n });\n\n $('.select_event_secondary').empty().append(select_obj_buffer);\n $('#event_secondary').append(select_obj_buffer);\n $('.select_event_secondary').each(function (index) {\n let id_buffer = parseInt($(this).parents('tr').attr('event_id'));\n let event_buffer = getReferenceById(id_buffer);\n\n $('#event_' + id_buffer + ' .select_event_primary').val(event_buffer.origin.ID);\n });\n }",
"_createWatcher() {\n const _watcher = Looper.create({\n immediate: true,\n });\n _watcher.on('tick', () => safeExec(this, 'fetch'));\n\n this.set('_watcher', _watcher);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utilities ========= `bubbleEvent(event)` Event listener to fire any bubbling events. Normal usage of this looks something like the following: child.addEventListener "", parent.bubbleEvent This allows the parent to fire any events that the child fires up the chain, restricted only to the events that are specified to bubble. | bubbleEvent(evt) {
if (evt.bubbles) {
evt.bubbleTrace = (evt.bubbleTrace || []).concat(this);
this.dispatchEvent(evt);
}
} | [
"function cancelBubble(event) {\r\n\r\n if (event.stopPropagation) {\r\n event.stopPropagation();\r\n } else {\r\n event.cancelBubble = true;\r\n }\r\n}",
"callChildMethod(){\n this.template.querySelector('c-bubble-event').childMethodCallingFromParent('Parent message passed');\n }",
"function dispatchFakeEvent(node, type, bubbles) {\n return dispatchEvent(node, createFakeEvent(type, bubbles));\n}",
"function cancelbubbling(e) {\n Event.stop(e);\n }",
"function handleBubbleClick(bubble) {\n bubble.speed += ACCELERATION;\n bubble.points--;\n if (bubble.points === 0) {\n popBubble(bubble);\n }\n bubble.text(bubble.points);\n}",
"_callEventListeners(event, args = []) {\n // Make args an array if it's not\n const arrayArgs = Array.isArray(args) ? args : [args];\n if (this._eventListeners[event]) {\n for (const handler of this._eventListeners[event]) {\n handler.apply(null, arrayArgs);\n }\n }\n }",
"function sendEvent(event) {\n const element = event.target;\n\n // If event was generated from any of the event buttons\n if (element.hasAttribute(\"data-event\")) {\n match.handleEvent(element.getAttribute(\"data-event\")); // send event to match handler\n }\n}",
"function sendParent(event, options) {\n return send$1(event, __assign({}, options, { to: SpecialTargets.Parent }));\n}",
"function HookEvents() {\n\t// Get all the inputs we want to add events to, generally this will be input fields\n\tvar inputs = document.getinputsByTagName('input');\n\tfor (i = 0; i < inputs.length; i++) {\n\t\t//Add a function call to the onblur event\n\t\tAddFunctionToControlEvent(inputs[i], 'onblur', HookedFunction);\n\t}\n\t// We can also monitor dropdowns\n\tvar selects = document.getinputsByTagName('select');\n\tfor (i = 0; i < selects.length; i++) {\n\t\tif (selects[i].addEventListener) {\n\t\t\tselects[i].addEventListener('onblur', HookedFunction, false); \n\t\t}\n\t\telse {\n\t\t\tselects[i].attachEvent('onblur', HookedFunction); \n\t\t}\n\t}\n}",
"function sendChildrenEvent(children, event) {\n for (var i = 0; i < children.length; ++i) {\n sendEvent(children[i], event);\n }\n }",
"function extendEvent(e) {\n if (typeof window.addEventListener === 'function') {\n } else {\n e.stopPropagation = function() {\n e.cancelBubble = true;\n };\n\n e.preventDefault = function() {\n e.returnValue = false;\n };\n }\n if (!e.target && e.srcElement) {\n e.target = e.srcElement;\n }\n return e;\n }",
"function ChildEvent(type, child) {\n _super.call(this, type);\n this._m_child = child;\n }",
"function patchAddEventListener() {\n if (_addEventListenerIsPatched) {\n debugLog('patchAddEventListener: addEventListener is already patched.');\n return;\n }\n\n debugLog('Patching addEventListener.');\n\n var prototypeSplash = getHH(Element.prototype);\n prototypeSplash.oldAddEventListener = Element.prototype.addEventListener;\n\n Element.prototype.addEventListener = function(eventType, listener, useCapture) {\n debugLog('patchAddEventListener: addEventListener called.\\nelement: ', this,\n '\\neventType: ', eventType,\n '\\nlistener: ', listener,\n '\\nuseCapture: ', useCapture);\n\n var thisSplash = getHH(this);\n\n // Register this event on the element itself.\n if (!thisSplash.hasOwnProperty('eventListeners')) {\n thisSplash.eventListeners = {};\n }\n\n if (!thisSplash.eventListeners.hasOwnProperty(eventType)) {\n thisSplash.eventListeners[eventType] = [];\n }\n\n thisSplash.eventListeners[eventType].push(listener);\n\n // Register this event in the registry.\n if (!_elementsWithListeners.hasOwnProperty(eventType)) {\n _elementsWithListeners[eventType] = [];\n }\n\n // TODO: Elements with multiple listeners will be pushed on this\n // list multiple times, but I'm not aware of any more efficient\n // data structure to do this.\n _elementsWithListeners[eventType].push(this)\n\n // Finally, call the patched function.\n args = [eventType, listener, useCapture];\n prototypeSplash.oldAddEventListener.apply(this, args);\n }\n\n _addEventListenerIsPatched = true;\n }",
"function releaseBubbles() {\n createBubbles();\n for (var i = 0; i < bubbleCount; i++) {\n containerDiv.appendChild(bubbleBuffer[i]);\n }\n console.log(\"Bubbles released\");\n}",
"function eventPreventer(event) {\r\n\tif ( typeof event.target === 'object' && event.target ) {\r\n\t\tevent.preventDefault();\r\n\t}\r\n}",
"function bind(element, event, handler) {\n // Convert a string element to its DOM equivalent\n if (typeof element == \"string\") {\n element = $(element)[0];\n }\n\n if (element) {\n element.addEventListener(event, handler, false);\n }\n }",
"function bubbleSort(arr) {\n\n}",
"runHook(hookName, options, ...params) {\n if (!this.initialized) {\n return;\n }\n\n const hook = (this.getConfig(`hooks`) || {})[hookName];\n if (hook) {\n hook(...params);\n }\n if (options.cascade) {\n for (const child of this.$panelChildren) {\n if (options.exclude !== child) {\n child.runHook(hookName, options, ...params);\n }\n }\n }\n }",
"function simulateEvent($event, eventElement) {\n $(eventElement).trigger($event);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the number of "children" obj has | function numChildren(obj) {
return obj.children.length;
} | [
"numDescendants() {\n let num = 1;\n for (const branch of this.branches) {\n num += branch.numDescendants();\n }\n return num;\n }",
"function numOfTotalEnemies() {\n\tconst totalEnemies = gameState.enemies.getChildren().length;\n return totalEnemies;\n}",
"get depth() {\n let d = 0;\n for (let p = this.parent; p; p = p.parent)\n d++;\n return d;\n }",
"function speciesCount(node, parentNodes) {\n let childrenAmount = node.c.length;\n\n if (childrenAmount > 0 && node.r == 'Genus') {\n //say the node has N species\n node.cumulativeChildren += node.c.length;\n //add species count ot its parents\n parentNodes.forEach(function(familyNode) {\n familyNode.cumulativeChildren += childrenAmount;\n });\n }\n}",
"children(person) {\n return person.sons;\n }",
"immediateLiveChildren(subregion)\n {\n if (subregion == null)\n {\n return -1;\n }\n\n var sum = 0;\n\n if (subregion.first != null) sum++;\n if (subregion.second != null) sum++;\n if (subregion.third != null) sum++;\n if (subregion.fourth != null) sum++;\n\n return sum;\n }",
"function totalAmountAdjectives(obj) {\n\treturn Object.values(obj).length;\n}",
"async function getChildsLenByLevel(region) {\n let level = _.size(region.parents); // Region level equals number of parent regions\n\n if (level < maxRegionLevel) {\n // Find number of children by levels\n // Current region will be on position of current level\n // For example, children of region 77, wich has only one parent, will be found like that:\n // {'parents.1': 77, parents: {$size: 2}}\n // {'parents.1': 77, parents: {$size: 3}}\n // {'parents.1': 77, parents: {$size: 4}}\n const childrenQuery = { ['parents.' + level]: region.cid };\n const promises = [];\n\n while (level++ < maxRegionLevel) { // level инкрементируется после сравнения\n childrenQuery.parents = { $size: level };\n promises.push(Region.count(childrenQuery).exec());\n }\n\n return _.compact(await Promise.all(promises));\n }\n\n // If level is maximum just move to the mext step\n return [];\n}",
"function countNumberOfSubItems(item) {\n if (defined(item.items)) {\n return item.items.length;\n } else {\n return 1;\n }\n}",
"function getDepth(page_id) {\n\t\t\tif(!page_id || page_id < 1) return 0;\n\t\t\tconsole.log(page_id);\n\t\t\tvar depth = 0;\n\t\t\tvar parent_id = parents[page_id];\n\t\t\twhile (parent_id != 0 && depth < 3) {\n\t\t\t\tconsole.log(depth);\n\t\t\t\tdepth++;\n\t\t\t\tparent_id = parents[parent_id];\n\t\t\t}\n\t\t\treturn depth;\n\t\t}",
"function keysCounter(obj) {\n // your code here\n var counter = 0;\n counter = Object.keys(obj).length;\nreturn counter;\n // code ends here\n}",
"function countStars() {\n return starsContainer.childNodes.length;\n}",
"count() {\n return Object.keys(this.locations).reduce(\n ((total, current) => total + Object.keys(this.locations[current]).length)\n , 0);\n }",
"function deepCount(a) {\n var len = a.length;\n for(var i = 0; i < a.length; i++){\n if(Array.isArray(a[i])){\n len+=deepCount(a[i]);\n }\n }\n return len;\n}",
"function len( obj )\n {\n if ( undefined === obj.length && \"number\" !== typeof obj.length )\n { return undefined; }\n \n return obj.length\n }",
"function count_p(parenttag)\n {\n var n = 0;\n var c = parenttag.childNodes;\n for (var i = 0; i < c.length; i++) {\n if (c[i].tagName == \"p\" || c[i].tagName == \"P\")\n n++;\n }\n return n;\n }",
"function getSize(child, sizeName) {\n var size = 0;\n\n for (var j = 0; j < child.length; ++j)\n size += child[j][sizeName];\n\n return size;\n}",
"function childIsEmpty(arr, a){\n\tn = arr.length\n\tfor(var i = 0;i < n;i++){\n\t\tif(arr[i].length != 0)\n\t\t\tcontinue\n\t\telse return i\n\t}\n\treturn a\n}",
"hasChildren(blockId) {\n const block = this.blocks[blockId];\n invariant(block, 'expect to be able to find the block');\n return block.components && block.components.length;\n }",
"function countElements() {\n var theCount = $(\"*\").css(\"padding\", \"1px\").length;\n console.log(\"There are \" + theCount + \" elements\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start a JavaScript based Agent SelfUpdate | function agentUpdate_Start(updateurl, updateoptions) {
// If this value is null
var sessionid = (updateoptions != null) ? updateoptions.sessionid : null; // If this is null, messages will be broadcast. Otherwise they will be unicasted
// If the url starts with *, switch it to use the same protoco, host and port as the control channel.
if (updateurl != null) {
updateurl = getServerTargetUrlEx(updateurl);
if (updateurl.startsWith("wss://")) { updateurl = "https://" + updateurl.substring(6); }
}
if (agentUpdate_Start._selfupdate != null)
{
// We were already called, so we will ignore this duplicate request
if (sessionid != null) { sendConsoleText('Self update already in progress...', sessionid); }
}
else {
if (agentUpdate_Start._retryCount == null) { agentUpdate_Start._retryCount = 0; }
if (require('MeshAgent').ARCHID == null && updateurl == null) {
// This agent doesn't have the ability to tell us which ARCHID it is, so we don't know which agent to pull
sendConsoleText('Unable to initiate update, agent ARCHID is not defined', sessionid);
}
else
{
var agentfilename = process.execPath.split(process.platform == 'win32' ? '\\' : '/').pop(); // Local File Name, ie: MeshAgent.exe
var name = require('MeshAgent').serviceName;
if (name == null) { name = process.platform == 'win32' ? 'Mesh Agent' : 'meshagent'; }
if (process.platform == 'win32')
{
// Special Processing for Temporary/Console Mode Agents on Windows
var parms = windows_getCommandLine(); // This uses FFI to fetch the command line parameters that the agent was started with
if (parms.findIndex(function (val) { return (val != null && (val.toUpperCase() == 'RUN' || val.toUpperCase() == 'CONNECT')); }) >= 0)
{
// This is a Temporary/Console Mode Agent
sendConsoleText('This is a temporary/console agent, checking for conflicts with background services...');
// Check to see if our binary conflicts with an installed agent
var agents = _getPotentialServiceNames();
if (_getPotentialServiceNames().length > 0)
{
sendConsoleText('Self update cannot continue because the installed agent (' + agents[0] + ') conflicts with the currently running Temp/Console agent...', sessionid);
return;
}
sendConsoleText('No conflicts detected...');
name = null;
}
else
{
// Not running in Temp/Console Mode... No Op here....
}
}
else
{
// Non Windows Self Update
try
{
var s = require('service-manager').manager.getService(name);
if (!s.isMe())
{
if (process.platform == 'win32') { s.close(); }
sendConsoleText('Self Update cannot continue, this agent is not an instance of background service (' + name + ')', sessionid);
return;
}
if (process.platform == 'win32') { s.close(); }
}
catch (zz)
{
sendConsoleText('Self Update Failed because this agent is not an instance of (' + name + ')', sessionid);
sendAgentMessage('Self Update Failed because this agent is not an instance of (' + name + ')', 3);
return;
}
}
if ((sessionid != null) && (updateurl != null)) { sendConsoleText('Downloading update from: ' + updateurl, sessionid); }
var options = require('http').parseUri(updateurl != null ? updateurl : require('MeshAgent').ServerUrl);
options.protocol = 'https:';
if (updateurl == null) { options.path = ('/meshagents?id=' + require('MeshAgent').ARCHID); sendConsoleText('Downloading update from: ' + options.path, sessionid); }
options.rejectUnauthorized = false;
options.checkServerIdentity = function checkServerIdentity(certs) {
// If the tunnel certificate matches the control channel certificate, accept the connection
try { if (require('MeshAgent').ServerInfo.ControlChannelCertificate.digest == certs[0].digest) return; } catch (ex) { }
try { if (require('MeshAgent').ServerInfo.ControlChannelCertificate.fingerprint == certs[0].fingerprint) return; } catch (ex) { }
// Check that the certificate is the one expected by the server, fail if not.
if (checkServerIdentity.servertlshash == null) {
if (require('MeshAgent').ServerInfo == null || require('MeshAgent').ServerInfo.ControlChannelCertificate == null) { return; }
sendConsoleText('Self Update failed, because the url cannot be verified: ' + updateurl, sessionid);
sendAgentMessage('Self Update failed, because the url cannot be verified: ' + updateurl, 3);
throw new Error('BadCert');
}
if (certs[0].digest == null) { return; }
if ((checkServerIdentity.servertlshash != null) && (checkServerIdentity.servertlshash.toLowerCase() != certs[0].digest.split(':').join('').toLowerCase())) {
sendConsoleText('Self Update failed, because the supplied certificate does not match', sessionid);
sendAgentMessage('Self Update failed, because the supplied certificate does not match', 3);
throw new Error('BadCert')
}
}
options.checkServerIdentity.servertlshash = (updateoptions != null ? updateoptions.tlshash : null);
agentUpdate_Start._selfupdate = require('https').get(options);
agentUpdate_Start._selfupdate.on('error', function (e) {
sendConsoleText('Self Update failed, because there was a problem trying to download the update from ' + updateurl, sessionid);
sendAgentMessage('Self Update failed, because there was a problem trying to download the update from ' + updateurl, 3);
agentUpdate_Start._selfupdate = null;
});
agentUpdate_Start._selfupdate.on('response', function (img)
{
var self = this;
this._file = require('fs').createWriteStream(agentfilename + (process.platform=='win32'?'.update.exe':'.update'), { flags: 'wb' });
this._filehash = require('SHA384Stream').create();
this._filehash.on('hash', function (h)
{
if (updateoptions != null && updateoptions.hash != null)
{
if (updateoptions.hash.toLowerCase() == h.toString('hex').toLowerCase())
{
if (sessionid != null) { sendConsoleText('Download complete. HASH verified.', sessionid); }
}
else
{
agentUpdate_Start._retryCount++;
sendConsoleText('Self Update FAILED because the downloaded agent FAILED hash check (' + agentUpdate_Start._retryCount + '), URL: ' + updateurl, sessionid);
sendAgentMessage('Self Update FAILED because the downloaded agent FAILED hash check (' + agentUpdate_Start._retryCount + '), URL: ' + updateurl, 3);
agentUpdate_Start._selfupdate = null;
try
{
// We are clearing these two properties, becuase some older agents may not cleanup correctly causing problems with the retry
require('https').globalAgent.sockets = {};
require('https').globalAgent.requests = {};
}
catch(z)
{}
if (needStreamFix)
{
sendConsoleText('This is an older agent that may have an httpstream bug. On next retry will try to fetch the update differently...');
needStreamFix = false;
}
if (agentUpdate_Start._retryCount < 4)
{
// Retry the download again
sendConsoleText('Self Update will try again in 20 seconds...', sessionid);
agentUpdate_Start._timeout = setTimeout(agentUpdate_Start, 20000, updateurl, updateoptions);
}
else
{
sendConsoleText('Self Update giving up, too many failures...', sessionid);
sendAgentMessage('Self Update giving up, too many failures...', 3);
}
return;
}
}
else
{
sendConsoleText('Download complete. HASH=' + h.toString('hex'), sessionid);
}
// Send an indication to the server that we got the update download correctly.
try { require('MeshAgent').SendCommand({ action: 'agentupdatedownloaded' }); } catch (e) { }
if (sessionid != null) { sendConsoleText('Updating and restarting agent...', sessionid); }
if (process.platform == 'win32')
{
// Use _wexecve() equivalent to perform the update
windows_execve(name, agentfilename, sessionid);
}
else
{
var m = require('fs').statSync(process.execPath).mode;
require('fs').chmodSync(process.cwd() + agentfilename + '.update', m);
// remove binary
require('fs').unlinkSync(process.execPath);
// copy update
require('fs').copyFileSync(process.cwd() + agentfilename + '.update', process.execPath);
require('fs').chmodSync(process.execPath, m);
// erase update
require('fs').unlinkSync(process.cwd() + agentfilename + '.update');
switch (process.platform)
{
case 'freebsd':
bsd_execv(name, agentfilename, sessionid);
break;
case 'linux':
linux_execv(name, agentfilename, sessionid);
break;
default:
try
{
// restart service
var s = require('service-manager').manager.getService(name);
s.restart();
}
catch (zz)
{
if (zz.toString() != 'waitExit() aborted because thread is exiting')
{
sendConsoleText('Self Update encountered an error trying to restart service', sessionid);
sendAgentMessage('Self Update encountered an error trying to restart service', 3);
}
}
break;
}
}
});
if (!needStreamFix)
{
img.pipe(this._file);
img.pipe(this._filehash);
}
else
{
img.once('data', function (buffer)
{
if(this.immediate)
{
clearImmediate(this.immediate);
this.immediate = null;
// No need to apply fix
self._file.write(buffer);
self._filehash.write(buffer);
this.pipe(self._file);
this.pipe(self._filehash);
}
else
{
// Need to apply fix
this.pipe(self._file);
this.pipe(self._filehash);
}
});
this.immediate = setImmediate(function (self)
{
self.immediate = null;
},this);
}
});
}
}
} | [
"function start()\n {\n let reloadParams = \"reload=reload\";\n fetch(\"memomedia.php\", {method: 'POST', credentials: 'include', headers: {\"Content-Type\": \"application/x-www-form-urlencoded\"}, body: reloadParams})\n .then(response => response.json())\n .then(fillPage)\n }",
"function main() {\n urlParameters = new URLSearchParams(window.location.search);\n serverClient = new ServerClient(urlParameters);\n noVNCClient = new NoVNCClient(\n connectCallback, disconnectCallback, \n document.getElementById('session-screen'));\n addOnClickListenerToElements();\n let /** number */ setIntervalId = setInterval(() => {\n serverClient.getSession().then(session => {\n clearInterval(setIntervalId);\n noVNCClient.remoteToSession(session.getIpOfVM(), \n session.getSessionId());\n setReadOnlyInputs(session.getSessionId());\n document.getElementById('welcome-message').style.display = 'block';\n updateUI();\n }).catch(error => {\n window.alert('No contact with the server, retrying!');\n });\n }, sessionScriptConstants.SERVER_RECONNECT_CADENCE_MS);\n}",
"function start_monitoring()\n {\n browser.idle.onStateChanged.addListener(on_idle_state_change);\n }",
"function start(){\r\n console.info('TRACE: start autologin');\r\n if(!listenterAdded) {\r\n listenterAdded = true;\r\n webviewEle.addEventListener('contentload', function() {\r\n console.log('TRACE: contentload triggered', webviewEle.src);\r\n if(firstLoad){\r\n firstLoad = false;\r\n preLogin();\r\n }\r\n else{\r\n postLogin();\r\n }\r\n });\r\n }\r\n webviewEle.src = ns_url;\r\n\r\n function preLogin() {\r\n console.info('TRACE: Executing preLogin');\r\n webviewEle.executeScript({code:\r\n \"var dataFromWebview = {}; \\\r\n var appOrigin, appWindow; \\\r\n var logBuffer = '';\\\r\n \\\r\n window.addEventListener('message', (e) => { console.log(e,e.source); appOrigin = e.origin; appWindow= e.source; d = e.data.split(':'); dataFromWebview[d[0]] = d[1]; }); \\\r\n \\\r\n function logMsg(msg){ console.log(msg); if(appWindow){if(logBuffer.length > 0) {msg = logBuffer + msg; logBuffer = '';}appWindow.postMessage('log:' + msg, appOrigin);} else{logBuffer = logBuffer + msg + '-->';} }\\\r\n \\\r\n function getCookie(name) { var results = document.cookie.match('(^|;) ?' + name + '=([^;]*)'); return results ? unescape(results[2]) : null; } \\\r\n logMsg('Step 1 - Login to NS Gateway'); \\\r\n logMsg('Cookies before cgi login - ' + document.cookie); \\\r\n var xhr = new XMLHttpRequest(); \\\r\n xhr.open('POST', '/cgi/login'); \\\r\n xhr.onreadystatechange = function(){ if(xhr.readyState === 4 && xhr.status===200){ \\\r\n if(getCookie('NSC_AAAC')){ \\\r\n logMsg('Login Successful, ' + 'Cookies - ' + document.cookie); \\\r\n location.reload(); \\\r\n }else { \\\r\n logMsg('Login failed, Cookies - ' + document.cookie);\\\r\n } \\\r\n }}; \\\r\n xhr.send('login=\" + username + \"&passwd=\" + passwd + \"'); \\\r\n \"\r\n },\r\n function(){\r\n console.log('preLogin - sending dummy post message to contentwindow to get reference of current window inside webview');\r\n webviewEle.contentWindow.postMessage('dummy:dummy','*');\r\n });\r\n }\r\n \r\n function postLogin(){\r\n //Injecting code for login and fetching resources\r\n console.info('TRACE: Executing postLogin');\r\n webviewEle.executeScript({\r\n code:\r\n \"var dataFromWebview = {}; \\\r\n var appOrigin, appWindow, csrf; \\\r\n var xhr = new XMLHttpRequest(); \\\r\n var logBuffer = ''; \\\r\n window.addEventListener('message', (e) => { console.log(e); appOrigin = e.origin; appWindow= e.source; d = e.data.split(':'); dataFromWebview[d[0]] = d[1]; console.log(appWindow);}); \\\r\n \\\r\n function getCookie(name) { var results = document.cookie.match('(^|;) ?' + name + '=([^;]*)'); return results ? unescape(results[2]) : null; } \\\r\n \\\r\n function logMsg(msg){ console.log(msg); if(appWindow){if(logBuffer.length > 0) {msg = logBuffer + msg; logBuffer = '';}appWindow.postMessage('log:' + msg, appOrigin);} else{logBuffer = logBuffer + msg + '-->';} } \\\r\n \\\r\n logMsg('Checking CSRF Token - ' + document.cookie);\\\r\n \\\r\n var poller = setInterval(checkCSRFToken,100); \\\r\n var count = 0;\\\r\n function checkCSRFToken(){ csrf = getCookie('CsrfToken'); if(count > 100 ){clearInterval(poller); logMsg('Polling Ended Cookies -' + document.cookie);} count+=1; console.log('polling', document.cookie); if(csrf){clearInterval(poller); getAuthMethods();}} \\\r\n \\\r\n function getAuthMethods(){ \\\r\n logMsg('Step 3b - Get Auth methods from Storefront'); \\\r\n xhrWrapper({'url':'Authentication/GetAuthMethods', 'onSuccess': 'getAuthMethodSuccess'}); \\\r\n } \\\r\n function getAuthMethodSuccess(data, xmlData){ \\\r\n logMsg('parsing authMethods' + data.replace(/:/g,'-')); \\\r\n let url; \\\r\n let methods = xmlData.getElementsByTagName('method'); \\\r\n for(let i =0; i< methods.length; i++){ if(methods[i].attributes['name'].nodeValue === 'CitrixAGBasic') { url = methods[i].attributes['url'].nodeValue; break;};} \\\r\n if(url){ loginStorefront(url); } else{ console.log('CitrixAGBasic is not enabled'); } \\\r\n } \\\r\n function loginStorefront(authURL){ \\\r\n logMsg('Step 4 - Login to Storefront' + authURL); \\\r\n xhrWrapper({'url':authURL, 'onSuccess': 'getResources'}); \\\r\n } \\\r\n function getResources(){ \\\r\n logMsg('Step 5 - List Resources'); \\\r\n xhrWrapper({'url':'Resources/List', 'data':'format=json&resourceDetails=Default1', 'onSuccess': 'displayResources'}); \\\r\n } \\\r\n function displayResources(data){ \\\r\n logMsg('Displaying resources' + data.replace(/:/g,'-'));\\\r\n document.body.innerHTML = ''; \\\r\n let res = JSON.parse(data).resources; \\\r\n for(let i = 0; i < res.length; i+=1){ \\\r\n let divEle = document.createElement('div'); divEle.id=i;\\\r\n divEle.addEventListener('click', (e) => { getICA(xhr, res, divEle.id); } ); \\\r\n let name = document.createElement('p'); let imgRes = document.createElement('img'); \\\r\n name.innerText=res[i].name; imgRes.src= res[i].iconurl; \\\r\n divEle.appendChild(name); divEle.appendChild(imgRes); document.body.appendChild(divEle); \\\r\n } \\\r\n } \\\r\n function getICA(xhr, res, id){ \\\r\n logMsg('Step 7 - Fetching ICA'); \\\r\n let currentTime = (new Date()).getTime(); \\\r\n xhrWrapper({'method':'GET', 'url': res[id].launchurl +'?csrfToken='+csrf+'&launchID='+currentTime, 'onSuccess': 'postICA'}); \\\r\n } \\\r\n function postICA(){ \\\r\n logMsg('Sending ICA to main window for session launch'); \\\r\n appWindow.postMessage('icaData:' + xhr.responseText, appOrigin); \\\r\n } \\\r\n function xhrWrapper(params){ \\\r\n let method = 'POST'; \\\r\n let data = '';\\\r\n if(params.method) { method = params.method; } \\\r\n xhr.open(method, params.url); \\\r\n if(csrf) {xhr.setRequestHeader('Csrf-Token', csrf);} \\\r\n let isUsingHttps = location.protocol.toLowerCase() == 'https:' ? 'Yes' : 'No'; \\\r\n xhr.setRequestHeader('X-Citrix-IsUsingHTTPS', isUsingHttps); \\\r\n xhr.withCredentials = true; \\\r\n xhr.onreadystatechange = function(){ if(xhr.readyState === 4 && xhr.status===200){ console.log(xhr.responseText); window[params.onSuccess](xhr.responseText,xhr.responseXML);}}; \\\r\n if(params.data){data = params.data;}\\\r\n logMsg('Making XHR to ' + params.url + ' with cookies - ' + document.cookie);\\\r\n xhr.send(data); \\\r\n } \\\r\n \"\r\n },\r\n function(){\r\n console.log('postLogin - sending dummy post message to contentwindow to get reference of current window inside webview');\r\n webviewEle.contentWindow.postMessage('dummy:dummy','*');\r\n });\r\n }\r\n}",
"start() {\n return P.resolve()\n .then(() => {\n if (!this._started) {\n this._started = true;\n return this.reload()\n .then(() => {\n dbg.log0('Started hosted_agents');\n this._monitor_stats();\n });\n }\n dbg.log1(`What is started may never start`);\n })\n .catch(err => {\n this._started = false;\n dbg.error(`failed starting hosted_agents: ${err.stack}`);\n throw err;\n })\n .then(() => {\n // do nothing. \n });\n }",
"function startAgentARFinder() {\n\n // Get options ARFinder.\n var options = getOptionsSearchAcademicReferences();\n\n // Check config automatic references.\n if (options.autoAcademicReferences === true){\n //var watchEachSeconds = options.checkArticle * 1000;\n var watchEachSeconds = 4000;\n window.setInterval(agentSuggestAcademicReferences, watchEachSeconds);\n }\n\n}",
"start(){\n\t\t// Run immediately to avoid having to wait for the first timeout\n\t\tthis.onUpdate();\n\n\t\tvar updater = this.onUpdate.bind(this);\n\t\tthis.interval = setInterval(updater, this.updateInterval);\n\t}",
"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 main(toggler) {\n\n if (toggler.apiOn) {\n api.start()\n }\n\n if (toggler.backgroundCrawlOn) {\n backgroundCrawlJob.start()\n }\n\n}",
"_start () {\n this._loadPage();\n this._sayHello();\n }",
"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}",
"_autoSyncClient() {\n const {\n serviceWorker,\n } = navigator;\n\n const updateLog = debug.scope('update');\n\n /* istanbul ignore next: won't occur in tests */\n serviceWorker.addEventListener('controllerchange', async () => {\n try {\n const registration = await connect(true);\n this.controller = registration.active;\n\n updateLog.color('crimson')\n .warn('mocker updated, reload your requests to take effect');\n } catch (error) {\n updateLog.error('connecting to new service worker failed', error);\n }\n });\n }",
"static start() {\n\t\tconsole.log(\"Starting story.js...\");\n\t\tthis.loadJson(this.getJsonPath());\n\t\tUI.init();\n\t}",
"function restartAgent() {\n $(\".page\").css(\"display\", \"none\");\n $(\".active\").removeClass(\"active\");\n $(\"#main\").append('<i class=\"fa fa-spinner fa-pulse fa-3x fa-fw center loading_spinner\"></i>');\n\n $(\"#agent_status\").html(\"Not connected<br> to Agent\");\n $(\"#agent_status\").css({\n \"background\": 'linear-gradient(to bottom, #c62d1f 5%, #f24437 100%)',\n \"background-color\": '#c62d1f',\n \"border\": '1px solid #d02718',\n \"text-shadow\": '0px 1px 0px #810e05',\n 'left': '-180px'\n });\n\n // Disable the restart button to prevent multiple consecutive clicks\n $(\"#restart_button\").css(\"pointer-events\", \"none\");\n\n sendMessage(\"agent/restart\", \"\", \"post\",\n function(data, status, xhr){\n // Wait a few seconds to give the server a chance to restart\n setTimeout(function(){\n $(\".loading_spinner\").remove();\n $(\"#restart_button\").css(\"pointer-events\", \"auto\");\n\n if (data != \"Success\") {\n $(\"#general_status\").css(\"display\", \"block\");\n $('#general_status').html(\"<span class='center'>Error restarting agent: \" + DOMPurify.sanitize(data) + \"</span>\");\n } else loadStatus(\"general\");\n }, 10000);\n }, function() {\n $(\".loading_spinner\").remove();\n $(\"#general_status\").css(\"display\", \"block\");\n $('#general_status').html(\"<span class='center'>An error occurred.</span>\");\n $(\"#restart_button\").css(\"pointer-events\", \"auto\");\n });\n}",
"startDownload() {\n if (!this.update) {\n this.update = this.um.downloadingUpdate;\n }\n this.update.QueryInterface(Ci.nsIWritablePropertyBag);\n this.update.setProperty(\"foregroundDownload\", \"true\");\n\n let success = this.aus.downloadUpdate(this.update, false);\n if (!success) {\n this.selectPanel(\"downloadFailed\");\n return;\n }\n\n this.setupDownloadingUI();\n }",
"autoStart() {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n return this.config.autoStartRls && this.start().then(() => true);\r\n });\r\n }",
"constructor() {\n\n V1Agent.initialize(this);\n }",
"function startHR() {\nheartRateArray = new Array();\nwindow.webapis.motion.start(\"HRM\", function onSuccess(hrmInfo) {\n if (hrmInfo.heartRate > 0) \n HR = hrmInfo.heartRate;\n});\n//sendingInterval = setInterval(sendHR, 5000);\nsendingInterval = setInterval(makeJsonHR, 5000);\n}",
"constructor() {\n super('App Start', 'core.rosie.trigger.lifecycle');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
retrievs the name of the pic from the folder | function getImg(name){
let myList = readFile("Members", name);
let json = myList;
for(let i = 0; i < json.length; i++){
if(!json[i].endsWith(".txt")){
return json[i];
}
}
return "none";
} | [
"function findcardimg(card){\r\n var cardname = card.join(\"\");\r\n return \"img/cards/\" + cardname + \".png\";\r\n }",
"function findIMG(desc){\n\tvar indexJPG = desc.indexOf('.jpg');\n\tvar imageUrl;\n\tif (indexJPG === -1) {\n\t\t// if no .jpg is found, finds the first .png\n\t\timageUrl = findPNG(desc);\n\t\treturn imageUrl;\n\t} else {\n\t\tvar descUntilFirstJPG = desc.substring(0, indexJPG);\n\t\tvar indexHTTP = descUntilFirstJPG.lastIndexOf('http');\n\t\tif (indexHTTP === -1) {\n\t\t\timageUrl = '../img/EarthInHand.jpg';\n\t\t\treturn imageUrl;\n\t\t}\n\t\timageUrl = desc.substring(indexHTTP, indexJPG + 4);\n\t\t\n\t\treturn imageUrl;\n\t}\n}",
"function getImageName(category, callBack) {\n\t\t\tif (getImageName.imageName) {\n\t\t\t\tcallBack(getImageName.imageName);\n\t\t\t} else {\n\t\t\t\tsuite.execute('vm image list --json', function (result) {\n\t\t\t\t\tvar imageList = JSON.parse(result.text);\n\n\t\t\t\t\timageList.some(function (image) {\n\t\t\t\t\t\tif (image.category.toLowerCase() === category.toLowerCase()) {\n\t\t\t\t\t\t\tgetImageName.imageName = image.name;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tcallBack(getImageName.imageName);\n\t\t\t\t});\n\t\t\t}\n\t\t}",
"function readDir() {\n fs.readdir( 'public/images/memes', (error, files) => {\n return files.length;\n });\n}",
"function getImagePath(source){\n\tvar urlPath = url.parse(source).path;\n\tvar lastPath = _.last(urlPath.split(\"/\"));\n\tvar savePath = ORGINAL_IMAGE_PATH + lastPath;\n\treturn savePath;\n}",
"function get_img(i,f){var b,a=__CONF__.img_url+\"/img_new/{0}--{1}-{2}-1\",g=__CONF__.img_url+\"/img_src/{0}\",c=\"d96a3fdeaf68d3e8db170ad5\",d=\"43e2e6f41e3b3ebe22aa6560\",k=\"726a17bd880cff1fb375718c\",j=\"6ea1ff46aab3a42c975dd7ab\";i=i||\"0\";f=f||{};ObjectH.mix(f,{type:\"head\",w:30,h:30,sex:1});if(i!=\"0\"){if(f.type==\"src\"){b=g.format(i);}else{b=a.format(i,f.w,f.h);}}else{if(f.type==\"head\"){if(f.sex==1){b=a.format(c,f.w,f.h);}else{b=a.format(d,f.w,f.h);}}else{if(f.type==\"subject\"){b=a.format(k,f.w,f.h);}else{if(f.type==\"place\"){b=a.format(j,f.w,f.h);}else{b=a.format(\"0\",f.w,f.h);}}}}return b;}",
"function generaFoto(cedula)\n\t{\n\t\tvar r = '000000000' + cedula;\n\t\treturn r.substring(r.length,r.length-9) + \".jpg\";\n\t}",
"function getImagesByDate(day) {\n document.getElementById(`images-show${day}`).innerHTML = '';\n let directoryPath = path.join(__dirname, `/vendor/img/dates/${day}/`);\n\n fs.readdir(directoryPath, (err, files) => {\n if (err) {\n return alert('Проблем с четенето на системните файлове!');\n }\n files.forEach(function (file) {\n // Взимаме всичко файлове с даден extension\n if (path.extname(file) == \".jpg\" || path.extname(file) == \".png\" || path.extname(file) == \".jpeg\") {\n document.getElementById(`images-show${day}`).innerHTML += `\n <div class=\"col-sm mt-2 mb-2\">\n <a data-fancybox=\"gallery\" href=\"vendor/img/dates/${day}/${path.basename(file)}\">\n <img class=\"img_v\" src=\"vendor/img/dates/${day}/${path.basename(file)}\">\n </a>\n </div>\n `\n }\n ;\n });\n });\n\n}",
"async function getCvName(cv_id) {\n let queryattachment;\n try {\n queryattachment = await db.query(\n \"SELECT filename FROM cv where id = $1\",\n [cv_id]\n );\n return queryattachment;\n } catch (err) {\n console.error(err.stack);\n }\n }",
"function productNameFromImagePath(imagePath) {\n\t// This is the full filename, ex:\n\t// \"Box1_$10.png\"\n\tvar imageFileName = imagePath.match(/[\\w\\$]+\\.\\w+/)[0];\n\n\t// This is the filename without the extension, ex:\n\t// \"Box1_$10\"\n\timageFileName = imageFileName.split('.')[0];\n\n\t// This is the product name, ex:\n\t// \"Box1\"\n\tvar productName = imageFileName.split('_')[0];\n\n\treturn productName;\n}",
"getByUrl(name) {\n return Folder(this).concat(`('${encodePath(name)}')`);\n }",
"function getPieceImageName(id, player) {\n\tvar pieceName = getPieceNameFromId(id);\n\treturn player.getImageColor() + pieceName;\n}",
"function showImage(n, i, m){\n document.getElementById(\"img--\"+m).src = \"./album/\"+n+\"/\"+i+\".jpg\";\n}",
"function loadNextImage() {\n let next = games.splice(0, 1)[0];\n\n document.getElementById(\"background\").src = next.img;\n document.getElementById(\"jakob\").getElementsByTagName(\"span\")[0].innerText = next.name;\n}",
"chooseArtistImage(data) {\n \tvar imgSrc;\n \tif (data.images.length > 3) {\n imgSrc = data.images[2].url;\n } else if (data.images.length > 1) {\n imgSrc = data.images[0].url;\n } else {\n imgSrc = 'http://placehold.it/45x45';\n };\n return imgSrc;\n }",
"_currentPicture() {\n return this.props.pictures.get(this.state.idx, null);\n }",
"function imagePath(item_id, image_index, sold) {\n item_id = ITEM_TO_MASTER_ID_MAP[item_id];\n var path_str = \"\";\n var outlet_code = process.env.OUTLET_CODE\n if (fs.existsSync(source_folder + '/' + outlet_code + '/menu_items/' + item_id)) {\n path_str = source_folder + '/' + outlet_code + '/menu_items/' + item_id;\n } else {\n path_str = source_folder + '/' + item_id;\n }\n var sold_suffix = '';\n if (sold) {\n sold_suffix = '_sold';\n }\n path_str += '/{}{}.png'.format(image_index, sold_suffix);\n return path_str;\n}",
"function getQrImagePathToSave()\n{\n return path.join(__dirname,'../../../client/qr-images/');\n}",
"function findPNG(desc){\n\tvar indexPNG = desc.indexOf('.png');\n\tvar imageUrl;\n\tif (indexPNG === -1) {\n\t\timageUrl = '../img/EarthInHand.jpg';\n\t\treturn imageUrl;\n\t} else {\n\t\tvar descUntilFirstPNG = desc.substring(0, indexPNG);\n\t\tvar indexHTTP = descUntilFirstPNG.lastIndexOf('http');\n\t\t\n\t\tif (indexHTTP === -1) {\n\t\t\t// if no .png is found returns default image\n\t\t\timageUrl = '../img/EarthInHand.jpg';\n\t\t\treturn imageUrl;\n\t\t\n\t\t} else {\n\t\t\t// if .png is found checks whether it is social network icon\n\t\t\timageUrl = desc.substring(indexHTTP, indexPNG + 4);\n\t\t\tvar social = findSocial(imageUrl);\n\t\t\tif (social === true) {\n\t\t\t\timageUrl = '../img/EarthInHand.jpg';\n\t\t\t} else {\n\t\t\t\treturn imageUrl;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn imageUrl;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Body Detect EVENT Register. | function doHumanDetectBodyRegister(serviceId, sessionKey) {
let params = {
profile: 'humandetection',
attribute: 'onbodydetection',
params: {
serviceId: serviceId
}
};
addBodyOptionParameter(params.params, 'body');
sdk.addEventListener(params, message => {
// イベントメッセージが送られてくる
if (DEBUG) {
console.log('Event-Message:' + message);
}
let json = JSON.parse(message);
setBodyDetectResponse(json);
}).catch(e => {
alert(e.errorMessage);
});
} | [
"_registerEvent () {}",
"function addBodyListeners() {\n /** \n * Reference to the body element.\n *\n * @private\n * @property body\n * @type Element\n * */\n var body = document.getElementsByTagName('body')[0];\n\n if (body) {\n\n handleSpecificClicks();\n\n VeAPI.Utils.Shell.info('activating new click handler');\n document.documentElement.onmousedown = onBodyElementClick;\n VEjQuery(document.documentElement).on('click', onBodyElementClick);\n //on IE8 most of times the click does not get executed, this is analogous to the previous behavior.\n //TODO: Remove it from the next big release\n //document.documentElement.onclick = onBodyElementClick;\n\n Utils.addEventHandler(document, 'keydown', onBodyElementKeyDown);\n Utils.addEventHandler(body, 'change', onBodyElementChange);\n eventHandlersRemoved = false;\n }\n }",
"function onBodyElementChange() {\n VeAPI.Utils.Shell.info('body changed');\n delayChat();\n }",
"_setupCollision () {\n this.PhysicsManager.getEventHandler().on(this.PhysicsManager.getEngine(), 'collisionStart', (e) => {\n\n for (let pair of e.pairs) {\n let bodyA = pair.bodyA\n let bodyB = pair.bodyB\n\n if (bodyB === this.body) {\n this.onCollisionWith(bodyA)\n }\n }\n })\n }",
"function onDocumentBody(callback) {\n if (document.body) {\n callback();\n } else {\n setTimeout(function () {\n onDocumentBody(callback);\n }, 0);\n }\n }",
"function injectWeibo(){\n injectWeiboJs($('body'));\n document.addEventListener('DOMNodeInserted', function (event){\n node = event.target;\n if(!node.nodeName || node.nodeName.toUpperCase() !== 'DIV') return;\n injectWeiboJs(node);\n //if(node.classList.contains('WB_feed_type')){\n // // refresh events \n // injectWeiboJs(node);\n //}else if(node.classList.contains('WB_feed')){\n // // first loading events\n // injectWeiboJs(node);\n //}else{\n // // try always\n // injectWeiboJs(node);\n //}\n }, false);\n }",
"start() {\n if (!this.eb) {\n this.eb = new EventBus(this.busUrl);\n this.eb.onopen = function() {\n simulatorVerticle.eb.registerHandler(CALLSIGN_FLASH,simulatorVerticle.heartBeatHandler);\n simulatorVerticle.eb.registerHandler(CALLSIGN_BO,simulatorVerticle.carMessageHandler)\n };\n };\n this.enabled=true;\n }",
"function PushEvent() { }",
"function registerFormEvents() {\n if (inlineJs.crudId == 1 || inlineJs.crudId == 2) {\n validateForm('form#' + inlineJs.controller + 'Post');\n\n //Size the forms\n sizeForm();\n\n //Max length indicator\n maxLengthIndicator();\n\n //Register searchable select\n registerSearchableSelect();\n\n }//E# if statement\n //Register Reset button\n resetForm('.resetButton');\n}",
"function createEvent(req, res, next){\n //Take the request body... parse it and add the event to the db\n //Once done---> return next();\n}",
"registerHandlers(){\n\n\t\t// Notify event\n\t\tthis.process.on(\"notify\", function( state ){\n\t\t\tif (!print_debug) return;\n\t\t\tconsole.log( \"//-------------------NOTIFY----------------//\" );\n\t\t\tconsole.log( JSON.stringify(state, null, \"\\t\") );\n\t\t\tconsole.log( \"//-----------------------------------------//\" );\n\t\t});\n\t\t\n\t\t// Gdb close event\n\t\tthis.process.on(\"close\", (return_code, signal) => {\n\t\t\tthis.running = false;\n\t\t\tthis.emit('status', {\n\t\t\t\tgdbLog\t\t\t: 'Debugger closed with code '+return_code+' '+signal, \n\t\t\t\tdebugStatus\t\t: 'inactive', \n\t\t\t\tdebugRunning\t: false\n\t\t\t});\n\t\t});\n\t\t\n\t\t// GDB output\n\t\tthis.process.on('gdb', (data) => this.emit('status', {gdbLog: 'GDB> '+data}) );\n\t\t\n\t\t// Application output\n\t\tthis.process.on('app', (data) => this.emit('status', {debugBelaLog: data}) );\n\t\t\n\t}",
"_initEvent() {\n this.eventManager.listen('hide', this.hide.bind(this));\n this.eventManager.listen('show', this.show.bind(this));\n }",
"parseEvent() {\n\t\tlet addr = ppos;\n\t\tlet delta = this.parseDeltaTime();\n\t\ttrackDuration += delta;\n\t\tlet statusByte = this.fetchBytes(1);\n\t\tlet data = [];\n\t\tlet rs = false;\n\t\tlet EOT = false;\n\t\tif (statusByte < 128) { // Running status\n\t\t\tdata.push(statusByte);\n\t\t\tstatusByte = runningStatus;\n\t\t\trs = true;\n\t\t} else {\n\t\t\trunningStatus = statusByte;\n\t\t}\n\t\tlet eventType = statusByte >> 4;\n\t\tlet channel = statusByte & 0x0F;\n\t\tif (eventType === 0xF) { // System events and meta events\n\t\t\tswitch (channel) { // System message types are stored in the last nibble instead of a channel\n\t\t\t// Don't really need these and probably nobody uses them but we'll keep them for completeness.\n\n\t\t\tcase 0x0: // System exclusive message -- wait for exit sequence\n\t\t\t\t// console.log('sysex');\n\t\t\t\tlet cbyte = this.fetchBytes(1);\n\t\t\t\twhile (cbyte !== 247) {\n\t\t\t\t\tdata.push(cbyte);\n\t\t\t\t\tcbyte = this.fetchBytes(1);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 0x2:\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tbreak;\n\n\t\t\tcase 0x3:\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tbreak;\n\n\t\t\tcase 0xF: // Meta events: where some actually important non-music stuff happens\n\t\t\t\tlet metaType = this.fetchBytes(1);\n\t\t\t\tlet len;\n\t\t\t\tswitch (metaType) {\n\t\t\t\tcase 0x2F: // End of track\n\t\t\t\t\tthis.skip(1);\n\t\t\t\t\tEOT = true;\n\t\t\t\t\t// console.log('EOT');\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 0x51:\n\t\t\t\t\tlen = this.fetchBytes(1);\n\t\t\t\t\tdata.push(this.fetchBytes(len)); // All one value\n\t\t\t\t\tif (this.firstTempo === 0) {\n\t\t\t\t\t\t[this.firstTempo] = data;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0x58:\n\t\t\t\t\tlen = this.fetchBytes(1);\n\t\t\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t\t}\n\t\t\t\t\tif (this.firstBbar === 0) {\n\t\t\t\t\t\tthis.firstBbar = data[0] / 2 ** data[1];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlen = this.fetchBytes(1);\n\t\t\t\t\t// console.log('Mlen = '+len);\n\t\t\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\teventType = getIntFromBytes([0xFF, metaType]);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tconsole.log('parser error');\n\t\t\t}\n\t\t\tif (channel !== 15) {\n\t\t\t\teventType = statusByte;\n\t\t\t}\n\t\t\tchannel = -1; // global\n\t\t} else {\n\t\t\tswitch (eventType) {\n\t\t\tcase 0x9:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\tif (data[1] === 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tlet ins;\n\t\t\t\t// var ins = currentInstrument[channel]; // Patch out percussion splitting\n\t\t\t\t// TODO: Patch back in, in a new way\n\t\t\t\tif (channel === 9) {\n\t\t\t\t\tthis.trks[tpos].hasPercussion = true;\n\t\t\t\t\t[ins] = data;\n\t\t\t\t} else {\n\t\t\t\t\tins = currentInstrument[channel];\n\t\t\t\t}\n\t\t\t\tlet note = new Note(trackDuration, data[0], data[1], ins, channel);\n\t\t\t\tif ((data[0] < this.trks[tpos].lowestNote && !this.trks[tpos].hasPercussion)\n || this.trks[tpos].lowestNote === null) {\n\t\t\t\t\t[this.trks[tpos].lowestNote] = data;\n\t\t\t\t}\n\t\t\t\tif (data[0] > this.trks[tpos].highestNote && !this.trks[tpos].hasPercussion) {\n\t\t\t\t\t[this.trks[tpos].highestNote] = data;\n\t\t\t\t}\n\t\t\t\tthis.trks[tpos].notes.push(note);\n\t\t\t\tif (isNotInArr(this.trks[tpos].usedInstruments, ins)) {\n\t\t\t\t\tthis.trks[tpos].usedInstruments.push(ins);\n\t\t\t\t}\n\t\t\t\tif (isNotInArr(this.trks[tpos].usedChannels, channel)) {\n\t\t\t\t\tthis.trks[tpos].usedChannels.push(channel);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 0xC:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\t// console.log(tpos+': '+data[0]);\n\t\t\t\tcurrentLabel = getInstrumentLabel(data[0]);\n\t\t\t\t// The last instrument on a channel ends where an instrument on the same channel begins\n\t\t\t\t// this.usedInstruments[tpos].push({ins: data[0], ch: channel, start: trackDuration});\n\t\t\t\t// if(notInArr(this.usedInstruments,data[0])){this.usedInstruments.push(data[0])} // Do this for now\n\t\t\t\t[currentInstrument[channel]] = data;\n\t\t\t\tbreak;\n\t\t\tcase 0xD:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (!rs) {\n\t\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t\t}\n\t\t\t\tdata.push(this.fetchBytes(1));\n\t\t\t}\n\t\t\tfor (let i = 0; i < noteDelta.length; i++) {\n\t\t\t\tnoteDelta[i] += delta;\n\t\t\t}\n\t\t\tif (eventType === 0x9 && data[1] !== 0) {\n\t\t\t\t// console.log(bpbStuff);\n\t\t\t\tfor (let i = 1; i <= 16; i++) {\n\t\t\t\t\tlet x = (i * noteDelta[channel]) / this.timing;\n\t\t\t\t\tlet roundX = Math.round(x);\n\t\t\t\t\t// console.log(\"Rounded by: \" + roundX-x);\n\t\t\t\t\tthis.trks[tpos].quantizeErrors[i - 1] += Math.round(Math.abs((roundX - x) / i) * 100);\n\t\t\t\t}\n\t\t\t\tnoteDelta[channel] = 0;\n\t\t\t\tthis.noteCount++;\n\t\t\t}\n\t\t}\n\t\tthis.trks[tpos].events.push(new MIDIevent(delta, eventType, channel, data, addr));\n\t\t// console.log('+'+delta+': '+eventType+' @'+channel);\n\t\t// console.log(data);\n\t\t// this.debug++;\n\t\tif (this.debug > 0) {\n\t\t\treturn true;\n\t\t}\n\t\treturn EOT;// || this.debug>=4;\n\t}",
"registerEvents() {\n\t\t\tthis.container = this.getContainer();\n\t\t\tthis.registerListEvents();\n\t\t\tthis.registerForm();\n\t\t}",
"static uploadCustomBody (comp, event) {\n const scene = comp.scene\n const engine = scene.getEngine()\n\n // OBJFileLoader.OPTIMIZE_WITH_UV = true\n BABYLON.FilesInput.FilesToLoad = []\n var filesInput = new BABYLON.FilesInput(engine, null, null, null, null, null, function () { BABYLON.Tools.ClearLogCache() }, function () {}, null)\n filesInput.onProcessFileCallback = (function (file, name, extension) {\n BABYLON.FilesInput.FilesToLoad[name] = file\n if (['obj', 'STL', 'stl'].includes(extension)) {\n let ext = '.obj'\n if (name.indexOf('.stl') !== -1 || name.indexOf('.STL') !== -1) {\n ext = '.stl'\n }\n\n BABYLON.SceneLoader.ImportMesh('', 'file:', file.correctName, scene, function(loadedMeshes) {\n for (let i = 0; i < loadedMeshes.length; i++) {\n if (loadedMeshes[i].name.indexOf('body') !== -1) {\n console.log('body', loadedMeshes[i])\n }\n else {\n if (loadedMeshes[i].name.indexOf('pin') !== -1) {\n console.log('pin', loadedMeshes[i])\n }\n else {\n console.log('different mesh', loadedMeshes[i])\n }\n }\n }\n }, null, null, ext)\n }\n })\n\n filesInput.loadFiles(event)\n }",
"createEvents() {\n this.slider.addEventListener(this.deviceEvents.down, this.eventStartAll);\n window.addEventListener('resize', this.eventResize);\n }",
"function WorldEvent() {\r\n this.next = [];\r\n this.cellRange = new CellRange(0, 0, -1, -1);\r\n\r\n // This is a vector along which collision acceleration should be applied,\r\n // for default elastic collision resolution.\r\n this.collisionVec = new Vec2d();\r\n this.reset();\r\n}",
"registerSafeframeHost() {\n devAssert(this.sentinel_);\n safeframeHosts[this.sentinel_] = safeframeHosts[this.sentinel_] || this;\n if (!safeframeListenerCreated_) {\n safeframeListenerCreated_ = true;\n this.win_.addEventListener('message', safeframeListener, false);\n }\n }",
"async listen() {\n const contract = await this.getContract();\n contract.on('Claimed', async (vendor, phone, amount) => {\n try {\n const otp = Math.floor(1000 + Math.random() * 9000);\n const data = await this.setHashToChain(contract, vendor, phone.toString(), otp.toString());\n\n const message = `A vendor is requesting ${amount} token from your account. If you agree, please provide this OTP to vendor: ${otp}`;\n // eslint-disable-next-line global-require\n const sms = require(`./plugins/sms/${config.get('plugins.sms.service')}`);\n\n // call SMS function from plugins to send SMS to beneficiary\n sms(phone.toString(), message);\n } catch (e) {\n console.log(e);\n }\n });\n console.log('--- Listening to Blockchain Events ----');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
rootNode: calculation of root entropy Note: target value should be binary (0/1) Example: rootNode(obj, "target") | function rootNode(obj, target_var){
var pos = 0;
var neg = 0;
for(var i = 0; i < obj.length; i++){
if(obj[i][target_var] == 1){
pos = pos + 1;
} else {
neg = neg + 1;
}
}
tot = pos + neg;
pos1 = Math.log2(pos/tot)*pos/tot
neg1 = Math.log2(neg/tot)*neg/tot
if(isNaN(pos1) || !isFinite(pos1)){
pos1 = 0
}
if(isNaN(neg1) || !isFinite(neg1)){
neg1 = 0
}
return -(pos1 + neg1);
} | [
"constructor(){ // Definindo construtor da classe BinaryTree\n this.root = null; // inicializa a raiz da arvore como sendo nula\n }",
"function TrueNode() {\n}",
"function giniIndex(obj, target_var, input_var){\n \n rootEnt = rootNode(obj,target_var);\n\n //Variable breakage\n if(typeof(obj[input_var]==\"number\")){\n console.log(\"it's a number!\");\n x = unique(obj,input_var).sort();\n console.log(x);\n \n //Count aboves and belows\n info_gain = [];\n for(var k = 0; k < x.length; k++){ //use x-vals as thresholds\n\n var pos_above = 0;\n var neg_above = 0;\n var pos_below = 0;\n var neg_below = 0;\n var n_above = 0;\n var n_below = 0;\n \n for(var i = 0; i < obj.length; i++){ // go through each row\n \n if(obj[i][input_var] >= x[k]){\n \n n_above = n_above + 1;\n \n if(obj[i][target_var]>0){\n pos_above = pos_above + 1;\n } else{\n neg_above = neg_above + 1;\n }\n \n } else {\n n_below = n_below + 1;\n \n if(obj[i][target_var]>0){\n pos_below = pos_below + 1\n } else{\n neg_below = neg_below + 1\n }\n }\n \n //Calculate weighted entropy \n n = n_above + n_below;\n pos1 = Math.log2(pos_above/n_above)*pos_above/n_above;\n neg1 = Math.log2(neg_above/n_above)*neg_above/n_above;\n pos2 = Math.log2(pos_below/n_below)*pos_below/n_below;\n neg2 = Math.log2(neg_below/n_below)*neg_below/n_below;\n \n //Check for NaN or Infine Errors\n if(isNaN(pos1) || !isFinite(pos1)){\n pos1 = 0;\n }\n if(isNaN(pos2) || !isFinite(pos2)){\n pos2 = 0;\n }\n if(isNaN(neg2) || !isFinite(neg2)){\n neg2 = 0;\n }\n if(isNaN(neg1) || !isFinite(neg1)){\n neg1 = 0;\n }\n }\n gini= rootEnt - (n_above/n)*(pos1 + neg1) - (n_below/n)*(pos2 + neg2) ; \n console.log(gini);\n info_gain.push(gini);\n }\n\n //Returns value\n return {\"var_name\":input_var,\"optimal\": x[info_gain.indexOf(min(info_gain))], \"info_gain\":min(info_gain)} ;\n }\n}",
"function nodeValue(tree) {\n let retval = 0;\n let children = tree.children;\n let metadata = tree.metadata;\n\n if (tree.children.length === 0) {\n retval = sumMetadata(tree);\n } else {\n for (let meta of metadata) {\n if (meta > children.length || meta === 0) continue;\n let step = children[meta-1];\n retval = retval + nodeValue(step);\n }\n }\n return retval;\n}",
"initTree() {\n // var format=function(features){features.forEach(p=>{console.log(`{id:${new Number(p.properties.nid)}, x:${new Number(p.geometry.coordinates[1])}, y: ${new Number(p.geometry.coordinates[0])}},`)});}\n this._tree = new KDBush(this._points, p => Math.round(p.x), p => Math.round(p.y), 64, Int32Array);\n }",
"function makeTree() {\r\n // fragments for the aside on the right\r\n var aside = document.createElement(\"aside\");\r\n aside.id = \"treeBox\";\r\n aside.innerHTML = \"<h1>Node Tree</h1>\";\r\n\r\n // inserts the aside into the document inside the main article\r\n var sectionMain = document.getElementById(\"main\");\r\n sectionMain.appendChild(aside);\r\n\r\n // creates the list for the aside\r\n var nodeList = document.createElement(\"ol\")\r\n aside.appendChild(nodeList);\r\n\r\n // sets the article that will be used as a source (the book says to use querySelectorAll() but that breaks everything)\r\n var sourceArticle = document.querySelector(\"#main article\");\r\n\r\n // runs the make branches function for the aside\r\n makeBranches(sourceArticle, nodeList);\r\n\r\n // displays the number of differenet types of nodes within the page\r\n document.getElementById(\"totalNodes\").textContent = nodeCount;\r\n document.getElementById(\"elemNodes\").textContent = elemCount;\r\n document.getElementById(\"textNodes\").textContent = textCount;\r\n document.getElementById(\"wsNodes\").textContent = wsCount;\r\n}",
"get topNode() {\n return new TreeNode(this, 0, 0, null)\n }",
"computeNodeBytes() {\n return sizeof(this.value) + 160;\n }",
"term() {\n let node = this.factor();\n while (\n this.currentToken.type === tokens.mul ||\n this.currentToken.type === tokens.DIV ||\n this.currentToken.type === tokens.floatDiv\n ) {\n const token = this.currentToken;\n if (token.type === tokens.mul) {\n this.eat(tokens.mul);\n } else if (token.type === tokens.DIV) {\n this.eat(tokens.DIV);\n } else if (token.type === tokens.floatDiv) {\n this.eat(tokens.floatDiv);\n }\n\n node = new BinOp(node, token, this.factor());\n }\n\n return node;\n }",
"function createAVL() {\n root = null;\n var inputArray = document.getElementById(\"inputArray\").value.split(\",\");\n for (let i = 0; i < inputArray.length; i++) { // convert sstring array to number array\n inputArray[i] = parseInt(inputArray[i]);\n }\n\n // Create a root node and tree\n for (let value of inputArray) {\n root = insertValue(root, value);\n }\n\n document.getElementById(\"onorderTraverse\").innerText = inorderTraversal(root, []);\n document.getElementById(\"preOrderTraverse\").innerText = preOrderTraversal(root, []);\n}",
"function wrapTree(target){ \n\t\tvar tree = $(target); \n\t\ttree.addClass('tree'); \n\t\t \n\t\twrapNode(tree, 0); \n\t\t \n\t\tfunction wrapNode(ul, depth){ \n\t\t\t$('>li', ul).each(function(){ \n\t\t\t\tvar node = $('<div class=\"tree-node\"></div>').prependTo($(this)); \n\t\t\t\tvar text = $('>span', this).addClass('tree-title').appendTo(node).text(); \n\t\t\t\t$.data(node[0], 'tree-node', { \n\t\t\t\t\ttext: text \n\t\t\t\t}); \n\t\t\t\tvar subTree = $('>ul', this); \n\t\t\t\tif (subTree.length){ \n\t\t\t\t\t$('<span class=\"tree-folder tree-folder-open\"></span>').prependTo(node); \n\t\t\t\t\t$('<span class=\"tree-hit tree-expanded\"></span>').prependTo(node); \n\t\t\t\t\twrapNode(subTree, depth+1); \n\t\t\t\t} else { \n\t\t\t\t\t$('<span class=\"tree-file\"></span>').prependTo(node); \n\t\t\t\t\t$('<span class=\"tree-indent\"></span>').prependTo(node); \n\t\t\t\t} \n\t\t\t\tfor(var i=0; i<depth; i++){ \n\t\t\t\t\t$('<span class=\"tree-indent\"></span>').prependTo(node); \n\t\t\t\t} \n\t\t\t}); \n\t\t} \n\t\treturn tree; \n\t}",
"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 Tree(numNodes, nodeList, edgeProbs){\n\n\t//properties\n\n\t//number of nodes in the tree\n\tthis.numNodes = numNodes;\n\n\t//list of nodes in the tree (of type Node)\n\tthis.nodeList = nodeList;\n\n\t//2-D array of the different edge probabilities\n\t//edgeProbs[i] = [startNode, endNode, probability]\n\t//where i is some index, start node is the node where\n\t//the directed edge start, end node is the node where\n\t//the directed edge ends, and probability is between 0 and 1\n\tthis.edgeProbs = edgeProbs;\n\n\t/**\n\t\tget the node associated with a given id\n\t*/\n\tthis.getNodeById = function(theId){\n\t\tvar node;\n\t\tfor(var i = 0; i < this.numNodes; i++){\n\t\t\tif(this.nodeList[i].nodeId === theId){\n\t\t\t\treturn nodeList[i];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t\tget the node associated with a given label\n\t*/\n\tthis.getNodeByLabel = function(theLabel){\n\t\tvar node;\n\t\tfor(var i = 0; i < this.numNodes; i++){\n\t\t\tif(this.nodeList[i].nodeLabel === theLabel){\n\t\t\t\treturn nodeList[i];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t\tget the node id associated with a given label\n\t*/\n\tthis.getNodeIdByLabel = function(theLabel){\n\t\tfor(var i = 0; i < this.numNodes; i++){\n\t\t\tif(this.nodeList[i].nodeLabel === theLabel){\n\t\t\t\treturn nodeList[i].nodeId;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tthis.getNodeLabelById = function(theId){\n\t\tfor(var i = 0; i < this.numNodes; i++){\n\t\t\tif(this.nodeList[i].nodeId === theId){\n\t\t\t\treturn nodeList[i].nodeLabel;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t\tget the proability can go from idStart to idEnd\n\t*/\n\tthis.getDirectedProbabilityByIds = function (idStart, idEnd){\n\t\tvar labelStart = this.getNodeLabelById(idStart);\n\t\tvar labelEnd = this.getNodeLabelById(idEnd);\n\t\tfor(var i = 0; i < this.edgeProbs.length; i++){\n\t\t\tif(this.edgeProbs[i][0] === labelStart &&\n\t\t\t\tthis.edgeProbs[i][1] === labelEnd){\n\t\t\t\treturn this.edgeProbs[i][2];\n\t\t\t}\n\t\t}\n\t}\n}",
"tree() {\n return trie;\n }",
"function encode_root(v) {\n return v;\n }",
"function root() {\n return _root; \n }",
"rebuildTreeIndex() {\n let columnIndex = 0;\n\n this.#rootsIndex.clear();\n\n arrayEach(this.#rootNodes, ([, { data: { colspan } }]) => {\n // Map tree range (colspan range/width) into visual column index of the root node.\n for (let i = columnIndex; i < columnIndex + colspan; i++) {\n this.#rootsIndex.set(i, columnIndex);\n }\n\n columnIndex += colspan;\n });\n }",
"function createTree(x) {\n\t// Create the root\n\tvar a = createVector(width / 2, height);\n\tvar b = createVector(width / 2, height - 100);\n\ttree = new Tree(a, b);\n\n\t// Create the branches\n\tcreateXGenerations(x);\n}",
"static testGetValue() {\n let tree = new HuffTree(0);\n let testCnt = 0;\n let errCnt = 0;\n\n function runInsertTest(level, value, expected) {\n let val = tree.insertCode(level, value);\n testCnt++;\n if (val != expected) {\n console.error(\"Test \" + testCnt + \" Failed (expected \" + expected + \", got \" + val + \")\");\n errCnt++;\n }\n }\n\n runInsertTest(3, 4, true);\n runInsertTest(3, 5, true);\n runInsertTest(3, 3, true);\n runInsertTest(3, 2, true);\n runInsertTest(3, 6, true);\n runInsertTest(3, 1, true);\n runInsertTest(3, 0, true);\n // We shouldn't be able to insert an 8th node at L3, \n // but the tree currently has no way of knowing this\n // since nodes don't know the state of other nodes.\n // For this to be a problem in practice, the JPEG\n // file would have to be out-of-spec/corrupt\n //runInsertTest(3, 12, false); // Too many nodes in tree\n runInsertTest(4, 7, true);\n runInsertTest(5, 8, true);\n runInsertTest(6, 9, true);\n runInsertTest(7, 10, true);\n runInsertTest(8, 11, true);\n \n function runGetTest(input, expected) {\n let val = tree.getValue(input);\n testCnt++;\n if (val != expected) {\n console.error(\"Test \" + testCnt + \" Failed (expected \" + expected + \", got \" + val + \")\");\n errCnt++;\n }\n }\n\n runGetTest(\"000\", 4);\n runGetTest(\"001\", 5);\n runGetTest(\"010\", 3);\n runGetTest(\"011\", 2);\n runGetTest(\"100\", 6);\n runGetTest(\"101\", 1);\n runGetTest(\"110\", 0);\n runGetTest(\"1110\", 7);\n runGetTest(\"11110\", 8);\n runGetTest(\"111110\", 9);\n runGetTest(\"1111110\", 10);\n runGetTest(\"11111110\", 11);\n\n // Sequence not in the table\n runGetTest(\"11111111\", undefined);\n\n const testName = \"HuffTree.getValue\";\n if (errCnt === 0) {\n console.log(testName + \"tests passed!\");\n } else {\n console.error(testName + \"tests failed: \" + errCnt + \" errors\");\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles the user clicking the highlight edit menu item. | function menuHighlightClick() {
Data.Edit.Mode = EditModes.Highlight;
updateMenu();
} | [
"function menuEditClick() {\n Data.Edit.Open = !Data.Edit.Open;\n setEditMenuPosition();\n\n if (Data.Edit.Open) {\n if (Data.Edit.LastMode)\n Data.Edit.Mode = Data.Edit.LastMode;\n } else {\n Data.Edit.LastMode = Data.Edit.Mode;\n Data.Edit.Mode = EditModes.Off;\n }\n updateMenu();\n\n if (Data.Edit.Open && Data.Controls.Open) {\n Data.Controls.Open = false;\n setControlsPosition();\n }\n}",
"function theClickedItem(item) {\n setHighlightItem(item);\n }",
"function on_edit_button_click(){\n\t\tif ($(this).text()=='Edit'){\n\t\t\t$(\"#middle\").find(\"button.edit\").text('Edit')\n\t\t\t\t.siblings('span').hide()\n\t\t\t\t.siblings('span.value').show();\n\n\t\t\t$(this).siblings('span').show()\n\t\t \t\t\t .siblings('span.value').hide();\n\t\t\t$(this).text('Cancel');\n\t\t} else {\n\t\t\t$(this).siblings('span').hide().siblings('span.value').show();\n\t\t\t$(this).text('Edit');\n\t\t}\n}",
"editCornerViewClick () {\n this.deselectAllTabs();\n\n this.editCornerViewTab.className = \"WallEditor_EditCornerViewTab selected\";\n this.viewController = this.editCornerView;\n\n this.selectCurrentTab();\n }",
"function editElement(event){\n\t\t\t\t\tclickedItem.innerHTML = textBox.value;\n\t\t\t\t}",
"handleSelectedEdited(item){\n\n\t\t//if this is the currently selected object, let's fire our change event\n\t\tif(item.ID == this.selectedClassItem)\n\t\t\tthis.eventSelectionEdited.fire(item);\n\t}",
"function menuTextClick() {\n Data.Edit.Mode = EditModes.Text;\n updateMenu();\n}",
"editPointViewClick() {\n this.deselectAllTabs();\n\n this.editPointViewTab.className = \"WallEditor_EditPointViewTab selected\";\n this.viewController = this.editPointView;\n\n this.selectCurrentTab();\n }",
"function onEntryAction(evt) {\n if ($(this).hasClass(\"edit\")) {\n zdPage.navigate(\"edit/existing/\" + $(this).data(\"entry-id\"));\n //window.open(\"/\" + zdPage.getLang() + \"/edit/existing/\" + $(this).data(\"entry-id\"));\n }\n }",
"function handleEdit(event,ele){\n event.preventDefault();\n setEditing(true);\n setCurrentBlog(ele);\n\n }",
"function handleRecipeEdit() {\n var currentRecipe = $(this)\n .parent()\n .parent()\n .data(\"recipe\");\n window.location.href = \"/recipe?userId=\" + data.userId + \"&recipeId=\" + recipe.id;\n }",
"function DoEditSCWorkItem_clicked(newitemid) {\n ModalWorkItem = new C_WorkLog(null);\n ModalNewWorkItem = newitemid === -1;\n if (newitemid !== -1) {\n ModalWorkItem = BackendHelper.FindWorkItem(newitemid);\n }\n else {\n ModalWorkItem.UserId = OurUser.id;\n ModalWorkItem.Date = C_YMD.Now();\n }\n\n // build a dropdown of users to select from\n let vol = BackendHelper.FindAllVolunteers();\n vol.sort(function (a, b) {\n return a.Name.localeCompare(b.Name);\n });\n\n let usersChoices = [];\n vol.forEach(function (u) {\n let c = { \"text\": u.Name, \"item\" : u.id.toString() };\n usersChoices.push(c);\n });\n\n let userselitem = ModalWorkItem.UserId.toString();\n\n let usersOptions = {\n \"choices\": usersChoices,\n \"selitem\" : userselitem,\n \"dropdownid\" : \"vitasa_dropdown_users\",\n \"buttonid\" : \"vitasa_button_selectuser\"\n };\n usersDropDown = new C_DropdownHelper(usersOptions); // this must be in the global space\n usersDropDown.SetHelper(\"usersDropDown\");\n usersDropDown.CreateDropdown();\n\n BackendHelper.Filter.CalendarDate = ModalWorkItem.Date;\n $('#vitasa_scvolhours_edit_date_i')[0].value = ModalWorkItem.Date.toStringFormat(\"mmm dd, yyyy\");\n $('#vitasa_workitem_hours')[0].value = ModalWorkItem.Hours.toString();\n $('#vitasa_modal_scvolhours_sitename')[0].innerText = OurSite.Name;\n $('#vitasa_modal_title').innerText = \"Work Item\";\n\n DrawSCVolHoursCalendar();\n\n $('#vitasa_modal_scworkitem').modal({});\n\n BackendHelper.SaveFilter()\n .catch(function (error) {\n console.log(error);\n })\n}",
"_onHandlerClick(id, e) {\n\t\tthis.dispatchEvent(\n\t\t\tnew CustomEvent(\"selected-color\", { bubbles: false, detail: { id } })\n\t\t);\n\t}",
"function onClickOid(e)\n{\n\tvar row = this.data[0];\n\tvar item = convertOid(row[0],row[1]);\n\t//if (item)\n\t{\n\t\titemlist.appendData(item);\n\t\tEvent.element(e).setStyle('background-color: #ACCEDE');\n\t}\n}",
"function menuTooltipClick() {\n Data.Edit.Mode = EditModes.Notes;\n updateMenu();\n}",
"handleEdit(event) {\n console.log('inside handleEdit');\n this.displayMode = 'Edit';\n }",
"function handleClick (e) {\n if (e.target.matches('input')) {\n let index = e.target.dataset.index;\n let item = this.querySelector(`.item${index}`)\n item.classList.toggle('completed');\n if(item.classList.contains('completed')){\n showNotification('completed');\n }\n toggleCompleted(todos, index);\n localStorage.setItem('todos', JSON.stringify(todos));\n } else if (e.target.matches('.edit-button')){\n let index = e.target.dataset.index;\n let item = todos[index];\n toggleEditModal();\n populateEditForm(index, item, projects);\n } else if (e.target.matches('.expand-button')){\n let item = e.target;\n let parent = item.parentNode;\n let details = parent.parentNode.querySelector('.details');\n details.classList.toggle('expand-details');\n }\n}",
"function doubleClick(e) {\n edit_reservation($(this));\n}",
"edit() {\n\t\tvar value = this.input.val();\n\n\t\tthis.$el.addClass('editing');\n\t\tthis.input.val(value).focus();\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
for checking expiry of proposals contract function will delete proposal for you | function isExpired() {
ballotContract.IsProposalExpired((error, result) => {
logCatcher('is proposal expired has just been called');
setTimeout(() => {
// recursively check every 9 seconds. in the future make this a day.
isExpired();
}, 9000);
});
} | [
"function proposalDeleteConfirmation(){\n\t\t$(\".proposal_delete\").click(function(e){\t\n\t\t\tswal({\n\t title: 'Are you sure?',\n\t text: \"Deleting Proposal Slip\",\n\t icon: 'warning',\n\t buttons:{\n\t confirm: {\n\t text : 'Delete',\n\t className : 'btn btn-danger'\n\t },\n\t cancel: {\n\t visible: true,\n\t className: 'btn btn-info'\n\t }\n\t }\t\n\t }).then((Delete) => {\n\t if (Delete) {\n\t \tvar id = $(this).attr(\"id\");\n\t\t\t\t\tproposalDelete(id);\n\t }\n\t });\n\t\t});\n\t}",
"function validateDelete(type) {\n if (type == 'new_services') {\n if (confirm(\"Are you sure you want to delete this item?\\n\\nThis action cannot be undone.\")) {\n var item_name = nlapiGetCurrentLineItemValue(type, 'new_item');\n var item_package = nlapiGetCurrentLineItemValue(type, 'new_item_package');\n if (item_name == 17 && !isNullorEmpty(item_package)) {\n discount_created[item_package] = 'F';\n }\n if (!isNullorEmpty(nlapiGetCurrentLineItemValue(type, 'new_servicesinternalid'))) {\n\n //Inactive the service record on remove\n\n var service_record_id = nlapiGetCurrentLineItemValue(type, 'new_servicesinternalid');\n\n var service_record = nlapiLoadRecord('customrecord_service', service_record_id);\n\n service_record.setFieldValue('isinactive', 'T');\n\n nlapiSubmitRecord(service_record);\n }\n return true;\n } else {\n return false;\n }\n }\n}",
"function deleteExpiredContacts(cb) {\n console.log('INFO: delete expired contacts');\n var stream = Contact.find({'expires': true}).stream();\n\n stream.on('data', function(contact) {\n if (contact.isExpired()) {\n contact.remove();\n }\n });\n\n stream.on('close', function() {\n cb();\n });\n}",
"function para_del(name) {\n\tif (confirm(\"Do you want to delete this parameter?\")) {\n\t\tpara.remove(\"task='\" + document.getElementById('task').value + \"' and name='\" + name + \"'\");\n\t\tpara_fetch();\n\t\t$('#' + name.replace(/[^a-zA-Z 0-9]+/g, '').replace(/\\s+/g, \"\")).remove();\n\t\ttot();\n\t}\n}",
"function deletePubKey() {\n ctrl.pubKey.$remove(\n {id: ctrl.pubKey.id},\n function() {\n raiseAlert('success',\n '', 'Public key deleted successfully');\n $uibModalInstance.close(ctrl.pubKey.id);\n },\n function(httpResp) {\n raiseAlert('danger',\n httpResp.statusText, httpResp.data.title);\n ctrl.cancel();\n }\n );\n }",
"function deleteExpiredProfiles(cb) {\n console.log('INFO: delete expired profiles');\n var stream = Profile.find({'expires': true}).stream();\n\n stream.on('data', function(profile) {\n if (profile.isExpired()) {\n profile.remove();\n }\n });\n\n stream.on('close', function() {\n cb();\n });\n}",
"function expire(doc, cb_expire) {\n\t\t\tconst lc_status = (doc && doc.status) ? doc.status.toLowerCase() : null;\n\t\t\tif (lc_status === 'pending' && t.webhook.webhook_is_expired(doc)) {\t// see if its expired but the doc is not updated yet\n\t\t\t\tt.webhook.expire_webhook(req.params.tx_id, (error, new_doc) => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treturn cb_expire(error, null);\t\t\t\t\t\t\t// could not edit the webhook for some reason\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn cb_expire(null, new_doc);\t\t\t\t\t\t// webhook is expired and doc is now updated\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\treturn cb_expire(null, doc);\t\t\t\t\t\t\t\t\t// webhook is good\n\t\t\t}\n\t\t}",
"function mentorDeclineMeetingRequest() {\n return confirm(\"Are you sure you want to decline a meeting request from this mentee?. No record at this stage will be kept.\")\n}",
"createProposal(parameters = false, issuerAddress = this.tronWeb.defaultAddress.hex, callback = false) {\n if(utils.isFunction(issuerAddress)) {\n callback = issuerAddress;\n issuerAddress = this.tronWeb.defaultAddress.hex;\n }\n\n if(!parameters)\n return callback('Invalid proposal parameters provided');\n\n if(!callback)\n return this.injectPromise(this.createProposal, parameters, issuerAddress);\n\n if(!this.tronWeb.isAddress(issuerAddress))\n return callback('Invalid issuerAddress provided');\n\n if(!utils.isObject(parameters))\n return callback('Invalid parameters provided');\n\n this.tronWeb.fullNode.request('wallet/proposalcreate', {\n owner_address: this.tronWeb.address.toHex(issuerAddress),\n parameters: parameters\n }, 'post').then(transaction => {\n if(transaction.Error)\n return callback(transaction.Error);\n\n if(transaction.result && transaction.result.message) {\n return callback(\n this.tronWeb.toUtf8(transaction.result.message)\n );\n }\n\n callback(null, transaction);\n }).catch(err => callback(err));\n }",
"removeValidationRequest(address){\r\n //removes item in index reference array and mempool array\r\n let indexToFind = this.walletList[address];\r\n delete this.walletList[address];\r\n delete this.mempool[indexToFind];\r\n\r\n //clear timeouts\r\n clearTimeout(this.timeoutRequests[address]);\r\n delete this.timeoutRequests[address]\r\n }",
"deletePolicy(callback) {\n return this.deletePolicyRequest().sign().send(callback);\n }",
"toggleApproval(currency, current_approval) {\n let new_approval = !current_approval\n if(new_approval) {\n this.approveCurrency(currency)\n } else {\n this.unapproveCurrency(currency)\n }\n }",
"function getProposalsAndAwards(next) {\n\tdb.sequelize.query('SELECT p.id, p.Year, p.Number, p.ProposalTitle, p.Category, p.Department, p.Status, SUM(i.Price * i.Quantity) as Requested, a.FundedAmount FROM STF.Proposals p LEFT JOIN STF.Awards a ON p.id = a.ProposalId LEFT JOIN STF.Items i ON p.id = i.Proposalid WHERE (p.Status = 4 OR p.Status = 5 OR p.Status = 6) AND (i.PartialId IS NULL AND i.SupplementalId IS NULL) GROUP BY p.id;')\n\t.spread(function(proposals) {\n\t\tvar props = [];\n\t\tvar year = 2016;\n\t\tfor(proposal in proposals) {\n\t\t\tvar p = {};\n\t\t\tif(year != proposals[proposal].Year) {\n\t\t\t\ti++;\n\t\t\t\tyear++;\n\t\t\t\tyear_proposal[i] = [];\n\t\t\t}\n\t\t\tp.Year = proposals[proposal].Year;\n\t\t\tp.Number = proposals[proposal].Number;\n\t\t\t//p.UAC = proposals[proposal].UAC;\n\t\t\tp.Category = proposals[proposal].Category;\n\t\t\tp.Requested = proposals[proposal].Requested;\n\t\t\t// p.PrimaryNetId = proposals[proposal].PrimaryNetId;\n\t\t\t// p.PrimaryName = proposals[proposal].PrimaryName;\n\t\t\tp.Department = proposals[proposal].Department;\n\t\t\tif(proposals[proposal].Status == 4) {\n\t\t\t\tp.Decision = \"Funded\";\n\t\t\t} else if(proposals[proposal].Status == 5) {\n\t\t\t\tp.Decision = \"Partially Funded\";\n\t\t\t} else if(proposals[proposal].Status == 6) {\n\t\t\t\tp.Decision = \"Not Funded\";\n\t\t\t}\n\t\t\t\n\t\t\tif(proposals[proposal].FundedAmount) {\n\t\t\t\tp.Award = proposals[proposal].FundedAmount;\n\t\t\t} else {\n\t\t\t\tp.Award = 0;\n\t\t\t}\n\t\t\tprops.push(p);\n\t\t}\n\t\tnext(props);\n\t})\n}",
"requestProposal (projectId, proposalId) {\n\n\t\t\tlet proposalKey = deriveProposalId(githubOrgName, projectId, proposalId),\n\t\t\t\tproposal;\n\n\t\t\tstore.dispatch({\n\t\t\t\ttype: PROPOSAL_REQUESTED,\n\t\t\t\tmeta: { proposalKey }\n\t\t\t});\n\n\t\t\tlet url = `https://api.github.com/repos/${ githubOrgName }/${ projectId }/pulls/${ proposalId }`,\n\t\t\t\theaders = this.buildAuthHeader().headers;\n\n\t\t\t// add custom Accept header to return reactions\n\t\t\t// per: https://developer.github.com/v3/issues/comments/#reactions-summary\n\t\t\theaders.append('Accept', 'application/vnd.github.squirrel-girl-preview');\n\t\t\theaders = { headers };\n\n\t\t\ttransport.request(url, this.parseProposal, headers)\n\t\t\t.then(response => {\n\n\t\t\t\tproposal = { ...response };\n\n\t\t\t\treturn transport.request(proposal.commits_url, this.parseProposal, headers);\n\n\t\t\t})\n\t\t\t.then(response => {\n\n\t\t\t\tproposal.commits = response;\n\n\t\t\t\treturn transport.request(proposal.comments_url, this.parseProposal, headers);\n\t\t\t\t\n\t\t\t})\n\t\t\t.then(response => {\n\n\t\t\t\tproposal.comments = response;\n\n\t\t\t\turl = `https://api.github.com/repos/${ githubOrgName }/${ projectId }/issues/${ proposalId }/reactions`;\n\t\t\t\treturn transport.request(url, this.parseProposal, headers);\n\t\t\t\t\n\t\t\t})\n\t\t\t.then(response => {\n\n\t\t\t\tproposal.reactions = response;\n\n\t\t\t\tstore.dispatch({\n\t\t\t\t\ttype: PROPOSAL_RESPONDED,\n\t\t\t\t\tmeta: { proposalKey },\n\t\t\t\t\tpayload: proposal\n\t\t\t\t});\n\n\t\t\t})\n\t\t\t.catch(error => {\n\t\t\t\tthis.handleError(error);\n\t\t\t\tstore.dispatch({\n\t\t\t\t\ttype: PROPOSAL_RESPONDED,\n\t\t\t\t\tmeta: { proposalKey },\n\t\t\t\t\terror: error\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t});\n\n\t\t}",
"async function reclaimExchangeTx(contract, targetAddress, amount) {\n return await contract.functions\n .reclaim(wallet.bob.publicKey, new SignatureTemplate(wallet.bob.privateKey))\n .to(targetAddress, amount)\n .withFeePerByte(1)\n .send()\n}",
"deleteEmail() {\n\n \n switch (this.view) {\n\n // move item to trash\n case \"inbox\":\n this.$set(this.selectedEmail, \"deleted\", true);\n this.selectedEmail = \"\";\n break;\n // move item back from trash to inbox\n case \"trash\":\n this.$set(this.selectedEmail, \"deleted\", false);\n this.selectedEmail = \"\";\n break;\n }\n }",
"async function reschedulePriceCheck() {\n const highestDebtRatio = sortedVaultKits.highestRatio();\n if (!highestDebtRatio) {\n // if there aren't any open vaults, we don't need an outstanding RFQ.\n return;\n }\n\n const liquidationMargin = shared.getLiquidationMargin();\n\n // ask to be alerted when the price level falls enough that the vault\n // with the highest debt to collateral ratio will no longer be valued at the\n // liquidationMargin above its debt.\n const triggerPoint = multiplyBy(\n highestDebtRatio.numerator,\n liquidationMargin,\n );\n\n // if there's an outstanding quote, reset the level. If there's no current\n // quote (because this is the first loan, or because a quote just resolved)\n // then make a new request to the priceAuthority, and when it resolves,\n // liquidate anything that's above the price level.\n if (outstandingQuote) {\n E(outstandingQuote).updateLevel(\n highestDebtRatio.denominator,\n triggerPoint,\n );\n return;\n }\n\n outstandingQuote = await E(priceAuthority).mutableQuoteWhenLT(\n highestDebtRatio.denominator,\n triggerPoint,\n );\n\n // There are two awaits in a row here. The first gets a mutableQuote object\n // relatively quickly from the PriceAuthority. The second schedules a\n // callback that may not fire until much later.\n // Callers shouldn't expect a response from this function.\n const quote = await E(outstandingQuote).getPromise();\n // When we receive a quote, we liquidate all the vaults that don't have\n // sufficient collateral, (even if the trigger was set for a different\n // level) because we use the actual price ratio plus margin here.\n const quoteRatioPlusMargin = makeRatioFromAmounts(\n divideBy(getAmountOut(quote), liquidationMargin),\n getAmountIn(quote),\n );\n\n sortedVaultKits.forEachRatioGTE(quoteRatioPlusMargin, ({ vaultKit }) => {\n trace('liquidating', vaultKit.vaultSeat.getProposal());\n\n liquidate(\n zcf,\n vaultKit,\n runMint.burnLosses,\n liquidationStrategy,\n collateralBrand,\n );\n });\n outstandingQuote = undefined;\n reschedulePriceCheck();\n }",
"async destroy ({ params, auth, response }) {\n const establishments = await Establishments.findOrFail(params.id)\n\n if (establishments.user_id !== auth.user.id) {\n return response.status(401).send({ error: 'Not authorized' })\n }\n\n await establishments.delete()\n }",
"checkAvailableMessages() {\n let curDate = new Date();\n\n for (let i = 0; i < this.processing.length; i++) {\n let ttl = this.processing[i].ttl;\n if (curDate > ttl) {\n let message = this.processing.splice(i, 1);\n i--; // we are removing an element from the array and so don't want to increment\n this.store.push(message);\n }\n }\n }",
"function deleteDebtByID(token, debtID) {\n try {\n var userData = validateToken(token);\n var userEmail = userData.email;\n var createQuery = 'DELETE FROM Debts WHERE email=? AND debtID=?;';\n var parameters = [userEmail, debtID];\n executeManipulationQuery(createQuery, parameters);\n return \"Success\";\n }\n catch (err) {\n throw new Error( \"Error deleting debt!\" );\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find ID in DRUM_COMBO array | function getDrumComboId(inputArray){
if (inputArray.length == 0) return 0;
inputArray.sort();
for (let i = 0; i < DRUM_COMBOS.length; i++){
if (DRUM_COMBOS[i].length == inputArray.length &&
DRUM_COMBOS[i].every((val, index) => val === inputArray[index]))
return i + 1; // 0 is for empty
}
console.error("Something wrong with drum id", inputArray);
return -1; // error
} | [
"function findIndexInDidArrayMatchingSelection() {\t\n\t\tvar i=0;\n\t\twhile(i<detailIdJson.did_array.length) {\n\t\t\tif(detailIdJson.did_array[i].color==self.color() &&\n\t\t\t detailIdJson.did_array[i].size ==self.size() &&\n\t\t\t detailIdJson.did_array[i].sex ==self.sex() )\n\t\t\t\tbreak;\n\t\t\ti++;\n\t\t}\n\t\tif(i==detailIdJson.did_array.length)\n\t\t{\n\t\t\treturn -1;\n\t\t} else {\n\t\t\treturn i;\n\t\t}\t\n\t}",
"function searchForIdInArray(id,array){\n var returnValue;\n var position;\n\n (DEBUG || ALL ) && console.debug(\"Searching for id\",id,\"in\",array);\n for (position = 0; position < array.length; position++) {\n if (array[position].keyID === id) {\n returnValue = array[position];\n (DEBUG || ALL) && console.log(\"found!\");\n break;\n }\n }\n return returnValue;\n }",
"getIndex(id, data){\n for(let i=0; i<data.length; i++){\n if(id === data[i].id){\n return i;\n }\n }\n console.log(\"No match found\");\n return 0;\n }",
"function checkIfVehicleExists(vehicle, array) {\n for (var i = 0; i < array.length; i++) {\n if (vehicle.shortIdentifier == array[i].shortIdentifier) {\n return i;\n }\n }\n return -1;\n}",
"function findTruckWithID (truckID) {\n\tif(isArrayEmpty(localTruckArray)) return -2; // aey - if no trucks\n\tfor(let i = 0; i < localTruckArray.length; i++) {\n\t\tif(localTruckArray[i].id == truckID) return i; // aey - id was found, return where it was found\n\t}\n\treturn -1;\n}",
"function getIndexOfId(list, item) {\n return list.map(function(e) {\n return e.ID;\n }).indexOf(item);\n}",
"function getUniqueValue(variable_sys_id) {\n var values=[];\n\tvar ids = [];\n\tvar a = [];\n var gr = new GlideRecord('sc_item_option');\n gr.addQuery('item_option_new', variable_sys_id);\n gr.orderBy('value');\n gr.query();\n while (gr.next()){\n values.push(gr.getValue('value'));\n ids.push(gr.getValue('sys_id'));\n }\n\t\n var l = values.length;\n for (var i = 0; i < l; i++) {\n for (var j = i + 1; j < l; j++) {\n if (values[i] === values[j])\n j = ++i;\n }\n a.push(ids[i]);\n }\n return a;\n}",
"function findSelectorFullInfo(woid) {\n console.log(\"findSelectorFullInfo\", woid);\n console.log(\"findSelectorFullInfo selectData\", $scope.selectData);\n for (var i = 0; i < $scope.selectData.length; i++) {\n if ($scope.selectData[i]['woid'] == woid) {\n return $scope.selectData[i];\n }\n }\n }",
"function promptengine_findOptionInList(selectObj, optionValue)\r\n{\t\r\n if (selectObj == null || optionValue == null || optionValue == \"\")\r\n return -1;\r\n\t\r\n for (var i = 0; i < selectObj.options.length; i++)\r\n {\r\n if (selectObj.options[i].value == optionValue)\r\n return i;\r\n }\r\n\r\n return -1;\t\r\n}",
"indexOfId(id) {\n var Model = this.constructor.classes().model;\n var index = 0;\n var result = -1;\n id = String(id);\n\n while (index < this._data.length) {\n var entity = this._data[index];\n if (!(entity instanceof Model)) {\n throw new Error('Error, `indexOfId()` is only available on models.');\n }\n if (String(entity.id()) === id) {\n result = index;\n break;\n }\n index++;\n }\n return result;\n }",
"function getProductByID(productArray, id) {\r\n return productArray.find(function(product){\r\n return product.id == id;\r\n });\r\n}",
"getIdx(key = this.state.rec_key) {\n return this.state.records.findIndex(rec => rec.key === key);\n }",
"static isExistInArray(arr, value, index=0){\n\t\tif( typeof arr === 'object'){\n\t\t\tlet arrList = [];\n\t\t\tforEach( arr, (item, key) => {\n\t\t\t\tif(item.id){\n\t\t\t\t\tarrList.push(item.id);\n\t\t\t\t}\n\t\t\t});\n\t\t\tif(indexOf(arrList, value, index) >= 0){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}",
"function getArrayId(node) \r\n{\r\n\tfor (i=0; i<TreeNodes.length; i++) \r\n\t{\r\n\t\tvar nodeValues = TreeNodes[i].split(\"|\");\r\n\t\tif (nodeValues[0]==node) return i;\r\n\t}\r\n}",
"function finditembyid (id) {\n\tfor (var i = 0; i < food_pickup.length; i++) {\n\t\tif (food_pickup[i].id == id) {\n\t\t\treturn food_pickup[i]; \n\t\t}\n\t}\n\treturn false; \n}",
"function mapIdsToIdx(findIds) {\n var cellIds = self.cellIds;\n\n var notFoundIds = [];\n var idArr = [];\n\n if (hasWildcards) {\n var foundIds = {}; // = set = removes any duplicates\n for (var i=0; i<findIds.length; i++) {\n var searchId = findIds[i];\n var searchRe = new RegExp(searchId);\n var foundOne = false;\n for (var cellIdx = 0; cellIdx<cellIds.length; cellIdx++) {\n var cellId = cellIds[cellIdx];\n if (searchRe.exec(cellId)!==null) {\n foundIds[cellIdx] = null;\n foundOne = true;\n }\n }\n if (!foundOne)\n notFoundIds.push(searchId);\n }\n idArr = cbUtil.keys(foundIds); // convert to array\n idArr.sort();\n }\n else {\n for (let i=0; i<findIds.length; i++) {\n let searchId = findIds[i];\n var foundIdx = cellIds.indexOf(searchId);\n if (foundIdx===-1)\n notFoundIds.push(searchId);\n else\n idArr.push(foundIdx);\n\n }\n }\n return [idArr, notFoundIds];\n }",
"function findInArray(array, attr) {\n for ( let i = 0; i < array.length; i++ ) {\n if ( array[i].Name == attr.toString() ) {\n return i;\n }\n }\n }",
"function _assignValuesToCombo(object) {\n var comboValues = Array();\n\n try {\n for (var i = 0; i < object.comboIds.length; i++) {\n comboValues.push({\n id: object.comboIds[i],\n name: object.comboNames[i]\n });\n }\n\n return comboValues;\n } catch (e) {\n _self.emit(\"log\", \"Search.js\", \"_assignValuesToCombo error formatting combo\", \"error\", e.message);\n\n return false;\n }\n }",
"function game_find_unit_by_number(id)\n{\n return units[id];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Notify subscribers that the query has been updated. | queryUpdated() {
this.emit('core.state.queryUpdated', this)
} | [
"function notifyObservers() {\n _.each(views, function (aView) {\n aView.update();\n });\n } // notifyObservers",
"_registerUpdates() {\n const update = this.updateCachedBalances.bind(this);\n this.accountTracker.store.subscribe(update);\n }",
"function updateSubscribers(id) {\n var $subscribers = $(\"[data-entity=item][data-id='\" + id + \"'] .subscribers\");\n if (!$subscribers.length) {\n return;\n }\n\n $.ajax({\n url: weavy.url.resolve(\"/items/\" + id + \"/subscribers\"),\n method: \"GET\",\n contentType: \"application/json\"\n }).then(function (html) {\n $subscribers.replaceWith(html);\n });\n }",
"updateNotifications(connectionID, metadata) {\n const connection = this.getConnectionByID(connectionID);\n if (!connection) {\n return;\n }\n this.startNotifications(connection, metadata);\n }",
"watchUpdates(periodMS) {\n this.get('page').watchEntryUpdates(this, periodMS);\n }",
"function notify(key) {\n if (notificationsAreBatched) {\n changedPropertyKeys.push(key);\n } else {\n notifyCallbacksOnce(propertyInformation[key].observers);\n }\n } // Note this does not respect batched notifications, as property descriptions are not expected",
"emitUpdatedPublishingItem(publishingItem) {\n publishNamespace.emit(updatedPublishingItemEvent, publishingItem);\n }",
"function update()\n{\n\tq = document.getElementById(\"queries\").value;\n\tyasgui.current().yasqe.setValue(queries[q]);\n}",
"function onUpdate(fromVersion, toVersion) {\n\tconsole.log('Extension has been updated from version ', fromVersion, ' to version ', toVersion);\n}",
"queriesUpdated (neurons) {\n // Check if new list of neurons is the same as the ones already rendered on last update\n var matched = (this.state.neurons.length == neurons.length) && this.state.neurons.every(function (element, index) {\n return element.id === neurons[index].id; \n });\n \n // Request graph update if the list of new neurons is not the same\n if ( !this.state.loading && !matched ) {\n this.updateGraph(neurons, this.state.paths, this.state.weight);\n }\n }",
"static sendUpdatedEvent (model) {\n const PluginHelper = require('../helpers/plugin');\n PluginHelper.events().emit('update', {\n action: 'updated',\n name: 'account',\n model\n });\n }",
"function subscribe(id) {\n weavy.api.follow(\"item\", id).then(function () {\n updateSubscribers(id);\n });\n }",
"_emitServiceStreamDataUpdateEvent ( dataUpdate ) {\n\n super.emit(\n EMITABLE_EVENTS.serviceStreamDataUpdate\n , dataUpdate\n );\n }",
"itemsChanged() {\n this._processItems();\n }",
"onRetrievingUnreadEmails() {\r\n this._update('Retrieving emails...');\r\n }",
"function __refreshUserTopics() {\n VD_API\n .GetUsers(0, _filter.date.start, _filter.date.end)\n .done((users) => {\n users.forEach(__displayUserTopicsCounts);\n })\n .fail((response) => {\n console.error(`Failed to refresh user topics`);\n });\n }",
"subscribe(callback, done, schema = this.options.schema) {\n if (!done) {\n return new Promise((resolve) => this.schemaListener.getNotificationsForSchema(schema, callback, resolve));\n }\n this.schemaListener.getNotificationsForSchema(schema, callback, done);\n }",
"function onConnectionChange() {\n window.console.log('Connection changed. Attempting to sync…');\n syncIfPossible();\n }",
"update ( data ) {\n this.store.update(data);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registra un pedido, validando que el estado de la mesa sea desocupado | async function registrarPedido(parent, args, { usuario, prisma }) {
const mesa = await prisma.mesa.findOne({
where: { id: parseInt(args.mesa) },
select: { ocupado: true },
});
if (!mesa.ocupado) {
const data = {
personal: { connect: { id: usuario.id } },
mesa: { connect: { id: parseInt(args.mesa) } },
productos: {
create: args.productos.map((i) => {
return {
producto: { connect: { id: parseInt(i.producto) } },
precio: parseFloat(i.precio),
cantidad: parseInt(i.cantidad),
};
}),
},
};
const pedidoAgregado = await prisma.pedido
.create({ data })
.catch((err) => null);
pubsub.publish(PEDIDO_AGREGADO, { pedidoAgregado });
return pedidoAgregado;
} else {
throw new Error(MESA_OCUPADA);
}
} | [
"function onSuscriptorGuardado(err, suscriptorGuardado) {\n if (err) { return response.send(err); } \n response.send({ message: 'OK, suscriptor adicionado', _id: suscriptorGuardado._id, creado: suscriptorGuardado.creado });\n }",
"function agregarAlHeruku (pedido){\n let pedidoNuevo = {\n 'thing': {\n 'producto': pedido.producto,\n 'cantidad': pedido.cantidad,\n 'precio': pedido.precio\n }\n }\n\n // Escribe el objeto en el JSON del servidor\n fetch((url), {\n 'method': 'POST',\n 'headers': {\n 'content-type': 'application/JSON'\n },\n 'mode': 'cors',\n 'body': JSON.stringify(pedidoNuevo)\n })\n .then(function (respuesta) {\n if (respuesta.ok) {\n return respuesta.json();\n }\n else {\n alert(\"La solicitud al servidor falló.\");\n }\n })\n .then(function (herukoJson) {\n cargarPedido(pedido, herukoJson._id);\n })\n}",
"function Guardar() {\n \n \n $.post(\"ajax/AgregarPermisos.php\", {\n sName: sInputName.val()\n }, function(o) {\n if (o.Tupla > 0) {\n sInputName.val(\"\");\n objMangoMensaje.MensajeExito(o.sMensaje);\n objMangoTabla.CargaTabla();\n } else {\n sInputName.focus();\n objMangoMensaje.MensajeError(o.sMensaje);\n }\n }, \"json\");\n }",
"function guardarOrden() {\n let cliente = $('#cliente').val();\n let descripcion = $('#descripcion').val();\n let fechaRecep = moment().format('DD/MM/YYYY');\n let fechaEntrega = $('#fechaEntrega').val();\n let estado = \"Pendiente\";\n let encargado = $('#encargado').val();\n\n let ordenes = firebase.database().ref('ordenes/');\n let Orden = {\n cliente: cliente,\n descripcion: descripcion,\n fechaRecep: fechaRecep,\n fechaEntrega: fechaEntrega,\n estado: estado,\n encargado: encargado\n }\n\n ordenes.push().set(Orden); //inserta en firebase asignando un id autogenerado por la plataforma\n $('#agregarOrden').modal('hide');\n}",
"function actualizarPuesto() {\n if (!validarPuesto()) {\n mostrarMensaje(\"error\", \"Se debe soleccionar un puesto y proveer una justificación.\");\n return;\n }\n postulante.puesto_id = document.getElementById(\"selectPuesto\").value;\n postulante.justificacion = document.getElementById(\"inputJustificacion\").value;\n registrarPuesto(postulante).then(function(data) {\n mostrarMensaje(\"exito\", \"Los datos del puesto al que se postula ha sido actualizado.\");\n }); \n}",
"function guardarUsuario() {\n let nombre = $('#nombre').val();\n let apellidos = $('#apellidos').val();\n let agregarUsuarioEmail = $('#agregarUsuarioEmail').val();\n let agregarUsuarioPuesto = $('#agregarUsuarioPuesto').val();\n var agregarUsuarioContrasena;\n\n if($('#nuevacontrasena').val() == $('#confirmarcontrasena').val()) {\n agregarUsuarioContrasena = $('#nuevacontrasena').val();\n\n firebase.auth().createUserWithEmailAndPassword(agregarUsuarioEmail, agregarUsuarioContrasena)\n .then(function(data) {\n console.log(data);\n let uid = data.uid;\n console.log(uid);\n\n let usuarios = firebase.database().ref('usuarios/'+uid);\n let Usuario = {\n nombre: nombre,\n apellidos: apellidos,\n puesto: agregarUsuarioPuesto\n }\n usuarios.set(Usuario); //metodo set para insertar de Firebase\n\n })\n .catch(function(error) {\n console.log(error);\n });\n $('#agregarUsuario').modal('hide');\n\n logOut();\n }\n else {\n console.log(\"Las contraseñas no coinciden\");\n }\n}",
"function crearFormularioRegistrarse(btnIniciarSesion, btnRegistrarse){\r\n document.getElementById(\"formulario\").removeChild(btnIniciarSesion);\r\n document.getElementById(\"formulario\").removeChild(btnRegistrarse);\r\n\r\n crearBtnAtras();\r\n\r\n //formulario registro\r\n\r\n var pNombre = document.createElement(\"p\");\r\n pNombre.innerHTML = \"Nombre: \";\r\n\r\n var nombre = document.createElement(\"input\");\r\n nombre.setAttribute(\"type\", \"text\");\r\n nombre.setAttribute(\"name\", \"nombre\");\r\n nombre.setAttribute(\"id\", \"nombre\");\r\n nombre.setAttribute(\"placeholder\", \"Nombre\");\r\n nombre.setAttribute(\"required\", true);\r\n\r\n var pApellidos = document.createElement(\"p\");\r\n pApellidos.innerHTML = \"Apellidos: \";\r\n\r\n var apellidos = document.createElement(\"input\");\r\n apellidos.setAttribute(\"type\", \"text\");\r\n apellidos.setAttribute(\"name\", \"apellidos\");\r\n apellidos.setAttribute(\"id\", \"apellidos\");\r\n apellidos.setAttribute(\"placeholder\", \"Apellidos\");\r\n apellidos.setAttribute(\"required\", true);\r\n\r\n var pIdentificador = document.createElement(\"p\");\r\n pIdentificador.innerHTML = \"Usuario: \";\r\n\r\n var identificador = document.createElement(\"input\");\r\n identificador.setAttribute(\"type\", \"text\");\r\n identificador.setAttribute(\"name\", \"identificador\");\r\n identificador.setAttribute(\"id\", \"identificador\");\r\n identificador.setAttribute(\"placeholder\", \"Usuario\");\r\n identificador.setAttribute(\"required\", true);\r\n\r\n var pEmail = document.createElement(\"p\");\r\n pEmail.innerHTML = \"Email: \";\r\n\r\n var email = document.createElement(\"input\");\r\n email.setAttribute(\"type\", \"text\");\r\n email.setAttribute(\"name\", \"email\");\r\n email.setAttribute(\"id\", \"email\");\r\n email.setAttribute(\"placeholder\", \"Email\");\r\n email.setAttribute(\"required\", true);\r\n \r\n \r\n var pContrasenna = document.createElement(\"p\");\r\n pContrasenna.innerHTML = \"Contraseña: \";\r\n\r\n var contrasenna = document.createElement(\"input\");\r\n contrasenna.setAttribute(\"type\", \"password\");\r\n contrasenna.setAttribute(\"name\", \"contrasenna\");\r\n contrasenna.setAttribute(\"id\", \"contrasenna\");\r\n contrasenna.setAttribute(\"placeholder\", \"Contraseña\");\r\n contrasenna.setAttribute(\"required\", true);\r\n\r\n var pContrasenna2 = document.createElement(\"p\");\r\n pContrasenna2.innerHTML = \"Confirme su contraseña: \";\r\n\r\n var contrasenna2 = document.createElement(\"input\");\r\n contrasenna2.setAttribute(\"type\", \"password\");\r\n contrasenna2.setAttribute(\"name\", \"contrasenna2\");\r\n contrasenna2.setAttribute(\"id\", \"contrasenna2\");\r\n contrasenna2.setAttribute(\"placeholder\", \"Confirme su contraseña\");\r\n contrasenna2.setAttribute(\"required\", true);\r\n\r\n var registrarme = document.createElement(\"button\");\r\n registrarme.setAttribute(\"name\", \"registrarme\");\r\n registrarme.setAttribute(\"value\", \"registrarme\");\r\n registrarme.addEventListener(\"click\", function(){\r\n ajaxRegistrarNuevoUsuario(nombre, apellidos, identificador, email, contrasenna, contrasenna2);\r\n }) \r\n registrarme.innerHTML =\"Registrarme\";\r\n\r\n document.getElementById(\"formulario\").appendChild(pNombre);\r\n document.getElementById(\"formulario\").appendChild(nombre);\r\n document.getElementById(\"formulario\").appendChild(pApellidos);\r\n document.getElementById(\"formulario\").appendChild(apellidos);\r\n document.getElementById(\"formulario\").appendChild(pIdentificador);\r\n document.getElementById(\"formulario\").appendChild(identificador);\r\n document.getElementById(\"formulario\").appendChild(pEmail);\r\n document.getElementById(\"formulario\").appendChild(email);\r\n document.getElementById(\"formulario\").appendChild(pContrasenna);\r\n document.getElementById(\"formulario\").appendChild(contrasenna);\r\n document.getElementById(\"formulario\").appendChild(pContrasenna2);\r\n document.getElementById(\"formulario\").appendChild(contrasenna2);\r\n document.getElementById(\"formulario\").appendChild(registrarme);\r\n }",
"function guardarProyecto() {\n let nombreProyecto = $('#nombreProyecto').val();\n let fechaInicio = $('#fechaInicio').val();\n let fechaEntrega = $('#fechaEntrega').val();\n let encargadoProyecto = $('#encargadoProyecto').val();\n let estructuraProyecto = $('#estructuraProyecto').val();\n let descripcionProyecto = $('#descripcionProyecto').val();\n let documentacion = $('#documentacion').val();\n let indicador1 = $('#indicador1').val();\n let indicador2 = $('#indicador2').val();\n let objetivo1 = $('#objetivo1').val();\n let objetivo2 = $('#objetivo2').val();\n let objetivo3 = $('#objetivo3').val();\n let entregables = $('#entregables').val();\n\n let proyectos = firebase.database().ref('proyectos/');\n let Proyecto = {\n nombre: nombreProyecto,\n equipo: equipo,\n numtareas: numtareas,\n tareasCompletadas: 0,\n fechaInicio: fechaInicio,\n fechaEntrega: fechaEntrega,\n encargado: encargadoProyecto,\n estructura: estructuraProyecto,\n descripcion: descripcionProyecto,\n docuementacion: documentacion,\n objetivos: {\n objetivo1: objetivo1,\n objetivo2: objetivo2,\n objetivo3: objetivo3\n },\n indicadores: {\n indicador1: indicador1,\n indicador2: indicador2\n },\n entregables: entregables\n }\n proyectos.push().set(Proyecto);\n\n let tareasRef = firebase.database().ref('proyectos/tareas');\n\n for(tarea in tareas) {\n tareasRef.push().set(tarea);\n }\n $('#agregarProyecto').modal('hide');\n}",
"function guardarFirmaObservaciones(data){\n var deferred = $q.defer();\n $http.post(appConstant.LOCAL_SERVICE_ENDPOINT + \"/guardarFirmaObservaciones\", data).then(function (res) {\n deferred.resolve(res);\n }, function (err) {\n deferred.reject(err);\n console.log(err);\n });\n return deferred.promise;\n }",
"createTipo ({\n commit\n }, tipo) {\n ApiService.postTipo(tipo).then((response) => {\n tipo.idTipo = response.data.idTipo // retorna el nuevo identificador creado por el servidor\n\n commit('ADD_TIPO', tipo)\n }).catch(error => {\n console.log('ERROR:', error.message)\n })\n }",
"function insertData(e) {\n e.preventDefault();\n const fullName = document.getElementById('signup-name').value + \" \" + document.getElementById('signup-surname').value;\n const email = document.querySelector('#signup-email').value;\n const password = document.querySelector('#signup-password').value;\n idUser++;\n set(ref(database, \"Users/\" + idUser), {\n id: idUser,\n userName: fullName,\n userEmail: email\n })\n .then(() => {\n createUserWithEmailAndPassword(auth, email, password)\n .then((userCredential) => {\n signupForm.reset();\n $('#signupModal').modal('hide');\n })\n .catch((error) => {\n const errorCode = error.code;\n const errorMessage = error.message;\n });\n alert(\"Datos guardados correctamente\");\n })\n .catch((error) => {\n alert(\"Ha ocurrido un error\" + error);\n })\n}",
"ingresarDinero(ammount, cuenta) {\n if (cuenta.access === true && cuenta.id === this.id) {\n if (this.moneyPocket > ammount) {\n cuenta.balance += ammount;\n this.moneyPocket -= ammount;\n console.log(\n `Has ingresado ${ammount} $, tienes ${cuenta.balance} $ en la cuenta, y ${this.moneyPocket} $ en el monedero`\n );\n } else {\n alert(\"No tienes suficiente dinero\");\n }\n } else {\n console.log(\"No tienes acceso a la cuenta o no coincide con tu id\");\n }\n }",
"function fGuardar(){\n if(fValidaTodo()==true){\n if(fNavega()==true){\n //FRMPanel.fSetTraStatus(\"UpdateComplete\");\n fDisabled(true);\n FRMListado.fSetDisabled(false);\n }\n }\n }",
"async criar() {\n this.validar(true);\n const resultado = await TabelaProduto.inserir({\n titulo : this.titulo,\n preco: this.preco,\n estoque : this.estoque,\n fornecedor : this.fornecedor\n });\n this.id = resultado.id;\n this.dataCriacao = resultado.dataCriacao;\n this.dataAtualizacao = resultado.dataAtualizacao;\n this.versao = resultado.versao\n }",
"function salvarItemEstoque() {\n if ($scope.novoItemEstoque.Id > 0) {\n atualizarItemEstoque();\n }\n }",
"function confirmaEjecucionMotor(){\n\tvar confirmacionUsuario = confirm(preguntaConfirmacion);\n\tif(confirmacionUsuario){\n\t\tvar forma = document.forms[\"ejecucionMotorForm\"];\n\t\tforma[\"tipoEjecucion\"].value = \"1\";\n\t\tforma.submit();\n\t}\n}",
"function asignarProdutoSucursal(keyProducto){\n\t\t/*key sucursal es llamada del valor de un hidden que esta en area.php*/\t\n\t\tvar keySucursal= document.getElementById(\"lb1\").value;\n\t\n\t\tvar requestData = {};\n\t\t\n\t\trequestData.websafeSucursalKey=keySucursal;\n\t\trequestData.websafeProductoKey=keyProducto;\n\t\t\n\t\tgapi.client.doomiClientes.apiClientes.addProductoForSucursal(requestData).execute(\n\t\t\t\n\t\t\tfunction(resp) {\n\n\t\t\t\tif (!resp.code) {\n\t\t\t\t\t//se envia al metodo obtenerProductosXsucursal() para que actualize los productos \n\t\t\t\t\t\n\t\t\t\t\tdocument.getElementById('formrp').reset();\n\t\t\t\t\tobtenerProductosXsucursal();\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\talert(\"Ha ocurrido un error en Tu registro, intentalo de nuevo \");\n\t\t\t\t\t//window.location.href=\"registroCliente.html\";\n\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t});\n\t\n\t\t\n\t\t}",
"ajouter(data){\n var nouNoeud = new Noeud(data)\n if(this.racine === null){\n this.racine = nouNoeud\n }else{\n this.ajouterNoeud(this.racine,nouNoeud)\n }\n }",
"function fGuardarA(){\n if(fValidaTodo()==true){\n if(fNavega()==true){\n //FRMPanel.fSetTraStatus(\"UpdateComplete\");\n fDisabled(true);\n FRMListado.fSetDisabled(false);\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Redraws window(s) after a key is pressed | function redrawAfterKey() {
var sO = CurStepObj;
if (sO.focusBoxId == CodeBoxId.Index)
redrawGridIndexExpr(sO); // redraw the index *cell*
else
drawCodeWindow(sO); // redraw code window
} | [
"function keyPressed() {\n\tif (keyCode == 32) {\n\t\t// reset canvas\n\t\tclear();\n\t\tcount = 0;\n\t\tbutton.hide(); \n\t\tparticleCount = 0;\n\t\t// load next image in paintings array\n\t\tpainting = loadImage(paintings[paintingCount]);\n\t\t// move on to next painting. Go back to first one if the last one is complete\n\t\tif (paintingCount == 4) {\n\t\t\tpaintingCount = 0;\n\t\t} else {\n\t\t\tpaintingCount++;\n\t\t}\n\t\t// fix the position\n\t\tif(isTranslate == true) {\n\t\t\ttranslate(0, 50);\n\t\t\tisTranslate = false;\n\t\t}\n\t\t// reload background and frame (because of the reset)\n\t\tbackground(bg);\n\t\timage(frame, 55, -65);\n\t\t// start next painting \n\t\tstart = true;\n\t}\n}",
"function keyPressed() {\n if (keyCode == 32) {\n if (strokeToggle) {\n stroke(0);\n } else {\n noStroke();\n }\n strokeToggle = !strokeToggle;\n }\n if (keyCode == LEFT_ARROW) {\n circleSize = circleSize - 10;\n }\n if (keyCode == RIGHT_ARROW) {\n circleSize = circleSize + 10;\n }\n if (keyCode == UP_ARROW) {\n toggle++;\n toggle = toggle % 3;\n }\n if (keyCode == DOWN_ARROW) {\n toggle++;\n toggle = toggle % 3;\n }\n}",
"function tm_keystroke() {\n\n tm_keystrokes++;\n tm_calculate();\n}",
"function input_character_keys(key_array_index, event_type, character_key_index, key_code) {\r\n\tkey_array[key_array_index].addEventListener(event_type, function(event) {\r\n\t\tif (event_type == \"keydown\" && document.getElementById(\"mirrored_textarea\") != document.activeElement) {\r\n\t\t\tif (event.key === \" \" || event.key === \"Enter\" || event.key === \"Spacebar\") {\r\n\t\t\t\ttoggle_button(event.target);\r\n\t\t\t\tevent.preventDefault();\r\n\t\t\t\tedit_textarea(character_key_index);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tevent.preventDefault();\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t}\r\n\t});\r\n\r\n\tdocument.addEventListener(\"keydown\", function(event) {\r\n\t\tif (event.defaultPrevented) {\r\n\t\t\treturn; // Do nothing if event already handled\r\n\t\t}\r\n\t\tif (event.code == key_code && modifier_key_pressed == false) {\r\n\t\t\ttoggle_button(event.target);\r\n\t\t\tkey_button_array[key_array_index].classList.add(\"focus\");\r\n\t\t\tsetTimeout(function () {key_button_array[key_array_index].classList.remove(\"focus\");}, 250);\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t\tevent.preventDefault();\r\n\t\t}\r\n\t});\r\n}",
"function keyPressed() {\n switch (key) {\n case 'C':\n drawCos = !drawCos;\n break;\n case 'S':\n drawSin = !drawSin;\n break;\n case 'T':\n drawTan = !drawTan;\n break;\n }\n}",
"function handleKeyDownEvent(){\n if(d3.event.keyCode == 49){\n // Number 1: Set start point\n } else if(d3.event.keyCode == 50){\n // Number 2: Set end point\n } else if(d3.event.keyCode == 83){\n // Character S: Start search\n startSearch();\n } else if(d3.event.keyCode == 82){\n // Character R: Reset search\n resetSearch();\n } else if(d3.event.keyCode == 67){\n // Character C: Clear walls\n clearWalls();\n }\n}",
"update( )\r\n {\r\n\r\n for ( let key in this.pressed_keys )\r\n this.pressed_keys[ key ] = false\r\n\r\n for ( let key in this.mouse_clicked )\r\n this.mouse_clicked[ key ] = false\r\n\r\n }",
"function redraw() {\n\tvar html = window.renderProgram(program);\n\t$(\"#editor\").html(html);\n}",
"function keyPressed() {\n if(keyCode === 37 && currentCardIndex > 0) {\n pressedLeft = true;\n }\n\n if(keyCode === 39 && currentCardIndex < amountOfCards - 1) {\n pressedRight = true;\n }\n redraw();\n}",
"function keyPressed() {\r\n if (key == 'x') {\r\n save(\"screenshotART_151_\" + saveCount + \".png\");\r\n saveCount++;\r\n }\r\n}",
"function displayInput(){\r\n\tdrawNewInput();\r\n\tscrollToEnd();\r\n}",
"function redrawWidgets() {\n let W = global.WIDGETS;\n global.WIDGETS = {};\n Object.keys(W)\n .sort() // see comment in boot.js\n .sort((a, b) => (0|W[b].sortorder)-(0|W[a].sortorder))\n .forEach(k => {global.WIDGETS[k] = W[k];});\n Bangle.drawWidgets();\n }",
"function keyPressed(ev) {\n if (ev.key == 'Enter') {\n updateGuess();\n }\n }",
"function keyPressed(){\n // if key pressed is ENTER key\n if(keyCode===RETURN){\n // reset game\n playAgain();\n }\n}",
"function keyPressed() {\n changeSnakeDir(keyCode);\n}",
"function drawWindowRight() {\n //starts where it ended after it drew the left window, so moves to where the right window will be located on the house\n leftWindowToRightLocation();\n //leaves space so akward line is avoided, making it seem like it is not connected to the side of the house by a line\n penUp();\n moveForward(5);\n penDown();\n //draws small window (square)\n drawRightWindowSquare();\n //draws cross\n drawRightWindowCross();\n}",
"function keyPressed() {\n if (keyCode === DELETE) {\n background(0);\n }\n\n// If the return key is pressed this will give the user an option to save\n// their canvas\n if (keyCode === RETURN) {\n save();\n save('myCanvas.jpg');\n }\n }",
"buildKeyboard() {\n\t\tconst keybed = this.keyboard.getElementsByClassName('keybed');\n\t\tconst octaves = window.innerWidth / (window.innerWidth < 800 ? 600 : 500);\n\t\tkeybed[0].innerHTML = this.generateKeys(octaves, window.innerWidth < 800 ? 3 : 2);\n\t\tthis.keyboard.style.display = '';\n\t\tthis.initKeyListeners();\n\t}",
"function addOnKeyPressedListener(interpreter) {\n $(document).keypress(function(event){\n if (interpreter.keyPressedListenerActive) {\n event.preventDefault();\n if (event.keyCode == ENTER_KEY_CODE) {\n interpreter.keyPressedListenerActive = false;\n return;\n }\n // alert(String.fromCharCode(event.which));\n interpreter.commands = interpreter.commands + String.fromCharCode(event.which);\n interpreter.nextCommand(RunningMethodEnum.VISUALIZE);\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the next `LContainer` that is a sibling of the given container. | function getNextLContainer(container) {
return getNearestLContainer(container[NEXT]);
} | [
"function next () {\r\n return this.siblings()[this.position() + 1]\r\n}",
"function getNextSibling(node, tag){\n\tif (!tag) tag = node.nodeName;\n\ttag = tag.toUpperCase();\n\tvar cont = 20; // Limita o numero de itera��es para evitar sobrecarga no ie\n\twhile (node.nextSibling && node.nextSibling.nodeName && node.nextSibling.nodeName.toUpperCase() != tag && cont-- > 0 ){\n\t\tnode = node.nextSibling;\n\t}\n\treturn node.nextSibling;\n}",
"prevSibling() {\n return this.sibling(-1)\n }",
"function nextLeft(v){var children=v.children;return children?children[0]:v.t;} // This function works analogously to nextLeft.",
"function previousElement(element)\r\n{\r\n\twhile (element = element.previousSibling)\r\n\t{\r\n\t\tif (element.nodeType == 1) return element;\r\n\t}\r\n\treturn null;\r\n}",
"function getLastSibling(node) {\n let sibling = node;\n\n while (sibling && sibling.next) {\n sibling = sibling.next;\n }\n\n return sibling;\n}",
"function find_right_sibling(node)\n{\n if (node === null) \n {\n return;\n }\n var current = node.right;\n var rightSibling = null;\n \n while (current != null)\n {\n if (current.children.length > 0)\n {\n rightSibling = current.children[0];\n break;\n }\n else \n {\n current = current.right;\n }\n }\n \n return rightSibling;\n}",
"function nextChild(iter) {\n if (iter.iter >= children.length) {\n // we don't reset the iterator here; the user should create a new iterator\n return null;\n }\n\n return children[iter.iter++];\n }",
"function followingNonDescendantNode(node) {\n if (node.ownerElement) {\n if (node.ownerElement.firstChild) return node.ownerElement.firstChild;\n node = node.ownerElement;\n }\n do {\n if (node.nextSibling) return node.nextSibling;\n } while (node = node.parentNode);\n return null;\n }",
"function nextAll(item,selector){return untilAll(item,selector,'nextElementSibling');}",
"function siblings () {\r\n return this.parent().children()\r\n}",
"function findPrev(item) {\n var currNode = this.head;\n while (currNode.next.element != item && currNode.next.element != \"head\") {\n currNode = currNode.next;\n }\n if (currNode.next.element == item) {\n return currNode;\n }\n return -1;\n }",
"function setNextImage(image) {\n if(document.getElementById(image.id).parentNode.nextSibling !== null){\n nextImage=document.getElementById(image.id).parentNode.nextSibling.firstChild;\n }\n else{\n nextImage = document.getElementById('container').firstChild.firstChild;\n }\n}",
"function nextNonWhitespace(e) {\n\t\tconst {nextSibling} = (e instanceof $ ? e[0] : e);\n\t\tif (nextSibling &&\n\t\t\t\t((nextSibling instanceof Text && !nextSibling.textContent.trim())\n\t\t\t\t|| (nextSibling.tagName || '').toLowerCase() === \"br\")) {\n\n\t\t\tconst { whitespace, nextElem } = nextNonWhitespace(nextSibling);\n\t\t\treturn { whitespace: $(nextSibling).add(whitespace), nextElem };\n\t\t}\n\t\treturn { whitespace: $(), nextElem: $(nextSibling) };\n\t}",
"_panelForHeading(heading) {\n const next = heading.nextElementSibling;\n if (next.tagName.toLowerCase() !== 'howto-accordion-panel') {\n console.error('Sibling element to a heading need to be a panel.');\n return;\n }\n return next;\n }",
"get dropTargetNodes() {\n let target = this._lastDropTarget;\n\n if (!target) {\n return null;\n }\n\n let parent, nextSibling;\n\n if (this._lastDropTarget.previousElementSibling &&\n this._lastDropTarget.previousElementSibling.nodeName.toLowerCase() === \"ul\") {\n parent = target.parentNode.container.node;\n nextSibling = null;\n } else {\n parent = target.parentNode.container.node.parentNode();\n nextSibling = target.parentNode.container.node;\n }\n\n if (nextSibling && nextSibling.isBeforePseudoElement) {\n nextSibling = target.parentNode.parentNode.children[1].container.node;\n }\n if (nextSibling && nextSibling.isAfterPseudoElement) {\n parent = target.parentNode.container.node.parentNode();\n nextSibling = null;\n }\n\n if (parent.nodeType !== Ci.nsIDOMNode.ELEMENT_NODE) {\n return null;\n }\n\n return {parent, nextSibling};\n }",
"function siblingToSibling() {\n let visibilityStatus = s2sStatus();\n setType(\"s2s\", visibilityStatus);\n}",
"function getParent(eventTarget) {\n return isNode(eventTarget) ? eventTarget.parentNode : null;\n }",
"next() {\n let tmp = this.currentNode.next();\n\n if (!tmp.done) {\n this.currentNode = tmp.value;\n this.ptree();\n }\n\n return tmp;\n }",
"getParent(el, cls) {\n while (el.parentNode) {\n el = el.parentNode;\n if (el.classList) {\n if (el.classList.contains(cls))\n return el;\n }\n }\n return null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creatHandler creates a restify handler from a handlerObject. The handler object is or contains at the very least an action, which is executed whenever the routes receives a request. Furthermore, a transform, respond and error function can be defined. | function createHandler(handlerObject, path) {
handlerObject = extendHandlerObject(handlerObject, path);
return function(req, res) {
var handlerObject = this;
Promise.cast(req)
.bind(virgilio)
.then(handlerObject.validate)
.then(handlerObject.transform)
.then(handlerObject.handler)
.then(function(response) {
return handlerObject.respond.call(this, response, res);
})
.catch(function(error) {
if (error instanceof virgilio.ValidationError) {
return handlerObject
.validationError.call(this, error, res);
} else {
return handlerObject.error.call(this, error, res);
}
}).done();
}.bind(handlerObject);
} | [
"function extendHandlerObject(handlerObject, path) {\n //Instead of passing an object with only a handler property,\n //the user can pass just that property (the action name, a string).\n //In that case, create a full-fledgec handlerObject now.\n if (typeof handlerObject === 'string') {\n handlerObject = {\n handler: handlerObject,\n };\n }\n //Turn the handler property, now the action name, into a function.\n var handler = handlerObject.handler;\n handlerObject.handler = function(args) {\n args = [handler].concat(args);\n var result = virgilio.execute.apply(virgilio, args);\n if (handlerObject.timeout) {\n result.withTimeout(handlerObject.timeout);\n }\n return result;\n };\n handlerObject.validate = getValidationHandler(handlerObject.schema);\n\n //Extend the handlerObject with defaults.\n handlerObject.transform =\n handlerObject.transform || getDefaultTransform(path);\n handlerObject.respond = handlerObject.respond || defaultRespond;\n handlerObject.error = handlerObject.error || defaultError;\n handlerObject.validationError = handlerObject.validationError ||\n defaultValidationError;\n handlerObject.fallbackError = defaultError;\n return handlerObject;\n }",
"static create() {\n return new FastHttpMiddlewareHandler();\n }",
"function _new_handlerx( effect_name, reinit_fun, return_fun, finally_fun,\n branches0, handler_kind, handler_tag, wrap_handler_tag)\n{\n // initialize the branches such that we can index by `op_tag`\n // regardless if the `op_tag` is a number or string.\n const branches = new Array(branches0.length);\n for(let i = 0; i < branches0.length; i++) {\n const branch = branches0[i];\n branches[branch.op_tag] = branch;\n if (typeof op_tag !== \"number\") branches[i] = branch;\n }\n var shared_hinfo = null;\n // return a handler function: `action` is executed under the handler.\n return (function(action,local) {\n // only resources need to recreate the `hinfo` due to the handlertag\n // todo: also store the handler tag in the Handler instead of the Info\n var hinfo = shared_hinfo;\n if (hinfo==null) {\n hinfo = new HandlerInfo(effect_name, reinit_fun, return_fun, finally_fun,\n branches, 0, handler_kind, handler_tag);\n }\n if (wrap_handler_tag==null && shared_hinfo==null) {\n shared_hinfo = hinfo;\n }\n\t // the handler action gets the resource argument (the identifier of the handler)\n\t\tconst haction = function() {\n const resource = (wrap_handler_tag==null ? hinfo.handler_tag :\n wrap_handler_tag(hinfo.handler_tag));\n return yield_iter( action( resource ) ); // autoconvert from iterators\n };\n return _handle_action(hinfo, local, haction );\n });\n}",
"function realestateobject_create(req, res, next) {\n console.log('Real estate object create');\n\n RealEstateObjects.create(req.body)\n .then(realestateobject => {\n res.send(realestateobject);\n })\n .catch(error => next(error));\n}",
"function createMessageHandler(commObj){\n return function(msg){\n processedMessage = processMessage(msg);\n commObj.messageHandlerCallback(processedMessage);\n };\n}",
"function handlerMaker( type ) {\n\t\tvar input;\n\t\tif (\"post\" === type ) {\n\t\t\tinput = \"body\";\n\t\t} else if ( \"get\" === type ) {\n\t\t\tinput = \"query\";\n\t\t}\n\n\t\treturn function ( req, res ) {\n\t\t\t// get the error code\n\t\t\tvar errorCode = parseInt( req[input].error, 10 );\n\t\t\tif ( !errorCode ) {\n\t\t\t\t// no code, return a splash page\n\t\t\t\tfs.readFile( __dirname + '/splash.html', function( err, data ) {\n\t\t\t\t\tif ( err ) {\n\t\t\t\t\t\tres.writeHead( 500, { \"content-type\": \"text/html\" });\n\t\t\t\t\t\tres.end( err + \"Lol, I couldn't load the splash page\" );\n\t\t\t\t\t}\n\t\t\t\t\tres.writeHead( 200, { \"content-type\": \"text/html\" });\n\t\t\t\t\tres.end( data );\n\t\t\t\t});\n\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// get the optional content\n\t\t\tvar content = req[input].content;\n\t\t\tif ( !content ) {\n\t\t\t\tcontent = '';\n\t\t\t}\n\n\t\t\t// see if there's a request for a delay\n\t\t\tvar delay = parseInt( req[input].delay, 10 );\n\t\t\tif ( delay ) {\n\t\t\t\tsetTimeout( sendData, delay );\n\t\t\t} else {\n\t\t\t\tsendData();\n\t\t\t}\n\n\n\t\t\tfunction sendData() {\n\t\t\t\tres.writeHead( errorCode, {} );\n\t\t\t\tres.end( content );\n\t\t\t}\n\t\t}\n\t}",
"function route(handle, pathname, response, request) {\n if (typeof handle[pathname] === 'function') {\n handle[pathname](response, request);\n } else {\n var resource = pathname.substring(1, pathname.length);\n fs.exists(resource, function(exists) {\n if (exists) {\n handlers.render(resource, response);\n } else {\n console.log('No resource ' + resource + '.');\n handlers.write404(pathname, response);\n }\n });\n }\n}",
"getDynamicMockHandler (options) {\n\t\tconst { uri, method, handler } = options;\n\t\tlogService.info(reqFm(method, this.port, uri), '(dynamic)');\n\t\treturn (req, res) => {\n\t\t\trequestLogService.setEntryType(req.id, 'dynamic');\n\t\t\treturn handler(req, res);\n\t\t};\n\t}",
"function createRoutes(serviceLocator, viewPath) {\n\n var assetModel = serviceLocator.assetModel\n\n var thumb = thumbnail(serviceLocator.properties)\n\n function findAsset(req, res, next) {\n assetModel.read(req.params.id, function (err, result) {\n if (err) {\n next(err)\n } else if (!result) {\n next(new serviceLocator.httpErrorHandler.NotFound())\n } else {\n serviceLocator.uploadDelegate.get(result, function(err, data) {\n if (err) {\n next(err)\n } else {\n res.asset = { meta: result, data: data }\n next()\n }\n })\n }\n })\n }\n\n // Get the original asset\n serviceLocator.router.get(\n '/asset/:id/:name',\n findAsset,\n function (req, res, next) {\n\n var asset = res.asset\n res.header('Content-Type', asset.meta.type)\n res.header('Date', new Date().toUTCString())\n res.header('Cache-Control', 'public, max-age=' + (maxAge / 1000))\n res.header('Content-Length', asset.meta.size)\n // TODO also fs.stat header\n res.end(asset.data)\n\n }\n )\n\n // Create a thumbnail if\n // the asset is an image\n serviceLocator.router.get(\n '/asset/thumb/:id/:name',\n findAsset,\n function (req, res, next) {\n\n if (!/^image\\//.test(res.asset.meta.type)) {\n return next(new Error('Can only generate a thumbnail for image assets'))\n }\n\n thumb(res.asset.meta, function (err, imageStream) {\n if (err) {\n next(err)\n } else {\n res.header('Content-Type', res.asset.meta.type)\n res.header('Date', new Date().toUTCString())\n res.header('Cache-Control', 'public, max-age=' + (maxAge / 1000))\n imageStream.pipe(res)\n }\n })\n\n }\n )\n\n}",
"function toAsyncHandler(handler) {\n return callback => (0, _bluebird.resolve)().then(() => handler()).then(() => callback(), err => callback(err));\n}",
"_registerHandlers() {\n let obj = this;\n while (obj = Reflect.getPrototypeOf(obj)) {\n let keys = Reflect.ownKeys(obj)\n keys.forEach((method) => {\n if (method.startsWith('_handle')) {\n this[method]();\n }\n });\n }\n }",
"add(handler) {\n // Give it an ECS reference and let it set up its internal data\n // structure.\n handler.init(this.ecs, this.scriptRunner, this.firer);\n // Register all events the handler is interested in to it.\n for (let et of handler.eventsHandled()) {\n this.register(et, handler);\n }\n // Add it to the internal list for updates.\n this.handlers.push(handler);\n }",
"_setupRoutes() {\n // For requests to webhook handler path, make the webhook handler take care\n // of the requests.\n this.server.post(this.webhookOptions.path, (req, res, next) => {\n this.handler(req, res, error => {\n res.send(400, 'Error processing hook');\n this.logger.error({err: error}, 'Error processing hook');\n\n next();\n });\n });\n\n this.server.post('/builds/:bid/status/:context', restify.plugins.jsonBodyParser(), this.buildStatusController.bind(this));\n this.server.post('/update', restify.plugins.jsonBodyParser(), this.buildStatusController.bind(this));\n\n this.server.get('/pull-request/:owner/:repo/:pullRequestNumber', this.getPullRequest.bind(this));\n }",
"function createHandler(eventType) {\n xhr['on' + eventType] = function (event) {\n copyLifecycleProperties(lifecycleProps, xhr, fakeXHR);\n dispatchEvent(fakeXHR, eventType, event);\n };\n }",
"createMessageHandler(id) {\n // Because a \"conversation\" message handler has state, it will be cached\n // for future use for messages with the same id.\n return createConversation([\n parentHandler,\n whoopsHandler,\n ]);\n }",
"function createServerCB(req, res) {\n\t// Get the url and parse it\n\tlet parsedUrl = url.parse(req.url, true);\n\t\n\t// Get the path from Url\n\tlet path = parsedUrl.pathname;\n\tlet trimmedPath = path.replace(/^\\/+|\\/+$/g, '');\n\n\t// Get the query string and parse as an object\n\tlet queryStringObj = parsedUrl.query;\n\n\t// Get Request method\n\tlet method = req.method.toLowerCase();\n\n\t// Get the headers \n\tlet headers = req.headers;\n\n\t// Get the payload if it exists\n\tlet decoder = new StringDecoder('utf8');\n\tlet buffer = '';\n\treq.on('data', (data) => {\n\t\tbuffer += decoder.write(data);\t\t\n\t});\n\treq.on('end', () => {\n\t\tbuffer += decoder.end();\n\n\t\t// Construct data object for use by handler\n\t\tlet data = {\n\t\t\t'trimmedPath' : trimmedPath,\n\t\t\t'queryStringObj' : queryStringObj,\n\t\t\t'method' : method,\n\t\t\t'headers' : headers,\n\t\t\t'payload' : buffer\n\t\t};\n\n\t\t// if path isn't to hello, return 404\n\t\tif(trimmedPath == 'hello') {\n\t\t\trouter.hello(data, (statusCode, payload) => {\n\t\t\t\t//Sanity Checks\n\t\t\t\tstatusCode = typeof(statusCode) == 'number' ? statusCode : 200;\n\t\t\t\tpayload = typeof(payload) == 'object' ? payload : {};\n\t\t\t\t//Convert payload to a string\n\t\t\t\tlet payloadString = JSON.stringify(payload);\n\t\t\t\t// Return Response\n\t\t\t\tres.setHeader('Content-Type', 'application/json');\n\t\t\t\tres.writeHead(statusCode);\n\t\t\t\tres.end(payloadString);\n\t\t\t});\n\t\t} else {\n\t\t\tnotFound(data, (statusCode) => {\n\t\t\t\t// Return Response\n\t\t\t\tres.setHeader('Content-Type', 'application/json');\n\t\t\t\tres.writeHead(statusCode);\n\t\t\t\tlet msg = {\"Message\" :\"We Only welcome when people come through the right door.\"};\n\t\t\t\tres.end(JSON.stringify(msg));\n\t\t\t});\n\t\t}\n\n\t});\n}",
"function createMiddleware(config) {\n // Get the basePath for all spec versions.\n const basePaths = {};\n _.map(config.swaggerVersions, function(spec) {\n basePaths[spec.info.version] = spec.basePath;\n })\n\n // Build a swagger spec parameter that can be used to validate the version\n // header value. This approach results in consistent error messages.\n const versionHeaderParameter = {\n name: 'X-Api-Version',\n in: 'header',\n description: 'API version header',\n type: 'string',\n enum: _.keys(basePaths)\n };\n\n // Prepends the relevant basePath when a version header is found.\n return function*(next) {\n const version = this.headers['x-api-version'];\n if (version !== undefined) {\n const validationError = validate(version, versionHeaderParameter);\n if (validationError === undefined) {\n const basePath = basePaths[version];\n this.path = basePath + this.path;\n } else {\n this.status = 400;\n this.body = {\n error: 'Validation Failed',\n error_name: 'VALIDATION_FAILED',\n details: [validationError]\n };\n }\n }\n yield next;\n };\n}",
"function handle(vistaId, log, config, environment, job, handlerCallback) {\n\tlog.debug('vista-subscribe-request-handler.handle: Entering method. vistaId: %s; job: %j', vistaId, job);\n\n\tvar pid = idUtil.extractPidFromJob(job);\n\tvar pidSite = idUtil.extractSiteFromPid(pid);\n\n var domainList = config.vista.domains;\n\n\tlog.debug('vista-subscribe-request-handler.handle: Received request to subscribe pid: %s.', pid);\n\tvar isHdr = jobUtil.isVistAHdrSubscribeRequestType(job.type);\n\t// Set up the tasks that must be done to process this message - Bind all the arguments that we know.\n\t//--------------------------------------------------------------------------------------------------\n\tvar tasks = [\n\t\t_validateParameters.bind(null, vistaId, pidSite, pid, log),\n\t];\n\n var pollerJobIds = [];\n _.each(domainList, function(domain){\n var domainJobId = uuid.v4(); // Since this case we are not getting a JobId from DropWizard - we have to create our own. Use a UUID.\n pollerJobIds.push({'domain': domain, 'jobId': domainJobId});\n tasks.push(_createNewJobStatus.bind(null, vistaId, domain, pidSite, pid, job, domainJobId, environment.jobStatusUpdater, log));\n });\n\n if (!isHdr) {\n\t\ttasks.push(_subscribePatientToVistA.bind(null, vistaId, pidSite, pid, job, pollerJobIds, environment.vistaClient, log));\n\t}\n\telse {\n\t\ttasks.push(_subscribePatientToVistAHdr.bind(null, vistaId, pidSite, pid, job, pollerJobIds, environment.hdrClient, log));\n\t}\n\n\tprocessJob(vistaId, pidSite, pid, tasks, log, handlerCallback);\n}",
"function createService(callHandler) {\n const handler = new RpcProxyHandler(callHandler);\n return new Proxy({}, handler);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Correlation coefficient of population | function correlation_coeff_p(X, Y) {
return covariance_p(X, Y) / (stddev_p(X) * stddev_p(Y));
} | [
"function corr(xdata, ydata)\r\n{\r\n if(xdata==null ||xdata.lengtgh<=1)return 0;\r\n var sumx = 0, sumy = 0, sqx = 0, sqy = 0, xy = 0, len = xdata.length;\r\n for(i=0;i<xdata.length;i++)\r\n {\r\n sumx += xdata[i];\r\n sumy += ydata[i];\r\n sqx += xdata[i]*xdata[i];\r\n sqy += ydata[i]*ydata[i];\r\n xy += xdata[i]*ydata[i]; \r\n }\r\n \r\n var avgx = sumx/len;\r\n var avgy = sumy/len;\r\n var sigmax = Math.sqrt((sqx - len*avgx*avgx)/(len-1));\r\n var sigmay = Math.sqrt((sqy - len*avgy*avgy)/(len-1));\r\n if(sigmax==0||sigmay==0)return 0;\r\n var cov = xy - avgx*sumy - avgy*sumx + len*avgx*avgy;\r\n return (cov/(sigmax*sigmay*(len - 1))).toFixed(3);\r\n}",
"function local_correlations() {\n let R = 0;\n for (let x = 0; x < gridSize; x++) {\n for (let y = 0; y < gridSize; y++) {\n R += calcDeltaE(x, y) / 8;\n }\n }\n return R / N;\n}",
"function coeff_of_determination_s(X, Y) {\n return correlation_coeff_s(X, Y) ** 2;\n}",
"calculateCoefficients () {\n\n const modifiedInputs = this._applyCallbackToInputs();\n const transposedInputs = math.transpose(modifiedInputs);\n \n let result = math.multiply(transposedInputs, modifiedInputs);\n result = math.inv(result);\n result = math.multiply(result, transposedInputs);\n result = math.multiply(result, this._outputs);\n\n this._coefficients = \n this._getCoefficientsArrayByMatrix(result);\n\n return this._coefficients;\n }",
"addCovariance(r, covariance){\n var result = new UReal();\n\n }",
"function CorrelationPlotter(options) {\n options = options || {};\n var that = this,\n node = options.node,\n svgC = d3.select(node).append(\"svg\")\n .attr(\"class\", \"correlationPlot\"),\n svg = svgC.append(\"g\");\n\n // accessors to the variables to be displayed\n // these function should return values in [0, 1]\n // and have the property label defined to a\n // a string\n this.variables = options.variables || [];\n\n // the data to be displayed\n this.data = options.data || [];\n\n // the global display size if static\n // otherwise the size is computed from\n // the node size\n this.width = options.width;\n this.height = options.height;\n\n // an internal cache of the subplot objects\n this.plots = {};\n\n // the main draw function\n this.draw = function () {\n if (!that.variables.length) {\n return;\n }\n\n var full = options.full,\n padding = options.padding || 10,\n offset = 15,\n oWidth = that.width || $(node).width(),\n oHeight = that.height || $(node).height(),\n rWidth = Math.min(oWidth, oHeight),\n width = rWidth - 2 * padding - offset,\n height = rWidth - 2 * padding - offset,\n eWidth = (oWidth - rWidth) / 2,\n eHeight = (oHeight - rWidth) / 2,\n nvars = that.variables.length,\n nblocks = nvars - (full ? 0 : 1),\n sWidth = width / nblocks,\n sHeight = height / nblocks,\n plotSelection,\n table = [],\n xlabels, ylabels;\n\n // set the global plot size\n svgC\n .attr(\"width\", oWidth)\n .attr(\"height\", oHeight);\n\n // translate the main plot group for padding\n svg.attr(\"transform\", \"translate(\" + (padding + eWidth + offset) + \",\" + (padding + eHeight + offset) + \")\");\n\n // create the variable correlation table\n that.variables.forEach(function (d) {\n that.variables.forEach(function (e) {\n table.push({\n x: e,\n y: d,\n id: e.label + \"-\" + d.label\n });\n });\n });\n\n // add axis labels\n xlabels = svg.selectAll(\".xlabel\")\n .data(that.variables.slice(0, nblocks));\n xlabels.enter()\n .append(\"text\")\n .attr(\"class\", \"xlabel\")\n .attr(\"text-anchor\", \"middle\");\n xlabels.exit().remove();\n xlabels\n .attr(\"x\", function (d, i) {\n return (i + 0.5) * sWidth;\n })\n .attr(\"y\", -offset / 2)\n .text(function (d) {\n return d.label;\n });\n ylabels = svg.selectAll(\".ylabel\")\n .data(full ? that.variables : that.variables.slice(1));\n ylabels.enter()\n .append(\"text\")\n .attr(\"class\", \"ylabel\")\n .attr(\"x\", 0)\n .attr(\"y\", 0)\n .attr(\"text-anchor\", \"middle\");\n ylabels.exit().remove();\n ylabels\n .attr(\"transform\", function (d, i) {\n var cx = -offset / 2,\n cy = (nblocks - i - 0.5) * sWidth;\n return \"translate(\" + cx + \",\" + cy + \") rotate(-90)\";\n })\n .text(function (d) {\n return d.label;\n });\n\n // the main data join for the plot windows\n plotSelection = svg.selectAll(\".subPlot\")\n .data(table, function (d) {\n return d.id;\n });\n\n // on enter create a new group element and initialize\n // a subplot object in the cache\n plotSelection.enter()\n .append(\"g\")\n .attr(\"class\", \"subPlot\")\n .each(function (d, i) {\n var x = i % nvars,\n y = nvars - 1 - Math.floor(i / nvars);\n if (full || x + y < nvars - 1) {\n that.plots[d.id] = new CorrelationSubPlot({\n width: sWidth,\n height: sHeight,\n node: this,\n x: d.x,\n y: d.y,\n color: options.color\n });\n } else {\n that.plots[d.id] = {\n draw: function () {\n return null;\n }\n };\n }\n });\n plotSelection.exit().remove();\n\n // apply translation to put the subplot\n // in the correct position\n plotSelection\n .attr(\"transform\", function (d, i) {\n var x = i % nvars,\n y = nvars - 1 - Math.floor(i / nvars);\n return \"translate(\" + (x * sWidth) + \",\" + (y * sHeight) + \")\";\n });\n\n // set the size and data in the subplot\n // and trigger a redraw\n plotSelection.each(function (d) {\n var plot = that.plots[d.id];\n plot.width = sWidth;\n plot.height = sHeight;\n plot.data = that.data;\n plot.draw();\n });\n };\n }",
"function getCompositeScore() {\n localCrimeNormalized = localCrime / maxCrime;\n localRentNormalized = localRent / maxRent;\n return Math.pow( localCrimeNormalized * localCrimeNormalized + \n localRentNormalized * localRentNormalized, .5 );\n}",
"setCorrelation() {\n errors.throwNotImplemented(\"setting correlation (dequeue options)\");\n }",
"#rms(array) {\n const squares = array.map((value) => value * value);\n const sum = squares.reduce((accumulator, value) => accumulator + value);\n const mean = sum / array.length;\n return Math.sqrt(mean);\n }",
"function sample_covariance(x, y) {\n\n // The two datasets must have the same length which must be more than 1\n if (x.length <= 1 || x.length !== y.length) {\n return null;\n }\n\n // determine the mean of each dataset so that we can judge each\n // value of the dataset fairly as the difference from the mean. this\n // way, if one dataset is [1, 2, 3] and [2, 3, 4], their covariance\n // does not suffer because of the difference in absolute values\n var xmean = mean(x),\n ymean = mean(y),\n sum = 0;\n\n // for each pair of values, the covariance increases when their\n // difference from the mean is associated - if both are well above\n // or if both are well below\n // the mean, the covariance increases significantly.\n for (var i = 0; i < x.length; i++) {\n sum += (x[i] - xmean) * (y[i] - ymean);\n }\n\n // the covariance is weighted by the length of the datasets.\n return sum / (x.length - 1);\n }",
"function setCommonCovarianceMatrix(GestureSet) {\n for (let k = 0; k < 3; k++) {\n let matrix = [];\n for (var i = 0; i < RubineFeatures.length; i++) {\n matrix[i] = [];\n for (let j = 0; j < RubineFeatures.length; j++) {\n let num = 0.0;\n let den = -_this.gestureClasses.length;\n Object.keys(GestureSet[k]).forEach((GestureClass) => {\n let numExamples = GestureSet[k][GestureClass].length;\n num += (GestureSet[k][GestureClass].covMatrice)[i][j] / (numExamples - 1);\n den += numExamples;\n });\n matrix[i][j] = num / den;\n }\n }\n _this.covMatrix[k] = matrix;\n }\n}",
"function reduce(x) {\n x=x-BMR;\n x = x - (x * calorie_correction_percentage);\n \n return x;\n}",
"function correlate_geographies(responses, tracts, oncorrelated)\n{\n console.log('Responses:', responses.length);\n console.log('One response:', responses[0]);\n\n console.log('Tracts:', tracts.length);\n console.log('One tract:', tracts[0]);\n\n function work(item) {\n correlate = ResidentResearch.correlation();\n correlate.accumulate_tracts(tracts, item);\n }\n function finish(responses) {\n oncorrelated(tracts);\n }\n function chunkFinished(items) {\n jQuery( \"body\" ).trigger( \"surveyMessage\", ['Calculating tract '+(responses.length - items.length + 1)+' of '+responses.length+'...'] );\n }\n timedChunk(responses, work, this, finish, chunkFinished);\n}",
"function windC (savr) {\n return 7.47 * Math.exp(-0.133 * Math.pow(savr, 0.55))\n}",
"function generateRefractors(){\n refractorSet.clear();\n let refractorRows = Math.floor(1.5 + simHeight / 300);\n let refractorCols = Math.floor(1.5 + simWidth / 300);\n\n let rowSpace = simHeight / (refractorRows);\n let colSpace = simWidth / (refractorCols);\n\n let triangleRadius = Math.min(rowSpace / 2 - (7 + simHeight / 50), colSpace / 2 - (7 + simWidth / 50));\n\n for(let i = 0; i < refractorCols; i ++)\n {\n for(let j = 0; j < refractorRows; j ++)\n {\n if(i != 0 || refractorRows % 2 == 0 || j != Math.floor(refractorRows / 2)){\n let center = new Vector(colSpace / 2 + colSpace * i, rowSpace / 2 + rowSpace * j);\n let ang = Math.random() * Math.PI * 2;\n let p1 = addVectors(angleMagVector(ang, triangleRadius), center);\n ang += Math.PI / 3 + Math.random() * Math.PI * .4;\n let p2 = addVectors(angleMagVector(ang, triangleRadius), center);\n ang += Math.PI / 3 + Math.random() * Math.PI * .4;\n let p3 = addVectors(angleMagVector(ang, triangleRadius), center);\n\n refractorSet.add(new SimVector(p1, subVectors(p2, p1)));\n refractorSet.add(new SimVector(p2, subVectors(p3, p2)));\n refractorSet.add(new SimVector(p3, subVectors(p1, p3)));\n }\n }\n }\n}",
"function getResultForChromosome(chromosome,x){\n\t //\n\t return this.calculatePolynomialInPoint(Math.round(chromosome[8]),chromosome,x);\n\t\t//return (chromosome[0]*Math.pow(x,2))+(chromosome[1]*x)+chromosome[2];\n\t}",
"get coefficientList() {\n return this.coefficientLists[this.level];\n }",
"function similaridadeDoCosseno() {\n var vetorL2 = [];\n var vetorProdutoEscalar = [];\n\n var vetorCosseno = [];\n\n for (var linha = 0; linha < matriz.length; linha++) {\n vetorL2[linha] = calculaL2(linha);\n vetorProdutoEscalar[linha] = produtoEscalar(linha);\n }\n console.log(\"vetor produto \", vetorProdutoEscalar);\n\n var normaDaChave = vetorL2[vetorL2.length - 1];\n\n for (var i = 0; i < vetorL2.length - 1; i++) {\n vetorCosseno[i] = [i, vetorProdutoEscalar[i] / (normaDaChave * vetorL2[i])];\n }\n\n vetorCosseno.sort(compare);\n\n return vetorCosseno;\n}",
"function testCreateQueryFromJsonCorrelation() {\n // Call the function to test\n var generatedOutput = createQueryFromJson(jsonQueryCorrelation);\n var expectedOutput = \n 'Correlation between Unit Cost and Total for each Item';\n \n // Checking if generated output is same as expected output\n assertEquals(expectedOutput, generatedOutput, 'createQueryFromJsonCorrelation');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Potentially splits a literaltext string into multiple parts. For special cases. | function splitStringLiteral(s) {
if (s === '. ') {
return ['.', ' ']; // for locales with periods bound to the end of each year/month/date
}
else {
return [s];
}
} | [
"function textsplit(){\n\tvar aku = 'saya belajar di pasar';\n\tconsole.log(aku.split());\n\tconsole.log(aku.split(\"\"));\n\tconsole.log(aku.split(\" \"));\n}",
"function SPLIT(text, delimiter) {\n return text.split(delimiter);\n}",
"function splitSentences(text) {\r\n return text.replace(/([!?]|\\.\\.\\.)\\s+/g, \"$1. \").split(/[.;]\\s/);\r\n}",
"function splitParagraph(text){\n\n\tvar fragments = [];\n\n\twhile( text != ''){\n\t\tif (text.charAt(0) == \"*\"){\n\t\t\tfragments.push({type: 'emphasized',\n\t\t\t\t\t\t\t\t\t\t\tcontent: text.slice(1,takeUpTo('*',text))});\n\t\t\t//modify text so we remove the string we just stored\n\t\t\t//we add 1 because we want to remove the string added\n\t\t\t//PLUS the character at the end which may be } or *\n\t\t\ttext = text.slice(takeUpTo('*',text)+1);\n\t\t} else if (text.charAt(0) == \"{\"){\n\t\t\tfragments.push({type: 'footnote',\n\t\t\t\t\t\t\t\t\t\t\tcontent: text.slice(1,takeUpTo('}',text))});\n\t\t\t//modify text so we remove the string we just stored\n\t\t\ttext = text.slice(takeUpTo('}',text)+1);\n\t\t} else {\n\t\t\tfragments.push({type: 'normal',\n\t\t\t\t\t\t\t\t\t\t\tcontent: text.slice(0,takeNormal(text))});\n\t\t\t//modify text so we remove the string we just stored\n\t\t\ttext = text.slice(takeNormal(text));\n\t\t}\n\t}\n\n\treturn fragments;\n}",
"function splitWithEscape(value, splitChar, escapeChar) {\n var results = [];\n var escapeMode = false;\n var currentResult = \"\";\n for (var pos = 0; pos < value.length; pos++) {\n if (!escapeMode) {\n if (value[pos] === splitChar) {\n results.push(currentResult);\n currentResult = \"\";\n } else if (value[pos] === escapeChar) {\n escapeMode = true;\n } else {\n currentResult += value[pos];\n }\n } else {\n currentResult += value[pos];\n escapeMode = false;\n }\n }\n if (currentResult !== \"\") {\n results.push(currentResult);\n }\n return results;\n }",
"function splitProtected(contextSpec, startContext, s, splitters, saveSplitters=false) {\n\tlet sections = []\n\tlet last = 0\n\t\n\tparseProtected(contextSpec, startContext, s, handlers={\n\t\tonChar: ({index, section, c}) => {\n\t\t\t\n\t\t\tif (section.depth == 0) {\n\t\t\t\t\n\t\t\t\t// Find the largest splitter at this location\n\t\t\t\tlet splitter;\n\t\t\t\tfor (var i =0; i < splitters.length; i++) {\n\t\t\t\t\t// Is this one bigger?\n\t\t\t\t\tif (s.startsWith(splitters[i], index) \n\t\t\t\t\t\t&& (splitter === undefined || splitter.length < splitters[i].length)) {\n\t\t\t\t\t\tsplitter = splitters[i]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Found one?\n\t\t\t\tif (splitter) {\n\t\t\t\t\t// end this text section\n\t\t\t\t\tsections.push(s.substring(last, index))\n\n\t\t\t\t\tif (saveSplitters)\n\t\t\t\t\t\tsections.push({\n\t\t\t\t\t\t\tsplitter: splitter, \n\t\t\t\t\t\t\tindex: index\n\t\t\t\t\t\t})\n\n\t\t\t\t\tlast = index + splitter.length\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n\t// Last text section\n\tsections.push(s.substring(last))\n\n\n\treturn sections\n\n}",
"function split(text, IACB) { //IACB see crawl function definition\n\t\tconst arr = protectNumbers(text, IACB)\n\t\t\t.split(/([\\^*/+\\-])/)\n\t\t\t.filter(o => o.length > 0)\n\t\t\t.map(o => unprotectNumbers(o));\n\n\t\t//text is now split into array of strings, iterate through it and parse them\n\t\tconst arr2 = [];\n\t\tarr.forEach(function(o) {\n\t\t\t//try if it's a number\n\t\t\tlet num = Number(o);\n\t\t\tif(!isNaN(num) && isFinite(num)) {arr2.push(num); return;}\n\n\t\t\t//if it's an operator, let it be\n\t\t\tif(o.match(/^[\\^*/+\\-]$/)) {arr2.push(o); return;}\n\n\t\t\t//else we'll assume it's a unit\n\t\t\telse {\n\t\t\t\t//identify number that is right before the unit (without space or *)\n\t\t\t\tlet firstNum = o.match(/^[+\\-]?[\\d\\.]+(?:e[+\\-]?\\d+)?/);\n\t\t\t\tif(firstNum) {\n\t\t\t\t\tfirstNum = firstNum[0];\n\t\t\t\t\to = o.slice(firstNum.length); //strip number from the unit\n\t\t\t\t\tnum = Number(firstNum);\n\t\t\t\t\tif(isNaN(num) || !isFinite(num)) {throw convert.msgDB['ERR_NaN'](firstNum);} //this could occur with extremely large numbers (1e309)\n\t\t\t\t\t//if you have number and unit tightly together, they should have the same power; we achieve that by wrapping them in brackets array\n\t\t\t\t\tarr2.push([Number(num), '*', parsePrefixUnitPower(o)]);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t//identification of the unit itself and its power\n\t\t\t\tarr2.push(parsePrefixUnitPower(o));\n\t\t\t}\n\t\t});\n\t\treturn arr2;\n\t}",
"_completeLiteral(token) {\n // Create a simple string literal by default\n let literal = this._literal(this._literalValue);\n\n switch (token.type) {\n // Create a datatyped literal\n case 'type':\n case 'typeIRI':\n const datatype = this._readEntity(token);\n\n if (datatype === undefined) return; // No datatype means an error occurred\n\n literal = this._literal(this._literalValue, datatype);\n token = null;\n break;\n // Create a language-tagged string\n\n case 'langcode':\n literal = this._literal(this._literalValue, token.value);\n token = null;\n break;\n }\n\n return {\n token,\n literal\n };\n }",
"function splitText(text, ngram = 2) {\n\t const result = [];\n\n\t for (let i = 0; i < text.length - ngram + 1; i++) {\n\t result.push(text.slice(i, i + ngram));\n\t }\n\n\t return result;\n\t}",
"function splitLines(text) {\n\t return text.split(/\\r?\\n/);\n\t}",
"function splitString (string) {\r\n console.log(\"String to split: \" + string)\r\n var toSplit = string;\r\n var stringComponents = toSplit.split(\".\");\r\n return stringComponents;\r\n}",
"function searchLiterals(literalInputPipes, text, sep) {\n const literalMap = buildLiteralMap(text, sep)\n const literalInputArray = literalInputPipes.split('|')\n\n let outputTotal = {\n \"total\": literalInputArray.length,\n \"result\": []\n }\n Object.freeze(outputTotal)\n\n for (const literal of literalInputArray) {\n if (literalMap.has(literal)) {\n const output = {\n \"literal\": literal,\n \"count\" : literalMap.get(literal)\n }\n Object.freeze(output)\n\n outputTotal[\"result\"].push(output)\n }\n }\n console.log(outputTotal)\n}",
"splitTextSentences(text) {\n const sentences = [];\n const splitText = text.split(SENTENCE_SPLIT_REGEX);\n let currentSentence = splitText[0].replace(/^\\s+/, '');\n for (let i = 1; i < splitText.length; i += 1) {\n const chunk = splitText[i].replace(/^\\s+/, '');\n if (!chunk) continue;\n if (chunk.match(SENTENCE_PUNCT_MATCH_REGEX)) {\n currentSentence += chunk;\n } else {\n sentences.push(currentSentence);\n currentSentence = chunk;\n }\n }\n sentences.push(currentSentence);\n return sentences;\n }",
"function splitter(string, cb){\n return cb(string);\n}",
"enterMultiLineStringLiteral(ctx) {\n\t}",
"function tokenize(templ) {\n return (function (arr) {\n var tokens = [];\n for (i = 0; i < arr.length; i++) {\n (function (token) {\n return token === \"\" ?\n null :\n tokens.push(token);\n }(arr[i]));\n }\n return tokens;\n }(split(templ, new RegExp(\"(\" + VAR_TAG.source + \"|\" +\n BLOCK_TAG.source + \"|\" +\n END_BLOCK_TAG.source + \")\"))));\n }",
"function multiSplit(splitStr, splitDelimiters, callback)\n{\n\t/*\n\t * We use a helper function because this way we can pass the result and use\n\t * tail recursion for each recursive call.\n\t */\n\tfunction multiSplitHelp(str, delimiters, result)\n\t{\n\t\tvar i;\n\t\tvar minI;\n\t\tvar minIndex = -1;\n\n\t\t/*\n\t\t * For each delimiter, find the first instance of it in the string. If\n\t\t * it is closer than the current minimum index, store it.\n\t\t */\n\t\tfor (i = 0; i < delimiters.length; i++) {\n\t\t\tvar index = str.indexOf(delimiters[i]);\n\n\t\t\t/*\n\t\t\t * If there is an instance of the delimiter (i.e. index is not -1),\n\t\t\t * and there hasn't been an index found so far (i.e. minIndex is -1)\n\t\t\t * or the index is less than the current minimum index, then the\n\t\t\t * index is a new minimum.\n\t\t\t */\n\t\t\tif (index > -1 && (minIndex == -1 || index < minIndex)) {\n\t\t\t\tminIndex = index;\n\t\t\t\tminI = i;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * If the minimum index is still -1, no instance of a delimiter was\n\t\t * found. This is the base case, so return.\n\t\t *\n\t\t * Otherwise, add the found delimiter to the results and make a\n\t\t * recursive call.\n\t\t */\n\t\tif (minIndex == -1) {\n\t\t\tif (callback) {\n\t\t\t\tcallback(str, null);\n\t\t\t}\n\n\t\t\tresult.push([ str, null ]);\n\t\t\treturn result;\n\t\t} else {\n\t\t\tvar curStr = str.substr(0, minIndex);\n\t\t\tif (callback) {\n\t\t\t\tcallback(curStr, delimiters[minI]);\n\t\t\t}\n\n\t\t\tresult.push([ curStr, delimiters[minI] ]);\n\t\t\tstr = str.substr(minIndex + delimiters[minI].length,\n\t\t\t\tstr.length);\n\t\t\treturn multiSplitHelp(str, delimiters, result);\n\t\t}\n\t}\n\n\treturn multiSplitHelp(splitStr, splitDelimiters, new Array());\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}",
"function splitValue(value) {\n return value.match(/.{1,3}/g)\n}",
"exitMultiLineStringLiteral(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Appends clicked GIF to journal entry form | function GIFClick(img){
if (numberOfThumbs >= 6) {
document.querySelector('#userInput').appendChild(img);
img.id = "postGIF";
let postGIF = document.getElementById("postGIF").src;
}
img.setAttribute('onclick', 'GIFReturn(this)');
numberOfThumbs --;
} | [
"function gifClicked() {\n largeGifAppears(this);\n automatedSpeech();\n}",
"function largeGifAppears(e) {\n let src = $(e).attr('src');\n $chosenGif.attr(\"src\", src); // can i do this\n $chosenGif.show();\n}",
"function revokeWaitingGIF() {\n//\tRichfaces.hideModalPanel('loadingPanel');\n//\tdocument.body.style.cursor = 'default';\n\trevokeWaitingGIfForSave();\n}",
"function gifControl() {\n var state = $(this).attr('data-state');\n var still = $(this).attr('data-still');\n var animate = $(this).attr('data-animated');\n\n if (state == 'still') {\n $(this).attr('src', animate);\n $(this).attr('data-state', 'animate')\n } else if (state = 'animate') {\n $(this).attr('src', still);\n $(this).attr('data-state', 'still')\n }\n } // End of gifControl()",
"function appendGif(gifURL) {\n const $newGif = $(\"<img>\");\n $newGif.attr('src', gifURL)\n .addClass('gifImages'); //prefer addClass over attr\n $gifContainer.append($newGif);\n}",
"function refresh_icon(){\n var logging_button = jQuery('#crowdlogger-logging-button');\n // Logging is enabled.\n if( CROWDLOGGER.preferences.get_bool_pref('logging_enabled', false ) ){\n logging_button.addClass('crowdlogger-logging-on-button').\n removeClass('crowdlogger-logging-off-button');\n logging_button.html(\n CROWDLOGGER.gui.buttons.current.menu_label_logging_on);\n logging_button.attr('title', \n CROWDLOGGER.gui.buttons.current.logging_on_hover_text);\n // Logging is disabled.\n } else {\n logging_button.removeClass('crowdlogger-logging-on-button').\n addClass('crowdlogger-logging-off-button'); \n logging_button.html(\n CROWDLOGGER.gui.buttons.current.menu_label_logging_off);\n logging_button.attr('title', \n CROWDLOGGER.gui.buttons.current.logging_off_hover_text); \n }\n}",
"function imagebisButtonClick(e, data) {\n\t\t// Wire up the submit button click event handler\n\t\t$(data.popup).find(\"input[type=file]\")\n\t\t\t.unbind(\"change\")\n\t\t\t.bind(\"change\", function(e) {\n\t\t\t\tvar $_this = $(this);\n\n\t\t\t\t// Get the editor\n\t\t\t\tvar editor = data.editor; \n\t\t\t\t$_this.upload(URL_SITE+'ajax:photo/upload/align:'+ $(data.popup).find(\"input:radio[name=align]:checked\").val() +'/', function(res) {\n\t\t\t\t\tvar html = res.image;\n\n\t\t\t\t\t// Insert the html\n\t\t\t\t\tif (res.image) {\n\t\t\t\t\t\teditor.execCommand(data.command, html, null, data.button);\n\t\t\t\t\t\teditor.find( 'img[src=\"'+html+'\"]' ).attr( 'align', $(data.popup).find(\"input:radio[name=align]:checked\").val() );\n\t\t\t\t\t}\n\t\t\t\t}, 'json');\n\n\t\t\t\t// reset popup\n\t\t\t\t$(this).val('');\n\t\t\t\teditor.hidePopups();\n\t\t\t\teditor.focus();\n\t\t\t}\n\t\t);\n\t}",
"function _iconClickEvent() {\n\n\t\t_toggleVisibility();\n\n\t\t// Turn of file watching when not using it\n\t\tif (false === visible) {\n\t\t\ttailDomain.exec(\"quitTail\")\n\t\t\t\t.done(function () {\n\t\t\t\t\tconsole.log(\"[brackets-tail-node] quitTail done event\");\n\t\t\t\t}).fail(function (err) {\n\t\t\t\t\tconsole.error(\"[brackets-tail-node] quitTail error event\", err);\n\t\t\t\t});\n\t\t}\n\t}",
"function showIconPicture() {\n // Listen for file selection.\n fileInput.addEventListener('change', function (e) {\n file = e.target.files[0];\n var blob = URL.createObjectURL(e.target.files[0]);\n // Change DOM image.\n image.src = blob;\n\n // Store using this name.\n storageRef = storage.ref(\"images/\" + docAppID + \"icon.jpg\");\n\n storageRef.put(file)\n .then(function () {\n console.log('Uploaded to Cloud Storage.');\n })\n })\n }",
"function displayFavGif() {\n $(\"#movies-view\").empty();\n for (var i=0; i<favGif.length; i++) {\n var FavImage = $(\"<img>\").attr(\"src\", favGif[i]);\n $(\"#movies-view\").prepend(FavImage);\n }\n}",
"function pushInstructionButton() {\n\t $(\".instruction-button-container\").append(`\n\t <img class='instruction-button-push btn' src='assests/yellow-pushed-button.png'/>\n\t `);\n\t $('.instruction-button-push').delay(1000).fadeOut(1000, function () {\n\t $('.instruction-button-push').remove();\n\t });\n\t}",
"function newImage() {\n hangman.flagImage.style.opacity = 0;\n hangman.flagImage.style.backgroundImage = 'url(' + flagUrl(hangman.chosenWord) +')'\n }",
"function insert () {\n var link = escape($('#redactor-redimage-link').val());\n var title = escape($('#redactor-redimage-title').val());\n\n this.insert.html('<img src=\"' + link + '\" alt=\"' + title + '\">');\n this.modal.close();\n }",
"function imojieClick(emojie) {\n gMeme.lines.push({\n txt: `${emojie}`,\n size: 20,\n align: 'left',\n color: 'red',\n x: 250,\n y: 300\n }, )\n gMeme.selectedLineIdx = gMeme.lines.length - 1\n drawImgText(elImgText)\n}",
"function renderGif() {\n var animal = $(this).attr(\"data-name\");\n var queryURL = \"https://api.giphy.com/v1/gifs/search?q=\" + animal + \"&api_key=MJ68Z6txRmEzdp8Ow2QiKvYGwxbb9ip4&limit=10&rating=pg\";\n\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n $(\"#gif-div\").empty();\n $(\"#gifHeader\").html(`<h5>${animal} GIFs, click on the GIF to animate it!</h5>`);\n var results = response.data;\n for (var j = 0; j < results.length; j++) {\n var animalDiv = $(\"<div>\").addClass(\"animalDiv\");\n var p = $(\"<p>\")\n .addClass(\"card-text\")\n .html(`Rating: ${results[j].rating.toUpperCase()}`);\n var animalImage = $(\"<img>\")\n .addClass(\"gif img-thumbnail\")\n .attr(\"data-state\", \"still\")\n .attr(\"data-still\", results[j].images.fixed_width_still.url)\n .attr(\"data-animate\", results[j].images.fixed_width.url)\n .attr(\"src\", results[j].images.fixed_width_still.url);\n var addFavorite = $(\"<button>\")\n .addClass(\"btn btn-success favButton\")\n .attr(\"type\", \"button\")\n .text(\"Add to Favorites\");\n animalDiv.append(p, animalImage, addFavorite);\n $(\"#gif-div\").prepend(animalDiv);\n }\n });\n }",
"function showGif(value){\n if(value === 'show'){\n document.querySelector('.wait-icon').classList.add('show');\n }\n else if(value === 'hide'){\n document.querySelector('.wait-icon').classList.remove('show');\n }\n}",
"function printToPage(stillURL, gifURL, rating){\n // create new image element using jQuery \n var myImg = $(\"<img>\");\n // set the initial source to stillURL, will be changed on click\n myImg.attr(\"src\", stillURL);\n // set classes, center-block centers image within panel\n myImg.addClass(\"gifImg center-block\");\n // Store the full movement GIF URL as a data attribute so it can easily be accessed in future on click to change source\n myImg.attr(\"data-imgMove\", gifURL);\n // Store the still URL as a data attribute so we can access it in future\n myImg.attr(\"data-imgStill\", stillURL)\n // Initial status is still, therefore set value of curStatus key to still, will change on click\n myImg.attr(\"data-curStatus\", \"still\");\n // Create a div to hold panel\n var myPanel = $(\"<div>\");\n // Bootstrap panel attributes, col-lg-6 allows 2 each panels / row\n myPanel.addClass(\"panel panel-default gifPanel col-lg-6\");\n // create a div to hold panel body, see bootstrap docs \n var panelBody = $(\"<div>\");\n // Assign panel-body class, see bootstrap docs\n panelBody.addClass(\"panel-body\");\n // ADD the image into the panel body\n panelBody.append(myImg);\n // Create Panel Footer which will hold the rating\n var panelFooter = $(\"<div>\");\n // Add panel footer and text-center classes to footer, see bootstrap docs\n panelFooter.addClass(\"panel-footer text-center\");\n //Add the rating to the panel-footer, ideally make the rating bold, possibly add span element in future\n panelFooter.text(\"Rating: \" + rating);\n // append panelBody (which contains image) to the panel container (see Bootstrap docs)\n myPanel.append(panelBody);\n // append panelFooter (which contains rating) to panel container (see bootstrap docs)\n myPanel.append(panelFooter);\n //Finaally, append the finished panel to the DOM\n $(\".gifRow\").append(myPanel);\n}",
"function setAttachButtonHandler() {\n const attachmentButton = document.getElementById('attachmentButton');\n const attachmentInput = document.getElementById('attachmentInput');\n const attachmentSaveA = document.getElementById('attachmentSaveA');\n const deleteImg = document.getElementById('deleteImg');\n deleteImg.addEventListener('click', function() {\n\tattachmentSaveA.href = '';\n\tattachmentSaveA.download = '';\n\tattachmentInput.value = attachmentInput.files = null;\n\tattachmentSaveA.style.display = 'none';\n\tcommon.replaceElemClassFromTo('attachmentInput', 'visibleIB', 'hidden', true);\n\tcommon.replaceElemClassFromTo('attachmentButton', 'hidden', 'visibleIB', false);\n\tdeleteImg.style.display = 'none';\n\tif (msgTextArea.value == '')\n\t document.getElementById('msgFeeArea').value = 'Fee: 0 Wei';\n });\n attachmentButton.addEventListener('click', function() {\n\tattachmentInput.value = attachmentInput.files = null;\n\tcommon.replaceElemClassFromTo('attachmentButton', 'visibleIB', 'hidden', true);\n\tcommon.replaceElemClassFromTo('attachmentInput', 'hidden', 'visibleIB', false);\n });\n attachmentInput.addEventListener('change', function() {\n\tconsole.log('attachmentInput: got change event');\n\tif (attachmentInput.files && attachmentInput.files[0]) {\n\t console.log('attachmentInput: got ' + attachmentInput.files[0].name);\n\t const reader = new FileReader();\n\t reader.onload = (e) => {\n\t\t//eg. e.target.result = data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAMAAAC5zwKfAAACx1BMV...\n\t\tconsole.log('attachmentInput: e.target.result = ' + e.target.result);\n\t\t//\n\t\tattachmentSaveA.href = e.target.result;\n\t\tattachmentSaveA.download = attachmentInput.files[0].name;\n\t\tconst attachmentSaveSpan = document.getElementById('attachmentSaveSpan');\n\t\tattachmentSaveSpan.textContent = attachmentInput.files[0].name;\n\t\tattachmentSaveA.style.display = 'inline-block';\n\t\tdeleteImg.style.display = 'inline-block';\n\t\tcommon.replaceElemClassFromTo('attachmentInput', 'visibleIB', 'hidden', true);\n\t\t//message has content...\n\t\tdocument.getElementById('msgFeeArea').value = 'Fee: ' + ether.convertWeiBNToComfort(common.numberToBN(mtDisplay.composeFee));\n\t };\n\t reader.readAsDataURL(attachmentInput.files[0]);\n } else {\n\t attachmentSaveA.href = null;\n\t}\n });\n}",
"function showPictureToDelete()\n{\n\tif (document.forms[1].deletePics.value == \"\")\n\t{\n\t\t$('#showPicture').empty();\n\t}\n\telse\n\t{\n\t\t$('#showPicture').empty();\n\t\tvar picture = document.forms[1].deletePics.value;\n\t\tvar pictureScript = '<p><img src=\"../mainPictures/' + picture + '\"width=\"50\" height=\"76\" />';\n\t\t$('#showPicture').append(pictureScript);\n\t}\n}",
"function showDefaultBuddyIcon(image_element) {\n image_element.onerror = '';\n image_element.src = 'https://www.flickr.com/images/buddyicon.gif';\n return true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
round to nearby lower multiple of base | function floorInBase(n,base){return base*Math.floor(n/base)} | [
"function floorInBase(n,base){return base*Math.floor(n/base);}",
"function roundToGrid(numb) {\n\treturn Math.round(numb/10) * 10;\n}",
"function roundUp(n, up)\n{\n if (n % up == 0)\n return(n);\n else\n return(n + (up - (n % up)));\n}",
"function round5(x)\r\n{\r\n return Math.round(x/5)*5;\r\n}",
"function round1D(num) {\n return Math.round( num * 10 ) / 10;\n}",
"function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places\n\tvar newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);\n\treturn parseFloat(newnumber); // Output the result\n}",
"function roundTowardsZero(x) {\r\n var a;\r\n if (x < 0) {\r\n a = Math.ceil(x);\r\n } else {\r\n a = Math.floor(x);\r\n }\r\n return a;\r\n}",
"function toBaseFive(number) {\n if (!isNaN(number)) {\n return Math.ceil(number / 2);\n } else {\n return 0;\n }\n}",
"function CCur(num) {\n var dec=4;\n var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);\n return result;\n}",
"function roundDown(n, down)\n{\n return(n - (n % down));\n}",
"function ROUNDUP(number, precision) {\n var factors = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000];\n var factor = factors[precision];\n if (number > 0) {\n return Math.ceil(number * factor) / factor;\n } else {\n return Math.floor(number * factor) / factor;\n }\n}",
"function round( x, sd, rm, r ) {\r\n\t var d, i, j, k, n, ni, rd,\r\n\t xc = x.c,\r\n\t pows10 = POWS_TEN;\r\n\r\n\t // if x is not Infinity or NaN...\r\n\t if (xc) {\r\n\r\n\t // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n\t // n is a base 1e14 number, the value of the element of array x.c containing rd.\r\n\t // ni is the index of n within x.c.\r\n\t // d is the number of digits of n.\r\n\t // i is the index of rd within n including leading zeros.\r\n\t // j is the actual index of rd within n (if < 0, rd is a leading zero).\r\n\t out: {\r\n\r\n\t // Get the number of digits of the first element of xc.\r\n\t for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );\r\n\t i = sd - d;\r\n\r\n\t // If the rounding digit is in the first element of xc...\r\n\t if ( i < 0 ) {\r\n\t i += LOG_BASE;\r\n\t j = sd;\r\n\t n = xc[ ni = 0 ];\r\n\r\n\t // Get the rounding digit at index j of n.\r\n\t rd = n / pows10[ d - j - 1 ] % 10 | 0;\r\n\t } else {\r\n\t ni = mathceil( ( i + 1 ) / LOG_BASE );\r\n\r\n\t if ( ni >= xc.length ) {\r\n\r\n\t if (r) {\r\n\r\n\t // Needed by sqrt.\r\n\t for ( ; xc.length <= ni; xc.push(0) );\r\n\t n = rd = 0;\r\n\t d = 1;\r\n\t i %= LOG_BASE;\r\n\t j = i - LOG_BASE + 1;\r\n\t } else {\r\n\t break out;\r\n\t }\r\n\t } else {\r\n\t n = k = xc[ni];\r\n\r\n\t // Get the number of digits of n.\r\n\t for ( d = 1; k >= 10; k /= 10, d++ );\r\n\r\n\t // Get the index of rd within n.\r\n\t i %= LOG_BASE;\r\n\r\n\t // Get the index of rd within n, adjusted for leading zeros.\r\n\t // The number of leading zeros of n is given by LOG_BASE - d.\r\n\t j = i - LOG_BASE + d;\r\n\r\n\t // Get the rounding digit at index j of n.\r\n\t rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;\r\n\t }\r\n\t }\r\n\r\n\t r = r || sd < 0 ||\r\n\r\n\t // Are there any non-zero digits after the rounding digit?\r\n\t // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right\r\n\t // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.\r\n\t xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );\r\n\r\n\t r = rm < 4\r\n\t ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )\r\n\t : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&\r\n\r\n\t // Check whether the digit to the left of the rounding digit is odd.\r\n\t ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||\r\n\t rm == ( x.s < 0 ? 8 : 7 ) );\r\n\r\n\t if ( sd < 1 || !xc[0] ) {\r\n\t xc.length = 0;\r\n\r\n\t if (r) {\r\n\r\n\t // Convert sd to decimal places.\r\n\t sd -= x.e + 1;\r\n\r\n\t // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n\t xc[0] = pows10[ sd % LOG_BASE ];\r\n\t x.e = -sd || 0;\r\n\t } else {\r\n\r\n\t // Zero.\r\n\t xc[0] = x.e = 0;\r\n\t }\r\n\r\n\t return x;\r\n\t }\r\n\r\n\t // Remove excess digits.\r\n\t if ( i == 0 ) {\r\n\t xc.length = ni;\r\n\t k = 1;\r\n\t ni--;\r\n\t } else {\r\n\t xc.length = ni + 1;\r\n\t k = pows10[ LOG_BASE - i ];\r\n\r\n\t // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n\t // j > 0 means i > number of leading zeros of n.\r\n\t xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;\r\n\t }\r\n\r\n\t // Round up?\r\n\t if (r) {\r\n\r\n\t for ( ; ; ) {\r\n\r\n\t // If the digit to be rounded up is in the first element of xc...\r\n\t if ( ni == 0 ) {\r\n\r\n\t // i will be the length of xc[0] before k is added.\r\n\t for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );\r\n\t j = xc[0] += k;\r\n\t for ( k = 1; j >= 10; j /= 10, k++ );\r\n\r\n\t // if i != k the length has increased.\r\n\t if ( i != k ) {\r\n\t x.e++;\r\n\t if ( xc[0] == BASE ) xc[0] = 1;\r\n\t }\r\n\r\n\t break;\r\n\t } else {\r\n\t xc[ni] += k;\r\n\t if ( xc[ni] != BASE ) break;\r\n\t xc[ni--] = 0;\r\n\t k = 1;\r\n\t }\r\n\t }\r\n\t }\r\n\r\n\t // Remove trailing zeros.\r\n\t for ( i = xc.length; xc[--i] === 0; xc.pop() );\r\n\t }\r\n\r\n\t // Overflow? Infinity.\r\n\t if ( x.e > MAX_EXP ) {\r\n\t x.c = x.e = null;\r\n\r\n\t // Underflow? Zero.\r\n\t } else if ( x.e < MIN_EXP ) {\r\n\t x.c = [ x.e = 0 ];\r\n\t }\r\n\t }\r\n\r\n\t return x;\r\n\t }",
"function roundToNearestWeight(inWeight) {\n const minUnit = 5;\n return Math.ceil(inWeight / minUnit) * minUnit;\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 roundCoordinates(num) {\n return Math.round(num * 10000) / 10000\n}",
"static round(n, digits) {\n\t\treturn Math.round(n * (10**digits)) / (10**digits);\n\t}",
"function roundUpSecondSigDigit(num){\n var s = Math.floor(num).toString();\n var divisor = Math.pow(10,s.length-2);\n var result = Math.ceil(num/divisor) * divisor;\n return result;\n}",
"function squirt(n, g) {\n if (!g) {\n // Take an initial guess at the square root\n g = n / 2.0;\n }\n var d = n / g; // Divide our guess into the number\n var ng = (d + g) / 2.0; // Use average of g and d as our new guess\n if (g === ng) {\n // The new guess is the same as the old guess; further guesses\n // can get no more accurate so we return this guess\n return g;\n }\n // Recursively solve for closer and closer approximations of the square root\n return squirt(n, ng); //Recursion till g === ng\n}",
"function normalizeInRange(start, end, value) {\n if (value < 0.0 || value > 1.0) {\n return -1;\n }\n\n if (end < start) {\n // if end is 45 and start is 50\n\n return start - ((start - end) * value); \n } else {\n // if end is 55 and start is 50\n\n return start + ((end - start) * value);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the given properties match those of a `ActivityMetricsProperty` | function CfnStorageLens_ActivityMetricsPropertyValidator(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('isEnabled', cdk.validateBoolean)(properties.isEnabled));
return errors.wrap('supplied properties not correct for "ActivityMetricsProperty"');
} | [
"function CfnBucket_MetricsPropertyValidator(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('eventThreshold', CfnBucket_ReplicationTimeValuePropertyValidator)(properties.eventThreshold));\n errors.collect(cdk.propertyValidator('status', cdk.requiredValidator)(properties.status));\n errors.collect(cdk.propertyValidator('status', cdk.validateString)(properties.status));\n return errors.wrap('supplied properties not correct for \"MetricsProperty\"');\n}",
"function CfnAnomalyDetector_MetricPropertyValidator(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('aggregationFunction', cdk.requiredValidator)(properties.aggregationFunction));\n errors.collect(cdk.propertyValidator('aggregationFunction', cdk.validateString)(properties.aggregationFunction));\n errors.collect(cdk.propertyValidator('metricName', cdk.requiredValidator)(properties.metricName));\n errors.collect(cdk.propertyValidator('metricName', cdk.validateString)(properties.metricName));\n errors.collect(cdk.propertyValidator('namespace', cdk.validateString)(properties.namespace));\n return errors.wrap('supplied properties not correct for \"MetricProperty\"');\n}",
"function CfnStorageLens_AdvancedDataProtectionMetricsPropertyValidator(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('isEnabled', cdk.validateBoolean)(properties.isEnabled));\n return errors.wrap('supplied properties not correct for \"AdvancedDataProtectionMetricsProperty\"');\n}",
"function CfnAnomalyDetector_MetricSetPropertyValidator(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('dimensionList', cdk.listValidator(cdk.validateString))(properties.dimensionList));\n errors.collect(cdk.propertyValidator('metricList', cdk.requiredValidator)(properties.metricList));\n errors.collect(cdk.propertyValidator('metricList', cdk.listValidator(CfnAnomalyDetector_MetricPropertyValidator))(properties.metricList));\n errors.collect(cdk.propertyValidator('metricSetDescription', cdk.validateString)(properties.metricSetDescription));\n errors.collect(cdk.propertyValidator('metricSetFrequency', cdk.validateString)(properties.metricSetFrequency));\n errors.collect(cdk.propertyValidator('metricSetName', cdk.requiredValidator)(properties.metricSetName));\n errors.collect(cdk.propertyValidator('metricSetName', cdk.validateString)(properties.metricSetName));\n errors.collect(cdk.propertyValidator('metricSource', cdk.requiredValidator)(properties.metricSource));\n errors.collect(cdk.propertyValidator('metricSource', CfnAnomalyDetector_MetricSourcePropertyValidator)(properties.metricSource));\n errors.collect(cdk.propertyValidator('offset', cdk.validateNumber)(properties.offset));\n errors.collect(cdk.propertyValidator('timestampColumn', CfnAnomalyDetector_TimestampColumnPropertyValidator)(properties.timestampColumn));\n errors.collect(cdk.propertyValidator('timezone', cdk.validateString)(properties.timezone));\n return errors.wrap('supplied properties not correct for \"MetricSetProperty\"');\n}",
"function CfnStorageLens_DetailedStatusCodesMetricsPropertyValidator(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('isEnabled', cdk.validateBoolean)(properties.isEnabled));\n return errors.wrap('supplied properties not correct for \"DetailedStatusCodesMetricsProperty\"');\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 cfnStorageLensActivityMetricsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_ActivityMetricsPropertyValidator(properties).assertSuccess();\n return {\n IsEnabled: cdk.booleanToCloudFormation(properties.isEnabled),\n };\n}",
"function CfnBucket_MetricsConfigurationPropertyValidator(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('accessPointArn', cdk.validateString)(properties.accessPointArn));\n errors.collect(cdk.propertyValidator('id', cdk.requiredValidator)(properties.id));\n errors.collect(cdk.propertyValidator('id', cdk.validateString)(properties.id));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('tagFilters', cdk.listValidator(CfnBucket_TagFilterPropertyValidator))(properties.tagFilters));\n return errors.wrap('supplied properties not correct for \"MetricsConfigurationProperty\"');\n}",
"function checkVisibilityConstraints(props) {\n var constraints = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _mapState.MAPBOX_LIMITS;\n\n for (var constraintName in constraints) {\n // in the format of min* or max*\n var type = constraintName.slice(0, 3);\n var propName = decapitalize(constraintName.slice(3));\n\n if (type === 'min' && props[propName] < constraints[constraintName]) {\n return false;\n }\n\n if (type === 'max' && props[propName] > constraints[constraintName]) {\n return false;\n }\n }\n\n return true;\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 CfnStorageLens_AdvancedCostOptimizationMetricsPropertyValidator(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('isEnabled', cdk.validateBoolean)(properties.isEnabled));\n return errors.wrap('supplied properties not correct for \"AdvancedCostOptimizationMetricsProperty\"');\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 checkProperty(previous, property) {\n console.log(\"[EVT] Checking if property \" + property.key + \" changed to \" + property.value + \" \" + JSON.stringify(previous));\n\n if (previous[property.key]) {\n console.log(\"[EVT] Property present\");\n if (previous[property.key] === property.value) {\n console.log(\"[EVT] Same value, no need to forward\");\n return false;\n }\n else if ((property.key === 'x') || (property.key === 'y')) {\n console.log(\"[EVT] Checking x, y values from Hue\");\n if (previous.color.cie1931[property.key] === property.value) {\n console.log(\"[EVT] Same value, no need to forward\");\n return false;\n }\n }\n }\n return true;\n}",
"function hasProperties(json, properties) {\n return properties.every(property => {\n return json.hasOwnProperty(property);\n });\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 CfnAnomalyDetectorPropsValidator(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('anomalyDetectorConfig', cdk.requiredValidator)(properties.anomalyDetectorConfig));\n errors.collect(cdk.propertyValidator('anomalyDetectorConfig', CfnAnomalyDetector_AnomalyDetectorConfigPropertyValidator)(properties.anomalyDetectorConfig));\n errors.collect(cdk.propertyValidator('anomalyDetectorDescription', cdk.validateString)(properties.anomalyDetectorDescription));\n errors.collect(cdk.propertyValidator('anomalyDetectorName', cdk.validateString)(properties.anomalyDetectorName));\n errors.collect(cdk.propertyValidator('kmsKeyArn', cdk.validateString)(properties.kmsKeyArn));\n errors.collect(cdk.propertyValidator('metricSetList', cdk.requiredValidator)(properties.metricSetList));\n errors.collect(cdk.propertyValidator('metricSetList', cdk.listValidator(CfnAnomalyDetector_MetricSetPropertyValidator))(properties.metricSetList));\n return errors.wrap('supplied properties not correct for \"CfnAnomalyDetectorProps\"');\n}",
"function CfnRoute_GrpcRouteActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('weightedTargets', cdk.requiredValidator)(properties.weightedTargets));\n errors.collect(cdk.propertyValidator('weightedTargets', cdk.listValidator(CfnRoute_WeightedTargetPropertyValidator))(properties.weightedTargets));\n return errors.wrap('supplied properties not correct for \"GrpcRouteActionProperty\"');\n}",
"function CfnGatewayRoute_GrpcGatewayRouteMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('hostname', CfnGatewayRoute_GatewayRouteHostnameMatchPropertyValidator)(properties.hostname));\n errors.collect(cdk.propertyValidator('metadata', cdk.listValidator(CfnGatewayRoute_GrpcGatewayRouteMetadataPropertyValidator))(properties.metadata));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('serviceName', cdk.validateString)(properties.serviceName));\n return errors.wrap('supplied properties not correct for \"GrpcGatewayRouteMatchProperty\"');\n}",
"function CfnRoute_MatchRangePropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('end', cdk.requiredValidator)(properties.end));\n errors.collect(cdk.propertyValidator('end', cdk.validateNumber)(properties.end));\n errors.collect(cdk.propertyValidator('start', cdk.requiredValidator)(properties.start));\n errors.collect(cdk.propertyValidator('start', cdk.validateNumber)(properties.start));\n return errors.wrap('supplied properties not correct for \"MatchRangeProperty\"');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends the stored commands possible without changing the mapping. Note: this._current_row_major_mapping (hence also this.currentMapping) must exist already | _sendPossibleCommands() {
const active_ids = new Set(Array.from(this._currently_allocated_ids).map(k => parseInt(k, 10)))
Object.keys(this._current_row_major_mapping).forEach(logical_id => active_ids.add(parseInt(logical_id, 10)))
let new_stored_commands = []
for (let i = 0; i < this._stored_commands.length; ++i) {
const cmd = this._stored_commands[i]
if (len(active_ids) === 0) {
new_stored_commands = new_stored_commands.concat(this._stored_commands.slice(i))
break
}
if (cmd.gate instanceof AllocateQubitGate) {
const qid = cmd.qubits[0][0].id
if (qid in this._current_row_major_mapping) {
this._currently_allocated_ids.add(qid)
const mapped_id = this._current_row_major_mapping[qid]
const qb = new BasicQubit(this, this._mapped_ids_to_backend_ids[mapped_id])
const new_cmd = new Command(this, new AllocateQubitGate(), tuple([qb]), [], [new LogicalQubitIDTag(qid)])
this.send([new_cmd])
} else {
new_stored_commands.push(cmd)
}
} else if (cmd.gate instanceof DeallocateQubitGate) {
const qid = cmd.qubits[0][0].id
if (active_ids.has(qid)) {
const mapped_id = this._current_row_major_mapping[qid]
const qb = new BasicQubit(this, this._mapped_ids_to_backend_ids[mapped_id])
const new_cmd = new Command(this, new DeallocateQubitGate(), tuple([qb]), [], [new LogicalQubitIDTag(qid)])
this._currently_allocated_ids.delete(qid)
active_ids.delete(qid)
delete this._current_row_major_mapping[qid]
delete this._currentMapping[qid]
this.send([new_cmd])
} else {
new_stored_commands.push(cmd)
}
} else {
let send_gate = true
const mapped_ids = new Set()
for (let k = 0; k < cmd.allQubits.length; ++k) {
const qureg = cmd.allQubits[k]
for (let j = 0; j < qureg.length; ++j) {
const qubit = qureg[j]
if (!active_ids.has(qubit.id)) {
send_gate = false
break
}
mapped_ids.add(this._current_row_major_mapping[qubit.id])
}
}
// Check that mapped ids are nearest neighbour on 2D grid
if (len(mapped_ids) === 2) {
const [qb0, qb1] = Array.from(mapped_ids).sort((a, b) => a - b)
send_gate = false
if (qb1 - qb0 === this.num_columns) {
send_gate = true
} else if (qb1 - qb0 === 1 && (qb1 % this.num_columns !== 0)) {
send_gate = true
}
}
if (send_gate) {
// Note: This sends the cmd correctly with the backend ids
// as it looks up the mapping in this.currentMapping
// and not our internal mapping
// this._current_row_major_mapping
this.sendCMDWithMappedIDs(cmd)
} else {
cmd.allQubits.forEach(qureg => qureg.forEach(qubit => active_ids.delete(qubit.id)))
new_stored_commands.push(cmd)
}
}
}
this._stored_commands = new_stored_commands
} | [
"_run() {\n const num_of_stored_commands_before = len(this._stored_commands)\n if (!this._currentMapping) {\n this.currentMapping = {}\n } else {\n this._sendPossibleCommands()\n if (len(this._stored_commands) === 0) {\n return\n }\n }\n\n const new_row_major_mapping = this.returnNewMapping()\n // Find permutation of matchings with lowest cost\n let swaps\n let lowest_cost\n const matchings_numbers = arrayFromRange(this.num_rows)\n const ps = []\n if (this.num_optimization_steps <= math.factorial(this.num_rows)) {\n for (const looper of permutations(matchings_numbers, this.num_rows)) {\n ps.push(looper)\n }\n } else {\n for (let i = 0; i < this.num_optimization_steps; ++i) {\n ps.push(randomSample(matchings_numbers, this.num_rows))\n }\n }\n\n ps.forEach((permutation) => {\n const trial_swaps = this.returnSwaps(\n this._current_row_major_mapping,\n new_row_major_mapping,\n permutation\n )\n if (typeof swaps === 'undefined') {\n swaps = trial_swaps\n lowest_cost = this.optimization_function(trial_swaps)\n } else if (lowest_cost > this.optimization_function(trial_swaps)) {\n swaps = trial_swaps\n lowest_cost = this.optimization_function(trial_swaps)\n }\n })\n if (swaps.length > 0) { // first mapping requires no swaps\n // Allocate all mapped qubit ids (which are not already allocated,\n // i.e., contained in this._currently_allocated_ids)\n let mapped_ids_used = new Set()\n for (const logical_id of this._currently_allocated_ids) {\n mapped_ids_used.add(this._current_row_major_mapping[logical_id])\n }\n const not_allocated_ids = setDifference(setFromRange(this.num_qubits), mapped_ids_used)\n for (const mapped_id of not_allocated_ids) {\n const qb = new BasicQubit(this, this._mapped_ids_to_backend_ids[mapped_id])\n const cmd = new Command(this, new AllocateQubitGate(), tuple([qb]))\n this.send([cmd])\n }\n\n\n // Send swap operations to arrive at new_mapping:\n swaps.forEach(([qubit_id0, qubit_id1]) => {\n const q0 = new BasicQubit(this, this._mapped_ids_to_backend_ids[qubit_id0])\n const q1 = new BasicQubit(this, this._mapped_ids_to_backend_ids[qubit_id1])\n const cmd = new Command(this, Swap, tuple([q0], [q1]))\n this.send([cmd])\n })\n // Register statistics:\n this.num_mappings += 1\n const depth = return_swap_depth(swaps)\n if (!(depth in this.depth_of_swaps)) {\n this.depth_of_swaps[depth] = 1\n } else {\n this.depth_of_swaps[depth] += 1\n }\n if (!(len(swaps) in this.num_of_swaps_per_mapping)) {\n this.num_of_swaps_per_mapping[len(swaps)] = 1\n } else {\n this.num_of_swaps_per_mapping[len(swaps)] += 1\n }\n // Deallocate all previously mapped ids which we only needed for the\n // swaps:\n mapped_ids_used = new Set()\n for (const logical_id of this._currently_allocated_ids) {\n mapped_ids_used.add(new_row_major_mapping[logical_id])\n }\n const not_needed_anymore = setDifference(setFromRange(this.num_qubits), mapped_ids_used)\n for (const mapped_id of not_needed_anymore) {\n const qb = new BasicQubit(this, this._mapped_ids_to_backend_ids[mapped_id])\n const cmd = new Command(this, new DeallocateQubitGate(), tuple([qb]))\n this.send([cmd])\n }\n }\n\n // Change to new map:\n this._current_row_major_mapping = new_row_major_mapping\n const new_mapping = {}\n Object.keys(new_row_major_mapping).forEach((logical_id) => {\n const mapped_id = new_row_major_mapping[logical_id]\n new_mapping[logical_id] = this._mapped_ids_to_backend_ids[mapped_id]\n })\n\n this.currentMapping = new_mapping\n // Send possible gates\n this._sendPossibleCommands()\n // Check that mapper actually made progress\n if (len(this._stored_commands) === num_of_stored_commands_before) {\n throw new Error('Mapper is potentially in an infinite loop. '\n + 'It is likely that the algorithm requires '\n + 'too many qubits. Increase the number of '\n + 'qubits for this mapper.')\n }\n }",
"resetToDefault() {\n const command = this.edits.rowEl.dataset.command;\n const defaultMapping = Commands.defaultMappings.normal[command];\n this.edits.keyStrings = defaultMapping ? defaultMapping.split(Commands.KEY_SEPARATOR) : [];\n this.displayKeyString(this.edits.rowEl.querySelector(\".shortcut\"), defaultMapping);\n this.commitChange();\n }",
"sendNextCommand() {\n\t\tif (this.commandQueue.length > 0) {\n\t\t\tthis.socket.send(this.commandQueue[0]);\n\t\t\tthis.cts = false;\n\t\t}\n\t\telse {\n\t\t\tthis.cts = true;\n\t\t}\n\t}",
"batchUpdate() {\n let { row, colStart, colEnd } = this.pendingUpdate;\n const { cursor } = this.screen;\n\n this.pendingUpdate.row = cursor.row;\n this.pendingUpdate.colStart = this.pendingUpdate.colEnd = cursor.col;\n\n // Skip cells up to number column width so we don't output line numbers\n colStart = Math.max(this.lineNumberColumns, colStart);\n\n const lineNumberString = this.screen.cells[row].slice(0, this.lineNumberColumns).join('');\n // If start of number string is '~' then we have reached the end of the\n // file. Ignore changes is the line number column and any changes on\n // rows outside of the main text buffer (eg. the status line and\n // command line)\n if (lineNumberString[0] === '~' || colStart >= colEnd || row >= (this.statusLineNumber)) {\n return;\n }\n\n const text = this.screen.cells[row].slice(colStart, colEnd).join('');\n // As the cells as just the visible rows we need to translate the cell\n // row number to the actual line number. We have line numbers enabled\n // to easily allow this - extract the line number from the cell\n // contents.\n const lineNumber = Number(lineNumberString) - 1;\n const range = [\n [lineNumber, colStart - this.lineNumberColumns],\n [lineNumber, colEnd - this.lineNumberColumns]\n ];\n\n this.batch.push([range, text]);\n }",
"function submitMoveCommand(move) {\n\n if(move[0].command == 'move'){\n \n if(savedMap[move[0].to.x][move[0].to.y].tile == 'mount' || savedMap[move[0].from.x][move[0].from.y].units < 2){\n\n var badPath = savedMap[move[0].to.x][move[0].to.y];\n var pathIsGood = false;\n\n if(commandStack.length > 0){\n\n while(!pathIsGood && commandStack.length > 0){\n\n if ( isAdjacent( badPath , commandStack[0].to ) ) {\n \n displayElement(savedMap[commandStack[0].to.x][commandStack[0].to.y]);\n\n badPath = savedMap[commandStack[0].to.x][commandStack[0].to.y];\n commandStack.splice(0,1);\n\n deletePath();\n\n } \n \n else \n\n pathIsGood = true;\n\n }\n }\n }\n\n else{\n console.log(move[0]);\n socket.emit('makeMove', move[0]);\n }\n\n }\n else {\n console.log(move[0]);\n socket.emit('makeMove', move[0]);\n }\n\n}",
"flushWrites() {\n for (const tableName in this.writeOperations) {\n if (this.writeOperations[tableName].isEmpty()) {\n delete this.writeOperations[tableName];\n }\n else {\n this.writeOperations[tableName].execute();\n }\n }\n }",
"async FillRegisteredCommands () {\n this.REGISTERED_COMMANDS.GLOBAL = await this.GetAll({ local: false })\n this.REGISTERED_COMMANDS.LOCAL = await this.GetAll({ local: true })\n\n if (!this.config.UNIT_TESTS) { this.Purge() }\n }",
"sync_nearby ()\n {\n loot.CallRemoteCell('loot/sync/basic', this.cell.x, this.cell.y, JSON.stringify(this.get_basic_sync_data()));\n }",
"_normalizeCommandKeys() {\n // Normalize all command keys to be lowercase\n for (const [key, value] of this.Commands.entries()) {\n const lowercaseKey = key.toLowerCase();\n if (key !== lowercaseKey) {\n logger.info(`Switching ${key} command to lowercase ${lowercaseKey}`);\n this.Commands.set(lowercaseKey, value);\n this.Commands.delete(key);\n }\n }\n }",
"updateCommandInput() {\n const v = this.range;\n const nextPosition = this.nextPosition.value; // will be \"undefined\" in 2d.. defines behaviour of how next positions are computed\n const robots = [...canvasScript.robots].map(([label, {position: {x}, data: {faulty, localPosition: {y}}}]) => ({\n label,\n faulty,\n x: x - canvasScript.MIN_X,\n y: canvasScript.is2d() ? y : undefined,\n }));\n const command = {v, nextPosition, robots};\n this.commandInput.value = JSON.stringify(command, null, '\\t');\n\n // we know the command is good, no need to `parseCommandValue` it...\n // but we need to make sure it has at least 2 robots for it to be 100% valid\n if (robots.length < 2) {\n this.goodCommandIcon.classList.remove(\"show\");\n this.badCommandIcon.classList.add(\"show\");\n this.saveButton.disabled = true;\n } else {\n this.goodCommandIcon.classList.add(\"show\");\n this.badCommandIcon.classList.remove(\"show\");\n this.saveButton.disabled = false;\n }\n\n }",
"processRadioRows(){\n\t\tconsole.log(\"processRadioRows()\");\n\t\t//console.log(\"processRadioRows()\")\n\t\tif(this.new_rows){\n\t\t\tif(this.new_rows.length > 0){\n\t\t\t\tthis.new_current_row = this.new_rows.shift()\n\t\t\t\t//console.log(\"this.new_current_row (first_row)\",this.new_current_row)\n\t\t\t\tthis.processRadioRow(this.new_current_row) //solo pasamos la primer row de new_rows donde estan todos a processRow\t\n\t\t\t}else{\n\t\t\t\t\n\t\t\t\tthis.new_rows = null;\n\t\t\t\tthis.write([0x11]) //finish the rows sending should return 0x0D or 13\n\t\t\t}\n\t\t}else{\n\t\t\t\n\t\t\tconsole.log(\"there is not rows array on processRows\")\n\t\t}\n\t}",
"onOSCMessage(message){\n //Retransmits the message to every single robot\n for(let key of this.robots.keys()){\n this.sendCommand(key, message.cmd, message.arg);\n }\n }",
"submitCmd(){\n this.cmdText += `> ${this.cmd}\\n`\n let parsed = this.cmd.replace(/^\\s+/, '').split(/\\s+/)\n\n if(parsed[0]){\n let query = parsed[0].toLowerCase()\n if(cmds[query]){\n cmds[query](this, parsed.slice(1), mrp, db)\n }\n else {\n this.cmdText += `Command '${query}' not found. Type 'help' for a manual.`\n }\n }\n\n this.cmd = ''\n }",
"function loadCommandFloodProtect(){\r\n var oldsendcmd = unsafeWindow.sendcmd;\r\n unsafeWindow.sendcmd = function(command, data){\r\n if(command){\r\n //add the command to the cache\r\n commandCache.push({command:command,data:data});\r\n }\r\n //are we ready to send a command?\r\n if(sendcmdReady){\r\n if(commandCache.length !== 0){\r\n //set not ready\r\n sendcmdReady = false;\r\n //send the command\r\n oldsendcmd(commandCache[0].command,commandCache[0].data);\r\n //remove the sent command\r\n commandCache.splice(0,1);\r\n //after 400ms send the next command\r\n setTimeout(function(){sendcmdReady = true;unsafeWindow.sendcmd();},400);\r\n }\r\n }\r\n };\r\n}",
"function sendNoSuchCommandFound(){\n\tsendSMS('No such command found. Type \\'commands\\' for a list of commands.');\n}",
"_checkSendBuffer() {\n\n this._d(`${this.insertIndex} / ${this.deleteIndex}.`);\n\n if ( this.insertIndex === this.deleteIndex ) {\n\n // end buffer is 'empty' => nothing to do then wait till's flled again.\n this.isLoopRunning = false ;\n this._d(\"Send loop temp stopped - empty send buffer.\");\n } else {\n if ( this.sendAr[ this.deleteIndex ] === \"\" ) {\n\n // If the command to be send if empty consider it as\n // empty buffer and exit the data send loop.\n this.isLoopRunning = false ;\n this._d(\"Sendbuffer entry empty (stopping send loop)!.\");\n } else {\n let data = this.sendAr[ this.deleteIndex ];\n this.sendAr[ this.deleteIndex ] = \"\"; // clear used buffer.\n this.deleteIndex++;\n\n if ( this.deleteIndex >= this.MAXINDEX ) {\n this.deleteIndex = 0;\n }\n this._d(`Setting deleteIndex to ${this.deleteIndex}.`);\n\n this._sendToAvr( data );\n }\n }\n }",
"function processFinalStateChangingCommands(frame, commands, states, characters) {\n for(var player = 0; player <= 1; player++) {\n var command = commands[player][frame];\n\n // no command to be found\n if(!command) {\n continue;\n\n // land\n } else if(command == \"_L\" && states[player].airborne) {\n if(states[player].type == PlayerState.ATTACKING && states[player].move.recovery_after_landing) {\n states[player].type = PlayerState.LANDING_RECOVERY;\n states[player].landingRecovery = states[player].move.recovery_after_landing;\n } else {\n states[player].type = PlayerState.NEUTRAL;\n }\n states[player].airborne = false;\n }\n }\n}",
"function Commands({\n nodes,\n height,\n}) {\n /** Agents */\n // const [agentList, setAgentList] = useState([]);\n const list = useSelector((s) => s.list.agent_list);\n const macro = useSelector((s) => s.macro);\n const incoming = useSelector((s) => s.data);\n\n /** Selected agent to get requests from */\n const [selectedAgent, setSelectedAgent] = useState([]);\n /** Requests possible from selectedAgent */\n const [agentRequests, setAgentRequests] = useState({});\n /** List of sorted agent requests */\n const [sortedAgentRequests, setSortedAgentRequests] = useState([]);\n /** Selected agent request */\n const [selectedRequest, setSelectedRequest] = useState('> agent');\n /** Agent command arguments */\n const [commandArguments, setCommandArguments] = useState('');\n /** Agent command history (to display in the terminal) */\n const [commandHistory, setCommandHistory] = useState([]);\n /** Save the last sent argument value */\n const [lastArgument, setLastArgument] = useState('');\n /** Auto scroll the history log to the bottom */\n const [updateLog, setUpdateLog] = useState(null);\n /** Store autocompletions */\n const [autocompletions, setAutocompletions] = useState([]);\n /** Currently selected dropdown value of command list */\n const [macroCommand, setMacroCommand] = useState(null);\n\n /** Node to send data to */\n const [commandNode, setCommandNode] = useState(nodes[0]);\n /** List of commands stored in the node */\n const [commands, setCommands] = useState([]);\n /** Command to be sent */\n const [sending, setSending] = useState({});\n /** Time to send command */\n const [timeSend, setTimeSend] = useState(null);\n /** Time to send command */\n const [elapsedTime, setElapsedTime] = useState(0);\n /** Form to create a new command */\n const [commandForm] = Form.useForm();\n /** The command selected to be deleted */\n const [selected, setSelected] = useState(null);\n /** The global node to create/delete commands from */\n const [globalNode, setGlobalNode] = useState(commandNode);\n /** List of commands from the global node selected */\n const [deleteList, setDeleteList] = useState([]);\n\n /** DOM Element selector for history log */\n const cliEl = useRef(null);\n /** DOM Element selector for argument input */\n const inputEl = useRef(null);\n\n const commandHistoryEl = useRef(null);\n commandHistoryEl.current = commandHistory;\n\n const queryCommands = async (query = null, timeToSend = null) => {\n try {\n let data;\n switch (query) {\n case 'send':\n try {\n await axios.post(`/exec/${commandNode}`, {\n event: {\n event_data: sending.event_data,\n event_utc: timeToSend != null ? dateToMJD(dayjs()) : timeToSend,\n event_type: sending.event_type,\n event_flag: sending.event_flag,\n event_name: sending.event_name,\n },\n });\n setCommandHistory([\n ...commandHistoryEl.current,\n `➜ ${dayjs.utc().format()} ${commandNode} ${sending.event_data}`,\n ]);\n message.success(`Command '${sending.event_name}' has been sent to ${commandNode}!`);\n } catch {\n message.error(`Error executing ${macroCommand} on ${commandNode}.`);\n }\n break;\n case 'delete':\n try {\n data = await axios.delete(`/commands/${globalNode}`, {\n data: {\n event_name: selected,\n },\n });\n message.success(`${selected} deleted successfully.`);\n setSelected(null);\n } catch (err) {\n message.error(`Error deleting ${selected}.`);\n }\n break;\n default:\n break;\n }\n\n data = await axios.get(`/commands/${commandNode}`);\n\n setCommands(data.data);\n if (commandNode === globalNode) {\n setDeleteList(data.data);\n } else {\n data = await axios.get(`/commands/${globalNode}`);\n setDeleteList(data.data);\n }\n } catch (error) {\n message.error('Could not query commands from database.');\n }\n };\n\n /** Generate commands in database */\n const createCommand = async () => {\n const form = commandForm.getFieldsValue();\n\n if (deleteList.find((command) => command.event_name === form.name)) {\n message.error('Duplicate command cannot be created.');\n } else {\n try {\n await axios.post(`/commands/${globalNode}`, {\n command: {\n event_name: form.name,\n event_type: form.type,\n event_flag: form.flag,\n event_data: form.command,\n },\n });\n message.success(`Successfully created ${form.name}!`);\n } catch {\n message.error(`Error creating ${form.name}`);\n }\n\n commandForm.resetFields();\n }\n\n queryCommands();\n };\n\n useEffect(() => {\n queryCommands();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n const incomingInfo = Object.keys(incoming).find((el) => el.split(':')[1] === 'executed');\n if (incomingInfo != null) {\n setCommandHistory([\n ...commandHistoryEl.current,\n `${dayjs.utc().format()} ${incomingInfo}`,\n ]);\n }\n }, [incoming]);\n\n /** Manages requests for agent list and agent [node] [process] */\n const sendCommandApi = async (command) => {\n setCommandHistory([\n ...commandHistoryEl.current,\n `➜ ${dayjs.utc().format()} ${command}`,\n ]);\n\n setUpdateLog(true);\n\n // retrieve command output\n try {\n const { data } = await axios.post('/command', {\n data: {\n command,\n },\n });\n\n try {\n const json = JSON.parse(data);\n\n // json checking for json.output, json.error\n if (json && json.output && json.output.requests) {\n const sortedRequests = [];\n const requests = {};\n\n // Clear agent requests for new agent\n json.output.requests.forEach((request) => {\n sortedRequests.push(\n request.token,\n );\n\n // Make commands mapped into an object\n requests[request.token] = {\n ...request,\n };\n });\n\n // Alphabetical order\n sortedRequests.sort();\n\n // Set agent requests\n setAgentRequests(requests);\n setSortedAgentRequests(sortedRequests);\n\n message.destroy();\n message.success('Retrieved agent requests.');\n } else if (json && json.output) {\n // agent node proc cmd\n setCommandHistory([\n ...commandHistoryEl.current,\n `${dayjs.utc().format()} ${data.output}`,\n ]);\n\n message.destroy();\n } else if (json && json.error) {\n throw new Error(json.error);\n } else {\n throw new Error();\n }\n } catch (error) {\n message.destroy();\n // non-json\n setCommandHistory([\n ...commandHistoryEl.current,\n `${dayjs.utc().format()} ${data}`,\n ]);\n }\n setUpdateLog(true);\n } catch (error) {\n message.destroy();\n message.error(error.message);\n }\n };\n\n /** Handle submission of agent command */\n const sendCommand = async () => {\n setLastArgument(commandArguments);\n\n switch (selectedRequest) {\n case '> agent':\n sendCommandApi(`${process.env.COSMOS_BIN}agent ${commandArguments}`);\n break;\n case '> command_generator':\n sendCommandApi(`${process.env.COSMOS_BIN}command_generator ${commandArguments.replace(/\"/g, \"'\")}`);\n break;\n default:\n sendCommandApi(`${process.env.COSMOS_BIN}agent ${selectedAgent[0]} ${selectedAgent[1]} ${selectedRequest} ${macro ? `${macro} ` : ''}${commandArguments}`);\n break;\n }\n\n setUpdateLog(true);\n };\n\n /** Retrieve file autocompletion */\n const getAutocomplete = async (autocomplete) => {\n setCommandHistory([\n ...commandHistory,\n `autocomplete ${autocomplete}`,\n ]);\n\n // retrieve autocompletions\n const { data } = await axios.post('/command', {\n responseType: 'text',\n data: {\n command: `compgen -c ${autocomplete}`,\n },\n });\n\n setAutocompletions(data.split('\\n'));\n };\n\n /** Autocomplete automatically if it's the only one in the array */\n useEffect(() => {\n if (autocompletions.length === 2) {\n const args = commandArguments.split(' ');\n\n // eslint-disable-next-line prefer-destructuring\n args[args.length - 1] = autocompletions[0];\n\n setCommandArguments(args.join(' '));\n\n setAutocompletions([]);\n\n setUpdateLog(true);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [autocompletions]);\n\n /** Get the possible requests for selected agent */\n const getRequests = async (agent) => {\n setSelectedAgent(agent);\n\n setSortedAgentRequests([]);\n setAgentRequests({});\n\n if (agent.length > 0) {\n sendCommandApi(`${process.env.COSMOS_BIN}agent ${agent[0]} ${agent[1]} help_json`);\n }\n };\n\n /** Update height of the history log to go to the bottom */\n useEffect(() => {\n cliEl.current.scrollTop = cliEl.current.scrollHeight;\n setUpdateLog(null);\n }, [updateLog]);\n\n const colorTime = (command, i) => {\n const allCommands = command.split(' ');\n\n if (allCommands[0] === '➜') {\n allCommands.splice(0, 1);\n const time = allCommands.splice(0, 1);\n\n return (\n <div key={i}>\n ➜ \n <span className=\"text-gray-600\">\n [\n {time}\n ]\n </span>\n \n { allCommands.join(' ')}\n </div>\n );\n }\n\n const time = allCommands.splice(0, 1);\n\n return (\n <div key={i}>\n <span className=\"text-gray-600\">\n [\n {time}\n ]\n </span>\n \n {\n allCommands.join(' ')\n }\n </div>\n );\n };\n\n return (\n <BaseComponent\n name=\"Commands\"\n subheader=\"\"\n liveOnly\n height={height}\n showStatus={false}\n formItems={(\n <>\n <div>\n Target Node:\n <Select\n className=\"ml-2 w-32\"\n showSearch\n onChange={(value) => setGlobalNode(value)}\n onBlur={() => queryCommands()}\n placeholder=\"Select target node\"\n defaultValue={globalNode}\n value={globalNode}\n >\n {\n nodes.map((n) => (\n <Select.Option\n key={n}\n >\n {n}\n </Select.Option>\n ))\n }\n </Select>\n </div>\n <Tabs defaultActiveKey=\"1\">\n <TabPane tab=\"Create Command\" key=\"1\">\n <Form\n form={commandForm}\n layout=\"vertical\"\n name=\"commandForm\"\n onFinish={() => createCommand()}\n >\n <table className=\"w-full\">\n <tbody>\n <tr>\n <th>\n <Form.Item\n className=\"font-light w-4/5\"\n label=\"Event Name\"\n name=\"name\"\n rules={[{ required: true, message: 'Please type a name.' }]}\n >\n <Input placeholder=\"Name\" />\n </Form.Item>\n </th>\n <th rowSpan={2}>\n <Form.Item\n className=\"font-light\"\n label=\"Type\"\n name=\"type\"\n rules={[{ required: true, message: 'Please choose a type.' }]}\n >\n <InputNumber placeholder=\"#\" />\n </Form.Item>\n </th>\n <th>\n <Form.Item\n className=\"font-light\"\n label=\"Flag\"\n name=\"flag\"\n rules={[{ required: true, message: 'Please choose a flag.' }]}\n >\n <InputNumber placeholder=\"#\" />\n </Form.Item>\n </th>\n </tr>\n </tbody>\n </table>\n <Form.Item\n label=\"Command\"\n name=\"command\"\n rules={[{ required: true, message: 'Please type a command.' }]}\n >\n <Input placeholder=\"ex: ls, /bin/systemctl stop agent_cpu\" prefix=\"➜\" />\n </Form.Item>\n <hr className=\"mb-6\" />\n <Form.Item>\n <Button htmlType=\"submit\" type=\"primary\">\n Create\n </Button>\n </Form.Item>\n </Form>\n </TabPane>\n <TabPane tab=\"Delete Command\" key=\"2\">\n <Select\n placeholder=\"Select command to delete\"\n className=\"w-full mb-4\"\n onChange={(value) => setSelected(value)}\n >\n {deleteList.map((com) => (\n <Select.Option\n key={com.event_name}\n >\n {com.event_name}\n </Select.Option>\n ))}\n </Select>\n <hr className=\"mb-5\" />\n <Popconfirm\n placement=\"right\"\n title={`Are you sure you want to delete '${selected}' for ${globalNode}?`}\n onConfirm={() => queryCommands('delete')}\n okText=\"Yes\"\n cancelText=\"No\"\n icon={<ExclamationCircleOutlined style={{ color: 'red' }} />}\n >\n <Button\n type=\"primary\"\n disabled={!selected}\n danger\n >\n Delete\n </Button>\n </Popconfirm>\n </TabPane>\n </Tabs>\n </>\n )}\n >\n <div className=\"flex flex-wrap\">\n <div\n className=\"w-full\"\n >\n <Select\n className=\"block mb-2\"\n dropdownMatchSelectWidth={false}\n onChange={(value) => getRequests(value.split(':'))}\n placeholder=\"Select agent node and process\"\n >\n {\n list ? list.map(({ agent }) => (\n <Select.Option\n key={agent}\n >\n {agent}\n </Select.Option>\n )) : null\n }\n </Select>\n <div className=\"flex\">\n <Select\n showSearch\n className=\"mr-2 w-32\"\n onChange={(value) => setCommandNode(value)}\n onBlur={() => {\n // Change target node when changing command node\n setGlobalNode(commandNode);\n queryCommands();\n }}\n placeholder=\"Select node\"\n defaultValue={commandNode}\n value={commandNode}\n >\n {\n nodes.map((n) => (\n <Select.Option\n key={n}\n >\n {n}\n </Select.Option>\n ))\n }\n </Select>\n <div className=\"mr-2\">\n <Select\n showSearch\n className=\"block mb-2\"\n onChange={(value) => setMacroCommand(value)}\n onBlur={() => {\n const info = commands.find((command) => command.event_name === macroCommand);\n if (info) {\n setSending(info);\n }\n }}\n placeholder=\"Command List\"\n >\n {\n commands.map((command) => (\n <Select.Option\n key={command.event_name}\n >\n {command.event_name}\n </Select.Option>\n ))\n }\n </Select>\n </div>\n <div className=\"border-l mr-2 h-8\" />\n <DatePicker\n className=\"h-8 mr-2\"\n showTime\n onChange={(val) => setTimeSend(val)}\n />\n <Popconfirm\n placement=\"topRight\"\n title={`Send '${commandNode} ➜ ${sending.event_data}'?`}\n onConfirm={() => queryCommands('send', timeSend)}\n okText=\"Yes\"\n cancelText=\"No\"\n >\n <Button\n icon={<SendOutlined />}\n className=\"mr-2\"\n disabled={timeSend === null || macroCommand === null}\n >\n Send\n </Button>\n </Popconfirm>\n <RetweetOutlined className=\"mt-2 mr-2\" />\n <InputNumber\n className=\"h-8 mr-2 w-12\"\n formatter={(val) => `${val}s`}\n parser={(val) => val.replace('s', '')}\n min={0}\n max={60}\n onChange={(val) => setElapsedTime(val)}\n />\n <Popconfirm\n placement=\"topRight\"\n title={`Send '${commandNode} ➜ ${sending.event_data}' ${elapsedTime} seconds from now?`}\n onConfirm={() => queryCommands('send', dayjs().add(elapsedTime, 's'))}\n okText=\"Yes\"\n cancelText=\"No\"\n >\n <Button\n icon={<SendOutlined />}\n className=\"mr-2\"\n disabled={macroCommand === null || elapsedTime === null}\n >\n Send\n </Button>\n </Popconfirm>\n <div className=\"border-l mr-2 h-8\" />\n <Button\n onClick={() => {\n message.loading('Querying...');\n queryCommands();\n message.destroy();\n message.success('Querying complete.');\n }}\n type=\"dashed\"\n >\n Re-query Command List\n </Button>\n </div>\n </div>\n {/* <div className=\"w-full py-2\">\n <Search\n placeholder=\"Select node:process\"\n onSearch={(value) => setSelectedAgent(value.split(':'))}\n enterButton={<SelectOutlined />}\n />\n </div> */}\n </div>\n <div\n className=\"border border-gray-300 rounded mb-2 p-4 bg-white font-mono h-32 max-h-full resize-y overflow-y-auto\"\n ref={cliEl}\n >\n {\n // eslint-disable-next-line\n commandHistory.map((command, i) => (colorTime(command, i)))\n }\n {\n autocompletions.length > 1\n ? (\n <span className=\"text-red-500 cursor-pointer hover:underline\">\n Clear \n <CloseOutlined onClick={() => setAutocompletions([])} />\n </span>\n )\n : ''\n }\n {\n autocompletions.map((autocompletion) => (\n <span\n tabIndex={0}\n role=\"link\"\n onClick={() => {\n // Change the last array element of the command arguments\n // to have selected autocompeleted path\n const args = commandArguments.split(' ');\n\n args[args.length - 1] = autocompletion;\n setCommandArguments(args.join(' '));\n\n inputEl.current.focus();\n }}\n onKeyDown={() => { }}\n className=\"text-blue-500 p-2 hover:underline cursor-pointer\"\n key={autocompletion}\n >\n {autocompletion}\n </span>\n ))\n }\n </div>\n <div className=\"flex\">\n <Input\n addonBefore={(\n <Select\n showSearch\n className=\"w-auto\"\n defaultValue=\"> agent\"\n dropdownMatchSelectWidth={false}\n onChange={(value) => setSelectedRequest(value)}\n value={selectedRequest}\n style={minWidth}\n >\n <Select.Option value=\"> agent\">\n <Tooltip placement=\"right\" title=\"node process [arguments]\">\n ➜ agent\n </Tooltip>\n </Select.Option>\n <Select.Option value=\"> command_generator\">\n <Tooltip placement=\"right\" title=\"name command [time | +sec] [node] [condition] [repeat_flag]\">\n ➜ command_generator\n </Tooltip>\n </Select.Option>\n {\n sortedAgentRequests.map((token) => (\n <Select.Option value={token} key={token}>\n <Tooltip placement=\"right\" title={`${agentRequests[token] && agentRequests[token].synopsis ? `${agentRequests[token].synopsis} ` : ''}${agentRequests[token].description}`}>\n {token}\n </Tooltip>\n </Select.Option>\n ))\n }\n </Select>\n )}\n addonAfter={(\n <div\n className=\"cursor-pointer text-blue-600 hover:text-blue-400\"\n onClick={() => {\n sendCommand();\n setCommandArguments('');\n }}\n onKeyDown={() => { }}\n role=\"button\"\n tabIndex={0}\n >\n Send\n </div>\n )}\n placeholder=\"Arguments\"\n onChange={({ target: { value } }) => setCommandArguments(value)}\n onPressEnter={() => {\n sendCommand();\n setCommandArguments('');\n }}\n onKeyDown={(e) => {\n if (e.keyCode === 38) {\n setCommandArguments(lastArgument);\n } else if (e.keyCode === 9) {\n e.preventDefault();\n getAutocomplete(commandArguments.split(' ')[commandArguments.split(' ').length - 1]);\n }\n }}\n value={commandArguments}\n ref={inputEl}\n />\n </div>\n </BaseComponent>\n );\n}",
"function sendCmd(cmd) {\n return sendJson(ip+\"/cmd/{'c':\"+cmd+\"}\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Text is added to DOM | function addTextToDom(text) {
console.log('Adding the following Stirng to dom: ' + text);
const textContainer = document.getElementById('greeting-container');
textContainer.innerText = text;
} | [
"appendText(str) {\n this.current.appendChild(browser.createTextNode(str));\n return this;\n }",
"createText(){\n let text = Text.createText(this.activeColor);\n this.canvas.add(text);\n this.notifyCanvasChange(text.id, \"added\");\n }",
"write(text) {\n this.element.appendChild(document.createElement(\"div\")).textContent = text\n }",
"function appendTextToNode(id, text) {\n\t\tlet elem = document.getElementById(id);\n\t\tlet textNode = document.createTextNode(text);\n\t\telem.appendChild(textNode);\n\t}",
"function appendEntText(outputText)\n{\n\tentityDesc += outputText + \"<br>\";\n}",
"function addNewContent() {\n var para = document.createElement(\"p\");\n var node = document.createTextNode(\"The new text\");\n para.appendChild(node);\n\n var targetDiv = document.getElementById(\"theDiv\");\n targetDiv.appendChild(para);\n\n console.log(targetDiv.innerHTML);\n}",
"function updateTextUI() {\n select('#result_hf').html(currentText);\n}",
"function onAddLine() {\n addLine()\n document.querySelector('[name=\"text\"]').value = 'TYPE SOMETHING'\n renderMeme()\n}",
"function setText (elem, new_text)\n{\n if (!elem) {\n return;\n }\n\n newTextNode = document.createTextNode(new_text);\n\n if (elem.childNodes[0]) {\n elem.replaceChild(newTextNode, elem.childNodes[0]);\n } else {\n elem.appendChild(newTextNode);\n }\n}",
"function updateDescription(scene) {\n const textTag = document.getElementById(\"text\");\n textTag.innerText = scene.text;\n}",
"function appendStatus(text) {\n var status = document.getElementById('status');\n status.innerHTML += text + '<br>';\n}",
"function addElement(doc, parent, name, text) {\n\tvar e = doc.createElement(name);\n\tvar txt = doc.createTextNode(text);\n\t\n\te.appendChild(txt);\n\tparent.appendChild(e);\n\t\n\treturn e;\n}",
"function addParagraph(text) {\n // code goes here\n const paraGraph = document.createElement('p');\n paragraphListElement.appendChild(paraGraph).innerText = `${text}`;\n}",
"function addRandomText() {\n const newText = {\n id: uuidv4(),\n title: random_text,\n };\n // set state, adding the new text\n setItems((state) => [newText, ...state]);\n }",
"function questionWrite() {\n questionEl.textContent = questionText;\n}",
"function updateLog(text){\n actionLogDisplay.innerHTML = \n text + \"\\n\" + actionLogDisplay.innerHTML;\n}",
"function setInnerText (id, text) {\n document.getElementById(id).innerText = text;\n}",
"function insertProjectNameInDOM() {\n var oldValue = \"<b><u>Nom du Projet :</u></b> \";\n document.getElementById(\"projectName\").innerHTML = oldValue + getSelectedProjectsName();\n}",
"function createTextElement(text) {\n return new VirtualElement(0 /* Text */, text, emptyObject, emptyArray);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the app assets for this addon. These are the various classes that live under `app/`, including actions, models, etc., as well as any custom class types. Files are loaded into the container under their folder's namespace, so `app/roles/admin.js` would be registered as 'role:admin' in the container. Deeply nested folders become part of the module name, i.e. `app/roles/employees/manager.js` becomes 'role:employees/manager'. NonJS files are loaded as well, and their container names include the extension, so `app/mailer/welcome.html` becomes `mail:welcome.html`. | loadApp() {
if (fs.existsSync(this.mainDir)) {
eachDir(this.mainDir, (dirname) => {
let dir = path.join(this.mainDir, dirname);
let type = singularize(dirname);
glob.sync('**/*', { cwd: dir }).forEach((filepath) => {
let modulepath = withoutExt(filepath);
if (filepath.endsWith('.js')) {
let Class = require(path.join(dir, filepath));
Class = Class.default || Class;
this.container.register(`${ type }:${ modulepath }`, Class);
} else if (filepath.endsWith('.json')) {
let mod = require(path.join(dir, filepath));
this.container.register(`${ type }:${ modulepath }`, mod.default || mod);
}
});
});
}
} | [
"function loadAssets() {\n\t//setup a global, ordered list of asset files to load\n\trequiredFiles = [\n\t\t\"src\\\\util.js\",\"src\\\\setupKeyListeners.js\", //misc functions\n\t\t\"src\\\\classes\\\\Enum.js\", \"src\\\\classes\\\\Shape.js\", \"src\\\\classes\\\\MouseFollower.js\" //classes\n\t\t];\n\t\n\t//manually load the asset loader\n\tlet script = document.createElement('script');\n\tscript.type = 'text/javascript';\n\tscript.src = \"src\\\\loadAssets.js\";\n\tscript.onload = loadAssets;\n\t//begin loading the asset loader by appending it to the document head\n document.getElementsByTagName('head')[0].appendChild(script);\n}",
"addLayoutScriptsAndStyles() {\n this.asset.layoutScript = path.join(this.pageConfig.layoutsAssetPath, this.layout, 'scripts.js');\n this.asset.layoutStyle = path.join(this.pageConfig.layoutsAssetPath, this.layout, 'styles.css');\n this.includedFiles.add(\n path.join(this.pageConfig.rootPath, LAYOUT_FOLDER_PATH, this.layout, 'scripts.js'));\n this.includedFiles.add(\n path.join(this.pageConfig.rootPath, LAYOUT_FOLDER_PATH, this.layout, 'styles.css'));\n }",
"loadAppConfig() {\n // Load tools\n this.tools = Tools.map((t) => new t());\n EventBus.$emit(\"ui-set-tools\", this.tools);\n\n // Load menu\n this.menu = Menu;\n EventBus.$emit(\"ui-set-menu\", this.menu);\n }",
"function loadAssets() {\n\t\tbackground.src = \"assets/Wall720.png\";\n\t\tTERRAIN_TYPES.BASE.img.src = \"assets/TileSandstone100.png\";\n\t\tTERRAIN_TYPES.LAVA.img.src = \"assets/lava.png\";\n\t\t\n\t\tPLAYER_CLASSES.PALADIN.img.src = \"assets/paladinRun.png\";\n\t\tPLAYER_CLASSES.RANGER.img.src = \"assets/rangerRun.png\";\n\t\tPLAYER_CLASSES.MAGI.img.src = \"assets/magiRun.png\";\n\t\t\n\t\tENEMY_TYPES.RAT.img.src = \"assets/ratRun.png\";\n\t\tENEMY_TYPES.BAT.img.src = \"assets/batRun.png\";\n\t\tENEMY_TYPES.GATOR.img.src = \"assets/gatorRun.png\";\n\t\t\n\t\tPROJECTILE_TYPES.ARROW.img.src = \"assets/arrow.png\";\n\t\tPROJECTILE_TYPES.FIREBALL.img.src = PROJECTILE_TYPES.MAGIFIREBALL.img.src = \"assets/fireball.png\";\n\t\t\n\t\tPARTICLE_TYPES.FLAME.img.src = \"assets/flameParticle.png\";\n\t\tPARTICLE_TYPES.ICE.img.src = PARTICLE_TYPES.FROST.img.src = \"assets/iceParticle.png\";\n\t}",
"async bootContainer() {\n this.createContainer();\n await this.registerFrameworkServices();\n await this.registerPluginsServices();\n await this.registerApplicationServices();\n\n for (let p of this.getPlugins()) {\n const { path, plugin } = p;\n this.currentPluginPath = path;\n if (plugin.beforeContainerCompilation && _.isFunction(plugin.beforeContainerCompilation)) {\n await plugin.beforeContainerCompilation(this.container);\n }\n }\n\n await this.container.compile();\n console.log(this.container.getService(\"users.manager\"));\n for (let p of this.getPlugins()) {\n const { path, plugin } = p;\n this.currentPluginPath = path;\n if (plugin.afterContainerCompilation && _.isFunction(plugin.afterContainerCompilation)) {\n await plugin.afterContainerCompilation(this.container);\n }\n }\n\n await this.container.preload();\n }",
"function _initApp() {\n\n this.containers.forEach(function(containerObj, i) {\n\n var offsetModifier = new Modifier({\n size: [this.options.appWidth, this.options.appHeight],\n transform: Transform.translate(-containerObj.offset.x, -containerObj.offset.y, 0)\n });\n\n var app = new this.options.app({\n transitionables: this.options.transitionables\n });\n\n containerObj.container.add(offsetModifier).add(app);\n\n }.bind(this));\n}",
"function AppManager(){\n}",
"function Preload() {\n assets = new createjs.LoadQueue(); // asset container\n util.GameConfig.ASSETS = assets; // make a reference to the assets in the global config\n assets.installPlugin(createjs.Sound); // supports sound preloading\n assets.loadManifest(assetManifest); // load assetManifest\n assets.on(\"complete\", Start); // once completed, call start function\n }",
"registerStaticAssetsHook() {\n /**\n * Do not register hooks when not running in web\n * environment\n */\n if (!this.isWebOrTestEnvironment) {\n return;\n }\n /**\n * Register the cors before hook with the server\n */\n this.app.container.withBindings(['Adonis/Core/Config', 'Adonis/Core/Server', 'Adonis/Core/Application'], (Config, Server, Application) => {\n const config = Config.get('static', {});\n if (!config.enabled) {\n return;\n }\n const ServeStatic = require('../src/Hooks/Static').ServeStatic;\n const serveStatic = new ServeStatic(Application.publicPath(), config);\n Server.hooks.before(serveStatic.handle.bind(serveStatic));\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 }",
"static load()\n {\n // load non-phaser audio elements for pausing and unpausing\n this.pauseAudio = new Audio('assets/audio/sfx/ui/pause.mp3');\n this.resumeAudio = new Audio('assets/audio/sfx/ui/checkpoint.mp3');\n\n var path = game.load.path;\n game.load.path = 'assets/audio/sfx/levels/';\n\n game.load.audio('open_door', 'open_door.mp3');\n game.load.audio('begin_level', '../ui/begin_level.mp3');\n\n game.load.path = path;\n }",
"function loadAxioms(dir) {\n fs.readdirSync(path.join(__dirname, dir)).forEach(function(file) {\n var name = file.substr(0, file.length - 3);\n if(dir === 'services' && file === 'CrudService') {\n return;\n }\n\n global[name] = require('./' + dir + '/' + file);\n });\n }",
"function copyAssets(done) {\n var assets = {\n js: [\n \"./node_modules/jquery/dist/jquery.js\",\n \"./node_modules/bootstrap/dist/js/bootstrap.bundle.js\",\n \"./node_modules/metismenujs/dist/metismenujs.min.js\",\n \"./node_modules/jquery-slimscroll/jquery.slimscroll.js\",\n \"./node_modules/feather-icons/dist/feather.min.js\",\n ]\n };\n\n var third_party_assets = {\n css_js: [\n {\"name\": \"sortablejs\", \"assets\": [\"./node_modules/sortablejs/Sortable.min.js\"]},\n {\"name\": \"apexcharts\", \"assets\": [\"./node_modules/apexcharts/dist/apexcharts.min.js\"]},\n {\"name\": \"parsleyjs\", \"assets\": [\"./node_modules/parsleyjs/dist/parsley.min.js\"]},\n {\"name\": \"smartwizard\", \"assets\": [\"./node_modules/smartwizard/dist/js/jquery.smartWizard.min.js\", \n \"./node_modules/smartwizard/dist/css/smart_wizard.min.css\", \n \"./node_modules/smartwizard/dist/css/smart_wizard_theme_arrows.min.css\", \n \"./node_modules/smartwizard/dist/css/smart_wizard_theme_circles.min.css\",\n \"./node_modules/smartwizard/dist/css/smart_wizard_theme_dots.min.css\"\n ]},\n {\"name\": \"summernote\", \"assets\": [\"./node_modules/summernote/dist/summernote-bs4.min.js\", \"./node_modules/summernote/dist/summernote-bs4.css\"]},\n {\"name\": \"dropzone\", \"assets\": [\"./node_modules/dropzone/dist/min/dropzone.min.js\", \"./node_modules/dropzone/dist/min/dropzone.min.css\"]},\n {\"name\": \"bootstrap-tagsinput\", \"assets\": [\"./node_modules/@adactive/bootstrap-tagsinput/dist/bootstrap-tagsinput.min.js\", \"./node_modules/@adactive/bootstrap-tagsinput/dist/bootstrap-tagsinput.css\"]},\n {\"name\": \"select2\", \"assets\": [\"./node_modules/select2/dist/js/select2.min.js\", \"./node_modules/select2/dist/css/select2.min.css\"]},\n {\"name\": \"multiselect\", \"assets\": [\"./node_modules/multiselect/js/jquery.multi-select.js\", \"./node_modules/multiselect/css/multi-select.css\"]},\n {\"name\": \"flatpickr\", \"assets\": [\"./node_modules/flatpickr/dist/flatpickr.min.js\", \"./node_modules/flatpickr/dist/flatpickr.min.css\"]},\n {\"name\": \"bootstrap-colorpicker\", \"assets\": [\"./node_modules/bootstrap-colorpicker/dist/js/bootstrap-colorpicker.min.js\", \"./node_modules/bootstrap-colorpicker/dist/css/bootstrap-colorpicker.min.css\"]},\n {\"name\": \"bootstrap-touchspin\", \"assets\": [\"./node_modules/bootstrap-touchspin/dist/jquery.bootstrap-touchspin.min.js\", \"./node_modules/bootstrap-touchspin/dist/jquery.bootstrap-touchspin.css\"] },\n {\n \"name\": \"datatables\", \"assets\": [\"./node_modules/datatables.net/js/jquery.dataTables.min.js\",\n \"./node_modules/datatables.net-bs4/js/dataTables.bootstrap4.min.js\",\n \"./node_modules/datatables.net-responsive/js/dataTables.responsive.min.js\",\n \"./node_modules/datatables.net-responsive-bs4/js/responsive.bootstrap4.min.js\",\n \"./node_modules/datatables.net-buttons/js/dataTables.buttons.min.js\",\n \"./node_modules/datatables.net-buttons-bs4/js/buttons.bootstrap4.min.js\",\n \"./node_modules/datatables.net-buttons/js/buttons.html5.min.js\",\n \"./node_modules/datatables.net-buttons/js/buttons.flash.min.js\",\n \"./node_modules/datatables.net-buttons/js/buttons.print.min.js\",\n \"./node_modules/datatables.net-keytable/js/dataTables.keyTable.min.js\",\n \"./node_modules/datatables.net-select/js/dataTables.select.min.js\",\n \"./node_modules/datatables.net-bs4/css/dataTables.bootstrap4.min.css\",\n \"./node_modules/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css\",\n \"./node_modules/datatables.net-buttons-bs4/css/buttons.bootstrap4.min.css\",\n \"./node_modules/datatables.net-select-bs4/css/select.bootstrap4.min.css\"\n ]\n },\n {\"name\": \"moment\", \"assets\": [\"./node_modules/moment/min/moment.min.js\"]},\n {\"name\": \"fullcalendar-bootstrap\", \"assets\": [\"./node_modules/@fullcalendar/bootstrap/main.min.js\", \n \"./node_modules/@fullcalendar/bootstrap/main.min.css\",\n ]\n },\n {\"name\": \"fullcalendar-core\", \"assets\": [\"./node_modules/@fullcalendar/core/main.min.js\", \n \"./node_modules/@fullcalendar/core/main.min.css\",\n ]\n },\n {\"name\": \"fullcalendar-daygrid\", \"assets\": [\"./node_modules/@fullcalendar/daygrid/main.min.js\", \n \"./node_modules/@fullcalendar/daygrid/main.min.css\"\n ]\n },\n {\"name\": \"fullcalendar-interaction\", \"assets\": [\"./node_modules/@fullcalendar/interaction/main.min.js\"]},\n {\n \"name\": \"fullcalendar-timegrid\", \"assets\": [\"./node_modules/@fullcalendar/timegrid/main.min.js\",\n \"./node_modules/@fullcalendar/timegrid/main.min.css\"]\n },\n {\n \"name\": \"fullcalendar-list\", \"assets\": [\"./node_modules/@fullcalendar/list/main.min.js\",\n \"./node_modules/@fullcalendar/list/main.min.css\"]\n },\n {\"name\": \"list-js\", \"assets\": [\"./node_modules/list.js/dist/list.min.js\"]},\n {\n \"name\": \"jqvmap\", \"assets\": [\"./node_modules/jqvmap/dist/jquery.vmap.min.js\", \n \"./node_modules/jqvmap/dist/jqvmap.min.css\",\n \"./node_modules/jqvmap/dist/maps/jquery.vmap.usa.js\",\n ]\n },\n ]\n };\n\n //copying third party assets\n lodash(third_party_assets).forEach(function (assets, type) {\n if (type == \"css_js\") {\n lodash(assets).forEach(function (plugin) {\n var name = plugin['name'];\n var assetlist = plugin['assets'];\n lodash(assetlist).forEach(function (asset) {\n gulp.src(asset).pipe(gulp.dest(folder.dist_assets + \"libs/\" + name));\n });\n });\n //gulp.src(assets).pipe(gulp.dest(folder.dist_assets + \"css/vendor\"));\n }\n });\n\n //copying required assets\n lodash(assets).forEach(function (assets, type) {\n if (type == \"scss\") {\n gulp\n .src(assets)\n .pipe(\n rename({\n // rename aaa.css to _aaa.scss\n prefix: \"_\",\n extname: \".scss\"\n })\n )\n .pipe(gulp.dest(folder.src + \"scss/vendor\"));\n } else {\n gulp.src(assets).pipe(gulp.dest(folder.src + \"js/vendor\"));\n }\n });\n\n //copying data files\n gulp.src(folder.src + \"data/**\").pipe(gulp.dest(folder.dist_assets + \"/data\"));\n\n done();\n}",
"_onAddApplication() {\n this._showLoader();\n this.$.appscoApplicationAddSettings.addApplication();\n }",
"init() {\n\t\tdocument.body.append(this.view);\n\t\tthis.functions.load();\n\t\tthis.Loader.load(async (loader, resources) => {\n\t\t\tlet i = 0;\n\t\t\tfor (const [name, value] of Object.entries(resources)) {\n\t\t\t\tif (loader.rorkeResources[i].options) {\n\t\t\t\t\tconst urls = await this.Loader.splitSpritesheetIntoTiles(\n\t\t\t\t\t\tvalue.data,\n\t\t\t\t\t\tloader.rorkeResources[i].options,\n\t\t\t\t\t);\n\t\t\t\t\tconst textures = urls.map(tile => Texture.from(tile));\n\t\t\t\t\tthis.spritesheets.set(name, {\n\t\t\t\t\t\ttexture: value.texture,\n\t\t\t\t\t\toptions: loader.rorkeResources[i].options,\n\t\t\t\t\t\ttiles: urls,\n\t\t\t\t\t\ttextures,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tthis.textures.set(name, value.texture);\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tthis.runCreate();\n\t\t});\n\t}",
"function assetsTask() { return src('assets/**/*') .pipe(dest('dist/assets')) }",
"function loadScripts() {\n loadPageHeader();\n getPages();\n getStyles();\n getScripts();\n addEventListeners();\n}",
"function bootstrap() {\n var winston = require('winston');\n var logger = winston.loggers.get('logger');\n logger.info(\"Loading modules...\");\n return require('./ia_module_loader')(ia_interface, iaPath)\n .then(function (loadedModules) {\n return require(\"./ia_solver\")(loadedModules);\n })\n .then(function (ia_solver) {\n return require(\"./app\")(app, ia_solver);\n });\n}",
"function loadScript(directoryName, filesArr) {\n\n for (var i = 0; i < filesArr.length; i++) {\n\n w.load(\"modules/\" + directoryName + \"/\" + filesArr[i] + '.js');\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the given name (or [name, options] pair) from the given table object holding the available presets or plugins. Returns undefined if the preset or plugin is not available; passes through name unmodified if it (or the first element of the pair) is not a string. | function loadBuiltin(builtinTable, name) {
if (isArray(name) && typeof name[0] === 'string') {
if (builtinTable.hasOwnProperty(name[0])) {
return [builtinTable[name[0]]].concat(name.slice(1));
}
return;
} else if (typeof name === 'string') {
return builtinTable[name];
}
// Could be an actual preset/plugin module
return name;
} | [
"function loadPlugin(name, options) {\n return require(resolvePlugin(name, options) || name);\n}",
"getTable(name) {\n return this.tables.get(name);\n }",
"function loadPartSupplierPricingTable(options={}) {\n\n var part = options.part;\n\n if (!part) {\n console.error('No part provided to loadPartSupplierPricingTable');\n return;\n }\n\n var table = options.table || $('#part-supplier-pricing-table');\n var chartElement = options.chart || $('#part-supplier-pricing-chart');\n\n var chart = null;\n\n options.params = options.params || {};\n\n options.params.base_part = part;\n options.params.supplier_detail = true;\n options.params.part_detail = true;\n\n table.inventreeTable({\n url: '{% url \"api-part-supplier-price-list\" %}',\n name: 'partsupplierprice',\n queryParams: options.params,\n original: options.params,\n paginationVAlign: 'bottom',\n pageSize: 10,\n pageList: null,\n search: false,\n showColumns: false,\n formatNoMatches: function() {\n return '{% trans \"No supplier pricing data available\" %}';\n },\n onLoadSuccess: function(data) {\n // Update supplier pricing chart\n\n // Only allow values with pricing information\n data = data.filter((x) => x.price != null);\n\n // Sort in increasing order of quantity\n data = data.sort((a, b) => (a.quantity - b.quantity));\n\n var graphLabels = Array.from(data, (x) => (`${x.part_detail.SKU} - {% trans \"Quantity\" %} ${x.quantity}`));\n var graphValues = Array.from(data, (x) => (x.price / x.part_detail.pack_quantity_native));\n\n if (chart) {\n chart.destroy();\n }\n\n chart = loadBarChart(chartElement, {\n labels: graphLabels,\n datasets: [\n {\n label: '{% trans \"Supplier Pricing\" %}',\n data: graphValues,\n backgroundColor: 'rgba(255, 206, 86, 0.2)',\n borderColor: 'rgb(255, 206, 86)',\n stepped: true,\n fill: true,\n }\n ]\n });\n },\n columns: [\n {\n field: 'supplier',\n title: '{% trans \"Supplier\" %}',\n formatter: function(value, row) {\n var html = '';\n\n html += imageHoverIcon(row.supplier_detail.image);\n html += renderLink(row.supplier_detail.name, `/company/${row.supplier}/`);\n\n return html;\n }\n },\n {\n field: 'sku',\n title: '{% trans \"SKU\" %}',\n sortable: true,\n formatter: function(value, row) {\n return renderLink(\n row.part_detail.SKU,\n `/supplier-part/${row.part}/`\n );\n }\n },\n {\n sortable: true,\n field: 'quantity',\n title: '{% trans \"Quantity\" %}',\n },\n {\n sortable: true,\n field: 'price',\n title: '{% trans \"Unit Price\" %}',\n formatter: function(value, row) {\n\n if (row.price == null) {\n return '-';\n }\n\n // Convert to unit pricing\n var unit_price = row.price / row.part_detail.pack_quantity_native;\n\n var html = formatCurrency(unit_price, {\n currency: row.price_currency\n });\n\n if (row.updated != null) {\n html += `<span class='badge badge-right rounded-pill bg-dark'>${renderDate(row.updated)}</span>`;\n }\n\n\n return html;\n }\n }\n ]\n });\n}",
"function init() {\n loadName();\n}",
"static get table() { return this.name; }",
"function loadPluginDescriptor(\n descriptor: UnloadedDescriptor,\n context: SimpleContext,\n): Plugin {\n if (descriptor.value instanceof Plugin) {\n if (descriptor.options) {\n throw new Error(\n \"Passed options to an existing Plugin instance will not work.\",\n );\n }\n\n return descriptor.value;\n }\n\n return instantiatePlugin(loadDescriptor(descriptor, context), context);\n}",
"function loadPurchasePriceHistoryTable(options={}) {\n\n var part = options.part;\n\n if (!part) {\n console.error('No part provided to loadPurchasePriceHistoryTable');\n return;\n }\n\n var table = options.table || $('#part-purchase-history-table');\n var chartElement = options.chart || $('#part-purchase-history-chart');\n\n var chart = null;\n\n options.params = options.params || {};\n\n options.params.base_part = part;\n options.params.part_detail = true;\n options.params.order_detail = true;\n options.params.has_pricing = true;\n\n // Purchase order must be 'COMPLETE'\n options.params.order_status = {{ PurchaseOrderStatus.COMPLETE }",
"function loadResultTable(type){\n\t$(\"#divAlert\").dialog({\n\t\tmodal: true,\n\t\tautoResize:true,\n\t\twidth:\"auto\",\n\t\tmaxHeight: 700\n\t});\n\t$(\"#divAlert\").empty().load('pages/ConfigEditor/SanityResultTable.html?',function(){\n\t\t$('#santabs').tabs();\n\t\t$('#ulDevConf').hide();\n\t\tif(type == \"loadImage\"){\n\t\t\tsanityQuery(type);\n\t\t\t$('#tabs-1').hide();\t\n\t\t\t$('#tabs-6').show();\n\t\t}else if(type == \"loadConfig\"){\n\t\t\tsanityQuery(type);\n\t\t\t$('#tabs-1').hide();\n\t\t\t$('#tabs-7').show();\n\t\t}else if(type == \"deviceSanity\"){\n\t\t\tsanityQuery(type);\n\t\t\t$('#tabs-1').hide();\n\t\t\t$('#tabs-1').show();\n\t\t}else if(type == \"accessSanity\"){\n\t\t\tsanityQuery(type);\n\t\t\t$('#tabs-1').hide();\n\t\t\t$('#tabs-2').show();\n\t\t}else if(type == \"connectivity\"){\n\t\t\tsanityQuery(type);\n\t\t\t$('#tabs-1').hide();\n\t\t\t$('#tabs-3').show();\n\t\t}else if(type == \"linksanity\"){\n\t\t\tsanityQuery(type);\n\t\t\t$('#tabs-1').hide();\n\t\t\t$('#tabs-4').show();\n\t\t}else if(type == \"enableint\"){\n\t\t\tsanityQuery(type);\n\t\t\t$('#tabs-1').hide();\n\t\t\t$('#tabs-5').show();\n\t\t}\t\t\n\t\t$(\".ui-dialog\").position({\n\t\t my: \"center\",\n\t\t at: \"center\",\n\t\t of: window\n\t\t});\n\t});\n\t$(\"#divAlert\").dialog('open');\n}",
"function parseTable() {\n var name = t.identifier(getUniqueName(\"table\"));\n var limit = t.limit(0);\n var elemIndices = [];\n var elemType = \"anyfunc\";\n\n if (token.type === _tokenizer.tokens.string || token.type === _tokenizer.tokens.identifier) {\n name = identifierFromToken(token);\n eatToken();\n } else {\n name = t.withRaw(name, \"\"); // preserve anonymous\n }\n\n while (token.type !== _tokenizer.tokens.closeParen) {\n /**\n * Maybe export\n */\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.elem)) {\n eatToken(); // (\n\n eatToken(); // elem\n\n while (token.type === _tokenizer.tokens.identifier) {\n elemIndices.push(t.identifier(token.value));\n eatToken();\n }\n\n eatTokenOfType(_tokenizer.tokens.closeParen);\n } else if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.export)) {\n eatToken(); // (\n\n eatToken(); // export\n\n if (token.type !== _tokenizer.tokens.string) {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Expected string in export\" + \", given \" + tokenToString(token));\n }();\n }\n\n var exportName = token.value;\n eatToken();\n state.registredExportedElements.push({\n exportType: \"Table\",\n name: exportName,\n id: name\n });\n eatTokenOfType(_tokenizer.tokens.closeParen);\n } else if (isKeyword(token, _tokenizer.keywords.anyfunc)) {\n // It's the default value, we can ignore it\n eatToken(); // anyfunc\n } else if (token.type === _tokenizer.tokens.number) {\n /**\n * Table type\n */\n var min = parseInt(token.value);\n eatToken();\n\n if (token.type === _tokenizer.tokens.number) {\n var max = parseInt(token.value);\n eatToken();\n limit = t.limit(min, max);\n } else {\n limit = t.limit(min);\n }\n\n eatToken();\n } else {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected token\" + \", given \" + tokenToString(token));\n }();\n }\n }\n\n if (elemIndices.length > 0) {\n return t.table(elemType, limit, name, elemIndices);\n } else {\n return t.table(elemType, limit, name);\n }\n }",
"function startLoad() {\n selector = new Selector();\n}",
"plugin(plugin) {\n for (let inst of this.plugins)\n if (inst.spec == plugin)\n return inst.value;\n return null;\n }",
"plugin(plugin) {\n for (let inst of this.plugins)\n if (inst.spec == plugin)\n return inst.value;\n return null;\n }",
"function getPlayer(name) {\n\tfor (var p = 0; p < players.length; p++) {\n\t\tif (players[p].name == name) {\n\t\t\treturn players[p];\n\t\t}\n\t}\n\t\n\t// Player not found\n\treturn null;\n}",
"preloadMap() {\n\n // Read the previously parsed Tiled map JSON\n this.tilemapJson = this.game.cache.getJSON(this.mapName);\n\n // Load the Tiled map JSON as an actual Tilemap\n this.game.load.tilemap(this.mapName, null, this.tilemapJson, Phaser.Tilemap.TILED_JSON);\n\n // Load the tileset images\n this.loadTilesetImages();\n }",
"function getElement(name, index = 0, doc = document) {\n const __TAGS = document.getElementsByName(name);\n const __TABLE = (__TAGS === undefined) ? undefined : __TAGS[index];\n\n return __TABLE;\n}",
"function getAbilityTable(abilityTableName) {\n return document.getElementById(abilityTableName + 'Table');\n}",
"function loadContents(){\r\n\t//Load all of the table contents when the page loads\r\n\tupdateTable(\"brand\");\r\n\tupdateTable(\"drum_kit\"); \r\n\tupdateTable(\"stick\");\r\n\tupdateTable(\"drummer\");\r\n\tupdateTable(\"plays\");\r\n\t//Update all drop down menu values when the page loads\r\n\tupdateDropDowns();\r\n}",
"function getPlayer(name, callback) {\n\tvar url = `https://www.speedrun.com/api/v1/users?max=1&lookup=${name}`;\n\n\tgetAPIData(url, (err, resp) => {\n\t\tif (!resp.body.data.length) return callback(); // Cannot find player.\n\n\t\tvar data = resp.body.data[0];\n\t\tvar player = {};\n\t\tplayer.id = data.id;\n\t\tplayer.name = data.names.international;\n\t\tif (data.twitch && data.twitch.uri)\n\t\t\tplayer.twitch = data.twitch.uri.split('/')[data.twitch.uri.split('/').length-1];\n\t\tif (data.twitter && data.twitter.uri)\n\t\t\tplayer.twitter = data.twitter.uri.split('/')[data.twitter.uri.split('/').length-1];\n\t\tif (data.location && data.location.country)\n\t\t\tplayer.country = data.location.country.code;\n\n\t\tcallback(player);\n\t});\n}",
"function dynamicLoadPluginJs(source, callback) {\n var label = source.label ? source.label : getStream(source.type);\n\n // if (label == 'hls') {\n // loadScript('../../node_modules/videojs-contrib-hls/dist/videojs-contrib-hls.js', callback)\n // } else if (label == 'dash') {\n // loadScript('../../node_modules/dashjs/dist/dash.all.min.js', function() {\n // loadScript('../../node_modules/videojs-contrib-dash/dist/videojs-dash.js', callback)\n // })\n // } else {\n // callback();\n // }\n\n if (label == 'hls') {\n loadScript('../../dist/GPlayer/lib/videojs-contrib-hls.min.js', callback)\n } else if (label == 'dash') {\n loadScript('../../dist/GPlayer/lib/dash.all.min.js', function() {\n loadScript('../../dist/GPlayer/lib/videojs-dash.min.js', callback)\n })\n } else {\n callback();\n }\n\n function getStream(type) {\n var streamingFormats = {\n 'rtmp/mp4': 'rtmp',\n 'rtmp/flv': 'rtmp',\n 'application/x-mpegURL': 'hls',\n 'application/dash+xml': 'dash'\n }\n return streamingFormats[type]\n }\n}",
"function findByName(name) {\n return db.oneOrNone(`SELECT * FROM bands WHERE name = $1;`, [name]);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Close the websocket connection | function wsCloseConnection(){
webSocket.close();
} | [
"function f_CloseWebsocket(fWS)\n{\n\t// Check fWS object is defined and exists\n\tif (fWS != \"undefined\")\n\t{\n\t\tfWS.close();\n\t\tf_RADOME_log('Websocket \"'+ fWS.name+ '\" has been closed')\n\t}\n}",
"close() {\n this[_socket].close();\n\n if (this[_timeout] !== null) {\n clearTimeout(this[_timeout]);\n }\n }",
"function endWebSocketConnection(ws, code, message) {\n try {\n console.log('Terminating socket');\n ws.end(code, message);\n } catch(err) {\n console.error('Error ending web socket connection');\n console.error(err);\n }\n}",
"deregister() {\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n }",
"teardownWebsocket() {\n if (this.websocket !== undefined) {\n this.websocket.removeAllListeners('open');\n this.websocket.removeAllListeners('close');\n this.websocket.removeAllListeners('error');\n this.websocket.removeAllListeners('message');\n this.websocket = undefined;\n }\n }",
"function onSocketClose() {\n this[owner_symbol].destroy();\n}",
"close() {\n\t\t// Close all live sockets\n\t\tthis.sockets.forEach(socket => {\n\t\t\tif (!socket.destroyed) socket.end();\n\t\t});\n\n\t\tthis.sockets.clear();\n\t}",
"close(callback) {\r\n debugLog(\"ServerSecureChannelLayer#close\");\r\n // close socket\r\n this.transport.disconnect(() => {\r\n this._abort();\r\n if (_.isFunction(callback)) {\r\n callback();\r\n }\r\n });\r\n }",
"function stop_ws() {\n if (CLIENT) {\n userDisconnectFlag = true;\n CLIENT.disconnect();\n }\n}",
"close()\n\t{\n\n\t\tthis._closed = true;\n\n\t\t// Close the protoo Room.\n\t\tthis._protooRoom.close();\n\n\t\t// Emit 'close' event.\n\t\tthis.emit('close');\n\n\t\t// Stop network throttling.\n\t\tif (this._networkThrottled)\n\t\t{\n\t\t\tthrottle.stop({})\n\t\t\t\t.catch(() => {});\n\t\t}\n\t}",
"function disconnect(){\n if(socket.connected){\n socket.disconnect();\n }\n}",
"close () {\n if (this.closed) {\n // TODO: this should do something meaningful. May be throw an error or reject a Promise?\n return\n }\n if (!this.closed) {\n this.mediaRoom.close()\n }\n\n /**\n * Call close event\n *\n * @event Call#close\n *\n */\n this.emit('close', this._callId)\n }",
"function onConnectionClose() {\n\tif (shutdownInProgress && 0 === (httpServer.connections + httpsServer.connections))\n\t\tshutdownNext()\n}",
"[kEndpointClose](endpoint, error) {\n this.#endpoints.delete(endpoint);\n process.nextTick(emit.bind(this, 'endpointClose', endpoint, error));\n\n // If there are no more QuicEndpoints, the QuicSocket is no\n // longer usable.\n if (this.#endpoints.size === 0) {\n // Ensure that there are absolutely no additional sessions\n for (const session of this.#sessions)\n session.destroy(error);\n\n if (error) process.nextTick(emit.bind(this, 'error', error));\n process.nextTick(emit.bind(this, 'close'));\n }\n }",
"close(callback) {\n if (this.#state === kSocketDestroyed)\n throw new ERR_QUICSOCKET_DESTROYED('close');\n\n // If a callback function is specified, it is registered as a\n // handler for the once('close') event. If the close occurs\n // immediately, the close event will be emitted as soon as the\n // process.nextTick queue is processed. Otherwise, the close\n // event will occur at some unspecified time in the near future.\n if (callback) {\n if (typeof callback !== 'function')\n throw new ERR_INVALID_CALLBACK();\n this.once('close', callback);\n }\n\n // If we are already closing, do nothing else and wait\n // for the close event to be invoked.\n if (this.#state === kSocketClosing)\n return;\n\n // If the QuicSocket is otherwise not bound to the local\n // port, destroy the QuicSocket immediately.\n if (this.#state !== kSocketBound) {\n this.destroy();\n }\n\n // Mark the QuicSocket as closing to prevent re-entry\n this.#state = kSocketClosing;\n\n // Otherwise, gracefully close each QuicSession, with\n // [kMaybeDestroy]() being called after each closes.\n const maybeDestroy = this[kMaybeDestroy].bind(this);\n\n // Tell the underlying QuicSocket C++ object to stop\n // listening for new QuicServerSession connections.\n // New initial connection packets for currently unknown\n // DCID's will be ignored.\n if (this[kHandle]) {\n this[kHandle].stopListening();\n }\n this.#serverListening = false;\n\n // If there are no sessions, calling maybeDestroy\n // will immediately and synchronously destroy the\n // QuicSocket.\n if (maybeDestroy())\n return;\n\n // If we got this far, there a QuicClientSession and\n // QuicServerSession instances still, we need to trigger\n // a graceful close for each of them. As each closes,\n // they will call the kMaybeDestroy function. When there\n // are no remaining session instances, the QuicSocket\n // will be closed and destroyed.\n for (const session of this.#sessions)\n session.close(maybeDestroy);\n }",
"function closeWebGateway(callback) {\n if (gateway) {\n log(\"Closing gateway...\");\n gateway.close(function(err) {\n if (err) {\n logErr(err, \"Error when closing WebGateway object:\");\n }\n log(\"Disconnected from Sharemind and closed WebGateway object.\");\n gateway = null;\n callback();\n });\n } else {\n callback();\n }\n}",
"closeConnection() {\n driver.close();\n }",
"disconnectBoard(event){\n event.preventDefault();\n setLedBoardColour(this.state.socket, this.state.deviceName, 0, 0, 0);\n this.setState({ boardConnected: false });\n this.props.updateBoardDeviceName(undefined);\n\n clearInterval(this.state.socketPingInterval);\n disconnectWebSocket(this.state.socket);\n this.setState({socket: undefined, socketPingInterval: undefined});\n this.props.updateSocket(undefined);\n }",
"async close() {\n // close chokidar watchers\n if (this.watchers && this.watchers.length) {\n this.watchers.forEach(watcher => {\n watcher.close();\n });\n this.watchers = [];\n }\n // close devMiddleware\n if (this.devMiddleware) {\n await new Promise(resolve => {\n this.devMiddleware.close(() => resolve());\n });\n }\n // stop serverCompiler watching in ssr mode\n if (this.serverWatching) {\n await new Promise(resolve => {\n this.serverWatching.close(() => resolve());\n });\n this.serverWatching = null;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ImFont FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts>Fonts[0]. | get FontDefault() {
const font = this.native.FontDefault;
return (font === null) ? null : new ImFont(font);
} | [
"function GetFont() {\r\n return new ImFont(bind.GetFont());\r\n }",
"function _loadFont(fontname){\n var canvas = document.createElement(\"canvas\");\n //Setting the height and width is not really required\n canvas.width = 16;\n canvas.height = 16;\n var ctx = canvas.getContext(\"2d\");\n\n //There is no need to attach the canvas anywhere,\n //calling fillText is enough to make the browser load the active font\n\n //If you have more than one custom font, you can just draw all of them here\n ctx.font = \"4px \"+fontname;\n ctx.fillText(\"text\", 0, 8);\n}",
"setFont(font) {\n this.ctx.font = font;\n }",
"public FontFamily(string familyName) : this(null, familyName)\r\n {}",
"get Fonts() {\r\n const fonts = new ImVector();\r\n this.native.IterateFonts((font) => {\r\n fonts.push(new ImFont(font));\r\n });\r\n return fonts;\r\n }",
"public FontFamily()\r\n { \r\n _familyIdentifier = new FontFamilyIdentifier(null, null); \r\n _firstFontFamily = new CompositeFontFamily();\r\n }",
"function loadFontAndWrite(font,text,x,y) {\r\n document.fonts.load(font).then(function () {\r\n ctx.font = font\r\n ctx.fillText(text, x, y)\r\n });\r\n }",
"withTextFontFamily(fontFamily) {\n return this.extend({\n fontFamily,\n font: \"\"\n });\n }",
"constructor(fontImg, fontInfo) {\n fontInfo = JSON.parse(fontInfo).font;\n\n function toInt(str) {\n return parseInt(str, 10);\n }\n\n this.lineHeight = toInt(fontInfo.common.lineHeight);\n this.baseline = toInt(fontInfo.common.base);\n\n // Create glyph map\n this.glyphs = {};\n for (var i=0; i<fontInfo.chars.count; ++i) {\n var cInfo = fontInfo.chars.char[i];\n var glyph = new Glyph(fontImg, cInfo.id, toInt(cInfo.x), toInt(cInfo.y), toInt(cInfo.width), toInt(cInfo.height), toInt(cInfo.xoffset), toInt(cInfo.yoffset), toInt(cInfo.xadvance));\n this.glyphs[glyph.charCode] = glyph;\n }\n }",
"function getFont(){ \n\tvar fontForm = document.getElementById(\"fonts\");\n\tif(fontForm.selectedIndex == 0){\n\t\treturn \"Ubuntu\";\n\t}\n\tvar fontSelection = fontForm.options[fontForm.selectedIndex].value;\n\treturn fontSelection;\n}",
"function ShowFontSelector(label) {\r\n const io = GetIO();\r\n const font_current = GetFont();\r\n if (BeginCombo(label, font_current.GetDebugName())) {\r\n Selectable(font_current.GetDebugName());\r\n // TODO\r\n // for (let n = 0; n < io.Fonts->Fonts.Size; n++)\r\n // {\r\n // ImFont* font = io.Fonts->Fonts[n];\r\n // ImGui.PushID((void*)font);\r\n // if (ImGui.Selectable(font->GetDebugName(), font == font_current))\r\n // io.FontDefault = font;\r\n // ImGui.PopID();\r\n // }\r\n EndCombo();\r\n }\r\n SameLine();\r\n HelpMarker(\"- Load additional fonts with io.Fonts->AddFontFromFileTTF().\\n\" +\r\n \"- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\\n\" +\r\n \"- Read FAQ and documentation in misc/fonts for more details.\\n\" +\r\n \"- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().\");\r\n }",
"function loadDefaultFonts() {\n if (!$('link[href=\"fonts.css\"]').length) {\n $(\"head\").append('<link rel=\"stylesheet\" type=\"text/css\" href=\"fonts.css\">');\n const fontsToAdd = [\"Amatic+SC:700\", \"IM+Fell+English\", \"Great+Vibes\", \"MedievalSharp\", \"Metamorphous\", \"Nova+Script\", \"Uncial+Antiqua\", \"Underdog\", \"Caesar+Dressing\", \"Bitter\", \"Yellowtail\", \"Montez\", \"Shadows+Into+Light\", \"Fredericka+the+Great\", \"Orbitron\", \"Dancing+Script:700\", \"Architects+Daughter\", \"Kaushan+Script\", \"Gloria+Hallelujah\", \"Satisfy\", \"Comfortaa:700\", \"Cinzel\"];\n fontsToAdd.forEach(function (f) {\n if (fonts.indexOf(f) === -1) fonts.push(f);\n });\n updateFontOptions();\n }\n}",
"function increaseFontSize() {\n gMeme.currText.size += 3\n}",
"setFontFamily() {\n const fontFamily = this.options?.tooltip?.fontFamily ?? 'Roboto';\n fontStyle = `normal normal lighter 14px ${fontFamily}`;\n this.tooltipHeaderDOM.style.fontFamily = fontFamily;\n }",
"function setupHud() {\n setAttributes(\"antialias\", true)\n easycam = createEasyCam()\n document.oncontextmenu = function () {\n return false\n }\n\n // set initial camera state\n easycam.setState(state)\n easycam.state_reset = state // state to use on reset\n\n // use the loaded font\n textFont(f)\n textSize(16)\n}",
"setTextParams (obj, font, align = 'center', baseline = 'middle') {\n obj.font = font; obj.textAlign = align; obj.textBaseline = baseline\n }",
"function colocarNome(nome){\n app.activeDocument.layers[0].visible = true;\n app.activeDocument.layers[0].textItem.contents=nome;\n }",
"function drawText() {\n push();\n textAlign(CENTER);\n fill(this.color);\n textSize(this.size);\n text(this.txt, this.x, this.y);\n pop();\n}",
"static initialize() {\n this.fontTemplateList = [];\n let fontWidth = 0;\n for (let i = 0; i < 10; i++) {\n const fontImage = document.getElementById(`font${i}`);\n if (fontWidth === 0) {\n fontWidth = (fontImage.width / fontImage.height) * Config.fontHeight;\n }\n fontImage.height = Config.fontHeight;\n fontImage.width = fontWidth;\n this.fontTemplateList.push(fontImage);\n }\n\n this.fontLength = Math.floor(\n (Config.stageCols * Config.puyoImgWidth) / this.fontTemplateList[0].width\n );\n this.score = 0;\n this.showScore();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copyright 2018 Palantir Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Helper function for formatting ratios as CSS percentage values. | function formatPercentage(ratio) {
return (ratio * 100).toFixed(2) + "%";
} | [
"function format_percent(percent) {\n return Number(percent * 100).toFixed(2) + ' %';\n}",
"function format_percent(val) {\n return (val * 100).toFixed(places) + \"%\";\n}",
"function Percent() {\n Ratio.apply(this, arguments);\n this.cssType = PERCENT;\n }",
"function getPercentOf(p, n) {\n\treturn p/100 * n\n}",
"function getPercentage(str) {\n return parseFloat((str / max_cgMLST_count) * 100).toFixed(2);\n }",
"calcPercentage() {\n return Math.floor((this.volume / 20) * 100) + \"%\";\n }",
"getPercentage(bookmark) {\n var cco = bookmark.currentChapterOrder;\n var tc = this.props.book.totalChapter;\n var st = bookmark.scrollTop;\n var sh = bookmark.scrollHeight;\n var pt = cco * 100 / tc + 100 * st / sh / tc;\n return pt.toPrecision(3).toString() + '%';\n }",
"pixelToPercent(x)\n {\n if (!this.field || !this.field.offsetWidth)\n {\n return 0;\n }\n\n const percent = x / this.field.offsetWidth;\n\n if (this.props.steps)\n {\n const oneStep = 1 / this.props.steps;\n return Math.round(percent / oneStep) * oneStep;\n }\n\n return percent;\n }",
"function percentOf(num, num2){\n return (num/num2)*100\n}",
"function paintPercentCap() {\n if (percentCap >= 80) {\n return 'bg-success text-dark rounded';\n } else if (percentCap < 80 && percentCap >= 50) {\n return 'bg-warning text-dark rounded';\n } else if (percentCap < 50) {\n return 'bg-danger rounded';\n }\n }",
"getRatingColor(rating){\n //Colour mapping to percentage taken from: https://stackoverflow.com/a/17267684\n let a = rating / 100,\n b = (120 - 0) * a,\n c = b + 0;\n return 'hsl('+c+', 100%, 50%)';\n }",
"function settingsPercentage(projectJshintSettings) {\n verify.object(projectJshintSettings, 'expected jshint object');\n\n //console.log('looking at jshint settings\\n' +\n // JSON.stringify(projectJshintSettings, null, 2));\n\n var allSettings = getAllSettings();\n verify.object(allSettings, 'could not get all jshint settings');\n var totalSettings = Object.keys(allSettings).length;\n verify.positiveNumber(totalSettings, 'epected all settings to have properties');\n\n Object.keys(projectJshintSettings).forEach(function (key) {\n if (key === 'predef') { return; }\n\n if (typeof allSettings[key] === 'undefined') {\n console.error('unknown setting', key, projectJshintSettings[key]);\n }\n });\n\n var specifiedSettings = Object.keys(projectJshintSettings).length;\n\n return +(specifiedSettings / totalSettings * 100).toPrecision(2);\n}",
"function editDistancePercentage(x, y) {\n return (new difflib.SequenceMatcher(null, x, y)).ratio();\n}",
"function calculatePercentage(percentage) {\n return (5000 / 100) * percentage;\n}",
"static RangeToPercent(num, min, max) {\n return (num - min) / (max - min);\n }",
"generatePercent(deathState,totDeath) {\n return ((deathState / parseInt(totDeath)) * 100).toFixed(2) + '%'\n }",
"function time_percent(start, end) {\n let now = Date.parse(new Date());\n let percent = ((now-start) / (end-start))*100;\n console.log(\"%s%%\",percent.toFixed(2));\n document.getElementById('percent').innerHTML = percent.toFixed(2) ;\n return percent;\n}",
"function massPercent(_massList, total) {\n\n var str = '';\n\n var spaces = ' ';\n\n var row = 0;\n\n var nl = 0\n\n for (var i = 0; i <= _massList.length; i++) {\n\n if (_massList[i]) {\n\n row += 1;\n\n for (var n = 0; n < 13 - name[i].length; n++) {\n\n spaces += ' ';\n\n }\n\n str += name[i] + ': ' + ((_massList[i] / total) * 100).toPrecision(3) + ' %' + spaces + ' ';\n\n spaces = ' ';\n\n if (row == 5) {\n\n str += '\\n';\n\n row = 0;\n\n nl += 1;\n\n }\n\n }\n\n }\n\n return str;\n\n }",
"function getPercentageFromDistance(str) {\n return parseFloat((1 - str) * 100).toFixed(2);\n }",
"function discountPercentage(originalAmount, discountAmountPercent) {\n if (discountAmountPercent > 100 || discountAmountPercent < 0){\n return (\"Warning: Disount is greater than 100 or less than 0 percent\");\n }\n else {\n return (originalAmount*(discountAmountPercent/100));\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes axios get request to address and returns array of all API responses and function to make another request (and update array of responses) | function useAxios() {
const [responses, setResponses] = useState([]);
// name is not query (changed to resource) *******
async function fetchData (url, resource="") {
try {
const response = await axios(`${url}${resource}`);
setResponses(resps => [...resps, {...response.data, id: uuid()}]);
} catch {
console.log('error happened in API call');
}
};
return [responses, fetchData];
} | [
"apiPromise(apiAction) {\n Promise.all([this.apiCall(apiAction).getData(), this.apiCall(apiAction).getPrice()])\n .then(([data, prices]) => {\n this.setState({\n coinData: data,\n coinPrice: prices\n });\n })\n }",
"function getFreeProxies() {\n return new Promise((resolve, reject) => {\n let options = {\n host: 'proxylist.geonode.com',\n path: '/api/proxy-list?limit=200&page=1&sort_by=lastChecked&sort_type=desc&country=US'\n };\n https.request(options, (response) => {\n var str = '';\n\n //another chunk of data has been received, so append it to `str`\n response.on('data', function (chunk) {\n str += chunk;\n });\n \n //the whole response has been received, so we just print it out here\n response.on('end', function () {\n let parsed = JSON.parse(str);\n let data = parsed.data;\n for (let i = 0; i < data.length; i++) {\n let curr = data[i];\n proxies.push(`${curr.ip}:${curr.port}`);\n }\n resolve();\n });\n }).end();\n });\n}",
"async function fetchHistoricalRates() {\n var pastDays = [];\n for (var i = 1; i <= 7; i++) {\n var d = new Date();\n d.setDate(d.getDate() - i);\n pastDays.push( d.toISOString().slice(0, 10) );\n }\n setPassSevenDay(pastDays);\n // console.log(passSevenDates);\n var newExchangeRateHist = new Array(7);\n for (i = 0; i < 7; i++) {\n const response = await axios.get(`https://openexchangerates.org/api/historical/${pastDays[i]}.json?app_id=${appId}`)\n if (response && response.data) {\n newExchangeRateHist[i] = response.data.rates;\n } else {\n console.log(`error! can't get the exchange rate info of ${i+1} day before`)\n }\n }\n setExchangeRatesHist(newExchangeRateHist);\n // console.log(newExchangeRateHist)\n }",
"async function getAll(res) {\n let twitter = await getRemoteData(twitterCall);\n let facebook = await getRemoteData(fbCall);\n let instagram = await getRemoteData(instaCall);\n res.send({ \"twitter\": twitter, \"facebook\": facebook, \"instagram\": instagram });\n}",
"function queueAPIRequest(path, params){\n return gw2_API_queue.add(() => gw2API.get(path, {params})\n\n //then parse response depending on path\n .then((response) => {\n\n switch (path) {\n\n case '/items':\n //put each of the 200 items from API into DB\n itemsResponseHandler(response)\n break;\n\n case '/currencies':\n //for when I do currencies\n currenciesResponseHandler(response)\n break;\n\n default:\n break;\n }\n })\n\n //catch here for http error\n .catch((error) => {\n httpErrorHandler(error)\n\n })\n )\n}",
"async function getBikes() {\n let response = [];\n try {\n const res = await fetch(apiUrl);\n if (! res.ok) throw new Error(res.status);\n response = await res.json();\n } catch (error) {\n console.log(error);\n }\n return response;\n}",
"async function populateAllLocations(url){\n let response;\n let nextPage='/locations?page=22&perPage=1000';\n \n do{\n let locationIds = [];\n console.log(\"Fetching remote data: \", url+nextPage)\n response = await axios.get(url+nextPage);\n nextPage = response.data.nextPageUri;\n \n for (let i=0, len=response.data.locations.length; i<len; i++){\n locationIds.push(response.data.locations[i].locationId)\n }\n \n let locations = await getIndividualLocations(locationIds);\n \n for (let i=0, len=locations.length; i<len; i++){\n await models.location.create({\n locationid:locations[i].locationId,\n locationname: locations[i].name,\n addressline1: locations[i].postalAddressLine1,\n addressline2: locations[i].postalAddressLine2,\n towncity: locations[i].postalAddressTownCity,\n county: locations[i].postalAddressCounty,\n postalcode: locations[i].postalCode,\n mainservice: (locations[i].gacServiceTypes.length>0) ? locations[i].gacServiceTypes[0].name : null\n })\n }\n } while (nextPage != null);\n }",
"[FETCH_PATIENT_SIBLINGS]({ commit }) {\n let endpoint = `/api/v1/patient-sibling-b03/`;\n commit(FETCH_START);\n apiService(endpoint)\n .then(response => {\n commit(SET_PATIENT_SIBLINGS, response);\n commit(FETCH_END);\n })\n .catch(error => {\n console.log(error);\n });\n }",
"function handleAPIRequest(req,res){\n _handleRequest(req, function(err, query) {\n if (!err){\n getOffers(query, res)\n }\n });\n}",
"function getAllSites() {\n return new Promise(resolve => {\n axios({\n url: `https://api.netlify.com/api/v1/sites/?access_token\\=${NETLIFY_API_TOKEN}`,\n method: 'get',\n headers: {\n 'content-type': 'application/json',\n }\n }).then((response) => {\n resolve(response.data)\n }).catch((err) => {\n console.log(err)\n })\n })\n}",
"sendGETRequest() {\n\n const options = {\n hostname: 'localhost',\n port: SERVER_PORT,\n path: '/',\n method: 'GET'\n };\n\n const clientGETReq = http.request(options, function(res) {\n\n console.log(`STATUS CODE: ${res.statusCode}`);\n\n });\n\n clientGETReq.on('error', function(err) {\n console.log('ERROR:' + err);\n });\n\n clientGETReq.end();\n\n }",
"async function getAPIIndicators ($store) {\n // console.log('domains.auth.getUserInfos')\n const config = {\n headers: {\n // 'authorization': 'Bearer ' + token\n }\n }\n\n var randNb = Math.round(Math.random()*1000000)\n return axios.get(process.env.CONFIG_APP.api_url + 'getIndicators.php?rand=', config)\n .then(response => {\n var tmpArray = response.data\n\n $store.DBIndicators = []\n $store.DBIndicatorsObj = {}\n\n _.each(tmpArray.indicators, function (indicator) {\n var indicatorObj = indicator\n indicatorObj.value = indicator.id\n indicatorObj.text = indicator.name\n $store.DBIndicators.push(indicatorObj)\n $store.DBIndicatorsObj[indicator.id] = indicator\n })\n\n $store.DBKeyIndicators = _.filter(tmpArray.indicators, function (indicator) {\n return indicator.key_indicator == '1'\n })\n\n $store.DBDefaultCPage = _.filter(tmpArray.indicators, function (indicator) {\n return indicator.default_cpage == '1'\n })\n\n $store.DBClassifIndicators = []\n var tmpClassifsObj = _.groupBy(tmpArray.indicators, function (indicator) {\n return indicator.classif\n })\n\n _.each(tmpClassifsObj, function(classifItems, classifKey){\n var classifAlpha = 10\n if(classifKey == 'Production') classifAlpha = 2\n else if(classifKey == 'Dissemination') classifAlpha = 3\n else if(classifKey == 'Use') classifAlpha = 4\n else if(classifKey == 'Investment') classifAlpha = 5\n else if(classifKey == 'Planning') classifAlpha = 1\n\n classifItems = _.filter(classifItems, function (indic){\n return (indic.id !== \"94\" && indic.id !== \"35\" || indic.id !== \"77\")\n })\n\n var classif = {\n key: classifKey,\n alpha: classifAlpha,\n items: classifItems\n }\n $store.DBClassifIndicators.push(classif)\n })\n\n $store.DBClassifIndicators = _.sortBy($store.DBClassifIndicators, function(classif){\n return classif.alpha\n })\n\n return true\n })\n .catch(err => {\n console.log('Une erreur est survenue', err)\n return null\n })\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}",
"getMarketInfo(startingCurrency, endingCurrency) {\n return axios.get(`/marketinfo/${pair(startingCurrency, endingCurrency)}`,\n {\n responseType: \"json\"\n });\n }",
"async function api(endpoint, params) {\n\tconst BUNGIE_API_KEY = process.env.BUNGIE_API_KEY;\n\tconst baseUrl = 'https://www.bungie.net/Platform/Destiny/';\n\tconst trailing = '/';\n\tconst queryParams = params ? `?${params}` : '';\n\tconst url = baseUrl + endpoint + trailing + queryParams;\n\treturn new Promise((resolve, reject) => {\n\t\trequest({\n\t\t\turl: url,\n\t\t\theaders: {\n\t\t\t\t'X-API-Key': BUNGIE_API_KEY\n\t\t\t}\n\t\t}, (err, res, body) => {\n//\t\t\tconsole.log('api: err=%j', err);\n//\t\t\tconsole.log('api: res=%j', res);\n//\t\t\tconsole.log('api: body=%j', body);\t\t\t\n\t\t\tlet object = JSON.parse(body);\n\t\t\tresolve(object.Response);\n\t\t});\n\t});\n}",
"function getExpiredDealsAndUpdateRewards() {\n\n var body = {};\n nouvoController.getExpiredDeals(function (error, response) {\n if (error) {\n logger.error(\"Error while getting active deals\", error);\n setNextScheduledBatchInterval();\n } else {\n var stakeCalculated = [];\n response.body.responseData = functions.decryptData(response.body.responseData);\n if (response != null && response.body != null && response.body.responseData != null) {\n \n if (response.body.responseData.length > 0) {\n each(response.body.responseData,\n function (deal, next) {\n\n var params = [deal.merchantId, deal.startDate, deal.endDate];\n var query = 'call GetStakeOfAllUsersForMerchant(?,?,?)';\n\n var stakeForMerchant = {};\n stakeForMerchant.merchantId = deal.merchantId;\n stakeForMerchant.endDate = deal.endDate;\n stakeForMerchant.id = deal.id;\n con.query(query, params, function (err, result) {\n if (err) {\n setNextScheduledBatchInterval();\n }\n else {\n if (result[0].length > 0) {\n stakeForMerchant.stake = result[0];\n stakeCalculated.push(stakeForMerchant);\n next(err);\n }\n else {\n stakeForMerchant.stake = [];\n stakeCalculated.push(stakeForMerchant);\n next(err);\n }\n \n }\n });\n // next(err);\n },\n function (err) {\n if (!err) {\n // stakeCalculated\n // setNextScheduledBatchInterval();\n nouvoController.distributeRewards(stakeCalculated, function (error, response) {\n if (error) {\n logger.error(\"Error while getting active deals\", error);\n setNextScheduledBatchInterval();\n } else {\n setNextScheduledBatchInterval();\n }\n });\n }\n })\n }\n else {\n setNextScheduledBatchInterval();\n }\n\n }\n else {\n logger.error(\"Error while getting active deals\", error);\n setNextScheduledBatchInterval();\n }\n }\n })\n}",
"function watcherSaga() {\n return regeneratorRuntime.wrap(function watcherSaga$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n _context.next = 2;\n return Object(redux_saga_effects__WEBPACK_IMPORTED_MODULE_0__[\"takeEvery\"])(\"API_CALL_REQUEST\", workerSaga);\n\n case 2:\n case \"end\":\n return _context.stop();\n }\n }\n }, _marked, this);\n} // function that makes the api request and returns a Promise for response",
"getNotifications(url, trip_id) {\n return axios.get(`${url}notify/${trip_id}`).then(res => {\n return res.data;\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 }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parseConfig reads config from the source of truth, the environment. config must always be read this way because automation api introduces new program lifetime semantics where program lifetime != module lifetime. | function parseConfig() {
const { config } = state_1.getStore();
const parsedConfig = {};
const envConfig = config[exports.configEnvKey];
if (envConfig) {
const envObject = JSON.parse(envConfig);
for (const k of Object.keys(envObject)) {
parsedConfig[cleanKey(k)] = envObject[k];
}
}
return parsedConfig;
} | [
"function parseConfig() {\r\n let config\r\n if (process.env.WEBMONITOR_CONFIG) {\r\n // Strip escaped newlines\r\n let configString = process.env.WEBMONITOR_CONFIG.replace(/\\\\n/g, \"\\n\")\r\n //console.log(configString)\r\n config = JSON.parse(configString)\r\n } else {\r\n config = require('./config.json')\r\n }\r\n\r\n if (!config.emailTo) throw \"emailTo missing from config\"\r\n if (!Array.isArray(config.emailTo) || !config.emailTo.length > 0) throw \"emailTo should be an array with at least one element\"\r\n if (!config.emailFrom) config.emailFrom = \"webmonitor@benco.io\"\r\n if (!config.emailSubject) config.emailSubject = \"Web Monitor Alert!\"\r\n if (!config.headers) config.headers = {}\r\n\r\n if (!config.checks || config.checks.length == 0) throw \"Need at least one check\"\r\n\r\n return config\r\n}",
"function configureParser(context) {\n var cordova_util = context.requireCordovaModule('cordova-lib/src/cordova/util'),\n ConfigParser = context.requireCordovaModule('cordova-lib/src/configparser/ConfigParser');\n etree = context.requireCordovaModule('cordova-lib/node_modules/elementtree');\n\n var xml = cordova_util.projectConfig(projectRoot);\n config = createConfigParser(xml, etree, ConfigParser);\n}",
"function ParseConfiguration (err, data)\n{\n if (err)\n return console.log (err);\n\n config = JSON.parse (data);\n\n SetupClient ();\n}",
"function loadConfig() {\n\tconfig_file = fs.readFileSync(\"./config.json\");\n\tconfig = JSON.parse(config_file);\n}",
"function parseConfig(contents, config) {\n contents.server = contents.server || {};\n contents.proxy = contents.proxy || {};\n\n if (contents.proxy.gateway && typeof(contents.proxy.gateway) === \"string\" && contents.proxy.gateway.length > 0) {\n contents.proxy.gateway = parseGateway(contents.proxy.gateway);\n }\n\n contents.proxy.forward = parseConfigMap(contents.proxy.forward, parseForwardRule);\n contents.proxy.headers = parseConfigMap(contents.proxy.headers, parseHeaderRule);\n\n // override any values in the config object with values specified in the file;\n config.server.port = contents.server.port || config.server.port;\n config.server.webroot = contents.server.webroot || config.server.webroot;\n config.server.html5mode = contents.server.html5mode || config.server.html5mode;\n config.proxy.gateway = contents.proxy.gateway || config.proxy.gateway;\n config.proxy.forward = contents.proxy.forward || config.proxy.forward;\n config.proxy.headers = contents.proxy.headers || config.proxy.headers;\n\n return config;\n}",
"function parseConfigXml(platform) {\n var configData = {};\n parsePlatformPreferences(configData, platform);\n parseConfigFiles(configData, platform);\n\n return configData;\n }",
"configure(config) {\n // Hideous reflection-based kludge to make it easy to create a\n // slightly modified copy of a parser.\n let copy = Object.assign(Object.create(LRParser.prototype), this)\n if (config.props) copy.nodeSet = this.nodeSet.extend(...config.props)\n if (config.top) {\n let info = this.topRules[config.top]\n if (!info) throw new RangeError(`Invalid top rule name ${config.top}`)\n copy.top = info\n }\n if (config.tokenizers)\n copy.tokenizers = this.tokenizers.map((t) => {\n let found = config.tokenizers.find((r) => r.from == t)\n return found ? found.to : t\n })\n if (config.specializers) {\n copy.specializers = this.specializers.slice()\n copy.specializerSpecs = this.specializerSpecs.map((s, i) => {\n let found = config.specializers.find((r) => r.from == s.external)\n if (!found) return s\n let spec = Object.assign(Object.assign({}, s), {\n external: found.to\n })\n copy.specializers[i] = getSpecializer(spec)\n return spec\n })\n }\n if (config.contextTracker) copy.context = config.contextTracker\n if (config.dialect) copy.dialect = this.parseDialect(config.dialect)\n if (config.strict != null) copy.strict = config.strict\n if (config.wrap) copy.wrappers = copy.wrappers.concat(config.wrap)\n if (config.bufferLength != null) copy.bufferLength = config.bufferLength\n return copy\n }",
"function parseConfiguration( strFileName )\n{\n var gObjFs = new ActiveXObject(\"Scripting.FileSystemObject\");\n if( !gObjFs.FileExists( strFileName) ) \n throw \"File Name '\" + strFileName + \"' does not exist\";\n\n var xmlTree = new ActiveXObject(\"Microsoft.XMLDOM\");\n xmlTree.async = false;\n if( !xmlTree.load( strFileName) ) \n throw \"Failed to load file as XML.\\n\" \n + xmlTree.parseError.url \n + \":\" \n + xmlTree.parseError.line \n + \" \" \n + xmlTree.parseError.reason;\n\n var xmlRoot = xmlTree.documentElement;\n return xmlRoot;\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 }",
"async readConfigFile(configFilePath) {\n let tailwindConfigFile = nova.fs.open(configFilePath)\n let contents = tailwindConfigFile.readlines()\n let newContents = ''\n\n tailwindConfigFile.close()\n\n // Remove any lines including the require, such as 'require('@tailwindcss/forms')'\n contents.forEach((line) => {\n if (!line.includes('require(')) {\n newContents = newContents + line\n }\n })\n\n let configObject = eval(newContents)\n\n return configObject\n }",
"function readConfig() {\n fetch(\"/config/modules.json\")\n .then(response => response.json())\n .then(data => (config = data))\n .then(printModules);\n}",
"function readConfig (argv) {\n return new BB((resolve, reject) => {\n const npmBin = process.platform === 'win32' ? 'npm.cmd' : 'npm'\n const child = spawn(npmBin, [\n 'config', 'ls', '--json', '-l'\n // We add argv here to get npm to parse those options for us :D\n ].concat(argv || []), {\n env: process.env,\n cwd: process.cwd(),\n stdio: [0, 'pipe', 2]\n })\n\n let stdout = ''\n if (child.stdout) {\n child.stdout.on('data', (chunk) => {\n stdout += chunk\n })\n }\n\n child.on('error', reject)\n child.on('close', (code) => {\n if (code === 127) {\n reject(new Error('`npm` command not found. Please ensure you have npm@5.4.0 or later installed.'))\n } else {\n try {\n resolve(JSON.parse(stdout))\n } catch (e) {\n reject(new Error('`npm config ls --json` failed to output json. Please ensure you have npm@5.4.0 or later installed.'))\n }\n }\n })\n })\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 loadConfigurationFromPath(configFilePath) {\n if (configFilePath == null) {\n return exports.DEFAULT_CONFIG;\n }\n else {\n var resolvedConfigFilePath = resolveConfigurationPath(configFilePath);\n var rawConfigFile = void 0;\n if (path.extname(resolvedConfigFilePath) === \".json\") {\n var fileContent = utils_1.stripComments(fs.readFileSync(resolvedConfigFilePath)\n .toString()\n .replace(/^\\uFEFF/, \"\"));\n rawConfigFile = JSON.parse(fileContent);\n }\n else {\n rawConfigFile = require(resolvedConfigFilePath);\n delete require.cache[resolvedConfigFilePath];\n }\n var configFileDir_1 = path.dirname(resolvedConfigFilePath);\n var configFile = parseConfigFile(rawConfigFile, configFileDir_1);\n // load configurations, in order, using their identifiers or relative paths\n // apply the current configuration last by placing it last in this array\n var configs = configFile.extends.map(function (name) {\n var nextConfigFilePath = resolveConfigurationPath(name, configFileDir_1);\n return loadConfigurationFromPath(nextConfigFilePath);\n }).concat([configFile]);\n return configs.reduce(extendConfigurationFile, exports.EMPTY_CONFIG);\n }\n}",
"function parsePlatformPreferences(configData, platform) {\n var preferences = getPlatformPreferences(platform);\n switch(platform){\n case \"ios\":\n parseiOSPreferences(preferences, configData);\n break;\n case \"android\":\n parseAndroidPreferences(preferences, configData);\n break;\n }\n }",
"function parseOnlineConfigUrl(url) {\n if (!url || !url.startsWith(exports.ONLINE_CONFIG_PROTOCOL + \":\")) {\n throw new InvalidUri(\"URI protocol must be \\\"\" + exports.ONLINE_CONFIG_PROTOCOL + \"\\\"\");\n }\n // Replace the protocol \"ssconf\" with \"https\" to ensure correct results,\n // otherwise some Safari versions fail to parse it.\n var inputForUrlParser = url.replace(new RegExp(\"^\" + exports.ONLINE_CONFIG_PROTOCOL), 'https');\n // The built-in URL parser throws as desired when given URIs with invalid syntax.\n var urlParserResult = new URL(inputForUrlParser);\n // Use ValidatedConfigFields subclasses (Host, Port, Tag) to throw on validation failure.\n var uriFormattedHost = urlParserResult.hostname;\n var host;\n try {\n host = new Host(uriFormattedHost);\n }\n catch (_) {\n // Could be IPv6 host formatted with surrounding brackets, so try stripping first and last\n // characters. If this throws, give up and let the exception propagate.\n host = new Host(uriFormattedHost.substring(1, uriFormattedHost.length - 1));\n }\n // The default URL parser fails to recognize the default HTTPs port (443).\n var port = new Port(urlParserResult.port || '443');\n // Parse extra parameters from the tag, which has the URL search parameters format.\n var tag = new Tag(urlParserResult.hash.substring(1));\n var params = new URLSearchParams(tag.data);\n return {\n // Build the access URL with the parsed parameters Exclude the query string and tag.\n location: \"https://\" + uriFormattedHost + \":\" + port.data + urlParserResult.pathname,\n certFingerprint: params.get('certFp') || undefined,\n httpMethod: params.get('httpMethod') || undefined\n };\n}",
"function loadConfig() {\n var config = JSON.parse(require('fs').readFileSync(__dirname + '/defaults.json', 'utf-8'));\n for (var i in config) {\n config[i] = process.env[i.toUpperCase()] || config[i];\n }\n return config;\n}",
"constructor(config_dir){\n if(fs.existsSync(config_dir)){\n if(typeof require(config_dir) == 'json' || typeof require(config_dir) == 'object'){\n this.config = require(config_dir);\n\n // Load the access token key.\n if(this.config.mode == 'sandbox') this.config.token = this.config.keys.sandbox;\n else if(this.config.mode == 'production') this.config.token = this.config.keys.production;\n\n // Log to console.\n if(this.config.mode == 'sandbox'){\n console.log('[Flip Gocardless] => Running in ' + this.config.mode);\n console.log('[Flip GoCardless] => Loaded configuration files.');\n }\n }\n else throw '[Flip GoCardless] => Invalid config file contents.';\n }\n else throw '[Flip GoCardless] => Invalid config file.';\n }",
"function getCliConfig(): RNConfig {\n const cliArgs = minimist(process.argv.slice(2));\n const config = cliArgs.config != null\n ? Config.loadFile(path.resolve(__dirname, cliArgs.config))\n : Config.findOptional(__dirname);\n\n return {...defaultConfig, ...config};\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update Conditions Track Chart | function updateConditionsTrackChart2(){
var temp = getDpsActive();
var myData = [{
type: "bar",
showInLegend: true,
color: "blue",
name: "Active",
dataPoints: dpsActive
}, {
type: "bar",
showInLegend: true,
color: "green",
name: "winCount",
dataPoints: [
{y: conditionsTrack.cond1.winCount, label: "cond1"},
{y: conditionsTrack.cond2.winCount, label: "cond2"},
{y: conditionsTrack.cond3.winCount, label: "cond3"},
{y: conditionsTrack.cond4.winCount, label: "cond4"},
{y: conditionsTrack.cond5.winCount, label: "cond5"},
{y: conditionsTrack.cond6.winCount, label: "cond6"}
]
},{
type: "bar",
showInLegend: true,
color: "red",
name: "lossCount",
dataPoints: [
{y: conditionsTrack.cond1.lossCount, label: "cond1"},
{y: conditionsTrack.cond2.lossCount, label: "cond2"},
{y: conditionsTrack.cond3.lossCount, label: "cond3"},
{y: conditionsTrack.cond4.lossCount, label: "cond4"},
{y: conditionsTrack.cond5.lossCount, label: "cond5"},
{y: conditionsTrack.cond6.lossCount, label: "cond6"}
]
}];
// Options to display value on top of bars
var myoption = {
tooltips: {
enabled: true
},
hover: {
animationDuration: 1
},
animation: {
duration: 1,
onComplete: function () {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.textAlign = 'center';
ctx.fillStyle = "rgba(0, 0, 0, 1)";
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 5);
});
});
}
}
};
conditionsTrackChart = new CanvasJS.Chart("chartContainer5", {
backgroundColor: "black",
title: {
text: "Conditions Success Rate",
fontColor: "white"
},
axisX: {
//title: "Conditions",
titleFontColor: "green",
labelFontColor: "white"
},
axisY: {
title: "Count",
titleFontColor: "red",
labelFontColor: "white"
//interval: 10
},
legend: {
cursor:"pointer",
itemclick : toggleDataSeries
},
toolTip: {
shared: true,
content: toolTipFormatter
},
data: myData, // Chart data
options: myoption // Chart Options [This is optional paramenter use to add some extra things in the chart].
});
conditionsTrackChart.render();
} | [
"function updateConditionsTrackChart() {\r\n\t\t\t\t\tupdateConditionsTrackChart2();\r\n\t\t\t\t}",
"function updateHiSideChart() {\r\n\t\t\t\t\thandleHiSideTrack(2);\r\n\t\t\t\t\tupdateHiSideChart2();\r\n\t\t\t\t}",
"function updateLoSideChart() {\r\n\t\t\t\t\thandleLoSideTrack(2);\r\n\t\t\t\t\tupdateLoSideChart2();\r\n\t\t\t\t}",
"function updateChart() {\n const extent = d3.event.selection;\n \n if(!extent) {\n if (!idleTimeout) return idleTimeout = setTimeout(idled, 350); // This allows to wait a little bit\n x.domain(d3.extent(computedData, function(d) {\n return d.dateObj }))\n } else {\n x.domain([ x.invert(extent[0]), x.invert(extent[1]) ])\n areaChart.select(\".brush\").call(brush.move, null)\n }\n\n // Update axis and area position\n xAxis.transition().duration(1000).call(d3.axisBottom(x).ticks(6))\n areaChart\n .selectAll(\"path\")\n .transition().duration(1000)\n .attr(\"d\", area);\n \n }",
"function updateHiSideBreakChart() {\r\n\t\t\t\t\thandleHiSideTrack(3);\r\n\t\t\t\t\tupdateHiSideBreakChart2();\r\n\t\t\t\t}",
"function updateLoSideBreakChart() {\r\n\t\t\t\t\thandleLoSideTrack(3);\r\n\t\t\t\t\tupdateLoSideBreakChart2();\r\n\t\t\t\t}",
"function updatePeriods(){\n var periods;\n\n /* 726: Set the period to hourly for ww3 dataset and hide the monthly option as it is not available for surface map. */\n if (ocean.datasetid == 'ww3'){\n if (ocean.plottype == 'histogram'){\n periods = {\"monthly\": ocean.variables[ocean.variable].plots[getValue('plottype')]['monthly']};\n }else if (ocean.plottype == 'map'){\n periods = {\"hourly\": ocean.variables[ocean.variable].plots[getValue('plottype')]['hourly']};\n } else if (ocean.plottype == 'waverose'){\n periods = {\"monthly\": ocean.variables[ocean.variable].plots[getValue('plottype')]['monthly']};\n }\n } else {\n periods = ocean.variables[ocean.variable].plots[ocean.plottype];\n }\n\n filterOpts('period', periods);\n selectFirstIfRequired('period');\n showControls('period');\n}",
"function updateBidChart() {\r\n\t\t\t\t\tupdateBidChart2();\r\n\t\t\t\t}",
"onChartRender() {\n this.updateProxyOverlays();\n }",
"function updateChartValue(){\r\n myChart.data.datasets[0].data[0] = sumNo;\r\n myChart.data.datasets[0].data[1] = sumYes;\r\n myChart.update()\r\n}",
"function successfulCarmaPull(data) {\n geo_info_object.fossil = parseFloat(data[0].fossil.present);\n geo_info_object.hydro = parseFloat(data[0].hydro.present);\n geo_info_object.nuclear = parseFloat(data[0].nuclear.present);\n geo_info_object.renewable = parseFloat(data[0].renewable.present);\n google.charts.setOnLoadCallback(drawChart);\n}",
"componentDidUpdate() {\n this.buildChart();\n }",
"function updateChartModo(mode) {\r\n var actual;\r\n var title = 'Metro Comparison - Drive Alone';\r\n $('#T18-A .chart-title').html(title);\r\n $('#T18-A-chart').highcharts({\r\n chart: {\r\n type: 'line'\r\n },\r\n title: {\r\n text: ''\r\n },\r\n exporting: {\r\n chartOptions: {\r\n title: {\r\n text: title\r\n }\r\n }\r\n },\r\n xAxis: {\r\n categories: yearNames\r\n },\r\n yAxis: {\r\n min: 0,\r\n title: {\r\n text: 'Weighted Share of Structurally Deficient Bridges'\r\n }\r\n },\r\n legend: {\r\n reversed: true\r\n },\r\n // tooltip: {\r\n // enabled: true,\r\n // pointFormat: '<span style=\"color:{series.color}\">{series.name}</span>: <b>{point.percentage:.1f}%</b> ({point.y:,.0f})</b>',\r\n // shared: true\r\n // },\r\n colors: altColors,\r\n /*plotOptions: {\r\n series: {\r\n stacking: 'normal',\r\n point: {\r\n events: {\r\n mouseOver: function() {\r\n //console.log(this);\r\n update_areachartinfot14t15a(this.category, this.y);\r\n\r\n },\r\n click: function() {\r\n update_areachartinfot14t15a(this.category, this.y);\r\n }\r\n }\r\n }\r\n }\r\n },*/\r\n series: [{\r\n name: 'Bay Area',\r\n data: vmtRegion\r\n }]\r\n });\r\n }",
"updateSplitTrackAxis(categories) {\n const legend_axis = this.layout.track_split_legend_to_y_axis ? `y${this.layout.track_split_legend_to_y_axis}` : false;\n if (this.layout.split_tracks) {\n const tracks = +categories.length || 0;\n const track_height = +this.layout.track_height || 0;\n const track_spacing = 2 * (+this.layout.bounding_box_padding || 0) + (+this.layout.track_vertical_spacing || 0);\n const target_height = (tracks * track_height) + ((tracks - 1) * track_spacing);\n this.parent.scaleHeightToData(target_height);\n if (legend_axis && this.parent.legend) {\n this.parent.legend.hide();\n this.parent.layout.axes[legend_axis] = {\n render: true,\n ticks: [],\n range: {\n start: (target_height - (this.layout.track_height / 2)),\n end: (this.layout.track_height / 2),\n },\n };\n // There is a very tight coupling between the display directives: each legend item must identify a key\n // field for unique tracks. (Typically this is `state_id`, the same key field used to assign unique colors)\n // The list of unique keys corresponds to the order along the y-axis\n this.layout.legend.forEach((element) => {\n const key = element[this.layout.track_split_field];\n let track = categories.findIndex((item) => item === key);\n if (track !== -1) {\n if (this.layout.track_split_order === 'DESC') {\n track = Math.abs(track - tracks - 1);\n }\n this.parent.layout.axes[legend_axis].ticks.push({\n y: track - 1,\n text: element.label,\n });\n }\n });\n this.layout.y_axis = {\n axis: this.layout.track_split_legend_to_y_axis,\n floor: 1,\n ceiling: tracks,\n };\n }\n // This will trigger a re-render\n this.parent_plot.positionPanels();\n } else {\n if (legend_axis && this.parent.legend) {\n if (!this.layout.always_hide_legend) {\n this.parent.legend.show();\n }\n this.parent.layout.axes[legend_axis] = { render: false };\n this.parent.render();\n }\n }\n return this;\n }",
"handleSubChartPropertyChange(key, value) {\n const state = this.state;\n state.configuration.charts[0][key] = value;\n this.setState(state);\n this.props.onConfigurationChange(state.configuration);\n }",
"function showAccidentsHour(dataFor2017) {\n let dim = dataFor2017.dimension(dc.pluck(\"hour\"));\n\n let totalAccByHour = dim.group().reduceSum(dc.pluck(\"number_of_accidents\"));\n let totalCasByHour = dim.group().reduceSum(dc.pluck(\"number_of_casualties\"));\n let totalVehByHour = dim.group().reduceSum(dc.pluck(\"number_of_vehicles\"));\n\n let composite = dc.compositeChart(\"#composite-hour\");\n\n composite\n .width(840)\n .height(310)\n .margins({ top: 20, right: 60, bottom: 50, left: 45 })\n .dimension(dim)\n .elasticY(true)\n .legend(dc.legend().x(230).y(320).itemHeight(15).gap(5)\n .horizontal(true).itemWidth(100))\n .x(d3.scale.linear().domain([0, 23]))\n .y(d3.scale.linear())\n .transitionDuration(500)\n .shareTitle(false)\n .on(\"renderlet\", (function(chart) {\n chart.selectAll(\".dot\")\n .style(\"cursor\", \"pointer\");\n }))\n .on(\"pretransition\", function(chart) {\n chart.selectAll(\"g.y text\")\n .style(\"font-size\", \"12px\");\n chart.selectAll(\"g.x text\")\n .style(\"font-size\", \"12px\")\n .attr(\"dx\", \"-30\")\n .attr(\"dy\", \"-5\")\n .attr(\"transform\", \"rotate(-90)\");\n chart.select(\"svg\")\n .attr(\"height\", \"100%\")\n .attr(\"width\", \"100%\")\n .attr(\"viewBox\", \"0 0 840 340\");\n chart.selectAll(\".dc-chart text\")\n .attr(\"fill\", \"#E5E5E5\");\n chart.selectAll(\".dc-legend-item text\")\n .attr(\"font-size\", \"15px\")\n .attr(\"fill\", \"#ffffff\");\n chart.selectAll(\"line\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".domain\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".line\")\n .style(\"stroke-width\", \"2.5\");\n })\n .compose([\n dc.lineChart(composite)\n .group(totalAccByHour, \"Accidents\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n if (d.key < 10) {\n return numberWithCommas + \" accidents at \" + \"0\" +\n d.key + \":00\";\n }\n else {\n return numberWithCommas + \" accidents at \" +\n d.key + \":00\";\n }\n })\n .colors(\"#ff7e0e\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .group(totalCasByHour, \"Casualties\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n if (d.key < 10) {\n return numberWithCommas + \" casualties at \" + \"0\" +\n d.key + \":00\";\n }\n else {\n return numberWithCommas + \" casualties at \" +\n d.key + \":00\";\n }\n })\n .colors(\"#d95350\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .group(totalVehByHour, \"Vehicles involved\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n if (d.key < 10) {\n return numberWithCommas + \" vehicles involved at \" + \"0\" +\n d.key + \":00\";\n }\n else {\n return numberWithCommas + \" vehicles involved at \" +\n d.key + \":00\";\n }\n })\n .colors(\"#1e77b4\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 })\n ])\n .brushOn(false)\n .yAxisPadding(\"5%\")\n .elasticX(true)\n .xAxisPadding(\"2%\")\n .xAxis().ticks(24).tickFormat(function(d) {\n if (d < 10) {\n return \"0\" + d + \":00\";\n }\n else { return d + \":00\"; }\n }).outerTickSize(0);\n composite.yAxis().ticks(5).outerTickSize(0);\n}",
"function drawCharts(event) {\r\n\tfetchLineChart(event.target.textContent).then(res => {\r\n\t\tconsole.log(res);\r\n\t\t//updating the chart with the data of the selected activity\r\n\t\tline.data.datasets[0].data = res;\r\n\t\tline.update();\r\n\t});\r\n\r\n\tfetchBarChart(event.target.textContent).then(res => {\r\n\t\tconsole.log(res);\r\n\t\t//updating the chart with the data of the selected activity\r\n\t\tbar.data.datasets[0].data = res;\r\n\t\tbar.update();\r\n\t});\r\n}",
"function updateVis() {\n //saves parameters by which to split the bubbles / stack the data\n var splitParams = {\n depiction: 0,\n gender: 0,\n typeOfPic: 0\n };\n \n splitParams.depiction = document.getElementById(\"checkWithDepiction\").checked\n ? 1\n : 0;\n splitParams.gender = document.getElementById(\"checkGender\").checked ? 1 : 0;\n splitParams.typeOfPic = document.getElementById(\"checkPicType\").checked\n ? 1\n : 0;\n \n //console.log(\"splitparams\", splitParams);\n \n var arr = [splitParams.depiction, splitParams.gender, splitParams.typeOfPic];\n \n //erste Filteroption bei Filtern nach Abbildung unanklickbar und ungeklickt machen\n if (arr[2] == 1) {\n document.getElementById(\"checkWithDepiction\").checked = false;\n document.getElementById(\"checkWithDepiction\").disabled = true;\n } else {\n document.getElementById(\"checkWithDepiction\").disabled = false;\n }\n if(arr[0] == 1){ // if first option is checked, disable third option\n document.getElementById(\"checkPicType\").checked = false;\n document.getElementById(\"checkPicType\").disabled = true;\n } else{\n document.getElementById(\"checkPicType\").disabled = false;\n }\n \n /**updates bubble chart with filter as defined in arr array that contains the filter booleans */\n if(splitparamsArray[2] != arr[2]){ \n needToChangeYScaleStack = true;\n } else{\n needToChangeYScaleStack = false;\n }\n splitparamsArray = arr;\n updateBubbleChart();\n updateStackedAreaChart();\n \n \n }",
"function updateView() {\n \n $.when ($.getJSON(BASE_URL + \"/rides/count/per_month\", perYear), \n ).then(updateChart);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
[19] PathExpr ::= LocationPath | FilterExpr | FilterExpr '/' RelativeLocationPath | FilterExpr '//' RelativeLocationPath Unlike most other nodes, this one always generates a node because at this point all reverse nodesets must turn into a forward nodeset | function pathExpr(stream, a) {
// We have to do FilterExpr before LocationPath because otherwise
// LocationPath will eat up the name from a function call.
var filter = filterExpr(stream, a);
if (null == filter) {
var loc = locationPath(stream, a);
if (null == loc) {
throw new Error();
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': The expression shouldn\'t be empty...');
}
return a.node('PathExpr', loc);
}
var rel = relativeLocationPath(filter, stream, a, false);
if (filter === rel) return rel;else return a.node('PathExpr', rel);
} | [
"function relativeLocationPath(lhs, stream, a, isOnlyRootOk) {\n if (null == lhs) {\n lhs = step(stream, a);\n if (null == lhs) return lhs;\n }\n var op;\n while (op = stream.trypop(['/', '//'])) {\n if ('//' === op) {\n lhs = a.node('/', lhs, a.node('Axis', 'descendant-or-self', 'node', undefined));\n }\n var rhs = step(stream, a);\n if (null == rhs && '/' === op && isOnlyRootOk) return lhs;else isOnlyRootOk = false;\n if (null == rhs) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected step after ' + op);\n lhs = a.node('/', lhs, rhs);\n }\n return lhs;\n }",
"* __pathsGenerator(path, node) {\n const endingSlash =\n (node.children.length > 0 || node.endsWithSlash) ? '/' : '';\n const currentPath = path + node.name + endingSlash;\n if (!node.visited) {\n yield currentPath;\n node.visited = true;\n }\n for (const child of node.children) {\n yield * this.__pathsGenerator(currentPath, child);\n }\n }",
"function simplifyPathExpression(graph, p) {\n\n let reduced =\n _(p)\n .groupBy('compositionNode.id') // We group path that go to the same target\n .map(x => // For each of these groups\n ({\n compositionNode: x[0].compositionNode, // Merge target interactions by taking the first\n condition: _(x).pluck('condition').map(y => _.unique(y, z => (z.node.id + \" \" + z.index))).value() // Merge conditions, and remove duplicates conditions from paths\n })\n )\n .flatten()\n // Now the condition for each target is an array (disjunction) of paths (conjunction)\n .forEach(x => {\n\n\n let allConds =\n _(x.condition)\n .flatten()\n .map(c => ({\n cond: c,\n stringRep: (c.node.id + \" \" + c.index)\n }))\n .unique('stringRep')\n .value();\n\n if (allConds.length == 0) {\n x.simplifiedCond = null;\n } else {\n if (allConds.length == 1) { // We do not have to create a new Synthetic node in this case\n x.simplifiedCond = x.condition[0][0];\n } else {\n\n let satProblem =\n _(x.condition)\n .map(y => (\n _(y)\n .map(c => (c.node.id + \" \" + c.index))\n .value()))\n .value();\n\n\n // console.log(\"hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\");\n // console.log(_.pluck(allConds,'stringRep'));\n // console.log(satProblem);\n // console.log(\"iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii\");\n let solution = sat.solvePath(_.pluck(allConds, 'stringRep'), satProblem);\n // console.log(solution);\n // console.log(\"jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj\");\n\n let newNode =\n graph\n .addNode({\n type: 'InteractionInstance',\n content: {\n type: 'InteractionNative',\n content: \"TBD\"\n }\n });\n\n let allEdgesToConds =\n _(allConds)\n .map((c, index) => ({\n cond: c.cond,\n stringRep: c.stringRep,\n edge: graph.addEdge({\n type: 'InteractionInstanceOperand',\n from: {\n index: (index + 1),\n node: newNode,\n ports: {type:'InterfaceAtomic',direction:'in',data:{type:'DataAtomic',name:'Activation'}}\n },\n to: c.cond\n })\n }))\n .value();\n\n let code = _(solution)\n .map(s => {\n let solcode = \"if( \";\n solcode = solcode +\n _(s)\n .map((value, index) => ('( <%=a' + (index + 1) + '%>' + ' === ' + (value ? 'active' : 'inactive') + ' )'))\n .join(' && ');\n solcode = solcode + \") {\\n <%=a0%> = active;\\n} else {\\n <%=a0%> = inactive;\\n}\";\n return solcode;\n })\n .join(\"\\n\");\n\n // console.log(code);\n newNode.content.content = code;\n newNode.ports = [{type:'InterfaceAtomic',direction:'out',data:{type:'DataAtomic',name:'Activation'}}].concat(_.map(allConds, {type:'InterfaceAtomic',direction:'in',data:{type:'DataAtomic',name:'Activation'}}));\n\n // console.log('ffffffffffffffffffffffffffffffffffffffffffffffffff');\n\n x.simplifiedCond = {\n index: 0,\n node: newNode,\n ports: {type:'InterfaceAtomic',direction:'out',data:{type:'DataAtomic',name:'Activation'}}\n };\n\n }\n }\n\n\n\n })\n .value();\n\n // compositionNode\n\n // returns something which contains a key \"simplified cond\" which is a graph node that regroupd all conditions\n\n return reduced;\n}",
"get nextPath() { return this.next && this.next.path }",
"function pathSolver(path) {\n return path;\n}",
"finalizeSlicedFindPath() {\n\n\t\tlet path = [];\n\t\tif (this.m_query.status == Status.FAILURE) {\n\t\t\t// Reset query.\n\t\t\tthis.m_query = new QueryData();\n\t\t\treturn new FindPathResult(Status.FAILURE, path);\n\t\t}\n\n\t\tif (this.m_query.startRef == this.m_query.endRef) {\n\t\t\t// Special case: the search starts and ends at same poly.\n\t\t\tpath.push(this.m_query.startRef);\n\t\t} else {\n\t\t\t// Reverse the path.\n\t\t\tif (this.m_query.lastBestNode.id != this.m_query.endRef)\n\t\t\t\tthis.m_query.status = Status.PARTIAL_RESULT;\n\n\t\t\tlet prev = null;\n\t\t\tlet node = this.m_query.lastBestNode;\n\t\t\tlet prevRay = 0;\n\t\t\tdo {\n\t\t\t\tlet next = this.m_nodePool.getNodeAtIdx(node.pidx);\n\t\t\t\tnode.pidx = this.m_nodePool.getNodeIdx(prev);\n\t\t\t\tprev = node;\n\t\t\t\tlet nextRay = node.flags & Node.DT_NODE_PARENT_DETACHED; // keep track of whether parent is not adjacent (i.e. due to raycast shortcut)\n\t\t\t\tnode.flags = this.or(this.and(node.flags, ~Node.DT_NODE_PARENT_DETACHED), prevRay); // and store it in the reversed path's node\n\t\t\t\tprevRay = nextRay;\n\t\t\t\tnode = next;\n\t\t\t} while (node != null);\n\n\t\t\t// Store path\n\t\t\tnode = prev;\n\t\t\tdo {\n\t\t\t\tlet next = this.m_nodePool.getNodeAtIdx(node.pidx);\n\t\t\t\tif ((node.flags & Node.DT_NODE_PARENT_DETACHED) != 0) {\n\t\t\t\t\tlet iresult = raycast(node.id, node.pos, next.pos, this.m_query.filter, 0, 0);\n\t\t\t\t\tpath.addAll(iresult.path);\n\t\t\t\t\t// raycast ends on let boundary and the path might include the next let boundary.\n\t\t\t\t\tif (path[path.length - 1] == next.id)\n\t\t\t\t\t\tpath.remove(path.length - 1); // remove to aduplicates\n\t\t\t\t} else {\n\t\t\t\t\tpath.push(node.id);\n\t\t\t\t}\n\n\t\t\t\tnode = next;\n\t\t\t} while (node != null);\n\t\t}\n\n\t\tlet status = this.m_query.status;\n\t\t// Reset query.\n\t\tthis.m_query = new QueryData();\n\n\t\treturn new FindPathResult(status, path);\n\t}",
"function gotoPath(rawNodes, pathList) {\n\t console.log(Math.floor(Date.now() / 1000), \"start gotoPath\", rawNodes, pathList);\n\t \n\t try {\n\t \n\t if (pathList) {\n\n\t\t\t// use list to to generate new node graph\n\t\t\tvar pathNodes = []\n\t\t\tfor (var n=0; n<pathList.length; n++) {\n\t\t\t\tvar _id = pathList[n] ;\n\t\t\t\t// console.log('_id',_id)\n\t\t\t\tvar _node = getNodeById(rawNodes,_id) ;\n\t\t\t\t// console.log('_node',_node)\n\t\t\t\tpathNodes.push(_node) ;\n\t\t\t}\n\t\t\tconsole.log('pathNodes',pathNodes,pathNodes.length)\n\t\t\t\n\t\t\t\n\t\t\t// // create edges between path nodes - NEED TO MAKE MORE COMPLETE BY LOOP THROUGH PROPERTIES OF NODES\n\t\t\t// var pathEdges = []\n\t\t\t// if (pathNodes.length>0) {\n\t\t\t// for (var p=0; p<pathNodes.length-1; p++) {\t\t\t\t\t\t// only loop length - 1 \n\t\t\t// \tvar _nd1 = pathNodes[p] ;\t\t\t\t\tconsole.log('_nd1',_nd1)\n\t\t\t// \tvar _id1 = _nd1['@id']; ;\t\t\t\t\tconsole.log('_id1',_id1)\n\t\t\t// \tvar _nd2 = pathNodes[p+1] ;\t\t\t\t\tconsole.log('_nd2',_nd2)\n\t\t\t// \tvar _id2 = _nd2['@id'] ;\t\t\t\t\tconsole.log('_id2',_id2)\n\t\t\t\t\n\t\t\t// \tvar pathEdge = {};\n\t\t\t// \tpathEdge.arrows = {\"to\":\"true\"};\n\t\t\t// \tpathEdge.from = _id1;\n\t\t\t// \tpathEdge.to = _id2;\n\t\t\t// \tpathEdge.label = 'related to';\n\t\t\t\t\t\t\n\t\t\t// \tpathEdges.push(pathEdge);\n\t\t\t// }\n\t\t\t// }\n\t\t\t// console.log('pathEdges',pathEdges)\n\n\t\t\t// redrawn with path nodes and edges\n\t\t\t// setNetwork(pathNodes, pathEdges)\n\t\t\tvar startId = pathNodes[0] ;\n\t\t\t\n\t\t\tgotoNode(startId,pathNodes)\n\n\t }\n\t \n\t }\n\t\tcatch(e) {\n\t\t console.error(Math.floor(Date.now() / 1000), e)\n\t\t} \n\t\tfinally {\n\t\t\t// stop spinner\n\t\t\t// if (spinner) spinner.stop() ; \n\t\t\t// console.log(Math.floor(Date.now() / 1000), 'spinner stop',spinner)\n\t\t\t\n\t\t\tconsole.log(Math.floor(Date.now() / 1000), 'finish gotoPath')\n\t\t}\n\t} // end gotoPath",
"RelationExpression() {\n return this._BinaryExpression(\"AdditiveExpression\", \"RELATIONAL_OPERATOR\");\n }",
"function Expr() {\n var node = new Node('Expr');\n p.child.push(node);\n p = node;\n if (!Term()) {\n return false\n } else {\n p = node;\n return ExprTail();\n }\n }",
"visitXor_expr(ctx) {\r\n console.log(\"visitXor_expr\");\r\n let length = ctx.getChildCount();\r\n let value = this.visit(ctx.and_expr(0));\r\n for (var i = 1; i * 2 < length; i = i + 1) {\r\n if (ctx.getChild(i * 2 - 1).getText() === \"^\") {\r\n value = {\r\n type: \"BinaryExpression\",\r\n operator: \"^\",\r\n left: value,\r\n right: this.visit(ctx.and_expr(i)),\r\n };\r\n }\r\n }\r\n return value;\r\n }",
"transform(path, operation) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n return fn$4(path, p => {\n var {\n affinity = 'forward'\n } = options; // PERF: Exit early if the operation is guaranteed not to have an effect.\n\n if (path.length === 0) {\n return;\n }\n\n switch (operation.type) {\n case 'insert_node':\n {\n var {\n path: op\n } = operation;\n\n if (Path.equals(op, p) || Path.endsBefore(op, p) || Path.isAncestor(op, p)) {\n p[op.length - 1] += 1;\n }\n\n break;\n }\n\n case 'remove_node':\n {\n var {\n path: _op\n } = operation;\n\n if (Path.equals(_op, p) || Path.isAncestor(_op, p)) {\n return null;\n } else if (Path.endsBefore(_op, p)) {\n p[_op.length - 1] -= 1;\n }\n\n break;\n }\n\n case 'merge_node':\n {\n var {\n path: _op2,\n position\n } = operation;\n\n if (Path.equals(_op2, p) || Path.endsBefore(_op2, p)) {\n p[_op2.length - 1] -= 1;\n } else if (Path.isAncestor(_op2, p)) {\n p[_op2.length - 1] -= 1;\n p[_op2.length] += position;\n }\n\n break;\n }\n\n case 'split_node':\n {\n var {\n path: _op3,\n position: _position\n } = operation;\n\n if (Path.equals(_op3, p)) {\n if (affinity === 'forward') {\n p[p.length - 1] += 1;\n } else if (affinity === 'backward') ; else {\n return null;\n }\n } else if (Path.endsBefore(_op3, p)) {\n p[_op3.length - 1] += 1;\n } else if (Path.isAncestor(_op3, p) && path[_op3.length] >= _position) {\n p[_op3.length - 1] += 1;\n p[_op3.length] -= _position;\n }\n\n break;\n }\n\n case 'move_node':\n {\n var {\n path: _op4,\n newPath: onp\n } = operation; // If the old and new path are the same, it's a no-op.\n\n if (Path.equals(_op4, onp)) {\n return;\n }\n\n if (Path.isAncestor(_op4, p) || Path.equals(_op4, p)) {\n var copy = onp.slice();\n\n if (Path.endsBefore(_op4, onp) && _op4.length < onp.length) {\n copy[_op4.length - 1] -= 1;\n }\n\n return copy.concat(p.slice(_op4.length));\n } else if (Path.isSibling(_op4, onp) && (Path.isAncestor(onp, p) || Path.equals(onp, p))) {\n if (Path.endsBefore(_op4, p)) {\n p[_op4.length - 1] -= 1;\n } else {\n p[_op4.length - 1] += 1;\n }\n } else if (Path.endsBefore(onp, p) || Path.equals(onp, p) || Path.isAncestor(onp, p)) {\n if (Path.endsBefore(_op4, p)) {\n p[_op4.length - 1] -= 1;\n }\n\n p[onp.length - 1] += 1;\n } else if (Path.endsBefore(_op4, p)) {\n if (Path.equals(onp, p)) {\n p[onp.length - 1] += 1;\n }\n\n p[_op4.length - 1] -= 1;\n }\n\n break;\n }\n }\n });\n }",
"static create(expr) {\n if (isObject(expr)) {\n if (expr.isObjectionRelationExpression) {\n return expr;\n } else {\n return new RelationExpression(normalizeNode(expr));\n }\n } else if (isString(expr)) {\n if (expr.trim().length === 0) {\n return new RelationExpression();\n } else {\n try {\n return new RelationExpression(parse(expr));\n } catch (err) {\n if (err.duplicateRelationName) {\n throw new DuplicateRelationError(err.duplicateRelationName);\n } else {\n throw new RelationExpressionParseError(err.message);\n }\n }\n }\n } else {\n return new RelationExpression();\n }\n }",
"function createPath(parent, path)\n {\n if (!path.length) // never do \"path == []\"\n {\n return parent;\n }\n else\n {\n var head = path[0];\n var pathrest = path.slice(1, path.length);\n var target = null;\n var nextRoot = null;\n\n // check children\n var children = parent.getChildren();\n\n for (var i=0; i<children.length; i++)\n {\n if (children[i].label == head)\n {\n nextRoot = children[i];\n break;\n }\n }\n\n // else create new\n if (nextRoot == null)\n {\n nextRoot = new demobrowser.Tree(head);\n parent.add(nextRoot);\n }\n\n // and recurse with the new root and the rest of path\n target = createPath(nextRoot, pathrest);\n return target;\n }\n }",
"function computePath( startingNode, endingNode ) {\n // First edge case: start is the end:\n if (startingNode.id === endingNode.id) {\n return [startingNode];\n }\n\n // Second edge case: two connected nodes\n if ( endingNode.id in startingNode.next ) {\n return [startingNode, endingNode];\n }\n\t\n var path = [];\n var n = endingNode;\n while ( n && n.id !== startingNode.id ) {\n // insert at the beggining\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift\n if ( n.id !== endingNode.id ) {\n path.unshift( n );\n }\n n = n.prev;\n }\n\n if ( path.length ) {\n path.unshift( startingNode );\n path.push( endingNode );\n }\n\n return path;\n}",
"function xpathVisitor() {\n\tantlr4.tree.ParseTreeVisitor.call(this);\n\treturn this;\n}",
"transform(ref, op) {\n var {\n current,\n affinity\n } = ref;\n\n if (current == null) {\n return;\n }\n\n var path = Path.transform(current, op, {\n affinity\n });\n ref.current = path;\n\n if (path == null) {\n ref.unref();\n }\n }",
"visitRelational_operator(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"getNextRoutes(path: PathElement<*, *>[], location: Location): Route<*, *>[] {\n const query = getQueryParams(location)\n return path.map(element => {\n const matchedQueryParams = this.getMatchedQueryParams(element.node, query)\n const newRoute = createRoute(element.node, element.parentUrl, element.segment, element.params, query)\n const existingRoute = this.routes.find(x => areRoutesEqual(x, newRoute))\n \n if (existingRoute) {\n return existingRoute\n } else {\n return observable(createRoute(element.node, element.parentUrl, element.segment, element.params, matchedQueryParams))\n }\n })\n }",
"function unaryExpr(stream, a) {\n if (stream.trypop('-')) {\n var e = unaryExpr(stream, a);\n if (null == e) throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, 'Position ' + stream.position() + ': Expected unary expression after -');\n return a.node('UnaryMinus', e);\n } else return unionExpr(stream, a);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to make text Lowercase: | function lower(text) {
return text.toLowerCase();
} | [
"function lowercase(value) {\n return String(value).toLowerCase();\n}",
"toSnakeCase(text, opts = {}) {\n //(1) get case if needed\n if (opts.case == \"lower\") text = text.toLowerCase();\n else if (opts.case == \"upper\") text = text.toUpperCase();\n\n //(2) replace - and whitespaces\n text = text.replace(/[ -]/g, \"_\");\n\n //(3) return\n return text;\n }",
"function upper_lower(str) {\n if (str.length < 3) {\n return str.toUpperCase();\n }\n front_part = (str.substring(0, 3)).toLowerCase();\n back_part = str.substring(3, str.length); \n return front_part + back_part;\n }",
"function LOWER(value) {\n if (!ISTEXT(value)) return error$2.value;\n return value.toLowerCase();\n}",
"function convert_attr_name_to_lowercase(code)\n{\n\tr = /(style=[\"'][^\"']*?[\"'])/gi;\n\treturn code.replace(r,function(s1,s2){\n\t\t\t\t\t\t\ts2 = s2.replace(/;?([^:]*)/g,function(d1,d2){return d2.toLowerCase();}\n\t\t\t\t\t\t);\n\t\t\treturn s2;\n\t});\n}",
"function caps(str){\n return str.replace(/\\w\\S*/g, function(txt){\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n}",
"function allCapsTitleTrimmed(originalText) {\n\tvar text = originalText.trim();\n\ttext = text.toUpperCase();\n\tdocument.getElementById(\"txtTitle\").value = text;\n}",
"function trimWordLowerCase(word) {\n // Remove some zero-width unicode characters (esp. = u00A0)\n var pattern = /[\\u200B-\\u200D\\uFEFF\\u00A0]/g;\n word = word.replace(pattern,\"\");\n\n // Clear out any remaining whitespace surrounding the word\n pattern = /^[\\s]+|[\\s]+$/g;\n word = word.replace(pattern,\"\");\n\n // Remove any punctionation surrounding the word\n // List derived from NON_WORD_CHARS array in Annotext 3.0\n pattern = /^[.,!¡?¿:;\\/|\\\\'\"“”‘’‚„«»‹›()\\[\\]\\-_]+|[.,!¡?¿:;\\/|\\\\'\"“”‘’‚„«»‹›()\\[\\]\\-_]+$/g;\n word = word.replace(pattern,\"\");\n \n word = word.toLowerCase();\n\n return word;\n}",
"function setTextCase(field, toupper) {\r\n if (toupper) {\r\n field.value = field.value.toUpperCase();\r\n } else {\r\n field.value = field.value.toLowerCase();\r\n }\r\n}",
"function LowerCase() {\n var input = \"Do you need lowercase letters in you password? (y/n)\";\n var passLC = prompt(input);\n passLC = passLC.toLowerCase();\n validateYN(passLC);\n while (valid === \"error\") {\n passLC = prompt(errorMsg + input);\n validateYN(passLC);\n }\n if (valid === \"yes\") {\n criteria.push(\"lower\");\n }\n }",
"function normalize(w) {\n w = w.toLowerCase();\n var c = has(w);\n while (c != \"\") { //keep getting rid of punctuation as long as it has it\n var index = w.indexOf(c);\n if (index == 0) w = w.substring(1, w.length);\n else if (index == w.length - 1) w = w.substring(0, w.length - 1);\n else w = w.substring(0, index) + w.substring(index + 1, w.length);\n c = has(w);\n }\n return w;\n\n}",
"function transformText(node, text, context) {\r\n var textTransform = getAttribute(node, context.styleSheets, 'text-transform');\r\n switch (textTransform) {\r\n case 'uppercase':\r\n return text.toUpperCase();\r\n case 'lowercase':\r\n return text.toLowerCase();\r\n default:\r\n return text;\r\n // TODO: capitalize, full-width\r\n }\r\n }",
"function titleCase(name) {\r\n let nameArr = name.split(\" \");\r\n nameArr.forEach(function(curr, idx, arr) {\r\n arr[idx] = curr.toLowerCase().replace(/\\b[a-z]/g, function(first) {\r\n return first.toUpperCase();\r\n });\r\n });\r\n\r\n name = nameArr.join(\" \");\r\n return name;\r\n}",
"function spinalCase(str){\n return str;\n}",
"function SysFmtChangeCase(){}",
"prepare(str) {\n\t\treturn str.trim().toLowerCase();\n\t}",
"function upper(text) {\n return text.toUpperCase();\n }",
"function camelize(name, forceLower){\n if (firstDefined(forceLower, false)) {\n name = name.toLowerCase();\n }\n return name.replace(/\\-./g, function(u){\n return u.substr(1).toUpperCase();\n });\n }",
"function leetspeak(text) {\n regularText = text;\n\n //The global modifier is used to change more than just the first occurence\n regularText = regularText.toUpperCase();\n regularText = regularText.replace(/A/g, '4');\n regularText = regularText.replace(/E/g, '3');\n regularText = regularText.replace(/G/g, '6');\n regularText = regularText.replace(/I/g, '1');\n regularText = regularText.replace(/O/g, '0');\n regularText = regularText.replace(/S/g, '5');\n regularText = regularText.replace(/T/g, '7');\n\n console.log(regularText);\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
:: (Object, ?Object) A keymap binds a set of [key names](keyName) to commands names or functions. Construct a keymap using the bindings in `keys`, whose properties should be [key names](keyName) or spaceseparated sequences of key names. In the second case, the binding will be for a multistroke key combination. When `options` has a property `call`, this will be a programmatic keymap, meaning that instead of looking keys up in its set of bindings, it will pass the key name to `options.call`, and use the return value of that calls as the resolved binding. `options.name` can be used to give the keymap a name, making it easier to [remove](ProseMirror.removeKeymap) from an editor. | function Keymap(keys, options) {
this.options = options || {}
this.bindings = Object.create(null)
if (keys) this.addBindings(keys)
} | [
"function KeyboardLayout(options) {\n for (var key in options) {\n this[key] = options[key];\n }\n}",
"function iglooKeys () {\n\tthis.mode = 'default';\n\tthis.keys = ['default', 'search', 'settings'];\n\tthis.cbs = {\n\t\t'default': {},\n\t\t'search': {\n\t\t\tnoDefault: true\n\t\t},\n\t\t'settings': {}\n\t};\n\n\t//This registers a new keybinding for use in igloo\n\t//And then executes the function under the right circumstances\n\tthis.register = function (combo, mode, func) {\n\t\tvar me = this;\n\t\tif ($.inArray(mode, this.keys) !== -1 && iglooUserSettings.useKeys === true) {\n\t\t\tthis.cbs[mode][combo] = func;\n\n\t\t\tMousetrap.bind(combo, function(e, input) {\n\t\t\t\tif (!me.cbs[igloo.piano.mode].noDefault || input === 'f5') {\n\t\t\t\t\tif (e.preventDefault) {\n\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// internet explorer\n\t\t\t\t\t\te.returnValue = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tme.cbs[igloo.piano.mode][input]();\n\t\t\t});\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t};\n}",
"addShortcut(keys, callback) {\n Mousetrap.bind(keys, callback)\n }",
"function Keymap(){\r\n this.map = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\r\n 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'backspace', 'enter', 'shift', 'delete'];\r\n }",
"_keyboardShortcuts() {\n browser.commands.onCommand.addListener((command) => {\n if (command === 'action-accept-new') {\n this.app.modules.calls.callAction('accept-new')\n } else if (command === 'action-decline-hangup') {\n this.app.modules.calls.callAction('decline-hangup')\n } else if (command === 'action-dnd') {\n // Only toggle when calling options are enabled and webrtc is enabled.\n if (!this.app.helpers.callingDisabled() && this.app.state.settings.webrtc.enabled) {\n this.app.setState({availability: {dnd: !this.app.state.availability.dnd}})\n }\n } else if (command === 'action-hold-active') {\n this.app.modules.calls.callAction('hold-active')\n }\n })\n }",
"resetToDefault() {\n const command = this.edits.rowEl.dataset.command;\n const defaultMapping = Commands.defaultMappings.normal[command];\n this.edits.keyStrings = defaultMapping ? defaultMapping.split(Commands.KEY_SEPARATOR) : [];\n this.displayKeyString(this.edits.rowEl.querySelector(\".shortcut\"), defaultMapping);\n this.commitChange();\n }",
"function KeyConfig(config_name, left, right, down, fall, spin_right, spin_left, flip)\n{\n\tthis.config_name = config_name;\n\tthis.left = left;\n\tthis.right = right;\n\tthis.down = down;\n\tthis.fall = fall;\n\tthis.spin_right = spin_right;\n\tthis.spin_left = spin_left;\n\tthis.flip = flip;\n}",
"get keyName() {\n const prefix = this.guildIDs ? this.guildIDs.join(',') : 'global';\n return `${prefix}:${this.commandName}`;\n }",
"function build_key(options) {\n\t\tlet ret = '';\n\t\tif (!options) {\n\t\t\tlogger.error('[c-couch] missing \"options\" field in build key');\n\t\t\treturn null;\n\t\t} else if (!options.db_name) {\n\t\t\tlogger.error('[c-couch] missing \"db_name\" option in build key');\n\t\t\treturn null;\n\t\t} else if (!options._id && !options.query && !options.view) {\n\t\t\tif (!options.doc || !options.doc._id) {\t// only required if either options._id, options.query, or options.view is missing\n\t\t\t\tlogger.error('[c-couch] missing an option to build the cache key');\n\t\t\t\treturn null;\n\t\t\t}\n\t\t} else {\n\t\t\tret = options.db_name;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// this should always be found\n\n\t\t\t// its important to use a delimiter here, else its possible for two different sets of keys to look the same\n\t\t\tif (options.doc && options.doc._id) { ret += ':' + options.doc._id; }\n\t\t\tif (options.view) { ret += ':' + options.view; }\t\t\t\t\t\t\t\t// this will only be found if it is a couchdb view query\n\t\t\tif (options._id) { ret += ':' + options._id; }\t\t\t\t\t\t\t\t\t// this will only be found if its a simple doc query\n\t\t\tif (options.query) { ret += ':' + options.query; }\t\t\t\t\t\t\t\t// this is for views\n\t\t}\n\n\t\t//logger.debug('\\n\\n[c-couch] built key', ret);\n\t\treturn ret;\n\t}",
"function bindKeys(keys) {\n return Promise.all(keys.map(bindKey));\n\n // returns a promise when a key is bound\n function bindKey(key) {\n var deferred = Promise.defer();\n\n channel.bindQueue(newQueue.name, emitter.name, key, {}, function onBind(err, ok) {\n if (err) return deferred.reject(err);\n return deferred.resolve(ok);\n });\n return deferred.promise;\n }\n }",
"function buildSetter(key) {\n if (key === \"cmd\") {\n return function(val) { this.cmd = val; return this; };\n } else {\n return function(val) { this.options[key] = val; return this; };\n }\n }",
"kvMap( fn ){}",
"function BAKeyEquivalents() {\n\t/** associative array of key asign. { keymark : { aliasName, keyCode, DOMName }, ... }\n\t @type Object @const @private */\n\tthis.keyAlias = {\n\t\t'$' : { aliasName : 'Shift' , keyCode : 16, DOMName : 'shiftKey' }, \n\t\t'%' : { aliasName : 'Ctrl' , keyCode : 17, DOMName : 'ctrlKey' }, \n\t\t'~' : { aliasName : 'Alt' , keyCode : 18, DOMName : 'altKey' }, /* alt (Win), option (Mac) */\n\t\t'&' : { aliasName : 'Meta' , keyCode : 91, DOMName : null }, /* win (Win), command (Mac) (no browsers work this..?) */\n\t\t'#' : { aliasName : 'Enter' , keyCode : 13, DOMName : null },\n\t\t'|' : { aliasName : 'Tab' , keyCode : 9, DOMName : null },\n\t\t'!' : { aliasName : 'Esc' , keyCode : 27, DOMName : null },\n\t\t'<' : { aliasName : '\\u2190' , keyCode : 37, DOMName : null }, /* left */\n\t\t'{' : { aliasName : '\\u2191' , keyCode : 38, DOMName : null }, /* up */\n\t\t'>' : { aliasName : '\\u2192' , keyCode : 39, DOMName : null }, /* right */\n\t\t'}' : { aliasName : '\\u2193' , keyCode : 40, DOMName : null } /* down */\n\t}\n\t/** associative array of key equivalents. { name : { key, aCallBack, aThisObject }, ... }\n\t @type Object @private */\n\tthis.equivalents = {};\n\t/** number of equivalents\n\t @type Number @private */\n\tthis.numOfEquivs = 0;\n}",
"function keyTap(key = '', modified = []) {\n try {\n robot.keyTap(key, modified)\n } catch (err) {\n // Only on debug\n console.error(err);\n }\n}",
"function resolveKey(opKey, keys) {\n\tif (objUtils.isEmpty(keys)) {\n\t\t// when keys map is null or empty, use the param key in rsql string\n\t\treturn opKey;\n\t}\n\telse {\n\t\tif (opKey in keys) {\n\t\t\tvar key = keys[opKey];\n\t\t\tif (!objUtils.isEmpty(key)) {\n\t\t\t\treturn key;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthrow 'There is an unvalid key -' + opKey + '- in rsql string.'\n\t\t}\n\t}\n}",
"function emitKeySequence(keys) {\r\n var i;\r\n for (i = 0; i < keys.length; i++)\r\n emitKey(keys[i], 1);\r\n for (i = keys.length - 1; i >= 0; i--)\r\n emitKey(keys[i], 0);\r\n}",
"add(shortcut_combination, callback = () => {\r\n }, keyup_callback = () => {\r\n }) {\r\n this.saved_controls[shortcut_combination.join('+')] = {shortcut_combination, callback, keyup_callback};\r\n }",
"function keyTyped() {\n mode = key;\n}",
"function crosshairCursor(options = {}) {\n let [code, getter] = keys[options.key || 'Alt']\n let plugin = dist_ViewPlugin.fromClass(\n class {\n constructor(view) {\n this.view = view\n this.isDown = false\n }\n set(isDown) {\n if (this.isDown != isDown) {\n this.isDown = isDown\n this.view.update([])\n }\n }\n },\n {\n eventHandlers: {\n keydown(e) {\n this.set(e.keyCode == code || getter(e))\n },\n keyup(e) {\n if (e.keyCode == code || !getter(e)) this.set(false)\n },\n mousemove(e) {\n this.set(getter(e))\n }\n }\n }\n )\n return [\n plugin,\n EditorView.contentAttributes.of((view) => {\n var _a\n return (\n (_a = view.plugin(plugin)) === null || _a === void 0\n ? void 0\n : _a.isDown\n )\n ? showCrosshair\n : null\n })\n ]\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
static g_services = []; | static Get(serviceName) {
if(!this.g_services) this.g_services = [];
return this.g_services[serviceName];
} | [
"getServices() {\n let services = []\n this.informationService = new Service.AccessoryInformation();\n this.informationService\n .setCharacteristic(Characteristic.Manufacturer, \"OpenSprinkler\")\n .setCharacteristic(Characteristic.Model, \"OpenSprinkler\")\n .setCharacteristic(Characteristic.SerialNumber, \"opensprinkler-system\");\n services.push(this.informationService)\n\n // Add the irrigation system service\n this.irrigationSystemService = new Service.IrrigationSystem(this.name);\n this.irrigationSystemService.getCharacteristic(Characteristic.Active)\n .on(\"get\", syncGetter(this.getSystemActiveCharacteristic.bind(this)))\n .on('set', promiseSetter(this.setSystemActiveCharacteristic.bind(this)))\n\n this.irrigationSystemService.getCharacteristic(Characteristic.InUse)\n .on('get', syncGetter(this.getSystemInUseCharacteristic.bind(this)))\n\n this.irrigationSystemService.getCharacteristic(Characteristic.ProgramMode)\n .on('get', syncGetter(this.getSystemProgramModeCharacteristic.bind(this)))\n\n this.irrigationSystemService.addCharacteristic(Characteristic.RemainingDuration)\n .on('get', syncGetter(this.getSystemRemainingDurationCharacteristic.bind(this)))\n\n this.irrigationSystemService.setPrimaryService(true)\n\n services.push(this.irrigationSystemService)\n\n // Add the service label service\n this.serviceLabelService = new Service.ServiceLabel()\n this.serviceLabelService.getCharacteristic(Characteristic.ServiceLabelNamespace).setValue(Characteristic.ServiceLabelNamespace.DOTS)\n\n // Add all of the valve services\n this.sprinklers.forEach(function (sprinkler) {\n sprinkler.valveService = new Service.Valve(\"\", \"zone-\" + sprinkler.sid);\n // sprinkler.valveService.subtype = \"zone-\" + sprinkler.sid\n\n // Set the valve name\n const standardName = 'S' + ('0' + sprinkler.sid).slice(-2);\n let userGaveName = standardName != sprinkler.name;\n // log(\"Valve name:\", sprinkler.name, userGaveName)\n if (userGaveName) {\n sprinkler.valveService.getCharacteristic(Characteristic.Name).setValue(sprinkler.name)\n // sprinkler.valveService.addCharacteristic(Characteristic.ConfiguredName).setValue(sprinkler.name)\n }\n\n sprinkler.valveService.getCharacteristic(Characteristic.ValveType).updateValue(Characteristic.ValveType.IRRIGATION);\n\n sprinkler.valveService\n .getCharacteristic(Characteristic.Active)\n .on('get', syncGetter(sprinkler.getSprinklerActiveCharacteristic.bind(sprinkler)))\n .on('set', promiseSetter(sprinkler.setSprinklerActiveCharacteristic.bind(sprinkler)))\n\n sprinkler.valveService\n .getCharacteristic(Characteristic.InUse)\n .on('get', syncGetter(sprinkler.getSprinklerInUseCharacteristic.bind(sprinkler)))\n\n sprinkler.valveService.addCharacteristic(Characteristic.SetDuration)\n .on('get', syncGetter(() => sprinkler.setDuration))\n .on('set', (duration, next) => {\n sprinkler.setDuration = duration\n log.debug(\"SetDuration\", duration)\n next()\n })\n\n sprinkler.valveService.addCharacteristic(Characteristic.RemainingDuration)\n\n // Set its service label index\n sprinkler.valveService.addCharacteristic(Characteristic.ServiceLabelIndex).setValue(sprinkler.sid)\n \n // Check if disabled\n sprinkler.disabledBinary = this.disabledStations.toString(2).split('').reverse()\n sprinkler.isDisabled = sprinkler.disabledBinary[sprinkler.sid - 1] === '1'\n\n // log('DISABLED length + sid -------->' + this.sprinklers.length + ' ' + sprinkler.sid)\n // log('DISABLED DATA -------->' + sprinkler.disabledBinary + ' ' + (sprinkler.sid - 1) + ' ' + sprinkler.isDisabled)\n\n // Set if it's not disabled\n // const isConfigured = !sprinkler.isDisabled ? Characteristic.IsConfigured.CONFIGURED : Characteristic.IsConfigured.NOT_CONFIGURED\n sprinkler.valveService.getCharacteristic(Characteristic.IsConfigured)\n .on('get', syncGetter(sprinkler.getSprinklerConfiguredCharacteristic.bind(sprinkler)))\n .on('set', promiseSetter(sprinkler.setSprinklerConfiguredCharacteristic.bind(sprinkler)))\n // .setValue(isConfigured)\n\n // Link this service\n this.irrigationSystemService.addLinkedService(sprinkler.valveService)\n this.serviceLabelService.addLinkedService(sprinkler.valveService)\n\n services.push(sprinkler.valveService)\n }.bind(this))\n\n return services\n }",
"function createGSheetServices() {\n const gSheetServices = new GSheetServices(\n\n )\n return gSheetServices\n}",
"initServices () {\n this.services.db = new DBService({\n app: this,\n db: this.options.dbBackend\n })\n this.services.rpcServer = new RPCServerService({\n app: this,\n port: this.options.rpcPort\n })\n this.services.jsonrpc = new JSONRPCService({\n app: this\n })\n }",
"function onServiceHandler(s) {\n services[s.id] = s; // keep service object\n \n // if the service becomes unavailable remove it from the GUI and from the administration\n s.onRemove = function(service) {\n delete services[this.id];\n $(\"#\" + this.id).fadeOut('fast', function() {$(this).remove(); });\n }\n \n // Add the service to the GUI\n var target = (s.isMine()) ? \"#your_services_group\" : \"#buddies_services_group\";\n var topText = (s.name == 'geolocation') ? \"Location: unknown\" : s.name;\n var element = $(\"<div class='service \" + s.name + \"' id='\" + s.id + \"'>\" + topText + \"<br><em>\" + s.device + \"</em></div>\" )\n .hide().appendTo(target).fadeIn('fast');\n\n // Attach handlers for service removal and invocation\n $(element).click( function() {invoke($(this).attr('id'));} );\n \n // Install handlers that present results of geolocation queries\n if (s.name == 'geolocation') {\n s.onResult = function(lat, lon) {\n $('#' + this.id).html(lat + '° / ' + lon + \"°<br><em>\" + s.device + \"</em>\").effect(\"pulsate\", { times:1 }, 400);\n };\n s.onError = function(err) {\n $('#' + this.id).html(\"<span class=geo-error>\" + err + \"</span><br><em>\" + s.device + \"</em>\").effect(\"pulsate\", { times:1 }, 400);\n };\n }\n}",
"setupServices() {\n this.init = this.init.then(() => {\n // Instantiate independent core services.\n new NotificationEmailCoreSrv({mode: process.env.NODE_ENV});\n new NotificationSMSCoreSrv({mode: process.env.NODE_ENV});\n new SocketCoreSrv(this.server, {mode: process.env.NODE_ENV});\n\n return Promise.all([\n AuthSrv.connect(),\n UserSrv.connect(),\n FileSrv.connect(),\n ProductSrv.connect(),\n TagSrv.connect(),\n PriceSrv.connect(),\n OrderSrv.connect(),\n InvitationSrv.connect(),\n NotificationAlertSrv.connect(),\n CouponSrv.connect(),\n BrandSrv.connect(),\n ListSrv.connect(),\n ListSubscriptionSrv.connect(),\n CompanySrv.connect(),\n BillingSrv.connect(),\n AddressSrv.connect(),\n WalletSrv.connect(),\n TransferSrv.connect(),\n OrderItemSrv.connect()\n ]);\n });\n }",
"function listeners_(){this.listeners$bq6g=( {});}",
"function start() {\n\n service.gapi = gapi.client.init({\n 'apiKey': GOOGLE_API_KEY,\n 'discoveryDocs': [GOOGLE_API_LANGUAGE_URL]\n });\n \n if (cb) {\n cb();\n }\n \n }",
"function getAdvertismentImagesService() {\n\tvar data = {};\n\n\tdata.store_id = Ti.App.Properties.getString(\"store_id\");\n\n\tTi.API.info('DATA ' + JSON.stringify(data));\n\n\tvar SERVICE_GET_ADVERTISMENT = Alloy.Globals.Constants.SERVICE_GET_ADVERTISMENT;\n\tif (Ti.Network.online) {\n\t\tAlloy.Globals.LoadingScreen.open();\n\t\tCommunicator.post(DOMAIN_URL + SERVICE_GET_ADVERTISMENT, getAdvertismentImagesCallback, data);\n\t} else {\n\t\tAlloy.Globals.Notifier.show(L(\"internat_connection_message\"));\n\t}\n}",
"function init() {\r\n myService = new google.gdata.analytics.AnalyticsService('gaExportAPI_acctSample_v2.0');\r\n scope = 'https://www.google.com/analytics/feeds';\r\n var button = document.getElementById('authButton');\r\n \r\n // Add a click handler to the Authentication button.\r\n button.onclick = function() {\r\n // Test if the user is not authenticated.\r\n if (!google.accounts.user.checkLogin(scope)) {\r\n // Authenticate the user.\r\n google.accounts.user.login(scope);\r\n } else {\r\n // Log the user out.\r\n google.accounts.user.logout();\r\n getStatus();\r\n }\r\n }\r\n getStatus();\r\n }",
"loadAPIServices(){\n\n var selected = null;\n\n /**\n * Load Transactions Chart Data\n */\n this.loadGraph();\n\n /**\n * Load All API Services.\n */ \n this.loadVolumes(); \n this.loadMonthlyVolume();\n this.loadMonthlyVolumeByCard();\n this.loadVolumeAnalysis();\n }",
"function initLeService() {\n // Logentries service\n leSvc = LocalServiceRegistry.createService('logentries.avatax.svc', {\n createRequest: function (_svc, args) {\n if (args) {\n return JSON.stringify(args);\n }\n return null;\n },\n parseResponse: function (_svc, client) {\n return client.text;\n }\n });\n // Configure service related parameters\n leConfig = leSvc.getConfiguration();\n leCredential = leConfig.getCredential();\n if (url.toLowerCase().indexOf('sandbox') === -1) {\n if (session.privacy.sitesource && session.privacy.sitesource === 'sgjc') {\n leUrl = leCredential.getURL() + '1e91ee1e-5803-4190-82d6-7e20cd03300d'; // logentries sgjc production\n } else {\n leUrl = leCredential.getURL() + 'd220e459-1119-46b8-8b3b-8aa4dee04245'; // logentries sfra production\n }\n } else if (session.privacy.sitesource && session.privacy.sitesource === 'sgjc') {\n leUrl = leCredential.getURL() + '6e7e8a4d-e107-43fc-ade7-90bd69f83856'; // logentries sgjc development\n } else {\n leUrl = leCredential.getURL() + '78bf832b-72c4-4bf6-a062-39948937dcfb'; // logentries sfra development\n }\n leSvc.setURL(leUrl);\n leSvc.addHeader('Content-Type', 'application/json');\n}",
"function callAllServiceFunctions() {\n\t\tgetAllDataSpeakers();\n\t\tgetAllDataSponsors();\n\t\tgetAllDataSessions();\n\t\tgetAllDataExhibitors();\n\t}",
"function servicesList() {\n connection.query(\"SELECT * FROM servicesList\", function (err, results) {\n\n if (err) throw err;\n \n }\n\n )}",
"function ContactService(){\r\n\t\tthis.contacts = [];\r\n\t\tthis.contactsIndex = {};\r\n\t\tthis.uuid = 0;\r\n\t}",
"function refreshDiscovery(){\n\n\t//show \"load\" gif in room_config page\n\t$('.box').fadeIn('slow');\n\n\n\t//discovery for sensors\n\tfor ( var i in sensor_types) {\n\t\t\tvar type = sensor_types[i];\n\t\t\twebinos.discovery.findServices(new ServiceType(type), {\n\t\t\t\tonFound: function (service) {\n\t\t\t\t\tconsole.log(\"Service \"+service.serviceAddress+\" found (\"+service.api+\")\");\n\n\t\t\t\t\tif(service.serviceAddress.split(\"/\")[0]==pzh_selected || pzh_selected==\"\"){\n\t\t\t\t\t\t//flag used to avoid to change sensors state\n\t\t\t\t\t\tvar flag=false;\n\t\t\t\t\t\tfor(var j in sensors){\n\t\t\t\t\t\t\tif((service.id)==sensors[j].id){\n\t\t\t\t\t\t\t\tflag=true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\t \n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//put it inside sensors[]\n\t\t\t\t\t\tsensors[service.id] = service;\n\t\t\t\t\t\tservice.bind({\n\t\t\t\t\t\t\tonBind:function(){\n\t\t\t \t\t\tconsole.log(\"Service \"+service.api+\" bound\");\n\t\t\t \t\t\tconsole.log(service);\n\t\t\t \t\t\tservice.configureSensor({timeout: 120, rate: 500, eventFireMode: \"fixedinterval\"}, \n\t\t\t \t\t\t\tfunction(){\n\t\t\t \t\t\t\t\tvar sensor = service;\n\t\t\t \t\t\tconsole.log('Sensor ' + service.api + ' configured');\n\t\t\t \t\t\tvar params = {sid: sensor.id};\n\t\t\t \t\t\t\tvar values = sensor.values;\n\t\t\t \t\t\t\tvar value = (values && values[values.length-1].value) || '−';\n\t\t\t \t\t\t\tvar unit = (values && values[values.length-1].unit) || '';\n\t\t\t \t\t\t\tvar time = (values && values[values.length-1].time) || '';\n\n\t\t\t \t\t\tservice.addEventListener('onEvent', \n\t\t\t \t\t\tfunction(event){\n\t\t\t \t\tconsole.log(\"New Event\");\n\t\t\t \t\tconsole.log(event);\n\t\t\t \t\tonSensorEvent(event);\n\t\t\t \t\t},\n\t\t\t \t\t\tfalse\n\t\t\t \t\t);\n\n\t\t\t \t\t\tif(flag==false){\n\t\t\t\t\t \t\t//event listener is active (value=1)\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\tsensorEventListener_state.push({\n\t\t\t\t\t\t\t\t\t\t\t key: service.id,\n\t\t\t\t\t\t\t\t\t\t\t value: 1\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tfunction (){\n\t\t\t\t\t\t\t\t\t\tconsole.error('Error configuring Sensor ' + service.api);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t);\n\t\t\t \t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t \n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\t\n\t\t// discovering actuators\n\t\tfor ( var i in actuator_types) {\n\t\t\tvar type = actuator_types[i];\n\t\t\twebinos.discovery.findServices(new ServiceType(type), {\n\t\t\t\tonFound: function (service) {\n\t\t\t\t\tconsole.log(\"Service \"+service.serviceAddress+\" found (\"+service.api+\")\");\n\t\t\t\t\tif(service.serviceAddress.split(\"/\")[0]==pzh_selected || pzh_selected==\"\"){\n\t\t\t\t\t\t//put it in actuators[]\n\t\t\t\t\t\tactuators[service.id] = service;\n\t\t\t\t\t\tservice.bind({\n\t\t\t\t\t\t\tonBind:function(){\n\t\t\t \t\t\tconsole.log(\"Service \"+service.api+\" bound\");\n\t\t\t\t\t\t\t\tvar params = {aid: service.id};\n\t\t\t \t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t//load rules GUI\n\t\tsetTimeout(initRulesUI,1000);\n\t\tsetTimeout(refreshRules,1000);\n\n \t\t/** load file and GUI of room_config **/\n \t\tload_data_from_file(room_config_file);\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",
"clearClients () {\n this.clientsList = []\n this.loaded = false\n }",
"constructor() {\n this.entities = [];\n this.systems = [];\n }",
"pushScooter(){\n ChargingStation.allScooter.push(this)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the actual background color for content that sticks to the top of the grid. | get actualStickyRowBackground() {
return brushToString(this.i.d5);
} | [
"function getGridBackgroundColorClass() {\n return 'highlighted-' + getGridBackgroundColor();\n }",
"get_background_color(){\n \tconsole.log(\"returning color based on: \" + this.props.priority)\n\n \tswitch (this.props.priority){\n \t\tcase \"low\":\n \t\t\treturn \"#ffffe6\"\n \t\tcase \"medium\":\n \t\t\treturn \"#fff8eb\"\n \t\tcase \"high\":\n \t\t\treturn \"#ffebeb\"\n \t\tdefault:\n \t\t\treturn \"#ffffff\"\n \t}\n }",
"function GetBgColor()\n{\n\t// if (3.0 > h5Ver && !MainPhotos[startIdxY][startIdxX].complete) return;\n\t// if (3.0 <= h5Ver && !MainPhotosTiny[startIdxY][startIdxX].complete) return;\n\t// if (isBgColorSet) return;\n\t// var tempCanvas = document.createElement('canvas'); \n\t// tempCanvas.width = 1; \n\t// tempCanvas.height = 1; \n\t// var tempContext = tempCanvas.getContext(\"2d\"); \n\t// if (3.0 > h5Ver) tempContext.drawImage(MainPhotos[startIdxY][startIdxX], 10, 10, 1, 1, 0, 0, 1, 1);\n\t// else tempContext.drawImage(MainPhotosTiny[startIdxY][startIdxX], 10, 10, 1, 1, 0, 0, 1, 1);\n\t// var imgData = tempContext.getImageData(0, 0, 1, 1);\n\t// bgRed = imgData.data[0];\n\t// bgGreen = imgData.data[1];\n\t// bgBlue = imgData.data[2];\n\t// isBgColorSet = true;\n\t// delete tempCanvas;\n\t// Log(\"BackColor: \" + bgRed + \", \" + bgGreen + \", \" + bgBlue);\n}",
"function uucanvasbgcolor(node) { // @param Node:\n // @return ColorHash:\n var n = node, color = \"transparent\",\n ZERO = uucanvasbgcolor._ZERO;\n\n while (n && n !== doc && ZERO[color]) {\n if (uu.ie && !n.currentStyle) {\n break;\n }\n color = uu.style.quick(n).backgroundColor;\n n = n.parentNode;\n }\n return uu.color(ZERO[color] ? \"white\" : color);\n}",
"get backgroundColor() {\n let backgroundColor = 0xffffff;\n if (Store.getState()) {\n const tp = Store.getState().theme.options.type;\n if (tp === \"dark\") {\n backgroundColor = 0;\n }\n }\n return backgroundColor;\n }",
"getBackgroundStyle(childs) {\n\n if (!isArray(childs) || childs.length === 0) {\n return 'transparent';\n }\n\n let colors = A(A(childs).getEach('color'));\n colors = colors.uniq(); // every color only once!\n colors = colors.sort(); // assure color-order always the same\n colors = colors.filter(color => !isEmpty(color)); // remove empty color strings\n\n\n // single-color\n if (colors.length === 1) {\n return colors[0];\n }\n\n // multi-color\n let background = 'repeating-linear-gradient(90deg,'; // or 180? ;)\n let pxOffset = 0;\n let stripeWidth = get(this, 'stripeWidth');\n\n colors.forEach(color => {\n let nextOffset = pxOffset+stripeWidth;\n background+= `${color} ${pxOffset}px,${color} ${nextOffset}px,`;\n pxOffset = nextOffset;\n });\n\n background = background.substring(0, background.length-1) + ')';\n\n return background;\n }",
"function _renderBackground () {\n\t_ctx.fillStyle = _getColor(\"background\");\n _ctx.fillRect(0, 0, _ctx.canvas.clientWidth, _ctx.canvas.clientHeight);\n}",
"function getStartColor() {\n var editor = atom.workspace.getActiveTextEditor();\n var selection = editor.getSelectedText();\n\n if (selection.length === 7) {\n selection = selection.slice(1);\n }\n\n if (selection.length === 6) {\n return isValidColor(selection) ? [ '-startColor', selection ] : undefined;\n }\n}",
"function getBackground() {\n if ($('body').css('backgroundImage')) {\n return $('body').css('backgroundImage').replace(/url\\(\"?(.*?)\"?\\)/i, '$1');\n }\n }",
"function getNutrientBackgroundColors() {\n let carbsColor = getComputedStyle(document.body).getPropertyValue('--carbs-color');\n let fatColor = getComputedStyle(document.body).getPropertyValue('--fat-color');\n let proteinColor = getComputedStyle(document.body).getPropertyValue('--protein-color');\n return [carbsColor, fatColor, proteinColor];\n}",
"function randomBackground(value) {\n color =`rgb(${value()}, ${value()}, ${value()})`;\n return color\n }",
"function getColor() {\n randomcolor = Math.floor(Math.random() * colors.length);\n quotesBkg.style.backgroundColor = colors[randomcolor];\n // topbar.style.backgroundColor = colors[randomcolor];\n}",
"function getColors(){\n var rgb = mixerBottle.attr('style').replace('background-color: rgb(', '').replace(')', '').split(',');\n return rgb.map(x => parseInt(x));\n }",
"getColor() {\n if (this.state.erasing) { // This ensures that upon erase tool selected, clicking will erase label and color\n return null;\n } else {\n return this.colorBarRef.current.state.color;\n }\n }",
"function getCurrentColor() {\n\t\tlet expr = getStateExpr(ActiveItem.expression.index);\n\t\t\n\t\tif (expr.type === 'expression') {\n\t\t\treturn expr.color;\n\t\t\t\n\t\t} else if (expr.type === 'table') {\n\t\t\treturn expr.columns[ActiveItem.expression.colIndex].color;\n\t\t\t\n\t\t}\n\t\t\n\t}",
"function setBoxBackgroundColor() {\n let body = document.querySelector(\"body\");\n\n // Get current editor background color\n let editorBackgroundColor = tinycolor(\n getComputedStyle(root).getPropertyValue(\"--editorBackgroundColor\")\n );\n let boxBackgroundColor = \"\";\n\n if (editorBackgroundColor.isLight()) {\n boxBackgroundColor = tinycolor(editorBackgroundColor)\n .darken(4)\n .toString();\n } else {\n boxBackgroundColor = tinycolor(editorBackgroundColor)\n .lighten(4)\n .toString();\n }\n\n root.style.setProperty(\"--boxBackgroundColor\", boxBackgroundColor);\n }",
"function randomColorGenerator() {\n\t\treturn Math.floor(Math.random() * backgroundColors.length);\n}",
"function complementElementBg(divs) {\n var i;\n for (i = 0; i < divs.length; ++i) {\n var t = divs[i].style.backgroundColor;\n var s = String(t);\n var rgb = s.substring(s.indexOf('(') + 1, s.indexOf(')'));\n var srgb = rgb.split(',');\n var x = parseInt(srgb[0]) - 255;\n if (x < 0) {\n x = x * ( - 1);\n }\n var y = parseInt(srgb[1]) - 255;\n if (y < 0) {\n y = y * ( - 1);\n }\n var z = parseInt(srgb[2]) - 255;\n if (z < 0) {\n z = z * ( - 1);\n }\n var crgb = 'rgb(' + x + ',' + y + ',' + z + ')';\n divs[i].style.backgroundColor = crgb;\n }\n}",
"function changeDisplayBackgroundColor() {\n iterations++;\n $(\"#display\").css(\"background-color\", DISPLAY_BACKGROUND_COLORS[iterations % DISPLAY_BACKGROUND_COLORS.length]);\n }",
"function startColor () {\n\t\treturn {\n\t\t\tr: 255,\n\t\t\tg: 255 * Math.random(),\n\t\t\tb: 75\n\t\t};\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get folds from and array of lines | function getFolds(lines, level, offset) {
var folds = Object.create(null);
var currentFold = null;
var key, l, line;
// Iterate in lines
for (l = 0; l < lines.length; l++) {
line = lines[l];
// If line is not indented it can be an object key or a key: value pair
if (line.substr(0, TAB_SIZE) !== tab) {
key = line.trim();
// Cover the case that key is quoted. Example: "/user/{userId}":
if ((key[0] === '"') && (key[key.length - 2] === '"') && (key[key.length - 1] === ':')) {
key = key.substring(1, key.length - 2) + ':';
}
// If colon is not the last character it's not an object key
if (!key || key.lastIndexOf(':') !== key.length - 1) {
continue;
}
// Omit colon character
if (key[key.length - 1] === ':') {
key = key.substring(0, key.length - 1);
}
// If there is no current fold in progress initiate one
if (currentFold === null) {
currentFold = {
start: l + offset,
folded: false,
end: null
};
folds[key] = currentFold;
// else, add middle folds recessively and close current fold in progress
} else {
addSubFoldsAndEnd(lines, l, currentFold, level, offset);
currentFold = {
start: l + offset,
end: null
};
folds[key] = currentFold;
}
}
}
// In case there is a current fold in progress finish it
addSubFoldsAndEnd(lines, l, currentFold, level, offset);
return folds;
} | [
"function fold(input, lineSize, lineArray = []) {\n if (input.length <= lineSize) {\n lineArray.push(input);\n return lineArray;\n }\n lineArray.push(input.substring(0, lineSize));\n var tail = input.substring(lineSize);\n return fold(tail, lineSize, lineArray);\n}",
"function foldable(state, lineStart, lineEnd) {\n for (let service of state.facet(foldService)) {\n let result = service(state, lineStart, lineEnd)\n if (result) return result\n }\n return syntaxFolding(state, lineStart, lineEnd)\n }",
"function _foldLine(cm, line) {\n var marks = cm.findMarksAt(CodeMirror.Pos(line + 1, 0)), i;\n if (marks && marks.some(function (m) { return m.__isFold; })) {\n return;\n } else {\n foldFunc(cm, line);\n }\n }",
"function getLines(array) {\n\tarray = array.join('');\n\treturn array.split(/\\n+/);\n}",
"function addSubFoldsAndEnd(lines, l, currentFold, level, offset) {\n var foldLines, subFolds;\n\n // If there is a current fold, otherwise nothing to do\n if (currentFold !== null) {\n\n // set end property which is current line + offset\n currentFold.end = l - 1 + offset;\n\n // If it's not too deep\n if (level > 0) {\n\n // Get fold lines and remove the indent in\n foldLines = lines.slice(currentFold.start + 1 - offset, currentFold.end - offset).map(indent);\n\n // Get subFolds recursively\n subFolds = getFolds(foldLines, level - 1, currentFold.start + 1);\n\n // If results are not empty assign it\n if (!_.isEmpty(subFolds)) {\n currentFold.subFolds = subFolds;\n }\n }\n }\n }",
"function foldableContainer(view, lineBlock) {\n // Look backwards through line blocks until we find a foldable region that\n // intersects with the line\n for (let line = lineBlock; ; ) {\n let foldableRegion = foldable(view.state, line.from, line.to)\n if (foldableRegion && foldableRegion.to > lineBlock.from)\n return foldableRegion\n if (!line.from) return null\n line = view.lineBlockAt(line.from - 1)\n }\n }",
"function foldingTime(array,n) {\n var newArray = array.slice();\n for (var z = 0; z < n; z++) {\n if(newArray.length%2===1){\n var newLength = Math.floor(newArray.length/2)+1;\n\n var x = newArray.length - newLength;\n var fold = newArray.splice(newLength,x).reverse();\n for (var i = 0; i < fold.length; i++) {\n newArray[i]+=fold[i];\n\n }\n }\n else{\n var newLength = newArray.length/2\n var fold = newArray.splice(newLength,newLength).reverse();\n for (var i = 0; i < fold.length; i++) {\n newArray[i]+=fold[i];\n }\n }\n }\n return newArray\n}",
"function codeFolding(config) {\n let result = [foldState, baseTheme$2];\n if (config)\n result.push(foldConfig.of(config));\n return result;\n }",
"_shiftLines(row) {\n\t\tconst blocks = [];\n\n\t\tfor (let y = this.dimensions.height - 1; y > row; y--) {\n\t\t\tblocks.push(Array.from(this.blocks.get(y)).map(x => { return { x: x, y: y }}));\n\t\t}\n\n\t\tconst diffY = (this.dimensions.height - 1) - row;\n\n\t\tfor (let y = row; y >= 0; y--) {\n\t\t\tconst xVals = this.blocks.get(y);\n\t\t\tthis.blocks.set(y + diffY, xVals);\n\t\t\tthis.blocks.delete(y);\n\t\t}\n\n\t\treturn blocks.flat();\n\t}",
"function codeFolding(config) {\n let result = [foldState, dist_baseTheme$1]\n if (config) result.push(foldConfig.of(config))\n return result\n }",
"function makeLines(corners) {\n const length = corners.length;\n for (var i = 0; i < length - 1; i++) {\n const line = new Line(corners[i], corners[i + 1]);\n regions.lines.push(line);\n }\n}",
"function getLines (field) {\n const horizontal_start = $$$$$.ceil(field / 3, 10) * 3,\n vertical_start = field % 3 == 0 ? 3 : field % 3,\n lines = [\n [horizontal_start, horizontal_start - 1, horizontal_start - 2],\n [vertical_start, vertical_start + 3, vertical_start + 6]\n ]\n if (field == 3 || field == 5 || field == 7) lines.push([3, 5, 7])\n if (field == 1 || field == 5 || field == 9) lines.push([1, 5, 9])\n return lines\n }",
"function readarray(){\n\t for (var i = 0; i < 30; i++){ \n\t rand_order = _.shuffle(order); //shuffle the order\n\t for (var j = 0; j <4; j++){ \n\t allwords_order.push(rand_order[j]); \n\t }\n\t } \n\n\t stimuli = readTextFile(\"/static/stim/practice-stim-list.txt\");\t\n\n\t var combined_cond = [];\n\t \n\t for(var i=0;i<30;i++) {\n\t\t combined_cond[i] = stimuli[i].concat(allwords_order[i]);\n\t\t}\n\t return combined_cond;\n\n\t}",
"extractBlocks () {\n return new Promise((resolve, reject) => {\n const result = []\n\n // iterate file lines\n const input = fs.createReadStream(_(this).filePath, { encoding: 'utf8' })\n const lineReader = readline.createInterface({input})\n let lineNumber = 0\n let block = null\n lineReader.on('line', lineString => {\n // name, from, to, content\n // detect block start\n // activate inside block flag\n if (!block && this[isAnStartBlock](lineString)) {\n block = this[buildBlock](lineNumber, lineString, reject)\n } else if (block && this[isAnEndBlock](lineString)) {\n block.to = (lineNumber + 1)\n // add block to result\n result.push(block)\n // deactivate inside block\n block = null\n } else if (!block && this[isAInlineBlock](lineString)) {\n block = this[buildInlineBlock](lineNumber, lineString, reject)\n block.to = block.from\n result.push(block)\n block = null\n } else if (block && !block.content) {\n block.content = lineString\n } else if (block && block.content) {\n block.content += `\\n${lineString}`\n }\n\n lineNumber++\n })\n\n input.on('error', (error) => {\n reject(error)\n })\n\n lineReader.on('close', () => {\n lineReader.close()\n resolve(result)\n })\n })\n }",
"function foldGutter(config = {}) {\n let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config);\n let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false);\n return [\n gutter({\n style: \"foldGutter\",\n lineMarker(view, line) {\n // FIXME optimize this. At least don't run it for updates that\n // don't change anything relevant\n let folded = foldInside(view.state, line.from, line.to);\n if (folded)\n return canUnfold;\n if (getFoldable(view.state, line.from, line.to))\n return canFold;\n return null;\n },\n initialSpacer() {\n return new FoldMarker(fullConfig, false);\n },\n domEventHandlers: {\n click: (view, line) => {\n let folded = foldInside(view.state, line.from, line.to);\n if (folded) {\n view.dispatch({ effects: unfoldEffect.of(folded) });\n return true;\n }\n let range = getFoldable(view.state, line.from, line.to);\n if (range) {\n view.dispatch({ effects: foldEffect.of(range) });\n return true;\n }\n return false;\n }\n }\n }),\n codeFolding()\n ];\n }",
"function getFoldLevel(editor) {\n\t\tfunction nestLevel(node) {\n\t\t\tvar level = 0;\n\t\t\twhile (node.parent) {\n\t\t\t\tlevel++;\n\t\t\t\tnode = node.parent;\n\t\t\t}\n\t\t\treturn level;\n\t\t}\n\t\t// what folds have we got ?\n\t\tvar tree = editor.tree(), folds = editor.folds(),\n\t\t\tlstLevels = [], i=0, lngFolds = folds.length, lngLine;\n\n\t\t// and how deep is the shallowest fold ?\n\t\tfor (i=0; i < lngFolds; i++) {\n\t\t\tlngLine = folds[i].range().startLine();\n\t\t\tlstLevels.push(nestLevel(tree.lineNumberToNode(lngLine)));\n\t\t}\n\t\t// null if no folds\n\t\treturn lstLevels.sort()[0];\n\t}",
"fold (f, a) {\n return fold(f, a, this)\n }",
"function computeLineLocations(numLines, canvasDim, lineList) {\n\tlineList.push(new Line(0));\n\n\tvar dx = canvasDim / numLines;\n\tvar currPos = 0;\n\t\n\twhile (numLines > 0) {\n\t\tcurrPos += dx;\n\t\tlineList.push(new Line(currPos));\n\t\tnumLines--;\n\t}\n\tlineList.push(new Line(canvasDim));\n}",
"result(contents) {\n const starts = new Set();\n this.offsets.forEach(o => starts.add(contents.lastIndexOf('\\n', o) + 1));\n let lines = '';\n for (const i of Array.from(starts).sort((a, b) => a-b)) {\n lines += contents.substring(i, contents.indexOf('\\n', i) + 1);\n }\n return new Result(this.name, this.score, lines);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
OpenAPI2Apigee creates an apiproxy.zip, deleting that | function deleteZip(apiProxy){
fs.unlink(__dirname+'/'+apiProxy+'/apiproxy.zip',function(err){
if(err) return console.log(err);
console.log('file deleted successfully');
});
} | [
"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 }",
"async function setup() {\n const url = new URL(KALEIDO_REST_GATEWAY_URL);\n url.username = KALEIDO_AUTH_USERNAME;\n url.password = KALEIDO_AUTH_PASSWORD;\n url.pathname = \"/abis\";\n var archive = archiver('zip'); \n archive.directory(\"../contracts\", \"\");\n await archive.finalize();\n let res = await request.post({\n url: url.href,\n qs: {\n compiler: \"0.5\", // Compiler version\n source: CONTRACT_MAIN_SOURCE_FILE, // Name of the file in the directory\n contract: `${CONTRACT_MAIN_SOURCE_FILE}:${CONTRACT_CLASS_NAME}` // Name of the contract in the \n },\n json: true,\n headers: {\n 'content-type': 'multipart/form-data',\n },\n formData: {\n file: {\n value: archive,\n options: {\n filename: 'smartcontract.zip',\n contentType: 'application/zip',\n knownLength: archive.pointer() \n }\n }\n }\n });\n // Log out the built-in Kaleido UI you can use to exercise the contract from a browser\n url.pathname = res.path;\n url.search = '?ui';\n console.log(`Generated REST API: ${url}`);\n console.log(`openapi: ${res.openapi}`);\n\n // Store a singleton swagger client for us to use\n swaggerClient = await Swagger(res.openapi, {\n requestInterceptor: req => {\n req.headers.authorization = `Basic ${Buffer.from(`${KALEIDO_AUTH_USERNAME}:${KALEIDO_AUTH_PASSWORD}`).toString(\"base64\")}`;\n }\n });\n\n // deploy contract\n try {\n let postRes = await swaggerClient.apis.default.constructor_post({\n body: {},\n \"kld-from\": FROM_ADDRESS,\n \"kld-sync\": \"true\"\n });\n console.log(\"Deployed instance: \" + postRes.body.contractAddress);\n contract_instance = postRes.body.contractAddress;\n }\n catch(err) {\n console.log(`${err.response && JSON.stringify(err.response.body)}\\n${err.stack}`);\n }\n}",
"removeApi(key, cb) {\n this.request('DELETE', '/api/apis/' + key, null, cb)\n }",
"function _resetUrlApi() {\n apiTest = ipApiByDefault;\n }",
"async revokeApiKey (obj, args, context) {\n try {\n await WIKI.models.apiKeys.query().findById(args.id).patch({\n isRevoked: true\n })\n await WIKI.auth.reloadApiKeys()\n return {\n responseResult: graphHelper.generateSuccess('API Key revoked successfully')\n }\n } catch (err) {\n return graphHelper.generateError(err)\n }\n }",
"function addVerifyAPIKeyPolicy(apiProxy, policyName){\n var verifyapikey = {\n \"VerifyAPIKey\":{\n \"$\":{\n \"async\": \"false\",\n \"continueOnError\": \"false\",\n \"enabled\": \"true\",\n \"name\": policyName\n },\n \"DisplayName\": policyName,\n \"Properties\":null,\n \"APIKey\":{\n \"$\":{\n \"ref\":\"request.queryparam.apikey\"\n }\n }\n }\n };\n var xml = builder.buildObject(verifyapikey);\n fs.writeFile(__dirname+'/'+apiProxy+'/apiproxy/policies/'+policyName+'.xml', xml, function(err, data){\n if (err) console.log(err);\n console.log(\"Successfully Written to File.\");\n });\n}",
"function createApi(opts){\n var deferred = Q.defer(),\n params = {\n name : opts.name,\n description : opts.description\n };\n\n apigateway.createRestApi(params, function(err, data) {\n if (err) deferred.reject(err);\n else deferred.resolve(data);\n });\n\n return deferred.promise;\n }",
"deleteV3ProjectsIdRepositoryFiles(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The project I\n/*let filePath = \"filePath_example\";*/ // String | The path to new file. Ex. lib/class.r\n/*let branchName = \"branchName_example\";*/ // String | The name of branc\n/*let commitMessage = \"commitMessage_example\";*/ // String | Commit Messag\n/*let opts = {\n 'authorEmail': \"authorEmail_example\", // String | The email of the author\n 'authorName': \"authorName_example\" // String | The name of the author\n};*/\napiInstance.deleteV3ProjectsIdRepositoryFiles(incomingOptions.id, incomingOptions.filePath, incomingOptions.branchName, incomingOptions.commitMessage, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"deleteV3HooksId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.HooksApi()\n/*let id = 56;*/ // Number | The ID of the system hook\napiInstance.deleteV3HooksId(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"deleteV3ProjectsIdHooksHookId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let hookId = 56;*/ // Number | The ID of the hook to delete\napiInstance.deleteV3ProjectsIdHooksHookId(incomingOptions.id, incomingOptions.hookId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"deleteV3ProjectsIdDeployKeysKeyIdDisable(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of the projec\n/*let keyId = 56;*/ // Number | The ID of the deploy key\napiInstance.deleteV3ProjectsIdDeployKeysKeyIdDisable(incomingOptions.id, incomingOptions.keyId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"deleteV3ProjectsIdDeployKeysKeyId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of the projec\n/*let keyId = 56;*/ // Number | The ID of the deploy key\napiInstance.deleteV3ProjectsIdDeployKeysKeyId(incomingOptions.id, incomingOptions.keyId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"deleteV3RunnersId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.RunnersApi()\n/*let id = 56;*/ // Number | The ID of the runner\napiInstance.deleteV3RunnersId(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"createApi(apiData, cb) {\n this.request('POST', '/api/apis', apiData, cb)\n }",
"deleteV3ProjectsIdKeysKeyIdDisable(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of the projec\n/*let keyId = 56;*/ // Number | The ID of the deploy key\napiInstance.deleteV3ProjectsIdKeysKeyIdDisable(incomingOptions.id, incomingOptions.keyId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"deleteIdentityprovidersAdfs() { \n\n\t\treturn this.apiClient.callApi(\n\t\t\t'/api/v2/identityproviders/adfs', \n\t\t\t'DELETE', \n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\tnull, \n\t\t\t['PureCloud OAuth'], \n\t\t\t['application/json'],\n\t\t\t['application/json']\n\t\t);\n\t}",
"function unlinkPrevious(callback) {\n fs.unlink(path.resolve(yeoman, 'foundation'), function(err) {\n if (err) return console.log('unlink error:', err);\n console.log('Previous version of yeoman-foundation successfully unlinked...');\n return callback();\n });\n}",
"function removeDeploy(cb){\n del(distPath, cb);\n}",
"deleteV3ProjectsIdServicesServiceSlug(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let serviceSlug = \"serviceSlug_example\";*/ // String | The name of the servic\n/*let id = 56;*/ // Number | \napiInstance.deleteV3ProjectsIdServicesServiceSlug(incomingOptions.serviceSlug, incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"deleteExternalMirror(callback) {\n return this.deleteExternalMirrorRequest().sign().send(callback);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
try to open a socket on handleChatroomModalClose | handleChatroomModalClose(save, chatRoom) {
socket.on('connection', function(socket) {
let newState = {chatroomModalIsOpen: false}
if (save) {
socket.on('setUsername', function(data) {
newState.chatRoom = chatRoom;
if(this.state.users.indexOf(data) > -1) {
this.state.users.push(data);
socket.emit('userSet', {name: data});
} else {
socket.emit('userExists', data + ' username is taken! Try some other username.')
}
this.setState(newState)
})
}
})
} | [
"async function onDisconnect(socket) {\n // socket.rooms is at this moment already emptied (by socket.IO)\n const mapping = registry.getMapping(socket.id);\n\n if (!mapping) {\n // this happens if user is on landing page, socket was opened, then user leaves - socket disconnects, user never joined a room. Perfectly fine.\n return;\n }\n\n const {userId, roomId} = mapping;\n\n if (registry.isLastSocketForUserId(userId)) {\n // we trigger a \"leaveRoom\" command\n const leaveRoomCommand = {\n id: uuid(),\n roomId: roomId,\n userId,\n name: 'leaveRoom',\n payload: {\n connectionLost: true // user did not send \"leaveRoom\" command. But connection was lost (e.g. browser closed)\n }\n };\n await handleIncomingCommand(socket, leaveRoomCommand);\n } else {\n // we have another socket mapped for that userId (e.g. multiple tabs open)\n // just remove the mapping for this socketId\n registry.removeSocketMapping(socket.id);\n }\n }",
"function openLobby(){\n\n\tlet update = {};\n\tupdate.method = 'openLobby';\n\tsocket.emit('player-update', update);\n}",
"function onSocketClose() {\n this[owner_symbol].destroy();\n}",
"function socketOpen() {\n that.debugOut('Socket fully connected');\n that.reconnect_attempts = 0;\n that.connected = true;\n that.emit('socket connected');\n }",
"function joinRoom() {\n initSocket();\n initRoom();\n }",
"onChatRoomInvite(socket) {\n socket.on('invite', (data, fn: (user: User, containsError: boolean, errorMessage: string) => void) => {\n const room: ChatRoom = this.roomProvider.getModel(data.roomId);\n if (!room) {\n fn(undefined, true, 'An error occurred');\n return;\n }\n const user: User = this.userProvider.models.find((model) => model.name === data.nickname);\n if (!user) {\n fn(user, true, 'The user does not exists');\n return;\n }\n if (room.users.find(u => u.id === user.id)) {\n fn(user, true, 'The user is already in the chat room');\n return;\n }\n room.users.push(user);\n user.chatRooms.push(room.id);\n fn(user, false);\n socket.to(user.id).emit('invite', room);\n this.chatWs.sendMessageToChat(room.id, new this.Message(`${user.name} has joined the group!`,\n user.name, this.MessageType.ServerMessage, room.id));\n console.log(`${data.nickname} was invited to ${room.name}`)\n })\n }",
"function initSocket() {\n socketRef.current = io(\"localhost:8000\");\n setId(socketRef.current.id);\n setSocket(socketRef.current);\n }",
"onDeleteChatRoom(socket) {\n socket.on('delete', (roomId: number) => {\n const room: ChatRoom = this.roomProvider.getModel(roomId);\n if (!room) return;\n this.roomProvider.deleteModel(roomId);\n room.users.forEach(user => {\n user.chatRooms = user.chatRooms.filter(id => id !== roomId);\n socket.to(user.id).emit('delete', roomId);\n });\n })\n }",
"close()\n\t{\n\n\t\tthis._closed = true;\n\n\t\t// Close the protoo Room.\n\t\tthis._protooRoom.close();\n\n\t\t// Emit 'close' event.\n\t\tthis.emit('close');\n\n\t\t// Stop network throttling.\n\t\tif (this._networkThrottled)\n\t\t{\n\t\t\tthrottle.stop({})\n\t\t\t\t.catch(() => {});\n\t\t}\n\t}",
"_onClosedConnection () {\n this.messageDisplayUl.classList.add('hidden')\n this.closedNotification.classList.remove('hidden')\n this.messageInput.setAttribute('disabled', '')\n this.sendBtn.setAttribute('disabled', '')\n }",
"function open_chat_box() {\n\n if(window.key_follow==false){\n var camera_chat = '<a href=\"camera\" class=\"com com_camera\" reason=\"camera\"><i class=\"mdi-notification-voice-chat\"></i></a>';\n var attach_file = '<a href=\"file\" class=\"com com_file\" reason=\"file\"> <i class=\"mdi-editor-attach-file\"></i></a>';\n }else{\n var camera_chat = '';\n var attach_file = '';\n }\n\n \n // var follow = '<a href=\"follow\" class=\"com\" reason=\"follow\"> <i class=\"following mdi-social-share\"></i></a>';\n var minimize = '<a class=\"\" style=\"color:#FFF;cursor:pointer;\" > <i class=\"mdi-content-remove\"></i></a>';\n var close = '<a href=\"close\" class=\"com\" reason=\"close_box\"> <i class=\"mdi-navigation-close\"></i></a>';\n\n \n $(\"#chat_div\").chatbox({id : \"chat_div\",\n title : '<span class=\"name_box truncate\"></span><span class=\"title_box_style\"><span class=\"ui-chatbox-icon\">'+camera_chat+attach_file+minimize+close+'</span></span>',\n user : \"can be anything\",\n hidden: false, // show or hide the chatbox\n offset:0,\n width: 230, // width of the chatbox\n messageSent: function(id,user,msg){ \n \n $(\"#chat_div\").chatbox(\"option\", \"boxManager\").addMsg(window.username, msg);//on écrit son message en local\n\n socket.emit('send_message',{'sender_name':window.username,'sender_num':window.user_number,'sender_msg':msg,'interloc_num':window.interloc_num});\n\n }\n });\n \n window.open_chat = true;\n }",
"function initSocketIO(){\n io.on('connection', function(socket){\n\n });\n}",
"function tryJoiningGame() {\n\tDisclaimer.style.display = \"none\"\n\tback2menuBtn.style.display = \"none\"\n\tcontainer.style.display = \"flex\"\n\tmenuModal.style.display = \"none\"\n\twaitingBox.style.display = \"flex\"\n\tscoreBoard.style.display = \"block\"\n\tsocket.emit(\"joinGameRequest\", { user: username })\n\tsocket.on(\"request_ack\", () => {\n\t\tnew Game(socket)\n\t})\n}",
"function joinChatRoom() {\n socketRef.current.emit(\"join chat\", { name, room: roomID });\n }",
"function openChat(props){\n //si setta lo stato \"isChatting\" su true per visualizzazione corretta degli elementi\n setIsChatting(true)\n //si setta la currentChat con gli attributi dalla chat aperta\n setCurrentChat({\n idFriendChatting: props.friendID,\n chatID: props.chatKey,\n usernameFriendChatting: props.friendUsername\n })\n }",
"function sendChatMessege()\n{\n var chat = cleanInput($(\"#chat-box\").val().substring(0, 100));\n\n if($.isBlank(chat))\n return;\n\n socket.emit('chat', chat);\n setPlayerMessege(player, chat);\n $(\"#chat-box\").val(\"\");\n}",
"function connectToRoom() {\n roomNo = document.getElementById('roomNo').value;\n name = document.getElementById('name').value;\n let imageUrl = document.getElementById('image_url').value;\n if (!name) name = 'Unknown-' + Math.random();\n // only if online\n if (chat)\n chat.emit('create or join', roomNo, name);\n initCanvas('chat', imageUrl);\n hideLoginInterface(roomNo, name);\n}",
"function sendQuestionClosedMSG() {\n let message = {\n messageType: \"QUESTION CLOSED\",\n };\n\n theSocket.sendJSON(message);\n}",
"close() {\n this[_socket].close();\n\n if (this[_timeout] !== null) {\n clearTimeout(this[_timeout]);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dismisses all currently displayed modal windows with the supplied reason. | dismissAll(reason) { this._modalStack.dismissAll(reason); } | [
"close() {\n this.showModal = false;\n\n this.onClose();\n }",
"hideVisibleModals() {\n let modals = this.game.modals;\n let visibleModals = Object.keys(modals).map(function(key) {\n let modal = modals[key];\n if(modal.alive && modal.visible == true) {\n return key.toString();\n } else {\n return null;\n }\n }, this).filter( (name) => name != null );\n visibleModals.forEach(function(visibleModal) {\n this.hideModal(visibleModal);\n }, this);\n }",
"function closeModalWindow() {\n $(\"#myModal\").css(\"display\", \"none\");\n $(\"#activeModalCoins\").empty();\n state.modalIsOpen = false;\n resetStatusActiveCoins();\n showAllCoins();\n //unbind close button avoid dubble binding\n $(\"#btnCloseModal\").unbind(\"click\");\n }",
"function closeModal() {\n // Collects all non-standard elements (modals past children[ 2 ])\n var modalElements = $(\"#custom-modal-content\")[0].children;\n // Delete all non-standard elements in the modal. Loop must be run backwards so we don't delete as we're iterating.\n for (i = modalElements.length - 1; i > 2; i--) {\n modalElements[i].remove();\n }\n $(\"#custom-modal-header\").text(\"\");\n $(\"#custom-modal-text\").text(\"\");\n $(\"#custom-modal\").css(\"display\", \"none\");\n}",
"function hideModalDialogs() {\n self.$createModalWindow.hide();\n self.$editModalWindow.hide();\n $.each([self.$createModalWindow.find(\"input\"), self.$editModalWindow.find(\"input\")],\n function(index, item) {\n $.each(item,\n function(index, input) {\n $(input).removeClass(\"error\");\n });\n });\n self.createModel.Age(\"\");\n self.createModel.Name(\"\");\n self.createModel.Position(\"\");\n self.createModel.StartDate(\"\");\n }",
"function closeModal() {\n\twinningMessage.style.display = 'none';\n}",
"attemptDismiss() {\n\t\tif(this.state.currentModal.props.dismissible) this.state.currentModal.props.onDismiss();\n\t}",
"function hideResultModal() {\n\tvar modal = $('#popup-window');\n modal.css('display', 'none');\n}",
"function closecancelpanel(){\n $.modal.close();\n }",
"closeAllWindows() {\n let windows = this.getInterestingWindows();\n for (let i = 0; i < windows.length; i++)\n windows[i].delete(global.get_current_time());\n }",
"function hide() {\n if (!settings.shown) return;\n win.hide();\n settings.shown = false;\n }",
"cancel () {\n this.close();\n this._reject(new Error('User closed dialog.'));\n }",
"function outsideClick(e) {\n if (e.target == modal) {\n modal.style.display = 'none';\n restartGame();\n }\n}",
"handleClose (evt) {\n if (this.focused() && !this.forceQuit) {\n this.contentWindows.forEach((w) => w.close())\n if (process.platform === 'darwin' || this.appSettings.hasTrayIcon) {\n this.mailboxesWindow.hide()\n evt.preventDefault()\n this.forceQuit = false\n }\n }\n }",
"function closeModal() {\r\n modal.style.display = 'none';\r\n }",
"function modalCloseHandlers(){\n const repoModal = document.getElementById('repo-edit-div');\n const deleteModal = document.getElementById('repo-delete-div');\n const entryModal = document.getElementById('entry-edit-div');\n const helpModal = document.getElementById('help-modal');\n\n repoModal.addEventListener('click', function(evt){\n switch(evt.target.id){\n case 'close-repo-modal':\n repoModal.style.display = 'none';\n break;\n case 'repo-edit-div':\n repoModal.style.display = 'none';\n break;\n }\n });\n\n deleteModal.addEventListener('click', function(evt){\n switch(evt.target.id){\n case 'btn-close-repo-delete':\n deleteModal.style.display = 'none';\n break;\n case 'repo-delete-div':\n deleteModal.style.display = 'none';\n break;\n }\n });\n\n entryModal.addEventListener('click', function(evt){\n switch(evt.target.id){\n case 'close-entry-modal':\n entryModal.style.display = 'none';\n break;\n case 'entry-edit-div':\n entryModal.style.display = 'none';\n break;\n }\n });\n\n helpModal.addEventListener('click', function(evt){\n switch(evt.target.id){\n case 'close-help-modal':\n helpModal.style.display = 'none';\n break;\n case 'help-modal':\n helpModal.style.display = 'none';\n break;\n }\n })\n\n}",
"function dismiss()\r\n{\r\n\twhile( subMenu = subMenusUp.pop() )\r\n\t{\r\n\t\tif( ! subMenu.cancelDismiss )\r\n\t\t{\r\n\t\t\tsubMenu.getElementsByTagName(\"ul\")[0].style.display = \"none\";\r\n\t\t}\r\n\t}\r\n}",
"function hideForModal(modalElement) {\n\treturn hideOthers([\n\t\tmodalElement,\n\t\t...document.querySelectorAll(`[aria-live]`),\n\t\t...document.querySelectorAll(`[${PREVENT_ARIA_HIDDEN_ATTRIBUTE}]`),\n\t]);\n}",
"@action closeDialog() {\r\n\t\tif (this.dialog) this.dialog.opened = false;\r\n\t}",
"function closeReportWindow () {\n\tset_element_display_by_id_safe('ReportWindow', 'none');\n\tset_element_display_by_id_safe('report_error1', 'none');\n\tset_element_display_by_id_safe('report_error2', 'none');\n\tset_element_display_by_id_safe('error_div', 'none');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a W3C DOM level 3 standard button value given an event.button property: 1 == none, 0 == primary/left, 1 == middle, 2 == secondary/right, 3 == X1/back, 4 == X2/forward, 5 == eraser (pen) | function getStandardizedButton( button ) {
if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {
// On IE 8, 0 == none, 1 == left, 2 == right, 3 == left and right, 4 == middle, 5 == left and middle, 6 == right and middle, 7 == all three
// TODO: Support chorded (multiple) button presses on IE 8?
if ( button === 1 ) {
return 0;
} else if ( button === 2 ) {
return 2;
} else if ( button === 4 ) {
return 1;
} else {
return -1;
}
} else {
return button;
}
} | [
"function getMouseButton(evt) {\n\tif (evt.which == null) { // internet explorer\n\t\treturn ((evt.button < 2)?MOUSE_BUTTON.LEFT:((evt.button == 4)?MOUSE_BUTTON.MIDDLE:MOUSE_BUTTON.RIGHT));\n\t}\n\t// other browsers\n\treturn ((evt.which < 2)?MOUSE_BUTTON.LEFT:((evt.which == 2)?MOUSE_BUTTON.MIDDLE:MOUSE_BUTTON.RIGHT));\n}",
"getButtonText() {\n return defaultValue(this.buttonText, this.pointEntities.entities.values.length >= 2\n ? i18next.t(\"models.userDrawing.btnDone\")\n : i18next.t(\"models.userDrawing.btnCancel\"));\n }",
"static get miniButtonLeft() {}",
"static get miniButtonRight() {}",
"function ButtonEvent(status, data1, data2) {\n this.status = status;\n this.data1 = data1;\n this.data2 = data2;\n}",
"function detectLeftButton(evt) {\n evt = evt || window.event;\n if (\"buttons\" in evt) {\n return evt.buttons == 1;\n }\n var button = evt.which || evt.button;\n return button == 1;\n}",
"function textBackwardButton() {\n\treturn (\n\t\t`<button class='mainPageButton' onclick='mainPage(); img='images/back.png'></button>`\n\t);\n}",
"function calButtonClick(btnValue){\n //check for symbol \n if (isNaN(parseInt(btnValue))) {\n handleOpetatorClick(btnValue)\n } else {\n handleNumberClick(btnValue.toString())\n }\n \n}",
"static set miniButtonRight(value) {}",
"static set miniButtonMid(value) {}",
"get BBTag() {return browser.element(\"//android.view.ViewGroup[1]/android.view.ViewGroup[3]/android.widget.Button\");}",
"function toggle_button(event_target) {\r\n\tvar event_target_aria_pressed = event_target.getAttribute(\"aria-pressed\");\r\n\tdocument.getElementById(\"introduction\").innerHTML += \"c \" + event_target.getAttribute(\"aria-pressed\");\r\n\tif (!event_target_aria_pressed) { //if false\r\n\t\tevent_target_aria_pressed = true;\r\n\t} else {\r\n\t\tevent_target_aria_pressed = false;\r\n\t}\r\n\tevent_target.setAttribute(\"aria-pressed\", event_target_aria_pressed);\r\n\tdocument.getElementById(\"introduction\").innerHTML += \" \" + event_target.getAttribute(\"aria-pressed\");\r\n}",
"function numberPress(event) {\n var symbol = String(event.target.value);\n if (memoryTrigger && !lastButtonOperator) {\n memoryTrigger = false;\n buttonState = true;\n display = symbol;\n } else if(lastButtonOperator) {\n if (!isNaN(symbol)) {\n buttonState = true;\n display = symbol;\n lastButtonOperator = false;\n } else {\n if (!buttonState) {\n buttonState = true;\n display = \"0\"\n lastButtonOperator = false;\n }\n }\n } else {\n if (!isNaN(symbol)) {\n if (!buttonState) {\n buttonState = true;\n display = \"0\"\n }\n if (display == \"0\" || lastButtonEquals || lastButtonHistory) {\n display = symbol;\n if(lastButtonHistory){\n changeLastNum = true;\n }\n } else {\n display += symbol;\n }\n }\n }\n lastButtonEquals = false;\n lastButtonHistory = false;\n updateDisplay();\n}",
"static set miniButtonLeft(value) {}",
"function alpha_button(textin,xpos_in,ypos_in,widthin,actif,varif,active)\r\n{\r\n if (draw_button(xpos_in,ypos_in,widthin,alpha_button_height,Hcontext,control_button_style,alpha_button_corner,\"src\",active,HmouseX,HmouseY,Hmouse_clicking))\r\n {\r\n if (actif)\r\n {\r\n button_next_action_2 = actif;\r\n }\r\n if (varif)\r\n {\r\n button_next_var_2 = varif;\r\n }\r\n }\r\n draw_text(xpos_in,ypos_in,widthin,alpha_button_height,3,textin,0,button_height*0.55,button_height*0.55,button_text_col,'',Hcontext);\r\n}",
"function drawButton(btn) {\n // Move text down 1 pixel and lighten background colour on mouse hover\n var textOffset;\n if (btn.state === 1) {\n btn.instances.current.background[3] = 0.8;\n textOffset = 1;\n } else {\n btn.instances.current.background[3] = 1.;\n textOffset = 0;\n }\n // Draw button rectangle\n mgraphics.set_source_rgba(btn.instances.current.background);\n mgraphics.rectangle(btn.rect);\n mgraphics.fill();\n // Draw button text\n mgraphics.select_font_face(MPU.fontFamily.bold);\n mgraphics.set_font_size(MPU.fontSizes.p);\n // Calculate text position\n var Xcoord = MPU.margins.x + (btn.rect[2] / 2) - (mgraphics.text_measure(btn.instances.current.text)[0] / 2);\n var Ycoord = MPU.margins.y + btn.rect[1] + (mgraphics.font_extents()[0] / 2) + textOffset;\n mgraphics.move_to(Xcoord, Ycoord);\n mgraphics.set_source_rgba(btn.instances.current.color);\n mgraphics.text_path(btn.instances.current.text);\n mgraphics.fill();\n}",
"function sendEvent(button, pos) {\n var term = ace.session.term;\n // term.emit('mouse', {\n // x: pos.x - 32,\n // y: pos.x - 32,\n // button: button\n // });\n\n if (term.vt300Mouse) {\n // NOTE: Unstable.\n // http://www.vt100.net/docs/vt3xx-gp/chapter15.html\n button &= 3;\n pos.x -= 32;\n pos.y -= 32;\n var data = '\\x1b[24';\n if (button === 0) data += '1';\n else if (button === 1) data += '3';\n else if (button === 2) data += '5';\n else if (button === 3) return;\n else data += '0';\n data += '~[' + pos.x + ',' + pos.y + ']\\r';\n term.send(data);\n return;\n }\n\n if (term.decLocator) {\n // NOTE: Unstable.\n button &= 3;\n pos.x -= 32;\n pos.y -= 32;\n if (button === 0) button = 2;\n else if (button === 1) button = 4;\n else if (button === 2) button = 6;\n else if (button === 3) button = 3;\n term.send('\\x1b[' + button + ';' + (button === 3 ? 4 : 0) + ';' + pos.y + ';' + pos.x + ';' + (pos.page || 0) + '&w');\n return;\n }\n\n if (term.urxvtMouse) {\n pos.x -= 32;\n pos.y -= 32;\n pos.x++;\n pos.y++;\n term.send('\\x1b[' + button + ';' + pos.x + ';' + pos.y + 'M');\n return;\n }\n\n if (term.sgrMouse) {\n pos.x -= 32;\n pos.y -= 32;\n term.send('\\x1b[<' + ((button & 3) === 3 ? button & ~3 : button) + ';' + pos.x + ';' + pos.y + ((button & 3) === 3 ? 'm' : 'M'));\n return;\n }\n\n var data = [];\n\n encode(data, button);\n encode(data, pos.x);\n encode(data, pos.y);\n\n term.send('\\x1b[M' + String.fromCharCode.apply(String, data));\n }",
"function findClosestButton(node) {\n if (node == null) {\n return null\n } else if (node.find('button').length) {\n return node.find('button');\n } else {\n return findClosestButton(node.parent());\n } \n }",
"mDown(e){\n this.xMouseStart=e.offsetX;\n this.yMouseStart=e.offsetY;\n if(this.insideButton){\n Button.shape=this.name;\n }\n }",
"hasButtonStateChanged( vButton ){\n if( VIRTUAL_BUTTONS_STATE[ vButton ] === VIRTUAL_BUTTONS_OLD_STATE[ vButton ] ) return false;\n else return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Populate the locations chart. | function populateLocationsChart(locs, id) {
if(!locs.length) {
$(`#${id}`).hide();
return;
}
let map = L.map('map', {scrollWheelZoom: false, minZoom:1}),
token = 'pk.eyJ1IjoibGliY3Jvd2RzIiwiYSI6ImNpdmlxaHFzNTAwN3YydHBncHV3dHc3aXgifQ.V4WUx9SDcU_XLFJo2M3RxQ',
url = `https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=${token}`;
map.fitWorld();
map.setZoom(2);
L.tileLayer(url, {
attribution: `Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors,
<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery ©
<a href="http://mapbox.com">Mapbox</a>`,
maxZoom: 18,
id: 'mapbox.streets',
accessToken: token
}).addTo(map);
let i = 0;
let locations = locs;
let l = locations.length;
let markers = new L.MarkerClusterGroup();
for (i; i < l; i++) {
if (locations[i].loc !== null) {
let lat = parseFloat(locations[i].loc.latitude),
lng = parseFloat(locations[i].loc.longitude);
markers.addLayer(L.marker([lat, lng]));
}
}
map.addLayer(markers);
} | [
"initializeLocations() {\n for (const filename of glob(kLocationDirectory, '.*\\.json$')) {\n const description = new FightLocationDescription(kLocationDirectory + filename);\n const location = new FightLocation(description);\n\n this.#locations_.set(description.name, location);\n }\n }",
"init() {\n const series = this.chartData.series;\n const seriesKeys = Object.keys(series);\n\n for (let ix = 0, ixLen = seriesKeys.length; ix < ixLen; ix++) {\n this.addSeries(seriesKeys[ix], series[seriesKeys[ix]]);\n }\n\n if (this.chartData.data.length) {\n this.createChartDataSet();\n }\n }",
"function plotLocationSummary(options)\n{\n //Disables in case Quick Load is chosen. For multiple days, the clustering can be annoyingly slow.\n if(quickload)\n {\n\toptions.outerElement.hide();\n\treturn;\n }\n\n var $mycontainer = $(\".template-location-table\").clone();\n $mycontainer.removeAttr(\"style\");\n $mycontainer.removeClass(\"template-location-table\");\n options.outerElement.append($mycontainer);\n $mycontainer.find(\"table\").attr('id','location_table'); \n var tbody = $(\"#location_table\").find(\"tbody\");\t\n\n var clustersArr = [];\n for (var i = 0; i < locationArray.length; i++)\n {\n var location = locationArray[i]\n\tclustersArr.push([location[1].latitude, location[1].longitude])\n }\n \n //Clusters adjacent points together\n clusters = clusterfck.hcluster(clustersArr, clusterfck.EUCLIDEAN_DISTANCE, clusterfck.AVERAGE_LINKAGE, 0.001);\n var clusterMap = generateMap(clusters);\n var clusterDict = generateMapDict(clusters);\n var clusterOp = [];\n var semanticCache = {};\n var start_cluster, end_cluster;\n var prev_cluster = -1;\n var count_cluster = 0;\n var count_speech = 0;\n var count_nonspeech = 0;\n var count_pending = 0;\n for (var i = 0; i < locationArray.length; i++)\n {\n var location = locationArray[i];\n\tvar current_cluster = clusterMap[location[1].latitude+\",\"+location[1].longitude];\n\tif(prev_cluster != current_cluster)\n\t{\n\t if(prev_cluster!=-1)\n\t {\n\t\ttempOp = {};\n\t\ttempOp.start = start_cluster;\n\t\ttempOp.end = end_cluster;\n\t\ttempOp.count = count_cluster;\n\t\ttempOp.cluster = clusterDict[prev_cluster];\n\t\ttempOp.speech = count_speech;\n\t\ttempOp.nonspeech = count_nonspeech;\n\t\ttempOp.pending = count_pending;\n\t\tclusterOp.push(tempOp);\n\t }\n\t prev_cluster = current_cluster;\n\t start_cluster = location[1].frameNo;\n\t end_cluster = location[1].frameNo;\n\t count_cluster = 1;\n\t count_pending = 0;\n\t count_speech = 0;\n\t count_nonspeech =0;\n\t}\n\telse\n\t{\n\t end_cluster = location[1].frameNo;\n\t count_cluster++;\n\t}\n\tbaseTS = getBase(location[1].frameNo);\n\tvar mode = speechMap[options.uname][baseTS];\n\tif(mode == undefined)\n\t{\n\t count_pending++;\n\t}\n\telse if (mode === \"speech\")\n\t{\n\t count_speech++;\n\t}\n\telse if(mode === \"nonspeech\")\n\t{\n\t count_nonspeech++;\n\t}\n }\n if(prev_cluster!=-1)\n {\n\ttempOp = {};\n\ttempOp.start = start_cluster;\n\ttempOp.end = end_cluster;\n\ttempOp.count = count_cluster;\n\ttempOp.cluster = clusterDict[prev_cluster];\n\ttempOp.speech = count_speech;\n\ttempOp.nonspeech = count_nonspeech;\n\ttempOp.pending = count_pending;\n\tclusterOp.push(tempOp);\n } \n\n for (var i = 0; i < clusterOp.length; i++)\n {\n\tif(clusterOp[i].count<=10)\n\t continue;\n\tvar trow = $(\"<tr>\");\n\tparseSemanticLocation(clusterOp[i], trow , semanticCache);\n\ttrow.appendTo(tbody);\n }\n}",
"refreshMap() {\n this.removeAllMarkers();\n this.addNewData(scenarioRepo.getAllEvents(currentScenario));\n this.showAllMarkers();\n }",
"function load_graph_to_map(results){\n load_markers(results.locations);\n //draw_lines(results);\n draw_spanning_tree(results);\n\n}",
"function getLocationsData() {\n middle = getMiddle();\n setPointOnMap(middle.lat, middle.long, key);\n var radiusInMeters = radius * 1609.34;\n\n $('.poweredBy').fadeIn();\n\n // create accessor\n var accessor = {\n consumerSecret: auth.consumerSecret,\n tokenSecret: auth.accessTokenSecret\n };\n\n // push params\n var parameters = [];\n parameters.push(['category_filter', category]);\n parameters.push(['sort', 1]);\n parameters.push(['limit', 10]);\n parameters.push(['radius_filter', radiusInMeters]);\n parameters.push(['ll', middle.lat + ',' + middle.long]);\n parameters.push(['oauth_consumer_key', auth.consumerKey]);\n parameters.push(['oauth_consumer_secret', auth.consumerSecret]);\n parameters.push(['oauth_token', auth.accessToken]);\n parameters.push(['oauth_signature_method', 'HMAC-SHA1']);\n\n var message = {\n 'action': 'http://api.yelp.com/v2/search',\n 'method': 'GET',\n 'parameters': parameters\n };\n\n OAuth.setTimestampAndNonce(message);\n OAuth.SignatureMethod.sign(message, accessor);\n\n var parameterMap = OAuth.getParameterMap(message.parameters);\n parameterMap.oauth_signature = OAuth.percentEncode(parameterMap.oauth_signature);\n\n var qs = '';\n\n for (var p in parameterMap) {\n qs += p + '=' + parameterMap[p] + '&';\n }\n\n var url = message.action + '?' + qs;\n\n\n WinJS.xhr({\n url: url\n }).then(success, failure);\n\n $('#searching').show(); // hide progress\n\n // handles a succesful yelp response\n function success(result) {\n\n var response = window.JSON.parse(result.responseText);\n\n $('#searching').hide(); // hide progress\n\n if (response.businesses.length == 0) { // handle no results error\n $('.error').show();\n\n if (radius == 25) {\n $('.error .noresultsLargest').show();\n }\n else {\n $('.error .noresults').show();\n }\n\n }\n\n var businesses = response.businesses;\n\n var list = new WinJS.Binding.List(); // create a new list to hold items\n\n response.businesses.forEach(function (item) {\n\n var cleaned = [];\n cleaned['name'] = item.name;\n\n var imgurl = item.image_url;\n\n if (imgurl == null || imgurl == '') {\n imgurl = '/images/no-image.png';\n }\n\n cleaned['image_url'] = imgurl;\n\n var address = '';\n var url_address = '';\n\n for (var x = 0; x < item.location.display_address.length; x++) {\n if (x > 0) {\n address += '<br>';\n url_address += ' ';\n }\n address = address + item.location.display_address[x];\n url_address = url_address + item.location.display_address[x];\n }\n\n cleaned['display_address'] = address;\n cleaned['url_address'] = encodeURIComponent(url_address);\n cleaned['city'] = item.location.city;\n cleaned['state'] = item.location.state_code;\n cleaned['city_state'] = item.location.city + ', ' + item.location.state_code;\n cleaned['cross_streets'] = item.location.cross_streets;\n cleaned['latitude'] = item.location.coordinate.latitude;\n cleaned['longitude'] = item.location.coordinate.longitude;\n cleaned['rating_img_url'] = item.rating_img_url;\n cleaned['display_phone'] = item.display_phone;\n cleaned['review_count'] = item.review_count;\n cleaned['url'] = item.url;\n cleaned['distance'] = (item.distance / 1609.34).toFixed(2) + ' miles away from the middle';\n\n list.push(cleaned);\n });\n\n // Set up the ListView\n var listView = el.querySelector(\".itemlist\").winControl;\n ui.setOptions(listView, {\n itemDataSource: list.dataSource,\n itemTemplate: el.querySelector(\".itemtemplate\"),\n layout: new ui.ListLayout(),\n oniteminvoked: itemInvoked\n });\n\n\n function itemInvoked(e) {\n\n var i = e.detail.itemIndex;\n\n // win-item\n var item = $(listView.element).find('.win-item')[i];\n\n var latitude = $(item).find('.lat').val();\n var longitude = $(item).find('.long').val();\n var title = $(item).find('.title').val();\n var address = jQuery.trim($(item).find('.address').val());\n var city_state = jQuery.trim($(item).find('.city_state').val());\n var url_address = jQuery.trim($(item).find('.url_address').val());\n var url = $(item).find('.url').val();\n var photo = $(item).find('.photo').val();\n var ratingimage = $(item).find('.ratingimage').val();\n var reviews = $(item).find('.reviews').val();\n var phone = $(item).find('.phone').val();\n\n current = {\n latitude: latitude,\n longitude: longitude,\n title: title,\n address: address,\n url_address: url_address,\n city_state: city_state,\n url: url,\n photo: photo,\n ratingimage: ratingimage,\n reviews: reviews,\n phone: phone,\n key: key\n };\n\n showCurrentInfoBox();\n }\n\n }\n\n // handles a failed yelp response\n function failure(result) {\n debug(result.responseText);\n }\n }",
"function populateSitesOnMap() {\n\tclearMap();\n $.when(loadSites()).done(function(results) {\n for (var s in sites) {\n var marker = new google.maps.Marker({\n position: new google.maps.LatLng(sites[s].location.x, sites[s].location.y),\n map: map,\n // label: \"A\",\n icon: {url: 'http://maps.gstatic.com/mapfiles/markers2/marker.png'},\n //animation: google.maps.Animation.DROP,\n title: sites[s].name\n });\n\n markers.push(marker);\n marker.setMap(map);\n bindInfoWindow(marker, map, infowindow, sites[s]);\n }\n });\n}",
"function updatePlacesLocationInformation() {\n\tupdatePlacesLocationInformationFromCategory(\"\", \"All Categories\");\n}",
"function generateCharts () {\n\tgenerateTemperatureChart();\n\tgenerateQPFChart();\n\tgenerateDailyWeatherChart($('#weatherChartDays'), 1, 7); //Also reused by zone available water\n\tgenerateProgramsChart();\n\tbindChartsSyncToolTipEvents();\n}",
"function sortLocations() {\n if (settings.offline) {\n //Use local locations\n if (!$scope.origin) return;\n $scope.locations = cqLocationService.sort($scope.origin);\n $scope.$apply();\n } else {\n //Fetch locations from server\n if (cqDeviceUtils.isConnected()) {\n var options = {};\n if ($scope.origin) {\n options.data = {lat: $scope.origin.lat, lng: $scope.origin.lng};\n } else if ($scope.query) {\n options.data = {q: $scope.query};\n }\n if (!options.data) return;\n cqLocationService.fetch(settings.locationURI, options.data)\n .then(function(data) {\n if (data.origin) {\n $scope.origin = data.origin.coordinates;\n }\n $scope.locations = cqLocationService.locations();\n });\n } else {\n toaster.pop(\"No connection\");\n }\n }\n }",
"function loadPointTimeSeries(measurements, locations, callback) {\n\n // Read and transform measurements\n var stats = new Set();\n d3.tsv(measurements, function(d) {\n stats.add(d.stat);\n d.var = parseFloat(d.var);\n d.t = new Date(d.time);\n d.time = d.t.valueOf();\n return d;\n }, function(data) {\n\n // Group measurements by time stamp\n var groupsByTimestamp = d3.nest()\n .key(function(d) { return d.time; })\n .entries(data);\n\n // Transform locations\n d3.tsv(locations, function(d) {\n return { stat: d.stat, x: +d.x, y: +d.y, z: +d.z };\n }, function(locs) {\n\n // Organize locations by names\n var locsObj = locs.reduce(function(p, c) {\n p[c.stat] = c;\n return p;\n }, {});\n\n // Avoid gaps in the table\n var data = groupsByTimestamp.map(function(e) {\n var measObj = e.values.reduce(function(p, c) {\n p[c.stat] = c;\n return p;\n }, {});\n var rec = [];\n stats.forEach(function(s) {\n var loc = locsObj[s];\n var meas = measObj[s];\n rec.push({ stat: s, x: loc.x, y: loc.y, z: loc.z, v0: meas ? meas.var : Number.NaN, t: e.key });\n });\n return rec;\n });\n \n // Return the data\n callback(data);\n });\n });\n \n }",
"function addVolunteersCountryMap(number_of_users_per_country) {\n var number_of_users_per_country_data = []\n var MIN = 1000000;\n var MAX = -1;\n \n for(var i=0;i<number_of_users_per_country.rows.length;i++){\n var c = number_of_users_per_country.rows[i]\n var data_point = {}\n if(country_code_map[c[0].replace(\"&\",\"&\")] !== undefined){\n data_point[\"hc-key\"] = country_code_map[c[0].replace(\"&\",\"&\")].toLowerCase()\n data_point[\"value\"] = parseInt(c[1])\n if(parseInt(c[1]) > MAX) {\n MAX = parseInt(c[1]);\n };\n \n if(parseInt(c[1]) < MIN) {;\n MIN = parseInt(c[1]);\n }\n number_of_users_per_country_data.push(data_point);\n }else {\n console.log(\"Wrong mapping: \" + c[0]);\n }\n }\n\n\n // Initiate the chart\n $('#map').highcharts('Map', {\n\n title : {\n text : ''\n },\n mapNavigation: {\n enabled: true,\n enableMouseWheelZoom: false,\n buttonOptions: {\n verticalAlign: 'bottom',\n align: \"right\"\n }\n },\n\n colorAxis: {\n min: MIN,\n max: MAX\n },\n\n\n series : [{\n data : number_of_users_per_country_data,\n mapData: Highcharts.maps['custom/world'],\n joinBy: 'hc-key',\n name: 'Total Volunteers',\n states: {\n hover: {\n color: '#BADA55'\n }\n },\n dataLabels: {\n enabled: false,\n format: '{point.name}'\n }\n }],\n credits: {\n enabled: true\n } \n }).unbind(document.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel');\n}",
"function CreateRegionCharts(region, title) {\n $.getJSON(\"crimes/6-2013/\" + region + \"/json\", function(data) {\n \n // Raw data\n $(\"#searchRegionData\").html(JSON.stringify(data, null,4));\n \n var crimeData = null;\n \n // Need to check for Further Stats, else we treat it as normal\n if (region === \"Action_Fraud\" || region === \"British_Transport_Police\") {\n var fStatsArray = new Array(data.response.crimes.national);\n crimeData = fStatsArray;\n }\n else {\n crimeData = data.response.crimes.region.areas;\n }\n \n // Loop through adding it to the table\n $.each(crimeData, function() {\n $(\"#searchRegionTable tr:last\").after(\"<tr><td>\" + this.id + \"</td><td>\" + this.total + \"</td></tr>\");\n });\n \n // Creates the region serach charts\n CreateCharts(\n crimeData,\n document.getElementById(\"region-chart-pie\"),\n document.getElementById(\"region-chart-bar\"),\n title,\n \"Region Name\",\n \"Total Including Fraud\");\n }).fail(function(data){\n alert(\"Error Occured. Failed to search for data\");\n });\n}",
"function updateDatapoints() {\n\t\t//remove all markers from the map in order to be able to do a refresh\n\t\tmarkers.clearLayers();\n\t\tmarkers_list = {};\n\t\t//for every datapoint\n\t\tbyId.top(Infinity).forEach(function(p, i) {\n\t\t\t//create a marker at that specific position\n\t\t\tvar marker = L.circleMarker([p.latitude,p.longitude]);\n\t\t\tmarker.setStyle({fillOpacity: 0.5,fillColor:'#0033ff'});\n\t\t\t//add the marker to the map\n\t\t\tmarkers.addLayer(marker);\n\t\t});\n\t}",
"async function populateAllLocations(url){\n let response;\n let nextPage='/locations?page=22&perPage=1000';\n \n do{\n let locationIds = [];\n console.log(\"Fetching remote data: \", url+nextPage)\n response = await axios.get(url+nextPage);\n nextPage = response.data.nextPageUri;\n \n for (let i=0, len=response.data.locations.length; i<len; i++){\n locationIds.push(response.data.locations[i].locationId)\n }\n \n let locations = await getIndividualLocations(locationIds);\n \n for (let i=0, len=locations.length; i<len; i++){\n await models.location.create({\n locationid:locations[i].locationId,\n locationname: locations[i].name,\n addressline1: locations[i].postalAddressLine1,\n addressline2: locations[i].postalAddressLine2,\n towncity: locations[i].postalAddressTownCity,\n county: locations[i].postalAddressCounty,\n postalcode: locations[i].postalCode,\n mainservice: (locations[i].gacServiceTypes.length>0) ? locations[i].gacServiceTypes[0].name : null\n })\n }\n } while (nextPage != null);\n }",
"async refresh() {\n this.locations = await this.getLocations();\n this.weatherModels = [];\n\n if (this.locations.length > 0) {\n document.getElementById('no-locations').style.display = 'none';\n }\n\n _util.default.displayLoading(true);\n\n if (this.locations.length) {\n _util.default.clearDivContents('weather');\n\n for (let i = 0; i < this.locations.length; i++) {\n if (this.locations[i]) {\n let model = new WeatherModel(this.locations[i].lat, this.locations[i].lng, i, this.locations[i].full_name);\n await model.init();\n new WeatherView(model).render();\n this.weatherModels.push(model);\n }\n }\n\n this.updateLastUpdated();\n }\n\n _util.default.displayLoading(false);\n }",
"function appendLocations(entriesID) {\n\t\t\t\tmyData.forEach(function(tile) {\n\t\t\t\t\tif (tile.hasOwnProperty(entriesID)) {\n\t\t\t\t\t\ttile[entriesID].forEach(function(entry) {\n\t\t\t\t\t\t\tif (entry.hasOwnProperty('location')) {\n\t\t\t\t\t\t\t\tlocations.push(entry.location);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}",
"function initMap() {\n $('#widgetRealTimeMapliveMap .loadingPiwik, .RealTimeMap .loadingPiwik').hide();\n map.addLayer(currentMap.length == 3 ? 'context' : 'countries', {\n styles: {\n fill: colorTheme[currentTheme].fill,\n stroke: colorTheme[currentTheme].bg,\n 'stroke-width': 0.2\n },\n click: function (d, p, evt) {\n evt.stopPropagation();\n if (currentMap.length == 2){ // zoom to country\n updateMap(d.iso);\n } else if (currentMap != 'world') { // zoom out if zoomed in\n updateMap('world');\n } else { // or zoom to continent view otherwise\n updateMap(UserCountryMap.ISO3toCONT[d.iso]);\n }\n },\n title: function (d) {\n // return the country name for educational purpose\n return d.name;\n }\n });\n if (currentMap.length == 3){\n map.addLayer('regions', {\n styles: {\n stroke: colors['region-stroke-color']\n }\n });\n }\n var lastVisitId = -1,\n lastReport = [];\n refreshVisits(true);\n }",
"function init() {\n\n // reset any previous data\n displayReset();\n\n // read in samples from JSON file\n d3.json(\"data/samples.json\").then((data => {\n\n\n // ********** Dropdown Menu ************// \n\n // Iterate over each name in the names array to populate dropdowns with IDs\n data.names.forEach((name => {\n var option = idSelect.append(\"option\");\n option.text(name);\n })); //end of forEach loop\n\n // get the first ID from the list as a default value for chart\n var initId = idSelect.property(\"value\")\n\n // plot charts with initial ID\n displayCharts(initId);\n\n }));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a testType state object This is the constructor for the state object that will be used to represent the student work. An instance of this object will be created each time the student submits an answer. note: you can change the variables in this constructor, the response variable is just used as an example. you can add any variables that will help you represent the student's work for your step type. | function TestTypeState(response, statestring, gradingHTML ) {
console.log("DEBUG: entered constructor in testTypeState.js");
this.response = "";
this.stateString = "";
this.gradingViewHTML = "<html>test</html>";
if(response != null) {
this.response = response;
}
if(statestring != null) {
this.stateString = statestring;
}
if(gradingHTML != null) {
this.gradingViewHTML = gradingHTML;
}
} | [
"constructor(props) {\n super(props)\n\n const parsedExerciseFormat = parseExerciseFormat(props.exercise.format)\n\n this.state = {\n exercise: props.exercise,\n exerciseStatus: null,\n failedSets: 0,\n passedSets: 0,\n ...parsedExerciseFormat,\n }\n this.startExercise = this.startExercise.bind(this)\n this.passSet = this.passSet.bind(this)\n this.failSet = this.failSet.bind(this)\n this.finishRest = this.finishRest.bind(this)\n // this.setNew5RepMax = this.setNew5RepMax.bind(this)\n }",
"_submitState() {\n let objFields = Object.values(Object.values(this.testObj));\n let stateArr = objFields.map(f => f.state); // Creates array from test object with state boolean values.\n // Checks if the test array includes false, and changes the submit button according to this result.\n this._inputState(this.HTML.submitForm, !stateArr.includes(false), false);\n }",
"function initQuizState( config ) {\n $scope.qzState = $scope.qzStateConfig.qzState;\n $scope.toolbar = $scope.qzStateConfig.toolbar;\n $scope.pgTitle = $scope.qzStateConfig.pgTitle;\n $scope.promptType = $scope.qzStateConfig.promptType;\n $scope.qzLength = $scope.qzStateConfig.qzLength;\n $scope.score = $scope.qzStateConfig.score; //zeros out scores\n $scope.currTrial = 0;\n }",
"function Tsts() {\n this.TSTs = [];\n this.Error = \"\";\n this.Text = \"\";\n this.webResponse = \"\";\n}",
"async function setNewStateForEvalFields(newStudent){\n if (newStudent == null) {\n return;\n } else {\n //assign values of new student to temp variables\n let newUntreatedDecay = newStudent.untreatedDecay;\n let newTreatedDecay = newStudent.treatedDecay ;\n let newTreatmentRecommendationCode = newStudent.treatmentRecommendationCode;\n let newSealantsPresent = newStudent.sealantsPresent;\n let newCannotEvaluate = newStudent.cannotEvaluate;\n let newEvalStatus = newStudent.evalStatus;\n \n\n // set initial values if new student fields are not valid values\n if (newUntreatedDecay == null | newUntreatedDecay == \"\") { newUntreatedDecay= \"No\"; } \n if (newTreatedDecay == null | newTreatedDecay == \"\") { newTreatedDecay = \"No\"; }\n if (newSealantsPresent == null | newSealantsPresent == \"\") { newSealantsPresent = \"No\"; } \n if (newTreatmentRecommendationCode == null | newTreatmentRecommendationCode == \"\") { newTreatmentRecommendationCode = \"Code 1\"; } \n if (newCannotEvaluate == null | newCannotEvaluate == \"\") { newCannotEvaluate = \"NA\"; } \n \n //set new state with initiated or valid values\n states.untreatedDecay = newUntreatedDecay;\n states.treatedDecay = newTreatedDecay;\n states.sealantsPresent = newSealantsPresent;\n states.treatmentRecommendationCode = newTreatmentRecommendationCode;\n states.cannotEvaluate = newCannotEvaluate;\n states.evalStatus = newEvalStatus;\n }\n }",
"function Quest(Type, Name, Level, Experience, Item) {\n function mainQuest() {\n var main = (Type == true) ? \"Main Quest\":\"Side Quest\";\n return main \n }\n this.questType = mainQuest();\n this.questName = Name;\n this.questLevel = Level;\n this.questExperience = Experience;\n this.questItem = Item;\n \n}",
"function setUpTests()\n {\n// var fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response'));\n var fullInteractionData;\n if(app.scorm.scormProcessGetValue('cmi.suspend_data') !== ''){\n fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.suspend_data'));\n }\n else if(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response') !== ''){\n fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response'));\n }\n else{\n console.log('There is a problem with test submission.');\n }\n \n // Inject the CMI DB data into the questionBank on first load\n if (fullInteractionData) {\n $.each(fullInteractionData, function (index, value)\n {\n if (!app.questionBank[index]) {\n app.questionBank[index] = value;\n }\n }); \n }\n \n // Setup the current test's question bank\n if (!app.questionBank[testID]) {\n app.questionBank[testID] = [];\n }\n \n return fullInteractionData;\n }",
"constructor(props)\n {\n super(props);\n this.state = {\n goalsArr: [],\n user: {\n id: \"\",\n token: \"\"\n },\n goal: {\n name: \"\",\n startDate: new Date(),\n endDate: new Date(),\n percentGoal: 0\n },\n goalRes: {\n name: \"\",\n startDate: new Date(),\n endDate: new Date(),\n percentComplete: 0\n },\n update: false,\n unsuccessfulCreate: false\n }\n }",
"function Tester() {\n console.log('Tester: constructor');\n\n // These class variables and methods are for the calling class to go step-by-step through the self-test steps.\n this.currentTestNum = -1;\n this.currentStepNum = -2;\n\n this.currentTestName = function() {\n return this.testArray[this.currentTestNum].name;\n };\n\n // Go on to the next test; return the name, or null if we are done.\n this.getNextTest = function() {\n var retName = null;\n if (++this.currentTestNum < this.testArray.length) {\n retName = this.testArray[this.currentTestNum].name;\n // console.log('getNextSelfTest: moving to ' + retName);\n this.currentStepNum = -2;\n }\n return retName;\n };\n\n // Go on to the next step; return the step object, or null if we are done.\n this.getNextStep = function() {\n var retObj = null;\n var steps = this.testArray[this.currentTestNum].steps;\n this.currentStepNum += 2;\n\n if (this.currentStepNum < steps.length) {\n // console.log('getNextSelfTest: moving to step ' + this.currentStepNum);\n retObj = {input: steps[this.currentStepNum],\n expected: steps[this.currentStepNum + 1]};\n }\n return retObj;\n };\n\n // Reset the test counters.\n this.reset = function() {\n this.currentTestNum = -1;\n this.currentStepNum = -2;\n };\n\n // Data for the self-test routine: as each key is pressed, check that the returned display is correct.\n this.testArray = [\n {name: 'Basic addition', steps: [ // 123 + 456 = 579\n 'C', '0',\n '1', '1',\n '2', '12',\n '3', '123',\n '+', '0',\n '4', '4',\n '5', '45',\n '6', '456',\n '=', '579' ]},\n {name: 'Basic subtraction, decimals', steps: [ // 42.5 - 21.7 = 20.8 (Note: picked to _not_ get floating error).\n 'C', '0',\n '4', '4',\n '2', '42',\n '.', '42.',\n '5', '42.5',\n '-', '0',\n '2', '2',\n '1', '21',\n '.', '21.',\n '7', '21.7',\n '=', '20.8' ]},\n {name: 'Basic multiplication', steps: [ // 72 * 3 = 216\n 'C', '0',\n '7', '7',\n '2', '72',\n 'X', '0',\n '3', '3',\n '=', '216' ]},\n {name: 'Basic division', steps: [ // 56 / 4 =\n 'C', '0',\n '5', '5',\n '6', '56',\n '/', '0',\n '4', '4',\n '=', '14' ]},\n {name: 'Successive operation', steps: [ // 4 + 5 + 6 = 15\n 'C', '0',\n '4', '4',\n '+', '0',\n '5', '5',\n '+', '0',\n '6', '6',\n '=', '15' ]},\n {name: 'Multiple decimals', steps: [ // 1...2 + 2...1 = 3.3\n 'C', '0',\n '1', '1',\n '.', '1.',\n '.', '1.',\n '.', '1.',\n '2', '1.2',\n '+', '0',\n '2', '2',\n '.', '2.',\n '.', '2.',\n '.', '2.',\n '1', '2.1',\n '=', '3.3' ]},\n {name: 'Multiple operator keys', steps: [ // 7 + + + 21 = 28\n 'C', '0',\n '7', '7',\n '+', '0',\n '+', '0',\n '+', '0',\n '2', '2',\n '1', '21',\n '=', '28' ]},\n {name: 'Changing operator key', steps: [ // 4 + / X 9 = 36\n 'C', '0',\n '4', '4',\n '+', '0',\n '/', '0',\n 'X', '0',\n '9', '9',\n '=', '36' ]},\n {name: 'Negative operands', steps: [ // -4 - -9 = 5\n 'C', '0',\n '-', '-',\n '4', '-4',\n '-', '0',\n '-', '-',\n '9', '-9',\n '=', '5' ]},\n {name: 'Division by zero', steps: [ // 1 / 0 = Error, locks calculator\n 'C', '0',\n '1', '1',\n '/', '0',\n '0', '0',\n '=', 'Error',\n '4', 'Locked: Clear',\n 'C', '0' ]},\n {name: 'Successive multi-operation', steps: [ // 1 + 3 / 4 + 10 * 2 = 22\n 'C', '0',\n '1', '1',\n '+', '0',\n '3', '3',\n '/', '0',\n '4', '4',\n '+', '0',\n '1', '1',\n '0', '10',\n 'X', '0',\n '2', '2',\n '=', '22' ]},\n {name: 'Operation repeat', steps: [ // 2 + 5 = = = 17\n 'C', '0',\n '2', '2',\n '+', '0',\n '5', '5',\n '=', '7',\n '=', '12',\n '=', '17' ]},\n {name: 'Premature operator', steps: [ // + X / + 2 * 3 = 6, note that minus becomes negative number.\n 'C', '0',\n '+', '0',\n 'X', '0',\n '/', '0',\n '2', '2',\n 'X', '0',\n '3', '3',\n '=', '6' ]},\n {name: 'Partial operand', steps: [ // 3 * = 9\n 'C', '0',\n '3', '3',\n 'X', '0',\n '=', '9' ]},\n {name: 'Missing operation', steps: [ // 3 = 3\n 'C', '0',\n '3', '3',\n '=', '3',\n 'X', '0',\n '6', '6',\n '=', '18' ]},\n {name: 'Missing operands', steps: [ // = = = =\n 'C', '0',\n '=', '0',\n '=', '0',\n '=', '0',\n '5', '5',\n '/', '0',\n '2', '2',\n '=', '2.5' ]},\n {name: 'Operation rollover', steps: [ // 1 + 1 + = + = 8\n 'C', '0',\n '1', '1',\n '+', '0',\n '1', '1',\n '+', '0',\n '=', '4',\n '+', '0',\n '=', '8' ]},\n {name: 'Clear entry', steps: [ // 5 X 623 CE 12 = 60\n 'C', '0',\n '5', '5',\n 'X', '0',\n '6', '6',\n '2', '62',\n '3', '623',\n 'CE', '0',\n '1', '1',\n '2', '12',\n '=', '60' ]}\n ];\n} // Tester",
"function initSaveWork() {\n // If we can't fetch AssignmentState, that means we are not\n // a Carnap assignment. So we'll just go ahead and create an\n // empty object.\n let as = {};\n try {\n as = JSON.parse(AssignmentState);\n } catch {\n console.log('Unable to parse AssignmentState');\n const dummyAssignmentState = '{\"Saved Work\":{\"saveAs:1.3\":\"Bob\",\"saveAs:1.7\":\"Badly\",\"saveAs:1.5\":\"Show (Q → P)\\\\nP :PR\",\"saveAs:1.4\":[\"-\",\"-\",\"-\",\"F\",\"-\",\"F\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"T\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\"]}}';\n as = JSON.parse(dummyAssignmentState);\n }\n\n // If this is the first time we run on a given assignment page,\n // we need to create as[\"Saved Work\"]\n if (typeof as['Saved Work'] === 'undefined') {\n as['Saved Work'] = {};\n }\n\n function saveWork() {\n // Syntax Checking (not implemented)\n // Translation, and Qualitative Short Answer\n $('[data-carnap-type=translate]',\n '[data-carnap-type=qualitative]',\n '[data-carnap-type=proofchecker]').each(function () {\n const exerciseId = $(this).attr('data-carnap-submission');\n const studentWork = $(this).find('input', 'textarea').val();\n as['Saved Work'][exerciseId] = studentWork;\n });\n\n // Truth Tables\n $('[data-carnap-type=truthtable]').each(function () {\n const exerciseId = $(this).attr('data-carnap-submission');\n as['Saved Work'][exerciseId] = [];\n $(this).find('select').each(function () {\n as['Saved Work'][exerciseId].push($(this).val());\n });\n });\n // Derivations\n $('[data-carnap-type=proofchecker]').each(function () {\n const exerciseId = $(this).attr('data-carnap-submission');\n const studentWork = $(this).find('textarea').val();\n as['Saved Work'][exerciseId] = studentWork;\n });\n // Model Checking\n // Multiple Choice and Numerical\n // Sequent Calculus Problems\n // Gentzen-Prawitz Natural Deduction Problems\n\n console.log(JSON.stringify(as));\n\n // If we can't putArgumentState, that probably means we aren't\n // a Carnap.io assignment.\n try {\n putAssignmentState(JSON.stringify(as));\n } catch {\n console.log('Unable to putArgumentState');\n }\n }\n\n function loadWork() {\n // Syntax Checking (not implemented)\n //\n // Translation and Qualitative Short Answer\n $('[data-carnap-type=translate]',\n '[data-carnap-type=qualitative]').each(function () {\n const exerciseId = $(this).attr('data-carnap-submission');\n if (typeof as['Saved Work'][exerciseId] !== 'undefined') {\n const studentWork = as['Saved Work'][exerciseId];\n $(this).find('input', 'textarea').val(studentWork);\n }\n });\n\n // Truth Tables\n $('[data-carnap-type=truthtable]').each(function () {\n const exerciseId = $(this).attr('data-carnap-submission');\n if (typeof as['Saved Work'][exerciseId] !== 'undefined') {\n $(this).find('select').each(function () {\n const value = as['Saved Work'][exerciseId].shift();\n $(this).val(value);\n });\n }\n });\n // Derivations\n $('[data-carnap-type=proofchecker]').each(function () {\n const exerciseId = $(this).attr('data-carnap-submission');\n if (typeof as['Saved Work'][exerciseId] !== 'undefined') {\n const studentWork = as['Saved Work'][exerciseId];\n $(this).find('textarea').val(studentWork);\n }\n });\n // Model Checking\n // Multiple Choice and Numerical\n // Sequent Calculus Problems\n // Gentzen-Prawitz Natural Deduction Problems\n\n // For debugging\n console.log(as);\n }\n\n loadWork();\n $(window).on('beforeunload', saveWork);\n $(window).on('blur', saveWork);\n}",
"function State(){\n this.max=100;\n this.value = this.max;\n this.stateFlag;\n \n /* This increases the value property of an object of type State\n * @param o object inheriting from State\n * @param inc int the increment to be added\n */\n this.increaseState = function(o, inc)\n {\n if(o.value<o.max)\n o.value+=inc;\n }\n /* This decreases the value property of an object of type State\n * @param o object inheriting from State\n * @param dec int the decrement to be subtracted\n */\n this.decreaseState = function(o, dec)\n {\n if(o.value>0)\n o.value-=dec;\n }\n \n this.checkState=function(o,threshold)\n {\n if(o.value<threshold)\n {\n o.stateFlag=true;\n }else{\n if(o.value>=o.max)\n {\n \n o.stateFlag=false;\n }\n }\n return o.stateFlag;\n }\n }",
"function Course_Output(class_score, artifact_score, slo_score, student_evaluations)\n{\n this.class_score = class_score;\n this.artifact_score = artifact_score;\n this.slo_score = slo_score;\n this.student_evaluations = student_evaluations;\n}",
"function Runner(first,last,lapone,laptwo){\r\n this.firstName = first;\r\n this.lastName = last;\r\n this.lapOne = lapone;\r\n this.lapTwo = laptwo;\r\n this.fullDetails = () => {return this.firstName + \" \" + this.lastName + \" \" + this.lapOne + \" \" + this.lapTwo;}\r\n }",
"function initializeExercise() {\n\t\t\n\t }",
"constructor(props) {\r\n\t\tsuper(props)\r\n\r\n var tripInfo = this.props.tripInfo;\r\n var tripDate = new Date(tripInfo.tripDate);\r\n\r\n this.state = {\r\n city: tripInfo.locationID.city,\r\n country: tripInfo.locationID.country,\r\n tripDate: (tripDate.getMonth() + 1) + \"/\" + tripDate.getDate() + \"/\" + tripDate.getFullYear(),\r\n notes: tripInfo.notes,\r\n donationItem: ( tripInfo.donations && tripInfo.donations.length > 1) ? tripInfo.donations[1].itemName : \"No donation item\",\r\n\t\t donationRating: ( tripInfo.donations && tripInfo.donations.length > 1) ? tripInfo.donations[1].rating : \"No rating\",\r\n privatePost: tripInfo.isPrivate\r\n }\r\n }",
"function initFromTraversalState(self, t) {\n self.aborted = false;\n self.adapter = t.adapter;\n self.body = t.body;\n self.callbackHasBeenCalledAfterAbort = false;\n self.autoHeaders = t.autoHeaders;\n self.contentNegotiation = t.contentNegotiation;\n self.rawPayload = t.rawPayload;\n self.convertResponseToObjectFlag = t.convertResponseToObject;\n self.links = [];\n self.jsonParser = t.jsonParser;\n self.requestModuleInstance = t.requestModuleInstance,\n self.requestOptions = t.requestOptions,\n self.resolveRelativeFlag = t.resolveRelative;\n self.preferEmbedded = t.preferEmbedded;\n self.startUrl = t.startUrl;\n self.templateParameters = t.templateParameters;\n}",
"function Challenges(){\nthis.viewsCompleted = 0;\nthis.organizesCompleted =0;\nthis.greetsCompleted = 0;\nthis.updatesCompleted = 0;\nthis.comparesCompleted =0;\n}",
"constructor(){\n this.started = false;\n this.score = 0;\n this.level = 1;\n this.grid = new Grid();\n this.active = new Block();\n }",
"function sendAnswer(answer) {\n testSendStudent.message = answer.message;\n testSendStudent.ID = answer.ID;\n testSendStudent.dateCreated = answer.dateCreated;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
NOTE: The values at even position need to be squared. For a language with zerobased indices, this will occur at oddlyindexed locations. For instance, in Python, the values at indices 1, 3, 5, etc. should be squared because these are the second, fourth, and sixth positions in the list. For Example: alternateSqSum([11, 12, 13, 14, 15]) // should return 379 Explanation: Elements at indices 0, 2, 4 are 11, 13, 15 and they are at odd positions as 11 is at position 1, 13 is at position 3 and 15 at 5. Elements at indices 1, 3 are 12 and 14 and they are at even position. So we need to add 11, 13, 15 as they are and square of 12 and 14 > 11 + 13 + 15 + 12^2 + 14^2 = 11 + 13 + 15 + 144 + 196 = 379 For empty arrays, result should be 0 (zero) (except for Haskell). | function alternateSqSum(arr){
let newArr = []
// happy coding :D
for(let i = 0;i<arr.length;i++){
if(i%2){
newArr.push(arr[i]**2)
}else{
newArr.push(arr[i])
}
}return newArr.reduce((a,b)=>a+b,0)
} | [
"function sumOfSquares(array){\n let squaresArray=array.map(i=>Math.pow(i,2));\n let sum=squaresArray.reduce((a,b)=>{\n return a+b;\n },0)\n return sum;\n}",
"function sumOfEvenSquares(array) {\n let sum = 0\n\n for (let elem of array) {\n if (isEven(elem)) {\n sum += square(elem)\n }\n }\n\n return sum\n}",
"function squaresSum(n) {\n\tconst a = [];\n\tfor (let i = 1; i <= n; i++) {\n\t\ta.push(Math.pow(i, 2));\n\t}\n\treturn a.reduce((x, i) => x + i);\n}",
"function get_sum(num_spiral) {\n let sum = 0;\n for (let i = 1; i <= (num_spiral + 1) / 2; i++) {\n sum += 16 * i ** 2 - 28 * i + 16;\n }\n return sum - 3;\n}",
"function sumSquareDifference(n) {\n const sum = (total, value) => total += value;\n const values = Array.from(new Array(n), (x, i) => x = i + 1);\n const squareOfSums = values.reduce(sum) ** 2;\n const sumOfSquares = values.map((value) => value ** 2).reduce(sum);\n return squareOfSums - sumOfSquares;\n}",
"function MaximalSquare(strArr) {\n var arr = [];\n\n var i,j;\n //Make string array a 2D array.\n for(i=0;i<strArr.length;i++){\n arr.push(strArr[i].split(\"\"));\n }\n\n var anyOnes = false;\n //Create the DP array/summation table\n\t//Single pass - O(n^2)\n for(i=0;i<arr.length;i++){\n for(j=0;j<arr[i].length;j++){\n arr[i][j] = parseInt(arr[i][j]); //make int first cos it's parsed as a string\n if(arr[i][j]==1) anyOnes = true;\n\n if(i>0) arr[i][j] += arr[i-1][j];\n if(j>0) arr[i][j] += arr[i][j-1];\n if(i>0 && j>0) arr[i][j] -= arr[i-1][j-1]; //avoid double counting\n }\n }\n\n if(!anyOnes) return 0;\n\n mx = 1;\n sm = 0;\n\n\t//Pass over again, with matrix k - O(n^2*k)\n for(i=0;i<arr.length;i++) for(j=0;j<arr[i].length;j++){ //start coord\n for(k=1;k<arr.length;k++){ //size of matrix, skip 1x1 because we know it'll be one unless there are no ones (checked beforehand)\n\t\t\t/* End coordinates */\n end_i = i+k;\n end_j = j+k;\n\t\t\tif(end_i>=arr.length || end_j>=arr[i].length) break;\n\n\t\t\t/* Sum from DP summation array/table */\n sm = arr[end_i][end_j]; //sum from (0,0) to (end_i, end_j) - O(1)\n if(i>0) sm -= arr[i-1][end_j]; //exclude subrect (0,0) to (i-1,end_j) - O(1)\n if(j>0) sm -= arr[end_i][j-1]; //exclude subrect (0,0) to (end_i,j-1) - O(1)\n if(i>0 && j>0) sm += arr[i-1][j-1]; //include back the double counted excluded (0,0) to (i-1,j-1) subrect - O(1)\n //The sum is finally here: sum from (i,j) to (end_i,end_j) - total O(4)\n\n if(sm!=(k+1)*(k+1)) continue;\n\n if(sm>mx){\n mx = sm;\n }\n }\n }\n\n // Return mx. Total O(2*n^2*k*4) = O(8*n^2*k)\n return mx;\n}",
"function sumOfSquares(a , b) {\n var aSquare = square(a)\n var bSquare = square(b)\n return add(aSquare, bSquare)\n}",
"function dynamicProgramming(coins, sum) {\n if (coins.length < 1) return 0\n const table = [...Array(sum + 1)].map(e => Array(coins.length + 1).fill(0))\n // when sum is 0, there's 1 way to fulfil it. simply by doing nothing\n for (let i = 0; i < table[0].length; i++) {\n table[0][i] = 1\n }\n for (let i = 1; i < table.length; i++) {\n for (let j = 1; j < table[i].length; j++) {\n table[i][j] = table[i][j-1]\n if (i - coins[j-1] >= 0) {\n table[i][j] += table[i-coins[j-1]][j]\n }\n }\n }\n console.log(table)\n return table[table.length-1][table[0].length-1]\n}",
"function sumOfPrimeIndices(arr){\n let sumPrime = 0;\n for(let i = 0 ; i< arr.length; i++){\n if(isPrime(i)){\n sumPrime += arr[i];\n }\n\n }\n return sumPrime;\n\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}",
"static length2sq(it) { return (it.x*it.x)+(it.y*it.y); }",
"function multiDimSum(arr) {}",
"function plusOneSum(arr) { \n var sum = arr.length;\n for (var index = 0; index < arr.length; index++) {\n sum += arr[index];\n } \n return sum;\n }",
"function arraySum(array){\n var sum=0;\n var index=0;\n function add(){\n if(index===array.length-1)\n return sum;\n\n sum=sum+array[index];\n index++;\n return add();\n }\n return add();\n}",
"function sumMultiplier(array, targetSum) {\n // initialize variable to avoid mutating original\n let arr = array\n // sort in ascending order\n arr.sort((a, b) => a - b)\n // Initialize start and end index\n let startIndex = 0, endIndex = arr.length - 1\n // Loop through array until target sum is found or all values are evaluated\n while (startIndex < endIndex) {\n const sum = arr[startIndex] + arr[endIndex]\n if (sum === targetSum) {\n return (arr[startIndex] * arr[endIndex])\n } else if (sum > targetSum) {\n endIndex--\n } else {\n startIndex++\n }\n }\n}",
"function sumEvenNumbers(input) {\n let sum = 0 \n for (let i = 0; i < input.length; i += 1) {\n if (input[i] % 2 === 0 && Number.isInteger(input[i])) {\n sum += input[i]\n console.log(sum)\n }\n \n }\n return sum \n}",
"function positiveSum(arr) {\n\n}",
"function sumArray (array) {\n\n var maxSum = Number.NEGATIVE_INFINITY;\n var currSum = 0;\n var preSum = 0;\n for (var i = 0; i < array.length; i++) {\n preSum = currSum;\n currSum = preSum + array[i];\n if (currSum > maxSum) {\n maxSum = currSum;\n }\n if (currSum < 0 && currSum<preSum) {\n currSum = 0;\n }\n }\n return maxSum;\n}",
"function posSum (array) {\r // var sum = 0;\r // for(var i = 0 ; i< array.length ; i++){\r // if(array[i] > 0){\r // sum+= array [i]\r // }\r // }\r // if(i > array.length)\r // return 0;\r // else if(array[i]<0){\r // return 0\r // }\r // else return array[i-1]+posSum(array)\r\r if(array.length===0){\r return 0\r } else { \r var item = array.shift()\r if(item > 0)\r return item+posSum(array)\r else\r return posSum(array)\r }\r\r}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the hash code specific to the current grammar. The hash code is computed based on the four elements of a grammar. | getHashCode()
{
let string = '';
for (const variable of this.getVariables())
{
string += variable + ',';
}
string += '|';
for (const terminal of this.getTerminals())
{
string += terminal + ',';
}
string += '|';
for (const rule of this.getRules())
{
string += rule.toString() + ',';
}
string += '|';
string += this.getStartVariable();
string += '|';
return stringHash(string);
} | [
"getHashCode() {\n let hash = this._m[0] || 0;\n for (let i = 1; i < 16; i++) {\n hash = (hash * 397) ^ (this._m[i] || 0);\n }\n return hash;\n }",
"getHashCode() {\n let hash = this.width || 0;\n hash = (hash * 397) ^ (this.height || 0);\n return hash;\n }",
"hashCode () {\n\n /* x hash code. */\n const xstr = String(this._x);\n const len0 = xstr.length;\n let xhsh = 0;\n for (let i = 0; i < len0; ++i) {\n xhsh = Math.imul(31, xhsh) ^ xstr.charCodeAt(i) | 0;\n }\n xhsh >>>= 0;\n\n /* y hash code. */\n const ystr = String(this._y);\n const len1 = ystr.length;\n let yhsh = 0;\n for (let j = 0; j < len1; ++j) {\n yhsh = Math.imul(31, yhsh) ^ ystr.charCodeAt(j) | 0;\n }\n yhsh >>>= 0;\n\n /* Composite hash code. */\n let hsh = -2128831035;\n hsh = Math.imul(16777619, hsh) ^ xhsh;\n hsh = Math.imul(16777619, hsh) ^ yhsh;\n return hsh;\n }",
"get hashId()\n\t{\n\t\t//this.id;\n\t\t//this.recurrenceId;\n\t\t//this.calendar;\n\t\treturn this._calEvent.hashId;\n\n/*\t\t this._hashId = [encodeURIComponent(this.id),\n\t\t\tthis.recurrenceId ? this.recurrenceId.getInTimezone(exchGlobalFunctions.ecUTC()).icalString : \"\",\n\t\t\tthis.calendar ? encodeURIComponent(this.calendar.id) : \"\"].join(\"#\");\n\n\t\t//dump(\"get hashId: title:\"+this.title+\", value:\"+this._hashId);\n\t\treturn this._hashId;*/\n\t}",
"inputHash(input) {\n return \"\";\n }",
"function structuralHash(term) {\n\n // The outer function does not take an environment.\n // Start recursing with an empty environment.\n return innerStructuralHash(term, Map());\n\n /**\n * An inner helper function that propagates an environment downward\n */\n function innerStructuralHash(term, env) {\n\n if (term.tag === \"bundle\") {\n return innerStructuralHash(term.proc, env);\n }\n\n // Hash of each AST is constructed from its tag and the \"rest\"\n // Rest depends on what type of AST we have.\n let rest;\n\n switch (term.tag) {\n\n case \"ground\":\n // Instantiated unforgeables are equivalent iff they have same randomState\n // See case \"new\" for internally-bound unforgeables.\n rest = qdHash(term.type) ^ qdHash(term.value);\n break;\n\n case \"send*\":\n throw \"hashing send* not yet implemented\";\n\n case \"send\":\n rest = innerStructuralHash(term.chan, env) ^ (innerStructuralHash(term.message, env) << 2);\n break;\n\n case \"join\":\n // Consider the continuation for proper joins (not join*s)\n // Merge this join's environment, shadowing as necessary\n rest = innerStructuralHash(term.body, env.merge(term.environment));\n // No break, so fall thorugh to remaining behavior that also applies to join*\n\n case \"join*\":\n //TODO This is broken. If listening on the same channel twice,\n // their hashes will cancel out. Bit-shifting isn't a great solution either\n // because then commutativity is lost. Normalization (link above)\n for (let action of term.actions) {\n rest ^= innerStructuralHash(action.chan, env) ^ innerStructuralHash(action.pattern, env);\n }\n\n break;\n\n case \"par\":\n throw \"hashing par not yet implemented\";\n\n case \"new\":\n // Bound unforgeables are inside. Rather than implementing additional logic\n // to do debruijn indices or maintain a map, Can we somehow start it with a\n // standard random State so that it will always hash the same.\n throw \"hashing new not yet implemented\";\n\n // Patterns need not be evaluated\n // Actually, why did this ever come up\n case \"variableP\":\n rest = 0;\n break;\n\n case \"variable\":\n // A variable always points to a fully concrete term,\n // so the environment we pass is irrelevant\n rest = innerStructuralHash(env.get(term.givenName), Map());\n break;\n\n default:\n throw \"Non-exhaustive pattern match in structuralHash: \" + term.tag;\n }\n\n return (qdHash(term.tag) ^ rest);\n }\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}",
"static async hash(data) {\n if (! (\"subtle\" in window.crypto)) {\n return undefined;\n }\n\n let input = new TextEncoder().encode(data);\n let hash = await window.crypto.subtle.digest(\"SHA-512\", input);\n let bytes = new Uint8Array(hash);\n\t let hex = Array.from(bytes).map(byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\n\t return hex.slice(0, 32);\n }",
"function hash52 (str) {\n var prime = fnv_constants[52].prime,\n hash = fnv_constants[52].offset,\n mask = fnv_constants[52].mask;\n\n for (var i = 0; i < str.length; i++) {\n hash ^= Math.pow(str.charCodeAt(i), 2);\n hash *= prime;\n }\n\n return new FnvHash(bn(hash).and(mask), 52);\n }",
"function qnHash() {\n var out = {};\n quiz.getCurrentLecture().questions.map(function (qn) {\n out[qn.uri] = {\"chosen\": qn.chosen, \"correct\": qn.correct};\n });\n return out;\n }",
"function getHashDifficulty(hash) {\n let difficulty = 0\n\n for (let i = 0; i < hash.length; i++) {\n if (hash[i] === 0) {\n difficulty += 8\n continue\n } else if (hash[i] === 1) {\n difficulty += 7\n } else if (hash[i] < 4) {\n difficulty += 6\n } else if (hash[i] < 8) {\n difficulty += 5\n } else if (hash[i] < 16) {\n difficulty += 4\n } else if (hash[i] < 32) {\n difficulty += 3\n } else if (hash[i] < 64) {\n difficulty += 2\n } else if (hash[i] < 128) {\n difficulty += 1\n }\n break\n }\n\n return difficulty\n}",
"hashFuncUnicodeKeyType(key){\n let hashValue = 0;\n const keyValueString = `${key}${typeof key}`;\n for ( let index = 0; index < keyValueString.length; index++){\n const keyCodeChar = keyValueString.charCodeAt(index);\n hashValue += keyCodeChar << (index * 8);\n }\n return hashValue;\n }",
"@computed get uniqueKey(): string {\n const hash = this.block == null ? 'undefined' : this.block.Hash;\n return `${this.txid}-${this.state}-${hash}`;\n }",
"function NewHash() {\n return blakejs_1[\"default\"].blake2bInit(32, null);\n}",
"function getHash(ctx) {\n\tif (DEBUG) {\n\t\treturn '';\n\t}\n\n\tconst paths = getEntryBundlesFromManifest(ctx);\n\n\treturn `${getHashPart(paths.app)}${getHashPart(paths.vendor)}${getHashPart(paths.runtime)}`;\n}",
"function hashFnDef( fn ) {\n\n return fn.toString(); // todo: actually hash this\n\n}",
"function hash(text) {\n return crypto.createHash('md5').update(text).digest('hex')\n}",
"static getHash(block){\r\n const {timestamp, lastHash, data, nonce} = block;\r\n return this.createHash(data, timestamp, lastHash, nonce, difficulty);\r\n }",
"function hashMessage(message, algorithm) {\n const hash = crypto.createHash(algorithm);\n hash.update(message);\n const hashValue = hash.digest('hex')\n console.log(hashValue);\n return hashValue;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clear the range from character start to before end. | function clearRange(value, start, end) {
return value.substring(0, start) + value.substring(end);
} | [
"function clear(array, start, stop) {\n if (start === void 0) { start = 0; }\n updateRange(array, null, start, stop);\n}",
"clearSelections () {\n this.editor.setCursorBufferPosition(this.editor.getCursorBufferPosition())\n }",
"clearSelect() {\n const [selection] = this.cm.getDoc().listSelections();\n\n if (selection) {\n this.cm.setCursor(selection.to());\n }\n }",
"function resetCursorPos(element) {\n element.selectionStart = 0;\n element.selectionEnd = 0;\n }",
"function range(start, len){\n var arr = [],\n i = start;\n\n if (i < start + len){\n while(i < start + len){\n arr.push(String.fromCharCode(i));\n i++;\n }\n return arr.join('');\n }\n else return '';\n}",
"function remove(keyCode) {\n var state = getState();\n if (keyCode === DELETE_KEYCODE && state.selection.start === state.selection.end &&\n\tstate.value.charAt(state.selection.start) === ',') {\n state.selection.start ++;\n state.selection.end ++;\n }\n removeExtraStuff(state);\n if (state.selection.start !== state.selection.end) {\n state.value = clearRange(state.value, state.selection.start, state.selection.end);\n } else if (keyCode === BACKSPACE_KEYCODE) {\n state.value = clearRange(state.value, state.selection.start - 1, state.selection.start);\n } else if (keyCode === DELETE_KEYCODE) {\n state.value = clearRange(state.value, state.selection.start, state.selection.start + 1);\n }\n var moveRight = state.selection.start === state.selection.end && keyCode === DELETE_KEYCODE;\n addExtraStuff(state, moveRight);\n setState(state);\n }",
"slice(startToken, endToken = undefined) {\n const { start, end } = this.getRange(startToken, endToken);\n return this.cssText.substring(start, end);\n }",
"range(start, end) {\n return new vscode.Range(start, end);\n }",
"function delete_function() {\r\n\tvar delete_end_char = textarea_element.selectionEnd;\r\n\tif (delete_end_char < textarea_element.value.length && delete_end_char == textarea_element.selectionStart) {\r\n\t\tdelete_end_char++;\r\n\t}\r\n\ttextarea_element.setRangeText(\"\", textarea_element.selectionStart, delete_end_char, \"end\");\r\n\ttextarea_element.focus();\r\n\tscroll_to_cursor();\r\n\tupdate_printable_table(); \r\n}",
"function clearAllSelection(){\n ds.clearSelection();\n arrDisp.length=0;\n updateSelDisplay();\n updateCurrSelection('','','startIndex',0);\n updateCurrSelection('','','endIndex',0);\n}",
"function clearInput()\n\t\t{\n\t\t\twindow.setTimeout(function()\n\t\t\t{\n\t\t\t\ttextInput.innerHTML = ' ';\n\t\t\t\ttextInput.focus();\n\t\t\t\tdocument.execCommand('selectAll', false, null);\n\t\t\t}, 0);\n\t\t}",
"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 }",
"function erase() {\n\tif (eachLetter >= 0) {\n var str=openTo[adding].toString().substring(0, eachLetter);\n document.getElementById(\"demo\").innerHTML = str;\n eachLetter--;\n setTimeout(erase, speed-25);\n } else {\n adding++;\n if(adding>=openTo.length) \n adding=0;\n setTimeout(typingTexts, speed);\n }\n}",
"function moveCursorToEnd (el) {\r\n\r\n\t// Move to the end of the element\r\n\tel.setSelectionRange(0, el.value.length);\r\n\tel.focus();\r\n\t\r\n}",
"function removeVals(arr,start,end) {\n var temp=end-1;\n arr.splice(start,temp);\n return arr;\n }",
"range(endToken, // last token of the range, inclusive\n text) // the text of the newly constructed token\n {\n return new Token(text, SourceLocation.range(this, endToken));\n }",
"function omitLines(input, start, length) {\n let updated = input.split(\"\\n\");\n updated.splice(start, length);\n return updated.join(\"\\n\");\n}",
"reset() {\n const _ = this;\n _._counter = _._startCount;\n }",
"function spliceChars($, $el, startIndex, deleteCount, ...insertions) {\n let endIndex = startIndex + deleteCount;\n let textNodes = collectTextNodes($, $el);\n\n for (let nodeIdx = 0, charIdx = 0; nodeIdx < textNodes.length && charIdx <= endIndex; nodeIdx++) {\n let $node = textNodes[nodeIdx];\n let nodeText = $node.text();\n if (charIdx <= endIndex && startIndex < charIdx + nodeText.length) {\n // copy any text following the end of the deletion range\n let trailingText = nodeText.slice(startIndex - charIdx + deleteCount);\n if (trailingText) {\n // insert the trailing text\n $node.after(trailingText);\n }\n\n // insert insertions in front of the trailingText\n while (insertions.length) {\n $node.after(insertions.pop());\n }\n\n // copy any text preceding the beginning of the deletion range\n let leadingText = nodeText.slice(0, startIndex - charIdx);\n if (leadingText && startIndex - charIdx > 0) {\n // insert the leading range\n $node.after(leadingText);\n }\n\n // remove the original text node\n let $parent = $node.parent();\n $node.remove();\n // remove empty parent elements (if any)\n while (!$parent.contents().length && !$parent.is($el)) {\n let $grandparent = $parent.parent();\n $parent.remove();\n $parent = $grandparent;\n }\n }\n charIdx += nodeText.length;\n }\n return $el;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Erreur affichee si echec de lecture | function erreur(evt) {
alert("Une erreur est survenue lors de la lecture du fichier.");
} | [
"function incrementoError()\n\t{\n\t\tif(presente === false)\n\t\t{\n\t\t\tmasUnError();//Instanciar la función que aumenta los fallos acumulados.\n\t\t}\n\t}",
"_observeError() {\n this._artikelService.observeError((err) => {\n // zuruecksetzen\n this.waiting = false;\n this.artikel = null;\n if (err === null) {\n this.errorMsg = 'Ein Fehler ist aufgetreten.';\n return;\n }\n if (shared_1.isString(err)) {\n this.errorMsg = err;\n return;\n }\n switch (err) {\n case 404:\n this.errorMsg = 'Keine Artikel gefunden.';\n break;\n default:\n this.errorMsg = 'Ein Fehler ist aufgetreten.';\n break;\n }\n console.log(`SuchErgebnis.errorMsg: ${this.errorMsg}`);\n }, this);\n }",
"function desactiveAfficheErreur(){\n\tvar afficheErreur=document.getElementById('afficheErreur');\n\tafficheErreur.style.display = ' none' ;\t\n}",
"function controleAvantAjout() {\n let UrlOk = controlerUrl();\n let TitreOk = controlerTitre();\n let DateOk = controlerDate();\n if (UrlOk && TitreOk && DateOk) ajouter();\n}",
"function editError(){\n\tdisplayMessage(\"There has been an error submitting your art.\\nSave your work locally and try again later.\",\n\t\t removePrompt(),removePrompt(),false,false);\n}",
"formNotOK() {\n alert(\"verifiez les champs en rouge\");\n }",
"function mensajeVacio(){\n return \"Campos obligatorios\";\n }",
"function ecranJeu() {\n\n\tcouleurFond(couleurfondCarte, 0, 0, largeurCanvas, hauteurCanvas); // appel de la fonction qui colorie le fond dans jeu.js\n\n\tajouteTexte(titreJeu, hauteurTitre1, 0, hauteurTitre1);\n\n\tbulleTexte(titreInventaire, tailleTuile*2, hauteurCanvas);\n\n}",
"function displayError(res) {\n if (res !== false) {\n var ok = res[0];\n var line = res[1];\n var err = res[2];\n if (!ok) {\n marker = editor.getSession().\n highlightLines(Math.max(0, line - 1),\n Math.max(0, line - 1));\n $(\"#editor-log\").html(\"Line \" + res[1] + \", \" + res[2]);\n // $(\"#editor-submit\").prop(\"disabled\", true);\n }\n else {\n $(\"#editor-log\").html(\"\");\n // $(\"#editor-submit\").prop(\"disabled\", false);\n }\n }\n }",
"function erro(msg) {\r\n regErro.setValue(msg);\r\n}",
"function errorConfirm() {\n vm.onErrorConfirm();\n }",
"function CambiarVolumen(accion, amplio){\n\tEjecutarAjax(CambiarVolumenError, {\"accion\": accion, \"amplio\": amplio}, CambiarVolumenOk);\n}",
"function LibererPourTransfererPatient(id_demande_hospi){\n\t\t \n\t var tooltips = $(\"#medicament, #voie_administration, #frequence, #dosage, #date_application, #heure_recommandee_, #duree\").tooltip();\n\t tooltips.tooltip( \"close\" );\n\t $(\"#medicament, #voie_administration, #frequence, #dosage, #date_application, #heure_recommandee_, #duree\").attr({'title':''});\n\t \t\n\t \t$(\"#medicament, #voie_administration, #frequence, #dosage, #date_application, #heure_recommandee_, #duree\").css(\"border-color\",\"\");\n\t \t$(\"#medicament, #voie_administration, #frequence, #dosage, #date_application, #heure_recommandee_, #duree\").val('');\n\t \t\t\n\t \tLaDuree = 0;\n\t //POUR LA SUPPRESSION DES ELEMENTS SELECTIONNES SUR LA LISTE\n\t for(var j = 0; j < 24; j++){\n\t \t$('.SlectBox')[0].sumo.unSelectItem(j);\n\t }\n\t //POUR LA SUPPRESSION DES ICONES COCHES SUR LA LISTE\n\t $(function(){\n\t $('select.SlectBox')[0].sumo.unload();\n\t $('.SlectBox').SumoSelect({ csvDispCount: 6 });\n\t });\n\t\t \n\t\t \n\t\tvar id_cons = $(\"#\"+id_demande_hospi).val();\n \tvar id_personne = $(\"#\"+id_demande_hospi+\"idPers\").val();\n \tvar chemin = tabUrl[0]+'public/consultation/info-patient';\n $.ajax({\n type: 'POST',\n url: chemin ,\n data:{'id_personne':id_personne, 'id_cons':id_cons, 'encours':111, 'terminer':111, 'id_demande_hospi':id_demande_hospi},\n success: function(data) {\n \tvar result = jQuery.parseJSON(data);\n \t$(\"#hospitaliser\").fadeOut(function(){\n \t\t$(\"#titre\").html(\"<iS style='font-size: 25px;'>¤</iS> LIBERATION DU PATIENT <i>(Transfert)</i>\");\n \t\t$(\"#vue_liberer_patient\").html(result).fadeIn(0); \n \t$(\"#terminerLiberer\").replaceWith(\"<button id='terminerLiberer2'>Annuler</button>\");\n \t$(\"#liberer\").replaceWith(\"<button type='submit' id='liberer' style='' >Transférer</button>\");\n \t$(\"#motif_sorti\").val(\"Transfert: \"+$(\"#motif_transfert\").val());\n \t$(\"#id_cons\").val(id_cons);\n \t$(\"#temoin_transfert\").val($(\"#service_accueil\").val()); //C'est la valeur du service car le patient est transferer dans un service\n \t\n \t\n \t$(\"#terminerLiberer2\").click(function(){\n \t \t$(\"#titre\").html(\"<iS style='font-size: 25px;'>¤</iS> ADMINISTRER DES SOINS\");\n \t\t\n \t\t$(\"#vue_liberer_patient\").fadeOut(function(){\n \t\t\t$(\"#hospitaliser\").toggle(true);\n \t\t}); \n \t \treturn false;\n \t });\n \t\n \t});\n \t\n },\n error:function(e){console.log(e);alert(\"Une erreur interne est survenue!\");},\n dataType: \"html\"\n });\n \n\t }",
"function FailToDisplay(err) {\n console.log(\"Failed to get the stream display\", err);\n }",
"function seleccionar_lapiz() {\n\t\t\therramienta = btn_lapiz.value;\n\t\t}",
"function ajouterBiceps()\n\n {\n mesBiceps += bicepsAjout\n txtMesBiceps.innerHTML = 'vous avez '+mesBiceps\n }",
"function offlineErrorModal(){\n return errorModal(\n _l( 'You appear to be offline. Please check your connection and try again.' ),\n _l( 'Offline?' )\n );\n}",
"validar() { }",
"function masUnAcierto(){\n\taciertosAcumulados++;\n\tdibujar();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save posts to local storage, only saves if called with argument 1 as an array | function savePosts(posts) {
if (Array.isArray(posts)) {
localStorage.setItem("posts", JSON.stringify(posts));
}
return true;
} | [
"function save () {\n\n\tvar title = postTitle.value;\n\tvar content = postContent.value;\n\tvar savedPost = { \"title\": title, \"content\": content };\n\n\tsaving = setInterval( saveItemToLocalStorage, 5000, savedPost, 'savedPost' );\n\n}",
"function save(){\n const a = JSON.stringify(answers);\n localStorage.setItem(\"answers\", a);\n}",
"function saveStorage() {\r\n //acessando a variavel global localStorage, e inserindo o todo para fucar armazenado\r\n //é nessessário transformar em jason pois o localstorage não entende array\r\n localStorage.setItem(\"list_todo\", JSON.stringify(todos));\r\n}",
"save(item){\n //if there is no data\n if(!this.data){\n this.data = [item];\n //create newData to store\n let newData = JSON.stringify(item);\n //pass in newData\n this.storage.set('todos', newData);\n } else {\n //if there is data, then push the new data\n this.data.push(item);\n let newData = JSON.stringify(this.data);\n this.storage.set('todos', newData);\n } // end save item if\n }",
"function saveToDos() {\r\n localStorage.setItem(TODOS_LS, JSON.stringify(toDos))\r\n}",
"archivePost() {\n var post = {};\n\n if(document.getElementById(\"title\").value) {\n post.title = document.getElementById(\"title\").value;\n }\n else {\n post.title = \"Untitled post\";\n }\n\n if(document.getElementById(\"post\").value) {\n post.post = document.getElementById(\"post\").value;\n }\n else {\n post.post = \"\";\n }\n\n /*If the current post was previously loaded, updates it*/\n if (this.loadedPost) {\n this.postArray[this.loadedPost].title = post.title;\n this.postArray[this.loadedPost].post = post.post;\n }\n /*Else, the post is stored as a new one*/\n else{\n post.id = this.postId;\n this.postId = this.postId + 1; // Updates the post ID for the next post to be created\n this.postArray.push(post);\n }\n\n /*Clears the text area*/\n this.clearPost();\n }",
"function saveData() {\n var self = this;\n\n try {\n localStorage.setItem(\n self.data.name,\n JSON.stringify(self.getArrayOfData())\n );\n } catch (e) {\n console.error('Local storage save failed!', e);\n }\n\n }",
"saveToStore() {\n localStorage.setItem(STORAGE.TAG, JSON.stringify(this.list));\n }",
"function getAllPosts(){\n var postsJSONArr = localStorage.getItem(\"post\");\n return JSON.parse(postsJSONArr);\n}",
"saveImagesToLocalStorage(uploadedImages) {\n const partialStorageArray = this.getPartialStorageArray();\n\n uploadedImages.forEach((uplodedImage) => {\n const jsonToSave = JSON.stringify(Object.assign({}, uplodedImage));\n partialStorageArray.push(jsonToSave);\n });\n\n this.localStorage.saveValueToLocalStorage(\n this.storageKey,\n JSON.stringify(partialStorageArray)\n );\n }",
"_store (tasks) {\n this.onListChanged(tasks);\n localStorage.setItem('tasks', JSON.stringify(tasks));\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}",
"function savePost(req, res) {\n shared.verifyPID(req, res, () => {\n const user = db.users[res.locals.userid];\n const post = db.posts.feed[req.params.pid];\n if (!user.saved.includes(post.id)) {\n user.saved.push(post.id);\n db.writeUsers();\n }\n res.send(\"Saved post.\")\n })\n}",
"function saveData() {\n if (hasLocalStorage)\n {\n localStorage.setItem(SAVE_LOCATION, JSON.stringify(books));\n }\n}",
"function saveDuration(number){\r\n durationArray.push(number);\r\n localStorage.setItem(\"durationLocal\", JSON.stringify(durationArray));\r\n}",
"function newPosts(in_posts, filename, callback) {\n fs.readFile(filename, 'utf-8', function(err, input) {\n // JSON object to be saved in the save file\n var save_posts = {};\n var saved_posts = [];\n save_posts.saved_posts = saved_posts;\n if(input) {\n // Concert the data to JSON\n var data = JSON.parse(input);\n // Json object for holding new posts to be tweeted\n var new_posts = {};\n var posts = [];\n new_posts.posts = posts;\n // Find any new posts by comparing the JSON objects\n in_posts.posts.forEach(function(post) {\n var match = false;\n data.saved_posts.forEach(function(data_post) {\n if(post && data_post) {\n if(post.id == data_post.id) {\n // New post found add it to new_posts\n match = true;\n }\n }\n });\n // Every post in the JSON object needs to be saved\n save_posts.saved_posts.push(post);\n // New posts to be Tweeted\n if(!match) {\n new_posts.posts.push(post);\n }\n });\n // Return the callback\n callback(new_posts, save_posts, err);\n }\n else {\n // No data saved, make a new JSON object for saving from the in_posts\n in_posts.posts.forEach(function(post) {\n save_posts.saved_posts.push(post);\n });\n callback(in_posts, save_posts, err);\n }\n });\n}",
"function saveStoredThings(){\n localStorage.setItem('fronter_fixes_links', links);\n}",
"function saveData(cityName) {\n\n //clear the previously generated buttons\n $(\"#previous-searches\").empty();\n\n cityNameArr = JSON.parse(localStorage.getItem(\"city_name\"));\n cityNameArr.push(cityName);\n localStorage.setItem(\"city_name\", JSON.stringify(cityNameArr));\n for (i = 0; i < cityNameArr.length; i++) {\n saveCity(cityNameArr[i]);\n }\n\n}",
"function addActivityLocalStorage(activity) {\n let activities;\n activities = getActivitiesLocalStorage();\n\n //Aggregate new tweet\n activities.push(activity);\n\n //Convert string to array\n localStorage.setItem(\"activities\", JSON.stringify(activities));\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r2owebviewback Directive Its an attribute directive. When this directive is used as an attribute to an element, the click on the element makes the webview go back | function r2oWebviewBack(){
return {
restrict : "A",
link: function(scope, element, attrs){
element.on('click', function(){
window.shopWebViewOverlay.goBack();
});
}
};
} | [
"get backButton() {return browser.element(\"//android.widget.FrameLayout/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup[1]\");}",
"backButtonClicked(){\n // get back to the previous page on the app-main navigator stack\n $('#app-main-navigator').get(0).popPage();\n }",
"_goBack(){\n this._backCallback();\n }",
"function OLiframeBack(){\r\n if(parent==self){\r\n alert('This feature is only for iframe content');\r\n return;\r\n }\r\n history.back();\r\n}",
"function clickHandlerBack(e) {\n e.preventDefault();\n console.log(\"Back to Listings button in MomViewDrvProfile clicked\");\n sessionStorage.removeItem(\"driverCardId\");\n history.push('/drvList');\n }",
"goBack(){\n BusinessActions.goBack();\n }",
"renderBackButton () {\n\t\tconst { t } = this.props;\n\t\tif (!Keystone.backUrl) return null;\n\n\t\treturn (\n\t\t\t<PrimaryNavItem\n\t\t\t\tlabel=\"octicon-device-desktop\"\n\t\t\t\thref={Keystone.backUrl}\n\t\t\t\ttitle={t('frontPage') + this.props.brand}\n\t\t\t>\n\t\t\t\t<span className=\"octicon octicon-device-desktop\" />\n\t\t\t</PrimaryNavItem>\n\t\t);\n\t}",
"handleBack(event) {\n console.log('inside handleBack');\n this.dispatchEvent(new CustomEvent('btnclick', {detail: {eventName: 'Search'}}));\n }",
"canGoBack () {\n cc.logID(7801);\n return true;\n }",
"function adelante() {\r\n history.forward();\r\n}",
"function back_button(){\n\t//back to home button's clicks and interaction\n\t\tvar back_button = $(\"<button type='button'>Back to Home</button>\")\n\t\tback_button.addClass(\"btn btn-secondary\")\n\t\t$('#back-to-home').append(back_button)\n\t\t\tback_button.click(function(){\n\t\t\twindow.location.href = \"/\"\n\t\t})\n}",
"function simulateBackClick() {\n backClickEvent = OverlayHelpers.createBackClickEvent();\n LiveUnit.Assert.isFalse(backClickEvent._winRTBackPressedEvent.handled);\n WinJS.Application.queueEvent(backClickEvent); // Fire the \"backclick\" event from WinJS.Application \n\n WinJS.Application.addEventListener(\"verification\", verify, true);\n WinJS.Application.queueEvent({ type: 'verification' });\n }",
"goBack() {\n sessionStorage.setItem(\"feedsub\",false)\n this.setState({\n feedSub:false\n })\n }",
"viewWasClicked (view) {\n\t\t\n\t}",
"function showBackBt() {\n if (_historyObj.length > 1) {\n return true;\n } else {\n return false;\n }\n }",
"function goBack() {\n if (pageStack.slice(-1)[0] === 'persons-list') {\n clearPersonList();\n }\n\n window.location.hash = pageStack.slice(-2)[0];\n pageStack = pageStack.slice(0, pageStack.length - 2);\n checkPageNav();\n}",
"setBackButtonText(text) {\n this._backText = text;\n }",
"function goBack() {\n pop();\n\n if(typeof last() === 'undefined') {\n return;\n }\n var previousView = last();\n $state.go(previousView);\n }",
"get meetingOne_ResultTab_FullReplayButton() {return browser.element(\"//android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup/android.widget.Button[1]\");}",
"function textBackwardButton() {\n\treturn (\n\t\t`<button class='mainPageButton' onclick='mainPage(); img='images/back.png'></button>`\n\t);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParsertableview_name. | visitTableview_name(ctx) {
return this.visitChildren(ctx);
} | [
"visitContainer_tableview_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSelected_tableview(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitCreate_view(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitObject_view_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"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}",
"function onViewType(e)\n{\n\tvar viewtype = $F($('viewtype')); // 0: autodetect, 1:table;\n\tclickTree(oidview._oid, oidview._idx, viewtype, column_names);\n}",
"visitAlter_view(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function STLangVisitor() {\n STLangParserVisitor.call(this);\n this.result = {\n \"valid\": true,\n \"error\": null,\n \"tree\": {\n \"text\": \"\",\n \"children\": null\n }\n };\n\treturn this;\n}",
"visitAlter_view_editionable(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitProcedure_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitCreate_materialized_view(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSelected_list(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitView_options(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSubpartition_template(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSubpartition_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitAugassign(ctx) {\r\n console.log(\"visitAugassign\");\r\n return this.visit(ctx.getChild(0).getText());\r\n }",
"visitCreate_materialized_view_log(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitAlter_materialized_view(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitImport_name(ctx) {\r\n console.log(\"visitImport_name\");\r\n return {\r\n type: \"ImportName\",\r\n imported: this.visit(ctx.dotted_as_names()),\r\n };\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to filter shape | function filterShape(aliens) {
return aliens.shape == $shapeInput.value.trim().toLowerCase();
} | [
"function filterByHairColor(arr, hairColor) {\n}",
"function doFilter() {\n var output;\n var imageEl = document.getElementById('sourceimg');\n\n var tmpcanvas = document.createElement('canvas');\n tmpcanvas.width = 100;\n tmpcanvas.height = 100;\n \n var tmpctx = tmpcanvas.getContext('2d');\n tmpctx.drawImage(imageEl, 0, 0, 100, 100);\n\n var imageData = tmpctx.getImageData(0, 0, 100, 100);\n\n var intensity = parseFloat(document.getElementById('intensity').value);\n\n switch(this.id) {\n case 'saturate':\n output = saturate(intensity, imageData);\n break;\n case 'brighten':\n output = brighten(intensity, imageData);\n break;\n case 'default':\n console.log('No such filter: '+this.id);\n }\n\n ctx.putImageData(output, 0, 0);\n}",
"function clearFilter(context) { \n // iterate over all the nodes in the graph and show them (unhide)\n var self = context;\n if (self && self.GraphVis) {\n self.GraphVis.showAll(true);\n }\n \n self.GraphVis.gv.fit();\n}",
"filterSubLayer(context) {\n return true;\n }",
"function GaussianFilter(arr, w, h){\n\t\tvar k = 3,\n\t\t\tsigma = 1,\n\t\t\tg_filter = fspecial('gaussian', k, sigma),\n\t\t\td = Math.floor(k/2),\n\t\t\tnewArr = [];\n\n\t\tnewArr = arr;\n\n\t\tfor (var x = d; x < w-d; x++) {\n\t\t\tfor (var y = d; y < h-d; y++) {\n\t\t\t\tvar i = getPixel(x, y, w),\n\t\t\t\t\tiArr = [\n\t\t\t\t\t\t[getPixel(x-1, y-1, w),getPixel(x, y-1, w),getPixel(x+1, y-1, w)],\n\t\t\t\t\t\t[getPixel(x-1, y, w),i,getPixel(x+1, y, w)],\n\t\t\t\t\t\t[getPixel(x-1, y+1, w),getPixel(x, y+1, w),getPixel(x+1, y+1, w)]\n\t\t\t\t\t],\n\t\t\t\t\tr=[],g=[],b=[];\n\t\t\t\tiArr.map(function(a){\n\t\t\t\t\tr.push([]);\n\t\t\t\t\tg.push([]);\n\t\t\t\t\tb.push([]);\n\t\t\t\t\ta.map(function(c){\n\t\t\t\t\t\tr[r.length-1].push(arr[c]);\n\t\t\t\t\t\tg[g.length-1].push(arr[c+1]);\n\t\t\t\t\t\tb[b.length-1].push(arr[c+2]);\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tnewArr[i]=Math.floor(sum(mult(r,g_filter)))%255;\n\t\t\t\tnewArr[i+1]=Math.floor(sum(mult(g,g_filter)))%255;\n\t\t\t\tnewArr[i+2]=Math.floor(sum(mult(b,g_filter)))%255;\n\t\t\t}\n\t\t}\n\t\treturn newArr;\n\t}",
"maskFilter (mask) {\n\t\treturn (el, index) => {\n\t\t\treturn mask[index % mask.length];\n\t\t};\n\t}",
"invertFilter() {\n let canvasID = `canvasID:${this.state.canvasID}`;\n let c = document.getElementById(canvasID);\n\n let ctx = c.getContext(\"2d\");\n let imgData = ctx.getImageData(0, 0, c.width, c.height);\n // invert colors\n var i;\n for (i = 0; i < imgData.data.length; i += 4) {\n imgData.data[i] = 255 - imgData.data[i];\n imgData.data[i + 1] = 255 - imgData.data[i + 1];\n imgData.data[i + 2] = 255 - imgData.data[i + 2];\n imgData.data[i + 3] = 255;\n }\n ctx.putImageData(imgData, 0, 0);\n }",
"filter (p) {\n return filter(p, this)\n }",
"function filterValues(source) {\n var self = this;\n hidden_simulations.sort(d3.ascending);\n var length = hidden_simulations.length;\n\n var filtered = cloneArrayBuffer(source);\n\n for (var i = length - 1; i >= 0; i--) {\n filtered.splice(hidden_simulations[i], 1);\n }\n\n return filtered;\n }",
"function filterChange() {\n Data.Svg.Node.style.filter = getFiltersCss(\n Data.Controls.Brightness.value,\n Data.Controls.Contrast.value,\n Data.Controls.Hue.value,\n Data.Controls.Saturation.value);\n}",
"function FILTER(range) {\n for (var _len7 = arguments.length, filters = Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) {\n filters[_key7 - 1] = arguments[_key7];\n }\n\n // A filter is an array of true/false values.\n // The filter may be for rows or for columns but not both.\n // A array filter may only filter a range that covers a single row or a single column.\n\n function makeFilter() {\n return function (value, index) {\n return filters.reduce(function (previousValue, currentValue) {\n if (previousValue === false) {\n return false;\n } else {\n return currentValue[index];\n }\n }, true);\n };\n }\n\n return range.filter(makeFilter());\n}",
"function apply_sobel_filter(img) {\n img.loadPixels();\n var n = img.width * img.height;\n var sobel_array = new Uint32Array(n);\n\n // compute the gradient in soble_array\n var index;\n var x, y;\n var xk, yk;\n var xGradient, xMultiplier;\n var yGradient, yMultiplier;\n var pixelValue;\n for (x = 1; x < img.width - 1; x++) {\n for (y = 1; y < img.height- 1; y++) {\n i = x + y * img.width;\n xGradient = 0;\n yGradient = 0;\n for (xk = -1; xk <= 1; xk ++) {\n for (yk = -1; yk <= 1; yk ++) {\n pixelValue = img.pixels[4 * ((x + xk) + (y + yk) * img.width)];\n xGradient += pixelValue * xKernel[yk + 1][xk + 1];\n yGradient += pixelValue * yKernel[yk + 1][xk + 1];\n }\n }\n sobel_array[i] = Math.sqrt(\n Math.pow(xGradient, 2) + Math.pow(yGradient, 2)\n );\n }\n }\n\n // copy sobel_array to image pixels;\n for (x = 0; x < img.width; x++) {\n for (y = 0; y < img.height; y++) {\n i = x + y * img.width;\n img.pixels[4 * i] = sobel_array[i];\n img.pixels[4 * i + 1] = sobel_array[i];\n img.pixels[4 * i + 2] = sobel_array[i];\n }\n }\n img.updatePixels();\n}",
"function returnFilteredRectangleOrCircle(rect) {\n if (rect.rx.baseVal.value == 0 && rect.ry.baseVal.value == 0) { // no values that define a radius\n return filterRectangle(rect);\n } else {\n return filterCircle(rect);\n }\n}",
"function blurImage(img){\n return imageMapXY(img, blurPixel);\n}",
"function removeShape() {\n for (var row = 0; row < currentShape.shape.length; row++) {\n for (var col = 0; col < currentShape.shape[row].length; col++) {\n if (currentShape.shape[row][col] !== 0) {\n grid[currentShape.y + row][currentShape.x + col] = 0;\n }\n }\n }\n }",
"function loadFilter() {\n const sepia = document.getElementById('sepia');\n // si existe el elemento sepia entonces ejecuta el JS que aplica el atributo style al elemento\n if (sepia !== null) {\n sepia.setAttribute('style', 'filter: sepia(75%)');\n } else {\n console.log('No existe el elemento sepia');\n }\n \n const blackAndWhite = document.getElementById('blackAndWhite');\n // si existe el elemento blackAndWhite entonces ejecuta el JS que aplica el atributo style al elemento\n if (blackAndWhite !== null) {\n blackAndWhite.setAttribute('style', 'filter: grayscale(100%)');\n } else {\n console.log('No existe el elemento blackAndWhite');\n }\n\n const saturation = document.getElementById('saturation');\n // si existe el elemento saturation entonces ejecuta el JS que aplica el atributo style al elemento\n if (saturation !== null) {\n saturation.setAttribute('style', 'filter: saturate(180%)');\n } else {\n console.log('No existe el elemento saturation');\n }\n}",
"trimEdges(stage) {\n if (!stage.srcCtx) {\n return;\n }\n\n const srcData = stage.srcCtx.getImageData(0, 0, stage.srcSize.w, stage.srcSize.h);\n\n // Always trim by top-left pixel color\n const trimPixel = getPixel_(stage, srcData, 0, 0);\n\n let insetRect = {l:0, t:0, r:0, b:0};\n let x, y;\n\n // Trim top\n trimTop:\n for (y = 0; y < stage.srcSize.h; y++) {\n for (x = 0; x < stage.srcSize.w; x++) {\n if (getPixel_(stage, srcData, x, y) != trimPixel) {\n break trimTop;\n }\n }\n }\n insetRect.t = y;\n // Trim left\n trimLeft:\n for (x = 0; x < stage.srcSize.w; x++) {\n for (y = 0; y < stage.srcSize.h; y++) {\n if (getPixel_(stage, srcData, x, y) != trimPixel) {\n break trimLeft;\n }\n }\n }\n insetRect.l = x;\n // Trim bottom\n trimBottom:\n for (y = stage.srcSize.h - 1; y >= 0; y--) {\n for (x = 0; x < stage.srcSize.w; x++) {\n if (getPixel_(stage, srcData, x, y) != trimPixel) {\n break trimBottom;\n }\n }\n }\n insetRect.b = stage.srcSize.h - y - 1;\n // Trim right\n trimRight:\n for (x = stage.srcSize.w - 1; x >= 0; x--) {\n for (y = 0; y < stage.srcSize.h; y++) {\n if (getPixel_(stage, srcData, x, y) != trimPixel) {\n break trimRight;\n }\n }\n }\n insetRect.r = stage.srcSize.w - x - 1;\n\n if (insetRect.l <= 0 && insetRect.t <= 0 && insetRect.r <= 0 && insetRect.b <= 0) {\n // No-op\n return;\n }\n\n // Build a new stage with inset values\n const size = {\n w: stage.srcSize.w - insetRect.l - insetRect.r,\n h: stage.srcSize.h - insetRect.t - insetRect.b\n };\n\n const rects = {\n contentRect: constrain_(size, {\n x: stage.contentRect.x - insetRect.l,\n y: stage.contentRect.y - insetRect.t,\n w: stage.contentRect.w,\n h: stage.contentRect.h\n }),\n stretchRect: constrain_(size, {\n x: stage.stretchRect.x - insetRect.l,\n y: stage.stretchRect.y - insetRect.t,\n w: stage.stretchRect.w,\n h: stage.stretchRect.h\n }),\n opticalBoundsRect: constrain_(size, {\n x: stage.opticalBoundsRect.x - insetRect.l,\n y: stage.opticalBoundsRect.y - insetRect.t,\n w: stage.opticalBoundsRect.w,\n h: stage.opticalBoundsRect.h\n })\n };\n\n stage.name = `${stage.name}-EDGES_TRIMMED`;\n let newCtx = studio.Drawing.context(size);\n newCtx.drawImage(stage.srcCtx.canvas,\n insetRect.l, insetRect.t, size.w, size.h,\n 0, 0, size.w, size.h);\n stage.loadSourceImage(newCtx, rects);\n }",
"function filter_attribute(obj) {\n var index = +(obj.id)\n $(combobox_rows_id).val(\"-\")\n $(combobox_columns_id).val(\"-\")\n if (obj.checked) {\n columns_mask[index] = true\n } else {\n columns_mask[index] = false\n }\n if(columns_mask.every(is_false)) {\n alert(\"Warning: The chart must have at least one attribute!\");\n columns_mask[index] = true;\n $(obj).prop('checked', true);\n } else {\n // reload\n selected_row = -1\n selected_column = -1\n chart_scatter_matrix();\n initialize_zoom_comboboxes();\n star_plot();\n }\n}",
"crop(data, xspan, yspan) {\n var halfx = xspan / 2,\n halfy = yspan / 2;\n\n return _.filter(data, function(entry) {\n return -halfx < entry.mercator[0] && halfx > entry.mercator[0]\n && -halfy < entry.mercator[1] && halfy > entry.mercator[1];\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove empty module declaration | function cleanEmptyNamespace (str, moduleName) {
let emptyDeclareRegexp = new RegExp("declare module " + moduleName + " {\\s*}\\s*", "gm");
str = str.replace(emptyDeclareRegexp, "");
return str;
} | [
"function removeModule() {\n\t\tcommon.naclModule.parentNode.removeChild(common.naclModule);\n\t\tcommon.naclModule = null;\n\t}",
"function removeShrink(){\n\t\tvar rows = $b42s_header.find( '.fl-row-content-wrap' ),\n\t\t\tmodules = $b42s_header.find( '.fl-module-content' );\n\n\t\trows.removeClass( 'fl-theme-builder-header-shrink-row-bottom' );\n\t\trows.removeClass( 'fl-theme-builder-header-shrink-row-top' );\n\t\tmodules.removeClass( 'fl-theme-builder-header-shrink-module-bottom' );\n\t\tmodules.removeClass( 'fl-theme-builder-header-shrink-module-top' );\n\t\t$b42s_header.removeClass( 'fl-theme-builder-header-shrink' );\n\t}",
"async removeExtraneousNodeModules() {\n // this is only relevant for the root workspace\n if (!this.isWorkspaceRoot) {\n return;\n }\n\n const workspacesInfo = await (0, _scripts.yarnWorkspacesInfo)(this.path);\n const unusedWorkspaces = new Set(Object.keys(workspacesInfo)); // check for any cross-project dependency\n\n for (const name of Object.keys(workspacesInfo)) {\n const workspace = workspacesInfo[name];\n workspace.workspaceDependencies.forEach(w => unusedWorkspaces.delete(w));\n }\n\n unusedWorkspaces.forEach(name => {\n const {\n dependencies,\n devDependencies\n } = this.json;\n\n const nodeModulesPath = _path.default.resolve(this.nodeModulesLocation, name);\n\n const isDependency = dependencies && dependencies.hasOwnProperty(name);\n const isDevDependency = devDependencies && devDependencies.hasOwnProperty(name);\n\n if (!isDependency && !isDevDependency && _fs.default.existsSync(nodeModulesPath)) {\n _log.log.debug(`No dependency on ${name}, removing link in node_modules`);\n\n _fs.default.unlinkSync(nodeModulesPath);\n }\n });\n }",
"exitSingleTypeImportDeclaration(ctx) {\n\t}",
"function hideModule() {\n\t\t// Setting common.naclModule.style.display = \"None\" doesn't work; the\n\t\t// module will no longer be able to receive postMessages.\n\t\tcommon.naclModule.style.height = '0';\n\t}",
"function clearExternals(externals = [], compiler) {\n}",
"exitTypeImportOnDemandDeclaration(ctx) {\n\t}",
"removeKeys () {\n this._eachPackages(function (_pack) {\n _pack.remove()\n })\n }",
"function skipModule (name) {\n var i, len;\n if (!skipModules) {\n return;\n }\n for (i = 0, len = skipModules.length; i < len; ++i) {\n // Accept a path prefix as well.\n if (name.indexOf(skipModules[i]) === 0) {\n return true;\n }\n }\n }",
"function restoreFunctionNames(ast) {\n var functionNames = [];\n t.traverse(ast, {\n FunctionNameMetadata: function FunctionNameMetadata(_ref) {\n var node = _ref.node;\n functionNames.push({\n name: node.value,\n index: node.index\n });\n }\n });\n\n if (functionNames.length === 0) {\n return;\n }\n\n t.traverse(ast, {\n Func: function (_Func) {\n function Func(_x) {\n return _Func.apply(this, arguments);\n }\n\n Func.toString = function () {\n return _Func.toString();\n };\n\n return Func;\n }(function (_ref2) {\n var node = _ref2.node;\n // $FlowIgnore\n var nodeName = node.name;\n var indexBasedFunctionName = nodeName.value;\n var index = Number(indexBasedFunctionName.replace(\"func_\", \"\"));\n var functionName = functionNames.find(function (f) {\n return f.index === index;\n });\n\n if (functionName) {\n var oldValue = nodeName.value;\n nodeName.value = functionName.name;\n nodeName.numeric = oldValue; // $FlowIgnore\n\n delete nodeName.raw;\n }\n }),\n // Also update the reference in the export\n ModuleExport: function (_ModuleExport) {\n function ModuleExport(_x2) {\n return _ModuleExport.apply(this, arguments);\n }\n\n ModuleExport.toString = function () {\n return _ModuleExport.toString();\n };\n\n return ModuleExport;\n }(function (_ref3) {\n var node = _ref3.node;\n\n if (node.descr.exportType === \"Func\") {\n // $FlowIgnore\n var nodeName = node.descr.id;\n var index = nodeName.value;\n var functionName = functionNames.find(function (f) {\n return f.index === index;\n });\n\n if (functionName) {\n node.descr.id = t.identifier(functionName.name);\n }\n }\n }),\n ModuleImport: function (_ModuleImport) {\n function ModuleImport(_x3) {\n return _ModuleImport.apply(this, arguments);\n }\n\n ModuleImport.toString = function () {\n return _ModuleImport.toString();\n };\n\n return ModuleImport;\n }(function (_ref4) {\n var node = _ref4.node;\n\n if (node.descr.type === \"FuncImportDescr\") {\n // $FlowIgnore\n var indexBasedFunctionName = node.descr.id;\n var index = Number(indexBasedFunctionName.replace(\"func_\", \"\"));\n var functionName = functionNames.find(function (f) {\n return f.index === index;\n });\n\n if (functionName) {\n // $FlowIgnore\n node.descr.id = t.identifier(functionName.name);\n }\n }\n }),\n CallInstruction: function (_CallInstruction) {\n function CallInstruction(_x4) {\n return _CallInstruction.apply(this, arguments);\n }\n\n CallInstruction.toString = function () {\n return _CallInstruction.toString();\n };\n\n return CallInstruction;\n }(function (nodePath) {\n var node = nodePath.node;\n var index = node.index.value;\n var functionName = functionNames.find(function (f) {\n return f.index === index;\n });\n\n if (functionName) {\n var oldValue = node.index;\n node.index = t.identifier(functionName.name);\n node.numeric = oldValue; // $FlowIgnore\n\n delete node.raw;\n }\n })\n });\n}",
"function printNodeModuleAll(modules) {\n print(``);\n print(`# Pseudo-module that basically acts as a module collection for the entire set`);\n print(`node_module(`);\n print(` name = \"_all_\",`);\n print(` deps = [`);\n modules.forEach(module => {\n print(` \":${module.yarn ? module.yarn.label : module.name}\",`);\n });\n print(` ],`);\n print(`)`);\n}",
"function onExecutableModuleDisposed() {\n goog.dom.classlist.remove(goog.dom.getElement('crash-warning'), 'hidden');\n}",
"static cleanNamespace(namespace) {\n this.getNamespace(namespace).__proto__ = null\n }",
"function removeTsickle() {\n return (tree, context) => {\n dependencies_1.removePackageJsonDependency(tree, 'tsickle');\n const logger = context.logger;\n const workspace = utils_1.getWorkspace(tree);\n for (const { target } of utils_1.getTargets(workspace, 'build', workspace_models_1.Builders.DeprecatedNgPackagr)) {\n for (const options of utils_1.getAllOptions(target)) {\n const tsConfigOption = json_utils_1.findPropertyInAstObject(options, 'tsConfig');\n if (!tsConfigOption || tsConfigOption.kind !== 'string') {\n continue;\n }\n const tsConfigPath = tsConfigOption.value;\n let tsConfigJson;\n try {\n tsConfigJson = new json_file_1.JSONFile(tree, tsConfigPath);\n }\n catch (_a) {\n logger.warn(`Cannot find file: ${tsConfigPath}`);\n continue;\n }\n tsConfigJson.remove(['angularCompilerOptions', 'annotateForClosureCompiler']);\n }\n }\n };\n}",
"exitSingleStaticImportDeclaration(ctx) {\n\t}",
"function cleanScopes(scopes) {\r\n var res = scopes;\r\n res = arrayRemove(res, 'source.json');\r\n res = arrayRemove(res, 'meta.structure.dictionary.json');\r\n res = arrayRemove(res, 'meta.structure.dictionary.value.json');\r\n //res = arrayRemove(scopes, 'source.json');\r\n return res;\r\n}",
"function routesEmpty() {\n fs.copySync(path.join(__dirname, 'assets', 'emptyModule.js'), routesFilePath);\n fs.copySync(path.join(__dirname, 'assets', 'ftlRoutes.js'), path.join(__dirname, 'tmp', 'ftlRoutes.js'));\n fs.removeSync(combinedFilePath);\n processor.process(filePaths, combinedFilePath, function() {\n t.ok(fs.existsSync(combinedFilePath), 'routes empty, combined file exists');\n var mod = helper.loadModule(combinedFilePath);\n t.ok(mod['GET /ftl'], 'routes empty, combined has ftl Components');\n t.notOk(mod['GET /test'], 'routes empty, combined does not have routes Components');\n ftlEmpty();\n });\n }",
"function removeModelClasses() {\n modelClasses = null;\n}",
"function resetState() {\n fileBuffers = [];\n outputFile = \"output.js\";\n latestFile = undefined;\n // Load the controller code that will be at the beginning of the output file\n const controller = fs.readFileSync(path.join(__dirname, \"moduleManager.js\"));\n fileBuffers.push(controller);\n lineCount = getLineCount(controller.toString(\"utf-8\"));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set platform specific data. | SetPlatformData() {} | [
"GetPlatformData() {}",
"_setData() {\n this._global[this._namespace] = this._data;\n }",
"SetCompatibleWithPlatform() {}",
"SetCompatibleWithAnyPlatform() {}",
"setData(data) {\n if (!data) {\n console.log('oops.. no data');\n return;\n }\n\n // console.log('got data...', data);\n this.data = data;\n if (this.script) {\n document.body.removeChild(this.script);\n this.script = undefined;\n }\n\n this.preloadImages(this.data.items);\n }",
"function setDeviceInformation(devPath,model,src,manufac,ostyp,prdfmly,ipadd,prot,hostnme,devtype){\n//\tvar devtype = getDeviceType(model);\n\tif(manufac){\n\t\tvar manu = manufac;\n\t}else{\n\t\tvar manu = getManufacturer(model);\n\t}\n\tvar myPortDev = [];\n\tif(globalInfoType == \"JSON\"){\n\t\tsetDevicesInformationJSON(\"\",devtype,devPath,model,model,\"\",\"\",ostyp,\"\",\"\",\"\",\"\",hostnme,\"new\",\"\",\"\",ipadd,\"\",\"\",\"\",\"Exclusive\",imgXPos,imgYPos,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",manu,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",prdfmly,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",window['variable' + dynamicDomain[pageCanvas] ],\"\",\"\",\"\",\"\",src,myPortDev,\"\",\"\");\n\t\tsetDevicesChildInformationJSON(\"\",\"\",\"\",\"\",\"\",\"\",devPath,\"\",\"\",devPath,\"\",\"\",model,model,manu,\"\",\"\",\"\",hostnme,\"new\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",prot,\"\",\"\",\"\");\n\t}else{\n\t\tstoreDeviceInformation(\"\",devtype,devPath,model,model,\"\",\"\",ostyp,\"\",\"\",\"\",\"\",hostnme,\"new\",\"\",\"\",ipadd,\"\",\"\",\"\",\"Exclusive\",imgXPos,imgYPos,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",manu,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",prdfmly,\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",window['variable' + dynamicDomain[pageCanvas] ],\"\",\"\",\"\",\"\",src,myPortDev,\"\",\"\");\n\n\t\tstoreChildDevicesInformation(\"\",\"\",\"\",\"\",\"\",\"\",devPath,\"\",\"\",devPath,\"\",\"\",model,model,manu,\"\",\"\",\"\",hostnme,\"new\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",prot,\"\",\"\",\"\");\n\t}\n}",
"function parsePlatformPreferences(configData, platform) {\n var preferences = getPlatformPreferences(platform);\n switch(platform){\n case \"ios\":\n parseiOSPreferences(preferences, configData);\n break;\n case \"android\":\n parseAndroidPreferences(preferences, configData);\n break;\n }\n }",
"set(id, data) {\n let oldData = this.raw();\n oldData[id] = data;\n this._write(oldData);\n }",
"function setAppData(appData) {\n self.LApp.data = appData;\n $log.debug('success storing application data');\n }",
"function updatePlatformConfig(platform) {\n var configData = parseConfigXml(platform),\n platformPath = path.join(rootdir, 'platforms', platform);\n\n _.each(configData, function (configItems, targetFileName) {\n var targetFilePath;\n if (platform === 'ios') {\n if (targetFileName.indexOf(\"Info.plist\") > -1) {\n targetFileName = projectName + '-Info.plist';\n targetFilePath = path.join(platformPath, projectName, targetFileName);\n ensureBackup(targetFilePath, platform, targetFileName);\n updateIosPlist(targetFilePath, configItems);\n }else if (targetFileName === \"project.pbxproj\") {\n targetFilePath = path.join(platformPath, projectName + '.xcodeproj', targetFileName);\n ensureBackup(targetFilePath, platform, targetFileName);\n updateIosPbxProj(targetFilePath, configItems);\n updateXCConfigs(configItems, platformPath);\n }\n\n } else if (platform === 'android' && targetFileName === 'AndroidManifest.xml') {\n targetFilePath = path.join(platformPath, targetFileName);\n ensureBackup(targetFilePath, platform, targetFileName);\n updateAndroidManifest(targetFilePath, configItems);\n } else if (platform === 'wp8') {\n targetFilePath = path.join(platformPath, targetFileName);\n ensureBackup(targetFilePath, platform, targetFileName);\n updateWp8Manifest(targetFilePath, configItems);\n }\n });\n }",
"setResourceData(state, {resource, data}) {\n _.forIn(data, (value, key) => {\n resource[key] = value\n })\n }",
"setUserData (user = {}) {\n this.memory.set(this.getName(\"userData\"), user);\n }",
"function SET_PAGE_DATA(state, value) {\n state.page.data = value;\n}",
"SetEditorData() {}",
"function updateAnalyticsProdObj(data, evtIndex) {\n if (typeof s_setP !== 'undefined' && typeof data !== 'undefined') {\n\n if(data.product && data.product.length > 0) {\n s_setP('digitalData.event['+evtIndex+'].attributes.product', data.product);\n }\n }\n}",
"function refreshPlatforms(platforms) {\n if(platforms === undefined) return;\n deleteDirSync(\"platforms\");\n\n if(platforms.indexOf(\"a\") !== -1)\n runShell(\"npx ionic cordova platform add android\");\n\n if(platforms.indexOf(\"i\") !== -1)\n if (OS.platform() === \"darwin\") runShell(\"npx ionic cordova platform add ios\");\n else consoleOut(`(set_brand.js) did not add ios-platform on the operating system \"${OS.platform()}\"`);\n}",
"function setBasicAttribs(data, elem) {\n //set token\n elem.find(\".item-token\").text(data.token).attr(\"href\", \"/resolution/editor/\" + data.token);\n\n //id and year only if present in data\n if (data.idYear && data.resolutionId) {\n elem.find(\".item-year\").text(data.idYear);\n elem.find(\".item-id\").text(data.resolutionId);\n }\n\n //set forum and main sponsor\n elem.find(\".item-forum\").text(data.address.forum);\n elem.find(\".item-sponsor\").text(data.address.sponsor.main);\n\n //set age, get delta time in seconds and convert to time text\n elem.find(\".item-age\").text(getTimeText((Date.now() - data.waitTime) / 1000));\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}",
"_setDataToUI() {\n const data = this._data;\n if (data === undefined) return;\n console.log('View#_setDataToUI', this);\n\n if (data instanceof Object) {\n eachEntry(data, ([name, val]) => this._setFieldValue(name, val));\n } else {\n this._setVal(this.el, data);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
method: reset watch display count | resetWatch() {
this.reset();
this.print();
} | [
"function clear() {\n if (count >= 1) {\n document.getElementById(\"numDisplay\").innerHTML = '';\n count = 0;\n }\n }",
"reset() {\n const _ = this;\n _._counter = _._startCount;\n }",
"function clearScreen(){ displayVal.textContent = null}",
"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}",
"clearDisplay() {\n\t\tconst {displayValue} = this.state\n\t\tthis.setState({\n\t\t\tdisplayValue: '0'\n\t\t})\n\t}",
"function updateCountDisplays() {\n\tdocument.getElementById(\"watcherCount\").innerHTML = ((watchers == 0) ? \"No\" : watchers) + \" viewer\" + ((watchers != 1) ? \"s\" : \"\");\n}",
"function reset(){\r\n document.getElementById(\"count-increment\").innerText= 0;\r\n countEnter =0\r\n document.getElementById(\"count-decrement\").innerText= 0;\r\n countLeft = 0;\r\n document.getElementById(\"count-total\").innerText=0;\r\n countInside= 0;\r\n console.log(\"Reset pressed\");\r\n}",
"function reset() {\n\t\tclearInterval(timerId);\n\t\ttimeId = null;\n\t\tindex = 0;\n\t\tid(\"output\").textContent = \"\";\n\t\tid(\"input-text\").value = \"\";\n\t\tid(\"input-text\").disabled = false;\n\t}",
"function clearEntry() {\n changeDisplay('0');\n }",
"clear() {\n\t\tthis.watchList.forEach((item) => this.remove(item.uri));\n\t\tthis.watchList = [];\n\n\t\tchannel.appendLocalisedInfo('cleared_all_watchers');\n\t\tthis._updateStatus();\n\t}",
"resetCount() {\n this.setStatistics({\n fetchedDocuments: 0,\n migratedDocuments: 0,\n totalDocuments: 0,\n ignoredDocuments: 0,\n });\n }",
"reset () {\n this.total = this.seconds * 1000.0;\n this._remaining = this.total;\n this._clearInterval();\n this.tick();\n }",
"function clearDisplay(val){\n\t\tprimaryOutput.innerHTML = \"\";\t\n\t\tif (val === \"AC\") {\n\t\t\ttotal = 0;\n\t\t\tsecondaryOutput.innerHTML = \"\";\n\t\t\tsecondaryOutput.style.right = \"0px\";\n\t\t\tlastOperator.length = 0;\n\t\t}\n\t}",
"function reinitializeAppropriateDisplay() {\n updateEventVars(getNow());\n displayOnPage();\n }",
"function resetClock() {\n window.clearInterval(runClock);\n let currentmsTens = 0;\n let currentmsHundreds = 0;\n let currentSecondOnes = 0;\n let currentSecondTens = 0;\n msHundreds.innerHTML = currentmsHundreds;\n msHundreds.style.color = 'black';\n msTens.innerHTML = currentmsTens;\n msTens.style.color = 'black';\n secondOnes.innerHTML = currentSecondOnes;\n secondOnes.style.color = 'black';\n secondTens.innerHTML = currentSecondTens;\n secondTens.style.color = 'black';\n colon.style.color = 'black';\n startButton.setAttribute('disabled', 'false');\n}",
"clearAndResetUpdate(){\n\t\tclearTimeout(timer);\n\t\tthis.getChats();\t\n\t}",
"reset() {\n\tthis.progress = new Progress(0);\n\tthis.question = [];\n\tthis.setChanged();\n\tthis.notifyObservers(this.progress);\n\tthis.clearChanged();\n }",
"function reset() {\n defaultRenderers_ = {};\n decoratorFunctions_ = {};\n}",
"function resetGame(){\n counter = 0;\n $(\"#scoreSoFar\").text(counter);\n numberOptions = [];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
show admin data for the specific class and id | function show(model, id) {
$('#adminData').show();
if (typeof model === 'object') {
current = [model.attr('data-class'), model.attr('data-id')];
} else {
current = [model, id];
}
updateActions(model, id);
return updateMeta(model, id);
} | [
"displayAdmin() {\n let add_form = document.getElementById(\"add_form\");\n add_form.classList.toggle(\"hidden\");\n \n let delete_btns = document.querySelectorAll(\".delete_btn\");\n delete_btns.forEach(function(item){\n item.classList.toggle(\"hidden\");\n })\n\n let edit_btns = document.querySelectorAll(\".edit_btn\");\n edit_btns.forEach(function(item){\n item.classList.toggle(\"hidden\");\n }) \n //disable sort function when inside admin, to avoid bugg.\n this.sort_btn.disabled = !this.sort_btn.disabled; \n }",
"function enableEditingOptionViewForStudentID(id) {\n\n // Hide options button\n $(`#${uniqueIDPrefix}options${id} .on-hover-show button`).attr('class', 'edit-content-hidden');\n $(`#${uniqueIDPrefix}options${id} .on-hover-show div.dropdown-content`).attr('class', 'edit-content-hidden');\n\n // Show edit links\n $(`#${uniqueIDPrefix}options${id} .on-edit-show div`).attr('class', 'is-editable');\n\n}",
"show(iemId) {\n return Api().get(`iems/${iemId}`)\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 }",
"show(req, res) {\n Scenario.findById(req.params.id)\n .then(function (scenario) {\n res.status(200).json(scenario);\n })\n .catch(function (error) {\n res.status(500).json(error);\n });\n }",
"singleClass (req,res){\n addClass.findById(req.params.classid, function(error, aclass){\n if (error) {console.error(error);}\n res.send(aclass)\n })\n }",
"function getAdminProfile() {\n FYSCloud.API.queryDatabase(\n \"SELECT * FROM profile WHERE user_id = ?\",\n [admin[0].user_id]\n\n ).done(function(adminDetails) {\n admin = adminDetails[0];\n // check if there is an avatar\n if(admin.avatar !== null) {\n $('#navbarAvatar').attr('src', admin.avatar);\n }\n }).fail(function(reason) {\n console.log(reason);\n });\n }",
"show(req, res) {\n Model.Company.findById(req.params.id, {\n })\n .then(function (company) {\n res.status(200).json(company);\n })\n .catch(function (error){\n res.status(500).json(error);\n });\n }",
"function details() {\n\n var storeID = request.httpParameterMap.StoreID.value;\n var store = dw.catalog.StoreMgr.getStore(storeID);\n\n var pageMeta = require('~/cartridge/scripts/meta');\n pageMeta.update(store);\n\n app.getView({Store: store})\n .render('storelocator/storedetails');\n\n}",
"getAdminInfo() {\n return {\n admin_1: this.data.persons.find((p) => p.a_code === this.data.config.AG_REGISTER_PERSON_1),\n admin_2: this.data.persons.find((p) => p.a_code === this.data.config.AG_REGISTER_PERSON_2),\n signature_1: this.data.config.AG_REGISTER_SIGNATURE_1,\n signature_2: this.data.config.AG_REGISTER_SIGNATURE_2,\n address_pos_left: this.data.config.ADDRESS_POS_LEFT,\n address_pos_top: this.data.config.ADDRESS_POS_TOP,\n }\n }",
"async show({ params }) {\n const { id } = params;\n return Type.findOrFail(id);\n }",
"function show(req, res){\n Listing.findById(req.params.id).populate('listing'){\n if(err) return console.log(err)\n res.json(listing)\n }\n }",
"function viewManagers() {\n connection.query(\"SELECT first_name AS First, last_name AS Last, department.name AS Department FROM employee INNER JOIN department ON department.id = employee.department_id WHERE manager_id IS NULL\", function (err, results) {\n if (err) throw err;\n console.table(\"List of Managers:\", results);\n mainMenu();\n });\n}",
"function controller_by_user(){\n\t\ttry {\n\t\t\t\n//debug: all data\nconsole.log(data_quotess);\n\t\t\t\n\t\t} catch(e){\n\t\t\tconsole.log(\"error: page quotes => custom controller\");\n\t\t\tconsole.log(e);\n\t\t}\n\t}",
"function _getAmenDetails(propid){\n\n\t$.ajax({\n\t\t\turl: srl+'props',\n\t\t\ttype: 'get',\n\t\t\tdata: {'amenid':propid},\n\t\t\tsuccess: function(result){\n\t\t\t\t$(result).each(function(i,data){\n\t\t\t\t\tconsole.log(data);\n\t\t\t\t\tvar _amen = data.amen_short_code;\n\t\t\t\t\tvar _div = $('<div></div>').addClass('col-md-2 amen-div').text(_amen);\n\t\t\t\t\t$('#amen-summary').append(_div);\n\t\t\t\t});\n\t\t\t},\n\t\t\terror:function (xhr, ajaxOptions, thrownError) {\n\t\t\t\tconsole.log(xhr.status);\n\t\t\t\t//alert(thrownError);\n\t\t}\n\t});\n}",
"function populateSpaceDetails(jsonData, id) {\n\t// If the space is null, the user can see the space but is not a member\n\tif (jsonData.space == null) {\n\t\t// Go ahead and show the space's name\n\t\t$('.spaceName').fadeOut('fast', function() {\n\t\t\tvar spaceName = $('.jstree-clicked').text();\n\t\t\t$('.spaceName').text(spaceName).fadeIn('fast');\n\t\t\tdocument.title = spaceName + \" - StarExec\";\n\t\t});\n\n\t\t// Show a message why they can't see the space's details\n\t\t$('#spaceDesc').fadeOut('fast', function() {\n\t\t\t$('#spaceDesc')\n\t\t\t.text(\n\t\t\t\t'you cannot view this space\\'s details since you are not a member. you can see this space exists because you are a member of one of its descendants.')\n\t\t\t.fadeIn('fast');\n\t\t});\n\t\t$('#spaceID').fadeOut('fast');\n\t\t// Hide all the info table fieldsets\n\t\t$('#detailPanel fieldset').fadeOut('fast');\n\t\t$('#loader').hide();\n\n\t\t// Stop executing the rest of this function\n\t\treturn;\n\t} else {\n\t\t// Or else the user can see the space, make sure the info table fieldsets are visible\n\t\t$('#userField').show(); // this fieldset is present only on the spacePermissions page\n\t\t$('#detailPanel fieldset').show();\n\t}\n\n\t// Update the selected space id\n\tspaceId = jsonData.space.id;\n\tspaceName = jsonData.space.name;\n\n\t// Populate space defaults\n\t$('.spaceName').fadeOut('fast', function() {\n\t\t$('.spaceName').text(spaceName).fadeIn('fast');\n\t\tdocument.title = spaceName + \" - StarExec\";\n\t});\n\t$('#spaceDesc').fadeOut('fast', function() {\n\t\t$('#spaceDesc').text(jsonData.space.description).fadeIn('fast');\n\t});\n\t$('#spaceID').fadeOut('fast', function() {\n\t\t$('#spaceID').text(\"id = \" + spaceId).fadeIn('fast');\n\t});\n\n\t// on the space permissions page, we display when the user is the space leader\n\tif (spaceId != \"1\") {\n\t\tcurIsLeader = jsonData.perm.isLeader;\n\t} else {\n\t\tcurIsLeader = false;\n\t}\n\t$('#spaceLeader').fadeOut('fast', function() {\n\t\tif (curIsLeader) {\n\t\t\t$('#spaceLeader').text(\"leader of current space\").fadeIn('fast');\n\t\t}\n\t});\n\t/*\n\t * Issue a redraw to all DataTable objects to force them to requery for\n\t * the newly selected space's primitives. This will effectively clear\n\t * all entries in every table, update every table with the current space's\n\t * primitives, and update the number displayed in every table's fieldset.\n\t */\n\tredrawAllTables();\n\n\t// Check the new permissions for the loaded space. Varies between spaces.js and spacePermissions.js\n\tcheckPermissions(jsonData.perm, id);\n\n\t// Done loading, hide the loader\n\t$('#loader').hide();\n\n\tlog('Client side UI updated with details for ' + spaceName);\n}",
"function viewDetail(id) {\n container.style.visibility = \"visible\";\n wrapper.style.visibility = \"visible\";\n\n // room detail\n fetch(apiRoom)\n .then((response) => response.json())\n .then(function (rooms) {\n\t let roomData = rooms.filter((allRooms) => {\n\t\treturn (allRooms.id == id);\n\t }).map((data) => {\n\t\treturn `<div class=\"info-header\">\n\t <h1>${data.name}<button class=\"close-btn\" onclick=\"hideDetail()\">×</button></h1>\n\t <div class=\"main-info\">\n\t <div class=\"name\">\n\t <i class=\"name-icon\"></i>\n\t <div class=\"name-text\">${data.houseOwner}</div>\n\t </div>\n\t <div class=\"phone\">\n\t <i class=\"phone-icon\"></i>\n\t <div class=\"phone-text\">${data.ownerPhone}</div>\n\t </div>\n\t <div class=\"address\">\n\t <i class=\"address-icon\"></i>\n\t <div class=\"address-text\">${data.address}</div>\n\t </div>\n\t </div>\n\t <h2>${data.price}</h2>\n\t </div>\n\t <div class=\"info\">\n\t <div class=\"info-type\">\n\t <h3>Loại phòng</h3>\n\t <p>${data.category}</p>\n\t </div>\n\t <div class=\"info-area\">\n\t <h3>Diện tích</h3>\n\t <p>${data.area}</p>\n\t </div>\n\t <div class=\"info-deposit\">\n\t <h3>Đặt cọc</h3>\n\t <p>${data.deposit}</p>\n\t </div>\n\t <div class=\"info-capacity\">\n\t <h3>Sức chứa</h3>\n\t <p>${data.capacity}</p>\n\t </div>\n\t <div class=\"info-electric\">\n\t <h3>Tiền điện</h3>\n\t <p>${data.electricPrice}</p>\n\t </div>\n\t <div class=\"info-water\">\n\t <h3>Tiền nước</h3>\n\t <p>${data.waterPrice}</p>\n\t </div>\n\t <div class=\"info-fee\">\n\t <h3>Chi phí khác</h3>\n\t <p>${data.otherPrice}</p>\n\t </div>\n\t <div class=\"info-status\">\n\t <h3>Tình trạng</h3>\n\t <p>${data.status}</p>\n\t </div>\n\t <div class=\"info-description\">\n\t <h3>Mô tả chi tiết</h3>\n\t <p>${data.description}</p>\n\t </div>\n\t </div>`;\n \t });\n\t container.innerHTML = \"\";\n\t container.innerHTML = roomData; \n\t});\n}",
"function show_admin_replies(reply_id) {\n\tvar url = \"mgArticle!getAdminReplies.shtml\";\n\tvar data = {replyId:reply_id};\n\t$.post(url, data, function (data) {\n\t\tvar admin_replies = eval(data);\n\t\tvar replies = [];\n\t\tfor (var i = 0; i < admin_replies.length; i++) {\n\t\t\treplies.push(\"<div class='message'><p><a>\" + admin_replies[i].admin.name + \"</a>\\u8bc4\\u8bba\\u8bf4:<span class='reply_content'>\" + admin_replies[i].replyContent + \"</span></p><p style='text-align: right'><a href=\\\"javascript:delete_admin_reply('\" + admin_replies[i].replyId + \"','\" + reply_id + \"')\\\">Delete Reply</a></p></div>\");\n\t\t}\n\t\t$(\"#admin_replies\").html(replies.join(\"\"));\n\t\t$(\"#admin_reply\").modal();\n\t});\n}",
"getById(id) {\n return tag.configure(FieldLink(this).concat(`(guid'${id}')`), \"fls.getById\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save and push EngineerData to empty ProductionTeam array. | function createNewEngineer (data, engineerData) {
var myNewEngineer = new Engineer (data.id, data.name, data.email, engineerData.github);
productionTeam.push(myNewEngineer);
console.log('Production Team', productionTeam);
// prompts add another question function to see whether they want to add another or stop
addAnother();
} | [
"function _createTeams() {\n gTeams = storageService.load('teams')\n storageService.store('teams', gTeams)\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}",
"function pushBusinessDev(projectId,businessDevelopment){\n Project.findById(projectId,function(err,proj){\n proj.businessDevelopment.push(businessDevelopment)\n proj.save();\n })\n}",
"function createNewIntern (data, internData) {\n var myNewIntern = new Intern (data.id, data.name, data.email, internData.school);\n productionTeam.push(myNewIntern);\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}",
"async function createEngineer() {\n const engineerInfo = await Inquirer.prompt([\n {\n type: 'input',\n message: 'Enter your name',\n name: 'name'\n },\n {\n type: 'input',\n message: 'Enter your id',\n name: 'id'\n },\n {\n type: 'input',\n message: 'Enter your email',\n name: 'email'\n },\n {\n type: 'input',\n message: 'Enter your github',\n name: 'github'\n }\n ]);\n const engineer = await new Engineer(\n engineerInfo.name,\n engineerInfo.id,\n engineerInfo.email,\n engineerInfo.github\n );\n\n await teamMembers.push(engineer);\n }",
"function storeData(data, store) {\r\n if(store === \"teams\") {\r\n $(data).find(\"match\").each(function(index) {\r\n var Match = {\r\n index: index + 1,\r\n name1: $(this).find(\"team\")[0].textContent,\r\n name2: $(this).find(\"team\")[1].textContent,\r\n score1: $(this).find(\"team\").eq(0).attr(\"score\") !== undefined ? $(this).find(\"team\").eq(0).attr(\"score\") : \"-\",\r\n score2: $(this).find(\"team\").eq(0).attr(\"score\") !== undefined ? $(this).find(\"team\").eq(0).attr(\"score\") : \"-\",\r\n venue: $(this).find(\"venue\")[0].textContent,\r\n date: $(this).find(\"day\")[0].textContent + \"/\" + $(this).find(\"month\")[0].textContent + \"/\" + $(this).find(\"year\")[0].textContent\r\n };\r\n\r\n matches.push(Match);\r\n\r\n if($.inArray(Match.name1, teams) === -1) {\r\n teams.push(Match.name1);\r\n }\r\n\r\n if($.inArray(Match.name2, teams) === -1) {\r\n teams.push(Match.name2);\r\n }\r\n });\r\n } else if (store === \"venues\") {\r\n $.each($(data).find(\"venues\").children(), function(index, venue) {\r\n if($.inArray(venue, venues) === -1) {\r\n venues.push(venue.textContent);\r\n }\r\n });\r\n }\r\n }",
"function saveData() {\n var self = this;\n\n try {\n localStorage.setItem(\n self.data.name,\n JSON.stringify(self.getArrayOfData())\n );\n } catch (e) {\n console.error('Local storage save failed!', e);\n }\n\n }",
"storeTeams() {\n try {\n const serializedTeams = JSON.stringify(this.state.teams);\n localStorage.setItem('teams', serializedTeams);\n } catch (err) {\n console.log('error: ', err);\n }\n }",
"function pushTeamRadarData(teamData){\n for (var i = 0; i < teamData.length; i++) { \n if (teamData[i].team == selectedTeamName) { //Grab the team\n var teamAxes = [];\n teamAxes.push({axis: \"Points\", value: regularizeRank(teamData[i].rPTS)});\n teamAxes.push({axis: \"Turnovers\", value: regularizeRank(teamData[i].rTOV)});\n teamAxes.push({axis: \"Steals\", value: regularizeRank(teamData[i].rSTL)});\n teamAxes.push({axis: \"Blocks\", value: regularizeRank(teamData[i].rBLK)});\n teamAxes.push({axis: \"Rebounds\", value: regularizeRank(teamData[i].rREB)});\n teamAxes.push({axis: \"Assists\", value: regularizeRank(teamData[i].rAST)});\n\n teamRadarData.push({className: teamData[i].team, axes: teamAxes});\n }\n }\n }",
"function teamDataSavedListener () {\n debug('match data saved, resolving state promise')\n module.exports.internal.teamDataSavedPromiseResolver()\n}",
"function employeeData() {\n\n let employeeInfo = [] //The new array containing the separate objects\n\n for (let i = 0; i < employees.length; i++) {\n const empl = employees[i];\n\n let stillEmployeed = true\n let currentSal = []\n let deptWorked = []\n\n for (let j = 0; j < employeeSalaries.length; j++) {\n const salaries = employeeSalaries[j];\n\n //for getting the salaries, push all of the salaries by employee id into an array and pull the last one.\n\n if (salaries[0] == empl[0]) {\n\n currentSal.push(salaries[1])\n\n //console.log(currentSal.slice(-1))\n\n currentSal = currentSal.slice(-1)\n\n if (salaries[3] != \"9999-01-01\") stillEmployeed = false\n\n else { stillEmployeed = true }\n\n\n }\n\n\n\n\n }\n for (let k = 0; k < employeeDepartment.length; k++) {\n const emplDept = employeeDepartment[k];\n\n\n for (let l = 0; l < departments.length; l++) {\n const dept = departments[l];\n\n if (empl[0] == emplDept[0] && emplDept[1] == dept[0]) deptWorked.push(dept[1])\n\n }\n\n }\n\n\n\n\n let workerInfo = {\n id: empl[0],\n name: `${empl[2]} ${empl[3]}`,\n gender: empl[4],\n birthday: empl[1],\n hireDate: empl[5],\n isStillEmployeed: stillEmployeed,\n departmentsWorkedFor: deptWorked,\n recentSalary: currentSal\n }\n\n employeeInfo.push(workerInfo)\n\n }\n\n console.log(employeeInfo)\n\n}",
"saveData() {\n let jsonData = {\n lastTicket: this.lastTicket,\n today: this.today,\n tickets: this.tickets,\n lastFour: this.lastFour\n }\n\n let jsonDataString = JSON.stringify(jsonData);\n \n fs.writeFileSync('./server/data/data.json', jsonDataString);\n }",
"function storeEarthquakeData(arr) {\n // Add data to Earthquake DB \n arr.forEach(element => {\nconsole.log(\"Adding ID: \" + element.id + \" to db.earthquake\") \n // ES6 destructuring to parse out; id, time, place, url, mag\n const { id, time, place, url, mag } = element;\n\n Earthquake.create({\n id: id,\n time : time,\n place : place,\n url : url,\n mag : mag\n })\n })\n}",
"updatePlayerData(playerData) {\n console.log(\"Updating player info...\");\n this.updateTeamData(this.contentRows, \".simLeft\", playerData);\n }",
"setLocalStore( newUuid, newTimestamp, newTrial_Count, newSolve_Count )\n\t{\n\t\tthis.EightQueensObj.uuid = newUuid;\n\t\tthis.EightQueensObj.timestamp = newTimestamp;\n\t\tthis.EightQueensObj.trial_count = newTrial_Count;\n\t\tthis.EightQueensObj.solve_count = newSolve_Count;\n\t\t\n\t\tconsole.log( \"setLocalStore called with values \" + JSON.stringify(this.EightQueensObj) );\n\t\t\n\t\twindow.localStorage.setItem( this.GAME, JSON.stringify( this.EightQueensObj ) );\n\t\t\n\t}",
"function teamUnitOfWorkCompletedPerSprint() {\n for (var k = 0; k < this.teamsArray.length; k++) {\n var tempTeam = this.teamsArray[k];\n\n tempTeam.unitOfWorkCompletedArray[tempTeam.unitOfWorkCompletedArray.length] = tempTeam.unitOfWorkCompleted;\n\n tempTeam.unitOfWorkCompleted = 0;\n }\n}",
"addGame(opponent, teamPoints, opponentPoints) {\n const game = {\n opponent,\n teamPoints,\n opponentPoints\n }\n //pushes to an array\n this._games.push(game)\n }",
"function updateArrays() {\n var storedHighScore = JSON.parse(localStorage.getItem(\"highScore\"));\n\n if (storedHighScore !== null) {\n highScore = storedHighScore;\n }\n\n var storedInitials = JSON.parse(localStorage.getItem(\"initials\"));\n\n if (storedInitials !== null) {\n initials = storedInitials;\n }\n}",
"function seedPlayerData(){\n\tconsole.info('seeding player data');\n \tconst seedData = [];\n \tfor (let i=1; i<=10; i++) {\n \tseedData.push({\n \t\tfirstName: faker.name.firstName(),\n \tlastName: faker.name.lastName(),\n \t\tstatus: faker.lorem.word(),\n \t\tpreferredPosition: faker.lorem.word()\n \t});\n\t}\n\tconsole.log('SEED DATA: '+seedData[0].firstName);\n \treturn Player.insertMany(seedData);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a named token generator. | getTokenGenerator (name) {
return get (this._tokenGenerators, name);
} | [
"function getNextToken(){\n currentToken = tokens[0];\n tokens.shift();\n}",
"forName(name) {\n let loader = ServiceLoader.load(\"io.swagger.codegen.CodegenConfig\");\n let availableConfigs = new StringBuilder();\n for (const config of loader) {\n if ((config.getName() === name)) {\n return config;\n }\n availableConfigs.append(config.getName()).append(\"\\n\");\n }\n try {\n return Class.forName(name).newInstance();\n }\n catch (e) {\n throw new Error(\"Can\\'t load config class with name \".concat(name) + \" Available: \" + availableConfigs.toString(), e);\n }\n }",
"function runGenerator(generatorName, \n// tslint:disable-next-line: no-any typings issues in yeoman\noptions = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const templateName = options['templateName'] || generatorName;\n const env = yield (options['env'] || createYeomanEnvironment());\n logger.info(`Running template ${templateName}...`);\n logger.debug(`Running generator ${generatorName}...`);\n const generators = env.getGeneratorsMeta();\n const generator = generators[generatorName];\n if (!generator) {\n logger.error(`Template ${templateName} not found`);\n throw new Error(`Template ${templateName} not found`);\n }\n return new Promise((resolve, reject) => {\n env.run(generatorName, {}, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n });\n}",
"defaultToken(){}",
"function generateUuid() {\n let uuid = token();\n return uuid;\n}",
"get(name) {\n if (this.current.hasOwnProperty(name)) {\n return this.current[name];\n } else {\n return this.builtins[name];\n }\n }",
"function genInput(name, value) {\n var input = document.createElement('input');\n input.name = name;\n input.value = value;\n return input;\n }",
"static getParser (name) {\n return require(`./parsers/${name}.js`);\n }",
"generateAuthTokens(clientName) {\n var self = this;\n self.getClientConfig(clientName).then(function (clientConfig) {\n const courseraCodeURI = util.format(\n COURSERA_CODE_URI,\n clientConfig.scope,\n COURSERA_CALLBACK_URI + clientConfig.clientId,\n clientConfig.clientId);\n startServerCallbackListener();\n (async () => {\n await open(courseraCodeURI);\n })();\n }).catch(function (error) {\n console.log(error);\n });\n }",
"getMacro(name) {\n const len = this.stack.length - 1;\n for (let i = len; i >= 0; i--) {\n const inst = this.stack[i]._getMacro(name);\n if (inst !== null) {\n return inst;\n }\n }\n return null;\n }",
"_getExpansion(name) {\n const definition = this.macros.get(name);\n\n if (definition == null) {\n // mainly checking for undefined here\n return definition;\n }\n\n const expansion = typeof definition === \"function\" ? definition(this) : definition;\n\n if (typeof expansion === \"string\") {\n let numArgs = 0;\n\n if (expansion.indexOf(\"#\") !== -1) {\n const stripped = expansion.replace(/##/g, \"\");\n\n while (stripped.indexOf(\"#\" + (numArgs + 1)) !== -1) {\n ++numArgs;\n }\n }\n\n const bodyLexer = new Lexer(expansion, this.settings);\n const tokens = [];\n let tok = bodyLexer.lex();\n\n while (tok.text !== \"EOF\") {\n tokens.push(tok);\n tok = bodyLexer.lex();\n }\n\n tokens.reverse(); // to fit in with stack using push and pop\n\n const expanded = {\n tokens,\n numArgs\n };\n return expanded;\n }\n\n return expansion;\n }",
"function createToken(){\n\t\t\treturn crypto.randomBytes(16).toString(\"hex\");\n\t\t}",
"Identifier() {\n const name = this._eat(\"IDENTIFIER\").value;\n return {\n type: \"Identifier\",\n name,\n };\n }",
"processNamedClass() {\n if (!this.tokens.matches2(tt._class, tt.name)) {\n throw new Error(\"Expected identifier for exported class name.\");\n }\n const name = this.tokens.identifierNameAtIndex(this.tokens.currentIndex() + 1);\n this.processClass();\n return name;\n }",
"function promptGeneratorSelection(options) {\n return __awaiter(this, void 0, void 0, function* () {\n options = options || {};\n const env = yield (options['env'] || createYeomanEnvironment());\n const generatorName = yield util_1.prompt(createSelectPrompt(env));\n yield runGenerator(generatorName, { templateName: getDisplayName(generatorName), env: env });\n });\n}",
"function getGeneratorMeta(rootDir, defaultName, defaultDescription) {\n let name = defaultName;\n let description = defaultDescription;\n if (rootDir && rootDir !== 'unknown') {\n try {\n const metapath = findup('package.json', { cwd: rootDir });\n const meta = JSON.parse(fs.readFileSync(metapath, 'utf8'));\n description = meta.description || description;\n name = meta.name || name;\n }\n catch (error) {\n if (error.message === 'not found') {\n logger.debug('no package.json found for generator');\n }\n else {\n logger.debug('unable to read/parse package.json for generator', {\n generator: defaultName,\n err: error.message,\n });\n }\n }\n }\n return { name, description };\n}",
"function getGuestToken(callback) {\n requests.getGuestToken(function (response) {\n if (response.success) {\n guestToken = response.token;\n callback && callback();\n }\n });\n}",
"function getDisplayName(generatorName) {\n // Breakdown of regular expression to extract name (group 3 in pattern):\n //\n // Pattern | Meaning\n // -------------------------------------------------------------------\n // (generator-)? | Grp 1; Match \"generator-\"; Optional\n // (polymer-init)? | Grp 2; Match \"polymer-init-\"; Optional\n // ([^:]+) | Grp 3; Match one or more characters != \":\"\n // (:.*)? | Grp 4; Match \":\" followed by anything; Optional\n return generatorName.replace(/(generator-)?(polymer-init-)?([^:]+)(:.*)?/g, '$3');\n}",
"getGetterName () {\n\t\tconst definition = this.definition;\n\t\tlet getterName;\n\n\t\tgetterName = definition.getter;\n\n\t\tif (!getterName) {\n\t\t\tconst name = definition.name;\n\t\t\tconst Name = (name.substr(0, 1).toUpperCase() + name.substr(1));\n\n\t\t\tgetterName = ('get' + Name);\n\t\t}\n\n\t\treturn getterName;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the display to show the specified time_frame | function displayTime(time_frame) {
label.text(Math.floor(time_frame));
//drawCloud(total_data[ Math.round(time_frame -1)]);
drawCloud(targeted_data[ Math.floor(time_frame -1)]);
} | [
"function updateDisplay(display_frame_name) \n{ \n var interval = 5000; \n var display_frame = getDisplayFrame(display_frame_name); \n \n if (display_frame.is_viewed == true) \n { \n makeDisplayRequest(display_frame_name); \n if (display_frame.viewed_l.length != 0) \n { \n window.frames[display_frame_name].location.href = getGifURL(display_frame_name); \n } \n } \n var this_function_call = \"updateDisplay('\" + display_frame_name + \"')\"; \n setTimeout(this_function_call, interval); \n}",
"function updateDisplayTimeRange() {\n if (model.properties.actualDuration === null || model.properties.actualDuration === Infinity) {\n return;\n }\n updatePropertyRange('displayTime', 0, model.properties.actualDuration);\n }",
"function refreshMainTimeView() {\n setText(document.querySelector(\"#text-main-hour\"),\n addLeadingZero(Math.floor(setting.timeSet / 3600), 2));\n setText(document.querySelector(\"#text-main-minute\"),\n addLeadingZero(Math.floor(setting.timeSet / 60) % 60, 2));\n setText(document.querySelector(\"#text-main-second\"),\n addLeadingZero(setting.timeSet % 60, 2));\n applyStyleTransition(document.querySelector(\"#box-hand-hour\"),\n ROTATE_DATA_HAND, \"START\", \"END\", (setting.timeSet % 43200) / 43200);\n applyStyleTransition(document.querySelector(\"#box-hand-minute\"),\n ROTATE_DATA_HAND, \"START\", \"END\", (setting.timeSet % 3600) / 3600);\n applyStyleTransition(document.querySelector(\"#box-hand-second\"),\n ROTATE_DATA_HAND, \"START\", \"END\", (setting.timeSet % 60) / 60);\n }",
"function updateTime() {\n const datetime = tizen.time.getCurrentDateTime();\n const hour = datetime.getHours();\n const minute = datetime.getMinutes();\n const second = datetime.getSeconds();\n\n const separator = second % 2 === 0 ? \":\" : \" \";\n\n $(\"#time-text\").html(padStart(hour.toString()) + separator + padStart(minute.toString()));\n\n // Update the hour/minute/second hands\n rotateElements((hour + (minute / 60) + (second / 3600)) * 30, \"#hands-hr-needle\");\n rotateElements((minute + second / 60) * 6, \"#hands-min-needle\");\n clearInterval(interval);\n if (!isAmbientMode) {\n let anim = 0.1;\n rotateElements(second * 6, \"#hands-sec-needle\");\n interval = setInterval(() => {\n rotateElements((second + anim) * 6, \"#hands-sec-needle\");\n anim += 0.1;\n }, 100);\n }\n }",
"function updateTimeElapsed() {\n var time = formatTime(Math.round(video.currentTime));\n timeElapsed.innerText = formatTimeHumanize(time);\n timeElapsed.setAttribute('datetime', `${time.hours}h ${time.minutes}m ${time.seconds}s`);\n }",
"displayTimer() {\n if (this.timer.classList.contains('gm-timer-hidden')) {\n this.timer.classList.remove('gm-timer-hidden');\n this.displayInterval = setInterval(this.displayTimer.bind(this), 1000);\n }\n\n const endTime = new Date();\n\n // compute seconds\n let timeDiff = endTime - this.startTime;\n timeDiff /= 1000;\n const seconds = Math.round(timeDiff % 60);\n\n // compute minutes\n timeDiff = Math.floor(timeDiff / 60);\n const minutes = Math.round(timeDiff % 60);\n\n this.timer.innerHTML = ('0' + minutes).slice(-2) + ':' + ('0' + seconds).slice(-2);\n\n // if the screencast is 3min long, we stop it\n if (minutes === MAX_SCREENCAST_LENGTH_IN_MINUTES) {\n this.stopRecording();\n }\n }",
"function onTimeUpdate(e) {\n var newTime = Math.floor(video.currentTime);\n if (newTime != timeInt) {\n timeInt = newTime;\n time_str = toTimeString(timeInt);\n updateTimeBar();\n }\n}",
"updateTimeProperties () {\r\n this.timeAtThisFrame = new Date().getTime();\r\n\r\n // divide by 1000 to get it into seconds\r\n this.time = (this.timeAtThisFrame - this.timeAtFirstFrame) / 1000.0;\r\n\r\n this.deltaTime = (this.timeAtThisFrame - this.timeAtLastFrame) / 1000.0;\r\n this.timeAtLastFrame = this.timeAtThisFrame;\r\n\r\n // update and set our scene time uniforms\r\n this.t = this.time / 10;\r\n this.dt = this.deltaTime;\r\n }",
"refresh(timeNow, enableAnimation) {\n }",
"function updateTime() {\n let label = moment().format(timeFormat);\n\n trayIcon.setTitle(label);\n}",
"function updateVideoCurrentTime() {\n let curtime = convertSecondsToMinutes(video.currentTime);\n videotime.innerHTML = curtime+' / '+videoduration;\n }",
"function setCurrentTime() {\n\t\tvar total = player.currentTime;\n\t\tcurrentTimeElement.innerHTML = timeFormat(total);\n\t}",
"_showFirstFrame() {\n if (!this._video.isPlaying) {\n this._video.getVideoElement().currentTime = 0;\n }\n }",
"function display24HrTime(hour, min, sec) {\n document.getElementById(\"clock-time\").innerText = `${hour} : ${min} : ${sec}`;\n setTimeout(getTime, 1000);\n}",
"function draw_display(video, context, width, height)\n {\n context.drawImage(video, 0, 0, width, height);\n context.drawImage(active_filter, 0, 0, width, height);\n display_timeout = setTimeout(draw_display, 10, video, context, width, height);\n }",
"updateTimeWindow(timeWindow){\n var oldWindow = this.timeWindow ;\n this.scaleTimeWindow.setUniform('oldWindow',oldWindow ) ;\n this.scaleTimeWindow.setUniform('newWindow',timeWindow ) ;\n this.timeWindow = timeWindow ;\n this.scaleTimeWindow.render() ;\n this.wA2b.render() ;\n this.hist.setUniform('shift',0) ;\n this.hist.render() ;\n this.wA2b.render() ;\n this.render() ;\n return ;\n }",
"updateVideoTime(videoPlayer, time) {\n videoPlayer.currentTime = time;\n \n }",
"function updateShotClock () {\n\tvar printShotClockTime = '';\n\tif (CURRENT_SHOT_CLOCK_TIME === 0) {\n\t\tdocument.getElementById('buzzer').play();\n\t\tstopClock();\n\t}\n\tif (CURRENT_SHOT_CLOCK_TIME < SHOT_CLOCK_TIME_CUTOFF) {\n\t\t$('#shotclocktimer').css('color', 'red');\n\t}\n\tvar formattedShotClockTime = msToTime(CURRENT_SHOT_CLOCK_TIME);\n\tif (CURRENT_SHOT_CLOCK_TIME >= TIME_CUTOFF) {\n\t\t// Greater than TIME_CUTOFF\n\t\tprintShotClockTime = formattedShotClockTime[1] + ':' + formattedShotClockTime[2];\n\t} else {\n\t\t// Less than TIME_CUTOFF\n\t\tvar ms = formattedShotClockTime[3];\n\t\tms = ms / 100;\n\t\tprintShotClockTime = parseInt(formattedShotClockTime[2]) + '.' + ms;\n\t}\n\t$('#shotclocktimer').text(printShotClockTime);\n}",
"function displayTime(hours,miutes,seconds,milliseconds){\n\t\tdocument.getElementById(\"timerBoard\").innerHTML = padZero(hours,2)+\":\"+padZero(minutes,2)+\":\"+padZero(seconds,2)+\":\"+padZero(milliseconds,3);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produces forum search form. | function forumSearchForm(root) {
document.write(
"<form method='POST' action='http://www.gridgainsystems.com/jiveforums/search.jspa' target='forum' style='margin: 1px; padding: 1px'>" +
"" +
"<input class='search_text' type='text' style='color: #ccc' onClick='this.value=\"\"; this.style.color=\"#333\"' name='q' value=' find...' size='20' maxlength='100'>" +
" " +
"<input title='Search Forum' class='search_button' name='button' type='submit' value='f o r u m'>" +
"</form>"
);
} | [
"function SearchForm(enableClear, parentEl, options){\n options = this.options = mergeObjs(options,{\n 'buttonText' : 'Search',\n 'hintString' : 'Search the map!'\n });\n var z=this,\n input,\n form=z.form=createEl('form','gsc-search-box',[\n createEl('table','gsc-search-box',[createEl('tbody',null,[\n createEl('tr',null,[\n createEl('td','gsc-input',[input=z['input']=createEl('input','gsc-input',null,{\n 'type' : 'text',\n 'autocomplete' : 'off',\n 'size' : 10,\n 'name' : 'search',\n 'title' : 'search',\n 'value' : options['hintString'],\n 'onfocus' : createClosure(z,SearchForm.prototype.toggleHint),\n 'onblur' : createClosure(z,SearchForm.prototype.toggleHint)\n })]),\n createEl('td','gsc-search-button',[z.button=createEl('input','gsc-search-button',null,{\n 'type' : 'submit',\n 'value' : options['buttonText'],\n 'title' : 'search'\n })]),\n z.clearButton=(enableClear ? createEl('td','gsc-clear-button',[createEl('div','gsc-clear-button',[' '],{\n 'title' : 'clear results',\n 'onclick' : function(){\n z.form['clearResults']()\n }\n })]) : null)\n ])\n ])],{\n 'cellspacing':0,\n 'cellpadding':0\n }),\n createEl('table','gsc-branding',[createEl('tbody',null,[\n createEl('tr',null,[\n createEl('td','gsc-branding-user-defined'),\n createEl('td','gsc-branding-text',[createEl('div','gsc-branding-text',['powered by'])]),\n createEl('gsc-branding-img-noclear',[createEl('img','gsc-branding-img-noclear',null,{\n 'src' : 'http://www.google.com/uds/css/small-logo.png'\n })])\n ])\n ])])\n ],{\n 'accept-charset' : 'utf-8'\n });\n if(parentEl){\n parentEl.appendChild(form)\n }\n }",
"function showSearch() {\n\t\ttm.fromTo($searchForm, .3, {'display': 'none', y: -220}, {'display': 'block', y: 0, ease: Power3.easeInOut})\n\t}",
"function emxCommonAutonomySearch() {\n //=================================================================\n // The URL parameters for emxFullSearch.jsp\n //=================================================================\n \n //\n //This is an optional parameter that can pass to specify the name of the function to be \n //invoked once submit button is clicked on the search component\n this.callbackFunction = null; // At this time this parameter is not working, so use onSubmit property\n\n //\n this.cancelLabel = null;\n\n //\n //List of OIDs to exclude from the search results\n this.excludeOID = null; \n\n //\n //JPO provided by Apps that returns list of OIDs to not display in results. This is used \n //to further filter the results. The method should return a StringList of OIDs to exclude \n //from the search results\n this.excludeOIDprogram = null;\n \n //\n //The parameter specifies the name of the form in the form-based search. It is an optional parameter.\n this.formName = null;\n \n //\n //The parameter specifies the name of the frame that contains the form. It is an optional parameter\n this.frameName = null;\n \n // List of indices and their default/allowed values for the initial search results\n this.field = null;\n //\n //This parameter is deprecated. It is present for the backward compatibility.\n // If user does txtType=\"type_abc\" then field is set to \"TYPES=txt_abc\"\n this.txtType = null;\n\n //\n //Optional parameter - Name of the field to which the selected value from the search results to be returned.\n this.fieldNameActual = null;\n \n //\n //Optional parameter ? If the display value is different from Actual value - Name of the field to which \n //the display value from the search results to be returned\n this.fieldNameDisplay = null;\n \n //\n //The optional parameter will be used to limit the list of indexed attributes displayed on a Form Based search.\n //This will not apply to Navigation based searches. Comma separated list\n this.formInclusionList = null;\n\n //\n //The parameter will be used to either show or hide the header on the search dialog. The header includes \n //the search text box along with the Search and Reset buttons and the page level toolbar\n this.hideHeader = null;\n \n //\n //All the selectable(s) of search criteria are optional by default. User can provide a coma separated \n //list of search criteria that are passed as part of URL parameter mandatorySearchParam to make them mandatory.\n //These refinements will be mandatory and displayed as disabled checked checkboxes in the breadcrumb display.\n //The user will not be allowed to uncheck these search criteria. The values passed as mandatorySearchParam must \n //be a part of the URL parameters.\n this.mandatorySearchParam = null;\n \n //\n //By default, the Search in Collection toolbar button will be displayed on the toolbar when in Navigate mode.\n //Can be turned off by this parameter. Recommended that this is not used when using type specific tables, \n //expandJPOs or relationships in the results table.\n this.searchCollectionEnabled = null;\n\n //\n //Controls whether the table page adds a column of check boxes or radio buttons in the left most column of \n //the search results table. The value passed can be multiple/single/none. \n //multiple ? to display a check box \n //single ? to display radio button.\n //none- no additional column is displayed for selection\n this.selection = null;\n\n //\n //The parameter value will allow display of the OOTB command ?AEFSaveQuery? on the toolbar. \n this.showSavedQuery = \"false\";\n\n //\n //If submitLabel is passed, as an URL parameter then the button will be displayed with the value passed else \n //will be displayed with label ?Done?.\n //This button will be shown only if Callback function is passed in the URL. This display can be suppressed \n //by passing additional parameter submitLink = false. \n //The value can be static text or a property key.\n //This is the existing URL parameter supported by structure browse component\n this.submitLabel = null;\n \n //\n //This parameter is used to define the callback URL. This could be the jsp page to perform the post processing \n //on an Add Existing command.\n //This is the existing URL parameter supported by structure browse component\n this.submitURL = \"../components/emxCommonAutonomySearchSubmit.jsp\";\n \n //\n //This is the table that will be passed to Indented Table to display the searched results\n this.table = \"AEFGeneralSearchResults\";\n \n //\n //This parameter is used to define a custom toolbar, if required for displaying the context \n //search using consolidated search view component. This is the toolbar that will be displayed \n //on the search results frame\n this.toolbar = null;\n\n //\n //This parameter will override the system setting for FormBased vs. Navigation Based.\n this.viewFormBased = null;\n\n \n //=================================================================\n // Other configurable parameters\n //=================================================================\n \n //\n // The height of the search window\n this.windowHeight = 600;\n \n //\n // The width of the search window\n this.windowWidth = 800;\n \n //\n // The Registered Suite parameter to be passed to JSP is needed.\n this.registeredSuite = null;\n \n //\n // The \"program\" parameter for Autonomy Search\n this.searchProgram = null;\n \n //\n //The javascript path of the callback submit javascript function.\n //Selected results will be submitted to this function. In general,\n //when the search is invoked from a chooser button on any dialog, we may pass \"getTopWindow().getWindowOpener().mySubmitCallback\"\n //where function mySubmitCallback is defined in the dialog page.\n //This is mandatory property to set.\n //\n //Example of the callback function\n //function mySubmitCallback(arrSelectedObjects) {\n // alert(\"DEBUG: ->mySubmitCallback \"+ arrSelectedObjects.length);\n // \n // for (var i = 0; i < arrSelectedObjects.length; i++) {\n // var objSelection = arrSelectedObjects[i];\n // objSelection.debug(); // Alerts the following properties\n // ...\n // objSelection.parentObjectId\n // objSelection.objectId\n // objSelection.type\n // objSelection.name\n // objSelection.revision\n // objSelection.relId\n // objSelection.objectLevel\n // ...\n // }\n //}\n this.onSubmit = null;\n \n //=================================================================\n // Opens the Autonomy Search window using the configured parameters\n //=================================================================\n this.open = function () {\n var strURL = \"../common/emxFullSearch.jsp\";\n \n // Collect the url parameters\n var arrParams = new Array;\n if (this.callbackFunction != null) {\n arrParams[arrParams.length] = \"callbackFunction=\" + this.callbackFunction;\n }\n if (this.cancelLabel != null) {\n arrParams[arrParams.length] = \"cancelLabel=\" + this.cancelLabel;\n }\n if (this.excludeOID != null) {\n arrParams[arrParams.length] = \"excludeOID=\" + this.excludeOID;\n }\n if (this.excludeOIDprogram != null) {\n arrParams[arrParams.length] = \"excludeOIDprogram=\" + this.excludeOIDprogram;\n }\n if (this.formName != null) {\n arrParams[arrParams.length] = \"formName=\" + this.formName;\n }\n if (this.frameName != null) {\n arrParams[arrParams.length] = \"frameName=\" + this.frameName;\n }\n if (this.field != null) {\n arrParams[arrParams.length] = \"field=\" + this.field;\n }\n else {\n if (this.txtType != null) {\n arrParams[arrParams.length] = \"field=TYPES=\" + this.txtType;\n }\n }\n if (this.fieldNameActual != null) {\n arrParams[arrParams.length] = \"fieldNameActual=\" + this.fieldNameActual;\n }\n if (this.fieldNameDisplay != null) {\n arrParams[arrParams.length] = \"fieldNameDisplay=\" + this.fieldNameDisplay;\n }\n if (this.formInclusionList != null) {\n arrParams[arrParams.length] = \"formInclusionList=\" + this.formInclusionList;\n }\n if (this.hideHeader != null) {\n arrParams[arrParams.length] = \"hideHeader=\" + this.hideHeader;\n }\n if (this.mandatorySearchParam != null) {\n arrParams[arrParams.length] = \"mandatorySearchParam=\" + this.mandatorySearchParam;\n }\n if (this.searchCollectionEnabled != null) {\n arrParams[arrParams.length] = \"searchCollectionEnabled=\" + this.searchCollectionEnabled;\n }\n if (this.selection != null) {\n arrParams[arrParams.length] = \"selection=\" + this.selection;\n }\n if (this.showSavedQuery != null) {\n arrParams[arrParams.length] = \"showSavedQuery=\" + this.showSavedQuery;\n }\n if (this.submitLabel != null) {\n arrParams[arrParams.length] = \"submitLabel=\" + this.submitLabel;\n }\n if (this.table != null) {\n arrParams[arrParams.length] = \"table=\" + this.table;\n }\n if (this.toolbar != null) {\n arrParams[arrParams.length] = \"toolbar=\" + this.toolbar;\n }\n if (this.viewFormBased != null) {\n arrParams[arrParams.length] = \"viewFormBased=\" + this.viewFormBased;\n }\n if (this.searchProgram != null) {\n arrParams[arrParams.length] = \"program=\" + this.searchProgram;\n }\n if (this.registeredSuite != null) {\n arrParams[arrParams.length] = \"Registered Suite=\" + this.registeredSuite;\n }\n if (this.onSubmit != null) {\n arrParams[arrParams.length] = \"onSubmit=\" + this.onSubmit;\n }\n if (this.submitURL != null) {\n arrParams[arrParams.length] = \"submitURL=\" + this.submitURL;\n }\n \n var strParams = arrParams.join(\"&\");\n strURL += \"?\" + strParams;\n\n // Open the search window\n showModalDialog(strURL, this.windowWidth, this.windowHeight, true);\n }//End: open()\n}//End: emxCommonAutonomySearch()",
"function do_search() {\n var $form = $('#search-form');\n var option = $form.find('select[name=action] option[selected]').val();\n if (!option) return false;\n var search_terms = $form.find('input[name=q]').val();\n var url = str_concat(option , '?q=' , search_terms);\n adr(url);\n return false;\n }",
"function setGenerateSearchElement(elt,config){if(config.logLevel>0)alert(\"running setGenerateSearchElement\");\nvar dynamicHTML=false;\nif(dynamicHTML){ // this kind of code may be needed for IE; \nvar A=[[\"form\",\"action\",\"javascript:void(0)\",\"name\",\"searchForm\",\"id\",\"searchForm\",\n \"onsubmit\",\n \"thePlayerManager.lookup(document.forms.searchForm.searchfield.value,document.forms.searchForm)\"],\n [\"input\",\"id\",\"searchfield\",\"name\",\"searchfield\",\"type\",\"text\",\"size\",\"35\",\n \"title\",\"search text; word for dict, can be reg exp for script or commentary\"],\n [\"input\",\"id\",\"searchbutton\",\"value\",\"Search\",\"type\",\"button\",\n \"onclick\",\"thePlayerManager.lookup(this.form.searchfield.value,this.form,event)\",\n \"title\",\"search for word in dict, or for text in page or (with ctrl key down) repository\"],\n [\"br\"],\n [[\"div\",\"id\",\"boxes\"],\n [\"input\",\"onchange\",\"checkChanger.change(this)\",\"type\",\"checkbox\",\n \"checked\",\"checked\", \"name\",\"dict\", \"id\",\"dictCheckbox\"],\n [null,\"dictionary\\u00A0\\u00A0\"],\n [\"input\",\"onchange\",\"checkChanger.change(this)\",\"type\",\"checkbox\",\n \"checked\",\"checked\", \"name\",\"script\", \"id\",\"scriptCheckbox\"],\n [null,\"script\\u00A0\\u00A0\"],\n [\"input\",\"onchange\",\"checkChanger.change(this)\",\"type\",\"checkbox\",\n \"checked\",\"checked\", \"name\",\"comm\", \"id\",\"commCheckbox\"] ,\n [null,\"commentary\\u00A0\\u00A0\"]\n ]\n ];\n var X=newElt(A); elt.appendChild(X);\n} else {\n\nvar S= // ' <div id=\"search\">\\n'+\n' <form action=\"javascript:void(0)\" name=\"searchForm\"\\n'+\n' onsubmit=\"thePlayerManager.lookup(document.forms.searchForm.searchfield.value,document.forms.searchForm)\">\\n'+\n' <input id=\"searchfield\" type=\"text\" size=\"35\" \\n'+\n' title=\"search text; word for dict, can be reg exp for script or commentary\" />\\n'+\n' \\n'+\n' <input id=\"searchbutton\" type=\"button\" value=\"Search\" \\n'+\n' onclick=\"thePlayerManager.lookup(this.form.searchfield.value,this.form,event)\" \\n'+\n' title=\"search for word in dict, or for text in page or (with ctrl key down) repository\" /> <br/> \\n'+\n' <div id=\"boxes\">\\n'+\n' <input onchange=\"checkChanger.change(this)\" type=\"checkbox\" \\n'+\n' checked=\"checked\" name=\"dict\" id=\"dictCheckbox\" />dictionary\\u00A0\\u00A0\\n'+\n' <input onchange=\"checkChanger.change(this)\" type=\"checkbox\" \\n'+\n' name=\"script\" id=\"scriptCheckbox\" />script\\u00A0\\u00A0\\n'+\n' <input onchange=\"checkChanger.change(this)\" type=\"checkbox\" \\n'+\n' name=\"comm\" id=\"commCheckbox\" />commentary\\u00A0\\u00A0</div>\\n'+\n' </form>\\n';\n// '</div>';\nelt.innerHTML=S;\n}\nif(config.logLevel>0)alert(\"done setGenerateSearchElement\");\n}",
"function doSearch(){\n document.SearchCustomer.search.value = true;\n document.SearchCustomer.curpos.value=0;\n submit('SearchCustomer');\n }",
"function markupSearch() {\n var _html = '';\n semdata.forEach( function(message) { _html += '<div id=\"data-title\">' + message.value + \n \"<input type=\\\"button\\\" class=\\\"removebutton\\\" onclick='ldinjs.remove(\\\"\"+\n message.id+\"\\\")' value=\\\"Remove\\\">\";\n //if (0 < message.data.size ) {\n _html += \"<input type=\\\"button\\\" class=\\\"removebutton\\\" onclick='drillDown.createSingleDatumList(\\\"\"+\n message.id+\"\\\", \\\"id-data\\\")' value=\\\"Show Details\\\">\";\n //}\n if (0 < message.similarity.length ) {\n _html += \"<input type=\\\"button\\\" class=\\\"removebutton\\\" onclick='sims.markUpSimilarity(\\\"\"+\n message.id+\"\\\")' value=\\\"Show Similar\\\">\";\n }\n _html += '</div>';\n });\n $( \"#results\" ).html(_html).prependTo( \"#results\" );\n $( \"#results\" ).scrollTop( 0 );\n }",
"function do_search() {\n var query = input_box.val().toLowerCase();\n\n if (query && query.length) {\n if (selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if (query.length >= settings.minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function () {\n run_search(query);\n }, settings.searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }",
"function search()\n{\n\tvar searchText = searchInput.value;\n\n\t// if input's empty\n\t// displaying everything\n\tif (searchText == \"\")\n\t{\n\t\tshowAllFilteredWordEntries();\n\t\treturn;\n\t}\n\n\t// hiding everything except the matched words\n\tfor (let i = 0; i < loadedData.length; i++)\n\t{\n\t\tlet entry = getFilteredWordEntry(i);\n\t\tvar regx = new RegExp(searchText);\n\t\tif (regx.test(loadedData[i]))\n\t\t\tentry.hidden = false;\n\t\telse\n\t\t\tentry.hidden = true;\n\t}\n}",
"function searchFunction () {\n activateSearch($searchInput, 'input');\n activateSearch($submit, 'click');\n}",
"function updateSearchFormFields(ev) {\n let searchForm = document.getElementById(\"participant_search_form\");\n let form = ev.target.closest(\"[data-js-search-filter]\");\n let checked = [...form.querySelectorAll(\":checked\")];\n let queries = {};\n for (let i = 0; i < checked.length; i++) {\n if (!queries[checked[i].name]) {\n queries[checked[i].name] = [];\n }\n queries[checked[i].name].push(`${checked[i].name}:${checked[i].value}`);\n }\n newQueries = Object.values(queries).map((q) => q.join(\" \"));\n searchForm\n .querySelectorAll(\"input[type='hidden']\")\n .forEach((e) => e.remove());\n for (let i = 0; i < newQueries.length; i++) {\n let input = document.createElement(\"input\");\n input.setAttribute(\"type\", \"hidden\");\n input.setAttribute(\"name\", \"addl_query\");\n input.setAttribute(\"value\", newQueries[i]);\n searchForm.append(input);\n }\n searchForm.querySelector(\"[type='submit']\").click();\n }",
"function populateFormFromUrl() {\n const createSearchItems = Private(SearchItemsProvider);\n const {\n indexPattern,\n savedSearch,\n combinedQuery } = createSearchItems();\n\n if (indexPattern.id !== undefined) {\n timeBasedIndexCheck(indexPattern, true);\n $scope.ui.datafeed.indicesText = indexPattern.title;\n $scope.job.data_description.time_field = indexPattern.timeFieldName;\n\n if (savedSearch.id !== undefined) {\n $scope.ui.datafeed.queryText = JSON.stringify(combinedQuery);\n }\n }\n }",
"function search() {\n\t\tvar searchVal = searchText.getValue();\n\n\t\tsources.genFood.searchBar({\n\t\t\targuments: [searchVal],\n\t\t\tonSuccess: function(event) {\n\t\t\t\tsources.genFood.setEntityCollection(event.result);\n\t\t\t},\n\t\t\tonError: WAKL.err.handler\n\t\t});\n\t}",
"function ajaxFAQsearch(){\n\t$('#faq-page').on('keyup','#s',function(e){\n\t\te.preventDefault();\n\t\tvar $form = $(this).parent().parent();\n var query = $(this).val();\n var $content = $('#accordion-container');\n var url = '';\n\n if ($('body').hasClass('es')) {\n \turl = templateURL + '/ajax-search-es.php';\n }else if($('body').hasClass('it')){\n \turl = templateURL + '/ajax-search-it.php';\n }else{\n \turl = templateURL + '/ajax-search.php';\n }\n\n\t\t$.ajax({\n\t\t\turl: url,\n\t\t\ttype: 'POST',\n\t\t\tdata: {query : query},\n\t\t\tsuccess: function(response) {\n $content.html(response).foundation();\n }\n\t\t});\n\t});\n}",
"function getQuery(winControl) { // getQuery() extracts the user's search query from the Millennium searchtool. winControl is the optional parameter used to select an alternate link display.\nvar searchQuery = \"\";\nif (!document.searchtool) { // This section applies when form name=\"searchtool\" does not exist. This case occurs on a \"no hit\" heading browse display, e.g., a subject search on mcrowave.\n\tvar searchArg = document.getElementsByName('searcharg'); // getting the user's search term\n \tfor (var i=0; i<searchArg.length; i++) {\n\t\tsearchQuery = searchArg[i].value;\n \t\t}\n\t\t\n\tif (document.forms[1]){ // this section changes the value of <option value=\"Y\"> KEYWORD</option> from \"Y\" to \"X\" (because I do not use the \"Y\" searchpage option, srchhelp_Y). Because the \"searchtool\" form is unnamed, I am using the DOM structure to address the option value. Because there is no guarantee that the structure will be stable with new software releases, this manipulation may not always work.\n\tif (document.forms[1].elements[0]){\n\tif (document.forms[1].elements[0].options[0]){\n\tif (document.forms[1].elements[0].options[0].value == \"Y\"){ \n\tdocument.forms[1].elements[0].options[0].value = \"X\";\n\t}}}}\n}\n\nelse { // document.searchtool exists on item browse and bib record displays\n\tsearchQuery = document.searchtool.searcharg.value; // get the search term\n\t\nvar testForSearchtype = document.searchtool.searchtype; // this section changes the searchtype Option value from Y to X. For our OPAC, \"Y\" (srchhelp_Y.html, keyword search) is an unnecessary duplicate, and I make this page automatically nav to /search. This caused a problem when customers used searchtool to perform a KW that retrieved no hits; users were taken to opacmenu.html with no No Entries Found message. This code is my workaround solution to this problem.\nif (typeof testForSearchtype != \"undefined\"){\n\t\tfor (var j=0; j<document.searchtool.searchtype.options.length; j++){\n\t\t\tif (document.searchtool.searchtype.options[j].value == \"Y\"){\n\t\t\t\tdocument.searchtool.searchtype.options[j].value = \"X\";\n\t\t\t\t}\n\t\t\t}\t\n\t}\n} // end of else\n\nif (searchQuery.length > 0) { // what to do if there is a search term\n\tvar WSCheck = searchQuery.search(/\\s/);\n\tif (WSCheck != -1) { // what to do if there is a whitespace character in the search term, indicating a multi-term query\n\t\t//searchQuery = searchQuery.replace(/(\\S+)(\\s.*)/, \"$1\"); // retains the first string of characters, and throws away the following whitespace and any subsequent characters \n\t\t//searchQuery = searchQuery.replace(/^(\\S+)(\\s)(\\S+)((\\s.*)?)/, \"$1$3\"); // removes the first whitespace, and throws away an characters following a second whitespace\n\t\tsearchQuery = searchQuery.replace(/^(\\S+)(\\s)(\\S+)(\\s)(\\S+)((\\s.*)?)/, \"$1$3$5\"); // removes the first and second whitespace, and throws away the third whitespace and any subsequent characters.\n\t\t}\n\tif (searchQuery != \"***\") { // Again, what to do next with the search term - but filtering out instances in which the search term is \"***\"\n\t\tvar termArg = \"insertionPoint\"; // \"insertionPoint\" is the id value of the placeholder tag that will eventually display the targetURL (e.g., see bib_display.html).\n\t\tvar termID = document.getElementById(termArg);\n\t\t\tif (!termID) {}\n\t\t\telse { // looking for the condition of the page having a tag with id=\"insertionPoint\".\n\t\t\tvar linkStringfromDocTarget = getDocTarget(searchQuery,winControl); // pass searchQuery to getDocTarget() function, and return a value (a targetURL/linkString)\n\t\t\tif (linkStringfromDocTarget != \"\") { // what to do if there is a OneSearch link to offer\n\t\t\t\ttermID.innerHTML = linkStringfromDocTarget; // replace the HTML of the insertionPoint tag with the targetURL/linkString. NOTE that this only affects the FIRST instance of \"insertionPoint\" on the page. Other instances are ignored.\n\t\t\t\tvar termArg2 = \"displaySwitchforMultisearch\"; // These several lines manage the display of the link to the Library's Multisearch. I want to hide this link when a OneSearch link exists so that it does not compete with the OneSearch link. This display management is performed with a span id=\"displaySwitchforMultisearch\", which is used on srchhelp_X, and the WebBridge resource definition for Multisearch.\n\t\t\t\tvar termID2 = document.getElementById(termArg2);\n\t\t\t\tif (!termID2) {}\n\t\t\t\telse {\n\t\t\t\t\ttermID2.style.display = \"none\"; \n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} // end searchQuery.length check condition \n} // end getQuery()",
"function appendSearchBar() {\n const header = document.querySelector('.page-header');\n const searchDiv = document.createElement('form');\n searchDiv.innerHTML = `<input placeholder=\"Search for students...\"><button>Search</button>`;\n searchDiv.className = 'student-search';\n header.appendChild(searchDiv);\n\n searchDiv.addEventListener('submit', (e) => {\n e.preventDefault();\n let searchValue = e.target[0].value;\n searchItem(listItems, searchValue);\n e.target[0].value = '';\n });\n}",
"function do_search() {\n var query = input_box.val();\n\n if((query && query.length) || !$(input).data(\"settings\").minChars) {\n if(selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if(query.length >= $(input).data(\"settings\").minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function(){\n run_search(query);\n }, $(input).data(\"settings\").searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }",
"function showSelectTags(){\n // show form and set the text field to null\n searchTagsForm.style.display = \"block\";\n document.getElementById(\"search\").value = \"\";\n formType = \"selectTags\";\n}",
"function _fnFeatureHtmlFilter ( oSettings )\n\t\t{\n\t\t\tvar sSearchStr = oSettings.oLanguage.sSearch;\n\t\t\tsSearchStr = (sSearchStr.indexOf('_INPUT_') !== -1) ?\n\t\t\t sSearchStr.replace('_INPUT_', '<input type=\"text\" />') :\n\t\t\t sSearchStr===\"\" ? '<input type=\"text\" />' : sSearchStr+' <input type=\"text\" />';\n\t\t\t\n\t\t\tvar nFilter = document.createElement( 'div' );\n\t\t\tnFilter.className = oSettings.oClasses.sFilter;\n\t\t\tnFilter.innerHTML = '<label>'+sSearchStr+'</label>';\n\t\t\tif ( oSettings.sTableId !== '' && typeof oSettings.aanFeatures.f == \"undefined\" )\n\t\t\t{\n\t\t\t\tnFilter.setAttribute( 'id', oSettings.sTableId+'_filter' );\n\t\t\t}\n\t\t\t\n\t\t\tvar jqFilter = $(\"input\", nFilter);\n\t\t\tjqFilter.val( oSettings.oPreviousSearch.sSearch.replace('\"','"') );\n\t\t\tjqFilter.bind( 'keyup.DT', function(e) {\n\t\t\t\t/* Update all other filter input elements for the new display */\n\t\t\t\tvar n = oSettings.aanFeatures.f;\n\t\t\t\tfor ( var i=0, iLen=n.length ; i<iLen ; i++ )\n\t\t\t\t{\n\t\t\t\t\tif ( n[i] != $(this).parents('div.dataTables_filter')[0] )\n\t\t\t\t\t{\n\t\t\t\t\t\t$('input', n[i]).val( this.value );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t/* Now do the filter */\n\t\t\t\tif ( this.value != oSettings.oPreviousSearch.sSearch )\n\t\t\t\t{\n\t\t\t\t\t_fnFilterComplete( oSettings, { \n\t\t\t\t\t\t\"sSearch\": this.value, \n\t\t\t\t\t\t\"bRegex\": oSettings.oPreviousSearch.bRegex,\n\t\t\t\t\t\t\"bSmart\": oSettings.oPreviousSearch.bSmart \n\t\t\t\t\t} );\n\t\t\t\t}\n\t\t\t} );\n\t\t\t\n\t\t\tjqFilter.bind( 'keypress.DT', function(e) {\n\t\t\t\t/* Prevent default */\n\t\t\t\tif ( e.keyCode == 13 )\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t} );\n\t\t\t\n\t\t\treturn nFilter;\n\t\t}",
"function watchForm() {\n // console.log('watchForm() ready');\n $('#js-searchForm').submit(e => {\n e.preventDefault();\n $('#js-results').html('');\n const userInput = $('#js-searchInput').val();\n refineInput(userInput);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
print pseudo legal move list | function printMoveList(moveList) {
var listMoves = ' Move Piece Captured Flag Score\n\n';
for (var index = 0; index < moveList.length; index++) {
let move = moveList[index].move;
listMoves += ' ' + COORDINATES[getSourceSquare(move)] + COORDINATES[getTargetSquare(move)];
listMoves += ' ' + PIECE_TO_CHAR[getSourcePiece(move)] +
' ' + PIECE_TO_CHAR[getTargetPiece(move)] +
' ' + getCaptureFlag(move) +
' ' + moveList[index].score + '\n';
}
listMoves += '\n Total moves: ' + moveList.length;
console.log(listMoves);
} | [
"printLegalMoves () {\n const legalMoves = this._board.legalMoves(this._turn);\n let result = '';\n for (const key in legalMoves) {\n result += key + ' ';\n }\n console.log(result);\n }",
"function printMoves(rover){\n\n for (var i = 0 ; i < rover.travelLog.length ; i++){\n console.log(\"COORDINATES \" + i +\": \" + rover.travelLog[i]);\n }\n console.log(\"COORDINATES \" + i +\": \" + rover.x + \",\" + rover.y);\n}",
"printForward() {\n // Only if the list is not empty\n if (this.#head) {\n let current = this.#head;\n let output = \"\";\n do {\n output += current.value;\n\n if (current.next != this.#head)\n output += \" -> \";\n\n current = current.next;\n } while (current != this.#head);\n\n console.log(output);\n }\n }",
"function make_pretty(ugly_move) {\nvar move = clone(ugly_move);\nmove.san = move_to_san(move, false);\nmove.to = algebraic(move.to);\nmove.from = algebraic(move.from);\n\nvar flags = '';\n\nfor (var flag in BITS) {\nif (BITS[flag] & move.flags) {\n flags += FLAGS[flag];\n}\n}\nmove.flags = flags;\n\nreturn move;\n}",
"printList() {\n // First, let's check if the list is empty\n if(this.isEmpty()) {\n console.log(\"The list is empty!\")\n return;\n }\n // Let's start a runner at the beginning of the singly linked list itself\n var runner = this.head;\n // This string will be added to as we traverse along the SLL\n var string = \"\";\n\n\n // Now we need a way to traverse through the SLL\n\n // If the runner is not null, we're still looking at a node, so we have things to do!\n while(runner != null) {\n // We want to add the node's value to our string, and a fancy little arrow for looks\n string += runner.value + \" -> \";\n // Then, we want to progress the runner to the NEXT node in the SLL\n runner = runner.next;\n }\n \n // Once we've finished moving through the entire list, we want to print the string\n console.log(string);\n }",
"printState(){\n let white = ' ';\n let printFormat = function(card) {\n let pstr = card.elem+white.slice(0,12-card.elem.length);\n if (card.faceUp == true){\n pstr = pstr.toUpperCase();\n }\n return pstr;\n }\n\n console.log('*'.repeat(61));\n console.log('');\n console.log('xxxx '+printFormat(this.grid[0][0])+printFormat(this.grid[0][1])+printFormat(this.grid[0][2])+printFormat(this.grid[0][3])+'xxxx');\n console.log('');\n console.log('xxxx '+printFormat(this.grid[1][0])+printFormat(this.grid[1][1])+printFormat(this.grid[1][2])+printFormat(this.grid[1][3])+'xxxx');\n console.log('');\n console.log('xxxx '+printFormat(this.grid[2][0])+printFormat(this.grid[2][1])+printFormat(this.grid[2][2])+printFormat(this.grid[2][3])+'xxxx');\n console.log('');\n console.log('xxxx '+printFormat(this.grid[3][0])+printFormat(this.grid[3][1])+printFormat(this.grid[3][2])+printFormat(this.grid[3][3])+'xxxx');\n console.log('');\n console.log('*'.repeat(61));\n console.log(this.grid);\n }",
"uci(move) {\n return move.from + move.to + (move.flags === \"p\" ? move.piece : \"\");\n }",
"handleOList(){\n this.sliceString();\n var list = this.selection.split(/\\n/);\n var text = \"\";\n var i = 1;\n list.map(function(word){\n text = text + \" \" + i.toString() + \". \" + word + \"\\n\";\n i = i + 1;\n })\n this.post.value = this.beg + text + this.end;\n }",
"function dumplist(l) { \n var i, rv = []; \n \n rv.push(\"has \"+l.length+\" elements:\"); \n for (i=0; i<l.length; i++) { \n rv.push(\" \"+i+\"\\t\"+l[i].toSpecifier()+ \n \"\\t\"+l[i].markupTag.name); \n } \n return rv.join(\"\\n\"); \n}",
"print() { \n let str = \"\"; \n for (var i = 0; i < this.size(); i++) \n str += this.stack[i] + \" \"; \n console.log(str); \n }",
"printTransitionTable(printConsole){\r\n\t\tvar text = \"\";\r\n\t\tfor(var i=0;i<this.nStates;i++){\r\n\t\t\tif(this.stateHolder[i].isFinal)\r\n\t\t\t\ttext = text.concat(\"*\");\r\n\t\t\ttext = text.concat(this.stateHolder[i].name,\" -> \");\r\n\t\t\tfor(var j=0;j<this.nInputs;j++){\r\n\t\t\t\tvar t2 = this.stateHolder[i].transitions[this.inputs[j]].length;\r\n\t\t\t\ttext = text.concat(\"<br/> \",this.inputs[j],\" : \");\r\n\t\t\t\tfor(var k=0;k<t2;k++){\r\n\t\t\t\t\tvar temp = this.stateHolder[i].transitions[this.inputs[j]][k];\r\n\t\t\t\t\tif(temp == null)\r\n\t\t\t\t\t\ttext = text.concat(\"NULL \");\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\ttext = text.concat(temp.name,\" \");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\ttext = text.concat(\"<br/>\");\r\n\t\t}\r\n\t\ttext = text.concat(\"<br/>Alphabets:<br/>\",this.inputs);\r\n\t\tvar para = document.getElementById(printConsole);\r\n\t\ttext = \"<div style='text-align:left;'><br/>\" + text + \"</div>\";\r\n\t\tpara.innerHTML += text;\r\n\t}",
"print() {\n console.log(this.ranges.map(range => `[${range.toString()})`).join(' '))\n }",
"print() {\n var runner = this.front; // Start at the front\n while (runner !== null) { // While we're not at the end\n console.log(runner.val); // Print value at current node\n runner = runner.next; // Move to next node\n }\n }",
"function displayPosition() {\r\n\tconsole.log(\"Rover Current Position: [\" + myRover.position[0] + \", \" + myRover.position[1] + \"]\");\r\n}",
"drawSequence() {\n\n // chords which are used in the sequence (in the correct order!)\n this.chords = ['C', 'F', 'G', 'Am'];\n\n // get the current sequence\n this.sequence = this.musicMenu.getSequence();\n\n this.chordTexts = [];\n let chord;\n\n // draw each chord of the sequence\n for (let i in this.sequence) {\n\n chord = this.add.text(this.xStart + i * this.distance, this.yPosition, this.chords[this.sequence[i]], this.styles.get(7)).setOrigin(0.5);\n this.chordTexts.push(chord);\n\n }\n\n }",
"function displayMovements(movements, sort = false) {\n // Empty pre-existing container items\n // .innerHTML is similiar to textContent but includes all the html tags\n containerMovements.innerHTML = \"\";\n\n const movs = sort ? movements.slice().sort((a, b) => a - b) : movements;\n\n movs.forEach(function (mov, i) {\n // Determine whether the type of the movement is deposit or withdrawl\n const type = mov > 0 ? \"deposit\" : \"withdrawal\";\n\n // template string that contains the new html code that will construct the class name\n // and string information\n const html = `\n <div class=\"movements__row\">\n <div class=\"movements__type movements__type--${type}\">${\n i + 1\n } ${type}</div>\n <div class=\"movements__value\">${mov}€</div>\n </div>`;\n\n // calls the insertAdjucentHTML on the variable for the movements class/element and\n // inserts the HTML afterbegin, which will place the new element after the beginning\n // of the parent element\n containerMovements.insertAdjacentHTML(\"afterbegin\", html);\n });\n}",
"function showList(a_oItems, g_nLoc){\n \n var s_List = \"\"; \n for (var i=0; i< a_oItems.length; i++){\n s_List = s_List + \"\\n\" + a_oItems[i].Name(g_nLoc); \n } \n return s_List; \n}",
"function write() {\n var length = arguments.length;\n for (var i = 0; i < length; i++) {\n output.print(String(arguments[i]));\n if (i < length - 1)\n output.print(' ');\n }\n}",
"function moveItem(tmpList, body) {\n item.resetOutput();\n let output = item.getOutput();\n // -> Move item to diffrent place - counts with equiping filling magazine etc\n //cartriges handler start\n if (body.to.container === 'cartridges') {\n let tmp_counter = 0;\n for (let item_ammo in tmpList.data[0].Inventory.items) {\n if (body.to.id === tmpList.data[0].Inventory.items[item_ammo].parentId) {\n tmp_counter++;\n }\n }\n body.to.location = tmp_counter;//wrong location for first cartrige\n }\n //cartriges handler end\n\n for (let item of tmpList.data[0].Inventory.items) {\n if (item._id && item._id === body.item) {\n item.parentId = body.to.id;\n item.slotId = body.to.container;\n if (typeof body.to.location !== \"undefined\") {\n item.location = body.to.location;\n } else {\n if (item.location) {\n delete item.location;\n }\n }\n\n profile.setCharacterData(tmpList);\n return output;\n }\n }\n\n return \"\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Event listener for HTTPS server "listening" event. | function onHttpsListening() {
var addr = httpsServer.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
logger.info('HTTPS Server Started ' + new Date(Date.now()).toString());
logger.info('Listening on ' + bind);
} | [
"function onSSLListening() {\n let addr = ssl_server.address();\n let bind = typeof addr === 'string'\n ? 'pipe ' + addr\n : 'port ' + addr.port;\n debug('SSL Listening on ' + bind);\n}",
"function onListening() {\n var addr = server.address();\n var bind = typeof addr === 'string'\n ? 'pipe ' + addr\n : 'port ' + addr.port;\n debug('HTTP Listening on ' + bind);\n}",
"function listening_handler() {\n\tconsole.log(`Now Listening on Port ${port}`);\n}",
"function onHttpsError(error) {\r\n if (error.syscall !== 'listen') {\r\n throw error;\r\n }\r\n\r\n var bind = typeof port === 'string'\r\n ? 'Pipe ' + port\r\n : 'Port ' + port;\r\n\r\n //Handle specific listen errors with friendly messages\r\n switch (error.code) {\r\n case 'EACCES':\r\n logger.error(bind + ' requires elevated privileges');\r\n process.exit(1);\r\n break;\r\n case 'EADDRINUSE':\r\n logger.error(bind + ' is already in use');\r\n process.exit(1);\r\n break;\r\n default:\r\n throw error;\r\n }\r\n}",
"function badCertListener() {\n}",
"listenHealthCheck() {\n let healthCheckServer = http.createServer(function(req, res) {\n res.writeHead(200); res.end();\n });\n\n // Start listen\n healthCheckServer.listen(process.env.CHECK_PORT);\n }",
"_addServiceStreamDataListener ( ) {\n\n this.serviceStream.on(\n 'data'\n , this.boundStreamListener\n );\n }",
"listen() {\n console.log('--- Listening on localhost:8000 ---');\n this.server.listen(8000);\n }",
"function IpEventAPI( port ) {\n this.port = port;\n this.server = HTTP.createServer();\n\n this.server.on( 'request', this.handler.request );\n this.server.on( 'connection', this.handler.connection );\n this.server.on( 'close', this.handler.close );\n}",
"function start() {\n test();\n var httpService = http.createServer(serve);\n httpService.listen(ports[0], '0.0.0.0');\n\n var options = {\n key: key,\n cert: cert\n };\n var httpsService = https.createServer(options, serve);\n httpsService.listen(ports[1], '0.0.0.0');\n\n var clients = clientService(httpsService);\n clients.onNewPos(updateEvents);\n\n printAddresses();\n}",
"function start()\n{\n if(!checkSite()) return;\n types = defineTypes();\n banned = [];\n banUpperCase(\"./public/\", \"\");\n var service = https.createServer(options, authenticate);\n\n/*\nservice.listen(PORT, () => {\n console.log(\"Our app is running on port \"+PORT);\n});\n*/\n\n service.listen(PORT);\n var address = \"https://localhost\";\n if(PORT != 80) address = address+\":\"+PORT+\"/\";\n console.log(\"Server running at\", address);\n\n}",
"async registerListeners () {\n this.container.on(DockerEventEnum.STATUS_UPDATE, newStatus => this.updateStatus(newStatus));\n this.container.on(DockerEventEnum.CONSOLE_OUTPUT, data => this.onConsoleOutput(data));\n\n this.on(DockerEventEnum.STATUS_UPDATE, newStatus => {\n if (newStatus === ServerStatus.OFFLINE) {\n if (this.config.properties.deleteOnStop) {\n this.logger.info('Server stopped, deleting container...');\n this.remove()\n .catch(err => this.logger.error('Failed to delete the container!', { err }));\n } else if (this.config.properties.autoRestart) {\n this.logger.info('Restarting the server...');\n this.start();\n }\n }\n });\n }",
"function listen( client )\n{\n\tclient.emit('welcome' , \"You have established an connection\");\n\tclient.on('login' , serverCommands.VerifyLogin );\n\t\n\tclient.on('re_establish' , \n\t\tfunction( message ) {\n\t\tclientSocketTable[ message.user_name ] = this;\n\t\tconsole.log(\"re-established \" + message.user_name );\n\t});\n\tclient.on('tag_page_request' , serverCommands.serveTagPage );\n\tclient.on('create_login' , serverCommands.VerifyCreate );\n\tclient.on('buy_hash' , serverCommands.serveBuyHash );\n\tclient.on('sell_hash' , serverCommands.serveSellHash );\n\tclient.on('trending_request' , serverCommands.serveTrending );\n\tclient.on('my_investments_request' , serverCommands.serveMyTrending );\n\tclient.on('player_info_request' , serverCommands.servePlayerInfo);\n\tclient.on('leader_request' , serverCommands.serveLeaderBoard );\n client.on('search_username' , serverCommands.serveSearchUser );\n\tclient.on('search_user_email' , serverCommands.serveSearchEmail );\n}",
"function listenOnSiteUrlChange(fCallback) {\n if ( !fCallback ) return;\n \n setInterval(\n function(){\n // iDoc changes when iframe is reloaded?\n var idoc=(iframe.contentWindow || iframe.contentDocument);\n if (idoc.document) {\n idoc=idoc.document;\n }\n \n var nowUrl = idoc.location.href;\n if ( lastUrl==null ) {\n lastUrl = nowUrl;\n } else if ( lastUrl!=nowUrl ) {\n lastUrl = nowUrl;\n fCallback(nowUrl);\n }\n },100);\n }",
"get isListening() {\n return this.listeners.length > 0;\n }",
"function onConnectionClose() {\n\tif (shutdownInProgress && 0 === (httpServer.connections + httpsServer.connections))\n\t\tshutdownNext()\n}",
"_startListeningForTermination() {\n this._terminationEvents.forEach((eventName) => {\n process.on(eventName, this._terminate);\n });\n }",
"setupServerEventHandlers() {\n const self = this;\n\n this.server.onTitleScreenUpdates(function(info) {\n self.enableSelectingGuesser(!info['guess_disable']);\n self.enableSelectingChooser(!info['choose_disable']);\n });\n\n // Result from pressing 'Become Chooser' button\n this.server.onChooserStatusUpdates(function(result) {\n if (result['chooser_confirmed']) {\n self.enableSelectingChooser(false);\n }\n });\n\n // Result from pressing 'Become Guesser' button\n this.server.onGuesserStatusUpdates(function(result) {\n if (result['guesser_confirmed']) {\n self.enableSelectingGuesser(false);\n }\n });\n }",
"function listenRouteEvent() {\n const ns = getDevtoolNS();\n ns.on(COMP_ROUTE, (...args) => {\n const data = buildRoutes(new CNode(args[0]), ns);\n if (ns.devtoolPanelCreated) {\n window.postMessage({...data, COMP_ROUTE}, '*');\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert that the direction is correct string. | function assertStudentDirection(direction) {
if (!["incoming", "outgoing"].includes(direction)) {
throw("Invalid student direction \"" + direction + "\".");
}
} | [
"check(target) {\n const targetType = typeof target;\n assert('string' === targetType, 'Type error, target should be a string, ' +\n `${targetType} given`);\n }",
"function test (actual, expected) { console.log(actual === expected ? `√ ${actual}` : `X ${actual} | ${expected}`) }",
"alertDirectionalMovement() {\n\n const newPosition = this.positionProperty.get();\n if ( !newPosition.equals( this.lastAlertedPosition ) ) {\n\n const directions = this.getDirections( newPosition, this.lastAlertedPosition );\n\n // make sure that these alerts exist\n if ( assert ) {\n directions.forEach( direction => { assert( this.movementAlerts[ direction ] && typeof this.movementAlerts[ direction ] === 'string' ); } );\n }\n this.alertDirections( directions );\n }\n }",
"isDirection(direction) {\n let sorting = this.context.listStore.getSorting();\n return sorting.fieldId === this.props.property && sorting.direction === direction;\n }",
"function check_if_can_move(location, direction){\n if(direction == \"secret\"){\n if (location[0] % 4 == 0 && location[1] % 4 == 0){\n return true;\n }\n return false;\n }\n \n switch(direction) {\n case \"left\": \n if ((location[0] - 1) < 0)\n return false;\n break;\n case \"up\":\n if ((location[1] + 1) > 4)\n return false;\n break;\n case \"right\":\n if((location[0] + 1) > 4)\n return false;\n break;\n case \"down\":\n if((location[1] - 1) < 0)\n return false;\n break;\n }\n return true;\n}",
"function _isValidAlignment(align) {\n\tif (ratify.isEmpty(align))\n\t\treturn false;\n\n\t//\n\t// dia1 : Diagonal 1\n\t// dia2 : Diagonal 2\n\t// ttb : top to bottom\n\t// btt : bottom to top\n\t// ltr : left to right\n\t// rtl : right to left\n\t//\n\tif (['dia1', 'dia2', 'ttb', 'btt', 'ltr', 'rtl'].indexOf(align.toLowerCase()) > -1)\n\t\treturn true;\n\n\treturn false;\n}",
"_isRtl() {\n return this._dir && this._dir.value === 'rtl';\n }",
"function isDirectionBackward(dir) {\n return (typeof dir == \"string\") ? /^backward(s)?$/i.test(dir) : !!dir;\n }",
"function isValidMoveName(id) {\n if (typeof id === 'undefined' || id == null) {\n return false;\n };\n if (typeof MOVE_DATA[id.toLowerCase()] === 'undefined') {\n return false;\n } else {\n return true;\n };\n}",
"function testNoArgumentsSetText() {\n\t\t\tjsUnity.assertions.assertNotUndefined(U.setText('output', 'test'));\n\t}",
"find_direction() {\n this.direction = (this.direction + 1) % 4; // CCW 90\n if (!this.is_facing_wall())\n return true;\n this.direction = (this.direction + 3) % 4; // CCW 270\n if (!this.is_facing_wall())\n return true;\n this.direction = (this.direction + 3) % 4; // CCW 270\n if (!this.is_facing_wall())\n return true;\n this.direction = (this.direction + 3) % 4; // CCW 270\n if (!this.is_facing_wall())\n return true;\n // If all four sides have walls\n console.log(\"Oops, an error occurred and the bot thinks it's trapped!\");\n return false;\n }",
"function opposite(dir1, dir2) {\n dir1 = dir1.toLowerCase()\n dir2 = dir2.toLowerCase()\n \n if (dir1 === 'north' && dir2 === 'south') { \n return true\n } else if (dir1 === 'south' && dir2 === 'north') {\n return true \n } else if (dir1 === 'east' && dir2 === 'west') { \n return true \n } else if (dir1 === 'west' && dir2 === 'east') { \n return true\n } else { \n return false \n }\n }",
"get correct(){ return(\n this.#correctIdx === undefined\n ? <i>— ei oikeaa tai väärää vastausta</i> // ...no correct answer at all...\n : this.#text[this.#text.length-1]==='=' // question ends with '='?\n ? this.#answers[this.#correctIdx] // ...if so, don't alter\n : ': '+this.#answers[this.#correctIdx] // ...but if not, fiddle with it a bit.\n )}",
"assertTransitionLegal(allowedState, transitionTo) {\n if (!(this.state === allowedState)) {\n throw new Error(`Assertion failure: cannot transition from ${TraitState[this.state]} to ${TraitState[transitionTo]}.`);\n }\n }",
"function determineOrder(value) {\n var result = stringValue.localeCompare(value);\n if (result < 0){\n alert(\"The string 'yellow' comes\");\n } else if (result > 0) {\n alert(\"The string 'yellow' comes\");\n } else {\n alert(\"The string 'yellow' is equal\");\n }\n}",
"ghostChangeDirection() {\n let direction = random(4);\n switch(int(direction)) {\n case 0:\n this.currentDirection = \"up\";\n break;\n case 1:\n this.currentDirection = \"down\";\n break;\n case 2:\n this.currentDirection = \"left\";\n break;\n case 3:\n this.currentDirection = \"right\";\n break;\n }\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 setTextDirection(direction) {\n document.body.setAttribute('dir', direction);\n}",
"function turnRight(rover) {\n var movement=\"r\";\n switch(rover.direction) {\n case 'N':\n rover.direction = 'E';\n break;\n case 'E':\n rover.direction = 'S';\n break;\n case 'S':\n rover.direction = 'W';\n break;\n case 'W':\n rover.direction = 'N';\n break;\n }\n var report = validations(rover,movement);\n printResult(report,rover,movement);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check changeable status for project description field | checkChangeableDescriptionStatus() {
if ('config' === this.currentTab) {
this.importProjectData.project.description = angular.copy(this.projectDescription);
return;
}
this.isChangeableDescription = this.projectDescription === this.importProjectData.project.description;
} | [
"@action\n statusChangeAction(field, value) {\n if (value == 'approved') {\n this.editEntry.set('create_entry', 1);\n }\n }",
"haveChanges() {\n return this.code !== this.codeFromTableau;\n }",
"function checkDescription(){\r\n\tif (description.value == null || description.value == \"\"){\r\n\t\temptyFieldsArray.push(\" Description of the problem\");\r\n\t\tborderRed(description);\r\n\t\treturn true;\r\n\t}\r\n\telse{\r\n\t\treturn false;\r\n\t}\r\n}",
"function checkFormState (){\n\t\tif (formModified && showUnsavedChangesPopup)\n\t\t\treturn 'There are unsaved changes';\n\t}",
"function formDisplayStatus () {\n $(\".js-resource_field\").each(function () {\n if (($(this).val().length >= 1) || ($(this).text().length >= 1)) {\n $(this).closest(\".js-resource_form_section\").find(\".js-title_right\").hide();\n $(this).closest(\".js-resource_form_section\").find(\".js-success_display\").show();\n } else {\n $(this).closest(\".js-resource_form_section\").find(\".js-title_right\").show();\n $(this).closest(\".js-resource_form_section\").find(\".js-success_display\").hide();\n }\n });\n }",
"updateDescription(newDesc) {\n this.description = newDesc;\n }",
"get pending() {\n return this.status === PENDING;\n }",
"get status() {\n if (!this._cancerProgression.value) return null;\n return this._cancerProgression.value.coding[0].displayText.value;\n }",
"function checkLineIfCommited(id){\n\tvar dv = id.split(\"||\");\n\tvar dev1 = dv[0].split(\".\");\n\tvar dev2 = dv[1].split(\".\");\n\tvar device1 = dev1[0];\n\tvar device2 = dev2[0];\n\tvar dev1Condition = false;\n\tvar dev2Condition = false;\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tfor (var a=0; a<devices.length; a++){\n\t\tif (devices[a].ObjectPath== device1 && devices[a].Status.toLowerCase() == \"reserved\"){\n\t\t\tdev1Condition = true;\n\t\t}\n\t\tif (devices[a].ObjectPath== device2 && devices[a].Status.toLowerCase() == \"reserved\"){\n\t\t\tdev2Condition = true;\n\t\t}\n\t}\n\tif (dev1Condition == true && dev2Condition == true){\n\t\treturn true;\n\t}else{\n\t\treturn false;\n\t}\n}",
"function isModified() {\n\tif (is_modified)\n\t\tif (!confirm('Data on this page has been modified.\\nIf you proceed, changes wont\\'t be saved.\\nProceed anyway?'))\n\t\t\treturn false;\n\treturn true;\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 }",
"function canEdit() {\n return Jupyter.narrative.uiModeIs('edit');\n }",
"static changeReadStatus(target) {\n if (target.classList.contains('read-btn')) {\n target.textContent === 'yes'\n ? (target.textContent = 'no')\n : (target.textContent = 'yes');\n // Success message\n UI.alertMessage('Read status changed', 'success');\n } else {\n return;\n }\n }",
"_onInputProjectNameChanged(projectName) {\n if(projectName) {\n this.shadowRoot.getElementById(\"dialog-button-create\").disabled = false;\n } else {\n this.shadowRoot.getElementById(\"dialog-button-create\").disabled = true;\n }\n }",
"validateActivityStatus() {\r\n let res = this.state.selectedData.every((livestock) => {\r\n return !(livestock.ActivitySystemCode == livestockActivityStatusCodes.Deceased ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Killed ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Lost);\r\n });\r\n if (!res) this.notifyToaster(NOTIFY_WARNING, { message: this.strings.INVALID_RECORD_LOST_STATUS });\r\n return res;\r\n }",
"function checkNotesStatus() {\n _.each(self.notes, function (note) {\n note.updateSchedulingColor();\n });\n }",
"function _check_project_item() {\n var pid = $('.project select[name=pid]').val()\n var ty = $('.project').attr('ty')\n var id = $('.project').attr('pid')\n \n $.ajax({\n url: '/projects/ajax/check/ty/'+ty+'/pid/'+pid+'/iid/'+id,\n type: 'GET',\n dataType: 'json',\n timeout: 5000,\n success: function(r) {\n var btns = {}\n btns[(r ? 'Remove' : 'Add')] = function() {\n if (pid && ty && id) {\n $.ajax({\n url: '/projects/ajax/addto/pid/'+pid+'/ty/'+ty+'/iid/'+id+(r ? '/rem/1' : ''),\n type: 'GET',\n dataType: 'json',\n timeout: 5000,\n success: function(r){\n $('.project').dialog('close')\n }\n })\n }\n }\n btns['Close'] = function() { $(this).dialog('close') }\n \n $('.project').dialog('option', 'buttons', btns)\n $('.project').dialog('option', 'title', r ? 'Remove From Project' : 'Add To Project')\n }\n })\n }",
"function checkTasksState() {\n var i, j, k, listTasks = Variable.findByName(gm, 'tasks'), taskDescriptor, taskInstance,\n newWeek = Variable.findByName(gm, 'week').getInstance(self), inProgress = false,\n listResources = Variable.findByName(gm, 'resources'), resourceInstance, assignment,\n newclientsSatisfaction = Variable.findByName(gm, 'clientsSatisfaction').getInstance(self);\n for (i = 0; i < listTasks.items.size(); i++) {\n inProgress = false;\n taskDescriptor = listTasks.items.get(i);\n taskInstance = taskDescriptor.getInstance(self);\n for (j = 0; j < listResources.items.size(); j++) {\n resourceInstance = listResources.items.get(j).getInstance(self);\n if (resourceInstance.getActive() == true) {\n for (k = 0; k < resourceInstance.getAssignments().size(); k++) {\n assignment = resourceInstance.getAssignments().get(k);\n if (assignment.getTaskDescriptorId() == taskInstance.getDescriptorId() && taskInstance.getActive() == true) {\n inProgress = true;\n }\n }\n }\n }\n if (inProgress ||\n (newWeek.getValue() >= taskDescriptor.getProperty('appearAtWeek') &&\n newWeek.getValue() < taskDescriptor.getProperty('disappearAtWeek') &&\n newclientsSatisfaction.getValue() >= taskDescriptor.getProperty('clientSatisfactionMinToAppear') &&\n newclientsSatisfaction.getValue() <= taskDescriptor.getProperty('clientSatisfactionMaxToAppear') &&\n taskInstance.getDuration() > 0\n )\n ) {\n taskInstance.setActive(true);\n }\n else {\n taskInstance.setActive(false);\n }\n }\n}",
"shouldReload() {\n return this.isPR && this.builds.any(b => isActiveBuild(b.get('status'), b.get('endTime')))\n ? SHOULD_RELOAD_YES\n : SHOULD_RELOAD_NO;\n }",
"isWorkInProgress() {\n return this.json_.work_in_progress === true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remember time user started the video | function videoStartedPlaying() {
timeStarted = new Date().getTime()/1000;
alertMsg();
} | [
"function playActorVideo(actor, time) {\n //playVideo(id, time - startTime of video)\n\n}",
"function onTimeupdate(){\n //if the video has finished\n if ( this.currentTime >= this.duration ){\n //if we are offering e-mail sharing\n if (configHandler.get('showLocalShare')){\n var vidElem = document.getElementById('videoReview');\n //if we have not shown the e-mail option yet\n if (haveShownShare === false ){\n //remember that we have shown it\n haveShownShare = true;\n //transition in the other UI elements\n var container = document.getElementById('videoReviewContainer');\n container.classList.add('share');\n var btn = document.getElementById('breakButton');\n btn.classList.remove('enabled');\n btn.classList.add('disabled');\n vidElem.muted = true;\n //play the audio after the e-mail option\n // has transitioned in\n if (soundPlayer.exists()){\n soundTimeout = setTimeout(function(){\n soundPlayer.play();\n }, 1000);\n }\n }\n //replay the video\n vidElem.currentTime = 0;\n vidElem.play();\n } else {\n //if we are not offering e-mail sharing\n // just transition to the thank you screen\n window.events.dispatchEvent(new Event('special'));\n }\n }\n }",
"function updateTillPlayed()\n{\n setCookie('timePlayed', song.currentTime);\n}",
"function getVideoTime() {\n return player.getCurrentTime();\n}",
"function updatevideostatus(){\n \n \n if(video.paused)\n {\n \n video.play();\n }\n else{\n video.pause();\n }\n\n \n }",
"_showFirstFrame() {\n if (!this._video.isPlaying) {\n this._video.getVideoElement().currentTime = 0;\n }\n }",
"function updateVideoCurrentTime() {\n let curtime = convertSecondsToMinutes(video.currentTime);\n videotime.innerHTML = curtime+' / '+videoduration;\n }",
"updateVideoTime(videoPlayer, time) {\n videoPlayer.currentTime = time;\n \n }",
"static isVideoPlaying(video){return video.currentTime>0&&!video.paused&&video.readyState>2;}",
"function e_timer() {\n if (!localStream)\n getVideo();\n\n if (peerConnection == null) {\n f_showTextMessage(\"Not connected\")\n if (started) start(true);\n }\n else\n f_showTextMessage(peerConnection.iceConnectionState);\n}",
"play(startTime, endTime) {\n let { remote, fullScreen, playing } = this.props\n let { vc } = this\n log(`play startTime=${startTime}, endTime=${endTime}, playing=${playing}`)\n\n if (playing) { \n log('play - stop before restarting play')\n this.stop() \n }\n\n if (!isNaN(startTime)) {\n vc.currentTime = startTime\n }\n\n if (fullScreen) this.requestFullScreen()\n\n this.endTime = endTime\n\n let { playbackRate } = remote\n vc.playbackRate = playbackRate || 1.0\n\n this.startupdater()\n remote.playing = true\n //console.log('play!!!')\n this.vc.play()\n }",
"function videoClick(clickedVideo){\n console.log('video es'+clickedVideo);\n sessionStorage.setItem('videoid', clickedVideo);\n}",
"function playVideoOnTime(videodata) {\n $.each(getVideos, function(key, value) {\n // See if any video should be played now\n if ((value.startSeconds > 1)) {\n //console.log('Video ID :' + value.videoId + ' at : ' + value.startSeconds);\n domYouTubeContainer.tubeplayer(\"play\", {\n id: value.videoId,\n time: value.startSeconds\n });\n }\n });\n }",
"function videoSeekTo(time) {\n player.seekTo(time);\n}",
"startTracking() {\n if (this.isTracking()) {\n return;\n }\n\n // If we haven't seen a timeupdate, we need to check whether playback\n // began before this component started tracking. This can happen commonly\n // when using autoplay.\n if (!this.timeupdateSeen_) {\n this.timeupdateSeen_ = this.player_.hasStarted();\n }\n\n this.trackingInterval_ = this.setInterval(this.trackLive_, 30);\n this.trackLive_();\n\n this.on(this.player_, 'play', this.trackLive_);\n this.on(this.player_, 'pause', this.trackLive_);\n\n // this is to prevent showing that we are not live\n // before a video starts to play\n if (!this.timeupdateSeen_) {\n this.one(this.player_, 'play', this.handlePlay);\n this.handleTimeupdate = () => {\n this.timeupdateSeen_ = true;\n this.handleTimeupdate = null;\n };\n this.one(this.player_, 'timeupdate', this.handleTimeupdate);\n }\n }",
"function video_done(e) {\n\tthis.currentTime = 0;\n}",
"function mouse_in_video()\n{\n\t$(\".chalk_player .media_controls\").addClass(\"media_show\");\n\tif($(\".chalk_player video\").attr(\"data-diy\")==\"1\")\n\t\t$(\".chalk_player .diy_wrapper .steps_container\").removeClass(\"hidden\");\n\tsetTimeout(function() {\n\t\tif($(\".chalk_player .media_controls\").attr(\"data-mouse-in\")==\"0\")\n\t\t\tif(Date.now()-$(\".chalk_player .media_controls\").attr(\"data-prev-hide\")>4000)\n\t\t\t{\n\t\t\t\t$(\".chalk_player .media_controls\").attr(\"data-prev-hide\",Date.now());\n\t\t\t\tmouse_out_video();\n\t\t\t}\n\t}, 4000);\n}",
"function setCurrentTime() {\n\t\tvar total = player.currentTime;\n\t\tcurrentTimeElement.innerHTML = timeFormat(total);\n\t}",
"function updatePlayer()\n{\n if (tillPlayed)\n {\n song.play();\n song.currentTime = tillPlayed;\n }\n else\n {\n song.play();\n setCookie('timePlayed', \"0\");\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ISSUE functionality / Assigns issue to the test | function assignIssue(issue, keyWord) {
if (!issue.testCaseId) {
issue.testCaseId = test.testCaseId;
}
issue.type = 'BUG';
TestService.createTestWorkItem(test.id, issue)
.then((rs) => {
const workItemType = issue.type;
const jiraId = issue.jiraId;
let message;
if (rs.success) {
var messageWord;
switch (keyWord) {
case 'SAVE':
messageWord = issue.id ? 'updated' : 'created';
break;
case 'LINK':
messageWord = 'linked';
break;
}
message = generateActionResultMessage(workItemType, jiraId, messageWord, true);
vm.newIssue = angular.copy(rs.data);
updateWorkItemList(rs.data);
vm.initIssueSearch(false);
initAttachedWorkItems();
vm.isNewIssue = jiraId !== vm.attachedIssue.jiraId;
messageService.success(message);
} else {
if (vm.isNewIssue) {
message = generateActionResultMessage(workItemType,
jiraId, 'assign', false);
} else {
message = generateActionResultMessage(workItemType,
jiraId, 'update', false);
}
messageService.error(message);
}
});
} | [
"function getIssues() {\n TestService.getTestCaseWorkItemsByType(test.id, 'BUG').\n then(function(rs) {\n if (rs.success) {\n vm.issues = rs.data;\n if (test.workItems.length && vm.attachedIssue) {\n angular.copy(vm.attachedIssue, vm.newIssue);\n }\n } else {\n messageService.error(rs.message);\n }\n });\n }",
"async postIssue() {\n if (!this.API || !this.options || this.issue || this.issueId)\n return;\n // login to create issue\n if (!this.isLogined) {\n this.login();\n }\n // only owner/admins can create issue\n // if (!this.isAdmin) return\n try {\n this.isCreatingIssue = true;\n const issue = await this.API.postIssue({\n title: this.issueTitle,\n content: await this.options.issueContent({\n options: this.options,\n url: getCleanURL(window.location.href),\n }),\n accessToken: this.accessToken,\n });\n const issueR = await this.API.postIssue({\n title: this.issueTitleR,\n content: await this.options.issueContent({\n options: this.options,\n url: getCleanURL(window.location.href),\n }),\n accessToken: this.accessToken,\n });\n this.issue = issue;\n this.issueR = issueR;\n this.isIssueNotCreated = false;\n await this.getComments();\n await this.getRatings();\n await this.getTotalRating();\n await this.getUserRating();\n }\n catch (e) {\n this.isFailed = true;\n }\n finally {\n this.isCreatingIssue = false;\n }\n }",
"function _createIssue() {\n if (currentRepo && currentRepo.repo) {\n var dialog = Dialogs.showModalDialogUsingTemplate(\n Mustache.render(IssueDialogNewTPL, currentRepo)\n );\n \n var submitClass = \"gh-create\",\n cancelClass = \"gh-cancel\",\n $dialogBody = dialog.getElement().find(\".modal-body\"),\n $title = $dialogBody.find(\".gh-issue-title\").focus(),\n $message = $dialogBody.find(\".comment-body\"),\n $preview = $dialogBody.find(\".comment-preview\");\n \n $dialogBody.find('a[data-action=\"preview\"]').on(\"shown\", function (event) {\n $preview.html(marked($message.val()));\n });\n \n $dialogBody.delegate(\".btn\", \"click\", function (event) {\n var $btn = $(event.currentTarget);\n \n if ($btn.hasClass(cancelClass)) {\n dialog.close();\n } else if ($btn.hasClass(submitClass)) {\n $dialogBody.toggleClass(\"loading\");\n \n gh.newIssue($title.val(), $message.val()).done(function (issue) {\n if (issue && issue.html_url) {\n dialog.close();\n _viewIssue(issue);\n } else {\n $dialogBody.toggleClass(\"error loading\");\n }\n });\n }\n });\n } else {\n Dialogs.showModalDialogUsingTemplate(_renderTPL(ErrorProjectNotFoundTPL));\n }\n }",
"async function transferIssues(owner, repo, projectId) {\n inform(\"Transferring Issues\");\n\n // Because each\n let milestoneData = await getAllGHMilestones(owner, repo);\n\n // get a list of all GitLab issues associated with this project\n // TODO return all issues via pagination\n let issues = await gitlab.Issues.all({projectId: projectId});\n\n // sort issues in ascending order of their issue number (by iid)\n issues = issues.sort((a, b) => a.iid - b.iid);\n\n // get a list of the current issues in the new GitHub repo (likely to be empty)\n let ghIssues = await getAllGHIssues(settings.github.owner, settings.github.repo);\n\n console.log(\"Transferring \" + issues.length.toString() + \" issues\");\n\n //\n // Create Placeholder Issues\n //\n\n for (let i=0; i<issues.length; i++) {\n // GitLab issue internal Id (iid)\n let expectedIdx = i+1;\n\n // is there a gap in the GitLab issues?\n // Create placeholder issues so that new GitHub issues will have the same\n // issue number as in GitLab. If a placeholder is used it is because there\n // was a gap in GitLab issues -- likely caused by a deleted GitLab issue.\n if (issues[i].iid != expectedIdx) {\n issues.splice(i, 0, {\n iid: expectedIdx,\n title: `placeholder issue for issue ${expectedIdx} which does not exist and was probably deleted in GitLab`,\n description: 'This is to ensure the issue numbers in GitLab and GitHub are the same',\n state: 'closed'\n });\n i++;\n console.log(\"Added placeholder issue for GitLab issue #\" + expectedIdx)\n }\n }\n\n //\n // Create GitHub issues for each GitLab issue\n //\n\n // if a GitLab issue does not exist in GitHub repo, create it -- along with comments.\n for (let issue of issues) {\n // TODO: get slice from issues instead of condition\n if (issue.iid < start || issue.iid > end) {\n continue\n }\n // try to find a GitHub issue that already exists for this GitLab issue\n let ghIssue = ghIssues.find(i => i.title.trim() === issue.title.trim() + \" - [glis:\" + issue.iid + \"]\");\n if (!ghIssue) {\n console.log(\"Creating: \" + issue.iid + \" - \" + issue.title);\n try {\n\n // process asynchronous code in sequence -- treats the code sort of like blocking\n await createIssueAndComments(settings.github.owner, settings.github.repo, milestoneData, issue);\n\n } catch (err) {\n console.error(\"Could not create issue: \" + issue.iid + \" - \" + issue.title);\n console.error(err);\n process.exit(1);\n }\n } else {\n console.log(\"Already exists: \" + issue.iid + \" - \" + issue.title);\n updateIssueState(ghIssue, issue);\n }\n };\n\n}",
"setIssue(issue) {\n this.issue = issue;\n }",
"_onIssueClicked(params) {\n const prefix = commentTypeToIDPrefix[params.commentType];\n const selector = `#${prefix}comment${params.commentID}`;\n\n this._entryViews.forEach(entryView => {\n if (entryView.$el.find(selector).length > 0) {\n entryView.expand();\n }\n });\n\n RB.navigateTo(params.commentURL);\n }",
"async function transferIssues() {\n inform('Transferring Issues');\n\n // Because each\n let milestoneData = await githubHelper.getAllGithubMilestones();\n\n // get a list of all GitLab issues associated with this project\n // TODO return all issues via pagination\n let issues = await gitlabApi.Issues.all({\n projectId: settings.gitlab.projectId,\n });\n\n // sort issues in ascending order of their issue number (by iid)\n issues = issues.sort((a, b) => a.iid - b.iid);\n\n // get a list of the current issues in the new GitHub repo (likely to be empty)\n let githubIssues = await githubHelper.getAllGithubIssues();\n\n console.log(`Transferring ${issues.length} issues.`);\n\n if (settings.usePlaceholderIssuesForMissingIssues) {\n for (let i = 0; i < issues.length; i++) {\n // GitLab issue internal Id (iid)\n let expectedIdx = i + 1;\n\n // is there a gap in the GitLab issues?\n // Create placeholder issues so that new GitHub issues will have the same\n // issue number as in GitLab. If a placeholder is used it is because there\n // was a gap in GitLab issues -- likely caused by a deleted GitLab issue.\n if (issues[i].iid !== expectedIdx) {\n issues.splice(i, 0, createPlaceholderIssue(expectedIdx));\n issueCounters.nrOfPlaceholderIssues++;\n console.log(\n `Added placeholder issue for GitLab issue #${expectedIdx}.`\n );\n }\n }\n }\n\n //\n // Create GitHub issues for each GitLab issue\n //\n\n // if a GitLab issue does not exist in GitHub repo, create it -- along with comments.\n for (let issue of issues) {\n // try to find a GitHub issue that already exists for this GitLab issue\n let githubIssue = githubIssues.find(\n i => i.title.trim() === issue.title.trim()\n );\n if (!githubIssue) {\n console.log(`\\nMigrating issue #${issue.iid} ('${issue.title}')...`);\n try {\n // process asynchronous code in sequence -- treats the code sort of like blocking\n await githubHelper.createIssueAndComments(milestoneData, issue);\n console.log(`\\t...DONE migrating issue #${issue.iid}.`);\n } catch (err) {\n console.log(`\\t...ERROR while migrating issue #${issue.iid}.`);\n\n console.error('DEBUG:\\n', err); // TODO delete this after issue-migration-fails have been fixed\n\n if (settings.useReplacementIssuesForCreationFails) {\n console.log('\\t-> creating a replacement issue...');\n const replacementIssue = createReplacementIssue(\n issue.iid,\n issue.title,\n issue.state\n );\n\n try {\n await githubHelper.createIssueAndComments(\n milestoneData,\n replacementIssue\n );\n\n issueCounters.nrOfReplacementIssues++;\n console.error('\\t...DONE.');\n } catch (err) {\n issueCounters.nrOfFailedIssues++;\n console.error(\n '\\t...ERROR: Could not create replacement issue either!'\n );\n }\n }\n }\n } else {\n console.log(`Updating issue #${issue.iid} - ${issue.title}...`);\n try {\n await githubHelper.updateIssueState(githubIssue, issue);\n console.log(`...Done updating issue #${issue.iid}.`);\n } catch (err) {\n console.log(`...ERROR while updating issue #${issue.iid}.`);\n }\n }\n }\n\n // print statistics about issue migration:\n console.log(`DONE creating issues.`);\n console.log(`\\n\\tStatistics:`);\n console.log(`\\tTotal nr. of issues: ${issues.length}`);\n console.log(\n `\\tNr. of used placeholder issues: ${issueCounters.nrOfPlaceholderIssues}`\n );\n console.log(\n `\\tNr. of used replacement issues: ${issueCounters.nrOfReplacementIssues}`\n );\n console.log(\n `\\tNr. of issue migration fails: ${issueCounters.nrOfFailedIssues}`\n );\n}",
"function Issue(props) {\n return e(\n \"div\",\n {},\n JSON.stringify(props.issue)\n );\n}",
"function saveIssue(e) \r\n{\r\n var issueDesc = document.getElementById('issueDescInput').value;\r\n var issueSeverity = document.getElementById('issueSeverityInput').value;\r\n var issueAssignedTo = document.getElementById('issueAssignedToInput').value;\r\n var issueId = chance.guid();\r\n var issueStatus = 'UnSolved';\r\n var issue = {\r\n id: issueId,\r\n description: issueDesc,\r\n severity: issueSeverity,\r\n assignedTo: issueAssignedTo,\r\n status: issueStatus\r\n }\r\n\r\n // if there is no issue description push the issue with no content\r\n if(localStorage.getItem('issues') == null) \r\n {\r\n var issues = [];\r\n issues.push(issue);\r\n localStorage.setItem('issues', JSON.stringify(issues));\r\n } \r\n\r\n // if issue is fully described put the issue along with the contents mentioned\r\n else \r\n {\r\n var issues = JSON.parse(localStorage.getItem('issues'));\r\n issues.push(issue);\r\n localStorage.setItem('issues', JSON.stringify(issues));\r\n }\r\n\r\n // reset the form eachtime after adding an issue to make space to add new issue\r\n document.getElementById('issueInputForm').reset();\r\n fetchIssues();\r\n e.preventDefault();\r\n}",
"function searchIssue(issue) {\n vm.isIssueFound = false;\n TestService.getJiraTicket(issue.jiraId).then(function(rs) {\n if (rs.success) {\n var searchResultIssue = rs.data;\n vm.isIssueFound = true;\n if (searchResultIssue === '') {\n vm.isIssueClosed = false;\n vm.issueJiraIdExists = false;\n vm.issueTabDisabled = false;\n return;\n }\n vm.issueJiraIdExists = true;\n vm.isIssueClosed = vm.closedStatusName.toUpperCase() ===\n searchResultIssue.status.toUpperCase();\n vm.newIssue.description = searchResultIssue.summary;\n vm.newIssue.assignee = searchResultIssue.assigneeName || '';\n vm.newIssue.reporter = searchResultIssue.reporterName || '';\n vm.newIssue.status = searchResultIssue.status.toUpperCase();\n vm.isNewIssue = vm.newIssue.jiraId !== vm.attachedIssue.jiraId;\n vm.issueTabDisabled = false;\n }\n });\n }",
"function initAttachedWorkItems() {\n var attachedWorkItem = {};\n attachedWorkItem.jiraId = '';\n vm.attachedIssue = attachedWorkItem;\n var workItems = vm.test.workItems;\n for (var i = 0; i < workItems.length; i++) {\n switch (workItems[i].type) {\n case 'BUG':\n vm.attachedIssue = workItems[i];\n break;\n }\n }\n }",
"function Issue(github, data) {\n this.github = github;\n this.data = data;\n var url = data.url;\n if (url == null) {\n throw \"Missing required `data.url`\";\n }\n var p = url.indexOf(\"/repos/\");\n if (p >= 0) {\n url = url.substring(p + 1);\n }\n this.apiurl = url;\n }",
"function initIssues() {\n\t//ids start at 5 so fill in 0-4 to make retrieval bawed on array index trivial\n\tissues = [0, 0, 0, 0, 0,\n {id:5,\tname:\"Alumni\"},\n\t\t\t{id:6,\tname:\"Animals\"},\n\t\t\t{id:7,\tname:\"Children\"},\n\t\t\t{id:8,\tname:\"Disabilities\"},\n\t\t\t{id:9,\tname:\"Disasters\"},\n\t\t\t{id:10,\tname:\"Education\"},\n\t\t\t{id:11,\tname:\"Elderly\"},\n\t\t\t{id:12,\tname:\"Environment\"},\n\t\t\t{id:13,\tname:\"Female Issues\"},\n\t\t\t{id:14, name:\"Fine Arts\"},\n\t\t\t{id:15,\tname:\"General Service\"},\n\t\t\t{id:16,\tname:\"Health\"},\n\t\t\t{id:17,\tname:\"Male Issues\"},\n\t\t\t{id:18, name:\"Minority Issues\"},\n\t\t\t{id:19,\tname:\"Office\"},\n\t\t\t{id:20,\tname:\"Patriotic\"},\n\t\t\t{id:21,\tname:\"Poverty\"},\n\t\t\t{id:22,\tname:\"PR\"},\n\t\t\t{id:23,\tname:\"Recreation\"},\n\t\t\t{id:24,\tname:\"Religious\"},\n\t\t\t{id:25,\tname:\"Service Leaders\"},\n\t\t\t{id:26,\tname:\"Technology\"}\n\t\t\t];\n}",
"onReportAnIssue_() {\n this.userActed('openFeedbackDialog');\n }",
"function updateIssueDataModel (issueName, projName, descr) {\n\n return {\n name : issueName,\n projname : projName,\n descr : descr\n }\n}",
"function post_jira(commit) {\n\n // only write one comment per commit\n if (!commit.distinct) {\n log('commit ' + commit.id + ' is not distinct. skipping');\n return;\n }\n\n var regex = /([A-Z]+-\\d+)/g;\n\n // extract all issues - might have dups\n var issue_list = commit.message.match(regex);\n \n // bail out of there are no issues found\n if (!issue_list) {\n return;\n }\n\n // dedup list\n var unique_issues = issue_list\n .slice() // don't mess with original\n .sort()\n .reduce(function (a, b) {\n if (a.slice(-1)[0] !== b) {\n a.push(b);\n }\n return a;\n }, []);\n\n // now add a comment to each issue\n unique_issues.forEach(function (issue_id) {\n\n var post_data = JSON.stringify({\n 'body' : get_msg(commit)\n });\n\n var post_options = {\n hostname: jira_hostname,\n port: jira_port,\n path: '/rest/api/latest/issue/' + issue_id + '/comment',\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': post_data.length\n },\n auth: jira_api_user + ':' + jira_pw\n };\n\n // will this work if http?\n var post_req = https.request(post_options, function (res) {\n log(\"Posting comment to JIRA issue: \" + issue_id);\n log(\"Response Status Code: \" + res.statusCode);\n res.setEncoding('utf8');\n res.on('data', function (chunk) {\n log('Response Body: ' + chunk + '\\n');\n });\n });\n\n post_req.on('error', function (e) {\n log('problem with request: ' + e.stack);\n });\n\n post_req.write(post_data);\n post_req.end();\n });\n}",
"async function createRepositoryIssues({ issues }) {\n const issuesHTML = HtmlBuilder.div()\n .addClass('repository-detail__issues mb-3 border p-3')\n let issueDetailHTML = createIssueDetail({ issue: undefined })\n\n if (!issues || issues.length <= 0) {\n return issuesHTML.append(HtmlBuilder.div(\"Não há issues\"))\n }\n\n async function fetchAndFillIssueDetail({ issue }) {\n const { comments_url } = issue\n const issueComments = await _gitHubService.fetchIssueComments(comments_url)\n issueDetailHTML.html(createIssueDetail({ issue, issueComments }))\n moveToPageElemnt(\"#issue-detail\")\n }\n\n const issuesTableHTML = HtmlBuilder.table(\"\")\n .addClass('table table-striped border')\n .attr('id', 'issues-table')\n const theadHTML = HtmlBuilder.thead(\"\")\n .append(HtmlBuilder.tr()\n .append(HtmlBuilder.th(\"Nome\"))\n .append(HtmlBuilder.th(\"Status\").attr(DataTableConsts.DATATABLE_SELECT_FILTER_COLUMN, DataTableConsts.DATATABLE_SELECT_FILTER_COLUMN))\n .append(HtmlBuilder.th(\"Detalhes\")))\n const tbodyHTML = HtmlBuilder.tbody(\"\")\n\n for (issue of issues) {\n const issueWithoutCache = issue\n const { title, state } = issueWithoutCache\n\n function onOpenIssueDetail() { fetchAndFillIssueDetail({ issue: issueWithoutCache }) }\n\n const trHTML = HtmlBuilder.tr(\"\")\n .append(HtmlBuilder.td(`${title}`))\n .append(HtmlBuilder.td(`${state}`))\n .append(HtmlBuilder.td(HtmlBuilder.button(\"Mais\")\n .addClass('btn btn-primary')\n .click(onOpenIssueDetail)))\n\n tbodyHTML.append(trHTML)\n }\n\n issuesTableHTML.append(theadHTML).append(tbodyHTML)\n issuesHTML\n .append(HtmlBuilder.h3(\"Issues\"))\n .append(issuesTableHTML)\n .append(HtmlBuilder.hr())\n .append(issueDetailHTML)\n\n _dataTableFactory.of(issuesTableHTML)\n\n return issuesHTML\n }",
"function updateIssue() {\n const usId = document.getElementById(\"modal-id\").value.substring(5);\n const nom = document.getElementById(\"modal-nom\").value;\n const description = document.getElementById(\"modal-description\").value;\n const priority = document.getElementById(\"modal-priority\").value;\n const difficulty = document.getElementById(\"modal-difficulty\").value;\n\n let jsonData = {\n \"name\": nom,\n \"description\": description,\n \"priority\": priority,\n \"difficulty\": difficulty\n }\n\n sendAjax(\"/api/issue/\" + usId, 'PUT', JSON.stringify(jsonData)).then(() => {\n document.getElementById(\"issue\" + usId + \"-name\").innerHTML = \"<h4><strong>\" + nom + \"</strong></h4>\";\n document.getElementById(\"issue\" + usId + \"-description\").innerHTML = description;\n document.getElementById(\"issue\" + usId + \"-priority-btn\").value = priority;\n document.getElementById(\"issue\" + usId + \"-priority\").innerHTML = \"<h6>Priorité :\" +\n \"<span class=\\\"label label-default\\\">\" + priority + \" </span>\" +\n \"</h6>\";\n document.getElementById(\"issue\" + usId + \"-difficulty-btn\").value = difficulty;\n document.getElementById(\"issue\" + usId + \"-difficulty\").innerHTML = \"<h6>Difficulté :\" +\n \"<span class=\\\"label label-default\\\">\" + difficulty + \" </span>\" +\n \"</h6>\";\n $(\"#modal\").modal(\"hide\");\n })\n .catch(() => {\n $(\".err-msg\").fadeIn();\n $(\".spinner-border\").fadeOut();\n })\n}",
"function JexpIssues() {\n _classCallCheck(this, JexpIssues);\n\n JexpIssues.initialize(this);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a new DOM builder that attaches to the given element. | static attach(element) {
return new DomBuilder(element);
} | [
"function addToDOM(element, someHTML) {\n var div = document.createElement('div');\n div.id = \"b\";\n div.innerHTML = someHTML;\n element.appendChild(div);\n}",
"createHTMLElement(parent){\n let htmlElement=document.createElement(this.htmlTagName);\n this.parent=parent;\n this.parent.appendChild(htmlElement);\n this.htmlElementId=getUniqueId(parent,this.htmlTagName);\n htmlElement.id=this.htmlElementId;\n this.applyStyleToElement();\n widgets[this.htmlElementId]=this;\n }",
"function addElement(prevElement, element, attribute, attrValue) {\n if (prevElement != \"\") {\n prevElement.after(element);\n if (attribute != \"\" || attrValue != \"\") {\n let attr = document.createAttribute(attribute);\n attr.value = attrValue;\n element.setAttributeNode(attr);\n }\n } else {\n document.querySelector(\"body\").appendChild(element);\n if (attribute != \"\" || attrValue != \"\") {\n let attr = document.createAttribute(attribute);\n attr.value = attrValue;\n element.setAttributeNode(attr);\n }\n }\n}",
"function attachOnDOM(){\n\tdocument.getElementsByTagName('body')[0].appendChild(getComponent())\n}",
"replace (element) {\r\n element = makeInstance(element);\r\n this.node.parentNode.replaceChild(element.node, this.node);\r\n return element\r\n }",
"function createFormElement(element, type, name, id, value, parent) {\r\n\tvar e = document.createElement(element);\r\n\te.setAttribute(\"name\", name);\r\n\te.setAttribute(\"type\", type);\r\n\te.setAttribute(\"id\", id);\r\n\te.setAttribute(\"value\", value);\r\n\tparent.appendChild(e);\r\n}",
"function BAElement() { }",
"setHtml(element, html){\n element.html(html);\n }",
"function MyCreateElement(type, attrs={}) {\n var elem = document.createElement(type);\n for (var key in attrs)\n elem.setAttribute(key, attrs[key]);\n return elem;\n}",
"function getElementFromAttachTo(attachTo) {\n\t\tif (typeof attachTo == 'string') {\n\t\t\tattachTo = document.getElementById(attachTo);\n\t\t}\n\t\tif (attachTo == null) {\n\t\t\tthrow new Error(\"You must define an element to append the chart to\");\n\t\t}\n\t\treturn attachTo;\n\t}",
"function $(el){\n\tif ($type(el) == 'string') el = document.getElementById(el);\n\tif ($type(el) == 'element'){\n\t\tif (!el.extend){\n\t\t\tUnload.elements.push(el);\n\t\t\tel.extend = Object.extend;\n\t\t\tel.extend(Element.prototype);\n\t\t}\n\t\treturn el;\n\t} else return false;\n}",
"function createTagAppend(loc, tag, id='', el_class='', text='') {\n var element = document.createElement(tag);\n if (id != '') {\n element.setAttribute('id', id);\n }\n if (el_class != '') {\n element.setAttribute('class', el_class);\n }\n if (text != '') {\n element.innerText = text;\n }\n loc.append(element);\n return element;\n}",
"dom(lastJstComponent, lastJstForm) {\n\n // TEMP protection...\n if (this.tag === \"-deleted-\") {\n console.error(\"Trying to DOM a deleted element\", this);\n return undefined;\n }\n let el = this.el;\n\n if (!el) {\n if (this.ns) {\n el = document.createElementNS(this.ns, this.tag);\n }\n else {\n el = document.createElement(this.tag);\n }\n }\n\n // If the element parameters contains a 'ref' attribute, then fill it in\n if (this.ref && lastJstComponent) {\n lastJstComponent.setRef(this.ref, this);\n }\n\n // Handle forms\n if (lastJstComponent && this.tag === \"form\" && (this.attrs.name || this.attrs.ref || this.attrs.id)) {\n lastJstForm = lastJstComponent.addForm(this);\n }\n else if (lastJstForm &&\n (this.tag === \"input\" ||\n this.tag === \"textarea\" ||\n this.tag === \"select\")) {\n lastJstForm.addInput(this);\n }\n\n if (!this.isDomified) {\n \n this.jstComponent = lastJstComponent;\n\n // Handle all the attributes on this element\n for (let attrName of Object.keys(this.attrs)) {\n let val = this.attrs[attrName];\n\n // Special case for 'class' and 'id' attributes. If their values start with\n // '-' or '--', add the scope to their values\n if (lastJstComponent && (attrName === \"class\" || attrName === \"id\") &&\n val.match && val.match(/(^|\\s)-/)) {\n val = val.replace(/(^|\\s)(--?)/g,\n (m, p1, p2) => p1 +\n (p2 === \"-\" ? lastJstComponent.getClassPrefix() :\n lastJstComponent.getFullPrefix()));\n }\n el.setAttribute(attrName, val);\n }\n\n // Add the properties\n for (let propName of this.props) {\n el[propName] = true;\n }\n\n // Add event listeners\n for (let event of Object.keys(this.events)) {\n // TODO: Add support for options - note that this will require\n // some detection of options support in the browser...\n el.addEventListener(event, this.events[event].listener);\n }\n \n // Now add all the contents of the element\n this._visitContents(\n lastJstComponent,\n // Called per JstElement\n (jstComponent, item) => {\n \n if (item.type === JstElementType.TEXTNODE) {\n if (!item.el) {\n item.el = document.createTextNode(item.value);\n el.appendChild(item.el);\n }\n }\n else if (item.type === JstElementType.JST_ELEMENT) {\n let hasEl = item.value.el;\n let childEl = item.value.dom(jstComponent, lastJstForm);\n if (!hasEl) {\n el.appendChild(childEl);\n }\n else if (childEl.parentNode && childEl.parentNode !== el) {\n childEl.parentNode.removeChild(childEl);\n el.appendChild(childEl);\n }\n }\n else {\n console.error(\"Unexpected contents item type:\", item.type);\n }\n \n },\n // Called per JstComponent\n jstComponent => {\n jstComponent.parentEl = el;\n }\n );\n\n }\n\n this.el = el;\n this.isDomified = true;\n return el;\n\n }",
"_buildDOM() {\n const HTML = this.render();\n if (!HTML) { return }\n this.DOMbuilder.build( HTML );\n }",
"function addAndReturnElement(elNameToAdd, nameSpace, xmlElement, preserveSpaces)\n {\n var elToAdd = document.createElementNS(nameSpace, elNameToAdd);\n if (preserveSpaces) Utils.setPreserveSpace(elToAdd);\n xmlElement.appendChild(elToAdd);\n return elToAdd;\n }",
"function createElement(loc, tag, id='', el_class='', text='') {\n var element = document.createElement(tag);\n if (id != '') {\n element.setAttribute('id', id);\n }\n if (el_class != '') {\n element.setAttribute('class', el_class);\n }\n if (text != '') {\n element.innerText = text;\n }\n loc.prepend(element);\n return element;\n}",
"get element() {\n return this.dom;\n }",
"create_dom_url_element(arg_dom_element, arg_tag, arg_id, arg_url, arg_type)\n\t{\n\t\t// SEARCH DEVAPT BOOTSTRAP SCRIPT TAG\n\t\tconst devapt_bootstrap_element = document.getElementById('js-devapt-bootstrap')\n\t\tconst has_bootstrap_element = devapt_bootstrap_element ? arg_dom_element == devapt_bootstrap_element.parentNode : false\n\n\t\tlet e = document.getElementById(arg_id)\n\t\tif (e)\n\t\t{\n\t\t\tif (e.getAttribute('src') == arg_url)\n\t\t\t{\n\t\t\t\twindow.devapt().monitor_asset_loading(arg_tag, arg_id, arg_url, e, true)\n\t\t\t\treturn\n\t\t\t}\n\t\t\te.parentNode.removeChild(e)\n\t\t}\n\t\t\n\t\te = document.createElement(arg_tag)\n\t\te.setAttribute('id', arg_id)\n\t\te.setAttribute('src', arg_url)\n\t\te.setAttribute('type', arg_type)\n\t\t// e.setAttribute('async', 'false')\n\n\t\twindow.devapt().monitor_asset_loading(arg_tag, arg_id, arg_url, e, false)\n\n\t\tif (has_bootstrap_element)\n\t\t{\n\t\t\targ_dom_element.insertBefore(e, devapt_bootstrap_element)\n\n\t\t\treturn\n\t\t}\n\t\targ_dom_element.appendChild(e)\n\t}",
"injectElement() {\n document.body.innerHTML = `\n <${this.tagName}></${this.tagName}>\n `;\n mount(this.tagName);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calls a callback with the correct object fragment and key from a compound name | function objectAndKeyFromAttributesAndName(attributes, name, options, callback) {
var key,
object = attributes,
keys = name.split('['),
mode = options.mode;
for (var i = 0; i < keys.length - 1; ++i) {
key = keys[i].replace(']', '');
if (!object[key]) {
if (mode === 'serialize') {
object[key] = {};
} else {
return callback(undefined, key);
}
}
object = object[key];
}
key = keys[keys.length - 1].replace(']', '');
callback(object, key);
} | [
"each(callback, ...names) {\n const {\n stack\n } = this;\n const {\n length\n } = stack;\n let value = getLast(stack);\n\n for (const name of names) {\n value = value[name];\n stack.push(name, value);\n }\n\n for (let i = 0; i < value.length; ++i) {\n if (i in value) {\n stack.push(i, value[i]); // If the callback needs to know the value of i, call\n // path.getName(), assuming path is the parameter name.\n\n callback(this);\n stack.length -= 2;\n }\n }\n\n stack.length = length;\n }",
"getItemsInBucket(arg = {bucket: null, callback: (bucketItem)=>{}}){\n if(arg.bucket != null && arg.bucket.contents != null){\n let contents = arg.bucket.contents\n if(!Array.isArray(contents)){\n contents = [contents];\n }\n for(let i = 0; i < contents.length; i++){\n let url = `${AWS_BASE_URL}${arg.bucket.name}/${contents[i].Key}`;\n this.makeJSONFetchRequest({url:url, callback:(jsonResponse)=>{\n if(typeof arg.callback === 'function'){\n let data = {\n name: this.jsonFileNameToTitle(contents[i].Key),\n data: jsonResponse\n }\n arg.callback(data);\n }\n }});\n }\n }\n }",
"visitRename_object(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"kvProps(key: string, name: ?string = null) {\n let finalName = name;\n if (!finalName) {\n if (/^[a-zA-Z_][a-zA-Z_0-9]*$/.test(key)) {\n finalName = key;\n } else {\n throw new Error(`HrQuery::kvProps expected either the second argument to be provided, or for the first argument to be a valid identifier.`);\n }\n }\n const desc = this.kvDesc(key);\n\n if (!desc) return {};\n\n const props = {\n [finalName]: desc.value,\n [`${finalName}Error`]: desc.error,\n [`${finalName}HasError`]: desc.hasError,\n [`${finalName}Loading`]: desc.loading,\n [`${finalName}Etc`]: desc.etc || {},\n };\n\n return props;\n }",
"splitFunctionFromKey (theKey) {\n if (theKey !== null && theKey.indexOf('(') !== -1) { // Must be an aggregate or queryFunction\n let functionKeyPair = theKey.split('('); // Split function and property\n let functionAlias = functionKeyPair[0];\n let fieldName = functionKeyPair[1];\n\n let queryFunction = QueryFunctionEnum.getTypeFromAlias(functionAlias);\n\n log.log('splitFunctionFromKey queryFunction', functionAlias, queryFunction);\n\n if (queryFunction !== null) {\n this.queryFunction = queryFunction;\n this.key = fieldName.replace(')', ''); // Remove closing parenthesis from the key\n } else {\n log.error('Unrecognized function alias used by constraint - ' + functionAlias);\n }\n } else {\n log.info('In splitFunctionFromKey, set this.key = ', theKey);\n this.key = theKey;\n }\n }",
"function storeIBjson(gdun, jsonBodyToStore, callback) {\t\t\t\t\n\n\t// put the data in the ECS bucket\n\tvar params = {\n\t\tBucket: 'installBase',\n\t\tKey: gdun + '.json',\n\t\tBody: JSON.stringify(jsonBodyToStore)\n\t};\t \n\t \n\tecs.putObject(params, function(err, data) {\n\t\tif (err) {\n\t\t\t// an error occurred\n\t\t\tconsole.log('Error in ECS putObject: ' + err, err.stack); \n\t\t} else {\n\t\t\t// successful response\n\t\t\t\n\t\t\ttry {\n\t\t\t\tvar parsedBodyToStore = JSON.parse(jsonBodyToStore);\n\t\t\t\tvar customer = parsedBodyToStore.rows[0].CS_CUSTOMER_NAME;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t} catch (e) {\n\t\t\t\tvar customer = 'not able to retrieve';\n\t\t\t}\t\t\n\t\n\t\t\tconsole.log(gdun + '.json object saved to ECS for customer: ' + customer);\n\t\t\tjsonBodyToStore = null; // free up memory\n\t\t\tcallback(null, customer); // this is the callback saying this storeIBjson function is complete\t\t\t\n\t\t};\n\t});\n}",
"fire(name, ...args) {\n if (this._cb.hasOwnProperty(name)) {\n this._cb[name](...args);\n }\n }",
"kvMap( fn ){}",
"function correct_name(name, gbid, id) {\n\t$.ajax({\n\t\turl: '/loves/revise_title.json',\n\t\tcontentType: 'application/json',\n\t\tdata: JSON.stringify({ page: { \"name\":name, \"id\":id, \"gbid\":gbid } }),\n\t\tdataType: 'json',\n\t\ttype: 'PUT',\n\t\tsuccess: function(data,text){\n\t\t// \t// put everything in here or it won't run on click\n\t\t// \t// batchId = data.batchId;\n\t\tlog(data);\n\t\t// \t//$(\"#progressbar\").show();\n\t\t}\n\t});\n}",
"function getObj(addr, cb) {\n dbContract.get(addr, function(error, data){\n console.log(addr, data);\n cb(JSON.parse(data));\n });\n}",
"function uploadFileAndStoreURL(file, object, name, callback)\n{ \n let fd = new FormData();\n fd.append(file.name, file);\n \n $.ajax({\n accepts: 'application/json',\n url: '/upload',\n data: fd,\n type: 'POST',\n contentType: false,\n processData: false,\n \n success: function(data) {\n object[name] = data.url;\n if(callback) {\n callback(data.url);\n }\n },\n error: function (xhr, ajaxOptions, thrownError) {\n \n }\n });\n}",
"queueLoadDiff(commentID, key, onFragmentRendered) {\n this.diffFragmentQueue.queueLoad(commentID, key, onFragmentRendered);\n }",
"function invoke(modulename, version, methodname, param, callback) {\n var moduleObject = getModuleByVersion(modulename, version);\n if (typeof callback === 'function') {\n if (moduleObject[methodname]) {\n moduleObject[methodname](param, callback);\n }\n else {\n console.log(\"method does not exist\");\n }\n }\n else {\n if (moduleObject[methodname]) {\n moduleObject[methodname](param);\n }\n else {\n console.log(\"method does not exist : Module : \" + modulename + \" , Method : \" + methodname);\n }\n }\n}",
"function processObject(value, dotName)\n\t{\n\t\tvar idx, \n\t\t\tkeys = [], \n\t\t\tidVal = value;\n\t\t\n\t\tif (value instanceof Object)\t\t\t//for Object or function\n\t\t{\n\t\t\tif (!map.objList.includes(value))\n\t\t\t\tmap.objList.push(value);\n\t\t\t\n\t\t\tif (typeof(value) == 'function'\t\t//hach to get list of EZ functions\n\t\t\t&& (value.name && !value.name.startsWith('bound'))\n\t\t\t&& (varName == '$' || value.name.startsWith(varName))\n\t\t\t&& !map.fnList.includes(value))\n\t\t\t\tmap.fnList.push(value);\n\t\t\t\n\t\t\tidx = map.values.indexOf(value);\n\t\t\tif (idx != -1)\t\t\t\t\t\t//if value is repeated Object, \n\t\t\t{\t\t\t\t\t\t\t\t\t//use String pseudo value\n\t\t\t\tvalue = '{$repeat:' + idx + '}';\n\t\t\t\tidVal = '{' + map.keys[idx] + '}';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tkeys = Object.keys(value);\n\t\t\t\tidVal = '[' + keys.join(',') + ']';\n\t\t\t}\t\t\t\n\t\t}\n\n\t\tif (lastMap)\t\t\t\t\t\t\t//compare value to prior map value . . .\n\t\t{\t\t\t\t\t\t\t\t\t\t//next new map index\n\t\t\tvar idx = map.keys.length;\n\t\t\tif (lastMap.keys.length < idx \t\t//if new map bigger than prior\n\t\t\t|| lastMap.keys[idx] !== dotName)\t//if diff dotName\n\t\t\t\treturn false;\t\t\t\t\t//quit comparing\n\n\t\t\tif (idx > 0\t\t\t\t\t\t\t//or if not same value or exact object\n\t\t\t&& lastMap.values[idx] !== value\n\t\t\t&& !isNaN(lastMap.values[idx]) && !isNaN(value))\n\t\t\t\treturn false;\t\t\t\t\t//quit comparing\t\t\n\t\t}\n\t\t\n\t\tmap.id += ',' + dotName + ':' + idVal;\t//append base id\n\t\tif (map.id.startsWith(','))\n\t\t\tmap.id = map.id.substr(1);\n\n\t\tmap.keys.push(dotName);\t\t\t\t\t//add key and pseudo value\n\t\tmap.types.push(EZ.getConstructorName(value));\n\t\tmap.values.push(value);\t\t\n\t\tmap.keysList[dotName] = keys;\n\t\tvar isEq = true;\n\t\tif (keys.length)\n\t\t{\n\t\t\t//var k = map.keysList[key] = [];\n\t\t\t//var v = map.shadowObj[key] = {};\n\t\t\tisEq = keys.every(function(key)\t//for this Object and all nested Object keys \n\t\t\t{\t\t\t\t\t\t\t\t\t//or until new map does not mast lastMap\t\t\t\t\n\t\t\t\t//k.push(key)\n\t\t\t\t//v[key] = value[key];\n\t\t\t\t\n\t\t\t\tvar dot = isNaN(key) ? '.' + key : '[' + key + ']';\n\t\t\t\tvar isEq = processObject(value[key], dotName + dot);\n\t\t\t\treturn isEq;\n\t\t\t});\n\t\t}\n\t\treturn isEq;\n\t}",
"function updateFuncName(obj) {\r\n\r\n var sO = CurStepObj;\r\n //\r\n if (!sO.isSpaceActive) {\r\n var pos = sO.activeChildPos;\r\n var fname = obj.innerHTML;\r\n\r\n if (isExistingName(CurModObj, CurFuncObj, CurStepObj, fname)) {\r\n\r\n alert(\"Function name \" + fname + \" already exists!\");\r\n\r\n } else {\r\n\r\n sO.activeParentExpr.exprArr[pos].str = obj.innerHTML;\r\n }\r\n\r\n // Redraw program structure heading to indicate new function name\r\n //\r\n drawProgStructHead(); // update program structre heading\r\n drawCodeWindow(sO);\r\n }\r\n}",
"visitSchema_object_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDotted_as_name(ctx) {\r\n console.log(\"visitDotted_as_name\");\r\n if (ctx.NAME() !== null) {\r\n return {\r\n type: \"Imported\",\r\n name: this.visit(ctx.dotted_name()),\r\n alias: ctx.NAME().getText(),\r\n };\r\n } else {\r\n return {\r\n type: \"Imported\",\r\n name: this.visit(ctx.dotted_name()),\r\n alias: null,\r\n };\r\n }\r\n }",
"visitRecord_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"rectifySignalReferencesByName(){\r\n this.plottedSignalsMap.forEach((ps, sigName) => {\r\n var newSig = this.signalFromNameCallback(sigName);\r\n if(newSig != null){\r\n ps.signal = newSig;\r\n }\r\n });\r\n }",
"function multipleCallbacks (myObject, callback1, callback2){\n var myObject = {status: ['success', 'error']};\n var keyValue = Object.values(myObject.status);\n for (let i=0; i<keyValue.length; i++){\n if (keyValue[i] === 'success'){\n return callback1;\n } else return callback2;\n}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Widgets: Main IMGUI_API bool Button(const char label, const ImVec2& size = ImVec2(0,0)); // button | function Button(label, size = ImVec2.ZERO) {
return bind.Button(label, size);
} | [
"function addButton(size) {\r\n\r\n}",
"button(x, y, content, opts){\n\n let button = new Button(x, y, content, opts);\n this.layer.buttons.push(button);\n return button;\n\n }",
"function drawButton(btn) {\n // Move text down 1 pixel and lighten background colour on mouse hover\n var textOffset;\n if (btn.state === 1) {\n btn.instances.current.background[3] = 0.8;\n textOffset = 1;\n } else {\n btn.instances.current.background[3] = 1.;\n textOffset = 0;\n }\n // Draw button rectangle\n mgraphics.set_source_rgba(btn.instances.current.background);\n mgraphics.rectangle(btn.rect);\n mgraphics.fill();\n // Draw button text\n mgraphics.select_font_face(MPU.fontFamily.bold);\n mgraphics.set_font_size(MPU.fontSizes.p);\n // Calculate text position\n var Xcoord = MPU.margins.x + (btn.rect[2] / 2) - (mgraphics.text_measure(btn.instances.current.text)[0] / 2);\n var Ycoord = MPU.margins.y + btn.rect[1] + (mgraphics.font_extents()[0] / 2) + textOffset;\n mgraphics.move_to(Xcoord, Ycoord);\n mgraphics.set_source_rgba(btn.instances.current.color);\n mgraphics.text_path(btn.instances.current.text);\n mgraphics.fill();\n}",
"function MinecraftButton(textSize, enableSound, customTextColor)\n{\n\t// textSize is the size of the text, enableSound is a boolean that when sets to true makes the button do a sound when pressed, customTextColor is the string of the color\n\n\tif(textSize == null)\n\t\ttextSize = MinecraftButtonLibrary.defaultButtonTextSize;\n\tif(enableSound == null)\n\t\tenableSound = true;\n\tif(customTextColor == null)\n\t\tcustomTextColor = MinecraftButtonLibrary.defaultButtonTextColor;\n\n\tvar button = new android.widget.Button(MinecraftButtonLibrary.context);\n\tbutton.setTextSize(textSize);\n\tbutton.setOnTouchListener(new android.view.View.OnTouchListener()\n\t{\n\t\tonTouch: function(v, motionEvent)\n\t\t{\n\t\t\tMinecraftButtonLibrary.onTouch(v, motionEvent, enableSound, customTextColor);\n\t\t\treturn false;\n\t\t}\n\t});\n\tif (android.os.Build.VERSION.SDK_INT >= 14) // 4.0 and up\n\t\tbutton.setAllCaps(false);\n\tMinecraftButtonLibrary.setButtonBackground(button, MinecraftButtonLibrary.ProcessedResources.mcNormalNineDrawable);\n\tbutton.setTag(false); // is pressed?\n\tbutton.setSoundEffectsEnabled(false);\n\tbutton.setGravity(android.view.Gravity.CENTER);\n\tbutton.setTextColor(android.graphics.Color.parseColor(customTextColor));\n\tbutton.setPadding(MinecraftButtonLibrary.convertDpToPixel(MinecraftButtonLibrary.defaultButtonPadding), MinecraftButtonLibrary.convertDpToPixel(MinecraftButtonLibrary.defaultButtonPadding), MinecraftButtonLibrary.convertDpToPixel(MinecraftButtonLibrary.defaultButtonPadding), MinecraftButtonLibrary.convertDpToPixel(MinecraftButtonLibrary.defaultButtonPadding));\n\tMinecraftButtonLibrary.addMinecraftStyleToTextView(button, MinecraftButtonLibrary.defaultButtonTextShadowColor, MinecraftButtonLibrary.defaultButtonTextLineSpacing);\n\n\treturn button;\n}",
"function ColorButton(desc_id, col, flags = 0, size = ImVec2.ZERO) {\r\n return bind.ColorButton(desc_id, col, flags, size);\r\n }",
"function InvisibleButton(str_id, size) {\r\n return bind.InvisibleButton(str_id, size);\r\n }",
"function makeWhaleSharkButton() {\n\n // Create the clickable object\n whaleSharkButton = new Clickable();\n \n whaleSharkButton.text = \"\";\n\n whaleSharkButton.image = images[23]; \n\n //makes the button color transparent \n whaleSharkButton.color = \"#00000000\";\n whaleSharkButton.strokeWeight = 0; \n\n //set width + height to image size\n whaleSharkButton.width = 270; \n whaleSharkButton.height = 390;\n\n // placing the button on the page \n whaleSharkButton.locate( width * (31/32) - whaleSharkButton.width * (31/32), height * (1/128) - whaleSharkButton.height * (1/128));\n\n // // Clickable callback functions for the whaleshark button , defined below\n whaleSharkButton.onPress = whaleSharkButtonPressed;\n whaleSharkButton.onHover = beginButtonHover;\n whaleSharkButton.onOutside = animalButtonOnOutside;\n}",
"function drawMapButton() \n{\n fill(0);\n rect(buttonX, buttonY, buttonWidth, buttonHeight);\n fill(255);\n text('Click here to change mappings', buttonX + 7, buttonY + 20);\n}",
"function makeOctopusButton() {\n\n // Create the clickable object\n octopusButton = new Clickable();\n \n octopusButton.text = \"\";\n\n octopusButton.image = images[21]; \n\n // makes the image transparent\n octopusButton.color = \"#00000000\";\n octopusButton.strokeWeight = 0; \n\n // set width + height to image size\n octopusButton.width = 290; \n octopusButton.height = 160;\n\n // places the button \n octopusButton.locate( width * (13/16) - octopusButton.width * (13/16), height * (1/2) - octopusButton.height * (1/2));\n\n // Clickable callback functions, defined below\n octopusButton.onPress = octopusButtonPressed;\n octopusButton.onHover = beginButtonHover;\n octopusButton.onOutside = animalButtonOnOutside;\n}",
"displayButtonAnimated() {\n //Button\n rectMode(CENTER);\n textSize(this.buttonAnimated.size);\n textFont(this.buttonAnimated.textFont);\n\n stroke(this.buttonAnimated.strokeColor);\n strokeWeight(this.buttonAnimated.strokeWeight);\n noFill();\n rect(\n this.buttonAnimated.x,\n this.buttonAnimated.y,\n this.buttonAnimated.width,\n this.buttonAnimated.height,\n this.buttonAnimated.cornerRadius\n );\n\n fill(this.buttonAnimated.color);\n textAlign(CENTER, CENTER);\n text(\n this.buttonAnimated.text,\n this.buttonAnimated.x,\n this.buttonAnimated.y\n );\n }",
"function makeDolphinButton() {\n\n // Create the clickable object\n dolphinButton = new Clickable();\n \n dolphinButton.text = \"\";\n\n dolphinButton.image = images[18]; \n\n // gives the dolphin a transparent background \n dolphinButton.color = \"#00000000\";\n dolphinButton.strokeWeight = 0; \n\n // set width + height to image size\n dolphinButton.width = 401; \n dolphinButton.height = 266;\n\n // places the button \n dolphinButton.locate( width * (1/2) - dolphinButton.width * (1/2), height * (1/4) - dolphinButton.height * (1/4));\n\n // Clickable callback functions, defined below\n dolphinButton.onPress = dolphinButtonPressed;\n dolphinButton.onHover = beginButtonHover;\n dolphinButton.onOutside = animalButtonOnOutside;\n}",
"function make_button(text, hover, click) {\n var btn = buttons.append('g').classed('button', true);\n \n var bg = btn.append('ellipse')\n .attr(\"rx\", rx).attr(\"ry\", ry)\n .attr(\"cx\", cx).attr(\"cy\", cy);\n var txt = btn.append('text').text(text)\n .attr(\"text-anchor\", \"middle\")\n .attr(\"x\", cx).attr(\"y\", function () {\n var height = d3.select(this).style(\"height\").split(\"px\")[0];\n return height / 3 + cy;\n });\n \n // Setup Event Handlers\n btn.on(\"mouseover\", function () {\n btn.classed(\"hover\", true);\n txt.text(hover);\n bg.transition().duration(250).attr(\"ry\",\n function () {\n return d3.select(this).attr(\"rx\");\n });\n }).on(\"mouseout\", function () {\n btn.classed(\"hover\", false);\n txt.text(text);\n bg.transition().duration(250).ease('linear').attr(\"ry\", ry);\n }).on(\"click\", click);\n return btn;\n }",
"function alpha_button(textin,xpos_in,ypos_in,widthin,actif,varif,active)\r\n{\r\n if (draw_button(xpos_in,ypos_in,widthin,alpha_button_height,Hcontext,control_button_style,alpha_button_corner,\"src\",active,HmouseX,HmouseY,Hmouse_clicking))\r\n {\r\n if (actif)\r\n {\r\n button_next_action_2 = actif;\r\n }\r\n if (varif)\r\n {\r\n button_next_var_2 = varif;\r\n }\r\n }\r\n draw_text(xpos_in,ypos_in,widthin,alpha_button_height,3,textin,0,button_height*0.55,button_height*0.55,button_text_col,'',Hcontext);\r\n}",
"function makeBleachingButton() {\n\n // Create the clickable object\n bleachingButton = new Clickable();\n \n bleachingButton.text = \"What is bleaching?\";\n bleachingButton.textColor = \"#365673\"; \n bleachingButton.textSize = 25; \n\n bleachingButton.color = \"#8FD9CB\";\n\n // set width + height to image size\n bleachingButton.width = 380;\n bleachingButton.height = 62;\n\n // places the button on the page \n bleachingButton.locate( width * (12/32) , height * (7/8));\n\n // // Clickable callback functions, defined below\n bleachingButton.onPress = bleachingButtonPressed;\n bleachingButton.onHover = beginButtonHover;\n bleachingButton.onOutside = beginButtonOnOutside;\n}",
"function makeMantaRayButton() {\n\n // Create the clickable object\n mantaRayButton = new Clickable();\n \n mantaRayButton.text = \"\";\n\n mantaRayButton.image = images[16]; \n\n // gives the Manta ray a transparent background \n mantaRayButton.color = \"#00000000\";\n mantaRayButton.strokeWeight = 0; \n\n // set width + height to image size\n mantaRayButton.width = 242; \n mantaRayButton.height = 156;\n\n // places the button on the page \n mantaRayButton.locate( width * (1/32) - mantaRayButton.width * (1/32), height * (1/3) - mantaRayButton.height * (1/3));\n\n // // Clickable callback functions, defined below\n mantaRayButton.onPress = mantaRayButtonPressed;\n mantaRayButton.onHover = beginButtonHover;\n mantaRayButton.onOutside = animalButtonOnOutside;\n}",
"function makeCoralReefButton() {\n\n // Create the clickable object\n coralReefButton = new Clickable();\n \n coralReefButton.text = \"Click here to see your coral reef!\";\n coralReefButton.textColor = \"#365673\"; \n coralReefButton.textSize = 37; \n\n coralReefButton.color = \"#8FD9CB\";\n\n // set width + height to image size\n coralReefButton.width = 994;\n coralReefButton.height = 90;\n\n // places the button on the page \n coralReefButton.locate( width/2 - coralReefButton.width/2 , height * (3/4));\n\n // // Clickable callback functions, defined below\n coralReefButton.onPress = coralReefButtonPressed;\n coralReefButton.onHover = beginButtonHover;\n coralReefButton.onOutside = beginButtonOnOutside;\n}",
"function makeJellyfishButton() {\n\n // Create the clickable object\n jellyfishButton = new Clickable();\n \n jellyfishButton.text = \"\";\n\n jellyfishButton.image = images[19]; \n\n // makes the image have a transparent background \n jellyfishButton.color = \"#00000000\";\n jellyfishButton.strokeWeight = 0; \n\n // // set width + height to image size\n jellyfishButton.width = 278; \n jellyfishButton.height = 120;\n\n // places the button on the page \n jellyfishButton.locate( width * (1/2) - jellyfishButton.width * (1/2), height * (3/4) - jellyfishButton.height * (3/4));\n\n // // Clickable callback functions, defined below\n jellyfishButton.onPress = jellyfishButtonPressed;\n jellyfishButton.onHover = beginButtonHover;\n jellyfishButton.onOutside = animalButtonOnOutside;\n}",
"function button(div, id, gid, cb, tooltip) {\n if (!divExists(div, 'button')) return null;\n\n var btnDiv = createDiv(div, 'button', id),\n cbFnc = fs.isF(cb) || noop;\n\n is.loadIcon(btnDiv, gid, btnSize, true);\n if (tooltip) { tts.addTooltip(btnDiv, tooltip); }\n\n btnDiv.on('click', cbFnc);\n\n return {\n id: id,\n width: buttonWidth,\n };\n }",
"toggleButton(id, value) {\n if (id in this.asset.map.buttons) {\n if (typeof value !== 'undefined') {\n this.asset.config.buttons[this.asset.map.buttons[id]].hidden = value;\n }\n else {\n this.asset.config.buttons[this.asset.map.buttons[id]].hidden = !this.asset.config.buttons[this.asset.map.buttons[id]].hidden;\n }\n this._emitChange('buttons');\n return true;\n }\n return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
addViews, handle cold videos and save game | function newViews() {
if (variables.cooldown <= 0) {
variables.cooldown = COOLDOWNTIME_VIDEO;
bake_cookie("chocolateChipCookie", variables, 14); //save game in cookie every COOLDOWNTIME_VIDEO seconds
if (variables.videos - variables.coldVideos > 10) {
variables.coldVideos++;
if (DEBUG) {console.log("coldVideos=" + variables.coldVideos);}
}
}
variables.cooldown--;
addViews(variables.videos - variables.coldVideos);
} | [
"function addGameView() {\n // Destroy Menu screen\n stage.removeChild(TitleView);\n TitleView = null;\n\n // Add Game View\n stage.addChild(bg, world, goal, rewards[0], rewards[1], restart, die, player, InventoryView);\n\n //Call startGame\n startGame();\n}",
"addViews(views) {\n for (let i = 0; i < views.length; i++)\n this.addView(views[i]);\n }",
"function stackTimelineView() {\n\n ViewVideo.OverlayTimeline.CollisionDetection({spacing:0, includeVerticalMargins: true});\n ViewVideo.adjustLayout();\n ViewVideo.adjustHypervideo();\n\n }",
"function changeView() {\n $(\"#titleScreen\").empty();\n $(\"#gameScreen\").show();\n}",
"insertVideos() {\n for(let i = 0; i < this.options.src.length; i++) {\n let videoTypeArr = this.options.src[i].split('.');\n let videoType = videoTypeArr[videoTypeArr.length - 1];\n\n this.addSourceToVideo(this.options.src[i], `video/${videoType}`);\n }\n }",
"_renderVitamins () {\n this._emptyContainer();\n this.vitamins.forEach(vit => this._container.appendChild(vit.element));\n console.log(Texts.RENDERING_VITAMINS);\n }",
"function generateGameViewPreview() {\n\t\tvar xSize = $('#xSize').val() || 0;\n\t\tvar ySize = $('#ySize').val() || 0;\n\t\t\n\t\tif(!validateDimensions(xSize, ySize)) {\n\t\t\treturn;\n\t\t}\n\t\tvar seed = $('#seed').val(); \n\t\tvar gameState = initializeGameState(xSize, ySize, seed);\n\t\tvar gameView = paintGameView(gameState);\n\t\t// Lower the opacity so it's clear it's a preview\n\t\tgameView.fadeTo(0, 0.5);\n\t}",
"function setupView() {\n // set home button view point to initial extent\n var homeButton = new Home({\n view: view,\n viewpoint: new Viewpoint({\n targetGeometry: initialExtent\n })\n });\n \n var track = new Track({\n viewModel:{\n view:view,\n scale: 100000\n }\n });\n\n // layer list\n var layerList = new LayerList({\n view: view, \n listItemCreatedFunction: function(event){\n var item = event.item;\n \n if (item.title === \"Trail Heads\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"th\"),\n open: true\n }\n } else if (item.title === \"Point of Interest\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"poi\"),\n open: true\n }\n } else if (item.title === \"Visitor Recommendations\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"rec\"),\n open: true\n }\n } else if (item.title === \"Roads\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"road\"),\n open: true\n }\n } else if (item.title === \"Trails\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"trail\"),\n open: true\n }\n }\n }\n });\n \n // expand layer list\n layerExpand = new Expand({\n expandIconClass: \"esri-icon-layers\",\n expandTooltip: \"Turn on and off Map Layers\",\n expanded: false,\n view: view,\n content: layerList,\n mode: \"floating\", \n group:\"top-left\"\n });\n \n\n // expand widget for edit area\n editExpand = new Expand({\n expandIconClass: \"esri-icon-edit\",\n expandTooltip: \"Add a Visitor Recommendation\",\n expanded: false,\n view: view,\n content: editArea,\n mode: \"floating\",\n group:\"top-left\"\n });\n \n // expand widget for query\n var query = document.getElementById(\"info-div\");\n queryExpand = new Expand ({\n expandIconClass: \"esri-icon-filter\",\n expandTooltip: \"Filter Points of Interest\",\n expanded: false,\n view: view,\n content: query,\n mode: \"floating\",\n group:\"top-left\"\n });\n \n // search widget\n var searchWidget = new Search({\n view:view,\n allPlaceholder: \"Search for SNP Places\",\n locationEnabled: false,\n sources: [{\n featureLayer: poi,\n resultSymbol: {\n type: \"simple-marker\",\n color: [0, 0, 0, 0],\n size: \"17px\",\n style: \"square\",\n outline: {\n color: [0, 255, 255, 1],\n width: \"2px\"\n }\n },\n outFields: [\"*\"],\n popupTemplate: poiP\n }, {\n featureLayer:aoi,\n resultSymbol: {\n type: \"simple-marker\",\n color: [0, 0, 0, 0],\n size: \"17px\",\n style: \"square\",\n outline: {\n color: [0, 255, 255, 1],\n width: \"2px\"\n }\n },\n outFields: [\"*\"],\n popupTemplate: aoiP\n }, {\n featureLayer: trailheads,\n resultSymbol: {\n type: \"simple-marker\",\n color: [0, 0, 0, 0],\n size: \"17px\",\n style: \"square\",\n outline: {\n color: [0, 255, 255, 1],\n width: \"2px\"\n }\n },\n outFields: [\"*\"],\n popupTemplate: trailheadsP\n }, {\n featureLayer:trails,\n resultSymbol: {\n type: \"simple-line\",\n color: [0, 255, 255, 1],\n width: \"2px\"\n },\n outFields: [\"*\"],\n popupTemplate: trailsP\n }]\n });\n // search expand\n searchExpand = new Expand({\n expandIconClass: \"esri-icon-search\",\n expandTooltip: \"Search for SNP Places\",\n view: view,\n content: searchWidget,\n mode: \"floating\",\n group:\"top-left\"\n });\n \n // add all widgets to view \n view.ui.move( \"zoom\", \"bottom-right\");\n view.ui.add([homeButton, track, layerExpand], \"bottom-right\")\n view.ui.add([searchExpand, queryExpand, layerExpand, editExpand],\"top-left\");\n }",
"function cargarVideo(url,imagen){\r\n var v = document.createElement(\"video\"); \r\n //if ( (!v.play) && (!Liferay.Browser.isSafari())) { // If no, use Flash.\r\n if(!Modernizr.video){\r\n var params = {\r\n allowfullscreen: \"true\",\r\n allowscriptaccess: \"always\",\r\n wmode:\"transparent\"\r\n };\r\n var flashvars = {\r\n config: \"{'playlist':[ {'url': '\"+url+\"','autoPlay':false,'autoBuffering':true}]}&\" \r\n };\r\n //swfobject.embedSWF(\"http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf\", \"video\", \"480\", \"272\", \"9.0.0\", \"expressInstall.swf\", flashvars, params);\r\n swfobject.embedSWF(\"flowplayer-3.2.1.swf\", \"video\", \"480\", \"272\", \"9.0.0\", \"expressInstall.swf\", flashvars, params);\r\n }\r\n}",
"function updateView() {\n // Check for Game Over\n if (questionsKeys.length < 1) {\n stop();\n mkInvisible(\"#questionsContainer\");\n setText(\"#correctAnswersCount\", gameInfo.toatlWin);\n setText(\"#wrongAnswersCount\", gameInfo.totalLost);\n setText(\"#noAnswersCount\", gameInfo.notAnswered);\n mkVisible(\"#gameOverContainer\");\n\n return;\n }\n // Get a rand key ussing splice (splice return a Array)\n let _key = questionsKeys.splice(rand(questionsKeys.length), 1);\n // Get randon object from questionsObjects using splice to void erpetitive questions\n let _obj = questionsObjects[_key[0]];\n // Get string question\n let _question = _obj.question;\n // Set the question\n setText(\"#question\", _question);\n // Get the correct_answer (it will be the return of this function)\n correctAnswer = _obj.correct_answer;\n // Add correct_answer to incorrect_answers array to shuffle\n _obj.incorrect_answers.push(correctAnswer);\n // Get all answer buttons\n let _questionButtons = document.querySelector(\"#btnColumn\").children\n // Random place correct and incorrect answer on the buttons\n for (let _btn of _questionButtons) {\n let _question = _obj.incorrect_answers.splice(rand(_obj.incorrect_answers.length), 1)[0];\n _btn.innerHTML = _question;\n }\n // Get Correct answer gif url\n getCorrectAnswerGIF(`right answer ${correctAnswer}`);\n // Get wronganswer git url\n getWrongAnswerGIF();\n // remove gif animation displayGIF\n mkInvisible(\"#displayGIF\");\n // display timerHearder, question and btnColumn\n mkVisible(\"#timerHearder\", \"#question\", \"#btnColumn\");\n // Stop timer\n stop();\n // Reset counter\n // timerCounter = 30;\n timerCounter = 10; ///////////////////////////////////////////////////////////////\n //Start timer and update each 1 second\n startTimer(updateTimer, 1);\n}",
"function TriageViewStandalone(container, values) {\n // Container is unused (global hardcoded dialog is used)\n this.videoPlayer = null;\n this.container = container;\n\n this.div = document.createElement('div');\n $(this.div).html(' <h2> <span class=\"triageLabel\"> </span> </h2> ' +\n '<br/> ' +\n '<div class=\"row-fluid\"> ' +\n '<div class=\"span4\"> ' +\n '<div class=\"row-fluid\"> ' +\n '<div class=\"triageClipEvidences\" class=\"span4\"> ' +\n '</div> ' +\n '</div> ' +\n '<div class=\"row-fluid\"> ' +\n '<div class=\"triageAdjudicationHeading\" class=\"span4\"> ' +\n '<h4> Adjudication </h4> <br/>' +\n\n '<div class=\"triageAdjudication\" class=\"span4\"> </div>' +\n '</div> ' +\n\n '</div> ' +\n '</div> ' +\n '<div class=\"triageVideo video-container span8\"> ' +\n '</div> ' +\n '</div> ' +\n '<div class=\"row-fluid\"> ' +\n '<div class=\"span12\"> ' +\n '<div class=\"triageTimeLineView\"></div> ' +\n '</div> ' +\n '</div> ' +\n '<div class=\"row-fluid\"> ' +\n '<div class=\"span12\"> ' +\n '<div class=\"triageFilmStripView\"></div> ' +\n '</div> ' +\n '</div> '\n );\n\n $(this.div).appendTo($(this.container));\n this.Init(values);\n this.adjudication = new Adjudication({container : $(this.div).find(\".triageAdjudication\")[0], clip : this.data.clip, display:true, opacity : 0.5});\n $(this.adjudication.div).css(\"position\",\"relative\");\n\n var that = this;\n // TODO: This should be called after results\n $(this.div).find('.triageClipEvidences').on('click', 'div label', function(event) {\n //if (!that.textView || !that.timelineView) {\n // return;\n //}\n\n event.stopPropagation();\n\n // Select current element\n that.textView.selectElement(this);\n var labelObj = $(this);\n\n// console.log('selecting......', labelObj.text());\n\n var timestamps = that.timelineView.select(labelObj.text());\n that.filmstripView.HideAll();\n for(var i=0; i < timestamps.length; i++)\n {\n that.filmstripView.SelectTimestamp(timestamps[i], \"selectframe_text\")\n }\n });\n\n// // Now initialize the timeline\n// $('#myModal').on('shown', function() {\n// if (that.currentClipId === null || that.currentClipId !== that.clip_id) {\n// return;\n// }\n// // Now show it\n// var clipEvidencesObj = $('#clipEvidences');\n// var timelineViewObj = $('#timelineView');\n// var filmstripViewObj = $('#filmstripView');\n//\n// // that.textView = new textView(clipEvidencesObj.get(0), that.data);\n// // that.timelineView = new timelineView(timelineViewObj.get(0), that.data);\n// // that.currentClipId = null;\n//\n// // Get the data\n// //var algorithm = $(\"#algorithms-combo\").find('option:selected').data('algo');\n\n\n //this.updateResults(that.kit_id, that.clip_id);\n\n $('body').on('selectedStandAlone', function(event, name, timestamp, x, y) {\n // that.filmstripView.SelectTime(event, timestamp);\n //alert('' + x+ y);\n that.filmstripView.ClearHighlight();\n that.filmstripView.SelectTimestamp(timestamp, \"selectframe_timeline\");\n that.selectStandalone(name, timestamp);\n });\n\n//\n// $('#myModal').on('hidden', function () {\n// // Clear current rendering\n// that.currentClipId = null;\n// if (that.videoPlayer) {\n// that.videoPlayer.pause();\n// }\n// });\n//\n// //$(this.div).click(function()\n//\n\n // Respond to adjugation buttons\n\n// $(this.div).find(\".triageAdjudication img\").click(function(event) {\n//\n// event.stopPropagation();\n// // TODO: Send the ajax to api\n//\n// switch($(this).attr(\"class\")) {\n// case \"yes\":\n// if ($(this).attr('src') === '/img/carbon-verified.png') {\n// $(this).attr('src', '/img/carbon-verified_on.png')\n// $(this).next().attr('src', '/img/carbon-rejected.png')\n// $(this).next().next().attr('src', '/img/carbon-star2.png')\n// } else {\n// $(this).attr('src', '/img/carbon-verified.png')\n// }\n// break;\n// case \"no\":\n// if ($(this).attr('src') === '/img/carbon-rejected.png') {\n// $(this).attr('src', '/img/carbon-rejected_on.png')\n// $(this).next().attr('src', '/img/carbon-star2.png')\n// $(this).prev().attr('src', '/img/carbon-verified.png')\n// } else {\n// $(this).attr('src', '/img/carbon-rejected.png')\n// }\n// break;\n// case \"star\":\n// if ($(this).attr('src') === '/img/carbon-star2.png') {\n// $(this).attr('src', '/img/carbon-star_on.png')\n// $(this).prev().attr('src', '/img/carbon-rejected.png')\n// $(this).prev().prev().attr('src', '/img/carbon-verified.png')\n// } else {\n// $(this).attr('src', '/img/carbon-star2.png')\n// }\n// break;\n// }\n// });\n//\n// var that = this;\n//\n// $(this.div).find(\".triageAdjudication div\").click(function(event) {\n// event.stopPropagation();\n//\n// // if ($(this).hasClass('btn')) {\n// // $(that.div).find(\".triageAdjudication div\").find('.myLabel').show();\n// // console.log($('#adjudication div').find('input').text());\n// // $(that.div).find(\".triageAdjudication div\").find('label').text($(that.div).find(\".triageAdjudication div\").find('input').val());\n// // $(that.div).find(\".triageAdjudication div\").find('input').addClass(\"disabled\");\n// // }\n// // if ($(this).hasClass('myLabel')) {\n// // $(that.div).find(\".triageAdjudication div\").find('input').val($(this).text());\n// // $(this).hide();\n// // $(that.div).find(\".triageAdjudication div\").find('input').show();\n// // }\n// if ($(event.target).hasClass('input')) {\n// //console.log(\"enabled\");\n// //$(event.target).removeAttr(\"disabled\",\"\");\n// }\n//\n// });\n//\n//$(this.div).find('.triageAdjudication div').find('input').keypress(function(e) {\n// if(e.which == 13) {\n// $(that.div).find(\".triageAdjudication div\").find('.myLabel').show();\n// //console.log($('#adjudication div').find('input').text());\n// //$(that.div).find(\".triageAdjudication div\").find('label').text($(that.div).find(\".triageAdjudication div\").find('input').val());\n// //$(that.div).find(\".triageAdjudication div\").find('input').attr(\"disabled\",\"\");\n// $(that.div).find(\".triageAdjudication div\").find('input').blur();\n// }\n// e.stopPropagation();\n// });\n\n}",
"function onPlayerAddOrRemove() {\n showHideVisibleColorOptions();\n enableOrDisablePlayerAddButton();\n enableOrDisableStartGameButton();\n}",
"function seqRender(views, done) {\n // Once all views have been rendered invoke the sequence render\n // callback\n if (!views.length) {\n return done();\n }\n\n // Get each view in order, grab the first one off the stack\n var view = views.shift();\n\n // This View is now managed by LayoutManager *toot*.\n view.__manager__.isManaged = true;\n\n // Render the View and once complete call the next view.\n view.render(function () {\n // Invoke the recursive sequence render function with the remaining\n // views\n seqRender(views, done);\n });\n }",
"function setUpSingleViewHandler() {\r\n const temp = document.querySelector(\"#template\")\r\n document.querySelector('#paintTable').addEventListener('click', function (e) {\r\n if (e.target.getAttribute('id') == 'title') {\r\n document.querySelector(\".galleryList\").style.display = \"none\"\r\n document.querySelector(\".singleView\").style.display = \"block\"\r\n document.querySelector(\".galleryInfo\").style.display = \"none\"\r\n document.querySelector(\"#map\").style.display = \"none\"\r\n document.querySelector(\".paintings\").style.display = \"none\"\r\n document.querySelector(\"#plus\").style.display = \"none\"\r\n document.querySelector(\"#minus\").style.display = \"none\"\r\n temp.innerHTML = \"\"\r\n for (let p of paintings) {\r\n if (e.target.getAttribute('alt') == p.Title && e.target.getAttribute('class') == p.LastName) {\r\n //first populates the single painting\r\n const fig = document.createElement(\"figure\");\r\n const img = document.createElement(\"img\");\r\n img.setAttribute('src', \"https://res.cloudinary.com/funwebdev/image/upload/w_800/art/paintings/\" + p.ImageFileName);\r\n img.setAttribute('id', \"bigimage\")\r\n fig.appendChild(img);\r\n temp.appendChild(fig)\r\n //creates the large version of the painting view \r\n mod = document.querySelector('#large')\r\n mod.innerHTML = \"\"\r\n const modImg = document.createElement(\"img\");\r\n modImg.setAttribute('src', \"https://res.cloudinary.com/funwebdev/image/upload/w_1500/art/paintings/\" + p.ImageFileName);\r\n modImg.setAttribute('id', \"biggestImage\")\r\n mod.appendChild(modImg)\r\n //creates the figure caption for the single image \r\n const figCap = document.createElement(\"figcaption\");\r\n figCap.setAttribute(\"id\", \"info\")\r\n const title = document.createElement(\"h2\");\r\n title.textContent = p.Title;\r\n figCap.appendChild(title);\r\n const artist = document.createElement(\"h3\");\r\n if (p.FirstName == null) {\r\n artist.textContent = p.LastName;\r\n }\r\n else if (p.LastName == null) {\r\n artist.textContent = p.FirstName;\r\n }\r\n else {\r\n artist.textContent = p.FirstName + \" \" + p.LastName;\r\n }\r\n figCap.appendChild(artist);\r\n //populates the figure caption with all the painting info\r\n const ul = document.createElement(\"ul\")\r\n const l1 = document.createElement(\"li\");\r\n const l2 = document.createElement(\"li\");\r\n const l3 = document.createElement(\"li\");\r\n const l4 = document.createElement(\"li\");\r\n const l5 = document.createElement(\"li\");\r\n const l6 = document.createElement(\"li\");\r\n const l7 = document.createElement(\"li\");\r\n const l8 = document.createElement(\"li\");\r\n const a = document.createElement(\"a\");\r\n const l9 = document.createElement(\"li\");\r\n l1.textContent = \"Year of work: \" + p.YearOfWork;\r\n l2.textContent = \"Medium: \" + p.Medium;\r\n l3.textContent = \"Width: \" + p.Width;\r\n l4.textContent = \"Height: \" + p.Height;\r\n l5.textContent = \"Copyright: \" + p.CopyrightText;\r\n l6.textContent = \"Gallery Name: \" + p.GalleryName;\r\n l7.textContent = \"Gallery city: \" + p.GalleryCity;\r\n a.textContent = p.MuseumLink;\r\n a.setAttribute('href', p.MuseumLink)\r\n l8.setAttribute('id', 'link')\r\n l9.textContent = p.Description;\r\n l9.setAttribute('id', 'des')\r\n\r\n l8.appendChild(a)\r\n ul.appendChild(l1)\r\n ul.appendChild(l2)\r\n ul.appendChild(l3)\r\n ul.appendChild(l4)\r\n ul.appendChild(l5)\r\n ul.appendChild(l6)\r\n ul.appendChild(l7)\r\n ul.appendChild(l8)\r\n ul.appendChild(l9)\r\n //populates the primary colors in the fig caption\r\n figCap.appendChild(ul)\r\n for (let c of p.JsonAnnotations.dominantColors) {\r\n span = document.createElement('span')\r\n console.log(c.color.red)\r\n span.style.backgroundColor = \"rgb(\" + c.color.red + \",\" + c.color.green + \",\" + c.color.blue + \")\"\r\n span.setAttribute('title', \"Name: \" + c.name + \" HEX: \" + c.web)\r\n figCap.appendChild(span)\r\n }\r\n fig.appendChild(figCap)\r\n temp.appendChild(fig)\r\n\r\n }\r\n }\r\n }\r\n\r\n\r\n })\r\n }",
"displayMovieFromLS() {\n const movies = this.getMovieFromLS()\n movies.forEach(movie => {\n this.addMovieToUI(movie)\n })\n }",
"function addVideo(e) {\n const id = (e.target.id !== 'addVideo')\n ? e.target.value\n : domCache['videoId'].value;\n const found = state.videos.filter(video => id === video.id);\n\n if (e && e.target.id === 'addVideo' && found.length > 0) {\n log('add video', `not added; id ${id} already in list`);\n return;\n }\n\n const func = (!state.player)\n ? setPlayer\n : loadVideo;\n\n func(id).then((loaded) => {\n // video is loaded, will be updated in loaded event.\n }).catch(function(error) {\n // the video did not load.\n log(`${func.name} called`, `video id ${id} not loaded.`);\n });\n }",
"newScene() {\n if (confirm(\"Clear all objects of current room?\")) {\n let room_buffer = this._room_canvas;\n let scale_buffer = this._scale;\n let canvas_objects = room_buffer.getObjects();\n\n canvas_objects.forEach(function (item, i) {\n\n if (item.type == 'player') {\n\n item.LineArray = [];\n item.PathArray = [];\n getReferenceById(item.AGObjectID).clearRoute();\n getReferenceById(item.AGObjectID).movable = false;\n\n }\n if (item.isObject && item.type != 'player') {\n\n\n getReferenceById(item.AGObjectID).kill();\n }\n if (item.type != 'grid_line' && item.type != 'player') {\n room_buffer.remove(item);\n }\n });\n\n\n this.deleteItemsEventsEtc();\n room_buffer.renderAll();\n }\n }",
"function displayView(view) {\n console.log(view);\n // hämta alla sidor/get all views\n const pageView = document.getElementById(\"page1\") \n const loginView = document.getElementById(\"logIn\") \n const varningView = document.getElementById(\"varning\") \n \n \n // dölj alla sidor/hide all views\n pageView.style.display = \"none\"\n loginView.style.display = \"none\"\n varningView.style.display = \"none\" \n \n\n // visa den specifika sidan/display specified view\n if (view === 'pageView') {\n pageView.style.display = \"block\"\n }\n \n if (view === 'loginView') {\n loginView.style.display = \"block\"\n }\n\n if (view === 'varningView') {\n varningView.style.display = \"block\"\n } \n \n}",
"function PhotonsView(html_id) {\n var DEFAULT_ID = 'energy2d-photons-view',\n DEFAULT_CLASS = 'energy2d-photons-view',\n PHOTON_LENGTH = 10,\n $photons_canvas,\n canvas_ctx,\n canvas_width,\n canvas_height,\n photons,\n scale_x,\n scale_y,\n scene_width,\n scene_height,\n //\n // Private methods.\n //\n initHTMLelement = function initHTMLelement() {\n $photons_canvas = $('<canvas />');\n $photons_canvas.attr('id', html_id || DEFAULT_ID);\n $photons_canvas.addClass(DEFAULT_CLASS);\n canvas_ctx = $photons_canvas[0].getContext('2d');\n },\n setCanvasStyle = function setCanvasStyle() {\n canvas_ctx.strokeStyle = \"rgba(255,255,255,128)\";\n canvas_ctx.lineWidth = 0.5;\n },\n //\n // Public API.\n //\n photons_view = {\n // Render vectormap on the canvas.\n renderPhotons: function renderPhotons() {\n var photon, sx, sy, r, i, len;\n\n if (!photons) {\n throw new Error(\"Photons view: bind parts array before rendering.\");\n }\n\n canvas_ctx.clearRect(0, 0, canvas_width, canvas_height);\n\n for (i = 0, len = photons.length; i < len; i += 1) {\n photon = photons[i];\n sx = photon.x * scale_x;\n sy = photon.y * scale_y;\n r = 1 / Math.sqrt(photon.vx * photon.vx + photon.vy * photon.vy);\n canvas_ctx.beginPath();\n canvas_ctx.moveTo(sx, sy);\n canvas_ctx.lineTo(sx + PHOTON_LENGTH * photon.vx * r, sy + PHOTON_LENGTH * photon.vy * r);\n canvas_ctx.stroke();\n }\n },\n // Bind vector map to the view.\n bindPhotonsArray: function bindPhotonsArray(new_photons, new_scene_width, new_scene_height) {\n photons = new_photons;\n scene_width = new_scene_width;\n scene_height = new_scene_height;\n scale_x = canvas_width / scene_width;\n scale_y = canvas_height / scene_height;\n },\n getHTMLElement: function getHTMLElement() {\n return $photons_canvas;\n },\n resize: function resize() {\n canvas_width = $photons_canvas.width();\n canvas_height = $photons_canvas.height();\n scale_x = canvas_width / scene_width;\n scale_y = canvas_height / scene_height;\n $photons_canvas.attr('width', canvas_width);\n $photons_canvas.attr('height', canvas_height);\n setCanvasStyle();\n }\n }; // One-off initialization.\n\n\n initHTMLelement();\n setCanvasStyle();\n return photons_view;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to get MetaData for both the Demographic Info Panel and to build/update Gauge chart | function getMetadata(sampleId) {
d3.json("samples.json").then((data) => {
console.log(data)
var metadata = data.metadata;
//console.log(metadata)
var metadataArray = metadata.filter(metadataObject => metadataObject.id == sampleId);
//console.log(metadataArray)
var metadataResult = metadataArray[0]
//console.log(metadataResult)
// Update the Demographic Info panel data reflected on the screen with the selected "Test Subject ID No"
var demoInfo = d3.select("#sample-metadata");
demoInfo.html("");
Object.entries(metadataResult).forEach(([key, value]) => {
demoInfo.append("h6").text(`${key}: ${value}`);
});
// BONUS: Wash Frequency Gauge Chart
var washFrequency = metadataResult.wfreq;
var gaugeData = [
{
type: "indicator",
mode: "gauge+number",
value: washFrequency,
title: { text: "Wash Frequency", font: { size: 24 } },
gauge: {
axis:
{ range: [0, 9], tickcolor: "darkblue" },
bar: { color: "teal" },
bgcolor: "white",
borderwidth: 2,
bordercolor: "lightgray",
steps: [
{ range: [0, 9], color: "beige", label: "0-1" }
],
}
}
];
var gaugeLayout = {
width: 500,
height: 400,
margin: { t: 100,
r: 30,
l: 30,
b: 30 },
paper_bgcolor: "white",
font: { color: "teal", family: "Arial" }
};
Plotly.newPlot('gauge', gaugeData, gaugeLayout);
//Plotly.newPlot('gauge', gaugeData, gaugeLayout);
});
} | [
"function buildMDataPanel (data, variableID){\n\n var mData = data.metadata.filter( d => d.id == variableID)[0];\n \n var div = d3.select(\"#sample-metadata\");\n // remove any children from the div, \n div.html(\"\");\n Object.entries(mData).forEach(([key, value]) => {\n var p = div.append(\"p\");\n p.text(`${key}: ${value}`);\n });\n}",
"function getMetricsData() {\n //select Average Page View\n data.avgPageView = $('#card_metrics > section.engagement > div.flex > div:nth-child(1) > p.small.data').text().replace(/\\s\\s+/g, '').split(' ')[0];\n\n //select Average Time On Site\n data.avgTimeOnSite = $('#card_metrics > section.engagement > div.flex > div:nth-child(2) > p.small.data').text().replace(/\\s\\s+/g, '').split(' ')[0];\n\n //select Bounce Rate\n data.bounceRate = $('#card_metrics > section.engagement > div.flex > div:nth-child(3) > p.small.data').text().replace(/\\s\\s+/g, '').split(' ')[0];\n\n //select Search Traffic Percent\n data.searchTrafficPercent = $('#card_mini_competitors > section.group > div:nth-child(2) > div.ThirdFull.ProgressNumberBar > span').text();\n\n //select Overall Rank\n data.overallRank = $('#card_rank > section.rank > div.rank-global > div:nth-child(1) > div:nth-child(2) > p.big.data').text().replace(/\\s+/g, ''); //.replace(/,/g, '');\n\n }",
"function moreInfo()\n{\n\tif (darkSky)\n\t{\n\t\tvar msg = \"\";\n\t\tmsg = msg.concat(\"Maximum Temperature: \" + darkSky.daily.data[0].temperatureMax + \"\\n\");\n\t\tmsg = msg.concat(\"Minimum Temperature: \" + darkSky.daily.data[0].temperatureMin + \"\\n\");\n\t\tmsg = msg.concat(\"Wind Speed: \" + darkSky.daily.data[0].windSpeed + \"\\n\");\n\t\tmsg = msg.concat(\"Precipitation: \" + darkSky.daily.data[0].precipIntensity + \"\\n\");\n\t\tmsg = msg.concat(\"Humidity: \" + darkSky.daily.data[0].humidity + \"\\n\");\n\t\tmsg = msg.concat(\"Pressure: \" + darkSky.daily.data[0].pressure + \"\\n\");\n\t\tmsg = msg.concat(\"Ozone: \" + darkSky.daily.data[0].ozone + \"\\n\");\n\t\tmsg = msg.concat(\"Visibility: \" + darkSky.daily.data[0].visibility + \"\\n\");\n\t\talert(msg);\n\t}\n\telse\n\t{\n\t\talert(\"Please enter a location\"); ''\n\t}\n}",
"function initGaugeChart() { \n var data = [\n {\n domain: { x: [0, 1], y: [0, 1] },\n value: justmetadata[0].wfreq,\n title: { text: \"Belly Button Washing Frequency (Scrubs per week)\" },\n type: \"indicator\",\n mode: \"gauge+number\",\n gauge: {\n axis: { range: [0, 9] },\n steps: [\n { range: [0, 1], color: \"rgb(255,102,102)\" },\n { range: [1, 2], color: \"rgb(255,153,153)\" },\n { range: [2, 3], color: \"rgb(255,204,204)\" },\n { range: [3, 4], color: \"rgb(255,229,204)\" },\n { range: [4, 5], color: \"rgb(204,255,153)\" },\n { range: [5, 6], color: \"rgb(178,255,102)\" },\n { range: [6, 7], color: \"rgb(153,255,51)\" },\n { range: [7, 8], color: \"rgb(51,255,51)\" },\n { range: [8, 9], color: \"rgb(0,255,0)\" }\n ],\n }\n }\n ];\n \n var layout = { width: 600, height: 450, margin: { t: 0, b: 0 } };\n Plotly.newPlot('gauge', data, layout);\n }",
"function getMainDataMap() {\n return {\n fans: {\n metric: 'fans',\n getter: commonGetters.getChannelsSeparatelyGetter('breakdownValues')\n },\n fansValue: {\n metric: 'fans',\n getter: commonGetters.getOnlyFromChannelsGetter('totalValue')\n },\n fansChangeValue: {\n metric: 'fans',\n getter: commonGetters.getOnlyFromChannelsGetter('changeValue')\n },\n fansChangePercent: {\n metric: 'fans',\n getter: commonGetters.getOnlyFromChannelsGetter('changePercent'),\n formatters: [\n dataFormatters.decimalToPercent\n ]\n }\n };\n} // end getMainDataMap",
"read_data_info() {\n this.json.data_info = {};\n this.add_string(this.json.data_info, \"date_and_time\");\n this.add_string(this.json.data_info, \"scan_summary\");\n this.json.data_info.apply_data_calibration = this.ole.read_bool();\n this.add_string(this.json.data_info, \"data_calibration_file\");\n this.add_string(this.json.data_info, \"certificate_file\");\n this.add_string(this.json.data_info, \"system_file\");\n this.add_string(this.json.data_info, \"pre_scan_addon_description\");\n this.add_string(this.json.data_info, \"post_scan_addon_description\");\n this.add_string(this.json.data_info, \"pre_scan_addon_filename\");\n this.add_string(this.json.data_info, \"post_scan_addon_filename\");\n this.add_string(this.json.data_info, \"type_and_units\");\n this.add_string(this.json.data_info, \"type_and_units_code\");\n this.add_string(this.json.data_info, \"auxiliary_type_and_units\");\n this.add_string(this.json.data_info, \"auxiliary_type_and_units_code\");\n this.json.data_info.apply_reference = this.ole.read_bool();\n this.add_string(this.json.data_info, \"reference_type\");\n this.add_string(this.json.data_info, \"reference_file\");\n this.add_string(this.json.data_info, \"reference_parameter\");\n this.json.data_info.file_time = this.ole.read_systemtime();\n\n // Read and discard measurement units and types;\n // these are in the data info as well\n // ar.Read(Buffer, 4*sizeof(int));\n this.ole.skip_uint32(4);\n\n // Right axis settings\n // ar >> TempInt;\n // ar.Read(Buffer, m_nNoOfDataSets*sizeof(int));\n this.ole.skip_uint32();\n this.ole.skip_uint32(this.json.data_set.length);\n }",
"function doMetaData() {\n\t\t\t// Metadata!!\n\n\t\t\t// Featured star!\n\t\t\t// These don't have anything unique, so we can construct whole hearted.\n\n\t\t\tif (($('#featured-star').length) \n\t\t\t\t|| ($('#protected-icon').length)\n\t\t\t\t|| ($('#good-star').length)\n\t\t\t\t|| ($('#spoken-icon').length) ) {\n\t\t\t\t// constuct the metadata box\n\t\t\t\tvar mdBox = $('<div />').addClass('rr_box').addClass('rr_mdcontainer');\n\n\t\t\t\t// Featured\n\t\t\t\tif ($('#featured-star').length) {\n\t\t\t\t\t// Remove the extant featured-star\n\t\t\t\t\t$('#featured-star').remove();\n\t\t\t\t\tvar tBox = $('<div />').addClass('rr_mdbox')\n\t\t\t\t\t\t\t\t\t.addClass('rr_fs')\n\t\t\t\t\t\t\t\t\t.text('Featured')\n\t\t\t\t\t\t\t\t\t.click(function() {\n\t\t\t\t\t\t\t\t\t\twindow.location = \"index.html?page=Wikipedia:Featured_articles\";\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\tmdBox.append(tBox);\n\t\t\t\t} else if ($('#good-star').length) {\n\t\t\t\t\t$('#good-star').remove();\n\t\t\t\t\tvar tBox = $('<div />').addClass('rr_mdbox')\n\t\t\t\t\t\t\t\t\t.addClass('rr_fs')\n\t\t\t\t\t\t\t\t\t.text('Good')\n\t\t\t\t\t\t\t\t\t.click(function() {\n\t\t\t\t\t\t\t\t\t\twindow.location = \"index.html?page=Wikipedia:Good_articles\";\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\tmdBox.append(tBox);\n\t\t\t\t}\n\n\t\t\t\t// Protected\n\t\t\t\tif ($('#protected-icon').length) {\n\t\t\t\t\t// Remove the extant featured-star\n\t\t\t\t\t$('#protected-icon').remove();\n\t\t\t\t\tvar tBox = $('<div />').addClass('rr_mdbox')\n\t\t\t\t\t\t\t\t\t.addClass('rr_prot')\n\t\t\t\t\t\t\t\t\t.text('Protected')\n\t\t\t\t\t\t\t\t\t.click(function() {\n\t\t\t\t\t\t\t\t\t\twindow.location = \"index.html?page=Wikipedia:Protection_policy\";\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\tmdBox.append(tBox);\n\t\t\t\t}\n\t\t\t\t// Spoken icon. Specialized.\n\t\t\t\tif ($('#spoken-icon').length) {\n\t\t\t\t\t//<a href=\"index.html?page=File:4chan.ogg\" title=\"File:4chan.ogg\"><img alt=\"Sound-icon.svg\" src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Sound-icon.svg/15px-Sound-icon.svg.png\" width=\"15\" height=\"11\" srcset=\"//upload.wikimedia.org/wikipedia/commons/thumb/4/47/Sound-icon.svg/23px-Sound-icon.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/4/47/Sound-icon.svg/30px-Sound-icon.svg.png 2x\" data-file-width=\"128\" data-file-height=\"96\"></a>\n\t\t\t\t\t// Remove the extant featured-star\n\t\t\t\t\t$('#spoken-icon').remove();\n\t\t\t\t\tvar tBox = $('<div />').addClass('rr_mdbox')\n\t\t\t\t\t\t\t\t.addClass('rr_spoken').text('Listen');\n\t\t\t\t\tmdBox.append(tBox);\n\t\t\t\t}\n\t\t\t\t$('#wsidebar').append(mdBox);\n\t\t\t}\n\t\t}",
"function getHealthInfo() {\n healthInfo.value = null;\n if (isSmoke.value == true) {\n var myDict = smoking_health_facts;\n healthInfo.add({ info: get_single_string(myDict) });\n healthInfo.add({ info: get_single_string(myDict) });\n healthInfo.add({ info: get_single_string(myDict) });\n } else {\n var myDict = snus_health_facts;\n healthInfo.add({ info: get_single_string(myDict) });\n }\n}",
"function buildCharts(formatedData) {\n buildRevenueChart(formatedData);\n buildGenderChart(formatedData);\n} // END: bulidCharts",
"function getDatasetInfoById(ds_id) {\n var ds_info, i;\n for (i = 0; i < entry.datasets.length; i++) {\n ds_info = entry.datasets[i];\n if (ds_info[\"id\"] == ds_id) {\n ds_info[\"ref\"] = i; //reference for pulling out datasetinfo from coresponding lists like colorbars\n return ds_info;\n break;\n }\n }\n}",
"function populateMetadata(visInfo) {\n visInfo.visitor.role = getHashedIndexFromArray(roles, visInfo.visitor.id);\n visInfo.visitor.team = getHashedIndexFromArray(teams, visInfo.visitor.id);\n visInfo.visitor.title = `${getHashedIndexFromArray(\n titlePrefixes,\n visInfo.visitor.id\n )}${getHashedIndexFromArray(\n titles[visInfo.visitor.team],\n visInfo.visitor.id\n )}`;\n visInfo.visitor.region = getHashedIndexFromArray(regions, visInfo.visitor.id);\n visInfo.visitor.office = getHashedIndexFromArray(\n offices[visInfo.visitor.region],\n visInfo.visitor.id\n );\n visInfo.visitor.system = getHashedIndexFromArray(systems, visInfo.visitor.id);\n\n return visInfo;\n}",
"function addMetaData(container, callback) {\n $('[data-id]', container).each(function (i, row) {\n var $item, model, id, data;\n\n $item = $(row);\n model = $item.attr('data-class');\n id = $item.attr('data-id');\n\n if (metaData && metaData[model] && metaData[model][id]) {\n data = metaData[model][id];\n appendMetaData(row, model, id, data);\n }\n });\n\n if (callback) {\n callback();\n }\n }",
"function getSettings() {\n var chartType = $scope.layout.prop.minichart.type;\n var amountMes = $scope.layout.qHyperCube.qMeasureInfo.length;\n\n switch (chartType) {\n case 'bar':\n switch (amountMes) {\n case 1:\n picassoSettings = chartdef.bar1mes($scope.layout.prop);\n break;\n case 2:\n picassoSettings = chartdef.bar2mes($scope.layout.prop);\n break;\n }\n break;\n case 'line':\n switch (amountMes) {\n case 1:\n picassoSettings = chartdef.line1mes($scope.layout.prop);\n break;\n case 2:\n picassoSettings = chartdef.line2mes($scope.layout.prop);\n break;\n }\n break;\n case 'gauge':\n picassoSettings = chartdef.gauge1mes($scope.layout.prop);\n break;\n }\n }",
"getMetricsData() {\n\n let innerMap = new Map();\n\n // Get interactions for each agent in current time\n for (let agent of this.agents) {\n this.getInteractions(innerMap, agent);\n }\n\n //save interactions for the current tick time.\n this.metricsMap.set(world.getTicks(), innerMap);\n\n for (let agent of this.agents) {\n this.recordAgentViscosityData(agent);\n }\n\n let vscsty = this.recordGlobalViscosityData();\n\n document.getElementById(\"viscosityInWorld\").innerHTML = vscsty.toFixed(2);\n }",
"_createInfoArray(decoratedImage, title, subtitle, mainDescription, secondaryDescription, link, htmlDescription) {\n let data = Object.assign({},\n decoratedImage ? { decoratedImage } : {},\n title ? { title } : {},\n subtitle ? { subtitle } : {},\n mainDescription ? { mainDescription } : {},\n secondaryDescription ? { secondaryDescription } : {},\n link ? { link } : {},\n htmlDescription ? { htmlDescription } : {}\n );\n this.set('description', [ data ]);\n }",
"function drawOneChart(chartInfo, jsondata)\r\n{\r\n if(jsondata==null||jsondata.resp==null\r\n ||jsondata.resp.results==null||jsondata.resp.results.results==null)\r\n {\r\n return 0;\r\n }\r\n \r\n var margin = chartInfo.margin;\r\n if(margin == null)margin = DEFAULT_MARGIN;\r\n\r\n d3.select(\"#\"+chartInfo.domid).select(\"svg\").remove();//remove old chart\r\n\r\n var parseDate = d3.time.format(\"%Y%m%d%H%M%S\").parse;\r\n\r\n //now extract our data\r\n var data = [];\r\n var mattr = [];//metrics attribute\r\n var times = [], avg = [], ts = [];\r\n var dlist = jsondata.resp.results.results;//metrics data\r\n var mdesc = jsondata.resp.results.metrics;//metrics descriptor from data\r\n var keys = jsondata.resp.results.keys; //some metrics might have multiple keys/entities, such as disk metrics\r\n var num_keys = keys!=null?keys.length: 0;\r\n var len = dlist.length;\r\n console.log(\"Data size for \" + chartInfo.label + \" \" + len);\r\n var i=0, j = 0, inc = 0; //inc=1 indicate some data are incremental data\r\n \r\n //initialize and exract metrics attribute\r\n var metrics = chartInfo.metrics;\r\n for(j = 0; j < metrics.length; j++)\r\n {\r\n var m = metrics[j]; //meta data provided by chartInfo will overwrite whatever from data set\r\n var mname = m.name; //metric name\r\n var mdata = mdesc != null? mdesc[mname]: null; //metric meta data from data\r\n if(num_keys == 0)\r\n\t data[j] = [];//for each metric, there will be one row\r\n\telse\r\n\t{\r\n\t for(var k = 0; k<num_keys; k++)\r\n\t data[j*num_keys + k] = []; \r\n\t}\r\n mattr[j] = new Object(); \r\n metrics[j].shortName = metrics[j].name;\r\n if(mdata != null)\r\n {\r\n if(mdata[\"shortName\"] != null)\r\n metrics[j].shortName = mdata[\"shortName\"];\r\n if (m.inc == null)\r\n \tmattr[j].inc = eval(mdata[\"inc\"]);\r\n else\r\n mattr[j].inc = m.inc;\r\n \r\n if (m.avg == null)\r\n \tmattr[j].avg = mdata[\"avg\"];\r\n else\r\n mattr[j].avg = m.avg; \t\r\n if(mattr[j].inc == 1 && mattr[j].avg == null)mattr[j].avg=\"min\";\r\n \r\n if(m.adj == null)\r\n\t\tmattr[j].adj = eval(mdata[\"adj\"]);\r\n\t else\r\n\t mattr[j].adj = m.adj;\r\n\t \r\n\t if(m.label == null) \r\n \tmattr[j].display = getMetricName(mname) + \"(\"+ mdata[\"display\"]+\")\";\r\n else\r\n mattr[j].display = m.label;\r\n if (mattr[j].display == null && mattr[j].inc == 1)\r\n mattr[j].display = getMetricName(mname) + \"(/\"+ mattr[j].avg.toUpperCase() +\")\";\r\n else if (mattr[j].display == null)\r\n mattr[j].display = getMetricName(mname); \r\n }else //if not set, treat as inc, avg by one minute\r\n {\r\n mattr[j].inc = 1;\r\n mattr[j].avg = \"min\";\r\n mattr[j].adj = 1;\r\n mattr[j].display = getMetricName(mname) +\"(/MIN)\";\r\n }\r\n if(mattr[j].inc==1)inc = 1;\r\n }\r\n \r\n //reprocess timestamp and data\r\n for(i=0;i<len;i++)\r\n {\r\n var srcrow = dlist[i];//source row, each row has one timestamp\r\n times[i] = \"\"+srcrow[\"TS\"];//extract time stamp\r\n ts[i] = parseDate(times[i]);\r\n for(j=0;j<metrics.length;j++)\r\n {\r\n if(num_keys == 0)\r\n \tdata[j][i] = srcrow[metrics[j].shortName];//extract metric data\r\n else\r\n {\r\n for(var k = 0; k <num_keys; k++)\r\n data[j*num_keys + k][i] = srcrow[metrics[j].shortName][keys[k].shortName];\r\n }\r\n }\r\n }\r\n\r\n //reprocess data\r\n //if any metric is incremental, we need calculate the diff and shift the other\r\n if(inc==1)\r\n {\r\n //we need get the diff of the data\r\n for(j=0;j<metrics.length;j++)\r\n {\r\n if(mattr[j].inc == 1)\r\n {\r\n var avgAdjust = 1;\r\n if(mattr[j].avg=='sec')avgAdjust = 1000;\r\n else if(mattr[j].avg=='min')avgAdjust = 60000;\r\n else if(mattr[j].avg=='hour')avgAdjust = 3600000;\r\n for(i=0;i<len-1;i++)\r\n {\r\n var interval = ts[i+1].getTime() - ts[i].getTime();\r\n if(num_keys == 0)\r\n {\r\n //data[j][i] = data[j][i+1]>=data[j][i]?data[j][i+1]-data[j][i]:data[j][i+1];\r\n //note directly use raw data can have unwanted spike when there is issue with data collection\r\n if(data[j][i+1]>=data[j][i])data[j][i] = data[j][i+1]-data[j][i];\r\n else if(i>0) data[j][i] = data[j][i-1];\r\n else data[j][i] = 0;\r\n \r\n if(interval>0)\r\n data[j][i] = eval((data[j][i]*avgAdjust*mattr[j].adj/interval).toFixed(3));\r\n }else\r\n {\r\n for(var k = 0; k<num_keys; k++)\r\n {\r\n var jk = j*num_keys+k;\r\n //data[jk][i] = data[jk][i+1]>=data[jk][i]?data[jk][i+1]-data[jk][i]:data[jk][i+1];\r\n if(data[jk][i+1]>=data[jk][i])data[jk][i] = data[jk][i+1]-data[jk][i];\r\n else if(i>0) data[jk][i] = data[jk][i-1];\r\n else data[jk][i] = 0;\r\n \r\n if(interval>0)\r\n data[jk][i] = eval((data[jk][i]*avgAdjust*mattr[j].adj/interval).toFixed(3));\r\n }\r\n }\r\n }//for loop\r\n }//if(mattr[j].inc==1)\r\n else\r\n {\r\n for(i=0;i<len-1;i++)\r\n {\r\n if(num_keys == 0)\r\n\t data[j][i] = eval((data[j][i+1]*mattr[j].adj).toFixed(3));//otherwise, shift\r\n\t else\r\n\t {\r\n for(var k = 0; k<num_keys; k++)\r\n {\r\n var jk = j*num_keys+k;\r\n\t data[jk][i] = eval((data[jk][i+1]*mattr[j].adj).toFixed(3));//otherwise, shift\r\n }\t \r\n\t }\r\n\t }\r\n }\r\n if(num_keys == 0)\r\n data[j].length = data[j].length - 1;\r\n else\r\n {\r\n for(var k = 0; k<num_keys; k++)\r\n {\r\n var jk = j*num_keys+k;\r\n data[jk].length = data[jk].length - 1;\r\n }\r\n }\r\n }\r\n for(i=0;i<len-1;i++)\r\n {\r\n times[i] = times[i+1];\r\n }\r\n times.length = times.length - 1;\r\n }//inc = 1\r\n else\r\n {\r\n for(j=0;j<metrics.length;j++)\r\n {\r\n for(i=0;i<data[j].length;i++)\r\n {\r\n if(num_keys == 0)\r\n data[j][i] = eval((data[j][i]*mattr[j].adj).toFixed(3));\r\n else\r\n {\r\n for(var k = 0; k<num_keys; k++)\r\n {\r\n var jk = j*num_keys+k;\r\n data[jk][i] = eval((data[jk][i]*mattr[j].adj).toFixed(3));\r\n }\r\n }\r\n }\r\n }\r\n //we still need shift by 1, otherwise we cannot align with inc=1\r\n for(i=0;i<len-1;i++)\r\n {\r\n times[i] = times[i+1];\r\n }\r\n times.length = times.length - 1;\r\n for(j=0;j<metrics.length;j++)\r\n {\r\n for(i=0;i<data[j].length;i++)\r\n {\r\n if(num_keys == 0)\r\n data[j][i] = data[j][i+1];\r\n else\r\n {\r\n for(var k = 0; k<num_keys; k++)\r\n {\r\n var jk = j*num_keys+k;\r\n data[jk][i] = data[jk][i+1];\r\n }\r\n }\r\n }\r\n data[j].length = data[j].length -1;\r\n for(var k = 0; k<num_keys; k++)\r\n data[jk].length = data[jk].length -1;\r\n }\r\n }\r\n //calculate average\r\n for(j=0;j<data.length;j++)\r\n {\r\n \tvar sum = 0;\r\n \tfor(i=0;i<data[j].length;i++)\r\n sum+= data[j][i];\r\n if(data[j].length>0)\r\n {\r\n avg[j] = eval((sum/data[j].length).toFixed(3));\r\n ret = 1;\r\n }\r\n else\r\n avg[j] = 0;\r\n }\r\n \r\n var width = chartInfo.width - margin.left - margin.right;\r\n var height = chartInfo.height - margin.top - margin.bottom;\r\n var parseDate = d3.time.format(\"%Y%m%d%H%M%S\").parse;\r\n var formatTime = d3.time.format(\"%Y-%m-%d %H:%M\");\r\n\r\n //axis\r\n var x = d3.time.scale().range([0, width]);\r\n x.domain(d3.extent(times, function(d) { return parseDate(d); }));\r\n var yExtents = d3.extent(d3.merge(data), function (d) { return d; });\r\n \r\n var y = d3.scale.linear().domain([0,yExtents[1]*1.2]).range([height, 0]);\r\n if(yExtents[1]==0)\r\n y = d3.scale.linear().domain([0,1]).range([height, 0]);\r\n var xAxis = d3.svg.axis().scale(x).orient(\"bottom\").ticks(10).tickFormat(d3.time.format('%H:%M'));\r\n var yAxis = d3.svg.axis().scale(y).orient(\"left\").tickFormat(d3.format(\"s\"));\r\n\r\n function make_x_axis()\r\n {\r\n return d3.svg.axis().scale(x).orient(\"bottom\");\r\n }\r\n function make_y_axis()\r\n {\r\n return d3.svg.axis().scale(y).orient(\"left\");\r\n }\r\n\r\n var colors = chartInfo.colors;\r\n //use default colors\r\n var nk = num_keys>0?num_keys:1;\r\n if(colors==null||colors.length==0)\r\n {\r\n colors = [];\r\n var c = d3.scale.category10();\r\n if(metrics.length * nk > 10)\r\n c = d3.scale.category20(); \r\n for(var i=0;i<metrics.length*nk;i++)\r\n colors[i] = c(i);\r\n } \r\n\r\n var svg = d3.select(\"#\"+chartInfo.domid).append(\"svg\")\r\n .attr(\"width\", width + margin.left + margin.right)\r\n .attr(\"height\", height + margin.top + margin.bottom)\r\n .append(\"g\")\r\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\r\n\r\n var gridCss = chartInfo.gridCss, lineCss = chartInfo.lineCss, tooltipCss = chartInfo.tooltipCss, legendCss = chartInfo.legendCss;\r\n if(gridCss == null)gridCss =\"grid\";\r\n if(lineCss == null)lineCss = \"line\";\r\n if(tooltipCss == null)tooltipCss = \"tooltip\";\r\n if(legendCss == null)legendCss = \"legend\";\r\n if(metrics.length>=1)\r\n {\r\n var line = d3.svg.line()\r\n .x(function(d, i) { return x(parseDate(times[i])); })\r\n .y(y);\r\n \r\n svg.append(\"g\")\r\n .attr(\"class\",gridCss)\r\n .attr(\"transform\",\"translate(0,\"+height+\")\")\r\n .call(make_x_axis()\r\n .tickSize(-height, 0,0)\r\n .tickFormat(\"\"));\r\n\r\n svg.append(\"g\")\r\n .attr(\"class\",gridCss)\r\n .call(make_y_axis()\r\n .tickSize(-width, 0,0)\r\n .tickFormat(\"\"));\r\n\r\n var lines = svg.selectAll( \"q\" )//using an non-exist element tag q so that selectAll returns empty selection and path data will be append to svg/g\r\n .data( data )\r\n .enter().append(\"path\")\r\n .attr(\"class\", lineCss)\r\n .attr(\"d\", line)\r\n .attr(\"style\", function(d, i) {return \"stroke: \" + colors[i];});\r\n }\r\n \r\n //tooltip\r\n var div = d3.select(\"body\").append(\"div\") \r\n .attr(\"class\", tooltipCss) \r\n .style(\"opacity\", 0);\r\n \r\n //axis\r\n svg.append(\"g\")\r\n .attr(\"class\", \"x axis\")\r\n .attr(\"transform\", \"translate(0,\" + height + \")\")\r\n .call(xAxis);\r\n\r\n svg.append(\"g\")\r\n .attr(\"class\", \"y axis\")\r\n .call(yAxis);\r\n\r\n //for mouseover\r\n for(var i1=0;i1<data.length;i1++)\r\n {\r\n svg.selectAll(\"dot\") \r\n .data(data[i1])\r\n .enter().append(\"circle\") \r\n .attr(\"r\", 5) \r\n .attr(\"cx\", function(d,i) { var a = x(parseDate(times[i]));return a; })\r\n .attr(\"cy\", function(d,i) { return y(data[i1][i]); }) \r\n .attr(\"fill\", function(d, i) {\r\n\t\t return colors[i1]; \r\n\t })\r\n\t .style(\"opacity\", 0)\r\n\t .on(\"mouseover\", function(d, i) {\r\n\t d3.select(this).transition() \r\n .duration(200) \r\n .style(\"opacity\", 1);\r\n div.transition() \r\n .duration(200) \r\n .style(\"opacity\", 1); \r\n div.html(\"<u>\"+formatTime(parseDate(times[i])) + \"</u><br/>\" + d3.format(\",\")(d)) \r\n .style(\"z-index\", \"1000\") \r\n .style(\"left\", (d3.event.pageX+20) + \"px\") \r\n .style(\"top\", (d3.event.pageY - 28) + \"px\"); \r\n }) \r\n .on(\"mouseout\", function(d) { \r\n\t d3.select(this).transition() \r\n .duration(500) \r\n .style(\"opacity\", 0);\r\n div.transition() \r\n .duration(500) \r\n .style(\"opacity\", 0); \r\n });\r\n }\r\n //metrics labels\r\n var legend = svg.append(\"g\")\r\n .attr(\"class\", legendCss)\r\n\t .attr(\"height\", 100)//.attr(\"width\", 100)\r\n .attr('transform', 'translate(-20,0)');\r\n \r\n legend.selectAll('rect')\r\n .data(num_keys==0?metrics:keys)\r\n .enter()\r\n .append(\"rect\")\r\n\t .attr(\"x\", 25)\r\n .attr(\"y\", function(d, i){ return i * 20;})\r\n\t .attr(\"width\", 10)\r\n\t .attr(\"height\", 10)\r\n\t .style(\"fill\", function(d, i) { \r\n var color = colors[i];\r\n return color;\r\n })\r\n \r\n legend.selectAll('text')\r\n .data(num_keys==0?metrics:keys)\r\n .enter()\r\n .append(\"text\")\r\n\t .attr(\"x\", 40)\r\n .attr(\"y\", function(d, i){ return i * 20 + 9;})\r\n\t .text(function(d, i) {\r\n var text = \"\";\r\n if(num_keys == 0)\r\n text = mattr[i].display;\r\n else\r\n {\r\n var ki = i%num_keys;\r\n var mi = (i - ki)/num_keys;\r\n if(mattr.length>=mi)\r\n text = mattr[mi].display+\"-\"+keys[ki].name;\r\n else\r\n text = keys[ki].name;\r\n }\r\n if(num_keys==0)\r\n text = text +\", AVG: \"+d3.format(\",\")(avg[i]) + \", 95%: \"+d3.format(\",\")(percental(data[i], 95));\r\n return text;\r\n });\r\n \r\n return 1;\r\n}",
"function chartDataCreator() {\n for (var i = 0; i < products.length; i++) {\n chartData.push(products[i].votes);\n chartData.push(products[i].views);\n }\n}",
"function populateMetadataInternal() {\n \"use strict\";\n\n const table = document.getElementById(\"metadataInternal\");\n\n const url = getBaseURL();\n\n fetch(url).then(function (response) {\n if (response.ok) {\n return response.json();\n }\n throw new Error(\"Internal metadata request failed.\");\n }).then(function (data) {\n data.metadata_items.forEach(function (item) {\n tableAppendRow(table, [item.field.name, item.value]);\n });\n }).catch(function (e) {\n tableAppendRow(table, e.toString());\n });\n}",
"function privateDisplaySongMetadata(){\n\t\t/*\n\t\t\tSets all elements that will contain the active song's name metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"name\"]') ){\n\t\t\tvar metaNames = document.querySelectorAll('[amplitude-song-info=\"name\"]');\n\t\t\tfor( i = 0; i < metaNames.length; i++ ){\n\t\t\t\tmetaNames[i].innerHTML = config.active_metadata.name;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all elements that will contain the active song's artist metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"artist\"]') ){\n\t\t\tvar metaArtist = document.querySelectorAll('[amplitude-song-info=\"artist\"]');\n\t\t\tfor( i = 0; i < metaArtist.length; i++ ){\n\t\t\t\tmetaArtist[i].innerHTML = config.active_metadata.artist;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all elements that will contain the active song's album metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"album\"]') ){\n\t\t\tvar metaAlbum = document.querySelectorAll('[amplitude-song-info=\"album\"]');\n\t\t\tfor( i = 0; i < metaAlbum.length; i++ ){\n\t\t\t\tmetaAlbum[i].innerHTML = config.active_metadata.album;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all elements that will contain the active song's cover art metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"cover\"]') ){\n\t\t\tvar coverImages = document.querySelectorAll('[amplitude-song-info=\"cover\"]');\n\t\t\tfor( i = 0; i < coverImages.length; i++ ){\n\t\t\t\t/*\n\t\t\t\t\tChecks to see if first, the song has a defined cover art and uses\n\t\t\t\t\tthat. If it does NOT have defined cover art, checks to see if there\n\t\t\t\t\tis a default. Otherwise it just sets the src to '';\n\t\t\t\t*/\n\t\t\t\tif( config.active_metadata.cover_art_url != undefined){\n\t\t\t\t\tcoverImages[i].setAttribute('src', config.active_metadata.cover_art_url);\n\t\t\t\t}else if( config.default_album_art != '' ){\n\t\t\t\t\tcoverImages[i].setAttribute('src', config.default_album_art);\n\t\t\t\t}else{\n\t\t\t\t\tcoverImages[i].setAttribute('src', '');\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\t/*\n\t\t\tStation information for live streams\n\t\t*/\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's call sign metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"call-sign\"]') ){\n\t\t\tvar metaCallSign = document.querySelectorAll('[amplitude-song-info=\"call-sign\"]');\n\t\t\tfor( i = 0; i < metaCallSign.length; i++ ){\n\t\t\t\tmetaCallSign[i].innerHTML = config.active_metadata.call_sign;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's station name metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"station-name\"]') ){\n\t\t\tvar metaStationName = document.querySelectorAll('[amplitude-song-info=\"station-name\"]');\n\t\t\tfor( i = 0; i < metaStationName.length; i++ ){\n\t\t\t\tmetaStationName[i].innerHTML = config.active_metadata.station_name;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's location metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"location\"]') ){\n\t\t\tvar metaStationLocation = document.querySelectorAll('[amplitude-song-info=\"location\"]');\n\t\t\tfor( i = 0; i < metaStationLocation.length; i++ ){\n\t\t\t\tmetaStationLocation[i].innerHTML = config.active_metadata.location; \n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's frequency metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"frequency\"]') ){\n\t\t\tvar metaStationFrequency = document.querySelectorAll('[amplitude-song-info=\"frequency\"]');\n\t\t\tfor( i = 0; i < metaStationFrequency.length; i++ ){\n\t\t\t\tmetaStationFrequency[i].innerHTML = config.active_metadata.frequency;\n\t\t\t}\t\n\t\t}\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's station art metadata\n\t\t\tTODO: Rename coverImages to stationArtImages\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"station-art\"]') ){\n\t\t\tvar coverImages = document.querySelectorAll('[amplitude-song-info=\"station-art\"]');\n\t\t\t/*\n\t\t\t\t\tChecks to see if first, the song has a defined station art and uses\n\t\t\t\t\tthat. If it does NOT have defined station art, checks to see if there\n\t\t\t\t\tis a default. Otherwise it just sets the src to '';\n\t\t\t\t*/\n\t\t\tfor( i = 0; i < coverImages.length; i++ ){\n\t\t\t\tif( config.active_metadata.cover_art_url != undefined){\n\t\t\t\t\tcoverImages[i].setAttribute('src', config.active_metadata.station_art_url);\n\t\t\t\t}else if( config.default_album_art != '' ){\n\t\t\t\t\tcoverImages[i].setAttribute('src', config.default_album_art);\n\t\t\t\t}else{\n\t\t\t\t\tcoverImages[i].setAttribute('src', '');\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scrolls to the left side of the carousel container | function scrolltoLeft() {
/** Initialize 'width' to device screen width */
var width = window.innerWidth > 0 ? window.innerWidth : screen.width;
/** Scroll to negative screen width on the x-axis */
document.getElementById("carousel-container").scrollTo(-width - width, 0);
} | [
"setCardsScrollLeft() {\n if (this.cardsLeftGlobal) {\n let margin = window.innerWidth >= 1200 ? 62.6 : 52.8;\n const cardWidth = $('.my-card').width() + margin;\n this.$cardTrack.scrollLeft(cardWidth * this.cardsLeftGlobal);\n }\n }",
"function scrolltoRight() {\n /** Initialize 'width' to device screen width */\n var width = window.innerWidth > 0 ? window.innerWidth : screen.width;\n /** Scroll to screen width on the x-axis */\n document.getElementById(\"carousel-container\").scrollTo(width + width, 0);\n}",
"scrollLeft() {\n let x = this.scrollElement.scrollLeft - this.scrollElement.clientWidth;\n let y = this.scrollElement.scrollTop;\n this._scrollTo(x, y);\n }",
"slideLeft() {\n let index = this.state.currentPane > 0 ? this.state.currentPane - 1 : this.state.maxSlides - 1 ;\n this.setState({currentPane : index});\n\n }",
"startAutoScroll() {\n this.selectNextSibling();\n this.setAutoScroll();\n }",
"setStickToCenterLeft() {\n this.logger.debug('setStickToCenterLeft');\n this.view.get$item().stickToCenterLeft(this.controller.getContainment());\n }",
"function leftCursor() {\n let beforeScroll = menu.scrollLeft;\n menu.scrollLeft -= 1;\n if (beforeScroll == menu.scrollLeft) {\n leftArrow.style.display = \"none\";\n } else {\n leftArrow.style.display = \"inline\";\n }\n menu.scrollLeft = beforeScroll;\n}",
"autoScrollOn() {\n const carouselItemsLength = this.carouselItems.length;\n\n if (!this.disableAutoScroll) {\n if (\n this.activeIndexItem === carouselItemsLength - 1 &&\n this.disableAutoRefresh\n ) {\n this.unselectCurrentItem();\n this.selectNewItem(0);\n }\n\n this.autoScrollIcon = PAUSE_ICON;\n this.ariaPressed = FALSE_STRING;\n this.setAutoScroll();\n }\n }",
"function slideLeftToRight(){\t\n\t\t\tinterval=setInterval(moveLeftToRight,settings['interval']);\n\t\t}",
"_carouselScrollOne(Btn) {\r\n let itemSpeed = this.speed;\r\n let translateXval = 0;\r\n let currentSlide = 0;\r\n const touchMove = Math.ceil(this.dexVal / this.itemWidth);\r\n this._setStyle(this.nguItemsContainer.nativeElement, 'transform', '');\r\n if (this.pointIndex === 1) {\r\n return;\r\n }\r\n else if (Btn === 0 && ((!this.loop && !this.isFirst) || this.loop)) {\r\n const currentSlideD = this.currentSlide - this.slideItems;\r\n const MoveSlide = currentSlideD + this.slideItems;\r\n this._btnBoolean(0, 1);\r\n if (this.currentSlide === 0) {\r\n currentSlide = this.dataSource.length - this.items;\r\n itemSpeed = 400;\r\n this._btnBoolean(0, 1);\r\n }\r\n else if (this.slideItems >= MoveSlide) {\r\n currentSlide = translateXval = 0;\r\n this._btnBoolean(1, 0);\r\n }\r\n else {\r\n this._btnBoolean(0, 0);\r\n if (touchMove > this.slideItems) {\r\n currentSlide = this.currentSlide - touchMove;\r\n itemSpeed = 200;\r\n }\r\n else {\r\n currentSlide = this.currentSlide - this.slideItems;\r\n }\r\n }\r\n this._carouselScrollTwo(Btn, currentSlide, itemSpeed);\r\n }\r\n else if (Btn === 1 && ((!this.loop && !this.isLast) || this.loop)) {\r\n if (this.dataSource.length <= this.currentSlide + this.items + this.slideItems &&\r\n !this.isLast) {\r\n currentSlide = this.dataSource.length - this.items;\r\n this._btnBoolean(0, 1);\r\n }\r\n else if (this.isLast) {\r\n currentSlide = translateXval = 0;\r\n itemSpeed = 400;\r\n this._btnBoolean(1, 0);\r\n }\r\n else {\r\n this._btnBoolean(0, 0);\r\n if (touchMove > this.slideItems) {\r\n currentSlide = this.currentSlide + this.slideItems + (touchMove - this.slideItems);\r\n itemSpeed = 200;\r\n }\r\n else {\r\n currentSlide = this.currentSlide + this.slideItems;\r\n }\r\n }\r\n this._carouselScrollTwo(Btn, currentSlide, itemSpeed);\r\n }\r\n }",
"scrollRight() {\n let x = this.scrollElement.scrollLeft + this.scrollElement.clientWidth;\n let y = this.scrollElement.scrollTop;\n this._scrollTo(x, y);\n }",
"function addScrollToCarousel() {\n\t$prevBtn.addEventListener(\"click\", scrollToPrevItem);\n\t$nextBtn.addEventListener(\"click\", scrollToNextItem);\n}",
"function displaceLeft() {\n\tvar currentLeft = $(pictureArray[leftPic]).offset().left;\n\t$(pictureArray[leftPic]).offset({left: currentLeft + slideshowWidth});\n\t\n\tleftPic = (leftPic + 1) % pictureArray.length;\n\t\n\trightPic = (rightPic + 1) % pictureArray.length;\n}",
"subSlideLeft() {\n\n let newSlide = this.state.mainActiveSlide > 0 ? (this.state.mainActiveSlide - 1) : (this.state.mainMaxSlides - 1);\n \n this.changeSlide(newSlide);\n \n }",
"setStickToBottomLeft() {\n this.logger.debug('setStickToBottomLeft');\n this.view.get$item().stickToBottomLeft(this.controller.getContainment());\n }",
"moveLeft() {\n\t\tsuper.moveLeft(KEN_SPRITE_POSITION.moveLeft, KEN_IDLE_ANIMATION_TIME, false, MOVE_SPEED);\n\t}",
"function getScrolledPosition(element){var position;//is not the window element and is a slide?\nif(element.self!=window&&hasClass(element,SLIDES_WRAPPER)){position=element.scrollLeft;}else if(!options.autoScrolling||options.scrollBar){position=getScrollTop();}else{position=element.offsetTop;}//gets the top property of the wrapper\nreturn position;}",
"function topContentLeft() {\n let top_Content_L = gsap.timeline({\n id: \"top content left\"\n });\n top_Content_L.from($top_Content_Left, {\n x: -200,\n autoAlpha: 0,\n duration: 1.5,\n ease: bo\n // delay: 3\n }, 2)\n }",
"function scroll(e) {\n $iFrame.contentWindow.postMessage({\n sender: sender,\n type: 'scroll',\n scroll: {\n left: ($window.pageXOffset || $documentElement.scrollLeft) - ($documentElement.clientLeft || 0),\n top: ($window.pageYOffset || $documentElement.scrollTop) - ($documentElement.clientTop || 0)\n }\n }, '*');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a hex file containing the user's Python from the firmware. | function getHexFile(python) {
var hexlified_python = hexlify(python);
var insertion_point = ':::::::::::::::::::::::::::::::::::::::::::';
return firmware.replace(insertion_point, hexlified_python);
} | [
"function generateProgram()\n\t{\n\t\t// Start code generation from the root\n\t\tgenerateStatement(_AST.root);\n\t\t// Place a break statement after the program to pad the static data\n\t\t_ByteCodeList.push(\"00\");\n\t}",
"function OnWroteExe() {\n // Write the padding to QuadWord Align the embedded JS\n var padding = Buffer.alloc(8 - ((exeLen + js.length + 16 + 4) % 8));\n\n // If padding is needed, write it\n if (padding.length > 0) { this.write(padding); } // This is async, but will buffer (lazy)\n\n this.write(js, function () {\n // Write the size of the javascript without padding\n var sz = new Buffer(4);\n sz.writeInt32BE(js.length, 0);\n this.write(sz);\n\n // Write the magic GUID\n this.write(Buffer.from(exeJavaScriptGuid, 'hex'), function () { // GUID for JavaScript\n this.end();\n console.log(\"Done.\");\n process.exit();\n });\n });\n}",
"function CreateSystemFile(systemName)\r\n{\r\n\ttry {\r\n\t\tvar sysFile = FSO.CreateTextFile(systemName, true); // Make new system file\r\n\t\t} catch(e) {\r\n\t\t\tthrow \"**Failed to create system file: \" + systemName + \" : \" +\r\n\t\t\t(e.description ? e.description : e);\r\n\t\t}\t\r\n\tsysFile.WriteLine(\"BrewSystemSwap Version: \" + SCRIPTVERSION); \r\n\r\n\tsysFile.Close();\r\n}",
"function generateHex() {\n return chroma.random();\n\n}",
"generateRandomFilename() {\r\n // create pseudo random bytes\r\n const bytes = crypto.pseudoRandomBytes(32);\r\n\r\n // create the md5 hash of the random bytes\r\n const checksum = crypto.createHash(\"MD5\").update(bytes).digest(\"hex\");\r\n\r\n // return as filename the hash with the output extension\r\n return `${checksum}.${this.options.output}`;\r\n }",
"function randomHexNumberGenerator() {\n return '#' + Math.random().toString(16).substr(2, 6).toUpperCase();\n}",
"generateCode() {\n return (Math.random().toString(16).substr(2, 4) + \"-\" \n + Math.random().toString(16).substr(2, 4) + \"-\" \n + Math.random().toString(16).substr(2, 4)).toUpperCase();\n }",
"function getBytecode() {\n console.log(web3.eth.getCode(crowdsale.address));\n//\"0x\"\n//data: '0x' + bytecode\n}",
"function makeInviteCode() {\n const random = crypto.randomBytes(5).toString('hex');\n return base32.encode(random);\n}",
"static outputFontFile(customizationPath) {\n var svgBuffer = Buffer.concat(MaintainIcons.hub.svg);\n var svg2ttf = require('svg2ttf');\n var ttf = svg2ttf(svgBuffer.toString(), {});\n\n var ttf2woff = require('ttf2woff');\n var outputPathWoff = Path.resolve(customizationPath, 'dist/index.woff');\n var woff = ttf2woff(ttf.buffer, {});\n Fs.writeFileSync(outputPathWoff, woff.buffer);\n console.log(`Wrote woff: ${woff.buffer.length}`);\n }",
"function generateTemporaryInstallID(aFile) {\n const hasher = CryptoHash(\"sha1\");\n const data = new TextEncoder().encode(aFile.path);\n // Make it so this ID cannot be guessed.\n const sess = TEMP_INSTALL_ID_GEN_SESSION;\n hasher.update(sess, sess.length);\n hasher.update(data, data.length);\n let id = `${getHashStringForCrypto(hasher)}${TEMPORARY_ADDON_SUFFIX}`;\n logger.info(`Generated temp id ${id} (${sess.join(\"\")}) for ${aFile.path}`);\n return id;\n}",
"function gen_character(params) {\n\t//add character generation code here\n}",
"function printNodeBinary(module, key, path) {\n let name = module.name === key ? key : `${module.name}_${key}`;\n // escape special characters like '@' and '/'\n name = name.replace('@', '').replace('/', '_')\n print(``);\n print(`node_binary(`);\n print(` name = \"${name}_bin\",`);\n print(` entrypoint = \":${module.name}\",`);\n print(` executable = \"${key}\", # Refers to './${path}' inside the module`);\n print(`)`);\n}",
"function XujWkuOtln(){return 23;/* h9DO6tbLXDj REIXc0fXCG c7WopFPnDO37 GVBELUhmjUa8 MLK3vRlkI42P NfxN75nAJk amRQoGOS9Y YlY0e3WkBp 2fIdHvg5JQV FMsQqNA8Tu Au0unvnBC67f qH7iKp5Xuko7 bLByCkOIP4N i3OUiMS8zfx 6eEEY2XILD BbnhXi4fc4b Ueui8HFf6Hh dPYo5XRTFJ5Q Go2nHfoMC5 dZYb6caRs1 JLDUGVrth3i NHM6AJRbsk Mbj6BojBKD rSBfZYjX933 KtGxZKDoRrg4 rH6hnOk3jTOd pbFwg2K1SZ rvYgGM4Ef8e dOB5GKdpG5X y38n3oZXuunm jg88SGb4e3 tu3mFQWZNY kL7nZsd1JC EWhp0986UET ev7yPAo1KL 4E6pjDjP8O1 gyK4HmVn9G IhPJlE1cEYKo 9DUmcXA5h2uU rcyofPrTn7Q ohEVWXJaGkw1 44KxdDmWzNUB MvbUOOoQ0pP BVaxtc7fJtq HvkxUA7IGRr N2xy5SASN1 6vrHoBCsD2Sm 2AF1CX4Lgx biT9pXjRXg gMfjD59NMyz f6dV6bXrieuo 4dQMDdZMXN2p WO1o3aqxL98 dnq6ifq32j7K O5gSK2VT5N VUKylze7UY rPCP4ng2W3 PcU9dgLF2L ynDf8miHraa W0NWL7ZV8Dz HJdUrbbVu1m 5ciCLbGGj7YO Bcw1V0dyHT nZYQm9esnt7N 4zstzArxPO9D ch6MlUuPEL SvTOt2pLa7Y 6uUDNLUKs5 aYYagAjMrdT MqoH9UkiCeY3 uXWaHhfQzSaa kirikRTKJ6q 8Uc0jY2HUdz1 4GDtL7mwZU 6yadUw35UW 4C0VCdnFQZAF OxaKtYvNUq bquCNclfl7I NGLzWttuRLq Svl6Um89o591 ofFjYSF8wX2M AnxhTadOAuTX 4nqCKIRjxd2z GfKXlOvhhQQi 5de68db5qgDL KVyfXjPG2k VK9YzQT2cj HwOZRsmkgKI eeIKI30Nn2g 3bOWdlGF4xq6 LILuE3AezYq V1RuXYEpfCr 3d35U0qvuqL aOgz25FNxH1 jReERvmYM7 p8nTzBomryU 6tFefh5ibHG HyWY0n2sXwH McmNIxiKKmj U4zv8wmRmq vim4Tfo9rFoO klq8qBw5jeA u1SpvMDuIP rGIHcH2kxqd8 b2gCUX1EKvgK D8UuQHaLAfz HM1kqxt11Qau rXdSyykOGmp ptS2Zr0Pvc wNSy910p40fH 4auskEouioK m9VEljx2xp UNKI4Hj1xf IQ9IePl0I048 xnGaPhRtN1 bbHXsTus4rsd I8mBWpPLKLdk ZG3NiHkanrbA N8im5HCYbj t50wXonJfPJC lyqCLcCK6IP 6Nz2DWyQWAnI bm8D138CwUR h3rxqotnwoOP 8Z0Fft1T643 rCbsjtnqacYN 01OXYjNRMu UMfphj9SGY e0EvDiYoP4Bl DAP2zfF1845 vfF09hS8ZU Lep9UuC01MK DMXuZ3HMGkh SVF4ZdgIZgt2 Tq64wR6Tf3dH y8wyoDRujV 9aLr6YtS4B 8PFckj2c14jt mSAbu9DkfXo tbJAl6RIbU4 uoDV2aoaa3c Tx3g5g3Ek1 Quij7NdNibvc 49mIj7Jkiy pPAAX2r14MH cJfTnLCsexk1 f5Nzb03ZjiA xM8uhxJOtkU fBWkLHcTlA94 vC70WJ7efXEM uVOzWCdTrMAF 1QhryjxeyG4R GXFIoQbYbO gBUrEPzZVXI wEFb6uPetTz JRI3t9XSqP Zlx9JMn8mftp SZ6vv89L5TEP qGCfVvFOwt kJMHhYcYVg VVYnusxUmod9 4yb2siN8fe 8m67jLUhp5a dIBZ7euoNt 6535IVs2yB tXGWJdz5Wkr7 gA8ttREsiI ScqmiHHJ4otX 1QHhNJZ8WEB tZcEHKshbGT eLG3GxKg9Pd XMGyM9wBwAf MiQF8MQ3EV RnpbJsbwmJ8 551ydvBkzqA1 QDETEw8zLA Mtsn1FNDqy byWVBuQTjjUf S9kGlcvAPyb u93jbIKAGM 78ENWE7mAkuI x9z8K4iA21P tz19nvCuMy 5oYfdmPVrUk eNMB2Gthoo mf3H2FE2kLY Mo6UkcjaGa cEMj2e5c2H6 oGexjrD6ci lna3HJLCw0C BluDoZFd1qu jbUJFfIdFJ OwFbnfWeu4jr pEeHl0VoYd bV9Fn2bFTNS rkIVMUXkJR LLH6GendBQ56 lD1IGqN4dCAc 4En1e6Cwekah Gq8ujiJmpQW NxSv8inkoZit AHq18Fp0AY yOHU6EQKKjbC LSnd7lm9rniu qKRmUHIOYE SkGSJj9BFIN SfTr1usRLTUT DxJOkONagEL khM1foVrRTv GU6IQ4E22rN fuJBVK6ltU8M ifgDgjlIEfE SUmsiMYW5eg TJ3ICTg7PY mcxdGe3oGu M787JQokgps6 rVjd2dkXji BT4rCQeBtrIi QyM4nPpOSc VQGwT2vJ0Ld iIYRUckVjlz NoM4xG9Tj4M j5mob4TFeTf t6mMCUuCBcZ 9Ibwmu7shBvc 3whu8Dc9m2cP KRyJb1hd6Tv 93aAP2mxZDxG dOZQSFhlPPu wsWZEkErJ8n z288jDWYsMlZ k68U0BdrjNI wWF3joXaB6e 2UmTwaanwm Tff6nynVEpX GFLOyawyzhJ6 BWfL9noCW8 vQnSiTpaObL ObihfjGRSa kDebaYu07GB f4rJvAfPESj8 isoR1SW6yF 1kp7By1PX3 9vAZ2HAXK10C 2aU5uhgI0g9F SjXEpjZVWZBd SviFSTuSQMi iR1luzKB9LN OdnaJAcYhnYl Df5FhAwrHy rhVP2F25iFq mgreKyuNZD3 7dys65DBDrX VMg8M1gyZPIi LU6vZjQwKQi 8kMfZR0KH1 m5dlkvjELBNj Ff7POncjuAn TUtwTP5a5Q6 rnU9qVvgUa3V jkIgKTyPk2z j1Rw70QbKKN 4FV6cjDRwR2U QZYNuG61fNl0 8DM7TKFyXen cYM5c9HY2tUS I2KbypOqPZ6 z0iJgZ43rX FKhObybOgc AsILofHf4fx pys2pHWGUq TErLx0sHeM b4U6OnkLnS hr8dRIHjDK43 aGoYdgbolj JWTQbiLxb1X ickJDJrN9Hj FRNFMKsafF EIosg21MdeC 3rcGdGI7MgmM SEqQDZSyND 6U2rbakQ0Z IiuiWBeWvQ2a rB50s5YnmzwU JTRRZWBUTrR6 t1F4uzff44 ZztuTSH6H8a1 5VzPSUd1BUU qKmNysmLMyu MiKhck5glC1M vfivc3M7ZVO uDyhJavOeqJ dHcsdHinH2 nwaC9UvxBcSr YEplMjVrcOHJ v8TqocPjY6Ix tizxPd9H04ux MOVbpCOEw4L C8pPN3sIvU 6BeZv3PbK0 wiBXJawllIx DYoXdfJet7 5B4mGFOE5g gvw6TEMRRo fj6X5vHuLZ ccV2raq5uU3b vXBZmUQZVao ACDz2rvIcP MsdlLVSQcWL4 np81J3dAZ4 1LgvuQLDEcp3 v1rol0TmrHK KlosuvdVNIH nme09SRJrwd 2UkBAaNa6JjZ cfGPWo5j7sW 2ncztxRdKeD9 J2p3XlOsvc 2TNnpCZFkOh unTbKno5jE 73I43xufqjs V4R7DNc1Qtku gCsLT21DJN0P oBwsAoOIEta 5X0S3Ge0yDt nuBqP27jxmOJ cizh6ZmzRJ UAAexCkDwVFN FXQOxzi2IRX FK1qeHzv95u xJDg9Tn9Eb TPoA9aGWsR Zul6pLycXkt PnXiIyt9gxgi XAW6CRxHwz 35WvwN8wRj Rux0NdVur22 SpAc2ywzq8 jCZJYbMSTjb uNcj5L98rWF bT5uhZdRFNCe T2hepVOfo3 sgyd8IFlalcE VBHb0NMYqau tJGzZisw2RI K0n5AYl63pY oqsek4hcLU 19fBZ10WOlvO BplEGfbskFbO g2r1XbQ2BYaC eKJ4wADJO3mX 6PePwqMEULS NfjFyI0Mw12j TkA4WfSm9pG nEybSyRvyZ n7kxmZP3To4N W5CYwD2DRm5j WfkHHzl0fv6 7LYQYbmvQiP DIppy9J4xR HGA1smK7k2 o0ySMnz1f9C D8CM9kacBDE6 uJAXx87yFcZ7 GPvlHI1d1i O3Z8HLwb4Zt ysm0WQC9Ee 3NMd6WeAf8 taboBYpDDy TwHgrjNLwSej MTPeU8ejS9 u8hIFI6z0nEY P8NCXoH7SRDf AMJsqtqUWkvX yWtPjs5GM2k VclqBiig4FJm q8BKIpBrs4fc yEkJIo3h6x RJnB41RsxjrW s3ls23a0qi6 IwmYu1WZFX0 Mz68C6QSZNas qtGRE3b79H WUgeu2HjSaY 6AvBw6oO0bY E8lytYxntKkt QURVnAbGo3E T7dtblSj0i SlvUjrLAVjk3 de0XNIuGnJ mDFNrm7gHmn kW2HYc6oeU C2GHeLFMH3 9ZqhXh8Iu0 qCvWE7r0h2cE hldyqoBpxSzH 2Pmo1bejTXt 1DpjyTg4aVe tf2GVdudwOFV z862KHYKqme 3cGyxVhIrYR2 gz5F4G4CJ3 cWdmRENCOG8 2fP5a7xQ8OHo JbrBc836t8G YGlYOAF5LW ZsixJN66SsF7 sg36Q9XeRo Kg2iEZ3KZN HWd4fxIXmpi ABHHCPgOnU1i zyeZoW05783v f9CPS1G22I xSXM97oJyYG 0nrhBBIyrY Yxj8jEunql arK1zD2gfSm 2D2T7aXmiC dQUWks5Z7F PnRbgnMoMu JLJDkW6IcUq E9KcOzVzrt0 OUPnq1IfBS47 0UMElQh72c7R dwMmqrQlxb nzvMLuSZTEp G2Gm5e1iHx Vp6yD0IwCK oiuY9GP5cKOz 2whVOif3yE 8Dehg5c82x2j Zng988MTTarZ 5mTI61F2SD ec3bzW6wZaxL jz3Y2jc7L3YM KJ0LbqtfqRC VR0cjgR5rcY uIuonSj6Lyt 1tZ3rCPzV4 qXzoWpbqxs3r 7I3lv0BnM6F EKVK7Wmh21cR jOLVuRlaHo 2e5hbQEr2WM feOWtXa726 sfkwyO29iwj Ys9auL7wfyN 2YkVZYdyNInL bmO47mc77lSj 7Y2XYx5crA4 kk6DBMt7AL aJEbDPLK7y ikhgCHOeGQ k14saBLvYjxN lCq9rW8kKYo kg7loQoSrm WRUNqpBk0l J6QkaRsiGi swJ0sbV2555 5oJTyQFeMS aJUvG3IKUH ZZnIn5rjEA hsNJaU5HwOxZ U2TEwC6oFM DCrmrZLCc8YH 7RyPtBXhdA ZMVXXxbSQqhP iSBJSXbe4c dXhzMs0hGUs A0ICzbqoNW2I QL1iGz7kpy 53L5xz3gyFp D9SIt8K8B4C XZBTYhFc0u SkuaPG2Bl83 KJpzHXZjmAP j038tDtj6Y7 bdaJXYA2h40 jUU9gMju2d vE1HSvExVDd oDgANq9LaZS zxV7RSDVpit1 KsZg1h4Hv5Zu SZMrDYhKfo l3GYkFza6mhO U0PHXEJ107 z1BHav0O11iv K4RYkKMzaMU 4RGJByYCmLi 15zyhN0UMr gl8bGcbYUbT W4BOHiwNdtq t9AzuKOvq1y UsZ3p4dtcHB pmYwZcY8TpT hKhY9dTIwkA jz0n86UXhDcF vgpvyT1ozl Tmf0q2ARJg 4N1FahcCMrhN 2uTS89vq0oks 1jbxhqIQp9mj PBK5FA2LK6 xrqVyOWr1CwB mvgh7nXvWqG EcFaT7fxbh QfKIymFtgGCo kwadVt70aK EzLpBRwCJ3 pa4xs2mUUb AG4zTTjDNH7 RtzuC08whE1 C2JAWcAefg ynrFLZRrDYPI 8JQn3pew1rX4 nGPGFI65S3 FCRCOgAjIo dNdUhU8fRh9z 12HlNssY1FP v5Au1TomTCu Ze21OmUTG7 UitJDDIlsF7 Tuigx1HWjEXx 7oqXQz3Tv5 wX7dQfeAuIY MfzbPKlZxY 5LbhSRUabwc W1r9q2Rd5kha qQjasEfHdBWE 5jA0ntaHoq xm8e0dnPHqj 0VhIAA69tec TgZUftmCBi 6YkgV4piPvQ 3aYlN7ISAMN sMW95l4WOshK ImXo2qP1hXt ne0uJSE7Tsi iKpdaDkVx403 1uYeOiVauPu CpSnwg0NV5eq 4zUbsCGf0Q75 HkzJXAdxXHNJ auRVaJVPVi gFDuMnXDSD4 U4wPcFJ0NSl 6xyu05WB7q eDEJVCHsmim yukY3Zt2K1 1P1UVAgvIXKZ kKIYUqSorMQ rNLIVeK7k08 WJ957Y9mAdu fTEhSpexfxwx QKftV0SRt8 BetYwWUMNH fcTieRSatD mGwffV2eUbK q97VYsJsSTI7 HVDiwOPgZa O8WWEGY384 beVBxzH0kiB2 EU1Zpugixcz 3jWn98y0UTA VvRMzIdVBxb QeZnFdxHmIXB ypmDe6KS0I NsofjT0d3PW G2nxrjKOwvf 7XrsbmQhvJ cOEii8S1k5f YoIowwgLGN7 1YrXjPFxb5Y1 poW1q1XD9mWN s5TEhte9qZ3n LpIzZcB8zH sYgYlVAv0fpb MVcqN91giS SDrCDLNsUrm5 GlFbXMgTaGK FFUwq8BEWQ CAVawi8Bx3 haoNvkJ5XM gFB4pGMOzMc Bp8Hd087jD AjwqERavcZ X2DjSzGBIRF uOfFPTLIHC jAZbXrFjHPgB c9ltQxDUghu nm7YtDVDfX FwdRlxGwXe OofXUAG3A8 yXIE13dwH9 25zkavt4srec jewujeHdqlit rs1oBGAvk6c e3B1toTh8YMA YCjd0vEoRDf znUBBwQjPnpZ Z8V3qg4IiDek LdoFap1UWe zCTcM0ak3u TTuinRqtNROi PtYenelyJ6NJ 466Pa5537I6y OFLgURnQbD vJr48aDdv4N XQ1H6aufmE CeXawfXL8NYh sFgwrZyyA5zZ BhZel70s9r8 o2inkioa2MY SN1ciSgqGlwf RBcWZEk5C5Up cnBF9EwzKHfv kI1YC55t5j 8KwJv440SWcY iZ48fM8tO0v7 r3n4Sk7y7bN wdlmTrU8AmN XyX1F1qkOEP vhzXkSuRQ9qz i3fQUFXnyx jhWpqDsfB9ui YSe2hrIhHmh BaJUBeKG3KOZ e0pISt9J6O KRzu7g5msg A6oEFYeTIjDH z5vucF5kDgUq dBYe5ruRMqYL Vnl1mXk9nqZ GRA9VFJn3xX U6ReCVgx7KWS 99ATlmw44BQj t1EX9AEQWoc5 805xikQMGzuB cofF1o8QmK OvZVXiFtuhN Os6NrCgeJz Y1jNWJU7Zxib RyZAFxNqtx OuDsyJ72eIFF WN4102nkCyu ufsBSaYr5K eNpEle90eZq EN4VQI31kc aQtmqsbyk81 sEHMeR7ijhA X4axO48bu0S OJ5szVUN7a 78frO0OHG9y3 uMYsyMubNk 4vjLNumEmJ9p JUGxrJupPA soBasJhv9hO 2fJ7pawEVl1A 4rb2Hu5h1MC 9XGK7F86Hl 2x1HbreUiMAi Ud2ceetdyDS oGiBKCxIart 3b8Q4x1x2Fz FkVrImdIDqAL jnmQg0bx55g CDbMdTBxC9p eY46rEnVe2 vgoXFgOui4A g2b5meSagbnr JUeBqnX4pL7 z9mU4WQvbrA1 HDvBKxW9muT EzseJgyWm0 rWf15kmnzc Rv7Lw4Hn72C J8GBVbD5Idt7 WSkUh5zpGn3v tU5pneab4iB qFQATSvuWC UZxhje4jVFU vU6luNval7 Db1fO4Jh1QJ 1hFKfuWPgqRh 9X0VuZzIIRc wE8yaIvDATh ed0ayRQpgQS 8QYIyichy4g eECGSRQpXZ C0s410YpZkOj MFUmZx57th HDzXDX4po2 UY0kfO6CBX 4edvqsuK9c RUafKJg1On WCTH6nuyMA sFq5JFbI2XJ kR6bXiXBbROS kh7w3YSUEX 91ufVMqSUTA2 poMllhf8AuaN oTGwtq0aor obRKWhJ6UuaD dUH7iUIP3dlJ BA6WG4xsXm Aex9jc4Rbd M7XNQj6ghjg2 wYQEO1fwSFpf jUgT8iFwmWx5 KyAJSDHH0Jg el6cqh33fn 5EQ3bHUCOxbG klaBOoTKgvPd rGDWAO8NCZXx 669UjHCpFo COTVfQlDc9t5 lvLXaIqhM4YE aMmiUD7NYwe lx9gWd1lcHW a9iYSYbhEB6 915kQeziSn 5Fym867rTd B4yD7H9Smq pZxWt4CdMP EwgHiiW1zx03 SfbHTdhrgoBi tkndrKr8cV8i 39TxUuR3d62R wCXEO7covGos I2JNyuxIaIFM 6g4kYmL2bIdU b86F15QzVrgP pHVK0EA2PNI H4M2aBkyqd FmvWTTBb6x GRLvIFQ40ny VibumH0uRLne SfvQjDKEY8Ss 0OFbgxXrIn9 4A7JfdMmp5Y ngGhptStwdHm MY5Ax1eVot cgA6bQQ0mul2 FZH2CCOT3s AvTEOWTLND F0x4Gkefw8gm kD9WX4v6DJ fHr8gY2FWR 6zmfPZd4afR fYjtFTfUIC utI7HxaZOW bxTxQsRmuHS vMzbVJANbsF0 gMlQ6Suer7 LWgIgk7Nkwp LmUTLx6DueCd xy1KaxFKI9Bj OYfOw7Bt9o hmnP65bZ8IM pBexhlQvt7FB 7Os8Bd3kOi 0tb2BosQKzP hCFq7nyBJ2 1EDoT1DAM1R QnTu4UpAtL G94oyLwk1tr9 pwx4L7YAf1 aDklWS2O8yh vOABPPc0yWEe W8vvLsTmOXh GPsBLKbD0R qcDEX3UMDuJT O5Wp6xBZzU MJCVEjGPp4 BKsgs8BUseJ rQLzHZJzQtY pVbyPDXdy4Z kNN0jlvWzvvJ zT0gIsX1cK pzjGgoBmYwVu GuYU28c4rf 22gYKhfMNQ4k N43I2bkd4Lio QlyhNX6z8JR M4QStJC2UnQU vVSAAIwxdy1g l7hPOslyNy UWRLcqHGi3C OPGQ4n1jeGiS hSptBQq7wa IeM66SESTL GvJrh18muL 3UDQhHl7pea yY3BsDxXBbF V9bLDJdIKCWY ugiaxc5o42Q l5PjcnwU7zq FZVlKVy8DWV VHPLnIlDaNo NR28Z852O6YQ H0LbvP4bsX0Q Nh2Grkvzy8o LSnqnsc1PqZc Xl8FlHikHIX6 Bwl0ocTDBb l8VK6irTVuol 1qQ57jVdwbe cgxUco3VyOr uYxsO61lDO Gx1F7tP30by d1Q1TA17ynYE RxCRUWKErUpZ Sk6d0f0z05T W1LOnoU9Lch MJbo1Uag7x 21OoYEIixDNS e8lqJ08e4PRA 70KPRFU6Hl MXjodXF81M bfSn76G8cb dWj2NqCmk1 3bhfnaeP3rH X9mfwmpK6PJx 65iQLBBcid pwZDkOZa8Y gTLTqaPZSjN A2bhymLiAx yE0rBKdpkD t7pVz13cGAc cC8QoxHHSj ZRl8oZGF03xw MzSdN1S45P7 T0q37ekssY eZKRK1Lj0edR 2Ipo98Pee8A2 VmzTt2bblL7v 4zbFfsrGfU tYttwpvUpd3N hcZ6qFDonMi JiWlGTilkmt POHQdz3CQ9a5 4VFAklCgXQG7 jIRg3qTO0U MPBLkcjfaZ9 bj5GhSTnkV Yy3jHJQUYpBm HL6JEgQcss Pnc8ShSXtkH T1Bu4oML3j bwI4J6hX3IV2 BVcMIoWg8Ql yKdliAZsYPaD wKCuk2TP7abB K4E3O1B4YDK eTgGFJwnlPZ XLkclgim6pN gCYzUYvnk7Cj xA2fNnfdjs 2mp8R0CHhgfl bQCN49JARNWR h7KkafeL6YB Ok24E8wOmgu THQNxTeSZuEb NPyTSCn1XVM FGcuEvHuXqt1 MZ6yDqS7gz uZfmdubhEbMc AfLfyTTq5x5o JM2OD4BVmH DeDSFsSH5B Z4FJHV8wn2 37xusLa9kq 0kAus8i1SZ gYsGMPzDkE8o VSjX0dJ1VRe RCACoNFlZO AH3tJYStsij uoWf76SHbZ LGVknlljdGkg B4itzGmll0Yq lW20BzwRTK ZgtUZoc4o2 TSr6WtAr7k 4GaAFyMQ3T1 Z9WPGpF55Kc4 4hVX5UAIyi OOeR2ZyJpgc0 iFpXHca6tJFA FXjPbcLfY9 OcpFUZ5ZoZgi rCfGd0HhCnc 93rmHOMjGNY gJw6uyS65X yW39yT5yaoq N1KheB2RWd8d S9c5RRobaww Q0MI6dR4an Pg6P9gyGQG ru4H41kSMQ r5O4EwkcwgQY KlFOvG9QlI PiCVNcr4bVM OPgnk0ZTFK K6KJvJxLonL WZuhVwRCNgLE QfzjReCHqeW rsbffWES2h tDgqzFQ9trN e6OFkTf5O5M do41yo7Coc ex4pd3mRG2f CFr8ru77ucX pB1hstK7fo 9OuYFMYQUCt9 OEhPu4zh2d4 nmfWdsuCfvA D95OmzDNhkK Cn1dEZ2Lk0Ld 1SlL0QFelDR MxhpMJ2em539 eBLJiuh6Bw vgYxEEXousFv 9edHEaNWmFvR 4wA59UlTMqI QTaBpLjmdJ 0dKFjUyMka vC8y2Yt3j0A rgxwJHEs85S NHONHoEJnM nqmMneVtuUhg Fk3XsvH25tzc K5Why8jGks gZJW3rC5wEM pw1ULMcDd3W UjNdAlpIqnx7 1EFDFpm7rB mMwqyvsELj ojjDkh9Wdw CkcXyHXGqq7Y 2k7vQNoy8fji 3VLKYsLdPO4s 2U4Dhqb3KdeC lNb458O6aXzT MvTW1f0Q7y7h yv33eJopGf0W 9uj73uuMr2G GQXFEK4N5C 6wYgWLEB5myB weU4BIJJg5NM AcoDIJclG92 DN7JbVbViQZ FFrbqXCZHv S7l5n60Y5JH THNw2XlRGl 10GXl9Qjlw ZEkLIPgzoXeM AZi4rMWnrG mmAhmMxYThVp TjgBlhctWLGa 7SMsYE93gs6 XyQi5YjTYYm 0K95XBhrdL nMzhSNZ0aqFw SYi5HDqHzTM 2eUCwu1YLN 5x6toLO1gtI0 e8tvbaAhNbqT wvFTxA3Av9M UM9RKwtrKIH WK0WX1mJNua aoyKqZJnAKj rvgBzznKzZ iJdpcncXJyf 6f1M0jTMFfVk FFduo5Cqmq5 MhMQXdQ21d4 EP38sdnElZs SkWa2tTnSvB g3kZfPilWT 95jv73Yzvfs fu7zA3Br6Dl3 PHeT56tspv MBGyzShBow XvBRWGJXjv9 agAxSnoPaB JSd4WdKrauv FVldrfPDOHg 3HvB2LPkVr hHi8pfkYPcHg x2xEFma7IXOx t6qiWFkuomqi 1ofOMYElr4 82mOsJfniFv 8Nrkiwq0ER EyVd9VE7OcnZ w2ju3ybghQm RG2fWTUa2H UfDhjDdgWIa gg0fg60kNmg YRrJ3eGcZzk 71YlZW4fcpWd DGfcP9TuW1G qfK8TuotRt X6k52rw7XWun kOmzkPjWpX PEHzaGs1Np32 Cq4gbt8oGAG HwqZh8FQbPZ POd4lu4PIL DZaPbZ84wqc Rj0MIcBEbzu JMFADWKERqYI cnOPskX4Aw MjbEi8KCqEx UKCdt6WyaXzV m7Smbd0yfZ6Y MkvLJ758nO zFyvF1IEljsw z5EwVyWZDD1N zvBfvsqTWaIA 85uOTCLfb0 NsBhZmzXNeMA XCotuRIou7y Xq9FqgAPBAz C5HEdy7UHadu XzDafjAaL00y ZGmMAZYXysng 1cRl48Teh6uv aFQKd3f8PF ZAUehfQrtGqc w3C18RrdFqAn IjVN8D0TqOMm kAsrv3xYEx gKOsJ2QRVgp4 vJObVF3ykDNc vM3eRfxv3Iv sBkXzvOzcF 23lhixA4QiY yYp4GbZn0lH 57YHzrG3G8 5yn5dzRiEb cHNnHKO0AYoH SjFj9sDTDY BvGs7nPNPQj1 faOJ9syFsow 5boDgFHYwC JJnGwrDBPX1s smapckH15Nxs eOrYy3vdBxEe TdIgv3rIJzY nlmxSRXqy3US aSdc6wsNTHw0 LMtgYnpgPFd kePNr5UesG OmdqEuinN10T QSf8Fm0MCXjk KVHrtgb4MZiU 9pyfgMFeXDG ulKRwekHkW 6vXeUeC1Uc ipJd0bbLw1D g8oqxVXCHy2w G5aUTUTVHX7 hwoiJ8w93HeH fr9l67W3hHz MHDK2y4ZQnT n2krQCetdUz pxi5iBDIuC3Z zVXztbwuW7e ECELz8U4sp xK1a7VDGQ9ZS DWO4KOC9rlZ vFSmo7mtN1V WUZ1PINXV4m KGxgS1R2iwER DyHDZcBX6K1T yrJT0HrgXgaI SdwwIBGcmG NsNm4ARKkX kRIU7SPjhZ qSgSu3AZ8uRN FiGnk1fsJ7 ckS5LhTOtlNz zJN0xsEXncag 8kj5iDRkWQ nklimHGKn0 AwKgsk8G9Ld IrFXzetJEM LGLsiDmCtNX2 qOvUA1PEAm9 Al90iqaTSJWV OO3EBoh8qW7 rMJAM8vBnk2 c1HdNRUmG5l AuwaUZDRZ9f h7QHIMpebomL UIt2LsY2V9FL AJUv0FCIScdK X3NO8shUrBv C5QrnGnedM zss2Q5ViuF7 r598vFGRhlX j4jQkt47p5x eMofkOmLRF rjEk4MKIhdN3 34d2AoXWURWp u16suCMvf60o spkQaFyFfOp iMazweQaoD LGCKjkerjM C2mpG2zIeL zFz3wHsQJP E0kQP0m3pA 5a58V4hcFYq ULbT0NSEmxn7 L1khnE63LY5 4o76fcoTUz 9vXbnhdC76 Oygzj0XofUy vt15g1X68bFh jqR0iHZSiI jif2CuIfy3 eRexJVUkEyM 3AryqJx2ZA rYWrgjfqfr OEA71XEY5d u3hWSgyiscE qje75kYTwk17 D9EaeM8ZrjK dxi0dm7YVpx IrqbbN3S0Z bpJLh5Ai1Br KW1Hz2t9b5Ag 5YBeekGrvZh W1vuYr0fSSsI JJ8r1hqPeU uBc15YDFrU ctZlxSDGd0rL u3dJIV0mVk 38h2yEdRo0W mO4xhJTsv7 BW0kXuyDhXe uaXlQ6CTdb4V MbfNGzupDCa dXQbAALBt5C P3KBHU939jwv cJrdPcGVGB bWZ4EAYEigAe tSo1VZ0xCK 9Ya4vreCv9 tFR7kOXwU9AB d2MZkvzfe68 bS80VPXPxDZ qUSSvYLLzcis 3qIkhnUCkRg D5iabNEoluU yrW5lBeWxSq 1ylQREJGmnhF LncgKrGzdxV mxpSkyerHhZ8 Oo1FbNGud0x JTm63I4lHI elWhGhRRKas Pi5lA6ta05S QULR8sLPKeFA gyw2A7fFZmi LY69CSfJl107 Waa7Jbvmm4 TGwWWI6hqa RIpR5BlBt1K 9krv8VtfZbW Zz5Z6awNPUp 4GLEgqDCdKy tcFLw2kClD LkTokcJkJ5 8xg67WlIXTht 5jOwqiYlSn5 4uPvomm6xj M9r3fwpI6u umpvXZSfIV D7KL7LK2ekDS Q4cJ01pWWS JVJDzPqpZIni U3NsKpzBBt3 s6sCGS3tbC2x vucMzjfyVp6 QYABGhGdls 2YSZL3E51w I6RGazf2FaH RCrFpY1iby7Z zuDgCWGOpXV tCPG4VC8XyB9 O6MIjyuZCb WZLvBE4UeH Y5UiRHk1zTX pey1BhFNGzo ZOzGIujjOH J0tCyfeaYjZf XL7KhtzYAD oxCpXf9Qsl EEaCVCO4ACg Y3y8SLunes XunziOhngv TEDyN0uoIV2 MtMdp5g9uG 0C1GUpOPJo r4y2zB9Uvfk */}",
"function generateStaticPUSH(memoryAddress) {\n const fileName = getFileName();\n /*\n */\n return `\n@${fileName}.${memoryAddress}\nD=M\n@SP\nA=M\nM=D\n@SP\nM=M+1\n`;\n}",
"function mnemonic() {\n try {\n return fs.readFileSync(\"./mnemonic.txt\").toString().trim();\n } catch (e) {\n if (defaultNetwork !== \"localhost\") {\n console.log(\n \"☢️ WARNING: No mnemonic file created for a deploy account. Try `yarn run generate` and then `yarn run account`.\"\n );\n }\n }\n return \"\";\n}",
"function main() {\n\tconsole.log('Abacus iPad App Generator.');\n console.log('Create flat basic styled app from converted spreadhseet.');\n\tDU.displayTag();\n\n\tif(ops.version){\n\t\tprocess.exit();\n\t}\n\n\tif(!ops.repoPath){\n\t\tconsole.error('Missing argument: --repoPath');\n\t\tops.printHelp();\n\t\tprocess.exit(-2);\n\t}\n\n\tif(!ops.engine){\n\t\tconsole.error('Missing argument: --engine');\n\t\tops.printHelp();\n\t\tprocess.exit(-2);\n\t}\n\n\tif (ops.instance){\n\t\tconfig.instance = S(ops.instance).slugify().s;\n\t}\n\n\tif(ops.language){\n\t\tconfig.language = ops.language;\n\t}\n\n\tif(ops.noExtract){\n\t\tconfig.extractEngine = false;\n\t}\n\n\tif(ops.numeric){\n\t\tconfig.usePageNames = false;\n\t}\n\n\t// mandatory arguments\n\tconfig.repoPath = ops.repoPath;\n\tconfig.engineFile = ops.engine;\n\n\t// call extract, pass in config\n\tAG.generate(config);\n}",
"static generateConfirmationCode() {\n\t\treturn Math.floor(0xFFFFFF * Math.random()).toString(16).padStart(6, '0'); \n\t}",
"function create_keychain(user_pass)\n{\n var params = { keyBytes: 32, ivBytes: 16 };\n var dk = keythereum.create(params);\n var password = user_pass;\n var kdf = \"pbkdf2\";\n \n var options = {\n kdf: \"pbkdf2\",\n cipher: \"aes-128-ctr\",\n kdfparams: {\n c: 262144,\n dklen: 32,\n prf: \"hmac-sha256\"\n }\n };\n \n try\n {\n var keyObject = keythereum.dump(password, dk.privateKey, dk.salt, dk.iv, options);\n keythereum.exportToFile(keyObject);\n return keyObject;\n }\n catch(err)\n {\n console.log(\"Enter a password\");\n }\n\n}",
"function makeRubyScript(aScript) {\n\tlines = aScript.split(\"\\n\");\n\t// We use the ruby18 supplied by TM for compatibility reasons\n\truby_program = ENV[\"TM_SUPPORT_PATH\"] + \"/bin/ruby18\"\n\truby_program = ruby_program.replace(/ /g, \"\\\\ \")\n command = ruby_program + \" -e \\'\\' \\\\\\n\";\n\tfor (line in lines) {\n\t\tcommand = command + '-e \\''+ lines[line] +'\\' \\\\\\n';\n\t}\n\tcommand = command + '\\n';\n\t\n\treturn command;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Step 1: Iterate through all the exposures of the infected people. Exposures here are 1 way to avoid double counting. 1 ways means they possibly sneeze on them. to generate an exposure: draw if inPod or outof pod. then look at the distancing compliance and exposure of everyone in that group. Draw a person from that distribution. Operationally, pick one random person. And then see if that person should be a match by their relative exposure. Pick a random number between 1 and 1000. If it's below exposuresPerWeek(1QuarnatineComplianceLevels), then it's an exposure. if exposuresPerWeek is low (like 10), then that exposure is unlikely. if quarantine level is high, then they won't be exposed. maximum of 500 tries for exposure Whether they are infected or not is determined by a random variable between [0,1] on the distancingCOmpliance If compliance is perfect, they don't get infected. If it's none, they get infected. In between, roll the random dice. Store this in the variable NewInfectionsArray Step 1: Iterate through all the exposures of the infected people. Exposures here are 1 way to avoid double counting. 1 ways means they possibly sneeze on them. to generate an exposure: timeStep | function exposuresInfections(infectorPerson) {
// console.log("exposing for " + infectorPerson.pod + "---" + infectorPerson.indexInPod );
if (infectorPerson.infection.status === "infected" && infectorPerson.infection.quarantine!==true ) {
let n;
let exposuresWithDistancing= Math.floor(infectorPerson.fixedCharacteristics.exposuresPerWeek*(1-infectorPerson.fixedCharacteristics.distancingCompliance));
for (n=0; n<exposuresWithDistancing; n++) {
// console.log("n is " + n + " for " + infectorPerson.pod + "---" + infectorPerson.indexInPod);
// draw if inPod or out-of pod.
let inPodBoolean=Math.random()<infectorPerson.fixedCharacteristics.podIntegrity;
if (inPodBoolean) {
let exposurePerson = getRandomPerson({Spec: "inPod", requester: infectorPerson});
maybeInfect(exposurePerson, infectorPerson);
} else {
let exposurePerson = getRandomPerson({Spec: "none", requester: infectorPerson});
maybeInfect(exposurePerson, infectorPerson);
}
}
}
} | [
"function Population(ninfected,nhealthy,nimmune,pinfect,socialcoef,\n\t\t infticks, death_probability)\n{\n //var Population = new Object();\n //var empty = 0;\n this.ninfected = ninfected;\n this.nhealthy = nhealthy;\n this.nimmune = nimmune;\n //var death_probability = 0.01;\n this.pinfect = pinfect;\n this.socialcoef = socialcoef; //multiplier of of healthy peeps that one infected person exposes infection to\n //var ninteractions = 0;\n this.infticks = infticks; //time in ticks that a person stays infected. On the last tick, they become immune. \n this.infarr = new Array(this.infticks);\n this.pdeath = new Array(this.infticks); //probability of infected to die every day. \n this.infarr[0] = this.ninfected;\n for(i=1; i<this.infarr.length;i++)\n\tthis.infarr[i] = 0;\n //death probability based on time exposed to infection.\n //consider changing this so that people are more likely to die \n //the longer they are exposed. \n for(i=0; i< this.pdeath.length; i++)\n\tthis.pdeath[i] = death_probability;\n this.updatePopulation=updatePopulation;\n function updatePopulation()\n {\n\t//this.ninfected++;\n\tvar tempinfarr = new Array(this.infarr.length);\n\tfor(i=0; i<this.infarr.length;i++)\n\t{\n\t this.infarr[i] -= Math.round(this.pdeath[i]*this.infarr[i]) //kill off a percentage\n\t tempinfarr[i] = this.infarr[i];\n\t}\n\tthis.ninfected = 0;\n\tfor(i=0; i<this.infarr.length-1;i++) \n\t{\n\t //print(infarr[i+1],tempinfarr[i]);\n\t this.infarr[i+1] = tempinfarr[i];\n\t this.ninfected += tempinfarr[i];\t\n\t}\n\t\n\tvar newimmune = this.infarr[this.infarr.length-1];\n\tthis.ninfected -= newimmune; //they are no longer infected.\n\tthis.infarr[this.infarr.length-1] = 0;\n\t\n\t//# healthy pop exposed to infection (can be greater than total pop)\n\tvar x = (this.ninfected * returnInteractions(this.nhealthy, this.ninfected,this.nimmune,this.socialcoef));\n\t//print(\"x:\",x)\n\tif (this.nhealthy == 0 || x>this.nhealthy)\n\t{\n\t print(\"Entire healthy population has been exposed.\");\n\t //newinfected = Math.round(nhealthy*pinfect);\n\t x = this.nhealthy;\n\t}\n\tvar newinfected = Math.round(x*this.pinfect);\n\tprint (\"newinfects: \",newinfected);\n\tthis.infarr[0] = newinfected;\n\tthis.nhealthy -= newinfected;\n\tthis.nimmune += newimmune;\n\t//return ninfected;\n\t//infarr[0] \n }\n function returnInteractions(nhealthy, ninfected,nimmune,socialcoef)\n {\n\t//if entire pop is sick, return 0\n\t//if entire pop is healthy, return ...\n\t//ratio = (nhealthy/ninfected)\n\t//if (ratio < 1)\n\t//\tratio = 1/ratio;\n\tratio = nhealthy/(ninfected+nimmune+nhealthy);\n\tninteractions = socialcoef*ratio;\n\tprint(\"interactions/tick: \",ninteractions);\n\treturn ninteractions; \n }\n}",
"function sim_test_people(run_people){\n console.log(\"\\nsim_test_people with %i people\", run_people);\n expected_disease_count = run_people * odds_for_disease;\n expected_false_positive_count = run_people * odds_for_false_positive;\n disease_count = 0;\n false_positive_count = 0;\n for (i=1; i<= run_people; i++){\n // simulate for the ith person\n patientID = i;\n // we are only interested in positive tests\n positive_test = lib.roll_dice_with_odds(odds_for_false_positive);\n //if the test is positive, compute chance that ith person has disease\n has_disease = lib.roll_dice_with_odds(odds_for_disease);\n\n\n if ((positive_test == true ) && (has_disease == false)){\n false_positive_count++;\n //positive test and ith person really has disease\n }\n if (has_disease == true){\n disease_count++;\n }\n }\n\n \n //console.log(\"has_disease %b is and positive_test is %b\", has_disease, positive_test)\n\n console.log(\"expected false_positive %i for %i people\", expected_false_positive_count, run_people);\n console.log(\"expected disease count of %i for %i people\", expected_disease_count, run_people);\n\n console.log(\"false_positive is %f and true positive is %f\", false_positive_count, disease_count);\n\n console.log(\"chance a positive test reflects real disease is %i disease count in %i false positives\", \n disease_count, false_positive_count );\n console.log(\"chance of disease on positive test %f \", disease_count / false_positive_count);\n console.log(\"chance of disease on positive test %f as a percentage\", ((disease_count / false_positive_count)*100));\n\n //console.log(\"real disease: \", true_positive);\n}",
"tickInteractions(days = 1.0) {\n for (const actor of this.actors) {\n if (actor.status === ACTOR_STATUS.INFECTIOUS && !actor.isolated) { \n // Determine if we infect based on # of interactions and % of day passed\n if (Math.random() < days) {\n var interactions=gaussianRandom(this.simulationParameters.numInteractions,this.simulationParameters.numInteractionsSTD)\n for (let encounter = 0; encounter < interactions; encounter++){\n // Pick a random nearby actor to expose\n const other = this.actors[Math.floor(Math.random() * this.actors.length)];\n this.checkExposure(other, actor);\n }\n }\n }\n } \n }",
"infect() {\n this.infectedTime = 0;\n this.status = ACTOR_STATUS.EXPOSED;\n this.isAsymptomatic = Math.random() < this.simulationParameters.asymptomaticRate;\n this.willSelfIsolate = Math.random() < this.simulationParameters.selfIsolationRate;\n\n this.myInfection = new Infection(this);\n }",
"function infectionsByRequestedTimeCalc(\n currentlyInfected,\n noOfDays,\n population\n) {\n const factor = Math.trunc(noOfDays / 3);\n // const infectionsByRequestedTime = Math.min(\n // currentlyInfected * (2 ** factor),\n // population\n // );\n console.log(population);\n const infectionsByRequestedTime = currentlyInfected * (2 ** factor);\n\n return infectionsByRequestedTime;\n}",
"function rollDice () {\n let randomArray = [];\n for (let dicePosition = 0; dicePosition < 6; dicePosition++) {\n let myRoll = Math.floor(Math.random() *6) + 1;\n randomArray.push(myRoll);\n let diceSVG = `img/small-dice/face${randomArray[dicePosition]}.svg`;\n if (document.getElementById(`dice${dicePosition + 1}`).className === 'dice') {\n document.querySelector(`.face${dicePosition}`).setAttribute('src', diceSVG);\n };\n };\n}",
"function randomEncounter() {\n\t\treturn Math.floor((Math.random() * encounters.length));\n\t}",
"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 randomizeDice(){\n diceRoll[0] = Math.floor( Math.random() * 6 )+1;\n diceRoll[1] = Math.floor( Math.random() * 6 )+1;\n}",
"function weaponHit(e, m, ei, mi) {\n\n if(m.x <= (e.x + e.w) && (m.x + m.w) >= e.x && m.y <= (e.y + e.h) && (m.y + m.h) >= e.y) {\n enemyArray.splice(ei,1)\n weaponArray.splice(mi,1)\n new enemyExplosion(\"./sfx/enemyExplosion.wav\")\n score += 100\n\n for(let d=0; d < 15; d++) {\n let size = Math.floor(Math.random() * 3) + 1\n let dx = (Math.random() - 0.5) * 20;\n let dy = (Math.random() - 0.5) * 20;\n let color = colorArray[Math.floor(Math.random()*colorArray.length)]\n debrisArray.push(new enemyDestroyed(e.x, e.y , size, dx, dy, color))\n }\n \n for(let d=0; d < 15; d++) {\n let size = Math.floor(Math.random() * 1) + 1\n let dx = (Math.random() - 0.5) * 30;\n let dy = (Math.random() - 0.5) * 30;\n let color = colorArray2[Math.floor(Math.random()*colorArray.length)]\n debrisArray.push(new enemyDestroyed(e.x, e.y , size, dx, dy, color))\n }\n }\n}",
"function scoreByCollision()\r\n{ \r\n for(let i=0; i<arrayOfShoot.length; i++)\r\n {\r\n for(let fi=0;fi<arrayOfEvil.length;fi++)\r\n {\r\n\r\n if((arrayOfShoot[i].yShoot+25+h1>arrayOfEvil[fi].yEvil)&&(arrayOfShoot[i].yShoot+25<arrayOfEvil[fi].yEvil+h2)&&(arrayOfShoot[i].xShoot+20+h1>arrayOfEvil[fi].xEvil)&&(arrayOfShoot[i].xShoot+20<arrayOfEvil[fi].xEvil+h2))\r\n {\r\n arrayOfEvil[fi].xEvil=600;\r\n arrayOfEvil[fi].yEvil= Math.random()*400;\r\n arrayOfShoot[i].xShoot=610;\r\n hittingSound.play();\r\n score++;\r\n }\r\n }\r\n }\r\n}",
"function generateEnergies()\r\n{\r\n var position = 0;\r\n\r\n for (var i = 0; i < numOfEnergies; i++)\r\n {\r\n\r\n //add platform to array with dimensions\r\n energies[i] = new Energy(Math.random()*(width-energyRadius),position);\r\n\r\n //if platform is below screen add it to the top of the screen.... (I think lol)\r\n if (position < height - energyRadius)\r\n {\r\n position += ~~(height / numOfEnergies);\r\n }\r\n }\r\n}",
"static populateCases() {\n let casesArray = [];\n\n let amounts = [\n 0.01,\n 1,\n 5,\n 10,\n 25,\n 50,\n 75,\n 100,\n 200,\n 300,\n 400,\n 500,\n 750,\n 1000,\n 5000,\n 10000,\n 25000,\n 50000,\n 75000,\n 100000,\n 200000,\n 300000,\n 400000,\n 500000,\n 750000,\n 1000000\n ];\n\n for (var i = 0; i < 26; i++) {\n //get a random number from the amounts array\n \n let ranIndex = Math.floor(Math.random() * (amounts.length));\n\n let ranAmount = amounts[ranIndex];\n casesArray.push(new CaseClass(i + 1, ranAmount));\n\n //take the selected case out of the case list so there are no duplicates of amounts.\n amounts.splice(ranIndex,1);\n \n }\n return casesArray;\n }",
"shortRest(recoveredHitPoints, hitDiceToSpend) {\n this.hitPoints += recoveredHitPoints\n if (this.hitPoints > this.maxHitPoints) {\n this.hitPoints = this.maxHitPoints\n }\n hitDiceToSpend.map(d => d.className).forEach(c => {\n this.toggleHitDie(c, true)\n })\n }",
"attackOutcome (opponentDodge) {\n let successRoll = this.getRandomInt();\n if (successRoll >= opponentDodge){\n return true;\n } else {\n return false;\n }\n }",
"function diceRoll() {\n\t\trollValues = [];\n\t\tdieRoll6 = Math.floor(Math.random() * 6 ) + 1;\n\t\trollValues.push(dieRoll6);\n\t\tdieRoll20 = Math.floor(Math.random() * 20 ) + 1;\n\t\trollValues.push(dieRoll20);\n\t\trollTotal = dieRoll6 * dieRoll20;\n\t\trollValues.push(rollTotal);\n\t\treturn rollValues;\n}",
"function countryKillers(){\n // init country object with country names as jeys\n for(let i = 0; i < countryNames.length; i++){\n let name = countryNames[i];\n countries[name] = {\"victim count\": 0, \"killer count\": 0, \"killer names\": []};\n }\n\n for(let i = 0; i < killerNames.length; i++){\n let name = killerNames[i]\n let info = killersInfo[name];\n\n for(let c of info[\"countries\"]){\n if(!(c in countries)) continue;\n countries[c][\"victim count\"] += info[\"Proven Victims\"];\n countries[c][\"killer count\"] ++;\n countries[c][\"killer names\"].push(name);\n\n }\n }\n\n for(let c of countryNames){\n let v = countries[c][\"victim count\"];\n if(v > maxVictims) maxVictims = v;\n }\n}",
"function createInitialPopulation() {\n //inits the array\n genomes = [];\n //for a given population size\n for (var i = 0; i < populationSize; i++) {\n //randomly initialize the 7 values that make up a genome\n //these are all weight values that are updated through evolution\n var genome = {\n //unique identifier for a genome\n id: Math.random(),\n //The weight of each row cleared by the given move. the more rows that are cleared, the more this weight increases\n rowsCleared: Math.random() - 0.5,\n //the absolute height of the highest column to the power of 1.5\n //added so that the algorithm can be able to detect if the blocks are stacking too high\n weightedHeight: Math.random() - 0.5,\n //The sum of all the column’s heights\n cumulativeHeight: Math.random() - 0.5,\n //the highest column minus the lowest column\n relativeHeight: Math.random() - 0.5,\n //the sum of all the empty cells that have a block above them (basically, cells that are unable to be filled)\n holes: Math.random() * 0.5,\n // the sum of absolute differences between the height of each column \n //(for example, if all the shapes on the grid lie completely flat, then the roughness would equal 0).\n roughness: Math.random() - 0.5,\n };\n //add them to the array\n genomes.push(genome);\n }\n evaluateNextGenome();\n }",
"generateCalBurnt()\r\n {\r\n var calories = Math.floor((Math.random() * 20) + 1)\r\n console.log(calories)\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
User Story 2: As a user I want to find a number that represents for a list of numbers: the sum of the numbers, divided by half the length of the list, plus the smallest value in the list. I want to do this for two lists of numbers and have the answer returned as a new list named numMeans. | function mean(numberList1, numberList2){
var numMeans = [];
numMeans = sum(numberList1, numberList2);
numMeans[0] = numMeans[0]/(numberList1.length/2) + Math.min.apply(null, numberList1);
numMeans[1] = numMeans[1]/(numberList2.length/2) + Math.min.apply(null, numberList2);
return numMeans;
} | [
"function averages(numbers){\n let avgNums = [];\n if(!numbers) return avgNums;\n for(let i = 1; i < numbers.length; i++){\n let avg = (numbers[i - 1] + numbers[i]) / 2;\n avgNums.push(avg);\n }\n return avgNums;\n}",
"function sumTwoSmallestNumbers(numbers) { \n let arrayNumFour = [55, 87, 2, 4, 22]\n //set the order of the array, either < , >, or vice versa\n arrayNumFour.sort()\n console.log(arrayNumFour)\n //write a line of code to find the lowest values\n \n // return sum of lowest values \n }",
"function calculateAverage(grades) {\n // grades is an array of numbers\n total = 0\n for(let i = 0; i <grades.length; i++){\n total += grades[i];\n }\n return Math.round(total / grades.length);\n}",
"function averageNumbers(array){\n let sum = 0;\n let avg;\n for ( let i = 0 ; i < array.length ; i++ ){\n sum = sum + array[i];\n avg = sum / array.length\n }\n return avg\n}",
"function calcAverage (tips) {\n var sum = 0;\n for (var i = 0; i < tips.length; i++) {\n sum += tips[i];\n }\n return sum / tips.length;\n}",
"function averageTestScore(testScores) {\n let average = 0;\n for (const score of testScores) {\n average += score;\n }\n return average / testScores.length;\n}",
"function mean(num) {\n\treturn [...num.toString()].reduce((x, i) => (Number(x) + Number(i))) / num.toString().length; \n}",
"function AVERAGE() {\n\n // compute sum all of the items.\n var sum = SUM.apply(undefined, arguments);\n\n // return sum when computed error.\n if (ISERROR(sum)) {\n return sum;\n }\n\n // return sum divided by item count\n return sum / arguments.length;\n}",
"function calcAverage(tips){\n var sum = 0\n for(var i = 0; i < tips.length; i++){\n sum = sum + tips[i]\n }\n return sum / tips.length\n }",
"function question1() {\n let listItems = 0;\n for (let i = 0; i < data.length; i++) {\n listItems += data[i].price;\n console.log(listItems);\n }\n let averageprice = (listItems / data.length);\n console.log(\"averageprice\");\n\n}",
"function average(){\n\t\t\tvar sum = 0;\n\t\t\tlist.forEach(function(item){\n\t\t\t\tsum += item.age;\n\t\t\t});\n\n\t\t\treturn sum / list.length;\n\t\t}",
"function getPromedio (scores) {\n return scores.reduce((acum, next) => {\n return acum + next.score / scores.length\n },0)\n}",
"function average() {\n\tvar total = 0;\n\tfor (var i = 0; i < this.grades.length; ++i) {\n\t\ttotal += this.grades[i];\n\t}//end for\n\treturn print(total / this.grades.length);\n}//end average function",
"function arithmeticMean(num1, num2, num3, num4) {\n return (num1 + num2 + num3 + num4) / 4;\n}",
"function findMedianSortedArrays(nums1, nums2) {\n\tlet merged = mergeTwoArrays(nums1, nums2);\n\tlet midIdx = Math.floor(merged.length/2);\n\n\t// if merged array has even num, return average of two middle\n\tif (merged.length % 2 === 0) {\n\t\treturn (merged[midIdx] + merged[midIdx - 1])/2.0;\n\t} else { // if merged array has odd num, return middle\n\t\treturn merged[midIdx];\n\t}\n}",
"function calculateAverage(ratings){\n var sum = 0;\n for(var i = 0; i < ratings.length; i++){\n sum += parseInt(ratings[i], 10);\n }\n\n var avg = sum/ratings.length;\n\n return avg;\n }",
"function avg(v){\n s = 0.0;\n for(var i=0; i<v.length; i++)\n s += v[i];\n return s/v.length;\n}",
"function avgAge(persons) \n{\n var out;\nout=persons.reduce()\n\n return out\n}",
"function calculateAverage(){\n\t// combined_average_video_confidence = 0\n\taverage_confidence_list = []\n\tfor(i = 0; i < grid.array.length; i++) {\n\t\tcurr_video = grid.array[i]\n\t\tsum_video_confidence = 0\n\t\tfor(j = 0; j < curr_video.grades.length; j++) {\n\t\t\tgrade = curr_video.grades[j]\n\t\t\tsum_video_confidence += grade.confidence\n\t\t}\n\t\taverage_video_confidence = sum_video_confidence / curr_video.grades.length\n\t\taverage_confidence_list.push(average_video_confidence)\n\t}\t\t\n\t// return combined_average_video_confidence /= grid.array.length\n\t// return calculateAverage\n\treturn average_confidence_list\n}",
"function findNumbers(num1, num2) {\n let array = [];\n\n for (x = num1; x <= num2; x++) {\n let elements = x.toString().split(\"\");\n let sum = 0;\n elements.forEach(function (element) {\n sum += element * element * element;\n });\n if (sum === x) array.push(x);\n }\n return array;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Animate the generated kittens | function animate(activeKittens) {
ctx.clearRect(0, 0, 1024, 450);
for (var i = 0; i < activeKittens.length; i++) {
var currentCat = activeKittens[i];
if (currentCat.update()) {
i--;
// Lose life and render flag if kitten reaches shore
livesDisplay.innerHTML--;
var pos = currentCat.kittenPos;
var rect = canvas.getBoundingClientRect();
var left = rect.right - 160;
var top = rect.top + pos[1];
if (lives === 3) {
flag1.style.left = "" + left + "px";
flag1.style.top = "" + (top + "px");
flag1.style.display = "inline";
} else if (lives === 2) {
flag2.style.left = "" + left + "px";
flag2.style.top = "" + (top + "px");
flag2.style.display = "inline";
} else if (lives === 1) {
flag3.style.left = "" + left + "px";
flag3.style.top = "" + (top + "px");
flag3.style.display = "inline";
}
lives--;
if (lives === 0) {
flag1.style.display = "none";
flag2.style.display = "none";
flag3.style.display = "none";
}
}
currentCat.draw(ctx);
}
window.requestAnimationFrame(function (timestamp) {
animate(activeKittens);
});
} | [
"function textWiggle() {\n var timelineWiggle = new TimelineMax({repeat:-1, yoyo:true}); \n for(var j=0; j < 10; j++) {\n timelineWiggle.staggerTo(chars, 0.1, {\n cycle: {\n x: function() { return Math.random()*4 - 2; },\n y: function() { return Math.random()*4 - 2; },\n rotation: function() { return Math.random()*10 - 5; }\n },\n ease: Linear.easeNone\n }, 0);\n }\n }",
"function drawKittens() {\n let html = \"\"\n kittens.forEach(kitten => {\n html +=\n `<div class=\"kitten\">\n <h3 class=\"kittendeets\">${kitten.name}</h3>\n <p class=\"kittenface\">${moods[kitten.mood]}</p>\n <p class=\"kittendeets\">Mood: <span>${kitten.mood}</span> | Affection: <span>${kitten.affection}</span> </p>\n <div class=\"kittenbuttons\">\n <button class=\"kittenbutton\" onclick=\"pet(${kitten.id})\">Pet</button>\n <button class=\"kittenbutton\" onclick=\"catnip(${kitten.id})\">Catnip</button>\n <button class=\"kittenbutton\" onclick=\"kill(${kitten.id})\">Kill >:(</button>\n </div>\n </div>`\n })\n document.getElementById(\"kittens\").innerHTML = html\n saveKittens()\n}",
"function confettiAnimation() {\n\nvar confettiSettings = {\n target: 'confetti-canvas'\n};\nvar confetti = new ConfettiGenerator(confettiSettings);\nconfetti.render();\n}",
"function tweenIteration() {\n var iteration = d3.interpolateNumber(+label.text(), maxIteration);\n return function (t) {\n displayIteration(iteration(t));\n };\n }",
"haduken() {\n\t\tthis.updateState(KEN_SPRITE_POSITION.haduken, KEN_IDLE_ANIMATION_TIME, false);\n\t}",
"function animateTiles(clickedIndex) {\n $(this).fadeOut(70); \n $(this).fadeIn(200); \n }",
"function knightsRunAway1(skew,callback) {//move left and skew\n $('.arthur').css('transform',skew).animate({\n left: '-=10px'\n },50,'linear',callback);\n}",
"function loopAnim() {\n // flake.animate({\n // top: 0,\n // left: thisLeft + Math.floor(Math.random() * (max - min + 1)) + min\n // }, 0)\n // .animate({\n // top: '100%',\n // left: thisLeft + Math.floor(Math.random() * (max - min + 1)) + min\n // }, thisSpeed, 'linear', function() {\n // loopAnim();\n // });\n // console.log(1111);\n flake.css({ \"transform\": \"translate(\" + (thisLeft + Math.floor(Math.random() * (max - min + 1)) + min) + \"px,\" + 0 + \"px)\", \"transition-duration\": \"0ms\", \"transition-timing-function\": \"linear\" });\n flake.timer = setTimeout(function() {\n loopAnim2();\n }, 16)\n }",
"function animateSlogan() {\n var slogan = $(\".PageTitle h3\").text();\n $(\".PageTitle h3\").text(\"\");\n var a = 0;\n\n function typingSlogan() {\n if (a == slogan.length) {\n clearInterval(interval);\n setTimeout(function () {\n a = 1;\n $(\".PageTitle h3\").animate({ opacity: 0 }, \"fast\");\n setTimeout(function () {\n $(\".PageTitle h3\").css(\"opacity\", 1).text(slogan.substr(0, 1));\n interval = setInterval(typingSlogan, 20);\n }, 1000);\n }, 4000);\n }\n $(\".PageTitle h3\").append(slogan.substr(a, 1))\n a++;\n }\n var interval = setInterval(typingSlogan, 20)\n\n }",
"function animateGame(){\n var i = 0;\n var intervalId = setInterval(function() {\n if(i >= sequenceArray.length) {\n clearInterval(intervalId);\n }\n animate(i);\n i++;\n }, 800);\n }",
"function Cards_animation() {\n\t\tvar i_count = 0;\n\t\tthis.fadeIn=function(){\n\t\t\ti_count = 0;\n\t\t\tfor (var ir = 0; ir < $('.row_for_cards').length ; ir++) {\n\t\t\t\tfor (var i = 0; i < $('.row_for_cards').eq(ir).find('.card').length; i++) {\n\t\t\t\t\t$('.row_for_cards').eq(ir).find('.card').eq(i).css({'display':'inline-block'});\n\t\t\t\t\t$('.row_for_cards').eq(ir).find('.card').eq(i).delay(700+i_count*25).fadeTo(1000, 1);\n\t\t\t\t\ti_count++;\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tthis.fadeOut=function(){\n\t\t\ti_count = 0;\n\t\t\tfor (var ir = $('.row_for_cards').length-1; ir >= 0 ; ir--) {\n\t\t\t\tfor (var i = $('.row_for_cards').eq(ir).find('.card').length-1; i >= 0; i--) {\n\t\t\t\t\t$('.row_for_cards').eq(ir).find('.card').eq(i).delay(700+i_count*25).fadeTo(1000, 0);\n\t\t\t\t\tif(ir===0 && i===0){\n\t\t\t\t\t\t$('#hide_cards').delay(700+i_count*25).fadeIn(1000);\n\t\t\t\t\t}\n\t\t\t\t\ti_count++;\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}",
"animate() {\n\t\t// increase the entropy value by one for use in animations\n\t\t// require more entropy in visual than in audio\n\t\tlet animateEntropy = this.state.entropy + 1;\n\n\t\t// kick off anime targeting unanimated note pieces\n\t\t// use random translate/transform values using entropy value in equation\n\t\tAnime({\n\t\t\ttargets: '[data-note-piece]:not(.animated)',\n\t\t\ttranslateX: () => {\n\t\t\t\tlet num = 3 * animateEntropy;\n\t\t\t\treturn Anime.random(num * -1, num) + 'rem';\n\t\t\t},\n\t\t\ttranslateY: () => {\n\t\t\t\tlet num = 3 * animateEntropy;\n\t\t\t\treturn Anime.random(num * -1, num) * animateEntropy + 'rem';\n\t\t\t},\n\t\t\tscale: () => {\n\t\t\t\treturn Anime.random(5, 30) * animateEntropy / 10;\n\t\t\t},\n\t\t\trotate: () => {\n\t\t\t\treturn Anime.random(-900, 900) * animateEntropy;\n\t\t\t},\n\t\t\tdelay: () => {\n\t\t\t\treturn Anime.random(0, 100);\n\t\t\t},\n\t\t\tduration: () => {\n\t\t\t\treturn Anime.random(500, 750);\n\t\t\t},\n\t\t\topacity: .7,\n\t\t\tdirection: 'alternate',\n\t\t});\n\n\t\t// once animation kicked off set all note pieces as 'animated'\n\t\t[].forEach.call(document.querySelectorAll('[data-note-piece]'), (piece) => {\n\t\t\tpiece.classList.add('animated');\n\t\t});\n\t}",
"function startDigitAnimation(digitType) {\n\n var fadein_tween = TweenLite.from( 'span.digit.'+digitType, 1, {autoAlpha:.4, y: 7} );\n}",
"function spawnPainting() {\n if (!animating) {\n scalar = 1;\n\n generateMondrian();\n\n animating = true;\n t = 0;\n // loop();\n }\n }",
"function animate() {\n illustration.updateRenderGraph();\n dice.rotate.x += 0.01;\n dice.rotate.y -= 0.01;\n requestAnimationFrame(animate);\n}",
"function showStars() {background(\n\t0, 0, 40, sparkle_trail);\n\n\t////moon///\n\tif (started) {\n\t\tfill(255);\n\t\tellipse(100, 100, 150, 150);\n\t\tfill(0, 0, 40);\n\t\tellipse(130, 90, 130, 130);\n\t}////moon///\n\n\tif (!showingStars) {showingStars = true;\n\t\tfor (let i = 0; i < 300; i++) {stars[i] = new Star;}\n\t}\n\tfor (let i = 0; i < stars.length; i++) {\n\t\tstars[i].show();\n\t}\n}////////MAKE 300 STARS AND SHOW THEM////////",
"animate () {\n if (this.multiStep) this.animateSteps()\n this.animateDraws()\n }",
"function mousePressed() {\n toggle++;\n toggle = toggle % 3;\n for (var i = 0; i < tendrilsPerMonster; i++) {\n tendrils.push(new Tendril());\n }\n}",
"startRandomAnimation() {\n this.clearPrevious();\n try {\n let n = this.getN();\n let parameterObject = this.generateParameter(n);\n this.startAnimation(parameterObject);\n } catch (e) {\n\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get selected mosaic and push it in mosaics array | attachMosaic() {
// increment counter
this.counter++;
// Get current account
let acct = this._Wallet.currentAccount.address;
if (this.formData.isMultisig) {
// Use selected multisig
acct = this.formData.multisigAccount.address;
}
// Get the mosaic selected
let mosaic = this._DataBridge.mosaicOwned[acct][this.selectedMosaic];
// Check if mosaic already present in mosaics array
let elem = $.grep(this.formData.mosaics, function(w) {
return helpers.mosaicIdToName(mosaic.mosaicId) === helpers.mosaicIdToName(w.mosaicId);
});
// If not present, update the array
if (elem.length === 0) {
this.formData.mosaics.push({
'mosaicId': mosaic['mosaicId'],
'quantity': 0,
'gid': 'mos_id_' + this.counter
});
this.updateFees();
}
} | [
"function generate_mosaic() {\n \n \n remove_previous_layer()\n var years_list = parse_years(); // Parse the years input\n var months_list = parse_months(); // Parse the months input\n print(\"Years List:\", years_list, \"Months list\", months_list); // Testing\n \n // Prepare date variables\n var start_year = parseInt(years_list.slice(0,1));\n var end_year = parseInt(years_list.slice(1,2));\n var start_month = parseInt(months_list.slice(0,1));\n var end_month = parseInt(months_list.slice(1,2));\n\n \n // Get drawing tools and get polyhon\n var drawingTools = Map.drawingTools(); \n\n\n // Logic to handle selection box for Q mosaic type\n //-----------------------------------------------------\n \n // Placeholder for image collection\n var collection = {}; \n \n // Define Visualization Parameters\n var viz = {bands: ['B4', 'B3', 'B2'], min: 0, max: 0.4, gamma: 1.5};\n \n\n var aoi = polygon\n \n // Cloudless Q Mosaic\n if (type_mosaic_select.getValue() == \"Cloudless Quality Mosaic\") {\n print(\"Cloudless Start\");\n collection = ee.ImageCollection(\"LANDSAT/LC08/C01/T1_TOA\") // Load LS8 TOA\n .filterBounds(aoi) // Filter for images by polygon\n .filter(ee.Filter.calendarRange(start_year, end_year, \"year\")) // Filter for years\n .filter(ee.Filter.calendarRange(start_month, end_month, 'month')) // Filter for months\n .map(cloudless_mosaic); // Send each image to the cloudless mosaic function\n Map.addLayer(collection, viz, \"Cloudless Quality Mosaic\"); // Add layer\n }\n // Greenest pixel (NDVI) mosaic\n else if (type_mosaic_select.getValue() == \"NDVI Quality Mosaic\") {\n print(\"NDVI Start\");\n collection = ee.ImageCollection(\"LANDSAT/LC08/C01/T1_TOA\") // Load LS8 TOA\n .filterBounds(aoi) // Filter for images by polygon\n .filter(ee.Filter.calendarRange(start_year, end_year, \"year\")) // Filter for years\n .filter(ee.Filter.calendarRange(start_month, end_month, 'month')) // Filter for months\n .map(add_ndvi); // Send images to the add NDVI function\n var greenest = collection.qualityMosaic('NDVI'); //Create a quality mosaic based on the NDVI function\n var clipped_greenest= greenest.clip(aoi); // Clip the Q mosaic \n\n // Add NDVI mosaic to the map\n Map.addLayer(clipped_greenest, viz, \"NDVI Quality Mosaic\");\n }\n \n\n}",
"function mosaicBySeasonS1(images) {\n var property = interval;\n \n var distinct = images.distinct([property]); //Removes duplicates from a collection\n \n // ---------- Create a time filter to define a match as overlapping timestamps.\n var filter = ee.Filter.equals({leftField: property, rightField: property});\n \n // ---------- Define the join.\n var saveAllJoin = ee.Join.saveAll({\n matchesKey: 'matches',\n ordering: 'system:time_start',\n ascending: true\n });\n \n // ---------- Apply the join.\n var results = saveAllJoin.apply(distinct, images, filter);\n \n // mosaic\n var bandNames = ee.Image(images.first()).bandNames();\n results = results.map(function(i) {\n var mosaic = null;\n mosaic = ee.ImageCollection.fromImages(i.get('matches')).sort(interval)\n .mean(); // create a mean mosaic\n \n return mosaic.copyProperties(i).set(property, i.get(property))\n .set('system:time_start', ee.Date(i.get(property)).millis());\n });\n return ee.ImageCollection(results);\n }",
"setMosaicTransfer() {\n if (this.formData.isMosaicTransfer) {\n // Set the initial mosaic array\n this.formData.mosaics = [{\n 'mosaicId': {\n 'namespaceId': 'nem',\n 'name': 'xem'\n },\n 'quantity': 0,\n 'gid': 'mos_id_0'\n }];\n // In case of mosaic transfer amount is used as multiplier,\n // set to 1 as default\n this.formData.amount = 1;\n } else {\n // Reset mosaics array\n this.formData.mosaics = null;\n // Reset amount\n this.formData.amount = 0;\n }\n this.updateFees();\n }",
"function imageSelect() {\n var cropChoices = cropData[0][\"crops\"];\n var currentCrop = document.getElementById(\"cropSelector\").value;\n\n\n // console.log(currentCrop);\n for (i in cropChoices) {\n var crop = cropChoices[i];\n var name = crop.name;\n // console.log(\"season\" + season);\n\n // set image source to currentCrop\"s value.\n if (currentCrop === name) {\n image.src = cropChoices[i][\"graph\"];\n }\n }\n}",
"function app(){\n //Set up the dropzone\n var dropZone = document.querySelector('#dropzone input');\n \n dropZone.addEventListener('dragenter',function(e){\n e.target.parentNode.classList.add('active');\n e.preventDefault();\n });\n \n dropZone.addEventListener('dragover',function(e){\n e.preventDefault();\n });\n \n dropZone.addEventListener('dragleave',function(e){\n e.target.parentNode.classList.remove('active');\n e.preventDefault();\n });\n\n dropZone.addEventListener('drop',function(e){\n e.target.parentNode.classList.remove('active');\n\n //# A file has been dropped, load the file\n loadFile(e.dataTransfer.files[0]);\n\n e.preventDefault();\n })\n\n //Listen to the change event of the file selector\n dropZone.addEventListener('change',function(e){\n\n //# A file has been chosen, load the file\n loadFile(e.target.files[0]);\n\n e.target.value = \"\";\n });\n\n //Listen to the click events of the close buttons on the result window\n var closeButtons = document.querySelectorAll(\".message .close\");\n for(var i = 0; i < closeButtons.length; i++){\n closeButtons[i].addEventListener('click',hideResult);\n }\n\n //Initialize the PhotoMosaic creator\n var drawArea = document.getElementById('drawArea');\n mosaicCreator = PhotoMosaic(drawArea,mosaicStarted,mosaicProgressChanged,mosaicCompleted,mosaicFailed);\n}",
"function flavour1(){\n flavourSelect=[\"flavour1\", 100];\n }",
"setImageAsPrimary(label) {\n let images = this.state.images;\n\n for (let i = 0; i < images.length; i++) {\n if (images[i].label === label) {\n let image = images[i];\n\n images.splice(i, 1);\n images.push(this.state.selectedImage);\n\n this.setState({\n selectedImage: image,\n images: images\n })\n return;\n }\n }\n }",
"function mosaic_and_reduce_IC_mean(an_IC){\n an_IC = ee.ImageCollection(an_IC);\n \n var reduction_geometry = ee.Feature(ee.Geometry(an_IC.get('original_polygon')));\n var WSDA = an_IC.get('WSDA');\n var start_date_DateType = ee.Date(start_date);\n var end_date_DateType = ee.Date(end_date);\n //######**************************************\n // Difference in days between start and end_date\n\n var diff = end_date_DateType.difference(start_date_DateType, 'day');\n\n // Make a list of all dates\n var range = ee.List.sequence(0, diff.subtract(1)).map(function(day){\n return start_date_DateType.advance(day,'day')});\n\n // Funtion for iteraton over the range of dates\n function day_mosaics(date, newlist) {\n // Cast\n date = ee.Date(date);\n newlist = ee.List(newlist);\n\n // Filter an_IC between date and the next day\n var filtered = an_IC.filterDate(date, date.advance(1, 'day'));\n\n // Make the mosaic\n var image = ee.Image(filtered.mosaic());\n\n // Add the mosaic to a list only if the an_IC has images\n return ee.List(ee.Algorithms.If(filtered.size(), newlist.add(image), newlist));\n }\n\n // Iterate over the range to make a new list, and then cast the list to an imagecollection\n var newcol = ee.ImageCollection(ee.List(range.iterate(day_mosaics, ee.List([]))));\n //print(\"newcol 1\", newcol);\n //######**************************************\n\n var reduced = newcol.map(function(image){\n return image.reduceRegions({\n collection:reduction_geometry,\n reducer:ee.Reducer.mean(), \n scale: 10\n });\n }\n ).flatten();\n \n reduced = reduced.set({ 'original_polygon': reduction_geometry,\n 'WSDA':WSDA\n });\n WSDA = ee.Feature(WSDA);\n WSDA = WSDA.toDictionary();\n \n // var newDict = {'WSDA':WSDA};\n reduced = reduced.map(function(im){return(im.set(WSDA))}); \n return(reduced);\n}",
"function buildMovieList(){\n\n for(let i=0; i < titles.length; i++){\n\n var mov = {\n 'title':titles[i],\n 'src':images[i],\n 'synopsis':synopsis[i],\n 'directors':directors[i],\n 'actors':actors[i],\n 'year':year[i]\n };\n\n //add to each set of info to allMovieInfo Array\n allMovieInfo.push(mov);\n\n }\n\n}",
"function getCards(){\r\n mosaic.innerHTML = ''\r\n fetch(SURVEY_URL)\r\n .then(resp => resp.json())\r\n .then(surveys => {\r\n const surveysArray = surveys['data']\r\n for (const survey of surveysArray) {\r\n mosaic.innerHTML += `\r\n <div class=\"card\" id=\"${survey.id}\">\r\n <div class=\"card-body\">\r\n <h5 class=\"card-title\">${survey['attributes']['name']}</h5>\r\n <p class=\"card-text survey_description\">${survey['attributes']['description']}</p>\r\n <button type=\"button\" class=\"btn btn-success\" data-toggle=\"modal\" data-target=\"#takeSurvey\" onclick=\"Survey.populate(${survey.id})\"> Take Survey </button>\r\n <button type=\"button\" class=\"btn btn-info\" data-toggle=\"modal\" data-target=\"#surveyResults\" onclick=\"Survey.results(${survey.id})\"> See Results </button>\r\n <br /><br />\r\n <button type=\"button\" class=\"btn btn-primary\" onclick=\"Survey.deleteSurvey(${survey.id})\"> Delete Survey </button>\r\n\r\n </div>\r\n </div>\r\n `\r\n }\r\n })\r\n}",
"function displaySceneImages() {\n for (let i = 0; i < extractImages.length; i++) {\n \n extractImages[i].style.display = 'block'\n }\n}",
"lookupSelectedRegions() {\r\n const collection = Array();\r\n for (const region of this.regions) {\r\n if (region.isSelected) {\r\n collection.push(region);\r\n }\r\n }\r\n return collection;\r\n }",
"function selectPropertiesInAllSelectedInsula(uniqueClicked){\n\t\tif(interactive){\n\t\t\tvar i=0;\n\t\t\tvar currentInsulaId;\n\t\t\tvar currentInsula;\n\t\t\tvar listOfSelectedInsulaIds=[];\n\t\t\tfor(i;i<clickedInsula.length;i++){\n\t\t\t\tcurrentInsula=clickedInsula[i];\n\t\t\t\tcurrentInsulaId=currentInsula[1];\n\t\t\t\tlistOfSelectedInsulaIds.push(currentInsulaId);\n\t\t\t}\n\t\t\tpompeiiInsulaLayer.eachLayer(function(layer){\n\t\t\t\tif(layer.feature!=undefined){\n\t\t\t\t\tif(listOfSelectedInsulaIds.indexOf(layer.feature.properties.insula_id)!=-1 && !uniqueClicked.includes(layer)){\n\t\t\t\t\t\tuniqueClicked.push(layer);\n\t\t\t\t\t\tlayer.feature.properties.clicked=true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn uniqueClicked;\n\t}",
"function selectPoint (poi) {\n\tselectedPoints.push(poi);\n}",
"categorizeAdventures() {\n const categorizedAdventures = [];\n this.props.adventures.forEach((adventure) => {\n if (adventure.catagory === this.props.category) { //sic\n categorizedAdventures.push(adventure);\n }\n })\n this.setState({adventures: categorizedAdventures})\n }",
"function loadArtistsInSelect(album) {\r\n // array per controllo nomi degli artisti da caricare nella select\r\n var arraySelect = [];\r\n // ciclo per caricare i nomi artisti nella select\r\n for (var i = 0; i < album.length; i++) {\r\n // controlla se il nome artista è già stato inserito nella select\r\n if (!arraySelect.includes(album[i].author)) {\r\n // aggiune il nome artista nell'array di controllo dei nomi\r\n arraySelect.push(album[i].author);\r\n // aggiunge il nome artista alla select\r\n $(\".select-artist\").append(\"<option value='\"+album[i].author+\"'>\"+album[i].author+\"</option>\");\r\n };\r\n };\r\n}",
"function getSelectedImg() {\n return gImgs.find(img => img.id === gMeme.selectedImgId)\n}",
"function add_EVI_collection(image_IC){\n var EVI_IC = image_IC.map(addEVI_to_image);\n return EVI_IC;\n}",
"function cat_pics() {\n var Cat_Picture = [] ;\n Cat_Picture[0] = \"sleeping\";\n Cat_Picture[1] = \"playing\";\n Cat_Picture[2] = \"eating\";\n Cat_Picture[3] = \"purring\";\n document.getElementById(\"Cat\").innerHTML = \"In this picture, the cat is \" + \n Cat_Picture[2] + \".\";\n }",
"function updateSelect() {\n for (var i=0;i<g_points.length;i++){\n figures.options[i+1] = new Option('Surface' +i, i);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates Raycaster object from the mouse pointer | pointerToRay(pointer) {
const camera = this.viewer.navigation.getCamera()
const pointerVector = new THREE.Vector3()
const rayCaster = new THREE.Raycaster()
const pointerDir = new THREE.Vector3()
const domElement = this.viewer.canvas
const rect = domElement.getBoundingClientRect()
const x = ((pointer.clientX - rect.left) / rect.width) * 2 - 1
const y = -((pointer.clientY - rect.top) / rect.height) * 2 + 1
if (camera.isPerspective) {
pointerVector.set(x, y, 0.5)
pointerVector.unproject(camera)
rayCaster.set(camera.position,
pointerVector.sub(
camera.position).normalize())
} else {
pointerVector.set(x, y, -15)
pointerVector.unproject(camera)
pointerDir.set(0, 0, -1)
rayCaster.set(pointerVector,
pointerDir.transformDirection(
camera.matrixWorld))
}
return rayCaster.ray
} | [
"function RayHelper(ray){this.ray=ray;}",
"function makeMantaRayButton() {\n\n // Create the clickable object\n mantaRayButton = new Clickable();\n \n mantaRayButton.text = \"\";\n\n mantaRayButton.image = images[16]; \n\n // gives the Manta ray a transparent background \n mantaRayButton.color = \"#00000000\";\n mantaRayButton.strokeWeight = 0; \n\n // set width + height to image size\n mantaRayButton.width = 242; \n mantaRayButton.height = 156;\n\n // places the button on the page \n mantaRayButton.locate( width * (1/32) - mantaRayButton.width * (1/32), height * (1/3) - mantaRayButton.height * (1/3));\n\n // // Clickable callback functions, defined below\n mantaRayButton.onPress = mantaRayButtonPressed;\n mantaRayButton.onHover = beginButtonHover;\n mantaRayButton.onOutside = animalButtonOnOutside;\n}",
"function mouseDragged(){\ncircles.push(new Circle(mouseX, mouseY));\n}",
"create() {\n this.scene.bringToTop('CursorScene');\n console.log('Starting screen:', this.key);\n // this.layers.setLayersDepth();\n }",
"function RaycastResult(){/**\n\t * @property {Vec3} rayFromWorld\n\t */this.rayFromWorld=new Vec3();/**\n\t * @property {Vec3} rayToWorld\n\t */this.rayToWorld=new Vec3();/**\n\t * @property {Vec3} hitNormalWorld\n\t */this.hitNormalWorld=new Vec3();/**\n\t * @property {Vec3} hitPointWorld\n\t */this.hitPointWorld=new Vec3();/**\n\t * @property {boolean} hasHit\n\t */this.hasHit=false;/**\n\t * The hit shape, or null.\n\t * @property {Shape} shape\n\t */this.shape=null;/**\n\t * The hit body, or null.\n\t * @property {Body} body\n\t */this.body=null;/**\n\t * The index of the hit triangle, if the hit shape was a trimesh.\n\t * @property {number} hitFaceIndex\n\t * @default -1\n\t */this.hitFaceIndex=-1;/**\n\t * Distance to the hit. Will be set to -1 if there was no hit.\n\t * @property {number} distance\n\t * @default -1\n\t */this.distance=-1;/**\n\t * If the ray should stop traversing the bodies.\n\t * @private\n\t * @property {Boolean} _shouldStop\n\t * @default false\n\t */this._shouldStop=false;}",
"function Cursor() {\r\n\tvar fader2d = Fader2D();\r\n\tvar pushDetector = PushDetector();\r\n\r\n\tvar events = Events();\r\n\tvar api = {\r\n\t\tonattach : onattach,\r\n\t\tondetach : ondetach,\r\n\t\tpushDetector : pushDetector,\r\n\t\tfader2d : fader2d,\r\n\t\tvalue : [0,0],\r\n\t\tx : 0,\r\n\t\ty : 0,\r\n\t}\r\n\tevents.eventify(api);\r\n\t\r\n\tfader2d.addEventListener('valuechange', function(f) {\r\n\t\tapi.value[0] = api.x = f.value[0];\r\n\t\tapi.value[1] = api.y = 1 - f.value[1];\r\n\t\tevents.fireEvent('move', api);\r\n\t});\r\n\r\n\tpushDetector.addEventListener('push', function(pd) {\r\n\t\tevents.fireEvent('push', api);\r\n\t});\r\n\tpushDetector.addEventListener('release', function(pd) {\r\n\t\tevents.fireEvent('release', api);\r\n\t});\r\n\tpushDetector.addEventListener('click', function(pd) {\r\n\t\tevents.fireEvent('click', api);\r\n\t});\r\n\r\n\tfunction onattach(target) {\r\n\t\ttarget.addListener(fader2d);\r\n\t\ttarget.addListener(pushDetector);\r\n\t}\r\n\r\n\tfunction ondetach(target) {\r\n\t\ttarget.removeListener(fader2d);\r\n\t\ttarget.removeListener(pushDetector);\r\n\t}\r\n\r\n\treturn api;\r\n}",
"createHitbox(obj, func)\r\n {\r\n let adjustedScale = Vector2.scale(Helpers.cssPerPx, obj.scale);\r\n let adjustedPos = Vector2.scale(Helpers.cssPerPx, obj.position);\r\n\r\n let hb = document.createElement(\"div\");\r\n\r\n hb.style.width = adjustedScale.x + \"px\";\r\n hb.style.height = adjustedScale.y + \"px\";\r\n\r\n hb.style.position = \"absolute\";\r\n hb.style.left = adjustedPos.x + \"px\";\r\n hb.style.top = adjustedPos.y + \"px\";\r\n\r\n hb.style.borderRadius = Math.round(Math.max(adjustedScale.x, adjustedScale.y) / 2) + \"px\";\r\n\r\n hb.style.pointerEvents = \"auto\";\r\n\r\n hb.addEventListener(\"click\", (event) => {\r\n this.mouseEvent(event);\r\n func(this.mouse.position);\r\n });\r\n\r\n this.wrapper.appendChild(hb);\r\n }",
"startTrackingMouse() {\n if (!this._pointerWatch) {\n let interval = 1000 / Clutter.get_default_frame_rate();\n this._pointerWatch = PointerWatcher.getPointerWatcher().addWatch(interval, this.scrollToMousePos.bind(this));\n }\n }",
"function updateMouseVector() {\n mouse = createVector(myMouseX * inverseScaleUp, myMouseY * inverseScaleUp);\n}",
"function Ray (\n o = new Point3(),\n d = new Vector3(),\n tMax = Infinity,\n time = 0,\n medium = null\n) {\n this.o = o // Point3\n this.d = d // Vector3\n\n this.tMax = tMax // Number\n this.time = time // Number\n\n this.medium = medium // Medium\n}",
"function mouseClicked(){\n coll.push(new collectionLines([mouseX, mouseY],30));\n}",
"function onSelectStart(event){\n\n if (event instanceof MouseEvent && !renderer.xr.isPresenting()){\n\t// Handle mouse click outside of VR.\n\t// Determine screen coordinates of click.\n\tvar mouse = new THREE.Vector2();\n\tmouse.x = (event.clientX / window.innerWidth) * 2 - 1;\n\tmouse.y = - (event.clientY / window.innerHeight) * 2 + 1;\n\t// Create raycaster from the camera through the click into the scene.\n\tvar raycaster = new THREE.Raycaster();\n\traycaster.setFromCamera(mouse, camera);\n\n\t// Register the click into the GUI.\n\tGUIVR.intersectObjects(raycaster);\n }\n\n}",
"function mouseDragged() {\n let r = random(10, 20);\n let b = new Snow(mouseX, mouseY, r);\n snow.push(b);\n}",
"function __Mouse() {\r\n\tthis.x = 0;\r\n\tthis.y = 0;\r\n\tthis.xWin\t = 0;\r\n\tthis.yWin\t = 0;\r\n\tthis.button = __config.nullString;\r\n\tthis.target = __config.nullString;\r\n\tthis.evnt = __config.nullString; \r\n\r\n\t// this function set the status of the mouse on each event\r\n\tthis.fire = function(e) {\r\n\t// e -> event\r\n\t\t__printDebug(e);\r\n\t\tif (e.type = \"mousemove\") {\r\n\t\t\tthis.x = e.screenX;\r\n\t\t\tthis.y = e.screenY;\r\n\t\t\tthis.xWin = e.clientX + window.pageXOffset;\r\n\t\t\tthis.yWin = e.clientY + window.pageYOffset;\r\n\t\t}\r\n\r\n\t\tif (e.type === \"click\" || e.type === \"dblclick\") {\r\n\t\t\tthis.target = \"[nodeName] = \" + e.target.nodeName + \r\n\t\t\t \" :: [Value] = \" + e.target.value + \r\n\t\t\t \" :: [HREF] = \" + (e.target.href ? \"NO\" : e.target.href) + \r\n\t\t\t\t\t \" :: [TEXTCONTENT] = \" + e.target.textContent.htmlEncode().substring(0,1024);\r\n\t\t\tswitch(e.button) {\r\n\t\t\tcase 0: \r\n\t\t\t\tthis.button = __config.LeftMouseDef;\r\n\t\t\t\tbreak;\r\n\t\t\tcase 1:\r\n\t\t\t\tthis.button = __config.CenterMouseDef;\r\n\t\t\t\tbreak;\r\n\t\t\tcase 2:\r\n\t\t\t\tthis.button = __config.RightMouseDef;\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tthis.button = __config.OtherMouseDef;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tthis.button = __config.nullString;\r\n\t\t\tthis.target = __config.nullString;\r\n\t\t}\r\n\r\n\t\tswitch(e.type) {\r\n\t\t\tcase \"click\": \r\n\t\t\t\tthis.evnt = __config.clickDef;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"dblclick\":\r\n\t\t\t\tthis.evnt = __config.dblclickDef;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"mousemove\":\r\n\t\t\t\tthis.evnt = __config.mousemoveDef;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"onmousedown\":\r\n\t\t\t\tthis.evnt = __config.clickDef;\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tthis.evnt = __config.nullString;\r\n\t\t}\r\n\t}\r\n\r\n\t// This functions returns the mouse object actual status\r\n\t/*\r\n\t{\r\n\t\tx: x position of the mouse with respect to screen \r\n\t\ty: y position of the mouse with respect to screen \r\n\t\tevnt: event that was triggered\r\n\t\tbutton: eventually clicked button\r\n\t}\r\n\t*/\r\n\tthis.get = function() {\r\n\t\treturn {\r\n\t\t\tx: this.x,\r\n\t\t\ty: this.y,\r\n\t\t\txWin: this.xWin,\r\n\t\t\tyWin: this.yWin,\r\n\t\t\tevnt: this.evnt,\r\n\t\t\tbutton: this.button,\r\n\t\t\ttarget: this.target\r\n\t\t}\r\n\t}\r\n}",
"function mousePressed() {\n covid20.x = mouseX;\n covid20.y = mouseY;\n}",
"buildCursor(props) {\n let cursorCameraControls = `movement-controls=\"controls: checkpoint\"`;\n let cursor = ``;\n\n if (props.cursorCamera === true) {\n // Add camera cursor\n // cursorCameraControls = `look-controls movement-controls=\"controls: checkpoint\"`;\n cursorCameraControls = `look-controls`;\n cursor = `<a-entity\n cursor=\"fuse: true\"\n material=\"color: black; shader: flat\"\n position=\"0 0 -3\"\n raycaster=\"objects: ${props.cursorTargetClass};\"\n geometry=\"primitive: ring; radiusInner: 0.08; radiusOuter: 0.1;\"\n >\n </a-entity>`;\n }\n return {\n cursorCameraControls: cursorCameraControls,\n cursor: cursor\n }\n }",
"function new_Hitbox(hitbox)\n{\n\tif(null == hitbox)\n\t\treturn null;\n\treturn new Hitbox(hitbox.width, hitbox.height);\t\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 FreeCameraMouseInput(/**\n * Define if touch is enabled in the mouse input\n */touchEnabled){if(touchEnabled===void 0){touchEnabled=true;}this.touchEnabled=touchEnabled;/**\n * Defines the buttons associated with the input to handle camera move.\n */this.buttons=[0,1,2];/**\n * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.\n */this.angularSensibility=2000.0;this.previousPosition=null;}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
===================================================================================================// _LOAD_BOOK_FILE_===================================================================================// Function called when there's a change in the "upload_stopwords" document element. Reads the given file and stores it in book_text. =================================================================================================== | function Load_Book_File(evt)
{
if(evt.target.files[0]) //if the file is available
{
var reader = new FileReader(); //create new reader file
reader.readAsText(evt.target.files[0]); //get file
reader.onload = function(e) //wait for the file to load
{
book_text = reader.result; //store the result
Enable_Word_Count_Button(); //check if the Word Count button can be enabled
};
}
} | [
"function Load_Stop_Words_File(evt)\n{\n if(evt.target.files[0]) //if the file is available\n {\n var reader = new FileReader(); //create new reader file\n reader.readAsText(evt.target.files[0]); //get file\n reader.onload = function(e) //wait for the file to load\n {\n stop_words_text = reader.result; //store the result\n\t\t\tEnable_Word_Count_Button(); //check if the Word Count button can be enabled\n };\n }\n}",
"function loadFileAsText() {\n\tvar fileToLoad = document.getElementById(\"fileToLoad\").files[0];\n\tvar textFromFileLoaded = \"\";\n\tvar fileReader = new FileReader();\n\tfileReader.onload = function(fileLoadedEvent) {\n\t\ttextFromFileLoaded = fileLoadedEvent.target.result;\n\t\tdocument.getElementById(\"inputTextToSave\").value = fileLoadedEvent.target.result;\n\t\tparseFile(textFromFileLoaded)\n\t\tsetCharacterInfo(fileInfo.character.class_name.toLowerCase())\n\t};\n\tfileReader.readAsText(fileToLoad, \"UTF-8\");\n}",
"function startReadingBibtexFile(completionFunction)\n\t {\n\t \t// Extracting bibtex file content.\n\t \t$.get(BIBTEXT_FILE_URL, completionFunction);\n\t }",
"function read_text_file_data(file) {\n var rawFile = new XMLHttpRequest();\n rawFile.open(\"GET\", file, false);\n rawFile.onreadystatechange = function() {\n if (rawFile.readyState === 4) {\n if (rawFile.status === 200 || rawFile.status == 0) {\n raw_text_file_data = rawFile.responseText;\n }\n }\n }\n rawFile.send(null);\n}",
"function uploadFile(event){\n var input = event.target;\n var reader = new FileReader();\n reader.onload = function (){\n cur_ns.descriptor = jsyaml.safeLoad(reader.result);\n editor.setValue(cur_ns.descriptor);\n };\n reader.readAsText(input.files[0]);\n}",
"function readbook(book) {\n var lev = book.arg;\n var i, tmp;\n if (lev <= 3)\n i = rund((tmp = splev[lev]) ? tmp : 1);\n else\n i = rnd((tmp = splev[lev] - 9) ? tmp : 1) + 9;\n learnSpell(spelcode[i]);\n updateLog(`Spell \\'<b>${spelcode[i]}</b>\\': ${spelname[i]}`);\n updateLog(` ${speldescript[i]}`);\n if (rnd(10) == 4) {\n updateLog(` Your intelligence went up by one!`);\n player.setIntelligence(player.INTELLIGENCE + 1);\n }\n}",
"importFromBookmarksFile() {}",
"function getWords() {\n fs.readFile(\"./words.txt\", \"utf8\", function(error, data) {\n if (error) {\n console.log(error);\n } else {\n var wordArray = data.split(\"\\n\");\n // do something after creating wordArray\n pickWord(wordArray);\n }\n })\n}",
"async loadFile() {\n let file = this.state.newFile\n if (file) {\n let currentTree = '#'\n B4ATreeActions.addFilesOnTree(file, currentTree)\n await this.setState({ newFile: '' })\n this.handleTreeChanges()\n }\n }",
"function loadWords() {\n var words = new PS.VectorWords();\n\n // Load wordList into VectorWords object\n wordList.forEach(function (wordPair) {\n words.push_back(wordPair);\n });\n\n if (recognizer.addWords(words) != PS.ReturnType.SUCCESS) {\n // Probably bad format used for pronunciation\n console.log('Error while adding words');\n }\n \n words.delete()\n}",
"function handleReaderLoadEnd(evt) {\n // update the editor with the files content\n editor.getSession().setValue(evt.target.result);\n}",
"async function addToRecentDocuments(filepath) {\n try {\n await docList.addFileToDocList(filepath);\n await docList.setOpened(filepath);\n app.addRecentDocument(filepath);\n } catch (err) {\n await dialog.showMessageBox(\n errorAlert(\n \"Recent Documents Error\",\n `Couldn't add ${filepath} to recent documents list`,\n err\n )\n );\n return;\n }\n}",
"importLibrary(file) {\n const controller = this;\n this.persistenceController.loadLibraryFromFile(file, function (lib) {\n if (lib != null) {\n if (controller.addLibrary(lib) == null) {\n InfoDialog.showDialog('Can\\'t import this library: a library with this name already exists!');\n }\n }\n else {\n InfoDialog.showDialog('Can\\'t import this library: invalid file content!');\n }\n });\n }",
"function importStyles()\r{\r var myDocumentsFolder = Folder.myDocuments.fullName;\r var stylesFilePath = myDocumentsFolder + \"/BIP/lessonStyles.indd\";\r $.writeln(\"loading styles from: \" + stylesFilePath);\r docData.xmlDocument.importStyles(ImportFormat.textStylesFormat, File(stylesFilePath), GlobalClashResolutionStrategy.loadAllWithOverwrite);\r}",
"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 readAndParseFile (file)\n{\n\tvar whichFile = doActionEx\t('DATA_READFILE',file, 'FileName', file,'ObjectName',gPRIVATE_SITE, \n\t\t\t\t\t\t\t\t'FileType', 'txt');\n\treturn (doActionEx('PAR_PARSE_BUFFER','Result', 'document', whichFile));\n}",
"function getFile(event) {\n\tconst input = event.target\n if ('files' in input && input.files.length > 0) {\n\t placeFileContent(\n document.getElementById('text-area-one'),\n input.files[0])\n }\n}",
"loadCodebook (callback) {\n console.debug('Reading codebook')\n this.initCodebookStructure(() => {\n this.initCodebookContent(callback)\n })\n }",
"function parseBigFile() {\n console.log(\"parse big file\");\n fs.readFile(__dirname + '/data/Song_List_by_Artist-NEW.rtf', 'utf8', function (err, data) {\n if (err) {\n console.log('error: ' + err);\n }\n let rtfParser = new RTFParser(data, standardIgnoreList);\n\n rtfParser.parse(function (result) {\n assert.equal(31311, result.length);\n });\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add read button for book | function readButton(li, book) {
let button = document.createElement('button');
button.setAttribute('id', 'read-' + book.title);
button.textContent = 'Read/Unread'
button.addEventListener('click', (e) => {
book.toggleRead();
appendBooks(library);
})
li.appendChild(button);
} | [
"function haveIRead () {\n //console.log('haveIRead ran');\n if(haveRead === false){\n haveRead = true;\n truRead.classList.add('clicked-button');\n //console.log(haveRead);\n } else if (haveRead === true) {\n haveRead = false;\n truRead.classList.remove('clicked-button');\n //console.log(haveRead);\n } else {\n console.log('Something messed up at the haveIRead function');\n }\n }",
"function changeReadStatus(bookTitle, newValue) {\n\tfor (var book in myLibrary) {\n\t\tif (myLibrary[book].title === bookTitle) {\n\t\t\tmyLibrary[book].read = newValue;\n\t\t\tbreak;\n\t\t}\n\t}\n}",
"function Load_Book_File(evt)\n{\n if(evt.target.files[0]) //if the file is available\n {\n var reader = new FileReader(); //create new reader file\n reader.readAsText(evt.target.files[0]); //get file\n reader.onload = function(e) //wait for the file to load\n {\n book_text = reader.result; //store the result\n\t\t\tEnable_Word_Count_Button(); //check if the Word Count button can be enabled\n };\n }\n}",
"static changeReadStatus(target) {\n if (target.classList.contains('read-btn')) {\n target.textContent === 'yes'\n ? (target.textContent = 'no')\n : (target.textContent = 'yes');\n // Success message\n UI.alertMessage('Read status changed', 'success');\n } else {\n return;\n }\n }",
"function ReadingList()\n{\n\n var book={};\n\n book.read = 0;\n book.unread = 0;\n book.toRead = [];\n book.currentRead = undefined;\n book.readBooks = [];\n book.addBook = addBook;\n book.finishCurrentBook = finishCurrentBook;\n return book;\n }",
"function addShowBookListener() {\n document.addEventListener('click', (event) => {\n if(event.target.className === 'book'){\n const bookId = parseInt(event.target.dataset.id);\n fetchSingleBook(bookId);\n }\n });\n}",
"function onReadLessClick() {\n $('#show-this-on-click').slideUp();\n $('.readless').hide();\n $('.readmore').show();\n }",
"get read_item(){\n\t\treturn this.Item.read\n\t}",
"function ReadingList(){\n var read = 0, unRead = 0, toRead = [], currentBook, readBooks = [];\n return{\n read : read,\n unRead : unRead,\n toRead : toRead,\n currentBook : currentBook,\n readBooks : readBooks,\n addBook : addBook,\n finishCurrentBook : finishCurrentBook\n }\n}",
"function _renderBook(book) {\n\t\tbook.render(booksGrid);\n\t\t\n\t\t// Needs to bind the delete event after the buttons are appended to the DOM\n\t\tdeleteButton = document.querySelector('.btn-delete');\n\t\tdeleteButton.addEventListener('click', deleteBook);\n\t}",
"function displayBook(){\n document.getElementById(\"reviews\").innerHTML = \"\";\n document.getElementById(\"singlebook\").style.display = \"block\";\n document.getElementById(\"allbooks\").innerHTML = \"\";\n getInfo(this.id);\n getDescription(this.id);\n getReviews(this.id);\n }",
"function renderBooks(books) {\n books.forEach(book => {\n listOfBooks.innerHTML += appendBookTitles(book)\n })\n //3.click on a book and be able to see thumbnail, and desc and list of users who liked book\n let listContainer = document.querySelector('#list-panel')\n listContainer.addEventListener('click', (event) => {\n if (event.target.tagName === \"LI\") {\n }\n })\n}",
"function readbook(book) {\n var lev = book.arg;\n var i, tmp;\n if (lev <= 3)\n i = rund((tmp = splev[lev]) ? tmp : 1);\n else\n i = rnd((tmp = splev[lev] - 9) ? tmp : 1) + 9;\n learnSpell(spelcode[i]);\n updateLog(`Spell \\'<b>${spelcode[i]}</b>\\': ${spelname[i]}`);\n updateLog(` ${speldescript[i]}`);\n if (rnd(10) == 4) {\n updateLog(` Your intelligence went up by one!`);\n player.setIntelligence(player.INTELLIGENCE + 1);\n }\n}",
"function showBookShelf() {}",
"function onReadMoreClick() {\n $('#show-this-on-click').slideDown();\n $('.readless').show();\n $('.readmore').hide(); \n }",
"function getBookInfo(e) {\n\te.preventDefault();\n\n\t// Get correct book\n\tconst bookId = parseInt(document.querySelector('#bookInfoId').value)\n\tconst book = libraryBooks[bookId]\n\n\t// Call displayBookInfo()\n\tdisplayBookInfo(book)\n\n}",
"function showBook(book, div) {\n console.log(\"showBook()\", book);\n\n // find the book detail element\n const bookDetail = document.getElementById(\"book-detail\");\n\n // populate the template with the data in the provided book\n bookDetail.getElementsByClassName(\"title\")[0].innerText = book.fields.title; //\n bookDetail.getElementsByClassName(\"description\")[0].innerText =\n book.fields.description;\n bookDetail.getElementsByClassName(\"more\")[0].href = book.fields.more;\n bookDetail.getElementsByClassName(\"cover-image\")[0].src =\n book.fields.cover_image[0].url;\n\n // remove the .active class from any book spines that have it...\n const shelf = document.getElementById(\"shelf\");\n const bookSpines = shelf.getElementsByClassName(\"active\");\n for (const bookSpine of bookSpines) {\n bookSpine.classList.remove(\"active\");\n }\n // ...and set it on the one just clicked\n div.classList.add(\"active\");\n\n // reveal the detail element, we only really need this the first time\n // but its not hurting to do it more than once\n bookDetail.classList.remove(\"hidden\");\n}",
"function editBookCard(b) {\n form.start(false, ID);\n }",
"function read(){\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a serialized copy of the exported visual model | exportSerializedVisualModel() {
let iv = this.i.ea();
return (iv);
} | [
"static save_both (comp) {\n if (comp.object3D) {\n const kid = comp.object3D\n kid.isVisible = true\n const kids = kid.getChildren()\n for (let i = 0; i < kids.length; i++) {\n kids[i].setEnabled(true)\n }\n kids[kids.length - 1].isVisible = false\n\n var myser = BABYLON.SceneSerializer.SerializeMesh(comp.object3D, false, true)\n var jsonData = JSON.stringify(myser)\n\n // Component.doDownload('part.babylon', new Blob([jsonData], { type: 'octet/stream' }))\n return [new Blob([jsonData], { type: 'octet/stream' }), new Blob([jsonData], { type: 'octet/stream' })]\n }\n }",
"SaveMe(graphComponent) {\n // get cytoscape instance\n let cy = graphComponent.getCytoGraph();\n \n const content = {\n nodes: cy.elements(\"node\"),\n edges: cy.elements(\"edge\"),\n minZoom: cy.data(\"minZoom\"),\n\n toString() {\n let Output = \" \";\n for (let i = 0; i < this.nodes.length; i++) {\n Output +=\n this.nodes[i].data(\"name\") +\n \", position: x:\" +\n this.nodes[i].position(\"x\") +\n \", y: \" +\n this.nodes[i].position(\"y\") +\n \" \";\n }\n Output += \", edges: \";\n for (let i = 0; i < this.edges.length; i++) {\n Output += this.edges[i].data(\"name\") + \" \";\n }\n return Output;\n },\n\n freezeEverything() {\n for (let i = 0; i < this.nodes.length; i++) {\n Object.freeze(this.nodes[i]);\n }\n for (let i = 0; i < this.edges.length; i++) {\n Object.freeze(this.edges[i]);\n }\n }\n };\n content.freezeEverything();\n Object.freeze(content);\n return content;\n }",
"saveNetworkToJson(){\n\n // Networksettings into json object\n const networkSetting = this.client.NN.getNetworkSettings();\n // networkSetting['LossChoice'] = ElementHandler.getElementValFromId(\"lossChoice\");\n // networkSetting['OptimizerChoice'] = ElementHandler.getElementValFromId(\"optimizerChoice\");\n // networkSetting['LearningRate'] = ElementHandler.getElementValFromId(\"learningRate\");\n\n // Create blob from dict\n const jsonFile = JSON.stringify(networkSetting, null, 1);\n const blob = new Blob(\n [ jsonFile ],\n {\n type: \"application/json\"\n }\n );\n const downloadUrl = URL.createObjectURL(blob);\n\n // Get filename and set attr.\n const filename = ElementHandler.getElementValFromId(\"jsonFileName\") + \".json\";\n ElementHandler.setAttrById(\"hrefNetworkModal\", \"download\", filename);\n ElementHandler.setAttrById(\"hrefNetworkModal\", \"href\", downloadUrl);\n\n this.hide();\n }",
"saveToJSON () {\n\t\tlet digimonJSON = JSON.stringify(this);\n\n\t\treturn digimonJSON;\n\t}",
"_serialize() {\n return JSON.stringify([\n this._id,\n this._label,\n this._properties\n ]);\n }",
"function saveDiagram()\n {\n\n var root = {};\n var xmlSection1 = [];\n var xmlSection2 = [];\n var xmlSection = [];\n var elements = [];\n var connects = [];\n var orders = [];\n\n for (var i in formatting)\n { // save the formatting values\n var item = formatting[i];\n connects.push(\n {\n \"chevronId\": item.chevronId,\n \"X\": item.positionX,\n \"Y\": item.positionY\n });\n }\n for (var i in specializations)\n { // save element flow\n var item = specializations[i];\n orders.push(\n {\n \"sourceId\": item.id,\n \"targetId\": item.successorId\n });\n }\n for (var i in chevrons)\n { // save element details\n var item = chevrons[i];\n\n elements.push(\n {\n\n \"chevronId\": item.chevronId,\n \"chevronName\": item.chevronName,\n \"associatedAsset\": item.processModel\n });\n }\n xmlSection1.push(\n {\n mainProcess: mainProcessName,\n element: elements,\n flow: orders\n });\n xmlSection2.push(\n {\n format: connects\n });\n xmlSection.push(\n {\n chevrons: xmlSection1,\n styles: xmlSection2\n });\n root.xmlSection = xmlSection;\n var savedCanvas = JSON.stringify(root);\n\n var x2js = new X2JS();\n var strAsXml = x2js.json2xml_str(savedCanvas); // convert to xml\n \n\n //ajax call to save value in api\n $.ajax(\n {\n type: \"POST\",\n url: \"/publisher/asts/chevron/apis/chevronxml\",\n data:\n {\n content: strAsXml,\n name: mainProcessName,\n type: \"POST\"\n }\n })\n\n .done(function(result)\n {\n \n });\n\n }",
"toOBJ() {\n let f;\n let v;\n let objstr=\"#Produced by polyHédronisme http://levskaya.github.com/polyhedronisme\\n\";\n objstr+=`group ${this.name}\\n`;\n objstr+=\"#vertices\\n\";\n for (v of this.vertices) {\n objstr += `v ${v[0]} ${v[1]} ${v[2]}\\n`;\n }\n objstr += \"#normal vector defs \\n\";\n for (f of this.faces) {\n const norm = normal(f.map(v=>this.vertices[v]))\n objstr += `vn ${norm[0]} ${norm[1]} ${norm[2]}\\n`;\n }\n objstr += \"#face defs \\n\";\n for (let i = 0; i < this.faces.length; i++) {\n f = this.faces[i];\n objstr += \"f \";\n for (v of f) {\n objstr += `${v+1}//${i+1} `;\n }\n objstr += \"\\n\";\n }\n return objstr;\n }",
"function getImageJSON(){\n var elem = document.getElementById('canvasJSON');\n elem.value = stage.toJSON();\n}",
"function saveToFile(){\n var params = new FocusModel;\n params.saveCurrent();\n var modeltype = $(\"#themodeltype\").val();\n var thejson = JSON.stringify(params);\n var theblob = new Blob([thejson], {type: \"application/json\"}); // reinforces the idea that this is json data (not just text to mess around with)\n// var theblob = new Blob([thejson], {type: \"text/plain\"}); // easier to open and edit, perhaps: but use the web page to edit a setup...\n\n var saveAs = window.saveAs;\n saveAs(theblob, \"focusmodel_\"+modeltype+\".json\");\n}",
"function saveDesign(){\n\n var temp = { //this is common for all modules\n A: _this.A_slider.value()\n ,B: _this.B_slider.value()\n ,C: _this.C_slider.value()\n ,D: _this.D_slider.value()\n ,E: _this.E_slider.value()\n ,gearSize: _this.currentGearSize //number 1~4\n ,gearSize_R: _this.currentGearSize_R //R gear number 1~4\n ,servoAngle: _this.currentServoAngle //1:180, 2:cont\n ,mirroring: _this.currentPairing// True/False\n ,linekedTo: 'none'\n }\n\n switch (_this.currentModule) { //module specific informaion\n case 1: //OpenClose\n temp.module = 1\n break;\n case 3: //Flapping\n temp.module = 3 // <-- this is for user to see from mysketch\n temp.F = _this.F_slider.value()\n temp.X = _this.X_slider.value()\n temp.Y = _this.Y_slider.value()\n\n temp.driveGear = _this.currentDrivingGear\n break;\n case 5: //Walking\n temp.module = 5\n temp.F = _this.F_slider.value()\n temp.G = _this.G_slider.value()\n break;\n case 7: //planet\n temp.module = 7\n break;\n default:\n } // end of switch - case\n\n _this.mySavedSketch.push(temp)\n\n if(temp.module != 0){\n _this.selectParent.forEach(function(sel){\n if(temp.module == 5) //walking cannot be linked to any\n return\n var ii = _this.mySavedSketch.length-1\n sel.option('Module '+ ii)\n });\n }\n }",
"function getSerializedViewState() {\n var jsonViewState = \"\";\n\n var viewState = jQuery(document).data(kradVariables.VIEW_STATE);\n if (!jQuery.isEmptyObject(viewState)) {\n var jsonViewState = jQuery.toJSON(viewState);\n\n // change double quotes to single because escaping causes problems on URL\n jsonViewState = jsonViewState.replace(/\"/g, \"'\");\n }\n\n return jsonViewState;\n}",
"function exportPngClick() {\n const filename = Data.IsSavedDiagram ?\n Data.SavedDiagramTitle :\n decodeURIComponent(Data.Filename);\n\n const svgXml = getSvgXml();\n const background = window.getComputedStyle(document.body).backgroundColor;\n exportPng(filename + '.png', svgXml, background);\n}",
"function recExport(rect) {\n return [rect.totext, rect.program, rect.height, 'Rectangle', rect.layer];\n}",
"function exportSvgClick() {\n const filename = Data.IsSavedDiagram ?\n Data.SavedDiagramTitle :\n decodeURIComponent(Data.Filename);\n\n const svgXml = getSvgXml();\n exportSvg(filename + '.svg', svgXml);\n}",
"function loadSavedDiagram() {\n if (!window.location.hash || window.location.hash.length <= 2) {\n showModalDialog('Missing saved diagram details',\n false, undefined,\n 'OK', Data.IsComparing ? undefined : backOrHome);\n\n return false;\n }\n\n // Trim '#*' and '/compare'\n if (Data.IsComparing) {\n Data.Filename = window.location.hash.slice(2, -8);\n } else {\n Data.Filename = window.location.hash.substring(2);\n }\n\n const json = localStorage.getItem(Data.Filename);\n if (!json) {\n showModalDialog('Failed to locate saved diagram',\n false, undefined,\n 'OK', Data.IsComparing ? undefined : backOrHome);\n\n return false;\n }\n\n const data = JSON.parse(json);\n if (!data || !data.SvgXml) {\n showModalDialog('Failed to process saved diagram data',\n false, undefined,\n 'OK', Data.IsComparing ? undefined : backOrHome);\n\n return false;\n }\n\n Data.SavedDiagramTitle = data.Title;\n document.title = `Saved Diagram: ${data.Title} | M365 Maps`;\n\n const svgXml = data.SvgXml.\n replace(/<!--.*-->/i, '').\n replace(/<\\?xml.*\\?>/i, '').\n replace(/<!doctype.*>/i, '').\n replace(/^[\\n\\r]+/, '');\n\n Data.Svg.Node = createElementFromHtml(svgXml);\n document.body.appendChild(Data.Svg.Node);\n\n return true;\n}",
"function exportCharms(){\n let expString = JSON.stringify(charmList);\n let box = document.getElementById(\"export\");\n box.textContent = expString;\n}",
"function exportAllCustomData() {\n let customDataObject = {\n cR: customRecipes,\n cI: customIngredients,\n sL: shoppingList,\n p: pantry,\n }\n download(\"menusmith.backup\", JSON.stringify(customDataObject));\n}",
"function SaveCurLayerset(){\n var lySetCur = docRef.activeLayer;\n var isLayer = lySetCur.typename == \"ArtLayer\"? true: false;\n var diagName = \"输出目录:当前选择的是 \" + (isLayer? \"层\": \"组\"); //FIXME: not displayed on windows\n var DirSaved = Folder.selectDialog(diagName); // using \"var path\" get wrong directory\n \n if(DirSaved == null)return;\n var file; //file name saved\n if(isLayer){ \n file = new File(DirSaved + \"/50.jpg\");\n ExportLayer(lySetCur, file);\n }else{\n var lysCount = lySetCur.artLayers.length\n for (var i = 0; i < lysCount; i++) {\n var lyCur = lySetCur.artLayers[i];\n //* layers order: from top to bottom; output order: from bottom to top\n var invertIndex = lysCount-i-1; \n var fileName = (invertIndex==4) ? 15: invertIndex + 1; //1, 2, 3, 4, 15\n file = new File(DirSaved + \"/\" + fileName + \".jpg\");\n ExportLayer(lyCur, file);\n }\n }\n\n alert(\"主人,我已经把图片都导出去了!\");\n}",
"function getSvgXml() {\n return new XMLSerializer().serializeToString(Data.Svg.Node);\n}",
"save() {\n for (let id in this.windows_) {\n let elem = this.windows_[id];\n let name = elem.id;\n saveConfig(name+\"-visible\", elem.check.checked);\n saveConfig(name+\"-width\", elem.style.width);\n saveConfig(name+\"-height\", elem.style.height);\n saveConfig(name+\"-top\", elem.style.top);\n saveConfig(name+\"-left\", elem.style.left);\n saveConfig(name+\"-canvas-width\", elem.obj.width);\n saveConfig(name+\"-canvas-height\", elem.obj.height);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function responsible for initialising connection with Ethereum blockchain If it fails to initialise web3 component, other functions will not work properly | async function initialiseBlockchainConnection() {
web3 = window.web3;
if (typeof web3 !== 'undefined') {
console.log('Web3 Detected! ' + web3.currentProvider.constructor.name);
window.web3 = new Web3(web3.currentProvider);
} else {
infuraAPIKey = 'Infurakey';
console.log('No Web3 Detected... using HTTP Provider');
window.web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/" + infuraAPIKey));
}
if (typeof web3 == 'undefined') {
console.log('web3 undefined');
}
} | [
"init() {\n // TODO: Move these constants to a global constants file\n const APP_NAME = 'DHBW Bachelors Night Ticketing 2020'\n const APP_LOGO_URL = 'https://einfachtierisch.de/media/cache/article_teaser/cms/2015/09/Katze-lacht-in-die-Kamera-shutterstock-Foonia-76562038.jpg?595617'\n const ETH_JSONRPC_URL = 'https://mainnet.infura.io/v3/efaece4f5f4443979063839c124c8171' // Mainnet\n const CHAIN_ID = 1\n\n this.setState({ walletAvailable: window.ethereum ? true : false });\n\n if (!window.ethereum) {\n\n // Initialize WalletLink\n this.walletLink = new WalletLink({\n appName: APP_NAME,\n appLogoUrl: APP_LOGO_URL,\n darkMode: false\n })\n\n // Initialize a Web3 Provider object\n window.ethereum = this.walletLink.makeWeb3Provider(ETH_JSONRPC_URL, CHAIN_ID);\n }\n\n // Checking if wallet is already connected or not\n // eslint-disable-next-line\n this.setState({ connected: window.ethereum.selectedAddress ? true : false });\n\n // Creating Web3 Instance\n this.web3 = new Web3(window.ethereum);\n }",
"function Ethereum() {\n this.web3; // Web3 object used by library\n this.gasAdjust = 0; // Deploy and exec gas estimate adjustments\n\n this.connectionType;\n\n /** Account index used for transactions */\n this.accountIndex = 0;\n\n /** Account to use for transactions */\n this.account;\n\n /** Default options */\n this.options = {\n /** Default transaction options */\n from: undefined,\n to: undefined,\n value: undefined,\n gas: 0,\n gasPrice: undefined,\n gasLimit: undefined,\n data: undefined,\n nonce: undefined,\n\n /** Default delib options*/\n accountIndex: undefined,\n maxGas: undefined\n };\n\n /** Paths to contract related folders */\n this.paths = paths;\n\n this.addresses = addresses;\n\n this._presetAdded = false;\n\n /**\n *\n * @param {string} rpcPath\n * @returns {Web3}\n */\n this.init = (rpcPath) => {\n if (this.connectionType === 'rpc') {\n return this.web3;\n } else if (this.web3) {\n this.web3.setProvider(new Web3.providers.HttpProvider(config.rpc.rpcPath));\n this.connectionType = 'rpc';\n return this.web3;\n } else {\n this.web3 = init(rpcPath);\n this.connectionType = 'rpc';\n\n if (this._presetAdded === false) {\n this._addPresetAccounts();\n this._presetAdded = true;\n }\n\n return this.web3;\n }\n };\n\n /**\n *\n * @param {string} ipcPath\n * @returns {Web3}\n */\n this.initIPC = (ipcPath) => {\n if (this.connectionType === 'ipc') {\n return this.web3;\n } else if (this.web3) {\n this.web3.setProvider(new Web3.providers.IpcProvider(config.ipc.ipcPath, net));\n this.connectionType = 'ipc';\n return this.web3;\n } else {\n this.web3 = initIPC(ipcPath);\n this.connectionType = 'ipc';\n\n if (this._presetAdded === false) {\n this._addPresetAccounts();\n this._presetAdded = true;\n }\n\n return this.web3;\n }\n };\n\n /**\n *\n * @param {string} wsPath\n * @returns {Web3}\n */\n this.initws = (wsPath) => {\n if (this.connectionType === 'ws') {\n return this.web3;\n\n } else if (this.web3) {\n this.web3.setProvider(new Web3.providers.WebsocketProvider(config.ws.wsPath));\n this.connectionType = 'ws';\n return this.web3;\n\n } else {\n this.web3 = initws(wsPath);\n this.connectionType = 'ws';\n\n if (this._presetAdded === false) {\n this._addPresetAccounts();\n this._presetAdded = true;\n }\n\n return this.web3;\n }\n };\n\n /**\n *\n */\n this.closeWSConnection = () => {\n this.web3.currentProvider.connection.close();\n };\n\n /**\n *\n * @param {string} privateKey\n * @returns {Object}\n */\n this.addAccount = (privateKeyOrMnemonic) => {\n this._checkConnectionError();\n return promisify(callback => {\n let key;\n if (privateKeyOrMnemonic.indexOf(' ') === -1) {\n key = this.web3.eth.accounts.wallet.add(privateKeyOrMnemonic);\n } else {\n const wallet = ethers.Wallet.fromMnemonic(privateKeyOrMnemonic);\n const privateKey = wallet.privateKey;\n key = this.web3.eth.accounts.wallet.add(privateKey);\n }\n\n this.getAccounts()\n .then(accounts => {\n const indexOf = accounts.indexOf(key.address);\n key['index'] = indexOf;\n callback(null, key);\n })\n .catch(err => {\n callback(err, null);\n })\n })()\n }\n\n /**\n *\n * @returns {Array}\n */\n this.getAccounts = () => {\n this._checkConnectionError();\n return promisify(callback => {\n const allAccounts = [];\n this.web3.eth.getAccounts()\n .then(accounts1 => {\n for (let i = 0; i < accounts1.length; i++) {\n allAccounts.push(accounts1[i]);\n }\n const accounts2 = this.web3.eth.accounts.wallet;\n\n for (let i = 0; i < accounts2.length; i++) {\n allAccounts.push(accounts2[i].address);\n }\n\n callback(null, allAccounts)\n })\n .catch(err => {\n callback(err, null);\n })\n })();\n }\n\n /**\n * Change web3 provider.\n * @param {string} path\n * @param {string} type\n * @returns {Web3}\n */\n this.changeProvider = (type, path) => {\n this._checkConnectionError();\n if (this.web3) {\n if (type === 'rpc') {\n path = path || config.rpc.rpcPath;\n this.web3.setProvider(new Web3.providers.HttpProvider(path));\n } else if (type === 'ipc') {\n path = path || config.ipc.host;\n this.web3.setProvider(new Web3.providers.IpcProvider(path, net));\n } else if (type === 'ws') {\n path = path || config.ws.wsPath;\n this.web3.setProvider(new Web3.providers.WebsocketProvider(path));\n }\n return this.web3;\n }\n }\n\n /**\n * Builds Solidity contracts.\n * @param {array} contractFiles\n * @param {string} contractPath\n * @param {string} buildPath\n * @returns {Promise}\n */\n this.build = (contractFiles, contractPath, buildPath) => {\n contractPath = (contractPath) ? path.join(__dirname, RELATIVE_PATH, contractPath) : path.join(__dirname, RELATIVE_PATH, this.paths.contract);\n buildPath = (buildPath) ? path.join(__dirname, RELATIVE_PATH, buildPath) : path.join(__dirname, RELATIVE_PATH, this.paths.built);\n return build(contractFiles, contractPath, buildPath);\n };\n\n /**\n * Builds Solidity contracts.\n * @param {array} contractFiles\n * @param {string} contractPath\n * @param {string} buildPath\n * @returns {Promise}\n */\n this.compile = (contractFiles, contractPath, buildPath) => {\n contractPath = (contractPath) ? path.join(__dirname, RELATIVE_PATH, contractPath) : path.join(__dirname, RELATIVE_PATH, this.paths.contract);\n buildPath = (buildPath) ? path.join(__dirname, RELATIVE_PATH, buildPath) : path.join(__dirname, RELATIVE_PATH, this.paths.built);\n return build(contractFiles, contractPath, buildPath);\n };\n\n /**\n *\n * @param {string} contractName\n * @returns {Contract}\n */\n this._builtContractDeployment = (contractName) => {\n const builtPath = path.join(config.projectRoot, this.paths.built, contractName + '.json');\n if (!pathExists(builtPath)) {\n var e = new Error(' \\'' + contractName + '\\' is not a valid built contract at:', builtPath);\n throw e;\n }\n\n const contractJSONPath = path.resolve(path.join(config.projectRoot, this.paths.built, contractName + '.json'));\n\n let contract;\n try {\n const contractJSONString = fs.readFileSync(contractJSONPath);\n const contractInfo = JSON.parse(contractJSONString);\n contract = new this.web3.eth.Contract(contractInfo.abi);\n } catch (e) {\n throw e;\n }\n return contract;\n };\n\n this._builtContractExec = (contractName, address) => {\n const contractJSONPath = path.resolve(path.join(config.projectRoot, this.paths.built, contractName + '.json'));\n let contract;\n try {\n const contractJSONString = fs.readFileSync(contractJSONPath);\n const contractInfo = JSON.parse(contractJSONString);\n contract = new this.web3.eth.Contract(contractInfo.abi, address);\n } catch (e) {\n throw e;\n }\n return contract;\n }\n\n this.getContractInfo = (contractName) => {\n const contractJSONPath = path.resolve(path.join(config.projectRoot, this.paths.built, contractName + '.json'));\n\n let contractInfo;\n try {\n const contractJSONString = fs.readFileSync(contractJSONPath);\n contractInfo = JSON.parse(contractJSONString);\n } catch (e) {\n throw e;\n }\n return contractInfo;\n };\n\n this._getByteCode = (contractName) => {\n const contractJSONPath = path.resolve(path.join(config.projectRoot, this.paths.built, contractName + '.json'));\n const contractJSONString = fs.readFileSync(contractJSONPath);\n const contractInfo = JSON.parse(contractJSONString);\n return contractInfo.bytecode;\n }\n\n /**\n * Deploy a built contract.\n * @param {string or number} accountOrIndex\n * @return {Number}\n */\n this.balanceOf = (accountOrIndex) => {\n this._checkConnectionError();\n\n return promisify(callback => {\n this.getAccounts()\n .then(accounts => {\n let address\n if (!accountOrIndex) {\n address = this.account || accounts[this.accountIndex];\n } else {\n if (typeof(accountOrIndex) === 'number') {\n address = accounts[accountOrIndex];\n } else {\n address = accountOrIndex;\n }\n }\n return this.web3.eth.getBalance(address);\n })\n .then(res => {\n callback(null, res);\n })\n .catch(err => {\n callback(err, null);\n })\n })();\n }\n\n /**\n * Deploy a built contract.\n * @param {string} toAccount\n * @param {Number} value\n * @param {Object} options\n * @return {Object}\n */\n this.transfer = (toAccount, value, options) => {\n this._checkConnectionError();\n\n options = this._optionsUtil(this.options, options);\n\n return promisify(callback => {\n this.getAccounts()\n .then(accounts => {\n options.to = toAccount || options.to;\n options.value = value || options.value;\n options.from = options.from || accounts[options.accountIndex] || this.account || accounts[this.accountIndex];\n\n if (!options.gas) {\n this.web3.eth.estimateGas(options)\n .then(gasEstimate => {\n return this.web3.eth.sendTransaction(options);\n })\n .then(tx => {\n callback(null, tx);\n })\n .catch(err => {\n callback(err, null);\n })\n }\n\n return this.web3.eth.sendTransaction(options);\n })\n .then(tx => {\n callback(null, tx);\n })\n .catch(err => {\n callback(err, null);\n });\n })();\n }\n\n /**\n *\n * @return {Array}\n */\n this._addPresetAccounts = () => {\n this._checkConnectionError();\n\n if (config.accounts.length === 0) return;\n else {\n const privateKeyAndMnemonicArr = config.accounts;\n const keys = [];\n for (let i = 0; i < privateKeyAndMnemonicArr.length; i++) {\n const key = this.addAccount(privateKeyAndMnemonicArr[i]);\n keys.push(key);\n }\n return keys;\n }\n }\n\n /**\n * Creates an Ethereum account and returns an account object\n * @param {string} entropy\n * @return {Object}\n */\n this.createAccount = (entropy) => {\n this._checkConnectionError();\n let key;\n return promisify(callback => {\n let account;\n this.getAccounts()\n .then(accounts => {\n return this.web3.eth.accounts.create(entropy);\n })\n .then(createdAccount => {\n account = createdAccount;\n return this.addAccount(account.privateKey);\n })\n .then(returnedKey => {\n key = returnedKey;\n return this.getAccounts()\n })\n .then(accounts => {\n const indexOf = accounts.indexOf(key.address);\n key['index'] = indexOf;\n callback(null, key);\n })\n .catch(err => {\n callback(err, null);\n });\n })();\n\n }\n\n /**\n * Deploy a built contract.\n * @param {string} contractName\n * @param {Array} args\n * @param {Object} options\n * @param {Array} links\n * @return {Promise}\n */\n this.deploy = (contractName, args, options, links) => {\n this._checkConnectionError();\n\n const builtPath = path.join(config.projectRoot, this.paths.built, contractName + '.json');\n if (!pathExists(builtPath)) {\n var e = new Error(contractName + ' is not a valid built contract at: ' + builtPath);\n throw e;\n }\n\n if (args === undefined) args = [];\n args = Array.isArray(args) ? args : [args];\n\n options = this._optionsUtil(this.options, options);\n const contract = this._builtContractDeployment(contractName);\n var self = this;\n\n return promisify(callback => {\n if (options.gas && options.gas > 0) {\n deployInstance(options);\n return;\n }\n // Only estimate gas if options.gas is 0 or null\n options.gas = undefined;\n self.deploy.estimate(contractName, args, options, links)\n .then(gasEstimate => {\n\n options.gas = Math.round(gasEstimate + gasEstimate * self.gasAdjust);\n // Throw error if est gas is greater than max gas\n if (options.maxGas && options.gas > options.maxGas) {\n throw new Error('Gas estimate of ' + options.gas + ' is greater than max gas allowed ' + options.maxGas);\n }\n deployInstance(options);\n })\n .catch(err => {\n callback(err, null);\n });\n\n // Deploys the contract and returns the instance only after its address is saved\n function deployInstance(deployOptions) {\n promisify(self.getAccounts)()\n .then(accounts => {\n deployOptions.from = deployOptions.from || accounts[deployOptions.accountIndex] || self.account || accounts[self.accountIndex];\n let byteCode = self._getByteCode(contractName);\n if (links) {\n byteCode = linker.linkBytecode(byteCode, links);\n }\n\n const data = contract.deploy({data: byteCode, arguments: args}).encodeABI(deployOptions);\n\n const transactionOptions = {\n from: deployOptions.from,\n gas: deployOptions.gas,\n data: data,\n value: deployOptions.value\n };\n return self.web3.eth.sendTransaction(transactionOptions);\n })\n .then(tx => {\n const contractJSONPath = path.resolve(path.join(config.projectRoot, self.paths.built, contractName + '.json'));\n const contractJSONString = fs.readFileSync(contractJSONPath);\n const contractInfo = JSON.parse(contractJSONString);\n\n const contractInstance = new self.web3.eth.Contract(contractInfo.abi, tx.contractAddress);\n self.addresses.set(contractName, tx.contractAddress, links);\n const contractInstanceWithMethods = self.execAt(contractName, tx.contractAddress);\n contractInstanceWithMethods.blockCreated = tx.blockNumber;\n contractInstanceWithMethods.from = tx.from;\n callback(null, contractInstanceWithMethods);\n })\n .catch(err => {\n callback(err, null);\n });\n }\n })();\n };\n\n /**\n * Estimates the gas usage for a deployed contract\n * @param {string} contractName\n * @param {Array} args\n * @param {Object} options\n * @returns {number}\n */\n this.deploy.estimate = (contractName, args, options, links) => {\n this._checkConnectionError();\n\n const builtPath = path.join(config.projectRoot, this.paths.built, contractName + '.json');\n if (!pathExists(builtPath)) {\n var e = new Error(contractName + ' is not a valid built contract at: ' + builtPath);\n throw e;\n }\n\n if (args === undefined) args = [];\n args = Array.isArray(args) ? args : [args];\n options = this._optionsUtil(this.options, options);\n const contract = this._builtContractDeployment(contractName);\n return promisify(callback => {\n promisify(this.getAccounts)()\n .then(accounts => {\n options.from = options.from || accounts[options.accountIndex] || this.account || accounts[this.accountIndex];\n const transactionOptions = Object.assign({}, options);\n transactionOptions.gas = undefined;\n const contractInfo = this.getContractInfo(contractName);\n let byteCode = this._getByteCode(contractName);\n\n var linkReferences = linker.findLinkReferences(byteCode)\n if (links) {\n byteCode = linker.linkBytecode(byteCode, links);\n }\n\n return contract.deploy({data: byteCode, arguments: args}).estimateGas();\n })\n .then(gasEstimate => {\n callback(null, gasEstimate);\n })\n .catch(err => {\n callback(err, null);\n });\n })();\n };\n\n /**\n * Calls a deployed contract\n * @param {string} contractName\n * @return {Contract}\n */\n this.exec = (contractName) => {\n const builtPath = path.join(config.projectRoot, this.paths.built, contractName + '.json');\n if (!pathExists(builtPath)) {\n var e = new Error(contractName + ' is not a valid built contract at: ' + builtPath);\n throw e;\n }\n\n const contractAddress = this.addresses.get(contractName).address;\n return this.execAt(contractName, contractAddress);\n };\n\n /**\n * Calls a deployed contract at a specific address.\n * @param {string} contractName\n * @param {string} contractAddress\n * @return {Contract} Contract\n */\n this.execAt = (contractName, contractAddress) => {\n this._checkConnectionError();\n\n const builtPath = path.join(config.projectRoot, this.paths.built, contractName + '.json');\n if (!pathExists(builtPath)) {\n var e = new Error(' \\'' + contractName + '\\' is not a valid built contract at:', builtPath);\n throw e;\n }\n\n const contract = this._builtContractExec(contractName, contractAddress);\n /** Create mockContract to add new behavior to contract methods */\n\n const mockContract = {};\n mockContract.estimate = {}; // Gas estimate method\n mockContract.call = {}; // Gas estimate method\n\n // Gets all properties in contractInstance. Overwrites all contract methods with new functions and re references all the others.\n for (let key in contract.methods) {\n if (typeof contract.methods[key] === 'function') {\n const methodName = key;\n\n // Re reference the default contract methods with __methodName\n mockContract['__' + key] = contract.methods[methodName];\n\n /** CALL METHOD */\n mockContract.call[methodName] = (...args) => {\n return promisify(callback => {\n const options = argOptions(args);\n\n promisify(this.getAccounts)()\n .then(accounts => {\n options.from = options.from || accounts[options.accountIndex] || this.account || accounts[this.accountIndex];\n return contract.methods[methodName](...args).call(options);\n })\n .then(value => {\n callback(null, value);\n })\n .catch(err => {\n callback(err, null);\n });\n })();\n };\n\n /** GAS ESTIMATE METHOD */\n mockContract.estimate[methodName] = (...args) => {\n return promisify(callback => {\n const options = argOptions(args);\n\n promisify(this.getAccounts)()\n .then(accounts => {\n options.from = options.from || accounts[options.accountIndex] || this.account || accounts[this.accountIndex];\n options.gas = undefined;\n return contract.methods[methodName](...args).estimateGas(options);\n })\n .then(gasEstimate => {\n callback(null, gasEstimate);\n })\n .catch(err => {\n callback(err, null);\n });\n })();\n };\n\n\n /** ACTUAL METHOD */\n mockContract[methodName] = (...args) => {\n return promisify((callback) => {\n const options = argOptions(args);\n\n /** ACTUAL: NO GAS ESTIMATE */\n if (options.gas && options.gas != 0) {\n promisify(this.getAccounts)()\n .then(accounts => {\n options.from = options.from || accounts[options.accountIndex] || this.account || accounts[this.accountIndex];\n\n const data = contract.methods[methodName](...args).encodeABI();\n const transactionOptions = {\n from: options.from,\n to: contractAddress,\n gas: options.gas,\n value: options.value,\n data: data,\n gasLimit: options.gasLimit\n };\n\n return this.web3.eth.sendTransaction(transactionOptions);\n })\n .then(res => {\n callback(null, res);\n })\n .catch(err => {\n callback(err, null);\n });\n return;\n }\n\n /** ACTUAL: WITH GAS ESTIMATE */\n promisify(this.getAccounts)()\n .then(accounts => {\n options.from = options.from || accounts[options.accountIndex] || this.account || accounts[this.accountIndex];\n options.gas = undefined;\n\n // Throw error if est gas is greater than max gas\n if (options.maxGas && options.gas > options.maxGas) {\n throw new Error('Gas estimate of ' + options.gas + ' is greater than max gas allowed ' + options.maxGas);\n }\n\n return contract.methods[methodName](...args).estimateGas(options);\n })\n .then(gasEstimate => {\n const data = contract.methods[methodName](...args).encodeABI();\n const transactionOptions = {\n from: options.from,\n to: contractAddress,\n gas: gasEstimate,\n value: options.value,\n data: data,\n gasLimit: options.gasLimit\n };\n // return contract.methods[methodName](...args).send(options);\n\n return this.web3.eth.sendTransaction(transactionOptions);\n })\n .then(res => {\n callback(null, res);\n })\n .catch(err => {\n callback(err, null);\n });\n })();\n };\n } else {\n // Re references all other properties\n mockContract.method[key] = contract.method[key];\n }\n }\n\n const contractInfo = this.getContractInfo(contractName);\n\n mockContract.abi = contractInfo.abi;\n /** Checks for options based on args */\n const self = this;\n function argOptions(args) {\n let options = self.options;\n if (typeof args[args.length - 1] === 'object' && !Array.isArray(args[args.length - 1])) {\n options = self._optionsUtil(options, args[args.length - 1]);\n args.pop(); // Will chance the arg array passed in\n } else {\n options = self._optionsUtil(options, {});\n }\n return options;\n }\n\n mockContract.address = contractAddress;\n\n return mockContract;\n };\n\n /**\n * Gets the event logs for an event\n * @param {string} contractName\n * @param {string} eventName\n * @param {number} blocksBack\n * @param {Object} filter\n * @return {Promise}\n */\n this.events = (contractName, eventName, blockOptions, filter) => {\n const builtPath = path.join(config.projectRoot, this.paths.built, contractName + '.json');\n if (!pathExists(builtPath)) {\n var e = new Error(contractName + ' is not a valid built contract at: ' + builtPath);\n throw e;\n }\n\n const contractAddress = this.addresses.get(contractName).address;\n return this.eventsAt(contractName, contractAddress, eventName, blockOptions, filter);\n };\n\n /**\n * Gets the event logs for an event at a specific address\n * @param {string} contractName\n * @param {string} contractAddress\n * @param {string} eventName\n * @param {number} blocksBack\n * @param {Object} filter\n * @return {Promise}\n */\n this.eventsAt = (contractName, contractAddress, eventName, blockOptions, filter) => {\n this._checkConnectionError();\n\n const builtPath = path.join(config.projectRoot, this.paths.built, contractName + '.json');\n if (!pathExists(builtPath)) {\n var e = new Error(' \\'' + contractName + '\\' is not a valid built contract at:', builtPath);\n throw e;\n }\n\n const contract = this._builtContractExec(contractName, contractAddress);\n\n // Check to see if valid event\n if (eventName !== 'allEvents' && (typeof contract.events[eventName] !== 'function' ||\n contract.events[eventName].hasOwnProperty('call'))) {\n throw new Error('Invalid event: ' + eventName + ' is not an event of ' + contractName);\n }\n\n return promisify(callback => {\n promisify(this.web3.eth.getBlock)('latest')\n .then(block => {\n blockOptions = blockOptions ? blockOptions : {};\n blockOptions = (blockOptions && typeof blockOptions === 'object') ? blockOptions : {};\n\n blockOptions.fromBlock = blockOptions.fromBlock ? blockOptions.fromBlock : 0;\n blockOptions.toBlock = blockOptions.toBlock ? blockOptions.toBlock : 'latest';\n\n const eventFilter = blockOptions;\n eventFilter.filter = filter;\n\n contract.getPastEvents(eventName, eventFilter)\n .then(res => {\n callback(null, res);\n })\n .catch(err => {\n callback(err, null);\n })\n })\n .catch(err => {\n callback(err, null);\n });\n })();\n };\n\n /**\n * Watch an event\n * @param {string} contractName\n * @param {string} eventName\n * @param {Object} options\n * @param {Function} callback\n * @returns\n */\n this.watch = (contractName, eventName, options, callback) => {\n const builtPath = path.join(config.projectRoot, this.paths.built, contractName + '.json');\n if (!pathExists(builtPath)) {\n var e = new Error(contractName + ' is not a valid built contract at: ' + builtPath);\n throw e;\n }\n\n const contractAddress = this.addresses.get(contractName).address;\n return this.watchAt(contractName, contractAddress, eventName, options, callback);\n };\n\n /**\n * Watch an event at a specific address\n * @param {string} contractName\n * @param {string} contractAddress\n * @param {string} eventName\n * @param {Object} options - Optional. Can replace with callback\n * @param {Function} callback\n * @returns\n */\n this.watchAt = (contractName, contractAddress, eventName, options, callback) => {\n this._checkConnectionError();\n\n // Allow no filter to be passed in\n if (typeof options === 'function' && !callback) {\n callback = options;\n }\n\n const contract = this._builtContractExec(contractName, contractAddress);\n\n // Check to see if valid event\n if (eventName !== 'allEvents' && (typeof contract.events[eventName] !== 'function' ||\n contract.events[eventName].hasOwnProperty('call'))) {\n throw new Error('Invalid event: ' + eventName + ' is not an event of ' + contractName);\n }\n\n options = (options && typeof options === 'object') ? options : {};\n options.address = options.hasOwnProperty('address') ? options.address : contractAddress;\n\n let watchEvents;\n\n this.web3.eth.getBlockNumber()\n .then(blockNumber => {\n blockNumber = options.blockNumber ? options.blockNumber : blockNumber;\n watchEvents = contract.events[eventName]({options: options, fromBlock: blockNumber});\n watchEvents\n .on(\"data\", (event) => {\n callback(null, event);\n })\n .on(\"error\", (err) => {\n callback(err, null);\n })\n })\n .catch(err => {\n throw err;\n })\n\n return {\n stop: function() {\n watchEvents.unsubscribe();\n }\n };\n\n };\n\n /** Performs necessary option adjustments\n * @param {Object} mergeOptions\n * @param {Object} options\n * @returns {Object}\n */\n this._optionsUtil = (mergeOptions, options) => {\n options = Object.assign({}, options);\n options = optionsMerge(mergeOptions, options);\n options = optionsFormat(options);\n options = optionsFilter(options);\n return options;\n };\n\n /**\n * Check the status of a certain connection type and throws error if not connected\n * @param {string} type - The connection type to test the status of. 'rpc', 'ipc'. Defaults to the current provider type.\n */\n this._checkConnectionError = (type) => {\n if (!this.connectionType) {\n throw new Error ('Not connected to any provider.');\n }\n type = type || this.connectionType;\n type = type.toLowerCase();\n };\n\n /**\n * Check the status of the web3 connection\n * @returns {bool} - Whether or not web3 is connected to a provider\n */\n this.isConnected = () => {\n return promisify(callback => {\n this.web3.eth.net.isListening()\n .then(connectionStatus => {\n callback(null, connectionStatus);\n })\n .catch(err => {\n callback(null, err);\n })\n })()\n }\n}",
"async function connect() {\n state.setStartEthereum(false);\n if (typeof window.ethereum !== \"undefined\") {\n const accounts = await ethereum.request({ method: \"eth_requestAccounts\" });\n const provider = await detectEthereumProvider();\n\n console.log(accounts);\n\n const web3 = new Web3(provider);\n state.setWeb3(web3);\n web3.eth.defaultAccount = accounts[0];\n\n initializeContracts(web3);\n startListeners();\n\n state.setEthereumAccounts(accounts);\n state.setEthereumConnected(true);\n } else {\n throw Error(\"Could not find ethereum in window.\");\n }\n }",
"async function initTestRunner(){\n\ttry {\n\t\t// Connect web3 with QTUM network\n\t\tconst web3 = await setupNetwork(JANUS_CONFIG);\n\n\t\t// const fundTestAccountResult = await fundTestAccount();\n\n\t\tconst chainId = 'JANUS'\n\t\tconsole.log(`[INFO] - Web3 is connected to the ${JANUS_CONFIG.name} node. Chain ID: ${chainId}`);\n\t\t\n\t\t// Deploy LinkToken or instantiate previously deployed contract\n\t\tconst LinkToken = await setupContract('LinkToken', JANUS_CONFIG, chainId, web3.currentProvider);\n\t\tconsole.log(`[INFO] - Deployed LinkToken contract address in ${JANUS_CONFIG.name} network is: ${LinkToken.address}`);\n\n\t\t// Deploy Oracle or instantiate previously deployed contract\n\t\tconst Oracle = await setupContract('Oracle', JANUS_CONFIG, chainId, web3.currentProvider);\n\t\tconsole.log(`[INFO] - Deployed Oracle contract address in ${JANUS_CONFIG.name} network is: ${Oracle.address}`);\n\n\t\t// Configure Chainlink node\n\t\tconst chainlinkData = await setupChainlinkNode(Oracle.address);\n\n\t\t// Deploy Consumer or instantiate previously deployed contract\n\t\tconst Consumer = await setupContract('Consumer', JANUS_CONFIG, chainId, web3.currentProvider);\n\t\tconsole.log(`[INFO] - Deployed Consumer contract address in ${JANUS_CONFIG.name} network is: ${Consumer.address}`);\n\t\t\n\t\t//const gasEstimate = await Consumer.requestQTUMPrice.estimateGas({from: process.env.HEX_QTUM_ADDRESS})\n\t\t//console.log(\"estimated gas: \", gasEstimate)\n\t\n\t\tConsumer.requestQTUMPrice({from: process.env.HEX_QTUM_ADDRESS, gas: \"0x4c4b40\", gasPrice: \"0x64\"})\n\t\t.then(function(result){\n\t\t\t// Watch for the RequestFulfilled event of the Consumer contract\n\t\t\tConsumer.RequestFulfilled({\n\t\t\t\t'address': Consumer.address,\n\t\t\t\t'topics': [],\n\t\t\t\t'fromBlock':'latest'\n\t\t\t}, function(error, event){\n\t\t\t\tif (!error){\n\t\t\t\t\tif (event.event == 'RequestFulfilled'){\n\t\t\t\t\t\tConsumer.currentPrice().then(function(price){\n\t\t\t\t\t\t\tconst priceNum = web3.utils.hexToNumber(price);\n\t\t\t\t\t\t\tif (priceNum !== 0){\n\t\t\t\t\t\t\t\tconsole.log('[INFO] - Received QTUM price: ' + (priceNum / 100000000) + ' BTC');\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}else{\n\t\t\t\t\tconsole.log(error);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}catch(e){\n\t\tconsole.error('[ERROR] - Test Runner initialization failed:' + e);\n\t}\n}",
"async _initWeb3(mnemonic) {\n this.setState({\n loading: true,\n });\n\n const facade = new ContractFacade();\n await facade.initialize(mnemonic);\n await this._checkBalance(facade);\n\n this.setState({\n contractFacade: facade,\n mode: Modes.MainScreen,\n loading: false,\n });\n }",
"async loadBlockchainData() {\n let web3\n \n this.setState({loading: true})\n if(typeof window.ethereum !== 'undefined') {\n web3 = new Web3(window.ethereum)\n await this.setState({web3})\n await this.loadAccountData()\n } else {\n let infuraURL = `https://ropsten.infura.io/v3/${process.env.REACT_APP_INFURA_API_KEY}`\n web3 = new Web3(new Web3.providers.HttpProvider(infuraURL))\n await this.setState({web3})\n }\n await this.loadContractData()\n await this.updateHouses()\n this.setState({loading: false})\n }",
"constructor() {\r\n this.web3 = new Web3(\"ws://localhost:7545\");\r\n this.network = 'ganache';\r\n }",
"function EthereumClient(host) {\n\n this.web3 = window.web3 = require('web3');\n this.addresses = {};\n this.filters = {}\n\n this.defaultGas = 1000000;\n\n this.contracts = {};\n _.defaults(this.addresses, constants.addresses);\n\n this.web3.setProvider(new web3.providers.HttpProvider('http://'+host));\n\n // hacking around agressive Augur\n try {\n //Augur = require('augur.js');\n } catch (err) {\n \n }\n}",
"async connectWallet() {\n // Requesting connection to wallet\n var accounts = await window.ethereum.enable().catch(this.displayError);\n if (!accounts) return;\n\n console.log(`User's address is ${accounts[0]}`);\n this.web3.eth.defaultAccount = accounts[0];\n this.setState({ connected: true });\n }",
"async loadBlockchainData(){\n const web3= window.web3\n const accounts= await web3.eth.getAccounts()\n this.setState({account:accounts[0]})\n console.log(\"Account Address: \",this.state.account)\n const networkId=await web3.eth.net.getId()\n // console.log(networkId);\n const networkData= StoreHash.networks[networkId]\n if(networkData){\n const abi= StoreHash.abi\n const address= networkData.address\n // fetch contract\n const contract= web3.eth.Contract(abi, address)\n this.setState({contract:contract})\n console.log(contract)\n // Now call the get() function of the contract to get the stored imageHash\n const imageHash= await contract.methods.get().call()\n console.log(\"imageHash from call: \",imageHash)\n this.setState({imageHash:imageHash}) \n }else{\n window.alert(\"Smart contract not deployed on the network\")\n }\n }",
"async function initialize() {\n const web3 = new Web3(await oracle_1.getWeb3Provider());\n // Get the provider and contracts\n const provider = await initProvider(web3);\n const title = await provider.getTitle();\n if (title.length == 0) {\n console.log(\"Initializing provider\");\n const res = await provider.initiateProvider(oracle_1.ProviderData);\n console.log(res);\n console.log(\"Successfully created oracle\", oracle_1.ProviderData.title);\n for (const spec in oracle_1.Responders) {\n const r = await provider.initiateProviderCurve({\n endpoint: spec,\n term: oracle_1.Responders[spec].curve\n });\n console.log(r);\n console.log(\"Successfully initialized endpoint\", spec);\n }\n }\n console.log(\"Oracle exists. Listening for queries\");\n provider.listenQueries({}, (err, event) => {\n if (err) {\n throw err;\n }\n handleQuery(provider, event, web3);\n });\n}",
"async addChain() {\n const chainId = await this.getCurrentChainNetwork();\n\n if (chainId != process.env.NUXT_ENV_BSC_HEX_ID) {\n try {\n\n if (this.currentProvider == this.metamask) {\n\n // Create BSC network configuration object.\n const chainObject = {\n chainId: process.env.NUXT_ENV_BSC_HEX_ID,\n chainName: process.env.NUXT_ENV_CHAIN_NAME,\n nativeCurrency: {\n name: process.env.NUXT_ENV_TOKEN_NAME,\n symbol: process.env.NUXT_ENV_TOKEN_SYMBOL,\n decimals: 18\n },\n rpcUrls: [process.env.NUXT_ENV_BSC_RPC, 'https://bsc-dataseed.binance.org/', 'https://bsc-dataseed1.binance.org'],\n blockExplorerUrls: [process.env.NUXT_ENV_BLOCKEXPLORER]\n }\n // This method is only available for metamask right now.\n const updatedChainId = await this.currentProvider.request({\n method: 'wallet_addEthereumChain',\n params: [chainObject]\n })\n //if (updatedChainId =! null) throw Error(`AddChainError: ${updatedChainId}`)\n if (updatedChainId) {\n console.log(updatedChainId)\n }\n } else {\n // Notify the user to change the chain they are on manually.\n alert(`Please update the current chain in your wallet.`)\n return\n }\n\n } catch (addChainError) {\n console.error(addChainError)\n }\n }\n\n }",
"async function initProvider(web3) {\n // loads the first account for this web3 provider\n const accounts = await web3.eth.getAccounts();\n if (accounts.length == 0)\n throw ('Unable to find an account in the current web3 provider');\n const owner = accounts[0];\n console.log(\"Loaded account:\", owner);\n // TODO: Add Zap balance\n console.log(\"Wallet contains:\", await web3.eth.getBalance(owner) / 1e18, \"ETH\");\n return new provider_1.ZapProvider(owner, {\n artifactsDir: path_1.join(__dirname, '../', 'node_modules/@zapjs/artifacts/contracts/'),\n networkId: (await web3.eth.net.getId()).toString(),\n networkProvider: web3.currentProvider,\n });\n}",
"async changeChain() {\n const provider = await detectEthereumProvider();\n await provider.request({\n method: \"wallet_addEthereumChain\",\n params: [\n {\n chainId: `0x38`,\n chainName: \"Binance Smart Chain Mainnet\",\n nativeCurrency: {\n name: \"BNB\",\n symbol: \"bnb\",\n decimals: 18,\n },\n rpcUrls: [\"https://bsc-dataseed1.ninicoin.io\"],\n blockExplorerUrls: [`https://bscscan.com/`],\n },\n ],\n });\n }",
"function setup_parts_lib(cb) {\r\n\tvar opts = helper.makePartsLibOptions();\r\n\tparts_lib = require('./utils/parts_cc_lib.js')(enrollObj, opts, fcw, logger);\r\n\tws_server.setup(wss.broadcast, parts_lib);\r\n\r\n\tlogger.debug('Checking if chaincode is already instantiated or not');\r\n\tconst channel = helper.getChannelId();\r\n\tconst first_peer = helper.getFirstPeerName(channel);\r\n\tvar options = {\r\n\t\tpeer_urls: [helper.getPeersUrl(first_peer)],\r\n\t};\r\n\tparts_lib.check_if_already_instantiated(options, function (not_instantiated, enrollUser) {\r\n\t\tif (not_instantiated) {\t\t\t\t\t\t\t\t\t//if this is truthy we have not yet instantiated.... error\r\n\t\t\tconsole.log('');\r\n\t\t\tlogger.debug('Chaincode was not detected: \"' + helper.getChaincodeId() + '\", all stop');\r\n\t\t\tlogger.debug('Open your browser to http://' + host + ':' + port + ' and login to tweak settings for startup');\r\n\t\t\tprocess.env.app_first_setup = 'yes';\t\t\t\t//overwrite state, bad startup\r\n\t\t\tbroadcast_state('find_chaincode', 'failed');\r\n\t\t}\r\n\t\telse {\t\t\t\t\t\t\t\t\t\t\t\t\t//else we already instantiated\r\n\t\t\tconsole.log('\\n----------------------------- Chaincode found on channel \"' + helper.getChannelId() + '\" -----------------------------\\n');\r\n\r\n\t\t\t// --- Check Chaincode Compatibility --- //\r\n\t\t\tparts_lib.check_version(options, function (err, resp) {\r\n\t\t\t\tif (helper.errorWithVersions(resp)) {\r\n\t\t\t\t\tbroadcast_state('find_chaincode', 'failed');\r\n\t\t\t\t} else {\r\n\t\t\t\t\tlogger.info('Chaincode version is good');\r\n\t\t\t\t\tbroadcast_state('find_chaincode', 'success');\r\n\t\t\t\t\tif (cb) cb(null);\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t});\r\n}",
"async function init(address, signer) {\n const abi = contract.abi;\n didReg = new ethers.Contract(address,abi,signer);\n \n}",
"function setup(cb) {\n console.log(\"initializing ...\");\n var chain = hlc.newChain(\"testChain\");\n chain.setKeyValStore(hlc.newFileKeyValStore(\"/tmp/keyValStore\"));\n chain.setMemberServicesUrl(\"grpc://localhost:50051\");\n chain.addPeer(\"grpc://localhost:30303\");\n console.log(\"enrolling deployer ...\");\n chain.enroll(\"WebAppAdmin\", \"DJY27pEnl16d\", function (err, user) {\n if (err) return cb(err);\n deployer = user;\n console.log(\"enrolling assigner ...\");\n chain.enroll(\"jim\",\"6avZQLwcUe9b\", function (err, user) {\n if (err) return cb(err);\n assigner = user;\n console.log(\"enrolling nonAssigner ...\");\n chain.enroll(\"lukas\",\"NPKYL39uKbkj\", function (err, user) {\n if (err) return cb(err);\n nonAssigner = user;\n });\n });\n });\n}",
"async function initialize() {\n simulator = new Simulator(credentials);\n\n await new Promise((resolve, reject) => {\n simulator\n .on('error', (err) => {\n reject(err);\n })\n .on('connected', () => {\n resolve();\n })\n .connect();\n });\n}",
"function init() {\n cache.set(\"appName\", \"Lunch Box\");\n cache.set(\"currency\", \"ETH\");\n cache.set(\"showAddBalance\", false);\n updateAccountInformation();\n\n // set up event listeners\n var contract = web3.eth.contract(deployedAbi);\n var contractInstance = contract.at(deployedAddress);\n\n var eventListener = contractInstance.allEvents();\n eventListener.watch(function(error, event) {\n // just update the meals cache whenever an event arrives\n getMeals();\n // also update single meal cache whenever the event is about the current displayed meal\n if (cache.get('meal') && cache.get('meal').id == event.args.ID.toNumber()) {\n getMeal(event.args.ID.toNumber());\n }\n // balance could also have been updated after an event, update accordingly\n updateAccountInformation();\n });\n //*/\n\n // update page when MetaMask account is changed\n ethereum.on(\"accountsChanged\", function() {\n updateAccountInformation();\n })\n}",
"static initializeDefaultPortfolio() {\n // Add default crypto objects to crypto array \n CryptoExchanger.cryptoExchangerArray.push(new CryptoExchanger(\"bitcoin\", \"Bitcoin\", false));\n CryptoExchanger.cryptoExchangerArray.push(new CryptoExchanger(\"ethereum\", \"Ethereum\", false));\n CryptoExchanger.cryptoExchangerArray.push(new CryptoExchanger(\"litecoin\", \"Litecoin\", false));\n CryptoExchanger.cryptoExchangerArray.push(new CryptoExchanger(\"monero\", \"Monero\", false));\n CryptoExchanger.areCryptosLoaded = true; \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to create the HTML string for the tool tip. Loops through each key in data object and returns the html string key: value | function toolTipHTML(data) {
var tip = '',
i = 0;
for (var key in data.data) {
// if value is a number, format it as a percentage
//var value = (!isNaN(parseFloat(data.data[key]))) ? percentFormat(data.data[key]) : data.data[key];
if (key == Field1 || key == Field2 )
{
var value = (!isNaN(parseFloat(data.data[key]))) ? (data.data[key]) : data.data[key];
// leave off 'dy' attr for first tspan so the 'dy' attr on text element works. The 'dy' attr on
// tspan effectively imitates a line break.
if (i === 0) tip += '<tspan x="0">' + key + ': ' + value + '</tspan>';
else tip += '<tspan x="0" dy="1.2em">' + key + ': ' + value + '</tspan>';
i++;
}
}
return tip;
} | [
"function toolTipHTML(data) {\n\n let tip = '',\n i = 0;\n\n for (let key in data.data) {\n\n // if value is a number, format it as a percentage\n let value = (!isNaN(parseFloat(data.data[key]))) ?\n percentFormat(data.data[key]) :\n data.data[key];\n\n // leave off 'dy' attr for first tspan so the 'dy' attr on\n // text element works. The 'dy' attr on\n // tspan effectively imitates a line break.\n if (i === 0) {\n tip += `<tspan x=\"0\">${key}: </tspan>\n <tspan style=\"font-weight: bold; font-size: 120%;\">${value}</tspan>`;\n } else {\n tip += `<tspan x=\"0\" dy=\"1.2em\">${key}:</tspan>\n <tspan x=\"0\" dy=\"1em\" style=\"font-weight: bold; font-size: 120%;\">${value}</tspan>`;\n }\n i++;\n }\n\n return tip;\n }",
"generateToolTip() {\n //Order the data array\n let data = formatArray.collectionToBottom(this.data, ['Database IDs', 'Comment']);\n\n if (!(data) || data.length === 0) {\n return generate.noDataWarning(this.name);\n }\n\n //Ensure name is not blank\n this.validateName();\n\n if (!(this.data)) { this.data = []; }\n return h('div.tooltip-image', [\n h('div.tooltip-heading', this.name),\n h('div.tooltip-internal', h('div', (data).map(item => generate.parseMetadata(item, true), this))),\n h('div.tooltip-buttons',\n [\n h('div.tooltip-button-container',\n [\n h('div.tooltip-button', { onclick: this.displayMore() }, [\n h('i', { className: classNames('material-icons', 'tooltip-button-show') }, 'fullscreen'),\n h('div.describe-button', 'Additional Info')\n ]),\n ])\n ])\n ]);\n }",
"function constructTooltipHTML(d){\n\t\t\t\t\tvar name = d.name;\n\t\t\t\t\tvar count = d.count;\n\t\t\t\t\tvar university = d.university;\n\t\t\t\t\tvar years = d.dates.toString();\n\t\t\t\t\tvar find =',';\n\t\t\t\t\tvar re = new RegExp(find,'g');\n\t\t\t\t\tvar fYears = years.replace(re,', ');\n\n\t\t\t\t\tvar html = \n\t\t\t\t\t'<div class=\"panel panel-primary\">' + \n\t\t\t\t\t\t'<div class=\"panel-heading\">' +\n\t\t\t\t\t\t\tname +\n\t\t\t\t\t\t'</div>' +\n\t\t\t\t\t\t'<div class=\"panel-body\">' + \n\t\t\t\t\t\t\t'<p><strong class=\"tooltip-body-title\">University: </strong>' + university +\n\t\t\t\t\t\t\t'</p><p><strong class=\"tooltip-body-title\">Number of times coauthored: </strong>' + count +\n\t\t\t\t\t\t\t'</p><p><strong class=\"tooltip-body-title\">Years Co-Authored: </strong>' + fYears + '</p>' +\n\t\t\t\t\t\t\t'<p>Double-Click to go to ' + name + '\\'s</p>'+\n\t\t\t\t\t\t'</div></div>';\n\n\t\t\t\t\treturn html;\n\t\t\t\t}",
"drawCustomTooltip(hitInfoItems) {\n const opt = this.options?.tooltip;\n if (opt.formatter?.html) {\n this.tooltipDOM.innerHTML = '';\n\n const seriesList = [];\n Object.keys(hitInfoItems).forEach((sId) => {\n seriesList.push({\n sId,\n data: hitInfoItems[sId].data,\n color: hitInfoItems[sId].color,\n name: hitInfoItems[sId].name,\n });\n });\n\n const userCustomTooltipBody = Util.htmlToElement(opt?.formatter?.html((seriesList)));\n if (userCustomTooltipBody) {\n this.tooltipDOM.appendChild(userCustomTooltipBody);\n }\n\n this.tooltipDOM.style.overflowY = 'hidden';\n this.tooltipDOM.style.backgroundColor = opt.backgroundColor;\n this.tooltipDOM.style.border = `1px solid ${opt.borderColor}`;\n this.tooltipDOM.style.color = opt.fontColor;\n }\n }",
"function tooltipTextConverter(data) {\n var str = \"\"\n var e = myDiagram.lastInput\n var currobj = e.targetObject\n if (currobj !== null && (currobj.name === \"ButtonA\" ||\n (currobj.panel !== null && currobj.panel.name === \"ButtonA\"))) {\n str = data.aToolTip\n } else {\n str = data.bToolTip\n }\n return str\n }",
"function dictToHtml(d) {\n html = \"\"\n d = limitDict(d)\n for (var k in d) {\n x = k.replace(/_/g,\" \")\n y = d[k]\n if(typeof(y)==\"string\"){\n y = d[k].replace(/_/g,\" \")\n }else if(typeof(y)==\"number\"){\n y = r(y)\n } else if(typeof(y)==\"object\"){\n y = d[k].toString().replace(/_/g,\" \")\n }\n html += x + \": \" + y + \"<br>\"\n }\n return html\n}",
"function setTooltipListeners() {\n\t\t\td3.selectAll(\"path.trend-area\").filter(function(d) {return !d3.select(this).classed(\"null\");}).tooltip(function(d, i) {\n\t\t\t\tvar content = '<div><p>';\n\t\t\t\tcontent += '<strong>Income Poverty:</strong> ' + (trends[d.id].Einkommen_Arm*100).toFixed(2) + '% → ' + (trends[d.id].Einkommen_Arm_t2*100).toFixed(2) +'%<br/>';\n\t\t\t\t//content += '<strong>Erwachsenen Armut:</strong> ' + (trends[d.id].Erwa_Arm*100).toFixed(2) + '%<br/>';\n\t\t\t\t//content += '<strong>Altersarmut:</strong> ' + (trends[d.id].Alter_Arm*100).toFixed(2) + '%';\n\t\t\t\tcontent += '<hr/>';\n\t\t\t\tcontent += '<strong>Rent Price:</strong> ' + (trends[d.id].Mietpreise*1).toFixed(2) + '€ → ' + (trends[d.id].Mietpreise_t2*1).toFixed(2) +'€<br/>';\n\t\t\t\tcontent += '<strong>Condominiums:</strong> ' + (trends[d.id].Anteil_ETW*100).toFixed(2) + '% → ' + (trends[d.id].Anteil_ETW_t2*100).toFixed(2) +'%<br/>';\n\t\t\t\tcontent += '<strong>Affordable Flats:</strong> ' + (trends[d.id].Anteil_KDU*100).toFixed(2) + '% → ' + (trends[d.id].Anteil_KDU_t2*100).toFixed(2) +'%<br/>';\n\t\t\t\tcontent += '</p></div>';\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"popover\",\n\t\t\t\t\ttitle: '<strong style=\"font-size:1.5em;\">' + trends[d.id].Stadtteil + '</strong><br/>' + trends[d.id].Bezirk,\n\t\t\t\t\tcontent: content,\n\t\t\t\t\tdetection: \"shape\",\n\t\t\t\t\tplacement: \"mouse\",\n\t\t\t\t\tgravity: 'up',\n\t\t\t\t\tposition: path.centroid(_.where(topojson.feature(dataset, dataset.objects.immoscout).features, {id: d.id})[0]),\n\t\t\t\t\tdisplacement: [10, 10],\n\t\t\t\t\tmousemove: false,\n\t\t\t };\n\t\t\t});\n\t\t}",
"function createTooltips(){\n $('select.role option').each( function(){\n console.log( this );\n var country = $('select.country').val();\n var role = $(this).attr('value');\n var element = $(this);\n console.log( \"Country: \" + country + \" Role: \" + role );\n $.getJSON( root + '/en/roles/get_all_access/' + country +'/' + role, function(data){\n var tooltip = \"\";\n console.log( element );\n if( data.access.length > 1 ){\n tooltip = i18n.gettext(\"Complete access from: \");\n tooltip += data.access.map(caps).join(', ') + \".\";\n }else{\n tooltip += i18n.gettext(\"Does not inherit any access.\");\n }\n console.log( tooltip );\n element.attr('title', tooltip);\n\n });\n });\n }",
"function popupText(data) {\n\t\tvar text = '<p class=\"alertHeader\">'+data.header+'</p>' +\n\t\t\t\t\t'<p class=\"alertBody1\">'+data.body1+'</p>' +\n\t\t\t\t\t'<p class=\"alertBody2\">'+data.body2+'</p>';\n\t\treturn text;\n\t}",
"function generateUIForJSON(data){\n return `\n <div class=\"quarter\">\n <div class=\"image\">\n <img src=\"${data.picture}\"/>\n </div>\n <div class=\"info\">\n <h3>${data.name}</h3>\n <h4>${data.gender}</h3>\n <h5>${data.email}</h5>\n </div>\n </div>\n `\n}",
"function fillTooltipsOnPage(tooltipData) {\n\t$.each(tooltipData, function(key, value) {\n\t\tif (key.startsWith('#')) {\n\t\t\tvar popupNode = $(key).parent().prev();\n\t\t\tfillDocumentationNode(popupNode, value);\n\t\t} else {\n\t\t\t$(key).each(function () {\n\t\t\t\tvar popupNode = $(this);\n\t\t\t\tfillDocumentationNode(popupNode, value);\n\t\t\t});\n\t\t}\n\t});\n}",
"function create_tooltips() {\n $(\"#additional_volunteers .might-overflow\").tooltip({ placement: \"left\"});\n $(\"#additional_volunteers .volunteer_name\").hover(function() {\n $(this).children(\".help-edit\").removeClass(\"hidden\");\n }, function() {\n $(this).children(\".help-edit\").addClass(\"hidden\");\n }).click(function() {\n $(this).addClass(\"editing\");\n var old_name = $(this).attr(\"volunteer_name\");\n var old_email = $(this).attr(\"volunteer_email\");\n var old_combined = old_name + ':' + old_email;\n $(this).attr(\"value\",old_combined);\n $(\"#volunteer_name\").val($(this).attr(\"volunteer_name\"));\n $(\"#volunteer_email\").val($(this).attr(\"volunteer_email\"));\n $(\"#add_edit_additional_volunteer\").html(\"Edit volunteer\");\n });\n }",
"function _genericInfo({ title, value }) {\n return HtmlBuilder.div().addClass('mt-2')\n .append(HtmlBuilder.div(HtmlBuilder.strong(title)))\n .append(HtmlBuilder.div(value))\n }",
"createTooltips() {\n for (let i = 0; i < this.shopItems.length; i++) {\n let tooltipPosition = this.getSelectionPosition(i);\n let tooltipPanel = this.add.nineslice(tooltipPosition.x, tooltipPosition.y,\n 0, 0, 'greyPanel', 7).setOrigin(1, 0);\n // Flip tooltip for lower selections so it doesn't get cut off at the bottom of the screen\n if (i >= tooltipFlipIndex) {\n tooltipPanel.setOrigin(1, 1);\n }\n\n // Create tooltip game objects\n let tooltipTitle = this.add.text(0, 0, \"\", { ...this.tooltipTextStyle, font: \"18px Verdana\" }).setOrigin(0.5, 0);\n let tooltipPrice = this.add.text(0, 0, \"\", { ...this.tooltipTextStyle, font: \"16px Verdana\" }).setOrigin(0.5, 0);\n let tooltipGrowthRate = this.add.text(0, 0, \"\", { ...this.tooltipTextStyle, font: \"16px Verdana\" }).setOrigin(0.5, 0);\n let tooltipClickValue = this.add.text(0, 0, \"\", { ...this.tooltipTextStyle, font: \"16px Verdana\" }).setOrigin(0.5, 0);\n let tooltipDescription = this.add.text(0, 0, \"\", this.tooltipTextStyle).setOrigin(0.5, 0);\n let tooltipTexts = [\n tooltipTitle, \n tooltipPrice, \n tooltipGrowthRate,\n tooltipClickValue,\n tooltipDescription\n ];\n let tooltipTitleBreak = this.add.line(0, 0, 0, 0, 0, 0, 0x999999).setOrigin(0, 0);\n let tooltipPriceBreak = this.add.line(0, 0, 0, 0, 0, 0, 0x999999).setOrigin(0, 0);\n let tooltipRatesBreak = this.add.line(0, 0, 0, 0, 0, 0, 0x999999).setOrigin(0, 0);\n let tooltipBreaks = [\n tooltipTitleBreak,\n tooltipPriceBreak,\n tooltipRatesBreak\n ];\n let tooltip = this.add.group([tooltipPanel].concat(tooltipTexts).concat(tooltipBreaks));\n tooltip.setVisible(false);\n this.tooltips.push(tooltip);\n\n // Set tooltip text values\n if (getType(this.shopItems[i].selection) == ShopSelectionType.DEMOLITION) {\n tooltipTitle.setText(\"Demolish building\");\n tooltipPrice.setText(\"Costs half of the construction cost for the selected building\");\n // Hide unneeded text and breaks\n tooltipPriceBreak.setAlpha(0);\n tooltipRatesBreak.setAlpha(0);\n tooltipGrowthRate.setText(\"\");\n tooltipClickValue.setText(\"\");\n tooltipDescription.setText(\"\");\n } else if (getType(this.shopItems[i].selection) == ShopSelectionType.EXPAND_MAP) {\n tooltipTitle.setText(\"Expand map\");\n formatPhaserCashText(tooltipPrice, getPrice(this.shopItems[i].selection), \"\", false, true);\n this.priceTexts[this.shopItems[i].selection][\"tooltipPriceText\"] = tooltipPrice;\n tooltipGrowthRate.setText(\"Add a set of new tiles to the map\");\n // Hide unneeded text and breaks\n tooltipRatesBreak.setAlpha(0);\n tooltipClickValue.setText(\"\");\n tooltipDescription.setText(\"\");\n } else {\n this.priceTexts[this.shopItems[i].selection][\"tooltipPriceText\"] = tooltipPrice;\n tooltipTitle.setText(this.shopItems[i].selection);\n formatPhaserCashText(tooltipPrice, getPrice(this.shopItems[i].selection), \"\", false, true);\n formatPhaserCashText(tooltipGrowthRate,\n getSelectionProp(this.shopItems[i].selection, 'baseCashGrowthRate'),\n \"/second\", true, false);\n formatPhaserCashText(tooltipClickValue,\n getSelectionProp(this.shopItems[i].selection, 'baseClickValue'),\n \"/click\", true, false);\n tooltipDescription.setText(getSelectionProp(this.shopItems[i].selection, 'description'));\n \n tooltipPriceBreak.setAlpha(1);\n tooltipRatesBreak.setAlpha(1);\n }\n \n // Resize and set positions of tooltip elements\n let panelWidth = 0;\n let panelHeight = tooltipTextMargin;\n let tooltipTextYDiff = [];\n // Resize panel\n for (let i = 0; i < tooltipTexts.length; i++) {\n if (!isBlank(tooltipTexts[i].text)) {\n panelWidth = Math.max(panelWidth, tooltipTexts[i].width + 2 * tooltipTextMargin);\n // No line break is added between the cash growth rates. Also should ignore presence of \"/click\"\n // in the last text, since it is the description, no the click value.\n if (i > 0 && (i == tooltipTexts.length - 1 || !tooltipTexts[i].text.includes(\"/click\"))) {\n panelHeight += tooltipTextBreakYMargin;\n }\n tooltipTextYDiff[i] = panelHeight;\n panelHeight += tooltipTexts[i].height + tooltipTextMargin;\n }\n }\n // There is a bug in Phaser 3 that causes fonts to looks messy after resizing\n // the nineslice. For now using the workaround of creating and immediately\n // deleting a dummy text object after resizing the nineslice.\n // When this is fixed in a future Phaser release this can be removed.\n // See https://github.com/jdotrjs/phaser3-nineslice/issues/16\n // See https://github.com/photonstorm/phaser/issues/5064\n tooltipPanel.resize(panelWidth, panelHeight);\n let dummyText = this.add.text(0, 0, \"\");\n dummyText.destroy();\n \n // Move text and break objects\n for (let i = 0; i < tooltipTexts.length; i++) {\n tooltipTexts[i].setPosition(tooltipPanel.getTopCenter().x, tooltipPanel.getTopCenter().y + tooltipTextYDiff[i]);\n tooltipTexts[i].width = panelWidth - 2 * tooltipTextMargin;\n }\n let breakX = tooltipPanel.getTopLeft().x + tooltipTextBreakXMargin;\n let breakY = tooltipPrice.getTopCenter().y - (tooltipTextBreakYMargin + tooltipTextMargin) / 2;\n tooltipTitleBreak.setTo(breakX, breakY, tooltipPanel.getTopRight().x - tooltipTextBreakXMargin, breakY);\n breakY = tooltipGrowthRate.getTopCenter().y - (tooltipTextBreakYMargin + tooltipTextMargin) / 2;\n tooltipPriceBreak.setTo(breakX, breakY, tooltipPanel.getTopRight().x - tooltipTextBreakXMargin, breakY);\n breakY = tooltipDescription.getTopCenter().y - (tooltipTextBreakYMargin + tooltipTextMargin) / 2;\n tooltipRatesBreak.setTo(breakX, breakY, tooltipPanel.getTopRight().x - tooltipTextBreakXMargin, breakY);\n }\n }",
"function buildInfoTemplate(popupInfo) {\n var json = {\n content: \"<table>\"\n };\n\n dojo.forEach(popupInfo.fieldInfos, function (field) {\n if (field.visible) {\n json.content += \"<tr><td valign='top'>\" + field.label + \": <\\/td><td valign='top'>${\" + field.fieldName + \"}<\\/td><\\/tr>\";\n }\n });\n json.content += \"<\\/table>\";\n return json;\n}",
"function mouseoverHandler (d) {\n tooltip.transition().style('opacity', .9)\n tooltip.html('<p>' + d[\"country\"] + '</p>' );\n }",
"function getMultiTooltipContent(e,tooltipFn,bucketTooltipFn,chart,selector) {\n var tooltipArray = [],result = {},nodeMap = {};\n //No. of tooltip contents to show per page\n var perPage = 1;\n var overlappedNodes = e['point']['overlappedNodes'];\n var series = concatenateDataFromMultipleSeries(e['series']);\n if(!e.point.isBucket) {\n for(var i = 0;i < overlappedNodes.length; i++){\n //Filter out nodes which are from disabled series\n var data = $.grep(series,function(obj,idx) {\n return (obj['name'] == overlappedNodes[i]['name'] && obj['type'] == overlappedNodes[i]['type'] &&\n !chart.state()['disabled'][chart.seriesMap()[obj['type']]]);\n });\n\n if(!isEmptyObject(data)) {\n //data['point'] = data[0];\n tooltipArray.push(tooltipFn(data[0],'simple'));\n //Creates a hashMap based on first key/value in tooltipContent\n nodeMap[tooltipFn(data[0],'simple')[0]['value']] = {point:data[0]};\n }\n }\n } else {\n // Use this if you want to display all the nodes\n /*\n * for(var i = 0;i < overlappedNodes.length; i++){\n * tooltipArray.push(tooltipFn(overlappedNodes[i],null,null));\n * //Creates a hashMap based on first key/value in tooltipContent\n * nodeMap[tooltipFn(overlappedNodes[i])[0]['value']] = {point:overlappedNodes[i]};\n * }\n */\n tooltipArray.push(bucketTooltipFn(e['point'],'simple'));\n //Creates a hashMap based on first key/value in tooltipContent\n nodeMap[bucketTooltipFn(e['point'],'simple')[0]['value']] = {point:e['point']};\n }\n result['content'] = tooltipArray;\n result['nodeMap'] = nodeMap;\n result['perPage'] = perPage;\n //If no.of tooltipContents to show is less than perPage\n var limit = (result['content'].length >= result['perPage']) ? result['perPage'] : result['content'].length;\n if(result['perPage'] > 1)\n result['pagestr'] = 1+\" - \"+limit+\" of \"+result['content'].length ;\n else if(result['perPage'] == 1)\n result['pagestr'] = 1+\" / \"+result['content'].length ;\n return result;\n}",
"function ToolTips(){\n\t\n\t// connector divs\n\tthis.createConnectors();\n\t\n\t// over lap of connector and trigger \n\tthis.overlapH = 10;\n\tthis.overlapV = -5;\n\n\t// time delay\n\tthis.showDelay = 500; // milliseconds\n\t\n\t// current showing tip\n\tthis.currentShowingEl = 0;\n}",
"function fillRowTooltipsOnPage(tooltipData) {\n\t$.each(tooltipData, function(key, value) {\n\t\tvar $popupNode = $(key).find('>td:first');\n\t\tfillDocumentationNode($popupNode, value);\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
compare the user hashes with order hashes | function compareUserHashes(userID, userHash, orderHash) {
var match = false,
, o = 0
, u = 0;
fs.appendFileSync(userResultsFile, "UserID: " + userID + " OrderID: " + orderHash[0] + "\n");
//for each entry in orders attempt to find the md5 in users
async.forEach(userHash, function(user, callbackUsers) {
++o;
async.forEach(orderHash, function(order, callbackOrders) {
if(order.AssetPath && order.ImageHash == user.md5) {
match = true;
++u;
}
callbackOrders();
}, function(orders_finished) {
if(!match) {
fs.appendFileSync(userResultsFile, "Source " + user.Source + "\n Social Source " + user.socialSource + "\n\n");
}
});
callbackUsers();
}, function(users_finished) {
if(match)
fs.appendFileSync(userResultsFile, "Good! \n \n");
});
} | [
"function compareOrderHashes(userID, userHash, orderHash, callback) {\n\t\n\tvar match = false,\n\t\t, o = 0\n\t\t, u = 0;\n\n\tfs.appendFileSync(orderResultsFile, \"UserID: \" + userID + \" OrderID: \" + orderHash[0] + \"\\n\");\n\n\t//for each entry in orders attempt to find the md5 in users\n\tasync.forEach(orderHash, function(order, callbackOrders) {\n\t\tif(order.AssetPath) {\n\t\t\t++o;\n\n\t\t\tasync.forEach(userHash, function(user, callbackUsers) {\n\t\t\t\tif(order.ImageHash == user.md5) {\n\t\t\t\t\tmatch = true;\n\t\t\t\t\t++u;\n\t\t\t\t}\n\t\t\t\tcallbackUsers();\n\n\t\t\t}, function(users_finished) {\n\t\t\t\tif(!match) {\n\t\t\t\t\tfs.appendFileSync(orderResultsFile, order.AssetPath + \"\\n \\n\");\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tcallbackOrders();\n\n\t}, function(orders_finished) {\n\t\tif(match) {\n\t\t\tfs.appendFileSync(orderResultsFile, \"Good! \\n \\n\");\n\t\t}\n\t\tcallback();\n\t});\t\n}",
"function checksumCompare(a, b){\r\n if (a.score == b.score){ // if scores tied sort by character\r\n return Object.compare(a.char, b.char);\r\n }\r\n\r\n // comparison to sort count / char by score first\r\n return Object.compare(b.score, a.score);\r\n}",
"function isSimilar(hash1,hash2) {\n\tvar similar = false;\n\tfor (var key1 in hash1) {\n\t\tfor (var key2 in hash2) {\n\t\t\tif ((key1 === key2) && (hash1[key1] === hash2[key2])) {\n\t\t\t\tsimilar = true;}\n\t\t\t}\n\t\t}\n\t\treturn similar;\n\t}",
"async function comparePassword(originalSecret, storedHashedPassword) {\n // call compare method that triggers a promise and returns a bool\n const isMatch = await bcrypt.compare(originalSecret, storedHashedPassword);\n if (isMatch) {\n console.log('Matched');\n } else {\n console.log('Not a Match... Sorry!');\n }\n}",
"function loadHashes() {\n global_hashes = new Set([]);\n for (note of raw_notes) {\n hashes = note[\"hashes\"];\n if (hashes == null) {\n continue;\n }\n for (hash of hashes) {\n global_hashes.add(hash);\n }\n }\n renderHashes(Array.from(global_hashes).sort((a,b) => a.localeCompare(b)));\n}",
"function check_previous_hash(username, chunk_num, hash) {\n if (chunk_num != 0) {\n if (rtc.hashed_message[username][chunk_num - 1] == hash) {\n return true; /* ok */\n } else {\n return false; /*not ok */\n }\n }\n return true; /* skip for 1st chunk */\n }",
"consistent(blindHash, factor, hash) {\n let n = this.key.keyPair.n;\n let e = new BigInteger(this.key.keyPair.e.toString());\n blindHash = blindHash.toString();\n let bigHash = new BigInteger(hash, 16);\n let b = bigHash.multiply(factor.modPow(e, n)).mod(n).toString();\n let result = blindHash === b;\n return result;\n }",
"function verifyHash(hash , message , pubKey){\n \n //pubKey = forge.pki.setRsaPublicKey(new forge.jsbn.BigInteger(pubKey.n) , new forge.jsbn.BigInteger(pubKey.e));\n try{\n var md = forge.md.sha1.create();\n md.update((message));\n var success = pubKey.verify(md.digest().getBytes() , hash);\n return success;\n }\n catch(err){\n return false;\n }\n\n}",
"digesting() {}",
"function isEqualPass(obj1,obj2){\r\n\t var pw1 = obj1.value;\r\n\t var pw2 = obj2.value;\r\n\t \r\n\t if(pw1.length ==0 || pw2.length ==0){\r\n\t\t return true;\r\n\t }\r\n\t if(pw1 == pw2){\r\n\t\t return false;\r\n\t }\r\n\t \r\n\t return true;\r\n }",
"function sortUsers() {\n users.sort((a, b) => {\n return b.wins - a.wins || b.points - a.points || b.goldJackets - a.goldJackets;\n });\n }",
"findBestMatch(order) {\n\t\tvar matches = [];\n\n\t\tthis.pool.forEach((o) => {\n\t\t\t// if (o.id == order.id)\n\t\t\t// \treturn;\n\t\t\t// if (o.exchangeContractAddress != order.exchangeContractAddress)\n\t\t\t// \treturn;\n\t\t\t// if (o.makerTokenAddress != order.takerTokenAddress)\n\t\t\t// \treturn;\n\t\t\t// if (o.takerTokenAddress != order.makerTokenAddress)\n\t\t\t// \treturn;\n\t\t\t// if (o.makerTokenAmount == 0 || o.takerTokenAmount == 0)\n\t\t\t// \treturn;\n\t\t\t// if (order.makerTokenAmount == 0 || order.takerTokenAmount == 0)\n\t\t\t// \treturn;\n\t\t\t// if (o.takerTokenAmount / o.makerTokenAmount < order.makerTokenAmount / order.takerTokenAmount)\n\t\t\t// \treturn;\n\t\t\tmatches.push({\n\t\t\t\torderA: order,\n\t\t\t\torderB: o,\n\t\t\t\tpriority: [o.makerFee + o.takerFee + order.makerFee + order.takerFee,\n\t\t\t\t\t\tBigNumber.min(o.expirationUnixTimestampSec, order.expirationUnixTimestampSec)],\n\t\t\t});\n\t\t});\n\n\t\t// matches.sort((a, b) => {\n\t\t// \tif (a.priority == b.priority)\n\t\t// \t\treturn 0;\n\t\t// \treturn a.priority > b.priority ? 1 : -1;\n\t\t// })\n\t\tif (matches.length == 0) {\n\t\t\tconsole.log('found match');\n\t\t\tconsole.log('Sending to ZRX exchangeContract')\n\t\t\treturn null;\n\t\t} else {\n\t\t\tlet bestMatch = matches[matches.length - 1];\n\t\t\treturn {\n\t\t\t\torderA: bestMatch.orderA,\n\t\t\t\torderB: bestMatch.orderB,\n\t\t\t};\n\t\t}\n\t}",
"function compareUsernameAscending(a, b) {\n\n if (a.username.toLowerCase() < b.username.toLowerCase()) {\n return -1;\n }\n if (a.username.toLowerCase() > b.username.toLowerCase()) {\n return 1;\n }\n // a must be equal to b\n return 0;\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}",
"function searchForUser(user,password){\n var check = 0;\n if(localStorage.length == 0 || localStorage.length == 1){\n return check;\n }\n for(var i = 0; i < localStorage.length; i++){\n if(localStorage.getItem(localStorage.key(i)) === localStorage.number || localStorage.key(i) === \"debug\"){\n ;\n }\n else{\n existingUser = localStorage.getItem(localStorage.key(i));\n existingUser = JSON.parse(existingUser);\n if(user == existingUser.username){\n check = 1;\n if(password == existingUser.password){\n check = 2;\n break;\n }\n break;\n }\n }\n }\n return check;\n}",
"function ignoreHash(user) {\r\n const { hash, ...otherUserData} = user;\r\n return otherUserData\r\n}",
"function compauthor(a, b) {\n return a.author > b.author;\n}",
"function isTransactionContain(t1, t2) {\n if (t1.length < t2.length) {\n return false;\n }\n const hash = {};\n for (let i = 0; i < t1.length; i++) {\n const item = t1[i];\n hash[item] = true;\n }\n for (let i = 0; i < t2.length; i++) {\n const item = t2[i];\n if (!hash[item]) {\n return false\n }\n }\n return true;\n}",
"function compare_pair(object1,object2)\r\n {\r\n if(object1['age']==object2['age']){\r\n console.log(\"TRUE\")\r\n } \r\n else {\r\n console.log(\"FALSE\")\r\n } \r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
See if the sample plane's dimensions have changed | _checkPlaneDidChange() {
const oldPlaneWidth = this._planeWidth;
const oldPlaneHeight = this._planeHeight;
const width = INITIAL_PLANE_SIZE * 2 * this._plane.scale.x;
const height = INITIAL_PLANE_SIZE * 2 * this._plane.scale.y;
if (oldPlaneWidth !== width || oldPlaneHeight !== height) {
this._delegate.onPlaneDidChange(width, height);
}
this._planeWidth = width;
this._planeHeight = height;
} | [
"resizeAxisCanvas() {\n const desiredWidth = this.visualizer.canvas.width;\n const desiredHeight = this.visualizer.canvas.height;\n\n if (this.canvas.width !== desiredWidth || this.canvas.height !== desiredHeight) {\n this.canvas.width = desiredWidth;\n this.canvas.height = desiredHeight;\n }\n }",
"function gotSomethingDifferent(){\n if (prevDetections.length != detections.length){\n return true;\n }\n var prev = getCountedObjects(prevDetections);\n var curr = getCountedObjects(detections);\n for (var k in curr){\n if (curr[k] !== prev[k]){\n return true;\n }\n }\n for (var k in prev){\n if (prev[k] !== curr[k]){\n return true;\n }\n }\n return false;\n}",
"get heightChanged() {\n return (this.flags & 2) /* Height */ > 0\n }",
"calculateDimensions() {\r\n let leftMostCoordinate = this.transformedPolygon[0][0],\r\n rightMostCoordinate = this.transformedPolygon[0][0],\r\n topMostCoordinate = this.transformedPolygon[0][1],\r\n bottomMostCoordinate = this.transformedPolygon[0][1];\r\n\r\n for(let i=0; i<this.transformedPolygon.length; i++) {\r\n if(this.transformedPolygon[i][0] < leftMostCoordinate) {\r\n leftMostCoordinate = this.transformedPolygon[i][0];\r\n } else if(this.transformedPolygon[i][0] > rightMostCoordinate) {\r\n rightMostCoordinate = this.transformedPolygon[i][0];\r\n }\r\n\r\n if(this.transformedPolygon[i][1] < topMostCoordinate) {\r\n topMostCoordinate = this.transformedPolygon[i][1];\r\n } else if(this.transformedPolygon[i][1] > bottomMostCoordinate) {\r\n bottomMostCoordinate = this.transformedPolygon[i][1];\r\n }\r\n }\r\n\r\n this.width = Math.abs(rightMostCoordinate - leftMostCoordinate);\r\n this.height = Math.abs(bottomMostCoordinate - topMostCoordinate);\r\n }",
"checkGeometries() {\n for (var i = 2; i < this.geometries.length; i++) {\n if (this.geometries[i].modelMatrix.elements[12] < -2.2) {\n this.removeGeometry(i);\n }\n }\n }",
"localClipped (x, y) {\n if (x !== null && (x < 0 || x >= this.Config.size.width)) return true;\n if (y !== null && (y < 0 || y >= this.Config.size.height)) return true;\n return false;\n }",
"function areDimensionsValid(dim, x, y){\n\n // Compare set dimensions to x and y coordinates\n if(x > dim || y > dim)\n {\n alert(\"Invalid player coordinates. Load a different file or fix the current one.\");\n window.location.replace(\"index.html\");\n }\n // The coordinates to dimensions are valid\n else\n return true;\n}",
"function EqualClientRectsData(r1, r2)\n{\n if (r1 === undefined || r2 === undefined || r1.length !== r2.length)\n return false;\n \n // Check if width and height of each Rect are identical\n\tfor(var i = 0, n = r1.length; i < n; i++)\n {\n if((r1[i] === undefined && r2[i] !== undefined) || (r1[i] !== undefined && r2[i] === undefined))\n return false;\n if(r1[i] === undefined)\n continue;\n\t\tfor(var j = 0; j < 4; j++)\n if(r1[i][j] !== r2[i][j])\n return false; // Stop iterating asap\n }\n\treturn true;\n\n}",
"function isAllBoundsEqual() {\r\n\tvar bounds = [];\r\n\tfor (var i=0; i<app.m; i++) {\r\n\t\tvar mapN = \"map\" + i;\r\n\t\tbounds.push(app[mapN].map.getBounds());\r\n\t}\r\n\tvar j = 0;\r\n\tvar isAllSameBounds = true;\r\n\tfor (var i=1; i<bounds.length; i++) {\r\n\t\tif (!boundsEqual(bounds[i], bounds[0])) {\r\n\t\t\tisAllSameBounds = false;\r\n\t\t\tj = i;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif (!isAllSameBounds) {\r\n\t\t//console.log('mapX bounds of all maps are not same. from: [map' + j + ']');\r\n\t\t//console.log(bounds)\r\n\t}\r\n\treturn isAllSameBounds;\r\n}",
"function updateSampleGrid(){\n binnedSamplePairs = getBinnedSamplePairs();\n previewControl.forceRedraw();\n }",
"function updateDimensions() {\n theight = templateHeight();\n cheight = containerHeight();\n vpheight = viewPortHeight();\n }",
"checkCols(){\n\t\tthis.checkBounds();\n\t\tthis.checkBlocks();\n\t}",
"function canHandleTrPxMan() {\n\t\tvar c, s1, s2;\n\t\tc = document.createElement(\"canvas\");\n\t\tc.width = 2;\n\t\tc.height = 1;\n\t\tc = c.getContext('2d');\n\t\tc.fillStyle = \"rgba(10,20,30,0.5)\";\n\t\tc.fillRect(0,0,1,1);\n\t\ts1 = c.getImageData(0,0,1,1);\n\t\tc.putImageData(s1, 1, 0);\n\t\ts2 = c.getImageData(1,0,1,1);\n\t\treturn (s2.data[0] === s1.data[0] && s2.data[1] === s1.data[1] && s2.data[2] === s1.data[2] && s2.data[3] === s1.data[3]);\n\t}",
"function privateCheckSongVisualization(){\n\t\tvar changed = false;\n\n\t\t/*\n\t\t\tChecks to see if the song actually has a specific visualization\n\t\t\tdefined.\n\t\t*/\n\t\tif( config.active_metadata.visualization ){\n\t\t\t\n\t\t\t/*\n\t\t\t\tIf the visualization is different and there is an active\n\t\t\t\tvisualization. We must stop the active visualization\n\t\t\t\tbefore setting the new one.\n\t\t\t*/\n\t\t\tif( config.active_metadata.visualization != config.active_visualization && config.active_visualization != '' ){\n\t\t\t\tprivateStopVisualization();\n\t\t\t\t\n\t\t\t\t/*\n\t\t\t\t\tSet the visualization changed to true\n\t\t\t\t\tso we return the status change.\n\t\t\t\t*/\n\t\t\t\tchanged = true;\n\n\t\t\t\t/*\n\t\t\t\t\tSets the active visualization to the new\n\t\t\t\t\tvisualization that the song uses.\n\t\t\t\t*/\n\t\t\t\tconfig.active_visualization = config.active_metadata.visualization;\n\t\t\t}\n\t\t}\n\t\t/*\n\t\t\tReturns the status of the new song visualization.\n\t\t\tIf there is a change it returns true and we will\n\t\t\thave to start the the visualization.\n\t\t*/\n\t\treturn changed;\n\t}",
"function hasParamChanged( paramName, paramValue ) {\r\n\r\n // If the param value exists, then we simply want to use that to compare\r\n // against the current snapshot.\r\n if ( ! ng.isUndefined( paramValue ) ) {\r\n\r\n return( ! isParam( paramName, paramValue ) );\r\n\r\n }\r\n\r\n // If the param was NOT in the previous snapshot, then we'll consider\r\n // it changing.\r\n if (\r\n ! previousParams.hasOwnProperty( paramName ) &&\r\n params.hasOwnProperty( paramName )\r\n ) {\r\n\r\n return( true );\r\n\r\n // If the param was in the previous snapshot, but NOT in the current,\r\n // we'll consider it to be changing.\r\n } else if (\r\n previousParams.hasOwnProperty( paramName ) &&\r\n ! params.hasOwnProperty( paramName )\r\n ) {\r\n\r\n return( true );\r\n\r\n }\r\n\r\n // If we made it this far, the param existence has not change; as such,\r\n // let's compare their actual values.\r\n return( previousParams[ paramName ] !== params[ paramName ] );\r\n\r\n }",
"equals(grid) {\n if (this.height !== grid.height) { return false; }\n if (this.width !== grid.width) { return false; }\n\n let ans = true;\n for (let r = 0; r < this.height; r++) {\n for (let c = 0; c < this.width; c++) {\n if (this.get(r,c) !== grid.get(r,c)) { ans = false; }\n }\n }\n return ans;\n }",
"function hasDynSize(gO) {\r\n\r\n for (var d = 0; d < gO.numDims; d++) {\r\n if (gO.dimDynSize[d]) {\r\n logMsg(\"has dyn size\");\r\n return true;\r\n }\r\n }\r\n\r\n\r\n return false;\r\n}",
"function sameLength(g1,g2) {\n return g1.hasOwnProperty('coordinates') ? \n g1.coordinates.length === g2.coordinates.length\n : g1.length === g2.length;\n}",
"function haveParamsChanged( paramNames ) {\r\n\r\n for ( var i = 0, length = paramNames.length ; i < length ; i++ ) {\r\n\r\n if ( hasParamChanged( paramNames[ i ] ) ) {\r\n\r\n // If one of the params has changed, return true - no need to\r\n // continue checking the other parameters.\r\n return( true );\r\n\r\n }\r\n\r\n }\r\n\r\n // If we made it this far then none of the params have changed.\r\n return( false );\r\n\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to find for parents, as parents were in an array in database, checks for if there arent, return appropriately | function findParents(people, foundPerson){
let parents = [];
for(let i = 0; i < 2; i++){
parents.push(people.filter( function(el){
return el.id === parseInt(foundPerson.parents[i]);
}));
}
if(parents[0].length >= 1){
let parentsOneArray = parents[0];
let parentsTwoArray = parents[1];
// let displayParents = parents[0][0].firstName+" "+parents[0][0].lastName+", ";
// displayParents += parents[1][0].firstName+" "+parents[1][0].lastName+".";
if(parentsOneArray.length == 1 && parentsTwoArray.length == 0){ //if person have only 1 parent
let displayParent = parentsOneArray.map(function(el){
return el.firstName + " " + el.lastName;
});
return displayParent;
}
else if(parentsOneArray.length == 1 && parentsTwoArray.length == 1){ //if person have 2 parents
let displayParents = parents.map(function(el){
return el[0].firstName + " " + el[0].lastName;
});
return displayParents;
}
else{
return;
}
}
else{
let noParents = "No Parents Found in database";
return noParents;
}
} | [
"function getParents (collection, result, callback) {\n if (!collection._parent) return callback(null, result)\n m.Collection.findById(collection._parent, function (err, parentCollection) {\n if (err) console.log(err)\n result.push(parentCollection)\n if (!parentCollection._parent) return callback(null, result)\n return getParents(parentCollection, result, callback)\n })\n}",
"function whoIsTheParent(tree, target) {\n let parentValue = tree['value'];\n let children = tree['children'];\n for(let child of children){\n if(child['value']===target){\n return parentValue\n }else {\n if(child['children'].length!==0){\n if(whoIsTheParent(child,target)!==undefined) return whoIsTheParent(child,target)\n }\n }\n }\n return undefined;\n}",
"isParent(valueParent, valueChild) {\n //2 same values return false\n if(valueParent === valueChild) return false;\n //Get the node object corresponding to our values\n let [existChild, nodeChild, nodeChildDirectParent, ] = this.find(valueChild);\n let [existParent, nodeParent, , ] = this.find(valueParent);\n //if any of the values doesn't exits return false;\n if(!existChild || !existParent) return false;\n //if the child to check is root node return false;\n if(nodeChild === this.root) return false;\n //recursion until we find a nodeParent as ancestor of nodeChild.\n // return a bool\n const go = node => {\n //Direct parent of our current node\n if(node === nodeParent) {\n return true;\n }\n else if(node === this.root)\n return false;\n else {\n let [, , directParent,] = this.find(node.value);\n return go(directParent);\n }\n };\n return go(nodeChildDirectParent);\n\n }",
"function findParents(node){\n\t\tvar rst = [];\n\t\tvar currentNode = node.parent;\n\t\twhile(currentNode!==null){\n\t\t\trst.unshift(currentNode);\n\t\t\tcurrentNode = currentNode.parent;\n\t\t}\n\t\treturn rst;\n\t}",
"isParent(path, another) {\n return path.length + 1 === another.length && Path.compare(path, another) === 0;\n }",
"function hasAncestor(l, ance) {\n var tick, ancestor, ancestors = [1, 2, 3, 4, 5];\n\n if (typeof ance === 'string') {\n ancestor = queryDOM(ance);\n } else {\n ancestor = ance;\n }\n\n ancestors[0] = l.parentNode;\n ancestors[1] = ancestors[0].parentNode;\n\n if (!!ancestors[1].parentNode) {\n ancestors[2] = ancestors[1].parentNode;\n }\n if (!!ancestors[2].parentNode) {\n ancestors[3] = ancestors[2].parentNode;\n }\n if (!!ancestors[3].parentNode) {\n ancestors[4] = ancestors[3].parentNode;\n }\n //For inspection....\n // var dir = {};\n // dir.ance = ance;\n // dir.l = l;\n // dir.ancestor = ancestor;\n // dir.ancestors = ancestors;\n //\n // console.log(dir);\n\n tick = 0;\n\n for (var i = 0; i < ancestors.length; i++) {\n if (ancestors[i] === ancestor) tick++;\n }\n if (tick > 0) return true;\n\n else return false;\n}",
"listOfAncestorsToBeLoadedForLevel(numGens = 10) {\n let theList = [];\n let maxNum = this.list.length;\n let maxNumInGen = 2 ** numGens;\n let theMax = Math.min(maxNum, maxNumInGen);\n\n let minNum = 1;\n let minNumInGen = 2 ** (numGens - 1);\n let theMin = Math.max(minNum, minNumInGen);\n\n for (var i = theMin; i < theMax; i++) {\n if (this.list[i] && this.list[i] > 0 && thePeopleList[this.list[i]]) {\n let thePeep = thePeopleList[this.list[i]];\n if (thePeep._data.Father && thePeep._data.Father > 0 && theList.indexOf(thePeep._data.Father) == -1) {\n if (thePeopleList[thePeep._data.Father]) {\n // father already exists, so don't need to re-load him\n } else {\n theList.push(thePeep._data.Father);\n }\n }\n if (thePeep._data.Mother && thePeep._data.Mother > 0 && theList.indexOf(thePeep._data.Mother) == -1) {\n if (thePeopleList[thePeep._data.Mother]) {\n // Mother already exists, so don't need to re-load her\n } else {\n theList.push(thePeep._data.Mother);\n }\n }\n\n // condLog(\"--> PUSHED !\",thisAncestor.ahnNum, thisAncestor.person._data.Id);\n }\n }\n condLog(\"listOfAncestorsToBeLoadedForLevel has \", theList.length, \" ancestors.\");\n return theList;\n }",
"function question2(pairs, A, B) {\n let indegree = new Map();\n let parentMap = new Map();\n for (let pair of pairs) {\n let parent = pair[0];\n let child = pair[1];\n\n if (!indegree.has(parent)) indegree.set(parent, 0);\n indegree.set(child, (indegree.get(child) || 0) + 1);\n\n let parentSet = parentMap.get(child) || [];\n parentSet.push(parent);\n parentMap.set(child, parentSet);\n }\n\n if (indegree.get(A) === 0 || indegree.get(B) === 0) return false;\n\n let ancestorOfA = new Set();\n getAncestor(A, ancestorOfA);\n let ancestorOfB = new Set();\n getAncestor(B, ancestorOfB);\n\n for (let el of ancestorOfA) {\n if (ancestorOfB.has(el)) return true;\n }\n\n return false;\n\n function getAncestor(child, list) {\n let queue;\n queue = parentMap.get(child);\n list.add(child);\n\n while (queue.length) {\n let curr = queue.shift();\n list.add(curr);\n let currParents = parentMap.get(curr) || [];\n for (let el of currParents) {\n queue.push(el);\n }\n }\n }\n}",
"parent() {\n\t const parents = [];\n\t this.each(el => {\n\t if (!parents.includes(el.parentNode)) {\n\t parents.push(el.parentNode);\n\t }\n\t });\n\t return new DOMNodeCollection(parents);\n\t }",
"ensureParentExist() {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n const collection = this.database.collection('choices');\n const parent = yield collection.findOne({\n id: this.parentId\n });\n if (!parent) {\n reject(new Error(`Unable to find the parent '${this.parentId}'`));\n return;\n }\n resolve();\n }));\n });\n }",
"function openParents(range, topRow, column, row, cell)\n{\n //Grab the parent we're currently examining\n var parent = range[row][column];\n\n //If the parent we're examining isn't empty...\n if (hasData(parent))\n {\n //And the cell to the left isn't the same (indicating a new parent)\n //or the cell is on the topRow (indicating it's a bottom-level parent)\n if ((range[row][column-1] != parent) || (row == topRow))\n {\n //Append the cell with a a new parent tag\n cell = openElement(parent) + cell;\n }\n }\n\n //If we're not at the top of the spreadsheet, move up a row and call this function again\n if (row > 0)\n {\n row = row-1;\n return openParents(range, topRow, column, row, cell);\n }\n \n //If we are at the top of the spreadsheet, it's time to stop and return the cell\n return cell;\n}",
"function childIsEmpty(arr, a){\n\tn = arr.length\n\tfor(var i = 0;i < n;i++){\n\t\tif(arr[i].length != 0)\n\t\t\tcontinue\n\t\telse return i\n\t}\n\treturn a\n}",
"function preceding( jq, expr ) {\n\tvar found;\n\t$(jq).parents().each(function() {\n\t\t// Check the parent and then it's preceding siblings\n\t\tfound = self(this, expr) || prevSiblings(this, expr);\n\t\treturn !found;\n\t});\n\treturn found;\n}",
"function GetSpaceParent(){\n var deferred = $q.defer();\n\n var spaceParents = [];\n angular.forEach(\n //Drupal.settings space_parents is json string\n\n JSON.parse(Drupal.settings.Api.space_parents), \n function (value, key) {\n this.push(new Node(key,value)); \n },\n spaceParents\n );\n deferred.resolve(spaceParents);\n\n return deferred.promise; \n }",
"function moreAboutKaren(parents, noOfSiblings, isNuclearFamily) {\n if (typeof parents === \"string\") {\n return true;\n } else {\n return false;\n }\n if (typeof noOfSiblings == \"number\") {\n return true;\n } else {\n return false;\n }\n if (typeof isNuclearFamily == \"boolean\") {\n return true;\n } else {\n return false;\n }\n}",
"static ancestorIds(id) {\n let parent = stacks[id]\n let ids = []\n\n ids.push(parent.id)\n while ((parent = Stack.getStackFrame(parent.id).parent)) {\n ids.push(parent.id)\n }\n\n return ids\n }",
"parentHashes(str) {\n if (Objects.type(str) === 'commit') {\n return str.split('\\n')\n .filter(line => line.match(/^parent/))\n .map(line => line.split(' ')[1]);\n }\n }",
"findFsParents () {\n for (const path of this.linkTargets) {\n const node = this.cache.get(path)\n if (!node.parent && !node.fsParent) {\n for (let p = dirname(path); p;) {\n if (this.cache.has(p)) {\n node.fsParent = this.cache.get(p)\n p = null\n } else {\n // walk up the tree until p === dirname(p)\n const pp = dirname(p)\n if (pp === p)\n p = null\n else\n p = pp\n }\n }\n }\n }\n }",
"function getBestParent(point){\n\t\tlet currCost, neighbors = getNeighbors(point)\n\t\treturn neighbors.reduce((best, neighbor) => {\n\t\t\tcurrCost = NODES[neighbor].cost + getDistance(point, NODES[neighbor])\n\t\t\tif(!edgeCollision(point, NODES[neighbor]) && (best[1] === null || currCost < best[1])) best = [neighbor, currCost]\n\t\t\treturn best\n\t\t}, [0, null])\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fn upload file to game | function upload(file) {
return Games.upload($game.id, file)
.then(function (res) {
// update game
vm.game.src = res.src;
$rootScope.$broadcast('game:uploaded');
}, function (error) {
console.log('error upload: ', error);
});
} | [
"function uploadImage(filename) {\n \n var req = request.post(config.webhookUrl, function (err, resp, body) {\n if(err) {\n console.log(err);\n }\n // console.log('sent image', fileName);\n });\n \n var form = req.form();\n form.append('file', fs.createReadStream(filename));\n form.append('content', config.username);\n }",
"function openUploadFile() {\n $('#game-file').click();\n }",
"_uploadFile(upload, file) {\n const formData = new FormData();\n\n // Copy the keys from our upload instructions into the form data\n for (const key in upload.fields) {\n formData.append(key, upload.fields[key]);\n }\n\n // AWS ignores all fields in the request after the file field, so all other\n // fields must appear before the file.\n formData.append('file', file);\n\n // Now we can upload the file\n fetch(upload.url, {\n method: 'post',\n body: formData\n }).then((response) => {\n if (response.ok) {\n this._finalizeFileUpload(upload, file);\n } else {\n this.options.onError(new AssetUploaderError(\"There was an error uploading the file. Please try again.\"));\n }\n });\n }",
"function upload() {\n\n isCanceled = false;\n indexNumbers = [];\n space = undefined;\n progress = 0;\n let path = $('#file-chooser').val();\n if (validatePath(path) & validateKey.call($('#space-key')) & validateTitle.call($('#space-title'))) {\n space = {\n name: $('#space-title').val(),\n key: $('#space-key').val()\n };\n setUploadMessage(i18n.PREPARING_FOR_UPLOAD, \"generic\");\n createDialog();\n if (AJS.$('#radioButtonUpdate').prop(\"checked\")) {\n\n } else if (AJS.$('#radioButtonClone').prop(\"checked\")) {\n specif = specIFLoader(URL.createObjectURL($('#file-chooser').prop('files')[0]), i18n, cloneToOldSpace, error);\n } else {\n specif = specIFLoader(URL.createObjectURL($('#file-chooser').prop('files')[0]), i18n, deleteOldSpace, error);\n }\n\n }\n }",
"function uploadFile(file) {\n const storageRef = firebase.storage().ref('uploads/' + file.name);\n const task = storageRef.put(file);\n\n task.on('state_changed',\n function progress(snap) {\n var progress = (snap.bytesTransferred / snap.totalBytes) * 100;\n uploadProgress.value = progress\n },\n\n function error(err) {\n console.error(err);\n },\n\n function complete() {\n task.snapshot.ref.getDownloadURL().then(function (downloadURL) {\n analysedImage.src = downloadURL;\n });\n const storedPath = task.snapshot.ref.fullPath;\n // Create request to vision\n submitToVision(storedPath);\n\n // Clear input and progress\n uploadProgress.removeAttribute('value');\n fileInput.value = \"\";\n }\n )\n}",
"function uploadProg() {\r\n\r\n // The fileUpload input box (hidden) declared in grid_main.html\r\n // is used to select the file. We just click the 'chose file' button\r\n // contained in that input element. When we automatically click the \r\n // input element below, we execute uploadFileContents() routine.\r\n //\r\n var upelem = document.getElementById('fileUpload');\r\n upelem.click();\r\n}",
"function writeFile(fldr, fileBlob, scrnBlob, username, usrClass, respForm, doFbPost, message) {\r\n \r\n // create file on google drive. Save the drive\r\n // file object and send it to be renamed to match\r\n // <username>_<class>_<form>.<extension> format\r\n if (fileBlob.getName()) {\r\n var drive_file = fldr.createFile(fileBlob)\r\n // get the file extension:\r\n var extension = getExtension(fileBlob)\r\n // rename file:\r\n drive_file.setName(username + \"_\" + usrClass + \r\n \"_\" + respForm + \"_geoselfie.\" + extension);\r\n }\r\n \r\n // if image was uploaded:\r\n if (scrnBlob.getName()) {\r\n var drive_file_scrn = fldr.createFile(scrnBlob)\r\n var extension_scrn = getExtension(scrnBlob)\r\n \r\n drive_file_scrn.setName(username + \"_\" + usrClass + \"_\" + respForm + \"_screenshot.\" + extension);\r\n }\r\n \r\n // update spreadsheeet to include class:\r\n update_sheet(respForm, usrClass); \r\n \r\n Logger.log(\"doFbPost: \" + doFbPost);\r\n Logger.log(\"message: \" + message);\r\n if (doFbPost == 'doFbPost') {\r\n drive_file.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.EDIT);\r\n var url = 'https://docs.google.com/uc?id=' + drive_file.getId();\r\n Logger.log('photo url: ' + url);\r\n fncPostItemFB(url, message);\r\n }\r\n}",
"upload(e){\n if(e.target.files.length) this.handleFile(e.target.files[0])\n }",
"function processForm(form) {\r\n // CONSTANT: id for destination folder\r\n var FOLDER_ID = '<Google folder ID>' // production folder\r\n \r\n // file uploaded through form:\r\n var fileBlob = form.fileUpload;\r\n // screen shot uploaded:\r\n var scrnBlob = form.fileGCXUpload;\r\n // class uploader belongs to:\r\n var usrClass = form.usrClass\r\n // form uploader is responding to:\r\n var respForm = form.respForm;\r\n // post to facebook process:\r\n var doFbPost = form.postToFB;\r\n // post to facebook caption:\r\n var message = form.postCaption;\r\n \r\n // Debug: log file name, file type, and fileblob object details\r\n Logger.log(\"fileBlob name: \" + fileBlob.getName())\r\n Logger.log(\"fileBlob type: \" + fileBlob.getContentType())\r\n Logger.log(\"fileBlob \" + fileBlob)\r\n \r\n // open folder for file upload:\r\n var fldr = DriveApp.getFolderById(FOLDER_ID)\r\n // get user information:\r\n var username = getUsername()\r\n \r\n // write file to drive:\r\n writeFile(fldr, fileBlob, scrnBlob, username, usrClass, respForm, doFbPost, message)\r\n \r\n}",
"function uploadFileToMongo(fileBlob, fileName, callback) {\r\n var url = appx_session.uploadURL + encodeURI(fileName.replace(/ /g, \"_\"));\r\n var xhr = new XMLHttpRequest;\r\n xhr.open(\"POST\", url);\r\n xhr.onreadystatechange = function () {\r\n if (xhr.readyState === 4 && xhr.status === 201) {\r\n appxClearStatusMsgText();\r\n appxSetStatusText(\"File upload to server complete...\");\r\n $(\"#main\").unblock();\r\n if (callback) {\r\n callback();\r\n }\r\n }\r\n }\r\n xhr.send(fileBlob);\r\n}",
"function uploadJSON() {\r\n\r\n}",
"static upload(fileData){\n\t\tlet kparams = {};\n\t\tlet kfiles = {};\n\t\tkfiles.fileData = fileData;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'upload', kparams, kfiles);\n\t}",
"function uploadPhoto(){\n if (isFromCamera == true) {\n var ft = new FileTransfer();\n var options = new FileUploadOptions();\n\n options.fileKey = \"image\";\n // we use the file name to send the username\n options.fileName = \"filename.jpg\"; \n options.mimeType = \"image/jpeg\";\n options.chunkedMode = false;\n options.params = { \n \"username\": username\n };\n\n ft.upload(imageSavedURI, encodeURI(serverURL + \"upload.php\"),\n function (e) {\n alert(\"Image uploaded\");\n },\n function (e) {\n alert(\"Upload failed\");\n }, \n options\n );\n } else {\n var formdata = new FormData();\n formdata.append(\"image\", file);\n formdata.append(\"username\", username);\n var ajax = new XMLHttpRequest();\n ajax.upload.addEventListener(\"progress\", progressHandler, false);\n ajax.addEventListener(\"load\", completeHandler, false);\n ajax.addEventListener(\"error\", errorHandler, false);\n ajax.addEventListener(\"abort\", abortHandler, false);\n ajax.open(\"POST\", serverURL + \"upload.php\");\n ajax.send(formdata);\n }\n}",
"function uploadTeamFile(filter_str, start_func, update_func) {\n // upload file about team\n $(filter_str).fileupload({\n type: 'POST',\n url: CONFIG.apiconfig.proxy + '/api/user/file?file_type=team_file',\n dataType: 'json',\n beforeSend: function (xhr, data) {\n xhr.setRequestHeader('token', $.cookie('token'));\n xhr.setRequestHeader('Authorization', \"token \" + $.cookie('token'));\n },\n start: start_func,\n done: function (e, obj) {\n var data = obj.result;\n if (data.error || ! \"files\" in data || data.files.length == 0) {\n oh.comm.alert('错误', data.error.friendly_message);\n } else {\n var url = data.files[0].url;\n update_func(url);\n }\n }\n });\n }",
"function uploadFile() {\n\t\t$.ajax({\n\t\t\turl : \"/api/brailleapplication/uploadFile\",\n\t\t\ttype : \"POST\",\n\t\t\tdata : new FormData($(\"#upload-file-form\")[0]),\n\t\t\tenctype : 'multipart/form-data',\n\t\t\tprocessData : false,\n\t\t\tcontentType : false,\n\t\t\tcache : false,\n\t\t\tsuccess : function() {\n\t\t\t\tpreviewFile();\n\t\t\t},\n\t\t\terror : function() {\n\t\t\t}\n\t\t});\n\t} // function uploadFile ",
"upload3DTexture () {\n\n }",
"uploadResource (itemId, owner, file, filename, replace = false, portalOpts) {\n let action = this.addResource.bind(this);\n if (replace) {\n action = this.updateResource.bind(this);\n }\n return action(itemId, owner, filename, file, portalOpts);\n }",
"onFileUploadSubmit(e){\n\t\te.preventDefault();\n\t\tconst self = this,\n\t\t\t files = document.getElementById('olyauth.file').files;\n\n\t\t//Users.User.uploadProfileImage({email:this.state.user.email,files})\n\t\t//\t.then(user=>{\n\t\t//\t\tl(this.state.user,user);\n\t\t//\t\tthis.setState({user});\n\t\t//\t\tthis.toggleProfileUpload();\n\t\t//\t});\n\t}",
"function FileUpload(file, options) {\n var fileCreationOptions, getServerFile, key, minParts, _i, _len, _ref;\n this.file = file;\n if (options == null) {\n options = {};\n }\n this._onUploadProgress = __bind(this._onUploadProgress, this);\n options = $.extend({\n folder: \"/\"\n }, options);\n _ref = [\"folder\", \"partSize\", \"fileCreationPool\", \"workerPool\", \"uploadPool\", \"api\", \"projectID\", \"minimumPartSize\", \"maximumPartSize\", \"maximumFileSize\", \"maximumNumParts\", \"emptyLastPartAllowed\"];\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n key = _ref[_i];\n if (options[key] == null) {\n throw new Error(\"Required parameter \" + key + \" is not specified\");\n }\n this[key] = options[key];\n }\n this.partSize = Math.max(Math.ceil(this.file.size / options.maximumNumParts), this.partSize, this.minimumPartSize);\n if (this.partSize < this.minimumPartSize) {\n throw new Error(\"Part size is less than the minimum allowed! (\" + this.partSize + \" vs. \" + this.minimumPartSize + \")\");\n } else if (this.partSize > this.maximumPartSize) {\n throw new Error(\"Part size is more than the maximum allowed! (\" + this.partSize + \" vs. \" + this.maximumPartSize + \")\");\n }\n if (this.file.size > this.maximumFileSize) {\n throw new Error(\"File size for '\" + this.file.name + \"' is too large! (\" + this.file.size + \" vs. \" + this.maximumFileSize + \")\");\n }\n this._uploadProgress = $.Deferred();\n this._checksumProgress = $.Deferred();\n this._closingProgress = $.Deferred();\n this._uploadCalls = {};\n this._uploadsDone = 0;\n this._bytesUploaded = 0;\n this._bytesResumed = 0;\n this._aborted = false;\n this._closing = false;\n this._closed = false;\n minParts = this.emptyLastPartAllowed ? 1 : 0;\n this.numParts = Math.max(minParts, Math.ceil(this.file.size / this.partSize));\n if (this.numParts > this.maximumNumParts) {\n throw new Error(\"Too many parts for '\" + this.file.name + \"'! (\" + this.numParts + \" vs. \" + this.maximumNumParts + \")\");\n }\n this.uploadStartedAt = null;\n this._checksumQueue = [];\n this._uploadQueue = [];\n this._parts = [];\n this._partUploadProgress = [];\n this._uploadPoolClientID = this.uploadPool.acquireClientID(\"file_upload_\");\n this._workerPoolClientID = this.workerPool.acquireClientID(\"file_worker_\");\n this.isDirectory = false;\n fileCreationOptions = {\n folder: this.folder,\n tags: options.tags,\n properties: options.properties\n };\n this.fileCreationStatus = $.Deferred();\n getServerFile = (function(_this) {\n return function() {\n return _this.fileCreationPool.acquire().done(function(createFileToken) {\n return FileUpload.prototype.findOrCreateFile(file, _this.api, _this.partSize, _this.projectID, fileCreationOptions).done(function(data) {\n var existingParts, i, part, start, _j, _ref1, _ref2, _ref3;\n existingParts = (_ref1 = data.parts) != null ? _ref1 : {};\n _this.fileID = data.fileID;\n for (i = _j = 0, _ref2 = _this.numParts; 0 <= _ref2 ? _j < _ref2 : _j > _ref2; i = 0 <= _ref2 ? ++_j : --_j) {\n start = _this.partSize * i;\n part = {\n index: i + 1,\n start: start,\n stop: Math.min(_this.file.size, start + _this.partSize)\n };\n _this._parts.push(part);\n if (((_ref3 = existingParts[i + 1]) != null ? _ref3.state : void 0) === \"complete\") {\n _this._uploadsDone += 1;\n _this._bytesResumed += part.stop - part.start;\n } else {\n _this._checksumQueue.push(part);\n }\n }\n _this._onUploadProgress();\n return _this.fileCreationStatus.resolve(_this.fileID);\n }).fail(function(error) {\n return _this.fileCreationStatus.reject(error);\n }).always(function() {\n return _this.fileCreationPool.release(createFileToken);\n });\n });\n };\n })(this);\n if (this.file.size < 1 * MB) {\n this.readBytes(0, 10).done(getServerFile).fail((function(_this) {\n return function() {\n var errorObject;\n _this.isDirectory = true;\n errorObject = {\n error: {\n type: \"InvalidType\",\n message: \"File is a directory and cannot be uploaded\"\n }\n };\n _this.fileCreationStatus.reject(errorObject);\n _this._uploadProgress.reject(errorObject);\n _this._checksumProgress.reject(errorObject);\n return _this._closingProgress.reject(errorObject);\n };\n })(this));\n } else {\n getServerFile();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads container configuration from JSON or YAML file. The type of the file is determined by file extension. | static readFromFile(correlationId, path, parameters) {
if (path == null)
throw new pip_services_commons_node_1.ConfigException(correlationId, "NO_PATH", "Missing config file path");
let ext = path.split('.').pop();
if (ext == "json")
return ContainerConfigReader.readFromJsonFile(correlationId, path, parameters);
if (ext == "yaml" || ext == "yml")
return ContainerConfigReader.readFromYamlFile(correlationId, path, parameters);
// By default read as JSON
return ContainerConfigReader.readFromJsonFile(correlationId, path, parameters);
} | [
"function loadConfig() {\n\tconfig_file = fs.readFileSync(\"./config.json\");\n\tconfig = JSON.parse(config_file);\n}",
"async load() {\n await this.ensureExists();\n this.conf = await fs.readJSON(this.location);\n }",
"function parseFileContents(path, extension) {\n switch (extension) {\n case 'yml': return parseYamlFile(path); break;\n case 'json': return parseJsonFile(path); break;\n default: return { error: `file extension: \"${extension}\" is not compatible.`}; break;\n }\n}",
"function parseYamlFile(path) {\n let parsed;\n try { parsed = yaml.safeLoad(fs.readFileSync(path, 'utf8')) }\n catch (err) { parsed = { error: err.message } };\n return parsed;\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 readConfig() {\n fetch(\"/config/modules.json\")\n .then(response => response.json())\n .then(data => (config = data))\n .then(printModules);\n}",
"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 }",
"function _load_hit_config() {\n var content = fs.readFileSync(task_directory_name + '/hit_config.json');\n return JSON.parse(content);\n}",
"function loadJSON(file) {\n return JSON.parse(FS.readFileSync(file, \"utf8\"));\n}",
"load(environment) {\n if (environment && environment.match(/[a-z]+/)) {\n environment = '.' + environment;\n } else {\n environment = '';\n }\n var err = new Error('Invalid configuration file, JSON expected. Check /config' + environment + '.json');\n this.$http.get('/config' + environment + '.json').success((result) => {\n if (!_.isObject(result)) {\n throw err;\n }\n this._loadingDeferred.resolve(result);\n }).error((e) => {\n err.details = e;\n throw err;\n });\n }",
"function loadConfigurationFromPath(configFilePath) {\n if (configFilePath == null) {\n return exports.DEFAULT_CONFIG;\n }\n else {\n var resolvedConfigFilePath = resolveConfigurationPath(configFilePath);\n var rawConfigFile = void 0;\n if (path.extname(resolvedConfigFilePath) === \".json\") {\n var fileContent = utils_1.stripComments(fs.readFileSync(resolvedConfigFilePath)\n .toString()\n .replace(/^\\uFEFF/, \"\"));\n rawConfigFile = JSON.parse(fileContent);\n }\n else {\n rawConfigFile = require(resolvedConfigFilePath);\n delete require.cache[resolvedConfigFilePath];\n }\n var configFileDir_1 = path.dirname(resolvedConfigFilePath);\n var configFile = parseConfigFile(rawConfigFile, configFileDir_1);\n // load configurations, in order, using their identifiers or relative paths\n // apply the current configuration last by placing it last in this array\n var configs = configFile.extends.map(function (name) {\n var nextConfigFilePath = resolveConfigurationPath(name, configFileDir_1);\n return loadConfigurationFromPath(nextConfigFilePath);\n }).concat([configFile]);\n return configs.reduce(extendConfigurationFile, exports.EMPTY_CONFIG);\n }\n}",
"function ParseConfiguration (err, data)\n{\n if (err)\n return console.log (err);\n\n config = JSON.parse (data);\n\n SetupClient ();\n}",
"function getFromFile() {\n try {\n const proxyPath = path.resolve(`${process.cwd()}/${config.proxy_file}`);\n return JSON.parse(fs.readFileSync(proxyPath, \"utf8\"));\n } catch (e) {\n return null;\n }\n }",
"function loadJSON() {\n return {\n resolve: {\n extensions: [\".json\"],\n },\n };\n}",
"async readConfigFile(configFilePath) {\n let tailwindConfigFile = nova.fs.open(configFilePath)\n let contents = tailwindConfigFile.readlines()\n let newContents = ''\n\n tailwindConfigFile.close()\n\n // Remove any lines including the require, such as 'require('@tailwindcss/forms')'\n contents.forEach((line) => {\n if (!line.includes('require(')) {\n newContents = newContents + line\n }\n })\n\n let configObject = eval(newContents)\n\n return configObject\n }",
"async readContainer() {\n const { resource: containerDefinition } = await this.client\n .database(this.databaseId)\n .container(this.containerId)\n .read()\n console.log(`Reading container:\\n${containerDefinition.id}\\n`)\n }",
"function parseConfig(contents, config) {\n contents.server = contents.server || {};\n contents.proxy = contents.proxy || {};\n\n if (contents.proxy.gateway && typeof(contents.proxy.gateway) === \"string\" && contents.proxy.gateway.length > 0) {\n contents.proxy.gateway = parseGateway(contents.proxy.gateway);\n }\n\n contents.proxy.forward = parseConfigMap(contents.proxy.forward, parseForwardRule);\n contents.proxy.headers = parseConfigMap(contents.proxy.headers, parseHeaderRule);\n\n // override any values in the config object with values specified in the file;\n config.server.port = contents.server.port || config.server.port;\n config.server.webroot = contents.server.webroot || config.server.webroot;\n config.server.html5mode = contents.server.html5mode || config.server.html5mode;\n config.proxy.gateway = contents.proxy.gateway || config.proxy.gateway;\n config.proxy.forward = contents.proxy.forward || config.proxy.forward;\n config.proxy.headers = contents.proxy.headers || config.proxy.headers;\n\n return config;\n}",
"function read(pathIn) {\n var myConfig = configObjectFromParamsOptions(getConfig());\n var myPath = pathIn.split('.');\n for (var i = 0; i < myPath.length; i++) {\n myConfig = typeof myConfig[myPath[i]] !== 'undefined' ? myConfig[myPath[i]] : myConfig[myPath[i]] = {};\n }\n var x = {};\n x[pathIn] = myConfig;\n return typeof myConfig === 'object' ? list(x) : pathIn + '=' + myConfig;\n }",
"function getDataSource() {\n let config = jsonfile.readFileSync(\"server/config.json\");\n\n return config.dataSource == \"jsonfile\" ? require(\"./JsonFileSource\") : require(\"./MongoDbSource\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
'keystroke ...' keymaps automatically work only for the user's ~/.atom/keymap.cson keymaps. We have to manually register them for our own package keymap/ keymaps. | consumeKeystroke(keystroke) {
atom.packages.getLoadedPackage(packageName).getKeymapPaths().forEach(path => {
this.disposables.add(
keystroke.registerKeystrokeCommandsFromFile(path),
);
});
} | [
"function tm_keystroke() {\n\n tm_keystrokes++;\n tm_calculate();\n}",
"function Keymap(){\r\n this.map = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\r\n 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'backspace', 'enter', 'shift', 'delete'];\r\n }",
"function extendedOnKeyPress() {\r\n this._handleEscapeToHome()\r\n originalOnKeyPress()\r\n }",
"addShortcut(keys, callback) {\n Mousetrap.bind(keys, callback)\n }",
"resetToDefault() {\n const command = this.edits.rowEl.dataset.command;\n const defaultMapping = Commands.defaultMappings.normal[command];\n this.edits.keyStrings = defaultMapping ? defaultMapping.split(Commands.KEY_SEPARATOR) : [];\n this.displayKeyString(this.edits.rowEl.querySelector(\".shortcut\"), defaultMapping);\n this.commitChange();\n }",
"function input_character_keys(key_array_index, event_type, character_key_index, key_code) {\r\n\tkey_array[key_array_index].addEventListener(event_type, function(event) {\r\n\t\tif (event_type == \"keydown\" && document.getElementById(\"mirrored_textarea\") != document.activeElement) {\r\n\t\t\tif (event.key === \" \" || event.key === \"Enter\" || event.key === \"Spacebar\") {\r\n\t\t\t\ttoggle_button(event.target);\r\n\t\t\t\tevent.preventDefault();\r\n\t\t\t\tedit_textarea(character_key_index);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tevent.preventDefault();\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t}\r\n\t});\r\n\r\n\tdocument.addEventListener(\"keydown\", function(event) {\r\n\t\tif (event.defaultPrevented) {\r\n\t\t\treturn; // Do nothing if event already handled\r\n\t\t}\r\n\t\tif (event.code == key_code && modifier_key_pressed == false) {\r\n\t\t\ttoggle_button(event.target);\r\n\t\t\tkey_button_array[key_array_index].classList.add(\"focus\");\r\n\t\t\tsetTimeout(function () {key_button_array[key_array_index].classList.remove(\"focus\");}, 250);\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t\tevent.preventDefault();\r\n\t\t}\r\n\t});\r\n}",
"function keyPressed() {\n changeSnakeDir(keyCode);\n}",
"_keyboardShortcuts() {\n browser.commands.onCommand.addListener((command) => {\n if (command === 'action-accept-new') {\n this.app.modules.calls.callAction('accept-new')\n } else if (command === 'action-decline-hangup') {\n this.app.modules.calls.callAction('decline-hangup')\n } else if (command === 'action-dnd') {\n // Only toggle when calling options are enabled and webrtc is enabled.\n if (!this.app.helpers.callingDisabled() && this.app.state.settings.webrtc.enabled) {\n this.app.setState({availability: {dnd: !this.app.state.availability.dnd}})\n }\n } else if (command === 'action-hold-active') {\n this.app.modules.calls.callAction('hold-active')\n }\n })\n }",
"function keyTyped() {\n mode = key;\n}",
"function Keymap(keys, options) {\n\t this.options = options || {}\n\t this.bindings = Object.create(null)\n\t if (keys) this.addBindings(keys)\n\t }",
"function main() {\n drawMap();\n setupKeyboardControls();\n }",
"function keyTap(key = '', modified = []) {\n try {\n robot.keyTap(key, modified)\n } catch (err) {\n // Only on debug\n console.error(err);\n }\n}",
"function keyPressed() {\n if (keyCode == 32) {\n if (strokeToggle) {\n stroke(0);\n } else {\n noStroke();\n }\n strokeToggle = !strokeToggle;\n }\n if (keyCode == LEFT_ARROW) {\n circleSize = circleSize - 10;\n }\n if (keyCode == RIGHT_ARROW) {\n circleSize = circleSize + 10;\n }\n if (keyCode == UP_ARROW) {\n toggle++;\n toggle = toggle % 3;\n }\n if (keyCode == DOWN_ARROW) {\n toggle++;\n toggle = toggle % 3;\n }\n}",
"function keyEvent() {\n for (const key of keyboard) {\n key.addEventListener(\"click\", keyboardClick);\n }\n}",
"function kaTool_redirect_onkeypress(e) {\r\n if (document.kaCurrentTool) {\r\n document.kaCurrentTool.onkeypress(e);\r\n }\r\n}",
"function CssViewerKeyMap(e) {\n\tif( ! cssViewer.IsEnabled() )\n\t\treturn;\n\n\t// ESC: Close the css viewer if the cssViewer is enabled.\n\tif ( e.keyCode === 27 ){\n\t\t// Remove the red outline\n\t\tCSSViewer_current_element.style.outline = '';\n\t\tcssViewer.Disable();\n\t}\n\t\n\tif( e.altKey || e.ctrlKey )\n\t\treturn;\n\n\t// f: Freeze or Unfreeze the css viewer if the cssViewer is enabled\n\tif ( e.keyCode === 70 ){\n\t\tif ( cssViewer.haveEventListeners ){\n\t\t\tcssViewer.Freeze();\n\t\t}\n\t\telse {\n\t\t\tcssViewer.Unfreeze();\n\t\t}\n\t}\n\n\t// c: Show code css for selected element. \n\t// window.prompt should suffice for now.\n\tif ( e.keyCode === 67 ){\n\t\twindow.prompt(\"Simple Css Definition :\\n\\nYou may copy the code below then hit escape to continue.\", CSSViewer_element_cssDefinition);\n\t}\n}",
"function setHotKeys() {\n\tdocument.onkeydown = function(ev) {\n\t\tev = ev||window.event;\n\t\tkey = ev.keyCode||ev.which;\n\t\tif (key == 18 && !ev.ctrlKey) {\t// start selection, skip Win AltGr\n\t\t\t_hotkeys.alt = true;\n\t\t\t_hotkeys.focus = -1;\n\t\t\treturn stopEv(ev);\n\t\t}\n\t\telse if (ev.altKey && !ev.ctrlKey && ((key>47 && key<58) || (key>64 && key<91))) {\n\t\t\tkey = String.fromCharCode(key);\n\t\t\tvar n = _hotkeys.focus;\n\t\t\tvar l = document.getElementsBySelector('[accesskey='+key+']');\n\t\t\tvar cnt = l.length;\n\t\t\t_hotkeys.list = l;\n\t\t\tfor (var i=0; i<cnt; i++) {\n\t\t\t\tn = (n+1)%cnt;\n\t\t\t\t// check also if the link is visible\n\t\t\t\tif (l[n].accessKey==key && (l[n].offsetWidth || l[n].offsetHeight)) {\n\t\t\t\t\t_hotkeys.focus = n;\n\t // The timeout is needed to prevent unpredictable behaviour on IE.\n\t\t\t\t\tvar tmp = function() {l[_hotkeys.focus].focus();};\n\t\t\t\t\tsetTimeout(tmp, 0);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn stopEv(ev);\n\t\t}\n\t\tif((ev.ctrlKey && key == 13) || key == 27) {\n\t\t\t_hotkeys.alt = false; // cancel link selection\n\t\t\t_hotkeys.focus = -1;\n\t\t\tev.cancelBubble = true;\n \t\t\tif(ev.stopPropagation) ev.stopPropagation();\n\t\t\t// activate submit/escape form\n\t\t\tfor(var j=0; j<this.forms.length; j++) {\n\t\t\t\tvar form = this.forms[j];\n\t\t\t\tfor (var i=0; i<form.elements.length; i++){\n\t\t\t\t\tvar el = form.elements[i];\n\t\t\t\t\tvar asp = el.getAttribute('aspect');\n\n\t\t\t\t\tif (!string_contains(el.className, 'editbutton') && (asp && asp.indexOf('selector') !== -1) && (key==13 || key==27)) {\n\t\t\t\t\t\tpassBack(key==13 ? el.getAttribute('rel') : false);\n\t\t\t\t\t\tev.returnValue = false;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (((asp && asp.indexOf('default') !== -1) && key==13)||((asp && asp.indexOf('cancel') !== -1) && key==27)) {\n\t\t\t\t\t\tif (validate(el)) {\n\t\t\t\t\t\t\tif (asp.indexOf('nonajax') !== -1)\n\t\t\t\t\t\t\t\tel.click();\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\tif (asp.indexOf('process') !== -1)\n\t\t\t\t\t\t\t\tJsHttpRequest.request(el, null, 600000);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tJsHttpRequest.request(el);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tev.returnValue = 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\tev.returnValue = false;\n\t\t\treturn false;\n\t\t}\n\t\tif (editors!==undefined && editors[key]) {\n\t\t\tcallEditor(key);\n\t\t\treturn stopEv(ev); // prevent default binding\n\t\t}\n\t\treturn true;\n\t};\n\tdocument.onkeyup = function(ev) {\n\t\tev = ev||window.event;\n\t\tkey = ev.keyCode||ev.which;\n\n\t\tif (_hotkeys.alt==true) {\n\t\t\tif (key == 18) {\n\t\t\t\t_hotkeys.alt = false;\n\t\t\t\tif (_hotkeys.focus >= 0) {\n\t\t\t\t\tvar link = _hotkeys.list[_hotkeys.focus];\n\t\t\t\t\tif(link.onclick)\n\t\t\t\t\t\tlink.onclick();\n\t\t\t\t\telse\n\t\t\t\t\t\tif (link.target=='_blank') {\n\t\t\t\t\t\t\twindow.open(link.href,'','toolbar=no,scrollbar=no,resizable=yes,menubar=no,width=900,height=500');\n\t\t\t\t\t\t\topenWindow(link.href,'_blank');\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\twindow.location = link.href;\n\t\t\t\t}\n\t\t\treturn stopEv(ev);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n}",
"function enableKeyEvents() {\n lumx.isFocus = true;\n $document.on('keydown keypress', _onKeyPress);\n }",
"function registerNavigationKeys(keynapse){\n\tkeynapse.listener.simple_combo(\"tab\", nextKnCell);\n\tkeynapse.listener.simple_combo(\"enter\", selectKnCell);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display grid_one or grid_two | function showGridOne() {
if (!gridOneVisible) {
gridOne.style.display = "inline";
gridTwo.style.display = "none";
gridOneVisible = true;
gridTwoVisible = false;
}
return null;
} | [
"showGrid(){\n this.Grid = true;\n this.Line = false\n \n }",
"function displayPlayingPiecesOne() {\n document.querySelectorAll('.pieces1').forEach(function(el) {\n el.style.display = 'grid';\n });\n\n }",
"function displayPlayingPiecesTwo() {\n document.querySelectorAll('.pieces2').forEach(function(el) {\n el.style.display = 'grid';\n });\n displayPlayAgainButton();\n }",
"function __showBigGrid(grid, obj, oldWidth, oldHeight) {\n\n var hideArray = [];\n var blockArray = obj.caller.blockArray;\n\n for (var i = 0; i < blockArray.length; i++) {\n if (obj.id != blockArray[i].id)\n hideArray[i] = blockArray[i].id;\n }\n\n var screenWidth = screen.width - 60;\n var screenHeight = screen.height;\n\n for (var i = 0; i < hideArray.length; i++) {\n if (hideArray[i] != \"\") {\n if (!SHOW_BIG_GRID_FLG) {\n if (Ext.getCmp(hideArray[i]) && Ext.getCmp(hideArray[i]).isVisible()) {\n newVisiableArray.push(hideArray[i]);\n Ext.getCmp(hideArray[i]).hide();\n }\n } else {\n for (var k = 0; k < newVisiableArray.length; k++) {\n if (newVisiableArray[k] == hideArray[i]) {\n Ext.getCmp(hideArray[i]).show();\n }\n }\n }\n }\n }\n\n var CM = grid.getColumnModel();\n var CM_COUNT = CM.getColumnCount();\n for (var j = 0; j < CM_COUNT; j++) {\n var OLD_WIDTH = CM.getColumnWidth(j);\n if (CM.getDataIndex(j) && CM.getDataIndex(j) != \"\") {\n if (!SHOW_BIG_GRID_FLG) {\n grid.getView().forceFit = true;\n CM.setColumnWidth(j, OLD_WIDTH);\n }\n else {\n\n grid.getView().forceFit = false;\n CM.setColumnWidth(j, OLD_WIDTH);\n }\n }\n }\n\n if (SHOW_BIG_GRID_FLG) {\n grid.setWidth(oldWidth);\n grid.setHeight(oldHeight);\n Ext.getCmp(obj.caller.id).setWidth(oldWidth + 20)\n }\n else {\n grid.setWidth(screenWidth);\n grid.setHeight(screenHeight - 400);\n\n Ext.getCmp(obj.caller.id).setWidth(screenWidth)\n }\n\n if (!SHOW_BIG_GRID_FLG) {\n SHOW_BIG_GRID_FLG = true;\n } else {\n SHOW_BIG_GRID_FLG = false;\n }\n\n var spans = document.getElementsByTagName(\"button\");\n for (var i = 0; i < spans.length; i++) {\n if (spans[i].innerHTML == \"放大显示\") {\n spans[i].innerHTML = \"缩小显示\";\n } else if (spans[i].innerHTML == \"缩小显示\") {\n spans[i].innerHTML = \"放大显示\";\n }\n }\n return;\n /////下面是完美的代码\n\n\n\n\n\n\n SHOW_BIG_GRID_FLG_DO = true;\n var divs = document.getElementsByTagName(\"div\");\n var spans = document.getElementsByTagName(\"button\");\n var screenWidth = screen.width - 60;\n var screenHeight = screen.height - 400;\n var widthDiff = screenWidth - oldWidth;\n\n for (var i = 0; i < divs.length; i++) {\n if (!SHOW_BIG_GRID_FLG) {\n var oldKey = (oldWidth + \"\").substring(0, 1);\n if (divs[i].style && divs[i].style.width) {\n var tempWidth = divs[i].style.width + \"\";\n tempWidth = tempWidth.replace(\"px\", \"\");\n var widthNum = parseInt(tempWidth, 10);\n if (widthNum <= oldWidth && (oldWidth - 50) <= widthNum && tempWidth.indexOf(oldKey) == 0) {\n widthNum += widthDiff;\n divs[i].style.width = widthNum + \"px\";\n }\n }\n } else {\n if (divs[i].style && divs[i].style.width) {\n var tempWidth = divs[i].style.width + \"\";\n tempWidth = tempWidth.replace(\"px\", \"\");\n var widthNum = parseInt(tempWidth, 10);\n widthNum = widthNum - widthDiff;\n if (widthNum <= oldWidth && (oldWidth - 50) <= widthNum) {\n divs[i].style.width = widthNum + \"px\";\n }\n }\n }\n }\n\n if (!SHOW_BIG_GRID_FLG) {\n grid.setHeight(screenHeight);\n } else {\n grid.setHeight(oldHeight);\n }\n\n for (var i = 0; i < spans.length; i++) {\n if (spans[i].innerHTML == \"放大显示\") {\n spans[i].innerHTML = \"缩小显示\";\n } else if (spans[i].innerHTML == \"缩小显示\") {\n spans[i].innerHTML = \"放大显示\";\n }\n }\n\n if (hideArray) {\n for (var i = 0; i < hideArray.length; i++) {\n if (hideArray[i] != \"\") {\n if (Ext.getCmp(hideArray[i])) {\n if (!SHOW_BIG_GRID_FLG) {\n Ext.getCmp(hideArray[i]).hide();\n } else {\n Ext.getCmp(hideArray[i]).show();\n }\n }\n }\n }\n }\n\n var slefFrom = WhiteShell.FormAssembly.businessForm;\n if (newHideArray && slefFrom != null && (!slefFrom.isOriginate() && slefFrom.getViewState() != \"republish\")) {\n if (isFirstShowBigFlg) {\n for (var i = 0; i < newHideArray.length; i++) {\n if (newHideArray[i] != \"\") {\n if (Ext.getCmp(newHideArray[i])) {\n if (!SHOW_BIG_GRID_FLG) {\n if (Ext.getCmp(newHideArray[i]).isVisible()) {\n Ext.getCmp(newHideArray[i]).hide();\n newVisiableArray.push(newHideArray[i]);\n }\n } else {\n Ext.getCmp(newHideArray[i]).show();\n }\n }\n }\n }\n isFirstShowBigFlg = false;\n } else {\n for (var i = 0; i < newVisiableArray.length; i++) {\n if (!SHOW_BIG_GRID_FLG) {\n Ext.getCmp(newVisiableArray[i]).hide();\n } else {\n Ext.getCmp(newVisiableArray[i]).show();\n }\n }\n }\n }\n\n if (!SHOW_BIG_GRID_FLG) {\n SHOW_BIG_GRID_FLG = true;\n } else {\n SHOW_BIG_GRID_FLG = false;\n }\n SHOW_BIG_GRID_FLG_DO = false;\n}",
"function alternateDisplay(obj1,obj2)\n{\n obj1.style.display=\"inline\";\n obj2.style.display=\"none\";\n}",
"getSecondDisplay() {\r\n const displays = this.getAllDisplays();\r\n let externalDisplay = null;\r\n for (const i in displays) {\r\n if (displays[i].bounds.x != 0 || displays[i].bounds.y != 0) {\r\n externalDisplay = displays[i];\r\n break;\r\n }\r\n }\r\n return externalDisplay;\r\n }",
"function drawInner2DGrid(gO, iO, htmlId, edit, showData) {\r\n\r\n\r\n // Create some shortcut names for commonly used members in gridObj\r\n // \r\n var pO = CurProgObj;\r\n\r\n var hasRowTitles = gO.dimHasTitles[RowDimId];\r\n var hasColTitles = gO.dimHasTitles[ColDimId];\r\n var hasRowIndices = gO.dimHasIndices[RowDimId];\r\n var hasColIndices = gO.dimHasIndices[ColDimId];\r\n var isHeaderStep = CurStepObj.isHeader;\r\n var isGlobal = gO.isGlobal; //MPI:\r\n var isDistributed = gO.isDistributed; //MPI:\r\n var dimIsExtended = gO.dimIsExtended; //MPI:\r\n //\r\n var colorize = (showData == ShowDataState.DataAndColor);\r\n //\r\n //\r\n var perColTy = (gO.typesInDim == ColDimId);\r\n var perRowTy = (gO.typesInDim == RowDimId);\r\n\r\n\r\n var str = \"\";\r\n\r\n // STEP : ...............................................................\r\n // table for the 2D grid (gridTable)\r\n //\r\n str += \"<table class='gridTable' id='\" + htmlId + \"2dgrid'>\";\r\n //\r\n // STEP 1: ...............................................................\r\n // Draw indices (or types) over columns.\r\n // Note: ColIndices/RowIndices contain indicies and/or types\r\n // based on the type of the Grid\r\n //\r\n // start a new row and leave columns for row labeles + indices/types\r\n //\r\n\r\n\r\n // STEP 1A: Draw indices .................................................\r\n //\r\n // Top Left Corner Cell always present -- in the same row as\r\n // column indices/titles AND same column as row indices/titles \r\n //\r\n //var configbut = \"<img src='images/gear.jpg' width=20px height=20px \" +\r\n //\t\" title='re-configure grid'\" + \">\";\r\n\r\n\r\n var commentId = getCommentHtmlId(CommentType.Grid, htmlId);\r\n var commentSpan =\r\n getCommentStr('span', commentId, \" style='margin:4px' \", gO.comment);\r\n var topleft = commentSpan;\r\n\r\n // STEP 2a: Draw column indices if required\r\n //\r\n var indstr = \"\";\r\n\r\n if (hasColIndices && (iO || showData)) { // draw column indices \r\n\r\n var col_start = (showData) ? gO.dimShowStart[ColDimId] : 0;\r\n var col_end = getDimEnd(gO, ColDimId, col_start, showData);\r\n\r\n // if showing data, draw left arrow to scroll. The left arrow is\r\n // drawn if and only if there are columns to the left to be shown\r\n // NOTE: The left arrow (when present) replaces table comment\r\n //\r\n if (showData && (col_start > 0)) {\r\n\r\n var newstart = gO.dimShowStart[ColDimId] - gO.dimShowSize[\r\n ColDimId];\r\n if (newstart < 0) newstart = 0;\r\n //\r\n var onc_args = \"'\" + htmlId + \"',\" + ColDimId + \",\" +\r\n newstart;\r\n var onc = \" onclick=\\\"scrollData(\" + onc_args + \")\\\" \";\r\n //\r\n topleft = \"<img src='images/larrow1.png' \" + onc +\r\n \" width=16px height=16px>\";\r\n }\r\n\r\n // skip cell for row types/titles\r\n //\r\n if (perRowTy) // if types present\r\n indstr += \"<td class='topLeft'></td>\";\r\n if (hasRowTitles && hasRowIndices) // if both titles/indices\r\n indstr += \"<td class='topLeft'></td>\";\r\n\r\n for (var c = col_start;\r\n (c < col_end) && gO.multiCol; c++) {\r\n\r\n // Draw column index cells\r\n //\r\n var onc = \"\";\r\n if (!edit) {\r\n var onc_args = \"this, '\" + htmlId + \"',\" + ColDimId + \",\" +\r\n c;\r\n onc = \" onmousedown=\\\"gridIndMouseDown(\" + onc_args +\r\n \")\\\" \";\r\n onc += \" onmouseup=\\\"gridIndMouseUp(\" + onc_args + \")\\\" \";\r\n }\r\n\r\n // whether to highlight col indices\r\n //\r\n var ishigh = (gO.selIndDim == ColDimId);\r\n var indclass = (ishigh) ? \"colindexhigh\" : \"colindex\";\r\n\r\n // if showing data, just use column number \r\n //\r\n var indname = (showData) ? c :\r\n getIndExprStr(iO.dimIndExprs[ColDimId][c]);\r\n indstr += \"<td class='\" + indclass + \"' \" + onc + \">\" +\r\n indname + \"</td>\";\r\n\t //MPI: 'indname' shows 0, col, end1 (for columns in 2D)\r\n\t // if NOT showing data (in which case it takes them\r\n\t // from iO.dimIndExprs[][]. Otherwise shows col number\r\n\t // Num columns it gets from col_start/col_end that take\r\n\t // it from dimShowStart[] if showing data or 0, and\r\n\t // getDimEnd() for end respectively.\r\n\r\n }\r\n\r\n // Draw a right arrow to scroll to right. Draw the arrow if and only if\r\n // there is more data to show\r\n // \r\n if (showData && (col_end < gO.dimActSize[ColDimId])) {\r\n\r\n var onc_args = \"'\" + htmlId + \"',\" + ColDimId + \",\" + col_end;\r\n var onc = \" onclick=\\\"scrollData(\" + onc_args + \")\\\" \";\r\n //\r\n indstr += \"<td><img src='images/rarrow1.png' width=16px \" +\r\n \" height=16px \" + onc + \" ></td>\";\r\n }\r\n }\r\n //\r\n str += \"<tr> <td class='topLeft' >\" + topleft + \"</td>\" + indstr +\r\n \"</tr>\";\r\n\r\n\r\n // STEP 2b: ...............................................................\r\n // Draw column titles (and types), if available\r\n //\r\n if (hasColTitles) { // draw column titles .................\r\n\r\n // Since we have column titles, the number of columns we show \r\n // are fixed\r\n //\r\n var showCols = gO.dimShowSize[ColDimId];\r\n\r\n // Draw per-column data types, if needed .....................\r\n //\r\n // Note: Col Types can be present only when there are col titles\r\n // Draw column types if necessary\r\n //\r\n if (perColTy) { // if data type in every col\r\n\r\n // skip cells for row indices/types/titles\r\n //\r\n if (hasRowIndices)\r\n str += \"<tr> <td class='topLeft'></td>\";\r\n if (hasRowTitles)\r\n str += \"<td class='topLeft'></td>\";\r\n\r\n // put type over each column\r\n //\r\n for (var c = 0; c < showCols; c++) {\r\n var sel = \"(\" + TypesArr[gO.dataTypes[c]] + \")\";\r\n if (edit) sel = getTypeSelectStr(c, gO.dataTypes[c],\r\n htmlId);\r\n str += \"<td class='colindex'>\" + sel + \"</td>\";\r\n }\r\n\r\n str += \"</tr>\"; // close index/type row\r\n }\r\n\r\n\r\n // Now draw actual COLUMN TITLES\r\n //\r\n str += \"<tr>\"; // start col-titles row\r\n //\r\n if (hasRowIndices) str += \"<td class='topLeft'></td>\";\r\n if (perRowTy) str += \"<td class='topLeft'></td>\";\r\n if (hasRowTitles) str += \"<td class='topLeft'></td>\";\r\n\r\n for (var c = 0; c < showCols; c++) {\r\n\r\n var onc_args = \"this, '\" + htmlId + \"',\" + ColDimId + \",\" + c;\r\n var fun = (!edit) ? \" onclick=\\\"titleClicked(\" + onc_args +\r\n \")\\\"\" :\r\n \" oninput='changeColTitle(this,\" + c +\r\n \")' contenteditable\";\r\n //\r\n var tip = (edit) ? \" title='click to edit' \" : \"\";\r\n var sty = \" style='padding:4px' \";\r\n var divstr = \"<div \" + fun + tip + sty + \">\" +\r\n gO.dimTitles[ColDimId][c];\r\n\r\n var commentId = getCommentHtmlId(CommentType.DimTitle +\r\n ColDimId, c);\r\n var cur_comment = gO.dimComments[ColDimId][c];\r\n var commentDiv = getCommentStr('div', commentId, \"\",\r\n cur_comment);\r\n\r\n str += \"<td class='coltitle'>\" + divstr + \"</div>\" +\r\n commentDiv + \"</td>\";\r\n }\r\n str += \"</tr>\"; // close column title row\r\n\r\n } // if there are column titles\r\n\r\n\r\n\r\n // STEP 3: ...............................................................\r\n // Draw each row (types/indices/titles/content-cells)\r\n //\r\n var row_start = (showData) ? gO.dimShowStart[RowDimId] : 0;\r\n var row_end = getDimEnd(gO, RowDimId, row_start, showData);\r\n\r\n for (var r = row_start;\r\n (r < row_end); r++) {\r\n\r\n str += \"<tr>\"; // start content row\r\n\r\n\r\n if (hasRowIndices && (iO || showData)) { // draw index in cell\r\n var onc = \"\";\r\n if (!edit) {\r\n var onc_args = \"this, '\" + htmlId + \"',\" + RowDimId + \",\" +\r\n r;\r\n onc = \" onmousedown=\\\"gridIndMouseDown(\" + onc_args +\r\n \")\\\" \";\r\n onc += \" onmouseup=\\\"gridIndMouseUp(\" + onc_args + \")\\\" \";\r\n }\r\n\r\n\r\n\r\n // whether to highlight row indices\r\n //\r\n var ishigh = (gO.selIndDim == RowDimId);\r\n //\r\n var indclass = (ishigh) ? \"rowindexhigh\" : \"rowindex\";\r\n\r\n // index string. If showing data, it is just the row number\r\n //\r\n var istr = \"\";\r\n //\r\n if (showData) {\r\n\r\n // Draw the up and down arrows, when we are showing data -- for\r\n // scrolling large matrices\r\n // Note: The arrows are shown if and only if there are more\r\n // rows to be seen in the given direction\r\n //\r\n if ((r == row_start) && (row_start > 0)) {\r\n\r\n var newstart =\r\n gO.dimShowStart[RowDimId] - gO.dimShowSize[\r\n RowDimId];\r\n if (newstart < 0) newstart = 0;\r\n //\r\n var args = \"'\" + htmlId + \"',\" + RowDimId + \",\" +\r\n newstart;\r\n var onc = \" onclick=\\\"scrollData(\" + args + \")\\\" \";\r\n //\r\n istr += \"<img src='images/uparrow1.png' \" + onc +\r\n \" width=16px height=16px>\";\r\n\r\n } else if (r == (row_end - 1) &&\r\n (row_end < gO.dimActSize[RowDimId])) {\r\n\r\n var args = \"'\" + htmlId + \"',\" + RowDimId + \",\" +\r\n row_end;\r\n var onc = \" onclick=\\\"scrollData(\" + args + \")\\\" \";\r\n //\r\n istr += \"<img src='images/downarrow1.png' \" + onc +\r\n \" width=16px height=16px>\";\r\n }\r\n\r\n istr += \"\" + r; // row number whiles showing data\r\n\r\n //logMsg(\"rowIndices w/ showdata: \" + hasRowIndices +\" \"+istr);\r\n\r\n\r\n } else if (gO.multiRow && iO) {\r\n istr = getIndExprStr(iO.dimIndExprs[RowDimId][r]);\r\n\t\t//MPI: 'istr' shows 0, row, end0 (if showing data, then\r\n\t\t// it has endered the \"if\" not this \"else if\"...\r\n }\r\n\r\n var rind_str = \"<td class='\" + indclass + \"' \" + onc + \">\" +\r\n istr + \"</td>\";\r\n\r\n // add row index only if multi-row\r\n //\r\n var scalar_str = \"<td class='rowindex'></td>\"; // empty cell\r\n str += (gO.multiRow) ? rind_str : scalar_str;\r\n\r\n } else if (hasRowIndices) {\r\n\r\n // We have row indices but no index object (e.g., for Header step)\r\n // Just draw an empty row-index cell.\r\n //\r\n str += \"<td class='rowindex'></td>\"; // empty cell\r\n\r\n }\r\n\r\n\r\n\r\n // Draw row types/titles, if present\r\n //\r\n if (hasRowTitles) { // draw TYPE in cell when row titles\r\n\r\n // if data type is in every row, draw it now \r\n //\r\n if (perRowTy) { // data type in every row\r\n\r\n str += \"<td class='rowindex'>\";\r\n //\r\n var sel = \"(\" + TypesArr[gO.dataTypes[r]] + \")\";\r\n if (edit) sel = getTypeSelectStr(r, gO.dataTypes[r],\r\n htmlId);\r\n str += sel;\r\n //\r\n str += \"</td>\";\r\n }\r\n\r\n // Now Draw the actual title\r\n //\r\n var fun = (!edit) ? \"\" :\r\n \" oninput='changeRowTitle(this,\" + r +\r\n \")' contenteditable\";\r\n //\r\n var tip = (edit) ? \" title='click to edit' \" : \"\";\r\n var sty = \" style='padding:4px' \";\r\n var tstr = \" <span \" + fun + tip + sty + \">\" +\r\n gO.dimTitles[RowDimId][r];\r\n\r\n var comId = getCommentHtmlId(CommentType.DimTitle + RowDimId,\r\n r);\r\n var cur_comment = gO.dimComments[RowDimId][r];\r\n var comSpan = getCommentStr('span', comId,\r\n \" style='margin:4px' \", cur_comment);\r\n\r\n str += \"<td class='rowtitle'>\" + comSpan + tstr + \"</span>\" +\r\n \"</td>\";\r\n\r\n } // if row titles (and types)\r\n\r\n\r\n // If this is a scalar grid, there are no row types/titles/indices\r\n // So, to move it right of the the topLeft comment, add a dummy\r\n // cell (beacause we assume there is always row titles/indices\r\n // will be present\r\n //\r\n if (gO.numDims == 0)\r\n str += \"<td></td>\";\r\n\r\n\r\n // Now draw CONTENT cells for all columns in this row\r\n //\r\n var col_start = (showData) ? gO.dimShowStart[ColDimId] : 0;\r\n var col_end = getDimEnd(gO, ColDimId, col_start, showData);\r\n //\r\n for (var c = col_start; c < col_end; c++) {\r\n\r\n // Select default cell class based on the row\r\n //\r\n var cell_class = (r % 2) ? \" class='odd' \" : \" class='even' \";\r\n\r\n\r\n\t //MPI: Show dotted cells type for extended dimensions' cells\r\n\t // Only when editing a grid\r\n\t if (edit) {\r\n\t if (gO.dimIsExtended[RowDimId] && \r\n\t\t !gO.dimIsExtended[ColDimId]) {\r\n\r\n\t if (r < 2 || r >= row_end - 2)\r\n\t\t cell_class = \" class='extended' \";\r\n\r\n\t } else if (gO.dimIsExtended[ColDimId] && \r\n\t\t !gO.dimIsExtended[RowDimId]) {\r\n\r\n\t \t if (c < 2 || c >= col_end - 2)\r\n\t\t cell_class = \" class='extended' \";\r\n\r\n\t } else if (gO.dimIsExtended[RowDimId] && \r\n\t\t gO.dimIsExtended[ColDimId]) {\r\n\r\n\t \t if ( (r < 2 || r >= row_end -2) || \r\n\t\t ( (r >= 2 || r <= row_end - 2) && \r\n\t\t (c<2 || c >= col_end - 2)) )\r\n\t\t cell_class = \" class='extended' \";\r\n\r\n\t }\r\n\t }\r\n\r\n\r\n var tip = \"\",\r\n val = \"\",\r\n prop = \"\";\r\n if (!edit && !showData && !isHeaderStep && iO) {\r\n var cel = getCellExpr(gO, iO, r, c); // array notation string\r\n if (cel.length) { // if not empty\r\n var args = \"'\" + htmlId + \"',\" + r + \",\" + c;\r\n var onc = \" onclick=\\\"putCellInd(\" + args + \")\\\"\";\r\n tip = \"title='\" + cel + \"' \" + onc;\r\n }\r\n }\r\n\r\n // if initilizatio of data is required, make cells contentedible.\r\n //\r\n if (edit && gO.hasInitData) {\r\n\r\n /*\r\n\t\tval = getDataVal(gO.numDims-1, gO.data, r, c, gO.dimSelectTabs);\r\n\t\tval = (val === undefined) ? \"\" : val;\r\n\t\t*/\r\n\r\n prop += \" contenteditable \";\r\n\r\n }\r\n\r\n\r\n // Highlight any selected cells.\r\n // We highlight only if an expression is selected in the \r\n // code window. \r\n //\r\n var ishigh = gO.hasSelection && !showData;\r\n var cell_high = false;\r\n //\r\n if ((gO.dimSelectTabs[RowDimId] == r) && ishigh &&\r\n (gO.dimSelectTabs[ColDimId] == c)) {\r\n cell_class = \" class='select' \";\r\n cell_high = true;\r\n }\r\n //\r\n if (showData && !edit && gO.data) { // data to show\r\n\r\n val = getDataValOfCell(gO, r, c);\r\n\r\n val = (val === undefined) ? \"\" : val;\r\n if (colorize && !cell_high) {\r\n var hexcol = getHexColor(val, CurStepObj.maxDataVal);\r\n cell_class += \" style='background-color:#\" + hexcol +\r\n \"' \";\r\n }\r\n }\r\n //\r\n str += \"<td \" + cell_class + tip + prop + \">\" + val + \"</td>\";\r\n }\r\n\r\n // Insert/Delete Row. \r\n //\r\n if (!edit) {\r\n str += \"<td class='insrow' onclick='sliceClicked(this,\" +\r\n RowDimId + \",\" + r + \",\\\"\" + htmlId + \"\\\")'></td>\";\r\n }\r\n //\r\n // close the row \r\n //\r\n str += \"</tr>\";\r\n\r\n } // for all rows\r\n\r\n str += \"</table>\"; // close grid table\r\n\r\n\r\n return str;\r\n\r\n}",
"showCellsId(G,ctx){\n\t\t\tconst cells = [...G.cells];\n\t\t\tfor (let i = 0; i < boardHeight; i++) {\n\t\t\t\tfor(let j=0;j<boardWidth;j++) {\n\t\t\t\t\tlet id = boardWidth * i + j;\n\t\t\t\t\tcells[id].setDisplay(id);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {...G,cells};\n\t\t}",
"function renderGrid(ctx) {\n drawGridLines(ctx);\n drawGridCells(ctx, minesweeper.cells );\n}",
"function layoutGrid(gridContainer, columns, rows){\n\tgridContainer.style.display = 'grid';\n\t//gridContainer.style.gridTemplateColumns = `repeat(${columns},${100/columns}%)`;\n\t//gridContainer.style.gridTemplateRows = `repeat(${rows}, ${100/rows}%)`;\n\tgridContainer.style.gridTemplateColumns = `repeat(${columns}, 1fr)`;\n\tgridContainer.style.gridTemplateRows = `repeat(${rows}, 1fr)`;\n\treturn;\n}",
"function catsOrDogs() {\n let sec = jsgui.section();\n\n let catPic = jsgui.img(\"cat.jpg\", \"a black cat\");\n let dogPic = jsgui.img(\"dog.jpg\", \"a shaggy Newfoundland dog\");\n\n let catPeople = animalDetail(\"Cat people\", catPic,\n \"Some people like cats. Cats are quiet, playful, soft, and sweet.\");\n\n let dogPeople = animalDetail(\"Dog people\", dogPic,\n \"Some people like dogs: loyal friends and quick with a trick.\");\n\n let grid = jsgui.grid(2);\n jsgui.addToGrid(grid, 1, catPeople);\n jsgui.addToGrid(grid, 2, dogPeople);\n jsgui.append(sec,\n jsgui.h2(\"Cats and Dogs\"),\n jsgui.p(\"Do you prefer cats or dogs?\"),\n grid,\n jsgui.hr());\n\n return sec;\n\n}",
"function assignNavAndSidebarHeaders() {\n\t\t\t$(\"#area-blank1 h3\").text(sgeonames[0]);\n\t\t\t$(\"#left-sidebar h3\").text(sgeonames[0]+\" Projects by :\");\n\n\t\t $(\".area-blank\").css(\"display\", \"inline-block\");\n\t\t if (sgeonames[1]) {\n\t\t \t$(\"#area-blank2 h3\").text(sgeonames[1]);\n\t\t\t\t$(\"#right-sidebar h3\").text(sgeonames[1]+\" Projects by :\");\n\t\t \t$(\"#data-buttons\").css(\"display\", \"inline-block\");\n\t\t }\n\t\t}",
"function toggleToCompBoard(evt) {\n gameBoard1.style.display = \"none\";\n gameBoard2.style.display = \"\";\n compHeader.style.display = \"\";\n playerHeader.style.display = \"none\";\n}",
"function drawGridContent(){\n for( var i =0; i<=cw/100; i++){\n for(var j=0; j<=ch/100; j++){\n var cI = i.toString()+'-'+j.toString();\n if( cI in gridContent){\n\tif(gridContent[cI]>=0){\n\t if( pickThis == cI){\n\t /* Mouse motion: puzzle piece follows mouse coordiantes: */\n\t drawPiece(mx, my, 100,100, cI==selectedItem, cI);\n\t\t\t\t//0 + 100*i,21 + 100*j, 100,100);\n\t }else{\n\t //Puzzle piece is static: \n\t drawPiece(0 + 100*i,21 + 100*j, 100,100, cI==selectedItem, cI);\n\t }\n\t //draw(mx, my, 100, 100);\n\t}\n }\n }\n }\n}",
"display() {\n for (let i = 0; i < this.columns; i++) {\n for (let j = 0; j < this.rows; j++) {\n this.board[i][j].display();\n }\n }\n }",
"buildSimpleDisplayPanel(title, single, double, immune) {\n single = single || []\n double = double || []\n immune = immune || []\n\n let panel = document.createElement(\"div\");\n panel.classList.add(\"panel\");\n\n let label = document.createElement(\"h3\");\n label.classList.add(\"label\");\n label.innerText = title;\n panel.appendChild(label);\n\n immune.forEach((t) => { panel.appendChild(this.buildType(t, false, \"immune\", \"small\")) });\n double.forEach((t) => { panel.appendChild(this.buildType(t, false, \"double\", \"small\")) });\n single.forEach((t) => { panel.appendChild(this.buildType(t, false, \"small\")) });\n\n return panel;\n }",
"function CallLayouts(){\n cy.elements(\"[filter!='yes']\").layout(springy);\n cy.elements(\"[home='yes']\").layout(home);\n cy.elements(\"[chrono='yes']\").layout(chrono);\n}",
"function drawGrid(gridObj, indObj, htmlId, edit) {\r\n\r\n // Create some shortcut names for commonly used members in gridObj\r\n // \r\n var pO = CurProgObj;\r\n var gO = gridObj; // shortcut reference to gridObj\r\n var iO = indObj;\r\n\r\n var caption = gO.caption;\r\n //var hasRowTitles = gO.dimHasTitles[RowDimId];\r\n //var hasColTitles = gO.dimHasTitles[ColDimId];\r\n //var hasRowIndices = gO.dimHasIndices[RowDimId];\r\n //var hasColIndices = gO.dimHasIndices[ColDimId];\r\n var isHeaderStep = CurStepObj.isHeader;\r\n\r\n // We use the show data state of the current Step object by default. \r\n // If it is necessary to override this, we can pass in an arg \r\n // to this function\r\n //\r\n var showData = pO.showData;\r\n\r\n // Draw assignment arrows when we are drawing non-editable output grid.\r\n // Also, we don't draw arrows for templates\r\n //\r\n var drawArrows = (OutHtmlId == htmlId) && !edit && !gO.isTemplate;\r\n\r\n clearTip();\r\n\r\n // Register this htmlId with the grid Object. This assumes that the same\r\n // gridObj is not drawn on the screen twice -- i.e., we always clone\r\n //\r\n gO.htmlId = htmlId;\r\n //gO.showData = showData; // record show data status\r\n\r\n var str = \"\"; // html code holder\r\n\r\n\r\n\r\n // STEP A.1: ----------- Draw outermost container ----------------------- \r\n //\r\n // This is the outermost container table for all cases. It is also\r\n // used to draw the 'assignment arrow'. This has the 'htmllId' assigned.\r\n //\r\n var id = \"id='\" + htmlId + \"'\"; // html id for outermost table\r\n str += \"<table class='outArrow' \" + id + \" >\";\r\n\r\n if (gO.typesInDim < 0) { // global type in row1\r\n\r\n\t// We allow changing the data type while editing a grid OR \r\n\t// for all grids w/ a global type (including return value) in a header\r\n\t//\r\n\tvar type_sel = edit || CurStepObj.isHeader;\t\r\n\tvar tstr = (type_sel)? \r\n\t getTypeSelectStr(0, gO.dataTypes[0], htmlId ) : \r\n\t \"(\" + TypesArr[gO.dataTypes[0]] + \")\";\r\n\r\n str += \"<tr><td class='type'>\" + tstr + \"</td></tr>\";\r\n }\r\n //\r\n // \r\n str += \"<tr><td>\"; // row2 for contents/arrows\r\n\r\n // STEP A.2: ----------- Draw Multi-Dimensional Panes --------------------\r\n //\r\n for (var d = gO.numDims - 1; d >= 2; d--) { // draw outer dimensions first\r\n\r\n // start an entire tabbed 2D pane\r\n //\r\n str += \"<table class='tabPane' \" + id + \" >\"; // 2D-pane\r\n\r\n\tvar color = TabColors[(d-2) % TabColors.length]; // tab color & style\r\n\tvar has_titles = gO.dimHasTitles[d];\r\n\t//\r\n\tvar sel =\" class=select \"; // selected style\r\n\tvar sty = \" style='background-color:#\" + color + \"' \";\r\n\tsel += sty; \r\n\t//\r\n\t// non-selected style\r\n\t//\r\n\tvar nosel = \" class=noselect style='background-color:#fefefe' \";\r\n\r\n // If the dimension has indices, draw it above titles (and types)\r\n //\r\n if (gO.dimHasIndices[d] && (iO || showData)) {\r\n str += \"<tr>\";\r\n\r\n // Select the background color of indices\r\n //\r\n var sty2 = \"\";\r\n if (gO.selIndDim == d) {\r\n\r\n // if this index range highligted\r\n //\r\n sty2 = \" style='background-color:#dcffed' \";\r\n\r\n } else if (d < gO.numDims - 1) {\r\n\r\n // if not the outermost dim, use the background color of the\r\n // outer dim (d+1) -- not TabColors[0] is for dim 2\r\n //\r\n var color = TabColors[d - 2 + 1];\r\n sty2 = \" style='background-color:#\" + color + \"' \";\r\n }\r\n\r\n // Find which tabs to show if we are showing data\r\n //\r\n var tab_start = (showData) ? gO.dimShowStart[d] : 0;\r\n var tab_end = getDimEnd(gO, d, tab_start, showData);\r\n //\r\n for (var t = tab_start; t < tab_end; t++) {\r\n var onc_args = \"this, '\" + htmlId + \"',\" + d + \",\" + t;\r\n onc = \" onmousedown=\\\"gridIndMouseDown(\" + onc_args +\r\n \")\\\" \";\r\n onc += \" onmouseup=\\\"gridIndMouseUp(\" + onc_args + \")\\\" \";\r\n\r\n var istr = (showData) ? t : getIndExprStr(iO.dimIndExprs[\r\n d][t]);\r\n //\r\n // Draw left/right arrows for scrolling a larger matrix\r\n //\r\n if (showData && (t == tab_start) && (tab_start > 0)) {\r\n\r\n var newstart =\r\n gO.dimShowStart[d] - gO.dimShowSize[d];\r\n if (newstart < 0) newstart = 0;\r\n //\r\n var args = \"'\" + htmlId + \"',\" + d + \",\" + newstart;\r\n var click = \" onclick=\\\"scrollData(\" + args + \")\\\" \";\r\n //\r\n istr = \"<img src='images/larrow1.png' \" + click +\r\n \" width=16px height=16px>\" + istr;\r\n\r\n\r\n } else if (showData &&\r\n (t == (tab_end - 1)) && (tab_end < gO.dimActSize[d])) {\r\n\r\n var args = \"'\" + htmlId + \"',\" + d + \",\" + tab_end;\r\n var click = \" onclick=\\\"scrollData(\" + args + \")\\\" \";\r\n //\r\n istr += \"<img src='images/rarrow1.png' \" + click +\r\n \"width=16px height=16px>\";\r\n }\r\n\r\n str += \"<th class='index' \" + sty2 + onc + \">\" + istr +\r\n \"</th>\";\r\n }\r\n str += \"</tr>\";\r\n }\r\n\r\n\r\n // draw tab TYPES, if the types are in this dimension\r\n //\r\n if (gO.typesInDim == d) {\r\n str += \"<tr>\";\r\n for (var t = 0; t < gO.dimShowSize[d]; t++) {\r\n var tstr = (edit) ?\r\n getTypeSelectStr(t, gO.dataTypes[t], htmlId) : \"\";\r\n str += \"<td class='type'>\" + tstr + \"</td>\";\r\n }\r\n str += \"</tr>\";\r\n }\r\n\r\n // draw tab heads. If the current tab is selected, it is drawn \r\n // differently than the other (un-selected) tabs.\r\n //\r\n str += \"<tr>\";\r\n for (var t = 0; t < gO.dimShowSize[d]; t++) {\r\n\r\n var prop = (t == gO.dimSelectTabs[d]) ? sel : nosel;\r\n\r\n // create the call for event handler. If we are editing, we \r\n // can change the tab and edit the title. Otherwise, just change\r\n // the tab.\r\n //\r\n if (edit && has_titles) { // editable titles\r\n //\r\n var args = \"this, '\" + htmlId + \"',\" + d + \",\" + t + \",\" +\r\n edit;\r\n prop += \" contenteditable oninput=\\\"changeTabTitle(\" +\r\n args + \",0)\\\"\" + \" onclick=\\\"changeTabTitle(\" + args +\r\n \",1)\\\" \"; + \" onblur=\\\"changeTabTitle(\" + args +\r\n \",2)\\\" \";\r\n\r\n } else { // NO-tiltles OR non-editable titles - allow tab change\r\n\r\n var args = \"this, '\" + htmlId + \"',\" + d + \",\" + t + \",\" +\r\n edit;\r\n prop += \" onclick=\\\"selectTab(\" + args + \")\\\" \";\r\n }\r\n //\r\n // if the tab has titles, use it. Otherwise, put an empty\r\n // cell - note we cannot put a div in 'cont' because it is picked up\r\n // by cell formula.\r\n //\r\n var cont = (has_titles) ? gO.dimTitles[d][t] : \"\";\r\n str += \"<td \" + prop + \">\" + cont + \"</td>\";\r\n\r\n }\r\n str += \"</tr>\";\r\n\r\n // start the contents cell. We draw another 2D pane, or a 2D grid\r\n // in a 'content' cell\r\n //\r\n str += \"<tr><td class='contents' \" + sty + \" colspan=\" \r\n\t + gO.dimShowSize[d] + \">\";\r\n }\r\n //\r\n // END STEP A: ----- End of Multi-Dimensional Panes -------------------\r\n\r\n\r\n\r\n // STEP ................................................................\r\n //\r\n // Draw the inner 2D grid of type 'gridTable' for each higher dimensional\r\n // tab. If we are showing data image, just get a canvas for drawing it --\r\n // the canvas will be filled at the end of this function.\r\n //\r\n if (showData == ShowDataState.DataImage)\r\n str += getCanvasFor2DGrid(gridObj, htmlId);\r\n else\r\n str += drawInner2DGrid(gridObj, indObj, htmlId, edit, showData);\r\n\r\n\r\n // STEP Z: --------------- Close Multi-Dimensional Pane(s) --------------\r\n //\r\n for (var d = 2; d < gO.numDims; d++) {\r\n str += \"</td></tr></table>\";\r\n }\r\n\r\n\r\n // STEP : ...............................................................\r\n // \r\n // Close the outermost container table (of type 'outArrow') after\r\n // putting in the assign arrow image AND caption of table\r\n\r\n //\r\n var img = \"\"; // draw Assign Arrow\r\n if (drawArrows) {\r\n img = \"<img src='images/bigarrow.jpg' width=60px height=60px>\";\r\n }\r\n //\r\n //\r\n str += \"</td><td>\" + img + \"</td></tr>\"; // close row2 of outermost table\r\n\r\n // STEP: Row for config button / context menu\r\n //\r\n var configbut = (edit || showData) ? \"\" :\r\n getGridConfContextMenu(htmlId, gO.isConst);\r\n //\r\n str += \"<tr><td class='gridconfbut'>\" + configbut + \"</td></tr>\";\r\n\r\n\r\n // Draw the caption cell at the bottom row of Multi-Dimension Pane\r\n // First, create a contenteditable caption (in div) an add oninput function\r\n //\r\n var attrib = \"\";\r\n if (gO.inArgNum >= 0 && (gO.deleted == DeletedState.None)) {\r\n attrib += \"<span class='captionParam'> (Parameter \" + gO.inArgNum +\r\n \") </span>\";\r\n }\r\n //\r\n var oninp = \"\";\r\n var indargs = \"\"; // index paramenters for grid cell reference\r\n //\r\n var isCapEdit = (edit || isHeaderStep) && !gO.beingReConfig;\r\n //\r\n if (isCapEdit) { // if caption is editable\r\n\tvar args = \"this, '\" + htmlId + \"'\";\r\n\t//var args = \"this\";\r\n\t//oninp = \" oninput=\\\"changeCaption(\" + args + \")\\\" contenteditable \";\r\n\toninp = \" onblur=\\\"changeCaption(\" + args + \")\\\" contenteditable \";\r\n\r\n } else { // if caption is NOT editable\r\n\r\n // When the user clicks on a grid name, insert a grid reference\r\n // (mainly as a function arg) \r\n //\r\n var args = \"'\" + htmlId + \"'\";\r\n oninp = \" onclick=\\\"putGridRef(\" + args + \")\\\" \";\r\n oninp += \" style='cursor:pointer' \";\r\n\r\n //if (gO.isGridCellRef) { // TODO:\r\n // indargs = getGridCellIndArgs(gO);\r\n //}\r\n\r\n }\r\n\r\n\r\n // Draw grid specific buttons at the bottom right corner of the grid\r\n //\r\n var configbut = \"\"; //\"<img src='images/gear.jpg' width=15px height=15px \" +\r\n \" title='re-configure grid'\" + \">\";\r\n if (edit || showData) configbut = \"\";\r\n\r\n var buttons = \"<div class='gridButDiv'>\" + configbut + \"</div>\";\r\n\r\n /*\r\n //\r\n // Navaigation buttons for scrolling through data grids\r\n // TODO: complete these.\r\n // \r\n var leftarr = \"\", rightarr = \"\";\r\n if (showData) {\r\n\tleftarr = \"<span style='float:left'><img src='images/larrow.jpg'\" +\r\n\t \" width=16px height=16px></span>\";\r\n\r\n\trightarr = \"<span style='float:right'><img src='images/rarrow.jpg'\" + \r\n\t \" width=16px height=16px> </span>\";\r\n }\r\n */\r\n\r\n str += \"<tr><td class='caption'>\" +\r\n \"<span \" + oninp + \">\" + caption + \"</span>\" + indargs + \"\" +\r\n buttons + \"</td></tr>\" + \"<tr><td>\" + attrib + \"</td></tr>\";\r\n // \r\n str += \"</table>\"; // close outermost table\r\n\r\n\r\n // STEP : update html object .............................................\r\n // Get the HTML object in the gridObj and update its innerHTML\r\n //\r\n var grid1 = document.getElementById(htmlId);\r\n grid1.innerHTML = str; // update HTML of grid\r\n grid1.className = 'outArrow'; // change class of htmlId\r\n\r\n\r\n\r\n var grid2d = document.getElementById(htmlId + \"2dgrid\");\r\n grid2d.className = 'gridTable'; // change class of 2d grid table\r\n\r\n\r\n // STEP\r\n // If we are showing the data image, draw the data on a canvas \r\n //\r\n if (showData == ShowDataState.DataImage) {\r\n draw2DGridOnCanvas(gridObj, htmlId);\r\n }\r\n}",
"function drawGrid() {\n for(var i = 0; i < nRows; i++) {\n\tfor(var j = 0; j < nCols; j++) {\n\t if(gol.getCell(i, j) == 1)\n\t\tgridCtx.fillStyle = \"white\";\n\t else\n\t\tgridCtx.fillStyle = \"black\";\n\t gridCtx.fillRect(j * cellWidth + 1, i * cellHeight + 1, cellWidth - 2, cellHeight - 2);\n\t}\n }\n //console.log(gol.toString());\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Arguments stockAmount= normal stock amount commonstockid = Id preorder = Preorder is Enable or not preorder_stock = prorder stock amount | function checkProductStockRoom(stockAmount, commonstockid, preorder, preorder_stock)
{
var isStock = true;
if (stockAmount > 0)
{
if (document.getElementById('pdaddtocart' + commonstockid))
{
document.getElementById('pdaddtocart' + commonstockid).style.display = '';
}
if (USE_AS_CATALOG == 1)
{
if (document.getElementById('pdaddtocart' + commonstockid)) {
document.getElementById('pdaddtocart' + commonstockid).style.display = 'none';
}
}
if (document.getElementById('preordercart' + commonstockid)) {
document.getElementById('preordercart' + commonstockid).style.display = 'none';
}
if (document.getElementById('stockaddtocart' + commonstockid)) {
document.getElementById('stockaddtocart' + commonstockid).style.display = 'none';
}
isStock = true;
} else {
if (stockAmount == 0) {
if ((preorder == 'global' && ALLOW_PRE_ORDER != 1) || (preorder == '' && ALLOW_PRE_ORDER != 1) || (preorder == 'no')) {
//isPreorderProductStock
if (document.getElementById('stockaddtocart' + commonstockid)) {
document.getElementById('stockaddtocart' + commonstockid).style.display = '';
}
if (document.getElementById('stockaddtocart' + commonstockid)) {
document.getElementById('stockaddtocart' + commonstockid).innerHTML = COM_REDSHOP_PRODUCT_OUTOFSTOCK_MESSAGE;
}
if (USE_AS_CATALOG == 1) {
if (document.getElementById('stockaddtocart' + commonstockid)) {
document.getElementById('stockaddtocart' + commonstockid).style.display = 'none';
}
}
if (document.getElementById('preordercart' + commonstockid)) {
document.getElementById('preordercart' + commonstockid).style.display = 'none';
}
if (document.getElementById('pdaddtocart' + commonstockid)) {
document.getElementById('pdaddtocart' + commonstockid).style.display = 'none';
}
} else {
if (preorder_stock == 0) {
if (document.getElementById('stockaddtocart' + commonstockid)) {
document.getElementById('stockaddtocart' + commonstockid).style.display = '';
}
if (document.getElementById('stockaddtocart' + commonstockid)) {
document.getElementById('stockaddtocart' + commonstockid).innerHTML = COM_REDSHOP_PREORDER_PRODUCT_OUTOFSTOCK_MESSAGE;
}
if (USE_AS_CATALOG == 1) {
if (document.getElementById('stockaddtocart' + commonstockid)) {
document.getElementById('stockaddtocart' + commonstockid).style.display = 'none';
}
}
if (document.getElementById('preordercart' + commonstockid)) {
document.getElementById('preordercart' + commonstockid).style.display = 'none';
}
if (document.getElementById('pdaddtocart' + commonstockid)) {
document.getElementById('pdaddtocart' + commonstockid).style.display = 'none';
}
} else {
if (document.getElementById('stockaddtocart' + commonstockid)) {
document.getElementById('stockaddtocart' + commonstockid).style.display = 'none';
}
if (document.getElementById('stockaddtocart' + commonstockid)) {
document.getElementById('stockaddtocart' + commonstockid).innerHTML = "";
}
if (document.getElementById('pdaddtocart' + commonstockid)) {
document.getElementById('pdaddtocart' + commonstockid).style.display = 'none';
}
if (document.getElementById('preordercart' + commonstockid)) {
document.getElementById('preordercart' + commonstockid).style.display = '';
}
if (USE_AS_CATALOG == 1) {
if (document.getElementById('preordercart' + commonstockid)) {
document.getElementById('preordercart' + commonstockid).style.display = 'none';
}
}
}
}
}
//isStock = false;
}
if (document.getElementById('stockQuantity' + commonstockid)) {
if (stockAmount > 0 || preorder_stock > 0) {
document.getElementById('stockQuantity' + commonstockid).style.display = '';
} else {
document.getElementById('stockQuantity' + commonstockid).style.display = 'none';
}
}
return isStock;
} | [
"function checkStock(variant) {\n var backorder = $variant_input.data('backorder'),\n nostock = $variant_input.data('nostock'),\n isBackorder = $.inArray(variant, backorder),\n isNostock = $.inArray(variant, nostock);\n\n // if its backordered, add class backorder (remove other classes)\n if (isBackorder != -1 && isNostock == -1) {\n $variant_input.addClass('backorder').removeClass('out-of-stock').removeClass('in-stock');\n hideNoMore();\n showBackordered();\n showQuantity();\n }\n // if its out of stock, add class out-of-stock (remove other classes)\n else if (isBackorder == -1 && isNostock != -1) {\n $variant_input.addClass('out-of-stock').removeClass('backorder').removeClass('in-stock');\n hideBackordered();\n showNoMore();\n hideQuantity();\n }\n // if neither (in stock), remove all classes\n else if (isBackorder == -1 && isNostock == -1) {\n $variant_input.addClass('in-stock').removeClass('out-of-stock').removeClass('backorder');\n hideBackordered();\n hideNoMore();\n showQuantity();\n }\n }",
"calculateTradeAmount(side, curAQuantity, usdtQuantity, price, initService){\n //Buy - we need to calculate how much token we can get for our USDT\n if(side == process.env.BUY){\n //Trade a little bit less than we currently hold to ensure valid transaction\n let amount = 1 / price * usdtQuantity * 1000 / 1001;\n\n //All binance transactions require a maximum precision level or fail\n amount = amount.toFixed(initService.precision);\n return amount;\n } else if(side == process.env.SELL){\n let amount = curAQuantity * 1000 / 1001;\n amount = amount.toFixed(initService.precision);\n return amount;\n }\n }",
"function topstock1() {\n homeStocksRef.on('value', getStockInfo1, errData);\n }",
"function checkStock(product,card, button){\r\n\tif(product.UnitsInStock == 0){\r\n\t\tcard.style.backgroundColor = \"#768A74\";\r\n\t\tbutton.disabled = true;\r\n\t} else {\r\n\t\tbutton.disabled = false;\r\n\t\tcard.style.backgroundColor = \"#A2D69F\";\r\n\t}\r\n\t\r\n\t\r\n}",
"function stockProductos(stock){\n if(stock<=0){\n alert(\"no hay stock disponible\")\n }else{\n stock--;\n alert(\"Gracias por su compra\" + nombre);\n console.log(\"stock actualizado\" + stock);\n }\n}",
"function getStockSymbols(stocks) {\n var symbols = [], // empty array that is going to store our symbols\n counter, // keeps track of the current index in the array\n stock; // keeps track of the current stock in the array\n\n // three parts\n // first part is what we want to get executed, initializing the counter which will point to the first index in the array\n // second part is the condition that we want to be true as long as we want the for loop to continue, in this case we want\n // the for loop to continue as like as the counter is smaller than the length of the stocks\n // the third part is what we want to execute at the bottom of each iteration thru the loop, and in this case we want to\n // increment counter\n for(counter = 0; counter < stocks.length; counter++){\n // assigning stock at the index of the counter\n // were looping through each item in the stocks array and assigning it to variable stock\n stock = stocks[counter];\n // we are adding to the symbols array and pull out the symbol from the stock and add it to the symbols array\n symbols.push(stock.symbol);\n }\n\n return symbols;\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 }",
"async function getBuySellQuotes(exchange0, exchange1, exchange0Pair, exchange1Pair, borrowAmount) {\n\n ////we need to check if our base token is smaller this lets us determine the pool t borrow from, we alsways\n //borrow from smaller pool as we see bwlo\n var baseTokenSmaller = await flashBot.methods.isbaseTokenSmaller(exchange0Pair, exchange1Pair).call();\n baseTokenSmaller = baseTokenSmaller[0]\n\n var baseToken;\n \n //depending on result we set the base token to etehr dai or 1 (we take the loan out in this toen)\n if (baseTokenSmaller) {\n baseToken = await exchange0.methods.dai().call()\n } else {\n baseToken = await exchange1.methods.token1().call();\n }\n\n //next we order our reserves again borrow from smaller pool sell on higher\n var orderedReserves = await flashBot.methods.getOrderedReserves(exchange0Pair, exchange1Pair, baseTokenSmaller).call();\n console.log(orderedReserves[0])\n orderedReserves = orderedReserves[2];\n //lower and higher price pools after eserver sorting (see TradeOrder.sol)\n const lowerPricePool = orderedReserves[0];\n const higherPricePool = orderedReserves[1];\n\n // borrow quote token on lower price pool, // sell borrowed quote token on higher price pool.\n // var borrowAmount = web3.utils.toWei(amountToTradeInEth.toString(), \"Ether\");\n var debtAmount = await registry.uniswapRouterContract.methods.getAmountIn(borrowAmount, orderedReserves[0], orderedReserves[1]).call();\n var baseTokenOutAmount = await registry.uniswapRouterContract.methods.getAmountOut(borrowAmount, orderedReserves[3], orderedReserves[2]).call();\n \n return [ baseTokenOutAmount, debtAmount, baseToken, lowerPricePool, higherPricePool];\n}",
"function buy_half_shares() {\n // Makes a fair split of cash and shares with start money for initialization\n var half_cash = cash / 2.0;\n var half_shares = Math.round(half_cash / data[0]);\n cash -= half_shares * data[0];\n shares = half_shares;\n liveSend(get_trade_report('Buy', data[0], half_shares));\n update_portfolio();\n\n}",
"function stockFirst(item){\n return item.inventory < 3\n}",
"calculateSqsPrice(fullTrace, fifoQueueChunkAmount = 0, isTraceFromCache = false) {\n // Pricing per 1 million Requests after Free tier(Monthly)\n // Standard Queue $0.40 ($0.0000004 per request)\n // FIFO Queue $0.50 ($0.0000005 per request)\n\n // FIFO Requests\n // API actions for sending, receiving, deleting, and changing visibility of messages from FIFO\n // queues are charged at FIFO rates. All other API requests are charged at standard rates.\n\n // Size of Payloads\n // Each 64 KB chunk of a payload is billed as 1 request\n // (for example, an API action with a 256 KB payload is billed as 4 requests).\n\n let messageAmountsPerType\n if (isTraceFromCache) {\n messageAmountsPerType = {\n standard: Number(fullTrace),\n fifo: Number(fifoQueueChunkAmount),\n }\n } else {\n const sqsRequestsMapPerQueue = calculateSqsRequestAmountsPerQueue(fullTrace)\n const queueUrls = Object.keys(sqsRequestsMapPerQueue)\n messageAmountsPerType = queueUrls.reduce((acc, url) => {\n const queueType = sqsRequestsMapPerQueue[url].QueueType\n const SendMessageRequestAmount = sqsRequestsMapPerQueue[url].SendMessage\n\n return {\n ...acc,\n [queueType]: acc[queueType] + SendMessageRequestAmount,\n }\n }, {\n standard: 0,\n fifo: 0,\n })\n }\n\n const { fifo, standard } = this.sqsPricing\n // in Nano USD\n const sqsStandardPrice = Number(`${standard}e9`) * messageAmountsPerType.standard\n const sqsFIFOPrice = Number(`${fifo}e9`) * messageAmountsPerType.fifo\n\n const sqsTotalPrice = sqsStandardPrice + sqsFIFOPrice\n return sqsTotalPrice\n }",
"function checkStock(response, answers) {\n var chosenItem = {\n item_id: 'invalid item'\n };\n\n //match user choice with the correct item\n for (var i = 0; i < response.length; i++) {\n if (answers.itemChoice == response[i].item_id) {\n chosenItem = response[i];\n }\n }\n //ensures that the customer has chosen a valid item\n if (chosenItem.item_id !== 'invalid item') {\n if (chosenItem.stock_quantity > answers.quantity) {\n console.log('Sufficient stock');\n var total = parseFloat(chosenItem.price) * parseFloat(answers.quantity);\n chosenItem.stock_quantity = parseFloat(chosenItem.stock_quantity) - parseFloat(answers.quantity);\n chosenItem.product_sales = parseFloat(chosenItem.product_sales) + total;\n console.log('You are purchasing ' + answers.quantity + ' ' + chosenItem.product_name + '.');\n console.log('Your total is: $' + total);\n updateProductTable(chosenItem);\n\n } else {\n inquirer.prompt([\n {\n type: 'input',\n name: 'anything',\n message: 'Insufficient stock. Please select fewer items, or wait until the stock has been replenished.\\nPress enter to continue.\\n'\n }\n ]).then(function () {\n getChoices();\n })\n }\n } else {\n console.log('You must select a valid item.')\n getChoices();\n }\n}",
"placeSellOrder() {\n let price = this.calculatePrice('sell');\n let amount = this.calculateAmount();\n let balance = this.balances.getBalance(this.quote)\n if(balance < amount) {\n console.log(`insufficient ${this.quote} balance, cannot place order (balance: ${balance}, order amount: ${amount}`);\n return;\n }\n this.orderService.placeOrder(this.symbol, 'sell', amount, price);\n }",
"function recalculate_moqioq_flag(product_id)\n{\n\tvar selected_supplier =order_list[product_id].selected_supplier;\n\t//if no supplier is selected return \n\tif (selected_supplier == -1) return;\n\t//get supplier moq, ioq\n\tvar moq = order_list[product_id].pricing_list[selected_supplier].moq;\n\tvar ioq = order_list[product_id].pricing_list[selected_supplier].ioq;\n\tvar product_qty = order_list[product_id].quantity;\n\t\n\tif ((product_qty<moq)||((product_qty-moq)%ioq!=0))\n\t\torder_list[product_id].moqioqflag = false;\t\t\n\telse \n\t\torder_list[product_id].moqioqflag = true;\t\n\n\t//See if off invoice applies - TBI\n\tvar supplier_id = order_list[product_id].selected_supplier;\n\tif (supplier_id!=-1) \n\t{\n\t\tvar minimum_quantity = order_list[product_id].pricing_list[supplier_id].minimum_quantity;\n\t\tvar offinvoice = order_list[product_id].pricing_list[supplier_id].offinvoice;\n\t\tvar pecentinvoice = order_list[product_id].pricing_list[supplier_id].percentinvoice;\n\t\tvar valueinvoice = order_list[product_id].pricing_list[supplier_id].valueinvoice;\n\t\tif (product_qty>=minimum_quantity)\n\t\t{\n\t\t\tif (offinvoice==1)\n\t\t\t{\n\t\t\t\tif (valueinvoice!=0)\n\t\t\t\t{\n\t\t\t\t\torder_list[product_id].selected_price = parseFloat(order_list[product_id].pricing_list[supplier_id].price) - valueinvoice;\n\t\t\t\t\torder_list[product_id].selected_discount = valueinvoice;\n\t\t\t\t}\n\t\t\t\telse if (percentinvoice!=0)\n\t\t\t\t{\n\t\t\t\t\torder_list[product_id].selected_price = parseFloat(order_list[product_id].pricing_list[supplier_id].price) * (1- (parseFloat(percentinvoice)/100));\n\t\t\t\t\torder_list[product_id].selected_discount = parseFloat(order_list[product_id].pricing_list[supplier_id].price) * (parseFloat(percentinvoice)/100);\n\t\t\t\t}\n\t\t\t}\n\t\t\torder_list[product_id].selected_rebate = order_list[product_id].pricing_list[supplier_id].rebate; //TBI\n\t\t}\n\t\telse\n\t\t{\n\t\t\torder_list[product_id].selected_price =parseFloat(order_list[product_id].pricing_list[supplier_id].price).toFixed(2);\n\t\t\t\n\t\t\t//order_list[product_id].selected_price = parseFloat(order_list[product_id].pricing_list[supplier_id].price)\n\t\t}\n\t}\n\t\n\t\n\t/*if ((product_qty<moq)||((product_qty-moq)%ioq!=0)\n\t\torder_list[product_id].moqioqflag = false;\t\t\n\telse \n\t\torder_list[product_id].moqioqflag = true;\t\t*/\n\t//redraw - TBD\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 fulfillOrder(order) {\n\tfor (var i = 0; i < order.items.length; i++) {\n\t\tif (order.items[i].isBase) {\n\t\t\tvar item = baseItems.get(order.items[i].type, order.items[i].name);\n\t\t} else {\n\t\t\tvar item = optionalItems.get(order.items[i].type, order.items[i].name);\n\t\t}\n\t\tif (item.stock < 1) {\n\t\t\tthrow \"ERROR: Trying to fullfill an order without stock\";\n\t\t}\n\t\titem.stock--;\n\t}\n\tvar id = order.setId();\n\torders.unshift(order);\n\tsyncToStorage();\n\treturn id;\n}",
"async getStocks (stockString) {\n\n return await axios.get(`https://portfolio-408-main.herokuapp.com/Portfol.io/Batch/Stock/${stockString}`);\n }",
"function getOrder(/*set objects here*/) {\r\n var totalPrice = 0;\r\n var totalCalories = 0;\r\n\r\n for (let i = 0; i < arguments.length; i++)\r\n {\r\n totalPrice = totalPrice + arguments[i].price;\r\n totalCalories = totalCalories + arguments[i].calories;\r\n }\r\n\r\n console.log(\"С вашего счета снято \" + totalPrice);\r\n console.log(\"Вы наели на \" + totalCalories + \" калорий\");\r\n}",
"function removeFromPortfolio() { \n portfolioArr = JSON.parse(localStorage.getItem(\"stock\"));\n portfolioCash = localStorage.getItem(\"cash\");\n let quantity = parseInt(stockSaleInput.val());\n console.log(sellQuantityAvailable);\n console.log(quantity);\n\n if(sellQuantityAvailable < quantity){\n $(\"#errorMessageDiv\").text(\"Insufficient shares available.\")\n }\n else {\n let saleTotal = quantity * sellPrice;\n portfolioCash = parseFloat(portfolioCash) + saleTotal;\n localStorage.setItem(\"cash\", portfolioCash);\n for (i=0 ; i<portfolioArr.length; i++){\n if(sellStock === portfolioArr[i].name){\n portfolioArr[i].quantity -= quantity;\n }\n }\n stockArr = JSON.stringify(portfolioArr);\n localStorage.setItem(\"stock\", stockArr);\n $(\"#portfolioDisplayDiv\").empty();\n generatePortfolio();\n $(\"#modalSell\").modal('close');\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
resizePanels goes through each tab panel within the sidebar and resizes their height to use all the available height. | resizePanels () {
// Retrieve the current window height.
const windowHeight = window.innerHeight
// Retrieve the top position of the HTML Element containing all the tab
// panels.
const panelsTopPosition = this.get('panelsTopPosition')
// Update the height of each panel.
this.get('panels').each((index, panel) => {
panel.style.height = (windowHeight - panelsTopPosition) + 'px'
})
} | [
"resizeTabContents() {\n let change = $(`#pcm-tabbedPandas`).height() - this.tabNavHeight;\n if (change !== 0 && this.tabContentsHeight > 0) { $('#pcm-pandaTabContents .pcm-tabs').height(`${this.tabContentsHeight - change}px`); }\n if (MyPandaUI !== null) MyPandaUI.innerHeight = window.innerHeight;\n this.tabContentsHeight = $('#pcm-pandaTabContents .pcm-tabs:first').height(); this.tabNavHeight = $(`#pcm-tabbedPandas`).height();\n }",
"function setSize(container) { \n\t\tvar opts = $.data(container, 'tabs').options; \n\t\tvar cc = $(container); \n\t\tif (opts.fit == true){ \n\t\t\tvar p = cc.parent(); \n\t\t\topts.width = p.width(); \n\t\t\topts.height = p.height(); \n\t\t} \n\t\tcc.width(opts.width).height(opts.height); \n\t\t \n\t\tvar header = $('>div.tabs-header', container); \n\t\tif ($.boxModel == true) { \n\t\t\tvar delta = header.outerWidth() - header.width(); \n//\t\t\tvar delta = header.outerWidth(true) - header.width(); \n\t\t\theader.width(cc.width() - delta); \n\t\t} else { \n\t\t\theader.width(cc.width()); \n\t\t} \n\t\t \n\t\tsetScrollers(container); \n\t\t \n\t\tvar panels = $('>div.tabs-panels', container); \n\t\tvar height = opts.height; \n\t\tif (!isNaN(height)) { \n\t\t\tif ($.boxModel == true) { \n\t\t\t\tvar delta = panels.outerHeight() - panels.height(); \n\t\t\t\tpanels.css('height', (height - header.outerHeight() - delta) || 'auto'); \n\t\t\t} else { \n\t\t\t\tpanels.css('height', height - header.outerHeight()); \n\t\t\t} \n\t\t} else { \n\t\t\tpanels.height('auto'); \n\t\t} \n\t\tvar width = opts.width; \n\t\tif (!isNaN(width)){ \n\t\t\tif ($.boxModel == true) { \n\t\t\t\tvar delta = panels.outerWidth() - panels.width(); \n//\t\t\t\tvar delta = panels.outerWidth(true) - panels.width(); \n\t\t\t\tpanels.width(width - delta); \n\t\t\t} else { \n\t\t\t\tpanels.width(width); \n\t\t\t} \n\t\t} else { \n\t\t\tpanels.width('auto'); \n\t\t} \n\t\t \n\t\tif ($.parser){ \n\t\t\t$.parser.parse(container); \n\t\t} \n\t\t \n//\t\t// resize the children tabs container \n//\t\t$('div.tabs-container', container).tabs();\t \n\t}",
"function adjustFrameContainerSizes () {\n\t\tvar windowHeight = $(window).height();\n\t\tvar windowWidth = $(window).width();\n\t\tvar maxSidePanelWidth = 300;\n\t\tvar maxBottomPanelHeight = 270;\n\n\t\tvar sidePanelWidth = (windowWidth * .3);\n\t\tsidePanelWidth = (sidePanelWidth > maxSidePanelWidth) ? maxSidePanelWidth : sidePanelWidth;\n\n\t\tvar midPanelWidth = windowWidth - sidePanelWidth;\n\n\t\tvar bottomPanelHeight = (windowHeight * .25);\n\t\t//console.log('bottomPanelHeight='+bottomPanelHeight);\n\t\tbottomPanelHeight = (bottomPanelHeight > maxBottomPanelHeight) ? maxBottomPanelHeight : bottomPanelHeight;\n\t\t//console.log('bottomPanelHeight='+bottomPanelHeight);\n\t\tvar midPanelHeight = windowHeight - bottomPanelHeight;\n\n\t\t$('#midPanelContainer').css({\n\t\t\t'height' : midPanelHeight + 'px',\n\t\t\t'width' : midPanelWidth + 'px'\n\t\t});\n\n\t\t$('#bottomPanelContainer').css({\n\t\t\t'height' : bottomPanelHeight + 'px',\n\t\t\t'width' : midPanelWidth + 'px'\n\t\t});\n\n\t\t$('#rightPanelContainer').css({\n\t\t\t'width' : sidePanelWidth + 'px'\n\t\t});\n\t}",
"function fitWindowSize() {\n // fit mainContainer to body size\n document.getElementById(\"mainContainer\").style.height = $('body').height() - 41 + 'px';\n \n //alert($('body').height() + ' ' + document.getElementById('mainContainer').style.height);\n \n // refresh mainTabs\n $('#mainTabs').tabs('resize');\n \n // select the tab again to complete the resizing the tab\n var tab = $('#mainTabs').tabs('getSelected');\n $('#mainTabs').tabs('select', tab.panel('options').title);\n}",
"function resizeSidebar() {\n var sidebarOffset = 0;\n var element = document.getElementById('page-sidebar');\n\n while (element) {\n sidebarOffset += (element.offsetTop - element.scrollTop + element.clientTop);\n element = element.offsetParent;\n }\n\n var calculatedHeight = window.innerHeight - sidebarOffset;\n document.getElementById('page-sidebar').setAttribute(\"style\", \"height:\" + calculatedHeight + \"px\");\n }",
"function resizeDynamicScrollingPanels()\n{\n\tvar scrollingWrappers = $$('div.scrollingWrapper');\n\tvar productCells = $$('div.scrollingWrapper div.productCell');\n\t// we need to get this figure now, because the offset width of the visible product\n\t// differs from the offsetWidth of the not-visible product\n\tvar productOffsetWidth = productCells.first().offsetWidth;\n\n\tscrollingWrappers.each(\n\t\tfunction(currentElement)\n\t\t{\n\t\t\tif(currentElement.childElements().size() > 0)\n\t\t\t{\n\t\t\t\t// make the container big enough to handle all the children\n\t\t\t\t// the 1.1 is for margin of error\n\t\t\t\tcurrentElement.style.width = ((currentElement.childElements().size() * productOffsetWidth) * 1.02) + 'px';\n\t\t\t}\n\t\t}\n\t)\n}",
"function resizeHashtagSelectionSidebar() {\n\tvar windowHeight = $(window).height();\n\n\thashtagSelectionSidebar.outerHeight(windowHeight);\n}",
"function resizeSideBar(e) {\n var w = window.innerWidth;\n var h = window.innerHeight - parseInt(window.getComputedStyle($(\"ul\")).height);\n var s = (w > h ? h : w);\n // side bar height\n $(\"#Sidebar\").style.height = h + \"px\";\n}",
"function setupDimensions() {\n\t$('.opt').css('width', width/numtabs+'px');\n\t$('.sub').css('width', width+'px');\n\t$('.sub').css('overflow', 'hidden');\n\t$('.controlgroup').css('width', numtabs*width+'px');\n\t$('#camera').css('margin-top', '1px');\n\t$('#camera').css('margin-bottom', '2px');\n\t$('.controlgroup').css('margin-top', '1px');\n\t$('.controlgroup').css('margin-bottom', '2px');\n\t$('#topbar').height($('#back').height());\n\t$('#topbar').css('padding', 'auto auto auto 10px');\n\t$('#back').css('margin', 'auto 10px auto');\n\t$('#text').css('height', (height-4*($('#enter').height()+10)-($('#topbar').height()+6))+'px');\n\t$('#text').css('width', width*3/4-10+'px');\n\t$('#links').css('height', (height-4*($('#enter').height()+10)-($('#topbar').height()+6))+'px');\n\t$('#links').css('width', width/4-10+'px');\n\t$('.bottom_opt').css('width', width/5+'px');\n}",
"function resizeLayout() {\n var max = 0,\n ctas = $('.callouts li').each(function() {\n $(this).css(\"height\", \"auto\");\n max = Math.max(max, $(this).height());\n }).height(max + 'px');\n\n if ($(document.documentElement).hasClass('ltie9')) {\n fix_aspect_ratio();\n } else {\n fix_background_image();\n }\n }",
"function fitSubPlotsHeight() {\n var height = $sonarElement.height();\n\n _.each(config.subPlots, function (subPlot) {\n subPlot.element.height(Math.floor(subPlot.height * height));\n });\n }",
"function saveNavPanels() {\n var basePath = getBaseUri(location.pathname);\n var section = basePath.substring(1,basePath.indexOf(\"/\",1));\n writeCookie(\"height\", resizePackagesNav.css(\"height\"), section);\n}",
"function slideContentHeight() {\n var contentHeight = $('.active-content').height();\n $('.radio-slide-content').css('height', contentHeight + 25);\n }",
"function adjustSizes() {\n var selectHeight = poemList.length * 15;\n var newHeight = Math.max(350, selectHeight);\n selectBar.setSize(maxWidth, newHeight);\n $(selectBar.canvas).parent().height(\"350px\");\n $(\"poem\").height(maxHeight);\n}",
"function ResizeScreenAfterContainerResize() {\r\n\r\n $(\"div [id$=InsertGridSubstance]\").css(\"height\", \"50%\");\r\n $(\"div [id$=InsertGridHealthHistory]\").css(\"height\", \"100\");\r\n}",
"function updateDimensions() {\n styleContentElements();\n parentDimensions = getParentDimensions();\n playerDimensions = getPlayerDimensions();\n }",
"_hardcodeDimensions() {\n const currentHeight = this._current && this._current.getBoundingClientRect().height || 0;\n let tallestHeight = 0;\n\n // Hardcode the height of each collapse to allow CSS transition\n this._elements.forEach(el => {\n el.classList.remove('is-ready');\n el.style.height = 'auto';\n\n const itemHeight = el.closest('.accordion-list__item').getBoundingClientRect().height;\n const collapseHeight = el.getBoundingClientRect().height;\n\n el.style.height = `${collapseHeight}px`;\n el.classList.add('is-ready');\n tallestHeight = Math.max(tallestHeight, itemHeight);\n });\n\n // Set a min-height on the container to avoid wiggles during transitions\n this._accordion.style.minHeight = 'auto';\n const minHeight = this._accordion.getBoundingClientRect().height - currentHeight + tallestHeight + 18;\n this._accordion.style.minHeight = `${minHeight}px`;\n }",
"function resizeTables (frame) {\n\t\tvar frameWidth = frame.geometricBounds[3] - frame.geometricBounds[1];\n\t\tvar tables = frame.tables.everyItem().getElements();\n\t\tfor (var i = tables.length-1; i >= 0; i--) {\n\t\t\tif (tables[i].width !== frameWidth) {\n\t\t\t\tresizeTable (tables[i], frameWidth);\n\t\t\t}\n\t\t\t// tables[i].rows.everyItem().autoGrow = false;\n\t\t\t// tables[i].rows.everyItem().height = 12;\n\t\t}\n\t}",
"_handleResize(e) {\n this.resizeToolbar();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that creates dashboard panel from the drag and drop element passed | function createDashboardPanel(el) {
var title = el.dataset.title;
var elementId = el.dataset.id;
var elementExists = $('#' + elementId);
if (!elementExists) {
var panel = document.createElement("div");
panel.setAttribute("id", elementId);
panel.classList.add('panel');
panel.classList.add('panel-default');
var panelHeader = document.createElement("div");
panelHeader.classList.add('panel-heading');
var panelTitle = document.createElement("div");
panelTitle.classList.add('panel-title');
panelTitle.innerText = title;
var deleteIcon = document.createElement("i");
deleteIcon.classList.add('far');
deleteIcon.classList.add('deleteIcon');
deleteIcon.classList.add('fa-trash-alt');
deleteIcon.classList.add('fa-fw');
deleteIcon.classList.add('pull-right');
deleteIcon.setAttribute('title', 'Remove Item');
panelTitle.appendChild(deleteIcon);
panelHeader.appendChild(panelTitle);
panel.appendChild(panelHeader);
var panelBody = document.createElement("div");
panelBody.classList.add('panel-body');
panel.appendChild(panelBody);
return panel;
}
} | [
"function createPanel( pw, ph, director ){\n\t\tdashBG = new CAAT.Foundation.ActorContainer().\n\t\t\t\t\tsetPreferredSize( pw, ph ).\n\t\t\t\t\tsetBounds( 0, 0, pw, ph ).\n\t\t\t\t\tsetClip(false);\n\n \n\t\t//create bottom panel\n\t\tfor(var i=0;i<dashBoardEle.length;i++){\n\t\t\tvar oActor = game.__addImageOnScene( game._director.getImage(dashBoardEle[i][0]), 1, 1 );\n\t\t\toActor.\t\t\t\n\t\t\t\tsetLocation(dashBoardEle[i][1], dashBoardEle[i][2]);\n\t\t\t\n\t\t\tdashBG.addChild(oActor);\t\t\t\n\t\t}\t\t\t\n\t\t\n\t\t__createDashBoardTxt();\n\t\t__createDashBoardButton();\t\n\t\t__createIncDecButton();\n\t\treturn dashBG;\n\t}",
"createUI() {\n var title = panelTitle;\n this.panel = new PanelClass(this.viewer, title);\n var button1 = new Autodesk.Viewing.UI.Button(panelTitle);\n\n button1.onClick = (e) => {\n if (!this.panel.isVisible()) {\n this.panel.setVisible(true);\n } else {\n this.panel.setVisible(false);\n }\n };\n\n button1.addClass('fa');\n button1.addClass('fa-child');\n button1.addClass('fa-2x');\n button1.setToolTip(onMouseOver);\n\n this.subToolbar = this.viewer.toolbar.getControl(\"spinalcom-sample\");\n if (!this.subToolbar) {\n this.subToolbar = new Autodesk.Viewing.UI.ControlGroup('spinalcom-sample');\n this.viewer.toolbar.addControl(this.subToolbar);\n }\n this.subToolbar.addControl(button1);\n this.initialize();\n }",
"function dragdropElementos(){\n $('img').draggable({\n\t\tcontainment: '.panel-tablero',\n grid: [115, 95],\n droppable: 'img',\n\t\trevert: true,\n\t\trevertDuration: 100,\n\t\topacity: 0.8,\n\t\tzIndex: 1,\n\t});\n\t$('img').droppable({\n\t\tdrop: intercambiar\n\t});\n}",
"function applyDragDropPanel(url, method)\r\n{\r\n \tvar htmlAreaObj = _getWorkAreaDefaultObj();\r\n\tvar objAjax = htmlAreaObj.getHTMLAjax();\r\n\tvar objHTMLData = htmlAreaObj.getHTMLDataObj();\r\n\tsectionName = objAjax.getDivSectionId();\r\n\r\n\t//Add condition for your action class url to check to see that all\r\n\t//arrays for items pertaining to your screen are not empty.\r\n\tif(url == \"materialpaletteoverview.do\")\r\n\t{\r\n\t\tif(mtrArray.length < 1)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n if(objAjax && objHTMLData)\r\n {\r\n bShowMsg = true;\r\n\r\n //Add condition for your action class url to add correct request params\r\n if(url == \"materialpaletteoverview.do\")\r\n {\r\n \tvar materials=getComps(mtrArray);\r\n //Tracker#18331 REGRESSION:UNABLE TO DRAG & DROP ARTWORKS THAT HAVE '&' IN ARTWORK COMBO NAME\r\n\t\t //Using Ajax call instead of loadWorkArea function and passing the parameter separately\r\n \tif(objAjax)\r\n \t\t{\r\n \t\tobjAjax.setActionURL(url);\r\n \t\tobjAjax.setActionMethod(method);\r\n \t\tobjAjax.parameter().add(\"materials\", materials);\r\n \t\tobjAjax.parameter().add(\"atnbtn\", actionId);\r\n \t\tobjAjax.parameter().add(\"delimiter\", _grdCompSep);\r\n \t\tobjAjax.setProcessHandler(_showWorkArea);\r\n \t\tobjAjax.sendRequest();\r\n \t}\r\n }\r\n }\r\n cancelSetting();\r\n}",
"function spawnDropZone() {\n Sortable.create(trash, {\n group: \"tag\",\n onAdd: function(evt) {\n this.el.removeChild(evt.item)\n }\n })\n Sortable.create(dep, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n }\n })\n Sortable.create(arr, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n }\n })\n Sortable.create(push, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n }\n })\n Sortable.create(taxi, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n }\n })\n Sortable.create(rwy, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy1, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy2, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy3, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy4, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy5, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy6, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy7, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy8, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy9, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n Sortable.create(rwy10, {\n group: 'tag',\n animation: 100,\n onAdd: function(evt) {\n state(evt.item.children[2].value, evt.item.parentNode)\n },\n onRemove: function(evt) {\n state(evt.item.children[2].value, evt.from)\n },\n })\n\n}",
"function createMenuPanel(panelID){\n const menuPanel = document.createElement(\"div\");\n menuPanel.className = \"menuPanel\";\n menuPanel.id = panelID;\n content.append(menuPanel);\n\n //Remove top margin of \"content\" div\n content.style.marginTop = \"0px\";\n}",
"function componentDropHandler(event, ui) {\n\tconst $item = $(ui.item);\n\tif (!$item.hasClass('drag-component')) {\n\t\t// if it is not dragged from the side; do nothing\n\t\treturn;\n\t}\n\n\t// remove leftover #just-dropped-down element, which could have spawned\n\t// from creating component with modal\n\tlet cnt = 0;\n\twhile ($(\"#just-dropped-down\").length != 0) {\n\t\t$div = $(\"#just-dropped-down\");\n\t\t$div.removeAttr('id');\n\t\tif ($div.html() == \"\") {\n\t\t\t$div.remove();\n\t\t}\n\t\tcnt++; // avoid infinite loop for some reason. should always run only 1 time.\n\t\tif (cnt > 5) {\n\t\t\tconsole.error('Fatal error: infinite loop in removing just-dropped-down!')\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tvar cmp = $item.attr('id');\n\t$item.empty();\n\t$item.removeAttr(\"style\");\n\t$item.removeAttr(\"class\");\n\t$item.off();\n\t$item.addClass('ud');\n\t$item.attr(\"id\", \"just-dropped-down\"); // drop to this element & remove later\n if (cmp === \"img-cmp\") {\n open_img_selection();\n }\n else if (cmp === 'textbox-cmp') {\n\t\t$item.append($('<div class=\"editable\">'+\n\t\t\t\t\t\t'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Dictum at tempor commodo ullamcorper. Ac turpis egestas maecenas pharetra convallis posuere morbi. Neque viverra justo nec ultrices. Commodo odio aenean sed adipiscing diam donec. Habitant morbi tristique senectus et netus et malesuada fames ac. Iaculis nunc sed augue lacus viverra. Cras sed felis eget velit aliquet sagittis id consectetur. Nunc scelerisque viverra mauris in aliquam. Vel fringilla est ullamcorper eget nulla facilisi etiam dignissim.'+\n\t\t\t\t\t '</div>'));\n editor = new MediumEditor('.editable', editable_settings);\n }\n else if (cmp === 'rule-cmp') {\n $item.append('<div class=\"ud\"><br><hr><br></div>');\n }\n else if (cmp === 'space-cmp') {\n $item.append('<div class=\"ud space\"></div>');\n }\n else if (cmp === 'quote-cmp') {\n $item.append(\n '<blockquote class=\"ud\">' +\n '<span class=\"editable ud\">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae!</span>' +\n '<cite class=\"editable ud\">Somebody famous</cite>' +\n '</blockquote>'\n );\n initializeEditable();\n }\n else if (cmp === 'embed-cmp') {\n resetGeneralModal();\n $('#embed-target').removeAttr('id');\n $('#add-general-input').click(addTargetEmbed);\n $('#general-modal .modal-header').text('ADD EMBED HTML CONTENT');\n $('#general-modal').modal('open');\n }\n else if (cmp === 'row-cmp') {\n $item.append(\n '<div class=\"row\">' +\n \t'<div class=\"col s4\">' +\n \t\t'<div class=\"editable\">This a column. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor</div>' +\n \t'</div>' +\n \t'<div class=\"col s4\">' +\n \t\t'<div class=\"editable\">This a column. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor</div>' +\n \t'</div>' +\n \t'<div class=\"col s4\">' +\n \t\t'<div class=\"editable\">This a column. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor</div>' +\n \t'</div>' +\n '</div>'\n );\n initializeEditable();\n }\n console.log('you dropped ' + cmp +' into the page preview!');\n}",
"function create_preview_segment(node_id, draggable_element_id) {\n table_selector = 'table#'.concat(draggable_element_id)\n $('#preview .table').addClass('d-none');\n cloned_table = $(table_selector).clone(true);\n cloned_table.attr({\n 'id': node_id,\n\n })\n cloned_table.removeClass('d-none')\n $('#preview').append(cloned_table);\n}",
"function buildSouthPane(p_data) {\n var l_html = \"<div class=\\\"ui-layout-south\\\">\" +\n \"<div id=\\\"south_title\\\" class=\\\"header ui-widget-header\\\"></div>\" +\n \"<div id=\\\"south_file\\\" class=\\\"file\\\"></div>\" +\n \"</div>\";\n\n jQuery(l_html).appendTo('body');\n }",
"async function generatePokemonPanel(panelToAppendTo, pokemonObject) {\r\n const name = pokemonObject.name;\r\n \r\n const pokemonPanel = document.createElement(\"div\");\r\n pokemonPanel.style.backgroundColor = \"#46ACC2\"\r\n panelToAppendTo.appendChild(pokemonPanel);\r\n pokemonPanel.style.margin = \"50px\";\r\n pokemonPanel.addEventListener(\"click\", displayClickedPokemonDetails);\r\n pokemonPanel.id = name;\r\n\r\n const pokemonPanelPictureElement = document.createElement(\"img\");\r\n const pokemonPanelPictureAddress = \"https://trex-sandwich.com/pokesignment/img/\" + pokemonObject.image;\r\n pokemonPanelPictureElement.src = pokemonPanelPictureAddress;\r\n pokemonPanel.appendChild(pokemonPanelPictureElement);\r\n pokemonPanelPictureElement.id = name;\r\n pokemonPanelPictureElement.setAttribute(\"width\", \"100%\");\r\n\r\n const pokemonPanelNameElement = document.createElement(\"h2\");\r\n const pokemonPanelName = pokemonObject.name;\r\n pokemonPanelNameElement.innerHTML = `<strong id=${name}>${name}</strong>`;\r\n pokemonPanel.appendChild(pokemonPanelNameElement);\r\n pokemonPanelNameElement.style.fontSize = \"medium\";\r\n pokemonPanelNameElement.style.paddingBottom = \"10px\";\r\n pokemonPanelNameElement.id = name;\r\n pokemonPanelNameElement.setAttribute(\"width\", \"100\")\r\n }",
"function setHtmlPanel(){\n\t\t\n\t\t//add panel wrapper\n\t\tg_objWrapper.append(\"<div class='ug-grid-panel'></div>\");\n\t\t\n\t\tg_objPanel = g_objWrapper.children('.ug-grid-panel');\n\t\t\n\t\t//add arrows:\n\t\tif(g_temp.isHorType){\n\t\t\t\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-left-hortype ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-right-hortype ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\t\n\t\t\tg_objArrowPrev = g_objPanel.children(\".grid-arrow-left-hortype\");\n\t\t\tg_objArrowNext = g_objPanel.children(\".grid-arrow-right-hortype\");\n\t\t}\n\t\telse if(g_options.gridpanel_vertical_scroll == false){\t\t//horizonatl arrows\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-left ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-right ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\t\n\t\t\tg_objArrowPrev = g_objPanel.children(\".grid-arrow-left\");\n\t\t\tg_objArrowNext = g_objPanel.children(\".grid-arrow-right\");\n\t\t\t\n\t\t}else{\t\t//vertical arrows\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-up ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\tg_objPanel.append(\"<div class='grid-arrow grid-arrow-down ug-skin-\" + g_options.gridpanel_arrows_skin + \"'></div>\");\n\t\t\t\n\t\t\tg_objArrowPrev = g_objPanel.children(\".grid-arrow-up\");\n\t\t\tg_objArrowNext = g_objPanel.children(\".grid-arrow-down\");\n\t\t}\n\t\t\n\t\tg_panelBase.setHtml(g_objPanel);\n\t\t\n\t\t//hide the arrows\n\t\tg_objArrowPrev.fadeTo(0,0);\n\t\tg_objArrowNext.fadeTo(0,0);\n\t\t\n\t\t//init the grid panel\n\t\tg_options.parent_container = g_objPanel;\n\t\tg_gallery.initThumbsPanel(\"grid\", g_options);\n\t\t\n\t\t//get the grid object\n\t\tvar objects = g_gallery.getObjects();\n\t\tg_objGrid = objects.g_objThumbs;\n\t\t\n\t\tsetHtmlProperties();\n\t}",
"buildSimpleDisplayPanel(title, single, double, immune) {\n single = single || []\n double = double || []\n immune = immune || []\n\n let panel = document.createElement(\"div\");\n panel.classList.add(\"panel\");\n\n let label = document.createElement(\"h3\");\n label.classList.add(\"label\");\n label.innerText = title;\n panel.appendChild(label);\n\n immune.forEach((t) => { panel.appendChild(this.buildType(t, false, \"immune\", \"small\")) });\n double.forEach((t) => { panel.appendChild(this.buildType(t, false, \"double\", \"small\")) });\n single.forEach((t) => { panel.appendChild(this.buildType(t, false, \"small\")) });\n\n return panel;\n }",
"function make_dragable_var(divid){\n new Draggable( divid, \n\t\t { ghosting: true, \n\t\t revert: true, \n\t\t\t scroll: window }); \n}",
"function FluidPanel() {}",
"onDemandCreateGUI() {\n \n if (this.internal.parentDomElement===null)\n return;\n \n this.internal.parentDomElement.empty();\n \n let basediv=webutil.creatediv({ parent : this.internal.parentDomElement});\n this.internal.domElement=basediv;\n \n let f1 = new dat.GUI({autoPlace: false});\n basediv.append(f1.domElement);\n\n // Global Properties\n let s1_on_cb=(e) => {\n let ind=this.internal.data.allnames.indexOf(e);\n this.setCurrentGrid(ind);\n };\n\n this.internal.data.allnames=[];\n for (let i=0;i<this.internal.multigrid.getNumGrids();i++) {\n this.internal.data.allnames.push(this.internal.multigrid.getGrid(i).description);\n }\n \n let sl=f1.add(this.internal.data,'currentname',this.internal.data.allnames).name(\"Current Grid\");\n sl.onChange(s1_on_cb);\n\n let dp=f1.add(this.internal.data,'showmode',this.internal.data.allshowmodes).name(\"Grids to Display\");\n let dp_on_cb=() => {\n this.showhidemeshes();\n this.updategui(true);\n };\n dp.onChange(dp_on_cb);\n\n webutil.removedatclose(f1);\n\n \n // --------------------------------------------\n let ldiv=$(\"<H4></H4>\").css({ 'margin':'15px'});\n basediv.append(ldiv);\n\n this.internal.landlabelelement=webutil.createlabel( { type : \"success\",\n name : \"Current Electrode Properties\",\n parent : ldiv,\n });\n let sbar=webutil.creatediv({ parent: basediv});\n let inlineform=webutil.creatediv({ parent: sbar});\n let elem1=webutil.creatediv({ parent : inlineform,\n css : {'margin-top':'20px', 'margin-left':'10px'}});\n \n let elem1_label=$(\"<span>Electrode: </span>\");\n elem1_label.css({'padding':'10px'});\n elem1.append(elem1_label);\n this.internal.currentelectrodeselect=webutil.createselect({parent : elem1,\n values : [ 'none' ],\n callback : (e) => {\n this.selectElectrode(e.target.value,true);\n this.centerOnElectrode();\n },\n });\n\n this.internal.checkbuttons={};\n\n let sbar2=webutil.creatediv({ parent: basediv});\n for (let i=0;i<PROPERTIES.length;i++) {\n this.internal.checkbuttons[PROPERTIES[i]]=\n webutil.createcheckbox({\n name: PROPERTIES[i],\n type: \"info\",\n checked: false,\n parent: sbar2,\n css: { 'margin-left': '5px' ,\n 'margin-right': '5px',\n 'width' : '100px'}\n });\n }\n \n \n \n\n // ----------- Landmark specific stuff\n\n if (this.internal.gridPropertiesGUI===null) {\n const f2 = new dat.GUI({autoPlace: false});\n console.log('F2=',f2,JSON.stringify(this.internal.data));\n \n console.log('Creating modal');\n let modal=webutil.createmodal(\"Grid Properties\",\"modal-sm\");\n this.internal.gridPropertiesGUI=modal.dialog;\n modal.body.append(f2.domElement);\n\n \n console.log('Radius=',this.internal.data.radius);\n \n f2.add(this.internal.data, 'radius',0.5,8.0).name(\"Radius\").step(0.5).onChange(() => {\n let grid=this.internal.multigrid.getGrid(this.internal.currentgridindex);\n grid.radius=this.internal.data.radius;\n this.updateMeshes(true);\n });\n \n console.log('Color=',this.internal.data.color);\n \n f2.addColor(this.internal.data, 'color').name(\"Landmark Color\").onChange(()=> { \n this.updatecolors();\n });\n \n webutil.removedatclose(f2);\n this.internal.folders=[f1, f2];\n } else {\n this.internal.folders[0]=f1;\n }\n // Save self for later\n \n // ---------------\n // rest of gui \n // ---------------\n\n let bbar0=webutil.createbuttonbar({ parent: basediv,\n css : {'margin-top': '20px','margin-bottom': '10px'}});\n\n \n let update_cb=() => { this.updateGridProperties();};\n webutil.createbutton({ type : \"primary\",\n name : \"Display Properties\",\n position : \"bottom\",\n tooltip : \"Click this to set advanced display properties for this set (color,radius)\",\n parent : bbar0,\n callback : update_cb,\n });\n\n let load_cb=(f) => { this.loadMultiGrid(f); };\n webfileutil.createFileButton({ type : \"warning\",\n name : \"Load\",\n position : \"bottom\",\n tooltip : \"Click this to load points from either a .mgrid or a .bisgrid file\",\n parent : bbar0,\n callback : load_cb,\n },{\n filename : '',\n title : 'Select file to load current landmark set from',\n filters : [ { name: 'Landmark Files', extensions: ['bisgrid','land' ]}],\n save : false,\n suffix : \".bisgrid,.mgrid\",\n });\n\n let save_cb=(f) => {\n f=f || 'landmarks.bisgrid';\n console.log('f=',f);\n let suffix=f.split(\".\").pop();\n if (suffix===\"land\")\n return this.exportMultiGrid(f);\n else\n return this.saveMultiGrid(f);\n };\n\n\n \n webfileutil.createFileButton({ type : \"primary\",\n name : \"Save\",\n position : \"bottom\",\n tooltip : \"Click this to save points to a .bisgrid or .mgrid file\",\n parent : bbar0,\n callback : save_cb,\n },\n {\n filename : '',\n title : 'Select file to load current landmark set from',\n filters : [ { name: 'Landmark Files', extensions: ['bisgrid','land' ]}],\n save : true,\n suffix : \".bisgrid,.mgrid\",\n initialCallback : () => { return this.getInitialSaveFilename(); },\n });\n\n \n webutil.createbutton({ type : \"info\",\n name : \"Multisnapshot (Current Grid)\",\n parent : bbar0,\n css : {\n 'margin-top': '20px',\n 'margin-left': '10px'\n },\n callback : () => { this.multisnapshot(false).catch( (e) => { console.log(e);});}\n });\n\n webutil.createbutton({ type : \"danger\",\n name : \"Multisnapshot (All Grids)\",\n parent : bbar0,\n css : {\n 'margin-top': '20px',\n 'margin-left': '10px'\n },\n callback : () => { this.multisnapshot(true).catch( (e) => { console.log(e);});}\n });\n\n \n webutil.tooltip(this.internal.parentDomElement);\n \n // ----------------------------------------\n // Now create modal\n // ----------------------------------------\n\n \n\n }",
"function dragAndDropItem() {\n $(\".empName\").each(function(){\n $(this).draggable({helper : \"clone\"});\n });\n $(\"#rolesTable ul > li\").droppable({\n drop: function(event, ui) {\n var $className = $(this).find('ul').attr(\"class\");\n if (!($(ui.draggable).hasClass($className))) {\n $(ui.draggable).addClass($className);\n var $li = insert_element($(\"<li></li>\").attr(\"emp\",$(ui.draggable).text()), \"newRow\", $(this).find('ul'));\n $li.text($(ui.draggable).text());\n insert_element($(\"<input/>\").attr(\"type\",\"image\").attr(\"src\",\"images/button.jpg\"), \"cancelButton\", $li);\n updateToDo($className, $(ui.draggable).text());\n }\n onhoverElement($(this).find(\"ul li\"));\n }\n });\n}",
"function clone(obj, addInsidePanel, $whereToPut) {\n var $obj = $(obj);\n var $newElement=null;\n \n if ( addInsidePanel ) {\n $newElement=$(\"<div></div>\");\n $newElement.append($(obj.cloneNode(true)));\n } else {\n $newElement=$(obj.cloneNode(true));\n }\n \n $newElement.\n css(\"position\",\"absolute\").\n css(\"top\" ,$obj.offset().top - $obj.scrollTop()).\n css(\"left\" ,$obj.offset().left - $obj.scrollLeft() ).\n css(\"width\" ,$obj.width()).\n css(\"height\",$obj.height());\n\n if ( $whereToPut ) {\n $whereToPut.append($newElement);\n } else if ( $webSiteContainer!=null ) {\n $webSiteContainer.append($newElement);\n }\n\n $obj.hide();\n \n return $newElement;\n }",
"makeWidget(els) {\r\n let el = GridStack.getElement(els);\r\n this._prepareElement(el, true);\r\n this._updateContainerHeight();\r\n this._triggerAddEvent();\r\n this._triggerChangeEvent();\r\n return el;\r\n }",
"function createWidgetDepartment(idContainer, cssClassWidget, name, idAdditionalEmployee) {\n var contentForWidgetOnMainPage = idAdditionalEmployee ? '<div class=\"containerOtdels\"> ' + departmentsTree[name] + '</div>' +\n '<div id=\"' + idAdditionalEmployee + '\" class=\"additionalEmployee\"> </div></div>' : \"\";\n $(idContainer).append('<div class=\"' + cssClassWidget + '\">' +\n '<div class=\"title_inner\"> ' + name + '</div>' + contentForWidgetOnMainPage);\n if (idAdditionalEmployee && departmentsTree[name] && departmentsTree[name].hasOwnProperty(\"additionalEmployess\")) {\n var names = departmentsTree[name].additionalEmployess;\n var id = \"#\" + idAdditionalEmployee;\n for (var i = 0; i <= names.length; i++) {\n getOnePersonFromSearch(names[i], id);\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a dictionary and a template function build a string | function template(dictionary, templateFn) {
return Object.keys(dictionary)
.map(item => templateFn(item))
.reduce((acc, memo) => acc + memo);
} | [
"function template(dom, object) {\n\treturn dom.replace(/{(\\w+)}/g, function(_, k) {\n\t\treturn object[k];\n\t});\n}",
"function template(str, data) {\n return new Function(\"obj\",\n \"var p=[],print=function(){p.push.apply(p,arguments);};\" +\n\n // Introduce the data as local variables using with(){}\n \"with(obj){p.push('\" +\n\n // Convert the template into pure JavaScript\n str.replace(/[\\r\\t\\n]/g, \" \")\n .replace(/'(?=[^%]*%>)/g,\"\\t\")\n .split(\"'\").join(\"\\\\'\")\n .split(\"\\t\").join(\"'\")\n .replace(/<%=(.+?)%>/g, \"',$1,'\")\n .split(\"<%\").join(\"');\")\n .split(\"%>\").join(\"p.push('\")\n + \"');}return p.join('');\")(data || {});\n}",
"function dictToHtml(d) {\n html = \"\"\n d = limitDict(d)\n for (var k in d) {\n x = k.replace(/_/g,\" \")\n y = d[k]\n if(typeof(y)==\"string\"){\n y = d[k].replace(/_/g,\" \")\n }else if(typeof(y)==\"number\"){\n y = r(y)\n } else if(typeof(y)==\"object\"){\n y = d[k].toString().replace(/_/g,\" \")\n }\n html += x + \": \" + y + \"<br>\"\n }\n return html\n}",
"function mapString(m, keyFunc, valFunc) {\n // Creating an array per frame is bad, but let's optimize later if we need\n // to (given this should be used debug-only).\n let res = [];\n for (let key of m.keys()) {\n res.push(keyFunc(key) + ' (' + valFunc(m.get(key)) + ')');\n }\n return res.join(', ');\n}",
"function fill (template, data) {\n\n Object.keys(data).forEach(function (key) {\n var placeholder = \"{{\" + key + \"}}\";\n var value = data[key];\n\n while (template.indexOf(placeholder) !== -1) {\n template = template.replace(placeholder, value);\n }\n });\n\n return template;\n}",
"_evalExpression(exp) {\n exp = exp.trim();\n\n // catch special cases, with referenced properties, e.g. resourceGroup().location\n let match = exp.match(/(\\w+)\\((.*)\\)\\.(.*)/);\n if(match) {\n let funcName = match[1].toLowerCase();\n let funcParams = match[2];\n let funcProps = match[3].toLowerCase();\n if(funcName == 'resourcegroup' && funcProps == 'id') return 'resource-group-id'; \n if(funcName == 'resourcegroup' && funcProps == 'location') return 'resource-group-location'; \n if(funcName == 'subscription' && funcProps == 'subscriptionid') return 'subscription-id'; \n if(funcName == 'deployment' && funcProps == 'name') return 'deployment-name'; \n }\n \n // It looks like a function\n match = exp.match(/(\\w+)\\((.*)\\)/);\n if(match) {\n let funcName = match[1].toLowerCase();\n let funcParams = match[2];\n //console.log(`~~~ function: *${funcName}* |${funcParams}|`);\n \n if(funcName == 'variables') {\n return this._funcVariables(this._evalExpression(funcParams));\n }\n if(funcName == 'uniquestring') {\n return this._funcUniquestring(this._evalExpression(funcParams));\n } \n if(funcName == 'concat') {\n return this._funcConcat(funcParams, '');\n }\n if(funcName == 'parameters') {\n // This is a small cop out, but we can't know the value of parameters until deployment!\n // So we just display curly braces around the paramter name. It looks OK\n return `{{${this._evalExpression(funcParams)}}}`;\n } \n if(funcName == 'replace') {\n return this._funcReplace(funcParams);\n } \n if(funcName == 'tolower') {\n return this._funcToLower(funcParams);\n } \n if(funcName == 'toupper') {\n return this._funcToUpper(funcParams);\n } \n if(funcName == 'substring') {\n return this._funcSubstring(funcParams);\n } \n if(funcName == 'resourceid') {\n // Treat resourceId as a concat operation with slashes \n let resid = this._funcConcat(funcParams, '/');\n // clean up needed\n resid = resid.replace(/^\\//, '');\n resid = resid.replace(/\\/\\//, '/');\n return resid;\n } \n }\n\n // It looks like a string literal\n match = exp.match(/^\\'(.*)\\'$/);\n if(match) {\n return match[1];\n }\n\n // It looks like a number literal\n match = exp.match(/^(\\d+)/);\n if(match) {\n return match[1].toString();\n }\n\n // Catch all, just return the expression, unparsed\n return exp;\n }",
"function template(url, subdomains) {\n\tvar n = subdomains.length,\n\t\tsalt = ~~(Math.random() * n); // per-session salt\n\n\t/** Returns the given coordinate formatted as a 'quadkey'. */\n\tfunction quad(column, row, zoom) {\n\t\tvar key = \"\";\n\t\tfor (var i = 1; i <= zoom; i++) {\n\t\t\tkey += (((row >> zoom - i) & 1) << 1) | ((column >> zoom - i) & 1);\n\t\t}\n\t\treturn key;\n\t}\n\n\treturn function (c) {\n\t\tvar quadKey = quad(c.column, c.row, c.zoom),\n\t\t\tserver = Math.abs(salt + c.column + c.row + c.zoom) % n;\n\t\treturn url\n\t\t\t.replace(\"{quadkey}\", quadKey)\n\t\t\t.replace(\"{subdomain}\", subdomains[server]);\n\t};\n}",
"function makeHtml(options) {\n options = options || {};\n\n var parts, fnCounter, propId, props;\n\n // Tagged function can be called multiple times, need to generate unique\n // IDs and track unique values per full use (until html.done is called).\n function reset() {\n parts = [];\n fnCounter = 0;\n propId = props = undefined;\n }\n reset();\n\n // The html() function used for the tagged template string. Call\n // html.done() to get the final string result.\n function html(strings, ...values) {\n strings.forEach(function(str, i) {\n // If there is no following value, at the end, just return;\n if (i >= values.length) {\n parts.push(str);\n return;\n }\n\n var value = values[i];\n if (!options.toStringAll &&\n typeof value !== 'string' &&\n !(value instanceof EscapedValue)) {\n // Check for propName=\" as the end of the previous string, if so, it\n // is a name to a property to be set/called later with the value.\n var match = propRegExp.exec(str);\n // data-prop should go the string path, since that is a defined HTML\n // API that maps to element.dataset.prop.\n if (match && match[1].indexOf('data-') !== 0) {\n if (propId === undefined) {\n propId = (idCounter++);\n }\n\n var propValueId = 'id' + (fnCounter++);\n\n if (!props) {\n props = {};\n }\n\n var propName = match[1];\n // Convert a-prop-name to aPropName\n if (propName.indexOf('-') !== -1) {\n propName = propName.split('-').map(function(part, partIndex) {\n return partIndex === 0 ?\n part : part.charAt(0).toUpperCase() + part.substring(1);\n }).join('');\n }\n\n props[propValueId] = {\n value: value,\n propName: propName\n };\n\n value = propValueId;\n\n // Swap out the attribute name to be specific to this html() use,\n // to make query selection faster and targeted.\n str = str.substring(0, match.index) + ' data-htemplateprop' +\n propId + '=\"';\n }\n }\n\n parts.push(str);\n\n if (value instanceof EscapedValue) {\n value = value.escapedValue;\n } else {\n if (typeof value !== 'string') {\n value = String(value);\n }\n value = esc(value);\n }\n parts.push(value);\n });\n }\n\n // Generates the final response by concatenating the previous html`` calls\n // into the final result.\n html.done = function() {\n var text = parts.join('');\n\n if (propId !== undefined) {\n // Process the text to replace multiple data-htemplateprop attributes\n // with one that groups the values. Otherwise the browser will just keep\n // the first value.\n text = groupProps(propId, text);\n }\n\n var result = {\n text: text\n };\n\n if (propId !== undefined) {\n result.propId = propId;\n result.props = props;\n }\n\n reset();\n\n return result;\n };\n\n return html;\n }",
"function format(string, vars) {\n\tif (vars) {\n\t\tfor (var k in vars) {\n\t\t\tstring = string.replace(new RegExp('\\\\{' + k + '\\\\}', 'g'), vars[k]);\n\t\t}\n\t}\n\treturn string;\n}",
"function hashMapToStr(hm){\n\t//init result\n\t//ES 2016-09-17 (b_dbg_test): shorten the text (needed for debugger to display\n\t//\tcontent of complex objects compactly)\n\tvar res = \"HM{\";\n\t//init if have not processed hashmap, yet\n\tvar isFirst = true;\n\t//check if hashmap is not empty\n\tif( Object.keys(hm).length > 0 ){\n\t\t//loop thru keys\n\t\t$.each(\n\t\t\thm, \n\t\t\tfunction(key, value){\n\t\t\t\t//ES 2016-09-17 (b_dbg_test): if value has 'getTypeName' function AND\n\t\t\t\t//\tit is either ENTITY or CONTENT\n\t\t\t\tif( typeof value.getTypeName === \"function\" &&\n\t\t\t\t\t(\n\t\t\t\t\t\tvalue.getTypeName() == RES_ENT_TYPE.CONTENT ||\n\t\t\t\t\t\tvalue.getTypeName() == RES_ENT_TYPE.ENTITY\n\t\t\t\t\t)\n\t\t\t\t){\n\t\t\t\t\t//reset value to be actual content's value\n\t\t\t\t\tvalue = interpreter.getContentObj(value)._value;\n\t\t\t\t}\t//ES 2016-09-17 (b_dbg_test): end if 'getTypeName' and either ENTITY or CONTENT\n\t\t\t\t//convert value\n\t\t\t\tvar val = objToStr(value);\n\t\t\t\t//check if val is not empty string\n\t\t\t\tif( val.length != 0 ){\n\t\t\t\t\t//compose string\n\t\t\t\t\tres += (isFirst ? \"\" : \", \") + key + \" => \" + val;\n\t\t\t\t\t//ensure it is not the first key\n\t\t\t\t\tisFirst = false;\n\t\t\t\t}\t//end if cal is not empty string\n\t\t\t}\t//end iterative function to loop thru hashmap\n\t\t);\t//end loop thru hashmap\n\t}\t//end if hashmap is not empty\n\treturn res + \"}\";\n}",
"function buildString() {\n var outString = arguments[0];\n for(var i = 1; i < arguments.length; i++) {\n outString = outString.replace(new RegExp(\"\\\\$\\\\[\" + i + \"\\\\]\", \"g\"), arguments[i]);\n }\n return outString;\n }",
"wrapToFunction(template, ...localVariables) {\n const args = ['template', 'state', 'ctx'].concat(localVariables);\n return new Function('', `return function template (${args.join(',')}) { ${template} }`)();\n }",
"function generate_title_from_dict(tags_dict, order_pre, order_post) {\n var title = '';\n var keys = Object.keys(tags_dict);\n keys.sort();\n order_pre.forEach(function(tag) {if(tag in tags_dict) {title += display_tag(tag, tags_dict[tag], true); }});\n keys.forEach(function (tag) { tag_v = tags_dict[tag]; if($.inArray(tag, order_pre) < 0 && $.inArray(tag, order_post) < 0) {title += display_tag(tag,tag_v, true); }});\n order_post.forEach(function(tag) {if(tag in tags_dict) {title += display_tag(tag, tags_dict[tag], true); }});\n return title;\n}",
"function generateTableRow(key, value) {\n return \"<tr><td>\" + key + \"</td><td>\" + value + \"</td></tr>\";\n}",
"function fnExoticToStringTag() {}",
"function stringifyWithFunctions(obj) {\n // first stringify except mark off functions with markers\n var str = JSON.stringify(obj, function (key, value) {\n // if the value is a function, we want to wrap it with markers\n if (!!(value && value.constructor && value.call && value.apply)) {\n return FUNC_START + value.toString() + FUNC_STOP;\n }\n else {\n return value;\n }\n });\n // now we use the markers to replace function strings with actual functions\n var startFuncIdx = str.indexOf(FUNC_START);\n var stopFuncIdx, fn;\n while (startFuncIdx >= 0) {\n stopFuncIdx = str.indexOf(FUNC_STOP);\n // pull string out\n fn = str.substring(startFuncIdx + FUNC_START.length, stopFuncIdx);\n fn = fn.replace(/\\\\n/g, '\\n');\n str = str.substring(0, startFuncIdx - 1) + fn + str.substring(stopFuncIdx + FUNC_STOP.length + 1);\n startFuncIdx = str.indexOf(FUNC_START);\n }\n return str;\n}",
"function formatDynamicDataRef(str, format)\r\n{\r\n var ret = str;\r\n var iStart = getIndexOfEchoForResponseWrite(str);\r\n\r\n if (iStart > -1)\r\n {\r\n var iEnd = str.search(/;\\s*\\?>/);\r\n if (iEnd == -1)\r\n {\r\n iEnd = str.search(/\\s*\\?>/);\r\n }\r\n \r\n if (iEnd > -1)\r\n {\r\n // The one and only argument is the function to ASP function to call.\r\n \r\n ret = str.substring(0, iStart) + \r\n ((str.charAt(iStart-1) != \" \")? \" \" : \"\") + \r\n format.func + \"(\" + str.substring(iStart, iEnd) + \")\" + \r\n str.substr(iEnd);\r\n }\r\n else\r\n {\r\n // Error: no termination of the PHP block.\r\n // alert(\"no end to PHP\");\r\n }\r\n }\r\n else\r\n {\r\n // Error: no start of PHP block.\r\n // alert(\"no equals\");\r\n }\r\n\r\n\treturn ret;\r\n}",
"function buildInfoTemplate(popupInfo) {\n var json = {\n content: \"<table>\"\n };\n\n dojo.forEach(popupInfo.fieldInfos, function (field) {\n if (field.visible) {\n json.content += \"<tr><td valign='top'>\" + field.label + \": <\\/td><td valign='top'>${\" + field.fieldName + \"}<\\/td><\\/tr>\";\n }\n });\n json.content += \"<\\/table>\";\n return json;\n}",
"function combineHandlebarsCompiledTemplates(exampleJSON) {\n var helpers = \"\"; //insert helpers here\n var templates = \" \";\n var templatesCollection = db._collection(module.context.collectionName(\"handlebarsTemplates\"));\n templatesCollection.load();\n var tc;\n if (exampleJSON == null) {\n tc = templatesCollection.all();\n } else {\n tc = templatesCollection.byExample(exampleJSON);\n }\n\n while (tc.hasNext()) {\n var templateObject = tc.next();\n templates += `templates['${templateObject._key}'] = template(${templateObject.compiled});`;\n if (typeof templateObject.helpers == \"string\") {\n helpers += templateObject.helpers;\n }\n }\n\n var template = `(function() { \n ${helpers} \n var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};\n ${templates}\n })();`;\n\n return template;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all videos from back end, adding average ratings and work with scroll in order to load more videos | function getVideos() {
if (vm.busy) {
return;
}
vm.busy = true;
var itemsDom = angular.element('.video').length,
items = (itemsDom === 0) ? 10 : itemsDom += 2;
VideosService.getVideos(items)
.then(function(response) {
if (response.status === 'success') {
vm.videos = response.data;
getAverageRankings(response.data);
vm.busy = false;
} else if (response.status === 'error') {
vm.errors = response.error;
}
})
.catch(function(err) {
vm.errors = err.error;
});
} | [
"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}",
"function loadMoreRecords(){\n if(count == 0){\n count++;\n }else{\n getAllVideos(self.videos.length,10);\n }\n }",
"function loadTopRated(page) {\n fetch(\"https://api.themoviedb.org/3/movie/top_rated?api_key=642874b006093ef1d8becb7a5a90179c&page=\" + page + \"\").then(function (resp) {\n return resp.json();\n }).then(function (resp) {\n var searchResult = resp.results;\n var maxLength = resp.total_pages;\n document.getElementById(\"movie-section\").innerHTML = \"\".concat(searchResult.map(movieCard).join(\"\"));\n document.getElementById(\"btns-container\").innerHTML = paginationCont();\n shortText();\n\n function paginationPage() {\n var btnNext = document.getElementById(\"nextBtn\");\n var btnPrev = document.getElementById(\"prevBtn\");\n\n function prevPage() {\n if (page > 1) {\n // currentPage--;\n loadTopRated(page - 1);\n }\n }\n\n function nextPage() {\n if (page < maxLength) {\n // currentPage++;\n loadTopRated(page + 1);\n console.log(page);\n }\n }\n\n btnNext.addEventListener(\"click\", nextPage);\n btnPrev.addEventListener(\"click\", prevPage);\n }\n\n paginationPage();\n });\n}",
"function loadVideo() {\n\t\tvar d = new Date();\n\t\tvar lastYear = d.getFullYear() - 1;\n\t\tvar month = d.getMonth() +1;\n\t\tvar day = d.getDate();\n\t\tvar myKey = \"AIzaSyAr0fnc8B-t96isVPUByudWNPFDKJIugoc\";\n\t\tvar request = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=10&order=viewCount&publishedAfter='+lastYear+'-'+month+'-'+day+'T00%3A00%3A00Z&q=teaser|trailer -india|game&type=video&videoCaption=any&relevanceLanguage=en&videoCategoryId=24&videoEmbeddable=true&key=' + myKey;\n\t\t$.ajax({\n\t\t\turl: request,\n\t\t\tsuccess: function (data) {\n\t\t\t\tvar id = data.items[0].id.videoId;\n\n\t\t\t\tdata.items.forEach(buildArray);\n\n\t\t\t\tplayVideo();\n\n\t\t\t}\n\t\t});\n\t}",
"function calculateAverage(){\n var sum = 0;\n for(var i = 0; i < self.video.ratings.length; i++){\n sum += parseInt(self.video.ratings[i], 10);\n }\n\n self.avg = sum/self.video.ratings.length;\n }",
"function getVideosWithTagsAndComments() {\n return getVideos()\n .then(function (videos) {\n return Promise.all([\n getTagsForVideos(videos),\n getCommentsForVideos(videos)\n ]).then(results => populateVideos(videos, ...results) )\n })\n }",
"async function getLikedVideoCount() {\n var filters = {\n \"part\": \"id\",\n \"maxResults\": 1,\n \"myRating\": \"like\"\n };\n\n console.log(\"getLikedVideoCount()\");\n return await gapi.client.youtube.videos.list(filters).then(\n function(response) {\n return response.result.pageInfo.totalResults;\n },\n function(err) {\n console.error(\"getLikedVideoCount(): client.youtube.videos.list failed\", err);\n return err;\n }\n );\n}",
"function getMostViewedEpisodes() {\n let api = \"../api/Episodes\";\n ajaxCall(\"GET\", api, \"\", getSuccessMostViewedEpisodes, errorMostViewedEpisodes);\n}",
"function displaySimilarMovies(movieId) {\n // api url info\n type = \"movie/\" + movieId + \"/similar\";\n let url = apiUrl + type + apiKey;\n\n fetch(url).then(response => response.json()).then(function(obj) {\n const NUMBER_OF_SIMILAR_MOVIES = 4;\n for (let i = 0; i < NUMBER_OF_SIMILAR_MOVIES; i++) {\n let img = imagePathPrefix + obj.results[i].poster_path;\n let title = obj.results[i].title;\n let genre = obj.results[i].genre_ids[0];\n let year = obj.results[i].release_date.substring(0, 4);\n let id = obj.results[i].id;\n document.getElementById(\"similar-movies\").innerHTML += \"<div class=' card mx-auto my-4 text-center col-12 col-sm-12 col-md-5 col-lg-3 col-xl-3' style='max-width: 18rem;'>\" +\n \"<img class='card-img-top mx-auto my-auto' style='max-width:16.5rem; max-height:300px;' src='\" + img + \"' alt='Card image cap'>\" +\n \" <div class='card-body'>\" +\n \"<h5 maxlength = '30' class='card-title'>\" + title + \"</h5>\" +\n \" <a href='#' class='card-link text-muted text-decoration-none'>\" + genre + \"</a>\" +\n \" <a href='#' class='card-link text-muted text-decoration-none'>(\" + year + \")</a>\" +\n \"<a href='#' onclick='previewItem(\" + id + \")' class='btn btn-primary btn-warning my-4 d-block'>View details</a>\" +\n \"</div> </div>\"\n }\n })\n\n}",
"function nextVideoByVotes()\n { \n var votes = [];\n Object.keys(videoVotes).forEach(function (key) \n { \n var value = videoVotes[key];\n votes.push([key, value]);\n });\n \n // Find highest voted video\n var highestVoted = [\"\", 0];\n for (var i = 0; i < votes.length; i++)\n {\n if (votes[i])\n {\n if (votes[i][1] > highestVoted[1] && votes[i][1] >= videoByVoteThresh)\n {\n highestVoted = votes[i];\n }\n }\n }\n \n if (videoVotes.length == 0 || highestVoted[0].length == 0)\n {\n nextVideo();\n return;\n }\n \n var highestVotedId = highestVoted[0];\n sendVideoChange(highestVotedId);\n }",
"function getRecentVideos( age ){\n var videoCollection = new Array();\n // get an array of avalible videos for this age\n if( Object.keys(video_player_data).length > 0 ){\n for (let i = 0; i < Object.keys(video_player_data).length; i++) { //recorre cada lista\n let key = Object.keys(video_player_data)[i];\n \n if( video_player_data[key][\"age\"] == 0 || video_player_data[key][\"age\"] == age ){\n for(let j = 0; j < Object.keys(video_player_data[key][\"type\"]).length; j++) { //recorre cada type\n let type_key = Object.keys(video_player_data[key][\"type\"])[j]\n\n for (let k = 0; k < Object.keys(video_player_data[key][\"type\"][type_key][\"playList\"]).length; k++) { //recorre el playlist\n let list_key = Object.keys(video_player_data[key][\"type\"][type_key][\"playList\"])[k]; \n\n videoCollection.push({\n \"key\": key, \n \"type_key\": type_key, \n \"list_key\": list_key,\n \"date\" : video_player_data[key][\"type\"][type_key][\"playList\"][list_key][\"date\"]\n });\n }\n }\n }\n }\n }\n\n // order the array by dates\n videoCollection.sort((a, b) => {\n let c = new Date(a.date);\n let d = new Date(b.date);\n \n return d - c;\n });\n\n return videoCollection;\n}",
"function populateVideos(drinkNameClick) {\n\n // Empty youtube div before populating\n $(\"#youTube\").empty();\n\n // Append youtube videos to the div\n $(\"#youTube\").append(\n '<div id=\"player1\"></div><div id=\"player2\"></div><div id=\"player3\"></div><div id=\"player4\"></div>'\n );\n\n\n // Puts video in an array \n var playerInfoList = [];\n $.ajax({\n method: 'GET',\n url: 'https://www.googleapis.com/youtube/v3/search?',\n data: {\n\n // Queries youtube API using the drink name \n q: 'how to make ' + drinkNameClick + ' drink',\n part: 'snippet',\n\n // API key \n\n key: 'AIzaSyCeUFpT98eO4cX9_pvFhQ4Jd_ssX51Ojyo',\n\n // Displays 4 videos not 5, not sure why number needs to be one higher to display desired amount \n maxResults: 5\n },\n dataType: 'jsonp'\n\n }).then(function (response) {\n console.log(response);\n var results = response.items;\n\n // Value parameter required, but doesn't get read \n $.each(results, function (index, value) {\n\n // Video player parameters\n var videoObj = {\n id: 'player',\n height: '25%',\n width: '100%',\n videoId: results[index].id.videoId,\n\n // This causes quota usage to only use 20 units instead of 200 :)\n type: 'video'\n }\n\n // Pushes the video player parameters into the player list array \n playerInfoList.push(videoObj);\n });\n onYouTubePlayerAPIReady();\n function onYouTubePlayerAPIReady() {\n for (var i = 0; i < playerInfoList.length; i++) {\n console.log(playerInfoList.length);\n\n // Targets player ids in the HTML, and populates embedded video with iframe into them \n player = new YT.Player('player' + [i], {\n height: '25%',\n width: '100%',\n videoId: playerInfoList[i].videoId\n });\n }\n }\n });\n\n // Creates script tag for the iFrame, in the HTML before all other scripts\n var tag = document.createElement('script');\n\n tag.src = \"https://www.youtube.com/iframe_api\";\n\n var firstScriptTag = document.getElementsByTagName('script')[0];\n firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);\n\n // End Youtube API \n }",
"function searchfunctionality(id){\n let count = 0;\n\n uploadedVideoContainer.style.display = 'none'; \n sysGeneratedPlaylistContainer.style.display = 'none';\n subscribersContainer.style.display = 'none';\n activitiesContainer.style.display = 'none';\n createPlaylistContainer.style.display = 'none';\n updatePlaylistContainer.style.display = 'none';\n searchContainer.style.display = 'block';\n\n const requestOptions = {\n part: 'snippet',\n maxResults: 10,\n topicId: id,\n type: 'video'\n }\n\n const request = gapi.client.youtube.search.list(requestOptions);\n\n request.execute(res => {\n const listItems = res.items;\n if(listItems){\n let output = '<h4 class=\"center-align\">Search Results</h4>'\n\n //loop through videos\n listItems.forEach(item => {\n const videoId = item.id.videoId;\n\n if(count === 10){\n return;\n }\n\n if(item.id.kind.includes('video')){\n output += `\n <div class=\"col s12\">\n <h5>${item.snippet.title}</h5>\n <iframe width=\"100%\" height=\"600px\" src=\"https://www.youtube.com/embed/${videoId}\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen>\n </iframe>\n </div>\n `;\n\n count++;\n }\n });\n\n searchContainer.innerHTML = output;\n } \n else{\n searchContainer.innerHTML = 'No resultls for given keyword'\n }\n })\n}",
"function getVideosByPopular(){\r\n //pick a random category ID, from the list of IDs\r\n var index = randInt(collectedData.categories.list.length);\r\n var categoryId = collectedData.currentCategory = collectedData.categories.list[index].id;\r\n\r\n //if we've already loaded videos for that category, no need for api call\r\n if( collectedData.categories[categoryId].loaded ){\r\n //get list of comments for random video in given category\r\n getCommentThread();\r\n }\r\n //otherwise we need to get the videos for this category from YouTube api \r\n else{\r\n var request = gapi.client.youtube.videos.list({\r\n part: 'id',\r\n chart: 'mostPopular',\r\n videoCategoryId: categoryId,\r\n maxResults: 50,\r\n\r\n });\r\n request.execute( function(response){\r\n //if network error, let user know with the option to try loading new comments\r\n if( response.code == -1 ){\r\n noConnectionError(true);\r\n }\r\n //otherwise, continue\r\n else{\r\n //if the response returns with videos for given category...\r\n if (response.items && response.items.length >= 1){\r\n //loop through the returned videos\r\n for (var i = 0; i < response.items.length; i++){\r\n //push object containing video id into given category's list array\r\n collectedData.categories[categoryId].list.push(response.items[i]);\r\n //create object property for category id, and populate it with\r\n //default 'unloaded' object\r\n //this will hold comments for this video in future\r\n collectedData.categories[categoryId][response.items[i].id] = {list: [], loaded: false};\r\n }\r\n //store the fact that the videos have been loaded for given category\r\n collectedData.categories[categoryId].loaded = true;\r\n //get list of comments for random video from this response \r\n getCommentThread();\r\n }\r\n //otherwise\r\n else{\r\n //, remove this category from our category list, since there are no videos \r\n //(or none left) and... \r\n removeIndex(collectedData.categories, index);\r\n //invoke this function again. should not recursively loop forever, since we remove\r\n //any categories that do not have videos \r\n getVideosByPopular();\r\n }\r\n }\r\n });\r\n }\r\n}",
"async function fetchStats(){\n const response = await fetch(\"https://youtube.googleapis.com/youtube/v3/videos?part=statistics&id=cjrOxszo6No&key=AIzaSyCZ0Nc68EsVvYNKeOeRsVGxnSehYBus3Xc\")\n const responseJ = await response.json()\n const stats = responseJ.items[0].statistics\n let rating = Math.floor(Number(stats.likeCount) / (Number(stats.likeCount) + Number(stats.dislikeCount)) * 100);\n console.log(\"Likes: \" + stats.likeCount);\n console.log(\"Dislikes:\" + stats.dislikeCount);\n console.log(\"Rating: \" + rating);\n console.log(stats);\n}",
"static async apiGetUserReviewMovies(req, res, next) {\n try {\n const user_id = req.query.user_id;\n const reviewsList = await ReviewsDAO.getReviewsByUser(user_id);\n let moviesReviewed = new Array(reviewsList.length);\n \n // For each of this user's reviews, get the corresponding movie\n for (let i = 0; i < reviewsList.length; i++) {\n let currReview = reviewsList[i];\n moviesReviewed[i] = await MoviesDAO.getMoviesByID(currReview.movie_id);\n }\n \n res.json(moviesReviewed);\n } catch (e) {\n res.status(500).json({ error: e.message });\n }\n }",
"function video_height(){\r\n var _height = $('.gallery-image').height();\r\n $('.video-item').height(_height);\r\n }",
"function loadVideoList() {\n state.videos.forEach((video) => {\n\n // create a new video option for the video selection list\n const opt = document.createElement(\"option\");\n opt.value = video.id;\n opt.text = `${video.id}: ${video.title.substring(0, 30)}${video.title.length > 30\n ? '...'\n : ''} (${video.duration}s)`;\n domCache['videos'].options.add(opt);\n });\n }",
"function populateList(listSize) {\n videoList = new LinkedVideoList(listSize);\n try {\n\n for (let i in videoData) {\n videoList.add(videoData[i].videoUrl, videoData[i].videoType, videoData[i].description);\n }\n\n } catch (error) {\n console.log(error);\n alert(\"Connection error encountered when trying to get the videos, please stand by...\");\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract matrix of pixels from an image containing grid of glyphs row: source row in glyph grid col: source column in glyph grid maxTrim: [top right bottom left] upper limits in pixels of whitespace to trim from border around glyph in grid cell Trim limits allow creation of patterns with whitespace borders, useful for purposes like making the radio strength sprites have the same size pattern. | function convertGlyphBoxToMatrix(row, col, maxTrim) {
const border = 2;
const columns = 16;
const rows = columns;
if (row < 0 || row >= rows || col < 0 || col >= columns) {
// Ignore clicks on grid border, etc.
return;
}
let w = canvas.width;
let h = canvas.height;
var idat = ctx.getImageData(0, 0, w, h);
// Get pixels for grid cell, converting from RGBA to 1-bit
let grid = Math.floor((w - border) / columns);
let pxMatrix = [];
for (let y=(row*grid)+border; y<(row+1)*grid; y++) {
let row = [];
for (let x=(col*grid)+border; x<(col+1)*grid; x++) {
let offset = ((w * y) + x) * 4;
let r = idat.data[offset];
row.push(r>0 ? 0 : 1);
}
pxMatrix.push(row);
}
// Use default trim limits if none were given and expand partial
// top/right/bottom/left trim bounds in the manner of css margins
if (maxTrim === null || maxTrim === undefined || maxTrim.length < 1) {
maxTrim = [h, w, h, w];
} else if (maxTrim.length === 1) {
let [t] = maxTrim;
maxTrim = [t, t, t, t];
} else if (maxTrim.length === 2) {
let [t, r] = maxTrim;
maxTrim = [t, r, t, r];
} else if (maxTrim.length === 3) {
let [t, r, b] = maxTrim;
maxTrim = [t, r, b, r];
}
// Trim left whitespace
pxMatrix = matrixTranspose(pxMatrix);
let limit = maxTrim[3];
trimLeadingEmptyRows(pxMatrix, limit);
// Trim right whitespace
pxMatrix.reverse();
limit = maxTrim[1];
trimLeadingEmptyRows(pxMatrix, limit);
pxMatrix.reverse();
pxMatrix = matrixTranspose(pxMatrix);
// Trim top whitespace and calculate y-offset
let preTrimH = pxMatrix.length;
limit = maxTrim[0];
trimLeadingEmptyRows(pxMatrix, limit);
let yOffset = preTrimH - pxMatrix.length;
// Trim bottom whitespace
pxMatrix.reverse();
limit = maxTrim[2];
trimLeadingEmptyRows(pxMatrix, limit);
pxMatrix.reverse();
// Return matrix and yOffset
return [pxMatrix, yOffset];
} | [
"function AnalyzeCells(img1, anadir, depth, resultname, intensities, areas, cell_xs, cell_ys) { \n\tif (img1.getNSlices() >= frame)\n\t\timg1.setSlice(frame);\n\n\tvar img3 = img1.duplicate(); \t\t\n\tif (img3.getNSlices() >= frame)\n \t\timg3.setSlice(frame);\n\n\tvar h = img1.getHeight(); \n\tvar w = img1.getWidth(); \n\t// set image scale cm->um \n var cal = img1.getCalibration(); \n\tcm2um(cal); \n\tvar stats = img1.getStatistics(MEASUREMENTS); \n\tvar fullarea = stats.area; \n\tvar bgval = stats.dmode;\n\t \n\t//Open mask file \n var maskfile = anadir + \"Capture-mask-\"+anaversion+\".\" + maskformat; \n var mask = openIf(maskfile, maskformat); \n\tsetMask(mask, depth, false); \n\t \n // get ROI of cell body \n var rs = new RoiSet(); \n\tvar rsname = anadir+\"analysis-RoiSet\"+anaversion+\".zip\"; \n\tvar rsfile = new File(rsname); \n\t// if rsfile does not exist, can still use the rsmanager window \n\tif (rsfile.exists()) \n\t\trs.runCommand(\"Open\", rsname); \n \n if (rs.getName(1) != \"Cells\") { \n IJ.showMessage(\"Error\", \"ROI Manager not populated\"); \n exit; \n } \n // get xy coordinates to identify cells with wand tool \n var rois = rs.getRoisAsArray(); // returns Java array of ij.gui.Roi[]\n\tvar xs = rois[1].getPolygon().xpoints; // returns Java array of int[]\n var ys = rois[1].getPolygon().ypoints; // returns Java array of int[]\n \n // invert image \n invertImage(img1); \n var ic = new Packages.ij.plugin.ImageCalculator(); \n var img2 = ic.run(\"Max create stack\", img1, mask); \n\tif (img2.getNSlices() >= frame)\n\t\timg2.setSlice(frame);\n \n // invert image \n invertImage(img2); \n \n\t// return to original image for quantitation \n\tvar rs = new RoiSet(); \n \n // set image scale cm->um \n var maskcal = mask.getCalibration(); \n\tcm2um(maskcal); \n\tvar maskstats = mask.getStatistics(MEASUREMENTS); \n\t\n\t// this is where the cell outlines are stored as ROIs\n for (var i = 0; i < xs.length; i++) { \n IJ.doWand(mask, xs[i], ys[i], 0, \"4-connected\"); \n\t\tStoreRoi(mask, mask.getRoi(), resultname+\" \"+IJ.d2s(i,0), rs); \n } \n\n \t// save mask \n saveImage(img2, format, anadir, \"Capture-mask-\"+resultname+anaversion, 0); \n \n // save rois \n rs.runCommand(\"Select All\"); \n rs.runCommand(\"Save\", anadir + \"cell-\"+resultname+\"-RoiSet\"+anaversion+\".zip\"); \n var rois = rs.getRoisAsArray(); \n\n // set image scale cm->um \n var cal = img3.getCalibration(); \n\tcm2um(cal); \n\t// Measure mean intensity in original unmodified image \n\tfor (var i = 0; i < rois.length; i++) { \n\t\timg3.setRoi(rois[i]); \n rs.select(img3, i); \n var cellstats = img3.getStatistics(MEASUREMENTS); \n // copy cell intensity and xy position to global data arrays\n intensities[i] = cellstats.mean - bgval; // mean background-corrected cell intensity\n if (xs[i] > 0 && ys[i] > 0) {\n \tcell_xs[i] = xs[i];\n \tcell_ys[i] = ys[i];\n }\n \n // Measure cell area and copy to global data array\n areas[i] = 0; \n if (cellstats.area < fullarea) // Incorrectly drawn ROIs will cover the full frame \n\t areas[i] = cellstats.area; \n IJ.log(IJ.d2s(intensities[i], 0)); \n } \n \n\tif (!DEBUG) { \n\t\timg1.close(); \n\t\timg2.close(); \n\t\timg3.close(); \n\t\tmask.close(); \n\t} \n}",
"trimEdges(stage) {\n if (!stage.srcCtx) {\n return;\n }\n\n const srcData = stage.srcCtx.getImageData(0, 0, stage.srcSize.w, stage.srcSize.h);\n\n // Always trim by top-left pixel color\n const trimPixel = getPixel_(stage, srcData, 0, 0);\n\n let insetRect = {l:0, t:0, r:0, b:0};\n let x, y;\n\n // Trim top\n trimTop:\n for (y = 0; y < stage.srcSize.h; y++) {\n for (x = 0; x < stage.srcSize.w; x++) {\n if (getPixel_(stage, srcData, x, y) != trimPixel) {\n break trimTop;\n }\n }\n }\n insetRect.t = y;\n // Trim left\n trimLeft:\n for (x = 0; x < stage.srcSize.w; x++) {\n for (y = 0; y < stage.srcSize.h; y++) {\n if (getPixel_(stage, srcData, x, y) != trimPixel) {\n break trimLeft;\n }\n }\n }\n insetRect.l = x;\n // Trim bottom\n trimBottom:\n for (y = stage.srcSize.h - 1; y >= 0; y--) {\n for (x = 0; x < stage.srcSize.w; x++) {\n if (getPixel_(stage, srcData, x, y) != trimPixel) {\n break trimBottom;\n }\n }\n }\n insetRect.b = stage.srcSize.h - y - 1;\n // Trim right\n trimRight:\n for (x = stage.srcSize.w - 1; x >= 0; x--) {\n for (y = 0; y < stage.srcSize.h; y++) {\n if (getPixel_(stage, srcData, x, y) != trimPixel) {\n break trimRight;\n }\n }\n }\n insetRect.r = stage.srcSize.w - x - 1;\n\n if (insetRect.l <= 0 && insetRect.t <= 0 && insetRect.r <= 0 && insetRect.b <= 0) {\n // No-op\n return;\n }\n\n // Build a new stage with inset values\n const size = {\n w: stage.srcSize.w - insetRect.l - insetRect.r,\n h: stage.srcSize.h - insetRect.t - insetRect.b\n };\n\n const rects = {\n contentRect: constrain_(size, {\n x: stage.contentRect.x - insetRect.l,\n y: stage.contentRect.y - insetRect.t,\n w: stage.contentRect.w,\n h: stage.contentRect.h\n }),\n stretchRect: constrain_(size, {\n x: stage.stretchRect.x - insetRect.l,\n y: stage.stretchRect.y - insetRect.t,\n w: stage.stretchRect.w,\n h: stage.stretchRect.h\n }),\n opticalBoundsRect: constrain_(size, {\n x: stage.opticalBoundsRect.x - insetRect.l,\n y: stage.opticalBoundsRect.y - insetRect.t,\n w: stage.opticalBoundsRect.w,\n h: stage.opticalBoundsRect.h\n })\n };\n\n stage.name = `${stage.name}-EDGES_TRIMMED`;\n let newCtx = studio.Drawing.context(size);\n newCtx.drawImage(stage.srcCtx.canvas,\n insetRect.l, insetRect.t, size.w, size.h,\n 0, 0, size.w, size.h);\n stage.loadSourceImage(newCtx, rects);\n }",
"* pixelMapper() {\n const width = this.mapWidth[1] - this.mapWidth[0];\n const height = this.mapHeight[1] - this.mapHeight[0];\n const dX = width / (this.canvasWidth - 1);\n const dY = height / (this.canvasHeight - 1);\n for (let y=0, curY=this.mapHeight[0]; y < this.canvasHeight; y++, curY+=dY) {\n for (let x=0, curX=this.mapWidth[0]; x < this.canvasWidth; x++, curX+=dX) {\n yield { x: x, y: y, mapX: curX, mapY: curY };\n }\n }\n }",
"function findDistances (img) {\n img.get = imgGet\n img.set = imgSet\n var view = new DataView(img.data.buffer)\n var nx = img.width\n var ny = img.height\n\n function distance (g, x, y, i) {\n return ((y - i) * (y - i) + g[i][x] * g[i][x])\n }\n\n function intersection (g, x, y0, y1) {\n return ((g[y0][x] * g[y0][x] - g[y1][x] * g[y1][x] + y0 * y0 - y1 * y1) / (2.0 * (y0 - y1)))\n }\n //\n // allocate arrays\n //\n var g = []\n for (var y = 0; y < ny; ++y) { g[y] = new Uint32Array(nx) }\n var h = []\n for (var y = 0; y < ny; ++y) { h[y] = new Uint32Array(nx) }\n var distances = []\n for (var y = 0; y < ny; ++y) { distances[y] = new Uint32Array(nx) }\n var starts = new Uint32Array(ny)\n var minimums = new Uint32Array(ny)\n //\n // column scan\n //\n for (var y = 0; y < ny; ++y) {\n //\n // right pass\n //\n var closest = -nx\n for (var x = 0; x < nx; ++x) {\n if (img.get(y, x, STATE) & INTERIOR) {\n g[y][x] = 0\n closest = x\n } else { g[y][x] = (x - closest) }\n }\n //\n // left pass\n //\n closest = 2 * nx\n for (var x = (nx - 1); x >= 0; --x) {\n if (img.get(y, x, STATE) & INTERIOR) { closest = x } else {\n var d = (closest - x)\n if (d < g[y][x]) { g[y][x] = d }\n }\n }\n }\n //\n // row scan\n //\n for (var x = 0; x < nx; ++x) {\n var segment = 0\n starts[0] = 0\n minimums[0] = 0\n //\n // down\n //\n for (var y = 1; y < ny; ++y) {\n while ((segment >= 0) &&\n (distance(g, x, starts[segment], minimums[segment]) > distance(g, x, starts[segment], y))) { segment -= 1 }\n if (segment < 0) {\n segment = 0\n minimums[0] = y\n } else {\n newstart = 1 + intersection(g, x, minimums[segment], y)\n if (newstart < ny) {\n segment += 1\n minimums[segment] = y\n starts[segment] = newstart\n }\n }\n }\n //\n // up\n //\n for (var y = (ny - 1); y >= 0; --y) {\n var d = Math.sqrt(distance(g, x, y, minimums[segment]))\n view.setUint32((img.height - 1 - y) * 4 * img.width + x * 4, d)\n if (y === starts[segment]) { segment -= 1 }\n }\n }\n}",
"function getMaxTrim(row, col, gridSize) {\n // Radio strength bars get trimmed to match bounds of three bars\n if (col === 0 && [5, 6, 7, 8, 9].includes(row)) {\n return [7, 5, 6, 4];\n }\n // Space gets 4px width and 2px height\n if (col === 2 && row === 0) {\n return [Math.floor((gridSize-3)/2), Math.floor((gridSize-5)/2)];\n }\n // Everything else gets default trim\n return null;\n}",
"function cells_of_regions(w, h, regions){\n // Create an array of cells initialized with [-1].\n var cells = new Array(w);\n for(var x = 0; x < w; x++){\n cells[x] = new Array(h);\n for(var y = 0; y < h; y++){\n cells[x][y] = -1;\n }\n }\n\n function is_empty(x, y){\n return cells[x][y] == -1;\n }\n\n // For each region, write its index in [regions] in the cells of its border.\n for(var i = 0; i < regions.length; i++){\n var x = regions[i].x;\n var y = regions[i].y;\n var horiz = true;\n\n for(j = 0; j < regions[i].path.length; j++){\n var n = regions[i].path[j];\n var pos = n >= 0;\n if(n < 0) n = -n;\n\n for(k = 0; k < n; k++){\n if(horiz){\n if(pos){\n x++;\n cells[x-1][y] = i;\n } else {\n x--;\n cells[x][y-1] = i;\n }\n } else {\n if(pos){\n y++;\n cells[x-1][y] = i;\n } else {\n y--;\n cells[x][y] = i;\n }\n }\n }\n\n horiz = !horiz;\n }\n }\n\n // For each unassigned cell, assign the first region in all directions.\n // We test all directions to support grids that are not covered by regions.\n for(var x = 0; x < w; x++){\n for(var y = 0; y < h; y++){\n if(is_empty(x, y)){\n var x_l = x; // left\n var x_r = x; // right\n var y_t = y; // top\n var y_b = y; // bottom\n\n while(x_l > 0 && is_empty(x_l, y)) x_l--;\n while(x_r < w && is_empty(x_r, y)) x_r++;\n while(y_t > 0 && is_empty(x, y_t)) y_t--;\n while(y_b < h && is_empty(x, y_b)) y_b++;\n\n var v_w = cells[x_l][y];\n var v_e = cells[x_r][y];\n var v_n = cells[x][y_t];\n var v_s = cells[x][y_b];\n\n var v = Math.max(v_w, v_e, v_n, v_s);\n\n if(v_w == -1 || v_w == v){\n if(v_e == -1 || v_e == v){\n if(v_n == -1 || v_n == v){\n if(v_s == -1 || v_s == v){\n cells[x][y] = v;\n }\n }\n }\n }\n }\n }\n }\n\n // We gather the cells for each region.\n var res = new Array(regions.length);\n for(var i = 0; i < regions.length; i++) res[i] = new Array();\n\n for(var x = 0; x < w; x++){\n for(var y = 0; y < h; y++){\n if(!is_empty(x, y)){\n res[cells[x][y]].push({x: x, y: y});\n }\n }\n }\n\n return res;\n}",
"function cutImageUp(image) \n{ \n\tfind_dimensions();\n\t\n for(var x = 0; x < numRowsToCut; x++) {\n for(var y = 0; y < numColsToCut; y++) {\n var canvas = document.createElement('canvas');\n canvas.width = widthOfOnePiece;\n canvas.height = heightOfOnePiece;\n var context = canvas.getContext('2d');\n\t\t\t\n context.drawImage(image, y * widthOfOnePiece,x * heightOfOnePiece, widthOfOnePiece, heightOfOnePiece, 0, 0, canvas.width, canvas.height);\n\t\t\t\n\t\t\n imagePieces.push(canvas.toDataURL());\n\t\t \n }\n }\n \n drawCells();\n\tdrawTable();\n\t\n}",
"assignImgsToCols() {\n let numOfCols = this.calculateCols();\n \n // Init cols\n let cols = [];\n let i;\n for (i = 0; i < numOfCols; i += 1) {\n cols.push({key: i, imgs: []});\n }\n\n let {imgs} = this.props;\n \n // Init colHeights\n let colHeights = [];\n for (i = 0; i < cols.length; i+=1) {\n colHeights[i] = 0;\n };\n\n // Add image to shortest column\n if (cols.length > 0) {\n imgs.forEach((img) => {\n let col = this.findShortestColumn(colHeights);\n cols[col].imgs.push(img);\n let {dimensions} = img.props.img.value;\n colHeights[col] += dimensions.small.maxHeight;\n });\n }\n \n return cols;\n }",
"function trimData(data){\r\n\tconst width = Math.floor(Math.sqrt(data.length));\r\n\tconst max_trim = Math.floor((width - 1) / 2);\r\n\r\n\tlet trim1 = 0\r\n\tfor (; trim1 < max_trim; trim1++){\r\n\t\tconst rowTop = trim1, colLeft = trim1;\r\n\t\tlet breakFlag = false;\r\n\t\tfor (i = 0; i < width; i++){\r\n\t\t\tif (myBoard.board.getCell(rowTop, i) || myBoard.board.getCell(i, colLeft)){\r\n\t\t\t\tbreakFlag = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (breakFlag){\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tlet trim2 = 0\r\n\tfor (; trim2 < width - trim1; trim2++){\r\n\t\tconst rowDown = width - 1 - trim2, colRight = width - 1 - trim2;\r\n\t\tlet breakFlag = false;\r\n\t\tfor (i = 0; i < width; i++){\r\n\t\t\tif (myBoard.board.getCell(rowDown, i) || myBoard.board.getCell(i, colRight)){\r\n\t\t\t\tbreakFlag = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (breakFlag){\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tconst newdata = [];\r\n\tfor(let row = trim1; row < width - trim2; row++){\r\n\t\tfor(let col = trim1; col < width - trim2; col++){\r\n\t\t\tnewdata.push(myBoard.board.getCell(row, col));\r\n\t\t}\r\n\t}\r\n\treturn newdata;\r\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 find_dimensions()\n{\n numColsToCut= parseInt(NumberofColumns);\n numRowsToCut= parseInt(NumberofRows);\n \n widthOfOnePiece=Target_width/numColsToCut;\n heightOfOnePiece=Target_height/numRowsToCut; \n}",
"getSurroundingTiles(x, y, data) {\n\n const tile = []; \n \n //up\n if (x > 0) {\n tile.push(data[x - 1][y]);\n } \n //down\n if (x < boardSize - 1) {\n tile.push(data[x + 1][y]);\n } \n //left\n if (y > 0) {\n tile.push(data[x][y - 1]);\n } \n //right\n if (y < boardSize - 1) {\n tile.push(data[x][y + 1]);\n } \n // top left\n if (x > 0 && y > 0) {\n tile.push(data[x - 1][y - 1]);\n } \n // top right\n if (x > 0 && y < boardSize - 1) {\n tile.push(data[x - 1][y + 1]);\n } \n // bottom right\n if (x < boardSize - 1 && y < boardSize - 1) {\n tile.push(data[x + 1][y + 1]);\n } \n // bottom left\n if (x < boardSize - 1 && y > 0) {\n tile.push(data[x + 1][y - 1]);\n } \n \n return tile;\n }",
"crop(data, xspan, yspan) {\n var halfx = xspan / 2,\n halfy = yspan / 2;\n\n return _.filter(data, function(entry) {\n return -halfx < entry.mercator[0] && halfx > entry.mercator[0]\n && -halfy < entry.mercator[1] && halfy > entry.mercator[1];\n });\n }",
"function fitImage(cw, ch, ir){\n var xpos = 0;\n var ypos = 0;\n var sizex = cw;\n var sizey = ch;\n var canvasRatio = cw/ch;\n var centerx = cw/2;\n var centery = ch/2;\n \n if (canvasRatio !== ir) {\n\n if (canvasRatio >= 1) {\n var smallest = Math.min(cw, ch);\n sizex = smallest * ir;\n sizey = smallest;\n } else if (canvasRatio > ir && canvasRatio < 1) {\n sizex = ch * ir;\n sizey = ch;\n } else {\n sizey = cw/ir;\n sizex = cw;\n }\n\n }\n xpos = centerx - sizex/2;\n ypos = centery - sizey/2;\n return [xpos, ypos, sizex, sizey];\n}",
"function cutImageUp() {\n for (var y = 0; y < numRowsToCut; ++y) {\n for (var x = 0; x < numColsToCut; ++x) {\n var canvas = document.createElement('canvas');\n canvas.width = widthOfOnePiece;\n canvas.height = heightOfOnePiece;\n var context = canvas.getContext('2d');\n context.drawImage(image, x * widthOfOnePiece, y * heightOfOnePiece, widthOfOnePiece, heightOfOnePiece, 0, 0, canvas.width, canvas.height);\n imagePieces.push(canvas.toDataURL());\n }\n }// imagePieces now contains data urls of all the pieces of the image\n}",
"function pixelOffset(){\n if(xoffset*cellSize < pixeloffx){\n pixeloffx = 0\n }\n if(yoffset*cellSize < pixeloffy){\n pixeloffy = 0\n }\n while(pixeloffx > 0){\n pixeloffx -= cellSize\n xoffset--\n }\n while(pixeloffy > 0){\n pixeloffy -= cellSize\n yoffset--\n }\n\n while(pixeloffx < -cellSize){\n pixeloffx += cellSize\n xoffset++\n }\n while(pixeloffy < -cellSize){\n pixeloffy += cellSize\n yoffset++\n }\n\n $(\"#coordinates\").text(`${xoffset},${yoffset}`)\n}",
"calculatePixelSize () {\n let diagonal = new gdal.LineString();\n diagonal.points.add(this.westernExtreme, this.northernExtreme);\n diagonal.points.add(this.easternExtreme, this.southernExtreme);\n if (!this.isImageryMetric()) {\n diagonal = this.convertLineToMetricProjection(diagonal);\n }\n const pixelsAlongDiagonal = Math.sqrt(\n (this.horizontalPixelCount * this.horizontalPixelCount) +\n (this.verticalPixelCount * this.verticalPixelCount)\n );\n const pixelSize = diagonal.getLength() / pixelsAlongDiagonal;\n return pixelSize;\n }",
"function convertImageToLineDrawing(img) {\n const kernel = cv.getStructuringElement(cv.MORPH_RECT,new cv.Size(5,5));\n\n const imgGray = new cv.Mat();\n cv.cvtColor(img, imgGray, cv.COLOR_RGBA2GRAY);\n\n const imgDilated = new cv.Mat();\n cv.dilate(imgGray, imgDilated, kernel, new cv.Point(-1, 1), 1);\n\n const imgDiff = new cv.Mat();\n cv.absdiff(imgDilated, imgGray, imgDiff);\n\n const contour = new cv.Mat();\n cv.bitwise_not(imgDiff, contour);\n return contour;\n}",
"function createGrid() {\n for (let i = 0; i < width * height; i++) {\n const cell = document.createElement('div')\n grid.appendChild(cell)\n cells.push(cell)\n }\n for (let i = 2; i < 22; i++) {\n rowArray.push(cells.slice(i * 10, ((i * 10) + 10)))\n }\n for (let i = 0; i < 20; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('top')\n }\n for (let i = 10; i < 20; i++) {\n cells[i].classList.remove('top')\n cells[i].classList.add('topline')\n }\n for (let i = 220; i < 230; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('bottom')\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/// Clears out the login form based on resetCode set by programmer | function resetForm(resetCode) {
var logindata = document.getElementById("userlogin");
switch (resetCode){
case 0:
// Reset all fields (usernmae, passwords, and major)
logindata.elements[0].value = '';
logindata.elements[3].value = 'default';
case 1:
// Reset "password" and "confirm password" fields
logindata.elements[1].value = '';
case 2:
// Reset just "confirm password" field
logindata.elements[2].value = '';
return;
default:
// log invalid resetCode input and return
console.log('#resetForm: Invalid resetCode ' + resetCode);
return;
}
} | [
"function resetForm() {\n $formLogin.validate().resetForm();\n $formLost.validate().resetForm();\n $formRegister.validate().resetForm();\n }",
"_clearLoginFields() {\n // clear input fields\n // @ts-ignore\n document.getElementById('email').value = '';\n // @ts-ignore\n document.getElementById('password').value = '';\n }",
"function clearSigninForm(){\r\n $('#signinform').trigger('reset');\r\n $('#signinMsg').html(\" \");\r\n}",
"function passwordReset() {\n app.getForm('requestpassword').clear();\n app.getView({\n ContinueURL: URLUtils.https('Account-PasswordResetForm')\n }).render('account/password/requestpasswordreset');\n}",
"function hideForceResetPwdMsg() {\n $(\"#forcedPwd\").hide();\n $(\"#new_pwd\").val(\"\");\n $(\"#new_pwd\").removeClass(\"error_red_border\");\n $(\"#re_new_pwd\").val(\"\");\n $(\"#re_new_pwd\").removeClass(\"error_red_border\");\n\n $(\"#wrong_resetpwd\").text(\"\");\n $(\"#wrong_resetpwd\").hide();\n $('#LogingetPwd').hide();\n $('#securityQuestionArea').hide();\n $(\"#login_name\").removeClass('error_red_border');\n}",
"function userResetForm(){\n $('.field-user-id').val('');\n $('.field-user-name').val('');\n $('.field-user-username').val('');\n $('.field-user-password').val('');\n $('.field-user-email').val('');\n}",
"function onClickReset() {\r\n cleanInputs();\r\n resetFieldsUi();\r\n}",
"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 clearSignupForm(){\r\n $('#signupform').trigger('reset');\r\n $('#nameMsg').html(\" \"); \r\n $('#emailMsg').html(\" \");\r\n $('#addressMsg').html(\" \");\r\n $('#passwordMsg').html(\" \");\r\n}",
"function handleUserResetPwdOnSuccess(user_reset_pwd_obj) {\n\tresetPswd = true;\n $(\"#LogingetPwd\").hide();\n $(\"#securityQuestionArea\").hide();\n $(\"#forcedPwd\").hide();\n $(\"#login_txt\").val(user_auth_obj.userName);/* Getting user name from USER_AUTH response object and setting it to user name field*/\n $(\"#password_txt\").val($('#re_new_pwd').val());\n showGeneralSuccessMsg(messages['login.resetPwdMsg']);\n}",
"function presentDefaultLoginForm(){\n\t$(\"#loginField\").empty();\n\t$(\"#loginField\").html(\"<a id=\\\"loginButton\\\" href=\\\"/login\\\"><strong>Login</strong></a>\");\n\t$(\"#loginStatus\").html(\"Login:\");\n\t$(\"#loginMessage\").html(\"Fill in the formula and click on the button to log in.\");\n\t$(\"#myform\").removeAttr(\"style\");\n}",
"function passwordResetDialog() {\n // @FIXME reimplement using dialogify\n app.getForm('requestpassword').clear();\n app.getView({\n ContinueURL: URLUtils.https('Account-PasswordResetDialogForm')\n }).render('account/password/requestpasswordresetdialog');\n}",
"function setNewPasswordForm() {\n\n app.getForm('profile').handleAction({\n cancel: function () {\n app.getView({\n ContinueURL: URLUtils.https('Account-SetNewPasswordForm')\n }).render('account/password/setnewpassword');\n return;\n },\n send: function () {\n var Customer;\n var Email;\n var passwordChangedMail;\n var resettingCustomer;\n var success;\n\n Customer = app.getModel('Customer');\n Email = app.getModel('Email');\n resettingCustomer = Customer.getByPasswordResetToken(request.httpParameterMap.Token.getStringValue());\n\n if (!resettingCustomer) {\n response.redirect(URLUtils.https('Account-PasswordReset'));\n }\n\n if (app.getForm('resetpassword.password').value() !== app.getForm('resetpassword.passwordconfirm').value()) {\n app.getForm('resetpassword.passwordconfirm').invalidate();\n app.getView({\n ContinueURL: URLUtils.https('Account-SetNewPasswordForm')\n }).render('account/password/setnewpassword');\n } else {\n\n success = resettingCustomer.resetPasswordByToken(request.httpParameterMap.Token.getStringValue(), app.getForm('resetpassword.password').value());\n if (!success) {\n app.getView({\n ErrorCode: 'formnotvalid',\n ContinueURL: URLUtils.https('Account-SetNewPasswordForm')\n }).render('account/password/setnewpassword');\n } else {\n passwordChangedMail = Email.get('mail/passwordchangedemail', resettingCustomer.object.profile.email);\n passwordChangedMail.setFrom('noreply@rapalausa.com');\n passwordChangedMail.setSubject(Resource.msg('email.resetpassword', 'email', null));\n passwordChangedMail.send({\n Customer: resettingCustomer.object\n });\n\n app.getView().render('account/password/setnewpassword_confirm');\n }\n }\n }\n });\n}",
"function resetForm() {\n setInputs(initial);\n }",
"function testcaseResetForm(){\n $('.field-testcase-id').val('');\n $('.field-testcase-name').val('');\n $('.field-testcase-action').val('');\n $('.field-testcase-expectedResult').val('');\n $('.field-testcase-actualResult').val('');\n $('.field-testcase-status').val('');\n $('.field-testcase-comment').val('');\n}",
"function resetForm() {\n $leaveComment\n .attr('rows', '1')\n .val('');\n $cancelComment\n .closest('.create-comment')\n .removeClass('focused');\n }",
"function resetForm() {\n\tvar reset = confirm(\"WARNING: Clicking 'OK' will reset all information in the form. Are you sure you wish to continue?\")\n\t\n\tif(reset) {\n\t\twindow.location='ResetForm';\n\t} else {\n\t\t\n\t}\n}",
"function resetStepForm() {\n editingStep = -1;\n stepType = 'script';\n clearStepForm();\n $('#script-form').addClass('hidden');\n }",
"function cleanup(){\n\t\t// reset button text\n\t\tdocument.getElementById('button1').value = \"Add User\";\n\t\t// clear fields\n\t\tdocument.getElementById('uname').value = \"\";\n\t\tdocument.getElementById('password').value = \"\";\n\t\tdocument.getElementById('fname').value = \"\";\n\t\tdocument.getElementById('lname').value = \"\";\n\t\tdocument.getElementById('email').value = \"\";\n\t\tdocument.getElementById('active').checked = false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a string of an rgb color takes a hex color as a string in argument | function rgbString(hex) {
col = hexToRgb(hex);
return "rgb("+col.r+","+col.g+","+col.b+")"
} | [
"function toRGBString (color) {\n\t\treturn color.r.toFixed(0) + ', ' + color.g.toFixed(0) + ', ' + color.b.toFixed(0);\n\t}",
"function rgb2hexa(str) {\n colors=/^rgb\\((\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})\\)$/.exec(str);\n hexa = \"#\";\n for (i=1; i<colors.length; i++) {\n color = colors[i];\n if (color>255) color=255;\n hexacolor = parseInt(color, 10).toString(16).toLowerCase();\n hexacolor = (hexacolor.length == 1) ? '0' + hexacolor : hexacolor ;\n hexa = hexa + hexacolor;\n } \n return hexa;\n}",
"hex2rgb(hex) {\n var h=hex.replace('#', '');\n h = h.match(new RegExp('(.{'+h.length/3+'})', 'g'));\n\n for(var i=0; i<h.length; i++)\n h[i] = parseInt(h[i].length==1? h[i]+h[i]:h[i], 16);\n\n return 'rgb('+h.join(',')+')';\n }",
"function getHex6(cssColor) {\n\t\tlet output;\n\t\t\n\t\t// try if cssColor is a named color\n\t\ttry {\n\t\t\toutput = parseNamedColor(cssColor);\n\t\t\treturn output;\n\t\t} catch (e) {\n\t\t\t// no need to log error, color might still be parsable\n\t\t}\n\t\t\n\t\t// try if cssColor is a hex value\n\t\ttry {\n\t\t\toutput = parseCSSHex(cssColor);\n\t\t\t// get rid of alpha channel if it exists\n\t\t\tif (output.length === 4) output.pop();\n\t\t\t\n\t\t\t// pads with 0 if number is less than 0x10\n\t\t\toutput = output.map((item) => {\n\t\t\t\treturn (item.length === 1 ? '0' : '') + item;\n\t\t\t});\n\t\t\t\n\t\t\t// merges numbers into hex format #nnnnnn\n\t\t\treturn `#${output.join('')}`;\n\t\t\t\n\t\t} catch (e) {\n\t\t\t// no need to log error, color might still be parsable\n\t\t}\n\t\t\n\t\t// try if cssColor is a function\n\t\ttry {\n\t\t\toutput = parseCSSFunc(cssColor);\n\t\t\tlet funcName = output.splice(0, 1)[0];\n\t\t\t\n\t\t\t// maps current color space onto rgb and converts the normalized coefficients onto a hexadecimal string\n\t\t\toutput = (mapToColorSpace(funcName, 'rgb')(output)).map((num) => {\n\t\t\t\treturn Math.trunc(num * 255).toString(16);\n\t\t\t});\n\t\t\t\n\t\t\t// pads with 0 if number is less than 0x10\n\t\t\toutput = output.map((item) => {\n\t\t\t\treturn (item.length === 1 ? '0' : '') + item;\n\t\t\t});\n\t\t\t\n\t\t\toutput = `#${output.join('')}`;\n\t\t} catch (e) {\n\t\t\tconsole.error(`${e.name}:${e.message}`);\n\t\t\toutput = '#7F7F7F';\n\t\t} finally {\n\t\t\treturn output;\n\t\t}\n\t\t\n\t}",
"function rgbColor()\n{\n\tvar string = \"rgb(\";\n\tstring = string + getRandomInt(255) + \", \";\n\tstring = string + getRandomInt(255) + \", \";\n\tstring = string + getRandomInt(255) + \")\";\n\treturn string;\n}",
"function rgb_to_color(rgb) {\r\n\t\tswitch(rgb) {\r\n\t\t\tcase \"#cb3594\":\r\n\t\t\t\treturn \"Purple\";\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"#659b41\":\r\n\t\t\t\treturn \"Green\";\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"#ffcf33\":\r\n\t\t\t\treturn \"Yellow\";\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"#986928\":\r\n\t\t\t\treturn \"Brown\";\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\r\n\t}",
"function hexToRGB(h, cell) {\n let r = 0,\n g = 0,\n b = 0;\n let rgb = '';\n h = colorPicker.value;\n // 3 digits\n if (h.length == 4) {\n r = \"0x\" + h[1] + h[1];\n g = \"0x\" + h[2] + h[2];\n b = \"0x\" + h[3] + h[3];\n // 6 digits\n } else if (h.length == 7) {\n r = \"0x\" + h[1] + h[2];\n g = \"0x\" + h[3] + h[4];\n b = \"0x\" + h[5] + h[6];\n }\n rgb = \"rgb(\" + +r + \", \" + +g + \", \" + +b + \")\";\n colorCheck(rgb, cell)\n}",
"function getHexColor() {\n if (Math.round(Math.random())) {\n return \"ff\";\n } else {\n return \"00\";\n }\n}",
"function fromHex(hex) {\n // remove any leading formatting characters\n hex = hex.replace(\"#\", \"\").replace(\"0x\", \"\");\n const colorValue = Number.parseInt(hex, 16);\n let r;\n let g;\n let b;\n switch (hex.length) {\n // 8-bit color\n case 2:\n r = (colorValue & 224) / 224;\n g = (colorValue & 28) / 28;\n b = (colorValue & 3) / 3;\n break;\n // 12-bit color\n case 3:\n r = (colorValue & 0xF00) / 0xF00;\n g = (colorValue & 0x0F0) / 0x0F0;\n b = (colorValue & 0x00F) / 0x00F;\n break;\n // 16-bit color\n case 4:\n r = (colorValue & 0xF800) / 0xF800;\n g = (colorValue & 0x07E0) / 0x07E0;\n b = (colorValue & 0x001F) / 0x001F;\n break;\n // 24-bit color\n case 6:\n r = (colorValue & 16711680) / 16711680;\n g = (colorValue & 65280) / 65280;\n b = (colorValue & 255) / 255;\n break;\n // 36-bit color\n case 9:\n r = (colorValue & 68702699520) / 68702699520;\n g = (colorValue & 16773120) / 16773120;\n b = (colorValue & 4095) / 4095;\n break;\n // 48-bit color\n case 12:\n r = (colorValue & 281470681743360) / 281470681743360;\n g = (colorValue & 4294901760) / 4294901760;\n b = (colorValue & 65535) / 65535;\n break;\n default:\n throw new Error(\"Invalid color format\");\n }\n return new Color(r, g, b);\n}",
"function rgbToHtml(r, g, b) {\n var decColor = r + 256 * g + 65536 * b,\n str = decColor.toString(16);\n\n while (str.length < 6) {\n str = '0' + str;\n }\n return \"#\" + str;\n}",
"function hslToHex(h ,s ,l){\n let rgb = Vibrant.Util.hslToRgb(h, s, l);\n let hex = Vibrant.Util.rgbToHex(rgb[0], rgb[1], rgb[2]);\n // console.log(hex)\n return hex;\n}",
"function setColorText(hexcolor) {\n color.textContent = hexcolor;\n}",
"function interpolateHexColor( color1, color2, percent )\n{\n red1 = parseInt( color1.substr(1,2), 16 );\n green1 = parseInt( color1.substr(3,2), 16 );\n blue1 = parseInt( color1.substr(5,2), 16 );\n \n red2 = parseInt( color2.substr(1,2), 16 );\n green2 = parseInt( color2.substr(3,2), 16 );\n blue2 = parseInt( color2.substr(5,2), 16 );\n \n red3 = Math.round(( red2 - red1 ) * percent + red1);\n green3 = Math.round(( green2 - green1 ) * percent + green1);\n blue3 = Math.round(( blue2 - blue1 ) * percent + blue1);\n \n return \"#\" + red3.toString(16) + green3.toString(16) + blue3.toString(16); \n}",
"function hslToHex(h, s, l) {\n var color = hslToRgb(h, s, l);\n\n color = color.map(function pad(v) {\n\n v = v.toString(16);\n v.length < 2 ? (v = \"0\" + v) : v; // Add zero before hex number to keep constant length of hex color string\n\n return v;\n });\n\n return color;\n }",
"function getHexColor(val, max) {\r\n\r\n var val2 = max - val; // difference from max \r\n var HiC = 255; // highest color value (lightest color)\r\n var LowC = 75; // lowest color value (darkest color)\r\n \r\n var x = LowC + (val2*(HiC - LowC))/max\r\n\r\n var bin = Math.floor(x).toString(16);\r\n var color = bin + bin + bin;\r\n return color;\r\n}",
"function colourParse(r, g, b) {\n if (typeof r === \"string\") {\n var b = parseInt(HexParse(r), 16);\n return [b >> 16, 255 & b >> 8, 255 & b]\n } else\n return (Math.round(r[2] || b) | Math.round(r[1] || g) << 8 | Math.round(r[0] || r) << 16 | 1 << 24).toString(16).slice(1)\n }",
"function convert_RGB(code) {\r\n var round = Math.round, data = /(\\d+),\\s*(\\d+),\\s*(\\d+)|#(\\w{1,2})(\\w{1,2})(\\w{1,2})/.exec(code), result;\r\n // Nice rgb() code\r\n if (data[1]) {\r\n result = [data[1], data[2], data[3]];\r\n }\r\n else {\r\n // Messy CSS colour code\r\n result = [parseInt(data[4], 16), parseInt(data[5], 16), parseInt(data[6], 16)];\r\n // Stretch out compact #000 codes to their full size\r\n if (code.length === 4) {\r\n result = [result[0] << 4 | result[0], result[1] << 4 | result[1], result[2] << 4 | result[2]];\r\n }\r\n }\r\n // Convert to a 15bit colour\r\n return round(result[2] / 8.226) << 10 | round(result[1] / 8.226) << 5 | round(result[0] / 8.226);\r\n }",
"function getColor(i, j) {\n let pix = img.get(i,j).toString();\n pix = pix.substring(0, pix.length - 4);\n pix = \"rgb(\" + pix + \")\";\n return pix;\n}",
"function sixToRgb(s) {\n return s * 51;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set counter checks text | function setCounterText() {
var qty = $( "#quantity" ).attr( "value" );
var n = $( ".receipments:checked" ).length;
if( n == 0 ) {
$( "#counterCheck" ).text( "No members selected." );
$( "#totalDonate" ).text( "" );
} else if( n == 1 ) {
$( "#counterCheck" ).text( "Selected 1 member." );
if( qty > 0 ) {
if( n*qty == 1 ) {
$( "#totalDonate" ).text( "Total donate: "+ (n*qty) +" item." );
} else $( "#totalDonate" ).text( "Total donate: "+ (n*qty) +" items." );
} else $( "#totalDonate" ).text( "" );
} else {
$( "#counterCheck" ).text( "Selected "+n+" members." );
if( qty > 0 ) {
$( "#totalDonate" ).text( "Total donate: "+ (n*qty) +" items." );
} else $( "#totalDonate" ).text( "" );
}
} | [
"function changeText() {\r\n $alertHolder.html(number);\r\n }",
"function updateUncheckedCountSpan(incr) {\n uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) + incr\n}",
"function setStatusText(text1, text2, text3) {\n svg.select(\".studyStatusText1\").text(text1);\n svg.select(\".studyStatusText2\").text(text2);\n svg.select(\".studyStatusText3\").text(text3);\n}",
"function updateCountDisplays() {\n\tdocument.getElementById(\"watcherCount\").innerHTML = ((watchers == 0) ? \"No\" : watchers) + \" viewer\" + ((watchers != 1) ? \"s\" : \"\");\n}",
"function incrementCounter() {\n attempts++;\n attemptCounter.innerHTML = attempts;\n}",
"function updateExamplePositionText() {\n var data = {\n currentExample: nextExample_ + 1,\n totalExamples: examples_.length,\n };\n var format = gettext('Example %(currentExample)s of %(totalExamples)s');\n var string = interpolate(format, data, true);\n document.getElementById('example-counter').textContent = string;\n}",
"function updateCounter(){\n\t//subtracts one from battery percentage \n\tbatteryPercentage -= 1;\n\t//changes text to match the new battery percentage \n\t\n\t\n}",
"function hfzberna_displayCount(countPhotos, countChecked)\r\n{\r\n\tvar spanInfoText = document.getElementById(\"spanInfoText\");\r\n\tspanInfoText.innerHTML = \r\n\t\t\"Fototaška obsahuje <b style='font-size:140%'>\" + countPhotos + \"</b> fotografií, označených je <b style='font-size:140%'>\" + countChecked + \"</b>\";\r\n}",
"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}",
"function updateCounter() {\n const totalTodosEl = document.querySelector('[data-total-todos]');\n totalTodosEl.innerText = `${todos.length} items left`;\n}",
"function updateCharacterCounter(event) {\n const remainder = 140 - $(this).val().length;\n $(this).siblings('.counter').text(remainder);\n // can also be written like: $('.counter').text(remainder); but using $(this).siblings('.counter') is more efficient\n // conditional statement checks if counter number is\n // less than 140 and if so changes its color to red\n if (remainder < 0) {\n $(this).siblings('.counter').css(\"color\", \"#FF0000\");\n } else {\n // when backspacing, if counter goes back to MORE\n // than 140, change colour of counter back to black\n $(this).siblings('.counter').css(\"color\", \"#000000\");\n }\n}",
"function retextCount() {\n this.Compiler = countWords;\n}",
"function addCountToDocumentTitle(countMessage) {\n\n if (document.title.indexOf(getMessage(kradVariables.MESSAGE_TOTAL_ERROR, null, null) > 0)\n || document.title.indexOf(getMessage(kradVariables.MESSAGE_TOTAL_WARNING, null, null) > 0)\n || document.title.indexOf(getMessage(kradVariables.MESSAGE_TOTAL_MESSAGE, null, null) > 0)) {\n\n var tokenIndex = document.title.lastIndexOf(\" - \");\n if (tokenIndex > -1) {\n document.title = document.title.substr(0, tokenIndex) + \" - \" + countMessage;\n return;\n }\n }\n\n document.title = document.title + \" - \" + countMessage;\n}",
"function setBadge(text){\n\tchrome.browserAction.setBadgeText({ text: text });\n}",
"function resetCounter() {\n var m = x\n x = 0;\n return m + \" and the counter reset now\"\n}",
"function showCount() {\n count.textContent = 'Showing '+ employees.length + ' employees';\n}",
"function FCCUpdateTestResult(){\r\n const button = document.getElementById('fcc_test_button');\r\n button.innerHTML = `Tests ${nbPassed}/${nbPassed+nbFailed}`;\r\n if(nbFailed){\r\n button.classList.add(\"fcc_test_btn-error\");\r\n } else {\r\n button.classList.add(\"fcc_test_btn-success\");\r\n }\r\n}",
"function updateDifficultyText() {\r\n if (difficulty === 0) {\r\n $($difficulty).text('Easy');\r\n updateScorecardColor('Easy');\r\n $diffButton.removeClass('challening');\r\n $diffButton.removeClass('impossible');\r\n $diffButton.addClass('easy');\r\n $titleBar.removeClass('challening');\r\n $titleBar.removeClass('impossible');\r\n $titleBar.addClass('easy');\r\n\r\n } else if (difficulty === 1) {\r\n $($difficulty).text('Challenging');\r\n updateScorecardColor('Challenging');\r\n $diffButton.removeClass('easy');\r\n $diffButton.removeClass('impossible');\r\n $diffButton.addClass('challening');\r\n $titleBar.removeClass('easy');\r\n $titleBar.removeClass('impossible');\r\n $titleBar.addClass('challening');\r\n\r\n } else if (difficulty === 2) {\r\n $($difficulty).text('Impossible');\r\n updateScorecardColor('Impossible');\r\n $diffButton.removeClass('easy');\r\n $diffButton.removeClass('challening');\r\n $diffButton.addClass('impossible');\r\n $titleBar.removeClass('easy');\r\n $titleBar.removeClass('challening');\r\n $titleBar.addClass('impossible');\r\n }\r\n console.log(difficulty);\r\n }",
"function countAnswer(){\n var _count = +document.getElementById('_count_answer').textContent;\n document.getElementById('_count_answer').innerHTML = ++_count;\n}",
"updateHtmlSteps() {\n this.htmlStepDisplay.innerText = `${this.emoji} steps: ${this.stepsTaken.toFixed(0)}`;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
stat goStatPrdUrl + ad trc | function goStatPrdUrlTrc(url, prdNo, code, target, typGugn, areaGubn, trcNo) {
stck( typGugn, areaGubn, trcNo);
goStatPrdUrl(url, prdNo, code, target);
} | [
"function estat(){}",
"function getLatency(ret, count) {\n var tmpUrl=\"\";\n if(count >= 0){\n var tmplatency=ret[0]/2;\n tmpUrl=ret[1].replace(\"images/small.bmp\", \"\");\n $latencyArray[count]=tmplatency;\n console.log(\"Evaluate_Server \"+tmpUrl+ \" Mode \"+$serverMode + \" Latency \"+ tmplatency);\n //console.log(\"Server: \"+tmpUrl+\", latency: \"+tmplatency); \n if(tmplatency<$latency){\n $latency=tmplatency;\n $temporalBestServer=tmpUrl;\n console.log(\"Updated_Best_Server \"+tmpUrl+ \" Mode \"+$serverMode + \" Latency \"+ tmplatency); \n } \n } \n count++;\n if(count < $servers.length){\n ping(\"http://\"+$servers[count]+\"/images/small.bmp\").then(function(retval) {\n getLatency(retval,count);\n }).catch(function(error) {\n console.log(\"Error: \"+ String(error));\n var errorRetval=[];\n errorRetval[1]=\"http://\"+$servers[count]+\"/\";\n errorRetval[0]=9999999;\n getLatency(errorRetval,count);\n });\n }\n if(count >= $servers.length && tmpUrl != \"\"){\n $server=$temporalBestServer;\n if($startup){\n $readyForTesting=true;\n $startup=false;\n }\n var latencyArrayString=\"\";\n for (var i=0; i <$latencyArray.length; i++){\n latencyArrayString+=$latencyArray[i]+\" \";\n }\n sendServerLog(\"Set_New_Server \"+$server+ \" Mode \"+$serverMode + \" Latency \"+ $latency + \" AllLatencies \" + latencyArrayString);\n }\n}",
"function dgetRsc(dt, cb) {\n request(dbaseUrl + dt, function(err, res, body) {\n if (!err && res.statusCode == 200) {\n console.log('\\nVerify new-user access to iControl REST API');\n cb();\n }\n });\n}",
"function retrieveStatus(){\n request(icecastUrl, function (error, response, body) {\n // If error, log it\n var mountpointList = JSON.parse(body).icestats.source;\n // Check for all three mountpoints\n checkStatus(mountpointList, 'listen');\n checkStatus(mountpointList, 'hub');\n checkStatus(mountpointList, 'harrow');\n });\n}",
"function sendStats() {\n if (hostname.indexOf(\"local\") != -1) {\n cleanup();\n return;\n }\n var app = options.app;\n\n // Status Code\n var statusCode = res.statusCode || 'unknown_status';\n\n // Increment\n sendData(\"server-stats.count.\"+app,1,{\n \"node\": hostname,\n \"status-code\":statusCode,\n \"path\":path\n });\n\n\n // Response Time\n var duration = new Date().getTime() - startTime;\n // Duration\n sendData(\"server-stats.response-time.\"+app,duration,{\n \"node\": hostname,\n \"path\":path\n });\n\n cleanup();\n }",
"function getWebsiteTraffic(url)\n{\t\n\t// Request for total traffic (Total Traffic API)\n\tvar startDate=\"2018-10\";\n\tvar endDate=\"2018-10\";\n\tvar mainDomain=false;\n\tvar granularity=\"monthly\";\n\t\n\t// Requesting Website\n\tvar reqApiUrl=\"https://api.similarweb.com/v1/website/\"+url+\"/total-traffic-and-engagement/visits?api_key=\"+pageStatsApiKey+\"&start_date=\"+startDate+\"&end_date=\"+endDate+\"&main_domain_only=\"+mainDomain+\"&granularity=\"+granularity;\n\t\n\t// Request for information for user requested website\n\tvar reqXmlHttp = new XMLHttpRequest();\n reqXmlHttp.open(\"GET\", reqApiUrl, false); // true for asynchronous \n reqXmlHttp.send(null);\n\tvar reqResponse = reqXmlHttp.responseText;\n\tvar reqObj = JSON.parse(reqResponse);\n\t\n\tconsole.log(\"Website Traffic: \" + url);\n\tconsole.log(reqObj);\n\t\n\treturn reqObj;\n}",
"function doSize(theurl, response) {\n response.setHeader(\"Content-Type\", \"text/plain\");\n theurl = theurl.substr(5);\n return new Promise((resolve, reject) => {\n fs.stat(WORKDIRECTORY + theurl.match(FILE)[0], (err, stat) => {\n // If there is an error, write an error message to the response\n if (err) {\n var errorMessage =\n \"ERROR: could not stat file \" + theurl.match(FILE)[0];\n\tconsole.log(errorMessage);\n response.statusMessage = errorMessage;\n response.write(errorMessage + '\\n');\n response.statusCode = 403;\n resolve(errorMessage);\n // Else, write a message to the response with the size of the file\n } else {\n var statMessage =\n \"STAT: the URL \" + theurl.match(FILE)[0] + \" size is \" + stat.size;\n response.statusCode = 200;\n response.write(statMessage + '\\n');\n resolve(statMessage);\n }\n });\n });\n}",
"static async getStats(request, response) {\n response.statusCode = 200;\n response.send({\n users: await dbClient.nbUsers(),\n files: await dbClient.nbFiles(),\n });\n }",
"apiCall(props) {\n\n let url_call = SWAPI_ROOT_URL.replace(\"{stat_type}\", props.stat_type).replace(\"{number}\", props.number);\n\n // The actual fetch\n return BasicJsonApiCall({baseUrl:url_call});\n }",
"function cooljsonp() {\n // calling the servlet hosted in Heroku to count visits\n var url = \"http://mysterious-peak-4595.herokuapp.com/JSONServlet\";\n //alert(\"Calling \" + url );\n var head = document.head;\n var script = document.createElement(\"script\");\n script.setAttribute(\"src\", url );\n head.appendChild(script);\n head.removeChild(script);\n}",
"function linkSanityData(data){\n\tvar linkStat='';\n\tvar linkSanityStat='';\t\n\tvar mydata = data;\n\tif(globalInfoType ==\"XML\"){\n\t\tvar parser = new DOMParser();\n\t\tvar xmlDoc = parser.parseFromString( mydata , \"text/xml\" );\n\t\tvar row = xmlDoc.getElementsByTagName('MAINCONFIG');\n\t\tvar uptable = xmlDoc.getElementsByTagName('DEVICE');\n\t\tvar lowtable = xmlDoc.getElementsByTagName('STATUS');\t \n\t}else{\n\t\tdata = data.replace(/'/g,'\"');\n var json = jQuery.parseJSON(data);\n\t\tif(json.MAINCONFIG){\n var uptable = json.MAINCONFIG[0].DEVICE;\n var lowtable = json.MAINCONFIG[0].STATUS;\n }\n\t}\n\tif(json.MAINCONFIG){\n\t\tclearTimeout(TimeOut);\n\t\tTimeOut = setTimeout(function(){\n\t\t\tlinkSanXML(uptable,lowtable);\n\t\t},5000);\n\t\treturn;\n\t}\n\tlinkSanInit();\n\tTimeOut = setTimeout(function(){\n\t\tsanityQuery('linksanity');\n\t},5000);\n}",
"async function fetchStats(){\n const response = await fetch(\"https://youtube.googleapis.com/youtube/v3/videos?part=statistics&id=cjrOxszo6No&key=AIzaSyCZ0Nc68EsVvYNKeOeRsVGxnSehYBus3Xc\")\n const responseJ = await response.json()\n const stats = responseJ.items[0].statistics\n let rating = Math.floor(Number(stats.likeCount) / (Number(stats.likeCount) + Number(stats.dislikeCount)) * 100);\n console.log(\"Likes: \" + stats.likeCount);\n console.log(\"Dislikes:\" + stats.dislikeCount);\n console.log(\"Rating: \" + rating);\n console.log(stats);\n}",
"function requestStats() {\n // if (Object.keys(peerConnectionDataStore).length > 0)\n // chrome.send('getAllStats');\n}",
"function getinfo(pp, callback) {\n if (pp.isDirectory) {\n directoryInfo(pp, function (result) {\n callback(result);\n });\n } else {\n fileInfo(pp, function (result) {\n callback(result);\n });\n }//if\n }//getinfo",
"function getStats() {\n var statFile = fs.readFileSync('/proc/stat', 'utf8');\n var arr = statFile.split(os.EOL);\n var stats = arr[0].split(/\\s+/g, 5);\n return stats;\n }",
"function reportStats() {\n const now = Date.now();\n console.log(`STATS Tweets: ${totalTweets}\\tErrors: ${totalErrors}\\tUptime: ${Math.round((now - startStatus)/1000)}s`);\n}",
"summary_stats(node) {\n return merge({\n path : `/api/v1/nodes/${node}/proxy/stats/summary`,\n method : 'GET',\n }, this.master_api);\n }",
"function tagUrl(tag) {\n return webbase + \"resourceview.php?tag=\" + tag; // this is probably wrong!\n }",
"function get_full_url(file) {\n\n //\n // We just concatenate strings. This is to ensure\n // efficient memory use as opposed to storing the\n // entire URLs as arrays\n //\n // return {domain: COMMONCRAWL_DOMAIN, path: '/crawl-data/' + file + '/wet.paths.gz'};\n return COMMONCRAWL_BASE_URL + file + COMMONCRAWL_WET_PATHS;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Like checkStatus, but it also tries to start/stop the service as appropriate. If the user has opted out or permissions are not available, stop. If the user has opted in and perissions are available, start. | static async checkStatusAndStartOrStop() {
const status = await this.checkStatus();
const { canTrack, isRunning } = status;
if (canTrack && !isRunning) {
this.start();
}
if (!canTrack && isRunning) {
this.stop();
}
return status;
} | [
"function check() {\n clearTimeout(timer)\n\n if (device.present) {\n // We might get multiple status updates in rapid succession,\n // so let's wait for a while\n switch (device.type) {\n case 'device':\n case 'emulator':\n willStop = false\n timer = setTimeout(work, 100)\n break\n default:\n willStop = true\n timer = setTimeout(stop, 100)\n break\n }\n }\n else {\n willStop = true\n stop()\n }\n }",
"function systemOn (req, res) {\n\t\t// Here we will have calls to public controller functions to switch on/off a boolean\n\t\t// within each controller that lets it know whether it has permission to run\n\t}",
"function startUserStatusSubscription() {\n var utilities = icwsDirectUsageExample.utilities;\n var diagnostics = icwsDirectUsageExample.diagnostics;\n var session = icwsDirectUsageExample.session;\n var icwsUser, payload, userCurrentStatusElement;\n \n // Provide contextual information for the request.\n diagnostics.reportInformationalMessage('Start IC user status subscription', 'Start a subscription for IC status changes for the logged in user.');\n \n // Start listening for IC status changes for the logged in user.\n icwsUser = session.getSessionUser();\n payload = { userIds:[icwsUser] };\n session.sendRequest('PUT', '/messaging/subscriptions/status/user-statuses', payload, function(status, jsonResponse) {\n if (!utilities.isSuccessStatus(status)) { \n updateInteractionDisplay('');\n }\n });\n }",
"function checkRunningAction() {\r\n let gmal_background = localStorage.getItem('gmal_background');\r\n\r\n if(gmal_background == 'running') {\r\n document.querySelector('#input').disabled = true;\r\n document.querySelector('#startBtn').disabled = true;\r\n document.querySelector('#stopBtn').disabled = false;\r\n\r\n setStatus('running');\r\n } else if(gmal_background == 'not_running') {\r\n document.querySelector('#input').disabled = false;\r\n document.querySelector('#input').value = '';\r\n document.querySelector('#stopBtn').disabled = true;\r\n document.querySelector('#startBtn').disabled = false;\r\n\r\n setStatus('not_running');\r\n }\r\n}",
"function IsServiceRunning(/**string*/ name) /**boolean*/\n{\n\tvar strComputer = \".\";\n\tvar SWBemlocator = new ActiveXObject(\"WbemScripting.SWbemLocator\");\n\tvar objCtx = new ActiveXObject(\"WbemScripting.SWbemNamedValueSet\")\n\tobjCtx.Add(\"__ProviderArchitecture\", 64); \n\tvar objWMIService = SWBemlocator.ConnectServer(strComputer, \"/root/CIMV2\", \"\", \"\", null, null, null, objCtx);\n\t\n\tvar query = \"Select * from Win32_Service\";\n\tif(name)\n\t{\n\t\tquery += \" WHERE Name='\" + name + \"'\";\n\t}\n\tvar colItems = objWMIService.ExecQuery(query);\n\t\n\tvar e = new Enumerator(colItems);\n\tfor(; ! e.atEnd(); e.moveNext())\n\t{\n\t\tLog(e.item().Name + \":\" + e.item().State);\n\t\tif (name) \n\t\t{\n\t\t\tif (e.item().State.toLowerCase() == \"running\")\n\t\t\t{\n\t\t\t\treturn true;\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (name) return false;\n}",
"function serviceHealthStatus(healths, service, usersInterested) {\n const serviceName = service.toLowerCase();\n const healthDoc = _.find(healths, health => health.service === service);\n if (healthDoc && (healthDoc.status === 'DOWN') && (serviceTracker[serviceName] === false)) {\n _.forEach(usersInterested, user => {\n const username = user.username;\n const type = 'system service down';\n const dataSummary = { service: serviceName, summary: `${service} service went down` };\n Notifications.define({ username, type, data: dataSummary });\n serviceTracker[serviceName] = true;\n });\n }\n if (healthDoc && healthDoc.status !== ('DOWN' || undefined) && serviceTracker[serviceName] === true) {\n serviceTracker[serviceName] = false;\n }\n}",
"function checkStatus() {\n if (supportsAvif !== null && supportsWebp !== null) {\n showOverlay();\n return;\n }\n }",
"function checkPrivateStationAndLaunch(adviseLaunchInfo){\n \n\t// Verify if this setup can support a Secure Station.\n\t// Else fall back to finding other stations\n\tvar secStationEligible = false;\n\ttry {\n\t\tif ((adviseLaunchInfo['cosMetaData']['major'] > 6) ||\n\t\t\t(adviseLaunchInfo['cosMetaData']['major'] === 6 && (adviseLaunchInfo['cosMetaData']['minor'] > 418)) ||\n\t\t\t(adviseLaunchInfo['cosMetaData']['major'] === 6 && (adviseLaunchInfo['cosMetaData']['minor'] === 418) &&\n\t\t\t\tadviseLaunchInfo['cosMetaData']['fixPack'] >= 3))\n\t\t\tsecStationEligible = true;\n\t} catch(ex){\n\t\tsecStationEligible = false;\n\t}\n\t\n\tif (! secStationEligible){\n\t\tcheckLocalStationAndLaunch(adviseLaunchInfo);\n\t\treturn;\n\t}\n\t\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_CHECK_PRIVATE_STATION'));\n \n var ports = [35125,45341,55447],\n successPort = -1,\n data = null,\n tooLate = false,\n deferreds = [new jQuery.Deferred(), new jQuery.Deferred(), new jQuery.Deferred()];\n \n ports.forEach(function(port, index, array){\n pingPrivateStation(port, function(_data) {\n \t\n \tadviseLaunchInfo['isSecureStation'] = true;\n \n var stationData = _data.getElementsByTagName('StationData');\n if(stationData) {\n stationData = stationData[0];\n\n\t\t\t\t// Check if this station is connected to the right \n\t\t\t\t// MCS server\n\t\t\t\tvar stationMCS = getURLObject(stationData.getAttribute('spaceurl')),\n\t\t\t\t\tmyMCS = getURLObject(adviseLaunchInfo.mcsUrl);\n\t\t\t\tif (stationMCS.hostname === myMCS.hostname && \n\t\t\t\t\t\tstationMCS.port === myMCS.port && \n\t\t\t\t\t\tstationMCS.pathname.replace(/\\//g, '') === myMCS.pathname.replace(/\\//g, '')){\n \tvar stationCOS = stationData.getAttribute('cosid'),\n \t\tstationUser = stationData.getAttribute('user');\n \t//Check COS Server & User\n \tif (stationCOS === adviseLaunchInfo['eedID'] &&\n \t\t\tstationUser === adviseLaunchInfo['currentUser']){\n \t\tvar stationIP = stationData.getAttribute('ip'),\n\t \tstationName = stationData.getAttribute('name');\n \n\t // Used to set the station name to the balloon \n\t // inside RA\n\t adviseLaunchInfo.stationDisplayName = stationName;\n\t \n\t adviseLaunchInfo.runInfo = \"<RunInfo logLevel=\\\"Debug\\\" submissionHost=\\\"\"+stationName+\"\\\"></RunInfo>\";\n\t adviseLaunchInfo.stationName = stationName;\n\t adviseLaunchInfo.proxyServer = \"https://dslauncher.3ds.com:\"+port+\"/SMAExeStation-REST/servant\";\n\t adviseLaunchInfo.secureStation = true;\n\t adviseLaunchInfo.stationAccess = \"https://dslauncher.3ds.com:\"+port+\"/SMAExeStation-REST/station\";\n\t\n\t successPort = port;\n\t \n\t // Skip the local station etc and go directly to launch?\n\t if(!tooLate) {\n\t tooLate = true;\n\t makeRunAdviseJob(adviseLaunchInfo);\n\t\t\t\t\t\t}\n\t\t }\n }\n }\n deferreds[index].resolve(); \n },\n function(_data){\n deferreds[index].resolve();\n }); \n });\n \n var continueExecution = function(){\n \ttooLate = true;\n \tif (adviseLaunchInfo.userSelectedStation !== '{localhost}'){\n \t\tcheckLocalStationAndLaunch(adviseLaunchInfo);\t\n \t}\n \telse{\n \t\t// If the user specifically set affinity to {localhost}, dont submit that job\n \t\t// to a regular station. Security reasons!!\n \t\tshowLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_FAIL_NO_LOCHOST'));\n\t\t\tadviseGoBack(\n\t\t\t\tadviseLaunchInfo.translator.translate('LAUNCH_SERVANT_EXEC_ERROR') + '<br\\>' +\n\t\t\t\tadviseLaunchInfo.translator.translate('LAUNCH_FAIL_NO_LOCHOST')\n\t\t\t);\n \t}\n };\n \n jQuery.when(deferreds[0], deferreds[1], deferreds[2]).done(\n function() {\n console.log(\"All pings to secure private stations are complete.\");\n console.log(\"Success port: \"+successPort);\n console.log(\"data: \"+ data);\n \n if(successPort<0 && !tooLate) continueExecution();\n });\n \n // If secure private station takes too long, then continue\n window.setTimeout(function(){\n if(!tooLate) continueExecution();\n }, 5000);\n}",
"start() {\n if (this.isL2PingAvailable){\n this.scanForAllDevices().bind(this);\n } else {\n this.checkForL2Ping(this.scanForAllDevices.bind(this));\n }\n }",
"function status(){\n if(!_.isEmpty(env)){\n console.log(\"Currently in the following environment:\");\n console.log(columnify(env));\n console.log(\" \"); \n }\n \n var ret = model.checkStatus();\n if(ret === false){\n console.log(\"You currently do not have any timers running\");\n }else{\n console.log(columnify(ret));\n }\n }",
"static get STATUS_RUNNING () {\n return 0;\n }",
"startWalking() {\r\n this.isWalking = true;\r\n\r\n this.setStatus();\r\n this.statusWrapper.classList.remove('stop');\r\n this.statusWrapper.classList.add('start');\r\n }",
"isService() {\n\n return this.type == 'service';\n }",
"function checkTasksState() {\n var i, j, k, listTasks = Variable.findByName(gm, 'tasks'), taskDescriptor, taskInstance,\n newWeek = Variable.findByName(gm, 'week').getInstance(self), inProgress = false,\n listResources = Variable.findByName(gm, 'resources'), resourceInstance, assignment,\n newclientsSatisfaction = Variable.findByName(gm, 'clientsSatisfaction').getInstance(self);\n for (i = 0; i < listTasks.items.size(); i++) {\n inProgress = false;\n taskDescriptor = listTasks.items.get(i);\n taskInstance = taskDescriptor.getInstance(self);\n for (j = 0; j < listResources.items.size(); j++) {\n resourceInstance = listResources.items.get(j).getInstance(self);\n if (resourceInstance.getActive() == true) {\n for (k = 0; k < resourceInstance.getAssignments().size(); k++) {\n assignment = resourceInstance.getAssignments().get(k);\n if (assignment.getTaskDescriptorId() == taskInstance.getDescriptorId() && taskInstance.getActive() == true) {\n inProgress = true;\n }\n }\n }\n }\n if (inProgress ||\n (newWeek.getValue() >= taskDescriptor.getProperty('appearAtWeek') &&\n newWeek.getValue() < taskDescriptor.getProperty('disappearAtWeek') &&\n newclientsSatisfaction.getValue() >= taskDescriptor.getProperty('clientSatisfactionMinToAppear') &&\n newclientsSatisfaction.getValue() <= taskDescriptor.getProperty('clientSatisfactionMaxToAppear') &&\n taskInstance.getDuration() > 0\n )\n ) {\n taskInstance.setActive(true);\n }\n else {\n taskInstance.setActive(false);\n }\n }\n}",
"function systemOff (req, res) {\n\t\t// Here we will have calls to public controller functions to switch on/off a boolean\n\t\t// within each controller that lets it know whether it has permission to run\n\t}",
"start() {\n if (!this.stop) return\n this.stop = false\n this.__poll()\n }",
"function C006_Isolation_Yuki_CheckToStop() {\n\n\t// Yuki doesn't allow the player to stop if she has the egg\n\tif (C006_Isolation_Yuki_EggInside) {\n\t\tOverridenIntroText = GetText(\"NoPullEgg\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t\tC006_Isolation_Yuki_AllowPullBack = false;\n\t}\n\n\t// Yuki doesn't allow the player to stop if she's dominant\n\tif (ActorGetValue(ActorSubmission) <= -3) {\n\t\tOverridenIntroText = GetText(\"NoPullSub\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t\tC006_Isolation_Yuki_AllowPullBack = false;\n\t}\n\t\n}",
"checkActionStatus() {\n if (this.state >= SolairesAction.STATUS.DONE)\n return;\n if (this.state == SolairesAction.STATUS.ACK)\n SolairesAction.updateGMAck(false);\n }",
"function checkStatus(mountpointList, streamToCheck){\n var needle = mountpointList.find(function(mountpoint){\n if(mountpoint.listenurl == \"http://77.68.10.108:8080/\" + streamToCheck){\n return true;\n }\n })\n // test whether the mountpoint was found\n if (typeof(needle) === 'object') {\n console.log('Mountpoint up!');\n } else {\n console.log('Mountpoint is down! Sending slack message...');\n if (streamToCheck == \"listen\") {\n slack.send(mainDown);\n } else if(streamToCheck == \"hub\"){\n slack.send(hubDown);\n } else if(streamToCheck == \"harrow\"){\n slack.send(harrowDown);\n }\n }\n}",
"startServices () {\n for (let serviceId in this.services) {\n let service = this.services[serviceId]\n service.start().then(() => {\n this.logger.log(`${service.name}: OK`)\n }).catch(() => {\n // TODO: Figure out how to handle errors here.\n })\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you | function GetMouseCursor() { return bind.GetMouseCursor(); } | [
"_setDefault(){\n this.defaultCursor = \"default\";\n // this.hOverCursor = \"pointer\";\n }",
"function changeCursor(cursor) {\n document.body.style.cursor = cursor; \n}",
"function showCursor(cur) {\n if (cur != undefined) selectCursor(cur);\n slides.style.cursor = currentCursor;\n }",
"function crosshairCursor(options = {}) {\n let [code, getter] = keys[options.key || 'Alt']\n let plugin = dist_ViewPlugin.fromClass(\n class {\n constructor(view) {\n this.view = view\n this.isDown = false\n }\n set(isDown) {\n if (this.isDown != isDown) {\n this.isDown = isDown\n this.view.update([])\n }\n }\n },\n {\n eventHandlers: {\n keydown(e) {\n this.set(e.keyCode == code || getter(e))\n },\n keyup(e) {\n if (e.keyCode == code || !getter(e)) this.set(false)\n },\n mousemove(e) {\n this.set(getter(e))\n }\n }\n }\n )\n return [\n plugin,\n EditorView.contentAttributes.of((view) => {\n var _a\n return (\n (_a = view.plugin(plugin)) === null || _a === void 0\n ? void 0\n : _a.isDown\n )\n ? showCrosshair\n : null\n })\n ]\n }",
"function drawMouseCursor()\n{\n drawingContext.beginPath();\n drawingContext.strokeStyle = \"#AAAA00\"\n if (switchLines || (isBonusRound && bonusRoundType == 1)) {\n drawingContext.moveTo(mouseX - 10, mouseY);\n drawingContext.lineTo(mouseX + 10, mouseY);\n }\n if (!switchLines || (isBonusRound && bonusRoundType == 1)) {\n drawingContext.moveTo(mouseX, mouseY - 10);\n drawingContext.lineTo(mouseX, mouseY + 10);\n }\n drawingContext.closePath();\n drawingContext.stroke();\n}",
"function dropCursor() {\n return [dropCursorPos, drawDropCursor]\n }",
"showSystemCursor() {\n if (this._cursorTracker.set_keep_focus_while_hidden)\n this._cursorTracker.set_keep_focus_while_hidden(false);\n this._cursorTracker.set_pointer_visible(true);\n }",
"__refreshCursor() {\n var currentCursor = this.getStyle(\"cursor\");\n this.setStyle(\"cursor\", null, true);\n this.setStyle(\"cursor\", currentCursor, true);\n }",
"buildCursor(props) {\n let cursorCameraControls = `movement-controls=\"controls: checkpoint\"`;\n let cursor = ``;\n\n if (props.cursorCamera === true) {\n // Add camera cursor\n // cursorCameraControls = `look-controls movement-controls=\"controls: checkpoint\"`;\n cursorCameraControls = `look-controls`;\n cursor = `<a-entity\n cursor=\"fuse: true\"\n material=\"color: black; shader: flat\"\n position=\"0 0 -3\"\n raycaster=\"objects: ${props.cursorTargetClass};\"\n geometry=\"primitive: ring; radiusInner: 0.08; radiusOuter: 0.1;\"\n >\n </a-entity>`;\n }\n return {\n cursorCameraControls: cursorCameraControls,\n cursor: cursor\n }\n }",
"function mouseReleased() {\n console.log('released!');\n cursorColor = 'rgb(0,0,0)';\n cursorDia = 60;\n}",
"function overrideCursor(cursor) {\n var body = document.body;\n if (cursorStack.length === 0) {\n body.classList.add(CURSOR_OVERRIDE);\n }\n var style = body.style;\n if (style.cursor !== cursor) {\n style.cursor = cursor;\n }\n var item = { cursor: cursor };\n cursorStack.push(item);\n return new Disposable(function () { return removeCursorItem(item); });\n }",
"function setCursor(canvas, image, defaultCursor) {\n canvas.style.cursor = (isIE() ? 'url(images/' + image + '.cur)' :\n 'url(images/' + image + '.svg) ' + + ' ' + curAnnotationXY + ' ' + curAnnotationXY) +\n ', ' + defaultCursor;\n}",
"createCursor() {\n var cursor = document.createElement( 'div' );\n cursor.classList.add( 'cursor' );\n cursor.style.height = this.lineHeight + 'px';\n this.overlay.appendChild( cursor );\n\n return cursor;\n }",
"function mouseDragged() {\n console.log('- dragged...');\n cursorColor = 'rgb(255,150,0)';\n}",
"function loadCursor(url, x,y) {\n\tvar img = loadImage(url);\n\timg.hotSpotX = x;\n\timg.hotSpotY = y;\n}",
"function setCursor(cursor) {\n var x = document.querySelectorAll(\"*\");\n for (var i = 0; i < x.length; i++) {\n x[i].style.cursor = cursor;\n }\n}",
"function Cursor() {\r\n\tvar fader2d = Fader2D();\r\n\tvar pushDetector = PushDetector();\r\n\r\n\tvar events = Events();\r\n\tvar api = {\r\n\t\tonattach : onattach,\r\n\t\tondetach : ondetach,\r\n\t\tpushDetector : pushDetector,\r\n\t\tfader2d : fader2d,\r\n\t\tvalue : [0,0],\r\n\t\tx : 0,\r\n\t\ty : 0,\r\n\t}\r\n\tevents.eventify(api);\r\n\t\r\n\tfader2d.addEventListener('valuechange', function(f) {\r\n\t\tapi.value[0] = api.x = f.value[0];\r\n\t\tapi.value[1] = api.y = 1 - f.value[1];\r\n\t\tevents.fireEvent('move', api);\r\n\t});\r\n\r\n\tpushDetector.addEventListener('push', function(pd) {\r\n\t\tevents.fireEvent('push', api);\r\n\t});\r\n\tpushDetector.addEventListener('release', function(pd) {\r\n\t\tevents.fireEvent('release', api);\r\n\t});\r\n\tpushDetector.addEventListener('click', function(pd) {\r\n\t\tevents.fireEvent('click', api);\r\n\t});\r\n\r\n\tfunction onattach(target) {\r\n\t\ttarget.addListener(fader2d);\r\n\t\ttarget.addListener(pushDetector);\r\n\t}\r\n\r\n\tfunction ondetach(target) {\r\n\t\ttarget.removeListener(fader2d);\r\n\t\ttarget.removeListener(pushDetector);\r\n\t}\r\n\r\n\treturn api;\r\n}",
"function setCursor(image) {\n\tif(!image)\n\t\tdelete theCanvas.style.cursor;\n\telse\n\t\ttheCanvas.style.cursor = \"url(\"+image.src+\") \"+\n\t\t\timage.hotSpotX+\" \"+\n\t\t\timage.hotSpotY+\n\t\t\t\", auto\";\n}",
"function save_mouse_position() {\n mouse_position_x = mouseX\n mouse_position_y = mouseY\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.