query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Filter locations by query | filterLocations(query, venues) {
return venues.filter(venue => venue.name.toLowerCase().includes(query.toLowerCase()))
} | [
"function filterByDistance() {\r\n //filter by Distance will only show \"pins\" within 1 mile of users location\r\n }",
"function filterPlace () {\n const data = { amenities: listIdAmenities };\n getPlaces(JSON.stringify(data));\n}",
"function querySearch (query) {\n if (query.length < 2) {\n return [];\n }\n return countryService.search(query);\n }",
"function filterCategory(category){\n\n currentcategory = category;\n \n if(category == 0){\n \n locations = orglocations;\n \n }else{\n \n locations = orglocations.filter( i => i.category == category );\n \n }\n \n initialize();\n\n}",
"function filterSearchResults(markers) {\n \n //If a region is selected, go through the list of markers and remove any that are not in the selected regions.\n //Check to see if the marker is contained within each of the polygons here.\n \n var positionWithinBounds = false;\n\tvar markersToKeep = new Array();\n\tfor (var i = 0; i < markers.length; i++) {\n var marker = markers[i];\n var regionListLength = regionList.length;\n\n\t\tfor(var j = 0; j < regionListLength; j++) {\n \n var region = regionList[j];\n if (region.isActive && google.maps.geometry.poly.containsLocation(marker.getPosition(), region.polygon)) {\n positionWithinBounds = true;\n\t\t\t\tmarkersToKeep.push(marker);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (markersToKeep.length <= 0) {\n\t\talert(\"No results were found in the selected regions for the given search term.\");\n\t} else {\n setMarkers(markersToKeep);\n\t\tcenterMap(markersToKeep);\n\t\tmarkers = markersToKeep;\n\t}\n\t\n\tfor (var i = 0; i < placeMarkerPairs.length; i++) {\n var found = false;\n\t\tfor (var j = 0; j < markersToKeep.length; j++) {\n \n if (markersToKeep[j] == placeMarkerPairs[i].marker) {\n found = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n if (!found) {\n\t\t\tplaceMarkerPairs.splice(i,1);\n\t\t}\n\t}\n\t\n\tsetPlaceMarkerDetails();\t\n}",
"function searchforLoaction(locations,isInit)\n {\n\t var viewModel = {\n\t\t \n query: ko.observable(''),\n\t\tselectItem: function(event) {\n\t\t var retObj = $.grep(markers, function(obj){\n\t\t\t \n\t\t\t return obj.label == event.label;\n\t\t\t \n\t\t\t });\n google.maps.event.trigger(retObj[0], 'click');\n } \n };\n\n\t\n viewModel.locations = ko.dependentObservable(function() {\n var search = this.query().toLowerCase();\n\t\tclearMarkers();\n\t\tmarkers=[];\n return ko.utils.arrayFilter(locations, function(location) {\n\t\t\t\n\t\t\tif(search===\"\")\n\t\t\t{\n\t\t\t\tfillmarkerBySearch(markers,null,searchLocation,true);\n\t\t\t}\n\t\t else \n\t\t\t{\n\t\t\t\tvar searchLocationExist = location.title.toLowerCase().indexOf(search) >= 0?true:false;\n\t\t\t\tif(searchLocationExist===true)\n\t\t\t\t{\n\t\t\t\tfillmarkerBySearch(markers,location,searchLocationExist,false);\n\t\t\t\t}\n\t\t\t}\n var searchLocation = location.title.toLowerCase().indexOf(search) > 0;\n\t\t\treturn location.title.toLowerCase().indexOf(search) >= 0;\n });\n }, viewModel);\n\n ko.applyBindings(viewModel);\n }",
"function searchPlaces(loc) {\n // create places service\n var service = new google.maps.places.PlacesService(map);\n service.nearbySearch({\n location: loc,\n radius: 500\n // type: ['store']\n },\n // callback function for nearbySearch\n function(results, status) {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n for (var i = 0; i < results.length; i++) {\n createMarker(results[i]);\n }\n } else {\n window.alert(\"Google places search failed at that moment, please try again\");\n }\n });\n }",
"function stationsQuery (vm) {\n const searchText = vm.searchText.trim()\n const query = {\n enabled: true,\n organization_id: vm.state.organization._id,\n station_type: 'weather',\n slug: {$exists: 1},\n $limit: 200,\n $sort: {name: 1} // ASC\n }\n if (searchText.length > 0) {\n query.name = {\n $regex: searchText,\n $options: 'i'\n }\n }\n\n return query\n}",
"apply_filters() {\n return this.data\n .filter(d => this.selected_towns[d.town])\n .filter(d => this.selected_categories[d.object_category])\n .filter(d => d.date_full >= this.selected_start && d.date_full <= this.selected_end);\n }",
"function filterByRegion(term, callback) {\n $.ajax({\n url: '/events/region/' + term,\n type: 'GET',\n dataType: 'json',\n success: callback\n });\n}",
"function searchSidebarResults ( term, baseurl, page, sort, search_count ) {\n var new_loc = $specified_loc.split(', ').join(',');\n var data = { what : term, where : new_loc, page_num : page, sortby : sort, count : search_count };\n $.ajax({\n type: \"POST\",\n url: baseurl + \"/api/search.php\",\n dataType: \"JSON\",\n data: data,\n success: function(data){\n if( data.success.results.locations.length > 0 ){\n if(!$.isEmptyObject(data.success.results.locations)){ \n renderSidebarResults(data.success.results.locations); \n }\n }\n }\n });\n }",
"function filterLocations(type, display) {\n for (let i = 0; i < locations.length; i++) {\n if (locations[i].classList.contains(type)) {\n if (display) {\n locations[i].style.display = 'block';\n } else {\n locations[i].style.display = 'none';\n //Uncheck all the corresponding locations when a location type gets unchecked.\n locations[i].firstChild.checked = false;\n }\n }\n }\n}",
"function callNearBySearchAPI() {\n //\n city = new google.maps.LatLng(coordinates.lat, coordinates.long);\n map = new google.maps.Map(document.getElementById(\"map\"), {\n center: city,\n zoom: 15,\n });\n //\n request = {\n location: city,\n radius: \"5000\", // meters\n type: [\"restaurant\"],\n // openNow: true,\n fields: [\n \"name\",\n \"business_status\",\n \"icon\",\n \"types\",\n \"rating\",\n \"reviews\",\n \"formatted_phone_number\",\n \"address_component\",\n \"opening_hours\",\n \"geometry\",\n \"vicinity\",\n \"website\",\n \"url\",\n \"address_components\",\n \"price_level\",\n \"reviews\",\n ],\n };\n //\n service = new google.maps.places.PlacesService(map);\n service.nearbySearch(request, getGooglePlacesData);\n //\n}",
"function searchFunc() {\n\t // get the value of the search input field\n\t var searchString = $('#search').val(); //.toLowerCase();\n\t markers.setFilter(showFamily);\n\n\t // here we're simply comparing the 'state' property of each marker\n\t // to the search string, seeing whether the former contains the latter.\n\t function showFamily(feature) {\n\t return (feature.properties.last_name === searchString || feature.properties[\"always-show\"] === true);\n\t }\n\t}",
"function useQuery () {\n return new URLSearchParams(useLocation().search)\n}",
"function searchRestaurant() {\n let search = {\n bounds: map.getBounds(),\n types: [\"restaurant\"],\n };\n places.nearbySearch(search, (results, status) => {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n clearResults();\n clearMarkers();\n\n // Create a marker for each resturant found, and\n // assign a letter of the alphabetic to each marker icon.\n for (let i = 0; i < results.length; i++) {\n let markerLetter = String.fromCharCode(\"A\".charCodeAt(0) + (i % 26));\n let markerIcon = MARKER_PATH + markerLetter + \".png\";\n\n // Use marker animation to drop the icons incrementally on the map.\n markers[i] = new google.maps.Marker({\n position: results[i].geometry.location,\n animation: google.maps.Animation.DROP,\n icon: markerIcon,\n });\n\n // If the user clicks a resturant marker, show the details of that place in an info window\n markers[i].placeResult = results[i];\n google.maps.event.addListener(markers[i], \"click\", showInfoWindow);\n setTimeout(dropMarker(i), i * 100);\n addResult(results[i], i);\n }\n }\n });\n}",
"function searchCity(id, direction) {\n\n var getParams = stringifyUrlQuery();\n\n if (direction === 'from') {\n if (getParams.includes('&fromPlaceId')) {\n getParams = getParams.replace(/fromPlaceId=[0-9]*/, 'fromPlaceId=' + id);\n } else {\n getParams += \"&fromPlaceId=\" + id;\n }\n } else if (direction === 'to') {\n if (getParams.includes('&toPlaceId')) {\n getParams = getParams.replace(/toPlaceId=[0-9]*/, 'toPlaceId=' + id);\n } else {\n getParams += \"&toPlaceId=\" + id;\n }\n }\n\n window.location = \"search\" + getParams;\n}",
"buildLocation() {\n const search = this.#params.toString();\n return { ...this.#location, search: search ? '?' + search : '' };\n }",
"searchWithParams(query) {\n if (Object.keys(query).length) {\n this.set('isSearching', true);\n this.get('store').query('patient-search', query).then(results => {\n this.setProperties({\n results: results.filterBy('isActive'),\n isSearching: false\n });\n this.sendAction('didSearch');\n\n if (this.get('displayResults')) {\n this.set('showResults', true);\n this.set('showHints', false);\n }\n }).catch(error => {\n if (!this.get('isDestroyed')) {\n this.set('isSearching', false);\n this.sendAction('didSearch', error);\n }\n });\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a function for getV3ProjectsIdTriggersToken | getV3ProjectsIdTriggersToken(incomingOptions, cb) {
const Gitlab = require('./dist');
let defaultClient = Gitlab.ApiClient.instance;
// Configure API key authorization: private_token_header
let private_token_header = defaultClient.authentications['private_token_header'];
private_token_header.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_header.apiKeyPrefix = 'Token';
// Configure API key authorization: private_token_query
let private_token_query = defaultClient.authentications['private_token_query'];
private_token_query.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_query.apiKeyPrefix = 'Token';
let apiInstance = new Gitlab.ProjectsApi()
/*let id = "id_example";*/ // String | The ID of a projec
/*let token = "token_example";*/ // String | The unique token of trigger
apiInstance.getV3ProjectsIdTriggersToken(incomingOptions.id, incomingOptions.token, (error, data, response) => {
if (error) {
cb(error, null)
} else {
cb(null, data)
}
});
} | [
"postV3ProjectsIdTriggers(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 project\napiInstance.postV3ProjectsIdTriggers(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"function deleteTriggers() {\r\n var triggers = ScriptApp.getProjectTriggers();\r\n for (var i = 0; i < triggers.length; i++) {\r\n ScriptApp.deleteTrigger(triggers[i]);\r\n }\r\n}",
"function deleteTriggers() {\r\n var triggers = ScriptApp.getProjectTriggers();\r\n for (var i = 0; i < triggers.length; i++) {\r\n ScriptApp.deleteTrigger(triggers[i]);\r\n }\r\n}",
"visitTrigger_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function DeletePostTrigger(){\n var triggerIDs = [properties.getProperty('scheduledPost_ID'), properties.getProperty('deleteTrigger_ID')];\n var allTriggers = ScriptApp.getProjectTriggers();\n for(var i = 0; i < allTriggers.length; i++){\n for(var j = 0; j < triggerIDs.length; j++){\n var trigger = allTriggers[i]\n var triggerID = trigger.getUniqueId();\n if(triggerID == triggerIDs[j]){\n ScriptApp.deleteTrigger(trigger);\n }\n }\n }\n DeleteProperty('scheduledPost_ID');\n DeletePropery('deleteTrigger_ID');\n}",
"function getTrigger() {\n let { eventName, payload } = github.context;\n const payload_action = payload.action;\n console.info(`Trigger -> ${eventName} - ${payload_action}`);\n switch (eventName) {\n case 'push':\n return 'commit';\n case 'pull_request':\n if (payload_action === \"opened\")\n return 'pull-request';\n if (payload_action === \"synchronize\")\n return 'pull-request-sync';\n return 'pull-request-other';\n // case 'pull_request_review_comment':\n // return 'pr-comment';\n case 'workflow_dispatch':\n return 'manual';\n default:\n console.warn(\"Event trigger not of type: commit, pull request or manual.\");\n throw new Error(\"Invalid trigger event\");\n }\n}",
"function removeTriggers() {\n var triggers = ScriptApp.getProjectTriggers();\n for (var i = 0; i < triggers.length; i++) {\n ScriptApp.deleteTrigger(triggers[i]);\n }\n}",
"function getInshiftTriggers (triggers_in_shift, alert_triggers) {\n if (triggers_in_shift != null) {\n const temp = [];\n if (alert_triggers != null) {\n for (let z = alert_triggers.length; z >= 0; z -= 1) {\n const trigger = alert_triggers[z];\n const triggers_array = triggers_in_shift.map(({ trigger_type }) => trigger_type);\n\n let y = triggers_array.indexOf(trigger);\n if (y !== -1) {\n temp.push(triggers_in_shift[y]);\n }\n\n if (trigger === \"G\" || trigger === \"S\" || trigger === \"M\") {\n y = triggers_array.indexOf(trigger.toLowerCase());\n if (y !== -1) {\n temp.push(triggers_in_shift[y]);\n }\n }\n }\n return temp;\n } return null;\n } return null;\n}",
"visitTrigger_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSimple_dml_trigger(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"postV3ProjectsIdServicesSlackSlashCommandsTrigger(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 UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdServicesSlackSlashCommandsTrigger(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"static get queriesHitTriggers() {}",
"visitCompound_dml_trigger(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitCreate_trigger(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"postV3ProjectsIdServicesMattermostSlashCommandsTrigger(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 UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdServicesMattermostSlashCommandsTrigger(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"getV3ProjectsIdKeys(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 project\napiInstance.getV3ProjectsIdKeys(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"static get_token({ organizationId, tokenId }) {\n return new Promise(\n async (resolve) => {\n try {\n resolve(Service.successResponse(''));\n } catch (e) {\n resolve(Service.rejectResponse(\n e.message || 'Invalid input',\n e.status || 405,\n ));\n }\n },\n );\n }",
"token_script(id) {\n return query.token_script(id, this.network)\n }",
"visitTrigger_block(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
void PutSubscriberProperty (string, Variant) | PutSubscriberProperty(string, Variant) {
} | [
"PutPublisherProperty(string, Variant) {\n\n }",
"onPropertySet(room, property, value, identifier) {\n room[prop] = value;\n }",
"function sendPropertyToTTS(thng, property) {\n console.log('[TTS] Sending property update');\n\n evrythng.thng(thng.id).read().then(function (thngRead) {\n\n var propertyUpdates = {\n status: thngRead.properties.status,\n color: {\n model: thngRead.properties.model,\n cie1931: {\n x: thngRead.properties.x,\n y: thngRead.properties.y\n }\n },\n brightness: thngRead.properties.brightness\n };\n\n //Save the last update to avoid duplicates\n lastTTSPropertyUpdate = propertyUpdates;\n\n var json = JSON.stringify({\n path: '/api/v1/device/perform/' + thng.identifiers.tts.split('/')[1],\n requestID: '3',\n perform: thngRead.properties.status,\n parameter: JSON.stringify(propertyUpdates)\n });\n\n manageWS.send(json);\n });\n}",
"addProperty(property, value) {\n this.properties.set(property, value);\n }",
"stateValuesSendSubscriptions () {\n this.send('state.values.subscribe', { paths: this.subscriptions })\n }",
"set topic(aValue) {\n this._logService.debug(\"gsDiggEvent.topic[set]\");\n this._topic = aValue;\n }",
"function subscribeTo(p) {\n publisher = p;\n p.addGlube(that);\n }",
"function updatePropertyInternal(conn, targets, propertyName, value) {\n\tvar me = controller.findActivePlayerByConnection(conn);\n\n\tif (!Array.isArray(targets)) \n\t\ttargets = [targets];\n\n\tvar ftargets = targets.filter(function(obj) {\n\t\treturn obj.ownerId === me.id;\n\t});\n\n\tif (ftargets.length === 0) {\n\t\t//nothing that belongs to you\n\t\tcontroller.sendMessage(conn, strings.permissionDenied);\n\t} else if (ftargets.length>1 && predicates.sameName(ftargets)) {\n\t\tcontroller.sendMessage(conn, strings.ambigSet);\n\t} else {\n\t\tvar target = ftargets[0];\n\n\t\ttarget[propertyName] = value;\n\t\ttarget.save().then(obj => {\n\t\t\tcontroller.sendMessage(conn, strings.set, {property: Str(strings[propertyName]).capitalize().s});\n\t\t});\n\t}\n}",
"function subSuccess() {\n // console.log(\"Subscribe succeeded\");\n}",
"function setProperty(propertyName, propertyValue)\r\n{\r\n loadSettingsDb();\r\n db.transaction(function(tx) {\r\n tx.executeSql(\"INSERT OR REPLACE INTO EasyListApp (property, value) VALUES (?,?)\", [propertyName, propertyValue]);\r\n });\r\n}",
"set(target, property, value, receiver) {\n const updateWasSuccessful = trap.set(target, property, value, receiver);\n return updateWasSuccessful;\n }",
"createProperty(obj, name, value, post = null, priority = 0, transform = null, isPoly = false) {\n obj['__' + name] = {\n value,\n isProperty: true,\n sequencers: [],\n tidals: [],\n mods: [],\n name,\n type: obj.type,\n __owner: obj,\n\n fade(from = 0, to = 1, time = 4, delay = 0) {\n Gibber[obj.type].createFade(from, to, time, obj, name, delay);\n return obj;\n }\n\n };\n Gibber.addSequencing(obj, name, priority, value, '__');\n Object.defineProperty(obj, name, {\n configurable: true,\n get: Gibber[obj.type].createGetter(obj, name),\n set: Gibber[obj.type].createSetter(obj, name, post, transform, isPoly)\n });\n }",
"async updatePropertyStatus(ctx, propertyId, name, aadharNumber, status){\r\n\r\n\t\tconst userKey = ctx.stub.createCompositeKey('org.property-registration-network.regnet.user',[name, aadharNumber]);\r\n\r\n\t\tlet userBuffer = await ctx.stub.getState(userKey).catch(err => console.log(err));\r\n\r\n\t\tif(userBuffer.length === 0){\r\n\t\t\tthrow new Error(\"User isn't registered\");\r\n\t\t}\r\n\r\n\t\tconst propertyKey = ctx.stub.createCompositeKey('org.property-registration-network.regnet.property',[propertyId]);\r\n\r\n\t\tlet propertyBuffer = await ctx.stub.getState(propertyKey).catch(err => console.log(err));\r\n\r\n\t\tif(propertyBuffer.length === 0){\r\n\t\t\tthrow new Error(\"Property isn't registered\");\r\n\t\t}\r\n\r\n\t\tlet propertyObject = JSON.parse(propertyBuffer.toString());\r\n\r\n\t\tif(propertyObject['owner'] !== userKey){\r\n\t\t\tthrow new Error(\"User isn't owner of this property\");\r\n\t\t}\r\n\r\n\t\tpropertyObject['status'] = status;\r\n\r\n\t\tlet dataBuffer = Buffer.from(JSON.stringify(propertyObject));\r\n\r\n\t\tawait ctx.stub.putState(propertyKey,dataBuffer);\r\n\r\n\t\treturn propertyObject;\r\n\r\n\t}",
"function setattr( obj, name, value )\n { obj[name] = value; }",
"stateValuesSubscribe (path) {\n // prevent duplicates\n if (contains(path, this.subscriptions)) return\n // subscribe\n this.subscriptions.push(path)\n this.stateValuesSendSubscriptions()\n }",
"function send_to_ppnr_slider(p,s_value){\n var dict = {type : \"slider\", value : s_value};\n var json_message = JSON.stringify(dict);\n connection_ppnr = ppnr_dict[\"client_id\"][p];//123. Might be an error here\n connection_ppnr.send(json_message);\n}",
"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 publishAboutObject() {\r\n lit.ABOUT_OBJECT.components[0].version = version;\r\n toolkit.mqtt.publish(\r\n lit.ENGINE_ABOUT_TOPIC,\r\n JSON.stringify(lit.ABOUT_OBJECT),\r\n false,\r\n 1,\r\n function (error, topic, message) {\r\n if (error) {\r\n toolkit.log.error(topic, error);\r\n } else {\r\n toolkit.log.debug(topic, \"Published about object \", message);\r\n toolkit.mqtt.deregister(\r\n lit.RUNLEVEL_TOPIC,\r\n true,\r\n function (error) {\r\n if (error) {\r\n toolkit.log.error(lit.RUNLEVEL_TOPIC, error);\r\n }\r\n }\r\n );\r\n }\r\n }\r\n );\r\n}",
"set(name, value) {\n this.bkts[this.bucketFor(name)] = value\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gives the path between [p_orig] (excluded) and [p_dest] (included). | function build_path(p_orig, p_dest){
var res = new Array();
if(p_orig.x == p_dest.x){
if(p_orig.y < p_dest.y){
// Vertical path, going downwards.
for(var y = p_orig.y + 1; y <= p_dest.y; y++){
res.push({x: p_orig.x, y: y});
}
} else {
// Vertical path, going upwards.
for(var y = p_orig.y - 1; y >= p_dest.y; y--){
res.push({x: p_orig.x, y: y});
}
}
} else if(p_orig.y == p_dest.y){
if(p_orig.x < p_dest.x){
// Horizontal path, going to the right.
for(var x = p_orig.x + 1; x <= p_dest.x; x++){
res.push({x: x, y: p_orig.y});
}
} else {
// Horizontal path, going to the left.
for(var x = p_orig.x - 1; x >= p_dest.x; x--){
res.push({x: x, y: p_orig.y});
}
}
} else {
res.push(p_dest); // TODO properly handle diagonal paths.
}
return res;
} | [
"function destPath() {\n // Remove preceding slash '/'.\n return window.location.pathname.slice(1) + window.location.search;\n }",
"function ipPath(fromNet , toNet){\n var ret = [];\n if (!SPTree)\n updateSPTree();\n if (!SPTree[fromNet][toNet]){\n showTitle(\"No path available from \"+fromNet+\" to \" +toNet);\n return ret;\n }\n // We do a backward path, from destination do source\n var e2e = SPTree[fromNet][toNet];\n var next = toNet;\n for (var step=0; step<e2e.distance; step++){\n var target = SPTree[fromNet][next].predecessor,\n gwIP;\n if (next != fromNet){\n if (isLeaf(next)){\n // If it is a leaf we directly use the IP (it should be a /32)\n var sp = getNetworkSubnet((getNetworkID(next))).split(\"/\");\n ret.push(sp[0]);\n }\n else{\n gwIP = gatewayIpOnNet(netGraph.edge(next , target) , next);\n if (gwIP){\n ret.push(network.extractIp(gwIP));\n }\n }\n\n }\n next = SPTree[fromNet][next].predecessor;\n }\n return ret;\n}",
"constructPath(cameFrom, goal) {\n let path = this.board.getNeighborTiles(goal[0], goal[1]);\n let pos = goal;\n while (pos !== null) {\n path.unshift(pos);\n pos = cameFrom[pos]; // set the pos to prev pos\n }\n\n return path;\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 getPath() {\n //this gets the full url\n var url = document.location.href, path;\n // first strip \n path = url.substr(url.indexOf('//') + 2, url.length - 1);\n path = path.substr(path.indexOf('/'), path.lastIndexOf('/') - path.indexOf('/') + 1);\n //return\n return path;\n }",
"function relatizePath(path) {\r\n\t\tif ('string' !== typeof path && 'function' === typeof path.getAttribute)\r\n\t\t\tpath = path.getAttribute('d');\r\n\t\treturn Raphael.pathToRelative(path).flatten().join(' ');\r\n\t}",
"function getRedirectedRoute({ src, redirects }) {\n\tconst match = redirects.find(redirect => {\n\t\tconst nonMatchingKeys = Object.keys(redirect.src).filter(key => {\n\t\t\tconst wildcardRedirectSrc = redirect.src[key]\n\t\t\tif (\n\t\t\t\ttypeof wildcardRedirectSrc === 'string' &&\n\t\t\t\twildcardRedirectSrc.endsWith('*')\n\t\t\t) {\n\t\t\t\treturn (\n\t\t\t\t\t!src[key] || !src[key].startsWith(wildcardRedirectSrc.slice(0, -1))\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn wildcardRedirectSrc !== src[key]\n\t\t})\n\t\treturn nonMatchingKeys.length === 0\n\t})\n\tif (!match) {\n\t\treturn null\n\t}\n\n\tconst dest = Object.assign({}, match.dest)\n\tObject.keys(dest).forEach(key => {\n\t\tif (dest[key] === '@SAME_AS_SRC@') {\n\t\t\tdest[key] = src[key]\n\t\t}\n\t})\n\n\treturn dest\n}",
"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 }",
"previous(path) {\n if (path.length === 0) {\n throw new Error(\"Cannot get the previous path of a root path [\".concat(path, \"], because it has no previous index.\"));\n }\n\n var last = path[path.length - 1];\n\n if (last <= 0) {\n throw new Error(\"Cannot get the previous path of a first child path [\".concat(path, \"] because it would result in a negative index.\"));\n }\n\n return path.slice(0, -1).concat(last - 1);\n }",
"ancestors(path) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var {\n reverse = false\n } = options;\n var paths = Path.levels(path, options);\n\n if (reverse) {\n paths = paths.slice(1);\n } else {\n paths = paths.slice(0, -1);\n }\n\n return paths;\n }",
"findPaths(fromNavNode, toNavNode) {\r\n\t\tlet walkingPaths = [[fromNavNode]];\r\n\t\tlet rtn = [];\r\n\r\n\t\twhile( walkingPaths.length > 0 ) {\r\n\t\t\tlet curPath = walkingPaths.pop();\r\n\t\t\tlet curNode = curPath[curPath.length-1].node;\r\n\t\t\tlet noRoute = false;\r\n\t\t\twhile( !noRoute && curNode != toNavNode ) {\r\n\t\t\t\tlet connections = curNode.connections.filter( connection => !curPath.includes(connection) );\r\n\t\t\t\tif ( connections.length > 0 ) {\r\n\t\t\t\t\tfor( let i = 1; i < connections.length; i++ ) {\r\n\t\t\t\t\t\tlet newPath = curPath.slice();\r\n\t\t\t\t\t\tnewPath.push(connections[i]);\r\n\t\t\t\t\t\twalkingPaths.push(newPath);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcurPath.push(connections[0]);\r\n\t\t\t\t\tcurNode = connections[0].node;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tnoRoute = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif ( !noRoute ) {\r\n\t\t\t\trtn.push(curPath);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn rtn;\r\n\t}",
"getPointOnPath(path, index, target = []) {\n const {positionSize} = this;\n if (index * positionSize >= path.length) {\n // loop\n index += 1 - path.length / positionSize;\n }\n const i = index * positionSize;\n target[0] = path[i];\n target[1] = path[i + 1];\n target[2] = (positionSize === 3 && path[i + 2]) || 0;\n return target;\n }",
"relative(path, ancestor) {\n if (!Path.isAncestor(ancestor, path) && !Path.equals(path, ancestor)) {\n throw new Error(\"Cannot get the relative path of [\".concat(path, \"] inside ancestor [\").concat(ancestor, \"], because it is not above or equal to the path.\"));\n }\n\n return path.slice(ancestor.length);\n }",
"function concatPath(a, b) {\n if (NodePath.sep === \"\\\\\") {\n return NodePath.normalize(a + \"/\" + b).replace(/\\\\/g, \"/\");\n }\n else {\n return NodePath.normalize(a + \"/\" + b);\n }\n}",
"getPointOnPath(path, index, target = []) {\n const {\n positionSize\n } = this;\n\n if (index * positionSize >= path.length) {\n // loop\n index += 1 - path.length / positionSize;\n }\n\n const i = index * positionSize;\n target[0] = path[i];\n target[1] = path[i + 1];\n target[2] = positionSize === 3 && path[i + 2] || 0;\n return target;\n }",
"function joinPath (first, second) {\n // If the second part starts with \"./\", it can be safely removed.\n second = shortenPath(second)\n // The parent path can be undefined, if the file is located in the current directory.\n if (first !== undefined) {\n // As long as \"../\" can be removed from the second path, shorten the first one.\n while (pointsToParent(second)) {\n // Remove the leading \"../\" and trim futher all leading \"./\".\n second = shortenPath(second.substring(3));\n // Cut the last directory from the first path.\n first = parentDir(first);\n // If the last part of the first path was removed and there is no parent\n // directory to go further, return the rest of the second path.\n if (first === undefined) {\n return second;\n }\n }\n // Return what remains from the first path concatenated with the second one.\n second = first + second;\n }\n return second;\n }",
"function joinPath(portion1, portion2) {\n\tlet a = [...portion1].filter(x => x.match(/[a-z0-9]/gi));\n\tlet b = [...portion2].filter(x => x.match(/[a-z0-9]/gi));\n\n\ta.push(\"/\");\n\t\n\treturn [...a, ...b].join(\"\");\n}",
"function utilDiff(orig, dest) /* diff object */ {\n\t\t/* eslint-disable id-length, max-depth */\n\t\tconst\n\t\t\tobjToString = Object.prototype.toString,\n\t\t\torigIsArray = Array.isArray(orig),\n\t\t\tkeys = []\n\t\t\t\t.concat(Object.keys(orig), Object.keys(dest))\n\t\t\t\t.sort()\n\t\t\t\t.filter((v, i, a) => i === 0 || a[i - 1] !== v),\n\t\t\tdiff = {};\n\t\tlet\n\t\t\taOpRef;\n\n\t\tconst keyIsAOpRef = key => key === aOpRef;\n\n\t\tfor (let i = 0, klen = keys.length; i < klen; ++i) {\n\t\t\tconst\n\t\t\t\tkey = keys[i],\n\t\t\t\torigP = orig[key],\n\t\t\t\tdestP = dest[key];\n\n\t\t\tif (orig.hasOwnProperty(key)) {\n\t\t\t\t// Key exists in both.\n\t\t\t\tif (dest.hasOwnProperty(key)) {\n\t\t\t\t\t// Values are exactly the same, so do nothing.\n\t\t\t\t\tif (origP === destP) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Values are of the same basic type.\n\t\t\t\t\tif (typeof origP === typeof destP) { // eslint-disable-line valid-typeof\n\t\t\t\t\t\t// Values are functions.\n\t\t\t\t\t\tif (typeof origP === 'function') {\n\t\t\t\t\t\t\t/* diff[key] = [DiffOp.Copy, destP]; */\n\t\t\t\t\t\t\tif (origP.toString() !== destP.toString()) {\n\t\t\t\t\t\t\t\tdiff[key] = [DiffOp.Copy, destP];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Values are scalars or null.\n\t\t\t\t\t\telse if (typeof origP !== 'object' || origP === null) {\n\t\t\t\t\t\t\tdiff[key] = [DiffOp.Copy, destP];\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Values are objects.\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tconst\n\t\t\t\t\t\t\t\torigPType = objToString.call(origP),\n\t\t\t\t\t\t\t\tdestPType = objToString.call(destP);\n\n\t\t\t\t\t\t\t// Values are objects of the same prototype.\n\t\t\t\t\t\t\tif (origPType === destPType) {\n\t\t\t\t\t\t\t\t// Special case: `Date` object.\n\t\t\t\t\t\t\t\tif (origPType === '[object Date]') {\n\t\t\t\t\t\t\t\t\tconst nDestP = Number(destP);\n\n\t\t\t\t\t\t\t\t\tif (Number(origP) !== nDestP) {\n\t\t\t\t\t\t\t\t\t\tdiff[key] = [DiffOp.CopyDate, nDestP];\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\t\t\t// Special case: `RegExp` object.\n\t\t\t\t\t\t\t\telse if (origPType === '[object RegExp]') {\n\t\t\t\t\t\t\t\t\tif (origP.toString() !== destP.toString()) {\n\t\t\t\t\t\t\t\t\t\tdiff[key] = [DiffOp.Copy, clone(destP)];\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\t\t\telse {\n\t\t\t\t\t\t\t\t\tconst recurse = Util.diff(origP, destP);\n\n\t\t\t\t\t\t\t\t\tif (recurse !== null) {\n\t\t\t\t\t\t\t\t\t\tdiff[key] = recurse;\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\t\t}\n\t\t\t\t\t\t\t// Values are objects of different prototypes.\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tdiff[key] = [DiffOp.Copy, clone(destP)];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// Values are of different types.\n\t\t\t\t\telse {\n\t\t\t\t\t\tdiff[key] = [\n\t\t\t\t\t\t\tDiffOp.Copy,\n\t\t\t\t\t\t\ttypeof destP !== 'object' || destP === null ? destP : clone(destP)\n\t\t\t\t\t\t];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Key only exists in orig.\n\t\t\t\telse {\n\t\t\t\t\tif (origIsArray && Util.isNumeric(key)) {\n\t\t\t\t\t\tconst nKey = Number(key);\n\n\t\t\t\t\t\tif (!aOpRef) {\n\t\t\t\t\t\t\taOpRef = '';\n\n\t\t\t\t\t\t\tdo {\n\t\t\t\t\t\t\t\taOpRef += '~';\n\t\t\t\t\t\t\t} while (keys.some(keyIsAOpRef));\n\n\t\t\t\t\t\t\tdiff[aOpRef] = [DiffOp.SpliceArray, nKey, nKey];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (nKey < diff[aOpRef][1]) {\n\t\t\t\t\t\t\tdiff[aOpRef][1] = nKey;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (nKey > diff[aOpRef][2]) {\n\t\t\t\t\t\t\tdiff[aOpRef][2] = nKey;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tdiff[key] = DiffOp.Delete;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Key only exists in dest.\n\t\t\telse {\n\t\t\t\tdiff[key] = [\n\t\t\t\t\tDiffOp.Copy,\n\t\t\t\t\ttypeof destP !== 'object' || destP === null ? destP : clone(destP)\n\t\t\t\t];\n\t\t\t}\n\t\t}\n\n\t\treturn Object.keys(diff).length > 0 ? diff : null;\n\t\t/* eslint-enable id-length, max-depth */\n\t}",
"function get_path(parent_node) {\n if (parent_node === current_room) {\n //return path\n } else {\n var parent = bfs_parents[parent_node.getName()];\n path.push(parent);\n return get_path(parent);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a 'presongs objects' promise for search result | function searchTermPromise(searchTerm){
//sends request and receives an array of presong objects
return fetch('http://localhost:4000/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({query: `query ($searchTerm: String!) {
searchFive(searchTerm: $searchTerm) {
name,
originalLink
}
}`, variables: { searchTerm }
})
})
.then(res => res.json())
.then(resObj => resObj.data.searchFive)
} | [
"singleFetch(predicates, options){\n return new Promise((resolve) => {\n this.prismic.getResults(predicates, options)\n .then((content) => resolve(content))\n .catch((error) => console.error(error));\n });\n }",
"function searchAllProducts() {\n let all_products = new Promise(function(resolve, reject) {\n setTimeout(function() {\n if(catalog.length > 0) {\n resolve(catalog);\n }\n else {\n reject(\"Catalog empty.\");\n }\n }, 1000); \n });\n\n return all_products;\n }",
"async function searchMultiple() {\n const searchInput = document.getElementById(\"searchInput\");\n let resultDiv = document.getElementById(\"resultDiv\");\n clearElementChild(resultDiv.id);\n\n const response = await makeSearchRequest(\n `http://www.omdbapi.com/?s=${searchInput.value}&apikey=b4a443f9`\n );\n latestSearchObject = response.Search;\n if (response.Response === \"True\") {\n renderSearchItems(response.Search);\n } else if (response.Response === \"False\") {\n const title = document.createElement(\"h3\");\n title.innerText = response.Error;\n resultDiv.appendChild(title);\n }\n}",
"function songSearch() {\n var spotify = new Spotify({ id: keys.apiKeys.id, secret: keys.apiKeys.secret });\n\n if (liriArgs) {\n spotify\n .search({ type: \"track\", query: liriArgs })\n .then(response => {\n var reply = response.tracks.items;\n reply.forEach(element => {\n console.log(\"=======spotify data=======\");\n console.log(\"Artist:\", element.album.artists[0].name);\n console.log(\"Song Title:\", element.name);\n console.log(\"Preview:\", element.preview_url);\n console.log(\"Album:\", element.album.name);\n console.log(\"=======spotify end=======\");\n });\n })\n .catch(err => {\n console.log(err);\n });\n } else {\n spotify\n .search({ type: \"track\", query: \"The Sign\", limit: 1 })\n .then(response => {\n var search = response.tracks.items[0];\n console.log(\"=======spotify data=======\");\n console.log(\"Artist:\", search.album.artists[0].name);\n console.log(\"Song Title:\", search.name);\n console.log(\"Preview:\", search.preview_url);\n console.log(\"Album:\", search.album.name);\n console.log(\"=======spotify end=======\");\n })\n .catch(err => {\n console.log(err);\n });\n }\n}",
"queryRemoteContent() {\n var query = this.get('query'),\n lastSearch = this.get('lastSearch') || {};\n query = query.trim();\n if (query === lastSearch.query) {\n return lastSearch.promise;\n }\n lastSearch.query = query;\n lastSearch.promise = DiagnosisRepository.search(query, this.get('requiredCodeSystems'), this.get('optionalCodeSystems'));\n this.set('lastSearch', lastSearch);\n return lastSearch.promise;\n }",
"async function fetchSong(searchTerm) {\n try {\n let token = await generateToken();\n // In options, we build the query string with the searchTerm\n const options = {\n url: 'https://api.spotify.com/v1/search',\n headers: {\n Authorization: 'Bearer ' + token\n },\n qs: { q: searchTerm, type: 'track,artist', limit: 1 },\n json: true\n };\n let result = await request.get(options);\n // Add error handling here -- if no song found return an error message\n if (result.tracks.items.length === 0) {\n return { message: 'Sorry, no tracks found' };\n }\n // Here we parse the result to return {name, songID, artist, artistID}\n let name = result.tracks.items[0].name;\n let songID = result.tracks.items[0].id;\n let artist = result.tracks.items[0].artists[0].name;\n let artistID = result.tracks.items[0].artists[0].id;\n return { name, songID, artist, artistID };\n } catch (error) {\n console.log(error);\n }\n}",
"queryRemoteContent() {\n var query = this.get('query'),\n lastSearch = this.get('lastSearch') || {};\n query = query.trim();\n if (query === lastSearch.query) {\n return lastSearch.promise;\n }\n lastSearch.query = query;\n lastSearch.promise = _diagnoses.default.search(query, this.get('requiredCodeSystems'), this.get('optionalCodeSystems'));\n this.set('lastSearch', lastSearch);\n return lastSearch.promise;\n }",
"async function findObjects(argv) {\n let body = {};\n const url = new URL(argv.url);\n url.pathname = '/api/saved_objects/_find';\n url.search = '?per_page=1000';\n for (const type of argv.types) url.search += `&type=${type}`;\n url.search;\n url.search += argv.search ? `&search=${argv.search}` : '';\n\n logger.verbose('url.search: ' + url.search);\n\n const options = {\n method: 'GET',\n headers: {\n 'kbn-xsrf': true,\n },\n };\n\n try {\n const res = await fetch(url, { ...options });\n body = await res.json();\n if (res.status === 200) {\n logger.info(\n `${res.status} ${res.statusText} Found: ${body.saved_objects.length} objects`\n );\n } else {\n logger.error(`${res.status} ${res.statusText} Error: ${body}`);\n }\n } catch (FetchError) {\n logger.error(`${FetchError.message}`);\n }\n return body.saved_objects;\n}",
"static searchProductionLines(keywords) {\n let query = ProductionLine.query();\n query.where(\"name like '%\" + keywords + \"%'\");\n query.order(\"id\", true);\n\n return new Promise( (resolve, reject) => {\n ProductionLine.exec(query).then( list => {\n resolve(list);\n }).catch(error => {\n reject(error);\n });\n });\n }",
"async function searchForListings(searchTerm) {\n let items = await itemListings.once('value')\n .then(data => data.val())\n // console.log(items)\n return allListings()\n .then(listingIDs => listingIDs.filter(\n listingID => items[listingID].blurb.toLowerCase().includes(searchTerm.toLowerCase())\n ))\n}",
"function begin_email_search(curr,num,resolve,reject) {\n var promise_list=[];\n var fullname=MTP.parse_name(curr.name);\n curr.fullname=fullname;\n var search_str,x;\n\n for(x in fullname) fullname[x]=fullname[x].toLowerCase();\n if(!fullname.mname) fullname.mname=\"\";\n /* Search for jsmith@domain.com OR smithj@domain.com, first.last@domain.com,firstlast@domain.com */\n var search_str_lst=[\"+\\\"\"+fullname.fname.charAt(0)+fullname.lname+\"@\"+my_query.domain+\"\\\"\",\n \"+\\\"\"+fullname.lname+fullname.fname.charAt(0)+\"@\"+my_query.domain+\"\\\"\",\n \"+\\\"\"+fullname.fname+\".\"+fullname.lname+\"@\"+my_query.domain+\"\\\"\",\n \"+\\\"\"+fullname.fname+fullname.lname.charAt(0)+\"@\"+my_query.domain+\"\\\"\",\n \"+\\\"\"+fullname.fname.charAt(0)+good_init(fullname.mname)+fullname.lname+\"@\"+my_query.domain+\"\\\"\",\n \"+\\\"\"+fullname.lname+fullname.fname.charAt(0)+good_init(fullname.mname)+\"@\"+my_query.domain+\"\\\"\"\n ];\n var currPromise;\n var i=0;\n function do_email_search(search_str,resolve,reject,i) {\n setTimeout(function() { query_search(search_str, resolve, reject, query_response,\"email\"); },(i*1000));\n }\n for(search_str of search_str_lst) {\n\n currPromise = new Promise((resolve, reject) => {\n console.log(\"Beginning URL search\");\n do_email_search(search_str,resolve,reject,i);\n\n });\n currPromise.then(MTP.my_then_func)\n .catch(function(val) {\n console.log(\"Failed at this emailPromise \" + val); });\n promise_list.push(currPromise);\n i++;\n }\n Promise.all(promise_list).then(function() { resolve(curr); }).catch(reject);\n\n\n\n console.log(\"new search_str=\"+search_str);\n\n }",
"function findJobs (query) {\n return Promise.cast(Job.find(query).exec());\n}",
"async function searchSong() {\n let response = await fetch('https://yt-music-api.herokuapp.com/api/yt/songs/' + input)\n let result = await response.json()\n setSongs(result.content)\n context.inputSongs = result.content\n }",
"async search(){\n let yp = await searchParameters.getYelpParams();\n let yelpReturn = await yelp.search(yp);\n if(yelpReturn.total !== 0){\n return yelpReturn;\n }\n else{\n return -1\n }\n }",
"async search() {\n if (this.#selected !== \"\") {\n this.#name.value = this.#name.value.trim();\n\n const query = {\n type: this.#selected,\n };\n\n if (this.#rarity.value !== \"\") {\n query.rarity = this.#rarity.value;\n }\n\n let result = await DataBase.search(\"armor\", query, {\n id: \"true\",\n name: \"true\",\n rarity: \"true\",\n defense: {\n base: \"true\",\n },\n \"resistances.fire\": \"true\",\n \"resistances.water\": \"true\",\n \"resistances.ice\": \"true\",\n \"resistances.thunder\": \"true\",\n \"resistances.dragon\": \"true\",\n });\n\n //Matches exist\n if (result !== undefined && result.length !== 0) {\n this.clearSearch();\n\n console.log(result);\n\n result.forEach((record) => {\n if (\n record.name.toLowerCase().includes(this.#name.value.toLowerCase())\n ) {\n let card = this.#createMiniCard(record);\n this.#result.appendChild(card);\n }\n });\n } else {\n this.#result.innerHTML = this.#createWarnCard(\"No results\");\n }\n } else {\n alert(\"Select an armor slot\");\n }\n }",
"getAllEntries() {\n //return a Promise object, which can be resolved or rejected\n return new Promise((resolve, reject) => {\n //use the find() function of the database to get the data, \n //with error first callback function, err for error, entries for data\n this.db.find({}, function(err, entries) {\n //if error occurs reject Promise\n if (err) {\n reject(err);\n //if no error resolve the promise and return the data\n } else {\n resolve(entries);\n //to see what the returned data looks like\n console.log('function all() returns: ', entries);\n }\n })\n })\n }",
"function petfinderCall() {\n var pf = new petfinder.Client({ apiKey: petfinderKey, secret: petfinderSecret });\n\n pf.animal.search({\n location: userSearch,\n type: \"dog\",\n distance: 15,\n limit: 100\n })\n .then(function (response) {\n //// Original array to pull data. \n animalsArr = response.data.animals;\n populateDogCards(animalsArr);\n })\n .catch(function (error) {\n // Handle the error\n console.log(error);\n });\n }",
"findBookingsByListing(listingId, status) {\n return new Promise((resolve, reject) => {\n //console.log(\"SERVICE err: \" + err); \n Booking.findBookingByListingId(listingId, status, (err, res) => {\n //console.log(\"SERVICE err: \" + err);\n if (err) {\n reject(err);\n } else {\n resolve(res);\n }\n });\n });\n }",
"function _searchApi(text, multi, cb) {\n\n var callback = cb || function () {};\n\n return new Promise(function (resolve, reject) {\n\n var error;\n\n if (typeof text !== 'string') {\n\n error = new Error(\"Parameter must be a string\");\n\n if (!cb) {\n reject(error);\n return;\n }\n\n return cb(error);\n\n }\n\n _search(text, multi, function (err, result) {\n\n if (err) {\n\n if (!cb) {\n reject(err);\n return;\n }\n\n return callback(err);\n\n } else {\n\n if (!cb) {\n resolve(result);\n return;\n }\n\n return callback(null, result);\n\n }\n\n });\n\n });\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes the department with matching ID; throws error if wrong type/number of arguments were provided. | async function deleteDept(deptId) {
//validates number of arguments
if (arguments.length != 1) {
throw new Error("Wrong number of arguments");
}
//validates arguments type
if (!deptId || typeof (deptId) != "string" || deptId.length == 0) {
throw "Invalid Department ID";
}
let deletedDept = await getDeptById(deptId);
const deptCollection = await dept();
const removedDept = await deptCollection.removeOne({ _id: ObjectId(deptId) });
if (!removedDept || removedDept.deletedCount == 0) {
throw "Could not remove Department";
}
return deletedDept;
} | [
"removeDepartment(departmentId) {\n return this.connection.query(\n \"DELETE FROM department WHERE id = ?\",\n departmentId\n );\n }",
"async function removeDepartment() {\n const departments = await db.findAllDepartments();\n\n const departmentChoices = departments.map(({ id, name }) => ({\n name: name,\n value: id\n }));\n\n const { departmentId } = await prompt([\n {\n type: \"list\",\n name: \"departmentId\",\n message: \"Which department do you want to remove?\",\n choices: departmentChoices\n }\n ]);\n\n await db.removeDepartment(departmentId);\n\n console.log(`Removed department from the database`);\n\n loadMainPrompts();\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}",
"async deleteAppointment(id) {\n return Appointment.destroy({where:{id}})\n }",
"deleteById(id) {\n return this.del(this.getBaseUrl() + '/' + id);\n }",
"function _deletePetById(petId){\n\t\t\tthis.errorMsg=\"\";\n\t\t\tUtilsApi.deletePetById(petId).then(\n\t\t\t\t_successCB_deletePetById.bind(this),\n\t\t\t\t_errorCB_deletePetById.bind(this)\n\t\t\t);\n\t\t}",
"delete ({ commit, getters }, { processId, portId, id }) {\n return new Promise( (resolve, reject) => {\n // Try to send data on the server.\n apiPortData.delete( processId, portId, id ).then(response => {\n // console.log(\"PortData Store, 'delete' action, API response:\")\n // console.log(response)\n\n // Update port in the Store\n commit('delete', { id, parentId: processId })\n\n resolve(response)\n }).catch(error => {\n reject(error)\n })\n })\n }",
"function deleteOne(req, res) {\n const id = req.params.applicantId;\n ApplicantModel.findByIdAndDelete(id, (err, applicant) => {\n if (err) throw err;\n if (applicant) {\n res.send({ success: true, message: 'successfully removed' });\n } else {\n res.send({ success: false, message: 'applicant does not exist' });\n }\n });\n}",
"function deleteIssue(id) {\n var url = 'http://localhost:1234/whap/issues?ID=';\n deleteData(url, id)\n .catch(rejected => {\n alert(\"Somehow ya broke it\\n\" +\n \"Don't know how but ya did\");\n });\n}",
"function deleteFlight(flightId) {\n return bookingModel\n .find({flights:flightId})\n .then(function (bookings) {\n var booking = bookings[0];\n var index = booking.flights.indexOf(flightId);\n booking.flights.splice(index, 1);\n return booking.save();\n });\n}",
"function addDepartment() {\n\tinquirer.prompt(prompt.insertDepartment).then(function (answer) {\n\t\tvar query = \"INSERT INTO department (name) VALUES ( ? )\";\n\t\tconnection.query(query, answer.department, function (err, res) {\n\t\t\tif (err) throw err;\n\t\t\tconsole.log(\n\t\t\t\t`You have added this department: ${answer.department.toUpperCase()}.`,\n\t\t\t);\n\t\t});\n\t\tconsole.log(\"\\n<<<<<<<<<<<<<<<<<<<< โ >>>>>>>>>>>>>>>>>>>>\\n\");\n\t\tviewAllDepartments();\n\t});\n}",
"function addDepartment() {\n\tinquirer.prompt(prompt.insertDepartment).then(function (answer) {\n\t\tvar query = \"INSERT INTO department (name) VALUES ( ? )\";\n\t\tconnection.query(query, answer.department, function (err, res) {\n\t\t\tif (err) throw err;\n\t\t\tconsole.log(\n\t\t\t\t`You have added this department: ${answer.department.toUpperCase()}.`,\n\t\t\t);\n\t\t});\n\t\tconsole.log(\"\\n<<<<<<<<<<<<<<<<<<<< โ >>>>>>>>>>>>>>>>>>>>\\n\");\n\t\tviewDepartments();\n\t});\n}",
"deleteGroup (id) {\n assert.equal(typeof id, 'number', 'id must be number')\n return this._apiRequest(`/group/${id}`, 'DELETE')\n }",
"function deleteFunction() {\n inquirer.prompt([{\n type: \"list\",\n message: \"Make a Selection:\",\n name: \"choice\",\n choices: [\n \"Delete Employee\",\n \"Delete Role\",\n \"Delete Department\"\n ]\n }]).then(function (event) {\n switch (event.choice) {\n case \"Delete Department\":\n deleteDepartment();\n break;\n case \"Delete Role\":\n deleteRole();\n break;\n case \"Delete Employee\":\n deleteEmployee();\n break;\n\n }\n })\n}",
"deleteOneLocation(id) {\n return db.none(`\n DELETE FROM location\n WHERE id = $1\n `, id);\n }",
"function deleteArticle(articleId) {\n firebase.firestore().collection('articles').doc(articleId).delete().then(function() {\n showAlert('Successfully deleted article');\n loadArticles();\n }).catch(function(error) {\n showAlert(error.toString());\n });\n}",
"function deleteExpense(id) {\n console.log(\"DELETE BUTTON WORKS\");\n }",
"function getDepartmentId(departments, departmentName) {\n for (let i=0; i<departments.length; i++) {\n if (departments[i].name === departmentName) {\n return departments[i].id;\n };\n };\n }",
"function deleteTipoProducto(req, res){\n \n const id = req.params.id;\n console.log(id)\n ModelTipoProducto.findByIdAndRemove( id, (err, doctipoProducto) => {\n\n if( err || !doctipoProducto ) return errorHandler(doctipoProducto, next, err)\n\n return res.json({\n data: doctipoProducto\n })\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
lets creat a pet from a function, name, species, behaviour | function createPet(name, species, well_behaved) {
return {name, species, well_behaved};
} | [
"function Pet(petName,age,adopted,markings,breed){\n this.petName = petName;\n this.age = age;\n this.adopted = adopted;\n this.markings = markings;\n this.breed = breed;\n}",
"function petInfo (pet) {\n\tconsole.log([name] + \" is a \" + [age] + \"-year-old, \" + [gender] + \" \" + [species] + \".\");\n}",
"function dogFactory(name, gender) {\n // some other code here\n\n return {\n name: name,\n gender: gender,\n nameAndGender: function () {\n return `${name} : ${gender}`;\n },\n };\n}",
"function createAnimal(species, noiseVerb, noiseNoun){\n return{\n species,\n [noiseVerb](){\n return `The ${[species]} says ${[noiseNoun]}.`\n }\n }\n }",
"function petInfo(pet) {\n\tif (age>=10) {\n\t\tconsole.log([name] + \" is a \" + [age] + \"-year-old, \" + [gender] + \" \" + [species] + \".\" + \" Pet's age indicates need for special nutrition. Recommend food for older animals and check for rabies shots.\");\n\t}\n\telse if (age<2) {\n\t\tconsole.log([name] + \" is a \" + [age] + \"-year-old, \" + [gender] + \" \" + [species] + \".\" + \" Pet's age indicates risk of not having had any shots. Ask about pet's shot history.\");\n\t}\n\telse if (age>2 && age<9) {\n\t\tconsole.log([name] + \" is a \" + [age] + \"-year-old, \" + [gender] + \" \" + [species] + \".\" + \" Check status of rabies shots.\")\n\t};\n\n\n\n}",
"function pet() {\n alert('Thanks for giving Wanda pets!');\n }",
"function makeAnimal(species,verb,sound) {\n let animal = {\n species,\n [verb](){\n return sound;\n }\n }\n return animal; \n}",
"function makePizza(crust,size,numberOfSlice,ingredient){\n return{\n ing :ingredient,\n nos : numberOfSlice , \n addIngredients:function(ingredient){\n return ing++;\n },\n displayIngredients:function(){\n return \"the ingredientsare :\" + \" \" + ingredient;\n },\n bakePizza:function(){\n return \"your\" + \" \" + crust + \" \" + size + \" \" + numberOfSlice + \" \" + \"slice pizza is done\" ;\n },\n eatSlice:function(numberOfSlice){\n if(numberOfSlice === 0){\n return \"you done eating\";\n }\n if(numberOfSlice > 0){\n return \"you can eat from those slices\"\n }\n nos--;\n }\n }\n\n}",
"function getNewCreature() {\n let newCreature = null;\n\n let randNum = int(random(0, 6));\n if (randNum < 2) {\n\n //shades of blue color array\n let colors = [\"darkCyan\", \"darkSlateBlue\", \"lightSteelBlue\", \"midnightBlue\", \"royalBlue\", \"steelBlue\"];\n let index = floor(random(colors.length));\n let color = colors[index];\n\n newCreature = new Spike(color); //instance of Triangle class\n }\n else if (randNum < 3) {\n //offwhite colors\n let colors = [\"aliceBlue\", \"azure\", \"cornsilk\", \"floralWhite\", \"honeyDew\", \"ivory\"];\n let index = floor(random(colors.length));\n let color = colors[index];\n newCreature = new Butterfly(color); //instance of Butterfly class\n }\n else if (randNum < 5) {\n //shades of pink/purple\n let colors = [\"paleVioletRed\", \"pink\", \"plum\", \"rosyBrown\", \"salmon\", \"thistle\"];\n let index = floor(random(colors.length));\n let color = colors[index];\n newCreature = new Orb(color); //instance of Orb class\n }\n else {\n //shades of green color array\n let colors = [\"forestGreen\", \"green\", \"greenYellow\", \"lawnGreen\", \"lightGreen\", \"lime\"];\n let index = floor(random(colors.length));\n let color = colors[index];\n\n newCreature = new Creature(color); //instance of Creature class\n }\n return newCreature;\n}",
"function createPokemon(_id, name, classification, type1, type2, hp, attack, defense, speed, sp_attack, sp_defense){\n return {\n \"_id\": _id,\n \"name\": name,\n \"classification\": classification,\n \"type1\": type1,\n \"type2\": type2,\n \"stats\": {\n \"hp\": hp,\n \"attack\": attack,\n \"defense\": defense,\n \"speed\": speed,\n \"sp_attack\": sp_attack,\n \"sp_defense\": sp_defense\n }\n }\n\n}",
"addSpecies() {\n let name = prompt('Enter name for the new species listing:');\n this.animalSpecies.push(new Species(name));\n let petName = prompt('What is the name of the animal?');\n let breed = prompt('What is the breed of the animal?');\n let age = prompt('What is the animals age in years?');\n let sex = prompt('Is the animal male or female?');\n this.animalSpecies[this.animalSpecies.length - 1].pets.push(new Pet(petName, breed, age, sex));\n }",
"spawnFruit(x,y,velX,velY) {\r\n let random = Phaser.Math.Between(0, 9);\r\n let spawnPointX = x;\r\n let spawnPointY = y;\r\n let fruit = this.physics.add.sprite(spawnPointX, spawnPointY, 'fruit' + random).setInteractive();\r\n fruit.name = 'fruit';\r\n fruit.setScale(Phaser.Math.Between(2.0, 3.0));\r\n fruit.body.setVelocityX(Phaser.Math.Between(-velX + 500, -velX - 500));\r\n fruit.body.setVelocityY(Phaser.Math.Between(-velY + 500, -velY - 500));\r\n }",
"function createEgg() {\n startMoving(new egg);\n}",
"function getPets(){\n shelterFinder();\n}",
"function practice(ninja, weapon, technique) {}",
"function playerCreature() {}",
"function generateRandomAnimal() {\n // random index to choose animal type\n var animalIndex = generateRandomIndex(animals.length);\n // get a random animal\n var animal = animals[animalIndex];\n // identify and create animal\n if (animal instanceof PolarBear) return new PolarBear(generateRandomName(), generateRandomAge());\n else if (animal instanceof Lion) return new Lion(generateRandomName(), generateRandomAge());\n else return new Rabbit(generateRandomName(), generateRandomAge());\n}",
"function add_grouped(entity_name) {\n var variance_mapping = {\n 'bubble': 100,\n 'jellyfish': 250\n };\n var spawn_mapping = {\n 'bubble': add_bubble,\n 'jellyfish': add_jellyfish\n }\n var max_mapping = {\n 'bubble': 50,\n 'jellyfish': 20\n }\n\n var x_coord = Math.floor(Math.random() * game.world.width);\n var y_coord = 0;\n var n = Math.floor(4 + (Math.random() * max_mapping[entity_name]));\n\n for (var i = 0; i < n; i++) {\n var pos_neg = Math.random() <= 0.5 ? -1 : 1;\n var x_variance = pos_neg * Math.random() * variance_mapping[entity_name];\n var y_variance = -1 * Math.random() * variance_mapping[entity_name];\n\n spawn_mapping[entity_name](\n x_coord + x_variance, y_coord + y_variance);\n }\n}",
"function makeName() {\n let prefixArr = [];\n let suffixArr = [];\n let name;\n\n if (mySpecies.length < 1) return; // Don't make a name if there are no traits\n // Populate the prefix and suffix arrays\n for ( let i = 0; i < mySpecies.length; i ++ ) {\n for ( let j = 0; j < mySpecies[i].prefixes.length; j ++ ) {\n prefixArr.push(mySpecies[i].prefixes[j]);\n }\n for ( let k = 0; k < mySpecies[i].suffixes.length; k ++ ) {\n suffixArr.push(mySpecies[i].suffixes[k]);\n }\n }\n // Get random values from the prefix and suffix arrays\n let pre1 = getRandom(prefixArr);\n let pre2;\n let suf = getRandom(suffixArr);\n if (mySpecies.length <= 2) {\n name = pre1 + suf;\n } else {\n let pre2 = getRandom(prefixArr);\n // Ensure unique prefixes\n while ( pre2 == pre1 ) {\n pre2 = getRandom(prefixArr);\n }\n name = pre1 + pre2 + suf;\n }\n name = name.charAt(0).toUpperCase() + name.slice(1);\n document.getElementById(\"name\").innerHTML = name;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ENHC0051710:Setting HTC Reviewer(AP Clerk Offshore) Value based on the subsidiary of the vendor selected | function setHTCReviewer(vbRec,vbSubs,vbOwner,k) {
var f3 = new Array();
f3[0] = new nlobjSearchFilter('custrecord_spk_sr_ap_clerk_subsidiary',null,'anyof',vbSubs);
f3[1] = new nlobjSearchFilter('isinactive',null,'is','F');
var col3 = new Array();
col3[0] = new nlobjSearchColumn('custrecord_spk_senior_apclerk_field');
var searchResult = nlapiSearchRecord('customrecord_spk_sr_ap_clerk_offshore',null,f3,col3);
if(searchResult) {
var htcReviewerRec = searchResult[0];
var htcReviewer = htcReviewerRec.getValue('custrecord_spk_senior_apclerk_field');
var delegate_htcReviewer = getDelegateApprover(htcReviewer);
nlapiLogExecution('DEBUG', 'HTC Reviewer', delegate_htcReviewer);
vbRec.selectNewLineItem('recmachcustrecord_spk_apvmtx_tranno');
vbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_seq', k);
if(delegate_htcReviewer) {
vbRec.setFieldValue('custbody_spk_inv_apvr',delegate_htcReviewer);
vbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr',delegate_htcReviewer);
vbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_delgtof',htcReviewer);
}
else {
var apclerk = vbRec.setFieldValue('custbody_spk_inv_apvr',htcReviewer);
nlapiLogExecution('DEBUG', 'apclerk', apclerk);
vbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr', htcReviewer);
}
vbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvrl','HTC Reviewer');
vbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apmanager',nlapiGetUser());
vbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_invown',vbOwner);
vbRec.commitLineItem('recmachcustrecord_spk_apvmtx_tranno');
}
} | [
"function SetAPClerk(vbRec,vbSubs,vbOwner,k) {\t\t\t\n\tvar f3 = new Array();\n\tf3[0] = new nlobjSearchFilter('custrecord_spk_sr_ap_clerk_ons_sub',null,'anyof',vbSubs);\n\tf3[1] = new nlobjSearchFilter('isinactive',null,'is','F');\t\t\t\t\t\n\tvar col3 = new Array();\n\tcol3[0] = new nlobjSearchColumn('custrecord_spk_sr_ap_clerk_onshore_field');\n\tvar searchResult = nlapiSearchRecord('customrecord_spk_sr_ap_clerk_onshore',null,f3,col3);\n\tif(searchResult) {\n\t\tvar apclerkOnshoreRec = searchResult[0];\n\t\tvar apclerkOnshore = apclerkOnshoreRec.getValue('custrecord_spk_sr_ap_clerk_onshore_field');\n\t\tvar delegate_apclerkonshore = getDelegateApprover(apclerkOnshore);\n\t\tnlapiLogExecution('DEBUG', 'apClerkOnshore', delegate_apclerkonshore);\n\t\tvbRec.selectNewLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_seq', k);\n\t\tif(delegate_apclerkonshore) {\n\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr',delegate_apclerkonshore);\n\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_delgtof',apclerkOnshore);\n\t\t}\n\t\telse {\n\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr', apclerkOnshore);\n\t\t}\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvrl','Sr. AP Clerk');\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apmanager',nlapiGetUser());\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_invown',vbOwner);\n\t\tvbRec.commitLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t}\n}",
"function SetAPManager(vbRec,vbSubs,vbOwner,k) {\t\t\t\n\tvar f3 = new Array();\n\tf3[0] = new nlobjSearchFilter('custrecord_spk_apm_sub',null,'anyof',vbSubs);\n\tf3[1] = new nlobjSearchFilter('isinactive',null,'is','F');\t\t\t\t\t\n\tvar col3 = new Array();\n\tcol3[0] = new nlobjSearchColumn('custrecord_spk_apm_apv');\n\tvar searchResult = nlapiSearchRecord('customrecord_spk_apm_approver',null,f3,col3);\n\tif(searchResult) {\n\t\tvar managerRec = searchResult[0];\n\t\tvar apmanager = managerRec.getValue('custrecord_spk_apm_apv');\n\t\tvar delegate_apmanager = getDelegateApprover(apmanager);\n\t\tvbRec.selectNewLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_seq', k);\n k=k+1;\n\t\tif(delegate_apmanager) {\n\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr',delegate_apmanager);\n\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_delgtof',apmanager);\n\t\t}\n\t\telse {\n\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr', apmanager);\n\t\t}\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvrl','AP Manager');\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apmanager',nlapiGetUser());\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_invown',vbOwner);\n\t\tvbRec.commitLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t}\n return k;\n}",
"function _updateLicense() {\n\t\tvar s = _shareSettings.sharing;\n\t\tvar a = _shareSettings.adaptations;\n\t\tvar c = _shareSettings.commercial;\n\n\t\tif (s == 'cc0' || s == 'reserved') {\n\t\t\t_license = s;\n\t\t} else\n\t\t{\n\t\t\t_license = 'cc-by';\n\t\t\tif (c == 'no') {\n\t\t\t\t_license += '-nc';\n\t\t\t}\n\t\t\tif (a == 'no') {\n\t\t\t\t_license += '-nd';\n\t\t\t} else\n\t\t\tif (a == 'sharealike') {\n\t\t\t\t_license += '-sa';\n\t\t\t}\n\t\t}\n\t\t_updateLicenseSummary();\n\t}",
"function postEditCommodityAPI() {\n var msg = callAPI(uRL + '/' + idManufacturer, \"GET\");\n if(msg)\n {\n $('#manufacturer-id').val(msg['tradeId']);\n $('#manufacturer-name').val(msg['companyName']);\n $('#manufacturer-address').val(msg['address']['street']);\n }\n else\n {\n alert(\"Khรดng lแบฅy ฤฦฐแปฃc dแปฏ liแปu tแปซ hแป thแปng!\");\n }\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}",
"static measurementDocumentCreateUpdateSetODataValue(pageClientAPI, key) {\n let binding = pageClientAPI.binding;\n let currentDateTime = libCom.getStateVariable(pageClientAPI, 'CurrentDateTime') || new Date();\n let odataDate = new ODataDate(currentDateTime);\n if (binding['@odata.type'] === '#sap_mobile.MyWorkOrderTool') {\n binding = binding.PRTPoint;\n }\n\n //Only create will be supported for now. SB and HCP SDK cannot support local updates merging into the create.\n //This means that we cannot allow local updates (edits) on a measurement document\n switch (key) {\n case 'RecordedValue':\n return String(libCom.getFieldValue(pageClientAPI, 'ReadingSim', '', null, true));\n case 'ReadingValue': {\n let readingValue = libCom.getFieldValue(pageClientAPI, 'ReadingSim', '', null, true);\n // if readingValue contains \",\" only then the type would be string, otherwise would be number\n if (typeof(readingValue) === 'string' && libCom.isDefined(readingValue)) {\n return libLocal.toNumber(pageClientAPI, readingValue);\n } else {\n if (libCom.isDefined(readingValue)) {\n return readingValue;\n } else {\n return 0;\n }\n }\n }\n case 'ReadingTime':\n return odataDate.toDBTimeString(pageClientAPI);\n case 'ReadingDate':\n return odataDate.toDBDateString(pageClientAPI);\n case 'MeasurementDocNum':\n return libCom.GenerateOfflineEntityId();\n case 'ValuationCode':\n return libCom.getListPickerValue(libCom.getFieldValue(pageClientAPI, 'ValuationCodeLstPkr', '', null, true));\n case 'CodeDescription':\n return pageClientAPI.read(\n '/SAPAssetManager/Services/AssetManager.service',\n \"PMCatalogCodes(Catalog='\"+ binding.CatalogType+\"',Code='\"+ libCom.getListPickerValue(libCom.getFieldValue(pageClientAPI, 'ValuationCodeLstPkr', '', null, true)) +\"',CodeGroup='\"+ binding.CodeGroup + \"')\",\n [],'').then(result2 => {\n if (result2.length > 0) {\n //Grab the first row (should only ever be one row)\n let row = result2.getItem(0);\n let codeDescription = row.CodeDescription;\n return codeDescription;\n }\n return '';\n }).catch((error) => {\n Logger.error('measurementDocumentCreateUpdateSetODataValue', error);\n return '';\n });\n case 'ReadBy':\n return libCom.getSapUserName(pageClientAPI);\n case 'ShortTextNote':\n return libCom.getFieldValue(pageClientAPI, 'ShortTextNote', '', null, true);\n case 'CodeGroup':\n if (binding.hasOwnProperty('CodeGroup')) {\n return binding.CodeGroup;\n } else {\n return binding.MeasuringPoint.CodeGroup;\n }\n case 'HasReadingValue':\n return (libVal.evalIsEmpty(libCom.getFieldValue(pageClientAPI, 'ReadingSim', '', null, true))) ? '' : 'X';\n case 'ReadingTimestamp':\n {\n return odataDate.toDBDateTimeString(pageClientAPI);\n }\n case 'UOM':\n {\n if (binding.hasOwnProperty('RangeUOM')) {\n return binding.RangeUOM;\n } else if (binding.hasOwnProperty('MeasuringPoint') && binding.MeasuringPoint.hasOwnProperty('RangeUOM')) {\n return binding.MeasuringPoint.RangeUOM;\n } else {\n return '';\n }\n }\n default:\n return '';\n }\n }",
"set PhonePad(value) {}",
"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 recommenderSensitivityValueListener() {\n var recommenderSensitivity = document.getElementById(\"recommenderSensitivity\");\n recommenderSensitivity.addEventListener(\"input\", function() {\n var newVal = recommenderSensitivity.value;\n chrome.storage.local.get(function(storage) {\n var cachedSettings = storage[\"cachedSettings\"];\n var oldSettings = storage[\"settings\"];\n if (!cachedSettings) {\n if (!oldSettings) {\n // Use default settings\n oldSettings = initialSettings;\n }\n cachedSettings = oldSettings;\n }\n\n cachedSettings[\"recommenderSensitivity\"] = newVal;\n var recommenderSensitivityVal = document.getElementById(\"recommenderSensitivityVal\");\n recommenderSensitivityVal.innerHTML = newVal;\n chrome.storage.local.set({ \"cachedSettings\": cachedSettings });\n });\n });\n}",
"function update_entityuse_codes() {\n //create an object with all unique customers \n nlapiLogExecution('AUDIT', ' -,-,- update entity/use codes -,-,- ');\n var array_of_customers = [];\n // var filters = [];\n // var columns = [\n // new nlobjSearchColumn('internalid')\n // ];\n // //run SuiteScript function to grab all customer ids and put them into an array\n // var customerSearch = nlapiCreateSearch('customer', filters, columns);\n // var result_set = customerSearch.runSearch();\n array_of_customers = nlapiSearchRecord(\"customer\", null,\n [\n [\"internalidnumber\", \"equalto\", \"894942\"],\n \"OR\",\n [\"internalidnumber\", \"equalto\", \"895145\"],\n \"OR\",\n [\"internalidnumber\", \"equalto\", \"895144\"]\n ],\n [\n new nlobjSearchColumn(\"entityid\").setSort(false)\n ]\n );\n // array_of_customers = getAllResults(result_set);\n checkGovernance(max_governance, 'Create Array of Customers', 0, array_of_customers.length);\n //run SuiteScript function to loop through customer ids, check if stage is equal to lead, prospect, then setting new entity fields\n for (var i = 0; i < array_of_customers.length; i++) {\n checkGovernance(max_governance, 'Set Entity/Use Code for Customer', i, array_of_customers.length);\n set_entityuse_code(array_of_customers[i].id, i, array_of_customers.length);\n }\n}",
"function change_product_supplier_settings(product_id)\n{\n\twhile(order_list[product_id].supplier_settings.length>0){order_list[product_id].supplier_settings.pop()};\n\torder_list[product_id].supplier_settings = {};\n\t//get information from checkmark and supplier id and premium values from HTML\n\t$.each(suppliers_list, function (supplier_id, supplier_details)\n\t{\n\t\tif(typeof(supplier_details)!='undefined')\n\t\t{\n\t\t\tvar supplier_checkbox = \"supsettings_\"+supplier_id+\"_\"+product_id;\n\t\t\tvar premium_input_name = \"supsetting_premium_\"+supplier_id+\"_\"+product_id;\n\t\t\tif ($(\"#\"+supplier_checkbox).prop(\"checked\"))\n\t\t\t{\n\t\t\t\torder_list[product_id].supplier_settings[supplier_id]={};\n\t\t\t\torder_list[product_id].supplier_settings[supplier_id].name = suppliers_list[supplier_id].name;\n\t\t\t\torder_list[product_id].supplier_settings[supplier_id].premium = $(\"#\"+premium_input_name).val();\n\t\t\t}\t\t\t\n\t\t}\n\t});\n\t//To find recommend supplier and then redraw complete order list\n\tfind_recommended_supplier(product_id)\n\t//\n\thide_product_supplier_settings();\n\t//redraw order list\n\tredraw_order_list();\n}",
"function getAlertCarrier(mobilecarrierIntParam) {\n if (mobilecarrierIntParam == 1) {\n mobilecarrier = \"T-Mobile\";\n } else if (mobilecarrierIntParam == 2) {\n mobilecarrier = \"AT&T\";\n } else if (mobilecarrierIntParam == 3) {\n mobilecarrier = \"VERIZON\";\n }\n alert('You are a '+mobilecarrier+' user!');\n}",
"set deviceName(value) {}",
"function industryCodeChange() {\n try {\n var code = Xrm.Page.getAttribute(\"industrycode\").getValue();\n alert(code);\n }\n catch (_a) {\n }\n }",
"set probeDensity(value) {}",
"function device_information(id)\n{\n document.getElementById(id).innerHTML = \"MODEL = \"+device.model;\n}",
"function getPatientInfo(qr) {\n setQr(qr);\n alert(\"The patient: \" + qr + \" has been scanned and added into the system\");\n }",
"set NamePhonePad(value) {}",
"function show_supplier_selector(product_id)\n{\n\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Counts the column offset in a string, taking tabs into account. Used mostly to find indentation. | function countColumn(string, end, tabSize) {
if (end == null) {
end = string.search(/[^\s\u00a0]/);
if (end == -1) end = string.length;
}
for (var i = 0, n = 0; i < end; ++i) {
if (string.charAt(i) == "\t") n += tabSize - (n % tabSize);
else ++n;
}
return n;
} | [
"indentation() {\n var _a\n return (_a = this.overrideIndent) !== null && _a !== void 0\n ? _a\n : countCol(this.string, null, this.tabSize)\n }",
"function countPreviousSpaces(str, pos) {\r\n var spaces = 0;\r\n // check the characters before the pos one at a time, break when a nonspace char is found\r\n while(pos > spaces && /\\s/.test(str.charAt(pos-1-spaces) ) ){\r\n spaces++; // if space, increment spaces count\r\n }\r\n return spaces; // return spaces\r\n}",
"get indentUnit() {\n let unit = this.facet(dist_EditorState.indentUnit);\n return unit.charCodeAt(0) == 9 ? this.tabSize * unit.length : unit.length;\n }",
"get indentUnit() {\n let unit = this.facet(EditorState.indentUnit);\n return unit.charCodeAt(0) == 9 ? this.tabSize * unit.length : unit.length;\n }",
"lineIndent(line) {\n var _a;\n let override = (_a = this.options) === null || _a === void 0 ? void 0 : _a.overrideIndentation;\n if (override) {\n let overriden = override(line.from);\n if (overriden > -1)\n return overriden;\n }\n let text = line.slice(0, Math.min(100, line.length));\n return this.countColumn(text, text.search(/\\S/));\n }",
"function getIndentUnit(state) {\n let unit = state.facet(indentUnit)\n return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length\n }",
"function lineColPositionFromOffset(offset, lineBreaks) {\n let line = remix_lib_1.util.findLowerBound(offset, lineBreaks);\n\n if (lineBreaks[line] !== offset) {\n line += 1;\n }\n\n const beginColumn = line === 0 ? 0 : lineBreaks[line - 1] + 1;\n return {\n line: line + 1,\n character: offset - beginColumn + 1\n };\n}",
"indentString(cols) {\n let result = \"\";\n if (this.facet(EditorState.indentUnit).charCodeAt(0) == 9)\n while (cols >= this.tabSize) {\n result += \"\\t\";\n cols -= this.tabSize;\n }\n for (let i = 0; i < cols; i++)\n result += \" \";\n return result;\n }",
"indentString(cols) {\n let result = \"\";\n if (this.facet(dist_EditorState.indentUnit).charCodeAt(0) == 9)\n while (cols >= this.tabSize) {\n result += \"\\t\";\n cols -= this.tabSize;\n }\n for (let i = 0; i < cols; i++)\n result += \" \";\n return result;\n }",
"function getOffset() {\n var indentation = [];\n var pos = line + 1;\n\n /* Done. Called when the last character is\n * eaten to retrieve the rangeโs offsets. */\n return function () {\n var last = line + 1;\n\n while (pos < last) {\n indentation.push((offset[pos] || 0) + 1);\n\n pos++;\n }\n\n return indentation;\n };\n }",
"function getColorableCount(text) {\n let colorableCount = 0;\n for (let i = 0; i < text.length; i++) {\n if (text[i] == '\\u001B') {\n do {\n i++;\n } while (text[i] != 'm');\n i++;\n }\n colorableCount++;\n }\n return colorableCount;\n}",
"function lengthWord(s){\n if(s.length === 0) return 0;\n var startCount = s[s.length-1] === ' ' ? false : true;\n var count = 0;\n for(var i = s.length-1; i>=0; i--){\n if(s[i] === ' '){\n if(startCount){\n return count;\n }\n }else{\n if(!startCount){\n startCount = true;\n }\n startCount && count++\n }\n\n }\n\n return count;\n}",
"function headerDelimiterPos(inputRem) {\n const patt = /-{3}/;\n const endHeader = inputRem.search(patt);\n// if (endHeader === -1) {\n // TODO: raise an error\n// }\n return endHeader;\n}",
"function getTextWrapping (text, maxWidth) {\n const {cells} = text;\n const lineStartCols = [0];\n let col = 0;\n let lastNonAlphabet = maxWidth - 1;\n let lastNonAlphabetBeforeLetter = 0;\n for (let iCell = 0; iCell < cells.length; iCell++) {\n if (col >= maxWidth) {\n const startCol = lastNonAlphabetBeforeLetter + 1;\n lineStartCols.push(startCol);\n lastNonAlphabet = lineStartCols.length * maxWidth - 1;\n col = iCell - startCol;\n }\n const cell = cells[iCell];\n if ('rank' in cell) {\n lastNonAlphabetBeforeLetter = lastNonAlphabet;\n } else {\n lastNonAlphabet = iCell;\n }\n col++;\n }\n lineStartCols.push(cells.length);\n return lineStartCols;\n}",
"function getCorrectPoints(s) {\n var i;\n var count = 0;\n for (i = 0; i < s.length; i++) {\n if (s.charAt(i) == 'C') {\n count++;\n }\n }\n return count;\n}",
"function charCount(txt){\n return txt.length;\n}",
"function countCode(str) {\n output = 0\n for (let i = 0; i < str.length; i++) {\n if (str.substring(i, i + 2) === \"co\" && str[i+3] === \"e\") {\n output++;\n }\n }\n return output\n}",
"function locate_line(elt) {\n var found\n var initlen = elt.textContent.length\n var textlen = 0\n var count = 10000\n var wentup = false\n\n while (count > 0 && elt) {\n count = count - 1\n // console.log(\"at\", elt)\n if (elt.nodeType == 3) {\n textlen += textContentLength(elt)\n } else if (found = atLineStart(elt)) {\n break;\n } else if (!wentup) {\n textlen += textContentLength(elt)\n }\n wentup = false\n var next = elt.previousSibling\n if (!next) {\n next = elt.parentNode\n wentup = true\n if (!next || next == elt) {\n break\n }\n }\n elt = next\n }\n if (found) {\n var minCol = textlen - initlen + 1\n var maxCol = textlen + 1\n return [found, minCol, maxCol, elt]\n } else {\n return\n }\n}",
"buildHighlightPosition (position, linenum, text) {\n var remainingCharacters = position;\n let lines = text.split(\"\\n\");\n\n // Iterate until we get to the position of the character we need, and then build\n // a relative vscode.Position.\n for (var i = 0; i < lines.length; i++) {\n let charactersInLine = lines[i].length + 1; // +1 for the newline.\n\n if (remainingCharacters - charactersInLine < 0) {\n return new vscode.Position(linenum - 1, remainingCharacters);\n }\n\n remainingCharacters = remainingCharacters - charactersInLine;\n }\n\n // If we get here, there's probaly a buffer mismatch.\n return undefined;\n }",
"getLineNumber() {\r\n const sourceFile = this.getSourceFile();\r\n const start = this.getStart();\r\n if (sourceFile == null || start == null)\r\n return undefined;\r\n return utils_1.StringUtils.getLineNumberAtPos(sourceFile.getFullText(), start);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return true if the specified `filePath` is contained in `relativePath` and false otherwise. | function inRelativePath(filePath) {
return filePath.startsWith(withSlash);
} | [
"function isInSrcDir(_filepath){\n var filepathRelativeToSrcDir = path.relative( srcDir, path.resolve(config.base,_filepath) );\n if( filepathRelativeToSrcDir.substr(0,2) !== '..' ) { // file is in srcDir\n return filepathRelativeToSrcDir;\n }\n return false;\n }",
"function fileExistInNpm(filePath) {\n return existsSync(path.resolve(__dirname, '../../', filePath));\n}",
"function addPath(filePath) {\n if (relativePath) {\n if (inRelativePath(filePath)) {\n const relative = path.relative(relativePath, filePath);\n result.push(relative);\n }\n }\n else {\n result.push(filePath);\n }\n }",
"isScriptFile(filePath) {\n return ['.js', '.json'].includes(path_1.extname(filePath));\n }",
"function relativePath(dirPath, filePath) {\n return filePath.replace(dirPath, \"\")\n}",
"function exists(file) {\n\treturn fs.existsSync(file) && file;\n}",
"fileExists() {\n return fs.pathExists(this.location);\n }",
"function fileInDirectory(a, b) {\n return path.dirname(a).toLowerCase() === b.toLowerCase();\n}",
"function addIfUnique( filePath, Paths ){\n\tif( Paths.indexOf( filePath ) === -1 ){\n\t\tPaths.push( filePath );\n\t}\n}",
"function isAbsolute(path) {\n return __WEBPACK_IMPORTED_MODULE_0__platform_js__[\"g\" /* isWindows */] ?\n isAbsolute_win32(path) :\n isAbsolute_posix(path);\n}",
"hasLoadedDataFile(fileName) {\n return this.loadedDataFiles.indexOf(fileName) >= 0;\n }",
"relative(path, ancestor) {\n if (!Path.isAncestor(ancestor, path) && !Path.equals(path, ancestor)) {\n throw new Error(\"Cannot get the relative path of [\".concat(path, \"] inside ancestor [\").concat(ancestor, \"], because it is not above or equal to the path.\"));\n }\n\n return path.slice(ancestor.length);\n }",
"function walkIfUnique( start, end, Paths, Ancestors ){\n\tvar index;\n\n\tif( Paths.indexOf( path.normalize(path.resolve(start + '/' + end)) ) >= 0 ){\n\t\treturn false;\n\t}\n\t\n\tindex = Ancestors.Starts.indexOf( start );\n\tif( index === -1 ){\n\t\tAncestors.Starts.push( start );\n\t\tAncestors.Ends.push( [end] );\n\t}\n\telse{\n\t\tif( Ancestors.Ends[index].indexOf( end ) >= 0 ){\n\t\t\treturn false;\n\t\t}\n\t\tAncestors.Ends[index].push( end );\n\t}\n\t\n\t//Store the start string as the 'Base' if there is not already a base\n\tif( !Ancestors.Base ) Ancestors.Base = start;\n\t\n\treturn true;\n}",
"checkFilenameExists(fileName){\n\n\t\tvar nodeIds = this.tree.get_node(this.workingDirectoryNode).children;\t\n\n\t\tfor (let i = 0; i < nodeIds.length; i++){\n\n\t\t\tvar child = this.tree.get_node({id: nodeIds[i] });\n\n\t\t\tif ( (child.data.name + child.data.ext) === fileName){\n\t\t\t\treturn child;\n\t\t\t}\n\n\t\t}\n\n\t}",
"function exploreDir (filePath) {\n fs.readdirSync(filePath).forEach(fileOrFolder => {\n const fileOrFolderPath = path.join(filePath, fileOrFolder)\n const stats = fs.statSync(fileOrFolderPath)\n if (stats.isDirectory()) {\n exploreDir(fileOrFolderPath)\n } else if (fileOrFolder.indexOf('.js') > -1) {\n analyzeFile(fileOrFolderPath)\n }\n })\n}",
"isDirExists() {\t\n\t\ttry\t{\n\t\t\tfs.statSync(this.options.dir);\n\t\t} catch(e) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}",
"async loadAsset(relativePath, file) {\n return VRSPACEUI.assetLoader.loadAsset(this.assetPath(relativePath)+file);\n }",
"isValid() {\n try {\n fs.accessSync(CONFIG_FILE_PATH, fs.constants.R_OK | fs.constants.W_OK);\n return true;\n } catch (err) {\n return false;\n }\n }",
"function expand(filePath, requiredFiles) {\n requiredFiles = requiredFiles || {};\n\n if(requiredFiles[filePath]) {\n this.lineConcat.add(filePath, '', null, 0);\n return;\n } // just return if already required\n\n requiredFiles[filePath] = true;\n\n var lines = String(fs.readFileSync(filePath)).split(/\\n/);\n\n lines.forEach(function(line, index) {\n var match = line.match(DIRECTIVE_REGEX);\n\n if(match) {\n var dirFiles = getFiles(filePath, match);\n\n dirFiles.forEach(function(dirFile) {\n expand(dirFile, requiredFiles);\n });\n }\n else {\n this.lineConcat.add(filePath, line, null, index);\n }\n });\n this.lineConcat.add(filePath, '', null, lines.length);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns number of followers after going through all pages | async function getFollowers(login) {
let response = 0;
let followers = 0;
let page = 1;
let done = false;
while (done === false) {
response = await fetch(githubFollowers(login, page))
.then(res => res.json())
.then(json => {
return json.length;
});
followers += response;
response < 100 ? (done = true) : page++;
}
return followers;
} | [
"async function getFollowing(login) {\n let response = 0;\n let following = 0;\n let page = 1;\n let done = false;\n while (done === false) {\n response = await fetch(githubFollowing(login, page))\n .then(res => res.json())\n .then(json => {\n return json.length;\n });\n following += response;\n response < 100 ? done = true : page++;\n }\n return following;\n}",
"function printReach(){\n for (var user in data){\n var second = 0;\n var followers = followingMe(user);\n console.log(`${data[user].name} has ${followers.length} followers`);\n followers.forEach(function(x){\n var followerObject = data[x];\n second += followingMe(x).length;\n });\n console.log(`And ${second} followers of followers.`);\n }\n}",
"function reach(){\n for(var person in data){\n var reachText = \"\";\n var numOfFollowers = 0;\n reachText += data[person].name + \"'s reach is: \";\n var followersArray = getFollowers(person);\n numOfFollowers += followersArray.length;\n followersArray.forEach(function(follower){\n numOfFollowers += getFollowersArray(follower).length;\n });\n reachText += numOfFollowers;\n console.log(reachText);\n }\n}",
"function mostFollowers(){\n var mostFollowersPersonId = 0;\n var maxNumFollowers = 0;\n for(var person in data){\n var followersNumber = getFollowers(person).length;\n if(maxNumFollowers <= followersNumber){\n maxNumFollowers = followersNumber;\n mostFollowersPersonId = person;\n }\n }\n console.log(\"The person with most followers is: \" + data[mostFollowersPersonId].name);\n\n}",
"function followers(){\n for(var person in data){\n var followersString = \"\";\n followersString += data[person].name + \" follows \";\n data[person].follows.forEach(function(follower, index, followers){\n if(index === followers.length - 1 && index !== 0){\n followersString += \"and \";\n }\n followersString += data[follower].name + \" \";\n });\n var followers = getFollowers(person);\n if(followers){\n followersString += \", this are his/her followers \"\n followers.forEach(function(follower, index, followers){\n if(index === followers.length - 1 && index !== 0){\n followersString += \"and \";\n }\n followersString += data[follower].name + \" \";\n });\n }\n console.log(followersString);\n }\n}",
"function followsLeastPeople(socialData) {\n var sorted = sortByNumberOfFollowers(socialData);\n sorted.reverse();\n console.log(sorted[0].name + \" follows the least people. (\" + sorted[0].follows.length + \" people)\");\n}",
"function numOfPages() {\n\tcurrency = data[\"currency\"];\n\tbaseurl = data[\"base-url\"];\n numberOfPages = Math.ceil(hotelsArr.length / numberPerPage);\n\n}",
"function mostFollowersOver30(){\n var maxNumFollowersOver30 = 0;\n var mostFollowersOver30PersonId = 0;\n for(person in data){\n var followersOver30 = getFollowersArray(person).filter(function(follower){\n return follower.age > 30\n });\n if(maxNumFollowersOver30 <= followersOver30.length){\n maxNumFollowersOver30 = followersOver30.length;\n mostFollowersOver30PersonId = person;\n }\n }\n console.log(\"The person with most followers over 30 is: \" + data[mostFollowersOver30PersonId].name);\n}",
"function computeRefererCounts() {\n \n var referrerCounts = {};\n for (var key in visitorsData) {\n var referringSite = visitorsData[key].referringSite || '(direct)';\n if (referringSite in referrerCounts) {\n referrerCounts[referringSite]++;\n } else {\n referrerCounts[referringSite] = 1;\n }\n }\n return referrerCounts; \n}",
"async getBookmarkCount() {\n const [result] = await this.client('bookmark').count();\n const value = parseInt(result['count(*)']) ?? 0;\n return value;\n }",
"function mostPeopleFollowingOver30(){\n var maxNumFollowingOver30 = 0;\n var mostFollowingOver30PersonId = 0;\n for(var person in data){\n var filteredFollowingArray = data[person].follows.filter(function(followingPersonId){\n return data[followingPersonId].age > 30;\n });\n if(maxNumFollowingOver30 <= filteredFollowingArray.length){\n maxNumFollowingOver30 = filteredFollowingArray.length;\n mostFollowingOver30PersonId = person;\n }\n }\n console.log(\"The person that follows more people over 30 is: \" + data[mostFollowingOver30PersonId].name);\n}",
"function sortByNumberOfFollowers (socialData) {\n var sortableSocialData = convertToArray(socialData);\n sortableSocialData.sort(function sortfunction (a,b){\n if(a.follows.length > b.follows.length)\n return -1;\n if(a.follows.length < b.follows.length)\n return 1;\n return 0;\n });\n\n return sortableSocialData;\n}",
"function jnParseGetNumItineraries(username) \n{\n\tvar numObjs = -1;\n\tfor (usernameItObj in _jnAllParsedItineraryObjs) {\n\t\tvar usernameFromObj = usernameItObj._username;\n\t\tif (usernameFromObj == username) {\n\t\t\tnumObjs = usernameItObj._itineraries.length;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\treturn numObjs;\n}",
"numOfPages() {\n var totPages = Math.ceil(this.productList.length / this.numOfProductsPerPage);\n return totPages;\n }",
"_countPlayedUsers() {\n let played = 0\n let remaining = 0\n for (let i = 0; i < this.users.length; i++) {\n if (this.users[i].checked) played++\n if (this.users[i].left !== true) remaining++\n }\n\n return { played, remaining }\n }",
"function lookupFollowers(userLogin, callback) {\n $.ajax({\n type: 'GET',\n url: \"/tatami/rest/followers/lookup?screen_name=\" + userLogin,\n dataType: 'json',\n success: function(data) {\n callback(data);\n }\n });\n return false;\n}",
"function getUsersFollowers(fguid, guid, lastUsername) {\n\n var query = \"SELECT `profile`.guid, f2.`status` AS followed_status, f2.blocked, `profile`.`username`, profile.`fullname`, profile.followers, profile.following, user_metrics.popularity, `profile`.`verified`, profile.is_private, profile.about, profile.domain, `profile`.image_url AS image_url, `profile`.allow_view_followers, `profile`.allow_view_followings FROM `profile` INNER JOIN `friends` ON `friends`.`guid1` = `profile`.`guid` AND `status` = ? profile.allow_view_me_followers_list = 1 LEFT JOIN user_metrics ON user_metrics.guid = profile.guid LEFT JOIN `friends` as f2 ON f2.guid1 = ? AND f2.guid2 = profile.guid WHERE `friends`.`guid2` = ? ORDER BY `username` ASC LIMIT 60\";\n var parameters = [ Relationship.IsFollowing, guid, fguid];\n\n if (isStringWithLength(lastUsername)) {\n \n query = \"SELECT `profile`.guid, f2.`status` AS followed_status, f2.blocked, `profile`.`username`, profile.`fullname`, profile.followers, profile.following, user_metrics.popularity, `profile`.`verified`, profile.is_private, profile.about, profile.domain, `profile`.image_url AS image_url, `profile`.allow_view_followers, `profile`.allow_view_followings FROM `profile` INNER JOIN `friends` ON `friends`.`guid1` = `profile`.`guid` AND `status` = ? profile.allow_view_me_followers_list = 1 LEFT JOIN user_metrics ON user_metrics.guid = profile.guid LEFT JOIN `friends` as f2 ON f2.guid1 = ? AND f2.guid2 = profile.guid WHERE `friends`.`guid2` = ? AND username > ? ORDER BY `username` ASC LIMIT 60\";\n parameters = [ Relationship.IsFollowing, guid, fguid, lastUsername];\n }\n\n /**\n * Result contains friends info as ( guid, status, blocked, username, fullname\n */\n connection.query({\n sql : query,\n values: parameters,\n }, \n function (error, results, fields) {\n\n printTimeForEvent(\"End getting Friends\");\n\n if (error) {\n console.log('Error:', JSON.stringify(error, null, 2));\n finalAppResponse( errorResponse( ErrorMessageGeneric))\n } \n\n if (results) {\n console.log('==== Printing out Results for ' + results.length + ' rows ====');\n \n var friends = followerResults(results);\n\n var response = listFriendsResponse(friends);\n \n printTimeForEvent(\"getFriends close to end of function\");\n\n finalAppResponse( response);\n\n console.log(\"=============== Done ================\");\n } else {\n console.log('Error:', JSON.stringify(error, null, 2));\n finalAppResponse(errorResponse( ErrorMessageGeneric));\n }\n });\n }",
"async LoadProfile() {\n\n // Load profile page\n await this.page.goto('https://www.instagram.com/'+this.profile,\n { waitUntil: 'networkidle0',\n timeout: 30000 })\n \n // Check access to profile\n //await this.Debug(this.page)\n await this.CheckAccessToProfile(this.page)\n\n // Get number of followers\n this.totalFol = await this.page.$eval(this.sel.profileHeader+this.sel.followersButton,\n el => { return el.innerHTML })\n .catch(err => { \n throw new Error(\"Followers button was not found:\\n\", err)\n })\n this.totalFol = await this.ParseNumber(this.totalFol)\n //console.log(this.totalFol)\n\n // Open dialog with followers\n await this.page.$eval(this.sel.profileHeader+this.sel.followersButton,\n el => el.click())\n try {\n await this.page.waitForSelector(this.sel.followersDiv+\" ul\",\n { visible: true,\n timeout: 10000 })\n } catch (err) {\n throw new Error(\"List with followers was not found in page DOM!\\n\", err)\n }\n }",
"async function scrapeUsers(n=10) {\n\tfor (var i=0;i<n;i++) {\n\t\tconst id = scrapeNextUser();\n\t\tif (await id) {\n\t\t\tawait parseUserByID(await id);\n\t\t} else {\n\t\t\treturn i+1;\n\t\t}\n\t\tawait sleep(delay);\n\t}\n\treturn n;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert the given transaction blob to a transaction hash. | static transactionBlobToTransactionHash(transactionBlobHex) {
if (!Utils.isHex(transactionBlobHex)) {
return undefined;
}
const prefixedTransactionBlob = this.toBytes(signedTransactionPrefixHex + transactionBlobHex);
const hash = this.sha512Half(prefixedTransactionBlob);
return this.toHex(hash);
} | [
"static hashTransactions(transactionDatas){\n let data = [];\n transactionDatas.forEach(transaction => {\n data.push(JSON.stringify(transaction));\n });\n\n // use sha256 to create a merkle tree\n let tree = merkle(\"sha256\").sync(data);\n\n // return the merkle root\n return tree.root();\n }",
"treeHash(str) {\n if (Objects.type(str) === 'commit') {\n return str.split(/\\s/)[1];\n }\n }",
"function hash(obj) {\n return JSON.stringify(obj)\n}",
"function toHex$1(requestId) {\n return blobToHex(requestId);\n}",
"eth_getTransactionByHash(transactionHash) {\n return this.request(\"eth_getTransactionByHash\", Array.from(arguments));\n }",
"function git_commit_hash () {\n if (!_HASH) {\n var start = process.cwd(); // get current working directory\n process.chdir(get_base_path()); // change to project root\n var cmd = 'git rev-parse HEAD'; // create name.zip from cwd\n var hash = exec_sync(cmd); // execute command synchronously\n process.chdir(start); // change back to original directory\n _HASH = hash.replace('\\n', ''); // replace the newline\n }\n return _HASH;\n}",
"static getHash(block){\r\n const {timestamp, lastHash, data, nonce} = block;\r\n return this.createHash(data, timestamp, lastHash, nonce, difficulty);\r\n }",
"_encodeBlob(blob = iCrypto.pRequired(\"_encodeBlob\"),\n encoding = iCrypto.pRequired(\"_encodeBlob\")){\n let self = this;\n if (!this.encoders.hasOwnProperty(encoding)){\n throw \"_encodeBlob: Invalid encoding: \" + encoding;\n }\n return self.encoders[encoding](blob)\n }",
"function hash(text) {\n return crypto.createHash('md5').update(text).digest('hex')\n}",
"static uniqueIdentityToHashObject(uniqueIdentity) {\n var terms = uniqueIdentity.split(':');\n if (terms.length != 2) {\n throw \"unique-identity has invalid format\";\n }\n let hashType = terms[0];\n let hashValue = terms[1];\n if (SUPPORTED_COMMON_NAME_HASH_TYPES.indexOf(hashType) < 0) {\n throw \"hash function '\" + hashType + \"' is not supported for certificate Common Name unique identity\";\n }\n return {\n 'hashType': hashType,\n 'hashValue': hashValue\n };\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}",
"function transform(tx){\n return {\n blockchain : 'vechain',\n block : tx.blockNumber, // or blockRef (?)\n id : tx.id,\n source : tx.origin,\n //operations : [], // TODO: operations from clauses (transfers, contract calls)\n result : null,\n }\n}",
"function calculateChangeHash(item) {\r\n const cpy = Object.assign({}, item);\r\n if (cpy.eTag) {\r\n delete cpy.eTag;\r\n }\r\n ;\r\n return JSON.stringify(cpy);\r\n}",
"calculateHash(data, timestamp, previousHash, nonce) {\n return SHA256(JSON.stringify(data) + timestamp + previousHash + nonce).toString();\n }",
"function hash(uuid) {\n var hash = 0, i, chr;\n if (uuid.length === 0) return hash;\n for (i = 0; i < uuid.length; i++) {\n chr = uuid.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n if (hash < 0) {\n hash += 1;\n hash *= -1;\n }\n return hash % constants.localStorage.numBins;\n}",
"function HashFileID(fileID) {\n return HashAll(encodeUint8(fileID.version), encodeString(fileID.applicationID), encodeUint8(fileID.fileType), encodeString(fileID.filename));\n}",
"function sha256_encode_bytes() {\n var j = 0;\n var output = new Array(32);\n for (var i = 0; i < 8; i++) {\n output[j++] = ((ihash[i] >>> 24) & 0xff);\n output[j++] = ((ihash[i] >>> 16) & 0xff);\n output[j++] = ((ihash[i] >>> 8) & 0xff);\n output[j++] = (ihash[i] & 0xff);\n }\n return output;\n }",
"function checksum (str, algorithm, encoding) {\n return crypto\n .createHash(algorithm || 'sha256')\n .update(str, 'utf8')\n .digest(encoding || 'hex');\n}",
"function hashParams(params) {\n const hashedParams = {};\n Object.keys(params).map((key) => {\n hashedParams[key] = hash.sha256().update(params[key]).digest('hex');\n });\n return hashedParams;\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 }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Triggers on change to a parameter in a selector, selectorNum is the selector | selectorParameterChange(event, selectorNum) {
var rulesets = this.state.rulesets
// The id is the index of the selector
rulesets[this.state.currentRuleset][selectorNum].parameters[event.target.id] = event.target.value
this.setState({rulesets: rulesets}, () => {
this.updateData()
})
} | [
"function sel_change(v, check, F, objs) {\n if (v == check) {\n sel_enable_objs(F, objs);\n } else {\n sel_disable_objs(F, objs);\n }\n}",
"onSelectionChange(func){ return this.eventSelectionChange.register(func); }",
"onSelectionEdited(func){ return this.eventSelectionEdited.register(func); }",
"handleModifySelPGTobj($change){\n\t const rIndex = this.props.UI.selectedRowIndex;\n\t this.props.onPGTobjArrayChange(\"update\", {index: rIndex, $Updater: $change});\n\t}",
"on_change(ev){\r\n\t\tthis.val = this.get_value();\r\n\t\t// hack to get around change events not bubbling through the shadow dom\r\n\t\tthis.dispatchEvent(new CustomEvent('pion_change', { \r\n\t\t\tbubbles: true,\r\n\t\t\tcomposed: true\r\n\t\t}));\r\n\t\t\r\n\t\tif(!this.hasAttribute(\"noupdate\")){ //Send value to server\t\t\r\n\t\t\tsend_update(this, this.getAttribute(\"item_name\"), new Value(this.val));\t\t\t\r\n\t\t}\r\n\t\t\r\n\t}",
"function changeNumber(event){\n setNumber(event.target.value);\n }",
"handleSelect(thisSelector, nextSs, selectorLevel, data) {\n this.state[thisSelector] = data.value;\n this.setState({selectorLevel: selectorLevel})\n for(let i in nextSs){\n this.refs[nextSs[i]].resetValue();\n if(i == 0){\n this.refs[nextSs[i]].loadOptions();\n }\n }\n }",
"function onSelectedChanged(val) {\n scope.$emit('selectedchange', val);\n }",
"changeRuleType(event, selectorNum) {\n var rulesets = this.state.rulesets\n\n var selectorParameters = rulesets[this.state.currentRuleset][selectorNum].parameters\n rulesets[this.state.currentRuleset][selectorNum].rules[event.target.id].rule = event.target.value\n\n if (event.target.value == \"Total\") { // Matches to the total rule\n rulesets[this.state.currentRuleset][selectorNum].rules[event.target.id].parameters = {\n \"condition\": \"\",\n \"amount\": null,\n \"category\": \"\",\n \"for\": \"\"\n }\n \n } else if (event.target.value == \"Repeats\") { // Matches to the repeats rule\n rulesets[this.state.currentRuleset][selectorNum].rules[event.target.id].parameters = {\n \"amount\": null,\n \"category\": \"\"\n }\n } else { // Matches to the filter rule\n rulesets[this.state.currentRuleset][selectorNum].rules[event.target.id].parameters = {\n \"type\": \"\",\n \"filter\": \"\"\n }\n }\n\n this.setState({rulesets: rulesets}, () => {\n this.updateData()\n })\n }",
"add_change(func) {\n this.add_event(\"change\", func);\n }",
"function onChangeGoalAmount() {\n calNumberOfContribution();\n }",
"function updateNumOutputpinsSelected() {\n\tvar num = 0;\n\tfor ( var i = 0; i < viewModel.selectedModuleOfInterest.availableOutputpinList().length; ++i)\n\t{\n\t\tnum += viewModel.selectedModuleOfInterest.availableOutputpinList()[i].isChecked();\n\t\t\n\t}\n\tviewModel.numOutputpinsSelected(num);\n}",
"function updateWeaponsNumber() {\r\n\t\tvar index = 0;\r\n\t\t$( \"#weaponQuality\" ).find( \"option\" ).each( function() {\r\n\r\n\t\t\tvar str = $(this).text();\r\n\t\t\tvar pos = str.indexOf( \",\", 0 );\r\n\t\t\tif( pos > -1 ) {\r\n\t\t\t\tnWeap = str.substr( pos + 2, str.indexOf( \" \", pos + 2 ) - pos - 1 );\r\n\t\t\t\t$( \"#weaponSelector\" ).children( \"div:eq(\"+ index +\")\" ).find( \".selectorNumWeapons\" ).text( nWeap );\r\n\t\t\t\t$( \"#availableWeaponsInfo\" ).text( nWeap + \" weap\" );\r\n\r\n\t\t\t\tif( selectedWeapon.attr( \"indexselect\" ) == index ) {\r\n\t\t\t\t\tif( nWeap == 0 ) {\r\n\t\t\t\t\t\tselectedWeapon.unbind( \"click\" );\r\n\t\t\t\t\t\tselectedWeapon.unbind( \"mouseover\" );\r\n\t\t\t\t\t\tselectedWeapon.unbind( \"mouseout\" );\r\n\t\t\t\t\t\tselectedWeapon.addClass( \"disabledWeapon\" );\r\n\t\t\t\t\t\t$( \"#weaponSelector\" ).children( \"div\" ).eq( 0 ).click();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tindex++;\r\n\t\t});\r\n\t}",
"add_select(func) {\n this.add_event(\"select\", func);\n }",
"function ChangeHandler() {\n PreviousSelectIndex = SelectIndex; \n /* Contains the Previously Selected Index */\n\n SelectIndex = document.forms[0].lstDropDown.options.selectedIndex;\n /* Contains the Currently Selected Index */\n\n if ((PreviousSelectIndex == (document.forms[0].lstDropDown.options.length - 1)) && (SelectIndex != (document.forms[0].lstDropDown.options.length - 1)) && (SelectChange != 'MANUAL_CLICK')) \n /* To Set value of Index variables */\n {\n document.forms[0].lstDropDown[(document.forms[0].lstDropDown.options.length - 1)].selected=true;\n PreviousSelectIndex = SelectIndex;\n SelectIndex = document.forms[0].lstDropDown.options.selectedIndex;\n SelectChange = 'MANUAL_CLICK'; \n /* Indicates that the Change in dropdown selected \n\t\t\tvalue was due to a Manual Click */\n }\n }",
"setSelector(selectorText){\n if (typeof selectorText !== \"string\") throw new TypeError(\"Your selectorText is not a string\");\n let head = super.getHead();\n\n this.patch({\n action: VirtualActions.PATCH_REPLACE,\n start: head.startOffset,\n end: head.endOffset,\n value: selectorText,\n patchDelta: selectorText.length - head.endOffset\n })\n }",
"changed() {\n ++this.revision_;\n this.dispatchEvent(EventType.CHANGE);\n }",
"function optionChanged(value) {\n console.log(value);\n updatePlotly(value);\n}",
"function MDEC_SelectLevelChange(el_select) {\n console.log(\"===== MDEC_SelectLevelChange =====\");\n\n mod_MEX_dict.lvlbase_pk = (el_select.value && Number(el_select.value)) ? Number(el_select.value) : null;\n MDEC_enable_btn_save();\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create new date time segment | constructor(dateSegment = '', timeSegment = '') {
this.dateSegment = dateSegment;
this.timeSegment = timeSegment;
} | [
"function createDate() {\n theDate = new Date();\n }",
"_addDate() {\n const valueLink = this.props.valueLink;\n const value = valueLink.value || {};\n const slots = (value.slots || []).slice();\n const start = this.state.start.getTime();\n const end = start + this.state.duration;\n\n // Store the timeslot state as seconds, not ms\n slots.push([start / 1000, end / 1000]);\n\n value.slots = slots;\n valueLink.requestChange(value);\n }",
"function create_new_activity(descript, time) {\n let new_activity = {\n id: generateHexString(50),\n description: descript,\n time: acquire_date.import_date(time)\n };\n\n return new_activity;\n}",
"constructor(title,days,time,duration,relative_time,relative_to,till,relative_to_till)\r\n {\r\n this.m_start = '' //moment object for start time\r\n this.title = title;\r\n this.days = days;\r\n this.time = time;\r\n this.duration = duration;\r\n this.relative_time = relative_time;\r\n this.relative_to = relative_to;\r\n this.till = till;\r\n this.relative_to_till = relative_to_till;\r\n this.type = ''; //i not put in constructor yet\r\n }",
"function createDay(week, date) { //TODO: remove week from parameters\n\tvar daySchedule = Parser.getSchedule(date);\n\t\n\t//TODO repeated code from Parser.getSchedule()\n\tvar dateString = date.getMonth().valueOf()+1 + \"/\" + date.getDate().valueOf() + \"/\" + date.getFullYear().toString().substr(-2);\n\t\n\tvar col = week.insertCell(-1);\n\tcol.date = date.valueOf(); //store date in cell element\n\t\n\tif(date.getMonth()==9 && date.getDate()==31) //check Halloween\n\t\tcol.classList.add(\"halloween\");\n\t\n\tvar head = document.createElement(\"div\");\n\thead.classList.add(\"head\");\n\tvar headWrapper = document.createElement(\"div\");\n\theadWrapper.classList.add(\"headWrapper\");\n\theadWrapper.innerHTML = DAYS_OF_WEEK[date.getDay()] + \"<div class=\\\"headDate\\\">\" + dateString + \"</div>\";\n\thead.appendChild(headWrapper);\n\tcol.appendChild(head);\n\t\n\tvar prevEnd = \"8:00\"; //set start of day to 8:00AM\n\t\n\tfor(var i=0;i<daySchedule.length;i++) {\n\t\tvar periodObj = daySchedule[i];\n\t\tvar passing = $(\"<div>\").addClass(\"period\");\n\n\t\tvar period = $(\"<div>\", { class: \"period\" });\n\t\t\n\t\tif(opts.showPassingPeriods) {\n\t\t\tpassing.append(Period.createPeriod(\"\",prevEnd,periodObj.start,date));\n \t\t col.appendChild(passing.get(0));\n\t\t\tprevEnd = periodObj.end;\n\t\t}\n\t\t\n\t\tperiod.append(periodObj.getHTML(date));\n\t\t\t\n\t\tcol.appendChild(period.get(0));\n\t}\n}",
"function buildNUSExam(data, semStart) {\n var examD = data.ExamDate;\n var tempT = parseInt(examD.substring(11,13))-8; //To UTC\n examD = examD.substring(0,4)+examD.substring(5,7)+\n examD.substring(8,10);\n var temp = {\n summary: data.ModuleCode + \" (EXAM)\",\n description: data.ModuleTitle, \n rrule: {\n freq: \"ONCE\"\n },\n dateStart: moment(examD,\"YYYYMMDD\").add('hour',tempT)\n };\n temp.dateEnd = temp.dateStart.clone().add('hour',3).toDate();\n temp.dateStart = temp.dateStart.clone().toDate();\n return temp;\n}",
"createDateTime(date, time) {\n // set default values for any inputs that were not chosen\n if (!date) {\n date = moment();\n }\n if (!time) {\n time = moment();\n }\n\n return moment({\n y: date.year(),\n M: date.month(),\n d: date.date(),\n h: time.hour(),\n m: time.minute(),\n s: 0,\n ms: 0\n })\n }",
"function makeDate(min, sec) {\n return new Date(Date.UTC(1970, 0, 1, 0, min, sec));\n }",
"setDate(now = new Date()) {\n let startDay = new Date(now.getFullYear(), now.getMonth(), 1).getDay() - 1;\n startDay = startDay < 0 ? 6 : startDay;\n\n this.date = {\n year: now.getFullYear(),\n month: now.getMonth(),\n day: now.getDate(),\n startDay: startDay,\n daysOfMonth: new Date(now.getFullYear(), now.getMonth()+1, 0).getDate()\n }\n }",
"createDtArray() {\n this.dtArray = this.priceArray.map(function(d){return d.Date;});\n }",
"addAppointment(date,time,title) {\n const appointment = new Appointment(date,time,title)\n\n if (this.map.has(date)) {\n this.map.get(date).push(appointment)\n }\n else {\n this.map.set(date,[appointment])\n }\n\n }",
"function newMidnightDate(year, month, day) {\n return new Date(year, month, day, 0, 0, 0, 0);\n }",
"addDateTime(title, properties) {\n return this.add(title, 4, {\n DateTimeCalendarType: 1 /* Gregorian */,\n DisplayFormat: DateTimeFieldFormatType.DateOnly,\n FriendlyDisplayFormat: DateTimeFieldFriendlyFormatType.Unspecified,\n ...properties,\n });\n }",
"function buildDate(date, hours, minutes) {\n\t\t\t\t\tvar timestamp = date.setHours(hours, minutes);\n\n\t\t\t\t\treturn new Date(timestamp);\n\t\t\t\t}",
"createTimeGapMapping() {\n let timeGapMapping = {};\n this.patients.forEach(d => {\n let curr = this.sampleStructure[d];\n for (let i = 1; i < curr.length; i++) {\n if (i === 1) {\n timeGapMapping[curr[i - 1]] = undefined\n }\n timeGapMapping[curr[i]] = this.sampleTimelineMap[curr[i]] - this.sampleTimelineMap[curr[i - 1]]\n }\n timeGapMapping[curr[curr.length - 1] + \"_post\"] = undefined;\n });\n this.staticMappers[this.timeDistanceId] = timeGapMapping;\n }",
"function scanhalfnext() {\n setTime(startdateinmilliseconds + diffmilliseconds/2, enddateinmilliseconds + diffmilliseconds/2);\n}",
"function assignTimestamp(){\n\tif (INTERSECTED && readOnly != 1) {\n\t\tif (INTERSECTED.name.dynamic==0) {\n\t\t\talert('Timestamp should be assigned to dynamic objects');\n\t\t\treturn;\n\t\t}\n\t\tif (INTERSECTED.name.dynamicIdx==-2) {\n\t\t\talert('Timestamp should be assigned to spline control objects');\n\t\t\treturn;\n\t\t}\n\t\tif (splineIsAutoBoxed[INTERSECTED.name.dynamicSeq]==1) {\n\t\t\talert('Timestamp cannot be modified after automatic boxes generated. ClearAutoBox at first for modification.');\n\t\t\treturn;\n\t\t}\n\t\tINTERSECTED.name.timestamp = shaderMaterial.uniforms.timestamp_center.value;\n\t\t//INTERSECTED.material.opacity = timestampOpacity;\n\t\tlabels_helper[currentIdx].material.color.setHex(WIREFRAME_COLOR[2]);\n \t\tdisplayMsg('status','Assign the current object with timestamp ' + shaderMaterial.uniforms.timestamp_center.value.toString());\n\t}\n}",
"function AddDate(){\n\tvar dateP = document.createElement(\"p\");\n\tdateP.append(Date());\n\tdateP.setAttribute(\"class\", \"dateP\");\n\tdateDiv.append(dateP);\n}",
"scale(time) {\n const dateOffsetMilli = this.dateOffset.getTime();\n const timeOffsetMilli = this.timeOffset\n .scale(this.scaleFactor).milliseconds;\n const newMilli = time.scale(this.scaleFactor).milliseconds;\n\n return new Date(dateOffsetMilli + timeOffsetMilli + newMilli);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
funcion para crear el xml | function createXMLConciliacion( root, params )
{
var nodes;
var xml = "";
if( root )
xml += "<" + root + ">";
for(var i=0; i<params.length; i++)
{
nodes=params[i];
xml += "<element>";
for( theNode in nodes )
{
xml += "<" + theNode + ">" + nodes[theNode] + "</" + theNode + ">";
}
xml += "</element>";
}
xml += "</" + root + ">";
return xml;
} | [
"function generateXML(){\n\t\t\t\tconsole.log(\"###### FUNCTION generateXML START\");\n\t\t\t\tvar xml2Send = '';\n\t\t\t\txml2Send += '<?xml version=\"1.0\" encoding=\"UTF-8\"?><simpledc xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dct=\"http://purl.org/dc/terms/\" xmlns:geonet=\"http://www.fao.org/geonetwork\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://purl.org/dc/elements/1.1/ http://dublincore.org/schemas/xmls/qdc/2006/01/06/simpledc.xsd http://purl.org/dc/terms/ http://dublincore.org/schemas/xmls/qdc/2006/01/06/dcterms.xsd\">';\n\t\t\t\txml2Send += '<dc:identifier>' + $scope.metadata.identifier + '</dc:identifier>';\n\t\t\t\txml2Send += '<dc:title>' + $scope.metadata.title + '</dc:title>';\n\t\t\t\tif($scope.metadata.alttitle){\n\t\t\t\t\txml2Send += '<dct:alternative>' + $scope.metadata.alttitle + '</dct:alternative>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dct:alternative></dct:alternative>';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t$scope.metadata.pubdate = $filter('date')($scope.metadata.pubdate, \"yyyy-MM-dd\");\n\t\t\t\tif($scope.metadata.pubdate){\n\t\t\t\t\txml2Send += '<dct:dateSubmitted>' + $scope.metadata.pubdate + '</dct:dateSubmitted>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dct:dateSubmitted></dct:dateSubmitted>';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t$scope.metadata.date = $filter('date')($scope.metadata.date, \"yyyy-MM-dd\");\n\t\t\t\txml2Send += '<dc:created>' + $scope.metadata.date + '</dc:created>';\n\t\t\t\tif($scope.metadata.dataidentifier){\n\t\t\t\t\txml2Send += '<dc:identifier>' + $scope.metadata.dataidentifier + '</dc:identifier>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dc:identifier></dc:identifier>';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\txml2Send += '<dc:description>' + $scope.metadata.abstract + '</dc:description>';\n\t\t\t\txml2Send += '<dc:creator>' + $scope.metadata.contact + ';' + $scope.metadata.email + '</dc:creator>';\n\t\t\t\tif ($scope.metadata.keywords) {\n\t\t\t\t\tvar keywordsString = $scope.metadata.keywords.toString();\n\t\t\t\t\tvar keywords = keywordsString.split(\",\");\n\t\t\t\t\t$.each(keywords, function (i) {\n\t\t\t\t\t\txml2Send += '<dc:subject>' + keywords[i] + '</dc:subject>';\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\txml2Send += '<dc:subject>' + $scope.metadata.keywords + '</dc:subject>';\n\t\t\t\t}\n\t\t\t\txml2Send += '<dc:type>' + $scope.metadata.theme + '</dc:type>';\n\t\t\t\tif($scope.metadata.accessuse){\n\t\t\t\t\txml2Send += '<dc:rights>' + $scope.metadata.accessuse + '</dc:rights>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dc:rights></dc:rights>';\n\t\t\t\t}\n\t\t\t\tif($scope.metadata.publicaccess){\n\t\t\t\t\txml2Send += '<dct:accessRights>' + $scope.metadata.publicaccess + '</dct:accessRights>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dct:accessRights></dct:accessRights>';\n\t\t\t\t}\n\t\t\t\txml2Send += '<dc:language>' + $scope.metadata.language.name + '</dc:language>';\n\t\t\t\txml2Send += '<dc:coverage>North ' + $scope.geolocation.bounds[3] + ',South ' + $scope.geolocation.bounds[1] + ',East ' + $scope.geolocation.bounds[2] + ',West ' + $scope.geolocation.bounds[0] + '. (Global)</dc:coverage>';\n\t\t\t\txml2Send += '<dc:format>' + $scope.metadata.format + '</dc:format>';\n\t\t\t\tif ($scope.metadata.url) {\n\t\t\t\t\tvar urlsString = $scope.metadata.url.toString();\n\t\t\t\t\tvar urls = urlsString.split(\",\");\n\t\t\t\t\t$.each(urls, function (i) {\n\t\t\t\t\t\txml2Send += '<dct:references>' + urls[i] + '</dct:references>';\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\txml2Send += '<dct:references>' + $scope.metadata.url + '</dct:references>';\n\t\t\t\t}\n\t\t\t\txml2Send += '<dc:source>' + $scope.metadata.lineage + '</dc:source>';\n\t\t\t\txml2Send += '</simpledc>';\n\t\t\t\tconsole.log(\"###### FUNCTION generateXML END\");\n\t\t\t\tconsole.log(\"###### FUNCTION generateXML RESULT: \" + xml2Send);\n\t\t\t\treturn xml2Send;\n\t\t\t}",
"function set2xml() {\n var xmlstr = new java.lang.StringBuffer(\"<\" + this.name + \" datum='\" + this.parent.datum + \"' val='\" + this.val + \"'\");\n if (this.desc) xmlstr.append(\" desc='\" + this.desc + \"'\");\n xmlstr.append(\"/>\");\n return xmlstr.toString(); \n}",
"function ProcessableXML() {\n\n}",
"function createXml (options, xmlObject) {\n const createdXml = js2xmlparser.parse('licenseSummary', xmlObject);\n if (!options.silent) {\n console.log(createdXml);\n }\n if (options.xml) {\n const fileName = options.xml.substring(0, options.xml.length - path.extname(options.xml).length);\n fs.writeFileSync(path.join(licensesDir, `${fileName}.xml`), createdXml);\n }\n}",
"function obj2xml() {//sonce, padavine, klima\n var xmlstr = new java.lang.StringBuffer(\"\");\n xmlstr.append(\"<\" + this.name + \" action=''\" + \" interval='false' id='\" + this.id + \"' postaja='\" + \n\t\t\t\t\t\t\t\tformatNumber(this.postaja) + \"' tip='\" + formatNumber(this.tip) + \"' ime_postaje='\" + \n\t\t\t\t\t\t\t\tthis.ime_postaje + \"' user='\" + user + \"'>\"); // za izpis postaje z vodilnimi niรลคlami\n var obj = this.getFirst();\n if (obj) {\n while (1) {\n xmlstr.append(obj.toXml());\n if (obj.hasNext()) obj = obj.getNext();\n\t\t\telse break;\n }\n }\n xmlstr.append(\"</\" + this.name + \">\");\n return toXml(xmlstr.toString());\n}",
"function xmlStringFromDocDom(oDocDom, encodeSingleSpaceTextNodes) {\n\tvar xmlString = new String();\n\n\t// if the node is an element node\n\tif (oDocDom.nodeType == 1 && oDocDom.nodeName.slice(0,1) != \"/\") {\n\t\t// define the beginning of the root element and that element's name\n\t\txmlString = \"<\" + oDocDom.nodeName.toLowerCase();\n\n\t\t// loop through all qualified attributes and enter them into the root element\n\t\tfor (var x = 0; x < oDocDom.attributes.length; x++) {\n\t\t\tif (oDocDom.attributes[x].specified == true || oDocDom.attributes[x].name == \"value\") {\t// IE wrongly puts unspecified attributes in here\n\t\t\t\t//if (oDocDom.attributes[x].name == \"class\") {\n\t\t\t\t//\txmlString += ' class=\"' + oNode.attributes[x].value + '\"';\n\t\t\t\t//} else {\n\n\t\t\t\t// If this is not an input, then add the attribute is \"input\", then skip this.\n\t\t\t\tif (oDocDom.nodeName.toLowerCase() != \"input\" && oDocDom.attributes[x].name == \"value\" && oDocDom.attributes[x].specified == false) {\n\n\t\t\t\t// If this is an img element.\n\t\t\t\t} else if (oDocDom.nodeName.toLowerCase() == \"img\" && oDocDom.attributes[x].name == \"width\" ||\n\t\t\t\t\toDocDom.nodeName.toLowerCase() == \"img\" && oDocDom.attributes[x].name == \"height\") {\n\n\t\t\t\t} else {\n\n\t\t\t\t\txmlString += ' ' + oDocDom.attributes[x].name + '=\"' + oDocDom.attributes[x].value + '\"';\n\t\t\t\t}\n\t\t\t\t//}\n\t\t\t}\n\t\t}\n\n\t\t// if the xml object doesn't have children, then represent it as a closed tag\n//\t\tif (oDocDom.childNodes.length == 0) {\n//\t\t\txmlString += \"/>\"\n\n//\t\t} else {\n\n\t\t// if it does have children, then close the root tag\n\t\txmlString += \">\";\n\t\t// then peel through the children and apply recursively\n\t\tfor (var i = 0; i < oDocDom.childNodes.length; i++) {\n\t\t\txmlString += xmlStringFromDocDom(oDocDom.childNodes.item(i), encodeSingleSpaceTextNodes);\n\t\t}\n\t\t// add the final closing tag\n\t\txmlString += \"</\" + oDocDom.nodeName.toLowerCase() + \">\";\n//\t\t}\n\n\t\treturn xmlString;\n\n\t} else if (oDocDom.nodeType == 3) {\n\t\t// return the text node value\n\t\tif (oDocDom.nodeValue == \" \" && encodeSingleSpaceTextNodes == true) {\n\t\t\treturn \"#160;\";\n\t\t} else {\n\t\t\treturn oDocDom.nodeValue;\n\t\t}\n\t} else {\n\t\treturn \"\";\n\t}\n}",
"function musicXML(source, callback) {\n var part = kPartWise, musicXML, impl, type, xmlHeader;\n\n // Create the DOM implementation\n impl = domino.createDOMImplementation();\n\n // Create the DOCTYPE\n type = impl.createDocumentType(part.type, part.id, part.url);\n\n // Create the document itself\n musicXML = impl.createDocument('', '', null);\n\n // Create the <?xml ... ?> header\n xmlHeader = musicXML.createProcessingInstruction('xml',\n 'version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"');\n\n // Append both the header and the DOCTYPE\n musicXML.appendChild(xmlHeader);\n musicXML.appendChild(type);\n\n // Start serializing the MusicJSON document\n musicXML.appendChild(toXML(musicXML, source[part.type], part.type));\n\n callback(null, musicXML);\n}",
"function createXML() {\n var typeChecker, request;\n showSpinner(\"verify-spin\");\n typeChecker = $('option:selected').val();\n\tconsole.log(\"typechecker is \" + typeChecker + \" \" + document.location.pathname);\n\tconsole.log(\"isXML \" + document.forms.isXML.value);\n\n //make ajax request to create XML file\n request = $.ajax({\n url : PHP_SCRIPT,\n type : \"POST\",\n data : {\"function\" : \"xml\", \"guid\" : uploadGUID, \"script\" : typeChecker}\n });\n\n\t//wait for ajax request to complete before continuing\n request.done(function (response) {\n if (response === \"SUCCESS\") {\n \t\tconsole.log(\"create XML success\");\n\t \tcreateGameFiles();\n } else {\n\t\tconsole.log(\"create XML fail \" + response);\n\n $('#verify-spin').html(\"<a style='color:red' target='_blank' \" +\n \"href='scripts/utilities.php\" +\n \"?function=displayError&file=\" + response + \"&id=\" + uploadGUID + \"\\'>Error</a>\");\n }\n });\n}",
"function DeltaXMLFactory() {\n}",
"function getXMLDocument(){\n var xDoc=null;\n\n if( document.implementation && document.implementation.createDocument ){\n xDoc=document.implementation.createDocument(\"\",\"\",null);//Mozilla/Safari \n }else if (typeof ActiveXObject != \"undefined\"){\n var msXmlAx=null;\n try{\n msXmlAx=new ActiveXObject(\"Msxml2.DOMDocument\");//New IE\n }catch (e){\n msXmlAx=new ActiveXObject(\"Msxml.DOMDocument\"); //Older Internet Explorer \n }\n xDoc=msXmlAx;\n }\n if (xDoc==null || typeof xDoc.load==\"undefined\"){\n xDoc=null;\n }\n return xDoc;\n}",
"static convertDocumentToString(xmlDocument, depth){\n var result =\"\";\n var nodeName = String(xmlDocument.nodeName);\n\n // set the tabulation with the depth\n var tab = \"\";\n\n if(depth!=0){\n for(var i = 1; i < depth; i++ ){\n tab += \"\\t\";\n }\n // add the node and the attributes\n result += tab +\"<\" + nodeName\n $(xmlDocument.attributes).each(function(i,attr){\n result += \" \" + String(attr.name) + \"=\\\"\" + _.escape(String(attr.value)) +\"\\\"\"\n })\n if($(xmlDocument).text() != \"\" || $(xmlDocument).children().length > 0){\n result += \">\";\n }else{\n result += \"/>\";\n }\n }\n // add the children to the result\n if ($(xmlDocument).children().length > 0){\n result += \"\\n\";\n $(xmlDocument).children().each(function(i,child){\n result += Writer.convertDocumentToString(child, depth + 1) + \"\\n\";\n })\n result += tab;\n }else{\n result += $(xmlDocument).text();\n }\n\n if(depth!=0){\n if($(xmlDocument).text() != \"\" || $(xmlDocument).children().length > 0){\n result += \"</\" + nodeName + \">\";\n }\n }\n return result;\n }",
"function makeDateFromXML(xmlDate) {\n var dd, mm, yyyy;\n dd = $(xmlDate).find(\"day\").text();\n if (dd < 10) {\n dd = '0' + dd;\n }\n mm = $(xmlDate).find(\"month\").text();\n if (mm < 10) {\n mm = '0' + mm;\n }\n yyyy = $(xmlDate).find(\"year\").text();\n return yyyy + '-' + mm + '-' + dd;\n }",
"function buildPackageXml(packageName) {\n\n var packageXml = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>';\n packageXml += '<Package xmlns=\"http://soap.sforce.com/2006/04/metadata\">';\n packageXml += (packageName !== 'unpackaged') ? '<fullName>'+ packageName +'</fullName>' : '';\n packageXml += '<types>';\n packageXml += '<members>*</members>';\n packageXml += '<name>CustomObject</name>';\n packageXml += '</types>';\n packageXml += '<types>';\n packageXml += '<members>*</members>';\n packageXml += '<name>CustomMetadata</name>';\n packageXml += '</types>';\n packageXml += '<version>33.0</version>';\n packageXml += '</Package>';\n\n return packageXml;\n\n }",
"function xmltostring(id,data,addr,idExtractor){\n console.log(\"debut xml to string\");\n fse.readFile('projects/'+id+'/video.xml',\"utf8\",function(err,data){\n if(err){\n console.log(err);\n }\n sendvideo(id, data, addr,idExtractor);\n });\n //.then(() => sendvideo(id, data, addr))\n //.catch(err => console.error(err))\n}",
"function initialXML(){\n\n\tvar dialogXML = \"\";\n\tdialogXML += \tinitialTitle();\n\tdialogXML += \t'<vbox>';\n dialogXML += \t\tinitialLabel();\n dialogXML += \t\t'<label control=\"choosePostfix\" value=\"Choose a suffix to append:\"/> ';\n dialogXML += \t\t'<textbox id=\"postfix\" value=\"_ft\" width=\"50\"/> ' ;\n dialogXML += \t'</vbox>';\n\tdialogXML += '</dialog>';\n\t\n\tvar xmlPanelOutput = displayXML(dialogXML);\n\treturn xmlPanelOutput;\n}",
"function customMetadataToXml(namespace,inputData,fields) {\n\n \n var ns = (namespace !== '' && vm.orgData.packages !== 'unpackeged') ? namespace : '';\n\n var customMetadataXml = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>';\n customMetadataXml += '<CustomMetadata xmlns=\"http://soap.sforce.com/2006/04/metadata\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">';\n customMetadataXml += '<description>'+ inputData.description + '</description>';\n customMetadataXml += '<label>' + inputData.label + '</label>';\n \n for (var c=0; c < inputData.values.length; c++){\n\n var field = inputData.values[c];\n\n customMetadataXml += '<values>';\n customMetadataXml += '<field>' + ns + fields[c].fullName + '</field>';\n customMetadataXml += '<value xsi:type=\"xsd:' + sfTypeToApexType(fields[c].type) + '\">' + field.value + '</value>';\n customMetadataXml += '</values>';\n\n }\n\n customMetadataXml += '</CustomMetadata>';\n\n\n if (typeof inputData !== 'undefined' || inputData !== {}) {\n\n return customMetadataXml;\n\n } else {\n\n return '';\n \n }\n \n }",
"getManifestXmlString() {\n const jsonToXmlbuilder = new Builder();\n const xml = jsonToXmlbuilder.buildObject(this.data);\n return xml;\n }",
"function wrapSitemapXML(xml) {\n\treturn '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n\t + '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">'\n\t + (Array.isArray(xml) ? xml.join('') : xml)\n\t + '</urlset>';\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}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes folder with sets from one archive | removeUploadedSet(dir) {
return removeDir(this.uploadPath + '/' + dir)
} | [
"function folderCleanUp() {\n DriveApp.getFoldersByName('test1').next().setTrashed(true);\n DriveApp.getFoldersByName('test2').next().setTrashed(true);\n}",
"function removeTestDuplicateFolders() {\n var folderName = 'duplicate folder';\n removeFolder(folderName);\n}",
"resetFolders(){\n // clear folder paths \n this._folderPaths = [];\n\n // update file\n return this.update();\n }",
"function clearBookmarkFolders() {\n while ($bookmarksList.children.length > 0) {\n $bookmarksList.removeChild($bookmarksList.firstChild);\n }\n }",
"function clearSetsList() {\n while ($setsArea.firstChild !== $createNewElem) {\n $setsArea.removeChild($setsArea.firstChild);\n }\n }",
"removeFolder(path){\n // remove the path from the array\n let updatedPaths = this._folderPaths.filter(currPath => currPath !== path);\n\n // update object\n this._folderPaths = updatedPaths;\n\n // update file \n return this.update();\n }",
"clearTemps() {\n fs.rmdirSync(this.temps, { recursive: true });\n }",
"function DistClean(){\n\t// return del([delHtml,delStatic]);\n}",
"removeKeys () {\n this._eachPackages(function (_pack) {\n _pack.remove()\n })\n }",
"[_delistFromMeta] () {\n const top = this.top\n const root = this.root\n\n root.inventory.delete(this)\n if (root.meta)\n root.meta.delete(this.path)\n\n // need to also remove from the top meta if that's set. but, we only do\n // that if the top is not the same as the root, or else we'll remove it\n // twice unnecessarily. If the top and this have different roots, then\n // that means we're in the process of changing this.parent, which sets the\n // internal _parent reference BEFORE setting the root node, because paths\n // need to be set up before assigning root. In that case, don't delist,\n // or else we'll delete the metadata before we have a chance to apply it.\n if (top.meta && top !== root && top.root === this.root)\n top.meta.delete(this.path)\n }",
"function clean_assets() {\n return del([\"./assets\"]);\n}",
"function cleanup(dir) {\n console.log('Removing temporarily extracted zip contents ...');\n\n // cf. http://stackoverflow.com/questions/18052762/remove-directory-which-is-not-empty\n var deleteFolderRecursive = function(path) {\n if( fs.existsSync(path) ) {\n fs.readdirSync(path).forEach(function(file,index){\n var curPath = path + \"/\" + file;\n if(fs.lstatSync(curPath).isDirectory()) { // recurse\n deleteFolderRecursive(curPath);\n } else { // delete file\n fs.unlinkSync(curPath);\n }\n });\n fs.rmdirSync(path);\n }\n };\n\n deleteFolderRecursive(dir);\n return Promise.resolve();\n}",
"deleteFromTree({ state, commit, getters, dispatch }, directories) {\n directories.forEach((item) => {\n // find this directory in the tree\n const directoryIndex = getters.findDirectoryIndex(item.path);\n\n if (directoryIndex !== -1) {\n // add directory index to array for deleting\n commit('addToTempArray', directoryIndex);\n\n // if directory has subdirectories\n if (state.directories[directoryIndex].props.hasSubdirectories) {\n // find subDirectories\n dispatch('subDirsFinder', state.directories[directoryIndex].id);\n }\n }\n });\n\n // filter directories\n const temp = state.directories.filter((item, index) => {\n if (state.tempIndexArray.indexOf(index) === -1) {\n return item;\n }\n return false;\n });\n\n // replace directories\n commit('replaceDirectories', temp);\n\n // clear temp array\n commit('clearTempArray');\n }",
"async function purgeNoArt(dir) {\n var configFile = configPath + dir + '.json';\n var config = await fsw.readFile(configFile, 'utf8');\n var config = JSON.parse(config);\n for await (let item of Object.keys(config.items)) {\n if ((config.items[item].hasOwnProperty('has_logo')) || (config.items[item].hasOwnProperty('has_video'))) {\n if ((config.items[item].has_logo == false) || (config.items[item].has_video == false)) {\n delete config.items[item];\n }\n }\n }\n var configContents = JSON.stringify(config, null, 2);\n await fsw.writeFile(configFile, configContents);\n renderRoms();\n }",
"rollback() {\n while (this._installedFiles.length > 0) {\n let move = this._installedFiles.pop();\n if (move.isMoveTo) {\n move.newFile.moveTo(move.oldDir.parent, move.oldDir.leafName);\n } else if (move.newFile.isDirectory() && !move.newFile.isSymlink()) {\n let oldDir = getFile(move.oldFile.leafName, move.oldFile.parent);\n oldDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);\n } else if (!move.oldFile) {\n // No old file means this was a copied file\n move.newFile.remove(true);\n } else {\n move.newFile.moveTo(move.oldFile.parent, null);\n }\n }\n\n while (this._createdDirs.length > 0)\n recursiveRemove(this._createdDirs.pop());\n }",
"function CleanUpHerokuDistFolder(){\n del.sync(`${deploymentPaths.HEROKU_DIST_FOLDER}/**`);\n}",
"function cleanTemp() {\n cleanFolder(uploadFolder);\n}",
"rm(ws, project, args) {\n\t\tlet recursive = false;\n\t\tconst glob = new Glob();\n\t\targs.forEach(arg => {\n\t\t\tif (arg.startsWith('-')) {\n\t\t\t\tif (arg === '-r') recursive = true;\n\t\t\t} else {\n\t\t\t\tglob.include(arg);\n\t\t\t}\n\t\t});\n\t\tglob.match(project.root).forEach(file => {\n\t\t\tif(fs.lstatSync(file).isDirectory()) {\n\t\t\t\t// TODO impl recursive dir removal?\n\t\t\t\t/*\n\t\t\t\t// ignore for now.\n\t\t\t\tfs.rmdirSync(file, {\n\t\t\t\t\trecursive: true\n\t\t\t\t});\n\t\t\t\t*/\n\t\t\t\tconsole.log('not removing directory:', file);\n\t\t\t} else {\n\t\t\t\t//console.log('rm file:', file);\n\t\t\t\tfs.unlinkSync(file);\n\t\t\t}\n\t\t});\n\t}",
"distinctBundles() {\n let bundles = [];\n this.html.forEach((file, index, arr) => {\n bundles = bundles.concat(file.bundles);\n });\n const clean = [];\n const group = helper.groupBy(bundles, b => b.dest);\n const keys = group.keys();\n for (let i = 0; i < group.size; i++) {\n const dest = keys.next().value;\n const matches = group.get(dest);\n // Check bundles\n if (matches.length > 1) {\n // const includes = helper.sortBy(matches[0].files, f => f);\n const includes = matches[0].files;\n matches.forEach((bundle, index, arry) => {\n // console.log(\"First: \" + includes.length + \" Found: \" + bundle.files.length + \" IN: \" + bundle.html + \" : \" + bundle.name );\n if (includes.length === bundle.files.length) {\n // const list = helper.sortBy(bundle.files, f => f);\n for (let i = 0; i < includes.length; i++) {\n if (includes[i] !== bundle.files[i]) {\n throw \"Bundle: \" + bundle.name + \" in file: \" + bundle.html + \", does not match.\\n\"\n + \"Asset file should be: \" + includes[i] + \", but it is: \" + bundle.files[i] + \"\\n\"\n + \"The included files are not identical with the other bundles, with the same destination.\";\n }\n }\n }\n else {\n throw \"Bundle: \" + bundle.name + \" in file: \" + bundle.html + \", does not match.\\n\"\n + \"Bundle should have: \" + includes.length + \", but it has: \" + bundle.files.length + \" assets.\\n\"\n + \"The included files are not identical with the other bundles, with the same destination.\";\n }\n });\n }\n clean.push(matches[0]);\n }\n this.bundles = clean;\n return this;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array containing the indices of this._docs where active is true, randomly ordered using their weights, i.e., the document with the highest weight is most likely but not guaranteed to come first, and the document with the lowest weight is most likely but not guaranteed to come last. FIXME | documentOrdering() {
var docs = [ ];
for(var i in this._docs) {
if(this._docs[i].active) {
docs.push(i);
}
}
var docs = docs.sort( function(a, b) { return (Math.random() * this._docs[a].weight) - (Math.random() * this._docs[b].weight); } );
if(this._diagnostics) {
var msg = "@documentOrdering();\n" +
"Output: [ " + docs + "]\n";
}
return docs;
} | [
"static fetchFreeIndex(){\n\t\t//There are no used indexes yet, so return index 0\n\t\tif ( referenceCount.size === 0){\n\t\t\treturn 0;\n\t\t}\n\n\t\tlet indices = Array.from( referenceCount.keys() );\n\t\t//Sort the usedIndices array ascending (or descending?)\n\t\tindices.sort(function(a, b){return a - b});\n\t\tlet i = 0;\n\t\twhile(indices.includes(i)){\n\t\t\t++i;\n\t\t}\n\t\treturn i;\n\t}",
"initializeWeights() {\n\t\t// Create weights for each node\n\t\tfor (let n = 0; n < this.numNodes; n++) {\n\t\t\tlet nodeWeights = [];\n\t\t\t// Each input gets a random weight\n\t\t\tfor (let i = 0; i < this.numInputs; i++) {\n\t\t\t\t// Add a random weight between -1 and 1\n\t\t\t\tnodeWeights.push(Math.random()*2 - 1);\n\t\t\t}\n\t\t\tthis.weights.push(nodeWeights);\n\t\t}\n\t}",
"function generateWordDistribution() {\t\t\t\n\t\tvar zipf = [15,8,5,4,3,3,2,2];\n\t\tvar words_and_distributions = [[],[],[]];\n\t\tfor (var ma = 0; ma < 3; ma++) {\n\t\t\tfor (var iq = 0; iq < 8; iq++) {\n\t\t\t\twords_and_distributions[ma].push([selected_words[ma][iq], zipf[iq]]);\n\t\t\t}\n\t\t}\t\n\t\treturn words_and_distributions\n\t}",
"get index() {\n return fromCache(this, CACHE_KEY_INDEX, () => {\n const { el, items } = this;\n const { length } = items;\n const { clientWidth } = el;\n const outerLeft = el.getBoundingClientRect().left;\n const index = [];\n let at = 0;\n for (; at < length; at++) {\n const item = items[at];\n const rect = item.getBoundingClientRect();\n const { width } = rect;\n let { left } = rect;\n left = left - outerLeft;\n if (left + width * VISIBILITY_OFFSET >= 0 &&\n left + width * (1 - VISIBILITY_OFFSET) <= clientWidth) {\n index.push(at);\n }\n }\n if (index.length === 0) {\n // If no index found, we return a [0] as default. This possibly happens\n // when the carousel is not attached to the DOM or is visually hidden (display: none).\n return [0];\n }\n return index;\n });\n }",
"function getSequenceWeights (tList, tNow)\n{\n\tvar wt = getEventWeight (tList[0], tList[0] - 100000000000 /* = 3 yrs */, tNow);\n\tvar wts = [wt];\n\tfor (var i = 1; i < tList.length; i++)\n\t{\n\t\tvar temp = getEventWeight(tList[i], tList[i-1], tNow);\n\t\ttemp = Math.round(temp*1000)/1000;\n\t\twt += temp;\n\t\twts.push(temp);\n\t}\n\treturn [wt, wts];\n}",
"allWeight(){\n let progress = 0;\n if(this.weightLog.length >= 2){\n progress = this.weightLog[this.weightLog.length-1].weight - this.weightLog[0].weight;\n }\n return {weights: this.weightLog, progress: progress};\n }",
"generateExampleBeginIndices_() {\n // Prepare beginning indices of examples.\n this.exampleBeginIndices_ = [];\n for (\n let i = 0;\n i < this.textLen_ - this.sampleLen_ - 1;\n i += this.sampleStep_\n ) {\n this.exampleBeginIndices_.push(i);\n }\n console.log('exampleBeginIndices_');\n console.log(this.exampleBeginIndices_);\n\n // Randomly shuffle the beginning indices.\n // tf.util.shuffle(this.exampleBeginIndices_);\n this.examplePosition_ = 0;\n }",
"getIndexes(women, facts) {\n db.collection('indexes').get().then(snapshot => {//get indexing files\n let snaps = {};\n snapshot.forEach(snap => {//put actual ids in to snaps\n if (snap.data() && snap.data()[\"IDs\"]) {\n let IDpool = snap.data()[\"IDs\"];\n let kind = snap.id;\n snaps[kind] = {};\n Object.keys(IDpool).forEach(key => {\n if (IDpool[key].includes(Dictionary.getLanguage()))\n snaps[kind][key] = IDpool[key];\n })\n }\n })\n \n //we are using {all} so I can know what to what collaction the id belongs.\n let all = {};\n //extract the amount of ids that were asked for in the function parameters\n Object.keys(snaps).forEach(key => {\n let arr = [];\n let kind = (key === \"women Index\") ? \"women\" : \"facts\";\n let amount = (kind === \"women\") ? women : facts;\n\n let data = Object.keys(snaps[key]);//make the ids of this kind an array\n\n if (amount > data.length)//make sure that there are enough ids\n amount = data.length;\n\n arr = this.randomizeArr(data, amount);//returns a random arr in the amount size\n\n //add the number of slides reternd so we know how meny slides we will have\n this.setState({ dataslide: this.state.dataslide + arr.length });\n all[key] = arr;\n });\n\n Object.keys(all).forEach(key => {//go over both keys and call all ids from firestore\n let collect = (key === \"women Index\") ? \"women\" : \"didYouKnow\";\n all[key].forEach(id => {//for each id for this key\n\n db.collection(collect).doc(id).get().then(snapshot => {\n if (snapshot.data()) {\n let item;\n let data = snapshot.data();\n if (collect === \"women\") {\n item = this.pushWomen(data);\n }\n else if (collect === \"didYouKnow\") {\n item = this.pushFact(data);\n }\n\n if (item) {//add item to the items state\n let items = this.state.items;\n items.push(item);\n this.setState({ items: items });\n }\n else\n this.setState({ dataslide: this.state.dataslide - 1 });//remove slide becuse id was not used\n\n\n if (this.state.dataslide === this.state.items.length)\n this.mixSlides();\n\n }\n\n }).catch(error => console.log(error))\n })\n })\n\n\n }).catch(error => console.log(error))\n }",
"generateExampleBeginIndices_() {\n // Prepare beginning indices of examples.\n this.exampleBeginIndices_ = [];\n for (let i = 0;\n i < this.textLen_ - this.sampleLen_ - 1;\n i += this.sampleStep_) {\n this.exampleBeginIndices_.push(i);\n }\n\n // Randomly shuffle the beginning indices.\n tf.util.shuffle(this.exampleBeginIndices_);\n this.examplePosition_ = 0;\n }",
"function get_weighted_layer(pdf){\n\tvar rand = Math.random();\n\tvar cdf = pdf_to_cdf(pdf);\n\tfor (var i = 0; i < cdf.length; i++){\n\t\tif (rand < cdf[i]){\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn \"Error: get_weighted_layer\";\n}",
"getActiveIndex() {\n return this.activeIndex;\n }",
"function crowningIndex (oActive) {\n return oActive / 54.680665 // CI in km/h\n}",
"function invDocFreq(term) {\n if (corpus == null){\n return -1;\n } else {\n //N = corpus.length;\n let docFreq = 0;\n for (let i in N){\n for (let j in corpus[i]) {\n if (corpus[i][j] == term.toLowerCase()){\n docFreq++;\n break;\n }\n }\n }\n let idf = Math.log((N) / (docFreq + 1)) + 1;\n return idf;\n }\n }",
"getWeights(){\n return this.weights;\n }",
"getRandomPhrase () {\n\t\tlet newIndex;\n\t\tdo {\n\t\t\tnewIndex = Math.floor(Math.random() * this.phrases.length);\n\t\t} while (this.usedIndexes.indexOf(newIndex) !== -1);\n\t\tthis.usedIndexes.push(newIndex);\n\t\tdocument.body.style.background = this.getRandomColor();\n\t\treturn this.phrases[newIndex];\n\t}",
"changeRandomWeight(){\n\t\tvar i = Math.floor(Math.random() * this.genes.length)\n\n\t\t//we can only use an available gene\n\t\tif (this.genes[i] != null){\n\t\t\tthis.genes[i].weigth = (Math.random() * 2) - 1 //betwenn -1 and 1\n\t\t} else {\n\t\t\tthis.changeRandomWeight()\n\t\t}\n\t}",
"function update_document_scores() {\n\tfor (article in file_entity_map) {\n\t\tvar entity_sum = 0;\n\t\tvar article_score = 0;\n\t\tfor (cur_entity in file_entity_map[article]) {\n\t\t\tunformatted_entity = unformat_name(cur_entity);\n// \t\t\tarticle_score += (file_entity_map[article][cur_entity] * entity_weight_map[unformatted_entity]);\n// \t\t\tentity_sum += file_entity_map[article][cur_entity];\n\t\t\tarticle_score += entity_weight_map[unformatted_entity];\n\t\t\tentity_sum += 1;\n\t\t}\n\n\t\tif (entity_sum != 0)\n\t\t\tarticle_score /= entity_sum;\n\n\t\tif (article_score > 1)\n\t\t\tarticle_score = 1;\n\n\t\tarticle_weight_map[article] = article_score;\n\t}\n\n\tupdate_timeline();\n\tupdate_doc_table();\n}",
"function docEdits_sortWeights()\n{\n //var msg=\"presort -------------\\n\";\n //for (i=0; i<docEdits.editList.length; i++) {\n // msg += i+\":\" +docEdits.editList[i].weight+\"=\"+docEdits.editList[i].text+\"\\n\";\n //}\n //alert(msg);\n\n //shift-sort algorithm. Keeps same-weight chunks together\n for (var i=0; i < docEdits.editList.length-1; i++)\n {\n for (var j=i+1; j < docEdits.editList.length; j++)\n {\n var aType = docEdits.editList[i].weightType;\n var bType = docEdits.editList[j].weightType;\n\n var a = docEdits.editList[i].weightNum;\n var b = docEdits.editList[j].weightNum;\n\n if ((aType == bType && a != null && b != null && a > b)\n || (aType == \"belowHTML\" && bType==\"aboveHTML\"))\n {\n var temp = docEdits.editList[j];\n for (var k=j; k>i; k--)\n {\n docEdits.editList[k] = docEdits.editList[k-1];\n }\n docEdits.editList[i] = temp;\n }\n }\n }\n\n //var msg=\"After pre sort:\\n\";\n //for (i=0; i<docEdits.editList.length; i++) {\n // msg += i+\":\" +docEdits.editList[i].weight+\"=\"+docEdits.editList[i].text+\"\\n\";\n //}\n //alert(msg);\n}",
"adjustRandomWeight(){\n\t\tvar i = Math.floor(Math.random() * this.genes.length)\n\n\t\t//we can only use an available gene\n\t\tif (this.genes[i] != null){\n\t\t\tvar value = ((Math.random() - 0.5) * 2 / 5) //between -0.2 and 0.2\n\t\t\tthis.genes[i].weigth += value\n\t\t} else {\n\t\t\tthis.adjustRandomWeight()\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`_encodeObject` represents an object | _encodeObject(object) {
switch (object.termType) {
case 'Quad':
return this._encodeQuad(object);
case 'Literal':
return this._encodeLiteral(object);
default:
return this._encodeIriOrBlank(object);
}
} | [
"function encodeExtensionObject(object, stream) {\n\n if (!object) {\n ec.encodeNodeId(ec.makeNodeId(0), stream);\n stream.writeUInt8(0x00); // no body is encoded\n stream.writeUInt32(0);\n } else {\n ec.encodeNodeId(object.encodingDefaultBinary, stream);\n stream.writeUInt8(0x01); // 0x01 The body is encoded as a ByteString.\n stream.writeUInt32(object.binaryStoreSize());\n object.encode(stream);\n }\n}",
"serialize(obj) {\n if (!obj.constructor || typeof obj.constructor.encode !== \"function\" || !obj.constructor.$type) {\n throw new Error(\"Object \" + JSON.stringify(obj) +\n \" is not a protobuf object, and hence can't be dynamically serialized. Try passing the object to the \" +\n \"protobuf classes create function.\")\n }\n return Any.create({\n type_url: \"type.googleapis.com/\" + AnySupport.fullNameOf(obj.constructor.$type),\n value: obj.constructor.encode(obj).finish()\n });\n }",
"function toJson(o) { return JSON.stringify(o); }",
"static serialize(obj, view, offset = 0, countBytes = false) {\r\n if (arguments.length < 1) {\r\n throw 'missing arguments';\r\n }\r\n if (typeof obj === 'undefined') {\r\n if (!countBytes)\r\n view.setUint8(offset, Cobton.UndefinedValue);\r\n offset++;\r\n return offset;\r\n }\r\n if (obj === null) {\r\n if (!countBytes)\r\n view.setUint8(offset, Cobton.NullValue);\r\n offset++;\r\n return offset;\r\n }\r\n if (typeof obj === 'boolean') {\r\n if (!countBytes)\r\n view.setUint8(offset, obj ? Cobton.TrueValue : Cobton.FalseValue);\r\n offset++;\r\n return offset;\r\n }\r\n if (typeof obj === 'number') {\r\n return Cobton.serializeNumber(obj, view, offset, countBytes);\r\n }\r\n if (typeof obj === 'string') {\r\n return Cobton.serializeString(obj, view, offset, countBytes);\r\n }\r\n if (typeof obj === 'function') {\r\n return Cobton.serializeFunction(obj, view, offset, countBytes);\r\n }\r\n if (typeof obj === 'object') {\r\n return Cobton.serializeObject(obj, view, offset, countBytes);\r\n }\r\n throw 'unexpected object type';\r\n }",
"function hash(obj) {\n return JSON.stringify(obj)\n}",
"function object_to_string(obj)\r\n{\r\n var res = \"\";\r\n for (var key in obj)\r\n {\r\n res += key + \"\\t\" + obj[key] + \"\\n\";\r\n }\r\n return res;\r\n}",
"_serialize() {\n return JSON.stringify([\n this._id,\n this._label,\n this._properties\n ]);\n }",
"encodeData(type, value) {\n return this.getEncoder(type)(value);\n }",
"function serialize(input, transferables) {\n if (input === null || input === undefined || typeof input === 'boolean' || typeof input === 'number' || typeof input === 'string' || input instanceof Boolean || input instanceof Number || input instanceof String || input instanceof Date || input instanceof RegExp) {\n return input;\n }\n\n if (input instanceof ArrayBuffer) {\n if (transferables) {\n transferables.push(input);\n }\n return input;\n }\n\n if (ArrayBuffer.isView(input)) {\n var view = input;\n if (transferables) {\n transferables.push(view.buffer);\n }\n return view;\n }\n\n if (input instanceof ImageData) {\n if (transferables) {\n transferables.push(input.data.buffer);\n }\n return input;\n }\n\n if (Array.isArray(input)) {\n var serialized = [];\n for (var i = 0, list = input; i < list.length; i += 1) {\n var item = list[i];\n\n serialized.push(serialize(item, transferables));\n }\n return serialized;\n }\n\n if (typeof input === 'object') {\n var klass = input.constructor;\n var name = klass._classRegistryKey;\n if (!name) {\n throw new Error(\"can't serialize object of unregistered class\");\n }\n assert_1(registry[name]);\n\n var properties = {};\n\n if (klass.serialize) {\n // (Temporary workaround) allow a class to provide static\n // `serialize()` and `deserialize()` methods to bypass the generic\n // approach.\n // This temporary workaround lets us use the generic serialization\n // approach for objects whose members include instances of dynamic\n // StructArray types. Once we refactor StructArray to be static,\n // we can remove this complexity.\n properties._serialized = klass.serialize(input, transferables);\n } else {\n for (var key in input) {\n // any cast due to https://github.com/facebook/flow/issues/5393\n if (!input.hasOwnProperty(key)) {\n continue;\n }\n if (registry[name].omit.indexOf(key) >= 0) {\n continue;\n }\n var property = input[key];\n properties[key] = registry[name].shallow.indexOf(key) >= 0 ? property : serialize(property, transferables);\n }\n\n if (input instanceof Error) {\n properties.message = input.message;\n }\n }\n\n return { name: name, properties: properties };\n }\n\n throw new Error(\"can't serialize object of type \" + typeof input);\n }",
"function createObjWriter(obj) {\n wasmInternalMemory.memoryToRead = obj;\n var module = new WebAssembly.Instance(webAssemblyModule, importObject);\n return {read_i8: module.exports.read_i8, write_i8: module.exports.write_i8, read_i16: module.exports.read_i16, write_i16: module.exports.write_i16, read_i32: module.exports.read_i32, write_i32: module.exports.write_i32, read_i64: read_i64.bind(null, module.exports.read_i16), write_i64: write_i64.bind(null, module.exports.write_i16), module: module}\n }",
"function uriSerialize(obj, prefix) {\n\t\tvar str = [];\n\t\tfor(var p in obj) {\n\t\t\tvar k = prefix ? prefix + \"[\" + p + \"]\" : p, v = obj[p];\n\t\t\tstr.push(typeof v == \"object\" ?\n\t\t\t\turiSerialize(v, k) :\n\t \t\tencodeURIComponent(k) + \"=\" + encodeURIComponent(v));\n\t\t}\n\t\treturn str.join(\"&\");\n\t}",
"_encodeBlob(blob = iCrypto.pRequired(\"_encodeBlob\"),\n encoding = iCrypto.pRequired(\"_encodeBlob\")){\n let self = this;\n if (!this.encoders.hasOwnProperty(encoding)){\n throw \"_encodeBlob: Invalid encoding: \" + encoding;\n }\n return self.encoders[encoding](blob)\n }",
"function ObjectMap(stringify){\n\n\tif(typeof stringify == 'function')\n /**\n \t* Method to find unique string keys for objects.\n \t*/\n \tthis.__stringify__ = stringify;\n else throw new Error(\"Please specify a valid function to find string representation of the objects\");\n\n \n /**\n * A plain old javascript object, to hold key-value pairs\n */\n this.__map__ = {};\n\n /**\n * A varibale to keep track of the number of key-value pairs\n * in the map\n */\n this.__size__=0;\n}",
"function toByteArray(termObj) {\n // note: if we forget new here, we get:\n // TypeError: this.$set is not a function\n const term = new proto.Par(termObj);\n\n const buf = term.toBuffer();\n return buf;\n }",
"getObject() {\n return this.object;\n }",
"function objToData(o) {\n console.log(o) // XXX TEMPORARY\n\n var fd = new FormData()\n\n for (var k in o) fd.append(k, encodeURIComponent(o[k]))\n\n return fd\n}",
"_encodeQuad({\n subject,\n predicate,\n object,\n graph\n }) {\n return `<<${this._encodeSubject(subject)} ${this._encodePredicate(predicate)} ${this._encodeObject(object)}${(0, _N3Util.isDefaultGraph)(graph) ? '' : ` ${this._encodeIriOrBlank(graph)}`}>>`;\n }",
"static encode(domain, types, value) {\n return (0, index_js_4.concat)([\n \"0x1901\",\n TypedDataEncoder.hashDomain(domain),\n TypedDataEncoder.from(types).hash(value)\n ]);\n }",
"function serialize(personObject) {\n\n // create an array with the keys in the correct order\n const personParts = [\n personObject.name,\n personObject.personhash,\n personObject.portoffset,\n ]\n\n // join the personParts using a comma and return that string\n return personParts.join(',')\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers the provided binding (prop + bindingIndex) into the context. This function is shared between bindings that are assigned immediately (via `updateBindingData`) and at a deferred stage. When called, it will figure out exactly where to place the binding data in the context. It is needed because it will either update or insert a styling property into the context at the correct spot. When called, one of two things will happen: 1) If the property already exists in the context then it will just add the provided `bindingValue` to the end of the binding sources region for that particular property. If the binding value is a number then it will be added as a new binding index source next to the other binding sources for the property. Otherwise, if the binding value is a string/boolean/null type then it will replace the default value for the property if the default value is `null`. 2) If the property does not exist then it will be inserted into the context. The styling context relies on all properties being stored in alphabetical order, so it knows exactly where to store it. When inserted, a default `null` value is created for the property which exists as the default value for the binding. If the bindingValue property is inserted and it is either a string, number or null value then that will replace the default value. Note that this function is also used for mapbased styling bindings. They are treated much the same as propbased bindings, but, because they do not have a property value (since it's a map), all mapbased entries are stored in an already populated area of the context at the top (which is reserved for mapbased entries). | function registerBinding(context, countId, prop, bindingValue, sanitizationRequired) {
var registered = false;
if (prop) {
// prop-based bindings (e.g `<div [style.width]="w" [class.foo]="f">`)
var found = false;
var i = getPropValuesStartPosition(context);
while (i < context.length) {
var valuesCount = getValuesCount(context, i);
var p = getProp(context, i);
found = prop <= p;
if (found) {
// all style/class bindings are sorted by property name
if (prop < p) {
allocateNewContextEntry(context, i, prop, sanitizationRequired);
}
addBindingIntoContext(context, false, i, bindingValue, countId);
break;
}
i += 3 /* BindingsStartOffset */ + valuesCount;
}
if (!found) {
allocateNewContextEntry(context, context.length, prop, sanitizationRequired);
addBindingIntoContext(context, false, i, bindingValue, countId);
registered = true;
}
}
else {
// map-based bindings (e.g `<div [style]="s" [class]="{className:true}">`)
// there is no need to allocate the map-based binding region into the context
// since it is already there when the context is first created.
addBindingIntoContext(context, true, 3 /* MapBindingsPosition */, bindingValue, countId);
registered = true;
}
return registered;
} | [
"function Binding(value){\r\n\t\tthis.value= value;\r\n\t\tif(value){\r\n\t\t\tvalue._binding = this;\r\n\t\t}\r\n\t}",
"updateTagIndexForBinding(binding) {\n this.removeTagIndexForBinding(binding);\n for (const tag of binding.tagNames) {\n let bindings = this.bindingsIndexedByTag.get(tag);\n if (bindings == null) {\n bindings = new Set();\n this.bindingsIndexedByTag.set(tag, bindings);\n }\n bindings.add(binding);\n }\n }",
"function addBindingProperty(e)\n {\n if(!e.binding)\n {\n e.binding = ko.dataFor(e.target);\n }\n\n return e;\n }",
"function PushStyleVar(idx, val) {\r\n bind.PushStyleVar(idx, val);\r\n }",
"function bindElement(element, object) {\n setPropertyOnElement(element, DATA_BINDING_ID, object);\n}",
"setupTagIndexForBindings() {\n this.bindingEventListener = ({ binding, operation }) => {\n if (operation === 'tag') {\n this.updateTagIndexForBinding(binding);\n }\n };\n this.tagIndexListener = event => {\n const { binding, type } = event;\n if (event.context !== this.context)\n return;\n if (type === 'bind') {\n this.updateTagIndexForBinding(binding);\n binding.on('changed', this.bindingEventListener);\n }\n else if (type === 'unbind') {\n this.removeTagIndexForBinding(binding);\n binding.removeListener('changed', this.bindingEventListener);\n }\n };\n this.context.on('bind', this.tagIndexListener);\n this.context.on('unbind', this.tagIndexListener);\n }",
"function applyAttributeBindings(element, attributeBindings, component, operations) {\n let seen = [];\n let i = attributeBindings.length - 1;\n while (i !== -1) {\n let binding = attributeBindings[i];\n let parsed = AttributeBinding.parse(binding);\n let attribute = parsed[1];\n if (seen.indexOf(attribute) === -1) {\n seen.push(attribute);\n AttributeBinding.install(element, component, parsed, operations);\n }\n i--;\n }\n if (seen.indexOf('id') === -1) {\n let id = component.elementId ? component.elementId : guidFor(component);\n operations.setAttribute('id', PrimitiveReference.create(id), false, null);\n }\n if (seen.indexOf('style') === -1) {\n IsVisibleBinding.install(element, component, operations);\n }\n}",
"updateBoundVariable(value) {\n let binddatavalue = this.binddatavalue;\n // return if the variable bound is not static.\n if (this.datavaluesource && this.datavaluesource.execute(DataSource.Operation.IS_API_AWARE)) {\n return;\n }\n else if (this.datavaluesource && !this.datavaluesource.twoWayBinding) {\n return;\n }\n // return if widget is bound.\n if (!binddatavalue || binddatavalue.startsWith('Widgets.') || binddatavalue.startsWith('itemRef.currentItemWidgets')) {\n return;\n }\n binddatavalue = binddatavalue.replace(/\\[\\$i\\]/g, '[0]');\n // In case of list widget context will be the listItem.\n if (_.has(this.context, binddatavalue.split('.')[0])) {\n _.set(this.context, binddatavalue, value);\n }\n else {\n _.set(this.viewParent, binddatavalue, value);\n }\n }",
"static ParseBindingss(bindings) {\n // We start out with a basic config\n const NAME = 'BTooltip';\n let config = {\n delay: getComponentConfig(NAME, 'delay'),\n boundary: String(getComponentConfig(NAME, 'boundary')),\n boundaryPadding: parseInt(getComponentConfig(NAME, 'boundaryPadding'), 10) || 0\n };\n // Process bindings.value\n if (isString(bindings.value)) {\n // Value is tooltip content (html optionally supported)\n config.title = bindings.value;\n }\n else if (isFunction(bindings.value)) {\n // Title generator function\n config.title = bindings.value;\n }\n else if (isObject(bindings.value)) {\n // Value is config object, so merge\n config = Object.assign({}, config, bindings.value);\n }\n // If argument, assume element ID of container element\n if (bindings.arg) {\n // Element ID specified as arg\n // We must prepend '#' to become a CSS selector\n config.container = `#${bindings.arg}`;\n }\n // Process modifiers\n keys(bindings.modifiers).forEach(mod => {\n if (/^html$/.test(mod)) {\n // Title allows HTML\n config.html = true;\n }\n else if (/^nofade$/.test(mod)) {\n // No animation\n config.animation = false;\n }\n else if (/^(auto|top(left|right)?|bottom(left|right)?|left(top|bottom)?|right(top|bottom)?)$/.test(mod)) {\n // Placement of tooltip\n config.placement = mod;\n }\n else if (/^(window|viewport|scrollParent)$/.test(mod)) {\n // Boundary of tooltip\n config.boundary = mod;\n }\n else if (/^d\\d+$/.test(mod)) {\n // Delay value\n const delay = parseInt(mod.slice(1), 10) || 0;\n if (delay) {\n config.delay = delay;\n }\n }\n else if (/^o-?\\d+$/.test(mod)) {\n // Offset value, negative allowed\n const offset = parseInt(mod.slice(1), 10) || 0;\n if (offset) {\n config.offset = offset;\n }\n }\n });\n // Special handling of event trigger modifiers trigger is\n // a space separated list\n const selectedTriggers = {};\n // Parse current config object trigger\n let triggers = isString(config.trigger) ? config.trigger.trim().split(/\\s+/) : [];\n triggers.forEach(trigger => {\n if (validTriggers[trigger]) {\n selectedTriggers[trigger] = true;\n }\n });\n // Parse modifiers for triggers\n keys(validTriggers).forEach(trigger => {\n if (bindings.modifiers[trigger]) {\n selectedTriggers[trigger] = true;\n }\n });\n // Sanitize triggers\n config.trigger = keys(selectedTriggers).join(' ');\n if (config.trigger === 'blur') {\n // Blur by itself is useless, so convert it to 'focus'\n config.trigger = 'focus';\n }\n if (!config.trigger) {\n // Remove trigger config\n delete config.trigger;\n }\n return config;\n }",
"function StatefulPropertyBinding(stateful, name){\r\n\t\tthis.stateful = stateful;\r\n\t\tthis.name = name;\r\n\t}",
"function updateBindings() {\n // if any binding changes, loop over all bindings again to see if the changed made\n // any changes to other bindings. Similar to Angular.js dirty checking method.\n var changed = true;\n \n while (changed) {\n changed = false;\n \n // loop through all bindings and check their old value compared to their current value\n for (var prop in bindings) {\n if (!bindings.hasOwnProperty(prop)) continue;\n \n var value = getBoundValue(prop);\n \n if (typeof value === 'function') {\n // a toString function must be called with it's associated object\n // i.e. value = obj.toString; value = value(); doesn't work\n value = value.call(getBoundObject(prop));\n }\n \n // value has changed, update all DOM\n if (value !== oldValues[prop]) {\n changed = true;\n oldValues[prop] = value;\n \n bindings[prop].forEach(function (node) {\n if (node.nodeName === 'INPUT') {\n node.value = typeof value !== 'undefined' ? value : '';\n } else {\n node.innerHTML = value;\n }\n });\n }\n }\n }\n }",
"function bindDynamicKeys(baseObj, values) {\n for (var i = 0; i < values.length; i += 2) {\n var key = values[i];\n if (typeof key === 'string' && key) {\n baseObj[values[i]] = values[i + 1];\n }\n else if (key !== '' && key !== null) {\n // null is a special value for explicitly removing a binding\n warn$2(\"Invalid value for dynamic directive argument (expected string or null): \".concat(key), this);\n }\n }\n return baseObj;\n }",
"bind(context) {\n\t\tif (!globalParams.modelProperty) {\n\t\t\tthrow new Error('Data key has not been set!');\n\t\t}\n\t\treturn Reflex.set(this, globalParams.modelProperty, context);\n\t}",
"buildStylingInstruction(sourceSpan, constantPool) {\n if (this.hasBindings) {\n return {\n sourceSpan,\n allocateBindingSlots: 0,\n reference: Identifiers$1.styling,\n buildParams: () => {\n // a string array of every style-based binding\n const styleBindingProps = this._singleStyleInputs ? this._singleStyleInputs.map(i => literal(i.name)) : [];\n // a string array of every class-based binding\n const classBindingNames = this._singleClassInputs ? this._singleClassInputs.map(i => literal(i.name)) : [];\n // to salvage space in the AOT generated code, there is no point in passing\n // in `null` into a param if any follow-up params are not used. Therefore,\n // only when a trailing param is used then it will be filled with nulls in between\n // (otherwise a shorter amount of params will be filled). The code below helps\n // determine how many params are required in the expression code.\n //\n // min params => styling()\n // max params => styling(classBindings, styleBindings, sanitizer)\n //\n const params = [];\n let expectedNumberOfArgs = 0;\n if (this._useDefaultSanitizer) {\n expectedNumberOfArgs = 3;\n }\n else if (styleBindingProps.length) {\n expectedNumberOfArgs = 2;\n }\n else if (classBindingNames.length) {\n expectedNumberOfArgs = 1;\n }\n addParam(params, classBindingNames.length > 0, getConstantLiteralFromArray(constantPool, classBindingNames), 1, expectedNumberOfArgs);\n addParam(params, styleBindingProps.length > 0, getConstantLiteralFromArray(constantPool, styleBindingProps), 2, expectedNumberOfArgs);\n addParam(params, this._useDefaultSanitizer, importExpr(Identifiers$1.defaultStyleSanitizer), 3, expectedNumberOfArgs);\n return params;\n }\n };\n }\n return null;\n }",
"_$setValue(value, directiveParent = this, valueIndex, noCommit) {\n const strings = this.strings;\n // Whether any of the values has changed, for dirty-checking\n let change = false;\n if (strings === undefined) {\n // Single-value binding case\n value = resolveDirective(this, value, directiveParent, 0);\n change =\n !isPrimitive$1(value) ||\n (value !== this._$committedValue && value !== noChange);\n if (change) {\n this._$committedValue = value;\n }\n }\n else {\n // Interpolation case\n const values = value;\n value = strings[0];\n let i, v;\n for (i = 0; i < strings.length - 1; i++) {\n v = resolveDirective(this, values[valueIndex + i], directiveParent, i);\n if (v === noChange) {\n // If the user-provided value is `noChange`, use the previous value\n v = this._$committedValue[i];\n }\n change || (change = !isPrimitive$1(v) || v !== this._$committedValue[i]);\n if (v === nothing) {\n value = nothing;\n }\n else if (value !== nothing) {\n value += (v !== null && v !== void 0 ? v : '') + strings[i + 1];\n }\n // We always record each value, even if one is `nothing`, for future\n // change detection.\n this._$committedValue[i] = v;\n }\n }\n if (change && !noCommit) {\n this._commitValue(value);\n }\n }",
"function setStateProp(index, {key, value}) {\n\t\tlet state = Calc.getState();\n\t\tstate.expressions.list[index][key] = value;\n\t\tCalc.setState(state, {allowUndo: true});\n\t}",
"function generateDynamicSourceBindings(sourceName)\n{\n var retList = new Array();\n\n // find the sbobj for the stored proc\n var sbObjs = dwscripts.getServerBehaviorsByTitle(sourceName);\n if (sbObjs && sbObjs.length)\n {\n // Add a binding for the status code if it is returned.\n var statusCodeVarName = sbObjs[0].getStatusCodeVarName();\n if (statusCodeVarName)\n {\n retList.push(new DataSourceBinding(statusCodeVarName, DATASOURCE_LEAF_FILENAME, \n false, \"CFSTOREDPROC.htm\", \"\"));\n }\n \n // Add a binding for each 'out' or 'inout' parameter.\n var callParams = new Array();\n sbObjs[0].getDatabaseCall(callParams);\n if (callParams.length > 0)\n {\n for (var j = 0; j < callParams.length; ++j)\n {\n var varType = callParams[j].varType.toUpperCase();\n if (varType.indexOf(\"OUT\") != -1)\n {\n retList.push(new DataSourceBinding(callParams[j].cfVarName, DATASOURCE_LEAF_FILENAME, \n false, \"CFSTOREDPROC.htm\", \"\"));\n }\n }\n }\n }\n\n return retList;\n}",
"function PushStyleColor(idx, col) {\r\n if (col instanceof ImColor) {\r\n bind.PushStyleColor(idx, col.Value);\r\n }\r\n else {\r\n bind.PushStyleColor(idx, col);\r\n }\r\n }",
"_bindTextures() {\n for (const uniformName in this.uniforms) {\n const uniformSetter = this._uniformSetters[uniformName];\n\n if (uniformSetter && uniformSetter.textureIndex !== undefined) {\n let uniform = this.uniforms[uniformName];\n\n if (uniform instanceof Framebuffer) {\n uniform = uniform.texture;\n }\n if (uniform instanceof Texture) {\n const texture = uniform;\n // Bind texture to index\n texture.bind(uniformSetter.textureIndex);\n }\n }\n }\n }",
"function AccessorPropertyBinding(accessor, name) {\n this.accessor = accessor;\n this.name = name;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a sidenote's length | function ebSidenoteConverterSidenoteLength(sidenote) {
'use strict';
var length = sidenote.innerText.length;
return length;
} | [
"function length () {\r\n return this.node.getComputedTextLength()\r\n}",
"function getLength(string){\n\n\n}",
"static get length() {\n return 0;\n }",
"len() {\n return quat.length(this);\n }",
"get collectiveSongLength() {\n let time = 0;\n SongManager.songList.forEach(s => {\n time += typeof s.details.songLength == \"number\" ? s.details.songLength : 0;\n });\n return time;\n }",
"function ParagraphLength()\r\n{\r\n let plength = Math.floor(Math.random() * 30) + 10;\r\n return plength;\r\n}",
"function len(sslice) /* (sslice : sslice) -> int32 */ {\n return sslice.len;\n}",
"function get_notes() {\n const numOfNotes = document.getElementById('todo-list').childNodes.length\n document.getElementById('stats').innerHTML = ` <p><strong>Num. of notes: </strong>${numOfNotes}</p>`\n}",
"function get_item_size() {\n var sz = 220;\n return sz;\n}",
"getLength() {\n return this._horizLeftHair.get_width();\n }",
"sectionLength(sectionLength) {\n // First branch is for when no variable is passed in, in which case the caller wants the current tempo\n if (typeof sectionLength === 'undefined') {\n if (typeof state.sectionLength === 'number')\n return state.sectionLength;\n if (state.section && typeof state.section.length === 'number')\n return state.section.length;\n if (state.song && typeof state.song.length === 'number')\n return state.song.length;\n return 4;\n }\n }",
"function strLength (string){\n return string.length;\n}",
"function len( obj )\n {\n if ( undefined === obj.length && \"number\" !== typeof obj.length )\n { return undefined; }\n \n return obj.length\n }",
"function nodeLength(node) {\n // \"The length of a node node depends on node:\n //\n // \"DocumentType\n // \"0.\"\n if (node.nodeType == Node.DOCUMENT_TYPE_NODE) {\n return 0;\n }\n // \"Text\n // \"ProcessingInstruction\n // \"Comment\n // \"Its length attribute value.\"\n // Browsers don't historically support the length attribute on\n // ProcessingInstruction, so to avoid spurious failures, do\n // node.data.length instead of node.length.\n if (node.nodeType == Node.TEXT_NODE || node.nodeType == Node.PROCESSING_INSTRUCTION_NODE || node.nodeType == Node.COMMENT_NODE) {\n return node.data.length;\n }\n // \"Any other node\n // \"Its number of children.\"\n return node.childNodes.length;\n}",
"get strokeWidth() {\n var stroke = SLD.stroke(this._symbolizer);\n return Number(stroke.getWidth());\n }",
"function iplength() {\n var model = prompt(\"Enter your favourite mobile phone model\");\n document.write(\"My favourite phone is \"+ model +\"Length is \"+ model.length);\n}",
"function getLength(data) {\n\treturn Object.keys(data).length;\n}",
"function HalfLength() {\n\t\treturn this.length * 0.5;\n\t}",
"function inputLength() {\n\treturn input.value.length;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build the member expression that reads from a global for a given source. | function buildBrowserArg(browserGlobals, exactGlobals, source) {
let memberExpression;
if (exactGlobals) {
const globalRef = browserGlobals[source];
if (globalRef) {
memberExpression = globalRef
.split(".")
.reduce(
(accum, curr) => t.memberExpression(accum, t.identifier(curr)),
t.identifier("global"),
);
} else {
memberExpression = t.memberExpression(
t.identifier("global"),
t.identifier(t.toIdentifier(source)),
);
}
} else {
const requireName = basename(source, extname(source));
const globalName = browserGlobals[requireName] || requireName;
memberExpression = t.memberExpression(
t.identifier("global"),
t.identifier(t.toIdentifier(globalName)),
);
}
return memberExpression;
} | [
"MemberExpression() {\n let object = this.PrimaryExpression();\n\n while (this._lookahead.type === \".\" || this._lookahead.type === \"[\") {\n // MemberExpression '.' Identifier\n if (this._lookahead.type === \".\") {\n this._eat(\".\");\n const property = this.Identifier();\n object = {\n type: \"MemberExpression\",\n computed: false,\n object,\n property,\n };\n }\n\n if (this._lookahead.type === \"[\") {\n // MemberExpression '[' Expression ']'\n this._eat(\"[\");\n const property = this.Expression();\n this._eat(\"]\");\n object = {\n type: \"MemberExpression\",\n computed: true,\n object,\n property,\n };\n }\n }\n\n return object;\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 localCompletionSource(context) {\n let inner = dist_syntaxTree(context.state).resolveInner(context.pos, -1)\n if (dontComplete.indexOf(inner.name) > -1) return null\n let isWord =\n inner.name == 'VariableName' ||\n (inner.to - inner.from < 20 &&\n Identifier.test(context.state.sliceDoc(inner.from, inner.to)))\n if (!isWord && !context.explicit) return null\n let options = []\n for (let pos = inner; pos; pos = pos.parent) {\n if (ScopeNodes.has(pos.name))\n options = options.concat(getScope(context.state.doc, pos))\n }\n return {\n options,\n from: isWord ? inner.from : context.pos,\n validFor: Identifier\n }\n }",
"function generateConstantPUSH(memoryAddress) {\n return `\n@${memoryAddress}\nD=A\n@SP\nA=M\nM=D\n@SP\nM=M+1\n`;\n}",
"getConstantScopeRef(expression) {\n // If the expression is of the form `a.b.c` then we want to get the far LHS (e.g. `a`).\n let bindingExpression = expression;\n while (t.isMemberExpression(bindingExpression)) {\n bindingExpression = bindingExpression.object;\n }\n if (!t.isIdentifier(bindingExpression)) {\n return null;\n }\n // The binding of the expression is where this identifier was declared.\n // This could be a variable declaration, an import namespace or a function parameter.\n const binding = this.declarationScope.getBinding(bindingExpression.name);\n if (binding === undefined) {\n return null;\n }\n // We only support shared constant statements if the binding was in a UMD module (i.e. declared\n // within a `t.Function`) or an ECMASCript module (i.e. declared at the top level of a\n // `t.Program` that is marked as a module).\n const path = binding.scope.path;\n if (!path.isFunctionParent() && !(path.isProgram() && path.node.sourceType === 'module')) {\n return null;\n }\n return path;\n }",
"CallMemberExpression() {\n // Super call:\n if (this._lookahead.type == \"super\") {\n return this._CallExpression(this.Super());\n }\n\n // Member part, might be part of a call:\n const member = this.MemberExpression();\n\n // See if we have a call expression:\n if (this._lookahead.type === \"(\") {\n return this._CallExpression(member);\n }\n\n // Simple member expression:\n return member;\n }",
"function scopeCompletionSource(scope) {\n let cache = new Map()\n return (context) => {\n let path = completionPath(context)\n if (!path) return null\n let target = scope\n for (let step of path.path) {\n target = target[step]\n if (!target) return null\n }\n let options = cache.get(target)\n if (!options)\n cache.set(\n target,\n (options = enumeratePropertyCompletions(target, !path.path.length))\n )\n return {\n from: context.pos - path.name.length,\n options,\n validFor: Identifier\n }\n }\n }",
"static define(config) {\n let field = new StateField(\n nextID++,\n config.create,\n config.update,\n config.compare || ((a, b) => a === b),\n config\n )\n if (config.provide) field.provides = config.provide(field)\n return field\n }",
"function parseGlobal() {\n var name = t.identifier(getUniqueName(\"global\"));\n var type; // Keep informations in case of a shorthand import\n\n var importing = null;\n maybeIgnoreComment();\n\n if (token.type === _tokenizer.tokens.identifier) {\n name = identifierFromToken(token);\n eatToken();\n } else {\n name = t.withRaw(name, \"\"); // preserve anonymous\n }\n /**\n * maybe export\n */\n\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.export)) {\n eatToken(); // (\n\n eatToken(); // export\n\n var exportName = token.value;\n eatTokenOfType(_tokenizer.tokens.string);\n state.registredExportedElements.push({\n exportType: \"Global\",\n name: exportName,\n id: name\n });\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n /**\n * maybe import\n */\n\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.import)) {\n eatToken(); // (\n\n eatToken(); // import\n\n var moduleName = token.value;\n eatTokenOfType(_tokenizer.tokens.string);\n var _name3 = token.value;\n eatTokenOfType(_tokenizer.tokens.string);\n importing = {\n module: moduleName,\n name: _name3,\n descr: undefined\n };\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n /**\n * global_sig\n */\n\n\n if (token.type === _tokenizer.tokens.valtype) {\n type = t.globalType(token.value, \"const\");\n eatToken();\n } else if (token.type === _tokenizer.tokens.openParen) {\n eatToken(); // (\n\n if (isKeyword(token, _tokenizer.keywords.mut) === false) {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unsupported global type, expected mut\" + \", given \" + tokenToString(token));\n }();\n }\n\n eatToken(); // mut\n\n type = t.globalType(token.value, \"var\");\n eatToken();\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n if (type === undefined) {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Could not determine global type\" + \", given \" + tokenToString(token));\n }();\n }\n\n maybeIgnoreComment();\n var init = [];\n\n if (importing != null) {\n importing.descr = type;\n init.push(t.moduleImport(importing.module, importing.name, importing.descr));\n }\n /**\n * instr*\n */\n\n\n while (token.type === _tokenizer.tokens.openParen) {\n eatToken();\n init.push(parseFuncInstr());\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n return t.global(type, init, name);\n }",
"visitGlobal_stmt(ctx) {\r\n console.log(\"visitGlobal_stmt\");\r\n let globallist = [];\r\n for (var i = 0; i < ctx.NAME().length; i++) {\r\n globallist.push(this.visit(ctx.NAME(i)));\r\n }\r\n return { type: \"GlobalStatement\", globallist: globallist };\r\n }",
"buildStylingInstruction(sourceSpan, constantPool) {\n if (this.hasBindings) {\n return {\n sourceSpan,\n allocateBindingSlots: 0,\n reference: Identifiers$1.styling,\n buildParams: () => {\n // a string array of every style-based binding\n const styleBindingProps = this._singleStyleInputs ? this._singleStyleInputs.map(i => literal(i.name)) : [];\n // a string array of every class-based binding\n const classBindingNames = this._singleClassInputs ? this._singleClassInputs.map(i => literal(i.name)) : [];\n // to salvage space in the AOT generated code, there is no point in passing\n // in `null` into a param if any follow-up params are not used. Therefore,\n // only when a trailing param is used then it will be filled with nulls in between\n // (otherwise a shorter amount of params will be filled). The code below helps\n // determine how many params are required in the expression code.\n //\n // min params => styling()\n // max params => styling(classBindings, styleBindings, sanitizer)\n //\n const params = [];\n let expectedNumberOfArgs = 0;\n if (this._useDefaultSanitizer) {\n expectedNumberOfArgs = 3;\n }\n else if (styleBindingProps.length) {\n expectedNumberOfArgs = 2;\n }\n else if (classBindingNames.length) {\n expectedNumberOfArgs = 1;\n }\n addParam(params, classBindingNames.length > 0, getConstantLiteralFromArray(constantPool, classBindingNames), 1, expectedNumberOfArgs);\n addParam(params, styleBindingProps.length > 0, getConstantLiteralFromArray(constantPool, styleBindingProps), 2, expectedNumberOfArgs);\n addParam(params, this._useDefaultSanitizer, importExpr(Identifiers$1.defaultStyleSanitizer), 3, expectedNumberOfArgs);\n return params;\n }\n };\n }\n return null;\n }",
"function _globalize($regexp) {\n return new RegExp(String($regexp).slice(1, -1), \"g\");\n }",
"NewExpression() {\n this._eat(\"new\");\n return {\n type: \"NewExpression\",\n callee: this.MemberExpression(),\n arguments: this.Arguments(),\n };\n }",
"s(root, path) {\n let sourcemap = this.v(root,\n `${path ? path + '.' : ''}attributes.sourceMap[0]`, null);\n\n if (sourcemap) {\n sourcemap = this.convertSourcemap(sourcemap);\n }\n\n return sourcemap;\n }",
"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}",
"get(name) {\n if (this.current.hasOwnProperty(name)) {\n return this.current[name];\n } else {\n return this.builtins[name];\n }\n }",
"visitBuild_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function ModuleObj(myname, skipInit) {\r\n\r\n this.name = myname;\r\n\r\n this.allFuncs = new Array(); // list of all function is this module\r\n\r\n this.curFuncNum = 0; // function number user is working on\r\n\r\n // funtions start from this ID -- before this ID, we have global scope\r\n // grids. This is a constant. \r\n //\r\n this.FuncStartID = 2; // Functions start after global scope\r\n this.GlobalScopeID = 1; // global scope just before funcs start\r\n\r\n // It is important to create this 'global' seq# at the module level\r\n // because there are function args, module level variables, etc, we\r\n // have to create expressions for. However, we don't have this at the\r\n // ProgramObj level in order to facilitate module portability.\r\n //\r\n this.nextExprSeq = 1; // Seq # given to next ExprObj created\r\n\r\n // --------------- initialization --------------------------------\r\n\r\n if (!skipInit) {\r\n\r\n\t// Must be done afer initializing this.nextExprSeq\r\n\t//\r\n\tthis.templateFunc = new FuncObj(); // grid/func templates\r\n\tthis.globalFunc = new FuncObj(); // global (static) scope\r\n\r\n }\r\n\r\n // If this module is a library, the implementation of the library\r\n // is stored in this variable. This need not be saved. This should be\r\n // initialized when each library is loaded -- which should happen every\r\n // time a prog is loaded\r\n //\r\n this.libObj = null;\r\n\r\n}",
"ThisExpression() {\n this._eat(\"this\");\n return {\n type: \"ThisExpression\",\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION NAME : invitePeopleSeesion AUTHOR :Juvindle C Tina DATE : March 26, 2014 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : invite user to join the seesion PARAMETERS : | function invitePeopleSeesion(){
var sessionid = seletedSessionId.split("__");
var url = getURL('Console') + "action=getUserNameForInvitation&query={'MAINCONFIG': [{'sessionId': '"+sessionid[1]+"','user':'"+globalUserName+"'}]}";
$.ajax({
url: url,
dataType: 'html',
method: 'POST',
proccessData: false,
async:false,
success: function(data) {
//data = "{'MAINCONFIG':[{'UserExist':'jctina,csalanda','UsersNotExist':'rimartinez,jpmanauis'}]}";
data = data.replace(/'/g,'"');
var json = jQuery.parseJSON(data);
var mainconfig = json.MAINCONFIG[0];
inviteUserPopUp(mainconfig);
}
});
} | [
"function inviteMember(current_user, invite_user, list_id) {\n if(confirmInvite(invite_user)) {\n\tif(list_id) {\n\t var result = null;\n\t var xmlhttp = null;\n\t if (window.XMLHttpRequest) {\n\t\txmlhttp=new XMLHttpRequest();\n\t } else {\n\t\txmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n\t }\n\t \n\t xmlhttp.onreadystatechange=function() {\n\t\tif (xmlhttp.readyState==4 && xmlhttp.status==200) {\n\t\t result = xmlhttp.responseText;\n\t\t}\n\t }\n\t \n\t var param1 = \"inv=\".concat(invite_user);\n\t var param2 = \"&i=\".concat(list_id); \n\t var params = param1.concat(param2);\n\t xmlhttp.open(\"POST\", \"resources/invite-member.php\", true);\n\t xmlhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n\t xmlhttp.send(params);\n\t} else {\n\t //TODO \n\t //: if(targetListId) fails\n\t}\n\tdocument.getElementById('inviteMemberTextField').value='';\n } else {\n\t//DO SOMETHING\n\t//:if(confirmInvite(inviteUser) fails\n }\n}",
"async function inviteToOrganization (orgName, username, teamId) {\n/*\n@orgName the organization's name as a string (case-sensitive)\n@username should be a string reprenting the user's Github login ID\n@team is an integers which represents the team's Github Id\n*/\n try {\n // get the user's github id\n const userId = await getUserId(username)\n const data = await request('POST /orgs/:org/invitations', {\n org: orgName,\n invitee_id: userId,\n team_ids: [teamId], // this has to be in array form according to api\n headers: {\n authorization: `basic ${btoa(CREDENTIALS)}`,\n accept: 'application/vnd.github.dazzler-preview+json',\n },\n })\n\n return data\n /*\n\n Here we can experiment with inviting through email instead of userId\n\n */\n } catch (err) {\n // *** log error - to do: develop more sophisticated logging techniques\n // console.log(err)\n return err\n }\n}",
"async invite(channelId, users) {\n try {\n const res = await this.client.conversations.invite({\n channel: channelId,\n users,\n });\n } catch (err) {\n console.error(err);\n }\n }",
"function sendInvites(json, statusText) {\n\t$(\"table.team tr:last\").after(json.members_html);\n for (i = 0; i < json.members_ids.length; i++) {\n\t\t$(\"#member_\"+ json.members_ids[i]).highlightFade({start: '#FFFF99', speed: 2000});\n\t $(\"#member_\"+ json.members_ids[i] +\" a.tip\").link_tips();\n\t};\n\t$(\"div.list-people\").after(\"<div class='invited-sent'><h3>Invites sent!</h3><p>Sent invites to \"+ json.members_names+\". Don't forget to edit their permissions on the left.</p></div>\");\t \n\tresetInviteQueue();\n\tcloseContactSelect();\n\t$(\"input[name='invites[]']\").remove();\n\tremove_this_after($(\"div.invited-sent\"), 7000);\n}",
"inviteOtherUser (callback) {\n\t\tlet data = {\n\t\t\tteamId: this.team.id,\n\t\t\temail: this.userData[1].user.email\n\t\t};\n\t\tthis.apiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'post',\n\t\t\t\tpath: '/users',\n\t\t\t\tdata,\n\t\t\t\ttoken: this.userData[0].accessToken\n\t\t\t},\n\t\t\tcallback\n\t\t);\n\t}",
"function sendInvite(newfriendname) {\n\t// post to /addfriend/ where database takes care of sending invite\n\t\n\t\n\t$(\" <div />\" ).attr(\"id\",'confirm_invitation')\n\t.attr(\"title\", 'Confirm Invitation')\n\t.html(\n\t\t'<div id=\"myconfirmationinvitation\">' + \n\t\t'<table width=100%> <tr style=\"text-align: center;\"><td colspan=\"2\" style=\"height: 50px;\">' +\n\t\t'Do you want to send an invitation email? </td></tr>' +\n\t\t'<tr style=\"text-align: center;\">' +\n\t\t'<td style=\"width: 100px;\"> <a id=\"sendInvitebutton\" class=\"btn btn-success\" style=\"width: 60px;\"> <i class=\"icon-ok icon-white\"></i></a> </td>' +\n\t\t'<td style=\"width: 100px\"> <a id=\"nosendInvitebutton\" class=\"btn btn-danger\" style=\"width: 60px;\"> <i class=\"icon-remove icon-white\"></i></a></td> ' +\n\t\t'</tr></table></div>'\n\t\t\n\t)\n\t.appendTo($( \"#boxes\" ));\n\n\t$('#sendInvitebutton').click(\n\t\tfunction() {\n\t\t\tinvite(newfriendname);\n\t\t\t$('#confirm_invitation').dialog('destroy').remove()\n\t\t}\n\t);\n\t$('#nosendInvitebutton').click(\n\t\tfunction() {\n\t\t\t$('#confirm_invitation').dialog('destroy').remove()\n\t\t}\n\t);\n\t\n\t$('#confirm_invitation').dialog( {\n autoOpen: true,\n modal: true\n });\n}",
"invite(userId, invitedId) {\n // use date for sorted set ordering\n return new Promise((resolve, reject) => {\n this.client.zadd(\n `${this.namespace}:user:${invitedId}:${STATE_KEY.invited}`,\n Date.now(),\n userId,\n (err, res) => {\n if (err) { reject(err); }\n debug(`${userId} invited ${invitedId}`);\n return resolve(res);\n });\n });\n }",
"acceptInvite (n, callback) {\n\t\tconst company = this.expectedCompanies[n];\n\t\tthis.doApiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'put',\n\t\t\t\tpath: '/join-company/' + company.id,\n\t\t\t\ttoken: this.users[0].accessToken\n\t\t\t},\n\t\t\t(error, response) => {\n\t\t\t\tif (error) { return callback(error); }\n\t\t\t\tif (n === 0) {\n\t\t\t\t\t// because original user gets deactivated\n\t\t\t\t\tthis.token = this.users[0].accessToken = response.accessToken;\n\t\t\t\t}\n\t\t\t\tthis.expectedCompanies[n].accessToken = response.accessToken;\n\t\t\t\tcallback();\n\t\t\t}\n\t\t);\n\t}",
"async inviteUser () {\n\t\tthis.log('NOTE: Inviting user under one-user-per-org paradigm');\n\t\tconst inviterClass = UserInviter;\n\t\tthis.userInviter = new inviterClass({\n\t\t\trequest: this,\n\t\t\tteam: this.team,\n\t\t\tdelayEmail: this._delayEmail,\n\t\t\tinviteType: this.inviteType,\n\t\t\tuser: this.user,\n\t\t\tdontSendEmail: this.dontSendEmail\n\t\t});\n\n\t\tconst userData = {\n\t\t\temail: this.request.body.email.trim()\n\t\t};\n\t\tthis.invitedUsers = await this.userInviter.inviteUsers([userData]);\n\t\tconst invitedUserData = this.invitedUsers[0];\n\t\tthis.transforms.createdUser = invitedUserData.user;\n\t}",
"requestInvite(){\n let ic = new iCrypto()\n ic.createNonce(\"n\")\n .bytesToHex(\"n\", \"nhex\");\n let request = new Message(self.version);\n let myNickNameEncrypted = ChatUtility.encryptStandardMessage(this.session.settings.nickname,\n this.session.metadata.topicAuthority.publicKey);\n let topicNameEncrypted = ChatUtility.encryptStandardMessage(this.session.settings.topicName,\n this.session.metadata.topicAuthority.publicKey);\n request.headers.command = \"request_invite\";\n request.headers.pkfpSource = this.session.publicKeyFingerprint;\n request.headers.pkfpDest = this.session.metadata.topicAuthority.pkfp;\n request.body.nickname = myNickNameEncrypted;\n request.body.topicName = topicNameEncrypted;\n request.signMessage(this.session.privateKey);\n this.chatSocket.emit(\"request\", request);\n }",
"static async inviteUsers(company_id, user_emails) {\n\t\t// find company\n\t\tlet company = await models.Company.findByPk(company_id)\n\t\t// generate random hash\n\t\tlet hash = generator.getRandomString(40)\n\t\t// save hash to db\n\t\tawait models.InviteHash.create({ hash, company_id })\n\n\t\t// send email\n\t\tconst mg = mailgun({ apiKey: 'key-f25a884c247378aa8dd34083fe6e4b28', domain: 'sandbox454409b9d64449f7b661a00c48d6a721.mailgun.org' })\n\t\tconst data = {\n\t\t\tfrom: '<me@samples.mailgun.org>',\n\t\t\tto: user_emails,\n\t\t\tsubject: 'Hello',\n\t\t\ttext: `Dear user you have been invited in ${company.name} <a href=\"http://localhost:3000/company/join/${hash}/\">Join company by hash: ${hash}</a>`\n\t\t}\n\t\tmg.messages().send(data, function(error, body) {\n\t\t\tconsole.log(body)\n\t\t})\n\n\t\treturn true\n\n\t\t// // Generate test SMTP service account from ethereal.email\n\t\t// let testAccount = await nodemailer.createTestAccount()\n\t\t// // create reusable transporter object using the default SMTP transport\n\t\t// let transporter = nodemailer.createTransport({\n\t\t// \thost: 'smtp.ethereal.email',\n\t\t// \tport: 587,\n\t\t// \tsecure: false, // true for 465, false for other ports\n\t\t// \tauth: {\n\t\t// \t\tuser: testAccount.user, // generated ethereal user\n\t\t// \t\tpass: testAccount.pass // generated ethereal password\n\t\t// \t}\n\t\t// })\n\n\t\t// send mail with defined transport object\n\t\t// let info = await transporter.sendMail({\n\t\t// \tfrom: '\"Fred Foo ๐ป\" <foo@example.com>', // sender address\n\t\t// \tto: user_emails, // list of receivers\n\t\t// \tsubject: `Invitation from ${company.name}`, // Subject line\n\t\t// \ttext: `Dear user you have been invited in ${company.name}`, // plain text body\n\t\t// \thtml: `<a href=\"http://localhost:3000/company/join/${hash}/\">Join company by hash: ${hash}</a>` // html body\n\t\t// })\n\n\t\t// return nodemailer.getTestMessageUrl(info)\n\t}",
"function processInvitation(r) {\n rInvitation = r;\n isIncoming = rInvitation.get('direction') == 'Incoming';\n setResource(ucwa.get(rInvitation.link('conversation').href));\n threadId.set(rInvitation.get('threadId') + '');\n // in outgoing invitation /from points to the local participant\n // which must not be added to the .participants collection\n if (rInvitation.hasLink('from') && isIncoming) {\n var senderHref = rInvitation.link('from').href; // rel=participant\n var senderName = ucwa.get(senderHref).get('name', void 0);\n resolveParticipant(senderHref, senderName);\n }\n else if (rInvitation.hasLink('to') && !isIncoming) {\n var receiverHref = rInvitation.link('to').href; // rel=person\n var matchingParticipants = participants.filter(function (p) { return p.person[Internal.sHref] == receiverHref; });\n if (matchingParticipants.size() == 0) {\n var person = contactManager.get(receiverHref);\n var participant = createParticipantFromPersonOrUri(person);\n addParticipant(participant);\n }\n }\n state(isIncoming ? Conversation.State.Incoming : Conversation.State.Connecting);\n if (rInvitation.rel == 'onlineMeetingInvitation') {\n self.meeting = new Internal.OnlineMeeting({\n ucwa: ucwa,\n rInvitation: rInvitation,\n from: isIncoming ? participants(0) : localParticipant,\n conversation: self,\n contactManager: contactManager\n });\n changed.fire();\n }\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 manage_inviteables( inviteable_list ){\r\n\t\t\r\n\t\t$( '#friends_to_invite div.not_invited_yet div, #friends_to_invite div.already_invited div' )\r\n\t\t\t.addClass( 'not_inviteable_del' );\r\n\t\t\r\n\t\t$.each( inviteable_list, function(i, list) {\r\n\t\t\tvar id = parseInt( list.id );\r\n\t\t\tvar name = list.name;\r\n\t\t\tvar invited = list.invited;\r\n\t\t\t\r\n\t\t\tvar act_obj = $( '#inviteable_one_'+id );\r\n\t\t\tif ( typeof act_obj != 'undefined' && act_obj.length > 0 ) {\r\n\t\t\t\tact_obj.removeClass( 'not_inviteable_del' );\r\n\t\t\t\tif ( !invited )\r\n\t\t\t\t\tif ( typeof $( 'div.already_invited div#inviteable_one_'+id ) != 'undefined' && $( 'div.already_invited div#inviteable_one_'+id ).length > 0 ) {\r\n\t\t\t\t\t\tact_obj.fadeOut( 50, function(){\r\n\t\t\t\t\t\t\tact_obj.appendTo( '#friends_to_invite div.not_invited_yet' ).fadeIn( 50 );\r\n\t\t\t\t\t\t} );\r\n\t\t\t\t\t\tact_obj.data( 'invited', false );\r\n\t\t\t\t\t}\r\n\t\t\t} else\r\n\t\t\t\t$( '<div/>' )\r\n\t\t\t\t\t.attr( 'id', 'inviteable_one_'+id )\r\n\t\t\t\t\t.appendTo( '#friends_to_invite div.not_invited_yet' )\r\n\t\t\t\t\t.html( name )\r\n\t\t\t\t\t.data( 'invited', false )\r\n\t\t\t\t\t.click( function(){\r\n\t\t\t\t\t\tvar o_this = $( this );\r\n\t\t\t\t\t\tif (!o_this.data( 'invited' )) {\r\n\t\t\t\t\t\t\to_this.fadeOut( 50, function(){\r\n\t\t\t\t\t\t\t\to_this.appendTo( '#friends_to_invite div.already_invited' ).fadeIn( 50 );\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$.ajax({\r\n\t\t\t\t\t\t\t\ttype: 'POST',\r\n\t\t\t\t\t\t\t\turl: 'send_invite.php',\r\n\t\t\t\t\t\t\t\tdata: {\r\n\t\t\t\t\t\t\t\t\t'id': id\r\n\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\tsuccess: function( data ) {\r\n\t\t\t\t\t\t\t\t\tif ( data!=0 ) {\r\n\t\t\t\t\t\t\t\t\t\t$( '#hv_alert_wrapper' ).hv_alert( 'show_alert', {\r\n\t\t\t\t\t\t\t\t\t\t\t'message': c['error_invite']+' '+data\r\n\t\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\t\to_this.fadeOut( 50 );\r\n\t\t\t\t\t\t\t\t\t} else\r\n\t\t\t\t\t\t\t\t\t\to_this.data( 'invited', true );\r\n\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\terror: function() {\r\n\t\t\t\t\t\t\t\t\t$( '#hv_alert_wrapper' ).hv_alert( 'show_alert', {\r\n\t\t\t\t\t\t\t\t\t\t'message': c['error_invite']+' '+data\r\n\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\to_this.fadeOut( 50 );\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t});\r\n\t\t$( '.not_inviteable_del' ).fadeOut( 50, function(){\r\n\t\t\t$( this ).remove();\r\n\t\t} );\r\n\t\t\r\n\t}",
"function inviteUserPopUp(mainconfig){\n\t$( \"#invitePeoplePopUp\").dialog({\n\t\tmodal: true,\n\t\tautoResize:true,\n\t\twidth: \"510\",\n\t\theight: \"500\",\n\t\topen: function(event, ui){ \n\t\t\t$(\".ui-dialog-titlebar-close\").show();\n\t\t}\n\t});\n\t$(\"#invitePeoplePopUp\").empty().load(\"pages/ConfigEditor/inviteuser.html\",function (event){\n\t\tvar txt= \"\";\n\t\tvar strArr = seletedSessionId.split(\"__\");\n\t\tfor(var t=0; t<validDevices.length; t++){\n\t\t\tif(seletedSessionId[0] == validDevices[t].DeviceId){\n\t\t\t\ttxt = validDevices[t].DeviceName;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tuserExistArray = [];\n\t\tuserNotExistArray = [];\n\t\tvar userexist = mainconfig.UserExist;\n\t\tvar usernotexist = mainconfig.UsersNotExist;\n\t\tif(userexist != null && userexist != undefined){\n\t\t\tvar str = userexist.split(\",\");\n\t\t\tfor(var t=0; t<str.length; t++){\n\t\t\t\tif (!checkArray(str[t],userExistArray)){\n\t\t\t\t\tuserExistArray.push(str[t]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(usernotexist != null && usernotexist != undefined){\n\t\t\tvar str = usernotexist.split(\",\");\n\t\t\tfor(var t=0; t<str.length; t++){\n\t\t\t\tif (!checkArray(str[t],userNotExistArray)){\n\t\t\t\t\tuserNotExistArray.push(str[t]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcreatetableforinvitation();\n\t});\n\n}",
"function processInvitation() {\n // if another tab starts a conversation, all other tabs get the\n // outgoing invitation event (with no message link); and they\n // do not need to process the toast message (toast message will\n // be sent to them via the multitab data channel)\n if (isIncoming()) {\n processFirstMessageInInvitation();\n state(cNotified);\n }\n else {\n // if the outgoing invitation contains a message, there will be\n // \"message completed\" event shortly after this invitation event:\n // to recognize that message, the rel=messaging needs to be known\n if (rInvitation.hasLink('messaging'))\n setResource(ucwa.get(rInvitation.link('messaging').href));\n state(cConnecting);\n }\n // the invitation can be cancelled by the remote party\n // and this must be somehow reflected in the modality\n ucwa.wait({\n type: 'completed',\n status: 'Failure',\n target: { rel: 'messagingInvitation', href: rInvitation.href }\n }).then(function (event) {\n invitationMessage = null;\n state(Internal.Modality.State.Disconnected, event.reason);\n });\n // the invitation can be accepted by the server without the client's consent\n ucwa.wait({\n type: 'completed',\n status: 'Success',\n target: { rel: 'messagingInvitation', href: rInvitation.href }\n }).then(function (event) {\n // if the state is still Notified and the invitation is incoming,\n // then the \"completed\" event is sent because another endpoint has\n // accepted the request as the accept() method would've changed\n // the state to Connecting; if the invitation is outgoing because\n // it was started on another tab, this tab must also recognize the\n // completion of the invitation and move to the Connected state\n if (state() == cNotified || state() == cConnecting && !isIncoming()) {\n setResourceAndObserveState(rInvitation.link('messaging').href);\n state(Internal.Modality.State.Connected, event.reason);\n // if the invitation was auto accepted, all the tabs become active\n // to display incoming messages in the UI, but once one of the tabs\n // sends a message, other tabs get the \"message completed\" event\n // and become disabled\n if (isIncoming())\n isTabActive(true, event.reason);\n }\n }).catch(function (error) {\n state(Internal.Modality.State.Disconnected, error);\n });\n }",
"inviteUserToCompanies (callback) {\n\t\tBoundAsync.timesSeries(\n\t\t\tthis,\n\t\t\t2,\n\t\t\tthis.inviteUserToCompany,\n\t\t\tcallback\n\t\t);\n\t}",
"function responseGameInvitation(e){\n\tvar recipientName = $(this).data(\"name\");\n\tif(recipientName == undefined || localStorage.gameTurn != undefined){\n\t\treturn false;\n\t}\n\tif(userNameChecker(recipientName)){\n\t\tvar recipientGameObject = getGameObject(recipientName);\n\t\tvar data = {\n\t\t\t\"recipientName\": recipientName,\n\t\t\t\"session\" : localStorage.sessionId,\n\t\t\t\"gameNum\" : recipientGameObject.gameNum\n\t\t};\n\t\tlocalStorage.setItem(\"gameTurn\", 0);\n\t\tperformPostRequest(\"invitation-response.php\", data, function(data){\n\t\t\tswitch(data.status) {\n\t\t\t\tcase 470:\n\t\t\t\t\tlocalStorage.removeItem('gameTurn');\n\t\t\t\t\tlogOut();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 200:\n\t\t\t\t\tlocalStorage.setItem(\"gameAreaClickCounter\", 0);\n\t\t\t\t\tlocalStorage.setItem(\"currentGameNum\", recipientGameObject.gameNum);\n\t\t\t\t\tbeginGame(recipientName);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 400:\n\t\t\t\t\tlocalStorage.removeItem('gameTurn');\n\t\t\t\t\tshowErrorMessage(\"ะขะพะทะธ ะฟะพััะตะฑะธัะตะป ะฒะตัะต ะธะณัะฐะต ั ะดััะณ ะธะณัะฐั!\", 1);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlocalStorage.removeItem('gameTurn');\n\t\t\t}\n\t\t});\n\t}\n\telse\n\t{\n\t\tshowErrorMessage(\"ะัะทะฝะธะบะฝะฐ ะฟัะพะฑะปะตะผ ะฟัะธ ะพะฟะธัะฐ ะทะฐ ะพัะณะพะฒะพั ะฝะฐ ัะฐะทะธ ะฟะพะบะฐะฝะฐ ะทะฐ ะธะณัะฐ!\");\n\t}\n}",
"function C101_KinbakuClub_RopeGroup_FriendOfAFriend() {\n\tif (ActorGetValue(ActorLove) >= 3) {\n\t\tOverridenIntroText = GetText(\"StayRightThere\");\n\t\tC101_KinbakuClub_RopeGroup_NoActor()\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 661;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clears the callback in charge of hiding the component after timeout | function clearHideTimeout() {
if (timeoutID === null) {
return;
}
window.clearTimeout(timeoutID);
timeoutID = null;
} | [
"hide() {\n\t\tlet _ = this\n\n\t\t_.timepicker.overlay.classList.add('animate')\n\t\t_.timepicker.wrapper.classList.add('animate')\n\t\tsetTimeout(function () {\n\t\t\t_._switchView('hours')\n\t\t\t_.timepicker.overlay.classList.add('hidden')\n\t\t\t_.timepicker.overlay.classList.remove('animate')\n\t\t\t_.timepicker.wrapper.classList.remove('animate')\n\n\t\t\tdocument.body.removeAttribute('mdtimepicker-display')\n\n\t\t\t_.visible = false\n\t\t\t_.input.focus()\n\n\t\t\tif (_.config.events && _.config.events.hidden)\n\t\t\t\t_.config.events.hidden.call(_)\n\t\t}, 300)\n\t}",
"dismissPanel() {\n this.setState({isVisible: false, messages: [], timeoutID: null})\n }",
"hide() {\n\t\tthis.element.style.visibility = 'hidden';\n\t}",
"hideSpinner() {\n this.spinnerVisible = false;\n }",
"function clearTimeOutHint() {\n clearTimeout(tHint);\n }",
"function clearMonitorTimeout() {\n serlog('Clear disp. off');\n consolelog('Clear display off');\n if (monitorTimeoutId != null) {\n clearTimeout(monitorTimeoutId);\n\tmonitorTimeoutId = null;\n }\n}",
"_hide() {\n this._updateTriggerWidth();\n if (this._settings.get_boolean('dock-fixed')) {\n return;\n }\n\n if (this._isHovering() || (this._hoveringDash && !Main.overview._shown)) {\n return;\n }\n\n let intellihideAction = this._settings.get_enum('intellihide-action');\n if (!Main.overview._shown && intellihideAction == IntellihideAction.SHOW_FULL && !this._autohideStatus) {\n return;\n }\n\n let overviewAction = this._settings.get_enum('overview-action');\n if (Main.overview._shown && overviewAction == OverviewAction.SHOW_FULL && !this._autohideStatus) {\n return;\n }\n\n // Only hide if dock is shown, is showing, or is partially shown\n if (this._dockState == DockState.SHOWN || this._dockState == DockState.SHOWING || this._slider.slidex > 0) {\n this._removeAnimations();\n\n // If the dock is shown, wait this._settings.get_double('show-delay') before hiding it;\n // otherwise hide it immediately.\n let delay = 0;\n if (this._dockState == DockState.SHOWN)\n delay = this._settings.get_double('hide-delay');\n\n if (Main.overview._shown && Main.overview.viewSelector._activePage == Main.overview.viewSelector._workspacesPage) {\n this._animateOut(this._settings.get_double('animation-time'), delay, false);\n } else {\n this._animateOut(this._settings.get_double('animation-time'), delay, this._autohideStatus);\n }\n }\n }",
"onPopupMouseLeave() {\n this.delaySetPopupVisible(false, this.props.delayHide);\n }",
"function participants_view_hide() {\n\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"rgba(0,0,0,.2)\";\n\tsetTimeout(function() {\n\t\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"transparent\";\n\t\tparticipants_view_visible = false;\n\t\tDOM(\"PARTICIPANTS_VIEW\").style.top = \"-100%\";\n\t\tsetTimeout(function() {\n\t\t\tDOM(\"PARTICIPANTS_VIEW\").style.display = \"none\";\n\t\t}, 500);\n\t}, 50);\n}",
"function hidePopUp(doneText = \"Done!\", type = '')\r\n{\r\n if (type == 'hide')\r\n {\r\n $(\"#timerStopPageOverlay > .popUpContainer\").removeClass(\"showPopUp\");\r\n setTimeout(function() {\r\n $(\"#timerStopPageOverlay\").removeClass(\"timerStopQuestion\");\r\n }, 1000);\r\n }\r\n else{\r\n $(\".questionLabel\").html(doneText);\r\n $('.loadingStopTimer').addClass('SavingDone');\r\n $('.loadingStopTimer').removeClass('animationCirle');\r\n setTimeout(function() {\r\n $(\"#timerStopPageOverlay > .popUpContainer\").removeClass(\"showPopUp\");\r\n setTimeout(function() {\r\n $(\"#timerStopPageOverlay\").removeClass(\"timerStopQuestion\");\r\n }, 1000);\r\n }, 3000);\r\n }\r\n\r\n}",
"cancelAutoClose() {\n var button = this.getJQueryObject().find(\".timeout\");\n\n if(this.timeout != null) {\n button.hide();\n clearInterval(this.timeout);\n }\n }",
"show() {\n\t\tthis.element.style.visibility = '';\n\t}",
"hide() {\n\t\tthis.activityIndicator.hide();\n\n\t\tif (!this.isAndroid) {\n\t\t\tthis.containerView.animate({\n\t\t\t\topacity: 0.0\n\t\t\t}, () => {\n\t\t\t\tthis.view.remove(this.containerView);\n\t\t\t});\n\t\t}\n\t}",
"function hideResult() {\n resultWrapper.css(\"opacity\", 0)\n resultWrapper.css(\"pointer-events\", \"none\")\n}",
"componentWillUnmount() {\n this.fadeOut();\n }",
"destroy() {\n // Animate the notification\n this.frame.fadeOut( \"fast\", function() {\n // Remove it from the DOM\n this.remove();\n });\n }",
"hideVolumeWidget(e) {\n\n StateManager.ResetModal();\n\n }",
"function showMessage() {\n document.getElementById('errorMsgDiv').hidden = false;\n\n setTimeout(function () {\n document.getElementById('errorMsgDiv').hidden = true;\n }, 3000);\n}",
"function hideLoading() {\n\t\tanimate(loadingDiv, {\n\t\t\topacity: 0\n\t\t}, {\n\t\t\tduration: options.loading.hideDuration,\n\t\t\tcomplete: function() {\n\t\t\t\tcss(loadingDiv, { display: NONE });\n\t\t\t}\n\t\t});\n\t\tloadingShown = false;\n\t}",
"displayUnlayoutUI_() {\n this.state = AdDisplayState.NOT_LAID_OUT;\n this.baseInstance_.deferMutate(() => {\n if (this.state != AdDisplayState.NOT_LAID_OUT) {\n return;\n }\n this.baseInstance_.togglePlaceholder(true);\n this.baseInstance_.toggleFallback(false);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send an `is_complete_request` message. Notes See [Messaging in Jupyter]( Fulfills with the `is_complete_response` content when the shell reply is received and validated. | requestIsComplete(content) {
let options = {
msgType: 'is_complete_request',
channel: 'shell',
username: this._username,
session: this._clientId
};
let msg = messages_1.KernelMessage.createShellMessage(options, content);
return Private.handleShellMessage(this, msg);
} | [
"async complete(result = \"unknown\") {\n if (!PaymentCompleteEnum.includes(result)) {\n throw new TypeError(\"Invalid argument value: \" + result);\n }\n if (this[_complete]) {\n throw new DOMException(\"Response already completed\", \"InvalidStateError\");\n }\n this[_complete] = true;\n await paymentSheet.requestClose(result);\n }",
"function respond() {\r\n if (!responded) {\r\n responded = true;\r\n self.callback.apply(null, arguments);\r\n }\r\n }",
"function ServerBehavior_getIsIncomplete()\n{\n return this.incomplete;\n}",
"get isReplyRequired() {\n return false;\n }",
"function completed () {\n return this.resolved.length === this.chain.__expectations__.length;\n}",
"function anotherRequestPending() {\n if (requestPending) {\n $scope.lastActionOutcome = $scope.lastActionOutcome + 'Please wait. ';\n return true;\n }\n requestPending = true;\n return false;\n }",
"async isBusy() {\n return new Promise((resolve, reject) => {\n this.rpc.stdin.write('busy' + os.EOL);\n this.rpc.stdout.once('data', (data) => {\n data = data.toString().trim();\n if ((typeof data == 'boolean' && data) || data == \"true\") {\n resolve(true)\n } else {\n resolve(false)\n }\n });\n });\n\n }",
"function send_CompleteTodo(todo) {\n server.emit('completeTodo', todo)\n input.focus();\n}",
"function sendNextProblemInputResponse (arg) {\n // send an InputResponse to the server with NO. callback fn should be processNextProblemResult\n servletGet(\"InputResponseNextProblemIntervention\",\"&probElapsedTime=\"+globals.probElapsedTime + \"&destination=\"+globals.destinationInterventionSelector + arg,\n processNextProblemResult)\n}",
"function completeGetRequest(requestId, optErrorName) {\n let response = {\n requestId: requestId,\n };\n if (optErrorName) {\n response.error = {name: optErrorName, message: TEST_ERROR_MESSAGE};\n } else {\n response.responseJson = GET_ASSERTION_RESPONSE_JSON;\n }\n return chrome.webAuthenticationProxy.completeGetRequest(response);\n}",
"function markReqComplete(reqId) {\n if (prereqsComplete(reqId, this.reqsCompleted)) {\n // push a new object onto the reqsCompleted array of the scout\n // should include a reqId and the current date\n var completedReq = {\n reqId: reqId,\n dateCompleted: new Date()\n };\n this.reqsCompleted.push(completedReq);\n return true;\n }\n return false;\n}",
"function prereqsComplete(reqId, completedReqIds) {\n //check only immediate prereqs\n var req = masterReqById[reqId];\n var prereqsCompleteCount = 0;\n for (var i = 0; i < req.prereqs.length; i++) {\n // increase prereqsCompleteCount by 1 each time we find one that is complete\n if (completedReqIds.indexOf(req.prereqs[i]) !== -1) {\n prereqsCompleteCount++;\n }\n }\n // check to make sure we completed enough prereqs\n var result = (prereqsCompleteCount >= req.numReqPrereqs);\n return result;\n}",
"function sendInterventionDialogYesNoConfirmInputResponse (event, fn, userInput) {\n\n incrementTimers(globals);\n servletFormPost(event, \"&probElapsedTime=\"+globals.probElapsedTime + \"&destination=\"+globals.destinationInterventionSelector + \"&userInput=\"+userInput,\n fn) ;\n}",
"get isCompleteUpdate() {\n // XXX: Bug 514040: _ums.isCompleteUpdate doesn't work at the moment\n if (this.activeUpdate.patchCount > 1) {\n var patch1 = this.activeUpdate.getPatchAt(0);\n var patch2 = this.activeUpdate.getPatchAt(1);\n\n return (patch1.URL == patch2.URL);\n } else {\n return (this.activeUpdate.getPatchAt(0).type == \"complete\");\n }\n }",
"function CompleteQuest () {\n\tif(coins >= 5){\n\n\t\t//This tells us that the quest is complete and ready to be turned in.\n\t\t_questDone = true;\n\t\t//This changes what our NPC will say now that the quest is finished and ready to be turned in.\n\t\t_npcs.NPCList[0].npcStage = 2;\n\t\t//This changes our quest log's details.\n\t\t_quests.QuestList[0].questStage = 2;\n\t}\n\telse {\n\t\t_questDone = false;\n\t}\n}",
"function completeQuestionnaire(con, aid, qid, callback){\n var sql = \"UPDATE questionnaire_animal SET done = true WHERE aid=\" + aid + \" AND qid=\" + qid;\n con.query(sql, function(err, result){\n if (err) {\n callback({status: 'failure'});\n }\n else {\n callback({status: 'success'});\n }\n console.log(\"Owner of animal \" + aid + \" completed survey \" + survey_id);\n });\n}",
"isComplete() {\n return this.selection != null;\n }",
"function markGoalComplete() {\n\t\tprops.markGoalComplete(props.goalId);\n }",
"function getServerStatus(){ \n\tvar client;\n\tclient = configureBrowserRequest(client);\t\n\tclient.open(\"POST\", \"?server-state\", true);\n\tclient.send();\n\t\n\tclient.onreadystatechange = function() {\n\t\tif(client.readyState == 4 && client.status == 200) {\n\t\t\tdocument.getElementById(\"server-status\").innerHTML = \"Conectado\";\n\t\t}\n\t\telse\n\t\t\tdocument.getElementById(\"server-status\").innerHTML = \"Desconectado\";\n\t}\n}",
"function successResponse()\n{\n // Finished\n return newResponse(true);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns section that belongs to the given subsection | getDisplayedSection(displayedSubsection) {
/* Returns the section that the user is currently viewing. */
return this.state.courseSidebar.sections.find((element) => {
return element.id === displayedSubsection.section_id
})
} | [
"getNextSubsection(section, subsection) {\n if (!section || !subsection) {\n return\n }\n\n // If not the last subsection in section, return the next subsection in section\n if (!isLast(section.subsections, subsection)) {\n const nextSubsection = section.subsections[subsection.position]\n return nextSubsection\n // If the last subsection, but section is not the last in the course, return\n // the first subsection in the next section\n } else if (!isLast(this.state.courseSidebar.sections, section)) {\n const nextSection = this.state.courseSidebar.sections[section.position]\n const nextSubsection = nextSection.subsections[0]\n return nextSubsection\n // If this is the last subsection and section in the course, return the given subsection\n } else {\n return subsection\n }\n }",
"function getSection( sectionPos ) {\r\n\t\treturn sections.eq( sectionPos );\r\n\t}",
"function getSectionByAnchor(sectionAnchor){var section=$(SECTION_SEL+'[data-anchor=\"'+sectionAnchor+'\"]',container)[0];if(!section){var sectionIndex=typeof sectionAnchor!=='undefined'?sectionAnchor-1:0;section=$(SECTION_SEL)[sectionIndex];}return section;}",
"function getSemanticSection(src,section,major,minor,sub) {\n var re,match,content = src;\n if(section) {\n re = new RegExp(\"(\\\\/\\\\*\\\\*+\\\\n\\\\s*\"+section+\"\\\\s*\\\\n\\\\*\\\\*+\\\\*\\\\/(.|\\\\n)*?(?=(\\\\/\\\\*\\\\*+\\\\n)|$))\",\"i\");\n match = content.match(re);\n content = match && match[1] || \"\";\n }\n \n if(major) {\n re = new RegExp(\"(\\\\/\\\\*\\\\-+\\\\n\\\\s*\"+major+\"\\\\s*\\\\n\\\\-+\\\\*\\\\/(.|\\\\n)*?(?=(\\\\/\\\\*\\\\-+\\\\n)|$))\",\"i\");\n match = content.match(re);\n content = match && match[1] || \"\";\n }\n if(minor) {\n re = new RegExp(\"(\\\\/\\\\*\\\\-{3}\\\\s*\"+minor+\"\\\\s*\\\\-{3}\\\\*\\\\/(.|\\\\n)*?(?=(\\\\/\\\\*\\\\-{3})|$))\",\"i\");\n match = content.match(re);\n content = match && match[1] || \"\";\n }\n if(sub) {\n re = new RegExp(\"(\\\\/\\\\*\\\\s*\"+sub+\"\\\\s*\\\\*\\\\/(.|\\\\n)*?(?=(\\\\/\\\\*)|$))\",\"i\");\n match = content.match(re);\n content = match && match[1] || \"\";\n }\n return content;\n}",
"getFirstSection(song = state.loadedSong) {\n if (!player.songHadAnySections(song))\n return false;\n if (Array.isArray(song.composition) && song.composition[0] && song.sections[song.composition[0]])\n return song.sections[song.composition[0]];\n return song.sections[Object.keys(song.sections)[0]];\n }",
"function getCurrentSection() {\r\n\t\tconst currentSectionPos = content.slick( \"slickCurrentSlide\" );\r\n\t\treturn sections.eq( currentSectionPos );\r\n\t}",
"displaySubsection(id, componentPosition) {\n const path = APIRoutes.getSubsectionPath(id)\n\n request.get(path, (response) => {\n const length = response.components.length\n\n const displayedSection = this.getDisplayedSection(response)\n\n let displayedComponent\n // If subsection is incomplete and componentPosition is null, use response.current_component\n if (!componentPosition && !response.is_complete) {\n displayedComponent = response.current_component\n // If subsection is complete and componentPosition is -1, get the last component\n } else if (response.is_complete || componentPosition == -1) {\n displayedComponent = response.components[length - 1]\n // If componentPosition is given, set displayedComponent based on given position\n } else {\n displayedComponent = response.components[componentPosition - 1]\n }\n this.setState({\n displayedSubsection: response,\n displayedComponent: displayedComponent,\n displayedSection: displayedSection,\n })\n }, (error) => {\n console.log(error)\n })\n }",
"function matchTagToSection(sectionlist, tag) {\n\t\n\tvar sectionlength = sectionlist.length;\n\t\n\tfor (var i = 0; i < sectionlength; i++) {\n\t\tif (sectionlist[i].includeTag(tag)) {\n\t\t\treturn sectionlist[i];\n\t\t}\n\t}\n\t\n\treturn false;\n}",
"function GetSurveySection(surveyId, language, respondentValue, transId) {\n\n\t\t\t\tvar firstSectionObj = {\n\t\t\t\t\t\"SurveyId\": surveyId,\n\t\t\t\t\t\"Language\": language,\n\t\t\t\t\t\"MemberId\": respondentValue,\n\t\t\t\t\t\"RespondentTransId\": transId,\n\t\t\t\t\t\"RespondentTypeId\": 1\n\t\t\t\t}\n\n\t\t\t\tmemberDataService.getSurveySection(firstSectionObj).success(function (data) {\n\n\t\t\t\t\tsetInitialValues(data);\n\n\t\t\t\t}).error(function (error) {\n\t\t\t\t\t$scope.SurveyName = \" Survey Not Available\";\n\t\t\t\t\t$scope.SurveyError = true;\n\t\t\t\t\t$scope.ErrorMsg = error;\n\t\t\t\t\tconsole.log(error);\n\t\t\t\t});\n\n\t\t\t}",
"function getNextSection( prefix ) {\r\n\r\n // Make sure the prefix is actually in the current action.\r\n if ( ! startsWith( prefix ) ) {\r\n\r\n return( null );\r\n\r\n }\r\n\r\n // If the prefix is empty, return the first section.\r\n if ( prefix === \"\" ) {\r\n\r\n return( sections[ 0 ] );\r\n\r\n }\r\n\r\n // Now that we know the prefix is valid, lets figure out the depth\r\n // of the current path.\r\n var depth = prefix.split( \".\" ).length;\r\n\r\n // If the depth is out of bounds, meaning the current action doesn't\r\n // define sections to that path (they are equal), then return null.\r\n if ( depth === sections.length ) {\r\n\r\n return( null );\r\n\r\n }\r\n\r\n // Return the section.\r\n return( sections[ depth ] );\r\n\r\n }",
"function CheckForActiveSection() {\n\n let Act_Section = Sections_Array[0];\n TopValue = 400;\n for (let section of Sections_Array) {\n\n let Sec_Bounding = section.getBoundingClientRect();\n //console.log(Sec_Bounding.top); --> for debugging\n if (Sec_Bounding.top < TopValue & Sec_Bounding.top > -200) {\n TopValue = Sec_Bounding.top;\n Act_Section = section;\n return Act_Section;\n } else {\n Act_Section = 1;\n }\n };\n /**\n * // For Debuging only\n *console.log(`Check For Active Section : Debuging Message -> ${Act_Section.id}is Active`);\n */\n //console.log(Act_Section);\n return Act_Section;\n}",
"function showSection(path) {\n path.shift();\n var wrapper = $('.manual .chapter-content .sub-section-wrapper');\n $.each(path, function(i, num) {\n var item = $(wrapper).children('.sub-section-item').get(num);\n $(item).trigger('click');\n wrapper = $(item).next().next();\n })\n}",
"function deeplinkToSection( ){\r\n\r\n\r\n $('.container').each(function () {\r\n // Helper variables\r\n var sectionIndex = 0;\r\n var deepLinkIndex = 0;\r\n var deepLinkSection = getDeepLinkSection();\r\n\r\n\r\n\r\n // Depending on the type of container,\r\n // set values for the selector we wil use\r\n // to find the section index.\r\n var containerSelector = \"\";\r\n var containerType = \"tabs\";\r\n\r\n if (isAccNav($(this))) {\r\n containerSelector = \"h3\";\r\n containerType = \"accordion\";\r\n } else if (isTabNav($(this))) {\r\n containerSelector = \"ul>li\";\r\n containerType = \"tabs\";\r\n }\r\n\r\n\r\n // Now we know what kind of container it is,\r\n // we can loop through the relevant sections\r\n // and check for a match against the hash value\r\n $(this).find(containerSelector).each(function () {\r\n\r\n if ($(this).data(\"sectionName\") === deepLinkSection) {\r\n deepLinkIndex = sectionIndex;\r\n return false;\r\n }\r\n\r\n sectionIndex++;\r\n });\r\n\r\n $(this)[containerType](\"option\", \"active\", deepLinkIndex);\r\n\r\n });\r\n\r\n }",
"function getSub (tag){\n var sub = \"\";\n for(var i = 0; i < tags.length; ++i){\n if(tags[i].name == tag) sub = tags[i].Sub;\n }\n return sub;\n }",
"function fnLoadPartOfSubSection()\n{\n\t\n\tdocument.forms[0].action=\"partOfAction.do?method=SubSectionLoad\";\n\tdocument.forms[0].submit();\n\t\n}",
"createPlayableSection(section) {\n var playableSection = state.playableSections[section.name] = [];\n section.tracks.forEach(track => {\n var instrument = library.instruments[track.instrument];\n track.notes.forEach(note => {\n var time = 0;\n // Starting to understand this next line. shortest time we'll ever need is about 30ms\n // At 120 bpm, that's the time between 32nd notes, which will only get played for crazy fast doubles\n // But we can have triplets at the 16th level\n // Which makes sense, because that leaves the quarter notes untouched\n // Which is typically where the pulse is\n // And therefore switching from 4 to 3 between the pulse is dank\n note.time.forEach((count, level) => time += player.convertNotationToSteps(count, level)); // 1,0, 4,1\n if (playableSection[time])\n playableSection[time].push(instrument.notes[note.note].howl);\n else\n playableSection[time] = [instrument.notes[note.note].howl];\n });\n });\n return playableSection;\n }",
"function extractSections() {\n for (var i = 0; i < nytResponse.results.length; i++) {\n var s = nytResponse.results[i].section;\n append(sections, s);\n }\n\n}",
"function parseText(header, section) {\r\n let textArray = [];\r\n let indexArray = [];\r\n //get indexes of text breaks into sections based on header\r\n for (let i = 0; i < section.text.length; i++) {\r\n if (section.text.substr(i, header.length) == header && section.text.charAt(i + header.length) != \"#\" && section.text.charAt(i - 1) != \"#\" ) {\r\n indexArray.push(i);\r\n }\r\n }\r\n //get name if there is one after the header, break text, push into array\r\n for (let i = 0; i < indexArray.length; i++) {\r\n let pos = indexArray[i] + header.length;\r\n let name = \"\";\r\n for (let j = pos; j < section.text.length; j++) {\r\n if (section.text.charAt(j) == \"\\n\") {\r\n break;\r\n }\r\n name += section.text.charAt(j);\r\n }\r\n let end = 0;\r\n if (i == indexArray.length - 1) {\r\n end = section.text.length;\r\n } else {\r\n end = indexArray[i + 1];\r\n }\r\n textArray.push({\"name\": name, \"text\": section.text.substring(pos, end)});\r\n }\r\n\r\n if (textArray.length > 0) {\r\n for (let i = 0; i < textArray.length; i++) {\r\n section.sections.push({\r\n \"name\": textArray[i].name,\r\n \"id\": section.id + \".\" + i,\r\n \"text\": textArray[i].text,\r\n \"sections\": [],\r\n \"level\": section.level + 1,\r\n \"header\": header + \"#\",\r\n \"data\": {\r\n \"annotations\": [],\r\n /*\r\n {\r\n \"text\"\r\n \"start\"\r\n \"end\"\r\n }\r\n */\r\n \"highlights\": [],\r\n /*\r\n {\r\n \"key\"\r\n \"text\"\r\n \"start\"\r\n \"end\"\r\n }\r\n */\r\n \"topics\": []\r\n /*\r\n {\r\n \"key\"\r\n \"text\"\r\n \"start\"\r\n \"end\"\r\n }\r\n */\r\n }\r\n });\r\n }\r\n //recursively call on each section\r\n for (let i = 0; i < section.sections.length; i++) {\r\n parseText(section.sections[i].header, section.sections[i]);\r\n }\r\n }\r\n\r\n}",
"sub() {\n return styles[sub[this.id]];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Does the jQueryspecific responseText checking on the xhr for errors | _handleErrorResponse(xhr, callback) {
var response = xhr.responseText;
if (_.isString(response) && response !== "") {
try {
response = JSON.parse(response);
} catch (e) {
response = {
error: e
};
}
}
callback(response, xhr);
} | [
"function handleXhrError(response, ioArgs) {\n if(response instanceof Error){\n if(_ldc) _ldc.hide();\n if(response.dojoType == \"cancel\"){\n //The request was canceled by some other JavaScript code.\n console.debug(\"Request canceled.\");\n }else if(response.dojoType == \"timeout\"){\n //The request took over 5 seconds to complete.\n console.debug(\"Request timed out.\");\n }else{\n //Some other error happened.\n console.error(response);\n if(djConfig.isDebug) alert(response.toSource());\n }\n }\n}",
"function error(status) {\n\tdisplayLoading('none');\n\tvar message = \"something wrong, THIS IS HTTP \" + status + \" ERROR\";\n\tdocument.getElementById('errors').innerHTML = message;\n}",
"function httpErrors(errorNumber) {\n var text = '<span class=\"glyphicon glyphicon-exclamation-sign\"></span>';\n switch (errorNumber) {\n case 400:\n // Bad request.\n text += '<strong> Requรชte incorrecte</strong>';\n break;\n case 401:\n // Unauthorized.\n text += '<strong> Veuillez vous authentifier</strong>';\n break;\n case 403:\n // Forbidden.\n text += '<strong> Accรจs refusรฉ</strong>';\n break;\n case 404:\n // Ressource not found.\n text += '<strong> Page non trouvรฉe</strong>';\n break;\n case 500:\n // Internal server error.\n text += '<strong> Erreur interne du serveur</strong>';\n break;\n case 503:\n // Service unavailable.\n text += '<strong> Service indisponible</strong>';\n break;\n default:\n text += '<strong> HTTP erreur ' + errorNumber + '</strong>';\n break;\n }\n $('#errors').html(text);\n $('#errors').show();\n}",
"function tweetError(errText) {\n $(\"#submit-tweet\").append($('<div></div>')\n .addClass(\"tweet-error\")\n .text(errText)\n .fadeIn(500)\n .fadeOut(2500));\n }",
"function _success(res, status, xhr) {\n\n\t// If the result is a string\n\tif(typeof res == 'string') {\n\n\t\t// Try to conver it to JSON\n\t\ttry {\n\t\t\tres\t= JSON.parse(res);\n\t\t} catch(err) {\n\t\t\tconsole.error(method + ' ' + xhr._url + ' returned invalid JSON: ' + err);\n\t\t\tres = {\"error\":{\"code\":0,\"msg\":err}};\n\t\t}\n\t}\n}",
"function isFault(response) {\n response = response + \"\";\n return (response.match(/<Fault.*?>/) != null);\n}",
"function write_html_error(text)\n{\n\tL_html = L_html + \"<span style='color:red'>\" + \"ERROR : \" + text + \"</span></br>\";\n\t$(\"#sync_report\").html(L_html);\t\n}",
"error() {\n const isAbsolute = this.options.fail.indexOf('://') > -1;\n const url = isAbsolute ? this.options.fail : this.options.url + this.options.fail;\n\n this.request(url);\n }",
"function ajaxHandleResponses(s,jqXHR,responses){var contents=s.contents,dataTypes=s.dataTypes,responseFields=s.responseFields,ct,type,finalDataType,firstDataType;// Fill responseXXX fields\nfor(type in responseFields){if(type in responses){jqXHR[responseFields[type]]=responses[type];}}// Remove auto dataType and get content-type in the process\nwhile(dataTypes[0]===\"*\"){dataTypes.shift();if(ct===undefined){ct=s.mimeType||jqXHR.getResponseHeader(\"content-type\");}}// Check if we're dealing with a known content-type\nif(ct){for(type in contents){if(contents[type]&&contents[type].test(ct)){dataTypes.unshift(type);break;}}}// Check to see if we have a response for the expected dataType\nif(dataTypes[0]in responses){finalDataType=dataTypes[0];}else{// Try convertible dataTypes\nfor(type in responses){if(!dataTypes[0]||s.converters[type+\" \"+dataTypes[0]]){finalDataType=type;break;}if(!firstDataType){firstDataType=type;}}// Or just use first one\nfinalDataType=finalDataType||firstDataType;}// If we found a dataType\n// We add the dataType to the list if needed\n// and return the corresponding response\nif(finalDataType){if(finalDataType!==dataTypes[0]){dataTypes.unshift(finalDataType);}return responses[finalDataType];}}// Chain conversions given the request and the original response",
"function validateSpeechFailHCLBResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"HTTP Chunk length bad\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}",
"function add_admin_error_response_function(errorThrown)\n {\n fade_out_loader_and_fade_in_form(\"loader\", \"form\"); \n show_notification(\"msg_holder\", \"danger\", \"Error\", errorThrown);\n }",
"function displayErrorResponse(timestamp, response) {\n displayChatTemplate(timestamp, \"right-border-error\", \"timestamp--right\", \"chat-response-error\", \"<p></p>\", \"Received: \");\n $(\".chat-response-error:last > p\").text(response);\n }",
"function ajaxErrorModal( model, xhr, options, message, title ){\n message = message || DEFAULT_AJAX_ERR_MSG;\n message += ' ' + CONTACT_MSG;\n title = title || _l( 'An error occurred' );\n var details = _ajaxDetails( model, xhr, options );\n return errorModal( message, title, details );\n}",
"function validateSpeechFailTMSResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"Too Much Speech\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}",
"function handleFileListAjaxError(result, textStatus, errorThrown) {\n\tunlockQueryFileList();\n\n\t// go to up level if timeout??? think about it!\n\t//if (textStatus == \"timeout\") {\n\t//\ttraverseUp();\n\t//}\n}",
"function checkErrors(data) {\n\tif (data['error'] !== false) {\n\t\tconsole.log(data['error']);\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}",
"function checkJson(json, ret, q) {\n\n var quiet = (typeof(q) == \"undefined\") ? false : q;\n\n\ttry {\n\t\t\n\t\t// Try to parse the json\n var h = eval (\"(\"+JSON.stringify(json)+\")\");\n\n\t\t// If there's no error field... this is an error!\n\t\tif (!quiet && typeof(h['error']) == \"undefined\") {\n\t\t\tvar str = \"Server error.<br/><br/>The json doesnt have an error field..\" +\n\t\t\t\t\t \"<br><br />You may want to try to <a href='#' class='refreshPage'>reload this page</a>\";\n\t\t\tdisplayError(str);\n\t\t\treturn false;\n\t\t}\n\n\t\t// Copy h's values into ret\n\t\t$.extend(ret, h);\n\n\t\t// Error field is 0 ==> no error\n\t\tif (parseInt(h['error']) == 0)\n\t\t\treturn true;\n\n\t\t// Otherwise we have an error .. :\\\n\t\tdisplayError(h.error +\": \" + h.message);\n\t\treturn false;\n\n\t} catch (e) { \n\t \n\t\tvar str = \"Il server ha restituito un contenuto non valido.\";\n\t \n\t if (typeof(json) == \"string\") {\n\t if (json.match(/HTTP Basic: Access denied/))\n\t str = \"Devi essere loggato per poter caricare dei notebooks\";\n\n\t }\n\t \n\t\t// Some error in the try block .. maybe unable to parse the given json\n if (!quiet) displayError(str);\n\t\treturn false;\n\t}\n\t\n} // checkJson",
"function validateSpeechFailUPResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0002\", \"messageId\");\n equal(se[\"text\"], \"Undefined Parameter\", \"text\");\n equal(se[\"variables\"], \"%1\", \"variables\");\n }\n }\n}",
"function errorResponse(exception)\n{\n // Finished\n return newResponse(false, true, exception);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
downpayment value: downPercentage assetValue | calculateDownPayment() { return this.getVariable().getPercentDown() * this.getAsset().getValue() } | [
"get percentage() {\n return this._percentage;\n }",
"bankSalery(){\n if( this.bankLoan > 0 ){\n let deduction = (this.payBalance * 0.10) \n this.payBalance = this.payBalance - deduction\n if(deduction > this.bankLoan){\n this.bankBalance = this.bankBalance + (deduction - this.bankLoan)\n this.bankLoan = 0\n } else {\n this.bankLoan = this.bankLoan - deduction\n }\n }\n this.bankBalance = this.bankBalance + this.payBalance \n this.payBalance = 0\n }",
"calDiscount(){\n this._discount = this._totalCharged * (10/100) ;\n }",
"verifyValueMax() {\n this.discount.value = discountHandler.getFixedValue(this.discount.value, this.discount.type);\n }",
"function limitingPercentage(){\r\n if(customPercentage > 100){\r\n document.querySelector(\".percentage-input\").value = \"100\";\r\n customPercentage = 100;\r\n }\r\n}",
"calcPercentage() {\n return Math.floor((this.volume / 20) * 100) + \"%\";\n }",
"function calculatePercentage(percentage) {\n return (5000 / 100) * percentage;\n}",
"setBalance(value) {\n this.balance = value;\n }",
"decrementTipPercent() {\n\t\tlet tipPercent = document.getElementById('tipPercent').value;\n\t\ttipPercent = tipPercent.substr(0,tipPercent.length-1);\n\t\tif(tipPercent > 0) {\n\t\t\t// decrease tipPercent one by one\n\t\t\ttipPercent = tipPercent - 1;\n\t\t\tdocument.getElementById('tipPercent').value = tipPercent + \"%\";\n\t\t}\n\t}",
"function calcFinalDamageValue () {\n modifiedDV = parseInt(document.getElementById(\"modifiedDV\").value);\n numOfRounds = parseInt(document.getElementById(\"numOfRounds\").value);\n document.getElementById(\"finalDV\").value = modifiedDV + (numOfRounds - 1);\n calcDefenderDamageTaken();\n}",
"generatePercent(deathState,totDeath) {\n return ((deathState / parseInt(totDeath)) * 100).toFixed(2) + '%'\n }",
"function percentChangeHandler(e) {\n\tvar value = parseInt(this.value);\n\tif(isNaN(value)) value = 0;\n\tif(value < 0) value = 0;\n\tif(value > 100) value = 100;\n\tthis.value = value;\n\n // If percent changed we need send updated configuration\n var $pin = this.parentNode.parentNode;\n var data = getPinData($pin);\n\n //console.log(data.pinNumber, data.pinType, data.value);\n makeUpdateConfiguration(data.pinNumber, data.pinType, data.value); \n}",
"soapPercent() {\n if (this.finalSoapuiSearchData.length !== null) {\n this.finalSoapuiSearchData = Math.round(\n (this.finalSoapuiSearchData.length / this.totalSearchData) * 100\n );\n } else {\n this.finalSoapuiSearchData = 0;\n }\n }",
"function get_percent(def)\n{\n\treturn prompt('Enter a percentage to be taken off the sale price:\\n(Enter 0 to remove the percentage)',def);\n}",
"deductBudget() {\n let price = parseInt(costClothing.value, 10);\n runningBudget -= price;\n updateBudget();\n }",
"function getNoUISliderValue(slider, percentage) {\n slider.noUiSlider.on('update', function () {\n var val = slider.noUiSlider.get();\n $(slider).parent().find('span.js-nouislider-value').text(parseInt(val));\n });\n}",
"seleniumPercent() {\n if (this.finalSeleniumSearchData.length !== null) {\n this.finalSeleniumSearchData = Math.round(\n (this.finalSeleniumSearchData.length / this.totalSearchData) * 100\n );\n } else {\n this.finalSeleniumSearchData = 0;\n }\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}",
"get percent() {\n return Math.max(0, (SongManager.player.currentTime - this.startPoint) / (this.endPoint - this.startPoint));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the thumbnail src. | set src(aValue) {
this._logService.debug("gsDiggThumbnailDTO.src[set]");
this._src = aValue;
} | [
"async updateImageSource() {\n const source = await this.getThumbnailURL();\n this.getImage().setAttribute('src', source);\n }",
"function setPicture(){\n\n\t\t\t\tvar sizes = new Object();\n\n\t\t\t\telement.find('source').each(function(){\n\n\t\t\t\t\tvar media, path, num;\n\t\t\t\t\tmedia = $(this).attr('media');\n\t\t\t\t\tpath = $(this).attr('src');\n\n\t\t\t\t\tif(media)\n\t\t\t\t\t\tnum = media.replace(/[^\\d.]/g, '');\n\t\t\t\t\telse\n\t\t\t\t\t\tnum = 0;\n\n\t\t\t\t\tsizes[num] = path;\n\n\t\t\t\t});\n\n\t\t\t\tif(element.find('img').length == 0){\n\n\t\t\t\t\tvar prep = '<img src=\"' + sizes[currentMedia] + '\" style=\"' + element.attr('style') + '\" alt=\"' + element.attr('alt') + '\">';\n\n\t\t\t\t\tif($('>a', element).length == 0){\n\n\t\t\t\t\t\telement.append(prep);\n\n\t\t\t\t\t}else{\n\n\t\t\t\t\t\t$('>a', element).append(prep);\n\n\t\t\t\t\t}\n\n\t\t\t\t}else{\n\t\t\t\t\t\n\t\t\t\t\telement.find('img').attr('src', sizes[currentMedia]);\n\n\t\t\t\t}\n\n\t\t\t}",
"set imageURL(aValue) {\n this._logger.debug(\"imageURL[set]\");\n this._imageURL = aValue;\n }",
"function resetThumbnailImg() {\n $('img.edit_thumbnail').attr('src', emptyImageUrl);\n currentThumbnailId = 0;\n}",
"set imageURL(aValue) {\n this._logService.debug(\"gsDiggEvent.imageURL[set]\");\n this._imageURL = aValue;\n }",
"function setImage(id, src) {\n\t// logMessage(\"id.src:\"+id+\"->\"+src);\n\tdocument.getElementById(id).src = src;\n}",
"function setThumbnail(url){\r\n\tvar imgUrl = \"\";\r\n\tif(url.match(/youtube/) != null){\r\n\t\timgUrl = \"http://img.youtube.com/vi/\" + getKey(url) + \"/0.jpg\";\r\n\t}\r\n\tif(imgUrl != \"\"){\r\n\t\t$(\"#formDialog img\").show();\r\n\t\t$(\"#formDialog img\").attr(\"src\", imgUrl);\r\n\t} else {\r\n\t\t$(\"#formDialog img\").hide();\r\n\t}\r\n}",
"function setImageSrc(image, location) {\n image.src = location + '-640_medium.webp';\n}",
"resetFileThumb() {\n const fileThumb = this.dom.querySelector(\".file-details-thumbnail\");\n fileThumb.src = require(\"../static/images/file-128x128.png\");\n }",
"swapPlaceholderImg(src) {\n this.$results.find('.results-overview-image img').attr('src', src).attr('alt', 'screenshot for ' + this.websiteUrl);\n }",
"set imageUrl(monImageUrl) {\n this._imageUrl = monImageUrl\n }",
"get src() {\n this._logService.debug(\"gsDiggThumbnailDTO.src[get]\");\n return this._src;\n }",
"function setElementSrc ( id, value )\n {\n\tvar elt = myGetElement(id);\n\t\n\tif ( elt && typeof(value) == \"string\" ) elt.src = value;\n }",
"function imageSwitch() {\n tmp = $(this).attr('src');\n $(this).attr('src', $(this).attr('alt_src'));\n $(this).attr('alt_src', tmp);\n }",
"function onImagePickerOptionChange(pickerOption) {\r\n $('#projectImagePreview').attr('src', $(pickerOption.option[0]).data('img-src'));\r\n}",
"function imageClicked() {\n var currentSource = $(this).attr('src');\n var altSource = $(this).attr('data-src');\n $(this).attr('src', altSource);\n $(this).attr('data-src', currentSource);\n }",
"static updateThumbnailFromUrl(entryId, url){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.url = url;\n\t\treturn new kaltura.RequestBuilder('media', 'updateThumbnailFromUrl', kparams);\n\t}",
"function setFigure(){\n\n\t\t\t\tvar sizes = new Object();\n\n\t\t\t\tvar mediaObj = element.data();\n\n\t\t\t\t$.each(mediaObj, function(media, path){\n\n\t\t\t\t\tvar num;\n\n\t\t\t\t\tnum = media.replace(/[^\\d.]/g, '');\n\n\t\t\t\t\tif(!num)\n\t\t\t\t\t\tnum = 0;\n\n\t\t\t\t\tsizes[num] = path;\n\n\t\t\t\t});\n\n\t\t\t\tif(element.find('img').length == 0){\n\n\t\t\t\t\tvar prep = '<img src=\"' + sizes[currentMedia] + '\" alt=\"' + element.attr('title') + '\">';\n\n\t\t\t\t\tif($('>a', element).length == 0){\n\n\t\t\t\t\t\telement.append(prep);\n\n\t\t\t\t\t}else{\n\n\t\t\t\t\t\t$('>a', element).append(prep);\n\n\t\t\t\t\t}\n\n\t\t\t\t}else{\n\n\t\t\t\t\telement.find('img').attr('src', sizes[currentMedia]);\n\n\t\t\t\t}\n\n\t\t\t}",
"updateSrcSet(newSrc) {\n if (this.srcValues.length > 0) {\n this.srcValues.forEach(function (src) {\n if (src.name === newSrc.name) {\n src.url = newSrc.url;\n }\n }.bind(this));\n }\n\n this.saveSrcSet();\n this.fredCropper.el.dataset.crop = 'true';\n this.fredCropper.pluginTools.fredConfig.setPluginsData('fredcropper'+this.fredCropper.el.fredEl.elId, 'activated', 'true');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
jobStatsMenuToggle function that scales map with job stats menu | function jobStatsMenuToggle(){
$('.jobStats').toggleClass('jobStatsHide')
$('.item4').toggleClass('select')
if($('.map').hasClass('mapWithoutList')){
$('.map').toggleClass('mapWithoutAnything')
} else if ($('.map').hasClass('mapWithoutAnything')){
$('.map').toggleClass('mapWithoutAnything')
}
$('.map').toggleClass('mapWithoutInfo')
} | [
"function jobListMenuToggle(){\n $('.sidebar').toggleClass('sidebarHide')\n $('.item1').toggleClass('select')\n if($('.map').hasClass('mapWithoutInfo')){\n $('.map').toggleClass('mapWithoutAnything')\n } else if ($('.map').hasClass('mapWithoutAnything')){\n $('.map').toggleClass('mapWithoutAnything')\n }\n $('.map').toggleClass('mapWithoutList')\n\n}",
"toggleOptionsMenu() {\n // Set the css variable for options width (for desktop only)\n if (window.innerWidth >= this.state.mobileBreakpoint) {\n let optionsSize = this.state.isOptionsMenuShowing ? \"0px\" : \"400px\";\n document.documentElement.style.setProperty('--options-width', optionsSize);\n }\n \n // Update the map so that it correctly uses the new width\n this.drawMap();\n \n // Update the state to the new view\n this.setState({\n isOptionsMenuShowing: !this.state.isOptionsMenuShowing,\n });\n }",
"function onClickChange(i,j){\n console.log(\"merp i = \"+i+\", j = \"+j)\n if (editTables) {\n //TODO edit table ids\n } else {\n // toggle map block\n mapModified = true;\n console.log(map);\n map[i][j] = mapSyms[(mapSyms.indexOf(map[i][j])+1)%4];\n console.log(map);\n updateMap(); \n }\n \n}",
"function showHeatmap(){\n const show = document.getElementById(\"showHeatmapCheckbox\").checked\n if(show){\n heat = loadHeatMapData()\n isShowHeadMap = true\n lastBiggestMapBounds = map.getBounds()\n }else {\n isShowHeadMap = false\n heat.remove(map)\n }\n}",
"function _showModifyTileMenu() {\n //topAppBar.winControl.hide();\n div_cockpits_bottomAppBar.winControl.hide();\n var item = lv_cockpits.winControl._selection.getItems()._value[0].data;\n item.idDashboard = CockpitHelper.currentDashboard.id;\n if (item.widgetType == CockpitHelper.TileType.Numerique) {\n RightMenu.showRightMenu(Pages.modifyKpiResumeStep, { \"tile\": item });\n }\n else if (item.widgetType == CockpitHelper.TileType.Exploration) {\n RightMenu.showRightMenu(Pages.modifyExploration, { \"tile\": item });\n }\n }",
"function updateUI() {\n if (isSmall) {\n view.ui.add(expandLegend, 'top-right');\n view.ui.remove(legend);\n view.ui.components = [\"attribution\"];\n } else {\n view.ui.add(legend, 'top-right');\n view.ui.remove(expandLegend);\n view.ui.components = [\"attribution\", \"zoom\"];\n }\n }",
"function toggleScrapingMarkers() {\n if (scrapingMarkersVisible) {\n scrapingMarkersGroup.remove();\n $('#scrapingLegendLabel').css('text-decoration', 'line-through');\n scrapingMarkersVisible = false;\n } else {\n scrapingMarkersGroup.addTo(mymap);\n $('#scrapingLegendLabel').css('text-decoration', 'none');\n scrapingMarkersVisible = true;\n }\n}",
"function setHeatmapLoadState(state){\n const label = document.getElementById(\"showHeatmapLabel\")\n const spinner = document.getElementById(\"heatmapSpinner\")\n if(state){\n label.classList.add(\"hidden\")\n spinner.classList.remove(\"hidden\")\n }else {\n label.classList.remove(\"hidden\")\n spinner.classList.add(\"hidden\")\n }\n}",
"updateVisibility() {\n //Get current zoom level\n let zoomLevel = this.map.getView().getZoom();\n let visible = this.isVisibleAtZoomLevel(zoomLevel);\n //Update visibility\n super.setVisible(visible);\n }",
"function toggleTrialMap() {\n\tvar map = $('#g_map');\n\t\n\t// hide\n\tif (map.is(':visible')) {\n\t\tvar link_offset = $('#g_map_toggle').offset().top - $(window).scrollTop();\n\t\tgeo_hideMap();\n\t\tgeo_clearAllPins();\n\t\t$('#g_map_toggle > a').text('Show Map');\n\t\t$('#selected_trial').empty().hide();\n\t\t\n\t\t// scroll in place\n\t\tvar new_offset = $('#g_map_toggle').offset().top - $(window).scrollTop();\n\t\tif (Math.abs(link_offset - new_offset) > 50) {\n\t\t\t$(window).scrollTop(Math.max(0, $('#g_map_toggle').offset().top - link_offset));\n\t\t}\n\t}\n\t\n\t// show\n\telse {\n\t\tgeo_showMap();\n\t\t// map.append('<div id=\"g_map_loading\">Loading...</div>');\n\t\t$('#g_map_toggle > a').text('Hide Map');\n\t\t\n\t\t// pins\n\t\twindow.setTimeout(function() {\n\t\t\tupdateTrialLocations();\n\t\t}, 200);\n\t}\n}",
"function update() { \n set_zoom_button_mode()\n show_zoom_button_tooltip(tooltip_showing)\n }",
"function heatmap_change(heatmap) {\n \n function set_active_page(number){\n //Hide all heatmaps and show the one selected\n $(\".heatmap\").hide();\n $(\"#heatmap\"+number).css('display','inline-block');\n //Deactivate all page buttons and activate the selected one\n $(\"#heatmap_pager .page-item\").removeClass(\"active\");\n $(\"#heatmap_page_\"+number).addClass(\"active\")\n }\n var new_heatmap;\n //If the clicked option is the current one, do nothing\n if ($(\"#heatmap_page_\"+heatmap).hasClass(\"active\")){\n //pass\n }\n else if (heatmap==\"next\"){\n new_heatmap = parseInt($(\".heatmap:visible\").attr(\"data-number\"))+1;\n if ($(\"#heatmap_page_\"+new_heatmap).length){\n set_active_page(new_heatmap);\n }\n } \n else if (heatmap==\"prev\"){\n new_heatmap = parseInt($(\".heatmap:visible\").attr(\"data-number\"))-1;\n if ($(\"#heatmap_page_\"+new_heatmap).length){\n set_active_page(new_heatmap);\n }\n }\n else {\n new_heatmap = heatmap;\n set_active_page(new_heatmap);\n }\n return false\n}",
"function toggleVolcanoes(){\n\tmap.closeInfoWindow();\n\tcount = 0;\n\tif(this.id ==\"plotVolcanoesTrue\"){\n\t\tplotVolcanoIcons = 1;\n\t\tplotVolcanoes();\n\t}else{\n\t\tplotVolcanoIcons = 0;\n\t\tfor (var i = 0; i<volcanomarker.length; i++){\n\t\t\tvolcanomarker[i].remove();\n\t\t}\n\t}\n}",
"function updateMenuFlag() {\n const menuFlag = document.getElementById('menu-flag');\n if (menuFlag) {\n if (Data.Flags.includes(Data.Filename)) {\n menuFlag.title = 'Remove flag';\n menuFlag.className = 'flagged';\n } else {\n menuFlag.title = 'Flag this diagram';\n menuFlag.className = 'unflagged';\n }\n }\n}",
"toggleProphecyOfKings() {\n this.setState({\n useProphecyOfKings: !this.state.useProphecyOfKings,\n }, this.showExtraTiles);\n }",
"function onZoom()\r\n{\r\n\tevaluateLayerVisibility();\r\n\t$(\"#zoomlevel\").val(Math.floor(map.getView().getZoom()));\r\n}",
"function toggleRaceCompendium(submenu){\n submenu.hidden == true ? submenu.hidden = false : submenu.hidden = true;\n\n const raceSubMenuOptions = submenu.querySelectorAll(\".item\")\n let counter = 1\n while(counter <= 9){\n raceSubMenuOptions.forEach(function(raceItem){\n raceItem.dataset.raceId = counter\n raceItem.addEventListener(\"click\", function(){\n displayRaceCompendium(raceItem.dataset.raceId)\n })\n counter += 1;\n });\n }\n}",
"function updateStats() {\n $(\".elevator-\" + index + \" .value\").text(floorButtonsQueue);\n }",
"rescaleTiles() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Map an array of effects through a change set. | static mapEffects(effects, mapping) {
if (!effects.length)
return effects;
let result = [];
for (let effect of effects) {
let mapped = effect.map(mapping);
if (mapped)
result.push(mapped);
}
return result;
} | [
"map(mapping) {\n let mapped = this.type.map(this.value, mapping);\n return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped);\n }",
"function Transition(id, asets, bsets) {\n var i = 1, j = 0, n = 8, interpolated = interpolateSets(asets, bsets, n);\n\n if (!asets.length) {\n return Chartlets.update(id, bsets);\n }\n\n function _render() {\n var set = [];\n\n for (j = 0; j < interpolated.length; j++) {\n set.push(interpolated[j][i]);\n }\n\n Chartlets.update(id, set);\n\n if (++i <= n) {\n animate(_render);\n }\n }\n\n animate(_render);\n }",
"function modifyStrings(strings, modify) {\n // YOUR CODE BELOW HERE //\n // I = array of strings and modify function\n // O = modified array\n // init empty array as modArray\n // use for loop to loop through entire array of strings\n // push strings into modArray array and into modify function\n var modArray = [ ];\n for (var i = 0; i < strings.length; i++) {\n modArray.push(modify(strings[i]));\n } \n \n return modArray;\n\n \n \n // YOUR CODE ABOVE HERE //\n}",
"function modifyArray(nums) {\n return nums.map(s=> s%2==0 ? s*2: s*3 )\n\n\n }",
"toggleEffects() {\n this.effectsOn = !this.effectsOn;\n let w = this.effectsOn ? 'on' : 'off';\n let f = this.effectsOn ? 'On' : 'Off';\n this.ecs.getSystem(System.GUIManager).runSequence('notification', new Map([['notification', 'sound effects ' + w]]), new Map([['notification', 'HUD/sound' + f]]));\n // Nothing else needs to happen here because sound effects are\n // short. We simply decide whether to play future effects based on\n // this setting.\n }",
"function CharacterAddEffect(C, NewEffect) {\n\tfor (var E = 0; E < NewEffect.length; E++)\n\t\tif (C.Effect.indexOf(NewEffect[E]) < 0)\n\t\t\tC.Effect.push(NewEffect[E]);\n}",
"function toggle_effects() {\n effects.mute = !effects.mute;\n effects.shoot.muted = effects.mute;\n effects.explosion.muted = effects.mute;\n effects.hit.muted = effects.mute;\n set_menu_item_text(menu_items.effects, music.mute);\n }",
"setAll({ state, dispatch, commit }, { corpuUid }) {\n // Loop over every layers uids\n Object.keys(state.actives).forEach(uid => {\n // Loop over every layers in a corpuUid\n state.lists[corpuUid].forEach(l => {\n // Activate the layer\n dispatch('set', { id: l.id, corpuUid, uid })\n })\n })\n }",
"function mapDefinedMutate(inputs, tryGetOutput) {\n let writeIndex = 0;\n for (const input of inputs) {\n const output = tryGetOutput(input);\n if (output !== undefined) {\n inputs[writeIndex] = output;\n writeIndex++;\n }\n }\n inputs.length = writeIndex;\n}",
"static applyTo({\n target,\n obj,\n hideEffects = true,\n instantEffects = [],\n isOnlyMutual = false,\n ...options\n }) {\n let { effectsByPriority } = options;\n if (!effectsByPriority) {\n effectsByPriority = this.getEffectsResultFor({\n ...options,\n obj: target,\n instantEffects,\n isOnlyMutual,\n });\n }\n\n Object.defineProperty(obj, 'effects', {\n value: effectsByPriority,\n configurable: true,\n enumerable: !hideEffects,\n });\n\n const modifier = this.isReduce ? -1 : 1;\n\n _(effectsByPriority).pairs().forEach(([priority, effects]) => {\n _(effects).pairs().forEach(([affect, affectEffects]) => {\n const effectValue = affectEffects.reduce(\n (sum, effect) => sum + effect.value,\n 0,\n );\n\n if (affect === 'damage') {\n if (!(obj.weapon && obj.weapon.damage)) {\n return;\n }\n } else if (affect === 'life') {\n if (!(obj.health && obj.health.armor)) {\n return;\n }\n } else if (obj[affect] === undefined) {\n return;\n }\n\n if (affect === 'damage') {\n const { damage } = obj.weapon;\n if (priority % 2 === 1) {\n damage.min += effectValue * modifier;\n damage.max += effectValue * modifier;\n } else {\n damage.min += Math.floor(damage.min * (0.01 * effectValue)) * modifier;\n damage.max += Math.floor(damage.max * (0.01 * effectValue)) * modifier;\n }\n } else if (affect === 'life') {\n const { health } = obj;\n if (priority % 2 === 1) {\n health.armor += effectValue * modifier;\n } else {\n health.armor += (Math.floor(health.armor * (0.01 * effectValue)) * modifier);\n }\n } else if (priority % 2 === 1) {\n // eslint-disable-next-line no-param-reassign\n obj[affect] += effectValue * modifier;\n } else if (affect === 'time') {\n const resultedValue = (Math.abs(effectValue) + 100) * 0.01;\n\n if ((this.isReduce && effectValue >= 0) || (!this.isReduce && effectValue < 0)) {\n // eslint-disable-next-line no-param-reassign\n obj[affect] = Math.ceil(obj[affect] / resultedValue);\n } else {\n // eslint-disable-next-line no-param-reassign\n obj[affect] = Math.ceil(obj[affect] * resultedValue);\n }\n } else {\n // eslint-disable-next-line no-param-reassign\n obj[affect] += Math.floor(obj[affect] * (0.01 * effectValue)) * modifier;\n }\n });\n });\n\n return obj;\n }",
"function map(fun, seq) {\n 'use strict';\n return function() {\n return couple(\n fun(nth(0, seq)),\n map(fun, skip(1, seq))\n ); \n };\n }",
"function map(env, fn, exprs) {\n return exprs.map(function (expr) {\n return fn(env, expr);\n });\n}",
"function replaceArray(original, replacement, av)\n {\n\tfor (var i = 0; i < original.size(); i++)\n\t{\n\t\toriginal.value(i, replacement.value(i));\n\t\tif (replacement.isHighlight(i))\n\t\t{\n\t\t\toriginal.highlight(i);\n\t\t} else {\n\t\t\toriginal.unhighlight(i);\n\t\t}\n\t}\n }",
"function customReducer3DataSets(oldArray) {\n // play with action.data here:\n let newArray = [];\n let accum = 0;\n\n for (\n let i = 1;\n i < oldArray.length;\n i++ // skip 0th elem, which is column labels\n ) {\n accum = +oldArray[i][0] + +oldArray[i][1] + +oldArray[i][2];\n newArray.push([accum.toString(), oldArray[i][3], oldArray[i][4]]);\n }\n return newArray;\n}",
"function onClickChange(i,j){\n console.log(\"merp i = \"+i+\", j = \"+j)\n if (editTables) {\n //TODO edit table ids\n } else {\n // toggle map block\n mapModified = true;\n console.log(map);\n map[i][j] = mapSyms[(mapSyms.indexOf(map[i][j])+1)%4];\n console.log(map);\n updateMap(); \n }\n \n}",
"rebased(newMaps, rebasedTransform, positions) {\n if (this.events == 0) return\n\n let rebasedItems = [], start = this.items.length - positions.length, startPos = 0\n if (start < 1) {\n startPos = 1 - start\n start = 1\n this.items[0] = new Item\n }\n\n if (positions.length) {\n let remap = new Remapping([], newMaps.slice())\n for (let iItem = start, iPosition = startPos; iItem < this.items.length; iItem++) {\n let item = this.items[iItem], pos = positions[iPosition++], id\n if (pos != -1) {\n let map = rebasedTransform.maps[pos]\n if (item.step) {\n let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos])\n let selection = item.selection && item.selection.type.mapToken(item.selection, remap)\n rebasedItems.push(new StepItem(map, item.id, step, selection))\n } else {\n rebasedItems.push(new MapItem(map))\n }\n id = remap.addToBack(map)\n }\n remap.addToFront(item.map.invert(), id)\n }\n\n this.items.length = start\n }\n\n for (let i = 0; i < newMaps.length; i++)\n this.items.push(new MapItem(newMaps[i]))\n for (let i = 0; i < rebasedItems.length; i++)\n this.items.push(rebasedItems[i])\n\n if (!this.compressing && this.emptyItems(start) + newMaps.length > max_empty_items)\n this.compress(start + newMaps.length)\n }",
"function replace(arr, target, source) {\n\t return arr.map(function (v) {\n\t return v === target ? source : v;\n\t });\n\t}",
"function mapMethod() {\n\tvar testarray=[1,2,3,4];\n\tvar result=_.map(testarray, function(num) {\n\t\treturn num*3;\n\t});\n\tconsole.log(result);\n}",
"callAllCallbacks() {\n this.callbackSets.forEach((set) => {\n this.callCallbackSet(set);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines if the given character can be part of a mention's text characters. | function isMentionTextChar(char) {
return mentionTextCharRe.test(char);
} | [
"function stateMentionTextChar(stateMachine, char) {\n if (isMentionTextChar(char)) ;\n else if (alphaNumericAndMarksRe.test(char)) {\n // Char is invalid for a mention text char, not a valid match.\n // Note that ascii alphanumeric chars are okay (which are tested\n // in the previous 'if' statement, but others are not)\n remove(stateMachines, stateMachine);\n }\n else {\n captureMatchIfValidAndRemove(stateMachine);\n }\n }",
"function isHashtagTextChar(char) {\n return char === '_' || alphaNumericAndMarksRe.test(char);\n }",
"function wordCharacter(character) {\n return re$3.test(\n typeof character === 'number' ? fromCode$1(character) : character.charAt(0)\n )\n }",
"function containsChar(str, target) {\n for (var i = 0; i<str.length; i++) {\n if(target.indexOf(str[i]) != -1) {\n return true;\n }\n }\n return false;\n}",
"function isSingleCharacter(oneChar){\n if (typeof onChar !== \"string\"){\n return false;\n }\n else if (onChar.length > 1){\n return false;\n }\n else {\n return true;\n }\n}",
"function isCharacterPunctuation(asciiValue) {\n let isPunctuation = false;\n switch (asciiValue) {\n // Space\n case 32:\n isPunctuation = true;\n break;\n // Exclamation mark\n case 33:\n isPunctuation = true;\n break;\n // Quotation mark\n case 34:\n isPunctuation = true;\n break;\n // Apostrophe mark\n case 39:\n isPunctuation = true;\n break;\n // Open parentheses\n case 40:\n isPunctuation = true;\n break;\n // Close parentheses\n case 41:\n isPunctuation = true;\n break;\n // Comma\n case 44:\n isPunctuation = true;\n break;\n // Hyphen\n case 45:\n isPunctuation = true;\n break;\n // Period\n case 46:\n isPunctuation = true;\n break;\n // Forward slash\n case 47:\n isPunctuation = true;\n break;\n // Colon\n case 58:\n isPunctuation = true;\n break;\n // Semicolon\n case 59:\n isPunctuation = true;\n break;\n // Question markk\n case 63:\n isPunctuation = true;\n break;\n default:\n isPunctuation = false;\n break;\n }\n return isPunctuation;\n }",
"checkLetter(input) {\r\n return this.phrase\r\n .split(\"\")\r\n .some(letter => letter == input);\r\n }",
"function isDomainLabelStartChar(char) {\n return alphaNumericAndMarksRe.test(char);\n }",
"function validateForbiddenChar(password) {\n for (const c of password) {\n if (FORBIDDEN_CHAR.has(c)) return false;\n }\n return true;\n }",
"function isSingleCharacter(oneChar){\n if (typeof oneChar !== 'string'){\n console.log(\"Sorry, not a string\");\n return false;\n }\n else if (oneChar.length > 1){\n console.log(\"Sorry, too long\");\n return false;\n }\n else {\n console.log(\"word\");\n return true;\n }\n}",
"function isCharAVowel(char){\n char = char.toLowerCase(); //with strings, converting to lower or upper is needed\n return ('aeiouy'.indexOf(char) > -1) // checking string 'aeiouy' for character passed into char argument \n}",
"function isEmailLocalPartChar(char) {\n return emailLocalPartCharRegex.test(char);\n }",
"isBoth(char) {\n return (\n \"\\u020C\" <= char && char <= \"\\u003E\" ||\n char == \"\\u0040\" /*@*/ ||\n \"\\u005B\" <= char && char <= \"\\u0060\" ||\n \"\\u007B\" <= char && char <= \"\\u007E\"\n );\n }",
"function invalid_char(val) {\n if (val.match('^[a-zA-z0-9_]+$') == null) {\n return true\n } else {\n return false\n }\n}",
"isEnglish(char) {\n return (\n \"\\u0021\" <= char && char <= \"\\u007E\" ||\n char == \"\\u003F\" /*?*/ ||\n \"\\u0041\" <= char && char <= \"\\u005A\" ||\n \"\\u0061\" <= char && char <= \"\\u007A\"\n );\n }",
"function isLetter(c) {\n return c.charCodeAt(0) >= 65 && c.charCodeAt(0) <= 90 ; \n}",
"function isUnicodeLetter(c) {\n return new RegExp(/[ a-zA-Z'\\\\\\/\\&\\(\\)\\-\\u3000-\\u3002\\uFF10-\\uFF19\\xAA\\xB5\\xBA\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC-\\u002F-\\u005c]/).test(c);\n}",
"function checkLetterInWordTree(wordTreeNode, tileLetter, strWorkString, wordLen)\n{\n var isLetterPartOfWord = false;\n\n // Is the current letter present at the current location in the word tree?\n if ( wordTreeNode.hasOwnProperty( tileLetter ) )\n {\n // Append current tile letter to the working string\n strWorkString = strWorkString + tileLetter;\n\n // indicate success, letter at this location is part of a valid word\n isLetterPartOfWord = true;\n\n // Check to see if the current string of letters is the last letter which completes a valid word\n if ( wordTreeNode[ tileLetter ]['iw'] )\n addWordToFoundList(strWorkString, wordLen);\n }\n\n return (isLetterPartOfWord);\n}",
"function isIsogram(str){\n if(str === '') {\n return true;\n }\n const lowLetters = str.toLowerCase()\n const splitStr = lowLetters.split('');\n return splitStr.every((letter, index) => str.indexOf(letter) === index);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a single event based on the eventid | function getEvent(eventid)
{
var defaultTestEvent = {
'eventid': '01',
'title': 'Success Through Failures',
'eventLocation': 'Atlanta',
'start': moment('2016-07-22'),
'attendees':[
{
'firstName': 'John',
'lastName': 'Smitty'
},
{
'firstName': 'Sue',
'lastName': 'Mee'
}
]
};
//parses events to search for matching eventid
var events = getEvents();
for( var i=0; i<events.length; i++){
if( events[i].eventid == eventid)
return events[i];
}
return defaultTestEvent;
} | [
"getSingleUserEvent(db, user_id, id){\n return db\n .from('events')\n .select('*')\n .where({user_id, id});\n }",
"async function get_event_id(tournament_name, event_name, token) {\n let variables = {\"tourneySlug\": tournament_name};\n let response = await run_query(t_queries.EVENT_ID_QUERY, variables, token);\n return filters.event_id_filter(response.data, event_name);\n}",
"deleteEvent (eventId) {\n assert.equal(typeof eventId, 'number', 'eventId must be number')\n return this._apiRequest(`/event/${eventId}`, 'DELETE')\n }",
"deleteEvent(db, id){\n return db\n .from('events')\n .where(id)\n .delete();\n }",
"function igcal_getCalendarById(id, e)\r\n{\r\n\tvar o,i1=-2;\r\n\tif(e!=null)\r\n\t{\r\n\t\twhile(true)\r\n\t\t{\r\n\t\t\tif(e==null) return null;\r\n\t\t\ttry{if(e.getAttribute!=null)id=e.getAttribute(\"calID\");}catch(ex){}\r\n\t\t\tif(!ig_csom.isEmpty(id)) break;\r\n\t\t\tif(++i1>1)return null;\r\n\t\t\te=e.parentNode;\r\n\t\t}\r\n\t\tvar ids=id.split(\",\");\r\n\t\tif(ig_csom.isEmpty(ids))return null;\r\n\t\tid=ids[0];\r\n\t\ti1=(ids.length>1)?parseInt(ids[1]):-1;\r\n\t}\r\n\tif((o=igcal_all[id])==null)\r\n\t\tfor(var i in igcal_all)if((o=igcal_all[i])!=null)\r\n\t\t\tif(o.ID==id || o.ID_==id || o.uniqueId==id)break;\r\n\t\t\telse o=null;\r\n\tif(o!=null && i1>-2)o.elemID=i1;\r\n\treturn o;\r\n}",
"delete(id) {\n return this.send(\"DELETE\", `events/${id}`);\n }",
"function eventWithId(func, id) {\n\t\treturn function(event) {func(event, id);};\n\t}",
"function load(req, res, next, id) {\n EventModel.findById(id)\n .then(event => {\n req.event = event; // eslint-disable-line no-param-reassign\n return next();\n })\n .catch(e => next(e));\n}",
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('eventnotification_eventnotificationtemplate', 'get', kparams);\n\t}",
"function getEventSearch(eventName) {\n if (dbPromise) {\n dbPromise.then(function (db) {\n var transaction = db.transaction('EVENT_OS', \"readonly\");\n var store = transaction.objectStore('EVENT_OS');\n var index = store.index('title');\n var request = index.getAll(eventName.toString());\n return request;\n }).then( function (request) {\n displayEvents(request)\n });\n }\n}",
"function pullEventReceived(event) {\n\n //store information about this event\n let thisEvent = JSON.stringify(event);\n\n console.log(\"Pull event received. \");\n console.log(thisEvent);\n}",
"async getInvitationsByEventId(req, res) {\n const userAuth = jwt_decode(req.token);\n const { event_id } = req.params;\n\n try {\n const user = await User.findOne({ cognito_id: userAuth.sub });\n\n // Check if user exist\n if (!user) {\n return res.status(400).json({\n errMessage: 'User Not Found',\n });\n }\n\n const event = await Event.findById(event_id);\n\n if (!event) {\n return res.status(400).json({\n errMessage: 'Event Not Found',\n });\n }\n\n const invitations = await Invitation.find({\n event_id: event._id,\n is_going: null,\n })\n .populate('user_id')\n .exec();\n\n return res.status(200).json({\n invitations,\n });\n } catch (error) {\n throw Error(`Error while getting invitation: ${error}`);\n }\n }",
"function get_element_from_event (event, element_type) {\n\t\tvar target = $(event.target);\n\t\tvar element = null;\n\n\t\tif(target.is(element_type)) {\n\t\t\telement = target;\n\t\t} else if(target.parent(element_type).length) {\n\t\t\telement = target.parent(element_type+\":first\");\n\t\t}\n\n\t\treturn element;\n\t}",
"function getEvent(item, refid) {\n var event = { 'refid': refid };\n var tree = item.tree;\n for (i in tree) {\n var tag = tree[i].tag;\n var tag_lc = mapTag(tag);\n switch (tag) {\n case 'TYPE':\n event['etype'] = tree[i].data;\n break;\n case 'DATE':\n event['edate'] = formatDate(tree[i].data);\n case 'PLAC':\n event[tag_lc] = tree[i].data;\n break;\n case 'SOUR':\n if (typeof event[tag_lc] === 'undefined') {\n event[tag_lc] = [getSour(tree[i])];\n }\n else {\n event[tag_lc].push(getSour(tree[i]));\n }\n break;\n case 'NOTE':\n event[tag_lc] = cleanPointer(tree[i].data);\n break;\n default:\n text = tag + \": \" + tree[i].data;\n if (typeof event.text === 'undefined') {\n event['text'] = text;\n }\n else {\n event['text'] += '; ' + text;\n }\n break;\n }\n }\n\n return event;\n}",
"function getEventChoosen(){\n\t\t\tfor (var i=0; i<events.length; i++) {\n\t\t\t\tif ( events[i].choosen )\n\t\t\t\t\treturn i;\n\t\t\t}\n\t\t\treturn -1;\n\t\t}",
"function selectEventID(){\n\n\tvar form = View.panels.get(\"abCompDocForm\");\n\t//consturct restricion for selecting event id\n\tvar res= \" activity_log.activity_type='COMPLIANCE - EVENT' \";\n\tvar regulation = form.getFieldValue(\"docs_assigned.regulation\");\n\tif(regulation){\n\t\tres+= \" AND activity_log.regulation='\"+regulation+\"' \";\n\t}\n\tvar program = form.getFieldValue(\"docs_assigned.reg_program\");\n\tif(program){\n\t\tres+=\" AND activity_log.reg_program='\"+program+\"' \";\n\t}\n\tvar requirement = form.getFieldValue(\"docs_assigned.reg_requirement\");\n\tif(requirement){\n\t\tres+=\" AND activity_log.reg_requirement='\"+requirement+\"' \";\n\t}\n \tvar locatioId = form.getFieldValue(\"docs_assigned.location_id\");\n\tif(locatioId){\n\t\tres+=\" AND activity_log.location_id=\"+locatioId;\n\t}\n\n\tView.selectValue({\n\t\tformId: 'abCompDocForm',\n\t\ttitle: getMessage('titleEventID'),\n\t\trestriction: res,\n\t\tactionListener: \"afterSelectEventID\",\n\t\tfieldNames: ['docs_assigned.regulation', 'docs_assigned.reg_program', 'docs_assigned.reg_requirement',\n\t\t\t'docs_assigned.activity_log_id', 'docs_assigned.location_id'],\n\t\tselectTableName : 'activity_log',\n\t\tselectFieldNames: ['activity_log.regulation', 'activity_log.reg_program', 'activity_log.reg_requirement', \n\t\t\t'activity_log.activity_log_id', 'activity_log.location_id'],\n\t\tvisibleFields: [\n\t\t\t{fieldName: 'activity_log.activity_log_id', title: getMessage('titleEventID')},\n\t\t\t{fieldName: 'activity_log.action_title', title: getMessage('titleEvent')},\n\t\t\t{fieldName: 'activity_log.date_scheduled', title: getMessage('titleDateScheduled')},\n\t\t\t{fieldName: 'activity_log.regulation'},\n\t\t\t{fieldName: 'activity_log.reg_program'},\n\t\t\t{fieldName: 'activity_log.reg_requirement'}\n\t\t]\n\t});\n}",
"deleteGlobalEvent(_event_id) {\n getReferenceById(getReferencesOfType(\"AGEventHandler\")[0]).removeGlobalEventByID(parseInt(_event_id));\n }",
"function getEntityFromElementID(entityID) {\n entityID = entityID.substring(6, entityID.length)\n var entity;\n // Look through all the squares\n for(i = 0; i < squares.length; i++){\n // If it has an entity and that entityElements id is equal to the id we're looking for\n if(squares[i] && squares[i].id == entityID) { \n entity = squares[i];\n break;\n }\n }\n return entity;\n}",
"function addEvent(eventID) {\r\n\t\tif($.inArray(eventID, eventIDs) < 0) {\r\n\t\t\teventIDs.push(eventID);\r\n\t\t}\r\n\t}",
"function remove_event_from_fullcalendar(eventId) {\n\ttimetableCalend.fullCalendar('removeEvents', eventId);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
================================= Simplified API access Ensures this instance is linked to a tradfri client and an accessory | ensureLink() {
if (this.client == null) {
throw new Error("Cannot use the simplified API on devices which aren't linked to a client instance.");
}
if (!(this._accessory instanceof accessory_1.Accessory)) {
throw new Error("Cannot use the simplified API on lightbulbs which aren't linked to an Accessory instance.");
}
} | [
"Xe() {\n return this.runTransaction(\"updateClientMetadataAndTryBecomePrimary\", \"readwrite\", t => er(t).put(new Fs(this.clientId, Date.now(), this.networkEnabled, this.inForeground)).next(() => {\n if (this.isPrimary) return this.sn(t).next(t => {\n t || (this.isPrimary = !1, this.Oe.enqueueRetryable(() => this.Qe(!1)));\n });\n }).next(() => this.rn(t)).next(e => this.isPrimary && !e ? this.on(t).next(() => !1) : !!e && this.an(t).next(() => !0))).catch(t => {\n if (zs(t)) // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return k(\"IndexedDbPersistence\", \"Failed to extend owner lease: \", t), this.isPrimary;\n if (!this.allowTabSynchronization) throw t;\n return k(\"IndexedDbPersistence\", \"Releasing owner lease after error during lease refresh\", t),\n /* isPrimary= */\n !1;\n }).then(t => {\n this.isPrimary !== t && this.Oe.enqueueRetryable(() => this.Qe(t)), this.isPrimary = t;\n });\n }",
"async function test_restrictedWithdrawals(instanceGetter, accounts) {\n // Get the instance that we're working with.\n const FROM = utils_1.makeFROM(accounts);\n let instance;\n let erc1155;\n utils_1.IT(\"Set up environment\", async () => {\n instance = await instanceGetter(accounts);\n erc1155 = await artifacts.require(\"StubERC1155_0\").deployed();\n // Approve the accounts for all transfers\n for (let i = 0; i < 3; i++) {\n await erc1155.setApprovalForAll(instance.address, true, FROM[i]);\n }\n // Enable withdrawal restrictions.\n await instance.changeRoleRestrictions(false, true);\n });\n utils_1.IT(\"Should be able to mint tokens\", async () => {\n // We give one token each to two accounts, the first is authorized the second not.\n for (let i = 0; i < 2; i++) {\n await utils_1.numberIs(erc1155, 0, \"\", \"balanceOf\", accounts[i], 1);\n await erc1155.mint(accounts[i], 1, 10);\n await utils_1.numberIs(erc1155, 10, \"\", \"balanceOf\", accounts[i], 1);\n }\n });\n utils_1.IT(\"Should be able to do initial deposit\", async () => {\n // Do an initial deposit so we can test withdrawals.\n await utils_1.numberIs(instance, 0, \"\", \"balanceOf\", accounts[0]);\n await utils_1.numberIs(erc1155, 10, \"\", \"balanceOf\", accounts[0], 1);\n await instance.deposit(accounts[0], [erc1155.address], [1], [8], FROM[0]);\n await utils_1.numberIs(instance, 8, \"\", \"balanceOf\", accounts[0]);\n await utils_1.numberIs(erc1155, 2, \"\", \"balanceOf\", accounts[0], 1);\n // Check the token details.\n const [fakeAddress, id, count] = await instance.tokenAt(0);\n utils_1.addressIs(fakeAddress, erc1155, \"Contract should match\");\n assert.equal(id.toNumber(), 1, \"ID should match\");\n assert.equal(count.toNumber(), 8, \"Count should match\");\n // Also send sone of the tokens to the other account so we can test for withdrawals.\n await instance.transfer(accounts[1], 3, FROM[0]);\n await utils_1.numberIs(instance, 5, \"\", \"balanceOf\", accounts[0]);\n await utils_1.numberIs(instance, 3, \"\", \"balanceOf\", accounts[1]);\n await utils_1.numberIs(erc1155, 2, \"\", \"balanceOf\", accounts[0], 1);\n });\n utils_1.IT(\"Should be able to withdraw\", async () => {\n await utils_1.numberIs(instance, 0, \"\", \"getTokenIndex\", erc1155.address, 1);\n await utils_1.numberIs(instance, 5, \"\", \"balanceOf\", accounts[0]);\n await utils_1.numberIs(erc1155, 2, \"\", \"balanceOf\", accounts[0], 1);\n await instance.withdrawTokens(accounts[0], [erc1155.address], [1], [1], FROM[0]);\n await utils_1.numberIs(instance, 4, \"\", \"balanceOf\", accounts[0]);\n await utils_1.numberIs(erc1155, 3, \"\", \"balanceOf\", accounts[0], 1);\n // Check the token details.\n const [fakeAddress, id, count] = await instance.tokenAt(0);\n utils_1.addressIs(fakeAddress, erc1155, \"Contract should match\");\n assert.equal(id.toNumber(), 1, \"ID should match\");\n assert.equal(count.toNumber(), 7, \"Count should match\");\n });\n utils_1.IT(\"Should not be able to withdraw\", async () => {\n await utils_1.expectReversion(instance, \"Invalid parameters\", accounts[1], \"withdrawTokens\", accounts[1], [erc1155.address], [1], [1]);\n });\n utils_1.IT(\"Should be able to withdraw after gaining permission\", async () => {\n await instance.setRoles([accounts[1]], true, false, false, true, FROM[0]);\n // Withdraw\n await utils_1.numberIs(instance, 3, \"\", \"balanceOf\", accounts[1]);\n await utils_1.numberIs(erc1155, 10, \"\", \"balanceOf\", accounts[1], 1);\n await instance.withdrawTokens(accounts[1], [erc1155.address], [1], [1], FROM[1]);\n await utils_1.numberIs(instance, 2, \"\", \"balanceOf\", accounts[1]);\n await utils_1.numberIs(erc1155, 11, \"\", \"balanceOf\", accounts[1], 1);\n // Check the token details.\n const [fakeAddress, id, count] = await instance.tokenAt(0);\n utils_1.addressIs(fakeAddress, erc1155, \"Contract should match\");\n assert.equal(id.toNumber(), 1, \"ID should match\");\n assert.equal(count.toNumber(), 6, \"Count should match\");\n });\n utils_1.IT(\"Should not be able to withdraw again\", async () => {\n await instance.setRoles([accounts[1]], false, false, false, true, FROM[0]);\n await utils_1.expectReversion(instance, \"Invalid parameters\", accounts[1], \"withdrawTokens\", accounts[1], [erc1155.address], [1], [1]);\n });\n }",
"onAddTetheredClient(tetheredClient) {\n super.onAddTetheredClient(tetheredClient);\n\n const client = tetheredClient.client;\n const myClient = tetheredClient.myClient;\n const incomingData = tetheredClient.incomingData;\n console.log(\"SharedRoom\", \"onAddMyClient\");\n }",
"function KeychainAccess() {\n\n}",
"constructor() { \n \n MozuTenantContractsTenant.initialize(this);\n }",
"async sellCar(ctx, carCRN, dealerCRN, adhaarNumber) {\n //Verify if this funtion is called by Dealer\n let verifyDealer = await ctx.clientIdentity.getMSPID();\n //calling the function carDeatils to retrieve the car details\n let carObject = this.carDetails(ctx, carCRN);\n //Verify if the function is called by Dealer and and also if he is the owner of the car\n if (verifyDealer === \"dealerMSP\" && dealerCRN === carObject.owner) {\n if (carObject !== undefined) {\n carObject.status = \"SOLD\";\n carObject.owner = adhaarNumber;\n //creating the composite key\n const carKey = ctx.stub.createCompositekey(\n \"org.cartracking-network.carnet.car\",\n [carCRN]\n );\n //converting the json object to buffer and saving it in blockchain\n let databuffer = Buffer.from(JSON.stringify(carObject));\n await ctx.stub.putState(carKey, carObject);\n }\n }\n }",
"async function attestationProviderPutPrivateEndpointConnection() {\n const subscriptionId = \"{subscription-id}\";\n const resourceGroupName = \"res7687\";\n const providerName = \"sto9699\";\n const privateEndpointConnectionName = \"{privateEndpointConnectionName}\";\n const properties = {\n privateLinkServiceConnectionState: {\n description: \"Auto-Approved\",\n status: \"Approved\",\n },\n };\n const credential = new DefaultAzureCredential();\n const client = new AttestationManagementClient(credential, subscriptionId);\n const result = await client.privateEndpointConnections.create(\n resourceGroupName,\n providerName,\n privateEndpointConnectionName,\n properties\n );\n console.log(result);\n}",
"static createTenant() {\n return HttpClient.post(`${TENANT_MANAGER_ENDPOINT}tenant`);\n }",
"async function confidentialLedgerGet() {\n const subscriptionId =\n process.env[\"CONFIDENTIALLEDGER_SUBSCRIPTION_ID\"] || \"0000000-0000-0000-0000-000000000001\";\n const resourceGroupName =\n process.env[\"CONFIDENTIALLEDGER_RESOURCE_GROUP\"] || \"DummyResourceGroupName\";\n const ledgerName = \"DummyLedgerName\";\n const credential = new DefaultAzureCredential();\n const client = new ConfidentialLedgerClient(credential, subscriptionId);\n const result = await client.ledger.get(resourceGroupName, ledgerName);\n console.log(result);\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}",
"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}",
"acquireSubContract() {\n acquireSubContract(this.props.contract, this.props.address, this.state.anytimeIndex).then(() => {\n this.setState({\n acquisitionError: \"\",\n acquisitionErrorDetails: null\n });\n\n this.props.callback();\n }, err => {\n this.setState({\n acquisitionError: \"Could not acquire sub-contract. The sub-contract's parent combinator may not yet have been acquired.\",\n acquisitionErrorDetails: err.toString()\n })\n });\n }",
"connect(initObject) {\n let {\n end, user, pass\n } = initObject;\n return new Promise(function(resolve, reject) {\n try {\n LRS = new TinCan.LRS({\n endpoint: end,\n username: user,\n password: pass,\n allowFail: false\n });\n resolve();\n } catch (err) {\n reject(err);\n }\n });\n }",
"function SetAPClerk(vbRec,vbSubs,vbOwner,k) {\t\t\t\n\tvar f3 = new Array();\n\tf3[0] = new nlobjSearchFilter('custrecord_spk_sr_ap_clerk_ons_sub',null,'anyof',vbSubs);\n\tf3[1] = new nlobjSearchFilter('isinactive',null,'is','F');\t\t\t\t\t\n\tvar col3 = new Array();\n\tcol3[0] = new nlobjSearchColumn('custrecord_spk_sr_ap_clerk_onshore_field');\n\tvar searchResult = nlapiSearchRecord('customrecord_spk_sr_ap_clerk_onshore',null,f3,col3);\n\tif(searchResult) {\n\t\tvar apclerkOnshoreRec = searchResult[0];\n\t\tvar apclerkOnshore = apclerkOnshoreRec.getValue('custrecord_spk_sr_ap_clerk_onshore_field');\n\t\tvar delegate_apclerkonshore = getDelegateApprover(apclerkOnshore);\n\t\tnlapiLogExecution('DEBUG', 'apClerkOnshore', delegate_apclerkonshore);\n\t\tvbRec.selectNewLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_seq', k);\n\t\tif(delegate_apclerkonshore) {\n\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr',delegate_apclerkonshore);\n\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_delgtof',apclerkOnshore);\n\t\t}\n\t\telse {\n\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr', apclerkOnshore);\n\t\t}\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvrl','Sr. AP Clerk');\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apmanager',nlapiGetUser());\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_invown',vbOwner);\n\t\tvbRec.commitLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t}\n}",
"function AuthenticationServiceIL(toaster) {\r\n try {\r\n var myIns = this;\r\n /// <summary>\r\n /// GetUserDetails : Get the User Details if it is anthenticate.\r\n /// </summary>\r\n /// <param name=\"UserName\">Provided UserName</param>\r\n /// <param name=\"Password\">Provided Password</param>\r\n /// <returns>User Details : It returns the true if it is valid and other information like (ServerId,UserName,OrganizationName ...) \r\n ///and returns false if the User credentials is invalid</returns>\r\n this.GetUserDetails = function (UserName, Password) {\r\n try {\r\n OneViewConsole.Debug(\"GetUserDetails Start\", \"AuthenticationServiceIL.GetUserDetails\");\r\n OneViewConsole.DataLog(\"UserName :\", JSON.stringify(UserName));\r\n OneViewConsole.DataLog(\"Password :\", JSON.stringify(Password));\r\n\r\n //Get Encrypted password\r\n // var _oOneViewEncryptionPlugin = new OneViewEncryptionPlugin();\r\n // Password= _oOneViewEncryptionPlugin.GetMd5HashString(Password);\r\n\r\n var _oOneViewChannel = new OneViewChannel();\r\n //_oOneViewChannel.toaster = toaster;\r\n _oOneViewChannel.url = oneViewGlobalVariables.RegistryURl + \"OneViewTokenFacedService.svc/GetUserDetails\";\r\n _oOneViewChannel.parameter = JSON.stringify({ \"UserName\": UserName, \"Password\": Password });\r\n var oUserDTO = _oOneViewChannel.Send();\r\n OneViewConsole.Debug(\"GetUserDetails End\", \"AuthenticationServiceIL.GetUserDetails\");\r\n if (oUserDTO != null) {\r\n OneViewConsole.DataLog(\"Response from Server\" + JSON.stringify(oUserDTO.GetUserDetailsResult), \"AuthenticationServiceIL.GetUserDetails\");\r\n return oUserDTO.GetUserDetailsResult;\r\n }\r\n else {\r\n return oUserDTO;\r\n }\r\n \r\n }\r\n catch (Excep) {\r\n throw oOneViewExceptionHandler.Create(\"IL\", \"AuthenticationServiceIL.GetUserDetails\", Excep);\r\n }\r\n finally {\r\n _oOneViewChannel = null;\r\n oUserDTO = null;\r\n }\r\n }\r\n\r\n\r\n /// <summary>\r\n /// GetServiceDetails : Get the Service Details for the authenticate user.\r\n /// </summary>\r\n /// <param name=\"UserId\">Logged in userid</param>\r\n /// <returns>Service Details : It returns the information like (ServiceId,ServiceName,ServiceOMGuid) \r\n /// if service is avilable for logged in user</returns>\r\n this.GetServiceDetails = function (UserId) {\r\n try {\r\n OneViewConsole.Debug(\"GetServiceDetails Start\", \"AuthenticationServiceIL.GetServiceDetails\");\r\n OneViewConsole.DataLog(\"UserId :\", JSON.stringify(UserId));\r\n\r\n var _oOneViewChannel = new OneViewChannel();\r\n _oOneViewChannel.url = oneViewGlobalVariables.RegistryURl + \"GetServiceDetails\";\r\n _oOneViewChannel.parameter = JSON.stringify({ \"UserId\": UserId });\r\n var oServiceDTO = _oOneViewChannel.Send();\r\n\r\n OneViewConsole.DataLog(\"Response from Server\" + JSON.stringify(oUserDTO.GetUserDetailsResult), \"AuthenticationServiceIL.GetServiceDetails\");\r\n OneViewConsole.Debug(\"GetServiceDetails End\", \"AuthenticationServiceIL.GetServiceDetails\");\r\n\r\n return oServiceDTO.GetServiceDetailsResult;\r\n }\r\n catch (Excep) {\r\n throw oOneViewExceptionHandler.Create(\"IL\", \"AuthenticationServiceIL.GetServiceDetails\", Excep);\r\n }\r\n finally {\r\n _oOneViewChannel = null;\r\n oServiceDTO = null;\r\n }\r\n }\r\n }\r\n catch (Excep) {\r\n throw oOneViewExceptionHandler.Create(\"IL\", \"IL.AuthenticationServiceIL\", Excep);\r\n }\r\n}",
"async getContract() {\n let res = await axios(`${rahatServer}/api/v1/app/contracts/Rahat`);\n const { abi } = res.data;\n res = await axios(`${rahatServer}/api/v1/app/settings`);\n const contractAddress = res.data.agency.contracts.rahat;\n return new ethers.Contract(contractAddress, abi, wallet);\n }",
"constructor() { \n \n MozuAppDevContractsProvisionTenantRequest.initialize(this);\n }",
"getClient() {\n return this.tadoClient;\n }",
"function initialize(callback){\n\n\tsoap.createClient(apiInfo.wsdl, { endpoint: apiInfo.endpoint }, function(err,client){ \n\t\tif(err){ console.log(err); callback(err); }\n\t\telse {\n\t\t\tclient.setSecurity(new soap.BasicAuthSecurity(apiInfo.httpUsername, apiInfo.httpPassword));\n\t\t\tsoapClient = client;\n\t\t\tcallback(null);\n\t\t}\n\t});\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Main worker method. checks all permutations of a given edit length for acceptance. | function execEditLength() {
for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
var basePath = /*istanbul ignore start*/void 0 /*istanbul ignore end*/;
var addPath = bestPath[diagonalPath - 1],
removePath = bestPath[diagonalPath + 1],
_oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
// No one else is going to attempt to use this value, clear it
bestPath[diagonalPath - 1] = undefined;
}
var canAdd = addPath && addPath.newPos + 1 < newLen,
canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
if (!canAdd && !canRemove) {
// If this path is a terminal then prune
bestPath[diagonalPath] = undefined;
continue;
}
// Select the diagonal that we want to branch from. We select the prior
// path whose position in the new string is the farthest from the origin
// and does not pass the bounds of the diff graph
if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
basePath = clonePath(removePath);
self.pushComponent(basePath.components, undefined, true);
} else {
basePath = addPath; // No need to clone, we've pulled it from the list
basePath.newPos++;
self.pushComponent(basePath.components, true, undefined);
}
_oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
// If we have hit the end of both strings, then we are done
if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
} else {
// Otherwise track this path as a potential candidate and continue.
bestPath[diagonalPath] = basePath;
}
}
editLength++;
} | [
"function execEditLength() {\n\t for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {\n\t var basePath;\n\t var addPath = bestPath[diagonalPath - 1];\n\t var removePath = bestPath[diagonalPath + 1];\n\t var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;\n\n\t if (addPath) {\n\t // No one else is going to attempt to use this value, clear it\n\t bestPath[diagonalPath - 1] = undefined;\n\t }\n\n\t var canAdd = addPath && addPath.newPos + 1 < newLen;\n\t var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;\n\n\t if (!canAdd && !canRemove) {\n\t // If this path is a terminal then prune\n\t bestPath[diagonalPath] = undefined;\n\t continue;\n\t } // Select the diagonal that we want to branch from. We select the prior\n\t // path whose position in the new string is the farthest from the origin\n\t // and does not pass the bounds of the diff graph\n\n\n\t if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {\n\t basePath = clonePath(removePath);\n\t self.pushComponent(basePath.components, undefined, true);\n\t } else {\n\t basePath = addPath; // No need to clone, we've pulled it from the list\n\n\t basePath.newPos++;\n\t self.pushComponent(basePath.components, true, undefined);\n\t }\n\n\t oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath); // If we have hit the end of both strings, then we are done\n\n\t if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {\n\t return buildValues(self, basePath.components, newArr, oldArr);\n\t } else {\n\t // Otherwise track this path as a potential candidate and continue.\n\t bestPath[diagonalPath] = basePath;\n\t }\n\t }\n\n\t editLength++;\n\t }",
"function generateAndCheck(input, length) {\n while (true) {\n if (input.length >= length) {\n return checksum(input.slice(0, length));\n break;\n }\n input = dragonIt(input);\n }\n}",
"function checkAllInputs() {}",
"checkPartecipants(){\n \n }",
"_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 }",
"function checkSequence(){\n\t\t\n\t\t//position 3,3 is the bottom right box which must be empty\n\t\t//this if checks that condition\n\t\tif(getBox(2, 2).className != 'em_box'){\n\t\t\treturn;\n\t\t}\n\t\n\t\tvar k= 1;\n\n\t\t//checks number of all boxs\n\t\tfor(var i = 0; i <= 2; i++){ \n\t\t\tfor(var j = 0; j <= 2; j++){\n\t\t\t\tif(k <= 8 && getBox(i, j).innerHTML != k.toString()){ //if postion(i,j) order does not equal string order\n\t\t\t\t\t// Order is incorrect\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// if the puzzle is solved then a msg pops up with thi msg\n\t\t//The confirm() method displays a dialog box with a specified message, along with an OK and a Cancel button\n\t\tif(confirm('Congratulation! You won!!!\\nShuffle the puzzle?')){\n\t\t\tshuffle(); //if they clicked yes then shuffle function is called\n\t\t}\n\t\n\t}",
"function requirement_checker(passwordData, passwordObjects, gridWidth, gridHeight) {\r\n //used R G B \"boolean\" values\r\n let coloursUsed = [0, 0, 0],\r\n uniqueNodesUsed = [], //used coordinates, again \"boolean\" values\r\n uniqueNodesUsedCounter = 0;\r\n let i = 0, j = 0;\r\n let tempX = 0, tempY = 0;\r\n\r\n //input error handling\r\n if(typeof gridHeight != \"number\" || typeof gridWidth != \"number\") {\r\n console.log(\"requirement_checker - error: gridHeight and/or gridWidth not a number\")\r\n return;\r\n }\r\n if(typeof passwordObjects != \"number\") {\r\n console.log(\"requirement_checker - error: passwordObjects not a number\")\r\n return;\r\n }\r\n if(passwordObjects == 0) {\r\n return 0; //not within requirements\r\n } else if (passwordObjects < 0) {\r\n console.log(\"requirement_checker - error: passwordObjects less than 0\")\r\n return;\r\n }\r\n\r\n\r\n //finds colours used\r\n for(i = 0; i < passwordObjects; ++i) {\r\n if(passwordData[i].colour == \"red\") {\r\n coloursUsed[0] = 1;\r\n } else if (passwordData[i].colour == \"green\") {\r\n coloursUsed[1] = 1;\r\n } else if (passwordData[i].colour == \"blue\") {\r\n coloursUsed[2] = 1;\r\n } else {\r\n console.log(\"requirement_checker - error: wrong colour\");\r\n }\r\n }\r\n //checks colours used\r\n if(coloursUsed[0] + coloursUsed[1] + coloursUsed[2] < 2) {\r\n //console.log(\"fail: colours used is \" + (coloursUsed[0] + coloursUsed[1] + coloursUsed[2]));\r\n return 0; //not within requirements\r\n }\r\n\r\n //makes uniqueNodesUsed into a 2D array and sets everything to 0\r\n for(i = 0; i < gridHeight; ++i) {\r\n uniqueNodesUsed[i] = [];\r\n for(j = 0; j < gridWidth; ++j){\r\n uniqueNodesUsed[i][j] = 0;\r\n }\r\n }\r\n //finds unique nodes used\r\n for(i = 0; i < passwordObjects; ++i) {\r\n //separate into cases point / arrow / connected lines\r\n if(passwordData[i].type == \"point\") {\r\n tempX = passwordData[i].id[7];\r\n tempY = passwordData[i].id[9];\r\n uniqueNodesUsed[tempX][tempY] = 1;\r\n } else if(passwordData[i].type == \"arrow\") {\r\n tempX = passwordData[i].idStart[7];\r\n tempY = passwordData[i].idStart[9];\r\n uniqueNodesUsed[tempX][tempY] = 1;\r\n tempX = passwordData[i].idEnd[7];\r\n tempY = passwordData[i].idEnd[9];\r\n uniqueNodesUsed[tempX][tempY] = 1;\r\n } else if(passwordData[i].type == \"connected lines\") {\r\n for(j = 0; j < passwordData[i].IDs.length; ++j) {\r\n tempX = passwordData[i].IDs[j][7];\r\n tempY = passwordData[i].IDs[j][9];\r\n uniqueNodesUsed[tempX][tempY] = 1;\r\n }\r\n } else {\r\n console.log(\"requirement_checker - error: wrong password object type\");\r\n }\r\n }\r\n\r\n //checks unique nodes used\r\n for(i = 0; i < gridHeight; ++i) {\r\n for(j = 0; j < gridWidth; ++j){\r\n uniqueNodesUsedCounter += uniqueNodesUsed[i][j];\r\n }\r\n }\r\n if(uniqueNodesUsedCounter < 10) {\r\n //console.log(\"fail: nodes used is \" + uniqueNodesUsedCounter);\r\n return 0; //not within requirements\r\n }\r\n return 1; //within requirements\r\n}",
"static consistencyCheck()\n {\n const folder = QuestFolder.get();\n\n if (!folder || Utils.isFQLHiddenFromPlayers()) { return; }\n\n const questEntryMap = new Map(QuestDB.getAllQuestEntries().map((e) => [e.id, e]));\n\n const isTrustedPlayerEdit = Utils.isTrustedPlayerEdit();\n\n for (const entry of folder.content)\n {\n const content = entry.getFlag(constants.moduleName, constants.flagDB);\n\n if (content)\n {\n if (s_IS_OBSERVABLE(content, entry, isTrustedPlayerEdit))\n {\n let questEntry = questEntryMap.get(entry.id);\n\n if (!questEntry)\n {\n questEntry = new QuestEntry(new Quest(content, entry));\n s_SET_QUEST_ENTRY(questEntry.hydrate());\n\n Hooks.callAll('addQuestEntry', questEntry, entry.flags, { diff: false, render: true }, entry.id);\n }\n else\n {\n questEntry.update(content, entry);\n }\n }\n else\n {\n const questEntry = questEntryMap.get(entry.id);\n if (questEntry)\n {\n questEntryMap.delete(entry.id);\n s_REMOVE_QUEST_ENTRY(entry.id);\n\n // This quest is not deleted; it has been removed from the in-memory DB.\n Hooks.callAll('removeQuestEntry', questEntry, entry.flags, { diff: false, render: true }, entry.id);\n }\n }\n }\n }\n\n this.enrichAll();\n }",
"function calculatePossible(){\n\tvar allLetters = '';\n\tvar l = table.find('button');\n\tfor(var i = 0; i < l.length; i++){\n\t\tallLetters += l[i].innerHTML;\n\t}\n\t\tvar canBeFormed;\n\t\tvar yesCounter;\n\t\tvar tmpAllLetters;\n\t\tfor(var k = 0; k < wordsArray.length; k ++){\n\t\t\tyesCounter = 0;\n\t\t\ttmpAllLetters = allLetters;\n\t\t\tif(canBeFormed == true){\n\t\t\t\tvar postfixNum = k - 1;\n\t\t\t\tlsId = \"ls\" + postfixNum;\n\t\t\t\t$('#' + lsId).addClass('text-warning');\n\t\t\t\t$('#' + lsId).css( \"color\", \"orange\" );\n\t\t\t\tCheckStatus(lsId);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tvar postfixNum = k - 1;\n\t\t\t\tlsId = \"ls\" + postfixNum;\n\t\t\t\t$('#' + lsId).removeClass('text-warning');\n\t\t\t\t$('#' + lsId).css(\"color\", \"#333333\");\n\t\t\t\tstopCounter(lsId);\n\t\t\t}\n\t\t\tfor(var l = 0; l < wordsArray[k].length; l++){\n\t\t\t\tcanBeFormed = false;\n\t\t\t\tfor(var m = 0; m < tmpAllLetters.length; m++){\n\t\t\t\t\tif(wordsArray[k].charAt(l) == tmpAllLetters.charAt(m)){\n\t\t\t\t\t\tyesCounter++;\n\t\t\t\t\t\tvar let = wordsArray[k].charAt(l);\n\t\t\t\t\t\tvar reg = new RegExp(let);\n\t\t\t\t\t\ttmpAllLetters = tmpAllLetters.replace(reg, \"\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\tif(yesCounter == wordsArray[k].length){\n\t\t\t\t\tcanBeFormed = true;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tcanBeFormed = false;\n\t\t\t\t}\n\t\t}\n\t\tif(canBeFormed == true){\n\t\t\tvar postfixNum = k - 1;\n\t\t\tlsId = \"ls\" + postfixNum;\n\t\t\t$('#' + lsId).addClass('text-warning');\n\t\t\t$('#' + lsId).css(\"color\", \"orange\");\n\t\t\tCheckStatus(lsId);\n\t\t}\n\t\telse{\n\t\t\tvar postfixNum = k - 1;\n\t\t\tlsId = \"ls\" + postfixNum;\n\t\t\t$('#' + lsId).removeClass('text-warning');\n\t\t\t$('#' + lsId).css(\"color\", \"#333333\");\n\t\t\tstopCounter(lsId);\n\t\t}\n}",
"function compareSet(base,arr){\r\n\tvar tot = 0;\r\n\tvar matched_any = false;\r\n\tvar breakable = false;\r\n\tvar invalid = false;\r\n\t\r\n\tvar words = base.words;\r\n\tvar in_arr = arr;\r\n\t\r\n\tvar a = 0;\r\n\tvar b = 0;\r\n\t\r\n\tfor (b in words) {\r\n\t\tvar b_w = words[b];\r\n\t\t\t\r\n\t\tfor(a in in_arr){\r\n\t\t\tvar in_w = in_arr[a];\r\n\t\t\t\r\n\t\t\tif(typeof(b_w) == \"object\"){\r\n\t\t\t\tconsole.log(\"checkList in keylist - \" + base.action);\r\n\t\t\t\tif(iterateCheckList(b_w,in_w)){\r\n\t\t\t\t\tvar invalid = false;\r\n\t\t\t\t\ttot += 1;\r\n\t\t\t\t\tif (base.any) {\r\n\t\t\t\t\t\tmatched_any = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tvar invalid = true;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t} else if(typeof(b_w) == \"function\"){\r\n\t\t\t\tconsole.log('function in keylist - ' + base.action);\r\n\t\t\t\tvar b = b_w(in_w); //TODO if match => userInput.check[base.id] = in_w\r\n\t\t\t\tif(b == true){\r\n\t\t\t\t\t//userInput.check[base.id] = in_w;\r\n\t\t\t\t\ttot += 1;\r\n\t\t\t\t\tif (base.any) {\r\n\t\t\t\t\t\tmatched_any = true;\r\n\t\t\t\t\t\tbreakable = true;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t} else if(b_w == in_w){\r\n\t\t\t\ttot += 1;\r\n\t\t\t\tif (base.any) {\r\n\t\t\t\t\tmatched_any = true;\r\n\t\t\t\t\tbreakable = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\tif(breakable)\r\n\t\t\tbreak;\r\n\t}\r\n\t\r\n\tvar tot_a = tot/in_arr.length; \t// the % of matched words in 'arr'\r\n\tvar tot_b = typeof(words) == \"object\" ? tot/words.length : 0.5; \t// the % of matched words in 'base'\r\n\t\r\n\t// if base.any && matched_any => return 1.0 else return median of tot_a & tot_b\r\n\tvar p = matched_any ? 1.0 : (tot_a+tot_b)*0.5;\r\n\tif (invalid)\r\n\t\tp = 0;\r\n\t\r\n\t//var f = p < 0.5 ? 0 : p;\r\n\t\r\n\t/* console.log(\"tot_matched: \" + tot,\r\n\t\t\t\t\"percent: \" + (tot_a+tot_b)*0.5,\r\n\t\t\t\t\"final score: \" + p); */\r\n\t\r\n\treturn p;\r\n}",
"function numKeypadSolutions(wordlist, keypads) {\n // Write your code here\n // INPUT: an array of acceptable words\n // an array of 7 letter strings, each letter representing a key button\n // OUTPUT: array of numbers corresponding to the number of words from wordlist\n // that can be made from each keypad in order\n // CONSTRAINTS: all words in wordlist are at least 5 letters long\n // first letter of each keypad is guaranteed to be in the word\n // longest word in scrabble dictionary is 15 characters long - must be faster way\n // EDGE CASES: what happens if no letters match?\n\n // iterate over wordlist, and store a set in a new wordlist array of all letters of word\n let wordListSets = wordlist.map(word => {\n let wordSet = new Set();\n for(let i=0; i < word.length; i++) {\n let letter = word[i];\n if(!wordSet.has(letter)) { wordSet.add(letter) }\n }\n return wordSet;\n });\n\n // write a mapping function that takes a keypad string\n // initiates a count at 0\n // makes a set of the string\n // loops through the entire new wordlist array\n // if the word doesn't have keypadstring[0] continue\n // if all letters in word set are contained in string set increment the count\n // return the count\n let numValidSolutions = keypads.map(keyString => {\n let solutionCount = 0;\n let keyStringSet = new Set();\n for(let i=0; i < keyString.length; i++) {\n let letter = keyString[i];\n if(!keyStringSet.has(letter)) { keyStringSet.add(letter) }\n }\n\n for(let j = 0; j < wordListSets.length; j++) {\n let allLettersPresent = true;\n let wordSetInQuestion = wordListSets[j];\n if (!wordSetInQuestion.has(keyString[0])) { continue }\n for(let letter of wordSetInQuestion) {\n if(!keyStringSet.has(letter)) {\n allLettersPresent = false;\n break;\n }\n }\n\n if (allLettersPresent) { solutionCount++ }\n }\n\n return solutionCount;\n })\n\n return numValidSolutions;\n // THE ULTRA 1337 SOLUTION USES A BIT MASK. WTF IS THAT\n}",
"function sanityCheck(){\n if(!passLowerCase && !passUpperCase && !passNumeric && !passSpecial){\n // We can't have a password without anything in it!\n passLowerCase=true;\n document.getElementById(\"include-lowercase\").checked=true;\n }\n if(passLength>maxPassLength){\n // Larger passwords are more secure, but let's set a limit somewhere!\n passLength=maxPassLength;\n document.getElementById(\"length-input\").value=maxPassLength;\n }\n if(passLength<1){\n // We probably shouldn't allow the user to have a one character password\n // But we certainly can't let them have a -5 character password!\n passLength=1;\n document.getElementById(\"length-input\").value=1;\n }\n}",
"function sudokuVerifier(grid) { \n let columns = [];\n let squares = [];\n \n //Grabbing columns\n for(let i = 0; i < 9; i++){\n let tempColumn = [];\n for(let j = 0; j < 9; j++){\n tempColumn.push(grid[j][i]);\n }\n columns.push(tempColumn);\n }\n //grabbing squares, the first two for loops control the current square\n //for instance, i = 0 and j = 0 they are grabbing the top left square\n //they are just multipliers for the position\n for( let i = 0; i < 3; i++){\n for( let j = 0; j < 3; j++){\n let tempSquare = [];\n for(let k = 0; k < 3; k++){\n for(let l = 0; l < 3; l++){\n let x = k + (i * 3);\n let y = l + (j * 3);\n tempSquare.push(grid[x][y]);\n }\n }\n squares.push(tempSquare);\n }\n }\n // numbers in the arrays are still strings, plus the placeholder is a period\n let validChars = '123456789.'.split('');\n return [columns, squares, grid].every( rows => { // All the grids, horizontal, vertical, squares\n return rows.every( row => { // rows in each grid\n let prevArr = [];\n if(row.length !== 9){\n return false;\n }\n return row.every( char => {\n //checks if its a valid character and it hasn't been called before\n if(!prevArr.includes(char) && validChars.includes(char)){\n //dont want to add the place holder otherwise most puzzles would fail!\n if(char !== '.'){\n prevArr.push(char)\n }\n return true;\n } else {\n return false;\n }\n });\n })\n })\n}",
"handleMutations() {\n // Copy and clear parkedNodes.\n let _parkedNodes = this.parkedNodes.slice()\n this.parkedNodes = []\n // Handle mutations if it probably isn't too much to handle\n // (current limit is totally random).\n if (_parkedNodes.length < 151) {\n this.logger.debug(`${this}processing ${_parkedNodes.length} parked nodes.`)\n let batchSize = 40 // random size\n for (let i = 0; i < Math.ceil(_parkedNodes.length / batchSize); i++) {\n ((index) => {\n setTimeout(() => {\n for (let j = index * batchSize; j < (index + 1) * batchSize; j++) {\n let node = _parkedNodes[j]\n let stillInDocument = document.contains(node) // no lookup costs\n if (stillInDocument) {\n this.insertIconInDom(node)\n }\n }\n }, 0) // Push back execution to the end on the current event stack.\n })(i)\n }\n }\n }",
"function PunishmentCheck() {\r\n // We check if a restraint is invalid\r\n for (let i = cursedConfig.punishmentRestraints.length - 1; i >= 0; i--) {\r\n if (!Asset.find(A => A.Name === cursedConfig.punishmentRestraints[i].name && A.Group.Name === cursedConfig.punishmentRestraints[i].group)) {\r\n delete cursedConfig.punishmentRestraints[i];\r\n popChatSilent({ Tag: \"ErrorInvalidPunishment\"}, \"System\");\r\n }\r\n }\r\n\r\n cursedConfig.punishmentRestraints = cursedConfig.punishmentRestraints.filter(PR => PR);\r\n\r\n // Check if we need to punish\r\n const difference = cursedConfig.strikes - cursedConfig.lastPunishmentAmount;\r\n const stageFactor = cursedConfig.strictness * 15;\r\n let r = false;\r\n if (difference > stageFactor && !cursedConfig.punishmentsDisabled) {\r\n //More restraints per stages, resets every week\r\n cursedConfig.punishmentRestraints.forEach(PR => {\r\n r = WearPunishment(PR.stage, PR.name, PR.group) || r;\r\n });\r\n if (r) {\r\n TryPopTip(41);\r\n SendChat({ Tag: \"PunishmentTriggered\"});\r\n }\r\n cursedConfig.lastPunishmentAmount = cursedConfig.strikes;\r\n }\r\n return r;\r\n}",
"function checkAllLegalMoves(oldPosition, faction, isFirstTurn){\n let oldPositionDiv = document.getElementById(oldPosition)\n let splitPosition = oldPosition.split(\"\")\n let letter = splitPosition[0]\n let number = splitPosition[1]\n\n //black goes up; black is 0 and K\n //kings and queens should have access to both sides' move options trees\n if (faction === \"black\" || oldPositionDiv.innerText === \"K\" || oldPositionDiv.innerText === \"Q\"){ \n //increments and decrements letter of new position (\"B\" becomes \"C\" and \"A\")\n let columnA = String.fromCharCode(letter.charCodeAt(0) + 1)\n let columnB = String.fromCharCode(letter.charCodeAt(0) - 1)\n let row = checkAboveRow(number)\n // below lines concatenate new column with row\n let newPositionA = columnA.concat(checkAboveRow(number)).toString()\n let newPositionB = columnB.concat(checkAboveRow(number)).toString()\n \n if (validColumn(columnA) && validRow(row)) {\n let moveDivA = document.getElementById(newPositionA)\n //if potential space to move in is empty, push it into validMoves Array\n if (moveDivA.innerText === \"\" && isFirstTurn){\n validMovesArray.push(newPositionA)\n }\n //else, if potential space to move in is occupied by opposite team\n //check if that's a possible attack opening\n if (moveDivA.innerText === \"1\"){\n //get rid of determinedirection???\n \n let direction = determineBlackDirection(oldPosition, newPositionA)\n blackAttack(newPositionA, direction)\n }\n } \n if (validColumn(columnB) && validRow(row)) {\n let moveDivB = document.getElementById(newPositionB)\n //if potential space to move in is empty, push it into validMoves Array\n if (moveDivB.innerText === \"\" && isFirstTurn){\n validMovesArray.push(newPositionB)\n }\n //else, if potential space to move in is occupied by opposite team\n //check if that's a possible attack opening\n if (moveDivB.innerText === \"1\"){ \n let direction = determineBlackDirection(oldPosition, newPositionB)\n blackAttack(newPositionB, direction)\n } \n }\n }\n //white goes down; white is 1 and Q\n //kings and queens should have access to both sides' moves options trees\n if (faction === \"white\" || oldPositionDiv.innerText === \"K\" || oldPositionDiv.innerText === \"Q\" ) {\n //increments and decrements letter of new position (\"B\" becomes \"C\" and \"A\")\n let columnA = String.fromCharCode(letter.charCodeAt(0) + 1)\n let columnB = String.fromCharCode(letter.charCodeAt(0) - 1)\n let row = checkBelowRow(number)\n // below lines concatenate new column with row\n let newPositionA = columnA.concat(checkBelowRow(number)).toString()\n let newPositionB = columnB.concat(checkBelowRow(number)).toString()\n\n //below two lines concatenate new columns with below row\n if (validColumn(columnA) && validRow(row)) {\n let moveDivA = document.getElementById(newPositionA)\n //if potential space to move in is empty, push it into validMoves Array\n if (moveDivA.innerText === \"\" && isFirstTurn){\n validMovesArray.push(newPositionA)\n }\n //else, if potential space to move in is occupied by opposite team\n //check if that's a possible attack opening\n if (moveDivA.innerText === \"0\"){\n let direction = determineWhiteDirection(oldPosition, newPositionA)\n whiteAttack(newPositionA, direction)\n }\n } \n if (validColumn(columnB) && validRow(row)) {\n let moveDivB = document.getElementById(newPositionB)\n //if potential space to move in is empty, push it into validMoves Array\n if (moveDivB.innerText === \"\" && isFirstTurn){\n validMovesArray.push(newPositionB)\n }\n //else, if potential space to move in is occupied by opposite team\n //check if that's a possible attack opening\n if (moveDivB.innerText === \"0\"){\n let direction = determineWhiteDirection(oldPosition, newPositionB)\n whiteAttack(newPositionB, direction)\n }\n } \n }\n }",
"function rowsChecker(puzzle){\n for(let i=0;i<9;i++){\n if(repeatsChecker(getRow(puzzle,i))===false){\n return false\n }\n }\n return true\n}",
"function permutation(courses, arrangement) {\n if (courses.length == 0) {\n permutations.push(arrangement);\n } else {\n // check to see that course is not empty i.e wrong course\n if (courses[0].meeting_sections != null){\n //check to see that there are meeting sections for the course\n if (courses[0].meeting_sections.length != 0){\n for (var i = 0; i < courses[0].meeting_sections.length; i++) {\n // if its a lecture section, add the course.\n //if (courses[0].meeting_sections[i].code[0] == 'L' && courses[0].meeting_sections[i].times.length != 0) {\n var course = {\n \"meeting_section\" : courses[0].meeting_sections[i],\n \"course_code\" : courses[0].code\n };\n var newArrangement = arrangement.slice(0);\n newArrangement.push(course);\n\n permutation(courses.slice(1), newArrangement);\n //} else {\n // tutorial, skip this iteration\n //continue; \n //} \n }\n } else {\n //no meeting section, alert user, continue to next course\n permutation(courses.slice(1), arrangement);\n }\n }\n else{\n //wrong course, alert user, continue to next course\n permutation(courses.slice(1), arrangement);\n }\n }\n \n}",
"function generatePassword() {\n var useableCharactersArray = [];\n getUserPreferences();\n var lowerArray = []; \n var upperArray = [];\n var numberArray = [];\n var specialCharsArray = [];\n if (userPreferences.useLowerCase) {\n lowerArray = Array.from(lowercaseAlphabet);\n for (var i = 0; i < lowercaseLength; i++) {\n useableCharactersArray.push(lowerArray[i]);\n };\n } else {\n console.log(useableCharactersArray.length);\n };\n if (userPreferences.useUpperCase) {\n upperArray = Array.from(uppercaseAlphabet);\n for (var i = 0; i < uppercaseLength; i++) {\n useableCharactersArray.push(upperArray[i]);\n };\n } else {\n console.log(useableCharactersArray.length);\n };\n if (userPreferences.useNumbers) {\n numberArray = Array.from(useableNumbers);\n for (var i = 0; i < useableNumbersLength; i++) {\n useableCharactersArray.push(numberArray[i]);\n };\n } else {\n console.log(useableCharactersArray.length);\n };\n if (userPreferences.useSpecialCharacters) {\n specialCharsArray = Array.from(specialCharacters);\n for (var i = 0; i < specialCharactersLength; i++) {\n useableCharactersArray.push(specialCharsArray[i]);\n };\n } else {\n console.log(useableCharactersArray.length);\n };\n // final if statement to validate whether user has input the minimum requirements resulting in a useableCharacterArray.length > 0\n // if no character types are confirmed, this if statement will force user to start from the getPasswordLengthPreference via generatePassword calling getUserPreferences\n if (useableCharactersArray.length == 0) {\n return generatePassword();\n } else {\n var password = '';\n for (let i = 0; i < userPreferences.passwordLength; i++) {\n password += useableCharactersArray[Math.floor(Math.random()*useableCharactersArray.length)]\n };\n };\n return password;\n}",
"quitarValores(iteracion, maxIteracion, valoresPrevios, valoresMenosUno){\n let validar=false; //Esta variable va a ser la que indique si el valor que se quita permite una soluci[on [unica o no\n do {\n validar=false;\n const cuadrado = Math.floor(Math.random() * (9));\n const posicion = Math.floor(Math.random() * (9));\n if(this.valoresFinales[cuadrado][posicion] !=\"\"){\n this.valoresFinales[cuadrado][posicion] = \"\";\n for (let i = 0; i < 9; i++) {\n for (let j = 0; j < 9; j++) {\n valoresMenosUno[i][j] = this.valoresFinales[i][j];\n }\n }\n this.solucionarSudoku();\n if (this.isTableroLleno()) {\n validar = true;\n } else {\n for (let i = 0; i < 9; i++) {\n for (let j = 0; j < 9; j++) {\n this.valoresFinales[i][j] = valoresPrevios[i][j];\n }\n }\n }\n }\n } while (!validar);\n for (let i = 0; i < 9; i++) {\n for (let j = 0; j < 9; j++) {\n this.valoresFinales[i][j] = valoresMenosUno[i][j];\n valoresPrevios[i][j] = valoresMenosUno[i][j];\n }\n }\n if(iteracion !== maxIteracion){\n iteracion++\n this.quitarValores(iteracion, maxIteracion, valoresPrevios, valoresMenosUno);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=========================================================================================== Functions calculates the angle for the middle of a slice | function midAngle(d) { return d.startAngle + (d.endAngle - d.startAngle) / 2; } | [
"@computed\n get sideCenterAngles() {\n const sideSum = this.windowDimensions.width + this.windowDimensions.height;\n const topBottom = this.windowDimensions.width / sideSum * Math.PI;\n const leftRigth = Math.abs(topBottom - Math.PI);\n return { topBottom, leftRigth };\n }",
"calculateRotation() {\n const extentFeature = this._extentFeature;\n const coords = extentFeature.getGeometry().getCoordinates()[0];\n const p1 = coords[0];\n const p2 = coords[3];\n const rotation = Math.atan2(p2[1] - p1[1], p2[0] - p1[0]) * 180 / Math.PI;\n\n return -rotation;\n }",
"function angle(line) {\n return Math.atan2(line[1][1] - line[0][1], line[1][0] - line[0][0]) * 180 / Math.PI;\n} // Returns the midpoint of a line.",
"function calcAngle(startPosition, endPosition) {\n let angle = 0;\n\n if (endPosition < startPosition) {\n angle = PI * 2 - Math.abs(endPosition - startPosition);\n } else if (endPosition > startPosition) {\n angle = endPosition - startPosition;\n }\n\n return angle;\n}",
"function clockwise_angle(pt, centre) {\n var recentred = sum(pt, scale(-1., centre));\n var anticlockwise_angle = Math.atan2(recentred[1], recentred[0]);\n return -1 * anticlockwise_angle;\n}",
"function calcAngle(a, b) {\n return Math.atan2(b[1] - a[1], b[0] - a[0]) * 180 / Math.PI;\n}",
"function clockwise_arc_length(angle0, angle1) {\n var diff = angle1 - angle0;\n while (diff < 0) {\n diff = diff + 2 * Math.PI;\n }\n return diff;\n}",
"angle(v) {\n let d = this.dot(v);\n let m = this.mag() * v.mag();\n return Math.acos(d/m);\n }",
"function getAngle(x, y) { \n return Math.atan(y/(x==0?0.01:x))+(x<0?Math.PI:0); \n}",
"function shouldFlipLabel(startAngle, endAngle) {\n return (\n // End angle lies beyond a quarter of a circle (90 degrees or pi/2)\n radiansToDegrees(endAngle) > 90 &&\n radiansToDegrees(endAngle) < 270 &&\n // Slice \"length\" is less than 180 degrees\n radiansToDegrees(endAngle - startAngle) < 180\n );\n }",
"get rulerBearing() {\n let dx = this.mRulerGeom.vertices[1].x - this.rulerStart.x;\n let dy = this.mRulerGeom.vertices[1].y - this.rulerStart.y;\n if (dy === 0)\n return dx < 0 ? 270 : 90;\n let quad = (dx > 0) ? ((dy > 0) ? 0 : 180) : ((dy > 0) ? 360 : 180);\n return Math.round(quad + 180 * Math.atan(dx / dy) / Math.PI);\n }",
"function angularCoord(x, y)\n {\n var phi = 0.0;\n\n if (x > 0 && y >= 0) {\n phi = Math.atan(y / x);\n }\n if (x > 0 && y < 0) {\n phi = Math.atan(y / x) + 2 * Math.PI;\n }\n if (x < 0) {\n phi = Math.atan(y / x) + Math.PI;\n }\n if (x = 0 && y > 0) {\n phi = Math.PI / 2;\n }\n if (x = 0 && y < 0) {\n phi = 3 * Math.PI / 2;\n }\n\n return phi;\n }",
"subtractAngles (rad1, rad2) {\n const PI = Math.PI\n let dr = rad1 - rad2\n if (dr <= -PI) dr += 2 * PI\n if (dr > PI) dr -= 2 * PI\n return dr\n }",
"function lerpAnglesInDegrees(i, min, max) {\n if (i <= 0.0) {\n return min % 360.0;\n }\n else if (i >= 1.0) {\n return max % 360.0;\n }\n const a = (min - max + 360.0) % 360.0;\n const b = (max - min + 360.0) % 360.0;\n if (a <= b) {\n return (min - a * i + 360.0) % 360.0;\n }\n return (min + a * i + 360.0) % 360.0;\n}",
"arg() {\n if (this.equalTo(0)) {\n return undefined;\n }\n\n if (this.re < 0 && y == 0) {\n return Math.PI;\n }\n\n return 2 * Math.atan(this.im / (this.abs() + this.re));\n }",
"function theta_oh(o,h) {\n console.log((Math.asin(o/h))*180/Math.PI)\n}",
"function getAngle(point) {\n\n var x1 = point.lx - point.ax\n var y1 = point.ly - point.ay\n var x2 = point.rx - point.ax\n var y2 = point.ry - point.ay\n\n return Math.atan2((y2 * x1) - (x2 * y1), (x2 * x1) + (y2 * y1)) * 180 / Math.PI\n}",
"setCorrectRotation (raoad) {\r\n var pointBefore = this._lastRoad.children[0].children\r\n\r\n var SlopEndPosition2 = pointBefore[\r\n pointBefore.length - 1\r\n ].parent.convertToWorldSpace(pointBefore[pointBefore.length - 1].position)\r\n var SlopEndPosition1 = pointBefore[\r\n pointBefore.length - 2\r\n ].parent.convertToWorldSpace(pointBefore[pointBefore.length - 2].position)\r\n\r\n var slopEndY = SlopEndPosition2.y - SlopEndPosition1.y\r\n var slopEndX = SlopEndPosition2.x - SlopEndPosition1.x\r\n\r\n var point = raoad.children[0].children\r\n var SlopStartPosition2 = point[1].parent.convertToWorldSpace(\r\n point[1].position\r\n )\r\n var SlopStartPosition1 = point[0].parent.convertToWorldSpace(\r\n point[0].position\r\n )\r\n\r\n var slopeStartY = SlopStartPosition2.y - SlopStartPosition1.y\r\n var slopeStartX = SlopStartPosition2.x - SlopStartPosition1.x\r\n\r\n var angleBefore = Math.atan2(slopEndX, slopEndY)\r\n var angleStart = Math.atan2(slopeStartX, slopeStartY)\r\n\r\n raoad.rotation = cc.radiansToDegrees(angleBefore - angleStart)\r\n }",
"function getDegreeValue() {\r\n var transformValue = ballStyle.transform;\r\n var values = transformValue.split('(')[1].split(')')[0].split(',');\r\n var a = values[0];\r\n var b = values[1];\r\n var c = values[2];\r\n var d = values[3];\r\n\r\n var scale = Math.sqrt(a * a + b * b);\r\n var sin = b / scale;\r\n return angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));\r\n }",
"function findAngle(object, unit, directions) {\n// var dy = (object.y) - (unit.y);\n// var dx = (object.x) - (unit.x);\n var direction;\n if (object.x > unit.x) {\n if (object.y > unit.y) {\n direction = 3;\n } else if (object.y < unit.y) {\n direction = 1;\n } else {\n direction = 2;\n }\n } else if (object.x < unit.x) {\n if (object.y > unit.y) {\n direction = 5;\n } else if (object.y < unit.y) {\n direction = 7;\n } else {\n direction = 6;\n }\n } else if (object.y > unit.y) {\n direction = 4;\n } else if (object.x == unit.x\n && object.y == unit.y) {\n direction = unit.newDirection;\n } else {\n direction = 0;\n }\n return direction;\n //Convert Arctan to value between (0 - directions)\n\n\n// var angle = wrapDirection(directions/2-(Math.atan2(dx,dy)*directions/(2*Math.PI)),directions);//console.log(angle);\n// return angle;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Redirect to enrolment page | function enrol() {
console.log("In enrol(): " + tournament.id);
window.location.href = "../enrolment/enrolment.html";
} | [
"function online_course() {\n window.location.href = \"../onlineCourses/online_courses.html\";\n}",
"function lockAndLeave()\n{\n let payload = {sId: selected ,round , user};\n console.log(\"POSTING-->\", payload, \" TO /engage\");\n post( \"../engage\", payload ); // it should be ../\n window.location.href = '/myrounds'; \n}",
"function redirectAfterLogin() {\n\n var identity = getAuthenticatedIdentity();\n\n if (!identity) {\n spAppError.add('Attempted redirect after signed in');\n\n } else {\n\n if (redirectState && redirectState.toParams.tenant.toLowerCase() === identity.tenant.toLowerCase()) {\n $state.go(redirectState.toState.name, redirectState.toParams);\n } else {\n $state.go('home', { tenant: identity.tenant });\n }\n\n }\n }",
"function continueShopping() {\n\tsaveFormChanges();\n\twindow.location.href = thisSiteFullurl + backURL;\n}",
"changeStep() {\n window.location.assign('#/eventmgmt/shop');\n }",
"function goadd(){\n window.location = \"/admin/products/add\";\n}",
"function redirect() {\r\n if (document.location.pathname.endsWith(\"/admin/index.html\")) {\r\n document.body.innerHTML = '<h2 class=\"w3-center\">Login Required</h2><p class=\"w3-center\">If not redirected, please click <a href=\"' +\r\n cognitoURL + document.location.href.split(\"?\")[0] + '\">here</a> to go to the login page</p>'\r\n window.location.href = cognitoURL + document.location.href.split(\"#\")[0];\r\n }\r\n else {\r\n window.location.href = document.location.origin + \"/admin/index.html\";\r\n }\r\n}",
"redirectIfRolloverActive(path) {\n var onBusinessPage = path.indexOf(Constant.BUSINESS_PORTAL_PATHNAME) === 0;\n var onRolloverPage = path === Constant.ROLLOVER_PATHNAME;\n if (onBusinessPage || onRolloverPage) {\n return;\n }\n\n var { user } = this.props;\n if (!user.district) {\n return;\n }\n\n const districtId = user.district.id;\n Api.getRolloverStatus(districtId).then(() => {\n const status = this.props.lookups.rolloverStatus;\n\n if (status.rolloverActive) {\n this.props.history.push(Constant.ROLLOVER_PATHNAME);\n } else if (status.rolloverComplete) {\n // refresh fiscal years\n Api.getFiscalYears(districtId);\n }\n });\n }",
"function redirectToCreateUser() {\n window.location = \"createUser.html\";\n}",
"function onUserModify() {\n\talert(\"You try to modify a user\");\n\twindow.location.href = \"#user-list\";\n}",
"function forgotPassword() {\r\n window.location = \"newPassword.html\"; \r\n}",
"redirect() {\n Radio.request('utils/Url', 'navigate', {\n trigger : false,\n url : '/notebooks',\n includeProfile : true,\n });\n }",
"function gotoProfile(e){\n window.location.href = \"http://localhost:8080/TeamOneSports/profile.jsp\";\n}",
"function redirectToSuccess() {\n window.location.href = \"completely-added.html\"\n }",
"function goToeditEventPage(owner,docId){\n window.location.href = \"/edit-event1.html?owner=\" + owner + '&docId=' + docId;\n}",
"function enrolParticipant(participantID, courseID)\r\n{\r\n //Find the participant and course in the database\r\n participant = getParticipantByID(participantID);\r\n course = getCourseByID(courseID);\r\n if(course == null || participant == null)\r\n return;\r\n \r\n //Enrol the participant\r\n var alreadyEnrolled = false;\r\n for(enroledCourse in participant.courses)\r\n {\r\n if(participant.courses[enroledCourse] == courseID)\r\n {\r\n alreadyEnrolled = true;\r\n }\r\n }\r\n if(!alreadyEnrolled)\r\n {\r\n participant.courses.push(courseID);\r\n showAdminToolsPopup(participantID);\r\n return;\r\n }\r\n}",
"redirectToLogin () {\n window.location.assign('/login')\n }",
"function goHome() {\n let participant = JSON.parse(localStorage.getItem(\"participant\"));\n if (participant !== null) {\n window.location.href = \"../participant/participant.html?id=\" + participant.id;\n } else {\n let admin = JSON.parse(localStorage.getItem(\"admin\"));\n if (admin !== null) {\n window.location.href = \"../admin/admin.html?id=\" + admin.id;\n } else {\n alert(\"Not logged in as participant or admin.\");\n }\n }\n}",
"function Redirect(urlEnd){\r\n window.location.href = BuildRedirectString(urlEnd);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
timeSelection a function to find out what time span button was pressed (and sends the information to another function that will make the spotify api call) once one button is clicked, the others will not have a click feature and the clicked button will change color. | function timeSelection(button_id) {
/* get the button and change the color to show it is selected */
let selected_button = document.getElementById(button_id);
selected_button.style.background = "black";
selected_button.style.color = "#cfe8fa";
/* change the unselected buttons colors */
if (button_id == "short-term-time-button" ||
button_id == "medium-term-time-button") {
document.getElementById("long-term-time-button").style.background = "#cfe8fa";
document.getElementById("long-term-time-button").style.color = "black";
}
if (button_id == "short-term-time-button" ||
button_id == "long-term-time-button") {
document.getElementById("medium-term-time-button").style.background = "#cfe8fa";
document.getElementById("medium-term-time-button").style.color = "black";
}
if (button_id == "medium-term-time-button" ||
button_id == "long-term-time-button") {
document.getElementById("short-term-time-button").style.background = "#cfe8fa";
document.getElementById("short-term-time-button").style.color = "black";
}
/* button_id looks like short-term-time-button */
let selection_arr = button_id.split("-");
console.log(selection_arr);
/* user_time_selection is just one word: short, medium, or long */
user_time_selection = selection_arr[0];
console.log(user_time_selection);
} | [
"function onMouseDownEvent()\n{\n let clickedTime = calculateClickedTime();\n let minute = (30 * clock.indicators.m.angle) / (Math.PI + 15);\n let hour = (6 * clock.indicators.h.angle) / (Math.PI + 3);\n let threshold = 0.25;\n\n if((clickedTime[0] < minute + threshold) && (clickedTime[0] > minute - threshold))\n {\n clock.minuteTimeChanger.highlightIndicator('red'); // threshold makes it easier to click on hand \n return;\n } \n if((clickedTime[1] < hour + threshold) && (clickedTime[1] > hour - threshold)) \n clock.hourTimeChanger.highlightIndicator('red'); \n}",
"function clickHour() {\n let oldSelected = document.querySelector(\".selectedHourTile\");\n if (oldSelected != null) {\n oldSelected.classList.remove(\"selectedHourTile\");\n }\n this.classList.add(\"selectedHourTile\");\n $(\"selectedHour\").textContent = this.textContent + \" \" + $(\"selectedAmpm\").textContent;\n \n // make load button visible\n $(\"loadContainer\").style.display = \"block\";\n\n // duration check \n // for now im too lazy to write a check, just going to reset to 1 every time\n // might be slightly annoying for user\n $(\"selectedDuration\").textContent = \"1 hour(s) long\";\n }",
"function timeStepBtn(){\n console.log(\"time stepped\");\n arr = getNextIteration(arr);\n drawCanvas(arr);\n}",
"function loginSelection(button_id) {\r\n /* get the button, and change the color to show selection */\r\n let selected_button = document.getElementById(button_id);\r\n selected_button.style.background = \"black\";\r\n selected_button.style.color = \"#cfe8fa\";\r\n\r\n /* on successful login, should changed to successfully logged in */\r\n /*might need to implement alerts for if the user is trying to press\r\n the music and time span buttons before logging in that just say like\r\n 'you need to login before we can show you your data' */\r\n\r\n}",
"function highlight() {\n\tvar curmins = Math.floor(vid.currentTime / 60);\n var cursecs = Math.floor(vid.currentTime - curmins * 60);\n\nif (cursecs <= 3.50 ) {p[0].style.color=\"orange\";\n\t \tp[0].style.backgoundcolor=\"\";\n\t } else if (cursecs >= 3.50 && cursecs <= 7.53) {\n\t \tp[1].style.color=\"orange\";\n\t \tp[0].style.color=\"\";\n\t } else if (cursecs >= 7.54 && cursecs <= 10.40) {\n\t \tp[2].style.color=\"orange\";\n\t \tp[1].style.color=\"\";\n\t }\n\t else if (cursecs >= 10.41 && cursecs <= 13.90) {\n\t \tp[3].style.color=\"orange\";\n\t \tp[2].style.color=\"\";\n\t }\n\t else if (cursecs >= 13.91 && cursecs <= 17.94) {\n\t \tp[4].style.color=\"orange\";\n\t \tp[3].style.color=\"\";\n\t }\n\t else if (cursecs >= 17.95 && cursecs <= 21.30) {\n\t \tp[5].style.color=\"orange\";\n\t \tp[4].style.color=\"\";\n\t }\n\t else if (cursecs >= 21.31 && cursecs <= 25) {\n\t \tp[6].style.color=\"orange\";\n\t \tp[5].style.color=\"\";\n\t } \n\t else if (cursecs >= 25.30 && cursecs <= 30.92) {\n\t \tp[7].style.color=\"orange\";\n\t \tp[6].style.color=\"\";\n\t } \n\t else if (cursecs >= 31 && cursecs <= 33.30) {\n\t \tp[8].style.color=\"orange\";\n\t \tp[7].style.color=\"\";\n\t }\n\t else if (cursecs >= 33.31 && cursecs <= 38.40) {\n\t \tp[9].style.color=\"orange\";\n\t \tp[8].style.color=\"\";\n\t }\n\t else if (cursecs >= 38.41 && cursecs <= 41) {\n\t \tp[10].style.color=\"orange\";\n\t \tp[9].style.color=\"\";\n\t }\n\t else if (cursecs >= 42 && cursecs <= 45.40) {\n\t \tp[11].style.color=\"orange\";\n\t \tp[10].style.color=\"\";\n\t }\n\t else if (cursecs >= 45.41 && cursecs <= 48.40) {\n\t \tp[12].style.color=\"orange\";\n\t \tp[11].style.color=\"\";\n\t }\n\t else if (cursecs >= 48.41 && cursecs <= 52.30) {\n\t \tp[13].style.color=\"orange\";\n\t \tp[12].style.color=\"\";\n\t }\n\t else if (cursecs >= 52.31 && cursecs <= 56.40) {\n\t \tp[14].style.color=\"orange\";\n\t \tp[13].style.color=\"\";\n\t }\n\t else if (cursecs >= 56.41) {\n\t \tp[15].style.color=\"orange\";\n\t \tp[14].style.color=\"\";\n } \n}",
"function selectCategory(startColor) {\n if (startColor === 1) {\n startTimer.classList.add('study-color');\n }\n if (startColor === 2) {\n startTimer.classList.add('meditate-color');\n }\n if (startColor === 3) {\n startTimer.classList.add('exercise-color');\n }\n}",
"function checkBtn(){\n\tvar tOd = document.getElementById(\"tOd\");\n\t\n\ttOd.addEventListener(\"click\", switchModeTime);\n\ttOd.addEventListener(\"contextmenu\",dateToTime);\t\n\t\n}",
"function renderShowtimeButton(showtime) {\r\n\t\tvar showtimeBtn = Titanium.UI.createView({\r\n\t\t \tbackgroundColor: '#CCCCCC',\r\n\t\t \theight:50,\r\n\t\t \twidth:50,\r\n\t\t \tshowtime:showtime,\r\n\t\t \tborderColor:\"#0B6121\",\r\n\t\t\tborderWidth:\"4\",\r\n\t\t\tborderRadius:\"4\"\r\n\t\t});\r\n\t\tvar showtimeLabel = Titanium.UI.createLabel({\r\n\t\t\ttext: showtime.get('schedule').get('time'),\r\n\t\t\tcolor: '#000000',\r\n\t\t\tshowtime:showtime\r\n\t\t});\r\n\t\t\r\n\t\tshowtimeBtn.addEventListener('click', openShowtimeView);\r\n\t\tshowtimeBtn.add(showtimeLabel);\r\n\t\t$.showtimesContainer.add(showtimeBtn);\r\n\t\t\r\n\t\t//Add separator view for margin between view\r\n\t\tvar separator = Titanium.UI.createView({\r\n\t\t \theight:50,\r\n\t\t \twidth:5\r\n\t\t});\r\n\t\t$.showtimesContainer.add(separator);\r\n\t}",
"function clickevent(TorF)\n{\n\t//The startend value will only activate until it becomes true. This will happen when the button is pressed and calls RandVal().\n\t//Will allow the rest of the code inside to continue while true, but when time ends, will stop the function from running.\n\tif (startEnd) \n\t{\n\t\t//This if statement is checking if the parameter value from the onclick is the same as the rand value.\n\t\tif (TorF == rand)\n\t\t{\n\t\t\tclicked=TorF; //Assigns the TorF value to clicked. clicked will act as a container of the last parameter clicked.\n\t\t\tscore++; //Will increment the score once the if statement activates.\n\t\t\tRandVal() //Calls to RandVal to change the value of rand again.\n\t\t}\n\t\t//Will activate the while statement as long as clicked equals rand.\n\t\t//Clicked is the previous parameter value, so in this statement, it will make sure that the 'mole' will not be in the same place.\n\t\twhile (clicked == rand)\n\t\t{\n\t\t\tRandVal() //Calls to RandVal to change the value of rand again.\n\t\t}\n\t\tdocument.getElementById(clicked).src= 'images/hole.png'; //Will change the src of img on clicked back to a hole.\n\t}\n}",
"function clickDay() {\n let oldSelected = document.querySelector(\".selectedDayTile\");\n if (oldSelected != null) {\n oldSelected.classList.remove(\"selectedDayTile\");\n }\n this.classList.add(\"selectedDayTile\");\n let d = f(this.textContent);\n let monthYear = $(\"selectedMonth\").textContent.split(\" \");\n let month = f(String(monthNames.indexOf(monthYear[0]) + 1));\n let display = month + \" / \" + d + \" / \" + monthYear[1];\n $(\"selectedDate\").textContent = display;\n date = monthYear[1] + \"-\" + month + \"-\" + d;\n\n // populate time picker with available times for this day, then make\n // time section appear\n // first clear old hours\n $(\"amTable\").textContent = \"\";\n $(\"pmTable\").textContent = \"\";\n loadHours(date);\n $(\"timeContainer\").style.display = \"block\";\n }",
"function OnTimeMouseDown(){\n\n \tg_bTimeUpdate = false;\n}",
"function userColorPicked(event) {\n clickColor = event.target.value;\n mouseClickBtn.style.backgroundColor = clickColor;\n clickButton.style.backgroundColor = clickColor;\n}",
"function colorBlocks() {\n //console.log(now)\n if (now > 9) {\n $(\"#9am\").addClass(\"past\");\n } else if (now >= 9 && now < 10) {\n $(\"#9am\").addClass(\"present\");\n } else if (now < 9) {\n $(\"#9am\").addClass(\"future\");\n }\n if (now > 10) {\n $(\"#10am\").addClass(\"past\");\n } else if (now >= 10 && now < 11) {\n $(\"#10am\").addClass(\"present\");\n } else if (now < 10) {\n $(\"#10am\").addClass(\"future\");\n }\n if (now > 11) {\n $(\"#11am\").addClass(\"past\");\n } else if (now >= 11 && now < 12) {\n $(\"#11am\").addClass(\"present\");\n } else if (now < 11) {\n $(\"#11am\").addClass(\"future\");\n }\n if (now > 12) {\n $(\"#12pm\").addClass(\"past\");\n } else if (now >= 12 && now < 13) {\n $(\"#12pm\").addClass(\"present\");\n } else if (now < 12) {\n $(\"#12pm\").addClass(\"future\");\n }\n if (now > 13) {\n $(\"#1pm\").addClass(\"past\");\n } else if (now >= 13 && now < 14) {\n $(\"#1pm\").addClass(\"present\");\n } else if (now < 13) {\n $(\"#1pm\").addClass(\"future\");\n }\n if (now > 14) {\n $(\"#2pm\").addClass(\"past\");\n } else if (now >= 14 && now < 15) {\n $(\"#2pm\").addClass(\"present\");\n } else if (now < 14) {\n $(\"#2pm\").addClass(\"future\");\n }\n if (now > 15) {\n $(\"#3pm\").addClass(\"past\");\n } else if (now >= 15 && now < 16) {\n $(\"#3pm\").addClass(\"present\");\n } else if (now < 15) {\n $(\"#3pm\").addClass(\"future\");\n }\n if (now > 16) {\n $(\"#4pm\").addClass(\"past\");\n } else if (now >= 16 && now < 17) {\n $(\"#4pm\").addClass(\"present\");\n } else if (now < 16) {\n $(\"#4pm\").addClass(\"future\");\n }\n if (now > 17) {\n $(\"#5pm\").addClass(\"past\");\n } else if (now >= 17 && now < 18) {\n $(\"#5pm\").addClass(\"present\");\n } else if (now < 17) {\n $(\"#5pm\").addClass(\"future\");\n }\n }",
"function checkIfPassed() {\n let currentTime = moment().format('HH') ;\n $(\"li\").each(function(index) {\n if (scheduler[index].time > currentTime) {\n $(this).find(\"input\").css(\"background-color\", \"green\");\n }\n if (scheduler[index].time < currentTime){\n $(this).find(\"input\").css(\"background-color\", \"gray\");\n }\n if (scheduler[index].time == currentTime){\n $(this).find(\"input\").css(\"background-color\", \"\tred\");\n }\n});\n}",
"function doFiveClick()\n{ \n // Clear existing\n if( interval != null )\n {\n clearInterval( interval );\n interval = null;\n }\n \n // Latest value from Parse\n queryLatest();\n \n // Show plot dot on chart\n comfort.plot.setAttribute( 'opacity', 1 );\n comfort.chart.setAttribute( 'd', 'M0 0' ); \n comfort.chart.setAttribute( 'opacity', 0 );\n \n kaazing = false;\n \n // Repeat every five seconds\n interval = setInterval( queryLatest, 5000 );\n \n // Highlight selected interval\n setSelectedControlButton( '.turtle' ); \n}",
"function changeTextColorEveryHour(){\n today = new Date();\n h = today.getHours();\n m = today.getMinutes();\n s = today.getSeconds();\n if(m === 0 && s === 0){\n document.div.style.text = selectedColors[Math.floor(Math.random() * colors.length)];\n }\n }",
"function colorizor() {\n var timeOfDay = moment().hour();\n var timeSlots = [9, 10, 11, 12, 13, 14, 15, 16, 17];\n\n $.each(timeSlots, function (index, slot) {\n\n var hrNum = slot < 13 ? slot : slot - 12;\n\n if ((timeOfDay > slot)) {\n $('#hour-' + hrNum).children('.description').addClass('past');\n } else if (timeOfDay < slot) {\n $('#hour-' + hrNum).children('.description').addClass('future');\n } else {\n $('#hour-' + hrNum).children('.description').addClass('present');\n }\n });\n }",
"function OnTimeSliderClick()\n{\n\t\n\tnDomain = DVD.CurrentDomain;\n\tif (nDomain == 2 || nDomain == 3) \n\t\treturn;\n\n\tlTitle = DVD.CurrentTitle;\n\ttimeStr = GetTimeSliderBstr();\n\n\tDVD.PlayAtTimeInTitle(lTitle, timeStr);\n\tDVD.PlayForwards(DVDOpt.PlaySpeed);\n}",
"function selectDayTile() {\n document\n .querySelectorAll(\".calender-tile:not(.name-of-day)\")\n .forEach((dayTile) => {\n dayTile.onclick = () => {\n headerSpan = document.querySelector(\".header > span\");\n selectedDate = parseInt(dayTile.dataset.day);\n selectedMonth = parseInt(headerSpan.dataset.month);\n selectedYear = parseInt(headerSpan.dataset.year);\n\n clearSelectedDayTileColor();\n\n dayTile.style.backgroundColor = SELECTED_DAYTILE_COLOR;\n\n showTodo();\n };\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
represents a music item | function MusicItem( id, name, playlistId ) {
this.id = id;
this.name = name;
this.playlistId = playlistId;
var type = id.substring( 0, 2 );
this.getTypeName = function() {
switch ( type ) {
case 'tr': return 'track';
case 'ar': return 'artist';
case 'al': return 'album';
case 'pl': return 'playlist';
}
};
} | [
"function Item () {\n\tthis.name = \"\";\n\tthis.relatedItems = [];\n\tthis.relationTypes = [];\n}",
"getItem(a) {\n if (!a) {\n return null;\n }\n\n if (a[0] === 'txt') {\n return this.state.textTrack[a[1]];\n } else {\n return this.state.mediaTrack[a[1]];\n }\n }",
"function Item(idName, idAliases, deText, plText, itemGet, itemAct, uses, reacts)\n{\n\tthis.ident = idName;\n\tthis.alias = idAliases;\n\tthis.descText = deText;\n\tthis.placeText = plText;\n\tthis.canGet = itemGet;\n\tthis.canUse = itemAct;\n\tthis.itemUse = uses;\n\tthis.itemReaction = reacts;\n}",
"function Item ( db, id, description, equipType, strength ) {\n Thing.call( this, db, \"items\", id, description );\n this.equipType = equipType || \"none\";\n this.strength = strength || 0;\n this.name = id;\n}",
"function FavoriteItem () {\n\tthis._init ();\n}",
"function MusicTrigger(game, AM, x, y, width, height, music) {\n this.entity = new Entity(x, y, width, height);\n this.game = game;\n this.music = music;\n this.entity.intangible = true;\n}",
"function Album(artist, title, year){\n this.artist = artist\n this.title = title\n this.year = year\n this.songs = [];\n}",
"function createMusic (data, cb) {\n connection.query(\n 'INSERT INTO `inventory` SET type=?;INSERT INTO `musics` SET ?, id=LAST_INSERT_ID()', ['music', data],\n (err, result) => {\n if (err) {\n cb(err);\n return;\n }\n readMusic(result[0].insertId, cb);\n });\n}",
"function generateSong(id) {\n return {\n id,\n name: `The song ${id}`,\n artists: [\n {\n name: 'The Artist',\n },\n ],\n };\n}",
"function MusicStaff() {\n this.count = 5;\n this.gap = 20;\n }",
"function item( term, definition, cat, cat2 )\n{\n\tthis.term = term;\n\tthis.definition = definition;\n\tthis.cat = cat;\n\tthis.cat2 = cat2;\n}",
"function PlaylistEntry(title) {\n\t// alert(\"create new playlist entry.\");\n\tthis.title = title;\n\tthis.url = \"\";\n}",
"onplay(song) { }",
"function showSong(song) {\n this.querySelector('span.title').textContent = song.title;\n this.querySelector('span.artist').textContent = song.artist;\n this.querySelector('span.album').textContent = song.album;\n}",
"function AbstractMusicInputComponent() {\n }",
"createItems () {\n let items = []\n // if there's only one audio track, there no point in showing it\n this.hideThreshold_ = 1;\n\n const tracks = this.player_.audioTracks();\n\n for (let i = 0; i < tracks.length; i++) {\n const track = tracks[i];\n\n items.push(new AudioTrackMenuItem(this.player_, {\n track,\n // MenuItem is selectable\n selectable: true\n }));\n }\n\n return items;\n\n /*let items = []\n items.push(new AudioTrackMenuItem(this.player_, {\n label: this.controlText_,\n selectable: false\n }))\n\n let tracks = this.player_.audioTracks()\n\n if (!tracks) {\n return items\n }\n\n if (tracks.length < 2) {\n this.hide()\n return items\n }\n\n for (let i = 0; i < tracks.length; i++) {\n let track = tracks[i]\n\n // only add tracks that are of the appropriate kind and have a label\n if (track['kind'] === 'main') {\n items.push(new AudioTrackMenuItem(this.player_, {\n // MenuItem is selectable\n 'selectable': true,\n 'track': track\n }))\n }\n }\n\n return items*/\n }",
"function ImageItemModel(){\n this.attachementID;\n this.setAttachementID = function(val){\n this.attachementID = val;\n this.onChange();\n }\n this.getAttachementID = function(){\n return this.attachementID;\n }\n \n this.itemID;\n this.setIdItem = function(val){\n this.itemID = val;\n } \n this.getIdItem = function(){\n return this.itemID;\n }\n \n this.caption;\n this.setCaption = function(val){\n this.caption = val;\n this.onChange();\n }\n this.getCaption = function(val){\n return this.caption;\n }\n \n this.imageHeight;\n this.setImageHeight = function(val){\n this.imageHeight = val;\n }\n this.getImageHeight = function(){\n return this.imageHeight;\n }\n }",
"function ManageMusic() {\r\n music.src = BGMusics[0].SRC;\r\n music.volume = 0.01;\r\n music.play();\r\n music.loop = true;\r\n}",
"function ItemSet() {\r\n/**\r\n * @type Object\r\n * @private\r\n */\r\n\tthis._contents = {};\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
28.Writ a function called createMatrix which takes in two whole numbers, n and m, and creates a twodimensional array with n columns and m rows. All of the values inside of your array should be 0. | function createMatrix(n, m){
let arr = [];
for (let i=0; i<m ;i++) {
arr[i]=[];
for (let j=0; j<n; j++) {
arr[i][j]=0;
}
}
return arr;
} | [
"function createZeroMatrix() {\n\t\tvar rows = arguments[0];\n\t\tvar cols = arguments[1];\n\t\tvar m = [];\n\t\tfor(var r = 0; r < rows; r++) {\n\t\t\tvar row = [];\n\t\t\tfor(var c = 0; c < cols; c++) {\n\t\t\t\tvar col = 0;\n\t\t\t\trow.push(col);\n\t\t\t}\n\t\t\tm.push(row);\n\t\t}\n\t\treturn m;\n\t}",
"function makeZero() {\n\t\tvar m = arguments[0];\n\t\tvar rows = m.length;\n\t\tvar cols = m[0].length;\n\t\tfor(var r = 0; r < rows; r++) {\n\t\t\tfor(var c = 0; c < cols; c++) {\n\t\t\t\tm[r][c] = 0;\n\t\t\t}\n\t\t}\n\t}",
"function zeros(n) {\r\n var arr= new Array(n);\r\n for(var i=0;i<n;i++) { arr[i]= 0; }\r\n return arr;\r\n }",
"function identityMatrix(num,arr){\n\tif(typeof(arr) !== 'undefined'){\n\t\tif(num !== arr.length){\n\t\t\tthrow \"Length of leading entries array is not matched.\"\n\t\t}\n\t}\n\tvar matrix = [];\n\tfor(var i = 0; i < num; i++){\n\t\tmatrix.push([]);\n\t\tfor(var j = 0; j < num; j++){\n\t\t\tif(i===j){\n\t\t\t\tif(typeof(arr) !== 'undefined'){\n\t\t\t\t\tmatrix[i].push(arr[i]);\n\t\t\t\t}else{\n\t\t\t\t\tmatrix[i].push(1);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tmatrix[i].push(0);\n\t\t\t}\n\t\t}\n\t}\n\treturn matrix;\n}",
"initialize2dArray(numCols){\n let arr = [];\n for(let i = 0; i < numCols; i++){\n arr.push(new Array(8));\n }\n return arr;\n }",
"buildAdjacencyMatrix (edges, n) {\n const matrix = Array.from(Array(n), () => Array(n).fill(null))\n edges.forEach(([ i, j ]) => { matrix[i][j] = 1 })\n\n return matrix\n }",
"function identityMatrix(dim) {\n let result = [];\n\n for(let i=0; i< dim+1; ++i) {\n result.push([]); // so the inner array exists\n for(let j=0; j < dim+1 ; ++j) {\n if(i == j) {\n result [i][j] = 1;\n\n }\n else {\n result[i][j] = 0;\n }\n }\n }\n return result;\n}",
"function array6x6() {\n let m = Array.from({length: 6}, e => Array(6).fill({key:true}));\n // let m = Array.from({length: 6}, e => Array(6).fill(0)); \n return m \n }",
"function initialize_empty_array(size){\n var zeros = [];\n for (var i = 0; i < size; i++) zeros[i] = 0;\n return zeros;\n}",
"function create_dummy_array(n){\n var arr = [];\n for(var i = 0; i < n; i++){\n arr.push(Math.floor(Math.random() * 10));\n }\n return arr;\n}",
"buildEmptyBoard(dimension) {\n for (let i = 0; i < dimension; i++) {\n this.boardArray.push(new Array(dimension).fill(0));\n }\n }",
"function redefineTableArray () {\n\t//function to redefinetableArray\n\t\n\tvar r = originalNumberRecords; //start from rows 3\nvar c = originalNumberOfFields; //start from col 5..if edit don't forget to increase the numberOfFields value\n\nvar rows = tableTitle.length;//current total number of rows after adding new ones will = tableTitle.length\nvar cols = currentNumberOfFields;\n\nfor (var i = 0; i < rows; i++) {\n var start;\n if (i < r) {\n start = c;\n } else {\n start = 0;\n tableArray.push([]);\n }\n for (var j = start; j < cols; j++) {\n tableArray[i].push(0);\n }\n}\nreturn tableArray;\n//above is trial code to define new tableArray\n//PUTS 7 0's after each record ? How come?\n}//end function redefineTableArray",
"function createArray(size) {\n\t// Validate parameter value\n\tif (size+\"\" == \"undefined\" || size == null) \n\t\treturn null;\t\n\tthis.length = size;\n\tfor (var i = 0; i < size; i++) {\n\t\tthis[i] = 0; \n\t}\n\treturn this;\n}",
"constructor (size) {\n\n var i,j;\n var board = [];\n\n //Initialize each space to 0\n for (i=0; i<size; i++) {\n\n var row = [];\n\n for (j=0; j<size; j++) {\n row.push(0);\n }\n\n board.push(row);\n }\n\n this.board = board;\n this.size = size;\n\n }",
"get matrix() {\n let dom = this._domain.toArray();\n let ran = this._range.toArray();\n return number_matrix_1.NumberMatrix.generate(this._domain.size(), this._range.size(), (r, c) => {\n return this._relationFn(dom[r], ran[c]) ? 1 : 0;\n });\n }",
"function matrix(numColumns, numRows, start, increment) {\r\n if (!isNumber(numColumns))\r\n throw new Error(\"Expect 'numColumns' parameter to 'dataForge.matrix' function to be a number.\");\r\n if (!isNumber(numRows))\r\n throw new Error(\"Expect 'numRows' parameter to 'dataForge.matrix' function to be a number.\");\r\n if (!isNumber(start))\r\n throw new Error(\"Expect 'start' parameter to 'dataForge.matrix' function to be a number.\");\r\n if (!isNumber(increment))\r\n throw new Error(\"Expect 'increment' parameter to 'dataForge.matrix' function to be a number.\");\r\n var rows = [];\r\n var columnNames = [];\r\n var nextValue = start;\r\n for (var colIndex = 0; colIndex < numColumns; ++colIndex) {\r\n columnNames.push((colIndex + 1).toString());\r\n }\r\n for (var rowIndex = 0; rowIndex < numRows; ++rowIndex) {\r\n var row = [];\r\n for (var colIndex = 0; colIndex < numColumns; ++colIndex) {\r\n row.push(nextValue + (colIndex * increment));\r\n }\r\n nextValue += numColumns * increment;\r\n rows.push(row);\r\n }\r\n return new DataFrame({\r\n columnNames: columnNames,\r\n rows: rows,\r\n });\r\n}",
"function minesweeper(matrix = []) {\n\n let mm = [];\n for (let i = 0; i < matrix.length; i++) {\n mm.push([])\n }\n\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j]) {\n mm[i][j] = 1;\n\n } else {\n // 00\n if (i == 0 && j == 0) {\n mm[i][j] = (matrix[i][j + 1]) + (matrix[i + 1][j]);\n\n }\n // 01\n else if (i == 0 && j > 0 && j !== matrix[i].length - 1) {\n mm[i][j] = (matrix[i][j - 1]) + (matrix[i][j + 1]) + (matrix[i + 1][j])\n }\n //02\n else if (i == 0 && j == matrix[i].length - 1) {\n mm[i][j] = (matrix[i][j - 1]) + (matrix[i + 1][j]);\n\n }\n\n // 20\n else if (i == matrix.length - 1 && j == 0) {\n mm[i][j] = (matrix[i - 1][j]) + (matrix[i][j + 1]);\n\n }\n\n // 21\n else if (i == matrix.length - 1 && j > 0 && j !== matrix[i].length - 1) {\n mm[i][j] = (matrix[i][j - 1]) + (matrix[i][j + 1]) + (matrix[i - 1][j])\n\n }\n // 22\n else if (i == matrix.length - 1 && j == matrix[i].length - 1) {\n mm[i][j] = (matrix[i][j - 1]) + (matrix[i - 1][j])\n\n }\n // 10\n else if (i > 0 && i !== matrix.length - 1 && j == 0) {\n mm[i][j] = (matrix[i - 1][j]) + (matrix[i + 1][j]) + (matrix[i][j + 1])\n\n }\n // 12\n else if (i > 0 && i !== matrix.length - 1 && j == matrix[i].length - 1) {\n mm[i][j] = (matrix[i - 1][j]) + (matrix[i + 1][j]) + (matrix[i][j - 1])\n } else {\n mm[i][j] = (matrix[i][j + 1]) + (matrix[i][j - 1]) + (matrix[i + 1][j]) + (matrix[i - 1][j])\n }\n mm[i][j] = mm[i][j] == 0 ? 1 : mm[i][j];\n\n\n }\n\n\n }\n\n }\n return mm;\n}",
"static identity(){\n return new matrix4([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]);\n }",
"function bidimensionale(myArray){\r\n var n = Math.sqrt(myArray.length);\r\n var resarray = [];\r\n var row = [];\r\n for (var i = 0; i < myArray.length; i++){\r\n row[row.length] = myArray[i];\r\n if (row.length == n){\r\n resarray.push(row);\r\n row = [];\r\n }\r\n }\r\n return resarray;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
isSemigroup : a > Boolean | function isSemigroup(m) {
return isString(m)
|| !!m && hasAlg('concat', m)
} | [
"canGroupSelectedItems()\n {\n if (Object.keys(this._selectedItems).length > 1)\n {\n for (var itemIndex in this._selectedItems)\n {\n var item = this._selectedItems[itemIndex];\n if (!(item instanceof WorkflowJobItem))\n {\n return false;\n }\n }\n return true;\n }\n return false;\n }",
"function isRepeatTest(groupEl) {\n if($(groupEl)[0].tagName !== 'group') {\n return false;\n }\n return $(groupEl).children('repeat').length === 1;\n }",
"function isPriemgetal(getal) {\n\n}",
"function is_in_set(set, x) {} // --> true or false",
"function groupIsActive(groupName) {\n const g = groups.find(g => g.name === groupName);\n if (g === undefined) {\n return false;\n }\n return g.startDate <= todayYMD && g.endDate >= todayYMD;\n}",
"function isGroup(groupName, callback) { //FOR TESTING TIME: When a group is added that already exists, this breaks\n chrome.storage.local.get(\"groups\", function(data) {\n isGroup = false;\n let groupNames = Object.keys(data[\"groups\"]);\n for (aGroup of groupNames) {\n if (groupName === aGroup) {\n isGroup = true;\n }\n }\n callback(isGroup);\n });\n}",
"bitgroup(pref, succ) {\n if (succ === null && pref !== null) return false;\n return pref === null || parseInt(pref, 10) === parseInt(succ, 10);\n }",
"isSubset(otherSet) {\n let result = this.set.every(function(element) {\n return otherSet.contains(element);\n });\n console.log('isSubset: ', result);\n }",
"is(name) {\n if (typeof name == 'string') {\n if (this.name == name) return true\n let group = this.prop(dist_NodeProp.group)\n return group ? group.indexOf(name) > -1 : false\n }\n return this.id == name\n }",
"hasValue() {\n return this.children.some((child) => child.hasValue());\n }",
"function hasGroupByDate(curTgrp){\n var sortFields = curTgrp.sortFields;\n if ((sortFields) && (sortFields.length > 0)) {\n \tfor(var i=0; i<sortFields.length; i++){\n \t\tvar sortField = sortFields[i];\n var groupByDate = sortFields[i].groupByDate;\n if ((groupByDate != '')) {\n \t return true;\n }\n \t}\n }\n return false; \n}",
"function showGroup() {\n\tvar ps = document.querySelectorAll('p, nav, section, article');\n\tvar i = 0;\n\twhile(i < ps.length) {\n\t\tgroupLength = ps[i].childNodes.length;\n\t\tif(groupLength > 1) {\n\t\t\tvar groupChild = document.createElement('span');\n\t\t\tgroupChild.classList.add('vasilis-srm-group');\n\t\t\tgroupChild.innerHTML = \" Group \" + groupLength + \" items\";\n\t\t\tps[i].appendChild(groupChild);\n\t\t}\n\t\ti++;\n\t}\n}",
"isSubsetOf(otherSet) {\n for (let key of this) {\n if (!otherSet.has(key)) {\n return false;\n }\n }\n return true;\n }",
"function isValidGroupName(name) {\n\treturn isValidUsername(name);\n}",
"function isCheckedMultiple(f,is_checked,field_boxchecked){\n\n\t// get boxchecked object\n\tvar boxchecked = eval(\"document.\"+f.name+\".\"+field_boxchecked);\n\n\tif (is_checked == true) // is checked\n\t\n\t\t// increase number of checkboxes checked, of this group\n\t\tboxchecked.value++;\n\t\t\n\telse // is unchecked\n\t\n\t\t// decrease number of checkboxes checked, of this group\n\t\tboxchecked.value--;\n}",
"isGroupMember (groupId) {\n let user = this.get('currentUser');\n if (!Ember.isArray(user.groups)) {\n // if the provider has not been configured to load groups, show a warning...\n Ember.debug('Session.isGroupMember was called, but torii-provider-arcgis has not been configured to fetch user groups. Please see documentation. (https://github.com/dbouwman/torii-provider-arcgis#ember-cli-torii-provider-arcgis)');\n return false;\n } else {\n // look up the group in the groups array by it's Id\n let group = user.groups.find((g) => {\n return g.id === groupId;\n });\n if (group) {\n return true;\n } else {\n return false;\n }\n }\n }",
"function huboVentas (mes, anio) {\r\n return ventasMes(mes, anio) > 0;\r\n }",
"studentInQueues(student) {\n const queueNames = Object.keys(this.queues);\n\n for (let i = 0; i < queueNames.length; i++) {\n const queueName = queueNames[i];\n if (this.queues[queueName].contains(student)) {\n return true;\n }\n }\n\n return false;\n }",
"function eq_ques_(order0) /* (order : order) -> bool */ {\n return (order0 === 2);\n}",
"visitGrouping_sets_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detects if there are other JSXElements in a higher scope. | function findOtherJSX(path) {
var state = { otherJSX: false, node: path.node };
path.findParent(function (path) {
if (path.isJSXElement()) {
state.node = path.node;
} else if (path.isFunction()) {
path.traverse(jsxVisitor, state);
} else if (path.isProgram()) {
path.traverse(jsxVisitor, state);
}
// End early if another JSXElement is found.
return state.otherJSX;
});
return state.otherJSX;
} | [
"hasWrappers() {\n return this.wrappers.length > 0\n }",
"inDOM() {\n\t\t\treturn $(Utils.storyElement).find(this.dom).length > 0;\n\t\t}",
"function hasErrorOverlay() {\n return document.querySelectorAll(ERROR_OVERLAY_NAME).length;\n}",
"function inDOM() {\n var closestBody = $that.closest(body),\n isInDOM = !!closestBody.length;\n return isInDOM;\n }",
"diagnosticDetectDuplicateAncestorScriptImports() {\n var _a, _b;\n if (this.xmlFile.parentComponent) {\n //build a lookup of pkg paths -> FileReference so we can more easily look up collisions\n let parentScriptImports = this.xmlFile.getAncestorScriptTagImports();\n let lookup = {};\n for (let parentScriptImport of parentScriptImports) {\n //keep the first occurance of a pkgPath. Parent imports are first in the array\n if (!lookup[parentScriptImport.pkgPath]) {\n lookup[parentScriptImport.pkgPath] = parentScriptImport;\n }\n }\n //add warning for every script tag that this file shares with an ancestor\n for (let scriptImport of this.xmlFile.scriptTagImports) {\n let ancestorScriptImport = lookup[scriptImport.pkgPath];\n if (ancestorScriptImport) {\n let ancestorComponent = ancestorScriptImport.sourceFile;\n let ancestorComponentName = (_b = (_a = ancestorComponent.componentName) === null || _a === void 0 ? void 0 : _a.text) !== null && _b !== void 0 ? _b : ancestorComponent.pkgPath;\n this.diagnostics.push(Object.assign({ file: this.xmlFile, range: scriptImport.filePathRange }, DiagnosticMessages_1.DiagnosticMessages.unnecessaryScriptImportInChildFromParent(ancestorComponentName)));\n }\n }\n }\n }",
"exists() {\n return this.element ? true : false;\n }",
"function isTopLevelEl(el) {\r\n\t\tif (!el) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tvar tn = propAttr(el, 'tagName');\r\n\t\ttn = tn ? tn.toLowerCase() : null;\r\n\t\treturn tn === 'html' || tn === 'head';\r\n\t}",
"function atTopLevel() {\n return Object.is(topBlock,currentBlock);\n }",
"assertNoNestedFbts(node) {\n const moduleName = this.moduleName;\n node.children.forEach(child => {\n if (fbtChecker.isJSXElement(child) || fbsChecker.isJSXElement(child)) {\n throw errorAt(\n child,\n `Don't put <${child.openingElement.name.name}> directly within <${node.openingElement.name.name}>. This is redundant. ` +\n `The text is already translated so you don't need to translate it again`,\n );\n } else {\n const otherChecker = moduleName === FBT ? fbsChecker : fbtChecker;\n if (otherChecker.isJSXNamespacedElement(child)) {\n const childOpeningElementNode = child.openingElement.name;\n throw errorAt(\n child,\n `Don't mix <fbt> and <fbs> JSX namespaces. ` +\n `Found a <${childOpeningElementNode.namespace.name}:${childOpeningElementNode.name.name}> directly within a <${moduleName}>`,\n );\n }\n }\n });\n }",
"visitWindowing_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"_containsFocus() {\n const activeElement = _getFocusedElementPierceShadowDom();\n return activeElement && this._element.nativeElement.contains(activeElement);\n }",
"htmlIsOverflowing(cellId) {\n let elem = $('#'+cellId);\n let children = elem.children('.item');\n let actionButtonsBar = elem.closest('.ui-grid-row').find('.grid-action-bar:eq(0)');\n let actionButtonsWidth = actionButtonsBar.outerWidth();\n let maxWidth = elem.outerWidth() - 60 - actionButtonsWidth;\n let totalChildrenWidth = 0;\n children.each((i,child) => {\n let childElem = $(child);\n totalChildrenWidth += childElem.outerWidth()\n + parseInt(childElem.css('margin-left'))\n + parseInt(childElem.css('margin-right'));\n\n if(totalChildrenWidth < maxWidth){\n childElem.removeClass('overflowing-child');\n }\n if(totalChildrenWidth > maxWidth && !childElem.is('.overflowing-child')){\n childElem.addClass('overflowing-child');\n }\n\n });\n return elem.children('.item.overflowing-child').length>0;\n }",
"isAncestor(value) {\n return isPlainObject(value) && Node$1.isNodeList(value.children);\n }",
"isInsideAList(element) {\n let parent = element.parentNode;\n while (parent !== null) {\n if (parent.nodeName === 'UL' || parent.nodeName === 'OL') {\n return true;\n }\n parent = parent.parentNode;\n }\n return false;\n }",
"function hasMultipleInstancesOfName( name ){\n\treturn usedNames[ name ] > 1;\n}",
"async exists() {\n return $(this.rootElement).isExisting();\n }",
"isInDOM() {\n return document.querySelector(\"#iovon-hybrid-modal\") !== null;\n }",
"areComponentsLoaded() {\n return this.vues.filter((component) => !component.isLoaded).length === 0;\n }",
"function underLevel(name) {\n for (var blo of blockStack) {\n if (blo.getLabel() == name)\n return true;\n }\n return currentBlock.getLabel() == name;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the subfolder inside the current folder, as specified by the leafPath | async addSubFolderUsingPath(leafPath) {
await spPost(Folder(this, "AddSubFolderUsingPath"), request_builders_body({ leafPath: toResourcePath(leafPath) }));
return this.folders.getByUrl(leafPath);
} | [
"function createNewFolder() {\n var id = $(this).parent().attr(\"data-id\");\n fileSystem.createFileOrFolder(id, \"folder\");\n updateUI();\n }",
"function subFolderCreate() {\n var requester = gapi.client.request({\n 'path': '/drive/v2/files',\n 'method': 'POST',\n 'body': {'title': 'Auto Save', 'mimeType' : 'application/vnd.google-apps.folder', 'parents': [{\"id\": ENGRFolderId}]}\n });\n requester.execute(function(res) {\n autoSaveFolderId = res.id;\n readFiles(ENGRFolderId, autoSaveFolderId);\n })\n }",
"createFolder(parentPath, name, callback) {\n\t\tlet params = {\n\t\t\tBucket: this._bucket,\n\t\t\tKey: parentPath + name\n\t\t};\n\t\tthis._s3.putObject(params, function (err, data) {\n\t\t\tcallback(parentPath + name);\n\t\t});\n\t}",
"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 insertNode(currentPath, remainingPath, parent, firstLevel) {\n var remainingDirectories = remainingPath.split('/');\n var nodeName = remainingDirectories[0];\n var newPath = firstLevel ? nodeName : (currentPath + '/' + nodeName);\n // console.log('=== inserting: '+ nodeName);\n if (remainingDirectories.length === 1) { // actual file to insert\n // console.log('last item');\n var node = createNode(nodeName, newPath, parent, [], 0);\n parent.children.push(node);\n return;\n }\n else {\n // path consists of multiple directories and a file\n // console.log('not last item')\n var node = findAndGetChild(nodeName, parent);\n remainingDirectories.shift();\n var pathToGo = remainingDirectories.join('/');\n if (node) {\n // directory already exists\n insertNode(newPath, pathToGo, node, false);\n return;\n }\n else {\n // create the directory and insert on it\n node = createNode(nodeName, newPath, parent, [], 0);\n parent.children.push(node);\n insertNode(newPath, pathToGo, node, false);\n return;\n }\n }\n}",
"addToTree({ state, commit, getters }, { parentPath, newDirectory }) {\n // If this directory is not the root directory\n if (parentPath) {\n // find parent directory index\n const parentDirectoryIndex = getters.findDirectoryIndex(parentPath);\n\n if (parentDirectoryIndex !== -1) {\n // add a new directory\n commit('addDirectories', {\n directories: newDirectory,\n parentId: state.directories[parentDirectoryIndex].id,\n });\n\n // update parent directory property\n commit('updateDirectoryProps', {\n index: parentDirectoryIndex,\n props: {\n hasSubdirectories: true,\n showSubdirectories: true,\n subdirectoriesLoaded: true,\n },\n });\n } else {\n commit('fm/messages/setError', { message: 'Directory not found' }, { root: true });\n }\n } else {\n // add a new directory to the root of the disk\n commit('addDirectories', {\n directories: newDirectory,\n parentId: 0,\n });\n }\n }",
"function createFolder(auth) {\r\n\tconst drive = google.drive({version: 'v3', auth}); \r\n\t\r\n\tvar fileMetadata = {\r\n\t\t'name': DRIVE_PATH,\r\n\t\tmimeType: 'application/vnd.google-apps.folder'\r\n\t};\r\n\r\n\tdrive.files.create(\r\n\t\t{\r\n\t\t\tresource: fileMetadata,\r\n\t\t\tfields: 'id'\r\n\t\t}, \r\n\t\t(err, folder) => {\r\n\t\t\tif (err) {\r\n\t\t\t console.error(err);\r\n\t\t\t} else {\r\n\t\t\t DRIVE_PATH_ID = folder.data.id;\r\n\t\t\t console.log('Created folder with id: ', folder.data.id);\r\n\t\t\t}\r\n\t\t}\r\n\t);\r\n}",
"function createDirectory(index, path) {\n\n //update path\n path = path + '/' + index.prefix + '-' + index.num;\n\n //create a directory\n if (!fs.existsSync(path)){\n fs.mkdirSync(path);\n }\n\n //save index file\n fs.writeFile(path + '/index.json', JSON.stringify(index, null, 2));\n\n return path;\n }",
"function makeFolders(){\n try {\n var projFolderString = my.dat.meta.rootFolder + \"ScriptProjects/\" + my.dflts.titles.cTitle\n var dskPath = projFolderString + \"/\";\n writeFolder(dskPath);\n\n var myPath;\n var diskFolders = my.dat.folders.descendants().(@disk == \"yes\");\n // Do the disk folders\n for (var s = 0; s < diskFolders.length(); s++) {\n var finalPath;\n myPath = \"\";\n var currLmnt = diskFolders.child(s);\n var topLev = \"\";\n if (currLmnt.parent().name() == \"folders\") {\n topLev = currLmnt.@name + \"/\"; // Previously, topLev had been defined here. I moved the declaration out above.\n }\n while(currLmnt.parent().name() != \"folders\") {\n myPath = currLmnt.@name + \"/\" + myPath;\n currLmnt = currLmnt.parent();\n }\n finalPath = dskPath + topLev + myPath; // This was messed up, with erroneous slashes.\n writeFolder(finalPath);\n } \n } catch(err){ alert(\"Oops. On line \" + err.line + \" of \\\"makeFolders()\\\" you got \" + err.message);}\n }",
"mkParentPath(dir, cb) {\n var segs = dir.split(/[\\\\\\/]/);\n segs.pop();\n if (!segs.length) {\n return cb && cb();\n }\n dir = segs.join(path.sep);\n return this.mkpath(dir, cb);\n }",
"function createTestFolder() {\n DriveApp.createFolder('test1');\n DriveApp.createFolder('test2');\n}",
"addFolder(e) {\n e.preventDefault();\n if(this.props.client) {\n let clientName = this.props.client.clientName;\n let clientId = this.props.client.objectId;\n let subFolderName = this.refs.folderName.value.toLowerCase();\n store.fileStore.createSubFolder(clientName, clientId, subFolderName);\n\n } else {\n let clientName = this.refs.folderName.value;\n store.fileStore.createClientFolder(clientName);\n store.session.set({ addFolder: false});\n }\n }",
"function mkdirp(base, subdir) {\n var steps = subdir.split(path.sep);\n var current = base;\n for (var i = 0; i < steps.length; i++) {\n current = path.join(current, steps[i]);\n if (!fs.existsSync(current))\n fs.mkdirSync(current);\n }\n }",
"function test_custom_folder_exists() {\n assert_folder_mode(\"smart\");\n assert_folder_displayed(smartFolderA);\n // this is our custom smart folder parent created in folderPane.js\n mc.folderTreeView.selectFolder(subfolderA);\n assert_folder_selected_and_displayed(subfolderA);\n}",
"function createItemFolder (req, res, next) {\r\n\r\n\tvar folder = ParseReqRes.getItemFolder(req, res);\r\n\r\n\tconsole.log('DEBUG (INFO): createItemFolder:', folder);\r\n\r\n\tcreateDir(folder).done(\r\n\r\n\t\tfunction (result) {\r\n\t\t\treturn next();\r\n\t\t},\r\n\t\tfunction (error) {\r\n\t\t\tconsole.log('DEBUG (ERR): createItemFolder:', error);\r\n\t\t\treturn res.status(500).send(error);\r\n\t\t}\r\n\t);\r\n}",
"function insertFileIntoFolder(folder_Id, fileId, callback) {\n\tvar body = {'id': fileId};\n\tvar request = gapi.client.drive.children.insert({\n\t\t'folderId': folder_Id,\n\t\t'resource': body\n\t});\n\trequest.execute(function(resp) { \n\t\tcallback && callback(resp);\n\t});\n}",
"function createDashboardFolderAndSave(savedDashboard, callback) {\n var awsAssetsKeyPrefix = utils.generateRandomString(16);\n getDashboardsByParams({awsAssetsKeyPrefix : awsAssetsKeyPrefix}, function (searchErr, searchResult) {\n if(searchErr) {\n callback(searchErr);\n }\n else {\n if(searchResult.length > 0) {\n awsAssetsKeyPrefix += utils.generateRandomString(4);\n }\n savedDashboard.awsAssetsKeyPrefix = awsAssetsKeyPrefix;\n savedDashboard.save(function (saveDashboardErr, updatedDashboard) {\n if (saveDashboardErr) {\n callback(saveDashboardErr, null);\n } else {\n callback(null, updatedDashboard);\n }\n });\n }\n });\n \n}",
"mkdirIf(cond, ...args) {\n if (isTrue(cond)) this.mkdir(...args);\n }",
"function createDirectories(col, callback){\n if(col > maxCol){\n callback(null);\n } else {\n var colDir = \"\"+zoomDirectory+\"/\"+col+\"\";\n mkdirp(colDir, function (err) {\n if (err) console.error(err);\n else createDirectories(col+1, callback);\n });\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to recursively walk through arrays and find highest and lowest number | function recursiveHighLow(data){if(data===void 0){return void 0}else if(babelHelpers.instanceof(data,Array)){for(var i=0;i<data.length;i++){recursiveHighLow(data[i])}}else{var value=dimension?+data[dimension]:+data;if(findHigh&&value>highLow.high){highLow.high=value}if(findLow&&value<highLow.low){highLow.low=value}}}// Start to find highest and lowest number recursively | [
"function findMaximumValue(array) {\n\n}",
"function maxRecurse(...num) {\n const array = num[0];\n const array2 = [...array];\n let max = array2[0];\n\n if (array2.length === 1) {return max}\n array2.shift();\n let newMax = maxRecurse(array2);\n if (max < newMax) {max = newMax}\n \n return max; \n}",
"function findDiff(arr) {\n var max = Math.max(...arr)\n var min = Math.min(...arr)\n return max - min;\n }",
"function findMinMax(array, minmax) {\n if ( minmax == \"max\" ) {\n return Math.max.apply(Math, array);\n }\n else if ( minmax == \"min\" ) {\n return Math.min.apply(Math, array);\n }\n return 'incorrect arguments';\n }",
"function findMinimumValue(array) {\n\n}",
"function minRecurse(...num) {\n const array = num[0];\n const array2 = [...array];\n let min = array2[0];\n\n if (array2.length === 1) {return min}\n array2.shift();\n let newMin = minRecurse(array2);\n if (min > newMin) {min = newMin}\n \n return min;\n}",
"function peak_of_mountain_array(arr) {\n // WRITE YOUR BRILLIANT CODE HERE\n let left = 0\n let right = arr.length - 1\n let peak = -1\n \n while (left <= right) {\n let mid = Math.floor((left + right)/2)\n \n if (mid === arr.length -1 || arr[mid] >= arr[mid+1]) {\n peak = mid\n right = mid -1\n } else {\n left = mid +1\n }\n }\n return peak\n}",
"function subarraySort(array) {\n\n let min = Infinity;\n let max = -Infinity;\n\n for(let i = 0; i < array.length; i++){\n let num = array[i]\n if(isNotSorted(i, array)){\n min = Math.min(min, num)\n max = Math.max(max,num)\n }\n\n }\n\n if(min === Infinity){\n return [-1,-1]\n }else{\n return max - min + 1\n }\n\n}",
"function max_subarray(A){\n let max_ending_here = A[0]\n let max_so_far = A[0]\n\n for (let i = 1; i < A.length; i++){\n max_ending_here = Math.max(A[i], max_ending_here + A[i])\n // console.log(max_ending_here)\n max_so_far = Math.max(max_so_far, max_ending_here)\n // console.log(max_so_far)\n } \n\n return max_so_far\n}",
"function peakOfMountainArray(arr) {\n let left = 0;\n let right = arr.length - 1;\n let idx;\n while(left <= right) {\n let mid = Math.floor((left + right) / 2);\n if(arr[mid] > arr[mid + 1]) {\n idx = mid;\n right = mid - 1;\n } else {\n left = mid + 1;\n };\n };\n return idx;\n}",
"function MinMax() {\n console.log('MAX: ', Math.max.apply(Math, newArr));\n console.log('MIN: ', Math.min.apply(Math, newArr));\n}",
"function bruteForceMaxSubarray(numbers) {\n let n = numbers.length; \n let res = 0; \n\n for (let i = 0; i < n; ++i) {\n let sum = 0; \n for (let j = i; j < n; ++j) {\n // for every subarray [i ... j]\n sum += numbers[j]; \n res = Math.max(res, sum);\n }\n }\n return res; \n }",
"function findMaxProduct(array) {\n\n}",
"function max_min_avg () {\n var sum = 0;\n var i = 0;\n var arr = [3, 7, -8, 19, 27, -5, 6];\n var max = arr[i];\n var min = arr[i];\n var newarr = [];\n for (var i = 0; i < arr.length; i++) {\n sum = sum + arr[i];\n if (i > 0) {\n if (arr[i] > max){\n var max = arr[i];\n }\n \n else if (arr[i] < min){\n var min = arr[i];\n }\n }\n }\n var avg = sum / arr.length;\n newarr.push(max);\n newarr.push(min);\n newarr.push(avg);\n return newarr;\n\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 maxFinderFunction(receivingGivingNumber) {\n // Assigning a hypothetic possibly-giving constraint\n let maxNumber = -1000000;\n// Looping through the given number array to iterate and search\n for(i = 0; i < receivingGivingNumber.length; i++) {\n if(receivingGivingNumber[i] > maxNumber) {\n maxNumber = receivingGivingNumber[i];\n }\n }\n // Returning result after looping completion\n console.log(maxNumber);\n return maxNumber;\n}",
"function findSmallestAndLargestProperty() {\n\n var objects = [document, window, navigator],\n idx,\n property,\n smallestProperty,\n biggestProperty;\n\n for (idx in objects) {\n\n for (property in objects[idx]) {\n\n smallestProperty = property;\n biggestProperty = property;\n break;\n }\n\n for (property in objects[idx]) {\n\n if (property < smallestProperty) {\n\n smallestProperty = property;\n }\n\n if (property > biggestProperty) {\n\n biggestProperty = property;\n }\n }\n\n jsConsole.writeLine(objects[idx]);\n jsConsole.writeLine('Smallest = ' + smallestProperty);\n jsConsole.writeLine('Biggest = ' + biggestProperty);\n jsConsole.writeLine(' ');\n }\n}",
"function find_largest_array(array)\n{\n\tvar index = 0;\n\tfor (var i = 0; i < array.length; i++)\n\t{\n\t\tif (array[i].length > array[0].length)\n\t\t{\n\t\t\tindex = i;\n\t\t}\n\t}\n\treturn index;\n}",
"function highestProduct2(arr){\nvar point1 = 0;\nvar point2 = 0;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
transforamtion des isbn en chaine | function formeIsbn(liste) {
var isbnOffre = "";
for (var i = 0; i < liste.length; i++) {
if (i == 0) isbnOffre = liste[i].book.isbn;
else {
if (i == liste.length - 1) isbnOffre = isbnOffre + "," + liste[i].book.isbn;
else isbnOffre = isbnOffre + "," + liste[i].book.isbn;
}
}
return isbnOffre;
} | [
"function convertIsbn10ToIsbn13(isbn10){\n // Check if isbn10 is valid\n if (!isValidIsbn10(isbn10)){\n console.warn(`${isbn10} is not a valid ISBN10 or not expecting dashes in argument`);\n return \"\";\n }\n let prefix = \"978\";\n let middle = isbn10.substring(0, isbn10.length - 1);\n let isbn13 = prefix + middle;\n // Determine the checksum of the ISBN13 number\n let sum = 0;\n for (let i = 0; i < isbn13.length; i++){\n if (i % 2 == 0){\n sum += parseInt(isbn13[i]);\n }\n else {\n sum += 3 * parseInt(isbn13[i]);\n }\n }\n let checksum = 10 - (sum % 10);\n return isbn13 + checksum;\n}",
"function RomanNumeralEncoder(){\n // ...\n }",
"function GenerateISBN() {\n var EANPrefix = MaxMinGenerator(978, 979).toString();\n var RegistrationGroup = DigitGenerator(MaxMinGenerator(1, 5));\n var RegistrationElement = DigitGenerator(MaxMinGenerator(1, 7));\n var PublicationElement = DigitGenerator(MaxMinGenerator(1, 6));\n var CheckDigit = MaxMinGenerator(1, 9).toString();\n var ISBN = EANPrefix + \"-\" + RegistrationGroup + \"-\" + RegistrationElement + \"-\" + PublicationElement + \"-\" + CheckDigit;\n return ISBN;\n}",
"function isbn13to10(isbn13)\n{\n var first9 = (isbn13 + '').slice(3).slice(0, -1);\n var isbn10 = first9 + isbn10_check_digit(first9);\n return isbn10;\n}",
"function isbn10_check_digit(isbn10)\n{\n var i = 0;\n var s = 0;\n var v;\n\n for (n = 10; n > 1; n--) {\n s += n * Number(isbn10[i]);\n i++;\n }\n\n s = s % 11;\n s = 11 - s;\n v = s % 11;\n\n if (v == 10)\n return 'x';\n else\n return v + '';\n}",
"function IATAConverter(iata) {\n switch (iata) {\n case 'MZG':\n return 'makung';\n case 'KHH':\n return 'kaohsiung';\n case 'TSA':\n return 'taipei-sung-shan';\n case 'RMQ':\n return 'taichung';\n default:\n return 'null';\n break;\n }\n}",
"function encode_digit(d, flag) {\n return d + 22 + 75 * (d < 26) - ((flag != 0) << 5);\n // 0..25 map to ASCII a..z or A..Z \n // 26..35 map to ASCII 0..9 \n }",
"function witCodes() {\n return {\n sq: 'Albanian',\n ar: 'Arabic',\n bn: 'Bengali',\n bs: 'Bosnian',\n bg: 'Bulgarian',\n my: 'Burmese',\n ca: 'Catalan',\n zh: 'Chinese',\n hr: 'Croatian',\n cs: 'Czech',\n da: 'Danish',\n nl: 'Dutch',\n en: 'English',\n et: 'Estonian',\n fi: 'Finnish',\n fr: 'French',\n ka: 'Georgian',\n de: 'German',\n el: 'Greek',\n he: 'Hebrew',\n hi: 'Hindi',\n hu: 'Hungarian',\n id: 'Indonesian',\n is: 'Icelandic',\n it: 'Italian',\n ja: 'Japanese',\n ko: 'Korean',\n la: 'Latin',\n lt: 'Lithuanian',\n mk: 'Macedonian',\n ms: 'Malay',\n no: 'Norwegian',\n fa: 'Persian',\n pl: 'Polish',\n pt: 'Portugese',\n ro: 'Romanian',\n ru: 'Russian',\n sr: 'Serbian',\n sk: 'Slovak',\n sl: 'Slovenian',\n es: 'Spanish',\n sw: 'Swahili',\n sv: 'Swedish',\n tl: 'Tagalog',\n ta: 'Tamil',\n th: 'Thai',\n tr: 'Turkish',\n uk: 'Ukrainian',\n vi: 'Vietnamese',\n }\n}",
"function convertNorwegianSentence(number) {\n \treturn \"Norwegian Sentence\";\n }",
"function invertirFrase(n) {\n let frase = \"\";\n for (let i = n.length - 1; i >= 0; i--) {\n frase += n[i];\n }\n return frase;\n }",
"function NbCaseVide() {\n let nombreDeCaseVide = 0;\n // TODO: parcourir le tableau damier avec une boucle for\n for (let i = 0 ; i < damier.length ; i++){\n // ร chaque itรฉration, si la valeur damier[i] est รฉgale 'V': incrรฉmenter nombreDeCaseVide de plus 1\n if (damier[i] === 'V'){\n nombreDeCaseVide++\n }\n }\n\n return nombreDeCaseVide;\n}",
"function siiB(e) {\r\n\treturn Math.round(parseInt(e)).toString(36);\r\n}",
"function bit_to_ascii(array) {\n var num = 0;\n var n;\n for (n = 0; n < 8; n++) {\n if (array[n] == '1') {\n num += Math.pow(2, 7 - n);\n console.log(num);\n }\n }\n return String.fromCharCode(num);\n}",
"function changeUppercase(str)\n{\n if(str==\"\" || eval(str)==0)\n return \"\\u96f6\";\n \n if(str.substring(0,1) == \"-\")\n { \n if(eval(str.substring(1)) < 0.01)\n return \"\\u91d1\\u989d\\u6709\\u8bef!!\";\n else\n str = str.substring(1);\n }\n \n var integer_part=\"\";\n var decimal_part=\"\\u6574\";\n var tmpstr=\"\";\n var twopart=str.split(\".\");\n \n //\\u5904\\u7406\\u6574\\u578b\\u90e8\\u5206\\uff08\\u5c0f\\u6570\\u70b9\\u524d\\u7684\\u6574\\u6570\\u4f4d\\uff09\n var intlen=twopart[0].length;\n \n if (intlen > 0 && eval(twopart[0]) != 0)\n {\n var gp=0;\n var intarray=new Array();\n \n while(intlen > 4)\n {\n intarray[gp]=twopart[0].substring(intlen-4,intlen);\n gp=gp+1;\n intlen=intlen-4;\n }\n \n intarray[gp]=twopart[0].substring(0,intlen);\n \n for(var i=gp;i>=0;i--)\n {\n integer_part=integer_part+every4(intarray[i])+pubarray3[i];\n }\n\n integer_part=replace(integer_part,\"\\u4ebf\\u4e07\",\"\\u4ebf\\u96f6\");\n integer_part=replace(integer_part,\"\\u5146\\u4ebf\",\"\\u5146\\u96f6\");\t\n\n while(true)\n {\n if (integer_part.indexOf(\"\\u96f6\\u96f6\")==-1)\n break;\n\n integer_part=replace(integer_part,\"\\u96f6\\u96f6\",\"\\u96f6\");\n }\n \n integer_part=replace(integer_part,\"\\u96f6\\u5143\",\"\\u5143\");\n\n /*\\u6b64\\u5904\\u6ce8\\u91ca\\u662f\\u4e3a\\u4e86\\u89e3\\u51b3100000\\uff0c\\u663e\\u793a\\u4e3a\\u62fe\\u4e07\\u800c\\u4e0d\\u662f\\u58f9\\u62fe\\u4e07\\u7684\\u95ee\\u9898\\uff0c\\u6b64\\u6bb5\\u7a0b\\u5e8f\\u628a\\u58f9\\u62fe\\u4e07\\u622a\\u6210\\u4e86\\u62fe\\u4e07\n tmpstr=intarray[gp];\n \n if (tmpstr.length==2 && tmpstr.charAt(0)==\"1\")\n {\n intlen=integer_part.length;\n integer_part=integer_part.substring(char_len,intlen);\n }\n */\n }\n \n //\\u5904\\u7406\\u5c0f\\u6570\\u90e8\\u5206\\uff08\\u5c0f\\u6570\\u70b9\\u540e\\u7684\\u6570\\u503c\\uff09\n tmpstr=\"\";\n if(twopart.length==2 && twopart[1]!=\"\")\n {\n if(eval(twopart[1])!=0)\n {\n decimal_part=\"\";\n intlen= (twopart[1].length>2) ? 2 : twopart[1].length;\n \n for(var i=0;i<intlen;i++)\n {\n tmpstr=twopart[1].charAt(i);\n decimal_part=decimal_part+pubarray1[eval(tmpstr)]+pubarray4[i];\n }\n \n decimal_part=replace(decimal_part,\"\\u96f6\\u89d2\",\"\\u96f6\");\n decimal_part=replace(decimal_part,\"\\u96f6\\u5206\",\"\");\n \n if(integer_part==\"\" && twopart[1].charAt(0)==0)\n {\n intlen=decimal_part.length;\n decimal_part=decimal_part.substring(char_len,intlen);\n }\n }\n }\n \n tmpstr=integer_part+decimal_part;\n \n return tmpstr;\n}",
"function ak2uy ( akstr )\n{\n var tstr = \"\" ;\n for ( i = 0 ; i < akstr.length ; i++ ) {\n code = akstr.charCodeAt(i) ;\n if ( code < BPAD || code >= BPAD + akmap.length ) {\n tstr = tstr + akstr.charAt(i) ; \n continue ;\n }\n\n code = code - BPAD ; \n\n if ( code < akmap.length && akmap[code] != 0 ) {\n tstr = tstr + String.fromCharCode ( akmap[code] ) ;\n } else {\n tstr = tstr + akstr.charAt(i) ; \n }\n }\n\n return tstr ;\n}",
"complement(){\n this.dna = complementStrand(this.dna);\n }",
"static convertToEng(number) {\n var arabic = { \"ู \": \"0\", \"ูก\": \"1\", \"ูข\": \"2\", \"ูฃ\": \"3\", \"ูค\": \"4\", \"ูฅ\": \"5\", \"ูฆ\": \"6\", \"ูง\": \"7\", \"ูจ\": \"8\", \"ูฉ\": \"9\" };\n var chars = number.toString().split(\"\");\n var newNum = new Array();\n for (var i = 0; i < chars.length; i++) {\n if (arabic[chars[i]] == undefined || arabic[chars[i]] == null)\n newNum[i] = chars[i];\n else\n newNum[i] = arabic[chars[i]];\n }\n return newNum.join(\"\");\n }",
"function parse_ISBN13() {\n\n var prod_details_elms = $('div#detail-bullets table#productDetailsTable div.content ul');\n var isbn_text = $(prod_details_elms).find('li:has(b:contains(\"ISBN-13:\"))').text();\n\n isbn_text = isbn_text.split(' ')[1];\n return isbn_text;\n}",
"function checkISBN(field, rules, i, options) {\r\n\t\tvar ISBN = field.val().replace(/[^0-9a-zA-Z]/g, ''); //Strip off any dashes from the ISBN\r\n\t\t\r\n\t\tif (ISBN.length == 10 || ISBN.length == 13) {\r\n\t\t\t//No problem!\r\n\t\t} else {\r\n\t\t\treturn '* An ISBN will have either 10 or 13 numbers, dashes are okay';\r\n\t\t}\r\n\t}",
"if (conv === verdadero) {\n\t\t\t\t\t\t\t\t\tconv = convertidores [conv2];\n\n\t\t\t\t\t\t\t\t// De lo contrario, inserte el tipo de datos intermedio\n\t\t\t\t\t\t\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pool Does Not Contain Entity Exception | function PoolDoesNotContainEntityException(entity, message) {
_super.call(this, message + "\nPool does not contain entity " + entity);
} | [
"function PoolRequests (){ \n return myContract.methods.getRequestCount().call().then(function(totalCount){ \n console.log(\"-----------------------------------------------------\");\n console.log(\"Total Request since start = \", totalCount);\n }).then(function(){\t \n return myContract.methods.getRequestPool().call().then(function(pool){ \n console.log(\"Active Request pool: total = \", pool.length);\n console.log(pool);\n return pool;\n })\n }).then(function(pool){\t\n ListoutPool(pool, 'request');\n }).catch(function(err){ //catch any error at end of .then() chain!\n console.log(\"List Pool Request Info Failed! \")\n console.log(err);\n process.exit();\n }) \n}",
"async function connectMetPool(){\n //vind de geneiss file. In dit project zit het in de code map. Een map hoger dan deze\n const genesisFilePath = path.join(__dirname, '..', '..', 'pool_genesis.txn');\n \n //creeer de poolconfig\n const poolConfig = {'genesis_txn': genesisFilePath}\n \n //probeer een poolLedgerConfig te maken.\n try{ \n await indy.createPoolLedgerConfig(POOL_NAME, poolConfig)\n }catch(e){ \n console.log(`pool ledger already exists with name ${POOL_NAME}`);\n }\n \n //connect met de pool zodat je een hadle terug krijgt om er mee te praten\n LedgerHandler.poolHandle = await indy.openPoolLedger(POOL_NAME, undefined);\n}",
"queryPool() {\n const request = new types.staking_query_pb.QueryPoolRequest();\n return this.client.rpcClient.protoQuery('/cosmos.staking.v1beta1.Query/Pool', request, types.staking_query_pb.QueryPoolResponse);\n }",
"function insertPoolRecord(dynamo, config, pool) {\n return dynamo.put(insertRequest(config, poolItem(config, pool))).promise();\n}",
"function getPool(name='_default'){\n // pool exists ?\n if (name in _pools){\n return _pools[name];\n }else{\n throw new Error('Unknown pool <' + name + '> requested');\n }\n}",
"function insertPoolListRecord(dynamo, config, pool) {\n return dynamo\n .put(insertRequest(config, poolListItem(config, pool)))\n .promise();\n}",
"function LMSGetPooledQuestionNos() {\n return (LMSGetValue(\"instancy.pooledquestionnos\"));\n}",
"addpool(id) {\n\t\tconst idx = this.poolids.indexOf(id);\n\t\tif(idx == -1) this.poolids.push(id);\n\t\tfor(var m of this.unassigned()) this.assign(m);\n\t}",
"function getParticleFromPool() {\n for (var i = 0, l = particles.length; i < l; i++) {\n if (!particles[i].attract) return particles[i];\n }\n return false;\n}",
"getMissingEntities (memory) {\n return this.notions.filter(c => c.entities.some(e => memory[e.alias]) === false)\n }",
"async function bulkInsert(pool, bulkContent, sql) {\n let con;\n try {\n con = await pool.getConnection();\n if (con) {\n con.beginTransaction();\n await con.batch(sql, bulkContent);\n con.commit();\n }\n } catch (batchError) {\n if (con) {\n con.rollback();\n }\n throw batchError;\n } finally {\n if (con) {\n con.release();\n }\n }\n}",
"open() {\n if (!this.pool) {\n this.pool = new pg_1.Pool({\n host: this.host,\n port: this.port,\n database: this.database,\n user: this.username,\n password: this.password,\n min: this.minPoolSize,\n max: this.maxPoolSize\n });\n }\n return this.pool;\n }",
"checkSpaceAvailable(vehicle)\n {\n throw new Error(\"Unparked..\"+vehicle)\n }",
"constructor(){\n this.mempool = {};\n this.timeoutRequests = {};\n }",
"runPool() {\n info('Running stacked command pool');\n let data;\n while (this.pool.length > 0) {\n data = this.pool.shift();\n this.socket.write(data);\n }\n }",
"packEntities(options) {\n this.entities = [];\n let identityFn = null;\n if(this.metadata.generator === 'id') {\n identityFn = (a,b) => !_.isUndefined(a.id) && !_.isUndefined(b.id) && a.id === b.id;\n }\n // console.log(this);\n\n _.forOwn(this, (v,k) => {\n if(k !== 'entities') {\n // console.log(k, v);\n this[k] = Pson.map(v, e => this.insertToEntities(e, identityFn));\n }\n });\n\n // only regenerate if not exists\n _.forEach(this.entities, (e, i) => {\n if(!e.id) {\n e.id = e.className+'-'+i;\n }\n });\n \n this.entities = _.map(this.entities, e => Pson.map(e, (c, path) => {\n if(path === '') {\n return c; \n } else {\n return c.id;\n }\n }));\n \n _.forOwn(this, (v,k) => {\n if(k !== 'entities') {\n this[k] = Pson.map(v, e => e.id);\n }\n });\n // console.log('entities', this.entities);\n }",
"findNotLoadedIds(persistedEntities, dbEntities) {\n return __awaiter(this, void 0, void 0, function* () {\n const newDbEntities = dbEntities ? dbEntities.map(dbEntity => dbEntity) : [];\n const missingDbEntitiesLoad = persistedEntities.map((entityWithId) => __awaiter(this, void 0, void 0, function* () {\n if (entityWithId.id === null || // todo: not sure if this condition will work\n entityWithId.id === undefined || // todo: not sure if this condition will work\n newDbEntities.find(dbEntity => dbEntity.entityTarget === entityWithId.entityTarget && dbEntity.compareId(entityWithId.id)))\n return;\n const alias = entityWithId.entityTarget.name; // todo: this won't work if target is string\n const parameters = {};\n let condition = \"\";\n const metadata = this.connection.entityMetadatas.findByTarget(entityWithId.entityTarget);\n if (metadata.hasParentIdColumn) {\n condition = metadata.parentIdColumns.map(parentIdColumn => {\n parameters[parentIdColumn.propertyName] = entityWithId.id[parentIdColumn.propertyName];\n return alias + \".\" + parentIdColumn.propertyName + \"=:\" + parentIdColumn.propertyName;\n }).join(\" AND \");\n }\n else {\n condition = metadata.primaryColumns.map(primaryColumn => {\n parameters[primaryColumn.propertyName] = entityWithId.id[primaryColumn.propertyName];\n return alias + \".\" + primaryColumn.propertyName + \"=:\" + primaryColumn.propertyName;\n }).join(\" AND \");\n }\n const loadedEntity = yield new QueryBuilder(this.connection, this.queryRunner)\n .select(alias)\n .from(entityWithId.entityTarget, alias)\n .where(condition, parameters)\n .getSingleResult();\n if (loadedEntity)\n newDbEntities.push(new OperateEntity(metadata, loadedEntity));\n }));\n yield Promise.all(missingDbEntitiesLoad);\n return newDbEntities;\n });\n }",
"setupBubblePool(_numBubbles){\n let numObjs = _numBubbles;\n \n for (let i = 0; i < numObjs; i++){\n this.createBubble\n (-99,-99, Math.random()*\n (this.maxB-this.minB)+this.minB);\n // Grab this object.\n this.bubbles[i] = RedHen_2DPhysics.\n lastObjectCreated();\n // Time to sleep.\n RedHen_2DPhysics.lastObjectCreated().\n makeSleep(true);\n }\n \n }",
"function poolListItem(config, pool) {\n return {\n id: \"POOL_LIST:\" + config.env,\n env: pool.name,\n name: pool.name,\n url: encodeURIComponent(pool.name)\n };\n}",
"createParkingLot(capacity) {\n try {\n const result = this.parkingManager.createParkingLot(capacity);\n console.log(`Created parking lot with ${capacity} slots`);\n return result;\n } catch (e) {\n throw new Exception(errorMessage.PROCESSING_ERROR, e);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove from the canvas the given particle | function clearParticle(particle) {
var locationToRemove = particle.locations.shift();
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(locationToRemove.x * (width / rows), locationToRemove.y * (height / rows), width / rows, height / rows);
} | [
"function stopParticle(particle, xnum, ynum) {\n particle.x = xnum;\n particle.y = ynum;\n particle.draw();\n\n return;\n}",
"__removeParticleEventListener(){\n Utils.changeCursor(this.myScene.canvasNode, \"pointer\");\n this.myScene.canvasNode.addEventListener(\"mousedown\", this.__removeParticleDisposableEvent);\n }",
"delete() {\n this.deltaX = 0;\n this.deltaY = +5;\n // if bubble currently on the board, remove it\n if (this.row !== undefined && this.col !== undefined) {\n let row = this.board.pieces[this.row];\n let col = this.col;\n row[col] = null;\n }\n this.falling = true;\n this.collided = false;\n this.canvas.objects.push(this);\n }",
"function removePoint(){\n \t if(currentPt != null){\n \t\t map.removeLayer(currentPt);\n \t\t currentPt = null;\n \t\t recenterMap();\n \t\t resetCurrentLoc();\n \t }\n }",
"removeHitObject() {\n const pos = this.findObj(this.lastUpdated);\n if (pos >= 0) {\n const sprite = this.hitObjectSpriteList.filter(item => item.id === 'CIRCLE_' + this.lastUpdated);\n if (sprite.length > 0) {\n this.hitObjectStage.removeChild(sprite[0]);\n sprite[0].destroy();\n }\n this.hitObjects.splice(pos, 1);\n this.hitObjectSpriteList.splice(pos, 1);\n }\n }",
"function popPart(particle) {\n\t\tif (particle.currentSize < 3) {\n\t\t\tparticle.currentSize = Math.random() * SEED_SIZE;\n\t\t} else {\n\t\t\tparticle.currentSize *= .96;\n\t\t}\n\t}",
"remove(point) {\n if (this.divided) {\n // If there are children then perform the removal on them\n this.children.forEach(child => {\n child.remove(point);\n });\n // Check if quads can be merged, being placed here is performed recursively from inner to outer quads\n this.merge();\n }\n\n // There are no children so check the current quad\n if (this.boundary.contains(point)) {\n // Filter the points that coincide with the target to remove\n this.points = this.points.filter(p => p.x !== point.x || p.y !== point.y);\n }\n }",
"function removeFood(){\n //First paint over the food with white\n var ctx = document.getElementById(\"gameCanvas\").getContext('2d');\n ctx.fillStyle = \"white\";\n ctx.beginPath;\n ctx.moveTo(this.xLoc, this.yLoc);\n ctx.arc(this.xLoc, this.yLoc, foodSize / 2, 0, 2 * Math.PI);\n ctx.fill();\n ctx.beginPath;\n //Now find this food in the global array and remove it\n for (var i = 0; i < foodList.length; i++){\n var curFood = foodList[i];\n if (curFood.xLoc == this.xLoc && curFood.yLoc == this.yLoc){\n foodList.splice(i, 1);\n break;\n }\n }\n if (foodList.length == 0){\n endRound();\n }\n}",
"remove(id) {\n if (this._particles.hasOwnProperty(id)) {\n this._particles[id].parent.removeChild(this._particles[id])\n delete this._particles[id];\n // update keys\n this._keys = Object.keys(this._particles);\n return true;\n }\n return false;\n }",
"removeFigure(figure){\n\t\tthis.boardMatrix[figure.positionY][figure.positionX].sprite.destroy();\n\t\tthis.boardMatrix[figure.positionY][figure.positionX].figure = null;\n\t\tfigure.isAlive = false;\n\t}",
"onRemovedFromScene() {\n if (this._pixiObject !== null)\n this._pixiContainer.removeChild(this._pixiObject);\n if (this._threeObject !== null) this._threeGroup.remove(this._threeObject);\n }",
"deleteDots() {\n let room_buffer = this._room_canvas;\n let canvas_objects = room_buffer.getObjects();\n canvas_objects.forEach(function (item, i) {\n if (item.type == 'debug') {\n room_buffer.remove(item);\n }\n });\n room_buffer.renderAll();\n }",
"delete(){\n\t\tif (removeFromReferenceCount(this.index) === 0){\n\t\t\tthis.gl.deleteTexture(this.texture);\n\t\t}\n }",
"remove() {\n this.floor.itemSprites.removeChild(this.sprite);\n }",
"function checkUnclickedBanana( moving_banana )\n{\n stage.removeChild( moving_banana );\n}",
"function placeMark(x, y, image) {\n // the particle will be scaled from min to max to add variety\n var scale = Math.random() * (trpm.maxScale - trpm.minScale) + trpm.minScale;\n var w = image.width;\n var h = image.height;\n\n if (clearPathContext) {\n clearPathContext.globalAlpha = Math.random() * (trpm.maxOpacity - trpm.minOpacity) + trpm.minOpacity;\n clearPathContext.globalCompositeOperation = \"destination-out\";\n clearPathContext.drawImage(\n // image\n image,\n // source x\n 0,\n // source y\n 0,\n // source width\n w,\n // source height\n h,\n // target x\n x - w / 2,\n // target y\n y - h / 2,\n // target width\n w * scale,\n // target height\n h * scale);\n // request to update that out of normal rendering loop\n requestFrameRender();\n }\n }",
"stopGC() {\n if (this.currentParams.pointList.length > 1) {\n this.drawTurtle.CreateExtrudeShape(\"tube\" + (this.drawTurtle.graphicElems.length + 1).toString(), { shape: this.currentParams.shapeSection, path: this.currentParams.pointList, sideOrientation: BABYLON.Mesh.DOUBLESIDE, radius: 0.075 }, this.drawTurtle.materialTextures[0]);\n this.currentParams.pointList = [];\n }\n this.currentParams.generalizedCylinder = false;\n this.currentParams.customId = SHAPE_NOID;\n this.currentParams.customParentId = SHAPE_NOID;\n }",
"function mousePressed(){\r\n count-=1;\r\n if(gameState===\"PLAY\" && count>0){\r\n particle=new Particle(mouseX,10,10);\r\n }\r\n}",
"removeObject(object) {\n this.scene.remove(object);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
verifForm(login, mot_de_passe) Cette fonction verifies si le login et le mot de passe de sont bien saisis. | function verifForm(login, mdp) {
/*********** Login verification **********************/
if ((login == undefined) || (login.length == 0)) {
$('#login_obligatoire').show();
return false;
}
$('#login_obligatoire').hide();
/************* Mot de passe verification **************/
if ((mdp == undefined) || (mdp.length == 0)) {
$('#mdp_obligatoire').show();
return false;
}
$('#mdp_obligatoire').hide();
return true;
} | [
"function VerificationConfirmation() {\n const confirmation = document.getElementById(\"confirmation\");\n const pwd = document.getElementById(\"pwd\");\n const LMINI = 8; // DP LMINI = longueur minimale du mot de passe\n\n //DP si le mot de passe comporte moins de 8 lettres et que la confirmation est differente au mot de passe alors erreur\n if ((confirmation.value.length < LMINI) || (confirmation.value !== pwd.value)) {\n console.log(\"longueur confirmation NOK\", pwd.value.length, confirmation.value.length);\n return false;\n } else {\n console.log(\"longueur confirmation OK\", pwd.value.length, confirmation.value.length);\n return true;\n }\n}",
"function validaClave( form )\n\t{\n\t\tvar regreso;\n\t\t\tregreso = true;\n\t\t\tregreso = vtxtVacio( form.txt_clave, \"Clave\" );\n\t\t\tif ( regreso )\n\t\t\t\tregreso = vtxtLongitudMenorIgual( form.txt_clave, 10 );\t\t\t\n\t\t\tif ( regreso )\n\t\t\t\tregreso = vtxtEspacios( form.txt_clave );\n\t\t\tif( regreso )\n\t\t\t\tregreso = vtxtAlfa2( form.txt_clave );\n\t\treturn regreso;\t\t\n\t}",
"function areTheyLogged(form)\n{\n if(!validatelogin(form)) return false;\n\n return true;\n}",
"function VerificationPwd() {\n const pwd = document.getElementById(\"pwd\");\n const LMINI = 8; // DP LMINI = longueur minimale du mot de passe\n\n //DP si le mot de passe comporte moins de 8 lettres alors erreur\n if (pwd.value.length < LMINI) {\n console.log(\"longueur pwd NOK\", pwd.value.length);\n return false;\n } else {\n console.log(\"longueur pwd OK\", pwd.value.length);\n return true;\n }\n}",
"formNotOK() {\n alert(\"verifiez les champs en rouge\");\n }",
"function validaPerfil( form )\n\t{\t\n\t\tvar\t\tmensaje\t\t=\t'';\n\t\tvar\t\tsalida\t\t=\tfalse;\n\t\t\n if( form.slc_perfil.value == '' )\n {\n \t\tmensaje\t=\t' Debe seleccionar un PERFIL para el usuario.\\n';\n \t\tmensajeError( form.slc_perfil , mensaje );\n } \n else\n if( form.slc_perfil.value == 'OCIINSCR' && form.txt_curp.value=='') // Operador asesor certificado\n {\n \t\tmensaje\t=\t'\\t****** I M P O R T A N T E ****** \\n\\n'\n \t\t\t\t+\t' Este PERFIL requiere el CURP para validarlo en el \\n'\n \t\t\t\t+\t' - Sistema de Asesores Certificados ( SAC )\\n\\n'\n \t\t\t\t+\t' El CURP validado incluira el Nombre y Apellidos que existan en SAC.'\n \t\t\t\t; \n \tmensajeInfonavit( mensaje );\n }\n else\n {\n \tsalida\t=\ttrue;\n }\n \n return \tsalida;\n\t}",
"function validateLosePwdOne(form) {\r\n var flag = validateField(\"#j_username\", /.{1,100}$/, usernameErrormsg, true);\r\n flag = flag && validateField(\"#j_checkcode\", /^[A-Za-z0-9]{5}$/, checkcodeErrormsg, false);\r\n flag = flag && validateField(\"#j_smscode\", /^[0-9]{6}$/, smscodeErrormsg, false);\r\n\r\n return flag;\r\n}",
"function VerificationVille() {\n const ville = document.getElementById(\"ville\");\n const LMAXI = 50; // DP LMAXI = longueur maximale de la ville\n\n //DP si la ville comporte plus de 50 lettres alors erreur\n if ((ville.value.length > LMAXI) || (ville.value.length === 0)) {\n console.log(\"longueur ville NOK\", ville.value.length);\n return false;\n } else {\n console.log(\"longueur ville OK\", ville.value.length);\n return true;\n }\n}",
"function VerificationPrenom() {\n const prenom = document.getElementById(\"prenom\");\n const LMINI = 2, // DP LMINI = longueur minimale du prenom\n LMAXI = 50; //DP LMAXI = longueur maximale du prenom\n\n //DP si le prenom comporte moins de 2 lettres ou plus de 50 lettres alors erreur\n if ((prenom.value.length < LMINI) || (prenom.value.length > LMAXI)) {\n console.log(\"longueur prenom NOK\", prenom.value.length);\n return false;\n } else {\n console.log(\"longueur prenom OK\", prenom.value.length);\n return true;\n }\n}",
"function changepw(form, password, conf, email=\"testforempty\") {\r\n\t\r\n // Check each field has a value\r\n if ( email.value == '' || password.value == '' || conf.value == '') {\r\n custom_show_message(\"Error\", 'You must provide all the requested details. Please try again', \"alert\");\r\n return false;\r\n }\r\n \r\n\tif(!check_password(password, conf, form)){\r\n\t\treturn false;\r\n\t}\r\n\t\r\n // Create a new element input, this will be our hashed password field. \r\n var p = document.createElement(\"input\");\r\n \r\n // Add the new element to our form. \r\n form.appendChild(p);\r\n p.name = \"p\";\r\n p.type = \"hidden\";\r\n p.value = hex_sha512(password.value);\r\n \r\n // Make sure the plaintext password doesn't get sent. \r\n password.value = \"\";\r\n conf.value = \"\";\r\n\r\n return true;\r\n}",
"function IndivisualLog() {\n\n \n var inFieldU = document.getElementById(\"in-userf\");\n var inFieldP = document.getElementById(\"in-passf\");\n \n var inLabelU = document.getElementById(\"in-user\");\n var inLabelP = document.getElementById(\"in-pass\");\nusernameRegex .exec(inFieldU);//regular expression\n const vaild=!!usernameRegex;\n if(!vaild){\nalert(\"user name is invaild\");\nreturn false\n }\n\n //if already shown from previous submit to hide it\n if (inLabelU.style.display === \"inline\" || \n inLabelP.style.display === \"inline\" \n \n \n ) {\n\n inLabelU.style.display = \"none\";\n inLabelP.style.display = \"none\";\n \n \n \n }\n if( inFieldU.value[0].match(RegexFirstchar) != null ){\n inLabelU.innerHTML=\"user name should not start with number or Literal Characters\";\n inLabelU.style.display=\"inline\"\n return false\n }\n\n \n }",
"function validar(){ \n let IDcalle= document.getElementById(\"IDcalle\").value;\n let IDnumero = document.getElementById(\"IDnumero\").value;\n if ((IDcalle == 0) || (IDnumero == 0) ) {\n alert(\"Debes completar todos los campos correctamente\");\n } \n else{\n let captcha = document.getElementById(\"captchaintroducido\").value;\n if (captcha != valorCaptcha){\n alert(\"El captcha introducido es incorrecto, por favor intente nuevamente\");\n }\n else{\n alert(\"El formulario fue enviado correctamente\");\n IDpedido.reset();\n //borrarTabla();\n }\n crearCaptcha();\n }\n}",
"function validatePassLogin(){\n\n\n\tif (logInUserForm.users_Password.value === \"\" || logInUserForm.users_Password.value === null) {\n\n\t\tlogInUserForm.users_Password.style.borderColor = \"red\";\n\t\ttheUserLoginPassErr.innerHTML = \"Password is required\";\n\t}else{\n\n\t\tlogInUserForm.users_Password.style.borderColor = \"green\";\n\t\ttheUserLoginPassErr.innerHTML = \"\";\n\n\t}\n}",
"function GuardarFormularioCaptura(form){\n \n\tif (!ValidateForm(form)){\n\n\t if(VAR_ERROR.length > 0){\n var html = '';\n CAMPOS_OBLIGATORIOS=[];\n //Si el anexo accionistas no estรก habilitado remueve los campos obligatorios\n if(!($(\"input[name='anexo_accionistas'][value='SI']\")[0].checked)){\n var index = []; \n for(var key in VAR_ERROR){\n if(VAR_ERROR[key]==$(\"input.accionista_cotiza_bolsa\")[0] || VAR_ERROR[key]==$(\"input.accionista_persona_publica\")[0] || VAR_ERROR[key]==$(\"accionista_obligaciones_otro_pais\")[0]){\n index.push(key);\n }\n }\n for(var key = index.length-1; key>=0; key--){\n VAR_ERROR.splice(index[key], 1);\n }\n \n }\n\n\t $('div#modal-juridico').on('show.bs.modal',function(){\n\n $(this).off('show.bs.modal');\n\t $(this).find('.modal-content').find('.modal-title').text('ALGUNOS CAMPOS ESTAN VACIOS ESTA DE ACUERDO ?')\n $(this).find('.modal-content').find('.modal-body').html('<div class=\"container-fluid\"><ul style=\"list-style-type: circle;\">');\n $('div#modal-juridico').find('.modal-content').find('.modal-footer').find('button.btn-guardar').html('Guardar <span class=\"glyphicon glyphicon-save\"></span>').attr('id','guardar-formulario-captura').removeAttr('disabled');\n \n\t $.each(VAR_ERROR, function(indexItem, valItem) {\n\t if($('label[for=\"' + valItem.name + '\"]').length){\n\t html += '<li style=\"line-height: 1.5;\">'+$('label[for=\"' + valItem.name + '\"]').text().replace(':','');\n }\n if($(valItem).hasClass(\"campo_obligatorio\")){\n html += '*';\n CAMPOS_OBLIGATORIOS.push(valItem);\n }\n\t });\n\n\t $('div#modal-juridico').find('.modal-content').find('.modal-body ul').html(html);\n\t \n }).modal({keyboard: false, backdrop: 'static', show:true});\n \n if(CAMPOS_OBLIGATORIOS.length > 0){\n $('div#modal-juridico').on('show.bs.modal',function(){\n html='';\n\n $(this).off('show.bs.modal');\n $(this).find('.modal-content').find('.modal-title').text('LOS SIGUIENTES CAMPOS SON OBLIGATORIOS')\n $(this).find('.modal-content').find('.modal-body').html('<div class=\"container-fluid\"><ul style=\"list-style-type: circle;\">');\n $('div#modal-juridico').find('.modal-content').find('.modal-footer').find('button.btn-guardar').html('Guardar <span class=\"glyphicon glyphicon-save\"></span>').attr('disabled','true');;\n \n $.each(CAMPOS_OBLIGATORIOS, function(indexItem, valItem) {\n if($('label[for=\"' + valItem.name + '\"]').length){\n html += '<li style=\"line-height: 1.5;\">'+$('label[for=\"' + valItem.name + '\"]').text().replace(':','');\n }\n });\n \n $('div#modal-juridico').find('.modal-content').find('.modal-body ul').html(html);\n \n }).modal({keyboard: false, backdrop: 'static', show:true});\n }\n\t }\n\t}else{\n GuardarFormulario(form); \n }\n}",
"function showPass() {\n const password = document.getElementById('password');\n const rePassword = document.getElementById('masterRePassword');\n if (password.type === 'password') {\n password.type = 'text';\n rePassword.type = 'text';\n logMe(\"User\", \"Toggle-Password\", \"Create ByPass account\", \"ON - Password Confirm Input : \" + password.value);\n } else {\n password.type = 'password';\n rePassword.type = 'password';\n logMe(\"User\", \"Toggle-Password\", \"Create ByPass account\", \"OFF - Password Confirm Input : \" + password.value);\n }\n} // show password function",
"function formVerify() {\n if (formInfo.contactMsg.value !== \"\") {\n if (emailRegex.test(formInfo.contactEmail.value)) {\n if (formInfo.contactName.value !== \"\") {\n return \"allGood\";\n }\n return \"nameInvalid\";\n }\n return \"emailInvalid\";\n }\n\n return \"msgInvalid\";\n}",
"function check() {\r\n\r\n // stored data from the register-form\r\n let storedID = localStorage.getItem('id_no1');\r\n let storedName = localStorage.getItem('name1');\r\n let storedPw = localStorage.getItem('psw1');\r\n\r\n // entered data from the login-form\r\n let userID = document.getElementById('id_no');\r\n let userName = document.getElementById('name');\r\n var userPw = document.getElementById('psw');\r\n\r\n // check if stored data from register-form is equal to data from login form\r\n if(userID.value == storedID && userName == storedName && userPw.value == storedPw) {\r\n alert('Error already hav an account');\r\n }else {\r\n alert('You Logged in.');\r\n }\r\n}",
"function reg_validateForm(){\n\t// Effacer les erreurs prรฉcรฉdents\n\tremove_errors();\n\tvar flag = true;\n\t\n\t// Vรฉrifier la validtรฉ de l'entrรฉe pour tout objet de la classe .ids \n\t$( \".ids_reg\" ).each(function() {\n\t\tvar e = $( this ).children(\"input\");\n\t\tflag &= validateEntry(e);\n\t\t});\n\t\n\tif( !validateEmail($(\"#mail_register\").val()) ){\n\t\tfonc_erreur($(\"#mail_register\"), \"Le mail n'est pas valide\");\n\t\treturn;\n\t}\n\t\n\tif($(\"#pass_register\").val() != $(\"#repass_register\").val()){\n\t\tfonc_erreur($(\"#repass_register\"), \"Les mots de pass ne sont pas รฉgales\");\n\t\t\n\t\treturn;\n\t}\n\t\n\tif(flag){\n\t\tregister(\t$(\"#login_register\").val(),\n\t\t\t\t\t$(\"#mail_register\").val(),\n\t\t\t\t\t$(\"#nom_register\").val(),\n\t\t\t\t\t$(\"#prenom_register\").val(),\n\t\t\t\t\t$(\"#pass_register\").val()\n\t\t\n\t\t);\n\t\t\n\t}\n}",
"function provera() { \n\tif (!proveriIme()) {\n\t\talert(\"Duลพina imena treba da je izmeฤu 6 i 10 znakova.\"); \n\t\treturn false;\n\t} else if (!proveriJednakostSifri()) { \n\t\talert (\"ล ifre nisu iste.\"); \n\t\treturn false;\n\t} else if (!proveriValidnostSifre()) { \n\t\talert(\"ล ifra mora imati makar jedan mali i veliki znak i cifru.\");\n\t\treturn false;\n\t}\n\treturn true;\n}",
"function VerificationAdresse() {\n const adresse = document.getElementById(\"adress\");\n const LMAXI = 100; // DP LMAXI = longueur maximale de l adresse\n\n //DP si l adresse comporte plus de 100 lettres alors erreur\n if ((adresse.value.length > LMAXI) || (adresse.value.length === 0)) {\n console.log(\"longueur adresse NOK\", adresse.value.length);\n return false;\n } else {\n console.log(\"longueur adresse OK\", adresse.value.length);\n return true;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch phases from server | @action fetchPhases() {
// To reduce number of REST api calls, fetch phases only when list is empty
if (this.phases.length == 0) {
RestClientService.callGet('/phases').then(response => {
return response
.json()
.then(json => {
this.phases = json;
});
}).catch(err => {
console.error('Fetch phases failed');
});
}
} | [
"_fetchState() {\n this._fetchLeagues();\n this._fetchSeasons();\n this._fetchRallies();\n this._fetchDrivers();\n }",
"getArchived({commit}, data) {\n commit('setElectionsLoadStatus', 1);\n\n ElectionAPI.getArchived(\n data.url\n )\n .then( function(response) {\n commit('setElections', response.data.data);\n commit('setElectionsLoadStatus', 2);\n commit('setElPagination', {\n meta: response.data.meta,\n links: response.data.links\n });\n })\n .catch( function() {\n commit('setElections', []);\n commit('setElectionsLoadStatus', 3);\n });\n }",
"getTracks() {\n return new Promise((resolve, reject) => {\n this._get('/tracks').then((response) => { resolve(response) });\n })\n }",
"fetchAdminCompletedOrders() {\n return this.http.get('order/completedOrder');\n }",
"async getRespondentsOfAllSurveys(){\n\n const cookies = new Cookies();\n var token = cookies.get('token');\n\n for(let i = 0 ; i < this.state.surveys.length ; ++i){\n const response = await fetch('https://localhost:44309/Answer/getReport/' + this.state.surveys[i].surveyId, {\n headers: {\n 'Authorization': `Bearer ${token}`\n }\n \n });\n if(!response.ok) this.respondents.push({\n surveyId: this.state.surveys[i].surveyId,\n completedCounter: 0\n });\n else{\n const counters = await response.json();\n this.respondents.push({\n surveyId: this.state.surveys[i].surveyId,\n completedCounter: counters.completedCounter\n });\n }\n }\n }",
"getProgresses ({ commit, dispatch }) {\n return this._vm.$api.get('tmdb/progresses/')\n .then(response => {\n commit('setProgresses', response.data)\n dispatch('finishProgressesFirstLoad')\n })\n }",
"getGoals() {\n return new Promise((resolve, reject) => {\n this._get('/goals').then((response) => { resolve(response) });\n })\n }",
"async getPhenotypes({ state, commit }) {\n let qs = queryString.stringify(\n { q: state.host.subDomain || \"md\" },\n { skipNull: true }\n );\n let json = await fetch(\n `${BIO_INDEX_HOST}/api/portal/phenotypes?${qs}`\n ).then(resp => resp.json());\n\n // set the list of phenotypes\n commit(\"setPhenotypes\", json.data);\n }",
"function fetchLanguageInfo(submissions) {\n const languageArr = [];\n\n submissions.reduce((promise, submission) => {\n const {id, country} = submission\n return promise.then((result) => {\n return doSyncCall(id, country).then(val => {\n languageArr.push(val);\n });\n });\n }, Promise.resolve()).then(() => { // TODDO: Optimize with promise.all/race\n //console.log(\"Final Language Array: \", languageArr);\n appendLangToDOM(languageArr);\n });\n }",
"getElections({commit}, data) {\n commit('setElectionsLoadStatus', 1);\n\n ElectionAPI.getElections(\n data.url\n )\n .then( function(response) {\n commit('setElections', response.data.data);\n commit('setElectionsLoadStatus', 2);\n commit('setElPagination', {\n meta: response.data.meta,\n links: response.data.links\n });\n })\n .catch( function() {\n commit('setElections', []);\n commit('setElectionsLoadStatus', 3);\n });\n }",
"function getIds(){\n let url = 'services/getIdsService.php';\n fetchFromJson(url)\n .then(processAnswer)\n .then(updateIds, errorIds);\n}",
"async getServiceOfferings(serviceLine) {\n try {\n this.$router.push('/ServiceLine')\n this.$store.commit('clearServiceOfferings'); \n this.$store.commit('addBreadcrumb', {\n index: 1, \n link: {\n 'text': serviceLine,\n 'disabled': false,\n 'to': 'ServiceLine'\n }\n });\n const res = await axios.get(`https://sharepoint.mcipac.usmc.mil/g6/internal/csb/_api/web/lists/getByTitle('Service Catalog')/items?$filter=Title eq '${serviceLine}'`)\n const data = res.data.d.results;\n console.log(data);\n for (let key in data) {\n const offering = data[key];\n this.$store.commit('addOffering', offering);\n }\n } catch (error) {\n console.log(error);\n }\n }",
"getBoughtTracks () {\n return music.getBoughtTracks().then((response) => {\n return response.data\n })\n }",
"function scrapeStatus() {\n return new Promise((resolve, reject) => {\n request(mtaStatusUrl, (err, response, responseHtml) => {\n if (err) {\n reject(err);\n }\n\n const $ = cheerio.load(responseHtml);\n\n let results = {\n subway: []\n };\n\n $('#subwayDiv').find('tr').each((index, row) => {\n // First row is irrelevant.\n if (index !== 0) {\n\n results.subway.push({\n name: $(row).find('img').attr('alt').replace(/subway|\\s/ig, ''),\n status: $(row).find('span[class^=\"subway_\"]').text(),\n });\n }\n });\n\n // Write to the local cache.\n fs.writeFile(__dirname + cachedData, JSON.stringify(results), (err) => {\n // @todo: handle error\n });\n\n resolve(results);\n });\n });\n}",
"function getSongs() {\n fetch(songsURL)\n .then((response) => response.json())\n .then((songs) => songs.forEach((song) => renderSong(song)));\n}",
"getUpcoming({commit},data) {\n commit('setElectionsLoadStatus', 1);\n\n ElectionAPI.getUpcoming(\n data.url\n )\n .then( function(response) {\n commit('setElections', response.data.data);\n commit('setElectionsLoadStatus', 2);\n commit('setElPagination', {\n meta: response.data.meta,\n links: response.data.links\n });\n })\n .catch( function() {\n commit('setElections', []);\n commit('setElectionsLoadStatus', 3);\n });\n }",
"function loadTrackstatusData() {\n var path = [{ url: 'project/trackStatus/trackStatusData.json', method: \"GET\" }];\n PPSTService.getJSONData(path).then(function (response) {\n $scope.statusListData = response[0].data; // data for track status\n //$scope.loaderFlag = false;\n trackStatusService.dataChange();\n //trackStatusService.getChange();\n }).catch(function (err) {\n console.error(\"error fecthing tracj status data\");\n });\n }",
"getOngoing({commit}, data) {\n commit('setElectionsLoadStatus', 1);\n\n ElectionAPI.getOngoing(\n data.url\n )\n .then( function(response) {\n commit('setElections', response.data.data);\n commit('setElectionsLoadStatus', 2);\n commit('setElPagination', {\n meta: response.data.meta,\n links: response.data.links\n });\n })\n .catch( function() {\n commit('setElections', []);\n commit('setElectionsLoadStatus', 3);\n });\n }",
"function getVr() {\n fetch(url)\n .then(response => response.json())\n // .then(response => response.filter(value => value.trainCategory == \"Commuter\" || value.trainCategory == \"Long-distance\"))\n .then(response => response.filter(value => value.trainCategory !== \"Shunting\"))\n .then(response => response.filter(value => value.trainCategory !== \"Cargo\"))\n .then(response => response.sort((a, b) =>\n new Date(b.timeTableRows[findCurrentStation(b)].scheduledTime) - new Date(a.timeTableRows[findCurrentStation(a)].scheduledTime)))\n .then(response => renderData(response))\n .catch(error => console.log(error));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attempt to add player disk to Ith grid column | add(I, player) {
let empty = this.slice((i, j) => i == I).filter(cell => !cell.val);
if (empty.length) {
// Disk falls to the bottom-most available grid cell
let move = empty[empty.length-1];
// Add the player's disk and drop it into the grid
move.drop(player);
return move;
}
// If no available cells
else return false;
} | [
"function moveDisk(evt) {\n let clickedTower = evt.currentTarget;\n \n if (currentMode === \"pickUp\") {\n diskSelected = clickedTower.lastElementChild;\n diskSelected.style = \"border: 3px solid gold\";\n currentMode = \"putDown\"\n } else if (currentMode === \"putDown\") {\n if (!clickedTower.lastElementChild) {\n clickedTower.appendChild(diskSelected);\n diskSelected.style = \"border: 1px solid black\";\n currentMode = \"pickUp\"\n } else if (diskSelected.dataset.width < clickedTower.lastElementChild.dataset.width) { \n clickedTower.appendChild(diskSelected)\n diskSelected.style = \"border: 1px solid black\";\n currentMode = \"pickUp\"\n } else {\n alert(\"No disk may be placed on top of a smaller disk!\")\n diskSelected.style = \"border: 1px solid black\";\n currentMode = \"pickUp\"\n }\n }\n \n if (towerEnd.childElementCount === 4) {\n alert(\"Winner!!!\");\n reset() /* refresh page to play again*/\n }\n }",
"function addSpecialVoldemorts(index){\n cells[voldemorts[index].position].classList.add('special-ghost')\n }",
"draw() {\n push();\n translate(GSIZE / 2, GSIZE / 2);\n // Ordered drawing allows for the disks to appear to fall behind the grid borders\n this.el_list.forEach(cell => cell.drawDisk());\n this.el_list.forEach(cell => cell.drawBorder());\n this.el_list.filter(cell => cell.highlight)\n .forEach(cell => cell.drawHighlight());\n pop();\n }",
"update_disk(disk, t1, t2) {\n\t\tt1.arrDisk.pop() //pop the disk out of the fromTower\n\t\tt2.arrDisk.push(disk) //push the disk being moved into the toTower\n\t}",
"function addHarry(){\n cells[harryPosition].classList.add(harryClass)\n }",
"function moveDisk(height, fp, tp) {\n console.log(\"moving disk \" + height + \" from pole \" + fp + \" to pole \" + tp);\n}",
"initFiguresOnMatrix(player){\n\t\tObject.values(player.figureList).forEach(type => {\n\t\t\ttype.forEach(figure => {\n\t\t\t\tlet tile = this.boardMatrix[figure.positionY][figure.positionX];\n\t\t\t\ttile.sprite = this.add.sprite(tile.x, tile.y, figure.asset)\n\t\t\t\ttile.figure = figure;\n\t\t\t})\n\t\t})\n\t}",
"function triggerCol(col) {\n col = floor(col);\n\n for (let r = 0; r < rows; r++) {\n if (grid[r][col]) {\n chirps[r][currentBank].play();\n }\n }\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}",
"function gridify() {\n let numDivision = ceil(Math.sqrt(obj.numOfMols));\n let spacing = (width - obj.maxMolSize) / numDivision;\n\n molecules.forEach((molecule, index) => {\n\n let colPos = (index % numDivision) * spacing;\n let rowPos = floor(index / numDivision) * spacing;\n //console.log(`The col pos ${colPos} and the row pos ${rowPos}`);\n molecule.position.x = colPos + obj.maxMolSize;\n molecule.position.y = rowPos + obj.maxMolSize;\n\n });\n}",
"addNewRow(){\n this.canvas.unshift([1,1,0,0,0,0,0,0,0,0,0,0,1,1]);\n }",
"function addTurnToArch(player, cell_coord){\n let cellCol = cell_coord[0];\n let cellRow = cell_coord[1];\n gameStageArch[cellRow][cellCol] = player;\n // console.clear(); // for debugging\n // console.log(winComb); // show win combinations\n // console.table(gameStageArch); // show game arr\n}",
"function toggleSnakeCell(x, y) {\n cellDiv(x, y).toggleClass('snake');\n}",
"function drawSnakeStart() {\n var gridCenter = Math.floor((TOTALBOXES / 2) - COLS / 2 );\n\n $(\"#grid\").find(\"#\" + gridCenter).addClass(\"snakeHead\");\n snakePos.push(gridCenter);\n}",
"drawToolRow() {\n let $Div = $('<div />').attr({ id: 'top-row'});\n let $MineCount = $('<input/>').attr({ type: 'text', id: 'mine-count', name: 'mine-count', readonly: true}).val(25);\n let $Timer = $('<input/>').attr({ type: 'text', id: 'timer', name: 'timer', readonly: true}).val('0000');\n let $GridSize = $('<input/>').attr({ type: 'text', id: 'grid-size', name: 'grid-size'}).val(15); // value is the size of the grid. Always a square\n let $Reset = $('<input />').attr({ type: 'button', id: 'reset-button'}).val('Reset').addClass('reset-button');\n let $Music= $('<input />').attr({ type: 'button', id: 'music-button'}).val('Music').addClass('music-button');\n let $gameScreen = $('#game-screen');\n\n $Div.append($MineCount).append($Timer).append($GridSize).append($Reset).append($Music);\n $gameScreen.prepend($Div);\n \n }",
"function dragFixup(e, ui, col, row) {\n\n var targetId = idFromLocation(col, row);\n var targetX = parseInt($('#'+targetId).attr('data-col'));\n var targetY = parseInt($('#'+targetId).attr('data-row'));\n var targetSizeX = parseInt($('#'+targetId).attr('data-sizex'));\n var targetSizeY = parseInt($('#'+targetId).attr('data-sizey'));\n var targetGrid = $('#'+targetId);\n var startGrid = $('#'+dragStartId);\n if(targetId == dragStartId) {\n // startGrid.offset({\n // top: dragStartOffset.top\n // });\n // setTimeout(function(){\n // startGrid.offset({\n // left: dragStartOffset.left\n // });\n // },500);\n // startGrid.removeClass('player');\n \n } else {\n var startOffset = startGrid.offset();\n var targetOffset = targetGrid.offset();\n startGrid.attr({\n 'data-col': targetGrid.attr('data-col'),\n 'data-row': targetGrid.attr('data-row'),\n 'data-sizex': targetGrid.attr('data-sizex'),\n 'data-sizey': targetGrid.attr('data-sizey')\n });\n startGrid.offset({\n top: targetOffset.top,\n left: targetOffset.left\n });\n targetGrid.attr({\n 'data-col': dragStartX,\n 'data-row': dragStartY,\n 'data-sizex': dragStartSizeX,\n 'data-sizey': dragStartSizeY\n });\n setTimeout(function(){\n targetGrid.offset({\n top: dragStartOffset.top,\n left: dragStartOffset.left\n });\n }, 200);\n \n }\n }",
"function cellClicked(cell) {\n if (gameOver == false && cell.innerText == \"\") {\n // decrease # of empty cells by 1\n empty--;\n\n /* set content according to players mark and changes current player. In the end tells weather there is a winner or not */\n cell.innerHTML = player;\n checkWin();\n player = (player === \"X\") ? \"O\" : \"X\";\n document.getElementById(\"player\").innerHTML = player;\n }\n}",
"function newSnakeCell() {\n\t\t\t\tswitch (Events.data.snakeDirection) {\n\t\t\t\t\tcase 'right':\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tx: $scope.snakeHeadPosition.x + $scope.options.cellWidth + $scope.options.cellMargin,\n\t\t\t\t\t\t\ty: $scope.snakeHeadPosition.y\n\t\t\t\t\t\t};\n\t\t\t\t\tcase 'left':\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tx: $scope.snakeHeadPosition.x - $scope.options.cellWidth - $scope.options.cellMargin,\n\t\t\t\t\t\t\ty: $scope.snakeHeadPosition.y\n\t\t\t\t\t\t};\n\t\t\t\t\tcase 'up':\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tx: $scope.snakeHeadPosition.x,\n\t\t\t\t\t\t\ty: $scope.snakeHeadPosition.y - $scope.options.cellHeight - $scope.options.cellMargin\n\t\t\t\t\t\t};\n\t\t\t\t\tcase 'down':\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tx: $scope.snakeHeadPosition.x,\n\t\t\t\t\t\t\ty: $scope.snakeHeadPosition.y + $scope.options.cellHeight + $scope.options.cellMargin\n\t\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}",
"function addColumn(event) {\n rowColumns[currentRow] = rowColumns[currentRow] + 1;\n event.column = rowColumns[currentRow];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
inheritaning from super class vehicle | function Car(vehicletype,name,model,type){ //
Vehicle.call(this, vehicletype)
if(typeof(vehicletype) == typeof("")){
this.vehicletype = vehicletype;
}
else{
this.vehicletype = "Car";
}
if(typeof(name) == typeof("")){
this.name = name;
}
else{
this.name = "General";
}
if(typeof(model) == typeof("")){
this.model = model;
}
else{
this.model = "GM";
}
this.type = type;
if(this.name === "Porshe" || this.name === "Koenigsegg"){
this.numOfDoors = 2;
}
else{
this.numOfDoors = 4;
}
this.speed = "0 km/h";
this.drive = function(number){
this.gear = number;
if(this.name === "Porshe")
this.speed = "250 km/h";
if(this.name === "MAN")
this.speed ="77 km/h";
return this;
}
if(this.type === "trailer"){
this.numOfWheels = 8;
this.isSaloon = false;
}
else{
this.numOfWheels = 4;
this.isSaloon = true;
}
} | [
"function Price(color, make, model, price){\n // this is how I can inherit the properties of Car\n Car.call(this,color, make, model)\n\n this.price = price\n // return `car color ${this.color}, model ${this.model}, maker ${this.make} and price is $${price}`\n}",
"function TruckFactory() {\n TruckFactory.prototype = new VehicleFactory();\n TruckFactory.vehicleClass = Truck;\n}",
"function Motorcycle(make,model,year) {\n //using call\n Car.call(this,make,model,year)\n this.numWheels = 2;\n}",
"function Truck( options) {\n\n this.state = options.state || \"used\";\n this.wheelSize = options.wheelSize || \"large\";\n this.color = options.color || \"blue\";\n\n //NOT defined in prototype\n this.drive = function() {\n console.log(\"truck drive\");\n }\n\n this.breakDown = function() {\n console.log(\"truck breakdown\");\n }\n}",
"constructor() {\n //name of the Smart Contract => registration\n super(\"org.pharma-network.drugRegistration\");\n }",
"function driveIt(vehicle) {\n vehicle.start();\n racetrack.push(vehicle);\n}",
"function Toyota() {\n Object.assign(this, Car.call(this, arguments));\n // Car.call(this, arguments); // This way doesn't work here because Car superclass doesn't implement `this` keyword in fucntion.\n}",
"function getBaseArmourClass(agilityModifier){\n\tvar armourClass = 10;\n\tbaseArmourClass = armourClass + agilityModifier;\n\treturn baseArmourClass;\n}",
"function PvrModel( parentModel ) {\n SubModel.call( this, parentModel, PvrModelDefines );\n\n // --------------------------------------------------------------\n // Objects\n // -------------------------------------------------------------- \n// Need to fix\n//\tPvrModelDefines.SL2_TVAPI_ACTION_PVR_SPEED_TEST= \"tvapi.action.pvr.speed.test \"\n\n // SpeedTest\n this.registerActionObject(\n PvrModelDefines.SL2_TVAPI_ACTION_PVR_SPEED_TEST,\n\t\t\t [\n\t\t\t \t{name:\"SpeedTest\",method:function(object, path){\n\t\t\t \t\treturn object.invoke(path);\n\t\t\t \t\t}}\n ],\"getPvrSpeed\"\n\t\t\t );\n\n// Need to fix\n//\tPvrModelDefines.SL2_TVAPI_ACTION_PVR_PAR_INFO= \"tvapi.action.pvr.par.info \"\n\n // ParInfo\n this.registerActionObject(\n PvrModelDefines.SL2_TVAPI_ACTION_PVR_PAR_INFO,\n\t\t\t [\n\t\t\t \t{name:\"ParInfo\",method:function(object){\n\t\t\t \t\treturn object.invoke();\n\t\t\t \t\t}}\n ],\"getPvrParInfo\"\n\t\t\t );\n\n// Need to fix\n//\tPvrModelDefines.SL2_TVAPI_ACTION_PVR_START_RECORD= \"tvapi.action.pvr.start.record \"\n\n // StartRecord\n this.registerActionObject(\n PvrModelDefines.SL2_TVAPI_ACTION_PVR_START_RECORD,\n\t\t\t [\n\t\t\t \t{name:\"StartRecord\",method:function(object){\n\t\t\t \t\treturn object.invoke();\n\t\t\t \t\t}}\n ],\"getStartRecordInfo\"\n\t\t\t );\n\n// Need to fix\n//\tPvrModelDefines.SL2_TVAPI_ACTION_PVR_STOP_RECORD= \"tvapi.action.pvr.stop.record \"\n\n // StopRecord\n this.registerActionObject(\n PvrModelDefines.SL2_TVAPI_ACTION_PVR_STOP_RECORD,\n\t\t\t [\n\t\t\t \t{name:\"StopRecord\",method:function(object){\n\t\t\t \t\treturn object.invoke();\n\t\t\t \t\t}}\n ],\"StopRecordCallBack\"\n\t\t\t );\n\n // LeadTime\n this.registerIntegerObject(\n PvrModelDefines.SL2_TVAPI_I32_PVR_LEAD_TIME,\n \"getLeadTime\", \"setLeadTime\", \"onLeadTimeChaged\",\n null, null );\n\n // TrailingTime\n this.registerIntegerObject(\n PvrModelDefines.SL2_TVAPI_I32_PVR_TRAILING_TIME,\n \"getTrailingTime\", \"setTrailingTime\", \"onTrailingTimeChaged\",\n null, null );\n\n // RecordState\n this.registerIntegerObject(\n PvrModelDefines.SL2_TVAPI_I32_PVR_RECORD_STATE,\n \"getRecordState\", \"setRecordState\", \"onRecordStateChaged\",\n null, null );\n\n // ParAvailable\n this.registerIntegerObject(\n PvrModelDefines.SL2_TVAPI_I32_PVR_PAR_AVAILABLE,\n \"getParAvailable\", \"setParAvailable\", \"onParAvailableChaged\",\n null, null );\n\n // StationUuid\n this.registerStringObject(\n PvrModelDefines.SL2_TVAPI_STR_PVR_STATION_UUID,\n \"getStationUuid\", \"setStationUuid\", \"onStationUuidChaged\",\n null, null );\n\n // MainIsArchiveRecording\n this.registerIntegerObject(\n PvrModelDefines.SL2_TVAPI_I32_PVR_MAIN_IS_ARCHIVE_RECORDING,\n \"getMainIsArchiveRecording\", \"setMainIsArchiveRecording\", \"onMainIsArchiveRecordingChaged\",\n null, null );\n\n // ScheduleItem\n this.registerStringVectorObject(\n PvrModelDefines.SL2_TVAPI_VSTR_PVR_SCHEDULE_ITEM,\n \"getScheduleItem\", \"setScheduleItem\", \"onScheduleItemChaged\",\n null, null );\n\n // FreeMemThreshold\n this.registerIntegerObject(\n PvrModelDefines.SL2_TVAPI_I32_PVR_FREE_MEM_THRESHOLD,\n \"getFreeMemThreshold\", \"setFreeMemThreshold\", \"onFreeMemThresholdChaged\", \n null, null );\n\n // SignalState\n this.registerIntegerObject(\n PvrModelDefines.SL2_TVAPI_I32_PVR_SIGNAL_STATE,\n \"getSignalState\", \"setSignalState\", \"onSignalStateChaged\", \n null, null );\n\n\n}",
"constructor(brain) {\n // All the physics stuff\n this.fx = 0;\n this.vx = 0;\n this.x = random(width);\n this.r = 8;\n this.y = height - this.r * 2;\n\n // This indicates how well it is doing\n this.score = 0;\n\n // How many sensors does each vehicle have?\n // How far can each vehicle see?\n // What's the angle in between sensors\n\n // Create an array of sensors\n this.sensors = [];\n const deltaAngle = PI / TOTALSENSORS;\n for (let angle = PI; angle <= TWO_PI; angle += deltaAngle) {\n this.sensors.push(new Sensor(angle, deltaAngle));\n }\n\n // If a brain is passed via constructor copy it\n if (brain) {\n this.brain = brain.copy();\n this.brain.mutate(0.1);\n // Otherwise make a new brain\n } else {\n // inputs are all the sensors plus position and velocity info\n let inputs = this.sensors.length + 2;\n this.brain = new NeuralNetwork(inputs, inputs, 1);\n }\n }",
"dropVehicle()\n\t{\n\t\t// While the crane is not in position, update the car height\n\t\tif(this.rotateAngle < (210 * degToRad))\n\t\t\tthis.heightCar = -12*Math.sin(this.downArmAngle)-10*Math.sin(this.topArmAngle)-4.35;\n\t\telse {\n\t\t\t// When the crane is in position, decrease the car height until it touches the ground\n\t\t\tif (this.heightCar > 0)\n\t\t\t\tthis.heightCar -= 0.5;\n\t\t\telse {\n\t\t\t\t// Release the car\n\t\t\t\tthis.vehicleStuck = false;\n\t\t\t\tthis.vehicle.position[1] = 0;\n\t\t\t\tthis.vehicle.position[2] = 12*Math.cos(this.downArmAngle)+10*Math.cos(this.topArmAngle);\n\t\t\t\tthis.vehicle.position[0] = Math.sin(this.rotateAngle);\n this.lastTime = 0;\n this.position = 'D';\n }\n\t\t}\n\t}",
"constructor() {\n super();\n this.__avaliable = true;\n this.__instanceID = Ubject.__nextInstanceID++;\n this._uuid = Graphic_1.GL.Math.generateUUID();\n Ubject.__ubjects[this._uuid] = this;\n }",
"function VirtualElement(type, tag, data, children) {\n this.type = type;\n this.tag = tag;\n this.data = data;\n this.children = children;\n }",
"enterInheritanceModifier(ctx) {\n\t}",
"inherit(property) {\n }",
"constructor(id, name, price, wheels, doors, hasAc, owner, academy) {\n super(id, name, price, wheels, doors, hasAc);\n // setting value in constructor to private field (not recomended to set value send from outside to private field)\n // if(academy) this.#academy = academy;\n this._owner = owner;\n }",
"function VRExperienceHelper(scene,/** Options to modify the vr experience helper's behavior. */webVROptions){if(webVROptions===void 0){webVROptions={};}var _this=this;this.webVROptions=webVROptions;// Can the system support WebVR, even if a headset isn't plugged in?\nthis._webVRsupported=false;// If WebVR is supported, is a headset plugged in and are we ready to present?\nthis._webVRready=false;// Are we waiting for the requestPresent callback to complete?\nthis._webVRrequesting=false;// Are we presenting to the headset right now? (this is the vrDevice state)\nthis._webVRpresenting=false;// Are we presenting in the fullscreen fallback?\nthis._fullscreenVRpresenting=false;/**\n * Observable raised when entering VR.\n */this.onEnteringVRObservable=new BABYLON.Observable();/**\n * Observable raised when exiting VR.\n */this.onExitingVRObservable=new BABYLON.Observable();/**\n * Observable raised when controller mesh is loaded.\n */this.onControllerMeshLoadedObservable=new BABYLON.Observable();this._useCustomVRButton=false;this._teleportationRequested=false;this._teleportActive=false;this._floorMeshesCollection=[];this._rotationAllowed=true;this._teleportBackwardsVector=new BABYLON.Vector3(0,-1,-1);this._isDefaultTeleportationTarget=true;this._teleportationFillColor=\"#444444\";this._teleportationBorderColor=\"#FFFFFF\";this._rotationAngle=0;this._haloCenter=new BABYLON.Vector3(0,0,0);this._padSensibilityUp=0.65;this._padSensibilityDown=0.35;this._leftController=null;this._rightController=null;/**\n * Observable raised when a new mesh is selected based on meshSelectionPredicate\n */this.onNewMeshSelected=new BABYLON.Observable();/**\n * Observable raised when a new mesh is picked based on meshSelectionPredicate\n */this.onNewMeshPicked=new BABYLON.Observable();/**\n * Observable raised before camera teleportation\n */this.onBeforeCameraTeleport=new BABYLON.Observable();/**\n * Observable raised after camera teleportation\n */this.onAfterCameraTeleport=new BABYLON.Observable();/**\n * Observable raised when current selected mesh gets unselected\n */this.onSelectedMeshUnselected=new BABYLON.Observable();/**\n * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.\n */this.teleportationEnabled=true;this._teleportationInitialized=false;this._interactionsEnabled=false;this._interactionsRequested=false;this._displayGaze=true;this._displayLaserPointer=true;/**\n * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes\n */this.updateGazeTrackerScale=true;this._onResize=function(){_this.moveButtonToBottomRight();if(_this._fullscreenVRpresenting&&_this._webVRready){_this.exitVR();}};this._onFullscreenChange=function(){if(document.fullscreen!==undefined){_this._fullscreenVRpresenting=document.fullscreen;}else if(document.mozFullScreen!==undefined){_this._fullscreenVRpresenting=document.mozFullScreen;}else if(document.webkitIsFullScreen!==undefined){_this._fullscreenVRpresenting=document.webkitIsFullScreen;}else if(document.msIsFullScreen!==undefined){_this._fullscreenVRpresenting=document.msIsFullScreen;}else if(document.msFullscreenElement!==undefined){_this._fullscreenVRpresenting=document.msFullscreenElement;}if(!_this._fullscreenVRpresenting&&_this._canvas){_this.exitVR();if(!_this._useCustomVRButton){_this._btnVR.style.top=_this._canvas.offsetTop+_this._canvas.offsetHeight-70+\"px\";_this._btnVR.style.left=_this._canvas.offsetLeft+_this._canvas.offsetWidth-100+\"px\";}}};this.beforeRender=function(){if(_this._leftController&&_this._leftController._activePointer){_this._castRayAndSelectObject(_this._leftController);}if(_this._rightController&&_this._rightController._activePointer){_this._castRayAndSelectObject(_this._rightController);}if(_this._noControllerIsActive){_this._castRayAndSelectObject(_this._cameraGazer);}else{_this._cameraGazer._gazeTracker.isVisible=false;}};this._onNewGamepadConnected=function(gamepad){if(gamepad.type!==BABYLON.Gamepad.POSE_ENABLED){if(gamepad.leftStick){gamepad.onleftstickchanged(function(stickValues){if(_this._teleportationInitialized&&_this.teleportationEnabled){// Listening to classic/xbox gamepad only if no VR controller is active\nif(!_this._leftController&&!_this._rightController||_this._leftController&&!_this._leftController._activePointer&&_this._rightController&&!_this._rightController._activePointer){_this._checkTeleportWithRay(stickValues,_this._cameraGazer);_this._checkTeleportBackwards(stickValues,_this._cameraGazer);}}});}if(gamepad.rightStick){gamepad.onrightstickchanged(function(stickValues){if(_this._teleportationInitialized){_this._checkRotate(stickValues,_this._cameraGazer);}});}if(gamepad.type===BABYLON.Gamepad.XBOX){gamepad.onbuttondown(function(buttonPressed){if(_this._interactionsEnabled&&buttonPressed===BABYLON.Xbox360Button.A){_this._cameraGazer._selectionPointerDown();}});gamepad.onbuttonup(function(buttonPressed){if(_this._interactionsEnabled&&buttonPressed===BABYLON.Xbox360Button.A){_this._cameraGazer._selectionPointerUp();}});}}else{var webVRController=gamepad;var controller=new VRExperienceHelperControllerGazer(webVRController,_this._scene,_this._cameraGazer._gazeTracker);if(webVRController.hand===\"right\"||_this._leftController&&_this._leftController.webVRController!=webVRController){_this._rightController=controller;}else{_this._leftController=controller;}_this._tryEnableInteractionOnController(controller);}};// This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded\nthis._tryEnableInteractionOnController=function(controller){if(_this._interactionsRequested&&!controller._interactionsEnabled){_this._enableInteractionOnController(controller);}if(_this._teleportationRequested&&!controller._teleportationEnabled){_this._enableTeleportationOnController(controller);}};this._onNewGamepadDisconnected=function(gamepad){if(gamepad instanceof BABYLON.WebVRController){if(gamepad.hand===\"left\"&&_this._leftController!=null){_this._leftController.dispose();_this._leftController=null;}if(gamepad.hand===\"right\"&&_this._rightController!=null){_this._rightController.dispose();_this._rightController=null;}}};this._workingVector=BABYLON.Vector3.Zero();this._workingQuaternion=BABYLON.Quaternion.Identity();this._workingMatrix=BABYLON.Matrix.Identity();this._scene=scene;this._canvas=scene.getEngine().getRenderingCanvas();// Parse options\nif(webVROptions.createFallbackVRDeviceOrientationFreeCamera===undefined){webVROptions.createFallbackVRDeviceOrientationFreeCamera=true;}if(webVROptions.createDeviceOrientationCamera===undefined){webVROptions.createDeviceOrientationCamera=true;}if(webVROptions.laserToggle===undefined){webVROptions.laserToggle=true;}if(webVROptions.defaultHeight===undefined){webVROptions.defaultHeight=1.7;}if(webVROptions.useCustomVRButton){this._useCustomVRButton=true;if(webVROptions.customVRButton){this._btnVR=webVROptions.customVRButton;}}if(webVROptions.rayLength){this._rayLength=webVROptions.rayLength;}this._defaultHeight=webVROptions.defaultHeight;if(webVROptions.positionScale){this._rayLength*=webVROptions.positionScale;this._defaultHeight*=webVROptions.positionScale;}this._hasEnteredVR=false;// Set position\nif(this._scene.activeCamera){this._position=this._scene.activeCamera.position.clone();}else{this._position=new BABYLON.Vector3(0,this._defaultHeight,0);}// Set non-vr camera\nif(webVROptions.createDeviceOrientationCamera||!this._scene.activeCamera){this._deviceOrientationCamera=new BABYLON.DeviceOrientationCamera(\"deviceOrientationVRHelper\",this._position.clone(),scene);// Copy data from existing camera\nif(this._scene.activeCamera){this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ;this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ;// Set rotation from previous camera\nif(this._scene.activeCamera instanceof BABYLON.TargetCamera&&this._scene.activeCamera.rotation){var targetCamera=this._scene.activeCamera;if(targetCamera.rotationQuaternion){this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);}else{this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y,targetCamera.rotation.x,targetCamera.rotation.z));}this._deviceOrientationCamera.rotation=targetCamera.rotation.clone();}}this._scene.activeCamera=this._deviceOrientationCamera;if(this._canvas){this._scene.activeCamera.attachControl(this._canvas);}}else{this._existingCamera=this._scene.activeCamera;}// Create VR cameras\nif(webVROptions.createFallbackVRDeviceOrientationFreeCamera){this._vrDeviceOrientationCamera=new BABYLON.VRDeviceOrientationFreeCamera(\"VRDeviceOrientationVRHelper\",this._position,this._scene);}this._webVRCamera=new BABYLON.WebVRFreeCamera(\"WebVRHelper\",this._position,this._scene,webVROptions);this._webVRCamera.useStandingMatrix();this._cameraGazer=new VRExperienceHelperCameraGazer(function(){return _this.currentVRCamera;},scene);// Create default button\nif(!this._useCustomVRButton){this._btnVR=document.createElement(\"BUTTON\");this._btnVR.className=\"babylonVRicon\";this._btnVR.id=\"babylonVRiconbtn\";this._btnVR.title=\"Click to switch to VR\";var css=\".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }\";css+=\".babylonVRicon.vrdisplaypresenting { display: none; }\";// TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)\n// css += \".babylonVRicon.vrdisplaysupported { }\";\n// css += \".babylonVRicon.vrdisplayready { }\";\n// css += \".babylonVRicon.vrdisplayrequesting { }\";\nvar style=document.createElement('style');style.appendChild(document.createTextNode(css));document.getElementsByTagName('head')[0].appendChild(style);this.moveButtonToBottomRight();}// VR button click event\nif(this._btnVR){this._btnVR.addEventListener(\"click\",function(){if(!_this.isInVRMode){_this.enterVR();}else{_this.exitVR();}});}// Window events\nwindow.addEventListener(\"resize\",this._onResize);document.addEventListener(\"fullscreenchange\",this._onFullscreenChange,false);document.addEventListener(\"mozfullscreenchange\",this._onFullscreenChange,false);document.addEventListener(\"webkitfullscreenchange\",this._onFullscreenChange,false);document.addEventListener(\"msfullscreenchange\",this._onFullscreenChange,false);document.onmsfullscreenchange=this._onFullscreenChange;// Display vr button when headset is connected\nif(webVROptions.createFallbackVRDeviceOrientationFreeCamera){this.displayVRButton();}else{this._scene.getEngine().onVRDisplayChangedObservable.add(function(e){if(e.vrDisplay){_this.displayVRButton();}});}// Exiting VR mode using 'ESC' key on desktop\nthis._onKeyDown=function(event){if(event.keyCode===27&&_this.isInVRMode){_this.exitVR();}};document.addEventListener(\"keydown\",this._onKeyDown);// Exiting VR mode double tapping the touch screen\nthis._scene.onPrePointerObservable.add(function(pointerInfo,eventState){if(_this.isInVRMode){_this.exitVR();if(_this._fullscreenVRpresenting){_this._scene.getEngine().switchFullscreen(true);}}},BABYLON.PointerEventTypes.POINTERDOUBLETAP,false);// Listen for WebVR display changes\nthis._onVRDisplayChanged=function(eventArgs){return _this.onVRDisplayChanged(eventArgs);};this._onVrDisplayPresentChange=function(){return _this.onVrDisplayPresentChange();};this._onVRRequestPresentStart=function(){_this._webVRrequesting=true;_this.updateButtonVisibility();};this._onVRRequestPresentComplete=function(success){_this._webVRrequesting=false;_this.updateButtonVisibility();};scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);window.addEventListener('vrdisplaypresentchange',this._onVrDisplayPresentChange);scene.onDisposeObservable.add(function(){_this.dispose();});// Gamepad connection events\nthis._webVRCamera.onControllerMeshLoadedObservable.add(function(webVRController){return _this._onDefaultMeshLoaded(webVRController);});this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);this.updateButtonVisibility();//create easing functions\nthis._circleEase=new BABYLON.CircleEase();this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);if(this.webVROptions.floorMeshes){this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes});}}",
"function ParentThirdPartyClass() {}",
"function AbbeDielectric(name, iorVal, abbe) \n{\n Dielectric.call(this, name);\n this.iorVal = iorVal;\n this.abbe = abbe;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the text header to the header cell. | __textHeaderRenderer() {
this.__setTextContent(this._headerCell._content, this.header);
} | [
"_defaultHeaderRenderer() {\n if (!this.path) {\n return;\n }\n\n this.__setTextContent(this._headerCell._content, this._generateHeader(this.path));\n }",
"_renderHeaderCellContent(headerRenderer, headerCell) {\n if (!headerCell || !headerRenderer) {\n return;\n }\n\n this.__renderCellsContent(headerRenderer, [headerCell]);\n if (this._grid) {\n this._grid.__updateHeaderFooterRowVisibility(headerCell.parentElement);\n }\n }",
"paintHeaders(){\n var ret =[];\n let i=0;\n if(this.props.tableData.selectable){\n if(typeof this.props.selectAll==\"function\"){\n ret.push(<th style={{width:'1em'}} className={\"font-weight-light text-center align-middle\"} key={'select'} >\n <Input type=\"checkbox\" className=\"m-0 p-0\" value={this.state.check} onChange={this.checkAll} />\n </th>)\n }else{\n ret.push(<th style={{width:'1em'}} key={'select'}></th>)\n }\n }\n this.props.tableData.headers.headers.forEach(element => {\n if(this.isColumnVisible(i)){\n ret.push(<TableHeader\n key={element.key} \n header={element}\n leftShift={this.isLeftShift(i)} \n rightShift={this.isRightShift(i)}\n styleCorrector={this.props.styleCorrector}\n notImportantClasses={this.showUnImportantWhen}\n action={this.headerAction}\n headBackground={this.headBackground}\n loader={this.props.loader}\n changeCol={this.changeCol}\n />)\n }\n i++\n }\n );\n return ret;\n }",
"fillHeaderRow(headerRowNumber, rowData) {\n for (let [i, value] of rowData.entries()) {\n this.tableBodyNode.appendChild(this.createTableDiv('header ' + headerRowNumber, this.keys[i], value, 'string', this.columnFormats[i] + ' tableHeaderDiv'))\n }\n }",
"function _dayNoteHeaderRender(dayHeaderObj) {\r\n var date = dayHeaderObj[\"date\"];\r\n var $dayHeader = $(\"thead td[data-date=\"+date+\"]\");\r\n var dayNumber = $dayHeader.children().first().text();\r\n var html = \"<span class='fc-day-number day-number-of-header-note fright'>\" + dayNumber + \"</span>\" +\r\n \"<span class='fc-day-number fleft'><b>\" + dayHeaderObj[\"header_text\"] + \"</b></span>\"\r\n $dayHeader.html(html);\r\n }",
"function updateHeader(scope, control) {\n control.header = scope.header;\n if (typeof (scope.value) != 'undefined' && control.selectedItem && control.displayMemberPath) {\n var currentValue = control.selectedItem[control.displayMemberPath];\n if (currentValue != null) {\n control.header += ': <b>' + currentValue + '</b>';\n }\n }\n }",
"__getRowHeader () {\n\n var string = \" |\";\n var i;\n\n console.log(this.board);\n\n this.board.forEach(function (column, index) {\n string += \"-\" + index + \"-|\";\n });\n\n return string;\n }",
"formatHeader(column, title, el){\n\t\tvar formatter, params, onRendered, mockCell;\n\t\t\n\t\tif(column.definition.titleFormatter){\n\t\t\tformatter = this.getFormatter(column.definition.titleFormatter);\n\t\t\t\n\t\t\tonRendered = (callback) => {\n\t\t\t\tcolumn.titleFormatterRendered = callback;\n\t\t\t};\n\t\t\t\n\t\t\tmockCell = {\n\t\t\t\tgetValue:function(){\n\t\t\t\t\treturn title;\n\t\t\t\t},\n\t\t\t\tgetElement:function(){\n\t\t\t\t\treturn el;\n\t\t\t\t},\n\t\t\t\tgetType:function(){\n\t\t\t\t\treturn \"header\";\n\t\t\t\t},\n\t\t\t\tgetColumn:function(){\n\t\t\t\t\treturn column.getComponent();\n\t\t\t\t},\n\t\t\t\tgetTable:() => {\n\t\t\t\t\treturn this.table;\n\t\t\t\t}\n\t\t\t};\n\t\t\t\n\t\t\tparams = column.definition.titleFormatterParams || {};\n\t\t\t\n\t\t\tparams = typeof params === \"function\" ? params() : params;\n\t\t\t\n\t\t\treturn formatter.call(this, mockCell, params, onRendered);\n\t\t}else{\n\t\t\treturn title;\n\t\t}\n\t}",
"getTableHeading() {\n return (\n <Entries.Row isHeading={true}>\n { this.getCellLayouts() }\n </Entries.Row>\n );\n }",
"create_header() {\n // Removes children of thead element\n var thead = document.getElementById(\"table_thead\");\n while (thead.firstChild)\n thead.removeChild(thead.firstChild);\n\n // Creates array with date integers\n var headerArr = [\"Task\"];\n for (var i = 1; i <= this.num_days; i++) {\n if (i < 10)\n headerArr.push(\"0\" + i.toString());\n else\n headerArr.push(i);\n }\n var tr = element_maker.create_header_row(headerArr);\n thead.append(tr);\n }",
"function constructHeaderTbl() {\t\n\tprintHeadInnerTable = '<div class=\"page\"><table cellspacing=\"0\" class=\"printDeviceLogTable ContentTable\" style=\"font-size: 15px;height:45%;min-height:700px;max-height:780px;table-layout: fixed; width: 1100px;\" width=\"100%\">'\n\t\t+'<thead><tr><th rowspan=\"2\" width=\"50px\">Article</th>'\n\t\t+'<th rowspan=\"2\" width=\"5px\"></th>'\n\t\t+'<th rowspan=\"2\" class=\"columnDivider\">Description</th>'\n\t\t+'<th colspan=\"3\" class=\"centerValue columnDivider\">Last Received Details</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">OM</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">SOH</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"80px\">Units to Fill</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"100px\">LTO</th>'\n\t\t+'<th rowspan=\"2\" class=\"lastColumn leftValue\" width=\"140px\">Comment</th>'\n\t\t+'</tr><tr class=\"subHeader\">'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Date</th>'\n\t\t+'<th class=\"centerValue columnDivider\" width=\"50px\">Qty.</th>'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Order</th></tr></thead>';\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n}",
"[renderGroupHeading]() {\n\t\tconst self = this;\n\t\tconst doRenderCheckBox = !!self.columns().find((column) => column.type === COLUMN_TYPES.CHECKBOX);\n\n\t\tself[hideCells]();\n\n\t\tif (!self[GROUP_HEADING]) {\n\t\t\tself[GROUP_HEADING] = new Heading({\n\t\t\t\tcontainer: self,\n\t\t\t\twidth: HUNDRED_PERCENT,\n\t\t\t\tclasses: 'grid-group-header',\n\t\t\t\tisExpandable: true,\n\t\t\t\tshouldMainClickExpand: true,\n\t\t\t\tstopPropagation: true\n\t\t\t});\n\t\t}\n\n\t\tself[GROUP_HEADING]\n\t\t\t.isDisplayed(true)\n\t\t\t.data(self.rowData())\n\t\t\t.onExpand(self.onExpandCollapseGroup())\n\t\t\t.onSelect(self.onSelectGroup())\n\t\t\t.isExpanded(!self.rowData().isCollapsed)\n\t\t\t.showCheckbox(doRenderCheckBox)\n\t\t\t.isSelectable(doRenderCheckBox)\n\t\t\t.isSelected(self.isSelected())\n\t\t\t.isIndeterminate(self.isIndeterminate())\n\t\t\t.title(self.rowData().title)\n\t\t\t.subTitle(self.rowData().childCount + ' ' + (self.rowData().footerSuffix || 'items'))\n\t\t\t.image(self.rowData().image ? (self.rowData().image(self.rowData()) || '') : '')\n\t\t\t.buttons(self.rowData().buttons, true);\n\n\t\tdefer(() => self[GROUP_HEADING].resize());\n\t}",
"function constructHeaderTbl1() {\t\n\tprintHeadInnerTable = '<div class=\"page\"><table cellspacing=\"0\" class=\"printDeviceLogTable ContentTable\" style=\"font-size: 15px;height:45%;min-height:580px;max-height:580px;table-layout: fixed; width: 1100px;\" width=\"100%\">'\n\t\t+'<thead><tr><th rowspan=\"2\" width=\"50px\">Article</th>'\n\t\t+'<th rowspan=\"2\" width=\"5px\"></th>'\n\t\t+'<th rowspan=\"2\" class=\"columnDivider\">Description</th>'\n\t\t+'<th colspan=\"3\" class=\"centerValue columnDivider\">Last Received Details</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">OM</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">SOH</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"80px\">Units to Fill</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"100px\">LTO</th>'\n\t\t+'<th rowspan=\"2\" class=\"lastColumn leftValue\" width=\"140px\">Comment</th>'\n\t\t+'</tr><tr class=\"subHeader\">'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Date</th>'\n\t\t+'<th class=\"centerValue columnDivider\" width=\"50px\">Qty.</th>'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Order</th></tr></thead>';\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n}",
"generateHeader() {\n let res = []\n for (var i = 0; i < columnHeader.length; i++) {\n res.push(<th key={columnHeader[i]}>{columnHeader[i]}</th>)\n }\n return res;\n }",
"renderHeader(prop) {\n return (\n <th>\n <div>\n <label className=\"control-label\" style={{ margin: 0 }}>\n <span>{capitalizeWords(prop)}</span>\n </label>\n </div>\n </th>\n );\n }",
"handleHeading(){\n this.sliceString();\n this.post.value = this.beg + \"# \" + this.selection + this.end;\n }",
"function addTableTitle(tableNum, colSpan, innerText) {\r\n var table = document.getElementsByClassName(\"datadisplaytable\")[tableNum];\r\n\r\n var headRow = document.createElement(\"tr\");\r\n var headCell = document.createElement(\"td\");\r\n headCell.classList.add(\"tablehead\");\r\n headCell.colSpan = colSpan;\r\n headCell.innerHTML = innerText;\r\n headRow.appendChild(headCell);\r\n table.getElementsByTagName(\"tbody\")[0].insertBefore(headRow, table.getElementsByTagName(\"tr\")[0]);\r\n}",
"function drawEpisodesHeader() {\n let $header = $(\"<h2>\").text(episodes[0].Show_name + \" - Season \" + episodes[0].Season_num);\n let div = $(\"<div class='header'>\").append($header);\n $(\"#adminEpisodePH\").prepend(div);\n}",
"function addHeader(report) {\n var pageHeader = report.getHeader();\n pageHeader.addClass(\"header\");\n if (param.company) {\n pageHeader.addParagraph(param.company, \"heading\");\n }\n pageHeader.addParagraph(\"VAT Report Transactions currency to CHF\", \"heading\");\n pageHeader.addParagraph(Banana.Converter.toLocaleDateFormat(param.startDate) + \" - \" + Banana.Converter.toLocaleDateFormat(param.endDate), \"\");\n pageHeader.addParagraph(\" \", \"\");\n pageHeader.addParagraph(\" \", \"\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Restore the values of globals to undo the preceding pushGlobals() call. | function popGlobals() {
if (_globalsStack.length > 1) {
_globalsStack.pop();
}
_updateGlobals(G, _globalsStack[_globalsStack.length - 1]);
} | [
"function reInitializeGlobalVariable(){\n\t//empty all row in the designer area\n\t//$('#box-body').empty();\n\n\t//re-initialize the global values\t\n\t//delete gblEntityDesignJson[wrkTgtCollection];\n\tmstEntityDesignArr = [];\n\tselParentNodeArr = [];\n\twrkTgtCollection = '';\n}",
"set(name, value, global) {\n if (global === void 0) {\n global = false;\n }\n\n if (global) {\n // Global set is equivalent to setting in all groups. Simulate this\n // by destroying any undos currently scheduled for this name,\n // and adding an undo with the *new* value (in case it later gets\n // locally reset within this environment).\n for (let i = 0; i < this.undefStack.length; i++) {\n delete this.undefStack[i][name];\n }\n\n if (this.undefStack.length > 0) {\n this.undefStack[this.undefStack.length - 1][name] = value;\n }\n } else {\n // Undo this set at end of this group (possibly to `undefined`),\n // unless an undo is already in place, in which case that older\n // value is the correct one.\n const top = this.undefStack[this.undefStack.length - 1];\n\n if (top && !top.hasOwnProperty(name)) {\n top[name] = this.current[name];\n }\n }\n\n this.current[name] = value;\n }",
"function Globals() {\r\n\r\n\t/** @private */ var store = {};\r\n\t/** @private */ var count = 0;\r\n\t\r\n\t/**\r\n\t * Returns an array of all global variables names.\r\n\t * @public\r\n\t */\r\n\tthis.getValues = function() {\r\n\t\tvar result = new Array();\r\n\t\tfor (element in store) {\r\n\t\t\tif (store.hasOwnProperty(element)) {\r\n\t\t\t\tresult.push(store[element]);\r\n\t\t\t};\r\n\t\t};\r\n\t\treturn result;\r\n\t};\r\n\t\r\n\t/**\r\n\t * Returns the value of a global variable with the name.\r\n\t * @param {string} name Name of the global variable.\r\n\t * @public\r\n\t */\r\n\tthis.getValue = function(name) {\r\n\t\treturn store[name].value;\r\n\t};\r\n\t\r\n\t/**\r\n\t * Sets the value of a global variable with the name.\r\n\t * @param {string} name Name of the global variable.\r\n\t * @param {number} value Value of the global variable.\r\n\t * @public\r\n\t */\r\n\tthis.setValue = function(name, value) {\r\n\t\tif (store[name] == null) {\r\n\t\t\tstore[name] = {\r\n\t\t\t\taddress: (Const.ADDRESS_SPACE_SIZE + Const.GLOBALS_OFFSET_FROM_STACK + count++) * Const.ADDRESS_OFFSET,\r\n\t\t\t\tname: name,\r\n\t\t\t\tvalue: value\r\n\t\t\t};\r\n\t\t} else {\r\n\t\t\tstore[name].value = value;\r\n\t\t};\r\n\t};\r\n\t\r\n}",
"function saveState () {\n stack.splice(stackPointer);\n var cs = slots.slice(0);\n var ci =[];\n cs.forEach(function(s) {\n ci.push(s.slice(0));\n });\n stack[stackPointer] = [cs, ci];\n }",
"function resetGame() {\n // wipe these variables\n isInitialised = false;\n readySet = {};\n }",
"function resetRegisters () {\n for (var register in registers)\n registers[register] = 0;\n}",
"restore_stack(stuff){\n const v = stuff.stack;\n const s = v.length;\n for(var i=0; i<s; i++){\n this.stack[i] = v[i];\n }\n this.last_refer = stuff.last_refer;\n this.call_stack = [...stuff.call_stack];\n this.tco_counter = [...stuff.tco_counter];\n return s;\n }",
"function resetGraphVariables() {\n typeGroups = {};\n typeIndex = 0;\n\n currentGraph = {\n nodes: [],\n edges: []\n }\n labelGraph = {\n nodes: [],\n edges: []\n }\n\n idCache = {};\n}",
"restoreOriginalState() {\n\n\t\t\tconst originalValueOffset = this.valueSize * 3;\n\t\t\tthis.binding.setValue( this.buffer, originalValueOffset );\n\n\t\t}",
"function resetVars() {\n\t\tidArrays = [];\n\t\tdeathArrays = [];\n\t\tfollowUpArrays = [];\n\t\tdataType = \"number\";\n\t\tsources = 0;\n\t\tNs = [];\n\t\thaveFollowUp = false;\n\t\tdataName = \"\";\n\t\tdragZone = {'left':-1, 'top':-1, 'right':-1, 'bottom':-1, 'name':\"\", 'ID':\"\"};\n\t\tlimits = {'minX':0, 'maxX':0, 'minY':0, 'maxY':0};\n\t\tunique = 0; // number of data points with non-null values\n\t\tNULLs = 0;\n\t\tlocalSelections = []; // the data to send to the parent\n\t}",
"reset() {\n this._registry = new Map();\n }",
"static async reset(projectPath, resetHard, noGit = false) {\n const resolvedScopePath = Consumer._getScopePath(projectPath, noGit);\n\n _bitMap().default.reset(projectPath, resetHard);\n\n const scopeP = _scope().Scope.reset(resolvedScopePath, resetHard);\n\n const configP = _workspaceConfig().default.reset(projectPath, resetHard);\n\n await Promise.all([scopeP, configP]);\n }",
"clearAll() {\n this._stack.length = 0;\n\n // stuff the stack to mimic always needed registers\n for (let i = 0; i < MINIMUM_STACK; i++) {\n this._stack.push(0);\n }\n\n this._lastX = 0;\n this._clearMemory();\n }",
"function restoreSettings() {\n for (let index = 0; index < settingsStorage.length; index++) {\n let key = settingsStorage.key(index);\n if (key) {\n let data = {\n key: key,\n newValue: settingsStorage.getItem(key)\n };\n asap.send(data);\n }\n }\n}",
"function resetMain(){\n\tfor (var i = 0; i < leveldata.length; i++){\n\t\tleveldata[i].posX = leveldata[i].resetX;\n\t\tleveldata[i].spawned = false;\n\t\tleveldata[i].despawned = false;\n\t\tleveldata[i].removed = false;\n\t}\n\t\n\tscore = 0;\n\tspeed = 0;\n\teggsSaved = 0;\n\tcurrentGameState = gameStates[2];\n}",
"function resetInterpreterAndSequencerStore() {\n _storesSequencerStoreJs2['default'].resetState();\n /* SequencerStore now has new node/link refs,\n update via function closure */\n stateToNodeConverter = new _StateToNodeConverterStateToNodeConverterJs2['default'](_storesSequencerStoreJs2['default'].linkState().nodes, _storesSequencerStoreJs2['default'].linkState().links);\n // there isn't an AST if we switch from dynamic without parsing\n if (astWithLocations) {\n /* create deep copy so that d3 root modifications\n and interpreter transformations are not maintained */\n var sessionAst = (0, _lodash.cloneDeep)(astWithLocations).valueOf();\n try {\n interpreter = new _vendor_modJSInterpreterInterpreterJs2['default'](sessionAst, _jsInterpreterInitJsInterpreterInitJs2['default']);\n } catch (e) {\n displaySnackBarError('Interpreter error', e);\n }\n }\n }",
"function clearSavedState()\n{\n localStorage.clear(); // nuclear option\n console.info(\"All saved states have been cleared.\");\n}",
"function restoreAll() {\n clientMethods.forEach(function (methodName) {\n monitor[methodName].restore();\n });\n}",
"endGroup() {\n if (this.undefStack.length === 0) {\n throw new ParseError(\"Unbalanced namespace destruction: attempt \" + \"to pop global namespace; please report this as a bug\");\n }\n\n const undefs = this.undefStack.pop();\n\n for (const undef in undefs) {\n if (undefs.hasOwnProperty(undef)) {\n if (undefs[undef] === undefined) {\n delete this.current[undef];\n } else {\n this.current[undef] = undefs[undef];\n }\n }\n }\n }",
"function saveState() {\n\tvar stackMaxPlusOne = 4;\n\tif(gameType == 'creator') {\n\t\tstackMaxPlusOne = 11;\n\t}\n\tstate = {\n\t\t'level': level,\n\t\t'dimensions': level.dimensions,\n\t\t'row': row,\n\t\t'col': col,\n\t\t'moves': moves,\n\t\t'tiles': tiles,\n\t\t'curColumnsRight': curColumnsRight,\n\t\t'curColumnsLeft': curColumnsLeft,\n\t\t'curRowsTop': curRowsTop,\n\t\t'curRowsBottom': curRowsBottom,\n\t\t'flippedColumnsRight': flippedColumnsRight,\n\t\t'flippedColumnsLeft': flippedColumnsLeft,\n\t\t'flippedRowsTop': flippedRowsTop,\n\t\t'flippedRowsBottom': flippedRowsBottom,\n\t\t'actionStack': actionStack.toString(),\n\t\t'matrix': []\n\t};\n\tfor(var i = 0; i < level.dimensions; i++) {\n\t\tstate.matrix[i] = matrix[i].slice();\n\t}\n\t// add as first element of the stack\n\t// note the first element of the stack matches the current state\n\tundoStack.unshift(state);\n\tif(undoStack.length > stackMaxPlusOne) {\n\t\tundoStack.splice(stackMaxPlusOne, 1);\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate case note submitted from the Home page quick add widget | function validQuickCaseNote (cseVals)
{
var errors = [];
//check description
if (cseVals[4].value === '')
{errors.push('<p>Please provide a description of what you did.</p>');}
//check if the time entered is greater than 0 hours and 0 minutes
if (cseVals[2].value == '0' && cseVals[3].value == '0')
{errors.push('<p>Please indicate the amount of time for this activity.</p>');}
errString = errors.join(' ');
return errString;
} | [
"function validCaseNote(cseVals)\n{\n\n\tvar errors = [];\n\n\t//check if a description has been put in the textarea\n\tif (cseVals[6].value === 'Describe what you did...' || cseVals[6].value === '')\n\t{errors.push('<p>Please provide a description of what you did.</p>');}\n\n\t//check if the time entered is greater than 0 hours and 0 minutes\n\tif (cseVals[1].value == '0' && cseVals[2].value == '0')\n\t{errors.push('<p>Please indicate the amount of time for this activity.</p>');}\n\n\terrString = errors.join(' ');\n\n\treturn errString;\n\n}",
"function pageValidate(){\n var txtFieldIdArr = new Array();\n txtFieldIdArr[0] = \"tf1_SysName,\"+LANG_LOCALE['12134'];\n if (txtFieldArrayCheck(txtFieldIdArr) == false) \n return false;\n \n if (alphaNumericValueCheck (\"tf1_SysName\", '-', '') == false) \n return false;\n\n if (isProblemCharArrayCheck(txtFieldIdArr, \"'\\\" \", NOT_SUPPORTED) == false) \n return false;\n}",
"function validateCMSAddPageForm(formname)\n{\n \n if($('#frmDisplayPageTitle').val() == '')\n {\n alert(PAGE_DISP_TITLE);\n $('#frmDisplayPageTitle').focus()\n return false;\n }\n if($('#frmPageTitle').val() == '')\n {\n alert(PAGE_TIT_REQ);\n $('#frmPageTitle').focus()\n return false;\n } \n if($('#frmPageDisplayOrder').val() == '' )\n {\n alert(PAGE_ORDER_REQ);\n $('#frmPageDisplayOrder').focus()\n return false;\n } \n \n}",
"function valBlog(frm){\n\tvar passed=true;\n\tvar errorCount=0;\n\tvar t= frm.title.value;\t\n\tvar tags= frm.tags.value;\t\n\t\n\tif(t==\"\" || t==null){\n\t\terrorCount++;\n\t\tdocument.getElementById(\"title_err\").innerHTML=\"You must enter a title\";\n\t}else if(t.length>100){\n\t\terrorCount++;\n\t\tdocument.getElementById(\"title_err\").innerHTML=\"Your title cannot be more than 100 characters.\";\n\t}//end of title validation\n\t\n\tif(tags==\"\" || tags==null){\n\t\terrorCount++;\n\t\tdocument.getElementById(\"tag_err\").innerHTML=\"You must enter atleast one tag\";\n\t}//end of tag validation\n\t\n\t\tif(errorCount !=0)\n\t{\n\t\treturn false;\n\t}\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 confirmNote(){\n\tvar notes = document.getElementById('NotesVacID').value;\n\tif (notes !== '')\n\t\treturn notes;\n\t\treturn window.confirm(\"Your Notes are Empty, Confirm?\");\n}",
"function validateSocietyHouseNo() {\r\n\t\tclearMsg(\"societyHouseNoMsg\");\r\n\t\tvar societyHouseNo = document.getElementById(\"societyHouseNo\");\r\n\t\tif (societyHouseNo.value == null || societyHouseNo.value == \"\" || societyHouseNo.value == \" \") {\r\n\t\t\tdocument.getElementById(\"societyHouseNoMsg\").innerHTML = \"This field is required\";\r\n\t\t\tif (!isFocus) {\r\n\t\t\t\tsocietyHouseNo.focus();\r\n\t\t\t\tisFocus = true;\r\n\t\t\t}\r\n\t\t\treturn true;\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t}",
"static validateValuationCodeEntered(pageClientAPI, dict) {\n let error = false;\n let message = '';\n //Code group is not empty\n if (!libThis.evalCodeGroupIsEmpty(dict)) {\n //Characteristic is blank\n if (libThis.evalIsCodeOnly(dict)) {\n error = (libThis.evalValuationCodeIsEmpty(dict));\n if (error) {\n message = pageClientAPI.localizeText('field_is_required');\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ValuationCodeLstPkr'), message);\n }\n } else {\n //Code sufficient is set and reading is empty\n if (libThis.evalIsCodeSufficient(dict) && libThis.evalIsReadingEmpty(dict)) {\n error = (libThis.evalValuationCodeIsEmpty(dict));\n if (error) {\n message = pageClientAPI.localizeText('validation_valuation_code_or_reading_must_be_selected');\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ReadingSim'), message);\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ValuationCodeLstPkr'), message);\n }\n }\n }\n }\n if (error) {\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n } else {\n return Promise.resolve(true);\n }\n }",
"function validateReviewTextbox(){\r\n var reviewID = document.getElementById(\"reviewId\");\r\n var reviewMsg = document.getElementById(\"reviewMessage\");\r\n \r\n if (reviewID.value.length > 0) {\r\n if (reviewID.value.indexOf(' ') === -1) {\r\n reviewMsg.style.color = \"black\";\r\n reviewMsg.innerHTML = \"\";\r\n reviewID.style.border = \"\";\r\n reviewID.style.background = \"\";\r\n return true;\r\n } else {\r\n reviewMsg.style.color = \"red\";\r\n reviewMsg.innerHTML = \"No spaces allowed\";\r\n reviewID.style.border = \"1px solid red\";\r\n }\r\n } else {\r\n reviewMsg.style.color = \"red\";\r\n reviewMsg.innerHTML = \"Field Required\";\r\n reviewID.style.border = \"1px solid red\";\r\n }\r\n \r\n return false; \r\n }",
"function validateDemographics() {\n \n demographics = $('#demo').serializeArray();\n var ok = true;\n \n if (demographics.length != 5) {\n ok = false;\n alert('Please fill out all fields.');\n \n } else {\n \n for (var i = 0; i < demographics.length; i++) {\n // validate age\n if ((demographics[i].name == \"age\") && (/[^0-9]/.test(demographics[i].value))) {\n alert('Please only use numbers in age.');\n ok = false;\n break;\n }\n \n // test for empty answers\n if (demographics[i].value === \"\") {\n alert('Please fill out all fields.');\n ok = false;\n break;\n }\n \n // link this to their worker ID\n if (demographics[i].name == \"workerID\") {\n demographics[i].value = demographics[i].value.toUpperCase();\n demographics[i].value = demographics[i].value.replace(/\\s+/g, '');\n lasttime = getLastTime(demographics[i].value);\n }\n }\n }\n \n // goes to next section\n if (!ok) {\n showDemographics();\n } else { \n showGeneralInstructions();\n }\n}",
"validate() {\n this.verifTitle();\n this.verifDescription();\n this.verifNote();\n this.verifImg();\n console.log(this.errors);\n console.log(this.test);\n if (this.test !== 0) {\n return false;\n }\n return true;\n }",
"function validateCommentReplyForm(){\n\tvar field = document.getElementById(\"crField\");\n\tvar photoField = document.getElementById(\"crPhotoField\");\n\n\tif(field.value.trim().length >= 65500){\n\t\t// 65500\n\t\tfield.focus();\n\t\t$(\"#errorForContent\").show();\n\t\t$(\"#errorForContent\").text(\"Too Long Text\");\n\t\tfield.style.border = \"1px solid red\";\n\t\tfield.placeholder = \"Too long text\";\n\t\tevent.preventDefault();\n\t}else{\n\t\t$(\"#errorForContent\").hide();\n\t\tfield.style.border = \"none\";\n\t\tfield.placeholder = \"Add Comment...\"\n\t}\n\n\t// This if means if both the photo filed and comment field is empty then throw an error\n\tif(field.value.trim().length < 1 && photoField.files.length < 1){\n\t\t// for editing\n\t\tif($(\"#fileRemovedStatus\").is(\":disabled\")){\n\t\t\t// it means if someone just want to clear the text while editing and stick with old photo then do not show them error while submititng\n\t\t}else{\n\t\t\tfield.focus();\n\t\t\tfield.style.border = \"1px solid red\";\n\t\t\tfield.placeholder = \"can not add empty comment\";\n\t\t\t$(\"#errorForContent\").show();\n\t\t\t$(\"#errorForContent\").text(\"can not add empty comment\");\n\t\t\tevent.preventDefault();\n\t\t}\n\t}else{\n\t\tfield.placeholder = \"Add Comment...\";\n\t\t$(\"#errorForContent\").hide();\n\t\t$(\"#errorForContent\").text(\"\");\n\t\tfield.style.border = \"none\";\n\t}\t\n}",
"function custPreFormValidation(preChatlableObject, user){\n return true;\n}",
"addExercise()\n {\n if (this.addExerciseName.checkValidity()\n && this.addExerciseReps.checkValidity()\n && this.addExerciseRest.checkValidity()) {\n var name = this.addExerciseName.value;\n var reps = this.addExerciseReps.value;\n var rest = this.addExerciseRest.value;\n this.addExerciseName.value = \"\";\n this.addExerciseReps.value = \"\";\n this.addExerciseRest.value = \"\";\n Exercise.add(name, reps, rest);\n this.closeAddExerciseDialog();\n }\n }",
"function validateForm() {\n clientErrorStorage = new Object();\n var summaryTextExistence = new Object();\n var validForm = true;\n\n jQuery.watermark.hideAll();\n pauseTooltipDisplay = true;\n\n if (validateClient) {\n // Turn on this flag to avoid prematurely writing out messages which will cause performance issues if MANY\n // fields have validation errors simultaneously (first we are only checking for errors, not checking and\n // writing simultaneously like normal)\n clientErrorExistsCheck = true;\n\n // Temporarily turn off this flag to avoid traversing unneeded logic (all messages will be shown at the end)\n messageSummariesShown = false;\n\n // Validate the whole form\n validForm = jq(\"#kualiForm\").valid();\n\n // Handle field message bubbling manually, but do not write messages out yet\n jQuery(\"div[data-role='InputField']\").each(function () {\n var id = jQuery(this).attr('id');\n var field = jQuery(\"#\" + id);\n var data = getValidationData(field);\n var parent = field.data(\"parent\");\n handleMessagesAtGroup(parent, id, data, true);\n });\n\n // Toggle the flag back to default\n clientErrorExistsCheck = false;\n\n // Message summaries are going to be shown\n messageSummariesShown = true;\n\n // Finally, write the result of the validation messages\n writeMessagesForPage();\n }\n\n if (!validForm) {\n validForm = false;\n\n //ensure all non-visible controls are visible to the user\n jQuery(\".error:not(:visible)\").each(function () {\n cascadeOpen(jQuery(this));\n });\n\n jumpToTop();\n showClientSideErrorNotification();\n jQuery(\".uif-pageValidationMessages li.uif-errorMessageItem:first > a\").focus();\n }\n\n jq.watermark.showAll();\n pauseTooltipDisplay = false;\n\n return validForm;\n}",
"function quickContactErrorCheck(){\n\tvar errorFlag=0;\n\tclearQuickContactErrors();\n\tif((jQuery(\"#qc-name\").val() == null || jQuery(\"#qc-name\").val() == \"\") ){\n\t\tjQuery(\".olam_name\").fadeIn().html(\"Enter your name\");\n\t\terrorFlag=1;\n\t}\n\tif((jQuery(\"#qc-email\").val() == null || jQuery(\"#qc-email\").val() == \"\") ){\n\t\tjQuery(\".olam_email\").fadeIn().html(\"Enter your email\");\n\t\terrorFlag=1;\n\t}\n\tif((jQuery(\"#qc-message\").val() == null || jQuery(\"#qc-message\").val() == \"\") ){\n\t\tjQuery(\".olam_message\").fadeIn().html(\"Enter your message\");\n\t\terrorFlag=1;\n\t}\n\treturn errorFlag;\n}",
"function validateSlideThree() {\n\tvar motto = document.forms[\"register\"][\"businessmotto\"].value;\n\tvar mottoError = document.getElementById(\"error-businessmotto\");\n\tvar state = document.forms[\"register\"][\"state\"].value;\n\tvar area = document.forms[\"register\"][\"area\"].value;\n\tvar stateError = document.getElementById(\"error-state\");\n\tvar areaError = document.getElementById(\"error-area\");\n\n\t\n\n\t//validates business motto\n\tif (motto == \"\") {\n\t\tmottoError.innerHTML = \"This field is required\";\n\t} else {\n\t\tmottoError.innerHTML = \"\";\n\t}\n\n\tif (state == \"\") {\n\t\tstateError.innerHTML = \"This field is required\";\n\t} else {\n\t\tstateError.innerHTML = \"\";\n\t}\n\n\tif (area == \"\") {\n\t\tareaError.innerHTML = \"This field is required\";\n\t} else {\n\t\tareaError.innerHTML = \"\";\n\t}\n\n\t//if either fails validation remain on current slide else move to next slide\n\n\tif (motto == \"\" || area == \"\" || state == \"\") {\n\t\tcurrentSlide(3);\n\t} else {\n\t\tplusSlides(1);\n\t}\n}",
"function valReason(frm){\n\tvar passed=true;\n\tvar errorCount=0;\n\tvar r= frm.reason.value;\n\t\n\tif(r==\"\" || r==null){\n\t\terrorCount++;\n\t\tdocument.getElementById(\"reason_err\").innerHTML=\"You must select a reason to deny the post.\";\n\t}\n\t\n\t\tif(errorCount !=0)\n\t{\n\t\treturn false;\n\t}\n}",
"function validateAddPaymentForm()\n{\n\tvar box, i;\n\tvar form = document.addPayment;\n\t\n\tfor(i=0; i<4; i++)\n\t{\n\t\tbox=form.elements[i];\n\t\t//if it encountered a box without a value, an alert box would appear informing the user\n\t\tif(!box.value)\n\t\t{\n\t\t\t$().toastmessage({position:'middle-center', stayTime:2000});\n\t\t\t$().toastmessage('showErrorToast', \"You haven't filled in the \"+box.name+\".\");\n\t\t\tbox.focus();\n\t\t\treturn false;\n\t\t}\n\t}\n\t//if the form is complete, a confirm box would appear asking the user if he/she wants to continue\n\tvar confirmAdd = confirm(\"Continue Addition of Payment Entry?\");\n\t\n\t//return the answer of the user (true or false)\n\treturn confirmAdd;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send an EWS request for the message's subject. | function sendRequest() {
// Create a local variable that contains the mailbox.
var mailbox = Office.context.mailbox;
debugger;
var request = getSubjectRequest(mailbox.item.itemId);
var envelope = getSoapEnvelope(request);
mailbox.makeEwsRequestAsync(envelope, callback);
} | [
"function sendRequest() {\n // Create a local variable that contains the mailbox. \n var mailbox = Office.context.mailbox;\n var request = getSubjectRequest(mailbox.item.itemId);\n var envelope = getSoapEnvelope(request);\n\n mailbox.makeEwsRequestAsync(envelope, callback);\n }",
"function sendemail(){\t\n\t\n\t\t// make ajax request to post data to server; get the promise object for this API\n\t\tvar request = WmsPost.newAjaxRequest('/wms/x-services/email/producer', formToJSON());\n\t\n\t\t// register a function to get called when the data is resolved\n\t\trequest.done(function(data,status,xhr){\n\t\t\t//console.log(\"Email sent successfully!\");\n\t\t\tlocation.href = \"emailthankyou.html\";\n\t\t});\n\n\t\t// register the failure function\n\t\trequest.fail(function(xhr,status,error){\n\t\t\t//console.error(\"The following error occured: \"+ status, error);\n\t\t\talert(\"Problem occured while sending email: \" + error);\n\t\t});\n\n\t}",
"async function asyncSend(subject, messageBody) {\n console.log('Model::asyncSend');\n const body = {\n subject,\n body: messageBody,\n };\n const response = await fetch('http://localhost:8082/api/messages', {\n method: 'POST',\n body: JSON.stringify(body),\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n });\n const json = await response.json();\n return json;\n}",
"function getSubjectId (subject) {\n if ('uri' in subject) {\n return subject.uri\n } else if ('_subject_id' in subject) {\n return subject._subject_id\n } else {\n const result = '' + subjectIdCounter\n subject._subject_id = result\n ++subjectIdCounter\n return result\n }\n }",
"get_room_subject(callback){\n callback(this.parent.room.subject)\n }",
"requestInvite(){\n let ic = new iCrypto()\n ic.createNonce(\"n\")\n .bytesToHex(\"n\", \"nhex\");\n let request = new Message(self.version);\n let myNickNameEncrypted = ChatUtility.encryptStandardMessage(this.session.settings.nickname,\n this.session.metadata.topicAuthority.publicKey);\n let topicNameEncrypted = ChatUtility.encryptStandardMessage(this.session.settings.topicName,\n this.session.metadata.topicAuthority.publicKey);\n request.headers.command = \"request_invite\";\n request.headers.pkfpSource = this.session.publicKeyFingerprint;\n request.headers.pkfpDest = this.session.metadata.topicAuthority.pkfp;\n request.body.nickname = myNickNameEncrypted;\n request.body.topicName = topicNameEncrypted;\n request.signMessage(this.session.privateKey);\n this.chatSocket.emit(\"request\", request);\n }",
"function getEmail() {\n $http.get('/mail/messages').then(function(response) {\n if (response.data) {\n console.log('mail data', response.data);\n $scope.allMessageInfo = response.data.items;\n $scope.allMessages = [];\n $scope.allMessageInfo.forEach(function(item, index) {\n\n $http.post('/mail/messages/item', item).then(function(response1) {\n\n $scope.message = response1.data;\n console.log('job id from email: ', $scope.message['X-Mailgun-Variables']);\n //console.log($scope.message);\n var matches = $scope.message.Subject.match(/\\[(.*?)\\]/);\n\n if (matches) {\n var id = matches[1];\n console.log(\"submatch\", id);\n if (item.event == 'stored') {\n\n console.log('message matched to subject', $scope.message);\n $scope.messageObject = {\n message: $scope.message['stripped-text'],\n timestamp: item.timestamp * 1000,\n username: $scope.message.sender,\n msgType: 'received'\n };\n $http.put('/chats/' + id, $scope.messageObject).then(function(req, res) {\n $scope.messageContainer = {};\n });\n\n }\n }\n\n });\n\n });\n\n } else {\n console.log('error');\n }\n });\n }",
"function SendEmail( subject, body )\n{\n try\n {\n var outlookApp = new ActiveXObject(\"Outlook.Application\");\n var nameSpace = outlookApp.getNameSpace(\"MAPI\");\n mailFolder = nameSpace.getDefaultFolder(6);\n mailItem = mailFolder.Items.add('IPM.Note.FormA');\n mailItem.Subject = subject;\n mailItem.To = \"\";\n mailItem.HTMLBody = body;\n mailItem.display(0);\n }\n catch (e)\n {\n alert(e);\n // act on any error that you get\n }\n}",
"function MDEC_BtnSelectSubjectClick(el) {\n console.log(\"===== MDEC_BtnSelectSubjectClick =====\");\n\n if (mod_MEX_dict.is_addnew){\n\n console.log(\" duo_subject_dicts\", duo_subject_dicts);\n // PR2023-03-20 was: t_MSSSS_Open(loc, \"subject\", subject_rows, false, false, setting_dict, permit_dict, MDEC_Response);\n t_MSSSS_Open_NEW (loc, \"subject\", duo_subject_dicts, false, false, setting_dict, permit_dict, MDEC_Response);\n };\n }",
"async function getIncomingMessagesBySubject( subject )\n{\n\tlet queryInfo = { \tsubject: subject };\n\tlet messageList = ( await browser.messages.query( queryInfo ) ).messages;\n\n\tlet matchingMessages = [];\n\n\tfor( let i = 0; i < messageList.length; i++ )\n\t{\n\t\tif( messageList[ i ].folder.type !== \"sent\" && messageList[ i ].folder.type !== \"archives\" )\n\t\t{\n\t\t\tmatchingMessages.push( messageList[ i ] );\n\t\t}\n\t}\n\n\treturn matchingMessages;\n}",
"function sendCSWRequest(config) {\n config = config || {};\n\n if (config.host && config.request) {\n var host = config.host;\n var params = config.request;\n\n var xml = Sarissa.getDomDocument();\n xml.async = false;\n var xmlhttp = new XMLHttpRequest();\n\n xmlhttp.open(\"POST\", host, false);\n xmlhttp.setRequestHeader(\"Content-type\", \"application/xml\");\n xmlhttp.setRequestHeader(\"Content-length\", params.length);\n xmlhttp.setRequestHeader(\"Connection\", \"close\");\n\n if (config.accept) {\n xmlhttp.setRequestHeader(\"Accept\", config.accept);\n }\n xmlhttp.send(params);\n\n\n if (config.accept == HTML_MIME_TYPE) {\n xml = xmlhttp.responseText;\n } else if (config.accept == XML_MIME_TYPE) {\n xml = xmlhttp.responseXML;\n } else {\n xml = xmlhttp.responseText;\n }\n\n return xml;\n } else {\n return undefined;\n }\n }",
"function deliverMessage(params, callback) {\n let AWS = require('aws-sdk');\n let AWSregion = 'us-east-1';\n AWS.config.update({region: AWSregion});\n\n let SNS = new AWS.SNS();\n\n SNS.publish(params, function(err, data){\n console.log('sending message to ' + params.PhoneNumber.toString() );\n\n if (err) {\n console.log(err, err.stack);\n }\n\n callback('Success!');\n });\n}",
"function sendSubscriptionEmail(req, res) {\n if (!req.body.email) {\n return res.json(Response(402, \"failed\", constantsObj.validationMessages.requiredFieldsMissing));\n } else if (req.body.email && !validator.isEmail(req.body.email)) {\n return res.json(Response(402, \"failed\", constantsObj.validationMessages.invalidEmail));\n } else {\n var userMailData = { email: req.body.email};\n utility.readTemplateSendMailSubscribe(req.body.email, constantsObj.emailSubjects.sendSubscription, userMailData, 'subcribe_user', function(err, resp) {});\n return res.json(Response(200, \"success\", constantsObj.messages.subscribeSucess));\n }\n}",
"function subscribe(token, topic) {\n\t\tfetch('https://iid.googleapis.com/iid/v1/'+ token +'/rel/topics/' + topic, {\n\t\t\tmethod: 'POST',\n\t\t\t// Authorization: key=<your_server_key>\n\t\t\theaders: new Headers({\n\t\t\t\t'Authorization': 'key=AAAAq7m9O1U:APA91bFIqnWbILVhSmL7R2gKR60ed2Dv-h4IDArb6tuRIYqKks8DQ6yHvDZYoIw4Yin9L0iQIE9zr_xbn5Rb3oh8NgmW3w13rjxED2Qvy8TP_7VphcpuPe946UQyI8lx_BRaSElTjclQ',\n\t\t\t\t'Content-Type': 'application/json'\n\t\t\t})\n\t\t})\n\t\t.then(response => {\n\t\t\tif(response.status < 200 || response.status >=400) {\n\t\t\t\tthrow 'Error subscribing to topic: '+response.status + ' - ' + response.text();\n\t\t\t}\n\t\t\tconsole.log('Subscribed to ' + topic);\n\t\t})\n\t\t.catch(function(err) {\n\t\t\tconsole.log(err)\n\t\t})\n\t}",
"async function sendOmnisendEmail({ recipient, subject, text, attachments }) {\n if (!recipient || !subject || !text) {\n console.log('Recipient, subject, and text are required fields');\n return;\n }\n\n if (!_.isArray(attachments)) {\n console.log('Attachments must be array of objects');\n return;\n }\n\n const transporter = nodemailer.createTransport({\n host: 'smtp.gmail.com',\n port: 465,\n secure: true,\n auth: {\n type: 'OAuth2',\n clientId,\n clientSecret\n }\n });\n\n const info = transporter.sendMail({\n from: emailAddress,\n to: recipient,\n subject,\n text,\n attachments,\n auth: {\n user: emailAddress,\n refreshToken,\n accessToken,\n expires: expiry_date\n }\n });\n\n return 'Message sent: %s', info.messageId;\n}",
"function _sendEmail() {\n\t\t\t}",
"function main() {\n \n \t//Step 1: Add Email\n\tvar recipient = \"peterstavrop@gmail.com\";\n \n \t//Step 2: Change Subject Line\n\tvar subject = \"Add Subject Line Here\";\n \n\tvar body = AdWordsApp.currentAccount().getName() + \" Paid Search Email \\n\";\n \n \t//Step 3: Add Text to Email Body\n \tbody = body + \"Add Text Here\";\n\n\tMailApp.sendEmail(recipient, subject, body);\n\t\n}",
"function sendTwilioMessage (client,from,to,body){\n client.messages\n .create({\n body: \"your passowrd is:\"+body,\n /*from: '+12074075156',*/\n from:from,\n to:to \n })\n .then(message => console.log(\"here the message id:\"+message.sid));\n}",
"send(channel, message) {\n this.app.db.ipfs.pubsub.publish(channel, Buffer.from(message), err => {\n if (err) {\n this.app.logger.err(err)\n }\n this.app.logger.silly('Msg ' + message + ' sent to ' + channel)\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scales player size depending on difficulty mode | function scalePlayer(mode){
return map(mode, 1,3,2,1);
} | [
"function setCardSize(){\n if (windowHeight/rangee < gameWidth/column){\n cardSize = windowHeight/rangee*0.7;\n }\n else {\n cardSize = gameWidth/column*0.7;\n }\n}",
"setScales() {\n this.r3a1_char_north.setScale(3);\n this.r3a1_char_south.setScale(3);\n this.r3a1_char_west.setScale(3);\n this.r3a1_char_east.setScale(3);\n this.r3a1_exitDoor.setScale(1.5);\n this.r3a1_E_KeyImg.setScale(0.4);\n this.r3a1_notebook.setScale(0.75);\n this.r3a1_map.setScale(0.75);\n this.character.setScale(1);\n this.r3a1_floor.scaleY = 1.185;\n this.r3a1_floor.scaleX = 1.395;\n this.profile.setScale(1.5);\n\n }",
"setSize(\n width, // The width of the game.\n height // The height of the game.\n ) {\n const { game } = this;\n if (width > 0) {\n game.width = width;\n }\n if (height > 0) {\n game.height = height;\n }\n }",
"function split() {\n var newWidth = Math.sqrt(2) * currentPlayer.width / 2;\n var scale = newWidth / originalSize;\n var newX = getNewPlayerXCoord(currentPlayer.body.bottom - newWidth, newWidth);\n if(newX && scale >= 0.5) {\n var newPlayer = GeometrySplit.game.add.sprite(newX, currentPlayer.y, 'player');\n playerSetUp(newPlayer);\n newPlayer.scale.setTo(scale, scale);\n currentPlayer.scale.setTo(scale, scale);\n } else {\n //console.log('SPLIT FAILED')\n }\n}",
"_setCreatureSize(data, actor, sceneId) {\n const sizes = {\n tiny: 0.5,\n sm: 0.8,\n med: 1,\n lg: 2,\n huge: 3,\n grg: 4,\n };\n const aSize = actor.data.data.traits.size;\n let tSize = sizes[aSize];\n\n // if size could not be found return\n if (tSize === undefined) return;\n\n const scene = game.scenes.get(sceneId);\n\n // If scene has feet/ft as unit, scale accordingly\n // 5 ft => normal size\n // 10 ft => double\n // etc.\n if (/(ft)|eet/.exec(scene.data.gridUnits) !== null)\n tSize *= 5 / scene.data.gridDistance;\n\n if (tSize < 1) {\n data.scale = tSize;\n data.width = data.height = 1;\n } else {\n const int = Math.floor(tSize);\n\n // Make sure to only have integers\n data.width = data.height = int;\n // And scale accordingly\n data.scale = tSize / int;\n // Set minimum scale 0.25\n data.scale = Math.max(data.scale, 0.25);\n }\n }",
"function maxStageSize() {\n scene.setAttr('scaleX', 1);\n scene.setAttr('scaleY', 1);\n scene.setAttr('width', maxStageWidth);\n scene.setAttr('height', maxStageHeight);\n // document.getElementById(\"iframe\").style.transform = 1;\n // document.getElementById(\"iframe\").style.width = maxStageWidth;\n scene.draw();\n}",
"function updateCanvasScale() {\n cellSize = (window.innerWidth / 100) * gridCellSizePercent;\n cellsPerWidth = parseInt(window.innerWidth / cellSize);\n cellsPerHeight = parseInt((cellsPerWidth * 9) / 21);\n\n canvasWidth = window.innerWidth;\n canvasHeight = cellSize * cellsPerHeight;\n resizeCanvas(canvasWidth, canvasHeight);\n\n if (smallScreen != canvasWidth < minCanvasWidth) {\n smallScreen = canvasWidth < minCanvasWidth;\n if (!smallScreen) {\n ui.showUIByState();\n }\n }\n\n ui.hiscores.resize(false);\n}",
"function scaleStage() {\n var win = {\n width : $(window).width()-20,\n height: $(window).height()-20\n },\n stage = {\n width : 323,\n height: 574\n },\n scaling = Math.min(\n win.height/stage.height,\n win.width/stage.width\n );\n\n // Scale and FadeIn entire stage for better UX\n\n new TimelineLite()\n .set('#stage', {scale:scaling, transformOrigin:\"0 0 0\" })\n .to(\"#stage\", 0.5, {opacity:1});\n\n }",
"function setupPlayer() {\n playerX = 4*width/5;\n playerY = height/2;\n playerHealth = playerMaxHealth;\n}",
"function _scaling ( /*[Object] event*/ e ) {\n\t\tvar activeObject = cnv.getActiveObject(),\n\t\tscale = activeObject.get('scaleY') * 100;\n\t\tif ( scale > 500 ) {\n\t\t\tactiveObject.scale(5);\n\t\t\tactiveObject.left = activeObject.lastGoodLeft;\n \tactiveObject.top = activeObject.lastGoodTop;\n\t\t}\n\t\tactiveObject.lastGoodTop = activeObject.top;\n \tactiveObject.lastGoodLeft = activeObject.left;\n\t\tif ( is_text(activeObject) ) {\n\t\t\teditTextScale.set( scale );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'scale', scale );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'top', activeObject.top );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'left', activeObject.left );\n\t\t}\n\t\telse {\n\t\t\teditImageScale.set(scale);\n\t\t}\n\t}",
"function screenRatio(){\n sidebarWidth = width*0.25\n gameWidth = width*0.75;\n}",
"function setTileSizes() {\n $tileList = mainDiv.find(selector);\n for (var i = 0; i < $tileList.length; i++) {\n var size = $tileList.eq(i).attr(\"data-size\");\n var wdt = tileRatio * baseWH * tileSize[size].w-margin;\n var hgh = baseWH * tileSize[size].h-margin;\n $tileList.eq(i).css({\"width\": wdt, \"height\": hgh}).addClass('w' + tileSize[size].w + ' ' + 'h' + tileSize[size].h);\n }\n }",
"updateHealth(health) {\n // width is defined in terms of the player's health\n this.width = health * 5;\n }",
"function scaleToFit(x, scaleW, scaleH, type) {\n\tif (type == \"h\") {\n\t\t// x : res = scaleW : scaleH\n\t\treturn Math.round((x * scaleH) / scaleW)\n\t} else {\n\t\t// res : x = scaleW : scaleH\n\t\treturn Math.round((x * scaleW) / scaleH)\n\t}\n}",
"function set_sizes() {\n\tcurrSongLength = (currSong.song).length;\n\tcurrSongVoices = (currSong.song[0]).length;\n\tcurrSongTimes = (currSong.song[0][0]).length;\n\n\tcurrTact = 0;\n\tcurrTime = 0;\n\tlooping = eLoop.none;\n\n\tvar wH = window.innerHeight;\n\tvar par = 350; // ToDo: bind to window width\n\ttdSizeNorm = Math.round(0.8 * (wH - par) / (2 * currSongVoices));\n\ttdSizeBigger = Math.round((wH - par) / (2 * currSongVoices));\n\timgSizeNorm = Math.round(0.75 * (wH - par) / (2 * currSongVoices));\n\timgSizeBigger = Math.round(0.95 * (wH - par) / (2 * currSongVoices));\n\n\t// calculate offsets\n\timgOffsetTopNorm = '-' + imgSizeNorm/2 + 'px';\n\t//imgOffsetLeftNorm = '-' + imgSizeNorm/2 + 'px';\n\timgOffsetTopBigger = '-' + imgSizeBigger/2 + 'px';\n\timgOffsetLeftBigger = '-' + imgSizeBigger/2 + 'px';\n\t//imgOffsetTopNorm = imgOffsetTopBigger = 0;\n\timgOffsetLeftNorm = imgOffsetLeftBigger = '0px';\n}",
"function setSizes() {\n if (!currentMap) return;\n\n const viewMaxWidth = canvasElement.width - dpi(40);\n const viewMaxHeight = canvasElement.height - dpi(40);\n const tileWidth = Math.floor(viewMaxWidth / currentMap.cols);\n const tileHeight = Math.floor(viewMaxHeight / currentMap.rows);\n\n tileSize = Math.min(tileWidth, tileHeight);\n viewWidth = tileSize * currentMap.cols;\n viewHeight = tileSize * currentMap.rows;\n viewX = (canvasElement.width - viewWidth) / 2;\n viewY = (canvasElement.height - viewHeight) / 2;\n}",
"function sizeSlider(w) {\n // get width of slider if possible\n let sliderWidth = w || mprsSlider.getBoundingClientRect().width;\n if(!sliderWidth && sizing !== \"fixed\") return false; // use CSS rules\n //Elements are all sized using \"em\" units. Changing the font-size of\n //the main sllider div will cause all other elements to resize in\n //proportion. The sizing factor will influence the sizing curve so\n //that a higher factor will cause the elements to grow sooner.\n let weightFactor;\n if(sizing === \"fixed\" || !sliderWidth) {\n weightFactor = fixedSize;\n } else if(sizingFactor !== 1){\n weightFactor = .04 * sliderWidth * sizingFactor;\n } else {\n weightFactor = .04 * sliderWidth;\n }\n if(weightFactor < variableMin || weightFactor > variableMax) {\n weightFactor = weightFactor < variableMin ? variableMin : variableMax;\n }\n if(sliderWidth && (weightFactor) / sliderWidth > .13) {\n weightFactor = weightFactor * .7;\n }\n mprsSlider.style.fontSize = weightFactor + \"px\";\n }",
"function setSizePerElection(aSize) {\n sizePerElection = parseInt(aSize);\n } // setResolution",
"function gScale(sx,sy,sz) {\r\n modelViewMatrix = mult(modelViewMatrix,scale(sx,sy,sz)) ;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show the code on selected code cells. | function showCode(notebook) {
if (!notebook.model || !notebook.activeCell) {
return;
}
const state = Private.getState(notebook);
notebook.widgets.forEach(cell => {
if (notebook.isSelectedOrActive(cell) && cell.model.type === 'code') {
cell.inputHidden = false;
}
});
Private.handleState(notebook, state);
} | [
"function setCodeText(e) {\n document.querySelector(\"#language-selected\").innerHTML =\n extensionState.codeLanguage.charAt(0).toUpperCase() +\n extensionState.codeLanguage.slice(1);\n\n e = e || window.event;\n var keepWordList = e && e.shiftKey;\n\n // Change code snippet if shift key is not hit\n if (!keepWordList) {\n currentCode =\n selectedLanguageCodes[\n Math.floor(Math.random() * selectedLanguageCodes.length)\n ];\n }\n\n // Reset progress state\n clearTimeout(timer);\n gameOver = false;\n codeState = {\n firstChar: null,\n lastChar: null,\n currentChar: null,\n currentCharNum: 0,\n cursorLeftOffset: 0,\n cursorTopOffset: 0,\n linesLastCursorPositions: [],\n };\n\n // Reset cursor position\n cursor.classList.remove(\"hidden\");\n updateCursorPosition(0, 0);\n\n return;\n }",
"function showCell (evt) {\n evt.target.className = evt.target.className.replace(\"hidden\", \"\");\n if (evt.target.classList.contains(\"mine\")) {\n showAllMines();\n playBomb();\n reset();\n return;\n }\n showSurrounding(evt.target);\n checkForWin();\n}",
"function show_wysiwyg_button(cell) {\n cell.element.find(\".wysiwyg-toggle\").show();\n cell.element.find(\".wysiwyg-done\").show();\n }",
"function clickCode(){\n\tvar grid = abWasteRptProByReguCodeController.abWasteRptProByReguCodeGrid;\n\tvar num = grid.selectedRowIndex;\n\tvar rows = grid.rows;\n\tvar res = '1=1';\n\tvar code = rows[num]['waste_regulated_codes.regulated_code'];\n\tvar codeType = rows[num]['waste_regulated_codes.regulated_code_type'];\n\tvar res=new Ab.view.Restriction();\n\tres.addClause('waste_profile_reg_codes.regulated_code', code);\n\tres.addClause('waste_profile_reg_codes.regulated_code_type', codeType);\n\tabWasteRptProByReguCodeController.abWasteRptProByReguCodeDetailGrid.refresh(res);\n\t\n}",
"function drawCodeWindow(sO) {\r\n\r\n // STEP:\r\n // if we are currently editing an index expression in a grid -- e.g.,\r\n // row+4 -- we just need to redraw that expression -- we do not need\r\n // to redraw the entire code window.\r\n //\r\n if (sO.focusBoxId == CodeBoxId.Index) {\r\n redrawGridIndexExpr(sO);\r\n return;\r\n }\r\n\r\n // .....................................................................\r\n // STEP: Start drawing the code window table\r\n //\r\n var str = \"<table class='codeWin'>\";\r\n //\r\n // Small Vertical spaces between boxes\r\n //\r\n var vspace = \"<tr><td><div style='height:4px'> </div></td></tr>\";\r\n //\r\n // Find correct auto indentation AND total # of tab indents for table\r\n // Total columns is total indents + 1 + 1 (for 'let column')\r\n //\r\n var totcols = setCodeWindowIndentation(sO) + 1;\r\n\r\n\r\n // STEP: Draw Index names. Each index name is for a dimension.\r\n //\r\n var inames = getIndNames4Step(sO);\r\n //\r\n str += \"<tr>\" + \"<td></td>\" + \"<td colspan=\" + totcols +\r\n \" style='text-align:center'>\" + inames +\r\n \"<div style='height:10px'></div></td>\" + \"</tr>\" + vspace\r\n\r\n\r\n // STEP: Go thru each box and draw it\r\n //\r\n for (var box = CodeBoxId.Range; box < sO.boxAttribs.length; box++) {\r\n\r\n var expr = sO.boxExprs[box];\r\n var exprstr = \"\";\r\n var hasfocus = (sO.focusBoxId == box);\r\n //\r\n if (expr) {\r\n\r\n // If the box has focus always show expression. Otherwise, \r\n // show the expression only if the statment is 'not empty' --\r\n // i.e., just 'if' is an empty statement.\r\n //\r\n var deleted = (expr.deleted == DeletedState.Deleted)\r\n\r\n if (!deleted && (hasfocus || !isEmptyStmt(expr))) {\r\n\r\n sO.curBox = box; // pass box # to getHtmlExprStmt\r\n //\r\n exprstr = getHtmlExprStmt(expr, sO, \"\");\r\n }\r\n }\r\n\r\n // Onclick function to change the focus to this box if the user\r\n // clicks on it. If the user has already clicked on this box (hasfocus)\r\n // then draw a glowing shadow.\r\n //\r\n var oncBox = \" onclick='changeCWInputBox(\" + box + \")' \";\r\n //\r\n var glow = (!hasfocus) ? \"\" :\r\n \" style='box-shadow: -3px 3px 3px #dcffed' \";\r\n\r\n // Start a new row with label\r\n //\r\n var type = sO.boxAttribs[box].type;\r\n //\r\n var label = \"Index Range\";\r\n if (type == CodeBoxId.Mask) label = \"Condition\";\r\n if (type == CodeBoxId.Formula) label = \"Formula\";\r\n //\r\n str += \"<tr>\" + \"<td>\" + label + \":</td>\";\r\n\r\n // print empty cells for proper indentation AND find column span\r\n // for the expression\r\n //\r\n for (var t = 0; t < sO.boxAttribs[box].indent; t++) {\r\n str += \"<td></td>\";\r\n }\r\n var colspan = totcols - sO.boxAttribs[box].indent;\r\n\r\n // FIX: Unique id needed\r\n //\r\n var commentId = getCommentHtmlId(CommentType.StepBox, box);\r\n var cur_comment = sO.boxAttribs[box].comment;\r\n var comment = getCommentStr('span', commentId, \"\", cur_comment);\r\n //\r\n\r\n var letstr = \"\";\r\n /*\r\n\tif (box == 3) {\r\n\r\n\t letstr = \"<span onclick='letClicked()'>let</span>\";\r\n\t}\r\n\t*/\r\n\r\n // Draw the codebox containing expression\r\n //\r\n str += \"<td class='formula' colspan=\" + colspan + oncBox + glow +\r\n \">\"\r\n\r\n + letstr\r\n + exprstr + \"</td>\" + \"<td>\" + comment + \"</td>\" // comment\r\n + \"</tr>\" + vspace;\r\n }\r\n\r\n\r\n // ......................................................................\r\n // STEP: Draw operator buttons at the BOTTOM of code window (same table)\r\n //\r\n var hsep = \"<span>   </span>\";\r\n\r\n // default input button description\r\n //\r\n var bstr = \"<input type='button' class='opbutton' \"; \r\n var bstr2 = \"<button type='submit' class='opbutton' \";\r\n\r\n str += \"<tr><td><div style='height:10px'> </div></td></tr>\";\r\n str += \"<tr>\" + \"<td></td>\" // skip label cell\r\n\r\n\t+ \"<td style='text-align:center' colspan=\" + totcols + \"> \" \r\n\t+ bstr + \"value='+' onclick='addOpExpr(\\\"+\\\")'>\" \r\n\t+ bstr + \"value='-' onclick='addOpExpr(\\\"-\\\")'>\" \r\n\r\n\t+ bstr + \"value='*' onclick='addOpExpr(\\\"*\\\")'>\"\r\n\t+ bstr + \"value='/' onclick='addOpExpr(\\\"/\\\")'>\" \r\n\t+ hsep\r\n\r\n + bstr + \"value='<' onclick='addOpExpr(\\\"<\\\")'>\" \r\n + bstr + \"value='>' onclick='addOpExpr(\\\">\\\")'>\" \r\n + bstr + \"value='<' onclick='addOpExpr(\\\"<\\\")'>\" \r\n + bstr + \"value='=' onclick='addOpExpr(\\\"=\\\")'>\" \r\n + bstr + \"value='!=' onclick='addOpExpr(\\\"!=\\\")'>\" \r\n + bstr + \"value='<-' onclick='addOpExpr(\\\"<-\\\")'>\"\r\n\r\n\r\n\t+ bstr + \"value='OR' onclick='addOpExpr(\\\"OR\\\")'>\" \r\n\t+ bstr + \"value='AND' onclick='addOpExpr(\\\"AND\\\")'>\" \r\n\t+ bstr + \"value='NOT' onclick='addOpExpr(\\\"NOT\\\")'>\" \r\n\t+ hsep\r\n\r\n + bstr + \"value='(' onclick='addOpExpr(\\\"(\\\")'>\" \r\n + bstr + \"value=')' onclick='addOpExpr(\\\")\\\")'>\" \r\n + hsep\r\n \r\n\t// Buttons for functions. To create subscripts, we use 'bstr2'\r\n\t//\r\n\t+ bstr2 + \"onclick='addNewFuncExpr()' title='new function'> \" \r\n\t+ \"f<sub>new</sub></button>\"\r\n\t//\r\n\t+ bstr2 + \"onclick='addExistFuncExpr()' title='existing function'> \" \r\n\t+ \"f<sub> </sub></button>\"\r\n\t//\r\n\t+ bstr2 + \"onclick='addLibFuncExpr()' title='library function'> \" \r\n\t+ \"f<sub>lib</sub></button>\"\r\n\t//\r\n\t+ hsep\r\n\r\n\t// Note: number expression is useful for adding a numeric func arg\r\n\t// \r\n + bstr + \" title='number' \" \r\n\t+ \"value='123' onclick='addNumExpr(\\\"123\\\")'>\" \r\n\r\n + bstr + \" title='string (characters)' \" \r\n\t+ \"value='abc' onclick='addStrExpr(\\\"abc\\\")'>\" \r\n\r\n + bstr + \" title='index end' \" + \"value='end' onclick='addEndExpr()'>\" \r\n + hsep;\r\n\r\n str += bstr + \"value='Delete' onclick='delOpExpr()'>\" \r\n\t+ \"</td></tr>\";\r\n\r\n\r\n // Does the Code Window has the focus (the CW may not have focus when\r\n // we are editing something else like an dim name\r\n //\r\n var cwFocus = (sO.focusBoxId != CodeBoxId.INVALID);\r\n\r\n // Add additional buttons for condition processing (if/else/...) if\r\n // the focus is on a mask box\r\n //\r\n if (cwFocus && sO.boxAttribs[sO.focusBoxId].isMask() &&\r\n (sO.activeChildPos == ROOTPOS)) {\r\n\r\n str += \"<tr><td></td>\" \r\n\t + \"<td style='text-align:center' colspan=\" + totcols + \">\";\r\n\r\n var onc = \" onclick='changeCondKeyword(\\\"if\\\",\" + ExprType.If + \")'\";\r\n str += bstr + \"value='if' \" + onc + \">\";\r\n //\r\n var onc = \" onclick='changeCondKeyword(\\\"else\\\",\" + ExprType.Else +\r\n \")'\";\r\n str += bstr + \"value='else' \" + onc + \">\";\r\n //\r\n var onc = \" onclick='changeCondKeyword(\\\"else if\\\",\" +\r\n ExprType.ElseIf + \")'\";\r\n str += bstr + \"value='else if' \" + onc + \">\";\r\n //\r\n //var onc = \" onclick='changeCondKeyword(\\\"break if\\\",\" + \r\n // ExprType.BreakIf + \")'\";\r\n //str += bstr + \"value='break if' \" + onc + \">\";\r\n\r\n str += \"</td></tr>\";\r\n }\r\n\r\n\r\n // Add additional buttons for formula processing (break/return) if\r\n // the focus is on a formula box AND we are at the start of the formula\r\n //\r\n if (cwFocus && sO.boxAttribs[sO.focusBoxId].isFormula() &&\r\n sO.activeParentExpr && sO.activeParentExpr.isExprStmt() &&\r\n (sO.activeChildPos == 0)) {\r\n\r\n str += \"<tr><td></td>\" +\r\n \"<td style='text-align:center' colspan=\" + totcols + \">\";\r\n\r\n // Let\r\n //\r\n var onc = \" onclick='addLetExpr()' \";\r\n str += bstr + \"value='let' \" + onc + \">\";\r\n //\r\n // Continue\r\n //\r\n var onc = \" onclick='addFormulaKeyword(\\\"continue\\\",\" +\r\n ExprType.Continue + \")'\";\r\n str += bstr + \"value='continue' \" + onc + \">\";\r\n //\r\n // Return\r\n //\r\n var onc = \" onclick='addFormulaKeyword(\\\"return\\\",\" +\r\n ExprType.Return + \")'\";\r\n str += bstr + \"value='return' \" + onc + \">\";\r\n //\r\n // Break\r\n //\r\n var onc = \" onclick='addFormulaKeyword(\\\"break\\\",\" +\r\n ExprType.Break + \")'\";\r\n str += bstr + \"value='break' \" + onc + \">\";\r\n //\r\n str += \"</td></tr>\";\r\n }\r\n\r\n // Add additional buttons for keywords if the focus is on a range box\r\n //\r\n if (cwFocus && sO.boxAttribs[sO.focusBoxId].isRange() &&\r\n ((sO.activeChildPos == ROOTPOS) ||\r\n (sO.isSpaceActive && !sO.activeChildPos))) {\r\n\r\n str += \"<tr><td></td>\" +\r\n \"<td style='text-align:center' colspan=\" + totcols + \">\";\r\n\r\n var onc = \" onclick='changeLoopToForeach()' \";\r\n str += bstr + \"value='foreach' \" + onc + \">\";\r\n //\r\n var onc = \" onclick='changeLoopToForever()' \";\r\n str += bstr + \"value='forever' \" + onc + \">\";\r\n\r\n str += \"</td></tr>\";\r\n }\r\n // STEP: Show/hide step options\r\n if(sO.showOptions) {\r\n\r\n\t// Show checkbox for user to specify enabling converting to OpenCL.\r\n\t// Example: for simple initializations the data transfer and OpenCL\r\n\t// overhead may outweigh the benefits (so don't transform step to\r\n\t// OpenCL kernel).\r\n\tvar onc = \"onclick='markOCLstep(this.checked)'\";\r\n if (sO.potOCLstep) onc += \" checked \";\r\n\tstr += \"<tr><td></td>\" +\r\n \"<td style='text-align:center' colspan=\" + totcols + \">\";\r\n str += \"<input type='checkbox' \" + onc + \">\" +\r\n\t \"Enable OpenCL (if step parallelizable)\" +\r\n\t \"</td></tr\";\r\n\r\n }\r\n \r\n //\r\n str += \"</table>\";\r\n\r\n // Write to code window HTML element\r\n //\r\n var cw1 = document.getElementById('codeWindow');\r\n cw1.innerHTML = str;\r\n\r\n\r\n // .....................................................................\r\n // STEP: Draw Action Buttons to the right of the window\r\n //\r\n var but1 = \"\",\r\n but2 = \"\",\r\n but3 = \"\";\r\n\r\n // buttons appear after grid selection\r\n //\r\n var has_but = sO.stageInStep >= StageInStep.GridSelectDone;\r\n //\r\n if (has_but) {\r\n\r\n var onc = \" onclick='addSource()' \";\r\n but1 = bstr + \"value='Add Source Grid' \" + onc;\r\n //\r\n }\r\n //\r\n var focusbox = sO.focusBoxId;\r\n var prop = \" type='button' class='formulabut' \"\r\n\r\n //\r\n str = \"<table class='operatorWin'>\"\r\n\r\n + \"<tr><td>\" + but1 + \"</td></tr>\"\r\n //+ \"<tr><td><div style='height:10px'></div></td></tr>\"\r\n\r\n + \"<tr><td>\" + \"<input\" + prop +\r\n \"value='Add Formula' onclick='addFormulaBox()'>\" + \"</td></tr>\"\r\n\r\n + \"<tr><td>\" + \"<input\" + prop +\r\n \"value='Add Condition' onclick='addMaskBox()'>\" + \"</td></tr>\";\r\n\r\n // Delete Box (don't allow deleting first 3 boxes -- TODO: relax this)\r\n //\r\n if (sO.focusBoxId > CodeBoxId.Range) {\r\n\r\n var val = (sO.boxAttribs[sO.focusBoxId].isMask()) ?\r\n \"Delete Condition\" : \"Delete Formula\";\r\n str += \"<tr><td>\" + \"<input\" + prop + \"value='\" + val +\r\n \"' onclick='deleteBox()'>\" + \"</td></tr>\";\r\n }\r\n\r\n\r\n str += \"<tr><td>\" + \"<input\" + prop +\r\n \"value='<=' onclick='updateBoxIndent(-1)' \";\r\n var dis = isBoxIndentLegal(focusbox, -1) ? \"\" : \" disabled \"\r\n str += dis + \">\"\r\n\r\n + \"<input\" + prop + \"value='=>' onclick='updateBoxIndent(1)' \";\r\n var dis = isBoxIndentLegal(focusbox, 1) ? \"\" : \" disabled \"\r\n str += dis + \"></td></tr>\"\r\n\r\n /*\r\n str += \"<tr><td>\"\r\n\t+ \"<img src='images/refresh.png' width=20px height=20px \" \r\n\t+ \" title='refresh step' onclick='refreshCurStep()'>\"\r\n\t+ \"</td></tr>\";\r\n */\r\n\r\n + \"<tr><td>\" + \"<input\" + prop +\r\n \"value='Options' onclick='showHideOptions()'>\" + \"</td></tr>\"\r\n + \"</table>\";\r\n\r\n var opw1 = document.getElementById('operatorWindow');\r\n opw1.innerHTML = str;\r\n\r\n}",
"function showSelection() {\n iconsContainer.css(\"visibility\", \"hidden\");\n selectionContainer.css(\"visibility\", \"visible\");\n }",
"_createCodeCell(model) {\n const rendermime = this.rendermime;\n const contentFactory = this.contentFactory;\n const editorConfig = this.editorConfig.code;\n const options = {\n editorConfig,\n model,\n rendermime,\n contentFactory,\n updateEditorOnShow: false,\n placeholder: false,\n maxNumberOutputs: this.notebookConfig.maxNumberOutputs\n };\n const cell = this.contentFactory.createCodeCell(options, this);\n cell.syncCollapse = true;\n cell.syncEditable = true;\n cell.syncScrolled = true;\n return cell;\n }",
"function SelectCodeBlock() {\r\n\tvar uSel = Editor.Selection;\r\n if (Sel.SelStartLine == 0) return;\r\n\r\n\tvar startLine = FindCodeStart(uSel.SelStartLine);\r\n\r\n\tif (startLine >= 0) { \t\t\t\t\t\t// We found the starting line\r\n\t\t// Find line with starting curly bracket (not always the same as the startLine)\r\n\t\tvar bracketLine = FindStartBracket(startLine);\r\n\t\tif (bracketLine != -1) {\t\t\t\t// We found the starting curly bracket\r\n\t\t\tvar endLine = FindCodeEnd(bracketLine);\r\n\t\t\tif (endLine >= startLine) { \t // We found the ending line\r\n\t\t\t\t// Set selection\r\n\t\t\t\tuSel.SelStartLine = startLine;\r\n\t\t\t\tuSel.SelStartCol = 0;\r\n\t\t\t\tuSel.SelEndLine = endLine + 1;\r\n\t\t\t\tuSel.SelEndCol = 0;\r\n\t\t\t\tEditor.Selection = uSel;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}",
"function runCode() {\r\n const code = editor.getValue();\r\n if (!code) return;\r\n let { response, logs, error } = evaluate(code);\r\n\r\n if (error) response = '<span class=\"error\">' + response + '</span>';\r\n if (logs.length && response) response = logs.join('\\n') + '\\n' + response;\r\n else if (logs.length) response = logs.join('\\n');\r\n\r\n consoleHTML.innerHTML += `<pre class=\"log\">${response}\\n</pre>`;\r\n}",
"function call_hscode(){\n\t\tstrURL = \"hs_code.html\";\n\t\tPopupOpenDialog(850,490);\n\n\t\tif(PopWinValue != null ){\n\t\t\tgcDs2.namevalue(gcDs2.rowposition,\"HSCODE\") = PopWinValue[0]; \n\t\t\tgcDs2.namevalue(gcDs2.rowposition,\"HSCODENM\") = PopWinValue[1]; \n\t\t}\n\t}",
"function areaClicked(code) {\n var idx = $.inArray(code, currCodes);\n\n if (idx > -1) {\n currCodes.splice(idx, 1);\n } else {\n currCodes.push(code);\n currCodes = currCodes.sort();\n }\n\n $txtCodes.val(currCodes.join(\", \"));\n }",
"function codeButtons () {\n // get all <code> elements.\n var allCodeBlocksElements = $('div[class^=\"language-\"]');\n allCodeBlocksElements.each(function(i) {\n\t// add a sequentially increasing id to each code block.\n var currentId = \"codeblock\" + (i + 1);\n $(this).attr('id', currentId);\n //define and then add a clipboard button to all code blocks.\n var clipButton = '<button class=\"codebtn\" data-clipboard-target=\"#' + currentId + '\"><img class=\"copybefore\" src=\"https://clipboardjs.com/assets/images/clippy.svg\" width=\"13\" alt=\"Copy to clipboard\"><img class=\"copyafter\" src=\"img/done.svg\" width=\"13\" alt=\"Copy to clipboard\"></button>';\n $(this).append(clipButton);\n });\n//instantiate clipboardjs on the buttons. This controls the copy action.\n new ClipboardJS('.codebtn');\n //switch between clipboard icon to checkmark icon on click.\n $('.codebtn').click(function() {\n $(this).find('.copybefore').hide();\n $(this).find('.copyafter').show();\n });\n}",
"open() {\n this.__revertContents = document.createElement(\"div\");\n this.__revertContents.appendChild(this.__selection.getRangeContents());\n this.__selectionContents = this.__selection.wrapOrGetTag(this.tag);\n this.__selection.addHighlight();\n this.updatePrompt();\n //make sure there is a unique id so that the prompt popover appears near the selection\n if (!this.__selectionContents.getAttribute(\"id\"))\n this.__selectionContents.setAttribute(\"id\", \"prompt\" + Date.now());\n this.__prompt.setTarget(this);\n this.dispatchEvent(new CustomEvent(\"select\", { detail: this }));\n }",
"function navigateCells(e) {\n if($(\"div.griderEditor[style*=block]\").length > 0)\n return false;\n\n var $td = $table.find('.' + defaults.selectedCellClass);\n var col = $td.attr(\"col\");\n switch(e.keyCode) {\n case $.ui.keyCode.DOWN:\n //console.log($td);\n setSelectedCell($td.parent(\"tr:first\").next().find('td[col=' + col + ']') );\n break;\n case $.ui.keyCode.UP:\n setSelectedCell($td.parent(\"tr\").previous().find('td[col=' + col + ']') );\n break;\n case $.ui.keyCode.LEFT:\n //console.log(\"left\");\n break;\n case $.ui.keyCode.RIGHT:\n //console.log(\"right\");\n break;\n }\n }",
"function on_piece_select()\n{\n\tupdate_editor();\n}",
"function selectKnCell(e){\n\tvar knCell = keynapse.currentKnCell;\n\tstopKeynapse();\n\n\tif(knCell.type == 'text'){\n\t\t$(knCell).focus();\t\t\n\t} else {\n\t\t$(knCell).focus();\n\t\t$(knCell).trigger(\"click\");\n\t}\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 showCharacter(overwrite) {\n \n if (typeof(overwrite)==\"undefined\") overwrite=true;\n \n var asciiCode = screenCharacterArray[cursorPosY+firstLine][cursorPosX+leftLine][0];\n var foreground = screenCharacterArray[cursorPosY+firstLine][cursorPosX+leftLine][1];\n var background = screenCharacterArray[cursorPosY+firstLine][cursorPosX+leftLine][2];\n \n codepage.drawChar(globalContext, asciiCode, foreground, (copyMode == false) ? background : 15, cursorPosX, cursorPosY, false, overwrite);\n \n }",
"function showHideOptions() {\r\n\r\n // Toggle show options status in CurStepObj and draw code window\r\n // TODO: It is not necessary to draw the entire code window. Separate\r\n // drawCodeWindow() function into 2 (or 3) functions, and call the\r\n // the one responsible for drawing buttons.\r\n //\r\n CurStepObj.showOptions = !CurStepObj.showOptions;\r\n drawCodeWindow(CurStepObj);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to insert character information into 'chars' table | function charToDB(name, roomID, userID, langs, callback){
var insertobj = {};
insertobj["userID"] = new ObjectID(userID);
insertobj["roomID"] = new ObjectID(roomID);
insertobj["char_name"] = name;
insertobj["char_langs"] = langs;
mongoInsert("chars", insertobj, null, function(result, extra){
callback(result);
});
} | [
"function createCharacters() {\n _case_ = new character('_case_', 110, 4, 20);\n acid = new character('acid', 120, 2, 10);\n brute = new character('Brรผte', 170, 1, 15);\n fdat = new character('f.dat', 150, 1, 12);\n }",
"function addChar(charName, roomID, email, langs, callback){ \n\t\tvar userID;\n\t\t\n\t\tmongoFind(\"appusers\", \"email\", email, null, function(result, extra){\n\t\t\tif(result != null){\n\t\t\t\tuserID = result._id.toString();\n\t\t\t\tcharToDB(charName, roomID, userID, langs, function(result){\n\t\t\t\t\tif(result == \"success\"){\n\t\t\t\t\t\tcallback(\"success\");\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tcallback(\"addCharError\");\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse{\n\t\t\t\tcallback(\"addCharError\");\n\t\t\t}\n\t\t});\n\t}",
"function gen_character(params) {\n\t//add character generation code here\n}",
"function insertChar(charCode) {\n var state = getState();\n removeExtraStuff(state);\n var myChar = String.fromCharCode(charCode);\n if (state.selection.start !== state.selection.end) {\n state.value = clearRange(state.value, state.selection.start, state.selection.end);\n }\n dotPos = state.value.indexOf('.');\n if (myChar === '.' && dotPos !== -1) {\n // If there is already a dot in the field, don't do anything\n return;\n }\n if (state.value.length - (dotPos === -1 && myChar !== '.' ? 0 : 1) >= config.digits) {\n // If inserting the new value makes the field too long, don't do anything\n return;\n }\n state.value = state.value.substring(0, state.selection.start) + myChar +\n state.value.substring(state.selection.start);\n addExtraStuff(state, false);\n setState(state);\n }",
"function createLettersTable() {\n let html = \"\";\n for (let i = 0; i < 26; i++) {\n if (i % 4 === 0) {\n html += `<tr>`;\n }\n\n html += `<td>${String.fromCharCode(i + 65)}</td>`;\n\n if (i % 4 === 3) {\n html += `</tr>`;\n }\n }\n html += `<td></td><td></td></tr>`;\n $('#letters').append(html);\n}",
"function add_character(char_icon, char_name, char_rarity, char_level) {\n if (char_level == 1) {\n row_1_data['char_icon'].setAttribute(\"src\", char_icon);\n row_1_data['char_name'].innerHTML = char_name;\n row_1_data['char_rarity'].setAttribute(\"src\", char_rarity);\n } else if (char_level == 2) {\n row_2_data['char_icon'].setAttribute(\"src\", char_icon);\n row_2_data['char_name'].innerHTML = char_name;\n row_2_data['char_rarity'].setAttribute(\"src\", char_rarity);\n } else if (char_level == 3) {\n row_3_data['char_icon'].setAttribute(\"src\", char_icon);\n row_3_data['char_name'].innerHTML = char_name;\n row_3_data['char_rarity'].setAttribute(\"src\", char_rarity);\n }\n}",
"function silencios_insert()\n{\n var silencio_nota = document.getElementById('silencio_notas');\n silencio_nota = silencio_nota.value;\n var textarea = document.getElementById('textarea');\n var text = textarea.value;\n var cursor = getCaret(textarea); \n switch (silencio_nota) { \n case \"redonda\":\n text = text.substring(0,cursor)+'_z8'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"blanca\":\n text = text.substring(0,cursor)+'_z4'+text.substring(cursor,text.length);\n textarea.value = text; \n break;\n case \"negra\":\n text = text.substring(0,cursor)+'_z2'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"corchea\":\n text = text.substring(0,cursor)+'_z1'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"semicorchea\":\n text = text.substring(0,cursor)+'_z1/2'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"fusa\":\n text = text.substring(0,cursor)+'_z1/4'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"semifusa\":\n text = text.substring(0,cursor)+'_z1/8'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n default:\n alert(\"error\");\n break;\n }\n}",
"function makeChar() {\n\tvar probability=points(0,\"\")/hardness;//according to hardness of game\n\tif(typeof alphabets === 'undefined' || alphabets === \"\"){\n\t\tvar index=Math.floor(Math.random() * 5)+2;\n\t\talphabets=words[index][Math.floor(Math.random() * words[index].length)];\n\t\tif(points(0,\"\")===0){\n\t\t\t//showing Hint only for new players\n\t\t\tif(typeof(Storage) !== \"undefined\") {\n\t\t\t\tif(localStorage.getItem(\"score\")===null){\n\t\t\t\t\thint(alphabets);//help player to learn game\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\thint(alphabets);//help player to learn game\n\t\t\t}\n\t\t}\n\t\ttext = alphabets.charAt(0);\n\t\talphabets = alphabets.slice(1);\t\n\t}else if(points(0,\"\") >=bombPoint){\n\t\t\ttext = 'B';\n\t\t\tbombPoint*=3;\n\t}else if(points(0,\"\") >=blockPoint){\n\t\t\ttext = 'N';\n\t\t\tblockPoint*=3;\n\t}else{\n\t\tif(Math.random() <= probability){\n\t\t\t//if propability goes up, game gets harder\n\t\t\ttext = randomChar();\n\t\t}else{\n\t\t\ttext = alphabets.charAt(0);\n\t\t\talphabets = alphabets.slice(1);\n\t\t}\n\t}\n\treturn text;\n}",
"function _insertData(conn) {\r\n return function (tableName1, tableName2, tableName3, header, data, nameTranslationTable, callback) {\r\n /*var convertedData = data.map(function (dataLine) {\r\n var convertedDataLine = Object.keys(dataLine).map(function (key) {\r\n var value = dataLine[key];\r\n return value;\r\n });\r\n\r\n return convertedDataLine.join(', ');\r\n });\r\n\r\n var translatedHeader = header;\r\n\r\n if (nameTranslationTable)\r\n translatedHeader = header.map(function (headerEl) {\r\n return nameTranslationTable[headerEl];\r\n });\r\n var query = `insert into ${tableName3} (${translatedHeader.join(', ')}) values (${convertedData.join('), (')})`;\r\n */\r\n var query = `INSERT INTO ${tableName3} (SELECT ${tableName1}.*, \r\n ${tableName2}.REPAIR_TYPE_DETAILS, ${tableName2}.DIG_COMPLETION_YEAR\r\n FROM ${tableName1} FULL OUTER JOIN ${tableName2} ON \r\n ${tableName1}.DISTANCE__M_= ${tableName2}.ILI_CHAINAGE \r\n ORDER BY ${tableName1}.DISTANCE__M_)`;\r\n \r\n console.log(\"Executing SQL query: _insertData()\");\r\n conn.query(query, function (err, queryData) {\r\n if (err) {\r\n console.log(err);\r\n return callback(err);\r\n }\r\n return callback();\r\n });\r\n };\r\n}",
"function fillDisplayWord (letter) {\n\n}",
"function createChiefComplaintEntry(){\r\n\tdb.transaction(\r\n\t\tfunction(transaction) {\r\n\t\t\ttransaction.executeSql(\r\n\t\t\t\t'INSERT INTO chief_complaint (patient, assessed, primary_complaint, primary_other, secondary_complaint, diff_breathing, chest_pain, nausea, vomiting, diarrhea, dizziness, ' +\r\n\t\t\t\t' headache, loc, numb_tingling, gal_weakness, lethargy, neck_pain, time) ' +\r\n\t\t\t\t' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);', \r\n\t\t\t\t[getCurrentPatientId(), 'false', '0', '', '', '', '', '', '', '', '', '', '', '', '', '', '', getSystemTime()], \r\n\t\t\t\tnull,\r\n\t\t\t\terrorHandler\r\n\t\t\t);\r\n\t\t}\r\n\t);\r\n}",
"function make_unicode(data) {\r\n var table = { 13: '\\r' }, // New line conversion\r\n reverse = { 13: 13 }, i = 0;\r\n while (i < data.length) {\r\n table[155 + i] = String.fromCharCode(data[i]);\r\n reverse[data[i]] = 155 + i++;\r\n }\r\n i = 32;\r\n while (i < 127) {\r\n table[i] = String.fromCharCode(i);\r\n reverse[i] = i++;\r\n }\r\n self.unicode_table = table;\r\n self.reverse_unicode_table = reverse;\r\n }",
"function saveChar(na, re, gen, gol, sin, le, ti, at){ \n\n\t\t/*console.log( \"\" +\n\n\t\t\tna + ',' + re + ',' + gen + ',' + gold + \",\" + sin + ',' + INDEX + ',' + ti + ',' \n \t+ upgrades.attributes[5].level + \",\" \n \t+ upgrades.attributes[4].level + \",\"\n \t+ upgrades.attributes[3].level + \",\"\n \t+ upgrades.attributes[2].level + \",\"\n \t+ upgrades.attributes[1].level + \",\"\n \t+ upgrades.attributes[0].level + \"\"\n\t\t);*/\n\n \t document.cookie = na + ',' + re + ',' + gen + ',' + gold + \",\" + sin + ',' + INDEX + ',' + ti + ',' \n\t\t\t+ upgrades.attributes[5].level + \",\" \n\t + upgrades.attributes[4].level + \",\"\n\t + upgrades.attributes[3].level + \",\"\n\t + upgrades.attributes[2].level + \",\"\n \t + upgrades.attributes[1].level + \",\"\n \t+ upgrades.attributes[0].level + \"\"\t\n\t \t+ \";expires=Thu, 01 Jan 2020 00:00:00 UTC\";\n\t}",
"function storeLetters(letters) {\n let letterContainer = document.getElementById(\"letterContainer\");\n for (const char of letters) {\n let underlined = document.createElement(\"div\");\n underlined.setAttribute(\"class\", \"underlined\");\n letterContainer.appendChild(underlined);\n var charContainer = document.createElement(\"div\");\n charContainer.setAttribute(\"hidden\", \"\");\n charContainer.setAttribute(\"class\", \"hiddenChar\");\n charContainer.innerHTML = char;\n underlined.appendChild(charContainer);\n }\n}",
"function drawCharset() {\r\n let chars = \"\"\r\n for (let ch = 0x20; ch <= 0x7F; ch++)\r\n chars += String.fromCharCode(ch)\r\n drawText(21, 0, chars)\r\n}",
"function charUnion(chars) {\n const tokenized = chars.split('').map(c => char(c));\n return new Desugarer(empty()).arbitrary_union(tokenized);\n}",
"function insertDBRow (fileHash, numberscount, letterscount, wordscount, sentencescount, colemanLiauNum, automatedReadabiltyNum){\nย ย ย ย db.run(`INSERT INTO textsinfo(fileHash, numbercount, lettercount, wordcount, sentencescount, colemanLiau, automatedReadability) VALUES(?,?,?,?,?,?,?)`, [fileHash, numberscount, letterscount, wordscount, sentencescount, colemanLiauNum, automatedReadabiltyNum], function(err) {\nย ย ย ย ย ย ย ย if (err) {\nย ย ย ย ย ย ย ย return console.log(err.message);\nย ย ย ย ย ย ย ย }\n\nย ย ย ย });\n}",
"function contamination(text, char){\n if (text === '' || char === '') return '';\n \n let length = text.length;\n\n let newStr = '';\n for (let i = 0; i < length; i++) {\n newStr += char;\n }\n return newStr;\n}",
"function createCallInfoEntry(){\r\n\tdb.transaction(\r\n\t\tfunction(transaction) {\r\n\t\t\ttransaction.executeSql(\r\n\t\t\t\t'INSERT INTO call_info (patient, assessed, attendant1, attendant1_other, attendant2, attendant2_other, driver, driver_other, ' +\r\n\t\t\t\t' unit_nb, run_nb, respond, milage_start, milage_end, ' + //13\r\n\t\t\t\t' code_en_route, code_return, transported_to, transported_position, time_notified, time_route, time_on_scene, ' + //20\r\n\t\t\t\t' time_depart, time_destination, time_transfer, time_back_service, time_patient_contact, ppe_gloves, ppe_eyes, ppe_reflective, ' +\r\n\t\t\t\t' ppe_isolation, ppe_mask, det1, det2, det3, assistance, other, time)' + //36\r\n\t\t\t\t' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);', \r\n\t\t\t\t[getCurrentPatientId(), 'false', '0', '', '0', '', '0', '', '', '', '', '', '', '', '',\r\n\t\t\t\t'', '0', '', '', '', '', '', '', '', '', 'negative', //23\r\n\t\t\t\t'negative', 'negative', 'negative', 'negative', '', '0', '', '0', '', getSystemTime()], \r\n\t\t\t\tnull,\r\n\t\t\t\terrorHandler\r\n\t\t\t);\r\n\t\t}\r\n\t);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a defer object containing the location pointing to a resolvedList with all the found coordinates. | function createAmbiguityList(locCoord) {
// make example working even if nominatim service is down
if (locCoord.input.toLowerCase() === "madrid") {
locCoord.lat = 40.416698;
locCoord.lng = -3.703551;
locCoord.locationDetails = formatLocationEntry({
city: "Madrid",
country: "Spain"
});
locCoord.resolvedList = [locCoord];
}
if (locCoord.input.toLowerCase() === "moscow") {
locCoord.lat = 55.751608;
locCoord.lng = 37.618775;
locCoord.locationDetails = formatLocationEntry({
road: "Borowizki-Straรe",
city: "Moscow",
country: "Russian Federation"
});
locCoord.resolvedList = [locCoord];
}
if (locCoord.isResolved()) {
var tmpDefer = $.Deferred();
tmpDefer.resolve([locCoord]);
return tmpDefer;
}
locCoord.error = "";
locCoord.resolvedList = [];
var timeout = 3000;
if (locCoord.lat && locCoord.lng) {
var url = nominatim_reverse + "?lat=" + locCoord.lat + "&lon=" + locCoord.lng + "&format=json&zoom=16";
return $.ajax({
url: url,
type: "GET",
dataType: "json",
timeout: timeout
}).fail(function(err) {
// not critical => no alert
locCoord.error = "Error while looking up coordinate";
console.log(err);
}).pipe(function(json) {
if (!json) {
locCoord.error = "No description found for coordinate";
return [locCoord];
}
var address = json.address;
var point = {};
point.lat = locCoord.lat;
point.lng = locCoord.lng;
point.bbox = json.boundingbox;
point.positionType = json.type;
point.locationDetails = formatLocationEntry(address);
// point.address = json.address;
locCoord.resolvedList.push(point);
return [locCoord];
});
} else {
return doGeoCoding(locCoord.input, 10, timeout).pipe(function(jsonArgs) {
if (!jsonArgs || jsonArgs.length == 0) {
locCoord.error = "No area description found";
return [locCoord];
}
var prevImportance = jsonArgs[0].importance;
var address;
for (var index in jsonArgs) {
var json = jsonArgs[index];
// if we have already some results ignore unimportant
if (prevImportance - json.importance > 0.4)
break;
// de-duplicate via ignoring boundary stuff => not perfect as 'Freiberg' would no longer be correct
// if (json.type === "administrative")
// continue;
// if no different properties => skip!
if (address && JSON.stringify(address) === JSON.stringify(json.address))
continue;
address = json.address;
prevImportance = json.importance;
var point = {};
point.lat = round(json.lat);
point.lng = round(json.lon);
point.locationDetails = formatLocationEntry(address);
point.bbox = json.boundingbox;
point.positionType = json.type;
locCoord.resolvedList.push(point);
}
if (locCoord.resolvedList.length === 0) {
locCoord.error = "No area description found";
return [locCoord];
}
var list = locCoord.resolvedList;
locCoord.lat = list[0].lat;
locCoord.lng = list[0].lng;
// locCoord.input = dataToText(list[0]);
return [locCoord];
});
}
} | [
"function createAmbiguityList(locCoord) {\n locCoord.error = \"\";\n locCoord.resolvedList = [];\n var timeout = 3000;\n\n if (locCoord.isResolved()) {\n // if we changed only another location no need to look this up again\n var tmpDefer = $.Deferred();\n tmpDefer.resolve([locCoord]);\n return tmpDefer;\n } else if (locCoord.lat && locCoord.lng) {\n var url = nominatimReverseURL + \"?lat=\" + locCoord.lat + \"&lon=\"\n + locCoord.lng + \"&format=json&zoom=16\";\n return $.ajax({\n url: url,\n type: \"GET\",\n dataType: \"json\",\n timeout: timeout\n }).then(\n function (json) {\n if (!json) {\n locCoord.error = \"No description found for coordinate\";\n return [locCoord];\n }\n var address = json.address;\n var point = {};\n point.lat = locCoord.lat;\n point.lng = locCoord.lng;\n point.bbox = json.boundingbox;\n point.positionType = json.type;\n point.locationDetails = formatLocationEntry(address);\n // point.address = json.address;\n locCoord.resolvedList.push(point);\n return [locCoord];\n },\n function (err) {\n log(\"[nominatim_reverse] Error while looking up coordinate lat=\" + locCoord.lat + \"&lon=\" + locCoord.lng);\n locCoord.error = \"Problem while looking up location.\";\n return [locCoord];\n }\n );\n } else {\n return doGeoCoding(locCoord.input, 10, timeout).then(\n function (jsonArgs) {\n if (!jsonArgs || jsonArgs.length === 0) {\n locCoord.error = \"No area description found\";\n return [locCoord];\n }\n var prevImportance = jsonArgs[0].importance;\n var address;\n for (var index in jsonArgs) {\n var json = jsonArgs[index];\n // if we have already some results ignore unimportant\n if (prevImportance - json.importance > 0.4)\n break;\n\n // de-duplicate via ignoring boundary stuff => not perfect as 'Freiberg' would no longer be correct\n // if (json.type === \"administrative\")\n // continue;\n\n // if no different properties => skip!\n if (address && JSON.stringify(address) === JSON.stringify(json.address))\n continue;\n\n address = json.address;\n prevImportance = json.importance;\n var point = {};\n point.lat = round(json.lat);\n point.lng = round(json.lon);\n point.locationDetails = formatLocationEntry(address);\n point.bbox = json.boundingbox;\n point.positionType = json.type;\n locCoord.resolvedList.push(point);\n }\n if (locCoord.resolvedList.length === 0) {\n locCoord.error = \"No area description found\";\n return [locCoord];\n }\n var list = locCoord.resolvedList;\n locCoord.lat = list[0].lat;\n locCoord.lng = list[0].lng;\n // locCoord.input = dataToText(list[0]);\n return [locCoord];\n },\n function () {\n locCoord.error = \"Problem while looking up address\";\n return [locCoord];\n }\n );\n }\n}",
"function measureLocations() {\n let locationPromise;\n // Measures already available\n if (measures) {\n locationPromise = Promise.resolve(measures);\n // Promise of measures available\n } else if (measuresPromise) {\n locationPromise = measuresPromise;\n // Compute measures\n } else {\n measuresPromise = stationsCollection().then((stationlist) => {\n const measureLocs = {};\n stationlist.map((station) => {\n station.measure().map((measureVal) => {\n if (!measureLocs[measureVal['@id']]) {\n measureLocs[measureVal['@id']] = {\n lat: station.lat(),\n long: station.long(),\n };\n }\n return null;\n });\n return null;\n });\n measures = measureLocs;\n return measureLocs;\n });\n locationPromise = measuresPromise;\n }\n return locationPromise;\n}",
"function getLookupList() {\n\n\t\t\t\t\tvar def = $q.defer();\n\n\t\t\t\t\tif ($scope.lookupList === void 0) {\n\n\t\t\t\t\t\tSharePoint.getWeb($scope.schema.LookupWebId).then(function(web) {\n\n\t\t\t\t\t\t\tweb.getList($scope.schema.LookupList).then(function(list) {\n\n\t\t\t\t\t\t\t\t$scope.lookupList = list;\n\n\t\t\t\t\t\t\t\tlist.getProperties({ $expand: 'Forms' }).then(function() {\n\n\t\t\t\t\t\t\t\t\tlist.getFields().then(function() {\n\n\t\t\t\t\t\t\t\t\t\tdef.resolve($scope.lookupList);\n\n\t\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t});\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\t// Returns cached list\n\t\t\t\t\t\tdef.resolve($scope.lookupList);\n\t\t\t\t\t}\n\n\n\t\t\t\t\treturn def.promise;\n\t\t\t\t}",
"function getGelolocationFieldFromList() {\n var clientContext = new SP.ClientContext.get_current();\n var parentCtx = new SP.AppContextSite(clientContext, appData.AppHostUrl);\n var parentWeb = parentCtx.get_web();\n var targetList = parentWeb.get_lists().getByTitle(appData.ImageLibraryDisplayTitle);\n this.listFields = targetList.get_fields();\n clientContext.load(this.listFields, 'Include(InternalName, TypeAsString)');\n clientContext.executeQueryAsync(Function.createDelegate(this,\n this.onListGeolocationFieldsQuerySucceeded), Function.createDelegate(this,\n this.onSiteQueryFailed));\n}",
"function getFundedItemLocations(searchTerm, next) {\n\tdb.sequelize.query('SELECT DISTINCT p.Year, p.Number, p.ProposalTitle, i.ItemName, l.ProposalId, l.Address, l.Lat, l.Lng, l.Description FROM STF.Locations l JOIN STF.Items i ON i.id = l.ItemId JOIN STF.Proposals p ON p.id = i.ProposalId JOIN STF.Supplementals s ON p.id = s.ProposalId WHERE ((p.Status = 4 AND i.PartialId is null AND i.SupplementalId is null) OR (p.Status = 4 AND i.PartialId is null AND s.id is not null AND s.id = i.SupplementalId) OR (p.Status = 5 AND p.PartialFunded = i.PartialId)) AND i.ItemName LIKE ?;', {replacements: [searchTerm +'%']})\n\t.spread(function(itm) {\n\t\tvar items = [];\n\t\tfor(var i = 0; i < itm.length; i++) {\n\t\t\titems.push(itm[i]);\n\t\t}\n\t\tnext(items);\n\t});\n}",
"function getRideCoordinates() {\n\tvar collection = Alloy.createCollection(\"getTracking\");\n\tTi.API.error(\"Track ID: \" + _Track_ID_);\n\tTi.API.error(\"T_Id : \" + offset);\n\tcollection.fetch({\n\t\turlparams : {\n\t\t\tride_Id : _Track_ID_,\n\t\t\tt_Id : offset\n\t\t},\n\t\tsuccess : function(collection, response) {\n\t\t\tTi.API.error(\"Locations to Map Response: \" + JSON.stringify(response));\n\t\t\tTi.API.error(\"Locations to Map Response Length: \" + response.length);\n\t\t\tTi.API.error(\"Locations to Map Collection: \" + JSON.stringify(collection));\n\t\t\tTi.API.error(\"Locations to Map Collection Length: \" + collection.length);\n// [ERROR] : Track ID: 1134\n// [ERROR] : T_Id : 0\n// [ERROR] : Locations to Map Response: []\n// [ERROR] : Locations to Map Response Length: 0\n// [ERROR] : Locations to Map Collection: []\n// [ERROR] : Locations to Map Collection Length: 0\n//\n// [ERROR] : Track ID: 1141\n// [ERROR] : T_Id : 0\n// [ERROR] : Locations to Map Response: {\"id\":42604,\"ride_id\":1141,\"latitude\":\"0\",\"longitude\":\"0\",\"carpoolFrequency_id\":null,\"update_ts\":\"2017-07-18T04:16:48.000Z\",\"update_user\":\"admin\"}\n// [ERROR] : Locations to Map Response Length: undefined\n// [ERROR] : Locations to Map Collection: [{\"id\":42604,\"ride_id\":1141,\"latitude\":\"0\",\"longitude\":\"0\",\"carpoolFrequency_id\":null,\"update_ts\":\"2017-07-18T04:16:48.000Z\",\"update_user\":\"admin\"}]\n// [ERROR] : Locations to Map Collection Length: 1\n//\n// [ERROR] : Track ID: 1142\n// [ERROR] : T_Id : 0\n// [ERROR] : Locations to Map Response: [{\"id\":42605,\"ride_id\":1142,\"latitude\":\"12.9793914\",\"longitude\":\"80.2215002\",\"carpoolFrequency_id\":null,\"update_ts\":\"2017-07-18T04:29:08.000Z\",\"update_user\":\"admin\"},{\"id\":42606,\"ride_id\":1142,\"latitude\":\"12.9793814\",\"longitude\":\"80.2215009\",\"carpoolFrequency_id\":null,\"update_ts\":\"2017-07-18T04:29:08.000Z\",\"update_user\":\"admin\"}]\n// [ERROR] : Locations to Map Response Length: 2\n// [ERROR] : Locations to Map Collection: [{\"id\":42605,\"ride_id\":1142,\"latitude\":\"12.9793914\",\"longitude\":\"80.2215002\",\"carpoolFrequency_id\":null,\"update_ts\":\"2017-07-18T04:29:08.000Z\",\"update_user\":\"admin\"},{\"id\":42606,\"ride_id\":1142,\"latitude\":\"12.9793814\",\"longitude\":\"80.2215009\",\"carpoolFrequency_id\":null,\"update_ts\":\"2017-07-18T04:29:08.000Z\",\"update_user\":\"admin\"}]\n// [ERROR] : Locations to Map Collection Length: 2\n// [ERROR] : ShowRouteOnMap - Response Length : 2\n\n\t\t\tif (response.length == undefined && collection.length == 1) {\n\t\t\t\t// there is only one point (collection is an array, while response is an struct)\n\t\t\t\tvar rsp = [];\n\t\t\t\trsp.push(response);\n\t\t\t\tshowRouteOnMap(rsp);\n\t\t\t} else if (response.length == 0) {\n\t\t\t\t// there is not points\n\t\t\t\tshowRouteOnMap(response);\n\t\t\t} else {\n\t\t\t\t// there is more than one point\n\t\t\t\tshowRouteOnMap(response);\n\t\t\t}\n\t\t},\n\t\terror : function(err, response) {\n\t\t\tvar parseResponse = JSON.parse(response);\n\t\t\tTi.API.error(\"Locations to Map Error: \" + JSON.stringify(err));\n\t\t\tTi.API.error(\"Locations to Map Error Response: \" + JSON.stringify(response));\n\t\t\talert(\"session expired, please log back.\");\n\t\t\tif (parseResponse.status == 401) {\n\t\t\t\ttimeUtil.closeAllOpenWindows();\n\t\t\t\tAlloy.createController('signin').getView().open();\n\t\t\t}\n\t\t}\n\t});\n}",
"async getNearbyLocations(context) {\n let locations = null,\n nearbyLocations = [],\n radiusDistance = context.getters.radiusDistance;\n\n locations = await context.dispatch('getLocations');\n\n return new Promise(function (resolve) {\n locations.forEach(async function (location) {\n if (location) {\n let distanceAway = await context.dispatch('getDistanceAwayFromUser', location);\n\n if (parseInt(distanceAway) <= radiusDistance){\n nearbyLocations.push(location);\n location.DistanceFromUser = distanceAway + \" \" + Settings.units + \" away\";\n } \n }\n });\n\n context.commit('setLocations', nearbyLocations);\n context.commit('setActiveLocations', nearbyLocations);\n\n resolve(nearbyLocations);\n });\n }",
"function findSnappedLocation(lineLocation){\n\tvar finalLocation=lineLocation;\n\tvar listSize=globalPlList.size;\n\tfor(var i=1;i<=listSize;i++){\n\t\tvar line = globalPlList.get(i.toString());\n\t\tif(line!=undefined){\n\t\t\tvar startPath=line.getPath().getAt(0);\n\t\t\tvar endPath=line.getPath().getAt(1);\n\t\t\tvar tempCircleStart=new google.maps.Circle({\n\t\t\t\tcenter: startPath,\n\t\t\t\tradius: 10\n\t\t\t});\t\n\t\t\tvar tempCircleEnd=new google.maps.Circle({\n\t\t\t\tcenter: endPath,\n\t\t\t\tradius: 10,\n\t\t\t});\t\n\t\t\tvar isStartPath = google.maps.Circle.prototype.contains(lineLocation, tempCircleStart);\n\t\t\tvar isEndPath = google.maps.Circle.prototype.contains(lineLocation, tempCircleEnd);\n\t\t\tif(isStartPath){\n\t\t\t\tfinalLocation=startPath;\n\t\t\t\treturn finalLocation;\n\t\t\t}\n\t\t\telse if(isEndPath){\n\t\t\t\tfinalLocation=endPath;\n\t\t\t\treturn finalLocation;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tlistSize++; //To increase the size if a number is missing from id seq like 1,2,4,5,7 . Here Ids 3 and 6 are missing\n\t\t}\n\t}\n\treturn finalLocation;\n}",
"function locationFinder() {\n\t\t\tvar locations = [];\n\t\t\t// iterates through entries location and appends each location to\n\t\t\t// the locations array\n\t\t\tfunction appendLocations(entriesID) {\n\t\t\t\tmyData.forEach(function(tile) {\n\t\t\t\t\tif (tile.hasOwnProperty(entriesID)) {\n\t\t\t\t\t\ttile[entriesID].forEach(function(entry) {\n\t\t\t\t\t\t\tif (entry.hasOwnProperty('location')) {\n\t\t\t\t\t\t\t\tlocations.push(entry.location);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\tappendLocations('schools');\n\t\t\tappendLocations('works');\n\t\t\tappendLocations('allTheRest');\n\t\t\treturn removeDuplicate(locations);\n\t\t}",
"function locationFinder() {\n\n // initializes an empty array\n var locations = [];\n\n // adds the single location property from bio to the locations array\n locations.push(bio.contacts.location);\n\n // iterates through school locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide:\n // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop\n education.schools.forEach(function(school){\n locations.push(school.location);\n });\n\n // iterates through work locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide:\n // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop\n work.jobs.forEach(function(job){\n locations.push(job.location);\n });\n // console.log(locations);\n return locations;\n }",
"getContainerLocations() {\n if (this.containerLocations) { return this.containerLocations; }\n\n this.containerLocations = [];\n\n this.getSourceManagers().forEach(s => {\n s.findMiningSpots().forEach(pos => {\n this.containerLocations.push(pos);\n });\n });\n\n const room = this.object('room');\n const controllerPos = this.agent('controller').object('controller').pos;\n const adjacentOpen = room.lookAtArea(\n controllerPos.y - 1, controllerPos.x - 1,\n controllerPos.y + 1, controllerPos.y - 1, true).filter(lookObj => {\n return (lookObj.type === LOOK_TERRAIN &&\n lookObj[lookObj.type] !== 'wall');\n });\n let k = 0;\n for (let i = 0; i < adjacentOpen.length; i++) {\n this.containerLocations.push({\n x: adjacentOpen[i].x,\n y: adjacentOpen[i].y\n });\n k++;\n if (k > 2) { break; }\n }\n\n return this.containerLocations;\n }",
"function stationsCollection() {\n if (stations) {\n return Promise.resolve(stations);\n } else if (stationsPromise) {\n return stationsPromise;\n }\n\n return retrieveStations();\n}",
"function locationFinder() {\n\n // initializes an empty array\n let locations = [];\n\n // adds the single location property from bio to the locations array\n locations.push(bio.contacts.location);\n\n // iterates through school locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide:\n // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop\n education.schools.forEach(function (school) {\n locations.push(school.location);\n });\n\n // iterates through work locations and appends each location to\n // the locations array. Note that forEach is used for array iteration\n // as described in the Udacity FEND Style Guide above.\n work.jobs.forEach(function (job) {\n locations.push(job.location);\n });\n\n return locations;\n }",
"function geolocationPositionAcquired(ll, mainDispatch) {\n geocodeLocation(ll, mainDispatch, true);\n return {\n type: types.GEOLOCATION_POSITION_ACQUIRED,\n data: ll\n };\n}",
"getLookupList(listName) {\n return this.getLookupLists([listName]).then((lists) => {\n return lists[listName];\n });\n }",
"getLookupLists(listNames) {\n let lookupLists = get(this, 'lookupLists');\n let store = get(this, 'store');\n let listsToQuery = listNames.filter((listName) => {\n if (isEmpty(lookupLists[listName])) {\n return true;\n }\n });\n if (isEmpty(listsToQuery)) {\n return resolve(this._getLookupListsFromCache(listNames));\n } else {\n let queryHash = {};\n if (listsToQuery.includes('incidentCategories')) {\n queryHash.incidentCategories = store.findAll('inc-category');\n listsToQuery.removeObject('incidentCategories');\n }\n if (!isEmpty(listsToQuery)) {\n queryHash.lookup = store.query('lookup', {\n options: {\n keys: listsToQuery\n }\n });\n }\n return RSVP.hash(queryHash).then((hash) => {\n if (!isEmpty(hash.incidentCategories)) {\n lookupLists.incidentCategories = hash.incidentCategories.filterBy('archived', false);\n }\n if (!isEmpty(hash.lookup)) {\n listsToQuery.forEach((list) => {\n lookupLists[list] = hash.lookup.findBy('id', list);\n });\n }\n return this._getLookupListsFromCache(listNames);\n });\n }\n }",
"latLng(){\r\n return L.latLng(this.latitude, this.longitude);\r\n }",
"function getUserCoords(locationID) {\n console.log(\"searching for cordinates for \" + locationID)\n\n //geocoder key (used for getting lat and long from user's location id)\n var locIdCoordURL = \"https://geocoder.api.here.com/6.2/geocode.json?locationid=\" + locationID + \"&jsonattributes=1&gen=9&app_id=\" + appId + \"&app_code=\" + appCode;\n console.log(\"using api \" + locIdCoordURL)\n $.ajax({\n url: locIdCoordURL,\n type: \"GET\"\n }).then(function(data) {\n // console.log(data);\n userLatitude = data.response.view[0].result[0].location.displayPosition.latitude;\n userLongitude = data.response.view[0].result[0].location.displayPosition.longitude;\n console.log(\"Latitude \" + userLatitude + \" Longitude \" + userLongitude);\n\n setUserInfo();\n pushInfoInFireBase();\n });\n }",
"function getLookupItems($query) {\n\n\t\t\t\t\tvar def = $q.defer();\n\n\t\t\t\t\tif ($scope.lookupItems !== void 0) {\n\n\t\t\t\t\t\t// Returns cached items\n\t\t\t\t\t\tdef.resolve($scope.lookupItems);\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tgetLookupList().then(function(list) {\n\n\t\t\t\t\t\t\tlist.getListItems($query).then(function(items) {\n\n\t\t\t\t\t\t\t\t$scope.lookupItems = items;\n\t\t\t\t\t\t\t\tdef.resolve($scope.lookupItems);\n\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\treturn def.promise;\n\t\t\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION NAME : setChildDevice2() AUTHOR : James Turingan DATE : December 18, 2013 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : stores the data from cgi to json => devicesFilter PARAMETERS : DEV,hostname,ctr | function setChildDevice2(DEV,hostname,ctr){
var hname = hostname;
var InfoType = "JSON";
if(InfoType == "XML"){
var device = DEV.childNodes;
for(var i = 0; i < device.length; i++){
if(device[i].nodeName == "MODULE"){
var newModule = device[i];
var vId = newModule.getAttribute('ModuleVid');
var name = newModule.getAttribute('Module');
var pId = newModule.getAttribute('ModulePid');
if(hname = devicesFilter[ctr].Hostname ){
devicesFilter[ctr].Module.push({
VersionId: vId,
ProductId: pId,
ModuleName: name
});
}
}
if(device[i].nodeName == "ROUTEPROCESSOR"){
var newRoute = device[i];
var versionId = newRoute.getAttribute('RouteProcessorVid');
var memory = newRoute.getAttribute('TotalMemory');
var name = newRoute.getAttribute('RouteProcessorName');
var productId = newRoute.getAttribute('RouteProcessorPid');
if(hname = devicesFilter[ctr].Hostname){
devicesFilter[ctr].Route.push({
VersionId: versionId,
Memory: memory,
RouteName: name,
ProductId: productId
});
}
}
if(device[i].nodeName == "EMBEDDEDPROCESSOR"){
var newProcessor = device[i];
var versionId = newProcessor.getAttribute('EmbeddedProcessorVid');
var name = newProcessor.getAttribute('EmbeddedProcessorName');
var productId = newProcessor.getAttribute('EmbeddedProcessorVid');
var nitrox = newProcessor.getAttribute('Nitrox');
var octeon = newProcessor.getAttribute('Octeon');
if(hname = devicesFilter[ctr].Hostname ){
devicesFilter[ctr].Route.push({
VersionId: versionId,
Nitrox: nitrox,
Octeon: octeon,
EmbeddedName: name,
ProductId: productId
});
}
}
}
}else{
var device = DEV;
for(var i = 0; i < device.length; i++){
// if(device[i].nodeName == "MODULE"){
var newModule = device[i];
var vId = newModule.MODULE.ModuleVid;
var name = newModule.MODULE.Module;
var pId = newModule.MODULE.ModulePid;
if(hname = devicesFilter[ctr].Hostname ){
devicesFilter[ctr].Module.push({
VersionId: vId,
ProductId: pId,
ModuleName: name
});
}
// }
// if(device[i].nodeName == "ROUTEPROCESSOR"){
var newRoute = device[i];
var versionId = newRoute.ROUTEPROCESSOR.RouteProcessorVid;
var memory = newRoute.ROUTEPROCESSOR.TotalMemory;
var name = newRoute.ROUTEPROCESSOR.RouteProcessorName;
var productId = newRoute.ROUTEPROCESSOR.RouteProcessorPid;
if(hname = devicesFilter[ctr].Hostname){
devicesFilter[ctr].Route.push({
VersionId: versionId,
Memory: memory,
RouteName: name,
ProductId: productId
});
}
// }
// if(device[i].nodeName == "EMBEDDEDPROCESSOR"){
var newProcessor = device[i];
var versionId = newProcessor.EMBEDDEDPROCESSOR.EmbeddedProcessorVid;
var name = newProcessor.EMBEDDEDPROCESSOR.EmbeddedProcessorName;
var productId = newProcessor.EMBEDDEDPROCESSOR.EmbeddedProcessorVid;
var nitrox = newProcessor.EMBEDDEDPROCESSOR.Nitrox;
var octeon = newProcessor.EMBEDDEDPROCESSOR.Octeon;
if(hname = devicesFilter[ctr].Hostname ){
devicesFilter[ctr].Route.push({
VersionId: versionId,
Nitrox: nitrox,
Octeon: octeon,
EmbeddedName: name,
ProductId: productId
});
}
// }
}
}
} | [
"function setChildDevice(DEV,hostname,ctr){\n\tvar hname = hostname;\n\tvar InfoType = \"JSON\";\n\tif(InfoType == \"XML\"){\n\t\tvar device = DEV.childNodes;\n\t\tfor(var i = 0; i < device.length; i++){\n\t\t\tif(device[i].nodeName == \"LINECARD\" ){\n\t\t\t\tvar newLC = device[i];\n\t\t\t\tvar LineCardVid = newLC.getAttribute('LineCardVid');\n\t\t\t\tvar ProductId = newLC.getAttribute('ProductIdentifier');\n\t\t\t\tvar name = newLC.getAttribute('Name');\n\t\t\t\tvar num = newLC.getAttribute('Number');\n\t\t\t\tif(hname = devicesFilter[ctr].Hostname ){\n\t\t\t\t\tdevicesFilter[ctr].LineCard.push({\n\t\t\t\t\t\tLineCardVid:LineCardVid,\n\t\t\t\t\t\tProductId: ProductId,\n\t\t\t\t\t\tName: name,\n\t\t\t\t\t\tNumber: num \n\t\t\t\t\t});\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(device[i].nodeName == \"PORT\"){\n\t\t\t\tvar newPort = device[i];\n\t\t\t\tvar band = newPort.getAttribute('Bandwidth');\n\t\t\t\tvar speed = newPort.getAttribute('Speed');\n\t\t\t\tvar name = newPort.getAttribute('PortName');\n\t\t\t\tvar media = newPort.getAttribute('MediaType');\n\t\t\t\tif(hname = devicesFilter[ctr].Hostname ){\n\t\t\t\t\tdevicesFilter[ctr].Port.push({\n\t\t\t\t\t\tBandWidth: band,\n\t\t\t\t\t\tSpeed: speed,\n\t\t\t\t\t\tPortName: name,\n\t\t\t\t\t\tMediaType: media \n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}else{\n\t\tvar device = DEV;\n\t\tfor(var i = 0; i < device.length; i++){\n// if(device[i].nodeName == \"LINECARD\" ){\n var newLC = device[i];\n var LineCardVid = newLC.LINECARD.LineCardVid;\n var ProductId = newLC.LINECARD.ProductIdentifier;\n var name = newLC.LINECARD.Name;\n var num = newLC.LINECARD.Number;\n if(hname = devicesFilter[ctr].Hostname ){\n devicesFilter[ctr].LineCard.push({\n LineCardVid:LineCardVid,\n ProductId: ProductId,\n Name: name,\n Number: num\n });\n }\n// }\n// if(device[i].nodeName == \"PORT\"){\n var newPort = device[i];\n var band = newPort.PORT.Bandwidth;\n var speed = newPort.PORT.Speed;\n var name = newPort.PORT.PortName;\n var media = newPort.PORT.MediaType;\n if(hname = devicesFilter[ctr].Hostname ){\n devicesFilter[ctr].Port.push({\n BandWidth: band,\n Speed: speed,\n PortName: name,\n MediaType: media\n });\n }\n// }\n }\n\t}\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 loadFilterDevices(){\n\tvar query = {\"QUERY\":[{\"user\":globalUserName,\"domainname\":window['variable' + dynamicDomain[pageCanvas] ],\"zone\":\"Default\"}]};\n query = JSON.stringify(query);\n\t$.ajax({\n\t\turl: getURL(\"ConfigEditor\",\"JSON\"),\n\t\tdata : {\n\t\t\t\"action\": \"getdeviceinfo\",\n\t\t\t\"query\": query\n\t\t},\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\tgetDevInfoFilter(data);\t\t\n\t\t}\n\t});\n}",
"set deviceName(value) {}",
"function construct_device(devices_data, device_type){\n var device_data = get_device_data(devices_data, device_type);\n var device_map = {};\n return construct_device_inner(devices_data, device_data, device_map, '/');\n}",
"function createDevice(data) {\n var device = new models[\"Device\"](),\n deviceData = networkInfo.device[0];\n\n $.each(deviceData, function(key, value) {\n if (key !== \"value\") {\n device.set(key, value);\n }\n });\n\n return device;\n}",
"function addDevice(data) {\n try {\n if (data.id === \"SenseMonitor\" || data.id === 'solar') { //The monitor device itself is treated differently\n deviceList[data.id] = data;\n } else {\n\n //Ignore devices that are hidden on the Sense app (usually merged devices)\n if (data.tags.DeviceListAllowed == \"false\"){\n return 0\n }\n\n tsLogger(\"Adding New Device: (\" + data.name + \") to DevicesList...\");\n let isGuess = (data.tags && data.tags.NameUserGuess && data.tags.NameUserGuess === 'true');\n let devData = {\n id: data.id,\n name: (isGuess ? data.name.trim() + ' (?)' : data.name.trim()),\n state: \"unknown\",\n usage: -1,\n currentlyOn: false,\n recentlyChanged: true,\n lastOn: new Date().getTime()\n };\n\n if (data.id !== \"SenseMonitor\") {\n devData.location = data.location || \"\";\n devData.make = data.make || \"\";\n devData.model = data.model || \"\";\n devData.icon = data.icon || \"\";\n if (data.tags) {\n devData.mature = (data.tags.Mature === \"true\") || false;\n devData.revoked = (data.tags.Revoked === \"true\") || false;\n devData.dateCreated = data.tags.DateCreated || \"\";\n }\n }\n deviceList[data.id] = devData;\n deviceIdList.push(data.id);\n }\n } catch (error) {\n tsLogger(error.stack);\n }\n\n}",
"function createDataAutoD(idx){\n\n var d = autoDDevData[0];\n\tif(globalInfoType==\"XML\"){\n var autoDS = \"<MAINCONFIG>\";\n autoDS += \"<DEVICE \";\n autoDS += \"DeviceType='\"+d.DeviceType+\"' \";\n autoDS += \"Domain='\"+d.Domain+\"' \";\n autoDS += \"DomainId='\"+d.DomainId+\"' \";\n autoDS += \"ConsoleIp='\"+d.ConsoleIp+\"' \";\n autoDS += \"Manufacturer='\"+d.Manufacturer+\"' \";\n autoDS += \"ConsolePort='\"+d.ConsolePort+\"' \";\n autoDS += \"HostName='\"+d.HostName+\"' \";\n autoDS += \"LogsName='\"+d.LogsName+\"' \";\n autoDS += \"MTM='\"+d.MTM+\"' \";\n autoDS += \"ManagementIp='\"+d.ManagementIp+\"' \";\n autoDS += \"PartnerIp='\"+d.PartnerIp+\"' \";\n autoDS += \"ManagementPort='\"+d.ManagementPort+\"' \";\n\tautoDS += \"PartnerManufacturer='\"+d.PartnerManufacturer+\"' \";\n if(d.PartnerSlotNumber!=\"\"){d.PartnerSlotNumber = \";\"+d.PartnerSlotNumber}\n autoDS += \"PartnerSlotNumber='\"+d.PartnerSlotNumber+\"' \";\n autoDS += \"PartnerType='\"+d.PartnerType+\"' \";\n autoDS += \"Password='\"+d.Password+\"' \";\n autoDS += \"Username='\"+d.Username+\"' \";\n autoDS += \"SaveOption='\"+d.SaveOption+\"' \";\n autoDS += \"TotalPortsToSearch='\"+d.TotalPortsToSearch+\"' \";\n autoDS += \"Type='\"+d.Type+\"' \";\n autoDS += \"User='\"+d.User+\"' \";\n\tautoDS += \"></DEVICE>\";\n autoDS += \"</MAINCONFIG>\";\n\t}else{\n\n\tvar autoDS2 = \"{ 'MAINCONFIG': [{ 'DEVICE': [{ \";\n\tautoDS2 += \"'DeviceType': '\"+d.DeviceType+\"', \";\n\tautoDS2 += \"'Domain': '\"+d.Domain+\"', \";\n\tautoDS2 += \"'DomainId': '\"+d.DomainId+\"', \";\n\tautoDS2 += \"'ConsoleIp': '\"+d.ConsoleIp+\"', \";\n\tautoDS2 += \"'Manufacturer': '\"+d.Manufacturer+\"', \";\n\tautoDS2 += \"'ConsolePort': '\"+d.ConsolePort+\"', \";\n\tautoDS2 += \"'HostName': '\"+d.HostName+\"', \";\n\tautoDS2 += \"'LogsName': '\"+d.LogsName+\"', \";\n\tautoDS2 += \"'MTM': '\"+d.MTM+\"', \";\n\tautoDS2 += \"'ManagementIp': '\"+d.ManagementIp+\"', \";\n\tautoDS2 += \"'PartnerIp': '\"+d.PartnerIp+\"', \";\n\tautoDS2 += \"'ManagementPort': '\"+d.ManagementPort+\"', \";\n\tautoDS2 += \"'PartnerManufacturer': '\"+d.PartnerManufacturer+\"', \";\n\t//if(d.PartnerSlotNumber!=\"\"){d.PartnerSlotNumber = \";\"+d.PartnerSlotNumber;}\n\tautoDS2 += \"'PartnerSlotNumber': '\"+d.PartnerSlotNumber+\"', \";\n\tautoDS2 += \"'PartnerType': '\"+d.PartnerType+\"', \";\n\tautoDS2 += \"'Password': '\"+d.Password+\"', \";\n\tautoDS2 += \"'Username': '\"+d.Username+\"', \";\n\tautoDS2 += \"'SaveOption': '\"+d.SaveOption+\"', \";\n\tautoDS2 += \"'TotalPortsToSearch': '\"+d.TotalPortsToSearch+\"', \";\n\tautoDS2 += \"'Type': '\"+d.Type+\"', \";\n\tautoDS2 += \"'User': '\"+d.User+\"', \";\n\tautoDS2 += \"}] }] }\";\n\t}\n\n\tif(globalInfoType == \"XML\"){\n\t return autoDS;\n\t} else {\n\t return autoDS2;\n\t}\n}",
"function createLinkForDevicelist(device,device2){\n\tif(device.DeviceName != \"\" && device2.DeviceName != \"\"){\n\t\tif(lineName != \"\" && lineName != null && lineName != undefined && (lineName.toLowerCase() == \"ethernet\" || lineType == \"Any\")){\n\t\t\tcheckPortOfDeviceList2(device.ObjectPath,device2.ObjectPath);\n\t\t}else if(lineName != \"\" && lineName != null && lineName != undefined && lineName.toLowerCase() == \"ethernet2\"){\n\t\t\tgetPort2(device.ObjectPath,\"source\",\"L2\");\n\t\t\tgetPort2(device.ObjectPath,\"destination\",\"L2\");\n\t\t}else{\n\t\t\tcheckPortOfDeviceList(device.ObjectPath,\"source\");\n\t\t\tcheckPortOfDeviceList(device2.ObjectPath,\"destination\");\n\t\t}\n\t\tif(sourceSwitch != \"\" && destSwitch != \"\" && destSwitch.toLowerCase() != sourceSwitch.toLowerCase()){\n\t\t\tportflag = false;\n\t\t\tportflag2 = false;\n\t\t\tconnectedSwitch = true;\n\t\t}\n\t}else if(device.DeviceName != \"\" || device2.DeviceName != \"\"){\n\t\tif(device.DeviceName != \"\"){\n\t\t\tcheckPortOfDeviceList(device.ObjectPath,\"source\");\n\t\t\tportflag2 = true;\n\t\t}else if(device2.DeviceName != \"\"){\n\t\t\tcheckPortOfDeviceList(device2.ObjectPath,\"destination\");\n\t\t\tportflag = true;\n\t\t}\n\t\tif(device.DeviceName == \"\"){\n\t\t\tportflag2 = true;\n\t\t}else if(device2.DeviceName == \"\"){\n\t\t\tportflag = true;\n\t\t}\n\t}\n}",
"function createDevice(src){\n\tvar devPath = \"Device_\" + deviceCtr;\n\tidsArray = [];\n\tidsArray = getalldevicepath(idsArray);\n\tif(idsArray.length == 0){\n\t\tcreateConfigName(); \n\t}\n\tvar str ='';\n\tif(idsArray.indexOf(devPath) == -1){\n\t\tvar imageObj = new Image();\n\t\tvar srcN = ($(src).attr('src')).split(\"img\");\n\t\timageObj.src = dir+\"/img\"+srcN[1];\n\t\tvar id = $(src).attr('id');\n\t\tvar model = $(src).attr('model');\n\t\tvar manufac = $(src).attr('manufacturer');\n\t\tvar ostyp = $(src).attr('ostype');\n\t\tvar prdfmly = $(src).attr('productfamily');\n\t\tvar ipadd = $(src).attr('ipAdd');\n\t\tvar prot = $(src).attr('proto');\n\t\tvar hostnme = $(src).attr('hostname');\n\t\tvar devtype = $(src).attr('devtype');\n\t\tvar rTr=0;\n\t\tvar devices = getDevicesNodeJSON();\n\t\tfor(var a=0; a < devices.length; a++){\n\t\t\tif(devices[a].HostName == hostnme && hostnme != \"\" && devtype.toLowerCase() == \"dut\"){\n\t\t\t\treturn;\n\t\t\t}else if(devices[a].ManagementIp == ipadd && ipadd != \"\" && devtype.toLowerCase() == \"testtool\"){\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif(globalInfoType == \"JSON\"){\n\t\t\tsetJSONData();\n\t\t\tsetDeviceInformation(devPath,model,imageObj,manufac,ostyp,prdfmly,ipadd,prot,hostnme,devtype);\n\t\t\timgXPos+=70;\n \t\t\tidsArray.push(devPath);\n\t\t deviceCtr++;\n\t\t drawImage();\n\t\t}else{\n\t\t\tvar devices = devicesArr;\n\t\t\timageObj.onload = function() {\n\t\t\t\tsetDeviceInformation(devPath,model,imageObj,manufac,ostyp,prdfmly,ipadd,prot,hostnme);\n\t\t\t\timgXPos+=70;\n\t\t\t\tidsArray.push(devPath);\n\t\t\t\tdeviceCtr++;\n\t\t\t\tdrawImage();\n\t\t\t};\n\t\t}\n\t\tsetTimeout(function(){\n var ctrDck=0;\n for(var a=0; a < dynamicGreenRouletteArr.length; a++){\n var dkArr = dynamicGreenRouletteArr[a];\n if(dkArr.pageCanvas == pageCanvas){\n if(dkArr.model == model && dkArr.manufac == manufac && dkArr.ostyp == ostyp && dkArr.prdfmly == prdfmly && dkArr.ipadd==ipadd && dkArr.prot == prot && dkArr.hostnme == hostnme && dkArr.devtype == devtype){\n ctrDck++;\n a =dynamicGreenRouletteArr.length;\n }else if(dkArr.model == model && manufac == undefined && ostyp == undefined && prdfmly == undefined && ipadd== undefined && prot == undefined && hostnme && hostnme == undefined){\n ctrDck++;\n a =dynamicGreenRouletteArr.length;\n }\n }\n }\n if(ctrDck == 0){\n dynamicGreenRouletteArr.push({\"pageCanvas\":pageCanvas,\"devPath\":devPath,\"model\":model,\"imageObj\":imageObj,\"manufac\":manufac,\"ostyp\":ostyp,\"prdfmly\":prdfmly,\"ipadd\":ipadd,\"prot\":prot,\"hostnme\":hostnme,\"devtype\":devtype});\n }else{\n return;\n }\n\t\t\t$(\"#dockContainer\").show();\n\t\t\tvar text = createDeviceTooltip(devPath);\n\t\t\tstr += '<li>';\n\t\t\tstr += '<div class=\"divTooltipDock\">'+text+'</div>';\n\t\t\tstr += '<a href=\"#\" title=\"'+devPath+'\"><img id=\"'+devPath+hostnme+pageCanvas+'\" alt=\"'+devPath+' icon\" src=\"'+imageObj.src+'\" devpath=\"'+devPath+'\" class=\"dockImg\" width=\"62px\" hostname=\"'+hostnme+'\" proto=\"'+prot+'\" devtype=\"'+devtype+'\" ipAdd=\"'+ipadd+'\" productFamily=\"'+prdfmly+'\" ostype=\"'+ostyp+'\" manufacturer=\"'+manufac+'\" did=\"device\" model=\"'+model+'\"/></a>';\n\t\t\tstr += '</li>';\n\t\t\t$(\"#osxDocUL\").append(str);\n \n if(globalDeviceType != \"Mobile\"){\n $(\"#\"+devPath+hostnme+pageCanvas).click(function(e){\n\t\t\t\t\tcreatedev = this;\n\t\t \tvar srcN = getMiniModelImage($(this).attr('model'));\n\t\t\t\t\tsrcN = ($(srcN).attr('src')).split(\"img\")[1];\n\t\t\t\t\t$(\"#configContent\"+pageCanvas).css(\"cursor\",\"url(\"+dir+\"/img/\"+srcN+\") 10 18,auto\");\n clickIcon(this);\n });\n }else{\n $.mobile.document.on( \"taphold\",\"#\"+devPath+hostnme+pageCanvas, function(e){\n //$(\"#\"+devPath+hostnme).dblclick(function(e){\n createdev = this;\n \tclickIcon(this);\n\t\t });\n }\n\t\t\tvar el = $(\"#dockWrapper\");\n var w = el.width() + 40;\n var dvded = -Math.abs(w / 2);\n var css = {\"position\": 'absolute', \"left\": \"50%\",\"width\": w+\"px\",\"margin-left\":dvded};\n $(\"#dockContainer\").css(css);\n\t\t\t\n\t\t},100);\t\t\n\t\taddEvent2History(\"Created a device.\");\n\t}else{\n\t\tdeviceCtr++;\n\t\tcreateConfigName();\n\t\tcreateDevice(src);\n\t}\n}",
"function DmDeviceList(params) {\n cuiInitNode(this);\n var self = this;\n\n var autoRefreshInterval = (params.autoRefreshInterval ? params.autoRefreshInterval : 20000);\n\n var navBar;\n var canvas;\n var selectedDevice = null;\n\n var deviceQuery;\n var _deviceQuery;\n\n var devices;\n var interval;\n\n this.setDeviceQuery = function(__deviceQuery) {\n _deviceQuery = __deviceQuery;\n return this;\n }\n\n this.setFilterName = function(__filterName) {\n navBar.setFilterName(__filterName);\n return this;\n }\n\n this.onConstruct = function() {\n\n $deviceList = $(\"<div>\");\n\n navBar = new DmDeviceListNavBar({\n onPageChange: function(page) {\n self.markDirty(\"page\").refresh();\n },\n filterName: \"All\",\n });\n\n var $container = $(\"<div>\");\n\n canvas = new CuiCanvas({\n preceededBy: navBar,\n relativeTo: $container,\n contents: $deviceList,\n });\n\n\n $container.html(cuiCompose([navBar, canvas]));\n\n return $container;\n }\n\n function constructTable(_devices) {\n $table = $(\"<table border=0 class='dm_devices_page dm_device_table' cellspacing=0>\\\n <tr>\\\n <th align=left>\\\n UUID\\\n </th>\\\n <th align=left>\\\n </th>\\\n <th align=left>\\\n Device Name\\\n </th>\\\n <th align=left>\\\n Activity\\\n </th>\\\n <th align=left>\\\n WebSocket\\\n </th>\\\n <th align=left>\\\n Cloud Vars\\\n </th>\\\n <th align=left class='dm_hide_below_1024w' width=40%>\\\n <div style='display:inline-block; min-width:368px; height:1px'>\\\n </th>\\\n </tr>\\\n </table>\");\n\n for (var i = 0; i < _devices.length; i++) {\n var device = _devices[i];\n var lastActivity = device.lastActivitySecondsAgo();\n var selected = (selectedDevice && (selectedDevice.id() == device.id())) ? \"class=selected\" : \"\";\n $row = $(\"<tr \" + selected + \">\\\n <td class='dm_device_table dm_uuid' nowrap style='overflow: hidden; font-size:12px; font-family:monospace'><div style='position:relative; vertical-align=text-baseline;'><div style='display: inline-block;position:absolute;'>\" + device.id() + \"</div> </div></td>\\\n <td width=1 style='padding-left:0px'>\\\n <div class='dm_invisible_above_1260w' style='font-weight:300'>...</div>\\\n </td>\\\n <td>\\\n \" + device.name() + \"\\\n </td>\\\n <td>\\\n \" + (CanopyUtil_LastSeenSecondsAgoText(lastActivity)) + \"\\\n </td>\\\n <td>\\\n \" + (CanopyUtil_ConnectionStatusText(lastActivity, device.websocketConnected())) + \"\\\n </td>\\\n <td>\\\n \" + device.vars().length + \"\\\n </td>\\\n <td class='dm_hide_below_1024w' align=left width=40%>\\\n </td>\\\n </tr>\");\n $row.off('click').on('click', function(idx, device) {\n return function() {\n selectedDevice = device;\n if (params.onSelect) {\n params.onSelect(idx, device);\n }\n self.markDirty(\"table\").refresh();\n }\n }(i, device));\n $table.append($row);\n }\n return $table;\n }\n\n this.onRefresh = function($me, dirty, live) {\n var refresh = dirty(\"page\");\n\n if (this.liveStatus() == CUI_LIVE_STATUS_TRANSITION_TO_LIVE) {\n refresh = true;\n }\n if (deviceQuery != _deviceQuery) {\n refresh = true;\n deviceQuery = _deviceQuery;\n }\n\n if (refresh) {\n var start = navBar.startIdx();\n var count = navBar.numItemsPerPage();\n deviceQuery.count().onDone(function(result, data) {\n if (result != CANOPY_SUCCESS) {\n alert(\"Problem fetching device count: \" + data.errorMsg);\n return;\n }\n navBar.setNumItems(data.count).refresh();\n deviceQuery.getMany(start, count).onDone(function(result, data) {\n if (result != CANOPY_SUCCESS) {\n alert(\"Problem fetching devices: \" + data.errorMsg);\n return;\n }\n \n devices = data.devices;\n\n /*// update selectedDevice to use the new CanopyDevice object.\n for (var i = 0; i < devices.length; i++) {\n if (selectedDevice && (selectedDevice.id() == devices[i].id())) {\n selectedDevice = devices[i];\n break;\n }\n }\n if (i == devices.length) {\n selectedDevice = null;\n }*/\n\n $deviceList.html(constructTable(data.devices));\n });\n });\n } else if (dirty(\"table\")) {\n // TODO: it is very inefficient to regenerate the whole table all\n // the time.\n $deviceList.html(constructTable(devices));\n }\n\n cuiRefresh([navBar, canvas], live);\n }\n\n this.onSetupCallbacks = function() {\n if (!interval) {\n interval = setInterval(function() {\n self.markDirty(\"page\");\n self.refresh();\n }, autoRefreshInterval);\n }\n }\n}",
"function checkNewDeviceHostName(model,hostname,managementip,consoleip,attr){\n\tvar query = \"{'QUERY':[{'User':'\"+globalUserName+\"','DomainName':'\"+window['variable' + dynamicDomain[pageCanvas] ]+\"','HostName':'\"+hostname+\"','Model':'\"+model+\"','ManagementIp':'\"+managementip+\"','ConsoleIp':'\"+consoleip+\"','Server':'\"+attr+\"'}]}\"\n\t$.ajax({\n\t\turl: getURL(\"ConfigEditor\",\"JSON\"),\n\t\tdata : {\n\t\t\t\"action\": \"checkhostname\",\n\t\t\t\"query\":query,\n\t\t},\n\t\tdataType: 'html',\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tsuccess: function(data) {\n\t\t\t//var dat = data.replace(/'/g,'\"'); \n\t\t\t//var dat2 = $.parseJSON(dat);\n\t\t\t//var ret =da2.RESULT[0].Result\n\t\t\tif(data){\n\t\t\t\treturn data;\n\t\t\t}else{\n\t\t\t\talerts(ret);\n\t\t\t}\n\t\t}\n\t});\n}",
"function updateDeviceSA(device) {\n $.each(jsPlumbInstance.getConnections({\n source: device.attr(\"id\")\n }), function(index, connection) {\n var target = $(connection.target);\n if (target.attr(\"class\").indexOf(\"device\") == -1) {\n target.data(\"device\", device.data(\"name\"));\n target.data(\"deviceId\", device.data(\"id\"));\n }\n });\n }",
"function applyDevicePackets(device, packet_temp, packet_dire) {\r\n device.device.temperature_value = packet_temp.value;\r\n device.device.direction_value = packet_dire.value;\r\n return device;\r\n}",
"function updateDevice(device, payload){\n device.user_id = payload.user_id;\n device.uuid = payload.uuid;\n device.os_id = payload.os_id;\n device.createdAt = payload.createdAt;\n device.modifiedAt = Date.now();\n device.model = payload.model;\n}",
"function deleteDevSub(imgId){\n\tif(globalInfoType == \"JSON\"){\n \t\tvar devices = getDevicesNodeJSON();\n\t\tfor(var a=0; a<devices.length;a++){\n\t\t\tif(devices[a].Status == \"Reserved\" && devices[a].ObjectPath == imgId){\n\t\t\t\tdevices[a].UpdateFlag = \"delete\";\n\t\t\t\tdeleteLinkFromDev(devices[a].ObjectPath);\n\t\t\t\tdevices.splice(a,1);\n\t\t\t\taddEvent2History(\"Device deleted\");\n\t\t\t\ta = devices.length;\n\t\t\t}else if(devices[a].ObjectPath == imgId && devices[a].Status != \"Reserved\"){\n\t\t\t\tdeleteLinkFromDev(devices[a].ObjectPath);\n\t\t\t\tdevices.splice(a,1);\n\t\t\t\taddEvent2History(\"Device deleted\");\n\t\t\t\ta = devices.length;\n\t\t\t}\n\t\t}\n \t}\n\tdrawImage();\n}",
"function checkdataForConsole(device,devicesArr,data){\n\tdata = data.replace(/'/g,'\"');\n\tvar json = jQuery.parseJSON(data);\n\tvar mainconfig = json.MAINCONFIG[0];\n\tif(mainconfig.PASS != null && mainconfig.PASS != undefined && mainconfig.FAILED != null && mainconfig.FAILED != undefined){\n\t\tvar messageArray = new Array();\n\t\tvar devArray = [];\n\t\tvar devIdArray = [];\n\t\tfor(var f=0; f<mainconfig.FAILED.length; f++){\n\t\t\tvar devId = mainconfig.FAILED[f].DeviceId;\n\t\t\tvar message = mainconfig.FAILED[f].Message;\n\t\t\tvar flag = false;\n\t\t\tfor(var t=0; t<device.length; t++){\n\t\t\t\tif(devId == device[t].DeviceId){\n\t\t\t\t\tdevice.splice(t,1);\n\t\t\t\t\tflag = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!flag){\n\t\t\t\tif ($.inArray(devId,devIdArray) == -1) {\n\t\t\t\t\tdevIdArray.push(devId);\n\t\t\t\t}\t\t\t\t\t\n\t\t\t}\n\t\t\tif ($.inArray(message,messageArray) == -1) {\n\t\t\t\tmessageArray.push(message);\n\t\t\t}\t\t\t\t\t\n\t\t\t\t\n\t\t}\n\t\tfor(var f=0; f<mainconfig.PASS.length; f++){\n\t\t\tvar sessionid = mainconfig.PASS[f].SessionId;\n\t\t\tvar devId = mainconfig.PASS[f].DeviceId;\n\t\t\tfor(var t=0; t<device.length; t++){\n\t\t\t\tif(devId == device[t].DeviceId){\n\t\t\t\t\tdevice[t].SessionId = sessionid;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(messageArray.length){\n\t\t\tvar msg = messageArray.join(\"\") + \".Do you still want to continue?\";\n\t\t\talerts(msg,\"showConsolePopUp(device,devicesArr)\",\"console\");\n\t\t\treturn;\n\t\t}\n\t}else if(mainconfig.PASS != null && mainconfig.PASS != undefined){\n\t\tfor(var f=0; f<mainconfig.PASS.length; f++){\n\t\t\tvar sessionid = mainconfig.PASS[f].SessionId;\n\t\t\tvar devId = mainconfig.PASS[f].DeviceId;\n\t\t\tfor(var t=0; t<device.length; t++){\n\t\t\t\tif(devId == device[t].DeviceId){\n\t\t\t\t\tdevice[t].SessionId = sessionid;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tshowConsolePopUp(device,devicesArr);\n\t}else if(mainconfig.FAILED != null && mainconfig.FAILED != undefined){\n\t\tvar messageArray = new Array();\n\t\tvar devArray = [];\n\t\tvar devIdArray = [];\n\t\tfor(var f=0; f<mainconfig.FAILED.length; f++){\n\t\t\tvar devId = mainconfig.FAILED[f].DeviceId;\n\t\t\tvar message = mainconfig.FAILED[f].Message;\n\t\t\tif ($.inArray(message,messageArray) == -1) {\n\t\t\t\tmessageArray.push(message);\n\t\t\t}\t\t\t\t\t\n\t\t\t\t\n\t\t}\n\t\tif(messageArray.length){\n\t\t\tvar msg = messageArray.join(\"\");\n\t\t\talerts(msg);\n\t\t\treturn;\n\t\t}\n\t}\n}",
"function devSanInit(){\n\tvar devStat='';\n\tvar devSanityStat='';\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tfor(var i = 0; i < devices.length; i++){\n\t\tdevStat+=\"<tr>\";\n\t\tdevStat+=\"<td>\"+devices[i].HostName+\"</td>\";\n\t\tdevStat+=\"<td>\"+devices[i].ManagementIp+\"</td>\";\n\t\tdevStat+=\"<td>\"+devices[i].ConsoleIp+\"</td>\";\n\t\tdevStat+=\"<td>\"+devices[i].Manufacturer+\"</td>\";\n\t\tdevStat+=\"<td>\"+devices[i].Model+\"</td>\";\n\t\tdevStat+=\"<td>Init</td>\";\n\t\tdevStat+=\"<td>Waiting..</td>\";\n\t\tdevStat+=\"<td>Waiting..</td>\";\n\t\tdevStat+=\"<td>Waiting..</td>\";\n\t\tdevStat+=\"</tr>\";\n//2nd Table of Device Sanity\n\t\tdevSanityStat+=\"<tr>\";\n\t\tdevSanityStat+=\"<td></td>\";\n\t\tdevSanityStat+=\"<td>\"+devices[i].HostName+\"</td>\";\n\t\tdevSanityStat+=\"<td>\"+devices[i].ManagementIp+\"</td>\";\n\t\tdevSanityStat+=\"<td>\"+devices[i].ConsoleIp+\"</td>\";\n\t\tdevSanityStat+=\"<td>\"+devices[i].OSVersion+\"</td>\";\n\t\tdevSanityStat+=\"<td>Init</td>\";\n\t\tdevSanityStat+=\"<td>Waiting..</td>\";\n\t\tdevSanityStat+=\"</tr>\";\n\n\t}\n\t$(\"#devSanTableStat > tbody\").empty().append(devSanityStat);\n\t$(\"#devSanTable > tbody\").empty().append(devStat);\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\t$('#devTotalNo').empty().append(devices.length);\n\tif(globalDeviceType == \"Mobile\"){\n\t\t$(\"#devSanTableStat\").table(\"refresh\");\n\t\t$(\"#devSanTable\").table(\"refresh\");\n\t}\n\treturn;\n}",
"function openConsoleDevice(){\n\tif(glblDevMenImg != undefined && glblDevMenImg != null){\n\t\t$('#deviceMenuPopUp').dialog('close');\n\t}\n\tif(globalInfoType == \"JSON\"){\n\t\tdevicesArr = getDevicesNodeJSON();\n\t}\n\tif(devicesArr.length == 0){\n\t\talerts(\"No devices available in the canvas.\");\n\t}\n\tvar myArray = new Array();\n\tif(glblDevMenImg != undefined && glblDevMenImg != null){\n\t\tvar devArray = new Array()\n\t\tfor(var t=0; t<devicesArr.length; t++){\n\t\t\tif(devicesArr[t].ObjectPath == glblDevMenImg){\n\t\t\t\tdevArray.push(devicesArr[t]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tglblDevMenImg = null;\n\t\tdevicesArr = devArray;\n\t}\n\tdevicesArr = getAllServerAndDutCommitted(devicesArr);\n\tif(devicesArr.length == 0){\n\t\talerts(\"Devices in the canvas are not allowed to open a console.\");\n\t}else if(devicesArr.length == 1){\n\t\tvar type = \"Telnet\";\n\t\tif(devicesArr[0].DeviceType == \"Server\"){\n\t\t\ttype = \"SSH\";\n\t\t}\n\t\tmyArray.push({\n\t\t\tDeviceId:devicesArr[0].DeviceResId,\n\t\t\tDeviceName: devicesArr[0].DeviceName,\t\n\t\t\tType: type,\t\n\t\t\tSessionId:''\t\n\t\t});\t\n\t\tshowDevicetoSelect(devicesArr,myArray);\n\t\t//loadOpenConsole(myArray,devicesArr);\n\t}else if(devicesArr.length > 1){\n\t\tfor(var t=0; t<devicesArr.length; t++){\n\t\t\tvar type = \"Telnet\";\n\t\t\tif(devicesArr[t].DeviceType == \"Server\"){\n\t\t\t\ttype = \"SSH\";\n\t\t\t}\n\t\t\tmyArray.push({\n\t\t\t\tDeviceId:devicesArr[t].DeviceResId,\n\t\t\t\tDeviceName: devicesArr[t].DeviceName,\t\n\t\t\t\tType: type,\n\t\t\t\tSessionId:''\t\n\t\t\t});\t\n\t\t}\n\t\tshowDevicetoSelect(devicesArr,myArray);\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
saveRemoteCookiesInSession As distinct from the cookies we set in the user browser, we need to fake a cookie jar for the cookies of the remote gallery. Storing this in session allows it to persist across multiple user requests. This is necessary because loading images from the remote gallery requires that you have a cookie set by the framing page, so we have to make the scraper pretend that it is one set of browser requests by saving that cookie. | function saveRemoteCookiesInSession(req, cookies) {
if (!req.session.remoteCookieStore) {
req.session.remoteCookieStore = [];
} else {
req.session.remoteCookieStore = [];
}
cookies.forEach(function(remoteCookie) {
req.session.remoteCookieStore.push(remoteCookie);
if (config.system.debug) {
console.log("Saved cookie: " + remoteCookie);
}
});
} | [
"async function propagateBrowserCookieValues() {\n\n let zitiCookies = await ls.getWithExpiry(zitiConstants.get().ZITI_COOKIES);\n if (isNull(zitiCookies)) {\n zitiCookies = {}\n }\n\n // Obtain all Cookie KV pairs from the browser Cookie cache\n\tlet browserCookies = Cookies.get();\n\tfor (const cookie in browserCookies) {\n\t\tif (browserCookies.hasOwnProperty( cookie )) {\n\t\t\tzitiCookies[cookie] = browserCookies[cookie];\n\t\t}\n\t}\n\n await ls.setWithExpiry(zitiConstants.get().ZITI_COOKIES, zitiCookies, new Date(8640000000000000));\n}",
"function newSession(callback) {\n browser.get(\"http://www.linkedin.com/\", function() {\n browser.deleteAllCookies(function () {\n browser.refresh(function() {\n callback();\n });\n });\n });\n}",
"function saveToCookies()\n{\n const THREE_YEARS_IN_SEC = 94670777;\n chrome.cookies.set({\n \"url\": DOTABUFF_MATCH_LINK+'*',\n \"name\": \"player_id\",\n \"value\": MY_ID,\n \"expirationDate\": ((new Date().getTime() / 1000) + THREE_YEARS_IN_SEC) });\n chrome.cookies.set({\n \"url\": DOTABUFF_MATCH_LINK+'*',\n \"name\": \"whitelisted_ids_length\",\n \"value\": WHITELISTED_IDS.length.toString(),\n \"expirationDate\": ((new Date().getTime() / 1000) + THREE_YEARS_IN_SEC)});\n for (let index = 0; index < WHITELISTED_IDS.length; index++) {\n const WHITELISTED_ID = WHITELISTED_IDS[index];\n chrome.cookies.set({\n \"url\": DOTABUFF_MATCH_LINK+'*',\n \"name\": \"whitelisted_id\"+index.toString(),\n \"value\": WHITELISTED_ID.toString(),\n \"expirationDate\": ((new Date().getTime() / 1000) + THREE_YEARS_IN_SEC) });\n }\n}",
"function getCookies()\n {\n var retPromise = q.defer();\n\n var options = {\n url: REST_URL,\n method: \"GET\",\n };\n request(options, function(error, response, body) {\n // console.log(\"Response: \", response);\n\n console.log(\"Cookies: \".green,response.headers['set-cookie']);\n var cookies = (response.headers['set-cookie']).toString();\n var jsessionid = cookies.split(';');\n jsessionid = jsessionid[0];\n console.log(\"My Cookie:\",jsessionid);\n\n var options = {\n url: BASE_URL+ jsessionid,\n method: \"POST\"\n };\n request(options, function(error, response, body) {\n retPromise.resolve(body);\n });\n // console.log(\"Response Body: \".yellow,body);\n });\n\n return retPromise.promise;\n }",
"static clearCookie() {\n var cookies = document.cookie.split(\";\");\n\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i];\n var eqPos = cookie.indexOf(\"=\");\n var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;\n if (name.trim().toLowerCase() == 'voting-username')\n document.cookie = name + \"=;expires=Thu, 01 Jan 1970 00:00:00 GMT\";\n }\n \n }",
"async function redirectInIframeAndDumpCookies(mainUrl, redirectUrl, description) {\n helper.onceRequest(new RegExp(mainUrl)).fulfill({\n responseCode: 200,\n body: btoa(\"<html></html>\")\n });\n // Navigate to the main page URL.\n await dp.Page.navigate({url: mainUrl});\n // Load an iframe with `redirectUrl` which then redirects to a.test.\n session.evaluate(appendIframeScript(redirectUrl));\n const request = await helper.onceRequest(cookieUrl).matched();\n testRunner.log(`Cookies for ${description}:`);\n testRunner.log(request.request.headers['Cookie']);\n dp.Fetch.fulfillRequest({requestId: request.requestId, responseCode: 200});\n }",
"_initCookies() {\n\n const KEY = window.btoa('' + Math.random() * Math.random() * Math.random() * Math.PI),\n COOKIE = new Cookies(),\n PREFIX = 'default-wid';\n // expire cookie a month from now\n let expDate = new Date(Date.now());\n expDate.setDate(expDate.getDate() + 30);\n COOKIE.set(PREFIX, KEY, { path : '/', expires : expDate });\n }",
"function getAllCookies() {\n const cookiesString = document.cookie || '';\n const cookiesArray = cookiesString.split(';')\n .filter(cookie => cookie !== '')\n .map(cookie => cookie.trim());\n\n // Turn the cookie array into an object of key/value pairs\n const cookies = cookiesArray.reduce((acc, currentValue) => {\n const [key, value] = currentValue.split('=');\n const decodedValue = decodeURIComponent(value); // URI decoding\n acc[key] = decodedValue; // Assign the value to the object\n return acc;\n }, {});\n\n return cookies || {};\n}",
"function writeCookies(hostname, cookies) {\n getCurrentTabUrl(function(url) {\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i];\n\n chrome.cookies.remove({\n \"url\": url,\n \"name\": cookie.name\n });\n chrome.cookies.set({\n \"url\": url,\n \"name\": cookie.name,\n \"value\": cookie.value,\n \"domain\": cookie.domain,\n \"path\": cookie.path,\n \"secure\": cookie.secure,\n \"httpOnly\": cookie.httpOnly,\n \"expirationDate\": cookie.expirationDate,\n \"storeId\": cookie.storeId\n });\n }\n });\n\n chrome.tabs.getSelected(null, function(tab) {\n var code = 'window.location.reload();';\n chrome.tabs.executeScript(tab.id, {code: code});\n });\n}",
"function extractWebSession(sessionWrapper) {\n\t// You can add any objects to the session as required\n\tsessionWrapper.getSession().setValue(\"value1\", \"Example 1\");\n\tsessionWrapper.getSession().setValue(\"value2\", \"Example 2\");\n}",
"function removeAllCookiesStaticPages(){\n\n var cookies = $.cookie();\n var result = false;\n for(var cookie in cookies){\n\n if($.removeCookie(cookie, { path: '/afya-portal/'})||$.removeCookie(cookie, { path: '/afya-portal'})){\n\n result = true;\n }\n }\n //remove all session store variables\n afyaSessionStore().removeAll();\n //Re-paint the header and footer\n initializePage();\n}",
"function cookieFromFilterpanel(){\n var ch = [];\n if ($j('.shop-filter-panel .filter-toggle').hasClass(\"open\")){\n ch.push(true);\n }\n\n $j.cookie(\"filterpanelCookie\", ch.join(','));\n}",
"function savePizzaState() {\n console.log(\"Saving pizza state\");\n Cookies.set(\"version\", CURRENT_VERSION, { expires: 365, path: '/' });\n Cookies.set(\"pizza\", document.getElementById('id_pizza_style').value, { expires: 365, path: '/' });\n Cookies.set(\"dough_balls\", document.getElementById('id_dough_balls').value, { expires: 365, path: '/' });\n Cookies.set(\"size\", document.getElementById('id_size').value, { expires: 365, path: '/' });\n}",
"async function loadIframeAndDumpCookies(mainUrl, description) {\n // Navigate to the main page URL.\n helper.onceRequest(new RegExp(mainUrl)).fulfill({\n responseCode: 200,\n body: btoa(\"<html></html>\")\n });\n await dp.Page.navigate({url: mainUrl});\n // Load iframe with a.test.\n session.evaluate(appendIframeScript(cookieUrl));\n const request = await helper.onceRequest(cookieUrl).matched();\n testRunner.log(`Cookies for ${description}:`);\n testRunner.log(request.request.headers['Cookie']);\n dp.Fetch.fulfillRequest({requestId: request.requestId, responseCode: 200});\n }",
"function bakeCookies() {\n\n}",
"send() {\n let session = this.session;\n if (!session || !session.isDestroyed) {\n return super.send.apply(this, arguments);\n }\n let sessId = session.id,\n cookieSessionId = storeObj.signId(sessId),\n cookieOpt = getCookieOptions();\n if (session.isDestroyed()) { // if the session is destroyed, we have to remove it.\n cookieOpt.expires = new Date(1); //old expiration\n let delCookie = cookie.serialize(opt.cookieName, cookieSessionId, cookieOpt);\n this._addCookie(delCookie);\n storeObj.destroySession(sessId, (e) => {\n if (e && e.ns !== 'SESSION') logger.warn('Failed to remove session ' + sessId + ' from store.');\n });\n session.clear();\n return super.send.apply(this, arguments);\n }\n if (this[ignoreSave]) {\n return super.send.apply(this, arguments);\n }\n // save it.\n let args = arguments;\n storeObj.saveSession(session, (e, wasSaved) => {\n if (e && e.ns !== 'SESSION') {\n logger.warn(`Failed to store session '${sessId}' to store. [${e.code} - ${e.message}]`);\n }\n if (wasSaved) {\n cookieOpt.expires = new Date(Date.now() + opt.expire * 1000);\n let reqCookie = cookie.serialize(opt.cookieName, cookieSessionId, cookieOpt);\n this._addCookie(reqCookie);\n }\n super.send.apply(this, args);\n });\n }",
"function archiveSessionStorageToLocalStorage() {\n var backup = {};\n\n for (var i = 0; i < sessionStorage.length; i++) {\n backup[sessionStorage.key(i)] = sessionStorage[sessionStorage.key(i)];\n }\n\n localStorage[\"sessionStorageBackup\"] = JSON.stringify(backup);\n sessionStorage.clear();\n }",
"function sessionSetup(req, res, next){\n console.log(req.cookies.sid);\n if (req.cookies.sid === undefined){\n var uuid = uuidv4();\n var isAuthenticated = false;\n var id = false;\n var email = false;\n var username = false;\n var src = false;\n var client = redis.createClient();\n client.HMSET(uuid, {\n \"isAuthenticated\": isAuthenticated,\n \"id\": id,\n \"email\": email,\n \"username\": username,\n \"src\": src,\n \"sid\": uuid,\n \"videoCreated\": false,\n \"videoUpdated\": false,\n \"videoDeleted\": false,\n \"userCreated\": false,\n \"userUpdated\": false,\n }, function(){\n client.quit();\n req.session = {\n \"isAuthenticated\": isAuthenticated,\n \"id\": id,\n \"email\": email,\n \"username\": username,\n \"src\": src,\n \"sid\": uuid,\n \"videoCreated\": false,\n \"videoUpdated\": false,\n \"videoDeleted\": false,\n \"userCreated\": false,\n \"userUpdated\": false,\n }\n res.cookie('sid', uuid, { signed: false, maxAge: 60 * 1000, httpOnly: true });\n next();\n });\n } else {\n var client = redis.createClient();\n client.hgetall(req.cookies.sid, function (err, obj) {\n req.session = obj;\n client.quit();\n next();\n });\n\n\n }\n}",
"function deleteCookies() {\n\tchrome.cookies.getAll({ domain: \"nytimes.com\" }, function(cookies) { \n\t\tfor (var i in cookies) {\n\t\t\tvar div = document.createElement(\"div\");\n\t\t\tdiv.innerHTML = \"Removing: \" + extrapolateUrlFromCookie(cookies[i]);\n\t\t\tdocument.body.appendChild(div);\n\t\t\tchrome.cookies.remove({ url: extrapolateUrlFromCookie(cookies[i]),\n\t\t\t\t\t\t\t\t\tname: cookies[i].name});\n\t\t}\n\t})\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function splits the given Number of Seats and Aisle seats and constructs the srray which holds the Avalable Seats. lets say we have NumberOfSeats = 10 i.e. 09 Seats and [0,5,6,9] as aisle seats then the Object constructed will be [[0,1,2,3,4,5][6,7,8,9]] | initAvailableSeats(seatInfo) {
let availableSeats = {};
for (const key in seatInfo) {
if (seatInfo.hasOwnProperty(key)) {
const row = seatInfo[key];
let seats = [...Array(row.numberOfSeats || 0).keys()];
let aisles = row.aisleSeats || [];
let available = [];
if (!aisles.includes(0)) {
aisles.splice(0, 0, 0);
}
if (!aisles.includes(row.numberOfSeats - 1)) {
aisles.push(row.numberOfSeats - 1);
}
let originalAisles = [];
for (let i=0; i < aisles.length; i++) {
let aisle = aisles[i];
if (aisle !== 0 || aisle !== row.numberOfSeats - 1) {
originalAisles.push(aisle);
if (aisle > 0 && aisle + 1 < row.numberOfSeats - 1) {
originalAisles.push(aisle + 1);
if (aisles.includes(aisle + 1)) {
i++;
}
}
} else {
originalAisles.push(aisle);
}
}
if (row.numberOfSeats === 1) {
available[0] = [0];
} else {
while (originalAisles.length > 0) {
let j = originalAisles.pop() + 1;
let i = originalAisles.pop();
let insert = seats.splice(i, j);
available.splice(0, 0, insert);
}
}
availableSeats[key] = available;
}
}
return availableSeats;
} | [
"function prepareDataForReserve(data){\n var arr=[];\n for(let o in data[\"seats\"])\n {\n let c=(data[\"seats\"][o]);\n c.map(d1=>{\n let ret=o+\"\";\n ret+=d1;\n arr.push(ret);\n });\n\t\n }\n return arr;\n}",
"function draw_seats() {\n var sections = window.project.settings.airplane;\n var xOff = Math.abs(delta);\n var height = 0;\n\n function addRowOfSeats(count, yOff, maxCount) {\n var seatIndex;\n var padding = Math.min(0, 0.5 * delta * (maxCount - count));\n\n yOff += padding;\n for (seatIndex = 0; seatIndex < count; seatIndex++) {\n seat_positions.push({'x': xOff, 'y': yOff});\n\n var circle = svgContainer.append('circle')\n .attr('cx', xOff)\n .attr('cy', yOff)\n .attr('r', 0.4 * Math.abs(delta))\n .classed('seat', true);\n yOff += delta;\n height = Math.min(yOff, height);\n }\n return yOff + padding;\n }\n\n sections.forEach(function (section) {\n var rowIndex, i, yOff;\n\n for (rowIndex = 0; rowIndex < section.rows; rowIndex++) {\n yOff = delta;\n for (i = 0; i < section.seats.length; i++) {\n yOff = addRowOfSeats(\n section.seats[i],\n yOff,\n max_seats[i]\n );\n\n if (i < section.seats.length - 1) {\n aisle_positions.push({'x': xOff, 'y': yOff});\n yOff += delta;\n }\n\n }\n xOff += Math.abs(delta);\n }\n });\n\n svgContainer.attr(\n 'viewBox',\n '0 ' + height + ' ' + xOff + ' ' + Math.abs(height)\n );\n }",
"componentDidMount() {\n const { possibleSeats } = this.state;\n const seats = [];\n for(let i = 0; i < 88; i +=1) {\n seats.push(randomItem(possibleSeats));\n }\n this.setState({\n seats,\n })\n }",
"function getAvailableSeatsWithChoice(screen,numSeats,choice) {\n\n\treturn new Promise(function (resolve, reject) {\n\t\t//console.log(screen);\n\t\tvar availSeats = \n\t\t{\n\t\t}\n\t\tvar rowNo = choice[0]\n\t\tvar preferSeatNo = choice.substr(1, choice.length)\n\t\tconsole.log(rowNo)\n\t\tconsole.log(preferSeatNo)\n\n\t\tvar seatsInRow = []\n\t\tif(rowNo == \"A\") {\n\t\t\tseatsInRow= screen[0].screenInfo.A.rowStatus\n\t\t\tavailSeats = { \"A\":[]}\n\t\t}\n\t\tif(rowNo == \"B\"){\n\t\t seatsInRow= screen[0].screenInfo.B.rowStatus\n\t\t availSeats = { \"B\":[]}\n\t\t}\n\t\tif(rowNo == \"D\"){\n\t\t seatsInRow= screen[0].screenInfo.D.rowStatus\n\t\t availSeats = { \"D\":[]}\n\t\t}\n\t\t\n\n\t\tconsole.log(seatsInRow)\n\n\t\tif(numSeats ==1 && preferSeatNo < seatsInRow.length) {\n\t\t\tconsole.log(seatsInRow[parseInt(preferSeatNo)])\n\t\t\tif(seatsInRow[parseInt(preferSeatNo)].seatStatus == 'unreserved') {\n\t\t\t\tavailSeats[rowNo].push(preferSeatNo)\n\t\t\t\tresolve(availSeats)\n\t\t\t}\n\t\t\telse {\n\t\t\t\treject(\"seats are not available for this choice\") //can give some err\n\t\t\t}\n\t\t}\n\t\t\n\t\telse if(preferSeatNo < seatsInRow.length){\n\n\t\t\tif(seatsInRow[parseInt(preferSeatNo)].seatStatus==\"unreserved\" ) {\n\t\t\t //case 1 starts from prefered seat number\n\t\t\t var count = 0;\n\t\t\t for(var s = parseInt(preferSeatNo) ; s< seatsInRow.length ; s++) {\n\t\t\t\tif(count >= numSeats) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(seatsInRow[s].seatStatus == \"unreserved\" && seatsInRow[s].isAisel == false ) {\n\t\t\t\t\tconsole.log(seatsInRow[s])\n\t\t\t\t\tcount++;\n\t\t\t\t\tavailSeats[rowNo].push(seatsInRow[s].seatNo)\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t }\n\t\t\t console.log(\"count =\" +count)\n\t\t\t console.log(\"after 1st case \" + availSeats)\n\t\t\t if(availSeats[rowNo].length >= numSeats) {\n\t\t\t\tresolve(availSeats)\n\t\t\t }\n\t\t\t //end of case 1\n\n\n\t\t\t //case 2 prefered seat number is the last\n\t\t\t\tcount = 0;\n\t\t\t\tif(rowNo == \"A\") {\n\t\t\t\tseatsInRow= screen[0].screenInfo.A.rowStatus\n\t\t\t\tavailSeats = { \"A\":[]}\n\t\t\t\t}\n\t\t\t\tif(rowNo == \"B\"){\n\t\t\t\tseatsInRow= screen[0].screenInfo.B.rowStatus\n\t\t\t\tavailSeats = { \"B\":[]}\n\t\t\t\t}\n\t\t\t\tif(rowNo == \"D\"){\n\t\t\t\tseatsInRow= screen[0].screenInfo.D.rowStatus\n\t\t\t\tavailSeats = { \"D\":[]}\n\t\t\t\t}\n\n\t\t\t\tfor(var s = parseInt(preferSeatNo) ; s>=0 ; s--) {\n\t\t\t\t\tif(count >= numSeats) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tif(seatsInRow[s].seatStatus == \"unreserved\" && seatsInRow[s].isAisel == false ) {\n\t\t\t\t\t\tconsole.log(seatsInRow[s])\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t\tavailSeats[rowNo].push(seatsInRow[s].seatNo)\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t }\n\t\t\t console.log(\"count =\" +count)\n\t\t\t console.log(\"after 2nd case \" + availSeats)\n\t\t\t if(availSeats[rowNo].length >= numSeats) {\n availSeats[rowNo] = availSeats[rowNo].reverse() // will keep in asc order\n\t\t\t\tresolve(availSeats)\n\t\t\t }\n\n\t\t\t //end of second case\n\n\n\t\t\t //third case is when the prefered seat is in between\n\t\t\t\tcount = 0;\n\t\t\t\tif(rowNo == \"A\") {\n\t\t\t\tseatsInRow= screen[0].screenInfo.A.rowStatus\n\t\t\t\tavailSeats = { \"A\":[]}\n\t\t\t\t}\n\t\t\t\tif(rowNo == \"B\"){\n\t\t\t\tseatsInRow= screen[0].screenInfo.B.rowStatus\n\t\t\t\tavailSeats = { \"B\":[]}\n\t\t\t\t}\n\t\t\t\tif(rowNo == \"D\"){\n\t\t\t\tseatsInRow= screen[0].screenInfo.D.rowStatus\n\t\t\t\tavailSeats = { \"D\":[]}\n\t\t\t\t}\n\t\t\t var start = parseInt(preferSeatNo)\n\t\t\t var end = start+1;\n\t\t\t\n\t\t\t if(seatsInRow[start].isAisel == true) {\n\t\t\t\treject(\"seats are not available\")\n\t\t\t }\n\n\t\t\t while(start>=0 || end < seatsInRow.length) {\n\t\t\t\tif(count >= numSeats) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif(start >=0 && end < seatsInRow.length && seatsInRow[start].seatStatus == \"unreserved\" && seatsInRow[end].seatStatus == \"unreserved\" && seatsInRow[start].isAisel == false && seatsInRow[end].isAisel==false) {\n\t\t\t\t\tavailSeats[rowNo].push(seatsInRow[start].seatNo)\n\t\t\t\t\tstart --;\n\t\t\t\t\tavailSeats[rowNo].push(seatsInRow[end].seatNo)\n\t\t\t\t\tend ++;\n\t\t\t\t\tcount ++;\n\t\t\t\t}\n\t\t\t\telse if(start >=0 && seatsInRow[start].seatStatus == \"unreserved\" && seatsInRow[start].isAisel == false ) {\n\t\t\t\t\tavailSeats[rowNo].push(seatsInRow[start].seatNo)\n\t\t\t\t\tstart --;\n\t\t\t\t\tcount ++;\n\t\t\t\t}\n\n\t\t\t\telse if( end < seatsInRow.length && seatsInRow[end].seatStatus == \"unreserved\" && seatsInRow[end].isAisel==false) {\n\t\t\t\t\tavailSeats[rowNo].push(seatsInRow[end].seatNo)\n\t\t\t\t\tend ++;\n\t\t\t\t\tcount ++;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t }\n\n //end of third case\n\n\t\t\t console.log(\"count =\" +count)\n\t\t\t console.log(\"after 3rd case \" + availSeats)\n\t\t\t if(availSeats[rowNo].length >= numSeats) {\n\t\t\t\tresolve(availSeats)\n\t\t\t }\n\t\t}\n }\n\n\t\tconsole.log(availSeats)\n\t\treject(\"seats are not available for this choice\") \n\t\t\n\t})\n\n}",
"constructor(major_name, start_season, start_year) {\n\n\t\tthis.major = MAJORS.find(major => major.major_name == major_name);\n\t\tconsole.log(this.major);\n\t\tthis.semesters = [];\n\t\tthis.course_bank = [];\n\t\tthis.transfer_bank = [];\n\t\tthis.fill_course_bank_w_req_classes();\n\t\tfor (var i = 0; i < 4; i++) {\n\t\t\t//Makes 8 semester of fall/spring, flips between fall and spring\n\t\t\t//ONLY WOKRS IF YOU START AT FALL/SPRING\n\t\t\tthis.semesters.push(new Semester(start_season, start_year, []));\n\t\t\tif (start_season == FALL) start_year++;\n\t\t\tthis.semesters.push(new Semester(2-start_season, start_year, []));\n\t\t\tif (start_season == SPRING) start_year++;\n\t\t}\n\t}",
"function reserveSeats(name,seats,screen) {\n\treturn new Promise(function(resolve,reject) {\n\t\t\n\t\t//console.log(seats)\n\t\tconsole.log(screen)\n\t\tvar currentScreenStatus = screen[0].screenInfo; //get complete object \n\t\tconsole.log(currentScreenStatus)\n\t\t\n\t\tfor(var row in seats) { //row is key , seats is dict\n\t\t\tfor( var c in currentScreenStatus) { //c is key,currentScreenStatus is dict\n\t\t\t\t//console.log(currentScreenStatus[c])\n\t\t\t\tif(row == c ) {\n\t\t\t\t var requiredSeats = seats[row] //requiredSeats is an array\n\t\t\t\t for(var s in requiredSeats) {\n\t\t\t\t\t console.log(requiredSeats[s])\n\t\t\t\t\t console.log(currentScreenStatus[c].rowStatus[requiredSeats[s]]) //row -> array of seats(seat no) -> checkstatus\n\t\t\t\t\t if( currentScreenStatus[c].rowStatus[requiredSeats[s]].seatStatus == \"reserved\") {\n\t\t\t\t\t\t reject(\"seats are not available\")\n\t\t\t\t\t }\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t} \n\t\t }\n\n\n\t\tfor(var row in seats) { //row is key \n\t\t\tfor( var c in currentScreenStatus) { //c is key\n\t\t\t\t//console.log(currentScreenStatus[c])\n\t\t\t\tif(row == c ) {\n\t\t\t\t var requiredSeats = seats[row] //this is an array\n\t\t\t\t for(var s in requiredSeats) {\n\t\t\t\t\t console.log(requiredSeats[s])\n\t\t\t\t\t console.log(currentScreenStatus[c].rowStatus[requiredSeats[s]]) //row -> array of seats(seat no) -> checkstatus\n\t\t\t\t\t currentScreenStatus[c].rowStatus[requiredSeats[s]].seatStatus = \"reserved\"\n\t\t\t\t }\n\t\t\t\t}\n\t\t\t} \n\t\t }\n\n\t\t console.log(currentScreenStatus)\n\t\t resolve(currentScreenStatus)\n\t})\n}",
"renderSeats () {\n this.bus.seats.forEach((seat) => {\n this.renderSeat(seat)\n })\n }",
"function seahaven(element, x, y) {\n this.constructMe(element);\n var i = 0;\n this.x = (x==null) ? 0 : x;\n this.y = (y==null) ? 0 : y;\n this.deck = new CardDeck('seahaven', this.element);\n this.holes = new Array(4);\n this.stacks = new Array(10);\n this.aces = {\n spades: this.newLocation(this.x, this.y, 0, 0),\n hearts: this.newLocation(this.x, this.y, 0, 0),\n diamonds: this.newLocation(this.x, this.y, 0, 0),\n clubs: this.newLocation(this.x, this.y, 0, 0)\n };\n for (i=0;i<4;++i) {\n this.holes[i] = this.newLocation(this.x, this.y, 0, 0);\n }\n for (i=0;i<10;++i) {\n this.stacks[i] = this.newLocation(this.x, this.y, 0, 0);\n }\n this.putUpCards = this.putUpCards.bind(this);\n this.reposition();\n}",
"function resetSeatsVar() {\n seat_a1 = \"\";\n seat_a2 = \"\";\n seat_a3 = \"\";\n seat_a4 = \"\";\n seat_a5 = \"\";\n seat_a6 = \"\";\n seat_a7 = \"\";\n seat_a8 = \"\";\n seat_b1 = \"\";\n seat_b2 = \"\";\n seat_b3 = \"\";\n seat_b4 = \"\";\n seat_b5 = \"\";\n seat_b6 = \"\";\n seat_b7 = \"\";\n seat_b8 = \"\";\n seat_b9 = \"\";\n seat_b10 = \"\";\n seat_c1 = \"\";\n seat_c2 = \"\";\n seat_c3 = \"\";\n seat_c4 = \"\";\n seat_c5 = \"\";\n seat_c6 = \"\";\n seat_c7 = \"\";\n seat_c8 = \"\";\n seat_c9 = \"\";\n seat_c10 = \"\";\n seat_d1 = \"\";\n seat_d2 = \"\";\n seat_d3 = \"\";\n seat_d4 = \"\";\n seat_d5 = \"\";\n seat_d6 = \"\";\n seat_d7 = \"\";\n seat_d8 = \"\";\n seat_e1 = \"\";\n seat_e2 = \"\";\n seat_e3 = \"\";\n seat_e4 = \"\";\n seat_e5 = \"\";\n seat_e6 = \"\";\n seat_e7 = \"\";\n seat_e8 = \"\";\n seat_f1 = \"\";\n seat_f2 = \"\";\n seat_f3 = \"\";\n seat_f4 = \"\";\n seat_f5 = \"\";\n seat_f6 = \"\";\n seat_f7 = \"\";\n seat_f8 = \"\";\n seat_f9 = \"\";\n seat_f10 = \"\";\n seat_g1 = \"\";\n seat_g2 = \"\";\n seat_g3 = \"\";\n seat_g4 = \"\";\n seat_g5 = \"\";\n seat_g6 = \"\";\n seat_g7 = \"\";\n seat_g8 = \"\";\n seat_g9 = \"\";\n seat_g10 = \"\";\n seat_h1 = \"\";\n seat_h2 = \"\";\n seat_h3 = \"\";\n seat_h4 = \"\";\n seat_h5 = \"\";\n seat_h6 = \"\";\n seat_h7 = \"\";\n seat_h8 = \"\";\n seat_h9 = \"\";\n seat_h10 = \"\";\n }",
"constructor(offsetY, numberOfBeats) {\n this.height = 70;\n this.width = width * 0.6;\n this.offsetX = width * 0.2;\n this.offsetY = offsetY;\n this.numberOfBeats = numberOfBeats;\n this.beatWidth = this.width / this.numberOfBeats;\n this.beats = [];\n\n for (let i = 0; i < this.numberOfBeats; i++) {\n const posX = this.offsetX + this.beatWidth * i;\n const posY = this.offsetY;\n\n this.beats.push(new Beat(posX, posY, this.beatWidth, this.height));\n }\n }",
"checkForAddedSeats(seats) {\n const userId = authService.getAuthenticatedUser().id;\n\n seats.forEach((row, rowNumber) => {\n row.forEach((seat, number) => {\n const isSeatNotListed =\n seat.status === TEMPORARY_OCCUPIED &&\n seat.occupiedBy === userId &&\n !this.props.addedSeats.find(item => item._id === seat._id);\n\n if (isSeatNotListed) {\n const payload = {\n ...seat,\n number,\n rowNumber,\n };\n this.props.dispatch(addSeat(payload));\n }\n });\n });\n }",
"function buildTimeslotArray(parsedItems) {\r\n var itemTimeslotArray = [];\r\n for (var i = 0; i < parsedItems.length; i++) {\r\n var rate = parsedItems[i].rate;\r\n var timeslotArray = rate.dates[rate.start_date].timeslots;\r\n itemTimeslotArray.push(timeslotArray);\r\n }\r\n console.log(itemTimeslotArray);\r\n return itemTimeslotArray;\r\n}",
"function assignSeatsByRow(seed, colOffset, rowOffset) {\n\tvar leftStudents = []\t// an array to hold the students who are left handed\n\tvar rightStudents = []\t// an array to hold the students who are right handed\n\tvar tempList = students;\n\tvar rightIndex = 0;\t// index containing how many students have been assigned in the left handed array\n\tvar leftIndex = 0;\t// index containing how many students have been assigned in the right handed array\n\tvar nonGhosts = 0;\t// total number of nonGhost seats in the classroom\n\tvar totalStudents = students.length;\n\tshuffle(tempList,seed);\t// Shuffles the list of students\n\t\n\tvar counter = 0\n\t// Copies over the map of seats and pushes it into an array in order to loop through it\n\tfor (var key in finalSeatMap) {\n\t\tif (finalSeatMap.hasOwnProperty(key)) {\n\t\t\t//seatArr.push(finalSeatMap[key])\n\t\t\tif (!finalSeatMap[key].isGhost) nonGhosts++\n\t\t}\n\t}\n\n\t// Enough space to spread out more\n\tconsole.log(\"Roster: \" + rosterSize)\n\tconsole.log(\"Seats available: \" + nonGhosts)\n\n\t// Goes through the shuffled student array and begins dividing it into left and right handed students\n\tfor(var i = 0; i < tempList.length; i++) {\n\t\tif (tempList[i].isLeftHanded)\n\t\t\tleftStudents.push(tempList[i]);\n\t\telse\n\t\t\trightStudents.push(tempList[i]);\n\t}\n\n\n\tfor (var key in finalSeatMap) {\n\t\tif (finalSeatMap.hasOwnProperty(key)) {\n\t\t\tseatArr.push(finalSeatMap[key]);\n\t\t\tif (!finalSeatMap[key].isGhost) nonGhosts++;\n\t\t}\n\t}\n\n\tvar statisfied = false;\n\tvar colOffset = 1;\n\tvar rowOffset = 0;\n\tvar seatsAssigned = 0;\n\tvar restart = false;\n\tvar numInspected = 0;\n\tvar attempts = 0\n\tvar removeLast = [];\n\tvar rowStart = 0;\n\tvar clear = false;\n\tvar flop = 0\n\twhile (seatsAssigned < totalStudents || !statisfied) {\n\t\tif (flop == 23) {\n\t\t\talert('terminated')\n\t\t\tbreak;\n\t\t}\n\t\tif (attempts == 0) {\n\t\t\tcolOffset = 1;\n\t\t\trowOffset = 0;\n\t\t\trowStart = 0;\n\t\t\tclear = false;\n\t\t}\n\t\telse if (attempts == 1) {\n\t\t\tcolOffset = 2;\n\t\t\trowStart = 0;\n\t\t\trowOffset = 0;\n\t\t\tclear = false;\n\t\t}\n\t\telse if (attempts == 2) {\n\t\t\tcolOffset = 2;\n\t\t\trowOffset = 1;\n\t\t\trowStart = 1;\n\t\t\tclear = true;\n\t\t}\n\t\telse if (attempts == 3) {\n\t\t\tcolOffset = 2;\n\t\t\trowOffset = 1;\n\t\t\trowStart = 0;\n\t\t\tclear = true;\n\t\t}\n\t\tconsole.log(\"attempts:\" + attempts);\n\t\t(function() {\n\t\t\t// remove seats\n\t\t\tfor (var i = rowStart; i < gridRow; i +=(1)) {\n\t\t\t\tvar m = 0;\n\n\t\t\t\t// starting from first unempty seat and clearing\n\t\t\t\tfor (var j = m; j < gridCol; j+=(colOffset+1)) {\n\t\t\t\t\tvar seat = seatArr[i*gridCol+j];\t\t\t\t\t\n\t\t\t\t\tif (!seat.isEmpty) {\n\t\t\t\t\t\tif (seat.isAisle) {\n\t\t\t\t\t\t\tremoveLast.push(seat);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tseat.isEmpty = true;\n\t\t\t\t\t\tif (seatsAssigned > 0) seatsAssigned--;\n\t\t\t\t\t\tif (seatsAssigned == totalStudents) {\n\t\t\t\t\t\t\tconsole.log('statisfied')\n\t\t\t\t\t\t\tstatisfied = true;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// removing aisles last\n\t\t\t\tfor (var k = 0; k < removeLast.length; k++) {\n\t\t\t\t\tremoveLast[k].isEmpty = true;\n\t\t\t\t\tif (seatsAssigned > 0) seatsAssigned--;\n\t\t\t\t\tif (seatsAssigned == totalStudents) {\n\t\t\t\t\t\tconsole.log('statisfied')\n\t\t\t\t\t\tstatisfied = true;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tremoveLast = [];\n\t\t\t\t//if (seatsAssigned < totalStudents) return;\n\t\t\t}\n\t\t})();\n\t\t(function () {\n\t\t\t// redo the rows with new offset starting at top row\n\t\t\tif (seatsAssigned == totalStudents) return;\n\t\t\tfor (var i = rowStart; i < gridRow; i +=(rowOffset+1)) {\n\t\t\t\tfor (var j = 0; j < gridCol; j+=(colOffset+1)) {\n\t\t\t\t\tif (!clear)\n\t\t\t\t\t\tseatsAssigned = assignEmpty(i,j,seatsAssigned);\n\t\t\t\t}\n\t\t\t}\n\t\t})();\n\t\tconsole.log(seatsAssigned);\n\t\tvar lastAvailRow = 0;\n\t\tvar lastAvailCol = 0;\n\t\tif (seatsAssigned == totalStudents) statisfied = true;\n\t\tvar fillCounter = 0;\n\t\tvar tempRowOff = rowOffset;\n\t\tvar tempColOff = colOffset;\n\t\twhile (seatsAssigned < totalStudents) {\n\t\t\tconsole.log('loop')\n\t\t\tif (fillCounter > 50) {\n\t\t\t\talert('too many loops');\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t(function() {\n\t\t\t\tfor (var i = gridRow-1; i >= 0; i -=(tempRowOff+1)) {\n\t\t\t\t\tfor (var j = 0; j < gridCol; j++) {\n\t\t\t\t\t\tif (seatArr[i*gridCol+j].isEmpty) {\n\t\t\t\t\t\t\tlastAvailRow = i;\n\t\t\t\t\t\t\tlastAvailCol = j;\n\t\t\t\t\t\t\tconsole.log('first empty at row : ' + lastAvailRow + ' col: ' + lastAvailCol);\n\t\t\t\t\t\t\tconsole.log(seatArr[lastAvailRow*gridCol+lastAvailCol]);\n\t\t\t\t\t\t\treturn\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\t(function() {\n\t\t\t\tvar div = 8;\n\t\t\t\tfor (var i = lastAvailRow; i >= 0; i -=(tempRowOff+1)) {\n\t\t\t\t\tfor (var j = lastAvailCol; j < gridCol; j +=(tempColOff+1)) {\n\t\t\t\t\t\tseatsAssigned = assignEmpty(i,j,seatsAssigned);\n\t\t\t\t\t\tif (seatsAssigned == totalStudents) {\n\t\t\t\t\t\t\tstatisfied = true;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfillCounter++;\n\t\t\t\tif (fillCounter % 3 == 0) {\n\t\t\t\t\tif (tempRowOff > 0) tempRowOff--;\n\t\t\t\t} else {\n\t\t\t\t\tif (tempColOff > 0) tempColOff--;\n\t\t\t\t}\n\t\t\t})();\n\t\t}\n\t\tflop++;\n\t\tattempts = (attempts+1) % 4;\n\t}\n\t// Seating students\n\tfor(var i = seatArr.length-1; i >= 0; i--) {\n\t\tvar right = true;\n\t\tvar tempStudent;\n\t\tvar seat = seatArr[i];\n\t\tif(seat.isGhost) { continue; }\n\t\tif((rightIndex + leftIndex) >= tempList.length) { continue; }\n\t\tif (!seat.isEmpty) {\n\t\t\tif(seat.student == null) { \n\t\t\t\tconsole.log(\"empty seat\")\n\t\t\t\tif(seat.isLeftHanded) {\n\t\t\t\t\t// If the students is left handed choose from the left handed array\n\t\t\t\t\t// only if there are any left handed students left otherwise choose from\n\t\t\t\t\t// the right handed array\n\t\t\t\t\tif(leftIndex < leftStudents.length) {\n\t\t\t\t\t\ttempStudent = leftStudents[leftIndex];\n\t\t\t\t\t\tright = false;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\ttempStudent = rightStudents[rightIndex];\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// If the student is right handed choose from the right handed array\n\t\t\t\t\t// only if there are any right handed students left otherwise choose from\n\t\t\t\t\t// the left handed array\n\t\t\t\t\tif(rightIndex < rightStudents.length)\t\n\t\t\t\t\t\ttempStudent = rightStudents[rightIndex];\n\t\t\t\t\telse {\n\t\t\t\t\t\ttempStudent = leftStudents[leftIndex];\n\t\t\t\t\t\tright = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Add students to seats only if there are students to add\n\t\t\t\tif (rightIndex + leftIndex < tempList.length) {\n\t\t\t\t\tif (right) rightIndex++;\n\t\t\t\t\telse leftIndex++;\n\t\t\t\t\tseat.student = tempStudent;\n\t\t\t\t\ttempStudent.seat = seat;\n\t\t\t\t\tcounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tconsole.log(\"leftIndex: \" + leftIndex + \" rightIndex: \" + rightIndex + \" tempList: \" + tempList.length)\n\n\tif (rightIndex + leftIndex < tempList.length) console.log(\"STILL STUDENTS MISSING\")\n\t// Fill the remaining seats with empty students\n\tfor(var i = 0; i < seatArr.length; i++) {\n\t\tvar s = seatArr[i];\n\t\tif(s.isGhost) { continue; }\n\t\tif(s.student == null) { \n\t\t\tvar emptyStudent = new Student(\"EMPTY\", \"EMPTY\", \"\", \"\", false, false, null);\n\t\t\ts.isEmpty = true;\n\t\t\temptyStudent.seat = s;\n\t\t\ts.student = emptyStudent; \n\t\t\tstudents.push(emptyStudent);\n\t\t}\n\t}\n\tconsole.log(counter + \" students assigned\")\n}",
"function createGameStageArray(){\n let borderSize = getBoardSize();\n let rows = borderSize[0];\n let cols = borderSize[1];\n for(let row=0;row<rows;row++){\n gameStageArch[row] = [];\n for(let col=0;col<cols;col++){\n gameStageArch[row][col] = false;\n }\n }\n}",
"function createYearsArray(size,year) {\n\t// Validate parameter value\n\tif (size+\"\" == \"undefined\" || size == null) \n\t\treturn null;\t\n\tthis.length = size;\n\tfor (var i = 0; i < size; i++) {\n\t\tthis[i] = year++; \n\t}\n\treturn this;\n}",
"aggregateBy(keyFunction)\r\n\t{\r\n\t\tlet buckets = {};\r\n\t\tfor(let i=0;i<this.roomList.length;i++)\r\n\t\t{\r\n\t\t\tlet key = keyFunction(this.roomList[i]);\r\n\t\t\tif (buckets.hasOwnProperty(key))\r\n\t\t\t{\r\n\t\t\t\tbuckets[key].addRoom(this.roomList[i]);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tlet bucketRoomUsageList = new RoomUsageList();\r\n\t\t\t\tbucketRoomUsageList.addRoom(this.roomList[i]);\r\n\t\t\t\tbuckets[key] = bucketRoomUsageList;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn buckets;\r\n\t}",
"static createDeck() {\n for (let i = 0; i < 4; i++) {\n for (let j = 1; j <= 7; j++) {\n let obj = { suit: i, value: j };\n deck.push(obj);\n }\n }\n }",
"ajouterPartie(nbAAjouter) {\n if (nbAAjouter <= 0 || this.nbPartiesAffichees >= 10) {\n return;\n } else if (nbAAjouter + this.nbPartiesAffichees > 10) {\n nbAAjouter = 10 - this.nbPartiesAffichees;\n }\n \n for (var i = 0; i < nbAAjouter; i++) {\n this.parties.push(new PartieGibet(++this.nbPartiesAffichees));\n }\n }",
"constructor (size) {\n\n var i,j;\n var board = [];\n\n //Initialize each space to 0\n for (i=0; i<size; i++) {\n\n var row = [];\n\n for (j=0; j<size; j++) {\n row.push(0);\n }\n\n board.push(row);\n }\n\n this.board = board;\n this.size = size;\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Splits the active hand into two hands | split() {
let playerHand = this.state.playerHand; // All player hands
let activeHand = this.state.playerHand[this.state.activeHand]; // Active player hand
let newHand = new Hand([]); // New hand
let cardToMove = activeHand.getCards()[1];
activeHand.removeCards(cardToMove);
newHand.addCards([cardToMove]);
newHand.setBet(activeHand.getBet());
this.drawCard(activeHand, 1, function (aHand) {
this.drawCard(newHand, 1, function (nHand) {
playerHand.splice(playerHand.indexOf(aHand), 1, aHand, nHand);
this.setState({ playerHand: playerHand },
this.checkWinCondition(false)
);
}.bind(this));
}.bind(this));
} | [
"function HandleFrame(frame) {\t\n\tvar InteractionBox = frame.interactionBox;\n\t//No hand - variables undefine\n\tif(frame.hands.length == 1 || frame.hands.length == 2){\n\t\t//Grabs 1st hand per frame\n\t\tvar hand = frame.hands[0];\n\t\tHandleHand(hand,1,InteractionBox);\n\t\tif(frame.hands.length == 2){\n\t\t\t//Grabs 2nd hand per frame\n\t\t\t//var hand = frame.hands[1];\n\t\t\tHandleHand(hand,2,InteractionBox);\n\t\t}\n\t}\n}",
"function createHand(world, replica, side) {\n const hand = new THREE.Group();\n\n const palm = new THREE.Mesh(world.primitiveGeo.box, replica.material);\n palm.scale.set(0.08, 0.02, 0.16);\n palm.rotation.set(0.3, 0, side * -1);\n palm.position.set(side * 0.02, 0, 0.05);\n hand.add(palm);\n\n const thumb = new THREE.Mesh(world.primitiveGeo.box, replica.material);\n thumb.scale.set(0.02, 0.02, 0.08);\n thumb.rotation.set(0, side * 0.5, 0);\n thumb.position.set(side * -0.02, 0.02, 0.08);\n hand.add(thumb); \n\n world.scene.add(hand);\n\n return hand;\n}",
"function completeStripPhase () {\n /* strip the player with the lowest hand */\n stripPlayer(recentLoser);\n updateAllGameVisuals();\n}",
"function getHand(){\n return hands[parseInt(Math.random()*10%3)];\n}",
"deal(hands,per_hand = 1){\n\t\t\tfor (let round = 1; round <= per_hand; round++) {\n\t\t\t\tfor (let hand of hands) {\n\t\t\t\t\tif(this.cards.length>0){\n\t\t\t\t\t\tlet top_card = this.cards[0];\n\t\t\t\t\t\tthis.give(top_card, hand)\n\t\t\t\t\t}else{\n\t\t\t\t\t\talert(\"I can not deal cards any more. Cards are Over!!!\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"async function changeHandState() {\n isHandRaised.toggleState();\n isHandRaised.sendAttendeeHandState();\n handleParticipantUpdate();\n document.getElementById(\"hand-img\").classList.toggle(\"hidden\");\n document.querySelector(\".raise-hand-button\").innerText = `${\n attendee.handRaised ? \"Lower Hand\" : \"Raise Hand\"\n }`;\n document.querySelector(\".hand-state\").innerText = `${\n attendee.handRaised ? \"Your hand is raised ๐\" : \"Your hand is down ๐\"\n }`;\n\n // Turn on video if hand is raised\n if (attendee.handRaised && !callFrame.participants().local.video) {\n callFrame.setLocalVideo(!callFrame.participants().local.video);\n } \n}",
"function swapPieces(face, times) {\n\tfor (var i = 0; i < 6 * times; i++) {\n\t\tvar piece1 = getPieceBy(face, i / 2, i % 2),\n\t\t\t\tpiece2 = getPieceBy(face, i / 2 + 1, i % 2);\n\t\tfor (var j = 0; j < 5; j++) {\n\t\t\tvar sticker1 = piece1.children[j < 4 ? mx(face, j) : face].firstChild,\n\t\t\t\t\tsticker2 = piece2.children[j < 4 ? mx(face, j + 1) : face].firstChild,\n\t\t\t\t\tclassName = sticker1 ? sticker1.className : '';\n\t\t\tif (className)\n\t\t\t\tsticker1.className = sticker2.className,\n\t\t\t\tsticker2.className = className;\n\t\t}\n\t}\n}",
"roundTwo() {\n\t\t// use the filterPlayers method\n\t\tconst roundTwoPlayers = this.filterPlayers(1);\n\t let roundTwoPairs = [];\n\t // pair up the players\n\t for (let i = 0; i < roundTwoPlayers.size; i +=2) {\n\t\t\tlet pair = roundTwoPlayers.slice(i, i + 2);\n\t\t\troundTwoPairs.push(pair);\n\t\t}\n\t\t// add pairs to state\n\t\tthis.setState({\n\t\t\troundTwoPairs: roundTwoPairs,\n\t\t});\n\t}",
"function hunterOne (){\n if (targetShip[0] < width - 1){\n nextShot.push(targetShip[0] - 1)\n nextShot.push(targetShip[0] + width)\n nextShot.push(targetShip[0] + 1)\n } if (targetShip[0] % width === 0){\n nextShot.push(targetShip[0] - width)\n nextShot.push(targetShip[0] + width)\n nextShot.push(targetShip[0] + 1)\n } if (targetShip[0] % width === width - 1){\n nextShot.push(targetShip[0] - 1)\n nextShot.push(targetShip[0] - width)\n nextShot.push(targetShip[0] + width)\n } if (targetShip[0] > cellCount - width){\n nextShot.push(targetShip[0] - 1)\n nextShot.push(targetShip[0] - width)\n nextShot.push(targetShip[0] + 1)\n } else {\n nextShot.push(targetShip[0] - 1)\n nextShot.push(targetShip[0] - width)\n nextShot.push(targetShip[0] + width)\n nextShot.push(targetShip[0] + 1)\n }\n }",
"function userHand() {\n\n}",
"function chooseSide() {\n if(singlePlayer) {\n var singleChose = document.createElement(\"div\");\n singleChose.className = \"singleChose\";\n var ask = document.createElement(\"h1\");\n ask.innerText = \"You wanna X or O?\";\n singleChose.appendChild(ask);\n var x = createXO('X');\n var o = createXO('O');\n singleChose.appendChild(x);\n singleChose.appendChild(o);\n backBoad[0].appendChild(singleChose);\n x.addEventListener(\"click\", function () {\n startPlay('X');\n });\n o.addEventListener(\"click\", function () {\n startPlay('O');\n });\n } else if (twoPlayer) {\n var twoChose = document.createElement(\"div\");\n twoChose.className = \"twoChose\";\n var ask = document.createElement(\"h1\");\n ask.innerText = \"You wanna X or O to move first?\";\n twoChose.appendChild(ask);\n var x = createXO('X');\n var o = createXO('O');\n twoChose.appendChild(x);\n twoChose.appendChild(o);\n backBoad[0].appendChild(twoChose);\n x.addEventListener(\"click\", function () {\n startPlay('X');\n });\n o.addEventListener(\"click\", function () {\n startPlay('O');\n });\n }\n}",
"function updateHand() {\n document.querySelector('.dealer-hand').textContent = dealerHand;\n document.querySelector('.player-hand').textContent = playerHand;\n}",
"function drawUserHand()\n {\n for (let i = 0; i < Game.userHand.cards.length; i++)\n {\n let card = Game.userHand.cards[i];\n \n if (card != null)\n {\n card.drawCard(50 + (i * 50), USER_HAND_Y);\n }\n }\n }",
"function HandSessionDetector() {\r\n\tvar events = Events();\r\n\tvar api = {\r\n\t\t// property: shouldRotateHand\r\n\t\t// Attempt to normalize hand positions to sensor center. Makes implementing UI controls a bit easier if we can assume the user is always facing the sensor, even when this isn't the case\r\n\t\tshouldRotateHand : true,\r\n\t\t// property: shouldSmoothPoints\r\n\t\t// Should hand points be smoothed\r\n\t\tshouldSmoothPoints : true,\r\n\t\tonuserupdate : onuserupdate,\r\n\t\tonattach : onattach,\r\n\t\tondetach : ondetach,\r\n\t\tstartSession : startSession,\r\n\t\tstopSession : stopSession,\r\n\t\t// property: startOnWave\r\n\t\t// Should a hand session start when user waves?\r\n\t\tstartOnWave : true,\r\n\t\t// property: startOnSteady\r\n\t\t// Should a hand session start on hand steady?\r\n\t\tstartOnSteady : true,\r\n\t\tstartOnExternalHandpoint : true,\r\n\t\t// property: bbox\r\n\t\t// Bounding box for session bounds\r\n\t\tbbox : BoundingBox([1000, 500, 500]),\r\n\t\t// property: bboxOffset\r\n\t\t// Offset of session bounds from user position\r\n\t\tbboxOffset : [0, 250, -300],\r\n\t\t// property: focusPosition\r\n\t\t// focus point for current session\r\n\t\tfocusPosition : [0,0,0]\r\n\t}\r\n\tevents.eventify(api);\r\n\r\n\t//var bboxOffset = $V([0, 250, -300]);\r\n\t//var bbox = BoundingBox([1000, 500, 500]);\r\n\r\n\tvar rotateReference;\r\n\tvar inSession = false;\r\n\tvar jointToUse;\r\n\tvar useExternalHandpoint = false;\r\n\tvar framesNotInBbox = 0;\r\n\tvar maxFramesNotInBbox = 15;\r\n\tvar lastPosition = undefined;\r\n\r\n\tvar currentUser;\r\n\r\n\tfunction onattach(user) {\r\n\t\tcurrentUser = user;\r\n\t\trotateReference = user.position;\r\n\r\n\t\tif (api.startOnWave) {\r\n\t\t\tvar wdLeft = WaveDetector();\r\n\t\t\tvar wdRight = WaveDetector();\r\n\t\t\twdLeft.addEventListener('wave', sessionShouldStart);\r\n\t\t\twdRight.addEventListener('wave', sessionShouldStart);\r\n\t\t\tuser.mapJointToControl(Joint.LeftHand, wdLeft);\r\n\t\t\tuser.mapJointToControl(Joint.RightHand, wdRight);\r\n\t\t}\r\n\r\n\t\tif (api.startOnSteady) {\r\n\t\t\tvar sdLeft = SteadyDetector();\r\n\t\t\tvar sdRight = SteadyDetector();\r\n\t\t\tsdLeft.addEventListener('steady', sessionShouldStart);\r\n\t\t\tsdRight.addEventListener('steady', sessionShouldStart);\r\n\t\t\tuser.mapJointToControl(Joint.LeftHand, sdLeft);\r\n\t\t\tuser.mapJointToControl(Joint.RightHand, sdRight);\r\n\t\t}\r\n\t}\r\n\r\n\tfunction ondetach(user) {\r\n\t\tif (inSession) {\r\n\t\t\tinSession = false;\r\n\t\t\tevents.fireEvent('sessionend');\r\n\t\t}\r\n\t\tcurrentUser = undefined;\r\n\t\t// TODO: unmap joint->control\r\n\t}\r\n\t\r\n\tfunction rotatedPoint(point) {\r\n\t\treturn (api.shouldRotateHand) ? rotatePoint(point, rotateReference) : point;\r\n\t}\r\n\r\n\tfunction inBbox(point) {\r\n\t\tvar userPosition = rotatedPoint(currentUser.position);\r\n\t\tapi.bbox.recenter($V(userPosition).add($V(api.bboxOffset)));\r\n\t\treturn api.bbox.contains(rotatedPoint(point));\r\n\t}\r\n\r\n\tfunction sessionShouldStart(detector) {\r\n\t\tif (inSession) return;\r\n\t\t\r\n\t\tif (inBbox(currentUser.skeleton[detector.mappedJoint].position)) {\r\n\t\t\tstartSession(detector.mappedJoint);\r\n\t\t}\r\n\t}\r\n\r\n\tfunction onuserupdate(userData) {\r\n\t\tif (!inSession && api.startOnExternalHandpoint && \r\n\t\t\tuserData.skeleton.hasOwnProperty(Joint.ExternalHandpoint)) {\r\n\t\t\tsessionShouldStart({mappedJoint : Joint.ExternalHandpoint });\r\n\t\t}\r\n\r\n\t\tif (inSession && jointToUse == Joint.ExternalHandpoint && \r\n\t\t\t!userData.skeleton.hasOwnProperty(Joint.ExternalHandpoint)) {\r\n\t\t\tstopSession();\r\n\t\t}\r\n\t\t\r\n\t\trotateReference = vlerp(rotateReference, userData.position, 0.5);\r\n\t\tif (inSession) {\r\n\t\t\tvar pos = userData.skeleton[jointToUse].position;\r\n\t\t\tif (!inBbox(pos)) {\r\n\t\t\t\tframesNotInBbox++;\r\n\t\t\t\tif (framesNotInBbox >= maxFramesNotInBbox) {\r\n\t\t\t\t\tframesNotInBbox = 0;\r\n\t\t\t\t\tstopSession();\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tframesNotInBbox = 0;\r\n\t\t\t\tvar rotatedPos = rotatedPoint(pos);\r\n\t\t\t\tif (api.shouldSmoothPoints) {\r\n\t\t\t\t\trotatedPos = vlerp(lastPosition, rotatedPos, 0.8);\r\n\t\t\t\t}\r\n\t\t\t\tlastPosition = rotatedPos;\r\n\t\t\t\tevents.fireEvent('sessionupdate', lastPosition);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tfunction startSession(joint) {\r\n\t\tstopSession();\r\n\t\tinSession = true;\r\n\t\tjointToUse = joint;\r\n\t\tlastPosition = rotatedPoint(currentUser.skeleton[joint].position);\r\n\t\tapi.focusPosition = lastPosition;\r\n\t\tevents.fireEvent('sessionstart', api.focusPosition);\r\n\t}\r\n\r\n\tfunction stopSession() {\r\n\t\tif (inSession) {\r\n\t\t\tinSession = false;\r\n\t\t\tevents.fireEvent('sessionend');\r\n\t\t}\r\n\t}\r\n\r\n\tfunction onlistenerattach(listener) {\r\n\t\tif (inSession) {\r\n\t\t\tevents.fireEvent(\"sessionstart\", api.focusPosition, listener);\r\n\t\t}\r\n\t}\r\n\r\n\tfunction onlistenerdetach(listener) {\r\n\t\tif (inSession) {\r\n\t\t\tevents.fireEvent(\"sessionend\", null, listener);\r\n\t\t}\r\n\t}\r\n\r\n\tfunction rotatePoint(handPos, comPos)\r\n\t{\r\n\t\t// change the forward vector to be u = (CoM - (0,0,0))\r\n\t\t// instead of (0,0,1)\r\n\t\tvar cx = comPos[0];\r\n\t\tvar cy = comPos[1];\r\n\t\tvar cz = comPos[2];\r\n\t\t\r\n\t\tvar len = Math.sqrt(cx*cx + cy*cy + cz*cz);\r\n\t\t// project the vector to XZ plane, so it's actually (cx,0,cz). let's call it v\r\n\t\t// so cos(angle) = v . u / (|u|*|v|)\r\n\t\tvar lenProjected = Math.sqrt(cx*cx + cz*cz);\r\n\t\tvar cosXrotation = (cx*cx + cz*cz) / (lenProjected * len); // this can be slightly simplified\r\n\t\tvar xRot = Math.acos(cosXrotation);\r\n\t\tif (cy < 0) xRot = -xRot; // set the sign which we lose in \r\n\t\t// now for the angle between v and the (0,0,1) vector for Y-axis rotation\r\n\t\tvar cosYrotation = cz / lenProjected;\r\n\t\tvar yRot = Math.acos(cosYrotation);\r\n\t\tif (cx > 0) yRot = -yRot;\r\n\t\treturn (Matrix.RotationX(xRot).x(Matrix.RotationY(yRot))).x($V(handPos)).elements;\r\n\t}\r\n\r\n\treturn api;\r\n}",
"function setSplits(pay_3, pay_2, pay_1) {\n\tvar check_box = document.getElementsByName('splits[]');\n\tvar chip_count = document.getElementsByName('chipcounts[]');\n\tvar original_splits = document.getElementsByName('original_splits[]');\n\tvar split_count = 0;\n\tvar chip_count_value = 0;\n\tvar preceeding_chip_count = 0;\n\tvar chip_count_sum = 0;\n\tvar players_chip_count = 0;\n\t\n\t// Loop through all the check boxes.\n\tfor (i = 0; i < check_box.length; i++) {\n\t\t// Hide all the chipcount text boxes\n\t\tchip_count[i].style.visibility = \"hidden\";\n\t\t\n\t\t// If the third place player is not checked to split, change their split_diff\n\t\t// back to it's default according to the settings\n\t\tif (check_box[i].checked === false && i === check_box.length - 3) {\n\t\t\tchip_count[i].value = pay_3;\n\t\t}\n\t\t\n\t\t// If the second place player is not checked to split, change their split_diff\n\t\t// back to it's default according to the settings\n\t\tif (check_box[i].checked === false && i === check_box.length - 2) {\n\t\t\tchip_count[i].value = pay_2;\n\t\t}\n\t\t\n\t\t// If the first place player is not checked to split, change their split_diff\n\t\t// back to it's default according to the settings\n\t\tif (check_box[i].checked === false && i === check_box.length - 1) {\n\t\t\tchip_count[i].value = pay_1;\n\t\t}\n\t\t\n\t\t// If a check box is checked count it as a splitting player.\n\t\tif (check_box[i].checked) {\n\t\t\tsplit_count = split_count + 1;\n\t\t}\n\t\t\n\t\t// If the associated chip count with the splitting player\n\t\t// has no value, set the chip count to 0. Otherwise, get \n\t\t// the integer value of the given chip count value.\n\t\tif (chip_count[i].value === \"\") {\n\t\t\tchip_count_value = 0;\n\t\t} else {\n\t\t\tchip_count_value = parseInt(chip_count[i].value);\n\t\t\t// Make sure that a lower winner, preceeding chip count, does not have a larger\n\t\t\t// chip count than a higher winner.\n\t\t\tif (preceeding_chip_count > chip_count_value) {\n\t\t\t\talert(\"Check you chip counts! You can not have a larger chip count for a lower winner.\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tpreceeding_chip_count = chip_count_value;\n\t\t}\n\t\t\n\t\t// Sum all the chip_count values to get the total chip count sum.\n\t\tchip_count_sum = chip_count_sum + chip_count_value;\n\t}\n\t\n\t// If there is only one split_count, notify the user that a split must have at least\n\t// two players and exit the function.\n\tif (split_count === 1) {\n\t\talert(\"You must have at least two players to split!\");\n\t\treturn false;\n\t}\n\t\n\t// If the chip count sum = 0, the the split is done evenly and set the\n\t// chip count sum to 1.\n\tif (chip_count_sum === 0) {\n\t\tchip_count_sum = 1;\n\t\t// For every check box that is checked, divide the chip count sum by\n\t\t// the split count to find the even percetage each splitting player gets.\n\t\tfor (i = 0; i < check_box.length; i++) {\n\t\t\tif (check_box[i].checked) {\n\t\t\t\tchip_count[i].value = chip_count_sum / split_count;\n\t\t\t}\n\t\t}\n\t// If the chip count sum > 0, then the split is done by percentage.\n\t} else {\n\t\t// For every check box that is checked, divide the corresponding\n\t\t// chip count value by the total chip count sum to get the\n\t\t// percentage of each splitting player.\n\t\tfor (i = 0; i < check_box.length; i++) {\n\t\t\tif (check_box[i].checked) {\n\t\t\t\tplayers_chip_count = parseInt(chip_count[i].value);\n\t\t\t\t// If the chip_count_sum is > 0 then the split is by percentage and no splitting players\n\t\t\t\t// can have a chip count of 0\n\t\t\t\tif (players_chip_count <= 0 || isNaN(players_chip_count)) {\n\t\t\t\t\talert(\"All splitting players must have a chip count!\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (split_count === 2) {\n\t\t\t\t\t// If only 2 players are splitting, subtract 3rd place's percetage from\n\t\t\t\t\t// each of the chip counts to account for the percentage they get.\n\t\t\t\t\tchip_count[i].value = (players_chip_count - (players_chip_count * pay_3)) / chip_count_sum;\n\t\t\t\t\t// Save the original split percentage to the hidden field to use when splitting points.\n\t\t\t\t\toriginal_splits[i].value = players_chip_count / chip_count_sum;\n\t\t\t\t} else {\n\t\t\t\t\tchip_count[i].value = players_chip_count / chip_count_sum;\n\t\t\t\t\t// Save the original split percentage to the hidden field to use when splitting points.\n\t\t\t\t\toriginal_splits[i].value = players_chip_count / chip_count_sum;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn true;\n}",
"isPokerHand(cards) {\n if (cards.length != 5) {\n return 'false';\n }\n\n var flushSuit = cards[0].getSuit();\n var prevRank = cards[0].getRank();\n\n var i;\n // check if STRAIGHT FLUSH / ROYAL FLUSH\n for (i = 1; i < cards.length; i++) {\n if ((cards[i].getSuit() == flushSuit) && (cards[i].getRank() == (prevRank + 1))) {\n prevRank = cards[i].getRank();\n }\n else if (cards[i].getRank() === 2 && prevRank === 14) {\n // if the card is a 2, it could be valid\n prevRank = cards[i].getRank();\n }\n else {\n break;\n }\n }\n if (i == cards.length) {\n return 'sf';\n }\n\n // check if FOUR OF A KIND\n var sameCardCount = 1;\n prevRank = cards[0].getRank();\n for (i = 1; i < cards.length; i++) {\n\n if (sameCardCount == 4) {\n // 4 cards in a row\n return '4k';\n }\n else if (cards[i].getRank() == prevRank) {\n // card is set, increase rank\n sameCardCount++;\n }\n else {\n // card is not set, set it and update rank\n sameCardCount = 1;\n prevRank = cards[i].getRank();\n }\n }\n if (sameCardCount == 4) {\n return \"4k\";\n }\n\n // check if FULL HOUSE\n let firstCardCount = 1;\n let firstRank = cards[0].getRank();\n let secondCardCount = 0;\n let secondRank = null;\n\n for (i = 1; i < cards.length; i++) {\n if (cards[i].getRank() == firstRank) {\n // card is same as first card\n firstCardCount++;\n }\n else if (secondRank == null) {\n // second rank is not set, set it and \n // update count\n secondRank = cards[i].getRank();\n secondCardCount++;\n }\n else if (cards[i].getRank() == secondRank) {\n // second rank is set and card is same, \n // update counts\n secondCardCount++;\n }\n else {\n // second rank is set, card is not same\n // thus not a full house\n break;\n }\n }\n if ((firstCardCount + secondCardCount) == 5) {\n return \"fh\";\n }\n\n\n // check if STRAIGHT\n prevRank = cards[0].getRank();\n\n for (i = 1; i < cards.length; i++) {\n // to be a straight, the cards must be in ascending order by rank\n if (cards[i].getRank() == (prevRank + 1)) {\n prevRank = cards[i].getRank();\n }\n else if (cards[i].getRank() === 2 && prevRank === 14) {\n // if the card is a 2, and the previous is an ace, it could be valid\n prevRank = cards[i].getRank();\n }\n else {\n break; // not a straight, but could be another poker hand\n }\n }\n if (i == cards.length) {\n return 's';\n }\n\n // check if FLUSH\n for (i = 1; i < cards.length; i++) {\n // to be a flush, the cards must have the same suit\n if (!(cards[i].getSuit() == flushSuit)) {\n break; // not a flush, but could be another poker hand\n }\n }\n // check if we got to the end of the loop\n if (i == cards.length) {\n return 'f';\n }\n\n // none of the poker hands are valid\n return 'false';\n }",
"function create_hand_set(main_arg) {\n // The default is the texas holdem config\n var hole_cards = [];\n var pick_min = 0;\n var pick_max = 2;\n var common_cards = [];\n var hand_set_object = null;\n \n if(_.isObject(main_arg))\n {\n hole_cards = main_arg.hole_cards || [];\n pick_min = main_arg.pick_min || 0;\n common_cards = main_arg.common_cards || [];\n\n if(_.isString(hole_cards)) {\n hole_cards = parse_hands(hole_cards);\n }\n\n if(_.isString(common_cards)) {\n common_cards = parse_hands(common_cards);\n }\n\n pick_max = main_arg.pick_max || hole_cards.length;\n }\n\n hand_set_object = _ucengine_.createProtectedObject(hand_set_prototype, {\n hole_cards: hole_cards,\n hole_pick_min: pick_min,\n hole_pick_max: pick_max,\n board: common_cards\n });\n\n return hand_set_object;\n }",
"function checkPlayerHandOptions(currentPlayerHand) {\n\n for (var i = 0; i < currentPlayerHand.length; ++i) {\n // player can play if he/she has card that is of same color or number\n if (currentPlayerHand[i].Color == discardPile[0].Color ||\n currentPlayerHand[i].Type == discardPile[0].Type) {\n canPlay.push(currentPlayerHand[i])\n }\n\n // player can play if he/she has wild card\n if (currentPlayerHand[i].Type == \"Wild\") {\n canPlay.push(currentPlayerHand[i])\n }\n }\n\n}",
"function cardOnHand() {\n if (player.selectedCarte.visible) return 1;\n else if (playerHand.selectedCarte.visible) return 2;\n else if (playerBoard.selectedCarte.visible) return 3;\n else if (playerPower.selectedCarte.visible) return 4;\n else return 0;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sorts array of jobs by distance | function sortByDistance(jobs){
jobs.sort(function(a,b){
if(a.distance > b.distance){ return 1}
if(a.distance < b.distance){ return -1}
return 0;
});
return jobs;
} | [
"function sortCoordsByDistance(array) {\n array.sort(function (current, next) {\n let dist_current = distanceBetweenPoints(character.real_x, character.real_y, current.x, current.y);\n let dist_next = distanceBetweenPoints(character.real_x, character.real_y, next.x, next.y);\n if (dist_current < dist_next) return -1; else if (dist_current > dist_next) return 1; else return 0;\n });\n return array;\n}",
"function sortResults(position) {\n\n var latlon = new LatLon(position.lat, position.lng);\n \n var locations = document.getElementById('meetings');\n var locationList = locations.querySelectorAll('.location');\n var locationArray = Array.prototype.slice.call(locationList, 0);\n\n locationArray.sort(function(a,b){\n var locA = a.getAttribute('data-latlon').split(',');\n var locB = b.getAttribute('data-latlon').split(',');\n \n distA = latlon.distanceTo(new LatLon(Number(locA[0]),Number(locA[1])));\n distB = latlon.distanceTo(new LatLon(Number(locB[0]),Number(locB[1])));\n return distA - distB;\n });\n \n //Reorder the list\n locations.innerHTML = \"\";\n locationArray.forEach(function(el) {\n locations.appendChild(el);\n });\n}",
"function sortEntitiesByDistance(array) {\n array.sort(function (current, next) {\n let dist_current = parent.distance(character, current);\n let dist_next = parent.distance(character, next);\n if (dist_current < dist_next) return -1; else if (dist_current > dist_next) return 1; else return 0;\n });\n return array;\n}",
"function sortByDist(trees) {\n\ttrees.forEach(function(tree) {\n\t\ttree.dist = getDistanceFromLatLonInM([tree.lon, tree.lat], state.user.location)\n\t})\n\ttrees.sort(function(a, b) {\n\t\tif (a.dist < b.dist)\n\t\t\treturn -1;\n\t\tif (a.dist > b.dist)\n\t\t\treturn 1;\n\t\treturn 0;\n\t})\n\treturn trees\n}",
"function calcDistanceFromUserAndSort(){\n output.bikeStationsArrWithDistance.forEach(calcDistanceFromUser);\n output.bikeStationsArrWithDistance.sort(function(a,b){\n return a.distanceFromUser - b.distanceFromUser;\n });\n\n function calcDistanceFromUser(curStationObj){\n //!!!!!!!!!!!!!!!!!!!!!!!! CHANGE PSEUDO_userObj with appropriate user obj\n curStationObj.distanceFromUser = getDistanceFromLatLonInMiles(PSEUDO_userObj.lat, PSEUDO_userObj.lon, curStationObj.lat, curStationObj.lon);\n return curStationObj;\n };\n }",
"sortTrip () {\r\n this.recorded_trip.sort(function (x, y) {\r\n if (x.distance < y.distance) {\r\n return 1 // sorts each trip from highest(y) to lowest(x)\r\n }\r\n if (x.distance > y.distance) {\r\n return -1 // sorts each trip from highest(x) to lowest(y)\r\n } // x must equal to y\r\n return 0 // trip order will remain the same\r\n })\r\n }",
"function calculateDistancesAndSortSearchResultsList() {\n var sortby = $('#page-find-results div.sortpicker a.active').attr('data-sortby');\n var target = $('#search_results');\n var here = MARKER_GPS.getLatLng();\n\n // step 1: recalculate the distance\n // seems wasteful if we're gonna sort by name anyway, but it's not: we still need to update distance readouts even if we're not sorting by distance\n target.children().each(function () {\n var raw = $(this).data('raw');\n var point = L.latLng(raw.lat,raw.lng);\n var meters = Math.round( here.distanceTo(point) );\n var bearing = here.bearingWordTo(point);\n\n // save the distance in meters, for possible distance sorting\n $(this).data('meters',meters);\n\n // make up the text: 12.3 mi NE then fill it in\n var miles = (meters / 1609.344).toFixed(1);\n var feet = Math.round( meters * 3.2808399 );\n var text = ( (feet > 900) ? miles + ' mi' : feet + ' ft' ) + ' ' + bearing;\n $(this).find('span.zoom_distance').text(text);\n });\n\n // step 2: perform the sort\n switch (sortby) {\n case 'distance':\n target.children('li').sort(_sortResultsByDistance);\n break;\n case 'alphabetical':\n target.children('li').sort(_sortResultsByName);\n break;\n }\n target.listview('refresh',true);\n}",
"sortCarsOnLoc(cars, lat, lng){\n return cars.slice(0).map(c => {\n c.distanceKM = distanceKM(\n c.location.coordinates.latitude, c.location.coordinates.longitude, lat, lng \n ); \n return c;\n }).sort((c1, c2) => (c1.distanceKM - c2.distanceKM));\n }",
"function filterByMaxDistance(jobs){\n\t\tvar filtereredJobs = [];\n\t\t\tjobs.forEach(function(job) {\n\t\t\t// console.log(job.max_distance);\n\t\t\t\tif (job.max_distance == null){ \n\t\t\t\t\tif (calcDistanceKms(map,job) <= 3) {\t\n\t\t\t\t\t\tfiltereredJobs.push(job);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (calcDistanceKms(map,job) <= job.max_distance) {\t\n\t\t\t\t\t\tfiltereredJobs.push(job);\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t});\n\t\treturn filtereredJobs;\n\t}",
"async function sortPosts(posts_array, keyword, userLat, userLong) {\r\n let post_object_list_with_weights = [];\r\n\r\n\r\n for (let post_id of posts_array) {\r\n \r\n let post_with_weight = await getPost(post_id, keyword, userLat, userLong);\r\n post_object_list_with_weights.push(post_with_weight);\r\n\r\n }\r\n\r\n let sorted_posts = arraySort(post_object_list_with_weights, 'weight'); // Sort weight ascending order\r\n return sorted_posts;\r\n}",
"function sortByDistance(pivot, cities = []) {\n return cities.sort((a, b) => {\n return distanceBetween(pivot, a) - distanceBetween(pivot, b);\n });\n}",
"function scheduleJob(jobs) {\n let sortedByProfit = jobs.sort((a, b) => b[2] - a[2]);\n let time = 1;\n let maxProfit = 0;\n let result = [];\n console.log(sortedByProfit)\n\n for (let i in sortedByProfit) {\n if (sortedByProfit[i][1] >= time) {\n result.push(sortedByProfit[i]);\n maxProfit += sortedByProfit[i][2];\n time++;\n }\n }\n result.push(maxProfit)\n return result\n}",
"function sortClumps (clumped) {\n var bigArray = [];\n\n while (clumped.length > 0) {\n var biggest = 0;\n var bigIndex = 0;\n for (var i = 0; i < clumped.length; i++) {\n if (clumped[i][0][0].getTime() > biggest) {\n biggest = clumped[i][0][0].getTime();\n bigIndex = i;\n };\n };\n bigArray.unshift(clumped[bigIndex]);\n clumped.splice(bigIndex, 1);\n };\n return bigArray;\n}",
"function sort(performer){\n var i = 0;\n for(i; i < performer.length; i++){\n if(performer[i]['reference'] === gLoggedUser){\n break;\n }\n }\n var temp = performer[i];\n performer.splice(i, 1);\n performer.push(temp);\n}",
"function sortTask() {\n var sheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName(\"priority_queue\");\n //var sheet = SpreadsheetApp.getActiveSheet();//.setName('Settings');\n var col_num=sheet.getDataRange().getNumColumns();\n var row_num=sheet.getDataRange().getNumRows();\n var priority_relevant_cols=sheet.getRange(1,1,row_num,3).getValues();\n var calculated_priority=[];\n var currentTime=new Date();\n for(i=0;i<row_num;i++){//reading all tasks and caculate the priority for sorting\n var priority=priority_relevant_cols[i][0];\n var assigningTime=new Date(priority_relevant_cols[i][1]);\n var requestingTime=new Date(priority_relevant_cols[i][2]);\n calculated_priority.push([]);\n \n var difference= Math.floor((currentTime-assigningTime)/1000/3600/24/10);//every 10 days' delay equals one priority level up\n if(i==0) calculated_priority[i].push(\"cal_pri\");\n else if(currentTime-requestingTime>=-1) calculated_priority[i].push(1000000);\n else calculated_priority[i].push(priority+ difference);\n\n }\n sheet.getRange(1, col_num+1, row_num, 1).setValues(calculated_priority);\n sheet.setFrozenRows(1);\n sheet.getRange(1, 1, row_num, col_num+1).sort({column:col_num+1,ascending: false});\n sheet.deleteColumn(col_num+1);\n}",
"sortTasks() {\n var tempTasks = this.taS.getTasks();\n tempTasks.sort(function(a,b){\n return a.deadline-b.deadline;\n });\n return tempTasks;\n }",
"function sortResults(username, friends, unheard, searchType, results) {\r\n\r\n // we use the sort function to order the results based on their score\r\n results.sort((a, b) => parseFloat(b.score) - parseFloat(a.score));\r\n\r\n if (unheard) {\r\n\r\n // first we make the progress bar visible and describe the current status\r\n document.getElementById('progress').style.width = '0%';\r\n document.getElementById('status').textContent = 'Filtering out results you have already heard...';\r\n\r\n let unheardReleases = [];\r\n filterUnheard(username, searchType, results, 0, unheardReleases);\r\n } else {\r\n // for the first 50 items in the results array, we want to display them\r\n pageDisplay(searchType, results, 0);\r\n }\r\n}",
"orderSegments() {\n this.segments.sort(this.compareSegment);\n }",
"function scoreSort(a, b){\n return b.score-a.score;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SEARCH CODE matchSearchFunc for definition to searchTerm (EngPlain) | function matchSearchFuncEngPlain (searchTerm) {
return function(element) {
if (element.definition == searchTerm) {
return true;
} else {
return false;
}
}
} | [
"function matchSearchFuncEngRegex (searchTerm) {\n return function(element) {\n var re = \".*\" + searchTerm + \".*\";\n if (element.definition.match(re)) {\n return true;\n } else {\n return false;\n }\n }\n }",
"function myIndexOf(string, searchTerm) {}",
"function matchSearchFuncMoroRegex (searchTerm) {\n return function(element) {\n return findMoroWordInArrayMoroRegex(element.moroword, searchTerm)\n }\n }",
"function search(searchString, titleSearchBool, tagsSearchBool, commentsSearchBool) {\r\n\tvar theTerms = splitSearchString(searchString);\r\n\tif (theTerms.length == 0) {\r\n\t\tvar allEntries = dataHandler.getAllEntries();\r\n\t\treturn allEntries;\r\n\t}\r\n\t\r\n\tvar positiveMatches = [];\r\n\tvar negativeMatches = [];\r\n\tvar finalMatches = [];\r\n\r\n\t\r\n\t// Get the first set of positive matches, corresponding to the first positive search term.\r\n\tvar termIndex = 0;\r\n\twhile((theTerms[termIndex].charAt(0) == \"-\") && (termIndex < theTerms.length)) termIndex++;\r\n\tif (termIndex < theTerms.length) {\r\n\t\tif (titleSearchBool) {\r\n\t\t\tpositiveMatches = positiveMatches.concat(dataHandler.findEntries(theTerms[termIndex], \"title\"));\r\n\t\t}\r\n\t\tif (tagsSearchBool) {\r\n\t\t\tpositiveMatches = positiveMatches.concat(dataHandler.findEntries(theTerms[termIndex], \"tag\"));\r\n\t\t}\r\n\t\tif (commentsSearchBool) {\r\n\t\t\tpositiveMatches = positiveMatches.concat(dataHandler.findEntries(theTerms[termIndex], \"comment\"));\r\n\t\t}\r\n\t\tpositiveMatches = unique(positiveMatches);\r\n\t}\r\n\r\n\t\r\n\t// Now, loop over the rest of the positive terms, ANDing the resulting arrays with\r\n\t// our first results array.\r\n\tvar nextPositiveMatches = [];\r\n\tfor (termIndex = 1; termIndex < theTerms.length; termIndex++) {\r\n\t\tif (theTerms[termIndex].charAt(0) != \"-\") {\r\n\t\t\tif (titleSearchBool) {\r\n\t\t\t\tnextPositiveMatches = nextPositiveMatches.concat(dataHandler.findEntries(theTerms[termIndex], \"title\"));\r\n\t\t\t}\r\n\t\t\tif (tagsSearchBool) {\r\n\t\t\t\tnextPositiveMatches = nextPositiveMatches.concat(dataHandler.findEntries(theTerms[termIndex], \"tag\"));\r\n\t\t\t}\r\n\t\t\tif (commentsSearchBool) {\r\n\t\t\t\tnextPositiveMatches = nextPositiveMatches.concat(dataHandler.findEntries(theTerms[termIndex], \"comment\"));\r\n\t\t\t}\r\n\t\t\tnextPositiveMatches = unique(nextPositiveMatches);\r\n\t\t\tpositiveMatches = positiveMatches.intersection(nextPositiveMatches);\r\n\t\t\tif (positiveMatches == null)\r\n\t\t\t\treturn [];\r\n\t\t\tnextPositiveMatches = [];\r\n\t\t}\r\n\t}\r\n\t\r\n\t// Get negative matches.\r\n\tfor (termIndex = 0; termIndex < theTerms.length; termIndex++) {\r\n\t\tif (theTerms[termIndex].charAt(0) == \"-\") {\r\n\t\t\tif (titleSearchBool) {\r\n\t\t\t\tnegativeMatches = negativeMatches.concat(dataHandler.findEntries(theTerms[termIndex].substring(1), \"title\"));\r\n\t\t\t}\r\n\t\t\tif (tagsSearchBool) {\r\n\t\t\t\tnegativeMatches = negativeMatches.concat(dataHandler.findEntries(theTerms[termIndex].substring(1), \"tag\"));\r\n\t\t\t}\r\n\t\t\tif (commentsSearchBool) {\r\n\t\t\t\tnegativeMatches = negativeMatches.concat(dataHandler.findEntries(theTerms[termIndex].substring(1), \"comment\"));\r\n\t\t\t}\r\n\t\t\tnegativeMatches = unique(negativeMatches);\r\n\t\t}\r\n\t}\r\n\r\n\t// Subtract the negative matches from the positive matches; put the result\r\n\t// in finalMatches.\r\n\tvar foundNegativeMatch;\r\n\tfor (var posIndex = 0; posIndex < positiveMatches.length; posIndex++) {\r\n\t\tfoundNegativeMatch = false;\r\n\t\tfor (var negIndex = 0; negIndex < negativeMatches.length; negIndex++) {\r\n\t\t\tif (positiveMatches[posIndex].getId() == negativeMatches[negIndex].getId()) {\r\n\t\t\t\tfoundNegativeMatch = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!foundNegativeMatch) {\r\n\t\t\tfinalMatches.push(positiveMatches[posIndex]);\r\n\t\t}\r\n\t}\r\n\t\r\n\t// finalMatches should now have all final matches.\r\n\treturn finalMatches;\r\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}",
"searchDocuments() {\n\n let searchObj = {}\n if (this.searchType === 'query') {\n searchObj.query = this.query;\n } else if (this.searchType === 'field') {\n searchObj.fieldCode = this.queryField;\n searchObj.fieldValue = this.queryFieldValue;\n }\n this.etrieveViewer.Etrieve.searchDocuments(searchObj)\n .catch(err => {\n console.error(err);\n });\n }",
"function 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 searchProgram(searchTerms) {\n\t\n\tvar matching_program_indices = [];\n\t\n\tif(!searchTerms) {\n\t\tsearchTerms = '';\n\t}\n\t\n\tif(searchTerms == '') {\n\t\tvar i;\n\t\tfor(i in programs) {\n\t\t\tmatching_program_indices.push(i);\n\t\t}\n\t}\n\telse\n\t{\n\t\tvar i;\n\t\tfor(i in programs) {\n\t\t\t\n\t\t\t//GIVEProgram reference and program name\n\t\t\tvar p = programs[i];\n\t\t\t\n\t\t\t//if name contains the search terms anywhere in the string,\n\t\t\t//add the program to the list of search results\n\t\t\tif(caseInsensitiveStringSearch(p.name, searchTerms) >= 0) {\n\t\t\t\tmatching_program_indices.push(i);\n\t\t\t}\n\t\t\telse if(p.descript) {\n\t\t\t\tif(caseInsensitiveStringSearch(p.descript, searchTerms) >= 0) {\n\t\t\t\t\tmatching_program_indices.push(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t/*\n\tclearLeftSideBar();\n\taddProgramsToLeftSideBar(matching_program_indices);\n\tif(matching_program_indices.length > 0) {\n\t\tdisplayProgramInfo(matching_program_indices[0]);\n\t}\n\t */\n\tprogram_search_results = matching_program_indices;\n}",
"search(text) {\n return this.addOption('search', text);\n }",
"function findMatch(node, params) {\n\n var nodeValue = node.nodeValue.trim();\n var nodeIndex = params.nodeIndex;\n var searchTerm = params.searchTerm;\n var searchElements = params.searchElements;\n var field = params.field;\n var total = params.total;\n var count = params.count;\n var text = params.text;\n var currentIndex = params.currentIndex;\n\n if (text === \"\") {\n text = nodeValue;\n } else {\n text += \" \" + nodeValue;\n }\n console.log(\"nodeIndex: \" + nodeIndex + \" - \" + nodeValue);\n console.log(textNodes[nodeIndex]);\n\n // if searchTerm is found, current text node is the end node for one count\n var index = text.toLowerCase().indexOf(searchTerm.toLowerCase(), currentIndex + 1);\n\n // if there is multiple instances of searchTerm in text (loops through while loop), use oldStartIndex to calculate startIndex\n var oldStartIndex, startNodeIndex;\n\n // stores the number of characters the start of searchTerm is from the end of text\n var charactersFromEnd = text.length - index;\n //console.log(\"charactersFromEnd: \" + charactersFromEnd);\n\n // loop through text node in case there is more than one searchTerm instance in text\n while (index !== -1) {\n currentIndex = index;\n\n // remember how many text nodes before current node we are pulling from textNodes\n var textNodesBackIndex = nodeIndex - 1;\n console.log(textNodesBackIndex);\n\n // textSelection will contain a combined string of all text nodes where current searchTerm spans over\n var textSelection = nodeValue;\n var startNode;\n\n // set textSelection to contain prevSibling text nodes until the current searchTerm matches\n while (textSelection.length < charactersFromEnd) {\n console.log(\"textSelection.length: \" + textSelection.length + \" < \" + charactersFromEnd);\n //console.log(\"old textSelection: \" + textSelection);\n console.log(\"textnodesback index: \" + textNodesBackIndex + \" \" + textNodes[textNodesBackIndex].nodeValue);\n\n textSelection = textNodes[textNodesBackIndex].nodeValue.trim() + \" \" + textSelection;\n //console.log(\"space added: \" + textSelection);\n textNodesBackIndex--;\n }\n\n // use old startNodeIndex value before re-calculating it if its the same as new startNodeIndex\n // startIndex needs to ignore previous instances of text\n var startIndex;\n if (startNodeIndex != null && startNodeIndex === textNodesBackIndex + 1) {\n // find index searchTerm starts on in text node (or prevSibling)\n startIndex = textSelection.toLowerCase().indexOf(searchTerm.toLowerCase(), oldStartIndex + 1);\n } else {\n startIndex = textSelection.toLowerCase().indexOf(searchTerm.toLowerCase());\n }\n oldStartIndex = startIndex;\n\n // startNode contains beginning of searchTerm and node contains end of searchTerm\n var startNodeIndex = textNodesBackIndex + 1;\n // possibly null parentNode because highlighted text before, adding MARK tag and then removed it\n startNode = textNodes[startNodeIndex];\n //console.log(\"final textSelection: \" + textSelection);\n\n if (startIndex !== -1) {\n // set parent as first element parent of textNode\n console.log(\"end parent\");\n console.log(node);\n var endParent = node.parentNode;\n\n console.log(\"start parent\");\n console.log(startNode);\n var startParent = startNode.parentNode;\n\n var targetParent;\n // start and end parents are the same\n if (startParent === endParent) {\n console.log(\"start parent is end parent\");\n targetParent = startParent;\n }\n // start parent is target parent element\n else if ($.contains(startParent, endParent)) {\n console.log(\"start parent is larger\");\n targetParent = startParent;\n }\n // end parent is target parent element\n else if ($.contains(endParent, startParent)) {\n console.log(\"end parent is larger\");\n targetParent = endParent;\n }\n // neither parents contain one another\n else {\n console.log(\"neither parent contains the other\");\n // iterate upwards until startParent contains endParent\n while (!$.contains(startParent, endParent) && startParent !== endParent) {\n startParent = startParent.parentNode;\n //console.log(startParent);\n }\n targetParent = startParent;\n }\n\n // set startNode to node before the parent we are calculating with\n if (textNodesBackIndex !== -1) {\n startNode = textNodes[textNodesBackIndex];\n textNodesBackIndex--;\n\n var startElement = startNode.parentNode;\n\n // continue adding text length to startIndex until parent elements are not contained in targetParent\n while (($.contains(targetParent, startElement) || targetParent === startElement) && textNodesBackIndex !== -1) {\n startIndex += startNode.nodeValue.trim().length + 1;\n startNode = textNodes[textNodesBackIndex];\n textNodesBackIndex--;\n startElement = startNode.parentNode;\n }\n }\n\n // find index searchTerm ends on in text node\n var endIndex = startIndex + searchTerm.length;\n /*console.log(\"start index: \" + startIndex);\n console.log(\"end index: \" + endIndex);*/\n\n // if a class for field search already exists, use that instead\n var dataField = \"data-tworeceipt-\" + field + \"-search\";\n if ($(targetParent).attr(dataField) != null) {\n console.log(\"EXISTING SEARCH ELEMENT\");\n console.log($(targetParent).attr(dataField));\n searchElements[count] = {\n start: startIndex,\n end: endIndex,\n data: parseInt($(targetParent).attr(dataField)),\n startNodeIndex: startNodeIndex,\n endNodeIndex: nodeIndex\n };\n } else {\n searchElements[count] = {\n start: startIndex,\n end: endIndex,\n data: count,\n startNodeIndex: startNodeIndex,\n endNodeIndex: nodeIndex\n };\n console.log(\"NEW SEARCH ELEMENT\");\n $(targetParent).attr(dataField, count);\n console.log($(targetParent));\n }\n\n console.log(searchElements[count]);\n\n count++;\n } else {\n console.log(textSelection);\n console.log(searchTerm);\n }\n\n index = text.toLowerCase().indexOf(searchTerm.toLowerCase(), currentIndex + 1);\n charactersFromEnd = text.length - index;\n //console.log(\"characters from end: \" + charactersFromEnd);\n\n if (total != null && count === total) {\n console.log(\"Completed calculations for all matched searchTerms\");\n nodeIndex++;\n return {\n nodeIndex: nodeIndex,\n searchTerm: searchTerm,\n searchElements: searchElements,\n field: field,\n total: total,\n count: count,\n text: text,\n currentIndex: currentIndex,\n result: false\n };\n }\n }\n nodeIndex++;\n return {\n nodeIndex: nodeIndex,\n searchTerm: searchTerm,\n searchElements: searchElements,\n field: field,\n total: total,\n count: count,\n text: text,\n currentIndex: currentIndex,\n result: true\n };\n}",
"visitSearch_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function searchFunction () {\n activateSearch($searchInput, 'input');\n activateSearch($submit, 'click');\n}",
"match(word) {\n if (this.pattern.length == 0) return [-100 /* NotFull */]\n if (word.length < this.pattern.length) return null\n let { chars, folded, any, precise, byWord } = this\n // For single-character queries, only match when they occur right\n // at the start\n if (chars.length == 1) {\n let first = codePointAt(word, 0),\n firstSize = codePointSize(first)\n let score = firstSize == word.length ? 0 : -100 /* NotFull */\n if (first == chars[0]);\n else if (first == folded[0]) score += -200 /* CaseFold */\n else return null\n return [score, 0, firstSize]\n }\n let direct = word.indexOf(this.pattern)\n if (direct == 0)\n return [\n word.length == this.pattern.length ? 0 : -100 /* NotFull */,\n 0,\n this.pattern.length\n ]\n let len = chars.length,\n anyTo = 0\n if (direct < 0) {\n for (\n let i = 0, e = Math.min(word.length, 200);\n i < e && anyTo < len;\n\n ) {\n let next = codePointAt(word, i)\n if (next == chars[anyTo] || next == folded[anyTo]) any[anyTo++] = i\n i += codePointSize(next)\n }\n // No match, exit immediately\n if (anyTo < len) return null\n }\n // This tracks the extent of the precise (non-folded, not\n // necessarily adjacent) match\n let preciseTo = 0\n // Tracks whether there is a match that hits only characters that\n // appear to be starting words. `byWordFolded` is set to true when\n // a case folded character is encountered in such a match\n let byWordTo = 0,\n byWordFolded = false\n // If we've found a partial adjacent match, these track its state\n let adjacentTo = 0,\n adjacentStart = -1,\n adjacentEnd = -1\n let hasLower = /[a-z]/.test(word),\n wordAdjacent = true\n // Go over the option's text, scanning for the various kinds of matches\n for (\n let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */;\n i < e && byWordTo < len;\n\n ) {\n let next = codePointAt(word, i)\n if (direct < 0) {\n if (preciseTo < len && next == chars[preciseTo])\n precise[preciseTo++] = i\n if (adjacentTo < len) {\n if (next == chars[adjacentTo] || next == folded[adjacentTo]) {\n if (adjacentTo == 0) adjacentStart = i\n adjacentEnd = i + 1\n adjacentTo++\n } else {\n adjacentTo = 0\n }\n }\n }\n let ch,\n type =\n next < 0xff\n ? (next >= 48 && next <= 57) || (next >= 97 && next <= 122)\n ? 2 /* Lower */\n : next >= 65 && next <= 90\n ? 1 /* Upper */\n : 0 /* NonWord */\n : (ch = fromCodePoint(next)) != ch.toLowerCase()\n ? 1 /* Upper */\n : ch != ch.toUpperCase()\n ? 2 /* Lower */\n : 0 /* NonWord */\n if (\n !i ||\n (type == 1 /* Upper */ && hasLower) ||\n (prevType == 0 /* NonWord */ && type != 0) /* NonWord */\n ) {\n if (\n chars[byWordTo] == next ||\n (folded[byWordTo] == next && (byWordFolded = true))\n )\n byWord[byWordTo++] = i\n else if (byWord.length) wordAdjacent = false\n }\n prevType = type\n i += codePointSize(next)\n }\n if (byWordTo == len && byWord[0] == 0 && wordAdjacent)\n return this.result(\n -100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0),\n byWord,\n word\n )\n if (adjacentTo == len && adjacentStart == 0)\n return [\n -200 /* CaseFold */ -\n word.length +\n (adjacentEnd == word.length ? 0 : -100) /* NotFull */,\n 0,\n adjacentEnd\n ]\n if (direct > -1)\n return [\n -700 /* NotStart */ - word.length,\n direct,\n direct + this.pattern.length\n ]\n if (adjacentTo == len)\n return [\n -200 /* CaseFold */ + -700 /* NotStart */ - word.length,\n adjacentStart,\n adjacentEnd\n ]\n if (byWordTo == len)\n return this.result(\n -100 /* ByWord */ +\n (byWordFolded ? -200 /* CaseFold */ : 0) +\n -700 /* NotStart */ +\n (wordAdjacent ? 0 : -1100) /* Gap */,\n byWord,\n word\n )\n return chars.length == 2\n ? null\n : this.result(\n (any[0] ? -700 /* NotStart */ : 0) +\n -200 /* CaseFold */ +\n -1100 /* Gap */,\n any,\n word\n )\n }",
"function getSearchTerm(params) {\n\tvar string = \"\";\n\tfor (var item in params) {\n\t\tstring += params[item] + ' ';\n\t}\n\treturn encodeURI(string);\n}",
"function text_search(q, ids, search_index){\n if (!search_index){\n console.log('Warning, no search index, searching manually');\n ids = ids.filter(id => id.match(q));\n } else {\n const results = search_index.query((query) => {\n const {LEADING, TRAILING} = lunr.Query.wildcard;\n q.split(/(\\s+)/).forEach(s => {\n if (s){\n query = query.term(s, {wildcard: LEADING|TRAILING});\n }\n });\n return query;\n });\n const valid_ids = {};\n results.forEach(r => valid_ids[r.ref] = 1);\n ids = ids.filter(id => valid_ids[id]);\n }\n return ids;\n}",
"function perform_search() {\n if (lastSearchType == \"D\") {\n searchHistory();\n } else if (lastSearchType == \"E\") {\n searchEpg();\n }\n }",
"function mkSearchResultsFilter(index, filterText) {\n var tokens = index.pipeline.run(lunr.tokenizer(filterText));\n if (tokens.length > 0) {\n var resultHash = {};\n index.search(filterText).map(function (res) {\n resultHash[res['ref']] = res['score'];\n });\n return function (ref) {\n return (resultHash[ref.id] != null);\n };\n } else {\n /* by default return all results */\n return function (e) { return true; };\n }\n}",
"function searchFunc() {\n\t // get the value of the search input field\n\t var searchString = $('#search').val(); //.toLowerCase();\n\t markers.setFilter(showFamily);\n\n\t // here we're simply comparing the 'state' property of each marker\n\t // to the search string, seeing whether the former contains the latter.\n\t function showFamily(feature) {\n\t return (feature.properties.last_name === searchString || feature.properties[\"always-show\"] === true);\n\t }\n\t}",
"function search(foundArticles, searchedName) {\n matchedArticles = [];\n str = searchedName.replace(/\\s/g, '');\n if (str == \"\") {\n return matchedArticles;\n }\n foundArticles.forEach(function(article) {\n if (article.name.toLowerCase().includes(searchedName.toLowerCase())) {\n matchedArticles.push(article);\n }\n else if (article.author.toLowerCase().includes(searchedName.toLowerCase())) {\n matchedArticles.push(article);\n }\n else if (article.keywords.toLowerCase().includes(searchedName.toLowerCase())) {\n matchedArticles.push(article);\n }\n });\n return matchedArticles;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a convenience method that generates code to read a variable, given its index and a Boolean that indicates whether it's a global. | getVariable (index, isGlobal) {
if (isGlobal) {
return this.op("get_global").varuint(index, "global_index");
} else {
return this.op("get_local").varuint(index, "local_index");
}
} | [
"setVariable (index, isGlobal, tee) {\n if (isGlobal) {\n if (tee) {\n this\n .op(\"set_global\").varuint(index, \"global_index\")\n .op(\"get_global\").varuint(index, \"global_index\");\n } else {\n this.op(\"set_global\").varuint(index, \"global_index\");\n }\n } else if (tee) {\n this.op(\"tee_local\").varuint(index, \"local_index\");\n } else {\n this.op(\"set_local\").varuint(index, \"local_index\");\n }\n }",
"function getManifestvariable(variableName) {\n return config[variableName]; //dont know if called\n}",
"function lookup_variable_value(variable,env) {\n function env_loop(env) {\n if (is_empty_environment(env)) {\n error(\"Unbound variable: \" + variable);\n } else if (has_binding_in_frame(variable,first_frame(env))) {\n return first_frame(env)[variable];\n } else {\n return env_loop(enclosing_environment(env));\n }\n }\n return env_loop(env);\n}",
"offsetOf(variable, index) {\n const slot = this.getLocalDepth(variable);\n const depth = this.getMemoryOffset(slot);\n const size = this.sizeOfVal(variable);\n\n if (this.stackTop().size != 1) {\n this.error(\n \"Cannot assign value larger than 1 byte to bus or string index.\"\n );\n } else if (size != 1) {\n this.error(\"cannot index a variable that is not a bus or string.\");\n }\n\n return depth + index + 2; // account for 2 bytes of padding prior.\n }",
"function get_value(loc, mode, intcode) {\r\n if (mode == 0) {\r\n // position mode\r\n return intcode[loc];\r\n } else if (mode == 1) {\r\n // immediate mode\r\n return loc;\r\n }\r\n}",
"get(index){\n // return the value of an element at given index\n return memory.get(index);\n }",
"getVariable(index) {\n const depth = this.getLocalDepth(index); // depth of the local in the stack.\n const memoryOffset = this.getMemoryOffset(depth); // actual depth in BF memory.\n const size = this.sizeOfVal(index); // how many byes to copy.\n const type = this.typeOfVal(index);\n\n for (let i = 0; i < size; i++) {\n this.copyByte(memoryOffset, true);\n }\n\n this.stack.push(StackEntry(type, size));\n }",
"function get_value_for_variable_from_workspace(variable_name){\n var value = scilabVariableMap.get(variable_name); // map in prerequisitefile.js\n if(value == undefined || value == null){\n return null;\n }else{\n return value;\n }\n\n}",
"function get_variable_display(instrPtr, variableLoc, objData) { \n var varName = variableLoc.name\n var varLoc = variableLoc.value\n\n // resolve structs that are split between registers\n if (objData[varName] && variableLoc.hasOwnProperty('var_offset') && variableLoc['var_offset'] != null) {\n var offset = variableLoc['var_offset'];\n var name = varName + \".\" + objData[varName][offset];\n return name + \"=\" + \"<span class='reg'>\" + varLoc + \"</span>\";\n }\n\n // resolve names for xword ptrs\n if (objData[varName] && instrPtr) {\n var reg = instrPtr[0]\n var offset = instrPtr[2] != \"\" ? parseInt(instrPtr[2], 16) : 0;\n if (reg == varLoc && objData[varName][offset]) {\n var sign = offset >= 0 ? \"+\" : \"\";\n var name = varName + \".\" + objData[varName][offset];\n return name + \"=\" + \"<span class='reg'>\" + varLoc + \"</span>\" + sign + '0x' + offset.toString(16);\n }\n }\n return varName + \"=\" + \"<span class='reg'>\" + varLoc + \"</span>\";\n}",
"setVariable(index) {\n // how far down the value is, in the compile time stack.\n const slot = this.getLocalDepth(index);\n // how far down the first byte of the variable will be in BF memory-tape\n const memoryOffset = this.getMemoryOffset(slot);\n const size = this.sizeOfVal(index);\n\n let stackTopSize = this.sizeOfVal(this.stack.length - 1);\n if (size != stackTopSize) {\n this.error(\n `Cannot assign value of size ${size} to value of size ${stackTopSize}`\n );\n }\n\n for (let i = 0; i < size; i++) {\n this.setByte(memoryOffset - size + 1);\n }\n this.stack.pop();\n }",
"initiateVariableName() {\n this.variableName = this.variableName || `val_${this.compiler.referenceVariableCounter++}`;\n }",
"function getGlobal(key) {\n // @ts-ignore\n return globalRef && globalRef[key];\n}",
"get(name) {\n if (this.current.hasOwnProperty(name)) {\n return this.current[name];\n } else {\n return this.builtins[name];\n }\n }",
"function parseGlobal() {\n var name = t.identifier(getUniqueName(\"global\"));\n var type; // Keep informations in case of a shorthand import\n\n var importing = null;\n maybeIgnoreComment();\n\n if (token.type === _tokenizer.tokens.identifier) {\n name = identifierFromToken(token);\n eatToken();\n } else {\n name = t.withRaw(name, \"\"); // preserve anonymous\n }\n /**\n * maybe export\n */\n\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.export)) {\n eatToken(); // (\n\n eatToken(); // export\n\n var exportName = token.value;\n eatTokenOfType(_tokenizer.tokens.string);\n state.registredExportedElements.push({\n exportType: \"Global\",\n name: exportName,\n id: name\n });\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n /**\n * maybe import\n */\n\n\n if (lookaheadAndCheck(_tokenizer.tokens.openParen, _tokenizer.keywords.import)) {\n eatToken(); // (\n\n eatToken(); // import\n\n var moduleName = token.value;\n eatTokenOfType(_tokenizer.tokens.string);\n var _name3 = token.value;\n eatTokenOfType(_tokenizer.tokens.string);\n importing = {\n module: moduleName,\n name: _name3,\n descr: undefined\n };\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n /**\n * global_sig\n */\n\n\n if (token.type === _tokenizer.tokens.valtype) {\n type = t.globalType(token.value, \"const\");\n eatToken();\n } else if (token.type === _tokenizer.tokens.openParen) {\n eatToken(); // (\n\n if (isKeyword(token, _tokenizer.keywords.mut) === false) {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unsupported global type, expected mut\" + \", given \" + tokenToString(token));\n }();\n }\n\n eatToken(); // mut\n\n type = t.globalType(token.value, \"var\");\n eatToken();\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n if (type === undefined) {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Could not determine global type\" + \", given \" + tokenToString(token));\n }();\n }\n\n maybeIgnoreComment();\n var init = [];\n\n if (importing != null) {\n importing.descr = type;\n init.push(t.moduleImport(importing.module, importing.name, importing.descr));\n }\n /**\n * instr*\n */\n\n\n while (token.type === _tokenizer.tokens.openParen) {\n eatToken();\n init.push(parseFuncInstr());\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n return t.global(type, init, name);\n }",
"function get (str) {\n if (registers.hasOwnProperty(str))\n return Number(registers[str]);\n else if (str === \"$zero\")\n return 0;\n else\n output(\"Error getting register \" + str + \" on Line \" + line, 'e');\n}",
"function readGlobalYUI(callback) {\n console.log(\"reading global ENV from yui.js [\" + YUIVersion + \"]\");\n\n http.request({\n host : \"yui.yahooapis.com\",\n path : \"/\" + YUIVersion + \"/build/yui/yui.js\"\n\n }, function(resp){\n var _yuiRaw = \"\";\n resp.on('data', function(data){\n _yuiRaw += data;\n });\n resp.on('end', function(){\n whiteList = findYUIAdd(esprima.parse(_yuiRaw, {tokens : true}).body);\n setTimeout(callback, 1000);\n });\n\n }).end();\n\n\n}",
"get(index) {\n let foundNode = this._find(index);\n return foundNode ? foundNode.value : undefined;\n }",
"function evaluate_var_definition(stmt,env) {\n define_variable(var_definition_variable(stmt),\n evaluate(var_definition_value(stmt),env),\n env);\n return undefined;\n}",
"function make ( ) {\n\n //\n // Most of these fields and methods are involved in the variable\n // identification algorithm.\n //\n //\n // The basic way this algorithm works is that as a scope is walked,\n // variables are collected into an 'unknown' array.\n //\n // Assigned variables are also accumulated.\n // When the scope ends, assigned variables are compared to unknown variables.\n // If the variable was assigned in this scope and not in any scope above\n // it (with except possibly the global scope), then the unknown's callback\n // is invoked. This callback is used to set the variable for the\n // corresponding identifiers.\n // Otherwise, if the variable's assignment is not found, the unkown is\n // bubbled up to the scope above.\n // This continues upward until we hit the global scope, where we then store\n // the remaining unknowns as imports.\n //\n // TODO(kzentner): Improve imports and exports, possible using an entirely\n // seperate module.\n //\n\n return {\n unknownses : null,\n scope_depth : null,\n current_scope : null,\n objects : null,\n variables : null,\n get_objects : function ( ) {\n return this.objects [ this.objects.length - 1 ];\n },\n get_unknowns : function ( ) {\n return this.unknownses [ this.unknownses.length - 1 ];\n },\n add_object : function ( obj ) {\n this.get_objects ( ).push ( obj );\n },\n push_object_list : function ( obj_list ) {\n this.objects.push ( obj_list );\n },\n pop_object_list : function ( ) {\n this.objects.pop ( );\n },\n get_text : function ( text, callback ) {\n var unknown = this.get_unknowns ( ).get_text ( text );\n if ( unknown === undefined ) {\n unknown = [];\n this.get_unknowns ( ).set_text ( text, unknown );\n }\n unknown.push ( { scope : this.current_scope,\n callback : callback } );\n },\n set_variable : function ( text, val ) {\n var variable = this.current_scope.get_text ( text );\n if ( variable === undefined || variable.location === 'global' ) {\n // This is a variable declaration.\n variable = varb.make ( text );\n this.variables.push ( variable );\n this.current_scope.set_text ( text, variable );\n }\n variable.assignments.push ( val );\n return variable;\n },\n push_scope : function ( new_scope ) {\n misc.assert ( new_scope.above ( ) === this.current_scope,\n \"New scope should be child of current scope.\" );\n if ( this.current_scope.children === undefined ) {\n this.current_scope.children = [];\n }\n this.current_scope.children.push ( new_scope );\n this.current_scope = new_scope;\n this.scope_depth += 1;\n this.unknownses.push ( scope.make ( ) );\n },\n finalize_scope : function ( ) {\n var unknowns = this.get_unknowns ( );\n var parent_unknowns;\n if ( this.unknownses.length === 1 ) {\n // TODO(kzentner): Remove this hack.\n parent_unknowns = this.root_module.imports;\n }\n else {\n parent_unknowns = this.unknownses[this.unknownses.length - 2];\n }\n var self = this;\n unknowns.each_text ( function ( key, vals ) {\n if ( self.current_scope.text_distance ( key ) === 0 ) {\n // Variable was declared in this scope.\n vals.forEach ( function ( val ) {\n val.callback ( self.current_scope.get_text ( key ) );\n } );\n }\n else {\n // Variable was not declared in this scope, bubble it up.\n var parent_list = parent_unknowns.get_text ( key );\n if ( parent_list === undefined ) {\n parent_unknowns.set_text ( key, vals );\n }\n else {\n parent_unknowns.set_text ( key, parent_list.concat ( vals ) );\n }\n }\n } );\n },\n pop_scope : function ( ) {\n this.finalize_scope ( );\n this.unknownses.pop ( );\n this.current_scope = this.current_scope.above ( );\n this.scope_depth -= 1;\n },\n //\n // Walk the AST.\n //\n recurse : function ( node ) {\n if ( node.analyze !== undefined ) {\n // If we can analyze this node, do so.\n return node.analyze ( this );\n }\n else if ( node.recurse !== undefined ) {\n var self = this;\n return node.recurse ( function ( child ) {\n self.recurse ( child );\n } );\n }\n else {\n throw 'Could not analyze ' + JSON.stringify ( node, null, ' ' );\n }\n },\n init : function ( root_module ) {\n this.unknownses = [ scope.make ( ) ];\n this.scope_depth = 0;\n this.current_scope = root_module.globals;\n this.objects = [ root_module.objects ];\n this.variables = [];\n this.root_module = root_module;\n },\n analyze : function ( tree, modules ) {\n var root_module = modul.make ( '' );\n var core_module;\n // TODO(kzentner): Fix this hackery.\n if ( modules !== undefined ) {\n core_module = modules.get ( 'core' );\n }\n if ( core_module === undefined ) {\n core_module = make_core_module ( );\n }\n root_module.ast = tree;\n this.init ( root_module );\n this.recurse ( tree );\n // TODO(kzentner): Add support for modules besides the core module.\n root_module.imports.each_text ( function ( key, imprts ) {\n var res = core_module.exports.get_text ( key );\n if ( res !== undefined ) {\n imprts.forEach ( function ( imprt ) {\n imprt.callback ( res );\n } );\n }\n } );\n this.map = generate_canonical_map ( root_module );\n generate_enumerations ( this.map );\n this.all_objects = extract_all_objs ( root_module );\n },\n setupScopes : setupScopes,\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create transformation matrix for a shape | function create_matrix(index, global_mode,global_rotation,shapes_tx,shapes_ty,shapes_rotation,shapes_scale){
var mvMatrix = mat4.create(); // this is the matrix for transforming each shape before draw
//set into an identity matrix (after create you don't know if there's junk in it)
// set identity - fresh matrix
mat4.identity(mvMatrix);
if(global_mode[index]){
for(var j = 0; j < global_rotation[index].length; j++){
mat4.rotate(mvMatrix,degToRad(global_rotation[index][j]),[0,0,1]);
}
var scale = [1,1,1];
scale[0] = scale[1] = scale[2] = global_scale;
// finish consruct matrix here but haven't set it
mvMatrix = mat4.scale(mvMatrix, scale);
}
var trans = [0,0,0];
trans[0] = shapes_tx[index];
trans[1] = shapes_ty[index];
trans[2] = 0.0;
//translate is multiplied to the right side of the mvMatrix
mvMatrix = mat4.translate(mvMatrix, trans); // move from origin to mouse click
//2d x-y in 3d x-z rotate around z
// only accept radian, not degree. so we use degToRad
mvMatrix = mat4.rotate(mvMatrix, degToRad(shapes_rotation[index]), [0, 0, 1]); // rotate if any
var scale = [1,1,1];
scale[0] = scale[1] = scale[2] = shapes_scale[index];
// finish consruct matrix here but haven't set it
mvMatrix = mat4.scale(mvMatrix, scale); // scale if any
//var mvMatrix1 = mat4.inverse(mvMatrix);
//mvMatrix = mat4.multiply(mvMatrix1,mvMatrix);
return mvMatrix;
} | [
"function transformMatrix_(s, t) {\n return [t[0] * s[0] + t[1] * s[2],\n t[0] * s[1] + t[1] * s[3],\n s[0] * t[2] + s[2] * t[3],\n s[1] * t[2] + t[3] * s[3],\n s[0] * t[4] + s[4] + s[2] * t[5],\n s[1] * t[4] + s[3] * t[5] + s[5]];\n}",
"transform(transformation) {\n const transposedMatrix = preallocatedVariables_1.MathTmp.Matrix[0];\n Matrix_1.Matrix.TransposeToRef(transformation, transposedMatrix);\n const m = transposedMatrix.m;\n const x = this.normal.x;\n const y = this.normal.y;\n const z = this.normal.z;\n const d = this.d;\n const normalX = x * m[0] + y * m[1] + z * m[2] + d * m[3];\n const normalY = x * m[4] + y * m[5] + z * m[6] + d * m[7];\n const normalZ = x * m[8] + y * m[9] + z * m[10] + d * m[11];\n const finalD = x * m[12] + y * m[13] + z * m[14] + d * m[15];\n return new Plane(normalX, normalY, normalZ, finalD);\n }",
"function scaleMatrix(sx,sy,sz) { // identidade\n return [\n [sx, 0, 0, 0],\n [0, sy, 0, 0],\n [0, 0, sz, 0],\n [0, 0, 0, 1]\n ]; //retorna matriz 4x4\n}",
"createTransformedPolygon() {\r\n this.transformedPolygon = [];\r\n\r\n for(let i=0; i<this.polygon.length; i++) {\r\n this.transformedPolygon.push(\r\n [\r\n this.polygon[i][0] * this.scale + this.origin.x,\r\n this.polygon[i][1] * this.scale + this.origin.y\r\n ]\r\n );\r\n }\r\n }",
"function myTranspose (mtx) {\n\nlet grid = [];\n for (let i = 0; i < mtx[0].length; i++) {\n grid[i] = [];\n for (let j = 0; j < mtx.length; j++) {\n grid[i][j] = mtx[j][i];\n }\n }\n return grid;\n}",
"function toTransformation(a, b, c, d) {\r\n return new Transformation(a, b, c, d);\r\n}",
"transform (m) {\r\n const points = [];\r\n\r\n for (let i = 0; i < this.length; i++) {\r\n const point = this[i];\r\n // Perform the matrix multiplication\r\n points.push([\r\n m.a * point[0] + m.c * point[1] + m.e,\r\n m.b * point[0] + m.d * point[1] + m.f\r\n ]);\r\n }\r\n\r\n // Return the required point\r\n return new PointArray(points)\r\n }",
"function Transform() {\n _classCallCheck(this, Transform);\n\n this.matrix = Matrix.identity(3);\n this._centerPoint = new Point(0, 0);\n }",
"static identity(){\n return new matrix4([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]);\n }",
"function rotateShape() {\n removeShape();\n currentShape.shape = rotate(currentShape.shape, 1);\n if (collides(grid, currentShape)) {\n currentShape.shape = rotate(currentShape.shape, 3);\n }\n applyShape();\n }",
"function copy(shape) {\n return shape.map(p => new Vec2(p.x, p.y));\n}",
"function transformation(objects, matrix, scaleRadius=false) {\r\n objects.forEach(item => {\r\n switch(item.type) {\r\n case \"line\":\r\n transform(item, \"p1x\", \"p1y\", matrix);\r\n transform(item, \"p2x\", \"p2y\", matrix);\r\n break;\r\n case \"circle\":\r\n transform(item, \"centerx\", \"centery\", matrix);\r\n if(scaleRadius)\r\n item.radius = item.radius*matrix[0][0];\r\n break;\r\n case \"curve\":\r\n transform(item, \"p1x\", \"p1y\", matrix);\r\n transform(item, \"p2x\", \"p2y\", matrix);\r\n transform(item, \"p3x\", \"p3y\", matrix);\r\n transform(item, \"p4x\", \"p4y\", matrix);\r\n break;\r\n }\r\n })\r\n}",
"identity() { \n this.internal.gridTransformationList = [];\n this.internal.linearTransformation.identity();\n }",
"transform ( translationVector, theta, axis, scalingVector ) {\n \n modelViewMatrix = mat4.create();\n mat4.lookAt( modelViewMatrix, eye, at, up );\n\n var ctm = mat4.create();\n var q = quat.create();\n \n if ( axis === \"X\" ) {\n mat4.fromRotationTranslationScale( ctm, quat.rotateX( q, q, theta ), translationVector, scalingVector );\n } else if ( axis === \"Y\" ) {\n mat4.fromRotationTranslationScale( ctm, quat.rotateY( q, q, theta ), translationVector, scalingVector );\n } else if ( axis === \"Z\" ) {\n mat4.fromRotationTranslationScale( ctm, quat.rotateZ( q, q, theta ), translationVector, scalingVector );\n } else {\n throw Error( \"Axis isn't specified correctly.\" );\n }\n \n // calculates and sends the modelViewMatrix\n mat4.mul( modelViewMatrix, modelViewMatrix, ctm );\n this.gl.uniformMatrix4fv( modelViewLoc, false, modelViewMatrix );\n\n // calculates and sends the normalMatrix using modelViewMatrix\n normalMatrix = mat3.create();\n mat3.normalFromMat4( normalMatrix, modelViewMatrix );\n this.gl.uniformMatrix3fv( normalMatrixLoc, false, normalMatrix );\n\n }",
"removeRotationAndScaling() {\n const m = this.m;\n Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, m[12], m[13], m[14], m[15], this);\n this._updateIdentityStatus(m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1);\n return this;\n }",
"getRotationMatrixToRef(result) {\n const scale = preallocatedVariables_1$3.MathTmp.Vector3[0];\n if (!this.decompose(scale)) {\n Matrix.IdentityToRef(result);\n return this;\n }\n const m = this._m;\n // tslint:disable-next-line:one-variable-per-declaration\n const sx = 1 / scale.x, sy = 1 / scale.y, sz = 1 / scale.z;\n Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, result);\n return this;\n }",
"mapTriangle(ctx,p0, p1, p2, p_0, p_1, p_2) {\n\n // break out the individual triangles x's & y's\n var x0=p_0.x, y0=p_0.y;\n var x1=p_1.x, y1=p_1.y;\n var x2=p_2.x, y2=p_2.y;\n var u0=p0.x, v0=p0.y;\n var u1=p1.x, v1=p1.y;\n var u2=p2.x, v2=p2.y;\n\n // save the unclipped & untransformed destination canvas\n ctx.save();\n\n // clip the destination canvas to the unwarped destination triangle\n ctx.beginPath();\n ctx.moveTo(x0, y0);\n ctx.lineTo(x1, y1);\n ctx.lineTo(x2, y2);\n ctx.closePath();\n ctx.clip();\n\n // Compute matrix transform\n var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2;\n var delta_a = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2;\n var delta_b = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2;\n var delta_c = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2;\n var delta_d = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2;\n var delta_e = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2;\n var delta_f = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2;\n\n // Draw the transformed image\n ctx.transform(\n delta_a / delta, delta_d / delta,\n delta_b / delta, delta_e / delta,\n delta_c / delta, delta_f / delta\n );\n \n // draw the transformed source image to the destination canvas\n ctx.drawImage(this.state.img, 0 , 0);\n\n // restore the context to it's unclipped untransformed state\n ctx.restore();\n }",
"transformGroup() {\n return this.canvas.append(\"g\")\n .attr(\"transform\", \"translate(\" + this.width / 2 + \",\" + this.height / 2 + \")\");\n }",
"function vec4Transpose(v4) {\r\n return [[v4[0]], [v4[1]], [v4[2]], [v4[3]]]\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enable and hide all disabled fields in a form before submit | function enableFieldsForSubmit(theform) {
var elems = theform.elements;
for (var i = 0; i < elems.length; i++) {
if (elems[i].disabled) {
elems[i].style.visibility = "hidden";
elems[i].disabled = false;
}
}
} | [
"disableSubmitInputs() {\n this.jqueryForm.find('[type=submit]').each(function () {\n $(this).prop('disabled', true);\n });\n }",
"function disableAgencySubmit(disable) {\n $('#agencySubmit').attr('disabled', disable);\n}",
"function disableAttendeeSubmit(disable) {\n $('#attendeeSubmit').attr('disabled', disable);\n}",
"function disableAttendeeHourSubmit(disable) {\n $('#attendeeHourSubmit').attr('disabled', disable);\n}",
"function Enable_Place_Forms(){\n $(\".place\").removeAttr('disabled');\n}",
"function disableEditing() {\n disableForm(true);\n}",
"function enableNumFields() {\n\tvar numFields = parseInt(document.getElementById('betType').value);\n\tvar bet1 = document.getElementById('bet1');\n\tvar bet2 = document.getElementById('bet2');\n\tvar bet3 = document.getElementById('bet3');\n\tvar bet4 = document.getElementById('bet4');\n\tvar bet5 = document.getElementById('bet5');\n\tvar bet6 = document.getElementById('bet6');\n\tvar bet7 = document.getElementById('bet7');\n\tvar bet8 = document.getElementById('bet8');\n\t\n\t//Enable all fields initially\n\tbet1.disabled = false;\n\tbet2.disabled = false;\n\tbet3.disabled = false;\n\tbet4.disabled = false;\n\tbet5.disabled = false;\n\tbet6.disabled = false;\n\tbet7.disabled = false;\n\tbet8.disabled = false;\n\t\t\n\tif(numFields == -1){\n\t\tbet1.setAttribute(\"disabled\", \"\");\n\t\tbet2.setAttribute(\"disabled\", \"\");\n\t\tbet3.setAttribute(\"disabled\", \"\");\n\t\tbet4.setAttribute(\"disabled\", \"\");\n\t\tbet5.setAttribute(\"disabled\", \"\");\n\t\tbet6.setAttribute(\"disabled\", \"\");\n\t\tbet7.setAttribute(\"disabled\", \"\");\n\t\tbet8.setAttribute(\"disabled\", \"\");\n\t}else if(numFields !== 8){\n\t\tbet8.setAttribute(\"disabled\", \"\");\n\t\tif(numFields < 7){\n\t\t\tbet7.setAttribute(\"disabled\", \"\");\n\t\t\tif(numFields < 6){\n\t\t\t\tbet6.setAttribute(\"disabled\", \"\");\n\t\t\t\tif(numFields < 5){\n\t\t\t\t\tbet5.setAttribute(\"disabled\", \"\");\n\t\t\t\t\tif(numFields < 4){\n\t\t\t\t\t\tbet4.setAttribute(\"disabled\", \"\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"function tryToEnableSearch(){\n\tif (yearOk && nameOk){\n\t\t$(\"#submit\").removeAttr(\"disabled\", \"disabled\");\n\t} \n}",
"function hiddenInputValidationToggle(id) {\n var element = jQuery(\"#\" + id);\n if (element.length) {\n if (element.css(\"display\") === \"none\") {\n jQuery(\":input:hidden\", element).each(function () {\n storeOriginalDisabledProperty(jQuery(this));\n jQuery(this).addClass(\"ignoreValid\");\n //disable hidden inputs to prevent from being submitted\n jQuery(this).prop(\"disabled\", true);\n });\n }\n else {\n jQuery(\":input:visible\", element).each(function () {\n storeOriginalDisabledProperty(jQuery(this));\n jQuery(this).removeClass(\"ignoreValid\");\n //return to original disabled property value\n jQuery(this).prop(\"disabled\", jQuery(this).data('original-disabled'));\n });\n }\n }\n}",
"function hideInputs() {\n var selectedDistribution = jQuery(\"#distribution\").val();\n for (inputName in fEnableObj) {\n var inputField = jQuery(`input[name='${inputName}']`);\n if (fEnableObj[inputName] === selectedDistribution)\n inputField.parent(\"label\").removeClass(\"hidden\");\n else\n inputField.parent(\"label\").addClass(\"hidden\");\n }\n if (selectedDistribution === \"parcel\") {\n jQuery(\"#geometry-box\").prop(\"checked\", true);\n jQuery(\"select#geometry\").attr(\"disabled\", true);\n jQuery(\".inputfield.maxsize\").addClass(\"hidden\");\n } else {\n jQuery(\"select#geometry\").attr(\"disabled\", false)\n if (jQuery(\"#geometry\").val() == \"box\") {\n jQuery(\".inputfield.maxsize\").removeClass(\"hidden\");\n } else {\n jQuery(\".inputfield.maxsize\").addClass(\"hidden\");\n }\n }\n}",
"function enableDisableRegisterBtn(frmElementDivId, submitBtnId){\n\tvar buttonStatusEnabled = true;\n\tvar $inputFields = $('#' + frmElementDivId + ' :input');\n\t$inputFields.each(function() {\n\t\tvar inputType = $(this).attr('type');\n\t\tvar inputId= $(this).attr('id');\n\t\tif(inputId != 'promoCodeDiscount1'){\n\t\t\tif(inputType && inputType != 'checkbox') {\n\t\t\t\tif($(this).hasClass('error_red_border') || !$(this).val()) {\n\t\t\t\t\tbuttonStatusEnabled = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n\tif(buttonStatusEnabled) {\n\t\tsubmitBtnEnableUI(submitBtnId);\n\t} else {\n\t\tsubmitBtnDisableUI(submitBtnId);\n\t}\n}",
"function activateForm() {\n form.classList.remove('ad-form--disabled');\n switchingFormFieldsetState(false);\n }",
"function refreshPasscodeQueryEditability() {\n $(\".passcode-query-edit\").prop(\"disabled\", passcodeQueryIndex >= 0);\n }",
"function checkAttendeeForm() {\n var canSubmit = true;\n\n // Check first name\n if ($('#firstName').val() === '')\n canSubmit = false;\n\n // Check last name\n if ($('#lastName').val() === '')\n canSubmit = false;\n\n // Check agency id\n if ($('#attendeeAgencyId').val() === '')\n canSubmit = false;\n\n // Enable/disable submit button\n disableAttendeeSubmit(!canSubmit);\n}",
"function disableFormInputs(msg, time) {\n\t\tpinAllowed = false;\n\t\t$('#submitPin').prop('disabled', true);\n\t\t$('#oldPin').prop('disabled', true);\n\t\t$('#pinWarning').html(msg);\n\t\t$('#pinError').hide();\n\t\tlocalStorage.setItem('restrictTimer', time);\n\t\tlocalStorage.setItem('pinAllowed', false);\n\t\trestrictTimer = time;\n\t}",
"function nextDisable() {\r\n\t$('#btnNextStep').attr('disabled', 'disabled');\r\n}",
"function disableeditfields(moduleid)\n{\n Element.addClassName('editmodulenavtype_' + moduleid, 'z-hide');\n Element.addClassName('editmoduleenablelang_' + moduleid, 'z-hide');\n Element.addClassName('editmoduleaction_' + moduleid, 'z-hide');\n Element.addClassName('editmoduleexempt_' + moduleid, 'z-hide');\n Element.removeClassName('modulenavtype_' + moduleid, 'z-hide');\n Element.removeClassName('moduleenablelang_' + moduleid, 'z-hide');\n Element.removeClassName('moduleaction_' + moduleid, 'z-hide');\n Element.removeClassName('moduleexempt_' + moduleid, 'z-hide');\n if(allownameedit[moduleid] == true) {\n Element.addClassName('editmodulename_' + moduleid, 'z-hide');\n Element.removeClassName('modulename_' + moduleid, 'z-hide');\n }\n}",
"function DisallowFieldsPageNext(button_state){\n document.getElementById('fields_next_page').disabled = button_state;\n}",
"onDisabled() {\n this.updateInvalid();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue". | static LerpToRef(startValue, endValue, gradient, result) {
for (let index = 0; index < 16; index++) {
result._m[index] =
startValue._m[index] * (1.0 - gradient) + endValue._m[index] * gradient;
}
result._markAsUpdated();
} | [
"static Lerp(startValue, endValue, gradient) {\n const result = new Matrix();\n Matrix.LerpToRef(startValue, endValue, gradient, result);\n return result;\n }",
"static DecomposeLerp(startValue, endValue, gradient) {\n const result = new Matrix();\n Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);\n return result;\n }",
"function calculateGradient(x1, y1, y, m) {\n x = ((-y + y1) / m) + x1\n return x\n }",
"function setGradient() {\n\tbody.style.background =\n\t\"linear-gradient(to right, \" + color1.value + \", \" + color2.value + \")\";\n\tcss.textContent = \"background : linear-gradient(to right, \" + color1.value + \", \" + color2.value + \")\";\n}",
"function animateGradient() {\n updateGradient();\n requestAnimationFrame(animateGradient);\n}",
"function initializeGradientColors() {\n gradient.append(\"stop\")\n .attr(\"id\", \"gstart\")\n .attr(\"offset\", \"0%\")\n .attr(\"stop-color\", \"#ffffff\");\n gradient.append(\"stop\")\n .attr(\"id\", \"gstop\")\n .attr(\"offset\", \"100%\")\n .attr(\"stop-color\", \"#ffffff\");\n}",
"function generateRedGradient(){\n var gradient = svg.append(\"svg:defs\")\n .append(\"svg:linearGradient\")\n .attr(\"id\", \"redgradient\")\n .attr(\"x1\", \"200%\")\n .attr(\"y1\", \"0%\")\n .attr(\"x2\", \"0%\")\n .attr(\"y2\", \"0%\")\n .attr(\"spreadMethod\", \"pad\");\n\n gradient.append(\"svg:stop\")\n .attr(\"offset\", \"50%\")\n .attr(\"stop-color\", \"white\")\n .attr(\"stop-opacity\", 1);\n\n gradient.append(\"svg:stop\")\n .attr(\"offset\", \"50%\")\n .attr(\"stop-color\", \"red\")\n .attr(\"stop-opacity\", 1);\n }",
"function drawGradient() {\n noFill();\n const startPos = rightOffset + maxWidth * (cuttingPoint + 0.02);\n const endPos = displayWidth;\n function easeOutExpo(x) {\n return x === 1 ? 1 : 1 - pow(2, -2 * x);\n }\n for (let x = startPos; x <= endPos; x++) {\n let inter = map(x, startPos, endPos, 0, 1);\n stroke(60, 70 * easeOutExpo(inter));\n line(x, 0, x, pageHeight);\n }\n}",
"static LerpToRef(start, end, amount, result) {\n result.x = start.x + (end.x - start.x) * amount;\n result.y = start.y + (end.y - start.y) * amount;\n result.z = start.z + (end.z - start.z) * amount;\n }",
"function color_interp(value, max, min, color_max, color_min, incl_a) {\n incl_a = typeof incl_a !== 'undefined' ? incl_a : false;\n color_max = typeof color_max !== 'undefined' ? color_max : { a: 255, r: 255, g: 0, b: 0 };\n color_min = typeof color_min !== 'undefined' ? color_min : { a: 255, r: 0, g: 0, b: 255 };\n max = typeof max !== 'undefined' ? max : 100;\n min = typeof min !== 'undefined' ? min : 0;\n\n if (value >= max) {\n return color_max;\n }\n\n if (value <= min) {\n return color_min;\n }\n\n a_new = incl_a ? Math.round(linear_interpolate(value, min, max, Math.min(color_min.a, color_max.a), Math.max(color_min.a, color_max.a))) : 255;\n r_new = Math.round(linear_interpolate(value, min, max, Math.min(color_min.r, color_max.r), Math.max(color_min.r, color_max.r)));\n g_new = Math.round(linear_interpolate(value, min, max, Math.min(color_min.g, color_max.g), Math.max(color_min.g, color_max.g)));\n b_new = Math.round(linear_interpolate(value, min, max, Math.min(color_min.b, color_max.b), Math.max(color_min.b, color_max.b)));\n\n return { a: a_new, r: r_new, g: g_new, b: b_new };\n}",
"static Lerp(start, end, amount) {\n const result = new Color3(0.0, 0.0, 0.0);\n Color3.LerpToRef(start, end, amount, result);\n return result;\n }",
"set(x, y, value) {\n const index = this.linear(x, y);\n\n return new Matrix2D(this.xSize, this.ySize, [\n ...this.data.slice(0, index),\n value,\n ...this.data.slice(index + 1)\n ])\n }",
"setInterpolatedDistance(valA, valB, t) {\n this.cam.state.distance = Scalar.mix(valA, valB, Scalar.smoothstep(t));\n }",
"function colorChanged(){\n\tsetGradientColor(lastDirection , rgbString(color1.value) , rgbString(color2.value) , true);\n}",
"function GradientStop(offset, rgbColor)\n{\n\tthis.offset = offset;\n\tthis.rgbColor = rgbColor;\n}",
"function setColorByRange(startIndex, endIndex) {\n\t\t\n\t\tvar jsmolCommand = ''; //holds string command to send to jsmol\n\t\tresetJsmolColors();\n\t\t\n\t\tfor(var i = startIndex-1; i<=endIndex-1; i++){\n\t\t\tvar residueSpan = res[i];\n\t\t\t//I'm getting the color from the first atom from the residue, I think that's enough\n\t\t\t//Jmol.evaluateVar( myJmol, \"{\"+res[i]+\" and *.CA}.color \" );//get carbon alpha http://chemapps.stolaf.edu/jmol/docs/misc/atomInfo.txt\n\t\t\tvar resColor = Jmol.evaluateVar( myJmolOb, \"{\"+residueSpan+\"}[0].color \" );\t\t\n\t\t\t\n\t\t\tjsmolCommand += 'select '+ residueSpan +' ; color \"#CCE77B\";';\n\t\t\t\n\t\t}\n\t\tconsole.log(\"command to send to jsmol: \"+ jsmolCommand);\n\t\tJmol.script(myJmolOb, jsmolCommand);\n\t}",
"function setRadialGradient(){\r\n\t\r\n\tbody.style.background = \r\n\t\t\t\t\"radial-gradient(\"\r\n\t\t\t\t+ color1.value \r\n\t\t\t\t+\", \" \r\n\t\t\t\t+ color2.value + \")\";\r\n\r\n\t\tcss.textContent = body.style.background + \";\";\r\n}",
"interpolateTextureBaseColors(val1, val2, alpha = 0.5)\n {\n //TODO\n }",
"function linear_interpolate(x, x0, x1, y0, y1){\n return y0 + ((y1 - y0)*((x-x0) / (x1-x0)));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simple tree methods Adds the vampire as an offspring of this vampire | addOffspring(vampire) {
this.offspring.push(vampire);
vampire.creator = this;
} | [
"addOffspring(vampire) {\n // should add parent as creator\n vampire.creator = this;\n this.offspring.push(vampire);\n }",
"vampireWithName(name) {\n\n if (this.name === name) {\n return this;\n }\n for (let child of this.offspring) {\n let vampire = child.vampireWithName(name);\n if (vampire) {\n return vampire;\n }\n }\n return null;\n }",
"function SplayTree() { }",
"append(node) {\n\n // Checks if argument is a node:\n if (node instanceof YngwieNode) {\n\n // If given node has parent, detach that node from it's parent:\n if (node._parent) {\n node.detach();\n }\n\n // Set new node as last sibling:\n if (this._first !== undefined) {\n node._prev = this._last; // Sets new last child's previous node to old last node\n this._last._next = node; // Set old last child next element to new last child\n this._last = node; // Set new last child to given node\n } else {\n // If ther are no children, then this node is an only child:\n this._first = node;\n this._last = node;\n }\n\n // Set parent\n node._parent = this;\n\n // Return instance:cosnole\n return this;\n\n }\n\n throw new _Error_main_js__WEBPACK_IMPORTED_MODULE_0__.default(\"Can only apppend YngwieNode to other YngwieNodes\", node);\n\n }",
"replaceWith (node) {\n node.path = this.path\n node.name = this.name\n if (!node.isLink)\n node.realpath = this.path\n node.root = this.isRoot ? node : this.root\n // pretend to be in the tree, so top/etc refs are not changing for kids.\n node.parent = null\n node[_parent] = this[_parent]\n this.children.forEach(c => c.parent = node)\n this.fsChildren.forEach(c=> c.fsParent = node)\n // now remove the hidden reference, and call parent setter to finalize.\n node[_parent] = null\n node.parent = this.parent\n }",
"get allMillennialVampires() {\n let vampires = [];\n if (this.yearConverted > 1980) {\n vampires.push(this);\n }\n for (let child of this.offspring) {\n vampires = vampires.concat(child.allMillennialVampires);\n }\n return vampires;\n }",
"_renderVitamins () {\n this._emptyContainer();\n this.vitamins.forEach(vit => this._container.appendChild(vit.element));\n console.log(Texts.RENDERING_VITAMINS);\n }",
"addViking(viking) {\n this.vikingArmy.push(viking);\n }",
"visitAlter_method_element(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"addLeft(data){\n\t\tlet copyRoot = this.root;\n\t\twhile (this.root.left){\n\t\t\tthis.root = this.root.left;\n\t\t}\n\n\t\tthis.root.left = new TreeNode(data, this.root);\n\t\tthis.root = copyRoot;\n\t}",
"function testAddPion(){\n var tDamier =remplirDamier(8, \"P\");\n var tPion = positionPion(8);\n tDamier = addPion(tPion, tDamier);\n afficheDamier(tDamier);\n}",
"recycle() {\n\t\tQuadTree.pool.push(this)\n\t\tthis.idx = 0 // array stays allocated, but points inside it are ignored\n\t\tif (this.nw) this._recycle()\n\t}",
"tree(tree) {\n if (tree) {\n this._tree = tree;\n }\n return this._tree;\n }",
"function Scene_DvLyonPromo() {\n this.initialize.apply(this, arguments);\n }",
"build() {\n\t\tconst self = this;\n\n\t\tself.buildTags();\n\t\tself.buildTree();\n\t}",
"constructChildren() {\n\t\t\n\t\t// this.children.push();\n\t}",
"function updateBuildingPath() {\n\n // clean DOM\n var $breadCrumb = $(\".breadcrumb\").empty();\n\n for (var i = 0; i < navbar.length - 1; i++) {\n $breadCrumb.append(\"<li><a class=\\\"nave\\\" name=\\\"\" + navbar[i] + \"\\\" style=\\\"cursor : pointer;\\\">\" + navbar[i] + \"</a></li>\");\n }\n}",
"function AABBTree() {}",
"function doNavboxen() {\n\t\t\t// Move vertical-navbox into the right rail.\n\t\t\tvar $nbClone = $('.vertical-navbox').clone(true, true);\n\t\t\tif ($nbClone.length) {\n\t\t\t\t// Remove the old one.\n\t\t\t\t$('.vertical-navbox').remove();\n\t\t\t\t$('#wsidebar').append($nbClone);\n\t\t\t}\n\t\t}",
"get allMillennialVampires() {\n let convertedVamp = [];\n\n if (this.yearConverted > 1980) {\n convertedVamp.push(this);\n }\n\n for (const child of this.offspring) {\n const converted = child.allMillennialVampires;\n convertedVamp = convertedVamp.concat(converted);\n }\n\n return convertedVamp;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
IMGUI_API bool InputInt(const char label, int v, int step = 1, int step_fast = 100, ImGuiInputTextFlags extra_flags = 0); | function InputInt(label, v, step = 1, step_fast = 100, extra_flags = 0) {
const _v = import_Scalar(v);
const ret = bind.InputInt(label, _v, step, step_fast, extra_flags);
export_Scalar(_v, v);
return ret;
} | [
"function InputInt2(label, v, extra_flags = 0) {\r\n const _v = import_Vector2(v);\r\n const ret = bind.InputInt2(label, _v, extra_flags);\r\n export_Vector2(_v, v);\r\n return ret;\r\n }",
"function InputInt3(label, v, extra_flags = 0) {\r\n const _v = import_Vector3(v);\r\n const ret = bind.InputInt3(label, _v, extra_flags);\r\n export_Vector3(_v, v);\r\n return ret;\r\n }",
"function InputScalar(label, v, step = null, step_fast = null, format = null, extra_flags = 0) {\r\n if (v instanceof Int8Array) {\r\n return bind.InputScalar(label, ImGuiDataType.S8, v, step, step_fast, format, extra_flags);\r\n }\r\n if (v instanceof Uint8Array) {\r\n return bind.InputScalar(label, ImGuiDataType.U8, v, step, step_fast, format, extra_flags);\r\n }\r\n if (v instanceof Int16Array) {\r\n return bind.InputScalar(label, ImGuiDataType.S16, v, step, step_fast, format, extra_flags);\r\n }\r\n if (v instanceof Uint16Array) {\r\n return bind.InputScalar(label, ImGuiDataType.U16, v, step, step_fast, format, extra_flags);\r\n }\r\n if (v instanceof Int32Array) {\r\n return bind.InputScalar(label, ImGuiDataType.S32, v, step, step_fast, format, extra_flags);\r\n }\r\n if (v instanceof Uint32Array) {\r\n return bind.InputScalar(label, ImGuiDataType.U32, v, step, step_fast, format, extra_flags);\r\n }\r\n // if (v instanceof Int64Array) { return bind.InputScalar(label, ImGuiDataType.S64, v, step, step_fast, format, extra_flags); }\r\n // if (v instanceof Uint64Array) { return bind.InputScalar(label, ImGuiDataType.U64, v, step, step_fast, format, extra_flags); }\r\n if (v instanceof Float32Array) {\r\n return bind.InputScalar(label, ImGuiDataType.Float, v, step, step_fast, format, extra_flags);\r\n }\r\n if (v instanceof Float64Array) {\r\n return bind.InputScalar(label, ImGuiDataType.Double, v, step, step_fast, format, extra_flags);\r\n }\r\n throw new Error();\r\n }",
"function DragInt(label, v, v_speed = 1.0, v_min = 0, v_max = 0, format = \"%d\") {\r\n const _v = import_Scalar(v);\r\n const ret = bind.DragInt(label, _v, v_speed, v_min, v_max, format);\r\n export_Scalar(_v, v);\r\n return ret;\r\n }",
"function VSliderInt(label, size, v, v_min, v_max, format = \"%d\") {\r\n const _v = import_Scalar(v);\r\n const ret = bind.VSliderInt(label, size, _v, v_min, v_max, format);\r\n export_Scalar(_v, v);\r\n return ret;\r\n }",
"function InputInt4(label, v, extra_flags = 0) {\r\n const _v = import_Vector4(v);\r\n const ret = bind.InputInt4(label, _v, extra_flags);\r\n export_Vector4(_v, v);\r\n return ret;\r\n }",
"function InputFloat(label, v, step = 0.0, step_fast = 0.0, format = \"%.3f\", extra_flags = 0) {\r\n const _v = import_Scalar(v);\r\n const ret = bind.InputFloat(label, _v, step, step_fast, format, extra_flags);\r\n export_Scalar(_v, v);\r\n return ret;\r\n }",
"function makeIntegerWidget(id, name, def, value)\n{\n var jq = $(\"<input type='text' class='widget integer-widget' name='\"+name+\" id='\"+id+\"'/>\");\n new IntegerWidget(jq,def);\n if (typeof value != 'undefined')\n jq.val(value);\n return jq;\n}",
"function SliderInt2(label, v, v_min, v_max, format = \"%d\") {\r\n const _v = import_Vector2(v);\r\n const ret = bind.SliderInt2(label, _v, v_min, v_max, format);\r\n export_Vector2(_v, v);\r\n return ret;\r\n }",
"function inputValue() {\n //*1 Get clicked numpad value\n const value = getNumpadValue();\n\n //*2 if a digit has been clicked\n if (value !== 0 && !isNaN(value)) {\n setCellValue(value);\n } else if (value === \"clear\") {\n setCellValue(\"\");\n } else return;\n resetNumpad();\n}",
"function SliderInt3(label, v, v_min, v_max, format = \"%d\") {\r\n const _v = import_Vector3(v);\r\n const ret = bind.SliderInt3(label, _v, v_min, v_max, format);\r\n export_Vector3(_v, v);\r\n return ret;\r\n }",
"Draw(label = \"Filter (inc,-exc)\", width = 0.0) {\r\n if (width !== 0.0)\r\n bind.PushItemWidth(width);\r\n const value_changed = InputText(label, this.InputBuf, IM_ARRAYSIZE(this.InputBuf));\r\n if (width !== 0.0)\r\n bind.PopItemWidth();\r\n if (value_changed)\r\n this.Build();\r\n return value_changed;\r\n }",
"function InputDouble(label, v, step = 0.0, step_fast = 0.0, format = \"%.6f\", extra_flags = 0) {\r\n const _v = import_Scalar(v);\r\n const ret = bind.InputDouble(label, _v, step, step_fast, format, extra_flags);\r\n export_Scalar(_v, v);\r\n return ret;\r\n }",
"function DragInt3(label, v, v_speed = 1.0, v_min = 0, v_max = 0, format = \"%d\") {\r\n const _v = import_Vector3(v);\r\n const ret = bind.DragInt3(label, _v, v_speed, v_min, v_max, format);\r\n export_Vector3(_v, v);\r\n return ret;\r\n }",
"function input(event_type) {\r\n\tinput_keyboard_options_with_one_state(0, event_type, \"lowercase_alphabet\"); //virtual_keyboard option 0; alphabet\r\n\tinput_keyboard_options_with_two_states(1, event_type, \"lowercase_accent_characters_one\", 8, 9); //virtual_keyboard option 1; accent characters one\r\n\tinput_keyboard_options_with_two_states(2, event_type, \"lowercase_accent_characters_two\", 10, 11); //virtual_keyboard option 2; accent characters two\r\n\tinput_keyboard_options_with_one_state(3, event_type, \"lowercase_accent_characters_three\"); //virtual_keyboard option 3; accent characters three\r\n\tinput_keyboard_options_with_one_state(4, event_type, \"lowercase_accent_characters_four\"); //virtual_keyboard option 4; accent characters four\r\n\tinput_keyboard_options_with_two_states(5, event_type, \"punctuation_numbers_one\", 4, 5); //virtual_keyboard option 5; punctuation and numbers\r\n\tinput_keyboard_options_with_two_states(6, event_type, \"punctuation_numbers_two\", 6, 7); //virtual_keyboard option 6; punctuation\r\n\r\n\tinput_editing_keys(7, event_type, delete_function, \"Delete\"); //delete \r\n\tinput_character_keys(8, event_type, 0, \"KeyQ\") //q (113), Q (81), 1 (49)\r\n\tinput_character_keys(9, event_type, 1, \"KeyW\"); //w (119), W (87), 2 (50)\r\n\tinput_character_keys(10, event_type, 2, \"KeyE\"); //e (101), E (69), 3 (51)\r\n\tinput_character_keys(11, event_type, 3, \"KeyR\"); //r (114), R (82), 4 (52)\r\n\tinput_character_keys(12, event_type, 4, \"KeyT\"); //t (116), T (84), 5 (53)\r\n\tinput_character_keys(13, event_type, 5, \"KeyY\"); //y (121), Y (89), 6 (54)\r\n\tinput_character_keys(14, event_type, 6, \"KeyU\"); //u (117), U (85), 7 (55)\r\n\tinput_character_keys(15, event_type, 7, \"KeyI\"); //i (105), I (73), 8 (56)\r\n\tinput_character_keys(16, event_type, 8, \"KeyO\"); //o (111), O (79), 9 (57)\r\n\tinput_character_keys(17, event_type, 9, \"KeyP\"); //p (112), P (80), 0 (48)\r\n\tinput_editing_keys(18, event_type, backspace_function, \"Backspace\") //backspace\r\n\t\r\n\tinput_whitespace_keys(19, event_type, 9, \"Tab\"); //horizonal tab (9)\r\n\tinput_character_keys(20, event_type, 10, \"KeyA\"); //a (97), A (65), @ (64)\r\n\tinput_character_keys(21, event_type, 11, \"KeyS\"); //s (115), S (83), # (35)\r\n\tinput_character_keys(22, event_type, 12, \"KeyD\"); //d (100), D (68), $ (36)\r\n\tinput_character_keys(23, event_type, 13, \"KeyF\"); //f (102), F (70), & (38)\r\n\tinput_character_keys(24, event_type, 14, \"KeyG\"); //g (103), G (71), * (42)\r\n\tinput_character_keys(25, event_type, 15, \"KeyH\"); //h (104), H (72), ( (40)\r\n\tinput_character_keys(26, event_type, 16, \"KeyJ\"); //j (106), J (74), ) (41)\r\n\tinput_character_keys(27, event_type, 17, \"KeyK\"); //k (107), K (75),' (39)\r\n\tinput_character_keys(28, event_type, 18, \"KeyL\"); //l (108), L (76), \" (34)\r\n\tinput_whitespace_keys(29, event_type, 13, \"Enter\") //enter (13)\r\n\r\n\tinput_caps_lock(30, event_type, 0, 1, 2, 3, \"CapsLock\"); //left caps lock\r\n\tinput_character_keys(31, event_type, 19, \"KeyZ\"); //z (122), Z (90), % (37)\r\n\tinput_character_keys(32, event_type, 20, \"KeyX\"); //x (120), X (88), - (45)\r\n\tinput_character_keys(33, event_type, 21, \"KeyC\"); //c (99), C (67), + (43)\r\n\tinput_character_keys(34, event_type, 22, \"KeyV\"); //v (118), V (86), = (61)\r\n\tinput_character_keys(35, event_type, 23, \"KeyB\"); //b (98), B (66), / (47)\r\n\tinput_character_keys(36, event_type, 24, \"KeyN\"); //n (110), N (78), semicolon (59)\r\n\tinput_character_keys(37, event_type, 25, \"KeyM\"); //m (109), M (77), colon (59)\r\n\tinput_character_keys(38, event_type, 26, \"Comma\"); //comma (44), exclamtion mark (33)\r\n\tinput_character_keys(39, event_type, 27, \"Period\"); //full stop (46), question mark (63)\r\n\tinput_caps_lock(40, event_type, 0, 1, 2, 3, \"CapsLock\"); //right caps lock\r\n\r\n\tinput_keyboard_options_with_two_states(41, event_type, \"punctuation_numbers_one\", 4, 5); // punctuation numbers \r\n\tinput_keyboard_options_with_two_states(42, event_type, \"punctuation_numbers_two\", 6, 7);//punctuation 2\r\n\tinput_whitespace_keys(43, event_type, 32, \"Space\"); //space (32)\r\n\tinput_keyboard_options_with_two_states(44, event_type, \"lowercase_accent_characters_one\", 8, 9); //accent chars\r\n\tinput_keyboard_options_with_two_states(45, event_type, \"lowercase_accent_characters_two\", 10, 11); //accent chars 2\t\r\n}",
"function changeBoolToInt(e){\n if(e===true){\n return 1\n } else {\n return 0\n }\n}",
"function getInputValue(id) {\n var inputValue = document.getElementById(id).value;\n return parseInt(inputValue, 10);\n}",
"function displayInput(){\r\n\tdrawNewInput();\r\n\tscrollToEnd();\r\n}",
"function InputText(label, buf, buf_size = buf instanceof ImStringBuffer ? buf.size : ImGuiInputTextDefaultSize, flags = 0, callback = null, user_data = null) {\r\n const _callback = callback && ((data) => callback(new ImGuiInputTextCallbackData(data, user_data))) || null;\r\n if (Array.isArray(buf)) {\r\n return bind.InputText(label, buf, buf_size, flags, _callback, null);\r\n }\r\n else if (buf instanceof ImStringBuffer) {\r\n const ref_buf = [buf.buffer];\r\n const _buf_size = Math.min(buf_size, buf.size);\r\n const ret = bind.InputText(label, ref_buf, _buf_size, flags, _callback, null);\r\n buf.buffer = ref_buf[0];\r\n return ret;\r\n }\r\n else {\r\n const ref_buf = [buf()];\r\n const ret = bind.InputText(label, ref_buf, buf_size, flags, _callback, null);\r\n buf(ref_buf[0]);\r\n return ret;\r\n }\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Only edit price for caretaker, pet must exist first in caretaker's table already | async function edit_caretaker_price_of_pet(req, res, next) {
var username = req.user.username;
var type = req.body.type;
var price = req.body.price;
var data;
try {
data = await pool.query(sql_query.query.caretaker_fulltime_parttime, [username]);
if (data.rows[0].is_fulltime) {
console.error("Full-timer, cannot update price");
res.redirect('/caretaker?edit-pet_price=fulltimer');
} else {
pool.query(sql_query.query.update_caretaker_pettype_price, [username, type, price]);
res.redirect('/caretaker?edit-pet_price=pass&price='+price+'&type='+type);
}
} catch (err) {
console.error("Error in updating pet type + price, ERROR: " + err);
res.redirect('/caretaker?edit-pet_price=fail');
}
} | [
"async price_update() {}",
"function addEditClick() {\r\n $(\".edit_btn\").on(\"click\", function (evt) {\r\n evt.preventDefault();\r\n id = evt.target.id;\r\n const filtered = cupcakes.filter((c) => c.id == id);\r\n const cupcake = filtered[0];\r\n $(\".cupcake_list\").html(\"\");\r\n $(\".cupcake_side\").css(\"width\", \"250px\");\r\n $(\"#add\").hide();\r\n $(\"h2\").text(\"Edit Cupcake\");\r\n $(\"#flavor_input\").val(cupcake.flavor);\r\n $(\"#size_input\").val(cupcake.size);\r\n $(\"#image_input\").val(cupcake.image);\r\n $(\"#rating_input\").val(cupcake.rating);\r\n $(\".update\").show();\r\n showCupcake(cupcake);\r\n $(\".edit_btn\").hide();\r\n \r\n });\r\n }",
"set price(value) {\n this._price = 80;\n }",
"function changeFruitPrice (fruit) {\n\tvar priceAdj = 0;\n\t//randomly chooses a value between -50 and 50\n\tpriceAdj = randomNumber(-50,50);\n\t//turns it in to cents\n\tpriceAdj /= 100;\n\tconsole.log(\"priceAdj\", priceAdj);\n\tfruit.price +=priceAdj;\n\t//prevents the fruit price from going above 9.99 and below .50\n\tif (fruit.price > 9.99) {\n\t\tfruit.price = 9.99;\n\t} else if (fruit.price < 0.50) {\n\t\tfruit.price = 0.50;\n\t}\n\tvar price = '#' + fruit.name + \"Price\";\n\t$(price).text(fruit.price.toFixed(2));\n}",
"async editAtelier({ commit }, atelier) {\n const response = await axios.put(\n `/ateliers/${atelier._id}.json` + '?auth=' + auth.state.idToken,\n atelier\n );\n\n commit('updateAtelier', response.data);\n }",
"function updatePrice() {\n for (i=0;i<fruitList.length;i++){\n object = $('.fruits').eq(i).data();\n object.marketPrice = generateRandomPrice(object.marketPrice);\n $('.fruits').eq(i).data(object);\n $('.fruits').eq(i).find('.market-price').text(object.marketPrice);\n }\n }",
"function priceChange() {\n\tfor (var i = 0; i < fruits.length; i++) {\n\t\tvar randomPrice = randomNumber(-.50, .50);\n\t\tvar currentPrice = fruits[i][1];\n\t\tvar newPrice = randomPrice + currentPrice;\n\t\tif (newPrice < .50) {\n\t\t\tnewPrice = .50;\n\t\t} else if (newPrice > 9.99) {\n\t\t\tnewPrice = 9.99;\n\t\t}\n\t\tfruits[i][1] = newPrice;\n\t}\n}",
"async function add_caretaker_type_of_pet(req, res, next) {\n\tvar username = req.user.username;\n\tvar type = req.body.type;\n try {\n await pool.query(sql_query.query.add_caretaker_type_of_pet, [username, type]);\n res.redirect('/caretaker?add-pet_type=pass&pet_type=' + type);\n } catch (err) {\n err = wrapError(err);\n if (err instanceof UniqueViolationError) {\n\t\t\tconsole.error(\"You can take care of this pet!\");\n\t\t\tres.redirect('/caretaker?add-pet_type=duplicate&pet_type=' + type);\n } else if (err instanceof ForeignKeyViolationError) {\n\t\t\tconsole.error(\"No such pet\");\n\t\t\tres.redirect('/caretaker?add-pet_type=non_exist');\n } else {\n\t\t\tconsole.error(err);\n\t\t\tres.redirect('/caretaker?add-pet_type=fail');\n }\n }\n}",
"async function editCupcake(evt) {\r\n evt.preventDefault();\r\n let data = {};\r\n const id = $(\".cupcakes\").attr(\"id\");\r\n const filtered = cupcakes.filter((cupcake) => cupcake.id == id);\r\n const cupcake = filtered[0];\r\n let inputs = {\r\n flavor: $(\"#flavor_input\").val(),\r\n size: $(\"#size_input\").val(),\r\n image: $(\"#image_input\").val(),\r\n rating: $(\"#rating_input\").val(),\r\n };\r\n try {\r\n checkForm(inputs);\r\n for (let key in inputs) {\r\n if (inputs[key]) {\r\n data[key] = inputs[key];\r\n }\r\n }\r\n await cupcake.updateCupcake(data); \r\n restoreCupcakeList();\r\n await getCupcakes();\r\n showMessage(\"Cupcake updated.\")\r\n } catch (err) {\r\n alert(err.message);\r\n }\r\n }",
"function Pet(petName,age,adopted,markings,breed){\n this.petName = petName;\n this.age = age;\n this.adopted = adopted;\n this.markings = markings;\n this.breed = breed;\n}",
"function editKoders(){\n let addKoder = prompt(\"ยฟDesea agregar o borrar algรบn koder?\");\n (addKoder === \"agregar\" ? Koders() : dropKoders(addKoder))\n}",
"function updateTaxForPrice(rates, price) {\n var priceEffective = moment(moment(price.effectiveDate).utc().format('YYYY-MM-DD')).toDate();\n if (priceEffective < new Date()) {\n priceEffective = new Date();\n }\n var productTaxRate = taxHelper.getEffectiveTaxRate(rates, priceEffective);\n if (productTaxRate && !$.isEmptyObject(productTaxRate)) {\n price.taxRate = productTaxRate.rate;\n } else {\n taxHelper.getAllTaxRates().then(function(systemRates) {\n var systemRate = taxHelper.getEffectiveTaxRate(systemRates, priceEffective);\n if (systemRate && !$.isEmptyObject(systemRate)) {\n price.taxRate = systemRate.rate;\n } else {\n price.taxRate = 0;\n }\n });\n }\n }",
"get price() {\n return this._price\n }",
"function updatePrice(fruit) {\n\tconsole.log(\"updatePrice:\", 'running');\n\tdo {\n\t\tvar priceChange = randomNumber(-50, 50);\n\t\tconsole.log('priceChange', priceChange);\n\t\tfruit.price += priceChange;\n\t} while(fruit.price >= 999 || fruit.price <= 50);\n\n\tconsole.log(fruit.price);\n\treturn fruit.price;\n}",
"getPrice() {\n return this.beveragePrice;\n }",
"function getIngPrice(item)\n{\n alert(\"get price of ingridient \"+item+\" from DB\");\n return 100;\n\n // TODO: can we multiple iingredients ?\n}",
"adoptPet(currentSpecies) {\n let index = prompt('Enter the index of the pet you want to adopt:');\n if (index > -1 && index < this.selectedSpecies.pets.length) {\n this.selectedSpecies.pets.splice(index, 1);\n }\n if (this.selectedSpecies.pets.length < 1){\n this.animalSpecies.splice(currentSpecies, 1);\n }\n }",
"function editSave() {\n if (!inputValid()) return;\n vm.editObj.id = -3;\n server.addBuoy(vm.editObj).then(function(res) {\n queryBuoys();\n queryBuoyInstances();\n gui.alertSuccess('Buoy added.');\n }, function(res) {\n gui.alertBadResponse(res);\n vm.buoys.splice(vm.buoys.length - 1, 1);\n });\n vm.editId = -1;\n }",
"showPrice(id) {\r\n document.getElementById(\"servingPrice\").innerHTML = \"Price per Serving $\" + (id.pricePerServing / 100).toFixed(2);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the address has a number, a label, a zip code and a city using a regex. | function validateAddress() {
var addressInput = $('#register-address');
var addressInputValue = addressInput.val();
var addressRegex = /^\d+\s([A-Z]?[a-z]+\s){2}\d{5}\s[A-Z]?[a-z]+$/;
if (addressInputValue.match(addressRegex)) {
validInput(addressInput);
} else {
invalidInput(addressInput, $mustBeAnAddress)
}
} | [
"function zipOrCity(searchInput) {\n regexp = /^[0-9]{5}(?:-[0-9]{4})?$/;\n\n if (regexp.test(searchInput))\n {\n return true;\n }\n else\n {\n return false;\n }\n }",
"function validateAddress() {\n return checkPersonalInfo(\"address\", \"Address must have at least 3 characters\");\n}",
"function is_valid_latlng(address) {\n return address.match(/^([-+]?[1-8]?\\d(\\.\\d+)?|90(\\.0+)?),?\\s*([-+]?180(\\.0+)?|[-+]?((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)(,\\d+z)?$/);\n }",
"function check_address_enough(address_components,conditions) {\n var out = true;\n $.each(conditions, function(index, value) {\n if (typeof g_find_type_in_results(address_components, value[0], value[1]) === 'undefined') out = false;\n });\n return out;\n}",
"function ssw_js_validate_site_address() {\n\n var site_address_regex = /^[a-zA-Z0-9]+[a-zA-Z0-9_]*$/;\n site_address = document.getElementById('ssw-steps').site_address.value;\n\n if (!site_address_regex.test(site_address)) {\n document.getElementById(\"ssw-site-address-error-label\").innerHTML=ssw_site_address_invalid_msg;\n document.getElementById(\"ssw-site-address-error\").style.display=\"block\"; \n return false;\n }\n else {\n document.getElementById(\"ssw-site-address-error\").style.display=\"none\";\n return true;\n }\n}",
"function isAddress(string) {\n try {\n bitcoin.Address.fromBase58Check(string)\n } catch (e) {\n return false\n }\n\n return true\n}",
"function validateCity() {\n return checkPersonalInfo(\"city\", \"City name must have at least 3 characters\");\n}",
"function ccvAndZipEntered() {\n\tvar zipVal = /^\\d{5}$|^\\d{5}-\\d{4}$/;\n\tvar cvvVal = /^\\d{3}$/;\n\treturn zipVal.test($(\"#zip\").val()) && cvvVal.test($(\"#cvv\").val());\n}",
"function validateBillingAddress(formname)\n{\n\t\n if(validateForm(formname,'frmAddressLine1', 'Address', 'R','frmCountry', 'Country', 'R', 'frmState', 'State','R', 'frmCity', 'City', 'R', 'frmZipCode', 'Zip Code', 'R'))\n {\t\n\t\t\n\t\t\n return true;\n } \n else \n {\n return false;\n } \n}",
"function getCity(address) {\r\n\tvar lastCommaPos = address.lastIndexOf(\",\", address.length);\r\n\tvar firstCommaPos = address.indexOf(\",\");\r\n\tif (lastCommaPos != firstCommaPos)\r\n\t\treturn address.substring(firstCommaPos + 8, lastCommaPos);\r\n\telse\r\n\t\treturn address.substring(0, lastCommaPos);\r\n}",
"function parseAddress(addrEl) {\n var els = addrEl.elsByTag('streetAddressLine');\n var street = [];\n\n for (var i = 0; i < els.length; i++) {\n var val = els[i].val();\n if (val) {\n street.push(val);\n }\n }\n\n var city = addrEl.tag('city').val(),\n state = addrEl.tag('state').val(),\n zip = addrEl.tag('postalCode').val(),\n country = addrEl.tag('country').val();\n\n return {\n street: street,\n city: city,\n state: state,\n zip: zip,\n country: country\n };\n}",
"function validateCanadaPostalCode(postalCodeFld) {\r\n if (isEmpty(postalCodeFld.value) || isFieldMasked(postalCodeFld)) {\r\n return \"\";\r\n }\r\n\r\n var postalCodeRegExp = new RegExp(\"^[a-zA-Z]\\\\d[a-zA-Z] \\\\d[a-zA-Z]\\\\d$\");\r\n\r\n if (!postalCodeRegExp.test(postalCodeFld.value)) {\r\n return getMessage(\"ci.entity.message.postalCode.invalid\");\r\n }\r\n return \"\";\r\n}",
"function valida_telefone(tel, nulo){\n \n if (nulo != 0 && tel.length == 0){\n return 1;\n }else{\n \n if(tel.length < 8){\n return 0;\n }\n \n for(var i = 0; i < tel.length; i++){\n var char = tel.substring(i, i+1);\n if(char != '(' && char != ')' && char != '-' && char != ' ' && (char.charCodeAt(0) < 48 || char.charCodeAt(0) > 58)){\n return 0;\n }\n }\n \n return 1;\n }\n}",
"function hasAddressVal(addressTable) {\n for(var i = 0; i < 4; i++) {\n if(!addressTable[i]) {\n ui.alert(\"You must select a location before I can get your values.\");\n return false;\n } \n }\n return true;\n}",
"static isValidXAddress(address) {\n return addressCodec.isValidXAddress(address);\n }",
"function check_in_region(address_components,type,name_,value) {\n if (g_find_type_in_results(address_components,type,name_) == value) {\n return true;\n } else {\n return false;\n }\n}",
"function cityInputLetters(value) {\n\tvar letters = /^[A-Za-zฤ-ลฝฤ-ลพ]+$/; //includes latvian characters as well\n\tif (value.match(letters)) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}",
"function validatePhone(a, b, c) {\n\t\t\t\t\t// Value in the field\n\t\t\t\t\tvar phone = $(a).val();\n\t\t\t\t\t// Regular Expression to validate value against\n\t\t\t\t\tvar regularExpression = /^\\+[0-9]{1,3}\\-[0-9]{4,14}(?:x.+)?$/;\n\n\t\t\t\t\tif (c) {\n\t\t\t\t\t\t// Validating field content\n\t\t\t\t\t\tif (!regularExpression.test(phone)) {\n\t\t\t\t\t\t\t$(b).text(\"Your input is invalid. Phone number only!\")\n\t\t\t\t\t\t\t\t\t.attr(\"class\", \"invalid\");\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$(b).text(\"valid\").attr(\"class\", \"valid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}",
"function validateJointPhoneNumberField (field) {\n \n // Strip non-numeric characters from the field's value\n value = field.val().replace(/\\D/g,'');\n if ( ! isDefined(value) ) return false;\n \n // Create a variable to store the index of the character after the country code\n var slicePosition = 0;\n debugLog(\"hello\");\n \n // Loop through our country codes and see if our value begins with one of them\n for ( var i in countryDataJSON.countries ) {\n var currentCountryCode = countryDataJSON.countries[i]['phoneCode'];\n if ( value.charAt(0) == currentCountryCode )\n slicePosition = 1;\n else if ( value.slice(0,2) == currentCountryCode )\n slicePosition = 2;\n else if ( value.slice(0,3) == currentCountryCode )\n slicePosition = 3;\n }\n \n // If the splice position is still zero, our value doesn't begin with a country code and is therefore invalid\n if ( slicePosition == 0 ) {\n field.val(\"+ \" + value);\n return false;\n \n // If the splice position was set, we found our country code!\n } else {\n var countryCode = value.slice(0, slicePosition);\n var phoneNumber = value.slice(slicePosition);\n \n // Format the field appropriately\n \n if ( phoneNumber.length >= 7 )\n phoneNumber = [phoneNumber.slice(0, 3), \"-\", phoneNumber.slice(3,6), \"-\", phoneNumber.slice(6)].join('');\n else if ( phoneNumber.length > 3 && phoneNumber.length < 7 )\n phoneNumber = [phoneNumber.slice(0, 3), \"-\", phoneNumber.slice(3)].join('');\n \n if ( phoneNumber.length > 0 )\n field.val(\"+ \" + [countryCode, \"-\", phoneNumber].join('') );\n else\n field.val(\"+ \" + countryCode );\n \n // If the phone number portion is longer than five digits,the field is valid\n if ( phoneNumber.replace(/\\D/g,'').length > 5 )\n return true;\n else\n return false;\n } \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the class name for a specific cell | function getClassName(location) {
var cellClass = 'cell-' + location.i + '-' + location.j;
return cellClass;
} | [
"function OnCellClick(){\n this.classList.add(\"clicked\");\n // console.log(this);\n}",
"function resolveGridColorClass(cell)\n{\n\tvar cc = \"gold\";\n\tif(cell.detected>0)\n\t{\n\t\t// apply the detected bin\n\t\tif(cell.detected < 5)\n\t\t{\n\t\t\tcc = \"blue1\";\n\t\t}\n\t\telse if(cell.detected < 51)\n\t\t{\n\t\t\tcc = \"blue2\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcc = \"blue3\";\n\t\t}\n\t}\n\telse if(cell.ambiguous>0) cc = \"gray\";\n\telse if(cell.notDetected>0)\n\t{\n\t\t// apply the not detected bin\n\t\tif(cell.notDetected < 5)\n\t\t{\n\t\t\tcc = \"red1\";\n\t\t}\n\t\telse if(cell.notDetected < 21)\n\t\t{\n\t\t\tcc = \"red2\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcc = \"red3\";\n\t\t}\n\t}\n\treturn cc;\n}",
"function getCell(row, col) {\n return document.getElementById(`cell-${row}-${col}`);\n }",
"generateCellClassNames() {\n Array.from(this.$.items.children)\n .filter((row) => !row.hidden)\n .forEach((row) => this._generateCellClassNames(row, this.__getRowModel(row)));\n }",
"function placeMarker(cell, currentClass) {\n cell.classList.add(currentClass);\n}",
"extractTileClass(tile){\n if(tile.length <= 1 || tile[0] !== 'tile') return; \n\n let [ ,row, col] = [...tile];\n\n return (parseInt(row) * 9) + (col ? parseInt(col) : parseInt(row));\n }",
"function getIEClass()\n{\n if(isIE(6))\n return \"ie ie6 lte9 lte8 lte7 lte6\";\n if(isIE(7))\n return \"ie ie7 lte9 lte8 lte7\";\n if(isIE(8))\n return \"ie ie8 lte9 lte8\";\n if(isIE(9))\n return \"ie ie9 lte9\";\n if(isIE())\n return \"ie\";\n return \"\";\n}",
"function typeOfCell(p, q, r) {\n\n const name = p + \"-\" + q + \"-\" + r;\n\n if ([\"3-3-3\", \"3-3-4\", \"3-3-5\", \"3-4-3\", \"4-3-3\", \"5-3-3\"].includes(name)) {\n\n return \"s\";\n\n } else if (name === \"4-3-4\") {\n\n return \"e\";\n\n } else {\n\n const qr = (q - 2) * (r - 2);\n\n if (qr < 4) {\n\n return \"h\"\n\n } else if (qr == 4) {\n\n return \"p\"\n\n } else {\n\n return \"u\"\n\n }\n\n }\n\n}",
"klass(i) {\n var col, mod, ncol, row;\n ncol = 3;\n mod = i % ncol;\n row = (i - mod) / ncol + 1;\n col = mod + 1;\n return `r${row}c${col}`;\n }",
"function isCell(target) {\n return target.tagName === \"INPUT\"\n && target.classList.length\n && target.classList[0] === 'sudoku-input';\n}",
"function findLastEmptyCell(incoming_col){\n const container = document.querySelector('#connect4');\n const containerRow = container.querySelectorAll('.row');\n cellsArr = [];\n containerRow.forEach(function(row){\n cells = row.querySelector('[data-col=\"'+ incoming_col +'\"]');\n cellsArr.push(cells);\n });\n\n // Looping through array of each column to find the last empty spot\n for(let i = cellsArr.length-1; i>=0; i--){\n const classes = cellsArr[i].classList\n if(classes == 'col empty'){\n console.log(classes)\n return cellsArr[i];\n }\n }\n return null;\n }",
"findCell(target) {\n const { width, height, right, bottom } = target.getBoundingClientRect();\n return document.elementFromPoint(\n this.checkClass(target, \"btn-remove-row\") ? width + right : right,\n this.checkClass(target, \"btn-remove-column\") ? height + bottom : bottom\n );\n }",
"getColumnIndex(): number {\n const { row, cell } = this;\n const cells = row.nodes;\n\n return cells.findIndex(x => x === cell);\n }",
"function getRow(element){\n var row_num = parseInt(element.classList[0][4]);\n return row_num;\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 getClass(element, k) {\n return element.attr(\"class\").split(\" \")[k-1];\n}",
"function findDataTypeOfGridCellExpr(expr) {\r\n\r\n assert(expr.isGridCell(), \"must be a grid cell expr\");\r\n assert(expr.gO, \"grid cell must have gO reference\");\r\n\r\n var gO = expr.gO;\r\n\r\n if (gO.typesInDim < 0) { // global type\r\n\r\n return gO.dataTypes[0];\r\n\r\n } else { // type is in each title\r\n\r\n // Data types are in gO.typesInDim dimension\r\n // Note: For any grid cell, dimIds contain which indices for picked\r\n //\r\n var indExpr = expr.exprArr[gO.typesInDim]; // index expr\r\n var indval = expr.dimIds[gO.typesInDim];\r\n var datatype = gO.dataTypes[indval];\r\n //\r\n // alert(\"dim:\" + gO.typesInDim + \" title:\" + indExpr.str \r\n // + \" ind:\" + indval + \" datatype:\" + datatype);\r\n //\r\n return datatype;\r\n }\r\n}",
"function changeClassName(gridname) {\r\n\r\n\t//document.getElementById('mynew').className= 'dgItem0';\r\n\tvar grid=document.getElementById(gridname);\r\n\r\nvar cname='dgItem0';\r\n\r\n\tfor(var i=1;i<grid.rows.length; i++)\r\n\t{\r\n\r\n\t if (grid.rows[i].style.display != 'none') {\r\n\r\n\t\t\t\tgrid.rows[i].className = cname;\r\n\r\n\t\t\t\tif(cname=='dgItem0')\r\n\t\t\t\tcname='dgItem1';\r\n\t\t\t\telse\r\n\t\t\t\tcname='dgItem0';\r\n\t\t\t\t//var cells=grid.rows[i].getElementsByTagName(\"TD\");\r\n \t\t\t//\tfor (var j=0; j<cells.length; j++)\r\n\t\t\t\t//\t{\r\n \t\t\t//\t cells[j].setAttribute('className','dgGrid td');\r\n\t\t\t\t//\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n}",
"function getClass(){\n\tvar classes = ['barbarian', 'monk', 'fighter', 'paladin', 'rogue', 'ranger',\n\t'bard', 'wizard', 'warlock', 'sorcerer', 'cleric', 'druid'];\n\treturn classes[Math.floor((Math.random() * classes.length) + 1)-1];\n}",
"function getGridBackgroundColorClass() {\n return 'highlighted-' + getGridBackgroundColor();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the visualization settings passed in the World settings of MATRX. Also changes the bg if needed | function parse_vis_settings(vis_settings) {
bg_colour = vis_settings['vis_bg_clr'];
bg_image = null;
if (Object.keys(vis_settings).includes('vis_bg_img') && vis_settings['vis_bg_img'] != null) {
bg_image = fix_img_url(vis_settings['vis_bg_img']);
}
// update background colour / image if needed
draw_bg();
} | [
"function parse_world_settings(world_settings) {\n tps = (1.0 / world_settings['tick_duration']).toFixed(1);\n current_tick = world_settings['nr_ticks'];\n\n if (current_tick > latest_tick_processed + 1) {\n console.log(\"Dropped frame, current tick:\", current_tick, \" last tick processed: \", latest_tick_processed);\n }\n\n // reset some things if we are visualizing a new world\n if (world_ID != world_settings['world_ID']) {\n // if it is not the first load of a world, but a genuine transition to a new world, reset\n // the chat\n if (world_ID != null) {\n reset_chat();\n }\n populate_god_agent_menu = true;\n pop_new_chat_dropdown = true;\n\n // add MATRX version to screen on the bottom right\n $(\"body\").append(`<div class=\"matrx_core_version\">MATRX Core version: ${lv_matrx_version}</div>`)\n }\n world_ID = world_settings['world_ID'];\n\n // calculate how many milliseconds the movement animation should take\n animation_duration_s = (1.0 / tps) * animation_duration_perc;\n\n // parse new visualization settings\n vis_settings = world_settings['vis_settings'];\n parse_vis_settings(vis_settings);\n\n // update grid\n update_grid_size(world_settings['grid_shape']);\n}",
"readSettings() {\n\n this._hue.bridges = this._settings.get_value(Utils.HUELIGHTS_SETTINGS_BRIDGES).deep_unpack();\n this._indicatorPosition = this._settings.get_enum(Utils.HUELIGHTS_SETTINGS_INDICATOR);\n this._zonesFirst = this._settings.get_boolean(Utils.HUELIGHTS_SETTINGS_ZONESFIRST);\n this._showScenes = this._settings.get_boolean(Utils.HUELIGHTS_SETTINGS_SHOWSCENES);\n }",
"function updateStyle() {\r\n\tif (settings.darkThemeSettings) {\r\n\t\t//dark theme colors\r\n\t\troot.style.setProperty(\"--background-color\", \"#0F0F0F\");\r\n\t\troot.style.setProperty(\"--foreground-color\", \"#FFFFFF\");\r\n\t\troot.style.setProperty(\"--red-color\", \"#a53737\");\r\n\t} else {\r\n\t\t//light theme colors\r\n\t\troot.style.setProperty(\"--background-color\", \"#FFFFFF\");\r\n\t\troot.style.setProperty(\"--foreground-color\", \"#000000\");\r\n\t\troot.style.setProperty(\"--red-color\", \"#f55555\");\r\n\t}\r\n}",
"function setupNewColorsMeshs() {\n cubeMeshs.forEach(object => {\n object.children[0].children[0].material[1].color = colorScene;\n object.children[0].children[0].material[1].emissive = colorScene;\n });\n\n torusMesh.forEach(object => {\n switch (countTic > 2) {\n case true:\n object.children[0].material[1].emissive = new THREE.Color(0xffffff);\n object.children[0].material[1].color = new THREE.Color(0xffffff);\n object.children[0].material[4].emissive = colorScene;\n object.children[0].material[4].color = colorScene;\n break;\n case false:\n object.children[0].material[1].emissive = colorScene;\n object.children[0].material[1].color = colorScene;\n object.children[0].material[4].emissive = new THREE.Color(0xffffff);\n object.children[0].material[4].color = new THREE.Color(0xffffff);\n break;\n }\n });\n}",
"configureWebGLRenderer() {\n if (this.WebGLRenderer !== undefined) {\n /* Configures THREE.WebGLRenderer according to this.nature.WebGLRendererParameters */\n if (this.nature.WebGLRendererParameters) {\n if (this.nature.WebGLRendererParameters.clearColor)\n this.WebGLRenderer.setClearColor(parseInt(this.nature.WebGLRendererParameters.clearColor));\n if (this.nature.WebGLRendererParameters.shadowMap == true) {\n this.WebGLRenderer.shadowMap.enabled = true;\n this.WebGLRenderer.shadowMap.type = THREE.PCFSoftShadowMap; // default THREE.PCFShadowMap\n }\n }\n /** Configures THREE.WebGLRenderer according to this.SceneDispatcher.currentVLabScene.nature.WebGLRendererParameters\n * if this.SceneDispatcher.currentVLabScene.nature is defined\n */\n if (this.SceneDispatcher.currentVLabScene.nature) {\n if (this.SceneDispatcher.currentVLabScene.nature.WebGLRendererParameters) {\n if (this.SceneDispatcher.currentVLabScene.nature.WebGLRendererParameters.clearColor)\n this.WebGLRenderer.setClearColor(parseInt(this.SceneDispatcher.currentVLabScene.nature.WebGLRendererParameters.clearColor));\n }\n }\n }\n }",
"_applyConfigStyling() {\n if (this.backgroundColor) {\n const darkerColor = new ColorManipulator().shade(-0.55, this.backgroundColor);\n this.headerEl.style['background-color'] = this.backgroundColor; /* For browsers that do not support gradients */\n this.headerEl.style['background-image'] = `linear-gradient(${this.backgroundColor}, ${darkerColor})`;\n }\n\n if (this.foregroundColor) {\n this.headerEl.style.color = this.foregroundColor;\n }\n }",
"function updateMazeStyle(isLight) {\r\n clearCanvas(); /* Clear the Canvas first */\r\n if (isLight) {\r\n lineClr = 'rgba(0,0,0,0.5)';\r\n } else {\r\n lineClr = 'rgba(255,255,255,0.5)';\r\n }\r\n drawcells(); /* Redraw the cells */\r\n}",
"function loadSurfaceColor () {\n\n setShaderColor( controller.configure.color.surface );\n\n if ( controller.configure.color.selected === null ) {\n\n setHighlightColor( controller.configure.color.surface );\n\t\t\tconsole.log('highlight color===========>', controller.configure.color.surface)\n } else {\n\n setHighlightColor( controller.configure.color.selected );\n\n }\n\n }",
"_Init(params) {\n this._sky = new Sky();\n this._sky.scale.setScalar(10000);\n params.scene.add(this._sky);\n\n params.guiParams.sky = {\n turbidity: 10.0,\n rayleigh: 2,\n mieCoefficient: 0.005,\n mieDirectionalG: 0.8,\n luminance: 1,\n };\n\n //determined by inclination and azimuth of the brightness of sun and darkness of the sky\n params.guiParams.sun = {\n inclination: 0.31,\n azimuth: 0.25,\n };\n\n const onShaderChange = () => {\n for (let k in params.guiParams.sky) {\n this._sky.material.uniforms[k].value = params.guiParams.sky[k];\n }\n for (let k in params.guiParams.general) {\n this._sky.material.uniforms[k].value = params.guiParams.general[k];\n }\n };\n\n const onSunChange = () => {\n var theta = Math.PI * (params.guiParams.sun.inclination - 0.5);\n var phi = 2 * Math.PI * (params.guiParams.sun.azimuth - 0.5);\n\n const sunPosition = new THREE.Vector3();\n sunPosition.x = Math.cos(phi);\n sunPosition.y = Math.sin(phi) * Math.sin(theta);\n sunPosition.z = Math.sin(phi) * Math.cos(theta);\n\n this._sky.material.uniforms['sunPosition'].value.copy(sunPosition);\n };\n\n //adds gui for the user to change\n const sunRollup = params.gui.addFolder('Day & Night');\n sunRollup.add(params.guiParams.sun, \"inclination\", 0.0, 1.0).onChange(\n onSunChange);\n sunRollup.add(params.guiParams.sun, \"azimuth\", 0.0, 1.0).onChange(\n onSunChange);\n\n onShaderChange();\n onSunChange();\n }",
"setAlphas() {\n this.r3a1_exitDoor.alpha = 1.0;\n this.character.alpha = 1.0;\n this.r3a1_char_north.alpha = 0.0;\n this.r3a1_char_south.alpha = 0.0;\n this.r3a1_char_west.alpha = 0.0;\n this.r3a1_char_east.alpha = 0.0;\n this.r3a1_map.alpha = 0.0;\n this.r3a1_notebook.alpha = 0.0;\n this.r3a1_activityLocked.alpha = 0.0;\n this.r3a1_E_KeyImg.alpha = 0.0;\n this.r3a1_help_menu.alpha = 0.0;\n this.r3a1_redX.alpha = 0.0;\n this.r3a1_greenCheck.alpha = 0.0;\n //this.r3a1_hole.alpha = 0.0;\n this.hideActivities();\n this.profile.alpha = 0.0;\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 }",
"function generalSetup() {\n // Scene\n scene = new THREE.Scene();\n // Camera setup\n camera = new THREE.PerspectiveCamera(75, canvasSize.width / canvasSize.height, 0.1, 1000);\n camera.position.set(1, 0, 0);\n // Renderer setup\n renderer = new THREE.WebGLRenderer({antialias: true});\n renderer.setSize(canvasSize.width, canvasSize.height);\n cv.appendChild(renderer.domElement);\n // Post processing setup\n composer = new POSTPROCESSING.EffectComposer(renderer);\n composer.addPass(new POSTPROCESSING.RenderPass(scene, camera));\n const effectPass = new POSTPROCESSING.EffectPass(camera, new POSTPROCESSING.BloomEffect());\n effectPass.renderToScreen = true;\n composer.addPass(effectPass);\n}",
"initAnnotSettings() {\n if (\n this.config.annotationsPath ||\n this.config.localAnnotationsPath ||\n this.annots || this.config.annotations\n ) {\n if (!this.config.annotationHeight) {\n var annotHeight = Math.round(this.config.chrHeight / 100);\n this.config.annotationHeight = annotHeight;\n }\n\n if (this.config.annotationTracks) {\n this.config.numAnnotTracks = this.config.annotationTracks.length;\n } else {\n this.config.numAnnotTracks = 1;\n }\n this.config.annotTracksHeight =\n this.config.annotationHeight * this.config.numAnnotTracks;\n\n if (typeof this.config.barWidth === 'undefined') {\n this.config.barWidth = 3;\n }\n } else {\n this.config.annotTracksHeight = 0;\n }\n\n if (typeof this.config.annotationsColor === 'undefined') {\n this.config.annotationsColor = '#F00';\n }\n }",
"set MeshRenderer(value) {}",
"function visualize() {\n\n visualizer.updatePitchChart(audioProcessor.getPitches(), audioProcessor.getTimestamps());\n visualizer.updateRateChart(audioProcessor.getVibratoRates(), audioProcessor.getTimestamps());\n visualizer.updateWidthChart(audioProcessor.getVibratoWidths(), audioProcessor.getTimestamps());\n calcPitch();\n}",
"_configureProperties(data, style, summary) {\n var vis = _.extend({}, style), d, key;\n if (vis.strokeColorKey) {\n vis.strokeColor = _.compose(\n geojsonUtil.colorScale(vis.strokeRamp, summary[vis.strokeColorKey]),\n function (props) { return props[vis.strokeColorKey]; }\n );\n }\n\n if (vis.fillColorKey) {\n d = [];\n key = vis.fillColorKey;\n data.features.forEach(function (item, index, array) {\n d.push(item.properties[key]);\n });\n vis.fillColor = _.compose(\n geojsonUtil.colorScale(vis.fillRamp, summary[vis.fillColorKey],\n vis.logFlag, vis.quantileFlag,\n vis.clampingFlag, vis.minClamp, vis.maxClamp, d),\n function (props) { return props[vis.fillColorKey]; }\n );\n }\n return vis;\n }",
"function setSpecialSettings(src, dst) {\n\t if (src.backgroundColor !== undefined) {\n\t setBackgroundColor(src.backgroundColor, dst);\n\t }\n\n\t setDataColor(src.dataColor, dst);\n\t setStyle(src.style, dst);\n\t setShowLegend(src.showLegend, dst);\n\t setCameraPosition(src.cameraPosition, dst);\n\n\t // As special fields go, this is an easy one; just a translation of the name.\n\t // Can't use this.tooltip directly, because that field exists internally\n\t if (src.tooltip !== undefined) {\n\t dst.showTooltip = src.tooltip;\n\t }\n\t }",
"function updateColorThemeDisplay() {\n // template string for the color swatches:\n const makeSpanTag = (color, count, themeName) => (\n `<span style=\"background-color: ${color};\" `\n + `class=\"color_sample_${count}\" `\n + `title=\"${color} from d3 color scheme ${themeName}\">`\n + ' </span>'\n );\n for (const t of colorThemes.keys()) {\n const theme = approvedColorTheme(t),\n themeOffset = elV(offsetField(t)),\n colorset = rotateColors(theme.colorset, themeOffset),\n // Show the array rotated properly given the offset:\n renderedGuide = colorset\n .map((c) => makeSpanTag(c, colorset.length, theme.d3Name))\n .join('');\n // SOMEDAY: Add an indicator for which colors are/are not\n // in use?\n el(`theme_${t}_guide`).innerHTML = renderedGuide;\n el(`theme_${t}_label`).textContent = theme.nickname;\n }\n }",
"function showgreen() {\r\n var o_panel_info = document.getElementById(\"outputpanel\").classList\r\n if(o_panel_info.length > 1){\r\n o_panel_info.remove(\"redbg\", \"darkbg\", \"lightbg\");\r\n }\r\n o_panel_info.add(\"greenbg\");\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
1. makeTimeSliceGraph and its helper functions / Given a timeseries graph and a string matching a timestamp in that graph, returns a new graph containing only data present at that particular moment. Can generate a timeslice from a C3 graph specification with an xaxis of either "timeseries" (like a Long Term Average graph) or "category" (like an Annual Cycle graph) type, but not from a graph with an "indexed" type x axis. | function makeTimeSliceGraph (timestamp, graph) {
let slicedData = [];
let timestamps = [];
let sliceIndex = -1;
if(graph.axis.x.type == "timeseries") {
//x-axis has a series of dates
timestamps = graph.data.columns.find(function(series) {return series[0] === 'x'});
}
else if(graph.axis.x.type == "category") {
//x-axis is text, most likely month names
timestamps = graph.axis.x.categories;
}
else {
throw new Error("Error: timeslice graph must be generated from a timeseries");
}
if(_.isUndefined(timestamps)) {
throw new Error("Error: time information missing from source graph");
}
sliceIndex = timestamps.indexOf(timestamp);
if(sliceIndex === -1) {
throw new Error("Error: invalid timestamp selected");
}
for(let i = 0; i < graph.data.columns.length; i++) {
let series = graph.data.columns[i];
if(!_.isUndefined(series[sliceIndex]) && series[0] !== 'x'){
slicedData.push([series[0], series[sliceIndex]]);
}
}
//sort the data series by value, to make matching with the legend easier
slicedData.sort((a, b) => {return b[1] - a[1]});
graph.data.columns = slicedData;
//remove timeseries-related formatting
let date = new Date(timestamp);
graph.axis.x = {
type: 'category',
categories: [date.getFullYear()]
};
graph.data.x = undefined;
graph.tooltip = {show: false};
return graph;
} | [
"slice(begin, end) {\n const size = this.size();\n const b = resolveBegin(begin, size);\n const e = resolveEnd(end, size);\n\n if (b === 0 && e === size ) {\n return this;\n }\n\n const events = [];\n for (let i = b; i < e; i++) {\n events.push(this.at(i));\n }\n\n return new TimeSeries({ name: this._name,\n index: this._index,\n utc: this._utc,\n meta: this._meta,\n events });\n }",
"function getCrossSlice(startSlice,endSlice)\n{\n var sliceString;\n\n //trying to move z slices from the top towards the upper right corner\n //start from x_slice1 and land on x_slice2 or x_slice3, or start from\n //x_slice2 or x_slice3 and land on x_slice1\n if(((startSlice === \"x_slice1\") && ((endSlice === \"x_slice2\") || (endSlice === \"x_slice3\")))\n || (((startSlice === \"x_slice2\") || (startSlice === \"x_slice3\")) \n && ((endSlice === \"x_slice2\") || (endSlice === \"x_slice1\")))){\n if((startX < .531) && (startX > -.106) && (startY < .383) && (startY > .227)\n && (endX < .531) && (endX > -.106) && (endY < .383) && (endY > .227)){\n sliceString = \"z_slice1\";\n //window.alert(\"In here z1\"); \n }\n else if((startX < .367) && (startX > -.309) && (startY < .422) && (startY > .273)\n && (endX < .367) && (endX > -.309) && (endY < .422) && (endY > .273)){\n sliceString = \"z_slice2\";\n //window.alert(\"In here z2\"); \n }\n else if((startX < .145) && (startX > -.484) && (startY < .465) && (startY > .305)\n && (endX < .145) && (endX > -.484) && (endY < .465) && (endY > .305)){\n sliceString = \"z_slice3\";\n //window.alert(\"In here z3\"); \n } \n }//end z slices\n //y slices right side\n if(((startSlice === \"x_slice1\") && ((endSlice === \"x_slice2\") || (endSlice === \"x_slice3\")))\n || (((startSlice === \"x_slice2\") || (startSlice === \"x_slice3\")) && \n ((endSlice === \"x_slice2\") || (endSlice === \"x_slice1\")))\n ){\n if((startX < .563) && (startX > .059) && (startY < .344) && (startY > -.012)\n && (endX < .563) && (endX > .059) && (endY < .344) && (endY > -.012)){\n sliceString = \"y_slice1\";//right side \n //window.alert(\"In here y1 right\");\n } \n else if((startX < .574) && (startX > .051) && (startY < .098) && (startY > -.277)\n && (endX < .574) && (endX > .051) && (endY < .098) && (endY > -.277)){\n sliceString = \"y_slice2\";//right side \n //window.alert(\"In here y2 right\");\n } \n else if((startX < .578) && (startX > .051) && (startY < -.152) && (startY > -.538)\n && (endX < .578) && (endX > .051) && (endY < -.152) && (endY > -.538)){\n sliceString = \"y_slice3\";//right side \n //window.alert(\"In here y3 right\");\n } \n }//end y right slices\n //y slices left side\n if(((startSlice === \"z_slice1\") && ((endSlice === \"z_slice2\") || (endSlice === \"z_slice3\")))\n || (((startSlice === \"z_slice2\") || (startSlice === \"z_slice3\")) && \n ((endSlice === \"z_slice2\") || (endSlice === \"z_slice1\")))\n ){\n if((startX < .043) && (startX > -.576) && (startY < .332) && (startY > -.027)\n && (endX < .043) && (endX > -.576) && (endY < .332) && (endY > -.027)){\n sliceString = \"y_slice1\";//right side \n //window.alert(\"In here y1 left\");\n } \n else if((startX < .051) && (startX > -.512) && (startY < .078) && (startY > -.28)\n && (endX < .051) && (endX > -.512) && (endY < .078) && (endY > -.28)){\n sliceString = \"y_slice2\";//right side \n //window.alert(\"In here y2 left\");\n } \n else if((startX < .051) && (startX > -.512) && (startY < -.179) && (startY > -.531)\n && (endX < .051) && (endX > -.512) && (endY < -.179) && (endY > -.531)){\n sliceString = \"y_slice3\";//right side \n //window.alert(\"In here y3 left\");\n } \n }//end y left slices\n return sliceString;\n}",
"function ThreadTimeSlice(thread, schedulingState, cat,\n start, args, opt_duration) {\n Slice.call(this, cat, schedulingState,\n this.getColorForState_(schedulingState),\n start, args, opt_duration);\n this.thread = thread;\n this.schedulingState = schedulingState;\n this.cpuOnWhichThreadWasRunning = undefined;\n }",
"function parseTime(datetime, format) {\n\tvar parser = d3.timeParse(format);\n\treturn parser(datetime);\n}",
"function makeVariableResponseGraph (x, y, graph) {\n let c3Data = {};\n\n const seriesNameContains = function (series, keyword) {\n return caseInsensitiveStringSearch(series[0], keyword);\n }\n \n const xseries = _.filter(graph.data.columns, series => seriesNameContains(series, x));\n const yseries = _.filter(graph.data.columns, series => seriesNameContains(series, y));\n\n let tuples = [];\n let seriesMatched = false;\n for(const independent of xseries) {\n //Try to match each dependent variable series with an independent variable series\n let dependent = _.find(yseries, series => {\n return series[0].toLowerCase().replace(y.toLowerCase(), x.toLowerCase()) === \n independent[0].toLowerCase();\n });\n if(dependent) {\n seriesMatched = true;\n for(let n = 1; n < independent.length; n++) {\n if(!_.isNull(independent[n]) && !_.isNull(dependent[n])) {\n tuples.push([independent[n], dependent[n]]);\n }\n }\n }\n }\n if(!seriesMatched) {\n throw new Error(\"Unable to correlate variables\");\n }\n \n //sort by x value, preperatory to putting on the graph.\n tuples.sort((a, b) => a[0] - b[0]); \n \n //C3 doesn't really support scatterplots, but we can fake it by adding\n //a missing data point between each actual data point, and instructing C3\n //not to connect across missing data points with {connectNull: false} \n //TODO: break this out into makeScatterplot(); we'll likely need it again\n c3Data.columns = [];\n c3Data.columns.push(_.reduce(tuples, (memo, tuple, index, list) => {\n memo.push(tuple[0]);\n if(index < list.length - 1) {\n memo.push(tuple[0] / 2 + list[index + 1][0] / 2);\n }\n return memo;\n }, [\"x\"])); \n c3Data.columns.push(_.reduce(tuples, (memo, tuple, index, list) => {\n index < list.length - 1 ? memo.push(tuple[1], null) : memo.push(tuple[1]);\n return memo;\n }, [y]));\n \n // Generate x and y axes. Reuse labels from source graph,\n // but add variable names if not present.\n let xAxisLabel = getAxisTextForVariable(graph, x);\n xAxisLabel = xAxisLabel.search(x) === -1 ? `${x} ${xAxisLabel}` : xAxisLabel;\n const xAxis = {\n tick: {\n count: 8,\n fit: true,\n format: fixedPrecision\n },\n label: xAxisLabel\n };\n\n let yAxisLabel = getAxisTextForVariable(graph, y);\n yAxisLabel = yAxisLabel.search(y) === -1 ? `${y} ${yAxisLabel}` : yAxisLabel;\n const yAxis = {\n tick: {\n format: fixedPrecision\n },\n label: yAxisLabel\n };\n\n //Whole-graph formatting options\n c3Data.x = 'x'; //use x series\n const c3Line = {connectNull: false}; //don't connect point data\n const c3Tooltip = {show: false}; //no tooltip or legend, simplify graph.\n const c3Legend = {show: false};\n\n return {\n data: c3Data,\n line: c3Line,\n tooltip: c3Tooltip,\n legend: c3Legend,\n axis: {\n y: yAxis,\n x: xAxis\n },\n };\n}",
"function renderGanttStation(incData, selectedStation) {\r\n //console.log('renderGanttStation ' + selectedStation);\r\n viewData = incData;\r\n var locomotives = [];\r\n var startTimes = [];\r\n var endTimes = [];\r\n if (firstTime == 0) {\r\n tasks = [];\r\n locomotives = [];\r\n }\r\n for (var i = 0; i < viewData.Events.length; i++) {\r\n if ((viewData.Events[i].station == selectedStation) && (viewData.Events[i].completionTime != viewData.Events[i].startTime)) {\r\n //also get a customer name from the Names Json\r\n for (var j = 0; j < viewData.Names.length; j++) {\r\n if (viewData.Names[j].PO == viewData.Events[i].PO) {\r\n var custName = viewData.Names[j].customer;\r\n //console.log(custName);\r\n }\r\n }\r\n locomotives.push(custName + \" \" + viewData.Events[i].seq);\r\n endTimes.push(new Date(parseInt(viewData.Events[i].completionTime)));\r\n startTimes.push(new Date(parseInt(viewData.Events[i].startTime)));\r\n tasks.push({\r\n \"endDate\" : new Date(parseInt(viewData.Events[i].completionTime)),\r\n \"startDate\" : new Date(parseInt(viewData.Events[i].startTime)),\r\n \"locomotive\" : custName + \" \" + viewData.Events[i].seq,\r\n \"status\" : \"YELLOW\"\r\n });\r\n }\r\n }\r\n //locomotives.sort();\r\n //now add customer names\r\n var taskStatus = {\r\n \"BLUE\" : \"bar-blue\",\r\n \"RED\" : \"bar-red\",\r\n \"GREEN\" : \"bar-green\",\r\n \"YELLOW\" : \"bar-yellow\"\r\n };\r\n tasks.sort(function (a, b) {\r\n return a.endDate - b.endDate;\r\n });\r\n var maxDate = tasks[tasks.length - 1].endDate;\r\n tasks.sort(function (a, b) {\r\n return a.startDate - b.startDate;\r\n });\r\n var minDate = tasks[0].startDate;\r\n /**FORMAT FOR X AXIS DATES CAN BE CHANGED HERE using d3.time.format\r\n * SEE https://github.com/mbostock/d3/wiki/Time-Formatting\r\n **/\r\n var format = \" %a, %x\";\r\n if (firstTime == 0) { //the view is being redrawn\r\n //remove current view\r\n d3.select(\"svg\").remove();\r\n //draw a new one with new input\r\n gantt = d3.gantt(tasks).taskTypes(locomotives).taskStatus(taskStatus).tickFormat(format);\r\n gantt(tasks);\r\n } else { //the view is being drawn first time\r\n firstTime = 0;\r\n gantt = d3.gantt(tasks).taskTypes(locomotives).taskStatus(taskStatus).tickFormat(format);\r\n gantt(tasks);\r\n }\r\n}",
"function switch_chart_to(spec) {\n if (spec == \"\") {\n return;\n }\n\n document.getElementById(\"pre_chart_options\").style.display = 'block';\n\n // load scripts/data of the wanted chart if it's not already present\n var already_loaded = false;\n var scripts = document.scripts\n for (var i = scripts.length - 1; i >= 0; i--) {\n // if a script already is loaded for the fight style and spec, don't load again\n if (~scripts[i].src.indexOf(\"js/crucible/crucible_\" + spec + \"_\" + fight_style + \".js\")) {\n already_loaded = true;\n }\n }\n if ( ! already_loaded) {\n getScript(\"js/crucible/crucible_\" + spec + \"_\" + fight_style + \".js\");\n }\n\n // hide/show charts\n var container = document.getElementsByClassName(\"container-relics\");\n for (var i = container.length - 1; i >= 0; i--) {\n if (container[i].id === \"crucible_\" + spec + \"_\" + fight_style) {\n container[i].style.display = 'block';\n active_spec = spec;\n } else {\n container[i].style.display = 'none';\n }\n }\n\n // hide/show TC-resource and Discord of the spec\n var tc_boxes = document.getElementsByClassName(\"tc-box\");\n for (var i = tc_boxes.length - 1; i >= 0; i--) {\n if (tc_boxes[i].id === \"tc_\" + spec) {\n tc_boxes[i].style.display = 'block';\n } else {\n tc_boxes[i].style.display = 'none';\n }\n }\n\n ga('send', 'event', 'relics', fight_style, active_spec);\n\n if (language != \"EN\") {\n //console.log(\"Starting translation process.\");\n setTimeout(translate_charts, 200);\n }\n}",
"function drawCategoryChart() {\n\t\n\tvar entertainmentnum = 0\n\tvar productivitynum = 0\n\tvar othernum = 0\n\tvar shoppingnum = 0\n\tvar data\n\tif(!useDateRangeSwitch)\n\t\tdata = listSiteData(globsiteData)\n\telse \n\t\tdata = listSiteData(dateRangeData)\n\n\tfor (i=1; i<data.length; i++){\n\t\ttemp = String(data[i][0]).trim()\n\t\tif(globCategoriesHostname.includes(temp)){\n\t\t\tif(globCategoriesCategory[globCategoriesHostname.indexOf(temp)].trim() === \"Entertainment\")\n\t\t\t\tentertainmentnum += data[i][1]\n\t\t\telse if(globCategoriesCategory[globCategoriesHostname.indexOf(temp)].trim() === \"Productivity\")\n\t\t\t\tproductivitynum+=data[i][1]\n\t\t\telse if(globCategoriesCategory[globCategoriesHostname.indexOf(temp)].trim() === \"Shopping\")\n\t\t\t\tshoppingnum+=data[i][1]\n\t\t}\n\t\telse \n\t\t\tothernum+=data[i][1]\n\t}\n\tvar catData = [\n\t\t['Task', 'Hours per Day'],\n\t\t['Entertainment', entertainmentnum],\n\t\t['Productivity', productivitynum],\n\t\t['Shopping', shoppingnum],\n\t\t['Other', othernum],\n\t];\n\n\tcatData.sort(function(a,b){\n\t\treturn b[1]-a[1] //high to low\n\t});\n\t\n\tvar processeddata = google.visualization.arrayToDataTable(catData);\n\n\tvar options = {\n\t title: 'Daily Screentime By Category'\n\t};\n\n\t//piechart\n\tvar piechart_options = {\n\t\ttitle: 'Pie Chart: My Daily Screentime'\n\t\t};\n\tvar piechart = new google.visualization.PieChart(document.getElementById('piechart'));\n\tpiechart.draw(processeddata, piechart_options);\n\n\t//barchart\n\tvar barchart_options = {\n\t\ttitle: 'Bar Chart: My Daily Screentime'\n\t}\n\tvar barchart = new google.visualization.BarChart(document.getElementById('barchart'));\n\tbarchart.draw(processeddata, barchart_options);\n}",
"_getTimeRangeInReverse(startTime, endTime) {\n const slices = this.streamBuffer.getTimeslices({start: startTime, end: endTime}).reverse();\n return {\n streams: slices.map(timeslice => timeslice.streams).filter(Boolean),\n links: slices.map(timeslice => timeslice.links).filter(Boolean)\n };\n }",
"function create(data) {\n console.log('one pie coming up... here is data: ');\n console.log(data);\n data = data.slice(0,12);\n\n /* ------- PIE SLICES -------*/\n var slice = svg.select(\".slices\").selectAll(\"path.slice\")\n .data(pie(data))\n\n slice.enter()\n .insert(\"path\")\n .style(\"fill\", function(d) {\n if(d.data.sentiment.score) {\n console.log('coloring slice');\n return color(d.data.sentiment.score);\n }\n else {\n return color(0);\n }\n })\n .attr(\"class\", \"slice\");\n\n slice\n .transition().duration(1000)\n .attrTween(\"d\", function(d) {\n this._current = this._current || d;\n var interpolate = d3.interpolate(this._current, d);\n this._current = interpolate(0);\n return function(t) {\n return arc(interpolate(t));\n };\n })\n\n slice.exit()\n .remove();\n\n /* ------- TEXT LABELS -------*/\n\n var text = svg.select(\".labels\").selectAll(\"text\")\n .data(pie(data))\n\n text.enter()\n .append(\"text\")\n .attr(\"dy\", \".35em\")\n .text(function(d) {\n return d.data.text;\n });\n\n function midAngle(d){\n return d.startAngle + (d.endAngle - d.startAngle)/2;\n }\n\n text.transition().duration(1000)\n .attrTween(\"transform\", function(d) {\n this._current = this._current || d;\n var interpolate = d3.interpolate(this._current, d);\n this._current = interpolate(0);\n return function(t) {\n var d2 = interpolate(t);\n var pos = outerArc.centroid(d2);\n pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1);\n return \"translate(\"+ pos +\")\";\n };\n })\n .styleTween(\"text-anchor\", function(d){\n this._current = this._current || d;\n var interpolate = d3.interpolate(this._current, d);\n this._current = interpolate(0);\n return function(t) {\n var d2 = interpolate(t);\n return midAngle(d2) < Math.PI ? \"start\":\"end\";\n };\n });\n\n text.exit()\n .remove();\n\n /* ------- SLICE TO TEXT POLYLINES -------*/\n\n var polyline = svg.select(\".lines\").selectAll(\"polyline\")\n .data(pie(data))\n\n polyline.enter()\n .append(\"polyline\");\n\n polyline.transition().duration(1000)\n .attrTween(\"points\", function(d){\n this._current = this._current || d;\n var interpolate = d3.interpolate(this._current, d);\n this._current = interpolate(0);\n return function(t) {\n var d2 = interpolate(t);\n var pos = outerArc.centroid(d2);\n pos[0] = radius * 0.95 * (midAngle(d2) < Math.PI ? 1 : -1);\n return [arc.centroid(d2), outerArc.centroid(d2), pos];\n };\n });\n\n polyline.exit()\n .remove();\n }",
"function createTestContainer(tick, length, subclips)\n{\n return {\n \"_id\": \"[container]\",\n \"asset_id\": \"[container]\",\n \"project_id\": \"test\",\n \"trim\": {\"left\": 0, \"right\": 0},\n \"tick\": tick,\n \"length\": length,\n \"track\": 0,\n \"subclips\": subclips\n };\n}",
"async function get_all_divvy_stations_log(timeRange, newTimeRangeSelection) {\n var start_datetime_var = new Date();\n var scrollVal;\n\n\n all_docks_found = [];\n\n if(timeRange.includes(PAST_HOUR)){\n if(newTimeRangeSelection){\n isBeginningOfTimeRangeSet = false;\n\n }\n\n if(!isBeginningOfTimeRangeSet){\n\n all_docks_found = [];\n\n isBeginningOfTimeRangeSet = true;\n\n var start_datetime_var = new Date();\n var start_datetime_var_2 = new Date();\n var targetTime = new Date(start_datetime_var);\n var tzDifference = targetTime.getTimezoneOffset();\n\n //convert the offset to milliseconds, add to targetTime, and make a new Date\n start_datetime_var = new Date(targetTime.getTime() - tzDifference * 60 * 1000);\n start_datetime_var_2 = new Date(targetTime.getTime() - tzDifference * 60 * 1000);\n go_back_in_time_var = start_datetime_var.getHours() - 1;\n\n start_datetime_var_2.setHours(go_back_in_time_var);\n time_stamp_var_2 = start_datetime_var_2.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n\n time_stamp_var_1 = start_datetime_var.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n time_stamp_var_4 = new Date(new Date(time_stamp_var_2).getTime() - new Date(time_stamp_var_2).getTimezoneOffset() * 60 * 1000);\n\n var go_forward_in_time_var_2 = time_stamp_var_4 .getMinutes() + 2 ;\n time_stamp_var_4 .setMinutes(go_forward_in_time_var_2);\n\n time_stamp_var_3 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n time_stamp_var_1 = start_datetime_var.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n\n\n sizeVal = 1000000;\n scrollVal='1s';\n }\n\n }\n\n\n\n else if(timeRange == PAST_24_HOURS ){\n\n if(newTimeRangeSelection){\n isBeginningOfTimeRangeSet = false;\n }\n\n\n if(! isBeginningOfTimeRangeSet){\n\n isBeginningOfTimeRangeSet = true;\n var start_datetime_var = new Date();\n var start_datetime_var_2 = new Date();\n var targetTime = new Date(start_datetime_var);\n var tzDifference = targetTime.getTimezoneOffset();\n\n //convert the offset to milliseconds, add to targetTime, and make a new Date\n start_datetime_var = new Date(targetTime.getTime() - tzDifference * 60 * 1000);\n start_datetime_var_2 = new Date(targetTime.getTime() - tzDifference * 60 * 1000);\n\n go_back_in_time_var = start_datetime_var.getHours() - 24;\n\n start_datetime_var_2.setHours(go_back_in_time_var);\n time_stamp_var_2 = start_datetime_var_2.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n time_stamp_var_4 = new Date(new Date(time_stamp_var_2).getTime() - new Date(time_stamp_var_2).getTimezoneOffset() * 60 * 1000);\n\n var go_forward_in_time_var_2 = time_stamp_var_4 .getHours() + 1 ;\n time_stamp_var_4 .setHours(go_forward_in_time_var_2);\n\n time_stamp_var_3 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n time_stamp_var_1 = start_datetime_var.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n\n // Recalculate lower bound for the time-window\n // Take 2 minutes sample on the top of every hour for the past 24 hours\n // This is NOT the best we could do..\n // We can calculate the average for every hour and use that \n // as the average sample for the heatmap to display \n time_stamp_var_4 = new Date(new Date(time_stamp_var_3).getTime() - new Date(time_stamp_var_3).getTimezoneOffset() * 60 * 1000);\n\n diffMinutes = time_stamp_var_4 .getMinutes() - 2 ;\n time_stamp_var_4 .setMinutes(diffMinutes);\n\n time_stamp_var_2 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n \n\n sizeVal = 300;\n scrollsize = 10000;\n scrollVal='15s';\n }\n }\n\n\n\n else if(timeRange.includes(PAST_7_DAYS)){\n\n if(newTimeRangeSelection){ \n isBeginningOfTimeRangeSet = false;\n \n }\n\n\n if(! isBeginningOfTimeRangeSet){\n\n isBeginningOfTimeRangeSet = true;\n var start_datetime_var = new Date();\n var start_datetime_var_2 = new Date();\n var targetTime = new Date(start_datetime_var);\n var tzDifference = targetTime.getTimezoneOffset();\n\n\n\n //convert the offset to milliseconds, add to targetTime, and make a new Date\n start_datetime_var = new Date(targetTime.getTime() - tzDifference * 60 * 1000);\n start_datetime_var_2 = new Date(targetTime.getTime() - tzDifference * 60 * 1000);\n\n go_back_in_time_var = start_datetime_var.getHours() - 168;\n\n start_datetime_var_2.setHours(go_back_in_time_var);\n time_stamp_var_2 = start_datetime_var_2.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n\n time_stamp_var_1 = start_datetime_var.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n time_stamp_var_4 = new Date(new Date(time_stamp_var_2).getTime() - new Date(time_stamp_var_2).getTimezoneOffset() * 60 * 1000);\n\n var go_forward_in_time_var_2 = time_stamp_var_4 .getHours() + 24 ;\n time_stamp_var_4 .setHours(go_forward_in_time_var_2);\n\n time_stamp_var_3 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n time_stamp_var_1 = start_datetime_var.toISOString().slice(0,-5).replace('Z', ' ').replace('T', ' ');\n\n\n // Recalculate lower bound fo the time-window\n // Take 2 minutes sample on the top of every hour of every day for the past 7 days\n // This is NOT the best we could do...\n // We can calculate the average for every hour and use that \n // as the average sample for the heatmap to display \n time_stamp_var_4 = new Date(new Date(time_stamp_var_3).getTime() - new Date(time_stamp_var_3).getTimezoneOffset() * 60 * 1000);\n\n diffMinutes = time_stamp_var_4 .getMinutes() - 2 ;\n time_stamp_var_4 .setMinutes(diffMinutes);\n\n time_stamp_var_2 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n sizeVal = 100000;\n scrollVal='15s';\n }\n }\n\n\n\n \n results = await esClient.search({\n index: 'divvy_station_logs',\n type: 'log',\n scroll: scrollVal,\n // search_type : 'scan',\n size: 1000000,\n from: 0,\n body: {\n\n query: {\n \"bool\":{\n \"filter\":\n {\n \"bool\" : {\n \"must\" :[\n {\n \"range\" : {\n \"lastCommunicationTime.keyword\" : {\n \"gte\": time_stamp_var_2,\n \"lt\": time_stamp_var_3\n }\n }\n }\n ]\n }\n }\n }\n }, \"sort\": [\n { \"lastCommunicationTime.keyword\": { \"order\": \"desc\" }},\n\n ]\n }\n });\n\n\n \n // collect all the records\n\n // console.log('results.hits.total = ', results.hits.total);\n\n results.hits.hits.forEach(function (hit) {\n allRecords.push(hit);\n var docks = {\n \"availableDocks\": hit._source.availableDocks,\n \"latitude\": hit._source.latitude,\n \"longitude\": hit._source.longitude\n };\n all_docks_found.push(docks);\n });\n\n\n \n // Adjust lower bound and upper bound for the time-window\n // for data collection for the next round from ElasticSearch\n\n if(timeRange.includes(PAST_HOUR)){\n time_stamp_var_2 = time_stamp_var_3;\n\n time_stamp_var_4 = new Date(new Date(time_stamp_var_2).getTime() - new Date(time_stamp_var_2).getTimezoneOffset() * 60 * 1000);\n\n diffMinutes = time_stamp_var_4 .getMinutes() + 2 ;\n time_stamp_var_4 .setMinutes(diffMinutes);\n\n time_stamp_var_3 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n }\n\n\n else if(timeRange == PAST_24_HOURS){\n\n time_stamp_var_2 = time_stamp_var_3;\n\n time_stamp_var_4 = new Date(new Date(time_stamp_var_2).getTime() - new Date(time_stamp_var_2).getTimezoneOffset() * 60 * 1000);\n\n go_forward_in_time_var = time_stamp_var_4 .getHours() + 1 ;\n time_stamp_var_4 .setHours(go_forward_in_time_var);\n\n time_stamp_var_3 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n // Recalculate lower bound fo the time-window\n // Take 2 minutes sample on the top of every hour for the past 24 hours\n // This is NOT the best we could do..\n // We can calculate the average for every hour and use that \n // as the average sample for the heatmap to display \n time_stamp_var_4 = new Date(new Date(time_stamp_var_3).getTime() - new Date(time_stamp_var_3).getTimezoneOffset() * 60 * 1000);\n\n diffMinutes = time_stamp_var_4 .getMinutes() - 2 ;\n time_stamp_var_4 .setMinutes(diffMinutes);\n\n time_stamp_var_2 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n\n }\n\n\n else if(timeRange == PAST_7_DAYS){\n\n\n time_stamp_var_2 = time_stamp_var_3;\n\n time_stamp_var_4 = new Date(new Date(time_stamp_var_2).getTime() - new Date(time_stamp_var_2).getTimezoneOffset() * 60 * 1000);\n\n go_forward_in_time_var = time_stamp_var_4 .getHours() + 24 ;\n time_stamp_var_4 .setHours(go_forward_in_time_var);\n\n time_stamp_var_3 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n\n\n\n // Recalculate lower bound fo the time-window\n // Take 2 minutes sample on the top of every hour of every day for the past 7 days\n // This is NOT the best we could do...\n // We can calculate the average for every hour and use that \n // as the average sample for the heatmap to display \n time_stamp_var_4 = new Date(new Date(time_stamp_var_3).getTime() - new Date(time_stamp_var_3).getTimezoneOffset() * 60 * 1000);\n\n diffMinutes = time_stamp_var_4 .getMinutes() - 2 ;\n time_stamp_var_4 .setMinutes(diffMinutes);\n\n time_stamp_var_2 = time_stamp_var_4 .toISOString().replace('Z', '').replace('T', ' ').slice(0, -4);\n \n\n }\n \n\n\n}",
"function yearlyTimeChart (result) {\n // Get chart data\n function getMessagesByMonth (data, channelFilter) {\n const channels = {}\n\n // Loops through the data to build the `channels` object\n data.forEach(item => {\n const channel = moment(item.MessageTime).format('YYYY-MM'); const id = item.MessageID\n\n // Makes sure there is no filter, or channel matches filter, before proceeding\n if (!channelFilter || channelFilter === channel) {\n if (!channels[channel]) {\n // Adds a property to the `channels` object. Its value is an array including one item: the MessageID.\n channels[channel] = [id]\n } else if (!channels[channel].includes(id)) {\n // Add a new MessageID to the array for this channel\n channels[channel].push(id)\n }\n }\n })\n\n // Replaces the property's value with a number indicating the number of unique conversations\n for (var channel in channels) {\n // Uses `for...in` to loop through object properties\n channels[channel] = channels[channel].length\n }\n\n return channels\n }\n\n // Push 0s where data is missing\n var timeArray = getMessagesByMonth(result)\n\n const timeLabels = []\n const timeData = []\n\n const date = moment(thisYear + '-01')\n const endDate = moment(thisYear + '-12')\n do {\n const dateStr = date.format('YYYY-MM')\n timeLabels.push(dateStr)\n\n if (timeArray.hasOwnProperty(dateStr)) { timeData.push(timeArray[dateStr]) } else { timeData.push(0) }\n\n date.add(1, 'month')\n } while (date.isBefore(endDate))\n\n // Set data and labels\n var labels = timeLabels\n var data = timeData\n\n document.getElementById('yearlyTotalTime').innerHTML = ''\n\n // Create chart\n var ctx = document.getElementById('yearlyTimeChart').getContext('2d')\n var chart = new Chart(ctx, {\n type: 'line',\n data: {\n labels: labels,\n datasets: [{\n label: '# of Messages',\n data: data\n }]\n },\n options: {\n title: {\n display: true,\n text: 'Messages Received'\n },\n legend: {\n display: false\n },\n scales: {\n xAxes: [{\n type: 'time',\n time: {\n displayFormats: {\n month: 'MMM'\n },\n unit: 'month',\n min: thisYear + '-01-01T00:00',\n max: thisYear + '-12-31T23:39'\n }\n }],\n yAxes: [{\n gridLines: {\n display: false\n },\n ticks: {\n beginAtZero: true\n }\n }]\n },\n plugins: {\n colorschemes: {\n scheme: chartColorScheme\n },\n datalabels: {\n display: function (context) {\n return context.dataset.data[context.dataIndex] !== 0 // or >= 1 or ...\n }\n }\n }\n }\n })\n}",
"function BtcMultiLinegraph() {\n var prct_btc;\n d3.json(\"/percentbtc\").then(function(data){\n prct_dji = data;\n var priceClose = [];\n var prctClose = [];\n var prctDates = [];\n for (var i = 0; i < data.length; i++) {\n priceClose.push(data[i].close_dji);\n prctClose.push(data[i].close);\n prctDates.push(data[i].datetime);\n }\n var trace1 = {\n x: prctDates,\n y: prctClose,\n name: 'Percent Change',\n line: {\n color: \"rgb(255, 77, 77)\",\n width: 2\n },\n type: 'scatter'\n };\n \n var trace2 = {\n x: prctDates,\n y: priceClose,\n name: 'Closing prices',\n yaxis: 'y2',\n line: {\n color: \"rgb(1, 87, 155)\",\n width: 2\n },\n type: 'scatter'\n };\n \n var data = [trace1, trace2];\n \n var layout = {\n title: 'Bitcoin vs Percent Change in Closing Prices',\n xaxis: {\n rangeselector: selectorOptions,\n },\n yaxis: {title: 'Percent Change (%)', tickformat:',%',range:[-.50,.50]},\n yaxis2: {\n title: 'Value per day ($)',\n titlefont: {color: 'rgb(148, 103, 189)'},\n tickfont: {color: 'rgb(148, 103, 189)'},\n overlaying: 'y',\n side: 'right'\n }\n };\n\n Plotly.newPlot('plot', data, layout);\n // console.log(priceClose);\n // console.log(prctClose);\n // console.log(prctDates);\n });\n}",
"function setUpPageLayout(isTimeseries, data=null) {\n // Variables to help calculate the height of the divs\n var windowHeight = d3.select(\"html\")[0][0].clientHeight;\n var windowHeightOffset = 210;\n var divMargin = 10;\n var scrollBarWidth = 10;\n\n // If the CSV file contains timeseries data, create 2 independently\n // scrolling divs: one on the left for the categorized timelines for the\n // user to select from and one on the right to contain the SVG chain\n if (isTimeseries) {\n // Create an outer container\n var outerContainer = d3.select(\"body\").append(\"div\")\n .attr(\"id\", \"outerContainer\");\n \n // Capture the windowWidth to help calculate the width of the divs\n var outerContainerWidth = outerContainer[0][0].clientWidth -\n divMargin*4 - scrollBarWidth*2;\n\n // Create the container for everything on the left side of\n // the page. Append the instructions and a br to separate\n // the instructions from the leftContainer\n var leftDiv = outerContainer.append(\"div\")\n .style(\"width\", (outerContainerWidth/3) + \"px\")\n .style(\"overflow\", \"hidden\");\n var instructions = leftDiv.append(\"h4\")\n .text(\"Click on the chart with the data you wish to explore:\");\n var br = leftDiv.append(\"br\");\n\n // Append a div to contain all the searching-related elements\n // Append the instructions, input box, and button\n var searchDiv = leftDiv.append(\"div\")\n .style(\"float\", \"left\")\n .style(\"overflow\", \"hidden\");\n searchDiv.append(\"p\")\n .style(\"display\", \"inline-block\")\n .style(\"margin\", \"0px\")\n .text(\"Search for a timeline:\");\n searchDiv.append(\"input\")\n .attr(\"id\", \"searchTerm\")\n .attr(\"type\", \"text\")\n .style(\"margin\", \"0px\");\n searchDiv.append(\"button\")\n .style(\"margin\", \"0px\")\n .text(\"Search\")\n .on(\"click\", function() { searchForTimeline(data); });\n\n // The leftContainer will be shorter than the mainContainer so that the\n // bottoms of their divs line up\n var leftContainerHeightOffset = instructions[0][0].clientHeight +\n br[0][0].clientHeight + searchDiv[0][0].clientHeight + divMargin*6;\n\n // Append the leftContainer, where all the timelines will be appended\n leftDiv.append(\"div\")\n .attr(\"id\", \"leftContainer\")\n .style(\"width\", \"98%\")\n .style(\"height\",\n (windowHeight-windowHeightOffset-leftContainerHeightOffset) + \"px\")\n .style(\"overflow-y\", \"scroll\");\n\n // Append the mainContainer, where the SVG chain will be contained\n outerContainer.append(\"div\")\n .attr(\"id\", \"mainContainer\")\n .style(\"width\", (outerContainerWidth*2/3) + \"px\")\n .style(\"height\", (windowHeight-windowHeightOffset) + \"px\")\n .style(\"overflow\", \"scroll\")\n .append(\"div\").attr(\"id\", \"mainInnerContainer\");\n\n // Set the supported GRAPH_TYPES to include BARCHART_OVERVIEW and\n // TIMELINE\n GRAPH_TYPES = Object.freeze({ SCATTERPLOT: 0, HEATMAP: 1,\n BARCHART: 2, BARCHART_OVERVIEW: 3, TIMELINE: 4 });\n }\n // For non-timeseries data, only a scrolling div for the SVG chain is needed\n else {\n\n // For non-timeseries data, only the mainContainer and\n // mainInnerContainer are necessary\n d3.select(\"body\").append(\"div\")\n .attr(\"id\", \"mainContainer\")\n .style(\"width\", d3.select(\"html\")[0][0].clientWidth - divMargin*2 -\n scrollBarWidth)\n .style(\"height\", (windowHeight-windowHeightOffset) + \"px\")\n .style(\"overflow-y\", \"scroll\")\n .append(\"div\").attr(\"id\", \"mainInnerContainer\");\n\n // Support only graphs types that do not rely on timeseries data (i.e.\n // exlude BARCHART_OVERVIEW and TIMELINE)\n GRAPH_TYPES = Object.freeze({ SCATTERPLOT: 0, HEATMAP: 1,\n BARCHART: 2 });\n }\n \n // Set the default graph type to SCATTERPLOT\n defaultGraph = GRAPH_TYPES.SCATTERPLOT;\n}",
"function multipleLineChart(data) {\n\n var width = 200\n\n var g = sidebar_svg.append(\"g\")\n .attr(\"class\",\"lineChart\")\n .attr(\"transform\", \"translate(30, 0)\")\n\n g.append('g')\n .attr('class', 'lines')\n\n g.append(\"g\")\n .attr(\"class\", \"x_axis\")\n\n g.append(\"g\")\n .attr(\"class\", \"y_axis\")\n\n g.append('g')\n .attr('class', 'gLegend')\n .attr(\"transform\", \"translate(\" + 0 + \",\" + 10 + \")\")\n\n var xScale = d3.scaleBand()\n .domain(data.map(d=>d.time))\n .range([0, width])\n .padding(0.1)\n\n var yScale = d3.scaleLinear()\n .domain([0, 5028])\n .range([height+20, 20]);\n\n var category = ['female', 'male']\n var color = d3.scaleOrdinal()\n .domain(category)\n .range([\"white\", KIRON_COLOR])\n\n // CREATE AXES // \n // render axis first before lines so that lines will overlay the horizontal ticks\n var ticks = xScale.domain().filter((d,i)=>{ return !(i%2) } ) // only show tick labels for the first bidding exercise of the year\n var xAxis = d3.axisBottom(xScale)\n .tickSizeOuter(0)\n .tickSizeInner(-height)\n .tickValues(ticks)\n\n var yAxis = d3.axisLeft(yScale)\n .ticks(10, \"s\")\n .tickSize(-width)\n\n g.select(\".x_axis\")\n .attr(\"transform\", `translate(0, ${height+20})`) \n .call(xAxis)\n .call(g => {\n g.selectAll(\"text\")\n .style(\"text-anchor\", \"middle\")\n .attr(\"y\", axisPad)\n .attr('fill', '#A9A9A9')\n\n g.selectAll(\"line\")\n .attr('stroke', '#A9A9A9')\n .attr('stroke-width', 0.7) // make horizontal tick thinner and lighter so that line paths can stand out\n .attr('opacity', 0.7)\n\n g.select(\".domain\")\n .attr('stroke', '#A9A9A9')\n }) \n\n g.select(\".y_axis\")\n .call(yAxis)\n .call(g => {\n g.selectAll(\"text\")\n .style(\"text-anchor\", \"middle\")\n .attr(\"x\", -axisPad*2)\n .attr('fill', '#A9A9A9')\n\n g.selectAll(\"line\")\n .attr('stroke', '#A9A9A9')\n .attr('stroke-width', 0.7) // make horizontal tick thinner and lighter so that line paths can stand out\n .attr('opacity', 0.3)\n\n g.select(\".domain\").remove()\n })\n \n // APPEND MULTIPLE LINES //\n var line = d3.line()\n .x(d => xScale(d.time) + xScale.bandwidth() / 2)\n .y(d => yScale(+d.rollup))\n\n var res_nested = d3.nest() // necessary to nest data so that keys represent each category\n .key(d=>d.gender)\n .entries(data)\n\n var glines = g.select('.lines').selectAll('.line-group')\n .data(res_nested)\n\n glines.enter().append('g')\n .attr('class', 'line-group') \n .append('path')\n .attr('class', 'line') \n .attr('d', d => line(d.values))\n .style('stroke', (d, i) => color(i))\n .style('fill', 'none')\n .style('opacity', lineOpacity)\n .style('stroke-width', lineStroke)\n\n glines.select('path').attr('d', d => line(d.values)) // update\n\n glines.exit().remove()\n\n // CREATE LEGEND // \n var legend = g.select('.gLegend').selectAll('.legend')\n .data(category)\n .enter().append('g')\n .attr(\"class\", \"legend\")\n .attr(\"transform\", function (d, i) {return \"translate(\" + i * 80 + \",\" + i * 0 + \")\"})\n\n legend.append(\"circle\")\n .attr(\"class\", \"legend-node\")\n .attr(\"cx\", 0)\n .attr(\"cy\", 0)\n .attr(\"r\", R)\n .style(\"fill\", d=>color(d))\n\n legend.append(\"text\")\n .attr(\"class\", \"legend-text\")\n .attr(\"x\", R*2)\n .attr(\"y\", R/2)\n .style(\"fill\", \"#A9A9A9\")\n .style(\"font-size\", 12)\n .text(d=>d)\n\n }",
"function sliceMovementStop(x,y)\n{\n endX = x;\n endY = y;\n var startSlice = getSliceRange(startX,startY).slice;\n var endSlice = getSliceRange(endX,endY).slice;\n var movDir;\n var degreeAdd;\n var sliceString;\n var sliceArr;\n var results = {};\n/*\n window.alert(\"Start Slice \" + startSlice);\n window.alert(\"End Slice \" + endSlice);\n\n window.alert(\"start X \" + startX);\n window.alert(\"start Y \" + startY);\n window.alert(\"end X \" + endX); \n window.alert(\"end Y \" + endY);\n*/ \n if(startSlice === endSlice){\n if(endY > startY){//moved up\n movDir = -1;//up towards upper left corner\n degreeAdd = -3;\n }\n else if((endX < startX) && (endY > 0)){//top of cube move\n movDir = -1;//up towards upper left corner\n degreeAdd = -3;\n }\n else if((endX > startX) && (endY > 0)){//top of cube move\n movDir = 1;//down towards bottom right corner\n degreeAdd = 3;\n }\n else if(endY < startY){//moved down\n movDir = 1;//down towards bottom right corner\n degreeAdd = 3;\n }\n sliceString = endSlice; \n }\n //slices compositions\n else{\n sliceString = getCrossSlice(startSlice,endSlice);\n //window.alert(\"In here \" + sliceString);\n if((sliceString === \"z_slice1\") || (sliceString === \"z_slice2\") || (sliceString === \"z_slice3\")){\n if(startSlice === \"x_slice1\"){\n movDir = -1;//down towards bottom right corner\n degreeAdd = -3; \n }\n else{\n movDir = 1;//down towards bottom right corner\n degreeAdd = 3;\n }\n }\n else if((sliceString === \"y_slice1\") || (sliceString === \"y_slice2\") || (sliceString === \"y_slice3\")){\n //window.alert(\"In here\");\n if((startSlice === \"x_slice1\") || (startSlice === \"z_slice3\")){\n movDir = 1;//spin towards right\n degreeAdd = 3; \n }\n else{\n movDir = -1;//spin towards left\n degreeAdd = -3;\n } \n }\n }//end else slices compositions\n\n sliceArr = sliceArrayIndexs(sliceString);//in slices.js\n\n results.movDir = movDir;\n results.degreeAdd = degreeAdd;\n results.sliceString = sliceString;\n results.sliceArr = sliceArr;\n\n return results;\n}",
"function makeGraphs(data) {\n \n var ndx = crossfilter(data);\n \n has_website(ndx);\n pieChart(ndx);\n barChart(ndx);\n table(ndx, 10);\n \n dc.renderAll();\n $(\".dc-select-menu\").addClass(\"custom-select\");\n\n}",
"function constructDataFrame(times, timesNs, lines, uids, labels, reverse, refId) {\n var dataFrame = {\n refId: refId,\n fields: [{\n name: 'ts',\n type: _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"FieldType\"].time,\n config: {\n displayName: 'Time'\n },\n values: times\n }, // Time\n {\n name: 'line',\n type: _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"FieldType\"].string,\n config: {},\n values: lines,\n labels: labels\n }, // Line - needs to be the first field with string type\n {\n name: 'id',\n type: _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"FieldType\"].string,\n config: {},\n values: uids\n }, {\n name: 'tsNs',\n type: _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"FieldType\"].time,\n config: {\n displayName: 'Time ns'\n },\n values: timesNs\n } // Time\n ],\n length: times.length\n };\n\n if (reverse) {\n var mutableDataFrame = new _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"MutableDataFrame\"](dataFrame);\n mutableDataFrame.reverse();\n return mutableDataFrame;\n }\n\n return dataFrame;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a change Document has not been provided, prompt for one. This will use the change document Validator. | async changeDocumentStep(stepContext) {
const changeDocument = stepContext.options;
if(stepContext.parent.result){
// changeDocument.intent = stepContext.parent.intent;
if (!changeDocument.number) {
return await stepContext.beginDialog(CD_VALIDATOR_DIALOG, { changeDocument: changeDocument.number });
}
return await stepContext.next(changeDocument.number);
}
return await stepContext.next();
} | [
"get newDoc() {\n return (\n this._doc || (this._doc = this.changes.apply(this.startState.doc))\n )\n }",
"function LoadDocumentBtnClicked() \n{\n\n //Initialize Viwer\n\tOnInitializeViwer();\n\t\n //get the document provided by the user\n documentId = document.getElementById(\"DocIdTB\").value;\n\n //load the document\n Autodesk.Viewing.Document.load(documentId, Autodesk.Viewing.Private.getAuthObject(), onSuccessDocumentLoadCB, onErrorDocumentLoadCB);\n //update the command line text.\n UpdateCommandLine(\"Loading document : \" + documentId);\n}",
"function BADocument() { }",
"function validate()\n{\n\tvar docF = document.form1;\n\tif(docF.executive.value==\"\")\n\t{\n\t\talert('Please select an executive to assign');\n\t\tdocF.executive.focus();\n\t\treturn false;\n\t}\n}",
"async function confirmNewDoc() {\n var title = $(\"#new-doc-input\").val().trim();\n if (!title){\n $(\"#new-doc-input\").trigger(\"focus\");\n return;\n }\n\n var targetFID = activeFolderID || \"f-uncat\";\n\n $(\"#confirmNewDocButton\").addClass(\"loading\");\n $(\"#newDocButton\").addClass(\"loading\");\n $(\"#new-doc-input\").trigger(\"blur\");\n hidePanels();\n\n // if the target folder is inbox, make sure it exists.\n if (targetFID === \"f-uncat\") { \n var inboxFolder = await getFolderFromCatalog(\"f-uncat\");\n if (isEmpty(inboxFolder)) {\n await newFolder(\"\",\"Inbox\",\"f-uncat\");\n }\n }\n\n await newDoc(targetFID,title);\n\n $(\"#confirmNewDocButton\").removeClass(\"loading\");\n $(\"#newDocButton\").removeClass(\"loading\");\n $(\"#new-doc-input\").val(\"\");\n\n quill.focus();\n\n return true;\n}",
"function saveDocument() {\n if (current.id) {\n console.log(\"saveDocument(old) started\");\n var isUpdateSupported = current.resources.self && $.inArray('PUT', current.resources.self.allowed) != -1;\n if (!isUpdateSupported) {\n alert(\"You are not allowed to update this document\");\n return;\n }\n showMessage(\"Updating existing document ...\");\n current.subject = $(\"#document-subject\").val();\n current.content.text = $(\"#document-text\").val();\n current.update().execute(function(response) {\n console.log(\"Update response = \" + JSON.stringify(response));\n loadDocuments();\n });\n }\n else {\n console.log(\"saveDocument(new) started\");\n showMessage(\"Saving new document ...\");\n current.subject = $(\"#new-document-subject\").val();\n current.html = $(\"#new-document-html\").val();\n user.privateDocuments.create(current).execute(function(response) {\n console.log(\"saveDocument(new) response = \" + JSON.stringify(response));\n loadDocuments();\n });\n }\n}",
"prompter(cz, commit) {\n // console.log('\\nLine 1 will be cropped at 100 characters. All other lines will be wrapped after 100 characters.\\n');\n console.log(\n '\\n1่ก็ฎใฏ100ๆๅญใงๅใๅใใใ่ถ
้ๅใฏๆฌก่กไปฅ้ใซ่จ่ผใใใพใใ\\n'\n );\n\n // Let's ask some questions of the user\n // so that we can populate our commit\n // template.\n //\n // See inquirer.js docs for specifics.\n // You can also opt to use another input\n // collection library if you prefer.\n cz.prompt([\n {\n type: 'list',\n name: 'type',\n message: 'ใณใใใใใๅคๆดใฟใคใใ้ธๆ:',\n choices: choicesPrefix\n },\n {\n type: 'input',\n name: 'scope',\n message:\n 'ๅคๆดๅ
ๅฎนใฎในใณใผใ(ไพ:ใณใณใใผใใณใใใใกใคใซๅ):๏ผenterใงในใญใใ๏ผ\\n'\n },\n {\n type: 'list',\n name: 'emoji',\n message: 'ใณใใใๅ
ๅฎนใซๅใemojiใ้ธๆ:',\n choices: choicesEmojiPrefix\n },\n {\n type: 'input',\n name: 'subject',\n message: 'ๅคๆดๅ
ๅฎนใ่ฆ็ดใใๆฌ่ณช็่ชฌๆ:\\n'\n },\n {\n type: 'input',\n name: 'body',\n message: 'ๅคๆดๅ
ๅฎนใฎ่ฉณ็ดฐ:๏ผenterใงในใญใใ๏ผ\\n'\n },\n {\n type: 'confirm',\n name: 'isBreaking',\n message: '็ ดๅฃ็ๅคๆดใๅซใฟใพใใ๏ผ',\n default: false\n },\n {\n type: 'input',\n name: 'breaking',\n message: '็ ดๅฃ็ๅคๆดใซใคใใฆใฎ่จ่ฟฐ:\\n',\n when(answers) {\n return answers.isBreaking;\n }\n },\n {\n type: 'confirm',\n name: 'isIssueAffected',\n message: 'issueใซ้ข้ฃใใๅคๆดใงใใ๏ผ',\n default: false\n },\n {\n type: 'input',\n name: 'issues',\n message: '้ข้ฃissueใ่ฟฝ่จ (ไพ:\"fix #123\", \"re #123\"):\\n',\n when(answers) {\n return answers.isIssueAffected;\n }\n }\n ]).then(answers => {\n const maxLineWidth = 100;\n\n const wrapOptions = {\n trim: true,\n newline: '\\n',\n indent: '',\n width: maxLineWidth\n };\n\n // parentheses are only needed when a scope is present\n let scope = answers.scope.trim();\n scope = scope ? `(${answers.scope.trim()})` : '';\n\n // Hard limit this line\n const head = `${answers.type}${scope}: :${\n answers.emoji\n }: ${answers.subject.trim()}`.slice(0, maxLineWidth);\n\n // Wrap these lines at 100 characters\n const body = wrap(answers.body, wrapOptions);\n\n // Apply breaking change prefix, removing it if already present\n let breaking = answers.breaking ? answers.breaking.trim() : '';\n breaking = breaking\n ? `BREAKING CHANGE: ${breaking.replace(/^BREAKING CHANGE: /, '')}`\n : '';\n breaking = wrap(breaking, wrapOptions);\n\n const issues = answers.issues ? wrap(answers.issues, wrapOptions) : '';\n\n const footer = filter([breaking, issues]).join('\\n\\n');\n\n commit(`${head}\\n\\n${body}\\n\\n${footer}`);\n console.log(`\n======================\n${head}\\n\\n${body}\\n\\n${footer}\n======================\n `)\n });\n }",
"async baseSchemaOnModelAsk() {\n if (this.isNewFile && this.ctx.haveModel) {\n const ask = {\n type: 'confirm',\n name: 'modelBasedOnSchema',\n message: 'Use a model as base?',\n default: true,\n };\n this.useModelAsBase = (await this.prompt([ask])).modelBasedOnSchema;\n }\n }",
"function askForAnalysisURL () {\n return inquirer.prompt([\n {\n type: 'input',\n name: 'docurl',\n message: 'What\\'s the URL of the analysis?'\n },\n {\n type: 'input',\n name: 'docid',\n message: 'Confirm analysis ID',\n default (answers) {\n const match = /\\/([a-z0-9]{24})/.exec(answers.docurl);\n return match && match[1];\n },\n when (answers) {\n return /\\/platforms\\/[a-z0-9]{24}/.test(answers.docurl);\n }\n }\n ]);\n}",
"manageDocument() {\n if (this.open) {\n // When the modal is opened, inert the rest of the document.\n openModal();\n\n // If the modal is triggered by an element in a parent modal,\n // inert the triggering modal and tag it so it can be uninerted later.\n // (Tagging prevents failure if elements move around in the DOM.)\n const parent = this.closest(this.parentModal);\n\n if (parent) {\n parent.inert = true;\n this._parent = parent;\n }\n } else if (!this.open && this.parentModal) {\n // If the modal is triggered by an element in another modal,\n // uninert the triggering modal but leave the document inert.\n\n if (parent) {\n parent.inert = false;\n this._parent = null;\n }\n } else {\n // When the modal is closed, uninert the rest of the document.\n closeModal();\n }\n }",
"function check_employee()\n{\n\tvar obj = document.emplID.employeeID;\n\n\tif (obj.options.length == 1) { return true; }\n\telse\n\t{\n\t\tif (obj.selectedIndex == 0) { return confirm(\"You didn't select an employee.\\n\\nAre you sure you want to continue?\"); }\n\t\telse { return true; }\n\t}\n}",
"function prompter(cz, commit) {\n // Let's ask some questions of the user\n // so that we can populate our commit\n // template.\n //\n // See inquirer.js docs for specifics.\n // You can also opt to use another input\n // collection library if you prefer.\n inquirer\n .prompt([\n {\n type: \"input\",\n name: \"message\",\n message: \"GitHub commit message (required):\\n\",\n validate: function(input) {\n if (!input) {\n return \"empty commit message\";\n } else {\n return true;\n }\n }\n },\n {\n type: \"input\",\n name: \"issues\",\n message: \"Jira Issue ID(s) (required):\\n\",\n default: ticketNumber,\n validate: function(input) {\n if (!input) {\n return \"Must specify issue IDs, otherwise, just use a normal commit message\";\n } else {\n return true;\n }\n }\n },\n {\n type: \"input\",\n name: \"time\",\n message: \"Time spent (i.e. 3h 15m) (optional):\\n\"\n }\n ])\n .then(answers => {\n formatCommit(commit, answers);\n });\n}",
"function validateOrganFrm(){\n\tif (document.formOrgan.organization.value==null || document.formOrgan.organization.value==\"\"){\n\t\talert(\"Please enter org name.\");\n\t\tdocument.formOrgan.organization.focus();\n\t\treturn false;\n\t}\n\tif (document.formOrgan.cemail.value==null || document.formOrgan.cemail.value==\"\"){\n\t\talert(\"Please enter org email.\");\n\t\tdocument.formOrgan.cemail.focus();\n\t\treturn false;\n\t}\n\tif (echeck(document.formOrgan.cemail.value)==false){\n\t\tdocument.formOrgan.cemail.value=\"\";\n\t\tdocument.formOrgan.cemail.focus();\n\t\treturn false;\n\t}\n\tif (document.formOrgan.chgstate.value==\"new\"){\n\t\tif (document.getElementById(\"meadmin1\").checked == false){//Admin1: if admin not default, validate all fields\n\t\t\tif (document.formOrgan.cd1firstname.value==null || document.formOrgan.cd1firstname.value==\"\"){\n\t\t\t\talert(\"Please enter Admin 1 first name.\");\n\t\t\t\tdocument.formOrgan.cd1firstname.focus();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (document.formOrgan.cd1lastname.value==null || document.formOrgan.cd1lastname.value==\"\"){\n\t\t\t\talert(\"Please enter Admin 1 last name.\");\n\t\t\t\tdocument.formOrgan.cd1lastname.focus();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (document.formOrgan.cd1email.value==null || document.formOrgan.cd1email.value==\"\"){\n\t\t\t\talert(\"Please enter Admin 1 e-mail.\");\n\t\t\t\tdocument.formOrgan.cd1email.focus();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t//=>function*js/\n\t\t\tif (echeck(document.formOrgan.cd1email.value)==false){\n\t\t\t\tdocument.formOrgan.cd1email.value=\"\";\n\t\t\t\tdocument.formOrgan.cd1email.focus();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (document.getElementById(\"meadmin2\").checked == false){//Admin1: if admin not default, validate all fields\n\t\t\tif (document.formOrgan.cd2firstname.value!=\"\" && document.formOrgan.cd2lastname.value!=\"\" && document.formOrgan.cd2email.value!=\"\"){\n\t\t\t\tif (document.formOrgan.cd2firstname.value==null || document.formOrgan.cd2firstname.value==\"\"){\n\t\t\t\t\talert(\"Please enter Admin 2 first name.\");\n\t\t\t\t\tdocument.formOrgan.cd2firstname.focus();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (document.formOrgan.cd2lastname.value==null || document.formOrgan.cd2lastname.value==\"\"){\n\t\t\t\t\talert(\"Please enter Admin 2 last name.\");\n\t\t\t\t\tdocument.formOrgan.cd2lastname.focus();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (document.formOrgan.cd2email.value==null || document.formOrgan.cd2email.value==\"\"){\n\t\t\t\t\talert(\"Please enter Admin 2 e-mail.\");\n\t\t\t\t\tdocument.formOrgan.cd2email.focus();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t//=>function*js/\n\t\t\t\tif (echeck(document.formOrgan.cd2email.value)==false){\n\t\t\t\t\tdocument.formOrgan.cd2email.value=\"\";\n\t\t\t\t\tdocument.formOrgan.cd2email.focus();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}//end admin2\n\t\t}\n\t}//end of new process\n}",
"provideDocumentFormattingEdits(document, formattingOptions) {\n // \tconsole.log('HTML Beautifying running.');\n // \tconst htmlFormatting = commands.executeCommand('editor.action.formatDocument');\n console.log(\"AMPscript Beautifying running.\");\n const setup = vscode.workspace.getConfiguration(\"beautyAmp\");\n \n const editorSetup = {\n tabSize: formattingOptions.tabSize,\n insertSpaces: formattingOptions.insertSpaces\n };\n console.log('SETUP:', setup, editorSetup);\n\n beautifier.setup(setup, editorSetup, { loggerOn: loggerOn });\n\n // get document as an array of strings:\n let lines = getLinesAsText(document);\n\n // run the beautify:\n const newLines = beautifier.beautify(lines);\n return rewriteDocument(vscode, document, newLines);\n }",
"function validPdfForm() {\r\n return true;\r\n}",
"function showChangeTracking(parentDocViewId)\r\n{\r\n\tcloseMsgBox(); \r\n\tvar htmlAreaObj = _getWorkAreaDefaultObj();\r\n \tvar objAjax = htmlAreaObj.getHTMLAjax();\r\n\tvar objHTMLData = htmlAreaObj.getHTMLDataObj();\r\n\t//alert(objHTMLData);\r\n\tif(objHTMLData && objHTMLData.hasUserModifiedData() && objHTMLData.isDataModified())\r\n {\r\n var htmlErrors = objAjax.error();\r\n htmlErrors.addError(\"confirmInfo\", szMsg_Changes, false);\r\n var saveFunc =\"\\\"Main.loadWorkAreaWithSave()\\\"\";\t \r\n var canceFunc =\"_showChangeTracking('\"+parentDocViewId+\"')\";\r\n messagingDiv(htmlErrors, saveFunc, canceFunc);\r\n } \r\n else\r\n {\r\n \t_showChangeTracking(parentDocViewId);\r\n }\r\n}",
"function confirmNote(){\n\tvar notes = document.getElementById('NotesVacID').value;\n\tif (notes !== '')\n\t\treturn notes;\n\t\treturn window.confirm(\"Your Notes are Empty, Confirm?\");\n}",
"function makeBooksForm(service_email, user_name) {\n var temp_str = user_name + \"'s Book Suggestion Input\";\n var input_form = FormApp.create(temp_str);\n input_form.setTitle(temp_str);\n \n temp_str = \"New book title\";\n var temp_question = input_form.addTextItem();\n temp_question.setTitle(temp_str);\n temp_question.setHelpText(temp_str);\n temp_question.setRequired(true);\n \n temp_str = \"New book author's first name\";\n temp_question = input_form.addTextItem();\n temp_question.setTitle(temp_str);\n temp_question.setHelpText(temp_str);\n temp_question.setRequired(true);\n \n temp_str = \"New book author's last name\";\n temp_question = input_form.addTextItem();\n temp_question.setTitle(temp_str);\n temp_question.setHelpText(temp_str);\n temp_question.setRequired(true);\n \n // Emails can't be delivered to a service account.\n // There's an annoying \"failed to deliver email\" email that is sent to the user if it tries.\n var form_id = input_form.getId();\n Drive.Permissions.insert(\n {\n 'role': 'writer',\n 'type': 'user',\n 'value': service_email\n },\n form_id,\n {\n 'sendNotificationEmails': 'false' //The normal way of adding editors doesn't have this option\n }\n );\n \n var form_url = input_form.getPublishedUrl();\n \n return {form_id: form_id, form_url: form_url};\n}",
"function ChangedDocumentTracker() {\n var self = this;\n \n this._changedPaths = {};\n this._windowFocus = true;\n this._addListener = this._addListener.bind(this);\n this._onChange = this._onChange.bind(this);\n this._onWindowFocus = this._onWindowFocus.bind(this);\n \n $(DocumentManager).on(\"workingSetAdd\", function (event, fileEntry) {\n // Only track documents in the current project\n if (ProjectManager.isWithinProject(fileEntry.fullPath)) {\n DocumentManager.getDocumentForPath(fileEntry.fullPath).done(function (doc) {\n self._addListener(doc);\n });\n }\n });\n \n $(DocumentManager).on(\"workingSetRemove\", function (event, fileEntry) {\n // Only track documents in the current project\n if (ProjectManager.isWithinProject(fileEntry.fullPath)) {\n DocumentManager.getDocumentForPath(fileEntry.fullPath).done(function (doc) {\n $(doc).off(\"change\", self._onChange);\n doc.releaseRef();\n });\n }\n });\n \n // DocumentManager has already initialized the working set\n DocumentManager.getWorkingSet().forEach(function (fileEntry) {\n // Can't use getOpenDocumentForPath() here since being in the working set\n // does not guarantee that the file is opened (e.g. at startup)\n DocumentManager.getDocumentForPath(fileEntry.fullPath).done(function (doc) {\n self._addListener(doc);\n });\n });\n \n $(window).focus(this._onWindowFocus);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Private helper to create a tooltip item model | function createTooltipItem(element) {
var xScale = element._xScale;
var yScale = element._yScale || element._scale; // handle radar || polarArea charts
var index = element._index;
var datasetIndex = element._datasetIndex;
return {
xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
index: index,
datasetIndex: datasetIndex,
x: element._model.x,
y: element._model.y
};
} | [
"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 }",
"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 createTooltip(title, tiptext, parent) {\n let box = create(\"td\");\n let tooltip = create(\"a\");\n append(box, tooltip);\n tooltip.classList.add(\"tooltip\");\n appendText(tooltip, title);\n\n let tooltipText = create(\"span\");\n tooltipText.classList.add(\"tooltiptext\");\n\n appendText(tooltipText, tiptext);\n append(tooltip, tooltipText);\n append(parent, box);\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 TooltipUtils() {\n}",
"function _initializeTooltip(){\r\n gTooltipGenerator = d3.oracle.tooltip()\r\n .accessors({\r\n label : (pOptions.tooltipX || pOptions.tooltipSeries) ?\r\n function( d ) {\r\n if ( pOptions.tooltipX && !pOptions.tooltipSeries) {\r\n return pOptions.xDataType.toLowerCase() === 'number' ? gXValueFormatter(d.x) : gXValueFormatter(new Date(d.x));\r\n } else if ( !pOptions.tooltipX && pOptions.tooltipSeries) {\r\n return d.series;\r\n } else {\r\n var formattedXValue = pOptions.xDataType.toLowerCase() === 'number' ? gXValueFormatter(d.x) : gXValueFormatter(new Date(d.x));\r\n return d.series + ' (' + formattedXValue + ')';\r\n }\r\n } : null,\r\n value : pOptions.tooltipY ? function( d ) { return d.y; } : null,\r\n color : function() { return gTooltipColor },\r\n content : function( d ) {\r\n return d.tooltip;\r\n }\r\n })\r\n .formatters({\r\n value : gYValueFormatter\r\n })\r\n .transitions({\r\n enable : false\r\n }) \r\n .symbol( 'circle' );\r\n }",
"function testTipItem() {\n var el = tip.container;\n assertEquals(String(goog.dom.TagName.DIV), el.tagName);\n assertEquals(TIP_ID, tip.id);\n assertContains('Tip', goog.dom.getTextContent(el));\n assertContains(CAPTION, goog.dom.getTextContent(el));\n assertNotContains('Warning', goog.dom.getTextContent(el));\n\n el = warn_tip.container;\n assertEquals(String(goog.dom.TagName.DIV), el.tagName);\n assertEquals(WARN_ID, warn_tip.id);\n assertNotContains('Tip', goog.dom.getTextContent(el));\n assertContains(CAPTION, goog.dom.getTextContent(el));\n assertContains('Warning', goog.dom.getTextContent(el));\n assertContains('vsaq-bubble-medium', el.innerHTML);\n\n el = why_tip.container;\n assertEquals(String(goog.dom.TagName.DIV), el.tagName);\n assertEquals(WHY_ID, why_tip.id);\n assertNotContains('Tip', goog.dom.getTextContent(el));\n assertContains(CAPTION, goog.dom.getTextContent(el));\n assertContains('Warning', goog.dom.getTextContent(el));\n assertContains('vsaq-bubble-medium', el.innerHTML);\n\n assertEquals(NAME_ID, name_tip.id);\n assertEquals(NAME, name_tip.name);\n\n assertEquals(TODO_ID, todo_tip.id);\n assertEquals(TODO, todo_tip.todo);\n\n assertEquals(CUSTOMTITLE_ID, custom_title_tip.id);\n assertEquals(CUSTOMTITLE_TEXT, custom_title_tip.customTitle);\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 testTipItemParse() {\n var testStack = [{\n 'type': 'tip',\n 'text': CAPTION,\n 'id': TIP_ID,\n 'warn': 'yes',\n 'why': WHY_TEXT,\n 'todo': TODO,\n 'customTitle' : CUSTOMTITLE_TEXT,\n }];\n tip = vsaq.questionnaire.items.TipItem.parse(testStack);\n assert(tip instanceof vsaq.questionnaire.items.TipItem);\n assertEquals(TIP_ID, tip.id);\n assertEquals(CAPTION, tip.text);\n assertEquals(true, tip.warn);\n assertEquals(WHY_TEXT, tip.clarification);\n assertEquals(0, testStack.length);\n assertEquals(TODO, tip.todo);\n assertEquals(CUSTOMTITLE_TEXT, tip.customTitle);\n}",
"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 }",
"initTooltip() {\n const self = this;\n\n // Array containing all tooltip lines (visible or not)\n self.d3.tooltipLines = [];\n self.curData.forEach(function (datum, index) {\n if (index > self.colorPalette.length) {\n notify().error(\"Palette does not contain enough colors to render curve with color, \" +\n \"this should never occur, contact an administrator\");\n self.d3.tooltipLines.push(\n self.d3.o.tooltip.append(\"p\")\n .style(\"color\", \"#000\")\n .style(\"margin\", \"0 0 4px\")\n .style(\"font-size\", \"0.8em\")\n );\n } else {\n self.d3.tooltipLines.push(\n self.d3.o.tooltip.append(\"p\")\n .style(\"color\", self.colorPalette[index])\n .style(\"margin\", \"0 0 4px\")\n .style(\"font-size\", \"0.8em\")\n );\n }\n });\n }",
"function setLinkToolTip()\n{\n linkToolTip = d3.tip()\n .attr(\"class\", \"d3-tip\")\n .html(\"some text\")\n .offset([-10, 0]);\n\n svg.call(linkToolTip);\n}",
"drawTip() {\n let tipLocationInfo;\n\n if (this.lastHitInfo) {\n tipLocationInfo = this.lastHitInfo;\n } else if (this.defaultSelectItemInfo) {\n tipLocationInfo = this.getItem(this.defaultSelectItemInfo, false);\n } else if (this.defaultSelectInfo && this.options.selectLabel.use) {\n tipLocationInfo = this.getItem(this.defaultSelectInfo, false);\n } else {\n tipLocationInfo = null;\n }\n\n this.drawTips?.(tipLocationInfo);\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 createMeasureTooltip() {\n if (measureTooltipElement && measureTooltipElement.parentNode) {\n measureTooltipElement.parentNode.removeChild(measureTooltipElement);\n }\n measureTooltipElement = document.createElement('div');\n measureTooltipElement.className = 'tooltip tooltip-measure';\n measureTooltip = new Overlay({\n element: measureTooltipElement,\n offset: [0, -30],\n positioning: 'bottom-center',\n });\n App4Sea.OpenLayers.Map.addOverlay(measureTooltip);\n }",
"function tooltips ( ) {\n\n // Tooltips are added with options.tooltips in original order.\n var tips = scope_Handles.map(addTooltip);\n\n bindEvent('update', function(f, o, r) {\n if ( tips[o] ) {\n tips[o].innerHTML = options.tooltips[o] === true ? f[o] : options.tooltips[o].to(r[o]);\n }\n });\n }",
"getTooltipPopup() {\n return this.selector(`[id^=\"${this.id}_\"]`);\n }",
"function ReplaceTooltipBuild() {\n Object.keys(Game.Objects).forEach((i) => {\n const me = Game.Objects[i];\n if (l(`product${me.id}`).onmouseover !== null) {\n TooltipBuildBackup[i] = l(`product${me.id}`).onmouseover;\n l(`product${me.id}`).onmouseover = function () {\n Game.tooltip.dynamic = 1;\n Game.tooltip.draw(this, () => CreateTooltip('b', `${i}`), 'store');\n Game.tooltip.wobble();\n };\n }\n });\n}",
"function appendMetaData(item, model, id, data) {\n var $item, ul;\n\n $item = $(item);\n if (!$('#adminMeta-' + model + '-' + id).length) {\n ul = jsonToDl(data);\n\n if (ul) {\n ul\n .attr('id', 'adminMeta-' + model + '-' + id)\n .appendTo($('#adminMetaContainer'));\n }\n }\n\n $item\n .hover(function (e) {\n var $this = $(this);\n\n e.stopPropagation();\n\n if (!enabled) {\n return;\n }\n\n $this.addClass('hovered');\n setTimeout(function () {\n if ($this.hasClass('hovered')) {\n $this.removeClass('hovered');\n show($this);\n }\n }, 1000);\n }, function (e) {\n e.stopPropagation();\n\n if (!enabled) {\n return;\n }\n\n $(this).removeClass('hovered');\n });\n }",
"displayLess() {\n let that = this;\n return () => that.collapseToolTip(that.tooltip, that.tooltipExt);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check project root and composer.json | function preFlightCheck(root) {
if (!fs.existsSync(root)) {
throw new Error('Invalid project root');
}
consola.success('Found project root');
if (!fs.existsSync(root + '/composer.json')) {
throw new Error('composer.json not found in project root');
}
consola.success('Found composer.json');
var json = fs.readFileSync(root + '/composer.json');
try {
json = JSON.parse(json);
} catch (e) {
throw new Error('composer.json is no valid json file ' + e);
}
consola.success('composer.json is a valid JSON file');
if (!json.extra || (!json.extra.patches && !json.extra['patches-file'])) {
throw new Error('composer.json does not list any patches');
}
consola.success('composer.json has a list of patches');
return json;
} | [
"function checkRepo() {\n\t\tif (!pkg.repository) {\n\t\t\tproblems.push({\n\t\t\t\tmessage: `cannot found \"repository\" in package.json.`\n\t\t\t});\n\t\t}\n\t}",
"function findCliConfig() {\n return ['angular.json', '.angular.json', 'angular-cli.json', '.angular-cli.json'].find(file => fs.existsSync(file));\n}",
"function checkMain() {\n\t\tif (pkg.main) {\n\t\t\t!exsitsFile(pkg.main, opts.cwd) &&\n\t\t\t\tproblems.push({\n\t\t\t\t\tmessage: `cannot found file \"${pkg.main}\"(pkg.main).`\n\t\t\t\t});\n\t\t}\n\t}",
"function fileExistInNpm(filePath) {\n return existsSync(path.resolve(__dirname, '../../', filePath));\n}",
"function checkLisence() {\n\t\tif (!pkg.license) {\n\t\t\tproblems.push({\n\t\t\t\tmessage: 'cannot found \"license\" in package.json.'\n\t\t\t});\n\t\t}\n\t}",
"function checkGitInstallFn () {\n var promise_obj = makeStatProm( fqGitDirname );\n promise_obj.then( function () {\n logFn( 'Git directory ' + fqGitDirname + ' found.');\n logFn( 'Installing commit hook...' );\n eventObj.emit( '06UnLinkHook' );\n })\n .catch( function () {\n logFn( 'Git directory ' + fqGitDirname + ' NOT found.');\n logFn( 'Please \"npm run setup\" if you add code to a git repo.' );\n eventObj.emit( '99FinishRun');\n });\n }",
"async checkPJSON () {\n if (atom.config.get('atom-aframe.project.checkPackageJson')) {\n const pjw = new PJW()\n try {\n await pjw.check()\n this.dependsOnAframe = pjw.hasDependency()\n } catch (e) {\n // should listen package.json onCreate\n this.dependsOnAframe = false\n }\n }\n }",
"function checkSite()\n{\n var path = \"./public\";\n var ok = fs.existsSync(path);\n if(ok) path = \"./public/index.html\";\n if(ok) ok = fs.existsSync(path);\n if(!ok) console.log(\"Can't find\", path);\n return(ok);\n}",
"function checkBin() {\n\t\tif (pkg.bin) {\n\t\t\tconst bins =\n\t\t\t\ttypeof pkg.bin === 'string'\n\t\t\t\t\t? [pkg.bin]\n\t\t\t\t\t: Object.keys(pkg.bin).map(it => pkg.bin[it]);\n\t\t\tbins.forEach(it => {\n\t\t\t\t!exsitsFile(it, opts.cwd) &&\n\t\t\t\t\tproblems.push({\n\t\t\t\t\t\tmessage: `cannot found file \"${it}\"(pkg.bin).`\n\t\t\t\t\t});\n\t\t\t});\n\t\t}\n\t}",
"function checkComposer() {\n\tvar process = runExec(pgrepPath, pgrepComposer, true);\n\t\n\tif (process.exitValue != 0) {\n\t\tstartComposer();\n\n\t\t//wait for the pipe to be created\n\t\tvar i = 0;\n\t\twhile (!checkPipe() && i < 5000) i++;\n\t}\n}",
"function checkServerName(serverName) {\n const validationResult = validateProjectName(serverName);\n if (!validationResult.validForNewPackages) {\n error(\n chalk.red(`Cannot create a project named ${chalk.green(`\"${serverName}\"`)} because of npm naming restrictions:\\n`)\n );\n [...(validationResult.errors || []), ...(validationResult.warnings || [])].forEach(err => {\n error(chalk.red(` * ${err}`));\n });\n error(chalk.red('\\nPlease choose a different project name.'));\n process.exit(1);\n }\n\n // TODO: there should be a single place that holds the dependencies\n const dependencies = ['debug', 'dotenv', 'express', 'mysql', 'prettier', 'morgan'].sort();\n\n if (dependencies.includes(serverName)) {\n error(\n chalk.red(\n `Cannot create a project named ${chalk.green(\n `\"${serverName}\"`\n )} because a dependency with the same name exists.\\n` +\n `Due to the way npm works, the following names are not allowed:\\n\\n`\n ) +\n chalk.cyan(dependencies.map(depName => ` ${depName}`).join('\\n')) +\n chalk.red('\\n\\nPlease choose a different project name.')\n );\n process.exit(1);\n }\n}",
"async function validateRepository() {\n const projectRepo = await targetProjectRepo();\n const ENSURE_REMOTE_PROJECT = projectRepo.url;\n\n if (!projectRepo || !(projectRepo.type !== 'gitlab' || projectRepo.type !== 'git' || projectRepo.type !== 'bitbucket' || projectRepo.type !== 'stash')) {\n console.log(`\n You MUST have a repository specified in your package json to use the\n release script. It must be of 'type: git' and have a valid ssh url to\n your git repo.\n\n Additionally, you MUST have a remote configured for your project of\n 'origin' that matches the repo url listed in your package.json.\n\n Thus: \"git remote -v\" SHOULD output a line with\n origin <url in your package json repository field> (push)\n `);\n process.exit(1);\n }\n\n // We check our remote to ensure we have a projected with expected values\n const remoteListProcess = shell.exec('git remote -v');\n\n if (remoteListProcess.code !== 0) {\n console.log('Could not list remotes for the git project.');\n process.exit(1);\n }\n\n const remotes = remoteListProcess.stdout.toString().split(/\\r?\\n/g);\n\n const foundRemote = remotes.find(row =>\n row.indexOf(ENSURE_REMOTE) >= 0 && row.indexOf(ENSURE_REMOTE_PROJECT) >= 0\n );\n\n if (!foundRemote) {\n console.log(\n 'Could not match package json repository to an origin remote in git CLI',\n ENSURE_REMOTE,\n ENSURE_REMOTE_PROJECT\n );\n process.exit(1);\n }\n\n // Now check to make sure the repo specified exists in git and is available to the user\n const checkRemoteAccessProcess = shell.exec(`git ls-remote ${ENSURE_REMOTE_PROJECT}`);\n\n if (checkRemoteAccessProcess.code !== 0) {\n console.log(`\n You do not seem to have access to the repo listed in the package json of\n this project. Please ensure you have write access to the repo:\n ${ENSURE_REMOTE_PROJECT}\n and then try to run the release again.\n `);\n process.exit(1);\n }\n}",
"async installProject() {\n // git clone\n await this.gitClone();\n\n // run hook\n await this.install();\n }",
"async validateSingleSpaDependency() {\n const { dependencies } = await this.fs.readJSON(`${this.cwd}/package.json`);\n if (dependencies && !dependencies[\"single-spa\"]) {\n const install = (cmd, opts) =>\n spawnSync(cmd, opts, {\n stdio: \"inherit\",\n cwd: this.cwd,\n });\n switch (this.options.packageManager) {\n case \"npm\":\n install(\"npm\", [\"install\", \"single-spa\"]);\n break;\n case \"yarn\":\n install(\"yarn\", [\"add\", \"single-spa\"]);\n break;\n default:\n break;\n }\n }\n }",
"function checkFiles() {\n\t\tpkg.files &&\n\t\t\tpkg.files.forEach(pattern => {\n\t\t\t\t// skip patterns like \"!foo\"\n\t\t\t\tif (!pattern.startsWith('!')) {\n\t\t\t\t\tconst matchedFiles = globby.sync(pattern, {\n\t\t\t\t\t\tcwd: opts.cwd\n\t\t\t\t\t});\n\t\t\t\t\tif (matchedFiles.length === 0) {\n\t\t\t\t\t\tproblems.push({\n\t\t\t\t\t\t\tmessage: `cannot found file \"${pattern}\"(pkg.files).`\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t}",
"get manifest(){\n if(fs.existsSync(path.join(this.root, 'package.json'))){\n return JSON.parse(fs.readFileSync(path.join(this.root, 'package.json')))\n }\n }",
"hasProject(name) {\n return this.allWorkspaceProjects.has(name);\n }",
"function getLockFileExists () {\n const result = {};\n const cwd = process.cwd();\n if (!fs.existsSync(path.join(cwd, 'package.json'))) {\n return result;\n }\n if (fs.existsSync(path.join(cwd, 'yarn.lock'))) {\n result.yarn = true;\n }\n if (fs.existsSync(path.join(cwd, 'package-lock.json'))\n || fs.existsSync(path.join(cwd, 'npm-shrinkwrap.json'))\n ) {\n result.npm = true;\n }\n return result;\n}",
"async function inGitDirectory(abort) {\n\n\t// Check if .git folder exists\n\tlet exists = await Files.exists('./.git');\n\n\tif (!exists) {\n\n\t\tif (abort) {\n\t\t\tLog.error('You are not in a git directory');\n\t\t\tthrow 'This command must be run in a git directory';\n\t\t}\n\n\t}\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split a block tags contents in to an array of bits that contains the type of block node, and any arguments that were passed to the block node if they exist. | function makeBits(blockToken) {
return (function (bits, split) {
// Remove empty strings and strip whitespace.
for (i = 0; i < split.length; i++) {
(function (bit) {
return bit === "" ? null : bits.push(bit);
}(strip(split[i])));
}
return bits;
}([], split(blockToken.replace(OPEN_BLOCK_TAG, "")
.replace(CLOSE_BLOCK_TAG, ""),
/[\s]+?/)));
} | [
"function _extract_tags(cblock, tags) {\n var extracted = tags.map(function(tag) {\n return cblock[tag];\n });\n if (extracted[0] === undefined)\n return null;\n // Verify that, in case of loops, all tags have the same length\n var basetype = extracted[0].type;\n var baselen = null;\n if (basetype == 'loop') {\n baselen = extracted[0].value.length;\n }\n\n extracted = extracted.map(function(x) {\n if (x === undefined)\n return null;\n if (x.type != basetype)\n return null;\n if (basetype == 'loop' && x.value.length != baselen)\n return null;\n\n if (basetype == 'loop') {\n return x.value;\n } else {\n return [x.value];\n }\n });\n\n return extracted;\n}",
"function makeBlockNode(nodes, tokens, f) {\n // Remove the templating syntax and split the type of block tag and\n // its arguments.\n var bits = makeBits(tokens[0]),\n\n // The type of block tag is the first of the bits, the rest\n // (if present) are args\n type = bits[0],\n args = cdr(bits),\n\n // Make the node from the set of block tags that Tempest knows\n // about.\n node = makeObj(BLOCK_NODES[type]),\n resultsArray;\n\n // Ensure that the type of block tag is one that is defined in\n // BLOCK_NODES\n if (node === undefined) {\n throw new TemplateSyntaxError(\"Unknown Block Tag.\");\n }\n\n node.args = args;\n tokens = cdr(tokens);\n\n if (node.expectsEndTag === true) {\n resultsArray = makeNodes(tokens);\n\n if (resultsArray[2] !== undefined) {\n // The third item in the array returned by makeNodes is\n // only defined if the last of the tokens was made in to a\n // node and it wasn't an end-block tag.\n throw new TemplateSyntaxError(\n \"A block tag was expecting an ending tag but it was not found.\"\n );\n }\n node.subNodes = resultsArray[0];\n tokens = resultsArray[1];\n }\n\n // Add the newly created node to the nodes list.\n nodes = append(node, nodes);\n\n // Continue where we were before the block node.\n return f(nodes, tokens);\n }",
"function getBlocks(args) {\n // Get all blocks (avoid deprecated warning).\n var blocks = select('core/block-editor').getBlocks(); // Append innerBlocks.\n\n var i = 0;\n\n while (i < blocks.length) {\n blocks = blocks.concat(blocks[i].innerBlocks);\n i++;\n } // Loop over args and filter.\n\n\n for (var k in args) {\n blocks = blocks.filter(function (block) {\n return block.attributes[k] === args[k];\n });\n } // Return results.\n\n\n return blocks;\n } // Data storage for AJAX requests.",
"function createBlocksForAST(ast, workspace) {\n\tconst parse_node = (node) => {\n\t\t\n\t\tconst node_meta = lpe_babel.types.NODE_FIELDS[node.type];\n\t\t\n\t\tlet block = workspace.newBlock(TYPE_PREFIX + node.type);\n\t\tblock.babel_node = node;\n\t\tnode.blockly_block = block;\n\t\t\n\t\tblock.initSvg();\n\t\tblock.render();\n\n\t\tif(typeof node_meta.value !== 'undefined') {\n\t\t\tblock.getField(\"value\").setValue(node.value);\n\t\t} else {\n\t\t\t// Go through the inputs\n\t\t\tfor(const field_name in node_meta) {\n\t\t\t\tconst field_meta = node_meta[field_name];\n\n\t\t\t\t// Check if this is a chaining input\n\t\t\t\tif(!field_meta.validate) {\n\t\t\t\t\tconsole.log(\"Error: field can't be validated:\");\n\t\t\t\t\tconsole.log(field_meta);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif(field_meta.validate.chainOf) {\n\n\t\t\t\t\t// Decide if this is a series of nodes or a limited selection of nodes\n\t\t\t\t\tif(field_meta.validate.chainOf[0].type === 'array') {\n\t\n\t\t\t\t\t\tlet node_list = node[field_name];\n\n\t\t\t\t\t\tif(node_list && node_list.length > 0) {\n\t\t\t\t\t\t\t// Transform list to tree\n\t\t\t\t\t\t\tfor(let i = node_list.length-1; i > 0; i--) {\n\t\t\t\t\t\t\t\tnode_list[i-1].next = node_list[i];\n\t\t\t\t\t\t\t\t//node_list.pop();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tblockly_tools.setAsFirstStatement(parse_node(node_list[0]), block, field_name);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblock.getField(field_name).setValue(node[field_name]);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t//console.log(field.validate.chainOf)\n\t\t\t\t} else if (field_meta.validate.oneOfNodeTypes) {\n\t\t\t\t if(node[field_name]) {\n\t\t\t\t\t blockly_tools.setAsInput(parse_node(node[field_name]), block, field_name)\n\t\t\t\t }\n\t\t\t\t} else if (field_meta.validate.type && field_meta.validate.type !== 'string') {\n\t\t\t\t\tif(node[field_name]) {\n\t\t\t\t\t blockly_tools.setAsInput(parse_node(node[field_name]), block, field_name)\n\t\t\t\t }\n\t\t\t\t} else {\n\t\t\t\t\tblock.getField(field_name).setValue(node[field_name]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(node.next) {\n\t\t\tblockly_tools.setAsNext(parse_node(node.next), block)\n\t\t}\n \n\t\treturn block;\n\t}\n\t\n\tif(ast.program) {\n\t return parse_node(ast.program);\n\t} else if(ast instanceof Array) {\n\t let parsedNodes = ast.map(parse_node);\n\t return parsedNodes;\n\t} else {\n\t return parse_node(ast);\n\t}\n\t\n}",
"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 parseTags(body) {\n const tagIndex = body.indexOf(\"#\");\n let tags = [];\n if (tagIndex >= 0) {\n tags = body.substring(tagIndex, body.length).split(\"#\");\n tags = tags.reduce((result, tag) => {\n tag = tag.trim();\n if (tag.length > 0) \n result.push(tag);\n return result;\n }, []);\n }\n return tags;\n}",
"function instructify (blocks) {\r\n\r\n let instructions = [];\r\n\r\n\r\n // For each of the selected blocks\r\n for (const block of blocks) {\r\n\r\n // For each line of the corresponding script\r\n for( const line of block.script) {\r\n\r\n // Retrieve instruction and body\r\n let inst = line.split(' ')[0];\r\n let bod = line.split(' ').splice(1).join(' ');\r\n\r\n\r\n if (keypresses.find(k => k === inst)) {\r\n bod = `${inst} ${bod}`;\r\n inst = 'KEY';\r\n }\r\n\r\n\r\n instructions.push({instruction: inst, body: bod});\r\n }\r\n }\r\n\r\n\r\n return instructions;\r\n}",
"function extUtils_isBlockTag(node)\n{\n var retVal = false;\n\n if (node && node.nodeType == Node.ELEMENT_NODE)\n {\n var nodeHTML = dwscripts.getOuterHTML(node);\n\n if (nodeHTML)\n {\n var tagName = dwscripts.getTagName(node);\n retVal = (nodeHTML.search(RegExp(\"<\\\\/\"+tagName,\"i\")) != -1);\n }\n }\n\n return retVal;\n}",
"function get_basic_blocks( arg_startEA , arg_endEA )\n{\n\tvar bbArray = process.reserved.hostDependBindings.ida_get_basic_blocks( Number64(arg_startEA) , Number64(arg_endEA) );\n\tif ( !bbArray )\n\t{\n\t\treturn;\n\t}\n\t\n\treturn _.map( bbArray , function(oldItem)\n\t{\n\t\tvar newItem = {};\n\t\t\n\t\tnewItem.id = oldItem.id;\n\t\t\n\t\tnewItem.startEA = Number64( oldItem.startEA );\n\t\tnewItem.endEA = Number64( oldItem.endEA );\n\t\t\n\t\treturn newItem;\n\t});\n}",
"function check_blockquote(blocks) {\n var patt = /^>\\s(.*)$/;\n var match;\n\n for (var b = 0; b < blocks.length; b++) {\n if (blocks[b].tag == null) {\n var content = blocks[b].content;\n for (var l = 0; l < content.length; l++) {\n if ((match = patt.exec(content[l])) != null) {\n var inner_content = '';\n var same_block = true; //Keeps track of inner blockquote blocks\n for (var end = l; end < content.length; end++) {\n if ((match = patt.exec(content[end])) != null) {\n inner_content += match[1] + '\\n';\n same_block = true;\n }\n else if (content[end].trim().length == 0) { //End of block may mean end of blockquote\n inner_content += '\\n';\n same_block = false;\n } else if (same_block) { inner_content += content[end] + '\\n'; }\n else { break; }\n }\n inner_content = parse_blocks(inner_content, false);\n\n var raw1 = {content:content.slice(0,l)};\n var blockquote = {tag:'blockquote', content:inner_content};\n var raw2 = {content:content.slice(end,content.length)};\n\n blocks.splice(b, 1, raw1, blockquote, raw2);\n b++;\n break;\n }\n }\n }\n }\n}",
"async formatChildBlocks(block) {\n const children = block.children;\n if (!block.has_children) {\n return [];\n }\n\n (await Promise.all(children.map((child) => this.formatChildBlocks(child))))\n .forEach((c, i) => {\n const child = children[i];\n if (child.type === \"child_page\") {\n // convert child pages to links\n children[i] = this.childPageToLink(child);\n } else if (child.type === \"child_database\") {\n // convert child databases to links\n children[i] = this.childDatabaseToLink(child);\n } else {\n if (this.notValid(child, c)) {\n children[i] = undefined;\n } else {\n children[i] = {\n object: \"block\",\n type: child.type,\n [child.type]: child[child.type],\n };\n\n if (c.length > 0) {\n children[i][child.type].children = c;\n } else if (Object.keys(children[i][child.type]).length === 0) {\n // block has no children and no content\n children[i] = undefined;\n }\n }\n }\n });\n return children.filter((child) => child !== undefined);\n }",
"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 parseBlock() {\n var label = t.identifier(getUniqueName(\"block\"));\n var blockResult = null;\n var instr = [];\n\n if (token.type === _tokenizer.tokens.identifier) {\n label = identifierFromToken(token);\n eatToken();\n } else {\n label = t.withRaw(label, \"\"); // preserve anonymous\n }\n\n while (token.type === _tokenizer.tokens.openParen) {\n eatToken();\n\n if (lookaheadAndCheck(_tokenizer.keywords.result) === true) {\n eatToken();\n blockResult = token.value;\n eatToken();\n } else if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === \"keyword\" // is any keyword\n ) {\n // Instruction\n instr.push(parseFuncInstr());\n } else {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected token in block body of type\" + \", given \" + tokenToString(token));\n }();\n }\n\n maybeIgnoreComment();\n eatTokenOfType(_tokenizer.tokens.closeParen);\n }\n\n return t.blockInstruction(label, instr, blockResult);\n }",
"function YieldBlock(to, params) {\n return [op('SimpleArgs', {\n params,\n hash: null,\n atNames: true\n }), op(24\n /* GetBlock */\n , to), op(25\n /* JitSpreadBlock */\n ), op('Option', op('JitCompileBlock')), op(64\n /* InvokeYield */\n ), op(40\n /* PopScope */\n ), op(1\n /* PopFrame */\n )];\n}",
"function createNewBlock(name) {\n\t\t\t\tvar node = container, block, clonedNode, caretNode;\n\n\t\t\t\tblock = name || parentBlockName == \"TABLE\" ? dom.create(name || newBlockName) : parentBlock.cloneNode(false);\n\t\t\t\tcaretNode = block;\n\n\t\t\t\t// Clone any parent styles\n\t\t\t\tif (settings.keep_styles !== false) {\n\t\t\t\t\tdo {\n\t\t\t\t\t\tif (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(node.nodeName)) {\n\t\t\t\t\t\t\t// Never clone a caret containers\n\t\t\t\t\t\t\tif (node.id == '_mce_caret') {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tclonedNode = node.cloneNode(false);\n\t\t\t\t\t\t\tdom.setAttrib(clonedNode, 'id', ''); // Remove ID since it needs to be document unique\n\n\t\t\t\t\t\t\tif (block.hasChildNodes()) {\n\t\t\t\t\t\t\t\tclonedNode.appendChild(block.firstChild);\n\t\t\t\t\t\t\t\tblock.appendChild(clonedNode);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcaretNode = clonedNode;\n\t\t\t\t\t\t\t\tblock.appendChild(clonedNode);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} while ((node = node.parentNode));\n\t\t\t\t}\n\n\t\t\t\t// BR is needed in empty blocks on non IE browsers\n\t\t\t\tif (!isIE) {\n\t\t\t\t\tcaretNode.innerHTML = '<br data-mce-bogus=\"1\">';\n\t\t\t\t}\n\n\t\t\t\treturn block;\n\t\t\t}",
"function isBlockContainer(node) {\n return Boolean(acceptedBlocks(node));\n}",
"function acceptedBlocks(container) {\n return CONTAINERS[container.type || container.object];\n}",
"removeTags(tagName) {\n (0, utils_1.removeIf)(this.blockTags, (tag) => tag.tag === tagName);\n }",
"function buildListOfbooks(leftBlock, rightBlock) {\n for (var i = 0; i < leftBlock.length; i++) {\n builder(leftBlock[i], \".left\");\n }\n\n for (var i = 0; i < rightBlock.length; i++) {\n builder(rightBlock[i], \".right\");\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mark/unmark todo as done Move todo to bottom if done If unmarked, move up (before first marked as "done") | markAsDone(state, todoIndex) {
let markedTodo = null;
const markAndMove = () => {
state.todos[todoIndex].isDone = !state.todos[todoIndex].isDone;
markedTodo = state.todos.splice(todoIndex, 1);
};
let insertIndex = null;
for (let i = 0; i < state.todos.length; i++) {
if (state.todos[i].isDone) {
insertIndex = i;
break;
}
}
if (!state.todos[todoIndex].isDone) {
markAndMove();
state.todos.push(...markedTodo);
} else {
markAndMove();
if (insertIndex === 0) {
state.todos.unshift(...markedTodo);
} else if (insertIndex) {
state.todos.splice(insertIndex, 0, ...markedTodo);
} else {
state.todos.push(...markedTodo);
}
}
} | [
"moveTaskBack(task) {\n const index = this.state.tasksDone.indexOf(task);\n this.state.tasksDone.splice(index, 1);\n this.state.toDoTasks.unshift(task);\n this.setState({toDoTasks: this.state.toDoTasks,\n tasksDone: this.state.tasksDone\n })\n }",
"moveToTasksDone(task) {\n if (task !== \"\") {\n this.state.tasksDone.push(task);\n const index = this.state.toDoTasks.indexOf(task);\n this.state.toDoTasks.splice(index,1);\n this.setState({\n toDoTasks: this.state.toDoTasks,\n tasksDone: this.state.tasksDone\n })\n }\n }",
"checkAndMoveToDo (context, [todo, direction]) {\n switch (direction) {\n case 'left':\n // If the todo is completed and the pressed button is left it can only get set to in progress\n if (todo.isCompleted) {\n context.commit('setTodoInProgress', todo)\n context.dispatch('sendUpdateTodo', context.getters.getNewTodo(todo))\n } else if (todo.isInProgress) {\n context.commit('setTodoTodo', todo)\n context.dispatch('sendUpdateTodo', context.getters.getNewTodo(todo))\n }\n break\n case 'right':\n if (todo.isInTodo) {\n context.commit('setTodoInProgress', todo)\n context.dispatch('sendUpdateTodo', context.getters.getNewTodo(todo))\n } else if (todo.isInProgress) {\n context.commit('setTodoCompleted', todo)\n context.dispatch('sendUpdateTodo', context.getters.getNewTodo(todo))\n }\n break\n }\n }",
"moveTodo(state, moveInfo) {\n const i = moveInfo.index;\n const iShift = moveInfo.direction === 'up' ? -1 : 1;\n\n const todoMover = () => {\n state.todos[i].isMoved = true;\n setTimeout(() => {\n state.todos[i + iShift].isMoved = false;\n }, 400);\n const todoToMove = state.todos.splice(i, 1);\n state.todos.splice(i + iShift, 0, ...todoToMove);\n };\n\n if (moveInfo.direction === 'up') {\n if (i > 0) {\n todoMover(); \n }\n } else if (i < state.todos.length - 1 && !state.todos[i + 1].isDone) {\n todoMover(); \n }\n }",
"function toggle_done() {\n if (active_timer_idx >= 0 && active_timer_idx != selected_timer_idx) {\n return; // Special case of discussion toggled on. Don't set to done in this case.\n }\n\n var next_timer_idx = -1;\n if (active_timer_idx < 0) {\n timer_object = timers[selected_timer_idx];\n } else {\n timer_object = timers[active_timer_idx];\n if (typeof timers[active_timer_idx + 1] != 'undefined') {\n next_timer_idx = active_timer_idx + 1;\n }\n }\n if (timer_object != null) {\n if (active_timer_idx >= 0) {\n timer_object.circleProgress('timer_done', 1);\n start_stop_timer(active_timer_idx, 0);\n if (next_timer_idx >= 0) {\n change_selected_to(next_timer_idx);\n start_stop_timer(next_timer_idx, 1);\n active_timer_idx = next_timer_idx;\n } else {\n active_timer_idx = -1;\n }\n\n } else {\n timer_object.circleProgress('timer_done', -1);\n }\n }\n}",
"function changeTodoAsIncomplete(index) {\n var obj = todos[index];\n obj.isDone = false;\n storeTodos();\n displayTodoItems(todos);\n }",
"function delete_finished_todos(jquery_obj) {\n\tjquery_obj.find(\"div.project-content div.single-todo div.done\").parent().remove();\n\tsave_projects();\n}",
"function handleDoneList(e) {\n const li = e.target.parentNode.parentNode;\n finishNoList.style.display = \"none\";\n handleCreateFinished(li.innerText);\n\n handleDelToDos(e);\n}",
"function toggleTodoCompleted(item_li) {\n var item = get_li_item(item_li);\n var id = item.get(\"id\");\n if (item.get(\"state\") == \"completed\") {\n // Mark as active\n item.set({state:\"active\", completed_at:null});\n item.save();\n console.log(\"item id \" + id + \" marked as open.\");\n }\n else {\n // Mark as completed\n item.set({state:\"completed\", completed_at:new Date().toISOString()});\n item.save();\n console.log(\"item id \" + id + \" marked as completed.\");\n }\n}",
"handleEnterAndDelete(i, event) {\n if (event.keyCode === 13 && !this.state.toDoTasks.includes(\"\")) {\n this.state.toDoTasks.push(\"\");\n this.setState({\n toDoTasks: this.state.toDoTasks \n },this.handleCursor); \n } \n if ((event.key === \"Delete\" || event.key === \"Backspace\") && this.state.toDoTasks.length >=2 && i === this.state.toDoTasks.length - 1 && event.target.value === \"\") { \n this.state.toDoTasks.splice(i, 1);\n this.setState({toDoTasks: this.state.toDoTasks}, document.getElementById(\"task\" + (i-1)).focus());\n }\n }",
"function deleteToDo(position){\r\ntoDos.splice(position, 1);\r\ndisplayToDos();\r\n}",
"function changeToDo(position, newVal) {\r\ntoDos[position] = newVal;\r\ndisplayToDos();\r\n}",
"function moveTask(index, task, value) {\n $scope.schedule[$scope.currentUserId].splice(index, 1);\n if (value == 1) {\n $scope.schedule[$scope.currentUserId].splice(index - 1, 0, task);\n } else {\n $scope.schedule[$scope.currentUserId].splice(index + 1, 0, task);\n }\n saveUserSchedule();\n }",
"function toggleDone(e){ \n if(!e.target.matches('input')) return;\n const el = e.target;\n const index = el.dataset.index;\n dishes[index].done = !dishes[index].done;\n localStorage.setItem('dishes', JSON.stringify(dishes));\n populateDish(dishes, savedDishes);\n\n }",
"@action.bound\n setTaskParent(task, target_parent, skip_save=false) {\n // If `task` is an ancestor of `target_parent`, do nothing - we don't want to move a task\n // inside itself.\n if (this.isAncestor(target_parent, task)) {\n return;\n }\n\n // Set the moved task's sort_order to be after those of its new siblings.\n let max_sort_order = 0;\n for (let child of Object.values(target_parent.children)) {\n max_sort_order = Math.max(max_sort_order, child.sort_order);\n }\n task.sort_order = max_sort_order + 1;\n\n // Move `task` from its parent's set of children to `target_parent`'s set of children.\n let original_parent = task.parent;\n delete original_parent.children[task.id];\n target_parent.children[task.id] = task;\n task.parent = target_parent;\n\n // Tell the API about the changes - both to the sort order and to the parent.\n if (!skip_save) {\n this.setSortOrder(task, max_sort_order + 1, target_parent);\n }\n }",
"function isTodoCompleted(todo) {\n return todo.isDone;\n }",
"moveWorkToTop(workToMove) {\n // REMOVE THE WORK IF IT EXISTS\n this.removeWork(workToMove);\n\n // AND THEN ADD IT TO THE TOP OF THE STACK\n this.prependWork(workToMove);\n }",
"decrementTasksCompleted() {\n if (this.tasksCompleted > 0) {\n this.tasksCompleted -= 1;\n this.updateMinorLocalStorage();\n } // else I'm interested to see how you got there\n }",
"addToFront(task) {\n this._taskArr.unshift(task);\n if(this._taskArr.length > 1) {\n this.adjustAllStartTimes(1);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to downlaod svg with id 'visual' | function download () {
//get svg element.
var svg = document.getElementById("visual");
//get svg source.
var serializer = new XMLSerializer();
var source = serializer.serializeToString(svg);
//add name spaces.
if(!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)){
source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
}
if(!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)){
source = source.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
}
//add xml declaration
source = '<?xml version="1.0" standalone="no"?>\r\n' + source;
//convert svg source to URI data scheme.
var url = "data:image/svg+xml;charset=utf-8,"+encodeURIComponent(source);
//set url value to a element's href attribute.
// var downloadButton = document.getElementById("download");
var downloadLink = document.createElement("a");
downloadLink.href = url;
downloadLink.download = "graph.svg";
document.body.appendChild(downloadLink);
downloadLink.click();
// document.body.removeChild(downloadLink);
//you can download svg file by right click menu.
} | [
"_downloadSvgAsPng() {\n savesvg.saveSvgAsPng(document.getElementById(\"svg\"), \"timeline.png\");\n }",
"function getSvg(){\r\n return d3.select('svg');\r\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 getSvgXml() {\n return new XMLSerializer().serializeToString(Data.Svg.Node);\n}",
"writeDataToDom () {\r\n // remove previously set data\r\n this.node.removeAttribute('svgjs:data');\r\n\r\n if (Object.keys(this.dom).length) {\r\n this.node.setAttribute('svgjs:data', JSON.stringify(this.dom)); // see #428\r\n }\r\n\r\n return super.writeDataToDom()\r\n }",
"function grabSVG(selector){\n var svg = null;\n svg = d3.select('div#' + selector + ' svg');\n svg.attr('xmlns', 'http://www.w3.org/2000/svg');\n return svg.node();\n }",
"_updateSVG() {\n this.SVGInteractor.updateView(this.currentXRange, this.currentYRange, this.width, this.height);\n this.SVGInteractor.updateSelectView(this._currentSelectionPoints);\n }",
"async function loadSVG() {\n const response = await fetch(\"coloringBook.svg\");\n const svgData = await response.text();\n\n document.querySelector(\"#placeSvg\").innerHTML = svgData;\n registerEventListeners();\n}",
"function refreshPreview () {\n var options = {\n grid: true,\n noteNames: true,\n stripBorder: true,\n export: false\n }\n $('#preview-wrapper').html(generateSVG(options))\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 svgSaveToLocal() {\n\tremoveEventListeners();\n\thandleShapeInProgress();\n\t\n\t// generate the file string\n\tvar myFileString = svgFileHeader +\n\t\t\t\t\t\tsvgMinPrepend +\n\t\t\t\t\t\tartToString() +\n\t\t\t\t\t\tplatformToString() +\n\t\t\t\t\t\tsvgAppend;\n\t\t\t\n\t// get filename to save to\n\tmyFileName = \"art.svg\";\n\tif (msgTextInput.value != \"\") {\n\t\tmyFileName = msgTextInput.value;\n\t}\n\tif (myFileName.substr(myFileName.length - 4) != \".svg\") {\n\t\tmyFileName += \".svg\";\n\t}\n\n\t// call helper function\n\tsaveToFile(myFileName, myFileString);\n\t\n\t// debug message\n\tif (debugging) {\n\t\tconsole.log(\"Saved SVG data to file: \" + myFileName);\n\t}\n\n\t// hide message box\n\tmessageDiv.style.display = \"none\";\n}",
"clearBig(){\n const bigSVG = document.querySelector('.bigSVG')\n bigSVG.innerHTML = ''\n }",
"function downloadImage() {\n var link = document.createElement('a');\n link.download = 'diagram.png';\n link.href = myDiagram.makeImage().src;\n link.click();\n}",
"function showViz() {\n viz.show();\n}",
"svgFromFetch(url) {\r\n\t\treturn fetch(url)\r\n\t\t.then(res => res.text())\r\n\t\t.then(data => {\r\n\t\t\t// Resolve and parsing SVG\r\n\t\t\tlet doc = new DOMParser().parseFromString(data, 'text/html');\r\n\t\t\treturn doc.querySelector('svg')\r\n\t\t})\r\n\t}",
"function SVGThumbs() {\n\tvar file = document.getElementById(\"file\"); // might fail if MediaWiki can't render the SVG\n\tif (file && wgIsArticle && wgTitle.match(/\\.svg$/i)) {\n\t\tvar thumbu = file.getElementsByTagName('IMG')[0].src;\n\t\tif(!thumbu) return;\n \n\t\tfunction svgAltSize( w, title) {\n\t\t\tvar path = thumbu.replace(/\\/\\d+(px-[^\\/]+$)/, \"/\" + w + \"$1\");\n\t\t\tvar a = document.createElement(\"A\");\n\t\t\ta.setAttribute(\"href\", path);\n\t\t\ta.appendChild(document.createTextNode(title));\n\t\t\treturn a;\n\t\t}\n \n\t\tvar p = document.createElement(\"p\");\n\t\tp.className = \"SVGThumbs\";\n\t\tp.appendChild(document.createTextNode(\"This image rendered as PNG in other sizes\"+\": \"));\n\t\tvar l = [200, 500, 1000, 2000, 3000];\n for( var i = 0; i < l.length; i++ ) {\n\t\t\tp.appendChild(svgAltSize( l[i], l[i] + \"px\"));\n\t\t\tif( i < l.length-1 ) p.appendChild(document.createTextNode(\", \"));\n }\n\t\tp.appendChild(document.createTextNode(\".\"));\n\t\tvar info = getElementsByClassName( file.parentNode, 'div', 'fullMedia' )[0];\n\t\tif( info ) info.appendChild(p);\n\t}\n}",
"function updateStyle () {\n var svg = document.querySelectorAll('#' + id + ' svg > g')[0];\n\n svg.setAttribute('style', 'pointer-events: none');\n\n var diagramId = 'svg-' + id;\n var diagram = document.getElementById(diagramId);\n var height = svg.getBoundingClientRect().height + 50;\n\n diagram.setAttribute('style', 'height: ' + height + 'px;');\n }",
"function SVGThumbs() {\n\tvar file = document.getElementById(\"file\"); // might fail if MediaWiki can't render the SVG\n\tif (file && wgIsArticle && wgTitle.match(/\\.svg$/i)) {\n\t\tvar thumbu = file.getElementsByTagName('IMG')[0].src;\n\t\tif(!thumbu) return;\n \n\t\tfunction svgAltSize( w, title) {\n\t\t\tvar path = thumbu.replace(/\\/\\d+(px-[^\\/]+$)/, \"/\" + w + \"$1\");\n\t\t\tvar a = document.createElement(\"A\");\n\t\t\ta.setAttribute(\"href\", path);\n\t\t\ta.appendChild(document.createTextNode(title));\n\t\t\treturn a;\n\t\t}\n \n\t\tvar p = document.createElement(\"p\");\n\t\tp.className = \"SVGThumbs\";\n\t\tp.appendChild(document.createTextNode(\"This image rendered as PNG in other sizes\"+\": \"));\n\t\tvar l = [200, 500, 1000, 2000];\n for( var i = 0; i < l.length; i++ ) {\n\t\t\tp.appendChild(svgAltSize( l[i], l[i] + \"px\"));\n\t\t\tif( i < l.length-1 ) p.appendChild(document.createTextNode(\", \"));\n }\n\t\tp.appendChild(document.createTextNode(\".\"));\n\t\tvar info = getElementsByClassName( file.parentNode, 'div', 'fullMedia' )[0];\n\t\tif( info ) info.appendChild(p);\n\t}\n}",
"createSVGElement(w,h){const svgElement=document.createElementNS(svgNs$1,'svg');svgElement.setAttribute('height',w.toString());svgElement.setAttribute('width',h.toString());return svgElement;}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes a message on a timeout. | function deleteMessage(message) {
message.delete(deleteTimeout);
} | [
"function prevMsgDelete() {\n message.delete([300])\n .then(msg => console.log(`Deleted message from ${msg.author.username}`))\n .catch(console.error);\n }",
"async deleteMessage() {\n try {\n await AsyncStorage.removeItem('messages');\n } catch (error) {\n console.log(error.message);\n }\n }",
"function messagesDelete(token_id) {\n var where_param = '{\"name\":\"token\",\"condition\":\"EQUAL\",\"data\":\"' + token_id + '\"}';\n var del_raw_data = config.getToken(\"cloud_push\"); //Getting Tokens From Config\n del_raw_data['table_name'] = 'messages';\n del_raw_data['wheres'] = where_param;\n var del_data = querystring.stringify(del_raw_data);\n var options = config.apiOptions(\"DELETE\", del_data); //calling API options\n var del_req = http.get(options, function(resd) {\n var bodyChunks = [];\n resd.on('data', function(chunk) {\n // You can process streamed parts here...\n bodyChunks.push(chunk);\n }).on('end', function() {\n var body = Buffer.concat(bodyChunks);\n // console.log('BODY: ' + body);\n var body = JSON.parse(body);\n console.log('***********----messages table deleted----*********');\n console.log(body);\n if (body.hasOwnProperty('success')) {\n console.log(\"Messages table Success\");\n devicesDelete(token_id, unregister_device_id);\n } //on success in deleting form messages table\n else if (body.hasOwnProperty('error')) {\n console.log(\"Messages table error\");\n devicesDelete(token_id, unregister_device_id);\n }\n });\n });\n del_req.write(del_data); //sending delete request\n del_req.on('error', function(e) {\n console.log('ERROR: ' + e.message);\n }); //printing error if found\n }",
"function deleteMessage(chatId, messageId, message, userId) {\n\tvar config = { chat_id: chatId, message_id: messageId };\n\taxios.post('https://api.telegram.org/bot' + RynodObjects.API + '/deleteMessage', config ) \n\t.then(response => {\n\t\tif (userId === 0) return;\n\t\tvar deletedMessage = { \n\t\t\tdate: + new Date(),\n\t\t\tchat_id: chatId,\n\t\t\tmessage_id: messageId,\n\t\t\tuser_id: userId,\n\t\t\tmessage: message\n\t\t}\n\t\t//use the database_op\n\t\tRynodObjects.Db.DeletedMessages.insert(deletedMessage, function (err, newDoc) {\n\t\t console.log(\"Deleted Message. Message ID: \"+newDoc.message+\", Chat ID: \"+newDoc.chat_id)\n\t\t});\n })\n .catch(err => {\n\t\tconsole.log('Error :', err)\n });\n}",
"deleteMessage(id) {\n const self = this;\n const model = this.application.getModel();\n\n const confirmComplete = function f() {\n model.deleteMessageById(id);\n self.render();\n self.application.renderDiagram();\n };\n\n this.application.showConfirmDialog(\n 'Delete this message?',\n confirmComplete\n );\n }",
"unlockMessage() {\n // if message is over a day old (10 seconds for testing), unlock it and allow deletion\n if(Date.now() - this.posted > 10000) {\n this.isLocked = false;\n }\n }",
"function remove(message) {\n //Get the index of the message to be removed\n var idx = messages.indexOf(message);\n messages.splice(idx, 1);\n }",
"function deleteMessage(req, res, user) {\n // Get the message ID.\n var messageID = parseInt(req.params.id);\n\n if (!messageID || messageID < 0) {\n res.status(400).json({message: 'invalid id'});\n\n return;\n }\n\n MessageController.getByMID(messageID)\n .then((message) => {\n if (message.recipient != user.userID) {\n res.status(403).json({message: 'not allowed'});\n\n return;\n }\n\n MessageController.deleteByMID(messageID);\n res.json({message: 'success'});\n });\n}",
"function OnMessageTimeOut(id) {\n\n\tif (id == DVDMSGTIMER) {\n\t\tMessage.Text = \"\";\n\t\tMessageFull.Text = \"\";\n if (g_LTRReading)\n {\n xCoord = TitleFull.TextWidth;\n }\n else\n {\n xCoord = g_ConWidth - TitleFull.TextWidth - MessageFull.TextWidth - g_nButPosFull[g_nIndexMessage][0];\n }\n yCoord = g_nButPos[g_nIndexMessage][1] - 1000;\n\n\t\tMFBar.SetObjectPosition(\"MessageFull\", xCoord, yCoord,\n\t\t\tMessageFull.TextWidth, g_nButPosFull[g_nIndexMessage][3]);\n\n if (g_LTRReading)\n {\n xCoord = Title.TextWidth;\n }\n else\n {\n xCoord = g_ConWidth - Title.TextWidth - Message.TextWidth - g_nButPos[g_nIndexMessage][0];\n }\n yCoord = g_nButPos[g_nIndexMessage][1];\n\n\t\tMFBar.SetObjectPosition(\"Message\", xCoord, yCoord,\n\t\t\tMessage.TextWidth, g_nButPos[g_nIndexMessage][3]);\n\t}\n\n\telse if (id == FOCUSTIMER) {\n\t\tif (MFBar.ObjectEnabled(g_strFocusObj)) {\n\t\t\tbtn = MFBar.GetObjectUnknown(g_strFocusObj);\n\t\t\tif (!btn.Disable)\n\t\t\t\tMFBar.SetObjectFocus(g_strFocusObj, true);\n\t\t}\n\t\telse {\n\t\t}\n\t}\n}",
"function sendTimedMessage(userId, message, seconds) {\r\n setTimeout( function() {sendMessage(userId, message) }, seconds);\r\n}",
"quit(timeout = 0) {\r\n const lines = [];\r\n const handler = (line) => lines.push(line);\r\n const command = `QUIT\\r\\n`;\r\n return super.write(command, handler, timeout).then((code) => {\r\n if (code.charAt(0) === '2') {\r\n return code;\r\n }\r\n else {\r\n throw this._createSMTPResponseError(lines);\r\n }\r\n });\r\n }",
"function unloadMessage(){\r\n $(\"#printMessageBox\").delay(1000).animate({opacity:0}, 700, function(){\r\n $(this).remove();\r\n });\r\n }",
"async deleteSmartACKMailbox(){\n\t\tconst data = Buffer.from([0x0a, 0x05, 0x83, 0x4b, 0x83, 0x01, 0x9d, 0x45, 0x44]);\n\t\tawait this.sendData(this, data, null, 6);\n\t\tconst response = await this.waitForResponse();\n\t\tconst telegram = new HandleType2(this, response);\n\t\tconsole.log(`Delet Smart ACK mailbox: ${JSON.stringify(telegram.main)}`);\n\t}",
"function setMessageDeleted (message_id){\n\tconst delete_msg = `<p>---CHAT DELETED---</p>`\n\tdocument.getElementById(message_id).innerHTML = delete_msg;\n\n}",
"function cleanupReplies(message, userId) {\n bot.channels.get(curryBotChannel).fetchMessages().then(function(messages) {\n messages.forEach(function (msg) {\n if (msg.author.bot && msg.id !== message.id && msg.mentions.users.first()) {\n if (msg.mentions.users.first().id === userId) {\n msg.delete().then(function() {\n console.log(msg.id + \" deleted.\");\n }).catch(err => console.log(err));\n }\n }\n })\n }).catch(err => console.log(err));\n}",
"function auto_remove_sanction() {\n if (timeout != null) client.clearTimeout(timeout);\n db.query(\"SELECT id, serveur_id FROM sanction WHERE date + duration *interval'1 second' < now()\")\n .then( res => {\n // retirer toutes les sanctions terminรฉes\n for (let i=0 ; i<res.rowCount ; i++) {\n let id = res.rows[i].id;\n let guild = client.guilds.get(res.rows[i].serveur_id);\n require('./command/cancel')(['', id], guild, null, null, '!cancel '+id, null, null);\n }\n\n // set timeout before cancel next sanction\n return db.query(\"SELECT EXTRACT(EPOCH FROM date + duration *interval'1 second' -now()) AS delay FROM sanction WHERE duration IS NOT NULL ORDER BY (date + duration *interval'1 second') DESC LIMIT 1;\");\n })\n .then( res => {\n if (res.rowCount == 1)\n timeout = client.setTimeout(auto_remove_sanction, res.rows[0].delay);\n })\n .catch( err => {\n console.log(\"============= TimeOut Error =============\");\n console.log(err);\n timeout = client.setTimeout(auto_remove_sanction, 5000); // on error wait 5 sec and redo it..\n });\n}",
"remove(clientID) {\n var c = this.clients.get(clientID);\n if (!c) return;\n c.setTimer(null);\n c.deregister();\n this.clients.delete(clientID);\n\n debug(\"Removed client %s from room %s\", clientID, this.id);\n if (this.empty() && this.ecb) this.ecb();\n }",
"removeMessage(keyNum){\n this.messages.delete(keyNum)\n return this;\n }",
"function purgeQueue() {\n\tconsole.log(\"[x] Cleanup started..\");\n\tvar d = new Date();\n\tfor (var q in sending_queue_map) {\n\t\tif (d - sending_queue_map[q].lastAccessed >= INACTIVE_TIMEOUT_MILLS) {\n\t\t\t// purge this\n\t\t\tconsole.log(\"[x] Requesting to delete '\" + q + \"'..\");\n\t\t\tsenderChannel.sendToQueue(\n\t\t\t\tCOMMAND_QUEUE,\n\t\t\t\tBuffer.from(\n\t\t\t\t\t\"remove \" + q + \" \" + sending_queue_map[q].receivingQueue\n\t\t\t\t)\n\t\t\t);\n\t\t\tdelete sending_queue_map[q];\n\t\t\tdelete pendingChanges[q];\n\t\t}\n\t}\n\tconsole.log(\"[x] Cleanup finished..\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle months error message for periods | function showMonthsPeriodErrorIfPresent(error, id) {
if (!isEmpty(error)) {
$("#monthsError_"+id).text(error);
}
} | [
"function getValidMonth(){\r\n\treturn 3;\r\n}",
"function DateTimeDayMonth() { }",
"function hasProperDaysPerMonth(element){\n\t\n\t\t// months of the year\t\n\t\tvar MONTHS_ARRAY = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \n\t\t\t\"September\", \"October\", \"November\", \"December\"];\n\n\t\t// months with default days per month\t\t\n\t\tvar MONTHS_DAYS = {\n\t\t\t\"January\" : 31, \"February\":28, \"March\": 31, \"April\": 30, \"May\" : 31, \"June\" : 30, \"July\" : 31,\n\t\t\t\"August\" : 31, \"September\" : 30, \"October\" : 31, \"November\" : 30, \"December\" : 31\t\t\n\t\t};\n\t\t\n\t\t// MONTH_ARRAY begins at zero index (months 0-11); user's months are 1-12.\n\t\tvar MONTH_OFFSET = 1; \n\t\n\t\t// trim potential white space from user's input\n\t\tvar date = element.value.trim();\n\t\t\n\t\t// split mm/dd/yyyy string on \"/\" and store in array.\n\t\tvar dateArray = date.split(\"/\");\n\t\t\n\t\t// radix for parseInt\n\t\tvar RADIX = 10;\n\t\t\n\t\t// assign contents of array to variables\n\t\tvar month = parseInt(dateArray[0], RADIX) - MONTH_OFFSET;\t// subtract offset\n\t\tvar day = parseInt(dateArray[1], RADIX);\n\t\tvar year = parseInt(dateArray[2], RADIX);\n\t\t\n\t\t// if leap year increase February to 29 days.\t\t\n\t\tif(isLeapYear(year)){\n\t\t\n\t\t\tMONTHS_DAYS.February = 29;\n\t\t\t\n\t\t}//else do nothing.\n\t\t\n\t\t// check if user's input days exceed number of days the month should have\n\t\tif(day > MONTHS_DAYS[MONTHS_ARRAY[month]]){\n\t\t\n\t\t\t// User input has too many days\n\t\t\talert(MONTHS_ARRAY[month] +\" can't have \" + day + \" days in it, not in \" + year + \", anyway.\");\n\t\t\t\n\t\t\t// shift webpage focus to failed field\n\t\t\telement.focus();\n\t\t\t\n\t\t\t// failed test\n\t\t\treturn false;\n\t\t\t\n\t\t}else{\n\t\t\n\t\t\t// passed test\n\t\t\treturn true;\n\t\t\t\n\t\t}\t\t\n\t}",
"function _getMonth(m) {\n\t\tif(mc.os.config.translations) {\n\t\t\treturn mc.os.config.translations.pc.settings.nodes['_constants'].months[m];\n\t\t} else {\n\t\t\treturn $MONTHS[m];\n\t\t}\n\t}",
"function parse_months() {\n var raw_months = month_date_textbox.getValue();\n var months_to_list = raw_months.split(\"-\");\n return months_to_list;\n}",
"setMonths(state) {\n let months = [\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\",\"10\",\"11\",\"12\"]\n this.commit(\"setMonths\", months)\n }",
"function renderMonth() {\r\n // Creo un oggetto moment con anno e mese scelti\r\n var momentObject = {\r\n \"year\": startYear,\r\n \"month\": startMonth\r\n };\r\n\r\n // Creo una data moment.js passando l'oggetto creato\r\n var momentDate = moment(momentObject);\r\n // Ottengo il numero di giorni nel mese selezionato\r\n var daysInMonth = momentDate.daysInMonth();\r\n\r\n // Modifico il titolo in base al mese scelto\r\n $(\"h1\").text(momentDate.format(\"MMMM YYYY\"));\r\n\r\n // Per ognuno dei giorni nel mese, modifico il context e compilo il template\r\n for (var i = 1; i <= daysInMonth; i++) {\r\n var context = {\r\n \"day\": i,\r\n \"month\": momentDate.format(\"MMMM\")\r\n }\r\n\r\n // Compilo il template e lo aggiungo alla lista sulla pagina\r\n var html = template(context);\r\n $(\"ul.month-display\").append(html);\r\n }\r\n }",
"function validateAmortization(errorMsg) {\n var tempAmortization = document.mortgage.amortization.value;\n tempAmortization = tempAmortization.trim();\n var tempAmortizationLength = tempAmortization.length;\n var tempAmortizationMsg = \"Please enter Amortization!\";\n\n if (tempAmortizationLength == 0) {\n errorMsg += \"<p><mark>No. of years field: </mark>Field is empty <br />\" + tempAmortizationMsg + \"</p>\";\n } else {\n if (isNaN(tempAmortization) == true) {\n errorMsg += \"<p><mark>No. of years field: </mark>Must be numeric <br />\" + tempAmortizationMsg + \"</p>\";\n } else {\n if (tempAmortization < 5 || tempAmortization > 20) {\n errorMsg += \"<p><mark>No. of years field: </mark>Must be values: 5 thru 20 inclusive <br />\" + tempAmortizationMsg + \"</p>\";\n }\n }\n }\n return errorMsg;\n}",
"function common_dateWarning(period, timeLimit, ngaybd, ngaykt)\n{\n\n limitJson = JSON.parse(timeLimit);\n\tvar message = '';\n\n\tif(period != '')\n\t{\n var limit;\n\t\tvar retval;\n\t\tvar suffix;\n\t\tvar prefix = Language.translate('CONFIRM_DATE_OVER');\n\t\tvar startArr = ngaybd.split(\"-\");\n\t\tvar endArr = ngaykt.split(\"-\");\n\t\tvar start = new Date( parseInt(startArr[2]), parseInt(startArr[1]) - 1, parseInt(startArr[0]));\n\t\tvar secondDate = new Date();\n\t\tvar secondDateLimit = new Date();\n\t\t\n\t\tswitch(period)\n\t\t{\n\t\t\tcase 'D':\n limit = (limitJson['D'] != undefined && !isNaN(limitJson['D']))?limitJson['D']:0;\n limit = parseInt(limit);\n\t\t\t\tstart.setDate(start.getDate() + limit - 1); \n\t\t\t\tsuffix = Language.translate('CONFIRM_DATE_OVER_DAYS');\n\t\t\tbreak;\n\t\t\tcase 'W':\n limit = (limitJson['W'] != undefined && !isNaN(limitJson['W']))?limitJson['W']:0;\n limit = parseInt(limit);\n\t\t\t\tstart.setDate(start.getDate() + (limit *7 ) -1);\n\t\t\t\tsuffix = Language.translate('CONFIRM_DATE_OVER_WEEKS');\n\t\t\tbreak;\n\t\t\tcase 'M':\n limit = (limitJson['M'] != undefined && !isNaN(limitJson['M']))?limitJson['M']:0;\n limit = parseInt(limit);\n\t\t\t\tstart.setMonth(start.getMonth() + limit);\n\t\t\t\tstart.setDate(start.getDate() - 1);\n\t\t\t\tsuffix = Language.translate('CONFIRM_DATE_OVER_MONTHS');\n\t\t\tbreak;\n\t\t\tcase 'Q':\n limit = (limitJson['Q'] != undefined && !isNaN(limitJson['Q']))?limitJson['Q']:0;\n limit = parseInt(limit);\n\t\t\t\tstart.setMonth(start.getMonth() + limit);\n\t\t\t\tstart.setDate(start.getDate() - 1);\n\t\t\t\tsuffix = Language.translate('CONFIRM_DATE_OVER_QUARTERS');;\n\t\t\tbreak;\n\t\t\tcase 'Y':\n limit = (limitJson['Y'] != undefined && !isNaN(limitJson['Y']))?limitJson['Y']:0;\n limit = parseInt(limit);\n\t\t\t\tstart.setYear(start.getFullYear() + limit); \n\t\t\t\tstart.setDate(start.getDate() - 1); \n\t\t\t\tsuffix = Language.translate('CONFIRM_DATE_OVER_YEARS');\n\t\t\tbreak;\t\t\t\t\t\t\t\t\n\t\t}\n\t\tsecondDate.setFullYear(parseInt(endArr[2]), parseInt(endArr[1]) - 1, parseInt(endArr[0]));\n\t\tsecondDateLimit.setFullYear(start.getFullYear(), start.getMonth(), start.getDate());\n\n\t\tif( (secondDateLimit < secondDate ) && (limit > 0) )\n\t\t{\n\t\t\tmessage = prefix + ' ' + limit + ' ' + suffix;\n\t\t}\n\t}\n\treturn message;\n}",
"function validateStandardDate(due){\n var mess = \"\";\n if (due == \"\") {\n return mess;\n }\n var patt = /^20[0-9]{2}\\/[01][0-9]\\/[0-3][0-9]$/;\n var tmp = patt.exec(due);\n if (tmp == \"\") {\n return \"Date must take form YYYY/MM/DD.\";\n }\n return tmp;\n\n var DDcap = new Array();\n DDcap[0] = 31;\n DDcap[1] = 28;\n DDcap[2] = 31;\n DDcap[3] = 30;\n DDcap[4] = 31;\n DDcap[5] = 30;\n DDcap[6] = 31;\n DDcap[7] = 31;\n DDcap[8] = 30;\n DDcap[9] = 31;\n DDcap[10] = 30;\n DDcap[11] = 31;\n var PYY = /^[0-9]{1,4}/;\n var YY = parseInt(PYY.exec(due), 10);\n var PTMM = /\\/[0-9]{1,2}\\//;\n var TMM = PTMM.exec(due);\n var PMM = /[0-9]{1,2}/;\n var MM = parseInt(PMM.exec(TMM), 10);\n var PDD = /[0-9]{1,2}$/;\n var DD = parseInt(PDD.exec(due), 10);\n var t = new Date();\n //var et = (t.getTime() - t.getMilliseconds())/1000 - 1293840000; // time since 0:00:00 on Jan 1, 2011\n var bau = true;\n if(YY < 2013){\n mess = \"Date must take form YYYY/MM/DD. \";\n }\n if(MM > 12 || MM < 1){\n mess = \"Date must take form YYYY/MM/DD. \";\n }\n if(DD > DDcap[MM-1] && !(DD==29 && MM==2 && YY % 4 == 0) || DD == 0){\n mess += \"The date you entered is invalid for the month selected\";\n }\n return mess;\n}",
"function isValidYrMonth(dtStr, FromToCheck){\n\n re = new RegExp(\"/\",\"g\");\n var dtStr = dtStr.replace(re,\"\");\n\n if(!isInteger(dtStr)){\n return false;\n }\n if(dtStr == '000000' && FromToCheck == '1'){\n return false;\n }\n if(dtStr == '999999' && FromToCheck == '2'){\n return false;\n }\n var month;\n var year;\n if(dtStr.length != 6) {\n return false;\n }\n year = dtStr.substring (0, 4);\n month = dtStr.substring (4, 6);\n\n if(year.length != 4 ){\n return false;\n }\n if(month.length != 2 ){\n return false;\n }\n if(month < \"01\" || month > \"12\"){\n return false;\n }\n if(year < \"1000\" || year > \"9999\"){\n return false;\n }\n return true\n}",
"function isMonthSelected() {\n //create a variable that targets the month box\n //give month box class name of not-valid if value not selected\n const monthBox = document.querySelector('.month-box');\n const expMon = document.querySelector('#exp-month');\n monthBox.addEventListener('click', (e) => {\n if(monthBox != null) {\n expMon.classList.remove('error-border');\n monthBox.classList.remove('not-valid');\n monthBox.classList.add('valid');\n return true;\n } else { \n expMon.classList.add('error-border');\n monthBox.classList.add('not-valid');\n monthBox.classList.remove('valid');\n }\n \n });\n }",
"function setMonth() {\n\tvar element = document.getElementById(\"selected_month\");\n\tMONTH = element.options[element.selectedIndex].value;\n\tsetDateContent(MONTH, YEAR);\n}",
"function getMonthlyHolidays() {\n calendarificURL = \"https://calendarific.com/api/v2/holidays?&api_key=\" + cAPIkey + \"&country=\" + countries[country].abbr + \"&year=2021&type=national,local,religious\";\n var trueMonths = [];\n $.ajax({\n url: calendarificURL,\n method: \"GET\"\n }).then(function (calendarResponse) {\n for (var m = 1; m < 13; m++) {\n for (var i = 0; i < calendarResponse.response.holidays.length; i++) {\n if (calendarResponse.response.holidays[i].date.datetime.month === m) {\n var index = m - 1;\n trueMonths.push((Object.keys(months)[index]));\n break;\n }\n }\n }\n var message1 = $(\"<p>\").text(\"There are no holidays in \" + country + \" in \" + month + \" in our database.\")\n var message2 = $(\"<p>\").text(country + \" has holidays in \" + trueMonths.join(\", \") + \".\")\n $(\"#messageDiv\").append(message1).append(message2);\n })\n}",
"function monthlyReport() {\n\n}",
"nameMonths() {\n var d = new Date()\n var mount = d.getMonth()\n var months = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December'\n ]\n\n return [\n {label: months[(mount != 0) ? (mount - 1) : 11], value: 'lastMonth'},\n {label: months[mount], value: 'currentMonth'},\n {label: 'Today', value: 'today'}\n ]\n }",
"function updateMonths(minMonth, maxMonth) {\n var selectedyear = getValue('year') || 0;\n var fmt;\n\n if (minMonth == null) {\n minMonth = 0;\n }\n\n if (maxMonth == null) {\n maxMonth = 11;\n }\n\n function _dateRange(year, range) {\n range -= 1;\n\n if ($('#year').is(':visible')) {\n return function (m) {\n return $.datepick.formatDate('M y',\n new Date(selectedyear, m - range)) + ' – ' +\n $.datepick.formatDate('M y',\n new Date(selectedyear, m));\n }\n } else {\n return function (m) {\n return $.datepick.formatDate('M',\n new Date(selectedyear, m - range)) + ' – ' +\n $.datepick.formatDate('M',\n new Date(selectedyear, m));\n }\n }\n }\n\n switch (ocean.period) {\n case 'hourly':\n fmt = function (m) {\n return $.datepick.formatDate('MM',\n new Date(selectedyear, m));\n };\n break;\n\n case 'monthly':\n fmt = function (m) {\n return $.datepick.formatDate('MM',\n new Date(selectedyear, m));\n };\n break;\n\n case '3monthly':\n fmt = _dateRange(selectedyear, 3);\n break;\n\n case '6monthly':\n fmt = _dateRange(selectedyear, 6);\n break;\n\n case '12monthly':\n fmt = _dateRange(selectedyear, 12);\n break;\n\n case 'yearly':\n /* ignore */\n return;\n\n default:\n console.error(\"ERROR: should not be reached\");\n return;\n }\n\n var month = $('#month');\n\n month.find('option').remove();\n\n for (m = minMonth; m <= maxMonth; m++) {\n $('<option>', {\n value: m,\n html: fmt(m)\n }).appendTo(month);\n }\n\n var selectedmonth = ocean.date.getMonth();\n\n if (selectedmonth < minMonth) {\n selectFirstIfRequired('month');\n } else if (selectedmonth > maxMonth) {\n month.find('option:last').attr('selected', true);\n month.change();\n } else {\n setValue('month', selectedmonth);\n }\n}",
"function buildMonth(start, month){\n var done = false, date = start.clone(), monthIndex = date.month(), count = 0;\n monthArray = [];\n $scope.month = moment().month(start.month() +1).format('MMMM');\n var viewedMonth = moment().month(start.month() +1);\n $scope.viewedMonth = viewedMonth.month();\n while (!done) {\n monthArray.push({ days: buildWeek(date.clone(), month, viewedMonth) });\n date.add(1, \"w\");\n done = count++ > 2 && monthIndex !== date.month();\n monthIndex = date.month();\n }\n var filterForBadWeek = [];\n filterForBadWeek = _.filter(monthArray[0].days, {'number': 1 })\n\n if (filterForBadWeek.length == 0){\n monthArray.shift();\n }\n $scope.monthArray = monthArray;\n\n console.log('Currently viewed month Array', $scope.monthArray);\n\n }",
"function changeMonth(months){\n Calendar.today = addMonth(Calendar.today, months);\n buildCalendar();\n displayAppointments();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles object size & sprite updates. Should get rid of this in favor of accessors. | function __handle_sprite__(_object_) {
if (_object_.sprite_index == null) return;
_object_.sprite_width = _object_.sprite_index.width;
_object_.sprite_height = _object_.sprite_index.height;
_object_.sprite_xoffset = _object_.sprite_index.xoffset;
_object_.sprite_yoffset = _object_.sprite_index.yoffset;
_object_.image_number = _object_.sprite_index.frames.length;
_object_.image_index += _object_.image_speed;
if (_object_.image_index >= _object_.image_number) _object_.image_index = _object_.image_index % _object_.image_number;
if (_object_.image_index < 0) _object_.image_index = _object_.image_number - 1 + (_object_.image_index % _object_.image_number);
} | [
"function massOfObjAChange(scope) {\n mass_ball_a = scope.mass_of_a;\n getChild(\"ball_a\").scaleX = 0.5 + (scope.mass_of_a - 1) / 20;\n getChild(\"ball_a\").scaleY = 0.5 + (scope.mass_of_a - 1) / 20;\n ball_a_radius = (getChild(\"ball_a\").image.height * getChild(\"ball_a\").scaleY) / 2;\n}",
"update()\n {\n for(let i = 0; i < this.sprites.length; i++)\n {\n this.sprites[i].update();\n }\n }",
"function massOfObjBChange(scope) {\n mass_ball_b = scope.mass_of_b;\n getChild(\"ball_b\").scaleX = 0.5 + (scope.mass_of_b - 1) / 20;\n getChild(\"ball_b\").scaleY = 0.5 + (scope.mass_of_b - 1) / 20;\n ball_b_radius = (getChild(\"ball_b\").image.height * getChild(\"ball_b\").scaleY) / 2;\n}",
"_updateHeight() {\n this._updateSize();\n }",
"__update() {\n this.__gameObjects.update();\n this.getCurrentEvents().flush();\n }",
"_updateYPosition() {\n this._updateSize();\n }",
"positionElementsOnResize() {\n this.spritePlane.position.x = this.width / 2;\n this.spritePlane.position.y = this.height / 2;\n }",
"update() {\n //Fill the rectangle at the new position\n this.context.fillRect(this.x, this.y, this.width, this.height);\n //Check if the wall is top or bottom\n\t\tif (this.isTop) {\n //Draw the new image position\n\t\t\tthis.context.drawImage(this.topImage, this.x, this.y, this.width, this.height);\n\t\t} else {\n //Draw the new image position\n\t\t\tthis.context.drawImage(this.bottomImage, this.x, this.y, this.width, this.height);\n\t\t}\t\n }",
"update(deltaTime, maxX, maxY) {\n if(this.x + this.width > maxX) {\n this.x = maxX - this.width;\n }\n \n if(this.x < 0) {\n this.x = 0;\n }\n \n if(this.y + this.height > maxY) {\n this.y = maxY - this.height;\n }\n \n if(this.y < 0) {\n this.y = 0;\n }\n \n /* Update the Objects contained within this Object */\n for(var i = 0; i < this.objects.length; i++) {\n this.objects[i].update(deltaTime, maxX, maxY);\n }\n \n if(this.propertiesWindowVisible)\n this.propertiesWindow.update(deltaTime, maxX, maxY); // Update the properties windows coordinates\n }",
"update() {\n if(!this.valid) return;\n _wl_renderer_updateTexture(this._id, this._imageIndex);\n }",
"changeSize() {\n // Calculate the distance between the mouse and the center of the shape\n this.distanceFromCenterX = mouseX - this.x;\n this.distanceFromCenterY = mouseY - this.y;\n // Change width and height according to the mouse position\n this.width = 2 * (this.distanceFromCenterX);\n this.height = 2 * (this.distanceFromCenterY);\n }",
"function updateDimensions() {\n styleContentElements();\n parentDimensions = getParentDimensions();\n playerDimensions = getPlayerDimensions();\n }",
"updateSprite() {\n\t\tif(!this.multiTexture) {\n\t\t\tthis.graphics.sprite.texture = PIXI.Texture.fromFrame('sprite_' + (this.id < 10 ? '0' : '') + this.id + '.png');\n\t\t}\n\t\telse {\n\t\t\tthis.graphics.sprite.texture = PIXI.Texture.fromFrame('sprite_' + (this.id < 10 ? '0' : '') + this.id + '_' +\n\t\t\t\t\t\t\t\t\t\t\t(this.multiTextureId < 10 ? '0' : '') + this.multiTextureId + '.png');\n\t\t}\n\t}",
"updateAndRender(){\n if (this.scene) {\n this.calculateSquareLayout();\n this.updateSquares();\n this.updateYPos();\n this.updateTexture();\n this.updateUniforms();\n this.scene.render();\n }\n }",
"updateSquares() {\n if(this.squareProps.length !== this.squares.length) {\n const diff = this.squareProps.length - this.squares.length;\n if(diff > 0) {\n for (let i = 0; i < diff; i++) {\n let newSquareInstance = this.baseSquare.createInstance(\"\" + i);\n this.squares.push(newSquareInstance);\n }\n } else {\n while(this.squares.length > this.squareProps.length) {\n const inst = this.squares[this.squares.length - 1];\n inst.dispose();\n this.squares.pop();\n }\n }\n }\n for (let i = 0; i < this.squareProps.length; i++) {\n const props = this.squareProps[i];\n const square = this.squares[i];\n square.position.x = props.x;\n square.position.y = -props.y;\n square.scaling.x = props.w;\n square.scaling.y = props.h;\n }\n\n this.scene.executeWhenReady(() => {\n this.scene.render();\n })\n }",
"_refresh(){\n this._refreshSize();\n this._refreshPosition();\n }",
"function update() {\n\tchangeSpeed(game_object);\n\tchangeLivesOfPlayer(game_object);\n\thackPlayerScore(game_object);\n}",
"render(lagOffset = 1) {\n\n //Calculate the sprites' interpolated render positions if\n //`this.interpolate` is `true` (It is true by default)\n\n if (this.interpolate) {\n\n //A recursive function that does the work of figuring out the\n //interpolated positions\n let interpolateSprite = (sprite) => {\n\n\n //Position (`x` and `y` properties)\n if(this.properties.position) {\n\n //Capture the sprite's current x and y positions\n sprite._currentX = sprite.x;\n sprite._currentY = sprite.y;\n\n //Figure out its interpolated positions\n if (sprite._previousX !== undefined) {\n sprite.x = (sprite.x - sprite._previousX) * lagOffset + sprite._previousX;\n }\n if (sprite._previousY !== undefined) {\n sprite.y = (sprite.y - sprite._previousY) * lagOffset + sprite._previousY;\n }\n }\n\n //Rotation (`rotation` property)\n if(this.properties.rotation) {\n\n //Capture the sprite's current rotation\n sprite._currentRotation = sprite.rotation;\n\n //Figure out its interpolated rotation\n if (sprite._previousRotation !== undefined) {\n sprite.rotation = (sprite.rotation - sprite._previousRotation) * lagOffset + sprite._previousRotation;\n }\n } \n\n //Size (`width` and `height` properties)\n if(this.properties.size) {\n \n //Only allow this for Sprites or MovieClips. Because\n //Containers vary in size when the sprites they contain\n //move, the interpolation will cause them to scale erraticly\n if (sprite instanceof this.Sprite || sprite instanceof this.MovieClip) {\n\n //Capture the sprite's current size\n sprite._currentWidth = sprite.width;\n sprite._currentHeight = sprite.height;\n\n //Figure out the sprite's interpolated size\n if (sprite._previousWidth !== undefined) {\n sprite.width = (sprite.width - sprite._previousWidth) * lagOffset + sprite._previousWidth;\n }\n if (sprite._previousHeight !== undefined) {\n sprite.height = (sprite.height - sprite._previousHeight) * lagOffset + sprite._previousHeight;\n }\n }\n }\n\n //Scale (`scale.x` and `scale.y` properties)\n if(this.properties.scale) {\n \n //Capture the sprite's current scale\n sprite._currentScaleX = sprite.scale.x;\n sprite._currentScaleY = sprite.scale.y;\n\n //Figure out the sprite's interpolated scale\n if (sprite._previousScaleX !== undefined) {\n sprite.scale.x = (sprite.scale.x - sprite._previousScaleX) * lagOffset + sprite._previousScaleX;\n }\n if (sprite._previousScaleY !== undefined) {\n sprite.scale.y = (sprite.scale.y - sprite._previousScaleY) * lagOffset + sprite._previousScaleY;\n }\n }\n\n //Alpha (`alpha` property)\n if(this.properties.alpha) {\n\n //Capture the sprite's current alpha\n sprite._currentAlpha = sprite.alpha;\n\n //Figure out its interpolated alpha\n if (sprite._previousAlpha !== undefined) {\n sprite.alpha = (sprite.alpha - sprite._previousAlpha) * lagOffset + sprite._previousAlpha;\n }\n } \n\n //Tiling sprite properties (`tileposition` and `tileScale` x\n //and y values)\n if (this.properties.tile) {\n\n //`tilePosition.x` and `tilePosition.y`\n if (sprite.tilePosition !== undefined) {\n\n //Capture the sprite's current tile x and y positions\n sprite._currentTilePositionX = sprite.tilePosition.x;\n sprite._currentTilePositionY = sprite.tilePosition.y;\n\n //Figure out its interpolated positions\n if (sprite._previousTilePositionX !== undefined) {\n sprite.tilePosition.x = (sprite.tilePosition.x - sprite._previousTilePositionX) * lagOffset + sprite._previousTilePositionX;\n }\n if (sprite._previousTilePositionY !== undefined) {\n sprite.tilePosition.y = (sprite.tilePosition.y - sprite._previousTilePositionY) * lagOffset + sprite._previousTilePositionY;\n }\n }\n\n //`tileScale.x` and `tileScale.y`\n if (sprite.tileScale !== undefined) {\n\n //Capture the sprite's current tile scale\n sprite._currentTileScaleX = sprite.tileScale.x;\n sprite._currentTileScaleY = sprite.tileScale.y;\n\n //Figure out the sprite's interpolated scale\n if (sprite._previousTileScaleX !== undefined) {\n sprite.tileScale.x = (sprite.tileScale.x - sprite._previousTileScaleX) * lagOffset + sprite._previousTileScaleX;\n }\n if (sprite._previousTileScaleY !== undefined) {\n sprite.tileScale.y = (sprite.tileScale.y - sprite._previousTileScaleY) * lagOffset + sprite._previousTileScaleY;\n }\n } \n }\n \n //Interpolate the sprite's children, if it has any\n if (sprite.children.length !== 0) {\n for (let j = 0; j < sprite.children.length; j++) {\n\n //Find the sprite's child\n let child = sprite.children[j];\n\n //display the child\n interpolateSprite(child);\n }\n }\n };\n \n //loop through the all the sprites and interpolate them\n for (let i = 0; i < this.stage.children.length; i++) {\n let sprite = this.stage.children[i];\n interpolateSprite(sprite);\n } \n }\n\n //Render the stage. If the sprite positions have been\n //interpolated, those position values will be used to render the\n //sprite\n this.renderer.render(this.stage);\n\n //Restore the sprites' original x and y values if they've been\n //interpolated for this frame\n if (this.interpolate) {\n\n //A recursive function that restores the sprite's original,\n //uninterpolated x and y positions\n let restoreSpriteProperties = (sprite) => {\n if(this.properties.position) {\n sprite.x = sprite._currentX;\n sprite.y = sprite._currentY;\n }\n if(this.properties.rotation) {\n sprite.rotation = sprite._currentRotation;\n }\n if(this.properties.size) {\n\n //Only allow this for Sprites or Movie clips, to prevent\n //Container scaling bug\n if (sprite instanceof this.Sprite || sprite instanceof this.MovieClip) {\n sprite.width = sprite._currentWidth;\n sprite.height = sprite._currentHeight;\n }\n }\n if(this.properties.scale) {\n sprite.scale.x = sprite._currentScaleX;\n sprite.scale.y = sprite._currentScaleY;\n }\n if(this.properties.alpha) {\n sprite.alpha = sprite._currentAlpha;\n }\n if(this.properties.tile) {\n if (sprite.tilePosition !== undefined) {\n sprite.tilePosition.x = sprite._currentTilePositionX;\n sprite.tilePosition.y = sprite._currentTilePositionY;\n }\n if (sprite.tileScale !== undefined) {\n sprite.tileScale.x = sprite._currentTileScaleX;\n sprite.tileScale.y = sprite._currentTileScaleY;\n }\n }\n\n //Restore the sprite's children, if it has any\n if (sprite.children.length !== 0) {\n for (let i = 0; i < sprite.children.length; i++) {\n\n //Find the sprite's child\n let child = sprite.children[i];\n\n //Restore the child sprite properties\n restoreSpriteProperties(child);\n }\n }\n };\n for (let i = 0; i < this.stage.children.length; i++) {\n let sprite = this.stage.children[i];\n restoreSpriteProperties(sprite);\n }\n }\n }",
"update() {\r\n\t\tthis.flock();\r\n\t\tthis.drawBoid();\r\n\t}",
"setSize(\n width, // The width of the game.\n height // The height of the game.\n ) {\n const { game } = this;\n if (width > 0) {\n game.width = width;\n }\n if (height > 0) {\n game.height = height;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checking preferences setup on the index page | function checkPreferences() {
// Check for preferences
if (typeof (Storage) !== "undefined" && window.location.pathname.indexOf("dashboard.php") === -1) {
var location_value = localStorage.location;
if (location_value !== undefined && location_value !== "") {
var element = document.getElementById('location');
if (element !== null && element !== undefined) {
element.value = location_value;
// Check off that req field is now valid
flipInputGroupIcon(".location .input-group-addon", "ok");
}
}
}
} | [
"function checkSettings() {\n\tconsole.log('--checking for db settings...');\n\tlet settings;\n\ttry {\n\t\tsettings = db.getData('/settings');\n\t} catch (err) {\n\t\tsettings = {\n\t\t\twhiteList: [],\n\t\t\tlandingBg: {\n\t\t\t\tenable: false,\n\t\t\t\turl: ''\n\t\t\t},\n\t\t\tautoCrop: true\n\t\t};\n\t\tdb.push('/settings', settings);\n\t}\n}",
"function setupSearchPreferences(){\r\n\t\t// Set the initial search preferences, which are updated everytime a search is performed\r\n\t\tif(localStorage.hasOwnProperty('bSearchPreferencesCreated') != true){\r\n\t\t\t// Comments\r\n\t\t\tvar aDayOfWeek = new Object();\r\n\t\t\taDayOfWeek['su'] = 1;\r\n\t\t\taDayOfWeek['mo'] = 1;\r\n\t\t\taDayOfWeek['tu'] = 1;\r\n\t\t\taDayOfWeek['we'] = 1;\r\n\t\t\taDayOfWeek['th'] = 1;\r\n\t\t\taDayOfWeek['fr'] = 1;\r\n\t\t\taDayOfWeek['sa'] = 1;\r\n\t\t\r\n\t\t\t// oCurrentSearchSettings\r\n\t\t\tvar oCurrentSearchSettings = new Object();\r\n\t\t\toCurrentSearchSettings['sLocationName']\t\t= 'Amsterdam';\r\n\t\t\toCurrentSearchSettings['fLocationLat']\t\t= 52.378;\r\n\t\t\toCurrentSearchSettings['fLocationLng']\t\t= 4.9;\r\n\t\t\toCurrentSearchSettings['iLocationRadius']\t= iDefaultLocationRadius;\r\n\t\t\toCurrentSearchSettings['iPriceMin']\t\t\t= iDefaultPriceMin;\r\n\t\t\toCurrentSearchSettings['iPriceMax']\t\t\t= iDefaultPriceMax;\r\n\t\t\toCurrentSearchSettings['iDayOffsetFrom']\t= 0;\r\n\t\t\toCurrentSearchSettings['iDayOffsetTo']\t\t= iDefaultDateMax;\r\n\r\n\t\t\toCurrentSearchSettings['dStartDate']\t\t= new Date();\r\n\t\t\toCurrentSearchSettings['dEndDate']\t\t\t= oCurrentSearchSettings['dStartDate'].addDays(iDefaultDateMax);\r\n\r\n\t\t\toCurrentSearchSettings['aDayOfWeek']\t\t= JSON.stringify(aDayOfWeek);\r\n\t\t\tlocalStorage.setItem('oCurrentSearchSettings', JSON.stringify(oCurrentSearchSettings));\r\n\t\t\t\r\n\t\t\tvar oPanelSearchSettings = new Object();\r\n\t\t\toPanelSearchSettings['sLocationName']\t\t= oCurrentSearchSettings['sLocationName'];\r\n\t\t\toPanelSearchSettings['fLocationLat']\t\t= oCurrentSearchSettings['fLocationLat'];\r\n\t\t\toPanelSearchSettings['fLocationLng']\t\t= oCurrentSearchSettings['fLocationLng'];\r\n\t\t\toPanelSearchSettings['iLocationRadius']\t\t= oCurrentSearchSettings['iLocationRadius'];\r\n\t\t\toPanelSearchSettings['iPriceMin']\t\t\t= oCurrentSearchSettings['iPriceMin'];\r\n\t\t\toPanelSearchSettings['iPriceMax']\t\t\t= oCurrentSearchSettings['iPriceMax'];\t\t\t\r\n\t\t\toPanelSearchSettings['iDayOffsetFrom']\t\t= oCurrentSearchSettings['iDayOffsetFrom'];\r\n\t\t\toPanelSearchSettings['iDayOffsetTo']\t\t= oCurrentSearchSettings['iDayOffsetTo'];\r\n\t\t\t\r\n\t\t\toPanelSearchSettings['dStartDate']\t\t\t= oCurrentSearchSettings['dStartDate'];\r\n\t\t\toPanelSearchSettings['dEndDate']\t\t\t= oCurrentSearchSettings['dEndDate'];\r\n\r\n\t\t\toPanelSearchSettings['aDayOfWeek']\t\t\t= oCurrentSearchSettings['aDayOfWeek'];\r\n\t\t\tlocalStorage.setItem('oPanelSearchSettings', JSON.stringify(oPanelSearchSettings));\r\n\r\n\t\t\t// Comments\r\n\t\t\tlocalStorage.setItem(\"bSearchPreferencesCreated\",\t\ttrue);\r\n\t\t\tlocalStorage.setItem(\"iMusicFactIndex\",\t\t\t\t\ttrue);\r\n\t\t};\r\n\t}",
"function read_preferences()\n{\n\t// time\n\t\n\tvar time = get_preference('time');\n\tvar time_int = parseInt(time);\n\t\n\tif (time && [15, 30, 45, 60].indexOf(time_int) > -1)\n\t\tconfig.time = time_int;\n\telse\n\t\tconfig.time = 45;\n\t\n\tdocument.getElementById('popup_lookahead').setAttribute('value', config.time);\n\n\t// routes\n\n\tvar routes = get_preference('routes');\n\t\n\tif (routes) {\n\t\tvar routes_arr = routes.replace(/\\[(.+)\\]/g, '$1').split(',');\n\n\t\troutes_arr = routes_arr.map(function(e) {\n\t\t\treturn parseInt(e);\n\t\t});\n\t\troutes_arr = routes_arr.filter(function(e) {\n\t\t\treturn (all_routes.indexOf(e) > -1);\n\t\t});\n\t\t\n\t\tconfig.routes = routes_arr;\n\t} else\n\t\tconfig.routes = all_routes.slice();\n\t\n\tupdate_routes_checkboxes_from_list(config.routes);\n\n\t// stop code\n\n\tvar stop_code = get_preference('stop_code');\n\t\n\tif (stop_code) {\n\t\tif (!(stop_code in stops)) {\n\t\t\tbad_stop_code = stop_code;\n\n\t\t\tset_title('CU BusBoard');\n\t\t\tdisplay_message('“' + bad_stop_code +\n\t\t\t\t\t'” isn’t a stop. Please double-check your code.');\n\t\t\t\t\t\n\t\t\tconfig.stop_code = '';\n\t\t\tconfig.stop_id = '';\n\t\t\tconfig.stop_verbose = '';\n\t\t\t\t\n\t\t\tdocument.getElementById('field_stop').setAttribute('value', stop_code);\n\t\t\t\t\n\t\t\treturn 2;\n\t\t} else {\n\t\t\tbad_stop_code = '';\n\n\t\t\tconfig.stop_code = stop_code;\n\t\t\tconfig.stop_id = get_intersection_id(stop_code);\n\t\t\tconfig.stop_verbose = get_verbose_stop_name_from_code(stop_code);\n\t\t\t\t\t\n\t\t\tdocument.getElementById('field_stop').setAttribute('value', stop_code);\n\n\t\t\treturn 0;\n\t\t}\n\t} else {\n\t\tdisplay_message(\"Please click the\"\n\t\t\t\t+ \" <span style='font-style: italic; font-family: \\\"Times New Roman\\\"; font-weight: bold'>i</span>\"\n\t\t\t\t+ \" button at the bottom-right of this widget and enter a stop code.\");\n\t\t\t\t\n\t\tconfig.stop_code = '';\n\t\tconfig.stop_id = '';\n\t\tconfig.stop_verbose = '';\n\n\t\treturn 1;\n\t}\n}",
"function saveSettingsAndUpdatePopup(){\n\tvar settings = {};\n settings.on = document.getElementById(\"onoff\").innerText.toLowerCase().includes(\"on\"); // Sorry about this line\n\tsettings.fast_mode = document.getElementById(\"fast_mode\").checked;\n\tsettings.run_at = document.getElementById(\"run_at\").value;\n\n\tsaveNewSettings(settings);\n\n\t/* Update the UI in the popup depending on the settings */\n\tdocument.getElementById(\"onoff\").style.backgroundColor = settings.on ?\n\t\tON_COLOR : OFF_COLOR;\n\n\t/* Update whitelist display */\n\tredrawWhitelists();\n\tredrawIcon(settings.on);\n\n\treturn settings;\n}",
"function confirmConfig(){\n $scope.showConfig = false;\n $scope.parkingLotConfig = {\n 'totalParkingLots' : $scope.totalParkingLots,\n 'priceFirstHour' : $scope.priceFirstHour,\n 'pricePerHour' : $scope.pricePerHour,\n 'parkingLotName' : $scope.parkingLotName\n };\n \n localStorageService.add('0', $scope.parkingLotConfig);\n\n updateParkingLotSpaces();\n\n }",
"function showConfig() {\n\ttheApplet.showConfiguration();\n}",
"function loadSettingsPage() {\n refreshRunesButton = true; // Reset toggle when main page eventually reloads\n $('#main-container').load('./settings.html', () => {\n buildRuneSettingsTable();\n markCheckboxes();\n });\n }",
"function showInitialPage(){\n\t// other initiations here\n\tformMessageReset();\n\tinitSettingVal(); // initial settings value\n\tinitNodeCompletion(); // initial public node completion list\n\tinitAddressCompletion();\n\n\tif(!settings.has('firstRun') || settings.get('firstRun') !== 0){\n\t\tchangeSection('section-settings');\n\t\tsettings.set('firstRun', 0);\n\t}else{\n\t\tchangeSection('section-welcome');\n\t}\n\n\tlet versionInfo = document.getElementById('walletShellVersion');\n\tif(versionInfo) versionInfo.innerHTML = WS_VERSION;\n\tlet wVersionInfo = document.getElementById('walletVersion');\n\tif(wVersionInfo) wVersionInfo.innerHTML = remote.app.getVersion();\n}",
"function gadgetShowSettings(){\r\n \r\n //toggle display of settings\r\n if($('#gadgetSettings').css('display')!='none'){\r\n $('#gadgetSettings').css('display','none');\r\n return;\r\n }\r\n else $('#gadgetSettings').css('display','block');\r\n \r\n //if form elements already drawn, return\r\n if($('#prefsForm').attr('id')) return;\r\n \r\n //get prefs profiles obj\r\n profilesOn = prefs.getArray('profiles');\r\n \r\n //build settings html form\r\n html = '<form id=\"prefsForm\">';\r\n \r\n //checkbox's for turning profile display on/off\r\n for(var i=0; i<profiles.length; i++){\r\n id = profiles[i].getTableId().getValue();\r\n \r\n //if profileId is in profilesOn[] then checked=checked\r\n html += '<input type=\"checkbox\" value=\"' + id + '\" id=\"settingsProfile'+i+'\" name=\"profile\"';\r\n if($.inArray(id, profilesOn) >= 0) html += ' checked=\"checked\"';\r\n html += '/>' + \r\n '<label for=\"settingsProfile'+i+'\">'+profiles[i].getPropertyValue('ga:AccountName')+'</label><br/>';\r\n }\r\n\r\n //finish form, submit btn\r\n html += '</form>';\r\n html += '<button onclick=\"gadgetSetSettings()\">Save</button>';\r\n \r\n //append form\r\n document.getElementById('gadgetSettings').innerHTML = html;\r\n \r\n //resize window\r\n _IG_AdjustIFrameHeight();\r\n }",
"function initializeSettings() {\n if (Drupal.eu_cookie_compliance !== undefined && Drupal.eu_cookie_compliance.hasAgreed()) {\n $('.js-social-media-settings-open').removeClass('hidden');\n\n if (cookieExists()) {\n sources = cookieGetSettings();\n }\n else {\n sources = settings.sources;\n cookieSaveSettings();\n }\n }\n }",
"function gadgetFirstRun(){\r\n \r\n var profileStates = prefs.getArray('profiles');\r\n if(!profileStates || profileStates=='') return true;\r\n else return false;\r\n }",
"function show_global_supplier_settings()\n{\n\t//Check if order list is empty \n\tif (order_list.length>0)\n\t{\t\n\t\tif (!ask_notification(\"Changing global supplier settings will change individual product supplier settings. Are you sure you want to proceed?\"))\n\t\t\treturn;\n\t}\n\t//Draw the global supplier settings page \n\t//Draw the items on the page as per global settings values \n\t$.each(suppliers_list, function (supplier_id, supplier_details)\n\t{\n\t\tvar supplier_name = supplier_details.name;\n\t\tvar checked = \"\";\n\t\tvar premium = 0;\n\t\t//Check if this global \n\t\tif (supplier_id in global_supplier_settings) \n\t\t{\n\t\t\tchecked = \" checked \";\n\t\t\tpremium = global_supplier_settings[supplier_id].premium;\n\t\t}\n\t\t//Write the HTML\n\t\tstr = str + \"<div class='ss-supplier'><div class='ss-supplier-selector'><input type='checkbox' id='glob_\"+supplier_id+\"' \"+checked+\" /></div><div class='ss-supplier-label'>\"+supplier_name+\"</div><div class='ss-supplier-percentage' ><input type='number' value='\"+premium+\"' id='gprem\"+supplier_id+\"' /> %</div></div>\";\n\n\t});\n\t//Include the HTML into basic frame\n\t$(\"#sup_list_view_global\").html(str);\t\t\n\t//make things visible\n\t$('.overlay').fadeIn(100); \n\t$('#setng_supplier_global').fadeIn(100);\n\n}",
"function getSettings() {\n var savedselection = localStorage[\"pweGameServerStatus\"];\n if (savedselection) { \n gameselection = savedselection; \n } else {\n gameselection = $.map(_jsongames.games, function(item) { if(item.hasOwnProperty('scrape')) { return '#' + item.name + '_block';} }).join(\", \");\n saveSettings();\n }\n}",
"function getPreferences() {\n \treturn preferencesCache;\n }",
"function showConfig() {\n var ui = HtmlService.createTemplateFromFile('ConfigSidebar')\n .evaluate()\n .setTitle('shmdoc settings');\n SpreadsheetApp.getUi().showSidebar(ui);\n}",
"DisplayAspNetConfigSettings() {\n\n }",
"function displaySettings() {\r\n\t\t// Hide other menus\r\n\t\taddClass($('#main_menu #shortcuts'), 'hide');\r\n\t\taddClass($('#main_menu #story'), 'hide');\r\n\t\taddClass($('#main_menu #spellbook'), 'hide');\r\n\t\taddClass($('#main_menu #stats'), 'hide');\r\n\r\n\t\t// Show settings screen\r\n\t\tremoveClass($('#main_menu #settings'), 'hide');\r\n\t}",
"function configurePermanent() {\n $('input[type=\"checkbox\"]').change(function () {\n if (this.checked) {\n $(\"#permanent\").val(1);\n } else {\n $(\"#permanent\").val(0);\n }\n });\n}",
"function checkSetupSuccess() {\n // Conditionals.\n var hasUndefined = false;\n var hasFalse = false;\n // Iterate through global successFactors JSON object.\n for (var key in global.successFactors) {\n if (global.successFactors[key] === undefined) {\n hasUndefined = true;\n break;\n }\n if (global.successFactors[key] === false) {\n console.log('key: ',key);\n hasFalse = true;\n break;\n }\n }\n // If no undefined and no false, print success.\n if (!hasUndefined && !hasFalse) {\n console.log(\"---\\nSetup was a success! Please enjoy MMM-RemoteCompliments!\");\n }\n // If false, let user know and exit.\n if (hasFalse){\n console.log(\"---\\nSomething went wrong with the setup. It is recommended you delete the files created on your Google Drive and try setup again after fixing the above error.\");\n process.exit(1);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders all roles into a table | function viewRoles() {
connection.query("SELECT title FROM role;", function (err, res) {
renderTable2(err, res, "Role Title", "title");
})
} | [
"function showAllRoles() {\n query = 'SELECT * FROM role;';\n connection.query(query, (err, results) => {\n if (err) throw err;\n console.table(results);\n // return to main menu\n askUser();\n });\n}",
"function populate_roles_fields () {\n // Populate the fields from the roles table\n for (var i in roles) {\n var current_role = new Array();\n $('.roles-row').each(function(index) {\n user = $(this).attr('user_id');\n if ($('#checkbox-'+roles[i]+'-'+user).is(':checked')) {\n current_role.push(user);\n };\n });\n $('#'+roles[i]).val(current_role.join(','));\n $('#list-'+roles[i]+' span').html(current_role.join(', '));\n }\n}",
"role() {\n return this.props.projectData.role \n .map(role => \n <span className=\"tag is-size-5 is-white has-text-weight-bold\">{role}</span>\n );\n }",
"function displayAll() {\n connection.query(\"SELECT e.id, e.first_name, e.last_name, r.title, r.salary, d.name, m.first_name AS ? , m.last_name AS ? FROM employee e JOIN role r ON e.role_id = r.id JOIN department d ON r.department_id = d.id LEFT JOIN employee m on e.manager_id = m.id;\", [\"manager_first_name\", \"manager_last_name\"], function (err, res) {\n renderTable(err, res);\n \n })\n}",
"function viewAll(){\n connection.query(\"select employee.id, first_name, last_name, title, department.name, salary from employee inner join role on employee.id = role.id inner join department on department.id = role.id\",\n (err, data) =>{\n if (err) throw err;\n console.table(data)\n initalise();\n // connection.end\n })\n}",
"getAllEntities() {\n let queryParameters = {};\n let headerParams = this.defaultHeaders;\n let isFile = false;\n let formParams = {};\n return this.execute('GET', '/api/user/v1/role/get-all', queryParameters, headerParams, formParams, isFile, false, undefined);\n }",
"function renderAllStaff( allStaff ){\n for(var i = 0; i < allStaff.length; i++){\n renderOneStaff(allStaff[i]);\n }\n}",
"async getRoles() {\n let roles = await groupFunctions.getRoles(this.groupId, this._id);\n return [].concat(roles).map(x=> new Role(x, this.groupId, this._id));\n }",
"function addEmployeeRoles(managers){\n \n console.clear();\n db.loadRoles(addEmployeePrompt, managers);\n}",
"function addAllToTables() {\n\n let table = document.getElementById(\"eveTable\");\n\n // reset eve's table\n table.innerHTML = \"\";\n let tr = document.createElement(\"tr\");\n let th1 = document.createElement(\"th\");\n let th2 = document.createElement(\"th\");\n th1.innerHTML = \"Recipient\";\n th2.innerHTML = \"Message\";\n tr.appendChild(th1);\n tr.appendChild(th2);\n table.appendChild(tr);\n\n for (let i = 0; i < messageList.names.length; i++) {\n addToTable(messageList.names[i], messageList.messages[i]);\n }\n }",
"render() {\n const { machines } = this.context;\n\n return (\n <table className=\"MFG_Table\">\n <thead>\n <tr>\n <th>ID</th>\n <th>Name</th>\n <th>Type</th>\n </tr>\n </thead>\n <tbody>\n {machines.map((val, ind) => {\n return (\n <tr key={ind} className=\"machine\">\n <td>{val.id}</td>\n <td>{val.name}</td>\n <td>{val.type}</td>\n </tr>\n );\n })}\n </tbody>\n </table>\n );\n }",
"function displayRolesSelectMenu(container) {\n\n fetch('http://sandbox.bittsdevelopment.com/code1/fetchroles.php')\n .then((response) => {\n return response.json();\n })\n .then((rolesArray) => {\n\n let rolesMenu = `<form action=\"#\" method=\"GET\">\n <fieldset>\n <legend>Find Team Members By Roles</legend>`;\n \n // Loop over the array of roles and extract the role id and role name to constuct the checkbox menu\n rolesArray.forEach((roleObject) => {\n rolesMenu += `<div>\n <input type=\"checkbox\" id=\"roleid_${roleObject.roleid}\" name=\"selectedroles\" value=\"${roleObject.roleid}\">\n <label for=\"roleid_${roleObject.roleid}\">${roleObject.rolename}</label>\n </div>`\n });\n\n rolesMenu += `<button type=\"submit\" onclick=\"rolesFormHandler(event);\">Select Roles</button>\n </fieldset>\n </form>`;\n\n container.innerHTML = rolesMenu;\n\n })\n .catch((err) => {\n console.log(err)\n });\n\n}",
"function allMenusHtml(req, res) {\n\n menus.getAllMenus()\n .then((results) => res.render('pages/index', results))\n .catch(err => {\n console.log('error in allMenusHtml: ', err);\n res.send('There was an error, sorry!')\n });\n}",
"function populateRoles(data) \n{\n\t$(\"#fetchedRolesCombo\").empty();\n\t$(\"#fetchedRolesCombo\").removeAttr(\"class\");\n\t$(\"#fetchedRolesCombo_chzn\").remove();\n\t\n\t$(\"#fetchedUsersCombo\").empty();\n\t$(\"#fetchedUsersCombo\").removeAttr(\"class\");\n\t$(\"#fetchedUsersCombo_chzn\").remove();\n\t\n\tif(data.role instanceof Array) {\n\t\t$.each(data.role,function(key,obj) {\n\t\t\t$(\"#fetchedRolesCombo\").append(\"<option value=\"+obj+\">\"+obj+\"</option>\");\n\t\t\t\tif(parseInt(key)==parseInt(data.role.length-1))\n\t\t\t\t\texecuteRbacAction(\"getAssignedUsers\",populateUsers,obj,true);\n\t\t\t\telse\n\t\t\t\t\texecuteRbacAction(\"getAssignedUsers\",populateUsers,obj,false);\n\t\t\t});\n\t\t}\n\telse {\n\t\t\t$(\"#fetchedRolesCombo\").append(\"<option value=\"+data.role+\">\"+data.role+\"</option>\");\n\t\t\texecuteRbacAction(\"getAssignedUsers\",populateUsers,data.role,true);\n\t\t}\n\t\n\t$(\"#fetchedRolesCombo\").chosen();\n\t$(\"#fetchedRolesCombo_chzn\").css(\"width\",240);\n\tmodalShow('reassignTaskModal');\n}",
"function create_row(user_id) {\n id_list = roles.concat([\"user\", \"remove\"]);\n for (i in id_list) {\n\tvar last_row_td = $('#roles-last-row-' + id_list[i]);\n\tif(last_row_td.attr(\"class\") == \"table-row-bottom\")\n\t last_row_td.attr(\"class\", \"table-row-general\");\n\tlast_row_td.attr(\"id\", \"\");\n }\n var row = $('<tr class=\"roles-row\" user_id=\"'+user_id+'\">');\n if ( user_id ) {\n $('<td id=\"roles-last-row-user\" class=\"table-row-bottom\">').html(user_id).appendTo(row);\n } else {\n // Get a text input field to add a new role.\n $('<td id=\"roles-last-row-user\" class=\"table-row-bottom\">')\n\t .append($('<input id=\"edit-new-username\" type=\"text\">').blur(fix_role_checkboxes))\n\t .appendTo(row);\n };\n for (i in roles) {\n $('<td id=\"roles-last-row-' + roles[i] + '\" class=\"table-row-bottom\" style=\"text-align:center;\">')\n .append($('<input type=\"checkbox\" id=\"checkbox-'\n +roles[i]+'-'+user_id+'\">'))\n .appendTo(row);\n };\n $('<td id=\"roles-last-row-remove\" style=\"text-align:center;\">')\n\t.append($('<img src=\"/static/images/delete_icon.png\" alt=\"Delete\" id=\"remove-'+user_id+'\">').click(clear_role_checkboxes))\n\t.appendTo(row);\n return row;\n}",
"function getAvailableRoles() {\n StaticDataFactory.getAvailableRoles().then(function (data) {\n vm.claimRoles = data.roles.role;\n if(typeof vm.claimRoles === 'string')\n {\n vm.claimRoles = [];\n vm.claimRoles.push(data.roles.role);\n }\n vm.selectedManagementRole = vm.claimRoles[0];\n console.log(\"ClaimRoles die binnenkomen:\", vm.claimRoles);\n });\n }",
"allRolesOn(on=true) {\n if (on) {\n this.allRoleSwitchesOn();\n this.selectedRoles = this.roles.map(x => String(x.code));\n } else {\n this.allRoleSwitchesOn(false);\n this.selectedRoles = [];\n }\n }",
"function displayMovies ( movies ) {\n let table;\n table = \"<table border='1' style='width: 100%'>\";\n table += \"<tr><th>ID</th><th>Name</th><th>Rank</th></tr>\";\n for ( let index = 0; index < movies.length; index ++ ) {\n table += \"<tr>\";\n table += \"<td>\" + movies[ index ].id + \"</td>\";\n table += \"<td>\" + movies[ index ].title + \"</td>\";\n table += \"<td>\" + movies[ index ].rank + \"</td>\";\n table += \"</tr>\";\n }\n// Close the table\n table += \"</table>\";\n document.getElementById ( \"movies-list\" ).innerHTML = table;\n}",
"renderStoreManagerForm() {\n console.log('@renderStoreManagerForm')\n console.log(this.props.loggedInUser.role[0])\n if (this.props.loggedInUser.roles[0] == \"ROLE_USER\") {\n return (\n <span style={{ fontSize: 12, color: \"#504F5A\", marginTop: 5 }}>Create a Store Manager</span>\n );\n }\n return;\n }",
"function initRolesTabs(rolesToInit) {\n for(var role in rolesToInit) {\n tabsByRoles[role] = [];\n sortTabsByRoles(tabs[role], role);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update position based on the selected anchor node | _recalculatePosition() {
if (!this._isActive()) { return; }
const anchorNode = this._getAnchorNode();
const rect = anchorNode.getBoundingClientRect();
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
let node = ReactDOM.findDOMNode(this);
node.style.top = rect.top + scrollTop - 5 + "px";
node.style.left = rect.left - 70 + "px";
} | [
"function updateAnchor() {\n\t\tif (!labels.selection) return;\n\t\tlabels.selection.each(function(d) {\n\t\t var bbox = this.getBBox(),\n\t\t x = bbox.x + bbox.width / 2,\n\t\t y = bbox.y + bbox.height / 2;\n\t\t \n\t\t d.anchorPos.x = x;\n\t\t d.anchorPos.y = y;\n\t\t \n\t\t // If a label position does not exist, set it to be the anchor position \n\t\t if (d.labelPos.x == null) {\n\t\t\td.labelPos.x = x;\n\t\t\td.labelPos.y = y;\n\t\t }\n\t\t});\n\t }",
"assignPosition(node, position) {\n this.spot = Math.max(this.spot, position);\n node.position = position;\n if (node.children.length > 0) {\n this.assignPosition(node.children[0], position);\n }\n for (let i = 1; i < node.children.length; i++) {\n if (this.spot > position) {\n this.assignPosition(node.children[i], this.spot+1);\n } else {\n this.assignPosition(node.children[i], position+1);\n }\n }\n }",
"_reCalculateVisibleNodePosition() {\n // clear all to avoid leaving selected/select-ready dep lines\n // which created before node position changes.\n this.clearAllHighlight()\n // position calculation\n this.refreshDiagramElements()\n this._setAllDiagramElementsHandler()\n }",
"assignPosition(node, position) {\n node.position = position \n if (node.children.length){\n for (let child_node of node.children){\n position = this.assignPosition(child_node, position)\n }\n }else{\n position++;\n }\n return position\n }",
"function setNodePosition(){\n\t\tvar num = 0;\n\t\tvar change = 0;\n\t\t//check if node is outside or not, when the status of node changes, the transition happens\n\t\tnodes.each(function(d){\n\t\t\tif (d.noLayer){\n\t\t\t\td.outside.isOutside = true;\n\t\t\t\td3.select(this)\n\t\t\t\t\t.transition()\n\t\t\t\t\t.duration(500)\n\t\t\t\t\t.attr(\"opacity\", 0.8)\n\t\t\t\t\t.attr(\"r\", nodeRadius)\n\t\t\t\t\t.attr(\"fill\", \"red\");\t\n\t\t\t\treturn;\t\t\t\t\n\t\t\t}\t\t\t\n\t\t\tvar offset = Math.max(xOffset - leftPanelWidth,0);\n\t\t\tif (d.position.x - nodeRadius < offset || d.position.x + nodeRadius > offset + windowWidth){\t\t\t\t\n\t\t\t\td3.select(this).classed(\"fixed\", d.fixed = false);\n\t \t\t\td.position.x = d.xpos;\n\t\t\t\td.position.y = height - nodeRadius - d.layer * unitLinkLength;\n\t\t\t}\n\t\t\tif (d.position.x - nodeRadius < offset || d.position.x + nodeRadius > offset + windowWidth){\n\t\t\t\tif (d.unAssigned == true){\n\n\t\t\t\t}\n\t\t\t\telse if (!d.outside.isOutside){\n\t\t\t\t\td.outside.isOutside = true;\t\t\t\t\n\t\t\t\t\td3.select(this)\n\t\t\t\t\t\t.transition()\n\t\t\t\t\t\t.duration(500)\n\t\t\t\t\t\t.attr(\"opacity\", 0.5)\n\t\t\t\t\t\t.attr(\"r\", nodeRadius)\n\t\t\t\t\t\t.attr(\"fill\", function(d){\n\t\t\t\t\t\t\treturn cScale(d.index + 1);\n\t\t\t\t\t\t});\t\t\t\t\t\n\t\t\t\t\tchange++;\n\t\t\t\t\tnum++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (d.outside.isOutside){\n\t\t\t\t\td.outside.isOutside = false;\n\t\t\t\t\td3.select(this)\n\t\t\t\t\t\t.transition()\n\t\t\t\t\t\t.duration(500)\n\t\t\t\t\t\t.attr(\"opacity\", 0.7)\n\t\t\t\t\t\t.attr(\"r\", nodeRadius)\n\t\t\t\t\t\t.attr(\"fill\", \"red\");\n\n\t\t\t\t\tchange++;\n\t\t\t\t\tnum--;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//console.log(d.id + \" \" + d.outside.isOutside + \" \" + d.position.x);\n\t\t});\n\n\t\t//when some node changes its status, the correspoding links, labels and the x position of inside nodes should also change.\n\t\tif (change > 0 || firstTime){\n\t\t\tfirstTime = false;\n\t\t\toutsideNodesNum = num;\t\n\t\t\td3.selectAll(\".nodeLabel\")\n\t\t\t\t.attr(\"opacity\", function(d){\n\t\t\t\t\tif (d.node.noLayer){\n\t\t\t\t\t\td.node.showLabel = true;\n\t\t\t\t\t\treturn 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (d.type == \"nodeLabel\" && d.node.outside){\n\t\t\t\t\t\tif ((!d.node.outside.isOutside && d.node.type != \"anchor\") || (d.node.outside.isOutside && d.node.degree >= 3)){\n\t\t\t\t\t\t\td.node.showLabel = true;\n\t\t\t\t\t\t\treturn 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\n\t\t\t\t\td.node.showLabel = false;\n\t\t\t\t\treturn 0;\t\t\t\n\t\t\t\t});\n\t\t\td3.selectAll(\".linkLabel\")\n\t\t\t\t.attr(\"opacity\", function(d){\n\t\t\t\t\tif (d.type == \"linkLabel\"){\n\t\t\t\t\t\tif (nodesData[d.node.tgt].noLayer){\n\t\t\t\t\t\t\td.show = true;\n\t\t\t\t\t\t\treturn 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (nodesData[d.node.src].outside.isOutside || nodesData[d.node.tgt].outside.isOutside){\n\t\t\t\t\t\t\td.show = false;\n\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\td.show = true;\n\t\t\t\t\t\treturn 1;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\td3.selectAll(\".edgeLinkLabel\")\n\t\t\t\t.attr(\"opacity\", function(d){\n\t\t\t\t\t//console.log(d.index);\n\t\t\t\t\tif (!d.node.src.show || nodesData[d.node.tgt].outside.isOutside){\n\t\t\t\t\t\td.show = false;\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\t\t\t\t\td.show = true;\n\t\t\t\t\treturn 1;\t\t\t\t\t\n\t\t\t\t});\n\t\t\td3.selectAll(\".clickBoard\")\n\t\t\t\t.attr(\"fill\", function(d){\n\t\t\t\t\tif (d.content == \"edgeLinks\"){\n\t\t\t\t\t\tif (nodesData[d.node.tgt].outside.isOutside || !d.node.src.show){\n\t\t\t\t\t\t\treturn \"node\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn \"transparent\";\n\t\t\t\t\t} else if (d.type == \"linkLabel\"){\n\t\t\t\t\t\tif (nodesData[d.node.src].outside.isOutside || nodesData[d.node.tgt].outside.isOutside){\n\t\t\t\t\t\t\treturn \"none\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn \"transparent\";\n\t\t\t\t\t} \n\t\t\t\t\treturn d.node.showLabel ? \"transparent\" : \"none\";\n\t\t\t\t});\n\n\t\t\tlinks.classed(\"outsideLink\", function(d){\n\t\t\t\tif (d.type == \"edgeLink\"){\n\t\t\t\t\treturn d.target.outside.isOutside;\n\t\t\t\t}\n\t\t\t\tif (d.target.noLayer){\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (d.source.outside && d.target.outside){\n\t\t\t\t\t//console.log(d.source.outside.isOutside + \" \" + d.target.outside.isOutside);\n\t\t\t\t\treturn d.source.outside.isOutside || d.target.outside.isOutside;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t});\n\n\t\t\tlayerMap.forEach(function(d, i){\n\t\t\t\tif (i > 0){\n\t\t\t\t\td.forEach(function(e){\n\t\t\t\t\t\tif (!nodesData[e].outside.isOutside && !nodesData[e].fixed){\n\t\t\t\t\t\t\tvar tmp = [];\n\t\t\t\t\t\t\tnodesChildren[e].forEach(function(f){\n\t\t\t\t\t\t\t\tif (!nodesData[f].outside.isOutside){\n\t\t\t\t\t\t\t\t\ttmp.push(nodesData[f].xpos);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\t\t\t\t\n\t\t\t\t\t\t\tnodesData[e].xpos = (d3.min(tmp) + d3.max(tmp)) / 2;\n\t\t\t\t\t\t\tnodesData[e].position.x = nodesData[e].xpos;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\t\n\t\t\tforce.start();\n\t\t}\n\t}",
"function moveNodeForNew(node) {\n // when create new box dom, move pass to 150 right\n var first_sub_node_x = getFirstSubNodePosition(node).x;\n // move each node position\n // add paret node, then sub node change position\n // add sub node, then parent node do not change position\n $('g[data-object-id=\"'+node.parent_id+'\"]>use').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x\", x);\n });\n $('g[data-object-id=\"'+node.parent_id+'\"]>text').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x\", x+30);\n });\n $('g[data-object-id=\"'+node.parent_id+'\"]>line').each(function(index_g, element_g){\n var x = first_sub_node_x + index_g * 150;\n $(element_g).attr(\"x2\", x+50);\n });\n // moving px\n var px = 0;\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('use').each(function(index_g, element_g){\n var x = parseInt($(element_g).attr(\"x\"));\n px = x - parseInt($(element_g).attr(\"x\"));\n $(element_g).attr(\"x\", x-75);\n });\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('text').each(function(index_g, element_g){\n var x = parseInt($(element_g).attr(\"x\"));\n $(element_g).attr(\"x\", x-75);\n });\n $('use[data-object-id=\"'+node.object_id+'\"]').parent().find('g').children('line').each(function(index_g, element_g){\n var x1 = parseInt($(element_g).attr(\"x1\"));\n var x2 = parseInt($(element_g).attr(\"x2\"));\n $(element_g).attr(\"x1\", x1-75);\n $(element_g).attr(\"x2\", x2-75);\n });\n }",
"TreeAdvanceToLabelPos()\n {\n let g = this.guictx;\n g.CurrentWindow.DC.CursorPos.x += this.GetTreeNodeToLabelSpacing();\n }",
"_updateKnobPosition() {\n this._setKnobPosition(this._valueToPosition(this.getValue()));\n }",
"function updatePosition() {\n\t \n\t\tbox.css({\n\t\t\t'width': ($(element).width() - 2) + 'px',\n\t\t\t'top': ($(element).position().top + $(element).height()) + 'px',\n\t\t\t'left': $(element).position().left +'px'\n\t\t});\n\t}",
"function position(){\n var num = 1;\n tf.forEach(function(e){\n $('[data-show_id='+e+']').parent().css({\n 'order': num++\n });\n });\n }",
"function setMenuLocation() {\n\t\tlet menu = ActiveItem.element.getBoundingClientRect();\n\t\t\n\t\tlet x = menu.left + menu.width + 8;\n\t\tlet y = menu.top;\n\t\t\n\t\tctrColor.propMenu.style.left = `${x}px`;\n\t\tctrColor.propMenu.style.top = `${y}px`;\n\t}",
"changePxPositionPostIts() {\n let elArray = this.main.children;\n this.getWindowSize();\n for (let i = 0; i < elArray.length; i++) {\n let element = elArray[i];\n let posX = element.getAttribute(\"posX\");\n let posY = element.getAttribute(\"posY\");\n let newPx = this.calculatePercentToPX(posX, posY);\n element.style.transform = `translate(${newPx.pxX}px, ${newPx.pxY}px)`;\n }\n }",
"function updateScroll() {\n\t\tlet elements = container.getElementsByClassName('selected');\n\t\tif (elements.length > 0) {\n\t\t\tlet element = elements[0];\n\t\t\t// make group visible\n\t\t\tlet previous = element.previousElementSibling;\n\t\t\tif (previous && previous.className.indexOf('group') !== -1 && !previous.previousElementSibling) {\n\t\t\t\telement = previous;\n\t\t\t}\n\t\t\tif (element.offsetTop < container.scrollTop) {\n\t\t\t\tcontainer.scrollTop = element.offsetTop;\n\t\t\t} else {\n\t\t\t\tlet selectBottom = element.offsetTop + element.offsetHeight;\n\t\t\t\tlet containerBottom = container.scrollTop + container.offsetHeight;\n\t\t\t\tif (selectBottom > containerBottom) {\n\t\t\t\t\tcontainer.scrollTop += selectBottom - containerBottom;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function position() {\n // position of the container: $('#graphic')\n var pos = window.pageYOffset - 10 - containerStart;\n\n // BK => This is a nice way to find the figure out which section \n // is next but it trigger each time the current section has a piece out.\n var sectionIndex = d3.bisect(sectionPositions, pos);\n\n //BK => What is this doing? \n //sectionIndex = Math.min(sections.size() - 1, sectionIndex);\n\n $.each(sectionPositions, function(i, sPos) {\n // get the real position of the sections\n var nPos = sPos - pos;\n // check if the section is within the right range\n if ( nPos < displayRange ) {\n sectionIndex = i;\n return;\n }\n });\n\n // this will trigger the change of section\n if (currentIndex !== sectionIndex) {\n dispatch.active(sectionIndex);\n currentIndex = sectionIndex;\n }\n\n var prevIndex = Math.max(sectionIndex - 1, 0);\n var prevTop = sectionPositions[prevIndex];\n var progress = (pos - prevTop) / (sectionPositions[sectionIndex] - prevTop);\n \n dispatch.progress(currentIndex, progress);\n }",
"function updatePointers(num_ops_processed, log_position) {\n if (num_ops_processed != -1) {\n d3.select('#commands')\n .selectAll(\"li\")\n .attr('class','');\n d3.select('#commands')\n .selectAll(\"li\")\n .filter(function(d, i) { return i == num_ops_processed; })\n .attr('class','current-op');\n var commandEle = document.getElementById('commands');\n commandEle.scrollTop = commandEle.children[0].offsetHeight * (num_ops_processed -2);\n }\n if (log_position != -1) {\n d3.select('#log')\n .selectAll(\"tr\")\n .filter(function(d, i) { return i == log_position; })\n .attr('class','current-row');\n }\n }",
"__update_position_hook() {\n for (var i = 0; i < this.__shapes.length; ++i) {\n this.__shapes[i].shape.set_position(this.__position.add(this.__shapes[i].offset));\n }\n }",
"function anchorToPoint(anchor, box) {\n if (anchor.side === 'top' || anchor.side === 'bottom') {\n const {\n side,\n align\n } = anchor;\n const x = align === 'left' ? 0 : align === 'center' ? box.width / 2 : align === 'right' ? box.width : align;\n const y = side === 'top' ? 0 : side === 'bottom' ? box.height : side;\n return elementToViewport({\n x,\n y\n }, box);\n } else if (anchor.side === 'left' || anchor.side === 'right') {\n const {\n side,\n align\n } = anchor;\n const x = side === 'left' ? 0 : side === 'right' ? box.width : side;\n const y = align === 'top' ? 0 : align === 'center' ? box.height / 2 : align === 'bottom' ? box.height : align;\n return elementToViewport({\n x,\n y\n }, box);\n }\n return elementToViewport({\n x: box.width / 2,\n y: box.height / 2\n }, box);\n}",
"function updateCursorPosition(left, top) {\n cursor.style.left = `${left}px `;\n cursor.style.top = `${top}px`;\n cursor.scrollIntoView({\n behavior: \"smooth\",\n block: \"center\",\n inline: \"center\",\n });\n }",
"highlightSelected() {\n\n this.highlighter.setPosition(this.xStart + this.selected * this.distance, this.yPosition + this.highlighterOffsetY);\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This acts as a base class for all distributions. | function Distribution() {} | [
"function Distribution(props) {\n return __assign({ Type: 'AWS::CloudFront::Distribution' }, props);\n }",
"static add(entryDistribution){\n\t\tlet kparams = {};\n\t\tkparams.entryDistribution = entryDistribution;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_entrydistribution', 'add', kparams);\n\t}",
"function plotDistribution(dist) {\n dist = getDisplayDistribution(dist);\n var points = [];\n var count = 0;\n for (distance in dist) {\n var latlng = distanceToPoint(parseInt(distance));\n if (latlng === null) {\n break;\n }\n var loc = {\n \"location\": new google.maps.LatLng(latlng[0], latlng[1]),\n \"weight\": dist[distance]\n };\n points.push(loc);\n }\n\n MAP.panTo(points[Math.floor(points.length/2)].location);\n HEATMAP.setData(new google.maps.MVCArray(points));\n}",
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_entrydistribution', 'get', kparams);\n\t}",
"constructor(height: number, width: number) {\r\n super(height, width);\r\n // now we can use \"this\"\r\n }",
"static update(id, entryDistribution){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.entryDistribution = entryDistribution;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_entrydistribution', 'update', kparams);\n\t}",
"get forceScale() {}",
"function domain_extender(self, axis, ordinal) {\n var scalename = `${axis}scale`,\n zero = `${axis}0`,\n zero_val = `${axis}0_value`\n if (ordinal)\n return function() {\n var scale_prop = self[scalename],\n scale = scale_prop(),\n domain = self.data().map(self[axis]())\n if (scale_prop._has_domain) {\n var old_domain = scale.domain(),\n add_values = domain.filter(val => old_domain.indexOf(val) < 0)\n scale.domain(old_domain.concat(add_values))\n } else {\n scale.domain(domain)\n scale_prop._has_domain = true\n }\n return scale\n }\n else\n return function() {\n var scale_prop = self[scalename],\n scale = scale_prop(),\n domain = d3.extent(self.data(), self[axis]())\n\n // Incorporate the zero value\n var z = self[zero]()\n if (typeof z != 'undefined') {\n if (domain[0] > z)\n domain[0] = z\n if (domain[1] < z)\n domain[1] = z\n } else {\n z = domain[0]\n }\n self[zero_val] = z\n\n // Extend the domain\n if (scale_prop._has_domain)\n scale.domain(d3.extent([...scale.domain(), ...domain]))\n else {\n scale.domain(domain)\n scale_prop._has_domain = true\n }\n return scale\n }\n}",
"constructor(attrs = {}) {\n super(attrs)\n this.layerClass = 'GlobalAveragePooling1D'\n\n this.poolingFunc = 'average'\n }",
"constructor(attrs = {}) {\n super(attrs);\n this.name = '_Pool2D';\n const { \n kernel_size = [2, 2], \n strides = [2, 2], \n padding = 'VALID', \n data_format = 'NHWC',\n activation = 'NONE'\n } = attrs;\n\n if (Array.isArray(kernel_size)) {\n this.kernelShape = kernel_size;\n } else {\n this.kernelShape = [kernel_size, kernel_size];\n }\n\n if (Array.isArray(strides)) {\n this.strides = strides;\n } else {\n this.strides = [strides, strides];\n }\n\n if (Array.isArray(padding)) {\n if (padding.length !== 4) {\n this.throwError('Invalid padding.');\n // if all numbers in padding are 0, use padding = 'VALID'\n } else if (padding.every((x)=>!x)) {\n this.padding = 'VALID';\n } else {\n this.padding = padding;\n }\n } else if (padding === 'VALID' || padding === 'SAME') {\n this.padding = padding;\n } else {\n this.throwError('Invalid padding.');\n }\n\n if (data_format === 'NHWC') {\n this.dataFormat = data_format;\n } else {\n this.throwError('Only NHWC data formats are allowed.');\n }\n\n this.activation = activation;\n if (this.activation !== 'NONE') {\n this.activationProgram = webgl2.createProgram(activations[this.activation]);\n }\n }",
"forEachAxisScale(f) {\n this.axes.forEach(f);\n\n return this;\n }",
"static add(genericDistributionProvider){\n\t\tlet kparams = {};\n\t\tkparams.genericDistributionProvider = genericDistributionProvider;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_genericdistributionprovider', 'add', kparams);\n\t}",
"function DiscreteFaceter(aAttrDef, aFacetDef) {\n this.attrDef = aAttrDef;\n this.facetDef = aFacetDef;\n}",
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_genericdistributionprovideraction', 'get', kparams);\n\t}",
"constructor(dataentry) {\n this.dataentry = dataentry;\n // default to tooltips if not specified otherwise\n this.markStyle = dataentry ? (dataentry.options.markStyle || TOOLTIPS) : TOOLTIPS;\n this.options = _.extend({}, DomDecorator.defaults, dataentry && dataentry.options ? dataentry.options.decoratorOptions : {});\n this._elements = [];\n }",
"function componentAxis () {\r\n\r\n\t/* Default Properties */\r\n\tvar dimensions = { x: 80, y: 40, z: 160 };\r\n\tvar color = \"black\";\r\n\tvar classed = \"d3X3domAxis\";\r\n\tvar labelPosition = \"proximal\";\r\n\tvar labelInset = labelPosition === \"distal\" ? 1 : -1;\r\n\r\n\t/* Scale and Axis Options */\r\n\tvar scale = void 0;\r\n\tvar direction = void 0;\r\n\tvar tickDirection = void 0;\r\n\tvar tickArguments = [];\r\n\tvar tickValues = null;\r\n\tvar tickFormat = null;\r\n\tvar tickSize = 1;\r\n\tvar tickPadding = 1.5;\r\n\r\n\tvar axisDirectionVectors = {\r\n\t\tx: [1, 0, 0],\r\n\t\ty: [0, 1, 0],\r\n\t\tz: [0, 0, 1]\r\n\t};\r\n\r\n\tvar axisRotationVectors = {\r\n\t\tx: [1, 1, 0, Math.PI],\r\n\t\ty: [0, 0, 0, 0],\r\n\t\tz: [0, 1, 1, Math.PI]\r\n\t};\r\n\r\n\t/**\r\n * Get Axis Direction Vector\r\n *\r\n * @private\r\n * @param {string} axisDir\r\n * @returns {number[]}\r\n */\r\n\tvar getAxisDirectionVector = function getAxisDirectionVector(axisDir) {\r\n\t\treturn axisDirectionVectors[axisDir];\r\n\t};\r\n\r\n\t/**\r\n * Get Axis Rotation Vector\r\n *\r\n * @private\r\n * @param {string} axisDir\r\n * @returns {number[]}\r\n */\r\n\tvar getAxisRotationVector = function getAxisRotationVector(axisDir) {\r\n\t\treturn axisRotationVectors[axisDir];\r\n\t};\r\n\r\n\t/**\r\n * Constructor\r\n *\r\n * @constructor\r\n * @alias axis\r\n * @param {d3.selection} selection - The chart holder D3 selection.\r\n */\r\n\tvar my = function my(selection) {\r\n\t\tselection.each(function () {\r\n\r\n\t\t\tvar element = d3.select(this).classed(classed, true);\r\n\r\n\t\t\tvar makeSolid = function makeSolid(shape, color) {\r\n\t\t\t\tshape.append(\"appearance\").append(\"material\").attr(\"diffuseColor\", color || \"black\");\r\n\t\t\t\treturn shape;\r\n\t\t\t};\r\n\r\n\t\t\tvar range = scale.range();\r\n\t\t\tvar range0 = range[0];\r\n\t\t\tvar range1 = range[range.length - 1];\r\n\r\n\t\t\tvar axisDirectionVector = getAxisDirectionVector(direction);\r\n\t\t\tvar tickDirectionVector = getAxisDirectionVector(tickDirection);\r\n\t\t\tvar axisRotationVector = getAxisRotationVector(direction);\r\n\t\t\tvar tickRotationVector = getAxisRotationVector(tickDirection);\r\n\r\n\t\t\t/*\r\n // FIXME: Currently the tickArguments option does not work.\r\n const tickValuesDefault = scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain();\r\n tickValues = tickValues === null ? tickValuesDefault : tickValues;\r\n */\r\n\t\t\ttickValues = scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain();\r\n\r\n\t\t\tvar tickFormatDefault = scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : function (d) {\r\n\t\t\t\treturn d;\r\n\t\t\t};\r\n\t\t\ttickFormat = tickFormat === null ? tickFormatDefault : tickFormat;\r\n\r\n\t\t\t// Main Lines\r\n\t\t\tvar domain = element.selectAll(\".domain\").data([null]);\r\n\r\n\t\t\tvar domainEnter = domain.enter().append(\"transform\").attr(\"class\", \"domain\").attr(\"rotation\", axisRotationVector.join(\" \")).attr(\"translation\", axisDirectionVector.map(function (d) {\r\n\t\t\t\treturn d * (range0 + range1) / 2;\r\n\t\t\t}).join(\" \")).append(\"shape\").call(makeSolid, color).append(\"cylinder\").attr(\"radius\", 0.1).attr(\"height\", range1 - range0);\r\n\r\n\t\t\tdomainEnter.merge(domain);\r\n\r\n\t\t\tdomain.exit().remove();\r\n\r\n\t\t\t// Tick Lines\r\n\t\t\tvar ticks = element.selectAll(\".tick\").data(tickValues);\r\n\r\n\t\t\tvar ticksEnter = ticks.enter().append(\"transform\").attr(\"class\", \"tick\").attr(\"translation\", function (t) {\r\n\t\t\t\treturn axisDirectionVector.map(function (a) {\r\n\t\t\t\t\treturn scale(t) * a;\r\n\t\t\t\t}).join(\" \");\r\n\t\t\t}).append(\"transform\").attr(\"translation\", tickDirectionVector.map(function (d) {\r\n\t\t\t\treturn d * tickSize / 2;\r\n\t\t\t}).join(\" \")).attr(\"rotation\", tickRotationVector.join(\" \")).append(\"shape\").call(makeSolid, \"#d3d3d3\").append(\"cylinder\").attr(\"radius\", 0.05).attr(\"height\", tickSize);\r\n\r\n\t\t\tticksEnter.merge(ticks);\r\n\r\n\t\t\tticks.transition().attr(\"translation\", function (t) {\r\n\t\t\t\treturn axisDirectionVector.map(function (a) {\r\n\t\t\t\t\treturn scale(t) * a;\r\n\t\t\t\t}).join(\" \");\r\n\t\t\t});\r\n\r\n\t\t\tticks.exit().remove();\r\n\r\n\t\t\t// Labels\r\n\t\t\tif (tickFormat !== \"\") {\r\n\t\t\t\tvar labels = element.selectAll(\".label\").data(tickValues);\r\n\r\n\t\t\t\tvar labelsEnter = ticks.enter().append(\"transform\").attr(\"class\", \"label\").attr(\"translation\", function (t) {\r\n\t\t\t\t\treturn axisDirectionVector.map(function (a) {\r\n\t\t\t\t\t\treturn scale(t) * a;\r\n\t\t\t\t\t}).join(\" \");\r\n\t\t\t\t}).append(\"transform\").attr(\"translation\", tickDirectionVector.map(function (d, i) {\r\n\t\t\t\t\treturn labelInset * d * tickPadding + (labelInset + 1) / 2 * (range1 - range0) * tickDirectionVector[i];\r\n\t\t\t\t})).append(\"billboard\").attr(\"axisofrotation\", \"0 0 0\").append(\"shape\").call(makeSolid, \"black\").append(\"text\").attr(\"string\", tickFormat).append(\"fontstyle\").attr(\"size\", 1.3).attr(\"family\", \"SANS\").attr(\"style\", \"BOLD\").attr(\"justify\", \"MIDDLE\");\r\n\r\n\t\t\t\tlabelsEnter.merge(labels);\r\n\r\n\t\t\t\tlabels.transition().attr(\"translation\", function (t) {\r\n\t\t\t\t\treturn axisDirectionVector.map(function (a) {\r\n\t\t\t\t\t\treturn scale(t) * a;\r\n\t\t\t\t\t}).join(\" \");\r\n\t\t\t\t}).select(\"transform\").attr(\"translation\", tickDirectionVector.map(function (d, i) {\r\n\t\t\t\t\treturn labelInset * d * tickPadding + (labelInset + 1) / 2 * (range1 - range0) * tickDirectionVector[i];\r\n\t\t\t\t})).on(\"start\", function () {\r\n\t\t\t\t\td3.select(this).select(\"billboard\").select(\"shape\").select(\"text\").attr(\"string\", tickFormat);\r\n\t\t\t\t});\r\n\r\n\t\t\t\tlabels.exit().remove();\r\n\t\t\t}\r\n\t\t});\r\n\t};\r\n\r\n\t/**\r\n * Dimensions Getter / Setter\r\n *\r\n * @param {{x: number, y: number, z: number}} _v - 3D object dimensions.\r\n * @returns {*}\r\n */\r\n\tmy.dimensions = function (_v) {\r\n\t\tif (!arguments.length) return dimensions;\r\n\t\tdimensions = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Scale Getter / Setter\r\n *\r\n * @param {d3.scale} _v - D3 Scale.\r\n * @returns {*}\r\n */\r\n\tmy.scale = function (_v) {\r\n\t\tif (!arguments.length) return scale;\r\n\t\tscale = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Direction Getter / Setter\r\n *\r\n * @param {string} _v - Direction of Axis (e.g. 'x', 'y', 'z').\r\n * @returns {*}\r\n */\r\n\tmy.direction = function (_v) {\r\n\t\tif (!arguments.length) return direction;\r\n\t\tdirection = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Tick Direction Getter / Setter\r\n *\r\n * @param {string} _v - Direction of Ticks (e.g. 'x', 'y', 'z').\r\n * @returns {*}\r\n */\r\n\tmy.tickDirection = function (_v) {\r\n\t\tif (!arguments.length) return tickDirection;\r\n\t\ttickDirection = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Tick Arguments Getter / Setter\r\n *\r\n * @param {Array} _v - Tick arguments.\r\n * @returns {Array<*>}\r\n */\r\n\tmy.tickArguments = function (_v) {\r\n\t\tif (!arguments.length) return tickArguments;\r\n\t\ttickArguments = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Tick Values Getter / Setter\r\n *\r\n * @param {Array} _v - Tick values.\r\n * @returns {*}\r\n */\r\n\tmy.tickValues = function (_v) {\r\n\t\tif (!arguments.length) return tickValues;\r\n\t\ttickValues = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Tick Format Getter / Setter\r\n *\r\n * @param {string} _v - Tick format.\r\n * @returns {*}\r\n */\r\n\tmy.tickFormat = function (_v) {\r\n\t\tif (!arguments.length) return tickFormat;\r\n\t\ttickFormat = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Tick Size Getter / Setter\r\n *\r\n * @param {number} _v - Tick length.\r\n * @returns {*}\r\n */\r\n\tmy.tickSize = function (_v) {\r\n\t\tif (!arguments.length) return tickSize;\r\n\t\ttickSize = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Tick Padding Getter / Setter\r\n *\r\n * @param {number} _v - Tick padding size.\r\n * @returns {*}\r\n */\r\n\tmy.tickPadding = function (_v) {\r\n\t\tif (!arguments.length) return tickPadding;\r\n\t\ttickPadding = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Color Getter / Setter\r\n *\r\n * @param {string} _v - Color (e.g. 'red' or '#ff0000').\r\n * @returns {*}\r\n */\r\n\tmy.color = function (_v) {\r\n\t\tif (!arguments.length) return color;\r\n\t\tcolor = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Label Position Getter / Setter\r\n *\r\n * @param {string} _v - Position ('proximal' or 'distal')\r\n * @returns {*}\r\n */\r\n\tmy.labelPosition = function (_v) {\r\n\t\tif (!arguments.length) return labelPosition;\r\n\t\tlabelPosition = _v;\r\n\t\tlabelInset = labelPosition === \"distal\" ? 1 : -1;\r\n\t\treturn my;\r\n\t};\r\n\r\n\treturn my;\r\n}",
"static update(id, genericDistributionProvider){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.genericDistributionProvider = genericDistributionProvider;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_genericdistributionprovider', 'update', kparams);\n\t}",
"create() {\n this.scaleColor = d3.scaleOrdinal().range(getColor(this.color));\n this.canvas = this.mainCanvas();\n this.transformGroup = this.transformGroup();\n this.addTitles(this.data.title, this.data.subtitle);\n this.addPieArcs(this.data.percentages);\n this.addSideStrokes();\n\n return this;\n }",
"function HistogramScale() {\n // The x scale is a funky one - we may (or may not) have an ordinal chunk\n // and a categorical chunk on the same scale. We want to try to use the\n // available horizontal space, but don't let bars get smaller than 1em\n // wide. Ordinal bars will be mashed together, with 0.25 * barSize of padding\n // on either side of the whole set, whereas categorical bars are spaced out\n // with 0.25 padding on both sides for each individual bar. In addition to\n // drawing, we also need to translate interactions to their nearest bar\n // (TODO: support sub-bin dragging in the ordinal section).\n // Consequently, we write our own scale functions instead of using d3.scale\n // (we need to be able to invert ordinal scales, and decide which range we're\n // actually dealing with)\n\n // The y scale needs to be independently adjustable; we need to keep track\n // of a custom max y, as well as the actual max value of the data\n this.customYmax = null;\n}",
"set probeDensity(value) {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to get the formatter method for a given field key | getFieldFormatter(key) {
const field = this.computedFieldsObj[key]
// `this.computedFieldsObj` has pre-normalized the formatter to a
// function ref if present, otherwise `undefined`
return field ? field.formatter : undefined
} | [
"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}",
"static measuringPointDetailsFieldFormat(sectionProxy, key) {\n\n var binding = sectionProxy.binding;\n\n //Handle the previous reading fields on the point detail screen\n var dateTime;\n if (binding.ReadingDate) {\n dateTime = new OffsetODataDate(sectionProxy,binding.ReadingDate, binding.ReadingTime);\n }\n let value = '';\n switch (key) {\n case 'Reading':\n if (binding.ReadingValue) {\n value = sectionProxy.formatNumber(binding.ReadingValue);\n if (binding.MeasuringPoint.UoM) {\n value = value + ' ' + binding.MeasuringPoint.UoM;\n }\n }\n return value;\n case 'Valuation':\n return libThis.getValuationAndCodeDescription(sectionProxy, binding.ValuationCode, sectionProxy.getPageProxy().binding.CodeGroup, sectionProxy.getPageProxy().binding.CatalogType);\n case 'ReadingDate':\n if (binding.ReadingDate) {\n value = sectionProxy.formatDate(dateTime.date());\n }\n return value;\n case 'ReadingTime':\n if (binding.ReadingTime) {\n value = sectionProxy.formatTime(dateTime.date());\n }\n return value;\n case 'ReadBy':\n if (binding.ReadBy) {\n value = binding.ReadBy;\n }\n return value;\n case 'LowerRange':\n if (binding.IsLowerRange === 'X') {\n value = sectionProxy.formatNumber(binding.LowerRange);\n }\n return value;\n case 'UpperRange':\n if (binding.IsUpperRange === 'X') {\n value = sectionProxy.formatNumber(binding.UpperRange);\n }\n return value;\n case 'Characteristic':\n if (!libVal.evalIsEmpty(binding.CharName)) {\n value = libForm.getFormattedKeyDescriptionPair(sectionProxy, binding.CharName, binding.CharDescription);\n }\n return value;\n case 'Difference':\n if (binding.IsCounterReading === 'X') {\n value = sectionProxy.formatNumber(binding.CounterReadingDifference);\n }\n return value;\n case 'CurrentReading':\n var recordedValue = binding.RecordedValue;\n if (!libVal.evalIsEmpty(recordedValue)) {\n value = sectionProxy.formatNumber(recordedValue) + ' ' + binding.UOM;\n }\n return value;\n case 'CurrentShortText':\n return libVal.evalIsEmpty(binding.ShortText) ? '' : binding.ShortText;\n default:\n return '';\n }\n }",
"getLookupFieldName(fieldName) {\n let lookupFieldName = fieldName;\n if (fieldName) {\n let lowercaseFieldName = fieldName.toLowerCase();\n if (lowercaseFieldName.endsWith(\"id\")) {\n // standard fields are same name but without 'Id' suffix\n lookupFieldName = fieldName.slice(0, -2);\n } else if (lowercaseFieldName.endsWith(\"__c\")) {\n // custom fields have __r suffix instead of __c suffix\n lookupFieldName = fieldName.slice(0, -1) + \"r\";\n }\n }\n return lookupFieldName;\n }",
"static measurementDocumentFieldFormat(sectionProxy) {\n var section = sectionProxy.getName();\n var property = sectionProxy.getProperty();\n var binding = sectionProxy.binding;\n let format = '';\n switch (section) {\n case 'MeasurementDocumentsList': {\n\n switch (property) {\n case 'Footnote': {\n let offset = -1 * libCom.getBackendOffsetFromSystemProperty(sectionProxy);\n let odataDate = new ODataDate(binding.ReadingDate, binding.ReadingTime, offset);\n format = sectionProxy.formatDatetime(odataDate.date());\n break;\n }\n case 'Subhead': {\n format = binding.ReadBy;\n break;\n }\n case 'Description': {\n let value = '';\n if (!libVal.evalIsEmpty(binding.ValuationCode)) {\n if (!libVal.evalIsEmpty(value)) {\n value = value + ': ';\n }\n value = value + libForm.getFormattedKeyDescriptionPair(sectionProxy, binding.ValuationCode, binding.CodeShortText);\n }\n format = value;\n break;\n }\n case 'Title': {\n let value = '';\n if (binding.HasReadingValue === 'X') {\n value = binding.ReadingValue + value + ' ' + binding.UOM;\n } else {\n value = binding.ReadingValue + ' ' + binding.MeasuringPoint.UoM;\n }\n if (!libVal.evalIsEmpty(binding.ValuationCode)) {\n if (!libVal.evalIsEmpty(value)) {\n value = value + ': ';\n }\n value = value + libForm.getFormattedKeyDescriptionPair(sectionProxy, binding.ValuationCode, binding.CodeShortText);\n }\n format = value;\n break;\n }\n default:\n break;\n }\n break;\n }\n default:\n break;\n }\n return format;\n }",
"static getFieldInfoByName(field_name){\n\t}",
"renderField() {}",
"function getErrorField(_fieldKey) {\n\n // console.log('++++fieldKey', _fieldKey);\n\n var errorField;\n var fieldKey;\n if (_.contains(_fieldKey, 'ui-select-extended')) {\n errorField = _fieldKey.split('ui-select-extended_')[1];\n fieldKey = errorField.split('_')[0];\n } else {\n if (_fieldKey.startsWith('obs')) {\n errorField = _fieldKey.split('obs')[1];\n fieldKey = 'obs' + errorField.split('_')[0] + '_' + errorField.split('_')[1];\n }\n }\n\n var field = FormentryService.getFieldByIdKey(fieldKey, $scope.vm.tabs);\n // console.log('error Field ', field);\n return field;\n }",
"getFieldType() {\n return this._fieldTypeId\n }",
"function FILTER_KEY(key) {\n var string = %ToString(key);\n if (%HasProperty(this, string)) return string;\n return 0;\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 outputFldName(fld) {\n const prefixLen = currentSettingGroup.length,\n shortFldName = prefixLen && fld.startsWith(`${currentSettingGroup}_`)\n ? ` ${fld.substring(prefixLen + 1)}`\n : fld;\n return shortFldName.replaceAll('_', ' ');\n }",
"function formatValore(field)\n{\n\tformatDecimal(field,9,6,true);\n}",
"isKeyField() {\n return 1 === this.length && \"__name__\" === this.get(0);\n }",
"function field(obj, pathString) {\n if (!obj || typeof pathString !== 'string') return '';\n function fn(obj, path) {\n var prop = path.shift();\n if (!(prop in obj) || obj[prop] == null) return '';\n if (path.length) {\n return fn(obj[prop], path);\n }\n return String(obj[prop]);\n }\n return fn(obj, pathString.split('.'));\n}",
"formatValue(cell){\n\t\tvar component = cell.getComponent(),\n\t\tparams = typeof cell.column.modules.format.params === \"function\" ? cell.column.modules.format.params(component) : cell.column.modules.format.params;\n\t\t\n\t\tfunction onRendered(callback){\n\t\t\tif(!cell.modules.format){\n\t\t\t\tcell.modules.format = {};\n\t\t\t}\n\t\t\t\n\t\t\tcell.modules.format.renderedCallback = callback;\n\t\t\tcell.modules.format.rendered = false;\n\t\t}\n\t\t\n\t\treturn cell.column.modules.format.formatter.call(this, component, params, onRendered);\n\t}",
"dateToKey(date){\n return format(date,'DD/MM/YYYY')\n }",
"function transformFieldValue (field, item, options) {\n\tvar transform = typeof field.options.toCSV === 'string'\n\t\t? listToArray(field.options.toCSV)\n\t\t: field.options.toCSV;\n\tif (typeof transform === 'function') {\n\t\treturn transform.call(item, field, options);\n\t}\n\tif (Array.isArray(transform)) {\n\t\tvar value = item.get(field.path);\n\t\tif (transform.length === 1) {\n\t\t\treturn value[transform[0]];\n\t\t} else {\n\t\t\treturn _.pick(value, transform);\n\t\t}\n\t}\n\treturn field.format(item);\n}",
"static getFieldProps(key, props){\n return {\n iconmap: IconMap[key],\n id : key,\n name : key,\n value : props.values?.[key],\n error : props.errors?.[key],\n };\n }",
"get fieldValue(){}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Chord Bank, Patch and PitchwheelDeviation messages Returns undefined if there are no attributes | function attributesMoment(channel, midiChordDef)
{
var attrMoment,
msg,
attributes;
/// Sets both RegisteredParameter controls to 0 (zero). This is standard MIDI for selecting the
/// pitch wheel so that it can be set by the subsequent DataEntry messages.
/// A DataEntryFine message is not set, because it is not needed and has no effect anyway.
/// However, RegisteredParameterFine MUST be set, otherwise the messages as a whole have no effect!
function setPitchwheelDeviation(attrMoment, deviation, channel)
{
var msg;
msg = new Message(CMD.CONTROL_CHANGE + channel, CTL.REGISTERED_PARAMETER_COARSE, 0);
attrMoment.messages.push(msg);
msg = new Message(CMD.CONTROL_CHANGE + channel, CTL.REGISTERED_PARAMETER_FINE, 0);
attrMoment.messages.push(msg);
msg = new Message(CMD.CONTROL_CHANGE + channel, CTL.DATA_ENTRY_COARSE, deviation);
attrMoment.messages.push(msg);
}
if(midiChordDef.attributes !== undefined)
{
attributes = midiChordDef.attributes;
attrMoment = new Moment(0); // the attributes moment is always the first moment in the chord
// the id, and minBasicChordMsDuration attributes are not midi messages
// the hasChordOff attribute is dealt with later.
if(attributes.bank !== undefined)
{
msg = new Message(CMD.CONTROL_CHANGE + channel, 0, attributes.bank); // 0 is bank control
attrMoment.messages.push(msg);
}
if(attributes.patch !== undefined)
{
msg = new Message(CMD.PROGRAM_CHANGE + channel, attributes.patch, 0);
attrMoment.messages.push(msg);
}
if(attributes.pitchWheelDeviation !== undefined)
{
setPitchwheelDeviation(attrMoment, attributes.pitchWheelDeviation, channel);
}
}
return attrMoment;
} | [
"function getChordMoments(channel, midiChordDef, msDurationInScore)\n\t\t{\n\t\t\tvar i, j,\n len = midiChordDef.basicChordsArray.length,\n pitches,\n pitchesLength,\n basicChordDef,\n msPositionInChord = 0,\n allNoteOffs = [],\n chordMoments = [],\n noteNumber,\n moment,\n currentMoment,\n msDurationOfBasicChords;\n\n\t\t\t// NEW: bcMsDurations(basicChords) simply returns an array containing the durations of the basic Chords,\n\t\t\t// taking no account of the global speed option.\n\t\t\t// Replaces:\n\t\t\t// function bcMsDurations(basicChords, totalMsDuration), which adjusted the durations to the duration\n\t\t\t// of the MidiChord in the score, taking the global speed option into account.\n\t\t\tfunction bcMsDurations(basicChords)\n\t\t\t{\n\t\t\t\tvar msDurations = [], i, basicChordsLength = basicChords.length;\n\n\t\t\t\tif(basicChordsLength < 1)\n\t\t\t\t{\n\t\t\t\t\tthrow \"Condition: there must be at least one basic chord here.\";\n\t\t\t\t}\n\n\t\t\t\tfor(i = 0; i < basicChordsLength; ++i)\n\t\t\t\t{\n\t\t\t\t\tmsDurations.push(basicChords[i].msDuration);\n\t\t\t\t}\n\n\t\t\t\treturn msDurations;\n\t\t\t}\n\n\t\t\tfunction sumBCMD(basicChordMsDurations)\n\t\t\t{\n\t\t\t\tvar i, sum = 0;\n\t\t\t\tfor(i = 0; i < basicChordMsDurations.length; ++i)\n\t\t\t\t{\n\t\t\t\t\tsum += basicChordMsDurations[i];\n\t\t\t\t}\n\t\t\t\treturn sum;\n\t\t\t}\n\n\t\t\t// Chord Bank, Patch and PitchwheelDeviation messages\n\t\t\t// Returns undefined if there are no attributes\n\t\t\tfunction attributesMoment(channel, midiChordDef)\n\t\t\t{\n\t\t\t\tvar attrMoment,\n msg,\n attributes;\n\n\t\t\t\t/// Sets both RegisteredParameter controls to 0 (zero). This is standard MIDI for selecting the\n\t\t\t\t/// pitch wheel so that it can be set by the subsequent DataEntry messages.\n\t\t\t\t/// A DataEntryFine message is not set, because it is not needed and has no effect anyway.\n\t\t\t\t/// However, RegisteredParameterFine MUST be set, otherwise the messages as a whole have no effect!\n\t\t\t\tfunction setPitchwheelDeviation(attrMoment, deviation, channel)\n\t\t\t\t{\n\t\t\t\t\tvar msg;\n\t\t\t\t\tmsg = new Message(CMD.CONTROL_CHANGE + channel, CTL.REGISTERED_PARAMETER_COARSE, 0);\n\t\t\t\t\tattrMoment.messages.push(msg);\n\t\t\t\t\tmsg = new Message(CMD.CONTROL_CHANGE + channel, CTL.REGISTERED_PARAMETER_FINE, 0);\n\t\t\t\t\tattrMoment.messages.push(msg);\n\t\t\t\t\tmsg = new Message(CMD.CONTROL_CHANGE + channel, CTL.DATA_ENTRY_COARSE, deviation);\n\t\t\t\t\tattrMoment.messages.push(msg);\n\t\t\t\t}\n\n\t\t\t\tif(midiChordDef.attributes !== undefined)\n\t\t\t\t{\n\t\t\t\t\tattributes = midiChordDef.attributes;\n\t\t\t\t\tattrMoment = new Moment(0); // the attributes moment is always the first moment in the chord\n\n\t\t\t\t\t// the id, and minBasicChordMsDuration attributes are not midi messages\n\t\t\t\t\t// the hasChordOff attribute is dealt with later.\n\t\t\t\t\tif(attributes.bank !== undefined)\n\t\t\t\t\t{\n\t\t\t\t\t\tmsg = new Message(CMD.CONTROL_CHANGE + channel, 0, attributes.bank); // 0 is bank control\n\t\t\t\t\t\tattrMoment.messages.push(msg);\n\t\t\t\t\t}\n\t\t\t\t\tif(attributes.patch !== undefined)\n\t\t\t\t\t{\n\t\t\t\t\t\tmsg = new Message(CMD.PROGRAM_CHANGE + channel, attributes.patch, 0);\n\t\t\t\t\t\tattrMoment.messages.push(msg);\n\t\t\t\t\t}\n\n\t\t\t\t\tif(attributes.pitchWheelDeviation !== undefined)\n\t\t\t\t\t{\n\t\t\t\t\t\tsetPitchwheelDeviation(attrMoment, attributes.pitchWheelDeviation, channel);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn attrMoment;\n\t\t\t}\n\n\t\t\t// BasicChord Bank, Patch and ChordOn messages\n\t\t\tfunction basicChordOnMoment(channel, basicChordDef, msPosition)\n\t\t\t{\n\t\t\t\tvar midiNotes = basicChordDef.pitches,\n midiVelocities = basicChordDef.velocities,\n len = midiNotes.length,\n message,\n bcoMoment = new Moment(msPosition),\n i;\n\n\t\t\t\tif(basicChordDef.bank !== undefined) // default is dont send a bank change\n\t\t\t\t{\n\t\t\t\t\tmessage = new Message(CMD.CONTROL_CHANGE + channel, basicChordDef.bank, 0);\n\t\t\t\t\tbcoMoment.messages.push(message);\n\n\t\t\t\t\tmessage = new Message(CMD.PROGRAM_CHANGE + channel, basicChordDef.patch, 0);\n\t\t\t\t\tbcoMoment.messages.push(message);\n\t\t\t\t}\n\t\t\t\telse if(basicChordDef.patch !== undefined) // default is dont send a patch change\n\t\t\t\t{\n\t\t\t\t\tmessage = new Message(CMD.PROGRAM_CHANGE + channel, basicChordDef.patch, 0);\n\t\t\t\t\tbcoMoment.messages.push(message);\n\t\t\t\t}\n\n\t\t\t\tfor(i = 0; i < len; ++i)\n\t\t\t\t{\n\t\t\t\t\tmessage = new Message(CMD.NOTE_ON + channel, midiNotes[i], midiVelocities[i]);\n\t\t\t\t\tbcoMoment.messages.push(message);\n\t\t\t\t}\n\n\t\t\t\treturn bcoMoment;\n\t\t\t}\n\n\t\t\tfunction basicChordOffMoment(channel, basicChordDef, msPosition)\n\t\t\t{\n\t\t\t\tvar pitches = basicChordDef.pitches,\n len = pitches.length,\n velocity = 127,\n bcoffMoment = new Moment(msPosition),\n message,\n i;\n\n\t\t\t\tfor(i = 0; i < len; ++i)\n\t\t\t\t{\n\t\t\t\t\tmessage = new Message(CMD.NOTE_OFF + channel, pitches[i], velocity);\n\t\t\t\t\tbcoffMoment.messages.push(message);\n\t\t\t\t}\n\n\t\t\t\treturn bcoffMoment;\n\t\t\t}\n\n\t\t\t// noteOffs contains all the noteNumbers that need to be sent a noteOff,\n\t\t\t// noteOffs contains duplicates. Avoid creating duplicate noteOffs in this function.\n\t\t\tfunction chordOffMoment(channel, noteOffs, msPosition)\n\t\t\t{\n\t\t\t\tvar uniqueNoteNumbers = [], nnIndex, noteNumber,\n velocity = 127,\n cOffMoment = new Moment(msPosition),\n message;\n\n\t\t\t\tfunction getUniqueNoteNumbers(noteOffs)\n\t\t\t\t{\n\t\t\t\t\tvar unique = [], i, length = noteOffs.length, val;\n\t\t\t\t\tfor(i = 0; i < length; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tval = noteOffs[i];\n\t\t\t\t\t\tif(unique.indexOf(val) === -1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tunique.push(val);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn unique;\n\t\t\t\t}\n\n\t\t\t\tuniqueNoteNumbers = getUniqueNoteNumbers(noteOffs);\n\n\t\t\t\tfor(nnIndex = 0; nnIndex < uniqueNoteNumbers.length; ++nnIndex)\n\t\t\t\t{\n\t\t\t\t\tnoteNumber = uniqueNoteNumbers[nnIndex];\n\t\t\t\t\tmessage = new Message(CMD.NOTE_OFF + channel, noteNumber.valueOf(), velocity);\n\t\t\t\t\tcOffMoment.messages.push(message);\n\t\t\t\t}\n\n\t\t\t\treturn cOffMoment;\n\t\t\t}\n\n\t\t\t// initial AttributesMoment\n\t\t\tcurrentMoment = attributesMoment(channel, midiChordDef);\n\t\t\tif(currentMoment !== undefined)\n\t\t\t{\n\t\t\t\tchordMoments.push(currentMoment);\n\t\t\t}\n\n\t\t\t// old: these basicChordMsDurations take the global speed option into account.\n\t\t\t// old: basicChordMsDurations = bcMsDurations(midiChordDef.basicChordsArray, timeObject.msDuration);\n\t\t\t// new: these basicChordMsDurations do NOT take the global speed option into account.\n\t\t\tbasicChordMsDurations = bcMsDurations(midiChordDef.basicChordsArray);\n\t\t\tmsDurationOfBasicChords = sumBCMD(basicChordMsDurations);\n\n\t\t\t// BasicChordMoments\n\t\t\tfor(i = 0; i < len; i++)\n\t\t\t{\n\t\t\t\tbasicChordDef = midiChordDef.basicChordsArray[i];\n\n\t\t\t\tif(midiChordDef.attributes.hasChordOff === undefined || midiChordDef.attributes.hasChordOff === true)\n\t\t\t\t{\n\t\t\t\t\tpitches = basicChordDef.pitches;\n\t\t\t\t\tpitchesLength = pitches.length;\n\t\t\t\t\tfor(j = 0; j < pitchesLength; ++j)\n\t\t\t\t\t{\n\t\t\t\t\t\tnoteNumber = pitches[j];\n\t\t\t\t\t\tif(allNoteOffs.indexOf(noteNumber) === -1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tallNoteOffs.push(noteNumber);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// allNoteOffs is used at the end of the ornament to turn notes off that were turned on during the ornament.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmoment = basicChordOnMoment(channel, basicChordDef, msPositionInChord);\n\n\t\t\t\tif(currentMoment !== undefined && currentMoment.msPositionInChord === moment.msPositionInChord)\n\t\t\t\t{\n\t\t\t\t\tcurrentMoment.mergeMoment(moment);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tchordMoments.push(moment);\n\t\t\t\t\tcurrentMoment = moment;\n\t\t\t\t}\n\n\t\t\t\tmsPositionInChord += basicChordMsDurations[i];\n\n\t\t\t\tif(basicChordDef.hasChordOff === undefined || basicChordDef.hasChordOff === true)\n\t\t\t\t{\n\t\t\t\t\t// chordOff always comes after chordOn\n\t\t\t\t\tcurrentMoment = basicChordOffMoment(channel, basicChordDef, msPositionInChord);\n\t\t\t\t\tchordMoments.push(currentMoment);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// finalChordOffMoment contains a noteOFF for each note that has been sent a noteON during the BasicChordMoments.\n\t\t\tif(midiChordDef.attributes.hasChordOff === undefined || midiChordDef.attributes.hasChordOff === true)\n\t\t\t{\n\t\t\t\tif(allNoteOffs.length === 0)\n\t\t\t\t{\n\t\t\t\t\tthrow \"Error: this chord must have sent at least one note!\";\n\t\t\t\t}\n\t\t\t\tfinalChordOffMoment = chordOffMoment(channel, allNoteOffs, msDurationInScore);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfinalChordOffMoment = new Moment(msDurationInScore);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\t\"chordMoments\": chordMoments,\n\t\t\t\t\"finalChordOffMoment\": finalChordOffMoment,\n\t\t\t\t\"msDurationOfBasicChords\": msDurationOfBasicChords\n\t\t\t};\n\t\t}",
"function formatTacktickMessage(data) {\n var key = data.subtype === 'heading'?'FFP':'FFD';\n key += data.index;\n\n var parts = [\"PTAK\",key].concat(data.values);\n return parts.join(',');\n}",
"buildHpiNarrative(patient) {\n let hpiText = this.buildInitialPatientDiagnosisPreamble(patient);\n \n // Staging\n const staging = this.getMostRecentStaging();\n if (staging) {\n if (staging.stage) {\n hpiText += ` Stage ${staging.stage}`;\n }\n if (!Lang.isUndefined(staging.t_Stage) && !Lang.isNull(staging.t_Stage)) {\n hpiText += ` ${staging.t_Stage}`;\n }\n if (!Lang.isUndefined(staging.n_Stage) && !Lang.isNull(staging.n_Stage)) {\n hpiText += ` ${staging.n_Stage}`;\n }\n if (!Lang.isUndefined(staging.m_Stage) && !Lang.isNull(staging.m_Stage) && staging.m_Stage !== 'M0') { // don't show m if it is 0\n hpiText += ` ${staging.m_Stage}`;\n }\n if (staging.mitoticRate) {\n hpiText += `. Mitotic rate ${staging.mitoticRate}`;\n }\n hpiText += '.';\n }\n\n // Tumor Size and HistologicGrade\n const tumorSize = this.getObservationsOfType(FluxTumorDimensions);\n const histologicGrade = this.getObservationsOfType(FluxHistologicGrade);\n if (tumorSize.length > 0) {\n hpiText += ` Primary tumor size ${tumorSize[tumorSize.length - 1].quantity.number} ${tumorSize[tumorSize.length - 1].quantity.unit}.`;\n }\n if (histologicGrade.length > 0) {\n hpiText += ` ${histologicGrade[0].grade}.`;\n }\n\n // genetics\n const geneticpanels = patient.getGastrointestinalStromalTumorCancerGeneticAnalysisPanelsChronologicalOrder();\n //const geneticspanelMostRecent = geneticpanels[geneticpanels.length - 1];\n if (geneticpanels && geneticpanels.length > 0) {\n const panel = geneticpanels.pop();\n hpiText += \" \" + panel.members.map((item) => {\n const v = item.value === 'Positive' ? '+' : '-';\n return item.abbreviatedName + v;\n }).join(\",\");\n }\n\n hpiText = this.buildEventNarrative(hpiText, patient, this.code);\n \n return hpiText;\n }",
"function drawFeedback() {\n 'use strict';\n let ctx = document.getElementById('canvas').getContext('2d');\n let dat = jsPsych.data.get().last(1).values()[0];\n ctx.font = prms.fbFont;\n ctx.textAlign = 'center';\n ctx.textBaseline = 'middle';\n ctx.fillStyle = 'black';\n ctx.fillText(prms.fbTxt[dat.corrCode], dat.end_x, dat.end_y);\n}",
"function requiredDialogProps () {\n return {\n title: '๐ฏ Add credits',\n message: <Typography variant='body1'>Cannot start with no bet credits, you should add some</Typography>,\n type: 'error'\n }\n}",
"function bcMsDurations(basicChords)\n\t\t\t{\n\t\t\t\tvar msDurations = [], i, basicChordsLength = basicChords.length;\n\n\t\t\t\tif(basicChordsLength < 1)\n\t\t\t\t{\n\t\t\t\t\tthrow \"Condition: there must be at least one basic chord here.\";\n\t\t\t\t}\n\n\t\t\t\tfor(i = 0; i < basicChordsLength; ++i)\n\t\t\t\t{\n\t\t\t\t\tmsDurations.push(basicChords[i].msDuration);\n\t\t\t\t}\n\n\t\t\t\treturn msDurations;\n\t\t\t}",
"function BandRatio_getNotifyFraction() {\n\tvar returnStr = \"Please get values for \";\n\tvar isSelectedAll = true;\n\tif(bandRatioNumeratorValues.length === 0 ) {\n\t\treturnStr = returnStr + \" Numerator and \";\n\t\tisSelectedAll = false;\n\t}\n\n\tif(bandRatioDenominatorValues.length === 0 ) {\n\t\treturnStr = returnStr + \" Denominator \";\n\t\tisSelectedAll = false;\n\t}\n\n\t// no notify if numerator and denomiator has values\n\tif(isSelectedAll) {\n\t\treturnStr = \"Numerator and Denominator selected\";\n\t}\n\n\t$(\"#bandRatioNotification\").text(returnStr);\n}",
"function jtabChord (token) {\n\n this.scale = jtab.WesternScale;\n this.baseNotes = this.scale.BaseNotes;\n this.baseChords = jtab.Chords;\n this.chordArray = null;\n this.isValid = false;\n\n this.fullChordName = token;\n this.isCustom = ( this.fullChordName.match( /\\%/ ) != null )\n this.isCaged = ( this.fullChordName.match( /\\:/ ) != null )\n\n\n if (this.isCaged) {\n var parts = this.fullChordName.split(':');\n this.chordName = parts[0];\n this.cagedPos = parts[1];\n } else if (this.isCustom){\n var parts = this.fullChordName.match( /\\[(.+?)\\]/ );\n if(parts){\n this.chordName = parts[1];\n } else {\n this.chordName = '';\n }\n } else {\n this.chordName = this.fullChordName;\n this.cagedPos = 1;\n }\n this.rootExt = this.chordName.replace(/^[A-G#b]{1,2}/,'');\n this.rootNote = this.chordName.substr(0, this.chordName.length - this.rootExt.length);\n var baseNoteInfo = this.baseNotes[this.rootNote];\n if (baseNoteInfo) {\n this.baseName = baseNoteInfo[0] + this.rootExt;\n this.cagedBaseShape = baseNoteInfo[1];\n this.cagedBaseFret = baseNoteInfo[2];\n } else {\n this.cagedBaseShape = '';\n this.cagedBaseFret = 0;\n }\n if ( ( this.isCaged ) && ( this.cagedPos > 1 ) ) {\n this.setCagedChordArray();\n } else if (this.isCustom){\n this.setCustomChordArray();\n } else {\n this.setChordArray(this.baseName);\n }\n}",
"function getChord() {\n //get all playing keys\n var keys = document.querySelectorAll(\".key.playing\");\n\n //if less than 2 keys there is no chord, return blank\n if (keys.length < 2) {\n return \"\";\n }\n\n //get bass note (lowest playing note)\n var bass = keys[0].dataset.note;\n //get indicies of currently playing notes\n var indicies = [];\n for (i = 0; i < keys.length; i++) {\n indicies.push(keys[i].dataset.pos);\n }\n\n //test every note as a potential root in order\n for (i = 0; i < keys.length; i++) {\n //set current root to test\n var root = i;\n\n //get intervals of all notes from root; stored as a set\n let intervals = new Set();\n for (j = 0; j < indicies.length; j++) {\n //get interval between root and current note\n //if current note is < root shift it an octave up for calculations\n if ((indicies[j] % 12) < (indicies[root] % 12)) {\n var interval = Math.abs(((indicies[j] % 12) + 12) - (indicies[root] % 12));\n }\n else {\n var interval = Math.abs((indicies[j] % 12) - (indicies[root] % 12));\n }\n //mudolo to remove compound intervals\n interval = interval % 12;\n //add interval to set of intervals\n intervals.add(interval);\n }\n\n //loop through every chord in the chord db\n for (j = 0; j < chords.length; j++) {\n //if match found return chord\n if (chordEq(chords[j].intervals, intervals)) {\n //add root note and notation to chord display\n var chord = keys[root].dataset.note + chords[j].notation;\n //if bass note is different from the root add it\n if (bass != keys[root].dataset.note) {\n chord += \"\\\\\" + bass;\n }\n\n return chord\n }\n }\n }\n \n //nothing found; return blank\n return \"\";\n}",
"function getExplorerCgCircleText(d) {\n if (!d || !d.data || !d.data.name) return \"UNDEFINED 'D'\";\n else if (currentFrameworkCompetencyData.competencyD3NodeTrackerMap[d.data.name]) {\n var text = getCompetencyName(d.data.name);\n if (text == \"\") text = \"UNDEFINED NODE PACKET\";\n return text;\n }\n return \"UNDEFINED NAME\";\n}",
"ensureParsed() {\n if (this.message_ === null) {\n var parsed = Description.parse(this.text_);\n this.message_ = parsed[0];\n this.attributes_ = parsed[1];\n }\n }",
"parseHeader() {\n\t\tif (this.fetchString(4) === 'MThd') { /* console.log('MThd'); */\n\t\t} else {\n\t\t\tconsole.log('ERROR: No MThd');\n\t\t\tthis.error = { code: 1, pos: ppos, msg: 'No MIDI header detected.' };\n\t\t\treturn;\n\t\t}\n\t\tif (this.fetchBytes(4) !== 6) {\n\t\t\tconsole.log('ERROR: File header is not 6 bytes long.');\n\t\t\tthis.error = { code: 2, pos: ppos, msg: 'Unrecognized MIDI header length.' };\n\t\t\treturn;\n\t\t}\n\t\tthis.fmt = this.fetchBytes(2);\n\t\tif (this.fmt > 2) {\n\t\t\tconsole.log('ERROR: Unrecognized format number.');\n\t\t\tthis.error = { code: 3, pos: ppos, msg: 'Unrecognized MIDI format number.' };\n\t\t}\n\t\tthis.ntrks = this.fetchBytes(2);\n\t\t// console.log('Format '+this.fmt+', '+this.ntrks+' tracks');\n\n\t\t// Parse timing division\n\t\tlet tdiv = this.fetchBytes(2);\n\t\tif (!(tdiv >> 16)) {\n\t\t\t// console.log(tdiv+' ticks per quarter note');\n\t\t\tthis.timing = tdiv;\n\t\t} else {\n\t\t\tconsole.log('SMPTE timing format is unsupported.');\n\t\t\talert('SMPTE timing format is currently unsupported. Please give feedback if you see this message.');\n\t\t\tthis.timingFormat = 1;\n\t\t}\n\t}",
"function getZaxisText(){\n var units;\n \n if(layerDetails.zaxis !== undefined){\n units= layerDetails.zaxis.units.toLowerCase();\n\t\n\t//TODO we can't use the corrent name from the properties because the text\n\t// is being filled by javascript but it has to be a better way\n\n if(units === 'pa') {\n\t\treturn presText;\n\n }\n else if( (units === 'm') || (units === 'meter'))\n {\n if(layerDetails.zaxis.positive){\n return heightText; \n }else{\n return depthText; \n }\n }\n else if(units === 'pa' || units === \"pressure\" || units === \"bar\" || units === \"at\" || units === \"atm\" || units === \"torr\" ) {\n return presText;\n } else if( (units === 'm') || (units === 'meter') || (units === 'km') || (units === 'ft') || (units === 'mi') ) {\n if(layerDetails.zaxis.positive){\n return heightText; \n }else{\n return depthText; \n } \n } else {\n return depthText+\" / \"+presText; \n }\n } else {\n return \"UNDEFINED\";\n }\n}",
"describeMeterData(meterData = false) {\n if (!meterData)\n return 'unknown';\n\n const types = {\n '06': 'VolumeHeat',\n '16': 'VolumeCold'\n }\n\n let meterType = types.hasOwnProperty(meterData['deviceType']) ?\n types[meterData['deviceType']] : \"unknown\";\n return `${meterData['label']} (${meterType})`;\n }",
"displayDificalty(diff) {\n difficulty = diff;\n textSize(15);\n if (difficulty == 5) {\n text(\"Inside joke:\", 19, 273);\n } else if (difficulty == 4) {\n text(\"Phrase:\", 19, 273);\n\n } else if (difficulty == 2) {\n text(\"Moderate phrase:\", 19, 273);\n\n } else if (difficulty == 3) {\n text(\"Hard phrase:\", 19, 273);\n\n } else if (difficulty == 1) {\n text(\"Easy phrase:\", 19, 273);\n } else {\n text(\"Your phrase:\", 19, 273);\n }\n }",
"function checkAttributes(attributes) {\n const badgeEl = rootEl.shadowRoot.getRootNode().querySelector(\".badge\");\n const textEl = rootEl.shadowRoot.getRootNode().querySelector(\".text\");\n\n expect(badgeEl).toBeDefined();\n expect(textEl).toBeDefined();\n expect(textEl.innerText).toBe(attributes.text);\n expect(rgbToHex(badgeEl.style.color)).toBe(attributes[\"text-color\"]);\n expect(rgbToHex(badgeEl.style.backgroundColor)).toBe(\n attributes[\"background-color\"]\n );\n if (attributes[\"border-color\"] === \"transparent\") {\n expect(badgeEl.style.borderColor).toBe(attributes[\"border-color\"]);\n } else {\n expect(rgbToHex(badgeEl.style.borderColor)).toBe(\n attributes[\"border-color\"]\n );\n }\n\n if (attributes[\"has-animation\"] === \"true\") {\n expect(badgeEl.classList.contains(\"animated\")).toBeTrue();\n } else {\n expect(badgeEl.classList.contains(\"animated\")).toBeFalse();\n }\n\n expect(badgeEl.classList.contains(attributes.position)).toBeTrue();\n }",
"function ServerBehavior_toString()\n{\n var partStr = \"\";\n for (var i = 0; i < this.sbParticipants.length; ++i)\n {\n partStr += ((partStr.length) ? \", \" : \"\") + this.sbParticipants[i].getName();\n }\n \n var str = \"ServerBehavior Instance\\n\"\n + \"=======================\\n\"\n + \"Name: \" + this.name + \"\\n\"\n + \"Title: \" + this.title + \"\\n\"\n + \"Parameters: {\" + this.getParameters() + \"}\\n\"\n + \"IsIncomplete: \" + this.incomplete + \"\\n\"\n + \"Participants: \" + partStr + \"\\n\"\n + \"ForceMultipleUpdate: \" + this.bForceMultipleUpdate + \"\\n\"\n + \"ForcePriorUpdate: \" + this.forcePriorUpdate + \"\\n\"\n + \"Family: \" + this.family + \"\\n\"\n + \"Errors: \" + this.errorMsg + \"\\n\"\n + \"UD4 backward compatible? \" + (this.type != null) + \"\\n\";\n\n // Add UD4 backward compatible properties if it is backward compatible.\n if (this.type != null)\n {\n str += \"\\nUD4 Backward Compatible Properties\\n\"\n + \"==================================\\n\"\n + \"Type: \" + this.type + \"\\n\"\n + \"ServerBehavior: \" + this.serverBehavior + \"\\n\"\n + \"SubType: \" + this.subType + \"\\n\"\n + \"DataSource: \" + this.dataSource + \"\\n\"\n + \"Params: \" + this.params + \"\\n\"\n + \"DeleteTypes: \" + this.deleteTypes + \"\\n\"\n + \"Weights: \" + this.weights + \"\\n\"\n + \"Types: \" + this.types + \"\\n\"; \n }\n\n return str;\n}",
"function getBasicChord(chord) {\n\tchordNotes = [1, 5, 8, 10];\n\treturn chordNotes.map(rel => getIntervalNote(chord + chordData.baseOctave, rel));\n}",
"function displayChord(el) {\n // first, clear the diagram that involves toggling so we can reuse functions\n clearDiagram();\n\n pressedDownStrings = getByValue(chordMap, el.innerHTML).split(',');\n\n for(let i = 0; i < pressedDownStrings.length; ++i) {\n pressedDownStrings[i] = parseInt(pressedDownStrings[i]);\n }\n\n\n for(let i = 1; i <= 6; ++i) {\n if(pressedDownStrings[i] == -1) {\n // set closed string to closed\n toggleStringClosed(document.getElementById(\"string-\"+i));\n }\n // if it's an open chord do nothing\n else if(pressedDownStrings[i] != 0) {\n let id = pressedDownStrings[i]+'-'+i;\n toggleClick(document.getElementById(pressedDownStrings[i]+'-'+i));\n }\n }\n\n // really setting the barre :)\n if(pressedDownStrings[0] != 0) {\n let barreInput = document.getElementById(\"barre-input\");\n barreInput.value = pressedDownStrings[0];\n\n doBarreGraphic(barreInput);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate the database name | function validateDatabaseName(databaseName) {
if (typeof databaseName !== 'string')
throw MongoError.create({ message: 'database name must be a string', driver: true });
if (databaseName.length === 0)
throw MongoError.create({ message: 'database name cannot be the empty string', driver: true });
if (databaseName === '$external') return;
const invalidChars = [' ', '.', '$', '/', '\\'];
for (let i = 0; i < invalidChars.length; i++) {
if (databaseName.indexOf(invalidChars[i]) !== -1)
throw MongoError.create({
message: "database names cannot contain the character '" + invalidChars[i] + "'",
driver: true
});
}
} | [
"function name_check() {\r\n name_warn();\r\n final_validate();\r\n}",
"function nameValidation() {\n // Name validation\n const nameValue = name.value;\n const nameValidator = /[a-zA-z]+/.test(nameValue);\n\n return nameValidator;\n}",
"function getLegalDBName(input) {\n input = input.toLowerCase();\n var output = encodeURIComponent(input);\n output = output.replace(/\\./g, '%2E');\n output = output.replace(/!/g, '%21');\n output = output.replace(/~/g, '%7E');\n output = output.replace(/\\*/g, '%2A');\n output = output.replace(/'/g, '%27');\n output = output.replace(/\\(/g, '%28');\n output = output.replace(/\\)/g, '%29');\n output = output.replace(/\\-/g, '%2D');\n output = output.toLowerCase();\n output = output.replace(/(%..)/g, function(esc) {\n esc = esc.substr(1);\n return '(' + esc + ')';\n });\n return output;\n}",
"function validName(input) {\n return input.length > 0\n }",
"validate(name, callback){\n let sql = \"SELECT admin FROM users WHERE username=$name\";\n this.db.all(sql, {\n $name: name\n }, (err, rows) => {\n if(err) {\n throw(err);\n }\n if(rows.length != 0) {\n return callback(rows[0].admin);\n }\n });\n }",
"function isOracleDataBase() {\n\tvar checkOracleDataSource = View.dataSources.get('checkOracleDataSource');\n\n\tif(valueExistsNotEmpty(checkOracleDataSource.getRecord().records)){\n\t\treturn checkOracleDataSource.getRecord().records[0].values['afm_tbls.table_name']\n\t} else {\n\t\t//older database.\n\t\treturn checkOracleDataSource.getRecord().getValue(\"afm_tbls.table_name\");\n\t}\n}",
"function groupNameValid(name) {\n return (typeof name === \"string\" && name.length <= 50 && name.length > 2)\n}",
"validateEnvironmentNames() {}",
"function hasValidNameField(manifest) {\n return misc_utils_1.isTruthyString(manifest[ManifestFieldNames.Name]);\n}",
"getDatabaseName() {\n return this.application_id + '!' + this.name;\n }",
"async function configureDb() {\n var answer = await prompt([\n {\n type: 'list',\n name: 'dbOption',\n message:\n \"You've chosen to manually configure the database URL. Would you like to use the default or your own?\",\n choices: [\n `Use the default URL (${defaultDbUrl})`, \n 'Use a different URL',\n CANCEL\n ]\n }\n ]);\n\n if (answer.dbOption == CANCEL) {\n process.exit();\n }\n\n // the user wants to use a databse string different from the default\n if (answer.dbOption == 'Use a different URL') {\n let answer = await prompt([\n {\n type: 'input',\n name: 'dbUrl',\n message:\n 'What is the URL of the database you wish to use? (eg. mongodb://[username:password@]host[:port][/[database])',\n // if the user enters nothing, fall back to using default\n default: function() {\n return defaultDbUrl;\n },\n // simple validation on the URL\n validate: function(value) {\n var pass = value.match(\n /^mongodb(\\+srv)?:\\/\\/(.+:.+@)?.+(:\\d{1,5})?\\/.+/\n );\n if (pass) {\n return true;\n }\n return 'You need to provide a valid mongodb url.';\n }\n }\n ]);\n\n return testAndSaveConnection(answer.dbUrl);\n } else {\n return testAndSaveConnection(defaultDbUrl);\n }\n}",
"function isValidGroupName(name) {\n\treturn isValidUsername(name);\n}",
"function ValidNameField(sender) {\n var id = $(sender).attr('id');\n var nameField = $('#' + id).val();\n var regexpp = /^[a-zA-Z][a-zA-Zรฉรผรถรณรชรฅรร
รรก .ยด'`-]*$/\n var Exp = /^[0-9]+$/;\n\n if (nameField.length > 0) {\n if (nameField.trim() == '')\n return false\n else {\n if (Exp.test(nameField.trim()))\n return false\n else\n return regexpp.test(nameField)\n }\n } else\n return true;\n}",
"function validatePackageName(packageName) {\n return /^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$/i.test(packageName);\n}",
"function check_gardening_botanical_name() \n\t\t{ \n\t\t\tvar boname_length = $(\"#update_gardening_botanical_name\").val().length;\n\n\t\t\tif(boname_length == \"\" || boname_length == null)\n\t\t\t\t{\n\t\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").html(\"Please fill in data into the field\"); \n\t\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").show(); \n\t\t\t\t\terror_gardening_botanical_name = true;\n\t\t\t\t}\n\t\t\t\n\t\t\telse if(boname_length <2 || boname_length > 20) {\n\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").html(\"Should be between 2-20 characters\");\n\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").show(); \n\t\t\t\terror_gardening_botanical_name = true;\n\t\t\t}\n\t\t\t\n\t\t\telse \n\t\t\t{\n\t\t\t\t$(\"#update_gardening_botanical_name_error_message\").hide();\n\t\t\t}\n\t\t}",
"function validateName()\n{\n\t//variable name is set by element id contactName from the form\n\tvar name = document.getElementById(\"contactName\").value; \n\t\n\t//validation for name\n\tif(name.length == 0)\n\t{\n\t\tproducePrompt(\"Name is Required\", \"namePrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tif(!name.match(/^[A-Za-z]*\\s{1}[A-Za-z]*$/))\n\t{\n\t\tproducePrompt(\"First and Last name Please\", \"namePrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tproducePrompt(\"Welcome \" + name, \"namePrompt\", \"green\"); \n\t\treturn true; \n\t\n}",
"function checkContractName(contractName) {\n if (!contractName || (typeof contractName !== 'string') || contractName.trim() === '') {\n throw new Error('Contract: Contract name: \"' + contractName + '\" is invalid.');\n }\n }",
"visitDatabase_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"validate() {\n const seenTables = new Map();\n for (const meta of this.values()) {\n if (seenTables.get(meta.tableName)) {\n throw new Error(\n `DB table \"${meta.tableName}\" already exists. Change the collectionName of the related content type.`\n );\n }\n seenTables.set(meta.tableName, true);\n }\n }",
"function ensureNoMoreCollections(args) {\n if (DBS_WITH_SERVER.has(args.database)) {\n var err = newRxError('S1', {\n collection: args.name,\n database: args.database.name\n });\n throw err;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prepares event array for local storage. Removes moment objects. | function prepareEventsForStorage(events) {
const prepared = events.map(event => {
const { startObj, endObj, ...rest } = event;
return rest;
});
return JSON.stringify(prepared);
} | [
"function loadFakeEvents () {\n\tif(localStorage.getItem('event') == null) {\n\t\t//load in fake events array\n\t\tlocalStorage.setItem('event', JSON.stringify(fake_events));\n\t}\n}",
"clearUncommittedEvents () {\n this._uncommittedEvents = [];\n }",
"getDanglingAudioEvents(millis, events){\n let num = 0;\n\n for(let event of this.audioEvents){\n if(event.millis < millis && event.endMillis > millis){\n event.playheadOffset = (millis - event.millis);\n event.time = this.startTime + event.millis - this.songStartMillis + event.playheadOffset;\n event.playheadOffset /= 1000;\n this.scheduledAudioEvents[event.id] = event;\n //console.log('getDanglingAudioEvents', event.id);\n events.push(event);\n num++;\n }else{\n event.playheadOffset = 0;\n }\n //console.log('playheadOffset', event.playheadOffset);\n }\n //console.log('getDanglingAudioEvents', num);\n return events;\n }",
"_persist() {\n\t\tstorage.set(STORAGE_KEY, this.events);\n\t}",
"deleteEvent() {\n let updatedEvents = this.state.events.filter(\n event => event[\"start\"] !== this.state.start\n );\n // localStorage.setItem(\"cachedEvents\", JSON.stringify(updatedEvents));\n this.setState({ events: updatedEvents });\n }",
"function loadCalenedarLocal(){\n let loadedCalendar = JSON.parse(localStorage.getItem(calendarLocalKey));\n \n if (!loadedCalendar){\n return;\n }\n timeArr.length = 0;\n\n loadedCalendar.forEach(element => {\n timeArr.push(element);\n });\n}",
"function storeCal() {\n localStorage.setItem(\"calEvents\", JSON.stringify(calEvents));\n }",
"function clearCalendar() {\n calEvents = {};\n storeCal();\n initCalendar();\n }",
"function destroy_event() {\n event = null;\n events.pop();\n if (events.length > 0)\n event = events[events.length - 1];\n}",
"removeFront() {\n this._taskArr.shift();\n /*\n if(this._taskArr.length === 1) {\n \n } else if(this._taskArr.length > 1) {\n let curr = this._taskArr[0];\n let next = this._taskArr[1];\n next.setStartTime(curr.startTime);\n this._taskArr.shift();\n }\n */\n }",
"function emptyUsedQuoteArrayAndRefillQuoteArray(){\n\t\t\twhile (usedQuotes.length > 0){\n\t\t\t\tquotes.push(usedQuotes.pop());\n\t\t\t}\n\t\t}",
"function decodeEvents(events) {\n // If `events` is falsy return empty array\n if(!events){\n return [];\n }\n // If value passed is an array, return it untouched\n if (_.isArray(events)) return events;\n\n // If value passed is an object, return it wrapped in an array\n if (_.isObject(events)) return [events];\n\n // Split name string by spaces\n // and remove falsy values\n return _.compact(events.split(' '));\n }",
"function eventDropped(date, externalEvent) {\n var event_object;\n var copiedEventObject;\n var duration = 60;\n var newId = getNewID();\n maxEventID += 1;\n var endDate = date.clone().add(1, 'h');\n event_object = $(externalEvent).data('event');\n event_object.description = $('#txtExternalEventDescription').val();\n event_object.title = $('#txtExternalEventTitle').val();\n copiedEventObject = $.extend({}, event_object);\n copiedEventObject.start = date;\n copiedEventObject.id = maxEventID;\n copiedEventObject.end = endDate;\n copiedEventObject.allDay = false;\n copiedEventObject.placeID = place.place_id;\n copiedEventObject.topic = event_object.topic;\n copiedEventObject.description = event_object.description;\n console.log(copiedEventObject);\n addNewEvent(copiedEventObject);\n place = \"\";\n}",
"_createEvents(prefix, events) {\n for(let eventName in events) {\n events[eventName] = new Event(prefix + '_' + eventName, this);\n }\n }",
"function normaliseEvent(evt) {\n var duration = {};\n\n if (!evt.dtend) {\n if (evt.duration) {\n duration.original = evt.duration;\n duration.minutes = evt.duration.match(/^PT(\\d+)M$/)[1];\n evt.dtend = new Date();\n evt.dtend.setTime(\n evt.dtstart.getTime() + duration.minutes * 60000);\n } else {\n evt.dtend = evt.dtstart;\n duration.minutes = 0;\n }\n } else {\n duration.minutes = (evt.dtend.getTime() - evt.dtstart.getTime());\n duration.minutes /= 60000;\n }\n\n if (duration.minutes >= 60) {\n duration.hours = Math.floor(duration.minutes / 60);\n duration.minutes -= duration.hours * 60;\n } else {\n duration.hours = 0;\n }\n\n duration.str = pad(duration.hours) + pad(duration.minutes);\n evt.duration = duration;\n\n evt.dtstart.iso8601 = iso8601(evt.dtstart);\n evt.dtend.iso8601 = iso8601(evt.dtend);\n }",
"addToQueue(events) {\n const eventsArray = [].concat(events);\n eventsArray.map((event) => {\n this._eventQueue.push(event);\n });\n }",
"removeBack() {\n this._taskArr.pop();\n /*\n if(this._taskArr.length === 1) {\n this._taskArr.pop();\n } else if(this._taskArr.length > 1) {\n let curr = this._taskArr[this._taskArr.length - 1];\n let prev = this._taskArr[this._taskArr.length - 2];\n prev.setEndTime(curr.endTime);\n }\n */\n }",
"function unWhatchedQuotesInit(){\n unWatchedQuotes = quotes.slice().map((x, index) => index);\n\n}",
"function callbackLoadTaskSuccess(listTask)\n{\n var tasks = [];\n \n listTask.forEach(function(task, index) {\n var taskOnCalendar = {\n id: task['id'],\n title: task['name'],\n start: task['start_date'],\n end: task['end_date'],\n status: task['status'],\n backgroundColor: getBackgroundStatus(task['status'])\n }\n tasks.push(taskOnCalendar);\n });\n \n $(\"#calendar\").fullCalendar('removeEvents'); \n $('#calendar').fullCalendar('addEventSource', tasks);\n $('#calendar').fullCalendar('rerenderEvents');\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Empty constructor for the Constants class. | function Constants() {
throw new Error('Constants should not be instantiated!');
} | [
"function SingletonClass() {}",
"get OccludeeStatic() {}",
"constructor() { \n \n ConfigHash.initialize(this);\n }",
"function MppOptions() {\n throw new Error('This is a static class');\n}",
"function DocBookNamespace()\n{\n\tthis.Strings = new Object;\n}",
"constructor() {\r\n super();\r\n this.type = \"NO_CRITERIA\";\r\n }",
"constructor() { \n \n Warning.initialize(this);\n }",
"function ConstantFunction()\r\n{\r\n const Pi=3.142;\r\n //Pi=5; // we cannot update the values in const variables\r\n console.log(Pi);\r\n}",
"constructor() {\n\n V1Event.initialize(this);\n }",
"static Black() {\n return new Color3(0, 0, 0);\n }",
"static Zero() {\n return new Vector2(0, 0);\n }",
"constructor() {\n this.displayVal = \"0\";\n this.firstOperand = null;\n this.waitingForSecondOperand = false;\n this.operator = null;\n }",
"constructor() { \n \n Operation.initialize(this);\n }",
"static Red() {\n return new Color3(1, 0, 0);\n }",
"get OccluderStatic() {}",
"function RenderConstants(viewMatrix)\n{\n this.viewMatrix = viewMatrix;\n}",
"function AutoDiffLogger() {\r\n throw new Error('This is a static class');\r\n}",
"function Globals() {\r\n\r\n\t/** @private */ var store = {};\r\n\t/** @private */ var count = 0;\r\n\t\r\n\t/**\r\n\t * Returns an array of all global variables names.\r\n\t * @public\r\n\t */\r\n\tthis.getValues = function() {\r\n\t\tvar result = new Array();\r\n\t\tfor (element in store) {\r\n\t\t\tif (store.hasOwnProperty(element)) {\r\n\t\t\t\tresult.push(store[element]);\r\n\t\t\t};\r\n\t\t};\r\n\t\treturn result;\r\n\t};\r\n\t\r\n\t/**\r\n\t * Returns the value of a global variable with the name.\r\n\t * @param {string} name Name of the global variable.\r\n\t * @public\r\n\t */\r\n\tthis.getValue = function(name) {\r\n\t\treturn store[name].value;\r\n\t};\r\n\t\r\n\t/**\r\n\t * Sets the value of a global variable with the name.\r\n\t * @param {string} name Name of the global variable.\r\n\t * @param {number} value Value of the global variable.\r\n\t * @public\r\n\t */\r\n\tthis.setValue = function(name, value) {\r\n\t\tif (store[name] == null) {\r\n\t\t\tstore[name] = {\r\n\t\t\t\taddress: (Const.ADDRESS_SPACE_SIZE + Const.GLOBALS_OFFSET_FROM_STACK + count++) * Const.ADDRESS_OFFSET,\r\n\t\t\t\tname: name,\r\n\t\t\t\tvalue: value\r\n\t\t\t};\r\n\t\t} else {\r\n\t\t\tstore[name].value = value;\r\n\t\t};\r\n\t};\r\n\t\r\n}",
"function _initStatic()\n\t{\n\t\tvar obj = this;\n\t\tvar fn = new obj();\t\t\t\t\t\t//...create new this() to capture instance properties\n\t\tfor (var p in fn) obj[p] = fn[p];\t\t//...copy instance properties to global CLASS Object\n\n\t\tif (this == ___)\t\t\t\t\t\t//initializing global EZ.returnValue\n\t\t{\t\t\t\t\t\t\t\t\t\t//...create global default EZ.returnValue options\n\t\t\toptions = this._options = defaultOptions();\n\t\t\tlog = new ___.log();\n\t\t\tthis._logs = log.logs;\n\t\t\tCIDS = this.CIDS = [___];\n\t\t}\n\n\t\tobj['~nextseq'] = 0;\n\t\treturn obj;\t\t\t\t\t\t\t\t//return populated global Object for EZ.returnValue\n\t}",
"constructor() { \n \n LastStatusInfo.initialize(this);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Push string onto the stack. | pushString(s) {
this.pushObject(s);
} | [
"push(val) {\n this._stack.push(val);\n }",
"push(msg) {\r\n this._msgStack.push(msg)\r\n }",
"stackPush(byte) {\n this.writeRam({ address: 0x0100 + this.cpu.sp, value: byte });\n this.decrementRegister('sp');\n }",
"pushToken(token) {\n this.stack.push(token);\n }",
"push(element) {\r\n //this.stack.push(element);\r\n this.stack.unshift(element);\r\n }",
"pushByte(value) {\n this.write(\">\" + \"+\".repeat(value));\n this.stack.push(StackEntry(DataType.Byte, 1));\n }",
"pushNode(node) {\n this.stack.push(new Frame(node));\n }",
"TreePush(str_id=null)\n {\n let win = this.getCurrentWindow();\n this.Indent();\n win.DC.TreeDepth++;\n this.PushID(str_id ? str_id : \"#TreePush\");\n }",
"pushTokens(tokens) {\n this.stack.push(...tokens);\n }",
"pushState(state, start) {\n this.stack.push(this.state, start, this.bufferBase + this.buffer.length)\n this.state = state\n }",
"plus() {\n this._lastX = this.pop();\n this._stack.push(this.pop() + this._lastX);\n }",
"popValue() {\n let size = this.stack.pop().size;\n this.write(\"[-]<\".repeat(size));\n }",
"push(inputContent, slotRef) {\n if (typeof inputContent !== 'string')\n throw 'ERROR : @inputContent must be a type string !';\n if (!typ.isSlotRef(slotRef))\n throw 'ERROR : @slotRef must be a type slotRef !';\n if (this.isFree(slotRef)) {\n let rs = this.stringToJsonStream(inputContent, slotRef.slotName);\n let mySlot = this.slots[slotRef.taskIndex][slotRef.slotName];\n this.createPipe(rs, mySlot);\n }\n else {\n console.log('push not possible');\n }\n }",
"function stackLetters (alphabet) {\n for (var i=0; i < alphabet.length; i++) {\n \tstack += alphabet[i]\n \tconsole.log(stack)\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 }",
"function push() {\n var lastState = newState(),\n i;\n copyModelState(lastState);\n list[listState.index + 1] = lastState; // Drop the oldest state if we went over the max list size\n\n if (list.length > listState.maxSize) {\n list.splice(0, 1);\n listState.startCounter++;\n } else {\n listState.index++;\n }\n\n listState.counter = listState.index + listState.startCounter; // Send push request to external objects defining TickHistoryCompatible Interface.\n\n for (i = 0; i < externalObjects.length; i++) {\n externalObjects[i].push();\n }\n\n invalidateFollowingState();\n listState.length = list.length;\n }",
"function incrementPointer() {\n\tcode_string_pointer++;\n}",
"pushWord(value) {\n this.pushByte(hi(value));\n this.pushByte(lo(value));\n }",
"function dockerPush(tag) {\n console.log(chalk.cyan(`Pushing image ${tag}`));\n return execute('gcloud', ['docker', '--', 'push', tag]);\n}",
"function push(tile) {\n \tvar id = tile.value == 1? tile.id1 : tile.id2;\n \tvar newState = { 'parent': currentState, tile: tile };\n \t// add the new state on top of the current\n \tcurrentState[id] = newState;\n \t// for this specific tile, count how many values have been tried\n \tif (currentState[tile.id])\n \t\tcurrentState[tile.id]++\n \telse\n \t\tcurrentState[tile.id] = 1;\n \tcurrentState = newState;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if all key/value pairs in the given query are currently active. | function queryIsActive(query, activeQuery) {
if (activeQuery == null) return query == null;
if (query == null) return true;
for (var p in query) if (query.hasOwnProperty(p) && String(query[p]) !== String(activeQuery[p])) return false;
return true;
} | [
"_query_is_valid() {\n let valid = this._required.reduce((res, key) => {\n return res && this._param_is_set(key);\n }, true);\n\n for (let [parent_key, one_required] of Object.entries(this._one_required)) {\n valid =\n valid &&\n one_required.reduce((res, required_key) => {\n let key = parent_key ? `${parent_key}:${required_key}` : required_key;\n return res || this._param_is_set(key);\n }, false);\n }\n\n return valid;\n }",
"isInUse() {\n const { items, filters = {} } = this.props;\n let inUse = false;\n items.forEach(item => {\n if (item.key in filters && Array.isArray(filters[item.key]) && filters[item.key].length) {\n inUse = true;\n this.hasBeenUsed = true;\n }\n });\n return inUse;\n }",
"function checkAllAliases (key, flag) {\n var isSet = false\n var toCheck = [].concat(aliases[key] || [], key)\n \n toCheck.forEach(function (key) {\n if (flag[key]) isSet = flag[key]\n })\n \n return isSet\n }",
"isQueryOperator (qs = null) {\n return queryOperators.hasOwnProperty(qs) == true;\n }",
"hasValidTransactions() {\n for (const tx of this.transactions) {\n if (!tx.isValid()) {\n return false;\n }\n }\n return true;\n }",
"Exists() {\n return this.transaction != null;\n }",
"function hasAllColumnsSelected() {\n var allSelected = true;\n for( var i = 0; i < vm.items.length; i++ ) {\n if(!vm.items[i].selected) {\n allSelected = false;\n break;\n }\n }\n return allSelected;\n }",
"isCategoryActive(category, activeCategory) {\n for (let activeTag of activeCategory) {\n for (let tag of category) {\n if (tag === activeTag) {\n return true;\n }\n }\n }\n return false;\n }",
"async includes (key, value) {\r\n\t\tconst obj = await this.model.findOne({ name: key });\r\n\t\tif (obj) {\r\n\t\t\treturn obj.value.includes(value);\r\n\t\t}\r\n\t\telse {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}",
"any() {\n return Object.keys(this.datos).length > 0;\n }",
"function _isMapActivatable() {\n return self.type !== ScrollableMap.TYPE_NEWWEB && // Web maps are never activatable\n bodyScrolls &&\n pref('frameRequireFocus') &&\n enabled &&\n !mapClicked;\n }",
"isComplete() {\n return this.selection != null;\n }",
"function isGameActive(game){\n return (game.ending - new Date() > 0 && game.isEnded===false);\n }",
"function ollHasSelected(oll)\r\n{\r\n var ollMap = zbllMap[oll];\r\n for (var coll in ollMap) if (ollMap.hasOwnProperty(coll)) {\r\n collMap = ollMap[coll];\r\n for (var zbll in collMap) if (collMap.hasOwnProperty(zbll))\r\n if (collMap[zbll][\"c\"])\r\n return true;\r\n }\r\n return false;\r\n}",
"function every(obj, func) {\n let result = false;\n for (let key in obj) {\n let match = func(obj[key]);\n if (match) {\n result = true;\n }\n else { return false; }\n }\n return result;\n}",
"isLocalOnHold() {\n if (this.state !== CallState.Connected) return false;\n if (this.unholdingRemote) return false;\n let callOnHold = true; // We consider a call to be on hold only if *all* the tracks are on hold\n // (is this the right thing to do?)\n\n for (const tranceiver of this.peerConn.getTransceivers()) {\n const trackOnHold = ['inactive', 'recvonly'].includes(tranceiver.currentDirection);\n if (!trackOnHold) callOnHold = false;\n }\n\n return callOnHold;\n }",
"function CheckActiveXAlive()\n{\n var res = true;\n var obj = GE(AxID);\n if (obj != null)\n {\n try\n {\n //if (obj.IsAlive == 0)\n {\n res = false;\n }\n }\n catch (e)\n {}\n }\n return res;\n}",
"function allAreAnswered(questions){\n if(questions.status===1){\n return true\n }\n}",
"isFinished() {\n\t\treturn this.staircases.every(function(s) {return s.staircase.isComplete();});\n\t}",
"allChecked() {\n return this.playedUser === this.remainingUsers\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make sure the scale of the object is within a given range, else, switch the scale direction | function maintainScale(item) {
var small = 5; // smallest allowed size (diameter, not radius)
var large = 20; // largest allowed size (diameter, not radius)
if ((item.bounds.width >= large) || (item.bounds.width <= small)) {
item.data.scale.direction *= -1; // reverse direction
}
} | [
"function _scaling ( /*[Object] event*/ e ) {\n\t\tvar activeObject = cnv.getActiveObject(),\n\t\tscale = activeObject.get('scaleY') * 100;\n\t\tif ( scale > 500 ) {\n\t\t\tactiveObject.scale(5);\n\t\t\tactiveObject.left = activeObject.lastGoodLeft;\n \tactiveObject.top = activeObject.lastGoodTop;\n\t\t}\n\t\tactiveObject.lastGoodTop = activeObject.top;\n \tactiveObject.lastGoodLeft = activeObject.left;\n\t\tif ( is_text(activeObject) ) {\n\t\t\teditTextScale.set( scale );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'scale', scale );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'top', activeObject.top );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'left', activeObject.left );\n\t\t}\n\t\telse {\n\t\t\teditImageScale.set(scale);\n\t\t}\n\t}",
"set scale(newscale)\n\t{\n\t\tthis.myscale.x = newscale;\n\t\tthis.myscale.y = newscale;\n\n\t\tthis.container.style.transform = \"scale(\" + newscale + \",\" + newscale + \")\";\n \n\t\t//get width and height metrics\n\t\tthis.size.x = this.container.getBoundingClientRect().width;\n this.size.y = this.container.getBoundingClientRect().height;\n\n\t\t//adjust z order based on scale\n\t\tthis.container.style.zIndex = (100 * newscale).toString();\n\t}",
"onTransformScaling() {\n const scale = this.getClosestScaleToFitExtentFeature();\n this.setScale(scale);\n }",
"function scale_changed() {\n\n var s = document.getElementById(\"scale_input\");\n //alert(\"slider value \" + s.value);\n\n var range = s.value / 100; // .25 - 2\n\n g_config.scale_factor = range;\n\n if (g_enableInstrumentation) {\n alert(\"scale_factor \" + g_config.scale_factor);\n }\n\n updateScaleCSS(g_config.scale_factor);\n\n refreshMode();\n}",
"get scale() { return (this.myscale.x + this.myscale.y)/2;}",
"function scale(data, chosenAxis, dir) {\n let r = [0, width]\n if (dir === height) {\n r = [height, 0]\n }\n var linearScale = d3.scaleLinear()\n .domain([d3.min(data, sd => sd[chosenAxis]) * 0.9, //0.8 and 1.2 gives us a buffer from the edges of the chart\n d3.max(data, sd => sd[chosenAxis]) * 1.1\n ])\n .range(r);\n return linearScale\n}",
"get forceScale() {}",
"function limitToRange(val, direction) {\n var defaultPrecision = series[direction.toLowerCase() + 'Axis']\n .categories ? 1 : 0,\n precision = pick(\n options['dragPrecision' + direction], defaultPrecision\n ),\n min = pick(options['dragMin' + direction], -Infinity),\n max = pick(options['dragMax' + direction], Infinity),\n res = val;\n\n if (precision) {\n res = Math.round(res / precision) * precision;\n }\n return Math.max(min, Math.min(max, res));\n }",
"function resetScaleTransform() {\n Data.Edit.Transform.Scale = 1;\n updateTransform();\n}",
"function checkInBoundsAndScale(container, event) {\n\tbounds = container.getBoundingClientRect();\n\tlet x = event.clientX;\n\tlet y = event.clientY;\n\t//in this case, the mouseX and mouseY are in bounds of one of the table sections\n\tif (x > bounds.left && x < bounds.right && y > bounds.top && y < bounds.bottom) {\n\t\tcontainer.style.transform = 'scale(1.06)';\n\t\treturn true;\n\t}\n\telse {\n\t\tcontainer.style.transform = 'scale(1)';\n\t\treturn false;\n\t}\n}",
"scaleToRange(x) {\r\n var t;\r\n t = this.minHeight + ((x - this.minTemp) * (this.maxHeight - this.minHeight)) / (this.maxTemp - this.minTemp); // Based on a formula googled from various sources.\r\n return t;\r\n }",
"function gScale(sx,sy,sz) {\r\n modelViewMatrix = mult(modelViewMatrix,scale(sx,sy,sz)) ;\r\n}",
"function scaleTime(range)\n{\n\tif (range == undefined || range == NaN) {\n\t\tconsole.log(\"range is not defined\");\n\t\tthrow new Error(\"range is not defined\");\n\t}\n\telse\n\treturn d3.scaleTime().range(range);\n}",
"function linearScale(domain, range, value) {\n return ((value - domain[0]) / (domain[1] - domain[0])) * (range[1] - range[0]) + range[0];\n}",
"function updateScale(increment) {\n var ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n //var viewportScale = document.getElementById(\"scale\").value;\n axes.scale += increment;\n draw();\n}",
"setScales() {\n this.r3a1_char_north.setScale(3);\n this.r3a1_char_south.setScale(3);\n this.r3a1_char_west.setScale(3);\n this.r3a1_char_east.setScale(3);\n this.r3a1_exitDoor.setScale(1.5);\n this.r3a1_E_KeyImg.setScale(0.4);\n this.r3a1_notebook.setScale(0.75);\n this.r3a1_map.setScale(0.75);\n this.character.setScale(1);\n this.r3a1_floor.scaleY = 1.185;\n this.r3a1_floor.scaleX = 1.395;\n this.profile.setScale(1.5);\n\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}",
"function fixedControlObj(event){\n\tif (scaleUpdated == true){\n\t\tscaleUpdated = false;\n\t}else{\n\t\tundoMove();\n\t\talert('ClearAutoBox before transforming the control object');\n\t}\n}",
"setPanScale(scale_pan){\n this.scale_pan = scale_pan;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
BigNat > Int > Int | function h$ghcjsbn_indexBigNat(b, i) {
h$ghcjsbn_assertValid_b(b, "indexBigNat");
h$ghcjsbn_assertValid_s(i, "indexBigNat");
var bl = b[0];
return i >= bl ? 0 : b[i+1];
} | [
"static int64(v) { return n(v, -64); }",
"static int128(v) { return n(v, -128); }",
"static int8(v) { return n(v, -8); }",
"static int208(v) { return n(v, -208); }",
"isBigInt() {\n return !!(this.type.match(/^u?int[0-9]+$/));\n }",
"function bool(i) /* (i : int) -> bool */ {\n return $std_core._int_ne(i,0);\n}",
"function nbi() { return new BigInteger(null); }",
"static int168(v) { return n(v, -168); }",
"static int176(v) { return n(v, -176); }",
"function integerBoolean(n) {\n\treturn [...n].map(x => x === '1');\n}",
"static int256(v) { return n(v, -256); }",
"static int88(v) { return n(v, -88); }",
"static int216(v) { return n(v, -216); }",
"static int48(v) { return n(v, -48); }",
"function checkBigInts(...args) {\n\tfor (var i = args.length - 1; i >= 0; i--) {\n\t\tlet arg = args[i];\n\n\t\tif (arg instanceof bigInt) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (typeof arg === 'object') {\n\t\t\tcheckBigInts(...Object.values(arg));\n\t\t\tcontinue;\n\t\t}\n\n\t\tthrow new TypeError(`object contains something that is not a bigInt (${arg} is of type ${typeof arg})`);\n\t}\n}",
"static int144(v) { return n(v, -144); }",
"static int112(v) { return n(v, -112); }",
"static uint64(v) { return n(v, 64); }",
"static uint192(v) { return n(v, 192); }",
"static uint208(v) { return n(v, 208); }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return true if current can be used for model run: if workset in readonly state | isReadonlyWorksetCurrent () {
return this.worksetCurrent?.Name && this.worksetCurrent?.IsReadonly
} | [
"isUseCurrentAsBaseRun () {\n return this.isCompletedRunCurrent && (!this.isReadonlyWorksetCurrent || this.isPartialWorkset())\n }",
"isPartialWorkset () {\n return (Mdf.worksetParamCount(this.worksetCurrent) !== Mdf.paramCount(this.theModel)) &&\n (!this.worksetCurrent?.BaseRunDigest || !this.isExistInRunTextList({ ModelDigest: this.digest, RunDigest: this.worksetCurrent?.BaseRunDigest }))\n }",
"isLockedWork() {\n let userId = userService.getLoggedId();\n let attendance = attendanceService.getAttendance(workToEdit.idAttendance);\n if(!attendance || !attendance.approved)\n return false;\n return true;\n }",
"function isEditable() {\n return (current && current.isOwner && !current.frozen);\n}",
"get atWork () {\n return this.room.name === this._mem.rooms.work;\n }",
"isWorkInProgress() {\n return this.json_.work_in_progress === true;\n }",
"checkIfCurrentJob() {\n return (this.jobId === DiffDrawer.currentJobId);\n }",
"inSafeMode() {\n return this.getLoadSettings().safeMode;\n }",
"function canEdit() {\n return Jupyter.narrative.uiModeIs('edit');\n }",
"isCompletedRunCurrent () {\n return this.runCurrent?.RunDigest && Mdf.isRunCompleted(this.runCurrent)\n }",
"get locked() { return false }",
"isOnline() {\n return this.worldManager && this.worldManager.isOnline();\n }",
"get isReadyForRestart() {\n if (this.updateStagingEnabled) {\n let errorCode;\n if (this.update) {\n errorCode = this.update.errorCode;\n } else if (this.um.readyUpdate) {\n errorCode = this.um.readyUpdate.errorCode;\n }\n // If the state is pending and the error code is not 0, staging must have\n // failed and Firefox should be restarted to try to apply the update\n // without staging.\n return this.isApplied || (this.isPending && errorCode != 0);\n }\n return this.isPending;\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}",
"get canMarkThreadAsRead() {\n if (\n (this.displayedFolder && this.displayedFolder.getNumUnread(false) > 0) ||\n this.view._underlyingData === this.view.kUnderlyingSynthetic\n ) {\n // If the messages limit is exceeded we bail out early and return true.\n if (this.selectedIndices.length > this.MAX_COUNT_FOR_MARK_THREAD) {\n return true;\n }\n\n for (let i of this.selectedIndices) {\n if (\n this.view.dbView.getThreadContainingIndex(i).numUnreadChildren > 0\n ) {\n return true;\n }\n }\n }\n return false;\n }",
"get isMutable()\n\t{\n\t\t//dump(\"get isMutable: title:\"+this.title+\", value:\"+this._calEvent.isMutable);\n\t\treturn this._isMutable;\n\t}",
"function isDirty(){\n return this.__isDirty__;\n}",
"get reconfigured() {\n return this.startState.config != this.state.config\n }",
"function checkState() {\n \n \n if(currentState.running == false) {\n return;\n }\n \n // get request of the job information\n $.ajax({\n url: \"job?id=\" + currentState.currentId\n , type: \"GET\"\n\n , success: function (data) {\n \n currentState.running = data.finished !== true;\n currentState.ready = data.finished;\n currentState.status = data.status;\n currentState.fileName = data.fileName;\n if (currentState.running) {\n setTimeout(checkState, 1000);\n }\n updateView();\n } \n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
using useStare in React whatever the user inputs the emoji it is rendered and matched with DB | function emojiInputHandler(event) {
var userInput = event.target.value;
// var meaning = emojiDictionary[userInput];
if (userInput in emojiDictionary) {
setMeaning(emojiDictionary[userInput]);
} else setMeaning("That's a new one! We don't have this in our database");
} | [
"textChangeHandler(event) {\n let newConvertedText = \"\"\n let buffer = \"\";\n\n for (let i = 0; i < event.target.value.length; i++) {\n let targetChar = event.target.value.charAt(i);\n\n if (JAPANESE_CHARACTER_REGEX.test(targetChar)) {\n newConvertedText += buffer + targetChar;\n buffer = \"\";\n continue;\n }\n\n buffer += targetChar;\n\n if (buffer in hiragana) {\n newConvertedText += hiragana[buffer];\n buffer = \"\";\n }\n }\n\n newConvertedText += buffer;\n\n this.setState({\n convertedText: newConvertedText,\n isValid: true,\n helperText: \"\"\n });\n }",
"function chooseEmoji(e) {\n if(e.target.matches(\".emoji\")) {\n textarea.value += e.target.innerHTML\n }\n}",
"render(){\n return(\n <div className=\"container-fluid d:flex\" id=\"main\">\n \n <div id=\"textAreaContainer\">\n <h3 id=\"editor-head\">Markdown Editor</h3>\n <textarea className=\"bg-dark \" id=\"editor\" value={this.state.input} onChange={this.handleChange}/>\n </div>\n\n <div id=\"previewContainer\">\n <h3 id=\"preview-head\">Markdown preview</h3>\n <div id=\"preview\" dangerouslySetInnerHTML={{__html:marked(this.state.input,{breaks:true})}}>\n </div>\n </div>\n\n </div>\n );\n }",
"_updateText() {\n const {data, characterSet} = this.props;\n const textBuffer = data.attributes && data.attributes.getText;\n let {getText} = this.props;\n let {startIndices} = data;\n let numInstances;\n\n const autoCharacterSet = characterSet === 'auto' && new Set();\n\n if (textBuffer && startIndices) {\n const {texts, characterCount} = getTextFromBuffer({\n ...(ArrayBuffer.isView(textBuffer) ? {value: textBuffer} : textBuffer),\n length: data.length,\n startIndices,\n characterSet: autoCharacterSet\n });\n numInstances = characterCount;\n getText = (_, {index}) => texts[index];\n } else {\n const {iterable, objectInfo} = createIterable(data);\n startIndices = [0];\n numInstances = 0;\n\n for (const object of iterable) {\n objectInfo.index++;\n // Break into an array of characters\n // When dealing with double-length unicode characters, `str.length` or `str[i]` do not work\n const text = Array.from(getText(object, objectInfo) || '');\n if (autoCharacterSet) {\n text.forEach(autoCharacterSet.add, autoCharacterSet);\n }\n numInstances += text.length;\n startIndices.push(numInstances);\n }\n }\n\n this.setState({\n getText,\n startIndices,\n numInstances,\n characterSet: autoCharacterSet || characterSet\n });\n }",
"function renderEmojis() {\n emojiContainer.innerHTML = \"\" // clear the container first\n for (let i = 0; i < myEmojis.length; i++) {\n // create a span to hold emojis\n const emoji = document.createElement('span')\n \n // render on the page\n emoji.textContent = myEmojis[i]\n \n // append the span to the container\n emojiContainer.append(emoji)\n }\n}",
"function App() {\n // Call your hook\n const hKey = useKeyPressWithKey('h');\n const fKey = useKeyPressWithKey('f');\n\n\n const enterKey = useKeyPressWithKeyCode(13);\n const escKey = useKeyPressWithKey(27);\n return (\n <div>\n <div>h, s, r, f</div>\n <div>\n {hKey && 'you pressed h'}\n {fKey && 'you pressed f'}\n\n {enterKey && 'you press enter'}\n {escKey && 'you press esc'}\n </div>\n </div>\n );\n}",
"function InputText({ userMessage, setUserMessage, sendUserMessages }) {\n return (\n <form className=\"form-input\">\n <input\n className=\"input-text\"\n type=\"text\"\n placeholder=\"Enter a message...\"\n value={userMessage}\n onChange={(e) => setUserMessage(e.target.value)}\n onKeyDown={(e) => (e.key === \"Enter\" ? sendUserMessages(e) : null)}\n />\n <button className=\"button-two\" onClick={(e) => sendUserMessages(e)}>\n <i class=\"fa fa-paper-plane\" aria-hidden=\"true\"></i>\n </button>\n </form>\n );\n}",
"renderHighlightedText(text, subSting) {\n const replaceWith = `<span class=\"highlight\">${subSting}</span>`;\n const result = replaceAll(text, subSting, replaceWith);\n return result;\n }",
"handleChange({ value, selectionStart }) {\n // Get the word being edited and handle the changes\n const word = getWordAt(value, selectionStart);\n const screenName = word.includes('@') && getScreenName(word);\n this.props.handleChange(value);\n\n // If screen name is being edited, handle differently\n if (screenName) {\n this.props.handleEditScreenName(screenName, value.split(' ').indexOf(`@${screenName}`));\n }\n }",
"_renderInstructions(parseState: PassageParseState): React.Element<any> {\n const firstQuestionNumber = parseState.firstQuestionRef;\n const firstSentenceRef = parseState.firstSentenceRef;\n\n let instructions = \"\";\n if (firstQuestionNumber) {\n instructions += i18n._(\n \"The symbol %(questionSymbol)s indicates that question \" +\n \"%(questionNumber)s references this portion of the \" +\n \"passage.\",\n {\n questionSymbol: \"[[\" + firstQuestionNumber + \"]]\",\n questionNumber: firstQuestionNumber,\n }\n );\n }\n if (firstSentenceRef) {\n instructions += i18n._(\n \" The symbol %(sentenceSymbol)s indicates that the \" +\n \"following sentence is referenced in a question.\",\n {\n sentenceSymbol: \"[\" + firstSentenceRef + \"]\",\n }\n );\n }\n const parsedInstructions = PassageMarkdown.parse(instructions);\n return (\n <div className=\"perseus-widget-passage-instructions\">\n {PassageMarkdown.output(parsedInstructions)}\n </div>\n );\n }",
"render() {\n\t\treturn (\n\t\t\t<div>\n\t\t\t\t<div style={{backgroundColor: '#DC143C', color: 'white'}}>\n\t\t\t\t\t<br />\n\t\t\t\t\t<h1 style={{display: 'flex', justifyContent: 'center'}}><u>PENDULUM</u></h1>\n\t\t\t\t\t<h3 style={{display: 'flex', justifyContent: 'center', paddingBottom: '5px'}}>Diverse stories from a partisan world</h3>\n\t\t\t\t\t<br />\n\t\t\t\t</div>\n\t\t\t\t{ this.state.suggestions.map(( info, idx ) =>\n\t\t\t\t\t<Preview key={ idx } info={ info } />\n\t\t\t\t) }\n\t\t\t</div>\n\t\t);\n\t}",
"renderSuggestions() {\n const { value, matched, showList, selectedIndex } = this.state;\n\n if (!showList || matched.length < 1) {\n return null; // Nothing to render\n }\n\n return (\n <ul className=\"suggestions\">\n {matched.map((item, index) => (\n <li\n key={`item-${item}-${index}`}\n className={index === selectedIndex ? 'selected' : ''}\n dangerouslySetInnerHTML={{ __html: this.renderHighlightedText(item, value) }}\n onClick={this.handleOnItemClick}\n />\n ))}\n </ul>\n );\n }",
"render() {\n return (\n <LayoutDiv>\n <Title/>\n <CenterDiv>\n <FormContainer dataReturnHandler={this.handleData}/>\n {this.state.FormInputData === '' ? null : <WordCloudDisplay rawData={this.state.FormInputData}/>}\n </CenterDiv>\n {this.state.AlertDisplay === true ? <Alert /> : null}\n </LayoutDiv>\n );\n }",
"function insert(emoji) {\n let editor = N.MDEdit.__textarea__;\n\n // Find nearest ':' symbol before cursor on the current line\n editor.selectionStart = Math.max(\n editor.value.lastIndexOf('\\n', editor.selectionStart - 1) + 1,\n editor.value.lastIndexOf(':', editor.selectionStart)\n );\n\n $popup.removeClass('emoji-autocomplete__m-visible');\n\n text_field_update.insert(editor, ':' + emoji + ':');\n }",
"function drawEmoji(canvas, img, face) {\n // Obtain a 2D context object to draw on the canvas\n var ctx = canvas.getContext('2d');\n let fp_0 = face.featurePoints[0];\t\n let em = face.emojis.dominantEmoji;\n \n ctx.font = '48px serif';\n ctx.fillText(em, fp_0.x-70, fp_0.y);\n}",
"function DisplaySecret() {\n if (language == \"CSS\") {\n return (\n <SyntaxHighlighter\n language=\"css\"\n wrapLongLines=\"true\"\n customStyle={{ background: \"rgb(249,248,240)\" }}\n >\n {secret}\n </SyntaxHighlighter>\n );\n } else if (language == \"Javascript\") {\n return (\n <SyntaxHighlighter\n language=\"javascript\"\n wrapLongLines=\"true\"\n customStyle={{ background: \"rgb(249,248,240)\" }}\n >\n {secret}\n </SyntaxHighlighter>\n );\n } else if (language == \"JSON\") {\n return (\n <SyntaxHighlighter\n language=\"json\"\n wrapLongLines=\"true\"\n customStyle={{ background: \"rgb(249,248,240)\" }}\n >\n {secret}\n </SyntaxHighlighter>\n );\n } else if (language == \"Markdown\") {\n return <div dangerouslySetInnerHTML={createMarkup(secret)}></div>;\n } else if (language == \"Python\") {\n return (\n <SyntaxHighlighter\n language=\"python\"\n wrapLongLines=\"true\"\n customStyle={{ background: \"rgb(249,248,240)\" }}\n >\n {secret}\n </SyntaxHighlighter>\n );\n } else if (language == \"PlainText\") {\n return <div dangerouslySetInnerHTML={purifyPlainText(secret)}></div>;\n } else {\n return null;\n }\n }",
"resetGame() {\n this.setState({\n turns: 0,\n compare: null,\n turn: Array(2).fill(null),\n flipped: Array(tableSize[0] * tableSize[1]).fill(false),\n matched: [] \n });\n\n setTimeout(() => {\n emojis = getEmojis((tableSize[0] * tableSize[1]) / 2);\n }, 600);\n }",
"function emotify(str) {\n const emoticons = {\n smile: ':D',\n grin: ':)',\n sad: ':(',\n mad: ':P',\n };\n return `Make me ${emoticons[str.split(' ').pop()]}`;\n}",
"_encode(data) {\n let codeData = JSON.parse(JSON.stringify(data));\n let qrString = encodeStringData(codeData);\n this.setState({qrString: qrString});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Results directory from the case on a popup dialog The dialog is shown BELOW the popup. BUG. | function getResultsDirForCaseStep(tag) {
var callback_on_accept = function(selectedValue) {
console.log(selectedValue);
var popup = katana.$activeTab.find("#editCaseStepDiv").attr('popup-id');
// Convert to relative path.
var pathToBase = katana.$activeTab.find('#savefilepath').text();
console.log("File path ==", pathToBase);
// var nf = katana.fileExplorerAPI.prefixFromAbs(pathToBase, selectedValue);
var nf = prefixFromAbs(pathToBase, selectedValue);
popup.find(tag).attr("value", nf);
popup.find(tag).attr("fullpath", selectedValue);
};
var callback_on_dismiss = function(){
console.log("Dismissed");
};
//var popup = katana.$activeTab.find("#editCaseStepDiv").attr('popup-id');
katana.fileExplorerAPI.openFileExplorer("Select a file", false , $("[name='csrfmiddlewaretoken']").val(), false, callback_on_accept, callback_on_dismiss);
} | [
"function getResultsDirForCase(tag) {\n var callback_on_accept = function(selectedValue) { \n \t\tconsole.log(selectedValue);\n \t\t// Convert to relative path.\n \t\tvar savefilepath = katana.$activeTab.find('#savefilepath').text();\n \t\tconsole.log(\"File path ==\", savefilepath);\n \t\t//var nf = katana.fileExplorerAPI.prefixFromAbs(pathToBase, selectedValue);\n \t\tvar nf = prefixFromAbs(savefilepath, selectedValue);\n \t\tkatana.$activeTab.find(tag).attr(\"value\", nf);\n \t\tkatana.$activeTab.find(tag).attr(\"fullpath\", selectedValue);\n\n };\n var callback_on_dismiss = function(){ \n \t\tconsole.log(\"Dismissed\");\n\t };\n katana.fileExplorerAPI.openFileExplorer(\"Select a file\", false , $(\"[name='csrfmiddlewaretoken']\").val(), false, callback_on_accept, callback_on_dismiss);\n}",
"newWorkspaceDialog() {\n\t\tlet Dialog_SelectWorkspace = require(path.join(__rootdir, \"js\", \"dialogs\", \"selworkspace.js\"))\n\t\tnew Dialog_SelectWorkspace(600, \"\", (result) => {\n\t\t\tif(result === false)\n\t\t\t\treturn\n\t\t\t\n\t\t\tlet ws = wmaster.addWorkspace(result)\n\t\t\tthis.setWorkspace(ws)\n\t\t\t\n\t\t\t// display loading indicator\n\t\t\tthis.body.innerHTML = `<div class=\"abs-fill flex-col\" style=\"justify-content: center\"><div style=\"align-self: center\">...</dib></div>`\n\t\t})\n\t}",
"function showDirectory(){\n\twindow.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {\n// \talert(\"Root = \" + fs.root.fullPath);\n\t\tvar directoryReader = fs.root.createReader();\n\t\tdirectoryReader.readEntries(success,failDir);\n\t}, function (error) {\n\t\talert(error.code);\n\t});\n\tfunction success(entries) {\n\t\tvar ent=\"<option>Select File</option>\";\n\t\tfor (var i=0; i<entries.length; i++) {\n\t\t\tent += \"<option value=\"+entries[i].name+\">\"+entries[i].name+\"</option>\";\n\t\t}\n\t\t$(\"#loadConfSelect\").html(ent);\t\t\n//\t\talert(\"pasok sa success?\"+ent);\n\t}\n\tfunction failDir(error) {\n\t\talert(\"Failed to list directory contents: \" + error.code);\n\t}\n}",
"function portTablePopUp(){\n\t$( \"#testToolPopUp\" ).dialog({\n\t\tmodal: true,\n\t\tautoResize:true,\n\t\twidth: \"auto\",\n\t\tmaxHeight: 500\n\t});\n\t$( \"#testToolPopUp\" ).load('pages/ConfigEditor/PortTestTool.html',function(){\n\t\t//deviceListPopupTable('deviceMenu','local');\n\t\t$('#PortTitle').text(HostName);\t\n\t\tsetTimeout(function(){\n\t\t\tPortTestToolTable();\n\t\t},100);\n\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}",
"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 getDialogPath() {\n var gAuthor = Granite.author,\n currentDialog = gAuthor.DialogFrame.currentDialog, dialogPath;\n\n if (currentDialog instanceof gAuthor.actions.PagePropertiesDialog) {\n var dialogSrc = currentDialog.getConfig().src;\n dialogPath = dialogSrc.substring(0, dialogSrc.indexOf(\".html\"));\n } else {\n var editable = gAuthor.DialogFrame.currentDialog.editable;\n\n if (!editable) {\n console.log(\"EAEM - editable not available\");\n return;\n }\n\n dialogPath = editable.config.dialog;\n }\n\n return dialogPath;\n }",
"function recordsetDialog_getCommandDialogPref(cmdFilenameDefault)\r\n{\r\n prefValue = dw.getPreferenceString(recordsetDialog.CMD_FILENAME_PREF_SECTION, \r\n recordsetDialog.CMD_FILENAME_PREF_KEY, \r\n cmdFilenameDefault);\r\n\r\n return prefValue;\r\n}",
"function showSetupDialog() {\n openDialog('/html/setup.html', 500, 660);\n}",
"function browseFolder() \n{\n\t//Is the folder writable/unlocked?\n\tif (isSiteRootSane()) {\n\t\t//Set lib source folder\n\t\tvar libFolder = settings.cssType == SPLIT_CSS ? PREF_SPLIT_JQLIB_SOURCE_FOLDER : PREF_JQLIB_SOURCE_FOLDER;\n\t\t\n\t\t// Call Dw to bring up the browse for folder dialog\n\t\tvar browseRoot = dw.getPreferenceString(PREF_SECTION, libFolder, dw.getConfigurationPath()+\"/\"+assetDir);\n\t\tvar jQuerySourceFolder = dw.browseForFolderURL(dw.loadString(\"Commands/jQM/files/alert/browseFile\"), browseRoot, false);\n\t \n\t\tfindjQMFiles(jQuerySourceFolder);\n\t} else {\n\t\talert(dw.loadString(\"Commands/jQM/files/alert/lockedFolder\"));\n\t}\n}",
"function displayEval(data, evalType) {\n\n //$('#evalDetailsDialog > ul').html('');\n $.each(data[0], function(key, value) {\n $('#detail-' + key).find('span').text(unescape(value));\n //$('#evalDetailsDialog > ul').append('<li id=\"detail-'+key+'\"><strong>'+key+': </strong><span>'+unescape(value)+'</span></li>')\n });\n\n var dialogId;\n switch (evalType) {\n case 'resultsByCourse':\n $.each(data[0], function(key, value) {\n $('#detail-' + key).find('span').text(unescape(value));\n //$('#evalDetailsDialog > ul').append('<li id=\"detail-'+key+'\"><strong>'+key+': </strong><span>'+unescape(value)+'</span></li>')\n });\n\n dialogId = 'evalDetailsDialog';\n\n break;\n case 'resultsByAwardMid':\n $.each(data[0], function(key, value) {\n $('#detail-app-' + key).find('span').text(unescape(value));\n //$('#evalDetailsDialog > ul').append('<li id=\"detail-'+key+'\"><strong>'+key+': </strong><span>'+unescape(value)+'</span></li>')\n });\n dialogId = 'apprenticeDetailsDialog';\n break;\n\n }\n\n $('#' + dialogId).dialog('open');\n }",
"function filterPopUp(){\n\t$(\"#divAlert\").dialog({\n\t\tmodal: true,\n\t\tautoResize:true,\n\t\twidth: width - 200,\n\t\tmaxHeight: 700\n\t});\n\tif(enDisFilter == true){\n\t\t$(\"#divAlert\").load(\"pages/ConfigEditor/Filter.html\",function(){\n\t\t\tinitDynamicFilterValue();\n\t\t});\n\t}\n}",
"function city_name_dialog(suggested_name, unit_id) {\n // reset dialog page.\n $(\"#city_name_dialog\").remove();\n $(\"<div id='city_name_dialog'></div>\").appendTo(\"div#game_page\");\n\n $(\"#city_name_dialog\").html($(\"<div>What should we call our new city?</div>\"\n\t\t \t + \"<input id='city_name_req' type='text' value='\" \n\t\t\t + suggested_name + \"'>\"));\n $(\"#city_name_dialog\").attr(\"title\", \"Build New City\");\n $(\"#city_name_dialog\").dialog({\n\t\t\tbgiframe: true,\n\t\t\tmodal: true,\n\t\t\twidth: \"300\",\n\t\t\tclose: function() {\n\t\t\t\tkeyboard_input=true;\n\t\t\t},\n\t\t\tbuttons: [\t{\n\t\t\t\t\ttext: \"Cancel\",\n\t\t\t\t click: function() {\n\t\t\t\t\t\t$(\"#city_name_dialog\").remove();\n \t\t\t\t\tkeyboard_input=true;\n\t\t\t\t\t}\n\t\t\t\t},{\n\t\t\t\t\ttext: \"Ok\",\n\t\t\t\t click: function() {\n\t\t\t\t\t\tvar name = $(\"#city_name_req\").val();\n\t\t\t\t\t\tif (name.length == 0 || name.length >= MAX_LEN_NAME - 4 \n\t\t\t\t\t\t || encodeURIComponent(name).length >= MAX_LEN_NAME - 4) {\n\t\t\t\t\t\t swal(\"City name is invalid\");\n\t\t\t\t\t\t return;\n\t\t\t\t\t\t}\n\n var actor_unit = game_find_unit_by_number(unit_id);\n\n var packet = {\"pid\" : packet_unit_do_action,\n \"actor_id\" : unit_id,\n \"target_id\": actor_unit['tile'],\n \"value\" : 0,\n \"name\" : encodeURIComponent(name),\n \"action_type\": ACTION_FOUND_CITY};\n\t\t\t\t\t\tsend_request(JSON.stringify(packet));\n\t\t\t\t\t\t$(\"#city_name_dialog\").remove();\n\t\t\t\t\t\tkeyboard_input=true;\n\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t});\n\n $(\"#city_name_req\").attr('maxlength', MAX_LEN_NAME);\n\t\n $(\"#city_name_dialog\").dialog('open');\t\t\n\n $('#city_name_dialog').keyup(function(e) {\n if (e.keyCode == 13) {\n \tvar name = $(\"#city_name_req\").val();\n\n var actor_unit = game_find_unit_by_number(unit_id);\n\n var packet = {\"pid\" : packet_unit_do_action,\n \"actor_id\" : unit_id,\n \"target_id\": actor_unit['tile'],\n \"value\" : 0,\n \"name\" : encodeURIComponent(name),\n \"action_type\": ACTION_FOUND_CITY};\n\tsend_request(JSON.stringify(packet));\n\t$(\"#city_name_dialog\").remove();\n keyboard_input=true;\n }\n });\n keyboard_input=false;\n}",
"function FilesDlg(form, element,directory, tag_id) {\n tag_id = parseInt(\"0\"+tag_id)*1;\n window.open('?page=filestoragedlg&isOpen=1&form=' + form + '&element=' + element + '&directory=' + directory + '&tag_id=' + tag_id,\n 'FilesDlg', 'menubar=no,width=400,height=400,scrollbars=yes,resizable=no');\n }",
"function testToolTablePopUp(){\n\t$( \"#configPopUp\" ).dialog({\n\t\tmodal: true,\n\t\tautoResize:true,\n\t\twidth: \"auto\",\n\t\theight: \"auto\"\n\t});\n\t$( \"#configPopUp\" ).empty().load('pages/ConfigEditor/TestToolTable.html',function(){\n\t\tsetTimeout(function(){\n\t\t\tTestToolListTable();\n\t\t\t$(\".ui-dialog\").position({\n\t\t\t my: \"center\",\n\t\t\t at: \"center\",\n\t\t\t of: window\n\t\t\t});\n\n\t\t},1000);\n\t});\n}",
"function popupFindItem(ui) {\n\n v_global.event.type = ui.type;\n v_global.event.object = ui.object;\n v_global.event.row = ui.row;\n v_global.event.element = ui.element;\n\n switch (ui.element) {\n case \"emp_nm\":\n case \"manager1_nm\":\n case \"manager2_nm\":\n case \"manager3_nm\":\n case \"manager4_nm\": \n {\n var args = { type: \"PAGE\", page: \"DLG_EMPLOYEE\", title: \"์ฌ์ ์ ํ\"\n \t, width: 700, height: 450, locate: [\"center\", \"top\"], open: true\n };\n if (gw_com_module.dialoguePrepare(args) == false) {\n var args = { page: \"DLG_EMPLOYEE\",\n param: { ID: gw_com_api.v_Stream.msg_selectEmployee }\n };\n gw_com_module.dialogueOpen(args);\n }\n } break;\n case \"dept_nm\":\n {\n var args = { type: \"PAGE\", page: \"DLG_TEAM\", title: \"๋ถ์ ์ ํ\", width: 500, height: 450, open: true };\n if (gw_com_module.dialoguePrepare(args) == false) {\n var args = { page: \"DLG_TEAM\",\n param: { ID: gw_com_api.v_Stream.msg_selectTeam }\n };\n gw_com_module.dialogueOpen(args);\n }\n } break;\n case \"supp_nm\":\n {\n var args = { type: \"PAGE\", page: \"w_find_supplier\", title: \"ํ๋ ฅ์ฌ ์ ํ\", width: 500, height: 450, open: true };\n if (gw_com_module.dialoguePrepare(args) == false) {\n var args = { page: \"w_find_supplier\",\n param: { ID: gw_com_api.v_Stream.msg_selectedSupplier }\n };\n gw_com_module.dialogueOpen(args);\n }\n } break;\n default: return;\n }\n}",
"function showResults() {\n ipMarkersGroup.eachLayer(function(layer) {\n if (layer.isPopupOpen()) {\n content = layer.getPopup().getContent();\n index = content.indexOf('<ul');\n index2 = content.indexOf('</div>');\n content = content.substr(index, index2);\n latLng = layer.getPopup().getLatLng();\n L.popup({\n maxWidth: 400\n }).setContent(content).setLatLng(latLng).openOn(mymap);\n return;\n }\n });\n\n scrapingMarkersGroup.eachLayer(function(layer) {\n if (layer.isPopupOpen()) {\n content = layer.getPopup().getContent();\n index = content.indexOf('<ul');\n index2 = content.indexOf('</div>');\n content = content.substr(index, index2);\n latLng = layer.getPopup().getLatLng();\n L.popup({\n maxWidth: 400\n }).setContent(content).setLatLng(latLng).openOn(mymap);\n return;\n }\n });\n}",
"function showDevMenuPop(){\n\t$( \"#deviceMenuPopUp\" ).dialog({\n\t\tmodal: true,\n\t\twidth: \"auto\",\n\t\tmaxHeight: 500,\n\t\topen: function(event, ui) { $(\".ui-dialog-titlebar-close\").show(); }\n\t});\n\t$(\"#deviceMenuPopUp\").empty().load(\"pages/ConfigEditor/deviceMenu.html\", function(){\n\t\tvar devices = getDevicesNodeJSON();\n\t\t$('span.ui-dialog-title').text('DEVICE');\n\t\t$('.ui-dialog-title').css({'margin-top':'7px','text-align':'center'});\n\t\tvar bck2 = '<div id=\"go-Back\" style=\"display:none;position:absolute;cursor:pointer;\" onclick=\"goBack()\"><img src=\"img/backArrow.png\" style=\"width: 20px;margin-left:10px;margin-top:5px;\"></div>';\n\t\t\t$('.ui-dialog-titlebar').prepend(bck2);\n\n\t\tfor(var a=0; a<devices.length; a++){\n\t\t\tif(devices[a].Status.toLowerCase()==\"reserved\"){\n\t\t\t\t$(\"#logsList\").show();\n\t\t\t\t$(\"#devList\").show();\n\t\t\t\t$(\"#deviceToolsList\").show();\n\t\t\t}else{\n\t\t\t\t$(\"#logsList\").hide();\n\t\t\t\t$(\"#devList\").hide();\n\t\t\t\t$(\"#deviceToolsList\").hide();\n\t\t\t}\n\t\t}\n\t\t$(\".ui-dialog\").position({\n\t\t\tmy: \"center\",\n\t\t\tat: \"center\",\n\t\t\tof: window\n\t\t});\n\t});\n}",
"function bcms_promptDirectToSpeedGrader() {\r\n let link = $(\"#assignment-speedgrader-link a\");\r\n if ( !link.length ) return; //return if we're not on an assignment.\r\n \r\n // link.attr('target', '_self'); //target = self, not blank.\r\n let prompt = $('<div id=\"dialog-directToSpeedGrader\" title=\"Open the Speed Grader?\">\\\r\n <p><span class=\"ui-icon ui-icon-extlink\" style=\"float:left; margin:0 0 20px 0;\"></span>Open the assessment screen (i.e., Speed Grader)?</p>\\\r\n </div>');\r\n setTimeout( () => {\r\n prompt.dialog({\r\n resizable: false,\r\n height: \"auto\",\r\n width: 400,\r\n modal: true,\r\n buttons: {\r\n \"Open Assessment\": function() {\r\n $( this ).dialog( \"close\" );\r\n link[0].click();\r\n },\r\n Cancel: function() {\r\n $( this ).dialog( \"close\" );\r\n }\r\n }\r\n });\r\n }, 250)\r\n}",
"async finalStep(stepContext) {\n // If the child dialog (\"bookingDialog\") was cancelled or the user failed to confirm, the Result here will be null.\n if (stepContext.result) {\n const result = stepContext.result;\n // Now we have all the booking details.\n\n console.log(result);\n\n // This is where calls to the booking AOU service or database would go.\n let msg = 'I wasn\\'t able to find anyone :( Try searching with different specs?'\n var foundPerson = MainDialog.findPeople(result);\n\n console.log(foundPerson);\n\n if (foundPerson) {\n msg = `You should talk to ${foundPerson.name} in Building ${foundPerson.location}!`; \n }\n\n // If the call to the booking service was successful tell the user.\n const timeProperty = new TimexProperty(result.travelDate);\n const travelDateMsg = timeProperty.toNaturalLanguage(new Date(Date.now()));\n await stepContext.context.sendActivity(msg, 'yeet');\n } else {\n await stepContext.context.sendActivity('Thank you.');\n }\n return await stepContext.beginDialog(MAIN_WATERFALL_DIALOG);\n //return await stepContext.endDialog();\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.