query
stringlengths
9
14.6k
document
stringlengths
8
5.39M
metadata
dict
negatives
listlengths
0
30
negative_scores
listlengths
0
30
document_score
stringlengths
5
10
document_rank
stringclasses
2 values
Use this if something is never supposed to have a value. Not even `undefined`. For example, `never[]` can be, ```ts const arrayOfNever = array(never()); ``` The only value that will satisfy this mapper is the empty array.
function never() { return function (name, mixed) { throw error_util_1.makeMappingError({ message: name + " must be never", inputName: name, actualValue: mixed, expected: "never", }); }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Array$empty() {\n return [];\n }", "function Array$empty() {\n return [];\n }", "function requireValue(isset) {\n if (!isset) {\n throw new Error(\"reduce of empty array with no initial value\");\n }\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0)\n return val;\n var arr = arrayWrap(val);\n var result = map(arr, callback);\n return allTruthyMode === true ? filter(result, function (x) { return !x; }).length === 0 : arrayUnwrap(result);\n };\n }", "function never() {\n return struct('never', () => false);\n}", "function never() {\n return struct('never', () => false);\n}", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0)\n return val;\n var arr = arrayWrap(val);\n var result = map(arr, callback);\n return (allTruthyMode === true) ? filter(result, function (x) { return !x; }).length === 0 : arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0)\n return val;\n var arr = arrayWrap(val);\n var result = map(arr, callback);\n return (allTruthyMode === true) ? filter(result, function (x) { return !x; }).length === 0 : arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0) return val;\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0) return val;\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0) return val;\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0) return val;\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0) return val;\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0) return val;\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0) return val;\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0) return val;\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0) return val;\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0) return val;\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0) return val;\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0) return val;\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n if (isArray(val) && val.length === 0) return val;\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n\t return function handleArray(val) {\n\t if (isArray(val) && val.length === 0) return val;\n\t val = arrayWrap(val);\n\t var result = map(val, callback);\n\t if (allTruthyMode === true)\n\t return filter(result, falsey).length === 0;\n\t return arrayUnwrap(result);\n\t };\n\t }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n\t return function handleArray(val) {\n\t val = arrayWrap(val);\n\t var result = map(val, callback);\n\t if (allTruthyMode === true)\n\t return filter(result, falsey).length === 0;\n\t return arrayUnwrap(result);\n\t };\n\t }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }", "function arrayHandler(callback, allTruthyMode) {\n return function handleArray(val) {\n val = arrayWrap(val);\n var result = map(val, callback);\n if (allTruthyMode === true)\n return filter(result, falsey).length === 0;\n return arrayUnwrap(result);\n };\n }" ]
[ "0.5621741", "0.5621741", "0.5577489", "0.5539898", "0.5457381", "0.5457381", "0.5441638", "0.5441638", "0.5438645", "0.5438645", "0.5438645", "0.5438645", "0.5438645", "0.5438645", "0.5438645", "0.5438645", "0.5438645", "0.5438645", "0.5438645", "0.5438645", "0.5438645", "0.54353493", "0.53984714", "0.53695905", "0.5357148", "0.5352905", "0.5352905", "0.5352905", "0.5352905", "0.5352905" ]
0.5986685
0
restores the entries and adds them to pokedex entries
function restoreEntries( storedEntries ) { // convert the stored entries // from a string back to an object // with the pokemonIds as keys and // the stringified entries as values let restoredEntries = JSON.parse( storedEntries ); // convert the entry strings back to // objects and then add them to the // pokedex entries for ( let i = 1; i <= 151; i++ ) { // have to use object[ key ] notation let entryString = restoredEntries[ i ]; let entry = JSON.parse( entryString ); pokedexEntries.push( entry ); } // loop return; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function deleteMarkers() {\n clearMarkers();\n markers = [];\n choiceMarkers = [];\n searchResMarkers = [];\n}//deleteMarkers", "nuke() {\n this._clearSpatialIndex();\n this.byId = [];\n this.fieldIndexes = {};\n this.fieldsToIndex.forEach(field => {\n this.fieldIndexes[field] = {};\n });\n }", "function undoAdd(){\r\n\tvar marker=markers_array[markers_array.length-1];\r\n\tif(marker.plines.length==0){\r\n\tmarker.setMap(null);\r\n\tvar newmarkArray=new Array();\r\n\tfor(i=0;i<markers_array.length-1;i++)\r\n\tnewmarkArray.push(markers_array[i]);\r\n\tmarkers_array=newmarkArray;\r\n\t$(\"#tfbc li[id='\"+marker.id + \"']\").css('display','');\r\n\tdragHandleFlag=true;\r\n\t$(\"#newHostSaver\").css('display','none');\t\r\n\t}\r\n\telse{\t\r\n\tmarker.plines[0].setMap(null);\r\n\tmarker.plines=[];\r\n\tmarker.cm=[];\r\n\tnewHostConFlag=true;\r\n\t\r\n\t}\r\n}", "function clearPreviousResults() {\n setMapOnAllMarkers(null);\n markersOnMap = [];\n arrayOfLocations = [];\n}", "restore(){\n\t\tthis.resetCharges();\n\t\tthis.repair();\n\t}", "clear() {\n log.map(\"Clearing the map of all the entries\");\n this._map.clear();\n }", "clearToLastMarker() {\n const markerIdx = this.entries.indexOf(MARKER);\n if (markerIdx >= 0) {\n this.entries.splice(0, markerIdx + 1);\n }\n else {\n this.entries.length = 0;\n }\n }", "function resetMarkers() {\n deleteMarkers();\n updateShops();\n //setAllMarkers();\n}", "revert() {\n this._cache = this._checkpoints.pop();\n }", "function revertChanges() {\n if (typeof db.getItem(savedData) !== 'undefined' && db.getItem(savedData) !== 'undefined' && db.getItem(savedData) !== 'null' && db.getItem(savedData) != null && db.getItem(savedData) !== \"\") {\n mainP.innerHTML = db.getItem(savedData);\n //makeEditable();\n sanitizeItems();\n };\n }", "function resetCustomMapping() {\n chrome.storage.sync.get('custom',(val) => {\n const custom = val['custom'];\n if (custom == null || custom[hostname] == null) return;\n delete custom[hostname];\n chrome.storage.sync.set({custom:custom},() => {\n if (chrome.runtime.lastError) {\n console.error('Could not reset custom mapping');\n return;\n }\n resetInputBtn.classList.add('hidden');\n });\n });\n}", "restore() {\n let save = JSON.parse(this.saveData);\n let charaBuilder = new UnderCharacterBuilder();\n let entities = this.getEntities();\n for (let i = entities.length - 1; i >= 0; --i) {\n if (entities[i] instanceof MutableObject) {\n this.removeEntity(entities[i]);\n }\n }\n for (let it of save.deploy) {\n this.addEntity(charaBuilder.build(it.x, it.y, this.entityInfo[it.id]));\n this.addEntityID(it.id);\n }\n }", "reset() {\n Object.keys(this._cache).forEach((key) => {\n if (key !== \"0\") {\n let value = this._cache[key];\n this._cache[key] = {\n type: value.type,\n name: value.name,\n props: {\n transforms: []\n }\n };\n }\n });\n }", "reset() {\n this._objInfo.forEach(info => {\n info.obj.position.copy(info.pos);\n info.obj.up.copy(info.up);\n\n this._checkChange(info);\n info.last.pos.copy(info.pos);\n });\n }", "function undo() {\n window.annotationObjects.pop();\n }", "cleanMap() {\n this.savedMarker.forEach(marker => {\n marker.setMap(null);\n });\n this.savedMarker = new Array();\n }", "function cleanUp() {\n\n\t// before version 1.0.12, datacache was in {posttype}.data.cache.json\n\tfor ( var index in posts ) {\n\t\tStorage.deleteSync( index + '.data.cache.json' );\n\t}\n\n}", "function redoArrays() {\n // Pop out the selected defender character id from the original \n // array.\n charNames.splice(selectedChar.Id, 1);\n // Pop out the selected defender character Pid Addres id \n // from the original array.\n charPicIndexAddres.splice(selectedChar.Id, 1);\n // Pop out the selected defender character Thumbnail Pid Addres id \n // from the original array.\n charThumbnailPicSAddres.splice(selectedChar.Id, 1);\n // Pop out the selected defender character Company id \n // from the original array.\n charSelCompany.splice(selectedChar.Id, 1);\n\n}", "function _cleanupKeys()\n {\n if (this._count == this._keys.length) {\n return;\n }\n var srcIndex = 0;\n var destIndex = 0;\n var seen = {};\n while (srcIndex < this._keys.length) {\n var key = this._keys[srcIndex];\n if (_hasKey(this._map, key)\n && !_hasKey(seen, key)\n ) {\n this._keys[destIndex++] = key;\n seen[key] = true;\n }\n srcIndex++;\n }\n this._keys.length = destIndex;\n }", "function resetBudgetEntry() {\n getStorage().removeItem(storageKey)\n}", "clearSilent() {\n let me = this;\n\n me._items.splice(0, me.getCount());\n me.map.clear();\n }", "clear () {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n this.forEach(function (_value, key, map) {\n typeMapDelete(transaction, map, key)\n })\n })\n } else {\n /** @type {Map<string, any>} */ (this._prelimContent).clear()\n }\n }", "function remDict(){\n var opts = document.getElementById(\"text_replace_select\").children;\n var opt;\n var matcher = document.getElementById(\"text_replace_matcher\");\n for (e in opts)\n if (opts[e].selected){\n console.log(\"Converting...\");\n opt = replacers[opts[e].value];\n }\n try {\n list = JSON.parse(localStorage[storage + opt]);\n if (!(list instanceof Array))\n list = convertOldDict(list);\n } catch(e) {\n console.log(\"addDict: \" + e);\n list = [];\n }\n if (matcher.value != \"\"){\n var nlist = deleteKey(matcher.value, list);\n localStorage[storage + opt] = JSON.stringify(nlist);\n matcher.value = \"\";\n document.getElementById(\"text_replace_replacer\").value = \"\";\n } else console.log(\"remDict: matcher is empty.\");\n}", "onRemove() {\n super.onRemove()\n SpellJSFile.registry.clear(this.path)\n SpellLocation.registry.clear(this.path)\n }", "resetMap() {\n if (custom_maps[this.id]) {\n delete custom_maps[this.id];\n\n const map = getMap(this.pad);\n this.map = map;\n this.mapping = map.mapping;\n\n this._compileMapping();\n }\n }", "function clearSoFarThisEntry() {\n while (soFarThisEntry.length > 0) {\n soFarThisEntry.shift();\n }\n}", "function handleClearSearchPoiMarkers() {\n\t\t\tmap.clearMarkers(map.POI);\n\t\t}", "_revertToOriginal() {\n this._storage = {}\n this._length = 0\n this._head = 0\n }", "function resetMap(){\n websiteMap = {};\n chrome.storage.sync.clear();\n chrome.storage.sync.set(mapToSettings());\n}", "function putMarkerBack() {\n // put the attraction back where it was\n for (i = 0; i < markersArray.length; i++) {\n marker = markersArray[i];\n if (marker.get(\"id\") == attraction_id) {\n latLng = new google.maps.LatLng(marker.get(\"lat\"), marker.get(\"lng\"));\n marker.setPosition(latLng);\n }\n }\n }" ]
[ "0.54110515", "0.5402046", "0.5352943", "0.53236425", "0.53165203", "0.5305262", "0.5258091", "0.5242506", "0.5242101", "0.5137043", "0.51300323", "0.5115131", "0.5111485", "0.51015997", "0.5101113", "0.50692147", "0.50648636", "0.50505054", "0.5040968", "0.50399214", "0.50161123", "0.50056595", "0.50002027", "0.49905783", "0.49854785", "0.49663007", "0.4963653", "0.49494278", "0.49430257", "0.49420714" ]
0.69865996
0
this function updates the subjects dropdown on clicking any grade
function setsubs(grade) { $('.sub').html(''); $('.sub').append('<option value="no">SUBJECTS</option>'); data['data'].list.map(function(val) { if(val.name==grade) { val.subjectList.map(function(v) { var s=v.name; var add='<option value="'+s+'">'+s+'</option>'; $('.sub').append(add); }); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "selectSubject(event) {\n\n let subjects = document.getElementsByClassName('subject');\n\n for (let i = 0; i < subjects.length; i++) {\n subjects[i].className = 'subject';\n }\n\n event.target.className = 'subject selected';\n\n //update the selected id\n this.setState({\n subjectSelected: event.currentTarget.dataset.subject_id\n });\n \n // when someone selects a subject, we would re-render the secions\n this.listSection();\n }", "function subsubs(subject)\n{\n if(window.innerWidth>1024)\n {\n $('.side').html('');\n $('.side').append(' <h1><b>LOGO</b></h1> <h4><b>CONTENTS</b></h4>');\n }\n else if(window.innerWidth<768)\n {\n $('#navi').html('');\n }\n\n var e=document.getElementsByClassName('grade')[0];\n var gra=e.options[e.selectedIndex].value;\n grade=gra;\n sub=subject;\n \n \n data.data.list.map(function(val)\n {\n if(val.name==gra)\n {\n val.subjectList.map(function(va){\n if(va.name==subject)\n {\n $('#sel').html(\"\");\n va.subSubjectList.map(function(v)\n {\n subsub=v.name;\n if(window.innerWidth<=768)\n {\n var s='<a class=\"chap\">'+v.name+'</a>';\n $('#mySidenav').append(s);\n $('#mySidenav').append('<div ><ul id=\"'+v.name+'\" class=\"chapter\"></ul></div>');\n $('.chap').on('click',{subsub:v.name},showit);\n v.chapterList.map(function(c)\n {\n console.log(c);\n $('#'+v.name).append('<li><a >'+c.name+'</a></li>');\n });\n }\n else if(window.innerWidth>=1024)\n {\n var s='<p ><b class=\"subsub\" >'+v.name+'</b></p>';\n subsub=v.name;\n $('.side').append(s);\n $('.side').append('<div ><ul id=\"'+v.name+'\" class=\"chapter\"></ul></div>');\n v.chapterList.map(function(c)\n {\n console.log(c);\n $('#'+v.name).append('<li><a >'+c.name+'</a></li>');\n });\n $('.subsub').on('click',{subsub:v.name},showit);\n }\n });\n }\n });\n }\n });\n}", "function load_subject_selector()\n{\n var data = get_data();\n var select = document.getElementById(\"angst-subjects\");\n \n default_option = document.createElement(\"option\");\n default_option.value = \"\";\n default_option.appendChild(document.createTextNode(\"-\"));\n select.appendChild(default_option);\n select.appendChild\n for (var i=0; i < data.length; i++)\n {\n var course = data[i];\n var optgroup = document.createElement(\"optgroup\");\n optgroup.label = course.course;\n for (var j = 0; j < course.disciplines.length; j++)\n {\n var discipline = course.disciplines[j];\n var option = document.createElement(\"option\");\n option.appendChild(document.createTextNode(discipline.name));\n option.value = discipline.expr;\n optgroup.appendChild(option);\n }\n select.appendChild(optgroup);\n }\n}", "function subjectDropDown() {\n // Read in data\n d3.json('Data/samples.json').then((data) => {\n // Add list of subjects to dropdown menu\n var dropDownMenu = d3.select('#selDataset');\n var subjectList = data.names\n subjectList.forEach((subject) => {\n dropDownMenu\n .append('option')\n .text(subject)\n .property('value', subject)\n })\n\n });\n}", "function assignmentsClickOn(asgn_id) {\n\tvar asgnSelect = document.getElementById('assignment_select');\n\tvar idx = assignmentsGetIdxForId(asgn_id);\n\tif (idx >= 0) {\n\t\tasgnSelect.selectedIndex = idx;\n\t\tassignmentsChangeSelected();\n\t}\n}", "function setFeesSubjects(){\r\n var schYear = $('#syEntered').val();\r\n var regexNoSpace = /^\\d{0,4}(\\-\\d{0,4})?$/;\r\n var schYearLength = schYear.length;\r\n var lastSchYearInput = schYear.substring(schYearLength-1,schYearLength);\r\n var gyl = $('#currentGYL').val();\r\n var dept = $('input[name=radioDepartment]:checked').val();\r\n var selectedGYL = \"\";\r\n if(dept === \"Elementary Dept.\"){\r\n selectedGYL = $('#grade').val();\r\n }else if(dept === \"High School Dept.\"){\r\n selectedGYL = $('#yrLevel').val();\r\n }else{\r\n selectedGYL = \"wa\";\r\n }\r\n \r\n if($('#studentId').html()===\"\" || $('#studentName').html()===\"\"){\r\n $('#div-overlay-alert-msg').html(\"<i class='icon-exclamation-sign'></i>&nbsp;&nbsp;Enter student ID on the search textbox!\");\r\n $('#div-overlay-alert-msg').show('blind',1000);\r\n }else if($('#age').val()===\"\"){\r\n $('#div-overlay-alert-msg').html(\"<i class='icon-exclamation-sign'></i>&nbsp;&nbsp;Please enter age!\");\r\n $('#div-overlay-alert-msg').show('blind',1000);\r\n $('#age').css({border: '1px solid red'});\r\n $('#syEntered').css({border: '1px solid #c0c0c0'});\r\n $('#genAverage').css({border: '1px solid #c0c0c0'});\r\n }else if(!regexNoSpace.test(lastSchYearInput) || $('#syEntered').val()===\"\"){\r\n var resultSchYear = schYear.substring(0,schYearLength-1);\r\n $('#syEntered').val(resultSchYear);\r\n $('#div-overlay-alert-msg').html(\"<i class='icon-exclamation-sign'></i>&nbsp;&nbsp;Please enter school year correctly.\");\r\n $('#div-overlay-alert-msg').show('blind',1000);\r\n $('#syEntered').css({border: '1px solid red'});\r\n $('#age').css({border: '1px solid #c0c0c0'});\r\n $('#genAverage').css({border: '1px solid #c0c0c0'});\r\n }else if($('#genAverage').val()===\"\"){\r\n $('#div-overlay-alert-msg').html(\"<i class='icon-exclamation-sign'></i>&nbsp;&nbsp;Please enter gen average!\");\r\n $('#div-overlay-alert-msg').show('blind',1000);\r\n $('#genAverage').css({border: '1px solid red'});\r\n $('#syEntered').css({border: '1px solid #c0c0c0'});\r\n $('#age').css({border: '1px solid #c0c0c0'});\r\n\r\n }else if(selectedGYL === gyl){\r\n $('#div-overlay-alert-msg').html(\"<i class='icon-exclamation-sign'></i>&nbsp;&nbsp;You are currently enrolled in \"+selectedGYL);\r\n $('#div-overlay-alert-msg').show('blind',1000);\r\n }else{\r\n $('#div-overlay-alert-msg').hide('blind',1000);\r\n $('#genAverage').css({border: '1px solid #c0c0c0'});\r\n $('#syEntered').css({border: '1px solid #c0c0c0'});\r\n $('#age').css({border: '1px solid #c0c0c0'});\r\n \r\n $('#radioFullPaymnt').removeAttr('disabled');\r\n $('#radioMonthlyPaymnt').removeAttr('disabled');\r\n $('#radioSemestralPaymnt').removeAttr('disabled');\r\n $('#age').attr('readonly','readonly');\r\n $('#syEntered').attr('readonly','readonly');\r\n $('#genAverage').attr('readonly','readonly');\r\n $('#yrLevel').attr('disabled','disabled');\r\n var category=\"\";\r\n if($('input[name=radioDepartment]:checked').val()===\"Elementary Dept.\"){\r\n category = $('#grade').val();\r\n enabledMode();\r\n $('#btn-sub-fees').attr('disabled','disabled');\r\n }else if($('input[name=radioDepartment]:checked').val()===\"High School Dept.\"){\r\n category = $('#yrLevel').val();\r\n enabledMode();\r\n $('#btn-sub-fees').attr('disabled','disabled');\r\n }else{\r\n $('#div-overlay-alert-msg').html(\"<i class='icon-exclamation-sign'></i>&nbsp;&nbsp;Please choose what department!\");\r\n $('#div-overlay-alert-msg').show('blind',1000);\r\n disabledMode();\r\n $('#btn-sub-fees').removeAttr('disabled');\r\n }\r\n $('#category').html(category);\r\n }\r\n}", "function refreshSelect(targetObject,newSubject){\r\n\r\n // Only refresh the subject once (at start), and only the topic if the subject isn't 0 \r\n if ($(targetObject).attr('id') == 'edit-subject' || newSubject != 0)\r\n $.each(taxonomy, function(k,v) {\r\n if ((v.parents[0] * 1) == newSubject) {\r\n targetObject.append('<option value=\"' + v.tid + '\">'+ v.name +'</option>');\r\n }\r\n });\r\n }", "createSubjectSelect(subjects) {\n // Get subject div to add select box to\n const subject_div = document.getElementById('subject-choice');\n\n // Create select box\n const select = document.getElementById('subject-select');\n\n // Clear any previous options\n select.innerHTML = '';\n\n // Loop through subjects\n for (let i = 0; i < subjects.length; i++) {\n // Do not display general as general represents the hard coded questions\n if (subjects[i].subject !== 'General') {\n // Create option element\n const option = document.createElement('option');\n\n // Set value\n option.value = subjects[i].subject;\n\n // Display option text\n option.innerHTML = subjects[i].subject;\n\n // add option to select\n select.appendChild(option);\n }\n }\n\n // Add select to form\n subject_div.appendChild(select);\n }", "function onUpdateStudent() {\n\n if (classesSelectedIndex == -1 || classesSelectedIndex == 0) {\n updateTableOfStudents(true, true);\n } else {\n // retrieve key of currently selected class\n var keyClass = classes[classesSelectedIndex - 1].key;\n updateTableOfStudents(true, true, keyClass);\n }\n }", "function dropDownSelection(event) {\n var selectDd = document.querySelector('#gradeLevel');\n document.getElementById(\"results\").innerHTML = selectDd.value;\n\n\n}", "function subjectRead (subjects){\n\t\t$(\"#scr2\").html(\"\");\n\t\t$(\"#main\").html(\"\");\n\t\texamsNext.html(\"\");\n\t\tif (subjects.length == 0)\n\t\t{\n\t\t\t$(\"#main\").append(\"<p class='emphasis'>No subjects yet!</p><p>Go to 'Manage Exams' to add a new subject.\");\n\t\t\texamsNext.append(\"<p class='emphasis'>No subjects yet!</p><p>Go to 'Manage Exams' to add a new subject.\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$.each(subjects,function (key,value)\n\t\t\t{\n\t\t\t\tgpaCalc(key);\n\t\t\t\t$(\"#main\").append(\"<p class='emphasis'>\"+key+\"</p><p><b>Current: </b>\"+subjects[key][\"gpa\"]+\",<b> Goal: </b>\"+subjects[key][\"goal\"]+\"</p>\");\n\t\t\t\tchartDraw(\"#scr2\",key,subjects[key][\"chartdata\"],key);\n\t\t\t\texamsNext.append(\"<p class='emphasis'>\"+key+\"</p>\")\n\t\t\t\tvar count = 0;\n\t\t\t\tfor (var a = 0;a<subjects[key][\"chartdata\"].length;a++)\n\t\t\t\t{\n\t\t\t\t\tif (subjects[key][\"chartdata\"][a][\"done\"] == false)\n\t\t\t\t\t{\n\t\t\t\t\t\texamsNext.append(\"<p><b>\"+subjects[key][\"chartdata\"][a][\"exam\"]+\"</b>, \"+subjects[key][\"chartdata\"][a][\"weight\"]+\"% of final grade\");\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (count == 0)\n\t\t\t\t{\n\t\t\t\t\texamsNext.append(\"<p><b>None</b></p>\")\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}", "function subjectSem()\r\n{\r\n for (var i = 1; i <=8; i++) \r\n document.getElementById('sub'+i).style.display = 'none';\r\n\r\n if(document.getElementById('year-dropdown').value==\"fe\")\r\n {\r\n \r\n if( document.getElementById('sem-dropdown').value==\"odd\")\r\n document.getElementById('sub1').style.display='block';\r\n else if(document.getElementById('sem-dropdown').value==\"even\")\r\n document.getElementById('sub2').style.display = 'block'; \r\n }\r\n\r\n if(document.getElementById('year-dropdown').value==\"se\")\r\n {\r\n \r\n if( document.getElementById('sem-dropdown').value==\"odd\")\r\n document.getElementById('sub3').style.display='block';\r\n else if(document.getElementById('sem-dropdown').value==\"even\")\r\n document.getElementById('sub4').style.display = 'block'; \r\n }\r\n\r\n if(document.getElementById('year-dropdown').value==\"te\")\r\n {\r\n \r\n if( document.getElementById('sem-dropdown').value==\"odd\")\r\n document.getElementById('sub5').style.display='block';\r\n else if(document.getElementById('sem-dropdown').value==\"even\")\r\n document.getElementById('sub6').style.display = 'block'; \r\n }\r\n\r\n if(document.getElementById('year-dropdown').value==\"be\")\r\n {\r\n \r\n if( document.getElementById('sem-dropdown').value==\"odd\")\r\n document.getElementById('sub7').style.display='block';\r\n else if(document.getElementById('sem-dropdown').value==\"even\")\r\n document.getElementById('sub8').style.display = 'block'; \r\n }\r\n}", "function optionChanged(){\n\n // Use D3 to get selected subject ID from dropdown \n subjectID = d3.select(\"#selDataset\").property(\"value\");\n console.log(subjectID)\n \n\n // Update Charts based on selected Student_ID\n topOTUBar(subjectID)\n topOTUBubble(subjectID)\n demographTable(subjectID)\n washingGauge(subjectID)\n\n \n\n}", "function renderGrades(){\n // Get subject from standardID.\n standardSubjectID = _.find(_.find(standards, function(standard){\n return standard.id === OC.editor.lwOptions['standardID'];\n }).subjects, function(subject) { return subject.title === OC.editor.lwOptions['subject']; }).id;\n\n // Find the subject title in the standards list.\n $.get('/resources/api/get-child-categories/' + standardSubjectID + '/',\n function(response){\n if (response.status == 'true'){\n var list = response.categories,\n i,\n gradeList = $('.lesson-wizard-grade-level-list');\n for (i = 0; i < list.length; i++){\n gradeList.append($('<li/>', {\n 'class': 'lesson-wizard-grade-level-list-item',\n 'id': list[i].id,\n 'text': list[i].title,\n }));\n }\n // Handle clicks for grade & topic.\n $('.lesson-wizard-grade-level-list-item').click(\n gradeTopicClickHandler);\n }\n else {\n OC.popup(response.message, response.title);\n }\n\n },\n 'json');\n }", "function updateDropdownLabel() {\n // code goes here\n semesterDropLabel.innerHTML = semester\n}", "function updateQualification(ids)\r\n{\r\n addQualBut.style.display=\"none\";\r\n updQualButton.style.display=\"block\";\r\n canQualUpd.style.display=\"block\";\r\n\r\n\r\n typeUpd = document.getElementById(\"type0\");\r\n if(qualList[ids].qualification_type==\"Higher Ed\")\r\n {\r\n typeUpd.getElementsByTagName('option')[1].selected='selected';\r\n }\r\n if(qualList[ids].qualification_type==\"VET\")\r\n {\r\n typeUpd.getElementsByTagName('option')[2].selected='selected';\r\n }\r\n if(qualList[ids].qualification_type==\"TAFE\")\r\n {\r\n typeUpd.getElementsByTagName('option')[3].selected='selected';\r\n } \r\n degUpd=document.getElementById(\"degree0\");\r\n uniUpd=document.getElementById(\"uni0\");\r\n dateUpd=studyArr=document.getElementById(\"date0\");\r\n studyUpd =document.getElementById(\"study0\");\r\n if(qualList[ids].finished==0)\r\n {\r\n studyUpd.getElementsByTagName('option')[1].selected='selected';\r\n document.getElementById(\"date0\").style.display=\"none\";\r\n }\r\n if(qualList[ids].finished==1)\r\n {\r\n //studyUpd.value = \"Completed\";\r\n studyUpd.getElementsByTagName('option')[2].selected='selected';\r\n document.getElementById(\"date0\").style.display=\"block\";\r\n dateUpd.value=qualList[ids].end_date;\r\n }\r\n\r\n degUpd.value=qualList[ids].qualification_name;\r\n uniUpd.value=qualList[ids].University_name;\r\n qualId=document.getElementById(\"edu\"+ids).value; \r\n}", "function getElements(){\n var subject_conclusion_select_items = document.getElementById('id_subject_conclusion');\n var predicate_conclusion_select_items = document.getElementById('id_predicate_conclusion');\n subject_conclusion_select_items.innerHTML = '';\n predicate_conclusion_select_items.innerHTML = '';\n var major_subject = document.getElementById('id_subject_major').value;\n var major_predicate = document.getElementById('id_predicate_major').value;\n var minor_subject = document.getElementById('id_subject_minor').value;\n var minor_predicate = document.getElementById('id_predicate_minor').value;\n var subject_conclusion_select_items = document.getElementById('id_subject_conclusion');\n if(major_subject != null && major_subject != '' && subject_conclusion_select_items.innerHTML.indexOf('>'+major_subject+'<') == -1){\n subject_conclusion_select_items.innerHTML += '<option>' + major_subject + '</option>';\n predicate_conclusion_select_items.innerHTML += '<option>' + major_subject + '</option>';\n }\n if(major_predicate != null && major_predicate != '' && subject_conclusion_select_items.innerHTML.indexOf('>'+major_predicate+'<') == -1){\n subject_conclusion_select_items.innerHTML += '<option>' + major_predicate + '</option>';\n predicate_conclusion_select_items.innerHTML += '<option>' + major_predicate + '</option>';\n }\n if(minor_subject != null && minor_subject != '' && subject_conclusion_select_items.innerHTML.indexOf('>'+minor_subject+'<') == -1){\n subject_conclusion_select_items.innerHTML += '<option>' + minor_subject + '</option>';\n predicate_conclusion_select_items.innerHTML += '<option>' + minor_subject + '</option>';\n }\n if(minor_predicate != null && minor_predicate != '' && subject_conclusion_select_items.innerHTML.indexOf('>'+minor_predicate+'<') == -1){\n subject_conclusion_select_items.innerHTML += '<option>' + minor_predicate + '</option>';\n predicate_conclusion_select_items.innerHTML += '<option>' + minor_predicate + '</option>';\n }\n onInputTextValueChange();\n }", "function setDropdownContent(grade){\n\t\n\tvar na = \"<option value=\\\"NA\\\"> --- </option>\";\n var ip = \"<option value=\\\"inprog\\\"> In Progress </option>\";\n var a = \"<option value=\\\"A\\\"> A </option>\";\n var b = \"<option value=\\\"B\\\"> B </option>\";\n var c = \"<option value=\\\"C\\\"> C </option>\";\n var d = \"<option value=\\\"D\\\"> D </option>\";\n var f = \"<option value=\\\"F\\\"> F </option>\";\n var x = \"<option value=\\\"EX\\\"> EX </option>\";\n\tswitch(grade){\n\t\tcase \"inprogress\":\n\t\t\tip = \"<option value=\\\"inprog\\\" selected> In Progress </option>\";\n\t\t\tbreak;\n\t\tcase \"A\":\n\t\t\ta = \"<option value=\\\"A\\\" selected> A </option>\";\n\t\t\tbreak;\n\t\tcase \"B\":\n\t\t\tb = \"<option value=\\\"B\\\" selected> B </option>\";\n\t\t\tbreak;\n\t\tcase \"C\":\n\t\t\tc = \"<option value=\\\"C\\\" selected> C </option>\";\n\t\t\tbreak;\n\t\tcase \"D\":\n\t\t\td = \"<option value=\\\"D\\\" selected> D </option>\";\n\t\t\tbreak;\n\t\tcase \"F\":\n\t\t\tf = \"<option value=\\\"F\\\" selected> F </option>\";\n\t\t\tbreak;\n\t\tcase \"EX\":\n\t\t\tx = \"<option value=\\\"EX\\\" selected> EX </option>\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tna = \"<option value=\\\"NA\\\" selected> --- </option>\";\n\t\t\tbreak;\n\t}\n\n\treturn na + ip + a + b + c + d + f + x;\n}", "function updateSemester(clicked) {\n // code goes here\n semester = clicked.innerHTML\n}", "function initGradeSelection(cancelable, grade) {\n loadContent();\n\n function loadContent() {\n $.ajax({\n url: apiURL + '/school/grades',\n type: 'get',\n success: function(data, status) {\n data = parseGradeSelection(data['grades'], grade);\n $(data)\n .appendTo('body')\n .modal({\n escapeClose: cancelable,\n clickClose: cancelable\n })\n .promise()\n .done(function() {\n componentHandler.upgradeDom();\n });\n },\n error: function(xhr, desc, err) {\n //console.log(xhr);\n //console.log(\"Details: \" + desc + \"\\nError:\" + err);\n },\n headers: { auth: store.get(activeUser).auth }\n });\n }\n\n $(document).on('click', '#done-grade-selection', function(e) {\n e.preventDefault();\n var grade = $('input[name=options]:checked').val();\n initCourseSelection(grade, cancelable);\n });\n\n function parseGradeSelection(data, grade) {\n var grades =\n '<div class=\"modal\" id=\"grade-selection\"> <div class=\"mdl-card__supporting-text\"> <h4>Bitte wähle deine Klasse aus:</h4> <div class=\"mdl-grid action-type\"><ul style=\"list-style: none;\">';\n for (i = 0; i < data.length; i++) {\n var currentGrade = data[i];\n var checked = '';\n if (grade) {\n if (currentGrade == grade) {\n checked = 'checked';\n }\n } else if (i == 0) {\n checked = 'checked';\n }\n\n grades +=\n '<li> <label class=\"mdl-radio mdl-js-radio mdl-js-ripple-effect\" for=\"option-' +\n currentGrade +\n '\"> <input type=\"radio\" id=\"option-' +\n currentGrade +\n '\" class=\"mdl-radio__button\" name=\"options\" ' +\n checked +\n ' value=\"' +\n currentGrade +\n '\"> <span class=\"mdl-radio__label\">' +\n currentGrade +\n '</span> </label> </li>';\n }\n grades +=\n '</ul></div><button class=\"mdl-button\" id=\"done-grade-selection\">Weiter zur Kursauwahl</button></div>';\n\n return grades;\n }\n}", "function getChapterBySubject(e) {\n\t\tvar $examClasses = jQuery('#exam-classes'),\n\t\t\t$examQuestions = jQuery('#exam-questions'),\n\t\t\t$spinIcon = jQuery(e.target).parent('div').find('span.input-group-addon'),\n\t\t\t$subjectId = parseInt(jQuery(e.target).find('option:selected').val());\n\t\t\n\t\t// Remove elements\n\t\t$examClasses.empty();\n\t\t$examQuestions.empty();\n\t\t\n\t\t// If subject not is number, stop now\n\t\tif (!jQuery.isNumeric($subjectId)) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t// Show spin icon\n\t\t$spinIcon.html('<i class=\"fa fa-refresh fa-spin\"></i>');\n\t\t\n\t\t// Send request\n\t\tLumiaJS.ajaxRequest(window.location.base + '/admin/exam/get-classes-and-questions-by-subject', {\n\t\t\t'subject-id': $subjectId\n\t\t}).done(function(dataResponse){\n\t\t\t\n\t\t\tif (dataResponse.status == 'SUCCESS') {\n\t\t\t\t\n\t\t\t\t// Append classes\n\t\t\t\tif (typeof dataResponse.contexts.CLASSES === 'string') {\n\t\t\t\t\t$examClasses.html(dataResponse.contexts.CLASSES);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Append students into cache\n\t\t\t\tif (jQuery.isPlainObject(dataResponse.contexts.STUDENTS)) {\n\t\t\t\t\tLumiaJS.admin.exam.studentsByClasses = dataResponse.contexts.STUDENTS;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Append questions\n\t\t\t\tif (typeof dataResponse.contexts.QUESTIONS === 'string') {\n\t\t\t\t\t$examQuestions.html(dataResponse.contexts.QUESTIONS);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tBootstrapDialog.show({\n\t\t\t\t\ttitle: LumiaJS.i18n.translate('Dialog:@Error'),\n\t\t\t\t\tmessage: function() {\n\t\t\t\t\t\tjQuery('select[name=exam_subject] option:first-child').attr('selected', 'selected');\n\t\t\t\t\t\treturn dataResponse.message;\n\t\t\t\t\t},\n\t\t\t\t\tclosable: false,\n\t\t\t\t\ttype: BootstrapDialog.TYPE_DANGER,\n\t\t\t\t\tbuttons: [{\n\t\t label: LumiaJS.i18n.translate('Form:@Button cancel'),\n\t\t cssClass: 'btn-danger',\n\t\t action: function(dialogItself) {\n\t\t dialogItself.close();\n\t\t }\n\t\t }]\n\t\t\t\t});\n\t\t\t}\n\t\t\t\n\t\t}).always(function(){\n\t\t\t// Show mandatory icon\n\t\t\t$spinIcon.html('<i class=\"fa fa-caret-right icon-mandatory\"></i>');\n\t\t});\n\t}", "function assignmentsRender() {\n\tvar asgnSelect = document.getElementById('assignment_select');\n\tfor(i = asgnSelect.options.length - 1 ; i >= 0 ; i--) {\n\t\tasgnSelect.remove(i);\n\t}\n\t\n\tvar shown=0;\n\tfor (var i=0; i<assignments.length; i++) {\n\t\tvar option = document.createElement(\"option\");\n\t\toption.value = assignments[i].id;\n\t\toption.text = assignments[i].name;\n\t\tfor (var j=0; j<assignments[i].level; j++)\n\t\t\toption.text = \"__\" + option.text;\n\t\tif (assignments[i].visible == 0) option.style.display = \"none\";\n\t\telse shown++;\n\t\tasgnSelect.add(option);\n\t\tif (assignments[i].selected == 1) asgnSelect.value = assignments[i].id;\n\t}\n\tasgnSelect.size = shown;\n}", "function AssignmentsPerStudentPerCourseData(){\r\n \r\n console.log(\"am runnin...\"); \r\n \r\n let chosen = document.getElementById(\"choose\").value;\r\n console.log(chosen); \r\n if (chosen==\"apspc1\"){\r\n document.getElementById(\"first name\").value =\"Lefteris\";\r\n document.getElementById(\"last name\").value =\"Papadogiannis\";\r\n document.getElementById(\"title\").value=\"title1\"\r\n document.getElementById(\"stream\").value=\"Stream1\"\r\n document.getElementById(\"type\").value=\"Type1\"\r\n document.getElementById(\"assignment\").value=\"assignment1\"\r\n document.getElementById(\"subDate\").value=\"2020-12-02\"\r\n }\r\n else if(chosen==\"apspc2\"){\r\n document.getElementById(\"first name\").value =\"Mixalis\";\r\n document.getElementById(\"last name\").value =\"Karvelas\";\r\n document.getElementById(\"title\").value=\"title2\"\r\n document.getElementById(\"stream\").value=\"Stream1\"\r\n document.getElementById(\"type\").value=\"Type3\"\r\n document.getElementById(\"assignment\").value=\"assignment2\"\r\n document.getElementById(\"subDate\").value=\"2021-02-23\"\r\n }\r\n else if(chosen==\"apspc3\"){\r\n document.getElementById(\"first name\").value =\"Dimitris\";\r\n document.getElementById(\"last name\").value =\"Nikolidakis\";\r\n document.getElementById(\"title\").value=\"title1\"\r\n document.getElementById(\"stream\").value=\"Stream2\"\r\n document.getElementById(\"type\").value=\"Type1\"\r\n document.getElementById(\"assignment\").value=\"assignment3\"\r\n document.getElementById(\"subDate\").value=\"2021-04-13\"\r\n }\r\n else if(chosen==\"apspc4\"){\r\n document.getElementById(\"first name\").value =\"PROJECT1\";\r\n document.getElementById(\"last name\").value =\"PRIVATE SCHOOL\";\r\n document.getElementById(\"title\").value=\"title1\"\r\n document.getElementById(\"stream\").value=\"Stream3\"\r\n document.getElementById(\"type\").value=\"Type2\"\r\n document.getElementById(\"assignment\").value=\"assignment4\"\r\n document.getElementById(\"subDate\").value=\"2021-05-14\"\r\n }\r\n else{\r\n document.getElementById(\"first name\").value =\"--\";\r\n document.getElementById(\"last name\").value =\"--\";\r\n document.getElementById(\"title\").value=\"--\"\r\n document.getElementById(\"stream\").value=\"--\"\r\n document.getElementById(\"type\").value=\"--\"\r\n document.getElementById(\"assignment \").value=\"--\"\r\n document.getElementById(\"subDate\").value=\"--\"\r\n }\r\n}", "chooseData() {\n // ******* TODO: PART I *******\n //Changed the selected data when a user selects a different\n // menu item from the drop down.\n\n }", "chooseData() {\n // ******* TODO: PART I *******\n //Changed the selected data when a user selects a different\n // menu item from the drop down.\n\n }", "function updateTableGrades(sel_id, xml, i) {\n\tvar val = getCourseGradeAt(xml, i);\n\tif(val === \"\"){\n\t\tval = \"NA\";\n\t}\n\tvar sel = document.getElementById(\"sel_\"+sel_id);\n var opts = sel.options;\n\n\t// set selected value\n\tfor (var opt, j = 0; opt = opts[j]; j++) {\n\t if (opt.value == val) {\n\t // sel.selectedIndex = j;\n\t sel.options[j].selected = true;\n\t return;\n \t}\n\t}\t\n\t\n\t// Set table color corresponding to grade\n\tsetTableColor(sel_id, val);\n}", "function AssignmentsPerCourseData(){\r\n \r\n console.log(\"am runnin...\"); \r\n \r\n let chosen = document.getElementById(\"choose\").value;\r\n console.log(chosen); \r\n if (chosen==\"apc1\"){\r\n document.getElementById(\"assignment title\").value =\"PROJECT1\";\r\n document.getElementById(\"description\").value =\"PRIVATE SCHOOL\";\r\n document.getElementById(\"title\").value=\"title1\"\r\n document.getElementById(\"stream\").value=\"Stream1\"\r\n document.getElementById(\"type\").value=\"Type1\"\r\n }\r\n else if(chosen==\"apc2\"){\r\n document.getElementById(\"assignment title\").value =\"PROJECT2\";\r\n document.getElementById(\"description\").value =\"PRIVATE SCHOOL\";\r\n document.getElementById(\"title\").value=\"title1\"\r\n document.getElementById(\"stream\").value=\"Stream2\"\r\n document.getElementById(\"type\").value=\"Type2\"\r\n }\r\n else if(chosen==\"apc3\"){\r\n document.getElementById(\"assignment title\").value =\"PROJECT3\";\r\n document.getElementById(\"description\").value =\"CAR\";\r\n document.getElementById(\"title\").value=\"title3\"\r\n document.getElementById(\"stream\").value=\"Stream3\"\r\n document.getElementById(\"type\").value=\"Type2\"\r\n }\r\n else if(chosen==\"apc4\"){\r\n document.getElementById(\"assignment title\").value =\"PROJECT4\";\r\n document.getElementById(\"description\").value =\"HOME BUILD\";\r\n document.getElementById(\"title\").value=\"title1\"\r\n document.getElementById(\"stream\").value=\"Stream4\"\r\n document.getElementById(\"type\").value=\"Type1\"\r\n }\r\n else{\r\n document.getElementById(\"assignment title\").value =\"--\";\r\n document.getElementById(\"description\").value =\"--\";\r\n document.getElementById(\"title\").value=\"--\"\r\n document.getElementById(\"stream\").value=\"--\"\r\n document.getElementById(\"type\").value=\"--\"\r\n }\r\n}", "function optionChanged(SubjectID){\n demographicInfo(SubjectID);\n barChart(SubjectID);\n bubbleChart(SubjectID);\n}", "function subjectExpand(getData, response)\n{\n\t//generates base form html so that the database query can add options\n\tvar temp = \"document.getElementById('subjectL').value\";\n\tvar list = '<form action=\"\">'+ \n \t\t'<select id=\"courseL\" onchange=\"courseExpand(this.value,'+temp+') \">'+\n \t\t'<option value=\"\">Select a courseID</option>';\n \t//Funtion returns a function that generates the html for the options of the select box\n\tdatabase.queryDB(getData, list, getData['databaseType'], ['courseID','subject'])(function(htmlString){\n\t\thtmlString+='</select>'+'</form>';\n \t\tvar headers = {};\n \t\theaders[\"Content-Type\"] = \"text/html\";\n \t\theaders[\"Access-Control-Allow-Origin\"] = \"*\";\n\t\tresponse.writeHead(200, headers);\n\t\tresponse.write(htmlString);\n\t\tresponse.end();\n\t}, function(errback){throw errback;});\n}", "gradeSelect(selection) {\n this.state.gradeSel.push(selection);\n }" ]
[ "0.65726906", "0.6491116", "0.6424302", "0.64040977", "0.6280794", "0.6280423", "0.626298", "0.6253107", "0.62371063", "0.62352073", "0.62029254", "0.6176851", "0.6151119", "0.6121563", "0.61044115", "0.6094283", "0.6090541", "0.60407686", "0.5956725", "0.5935502", "0.5925065", "0.59227484", "0.59150743", "0.5860583", "0.5860583", "0.5828363", "0.58250797", "0.5812294", "0.58052903", "0.5799618" ]
0.72468215
0
it updates the subsubjects in navigation bar on clicking the the subject
function subsubs(subject) { if(window.innerWidth>1024) { $('.side').html(''); $('.side').append(' <h1><b>LOGO</b></h1> <h4><b>CONTENTS</b></h4>'); } else if(window.innerWidth<768) { $('#navi').html(''); } var e=document.getElementsByClassName('grade')[0]; var gra=e.options[e.selectedIndex].value; grade=gra; sub=subject; data.data.list.map(function(val) { if(val.name==gra) { val.subjectList.map(function(va){ if(va.name==subject) { $('#sel').html(""); va.subSubjectList.map(function(v) { subsub=v.name; if(window.innerWidth<=768) { var s='<a class="chap">'+v.name+'</a>'; $('#mySidenav').append(s); $('#mySidenav').append('<div ><ul id="'+v.name+'" class="chapter"></ul></div>'); $('.chap').on('click',{subsub:v.name},showit); v.chapterList.map(function(c) { console.log(c); $('#'+v.name).append('<li><a >'+c.name+'</a></li>'); }); } else if(window.innerWidth>=1024) { var s='<p ><b class="subsub" >'+v.name+'</b></p>'; subsub=v.name; $('.side').append(s); $('.side').append('<div ><ul id="'+v.name+'" class="chapter"></ul></div>'); v.chapterList.map(function(c) { console.log(c); $('#'+v.name).append('<li><a >'+c.name+'</a></li>'); }); $('.subsub').on('click',{subsub:v.name},showit); } }); } }); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "toggleSubject (addedSub){\n const foundSubject = _.find(this.state.subjects, subject => subject.name === addedSub);\n foundSubject.isCompleted = !foundSubject.isCompleted;\n this.setState ({subjects : this.state.subjects});\n }", "function lijstSubMenuItem() {\n\n if ($mLess.text() == \"meer\") {\n $mLess.text(\"minder\")\n } else {\n $mLess.text(\"meer\");\n\n }\n $list.toggleClass('hidden')\n $resum.get(0).scrollIntoView('slow');\n event.preventDefault()\n }", "selectSubject(event) {\n\n let subjects = document.getElementsByClassName('subject');\n\n for (let i = 0; i < subjects.length; i++) {\n subjects[i].className = 'subject';\n }\n\n event.target.className = 'subject selected';\n\n //update the selected id\n this.setState({\n subjectSelected: event.currentTarget.dataset.subject_id\n });\n \n // when someone selects a subject, we would re-render the secions\n this.listSection();\n }", "function load_subject_tab(){\n\t$(\"subject1\").onclick = function(){\n\t\t$(\"content1\").toggle();\n\t\tif($(\"content1\").getStyle('display') == \"none\"){\n\t\t\t//$(\"subject1_is_open\").replace('<span id=\"subject1_is_open\" style=\"margin-right: 50px;\">+</span>');\n\t\t\t$(\"subject1\").className = \"\";\n\t\t}else\n\t\t{\n\t\t\t//$(\"subject1_is_open\").replace('<span id=\"subject1_is_open\" style=\"margin-right: 50px;\">-</span>');\n\t\t\t$(\"subject1\").className = \"active\";\n\t\t}\t\n\t};\n\t$(\"subject2\").onclick = function(){\n\t\t$(\"content2\").toggle();\n\t\tif($(\"content2\").getStyle('display') == \"none\"){\n\t\t\t//$(\"subject2_is_open\").replace('<span id=\"subject2_is_open\" style=\"margin-right: 50px;\">+</span>');\n\t\t\t$(\"subject2\").className = \"\";\n\t\t}else\n\t\t{\n\t\t\t$(\"subject2\").className = \"active\";\n\t\t\t//$(\"subject2_is_open\").replace('<span id=\"subject2_is_open\" style=\"margin-right: 50px;\">-</span>');\n\t\t}\t\n\t};\n\t$(\"subject3\").onclick = function(){\n\t\t$(\"content3\").toggle();\n\t\tif($(\"content3\").getStyle('display') == \"none\"){\n\t\t\t$(\"subject3\").className = \"\";\n\t\t\t//$(\"subject3_is_open\").replace('<span id=\"subject3_is_open\" style=\"margin-right: 50px;\">+</span>');\n\t\t}else\n\t\t{\n\t\t\t$(\"subject3\").className = \"active\";\t\t\t\n\t\t\t//$(\"subject3_is_open\").replace('<span id=\"subject3_is_open\" style=\"margin-right: 50px;\">-</span>');\n\t\t}\t\n\t};\n\t$$(\".course_detail\").each(function(item){\n\titem.onclick = function(){\n\t\t$(\"subject_list\").hide();\n\t\t$(\"subject_detail\").show();\n\t\t};\n\t});\n\t$$(\".course_new\").each(function(item){\n\t\titem.onclick = function(){\n\t\t\t$(\"subject_list\").hide();\n\t\t\t$(\"subject_new\").show();\n\t\t\t};\n\t});\n\tload_course_new_tab();\n\tload_course_detail_tab();\n}", "function addOneSubject(sub) {\n var a = document.createElement('a');\n var li = document.createElement('li');\n var ct = document.createTextNode(sub.name);\n li.appendChild(ct);\n a.appendChild(li);\n a.setAttribute(\"href\", \"#\");\n a.setAttribute(\"id\", sub.id);\n a.setAttribute(\"onmousedown\", \"startDrag(event)\");\n\n document.getElementById(\"search_display\").appendChild(a);\n}", "function update() {\n displayed = false;\n prev_subject = curr_subject;\n curr_subject = select(\"#phrase\").value();\n loadJSON(api+curr_subject+access_token, gotData);\n}", "function toggleSublist(sub) {\n const sublist = document.getElementById('sublist');\n\n sublist.setAttribute('value', sub);\n displaySub(sublist);\n}", "function initiateSubCategories(subtopic) \n{\n\tdocument.getElementById('backBtn').removeAttribute(\"disabled\");\n\tdocument.getElementById('categoryTitle').innerHTML = subtopic;\n\tvar div = document.getElementById('categoryContainer');\n\tstrPath += \"/\" + subtopic; // Updated location string with subtopic\n\n\tclearButtons(div);\n\tsetCategories(strPath);\n}", "setupSubLinks() {\n for (let subLink in this.subLinks) {\n this.subLinks[subLink].addEventListener(\"click\", (e) => {\n let linkID = e.target.id;\n if (linkID === \"\") {\n linkID = e.target.parentNode.id;\n }\n let subViewToShow = linkID.slice(0, -5);\n this.showSubView(subViewToShow);\n });\n }\n }", "function updateNavigationLinks()\n {\n if (currentSubunitIsTheFirstSubunit()) {\n my.html.previousLink.style.visibility = 'hidden'\n my.html.nextLink.style.visibility = 'visible'\n } else if (currentSubunitIsTheLastSubunit()) {\n my.html.previousLink.style.visibility = 'visible'\n my.html.nextLink.style.visibility = 'hidden'\n } else {\n my.html.previousLink.style.visibility = 'visible'\n my.html.nextLink.style.visibility = 'visible'\n }\n }", "function Subscribe_Topic(incident){\n $currentElement = $(incident.target)\n $sub = $currentElement.closest('.subscriber');\n name = $sub.find('h5').html();\n TopicName = $sub.find('input')[0].value;\n\n\t\tsubscribers_array.forEach(function(sub, pos){\n\t\t\tif(name.toLowerCase() == sub.name.toLowerCase()){\n\t\t\t\tsub.TopicNames = sub.TopicNames || [] //There are no TopicNames array for a new subscribers array. So initialize an empty list []\n\t\t\t\tif(sub.TopicNames.indexOf(TopicName) == -1){\n\t\t\t\t\tsub.TopicNames.push(TopicName);\n\t\t\t\t\t_render()\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "function setSubheader(subheader){\r\n document.getElementById('subheader').innerText = \"Blog > Submit new blog\"\r\n}", "function updateSelection (){\n //initially all subject are active\n // on click all subject become inactive\n self.clickFlag = true;\n\n\n //1) check if subject is already active\n console.log(this.id)\n var elm = this.id\n var clickedSubjectId = self.svg.selectAll('.subject-bar')\n .filter(function (d) {\n return d.key == elm\n }).attr('id');\n if (self.activeSubjects.indexOf(clickedSubjectId) <= -1 ){\n //2) if not add it to the active array\n self.activeSubjects.push(clickedSubjectId)\n self.svg.select(clickedSubjectId)\n .attr('class', 'subject-bar active')\n } else {\n //remove from the array\n self.activeSubjects.splice(self.activeSubjects.indexOf(clickedSubjectId) , 1)\n }\n\n // make unselected bars inactive\n self.svg.selectAll('.subject-bar')\n .filter(function (d) {\n return self.activeSubjects.indexOf(d.key) <= -1\n })\n .attr('class', 'subject-bar inactive')\n\n console.log(self.activeSubjects)\n // filter domain\n self.dimension.filter(function(d){\n return self.activeSubjects.indexOf(d) > -1\n })\n\n // update all charts\n self.dispatch.call('update')\n\n}", "function updateNavigation() {\n\tif ($(document.body).hasClass('single-page')){\n\t\treturn;\n\t}\n\n\t$(\".toc .topic-link + ul\").hide();\n\n\tvar li = $(\".toc li\");\n\tvar next, prev;\n\t$.each(li, function(i, e){\n\t\tif ($(\".topic-link.active\").closest(\"li\").get(0) === this) {\n\t\t\tnext = $(li.get(i+1)).find(\".topic-link:first\");\n\t\t\tif (i>0){\n\t\t\t\tprev = $(li.get(i-1)).find(\".topic-link:first\");\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t});\n}", "function assignChapter() {\n manageSubjectService.getNotLinkedSubjectList($scope.selectedSubject).then(notLinkedSubjectSuccess, notLinkedSubjectError);\n $scope.selectedSubject.SubjectId;\n }", "function conservationCon() {\n console.log(\"Links Changed\")\n document.getElementById(\"subLinks\").innerHTML = \"\";\n document.getElementById(\"subLinks\").innerHTML = \"<h3>Conservation</h3><ul><li><a href='#'><h4>Carolinian Canada</h4></a></li><li><a href='#'><h4>Friends of the Thames / Thames River Cleanup</h4></a></li><li><a href='#'><h4>Nature London</h4></a></li><li><a href='#'><h4>North Shore Steelhead Association</h4></a></li><li><a href='#'><h4>Ontario Streams</h4></a></li><li><a href='#'><h4>Ontario Federation of Anglers and Hunters</h4></a></li><li><a href='#'><h4>Trout Unlimited Canada</h4></a></li></ul>\";\n}", "function updateSubMenu(mainId, initialSubId) {\n \n var subMenu = d3.select(\".subMenu\");\n subMenu.html(\"\");\n \n var s = 0;\n\n for (var subId in globalMetadata[mainId].charts) {\n \n subMenu.append(\"span\")\n .classed(\"subMenuItem\", true)\n .classed(initialSubId == subId ? \"subMenuItemActive subMenuItemHover\" : \"subMenuItemNormal\", true)\n .attr (\"id\" , \"chartPath_\" + mainId + \"_\" +subId)\n .text(globalMetadata[mainId].charts[subId].title)\n .on(\"mouseover\", function () { \n d3.select(\".subMenuItemHover\").classed(\"subMenuItemHover\", false);\n d3.select(this).classed(\"subMenuItemHover\", true);\n })\n .on(\"mouseout\", function () {\n d3.select(this).classed(\"subMenuItemHover\",false);\n d3.select(\".subMenuItemActive\").classed(\"subMenuItemHover\",true);\n })\n .on(\"click\", function () { \n changeChart( {\"chartPath\" : d3.select(this).attr(\"id\").replace(\"chartPath_\", \"\") }); \n });\n s++;\n }\n}", "function linkSubject(event) {\r\n event.preventDefault();\r\n\r\n console.log(event);\r\n var subId = event.target.id;\r\n var pageId = $('#pageId').text()\r\n console.log(subId);\r\n\r\n var subData = {'subject': subId };\r\n \r\n $.ajax({\r\n type: 'PUT',\r\n data: subData,\r\n url: '/pages/'+pageId+'/subject',\r\n\tdataType: 'JSON'\r\n }).done(function( response ) {\r\n if (response.msg === '') {\r\n $('span#subject').text(subId);\r\n }\r\n else {\r\n // If something goes wrong, alert the error message that our service returned\r\n alert('Error: ' + response.msg);\r\n }\r\n });\r\n \r\n}", "changeSubHeaderItem(item) {\n this.setState({subHeaderItemActive: item})\n }", "function updateCurrentStudent(position){\n $('#studentName').text(peopleArray[position].name);\n $('#studentGithub').html(\"<a href='\" + peopleArray[position].github + \"'>\"+peopleArray[position].github+\"</a>\");\n $('#studentShoutout').text(peopleArray[position].shoutout);\n}", "function edit_current_subject_id(ev) {\n var currentRow = $(ev).parents()[2];\n var subjectID = $(currentRow)[0].cells[1].innerText;\n loadSubjectInformation(ev, subjectID);\n}", "function addSubject() {\n var subjectID = $(\"#bootbox-subject-id\").val();\n addSubjectIDtoDataBase(subjectID);\n if (subjectsTableData.length !== 0) {\n $(\"#div-import-primary-folder-sub\").hide();\n }\n if (subjectsTableData.length === 2) {\n onboardingMetadata(\"subject\");\n }\n}", "function SubjectList(){\n firebase.auth().onAuthStateChanged(function(user){\n if(user){\n var uid = user.uid;\n var ref = firebase.database().ref(\"Classes/\");\n ref.orderByChild('tid').equalTo(uid).on(\"child_added\", function(snapshot) {\n ListDisp(snapshot.key,snapshot.val().subject_code,snapshot.val().subject_name);\n });\n } \n\n });\n \n}", "function refreshSelect(targetObject,newSubject){\r\n\r\n // Only refresh the subject once (at start), and only the topic if the subject isn't 0 \r\n if ($(targetObject).attr('id') == 'edit-subject' || newSubject != 0)\r\n $.each(taxonomy, function(k,v) {\r\n if ((v.parents[0] * 1) == newSubject) {\r\n targetObject.append('<option value=\"' + v.tid + '\">'+ v.name +'</option>');\r\n }\r\n });\r\n }", "subscriptions () {\r\n events.on(\"url-change\", (data) => {\r\n if (data.state && data.state.selector) {\r\n const target = document.querySelector(data.state.selector);\r\n\r\n this.toggleActivePages(target);\r\n this.toggleActiveSubnav(data.state.index);\r\n }\r\n });\r\n }", "function getSelectedSubjectDetails() {\n manageSubjectService.getSubjectListItem($scope.selectedSubject).then(selectedSubjectDetailSuccess, selectedSubjectDetailError);\n }", "function expand(event)\n{\n console.log(grade);\n console.log(sub);\n console.log(subsub);\n event.stopPropagation();\n event.stopImmediatePropagation();\n q=event.data.subsub;\n data.data.list.map(function(val)\n {\n if(val.name==grade)\n {\n val.subjectList.map(function(va){\n if(va.name==sub)\n {\n va.subSubjectList.map(function(v)\n {\n if(v.name==q)\n {\n\n if(v.chapterList.length==0)\n {\n $('#'+q).append('<p class=\"no\">No Chapters Found!</p>');\n }\n v.chapterList.map(function(c){\n console.log(c);\n $('#'+q).append('<li><a >'+c.name+'</a></li>');\n });\n }\n });\n }\n });\n }\n });\n \n}", "function setsubs(grade)\n{\n \n $('.sub').html('');\n $('.sub').append('<option value=\"no\">SUBJECTS</option>');\n data['data'].list.map(function(val)\n {\n if(val.name==grade)\n {\n \n val.subjectList.map(function(v)\n {\n var s=v.name;\n \n var add='<option value=\"'+s+'\">'+s+'</option>';\n $('.sub').append(add);\n });\n }\n });\n}", "function currentSubunit()\n {\n var m = my.current.unitNo\n var n = my.current.subunitNo\n\n window.location.href = unitHref(m, n)\n }", "function subjectRead (subjects){\n\t\t$(\"#scr2\").html(\"\");\n\t\t$(\"#main\").html(\"\");\n\t\texamsNext.html(\"\");\n\t\tif (subjects.length == 0)\n\t\t{\n\t\t\t$(\"#main\").append(\"<p class='emphasis'>No subjects yet!</p><p>Go to 'Manage Exams' to add a new subject.\");\n\t\t\texamsNext.append(\"<p class='emphasis'>No subjects yet!</p><p>Go to 'Manage Exams' to add a new subject.\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$.each(subjects,function (key,value)\n\t\t\t{\n\t\t\t\tgpaCalc(key);\n\t\t\t\t$(\"#main\").append(\"<p class='emphasis'>\"+key+\"</p><p><b>Current: </b>\"+subjects[key][\"gpa\"]+\",<b> Goal: </b>\"+subjects[key][\"goal\"]+\"</p>\");\n\t\t\t\tchartDraw(\"#scr2\",key,subjects[key][\"chartdata\"],key);\n\t\t\t\texamsNext.append(\"<p class='emphasis'>\"+key+\"</p>\")\n\t\t\t\tvar count = 0;\n\t\t\t\tfor (var a = 0;a<subjects[key][\"chartdata\"].length;a++)\n\t\t\t\t{\n\t\t\t\t\tif (subjects[key][\"chartdata\"][a][\"done\"] == false)\n\t\t\t\t\t{\n\t\t\t\t\t\texamsNext.append(\"<p><b>\"+subjects[key][\"chartdata\"][a][\"exam\"]+\"</b>, \"+subjects[key][\"chartdata\"][a][\"weight\"]+\"% of final grade\");\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (count == 0)\n\t\t\t\t{\n\t\t\t\t\texamsNext.append(\"<p><b>None</b></p>\")\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}" ]
[ "0.65367115", "0.5998079", "0.58859354", "0.58568424", "0.5854699", "0.58327657", "0.5800105", "0.5792945", "0.5792188", "0.57488364", "0.56903684", "0.5645654", "0.5645014", "0.56170017", "0.5615744", "0.55638194", "0.5516076", "0.5513796", "0.54779595", "0.5471836", "0.5463222", "0.54544985", "0.54497516", "0.5435885", "0.5411673", "0.5410134", "0.5400208", "0.5385111", "0.5378419", "0.5366447" ]
0.6626903
0
MOL2 file syntax defines the atom record as follows: atom_id atom_name x y z atom_type [subst_id [subst_name [charge [status_bit]]]] 0 1 2 3 4 5 6 7 8 9 MOL2 file syntax defines the bond record as follows: bond_id origin_atom_id target_atom_id bond_type [status_bits] 0 1 2 3 4
parseMolecule(index, atomRecords, bondRecords, result) { let {atoms, bonds} = result, inc = atoms.length, // total number of atoms added into the structure previously spaceRE = /\s+/; for (let rec of atomRecords) { let items = rec.trim().split(spaceRE); let dotPos = items[5].indexOf("."); // atom_type may look like "C.3" atoms.push({ el: (dotPos > -1) ? items[5].slice(0, dotPos) : items[5], x: +items[2], y: +items[3], z: +items[4], mol: index }); } for (let rec of bondRecords) { let items = rec.trim().split(spaceRE); let type = [...this.bondTypes].find(x => x[1] === items[3]); bonds.push({ iAtm: items[1] - 1 + inc, jAtm: items[2] - 1 + inc, type: type && type[0] || "s" }); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "parseMolecule(index, atomRecords, result) {\n let {atoms, bonds} = result,\n inc = atoms.length, // total number of atoms added into the structure previously\n spaceRE = /\\s+/;\n for (let i = 0, len = atomRecords.length; i < len; i++) {\n let items = atomRecords[i].trim().split(spaceRE);\n atoms.push({el: items[3], x: +items[7], y: +items[8], z: +items[9], mol: index});\n for (let j = 11, cn = 2 * items[10] + 11; j < cn; j += 2) {\n if (items[j] - 1 > i) {\n bonds.push({\n iAtm: i + inc,\n jAtm: items[j] - 1 + inc,\n type: items[j + 1]\n });\n }\n }\n }\n }", "function makeSciForm(mol) {\n var lines = mol.split(\"\\n\");\n var nodes = [];\n var bonds = [];\n var ncount = 0;\n var bcount = 0;\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i];\n if (i == 3) {\n ncount = line.substring(0, 3).trim() - 0;\n bcount = line.substring(4, 7).trim() - 0;\n }\n if (i > 3 && i <= ncount + 3) {\n var node = {};\n node.id = \"cdj\" + (i - 3);\n node.pos = {};\n node.pos.x = line.substring(0, 10).trim() - 0;\n node.pos.y = -1 * (line.substring(11, 20).trim() - 0);\n //node.z=line.substring(0,10).trim()-0;\n node.sym = line.substring(31, 34).trim();\n node.type = \"ring_or_chain\";\n node.nodeNumber = (i - 3);\n nodes.push(node);\n }\n if (i > ncount + 3 && i <= ncount + 3 + bcount) {\n var b1 = line.substring(0, 3).trim() - 0;\n var b2 = line.substring(3, 6).trim() - 0;\n var or = line.substring(6, 9).trim() - 0;\n var bond = {};\n bond.id = \"cdj\" + (i - 3);\n bond.fromId = \"cdj\" + b1;\n bond.toId = \"cdj\" + b2;\n if (or == 1) {\n bond.order = \"single\";\n } else if (or == 2) {\n bond.order = \"double\";\n } else if (or == 3) {\n bond.order = \"triple\";\n }\n bond.type = \"ring_or_chain\";\n bond.locked = false;\n bonds.push(bond);\n\n }\n }\n return {\n nodes: nodes,\n bonds: bonds\n };\n }", "function parseAtom(smiles, ctx) {\n var symbolInfo = readAtomSymbol(smiles);\n var atom = symbolInfo[0];\n\n if (atom === \"\") {\n return [\"error\", \"Unable to parse bracketed atom.\"];\n }\n\n var rest = symbolInfo[1]; // Atoms are indexed by a list of two-element lists. In each two-element\n // list, the first element is the atom counter, and the second element is\n // the branch counter. Branches are 1-indexed so that the main chain of\n // the molecule can be indicated by 0. Atoms may be either 0- or\n // 1-indexed, defaulting to 1, to maintain a alternating pattern of\n // odd/even indices. So, for example, if an atom has a branch off the main\n // chain, and its atom index is x, then the indices of atoms are:\n // Atom where branch occurs: [[x, 0]]\n // First atom in the branch: [[x, 1], [1, 0]] (assuming x is even)\n // Next atom in the main chain: [[x + 1, 0]]\n // increment the atom counter and reset the branch counter\n\n var newCtx = _mset(ctx, [\"idx\", ctx.idx.length - 1], [1 + ctx.idx[ctx.idx.length - 1][0], 0]);\n\n var restOfMolecule = parse$2(rest, _mset(newCtx, [\"bond\", \"bondType\"], \"single\"));\n\n if (!Array.isArray(restOfMolecule) && !!restOfMolecule) {\n //TODO(colin): fix this awkwardness.\n restOfMolecule = [restOfMolecule];\n }\n\n var atomObj = {\n type: \"atom\",\n symbol: atom,\n bonds: restOfMolecule,\n idx: newCtx.idx\n };\n\n if (ctx.bond) {\n return {\n type: \"bond\",\n bondType: ctx.bond.bondType,\n to: atomObj\n };\n }\n\n return atomObj;\n}", "function parseAtom(smiles, ctx) {\n\t var symbolInfo = readAtomSymbol(smiles, ctx);\n\t var atom = symbolInfo[0];\n\t if (atom === \"\") {\n\t return [\"error\", \"Unable to parse bracketed atom.\"];\n\t }\n\t var rest = symbolInfo[1];\n\n\t // Atoms are indexed by a list of two-element lists. In each two-element\n\t // list, the first element is the atom counter, and the second element is\n\t // the branch counter. Branches are 1-indexed so that the main chain of\n\t // the molecule can be indicated by 0. Atoms may be either 0- or\n\t // 1-indexed, defaulting to 1, to maintain a alternating pattern of\n\t // odd/even indices. So, for example, if an atom has a branch off the main\n\t // chain, and its atom index is x, then the indices of atoms are:\n\t // Atom where branch occurs: [[x, 0]]\n\t // First atom in the branch: [[x, 1], [1, 0]] (assuming x is even)\n\t // Next atom in the main chain: [[x + 1, 0]]\n\n\t // increment the atom counter and reset the branch counter\n\t var newCtx = _mset(ctx, [\"idx\", ctx.idx.length - 1], [1 + ctx.idx[ctx.idx.length - 1][0], 0]);\n\t var restOfMolecule = parse(rest, _mset(newCtx, [\"bond\", \"bondType\"], \"single\"));\n\t if (!Array.isArray(restOfMolecule) && !!restOfMolecule) {\n\t //TODO(colin): fix this awkwardness.\n\t restOfMolecule = [restOfMolecule];\n\t }\n\t var atomObj = {\n\t type: \"atom\",\n\t symbol: atom,\n\t bonds: restOfMolecule,\n\t idx: newCtx.idx\n\t };\n\t if (ctx.bond) {\n\t return {\n\t type: \"bond\",\n\t bondType: ctx.bond.bondType,\n\t to: atomObj\n\t };\n\t }\n\t return atomObj;\n\t}", "loadPDB(src, pdbid, bOpm, bVector, bMutation, bAppend) {\n let ic = this.icn3d,\n me = ic.icn3dui\n let helices = [],\n sheets = []\n //ic.atoms = {}\n let lines = src.split('\\n')\n\n let chainsTmp = {} // serial -> atom\n let residuesTmp = {} // serial -> atom\n\n let serial, moleculeNum\n if (!bMutation && !bAppend) {\n ic.init()\n moleculeNum = 1\n serial = 0\n } else {\n // remove the last structure\n if (ic.alertAlt) {\n let nStru = ic.oriNStru + 1 //Object.keys(ic.structures).length;\n let chainArray = ic.structures[nStru - 1]\n for (let i = 0, il = chainArray ? chainArray.length : 0; i < il; ++i) {\n for (let j in ic.chains[chainArray[i]]) {\n delete ic.atoms[j]\n delete ic.hAtoms[j]\n delete ic.dAtoms[j]\n }\n delete ic.chains[chainArray[i]]\n }\n\n delete ic.structures[nStru - 1]\n } else {\n ic.oriNStru = Object.keys(ic.structures).length\n }\n\n moleculeNum = ic.oriNStru + 1 //Object.keys(ic.structures).length + 1;\n // Concatenation of two pdbs will have several atoms for the same serial\n serial = Object.keys(ic.atoms).length\n }\n\n let sheetArray = [],\n sheetStart = [],\n sheetEnd = [],\n helixArray = [],\n helixStart = [],\n helixEnd = []\n\n let chainNum, residueNum, oriResidueNum\n let prevChainNum = '',\n prevResidueNum = '',\n prevOriResidueNum = '',\n prevResi = 0\n let prevRecord = ''\n let bModifyResi = false\n\n let oriSerial2NewSerial = {}\n\n let chainMissingResidueArray = {}\n\n let id = 'stru'\n\n let maxMissingResi = 0,\n prevMissingChain = ''\n let CSerial, prevCSerial, OSerial, prevOSerial\n\n for (let i in lines) {\n let line = lines[i]\n let record = line.substr(0, 6)\n\n if (record === 'HEADER') {\n // if(bOpm === undefined || !bOpm) ic.bSecondaryStructure = true;\n\n id = line.substr(62, 4).trim()\n if (id == '') {\n id = ic.inputid.indexOf('/') == -1 ? ic.inputid.substr(0, 10) : 'stru' //ic.filename.substr(0, 4);\n }\n\n ic.molTitle = ''\n } else if (record === 'TITLE ') {\n let name = line.substr(10)\n ic.molTitle += name.trim() + ' '\n } else if (record === 'HELIX ') {\n ic.bSecondaryStructure = true\n\n let startChain = line.substr(19, 1) == ' ' ? 'A' : line.substr(19, 1)\n let startResi = parseInt(line.substr(21, 4))\n let endResi = parseInt(line.substr(33, 4))\n\n let chain_resi\n for (let j = startResi; j <= endResi; ++j) {\n chain_resi = startChain + '_' + j\n helixArray.push(chain_resi)\n\n if (j === startResi) helixStart.push(chain_resi)\n if (j === endResi) helixEnd.push(chain_resi)\n }\n\n helices.push({\n chain: startChain,\n initialResidue: startResi,\n initialInscode: line.substr(25, 1),\n terminalResidue: endResi,\n terminalInscode: line.substr(37, 1),\n })\n } else if (record === 'SHEET ') {\n //ic.bSecondaryStructure = true;\n if (bOpm === undefined || !bOpm) ic.bSecondaryStructure = true\n\n let startChain = line.substr(21, 1) == ' ' ? 'A' : line.substr(21, 1)\n let startResi = parseInt(line.substr(22, 4))\n let endResi = parseInt(line.substr(33, 4))\n\n for (let j = startResi; j <= endResi; ++j) {\n let chain_resi = startChain + '_' + j\n sheetArray.push(chain_resi)\n\n if (j === startResi) sheetStart.push(chain_resi)\n if (j === endResi) sheetEnd.push(chain_resi)\n }\n\n sheets.push({\n chain: startChain,\n initialResidue: startResi,\n initialInscode: line.substr(26, 1),\n terminalResidue: endResi,\n terminalInscode: line.substr(37, 1),\n })\n } else if (record === 'HBOND ') {\n if (bOpm === undefined || !bOpm) ic.bSecondaryStructure = true\n /*\n //HBOND A 1536 N2 A 59 ND2 -19.130 83.151 52.266 -18.079 81.613 49.427 3.40\n bCalculateHbond = false;\n\n let chemicalChain = line.substr(6, 1);\n let chemicalResi = line.substr(8, 4).trim();\n let chemicalAtom = line.substr(14, 4).trim();\n let proteinChain = line.substr(18, 1);\n let proteinResi = line.substr(20, 4).trim();\n let proteinAtom = line.substr(25, 4).trim();\n\n let chemical_x = parseFloat(line.substr(30, 8));\n let chemical_y = parseFloat(line.substr(38, 8));\n let chemical_z = parseFloat(line.substr(46, 8));\n let protein_x = parseFloat(line.substr(54, 8));\n let protein_y = parseFloat(line.substr(62, 8));\n let protein_z = parseFloat(line.substr(70, 8));\n\n let dist = line.substr(78, 8).trim();\n\n ic.hbondpnts.push(new THREE.Vector3(chemical_x, chemical_y, chemical_z));\n ic.hbondpnts.push(new THREE.Vector3(protein_x, protein_y, protein_z));\n */\n } else if (record === 'SSBOND') {\n ic.bSsbondProvided = true\n //SSBOND 1 CYS E 48 CYS E 51 2555\n let chain1 = line.substr(15, 1) == ' ' ? 'A' : line.substr(15, 1)\n let resi1 = line.substr(17, 4).trim()\n let resid1 = id + '_' + chain1 + '_' + resi1\n\n let chain2 = line.substr(29, 1) == ' ' ? 'A' : line.substr(29, 1)\n let resi2 = line.substr(31, 4).trim()\n let resid2 = id + '_' + chain2 + '_' + resi2\n\n if (ic.ssbondpnts[id] === undefined) ic.ssbondpnts[id] = []\n\n ic.ssbondpnts[id].push(resid1)\n ic.ssbondpnts[id].push(resid2)\n } else if (record === 'REMARK') {\n let type = parseInt(line.substr(7, 3))\n\n if (line.indexOf('1/2 of bilayer thickness:') !== -1) {\n // OPM transmembrane protein\n ic.halfBilayerSize = parseFloat(line.substr(line.indexOf(':') + 1).trim())\n } else if (type == 350 && line.substr(13, 5) == 'BIOMT') {\n let n = parseInt(line[18]) - 1\n //var m = parseInt(line.substr(21, 2));\n let m = parseInt(line.substr(21, 2)) - 1 // start from 1\n if (ic.biomtMatrices[m] == undefined) ic.biomtMatrices[m] = new THREE.Matrix4().identity()\n ic.biomtMatrices[m].elements[n] = parseFloat(line.substr(24, 9))\n ic.biomtMatrices[m].elements[n + 4] = parseFloat(line.substr(34, 9))\n ic.biomtMatrices[m].elements[n + 8] = parseFloat(line.substr(44, 9))\n ic.biomtMatrices[m].elements[n + 12] = parseFloat(line.substr(54, 10))\n }\n // missing residues\n else if (\n type == 465 &&\n line.substr(18, 1) == ' ' &&\n line.substr(20, 1) == ' ' &&\n line.substr(21, 1) != 'S'\n ) {\n let resn = line.substr(15, 3)\n let chain = line.substr(19, 1)\n let resi = parseInt(line.substr(21, 5))\n\n //var structure = parseInt(line.substr(13, 1));\n //if(line.substr(13, 1) == ' ') structure = 1;\n\n //var chainNum = structure + '_' + chain;\n let chainNum = id + '_' + chain\n\n if (chainMissingResidueArray[chainNum] === undefined) chainMissingResidueArray[chainNum] = []\n let resObject = {}\n resObject.resi = resi\n resObject.name = me.utilsCls.residueName2Abbr(resn).toLowerCase()\n\n if (chain != prevMissingChain) {\n maxMissingResi = 0\n }\n\n // not all listed residues are considered missing, e.g., PDB ID 4OR2, only the firts four residues are considered missing\n if (\n !isNaN(resi) &&\n (prevMissingChain == '' ||\n chain != prevMissingChain ||\n (chain == prevMissingChain && resi > maxMissingResi))\n ) {\n chainMissingResidueArray[chainNum].push(resObject)\n\n maxMissingResi = resi\n prevMissingChain = chain\n }\n } else if (type == 900 && ic.emd === undefined && line.substr(34).trim() == 'RELATED DB: EMDB') {\n //REMARK 900 RELATED ID: EMD-3906 RELATED DB: EMDB\n ic.emd = line.substr(23, 11).trim()\n }\n } else if (\n record === 'SOURCE' &&\n ic.organism === undefined &&\n line.substr(11, 15).trim() == 'ORGANISM_COMMON'\n ) {\n ic.organism = line.substr(28).toLowerCase().trim()\n\n ic.organism = ic.organism.substr(0, ic.organism.length - 1)\n } else if (record === 'ENDMDL') {\n ++moleculeNum\n id = 'stru'\n } else if (record === 'JRNL ') {\n if (line.substr(12, 4) === 'PMID') {\n ic.pmid = line.substr(19).trim()\n }\n } else if (record === 'ATOM ' || record === 'HETATM') {\n //if(id == 'stru' && bOpm) {\n // id = pdbid;\n //}\n\n let structure = id\n if (id == 'stru' || bMutation || bAppend) {\n // bMutation: side chain prediction\n structure = moleculeNum === 1 ? id : id + moleculeNum.toString()\n }\n\n let alt = line.substr(16, 1)\n //if (alt !== \" \" && alt !== \"A\") continue;\n\n // \"CA\" has to appear before \"O\". Otherwise the cartoon of secondary structure will have breaks\n // Concatenation of two pdbs will have several atoms for the same serial\n ++serial\n\n let serial2 = parseInt(line.substr(6, 5))\n oriSerial2NewSerial[serial2] = serial\n\n let elem = line.substr(76, 2).trim()\n if (elem === '') {\n // for some incorrect PDB files, important to use substr(12,2), not (12,4)\n elem = line.substr(12, 2).trim()\n }\n let atom = line.substr(12, 4).trim()\n let resn = line.substr(17, 3)\n\n let chain = line.substr(21, 1)\n if (chain === ' ') chain = 'A'\n\n //var oriResi = line.substr(22, 4).trim();\n let oriResi = line.substr(22, 5).trim()\n\n let resi = oriResi //parseInt(oriResi);\n if (oriResi != resi || bModifyResi) {\n // e.g., 99A and 99\n bModifyResi = true\n //resi = (prevResi == 0) ? resi : prevResi + 1;\n }\n\n if (bOpm && resn === 'DUM') {\n elem = atom\n chain = 'MEM'\n resi = 1\n oriResi = 1\n }\n\n if (bVector && resn === 'DUM') break // just need to get the vector of the largest chain\n\n chainNum = structure + '_' + chain\n oriResidueNum = chainNum + '_' + oriResi\n if (chainNum !== prevChainNum) {\n prevResi = 0\n bModifyResi = false\n }\n\n residueNum = chainNum + '_' + resi\n\n let chain_resi = chain + '_' + resi\n\n let x = parseFloat(line.substr(30, 8))\n let y = parseFloat(line.substr(38, 8))\n let z = parseFloat(line.substr(46, 8))\n let coord = new THREE.Vector3(x, y, z)\n\n let atomDetails = {\n het: record[0] === 'H', // optional, used to determine chemicals, water, ions, etc\n serial: serial, // required, unique atom id\n name: atom, // required, atom name\n alt: alt, // optional, some alternative coordinates\n resn: resn, // optional, used to determine protein or nucleotide\n structure: structure, // optional, used to identify structure\n chain: chain, // optional, used to identify chain\n resi: resi, // optional, used to identify residue ID\n //insc: line.substr(26, 1),\n coord: coord, // required, used to draw 3D shape\n b: parseFloat(line.substr(60, 8)), // optional, used to draw B-factor tube\n elem: elem, // optional, used to determine hydrogen bond\n bonds: [], // required, used to connect atoms\n ss: 'coil', // optional, used to show secondary structures\n ssbegin: false, // optional, used to show the beginning of secondary structures\n ssend: false, // optional, used to show the end of secondary structures\n }\n\n if (!atomDetails.het && atomDetails.name === 'C') {\n CSerial = serial\n }\n if (!atomDetails.het && atomDetails.name === 'O') {\n OSerial = serial\n }\n\n // from DSSP C++ code\n if (\n !atomDetails.het &&\n atomDetails.name === 'N' &&\n prevCSerial !== undefined &&\n prevOSerial !== undefined\n ) {\n let dist = ic.atoms[prevCSerial].coord.distanceTo(ic.atoms[prevOSerial].coord)\n\n let x2 =\n atomDetails.coord.x + (ic.atoms[prevCSerial].coord.x - ic.atoms[prevOSerial].coord.x) / dist\n let y2 =\n atomDetails.coord.y + (ic.atoms[prevCSerial].coord.y - ic.atoms[prevOSerial].coord.y) / dist\n let z2 =\n atomDetails.coord.z + (ic.atoms[prevCSerial].coord.z - ic.atoms[prevOSerial].coord.z) / dist\n\n atomDetails.hcoord = new THREE.Vector3(x2, y2, z2)\n }\n\n ic.atoms[serial] = atomDetails\n\n ic.dAtoms[serial] = 1\n ic.hAtoms[serial] = 1\n\n // Assign secondary structures from the input\n // if a residue is assigned both sheet and helix, it is assigned as sheet\n if ($.inArray(chain_resi, sheetArray) !== -1) {\n ic.atoms[serial].ss = 'sheet'\n\n if ($.inArray(chain_resi, sheetStart) !== -1) {\n ic.atoms[serial].ssbegin = true\n }\n\n // do not use else if. Some residues are both start and end of secondary structure\n if ($.inArray(chain_resi, sheetEnd) !== -1) {\n ic.atoms[serial].ssend = true\n }\n } else if ($.inArray(chain_resi, helixArray) !== -1) {\n ic.atoms[serial].ss = 'helix'\n\n if ($.inArray(chain_resi, helixStart) !== -1) {\n ic.atoms[serial].ssbegin = true\n }\n\n // do not use else if. Some residues are both start and end of secondary structure\n if ($.inArray(chain_resi, helixEnd) !== -1) {\n ic.atoms[serial].ssend = true\n }\n }\n\n let secondaries = '-'\n if (ic.atoms[serial].ss === 'helix') {\n secondaries = 'H'\n } else if (ic.atoms[serial].ss === 'sheet') {\n secondaries = 'E'\n }\n //else if(ic.atoms[serial].ss === 'coil') {\n // secondaries = 'c';\n //}\n else if (\n !ic.atoms[serial].het &&\n me.parasCls.residueColors.hasOwnProperty(ic.atoms[serial].resn.toUpperCase())\n ) {\n secondaries = 'c'\n } else {\n secondaries = 'o'\n }\n\n ic.secondaries[residueNum] = secondaries\n\n // different residue\n //if(residueNum !== prevResidueNum) {\n if (oriResidueNum !== prevOriResidueNum) {\n let residue = me.utilsCls.residueName2Abbr(resn)\n\n ic.residueId2Name[residueNum] = residue\n\n if (serial !== 1 && prevResidueNum !== '') ic.residues[prevResidueNum] = residuesTmp\n\n if (residueNum !== prevResidueNum) {\n residuesTmp = {}\n }\n\n // different chain\n if (chainNum !== prevChainNum) {\n prevCSerial = undefined\n prevOSerial = undefined\n\n // a chain could be separated in two sections\n if (serial !== 1 && prevChainNum !== '') {\n if (ic.chains[prevChainNum] === undefined) ic.chains[prevChainNum] = {}\n ic.chains[prevChainNum] = me.hashUtilsCls.unionHash(ic.chains[prevChainNum], chainsTmp)\n }\n\n chainsTmp = {}\n\n if (ic.structures[structure.toString()] === undefined) ic.structures[structure.toString()] = []\n ic.structures[structure.toString()].push(chainNum)\n\n if (ic.chainsSeq[chainNum] === undefined) ic.chainsSeq[chainNum] = []\n\n let resObject = {}\n resObject.resi = resi\n resObject.name = residue\n\n ic.chainsSeq[chainNum].push(resObject)\n } else {\n prevCSerial = CSerial\n prevOSerial = OSerial\n\n let resObject = {}\n resObject.resi = resi\n resObject.name = residue\n\n ic.chainsSeq[chainNum].push(resObject)\n }\n }\n\n chainsTmp[serial] = 1\n residuesTmp[serial] = 1\n\n prevRecord = record\n\n prevChainNum = chainNum\n prevResidueNum = residueNum\n prevOriResidueNum = oriResidueNum\n } else if (record === 'CONECT') {\n let from = parseInt(line.substr(6, 5))\n for (let j = 0; j < 4; ++j) {\n let to = parseInt(line.substr([11, 16, 21, 26][j], 5))\n if (isNaN(to)) continue\n\n if (ic.atoms[oriSerial2NewSerial[from]] !== undefined)\n ic.atoms[oriSerial2NewSerial[from]].bonds.push(oriSerial2NewSerial[to])\n }\n } else if (record.substr(0, 3) === 'TER') {\n // Concatenation of two pdbs will have several atoms for the same serial\n ++serial\n }\n }\n\n // add the last residue set\n ic.residues[residueNum] = residuesTmp\n if (ic.chains[chainNum] === undefined) ic.chains[chainNum] = {}\n ic.chains[chainNum] = me.hashUtilsCls.unionHash2Atoms(ic.chains[chainNum], chainsTmp, ic.atoms)\n\n if (!bMutation) this.adjustSeq(chainMissingResidueArray)\n\n // ic.missingResidues = [];\n // for(let chainid in chainMissingResidueArray) {\n // let resArray = chainMissingResidueArray[chainid];\n // for(let i = 0; i < resArray.length; ++i) {\n // ic.missingResidues.push(chainid + '_' + resArray[i].resi);\n // }\n // }\n\n // copy disulfide bonds\n let structureArray = Object.keys(ic.structures)\n for (let s = 0, sl = structureArray.length; s < sl; ++s) {\n let structure = structureArray[s]\n\n if (structure == id) continue\n\n if (ic.ssbondpnts[structure] === undefined) ic.ssbondpnts[structure] = []\n\n if (ic.ssbondpnts[id] !== undefined) {\n for (let j = 0, jl = ic.ssbondpnts[id].length; j < jl; ++j) {\n let ori_resid = ic.ssbondpnts[id][j]\n let pos = ori_resid.indexOf('_')\n let resid = structure + ori_resid.substr(pos)\n\n ic.ssbondpnts[structure].push(resid)\n }\n }\n }\n\n // calculate disulfide bonds for PDB files\n if (!ic.bSsbondProvided) {\n // get all Cys residues\n let structure2cys_resid = {}\n for (let chainid in ic.chainsSeq) {\n let seq = ic.chainsSeq[chainid]\n let structure = chainid.substr(0, chainid.indexOf('_'))\n\n for (let i = 0, il = seq.length; i < il; ++i) {\n // each seq[i] = {\"resi\": 1, \"name\":\"C\"}\n if (seq[i].name == 'C') {\n if (structure2cys_resid[structure] == undefined) structure2cys_resid[structure] = []\n structure2cys_resid[structure].push(chainid + '_' + seq[i].resi)\n }\n }\n }\n\n this.setSsbond(structure2cys_resid)\n }\n\n // remove the reference\n lines = null\n\n let curChain,\n curResi,\n curInsc,\n curResAtoms = []\n // refresh for atoms in each residue\n let refreshBonds = function (f) {\n let n = curResAtoms.length\n for (let j = 0; j < n; ++j) {\n let atom0 = curResAtoms[j]\n for (let k = j + 1; k < n; ++k) {\n let atom1 = curResAtoms[k]\n if (atom0.alt === atom1.alt && me.utilsCls.hasCovalentBond(atom0, atom1)) {\n //if (me.utilsCls.hasCovalentBond(atom0, atom1)) {\n atom0.bonds.push(atom1.serial)\n atom1.bonds.push(atom0.serial)\n }\n }\n f && f(atom0)\n }\n }\n let pmin = new THREE.Vector3(9999, 9999, 9999)\n let pmax = new THREE.Vector3(-9999, -9999, -9999)\n let psum = new THREE.Vector3()\n let cnt = 0\n\n // lipids may be considered as protein if \"ATOM\" instead of \"HETATM\" was used\n let lipidResidHash = {}\n\n // assign atoms\n for (let i in ic.atoms) {\n let atom = ic.atoms[i]\n let coord = atom.coord\n psum.add(coord)\n pmin.min(coord)\n pmax.max(coord)\n ++cnt\n\n if (!atom.het) {\n if ($.inArray(atom.resn, me.parasCls.nucleotidesArray) !== -1) {\n ic.nucleotides[atom.serial] = 1\n //if (atom.name === 'P') {\n if (atom.name === \"O3'\" || atom.name === 'O3*') {\n ic.nucleotidesO3[atom.serial] = 1\n\n ic.secondaries[atom.structure + '_' + atom.chain + '_' + atom.resi] = 'o' // nucleotide\n }\n } else {\n if (atom.elem === 'P') {\n lipidResidHash[atom.structure + '_' + atom.chain + '_' + atom.resi] = 1\n }\n\n ic.proteins[atom.serial] = 1\n if (atom.name === 'CA') ic.calphas[atom.serial] = 1\n if (atom.name !== 'N' && atom.name !== 'CA' && atom.name !== 'C' && atom.name !== 'O')\n ic.sidec[atom.serial] = 1\n }\n } else if (atom.het) {\n if (atom.resn === 'HOH' || atom.resn === 'WAT' || atom.resn === 'SOL') {\n ic.water[atom.serial] = 1\n }\n //else if(bOpm && atom.resn === 'DUM') {\n // ic.mem[atom.serial] = 1;\n //}\n else if ($.inArray(atom.resn, me.parasCls.ionsArray) !== -1 || atom.elem.trim() === atom.resn.trim()) {\n ic.ions[atom.serial] = 1\n } else {\n ic.chemicals[atom.serial] = 1\n }\n\n atom.color = me.parasCls.atomColors[atom.elem]\n }\n\n if (!(curChain === atom.chain && curResi === atom.resi)) {\n // a new residue, add the residue-residue bond beides the regular bonds\n refreshBonds(function (atom0) {\n if (\n ((atom0.name === 'C' && atom.name === 'N') || (atom0.name === \"O3'\" && atom.name === 'P')) &&\n me.utilsCls.hasCovalentBond(atom0, atom)\n ) {\n atom0.bonds.push(atom.serial)\n atom.bonds.push(atom0.serial)\n }\n })\n curChain = atom.chain\n curResi = atom.resi\n //curInsc = atom.insc;\n curResAtoms.length = 0\n }\n curResAtoms.push(atom)\n } // end of for\n\n // reset lipid\n for (resid in lipidResidHash) {\n let atomHash = ic.residues[resid]\n for (serial in atomHash) {\n let atom = ic.atoms[serial]\n\n atom.het = true\n ic.chemicals[atom.serial] = 1\n ic.secondaries[resid] = 'o' // nucleotide\n\n delete ic.proteins[atom.serial]\n if (atom.name === 'CA') delete ic.calphas[atom.serial]\n if (atom.name !== 'N' && atom.name !== 'CA' && atom.name !== 'C' && atom.name !== 'O')\n delete ic.sidec[atom.serial]\n }\n }\n\n // last residue\n refreshBonds()\n\n ic.pmin = pmin\n ic.pmax = pmax\n\n ic.cnt = cnt\n\n //ic.maxD = ic.pmax.distanceTo(ic.pmin);\n //ic.center = psum.multiplyScalar(1.0 / ic.cnt);\n ic.center = ic.ParserUtilsCls.getGeoCenter(ic.pmin, ic.pmax)\n\n ic.maxD = ic.ParserUtilsCls.getStructureSize(ic.atoms, ic.pmin, ic.pmax, ic.center)\n\n if (ic.maxD < 5) ic.maxD = 5\n\n ic.oriMaxD = ic.maxD\n ic.oriCenter = ic.center.clone()\n\n if (bVector) {\n // just need to get the vector of the largest chain\n return this.getChainCalpha(ic.chains, ic.atoms)\n }\n }", "function toAtom() {\n const list1 = cson.load('./db-raw.cson')\n // console.log(list1)\n const rs1 = {}\n list1.forEach(({ scopeList, snippetList }) => {\n scopeList.forEach(({ atomScope, vscodeScope }) => {\n snippetList.forEach(({ name, trigger, content, desc }) => {\n rs1[atomScope] = rs1[atomScope] || {}\n rs1[atomScope][name] = {\n prefix: trigger,\n body: content,\n }\n })\n })\n })\n const rs2 = cson.createCSONString(rs1, {\n indent: ' ',\n })\n // fs.writeFileSync('./out-db-raw-to-atom.cson', rs2)\n const out_path = '/Users/hisland/.atom/snippets.cson'\n fs.writeFileSync(out_path, rs2)\n console.log('write to: ', out_path)\n}", "function convertToMolfile2(jsmeInstance, molecularRepresentation) {\r\n\t\t\tif (molecularRepresentation\r\n\t\t\t\t\t&& molecularRepresentation.indexOf(\"M END\") == -1\r\n\t\t\t\t\t&& molecularRepresentation.slice(0, 4) != \"$RXN\") {\r\n\t\t\t\t$.ajax({\r\n\t\t\t\t\turl : \"http://cactus.nci.nih.gov/chemical/structure\",\r\n\t\t\t\t\tcrossDomain : true,\r\n\t\t\t\t\tdata : {\r\n\t\t\t\t\t\t\"string\" : molecularRepresentation,\r\n\t\t\t\t\t\t\"representation\" : \"sdf\"\r\n\t\t\t\t\t},\r\n\t\t\t\t\tsuccess : function(data) {\r\n\t\t\t\t\t\tjsmeInstance.readMolFile(data);\r\n\t\t\t\t\t},\r\n\t\t\t\t\terror : function(jqXHR, textStatus, errorThrown) {\r\n\t\t\t\t\t\talert(\"Ajax error: \" + textStatus);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\r\n\t\t\t} else {\r\n\t\t\t\tjsmeInstance.readMolFile(molecularRepresentation);\r\n\t\t\t}\r\n\r\n\t\t}", "function create_bond(atom1, atom2, bo, id) {\n\t// Calculate the angle of the bond based on the two atoms\n\tvar angle_rad = Math.atan( (atom1.rel_top-atom2.rel_top)/(atom1.rel_left-atom2.rel_left) );\n\tvar angle = angle_rad * 180 / Math.PI;\n\t// angle is between -90 and 90\n\n\t// Create new bond\n\tif (id || id == 0) {\n\t\tvar b = new Bond(atom1, atom2, bo, angle, id);\n\t} else {\n\t\tvar b = new Bond(atom1, atom2, bo, angle);\n\t}\n\n\n\t// Add to bonds array\n\tif (id || id == 0) {\n\t\tbonds[id] = b;\n\t} else {\n\t\tbonds.push(b);\n\t}\n\n\t// Update the bonds list for both atoms.\n\tatom1.bonds.push(b);\n\tatom2.bonds.push(b);\n\tatom1.n_bonds += bo;\n\tatom2.n_bonds += bo;\n\n\t// Update the neighbors list for both atoms.\n\tatom1.neighbors.push(atom2);\n\tatom2.neighbors.push(atom1);\n\n\t// Update the bond_dirs for both atoms.\n\tif (angle >= -22.5 && angle < 22.5) {\n\t\t// left-right\n\t\tif (atom1.rel_left < atom2.rel_left) {\n\t\t\tconsole.assert(atom1.bond_dirs[\"right\"].length==0, \"Cannot bond, right direction occupied.\", atom1);\n\t\t\tatom1.bond_dirs[\"right\"].push(atom2);\n\t\t\tconsole.assert(atom2.bond_dirs[\"left\"].length==0, \"Cannot bond, left direction occupied.\", atom2);\n\t\t\tatom2.bond_dirs[\"left\"].push(atom1);\n\t\t} else {\n\t\t\tconsole.assert(atom1.bond_dirs[\"left\"].length==0, \"Cannot bond, left direction occupied.\", atom1);\n\t\t\tatom1.bond_dirs[\"left\"].push(atom2);\n\t\t\tconsole.assert(atom2.bond_dirs[\"right\"].length==0, \"Cannot bond, right direction occupied.\", atom2);\n\t\t\tatom2.bond_dirs[\"right\"].push(atom1);\n\t\t}\n\t} else if (angle >= 22.5 && angle < 67.5) {\n\t\t// top left-bottom right\n\t\tif (atom1.rel_left < atom2.rel_left) {\n\t\t\tconsole.assert(atom1.bond_dirs[\"bottom-right\"].length==0, \"Cannot bond, bottom-right direction occupied.\", atom1);\n\t\t\tatom1.bond_dirs[\"bottom-right\"].push(atom2);\n\t\t\tconsole.assert(atom2.bond_dirs[\"top-left\"].length==0, \"Cannot bond, top-left direction occupied.\", atom2);\n\t\t\tatom2.bond_dirs[\"top-left\"].push(atom1);\n\t\t} else {\n\t\t\tconsole.assert(atom1.bond_dirs[\"top-left\"].length==0, \"Cannot bond, top-left direction occupied.\", atom1);\n\t\t\tatom1.bond_dirs[\"top-left\"].push(atom2);\n\t\t\tconsole.assert(atom2.bond_dirs[\"bottom-right\"].length==0, \"Cannot bond, bottom-right direction occupied.\", atom2);\n\t\t\tatom2.bond_dirs[\"bottom-right\"].push(atom1);\n\t\t}\n\t} else if (angle >= 67.5 && angle <= 90 || angle >= -90 && angle < -67.5) {\n\t\t// top-bottom\n\t\tif (atom1.rel_top < atom2.rel_top) {\n\t\t\tconsole.assert(atom1.bond_dirs[\"bottom\"].length==0, \"Cannot bond, bottom direction occupied.\", atom1);\n\t\t\tatom1.bond_dirs[\"bottom\"].push(atom2);\n\t\t\tconsole.assert(atom2.bond_dirs[\"top\"].length==0, \"Cannot bond, top direction occupied.\", atom2);\n\t\t\tatom2.bond_dirs[\"top\"].push(atom1);\n\t\t} else {\n\t\t\tconsole.assert(atom1.bond_dirs[\"top\"].length==0, \"Cannot bond, top direction occupied.\", atom1);\n\t\t\tatom1.bond_dirs[\"top\"].push(atom2);\n\t\t\tconsole.assert(atom2.bond_dirs[\"bottom\"].length==0, \"Cannot bond, bottom direction occupied.\", atom2);\n\t\t\tatom2.bond_dirs[\"bottom\"].push(atom1);\n\t\t}\n\t} else if (angle >= -67.5 && angle < -22.5) {\n\t\t// top right-bottom left\n\t\tif (atom1.rel_left < atom2.rel_left) {\n\t\t\tconsole.assert(atom1.bond_dirs[\"top-right\"].length==0, \"Cannot bond, top-right direction occupied.\", atom1);\n\t\t\tatom1.bond_dirs[\"top-right\"].push(atom2);\n\t\t\tconsole.assert(atom2.bond_dirs[\"bottom-left\"].length==0, \"Cannot bond, bottom-left direction occupied.\", atom2);\n\t\t\tatom2.bond_dirs[\"bottom-left\"].push(atom1);\n\t\t} else {\n\t\t\tconsole.assert(atom1.bond_dirs[\"bottom-left\"].length==0, \"Cannot bond, bottom-left direction occupied.\", atom1);\n\t\t\tatom1.bond_dirs[\"bottom-left\"].push(atom2);\n\t\t\tconsole.assert(atom2.bond_dirs[\"top-right\"].length==0, \"Cannot bond, top-right direction occupied.\", atom2);\n\t\t\tatom2.bond_dirs[\"top-right\"].push(atom1);\n\t\t}\n\t}\n\n\n\treturn b;\n}", "function parseBondModifier(smiles, ctx) {\n var firstChar = smiles[0];\n var rest = smiles.slice(1);\n\n if (firstChar === \"=\") {\n return parse$2(rest, _mset(ctx, [\"bond\", \"bondType\"], \"double\"));\n } else if (firstChar === \"#\") {\n return parse$2(rest, _mset(ctx, [\"bond\", \"bondType\"], \"triple\"));\n }\n\n throw new ParseError$1(\"Invalid character: \" + firstChar);\n}", "function parseBondModifier(smiles, ctx) {\n\t var firstChar = smiles[0];\n\t var rest = smiles.slice(1);\n\t if (firstChar === \"=\") {\n\t return parse(rest, _mset(ctx, [\"bond\", \"bondType\"], \"double\"));\n\t } else if (firstChar === \"#\") {\n\t return parse(rest, _mset(ctx, [\"bond\", \"bondType\"], \"triple\"));\n\t }\n\t throw new ParseError(\"Invalid character: \" + firstChar);\n\t}", "function importMolGen(str,separator) {\n var lines = str.split(separator);\n var edges = {};\n\n for (var i=0; i<lines.length; i++) {\n var line = lines[i].trim().split(\" \");\n\n if (line[0] == '') continue;\n \n var valence = nodeValence[line[0]];\n if (!valence) { var ii=i+1;\n showImportError(\"line \" + ii + \": Unrecognized node type \" + line[0]);\n return;\n }\n if (line.length-1 < valence.length) { var ii=i+1;\n showImportError(\"line \" + ii + \": \" + line[0] + \" has \" + line.length-1 + \"edges, expected \" + valence.length);\n }\n \n var newNode = addNodeAndEdges(line[0]);\n \n for (var k=1; k<newNode.length; k++) {\n if (edges['e'+line[k]]) addLink(edges['e'+line[k]], newNode[k], 2);\n else edges['e'+line[k]] = newNode[k];\n }\n }\n update();\n}", "function parse(buffer) {\n var headerSize = 1024, headerView = new DataView(buffer, 0, headerSize), warnings = [];\n var endian = false;\n var mode = headerView.getInt32(3 * 4, false);\n if (mode !== 2) {\n endian = true;\n mode = headerView.getInt32(3 * 4, true);\n if (mode !== 2) {\n return Formats.ParserResult.error(\"Only CCP4 mode 2 is supported.\");\n }\n }\n var readInt = function (o) { return headerView.getInt32(o * 4, endian); }, readFloat = function (o) { return headerView.getFloat32(o * 4, endian); };\n var header = {\n extent: getArray(readInt, 0, 3),\n mode: mode,\n nxyzStart: getArray(readInt, 4, 3),\n grid: getArray(readInt, 7, 3),\n cellSize: getArray(readFloat, 10, 3),\n cellAngles: getArray(readFloat, 13, 3),\n crs2xyz: getArray(readInt, 16, 3),\n min: readFloat(19),\n max: readFloat(20),\n mean: readFloat(21),\n spacegroupNumber: readInt(22),\n symBytes: readInt(23),\n skewFlag: readInt(24),\n skewMatrix: getArray(readFloat, 25, 9),\n skewTranslation: getArray(readFloat, 34, 3),\n origin2k: getArray(readFloat, 49, 3)\n };\n var dataOffset = buffer.byteLength - 4 * header.extent[0] * header.extent[1] * header.extent[2];\n if (dataOffset !== headerSize + header.symBytes) {\n if (dataOffset === headerSize) {\n warnings.push(\"File contains bogus symmetry record.\");\n }\n else if (dataOffset < headerSize) {\n return Formats.ParserResult.error(\"File appears truncated and doesn't match header.\");\n }\n else if ((dataOffset > headerSize) && (dataOffset < (1024 * 1024))) {\n // Fix for loading SPIDER files which are larger than usual\n // In this specific case, we must absolutely trust the symBytes record\n dataOffset = headerSize + header.symBytes;\n warnings.push(\"File is larger than expected and doesn't match header. Continuing file load, good luck!\");\n }\n else {\n return Formats.ParserResult.error(\"File is MUCH larger than expected and doesn't match header.\");\n }\n }\n //const mapp = readInt(52);\n //const mapStr = String.fromCharCode((mapp & 0xFF)) + String.fromCharCode(((mapp >> 8) & 0xFF)) + String.fromCharCode(((mapp >> 16) & 0xFF)) + String.fromCharCode(((mapp >> 24) & 0xFF));\n // pretend we've checked the MAP string at offset 52\n // pretend we've read the symmetry data\n if (header.grid[0] === 0 && header.extent[0] > 0) {\n header.grid[0] = header.extent[0] - 1;\n warnings.push(\"Fixed X interval count.\");\n }\n if (header.grid[1] === 0 && header.extent[1] > 0) {\n header.grid[1] = header.extent[1] - 1;\n warnings.push(\"Fixed Y interval count.\");\n }\n if (header.grid[2] === 0 && header.extent[2] > 0) {\n header.grid[2] = header.extent[2] - 1;\n warnings.push(\"Fixed Z interval count.\");\n }\n if (header.crs2xyz[0] === 0 && header.crs2xyz[1] === 0 && header.crs2xyz[2] === 0) {\n warnings.push(\"All crs2xyz records are zero. Setting crs2xyz to 1, 2, 3.\");\n header.crs2xyz = [1, 2, 3];\n }\n if (header.cellSize[0] === 0.0 &&\n header.cellSize[1] === 0.0 &&\n header.cellSize[2] === 0.0) {\n warnings.push(\"Cell dimensions are all zero. Setting to 1.0, 1.0, 1.0. Map file will not align with other structures.\");\n header.cellSize[0] = 1.0;\n header.cellSize[1] = 1.0;\n header.cellSize[2] = 1.0;\n }\n var indices = [0, 0, 0];\n indices[header.crs2xyz[0] - 1] = 0;\n indices[header.crs2xyz[1] - 1] = 1;\n indices[header.crs2xyz[2] - 1] = 2;\n var originGrid;\n if (header.origin2k[0] === 0.0 && header.origin2k[1] === 0.0 && header.origin2k[2] === 0.0) {\n originGrid = [header.nxyzStart[indices[0]], header.nxyzStart[indices[1]], header.nxyzStart[indices[2]]];\n }\n else {\n // Use ORIGIN records rather than old n[xyz]start records\n // http://www2.mrc-lmb.cam.ac.uk/image2000.html\n // XXX the ORIGIN field is only used by the EM community, and\n // has undefined meaning for non-orthogonal maps and/or\n // non-cubic voxels, etc.\n originGrid = [header.origin2k[indices[0]], header.origin2k[indices[1]], header.origin2k[indices[2]]];\n }\n var extent = [header.extent[indices[0]], header.extent[indices[1]], header.extent[indices[2]]];\n var nativeEndian = new Uint16Array(new Uint8Array([0x12, 0x34]).buffer)[0] === 0x3412;\n var rawData = endian === nativeEndian\n ? readRawData1(new Float32Array(buffer, headerSize + header.symBytes, extent[0] * extent[1] * extent[2]), endian, extent, header.extent, indices, header.mean)\n : readRawData(new DataView(buffer, headerSize + header.symBytes), endian, extent, header.extent, indices, header.mean);\n var field = new Density.Field3DZYX(rawData.data, extent);\n var data = {\n spacegroup: Density.createSpacegroup(header.spacegroupNumber, header.cellSize, header.cellAngles),\n box: {\n origin: [originGrid[0] / header.grid[0], originGrid[1] / header.grid[1], originGrid[2] / header.grid[2]],\n dimensions: [extent[0] / header.grid[0], extent[1] / header.grid[1], extent[2] / header.grid[2]],\n sampleCount: extent\n },\n data: field,\n valuesInfo: { min: header.min, max: header.max, mean: header.mean, sigma: rawData.sigma }\n };\n return Formats.ParserResult.success(data, warnings);\n }", "function test_basics(){\n var bmol = RDKitModule.get_mol(\"c1ccccc\");\n assert.equal(bmol.is_valid(),0);\n \n var mol = RDKitModule.get_mol(\"c1ccccc1O\");\n assert.equal(mol.is_valid(),1);\n assert.equal(mol.get_smiles(),\"Oc1ccccc1\");\n assert.equal(mol.get_inchi(),\"InChI=1S/C6H6O/c7-6-4-2-1-3-5-6/h1-5,7H\");\n assert.equal(RDKitModule.get_inchikey_for_inchi(mol.get_inchi()),\"ISWSIDIOOBJBQZ-UHFFFAOYSA-N\");\n\n var mb = mol.get_molblock();\n assert(mb.search(\"M END\")>0);\n var mol2 = RDKitModule.get_mol(mb);\n assert.equal(mol2.is_valid(),1);\n assert.equal(mol2.get_smiles(),\"Oc1ccccc1\");\n \n var descrs = JSON.parse(mol.get_descriptors());\n assert.equal(descrs.NumAromaticRings,1);\n assert.equal(descrs.NumRings,1);\n assert.equal(descrs.amw,94.11299);\n\n var fp1 = mol.get_morgan_fp();\n assert.equal(fp1.length,2048);\n assert.equal((fp1.match(/1/g)||[]).length,11);\n var fp2 = mol.get_morgan_fp(0,512);\n assert.equal(fp2.length,512);\n assert.equal((fp2.match(/1/g)||[]).length,3);\n \n var svg = mol.get_svg();\n assert(svg.search(\"svg\")>0);\n\n var qmol = RDKitModule.get_qmol(\"Oc(c)c\");\n assert.equal(qmol.is_valid(),1);\n var match = mol.get_substruct_match(qmol);\n var pmatch = JSON.parse(match);\n assert.equal(pmatch.atoms.length,4);\n assert.equal(pmatch.atoms[0],6);\n var svg2 = mol.get_svg_with_highlights(match);\n assert(svg2.search(\"svg\")>0);\n assert(svg.search(\"#FF7F7F\")<0);\n assert(svg2.search(\"#FF7F7F\")>0);\n}", "function ModelE2() {\n this._position = new Geometric2().zero();\n this._attitude = new Geometric2().zero().addScalar(1);\n this._position.modified = true;\n this._attitude.modified = true;\n }", "parseAtom() {\n\t\tif (this.is('keyword', 'fn')) {\n\t\t\tthis.functions.push(this.parseFunction());\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.is('keyword', 'object')) return this.parseObject();\n\t\tif (this.is('keyword', 'if')) return this.parseIf();\n\t\tif (this.is('keyword', 'let')) return this.parseBinding();\n\n\t\t// parse binary within parenthesis first, because math\n\t\tif (this.is('punctuation', '(')) return this.parseParenthesisBinary();\n\t\tif (this.is('instruction', 'print')) return this.parsePrintInstruction();\n\t\tif (this.is('instruction', 'syscall')) return this.parseSyscallInstruction();\n\t\t\t\t\t\n\t\tif (this.is('keyword', 'ret')) return this.parseReturn();\n\t\tif (this.is('identifier')) return this.parseIdentifier();\n\n\t\tlet peek = this.peek();\n\t\tif (peek.type === 'numberLiteral') return this.next();\n\n\t\tthrow new ParserError(\n\t\t\t'E0002',\n\t\t\t'UnexpectedToken',\n\t\t\t`Unexpected token ${peek.value}, but I don't really know what I expected either`, \n\t\t\tpeek.position.line, \n\t\t\tpeek.position.column, \n\t\t\tpeek,\n\t\t\tthis.module\n\t\t);\n\t}", "function chemistry() {\n var clipHere = 0;\n var columns = [];\n var me = '';\n var em = '';\n var sym = '';\n var s = 0;\n var r = '';\n var tmp = '';\n var isoMass = '';\n var isoDesc = '';\n var iMass = '';\n var lines = [];\n var massSymIon = '';\n var symMass = '';\n var matched = '';\n var symbol = '';\n var a = ['angstroms','angstrom','ang','a',\n 'centimeters','centimeter','cm',\n 'millimeters','millimeter','millimetres','millimetre','mm',\n 'micrometers','micrometer','micrometres','micrometre','microns','micron','um',\n 'nanometers','nanometer','nanometres','nanometre','nm'];\n var b = ['gigahertz','ghz','megahertz','mhz','terahertz','thz'];\n var c = ['eV', 'keV'];\n var units = (a.concat(b).concat(c)).join('\\|');\n var uType = a.join('\\|').replace(/[^\\|]+/g,'w') + '\\|' +\n b.join('\\|').replace(/[^\\|]+/g,'f') + '\\|' +\n c.join('\\|').replace(/[^\\|]+/g,'e'); \n var num = /\\d{1,5}(?:\\.\\d+)?/.source;\n var and = /(?:[\\,\\+\\/and\\&]{1,4})/.source;\n var three = /((?:lambdalambdalambda)|(?:lambdalambda)|(?:lambda)|(?:lll)|(?:ll)|(?:l)|(?:nununu)|(?:nunu)|(?:nu)|(?:nnn)|(?:nn)|(?:n))?/.source +\n '('+num+')' + '('+units+')?' + and + '('+num+')' + '('+units+')?' + and + '('+num+')' + '('+units+')?';\n var two = /((?:lambdalambda)|(?:lambda)|(?:ll)|(?:l)|(?:nunu)|(?:nu)|(?:nn)|(?:n))?/.source +\n '('+num+')' + '('+units+')?' + and + '('+num+')' + '('+units+')?';\n var one = /((?:lambda)|(?:l)|(?:nu)|(?:n))?/.source + '('+num+')?' + '('+units+')?';\n var startHere = xLtr.length;\n\n// ============================== read in the MOLECULES file =================================\n lines = (GM_getResourceText(\"molecules\").trim()).split('\\n');\n clipHere = lines.reduce(function(x1,x2,x3) {if (x2.match(/\\={20,}/)) {x1.push(x3);} return x1;}, []); \n if (clipHere.length >= 2) {\n lines = lines.slice(clipHere[0]+1,clipHere[1]);\n } else if (clipHere.length == 1) {\n lines = lines.slice(clipHere[0]+1); }\n for (s = 0; s < lines.length; s++) {\n lines[s] = lines[s].trim().replace(/ +/g,' ');\n columns = lines[s].split(' ');\n sym = columns[0]+ /((?:\\d[\\+\\-])|(?:\\+){1,3}|(?:\\-){1,3})?(\\[\\d\\-\\d\\])?/.source;\n // ------------- 3 values listed:\n r = '(?:' + three + sym +')|(?:' + sym + three +')'; \n xLtr.push({\"reg\":r, \"priority\":\"1\", \"tIndx\":columns[1], \"nChars\":\"50\", \"molecule\":columns[0],\n \"nVals\":\"3\", \"waveFreqPos\":\"1|12\", \"valPos\":\"2|13\", \"val1Pos\":\"2|13\",\n \"unitPos\":\"3|5|7|14|16|18\", \"chargePos\":\"8|10\", \"transPos\":\"9|11\"});\n xLtr.push({\"reg\":r, \"priority\":\"1\", \"tIndx\":columns[1], \"nChars\":\"50\", \"molecule\":columns[0],\n \"nVals\":\"3\", \"waveFreqPos\":\"1|12\", \"valPos\":\"4|15\", \"val1Pos\":\"2|13\",\n \"unitPos\":\"3|5|7|14|16|18\", \"chargePos\":\"8|10\", \"transPos\":\"9|11\"});\n xLtr.push({\"reg\":r, \"priority\":\"1\", \"tIndx\":columns[1], \"nChars\":\"50\", \"molecule\":columns[0],\n \"nVals\":\"3\", \"waveFreqPos\":\"1|12\", \"valPos\":\"6|17\", \"val1Pos\":\"2|13\",\n \"unitPos\":\"3|5|7|14|16|18\", \"chargePos\":\"8|10\", \"transPos\":\"9|11\"});\n// ------------- 2 values listed:\n r = '(?:' + two + sym + ')|(?:' + sym + two + ')'; \n xLtr.push({\"reg\":r, \"priority\":\"1\", \"tIndx\":columns[1], \"nChars\":\"40\", \"molecule\":columns[0],\n \"nVals\":\"2\", \"waveFreqPos\":\"1|10\", \"valPos\":\"2|11\", \"val1Pos\":\"2|11\",\n \"unitPos\":\"3|5|12|14\", \"chargePos\":\"6|8\", \"transPos\":\"7|9\"});\n xLtr.push({\"reg\":r, \"priority\":\"1\", \"tIndx\":columns[1], \"nChars\":\"40\", \"molecule\":columns[0],\n \"nVals\":\"2\", \"waveFreqPos\":\"1|10\", \"valPos\":\"4|13\", \"val1Pos\":\"2|11\",\n \"unitPos\":\"3|5|12|14\", \"chargePos\":\"6|8\", \"transPos\":\"7|9\"});\n// ------------- 1 or no values listed:\n r = '(?:' + one + sym +')|(?:' + sym + one + ')'; \n xLtr.push({\"reg\":r, \"priority\":\"1\", \"tIndx\":columns[1], \"nChars\":\"25\", \"molecule\":columns[0],\n \"nVals\":\"1\", \"waveFreqPos\":\"1|8\", \"valPos\":\"2|9\", \"val1Pos\":\"2|9\",\n \"unitPos\":\"3|10\", \"chargePos\":\"4|6\", \"transPos\":\"5|7\"});\n }\n\n// ============================== read in the ELEMENTS file =================================\n// (https://www.khanacademy.org/science/chemistry/atomic-structure-and-properties/\n// names-and-formulas-of-ionic-compounds/a/naming-monatomic-ions-and-ionic-compounds\n// http://www.edu.xunta.es/ftpserver/portal/S_EUROPEAS/FQ/3rdESO_archivos/Nomenclature.htm\n// http://preparatorychemistry.com/Bishop_Isotope_Notation.htm\n clipHere = 0; \n lines = (GM_getResourceText(\"elements\").trim()).split('\\n');\n// clip out data table from any comments blocks\n clipHere = lines.reduce(function(x1,x2,x3) {if (x2.match(/\\={20,}/)) {x1.push(x3);} return x1;}, []); \n if (clipHere.length >= 2) {\n lines = lines.slice(clipHere[0]+1,clipHere[1]);\n } else if (clipHere.length == 1) {\n lines = lines.slice(clipHere[0]+1); }\n// format of the \"elements.txt\" file: Column 1: element symbol (like \"He\"), Column 2: written out name of the element\n// (like \"helium\"), Column 3: element's atomic number (# protons), Column 4: atomic mass of most abundant stable istope,\n// Column 5: list of other stable isotopes (atomic masses) delimited by vertical bars, Column 6: list of radioisotopes\n// (atomic mass) delimited by vertical bars\n\n\n// come back to\n// among the molecules is \"NaI\", sodium iodide. Could be confused with \"NaI\", neutral sodium! Need to have a\n// special catch that tries to distinguish which it is (if surrounded by brackets, is the neutral sodium. If \n// has a charge, is a molecule.\n\n for (s = 0; s < lines.length; s++) {\n lines[s] = lines[s].trim().replace(/ +/g,' ');\n// replace any lone vertical bars with \"\"\n columns = (lines[s].split(' ')).map(z => z.replace(/^\\|$/,''));\n isoMass = columns[3];\n isoDesc = columns[3].replace(/\\d+/g,'stable_isotope|most_abundant_isotope');\n isoMass = isoMass + ' ' + columns[4].replace(/\\|/g,' ');\n isoDesc = isoDesc + ' ' + columns[4].replace(/\\|/g,' ').replace(/\\d+/g,'stable_isotope');\n isoMass = isoMass + ' ' + columns[5].replace(/\\|/g,' ');\n isoDesc = isoDesc + ' ' + columns[5].replace(/\\|/g,' ').replace(/\\d+/g,'radio_isotope');\n isoMass = isoMass.replace(/ +/g,' ').trim();\n isoDesc = isoDesc.replace(/ +/g,' ').trim();\n iMass = isoMass.replace(/ /g,'\\|');\n massSymIon = '(?:(?:'+columns[2]+'('+iMass+'))|(?:'+'('+iMass+')'+columns[2]+')|('+iMass+'))?' + columns[0] + /([IVX]{0,6})/.source;\n symMass = columns[0] + '(?:(?:'+columns[2]+'('+iMass+'))|(?:'+'('+iMass+')'+columns[2]+')|('+iMass+'))';\n sym = /(\\[)?/.source + '(?:(?:'+ symMass + ')|(?:' + massSymIon + '))' + /(\\])?/.source;\n // ------------- 3 values listed:\n var r = '(?:' + sym + three + ')|(?:' + three + sym + ')';\n xLtr.push({\"reg\":r, \"priority\":\"1\", \"tIndx\":columns[1], \"nChars\":\"50\", \"element\":columns[0],\n \"isoMass\":isoMass, \"isoDesc\":isoDesc, \"nprotons\":columns[2], \"nVals\":\"3\",\n \"waveFreqPos\":\"10|17\", \"valPos\":\"11|18\", \"val1Pos\":\"11|18\",\n \"unitPos\":\"12|14|16|19|21|23\", \"massPos\":\"2|3|4|5|6|7|25|26|27|28|29|30\",\n \"ionPos\":\"8|31\", \"leftPos\":\"1|24\", \"rightPos\":\"9|32\"});\n xLtr.push({\"reg\":r, \"priority\":\"1\", \"tIndx\":columns[1], \"nChars\":\"50\", \"element\":columns[0],\n \"isoMass\":isoMass, \"isoDesc\":isoDesc, \"nprotons\":columns[2], \"nVals\":\"3\",\n \"waveFreqPos\":\"10|17\", \"valPos\":\"13|20\", \"val1Pos\":\"11|18\",\n \"unitPos\":\"12|14|16|19|21|23\", \"massPos\":\"2|3|4|5|6|7|25|26|27|28|29|30\",\n \"ionPos\":\"8|31\", \"leftPos\":\"1|24\", \"rightPos\":\"9|32\"});\n xLtr.push({\"reg\":r, \"priority\":\"1\", \"tIndx\":columns[1], \"nChars\":\"50\", \"element\":columns[0],\n \"isoMass\":isoMass, \"isoDesc\":isoDesc, \"nprotons\":columns[2], \"nVals\":\"3\",\n \"waveFreqPos\":\"10|17\", \"valPos\":\"15|22\", \"val1Pos\":\"11|18\",\n \"unitPos\":\"12|14|16|19|21|23\", \"massPos\":\"2|3|4|5|6|7|25|26|27|28|29|30\",\n \"ionPos\":\"8|31\", \"leftPos\":\"1|24\", \"rightPos\":\"9|32\"});\n// ------------- 2 values listed:\n var r = '(?:' + sym + two +')|(?:' + two + sym + ')'; \n xLtr.push({\"reg\":r, \"priority\":\"1\", \"tIndx\":columns[1], \"nChars\":\"40\", \"element\":columns[0],\n \"isoMass\":isoMass, \"isoDesc\":isoDesc, \"nprotons\":columns[2], \"nVals\":\"2\",\n \"waveFreqPos\":\"1|10\", \"valPos\":\"11|16\", \"val1Pos\":\"11|16\",\n \"unitPos\":\"12|14|17|19\", \"massPos\":\"2|3|4|5|6|7|21|22|23|24|25|26\",\n \"ionPos\":\"8|27\", \"leftPos\":\"1|20\", \"rightPos\":\"9|28\"});\n xLtr.push({\"reg\":r, \"priority\":\"1\", \"tIndx\":columns[1], \"nChars\":\"40\", \"element\":columns[0],\n \"isoMass\":isoMass, \"isoDesc\":isoDesc, \"nprotons\":columns[2], \"nVals\":\"2\",\n \"waveFreqPos\":\"1|10\", \"valPos\":\"13|18\", \"val1Pos\":\"11|16\",\n \"unitPos\":\"12|14|17|19\", \"massPos\":\"2|3|4|5|6|7|21|22|23|24|25|26\",\n \"ionPos\":\"8|27\", \"leftPos\":\"1|20\", \"rightPos\":\"9|28\"});\n// ------------- 1 or no values listed:\n var r = '(?:' + sym + one +')|(?:' + one + sym + ')'; \n xLtr.push({\"reg\":r, \"priority\":\"1\", \"tIndx\":columns[1], \"nChars\":\"25\", \"element\":columns[0],\n \"isoMass\":isoMass, \"isoDesc\":isoDesc, \"nprotons\":columns[2], \"nVals\":\"1\",\n \"waveFreqPos\":\"10|13\", \"valPos\":\"11|14\", \"val1Pos\":\"11|14\",\n \"unitPos\":\"12|15\", \"massPos\":\"2|3|4|5|6|7|17|18|19|20|21|22\",\n \"ionPos\":\"8|23\", \"leftPos\":\"1|16\", \"rightPos\":\"9|24\"});\n }\n // Now add their \"indx\" fields:\n for (s = startHere; s < xLtr.length; s++) {\n xLtr[s].indx = function(text, startPos, commonLines) {\n if (commonLines === undefined || typeof(commonLines) != \"boolean\") {commonLines = true; }\n this.endMatch = \"-1\";\n this.energy = '';\n this.accuracy = '';\n this.x = '';\n this.xSupp = '';\n this.noUnits = '';\n this.symbol = '';\n this.type = '';\n this.charge = '';\n this.transition = '';\n var tmp = '';\n var rightTst = false;\n var leftTst = false;\n var middleTst = true;\n var capTst = true;\n var elementMolecule = '';\n var digitVals = {I:1, V:5, X:10};\n var endMatch = -1;\n var noUnits = '';\n \n var t = JSON.parse(filterTheText(this.reg, text.slice(startPos)));\n if (this.element !== undefined && this.element !== '') {\n elementMolecule = this.element;\n } else {\n elementMolecule = this.molecule; }\n// perform a case-insensitive match initially. If a match exists, and if there are \n// capitalized letters involved in both the chemical symbol as well as in the matched text, then \n// perform a case-sensitive match and make sure that the match continues: \n m = t[0].match(new RegExp('^'+'(?:'+this.reg+')', 'i'));\n if (m && m[0].match(/[A-Z]/) && this.reg.match(/[A-Z]/)) {\n m = t[0].match(new RegExp('^'+'(?:'+this.reg+')')); }\n if (m) {\n endMatch = t[1][m[0].length-1] + 1 + startPos;\n// make sure that this is not a false-positive: if the word is less than 5 characters long,\n// insure that there is a non-alphanumeric character on the right and left side of it in\n// the unfiltered version of the text. \n if (m[0].length <= 5 && startPos > 0 && text.charAt(startPos-1).match(/[^A-Za-z0-9]/)) {\n leftTst = true; }\n if (startPos == 0) {leftTst = true; }\n if (m[0].length > 5) {leftTst = true;}\n if (m[0].length <= 5 && text.length >= endMatch+1 && text.charAt(endMatch).match(/[^A-Za-z0-9]/)) {\n rightTst = true; }\n if (text.length < endMatch+1) {rightTst = true; }\n if (m[0].length > 5) {rightTst = true; }\n// If the match consists of a single capitalized letter (like I for iodine), make sure that the match does \n// not occur as the first word of a sentence: \n if (m[0].match(/[A-Z]/) && m[0].length == 1 && startPos > 0 && text.slice(startPos-5, startPos).match(/[\\.\\,\\;\\:] +$/)) \n {capTst = false; }\n if (text.slice(startPos, endMatch).match(/\\;/) && (!(m[0].match(/\\; +[A-Z]/)))) {middleTst = false; }\n if (text.slice(startPos, endMatch).match(/\\:/) && (!(m[0].match(/\\: +[A-Z]/)))) {middleTst = false; }\n if (text.slice(startPos, endMatch).match(/\\?/) && (!(m[0].match(/\\? +[A-Z]/)))) {middleTst = false; }\n if (text.slice(startPos, endMatch).match(/\\!/) && (!(m[0].match(/\\! +[A-Z]/)))) {middleTst = false; }\n if (this.element !== undefined && text.slice(startPos, endMatch).match(/\\-/)) {middleTst = false; }\n// If all the tests come back OK, then we've got a legit match:\n }\n if (!(leftTst*rightTst*middleTst*capTst)) {return \"\"; }\n// everything below here assumes that there was an acceptable match\n this.endMatch = \"\"+endMatch \n var indx = this.tIndx;\n var xSupp = '';\n var x = '';\n var ion = '';\n var mass = '';\n var leftBra = '';\n var rightBra = '';\n var transition = '';\n var charge = '';\n// extract the \"lambdalambda\" or \"nununu\" words, if present in the matched text:\n var lamnu = (this.waveFreqPos.split('\\|')).map(z => m[parseInt(z)]).filter(z => z !== undefined && z != '')[0];\n if (lamnu === undefined) {lamnu = ''; }\n// extract the first value:\n var val1 = (this.val1Pos.split('\\|')).map(z => m[parseInt(z)]).filter(z => z !== undefined && z != '')[0];\n if (val1 === undefined) {val1 = ''; }\n// extract the value to be processed (which is the same as Val1 if there was only a single value in the matched text):\n var val = (this.valPos.split('\\|')).map(z => m[parseInt(z)]).filter(z => z !== undefined && z != '')[0];\n if (val === undefined) {val = ''; }\n// extract the matched units, if present:\n var units = (this.unitPos.split('\\|')).map(z => m[parseInt(z)]).filter(z => z !== undefined && z != '')[0];\n if (units === undefined) {units = ''; }\n// standardize the unit notation:\n units = units.replace(/^a[a-z]+/i,'ang');\n units = units.replace(/^um$/i,'um').replace(/^mu$/i,'um').replace(/^mic[a-z]+/i,'um');\n units = units.replace(/^cm/i,'cm');\n units = units.replace(/^mil[a-z]+/i,'mm').replace(/^mm/i,'mm');\n units = units.replace(/^n[a-z]+/i,'nm');\n units = units.replace(/^gh[a-z]+/i,'ghz').replace(/^gigah[a-z]+/i,'ghz');\n units = units.replace(/^kh[a-z]+/i,'khz').replace(/^kiloh[a-z]+/i,'khz');\n units = units.replace(/^th[a-z]+/i,'thz').replace(/^terah[a-z]+/i,'thz');\n units = units.replace(/^mh[a-z]+/i,'mhz').replace(/^megah[a-z]+/i,'mhz');\n units = units.replace(/^ev/i,'ev');\n units = units.replace(/^kev/i/'kev').replace(/^kiloe[a-z]+/i,'kev');\n if (this.element !== undefined && this.element != '') {\n// extract the ionization level, if present:\n var ion = (this.ionPos.split('\\|')).map(z => m[parseInt(z)]).filter(z => z !== undefined && z != '')[0];\n if (ion === undefined) {ion = ''; }\n// force symbol to carry an ion level designation. For example, if it is listed only as \"Ar\", assume\n// that \"ArI\" is implied and explicitly put in the \"I\". We insert the missing/implied \"I\" to insure \n// a consistent way to enter this line into the index ... would not want the same exact spectral line to\n// be listed under both \"Ar\" and \"ArI\". \n if (ion == '' && val != '') {ion = 'I'; }\n if (ion != '') {\n ion = ion.toUpperCase();\n// if an ion level is provided, insure that it is a feasible value (e.g., not in excess of the number of \n// electrons present in a neutral version of this atom). Accomplish this task by converting the roman numeral\n// into an arabic number and then compare to the value stored under nproton:\n tmp = 0;\n ion = ion.split('');\n for (i = 0; i < ion.length; i++) {\n if (digitVals[ion[i]] < digitVals[ion[i+1]]) {\n tmp += digitVals[ion[i+1]] - digitVals[ion[i]];\n i++;\n } else {tmp += digitVals[ion[i]]; }\n }\n ion = ion.join('');\n tmp = tmp - 1; // because ion level of I = neutral, II = missing 1 electron, etc.\n// see https://initjs.org/translate-roman-numerals-in-javascript-482ef6e55ee7\n if (tmp > parseInt(this.nprotons)) {\n// we have a physically impossible situation (more electrons missing than were there initially), so obviously\n// the match to the text has been a false positive, and there really isn't a match. Put everything back \n// the way it was before we thought we had a match, and bail out:\n this.endMatch = \"-1\";\n this.energy = '';\n this.accuracy = '';\n this.x = '';\n this.xSupp = '';\n this.noUnits = '';\n this.symbol = '';\n this.type = '';\n this.charge = '';\n this.transition = '';\n return ''; }\n// determine what adjective should be used to describe this ionization level: single for 1 missing electron,\n// double for 2 missing electrons, triple for 3 missing electrons, and then multiple if the number of \n// missing electrons is less than 10% of the total number of protons, and then high if number of missing\n// electrons is in excess of 10% of total number of protons and/or if 10 more more electrons are missing, \n// and complete/fully if all electrons are removed:\n ionDesc = '';\n if (tmp == 0) {\n ionDesc = 'neutral';\n } else if (tmp == 1) {\n ionDesc = 'singly_ionized';\n } else if (tmp == 2) {\n ionDesc = 'doubly_ionized'; \n } else if (tmp == 3) {\n ionDesc = 'triply_ionized'; \n } else if (tmp < 10 && tmp < 0.1*parseFloat(this.nprotons)) {\n ionDesc = 'multiply_ionized'; \n } else if ( ((tmp >= 10) || (tmp >= 0.1*parseFloat(this.nprotons))) && tmp < parseInt(this.nprotons) ) {\n ionDesc = 'highly_ionized';\n } else if (tmp == parseInt(this.nprotons)) {\n ionDesc = 'completely_ionized|fully_ionized'; }\n xSupp = ([... new Set((xSupp + ' ' + this.tIndx+'\\_'+ion + 'X4' + ionDesc).trim().split(' '))]).join(' ').trim(); }\n// extract the isotopic mass, if available:\n var mass = (this.massPos.split('\\|')).map(z => m[parseInt(z)]).filter(z => z !== undefined && z != '')[0];\n if (mass === undefined) {mass = ''; }\n// extract the left bracket (if present):\n var leftBra = (this.leftPos.split('\\|')).map(z => m[parseInt(z)]).filter(z => z !== undefined && z != '')[0];\n if (leftBra === undefined) {leftBra = ''; }\n// extract the right bracket (if present):\n var rightBra = (this.rightPos.split('\\|')).map(z => m[parseInt(z)]).filter(z => z !== undefined && z != '')[0];\n if (rightBra === undefined) {rightBra = ''; }\n if (leftBra != '' && rightBra != '') { // fully forbidden\n indx = indx + '\\|' + 'forbidden';\n } else if ( (leftBra != '')||(rightBra != '') ) { // semi forbidden\n leftBra = '';\n rightBra = '\\]';\n indx = indx + '\\|' + '*semi_forbidden'; }\n if (mass != '') {\n// see which description should go with this isotopic mass:\n z = this.isoMass.split(' ').indexOf(mass);\n indx = indx + '\\|' + mass; \n xSupp = ([... new Set((xSupp + ' ' + this.tIndx+'\\_'+mass + 'X4' + this.isoDesc.split(' ')[z]).trim().split(' '))]).join(' ').trim(); }\n xSupp = ([... new Set((xSupp + ' ' + this.tIndx + 'X4' + 'element').trim().split(' '))]).join(' ').trim(); \n symbol = leftBra + this.element + ion + rightBra; \n } else if (this.molecule !== undefined && this.molecule != '') {\n// extract the charge (if present):\n charge = (this.chargePos.split('\\|')).map(z => m[parseInt(z)]).filter(z => z !== undefined && z != '')[0];\n if (charge === undefined) {charge = ''; }\n// extract the transition (if present):\n transition = (this.transPos.split('\\|')).map(z => m[parseInt(z)]).filter(z => z !== undefined && z != '')[0];\n if (transition === undefined) {transition = ''; }\n if (charge != '') {\n indx = indx + '\\|' + charge;\n if (charge.match(/\\-$/)) {\n xSupp = ([... new Set((xSupp + ' ' + charge + 'X4' + 'anion').trim().split(' '))]).join(' ').trim(); \n } else if (charge.match(/\\+$/)) {\n xSupp = ([... new Set((xSupp + ' ' + charge + 'X4' + 'cation').trim().split(' '))]).join(' ').trim(); }\n }\n if (transition != '') {indx = indx + '\\|' + transition; }\n xSupp = ([... new Set((xSupp + ' ' + this.tIndx + 'X4' + 'molecule').trim().split(' '))]).join(' ').trim(); \n symbol = this.molecule + charge + transition;\n }\n// Now organize the information:\n if (lamnu.match(/^l/i)) {\n lamnu = 'w';\n } else if (lamnu.match(/^n/i)) {\n lamnu = 'f';\n } else {lamnu = ''; }\n// If units have been provided, then compute the energy of the line in units of ev, and let that value\n// enter as part of the words to be indexed.\n// If val is 2-digits, and val1 is 4 digits, then probably a shorthand notation has been used such\n// that the first 2 digits of the wavelength (in angstrom) have been removed for the values following the first one. \n// Check for this situation and attach the missing digits if necessary:\n if (val1.indexOf('\\.') == -1 && val1.length == 4 && val.length == 2) {\n units = 'ang';\n val = val1.slice(0,2) + val; } \n// if both a value and units have been supplied, we can compute an energy:\n var info = '';\n var energy = '';\n var delta = '';\n var region = ''; \n if (val != '' && units != '') {\n info = JSON.parse(extractLineEnergy(val, units));\n energy = info[0];\n delta = info[1];\n lamnu = info[3];\n xSupp = ([... new Set((xSupp + ' ' + energy + 'X4' + 'spectral_line' + '\\|' + info[2]).trim().split(' '))]).join(' ').trim();;\n indx = indx + '\\|' + info[0];\n }\n matched = '';\n// if a value has been supplied, then see if there is a match-up to any of the lines in the common\n// line list (type = lineList):\n// Look for matches between the value provided and those in the common-line list that has already been loaded\n// into the xLtr and designated by type = \"lineList\". There are 2 ways to kick off the search: if units have\n// been provided and are equal to ev, then do a search on energy. If no units, then search on the \n// wavelength/freqency raw value:\n if (commonLines && val != '') {\n if (info != '') {\n matched = xLtr.reduce(function(z1,z2,z3) {\n var diff;\n var totDelta;\n if (z2.type == 'lineList') {\n totDelta = Math.pow(Math.pow(parseFloat(z2.energyDelta),2) + Math.pow(parseFloat(delta),2),0.5);\n diff = Math.abs(parseFloat(z2.energy) - parseFloat(energy));\n if (diff <= totDelta) {z1.push(z3); } }\n return z1;}, []);\n } else {\n matched = xLtr.reduce(function(z1,z2,z3) {\n var diff;\n var totDelta;\n if (z2.type == 'lineList') {\n totDelta = Math.pow(Math.pow(parseFloat(z2.wfeDelta),2) + Math.pow(parseFloat(z2.wfeDelta),2),0.5);\n diff = Math.abs(parseFloat(z2.wfeValue) - parseFloat(val));\n if (diff <= totDelta) {z1.push(z3); } }\n return z1;}, []); }\n// If the symbol is specified, then lets see if we can further whittle down the list:\n if (matched.length > 0 && symbol != '') {\n tmp = matched;\n matched = xLtr.reduce(function(z1,z2,z3) {\n if (z2.type == 'lineList' && tmp.indexOf(z3) != -1 && z2.symbol == symbol) {z1.push(z3); }\n return z1;}, []); }\n// if the unit is specified, then whittle down even further:\n if (matched.length > 0 && info == '' && units != '' && units != 'ev') {\n tmp = matched;\n matched = xLtr.reduce(function(z1,z2,z3) {\n if (z2.type == 'lineList' && tmp.indexOf(z3) != -1 && z2.units == units) {z1.push(z3); }\n return z1; }, []); }\n// if the waveFreq is known and the units were not provided, then whittle down further:\n if (matched.length > 0 && info == '' && units == '' && lamnu != '') {\n tmp = matched;\n matched = xLtr.reduce(function(z1,z2,z3) {\n if (z2.type == 'lineList' && tmp.indexOf(z3) != -1 && z2.waveFreq == lamnu) {z1.push(z3); }\n return z1; }, []); }\n// if there were multiple matches, get the one that is closest to the provided value:\n tmp = matched;\n if (matched.length > 0 && info != '') {\n matched = xLtr.reduce(function(z1,z2,z3) {\n var diff;\n if (z2.type == 'lineList' && tmp.indexOf(z3) != -1) {\n diff = Math.abs(parseFloat(z2.energy) - parseFloat(energy));\n if (z1.length > 0 && diff < z1[0]) {z1 = [diff, z3];} else {z1 = [diff, z3]; } }\n return z1;}, []);\n } else if (matched.length > 0) {\n matched = xLtr.reduce(function(z1,z2,z3) {\n var diff;\n if (z2.type == 'lineList' && tmp.indexOf(z3) != -1) {\n diff = Math.abs(parseFloat(z2.wfeValue) - parseFloat(val));\n if (z1.length > 0 && diff < z1[0]) {z1 = [diff, z3];} else {z1 = [diff, z3]; } }\n return z1;}, []); }\n if (matched.length > 0) {\n matched = matched[1];\n this.x = xLtr[matched].x;\n this.xSupp = xLtr[matched].xSupp;\n this.type = \"spectralLine\";\n this.energy = xLtr[matched].energy;\n this.accuracy = xLtr[matched].energyDelta;\n this.noUnits = \"\";\n this.symbol = xLtr[matched].symbol;\n return xLtr[matched].indx; }\n }\n indx = ([... new Set(indx.split('\\|'))]).join('\\|');\n xSupp = ([... new Set(xSupp.trim().split(' '))]).join(' ').trim();\n x = x.replace(/^\\|/,'').replace(/\\|$/,'');\n if (x != '') {x = ([... new Set(x.split('\\|'))]).join('\\|'); }\n if (symbol == '') {symbol = 'TBD'; }\n tmp = '';\n if (energy != '') {\n tmp = energy + '\\_' + 'e';\n } else if (val != '') {\n tmp = val + '\\_' + lamnu; }\n if (tmp != '') {\n tmp = tmp.replace(/\\_$/,'');\n noUnits = (symbol + '\\_' + tmp); } \n if (symbol != 'TBD' && energy != '') {noUnits = ''; }\n// If this matched text indicates a spectral line (a value was present), proceed with the xLtr entry:\n if (val != '') {\n this.x = x;\n this.xSupp = xSupp;\n this.type = \"spectralLine\";\n this.energy = energy;\n if (energy == '') {delta = ''; }\n this.accuracy = delta;\n this.noUnits = noUnits;\n this.symbol = symbol;\n if (energy == '') {indx = indx + '\\|' + val; }\n return indx;\n }\n// If a value was not present, then we don't have a spectral line but rather mention of\n// an element or molecule. Proceed with that xLtr entry:\n this.x = x;\n this.xSupp = xSupp;\n if (this.element !== undefined && this.element != '') {\n this.type = \"element\";\n } else {this.type = \"molecule\"; }\n this.energy = '';\n this.accuracy = '';\n this.noUnits = '';\n this.symbol = symbol;\n return indx;\n }\n }\n return;\n }", "addNewAtom(curAtom, atoms, changes, x, y) {\n var newAtom = new Atom(new Coord(x, y, 0), curAtom.atom.atomicSymbol,\n curAtom.atom.elementName, curAtom.atom.atomicRadius,\n curAtom.atom.atomColor, null, new Set());\n atoms.add(newAtom);\n changes.push({type:\"atom\", payLoad:newAtom, action:\"added\", overwritten:null});\n }", "function ModelE2(type) {\n if (type === void 0) { type = 'ModelE2'; }\n _super.call(this, mustBeString('type', type));\n this._position = new G2().zero();\n this._attitude = new G2().zero().addScalar(1);\n /**\n * Used for exchanging number[] data to achieve integrity and avoid lots of temporaries.\n * @property _posCache\n * @type {R2}\n * @private\n */\n this._posCache = new R2();\n /**\n * Used for exchanging number[] data to achieve integrity and avoid lots of temporaries.\n * @property _attCache\n * @type {SpinG2}\n * @private\n */\n this._attCache = new SpinG2();\n this._position.modified = true;\n this._attitude.modified = true;\n }", "function parseOS2Table(data, start) {\n var os2 = {};\n var p = new parse.Parser(data, start);\n os2.version = p.parseUShort();\n os2.xAvgCharWidth = p.parseShort();\n os2.usWeightClass = p.parseUShort();\n os2.usWidthClass = p.parseUShort();\n os2.fsType = p.parseUShort();\n os2.ySubscriptXSize = p.parseShort();\n os2.ySubscriptYSize = p.parseShort();\n os2.ySubscriptXOffset = p.parseShort();\n os2.ySubscriptYOffset = p.parseShort();\n os2.ySuperscriptXSize = p.parseShort();\n os2.ySuperscriptYSize = p.parseShort();\n os2.ySuperscriptXOffset = p.parseShort();\n os2.ySuperscriptYOffset = p.parseShort();\n os2.yStrikeoutSize = p.parseShort();\n os2.yStrikeoutPosition = p.parseShort();\n os2.sFamilyClass = p.parseShort();\n os2.panose = [];\n for (var i = 0; i < 10; i++) {\n os2.panose[i] = p.parseByte();\n }\n\n os2.ulUnicodeRange1 = p.parseULong();\n os2.ulUnicodeRange2 = p.parseULong();\n os2.ulUnicodeRange3 = p.parseULong();\n os2.ulUnicodeRange4 = p.parseULong();\n os2.achVendID = String.fromCharCode(\n p.parseByte(),\n p.parseByte(),\n p.parseByte(),\n p.parseByte()\n );\n os2.fsSelection = p.parseUShort();\n os2.usFirstCharIndex = p.parseUShort();\n os2.usLastCharIndex = p.parseUShort();\n os2.sTypoAscender = p.parseShort();\n os2.sTypoDescender = p.parseShort();\n os2.sTypoLineGap = p.parseShort();\n os2.usWinAscent = p.parseUShort();\n os2.usWinDescent = p.parseUShort();\n if (os2.version >= 1) {\n os2.ulCodePageRange1 = p.parseULong();\n os2.ulCodePageRange2 = p.parseULong();\n }\n\n if (os2.version >= 2) {\n os2.sxHeight = p.parseShort();\n os2.sCapHeight = p.parseShort();\n os2.usDefaultChar = p.parseUShort();\n os2.usBreakChar = p.parseUShort();\n os2.usMaxContent = p.parseUShort();\n }\n\n return os2;\n }", "function abiParser () {\n var abi = {\n version: 'eosio::abi/1.0',\n types: [],\n structs: [],\n actions: [],\n tables: []\n };\n\n // parse action\n function createActions (TypeDefine) {\n var actions = [];\n var bodyDeclarations = TypeDefine.bodyDeclarations;\n bodyDeclarations.forEach((bodyDeclaration) => {\n if (bodyDeclaration.node == 'MethodDeclaration') {\n var methodExtracted = parseActionMethod(bodyDeclaration);\n actions.push(methodExtracted.action);\n abi.structs.push(methodExtracted.actionStruct);\n }\n });\n\n abi.actions = actions;\n }\n\n function parseActionMethod (bodyDeclaration) {\n var actionDef = {};\n var actionStruct = {\n 'name': '',\n 'base': '',\n 'fields': []\n };\n\n actionDef.name = bodyDeclaration.name.identifier;\n actionDef.type = actionDef.name;\n actionDef.ricardian_contract = '';\n actionStruct.name = actionDef.type;\n\n bodyDeclaration.parameters.forEach((parameter) => {\n if (parameter.node == 'SingleVariableDeclaration') {\n var parameterDef = {};\n parameterDef.name = parameter.name.identifier;\n parameterDef.type = parameter.type.name.identifier;\n actionStruct.fields.push(parameterDef);\n }\n });\n\n return {\n action: actionDef,\n actionStruct: actionStruct\n };\n }\n\n // create database define\n function createDatabase (TypeDefine) {\n var tableStruct = {};\n\n tableStruct.name = TypeDefine.name.identifier;\n TypeDefine.bodyDeclarations.forEach((bodyDeclaration) => {\n if (bodyDeclaration.node == 'FieldDeclaration') {\n var type = bodyDeclaration.type.name.identifier;\n var typeValues = [];\n if (bodyDeclaration.fragments) {\n bodyDeclaration.fragments.forEach((fragment) => {\n if (fragment.node == 'VariableDeclarationFragment') typeValues.push(fragment.name.identifier);\n });\n }\n\n if (type == 'key_names' || type == 'key_types') {\n tableStruct[type] = typeValues;\n } else {\n tableStruct[type] = typeValues[0];\n }\n }\n });\n\n abi.tables.push(tableStruct);\n }\n\n // create struct\n function createStruct (TypeDefine) {\n var structDef = {};\n\n structDef.name = TypeDefine.name.identifier;\n structDef.base = '';\n structDef.fields = [];\n\n TypeDefine.bodyDeclarations.forEach((bodyDeclaration) => {\n if (bodyDeclaration.node == 'FieldDeclaration') {\n var type = '';\n if (bodyDeclaration.type.node == 'ArrayType') {\n type = bodyDeclaration.type.componentType.name.identifier + '[]';\n } else {\n type = bodyDeclaration.type.name.identifier;\n }\n\n var typeValues = [];\n if (bodyDeclaration.fragments) {\n bodyDeclaration.fragments.forEach((fragment) => {\n if (fragment.node == 'VariableDeclarationFragment') typeValues.push(fragment.name.identifier);\n });\n }\n\n structDef.fields.push({\n name: typeValues[0],\n type: type\n });\n }\n });\n\n abi.structs.push(structDef);\n }\n\n function parseABI (content) {\n var results = parser.parse(content);\n results.types.forEach((Type) => {\n if (Type.superclassType && Type.superclassType.name.identifier == 'db') {\n return createDatabase(Type);\n }\n // table define\n if (Type.interface) {\n return createActions(Type);\n }\n return createStruct(Type);\n });\n return abi;\n }\n\n return {\n parse: parseABI\n };\n}", "function importMol(str) {\n\n importMolGen(str,\"\\n\");\n var molIntermed = exportMol();\n removeAllNodes();\n importMolGen(molIntermed,\"<br>\");\n}", "_readConnection (schematicData, index) {\n let junctionDef = {}\n // The connection is specified on a single line, so increment afterward.\n // We are already on the line of interest\n rd.readFieldsInto(junctionDef, schematicData[index++],\n [null, null, 'x', 'y'],\n [null, null, parseInt, parseInt])\n\n this._convertPoint(junctionDef)\n\n // TODO probably need to store this for later\n }", "parseAtom() {\n if (this.eat('.')) {\n return { type: 'Atom', subtype: '.', enclosedCapturingParentheses: 0 };\n }\n if (this.eat('\\\\')) {\n return this.parseAtomEscape();\n }\n if (this.eat('(')) {\n const node = {\n type: 'Atom',\n capturingParenthesesBefore: this.capturingGroups.length,\n enclosedCapturingParentheses: 0,\n capturing: true,\n GroupSpecifier: undefined,\n Disjunction: undefined,\n };\n if (this.eat('?')) {\n if (this.eat(':')) {\n node.capturing = false;\n } else {\n node.GroupSpecifier = this.parseGroupName();\n }\n }\n if (node.capturing) {\n this.capturingGroups.push(node);\n }\n if (node.GroupSpecifier) {\n this.groupSpecifiers.set(node.GroupSpecifier, node.capturingParenthesesBefore);\n }\n node.Disjunction = this.parseDisjunction();\n this.expect(')');\n node.enclosedCapturingParentheses = this.capturingGroups.length - node.capturingParenthesesBefore - 1;\n return node;\n }\n if (this.test('[')) {\n return {\n type: 'Atom',\n CharacterClass: this.parseCharacterClass(),\n };\n }\n if (isSyntaxCharacter(this.peek())) {\n throw new SyntaxError(`Expected a PatternCharacter but got ${this.peek()}`);\n }\n return {\n type: 'Atom',\n PatternCharacter: this.next(),\n };\n }", "function Molecule() {\n \n this.root = null;\n this.ident = \"\";\n}", "function parseOS2Table(data, start) {\n const os2 = {};\n const p = new _parse__WEBPACK_IMPORTED_MODULE_0__.default.Parser(data, start);\n os2.version = p.parseUShort();\n os2.xAvgCharWidth = p.parseShort();\n os2.usWeightClass = p.parseUShort();\n os2.usWidthClass = p.parseUShort();\n os2.fsType = p.parseUShort();\n os2.ySubscriptXSize = p.parseShort();\n os2.ySubscriptYSize = p.parseShort();\n os2.ySubscriptXOffset = p.parseShort();\n os2.ySubscriptYOffset = p.parseShort();\n os2.ySuperscriptXSize = p.parseShort();\n os2.ySuperscriptYSize = p.parseShort();\n os2.ySuperscriptXOffset = p.parseShort();\n os2.ySuperscriptYOffset = p.parseShort();\n os2.yStrikeoutSize = p.parseShort();\n os2.yStrikeoutPosition = p.parseShort();\n os2.sFamilyClass = p.parseShort();\n os2.panose = [];\n for (let i = 0; i < 10; i++) {\n os2.panose[i] = p.parseByte();\n }\n\n os2.ulUnicodeRange1 = p.parseULong();\n os2.ulUnicodeRange2 = p.parseULong();\n os2.ulUnicodeRange3 = p.parseULong();\n os2.ulUnicodeRange4 = p.parseULong();\n os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte());\n os2.fsSelection = p.parseUShort();\n os2.usFirstCharIndex = p.parseUShort();\n os2.usLastCharIndex = p.parseUShort();\n os2.sTypoAscender = p.parseShort();\n os2.sTypoDescender = p.parseShort();\n os2.sTypoLineGap = p.parseShort();\n os2.usWinAscent = p.parseUShort();\n os2.usWinDescent = p.parseUShort();\n if (os2.version >= 1) {\n os2.ulCodePageRange1 = p.parseULong();\n os2.ulCodePageRange2 = p.parseULong();\n }\n\n if (os2.version >= 2) {\n os2.sxHeight = p.parseShort();\n os2.sCapHeight = p.parseShort();\n os2.usDefaultChar = p.parseUShort();\n os2.usBreakChar = p.parseUShort();\n os2.usMaxContent = p.parseUShort();\n }\n\n return os2;\n}", "function atomLayout(atom, atoms, bonds, rotationAngle) {\n var textValue = atom.symbol;\n\n if (textValue === \"C\" && Object.keys(atoms).length !== 1) {\n // By convention, don't render the C for carbon in a chain.\n textValue = null;\n }\n\n if (atom.idx === \"1,0\") {\n // The first atom is special-cased because there are no neighbors for\n // relative positioning.\n var _pos = [0, 0];\n atom.pos = _pos; // Conventionally, molecules are rendered where the first bond is not\n // horizontal, but at a 30 degree angle, so subtract 30 degrees for the\n // first atom's direction.\n\n atom.baseAngle = -30 + rotationAngle;\n return {\n type: \"text\",\n value: textValue,\n pos: _pos,\n idx: atom.idx\n };\n } // If we're an atom with any other index than the case just handled, we're\n // guaranteed to have a neighbor who has a defined position.\n\n\n var prevPositionedAtom = atoms[atom.connections.find(function (c) {\n return atoms[c].pos;\n })]; // Find this atom's index in the previous atom's connections\n\n var myIndex = prevPositionedAtom.connections.indexOf(atom.idx);\n var baseAngleIncrement = 60;\n var angleIncrement = 120;\n\n if (prevPositionedAtom.connections.length === 4) {\n // By convention, if an atom has 4 bonds, we represent it with 90\n // degree angles in 2D, even though it would have tetrahedral geometry\n // with ~110 degree angles in 3D.\n angleIncrement = 90;\n baseAngleIncrement = 90;\n } else if (bonds.find(bond => bond.bondType === \"triple\" && bond.to === atom.idx) || bonds.find(bond => bond.bondType === \"triple\" && bond.to === prevPositionedAtom.idx)) {\n // Triple bonds have a bond angle of 180 degrees, so don't change the\n // direction in which we made the previous bond.\n angleIncrement = 0;\n baseAngleIncrement = 0;\n }\n\n var angle = 0;\n var idxPath = prevPositionedAtom.idx.split(\":\");\n var lastAtomIdx = idxPath[idxPath.length - 1].split(\",\")[0]; // Conventionally, a single chain of atoms is rendered as a zig-zag pattern\n // with 120 degree angles. This means we need to flip the angle every\n // other atom. The parser ensures that indices always alternate odd-even,\n // including taking into account branch points.\n // TODO(colin): don't depend on the parser's indexing scheme and just track\n // this entirely in the layout engine.\n\n if (parseInt(lastAtomIdx) % 2 !== 0) {\n angle = prevPositionedAtom.baseAngle - (baseAngleIncrement - angleIncrement * myIndex);\n } else {\n angle = prevPositionedAtom.baseAngle + (baseAngleIncrement - angleIncrement * myIndex);\n }\n\n var pos = polarAdd(prevPositionedAtom.pos, angle, bondLength);\n atom.pos = pos;\n atom.baseAngle = angle;\n return {\n type: \"text\",\n value: textValue,\n pos: pos,\n idx: atom.idx\n };\n}", "function importMolVector(str,chara) {\n var lines = str.split(chara);\n var output = [], line;\n\n for (var i=0; i<lines.length; i++) {\n line = lines[i].trim().split(\" \");\n output.push(line);\n }\n \n return output;\n}", "function parseOS2Table(data, start) {\n var os2 = {};\n var p = new parse.Parser(data, start);\n os2.version = p.parseUShort();\n os2.xAvgCharWidth = p.parseShort();\n os2.usWeightClass = p.parseUShort();\n os2.usWidthClass = p.parseUShort();\n os2.fsType = p.parseUShort();\n os2.ySubscriptXSize = p.parseShort();\n os2.ySubscriptYSize = p.parseShort();\n os2.ySubscriptXOffset = p.parseShort();\n os2.ySubscriptYOffset = p.parseShort();\n os2.ySuperscriptXSize = p.parseShort();\n os2.ySuperscriptYSize = p.parseShort();\n os2.ySuperscriptXOffset = p.parseShort();\n os2.ySuperscriptYOffset = p.parseShort();\n os2.yStrikeoutSize = p.parseShort();\n os2.yStrikeoutPosition = p.parseShort();\n os2.sFamilyClass = p.parseShort();\n os2.panose = [];\n for (var i = 0; i < 10; i++) {\n os2.panose[i] = p.parseByte();\n }\n\n os2.ulUnicodeRange1 = p.parseULong();\n os2.ulUnicodeRange2 = p.parseULong();\n os2.ulUnicodeRange3 = p.parseULong();\n os2.ulUnicodeRange4 = p.parseULong();\n os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte());\n os2.fsSelection = p.parseUShort();\n os2.usFirstCharIndex = p.parseUShort();\n os2.usLastCharIndex = p.parseUShort();\n os2.sTypoAscender = p.parseShort();\n os2.sTypoDescender = p.parseShort();\n os2.sTypoLineGap = p.parseShort();\n os2.usWinAscent = p.parseUShort();\n os2.usWinDescent = p.parseUShort();\n if (os2.version >= 1) {\n os2.ulCodePageRange1 = p.parseULong();\n os2.ulCodePageRange2 = p.parseULong();\n }\n\n if (os2.version >= 2) {\n os2.sxHeight = p.parseShort();\n os2.sCapHeight = p.parseShort();\n os2.usDefaultChar = p.parseUShort();\n os2.usBreakChar = p.parseUShort();\n os2.usMaxContent = p.parseUShort();\n }\n\n return os2;\n}", "function parseOS2Table(data, start) {\n var os2 = {};\n var p = new parse.Parser(data, start);\n os2.version = p.parseUShort();\n os2.xAvgCharWidth = p.parseShort();\n os2.usWeightClass = p.parseUShort();\n os2.usWidthClass = p.parseUShort();\n os2.fsType = p.parseUShort();\n os2.ySubscriptXSize = p.parseShort();\n os2.ySubscriptYSize = p.parseShort();\n os2.ySubscriptXOffset = p.parseShort();\n os2.ySubscriptYOffset = p.parseShort();\n os2.ySuperscriptXSize = p.parseShort();\n os2.ySuperscriptYSize = p.parseShort();\n os2.ySuperscriptXOffset = p.parseShort();\n os2.ySuperscriptYOffset = p.parseShort();\n os2.yStrikeoutSize = p.parseShort();\n os2.yStrikeoutPosition = p.parseShort();\n os2.sFamilyClass = p.parseShort();\n os2.panose = [];\n for (var i = 0; i < 10; i++) {\n os2.panose[i] = p.parseByte();\n }\n\n os2.ulUnicodeRange1 = p.parseULong();\n os2.ulUnicodeRange2 = p.parseULong();\n os2.ulUnicodeRange3 = p.parseULong();\n os2.ulUnicodeRange4 = p.parseULong();\n os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte());\n os2.fsSelection = p.parseUShort();\n os2.usFirstCharIndex = p.parseUShort();\n os2.usLastCharIndex = p.parseUShort();\n os2.sTypoAscender = p.parseShort();\n os2.sTypoDescender = p.parseShort();\n os2.sTypoLineGap = p.parseShort();\n os2.usWinAscent = p.parseUShort();\n os2.usWinDescent = p.parseUShort();\n if (os2.version >= 1) {\n os2.ulCodePageRange1 = p.parseULong();\n os2.ulCodePageRange2 = p.parseULong();\n }\n\n if (os2.version >= 2) {\n os2.sxHeight = p.parseShort();\n os2.sCapHeight = p.parseShort();\n os2.usDefaultChar = p.parseUShort();\n os2.usBreakChar = p.parseUShort();\n os2.usMaxContent = p.parseUShort();\n }\n\n return os2;\n}", "function create_atom(element, x, y, id) {\n\t// The Atom object\n\n\tif (id || id == 0) { // If id is specified\n\t\tvar a = new Atom(element, x, y, id);\n\t} else { // If id is not specified\n\t\tvar a = new Atom(element, x, y);\n\t}\n\n\t// If this is the first atom\n\tif (atoms.length == 0) {\n\t\t// active_atom = a;\n\t\t// a.fabric_atom.set(\"active\", true);\n\t\t// a.get_properties();\n\t\t$(\"#bondBtn\").html(\"Bond!\");\n\t\t$(\"#boSelect\").removeClass(\"hidden\");\n\t\t$(\"#boSelectLabel\").removeClass(\"hidden\");\n\t}\n\n\t// Add atom to the list of atoms\n\tif (id || id == 0) {\n\t\tatoms[id] = a;\n\t} else {\n\t\tatoms.push(a);\n\t}\n\n\t// Add the atom to the formula\n\tif (!formula_dict[element]) {\n\t\tformula_dict[element] = 1;\n\t} else {\n\t\tformula_dict[element] += 1;\n\t}\n\tupdate_formula();\n\n\n\treturn a;\n}" ]
[ "0.5408055", "0.51413727", "0.50928223", "0.5089889", "0.50736403", "0.5037518", "0.49817997", "0.4725309", "0.46532357", "0.45925558", "0.45044145", "0.44910482", "0.44699952", "0.4374528", "0.43132514", "0.43111685", "0.42993292", "0.4295641", "0.42842823", "0.42659193", "0.4230504", "0.4215828", "0.42121038", "0.42105782", "0.41991338", "0.41914672", "0.41647214", "0.4164265", "0.4164265", "0.416135" ]
0.56767416
0
Populates edge array based on vertices and faces.
computeEdges() { // array of arrays of edges this.edges = []; // map of vertex pairs to edge indices var vertexPairs = new Map(); let len = this.body.shapes[0].vertices.length; var faces = this.body.shapes[0].faces; faces.forEach(f => { var loop = []; for (var i = 0; i < f.length; i++) { // get index of each point var a = f[i]; var b = f[(i + 1) % f.length]; if (vertexPairs.has(a * len + b)) { loop.push(vertexPairs.get(a * len + b)); } else { // create new edge var edge = {a: a, b: b}; var reverse = {a: b, b: a}; edge.reverse = reverse; reverse.reverse = edge; // save edge vertexPairs.set(a * len + b, edge); vertexPairs.set(b * len + a, reverse); loop.push(edge); } } this.edges.push(loop); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function faceEdges(face) {\n var n = face.length,\n edges = [];\n for (var a = face[n - 1], i = 0; i < n; ++i) {\n edges.push([a, a = face[i]]);\n }return edges;\n}", "function faceEdges(face) {\n var n = face.length,\n edges = [];\n for (var a = face[n - 1], i = 0; i < n; ++i) edges.push([a, a = face[i]]);\n return edges;\n}", "function faceEdges(face) {\n var n = face.length,\n edges = [];\n for (var a = face[n - 1], i = 0; i < n; ++i) edges.push([a, a = face[i]]);\n return edges;\n}", "addVertices() {\n this.vertices = [];\n for (var i = 0; i < this.edges.length; i++) {\n var edge = this.edges[i];\n var start = edge.startVertex;\n var end = edge.endVertex;\n this.addVertex(start);\n this.addVertex(end);\n }\n }", "createEdges() {\n\n\t\tconst lines = this.edges;\n\t\tconst planes = this.planes;\n\t\tconst edgeMaterial = this.edgeMaterials[0];\n\t\tconst planeMaterial = this.planeMaterials[0];\n\t\tconst edges = this.hermiteData.edgeData.edges(this.cellPosition, this.cellSize);\n\n\t\tconst intersection = new Vector3();\n\n\t\tthis.clearEdges();\n\n\t\tfor(const edge of edges) {\n\n\t\t\tconst lineGeometry = new BufferGeometry();\n\t\t\tconst lineVertices = new Float32Array(6);\n\n\t\t\tedge.a.toArray(lineVertices);\n\t\t\tedge.b.toArray(lineVertices, 3);\n\n\t\t\tlineGeometry.setAttribute(\"position\", new BufferAttribute(lineVertices, 3));\n\t\t\tconst line = new Line(lineGeometry, edgeMaterial);\n\t\t\tlines.add(line);\n\n\t\t\tconst plane = new Mesh(new PlaneBufferGeometry(2, 2), planeMaterial);\n\t\t\tplane.position.copy(edge.computeZeroCrossingPosition(intersection));\n\t\t\tplane.lookAt(intersection.add(edge.n));\n\t\t\tplane.visible = false;\n\t\t\tplanes.add(plane);\n\n\t\t}\n\n\t}", "function initFaces(){\n\tf = [];\n\tfor (var o=0; o<faceObject.length; o+=1){\n\t\tfor (var i=0; i<faceObject[o].length; i+=1){\n\t\t\tf.push(faceObject[o][i]);\n\t\t}\n\t}\n}", "linkFacePointsToEdgePoints()\n {\n // Parcourt de toutes les faces pour lier le face point des faces aux edge points de chaque edge de la face\n for(var i = 0; i < this.polygones.length; ++i)\n {\n var tmpFacePoint = this.polygones[i].facePoint; \n var tmpEdges = this.polygones[i].edges;\n \n // Parcout des edges du polygone pour ajouter les edgesPoints et les nouvelles edges\n for(var j = 0; j < tmpEdges.length; ++j)\n {\n // Ajout de l'edge point dans la liste des vertice\n var tmpEdgePoint = tmpEdges[j].edgePoint;\n\n // Ajout de la nouvelle edge (facePoint --------- EdgePoint)\n if(this.hasEdge(tmpFacePoint, tmpEdgePoint) == false)\n {\n this.pushCatmullClarkEdge(new Edge(tmpFacePoint, tmpEdgePoint));\n }\n } \n }\n }", "generateLines() {\r\n for (var f = 0; f < this.faceData.length/3; f++) {\r\n // Calculate index of the face\r\n var fid = f*3;\r\n this.edgeData.push(this.faceData[fid]);\r\n this.edgeData.push(this.faceData[fid+1]);\r\n\r\n this.edgeData.push(this.faceData[fid+1]);\r\n this.edgeData.push(this.faceData[fid+2]);\r\n\r\n this.edgeData.push(this.faceData[fid+2]);\r\n this.edgeData.push(this.faceData[fid]);\r\n }\r\n }", "generateLines() {\r\n for (var f = 0; f < this.faceData.length/3; f++) {\r\n // Calculate index of the face\r\n var fid = f*3;\r\n this.edgeData.push(this.faceData[fid]);\r\n this.edgeData.push(this.faceData[fid+1]);\r\n \r\n this.edgeData.push(this.faceData[fid+1]);\r\n this.edgeData.push(this.faceData[fid+2]);\r\n \r\n this.edgeData.push(this.faceData[fid+2]);\r\n this.edgeData.push(this.faceData[fid]);\r\n }\r\n }", "function initializeEdges() {\n edges = [\n [5, 0, 1],\n [2, 0, 2],\n [10, 0, 3],\n [7, 1, 4],\n [4, 2, 5],\n [1, 1, 3],\n [5, 2, 3],\n [6, 3, 4],\n [3, 3, 6],\n [11, 3, 5],\n [13, 4, 6],\n [9, 5, 6]\n ]\n}", "_addNewFaces( vertex, horizon ) {\n\n\t\tconst newFaces = [];\n\n\t\tlet firstSideEdge = null;\n\t\tlet previousSideEdge = null;\n\n\t\tfor ( let i = 0, l = horizon.length; i < l; i ++ ) {\n\n\t\t\t// returns the right side edge\n\n\t\t\tlet sideEdge = this._addAdjoiningFace( vertex, horizon[ i ] );\n\n\t\t\tif ( firstSideEdge === null ) {\n\n\t\t\t\tfirstSideEdge = sideEdge;\n\n\t\t\t} else {\n\n\t\t\t\t// joins face.getEdge( 1 ) with previousFace.getEdge( 0 )\n\n\t\t\t\tsideEdge.next.linkOpponent( previousSideEdge );\n\n\t\t\t}\n\n\t\t\tnewFaces.push( sideEdge.polygon );\n\t\t\tpreviousSideEdge = sideEdge;\n\n\t\t}\n\n\t\t// perform final join of new faces\n\n\t\tfirstSideEdge.next.linkOpponent( previousSideEdge );\n\n\t\treturn newFaces;\n\n\t}", "getOrientedEdges() {\n var edge = this.edges[0];\n var edges = [edge];\n var used = new Set();\n used.add(edge);\n var vertices = [];\n vertices.push(edge.startVertex);\n vertices.push(edge.endVertex);\n for (var i = 1; i < this.edges.length; i++) {\n var res = this.getNextEdge(edge, used, vertices);\n edge = res.edge;\n vertices.push(res.vertex);\n edges.push(edge);\n used.add(edge);\n }\n // console.log(\"oriented edges\", edges, vertices);\n return vertices;\n }", "edgesForFaceId(face_id, geometry) {\n return geometry.faces.find(f => f.id === face_id)\n .edgeRefs.map(eR => this.edgeForId(eR.edge_id, geometry));\n }", "function findEdges() {\r\n\t\tedges = [];\r\n\t\tnumFaces = faces.length;\r\n\t\tnumEdges = 3;\r\n\t\tfor(var i=0; i<numFaces; i++){\r\n\t\t\tvar face = [getUniqueIndex(faces[i].a),\r\n\t\t\t\t\t\tgetUniqueIndex(faces[i].b),\r\n\t\t\t\t\t\tgetUniqueIndex(faces[i].c)];\r\n\t\t\tfor(var j=0; j<numEdges; j++){\r\n\t\t\t\tvar newEdge = [face[j], face[(j+1) % numEdges]];\r\n\t\t\t\tif(newEdge[0] < newEdge[1]) { newEdge.reverse(); }\r\n\t\t\t\tif(isEdgeUnique(edges, newEdge)) { edges.push(newEdge); }\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn edges;\r\n\t}", "initializeEdgeIndex() {\n let counter = 0;\n for (let i = 0; i < this.n; ++i) // iterate over nodes\n {\n for (let j = 0; j < this.m; ++j) {\n if (i != this.n - 1 && j != this.m - 1) { // if the node is not from the last row \n this.edge_index[counter] = i * this.m + j; // and not from the last column we add to\n ++counter // the array edge that goes down and the edge \n this.edge_index[counter] = i * this.m + j + 1; // that goes to the right\n ++counter;\n this.edge_index[counter] = i * this.m + j;\n ++counter;\n this.edge_index[counter] = (i + 1) * this.m + j;\n ++counter;\n }\n if (i != this.n - 1 && j == this.m - 1) { // similar to the rest of cases\n this.edge_index[counter] = i * this.m + j;\n ++counter;\n this.edge_index[counter] = (i + 1) * this.m + j;\n ++counter;\n }\n if (i == this.n - 1 && j != this.m - 1) {\n this.edge_index[counter] = i * this.m + j;\n ++counter\n this.edge_index[counter] = i * this.m + j + 1;\n ++counter;\n }\n }\n }\n }", "function makeEdges(){\n\t\n\tvar edgeList =[];\n\tfor (var i = 0; i < Maze.cells.length; i++) {\n\t\tfor (var j = 0; j < Maze.cells[i].length-1; j++) {\n\t\t\tvar edge =[];\n\t\t\t//if cells are on top row \n\t\t\tvar current = Maze.cells[i][j];\n\t\t\tvar leftCell = Maze.cells[i][j+1];\n\t\t\tedge.push(current,leftCell);\n\t\t\tedgeList.push(edge);\n\t\t\tif(i != 0){\n\t\t\t\tvar topCell = Maze.cells[i-1][j];\n\t\t\t\tvar edge =[];\n\t\t\t\tedge.push(current,topCell);\n\t\t\t\tedgeList.push(edge);\n\t\t\t}\n\t\t}\n\t}\n\n\t//make edgelist for last column for all rows\n\tfor(var i = 0; i < Maze.cells.length-1;i++){\n\t\tvar edge =[];\n\t\tedge.push(Maze.cells[i][Maze.cols-1]);\n\t\tedge.push(Maze.cells[i+1][Maze.cols-1]);\n\t\tedgeList.push(edge);\n\t}\n\n\treturn edgeList;\n}", "function newEdgesArray(array) {\r\n\tlet rez= new Array();\r\n\trez[0]=array[0];\r\n\trez[1]=array[array.length-1];\r\n\treturn rez\r\n}", "vertexAdjacentFaces() {\n return flatMapUniq(\n this.vertices,\n vertex => vertex.adjacentFaces(),\n 'index',\n );\n }", "function update_graph_edges(edges) {\n\t\t$.each(edges, function (i, edge) {\n\t\t\tvar edge_id = edge[\"id\"];\n\t\t\tvar ele = g.elements(\"edge\" + \"[id='\" + edge_id + \"']\")[0];\n\t\t\tif (ele) {\n\t\t\t\tele.data(edge);\n\t\t\t}\n\t\t\telse {\n\t\t\t\talert(edge_id + \" no ele\");\n\t\t\t}\n\t\t});\n\t}", "function prepareEdgeData() {\n //First only keep the edges that exist in the node list\n edges = edges.filter(function (d) {\n return node_by_id[d.source] && node_by_id[d.target];\n });\n linked_to_id = {};\n edges.forEach(function (d) {\n d.id = d.source + ',' + d.target;\n edge_by_id[d.id] = true; //Save all of the edges to a specific node\n\n if (!linked_to_id[d.source]) linked_to_id[d.source] = [];\n if (!linked_to_id[d.target]) linked_to_id[d.target] = [];\n linked_to_id[d.source].push(node_by_id[d.target]);\n linked_to_id[d.target].push(node_by_id[d.source]); //Save default specific stylings\n\n d.focus = 'secondary';\n d.opacity = edge_secondary_opacity;\n d.stroke_hidden = genColor(); //A unique rgb color for the edge hover later on\n\n color_to_edge[d.stroke_hidden] = d; //Save a mapping of the color to the edge\n }); //forEach\n } //function prepareEdgeData", "function buildSideFaces() {\n\n\t\tvar start = verticesArray.length/3;\n\t\tvar layeroffset = 0;\n\t\tsidewalls( contour, layeroffset );\n\t\tlayeroffset += contour.length;\n\n\t\tfor ( h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\tahole = holes[ h ];\n\t\t\tsidewalls( ahole, layeroffset );\n\n\t\t\t//, true\n\t\t\tlayeroffset += ahole.length;\n\n\t\t}\n\n\n\t\tscope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);\n\n\n\t}", "function buildSideFaces() {\n\n\t\tvar start = verticesArray.length/3;\n\t\tvar layeroffset = 0;\n\t\tsidewalls( contour, layeroffset );\n\t\tlayeroffset += contour.length;\n\n\t\tfor ( h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\tahole = holes[ h ];\n\t\t\tsidewalls( ahole, layeroffset );\n\n\t\t\t//, true\n\t\t\tlayeroffset += ahole.length;\n\n\t\t}\n\n\n\t\tscope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);\n\n\n\t}", "function buildSideFaces() {\n\n\t\tvar start = verticesArray.length/3;\n\t\tvar layeroffset = 0;\n\t\tsidewalls( contour, layeroffset );\n\t\tlayeroffset += contour.length;\n\n\t\tfor ( h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\tahole = holes[ h ];\n\t\t\tsidewalls( ahole, layeroffset );\n\n\t\t\t//, true\n\t\t\tlayeroffset += ahole.length;\n\n\t\t}\n\n\n\t\tscope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);\n\n\n\t}", "function buildSideFaces() {\n\n\t\tvar start = verticesArray.length/3;\n\t\tvar layeroffset = 0;\n\t\tsidewalls( contour, layeroffset );\n\t\tlayeroffset += contour.length;\n\n\t\tfor ( h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\tahole = holes[ h ];\n\t\t\tsidewalls( ahole, layeroffset );\n\n\t\t\t//, true\n\t\t\tlayeroffset += ahole.length;\n\n\t\t}\n\n\n\t\tscope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);\n\n\n\t}", "function buildSideFaces() {\n\n\t\tvar start = verticesArray.length/3;\n\t\tvar layeroffset = 0;\n\t\tsidewalls( contour, layeroffset );\n\t\tlayeroffset += contour.length;\n\n\t\tfor ( h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\tahole = holes[ h ];\n\t\t\tsidewalls( ahole, layeroffset );\n\n\t\t\t//, true\n\t\t\tlayeroffset += ahole.length;\n\n\t\t}\n\n\n\t\tscope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);\n\n\n\t}", "function buildSideFaces() {\n\n\t\tvar start = verticesArray.length/3;\n\t\tvar layeroffset = 0;\n\t\tsidewalls( contour, layeroffset );\n\t\tlayeroffset += contour.length;\n\n\t\tfor ( h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\tahole = holes[ h ];\n\t\t\tsidewalls( ahole, layeroffset );\n\n\t\t\t//, true\n\t\t\tlayeroffset += ahole.length;\n\n\t\t}\n\n\n\t\tscope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);\n\n\n\t}", "function buildSideFaces() {\n\n\t\tvar start = verticesArray.length/3;\n\t\tvar layeroffset = 0;\n\t\tsidewalls( contour, layeroffset );\n\t\tlayeroffset += contour.length;\n\n\t\tfor ( h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\tahole = holes[ h ];\n\t\t\tsidewalls( ahole, layeroffset );\n\n\t\t\t//, true\n\t\t\tlayeroffset += ahole.length;\n\n\t\t}\n\n\n\t\tscope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);\n\n\n\t}", "function buildSideFaces() {\n\n\t\tvar start = verticesArray.length/3;\n\t\tvar layeroffset = 0;\n\t\tsidewalls( contour, layeroffset );\n\t\tlayeroffset += contour.length;\n\n\t\tfor ( h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\tahole = holes[ h ];\n\t\t\tsidewalls( ahole, layeroffset );\n\n\t\t\t//, true\n\t\t\tlayeroffset += ahole.length;\n\n\t\t}\n\n\n\t\tscope.addGroup( start, verticesArray.length/3 -start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1);\n\n\n\t}", "function buildSideFaces() {\n\n\t\t\tvar start = verticesArray.length / 3;\n\t\t\tvar layeroffset = 0;\n\t\t\tsidewalls( contour, layeroffset );\n\t\t\tlayeroffset += contour.length;\n\n\t\t\tfor ( h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\t\tahole = holes[ h ];\n\t\t\t\tsidewalls( ahole, layeroffset );\n\n\t\t\t\t//, true\n\t\t\t\tlayeroffset += ahole.length;\n\n\t\t\t}\n\n\n\t\t\tscope.addGroup( start, verticesArray.length / 3 - start, 1 );\n\n\n\t\t}", "function buildSideFaces() {\n\n\t\t\tvar start = verticesArray.length / 3;\n\t\t\tvar layeroffset = 0;\n\t\t\tsidewalls( contour, layeroffset );\n\t\t\tlayeroffset += contour.length;\n\n\t\t\tfor ( h = 0, hl = holes.length; h < hl; h ++ ) {\n\n\t\t\t\tahole = holes[ h ];\n\t\t\t\tsidewalls( ahole, layeroffset );\n\n\t\t\t\t//, true\n\t\t\t\tlayeroffset += ahole.length;\n\n\t\t\t}\n\n\n\t\t\tscope.addGroup( start, verticesArray.length / 3 - start, 1 );\n\n\n\t\t}" ]
[ "0.6657784", "0.64646196", "0.64646196", "0.6414725", "0.63792056", "0.6263822", "0.6261526", "0.6238883", "0.6238728", "0.6108731", "0.60213214", "0.6017071", "0.5946632", "0.5846974", "0.5739629", "0.5691505", "0.567306", "0.5646524", "0.55966413", "0.5534578", "0.5532781", "0.5532781", "0.5532781", "0.5532781", "0.5532781", "0.5532781", "0.5532781", "0.5532781", "0.5484119", "0.5484119" ]
0.69835246
0
Copy position from physics simulation to rendered mesh
update() { this.mesh.position.copy(this.body.position); this.mesh.quaternion.copy(this.body.quaternion); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "setWorldPosition(position, update = false){ \n let new_pos = this.getParentSpaceMatrix().getInverse().times(position)\n let pp_r_s_inv = Matrix3x3.Translation(new_pos).times(\n Matrix3x3.Rotation(this.getRotation()).times(\n Matrix3x3.Scale(this.getScale())\n )).getInverse()\n let new_a_mat = pp_r_s_inv.times(this.matrix)\n this.setPosition(new_pos, update)\n this.setAnchorShift(new Vec2(new_a_mat.m02, new_a_mat.m12))\n this.updateMatrixProperties()\n }", "refreshFromPhysics() {\n //2D\n this.position.set(this.physicsObj.position.x,this.physicsObj.position.y);\n }", "refreshFromPhysics() {\n this.position.copy(this.physicsObj.position);\n this.quaternion.copy(this.physicsObj.quaternion);\n this.velocity.copy(this.physicsObj.velocity);\n this.angularVelocity.copy(this.physicsObj.angularVelocity);\n }", "refreshFromPhysics() {\n this.position.copy(this.physicsObj.position);\n this.quaternion.copy(this.physicsObj.quaternion);\n this.velocity.copy(this.physicsObj.velocity);\n this.angularVelocity.copy(this.physicsObj.angularVelocity);\n }", "update_positions() {\n let positions = this.vertex_positions;\n for (var i = 0; i < this.vertices.length; i++) {\n positions[i * 3] = this.vertices[i].x;\n positions[i * 3 + 1] = this.vertices[i].y;\n positions[i * 3 + 2] = this.vertices[i].z;\n }\n this.geometry.attributes.position.needsUpdate = true;\n }", "_setWorldPosition() {\n // dimensions and positions of our plane in the document and clip spaces\n // don't forget translations in webgl space are referring to the center of our plane and canvas\n const planeCenter = {\n x: (this._boundingRect.document.width / 2) + this._boundingRect.document.left,\n y: (this._boundingRect.document.height / 2) + this._boundingRect.document.top,\n };\n\n const containerCenter = {\n x: (this.renderer._boundingRect.width / 2) + this.renderer._boundingRect.left,\n y: (this.renderer._boundingRect.height / 2) + this.renderer._boundingRect.top,\n };\n\n this._boundingRect.world.top = ((containerCenter.y - planeCenter.y) / this.renderer._boundingRect.height) * this._boundingRect.world.ratios.height;\n this._boundingRect.world.left = ((planeCenter.x - containerCenter.x) / this.renderer._boundingRect.width) * this._boundingRect.world.ratios.width;\n }", "get position() { return p5.prototype.createVector(0, this.height + Earth.RADIUS, 0); }", "sendToStartPos() {\n this.x = this.spawnX;\n this.y = this.spawnY;\n }", "@autobind\n toScreenPosition(vec) {\n var targetVec = this.mesh.localToWorld(vec.clone());\n targetVec.project( this.camera );\n targetVec.x = (( targetVec.x ) * (this.windowWidth*0.5)) + (this.windowWidth * 0.5) ;\n targetVec.y = (( targetVec.y * -1 ) * (this.windowHeight*0.5)) + (this.windowHeight * 0.5) ;\n return targetVec;\n }", "adjustPosition() {\n //this.geometry.applyMatrix( new THREE.Matrix4().makeTranslation( -(this.width / 2), 0, -(this.height / 2)) );\n this.geometry.translate(-(this.width / 2), 0, -(this.height / 2));\n }", "physicsSetPosition(x, y, z) {\n\n\t if(x) {\n if (typeof this.scale !== \"undefined\") {\n //y -= (this.scale * this.size.y);\n }\n\n y -= 5;\n\n this.physics_vector = new THREE.Vector3(x, y, z);\n\n this.getModel().position.set(x, y, z);\n this.position.set(x, y, z);\n } else {\n\t //this.getModel().position.set(this.position.clone());\n }\n\n }", "updateLayout(position, rotation, up) {\r\n this.originalPosition = position.clone();\r\n this.originalRotation = rotation.clone();\r\n this.originalUp = up.clone();\r\n\r\n this.object.position.copy(position);\r\n this.object.rotation.copy(rotation);\r\n this.mesh.position.copy(position);\r\n this.mesh.rotation.copy(rotation);\r\n this.mesh.up = up;\r\n }", "update_positions() {\n let positions = this.vertex_positions;\n for (var i = 0; i < this.vertices.length; i++) {\n positions[i * 3] = this.vertices[i].x;\n positions[i * 3 + 1] = this.vertices[i].y;\n positions[i * 3 + 2] = this.vertices[i].z;\n }\n this.attributes.position.needsUpdate = true;\n }", "setPosition(newPos) {\n let difference = p5.Vector.sub(newPos, this.pixelCenter);\n difference.rotate(-this.body.angle);\n\n for (var i = 0; i < this.pixelVectorPositions.length; i++) {\n this.pixelVectorPositions[i].x += difference.x;\n this.pixelVectorPositions[i].y += difference.y;\n }\n\n this.setCenter();\n this.setShape();\n this.resetFixture();\n }", "function simulate(stepSize) {\n\tnewPosition = new Array(meshResolution*meshResolution);\n newVelocity = new Array(meshResolution*meshResolution);\n\n for(i = 0; i < meshResolution*meshResolution; ++i) {\n newPosition[i] = vec3.create();\n newVelocity[i] = vec3.create();\n }\n\n for (i = 0; i < meshResolution; ++i) {\n for (j = 0; j < meshResolution; ++j) {\n \t\n \tvar temp = meshResolution - 1;\n var gravity = vec3.create();\n \n gravity[1] = gravity[1] - mass * 9.8;\n vec3.add(gravity, vec3.scale(getVelocity(i, j), -Cd));\n vec3.add(gravity, vec3.scale(getNormal(i, j), Cv * vec3.dot(getNormal(i , j), vec3.subtract(vec3.create(uf), getVelocity(i, j)))));\n\n // structural\n if (j < temp) {\n vec3.add(gravity, springForce(getPosition(i, j), getPosition(i, j + 1), 0));\n }\n\n if (j > 0) {\n vec3.add(gravity, springForce(getPosition(i, j), getPosition(i, j - 1), 0));\n }\n\n if (i < temp) {\n vec3.add(gravity, springForce(getPosition(i, j), getPosition(i + 1, j), 0));\n }\n\n if (i > 0) {\n vec3.add(gravity, springForce(getPosition(i, j), getPosition(i - 1, j), 0));\n }\n \n // shear\n if (i < temp && j < temp) {\n vec3.add(gravity, springForce(getPosition(i, j),getPosition(i + 1, j + 1), 1));\n }\n\n if (i < temp && j > 0) {\n vec3.add(gravity, springForce(getPosition(i, j), getPosition(i + 1, j - 1), 1));\n }\n\n if (i > 0 && j > 0) {\n vec3.add(gravity, springForce(getPosition(i, j), getPosition(i - 1, j - 1), 1));\n }\n\n if (i > 0 && j < temp) {\n vec3.add(gravity, springForce(getPosition(i, j), getPosition(i - 1, j + 1), 1));\n }\n \n // flexion\n if (j < temp - 1) {\n vec3.add(gravity, springForce(getPosition(i, j), getPosition(i, j + 2), 2));\n }\n\n if (j > 1) {\n vec3.add(gravity, springForce(getPosition(i, j), getPosition(i, j - 2), 2));\n }\n \n if (i < temp - 1) {\n vec3.add(gravity, springForce(getPosition(i, j), getPosition(i + 2, j), 2));\n }\n\n if (i > 1) {\n vec3.add(gravity, springForce(getPosition(i, j), getPosition(i - 2, j), 2));\n }\n\n if ((i == temp && j == 0) || (i == temp && j == temp)) {\n newPosition[i * meshResolution + j] = getPosition(i, j);\n }\n\n else {\n newVelocity[i * meshResolution + j] = vec3.add(getVelocity(i, j), vec3.scale(gravity, stepSize/mass));\n newPosition[i * meshResolution + j] = vec3.add(getPosition(i, j), vec3.scale(vec3.create(newVelocity[i * meshResolution + j]), stepSize));\n }\n }\n }\n\n for (i = 0; i < meshResolution; ++i) {\n for (j = 0; j < meshResolution; ++j) {\n setPosition(i, j, newPosition[i * meshResolution + j]);\n setVelocity(i, j, newVelocity[i * meshResolution + j]);\n }\n } \n}", "update () {\n this.position = [this.x, this.y];\n }", "updatePosition(position) {\n if (position == null)\n return;\n const positionNodes = parseExpressions(position)[0].terms;\n for (let i = 0; i < 3; ++i) {\n this.position.setComponent(i, normalizeUnit(positionNodes[i]).number);\n }\n this.updateMatrixWorld();\n }", "refreshToPhysics() {\n this.physicsObj.position.copy(this.position);\n this.physicsObj.quaternion.copy(this.quaternion);\n this.physicsObj.velocity.copy(this.velocity);\n this.physicsObj.angularVelocity.copy(this.angularVelocity);\n }", "setPosition(gl, x, y, z) {\n this.x = x;\n this.y = y;\n this.z = z;\n\n let translatedPositions = [];\n gl.bindBuffer(gl.ARRAY_BUFFER, this.buffers.position);\n translatedPositions = this.sourcePositions.slice();\n let i = 0;\n for (i = 0; i < 12 * this.treeLOD; i++) {\n translatedPositions[i * 3] += this.x;\n translatedPositions[i * 3 + 1] += this.y;\n translatedPositions[i * 3 + 2] += this.z;\n }\n\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(translatedPositions), gl.STATIC_DRAW);\n \n }", "setFrom(pos)\n\t{\n\t\tthis.x = pos.x;\n\t\tthis.y = pos.y;\n\t\tthis.worldSpace = pos.worldSpace;\n\t}", "lockPosition() {\n const x = Math.round(this.fixedPositionVector.x);\n const y = Math.round(this.fixedPositionVector.y);\n const z = Math.round(this.fixedPositionVector.z);\n this.positionVector = new THREE.Vector3(x, y, z);\n this.fixedPositionVector = new THREE.Vector3(x, y, z);\n\n this.mesh.position.x = x;\n this.mesh.position.y = y;\n this.mesh.position.z = z;\n this.stickers.forEach((sticker) => {\n sticker.lockPosition();\n });\n }", "refreshToPhysics() {\n //2D setup needed\n this.physicsObj.position.x = this.position.x;\n this.physicsObj.position.y = this.position.y;\n this.physicsObj.angle = this.angle;\n\n //3D\n //this.physicsObj.position.copy(this.position);\n //this.physicsObj.quaternion.copy(this.quaternion);\n //this.physicsObj.velocity.copy(this.velocity);\n //this.physicsObj.angularVelocity.copy(this.angularVelocity);\n }", "function updateTopMesh(){\n\tif(typeof crystalmesh != 'undefined'){\n\t\tcrystalmesh.position.y=currentTowerHeight;\n\t}\n}", "setPosition(newPos) {\n let difference = p5.Vector.sub(newPos, this.pixelCenter);\n difference.rotate(-this.body.angle);\n this.x += difference.x;\n this.y += difference.y;\n this.center = createVector(this.x + this.w / 2, this.y + this.h / 2);\n this.calculateVectorsAndSetShape();\n this.resetFixture();\n }", "refreshFromPhysics() {\n this.copyVector(this.physicsObj.position, this.position);\n this.copyVector(this.physicsObj.velocity, this.velocity);\n this.angle = this.physicsObj.angle;\n this.angularVelocity = this.physicsObj.angularVelocity;\n }", "updatePosition() {\n // set the new plane sizes and positions relative to document by triggering getBoundingClientRect()\n this._setDocumentSizes();\n\n // apply them\n this._applyWorldPositions();\n }", "setPosition(newPos) {\n let difference = p5.Vector.sub(newPos, this.pixelCenter);\n difference.rotate(-this.body.angle);\n\n this.x += difference.x;\n this.y += difference.y;\n this.setCenter();\n this.setShape();\n this.resetFixture();\n }", "function setMeshRandomPos(mesh) {\n mesh.position.x = getRandomIntInclusive(-20, 20);\n mesh.position.y = getRandomIntInclusive(-10, 10);\n mesh.position.z = getRandomIntInclusive(-20, 20);\n}", "function sync(dt) {\n let ms = body.getMotionState();\n if (ms) {\n ms.getWorldTransform(transform_aux);\n let p = transform_aux.getOrigin();\n let q = transform_aux.getRotation();\n mesh.position.set(p.x(), p.y(), p.z());\n mesh.quaternion.set(q.x(), q.y(), q.z(), q.w());\n }\n }", "refreshToPhysics() {\n if (!this.physicsObj) return\n this.physicsObj.position.copy(this.position);\n this.physicsObj.quaternion.copy(this.quaternion);\n this.physicsObj.velocity.copy(this.velocity);\n this.physicsObj.angularVelocity.copy(this.angularVelocity);\n }" ]
[ "0.6462523", "0.6387515", "0.63394743", "0.6281849", "0.6277799", "0.62772626", "0.62642735", "0.62021154", "0.6199623", "0.61876595", "0.6187237", "0.61652184", "0.61549556", "0.61295533", "0.60690415", "0.60180783", "0.60169667", "0.60156226", "0.60047966", "0.5997315", "0.59845215", "0.5981102", "0.59778875", "0.59727633", "0.5951513", "0.5930504", "0.5919638", "0.5914997", "0.590662", "0.5886472" ]
0.70207316
0
Ace refuses to render all changes immediately
function renderChanges() { ui.editor.ace.renderer.updateFull(true); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function editOnCompositionStart(){this.setRenderGuard();this.setMode('composite');this.update(EditorState.set(this.props.editorState,{inCompositionMode:true}));}", "function setupEditor() {\n window.editor = ace.edit(\"editor\");\n editor.setTheme(\"ace/theme/monokai\");\n editor.getSession().setMode(\"ace/mode/html\");\n editor.setValue(``, 1); //1 = moves cursor to end\n\n\n\n\n document.getElementById('iframe').addEventListener('mouseover', function() {\n update();\n });\n\n editor.focus();\n\n//The font size and some others setting to the code editor\n editor.setOptions({\n fontSize: \"14pt\",\n showLineNumbers: true,\n showGutter: true,\n vScrollBarAlwaysVisible: true,\n enableBasicAutocompletion: false,\n enableLiveAutocompletion: false\n });\n\n editor.setShowPrintMargin(false);\n editor.setBehavioursEnabled(false);\n}", "function editOnCompositionStart() {\n\t this.setRenderGuard();\n\t this.setMode('composite');\n\t this.update(EditorState.set(this.props.editorState, { inCompositionMode: true }));\n\t}", "function enableEditor(){\n var editor = ace.edit(\"editor\");\n editor.focus();\n editor.setReadOnly(false);\n editor.container.style.opacity=1;\n}", "loadEditors() {\r\n\r\n // Loading content for HTML editor\r\n this.editorHTML = ace.edit('editorHTML')\r\n this.editorHTML.setTheme('ace/theme/sqlserver')\r\n this.editorHTML.session.setMode('ace/mode/html')\r\n let htmlDoc = '<!DOCTYPE html>\\n<html>\\n<head>\\n\\t<meta charset=\"UTF-8\">\\n\\t<title>LWE</title>\\n</head>\\n<body>\\n\\t<div id=\"welcome\">\\n\\t\\t<h1 id=\"title\">Welcome to Live Web Editor</h1>\\n\\t\\t<p>Execute HTML, CSS and JavaScript code in real time quickly and easily</p>\\n\\t\\t<p>Wherever you want, whenever you want</p>\\n\\t</div>\\n</body>\\n</html>'\r\n this.editorHTML.insert(htmlDoc)\r\n this.editorHTML.gotoLine(11,53)\r\n this.editorHTML.setShowPrintMargin(false)\r\n\r\n // Loading content for CSS editor\r\n this.editorCSS = ace.edit('editorCSS')\r\n this.editorCSS.setTheme('ace/theme/sqlserver')\r\n this.editorCSS.session.setMode('ace/mode/css')\r\n let cssDoc = '* {\\n\\tmargin: 0;\\n\\tpadding: 0;\\n}\\n\\n#welcome {\\n\\tfont-family: \"Segoe UI\";\\n\\ttext-align: center;\\n\\tmargin-top: 15%;\\n}\\n\\n#welcome h1 {\\n\\tcolor: #87CEEB;\\n}\\n\\n#welcome p {\\n\\tcolor: #009DA3;\\n}'\r\n this.editorCSS.insert(cssDoc)\r\n this.editorCSS.gotoLine(17,16)\r\n this.editorCSS.setShowPrintMargin(false)\r\n\r\n // Loading content for JS editor\r\n this.editorJS = ace.edit('editorJS')\r\n this.editorJS.setTheme('ace/theme/sqlserver')\r\n this.editorJS.session.setMode('ace/mode/javascript')\r\n let jsDoc = '// Your code here...'\r\n this.editorJS.insert(jsDoc)\r\n this.editorJS.gotoLine(1, 20)\r\n this.editorJS.setShowPrintMargin(false)\r\n \r\n }", "function codeEditor(lang_id) {\n var editor = ace.edit(\"editor\");\n editor.setTheme(\"ace/theme/monokai\");\n $(document).ready(function () {\n $(\"button\").click(function () {\n let code = editor.getValue();\n let input = document.getElementById('inputbox').value;\n $(\"#outputbox\").html(\"Compiling...\");\n let data = {\n source_code: code,\n language_id: lang_id,\n stdin: input,\n };\n let request = $.ajax({\n url: BASE_URL,\n type: \"post\",\n data: data,\n });\n request.done(async function (response, textStatus, jqXHR) {\n if(response.status.id==3){\n console.log(response);\n $(\"#outputbox\").html(response.stdout);\n } else{\n $(\"#outputbox\").html(response.status.description);\n }\n theButton.classList.remove(\"button--loading\");\n \n });\n });\n });\n\n if(lang_id==PYTHON_KEY){\n editor.setValue(`def execute(): \\n\\t for i in range(10):\\n\\t\\t print i \\nexecute()`)\n editor.getSession().setMode(\"ace/mode/python\");\n document.getElementById('inputbox').value = \"\";\n }\n if(lang_id==JAVA_KEY){\n editor.setValue(`public class Main{\\n\\tpublic static void main(String args[]){\\n\\t\\tSystem.out.println(\"Hello World!\");\\n\\t}\\n}`);\n editor.getSession().setMode(\"ace/mode/java\");\n document.getElementById('inputbox').value = \"\";\n }\n if(lang_id==CPP_KEY){\n editor.setValue(`#include <iostream>\\nusing namespace std;\\nint main() {\\n\\tstring name;\\n\\tcin >> name;\\n\\tcout<<\"Hello, Welcome to \" << name << \"!\";\\n}`);\n editor.getSession().setMode(\"ace/mode/c_cpp\");\n document.getElementById('inputbox').value = \"Cloud-IDE\";\n }\n editor.setTheme(\"ace/theme/monokai\");\n}", "function setEditorSilent(){\n silcentEditorEvents = true;\n aceEditorHtml.setValue($renderedHtml.innerHTML.trim(), -1);\n setTimeout(function(){\n silcentEditorEvents = false;\n },100);\n }", "function engageEditMode() {\n\tMainwinObj.engageEditMode(exitEditMode, update);\n}", "onBeforeRendering() {}", "function handleEditorUpdate() {\n if (updateTimerRef) {\n clearTimeout(updateTimerRef);\n }\n updateTimerRef = setTimeout(refreshRenderContent, timeBeforeEditorUpdate);\n}", "update () {\n this.render();\n }", "function playerCursorUpdateCache(element, context) {\n var renderer = api.renderer(element, context);\n element.data('alphaSynthCursorCache', renderer.BuildBoundingsLookup());\n }", "function updateEditor() {\n\t\ttextToEditor();\n\t\tpositionEditorCaret();\n\t}", "function reRender() {\n input.innerText = buffer;\n}", "render() {\n this.update();\n }", "function setupAceEditor(cell){\r\n // define texteditor and ace editor\r\n var texteditor = $('#interactive' + cell).hide();\r\n var editor = ace.edit('aceeditor' + cell);\r\n \r\n // setup ace editor\r\n editor.setTheme(\"ace/theme/tomorrow\");\r\n editor.setFontSize(13);\r\n editor.renderer.setShowGutter(false); \r\n editor.getSession().setMode(\"ace/mode/r\");\r\n editor.getSession().setUseWrapMode(true);\r\n editor.getSession().setWrapLimitRange();\r\n editor.getSession().setTabSize(2);\r\n editor.getSession().setFoldStyle('markbegin'); \r\n editor.getSession().setValue(texteditor.val());\r\n \r\n // hook it up to textarea\r\n editor.getSession().on('change', function(e){\r\n texteditor.val(editor.getSession().getValue());\r\n texteditor.change();\r\n });\r\n \r\n texteditor.onchange = function() {\r\n texteditor.select();\r\n };\r\n return(editor) \r\n}", "function update() {\n try{\n esprima.parseScript(editor.getValue());\n if($bugContainer.css('display') != 'none'){\n $bugContainer.css({'display': 'none'})\n }\n }catch(e){\n $bugReport[0].innerHTML = e.message;\n $bugContainer.css({'display': 'flex'})\n }\n }", "function rerender() {\n\tscreen.innerText = buffer;\n}", "onEditorChange() {\n // If the handler is in standby mode, bail.\n if (this._standby) {\n return;\n }\n const editor = this.editor;\n if (!editor) {\n return;\n }\n const text = editor.model.value.text;\n const position = editor.getCursorPosition();\n const offset = Text.jsIndexToCharIndex(editor.getOffsetAt(position), text);\n const update = { content: null };\n const pending = ++this._pending;\n void this._connector\n .fetch({ offset, text })\n .then(reply => {\n // If handler has been disposed or a newer request is pending, bail.\n if (this.isDisposed || pending !== this._pending) {\n this._inspected.emit(update);\n return;\n }\n const { data } = reply;\n const mimeType = this._rendermime.preferredMimeType(data);\n if (mimeType) {\n const widget = this._rendermime.createRenderer(mimeType);\n const model = new MimeModel({ data });\n void widget.renderModel(model);\n update.content = widget;\n }\n this._inspected.emit(update);\n })\n .catch(reason => {\n // Since almost all failures are benign, fail silently.\n this._inspected.emit(update);\n });\n }", "function madeVisible() {\n if (codeMirrorDirty) {\n codeMirrorDirty = false;\n // important we do it a bit later so things have had time to lay out\n setTimeout(function () {\n codeMirror.refresh();\n }, 1);\n }\n }", "function renderBeginningPage(){\n console.log('setting page back to original VIEW state');\n\n $('#calicers-speach-text').html('Hello, my name is Calcifer.');\n $('#califers-text-input-box').show();\n\n }", "afterRender() { }", "afterRender() { }", "function updateDropletMode(aceEditor) {\n }", "function detachFromAce(ace) {\n\n }", "function scheduleUpdate() {\n shaderEditorPanel.classList.remove('compiled');\n shaderEditorPanel.classList.remove('not-compiled');\n\n if (EditContext.ShaderEditorTimeout) {\n EditContext.ShaderEditorTimeout = clearTimeout(EditContext.ShaderEditorTimeout);\n }\n EditContext.ShaderEditorTimeout = setTimeout(updateShaderEditorCode, EditContext.keyTimeout);\n}", "function animate() {\n\n\t\tconst mixer = editor.mixer;\n\t\tconst delta = clock.getDelta();\n\n\t\tlet needsUpdate = false;\n\n\n\t\t//yomotsu camera\n\t\tneedsUpdate = controls.update( delta );\n\n\t\t// Animations\n\n\n\t\tconst actions = mixer.stats.actions;\n\n\t\tif ( actions.inUse > 0 || prevActionsInUse > 0 ) {\n\n\t\t\tprevActionsInUse = actions.inUse;\n\n\t\t\tmixer.update( delta );\n\t\t\tneedsUpdate = true;\n\n\t\t}\n\n\t\t// View Helper\n\n\t\tif ( viewHelper.animating === true ) {\n\n\t\t\tviewHelper.update( delta );\n\t\t\tneedsUpdate = true;\n\n\t\t}\n\n\t\tif ( vr.currentSession !== null ) {\n\n\t\t\tneedsUpdate = true;\n\n\t\t}\n\n\t\tif ( needsUpdate === true ) render();\n\n\t}", "refresh() {\n this.render();\n }", "doodle() {\n this.update()\n this.display()\n }", "init() {\n // Get saved editor settings if any or default values from SettingsHandler\n const initialLanguage = settingsHandler.getEditorLanguageMode();\n const initialContent = settingsHandler.getEditorContent();\n\n this.engine.setTheme('ace/theme/monokai');\n this.engine.$blockScrolling = Infinity;\n this.engine.setShowPrintMargin(false);\n // Define the language mode for syntax highlighting and editor content\n this.engine.getSession().setMode({path:'ace/mode/' + initialLanguage, inline:true});\n this.engine.setValue(initialContent);\n\n this.initEventListners();\n }" ]
[ "0.64449835", "0.63343364", "0.6219092", "0.60903287", "0.598501", "0.5948566", "0.58068204", "0.57846594", "0.5771719", "0.57518935", "0.5746964", "0.57378614", "0.57146156", "0.571317", "0.5712021", "0.56476974", "0.56461096", "0.5621992", "0.56145036", "0.56118566", "0.5594994", "0.55923575", "0.55923575", "0.5588414", "0.55695176", "0.55590725", "0.5557994", "0.5548953", "0.55484307", "0.55467474" ]
0.7972766
0
function to only enter number for text box
function onlyEnterNumberTextBox(id) { $("#" + id).keydown(function (e) { // Allow: backspace, delete, tab, escape, enter and . if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || // Allow: Ctrl+A (e.keyCode == 65 && e.ctrlKey === true) || // Allow: home, end, left, right, down, up (e.keyCode >= 35 && e.keyCode <= 40)) { // let it happen, don't do anything return; } // Ensure that it is a number and stop the keypress if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { e.preventDefault(); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function onlyNum(obj,event){\n\tvar num_regx=/^[0-9]*$/;\n\tif( !num_regx.test(obj.value) ) {\n\t\talert('숫자만 입력하실 수 있습니다.');\n\t\tobj.value = obj.value.substring(0, obj.value.length-1 );\n\t}\n}", "function numberTextField(e,elementId)\n{\n var reg = /[\\b0-9]/;\n var v = document.getElementById(elementId).value;\n if(v.toString().length==0)\n {\n reg = /[\\b\\.0-9-]/;\n }\n else if(v.toString().indexOf('.')==-1){\n reg = /[\\b0-9\\.]/;\n }\n else{\n reg = /[\\b0-9]/;\n }\n var key = window.event ? e.keyCode : e.which;\n var keychar = String.fromCharCode(key);\n if(key==0)\n {\n reg=!reg;\n }\n return reg.test(keychar);\n}", "function soloNumeros(evt){\n\tevt = (evt) ? evt : window.event\n var charCode = (evt.which) ? evt.which : evt.keyCode\n if (charCode > 31 && (charCode < 48 || charCode > 57)) {\n status = \"This field accepts numbers only.\"\n return false\n }\n status = \"\"\n return true\n}", "function numerico(campo)\n\t{\n\tvar charpos = campo.value.search(\"[^0-9]\");\n if (campo.value.length > 0 && charpos >= 0)\n\t\t{\n\t\tcampo.value = campo.value.slice(0, -1);\n\t\tcampo.focus();\n\t return false;\n\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\treturn true;\n\t\t\t\t}\n\t}", "function validatenumber(xxxxx) {\r\n \r\n \tvar maintainplus = '';\r\n \tvar numval = xxxxx.value\r\n \tif ( numval.charAt(0)=='+' ){ var maintainplus = '+';}\r\n \tcurnumbervar = numval.replace(/[\\\\A-Za-z!\"£$%^&*+_={};:'@#~,¦\\/<>?|`¬\\]\\[]/g,'');\r\n \txxxxx.value = maintainplus + curnumbervar;\r\n \tvar maintainplus = '';\r\n // alert(\"enter integers only\");\r\n \txxxxx.focus;\r\n}", "function onlyNumeric() {\n //Get element id\n const idName = this.id;\n // Regex that checks if input has somethong that is not a digit\n const current_value = $(`#${idName}`).val();\n const re = new RegExp(/(\\D+)/gi);\n const match = re.exec(current_value);\n // Check match\n if (match != null) {\n // remove user input\n $(`#${idName}`).val(\"\");\n // Put error message\n $(`#${idName}_wi`).text(\"¡Sólo se admiten valores numéricos!\");\n $(`#${idName}_wi`).show();\n } else {\n // Hide error message\n $(`#${idName}_wi`).text(\"\");\n $(`#${idName}_wi`).hide();\n }\n}", "function numberOnly(event) {\t\r\n\t var c = event.which || event.keyCode;\r\n\t if ( (c >= 48 && c <= 57) || c == 43) \r\n\t return true;\r\n\t return false;\t \r\n}", "function numberOnly(evt, input){\r\n var charCode = (evt.which) ? evt.which : event.keyCode;\r\n if (charCode > 31 && (charCode < 46 || charCode == 47 || charCode > 57)){\r\n return false;\r\n }\r\n if (charCode == 46 && input.value.indexOf('.') >= 0){\r\n return false;\r\n }\r\n return true;\r\n}", "function numberOnly(event) {\n var key = event.keyCode;\n return ((key >= 48 && key <= 57) || (key >= 96 && key <= 105) || key == 8 || key == 9);\n}", "function allowNumeric()\n{\n\tif (!SignUp.mobilenumber.value.match(/^[0-9]+$/) && SignUp.mobilenumber.value !=\"\")\n\t{\n\t\tSignUp.mobilenumber.value=\"\";\n\t\tSignUp.mobilenumber.focus();\n\t\talert(\"Proszę używać tylko liczb\");\n\t}\n}", "function type_number(evt){\n (document.all) ? key = evt.keyCode : key = evt.which;\n return (key <= 13 || key == 46 || key == 45 || key == 32 || evt.ctrlKey || (key >= 48 && key <= 57));\n}", "function isNumberKey(evt,id){\r\n\r\n let numericConfirm = (evt.which) ? evt.which : evt.keycode;\r\nif(numericConfirm == 46){\r\n var txt=document.getElementById(id).value;\r\n if(!(txt.indexOf(\".\") > -1)){\r\n return true;\r\n }\r\n}\r\n\r\n if(numericConfirm > 31 && (numericConfirm < 48 || numericConfirm > 57)){\r\n return false;\r\n return true;\r\n }\r\n }", "function ValidaSoloNumeros() \n\t{\n \t\tif ((event.keyCode < 48) || (event.keyCode > 57)) \n \t\tevent.returnValue = false;\n\t}", "function allnumeric(inputtxt){\n var numbers = /^[0-9]/\n if(inputtxt.match(numbers)){\n return true;\n }\n else{\n alert('Please input numeric characters above zero only');\n rawcode.value = \"\"\n return false;\n }\n }", "function isInputNumber(evt){\n var ch =String.fromCharCode(evt.which);\n if(!(/[0-9]/.test(ch))){\n evt.preventDefault();\n }\n }", "function isNumeric(obj)\r\n {\r\n\tobj.value=trim(obj.value);\r\n\tvar val=obj.value;\r\n\tinputStr = val.toString()\r\n\tfor (var i = 0; i < inputStr.length; i++)\r\n\t{\r\n\t\tvar oneChar = inputStr.charAt(i)\t\t\t\r\n\t\tif ((oneChar < \"0\" || oneChar > \"9\") && oneChar != \"/\")\r\n\t\t{\r\n\t\t\talert(\"Enter Numeric Only \");\r\n\t\t\tobj.value='';\r\n\t\t \tobj.focus();\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n}", "function ValidNum() {\n if (event.keyCode < 48 || event.keyCode > 57) {\n event.returnValue = false;\n }\n}", "function allowNum(fieldName){\n\tif((event.keyCode < 48)||(event.keyCode > 57)){\n\t\talert(\"Please enter only number for \"+fieldName);\n\t\tevent.returnValue = false;\n\t} //end-if\n}", "function numbersOnly(input) {\n var regex = /[^0-9]/;\n\n input.value = input.value.replace(regex, \"\");\n}", "function isNumberKey(evt) {\n var charCode = evt.which ? evt.which : evt.keyCode;\n if (charCode > 31 && (charCode < 48 || charCode > 57))\n alert(\"Enter a positive number for meme id\");\n}", "function onlyNumbers(enteredkey, location)\r\n{\r\n\t$(\"#\"+enteredkey).keypress(function (e){\r\n\t var charCode = (e.which) ? e.which : e.keyCode;\r\n\t if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 43 && charCode != 8 && charCode != 46 && charCode != 110 && charCode != 190) {\r\n\t\t$(\"#\"+location).html(\"<font color = 'red'>Only numeric values are allowed</font> <img src='../images/no.gif' name = 'img1' align = 'absmiddle' width='18' height = '18' alt='image'>\");\r\n\t\treturn false;\r\n\t }\r\n\t else\r\n\t {\r\n\t\t$(\"#\"+location).html(\"\");\r\n\t }\r\n\t});\r\n}", "function campo_numerico() {\r\n\r\n if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;\r\n\r\n}", "function numbersonly(myfield, e, dec)\n{\nvar key;\nvar keychar;\n\nif (window.event)\n key = window.event.keyCode;\nelse if (e)\n key = e.which;\nelse\n return true;\nkeychar = String.fromCharCode(key);\n\n// control keys\nif ((key==null) || (key==0) || (key==8) || \n (key==9) || (key==13) || (key==27) )\n return true;\n\n// numbers\nelse if (((\"-0123456789\").indexOf(keychar) > -1))\n return true;\n\n// decimal point jump\nelse if (dec && (keychar == \".\"))\n {\n myfield.form.elements[dec].focus();\n return false;\n }\nelse\n return false;\n}", "function isNumber(evt,id) {\n\t\tconsol.log(\"is bumber calling\");\n\t\t\t// When enter is pressed the value is enterd in the text box\n\t\t\tif(evt.keyCode === 13) {\n\t\t\t\t//console.log(\"Enter key is pressed...\");\n\t\t\t\tevt.preventDefault();\n\t\t\t\tvar elem = document.getElementById(id);\n\t\t\t\t\n\t\t\t\t$(elem).blur();\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tevt = (evt) ? evt : window.event;\n\t\t\tvar charCode = (evt.which) ? evt.which : evt.keyCode;\n\n\t\t\tif (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode != 46 && charCode != 110 && charCode != 190)) {\n\t\t\t\treturn false;\n\t\t\t}else {\t\t\t\n\t\t\t\tvar str = document.getElementById(id).value;\n\t\t\t\tvar flag = true;\n\t\t\t\tvar found = false;\t\t\t\n\t\t\t\tfor(var i = 0; i < str.length; i++) {\n\t\t\t\t\tvar temp_code = str.charCodeAt(i);\t\n\t\t\t\t\tif((temp_code == 46 || temp_code == 110 || temp_code == 190) && found == true) {\n\t\t\t\t\t\tflag = false;\n\t\t\t\t\t}else if((temp_code == 46 || temp_code == 110 || temp_code == 190) && found == false){\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t}else {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(flag == false) {\n\t\t\t\t\tvar new_val = str.substring(0,str.length-1);\n\t\t\t\t\tdocument.getElementById(id).value = new_val;\t\n\t\t\t\t\treturn false;\t\t\t\t\n\t\t\t\t}else {\n\t\t\t\t\treturn true;\n\t\t\t\t}\t\t\t\n\t\t\t}\n\t\t}", "function onlyNumber(evt) {\n var charCode = (evt.which) ? evt.which : evt.keyCode;\n if (charCode > 31 && (charCode < 48 || charCode > 57))\n return false;\n return true;\n}", "function validateNum(){\n\tvar getNumber = $(\"#altitudeid\").val();\n\tnumbers = /^[0-9]+$/;\n\tif(!getNumber.match(numbers)){\n\t\tnewVal = getNumber.replace(/[a-zA-Z<>`{}~,./?;:'\"!@#$%^&*()_+=\\-\\[\\]]+$/, \"\");\n\t\t$(\"#altitudeid\").val(newVal);\n\t}\n}", "function numbersOnly(input) {\n let regex = /[^0-9]/g\n input.value = input.value.replace(regex, \"\");\n}", "function bind_number_only_fields() {\n\t $(\".numeric\").keypress(function (e) {\n //if the letter is not digit then display error and don't type anything\n if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {\n //display error message\n var error_message = $(\"<span> Digits Only </span>\").css(\"color\",\"red\");\n $(this).parent().append(error_message);\n error_message.show().fadeOut(\"slow\");\n// $(\"#errmsg\").html(\"Digits Only\").show().fadeOut(\"slow\");\n return false;\n }\n });\n}", "function numbersonly(myfield, e, dec)\r\n{\r\n var key;\r\n var keychar;\r\n\r\n if (window.event)\r\n key = window.event.keyCode;\r\n else if (e)\r\n key = e.which;\r\n else\r\n return true;\r\n keychar = String.fromCharCode(key);\r\n\r\n // control keys\r\n if ((key == null) || (key == 0) || (key == 8) ||\r\n (key == 9) || (key == 13) || (key == 27))\r\n return true;\r\n\r\n // numbers\r\n else if (((\"0123456789\").indexOf(keychar) > -1))\r\n return true;\r\n\r\n // decimal point jump\r\n else if (dec && (keychar == \".\"))\r\n {\r\n myfield.form.elements[dec].focus();\r\n return false;\r\n } else\r\n return false;\r\n}", "function validNumber(obj){\n\tvar formObj = document.getElementById(obj.id);\n var filter = /^([0-9\\.])+$/;\n if (!filter.test(formObj.value)) {\n// \talert(\"Please input number !\");\n \tComShowCodeMessage('COM12178');\n \tformObj.value=\"\";\n }\n return true;\n}" ]
[ "0.7703949", "0.76587", "0.7606104", "0.7605462", "0.7569377", "0.74869925", "0.73793125", "0.73667973", "0.73271775", "0.7282426", "0.727135", "0.72620213", "0.7261236", "0.72301495", "0.72201645", "0.7187337", "0.7186212", "0.71597195", "0.71134293", "0.71053606", "0.70951307", "0.70788074", "0.7072667", "0.70707273", "0.70672137", "0.70549965", "0.70542574", "0.7029065", "0.70143884", "0.70006406" ]
0.7741312
0
convert date id to date
function convertDateIdToString(dateString) { if(dateString == null || dateString == '' ) return ""; dateString = dateString.toString(); var result = dateString.substr(6,2) + "-" + dateString.substr(4,2) + "-" + dateString.substr(0,4); return result; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function toYYYYMMDD (n) {\n const d = new Date(n)\n return d.toISOString().split('T')[0]\n }", "function getDateId() {\n\tvar date = new Date();\n\tvar year = date.getFullYear();\n\tvar month = date.getMonth()+1;\n\tvar day = date.getDate();\n\treturn year+month+day;\n}", "convertDate(day) {\n var dd = String(day.getDate()).padStart(2, '0');\n var mm = String(day.getMonth() + 1).padStart(2, '0'); //January is 0!\n var yyyy = day.getFullYear();\n\n return yyyy+mm+dd\n }", "function date_ymd2dmy(val)\r\n{\r\n\tval = trim(val);\r\n\tif (val == '') return val;\r\n\tvar date_arr = val.split('-');\r\n\tif (date_arr.length != 3) return '';\r\n\tif (date_arr[1].length < 2) date_arr[1] = \"0\" + date_arr[1];\r\n\tif (date_arr[2].length < 2) date_arr[2] = \"0\" + date_arr[2];\r\n\treturn date_arr[2]+\"-\"+date_arr[1]+\"-\"+date_arr[0];\r\n}", "function intToDate(intDate)\n{\n var dtm = new Date(Number(intDate));\n return (dtm.getMonth()+1)+'/'+dtm.getDate()+'/'+dtm.getFullYear();\n}", "function convertDate(d){\n var p = d.split(\"-\")\n return +(p[0]+p[1]+p[2])\n}", "convertIntDateToStringDate(intDate){\n let tempDate = intDate.toString();\n let year = tempDate.substring(0,4);\n let month = tempDate.substring(4,6);\n let day = tempDate.substring(6,8);\n let stringDate = year + \"-\" + month + \"-\" + day;\n return stringDate;\n }", "function convertDate(date) {\n let day = date.substr(8, 2);\n let month = date.substr(5, 2);\n let year = date.substr(0, 4);\n date = day + \"/\" + month + \"/\" + year;\n return date;\n }", "function birthDateFromID(id) {\n let day = Number(id.slice(0, 2));\n let month = Number(id.slice(2, 4));\n let year = id.slice(4, 6);\n\n return day + \".\" + month + \".19\" + year;\n}", "function dateConverter(date){\r\n dateF = date.trim();\r\n let d = dateF.substring(0, 2);\r\n let m = dateF.substring(3,5);\r\n let y = dateF.substring(6,10);\r\n return(y +\"-\"+m+\"-\"+d);\r\n}", "function dateToDDMMYYYY(date) {\n let d = date.getDate();\n let m = date.getMonth() + 1;\n let y = date.getFullYear();\n return (m <= 9 ? \"0\" + m : m) + \"/\" + (d <= 9 ? \"0\" + d : d) + \"/\" + y + \": \";\n}", "function date_dmy2ymd(val)\r\n{\r\n\tval = trim(val);\r\n\tif (val == '') return val;\r\n\tvar date_arr = val.split('-');\r\n\tif (date_arr.length != 3) return '';\r\n\tif (date_arr[0].length < 2) date_arr[0] = \"0\" + date_arr[0];\r\n\tif (date_arr[1].length < 2) date_arr[1] = \"0\" + date_arr[1];\r\n\treturn date_arr[2]+\"-\"+date_arr[1]+\"-\"+date_arr[0];\r\n}", "function convertDate(date) {\n var yyyy = date.getFullYear().toString();\n var mm = (date.getMonth() + 1).toString();\n var dd = date.getDate().toString();\n\n var mmChars = mm.split('');\n var ddChars = dd.split('');\n\n return yyyy + '-' + (mmChars[1] ? mm : \"0\" + mmChars[0]) + '-' + (ddChars[1] ? dd : \"0\" + ddChars[0]);\n}", "function genereID(){\nvar ref='DA-';\nvar date = new Date();\n\n // Format de l'ID de la demande d'achat DA-YYMMDD-HHMMSS\n ref+=(String(date.getFullYear())).slice(-2)+(\"0\"+ String(date.getMonth()+1)).slice(-2)+(\"0\" + String(date.getDate())).slice(-2);\n ref+=\"-\"\n ref+=(\"0\"+String(date.getHours())).slice(-2)+(\"0\"+ String(date.getMinutes()+1)).slice(-2)+(\"0\" + String(date.getSeconds())).slice(-2);\n return ref;\n}", "function convertDate(date)\n {\n date = date.split(\"-\")\n\n var month = date[1]\n var day = date[2]\n\n return (month + \"/\" + day)\n }", "function getYYYYMMDDDate(d) {\n\t\t\tfunction pad(s) {\n\t\t\t\treturn (s < 10) ? '0' + s : s;\n\t\t\t}\n\t\t\treturn [\n\t\t\t\td.getFullYear(),\n\t\t\t\tpad(d.getMonth() + 1),\n\t\t\t\tpad(d.getDate())\n\t\t\t].join('-');\n\t\t}", "function convertDate(date) {\n let day = date.substring(8);\n let month = date.substring(5, 7);\n let year = date.substring(2,4);\n let newDate = `${month} /${day} /${year}`;\n return newDate;\n}", "dateFormate(d) {\n const date = new Date(d)\n const j = date.getDate()\n const m = (date.getUTCMonth() + 1)\n const a = date.getUTCFullYear()\n return (\"0\" + j).slice(-2) + '/' + (\"0\" + m).slice(-2) + '/' + a\n }", "function date_ymd2mdy(val)\r\n{\r\n\tval = trim(val);\r\n\tif (val == '') return '';\r\n\tvar date_arr = val.split('-');\r\n\tif (date_arr.length != 3) return '';\r\n\tif (date_arr[1].length < 2) date_arr[1] = \"0\" + date_arr[1];\r\n\tif (date_arr[2].length < 2) date_arr[2] = \"0\" + date_arr[2];\r\n\treturn date_arr[1]+\"-\"+date_arr[2]+\"-\"+date_arr[0];\r\n}", "function dateTransformer(d) {\r\n const date = new Date(d);\r\n let dd = date.getDate();\r\n let mm = date.getMonth() + 1;\r\n const yyyy = date.getFullYear();\r\n if (dd < 10) {\r\n dd = `0${dd}`;\r\n }\r\n if (mm < 10) {\r\n mm = `0${mm}`;\r\n }\r\n\r\n return `${dd}/${mm}/${yyyy}`;\r\n }", "function convertDate( date ){\n\tvar day;\n\tvar month;\n\tvar year;\n\n\t//Extract year, month and day\n\tmonth = date.substr(0,2);\n\tday = date.substr(3,2);\n\tyear = date.substr(6);\n\n\t//compile the ynab compatible format\n\tdate = (year + \"-\" + month + \"-\" + day);\n\t\n\treturn date;\n}", "function convertDate(date) {\n return \"\" + new Date(date).getDate() + \".\" + (new Date(date).getMonth()+1) + \".\" + new Date(date).getFullYear(); \n }", "function convert(str) {\n var date = new Date(str),\n mnth = (\"0\" + (date.getMonth() + 1)).slice(-2),\n day = (\"0\" + date.getDate()).slice(-2);\n return [date.getFullYear(), mnth, day].join(\"-\");\n }", "function date_mdy2ymd(val)\r\n{\r\n\tval = trim(val);\r\n\tif (val == '') return '';\r\n\tvar date_arr = val.split('-');\r\n\tif (date_arr.length != 3) return '';\r\n\tif (date_arr[0].length < 2) date_arr[0] = \"0\" + date_arr[0];\r\n\tif (date_arr[1].length < 2) date_arr[1] = \"0\" + date_arr[1];\r\n\treturn date_arr[2]+\"-\"+date_arr[0]+\"-\"+date_arr[1];\r\n}", "convertNewDateToDateType() {\n var date = new Date(); // today's date\n var year = date.getFullYear();\n var month = 1 + date.getMonth();\t// adding 1 makes month accurate January = 1 + 0 = 1 and December = 1 + 11 = 12\n month = ('0' + month).slice(-2);\t// adding 0 makes single digit months 2 digit so that you get last 2 digits i.e. 2 -> 02 and 11 -> 11\n var day = date.getDate();\n day = ('0' + day).slice(-2);\t\t// single digit day such as 2 becomes two digit day 02\n return year + '-' + month + '-' + day;\n }", "function getIdentifier() {\r\n return \"\" + date.getDate() + date.getMonth() + 1 + date.getFullYear() + date.getHours() + date.getMinutes() + date.getSeconds()\r\n}", "function date_yyyymmdd (date_obj) {\n let now = date_obj || new Date();\n\n let month = now.getMonth() + 1;\n let day = now.getDate();\n\n month = (month < 10) ? ('-' + 0 + month) : ('-' + month);\n day = (day < 10) ? ('-' + 0 + day) : ('-' + day);\n\n return now.getFullYear() + month + day;\n}", "function convertDate(input)\r\n {\r\n function pad(s) { return (s < 10) ? '0' + s : s; }\r\n var d = new Date(input);\r\n return [d.getFullYear(), pad(d.getMonth()+1), pad(d.getDate())].join('-');\r\n }", "function get_date(d) {\n var date1 = new Date(d.substr(0, 4), d.substr(5, 2) - 1, d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));\n return date1;\n }", "function getFormattedDate (dateNum) {\r\n\tvar oneDay = 86400000;\r\n\tvar baseDate = new Date(1900,0,1);\r\n \tvar mydate= new Date(baseDate.getTime() - oneDay + (dateNum -1)*oneDay);\r\n return mydate;\r\n }" ]
[ "0.68168473", "0.656949", "0.65142363", "0.65084946", "0.6493539", "0.6490043", "0.6417927", "0.6417708", "0.64116424", "0.6380895", "0.63783115", "0.63737583", "0.6370005", "0.6330993", "0.62723917", "0.62697387", "0.62652177", "0.6244952", "0.62377936", "0.62369275", "0.61936694", "0.6193167", "0.6180418", "0.6152942", "0.61215335", "0.611349", "0.61015224", "0.60978395", "0.60807055", "0.60762084" ]
0.6851724
0
Control events are processed here. This is called when Alexa requests an action (IE turn off appliance).
function handleControl(event, context) { if (event.header.namespace === 'Alexa.ConnectedHome.Control') { /** * Retrieve the appliance id and accessToken from the incoming message. */ let accessToken = event.payload.accessToken; let applianceId = event.payload.appliance.applianceId; let deviceid = event.payload.appliance.additionalApplianceDetails.deviceId; let message_id = event.header.messageId; let param = ""; let index = "0"; let state = 0; let confirmation; let funcName; log("Access Token: ", accessToken); log("DeviceID: ", deviceid); if (event.header.name == "TurnOnRequest") { state = 1; confirmation = "TurnOnConfirmation"; funcName = "onoff"; } else if (event.header.name == "TurnOffRequest") { state = 0; confirmation = "TurnOffConfirmation"; funcName = "onoff"; } else if (event.header.name == "SetPercentageRequest") { state = event.payload.percentageState.value; confirmation = "SetPercentageConfirmation"; funcName = "setvalue"; } else if (event.header.name == "IncrementPercentageRequest") { let increment = event.payload.deltaPercentage.value; state += increment; if (state > 100) { state = 100; } confirmation = "IncrementPercentageConfirmation"; funcName = "setvalue"; } else if (event.header.name == "DecrementPercentageRequest") { let decrement = event.payload.deltaPercentage.value; state -= decrement; if (state < 0) { state = 0; } confirmation = "DecrementPercentageConfirmation"; funcName = "setvalue"; } let options = { method: 'POST', url: particleServer, headers: { 'cache-control': 'no-cache', authorization: 'Bearer ' + accessToken, 'content-type': 'application/json' }, body: { inputs: [{ intent: 'Alexa.ConnectedHome.Control', payload: { devices: deviceid, confirmation: confirmation, state: state, funcName: funcName } }] }, json: true }; request(options, function (error, response, body) { if (error) throw new Error(error); let headers = { authorization: "Bear " + accessToken, namespace: 'Alexa.ConnectedHome.Control', name: body.payload.commands, payloadVersion: '2', messageId: message_id }; let payloads = {}; let result = { header: headers, payload: payloads }; context.succeed(result); }); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function handleControl(event, context) {\n var requestType=event.header.name;\n var responseType=event.header.name.replace(\"Request\",\"Confirmation\");\n var headers = {\n namespace: \"Alexa.ConnectedHome.Control\",\n name: responseType,\n payloadVersion: \"2\",\n messageId: generateUUID()\n };\n var result = {\n header: headers,\n payload: {}\n };\n\n\n getVeraSession(username,password,PK_Device,function(ServerRelay,RelaySessionToken,PK_Device){\n\n var applianceId = event.payload.appliance.applianceId;\n\n if (typeof applianceId !== \"string\" ) {\n log(\"event payload is invalid\",event);\n context.fail(generateControlError(responseType, 'UNEXPECTED_INFORMATION_RECEIVED', 'Input is invalid'));\n }\n\n if (event.header.name == 'TurnOnRequest') {\n if(applianceId.indexOf(\"S\")===0){\n runScene(ServerRelay,PK_Device,RelaySessionToken,applianceId,function(response){\n if(response.indexOf(\"ERROR\")===0){\n context.fail(generateControlError(responseType, 'TargetHardwareMalfunctionError', response));\n } else {\n context.succeed(result);\n }\n });\n } else {\n switchDevice(ServerRelay,PK_Device,RelaySessionToken,applianceId,1,function(response){\n if(response.indexOf(\"ERROR\")===0){\n context.fail(generateControlError(responseType, 'TargetHardwareMalfunctionError', response));\n } else {\n context.succeed(result);\n }\n });\n }\n } else if (event.header.name == 'TurnOffRequest') {\n if (applianceId.indexOf(\"S\")===0){\n stopScene(ServerRelay,PK_Device,RelaySessionToken,applianceId,function(response){\n if(response.indexOf(\"ERROR\")===0){\n context.fail(generateControlError(responseType, 'TargetHardwareMalfunctionError', response));\n } else {\n context.succeed(result);\n }\n });\n } else {\n switchDevice(ServerRelay,PK_Device,RelaySessionToken,applianceId,0,function(response){\n if(response.indexOf(\"ERROR\")===0){\n context.fail(generateControlError(responseType, 'TargetHardwareMalfunctionError', response));\n } else {\n context.succeed(result);\n }\n });\n }\n } else if (event.header.name === 'SetPercentageRequest') {\n var targetDimLevel=event.payload.percentageState.value;\n\n dimDevice(ServerRelay,PK_Device,RelaySessionToken,applianceId,targetDimLevel.toFixed(),function(response){\n if(response.indexOf(\"ERROR\")===0){\n context.fail(generateControlError(responseType, 'TargetHardwareMalfunctionError', response));\n } else {\n context.succeed(result);\n }\n });\n } else if (event.header.name === 'IncrementPercentageRequest') {\n getCurrentDimLevel(ServerRelay,PK_Device,RelaySessionToken,applianceId,function(currentDimLevelString){\n var currentDimLevel=Number(currentDimLevelString);\n if(isNaN(currentDimLevel)){\n context.fail(generateControlError(responseType, 'TargetConnectivityUnstableError', 'Could not get current dim level'));\n } else {\n var targetDimLevel=currentDimLevel+event.payload.deltaPercentage.value;\n if(targetDimLevel>100||targetDimLevel<0){\n context.fail(generateControlError(responseType, 'UnwillingToSetValueError', 'Out of range'));\n }\n dimDevice(ServerRelay,PK_Device,RelaySessionToken,applianceId,targetDimLevel.toFixed(),function(response){\n if(response.indexOf(\"ERROR\")===0){\n context.fail(generateControlError(responseType, 'TargetHardwareMalfunctionError', response));\n } else {\n context.succeed(result);\n }\n });\n }\n });\n } else if (event.header.name === 'DecrementPercentageRequest') {\n getCurrentDimLevel(ServerRelay,PK_Device,RelaySessionToken,applianceId,function(currentDimLevelString){\n var currentDimLevel=Number(currentDimLevelString);\n if(isNaN(currentDimLevel)){\n context.fail(generateControlError(responseType, 'TargetConnectivityUnstableError', 'Could not get current dim level'));\n } else {\n var targetDimLevel=currentDimLevel-event.payload.deltaPercentage.value;\n if(targetDimLevel>100||targetDimLevel<0){\n context.fail(generateControlError(responseType, 'UnwillingToSetValueError', 'Out of range'));\n }\n dimDevice(ServerRelay,PK_Device,RelaySessionToken,applianceId,targetDimLevel.toFixed(),function(response){\n if(response.indexOf(\"ERROR\")===0){\n context.fail(generateControlError(responseType, 'TargetHardwareMalfunctionError', response));\n } else {\n context.succeed(result);\n }\n });\n }\n });\n } else if (event.header.name === 'SetTargetTemperatureRequest') {\n var targetTemperature=event.payload.targetTemperature.value;\n setTemperature(ServerRelay,PK_Device,RelaySessionToken,applianceId,targetTemperature.toFixed(),function(response){\n if(response.indexOf(\"ERROR\")===0){\n context.fail(generateControlError(responseType, 'TargetHardwareMalfunctionError', response));\n } else {\n var payloads = {achievedState: {targetTemperature:{value: targetTemperature},mode:{value:\"AUTO\"}},previousState: {targetTemperature:{value: targetTemperature},mode:{value:\"AUTO\"}},targetTemperature:{value: targetTemperature},temperatureMode:{value:\"AUTO\"}};\n var result = {header: headers,payload: payloads};\n context.succeed(result);\n }\n });\n } else if (event.header.name === 'IncrementTargetTemperatureRequest') {\n getCurrentTemperature(ServerRelay,PK_Device,RelaySessionToken,applianceId,function(currentTemperatureString){\n var currentTemperature=Number(currentTemperatureString);\n if(isNaN(currentTemperature)){\n context.fail(generateControlError(responseType, 'TargetConnectivityUnstableError', 'Could not get current temperature'));\n } else {\n var targetTemperature=currentTemperature+event.payload.deltaTemperature.value;\n setTemperature(ServerRelay,PK_Device,RelaySessionToken,applianceId,targetTemperature.toFixed(),function(response){\n if(response.indexOf(\"ERROR\")===0){\n context.fail(generateControlError(responseType, 'TargetHardwareMalfunctionError', response));\n } else {\n var payloads = {achievedState: {targetTemperature:{value: targetTemperature},mode:{value:\"AUTO\"}},previousState: {targetTemperature:{value: currentTemperature},mode:{value:\"AUTO\"}},targetTemperature:{value: targetTemperature},temperatureMode:{value:\"AUTO\"}};\n var result = {header: headers,payload: payloads};\n context.succeed(result);\n }\n });}});\n } else if (event.header.name === 'DecrementTargetTemperatureRequest') {\n getCurrentTemperature(ServerRelay,PK_Device,RelaySessionToken,applianceId,function(currentTemperatureString){\n var currentTemperature=Number(currentTemperatureString);\n if(isNaN(currentTemperature)){\n context.fail(generateControlError(responseType, 'TargetConnectivityUnstableError', 'Could not get current temperature'));\n } else {\n var targetTemperature=currentTemperature-event.payload.deltaTemperature.value;\n setTemperature(ServerRelay,PK_Device,RelaySessionToken,applianceId,targetTemperature.toFixed(),function(response){\n if(response.indexOf(\"ERROR\")===0){\n context.fail(generateControlError(responseType, 'TargetHardwareMalfunctionError', response));\n } else {\n var payloads = {achievedState: {targetTemperature:{value: targetTemperature},mode:{value:\"AUTO\"}},previousState: {targetTemperature:{value: currentTemperature},mode:{value:\"AUTO\"}},targetTemperature:{value: targetTemperature},temperatureMode:{value:\"AUTO\"}};\n var result = {header: headers,payload: payloads};\n context.succeed(result);\n }\n });}});\n\n } else {\n // error\n }\n\n });\n\n}", "function handleControl(event, callback) {\n\n if (event.queryStringParameters.namespace !== 'Alexa.ConnectedHome.Control' || \n !(event.queryStringParameters.name == 'TurnOnRequest' ||\n event.queryStringParameters.name == 'TurnOffRequest' || \n event.queryStringParameters.name == 'SetPercentageRequest' ||\n event.queryStringParameters.name == 'IncrementPercentageRequest' ||\n event.queryStringParameters.name == 'DecrementPercentageRequest'\n ) ) {\n console.log('Bad namespace or name:',event);\n callback(new Error('Unsupported Operation'));\n return;\n }\n\n var applianceId = event.queryStringParameters.applianceId;\n\n if (typeof applianceId !== \"string\" ) {\n console.log('Event payload is invalid:',event);\n callback(new Error('Unexpected Information Recieved'));\n return;\n }\n \n var deviceValue = event.queryStringParameters.value;\n \n if ((event.queryStringParameters.name == 'SetPercentageRequest' ||\n event.queryStringParameters.name == 'IncrementPercentageRequest' ||\n event.queryStringParameters.name == 'DecrementPercentageRequest') &&\n typeof deviceValue !== \"string\") {\n console.log('Value required for action:',event);\n callback(new Error('Value required for action'));\n return;\n }\n\n switch (event.queryStringParameters.name) {\n case 'TurnOnRequest':\n controlHSDevice(applianceId,'deviceon',100,function(response){\n if (response.error) {\n callback(new Error('Target Hardware Malfunction'));\n } else {\n callback();\n }\n });\n break;\n case 'TurnOffRequest':\n controlHSDevice(applianceId,'deviceoff',0,function(response){\n if (response.error) {\n callback(new Error('Target Hardware Malfunction'));\n } else {\n callback();\n }\n });\n break;\n case 'SetPercentageRequest':\n controlHSDevice(applianceId,'setdevicevalue',event.queryStringParameters.value,function(response){\n if (response.error) {\n callback(new Error('Target Hardware Malfunction'));\n } else {\n callback();\n }\n });\n break;\n case 'IncrementPercentageRequest':\n controlHSDevice(applianceId,'changedevicevalue',event.queryStringParameters.value,function(response){\n if (response.error) {\n callback(new Error('Target Hardware Malfunction'));\n } else {\n callback();\n }\n });\n break;\n case 'DecrementPercentageRequest':\n controlHSDevice(applianceId,'changedevicevalue',-event.queryStringParameters.value,function(response){\n if (response.error) {\n callback(new Error('Target Hardware Malfunction'));\n } else {\n callback();\n }\n });\n break;\n default:\n console.log('Err', 'No supported action: ' + event.queryStringParameters.name);\n callback(new Error('Something went wrong'));\n break;\n }\n}", "function handleControl(event, context) {\n\n /**\n * Create the response header for success\n */\n var headers = {\n messageID: event.header.messageId,\n namespace: event.header.namespace,\n name: event.header.name.replace(\"Request\",\"Confirmation\"),\n payloadVersion: '2'\n };\n var payloads = {};\n var result = {\n header: headers,\n payload: payloads\n };\n \n if (event.header.namespace !== 'Alexa.ConnectedHome.Control' || \n !(event.header.name == 'TurnOnRequest' ||\n event.header.name == 'TurnOffRequest' || \n event.header.name == 'SetPercentageRequest' ||\n event.header.name == 'IncrementPercentageRequest' ||\n event.header.name == 'DecrementPercentageRequest'\n ) ) {\n context.fail(generateControlError(event.header.name.replace(\"Request\",\"Response\"), 'UNSUPPORTED_OPERATION', 'Unrecognized operation'));\n }\n\n var applianceId = event.payload.appliance.applianceId;\n\n if (typeof applianceId !== \"string\" ) {\n log(\"event payload is invalid\",event);\n context.fail(generateControlError(event.header.name.replace(\"Request\",\"Response\"), 'UNEXPECTED_INFORMATION_RECEIVED', 'Input is invalid'));\n }\n\n switch (event.header.name) {\n case 'TurnOnRequest':\n controlHSDevice(applianceId,'deviceon',100,function(response){\n if (response.error) {\n context.succeed(generateControlError(\"TargetHardwareMalfunctionError\", 'TARGET_HARDWARE_MALFUNCTION', response.error));\n } else {\n context.succeed(result);\n }\n });\n break;\n case 'TurnOffRequest':\n controlHSDevice(applianceId,'deviceoff',0,function(response){\n if (response.error) {\n context.succeed(generateControlError(\"TargetHardwareMalfunctionError\", 'TARGET_HARDWARE_MALFUNCTION', response.error));\n } else {\n context.succeed(result);\n }\n });\n break;\n case 'SetPercentageRequest':\n controlHSDevice(applianceId,'setdevicevalue',event.payload.percentageState.value,function(response){\n if (response.error) {\n log('response', response.error);\n context.succeed(generateControlError(\"TargetHardwareMalfunctionError\", 'TARGET_HARDWARE_MALFUNCTION', response.error));\n } else {\n context.succeed(result);\n }\n });\n break;\n case 'IncrementPercentageRequest':\n controlHSDevice(applianceId,'changedevicevalue',event.payload.deltaPercentage.value,function(response){\n if (response.error) {\n log('response', response.error);\n context.succeed(generateControlError(\"TargetHardwareMalfunctionError\", 'TARGET_HARDWARE_MALFUNCTION', response.error));\n } else {\n context.succeed(result);\n }\n });\n break;\n case 'DecrementPercentageRequest':\n controlHSDevice(applianceId,'changedevicevalue',-event.payload.deltaPercentage.value,function(response){\n if (response.error) {\n log('response', response.error);\n context.succeed(generateControlError(\"TargetHardwareMalfunctionError\", 'TARGET_HARDWARE_MALFUNCTION', response.error));\n } else {\n context.succeed(result);\n }\n });\n break;\n default:\n log('Err', 'No supported action: ' + event.header.name);\n context.fail('Something went wrong');\n break;\n }\n}", "function handleControl(event, context) {\n requestForDeviceServiceAccessToken(event)\n .then(constructDeviceCommand, log)\n .then(submitHttpRequest, log)\n .then(function notifyAlexa(result) {\n log('Control', result);\n context.succeed(result);\n }, function notifyAlexa(result) {\n log('Control', result);\n context.fail(result);\n });\n}", "function handleControl(event, context) {\n\n log('Handle control event', JSON.stringify(event));\n\n\n let header = event.directive.header;\n let endpoint = event.directive.endpoint;\n let endpointId = endpoint.endpointId;\n\n /**\n * Fail the invocation if the header is unexpected. This example only demonstrates\n * turn on / turn off, hence we are filtering on anything that is not SwitchOnOffRequest.\n */\n if (header.namespace !== 'Alexa.PowerController' && header.namespace !== 'Alexa.PowerLevelController' || header.name === 'AdjustPowerLevel' ) {\n return context.fail(util.generateControlError('SwitchOnOffRequest', 'UNSUPPORTED_OPERATION', 'Unrecognized operation'));\n }\n\n //TODO: remove duplicate code\n if (header.namespace === 'Alexa.PowerController') {\n let accessToken = endpoint.scope.token;\n let requestMethod = header.name;\n let basePath = config.REMOTE_CLOUD_BASE_PATH + '/Stones/' + endpointId + '/switch?access_token=' + accessToken;\n\n let postData = JSON.stringify({type: (requestMethod === 'TurnOn' ? \"TURN_ON\" : \"TURN_OFF\")});\n\n let options = {\n hostname: config.REMOTE_CLOUD_HOSTNAME,\n port: 443,\n path: basePath,\n method: 'POST',\n headers: {\n accept: '*/*',\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(postData)\n }\n };\n\n console.log(options.method, 'Requesting to', basePath, \"with options\", options, 'and data', postData);\n\n let postRequest = https.request(options, getPowerRequestHandler(event, context));\n\n postRequest.on('error', util.getErrorHandler(context));\n postRequest.write(postData);\n postRequest.end();\n }\n else if (header.namespace === 'Alexa.PowerLevelController') {\n let accessToken = endpoint.scope.token;\n let payload = event.directive.payload;\n let level = payload.powerLevel;\n let basePath = config.REMOTE_CLOUD_BASE_PATH + '/Stones/' + endpointId + '/switch?access_token=' + accessToken;\n\n let postData = JSON.stringify({type: \"PERCENTAGE\", percentage: level });\n\n let options = {\n hostname: config.REMOTE_CLOUD_HOSTNAME,\n port: 443,\n path: basePath,\n method: 'POST',\n headers: {\n accept: '*/*',\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(postData)\n }\n };\n\n console.log(options.method, 'Requesting to', basePath, \"with options\", options, 'and data', postData);\n\n let postRequest = https.request(options, getPowerLevelRequestHandler(event, context, level))\n postRequest.on('error', util.getErrorHandler(context));\n postRequest.write(postData);\n postRequest.end();\n }\n}", "function unhandledAction(event, response, model) {\n response.speak(speaker.get(\"_Unhandled\"))\n .listen(speaker.get(\"WhatToDo\"))\n .send();\n}", "function unhandledAction(event, response, model) { \n const activeQuestion = model.getActiveQuestion();\n if (activeQuestion) {\n const speech = speaker.getQuestionSpeech(activeQuestion, 'unhandled');\n const reprompt = speaker.getQuestionSpeech(activeQuestion, 'reprompt');\n\n response.speak(speech)\n .listen(reprompt)\n .send();\n }\n else {\n // shouldn't happen, but clear out just in case\n model.exitQuestionMode();\n response.sendNil({saveState: true});\n }\n}", "function onIntent(intentRequest, session, callback) {\n console.log(\"onIntent requestId=\" + intentRequest.requestId +\n \", sessionId=\" + session.sessionId);\nconsole.log(\"session details:\"+JSON.stringify(session));\n var intent = intentRequest.intent,\n intentName = intentRequest.intent.name;\n var theFlagToEnterLoop = 0;\n \n \n if (\"AMAZON.HelpIntent\" === intentName) {\n getHelpResponse(callback,session);\n }else if (\"EmotionalIntent\" === intentName) {\n getEmotionalResponse(callback,session);\n }else if (\"AMAZON.StopIntent\" === intentName) {\n endSession(callback);\n } \n \n \n if(session.attributes){\n console.log(\"in session att\");\n if(session.attributes.istakeoff===false && intent.slots.Command.value=='take off'){\n // Dispatch to your skill's intent handlers\n console.log(\"in our true\");\n theFlagToEnterLoop = 1 ;\n session.attributes.istakeoff=true;\n }\n else if(session.attributes.istakeoff===true){\n console.log(\"in our false\");\n theFlagToEnterLoop = 1 ; \n }\n }\n\n\nif(theFlagToEnterLoop==1){\n if (\"CommandIntent\" === intentName) {\n sendCommand(intent, session, callback);\n } \n else {\n throw \"Invalid intent\";\n }\n}\nelse{\n getTakeoffResponse(callback,session);\n}\n\n\n\n \n //if((sessionAttributes.firstrun===1 && intent.slots.Command.value=='take off')&&(sessionAttributes.firstrun===0)){\n // Dispatch to your skill's intent handlers\n \n \n \n}", "function tv_on_handler (app) {\n //to IRKit API\n options.url = IRKIT_URL.replace('[]', TV_ON_IR);\n doPostIR();\n app.ask('Alright, turn on TV');\n console.log('Requested ' + TV_ON);\n }", "function volume_control(action) {\n $.getService('ALAudioDevice', function(ALAudioDevice) {\n ALAudioDevice.getOutputVolume().done(\n function (volume) {\n ALAudioDevice.isAudioOutMuted().done(\n function(muted){\n if (muted) {\n $('#am_vol_mute').css('color', '#000000');\n ALAudioDevice.muteAudioOut(false);\n volume = global_vol\n ALAudioDevice.setOutputVolume(volume);\n }\n else {\n switch(action) {\n case \"Up\":\n volume = volume + 5;\n if (volume > 100) {\n volume = 100;\n }\n ALAudioDevice.setOutputVolume(volume);\n break;\n case \"Down\":\n volume = volume - 5;\n if (volume < 0) {\n volume = 0;\n }\n ALAudioDevice.setOutputVolume(volume);\n break;\n case \"Mute\":\n global_vol = volume;\n $('#am_vol_mute').css('color', colors[robot_color]);\n ALAudioDevice.muteAudioOut(true);\n }\n }\n })\n })\n });\n}", "handleAction() {\n return false\n }", "function AdaHeads_Take_Call_Button_Click() {\n // Create a new call object, not implemented\n AdaHeads.Alice.Get_Next_Call({\n 200 : function (data) {\n $(\"#Current_Call\").addClass(\"disconnected\").show();\n\n AdaHeads.Status_Console.Log(\"Reserved call\"); \n },\n \n 404 : function (data) {\n AdaHeads.Status_Console.Log(\"Call not found\"); \n },\n \n 204 : function (data) {\n AdaHeads.Status_Console.Log(\"Pickup: No call available\"); \n console.log (data); \n\n },\n 400 : function (data) {\n AdaHeads.Status_Console.Log(\"Pickup: Bad request\");\n },\n \n 500 : function (data) {\n AdaHeads.Status_Console.Log(\"Pickup: Server error\");\n }\n }); \n \n// UI Changes\n// Disable the take call button and enable the end call button\n\n}", "onSwitch() {}", "onSwitch() {}", "onSwitch() {}", "async onAction(msg, nlp){\n switch(nlp.action[1]){\n\n case \"joke\":\n this.joke(msg)\n break;\n\n case \"chuck\":\n this.chuck(msg)\n break;\n\n default:\n return\n }\n }", "function resetPukiAutoIdleAction(){\n\tresetPukiActionList();\n\t\n\tautoAction = false;\n\tperforming = false;\n\tchangePukiAction('static');\n\tautoAIStartTime = 0;\n}", "function performActions(msbAction) {\r\n switch (msbAction.action) {\r\n case 'stop':\r\n self.onLog(\"State changed to \" + \"Inactive\".yellow);\r\n settingsHelper.settings.state = \"InActive\";\r\n stopAllServicesSync()\r\n .then(() => {\r\n self.onLog(\"All services stopped\".yellow);\r\n });\r\n break;\r\n case 'start':\r\n self.onLog(\"State changed to \" + \"Active\".green);\r\n settingsHelper.settings.state = \"Active\";\r\n _downloadedScripts = [];\r\n self._microServices = [];\r\n serviceCount = 0;\r\n startAllServices(_itineraries, function () { });\r\n break;\r\n case 'restart':\r\n break;\r\n case 'reboot':\r\n break;\r\n case 'script':\r\n break;\r\n default:\r\n }\r\n }", "function handleEarlyInteraction() {\n clearTimeout(tId);\n cleanup();\n }", "*releaseButtonA() {\n yield this.sendEvent({ type: 0x01, code: 0x130, value: 0 });\n }", "activate() {\n if(turn.actions < this.actions) {\n hand.deselect();\n return;\n }\n resolver.proccess(this.results, this.actions, this.discard.bind(this));\n }", "function action() {\n\t \t/* Check player's state and call appropriate action. */\n\t \tif( _Nimbb.getState() == \"recording\" ) {\n\t \t \tstop();\n\t \t} else {\n\t \t \trecord();\n\t \t}\n\t}", "function do_action(req) {\n var action = req.action\n var playing = isPlaying()\n if (req.action == 'activate') {\n console.log('vkmb: activate')\n console.log('vkmb: current page is playing - ', playing)\n if (playing) {\n chrome.runtime.sendMessage({activate: true})\n }\n } else if (\n (req.numtabs == 1) ||\n (\n ((req.action == 'play') && req.lastactive && !playing) ||\n (playing && (\n (action == 'prev') || (action == 'next') ||\n (action == 'pause') || (action == 'add') ||\n (action == 'repeat') || (action == 'shuffle')\n ))\n )\n ) {\n if (req.lastactive) console.log(\"vkmb: tab was active\");\n console.log('vkmb: '+req.action)\n /*if (action == 'play') {\n getAudioPlayer().play()\n } else if (action == 'pause') {\n getAudioPlayer().pause()\n }*/\n if (action == 'pause') {\n vkClick('play')\n } else {\n vkClick(action)\n }\n return true\n } else {\n console.log(\"vkmb: do nothing\")\n return false\n }\n}", "off(event) { // TODO\n\n }", "off(event) { // TODO\n\n }", "onAction(action) {\n switch (action.type) {\n case 'ADD_ACCOUNT':\n this._startUpdateStream(action.id, undefined, undefined)\n return\n case 'DELETE_ACCOUNT':\n this._stopUpdateStream(action.id)\n return\n }\n }", "onEnable() {}", "function _actions() {\r\n\r\n\t\tif (_lastcurrentEvents.time.toString() !== _currentEvents.time.toString()) {\r\n\t\t\t$evName.html(_currentEvents.name);\r\n\t\t\t_currentEvents.onCountdownStart(_currentEvents);\r\n\t\t}\r\n\r\n\t\t_lastcurrentEvents = _currentEvents;\r\n\r\n\t\tvar remainingTime = _getRemainingTime(_currentEvents);\r\n\r\n\t\tif (remainingTime.sum === 0) { //Event occur\r\n\t\t\t$seconds.html(0);\r\n\t\t\t_currentEvents.onEvent(_currentEvents);\r\n\t\t} else if (remainingTime.sum > 0) { //Still counting down\r\n\t\t\tif ($days) {\r\n\t\t\t\t$days.html(remainingTime.days);\r\n\t\t\t}\r\n\t\t\tif ($hours) {\r\n\t\t\t\t$hours.html(remainingTime.hours);\r\n\t\t\t}\r\n\t\t\tif ($minutes) {\r\n\t\t\t\t$minutes.html(remainingTime.minutes);\r\n\t\t\t}\r\n\t\t\tif ($seconds) {\r\n\t\t\t\t$seconds.html(remainingTime.seconds);\r\n\t\t\t}\r\n\t\t} else { //Event has happened\r\n\t\t\t_events.shift();\r\n\t\t\t_stop();\r\n\t\t\t_start();\r\n\t\t}\r\n\t}", "function mainHandler(event, _, callback) {\n const applicationId = event.session.application.applicationId;\n\n console.log(JSON.stringify({\n applicationId,\n requestId: event.session.requestId,\n sessionId: event.session.sessionId,\n type: event.request.type,\n }));\n\n try {\n if (skillId && applicationId !== `amzn1.echo-sdk-ams.app.${skillId}`) {\n callback('Invalid Application ID');\n }\n\n if (/^(?:Launch|Intent)Request$/.test(event.request.type)) {\n const topic = topics[~~(Math.random() * (topics.length - 1))];\n const speechOutput = `Your conversation topic is, \"${topic}\".`;\n // If the user either does not reply to the welcome message or says\n // something that is not understood, they will be prompted again\n const repromptText = 'Sorry, I did not understand. Please try again.';\n\n callback(null, speechletResponse('Welcome', speechOutput, repromptText));\n } else if (event.request.type === 'SessionEndedRequest') {\n callback(null, speechletResponse('Session Ended', 'Enjoy.', null, true));\n }\n } catch (err) {\n callback(err);\n }\n}", "preStateChange(action){return;}" ]
[ "0.69838643", "0.6960366", "0.6899015", "0.6748353", "0.63826334", "0.6018675", "0.593839", "0.57300425", "0.57023305", "0.56880707", "0.5606107", "0.55317867", "0.54922414", "0.54922414", "0.54922414", "0.5454328", "0.54481095", "0.5441287", "0.54377955", "0.5417028", "0.54102206", "0.5404709", "0.53996253", "0.5367505", "0.5367505", "0.53557837", "0.53449035", "0.53438467", "0.5339976", "0.5336302" ]
0.71767503
0
A function that takes as input the coordinates of an edges and gives out the coordinates of the location where its cost should be mentioned Uses a little trigonometry :)
function getEdgeCostLocation(x1, y1, x2, y2) { var midx = (x1 + x2) / 2; var midy = (y1 + y2) / 2; var angle = Math.atan((x1 - x2) / (y2 - y1)); var coords = { x: midx + 8 * Math.cos(angle), y: midy + 8 * Math.sin(angle) } return coords; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function squareAroundPoint(nearLat, nearLong, edge) {\n // Ideally, we should do a geospatial query for a circle around the target point. We approximate this\n // by a square.\n var dist = edge / 2 * 1609.34; // convert miles to meters\n var point = new google.maps.LatLng(nearLat, nearLong);\n var eastPoint = google.maps.geometry.spherical.computeOffset(point, dist, 90.0);\n var westPoint = google.maps.geometry.spherical.computeOffset(point, dist, 270.0);\n var northPoint = google.maps.geometry.spherical.computeOffset(point, dist, 0.0);\n var southPoint = google.maps.geometry.spherical.computeOffset(point, dist, 180.0);\n console.log([nearLat, nearLong, edge]);\n return [southPoint.lat(), westPoint.lng(), northPoint.lat(), eastPoint.lng()];\n }", "function calculatePath()\n\n{\n\n// create Nodes from the Start and End x,y coordinates\n\nvar\n\nmypathStart = Node(null, {x:pathStart[0], y:pathStart[1]});\n\nvar mypathEnd = Node(null, {x:pathEnd[0], y:pathEnd[1]});\n\n// create an array that will contain all world cells\n\nvar AStar = new Array(worldSize);\n\n// list of currently open Nodes\n\nvar Open = [mypathStart];\n\n// list of closed Nodes\n\nvar Closed = [];\n\n// list of the final output array\n\nvar result = [];\n\n// reference to a Node (that is nearby)\n\nvar myNeighbours;\n\n// reference to a Node (that we are considering now)\n\nvar myNode;\n\n// reference to a Node (that starts a path in question)\n\nvar myPath;\n\n// temp integer variables used in the calculations\n\nvar length, max, min, i, j;\n\n// iterate through the open list until none are left\n\nwhile(length = Open.length)\n\n{\n\nmax = worldSize;\n\nmin = -1;\n\nfor(i = 0; i < length; i++)\n\n{\n\nif(Open[i].f < max)\n\n{\n\nmax = Open[i].f;\n\nmin = i;\n\n}\n\n}\n\n// grab the next node and remove it from Open array\n\nmyNode = Open.splice(min, 1)[0];\n\n// is it the destination node?\n\nif(myNode.value === mypathEnd.value)\n\n{\n\nmyPath = Closed[Closed.push(myNode) - 1];\n\ndo\n\n{\n\nresult.push([myPath.x, myPath.y]);\n\n}\n\nwhile (myPath = myPath.Parent);\n\n// clear the working arrays\n\nAStar = Closed = Open = [];\n\n// we want to return start to finish\n\nresult.reverse();\n\n}\n\nelse // not the destination\n\n{\n\n// find which nearby nodes are walkable\n\nmyNeighbours = Neighbours(myNode.x, myNode.y);\n\n// test each one that hasn't been tried already\n\nfor(i = 0, j = myNeighbours.length; i < j; i++)\n\n{\n\nmyPath = Node(myNode, myNeighbours[i]);\n\nif (!AStar[myPath.value])\n\n{\n\n// estimated cost of this particular route so far\n\nmyPath.g = myNode.g + distanceFunction(myNeighbours[i], myNode);\n\n// estimated cost of entire guessed route to the destination\n\nmyPath.f = myPath.g + distanceFunction(myNeighbours[i], mypathEnd);\n\n// remember this new path for testing above\n\nOpen.push(myPath);\n\n// mark this node in the world graph as visited\n\nAStar[myPath.value] = true;\n\n}\n\n}\n\n// remember this route as having no more untested options\n\nClosed.push(myNode);\n\n}\n\n} // keep iterating until the Open list is empty\n\nreturn result;\n\n}", "function calculatePath(){\n\t\t// create Nodes from the Start and End x,y coordinates\n\t\tvar\tmypathStart = Node(null, {x:pathStart[0], y:pathStart[1]});\n\t\tvar mypathEnd = Node(null, {x:pathEnd[0], y:pathEnd[1]});\n\t\t// create an array that will contain all world cells\n\t\tvar AStar = new Array(worldSize);\n\t\t// list of currently open Nodes\n\t\tvar Open = [mypathStart];\n\t\t// list of closed Nodes\n\t\tvar Closed = [];\n\t\t// list of the final output array\n\t\tvar result = [];\n\t\t// reference to a Node (that is nearby)\n\t\tvar myNeighbours;\n\t\t// reference to a Node (that we are considering now)\n\t\tvar myNode;\n\t\t// reference to a Node (that starts a path in question)\n\t\tvar myPath;\n\t\t// temp integer variables used in the calculations\n\t\tvar length, max, min, i, j;\n\t\t// iterate through the open list until none are left\n\t\twhile(length = Open.length)\n\t\t{\n\t\t\tmax = worldSize;\n\t\t\tmin = -1;\n\t\t\tfor(i = 0; i < length; i++)\n\t\t\t{\n\t\t\t\tif(Open[i].f < max)\n\t\t\t\t{\n\t\t\t\t\tmax = Open[i].f;\n\t\t\t\t\tmin = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// grab the next node and remove it from Open array\n\t\t\tmyNode = Open.splice(min, 1)[0];\n\t\t\t// is it the destination node?\n\t\t\tif(myNode.value === mypathEnd.value)\n\t\t\t{\n\t\t\t\tmyPath = Closed[Closed.push(myNode) - 1];\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\tresult.push([myPath.x, myPath.y]);\n\t\t\t\t}\n\t\t\t\twhile (myPath = myPath.Parent);\n\t\t\t\t// clear the working arrays\n\t\t\t\tAStar = Closed = Open = [];\n\t\t\t\t// we want to return start to finish\n\t\t\t\tresult.reverse();\n\t\t\t}\n\t\t\telse // not the destination\n\t\t\t{\n\t\t\t\t// find which nearby nodes are walkable\n\t\t\t\tmyNeighbours = Neighbours(myNode.x, myNode.y);\n\t\t\t\t// test each one that hasn't been tried already\n\t\t\t\tfor(i = 0, j = myNeighbours.length; i < j; i++)\n\t\t\t\t{\n\t\t\t\t\tmyPath = Node(myNode, myNeighbours[i]);\n\t\t\t\t\tif (!AStar[myPath.value])\n\t\t\t\t\t{\n\t\t\t\t\t\t// estimated cost of this particular route so far\n\t\t\t\t\t\tmyPath.g = myNode.g + distanceFunction(myNeighbours[i], myNode);\n\t\t\t\t\t\t// estimated cost of entire guessed route to the destination\n\t\t\t\t\t\tmyPath.f = myPath.g + distanceFunction(myNeighbours[i], mypathEnd);\n\t\t\t\t\t\t// remember this new path for testing above\n\t\t\t\t\t\tOpen.push(myPath);\n\t\t\t\t\t\t// mark this node in the world graph as visited\n\t\t\t\t\t\tAStar[myPath.value] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// remember this route as having no more untested options\n\t\t\t\tClosed.push(myNode);\n\t\t\t}\n\t\t} // keep iterating until the Open list is empty\n\t\treturn result;\n\t}", "function calculatePath()\n\t{\n\t\t// create Nodes from the Start and End x,y coordinates\n\t\tvar\tmypathStart = Node(null, {x:pathStart[0], y:pathStart[1]});\n\t\t//console.log(\"mypathStart =\", mypathStart);\n\n\t\tvar mypathEnd = Node(null, {x:pathEnd[0], y:pathEnd[1]});\n\t\t//console.log(\"mypathend =\", mypathEnd);\n\t\t// create an array that will contain all world cells\n\t\tvar AStar = new Array(worldSize);\n\t\t// list of currently open Nodes\n\t\tvar Open = [mypathStart];\n\t\t// list of closed Nodes\n\t\tvar Closed = [];\n\t\t// list of the final output array\n\t\tvar result = [];\n\t\t// reference to a Node (that is nearby)\n\t\tvar myNeighbours;\n\t\t// reference to a Node (that we are considering now)\n\t\tvar myNode;\n\t\t// reference to a Node (that starts a path in question)\n\t\tvar myPath;\n\t\t// temp integer variables used in the calculations\n\t\tvar length, max, min, i, j;\n\t\t// iterate through the open list until none are left\n\t\twhile(length = Open.length)\n\t\t{\n\t\t\tmax = worldSize;\n\t\t\tmin = -1;\n\t\t\tfor(i = 0; i < length; i++)\n\t\t\t{\n\t\t\t\tif(Open[i].f < max)\n\t\t\t\t{\n\t\t\t\t\tmax = Open[i].f;\n\t\t\t\t\tmin = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// grab the next node and remove it from Open array\n\t\t\tmyNode = Open.splice(min, 1)[0];\n\t\t\t// is it the destination node?\n\t\t\tif(myNode.value === mypathEnd.value)\n\t\t\t{\n\t\t\t\tmyPath = Closed[Closed.push(myNode) - 1];\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\tresult.push([myPath.x, myPath.y]);\n\t\t\t\t}\n\t\t\t\twhile (myPath = myPath.Parent);\n\t\t\t\t// clear the working arrays\n\t\t\t\tAStar = Closed = Open = [];\n\t\t\t\t// we want to return start to finish\n\t\t\t\tresult.reverse();\n\t\t\t}\n\t\t\telse // not the destination\n\t\t\t{\n\n\t\t\t\tmyNeighbours = Neighbours(myNode.x, myNode.y);\n\t\t\t\t// test each one that hasn't been tried already\n\t\t\t\tfor(i = 0, j = myNeighbours.length; i < j; i++)\n\t\t\t\t{\n\t\t\t\t\tmyPath = Node(myNode, myNeighbours[i]);\n\t\t\t\t\tif (!AStar[myPath.value])\n\t\t\t\t\t{\n\t\t\t\t\t\t// estimated cost of this particular route so far\n\t\t\t\t\t\tmyPath.g = myNode.g + distanceFunction(myNeighbours[i], myNode);\n\t\t\t\t\t\t// estimated cost of entire guessed route to the destination\n\t\t\t\t\t\tmyPath.f = myPath.g + distanceFunction(myNeighbours[i], mypathEnd);\n\t\t\t\t\t\t// remember this new path for testing above\n\t\t\t\t\t\tOpen.push(myPath);\n\t\t\t\t\t\t// mark this node in the world graph as visited\n\t\t\t\t\t\tAStar[myPath.value] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tClosed.push(myNode);\n\t\t\t}\n\t\t} \n\t\treturn result;\n\t}", "function calculatePath()\n {\n // create Nodes from the Start and End x,y coordinates\n var mypathStart = Node(null,\n {\n x: pathStart[0],\n y: pathStart[1]\n });\n var mypathEnd = Node(null,\n {\n x: pathEnd[0],\n y: pathEnd[1]\n });\n // create an array that will contain all world cells\n var AStar = new Array(worldSize);\n // list of currently open Nodes\n var Open = [mypathStart];\n // list of closed Nodes\n var Closed = [];\n // list of the final output array\n var result = [];\n // reference to a Node (that is nearby)\n var myNeighbours;\n // reference to a Node (that we are considering now)\n var myNode;\n // reference to a Node (that starts a path in question)\n var myPath;\n // temp integer variables used in the calculations\n var length, max, min, i, j;\n // iterate through the open list until none are left\n while (length = Open.length)\n {\n max = worldSize;\n min = -1;\n for (i = 0; i < length; i++)\n {\n if (Open[i].f < max)\n {\n max = Open[i].f;\n min = i;\n }\n }\n // grab the next node and remove it from Open array\n myNode = Open.splice(min, 1)[0];\n // is it the destination node?\n if (myNode.value === mypathEnd.value)\n {\n myPath = Closed[Closed.push(myNode) - 1];\n do {\n result.push([myPath.x, myPath.y]);\n }\n while (myPath = myPath.Parent);\n // clear the working arrays\n AStar = Closed = Open = [];\n // we want to return start to finish\n result.reverse();\n }\n else // not the destination\n {\n // find which nearby nodes are walkable\n myNeighbours = Neighbours(myNode.x, myNode.y);\n // test each one that hasn't been tried already\n for (i = 0, j = myNeighbours.length; i < j; i++)\n {\n myPath = Node(myNode, myNeighbours[i]);\n if (!AStar[myPath.value])\n {\n // estimated cost of this particular route so far\n myPath.g = myNode.g + distanceFunction(myNeighbours[i], myNode);\n // estimated cost of entire guessed route to the destination\n myPath.f = myPath.g + distanceFunction(myNeighbours[i], mypathEnd);\n // remember this new path for testing above\n Open.push(myPath);\n // mark this node in the world graph as visited\n AStar[myPath.value] = true;\n }\n }\n // remember this route as having no more untested options\n Closed.push(myNode);\n }\n } // keep iterating until the Open list is empty\n return result;\n }", "function calculatePath() {\n // create Nodes from the Start and End x,y coordinates\n let mypathStart = Node(null, { x: pathStart[0], y: pathStart[1] });\n let mypathEnd = Node(null, { x: pathEnd[0], y: pathEnd[1] });\n // create an array that will contain all world cells\n let AStar = new Array(worldSize);\n // list of currently open Nodes\n let Open = [mypathStart];\n // list of the final output array\n let result = [];\n // reference to a Node (that is nearby)\n let myNeighbours;\n // reference to a Node (that we are considering now)\n let myNode;\n // reference to a Node (that starts a path in question)\n let myPath;\n // temp integer variables used in the calculations\n let length, max, min, i, j;\n // iterate through the open list until none are left\n do {\n max = worldSize;\n min = -1;\n for (i = 0; i < length; i++) {\n if (Open[i].f < max) {\n max = Open[i].f;\n min = i;\n }\n }\n // grab the next node and remove it from Open array\n myNode = Open.splice(min, 1)[0];\n // is it the destination node?\n if (myNode.value === mypathEnd.value) {\n // we found a path!\n do {\n result.unshift([myNode.x, myNode.y]);\n\n myNode = myNode.Parent;\n }\n while (myNode !== null);\n\n // clear the working arrays\n AStar = Open = [];\n\n return result;\n }\n\n // find which nearby nodes are walkable\n myNeighbours = neighbours(myNode.x, myNode.y);\n for (i = 0, j = myNeighbours.length; i < j; i++) {\n // test each one that hasn't been tried already\n myPath = Node(myNode, myNeighbours[i]);\n if (!AStar[myPath.value]) {\n // estimated cost of this particular route so far\n myPath.g = myNode.g + distanceFunction(myNeighbours[i], myNode);\n // estimated cost of entire guessed route to the destination\n myPath.f = myPath.g + distanceFunction(myNeighbours[i], mypathEnd);\n // remember this new path for testing above\n Open.push(myPath);\n // mark this node in the world graph as visited\n AStar[myPath.value] = true;\n }\n }\n\n length = Open.length;\n } while (0 < length);\n\n return result;\n }", "function calculatePath()\r\n\t{\r\n\t\t// create Nodes from the Start and End x,y coordinates\r\n\t\tvar\tmypathStart = Node(null, {x:pathStart[0], y:pathStart[1]});\r\n\t\tvar mypathEnd = Node(null, {x:pathEnd[0], y:pathEnd[1]});\r\n\t\t// create an array that will contain all world cells\r\n\t\tvar AStar = new Array(worldSize);\r\n\t\t// list of currently open Nodes\r\n\t\tvar Open = [mypathStart];\r\n\t\t// list of closed Nodes\r\n\t\tvar Closed = [];\r\n\t\t// list of the final output array\r\n\t\tvar result = [];\r\n\t\t// reference to a Node (that is nearby)\r\n\t\tvar myNeighbours;\r\n\t\t// reference to a Node (that we are considering now)\r\n\t\tvar myNode;\r\n\t\t// reference to a Node (that starts a path in question)\r\n\t\tvar myPath;\r\n\t\t// temp integer variables used in the calculations\r\n\t\tvar length, max, min, i, j;\r\n\t\t// iterate through the open list until none are left\r\n\t\twhile(length = Open.length)\r\n\t\t{\r\n\t\t\tmax = worldSize;\r\n\t\t\tmin = -1;\r\n\t\t\tfor(i = 0; i < length; i++)\r\n\t\t\t{\r\n\t\t\t\tif(Open[i].f < max)\r\n\t\t\t\t{\r\n\t\t\t\t\tmax = Open[i].f;\r\n\t\t\t\t\tmin = i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// grab the next node and remove it from Open array\r\n\t\t\tmyNode = Open.splice(min, 1)[0];\r\n\t\t\t// is it the destination node?\r\n\t\t\tif(myNode.value === mypathEnd.value)\r\n\t\t\t{\r\n\t\t\t\tmyPath = Closed[Closed.push(myNode) - 1];\r\n\t\t\t\tdo\r\n\t\t\t\t{\r\n\t\t\t\t\tresult.push([myPath.x, myPath.y]);\r\n\t\t\t\t}\r\n\t\t\t\twhile (myPath = myPath.Parent);\r\n\t\t\t\t// clear the working arrays\r\n\t\t\t\tAStar = Closed = Open = [];\r\n\t\t\t\t// we want to return start to finish\r\n\t\t\t\tresult.reverse();\r\n\t\t\t}\r\n\t\t\telse // not the destination\r\n\t\t\t{\r\n\t\t\t\t// find which nearby nodes are walkable\r\n\t\t\t\tmyNeighbours = Neighbours(myNode.x, myNode.y);\r\n\t\t\t\t// test each one that hasn't been tried already\r\n\t\t\t\tfor(i = 0, j = myNeighbours.length; i < j; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tmyPath = Node(myNode, myNeighbours[i]);\r\n\t\t\t\t\tif (!AStar[myPath.value])\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t// estimated cost of this particular route so far\r\n\t\t\t\t\t\tmyPath.g = myNode.g + distanceFunction(myNeighbours[i], myNode);\r\n\t\t\t\t\t\t// estimated cost of entire guessed route to the destination\r\n\t\t\t\t\t\tmyPath.f = myPath.g + distanceFunction(myNeighbours[i], mypathEnd);\r\n\t\t\t\t\t\t// remember this new path for testing above\r\n\t\t\t\t\t\tOpen.push(myPath);\r\n\t\t\t\t\t\t// mark this node in the world graph as visited\r\n\t\t\t\t\t\tAStar[myPath.value] = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t// remember this route as having no more untested options\r\n\t\t\t\tClosed.push(myNode);\r\n\t\t\t}\r\n\t\t} // keep iterating until the Open list is empty\r\n\t\treturn result;\r\n\t}", "function calculatePath() {\n\t // create Nodes from the Start and End x,y coordinates\n\t var mypathStart = Node(null, { x: pathStart[0], y: pathStart[1] });\n\t var mypathEnd = Node(null, { x: pathEnd[0], y: pathEnd[1] });\n\t // create an array that will contain all world cells\n\t var AStar = new Array(worldSize);\n\t // list of currently open Nodes\n\t var Open = [mypathStart];\n\t // list of closed Nodes\n\t var Closed = [];\n\t // list of the final output array\n\t var result = [];\n\t // reference to a Node (that is nearby)\n\t var myNeighbours;\n\t // reference to a Node (that we are considering now)\n\t var myNode;\n\t // reference to a Node (that starts a path in question)\n\t var myPath;\n\t // temp integer variables used in the calculations\n\t var length, max, min, i, j;\n\t // iterate through the open list until none are left\n\t while (length = Open.length) {\n\t max = worldSize * 999999;\n\t min = -1;\n\t for (i = 0; i < length; i++) {\n\t if (Open[i].f < max) {\n\t max = Open[i].f;\n\t min = i;\n\t }\n\t }\n\t // grab the next node and remove it from Open array\n\t myNode = Open.splice(min, 1)[0];\n\t // is it the destination node?\n\t if (myNode.value === mypathEnd.value) {\n\t myPath = Closed[Closed.push(myNode) - 1];\n\t do {\n\t result.push([myPath.x, myPath.y]);\n\t } while (myPath = myPath.Parent);\n\t // clear the working arrays\n\t AStar = Closed = Open = [];\n\t // we want to return start to finish\n\t result.reverse();\n\t } else // not the destination\n\t {\n\t // find which nearby nodes are walkable\n\t myNeighbours = Neighbours(myNode.x, myNode.y);\n\t // test each one that hasn't been tried already\n\t for (i = 0, j = myNeighbours.length; i < j; i++) {\n\t myPath = Node(myNode, myNeighbours[i], world[myNeighbours[i].x][myNeighbours[i].y]);\n\t if (!AStar[myPath.value]) {\n\t // estimated cost of this particular route so far\n\t myPath.g += myNode.g + distanceFunction(myNeighbours[i], myNode);\n\t // estimated cost of entire guessed route to the destination\n\t myPath.f = myPath.g + distanceFunction(myNeighbours[i], mypathEnd);\n\t // remember this new path for testing above\n\t Open.push(myPath);\n\t // mark this node in the world graph as visited\n\t AStar[myPath.value] = true;\n\t }\n\t }\n\t // remember this route as having no more untested options\n\t Closed.push(myNode);\n\t }\n\t } // keep iterating until the Open list is empty\n\t return result;\n\t }", "function calculateEdgeCenters(edges) {\n edges.forEach(function (d) {\n //Find a good radius\n d.r = Math.sqrt(sq(d.target.x - d.source.x) + sq(d.target.y - d.source.y)) * 2; //Find center of the arc function\n\n var centers = findCenters(d.r, d.source, d.target);\n d.sign = 1; //Math.random() > 0.5\n\n d.center = d.sign ? centers.c2 : centers.c1;\n }); ///////////// Calculate center for curved edges /////////////\n //https://stackoverflow.com/questions/26030023\n //http://jsbin.com/jutidigepeta/3/edit?html,js,output\n\n function findCenters(r, p1, p2) {\n // pm is middle point of (p1, p2)\n var pm = {\n x: 0.5 * (p1.x + p2.x),\n y: 0.5 * (p1.y + p2.y)\n }; // compute leading vector of the perpendicular to p1 p2 == C1C2 line\n\n var perpABdx = -(p2.y - p1.y);\n var perpABdy = p2.x - p1.x; // normalize vector\n\n var norm = Math.sqrt(sq(perpABdx) + sq(perpABdy));\n perpABdx /= norm;\n perpABdy /= norm; // compute distance from pm to p1\n\n var dpmp1 = Math.sqrt(sq(pm.x - p1.x) + sq(pm.y - p1.y)); // sin of the angle between { circle center, middle , p1 }\n\n var sin = dpmp1 / r; // is such a circle possible ?\n\n if (sin < -1 || sin > 1) return null; // no, return null\n // yes, compute the two centers\n\n var cos = Math.sqrt(1 - sq(sin)); // build cos out of sin\n\n var d = r * cos;\n var res1 = {\n x: pm.x + perpABdx * d,\n y: pm.y + perpABdy * d\n };\n var res2 = {\n x: pm.x - perpABdx * d,\n y: pm.y - perpABdy * d\n };\n return {\n c1: res1,\n c2: res2\n };\n } //function findCenters\n\n } //function calculateEdgeCenters", "function calculateEdgeCenters(edges) {\n edges.forEach(function (d) {\n //Find a good radius\n d.r = Math.sqrt(sq(d.target.x - d.source.x) + sq(d.target.y - d.source.y)) * 2; //Find center of the arc function\n\n var centers = findCenters(d.r, d.source, d.target);\n d.sign = 1; //Math.random() > 0.5\n\n d.center = d.sign ? centers.c2 : centers.c1;\n }); ///////////// Calculate center for curved edges /////////////\n //https://stackoverflow.com/questions/26030023\n //http://jsbin.com/jutidigepeta/3/edit?html,js,output\n\n function findCenters(r, p1, p2) {\n // pm is middle point of (p1, p2)\n var pm = {\n x: 0.5 * (p1.x + p2.x),\n y: 0.5 * (p1.y + p2.y)\n }; // compute leading vector of the perpendicular to p1 p2 == C1C2 line\n\n var perpABdx = -(p2.y - p1.y);\n var perpABdy = p2.x - p1.x; // normalize vector\n\n var norm = Math.sqrt(sq(perpABdx) + sq(perpABdy));\n perpABdx /= norm;\n perpABdy /= norm; // compute distance from pm to p1\n\n var dpmp1 = Math.sqrt(sq(pm.x - p1.x) + sq(pm.y - p1.y)); // sin of the angle between { circle center, middle , p1 }\n\n var sin = dpmp1 / r; // is such a circle possible ?\n\n if (sin < -1 || sin > 1) return null; // no, return null\n // yes, compute the two centers\n\n var cos = Math.sqrt(1 - sq(sin)); // build cos out of sin\n\n var d = r * cos;\n var res1 = {\n x: pm.x + perpABdx * d,\n y: pm.y + perpABdy * d\n };\n var res2 = {\n x: pm.x - perpABdx * d,\n y: pm.y - perpABdy * d\n };\n return {\n c1: res1,\n c2: res2\n };\n } //function findCenters\n\n } //function calculateEdgeCenters", "calculateCircleEdgePoint(currPosition, prevPosition, r, r_diff) {\n r = r + r_diff\n var a = (prevPosition.y - currPosition.y) / (prevPosition.x - currPosition.x);\n\n var x_diff = Math.sqrt((r * r) / (1 + a * a));\n var y_diff = Math.sqrt((a * a * r * r) / (1 + a * a));\n\n if (currPosition.x < prevPosition.x && currPosition.y < prevPosition.y) {\n return {\n new_x: -Math.sqrt((r * r) / (1 + a * a)),\n new_y: -Math.sqrt((a * a * r * r) / (1 + a * a))\n }\n } else if (currPosition.x < prevPosition.x && currPosition.y > prevPosition.y) {\n return {\n new_x: -Math.sqrt((r * r) / (1 + a * a)),\n new_y: Math.sqrt((a * a * r * r) / (1 + a * a))\n }\n }\n if (currPosition.x > prevPosition.x && currPosition.y < prevPosition.y) {\n return {\n new_x: Math.sqrt((r * r) / (1 + a * a)),\n new_y: -Math.sqrt((a * a * r * r) / (1 + a * a))\n }\n } else if (currPosition.x > prevPosition.x && currPosition.y > prevPosition.y) {\n return {\n new_x: Math.sqrt((r * r) / (1 + a * a)),\n new_y: Math.sqrt((a * a * r * r) / (1 + a * a))\n }\n } else if (currPosition.x == prevPosition.x && currPosition.y < prevPosition.y) {\n return {\n new_x: 0,\n new_y: -r\n }\n } else if (currPosition.x == prevPosition.x && currPosition.y > prevPosition.y) {\n return {\n new_x: 0,\n new_y: r\n }\n } else if (currPosition.x < prevPosition.x && currPosition.y == prevPosition.y) {\n return {\n new_x: -r,\n new_y: 0\n }\n } else if (currPosition.x > prevPosition.x && currPosition.y == prevPosition.y) {\n return {\n new_x: r,\n new_y: 0\n }\n }\n\n\n return {\n new_x: 0,\n new_y: 0\n }\n\n }", "function getCoordinatesForEdge(v1,v2){\r\n\tvar output = [];\r\n\tvar shortestDist = Math.pow(10,10);\r\n\t$.each(v1.coordinates, function(index1, item1){\r\n\t\t$.each(v2.coordinates, function(index2, item2){\r\n\t\t\t\r\n\t\t\tvar dist = getDistance(item1,item2);\r\n\t\t\tif (dist < shortestDist){\r\n\t\t\t\tshortestDist = dist;\r\n\t\t\t\toutput[0] = {lat:item1.lat, lng:item1.lng};\r\n\t\t\t\toutput[2] = {lat:item2.lat, lng:item2.lng};\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n\toutput[1] = {lat:(output[0].lat+output[2].lat)/2, lng:(output[0].lng+output[2].lng)/2}; // Setting the center point on the edge to locate the popup.\r\n\treturn output;\r\n}", "calcDirectionCoords(lat1, lon1, lat2, lon2) {\n //Line will be around 1000m long or something\n const multiplier = 1000 / this.calcDistance(lat1, lon1, lat2, lon2);\n return ([{\n latitude: lat1 + ((lat2 - lat1) * multiplier),\n longitude: lon1 + ((lon2 - lon1) * multiplier)\n },\n {\n latitude: lat1,\n longitude: lon1\n }]);\n }", "computeEdges() {\n\n let zeros = this.computeZeros();\n\n if (this.parab.left == null) {\n this.edge_left = Math.max(zeros[0], 0);\n } else {\n let interc = this.computeParabolaInterseption(this.parab.left); //x coordinates of the interseption with the parabola on the left\n this.interseption_point = { x: interc[0], y:this.calcF(interc[0])}; // Coordinates of the interseption to be saved\n this.edge_left = Math.max(/*zeros[0],*/ 0, Math.min(interc[0], Parabola.svgWidth)); // Left boundary of the parabola\n this.parab.left.edge_right = this.edge_left //Right boundary of the parabola on the left\n }\n\n // If there is no parabola on the right it means that it's the last parabola\n if (this.parab.right == null) {\n this.edge_right = Math.min(zeros[1], Parabola.svgWidth);\n }\n\n }", "function computeEdgePosition(edge, nodePositions, arcRatio) {\n\tconst p0 = nodePositions.get(edge.source);\n\tconst p1 = nodePositions.get(edge.target);\n\tconst mid = {x: p0.x + (p1.x - p0.x) / 2.0, y: p0.y + (p1.x - p0.x) * arcRatio }\n\treturn [p0, mid, p1];\n}", "function edgePathToPath(edges) {\n return edges.filter(isNotHidden).map(edgeToIPathSegment);\n}", "getDistancia(x, xi, xf, y, yi, yf) {\n\n let dist;\n\n if (xf === xi) {\n let yu = yf;\n let yd = yi;\n\n if (y >= yu) {\n dist = Math.abs(Math.sqrt((xi - x) * (xi - x) + (yu - y) * (yu - y)));\n dist = dist * DEGREE_TO_METER;\n return dist;\n }\n if (y <= yd) {\n dist = Math.abs(Math.sqrt((xi - x) * (xi - x) + (yd - y) * (yd - y)));\n dist = dist * DEGREE_TO_METER;\n return dist;\n }\n if ((y > yd) && (y < yu)) {\n dist = Math.abs(xi - x);\n dist = dist * DEGREE_TO_METER\n return dist;\n }\n }\n\n if (yf === yi) {\n\n let xr;\n let xl;\n if (xf > xi) {\n xr = xf;\n xl = xi;\n } else {\n xr = xi;\n xl = xf;\n }\n if (x >= xr) {\n dist = Math.abs(Math.sqrt((x - xr) * (x - xr) + (yi - y) * (yi - y)));\n dist = dist = dist * DEGREE_TO_METER;\n return dist;\n }\n if (x <= xl) {\n dist = Math.abs(Math.sqrt((x - xl) * (x - xl) + (yi - y) * (yi - y)));\n dist = dist * DEGREE_TO_METER;\n return dist;\n }\n if ((x > xl) && (x < xr)) {\n dist = Math.abs(yi - y);\n dist = dist;\n return dist = Math.abs((yi - y) * DEGREE_TO_METER);\n }\n }\n\n let xr = xf;\n let yr = yf;\n let xl = xi;\n let yl = yi;\n\n let M = (yf - yi) / (xf - xi);\n let b = yi - M * xi;\n let bp = y + (1 / M) * x;\n let xs = (bp - b) / (M + 1 / M);\n let ys = b + M * xs;\n\n if (xs > xr) {\n dist = Math.abs(Math.sqrt((xr - x) * (xr - x) + (yr - y) * (yr - y)));\n } else {\n if (xs < xl) {\n dist = Math.abs(Math.sqrt((xl - x) * (xl - x) + (yl - y) * (yl - y)));\n } else {\n dist = Math.abs(Math.sqrt((xs - x) * (xs - x) + (ys - y) * (ys - y)));\n }\n }\n return dist = Math.abs(dist * DEGREE_TO_METER);\n }", "function trasf_ecli_equa(njd,long,lat){\n\n // by Salvatore Ruiu Irgoli-Sardegna (Italy) dicembre 2009\n // funzione per trasformare le coordinate eclittiche in equatoriali.\n // long e lat: coordinate ecclittiche dell'astro in gradi sessadecimali.\n // njd=numero del giorno giuliano.\n\nvar obli_eclittica=obli_ecli(njd);\n obli_eclittica=obli_eclittica/180*Math.PI; \n \nlong=long/180*Math.PI;\n lat= lat/180*Math.PI;\n\nvar y=Math.sin(long)*Math.cos(obli_eclittica)-Math.tan(lat)*Math.sin(obli_eclittica);\nvar x=Math.cos(long);\n\nvar ascensione_retta=quadrante(y,x)/15;\n\nvar declinazione=Math.sin(lat)*Math.cos(obli_eclittica)+Math.cos(lat)*Math.sin(obli_eclittica)*Math.sin(long);\n declinazione=Math.asin(declinazione);\n declinazione=declinazione*180/Math.PI;\n\nvar coord_equa= new Array(ascensione_retta,declinazione) ; // restituisce le variabili AR e DEC .\n\nreturn coord_equa;\n\n}", "function disPoint(x1,y1,x2,y2){\n var distanceX=Math.pow((x1-x2),2)\n var distanceY=Math.pow((y1-y2),2)\n return Math.sqrt(distanceX+distanceY);\n \n}", "_coord(arr) {\n var a = arr[0], d = arr[1], b = arr[2];\n var sum, pos = [0, 0];\n sum = a + d + b;\n if (sum !== 0) {\n a /= sum;\n d /= sum;\n b /= sum;\n pos[0] = corners[0][0] * a + corners[1][0] * d + corners[2][0] * b;\n pos[1] = corners[0][1] * a + corners[1][1] * d + corners[2][1] * b;\n }\n return pos;\n }", "function ShoelaceFormula(svgVertices , startOrder, currentOrder ){\n\tlet p1, p2 = getSvgVerticeByOrder(svgVertices , startOrder);\n\n\tfor (let i of svgVertices){\n\t\tif(i.order == currentOrder)\n\t\t\tp1 = i;\n\t\telse if(i.order == currentOrder+1)\n\t\t\tp2 = i;\n\t}\n\tlet zVector = new THREE.Vector3(0, 0, 1);\n\tlet vectorP1 = p1.svgPoint.clone();\n\tlet vectorP2 = p2.svgPoint.clone();\n\tlet crossVector = vectorP1.cross(vectorP2);\n\t\n\t// -1 is counterClockwise ; 1 is Clockwise\n\treturn crossVector.dot(zVector);\n}", "function calcPoints(e) {\r\n\r\n\t\t\t\t\t// return;\r\n\t\t\t\t\tvar edge = g.edge(e.v, e.w),\r\n\t\t\t\t\t\ttail = g.node(e.v),\r\n\t\t\t\t\t\thead = g.node(e.w);\r\n\t\t\t\t\tvar points = edge.points.slice(0, edge.points.length - 1);\r\n\t\t\t\t\tvar afterslice = edge.points.slice(0, edge.points.length - 1);\r\n\r\n\t\t\t\t\t// switch (tail.shape) {\r\n\t\t\t\t\t// \tcase \"flowTask\":\r\n\t\t\t\t\t// \t\tpoints.unshift(dagreD3.intersect.rect(tail, points[0]));\r\n\t\t\t\t\t// \t\tbreak;\r\n\t\t\t\t\t// \tcase \"flowMainTask\":\r\n\t\t\t\t\t// \t\tpoints.unshift(dagreD3.intersect.rect(tail, points[0]));\r\n\t\t\t\t\t// \t\tbreak;\r\n\t\t\t\t\t// \tcase \"flowMilestone\":\r\n\t\t\t\t\t// \t\tvar tailPoints = [{\r\n\t\t\t\t\t// \t\t\tx: 0,\r\n\t\t\t\t\t// \t\t\ty: -tail.height / 2\r\n\t\t\t\t\t// \t\t}, {\r\n\t\t\t\t\t// \t\t\tx: -tail.width / 2,\r\n\t\t\t\t\t// \t\t\ty: 0\r\n\t\t\t\t\t// \t\t}, {\r\n\t\t\t\t\t// \t\t\tx: 0,\r\n\t\t\t\t\t// \t\t\ty: tail.height / 2\r\n\t\t\t\t\t// \t\t}, {\r\n\t\t\t\t\t// \t\t\tx: tail.width / 2,\r\n\t\t\t\t\t// \t\t\ty: 0\r\n\t\t\t\t\t// \t\t}];\r\n\t\t\t\t\t// \t\tpoints.unshift(dagreD3.intersect.polygon(tail, tailPoints, points[0]));\r\n\t\t\t\t\t// \t\tbreak;\r\n\t\t\t\t\t// \tdefault:\r\n\t\t\t\t\t// points.unshift(dagreD3.intersect.rect(tail, points[0]));\r\n\t\t\t\t\t// }\r\n\r\n\t\t\t\t\tswitch (head.shape) {\r\n\t\t\t\t\t\tcase \"flowTask\":\r\n\t\t\t\t\t\t\tpoints.push(dagreD3.intersect.rect(head, points[points.length - 1]));\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase \"flowMainTask\":\r\n\t\t\t\t\t\t\tpoints.push(dagreD3.intersect.rect(head, points[points.length - 1]));\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase \"flowMilestone\":\r\n\t\t\t\t\t\t\tvar headPoints = [{\r\n\t\t\t\t\t\t\t\tx: 0,\r\n\t\t\t\t\t\t\t\ty: -head.height / 2\r\n\t\t\t\t\t\t\t}, {\r\n\t\t\t\t\t\t\t\tx: -head.width / 2,\r\n\t\t\t\t\t\t\t\ty: 0\r\n\t\t\t\t\t\t\t}, {\r\n\t\t\t\t\t\t\t\tx: 0,\r\n\t\t\t\t\t\t\t\ty: head.height / 2\r\n\t\t\t\t\t\t\t}, {\r\n\t\t\t\t\t\t\t\tx: head.width / 2,\r\n\t\t\t\t\t\t\t\ty: 0\r\n\t\t\t\t\t\t\t}];\r\n\t\t\t\t\t\t\tpoints.push(dagreD3.intersect.polygon(head, headPoints, points[points.length - 1]));\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\tpoints.push(dagreD3.intersect.rect(head, points[points.length - 1]));\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tedge.points = points;\r\n\t\t\t\t\treturn d3.svg.line()\r\n\t\t\t\t\t\t.x(function(d) {\r\n\t\t\t\t\t\t\treturn d.x;\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t.y(function(d) {\r\n\t\t\t\t\t\t\treturn d.y;\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t// .interpolate(\"basis\")\r\n\t\t\t\t\t\t(points);\r\n\t\t\t\t}", "function heuristica(a, b) {\r\n var x = Math.abs(a.x - b.x);\r\n var y = Math.abs(a.y - b.y);\r\n\r\n var dist = x + y;\r\n\r\n return dist;\r\n}", "function getInner(edges)\n{\n var edd=[];\n for(var i=0;i<edges.length;i++){edd.push(pointify(edges[i]))} //Fill edd with the point notation of the data from edges\n var arr = edd.sort((a,b)=>{return a[0]-b[0]}); //Sort to get the farthest left point\n var left = arr[0][0];\n var avg = (arr[1][1] + arr[2][1])/2; //Take the avg of nearby points to get the trend of height\n return [left+1,Math.round(avg)]; //return inner point as 1 pixel to the right of the leftist edge pixel and the height of the avg\n}", "function edge(a, b) {\n if (a.row > b.row) { var t = a; a = b; b = t; }\n return {\n x0: a.column,\n y0: a.row,\n x1: b.column,\n y1: b.row,\n dx: b.column - a.column,\n dy: b.row - a.row\n };\n}", "calcDirectionCoordsForTraitor(lat1, lon1, lat2, lon2) {\n //Line will be around 1000m long or something\n const multiplier = 1000 / this.calcDistance(lat1, lon1, lat2, lon2);\n return ([{\n latitude: lat2 + ((lat1 - lat2) * multiplier),\n longitude: lon2 + ((lon1 - lon2) * multiplier)\n },\n {\n latitude: lat2,\n longitude: lon2\n }]);\n }", "function on_edge(a, e) {\n var tol = 0.01;\n var origin = e.get_origin();\n var dest = e.get_dest();\n var l1 = Math.sqrt((a.x - origin.x) * (a.x - origin.x) + (a.y - origin.y) * (a.y - origin.y));\n if (l1 < tol) {\n return true;\n }\n var l2 = Math.sqrt((a.x - dest.x) * (a.x - dest.x) + (a.y - dest.y) * (a.y - dest.y));\n if (l2 < tol) {\n return true;\n }\n var l = Math.sqrt((origin.x - dest.x) * (origin.x - dest.x) + (origin.y - dest.y) * (origin.y - dest.y));\n if (l1 > l || l2 > l) {\n return false;\n }\n if (Math.abs(l1 + l2 - l) < tol) {\n return true;\n }\n else {\n return false;\n }\n }", "function getArrowCoords(origLatLng, destLatLng, map) {\n\n var geo = google.maps.geometry.spherical;\n var bounds = map.getBounds();\n var N = bounds.f.f, W = bounds.b.b, S = bounds.f.b, E = bounds.b.f;\n var heading = geo.computeHeading(origLatLng, destLatLng);\n var headingNE = geo.computeHeading(origLatLng, new google.maps.LatLng(N,E));\n var headingNW = geo.computeHeading(origLatLng, new google.maps.LatLng(N,W));\n var headingSE = geo.computeHeading(origLatLng, new google.maps.LatLng(S,E));\n var headingSW = geo.computeHeading(origLatLng, new google.maps.LatLng(S,W));\n var padding, adjacent, hypotenuse;\n\n if ((heading < 0 && heading >= headingNW) || (heading >= 0 && heading <= headingNE)) { // north quadrant\n padding = (N-S)/PADDING_DIV;\n adjacent = geo.computeDistanceBetween(\n origLatLng, new google.maps.LatLng(N - padding, origLatLng.lng())\n );\n hypotenuse = Math.abs(adjacent / Math.cos(Math.abs(heading) * Math.PI / 180));\n } else if (headingSW < heading && heading < headingNW) { // west quadrant\n padding = Math.abs((E-W)/PADDING_DIV);\n adjacent = geo.computeDistanceBetween(\n origLatLng, new google.maps.LatLng(origLatLng.lat(), W + padding)\n );\n hypotenuse = Math.abs(adjacent / Math.cos(Math.abs(Math.abs(heading)-90) * Math.PI / 180));\n } else if (heading <= headingSW || heading >= headingSE) { // south quadrant\n padding = (N-S)/PADDING_DIV;\n adjacent = geo.computeDistanceBetween(\n origLatLng, new google.maps.LatLng(S + padding, origLatLng.lng())\n );\n hypotenuse = Math.abs(adjacent / Math.cos(Math.abs(heading) * Math.PI / 180));\n } else if (headingSE > heading && heading > headingNE) { // east quadrant\n padding = (E-W)/PADDING_DIV;\n adjacent = geo.computeDistanceBetween(\n origLatLng, new google.maps.LatLng(origLatLng.lat(), E - padding)\n );\n hypotenuse = Math.abs(adjacent / Math.cos(Math.abs(Math.abs(heading)-90) * Math.PI / 180));\n }\n\n var arrowCoords = geo.computeOffset(origLatLng, hypotenuse, heading);\n var toArrowCoords = geo.computeOffset(origLatLng, hypotenuse-0.001, heading);\n return [toArrowCoords, arrowCoords];\n\n}", "calDegrees(nodes) {\n\t\tvar xLat = this.tg.map.tgOrigin.origin.original.lat\n\t\tvar xLng = this.tg.map.tgOrigin.origin.original.lng\n\t var yLat, yLng, deg\n\n\t for(var i = 0; i < nodes.length; i++) {\n\t \tyLat = nodes[i].original.lat\n\t yLng = nodes[i].original.lng\n\t \n\t deg = Math.atan((yLng - xLng) / (yLat - xLat))\n\t if ((xLat == yLat)&&(xLng == yLng)) deg = 0\n\t if ((yLat - xLat) < 0) deg = deg + Math.PI\n\t nodes[i].deg = deg\n\t }\n\t}", "function calcPoints(e) {\r\n\t\t\t\t\t// return;\r\n\t\t\t\t\tvar edge = g.edge(e.v, e.w),\r\n\t\t\t\t\t\ttail = g.node(e.v),\r\n\t\t\t\t\t\thead = g.node(e.w);\r\n\r\n\t\t\t\t\tvar points = [];\r\n\t\t\t\t\tpoints.push(edge.points[0]);\r\n\t\t\t\t\tpoints.push(edge.points[edge.points.length - 1]);\r\n\r\n\t\t\t\t\tvar afterslice = edge.points.slice(0, edge.points.length - 1);\r\n\r\n\t\t\t\t\tswitch (head.shape) {\r\n\t\t\t\t\t\tcase \"flowTask\":\r\n\t\t\t\t\t\t\tpoints.push(dagreD3.intersect.rect(head, points[points.length - 1]));\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase \"flowMainTask\":\r\n\t\t\t\t\t\t\tpoints.push(dagreD3.intersect.rect(head, points[points.length - 1]));\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tcase \"flowMilestone\":\r\n\t\t\t\t\t\t\tvar headPoints = [{\r\n\t\t\t\t\t\t\t\tx: 0,\r\n\t\t\t\t\t\t\t\ty: -head.height / 2\r\n\t\t\t\t\t\t\t}, {\r\n\t\t\t\t\t\t\t\tx: -head.width / 2,\r\n\t\t\t\t\t\t\t\ty: 0\r\n\t\t\t\t\t\t\t}, {\r\n\t\t\t\t\t\t\t\tx: 0,\r\n\t\t\t\t\t\t\t\ty: head.height / 2\r\n\t\t\t\t\t\t\t}, {\r\n\t\t\t\t\t\t\t\tx: head.width / 2,\r\n\t\t\t\t\t\t\t\ty: 0\r\n\t\t\t\t\t\t\t}];\r\n\t\t\t\t\t\t\tpoints.push(dagreD3.intersect.polygon(head, headPoints, points[points.length - 1]));\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\tdefault:\r\n\t\t\t\t\t\t\tpoints.push(dagreD3.intersect.rect(head, points[points.length - 1]));\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tedge.points = points;\r\n\t\t\t\t\treturn d3.svg.line()\r\n\t\t\t\t\t\t.x(function(d) {\r\n\t\t\t\t\t\t\treturn d.x;\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t.y(function(d) {\r\n\t\t\t\t\t\t\treturn d.y;\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t(points);\r\n\t\t\t\t}" ]
[ "0.60282046", "0.5972613", "0.5940183", "0.5937488", "0.59330994", "0.59179926", "0.5848582", "0.5832108", "0.5809546", "0.5809546", "0.5731715", "0.57182956", "0.569109", "0.5689905", "0.5665226", "0.56597245", "0.5636308", "0.5621863", "0.56040365", "0.5544962", "0.55060184", "0.5499898", "0.5499191", "0.54888743", "0.5485166", "0.5476604", "0.54733294", "0.54730535", "0.54638976", "0.5461973" ]
0.7299202
0
/ This will consume any overflow in the time accumulated from 'UpdateTime' in 'FixedTimeStep' chunks. / The passed functoin will be invoked for each consumed chunk. This allows us to catch up with any / fraction portions of our fixed time step that overflowed during the normal update cycle.
static ConsumeAccumulatedTime(func) { let stepped = 0; let stepRate = FIXED_TIME_STEP; while(Time._accu >= stepRate) { stepped++; func(); Time._accu -= stepRate; //this is a safety feature to ensure we never take longer than an allowed maximum time. if(Time._time - Time._lastTime > MAX_TIME_STEP) { Time._accu = 0; return false; } } return true; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "update(timeStep) {\n\n }", "function timeStepUpdate() {\n if (incrementing == false) {\n incrementing = true;\n setTimeout(function () {\n time += 1;\n incrementing = false;\n }, timeStep * 1000);\n }\n}", "_processTick(tickTime, ticks) {\n // do the loop test\n if (this._loop.get(tickTime)) {\n if (ticks >= this._loopEnd) {\n this.emit(\"loopEnd\", tickTime);\n this._clock.setTicksAtTime(this._loopStart, tickTime);\n ticks = this._loopStart;\n this.emit(\"loopStart\", tickTime, this._clock.getSecondsAtTime(tickTime));\n this.emit(\"loop\", tickTime);\n }\n }\n // handle swing\n if (this._swingAmount > 0 &&\n ticks % this._ppq !== 0 && // not on a downbeat\n ticks % (this._swingTicks * 2) !== 0) {\n // add some swing\n const progress = (ticks % (this._swingTicks * 2)) / (this._swingTicks * 2);\n const amount = Math.sin(progress * Math.PI) * this._swingAmount;\n tickTime +=\n new TicksClass(this.context, (this._swingTicks * 2) / 3).toSeconds() * amount;\n }\n // invoke the timeline events scheduled on this tick\n enterScheduledCallback(true);\n this._timeline.forEachAtTime(ticks, (event) => event.invoke(tickTime));\n enterScheduledCallback(false);\n }", "function recomputeCallback() {\n var len = TO_CALL.length;\n CALL_TIMEOUT = null;\n while (len--) {\n (TO_CALL.shift() || NOOP).call();\n }\n\n TO_CALL.added = {};\n}", "update() {\n \n /* Run update piped methods on the corresponding frame */\n const { pipeline } = this;\n let x = 0, len = pipeline.length, item;\n \n for(x;x<len;x++)\n {\n item = pipeline[x];\n \n /* run frame delayed methods based on frame delay count */\n if(item.delay)\n {\n item.curr += 1;\n if(item.curr === item.delay)\n {\n item.curr = 0; item();\n }\n }\n \n /* run time based delayed methods based on the amount of time passed */\n else if(item.time)\n {\n const now = Date.now();\n if(now - item.curr >= item.time)\n {\n item.curr = now; item();\n }\n }\n \n /* run the item on each frame */\n else\n {\n item();\n \n /* remove items marked for single use */\n if(item.once) { pipeline.splice(x, 1); len = pipeline.length; x -= 1; }\n }\n }\n }", "update () {\n\n this.particleSystem.step(\n this.stopwatch.getElapsedMs() * 0.001)\n\n this.updateChunk ()\n\n // invalidate (needsClear, needsRender, overlayDirty)\n this.viewer.impl.invalidate(true, false, false)\n\n this.emit('fps.tick')\n }", "function loopFn() {\n\n // check that we're actually running...\n if (running) {\n\n var currentTime = new Date().getTime();\n var timeChange = currentTime - lastTime;\n var currentScroll = getScrollPos();\n\n // check if resize\n if (document.body.offsetWidth !== lastBodyWidth || document.body.offsetHeight !== lastBodyHeight) {\n // resize is true, save new sizes\n lastBodyWidth = document.body.offsetWidth;\n lastBodyHeight = document.body.offsetHeight;\n\n if (resizeTimeout)\n window.clearTimeout(resizeTimeout);\n resizeTimeout = window.setTimeout(function () {\n doLoopFunctions('resize',currentTime);\n }, resizeDebounce);\n }\n\n // check if scroll\n if (lastScroll !== currentScroll) {\n // scroll is true, save new position\n lastScroll = currentScroll;\n\n // call each function\n doLoopFunctions('scroll',currentTime);\n }\n\n // do the always functions\n doLoopFunctions('tick',currentTime);\n\n // save the new time\n lastTime = currentTime;\n\n\t\t\t// make sure we do the tick again next time\n\t requestAnimationFrame(loopFn);\n }\n }", "constructor (fixedTicksPerSeconds) {\n\t\tthis.frame = this.loop.bind(this);\n\t\tthis.fixedUpdateTimer = this.fixedInterval;\n\t\tthis.fixedTicksPerSeconds = fixedTicksPerSeconds;\n\t}", "function insulinOnBoardCalculator (iobObject) { //should update iob via formula & PUT call\n console.log(iobObject);\n //CURRENT issues:\n //Either need to make function for ONE array element at a Time OR\n //Find a way to clear all but one Set-timeout at a time\n\n let currentInsulinStack = [...iobObject.insulinStack];\n let updatedInsulinStack, bolusRate, stackLength;\n let duration = iobObject.duration;\n let iobId = $('#current-user-iob').val();\n let settingId = $('#current-user-settings').val();\n\n let totalIOBAmount = iobObject.iobAmount;\n let totalIOBTime = iobObject.iobTime;\n\n //Update Entries if there are any\n if (currentInsulinStack.length > 0) {\n\n //Updates Each Entry on insulin stack\n updatedInsulinStack = currentInsulinStack.map((el, ind) => {\n console.log(el);\n //For each element...Subtract 5 minutes, min = 0 and max = set duration\n el.timeRemaining = Math.min(Math.max((el.timeRemaining - 300000), 0), duration);\n\n //When all entries have 0 time remaining, stop recursively calling\n if (el.timeRemaining === 0) {\n //update everything to 0\n\n el.currentInsulin = 0;\n console.log('Time @ 0');\n }\n //First 15 minutes - time changes, insulin amount does not\n else if (el.timeRemaining >= (duration-900000)) {\n //Minus 5 minutes\n console.log('First 15 minutes', el.timeRemaining);\n }\n //first half of entry duration\n else if (el.timeRemaining >= (duration/2)) {\n bolusRate = ((el.entryAmount/2)/((duration-900000)/2))*300000; //5 minute increments\n el.currentInsulin = Math.max((el.currentInsulin - bolusRate), 0);\n totalIOBAmount -= bolusRate;\n console.log('First Half rate');\n }\n //second half of entry duration\n else if (el.timeRemaining < (duration/2)) {\n bolusRate = ((el.entryAmount/2)/((duration/2)))*300000; //5 minute increments\n // el.currentInsulin = Math.max((el.currentInsulin - bolusRate), 0);\n el.currentInsulin -= bolusRate;\n totalIOBAmount -= bolusRate;\n console.log('Second Half rate', bolusRate);\n }\n //Catch errors\n else {\n console.log('Something went wrong in IOB');\n return false;\n }\n\n return el;\n //Filter out entries that have zeroed out Locally and on Server\n }).filter((el)=> {\n console.log(el);\n if (el.timeRemaining === 0) deleteStackEntry(iobId, el._id);\n return !(el.timeRemaining === 0);\n });\n console.log(updatedInsulinStack);\n } else {\n updatedInsulinStack = [];\n }\n //Updating 5 minute time passage\n\n totalIOBTime = Math.min(Math.max((totalIOBTime - 300000), 0), duration);\n console.log('total Time' + totalIOBTime);\n //Set displayed IOB Totals\n $('#i-o-b').text(`${Math.round(totalIOBAmount * 100) / 100}`);\n $('#iob-time').text(`${Math.round((totalIOBTime/3600000) * 100) / 100}`);\n\n if (updatedInsulinStack.length === 0 || !updatedInsulinStack) {\n //Update each entry on insulin Stack\n updatedInsulinStack.map((el) => {\n updateStackEntry(el._id, el);\n })\n }\n //Update IOB Totals\n updateIob(iobId, {\n insulinOnBoard: {\n amount: totalIOBAmount,\n timeLeft: totalIOBTime\n }\n });\n //recursively call insulinOnBoard in 5 minutes\n setTimeout(() => {\n console.log('Timeout over', totalIOBTime, totalIOBAmount);\n\n insulinOnBoardCalculator({\n insulinStack: updatedInsulinStack,\n duration: iobObject.duration,\n iobAmount: totalIOBAmount,\n iobTime: totalIOBTime\n })\n }, 5000);//300000\n\n //If no entries left on stack, end recursive call\n// if (updatedInsulinStack.length === 0 || totalIOBAmount === 0 || totalIOBTime === 0) {\n// console.log('No entries in Insulin stack');\n//\n// updateIob(iobId, {\n// insulinOnBoard: { amount: 0, timeLeft: 0},\n// currentInsulinStack: [...updatedInsulinStack] //need to delete each entry?\n// });\n//\n// $('#i-o-b').text(`0`);\n// $('#iob-time').text(`0`);\n//\n// }\n // else {\n // console.log('Where insulinOnBoard called again')\n // //call to Update IOB Setting\n //\n // }\n}", "function update(time)\n {\n\t //console.log(\"UPDATE\");\n\t // calculation\n }", "updateR() {\n if (this.lastRUpdate==0 || globalUpdateCount - this.lastRUpdate >= DAY_LENGTH) {\n let pts = this.fields.map(f => f.pts).reduce((acc, pts) => acc.concat(pts), [])\n pts.push(...this.sender.objs.map(o => o.point))\n \n let nInfectious = 0\n const val = pts\n .map(pt => {\n if (pt.isInfectious()) {\n nInfectious += 1\n const timeInfectious = globalUpdateCount - pt.lastStatusUpdate + (pt.status == Point.INFECTIOUS2) ? Point.infectious1Interval : 0\n if (timeInfectious>0) {\n const timeRemaining = Point.infectious2Interval + Point.infectious1Interval - timeInfectious\n return pt.nInfected/timeInfectious*timeRemaining // estimated infections over duration of illness\n } else return 0\n } else return 0\n })\n .reduce((sum, ei) => sum + ei)\n \n if (nInfectious>0) {\n this.rVal = val/nInfectious\n this.rMax = this.rMax < this.rVal ? this.rVal : this.rMax\n } else this.rVal = 0\n this.lastRUpdate = globalUpdateCount\n }\n }", "update() {\n var lastTime = this.curTime;\n this.curTime += renko.fateFX.deltaTime * this.speed;\n\n this.updateSections(this.curTime, lastTime);\n\n // On update finished\n if(this.curTime > this.totalDuration) {\n this.handleUpdateFinished();\n }\n }", "update(time, delta) {\n }", "advance(numTimes, callback) {\n var _numTimes = numTimes || 1;\n\n _.times(_numTimes, () => {\n // update one time observers\n this.oneTimeFunctions.forEach(fn => fn());\n this.oneTimeFunctions = [];\n\n // update continue observers\n this.observers.forEach(observer => {\n observer.update();\n });\n\n this.currentTimeStep++; // should this go before or after updates? test!\n\n // for debugging\n if (callback) {\n callback();\n }\n });\n }", "function tick()\n {\n \t// schedule the next tick call.\n requestId = window.requestAnimationFrame(function(){ tick(); });\n \n // calculate the time since last tick in ms\n tickNow = Date.now();\n tickDelta = tickNow - tickThen;\n \n // if it's been long enough, call the given function.\n if (tickDelta >= tickInterval)\n {\n \t// adjust the tickThen time by how far OVER the tickInterval we went.\n tickThen = tickNow - (tickInterval !== 0 ? (tickDelta % tickInterval) : 0);\n \n if (obj === null)\n func(tickDelta);\n else\n func.call(obj, tickDelta);\n }\n }", "step(elapsed) {\r\n if (this.done) {\r\n return\r\n }\r\n\r\n console.log(elapsed)\r\n if (this.changes.length == 0) {\r\n console.log(\"getting more things\")\r\n this.update()\r\n }\r\n\r\n for (i in this.changes) {\r\n console.log(i, \" \", this.changes[i])\r\n if (this.changes[i].duration <= 0) {\r\n // remove, but ideally would have list sorted by duration remaining?\r\n this.changes.splice(i, 1)\r\n }\r\n\r\n }\r\n\r\n\r\n }", "_eventsUpdated() {\n this._part.clear();\n this._rescheduleSequence(this._eventsArray, this._subdivision, this.startOffset);\n // update the loopEnd\n this.loopEnd = this.loopEnd;\n }", "function part6() {\n\t\tclearImmediate(setImmediate(f6));\n\t\tclearTimeout(setTimeout(f6, 0));\n\t\tclearInterval(setInterval(f6, 0));\n\t\t//no way to stop a tick, so we won't start one here\n\t\tif (typeof requestAnimationFrame != \"undefined\") cancelAnimationFrame(requestAnimationFrame(f6));\n\t\tfunction f6() {\n\t\t\tspace(\"this should never get called!\");\n\t\t}\n\t\tpart7();\n\t}", "update() {\n if (this._futureTrackDeltaTimeCache !== -1) {\n return;\n }\n\n const currentTime = this.gameTimeSeconds;\n\n this._incrementFrame();\n this._calculateNextDeltaTime(currentTime);\n this._calculateFrameStep();\n }", "function fixedUpdate(args, ctx) {\n}", "update () {\n\n this.lastTime = this.time;\n\n this.time = Date.now();\n\n this.elapsedMS = this.time - this.lastTime;\n\n this.deltaScale = (this.elapsedMS / this._desiredFrameDurationMS) * this._timeScale;\n\n this.now = this.time;\n\n if (this.playing) {\n \n window.requestAnimationFrame(this.update.bind(this));\n\n this.eventObj.now = this.now;\n this.eventObj.elapsed = this.elapsedMS;\n this.eventObj.delta_scale = this.deltaScale;\n\n for (var i = 0, l = this._updates.length; i < l; i++) {\n this._updates[i](this.eventObj);\n }\n }\n }", "step(now) {\n let percent;\n if( this.duration === 0 ){\n percent = 1;\n } else {\n percent = (now - this.startTime) / this.duration;\n }\n\n for (let i = 0; i < this.nodeContainer.instanceCount; i++) {\n const currentPosition = this.calStep(\n { x: this.startPositions[2 * i], y: this.startPositions[2 * i +1 ]},\n { x: this.endPositions[2 * i], y: this.endPositions[2 * i +1 ]},\n percent\n );\n\n const nodeId = this.nodeContainer.idIndexMap.idFrom(i);\n const nodeSprite = this.nodeSprites[nodeId];\n nodeSprite.updateNodePosition(currentPosition);\n this.nodeContainer.nodeMoved(nodeSprite);\n }\n\n Object.values(this.edgeSprites).forEach((link) => {\n link.updatePosition();\n });\n\n if (percent > 1) {\n this.resolve();\n } else {\n requestAnimationFrame(this.step.bind(this));\n }\n }", "function d3_timer_sweep() {\n var t0,\n t1 = d3_timer_queueHead,\n time = Infinity;\n while (t1) {\n if (t1.f) {\n t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n;\n } else {\n if (t1.t < time) time = t1.t;\n t1 = (t0 = t1).n;\n }\n }\n d3_timer_queueTail = t0;\n return time;\n }", "function updateEta(num){\n\tif(currentEta <= 0){\n\t currentEta = 0;\n\t}\n\telse {\n\t currentEta = totalTime - (num * (timePerStep/60)/60);\n\t}\n }", "function step() {\n callback();\n window.requestAnimationFrame(step);\n }", "function part7() {\n\t\tstart = tick();\n\t\tcount = 0;\n\t\tvar timer7 = Timer();\n\t\ttimer7.immediate(f7);\n\t\tfunction f7() {\n\t\t\tif (tick() < start + 1000) {\n\t\t\t\tcount++;\n\t\t\t\ttimer7.immediate(f7);\n\t\t\t} else {\n\t\t\t\tlog(commas(count) + \" Timer's .immediate()\");\n\t\t\t\tshut(timer7);\n\t\t\t\tpart8();\n\t\t\t}\n\t\t}\n\t}", "performFinalCorrection(amount) {\n\n console.log(\"entering performFinalCorrection()\");\n\n let who = this.sjs.id;\n\n let bumpMs = 300;\n\n let limit = 128;\n\n let acc = 0;\n\n let curMs = 0;\n\n while(acc < amount) {\n let thisOne = Math.min(limit,amount-acc);\n\n // if( (amount-limit) > 0 ) {\n // amount -= thisOne;\n // }\n\n setTimeout(()=>{\n console.log(\"run: \" + thisOne);\n this.sjs.dsp.setPartnerSfoAdvance(who, thisOne, 4, false);\n },curMs);\n\n curMs += bumpMs;\n acc += thisOne;\n }\n\n setTimeout(()=>{\n if( this.onDoneCb ) {\n this.onDoneCb();\n }\n }, curMs);\n\n }", "group( state, pattern, phase, duration, overrideIncr=null ) {\n const start = phase.clone(),\n end = start.add( duration ),\n phaseIncr = overrideIncr === null \n ? getPhaseIncr( pattern ) \n : overrideIncr\n \n let eventList = []\n\n //console.log( \n // 'type:', pattern.type, \n // 'phase:', phase.toFraction(),\n // 'incr:', phaseIncr.toFraction(),\n // 'dur:', duration.toFraction()\n //)\n \n while( phase.compare( end ) < 0 ) {\n // if pattern is a list, read using current phase, else read directly\n const member = Array.isArray( pattern.values ) === true \n ? pattern.values[ getIndex( pattern, phase ) ] \n : pattern.value\n\n // get duration of current event being processed\n const dur = calculateDuration( phase, phaseIncr, end )\n\n // if value is not a numeric or string constant (if it's a pattern)...\n if( member === undefined || (isNaN( member.value ) && typeof member.value !== 'string') ) {\n // query the pattern and remap time values appropriately \n if( member !== undefined ) member.parent = pattern\n //console.log( 'processing ', pattern.type, member.type, dur.toFraction(), phaseIncr.toFraction() )\n const events = processPattern( \n member, \n Fraction(1), \n //member.type !== 'slow' ? Fraction(0) : phase.clone(), \n Fraction(0),\n null, //getPhaseIncr(member),\n null, \n false//shouldRemap( member )\n )\n .map( evt => {\n evt.arc.start = evt.arc.start.mul( dur ).add( phase )\n evt.arc.end = evt.arc.end.mul( dur ).add( phase )\n return evt\n })\n\n eventList = eventList.concat( events )\n }else{\n // XXX shouldn't we just process all patterns???\n // member does not need further processing, so add to event list\n const evt = { \n value:member.value, \n arc:Arc( phase, phase.add( dur ) ),\n }\n if( member.uid !== undefined ) evt.uid = member.uid \n\n eventList.push( evt )\n }\n\n // assuming we are starting / ending at a regular phase increment value...\n \n if( phase.mod( phaseIncr ).valueOf() === 0 ) {\n phase = advancePhase( phase, phaseIncr, end )\n }else{\n // advance phase to next phase increment\n phase = phase.add( phaseIncr.sub( phase.mod( phaseIncr ) ) ) \n }\n }\n\n // prune any events that fall before our start phase or after our end phase\n eventList = eventList.filter( evt => {\n return evt.arc.start.valueOf() >= start.valueOf() && evt.arc.start.valueOf() < end.valueOf()\n })\n \n return state.concat( eventList )\n }", "manageTimeSlice(currentProcess, time) {\n // console.log(\"This is the quantum\", this.quantum);\n // console.log(\"This is the priorityLevel\", this.priorityLevel);\n // console.log(\"Current process and time\", currentProcess, time);\n if (currentProcess.stateChanged === true) {\n // console.log(\"What is the queu of this TRUE,\",currentProcess);\n // console.log(\"state is true, don't affect this process\");\n return currentProcess;\n }\n if (currentProcess.stateChanged === false) {\n console.log(\"What is the cpuTimeNeeded of this,\", currentProcess.cpuTimeNeeded);\n console.log(\"This is the passed in time\", time);\n let timeAfterQuantime = this.doCPUWork(time);\n if (timeAfterQuantime === 0 || timeAfterQuantime < 0) {\n console.log(\"Returned after cpuWork, time\", timeAfterQuantime);\n // this.dequeue();\n };\n if (timeAfterQuantime !== 0 || timeAfterQuantime > 0) {\n console.log(\"Returned after cpuWork, not complete, time\", timeAfterQuantime);\n // this.dequeue();\n this.doBlockingWork(timeAfterQuantime);\n };\n // currentProcess.cpuTimeNeeded -= time;\n }\n\n\n }", "function _update(deltaTime) {\n _gameTime += deltaTime;\n\n var i;\n\n // Check whether this chapter has been completed\n if ((_scoreToEndChapter > 0 && _score >= _scoreToEndChapter) || \n (_layersToEndChapter > 0 && _layersCollapsedCount >= _layersToEndChapter)) {\n _endGame(null, true);\n } else {\n input.update(deltaTime);\n\n gameWindow.update(deltaTime);\n\n game.collapseBombWindow.update(deltaTime);\n game.settleBombWindow.update(deltaTime);\n\n // Update the preview windows\n switch (game.numberOfSidesBlocksFallFrom) {\n case 4:\n for (i = 0; i < 4; ++i) {\n game.previewWindows[i].update(deltaTime);\n if (game.previewWindows[i].isCoolDownFinished()) {\n _setupNextBlock(game.previewWindows[i]);\n }\n }\n break;\n case 3:\n game.previewWindows[0].update(deltaTime);\n if (game.previewWindows[0].isCoolDownFinished()) {\n _setupNextBlock(game.previewWindows[0]);\n }\n game.previewWindows[1].update(deltaTime);\n if (game.previewWindows[1].isCoolDownFinished()) {\n _setupNextBlock(game.previewWindows[1]);\n }\n game.previewWindows[3].update(deltaTime);\n if (game.previewWindows[3].isCoolDownFinished()) {\n _setupNextBlock(game.previewWindows[3]);\n }\n break;\n case 2:\n game.previewWindows[1].update(deltaTime);\n if (game.previewWindows[1].isCoolDownFinished()) {\n _setupNextBlock(game.previewWindows[1]);\n }\n game.previewWindows[3].update(deltaTime);\n if (game.previewWindows[3].isCoolDownFinished()) {\n _setupNextBlock(game.previewWindows[3]);\n }\n break;\n case 1:\n game.previewWindows[0].update(deltaTime);\n if (game.previewWindows[0].isCoolDownFinished()) {\n _setupNextBlock(game.previewWindows[0]);\n }\n break;\n default:\n return;\n }\n }\n }" ]
[ "0.5634498", "0.50159085", "0.49622566", "0.49606362", "0.48251945", "0.48162657", "0.48135534", "0.48130465", "0.47721896", "0.47691166", "0.47629115", "0.47433683", "0.4713767", "0.47011852", "0.46780702", "0.4674049", "0.4664973", "0.46626997", "0.4643626", "0.463386", "0.46319994", "0.46250552", "0.46204817", "0.46020302", "0.4601572", "0.45783377", "0.45742905", "0.45732558", "0.4562005", "0.45539328" ]
0.55785924
1
Generate a snapshot name given a base.
function snapshotName(base) { "use strict"; var when = formatDate(new Date()); return base + '-' + when; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function generateUsername(base) {\n base = base.toLowerCase();\n var entries = [];\n var finalName;\n return userDB.allDocs({startkey: base, endkey: base + '\\uffff', include_docs: false})\n .then(function(results){\n if(results.rows.length === 0) {\n return BPromise.resolve(base);\n }\n for(var i=0; i<results.rows.length; i++) {\n entries.push(results.rows[i].id);\n }\n if(entries.indexOf(base) === -1) {\n return BPromise.resolve(base);\n }\n var num = 0;\n while(!finalName) {\n num++;\n if(entries.indexOf(base+num) === -1) {\n finalName = base + num;\n }\n }\n return BPromise.resolve(finalName);\n });\n }", "function NavMakeFileName(/**string*/ root, /**string*/ baseName, /**string*/ number, /**string*/ extension)\r\n{\r\n\treturn root + \"\\\\\" + baseName + number + \".\" + extension;\r\n}", "function makeUniqueName(baseName) {\n // Find the first unique 'name_n', where n is a positive number\n if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {\n baseName += \"_\";\n }\n var i = 1;\n while (true) {\n var generatedName = baseName + i;\n if (isUniqueName(generatedName)) {\n return generatedNameSet[generatedName] = generatedName;\n }\n i++;\n }\n }", "function uniqueIDName(idBase, idIdx){\r\n /// returns unique ID name to be used when generating id names\r\n return idBase + idIdx;\r\n }", "publicName() {\n if (this.isSnapshot()) {\n return `${this.blobName}-${Date.parse(this.snapshotDate)}`;\n }\n if (this.isVirtualDirectory()) {\n return Buffer.from(this.blobName, 'utf8').toString('base64');\n }\n return this.blobName;\n }", "function getUniqScreenshotName() {\n //use the current date/time \"now\" variable captured when the program first ran \n //for the folder names\n const todaysDate = dateFormat(now, \"mm_dd_yy\");\n const startTime = dateFormat(now, \"h_MM_ss_TT\");\n \n //folder to store the screenshots\n const baseScreenshotFolder = \"screenshots\";\n const subFolder = todaysDate + \"__\" + startTime;\n const folderpath = baseScreenshotFolder + \"/\" + subFolder + \"/\";\n //create folders if they dont exist\n if (!fs.existsSync(baseScreenshotFolder)){fs.mkdirSync(baseScreenshotFolder);}\n if (!fs.existsSync(folderpath)){fs.mkdirSync(folderpath);} \n \n // increment the screenshot counter, i.e Awd3.png\n screenshotCounter = screenshotCounter + 1;\n console.log(\"should be creating screenshot: \" + folderpath + currModule + screenshotCounter + \".png\");\n return folderpath + currModule + screenshotCounter + \".png\";\n}", "publicName() {\n if (this.isSnapshot()) {\n return `${this.name}-${Date.parse(this.snapshotDate)}`;\n }\n if (this.isVirtualDirectory()) {\n return Buffer.from(this.name, 'utf8').toString('base64');\n }\n return this.name;\n }", "_getUniqueIdentifier(sourceFile, baseName) {\n if (this.isUniqueIdentifierName(sourceFile, baseName)) {\n this._recordUsedIdentifier(sourceFile, baseName);\n return ts.createIdentifier(baseName);\n }\n let name = null;\n let counter = 1;\n do {\n name = `${baseName}_${counter++}`;\n } while (!this.isUniqueIdentifierName(sourceFile, name));\n this._recordUsedIdentifier(sourceFile, name);\n return ts.createIdentifier(name);\n }", "function generateNewID(obj, base) {\n\t\tvar number = 1;\n\t\tbase = base || 'id';\n\t\tvar id = ('' + base + number);\n\t\twhile (obj.hasOwnProperty(id)) id = ('' + base + (++number));\n\n\t\treturn id;\n\t}", "function makeUniqueFrameName(baseName) {\n var objArray,tagCounter=1,i,possName,name,DOM,nameList=\"\";\n\n possName = baseName;\n DOM = dreamweaver.getDocumentDOM(\"parent\");\n if (!DOM) DOM = dreamweaver.getDocumentDOM(\"document\");\n objArray = DOM.body.getElementsByTagName('FRAME');\n if (objArray.length > 0) { //other images, check\n for (i=0; i<objArray.length; i++) { //create list of all img names\n name = objArray[i].getAttribute(\"name\"); if (name) nameList += \" \" + name + \" \";\n name = objArray[i].getAttribute(\"id\"); if (name) nameList += \" \" + name + \" \";\n }\n while (nameList.indexOf(possName) != -1) possName = baseName+tagCounter++; //find 1st avail\n }\n return possName\n}", "function globular_freshName(n) {\n return n.toString() + '-' + Math.random().toString(36).slice(2);\n}", "function _generateCurrentName() {\n NameWebAPIUtils.getNewCurrentName();\n}", "function baseName(str) {\n var base = new String(str).substring(str.lastIndexOf('/') + 1);\n if (base.lastIndexOf('.') !== -1) {\n base = base.substring(0, base.lastIndexOf('.'));\n }\n return base;\n}", "function profileNameToFileName(baseFileName, profileName) {\n var prefix = \"\";\n if (profileName) {\n prefix = profileName + \"-\";\n }\n return path.join(\n path.dirname(baseFileName),\n prefix + path.basename(baseFileName)\n );\n}", "function baseObj(name, baseDir) {\n var src = name.replace(/ /g , '');\n var baseDir = baseDir || 'Sp14/';\n return { name: name,\n img: baseDir + src + '.jpg',\n imgSrc: src + '.jpg' };\n}", "function getFullShotFileName (pageName, viewport) {\n return options.screenshotDir + '/originals/' + pageName + '_' + viewport.width + 'x' + viewport.height + '_full-page.png';\n }", "uniqueName(prefix) { return `${prefix}${this.nextNameIndex++}`; }", "uniqueName(prefix) { return `${prefix}${this.nextNameIndex++}`; }", "uniqueName(prefix) { return `${prefix}${this.nextNameIndex++}`; }", "function makeFileName (fileName) {\n\t\treturn (+new Date()) + '_' + fileName;\n\t}", "function generateUniqueString(prefix) {\n return `${prefix}-${Date.now()}-${Math.round(Math.random() * 1000000)}`;\n}", "function fn_getuniquefilename()\r\n{\r\n\tvar indate,inthr,intmi,intsec;\r\n\tindate = aqConvert.DateTimeToFormatStr(aqDateTime.Today(),\"%b_%d_%y\");\r\n\tinthr = aqDateTime.GetHours(aqDateTime.Now());\r\n\tintmi = aqDateTime.GetMinutes(aqDateTime.Now());\r\n\tintsec = aqDateTime.GetSeconds(aqDateTime.Now());\r\n\treturn indate + \"-\" + inthr + \"_\" + intmi + \"_\" + intsec;\r\n\t\r\n}", "createSnapshot(){\r\n let fs = require('fs');\r\n let fname = `data/snap${Date.now()}.bck`;\r\n let ws = fs.createWriteStream(fname);\r\n let base64Buffer = new Buffer.from(this.s.read());\r\n ws.write(base64Buffer.toString('base64'));\r\n }", "createSnapshot(){\r\n let fs = require('fs');\r\n let fname = `data/snap${Date.now()}.bck`;\r\n let ws = fs.createWriteStream(fname);\r\n let base64Buffer = new Buffer.from(this.s.read());\r\n ws.write(base64Buffer.toString('base64'));\r\n }", "function random_logo_name(max,prefix,suffix)\n{\n var rand_no = Math.floor((max+1) * Math.random())\n return prefix + rand_no + suffix\n}", "function generateName() {\n var sRnd = '';\n var sChrs = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz\";\n for (var i = 0; i < 5; i++) {\n var randomPoz = Math.floor(Math.random() * sChrs.length);\n sRnd += sChrs.substring(randomPoz, randomPoz + 1);\n }\n return sRnd;\n}", "generateResourceID(base=\"\"){function idPart(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}return base+idPart()+idPart()+\"-\"+idPart()+\"-\"+idPart()+\"-\"+idPart()+\"-\"+idPart()+idPart()+idPart()}", "function getUniqueImageFileName( type ) {\n\t\tvar date = new Date(),\n\t\t\tdateParts = [ date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds() ];\n\n\t\tuniqueNameCounter += 1;\n\n\t\treturn 'image-' + CKEDITOR.tools.array.map( dateParts, padNumber ).join( '' ) + '-' + uniqueNameCounter + '.' + type;\n\t}", "function base(dec, base) {\n var len = base.length;\n var ret = '';\n while(dec > 0) {\n ret = base.charAt(dec % len) + ret;\n dec = Math.floor(dec / len);\n }\n return ret;\n}", "static generateHashMNameByMName(name) {\n return `yrv_${YrvUtil.getHashCode(name)}`\n }" ]
[ "0.65490043", "0.6277193", "0.6116239", "0.60826117", "0.5952341", "0.5876089", "0.58199483", "0.573663", "0.5692679", "0.5687249", "0.5618089", "0.5602993", "0.5602118", "0.5575302", "0.5533787", "0.5522069", "0.55129623", "0.55129623", "0.55129623", "0.5436213", "0.5373377", "0.5371866", "0.5304354", "0.5299467", "0.52868545", "0.52741456", "0.5271267", "0.5249236", "0.52096784", "0.52070713" ]
0.8544114
0
Create a snapshot on the specified dataset with the specified name, exluding all datasets in excl.
function createSnapshot(ds, sn, excl) { "use strict"; function destroyExcludes(snaps, excl) { var toDestroy = snaps.filter(function (s) { var fields = s.name.split('@'); var createdNow = fields[1] === sn; var inExclude = _.contains(excl, fields[0]); return createdNow && inExclude; }); async.forEachSeries(toDestroy, function (snap, cb) { util.log('Destroy snapshot ' + snap.name + ' (excluded)'); zfs.destroy({ name: snap.name, recursive: true }, cb); }); } util.log('Create snapshot ' + ds + '@' + sn); zfs.snapshot({ dataset: ds, name: sn, recursive: true }, function (err) { if (err) { util.log(err); } else { zfs.list({ type: 'snapshot' }, function (err, snaps) { if (err) { util.log(err); } else { destroyExcludes(snaps, excl); } }); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async snap(name) {\n await this.nemo.screenshot.snap(name || 'screenshot')\n }", "takeMemorySnapshot(name) {\n if (!isProfiling) return;\n const snapshot = profiler.takeSnapshot(name);\n const heapFileName = path.join(__dirname, `../../performance/memory/${name}_${(new Date().toISOString())}.heapsnapshot`);\n\n console.log(snapshot.getHeader());\n snapshot.export((error, result) => {\n if (error) {\n console.error('ERROR == ', error);\n }\n fs.writeFile(heapFileName, result, { flag: 'wx' }, (err) => {\n if (err) throw err;\n snapshot.delete();\n });\n });\n }", "function createSnapshot() {\n let xmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);\n let xmlText = Blockly.Xml.domToPrettyText(xmlDom);\n localStorage.setItem(\"blockly.xml\", xmlText);\n displaySuccessNotification(\".menu\",\"Snapshot created\");\n}", "function saveImageData(data, name) {\n //combine all data into object\n ret = {}\n for (key in data) {\n //get images for one product\n var imagePath = data[key][name];\n var jdata = JSON.parse(imagePath);\n\n //put the images into object, key is product id(0,1,2,3,4...)\n ret[key] = jdata;\n }\n allData[name] = ret;\n}", "function copyDatasetForRenaming(dataset) {\n return utils.defaults({\n layers: dataset.layers.map(function(lyr) {return utils.extend({}, lyr);})\n }, dataset);\n }", "function createASnapshotFromAnExistingSnapshotInTheSameOrADifferentSubscription() {\n return __awaiter(this, void 0, void 0, function* () {\n const subscriptionId = \"{subscription-id}\";\n const resourceGroupName = \"myResourceGroup\";\n const snapshotName = \"mySnapshot2\";\n const snapshot = {\n creationData: {\n createOption: \"Copy\",\n sourceResourceId: \"subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/mySnapshot1\"\n },\n location: \"West US\"\n };\n const credential = new DefaultAzureCredential();\n const client = new ComputeManagementClient(credential, subscriptionId);\n const result = yield client.snapshots.beginCreateOrUpdateAndWait(resourceGroupName, snapshotName, snapshot);\n console.log(result);\n });\n}", "function createASnapshotFromAnExistingSnapshotInTheSameOrADifferentSubscriptionInADifferentRegion() {\n return __awaiter(this, void 0, void 0, function* () {\n const subscriptionId = \"{subscription-id}\";\n const resourceGroupName = \"myResourceGroup\";\n const snapshotName = \"mySnapshot2\";\n const snapshot = {\n creationData: {\n createOption: \"CopyStart\",\n sourceResourceId: \"subscriptions/{subscription-id}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/mySnapshot1\"\n },\n location: \"West US\"\n };\n const credential = new DefaultAzureCredential();\n const client = new ComputeManagementClient(credential, subscriptionId);\n const result = yield client.snapshots.beginCreateOrUpdateAndWait(resourceGroupName, snapshotName, snapshot);\n console.log(result);\n });\n}", "function createDataDir(snapshot) {\n return __awaiter(this, void 0, void 0, function* () {\n console.log('Writing snapshot data ...');\n const genPath = path.join(snapshot.rootPath, '.data');\n util.mkdirP(genPath);\n });\n}", "function addDataset(element, dataset) {\r\n for (var name_2 in dataset) {\r\n element.setAttribute(\"data-\" + name_2, dataset[name_2]);\r\n }\r\n }", "function setDataToLocalStroage(name, data) {\n let weatherData = {\n lastModifiedDate: today.getTime(),\n data: data\n };\n\n stroage.setItem(name, JSON.stringify(weatherData));\n}", "function saveSnapshot() {\n console.log(\"save snapshot\");\n}", "function data(name) {\n all(\"body /deep/ [data~=\\\"\" + name + \"\\\"]:not([inert])\").map(invoke);\n }", "function copyDatasetForExport(dataset) {\n var d2 = utils.extend({}, dataset);\n d2.layers = d2.layers.map(copyLayerShapes);\n if (d2.arcs) {\n d2.arcs = d2.arcs.getFilteredCopy();\n }\n return d2;\n }", "function useSelectedDataset() {\n let modUrl = \"/models-for-dataset?dataset=\" + getSelectedDatasetName();\n let imgUrl = \"/dataset-details?dataset=\" + getSelectedDatasetName();\n\n populateModels(modUrl);\n populateStaticImages(imgUrl);\n}", "function createASnapshotByImportingAnUnmanagedBlobFromTheSameSubscription() {\n return __awaiter(this, void 0, void 0, function* () {\n const subscriptionId = \"{subscription-id}\";\n const resourceGroupName = \"myResourceGroup\";\n const snapshotName = \"mySnapshot1\";\n const snapshot = {\n creationData: {\n createOption: \"Import\",\n sourceUri: \"https://mystorageaccount.blob.core.windows.net/osimages/osimage.vhd\"\n },\n location: \"West US\"\n };\n const credential = new DefaultAzureCredential();\n const client = new ComputeManagementClient(credential, subscriptionId);\n const result = yield client.snapshots.beginCreateOrUpdateAndWait(resourceGroupName, snapshotName, snapshot);\n console.log(result);\n });\n}", "function snapshot() {\n\t\t\tvar tmp;\n\n\t\t\tif (!hasSnapshot()) { // has no snapshots yet\n\t\t\t\tsnap.history = [angular.copy(object)];\n\t\t\t} else if (isChanged()) { // has snapshots and is changed since last version\n\t\t\t\ttmp = angular.copy(object);\n\t\t\t\tsnap.history.push(tmp);\n\t\t\t}\n\n\t\t\tsaveSnap();\n\t\t}", "updatedata(name, data) {\n let current = this.head;\n try {\n while (current != null) {\n if (current.name === name) current.nameset = data;\n current = current.next;\n }\n } catch (error) {\n console.log(\"/\" + dat + \"/\" + \"was entered\");\n }\n }", "function datasetDangerously () {}", "createSnapshot(){\r\n let fs = require('fs');\r\n let fname = `data/snap${Date.now()}.bck`;\r\n let ws = fs.createWriteStream(fname);\r\n let base64Buffer = new Buffer.from(this.s.read());\r\n ws.write(base64Buffer.toString('base64'));\r\n }", "createSnapshot(){\r\n let fs = require('fs');\r\n let fname = `data/snap${Date.now()}.bck`;\r\n let ws = fs.createWriteStream(fname);\r\n let base64Buffer = new Buffer.from(this.s.read());\r\n ws.write(base64Buffer.toString('base64'));\r\n }", "withSnapshot(snapshot) {\n return new AppendBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline);\n }", "withSnapshot(snapshot) {\n return new AppendBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline);\n }", "setData(name, data) {\n if(!App.pathFinder.data.visualisation_enabled) {\n return;\n }\n\n App.pathFinder.chart.series.find(\n el => el.name === name\n ).setData(data);\n }", "withSnapshot(snapshot) {\n return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline);\n }", "withSnapshot(snapshot) {\n return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline);\n }", "chartDataSource(data, name, random) {\n data.map(d=>{\n if (d.canvas) {\n let number = d.canvas.className.split('_')[1];\n\n if (number === random) {\n let properties = d.components.properties;\n\n for (let i = 0; i < properties.length; i++) {\n properties[i].name === 'dataSource' ? properties[i].value = name : null;\n }\n }\n }\n });\n this.props.saveData(data);\n }", "_constructLevel2Snapshot(data, market) {\n let asks = [];\n let bids = [];\n for (let datum of data) {\n // Construct the price lookup map for all values supplied here.\n // Per the documentation, the id is a unique value for the\n // market and the price.\n if (this.constructL2Price) {\n this.l2PriceMap.set(datum.id, datum.price.toFixed(8));\n }\n\n // build the data point\n let point = new Level2Point(datum.price.toFixed(8), datum.size.toFixed(8), undefined, {\n id: datum.id,\n });\n\n // add the datapoint to the asks or bids depending if its sell or bid side\n if (datum.side === \"Sell\") asks.push(point);\n else bids.push(point);\n }\n\n // asks arrive in descending order (best ask last)\n // ccxws standardizes so that best bid/ask are array index 0\n asks = asks.reverse();\n\n return new Level2Snapshot({\n exchange: \"BitMEX\",\n base: market.base,\n quote: market.quote,\n id: market.id,\n asks,\n bids,\n });\n }", "MakeManualSnapshot(serviceName) {\n let url = `/hosting/reseller/${serviceName}/snapshot`;\n return this.client.request('POST', url);\n }", "function writeNewCollection(uid, name) {\n\n return new Promise(function(resolve,reject){\n\n // A Collection Entry\n var collectionData = {\n name: name,\n dateCreated: new Date().toString(),\n public: true,\n }\n\n db.ref('/user-posts/' + uid + '/collections/').push(collectionData).once(\"value\")\n .then(function(snapshot) {\n state.currentCollection.id = snapshot.key\n state.currentCollection.data = snapshot.val()\n resolve();\n });\n\n });\n\n }", "function writeData(name, data){\n return dbPromise\n .then(function(db){\n const tx = db.transaction(name, 'readwrite');\n const store = tx.objectStore(name);\n store.put(data);\n \n return tx.complete;\n });\n}" ]
[ "0.57099885", "0.49952084", "0.49173602", "0.4823329", "0.48050103", "0.47906417", "0.47362155", "0.47198105", "0.46961048", "0.46948686", "0.4675691", "0.46605006", "0.4631633", "0.46235973", "0.46117425", "0.4595298", "0.45672947", "0.4545511", "0.45219707", "0.4511676", "0.45020017", "0.45020017", "0.44992778", "0.44965142", "0.44965142", "0.44883284", "0.44819725", "0.4470766", "0.44691095", "0.4460561" ]
0.5674466
1
Keep only num snapshots with the specified base on the specified dataset
function cleanSnapshots(ds, base, num) { zfs.list({ type: 'snapshot' }, function (err, snaps) { // Find all snapshots that match the specified dataset and base. var ourSnaps = snaps.filter(function (s) { var fields = s.name.split('@'); var parts = fields[1].split('-'); return fields[0] === ds && parts[0] === base; }); if (ourSnaps.length > num) { // Get just the sorted list of names. var snapNames = ourSnaps.map(function (s) { return s.name; }); snapNames.sort(); // Get the ones that exceed the specified number of snapshots. var toDestroy = snapNames.slice(0, snapNames.length - num); // Destroy them, one after the other. async.forEachSeries(toDestroy, function (sn, cb) { util.log('Destroy snapshot ' + sn + ' (cleaned)'); zfs.destroy({ name: sn, recursive: true }, cb); }); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function pruneAggregated() {\n return Sample.destroy({\n where: { aggregated: false },\n }).then(count => {\n console.log('Pruned %d pre-aggregation samples', count);\n });\n}", "function filterData(dataset) {\n dList = [];\n \n for (i=0; i < dataset.otu_ids.length; i++) { \n // console.log(`ROw${i}]: ${results.otu_ids[i]}, ${results.sample_values[i]}, ${results.otu_labels[i]}`) ;\n dict = {};\n dict[\"otu_ids\"] = dataset.otu_ids[i];\n dict[\"smpl_values\"] = dataset.sample_values[i];\n dict[\"otu_labels\"] = dataset.otu_labels[i];\n dList.push(dict);\n }\n // console.log(dList);\n\n // Sort by sample_values\n dList.sort(function(a, b) {\n return parseFloat(b.smpl_values) - parseFloat(a.smpl_values);\n });\n\n // Slice the first 10 objects for plotting\n results = dList.slice(0, 10);\n\n return results;\n}", "queryAllFilterLatestData(callback) {\n this.collection.find({}).project({_id: 0, data: {$slice: -1}})\n .toArray(callback);\n }", "function limitToFive(dataSet){\n let newArray = dataSet.sort((countA, countB) => (countA.count < countB.count ? 1 : -1));\nreturn newArray.slice(0, 5);\n}", "limitData(data) {\n if (this.metricsLimit === 0) { // we dont want to limit at all\n return data;\n }\n\n let currentSize = Object.keys(this.uniqMetrics).length;\n\n return data.filter((metric) => {\n const metricName = metric.MetricName;\n\n if (this.uniqMetrics[metricName]) {\n return true;\n }\n\n if (currentSize >= this.metricsLimit) {\n this.logger(`cloudwatch - ERROR - metrics limit reached - throwing away ${metricName}`);\n return false;\n }\n\n this.uniqMetrics[metricName] = true;\n currentSize += 1;\n return true;\n });\n }", "async filterAlreadyScraped(){\n //Get the existing reports' URIs\n const countStatement = this.db.prepare( `SELECT uri FROM data WHERE uri IN (${this.reportsURLs.map(() => '?').join(',')})`, this.reportsURLs )\n const asyncAll = promisify(countStatement.all).bind(countStatement)\n const alreadyInDb = (await asyncAll()).map((row) => row.uri)\n countStatement.finalize()\n\n //Filter out the existing reports\n this.reportsURLs = this.reportsURLs.filter((uri) => !alreadyInDb.includes( uri ))\n //Update the count\n this.howManyAlreadyScraped += alreadyInDb.length\n }", "function distill_analytics(table, filter) {\n\tswitch (filter) {\n\t\tcase \"all\":\n\t\t\t// Don't filter the checkins.\n\t\t\tvar grouped = google.visualization.data.group(table, [0], [Analytics.count_column]);\n\t\t\treturn [grouped, grouped.getSortedRows([{ column: 1, desc: true }]).slice(0,5)];\n\t\t\tbreak;\n\t\tcase \"month\":\n\t\t\t// Filter the checkins by month.\n\t\t\tvar now = new Date();\n\t\t\tvar rows_filtered = table.getFilteredRows([\n\t\t\t\t{ column: 1, minValue: (new Date(now - milliseconds_in_month)), maxValue: now }\n\t\t\t]);\n\t\t\tvar view = new google.visualization.DataView(table);\n\t\t\tview.setRows(rows_filtered);\n\t\t\tvar grouped = google.visualization.data.group(view.toDataTable(), [0], [Analytics.count_column]);\n\t\t\treturn [grouped, grouped.getSortedRows([{ column: 1, desc: true }]).slice(0,5)];\n\t\t\tbreak;\n\t\tcase \"quarter\":\n\t\t\t// Filter the checkins by quarter.\n\t\t\tvar now = new Date();\n\t\t\tvar rows_filtered = table.getFilteredRows([\n\t\t\t\t{ column: 1, minValue: (new Date(now - (milliseconds_in_month * 3))), maxValue: now }\n\t\t\t]);\n\t\t\tvar view = new google.visualization.DataView(table);\n\t\t\tview.setRows(rows_filtered);\n\t\t\tvar grouped = google.visualization.data.group(view.toDataTable(), [0], [Analytics.count_column]);\n\t\t\treturn [grouped, grouped.getSortedRows([{ column: 1, desc: true }]).slice(0,5)];\n\t\t\tbreak;\n\t\tcase \"half\":\n\t\t\t// Filter the checkins by half.\n\t\t\tvar now = new Date();\n\t\t\tvar rows_filtered = table.getFilteredRows([\n\t\t\t\t{ column: 1, minValue: (new Date(now - (milliseconds_in_month * 6))), maxValue: now }\n\t\t\t]);\n\t\t\tvar view = new google.visualization.DataView(table);\n\t\t\tview.setRows(rows_filtered);\n\t\t\tvar grouped = google.visualization.data.group(view.toDataTable(), [0], [Analytics.count_column]);\n\t\t\treturn [grouped, grouped.getSortedRows([{ column: 1, desc: true }]).slice(0,5)];\n\t\t\tbreak;\n\t\tcase \"year\":\n\t\t\t// Filter the checkins by year.\n\t\t\tvar now = new Date();\n\t\t\tvar rows_filtered = table.getFilteredRows([\n\t\t\t\t{ column: 1, minValue: (new Date(now - milliseconds_in_year)), maxValue: now }\n\t\t\t]);\n\t\t\tvar view = new google.visualization.DataView(table);\n\t\t\tview.setRows(rows_filtered);\n\t\t\tvar grouped = google.visualization.data.group(view.toDataTable(), [0], [Analytics.count_column]);\n\t\t\treturn [grouped, grouped.getSortedRows([{ column: 1, desc: true }]).slice(0,5)];\n\t\t\tbreak;\n\t}\n}", "function selectBarData(dataset, startDate, endDate, grp) {\n var ds = {};\n var date;\n var totalViews = 0;\n var totalVisits = 0;\n barGroup = grp;\n for (entry in dataset) {\n date = new Date(Date.parse(dataset[entry].key));\n if (date >= startDate && date <= endDate) {\n var appData = d3.entries(dataset[entry].value[barGroup]);\n for (app in appData) { \n if (ds[appData[app].key] === undefined) {\n ds[appData[app].key] = {};\n ds[appData[app].key]['views'] = appData[app].value.views;\n ds[appData[app].key]['visits'] = appData[app].value.visits;\n } else {\n ds[appData[app].key]['views'] += appData[app].value.views;\n ds[appData[app].key]['visits'] += appData[app].value.visits;\n }\n totalViews += appData[app].value.views;\n totalVisits += appData[app].value.visits;\n }\n }\n }\n return { data: ds, tvw: totalViews, tvs: totalVisits };\n}", "function getDataSubset() {\n const calculations = [{\n value: thirdParameter,\n method: \"Average\",\n },\n {\n value: \"Height\",\n method: \"Min\",\n },\n {\n value: \"Height\",\n method: \"Max\",\n },\n {\n value: \"Weight\",\n method: \"Min\",\n },\n {\n value: \"Weight\",\n method: \"Max\",\n },\n {\n value: \"Age\",\n method: \"Min\",\n },\n {\n value: \"Age\",\n method: \"Max\",\n },\n ];\n return gmynd.cumulateData(segmentedAthletes, [\"Sex\", ...currentFilters], calculations);\n}", "function removeData() {\n\t var newIndex = crossfilter_index(n, n),\n\t removed = [];\n\t for (var i = 0, j = 0; i < n; ++i) {\n\t if (filters[i]) newIndex[i] = j++;\n\t else removed.push(i);\n\t }\n\n\t // Remove all matching records from groups.\n\t filterListeners.forEach(function(l) { l(0, [], removed); });\n\n\t // Update indexes.\n\t removeDataListeners.forEach(function(l) { l(newIndex); });\n\n\t // Remove old filters and data by overwriting.\n\t for (var i = 0, j = 0, k; i < n; ++i) {\n\t if (k = filters[i]) {\n\t if (i !== j) filters[j] = k, data[j] = data[i];\n\t ++j;\n\t }\n\t }\n\t data.length = j;\n\t while (n > j) filters[--n] = 0;\n\t }", "function clearProceedingSnapshots(snapshots) {\n if (canMoveCurrentSnapshot_1.default(snapshots, 1)) {\n var removedSize = 0;\n for (var i = snapshots.currentIndex + 1; i < snapshots.snapshots.length; i++) {\n removedSize += snapshots.snapshots[i].length;\n }\n snapshots.snapshots.splice(snapshots.currentIndex + 1);\n snapshots.totalSize -= removedSize;\n }\n}", "function checkMatches(drawData) {\n const { winningNumbers, drawedSets} = drawData;\n //const numAmount = winningNumbers.size;\n for (set of drawedSets) {\n set.match = 0;\n for (let num of set.numbers) {\n if (winningNumbers.includes(num)) {\n set.match++;\n }\n }\n }\n //console.log(winningNumbers, drawedSets);\n}", "function splitVideoIdsIntoSets() {\n var tmpArray = [];\n // grab the first 100 as a new array, push into sets array\n tmpArray = videoIds.splice(0, 100);\n videoIdSets.push(tmpArray);\n // function recalls itself until videoIds array is empty\n if (videoIds.length > 0) {\n splitVideoIdsIntoSets();\n } else {\n return;\n }\n }", "function sort_data(datasets, schem) {\n var cut_data = $scope.summary_rows;\n var number_of_cuts = schem.cuts.length;\n var lumberSizes = $scope.lumberSizes;\n for (var a = 0; a < lumberSizes.length; a++) {\n for (var i = 0; i < number_of_cuts; i++) {\n if (cut_data[i][0].includes(lumberSizes[a])) {\n datasets.push(cut_data[i]);\n }\n }\n }\n }", "function filterStreams() {\n let filteredStreams = [];\n for (let i = 0; i < globalSetIndex.length; i++) {\n if (globalSetIndex[i].isFoV.FoV) {\n filteredStreams.push({\n index: i,\n id: globalSetIndex[i].id\n });\n }\n }\n return filteredStreams;\n}", "function perform5minAggregatBC2(siteId, startEpoch, endEpoch) {\n // create temp collection as placeholder for aggreagation results\n const aggrResultsName = `aggr${moment().valueOf()}`;\n const AggrResults = new Meteor.Collection(aggrResultsName);\n\n // gather all data, group by 5min epoch\n const pipeline = [\n {\n $match: {\n $and: [\n {\n epoch: {\n $gt: parseInt(startEpoch, 10),\n $lt: parseInt(endEpoch, 10)\n }\n }, {\n site: siteId\n }\n ]\n }\n }, {\n $sort: {\n epoch: 1\n }\n }, {\n $project: {\n epoch5min: 1,\n epoch: 1,\n site: 1,\n subTypes: 1\n }\n }, {\n $group: {\n _id: '$epoch5min',\n site: {\n $last: '$site'\n },\n subTypes: {\n $push: '$subTypes'\n }\n }\n }, {\n $out: aggrResultsName\n }\n ];\n\n Promise.await(LiveData.rawCollection().aggregate(pipeline, { allowDiskUse: true }).toArray());\n\n /*\n * Only aggregate data if a certain percentage (defined by thresholdPercent) of the required data is in the 5minepoch.\n * There is supposed to be 630 database documents per 5minepoch.\n *\n * 30 documents for DAQFactory, 300 documents for TAP01, and 300 documents for TAP02.\n * Eventually we'll just pull how many datapoints are expected from the database. This will work for now\n *\n * Take for example if thresholdPercent were .75.\n *\n * There would need to be:\n * 30 * .75 = 22.5 \n * round(22.5) = 23 documents for DAQFactory required\n *\n * 300 * .75 = 225\n * 225 documents for TAP01 and TAP02 are required\n *\n * ONE EXCEPTION:\n * aggregate regardless of missing data if it is 55 min from the startEpoch\n *\n * Also, left these outside the loop because unnecessary calculations slow the loop down. \n * Additionally, we will be querying for this data rather than relying on hardcoded numbers later on.\n * Querying a database is slow. The less of those we do, the better.\n */\n\n const thresholdPercent = .75;\n // Hard coded numbers. Should not be hardcoded but oh well. Should be changed in the future.\n const maxDAQFactoryCount = 30, maxTAPCount = 300;\n const minDAQFactoryCount = Math.round(thresholdPercent * maxDAQFactoryCount);\n const minTAPcount = Math.round(thresholdPercent * maxTAPCount);\n\n // tap switch variables ***MUST*** be viable over iterations of the foreach loop\n // 8 is offline. Assume offline unless specified otherwise in TAP switch implementation\n var TAP01Flag = 8, TAP02Flag = 8;\n var TAP01Epoch = 0, TAP02Epoch = 0;\n\n // For some god aweful reason, some sites don't have neph flags. Need to check for neph flag before assigning whatever\n let hasNephFlag = false;\n\n // Tap data filtration is required. These variables are simply placeholders for where the rgb abs coef indeces and sampleFlow index is at.\n // ***MUST*** be viable over for loop\n let hasCheckedTAPdataSchema = false;\n let tapDataSchemaIndex = {};\n tapDataSchemaIndex.RedAbsCoef = undefined, tapDataSchemaIndex.GreenAbsCoef = undefined, tapDataSchemaIndex.BlueAbsCoef = undefined, tapDataSchemaIndex.SampleFlow = undefined;\n let TAP01Name = undefined;\n let TAP02Name = undefined;\n const allElementsEqual = arr => arr.every(v => v === arr[0]);\n\n AggrResults.find({}).forEach((e) => {\n const subObj = {};\n subObj._id = `${e.site}_${e._id}`;\n subObj.site = e.site;\n subObj.epoch = e._id;\n const subTypes = e.subTypes;\n const aggrSubTypes = {}; // hold aggregated data\n let newData = (endEpoch - 3300 - subObj.epoch) < 0;\n\n let subTypesLength = subTypes.length\n for (let i = 0; i < subTypesLength; i++) {\n for (const subType in subTypes[i]) {\n if (subTypes[i].hasOwnProperty(subType)) {\n const data = subTypes[i][subType];\n let numValid = 1;\n var newkey;\n\n // if Neph flag is undefined, flag it 1, otherwise ignore\n if (subType.includes(\"Neph\")) {\n if (data[0].metric === 'Flag') {\n hasNephFlag = true;\n }\n if (!hasNephFlag) {\n data.unshift({ metric: 'Flag', val: 1, unit: 'NA' });\n }\n }\n\n\n /** Tap flag implementation **/\n // Get flag from DAQ data and save it\n if (subType.includes('TAP01')) {\n TAP01Flag = data[0].val === 10 ? 1 : data[0].val;\n TAP01Epoch = subObj.epoch;\n } else if (subType.includes('TAP02')) {\n TAP02Flag = data[0].val === 10 ? 8 : data[0].val\n TAP02Epoch = subObj.epoch;\n }\n\n // Get flag from TAP0(1|2)Flag and give it to the appropriate instrument\n if (subType.includes('tap_')) {\n\n // TAP01 = even\n // TAP02 = odd\n // confusing amirite!?\n // EXAMPLE:\n // tap_SN36 <- even goes to TAP01\n // tap_SN37 <- odd goes to TAP02\n // This is parsing tap_* string for integer id\n var subTypeName = subType;\n let epochDiff;\n do {\n subTypeName = subTypeName.slice(1);\n } while (isNaN(subTypeName));\n let subTypeNum = subTypeName;\n if (parseInt(subTypeNum) % 2 === 0) {\n // Even - Needs flag from TAP01\n // Make sure that tap data has a corresponding timestamp in DaqFactory file\n // If not, break and do not aggregate datapoint\n epochDiff = subObj.epoch - TAP01Epoch;\n\n if (epochDiff >= 0 && epochDiff < 10) {\n data[0].val = TAP01Flag;\n } else {\n data[0].val = 20;\n }\n } else {\n // Odd - Needs flag from TAP02\n // Make sure that tap data has a corresponding timestamp in DaqFactory file\n // If not, break and do not aggregate datapoint\n epochDiff = subObj.epoch - TAP02Epoch;\n if (epochDiff >= 0 && epochDiff < 10) {\n data[0].val = TAP02Flag;\n } else {\n data[0].val = 20;\n }\n }\n\n /** Data filtration start **/\n\n /* Reason for data filtration to be inside this subType.includes is for performance reasons. The less if statements ran, the faster.\n */\n\n /* Matlab code\n * Some data filtration is required. We will not aggregate datapoints (not records) that do not fit our standards.\n * To Note: Comments in matlab are my own comments\n\n % Do not aggregate data point if r, g, b is < 0 or > 100 \n r1=numa(:,7);\n g1=numa(:,8);\n b1=numa(:,9);\n r2(r2 < 0 | r2 > 100) = NaN;\n g2(g2 < 0 | g2 > 100) = NaN;\n b2(b2 < 0 | b2 > 100) = NaN;\n\n\n %TAP_02data defined here\n TAP_02data = [JD2 time2 A_spot2 R_spot2 flow2 r2 g2 b2 Tr2 Tg2 Tb2];\n\n % Don't aggregate data point if SampleFlow / Flow(L/min) is off 5% from 1.7 Min: 1.615, Max: 1.785\n idx = find(TAP_02data (:,5) <1.63 | TAP_02data (:,5) >1.05*1.7); %condition if flow is 5% off 1.7lpm\n TAP_02data(idx,5:8) = NaN; clear idx time2 A_spot2 R_spot2 flow2 r2 g2 b2 Tr2 Tg2 Tb2\n\n\n % This is for the TAP switching. It was a way to get the TAP switching working in the matlab script.\n % Don't aggregate the first 100s after a switch has occured. Let instrument recalibrate. \n R01 = strfind(isnan(TAP_02data(:,5)).', [1 0]); % Find Indices Of [0 1] Transitions\n for i=1:100\n TAP_02data(R01+i,6:8) = NaN; % Replace Appropriate Values With 'NaN '\n end\n\n\n 20 = potentially invalid data\n 1 = valid data\n */\n\n // Reason for if statement is to speed the code up alot. \n // Having to check for the schema every run is VERY significant.\n // Only having to do it once and assuming the rest will be the same is a very safe assumption.\n // If this isn't true, then lord help us all\n if (!hasCheckedTAPdataSchema) {\n let dataLength = data.length;\n for (let k = 0; k < dataLength; k++) {\n if (data[k].metric === 'RedAbsCoef') {\n tapDataSchemaIndex.RedAbsCoef = k;\n }\n if (data[k].metric === 'GreenAbsCoef') {\n tapDataSchemaIndex.GreenAbsCoef = k;\n }\n if (data[k].metric === 'BlueAbsCoef') {\n tapDataSchemaIndex.BlueAbsCoef = k;\n }\n if (data[k].metric === 'SampleFlow') {\n tapDataSchemaIndex.SampleFlow = k;\n }\n }\n hasCheckedTAPdataSchema = true;\n }\n\n // We flag the faulty data with flag 20.\n if (data[tapDataSchemaIndex.RedAbsCoef].val < 0 || data[tapDataSchemaIndex.RedAbsCoef].val > 100 || isNaN(data[tapDataSchemaIndex.RedAbsCoef].val)) {\n data[tapDataSchemaIndex.RedAbsCoef].Flag = 20;\n }\n\n if (data[tapDataSchemaIndex.GreenAbsCoef].val < 0 || data[tapDataSchemaIndex.GreenAbsCoef].val > 100 || isNaN(data[tapDataSchemaIndex.GreenAbsCoef].val)) {\n data[tapDataSchemaIndex.GreenAbsCoef].Flag = 20;\n }\n\n if (data[tapDataSchemaIndex.BlueAbsCoef].val < 0 || data[tapDataSchemaIndex.BlueAbsCoef].val > 100 || isNaN(data[tapDataSchemaIndex.BlueAbsCoef].val)) {\n data[tapDataSchemaIndex.BlueAbsCoef].Flag = 20;\n }\n\n if (data[tapDataSchemaIndex.SampleFlow].val < 1.615 || data[tapDataSchemaIndex.SampleFlow].val > 1.785 || isNaN(data[tapDataSchemaIndex.SampleFlow].val)) {\n data[tapDataSchemaIndex.SampleFlow].Flag = 20;\n }\n\n\n /** Data filtration finished **/ \n }\n\n /** End of TAP switch implementation **/\n\n // Don't aggregate TAP01 and TAP02 subtype. They are only useful for giving TAP_SNXX flags\n if (subTypes.includes(\"TAP01\") || subTypes.includes(\"TAP02\")) {\n continue;\n }\n\n\n // if flag is not existing, put 9 as default, need to ask Jim?\n if (data[0].val === '') {\n data[0].val = 9;\n }\n if (data[0].val !== 1) { // if flag is not 1 (valid) don't increase numValid\n numValid = 0;\n }\n for (let j = 1; j < data.length; j++) {\n newkey = subType + '_' + data[j].metric;\n\n // TAP data requires data filtration. Setting flag to 20 if such for specified values. \n // Otherwise, use suggested flag value from file\n const flag = data[j].Flag !== undefined ? data[j].Flag : data[0].val;\n\n if (flag !== 1) { // if flag is not 1 (valid) don't increase numValid\n numValid = 0;\n }\n\n if (!aggrSubTypes[newkey]) {\n if (numValid === 0) {\n data[j].val = 0;\n }\n\n aggrSubTypes[newkey] = {\n sum: Number(data[j].val),\n 'avg': Number(data[j].val),\n 'numValid': numValid,\n 'totalCounter': 1, // initial total counter\n 'flagstore': [flag], // store all incoming flags in case we need to evaluate\n unit: data[j].unit // use unit from first data point in aggregation\n };\n } else {\n if (numValid !== 0) { // keep aggregating only if numValid\n aggrSubTypes[newkey].numValid += numValid;\n aggrSubTypes[newkey].sum += Number(data[j].val); // holds sum until end\n if (aggrSubTypes[newkey].numValid !== 0) {\n aggrSubTypes[newkey].avg = aggrSubTypes[newkey].sum / aggrSubTypes[newkey].numValid;\n }\n }\n aggrSubTypes[newkey].totalCounter += 1; // increase counter\n aggrSubTypes[newkey].flagstore.push(flag); // /store incoming flag\n }\n numValid = 1; // reset numvalid\n }\n }\n }\n }\n\n // This is prep for calculations. Need ensure that we are working with data that has the data necessary to do calculations.\n // The for loop for transforming aggregated data to a generic data format is more useful for calculations than raw aggrSubTypes.\n // All I'm doing here is collecting a little bit of information of what we are working with before I do calculations.\n let hasTap = false;\n let hasNeph = false;\n // Don't have to do this with neph. Neph will always have the same name. Tap will always have different numbers\n let tapNames = [];\n\n // transform aggregated data to generic data format using subtypes etc.\n const newaggr = {};\n for (const aggr in aggrSubTypes) {\n if (aggrSubTypes.hasOwnProperty(aggr)) {\n const split = aggr.lastIndexOf('_');\n const instrument = aggr.substr(0, split);\n const measurement = aggr.substr(split + 1);\n\n if (!newaggr[instrument]) {\n newaggr[instrument] = {};\n }\n\n const obj = aggrSubTypes[aggr]; // makes it a little bit easier\n\n // dealing with flags\n if ((obj.numValid / obj.totalCounter) >= 0.75) {\n obj.Flag = 1; // valid\n } else {\n // find out which flag was majority\n const counts = {};\n for (let k = 0; k < obj.flagstore.length; k++) {\n counts[obj.flagstore[k]] = 1 + (counts[obj.flagstore[k]] || 0);\n }\n const maxObj = _.max(counts, function(obj) {\n return obj;\n });\n const majorityFlag = (_.invert(counts))[maxObj];\n obj.Flag = majorityFlag;\n }\n\n // Some specific setting up for tap calculations and skipping\n if (instrument.includes(\"Neph\")) {\n hasNeph = true;\n\n // If obj.totalCounter (which is documentation for the amount of datapoints in our 5minepoch) is < minTAPcount\n // And what we are aggregating is greater than 55 minutes from endEpoch: \n // SKIP \n if (obj.totalCounter < minDAQFactoryCount && newData) {\n // This forces the forEach loop to go to the next loop skipping pushing data into database\n return;\n }\n }\n\n if (instrument.includes(\"tap_\")) {\n hasTap = true;\n if (!tapNames.includes(instrument)) {\n tapNames.push(instrument);\n }\n\n if (obj.totalCounter < 300)\n // If obj.totalCounter (which is documentation for the amount of datapoints in our 5minepoch) is < minTAPcount\n // And what we are aggregating is greater than 55 minutes from endEpoch: \n // SKIP \n if (obj.totalCounter < minTAPcount && newData) {\n // This forces the forEach loop to go to the next loop skipping pushing data into database\n return;\n }\n }\n\n if (!newaggr[instrument][measurement]) { newaggr[instrument][measurement] = [];\n }\n\n // automatic flagging of aggregated values that are out of range for NO2 to be flagged with 9(N)\n if (instrument === '42i') {\n if (obj.avg < -0.5) {\n obj.Flag = 9;\n }\n }\n\n newaggr[instrument][measurement].push({ metric: 'sum', val: obj.sum });\n newaggr[instrument][measurement].push({ metric: 'avg', val: obj.avg });\n newaggr[instrument][measurement].push({ metric: 'numValid', val: obj.numValid });\n newaggr[instrument][measurement].push({ metric: 'unit', val: obj.unit });\n newaggr[instrument][measurement].push({ metric: 'Flag', val: obj.Flag });\n }\n }\n\n // If TAP or NEPH is missing AND what we are aggregating is greater than 55 minutes from endEpoch:\n // SKIP\n if ((tapNames.length < 2 || !hasNeph) && newData) {\n // This forces the forEach loop to go to the next loop skipping pushing data into database\n return; \n }\n\n /** Helpful functions for calculations **/\n\n // flips sign for all elements in array\n function flipSignForAll1D(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] *= -1;\n }\n }\n\n // flips sign for all elements in 2D array\n function flipSignForAll2D(M) {\n for (let i = 0; i < M.length; i++) {\n flipSignForAll1D(M[i]);\n }\n }\n\n // returns row reduced echelon form of given matrix\n // if vector, return rref vector\n // if invalid, do nothing\n function rref(M) {\n let rows = M.length;\n let columns = M[0].length;\n if (((rows === 1 || rows === undefined) && columns > 0) || ((columns === 1 || columns === undefined) && rows > 0)) {\n M = [];\n let vectorSize = Math.max(isNaN(columns) ? 0 : columns, isNaN(rows) ? 0 : rows);\n for (let i = 0; i < vectorSize; i++) {\n M.push(0);\n }\n M[0] = 1;\n return M;\n } else if (rows < 0 || columns < 0) {\n return;\n }\n\n let lead = 0;\n for (let k = 0; k < rows; k++) {\n if (columns <= lead) {\n return;\n }\n\n let i = k;\n while (M[i][lead] === 0) {\n i++;\n if (rows === i) {\n i = k;\n lead++;\n if (columns === lead) { \n return;\n }\n }\n }\n let p = M[i]\n let s = M[k];\n M[i] = s, M[k] = p;\n\n let scalar = M[k][lead];\n for (let j = 0; j < columns; j++) {\n M[k][j] /= scalar;\n }\n\n for (let i = 0; i < rows; i++) {\n if (i === k) continue;\n scalar = M[i][lead];\n for (let j = 0; j < columns; j++) {\n M[i][j] -= scalar * M[k][j];\n }\n }\n lead++;\n }\n return M;\n }\n /** END of Helpful functions for calculations **/\n\n // Calculations for Nepholometer is done here\n if (hasNeph) {\n newaggr['Neph']['SAE'] = [];\n\n if (newaggr['Neph']['RedScattering'] === undefined || newaggr['Neph']['GreenScattering'] === undefined || newaggr['Neph']['BlueScattering'] === undefined) {\n newaggr['Neph']['SAE'].push({ metric: 'calc', val: 'NaN' });\n newaggr['Neph']['SAE'].push({ metric: 'unit', val: \"undefined\" });\n newaggr['Neph']['SAE'].push({ metric: 'Flag', val: 20});\n } else {\n\n let RedScatteringFlagIndex = 0;\n let RedScatteringAvgIndex = 0;\n for (let index = 0; index < newaggr['Neph']['RedScattering'].length; index++) {\n if (newaggr['Neph']['RedScattering'][index].metric === 'Flag') {\n RedScatteringFlagIndex = index;\n }\n if (newaggr['Neph']['RedScattering'][index].metric === 'avg') {\n RedScatteringAvgIndex = index;\n }\n }\n\n let GreenScatteringFlagIndex = 0;\n let GreenScatteringAvgIndex = 0;\n for (let index = 0; index < newaggr['Neph']['GreenScattering'].length; index++) {\n if (newaggr['Neph']['GreenScattering'][index].metric === 'Flag') {\n GreenScatteringFlagIndex = index;\n }\n if (newaggr['Neph']['GreenScattering'][index].metric === 'avg') {\n GreenScatteringAvgIndex = index;\n }\n }\n\n let BlueScatteringFlagIndex = 0;\n let BlueScatteringAvgIndex = 0;\n for (let index = 0; index < newaggr['Neph']['BlueScattering'].length; index++) {\n if (newaggr['Neph']['BlueScattering'][index].metric === 'Flag') {\n BlueScatteringFlagIndex = index;\n }\n if (newaggr['Neph']['BlueScattering'][index].metric === 'avg') {\n BlueScatteringAvgIndex = index;\n }\n }\n\n\n // SAE calculations begin here \n // Need to make sure that Neph has valid data before calculations can begin\n if (newaggr['Neph']['RedScattering'][RedScatteringFlagIndex].val === 1 && newaggr['Neph']['GreenScattering'][GreenScatteringFlagIndex].val === 1 && newaggr['Neph']['BlueScattering'][BlueScatteringFlagIndex].val === 1) {\n let x = [635, 525, 450]; // Matlab code: x=[635,525,450]; %Wavelength values for Nephelometer \n let y_Neph = [\n newaggr['Neph']['RedScattering'][RedScatteringAvgIndex].val,\n newaggr['Neph']['GreenScattering'][GreenScatteringAvgIndex].val,\n newaggr['Neph']['BlueScattering'][BlueScatteringAvgIndex].val\n ]; // Matlab code: y_Neph = outdata_Neph(:,2:4); %Scattering coefficient values from Daqfactory for Neph\n\n let lx = mathjs.log(x); // Matlab code: lx = log(x); %Taking log of wavelength\n let ly_Neph = mathjs.log(y_Neph); // Matlab code: ly_Neph = log(y_Neph); %Taking log of scattering coefficient values\n\n // Matlab code: log_Neph = -[lx(:) ones(size(x(:)))] \\ ly_Neph(:,:)'; %Step 1- SAE calulation\n // going to have to break this down a little bit\n let log_Neph = [ // [lx(:) ones(size(x(:)))]\n lx, \n mathjs.ones(mathjs.size(x))\n ];\n log_Neph = mathjs.transpose(log_Neph); // Needed to make matrix 3 x 2\n\n // - operator just negates everything in the matrix\n flipSignForAll2D(log_Neph);\n /*\n * if A is a rectangular m-by-n matrix with m ~= n, and B is a matrix with m rows, then A\\B returns a least-squares solution to the system of equations A*x= B.\n * Least squares solution approximation is needed.\n * Links to calculating least squares solution:\n * https://textbooks.math.gatech.edu/ila/least-squares.html\n * https://www.youtube.com/watch?v=9UE8-6Jlezw\n */\n\n // A^T*A\n let ATA = mathjs.multiply(mathjs.transpose(log_Neph), log_Neph);\n // A^T*b\n let ATb = mathjs.multiply(mathjs.transpose(log_Neph), ly_Neph);\n\n // Create augmented matrix to solve for least squares solution\n ATA[0].push(ATb[0]);\n ATA[1].push(ATb[1]);\n\n log_Neph = rref(ATA);\n // Reason for index 0,2 is because I am skipping a step in the least squares approximation.\n // It is supposed to return a vector with 2 values, but I just shortcut it straight to the correct answer from the 3x2 rref matrix\n let SAE_Neph = log_Neph[0][2]; // SAE_Neph = log_Neph(1,:)'; %Step 2- SAE calulation\n\n // SAE ranges should be: -1 - 5\n // Matlab code: SAE_Neph(SAE_Neph > 5)= NaN;\n // Sujan said this ^^^\n // Unsure If I want to check for zero value\n if (SAE_Neph === undefined || SAE_Neph < -1 || SAE_Neph > 5) { \n newaggr['Neph']['SAE'].push({ metric: 'calc', val: ((SAE_Neph === undefined) ? 'NaN' : SAE_Neph) });\n newaggr['Neph']['SAE'].push({ metric: 'unit', val: \"undefined\" });\n newaggr['Neph']['SAE'].push({ metric: 'Flag', val: 20 });\n } else {\n newaggr['Neph']['SAE'].push({ metric: 'calc', val: SAE_Neph });\n newaggr['Neph']['SAE'].push({ metric: 'unit', val: \"undefined\" });\n // Must be valid data if it it came this far\n newaggr['Neph']['SAE'].push({ metric: 'Flag', val: 1 });\n }\n } else {\n newaggr['Neph']['SAE'].push({ metric: 'calc', val: 'NaN' });\n newaggr['Neph']['SAE'].push({ metric: 'unit', val: \"undefined\" });\n // It's just easier to assign flag 20 when if fails\n newaggr['Neph']['SAE'].push({ metric: 'Flag', val: 20 });\n }\n }\n }\n\n // Unfortunately, Neph doesn't really have a flag. It's just trusted that if there is data, it is valid. \n // I'll ensure data exists before a calculation for safety reasons.\n // Calculations for tap instruments done here\n tapNames.forEach((instrument) => {\n newaggr[instrument]['SSA_Red'] = [];\n newaggr[instrument]['SSA_Green'] = [];\n newaggr[instrument]['SSA_Blue'] = [];\n newaggr[instrument]['AAE'] = [];\n if (newaggr['Neph'] !== undefined && newaggr['Neph']['RedScattering'] !== undefined && newaggr['Neph']['GreenScattering'] !== undefined && newaggr['Neph']['BlueScattering'] !== undefined) {\n let RedScatteringFlagIndex = 0;\n let RedScatteringAvgIndex = 0;\n for (let index = 0; index < newaggr['Neph']['RedScattering'].length; index++) {\n if (newaggr['Neph']['RedScattering'][index].metric === 'Flag') {\n RedScatteringFlagIndex = index;\n }\n if (newaggr['Neph']['RedScattering'][index].metric === 'avg') {\n RedScatteringAvgIndex = index;\n }\n }\n\n let GreenScatteringFlagIndex = 0;\n let GreenScatteringAvgIndex = 0;\n for (let index = 0; index < newaggr['Neph']['GreenScattering'].length; index++) {\n if (newaggr['Neph']['GreenScattering'][index].metric === 'Flag') {\n GreenScatteringFlagIndex = index;\n }\n if (newaggr['Neph']['GreenScattering'][index].metric === 'avg') {\n GreenScatteringAvgIndex = index;\n }\n }\n\n let BlueScatteringFlagIndex = 0;\n let BlueScatteringAvgIndex = 0;\n for (let index = 0; index < newaggr['Neph']['BlueScattering'].length; index++) {\n if (newaggr['Neph']['BlueScattering'][index].metric === 'Flag') {\n BlueScatteringFlagIndex = index;\n }\n if (newaggr['Neph']['BlueScattering'][index].metric === 'avg') {\n BlueScatteringAvgIndex = index;\n }\n }\n\n let RedAbsCoefFlagIndex = 0;\n let RedAbsCoefAvgIndex = 0;\n for (let index = 0; index < newaggr[instrument]['RedAbsCoef'].length; index++) {\n if (newaggr[instrument]['RedAbsCoef'][index].metric === 'Flag') {\n RedAbsCoefFlagIndex = index;\n }\n if (newaggr[instrument]['RedAbsCoef'][index].metric === 'avg') {\n RedAbsCoefAvgIndex = index;\n }\n }\n\n let GreenAbsCoefFlagIndex = 0;\n let GreenAbsCoefAvgIndex = 0;\n for (let index = 0; index < newaggr[instrument]['GreenAbsCoef'].length; index++) {\n if (newaggr[instrument]['GreenAbsCoef'][index].metric === 'Flag') {\n GreenAbsCoefFlagIndex = index;\n }\n if (newaggr[instrument]['GreenAbsCoef'][index].metric === 'avg') {\n GreenAbsCoefAvgIndex = index;\n }\n }\n\n let BlueAbsCoefFlagIndex = 0;\n let BlueAbsCoefAvgIndex = 0;\n for (let index = 0; index < newaggr[instrument]['BlueAbsCoef'].length; index++) {\n if (newaggr[instrument]['BlueAbsCoef'][index].metric === 'Flag') {\n BlueAbsCoefFlagIndex = index;\n }\n if (newaggr[instrument]['BlueAbsCoef'][index].metric === 'avg') {\n BlueAbsCoefAvgIndex = index;\n }\n }\n\n // If any of the SSA calculations fail, AAE calculations will fail.\n // Allows Different SSA colors to still do calculations whilst preventing AAE from failing\n let SSAFailed = false;\n\n //SSA calculations begin here:\n let obj = {\n Flag:newaggr[instrument]['RedAbsCoef'][RedAbsCoefFlagIndex].val,\n avg:newaggr[instrument]['RedAbsCoef'][RedAbsCoefAvgIndex].val\n };\n if (parseInt(newaggr['Neph']['RedScattering'][RedScatteringFlagIndex].val) === 1 && parseInt(obj.Flag) === 1) {\n let redScatteringAvg = parseFloat(newaggr['Neph']['RedScattering'][RedScatteringAvgIndex].val);\n let TotalExtinction_R = redScatteringAvg + obj.avg; // Matlab code: TotalExtinction_R = AC_R_Combined + outdata_Neph(:,2); %Total Extinction calculation for Red wavelength\n let SSA_R = redScatteringAvg / TotalExtinction_R; // Matlab code: SSA_R = outdata_Neph(:,2)./TotalExtinction_R; % SSA calculation for Red Wavelength\n\n newaggr[instrument]['SSA_Red'].push({ metric: 'calc', val: SSA_R });\n newaggr[instrument]['SSA_Red'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Red'].push({ metric: 'Flag', val: obj.Flag});\n\n // Matlab code: SSA_R (SSA_R < 0 | SSA_R ==1)=NaN;\n // decided > 1 because I have no idea why he used == and not >\n // I decided to make it SSA_R <= 0 to because javascript sends error values to zero by default\n if (SSA_R === undefined || SSA_R <= 0 || SSA_R > 1) {\n newaggr[instrument]['SSA_Red'].push({ metric: 'calc', val: ((SSA_R === undefined) ? 'NaN' : SSA_R) });\n newaggr[instrument]['SSA_Red'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Red'].push({ metric: 'Flag', val: 20});\n }\n } else {\n newaggr[instrument]['SSA_Red'].push({ metric: 'calc', val: 'NaN' });\n newaggr[instrument]['SSA_Red'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Red'].push({ metric: 'Flag', val: obj.Flag});\n SSAFailed = true;\n }\n\n obj = {\n Flag:newaggr[instrument]['GreenAbsCoef'][GreenAbsCoefFlagIndex].val,\n avg:newaggr[instrument]['GreenAbsCoef'][GreenAbsCoefAvgIndex].val \n };\n if (parseInt(newaggr['Neph']['GreenScattering'][GreenScatteringFlagIndex].val) === 1 && parseInt(obj.Flag) === 1) {\n let greenScatteringAvg = parseFloat(newaggr['Neph']['GreenScattering'][GreenScatteringAvgIndex].val);\n let TotalExtinction_G = greenScatteringAvg + obj.avg; // Matlab code: TotalExtinction_G = AC_G_Combined + outdata_Neph(:,3); %Total Extinction calculation for Green wavelength\n let SSA_G = greenScatteringAvg / TotalExtinction_G; // Matlab code: SSA_G = outdata_Neph(:,3)./TotalExtinction_G; % SSA calculation for Green Wavelength\n newaggr[instrument]['SSA_Green'].push({ metric: 'calc', val: SSA_G });\n newaggr[instrument]['SSA_Green'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Green'].push({ metric: 'Flag', val: obj.Flag});\n\n // Matlab code: SSA_G (SSA_G < 0 | SSA_G ==1)=NaN;\n // decided > 1 because I have no idea why he used == and not >\n // I decided to make it SSA_G <= 0 to because javascript sends error values to zero by default\n if (SSA_G === undefined || SSA_G <= 0 || SSA_G > 1) {\n newaggr[instrument]['SSA_Green'].push({ metric: 'calc', val: ((SSA_G === undefined) ? 'NaN' : SSA_G) });\n newaggr[instrument]['SSA_Green'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Green'].push({ metric: 'Flag', val: 20 });\n }\n } else {\n newaggr[instrument]['SSA_Green'].push({ metric: 'calc', val: 'NaN' });\n newaggr[instrument]['SSA_Green'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Green'].push({ metric: 'Flag', val: obj.Flag});\n SSAFailed = true;\n }\n\n obj = {\n Flag:newaggr[instrument]['BlueAbsCoef'][BlueAbsCoefFlagIndex].val,\n avg:newaggr[instrument]['BlueAbsCoef'][BlueAbsCoefAvgIndex].val\n };\n if (parseInt(newaggr['Neph']['BlueScattering'][BlueScatteringFlagIndex].val) === 1 && parseInt(obj.Flag) === 1) {\n let blueScatteringAvg = parseFloat(newaggr['Neph']['BlueScattering'][BlueScatteringAvgIndex].val);\n let TotalExtinction_B = blueScatteringAvg + obj.avg; // Matlab code: TotalExtinction_B = AC_B_Combined + outdata_Neph(:,4); %Total Extinction calculation for Blue wavelength\n let SSA_B = blueScatteringAvg / TotalExtinction_B; // Matlab code: SSA_B = outdata_Neph(:,4)./TotalExtinction_B; % SSA calculation for Blue Wavelength\n\n newaggr[instrument]['SSA_Blue'].push({ metric: 'calc', val: SSA_B });\n newaggr[instrument]['SSA_Blue'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Blue'].push({ metric: 'Flag', val: obj.Flag});\n\n // Matlab code: SSA_B (SSA_B < 0 | SSA_B ==1)=NaN; \n // I decided to make it SSA_B <= 0 to because javascript sends error values to zero by default\n if (SSA_B === undefined || (SSA_B <= 0 || SSA_B == 1)) {\n newaggr[instrument]['SSA_Blue'].push({ metric: 'calc', val: ((SSA_B === undefined) ? 'NaN' : SSA_B) });\n newaggr[instrument]['SSA_Blue'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Blue'].push({ metric: 'Flag', val: 20});\n }\n } else {\n newaggr[instrument]['SSA_Blue'].push({ metric: 'calc', val: 'NaN' });\n newaggr[instrument]['SSA_Blue'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['SSA_Blue'].push({ metric: 'Flag', val: obj.Flag});\n SSAFailed = true;\n }\n if (!SSAFailed) {\n // AAE calculations begin here:\n // Make sure tap instrument is valid\n let x = [640, 520, 365]; // Matlab code: x=[640,520,365]; % Wavelengths values\n let y_TAP = [ // Matlab code: y_TAP_01 = outdata1_TAP_01(:,6:8); %Absorption coefficients from TAP01\n parseFloat(newaggr[instrument]['RedAbsCoef'][RedAbsCoefAvgIndex].val), \n parseFloat(newaggr[instrument]['GreenAbsCoef'][GreenAbsCoefAvgIndex].val), \n parseFloat(newaggr[instrument]['BlueAbsCoef'][BlueAbsCoefAvgIndex].val)\n ];\n\n let lx = mathjs.log(x); // Matlab code: lx = log(x); %Taking log of the wavelengths\n let ly_TAP = mathjs.log(y_TAP);// Matlab code: ly_TAP_01 = log(y_TAP_01); %Taking log of the absorption coefficients for TAP01\n for (let i = 0; i < ly_TAP.length; i++) {\n if (isNaN(ly_TAP[i]) || ly_TAP[i] < 0) {\n ly_TAP[i] = 0;\n }\n }\n\n // Going to have to break this matlab code down a bit, again:\n // Matlab code: log_TAP_01 = -[lx(:) ones(size(x(:)))] \\ ly_TAP_01(:,:)'; %Step 1 -AAE from TAP 01 data\n let log_TAP = [ // Matlab code: [lx(:) ones(size(x(:)))] \n lx,\n mathjs.ones(mathjs.size(x))\n ];\n log_TAP = mathjs.transpose(log_TAP); // Needs to be transposed into 3x2 matrix\n // - operator just negates everything in the matrix\n flipSignForAll2D(log_TAP);\n\n\n /* More information on how I came to the lines below is in the SAE calculations. \n * Essentially, we are finding the least squares solution to the system of equations:\n * A*x=b\n */\n\n // A \\ b\n let ATA = mathjs.multiply(mathjs.transpose(log_TAP), log_TAP);\n let ATb = mathjs.multiply(mathjs.transpose(log_TAP), ly_TAP);\n\n // Create augmented matrix to solve for least squares solution\n ATA[0].push(ATb[0]);\n ATA[1].push(ATb[1]);\n\n log_TAP = rref(ATA);\n // Reason for index 0,2 is because I am skipping a step in the least squares approximation.\n // It is supposed to return a vector with 2 values, but I just shortcut it straight to the correct answer from the 3x2 rref matrix\n let AAE_TAP = log_TAP[0][2]; // Matlab code: SAE_Neph = log_Neph(1,:)'; %Step 2- SAE calulation\n\n // AAE normal ranges: .5 - 3.5\n // Sujan said this ^^^\n // matlab comment: % AAE__TAP_A(AAE__TAP_A < 0)= NaN;\n // I decided to make it AAE_TAP <= 0 to because javascript sends error values to zero by default\n if (AAE_TAP === undefined || AAE_TAP <= 0 || AAE_TAP > 3.5) {\n newaggr[instrument]['AAE'].push({ metric: 'calc', val: ((AAE_TAP === undefined) ? 'NaN' : AAE_TAP) });\n newaggr[instrument]['AAE'].push({ metric: 'unit', val: \"undefined\"});\n newaggr[instrument]['AAE'].push({ metric: 'Flag', val: 20 });\n } else {\n newaggr[instrument]['AAE'].push({ metric: 'calc', val: AAE_TAP });\n newaggr[instrument]['AAE'].push({ metric: 'unit', val: \"undefined\"});\n newaggr[instrument]['AAE'].push({ metric: 'Flag', val: obj.Flag});\n }\n } else {\n newaggr[instrument]['AAE'].push({ metric: 'calc', val: 'NaN' });\n newaggr[instrument]['AAE'].push({ metric: 'unit', val: \"undefined\" });\n newaggr[instrument]['AAE'].push({ metric: 'Flag', val: 20 });\n }\n }\n });\n\n subObj.subTypes = newaggr;\n AggrData.insert(subObj, function(error, result) {\n if (result === false) {\n Object.keys(newaggr).forEach(function(newInstrument) {\n Object.keys(newaggr[newInstrument]).forEach(function(newMeasurement) {\n // test whether aggregates for this instrument/measurement already exists\n const qry = {};\n qry._id = subObj._id;\n qry[`subTypes.${newInstrument}.${newMeasurement}`] = { $exists: true };\n\n if (AggrData.findOne(qry) === undefined) {\n const newQuery = {};\n newQuery.epoch = subObj.epoch;\n newQuery.site = subObj.site;\n const $set = {};\n const newSet = [];\n newSet[0] = newaggr[newInstrument][newMeasurement][0];\n newSet[1] = newaggr[newInstrument][newMeasurement][1];\n newSet[2] = newaggr[newInstrument][newMeasurement][2];\n newSet[3] = newaggr[newInstrument][newMeasurement][3];\n newSet[4] = newaggr[newInstrument][newMeasurement][4];\n $set['subTypes.' + newInstrument + '.' + newMeasurement] = newSet;\n\n // add aggregates for new instrument/mesaurements\n AggrData.findAndModify({\n query: newQuery,\n update: {\n $set: $set\n },\n upsert: false,\n new: true\n });\n } else {\n // Some aggregations will have less than 5 parts to it. \n // Need if statements to make sure it doesn't generate errors.\n // I really think that this whole thing should change, but I have no idea how it works.\n // So just leave this be and it will keep working.\n let newaggrLength = newaggr[newInstrument][newMeasurement].length;\n if (newaggrLength > 1) {\n const query0 = {};\n query0._id = subObj._id;\n query0[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'sum';\n const $set0 = {};\n $set0[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][0].val;\n AggrData.update(query0, { $set: $set0 });\n }\n if (newaggrLength > 1) {\n const query1 = {};\n query1._id = subObj._id;\n query1[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'avg';\n const $set1 = {};\n $set1[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][1].val;\n AggrData.update(query1, { $set: $set1 });\n }\n if (newaggrLength > 2) {\n const query2 = {};\n query2._id = subObj._id;\n query2[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'numValid';\n const $set2 = {};\n $set2[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][2].val;\n AggrData.update(query2, { $set: $set2 });\n }\n if (newaggrLength > 3) {\n const query3 = {};\n query3._id = subObj._id;\n query3[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'unit';\n const $set3 = {};\n $set3[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][3].val;\n AggrData.update(query3, { $set: $set3 });\n }\n if (newaggrLength > 4) {\n const query4 = {};\n query4._id = subObj._id;\n query4[`subTypes.${newInstrument}.${newMeasurement}.metric`] = 'Flag';\n const $set4 = {};\n $set4[`subTypes.${newInstrument}.${newMeasurement}.$.val`] = newaggr[newInstrument][newMeasurement][4].val;\n AggrData.update(query4, { $set: $set4 });\n }\n }\n });\n });\n }\n });\n });\n // drop temp collection that was placeholder for aggreagation results\n AggrResults.rawCollection().drop();\n}", "function subSets(arr, n){\n if( arr.length <=3 )return arr;\n let result = [];\n result.push([]);\n \n arr.forEach(function (item){\n let len = result.length;\n for(let i=0; i<len; i++){\n let newArr =result[i].slice(0);\n\n newArr.push(item);\n result.push(newArr)\n }\n})\n return result.filter(elem => elem.length ===n)\n }", "function ExistenceFilter(count){this.count=count;}", "function filter_data(){\n //console.log(sliderValues)\n new_data = []\n for(i =0; i < dataset_size; i++){\n filtered_out = false;\n for(let slider in sliderValues){\n min = parseFloat(sliderValues[slider][0])\n max = parseFloat(sliderValues[slider][1])\n attr = sliderIdToAttr[slider]\n val = parseFloat(data[i][attr])\n //console.log(val, min, max)\n if(val < min || val>max){\n //remove from screen if dataset doesnt meet any filter range\n filtered_out = true\n }\n }\n if (!filtered_out) {\n new_data.push(data[i])\n }\n }\n return new_data\n }", "function num_availHouses(ndx, group) {\n dc.dataCount('.dc-data-count')\n .crossfilter(ndx)\n .groupAll(group)\n .transitionDuration(500);\n}", "function selectBarDataHourly(group, dataset, startDate, endDate) {\n var ds = {};\n var totalViews = 0;\n var totalVisits = 0;\n for (x in dataset) {\n if (dataset[x].key === group) {\n for (hour in dataset[x].value.views) {\n ds[hour] = {};\n ds[hour]['views'] = dataset[x].value.views[hour];\n }\n for (hour in dataset[x].value.visits) {\n ds[hour]['visits'] = dataset[x].value.visits[hour];\n }\n }\n }\n return ds;\n}", "function getSum(){\n\tnumImages = 0;\n\tfor(var i = 0; i < data_cube.length; i++){\n\t\t\n\t\tif (data_cube[i].PATIENT_ID == patient_value &&\n\t\t\tdata_cube[i].TEST_TYPE == test_type_value &&\n\t\t\tdata_cube[i].DATSTR == date_value) {\n\t\t\t\tfound = true;\n\t\t\t\tnumImages = data_cube[i].CNT;\n\t\t\t}\n\t}\n\t$(\".data-sum\").html(\"<p>\" + numImages + \" </p>Images\");\n}", "_filterLiveProfiles() {\n const profiles = this.sessionLiveProfile;\n const toKeep = new Set();\n let newItem = {};\n profiles.forEach((profile) => {\n let bwToKeep = this._getNearestBandwidth(profile.bw, Object.keys(this.mediaManifestURIs));\n toKeep.add(bwToKeep);\n });\n toKeep.forEach((bw) => {\n newItem[bw] = this.mediaManifestURIs[bw];\n });\n this.mediaManifestURIs = newItem;\n }", "function ls(t) {\n return ne(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, \"F\" /* First */ , t.startAt, t.endAt);\n}", "function filterGB(data) {\n for(d in data.tracks) {\n if(data.tracks[d].album.availability.territories.indexOf('GB') > 0) delete data.tracks[d];\n }\n console.log(data);\n return data;\n}", "getLatestEmptyFiltersForTelemetry() {\n let cumulativeSize = 0;\n return this.latestEmptyFilters.filter(filterText => (cumulativeSize += filterText.length) <= 8192);\n }", "function remove3s(arr) {\n var bucket = [];\n arr.forEach(function (num) {\n if (num !==3) {\n bucket.push(num);\n }\n })\n return bucket\n}", "deleteAnyPastReservations(bank, branch) {\r\n //Get current day time\r\n var currentDate = new Date();\r\n var month = currentDate.getMonth() + 1;\r\n var day = currentDate.getDate();\r\n var year = currentDate.getFullYear();\r\n\r\n //Get timeframes referrence\r\n var timeFramesRef = database.getDocumentFromCollection(bank, branch).collection('TimeFrames');\r\n\r\n var yearLookup = 'year';\r\n var monthLookup = 'month';\r\n var dayLookup = 'day';\r\n\r\n //Find old timeframes and write a batch do delete them\r\n timeFramesRef.get().then(function (querySnapshot, docId) {\r\n var batch = database.getBatch();\r\n querySnapshot.forEach(doc => {\r\n\r\n if (!(doc.data()[yearLookup] > year) &&\r\n !(doc.data()[yearLookup] == year &&\r\n doc.data()[monthLookup] > month) &&\r\n !(doc.data()[yearLookup] == year &&\r\n doc.data()[monthLookup] == month &&\r\n doc.data()[dayLookup] >= day)) {\r\n batch.delete(doc.ref);\r\n }\r\n });\r\n return batch.commit();\r\n }).catch(err => {\r\n console.log(err.message);\r\n });\r\n }", "function randomSubset(data) {\n \treturn data.filter(d => Math.random() > 0.5);\n}", "function filterAll() {\n emptyDatasets();\n filters[dimensionName] = members;\n return dimensionObj;\n }" ]
[ "0.5298788", "0.49141982", "0.4851278", "0.48118484", "0.46582255", "0.4651824", "0.4643439", "0.46391973", "0.46039373", "0.4591683", "0.4539239", "0.4504699", "0.44960055", "0.44899675", "0.4475318", "0.44503573", "0.44395456", "0.443218", "0.43800408", "0.4331613", "0.43246093", "0.43229643", "0.43221474", "0.43171734", "0.43059638", "0.42977807", "0.42751735", "0.42734602", "0.4261451", "0.4251059" ]
0.60423595
0
Mark a card as the new minimum.
function markMin(globals, params, q) { animToQueue(q, '#' + globals.cardArray[params].num, {top:globals.SELECT_MOVE}, "min", globals, params); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "set min(value) {\n this.changeAttribute('min', value);\n }", "set min(value) {\n Helper.UpdateInputAttribute(this, 'min', value);\n }", "set _min(value) {\n Helper.UpdateInputAttribute(this, \"min\", value);\n }", "set minIndex(_val) {\n (typeof _val === \"number\") && this.setAttribute(\"min\", _val);\n }", "function addMinimumValues(response) {\n drawMap(response, 'card', 'addMinimumValues');\n}", "minimum(min) {\n this.min = min;\n return this;\n }", "static minimize(card) {\n\t\t//Move the element to the inactive card box\n\t\tdocument.getElementById(\"inactivecards\").appendChild(card);\n\t\t//Set the attribute\n\t\tcard.setAttribute(\"cardvisible\",\"false\");\n\t\t//Get the card icon\n\t\tvar cardicon = CardManager.getCardIcon(card.getAttribute(\"cardname\"));\n\t\t//Show the icon\n\t\tcardicon.style.display = \"inline-block\";\n\t\t//Save the card state\n\t\tCardManager.saveState();\n\t}", "function decreaseMin () {\n newMin = getMinimum()-10;\n min = newMin;\n return min;\n }", "function unmarkMin(globals, params, q) {\n animToQueue(q, '#' + globals.cardArray[params].num,\n {top:'0px'}, \"unmin\", globals, params);\n}", "function minPrice(element, value) {\n element.min = value;\n element.placeholder = value;\n }", "incrementMin() {\n this.alarm.minutes < 59 ? this.alarm.minutes++ : this.alarm.minutes = 0;\n this.setDisplay();\n }", "function resetQuestionValueToMin(questionValue) {\n if (questionValue < 0) {\n questionValue = 0;\n }\n return questionValue;\n}", "setValueDiffMin (valueDiffMin) {\n this._valueDiffMin = valueDiffMin\n }", "static updateMinimum(obj) {\n if (CSRankings.minToRank <= 500) {\n let t = obj.scrollTop;\n CSRankings.minToRank = 5000;\n CSRankings.getInstance().rank();\n return t;\n }\n else {\n return 0;\n }\n }", "function selectionChangeSmallest(){\n addStep(\"Index Node \" + (selectionIndex + 1) + \" is smaller than smallest node \" + (selectionSmallest + 1) + \". Set Node \" + (selectionIndex + 1) + \" to \\\"smallest\\\"\");\n setClass(nodes[selectionIndex], 2, \"Selected\"); //changing the current node to a blend of index and smallest (selected).\n \n if(selectionSmallest == selectionCurrent){ //the previous smallest node is the first unsorted node\n setClass(nodes[selectionSmallest], 2, \"Current\");\n }else{\n setClass(nodes[selectionSmallest], 2, \"Default\");\n }\n\n selectionSmallest = selectionIndex;\n foundNewSorted = false;\n selectionIndex++;\n}", "get min() { return this._min; }", "get min() { return this._min; }", "get min() { return this._min; }", "get min() { return this._min; }", "get min() { return this._min; }", "get min() { return this._min; }", "min() {\n const { value, operation } = this.state;\n if (operation === 0) {\n this.setState({\n num1: Number(value),\n operation: 2,\n });\n this.clear();\n }\n }", "function increaseSupply() {\n shiftSupply([1, -1]);\n }", "get min() {\r\n return this._min\r\n }", "set low(low){\n\t\tthis._low = low;\n\t}", "set low(low){\n\t\tthis._low = low;\n\t}", "minOrderQuantity(minValue) {\n return minValue;\n }", "get min() {\n return this._min;\n }", "function updateMinN(min) {\n reset();\n if (min < 1 || min > 100 || Math.round(min) != min) {\n alert(\"Minimum value of n must be an integer between 1 and 100\");\n document.getElementById(\"minInput\").value = minN;\n } else {\n minN = min;\n }\n}", "min(other) {\n return other.pos < this.pos ? other : this;\n }" ]
[ "0.6762539", "0.6391446", "0.6310163", "0.5955062", "0.594887", "0.5933817", "0.57989806", "0.5765526", "0.5754966", "0.5736904", "0.57338846", "0.5725054", "0.5714888", "0.56963027", "0.56401217", "0.56140196", "0.56140196", "0.56140196", "0.56140196", "0.56140196", "0.56140196", "0.5524803", "0.54849315", "0.541646", "0.5414785", "0.5414785", "0.54133344", "0.5398396", "0.53867763", "0.53816617" ]
0.68334275
0
Unmark a card as the minimum.
function unmarkMin(globals, params, q) { animToQueue(q, '#' + globals.cardArray[params].num, {top:'0px'}, "unmin", globals, params); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "remove() {\n if (!this.value) {\n this.value = this.min || 0;\n }\n const step = this.ctrl_key ? 100 : this.shift_key ? 10 : this.step || 1;\n this.value -= step;\n if (this.value < this.min) {\n this.value = this.min || 0;\n }\n this.setValue(this.value);\n }", "static minimize(card) {\n\t\t//Move the element to the inactive card box\n\t\tdocument.getElementById(\"inactivecards\").appendChild(card);\n\t\t//Set the attribute\n\t\tcard.setAttribute(\"cardvisible\",\"false\");\n\t\t//Get the card icon\n\t\tvar cardicon = CardManager.getCardIcon(card.getAttribute(\"cardname\"));\n\t\t//Show the icon\n\t\tcardicon.style.display = \"inline-block\";\n\t\t//Save the card state\n\t\tCardManager.saveState();\n\t}", "function decreaseSupply() {\n shiftSupply([-1, 1]);\n }", "function markMin(globals, params, q) {\n animToQueue(q, '#' + globals.cardArray[params].num,\n {top:globals.SELECT_MOVE}, \"min\", globals, params);\n}", "function clearMinValues() {\n storage.unset(/min/)\n}", "function decreaseMin () {\n newMin = getMinimum()-10;\n min = newMin;\n return min;\n }", "removeNewMark() {\n this.card.removeChild(this.newPill);\n }", "async UnsetCard({ commit }) {\n commit(\"UNSET_CURRENT_CARD\");\n commit(\"UNSET_CURRENT_CARD_DETAIL\");\n commit(\"UNSET_SELECTED_CARD\");\n commit(\"UNSET_SELECTED_CARD_DETAIL\");\n }", "reset() {\r\n\t\tlet me = this;\r\n\t\tif (me.up > 50 && me.down >= me.up) {\r\n\t\t\tme.up = 0;\r\n\t\t\tme.down = 0;\r\n\t\t}\r\n\t}", "removeMin() {\r\n\t\tthis.remove(this.heap[0]);\r\n\t}", "removeCard() { this.df = null; }", "function fix_extrema(slot) {\n if (slot.maximum !== undefined) {\n slot.max = slot.maximum;\n delete slot.maximum;\n }\n if (slot.minimum !== undefined) {\n slot.min = slot.minimum;\n delete slot.minimum;\n }\n }", "function uncoverCard() {\n\t// to store id of clicked card\n\tlet clickedCard = this.id;\n\tdocument.getElementById(clickedCard).classList.add(\"card-rotate\");\n}", "fear() {\n\t\tthis.mentalScore--;\n\t\tif (this.mentalScore < 0) {\n\t\t\tthis.mentalScore = 0;\n\t\t}\n\t}", "markOff(){\n this.room.unmarkPosition(this.positionX, this.positionY);\n }", "reduceArmor(amount) {\n this._armor -= amount;\n if(this._armor <= 0) {\n console.log(this.toString()+' ran out of armor and expired');\n if (this._contained != null) {\n this.place.placeContained(this._contained);\n } else {\n this.place = undefined;\n }\n }\n }", "set min(value) {\n this.changeAttribute('min', value);\n }", "function removeOpenCards() {\n cardOpen = [];\n\n}", "hide() {\n this.card.style.transform = \"rotateY(0deg)\";\n this.editing = false;\n }", "function removeTookCards() {\n\tif (cardsmatched < 7){\n\t\n\t\tcardsmatched++;\n\t\t$(\".card-removed\").remove();\n\t}else{\n\t\t$(\".card-removed\").remove();\n\t\tuiCards.hide();\n\t\tuiGamerestart.hide();\n\t\tuiGameInfo.hide();\n\t\tuiLogo.hide();\n\t\tuiComplete.show();\n\t\tvar gamecomplete = document.getElementById(\"gameComplete\").getElementsByClassName(\"button\");\n\t\t\t//default select first card\n\t\t$(gamecomplete).addClass(\"active\");\n\t\ttagelementcount=3;\n\t\tclearTimeout(scoreTimeout);\n\t}\t\n}", "clearFromMark() {\r\n if (mark !== null) {\r\n stack.splice(mark);\r\n mark = null;\r\n }\r\n }", "_killCard(card) {\n const index = this.cards.getChildIndex(card);\n this.cards.removeChild(card);\n this.map[index].empty = true;\n }", "function resetBoard() {\n $(\".card\").attr(\"class\",\"card\");\n $(\".card\").removeAttr(\"style\")\n $(\".moves\").text(0);\n $(\".stars li i\").attr(\"class\",\"fa fa-star\");\n $(\".container\").removeAttr(\"style\");\n}", "function allowClick() {\r\n $(\".card\").removeClass(\"notouch\");\r\n}", "minusHP() {\n if (this.startHP > 0) {\n this.startHP -= 5;\n }\n }", "function deselectCard(cardElem) {\n cardElem.classList.remove(FLIP);\n\n // Update aria label to face down\n cardElem.setAttribute('aria-label', FACE_DOWN);\n }", "function unFlipCards() {\n clearCardInPlay();\n freezePlay = true;\n setTimeout(() => {\n cardOne.classList.remove(\"flip\");\n cardTwo.classList.remove(\"flip\");\n clearDeck();\n }, 1700);\n }", "drawCard() {\n let drawnCard = super.drawCard();\n this._decks.forEach(deck => deck.removeCard(drawnCard));\n return drawnCard;\n }", "function unflipCards (){\n lockBoard = true;\n\n setTimeout(() => {\n firstCard.classList.remove (\"flip\");\n secondCard.classList.remove (\"flip\");\n\n resetBoard();\n }, 1200);\n }", "function unflipCards() {\n lockBoard = true;\n setTimeout(() => {\n firstCard.classList.remove('flip');\n secondCard.classList.remove('flip');\n resetBoard();\n }, 1500);\n\n }" ]
[ "0.5794074", "0.57848006", "0.56940156", "0.56817675", "0.5626896", "0.560562", "0.55201274", "0.54891515", "0.5468478", "0.5459153", "0.53400993", "0.5333994", "0.5292736", "0.52908754", "0.5239382", "0.51999056", "0.51772475", "0.5173613", "0.5171734", "0.51701933", "0.5157415", "0.51375574", "0.5120611", "0.51179695", "0.51095307", "0.5106713", "0.51049733", "0.5086984", "0.50860727", "0.50811124" ]
0.70508796
0
Mark a card as sorted.
function markSorted(globals, params, q) { animToQueue(q, '#' + globals.cards[params].num, {top:'0px'}, "sort", globals, params); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "sortTheCard() {\n this.sort = this.cards.sort((currentCard, nextCard) => currentCard.value - nextCard.value);\n }", "function setSorted(globals, id) {\n var cards = globals.cards;\n cards[id].sorted = true;\n cards[id].flipped = false;\n globals.totFlip--;\n $('#' + id).css({\n backgroundImage:'url(' + globals.cards[id].sortedBack + ')'\n })\n}", "let isSort;\n for (let i=0; i<cards.length; i++) {\n const card = cards[i];\n const cardOld = cardsOld[i];\n if (card.id !== cardOld.id) {\n isSort = true;\n break;\n } else {\n if (!shallowEqual(card, cardOld)) {\n // its a card update\n isSort = false;\n break;\n }\n }\n }", "function sortCardList() {\r\n const sortedArray = sort(cardListArray);\r\n console.log(\"sorted --\", sortedArray);\r\n\r\n for (let i = 0; i < sortedArray.length; i++) {\r\n container.appendChild(sortedArray[i]);\r\n }\r\n }", "set sortingOrder(value) {}", "function bubbleSetSorted(){\n addStep(\"Node \" + (bubbleIndex + 1) + \" is now sorted.\");\n if(bubbleIsSorted){\n bubbleEarlyEnd();\n return;\n }\n setClass(nodes[bubbleIndex], 2, \"Sorted\"); //set node to sorted color\n setClass(nodes[bubbleIndex - 1], 2, \"Default\"); //set previous node to default\n bubbleEndStep++;\n bubbleLimit--;\n}", "function sortCards() {\n clearCards();\n for (i = 0; i < 9; i++) {\n createCard(i);\n }\n}", "function sortingDscend() { \n setSearchData(null)\n let sorted = studentData.sort(function(a, b){\n return a.id - b.id;\n })\n\n setSearchData(sorted)\n // console.log(sorted, typeof(sorted))\n }", "function kartenSortieren() {\n hand.sort(sortByvalue);\n hand.sort(sortBybild);\n handkarten();\n}", "function onSort() {\n\tvar items = {};\n\titems[ this.options.sortIdKey ] = this.sorTable.sortId;\n\titems[ this.options.sortAscKey ] = this.sorTable.sortAsc;\n\tchrome.storage.local.set( items );\n}", "Sort() {\n\n }", "function autoSort(cards) {\n var steps = [];\n var toInsert = 0;\n var currentMin = Number.MAX_VALUE;\n var minIndex = Number.MAX_VALUE;\n\n var length = cards.length;\n for (var i = 0; i < length; i++) {\n // Find the minimum\n for (var j = toInsert; j < length; j++) {\n steps.push('consider:'+j);\n if (cards[j] < currentMin) {\n if (minIndex != Number.MAX_VALUE) {\n steps.push('unmarkMin:'+minIndex)\n }\n steps.push('markMin:'+j);\n currentMin = cards[j];\n minIndex = j;\n }\n steps.push('unconsider:'+j);\n }\n\n // Move min to correct place\n steps.push('move:'+minIndex+';to;'+toInsert);\n steps.push('markSorted:'+toInsert);\n cards.move(minIndex, toInsert);\n toInsert++;\n currentMin = Number.MAX_VALUE;\n minIndex = Number.MAX_VALUE;\n }\n return steps;\n}", "function sortingAscend() {\n setSearchData(null)\n let sorted = studentData.sort(function(a, b){\n return b.id - a.id;\n })\n\n setStudentData(sorted)\n console.log(sorted, typeof(sorted))\n }", "_sortedByChanged(sorted) {\n const headerColumns = this.shadowRoot.querySelectorAll('.th');\n this._resetOldSorting();\n headerColumns.forEach((el) => {\n if (el.getAttribute('sortable') === sorted) {\n el.setAttribute('sorted', '');\n this.set('sortDirection', 'ASC');\n }\n });\n }", "function Sort() {}", "function ShellSortCardIndex(iCardIndexList, iCompareMethod)\r\r\n{\r\r\n DebugLn(\"ShellSortCardIndex\");\r\r\n var sortIncrement = 3\r\r\n while (sortIncrement > 0)\r\r\n {\r\r\n var iiCard = 0;\r\r\n for (iiCard = sortIncrement; iiCard < iCardIndexList.length; iiCard++)\r\r\n {\r\r\n var jjCard = iiCard;\r\r\n var tempCardNum = iCardIndexList[iiCard];\r\r\n while (jjCard >= sortIncrement && \r\r\n iCompareMethod(iCardIndexList[jjCard - sortIncrement], tempCardNum) > 0)\r\r\n {\r\r\n var delta = jjCard - sortIncrement;\r\r\n iCardIndexList[jjCard] = iCardIndexList[delta];\r\r\n jjCard = delta;\r\r\n }\r\r\n iCardIndexList[jjCard] = tempCardNum;\r\r\n }\r\r\n if (sortIncrement == 1)\r\r\n {\r\r\n sortIncrement = 0;\r\r\n }\r\r\n else\r\r\n {\r\r\n sortIncrement = Math.floor(sortIncrement / 2);\r\r\n if (sortIncrement == 0)\r\r\n sortIncrement = 1;\r\r\n }\r\r\n }\r\r\n}", "function magic() {\n const sortCards = cards;\n sortCards.length = 0;\n // Create an array with objects containing the value and the suit of each card\n for (let x = 0; x < suits.length; x += 1) {\n for (let i = 1; i <= 13; i += 1) {\n const cardObject = {\n value: i,\n suit: suits[x],\n };\n sortCards.push(cardObject);\n }\n }\n\n // For each dataObject, replace the previous card and append it to the DOM\n sortCards.forEach((card, i) => {\n const positionFromLeft = i * 30;\n const sortedCards = document.createElement('div');\n sortedCards.setAttribute('data-value', card.value);\n sortedCards.classList.add('card', `${card.suit}-${card.value}`);\n sortedCards.style.left = `${positionFromLeft}px`;\n cardsWrapper.replaceChild(sortedCards, cardsWrapper.children[i]);\n });\n}", "async function sort() {\r\n await sortBooks();\r\n // document.getElementById(\"sortButton\").style.display = \"none\";\r\n // document.getElementById(\"pauseButton\").style.display = \"inline\";\r\n // document.getElementById(\"resetButton\").style.display = \"inline\";\r\n // eventId = window.requestAnimationFrame(draw);\r\n // isSorting = true;\r\n }", "sorted(x) {\n super.sorted(0, x);\n }", "sort() {\n if (this.sortOrder === 'asc') {\n this.set('sortOrder', 'desc');\n\n } else if (this.sortOrder === '') {\n this.set('sortOrder', 'asc');\n\n } else {\n this.set('sortOrder', '');\n\n }\n }", "changeSorting() {\n this.currentlySelectedOrder =\n (this.currentlySelectedColumn === this.columnName) ? !this.currentlySelectedOrder : false;\n this.currentlySelectedColumn = this.columnName;\n }", "setSort(sort) {\n this.setState({\n sort\n });\n }", "set overrideSorting(value) {}", "function _sortDeck () {\n deck.sort ( (a, b) => {\n let cardA = getCardById(a);\n let cardB = getCardById(b);\n if (cardA[\"cost\"] > cardB[\"cost\"]) {\n return 1;\n }\n else if (cardA[\"cost\"] < cardB[\"cost\"]) {\n return -1;\n }\n else {\n return cardA[\"name\"] > cardB[\"name\"];\n }\n });\n}", "function sortCards(arr) {\r\n arr.sort(function(a,b){\r\n // If both cards have the same suit\r\n if (suits.indexOf(a.suit) == suits.indexOf(b.suit)) {\r\n // If Card A has a lower value than Card B\r\n // Return Card A, else return Card B\r\n if (values.indexOf(a.value) < values.indexOf(b.value)) {\r\n return -1;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n\r\n // Else if Card A has a lower suit than Card B\r\n // Return Card A, else return Card B\r\n else if (suits.indexOf(a.suit) < suits.indexOf(b.suit)) {\r\n return -1;\r\n }\r\n else {\r\n return 1;\r\n }\r\n });\r\n}", "function sortActive(item, index) {\n //console.log(\"im sort\" + item);\n putAtPosition(item, index);\n changeColorofBar(item + 1, true);\n key2++;\n}", "resetSortState() {\n this.props.dispatch(couponsActions.toggleSort(false, 4, 'Recommended'));\n this.props.dispatch(couponsActions.setSortResults([]));\n }", "function sortCards(dataArray) {\n var sortId = $(\".sort-dropdown .dropdown-inner li.active\").attr(\"id\");\n if (sortId == \"latest\") {\n dataArray.sort(custom_sort_date);\n dataArray.reverse();\n } else if (sortId == \"oldest\") {\n dataArray.sort(custom_sort_date);\n } else if (sortId == \"viewed\") {\n dataArray.sort(custom_sort_view);\n dataArray.reverse();\n } else if (sortId == \"liked\") {\n dataArray.sort(custom_sort_like);\n dataArray.reverse();\n }\n generateVideoListItems(dataArray);\n }", "sort(){\n\n }", "function BubbleSortCardIndex(iCardIndexList, iCompareMethod)\r\r\n{\r\r\n DebugLn(\"BubbleSortCardIndex\");\r\r\n \r\r\n var iiCard = 0;\r\r\n for (iiCard = 0; iiCard < iCardIndexList.length - 1; iiCard++)\r\r\n {\r\r\n var jjCard = 0;\r\r\n for (jjCard = iiCard + 1; jjCard < iCardIndexList.length; jjCard++)\r\r\n {\r\r\n if (iCompareMethod(iCardIndexList[jjCard], iCardIndexList[iiCard]) < 0)\r\r\n {\r\r\n var temp = iCardIndexList[iiCard];\r\r\n iCardIndexList[iiCard] = iCardIndexList[jjCard];\r\r\n iCardIndexList[jjCard] = temp;\r\r\n }\r\r\n }\r\r\n }\r\r\n}" ]
[ "0.70687985", "0.6549775", "0.62567806", "0.6168512", "0.6131611", "0.59777063", "0.58453494", "0.5823961", "0.57884926", "0.5781722", "0.57808983", "0.57802534", "0.5776661", "0.5752555", "0.5728674", "0.5721736", "0.56574416", "0.5646556", "0.5619388", "0.5619064", "0.5616602", "0.5607104", "0.56019264", "0.5590857", "0.5587588", "0.5586429", "0.557", "0.5545176", "0.5543108", "0.5542165" ]
0.6925067
1
calculate the distance from the the rssi
function distance_rssi(rssi_p){ var cal= -66; var dist; if(cal<rssi_p){ dist = Math.pow(10,rssi_p/cal) } else{ dist = (0.9*Math.pow(7.71,rssi_p/cal)+0.11)*0.001 } return dist }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function mapBeaconRSSI(rssi)\n {\n if (rssi >= 0) return 1; // Unknown RSSI maps to 1.\n if (rssi < -100) return 100; // Max RSSI\n return 100 + rssi;\n }", "function mapBeaconRSSI(rssi) {\n if (rssi >= 0)\n return 1; // Unknown RSSI maps to 1.\n if (rssi < -100)\n return 100; // Max RSSI\n return 100 + rssi;\n}", "get distance() {}", "calculer_distance() {}", "distance() {\n return this.speed * this.duration() / 3600000;\n }", "function distance(lRequirement, rRequirement, listening, reading) {\r\n var lr = Number.parseInt(lRequirement);\r\n var rr = Number.parseInt(rRequirement);\r\n var l = Number.parseInt(listening);\r\n var r = Number.parseInt(reading);\r\n if (l - lr < 0)\r\n return -1;\r\n if (r - rr < 0)\r\n return -1;\r\n return (l - lr) + (r - rr);\r\n}", "function getTotalDistance (result) {\n var total = 0;\n var myroute = result.routes[0];\n for (var i = 0; i < myroute.legs.length; i++) {\n total += myroute.legs[i].distance.value;\n }\n total /= 1000;\n return total;\n}", "GetDistanceToPoint() {}", "function calculate_distance() {\n\n currgal_length_in_Mpc = convert_ltyr_to_Mpc(currgal_length_in_ltyr);\n currgal_distance = currgal_length_in_Mpc / view_height_rad;\n\n print_distance(\"calculating.\");\n setTimeout(function () {\n print_distance(\"calculating..\")\n }, 500);\n setTimeout(function () {\n print_distance(\"calculating...\")\n }, 1000);\n setTimeout(function () {\n print_distance(Math.round(currgal_distance).toLocaleString() + \" Mpc\")\n }, 1500);\n }", "calDistance(lat1, lon1, lat2, lon2) {\n let R = 6371; // km\n let dLat = this.toRad(lat2 - lat1);\n let dLon = this.toRad(lon2 - lon1);\n let radlat1 = this.toRad(lat1);\n let radlat2 = this.toRad(lat2);\n let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(radlat1) * Math.cos(radlat2);\n let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n let d = R * c;\n return d;\n }", "function get_distance(device, link_station) {\n return Math.sqrt((device[0] - link_station[0])**2 + (device[1] - link_station[1])**2);\n}", "function getDistance() {\r\n\talert('Detecting distance');\r\n\tnavigator.geolocation.getCurrentPosition(getDistanceFromPoint); \r\n}", "function computeTotalDistance(result) {\n var total = 0;\n var myroute = result.routes[0];\n for (var i = 0; i < myroute.legs.length; i++) {\n total += myroute.legs[i].distance.value;\n }\n total = total / 1000.0;\n}", "function getDistance() {\n var dLat = deg2rad(loc2X - loc1X); // deg2rad below\n var dLon = deg2rad(loc2Y - loc1Y);\n var a =\n Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n Math.cos(deg2rad(loc1X)) *\n Math.cos(deg2rad(loc2X)) *\n Math.sin(dLon / 2) *\n Math.sin(dLon / 2);\n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n var d = rr * c; // Distance in km\n return d;\n}", "distance() {\n return distanceBetweenPoints(this.sourceAirport.latLng, this.destinationAirport.latLng);\n }", "function calculateDistance(pointer_1, pointer_2) {\n var dist = (google.maps.geometry.spherical.computeDistanceBetween(pointer_1, pointer_2) / 1000).toFixed(2);\n return parseFloat(dist);\n\n }", "function totalDistance() {\n var distanceSum = 0;\n for (let index = 0; index < distancesPointToPoint.length; index++) { //iterationg over the distances\n distanceSum += distancesPointToPoint[index]; //add the distance\n }\n distanceSum = Math.round(distanceSum * 1000) / 1000;\n return distanceSum;\n}", "function RSSI(measurementType, RSSIValue, proximityBinThreshold) {\n\n if (typeof measurementType !== \"undefined\")\n this.measurementType = measurementType;\n\n if (typeof RSSIValue !== \"undefined\")\n this.RSSIValue = RSSIValue;\n\n if (typeof proximityBinThreshold !== \"undefined\") {\n \n this.thresholdConfigurationValue = (new Int8Array([proximityBinThreshold]))[0]; // Default -128 dB = \"Off\" -setting , spec. p. 36, specified in proximity search command\n }\n}", "function getDistance(x, y){\n return power2(x) + power2(y);\n }", "function findXY(bid_1, bid_2, bid_3, rssi_1, rssi_2, rssi_3) {\n console.log(String.format('Matching BID:({0},{1},{2})', bid_1, bid_2, bid_3));\n\n // obj storing x,y with min. error\n var min_err = {\n 'x': -1, 'y': -1, 'err': Number.MAX_SAFE_INTEGER\n };\n var row_matched = 0;\n\n // loop all the data\n for(var i = 0; i < data.length; i++) {\n var row = data[i];\n // match the beacon ids\n if(row.bid_1 == bid_1 && row.bid_2 == bid_2 && row.bid_3 == bid_3) {\n row_matched++;\n var sum_err = 0;\n sum_err = Math.pow(row.rssi_1 - rssi_1, 2) + Math.pow(row.rssi_2 - rssi_2, 2) + Math.pow(row.rssi_3 - rssi_3, 2);\n if(sum_err < min_err.err) {\n min_err.x = row.x;\n min_err.y = row.y;\n min_err.err = Math.sqrt(sum_err/3); // TODO: Modify the error function\n }\n }\n }\n console.log(String.format(\"Total matched: {0}\", row_matched));\n console.log(\"RESULT:\");\n console.log(min_err);\n return min_err;\n}", "function distance(p1, p2) { return length_v2(diff_v2(p1, p2)); }", "_getRemainingDistance()\r\n {\r\n let distanceList = this._navPath.distances;\r\n let distRemaining = 0;\r\n\r\n // Add distance to next waypoint.\r\n distRemaining += this._distanceToNext();\r\n\r\n for (let distIdx = this._waypointIdx + 1; distIdx < distanceList.length; distIdx++)\r\n {\r\n // Add distances between all successive waypoints.\r\n distRemaining += distanceList[distIdx]\r\n }\r\n\r\n // Return distance in metres.\r\n return distRemaining;\r\n }", "function DISTANCE(here, there) {\n \n var mapObj = Maps.newDirectionFinder();\n mapObj.setOrigin(here);\n mapObj.setDestination(there);\n \n var directions = mapObj.getDirections();\n var getTheLeg = directions[\"routes\"][0][\"legs\"][0];\n var mins = getTheLeg[\"duration\"][\"text\"];\n \n return mins;\n}", "calculateDistanceBetween(position, source) {\n if ((position.lat === source.lat) && (position.lng === source.lng)) {\n return 0\n }\n\n var radlat1 = Math.PI * position.lat/180\n var radlat2 = Math.PI * source.lat/180\n var theta = position.lng - source.lng\n var radtheta = Math.PI * theta/180\n var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta)\n if (dist > 1) {\n dist = 1\n }\n return Math.acos(dist) * 180/Math.PI * DISTANCE_BETWEEN_LATITUDE_IN_MILES * KILOMETRES_IN_A_MILE \n }", "function getDistance(location) {\n return Math.abs(location[0]) + Math.abs(location[1]);\n}", "function pointToPointDistances(r) {\n for (let index_route = 0; index_route < r.length - 1; index_route++) {\n distancesPointToPoint[index_route] = distanceInMeter(r[index_route], r[index_route + 1]);\n }\n}", "function getDistance(a, b) {\n return ((addresses[a][0] - addresses[b][0]) ** 2) + ((addresses[a][1] - addresses[b][1]) ** 2)\n}", "function rssi_ping (sig) {\n if (sig > 199) {\n frq_ping(30, 0.2, 0.3) // ERROR\n } else {\n if (sig < 30) sig = 30\n const frq = Math.pow(2, (100 - sig) / 12) * 100\n frq_ping(frq, 0.5, 0.15)\n }\n }", "function calculateDistance(lat1, lon1, lat2, lon2) {\n var R = 6371e3; // m\n var dLat = (lat2 - lat1).toRad();\n var dLon = (lon2 - lon1).toRad(); \n var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * \n Math.sin(dLon / 2) * Math.sin(dLon / 2); \n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); \n var d = R * c;\n console.log(\"distance=\"+d + \"R = \"+ R);\n return Math.round(d);\n }", "distance(lat1, lon1) {\n if (lat1 === this.latitude && lon1 === this.longitude) {\n return 0;\n }\n else {\n const radlat1 = (Math.PI * lat1) / 180;\n const radlat2 = (Math.PI * this.latitude) / 180;\n const theta = lon1 - this.longitude;\n const radtheta = (Math.PI * theta) / 180;\n let dist = Math.sin(radlat1) * Math.sin(radlat2) +\n Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);\n if (dist > 1) {\n dist = 1;\n }\n dist = Math.acos(dist);\n dist = (dist * 180) / Math.PI;\n dist = dist * 60 * 1.1515;\n dist = dist * 1.609344;\n return dist;\n }\n }" ]
[ "0.65244526", "0.647684", "0.6271676", "0.6180164", "0.5978584", "0.59419155", "0.59161425", "0.5910772", "0.5836793", "0.5821521", "0.58053833", "0.5753798", "0.5730081", "0.57222176", "0.571949", "0.5654595", "0.56274945", "0.562134", "0.5585668", "0.5531825", "0.54504734", "0.54362464", "0.54044425", "0.5402833", "0.53960925", "0.53888756", "0.5380199", "0.5367861", "0.5364444", "0.53586274" ]
0.8016069
0
this function specifies the positions of bend points
bendPositionsFunction(ele) { return ele.data('bendPointPositions'); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "bpos()\n\t{\n\t\treturn [this.x + DIRS[this.dir][0], this.y + DIRS[this.dir][1]];\n\t}", "function Bezier(startPt, endPt, startCtrlPt, endCtrlPt) {\n\tvar b;\n\tb.startPoint=startPt;\n\tb.endPoint=endPt;\n\tb.startControlPoint = startCtrlPt;\n\tb.endControlPoint = endCtrlPt;\n\tb.getCartesianAt = new function(t) {\n\t\tif (t > 1 || t < 0) { /* TODO error handler */}\n\t\tvar x = Math.pow((1 - t),3) * b.startPoint.x +\n\t\t3*t*Math.pow((1-t),2) * b.startControlPoint.x +\n\t\t3*Math.pow(t,2)*(1-t) * b.endControlPoint.x +\n\t\tpow(t,3) * b.endPoint.x;\n\t\t\n\t\tvar y = Math.pow((1 - t),3) * b.startPoint.y +\n\t\t3*t*Math.pow((1-t),2) * b.startControlPoint.y +\n\t\t3*Math.pow(t,2)*(1-t) * b.endControlPoint.y +\n\t\tMath.pow(t,3) * b.endPoint.y;\n\t\t\n\t\treturn [x,y];\n\t}\n\treturn b;\n}", "function endPoint(branch) {\r\n\tvar x = branch.x + branch.l * Math.sin(branch.a);\r\n\tvar y = branch.y - branch.l * Math.cos(branch.a);\r\n\treturn {x: x, y: y};\r\n}", "function extraBpoints(mm){\n let shift;\n if (g.uniformGen == \"A\"){\n shift = 100;\n } else {\n shift = 75;\n }\n let value_temp = 550 - 5*mm + 150 - shift;\n push();\n strokeWeight(0); fill(255,0,0);\n circle(75, value_temp,12);\n circle(252, value_temp,12);\n strokeWeight(2); stroke(255,0,0);\n line(75,value_temp, 252+15, value_temp);\n pop();\n}", "function bishops (positions, w) {\n\n}", "positionPoints() {\n const padding = this.getBoundsPadding();\n\n const centerX = (this.content.width / (this.edgePointsAmount) / 2); // center on the X axis\n const rightX = this.getBoundsRightX(); // get the right point position\n const centerY = (this.content.height / (this.edgePointsAmount) / 2); // center on the Y axis\n const bottomY = this.content.height; // the bottom point position\n\n this.topPoint.x = centerX;\n this.topPoint.y = -padding.top;\n this.bottomPoint.x = centerX;\n this.bottomPoint.y = bottomY + padding.bottom;\n this.rightPoint.x = rightX + padding.right;\n this.rightPoint.y = centerY;\n this.leftPoint.x = -padding.left;\n this.leftPoint.y = centerY;\n }", "bouton_centrage_pos() {}", "breadcrumbPoints(i) {\n\t\t\tconst points = [];\n\t\t\tpoints.push(\"0,0\");\n\t\t\tpoints.push(`${this.b.w},0`);\n\t\t\tpoints.push(`${this.b.w + this.b.t},${this.b.h / 2}`);\n\t\t\tpoints.push(`${this.b.w},${this.b.h}`);\n\t\t\tpoints.push(`0,${this.b.h}`);\n\t\t\tif (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.\n\t\t\t\tpoints.push(`${this.b.t},${this.b.h / 2}`);\n\t\t\t}\n\t\t\treturn points.join(\" \");\n\t\t}", "get endB() { return Math.max(this.fromB, this.toB - 1); }", "function addBottomPoints(_points) {\n _points.push({x: 42, y:197});\n _points.push({x: 143, y:197});\n _points.push({x: 127, y:252});\n _points.push({x: 96, y:253});\n _points.push({x: 58, y:307});\n _points.push({x: 51, y:350});\n _points.push({x: 69, y:378});\n _points.push({x: 110, y:390});\n _points.push({x: 140, y:392});\n _points.push({x: 173, y:391});\n _points.push({x: 202, y:382});\n _points.push({x: 218, y:369});\n _points.push({x: 208, y:353});\n _points.push({x: 192, y:344});\n _points.push({x: 143, y:340});\n _points.push({x: 182, y:255});\n _points.push({x: 165, y:252});\n _points.push({x: 184, y:199});\n _points.push({x: 307, y:197});\n _points.push({x: 300, y:218});\n _points.push({x: 297, y:234});\n _points.push({x: 299, y:252});\n _points.push({x: 311, y:287});\n _points.push({x: 347, y:342});\n _points.push({x: 372, y:400});\n _points.push({x: 392, y:456});\n _points.push({x: 400, y:428});\n _points.push({x: 399, y:400});\n _points.push({x: 394, y:352});\n _points.push({x: 390, y:306});\n _points.push({x: 390, y:285});\n _points.push({x: 392, y:258});\n _points.push({x: 392, y:254});\n _points.push({x: 365, y:253});\n _points.push({x: 384, y:200});\n _points.push({x: 457, y:201});\n _points.push({x: 447, y:240});\n _points.push({x: 437, y:332});\n _points.push({x: 431, y:446});\n _points.push({x: 422, y:515});\n _points.push({x: 419, y:531});\n _points.push({x: 409, y:539});\n _points.push({x: 397, y:522});\n _points.push({x: 389, y:492});\n _points.push({x: 367, y:448});\n _points.push({x: 319, y:365});\n _points.push({x: 269, y:302});\n _points.push({x: 213, y:253});\n _points.push({x: 202, y:257});\n _points.push({x: 188, y:288});\n _points.push({x: 184, y:291});\n _points.push({x: 205, y:302});\n _points.push({x: 228, y:329});\n _points.push({x: 237, y:364});\n _points.push({x: 233, y:388});\n _points.push({x: 223, y:406});\n _points.push({x: 205, y:418});\n _points.push({x: 178, y:428});\n _points.push({x: 138, y:433});\n _points.push({x: 100, y:433});\n _points.push({x: 76, y:425});\n _points.push({x: 51, y:409});\n _points.push({x: 43, y:399});\n _points.push({x: 31, y:369});\n _points.push({x: 31, y:342});\n _points.push({x: 37, y:315});\n _points.push({x: 45, y:289});\n _points.push({x: 54, y:271});\n _points.push({x: 62, y:261});\n _points.push({x: 63, y:255});\n _points.push({x: 56, y:251});\n _points.push({x: 28, y:251});\n }", "get bending() {\n return {\n position: { max: 4.0 },\n angularVelocity: { percent: 0.0 },\n angleLocal: { percent: 0.0 }\n };\n }", "getStartingPosition(){\n return [this.x,this.y];\n }", "function blockpositions(B) {\n var posx = 0;\n var posy = 0;\n var Px = [];\n var Py = [];\n for (var x = 0; x < B; ++x) {\n for (var y = 0; y < B; ++y) {\n Px.push(posx);\n Py.push(posy);\n posx += B;\n posy += 1;\n }\n posx += (B * B * B) - (B * B)\n posy += (B * B) - B\n }\n return [Px, Py];\n}", "function getBranchPoints(begin, end) {\n const branchPartitionFactor = 20;\n\n const branchPoints = [];\n const dx = end.x - begin.x;\n const dy = end.y - begin.y;\n\n for (let i = 0; i < branchPartitionFactor; i++) {\n const x = begin.x + i*dx/branchPartitionFactor;\n const y = begin.y + i*dy/branchPartitionFactor;\n\n branchPoints.push(new Point(x, y));\n }\n branchPoints.push(new Point(end.x, end.y));\n\n return branchPoints;\n}", "calculateB() {\n let dx = this.len * Math.cos(this.angle);\n let dy = this.len * Math.sin(this.angle);\n this.b.set(this.a.x + dx, this.a.y + dy);\n }", "function ky__initB(position,normal){\n //create the buffer for the positions\n var positBuffer=ky__gl.createBuffer();\n //bind the buffer to the top webGL buffer editing interface\n ky__gl.bindBuffer(ky__gl.ARRAY_BUFFER,positBuffer);\n //set the vertices \n //add the positions array data to the positions buffer.\n ky__gl.bufferData(ky__gl.ARRAY_BUFFER,new Float32Array(position),ky__gl.STATIC_DRAW);\n \n return positBuffer;\n}", "function Bendpoints(eventBus, canvas, interactionEvents, bendpointMove, connectionSegmentMove) {\n\n function getConnectionIntersection(waypoints, event) {\n var localPosition = BendpointUtil.toCanvasCoordinates(canvas, event),\n intersection = getApproxIntersection(waypoints, localPosition);\n\n return intersection;\n }\n\n function isIntersectionMiddle(intersection, waypoints, treshold) {\n var idx = intersection.index,\n p = intersection.point,\n p0, p1, mid, aligned, xDelta, yDelta;\n\n if (idx <= 0 || intersection.bendpoint) {\n return false;\n }\n\n p0 = waypoints[idx - 1];\n p1 = waypoints[idx];\n mid = getMidPoint(p0, p1),\n aligned = pointsAligned(p0, p1);\n xDelta = Math.abs(p.x - mid.x);\n yDelta = Math.abs(p.y - mid.y);\n\n return aligned && xDelta <= treshold && yDelta <= treshold;\n }\n\n function activateBendpointMove(event, connection) {\n var waypoints = connection.waypoints,\n intersection = getConnectionIntersection(waypoints, event);\n\n if (!intersection) {\n return;\n }\n\n if (isIntersectionMiddle(intersection, waypoints, 10)) {\n connectionSegmentMove.start(event, connection, intersection.index);\n } else {\n bendpointMove.start(event, connection, intersection.index, !intersection.bendpoint);\n }\n }\n\n function getBendpointsContainer(element, create) {\n\n var layer = canvas.getLayer('overlays'),\n gfx = layer.select('.djs-bendpoints[data-element-id=' + element.id + ']');\n\n if (!gfx && create) {\n gfx = layer.group().addClass('djs-bendpoints').attr('data-element-id', element.id);\n\n domEvent.bind(gfx.node, 'mousedown', function(event) {\n activateBendpointMove(event, element);\n });\n }\n\n return gfx;\n }\n\n function createBendpoints(gfx, connection) {\n connection.waypoints.forEach(function(p, idx) {\n BendpointUtil.addBendpoint(gfx).translate(p.x, p.y);\n });\n\n // add floating bendpoint\n BendpointUtil.addBendpoint(gfx, 'floating');\n }\n\n function createSegmentDraggers(gfx, connection) {\n\n var waypoints = connection.waypoints;\n\n var segmentStart,\n segmentEnd;\n\n for (var i = 1; i < waypoints.length; i++) {\n\n segmentStart = waypoints[i - 1];\n segmentEnd = waypoints[i];\n\n if (pointsAligned(segmentStart, segmentEnd)) {\n BendpointUtil.addSegmentDragger(gfx, segmentStart, segmentEnd);\n }\n }\n }\n\n function clearBendpoints(gfx) {\n gfx.selectAll('.' + BENDPOINT_CLS).forEach(function(s) {\n s.remove();\n });\n }\n\n function clearSegmentDraggers(gfx) {\n gfx.selectAll('.' + SEGMENT_DRAGGER_CLS).forEach(function(s) {\n s.remove();\n });\n }\n\n function addHandles(connection) {\n\n var gfx = getBendpointsContainer(connection);\n\n if (!gfx) {\n gfx = getBendpointsContainer(connection, true);\n\n createBendpoints(gfx, connection);\n createSegmentDraggers(gfx, connection);\n }\n\n return gfx;\n }\n\n function updateHandles(connection) {\n\n var gfx = getBendpointsContainer(connection);\n\n if (gfx) {\n clearSegmentDraggers(gfx);\n clearBendpoints(gfx);\n createSegmentDraggers(gfx, connection);\n createBendpoints(gfx, connection);\n }\n }\n\n eventBus.on('connection.changed', function(event) {\n updateHandles(event.element);\n });\n\n eventBus.on('connection.remove', function(event) {\n var gfx = getBendpointsContainer(event.element);\n\n if (gfx) {\n gfx.remove();\n }\n });\n\n eventBus.on('element.marker.update', function(event) {\n\n var element = event.element,\n bendpointsGfx;\n\n if (!element.waypoints) {\n return;\n }\n\n bendpointsGfx = addHandles(element);\n bendpointsGfx[event.add ? 'addClass' : 'removeClass'](event.marker);\n });\n\n eventBus.on('element.mousemove', function(event) {\n\n var element = event.element,\n waypoints = element.waypoints,\n bendpointsGfx,\n floating,\n intersection;\n\n if (waypoints) {\n\n bendpointsGfx = getBendpointsContainer(element, true);\n floating = bendpointsGfx.select('.floating');\n\n if (!floating) {\n return;\n }\n\n intersection = getConnectionIntersection(waypoints, event.originalEvent);\n\n if (intersection) {\n floating.translate(intersection.point.x, intersection.point.y);\n }\n }\n });\n\n eventBus.on('element.mousedown', function(event) {\n\n var originalEvent = event.originalEvent,\n element = event.element,\n waypoints = element.waypoints;\n\n if (!waypoints) {\n return;\n }\n\n activateBendpointMove(originalEvent, element, waypoints);\n });\n\n eventBus.on('selection.changed', function(event) {\n var newSelection = event.newSelection,\n primary = newSelection[0];\n\n if (primary && primary.waypoints) {\n addHandles(primary);\n }\n });\n\n eventBus.on('element.hover', function(event) {\n var element = event.element;\n\n if (element.waypoints) {\n addHandles(element);\n interactionEvents.registerEvent(event.gfx.node, 'mousemove', 'element.mousemove');\n }\n });\n\n eventBus.on('element.out', function(event) {\n interactionEvents.unregisterEvent(event.gfx.node, 'mousemove', 'element.mousemove');\n });\n}", "setInitialBowlerPosition() {\n\t\tthis.startBowlPosX = config.width * 0.55;\n\t\tthis.startBowlPosY = config.height * 0.35;\n\t}", "breadcrumbPoints(d, i) {\n var points = [];\n var b = this.opt.breadcrumbs;\n points.push(\"0,0\");\n points.push(b.w + \",0\");\n points.push(b.w + b.t + \",\" + (b.h / 2));\n points.push(b.w + \",\" + b.h);\n points.push(\"0,\" + b.h);\n if (i > 0) {\n points.push(b.t + \",\" + (b.h / 2));\n }\n return points.join(\" \");\n }", "getBoneEndDistance(b) {\nreturn this.distance[b];\n}", "function posToBrgDst(x1, y1, x2, y2) {\n\tvar dx = x2-x1;\n\tvar dy = y2-y1;\n\t\n\treturn [\n\t\tMath.atan2(dx,dy), \n\t\tMath.sqrt(dx*dx+dy*dy)\n\t\t];\n}", "_parsePoints() {\n var top = this.options.topAnchor == \"\" ? 1 : this.options.topAnchor,\n btm = this.options.btmAnchor== \"\" ? document.documentElement.scrollHeight : this.options.btmAnchor,\n pts = [top, btm],\n breaks = {};\n for (var i = 0, len = pts.length; i < len && pts[i]; i++) {\n var pt;\n if (typeof pts[i] === 'number') {\n pt = pts[i];\n } else {\n var place = pts[i].split(':'),\n anchor = $(`#${place[0]}`);\n\n pt = anchor.offset().top;\n if (place[1] && place[1].toLowerCase() === 'bottom') {\n pt += anchor[0].getBoundingClientRect().height;\n }\n }\n breaks[i] = pt;\n }\n\n\n this.points = breaks;\n return;\n }", "function boundaryPoint_position(bp, relativeTo) {\n const nodeA = bp[0];\n const offsetA = bp[1];\n const nodeB = relativeTo[0];\n const offsetB = relativeTo[1];\n /**\n * 1. Assert: nodeA and nodeB have the same root.\n */\n console.assert(TreeAlgorithm_1.tree_rootNode(nodeA) === TreeAlgorithm_1.tree_rootNode(nodeB), \"Boundary points must share the same root node.\");\n /**\n * 2. If nodeA is nodeB, then return equal if offsetA is offsetB, before\n * if offsetA is less than offsetB, and after if offsetA is greater than\n * offsetB.\n */\n if (nodeA === nodeB) {\n if (offsetA === offsetB) {\n return interfaces_1.BoundaryPosition.Equal;\n }\n else if (offsetA < offsetB) {\n return interfaces_1.BoundaryPosition.Before;\n }\n else {\n return interfaces_1.BoundaryPosition.After;\n }\n }\n /**\n * 3. If nodeA is following nodeB, then if the position of (nodeB, offsetB)\n * relative to (nodeA, offsetA) is before, return after, and if it is after,\n * return before.\n */\n if (TreeAlgorithm_1.tree_isFollowing(nodeB, nodeA)) {\n const pos = boundaryPoint_position([nodeB, offsetB], [nodeA, offsetA]);\n if (pos === interfaces_1.BoundaryPosition.Before) {\n return interfaces_1.BoundaryPosition.After;\n }\n else if (pos === interfaces_1.BoundaryPosition.After) {\n return interfaces_1.BoundaryPosition.Before;\n }\n }\n /**\n * 4. If nodeA is an ancestor of nodeB:\n */\n if (TreeAlgorithm_1.tree_isAncestorOf(nodeB, nodeA)) {\n /**\n * 4.1. Let child be nodeB.\n * 4.2. While child is not a child of nodeA, set child to its parent.\n * 4.3. If child’s index is less than offsetA, then return after.\n */\n let child = nodeB;\n while (!TreeAlgorithm_1.tree_isChildOf(nodeA, child)) {\n /* istanbul ignore else */\n if (child._parent !== null) {\n child = child._parent;\n }\n }\n if (TreeAlgorithm_1.tree_index(child) < offsetA) {\n return interfaces_1.BoundaryPosition.After;\n }\n }\n /**\n * 5. Return before.\n */\n return interfaces_1.BoundaryPosition.Before;\n}", "function breadcrumbPoints(d, i) {\n\tvar points = [];\n\tpoints.push(\"0,0\");\n\tpoints.push(b.w + \",0\");\n\tpoints.push(b.w + b.t + \",\" + (b.h / 2));\n\tpoints.push(b.w + \",\" + b.h);\n\tpoints.push(\"0,\" + b.h);\n\tif (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.\n\t\tpoints.push(b.t + \",\" + (b.h / 2));\n\t}\n\treturn points.join(\" \");\n}", "function breadcrumbPoints(d, i) {\r\n var points = [];\r\n points.push(\"0,0\");\r\n points.push(b.w + \",0\");\r\n points.push(b.w + b.t + \",\" + (b.h / 2));\r\n points.push(b.w + \",\" + b.h);\r\n points.push(\"0,\" + b.h);\r\n if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.\r\n points.push(b.t + \",\" + (b.h / 2));\r\n }\r\n return points.join(\" \");\r\n }", "function breadcrumbPoints(d, i) {\n var points = [];\n points.push('0,0');\n points.push(b.w + ',0');\n points.push(b.w + b.t + ',' + (b.h / 2));\n points.push(b.w + ',' + b.h);\n points.push('0,' + b.h);\n if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.\n points.push(b.t + ',' + (b.h / 2));\n }\n return points.join(' ');\n }", "function breadcrumbPoints(d, i) {\n const points = [];\n points.push('0,0');\n points.push(`${b.w},0`);\n points.push(`${b.w + b.t},${b.h / 2}`);\n points.push(`${b.w},${b.h}`);\n points.push(`0,${b.h}`);\n if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.\n points.push(`${b.t},${b.h / 2}`);\n }\n return points.join(' ');\n}", "function breadcrumbPoints(d, i) {\n var points = [];\n points.push(\"0,0\");\n points.push(b.w*4 + \",0\");\n points.push(b.w*4 + b.t + \",\" + (b.h / 2));\n points.push(b.w*4 + \",\" + b.h);\n points.push(\"0,\" + b.h);\n if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.\n points.push(b.t + \",\" + (b.h / 2));\n }\n return points.join(\" \");\n}", "function breadcrumbPoints(d, i) {\n var points = [];\n points.push(\"0,0\");\n points.push(b.w + \",0\");\n points.push(b.w + b.t + \",\" + (b.h / 2));\n points.push(b.w + \",\" + b.h);\n points.push(\"0,\" + b.h);\n if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.\n points.push(b.t + \",\" + (b.h / 2));\n }\n return points.join(\" \");\n }", "function breadcrumbPoints(d, i) {\n var points = [];\n points.push(\"0,0\");\n points.push(b.w + \",0\");\n points.push(b.w + b.t + \",\" + (b.h / 2));\n points.push(b.w + \",\" + b.h);\n points.push(\"0,\" + b.h);\n if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.\n points.push(b.t + \",\" + (b.h / 2));\n }\n return points.join(\" \");\n }" ]
[ "0.6731586", "0.6204395", "0.6165572", "0.6045086", "0.6009413", "0.59384155", "0.5921679", "0.59192485", "0.5889758", "0.58740854", "0.58181715", "0.58097786", "0.5790465", "0.57809985", "0.5769285", "0.5757061", "0.5715059", "0.56950915", "0.5672013", "0.5658654", "0.5606313", "0.56015635", "0.5580816", "0.555212", "0.554054", "0.55098283", "0.55026793", "0.55008674", "0.55004716", "0.54953337" ]
0.6479256
1
Scrambles the given array
function scramble(arr) { let scrambled = []; let maxI = arr.length; for (let i = 0; i < maxI; i++) { // Appends the value at a random index in arr to the scrambled array and deletes it from arr let randomIndex = Math.floor(Math.random() * arr.length); scrambled.push(arr.splice(randomIndex, 1)[0]); } return scrambled; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function scramble(arr) {\n for (let i = arr.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * i);\n const temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n return arr;\n }", "function getScramble() {\n var moves = new Array();\n moves['r'] = new Array(\"R\", \"R'\", \"R2\");\n moves['l'] = new Array(\"L\", \"L'\", \"L2\");\n moves['u'] = new Array(\"U\", \"U'\", \"U2\");\n moves['d'] = new Array(\"D\", \"D'\", \"D2\");\n moves['f'] = new Array(\"F\", \"F'\", \"F2\");\n moves['b'] = new Array(\"B\", \"B'\", \"B2\");\n\n var limit = 25;\n var last = \"\";\n var scramble = \"\";\n var keys = \"\";\n\n for (var i = 1; i <= limit; i++) {\n keys = new Array(\"r\", \"l\", \"u\", \"d\", \"f\", \"b\");\n shuffle(keys);\n while (last == keys[0]) {\n shuffle(keys);\n }\n shuffle(moves[keys[0]]);\n move = moves[keys[0]][0];\n scramble += move + \" \";\n last = keys[0];\n } \n \n $$('.scramble .scramble-text').html( scramble);\n\n}", "function scrambleWord(word) {\n\t\n var charIndex = 0;\n //array of characters from the word\n wordArray = word.split(\"\");\n //empty array for scrambled word\n var scrambledArray = [];\n \n //scramble word\n while(wordArray.length > 0) {\n charIndex = Math.floor(Math.random()*wordArray.length);\n scrambledArray += wordArray[charIndex];\n wordArray.splice(charIndex,1);\n }\n\tscrambled = scrambledArray.toString();\n\n\tif (scrambled === word) {\n\t\tscrambleWord(word);\n\t}\n\n}", "function shufflePassword(array) {\n for (var i = array.length -1; i > 0; i--) {\n var j = Math.floor(Math.random() * (i+1)) ;\n var temp = array[i] ;\n array[i] = array[j] ;\n array[j] = temp ;\n }\n}", "function shuffleCharacters(array) {\n for (let i = array.length -1; i > 0; i--) {\n let j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n return array;\n}", "function scramble(){\n\tvar i,j,nameImage=0;\n\tvar tiles=new Array();\n\tfor(i=0;i<=numTiles;i++) tiles[i]=i;\n\ttiles[numTiles-1]=-1;tiles[numTiles-2]=-1;\n\tfor(i=0;i<height;i++){\n\t\tfor(j=0;j<wid;j++){\n\t\t\tk=Math.floor(Math.random()*tiles.length);\n\t\t\tposition[nameImage]=tiles[k];\n\t\t\tif(tiles[k]==numTiles) { blankx=j; blanky=i; }\n\t\t\ttiles[k]=tiles[tiles.length-1];\n\t\t\ttiles.length--;\n\t\t\tnameImage++;\n\t\t}\n\t}\n\tmode=1;\n\tfilltwo();\n}", "function mixCharacters(array) {\n for (let i = array.length - 1; i > 0; i--) {\n let j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n return array;\n}", "function rotateScramble (scramble) {\r\n const rotated = [\"R\", \"B\", \"L\", \"F\"];\r\n const rotation = Math.floor(Math.random()*4);\r\n for (let i = 0; i < scramble.length; i++) {\r\n let c = scramble.charAt(i);\r\n for (let j = 0; j < rotated.length; j++) {\r\n let r = rotated[j];\r\n if (c === r) {\r\n scramble = scramble.substring(0, i) + rotated[(j + rotation) % 4] + scramble.substring(i+1, scramble.length);\r\n }\r\n }\r\n }\r\n return scramble.replace(/^U./g, \"\").replace(/U.?$/g, \"\").trim();\r\n}", "function forceScrambleUpdate() {\n self.generateScramble();\n }", "function ramdomize(array) {\n var i, j, k;\n for (i = array.length - 1; i > 0; i--) {\n j = Math.floor(Math.random() * i);\n k = array[i];\n array[i] = array[j];\n array[j] = k;\n }\n}", "function shuffle (array) {\r\n var i = 0\r\n , j = 0\r\n , temp = null\r\n\r\n for (i = array.length - 1; i > 0; i -= 1) {\r\n j = Math.floor(Math.random() * (i + 1))\r\n temp = array[i]\r\n array[i] = array[j]\r\n array[j] = temp\r\n }\r\n }", "unscramble( scrambled ) {\n this.target = scrambled;\n console.log( this.target );\n\n for (var i=this.rules.length-1; i >= 0; i--) {\n var rule = this.rules[i];\n this.useRuleToScramble( rule, true );\n }\n return this.target;\n }", "shuffle(array) {\n for (let i = array.length - 1; i > 0; i--) {\n let j = Math.floor(Math.random() * (i + 1)); // случайный индекс от 0 до i\n\n [array[i], array[j]] = [array[j], array[i]];\n }\n }", "function shuffle(array) {\n\tfor (let i = array.length - 1; i > 0; i--) {\n\t let j = Math.floor(Math.random() * (i + 1));\n\t [array[i], array[j]] = [array[j], array[i]];\n\t}\n}", "function shuffle(array) {\n for (let i = array.length - 1; i > 0; i--) {\n let j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n }", "function shuffle(array) {\r\n for (let i = array.length - 1; i > 0; i--) {\r\n let j = Math.floor(Math.random() * (i + 1));\r\n [array[i], array[j]] = [array[j], array[i]];\r\n }\r\n}", "function shuffle(array) {\n var i, j, t;\n for (i = array.length - 1; i > 0; i--) {\n j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i\n t = array[i]; array[i] = array[j]; array[j] = t;\n }\n}", "function shuffle(array) {\n for (let i = array.length - 1; i > 0; i--) {\n let j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n}", "function shuffle(array) {\n for (let i = array.length - 1; i > 0; i--) {\n let j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n}", "function shuffle(array) {\n for (let i = array.length - 1; i > 0; i--) {\n let j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n}", "function shuffle(wordArray) {\n let currentIndex = wordArray.length, temporaryValue, randomIndex;//for this example = 4\n while (0 !== currentIndex) {\n randomIndex = Math.floor(Math.random() * currentIndex);\n currentIndex -= 1;\n temporaryValue = wordArray[currentIndex];\n wordArray[currentIndex] = wordArray[randomIndex];\n wordArray[randomIndex] = temporaryValue;\n }\n return wordArray;\n }", "function shuffle(array) {\n\n let currentIndex = array.length, temporaryValue, randomIndex;\n // While there remain elements to shuffle...\n while (0 !== currentIndex) {\n\n // Pick a remaining element...\n randomIndex = Math.floor(Math.random() * currentIndex);\n currentIndex -= 1;\n\n // And swap it with the current element.\n temporaryValue = array[currentIndex];\n array[currentIndex] = array[randomIndex];\n array[randomIndex] = temporaryValue;\n }\n\n // add slashes with every word\n let slashes = array.join(' / ');\n // make all words lowercase\n let lowerSlashes = slashes.toLowerCase()\n // console.log(typeof slashes)\n return '( ' + lowerSlashes + ' )'\n\n }", "function shuffle(a) {\n\tfor (let i = a.length; i; i--) {\n\t\tlet j = Math.floor(Math.random() * i);\n\t\t[a[i - 1], a[j]] = [a[j], a[i - 1]];\n\t}\n}", "function shuffle(a) {\n\tfor (let i = a.length; i; i--) {\n\t\tlet j = Math.floor(Math.random() * i);\n\t\t[a[i - 1], a[j]] = [a[j], a[i - 1]];\n\t}\n}", "function shuffle(a) {\n\tfor (let i = a.length; i; i--) {\n\t\tlet j = Math.floor(Math.random() * i);\n\t\t[a[i - 1], a[j]] = [a[j], a[i - 1]];\n\t}\n}", "function shuffle(array) {\n for (let i = array.length - 1; i > 0; i--) {\n let j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n}", "function shuffle(array) {\n for (let i = array.length - 1; i > 0; i--) {\n let j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n}", "function shuffle(array) {\n for (let i = array.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * i);\n const temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n}", "static shuffle(array) {\n var currentIndex = array.length, temporaryValue, randomIndex;\n while (currentIndex !== 0) {\n randomIndex = Math.floor(Math.random() * currentIndex);\n currentIndex -= 1;\n temporaryValue = array[currentIndex];\n array[currentIndex] = array[randomIndex];\n array[randomIndex] = temporaryValue;\n }\n return array;\n }", "function shuffle (array) {\r\n var i = 0\r\n , j = 0\r\n , temp = null\r\n\r\n for (i = array.length - 1; i > 0; i -= 1) {\r\n j = Math.floor(Math.random() * (i + 1))\r\n temp = array[i]\r\n array[i] = array[j]\r\n array[j] = temp\r\n }\r\n}" ]
[ "0.7952491", "0.722264", "0.6984794", "0.6961692", "0.6949615", "0.6908133", "0.681594", "0.67960477", "0.6733211", "0.658768", "0.65754473", "0.656906", "0.6533714", "0.65197945", "0.6506822", "0.64934915", "0.64804894", "0.645834", "0.645834", "0.645834", "0.6449667", "0.6447131", "0.6441504", "0.6441504", "0.6441504", "0.6434835", "0.6434835", "0.64288604", "0.6425803", "0.6424359" ]
0.7307965
1
find the (or one of them) smallest square who have A as a corner and B on a side
function findSquare (lineA, colA, lineB, colB) { // length of a side of that square let line, col; let dim = max(abs(lineA - lineB), abs(colA - colB)); if (lineB >= lineA) line = lineA; else line = lineA - dim; if (colB >= colA) col = colA; else col = colA - dim; return [line, col, dim + 1]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "minSquare() {\n var ind = -1;\n var min = L + 1;\n for (let i = 0; i < B; i++) {\n if (this.choices[i] != -1 && this.choices[i] < min) {\n min = this.choices[i];\n ind = i;\n }\n }\n return ind;\n }", "function getMinBox() {\n //get coordinates \n var coorX = coords.map(function(p) {\n return p.x\n });\n var coorY = coords.map(function(p) {\n return p.y\n });\n\n //find top left and bottom right corners \n var min_coords = {\n x: Math.min.apply(null, coorX),\n y: Math.min.apply(null, coorY)\n }\n var max_coords = {\n x: Math.max.apply(null, coorX),\n y: Math.max.apply(null, coorY)\n }\n\n //return as strucut \n return {\n min: min_coords,\n max: max_coords\n }\n}", "function getMinBox() {\n //get coordinates \n var coorX = coords.map(function(p) {\n return p.x\n });\n var coorY = coords.map(function(p) {\n return p.y\n });\n\n //find top left and bottom right corners \n var min_coords = {\n x: Math.min.apply(null, coorX),\n y: Math.min.apply(null, coorY)\n }\n var max_coords = {\n x: Math.max.apply(null, coorX),\n y: Math.max.apply(null, coorY)\n }\n\n //return as strucut \n return {\n min: min_coords,\n max: max_coords\n }\n}", "function minDistance(square, goal) {\n var horizDiff = Math.abs(goal.x - square.x);\n var vertDiff = Math.abs(goal.y - square.y);\n return Math.min(horizDiff, vertDiff);\n}", "function _scanWinSizeB(side) {\r\n var x, y, count;\r\n var startX, startY;\r\n // scan the left-bottom half until y == GRID_SIZE-1\r\n // only need scan to the last possible position\r\n for (y = GRID_SIZE - WIN_SIZE; y >= 0; --y) {\r\n x = 0;\r\n count = 0;\r\n for (var p = x, q = y; p < GRID_SIZE && q < GRID_SIZE; ++p, ++q) {\r\n if (positions[p][q].getValue() === side) {\r\n count++;\r\n if (count == 1) { // record the start position(x,y)\r\n startX = p; // we can reuse x BTW\r\n startY = q;\r\n } else if (count == WIN_SIZE) { // found WIN_SIZE link\r\n return positions[startX][startY];\r\n }\r\n } else {\r\n count = 0;\r\n }\r\n }\r\n }\r\n \r\n // scan the right-bottom half until x == GRID_SIZE-1\r\n // only need scan to the last possible position\r\n for (x = 1; x < GRID_SIZE-(WIN_SIZE-1); ++x) {\r\n y = 0;\r\n count = 0;\r\n for (var p = x, q = y; p < GRID_SIZE && q < GRID_SIZE; ++p, ++q) {\r\n if (positions[p][q].getValue() === side) {\r\n count++;\r\n if (count == 1) { // record the start position(x,y)\r\n startX = p;\r\n startY = q; // we can reuse y BTW\r\n } else if (count == WIN_SIZE) { // found WIN_SIZE link\r\n return positions[startX][startY];\r\n }\r\n } else {\r\n count = 0;\r\n }\r\n }\r\n }\r\n return null;\r\n }", "function squaresquare(a, b){\n\n a.left = a.x\n b.left = b.x\n a.right = a.x + a.width\n b.right = b.x + b.width\n a.top = a.y \n b.top = b.y\n a.bottom = a.y + a.height\n b.bottom = b.y + b.height\n\n\n\n if (a.left > b.right || a.top > b.bottom || \n a.right < b.left || a.bottom < b.top)\n {\n return false\n }\n else\n {\n return true\n }\n}", "function heuristic(a, b) {\n return dist(a.row, a.col, b.row, b.col);;\n}", "function solution(A) {\n const arr = A;\n const len = arr.length;\n let sum = 0;\n\n for (let i = 0; i < len; i++) {\n sum += arr[i];\n }\n\n let curLeft = 0;\n let curRight = 0;\n let lowest;\n for (let i = 0; i < len; i++) {\n curLeft += arr[i];\n curRight = sum - curLeft;\n const diff = Math.abs(curLeft - curRight);\n if (diff < lowest || lowest === undefined) {\n lowest = diff;\n }\n }\n\n return lowest;\n}", "function cobminRec(w,h){\n // first calculate the perimeter\n var p = 2*w + 2*h;\n\n var a = w*h\n\n //retruned both values\n retrun [p,a];\n}", "function bestSquareTiles(x, y, n) {\n //prevent div/0\n if (n === 0 || x === 0 || y === 0)\n return 0;\n var px = Math.ceil(Math.sqrt((n * x) / y));\n var sx = undefined;\n var sy = undefined;\n if (Math.floor((px * y) / x) * px < n) {\n sx = y / Math.ceil((px * y) / x);\n }\n else {\n sx = x / px;\n }\n var py = Math.ceil(Math.sqrt((n * y) / x));\n if (Math.floor((py * x) / y) * py < n) {\n sy = x / Math.ceil((x * py) / y);\n }\n else {\n sy = y / py;\n }\n var ret = Math.max(sx, sy);\n // console.log(\"kkkkkkkkkkkkkk ret\" + ret);\n return ret;\n}", "function _scanWinSizeS(side) {\r\n var x, y, count;\r\n var startX, startY;\r\n // scan the left-top half until y == GRID_SIZE-1\r\n // only need scan to the last possible position\r\n for (y = WIN_SIZE-1; y < GRID_SIZE; ++y) {\r\n x = 0;\r\n count = 0;\r\n for (var p = x, q = y; p < GRID_SIZE && q >= 0; ++p, --q) {\r\n if (positions[p][q].getValue() === side) {\r\n count++;\r\n if (count == 1) { // record the start position(x,y)\r\n startX = p; // we can reuse x BTW\r\n startY = q;\r\n } else if (count == WIN_SIZE) { // found WIN_SIZE link\r\n return positions[startX][startY];\r\n }\r\n } else {\r\n count = 0;\r\n }\r\n }\r\n }\r\n \r\n // scan the right-bottom half until x == GRID_SIZE-1\r\n // only need scan to the last possible position\r\n for (x = 1; x < GRID_SIZE-(WIN_SIZE-1); ++x) {\r\n y = GRID_SIZE-1;\r\n count = 0;\r\n for (var p = x, q = y; p < GRID_SIZE && q >= 0; ++p, --q) {\r\n if (positions[p][q].getValue() === side) {\r\n count++;\r\n if (count == 1) { // record the start position(x,y)\r\n startX = p;\r\n startY = q; // we can reuse y BTW\r\n } else if (count == WIN_SIZE) { // found WIN_SIZE link\r\n return positions[startX][startY];\r\n }\r\n } else {\r\n count = 0;\r\n }\r\n }\r\n }\r\n return null;\r\n }", "function tresureIsland2(grid) {\n\tif (grid == null || grid.length === 0) return false;\n\n\tlet queueStart = []; //all start points\n\tconst ROW = grid.length;\n\tconst directions = [\n\t\t[-1, 0],\n\t\t[1, 0],\n\t\t[0, 1],\n\t\t[0, -1]\n\t];\n\n\tlet min = 0;\n\n\t//fill queue with all starts\n\tgrid.forEach((row, r) => {\n\t\trow.forEach((col, c) => {\n\t\t\tif (grid[r][c] === 'S') {\n\t\t\t\tqueueStart.push([r, c]);\n\t\t\t}\n\t\t});\n\t});\n\n\twhile (queueStart.length) {\n\t\tmin++;\n\t\tlet len = queueStart.length;\n\t\tfor (let i = 0; i < len; i++) {\n\t\t\tlet [sr, sc] = queueStart.shift();\n\t\t\tfor (let [dr, dc] of directions) {\n\t\t\t\tlet r = sr + dr;\n\t\t\t\tlet c = sc + dc;\n\t\t\t\tif (r >= 0 && r < ROW && c >= 0 && c < grid[r].length) {\n\t\t\t\t\tif (grid[r][c] === 'X') {\n\t\t\t\t\t\treturn min;\n\t\t\t\t\t}\n\t\t\t\t\tif (grid[r][c] === 'O') {\n\t\t\t\t\t\tgrid[r][c] = 'D';\n\t\t\t\t\t\tqueueStart.push([r, c]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}", "function findMines() {\n for (let i = 0; i < numSquaresY; i++) {\n for (let j = 0; j < numSquaresX; j++) {\n board[i][j].calculateAdjacentMines();\n }\n }\n}", "function solution(A) {\n // write your code in JavaScript (Node.js 8.9.4)\n\n let left = 0;\n let right = A.reduce((acc, cur) => acc + cur);\n let min = null;\n\n for (let p = 1; p < A.length; p++) {\n left += A[p - 1];\n right -= A[p - 1];\n\n let temp = left - right;\n temp = temp < 0 ? -1 * temp : temp;\n\n if (min === null || temp < min) {\n min = temp;\n }\n }\n\n return min;\n}", "function csquareintsbetween (a, b) {\n return Math.floor(Math.sqrt(b)) - Math.ceil(Math.sqrt(a)) + 1;\n}", "function whichBox(whereRowY, whereColX) {\n let rowAdj, colAdj, boxRow, boxCol, box;\n\n // adjusting values to start at 1 not 0 do that the '(rowAdj % size) != 0' work properly\n rowAdj = (whereRowY).valueOf() + 1;\n colAdj = whereColX + 1;\n\n console.log(colAdj)\n\n // box row Y\n if ((rowAdj % size) != 0) {\n rowAdj += (rowAdj % size);\n }\n boxRow = rowAdj - size;\n\n // box column X\n if ((colAdj % size) != 0) {\n colAdj += (colAdj % size);\n }\n boxCol = colAdj / size;\n\n\n\n //which box\n box = boxRow + boxCol;\n\n return box;\n}", "static whichCorner(sideSize, idx) {\n let square = sideSize ** 2;\n\n if (idx < 0 || idx > square - 1) {\n return false; // out of scope\n }\n\n if (idx === 0) {\n // LEFT_TOP\n return 1;\n }\n\n if ((idx + 1) === sideSize) {\n // RIGHT_TOP\n return 2;\n }\n\n if ((idx + 1) === square) {\n // RIGHT_BOTTOM\n return 3;\n }\n\n if (idx === (square - sideSize)) {\n // LEFT_BOTTOM\n return 4;\n }\n\n return false;\n }", "getNearestTower(board, x, y, mine) {\n var towers_to_check = [];\n var result = [];\n if(mine == 0) {\n // get all towers on the board that are not mine\n for (let i = 0; i < board_size; i++) {\n for (let j = 0; j < board_size; j++ ) {\n if (board[i][j].tower == 1 && board[i][j].faction != this.faction) {\n if(j == x && i == y)\n continue;\n towers_to_check.push([j, i]);\n }\n }\n }\n } else {\n // i check just in my towers\n // is this how this works?\n for (let m = 0; m < this.towers.length; m++) {\n if(this.towers[m][0] == x && this.towers[m][1] == y)\n continue;\n towers_to_check.push(this.towers[m]);\n }\n\n }\n var min = 25;\n var new_x = 0;\n var new_y = 0;\n for (let i = 0; i < towers_to_check.length; i++) {\n let x1 = towers_to_check[i][0];\n let y1 = towers_to_check[i][1];\n let sum = Math.min(Math.abs(x - x1) + Math.abs(y - y1));\n if (sum < min) {\n min = sum;\n if (x1 == x) { //ox axis\n if(y == y1 ) {\n new_y = y;\n }\n if (y < y1 ) {\n new_y = y + 1;\n } else {\n new_y = y - 1;\n }\n new_x = x;\n } else if (y1 == y) { // on oy axis\n if (x < x1 ) {\n new_x = x + 1;\n } else {\n new_x = x - 1;\n }\n new_y = y;\n // // i check the 4 quadrants -> I am not sure here\n } else if ( x < x1 && y < y1) {\n new_x = x + 1;\n new_y = y + 1;\n } else if ( x < x1 && y > y1) {\n new_x = x + 1;\n new_y = y - 1;\n } else if ( x > x1 && y < y1) {\n new_x = x - 1;\n new_y = y + 1;\n } else if ( x > x1 && y > y1) {\n new_x = x - 1;\n new_y = y - 1;\n }\n }\n }\n result.push(new_x);\n result.push(new_y);\n result.push(min);\n return result;\n }", "calculateWinner(squares) {\n const lines = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [0, 3, 6],\n [1, 4, 7],\n [2, 5, 8],\n [0, 4, 8],\n [2, 4, 6],\n ];\n for (let i = 0; i < lines.length; i++) {\n const [a, b, c] = lines[i];\n if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {\n return lines[i];\n }\n }\n return null;\n}", "function winnerHorizontal(grid, row, lig) {\n if ((grid[row][lig] === grid[row + 1][lig]) && (grid[row][lig] === grid[row + 2][lig]) && (grid[row][lig] === grid[row + 3][lig])) {\n return grid[row][lig];\n } else {\n return NOBODY;\n }\n}", "function squareCorner(square, box) {\n var x = square.x,\n y = square.y,\n side = square.side;\n return ((box.x == x && box.y == y) || (box.x == x + side && box.y == y) || (box.x == x && box.y == y + side) || (box.x == x + side && box.y == y + side));\n}", "function calculateWinner(squares) {\r\n const lines = [\r\n [0, 1, 2],\r\n [3, 4, 5],\r\n [6, 7, 8],\r\n [0, 3, 6],\r\n [1, 4, 7],\r\n [2, 5, 8],\r\n [0, 4, 8],\r\n [2, 4, 6],\r\n ];\r\n for (let i = 0; i < lines.length; i++) {\r\n const [a, b, c] = lines[i];\r\n if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {\r\n return squares[a];\r\n }\r\n }\r\n return null;\r\n}", "calculateWinner(squares) {\r\n const lines = [\r\n [0, 1, 2],\r\n [3, 4, 5],\r\n [6, 7, 8],\r\n [0, 3, 6],\r\n [1, 4, 7],\r\n [2, 5, 8],\r\n [0, 4, 8],\r\n [2, 4, 6],\r\n ];\r\n for (let i = 0; i < lines.length; i++) {\r\n const [a, b, c] = lines[i];\r\n if (\r\n squares[a] &&\r\n squares[a] === squares[b] &&\r\n squares[a] === squares[c]\r\n ) {\r\n return squares[a];\r\n }\r\n }\r\n return null;\r\n }", "function sqInRect(l, w){\n if (l === w) {\n return null;\n };\n let tempArray = [l, w];\n let newArray = [];\n if (l > w) {\n tempArray = [w, l];\n };\n\n while(true) {\n while (tempArray[1] >= tempArray[0]) {\n newArray.push(tempArray[0]);\n let diff = tempArray[1] - tempArray[0];\n tempArray = [tempArray[0], diff];\n };\n\n if (tempArray[1] === 0) {\n return newArray;\n };\n tempArray = [tempArray[1], tempArray[0]];\n };\n}", "function calculate_snapping( intersection ){\n\tvar shortest = 65535; //shortest distance to a new square\n\tfor( move in possible_moves ){\n\t\tvar possible_x = possible_moves[ move ].x;\n\t\tvar possible_z = possible_moves[ move ].z;\n\n\t\tvar x_dist = board[ possible_x ][ possible_z ].position.x - intersection[ 0 ].point.x;\n\t\tvar z_dist = board[ possible_x ][ possible_z ].position.z - intersection[ 0 ].point.z;\n\n\t\tvar distance = Math.sqrt( x_dist*x_dist + z_dist*z_dist);\n\t\tvar candidate_x;\n\t\tvar candidate_z;\n\n\t\tif( distance < shortest ){\n\t\t\tshortest = distance;\n\t\t\tcandidate_x = possible_x;\n\t\t\tcandidate_z = possible_z;\n\t\t}\n\n\t\tsnap_to( candidate_x, candidate_z );\n\t}\n}", "function s(grid) {\n const directions = [\n [1, 0],\n [0, 1],\n [-1, 0],\n [0, -1],\n ];\n let max = 0;\n const set = new Set();\n for (let r = 0; r < grid.length; r++) {\n for (let c = 0; c < grid[r].length; c++) {\n if (grid[r][c] === 1 && !set.has(`${r} ${c}`)) {\n set.add(`${r} ${c}`);\n max = Math.max(max, helper(r, c));\n }\n }\n }\n return max;\n\n function helper(r, c) {\n if (!grid[r] || !grid[r][c]) return 0;\n let size = 1;\n for (let [r1, c1] of directions) {\n if (!set.has(`${r + r1} ${c + c1}`)) {\n set.add(`${r + r1} ${c + c1}`);\n size += helper(r + r1, c + c1);\n }\n }\n return size;\n }\n}", "function findSmallest(a, b, c){\n if (a < b && a < c){\n return a;\n } else if (b < a && b < c) {\n return b;\n} else {\n return c;\n }\n}", "function determineWinner(squares) {\n const lines = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [0, 3, 6],\n [1, 4, 7],\n [2, 5, 8],\n [0, 4, 8],\n [2, 4, 6],\n ];\n for (let i = 0; i < lines.length; i++) {\n const [a, b, c] = lines[i];\n if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {\n return squares[a];\n }\n }\n return null;\n}", "function getNearestCell(x, y, cells) {\r\n var min = Infinity;\r\n var result;\r\n $.each(cells, function(index, cell) { \r\n var d = distance(x, y, cell.center_x, cell.center_y);\r\n // Update minimum.\r\n if (d < min) {\r\n min = d;\r\n result = cell;\r\n }\r\n });\r\n return result;\r\n}", "function getClosestCorner(pt1, pt2) {\n var dx = pt2[0] - pt1[0];\n var m = (pt2[1] - pt1[1]) / dx;\n var b = (pt1[1] * pt2[0] - pt2[1] * pt1[0]) / dx;\n if (b > 0) return [m > 0 ? xEdge0 : xEdge1, yEdge1];else return [m > 0 ? xEdge1 : xEdge0, yEdge0];\n }" ]
[ "0.69085807", "0.6315294", "0.6315294", "0.6236337", "0.6224419", "0.6206841", "0.612851", "0.6127941", "0.6090618", "0.60611093", "0.5930872", "0.58946407", "0.58901054", "0.58175117", "0.5788505", "0.577618", "0.5757049", "0.573049", "0.5715967", "0.57059723", "0.5675279", "0.5667267", "0.56563485", "0.56456953", "0.56146896", "0.560322", "0.5595735", "0.5591653", "0.5577458", "0.55733556" ]
0.6543187
1
We want to approximate the length of a curve representing a function y = f(x) with a<= x <= b. First, we split the interval [a, b] into n subintervals with widths h1, h2, ... , hn by defining points x1, x2 , ... , xn1 between a and b. This defines points P0, P1, P2, ... , Pn on the curve whose xcoordinates are a, x1, x2 , ... , xn1, b and ycoordinates f(a), f(x1), ..., f(xn1), f(b) . By connecting these points, we obtain a polygonal path approximating the curve. Our task is to approximate the length of a parabolic arc representing the curve y = x x with x in the interval [0, 1]. We will take a common step h between the points xi: h1, h2, ... , hn = h = 1/n and we will consider the points P0, P1, P2, ... , Pn on the curve. The coordinates of each Pi are (xi, yi = xi xi). The function len_curve (or similar in other languages) takes n as parameter (number of subintervals) and returns the length of the curve. You can truncate it to 9 decimal places. alternative text
function lenCurve(n) { function seglg() { return Math.sqrt(Math.pow(n, 2) + 4 * Math.pow(k, 2) + 4 * k + 1) / Math.pow(n, 2); } var s = 0; for (var k = 0; k < n; k++) { s += seglg(); } return Math.floor(s * 1e9) / 1e9; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function curveLength({\n fun,\n curveStartParam,\n curveEndParam,\n\n //optionals:\n funIsAVector, //true for t |-> [x,y], false for y=f(x) \n INTEGRATION_POINTS_LIM,\n calculationAccuracy,\n STARTING_EXPONENT_FOR_2,\n SAFETY_INTERACTIONS_LIM,\n }){\n\n //value 10 gives limit = 2^10, possibly accuracy = 0.001\n //SAFETY_INTERACTIONS_LIM = 25; //experiment: 25 seems ~ 180 Meg, accuracy ~ 10^-11\n //SAFETY_INTERACTIONS_LIM = 23; //23 must be safe, 30 - danger\n SAFETY_INTERACTIONS_LIM = SAFETY_INTERACTIONS_LIM || 20; //30 - danger\n\n INTEGRATION_POINTS_LIM = INTEGRATION_POINTS_LIM || 1000;\n calculationAccuracy = calculationAccuracy || 0.000000001;\n STARTING_EXPONENT_FOR_2 = STARTING_EXPONENT_FOR_2 || 4;\n\n\n var expo = STARTING_EXPONENT_FOR_2;\n var basePointsCount = mat.powersOf2[ expo ];\n basePoints = [];\n funPoints = [];\n var currentBasePoints = basePoints[ expo ] = [];\n funPoints[ expo ] = [];\n var currentStep = ( curveEndParam - curveStartParam ) / basePointsCount;\n\n for( var it=0; it<=basePointsCount; it++ ) {\n currentBasePoints[ it ] = curveStartParam + currentStep * it;\n var tt = currentBasePoints[ it ];\n var funPoint = fun( currentBasePoints[ it ] );\n if( !funIsAVector ) {\n funPoint = [ tt, funPoint ];\n }\n funPoints[ expo ][ it ] = funPoint;\n }\n var prevLen = calculates_curvePoints2chordsSum( funPoints[ expo ] );\n\n\n function calculates_curvePoints2chordsSum( curvePoints )\n {\n var lenSum = 0;\n var curPLen = curvePoints.length;\n for( var it=1; it<curPLen; it++ ) {\n var prevP = curvePoints[ it-1 ];\n var curP = curvePoints[ it ];\n var dx = curP[0]-prevP[0];\n var dy = curP[1]-prevP[1];\n lenSum += Math.sqrt( dx*dx + dy*dy );\n }\n return lenSum;\n }\n\n for( var expo = STARTING_EXPONENT_FOR_2 + 1;\n expo < SAFETY_INTERACTIONS_LIM; expo++\n ) {\n var prevPC = mat.powersOf2[ expo-1 ];\n var prevBP = basePoints[ expo-1 ];\n var prevFP = funPoints[ expo-1 ];\n var currentBasePoints = basePoints[ expo ] = [];\n var funP = funPoints[ expo ] = [];\n\n for( var ip = 0; ip <= prevPC; ip++ ) {\n var it = ip*2;\n var fP = funP[ it ] = prevFP[ ip ];\n var tLeft = currentBasePoints[ it ] = prevBP[ ip ];\n var tRight = prevBP[ ip + 1 ];\n\n if( ip === prevPC ) break;\n var tMiddle = currentBasePoints[ it + 1 ] =\n ( tLeft + tRight ) * 0.5;\n var funPoint = fun( tMiddle );\n if( !funIsAVector ) {\n funPoint = [ tMiddle, funPoint ];\n }\n funP[ it + 1 ] = funPoint;\n }\n var newLen = calculates_curvePoints2chordsSum( funP );\n\n var reachedAccuracy = Math.abs( prevLen - newLen );\n if( calculationAccuracy > reachedAccuracy ) {\n /*\n ccc( 'reached accuracy=' + reachedAccuracy +\n 'value=', newLen, 'expo=', expo, 'memory~' + funP.length\n );\n */\n return newLen;\n }\n prevLen = newLen;\n }\n\n /*\n ccc( 'missed accuracy: reached only this =' + reachedAccuracy +\n 'value=', newLen, 'expo=', expo, 'memory~' + funP.length\n );\n */\n\n //we did not reach preset accuracy, so do return\n //what we have:\n return prevLen;\n }", "totalLength(){\n\n let clen = 0;\n let pts;\n\n for(let i = 0; i < this.nCurves; i++){\n let idx = i*2;\n pts = [ p5.Vector.add(this.cpts[idx], this.cpts[idx+1]).mult(0.5),\n this.cpts[idx+1],\n this.cpts[idx+2],\n p5.Vector.add(this.cpts[idx+2], this.cpts[idx+3]).mult(0.5)\n ];\n \n clen += this.segmentLength(pts);\n }\n\n return clen;\n\n }", "function len (p1, p2) {\n return Math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y))\n }", "function calculate_the_length(x1,y1,x2,y2){\n let length_AB = Math.sqrt ((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));\n console.log(length_AB)\n}", "function PathLength(points) {\n let length = 0.0;\n for (let i = 1; i < points.length - 1; i += 1) {\n length += EuclideanDistance(points[i - 1], points[i]);\n }\n return length;\n }", "function lenFromRATri(hyp, len) {\n return Math.pow(Math.pow(hyp, 2) - Math.pow(len, 2), 0.5);\n}", "function computeLineLength( x1, y1, x2, y2 ) {\n let xdiff = subtract( x2, x1 );\n let ydiff = subtract( y2, y1 );\n let total = add( square( xdiff ), square( ydiff ) );\n return Math.sqrt( total );\n}", "function getLength(a, b) {\n return Math.sqrt((Math.pow(b[0] - a[0], 2) + Math.pow(b[1] - a[1], 2) + Math.pow(b[2] - a[2], 2)));\n}", "function curveIncrement(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y, t) {\n\tvar v1x = -3*p0x + 9*p1x - 9*p2x + 3*p3x;\n\tvar v1y = -3*p0y + 9*p1y - 9*p2y + 3*p3y;\n\tvar v2x = 6*p0x - 12*p1x + 6*p2x;\n\tvar v2y = 6*p0y - 12*p1y + 6*p2y;\n\tvar v3x = -3*p0x + 3*p1x;\n\tvar v3y = -3*p0y + 3*p1y;\n\n\tvar x = t*t*v1x + t*v2x + v3x;\n\tvar y = t*t*v1y + t*v2y + v3y;\n\tvar length = Math.sqrt(x*x + y*y);\n\treturn length;\n}", "function chordLength(radius, angle) {\n return 2.0 * radius * Math.sin(angle / 2.0);\n}", "function lineLength(x, y, x0, y0){\n return Math.sqrt((x -= x0) * x + (y -= y0) * y);\n}", "function chord_length_parameterize(points, first, last) {\n var u = [0];\n for (var i = first + 1; i <= last; i++) {\n u[i - first] = u[i - first - 1] + distance(points[i], points[i - 1]);\n }\n for (var i = 1, m = last - first; i <= m; i++) u[i] /= u[m];\n return u;\n }", "function getLineLength(x1, y1, x2, y2) {\n var res = Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));\n return res;\n}", "function getLength(time, result) {\n // Get the end position from the polyLine's callback.\n var endPoint = redLine.polyline.positions.getValue(time, result)[1];\n endCartographic = Cesium.Cartographic.fromCartesian(endPoint);\n\n geodesic.setEndPoints(startCartographic, endCartographic);\n var lengthInMeters = Math.round(geodesic.surfaceDistance);\n return (lengthInMeters / 1000).toFixed(1) + \" km\";\n}", "function describeArcs(p,r,start,end, totalLength){\n\t\t\tvar paragraphFraction = p.words.length/totalLength;\n\t\t\tvar paragraphArea = Math.PI * r * r * paragraphFraction;\n\n\t\t\t// These will get incremented\n\t\t\tvar rPos = 0;\n\t\t\tvar currentVal = 0;\n\t\t\t\n\t\t\t// describe each ring\n\t\t\treturn function(s){\n\t\t\t\tvar innerRadius = rPos;\n\t\t\t\t\n\t\t\t\tcurrentVal += s.words.length;\n\t\t\t\tvar currentArea = paragraphArea * (currentVal/p.words.length);\n\t\t\t\trPos = Math.sqrt((currentArea*(1/paragraphFraction))/Math.PI);\n\n\t\t\t\touterRadius = rPos;\n\t\t\t\treturn {\n\t\t\t\t\t'innerRadius':innerRadius,\n\t\t\t\t\t'outerRadius':outerRadius,\n\t\t\t\t\t'startAngle':start,\n\t\t\t\t\t'endAngle':end,\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function calculateArea(f, startX, endX) {\n return trapeziumRule(0.1, 2000, f, startX, endX);\n}", "function rectangles(f, a, b, n, pos = \"l\"){\r\n //f is the function, [a,b] is the interval, n is the number of strips, and pos is which part of the rectangle should touch the curve\r\n\r\n fill(0, 0, 255, 200);\r\n stroke(0, 0, 0, 50);\r\n let w = (b-a)/n; //Width of rectangles\r\n let s = 0; // Sum variable\r\n\r\n let delta = 0; //This determines what part of the curve on the interval from xi to xi+1 will be the height of the rectangle\r\n if(pos == \"l\"){\r\n delta = 0;\r\n } else if(pos == \"m\"){\r\n delta = w/2;\r\n } else if (pos == \"r\"){\r\n delta = w;\r\n }\r\n\r\n for(let i = 0; i < n; i++){\r\n //Note we do up to i = n - 1 because the final rectangle will have its right side on x = b\r\n let xi = a + i * w;\r\n s += f(xi + delta)\r\n rect(xi * sclx, -f(xi + delta) * scly, w * sclx, f(xi + delta) * scly); //Negative height for rectangle means we want it to be above the given corner\r\n }\r\n return s * w;\r\n}", "function polypoint(w, h, sides, steps) {\n\n let centerX, centerY, lengthX, lengthY;\n let d, endpoint\n\n // find center point\n centerX = ( h/2 );\n centerY = ( w/2 );\n lengthX = (centerX-(h%steps) );\n lengthY = (centerY-(w%steps) );\n stepX = lengthX/steps\n stepY = lengthY/steps\n //_______ find end points_______\n // d = (2*pi/side) => d = ( 2*(Math.PI/side) )\n // will return the angle for\n d = angles(sides)\n // find the coords for each one. and return them as a tuple array to 2 decimals\n endpoints= new Array(sides).fill([])\n data = new Object\n\n for (let i = 0; i < sides; i++) {\n\n data[`_${i}`]={\n x:[Math.round( (lengthX*Math.cos(d*i)) +centerX)],\n y:[Math.round( (lengthY*Math.sin(d*i)) +centerY)]\n }\n\n endpoints[i] = [\n Math.round( (lengthX*Math.cos(d*i)) +centerX),\n Math.round( (lengthY*Math.sin(d*i)) +centerY)\n ];\n }\n endpoints.reverse()\n console.log(`endpoints ${endpoints}`.red);\n console.log(`data`.red, data);\n console.log(`variables lengthX ${lengthX}, lengthY ${lengthY}`.blue);\n console.log(`variables centerX ${centerX}, centerY ${centerY}`.blue);\n\n // there are steps involving changing it to a SVG coord system\n\n // create the step arrays.\n // find step length\nconsole.log(\"endpoints\".blue,endpoints);\n for (let i = 0; i < endpoints.length; i++) {\n for (let j = 1; j < sides; j++) {\n if (centerX < endpoints[i][0]) {//\n\n endpoints[i].push(centerX,endpoints[i][1]-j*stepX)\n\n }else if (centerX > endpoints[i][0]) {//\n\n endpoints[i].push(centerX,endpoints[i][1]+j*stepX)\n\n }else if (centerX == endpoints[i][0] ) {\n\n endpoints[i].push(endpoints[i][0]+j*stepX,centerX)\n\n }else if (centerY < endpoints[i][1]) {\n\n endpoints[i].push(endpoints[i][1]-j*stepY,centerY)\n\n }\n else if (centerY > endpoints[i][1]) {\n\n endpoints[i].push(endpoints[i][1]+j*stepY,centerY)\n\n }else if (centerY == endpoints[i][1] ) {\n\n endpoints[i].push(endpoints[i][1]+j*stepY,centerY)\n\n }\n }\n }\n console.log(\"endpoints\".green,endpoints);\n for (let i = 0; i < endpoints.length; i++) {\n if (i%2 == 0) {// reverse in pairs\n endpoints[i].reverse()\n }\n }\n console.log(\"endpoints\".green,endpoints);\n /*\n\n console.log(`endpoints`.red,endpoints );\n console.log(`variables lengthX ${lengthX}, lengthY ${lengthY}`.blue);\n console.log(`variables centerX ${centerX}, centerY ${centerY}`.blue);\n\n*/\n\n/*\n{\n _1:{ x:[1,2,4,5],y:[1,2,3,4] },\n _2:{ x:[1,2,4,5],y:[1,2,3,4] },\n _3:{ x:[1,2,4,5],y:[1,2,3,4] },\n _4:{ x:[1,2,4,5],y:[1,2,3,4] }\n}\n*/\n\n\n console.log(\n `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${w}px\" height=\"${h}\" viewbox=\"0 0 ${w} ${h}\">\n <g class=\"polypoint\" id=\"_${sides}_${steps}\">`.green\n +\n `<polygon points=\"${endpoints}\" />`.green\n +\n `</g>\n </svg>`.green);\n}", "function polygonLength(vertices){\n var i = -1,\n n = vertices.length,\n b = vertices[n - 1],\n xa,\n ya,\n xb = b[0],\n yb = b[1],\n perimeter = 0;\n\n while (++i < n) {\n xa = xb;\n ya = yb;\n b = vertices[i];\n xb = b[0];\n yb = b[1];\n xa -= xb;\n ya -= yb;\n perimeter += Math.sqrt(xa * xa + ya * ya);\n }\n\n return perimeter;\n }", "function computeLength(path) {\n path = common.convertToPositionArray(path);\n if (path.length < 2) {\n return 0;\n }\n var length = 0;\n var prev = path[0];\n var prevLat = toRadians(prev.lat);\n var prevLng = toRadians(prev.lng);\n path.forEach(function (point) {\n var lat = toRadians(point.lat);\n var lng = toRadians(point.lng);\n length += distanceRadians(prevLat, prevLng, lat, lng);\n prevLat = lat;\n prevLng = lng;\n });\n return length * EARTH_RADIUS;\n}", "function f(t) {\n\t\t\t\t\tvar count = getIterations(start, t);\n\t\t\t\t\tif (start < t) {\n\t\t\t\t\t\tlen += Numerical.integrate(ds, start, t, count);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlen -= Numerical.integrate(ds, t, start, count);\n\t\t\t\t\t}\n\t\t\t\t\tstart = t;\n\t\t\t\t\treturn len - length;\n\t\t\t\t}", "function getInnerPctCalcFunction(arcs, shapes) {\n var calcSegLen = arcs.isPlanar() ? geom.distance2D : geom.greatCircleDistance;\n var arcIndex = new ArcTopologyIndex(arcs, shapes);\n var outerLen, innerLen, arcLen; // temp variables\n\n return function(shp) {\n outerLen = 0;\n innerLen = 0;\n if (shp) shp.forEach(procRing);\n return innerLen > 0 ? innerLen / (innerLen + outerLen) : 0;\n };\n\n function procRing(ids) {\n ids.forEach(procArc);\n }\n\n function procArc(id) {\n arcLen = 0;\n arcs.forEachArcSegment(id, addSegLen);\n if (arcIndex.isInnerArc(id)) {\n innerLen += arcLen;\n } else {\n outerLen += arcLen;\n }\n }\n\n function addSegLen(i, j, xx, yy) {\n arcLen += calcSegLen(xx[i], yy[i], xx[j], yy[j]);\n }\n }", "calculateEndpoints(head = this.head, tail = this.tail) {\n const curve = new Curve(head, this.controlPt, tail);\n const incrementsArray = [0.001, 0.005, 0.01, 0.05];\n let increment = incrementsArray.pop();\n let t = 0;\n // let iterations = 0;\n while (increment && t < 0.5) {\n // iterations++;\n const pt = curve.bezier(t);\n if (this.tail.contains(pt)) {\n t += increment;\n } else {\n t -= increment;\n increment = incrementsArray.pop();\n t += increment || 0;\n }\n }\n // console.log('itertions: ' + iterations);\n this.endPt = curve.bezier(t);\n this.startPt = curve.bezier(1 - t);\n }", "getLineLengthBetweenPoints (x, y, x0, y0){\n return Math.sqrt((x -= x0) * x + (y -= y0) * y);\n }", "getCurveLengths() {\n\n\t\t// We use cache values if curves and cache array are same length\n\n\t\tif ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {\n\n\t\t\treturn this.cacheLengths;\n\n\t\t}\n\n\t\t// Get length of sub-curve\n\t\t// Push sums into cached array\n\n\t\tconst lengths = [];\n\t\tlet sums = 0;\n\n\t\tfor ( let i = 0, l = this.curves.length; i < l; i ++ ) {\n\n\t\t\tsums += this.curves[ i ].getLength();\n\t\t\tlengths.push( sums );\n\n\t\t}\n\n\t\tthis.cacheLengths = lengths;\n\n\t\treturn lengths;\n\n\t}", "function pathLength(path) {\n var i, sum = 0, a, b, dx, dy;\n for (i = 1; i < path.length; ++i) {\n a = path[i - 1];\n b = path[i];\n dx = a[0] - b[0];\n dy = a[1] - b[1];\n sum += Math.sqrt(dx * dx + dy * dy);\n }\n return sum;\n}", "function getLength(q){\n h = 1 / 128;\n var hh = h * 2;\n var m = [q[3][0] - q[0][0] + 3 * (q[1][0] - q[2][0]),\n q[0][0] - 2 * q[1][0] + q[2][0],\n q[1][0] - q[0][0]];\n var n = [q[3][1] - q[0][1] + 3 * (q[1][1] - q[2][1]),\n q[0][1] - 2 * q[1][1] + q[2][1],\n q[1][1] - q[0][1]];\n var k = [ m[0] * m[0] + n[0] * n[0],\n 4 * (m[0] * m[1] + n[0] * n[1]),\n 2 * ((m[0] * m[2] + n[0] * n[2]) + 2 * (m[1] * m[1] + n[1] * n[1])),\n 4 * (m[1] * m[2] + n[1] * n[2]), m[2] * m[2] + n[2] * n[2] ];\n var fc = function(t, k){\n return Math.sqrt(t * (t * (t * (t * k[0] + k[1]) + k[2]) + k[3]) + k[4]) || 0 };\n var sm = (fc(0, k) - fc(1, k)) / 2;\n for(var t = h; t < 1; t += hh) sm += 2 * fc(t, k) + fc(t + h, k);\n return sm * hh;\n}", "function polyArea(points){\n var p1,p2;\n for(var area=0,len=points.length,i=0;i<len;++i){\n p1 = points[i];\n p2 = points[(i-1+len)%len]; // Previous point, with wraparound\n area += (p2.x+p1.x) * (p2.y-p1.y);\n }\n return Math.abs(area/2);\n }", "getLength() {\n\n\t\tconst lens = this.getCurveLengths();\n\t\treturn lens[ lens.length - 1 ];\n\n\t}", "function rectangleRotation(a, b) {\n let count = 0;\n let midright = a / 2 / Math.sqrt(2);\n let midleft = -1 * midright;\n let x = b / 2 / Math.sqrt(2);\n let p1 = [midleft - x, midleft + x];\n let p2 = [midleft + x, midleft - x];\n let p3 = [midright - x, midright + x];\n let p4 = [midright + x, midright - x];\n let startx = Math.ceil(p1[0]);\n let endx = Math.floor(p4[0]);\n for (let i = startx; i <= endx; i++) {\n if (a > b) {\n if (i <= p2[0]) {\n count +=\n Math.floor(getyvaluefromline(p1, i, 1)) -\n Math.ceil(getyvaluefromline(p1, i, -1)) +\n 1;\n } else if (i > p2[0] && i <= p3[0]) {\n count +=\n Math.floor(getyvaluefromline(p1, i, 1)) -\n Math.ceil(getyvaluefromline(p2, i, 1)) +\n 1;\n } else {\n count +=\n Math.floor(getyvaluefromline(p3, i, -1)) -\n Math.ceil(getyvaluefromline(p2, i, 1)) +\n 1;\n }\n } else {\n if (i <= p3[0]) {\n count +=\n Math.floor(getyvaluefromline(p1, i, 1)) -\n Math.ceil(getyvaluefromline(p1, i, -1)) +\n 1;\n } else if (i > p3[0] && i <= p2[0]) {\n count +=\n Math.floor(getyvaluefromline(p3, i, -1)) -\n Math.ceil(getyvaluefromline(p1, i, -1)) +\n 1;\n } else {\n count +=\n Math.floor(getyvaluefromline(p3, i, -1)) -\n Math.ceil(getyvaluefromline(p2, i, 1)) +\n 1;\n }\n }\n }\n return count;\n}" ]
[ "0.6769427", "0.58905506", "0.5680087", "0.56241846", "0.5448378", "0.54405534", "0.5429641", "0.5369592", "0.53184587", "0.5288144", "0.5247235", "0.5210314", "0.5191495", "0.5182685", "0.5181171", "0.51801234", "0.5155166", "0.509476", "0.50758535", "0.5073273", "0.50525904", "0.50503427", "0.50421834", "0.5035627", "0.4988329", "0.49464884", "0.4919459", "0.49177265", "0.49122578", "0.48940995" ]
0.6514496
1
Calculates the increment values for R, G, and B using distance, fps, and duration. This calculation can be made in many different ways.
function calculateIncrement(distanceArray, fps, duration) { var fps = fps || 30; var duration = duration || 1; var increment = []; for (var i = 0; i < distanceArray.length; i++) { var incr = Math.abs(Math.floor(distanceArray[i] / (fps * duration))); if (incr == 0) { incr = 1; } increment.push(incr); } return increment; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function calculateIncrement(distanceArray, fps, duration) {\n var fps\t\t\t= fps || 30;\n var duration\t= duration || 1;\n var increment\t= [];\n for (var i = 0; i < distanceArray.length; i++) {\n var incr = Math.abs(Math.floor(distanceArray[i] / (fps * duration)));\n if (incr == 0) {\n incr = 1;\n }\n increment.push(incr);\n }\n return increment;\n }", "_calcDimentions() {\n this._props.time = this._props.duration + this._props.delay;\n this._props.repeatTime = this._props.time * (this._props.repeat + 1);\n }", "function distanceNextFrame(a, b) {\r\n return Math.sqrt((a.x + a.dx - b.x - b.dx)**2 + (a.y + a.dy - b.y - b.dy)**2) - a.radius - b.radius;\r\n}", "calculateFrame() {\n const nowTime = (new Date()).getTime();\n this.tick += 1;\n if (nowTime - this.beforeTime >= 1000) {\n console.log(`fps: ${this.tick}`);\n this.tick = 0;\n this.beforeTime = nowTime;\n }\n }", "_incrementFrame() {\n this._elapsedFrameCount += 1;\n }", "function compute_fps() {\n let counter_element = document.querySelector(\"#fps-counter\");\n if (counter_element != null) {\n counter_element.innerText = \"FPS: \" + g_frames_since_last_fps_count;\n }\n g_frames_since_last_fps_count = 0;\n}", "distance() {\n return this.speed * this.duration() / 3600000;\n }", "function update() {\n if (get() - lastFPS > 1000) {\n this.fps = fpsCounter;\n fpsCounter = 0; // Reset the FPS counter\n lastFPS += 1000; // Add one second\n }\n fpsCounter++;\n\n let time = get();\n let deltaTime = (time - lastFrame);\n lastFrame = time;\n if (!(deltaTime >= time)) {\n this.delta = deltaTime;\n }\n }", "function getFps(){\n\tfps++;\n\tif(Date.now() - lastTime >= 1000){\n\t\tfpsCounter.innerHTML = fps;\n\t\tfps = 0;\n\t\tlastTime = Date.now(); \n\t}\n}", "updateR() {\n if (this.lastRUpdate==0 || globalUpdateCount - this.lastRUpdate >= DAY_LENGTH) {\n let pts = this.fields.map(f => f.pts).reduce((acc, pts) => acc.concat(pts), [])\n pts.push(...this.sender.objs.map(o => o.point))\n \n let nInfectious = 0\n const val = pts\n .map(pt => {\n if (pt.isInfectious()) {\n nInfectious += 1\n const timeInfectious = globalUpdateCount - pt.lastStatusUpdate + (pt.status == Point.INFECTIOUS2) ? Point.infectious1Interval : 0\n if (timeInfectious>0) {\n const timeRemaining = Point.infectious2Interval + Point.infectious1Interval - timeInfectious\n return pt.nInfected/timeInfectious*timeRemaining // estimated infections over duration of illness\n } else return 0\n } else return 0\n })\n .reduce((sum, ei) => sum + ei)\n \n if (nInfectious>0) {\n this.rVal = val/nInfectious\n this.rMax = this.rMax < this.rVal ? this.rVal : this.rMax\n } else this.rVal = 0\n this.lastRUpdate = globalUpdateCount\n }\n }", "function animation_frame() {\n var datalen = animationState.order.length,\n styles = animationState.styleArrays,\n curTime = Date.now(), genTime, updateTime,\n position, i, idx, p;\n timeRecords.frames.push(curTime);\n animationState.raf = null;\n position = ((curTime - animationState.startTime) / animationState.duration) % 1;\n if (position < 0) {\n position += 1;\n }\n animationState.position = position;\n\n for (idx = 0; idx < datalen; idx += 1) {\n i = animationState.order[idx];\n p = idx / datalen + position;\n if (p > 1) {\n p -= 1;\n }\n styles.p[i] = p;\n }\n if (animationStyles.fill) {\n for (i = 0; i < datalen; i += 1) {\n styles.fill[i] = styles.p[i] >= 0.1 ? false : true;\n }\n }\n if (animationStyles.fillColor) {\n for (i = 0; i < datalen; i += 1) {\n p = styles.p[i];\n if (p >= 0.1) {\n styles.fillColor[i].r = 0;\n styles.fillColor[i].g = 0;\n styles.fillColor[i].b = 0;\n } else {\n styles.fillColor[i].r = p * 10;\n styles.fillColor[i].g = p * 8.39;\n styles.fillColor[i].b = p * 4.39;\n }\n }\n }\n if (animationStyles.fillOpacity) {\n for (i = 0; i < datalen; i += 1) {\n p = styles.p[i];\n styles.fillOpacity[i] = p >= 0.1 ? 0 : 1.0 - p * 10; // 1 - 0\n }\n }\n if (animationStyles.radius) {\n for (i = 0; i < datalen; i += 1) {\n p = styles.p[i];\n styles.radius[i] = p >= 0.1 ? 0 : 2 + 100 * p; // 2 - 12\n }\n }\n if (animationStyles.stroke) {\n for (i = 0; i < datalen; i += 1) {\n styles.stroke[i] = styles.p[i] >= 0.1 ? false : true;\n }\n }\n if (animationStyles.strokeColor) {\n for (i = 0; i < datalen; i += 1) {\n p = styles.p[i];\n if (p >= 0.1) {\n styles.strokeColor[i].r = 0;\n styles.strokeColor[i].g = 0;\n styles.strokeColor[i].b = 0;\n } else {\n styles.strokeColor[i].r = p * 8.51;\n styles.strokeColor[i].g = p * 6.04;\n styles.strokeColor[i].b = 0;\n }\n }\n }\n if (animationStyles.strokeOpacity) {\n for (i = 0; i < datalen; i += 1) {\n p = styles.p[i];\n styles.strokeOpacity[i] = p >= 0.1 ? 0 : 1.0 - p * p * 100; // (1 - 0) ^ 2\n }\n }\n if (animationStyles.strokeWidth) {\n for (i = 0; i < datalen; i += 1) {\n p = styles.p[i];\n styles.strokeWidth[i] = p >= 0.1 ? 0 : 3 - 30 * p; // 3 - 0\n }\n }\n var updateStyles = {};\n $.each(animationStyles, function (key, use) {\n if (use) {\n updateStyles[key] = styles[key];\n }\n });\n genTime = Date.now();\n pointFeature.updateStyleFromArray(updateStyles, null, true);\n updateTime = Date.now();\n timeRecords.generate.push(genTime - curTime);\n timeRecords.update.push(updateTime - genTime);\n show_framerate();\n if (animationState.mode === 'play') {\n animationState.raf = window.requestAnimationFrame(animation_frame);\n }\n }", "constructor(p, data, startHrs, startMins, am, width, height, fogTimes) {\n this.p = p;\n this.baseTimeMinutes = timeInMins(startHrs, startMins);\n this.ampm = am;\n this.data = data;\n this.fogTimes = fogTimes;\n\n /**\n * ANIMATION TIME CONSTANTS\n */\n /* Canvas will refresh 60 times a second */\n this.fRate = 60;\n /* A 'minute' in the animation will last 100 frames. */\n this.framesPerMin = 100;\n /** The length of this animation, in minutes. \n * Based on latest departure time of any visitor in the data array.\n * Add 5 to allow time for the latest departure to exit the screen\n * before restarting the animation. */\n this.durationInMins = 5 + getLatestDeparture(data);\n console.log(this.durationInMins);\n\n /**\n * ANIMATION LIFECYCLE STATE\n * Reset at the start of every animation\n */\n this.frameCount = 0;\n\n /**\n * MINUTE-BY-MINUTE STATE\n * Updated every minute for visitors within that minute\n */\n /* Array of objects that have x;N, y;N, and data:VisitorData fields,\n where VisitorData is {type:{r|c|w}, dir{up|down}, arrival:Minute, [departure:Minute]} */\n this.activeVisitors = [];\n // Shallow copy of data that can be mutated\n this.waitingVisitors = this.data.slice();\n /* Number of frames that elapse between each visitor in the current minute */\n this.framesPerVisitor;\n /* Array of VisitorData objects, the visitors that will be added\n to the animation during the current minute */\n this.visitorsInMin = [];\n\n /**\n * DRAWING (size + color) CONSTANTS\n * Known / given constants,\n * and dynamically calculated constants.\n */\n this.myWidth = width; // should be windowWidth when constructed\n this.myHeight = height; // should be 400 when constructed\n this.visitorDotSize = 10; // size of visitor dots in animatino\n // Calculate + set width-dependent drawing constants.\n this.initSizeConstants();\n // Init the color constants.\n this.initColorConstants();\n }", "function countingDistance() {\n setTimeout(function () {\n let color1 = document.querySelector(\"#RGBvalue> span\").innerHTML.split(\" \");\n let color2 = document.querySelector(\"#RGBvalue2>span\").innerHTML.split(\" \");\n color1 = color1.map((elem) => (elem = parseInt(elem)));\n color2 = color2.map((elem) => (elem = parseInt(elem)));\n console.log(226, color1, color2);\n let distance = Math.sqrt(\n (color2[0] - color1[0]) ** 2 +\n (color2[1] - color1[1]) ** 2 +\n (color2[2] - color1[2]) ** 2\n ).toFixed(1);\n // console.log(232, \"distance:\", distance);\n let putDistance = document.querySelector(\"p.fetched>span\").innerHTML;\n // console.log(234, putDistance);\n putDistance = putDistance.concat(\" [\", distance, \"]\");\n console.log(236, putDistance);\n document.querySelector(\"p.fetched>span\").innerHTML = putDistance;\n }, 150);\n}", "function getFramesPerInterval() {\n\treturn getInterval()*fps/1000;\n}", "animate(){\n // request another frame\n window.requestAnimationFrame(this.animate.bind(this));\n\n // calc elapsed time since last loop\n this.now = Date.now();\n this.elapsed = this.now - this.then;\n // if enough time has elapsed, draw the next frame\n if (this.elapsed > this.fpsInterval){\n // Get ready for next frame by setting then=now, but also adjust for your\n // specified fpsInterval not being a multiple of RAF's interval (16.7ms)\n this.then = this.now - (this.elapsed % this.fpsInterval)\n\n // animation code\n this.animateOneFrame();\n }\n }", "step() {\n this.currentColor += (this.redComponentRatio * (this.redDiff / this.steps)) & RED;\n this.currentColor += (this.greenComponentRatio * (this.greenDiff / this.steps)) & GREEN;\n this.currentColor += (this.blueComponentRatio * (this.blueDiff / this.steps)) & BLUE;\n return Math.floor(this.currentColor);\n }", "function frames(num1,num2) {\r\n\treturn num1*num2*60\r\n}", "function deltaRgb() {\n var STEPS = 60;\n var delta = {}\n for (var key in Colour) {\n delta[key] = Math.abs(Math.floor((colour[key] - nextColour[key]) / STEPS));\n if(delta[key] === 0) {\n delta[key]++;\n }\n }\n return delta;\n }", "function colorStep(c1, c2, t) {\n if (t < 0) {\n t = 0;\n } else if (t > 1) {\n t = 1;\n }\n\n return {\n r: parseInt(c1['r'] + (c2['r'] - c1['r']) * t),\n g: parseInt(c1['g'] + (c2['g'] - c1['g']) * t),\n b: parseInt(c1['b'] + (c2['b'] - c1['b']) * t)\n };\n }", "calculateRelativeValue(motion, key) {\n let a = motion.start[key];\n let b = motion.end[key];\n let r = motion.ratio;\n let easing = r > 0 ? motion.start.easing : motion.end.easing;\n\n switch (easing) {\n case \"in\": r = Math.sin((r * Math.PI) / 2); break;\n case \"out\": r = Math.cos((r * Math.PI) / 2); break;\n }\n\n return ((b - a) * r) + a;\n }", "get speed () {\n if (this.pointers.length > 0)\n return (this.pointers.reduce((sum, pointer) => { return sum+pointer.speed}, 0) / this.pointers.length);\n else\n return 0;\n }", "function calculate_distance() {\n\n currgal_length_in_Mpc = convert_ltyr_to_Mpc(currgal_length_in_ltyr);\n currgal_distance = currgal_length_in_Mpc / view_height_rad;\n\n print_distance(\"calculating.\");\n setTimeout(function () {\n print_distance(\"calculating..\")\n }, 500);\n setTimeout(function () {\n print_distance(\"calculating...\")\n }, 1000);\n setTimeout(function () {\n print_distance(Math.round(currgal_distance).toLocaleString() + \" Mpc\")\n }, 1500);\n }", "rgbDistance (r, g, b) {\n const [r1, g1, b1] = this\n const rMean = Math.round((r1 + r) / 2)\n const [dr, dg, db] = [r1 - r, g1 - g, b1 - b]\n const [dr2, dg2, db2] = [dr * dr, dg * dg, db * db]\n const distanceSq =\n (((512 + rMean) * dr2) >> 8) + (4 * dg2) + (((767 - rMean) * db2) >> 8)\n return distanceSq // Math.sqrt(distanceSq)\n }", "update() {\n if (this.isComplete()) {\n if (this.eventDispatcher && this.event) {\n this.eventDispatcher.dispatchEvent(this.event);\n }\n return -1;\n }\n // this.startTime = this.now();\n // this.endTime = this.startTime + this.totalTime;\n if (!this.endTime) return 0;\n var currentTime = this.now();\n var percentDone = (currentTime - this.startTime) / (this.endTime - this.startTime);\n if (percentDone < 0) percentDone = 0;\n else if (percentDone > 1) percentDone = 1;\n // var newVal = this.startVal + (this.endVal - this.startVal) * this.transition.applyTransition(percentDone);\n var trans = this.transition.applyTransition(percentDone);\n var newVal = this.startVal + (this.endVal - this.startVal) * trans;\n this.setValue(newVal);\n return 1;\n }", "function calcSpeed(distance, time){\n return distance/time;\n}", "update() {\n if (this._futureTrackDeltaTimeCache !== -1) {\n return;\n }\n\n const currentTime = this.gameTimeSeconds;\n\n this._incrementFrame();\n this._calculateNextDeltaTime(currentTime);\n this._calculateFrameStep();\n }", "function speedUp() {\r\n if (ballSpeedX > 0 && ballSpeedX < 16) {\r\n ballSpeedX += ballSpeedChange;\r\n aiSpeed += aiSpeedChange;\r\n }\r\n if (ballSpeedX < 0 && ballSpeedX > -16) {\r\n ballSpeedX -= ballSpeedChange;\r\n aiSpeed += aiSpeedChange;\r\n }\r\n if (ballSpeedY > 0 && ballSpeedY < 16) {\r\n ballSpeedY += ballSpeedChange;\r\n aiSpeed += aiSpeedChange;\r\n }\r\n if (ballSpeedY < 0 && ballSpeedY > -16) {\r\n ballSpeedY -= ballSpeedChange;\r\n aiSpeed += aiSpeedChange;\r\n }\r\n //console.log(ballSpeedX, ballY, aiSpeed, 'aiY=' + aiY)\r\n}", "function calc_steps() {\n\t\t for (var key in rgb_values) {\n\t\t if (rgb_values.hasOwnProperty(key)) {\n\t\t for(var i = 0; i < 4; i++) {\n\t\t rgb_values[key][i] = gradients[currentIndex][key][i];\n\t\t rgb_steps[key][i] = calc_step_size(gradients[nextIndex][key][i],rgb_values[key][i]);\n\t\t }\n\t\t }\n\t\t }\n\t\t}", "function calcTime(dist){\n\t//Get duration of the video\n\tvar dur = Popcorn(\"#video\").duration();\n\t//Get width of timeline in pixels\n\tvar wdth = document.getElementById(\"visualPoints\").style.width;\n\t//Trim for calculations\n\twdth = wdth.substr(0,wdth.length - 2);\n\t//Calculate pixel/total ratio\n\tvar ratio = dist / wdth;\n\t//Return time value in seconds calculated using ratio\n\treturn (ratio * dur);\n}", "calculateFPS(elapsedTimeMS) {\n this.fpsTimeElapsed += elapsedTimeMS;\n if (this.fpsTimeElapsed >= 1000) {\n this.currentFPS = this.fpsCounter;\n this.fpsCounter = 0;\n this.fpsTimeElapsed = 0;\n } else {\n this.fpsCounter++;\n }\n }" ]
[ "0.71802247", "0.56769407", "0.5670698", "0.56258494", "0.5583371", "0.5529605", "0.55150187", "0.55066925", "0.54881376", "0.5478588", "0.5415672", "0.5410037", "0.53956777", "0.539482", "0.5379198", "0.5377735", "0.53744066", "0.53606665", "0.5356631", "0.5353362", "0.5351561", "0.53445673", "0.5331744", "0.53296614", "0.5326162", "0.53205633", "0.52782226", "0.5260273", "0.52575094", "0.5253086" ]
0.71370786
1
==================== Transition Calculator ====================
function transition() { // checking R if (currentColor[0] > targetColor[0]) { currentColor[0] -= increment[0]; if (currentColor[0] <= targetColor[0]) { increment[0] = 0; } } else { currentColor[0] += increment[0]; if (currentColor[0] >= targetColor[0]) { increment[0] = 0; } } // checking G if (currentColor[1] > targetColor[1]) { currentColor[1] -= increment[1]; if (currentColor[1] <= targetColor[1]) { increment[1] = 0; } } else { currentColor[1] += increment[1]; if (currentColor[1] >= targetColor[1]) { increment[1] = 0; } } // checking B if (currentColor[2] > targetColor[2]) { currentColor[2] -= increment[2]; if (currentColor[2] <= targetColor[2]) { increment[2] = 0; } } else { currentColor[2] += increment[2]; if (currentColor[2] >= targetColor[2]) { increment[2] = 0; } } // applying the new modified color transElement.style.backgroundColor = rgb2hex(currentColor); // transition ended. start a new one if (increment[0] == 0 && increment[1] == 0 && increment[2] == 0) { startTransition(); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function transition() {\n generateNewColour();\n\n for (var key in Colour) {\n if(colour[key] > nextColour[key]) {\n colour[key] -= delta[key];\n if(colour[key] <= nextColour[key]) {\n delta[key] = 0;\n }\n }\n else {\n colour[key] += delta[key];\n if(colour[key] >= nextColour[key]) {\n delta[key] = 0;\n }\n }\n }\n }", "function CalculateTransition(parameter, destinyParameter, TransitionSpeed){\n\tif (parameter == destinyParameter) // If the parameter was in the same position of its destiny, return it\n\t\treturn parameter;\n\telse {\n\t\t\n\t\tif (parameter < destinyParameter) // If the parameter is minor than destiny, calculate the half of the track to the front\n\t\t\treturn parameter + Math.ceil((destinyParameter - parameter) / 5);\t\n\t\telse // And if the parameter is minor than destiny, calculate the half of the track to the back\n\t\t\treturn parameter - Math.ceil((parameter - destinyParameter) / 5);\t\n\t}\n\t\n}", "function transition() {\n // checking R\n if (currentColor[0] > targetColor[0]) {\n currentColor[0] -= increment[0];\n if (currentColor[0] <= targetColor[0]) {\n increment[0] = 0;\n }\n } else {\n currentColor[0] += increment[0];\n if (currentColor[0] >= targetColor[0]) {\n increment[0] = 0;\n }\n }\n \n // checking G\n if (currentColor[1] > targetColor[1]) {\n currentColor[1] -= increment[1];\n if (currentColor[1] <= targetColor[1]) {\n increment[1] = 0;\n }\n } else {\n currentColor[1] += increment[1];\n if (currentColor[1] >= targetColor[1]) {\n increment[1] = 0;\n }\n }\n \n // checking B\n if (currentColor[2] > targetColor[2]) {\n currentColor[2] -= increment[2];\n if (currentColor[2] <= targetColor[2]) {\n increment[2] = 0;\n }\n } else {\n currentColor[2] += increment[2];\n if (currentColor[2] >= targetColor[2]) {\n increment[2] = 0;\n }\n }\n \n // applying the new modified color\n transElement.style.backgroundColor = rgb2hex(currentColor);\n \n // transition ended. start a new one\n if (increment[0] == 0 && increment[1] == 0 && increment[2] == 0) {\n startTransition();\n }\n }", "function transition(updateCurrent){\n var next_state = {};\n \n for(var i in current_state){\n next_state[i] = 0;\n }\n \n for(var i in current_state){\n for(var j in transition_model[i]){\n next_state[i] += current_state[j]*transition_model[j][i]\n //console.log(i,j,'=',current_state[j],'*',transition_model[j][i]);\n }\n }\n\n if (updateCurrent){\n current_state = next_state;\n states_array.push(current_state);}\n else {return next_state;}\n }", "function transitionThreeUp(){\n\n}", "applyTransition(percentDone) {\n return percentDone;\n }", "stateTransition(){return}", "calculateTransition(transition) {\n // Start in true state so adding transition can make to uncraftable\n const depth = new Depth({value: 0, craftable: true});\n depth.addTransition(transition);\n transition.depth = depth;\n\n if (transition.newActor) {\n this.setObjectDepth(transition.newActor, depth);\n }\n if (transition.newTarget) {\n this.setObjectDepth(transition.newTarget, depth);\n }\n if (transition.newExtraTarget) {\n this.setObjectDepth(transition.newExtraTarget, depth);\n }\n }", "function Transition() {\n\n /**\n * The list of transitions associated to a state\n * @private\n */\n var _transitions = {};\n\n /**\n * Add a new transition\n * @private\n * @param {String} event the event that will trigger the transition\n * @param {Function} action the function that is executed\n * @param {Object} scope [optional] the scope in which to execute the action\n * @param {String} next [optional] the name of the state to transit to.\n * @returns {Boolean} true if success, false if the transition already exists\n */\n this.add = function add(event, action, scope, next) {\n\n var arr = [];\n\n if (_transitions[event]) {\n return false;\n }\n\n if (typeof event == \"string\" &&\n typeof action == \"function\") {\n\n arr[0] = action;\n\n if (typeof scope == \"object\") {\n arr[1] = scope;\n }\n\n if (typeof scope == \"string\") {\n arr[2] = scope;\n }\n\n if (typeof next == \"string\") {\n arr[2] = next;\n }\n\n _transitions[event] = arr;\n return true;\n }\n\n return false;\n };\n\n /**\n * Check if a transition can be triggered with given event\n * @private\n * @param {String} event the name of the event\n * @returns {Boolean} true if exists\n */\n this.has = function has(event) {\n return !!_transitions[event];\n };\n\n /**\n * Get a transition from it's event\n * @private\n * @param {String} event the name of the event\n * @return the transition\n */\n this.get = function get(event) {\n return _transitions[event] || false;\n };\n\n /**\n * Execute the action associated to the given event\n * @param {String} event the name of the event\n * @param {params} params to pass to the action\n * @private\n * @returns false if error, the next state or undefined if success (that sounds weird)\n */\n this.event = function event(newEvent) {\n var _transition = _transitions[newEvent];\n if (_transition) {\n _transition[0].apply(_transition[1], toArray(arguments).slice(1));\n return _transition[2];\n } else {\n return false;\n }\n };\n}", "currentMotion(){\n\n // an object to hold this function's result\n let result = {\n height:0,\n thighDisplacement:0,\n thighDisplacement2:0,\n kneeDisplacement:0,\n thighOrigin:0,\n thighOrigin2:0,\n kneeOrigin:0,\n }\n // if transition is active, ramp from this.last values to this.current values\n if(this.transition>0){\n result.height=lerp(this.current.height, this.last.height, this.transition);\n result.thighDisplacement=lerp(this.current.thighDisplacement, this.last.thighDisplacement, this.transition);\n result.kneeDisplacement=lerp(this.current.kneeDisplacement, this.last.kneeDisplacement, this.transition);\n result.thighOrigin=lerp(this.current.thighOrigin, this.last.thighOrigin, this.transition);\n result.kneeOrigin=lerp(this.current.kneeOrigin, this.last.kneeOrigin, this.transition);\n result.thighOrigin2=lerp(this.current.thighOrigin2, this.last.thighOrigin2, this.transition);\n result.thighDisplacement2=lerp(this.current.thighDisplacement2, this.last.thighDisplacement2, this.transition);\n this.backHeight = result.height;\n // increment transition by removing 1/length.\n // transition stops when it reaches 0.\n this.transition-=1/this.transitionLength;\n }\n else {\n // if transition isn't active, result becomes current motion values.\n result = this.current;\n this.backHeight = this.current.height;\n }\n // return result\n return result;\n }", "function updateTransitions() {\r\n\r\n if (motion.currentTransition !== nullTransition) {\r\n // is this a new transition?\r\n if (motion.currentTransition.progress === 0) {\r\n // do we have overlapping transitions?\r\n if (motion.currentTransition.lastTransition !== nullTransition) {\r\n // is the last animation for the nested transition the same as the new animation?\r\n if (motion.currentTransition.lastTransition.lastAnimation === avatar.currentAnimation) {\r\n // then sync the nested transition's frequency time wheel for a smooth animation blend\r\n motion.frequencyTimeWheelPos = motion.currentTransition.lastTransition.lastFrequencyTimeWheelPos;\r\n }\r\n }\r\n }\r\n if (motion.currentTransition.updateProgress() === TRANSITION_COMPLETE) {\r\n motion.currentTransition = nullTransition;\r\n }\r\n }\r\n}", "getTransitionMethod (transition) {\n\n switch (transition) {\n // ease linear\n case \"easeLinear\":\n return d3EaseLinear; \n break;\n // easeQuadIn as d3EaseQuadIn,\n case \"easeQuadIn\":\n return d3EaseQuadIn;\n break;\n // easeQuadOut as d3EaseQuadOut\n case \"easeQuadOut\":\n return d3EaseQuadOut;\n break;\n // easeQuadInOut as d3EaseQuadInOut\n case \"easeQuadInOut\":\n return d3EaseQuadInOut;\n break;\n // easeCubicIn as d3EaseCubicIn\n case \"easeCubicIn\":\n return d3EaseCubicIn;\n break;\n // easeCubicOut as d3EaseCubicOut,\n case \"easeCubicOut\":\n return d3EaseCubicOut;\n break;\n // easeCubicInOut as d3EaseCubicInOut,\n case \"easeCubicInOut\":\n return d3EaseCubicInOut;\n break;\n // easePolyIn as d3EasePolyIn,\n case \"easePolyIn\":\n return d3EasePolyIn;\n break;\n // easePolyOut as d3EasePolyOut,\n case \"easePolyOut\":\n return d3EasePolyOut;\n break;\n // easePolyInOut as d3EasePolyInOut,\n case \"easePolyInOut\":\n return d3EasePolyInOut;\n break;\n // easeSinIn as d3EaseSinIn,\n case \"easeSinIn\":\n return d3EaseSinIn;\n break;\n // easeSinOut as d3EaseSinOut,\n case \"easeSinOut\":\n return d3EaseSinOut;\n break;\n // easeSinInOut as d3EaseSinInOut,\n case \"easeSinInOut\":\n return d3EaseSinInOut;\n break;\n // easeExpIn as d3EaseExpIn,\n case \"easeExpIn\":\n return d3EaseExpIn;\n break;\n // easeExpOut as d3EaseExpOut,\n case \"easeExpOut\":\n return d3EaseExpOut;\n break;\n // easeExpInOut as d3EaseExpInOut,\n case \"easeExpInOut\":\n return d3EaseExpInOut;\n break;\n // easeCircleIn as d3EaseCircleIn,\n case \"easeCircleIn\":\n return d3EaseCircleIn;\n break;\n // easeCircleOut as d3EaseCircleOut,\n case \"easeCircleOut\":\n return d3EaseCircleOut;\n break;\n // easeCircleInOut as d3EaseCircleInOut,\n case \"easeCircleInOut\":\n return d3EaseCircleInOut;\n break;\n // easeBounceIn as d3EaseBounceIn,\n case \"easeBounceIn\":\n return d3EaseBounceIn;\n break;\n // easeBounceOut as d3EaseBounceOut,\n case \"easeBounceOut\":\n return d3EaseBounceOut;\n break;\n // easeBounceInOut as d3EaseBounceInOut,\n case \"easeBounceInOut\":\n return d3EaseBounceInOut;\n break;\n // easeBackIn as d3EaseBackIn,\n case \"easeBackIn\":\n return d3EaseBackIn;\n break;\n // easeBackOut as d3EaseBackOut,\n case \"easeBackOut\":\n return d3EaseBackOut;\n break;\n // easeBackInOut as d3EaseBackInOut,\n case \"easeBackInOut\":\n return d3EaseBackInOut;\n break;\n // easeElasticIn as d3EaseElasticIn,\n case \"easeElasticIn\":\n return d3EaseElasticIn;\n break;\n // easeElasticOut as d3EaseElasticOut,\n case \"easeElasticOut\":\n return d3EaseElasticOut;\n break;\n // easeElasticInOut as d3EaseElasticInOut,\n case \"easeElasticInOut\":\n return d3EaseElasticInOut;\n break;\n // easeElastic as d3EaseElastic,\n case \"easeElastic\":\n return d3EaseElastic;\n break;\n\n // ease elastic transition\n case \"easeElastic\":\n return d3EaseElastic; \n break;\n };\n\n }", "getTransition() {\n if ( this.props.finalTab ) {\n return WizardPage.transitions.submit;\n } else {\n return this.getPreferredTransition();\n }\n }", "function transition(source, input, target, output, direction) {\n return 'δ('+source+', '+input+') = ('+target+', '+output+', '+direction+')';\n }", "function ArrowViewStateTransition() {}", "function updateTransition() {\r\n\r\n if (motion.currentTransition !== nullTransition) {\r\n\r\n // new transition?\r\n if (motion.currentTransition.progress === 0) {\r\n\r\n // overlapping transitions?\r\n if (motion.currentTransition.lastTransition !== nullTransition) {\r\n\r\n // is the last animation for the nested transition the same as the new animation?\r\n if (motion.currentTransition.lastTransition.lastAnimation === motion.currentAnimation) {\r\n\r\n // sync the nested transitions's frequency time wheel for a smooth animation blend\r\n motion.frequencyTimeWheelPos = motion.currentTransition.lastTransition.lastFrequencyTimeWheelPos;\r\n }\r\n }\r\n\r\n if (motion.currentTransition.lastAnimation === motion.selectedWalk) {\r\n\r\n // decide at which angle we should stop the frequency time wheel\r\n var stopAngle = motion.selectedWalk.calibration.stopAngleForwards;\r\n var percentToMove = 0;\r\n var lastFrequencyTimeWheelPos = motion.currentTransition.lastFrequencyTimeWheelPos;\r\n var lastElapsedFTDegrees = motion.currentTransition.lastElapsedFTDegrees;\r\n\r\n // set the stop angle depending on which quadrant of the walk cycle we are currently in\r\n // and decide whether we need to take an extra step to complete the walk cycle or not\r\n // - currently work in progress\r\n if(lastFrequencyTimeWheelPos <= stopAngle && lastElapsedFTDegrees < 180) {\r\n\r\n // we have not taken a complete step yet, so we do need to do so before stopping\r\n percentToMove = 100;\r\n stopAngle += 180;\r\n\r\n } else if(lastFrequencyTimeWheelPos > stopAngle && lastFrequencyTimeWheelPos <= stopAngle + 90) {\r\n\r\n // take an extra step to complete the walk cycle and stop at the second stop angle\r\n percentToMove = 100;\r\n stopAngle += 180;\r\n\r\n } else if(lastFrequencyTimeWheelPos > stopAngle + 90 && lastFrequencyTimeWheelPos <= stopAngle + 180) {\r\n\r\n // stop on the other foot at the second stop angle for this walk cycle\r\n percentToMove = 0;\r\n if (motion.currentTransition.lastDirection === BACKWARDS) {\r\n\r\n percentToMove = 100;\r\n\r\n } else {\r\n\r\n stopAngle += 180;\r\n }\r\n\r\n } else if(lastFrequencyTimeWheelPos > stopAngle + 180 && lastFrequencyTimeWheelPos <= stopAngle + 270) {\r\n\r\n // take an extra step to complete the walk cycle and stop at the first stop angle\r\n percentToMove = 100;\r\n }\r\n\r\n // set it all in motion\r\n motion.currentTransition.stopAngle = stopAngle;\r\n motion.currentTransition.percentToMove = percentToMove;\r\n }\r\n\r\n } // end if new transition\r\n\r\n // update the Transition progress\r\n if (motion.currentTransition.updateProgress() >= 1) {\r\n\r\n // it's time to kill off this transition\r\n delete motion.currentTransition;\r\n motion.currentTransition = nullTransition;\r\n }\r\n }\r\n}", "detectTransitionType(){\n this.getTransitionType()\n this.toggleTransitionClasses()\n }", "function stateTransition(oldState, votes) {\n return oldState;\n}", "function change() {\n //Depending on which botton was checked is the respected\n //transition function called\n if (this.value == 2016) { \n transition2016();\n } else if (this.value == 2014) {\n transition2014();\n } else{\n transition2006(); \n }\n}", "calcStateChange(currentState, workersStates) {\n const nextState = STATE_HANDLERS[currentState](workersStates);\n return (nextState !== currentState)\n ? { type: CONTROL_ACTION_KEYS.SET_STATE, data: nextState } : null;\n }", "function CalculateScaleTransition(parameter, destinyParameter, TransitionSpeed){\n\t// Setting the transition speed\n\tif(TransitionSpeed == \"fast-background\")\n\t\tparameterChange = 0.05;\n\telse\n\t\tparameterChange = 0.01;\n\tif (parameter.toFixed(2) == destinyParameter.toFixed(2)) // If the parameter was in the same position of its destiny, return it\n\t\treturn parameter;\n\telse {\n\t\t\n\t\tif (parameter < destinyParameter) // If the parameter is minor than destiny, calculate the half of the track to the front\n\t\t\n\t\t\t//return parameter + roundValueToDigits((destinyParameter - parameter) / 5) + 0.01;\t\n\t\t\treturn roundValueToDigits(parameter + parameterChange);\t\n\t\telse // And if the parameter is minor than destiny, calculate the half of the track to the back\n\t\t\t//return parameter - roundValueToDigits((parameter - destinyParameter) / 5) - 0.01;\t\n\t\t\treturn roundValueToDigits(parameter - parameterChange);\t\n\t}\n}", "function getTransition(properties, duration, easing, type){\n\t\tvar ob = parse(properties);\n\t\tob[0].isTransition = type || 1;\n\t\tob[0].useAll = true;\n\t\treturn getCSS(ob, duration, easing);\n\t}", "function convertTransition(edge) {\n\t\tif(!visitedEdges.includes(edge)){\n\t\t\tvisitedEdges.push(edge);\n\t\t}else{\n\t\t\talert('This transitition has already been converted');\n\t\t\treturn;\n\t\t}\n\t\tvar transitions = toColonForm(edge.label()).split('<br>');\n\t\tfunction setTableValue (a, b, c) {\n\t\t\ttable.value(lastRow, 0, a);\n\t\t\ttable.value(lastRow, 1, b);\n\t\t\ttable.value(lastRow, 2, c);\n\t\t\ttable._arrays[lastRow].show();\n\t\t\tlastRow++;\n\t\t}\n\t\tfor(var i = 0; i < transitions.length; i++){\n\t\t\tvar transition = transitions[i];\n\t\t\tvar transitionSplit = transition.split(':');\n\t\t\tvar fromNode = edge.start();\n\t\t\tvar toNode = edge.end();\n\t\t\tvar qi = fromNode.value();\n\t\t\tvar qj = toNode.value();\n\t\t\tif(increaseOne.indexOf(transition) > -1) {\n\t\t\t\tvar states = g.nodes();\n\t\t\t\tfor (var k = 0; k < states.length; k++) {\n\t\t\t\t\tvar qk = states[k].value();\n\t\t\t\t\tfor (var l = 0; l < states.length; l++) {\n\t\t\t\t\t\tvar ql = states[l].value();\n\t\t\t\t\t\t// format ['', '', ['','','']]\n\t\t\t\t\t\tproductions.push(['(' + qi + transitionSplit[1] + qk + ')', arrow, [transitionSplit[0] , '(' + qj + transitionSplit[2][0] + ql + ')' , '(' + ql + transitionSplit[2][1] + qk + ')']]);\n\t\t\t\t\t\tsetTableValue('(' + qi + transitionSplit[1] + qk + ')', arrow, transitionSplit[0] + '(' + qj + transitionSplit[2][0] + ql + ')' + '(' + ql + transitionSplit[2][1] + qk + ')');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tproductions.push(['(' + qi + transitionSplit[1] + qj + ')', arrow, [transitionSplit[0]]]);\n\t\t\t\tsetTableValue('(' + qi + transitionSplit[1] + qj + ')', arrow, transitionSplit[0]);\n\t\t\t}\n\t\t\ttable.layout();\n\t\t}\n\t\tcount++;\n\t\tif(count >= g.edges().length){\n\t\t\tjsav.umsg('Finished');\n\t\t\talert('All transitions have been converted, export to grammar editor?');\n\t\t\tproductions = removeUseless(productions);\n\n\t\t\tvar reducedTable = jsav.ds.matrix(productions, {style: \"table\"});\n\t\t\treducedTable.layout();\n\t\t\t$(\".jsavmatrix\").css(\"margin-left\", \"auto\");\n\n\t\t\tproductions = transform(productions);\n\t\t\tlocalStorage['grammar'] = JSON.stringify(productions);\n\t\t\twindow.open(\"./grammarEditor.html\");\n\t\t}\n\t}", "function getTransitionTime (distance, speed) {\n return distance / speed * 1000;\n}", "function getTransition() {// Function to get transition for d3.v.6\n return d3.transition()\n .duration(750)\n //.ease(d3.easeLinear)\n}", "function transition_listener(p1, p2, time){\n\tp1.obj[p1.lstnr](p1.value);\n\treturn p1.value;\n}", "function transitionOpacities(fromOpacity, toOpacity, t) {\n var targetOpacity = (toOpacity - fromOpacity) * t + fromOpacity;\n // Based on the blending formula here. (http://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending)\n // This is a quadratic blending function that makes the top layer and bottom layer blend linearly.\n // However there is an asymptote at target=1 so that needs to be handled with an if else statement.\n if (targetOpacity == 1) {\n var newFromOpacity = 1;\n var newToOpacity = t;\n } else {\n var newFromOpacity = targetOpacity - t * t * targetOpacity;\n var newToOpacity = (targetOpacity - newFromOpacity) / (1 - newFromOpacity);\n }\n return [newFromOpacity, newToOpacity];\n }", "function parseStateFromTransition(transition) {\r\n const parsedState = {}\r\n\r\n for (let player in transition) parsedState[player] = transition[player].nextState\r\n return parsedState\r\n }", "function color_fsm() {\n if (color_stage == 0) {\n if (lorenz_red >= 255) {\n color_stage = 1;\n } else {\n lorenz_red++;\n }\n } else if (color_stage == 1) {\n if (lorenz_green >= 255) {\n color_stage = 2;\n } else {\n lorenz_green++;\n }\n } else if (color_stage == 2) {\n if (lorenz_blue >= 255) {\n color_stage = 3;\n } else {\n lorenz_blue++;\n }\n } else if (color_stage == 3) {\n if (lorenz_red <= 0) {\n color_stage = 4;\n } else {\n lorenz_red--;\n }\n } else if (color_stage == 4) {\n if (lorenz_green <= 0) {\n color_stage = 5;\n } else {\n lorenz_green--;\n }\n } else {\n if (lorenz_blue <= 0) {\n color_stage = 0;\n } else {\n lorenz_blue--;\n }\n }\n}", "function transicion () {\n\n ready_tapes = 0;\n var current_transition = \"\";\n current_transition += state + \",\";\n\n for ( var i = 0; i < n_tapes - 1; i++ ) {\n current_transition += tapes[ i ].get_current_symbol() + \",\";\n }\n current_transition += tapes[ n_tapes - 1 ].get_current_symbol();\n\n //If transition exists, apply transition.\n\n if ( transitions[ current_transition ] ) {\n var aux = transitions[ current_transition ].split( ',' );\n state = aux[ 0 ];\n $( '#state_text' ).text( \"State: \" + state );\n\n for ( var i = 0; i < n_tapes; i++ ) {\n tapes[ i ].set_middle_symbol( aux[ i + 1 ] );\n\n if ( aux[ i + n_tapes + 1 ] == 'r' ) {\n tapes[ i ].mover( -1, function () {\n transicion();\n } );\n }\n\n else if ( aux[ i + n_tapes + 1 ] == 'l' ) {\n tapes[ i ].mover( 1, function () {\n transicion();\n } );\n }\n\n else {\n tapes[ i ].mover( 0, function () {\n transicion();\n } );\n }\n }\n step_counter++;\n }\n\n //Otherwise verify if the input is accepted.\n\n else {\n ready_tapes = 2 * n_tapes;\n $( '#state_text' ).text( \"State: \" + state );\n if ( final_states.indexOf( state ) != -1 ) {\n $( '#accept_icon' ).removeClass( 'large red remove circle' )\n .addClass( 'large green check circle' ).show();\n }\n else {\n $( '#accept_icon' ).removeClass( 'large green check circle' )\n .addClass( 'large red remove circle' ).show();\n }\n\n layer.draw();\n $( '#load_input' ).removeClass( 'disabled' );\n $( '#input' ).removeClass( 'disabled' );\n disableMachineButtons();\n input_loaded = false;\n }\n $( '#counter_text' ).text( \"Steps: \" + step_counter );\n}" ]
[ "0.6630601", "0.6541303", "0.6538054", "0.63178617", "0.63018835", "0.62306374", "0.6152068", "0.61283296", "0.60233706", "0.5993718", "0.5973599", "0.59581375", "0.59218556", "0.59086174", "0.5902313", "0.58689725", "0.5867377", "0.5865813", "0.58509195", "0.58506835", "0.584715", "0.582811", "0.57974577", "0.57906353", "0.5772368", "0.5736266", "0.57268405", "0.57258445", "0.5719667", "0.57063866" ]
0.67392343
0
Create an object listing for an entry or page. This is used for Selected Entry, Selected Page, and Reciprocal Objects.
function createObjectListing(obj_title, obj_id, obj_class, obj_permalink, blog_id) { var $preview = jQuery('<span/>') .addClass('obj-title') .text(obj_title); // Edit link. var $edit = jQuery('<a/>') .attr('href', CMSScriptURI+'?__mode=view&_type='+obj_class+'&id='+obj_id+'&blog_id='+blog_id) .addClass('edit') .attr('target', '_blank') .attr('title', 'Edit in a new window') .html('<img src="'+StaticURI+'images/status_icons/draft.gif" width="9" height="9" alt="Edit" />'); // View link. var $view; if (obj_permalink) { $view = jQuery('<a/>') .attr('href', obj_permalink) .addClass('view') .attr('target', '_blank') .attr('title', 'View in a new window') .html('<img src="'+StaticURI+'images/status_icons/view.gif" width="13" height="9" alt="View" />'); } // Delete button. var $remove = jQuery('<img/>') .addClass('remove') .attr('title', 'Remove selected entry') .attr('alt', 'Remove selected entry') .attr('src', StaticURI+'images/status_icons/close.gif') .attr('width', 9) .attr('height', 9); // Insert all of the above into a list item. var $li = jQuery('<li/>') .attr('id', 'obj-'+obj_id) .append($preview) .append($edit) .append($view) .append($remove); return $li; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function newListEntry(entry) {\n var listEntry = newElement('li');\n var listText = newElement('span');\n var actionContainer = newElement('div');\n var runButton = createIconButton('power-off', true, null, entry, _run);\n var editButton = createIconButton('edit', true, null, entry, _edit);\n var deleteButton = createIconButton('trash', true, null, entry, _delete);\n listText.innerHTML = entry.name;\n actionContainer.appendChild(runButton);\n actionContainer.appendChild(editButton);\n actionContainer.appendChild(deleteButton);\n listEntry.appendChild(listText);\n listEntry.appendChild(actionContainer);\n return listEntry;\n}", "static displayEntries() {\n let posts = Store.getEntries();\n\n posts.forEach((entry) => UI.addEntryToList(entry));\n\n }", "function renderEntry(entry) {\n\n var $entrieslists = document.createElement('li');\n\n var $row = document.createElement('div');\n $row.className = 'row';\n $entrieslists.appendChild($row);\n var $columnHalf = document.createElement('div');\n $columnHalf.className = 'column-half';\n $row.appendChild($columnHalf);\n\n var $img = document.createElement('img');\n $img.setAttribute('src', entry.photoUrl);\n $img.className = 'entries-img';\n $columnHalf.appendChild($img);\n\n var $entriesText = document.createElement('div');\n $entriesText.className = 'column-half entries-text';\n $row.appendChild($entriesText);\n\n var $title = document.createElement('h2');\n $title.textContent = entry.title;\n $entriesText.appendChild($title);\n\n var $notes = document.createElement('p');\n $notes.textContent = entry.notes;\n $entriesText.appendChild($notes);\n\n return $entrieslists;\n\n}", "function addEntry(entries) {\n\n var newUnorderedList = document.createElement('ul');\n var dataViewEntry = document.querySelector('div[data-view=\"entries\"]');\n dataViewEntry.appendChild(newUnorderedList);\n\n var divRow = document.createElement('div');\n divRow.setAttribute('class', 'row');\n newUnorderedList.appendChild(divRow);\n\n var divColumnHalf1 = document.createElement('div');\n divColumnHalf1.setAttribute('class', 'column-half');\n divRow.appendChild(divColumnHalf1);\n\n var liImage = document.createElement('li');\n divColumnHalf1.appendChild(liImage);\n\n var image = document.createElement('img');\n image.setAttribute('src', entries.url);\n image.setAttribute('class', 'dom-tree-image');\n liImage.appendChild(image);\n\n var divColumnHalf2 = document.createElement('div');\n divColumnHalf2.setAttribute('class', 'column-half');\n divRow.appendChild(divColumnHalf2);\n\n var liText = document.createElement('li');\n divColumnHalf2.appendChild(liText);\n\n var heading = document.createElement('h2');\n heading.textContent = entries.title;\n liText.appendChild(heading);\n\n var bodyText = document.createElement('p');\n bodyText.textContent = entries.notes;\n liText.appendChild(bodyText);\n\n return newUnorderedList;\n}", "function ListEntry(id, name) {\n this.id = id;\n this.name = name;\n}", "function createObjectImagePage(web, object, object_num) {\n\tvar objectListResult = \"\";\n\tvar objectListHead = \"<p><input type='image' src='images/object/\";\n\n\tfor (var i = 0; i < object_num; i++) {\n\t\tvar objectName = object + (i+1).toString();\n\t\tvar objectListMiddle = \"value='\" + objectName+ \"' onclick='addObjectImage(\\\"\" + objectName + \"\\\", \\\"\" + web + \"\\\")' \";\n\t\tobjectListResult += objectListHead + objectName + \".jpg' \" + objectListMiddle + \"/></p>\";\n\t}\n\tvar footer = \"<div data-role=footer data-id=fool data-position=fixed><div data-role=navbar><ul><li><a href=#home>Home</a></li><li><a href=#friends>Accounts</a></li><li><a href=#confirm>Setting</a></li>\";\n\tvar newPage = $(\"<div data-role='page' data-title='\"+web+object+\"' id=\"+web+object+\"><div data-role='header' data-position=fixed><a href=#\" + web+\"Page data-icon='back'>Back</a><h1>\"+object+\"</h1></div><div data-role='content' class=images>\"+objectListResult+\"</div>\"+footer+\"</div>\");\n\treturn newPage;\n\t//newPage.appendTo( $.mobile.pageContainer );\n\t//$.mobile.changePage(newPage);\n}", "function createListNode(obj, path) {\n if (\"maneuvers\" in obj) {\n return null;\n }\n \n var $ul = $(\"<ul>\");\n\n for (var x in obj) {\n var child = obj[x];\n if (child === null || typeof child !== 'object') continue;\n \n var name = x;\n if (\"description\" in child) {\n name = child.description;\n }\n\n var childpath = (path == \"\"? x : path + \"_\" + x);\n var $a = $(\"<a>\").attr(\"href\", \"cube.html?case=\" + childpath).text(name);\n\n var $cul = createListNode(child, childpath);\n var count = getManeuverCount(child);\n\n var $li = $(\"<li>\");\n $li.append($a);\n if (count > 0) {\n $li.append($(\"<span>\").addClass(\"note\").text(\"(\" + count + \")\"));\n }\n if ($cul) {\n $li.append($cul);\n }\n $ul.append($li);\n }\n \n return $ul;\n}", "function createTaskList(object) {\n\n\tfor( let i=0; i<object.length; i++ ) {\n\t\tlet navListItem =\n\t\t\t'<li>' +\n\t\t\t'<a href=\"single.html?task=' + object[i].id + '\">' +\n\t\t\t'<h2 class=\"task-title\">' + object[i].title.rendered + '</h2>' +\n\t\t\t'<div class=\"task-date\">' +\n\t\t\tgetDate(object[i]) +\n\t\t\t'</div>' +\n\t\t\t'<div class=\"task-status\">' + getStatus(object[i].task_status) + '</div>' +\n\t\t\t'</a>' +\n\t\t\t'</li>';\n\n\t\t$('.task-list ul').append(navListItem);\n\t}\n\t$('.main-area').append('<button class=\"more\">Load more tasks</button>');\n\tmorePostsTrigger();\n\n}", "function createListing(payload, cb) {\n // TODO: handle validation here or at the controller level? Let's try controller level\n\n base('listings').create(payload, function(err, record) {\n if (err) {\n console.error(err);\n return cb(err);\n }\n\n clearCache();\n // cb(null, record.getId());\n // Q: how should we return this for the permalink?\n // The unique ID is really the most important part...\n var permalink = record.get('unique_id') + '-' + record.get('permalink');\n cb(null, permalink);\n });\n\n // fetch the record that was just created to get the unique ID (for the permalink...)\n\n // bust the cache so the new listing will show up on the home page\n}", "function displayList (listofObjs){\n // create an ul element\n // create a li element\n // -append a particular object(ex. sailor)\n // -set as innerHTML\n // append li to ul\n // append our ul to pirate class element\nvar unOrdered = document.createElement('ul');\nvar objectContent = \" \";\n\nfor(var i = 0; i < listofObjs.length; i++){\n// loop through objects to add list item content\n for (key in listofObjs[i]){\n var listItems = document.createElement('li');\n\n objectContent += (\"<br>\" + key + \": \" + listofObjs[i][key]);\n listItems.innerHTML = objectContent;\n }\n\n unOrdered.appendChild(listItems);\n}\n\ndocument.body.appendChild(unOrdered);\n\n}", "function MakeObjectToAddInList(success) {\n return {\n \"itemId\": success.data.data.id,\n \"itemName\": success.data.data.itemName,\n \"itemPrice\": null,\n \"collection\": null,\n \"images\": [],\n \"quantity\": null,\n \"dateOfPurchase\": success.data.data.dateOfPurchase,\n \"category\": null,\n \"rooms\": null,\n \"currentValue\": null,\n \"brand\": success.data.data.brand,\n \"model\": success.data.data.model,\n \"description\": success.data.data.description,\n \"roomId\": null,\n \"collectionId\": null,\n \"price\": success.data.data.quotedPrice,\n \"categoryId\": success.data.data.category.id,\n \"categoryName\": GetCategoryOrSubCategoryOnId(true, success.data.data.category.id),\n \"subCategoryId\": success.data.data.subCategory.id,\n \"subCategoryName\": GetCategoryOrSubCategoryOnId(false, success.data.data.subCategory.id),\n \"templateType\": null,\n \"itemWorth\": 0,\n \"policyNumber\": null,\n \"appraisalValue\": null,\n \"productSerialNo\": null,\n \"imageId\": null,\n \"jwelleryTypeId\": null,\n \"jwelleryType\": null,\n \"claimed\": false,\n \"claimId\": success.data.data.claimId,\n \"vendorId\": null,\n \"age\": success.data.data.age,\n \"status\": null,\n \"statusId\": success.data.data.statusId,\n \"itemCategory\": null,\n \"contact\": null,\n \"notes\": null,\n \"additionalInfo\": null,\n \"approved\": false,\n \"scheduled\": success.data.data.isScheduledItem\n }\n }", "function Listing(status, postID, manage, title, postedDate, from, subject){\n this.status = status || '';\n this.postID = postID || '';\n this.manage = manage || '';\n this.title = title || '';\n this.postedDate = postedDate || '';\n this.from = from || '';\n this.subject = subject || '';\n\n}", "function _createEntries() {\n\t\tvar lvStatus;\n\t\t//Get the Request Body\n\t\tvar oBody = JSON.parse($.request.body.asString());\n\n\t\t//Check if it is Bulk Scenario Asynchronous\n\t\tif (oBody.JOURNAL.constructor === Array) {\n\t\t\tfor (var i = 0; i < oBody.JOURNAL.length; i++) {\n\t\t\t\t//Create the Batch Entry\n\t\t\t\tlvStatus = _createBatch(oBody, oBody.JOURNAL[i]);\n\n\t\t\t\t//Create the Header\n\t\t\t\tif (lvStatus === \"SUCCESS\") {\n\t\t\t\t\tlvStatus = _createHeader(oBody.JOURNAL[i]);\n\t\t\t\t}\n\n\t\t\t\t//If Successful create the Item\n\t\t\t\tif (lvStatus === \"SUCCESS\") {\n\t\t\t\t\t_createItems(oBody.JOURNAL[i], oBody.JOURNAL[i].JOURNAL_ENTRY);\n\t\t\t\t}\n\t\t\t\tlvStatus = \"\";\n\t\t\t}\n\t\t} else {\n\t\t\t//Create Header Entry\n\t\t\tif (oBody.JOURNAL) {\n\t\t\t\t//Create the Batch Entry\n\t\t\t\tlvStatus = _createBatch(oBody, oBody.JOURNAL);\n\n\t\t\t\t//Create the Header\n\t\t\t\tif (lvStatus === \"SUCCESS\") {\n\t\t\t\t\tlvStatus = _createHeader(oBody.JOURNAL);\n\t\t\t\t}\n\n\t\t\t\t//Create the Items\n\t\t\t\tif (lvStatus === \"SUCCESS\") {\n\t\t\t\t\t_createItems(oBody.JOURNAL, oBody.JOURNAL.JOURNAL_ENTRY);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "function createPage () {\n\t$(\"ul li\").each(function(index) {\n\t\tobj = $(this)\n\t\tdivCount += 1\n\t\t\tif (divCount < 10) {\n\t\t\t\tobj.show()\n\t\t\t} else {\n\t\t\t\tobj.hide()\n\t\t\t}\n\t\t\tif (index % 10 === 0) {\n\t\t\t\tnewTag += \"<li id=\\\"page\\\"><a href=\\\"#\\\">\" + countCreate + \"</a></li>\"\n\t\t\t\tcountCreate++;\n\t\t\t}\n\t});\n\tif (newTag !== null) {\n\t\t$(\"ul\").append(\"<nav aria-label=\\\"Page navigation\\\"><ul class=\\\"pagination\\\">\" + newTag + \"</ul></nav>\");\n\t}\n\n}", "function insertSelectedObject(obj_title, obj_id, obj_class, obj_permalink, field, blog_id) {\n // Check if this is a reciprocal association, or just a standard Selected\n // Entry/Page.\n if ( jQuery('input#'+field+'.reciprocal-object').length ) {\n // If a reciprocal association already exists, we need to delete it\n // before creating a new association.\n if ( jQuery('input#'+field+'.reciprocal-object').val() ) {\n deleteReciprocalAssociation(\n field,\n jQuery('input#'+field+'.reciprocal-object').val()\n );\n createReciprocalAssociation(\n obj_title,\n obj_id,\n obj_class,\n obj_permalink,\n field,\n blog_id\n );\n }\n // No existing association exists, so just create the new reciprocal\n // entry association.\n else {\n createReciprocalAssociation(\n obj_title,\n obj_id,\n obj_class,\n obj_permalink,\n field,\n blog_id\n );\n }\n }\n // This is just a standard Selected Entries or Selected Pages insert.\n else {\n // Create a list item populated with title, edit, view, and remove links.\n var $li = createObjectListing(\n obj_title,\n obj_id,\n obj_class,\n obj_permalink,\n blog_id\n );\n\n // Insert the list item with the button, preview, etc into the field area.\n jQuery('ul#custom-field-selected-objects_'+field)\n .append($li)\n\n var objects = new Array();\n objects[0] = jQuery('input#'+field).val();\n objects.push(obj_id);\n jQuery('input#'+field).val( objects.join(',') );\n }\n}", "function Entry (entryObject) {\n this.title = entryObject.title;\n this.date = entryObject.date;\n this.category = entryObject.category;\n this.mood = entryObject.mood;\n this.text = entryObject.text;\n this.author = entryObject.author || 'Stephanie Lingwood';\n}", "static addEntryToList(entry) {\n const list = document.querySelector('#journal-list');\n\n const row = document.createElement('tr');\n\n row.innerHTML = `\n <td>${entry.date}</td>\n <td>${entry.title}</td>\n <td>${entry.post}</td>\n `;\n\n list.appendChild(row);\n }", "function displayListings(data) {\n // Target the housing container already present in index.html\n var $housing = $('.js-housing');\n $housing.empty();\n var $container, i;\n // Loop through each listing\n for (i=0; i<data.length; i++) {\n var listing = data[i].properties;\n var coordinates = data[i].geometry.coordinates;\n // Creates a basic listing\n if (listing.sublease) {\n $container = displaySublease(listing, i, coordinates);\n //console.log(\"listing in displaysublease: \", listing);\n //console.log('sublease listing');\n } else {\n $container = displayPromo(listing, i, coordinates);\n //console.log('promo listing');\n }\n // Add the listing to the DOM\n $housing.append($container);\n }\n}", "function newObject() {\r\n dojo.byId(\"newButton\").blur();\r\n id = dojo.byId('objectId');\r\n if (id) {\r\n id.value = \"\";\r\n unselectAllRows(\"objectGrid\");\r\n loadContent(\"objectDetail.php\", \"detailDiv\", dojo.byId('listForm'));\r\n } else {\r\n showError(i18n(\"errorObjectId\"));\r\n }\r\n}", "function ListView(props) {\n const entryViews = [];\n for (let entry of props.entries) {\n entryViews.push(React.createElement(ListEntry, { entry: entry, key: entry.name, performAction: props.performAction }));\n }\n let pagination;\n if (props.numPages > 1) {\n pagination = (React.createElement(\"div\", { className: \"jp-extensionmanager-pagination\" },\n React.createElement(react_paginate_1.default, { previousLabel: '<', nextLabel: '>', breakLabel: React.createElement(\"a\", { href: \"\" }, \"...\"), breakClassName: 'break-me', pageCount: props.numPages, marginPagesDisplayed: 2, pageRangeDisplayed: 5, onPageChange: (data) => props.onPage(data.selected), containerClassName: 'pagination', activeClassName: 'active' })));\n }\n const listview = (React.createElement(\"ul\", { className: \"jp-extensionmanager-listview\" }, entryViews));\n return (React.createElement(\"div\", { className: \"jp-extensionmanager-listview-wrapper\" },\n entryViews.length > 0 ? (listview) : (React.createElement(\"div\", { key: \"message\", className: \"jp-extensionmanager-listview-message\" }, \"No entries\")),\n pagination));\n}", "function create_object ()\n\t{\n\t\tvar list = {}, \n\t\t\tareas = [], \n\t\t\tknown = {}, \n\t\t\tactions = app.menuActions.everyItem().getElements();\n\t\t\t\n\t\tfor(var i = 0; i < actions.length; i++)\n\t\t{\n\t\t\tif (!ignore (actions[i]))\n\t\t\t{\n\t\t\t\tlist[actions[i].name] = {area: actions[i].area, id: actions[i].id};\n\t\t\t\tif (!known[actions[i].area])\n\t\t\t\t{\n\t\t\t\t\tareas.push (actions[i].area);\n\t\t\t\t\tknown[actions[i].area] = true;\n\t\t\t\t}\n\t\t\t} // ignore\n\t\t}\n\t\t// Initially sort by area\n\t\tlist = sort_object (list, \"area\");\n\t\tareas.sort();\n\t\tareas.unshift('[All]'); // add [All] at the beginning of the array\n\t\treturn {list: list, areas: areas}\n\t}", "listing_of(owner) {\n return this._get(`listing?owner=${owner}`);\n }", "function listingEntryCreate (listingEntry) {\n console.log(className+\".listingEntryCreate(\"+listingEntry+\")\");\n\n debugObject(listingEntry);\n\n var listingEntryHash = commit(\"listingEntry\", listingEntry);\n\n console.log(\"listingEntryHash = \"+listingEntryHash);\n\n // On the DHT, put a link from my hash to the hash of the new post\n var me = App.Agent.Hash;\n\n commit(\"listing_links\",{ Links: [ { Base: listingEntryHash,Link: me, Tag: \"listing_source\" } ] });\n\n return listingEntryHash;\n}", "function Objects() {\n this.id = 0\n this.list = []\n this.objectTypes = {\n ship: ObjectShip,\n point: ObjectPoint,\n meteor: ObjectMeteor\n }\n\n this.create = (options) => {\n var objectType = this.objectTypes[options.type]\n var object = new objectType(options)\n\n this.list.push({\n id: this.id++,\n type: options.type,\n object: object\n })\n }\n\n this.step = () => {\n for (var o of this.list) {\n o.object.step()\n }\n }\n\n this.find = (objectType) => {\n var listObject = this.list.find(o => o.type == objectType)\n if (listObject) return listObject.object\n }\n\n this.all = (objectType) => {\n var objects = this.list.reduce((sum, num) => {\n num.type == objectType && sum.push(num.object)\n return sum\n }, [])\n\n return objects\n }\n}", "function Entry(get, list, edit, _delete) {\n let obj,\n ref,\n ref1,\n ref2,\n ref3;\n this.get = get;\n this.list = list;\n this.edit = edit;\n this.delete = _delete;\n if (this.get instanceof Object) {\n obj = this.get;\n this.get = (ref = obj.get) != null ? ref : false;\n this.list = (ref1 = obj.list) != null ? ref1 : false;\n this.edit = (ref2 = obj.edit) != null ? ref2 : false;\n this.delete = (ref3 = obj.delete) != null ? ref3 : false;\n }\n }", "renderNewList() {}", "function createList() {\n //clear all items from list\n while (dataList.firstChild) dataList.removeChild(dataList.firstChild);\n\n //add all list items from entries array\n for (let i in entries) {\n li = document.createElement('li');\n // Add text node with input values\n li.appendChild(document.createTextNode(`${entries[i].pace} on ${entries[i].date.toDateString()}`));\n dataList.appendChild(li);\n }\n}", "function showEntry(list, type, title, amount, id){\n // this is the entire html of our new entry variable\n const entry = `<li id = \"${id}\" class = \"${type}\"> \n <div class = \"entry\">- ${title}: $${amount} </div>\n <div id = \"edit\"></div>\n <div id = \"delete\"></div>\n </li>`;\n // make the newest entries appear at the top of list\n const position = \"afterbegin\";\n list.insertAdjacentHTML(position,entry);\n}", "function createList(objects) {\n\t var list = blank(),\n\t head = list,\n\t listItems = [],\n\t listTriples,\n\t triples = [];\n\t objects.forEach(function (o) {\n\t listItems.push(o.entity);\n\t appendAllTo(triples, o.triples);\n\t });\n\n\t // Build an RDF list out of the items\n\t for (var i = 0, j = 0, l = listItems.length, listTriples = Array(l * 2); i < l;) {\n\t listTriples[j++] = triple(head, RDF_FIRST, listItems[i]), listTriples[j++] = triple(head, RDF_REST, head = ++i < l ? blank() : RDF_NIL);\n\t } // Return the list's identifier, its triples, and the triples associated with its items\n\t return { entity: list, triples: appendAllTo(listTriples, triples) };\n\t }", "function makePage(){\n\n codeFellows.makeList();\n disneyLand.makeList();\n}" ]
[ "0.5590515", "0.557202", "0.55439574", "0.553152", "0.54849875", "0.53939384", "0.5362691", "0.53309596", "0.5288687", "0.52574104", "0.5232727", "0.5219121", "0.52162504", "0.52097124", "0.5176707", "0.51550287", "0.5143397", "0.5116031", "0.5105161", "0.5089701", "0.5076542", "0.5064938", "0.50615615", "0.5047265", "0.50263566", "0.50074625", "0.50028116", "0.49863073", "0.49845192", "0.49813595" ]
0.6963715
0
Create the reciprocal entry association. This happens after selecting an entry from the popup.
function createReciprocalAssociation(obj_title, recip_obj_id, obj_class, obj_permalink, field, blog_id) { jQuery('input#'+field+'.reciprocal-object').val( recip_obj_id ); // Create a list item populated with title, edit, view, and remove links. var $li = createObjectListing( obj_title, recip_obj_id, obj_class, obj_permalink, blog_id ); jQuery('ul#custom-field-reciprocal-'+field) .append($li); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "addRelationship() {\n this.mapTypeForm.reset();\n this.submitted = false;\n this.displayModal = true;\n this.isedit = false;\n }", "function create_related_entry_dialog(data) {\n let dialog = elementFactory({ type: \"div\" });\n let lst_wrap = elementFactory({ type: \"div\", css: { margin: \"5px 0 5px 0\" } });\n let src_lst = elementFactory({ type: \"div\", attr: { id: \"related-entry-src-list\" }, class: \"dialog-list\" });\n let dst_lst = elementFactory({ type: \"div\", attr: { id: \"related-entry-dst-list\" }, class: \"dialog-list\" });\n let arrow_wrap = elementFactory({ type: \"div\", attr: { id: \"arrow-container\" } });\n let arrow_r = elementFactory({ type: \"div\", attr: { id: \"arrow-wrap-r\" }, class: \"select-disable\" });\n let arrow_l = elementFactory({ type: \"div\", attr: { id: \"arrow-wrap-l\" }, class: \"select-disable\" });\n let btn_wrap = elementFactory({ type: \"div\", css: { margin: \"5px 0 5px 0\" } });\n\n // query result show\n $(dialog).append(elementFactory({\n type: \"div\",\n css: { margin: \"5px 0 5px 0\" },\n html: \"找到 \" + Object.keys(data).length + \" 個相關條目\"\n }));\n\n // append wrapper for two list and arrow\n $(lst_wrap).append(src_lst);\n $(lst_wrap).append(arrow_wrap);\n $(lst_wrap).append(dst_lst);\n $(dialog).append(lst_wrap);\n // add query result to src list\n for (let key in data) {\n if(!data.hasOwnProperty(key))\n continue;\n $(src_lst).append(elementFactory({\n type: \"div\",\n attr: { url: data[key], title: decodeURIComponent(key) },\n class: \"related-entry-item select-disable\",\n html: decodeURIComponent(key),\n on: { click: click_related_entry_item }\n }));\n }\n // arrow right\n $(arrow_r).append(elementFactory({ type: \"div\", attr: { id: \"arrow-tail-r\" } }));\n $(arrow_r).append(elementFactory({ type: \"div\", attr: { id: \"arrow-body-r\" }, html: \"加入\" }));\n $(arrow_r).append(elementFactory({ type: \"div\", attr: { id: \"arrow-head-r\" } }));\n $(arrow_wrap).append(arrow_r);\n // arrow left\n $(arrow_l).append(elementFactory({ type: \"div\", attr: { id: \"arrow-head-l\" } }));\n $(arrow_l).append(elementFactory({ type: \"div\", attr: { id: \"arrow-body-l\" }, html: \"刪去\" }));\n $(arrow_l).append(elementFactory({ type: \"div\", attr: { id: \"arrow-tail-l\" } }));\n $(arrow_wrap).append(arrow_l);\n\n // query result add and cancel button\n $(btn_wrap).append(elementFactory({\n type: \"button\",\n attr: { id: \"related-entry-dialog-cancel\" },\n class: \"btn btn-default btn-xs\",\n css: { margin: \"0 20px 0 0\" },\n html: \"取消\",\n on: { click: $.unblockUI }\n }));\n $(btn_wrap).append(elementFactory({\n type: \"button\",\n attr: { id: \"related-entry-dialog-add\" },\n class: \"btn btn-default btn-xs\",\n css: { margin: \"0 0 0 20px\" },\n html: \"加入\",\n on: { click: add_related_entry }\n }));\n $(dialog).append(btn_wrap);\n\n $.blockUI({\n message: $(dialog),\n css: { width: \"450px\", height: \"330px\", top: 'calc(50% - 165px)', left: 'calc(50% - 225px)', cursor: 'auto' }\n });\n}", "function click_related_entry_item(e) {\n let self = e.data.target;\n let key = $(self).attr(\"title\");\n let url = $(self).attr(\"url\");\n let parent;\n if ($(self).parent().attr(\"id\") === \"related-entry-src-list\")\n parent = $(\"#related-entry-dst-list\");\n else\n parent = $(\"#related-entry-src-list\");\n $(self).remove();\n $(parent).append(elementFactory({\n type: \"div\",\n attr: { url: url, title: key },\n class: \"related-entry-item select-disable\",\n html: key,\n on: { click: click_related_entry_item }\n }));\n}", "function refreshDropsWithNewAssociation(){\n console.log(\"called refreshDropsWithNewAssociation\")\n //get the parent associated drop for add existing\n let currentInAddExistingAssociatedType = O('associated_add_existing_entity_select_box_type').value\n console.log(\"type \"+currentInAddExistingAssociatedType)\n fillExistingNameAssociations(currentInAddExistingAssociatedType)\n\n\n let currentInPendingEntityType = O('pending_entity_select_box_type').value\n console.log(\"type \"+currentInPendingEntityType)\n fillPendingNameAssociations(currentInPendingEntityType)\n}", "static associate() {\n // define association here\n }", "static associate() {\n // define association here\n }", "static associate() {\n // define association here\n }", "static associate() {\n // define association here\n }", "function insertSelectedObject(obj_title, obj_id, obj_class, obj_permalink, field, blog_id) {\n // Check if this is a reciprocal association, or just a standard Selected\n // Entry/Page.\n if ( jQuery('input#'+field+'.reciprocal-object').length ) {\n // If a reciprocal association already exists, we need to delete it\n // before creating a new association.\n if ( jQuery('input#'+field+'.reciprocal-object').val() ) {\n deleteReciprocalAssociation(\n field,\n jQuery('input#'+field+'.reciprocal-object').val()\n );\n createReciprocalAssociation(\n obj_title,\n obj_id,\n obj_class,\n obj_permalink,\n field,\n blog_id\n );\n }\n // No existing association exists, so just create the new reciprocal\n // entry association.\n else {\n createReciprocalAssociation(\n obj_title,\n obj_id,\n obj_class,\n obj_permalink,\n field,\n blog_id\n );\n }\n }\n // This is just a standard Selected Entries or Selected Pages insert.\n else {\n // Create a list item populated with title, edit, view, and remove links.\n var $li = createObjectListing(\n obj_title,\n obj_id,\n obj_class,\n obj_permalink,\n blog_id\n );\n\n // Insert the list item with the button, preview, etc into the field area.\n jQuery('ul#custom-field-selected-objects_'+field)\n .append($li)\n\n var objects = new Array();\n objects[0] = jQuery('input#'+field).val();\n objects.push(obj_id);\n jQuery('input#'+field).val( objects.join(',') );\n }\n}", "function addSelfToReverseMap() {\n console.log(\"Adding participant ID: \", getParticipantID(), \"to reverse map\");\n var reverseMap = getNameToIDMap();\n var participant = gapi.hangout.getParticipantById(getParticipantID());\n reverseMap[participant.person.name] = getParticipantID();\n var reverseMapStringified = JSON.stringify(reverseMap);\n gapi.hangout.data.submitDelta( { nameToIDMapKey : reverseMapStringified\n\t\t\t\t\t });\t\n}", "addRelationship() {\n this.relationTypeForm.reset();\n this.submitted = false;\n this.displayModal = true;\n this.isedit = false;\n }", "getEntry(face) { // Used in form view\n if (node.entries == null) {\n node.entries = {};\n }\n\n let entry = node.entries[face];\n if (entry === undefined) {\n entry = createFormEntry({onEntryStateChanged});\n node.entries[face] = entry;\n }\n\n return entry;\n }", "function addRelation()\n{\n var\ttable\t\t= document.getElementById('formTable');\n var tbody\t\t= table.tBodies[0];\n var newrownum\t= tbody.rows.length;\n var\tform\t\t= this.form;\n var formElts\t= form.elements;\n \n var\ttemplate\t= document.getElementById('newRowTemplate');\n var\tparms\t\t= {\"rownum\"\t: newrownum,\n\t\t\t\t\t \"idcp\"\t: newrownum + 1,\n\t\t\t\t\t \"relation\"\t: \"\"};\t\n var newrow\t\t= createFromTemplate(template,\n\t\t\t\t\t\t\t parms,\n\t\t\t\t\t\t\t null);\n tbody.appendChild(newrow);\n}", "static associate(models) {\n models.Identification_association.hasOne(models.AssociationPage);\n models.Identification_association.belongsTo(models.Representant_legale,{\n foreignKey: 'RepresentantLegaleId'\n });\n }", "handleNewEntry() {\n\t\tlet newEntry = {\n\t\t\tQualification: '',\n\t\t\tOrganization: '',\n\t\t\tFrom: '',\n\t\t\tEnd: ''\n\t\t}\n\t\tlet newEntryArray = this.state.entries.concat(newEntry)\n\t\tthis.setState({ entries: newEntryArray })\n\t}", "function add_related_entry() {\n $('#related-entry-dst-list div').each(function() {\n let key = $(this).html();\n let url = $(this).attr(\"url\");\n if (!window.table_wiki_list.includes(url)) {\n window.table_wiki_list.push(url);\n $(\"#wiki-table-body\").append(create_wiki_table_row({ name: key, url: url }, 1));\n }\n });\n $.unblockUI();\n}", "function populateEntryForm(entry) {\n console.log('POPULATE ENTRY with '+ entry.date + ' and ' + entry.entryId);\n //Call db with user_id and email JSON and get-entry-details action\n var userEmail = localStorage.getItem('user-email');\n var action = 'get-entry-details';\n\n\tvar jsonString = {\n user: jsonEscape(userEmail),\n action: action,\n entryId: entry.entryId\n };\n\n\tvar stringified = JSON.stringify(jsonString);\n\n //call database to grab\n getEntryDetails(stringified, 'http://howtoterminal.com/scripture-journal/db/web_service.php');\n}", "function LaserficheEntryDetails(){\n if(window.parent !== window && window.parent.webAccessApi !== undefined) {\n var id = window.parent.webAccessApi.getSelectedEntries()[0].id;\n var entryName = window.parent.webAccessApi.getSelectedEntries()[0].name;\n var entryType = window.parent.webAccessApi.getSelectedEntries()[0].entryType;\n var templateName = window.parent.webAccessApi.getSelectedEntries()[0].templateName;\n $('.entry-id input').val(id);\n $('.entryName input').val(entryName);\n $('.entryType input').val(entryType);\n $('.templateName input').val(templateName);\n\n }\n}", "function modifyRelationship() {\n\t\t\tconsole.log(\"modifyRelationship() -> AlleleFearUpdateAPI()\");\n\n\t\t\t// check if record selected\n\t\t\tif(vm.selectedIndex < 0) {\n\t\t\t\talert(\"Cannot Modify if a record is not selected.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n // skip duplicates; relationship type, marker\n var rKey = 0;\n var mKey = 0;\n var isMIduplicate = false;\n var isMInoreference = false;\n\t\t\tfor(var i=0;i<vm.apiDomain.mutationInvolves.length; i++) {\n rKey = vm.apiDomain.mutationInvolves[i].relationshipTermKey;\n mKey = vm.apiDomain.mutationInvolves[i].markerKey;\n\n if (rKey == \"\" || mKey == \"\") {\n continue\n }\n\n if (vm.apiDomain.mutationInvolves[i].refsKey == \"\") {\n isMInoreference = true;\n }\n\n\t\t\t for(var j=i+1;j<vm.apiDomain.mutationInvolves.length; j++) {\n if (\n vm.apiDomain.mutationInvolves[j].relationshipTermKey == rKey\n && vm.apiDomain.mutationInvolves[j].markerKey == mKey\n ) { \n vm.apiDomain.mutationInvolves[j].processStatus = \"x\";\n isMIduplicate = true;\n }\n }\n }\n //if (isMIduplicate) {\n //alert(\"Mutation Involves: duplicate found; the duplicate will be skipped.\");\n //}\n if (isMInoreference) {\n alert(\"MI: Reference is required.\");\n return;\n }\n \n // skip duplicates; organism, marker\n var oKey = 0;\n var mKey = 0;\n var isECduplicate = false;\n var isECnoreference = false;\n\t\t\tfor(var i=0;i<vm.apiDomain.expressesComponents.length; i++) {\n oKey = vm.apiDomain.expressesComponents[i].organismKey;\n mKey = vm.apiDomain.expressesComponents[i].markerKey;\n\n if (oKey == \"\" || mKey == \"\") {\n continue\n }\n\n if (vm.apiDomain.expressesComponents[i].refsKey == \"\") {\n isECnoreference = true;\n }\n\n\t\t\t for(var j=i+1;j<vm.apiDomain.expressesComponents.length; j++) {\n if (\n vm.apiDomain.expressesComponents[j].organismKey == oKey\n && vm.apiDomain.expressesComponents[j].markerKey == mKey\n ) { \n vm.apiDomain.expressesComponents[j].processStatus = \"x\";\n isECduplicate = true;\n }\n }\n }\n //if (isECduplicate) {\n //alert(\"Expresses Components: duplicate found; the duplicate will be skipped.\");\n //}\n if (isECnoreference) {\n alert(\"EC: Reference is required.\");\n return;\n }\n\n // skip duplicates; organism, marker\n var oKey = 0;\n var mKey = 0;\n var isDCduplicate = false;\n var isDCnoreference = false;\n\t\t\tfor(var i=0;i<vm.apiDomain.driverComponents.length; i++) {\n oKey = vm.apiDomain.driverComponents[i].organismKey;\n mKey = vm.apiDomain.driverComponents[i].markerKey;\n\n if (oKey == \"\" || mKey == \"\") {\n continue\n }\n\n if (vm.apiDomain.driverComponents[i].refsKey == \"\") {\n isDCnoreference = true;\n }\n\n\t\t\t for(var j=i+1;j<vm.apiDomain.driverComponents.length; j++) {\n if (\n vm.apiDomain.driverComponents[j].organismKey == rKey\n && vm.apiDomain.driverComponents[j].markerKey == mKey\n ) { \n vm.apiDomain.driverComponents[j].processStatus = \"x\";\n isDCduplicate = true;\n }\n }\n }\n //if (isDCduplicate) {\n //alert(\"Driver Components: duplicate found; the duplicate will be skipped.\");\n //}\n if (isDCnoreference) {\n alert(\"DC: Reference is required.\");\n return;\n }\n\n\t\t\tpageScope.loadingStart();\n\n\t\t\tAlleleFearUpdateAPI.update(vm.apiDomain, function(data) {\n\t\t\t\tif (data.error != null) {\n\t\t\t\t\talert(\"ERROR: \" + data.error + \" - \" + data.message);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tloadObject();\n\t\t\t\t}\n\t\t\t\tpageScope.loadingEnd();\n\t\t\t}, function(err) {\n\t\t\t\tpageScope.handleError(vm, \"API ERROR: AlleleFearUpdateAPI.update\");\n\t\t\t\tpageScope.loadingEnd();\n\t\t\t});\n\t\t}", "function createEntry() {\n var js = checkCommon();\n if (!js) {\n return;\n }\n\n\n js['type'] = 'entry';\n\n var introduction = document.getElementsByClassName(\"introduction-p\")[0].innerHTML;\n introduction = introduction.trimLeft().trimRight();\n if (introduction.length === 0 || introduction === \"填写简介 Fill Introduction Here\") {\n alert(\"Please fill in the introduction.\");\n return;\n }\n js['introduction'] = introduction;\n\n var subsecs = document.getElementsByClassName(\"a-group\");\n var subsections = [];\n for (var i = 0; i < subsecs.length; i++) {\n var subsec = packSubSection(subsecs[i]);\n if (!subsec) {\n return;\n }\n subsections.push(subsec);\n }\n if (subsections.length === 0) {\n alert(\"Please fill in at least one subsection.\");\n return;\n }\n js['content'] = subsections;\n\n var refs = document.getElementsByClassName(\"entry-ref-list\")[0].childNodes;\n var refrences = [];\n var count = 0;\n for (var i = 0; i < refs.length; i++) {\n if (refs[i].tagName === \"LI\") {\n var value = refs[i].innerHTML;\n value = value.trimRight().trimLeft();\n if (value.length === 0 || value === \"来源 Recourse\") {\n continue;\n }\n count++;\n refrences.push(value);\n }\n }\n if (count === 0) {\n alert(\"Please have at least one reference.\");\n return;\n }\n js[\"reference\"] = refrences;\n\n var arr_str_ss = [];\n for (var i = 0; i < js['content'].length; i++) {\n arr_str_ss.push(JSON.stringify(js['content'][i]['content']));\n }\n\n $.ajax({\n url: '../../backend/entry-create-php.php',\n data: {'js': JSON.stringify(js), 'str_contents': arr_str_ss},\n type: 'POST',\n success: function (response) {\n if (response.substr(0,3) === \"set\") {\n var id = Number(response.substr(4));\n var form = document.createElement('form');\n form.setAttribute(\"action\",\"../view/entry-view.php\");\n form.setAttribute(\"method\", \"POST\");\n var input = document.createElement('input');\n input.setAttribute(\"type\", \"text\");\n input.setAttribute(\"name\", \"id\");\n input.setAttribute(\"value\", id + \"\");\n var sub = document.createElement('input');\n sub.setAttribute(\"type\", \"submit\");\n form.append(input);\n form.append(sub);\n document.body.append(form);\n form.submit();\n } else {\n alert(response);\n }\n }\n });\n\n}", "function buildNewEntryButton(journalSelf, entrySelf){\n\tvar button = document.createElement(\"button\");\n\tvar buttonLabel = document.createTextNode(\"Add Entry\");\n\tbutton.appendChild(buttonLabel);\n\n\tbutton.addEventListener('click', function(event){\t\n\t\tvar entriesData = new EntriesData ();\n\t\tvar entriesRelation = currentJournal.data.relation(\"userEntries\");\n\t\tparseInt(currentNumEntries, 10);\n\t\tcurrentNumEntries++;\n\t\tvar newEntryTitle = \"Entry\" + currentNumEntries;\n\t\tnewEntryTitle.toString();\n\t\t\n\t\tentriesData.save({\n\t\t\tentryTitle: newEntryTitle,\n\t\t\tentryText: \"\"\n\t\t}, \n\t\t{\n\t\t\tsuccess: function(results){\n\t\t\t\tconsole.log(\"Created new entry\");\n\t\t\t\tentriesRelation.add(entriesData);\n\t\t\t\tcurrentEntry = entrySelf;\n\t\t\t\tcurrentEntryIndex = 0;\n\t\t\t\tcurrentJournal.data.save(null, {\n\t\t\t\t\tsuccess: function (results){\n\t\t\t\t\t\trefreshEntriesSection(journalSelf, entrySelf);\n\t\t\t\t\t},\n\t\t\t\t\terror:function(error){\n\t\t\t\t\t\talert(\"Something went wrong: error is \" + error.message);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t\terror: function(error){\n\t\t\t\tconsole.log(\"Error creating new entry. Error: \" + error);\n\t\t\t}\n\t\t});\n\n\t});\n\tnewEntryButton.appendChild(button);\n}", "function createItemMirrorFromGroupingItem(event) {\n var itemMirror = event.data.itemmirror;\n var GUID = event.data.guid;\n console.log(\"Now creating a grouping item for \" + GUID);\n itemMirror.createItemMirrorForAssociatedGroupingItem(\n GUID, function (error, newItemMirror) {\n if (error) { throw error; }\n \n newItemMirror.getGroupingItemURI(function (error, groupingItemURI) {\n listAssociations(newItemMirror, groupingItemURI);\n $('div#modalDialog button').click(function (e) {\n console.log(groupingItemURI);\n window.location.assign(DESTURL + DELIMITER + groupingItemURI);\n //window.location.reload(); RELOAD NOT REQUIRED WHEN REDIRECT FROM DIFFERENT PAGE\n });\n });\n });\n }", "function setEntries(entrList) {\r\n\t//get data table\r\n\tvar entryTable = dojo.widget.byId('entryTable');\r\n\tfor (i = 0; i < entrList.length; i++) {\r\n\t\tvar entry = {};\r\n \t\tentry.toRemove = \"<input type='checkbox' id='toRemove' name='toRemove' value='\" + entrList[i].entryId + \"'>\"\r\n \t\tentry.viewText = entrList[i].viewText;\r\n \t\tentry.refValue = entrList[i].refValue;\r\n \t\tentry.entryDescn = entrList[i].entryDescn;\r\n \t\t//the method editEntry(obj) id editEntry.js\r\n \t\tentry.entryEdit = \"<a href='#'><img id='\" + entrList[i].entryId + \"' src='../images/icons/edit_3.gif' title='\" +\r\n \t\t\t\t\t\t\t\t\t\t\t imgTitle + \"' onclick='editEntry(this)'/></a>\";\r\n \t\tentries.add(entry);\r\n\t}\r\n\tentryTable.store.setData(entries.toArray());\r\n\tentries.clear();\r\n}", "function clickedDuplicate()\n{\n\tvar selectedObj = dw.databasePalette.getSelectedNode();\n\tif (selectedObj && selectedObj.objectType==\"Connection\")\n\t{\n\t\tvar connRec = MMDB.getConnection(selectedObj.name);\n\t\tif (connRec)\n\t\t{\n\t\t\tMMDB.popupConnection(connRec,true);\n\t\t\tdw.databasePalette.refresh();\n\t\t}\n\t}\n}", "function refreshNewEntrySection(entryTitle, entriesData){\n\tcurrentEntry.buildEditEntry(entryTitle, entriesData);\n}", "function prntAssoc(error, displayText, GUID, itemMirror){\n if (error) {\n throw error;\n }\n \n itemMirror.isAssociatedItemGrouping(GUID, function(error, isGroupingItem){\n if (isGroupingItem) {\n var $thisAssoc;\n $thisAssoc = $('<li>', {'text': \" \" + displayText});\n $thisAssoc.prepend($('<span>', {class:'glyphicon glyphicon-folder-close'}));\n $thisAssoc.bind(\"click\",{guid:GUID, itemmirror:itemMirror},createItemMirrorFromGroupingItem);\n $('#modalDialog div.modal-body ul').append($thisAssoc);\n }\n });\n \n }", "function clickEntry() {\n //alert($(\".LaneAssign\").data(\"id\"));\n //alert($(this).data(\"id\"));\n ////$(\"#themodal\").modal(\"show\");\n\n //$(this).effect('explode', 500, function() {\n //\t$(this).remove();\n //});\n return false;\n }", "function prepairNewEntries(container, opt) {\n\n container.find('>.mega-entry-added').each(function (i) {\n var ent = $(this);\n if (!ent.hasClass('tp-layout')) {\n\n ent.removeClass('tp-layout-first-item').removeClass('tp-layout-last-item').removeClass('very-last-item');\n ent.addClass(\"tp-notordered\")\n ent.wrapInner('<div class=\"mega-entry-innerwrap\"></div>');\n //ent.find('.mega-socialbar').appendTo(ent)\n var iw = ent.find('.mega-entry-innerwrap')\n /*if (opt.ie) {\n iw.append('<img class=\"ieimg\" src='+ent.data(\"src\")+'>');\n } else {*/\n iw.css({\n 'background': 'url(' + ent.data(\"src\") + ')',\n 'backgroundPosition': '50% 49%',\n 'backgroundSize': 'cover',\n 'background-repeat': 'no-repeat'\n });\n //}\n\n // LET ACT ON THE CLICK ON ITEM SOMEWAY\n ent.find('.mega-show-more').each(function () {\n var msm = $(this);\n\n // SAVE THE ID OF THE mega-entry WHICH IS CORRESPONDING ON THE BUTTON\n msm.data('entid', ent.attr('id'));\n\n // HANDLING OF THE CLICK\n msm.click(function () {\n var msm = $(this);\n var ent = container.find('#' + msm.data('entid'));\n ent.addClass(\"mega-in-detailview\");\n opt.detailview = \"on\";\n\n });\n\n });\n }\n });\n\n\n }", "function OnPrimaryGirders_Change( e )\r\n{\r\n Alloy.Globals.ShedModeInfrastructure[\"PRIMARY_GIRDERS\"] = e.id ;\r\n}", "function addExistingRelationshipToForm(relationship) {\n var renderControlAlias;\n var json;\n\n if (relationship) {\n\n renderControlAlias = spFormBuilderService.getRelationshipRenderControlAlias(relationship);\n\n if (renderControlAlias) {\n /////\n // Construct a JSON structure.\n /////\n json = {\n typeId: renderControlAlias,\n 'console:relationshipToRender': relationship.getEntity(),\n 'console:renderingOrdinal': jsonInt(),\n 'console:renderingWidth': jsonInt(),\n 'console:renderingHeight': jsonInt(),\n 'console:renderingBackgroundColor': 'white',\n 'console:renderingHorizontalResizeMode': jsonLookup('console:resizeAutomatic'),\n 'console:renderingVerticalResizeMode': jsonLookup('console:resizeAutomatic'),\n };\n\n if (relationship.isReverse) {\n json['console:isReversed'] = !!relationship.isReverse();\n }\n\n if (renderControlAlias === 'console:tabRelationshipRenderControl') {\n json['console:renderingHorizontalResizeMode'] = jsonLookup('console:resizeSpring');\n json['console:renderingVerticalResizeMode'] = jsonLookup('console:resizeSpring');\n }\n\n handleDataPath(json);\n\n return spEntity.fromJSON(json);\n }\n }\n\n return undefined;\n }" ]
[ "0.5368761", "0.5305341", "0.5257124", "0.5232171", "0.51533616", "0.51533616", "0.51533616", "0.51533616", "0.5139111", "0.51008296", "0.50781304", "0.5073649", "0.5039997", "0.5020927", "0.5015054", "0.496429", "0.4951728", "0.4947675", "0.49365643", "0.49352273", "0.48883557", "0.4879358", "0.48743466", "0.4869813", "0.4853531", "0.4848582", "0.4836825", "0.48355597", "0.48325005", "0.48260257" ]
0.6117439
0
Unlink the selected entry from the current entry for a Reciprocal Association.
function deleteReciprocalAssociation(field, recip_obj_id) { var type = jQuery('#entry_form input[name=_type]').val(); jQuery.get( CMSScriptURI + '?__mode=unlink_reciprocal', { 'recip_field_basename': field, 'recip_entry_id': recip_obj_id, 'cur_entry_id': jQuery('input[name=id]').val(), 'recip_obj_type': type }, function(data) { jQuery('#'+field+'_status').html(data.message).show(500); // The association was successfully deleted from the database, // so delete the visible data. if (data.status == 1) { jQuery('input#'+field).val(''); jQuery('ul#custom-field-reciprocal-'+field).children().remove(); setTimeout(function() { jQuery('#'+field+'_status').hide(1000) }, 7000); } }, 'json' ); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "unlink(kcLink) {\n let i = this.kcLinks.indexOf(kcLink);\n this.kcLinks.splice(i,1);\n if (this === kcLink.outPoint) {\n // this is a required docking point and someone just removed the link :(\n this.courseObject.requiredWasUnlinked(this);\n }\n }", "unlink(cell){\n if (this.linked(cell)){\n for(var i=0; i<this.noLinks; i++){\n if (cell.id == this._linkIds[i]){\n this.linkIds.splice(i,1) ;\n delete this.links[cell.tag] ;\n break ;\n }\n }\n cell.unlink(this) ;\n }\n }", "unregister(element) {\n const set = this.getSet(element.name);\n set.set.delete(element);\n set.ordered = null;\n if (set.selected == element) {\n set.selected = null;\n }\n }", "removeLinkedResourceFromState(resourceObj) {\n const linkedResources = _.reject(this.state.linkedResources, linkedResource => linkedResource.id === resourceObj.id);\n this.setState({ linkedResources });\n this.setSearchResultDisplay(resourceObj.id, true);\n }", "function removeAssocRow( table, r ){\n\tvar trs = table.getElementsByTagName( 'tr' );\n\tvar tr = trs[r];\n\ttable.removeChild( tr );\n\tfixAssocTable( table );\n}", "clearEntry() {\n this._operation.pop();\n this.setLastNumberToDisplay();\n }", "clearEntry() {\n this._operation.pop();\n this.lastNumberToDisplay();\n }", "function unjoinObject(table, primaryid, primaryobjectid, secondaryid, secondaryobjectid, callback) {\n\tpg.connect(connectionString,\n\t\tfunction (error, database, done) {\n\t\t\tif (error) return callback(error);\n\t\t\tvar condition = map(primaryid, primaryobjectid) + ' AND ' +\n\t\t\t\tmap(secondaryid, secondaryobjectid);\n\t\t\tvar querystring = deleteFrom(table, condition);\n\t\t\tquery(database, done, querystring,\n\t\t\t\tfunction (error, result) {\n\t\t\t\t\tif (error) return callback(error);\n\t\t\t\t\treturn callback(SUCCESS, secondaryobjectid);\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t);\n}", "unenroll() {\r\n return super._unenroll(new core.Credential(core.Credential.ProximityCard));\r\n }", "function removeLink(editor) {\n editor.focus();\n editor.addUndoSnapshot(function (start, end) {\n editor.queryElements('a[href]', 1 /* OnSelection */, roosterjs_editor_dom_1.unwrap);\n editor.select(start, end);\n }, \"Format\" /* Format */);\n}", "function unSetReference(searchList, repList)\n {\n if (repList.options.length > 0)\n {\n\t repList.options[0].selected = 1;\n\t moveOptions (repList, searchList);\n }\n }", "unsubscribe(instance) {\n if (this._relation.aggregationKind === histria_utils_1.AGGREGATION_KIND.composite) {\n this._value = undefined;\n }\n }", "removeCompletelyFromInverse() {\n if (!this.inverseKey) {\n return;\n }\n\n // we actually want a union of members and canonicalMembers\n // they should be disjoint but currently are not due to a bug\n var seen = Object.create(null);\n var internalModel = this.internalModel;\n\n var unload = inverseInternalModel => {\n var id = Ember.guidFor(inverseInternalModel);\n\n if (seen[id] === undefined) {\n var relationship = inverseInternalModel._relationships.get(this.inverseKey);\n relationship.removeCompletelyFromOwn(internalModel);\n seen[id] = true;\n }\n };\n\n this.members.forEach(unload);\n this.canonicalMembers.forEach(unload);\n\n if (!this.isAsync) {\n this.clear();\n }\n }", "function deletePerson2(link) {\n var person = link.parentNode.parentNode;\n document.getElementById('tblPerson').removeChild(person);\n}", "unLink() {\n if (!this.isValid()) {\n return;\n }\n const selection = window.getSelection();\n\n if (selection && !selection.toString()) {\n let elementToUnwrap;\n const baseNode = selection.baseNode;\n if (baseNode && baseNode.nodeType === 3 && baseNode.parentElement) {\n elementToUnwrap = baseNode.parentElement;\n }\n if (baseNode && baseNode.nodeType === 1) {\n elementToUnwrap = elementToUnwrap.__closest(\"a\");\n }\n if (elementToUnwrap) {\n elementToUnwrap.unwrap();\n }\n return null;\n }\n const linkElements = Object(_services_range_service__WEBPACK_IMPORTED_MODULE_0__[\"wrapRangeWithElement\"])();\n Array.from(linkElements).forEach(r => {\n const closestATag = r.__closest(\"a\");\n if (closestATag) {\n var a = Object(_utilis_splitHTML__WEBPACK_IMPORTED_MODULE_2__[\"splitHTML\"])(r, closestATag, {\n tag: \"a\"\n })\n if (a) {\n a.center.unwrap();\n }\n }\n Array.from(r.querySelectorAll(\"a\")).forEach(a => {\n a.unwrap();\n });\n r.unwrap();\n });\n const { firstFlag, lastFlag } = Object(_services_range_service__WEBPACK_IMPORTED_MODULE_0__[\"setSelectionFlags\"])(linkElements[0], linkElements[linkElements.length - 1]); //Set Flag at last\n Object(_services_range_service__WEBPACK_IMPORTED_MODULE_0__[\"setSelectionBetweenTwoNodes\"])(firstFlag, lastFlag);\n }", "revertContact() {\n this.getContact().restore();\n }", "function destroyRelationship(rel) {\n rel.internalModelDidDematerialize();\n\n if (rel._inverseIsSync()) {\n // disconnect the graph so that the sync inverse relationship does not\n // prevent us from cleaning up during `_cleanupOrphanedInternalModels`\n rel.removeAllInternalModelsFromOwn();\n rel.removeAllCanonicalInternalModelsFromOwn();\n }\n}", "unenroll() {\r\n return super._unenroll(new core.Credential(core.Credential.Face));\r\n }", "disassociateFrom (context, key) {\n return ideaAdapter.disassociateFromIdea(key)\n }", "unshareLink(kind, shareId) {\r\n return this.clone(SharePointQueryableShareable, null).unshareLink(kind, shareId);\r\n }", "function Ur(t){delete Gr[t]}", "unshareLink(kind, shareId) {\r\n const dependency = this.addBatchDependency();\r\n return this.getShareable().then(shareable => {\r\n dependency();\r\n return shareable.unshareLink(kind, shareId);\r\n });\r\n }", "unshareLink(kind, shareId = \"00000000-0000-0000-0000-000000000000\") {\r\n return this.clone(SharePointQueryableShareable, \"unshareLink\").postCore({\r\n body: jsS({ linkKind: kind, shareId: shareId }),\r\n });\r\n }", "function eraseOne (attraction) {\n\t\t\tattraction.eraseMarker().eraseItineraryItem();\n\t\t}", "unlink() {\n let pos;\n let inode = this.inputNode;\n let onode = this.outputNode;\n\n if (!(inode && onode)) {\n return;\n }\n\n (pos = inode.edges.indexOf(this)) > -1 && inode.edges.splice(pos, 1);\n (pos = onode.edges.indexOf(this)) > -1 && onode.edges.splice(pos, 1);\n (pos = inode.outputEdges.indexOf(this)) > -1 &&\n inode.outputEdges.splice(pos, 1);\n (pos = onode.inputEdges.indexOf(this)) > -1 &&\n onode.inputEdges.splice(pos, 1);\n\n if (this.duplex) {\n (pos = inode.inputEdges.indexOf(this)) > -1 &&\n inode.inputEdges.splice(pos, 1);\n (pos = onode.outputEdges.indexOf(this)) > -1 &&\n onode.outputEdges.splice(pos, 1);\n }\n\n this.inputNode = null;\n this.outputNode = null;\n\n this.duplex = false;\n\n return true;\n }", "detachFromRecurringEvent() {\n const\n me = this,\n // For access further down, breaking the link involves engine if trying to get the occurrenceDate later,\n // resulting in the wrong date\n { recurringTimeSpan, occurrenceDate, startDate } = me;\n\n // Break the link\n me.recurringTimeSpan = null;\n\n // The occurrenceDate is injected into the data when an occurrence is created.\n // the recurringTimeSpan's afterChange will remove any cache occurrence\n // for this date; see above\n recurringTimeSpan.addExceptionDate(occurrenceDate);\n\n // If we still have a recurrenceRule, we're being promoted to be a new recurring event.\n // The recurrence setter applies the rule immediately to occurrences, so this will\n // always be correct.\n if (me.recurrenceRule) {\n // The RecurrenceModel removes occurrences and exceptions after this date\n recurringTimeSpan.recurrence.endDate = DateHelper.add(startDate, -1, 'minute');\n }\n }", "function pop() {\n model.data.pop();\n $.update(model, model.__ref);\n }", "function detachFromAce(ace) {\n\n }", "function unmatch(row) {\n //Get info\n let leftInfo = getSelectedLeftInfo(row);\n let rightEmail = row[rightEmailColumn.key];\n //Get Cross indecies\n let rightInLeftIndex = leftInfo.value.indexOf(rightEmail);\n //Unmatch logic\n leftInfo.value.splice(rightInLeftIndex, 1)\n //Write to google sheets\n writeToLeftGoogleSheet(leftInfo)\n }", "removeCloneLinkFromSection() {\n const cloneLinkParentElem = this.cloneWrapperElem;\n cloneLinkParentElem.parentNode.removeChild(cloneLinkParentElem);\n }" ]
[ "0.5946615", "0.57622755", "0.55962974", "0.5592985", "0.5504511", "0.54269713", "0.5403657", "0.536653", "0.53381896", "0.5303855", "0.52463424", "0.5215935", "0.52037936", "0.5190934", "0.51818377", "0.5181754", "0.5165549", "0.5155353", "0.5128827", "0.5123988", "0.5067149", "0.50582546", "0.5048223", "0.50351655", "0.50326896", "0.50147283", "0.50007683", "0.4982292", "0.4980213", "0.49739078" ]
0.58791316
1
MultiUse SingleLine Text Group
function addSingleLineTextGroup(parent,field_name) { var num = jQuery('#' + parent + ' ul').size(); jQuery('#'+field_name+'_multiusesinglelinetextgroupcf_invisible-field').clone().appendTo('#' + parent); // Switch to display:block so that the field is visible. jQuery('#' + parent + ' .cf-text-group').css('display', 'block'); // The text input field has "_invisible" appended so that it isn't // inadvertently saved. Remove that trailing identifier so that the // field can be properly used. jQuery('#' + parent + ' ul.cf-text-group input[type=text]').each(function(index) { var name = jQuery(this).attr('name'); name = name.replace(/_invisible$/, ''); var name = jQuery(this).attr('name', name); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function addGroupText() {\n\tif (groupText) { groupText.destroy(); }\n\tgroupText = game.add.group();\n\treturn groupText;\n}", "function multiLineText(text, x, y, width, height) {\n return '<switch>\\n' +\n '<foreignObject x=\"' + x + '\" y=\"' + y + '\" width=\"' + width + '\" height=\"' + height + '\">\\n' +\n '<p xmlns=\"http://www.w3.org/1999/xhtml\">' + text + '</p>\\n' +\n '</foreignObject>\\n' +\n '<text x=\"' + x + '\" y=\"' + y + '\">' + text + '</text>\\n' +\n '</switch>\\n'\n}", "function drawText$1(element) {\n\t var group = new Group();\n\t nodeInfo._clipbox = false;\n\t nodeInfo._matrix = Matrix.unit();\n\t nodeInfo._stackingContext = {\n\t element: element,\n\t group: group\n\t };\n\t pushNodeInfo(element, getComputedStyle$1(element), group);\n\t if (element.firstChild.nodeType == 3 /* Text */) {\n\t // avoid the penalty of renderElement\n\t renderText(element, element.firstChild, group);\n\t } else {\n\t _renderElement(element, group);\n\t }\n\t popNodeInfo();\n\t return group;\n\t}", "generateMultilineHTMLfromString(text) {\n if (isNullOrUndefined(text)) {\n return \"\";\n }\n\n let spl = text.split(\"\\n\");\n if (spl.length == 1) {\n return text;\n } else {\n let output = \"\";\n for (let i = 0; i < spl.length; i++) {\n output += \"<div>\" + spl[i] + \"</div>\";\n }\n return output;\n }\n }", "function breakLines(text){\n let multiLineName = {\n first : \"\",\n second : \"\"\n };\n\n let splitedText = text.split(\" \");\n if (splitedText.length > 2) {\n for (var i = 0; i < 2; i++) {\n if (i > splitedText.length) { //??\n break;\n }\n multiLineName.first = multiLineName.first+splitedText[i]+\" \";\n }\n multiLineName.first = multiLineName.first.slice(0, -1);\n\n for (i = 2; i < splitedText.length; i++) {\n multiLineName.second = multiLineName.second+splitedText[i]+\" \";\n }\n multiLineName.second = multiLineName.second.slice(0, -1);\n\n }\n else {\n multiLineName.first = text;\n multiLineName.second = \"\";\n }\n return multiLineName;\n }", "function joinText() {\n utilitymanager_1.um.utilityManager({\n utilType: utilitymanager_1.um.TIXUtilityType.utInTransform,\n sp: utilitymanager_1.um.TIXSelPolicy.All,\n pat: /\\n/g,\n repl: '',\n });\n }", "function renderEachLine() {\n return _.map(textArray, (eachLine, i) => {\n return <span key={i} >{eachLine}<br/></span>;\n });\n }", "function wrap(textObj, width) {\n textObj.each(function() {\n var textLineObj = d3.select(this);\n var text = textLineObj.text().replace(\"\\n\",\" **newline** \");\n var words = text.split(/\\s+/).reverse(),\n word,\n line = [],\n lineNumber = 0,\n lineHeight = 1.1, // ems\n y = textLineObj.attr(\"y\"),\n dy = parseFloat(textLineObj.attr(\"dy\")),\n tspan = textLineObj.text(null).append(\"tspan\").attr(\"x\", textLineObj.attr(\"x\")).attr(\"y\", y);\n while (word = words.pop()) {\n var newline = (word != \"**newline**\");\n if(newline) line.push(word);\n else word = \"\";\n tspan.text(line.join(\" \"));\n if (tspan.node().getComputedTextLength() > width || word == \"**newline**\") {\n line.pop();\n tspan.text(line.join(\" \"));\n line = [word];\n tspan = textLineObj.append(\"tspan\").attr(\"x\", textLineObj.attr(\"x\")).attr(\"y\", y).attr(\"dy\", ++lineNumber * lineHeight + dy + \"em\").text(word);\n //console.log(tspan);\n }\n }\n //console.log(\"wrap done: \"+text.text());\n });\n}", "function NewlineText(props) {\n const text = props.text;\n return text.split('\\n').map(str => <p>{str}</p>);\n }", "function wrapText(circles, labeller) {\n return function() {\n var text = d3Selection.select(this),\n data = text.datum(),\n width = circles[data.sets[0]].radius || 50,\n label = labeller(data) || '';\n\n var words = label.split(/\\s+/).reverse(),\n maxLines = 3,\n minChars = (label.length + words.length) / maxLines,\n word = words.pop(),\n line = [word],\n joined,\n lineNumber = 0,\n lineHeight = 1.1, // ems\n tspan = text.text(null).append(\"tspan\").text(word);\n\n while (true) {\n word = words.pop();\n if (!word) break;\n line.push(word);\n joined = line.join(\" \");\n tspan.text(joined);\n if (joined.length > minChars && tspan.node().getComputedTextLength() > width) {\n line.pop();\n tspan.text(line.join(\" \"));\n line = [word];\n tspan = text.append(\"tspan\").text(word);\n lineNumber++;\n }\n }\n\n var initial = 0.35 - lineNumber * lineHeight / 2,\n x = text.attr(\"x\"),\n y = text.attr(\"y\");\n\n text.selectAll(\"tspan\")\n .attr(\"x\", x)\n .attr(\"y\", y)\n .attr(\"dy\", function(d, i) {\n return (initial + i * lineHeight) + \"em\";\n });\n };\n}", "function wrapText(circles, labeller) {\n return function () {\n var text = d3Selection.select(this),\n data = text.datum(),\n width = circles[data.sets[0]].radius || 50,\n label = labeller(data) || '';\n var words = label.split(/\\s+/).reverse(),\n maxLines = 3,\n minChars = (label.length + words.length) / maxLines,\n word = words.pop(),\n line = [word],\n joined,\n lineNumber = 0,\n lineHeight = 1.1,\n // ems\n tspan = text.text(null).append(\"tspan\").text(word);\n\n while (true) {\n word = words.pop();\n if (!word) break;\n line.push(word);\n joined = line.join(\" \");\n tspan.text(joined);\n\n if (joined.length > minChars && tspan.node().getComputedTextLength() > width) {\n line.pop();\n tspan.text(line.join(\" \"));\n line = [word];\n tspan = text.append(\"tspan\").text(word);\n lineNumber++;\n }\n }\n\n var initial = 0.35 - lineNumber * lineHeight / 2,\n x = text.attr(\"x\"),\n y = text.attr(\"y\");\n text.selectAll(\"tspan\").attr(\"x\", x).attr(\"y\", y).attr(\"dy\", function (d, i) {\n return initial + i * lineHeight + \"em\";\n });\n };\n }", "function wrap(text) {\n text.each(function() {\n let text = d3.select(this),\n words = text.text().trim().split(/[\\s\\/\\\\]+/).reverse(),\n word,\n line = [],\n lineNumber = 0,\n lineHeight = 1.5, // ems\n dy = text.attr(\"dy\"),\n dx = text.attr(\"dx\"),\n width = text.attr(\"box-width\")-padding,\n tspan = text.text(null).append(\"tspan\").attr(\"x\", 0).attr(\"dy\", lineHeight + \"em\");\n while (word = words.pop()) {\n line.push(word);\n tspan.text(line.join(\" \"));\n if (tspan.node().getComputedTextLength() > width && line.length > 1) {\n line.pop();\n tspan.text(line.join(\" \"));\n line = [word];\n tspan = text.append(\"tspan\").attr(\"x\", 5).attr(\"dy\", lineHeight + \"em\").text(word);\n }\n }\n });\n}", "function wrapText(circles, labeller) {\n return function() {\n var text = d3Selection.select(this),\n data = text.datum(),\n width = circles[data.sets[0]].radius || 50,\n label = labeller(data) || '';\n\n var words = label.split(/\\s+/).reverse(),\n maxLines = 3,\n minChars = (label.length + words.length) / maxLines,\n word = words.pop(),\n line = [word],\n joined,\n lineNumber = 0,\n lineHeight = 1.1, // ems\n tspan = text.text(null).append(\"tspan\").text(word);\n\n while (true) {\n word = words.pop();\n if (!word) break;\n line.push(word);\n joined = line.join(\" \");\n tspan.text(joined);\n if (joined.length > minChars && tspan.node().getComputedTextLength() > width) {\n line.pop();\n tspan.text(line.join(\" \"));\n line = [word];\n tspan = text.append(\"tspan\").text(word);\n lineNumber++;\n }\n }\n\n var initial = 0.35 - lineNumber * lineHeight / 2,\n x = text.attr(\"x\"),\n y = text.attr(\"y\");\n\n text.selectAll(\"tspan\")\n .attr(\"x\", x)\n .attr(\"y\", y)\n .attr(\"dy\", function(d, i) {\n return (initial + i * lineHeight) + \"em\";\n });\n };\n }", "function linebreak(text) {\n text.each(function() {\n var text = d3.select(this),\n words = text.text().split(/\\n/).reverse(),\n word,\n lineNumber = 0,\n lineHeight = 1.1, // ems\n y = text.attr(\"y\"),\n x = text.attr(\"x\"),\n dx = text.attr(\"dx\"),\n dy = 0.3 - (words.length-1)*lineHeight*0.5; //ems\n text.text(null);\n while (word = words.pop()) {\n tspan = text.append(\"tspan\").attr(\"dx\",dx).attr(\"x\", x).attr(\"y\", y).attr(\"dy\", lineNumber++ * lineHeight + dy + \"em\").text(word);\n }\n });\n }", "function wrap(text, width, heightLine) {\n text.each(function() {\n var text = d3.select(this);\n var words = text.text().split(/\\s+/).reverse();\n var word;\n var line = [];\n var lineNumber = 0;\n var lineHeight = (typeof heightLine === 'undefined' ? 1.6 : heightLine);\n var y = text.attr('y');\n var x = text.attr('x');\n var dy = parseFloat(text.attr('dy'));\n var tspan = text.text(null).append('tspan').attr('x', x).attr('y', y).attr('dy', dy + 'em');\n\n while(word = words.pop()) {\n line.push(word);\n tspan.text(line.join(' '));\n if(tspan.node().getComputedTextLength() > width) {\n line.pop();\n tspan.text(line.join(' '));\n line = [word];\n tspan = text.append('tspan').attr('x', x).attr('y', y).attr('dy', ++lineNumber * lineHeight + dy + 'em').text(word);\n }\n }\n });\n}", "function wrapText(circles, labeller) {\n return function () {\n var text = d3Selection.select(this),\n data = text.datum(),\n width = circles[data.sets[0]].radius || 50,\n label = labeller(data) || '';\n\n var words = label.split(/\\s+/).reverse(),\n maxLines = 3,\n minChars = (label.length + words.length) / maxLines,\n word = words.pop(),\n line = [word],\n joined,\n lineNumber = 0,\n lineHeight = 1.1,\n // ems\n tspan = text.text(null).append(\"tspan\").text(word);\n\n while (true) {\n word = words.pop();\n if (!word) break;\n line.push(word);\n joined = line.join(\" \");\n tspan.text(joined);\n if (joined.length > minChars && tspan.node().getComputedTextLength() > width) {\n line.pop();\n tspan.text(line.join(\" \"));\n line = [word];\n tspan = text.append(\"tspan\").text(word);\n lineNumber++;\n }\n }\n\n var initial = 0.35 - lineNumber * lineHeight / 2,\n x = text.attr(\"x\"),\n y = text.attr(\"y\");\n\n text.selectAll(\"tspan\").attr(\"x\", x).attr(\"y\", y).attr(\"dy\", function (d, i) {\n return initial + i * lineHeight + \"em\";\n });\n };\n }", "function wrapText(circles, labeller) {\n return function () {\n var text = d3Selection.select(this),\n data = text.datum(),\n width = circles[data.sets[0]].radius || 50,\n label = labeller(data) || '';\n\n var words = label.split(/\\s+/).reverse(),\n maxLines = 3,\n minChars = (label.length + words.length) / maxLines,\n word = words.pop(),\n line = [word],\n joined,\n lineNumber = 0,\n lineHeight = 1.1,\n // ems\n tspan = text.text(null).append(\"tspan\").text(word);\n\n while (true) {\n word = words.pop();\n if (!word) break;\n line.push(word);\n joined = line.join(\" \");\n tspan.text(joined);\n if (joined.length > minChars && tspan.node().getComputedTextLength() > width) {\n line.pop();\n tspan.text(line.join(\" \"));\n line = [word];\n tspan = text.append(\"tspan\").text(word);\n lineNumber++;\n }\n }\n\n var initial = 0.35 - lineNumber * lineHeight / 2,\n x = text.attr(\"x\"),\n y = text.attr(\"y\");\n\n text.selectAll(\"tspan\").attr(\"x\", x).attr(\"y\", y).attr(\"dy\", function (d, i) {\n return initial + i * lineHeight + \"em\";\n });\n };\n }", "function wrap(text, baseline) {\n text.each(function() {\n var text = d3.select(this);\n var lines = text.text().split(/\\n/);\n\n var y = text.attr('y');\n var x = text.attr('x');\n var dy = parseFloat(text.attr('dy'));\n\n text\n .text(null)\n .append('tspan')\n .attr('x', x)\n .attr('y', y)\n .attr('dy', dy + 'em')\n .attr('dominant-baseline', baseline)\n .text(lines[0]);\n\n for (var lineNum = 1; lineNum < lines.length; lineNum++) {\n text\n .append('tspan')\n .attr('x', x)\n .attr('y', y)\n .attr('dy', lineNum * 1.1 + dy + 'em')\n .attr('dominant-baseline', baseline)\n .text(lines[lineNum]);\n }\n });\n }", "expandText(begin, end, lengthInterpolate, pointsThroughLine, alreadyAdded, signe, sketchLines, distance){\n \n // var point = interpolate(begin, end, lengthInterpolate);\n var that = this;\n var angle = Math.atan2(end.y-begin.y, end.x-begin.x)\n var point = createPositionAtLengthAngle(end, angle, 100);\n // console.log('GO')\n // drawCircle(point.x, point.y, 5, 'red');\n\n // drawLine(begin.x, begin.y, point.x, point.y, 'red');\n\n\n d3.select('.standAloneLines').selectAll('.parentLine').each(function(){\n var id = d3.select(this).attr('id').split('-')[1];\n \n var insideandWhichGroup = that.props.groupLines.find(group => group.lines.find((arrayEntry)=> arrayEntry.indexOf(id) > -1))//.indexOf(idSImple) > -1);//x.id == this.guideTapped.item)\n \n // console.log(insideandWhichGroup)\n\n \n if (alreadyAdded.indexOf(id) == -1 && insideandWhichGroup == undefined){\n \n var BB = _getBBox('item-'+id);\n var originalBB = JSON.parse(JSON.stringify(BB));\n if (distance != 0){\n BB.x -= 2;\n BB.y -= 2;\n BB.width +=2;\n BB.height += 2\n } else {\n BB.x -= 15;\n BB.y -= 15;\n BB.width +=30;\n BB.height += 30\n }\n var oobbNew = [\n {'x': BB.x, 'y':BB.y},\n {'x': BB.x+ BB.width, 'y':BB.y},\n {'x': BB.x+ BB.width, 'y':BB.y + BB.height},\n {'x': BB.x, 'y':BB.y + BB.height}\n ]\n var isIntersect = lineIntersectsPolygone(begin, point, oobbNew);\n if ((originalBB.width > 400 && originalBB.height < 50) || (originalBB.height > 400 && originalBB.width <50)){\n }\n else if (isIntersect){\n // showBboxBB(BB, 'red')\n // showBbox('item-'+id, 'blue');\n alreadyAdded.push(id)\n lengthInterpolate = lengthInterpolate *2;\n\n var centerPolygon = getCenterPolygon(oobbNew);\n var rightSide = {'x': BB.x+ BB.width, 'y':BB.y+ (BB.height/2)}\n // var result = that.increasePrecisionLine(begin, end, oobbNew, pointsThroughLine,)\n if (signe == 1) that.expandText(centerPolygon, rightSide, lengthInterpolate, pointsThroughLine, alreadyAdded, signe, sketchLines, distance)//, arraySorted,oobb, iteration)\n else that.expandText(rightSide, centerPolygon, lengthInterpolate, pointsThroughLine, alreadyAdded, signe, sketchLines, distance)\n }\n }\n })\n }", "function splitLineText() {\r\n\t\t\t\t\t$('.nectar-recent-posts-single_featured.multiple_featured').each(function () {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar $slideClass = ($(this).find('.project-slides').length > 0) ? '.project-slide' : '.nectar-recent-post-slide',\r\n\t\t\t\t\t\t$slideInfoClass = ($(this).find('.project-slides').length > 0) ? '.project-info h1' : '.inner-wrap h2 a';\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$(this).find($slideClass).each(function () {\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$(this).find($slideInfoClass).each(function () {\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tvar textArr = $(this).text();\r\n\t\t\t\t\t\t\t\ttextArr = textArr.trim();\r\n\t\t\t\t\t\t\t\ttextArr = textArr.split(' ');\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t$(this)[0].innerHTML = '';\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tfor (var i = 0; i < textArr.length; i++) {\r\n\t\t\t\t\t\t\t\t\t$(this)[0].innerHTML += '<span>' + textArr[i] + '</span> ';\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$(this).find($slideInfoClass + ' > span').wrapInner('<span class=\"inner\" />');\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t}", "function textWrap (text) {\n var getText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (d) {\n return d.label;\n };\n var getCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Infinity;\n var getAnchor = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'start';\n getText = functor(getText);\n getCount = functor(getCount);\n getAnchor = functor(getAnchor);\n text.each(function (d, i) {\n var text = d3Selection.select(this),\n words = \"\".concat(getText.call(this, d, i)).split(/\\s+/).reverse(),\n word,\n lines = [],\n line = [words.pop()],\n lineHeight = 1.1,\n count = getCount.call(this, d, i),\n anchor = getAnchor.call(this, d, i),\n x = +text.attr('x'),\n y = +text.attr('y'),\n dy = parseFloat(text.attr('dy')) || 0; // clear text if the wrapper is being run for the first time\n\n if (oreq(text.html(), '').indexOf('tspan') === -1) text.text('');\n word = words.pop();\n\n while (word) {\n if (line.join(' ').length + word.length > count) {\n lines.push(line);\n line = [];\n }\n\n line.push(word);\n word = words.pop();\n }\n\n lines.push(line);\n var tspan = text.selectAll('tspan').data(lines),\n height = (lines.length - 1) * lineHeight,\n offset = anchor === 'end' ? height : anchor === 'middle' ? height / 2 : 0;\n tspan.merge(tspan.enter().append('tspan')).text(function (d) {\n return d.join(' ');\n }).attr('x', x).attr('y', y).attr('dy', function (d, i) {\n return \"\".concat(dy + i * lineHeight - offset, \"em\");\n });\n });\n}", "function wrap(text, width, heightLine) {\n text.each(function() {\n var text = d3.select(this),\n words = text.text().split(/\\s+/).reverse(),\n word,\n line = [],\n lineNumber = 0,\n lineHeight = (typeof heightLine === \"undefined\" ? 1.6 : heightLine), // ems\n y = text.attr(\"y\"),\n x = text.attr(\"x\"),\n dy = parseFloat(text.attr(\"dy\")),\n tspan = text.text(null).append(\"tspan\").attr(\"x\", x).attr(\"y\", y).attr(\"dy\", dy + \"em\");\n while (word = words.pop()) {\n line.push(word);\n tspan.text(line.join(\" \"));\n if (tspan.node().getComputedTextLength() > width) {\n line.pop();\n tspan.text(line.join(\" \"));\n line = [word];\n tspan = text.append(\"tspan\").attr(\"x\", x).attr(\"y\", y).attr(\"dy\", ++lineNumber * lineHeight + dy + \"em\").text(word);\n }\n }\n });\n}//wrap", "function armour_cg_outgroup() {\r\n if (acgcl.length > maxLineLength) {\r\n acgt += acgcl + \"\\n\";\r\n acgcl = \"\";\r\n }\r\n if (acgcl.length > 0) {\r\n acgcl += \" \";\r\n }\r\n acgcl += acgg;\r\n acgg = \"\";\r\n}", "function wrap(d){\n var sel = d3.select(this),\n tokens = sel.text().split(\"\\n\");\n\n if(tokens.length > 1) {\n var h = sel.node().getBBox().height,\n x = sel.attr('x'),\n y = sel.attr('y');\n\n sel.text(null);\n\n for(var i = 0, l = tokens.length; i < l; i++) {\n sel.append('tspan').attr('x', x).attr('y', y).attr('dy', h * i).text(tokens[i].trim());\n }\n }\n }", "wrapText(textTextureRender, text, wordWrapWidth) {\n // Greedy wrapping algorithm that will wrap words as the line grows longer.\n // than its horizontal bounds.\n let lines = text.split(/\\r?\\n/g);\n let allLines = [];\n let realNewlines = [];\n for (let i = 0; i < lines.length; i++) {\n let resultLines = [];\n let result = '';\n let spaceLeft = wordWrapWidth;\n let words = lines[i].split(' ');\n for (let j = 0; j < words.length; j++) {\n let wordWidth = textTextureRender._context.measureText(words[j]).width;\n let wordWidthWithSpace = wordWidth + textTextureRender._context.measureText(' ').width;\n if (j === 0 || wordWidthWithSpace > spaceLeft) {\n // Skip printing the newline if it's the first word of the line that is.\n // greater than the word wrap width.\n if (j > 0) {\n resultLines.push(result);\n result = '';\n }\n result += words[j];\n spaceLeft = wordWrapWidth - wordWidth;\n }\n else {\n spaceLeft -= wordWidthWithSpace;\n result += ' ' + words[j];\n }\n }\n\n if (result) {\n resultLines.push(result);\n result = '';\n }\n\n allLines = allLines.concat(resultLines);\n\n if (i < lines.length - 1) {\n realNewlines.push(allLines.length);\n }\n }\n\n return {l: allLines, n: realNewlines};\n }", "function wrap_text(text, width, token, tspanAttrs) {\n text.each(function() {\n var text = d3.select(this),\n words = text.text().split(token || /\\s+/).reverse(),\n word,\n line = [],\n lineNumber = 0,\n lineHeight = 1.1, // ems\n y = text.attr(\"y\"),\n dy = 0,\n tspan = text.text(null)\n .append(\"tspan\")\n .attr(\"x\", 0)\n .attr(\"y\", dy + \"em\")\n .attr(tspanAttrs || {});\n\n while (!!(word = words.pop())) {\n line.push(word);\n tspan.text(line.join(\" \"));\n if (width === null || tspan.node().getComputedTextLength() > width) {\n line.pop();\n tspan.text(line.join(\" \"));\n line = [word];\n tspan = text\n .append(\"tspan\")\n .attr(\"x\", 0)\n .attr(\"y\", ++lineNumber * lineHeight + dy + \"em\")\n .attr(tspanAttrs || {})\n .text(word);\n }\n }\n });\n}", "addText(text) {\n let nodes = this.top().content, last = nodes[nodes.length - 1]\n let node = this.schema.text(text, this.marks), merged\n if (last && (merged = maybeMerge(last, node))) nodes[nodes.length - 1] = merged\n else nodes.push(node)\n }", "function wrap_text(text, width, token, tspanAttrs) {\n text.each(function() {\n var text = d3.select(this),\n words = text.text().split(token || /\\s+/).reverse(),\n word,\n line = [],\n lineNumber = 0,\n lineHeight = 1.1, // ems\n y = text.attr(\"y\"),\n dy = 0,\n tspan = text.text(null)\n .append(\"tspan\")\n .attr(\"x\", 0)\n .attr(\"y\", dy + \"em\")\n .attr(tspanAttrs || {});\n\n while (!!(word = words.pop())) {\n line.push(word);\n tspan.text(line.join(\" \"));\n if (width === null || tspan.node().getComputedTextLength() > width) {\n line.pop();\n tspan.text(line.join(\" \"));\n line = [word];\n tspan = text\n .append(\"tspan\")\n .attr(\"x\", 0)\n .attr(\"y\", ++lineNumber * lineHeight + dy + \"em\")\n .attr(tspanAttrs || {})\n .text(word);\n }\n }\n });\n}", "function wrap(text,width){text.each(function(){var text=d3.select(this),words=text.text().split(/\\s+/).reverse(),word,line=[],lineNumber=0,lineHeight=1.1, // ems\n\ty=text.attr(\"y\"),dy=parseFloat(text.attr(\"dy\")),tspan=text.text(null).append(\"tspan\").attr(\"x\",0).attr(\"y\",y).attr(\"dy\",dy+\"em\");while(word=words.pop()){line.push(word);tspan.text(line.join(\" \"));if(tspan.node().getComputedTextLength()>width){line.pop();tspan.text(line.join(\" \"));line=[word];tspan=text.append(\"tspan\").attr(\"x\",0).attr(\"y\",y).attr(\"dy\",++lineNumber*lineHeight+dy+\"em\").text(word);}}});}", "wrap(text, width) {\n text.each(function () {\n const text2 = d3.select(this);\n const words = text2.text().split(/\\s+/).reverse();\n let word;\n let line = [];\n const y = text2.attr('y');\n const dy = parseFloat(text2.attr('dy'));\n\n let tspan = text2\n .text(null)\n .append('tspan')\n .attr('x', -10)\n .attr('y', y)\n .attr('dy', `${dy}em`);\n\n while ((word = words.pop())) {\n line.push(word);\n tspan.text(line.join(' '));\n\n if (tspan.node().getComputedTextLength() > width) {\n line.pop();\n tspan.text(line.join(' '));\n line = [word];\n tspan = text2\n .append('tspan')\n .attr('x', -10)\n .attr('y', y)\n .attr('dy', `${1 + dy}em`)\n .text(word);\n }\n }\n });\n }" ]
[ "0.6478826", "0.6269797", "0.62565714", "0.5962304", "0.5921791", "0.57596415", "0.57466376", "0.5706988", "0.5638568", "0.56331825", "0.5615477", "0.5566478", "0.55554104", "0.5538422", "0.5508039", "0.5506424", "0.5506424", "0.5470638", "0.5463635", "0.5440184", "0.54318166", "0.54220617", "0.54097444", "0.539637", "0.53935874", "0.5373579", "0.53649145", "0.5355985", "0.535307", "0.53489876" ]
0.6793016
0
Decamelizes a string with/without a custom separator (hyphen by default). from:
function decamelize(str, separator = '-') { return str .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2') .toLowerCase(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function _dasherize(str){return _decamelize(str).replace(/[ _]/g, '-')}", "function unhyphenate(str){\n\t str = toString(str);\n\t return str.replace(/(\\w)(-)(\\w)/g, '$1 $3');\n\t }", "function toHyphenDelimited (string) {\n return string.replace(/([a-z][A-Z])/g, function (g) {\n return g[0] + '-' + g[1];\n }).toLowerCase();\n}", "_deCamelize(_str) {\n return _str.replace(/(([A-Z])(\\w))/g, ($0, $1, $2, $3) => {\n return '-' + $2.toLowerCase() + $3;\n });\n }", "_deCamelize(_str) {\n return _str.replace(/(([A-Z])(\\w))/g, ($0, $1, $2, $3) => {\n return '-' + $2.toLowerCase() + $3;\n });\n }", "function dashify(str){\n return str.replace(/([a-z])([A-Z])/g, \"$1-$2\").toLowerCase();\n}", "function uncamelizeString(str, separator) {\n if (typeof separator == \"undefined\") {\n separator = \" \";\n }\n\n return str.replace(/[A-Z]/g, function (char) {\n return separator + char.toLowerCase();\n });\n}", "function hyphenate(str) {\n str = toString_1[\"default\"](str);\n str = unCamelCase_1[\"default\"](str);\n return slugify_1[\"default\"](str, '-');\n}", "function hyphenate(str){\n\t str = toString(str);\n\t str = unCamelCase(str);\n\t return slugify(str, \"-\");\n\t }", "function hyphenate(str) {\n\t return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n\t }", "function camelCaseToDash(string) {\n\treturn string.replace(/([\\w])([A-Z])/g,'$1-$2').toLowerCase();\n}", "function getAlphaNumericDash(s) {\n return s.replace(/[\\W_]+/g,'-')\n}", "function string_string(str) {\n\n\t//hello_word = \"hello world\", hello-world=>hello-word\n\t//hello--worlf=\n\tconsole.log(str);\n\t\n\nreturn str.replace(/^[-]/,'')\n\t\t\treplace(/--/g,\",\")\n\t\t\t.replace(/_/g,\" \");\n\n \n\n // let result = \"\";\n\n // str.split('--').forEach((each) => {\n\n // if (each.match(/[_]/)) {\n // result += '\"'+ each.replace(/[_]/g, \" \") + '\"';\n // } else {\n // result += \" \"+each;\n // }\n // })\n\n // return result.replace(/[\\s]dot/g, \" . \");\n\n}", "function camelToDash(str) {\n if (!str) return '';\n\n return str.replace(/\\W+/g, '-')\n .replace(/([a-z\\d])([A-Z])/g, '$1-$2');\n }", "function hyphenate(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n }", "function hyphenate(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n }", "function hyphenate(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n }", "function hyphenate(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n }", "function hyphenate(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n }", "function hyphenate(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n }", "function camelToDashed(str) {\n return str.replace(/\\W+/g, '-').replace(/([a-z\\d])([A-Z])/g, '$1-$2').toLowerCase();\n}", "function denormalize(str) {\n return str.replace(/\\W+/g, '-')\n .replace(/([a-z\\d])([A-Z])/g, '$1-$2').toLowerCase();\n }", "function hyphenate(str){\n str = toString(str);\n str = unCamelCase(str);\n return slugify(str, \"-\");\n }", "function hyphenateString(string) {\n return string.toLowerCase().replace(/ /g,\"-\");\n}", "function hyphenate(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n}", "function hyphenate(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n}", "function hyphenate(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n}", "function hyphenate(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n}", "function spaceToDash(text) {\n return text.trim().replace(/\\s/g, '-');\n }", "function unCamelCase(str, delimiter){\n\t if (delimiter == null) {\n\t delimiter = ' ';\n\t }\n\n\t function join(str, c1, c2) {\n\t return c1 + delimiter + c2;\n\t }\n\n\t str = toString(str);\n\t str = str.replace(CAMEL_CASE_BORDER, join);\n\t str = str.toLowerCase(); //add space between camelCase text\n\t return str;\n\t }" ]
[ "0.7354994", "0.68960834", "0.65580666", "0.65105164", "0.65105164", "0.6434672", "0.63976294", "0.63621306", "0.63453674", "0.63419646", "0.6294325", "0.6270401", "0.62457764", "0.6242554", "0.6231834", "0.6231834", "0.6231834", "0.6231834", "0.6231834", "0.6231834", "0.6225177", "0.6211138", "0.62110156", "0.6191575", "0.6167839", "0.6167839", "0.6167839", "0.6167839", "0.6164094", "0.61435413" ]
0.7090734
1
show image as icon on button
function showImageOnButton(uri) { //me.getAddImageButtonRef().setHtml('<div class="addPhotoButtonHolder"><img src="' + uri + '" class="addPhotoButtonImage"/></div>'); me.getAddImageButtonRef().setHtml('<div class="addPhotoButtonHolder" style="background:url(' + uri + '); background-size:cover; background-repeat:no-repeat; background-position:center;">&nbsp;</div>'); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function penguinIcon() {\n iconType = image[0];\n $('#status').html(\"Selected place icon is \"+'<img src=\"'+iconType+'\">');\n}", "function displayIcon(id, imgSrc){\n var elem = document.getElementById(id);\n if (elem) \n elem.src = imgSrc;\n }", "function createButton(icon) {\n const image = document.createElement('img')\n image.src = icon.src\n image.classList.add(CLASSES.ICON_IMG)\n if (icon.spinning) {\n image.classList.add(CLASSES.ICON_IMG_SPINNING)\n }\n const container = document.createElement('div')\n container.title = icon.title\n container.classList.add(CLASSES.ICON_CONTAINER)\n container.classList.add(CLASSES.ICON_CONTAINER_BUTTON)\n container.appendChild(image)\n return container\n}", "getIcon() {\n return \"document-cook\";\n }", "function showIcons() {\n\t$(this).find(\".upload_button\").show();\n\t$(this).find(\".close_button\").show();\n}", "function TB_image() {\n\tvar t = this.title || this.name ;\n\tTB_show(t,this.href,'image');\n\treturn false;\n}", "function addIcon(element){\n var image_path = \"/archibus/schema/ab-core/graphics/icons/tick-white.png\";\n var src = image_path;\n \n var img = document.createElement(\"img\");\n img.setAttribute(\"src\", src);\n img.setAttribute(\"border\", \"0\");\n \n img.setAttribute(\"align\", \"middle\");\n img.setAttribute(\"valign\", \"right\");\n \n element.appendChild(img);\n}", "function setUserLocationRequestButtonIcon(iconName) {\r\n $('#searchLocationButton').css('background-image', 'url(/static/img/ic_location_' + iconName + '.svg)');\r\n}", "function iconShow(el) {\r\n eyeIcon.style.display = \"inline-block\";\r\n}", "set type(type) {\n this.setIcon(type);\n }", "setIcon(icon){\r\n\t\tvar c = this.vc()\r\n\t\tthis.icon = icon\r\n\t\tc.innerHTML = this.inner_html()\r\n\t}", "function setIconImage(info, key) {\n var value, iconDiv, iconDivUrl, iconName;\n value = weatherMethods[info]();\n iconDiv = document.getElementById('iconDiv' + key);\n if (action.savedElements.iconName) {\n iconName = action.savedElements.iconName;\n } else {\n iconName = 'simply';\n }\n if (iconDiv) {\n iconDivUrl = 'http://junesiphone.com/weather/IconSets/' + iconName + '/' + value + '.png';\n if (iconDiv.src != iconDivUrl) {\n iconDiv.src = iconDivUrl;\n }\n }\n}", "get imageButton() {\n return {\n type: \"rich-text-editor-image\",\n };\n }", "function setIcon () {\n if ( oauth.hasToken() ) {\n chrome.browserAction.setIcon( { 'path': 'img/icon-19-on.png' } );\n } else {\n chrome.browserAction.setIcon( { 'path': 'img/icon-19-off.png' } );\n }\n}", "function attachIcon (){ \n var iconID= data.current.weather[0].icon;\n\n var iconURL= \"https://api.openweathermap.org/img/w/\" + iconID + \".png\"\n \n $('#weather-icon').attr('src', iconURL);\n $('#weather-icon').attr('alt', data.current.weather.description);\n}", "function showEditIcon() {\n $(this).append('<span class=\"glyphicon glyphicon-wrench edit\"' +\n 'aria-hidden=\"true\"></span>');\n $(this).children().last().click(editRes);\n}", "set cxIcon(type) {\n this.setIcon(type);\n }", "function setIconImage(info, key) {\n var value, iconDiv, iconDivUrl, iconName;\n value = weatherMethods[info]();\n iconDiv = document.getElementById('iconDiv' + key);\n if (action.savedElements.iconName) {\n iconName = action.savedElements.iconName;\n } else {\n iconName = 'simply';\n }\n if (iconDiv) {\n iconDivUrl = 'https://junesiphone.com/weather/IconSets/' + iconName + '/' + value + '.png';\n if (iconDiv.src != iconDivUrl) {\n var img = new Image();\n img.onload = function(){\n iconDiv.src = iconDivUrl;\n //set opacity to 1 after loaded\n iconDiv.style.opacity = 1;\n }; \n img.src = iconDivUrl;\n }\n }\n}", "setIcon(i) {\n this.icon = i;\n }", "function installImage(name, img) {\n RichTextView[name].iconUrl = '/images/' + img + '.svg';\n RichTextView[name].label = '';\n}", "get iconButton() {\n return {\n type: \"rich-text-editor-icon-picker\",\n };\n }", "setIcon (Icon) {\n _Icon = Icon\n }", "function MatIconLocation() {}", "GetTemplateActionImagesButton(){\n // Bouton Logout sous forme d'image\n const LogoutSvg = \"PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IiB2aWV3Qm94PSIwIDAgMTAwMCAxMDAwIiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCAxMDAwIDEwMDAiIHhtbDpzcGFjZT0icHJlc2VydmUiPgo8bWV0YWRhdGE+IFN2ZyBWZWN0b3IgSWNvbnMgOiBodHRwOi8vd3d3Lm9ubGluZXdlYmZvbnRzLmNvbS9pY29uIDwvbWV0YWRhdGE+CjxnPjxwYXRoIGQ9Ik03NTcuNSwxNTIuMWMzMC4xLDIyLDU2LjksNDYuOCw4MC4zLDc0LjZjMjMuNCwyNy44LDQzLjUsNTcuOCw2MC4yLDkwLjFjMTYuNywzMi4zLDI5LjQsNjYuNCwzOC4xLDEwMi40YzguNywzNiwxMy4xLDcyLjYsMTMuMSwxMDkuNmMwLDYzLjgtMTEuOSwxMjMuNy0zNS42LDE3OS42Yy0yMy43LDU1LjktNTUuOSwxMDQuNy05Ni40LDE0Ni4yYy00MC41LDQxLjUtODgsNzQuNS0xNDIuNSw5OC44QzYyMC4xLDk3Ny44LDU2MS43LDk5MCw0OTkuNSw5OTBjLTYxLjYsMC0xMTkuNi0xMi4yLTE3NC4xLTM2LjVjLTU0LjUtMjQuNC0xMDIuMi01Ny4zLTE0My05OC44Yy00MC44LTQxLjUtNzIuOS05MC4zLTk2LjQtMTQ2LjJjLTIzLjQtNTUuOS0zNS4xLTExNS44LTM1LjEtMTc5LjZjMC0zNi40LDQuMi03Mi4xLDEyLjYtMTA3LjFjOC40LTM1LDIwLjItNjguMywzNS42LTk5LjhjMTUuNC0zMS42LDM0LjUtNjEuMSw1Ny4yLTg4LjVjMjIuOC0yNy41LDQ4LjItNTIuMiw3Ni4zLTc0LjFjMTQuNy0xMSwzMC42LTE1LjEsNDcuNy0xMi40YzE3LjEsMi43LDMwLjksMTEuMyw0MS43LDI1LjdjMTAuNywxNC40LDE0LjcsMzAuNSwxMiw0OC40Yy0yLjcsMTcuOC0xMSwzMi4zLTI1LjEsNDMuMmMtNDIuMiwzMS42LTc0LjQsNzAuMy05Ni45LDExNi4zYy0yMi40LDQ2LTMzLjYsOTUuNC0zMy42LDE0OC4yYzAsNDUuMyw4LjQsODgsMjUuMSwxMjguMmMxNi43LDQwLjEsMzkuNiw3NS4xLDY4LjgsMTA1YzI5LjEsMjkuOSw2My4yLDUzLjUsMTAyLjQsNzFjMzkuMSwxNy41LDgwLjgsMjYuMywxMjUsMjYuM2M0NC4yLDAsODUuOC04LjgsMTI1LTI2LjNjMzkuMS0xNy41LDczLjMtNDEuMiwxMDIuNC03MWMyOS4xLTI5LjksNTIuMi02NC45LDY5LjMtMTA1YzE3LjEtNDAuMiwyNS42LTgyLjksMjUuNi0xMjguMmMwLTUzLjUtMTItMTA0LjEtMzYuMS0xNTEuOGMtMjQuMS00Ny43LTU3LjktODctMTAxLjQtMTE3LjljLTE0LjctMTAuMy0yMy42LTI0LjQtMjYuNi00Mi4yYy0zLTE3LjksMC41LTM0LjMsMTAuNS00OS40YzEwLTE0LjQsMjMuOC0yMy4yLDQxLjItMjYuMkM3MjYuNywxMzguMiw3NDIuNywxNDEuOCw3NTcuNSwxNTIuMUw3NTcuNSwxNTIuMXogTTQ5OS41LDUzMS45Yy0xNy40LDAtMzIuMy02LjMtNDQuNy0xOWMtMTIuNC0xMi43LTE4LjYtMjgtMTguNi00NS44Vjc1LjljMC0xNy44LDYuMi0zMy4zLDE4LjYtNDYuM2MxMi40LTEzLDI3LjMtMTkuNiw0NC43LTE5LjZjMTguMSwwLDMzLjMsNi41LDQ1LjcsMTkuNmMxMi40LDEzLDE4LjYsMjguNSwxOC42LDQ2LjN2MzkxLjJjMCwxNy44LTYuMiwzMy4xLTE4LjYsNDUuOEM1MzIuOCw1MjUuNiw1MTcuNiw1MzEuOSw0OTkuNSw1MzEuOUw0OTkuNSw1MzEuOXoiLz48L2c+Cjwvc3ZnPg==\"\n const UserConfigSvg = \"PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgaWQ9IkxheWVyXzEiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDEyOCAxMjg7IiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCAxMjggMTI4IiB4bWw6c3BhY2U9InByZXNlcnZlIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj48c3R5bGUgdHlwZT0idGV4dC9jc3MiPgoJLnN0MHtmaWxsOiM0RjRGNEY7fQoJLnN0MXtmaWxsOiNGRkZGRkY7fQo8L3N0eWxlPjxjaXJjbGUgY2xhc3M9InN0MCIgY3g9IjY0IiBjeT0iNjQiIHI9IjY0Ii8+PHBhdGggY2xhc3M9InN0MSIgZD0iTTc3LjQsNzUuM2MtMi0wLjMtMy40LTEuOS0zLjQtMy45di01LjhjMi4xLTIuMywzLjUtNS4zLDMuOC04LjdsMC4yLTMuMmMxLjEtMC42LDIuMi0yLDIuNy0zLjggIGMwLjctMi41LDAuMS00LjctMS41LTQuOWMtMC4yLDAtMC40LDAtMC43LDBsMC40LTUuOUM3OS42LDMwLjksNzMuMywyNCw2NS4zLDI0aC0yLjVjLTgsMC0xNC4zLDYuOS0xMy44LDE1LjFsMC40LDYgIEM0OS4yLDQ1LDQ5LDQ1LDQ4LjgsNDVjLTEuNiwwLjItMi4yLDIuNC0xLjUsNC45YzAuNSwxLjksMS43LDMuMywyLjgsMy45bDAuMiwzLjFjMC4yLDMuNCwxLjYsNi40LDMuNyw4Ljd2NS44YzAsMi0xLjQsMy42LTMuNCwzLjkgIEM0MS44LDc2LjgsMjcsODMuMiwyNyw5MHYxNGg3NFY5MEMxMDEsODMuMiw4Ni4yLDc2LjgsNzcuNCw3NS4zeiIvPjwvc3ZnPg==\"\n const GoToAppAdminSvg = \"PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZGFsb25lPSJubyI/Pgo8IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDIwMDEwOTA0Ly9FTiIKICJodHRwOi8vd3d3LnczLm9yZy9UUi8yMDAxL1JFQy1TVkctMjAwMTA5MDQvRFREL3N2ZzEwLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4wIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiB3aWR0aD0iMTIwMC4wMDAwMDBwdCIgaGVpZ2h0PSIxMjgwLjAwMDAwMHB0IiB2aWV3Qm94PSIwIDAgMTIwMC4wMDAwMDAgMTI4MC4wMDAwMDAiCiBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJ4TWlkWU1pZCBtZWV0Ij4KPG1ldGFkYXRhPgpDcmVhdGVkIGJ5IHBvdHJhY2UgMS4xNSwgd3JpdHRlbiBieSBQZXRlciBTZWxpbmdlciAyMDAxLTIwMTcKPC9tZXRhZGF0YT4KPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMC4wMDAwMDAsMTI4MC4wMDAwMDApIHNjYWxlKDAuMTAwMDAwLC0wLjEwMDAwMCkiCmZpbGw9IiMwMDAwMDAiIHN0cm9rZT0ibm9uZSI+CjxwYXRoIGQ9Ik04NTAwIDEyNzkzIGMtMjAzIC0xOSAtMjUyIC0yNCAtMjY0IC0yOSAtMjEgLTggLTY3IC00MDEgLTg0IC03MTgKbC03IC0xMjkgLTExMCAtMjcgYy02MCAtMTUgLTE0NCAtNDEgLTE4NSAtNTggLTEwNSAtNDMgLTMzNyAtMTU0IC0zOTcgLTE5MQotMjggLTE3IC01MyAtMzEgLTU1IC0zMSAtMyAwIC0xNTEgMTIwIC0zMjkgMjY2IC0xNzggMTQ2IC0zMzAgMjY4IC0zMzYgMjcxCi0yNCAxMCAtMjI5IC0xNjQgLTM4MiAtMzIzIC0xNDcgLTE1MiAtMzE1IC0zNjIgLTMwMyAtMzc3IDQzIC01NyAyMDcgLTI1OQozNDcgLTQyNyA5NCAtMTEzIDE3NSAtMjExIDE3OSAtMjE4IDQgLTggLTkgLTM4IC0zNCAtNzggLTY3IC0xMDYgLTE0NSAtMjcxCi0xODAgLTM3OSAtMTggLTU1IC00MyAtMTMyIC01NiAtMTcyIC0xMyAtMzkgLTI0IC03OCAtMjQgLTg2IDAgLTExIC0xOSAtMTYKLTcyIC0yMSAtMzkwIC0zNiAtNzY1IC03OSAtNzc1IC05MCAtMzEgLTMwIC01MSAtNDMyIC0zNCAtNjQ5IDEyIC0xNTEgMzUKLTMxNSA0NiAtMzI1IDQgLTUgMjk5IC0zNCA3NTcgLTc3IGw3NyAtNyA2IC00MSBjNCAtMjMgMTUgLTYyIDI1IC04NyAxMCAtMjUKMzQgLTk3IDU0IC0xNjEgMzkgLTEyMSAxMjAgLTI5MyAxODcgLTM5MyAyMiAtMzMgMzggLTY1IDM1IC03MyAtMyAtNyAtODMKLTEwNiAtMTc5IC0yMjAgLTI2NCAtMzE2IC0zNDggLTQyMyAtMzQwIC00MzYgMzQgLTYwIDE5NSAtMjQ5IDMwOCAtMzYzIDE0OQotMTUwIDM4MiAtMzQ0IDM5MyAtMzI4IDQgNiA5OSA4NiAyMTIgMTc5IDExMyA5MyAyNTAgMjA3IDMwNSAyNTQgNTUgNDggMTA3CjkyIDExNyA5OSAxNCAxMSAzMyA0IDEzMCAtNTEgMTM0IC03NiAyOTkgLTE0NCA0NTkgLTE4NyA2MyAtMTcgMTIxIC0zNSAxMjcKLTM5IDggLTUgMjMgLTEwOSA0MiAtMzAyIDMwIC0yOTMgNTcgLTUyNCA2NCAtNTQ1IDggLTIxIDMxMCAtMzcgNTY5IC0zMSAyMDYKNSA0MDcgMjQgNDIzIDM5IDIgMyAyMCAxODAgMzkgMzk0IDIwIDIxNCAzOCA0MDQgNDEgNDIyIDYgMzggNCAzNyAxNzcgODggMTQ1CjQzIDMzOCAxMjggNDU1IDIwMSA0NyAzMCA5MCA1MiA5NiA0OSA2IC0yIDY3IC01MiAxMzYgLTExMSAyMzIgLTIwMCA1MjIgLTQyNgo1MzcgLTQyMSAyNyAxMSAxMzggOTYgMjAwIDE1MyAxMjkgMTIwIDQ4MyA1MjEgNDgzIDU0NyAwIDMgLTExNCAxNDEgLTI1MiAzMDcKLTEzOSAxNjUgLTI2MyAzMTMgLTI3NSAzMjggbC0yMiAyNyA1OSAxMTQgYzc5IDE1MSAxNTYgMzQ0IDE4OSA0NzEgbDI2IDEwNAoxODUgMTcgYzEwMiA5IDI5NCAyNyA0MjcgMzkgbDI0MiAyMyA2IDI2IGMxMyA2MyAyNiAyMTkgMzEgMzgwIDkgMjM3IC0xNyA1ODIKLTQ0IDU5OSAtNyA0IC0xOTcgMjQgLTQyNCA0NSAtMjI3IDIxIC00MTYgNDAgLTQyMCA0MiAtNCAyIC0xMiAzMCAtMTggNjIgLTI3CjEzNyAtMTE1IDM2NCAtMjA2IDUzMyBsLTY1IDEyMSAzOCA0NiBjMjEgMjYgMTM5IDE3MSAyNjQgMzIzIDEyNCAxNTIgMjI5IDI4MQoyMzMgMjg4IDggMTIgLTcxIDExMyAtMjAzIDI2MCAtMTQ2IDE2MiAtNDgxIDQ1MSAtNTA0IDQzNCAtODMgLTYzIC0zODIgLTMwNQotNDg3IC0zOTQgLTc1IC02MiAtMTQyIC0xMTkgLTE1MSAtMTI2IC0xMiAtMTAgLTU0IDcgLTIyOSA5NiAtMTUzIDc2IC0yNDcKMTE2IC0zMjUgMTM5IC02MCAxOCAtMTIwIDMyIC0xMzIgMzIgLTI1IDAgLTI1IC0zIC00OSAyNTUgLTE3IDE5MSAtNjQgNjA4Ci02OCA2MTIgLTggOCAtMTI2IDIzIC0yNTIgMzIgLTEzMCAxMCAtMzcyIDEyIC00NTQgNHogbTQ1NSAtMjA5NCBjMjE3IC0zNgo0MjcgLTE1MSA2MTAgLTMzMyAxNzkgLTE3OCAyODkgLTM3NCAzMzUgLTYwMSAxMDQgLTUwMSAtOTkgLTk5OCAtNTIwIC0xMjc2Ci0xOTIgLTEyNyAtMzc4IC0xODYgLTYxNiAtMTk2IC0yMjIgLTEwIC0zODggMjQgLTU3OSAxMTcgLTIzOSAxMTcgLTQxOSAyOTMKLTU0NiA1MzQgLTk2IDE4MyAtMTM0IDM0MyAtMTMzIDU3MSAxIDI4MSA3NyA1MDcgMjQ0IDcyMyAyMTIgMjc1IDUwMCA0NDYgNzk1CjQ3MSAxMTEgOSAzMjkgNCA0MTAgLTEweiIvPgo8cGF0aCBkPSJNODUwMCAxMDUyMSBjLTM2NSAtODAgLTY2MyAtMzU5IC03NzcgLTcyNyAtMjUgLTgzIC0yNyAtMTAxIC0yNwotMjc5IC0xIC0yMDcgNCAtMjM4IDY1IC0zOTYgNjUgLTE2OSAyMzUgLTM3OCAzOTggLTQ4OCA5MCAtNjEgMjE0IC0xMTcgMzE3Ci0xNDMgMTI4IC0zMiAzNzIgLTMyIDQ5MCAwIDE0MCAzOCAyNDEgODYgMzU0IDE3MCAzMjAgMjM4IDQ3MyA1ODMgNDMwIDk3MAotMjcgMjUwIC0xMjQgNDQ4IC0zMDEgNjE3IC0xMzQgMTI4IC0yNzQgMjEwIC00NDggMjYyIC0xMTkgMzUgLTM3MSA0MyAtNTAxCjE0eiBtMzgyIC0yNTYgYzIyOCAtNDggNDQwIC0yMDkgNTM3IC00MDcgMTcgLTM1IDQxIC0xMDEgNTIgLTE0NyAxOCAtNzMgMjEKLTEwNSAxNyAtMjM1IC00IC0xMzIgLTggLTE2MSAtMzQgLTIzNiAtNzYgLTIyNyAtMjk4IC00MjkgLTU0NiAtNDk2IC03NiAtMjEKLTI5MCAtMjQgLTM1OCAtNSAtMTQ3IDQwIC0yNjcgMTEwIC0zNzQgMjE3IC00NSA0NCAtOTYgMTA2IC0xMTUgMTM3IC0yMjIgMzczCi0xMDUgODYyIDI1OSAxMDc4IDc0IDQzIDE4NiA4NyAyNjAgOTkgNzUgMTMgMjMxIDEwIDMwMiAtNXoiLz4KPHBhdGggZD0iTTQ3MTYgODQ0OCBjLTc1IC0xOTEgLTE2MiAtNDI4IC0yNTEgLTY4MCBsLTk4IC0yNzggLTEyMiAwIGMtMjMxIDAKLTU4MyAtNDcgLTc4OCAtMTA2IC03MCAtMjAgLTEyOSAtMzUgLTEzMSAtMzMgLTEgMiAtMzYgNTEgLTc3IDEwOSAtMTQwIDIwMAotNTcwIDc5MCAtNTc1IDc5MCAtMTAgMCAtMTgxIC02OCAtMjE5IC04OCAtMjIgLTExIC03NCAtMzYgLTExNSAtNTYgLTQxIC0xOQotMTIwIC02MSAtMTc1IC05NCAtNTUgLTMyIC0xNDggLTg3IC0yMDcgLTEyMiAtMTA1IC02MiAtMjUwIC0xNjYgLTM0MiAtMjQ1CmwtNDYgLTQxIDEyMCAtMjU5IGM2NyAtMTQzIDE3MSAtMzY3IDIzMiAtNDk4IGwxMTEgLTIzOCAtNzYgLTc3IGMtMTk2IC0yMDAKLTQzMyAtNTExIC01MTMgLTY3NSAtMTYgLTMyIC0zMiAtNTcgLTM3IC01NyAtNCAwIC0xNDYgMjQgLTMxNSA1NCAtMzI5IDU4Ci03NzMgMTI5IC03NzcgMTI0IC04IC04IC0xMDMgLTI0OCAtMTQwIC0zNTMgLTUxIC0xNDYgLTEzNSAtNTU4IC0xNzAgLTg0MApsLTYgLTUwIDUwOCAtMTk1IDUwOCAtMTk1IDIgLTk1IGM0IC0xNzEgMjMgLTM4MSA0NCAtNDg5IDExIC01OCAyNyAtMTQxIDM1Ci0xODMgOCAtNDMgMjYgLTExNiAzOSAtMTYzIDE0IC00NyAyNSAtOTIgMjUgLTEwMCAwIC03IC05MyAtODAgLTIwNyAtMTYxCi0xMTUgLTgxIC0zMTMgLTIyNCAtNDQxIC0zMTggLTIwOCAtMTUyIC0yMzIgLTE3MyAtMjI3IC0xOTMgMjIgLTg4IDIxNiAtNDY0CjM0NiAtNjcyIDc0IC0xMTYgMjIzIC0zMzAgMjY0IC0zNzggbDMwIC0zNCAxNzUgODEgYzE3MiA4MSA3MzYgMzM5IDc5NiAzNjUKbDMwIDE0IDEzNSAtMTI1IGMxNjkgLTE1OCAyNTMgLTIyMSA0ODIgLTM2MSAxMzggLTg0IDE4MiAtMTE2IDE4MCAtMTMwIC0xCi0xMCAtMjIgLTE0MiAtNDcgLTI5MyAtNDQgLTI2NiAtMTE2IC03NDggLTExNiAtNzczIDAgLTcgMTUgLTE4IDMzIC0yNiAyMjUKLTkwIDQyNiAtMTUyIDcxNSAtMjIwIDE5MyAtNDYgNDczIC05NCA0ODMgLTgzIDE4IDIwIDI2MSA2NTkgMzU1IDkyOSBsMzggMTEzCjE1MiAwIGMyNjIgMCA0NDcgMjYgNzEyIDEwMiAxMjIgMzQgMTQ2IDM4IDE1NyAyNyA3IC04IDE1MyAtMjEyIDMyNSAtNDU0IDE3MgotMjQyIDMxNCAtNDQyIDMxNiAtNDQzIDMgLTQgOTEgMzcgMzYxIDE3MCAxMTIgNTUgMjQzIDEzMCAzNDUgMTk3IDE0NSA5NiAzMzEKMjMzIDM4MSAyODEgMTggMTYgMTUgMjUgLTgxIDI0MSAtNTUgMTIzIC0xNTkgMzUwIC0yMzAgNTA0IGwtMTMwIDI3OSAxMTcgMTI2CmMxNjAgMTcwIDMwNSAzNjggNDA1IDU1MiAyNSA0OCA1MCA4OSA1NCA5MSA0IDIgOTUgLTExIDIwMiAtMjkgNTU5IC05NCA4ODMKLTE0NSA4OTQgLTE0MSAyMiA5IDE3OCA0NTMgMjIxIDYyNyA4IDM2IDIwIDc1IDI1IDg3IDkgMjEgNzMgMzgyIDg0IDQ3NSBsNgo0NyAtNDggMjEgYy02MiAyOCAtNDgwIDE4NiAtNzY0IDI5MCBsLTIyOCA4MyAwIDE1NiBjMCAxNzkgLTEwIDI4MSAtNDEgNDQ4Ci0xOCA5OSAtNjcgMzE0IC04NSAzNzUgLTQgMTIgNDQgNTEgMTg4IDE1NCAyMTcgMTU1IDY5NSA1MTEgNzAzIDUyNSA3IDExIC02MQoxNzEgLTE0MyAzMzQgLTExNiAyMzMgLTI2NiA0NjggLTQyNCA2NjcgbC03NyA5NyAtMTMzIC01OCBjLTE4NCAtODEgLTQ4MAotMjE3IC02ODcgLTMxNyBsLTE3MyAtODQgLTEzNCAxMjcgYy0xNDIgMTM0IC0zMTQgMjY4IC00MjkgMzM2IC02MCAzNSAtMTgzCjExNiAtMjA4IDEzNyAtNCA0IDExIDEyMyAzMyAyNjYgMTEyIDcxNCAxMzEgODM2IDEyOCA4MzkgLTIgMSAtNzMgMjkgLTE1OCA2MgotMTgwIDcwIC0zOTkgMTQzIC00MzEgMTQzIC0xMiAwIC00NyA5IC03OCAxOSAtODAgMjggLTQ4OCAxMTAgLTU0NiAxMTEgLTE2IDAKLTI2IC0xNiAtNDkgLTcyeiBtLTE4MSAtMjYyMyBjMjc2IC00OSA1NjQgLTE4NCA3NzIgLTM2MyAyNDYgLTIxMiA0NjAgLTU5OQo1MTggLTkzNiAyMiAtMTI3IDIwIC0zNDcgLTQgLTQ4OCAtNDQgLTI1NSAtMTU0IC01MjUgLTI4NSAtNjk4IC0yMzEgLTMwNwotNjMxIC01NDggLTEwMjAgLTYxNSAtMTE0IC0xOSAtMzM0IC0xOSAtNDU0IDAgLTIyOCAzNyAtNDg2IDEzMCAtNjQ2IDIzMwotMzU2IDIzMCAtNjIwIDYyNSAtNzAyIDEwNTIgLTI0IDEyNyAtMjQgMzU4IDAgNDk1IDkwIDUwOSAzMjkgODYyIDc2MSAxMTI2CjExNCA3MCAyOTMgMTQyIDQzMCAxNzUgMTkzIDQ2IDQzOSA1MyA2MzAgMTl6Ii8+CjxwYXRoIGQ9Ik00MTc1IDU2MjMgYy0yMTUgLTI1IC0zMzcgLTYyIC01MTUgLTE1NCAtMzUwIC0xODEgLTU1OSAtNDQ0IC02NjUKLTgzOCAtNTAgLTE4NCAtNTggLTI0MSAtNTkgLTM5MSAwIC0xNDIgMTYgLTI1MiA1NSAtMzcxIDI0IC03NCAxMDkgLTI1OSAxMTkKLTI1OSAzIDAgMzQgLTQyIDY3IC05MiAxNDggLTIyMyAzNTUgLTM4OSA2MDkgLTQ4OCA1MDYgLTE5OCAxMDM3IC05NCAxNDM3CjI4MCAxODAgMTY4IDMyOCA0MzYgMzc4IDY4MiA2OSAzNDMgMTIgNjY0IC0xNzMgOTc0IC0xOTkgMzM1IC00NTkgNTI0IC04NTgKNjIzIC0xMzQgMzMgLTI5MiA0NyAtMzk1IDM0eiBtMzQ1IC0zNzQgYzMxMiAtNzggNTMyIC0yNjEgNjgxIC01NjUgNjggLTE0MQo4MyAtMjE0IDgzIC00MDkgMCAtMTk5IC0xNSAtMjcwIC05MCAtNDI0IC01NSAtMTE1IC0xMTIgLTE5NiAtMTk1IC0yNzkgLTI5MAotMjg1IC02MjcgLTM2OCAtMTAyNCAtMjUyIC0yNTggNzUgLTQ2MiAyNTMgLTU5NSA1MTkgLTEyNyAyNTQgLTEzOSA1NzMgLTMzCjgxNiAxMDUgMjM2IDI4OSA0MjQgNTI1IDUzNSAyMTcgMTAyIDQwOCAxMTkgNjQ4IDU5eiIvPgo8L2c+Cjwvc3ZnPgo=\"\n const GoToHomeSvg = \"PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pg0KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE4LjEuMSwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPg0KPHN2ZyB2ZXJzaW9uPSIxLjEiIGlkPSJDYXBhXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4Ig0KCSB2aWV3Qm94PSIwIDAgMjcuMDIgMjcuMDIiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDI3LjAyIDI3LjAyOyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8Zz4NCgk8cGF0aCBzdHlsZT0iZmlsbDojMDMwMTA0OyIgZD0iTTMuNjc0LDI0Ljg3NmMwLDAtMC4wMjQsMC42MDQsMC41NjYsMC42MDRjMC43MzQsMCw2LjgxMS0wLjAwOCw2LjgxMS0wLjAwOGwwLjAxLTUuNTgxDQoJCWMwLDAtMC4wOTYtMC45MiwwLjc5Ny0wLjkyaDIuODI2YzEuMDU2LDAsMC45OTEsMC45MiwwLjk5MSwwLjkybC0wLjAxMiw1LjU2M2MwLDAsNS43NjIsMCw2LjY2NywwDQoJCWMwLjc0OSwwLDAuNzE1LTAuNzUyLDAuNzE1LTAuNzUyVjE0LjQxM2wtOS4zOTYtOC4zNThsLTkuOTc1LDguMzU4QzMuNjc0LDE0LjQxMywzLjY3NCwyNC44NzYsMy42NzQsMjQuODc2eiIvPg0KCTxwYXRoIHN0eWxlPSJmaWxsOiMwMzAxMDQ7IiBkPSJNMCwxMy42MzVjMCwwLDAuODQ3LDEuNTYxLDIuNjk0LDBsMTEuMDM4LTkuMzM4bDEwLjM0OSw5LjI4YzIuMTM4LDEuNTQyLDIuOTM5LDAsMi45MzksMA0KCQlMMTMuNzMyLDEuNTRMMCwxMy42MzV6Ii8+DQoJPHBvbHlnb24gc3R5bGU9ImZpbGw6IzAzMDEwNDsiIHBvaW50cz0iMjMuODMsNC4yNzUgMjEuMTY4LDQuMjc1IDIxLjE3OSw3LjUwMyAyMy44Myw5Ljc1MiAJIi8+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8L3N2Zz4NCg==\"\n const GoToAppSvg =\"PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHZpZXdCb3g9IjAgMCAxNzIgMTcyIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9Im5vbnplcm8iIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBzdHJva2UtbGluZWNhcD0iYnV0dCIgc3Ryb2tlLWxpbmVqb2luPSJtaXRlciIgc3Ryb2tlLW1pdGVybGltaXQ9IjEwIiBzdHJva2UtZGFzaGFycmF5PSIiIHN0cm9rZS1kYXNob2Zmc2V0PSIwIiBmb250LWZhbWlseT0ibm9uZSIgZm9udC13ZWlnaHQ9Im5vbmUiIGZvbnQtc2l6ZT0ibm9uZSIgdGV4dC1hbmNob3I9Im5vbmUiIHN0eWxlPSJtaXgtYmxlbmQtbW9kZTogbm9ybWFsIj48cGF0aCBkPSJNMCwxNzJ2LTE3MmgxNzJ2MTcyeiIgZmlsbD0ibm9uZSI+PC9wYXRoPjxnIGZpbGw9IiMwMDAwMDAiPjxwYXRoIGQ9Ik04NiwxNC4zMzMzM2MtMzkuNDk1NTIsMCAtNzEuNjY2NjcsMzIuMTcxMTUgLTcxLjY2NjY3LDcxLjY2NjY3YzAsMzkuNDk1NTIgMzIuMTcxMTUsNzEuNjY2NjcgNzEuNjY2NjcsNzEuNjY2NjdjMzkuNDk1NTIsMCA3MS42NjY2NywtMzIuMTcxMTUgNzEuNjY2NjcsLTcxLjY2NjY3YzAsLTM5LjQ5NTUyIC0zMi4xNzExNSwtNzEuNjY2NjcgLTcxLjY2NjY3LC03MS42NjY2N3pNODYsMjguNjY2NjdjMzEuNzQ5MjEsMCA1Ny4zMzMzMywyNS41ODQxMiA1Ny4zMzMzMyw1Ny4zMzMzM2MwLDMxLjc0OTIxIC0yNS41ODQxMiw1Ny4zMzMzMyAtNTcuMzMzMzMsNTcuMzMzMzNjLTMxLjc0OTIxLDAgLTU3LjMzMzMzLC0yNS41ODQxMiAtNTcuMzMzMzMsLTU3LjMzMzMzYzAsLTMxLjc0OTIxIDI1LjU4NDEyLC01Ny4zMzMzMyA1Ny4zMzMzMywtNTcuMzMzMzN6TTcxLjY2NjY3LDYxLjE2ODYydjQ5LjY2Mjc2bDQzLC0yNC44MzEzOHoiPjwvcGF0aD48L2c+PC9nPjwvc3ZnPg==\"\n \n var Div = document.createElement(\"div\")\n Div.setAttribute(\"style\",\"display: flex; flex-direction: row; align-items: center; justify-content: space-around; align-content: center;\")\n var ButtonLogout = document.createElement(\"button\")\n ButtonLogout.setAttribute(\"title\", \"Logout\")\n ButtonLogout.setAttribute(\"class\", \"CoreXActionButtonImageButton\")\n ButtonLogout.addEventListener(\"click\", ()=>{CoreXWindow.DeleteWindow(); GlobalLogout()})\n ButtonLogout.innerHTML = '<img src=\"data:image/svg+xml;base64,' + LogoutSvg + '\" height=\"100%\" width=\"100%\">'\n Div.appendChild(ButtonLogout)\n\n var ButtonUserConfig = document.createElement(\"button\")\n ButtonUserConfig.setAttribute(\"title\", \"User\")\n ButtonUserConfig.setAttribute(\"class\", \"CoreXActionButtonImageButton\")\n ButtonUserConfig.addEventListener(\"click\", ()=>{CoreXWindow.DeleteWindow(); CoreXWindowUserConfig.BuildWindow()})\n ButtonUserConfig.innerHTML = '<img src=\"data:image/svg+xml;base64,' + UserConfigSvg + '\" height=\"100%\" width=\"100%\">'\n Div.appendChild(ButtonUserConfig)\n\n var ButtonHome = document.createElement(\"button\")\n ButtonHome.setAttribute(\"title\", \"Home\")\n ButtonHome.setAttribute(\"class\", \"CoreXActionButtonImageButton\")\n ButtonHome.addEventListener(\"click\", ()=>{CoreXWindow.DeleteWindow(); this._ClickOnHomeFct()})\n ButtonHome.innerHTML = '<img src=\"data:image/svg+xml;base64,' + GoToHomeSvg + '\" height=\"100%\" width=\"100%\">'\n Div.appendChild(ButtonHome)\n\n if(GlobalIsAdminUser()){\n var ButtonGoToApp = document.createElement(\"button\")\n ButtonGoToApp.setAttribute(\"class\", \"CoreXActionButtonImageButton\")\n let LocalStorageApp = localStorage.getItem(\"CoreXApp\")\n if(LocalStorageApp == \"App\"){\n ButtonGoToApp.setAttribute(\"title\", \"Go to Admin App\")\n ButtonGoToApp.addEventListener(\"click\", ()=>{this.GoToApp.bind(this, false)()})\n ButtonGoToApp.innerHTML = '<img src=\"data:image/svg+xml;base64,' + GoToAppAdminSvg + '\" height=\"100%\" width=\"100%\">'\n } else {\n ButtonGoToApp.setAttribute(\"title\", \"Go to App\")\n ButtonGoToApp.addEventListener(\"click\", ()=>{this.GoToApp.bind(this, true)()})\n ButtonGoToApp.innerHTML = '<img src=\"data:image/svg+xml;base64,' + GoToAppSvg + '\" height=\"100%\" width=\"100%\">'\n }\n Div.appendChild(ButtonGoToApp)\n }\n return Div\n }", "function backToIconHome(){\n $(this).text(\"\");\n $(this).append(\"<img src=\\'../icons/homeicon.png\\' alt=\\'circleicon\\'>\");\n}", "onImageClick() {\n console.log('Clicked Image')\n }", "function Icon(props){\n return <img src={props.name} width=\"auto\" height=\"20px\"/>; \n }", "function replaceMagnet() { \n var newMagImgUrl = chrome.extension.getURL(\"images/download-button.png\"),\n magIcon = \"/static/img/icon-magnet.gif\";\n $('#searchResult > tbody > tr > td > a > img[src=\"'+ magIcon +'\"]').attr('src', newMagImgUrl);\n }", "function updateIcon () {\n browser.browserAction.setIcon({\n path: currentBookmark\n ? {\n 19: '../public/star-filled-19.png',\n 38: '../public/star-filled-38.png'\n }\n : {\n 19: '../public/star-empty-19.png',\n 38: '../public/star-empty-38.png'\n },\n tabId: currentTab.id\n })\n browser.browserAction.setTitle({\n // Screen readers can see the title\n title: currentBookmark ? 'Unbookmark it!' : 'Bookmark it!',\n tabId: currentTab.id\n })\n}", "function Icon(id, resPath, src, width, height, tooltip, alt) {\n\tthis.id = id; // unique button id\n\tthis.width = width; // button width\n\tthis.height = height; // button height\n\tthis.src = src; // src-Attribute\n\tthis.onclick = Icon_onclick;\n\tthis.resPath = resPath;\n\tthis.tooltip = tooltip; // Tooltip\n\tthis.alt = alt;\n\tthis.border = 0;\n}" ]
[ "0.703531", "0.6779759", "0.6743075", "0.6592491", "0.6543792", "0.65394133", "0.6497033", "0.64916337", "0.6489585", "0.6455797", "0.641277", "0.62939835", "0.62808466", "0.62791866", "0.62377536", "0.62253857", "0.6222732", "0.6217703", "0.62109554", "0.6205579", "0.61768186", "0.6171654", "0.6165716", "0.6153216", "0.6123313", "0.6108939", "0.6095328", "0.6076676", "0.6060237", "0.6058816" ]
0.7310389
0
copy photo from gallery to tfs (for iOS)
function copyPhoto(fileEntry) { window.resolveLocalFileSystemURL( Sencha.app.getImagesFolder(), function(fspDestDir) { fileEntry.copyTo( fspDestDir, null, setImageURL, function (err) { console.log('fail'); console.log('error code: ' + err.code); } ); } ); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function chooseFromGallery(){\n navigator.camera.getPicture(videoTakenFromGallerySuccess,videoTakenFromGalleryFailed,{ sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,\n mediaType:navigator.camera.MediaType.ALLMEDIA,allowEdit:true,\n });\n}", "phototaked(file) {}", "function Take_Photo (e) {\r\n\tTitanium.Media.showCamera({\r\n\t\tsuccess:function(e){\r\n\t\t\t\r\n\t\t\t$.Img_User.image=e.media;\r\n\t\t},\r\n\t\terror:function(e){\r\n\t\t\talert(\"Error al accesar al dispositivo\");\r\n\t\t},\r\n\t\tcancel:function(e){\r\n\t\t\talert(\"Captura cancelada\");\r\n\t\t},\r\n\t\tallowEditing:true,\r\n\t\tsaveToPhotoGallery:true,\r\n\t\tmediaTypes:[Titanium.Media.MEDIA_TYPE_PHOTO] \r\n\t});\r\n\r\n}", "function upload(){\n\t\t\t\tvar b64content = fs.readFileSync('image-store/photo.jpg', { encoding: 'base64' })\n\n\t\t\t\tT.post('media/upload', { media_data: b64content }, function (err, data, response) {\n\t\t\t\t // now we can assign alt text to the media, for use by screen readers and\n\t\t\t\t // other text-based presentations and interpreters\n\t\t\t\t var mediaIdStr = data.media_id_string\n\t\t\t\t // var altText = \"Small flowers in a planter on a sunny balcony, blossoming.\"\n\t\t\t\t var meta_params = { media_id: mediaIdStr }\n\n\t\t\t\t T.post('media/metadata/create', meta_params, function (err, data, response) {\n\t\t\t\t if (!err) {\n\t\t\t\t // now we can reference the media and post a tweet (media will attach to the tweet)\n\t\t\t\t var params = { status: txt.text, media_ids: [mediaIdStr] }\n\n\t\t\t\t T.post('statuses/update', params, function (err, data, response) {\n\t\t\t\t console.log(\"tweet with picture\");\n\t\t\t\t })\n\t\t\t\t }\n\t\t\t\t })\n\t\t\t\t});\n\n\t\t\t\t// clear directory\n\n\t\t\t\tvar path = 'image-store/*';\n\n\t\t\t\texec('rm -r ' + path, function (err, stdout, stderr) {\n\t\t\t\t // your callback goes here\n\t\t\t\t});\n\t\t\t}", "copyImageAsDataUri() {\n const { mimeType, text, encoding } = this.selectedRequest.responseContent.content;\n\n getString(text).then(string => {\n let data = formDataURI(mimeType, encoding, string);\n copyToClipboard(data);\n });\n }", "function copyImage() {\r\n fs.readFile(imagePath, function (err, data) {\r\n if (err) throw err;\r\n fs.writeFile(\"/DATA/GRN_Images/\" + imageName, data, function (err) {\r\n if (err) throw err;\r\n console.log('Image copied to correct directory');\r\n });\r\n });\r\n}", "photoUploadComplete() {\n this.thisStoryFetch({searchLocation: constants.searchLocation.STORY});\n }", "function choosePhotoGallery(arg) {\n\ttry {\n\t\tTitanium.Media.openPhotoGallery({\n\t\t\tsuccess : photoFattchSuccess, // end of success block\n\t\t\tcancel : function() {\n\t\t\t\tTi.API.info(' Cancelled ');\n\t\t\t},\n\t\t\terror : function(error) {\n\t\t\t\tTi.API.info(' An error occurred!! ');\n\t\t\t},\n\t\t\tallowEditing : true,\n\t\t\tmediaTypes : arrMediaTypes,\n\n\t\t});\n\t} catch(ex) {\n\t}\n\n}", "function getPhotoFromGallery() {\n disableButtons(true);\n \n // Retrieve image file location from specified source\n navigator.camera.getPicture(onPhotoSuccess, onFail, { \n quality: 100, \n correctOrientation: true,\n destinationType: destinationType.FILE_URI,\n sourceType: pictureSource.PHOTOLIBRARY }\n );\n}", "onPhotoAdd() {\n navigator.camera.getPicture( photo => {\n let promise;\n const device = Device.getDevice();\n switch ( device.getPhotoEncodingMethod() ) {\n case PhotoEncodingMethods.ImgSrc:\n promise = imgSrcToBlob( photo );\n break;\n case PhotoEncodingMethods.Base64String:\n promise = base64StringToBlob( photo );\n break;\n case PhotoEncodingMethods.None:\n default:\n promise = null;\n }\n if ( promise ) {\n promise.then( coverBlob => {\n const coverUrl = createObjectURL( coverBlob );\n this.setState( { coverBlob, coverUrl } );\n } );\n }\n }, err => {\n console.error( err );\n }, {\n sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,\n destinationType: navigator.camera.DestinationType.FILE_URI,\n encodingType: navigator.camera.EncodingType.PNG\n } );\n }", "function createNewFileEntry(imgUri) {\n window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function success(dirEntry) {\n\n // JPEG file\n dirEntry.getFile(\"tempFile.jpeg\", { create: true, exclusive: false }, function (fileEntry) {\n\n // Do something with it, like write to it, upload it, etc.\n // writeFile(fileEntry, imgUri);\n console.log(\"got file: \" + fileEntry.fullPath);\n // displayFileData(fileEntry.fullPath, \"File copied to\");\n\n }, onErrorCreateFile);\n\n }, onErrorResolveUrl);\n}", "function onPhotoURISuccess(imageURI) {\n\n //alert('ok 1: ' + imageURI);\n\n try {\n //FileIO.updateCameraImages(imageURI);\n //alert('ok 2: ' + imageURI);\n upload_file (imageURI); \n \n }\n catch (e) {\n navigator.notification.alert('Error code: ' + e, null, 'Capture Loading Error');\n } \n\n}", "upload(event){\n let image = document.getElementById('output');\n url.push(URL.createObjectURL(event.target.files[0]));\n image.src = URL.createObjectURL(event.target.files[0])\n }", "function processImage(path, name) {\n\tvar new_location = 'public/uploads/';\n\n\tfs.copy(path, new_location + name, function(err) {\n\t\tif (err) {\n\t\t\tconsole.error(err);\n\t\t} else {\n\t\t\tconsole.log(\"success!\")\n\t\t}\n\t});\n}", "function uploadPhoto(accessToken, photo) {\n let data = new FormData();\n let config;\n\n data.append('access_token', accessToken);\n data.append('source', photo);\n data.append('privacy', JSON.stringify({ 'value': 'SELF' }));\n config = {\n method: 'POST',\n body: data\n }\n // Upload the photo to user's Facebook by using multipart/form-data post.\n return fetch(`${externalApiConfig.facebook.apiRoot}/me/photos?access_token=${accessToken}`, config);\n}", "function takePhoto() {\n imageCapture.takePhoto().then(function(blob) {\n console.log('Took photo:', blob);\n img.classList.remove('hidden');\n img.src = URL.createObjectURL(blob);\n }).catch(function(error) {\n console.log('takePhoto() error: ', error);\n });\n}", "function uploadPhoto(photoURI, photoType, databaseID){\n // !! Assumes variable fileURL contains a valid URL to a text file on the device,\n // for example, cdvfile://localhost/persistent/path/to/file.txt\n\n var leafSuccess = function (r) {\n //navigator.notification.alert(\"leaf photo uploaded\");\n console.log(\"Code = \" + r.responseCode);\n console.log(\"Response = \" + r.response);\n console.log(\"Sent = \" + r.bytesSent);\n cosole.log(\"survey.timeStart = \" + survey.timeStart);\n // deleteSurvey(survey.timeStart);\n };\n\n var fail = function (error) {\n navigator.notification.alert(\"An error has occurred: Code = \" + error.code);\n alert(\"upload error source: \" + error.source);\n alert(\"upload error target: \" + error.target);\n console.log(\"upload error source \" + error.source);\n console.log(\"upload error target \" + error.target);\n };\n\n var arthropodSuccess = function(r){\n //navigator.notification.alert(\"order photo uploaded\");\n\n //Increment number of arthropods submitted\n //here when there is a photo to upload\n //to prevent duplicate success alerts\n console.log(\"Code = \" + r.responseCode);\n console.log(\"Response = \" + r.response);\n console.log(\"Sent = \" + r.bytesSent);\n\n //If this was the last order photo to submit, clear form, submission succeeded\n // if(numberOfArthropodsSubmitted == numberOfArthropodsToSubmit) {\n // navigator.notification.alert(\"Successfully submitted survey data!\");\n // clearFields();\n\n // }\n };\n\n var options = new FileUploadOptions();\n options.fileKey = \"file\";\n options.mimeType=\"image/jpeg\";\n options.chunkedMode = false;\n options.headers = {\n Connection: \"close\"\n };\n\n // var params = {};\n // params.fullpath = imageURI;\n // params.name = options.fileName;\n \n // options.params = params;\n\n var ft = new FileTransfer();\n //If uploading leaf photo\n if(photoType.localeCompare(\"leaf-photo\") === 0) {\n options.fileName = \"survey_\" + databaseID + \"_leaf_photo.jpg\";\n ft.upload(photoURI, encodeURI(DOMAIN + \"/api/uploads.php?surveyID=\" + databaseID), leafSuccess, fail, options);\n }\n //Uploading arthropod photo\n else if(photoType.localeCompare(\"arthropod-photo\") === 0){\n options.fileName = \"order_\" + databaseID + \"_arthropod_photo.jpg\";\n ft.upload(photoURI, encodeURI(DOMAIN + \"/api/uploads.php?orderID=\" + databaseID), arthropodSuccess, fail, options);\n }\n}", "function onCopySuccess(entry) {\n var name = entry.nativeURL.slice(0, -4);\n window.PKVideoThumbnail.createThumbnail (entry.nativeURL, name + '.png', function(prevSucc) {\n return prevImageSuccess(prevSucc);\n }, fail);\n }", "function onCopySuccess(entry) {\n var name = entry.nativeURL.slice(0, -4);\n window.PKVideoThumbnail.createThumbnail (entry.nativeURL, name + '.png', function(prevSucc) {\n return prevImageSuccess(prevSucc);\n }, fail);\n }", "function moverPhoto(file){\r\n //alert(file);\r\n window.resolveLocalFileSystemURI(file, resolveOnSuccess, resOnError);\r\n //window.resolveLocalFileSystemURI( file , resolveOnSuccess, resOnError);\r\n}", "copyFileToUsersCollection(sourceFileId) {\n const { shouldCopyFileToRecents, userMediaStore, tenantUploadParams, } = this;\n if (!shouldCopyFileToRecents || !userMediaStore) {\n return Promise.resolve();\n }\n const { collection: sourceCollection } = tenantUploadParams;\n const { authProvider: tenantAuthProvider } = this.tenantMediaClient.config;\n return tenantAuthProvider({ collectionName: sourceCollection }).then(auth => {\n const body = {\n sourceFile: {\n id: sourceFileId,\n collection: sourceCollection,\n owner: {\n ...mapAuthToSourceFileOwner(auth),\n },\n },\n };\n const params = {\n collection: RECENTS_COLLECTION,\n };\n return userMediaStore.copyFileWithToken(body, params);\n });\n }", "function getPhoto(source) {\n // Retrieve image file location from specified source\n store('photoSource', 'album')\n navigator.camera.getPicture(uploadPhoto, onFail, {\n quality: 20,\n destinationType: DESTINATION_TYPE.FILE_URI,\n sourceType: source\n });\n}", "async function testGetStepImages_savesFiles() {\n let api = await getGoogleApiClient();\n let filePath = await api.saveStepImage('5fb5bee7.Photo1.132604.jpg', '05d8fd63').catch(error => console.log('GOOGLE API RESPONSE ERROR: ' + error));\n await deletePhotoFile(filePath);\n}", "copyProfilePicture() {\n fs.createReadStream(path.join(this._dataExportDirectory, PROFILE_PICTURE_FILE))\n .pipe(fs.createWriteStream(path.join(__dirname, '..', COPIED_PROFILE_PICTURE_FILE)));\n }", "function downloadPhoto(photoURL) {\r\n\tvar fileTransfer = new FileTransfer();\r\n\tvar uri = encodeURI(photoURL);\r\n\t// filesystem access for images\r\n\twindow.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function onRequestFileSystemSuccess(fileSystem) { \r\n\t\talert('requestFileSystem success');\r\n\t}, null);\r\n}", "async takePicture() {\n var photoLoc = `${FileSystem.documentDirectory}photos/Photo_${\n this.state.photoId\n }_Base64`;\n if (this.camera) {\n let photo = await this.camera.takePictureAsync({ base64: true });\n FileSystem.moveAsync({\n from: photo.uri,\n to: photoLoc\n }).then(() => {\n this.setState({\n photoId: this.state.photoId + 1\n });\n this.sendToImgur(photoLoc);\n });\n }\n }", "openVideoGallery(){\n let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})\n let context = this;\n let { dispatch } = context.props.navigation;\n let arr = context.state.workImages;\n ImagePicker.openPicker({\n showCropGuidelines :false,\n maxFiles:context.state.maxNumberOfVideos,\n mediaType:\"video\"\n }).then(images => {\n let source = {uri: images.path, isStatic: true};\n ThumbnailGenerator.get(source.uri).then((result) => {\n let imageClone = context.state.workImages;\n result.isVideo = true;\n result.videoPath = images.path;\n result.id = Math.random();\n imageClone.push(result);\n context.setState({\n maxNumberOfVideos:0,\n dataSource:ds.cloneWithRows(imageClone)\n });\n })\n }).catch(e => {\n if(e.code===\"ERROR_PICKER_UNAUTHORIZED_KEY\"){\n dispatch(ToastActionsCreators.displayInfo(\"Cannot access images. Please allow access if you want to be able to select images.\"));\n return;\n }\n if(e.code===\"ERROR_PICKER_NO_CAMERA_PERMISSION\"){\n dispatch(ToastActionsCreators.displayInfo(\"Cannot access camera. Please allow access if you want to be able to click images.\"));\n return;\n }\n });\n }", "function ChoosePhoto(e) {\n console.log(\"gggg\");\n getPhoto(pictureSource.PHOTOLIBRARY);\n }", "static formImages() {\n let mainfsDirCount = PP64.fs.mainfs.getDirectoryCount();\n for (let d = 0; d < mainfsDirCount; d++) {\n let dirFileCount = PP64.fs.mainfs.getFileCount(d);\n for (let f = 0; f < dirFileCount; f++) {\n let fileBuffer = PP64.fs.mainfs.get(d, f);\n if (!PP64.utils.FORM.isForm(fileBuffer))\n continue;\n\n try {\n let formUnpacked = PP64.utils.FORM.unpack(fileBuffer);\n if (formUnpacked.BMP1.length) {\n formUnpacked.BMP1.forEach(bmpEntry => {\n let dataUri = PP64.utils.arrays.arrayBufferToDataURL(bmpEntry.parsed.src, bmpEntry.parsed.width, bmpEntry.parsed.height);\n console.log(`${d}/${f}:`);\n console.log(dataUri);\n });\n }\n }\n catch (e) {}\n }\n }\n }", "async uploadImage(currentBook) {\n const { imageFile } = this.state\n debugger\n const storageRef = storage.ref();\n const fileRef = storageRef.child(imageFile.name);\n await fileRef.put(imageFile);\n currentBook.image = await fileRef.getDownloadURL();\n // const fileUrl = await fileRef.getDownloadURL();\n // this.setState(currentBook);\n }" ]
[ "0.561532", "0.55945224", "0.5586316", "0.544252", "0.53647995", "0.53227454", "0.5286344", "0.52729326", "0.52709943", "0.52616906", "0.52192575", "0.51363444", "0.51013196", "0.5085947", "0.50716823", "0.5056637", "0.5042237", "0.50379175", "0.503484", "0.50297225", "0.5026766", "0.49849513", "0.495574", "0.49434572", "0.4942512", "0.49406043", "0.49403423", "0.49382046", "0.4938174", "0.49313587" ]
0.64179885
0
Valid if it exists, and is not an autoadded Storybook element i.e. It is not dependent on Storybook's Preview implementation, so it'll work in JSDom (Jest)
function isValidTargetElement(targetElement) { return (0, _typeGuards.isNotNil)(targetElement) && targetElement !== _storybook.A11yElement.Root && targetElement !== _storybook.A11yElement.Component; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_assertElementExists(matchElement, element) {\n const elName = element.name.replace(/^:xhtml:/, '');\n if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) {\n let errorMsg = `'${elName}' is not a known element:\\n`;\n errorMsg += `1. If '${elName}' is an Angular component, then verify that it is part of this module.\\n`;\n if (elName.indexOf('-') > -1) {\n errorMsg += `2. If '${elName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`;\n }\n else {\n errorMsg +=\n `2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;\n }\n this._reportError(errorMsg, element.sourceSpan);\n }\n }", "_assertElementExists(matchElement, element) {\n const elName = element.name.replace(/^:xhtml:/, '');\n if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) {\n let errorMsg = `'${elName}' is not a known element:\\n`;\n errorMsg += `1. If '${elName}' is an Angular component, then verify that it is part of this module.\\n`;\n if (elName.indexOf('-') > -1) {\n errorMsg += `2. If '${elName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`;\n }\n else {\n errorMsg +=\n `2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;\n }\n this._reportError(errorMsg, element.sourceSpan);\n }\n }", "_assertElementExists(matchElement, element) {\n const elName = element.name.replace(/^:xhtml:/, '');\n if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) {\n let errorMsg = `'${elName}' is not a known element:\\n`;\n errorMsg +=\n `1. If '${elName}' is an Angular component, then verify that it is part of this module.\\n`;\n if (elName.indexOf('-') > -1) {\n errorMsg +=\n `2. If '${elName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`;\n }\n else {\n errorMsg +=\n `2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;\n }\n this._reportError(errorMsg, element.sourceSpan);\n }\n }", "_assertElementExists(matchElement, element) {\n const elName = element.name.replace(/^:xhtml:/, '');\n if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) {\n let errorMsg = `'${elName}' is not a known element:\\n`;\n errorMsg +=\n `1. If '${elName}' is an Angular component, then verify that it is part of this module.\\n`;\n if (elName.indexOf('-') > -1) {\n errorMsg +=\n `2. If '${elName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`;\n }\n else {\n errorMsg +=\n `2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;\n }\n this._reportError(errorMsg, element.sourceSpan);\n }\n }", "_checkForUndefinedComponents() {\n if (this.html == null) {\n return;\n }\n const matches = this.html.matchAll(/<([a-z]+-[a-z]*)[ \\/].*>/g);\n if (matches == null) {\n return;\n }\n const tags = Array.from(matches).map(m => m[1]);\n for (const tag of tags) {\n if (customElements.get(tag) == null) {\n console.error(`${this.constructor.name} tried to use tag ${tag}, but it has not been defined yet.`);\n }\n }\n }", "setupUselessElement() {}", "static getNativeElement(el) {\n if (el instanceof UnitTestElement) {\n return el.element;\n }\n throw Error('This TestElement was not created by the TestbedHarnessEnvironment');\n }", "validateNoReviewComponent() {\n return this\n .waitForElementVisible('@productCardWithoutReviewComponent', 10000, () => {}, '[STEP] - Product Card should not have review component')\n .assert.visible('@productCardWithoutReviewComponent');\n }", "checkIfElementExists(el) {\n if (!this.context.querySelector('#'+el)) {\n throw new Error(`#${el} does not exist`);\n }\n }", "function isDOMRequired() { \n\treturn true;\n}", "function isDOMRequired() {\r\n return false;\r\n}", "function isDOMRequired()\n{\n\treturn true;\n}", "get exists() {\n return (\n (this.opts.selector !== undefined || this.opts.element !== undefined)\n && ((this.$component instanceof Node\n && this.$component !== undefined\n && this.$component !== null)\n || (this.$component instanceof NodeList && this.$component.length > 0))\n );\n }", "function isElement(obj) {\n return !!((typeof HTMLElement === 'undefined' ? 'undefined' : _typeof(HTMLElement)) === 'object' ? obj instanceof HTMLElement : obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === 'string');\n }", "function isElement(obj) {\n return !!((typeof HTMLElement === 'undefined' ? 'undefined' : _typeof(HTMLElement)) === 'object' ? obj instanceof HTMLElement : obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === 'string');\n }", "isElement(value) {\n return Object(__WEBPACK_IMPORTED_MODULE_0_is_plain_object__[\"a\" /* default */])(value) && Node.isNodeList(value.children) && !Editor.isEditor(value);\n }", "function isElement(o) {\n return o && (typeof o === 'undefined' ? 'undefined' : _typeof(o)) === 'object' && o !== null && o.nodeType === 1 && typeof o.nodeName === 'string';\n}", "function canUseDOM() {\n return !!(typeof window !== \"undefined\" && window.document && window.document.createElement);\n}", "function isPlaywrightElementHandle(obj) {\n return !('$x' in obj);\n}", "function isElement(target) {\n return !!target && typeof target['tagName'] === 'string';\n }", "function isElement(obj) {\n return !!((typeof HTMLElement === 'undefined' ? 'undefined' : _typeof(HTMLElement)) === 'object' ? obj instanceof HTMLElement : obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === 'string');\n}", "function documentElementCheck () {\n const docNode = document.documentElement.nodeName;\n if (docNode) {\n return docNode.toLowerCase() === 'html';\n }\n return true;\n}", "validateReviewComponent() {\n return this\n .waitForElementVisible('@reviewComponent', 10000, () => {}, '[STEP] - Product Card should have review component')\n .assert.visible('@reviewComponent');\n }", "createNodeMock(element) {\n if (element.type === 'input') {\n return {};\n }\n return null;\n }", "function isValidElement(elem) {\n return !!elem && elem.nodeType === 1;\n }", "function hasDocument() {\n return typeof document !== \"undefined\";\n}", "function hasDocument() {\n return typeof document !== \"undefined\";\n}", "function assertDomElement(value) {\n if (typeof Element !== 'undefined' && !(value instanceof Element)) {\n throw new Error('Expecting instance of DOM Element');\n }\n }", "function checkElementIdShadowing(value) {\n return value && value.nodeType === undefined ? value : undefined;\n }", "function checkElementIdShadowing(value) {\n return value && value.nodeType === undefined ? value : undefined;\n }" ]
[ "0.61298835", "0.61298835", "0.61205226", "0.61205226", "0.60724515", "0.5960004", "0.5713902", "0.57050514", "0.5687601", "0.56861067", "0.567351", "0.5665304", "0.5644558", "0.5642582", "0.5637174", "0.55661213", "0.5520047", "0.5512397", "0.5487254", "0.5466414", "0.5460662", "0.54573804", "0.5443412", "0.5443376", "0.5421999", "0.54183435", "0.54183435", "0.54068416", "0.5405557", "0.5405557" ]
0.63711554
0
endregion Generates Jest a11y tests for all stories in a module Note: `colorcontrast` rule is NOT checked, and it is not likely to be fixed soon. Verify it is/isn't checked with a `console.log(results)` below
async function generateA11yStoryTests(storyModule) { var _storyModule$default$, _storyModule$default$2; const storiesTargetElement = (_storyModule$default$ = storyModule.default.parameters) === null || _storyModule$default$ === void 0 ? void 0 : (_storyModule$default$2 = _storyModule$default$.a11y) === null || _storyModule$default$2 === void 0 ? void 0 : _storyModule$default$2.element; Object.entries(storyModule).filter(isA11yStoryEntry).forEach(([storyName, story]) => { it(`${storyName} story is accessible`, async () => { var _story$parameters$a, _story$parameters, _story$parameters$a2, _baseElement$querySel; const targetElement = (_story$parameters$a = (_story$parameters = story.parameters) === null || _story$parameters === void 0 ? void 0 : (_story$parameters$a2 = _story$parameters.a11y) === null || _story$parameters$a2 === void 0 ? void 0 : _story$parameters$a2.element) !== null && _story$parameters$a !== void 0 ? _story$parameters$a : storiesTargetElement; const { baseElement, container } = (0, _render.renderStory)(story); const results = isValidTargetElement(targetElement) ? await axe((_baseElement$querySel = baseElement.querySelector(targetElement)) !== null && _baseElement$querySel !== void 0 ? _baseElement$querySel : baseElement) : await axe(container); expect(results).toHaveNoViolations(); }); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async function runTests() {\n await fse.remove(\"cypress/report\");\n await cypress.run({\n spec: \"cypress/integration/**/*.spec.ts\",\n });\n const jsonReport = await merge({\n reportDir: \"cypress/report\",\n });\n await generator.create(jsonReport, {\n reportDir: \"cypress/report\",\n reportTitle: \"Bridge-X E2E All Test\",\n });\n await fse.writeJson(\"cypress/report/mochawesome-stat.json\", jsonReport, { spaces: 2 });\n}", "function jestTestsAndCoverage() {\n return gulp.src(SPEC_DIR)\n .pipe(jest(jestConfig));\n}", "function testAllTests() {\n testExtremal();\n testDifference();\n testSpearman();\n testSerial()\n}", "function runTest(test) {\n test.testOptions.screenCapture = './accessability-test/output/' + test.name +'.png'\n var options = { \n ...test.testOptions, \n standard: 'Section508'}; //standard: 'Section508'}; standard: 'WCAG2AAA'; \"WCAG2A\"; WCAG2AA}; \n pa11y(test.url, options).then((results) => {\n results.screenGrab = test.name + '.png';\n var htmlResults = accReporter.process(results, test.url, true);\n fs.writeFile('accessability-test/output/'+ test.name + '.html', htmlResults, function(err) {})\n }).catch((err) => {\n console.log(err);\n });\n}", "async runTests({tests} = {}) {\n const vizTargetRoot = document.getElementById('vizTargetRoot');\n\n for (const {screenshotOutputPath, testName, suiteName} of tests) {\n // This is to call out tests that may be 'hung', which is helpful for debugging\n const hungConsoleWarningTimeout = setTimeout(\n () => {\n console.log(`${suiteName}/${testName} being slow.`);\n },\n 5 * 1000\n );\n\n const target = vizTargetRoot.appendChild(document.createElement('div'));\n const {testRunner} = this.registeredTests.find((test) => test.testName === testName && test.suiteName === suiteName);\n const testInitializer = this.registeredTestInitializers[suiteName] || noop;\n const testFinalizer = this.registeredTestFinalizers[suiteName] || noop;\n\n // Run the test to render something to the viewport\n let screenshotTarget;\n\n try {\n await testInitializer();\n screenshotTarget = await testRunner(target);\n } catch (e) {\n console.error(`Error running test ${suiteName}/${testName}`, e);\n }\n\n if (!screenshotTarget) {\n throw new Error(`No screenshot target returned from test ${suiteName}/${testName}. Did you forget to 'return'?`);\n }\n\n let targetRect = screenshotTarget.getBoundingClientRect();\n\n // If the screenshot target has a parent, add the parent's padding to the clipping rectangle.\n if (screenshotTarget.parentElement && screenshotTarget.parentElement !== target) {\n const {\n paddingTop,\n paddingRight,\n paddingBottom,\n paddingLeft,\n } = window.getComputedStyle(screenshotTarget.parentElement);\n\n const paddingTopPx = parseInt(paddingTop.replace('px', '')) || 0;\n const paddingRightPx = parseInt(paddingRight.replace('px', '') || 0);\n const paddingBottomPx = parseInt(paddingBottom.replace('px', '') || 0);\n const paddingLeftPx = parseInt(paddingLeft.replace('px', '') || 0);\n\n targetRect = {\n x: targetRect.x - paddingLeftPx,\n y: targetRect.y - paddingTopPx,\n width: targetRect.width + paddingLeftPx + paddingRightPx,\n height: targetRect.height + paddingTopPx + paddingBottomPx,\n };\n }\n\n await window.takeScreenshot({\n targetRect,\n screenshotOutputPath,\n });\n\n try {\n await testFinalizer(target);\n } catch (e) {\n console.error(`Error calling afterEach for test ${suiteName}/${testName}`, e);\n }\n\n vizTargetRoot.removeChild(target);\n\n await window.resetMouse();\n\n clearTimeout(hungConsoleWarningTimeout);\n }\n }", "function indexTests() {\n let startTestNum = startGameTests(); //testing the startGame function\n let callUnoTestNum = callUnoTests(); //testing the callUno function\n let cheatTestNum = cheatTests();\n console.log(\"\\n$ * * * * All tests for index.js * * * *\");\n console.log(\n \"$ Total tests for start() - 3. Passed: \" +\n startTestNum +\n \". Failed: \" +\n (3 - startTestNum)\n );\n console.log(\n \"$ Total tests for callUno() - 2. Passed: \" +\n callUnoTestNum +\n \". Failed: \" +\n (2 - callUnoTestNum)\n );\n console.log(\n \"$ Total tests for all cheats - 4. Passed: \" +\n cheatTestNum +\n \". Failed: \" +\n (4 - cheatTestNum)\n );\n console.log(\"\\n$ * * * * End tests for index.js * * * *\");\n return startTestNum + callUnoTestNum + cheatTestNum;\n}", "function testAccessibility2() {\n return pa11y(\"./build/index.html\").then((results) => { \n console.log(results);\n })\n}", "function testRunner() {\n\t var featureNames;\n\t var feature;\n\t var aliasIdx;\n\t var result;\n\t var nameIdx;\n\t var featureName;\n\t var featureNameSplit;\n\t for (var featureIdx in tests) {\n\t if (tests.hasOwnProperty(featureIdx)) {\n\t featureNames = [];\n\t feature = tests[featureIdx];\n\t // run the test, throw the return value into the Modernizr,\n\t // then based on that boolean, define an appropriate className\n\t // and push it into an array of classes we'll join later.\n\t //\n\t // If there is no name, it's an 'async' test that is run,\n\t // but not directly added to the object. That should\n\t // be done with a post-run addTest call.\n\t if (feature.name) {\n\t featureNames.push(feature.name.toLowerCase());\n\t if (feature.options && feature.options.aliases && feature.options.aliases.length) {\n\t // Add all the aliases into the names list\n\t for (aliasIdx = 0; aliasIdx < feature.options.aliases.length; aliasIdx++) {\n\t featureNames.push(feature.options.aliases[aliasIdx].toLowerCase());\n\t }\n\t }\n\t }\n\t // Run the test, or use the raw value if it's not a function\n\t result = is(feature.fn, 'function') ? feature.fn() : feature.fn;\n\t // Set each of the names on the Modernizr object\n\t for (nameIdx = 0; nameIdx < featureNames.length; nameIdx++) {\n\t featureName = featureNames[nameIdx];\n\t // Support dot properties as sub tests. We don't do checking to make sure\n\t // that the implied parent tests have been added. You must call them in\n\t // order (either in the test, or make the parent test a dependency).\n\t //\n\t // Cap it to TWO to make the logic simple and because who needs that kind of subtesting\n\t // hashtag famous last words\n\t featureNameSplit = featureName.split('.');\n\t if (featureNameSplit.length === 1) {\n\t Modernizr[featureNameSplit[0]] = result;\n\t } else {\n\t // cast to a Boolean, if not one already\n\t if (Modernizr[featureNameSplit[0]] && !(Modernizr[featureNameSplit[0]] instanceof Boolean)) {\n\t Modernizr[featureNameSplit[0]] = new Boolean(Modernizr[featureNameSplit[0]]);\n\t }\n\t Modernizr[featureNameSplit[0]][featureNameSplit[1]] = result;\n\t }\n\t classes.push((result ? '' : 'no-') + featureNameSplit.join('-'));\n\t }\n\t }\n\t }\n\t }", "function testRunner() {\n var featureNames;\n var feature;\n var aliasIdx;\n var result;\n var nameIdx;\n var featureName;\n var featureNameSplit;\n\n for (var featureIdx in tests) {\n if (tests.hasOwnProperty(featureIdx)) {\n featureNames = [];\n feature = tests[featureIdx]; // run the test, throw the return value into the Modernizr,\n // then based on that boolean, define an appropriate className\n // and push it into an array of classes we'll join later.\n //\n // If there is no name, it's an 'async' test that is run,\n // but not directly added to the object. That should\n // be done with a post-run addTest call.\n\n if (feature.name) {\n featureNames.push(feature.name.toLowerCase());\n\n if (feature.options && feature.options.aliases && feature.options.aliases.length) {\n // Add all the aliases into the names list\n for (aliasIdx = 0; aliasIdx < feature.options.aliases.length; aliasIdx++) {\n featureNames.push(feature.options.aliases[aliasIdx].toLowerCase());\n }\n }\n } // Run the test, or use the raw value if it's not a function\n\n\n result = is(feature.fn, 'function') ? feature.fn() : feature.fn; // Set each of the names on the Modernizr object\n\n for (nameIdx = 0; nameIdx < featureNames.length; nameIdx++) {\n featureName = featureNames[nameIdx]; // Support dot properties as sub tests. We don't do checking to make sure\n // that the implied parent tests have been added. You must call them in\n // order (either in the test, or make the parent test a dependency).\n //\n // Cap it to TWO to make the logic simple and because who needs that kind of subtesting\n // hashtag famous last words\n\n featureNameSplit = featureName.split('.');\n\n if (featureNameSplit.length === 1) {\n Modernizr[featureNameSplit[0]] = result;\n } else {\n // cast to a Boolean, if not one already\n if (Modernizr[featureNameSplit[0]] && !(Modernizr[featureNameSplit[0]] instanceof Boolean)) {\n Modernizr[featureNameSplit[0]] = new Boolean(Modernizr[featureNameSplit[0]]);\n }\n\n Modernizr[featureNameSplit[0]][featureNameSplit[1]] = result;\n }\n\n classes.push((result ? '' : 'no-') + featureNameSplit.join('-'));\n }\n }\n }\n }", "function runTests (port, build){\n\n describe('build tests', function() {\n this.timeout(20000);\n\n build();\n\n var browser = new Browser();\n\n before(function(d) {\n browser.visit('http://localhost:' + port, d);\n });\n\n\n // layout\n it('should show layout hbs content', function() {\n browser.assert.hasText('.layout', '[defaultLayout-hbs-output]');\n });\n\n\n\n // page\n it('should show index page hbs content', function() {\n browser.assert.hasText('.page', '[indexPage-hbs-output]');\n });\n\n\n\n // partial\n it('should show partial hbs content', function() {\n browser.assert.hasText('.partial', '[partial-hbs-output]');\n });\n\n it('should show partial json content', function() {\n browser.assert.hasText('.partial', '[partial-json-output]');\n });\n\n\n\n // first\n it('should show first hbs content', function() {\n browser.assert.hasText('.first', '[first-hbs-output]');\n });\n\n it('should show first js content', function() {\n browser.assert.hasText('.first', '[first-js-output]');\n });\n\n it('should show first json content', function() {\n browser.assert.hasText('.first', '[first-json-output]');\n });\n\n\n\n // second\n it('should show second hbs content', function() {\n browser.assert.hasText('.second', '[second-hbs-output]');\n });\n\n it('should show second js content', function() {\n browser.assert.hasText('.second', '[second-js-output]');\n });\n\n it('should show second dependency1 js content', function() {\n browser.assert.hasText('.second', '[someDependency1-js-output]');\n });\n\n it('should show second dependency2 js content', function() {\n browser.assert.hasText('.second', '[someDependency2-js-output]');\n });\n\n\n\n var lymCssBrowser = new Browser();\n\n before(function(d) {\n lymCssBrowser.visit('http://localhost:' + port+ '/css/lym.css', d);\n });\n\n it('should show first-settings css', function() {\n lymCssBrowser.assert.hasText('body', '.first-setting{color:red;}',true);\n });\n\n it('should show first-mixin css', function() {\n lymCssBrowser.assert.hasText('body', '.first-mixins{color:red;}',true);\n });\n\n it('should show second-mixin css', function() {\n lymCssBrowser.assert.hasText('body', '.second-mixins{color:orange;}',true);\n });\n\n it('should show second css', function() {\n lymCssBrowser.assert.hasText('body', '.second{color:green;}',true);\n });\n\n\n var firstBundleCssBrowser = new Browser();\n\n before(function(d) {\n firstBundleCssBrowser.visit('http://localhost:' + port+ '/css/first-bundle.css', d);\n });\n\n it('should show first css', function() {\n firstBundleCssBrowser.assert.hasText('body', '.first{color:red;}',true);\n });\n });\n}", "function testAll() {\n testAssert()\n testRemainder()\n testConversions()\n}", "function testRunner() {\n var featureNames;\n var feature;\n var aliasIdx;\n var result;\n var nameIdx;\n var featureName;\n var featureNameSplit;\n\n for (var featureIdx in tests) {\n if (tests.hasOwnProperty(featureIdx)) {\n featureNames = [];\n feature = tests[featureIdx];\n // run the test, throw the return value into the Modernizr,\n // then based on that boolean, define an appropriate className\n // and push it into an array of classes we'll join later.\n //\n // If there is no name, it's an 'async' test that is run,\n // but not directly added to the object. That should\n // be done with a post-run addTest call.\n if (feature.name) {\n featureNames.push(feature.name.toLowerCase());\n\n if (feature.options && feature.options.aliases && feature.options.aliases.length) {\n // Add all the aliases into the names list\n for (aliasIdx = 0; aliasIdx < feature.options.aliases.length; aliasIdx++) {\n featureNames.push(feature.options.aliases[aliasIdx].toLowerCase());\n }\n }\n }\n\n // Run the test, or use the raw value if it's not a function\n result = is(feature.fn, 'function') ? feature.fn() : feature.fn;\n\n\n // Set each of the names on the Modernizr object\n for (nameIdx = 0; nameIdx < featureNames.length; nameIdx++) {\n featureName = featureNames[nameIdx];\n // Support dot properties as sub tests. We don't do checking to make sure\n // that the implied parent tests have been added. You must call them in\n // order (either in the test, or make the parent test a dependency).\n //\n // Cap it to TWO to make the logic simple and because who needs that kind of subtesting\n // hashtag famous last words\n featureNameSplit = featureName.split('.');\n\n if (featureNameSplit.length === 1) {\n Modernizr[featureNameSplit[0]] = result;\n } else {\n // cast to a Boolean, if not one already\n /* jshint -W053 */\n if (Modernizr[featureNameSplit[0]] && !(Modernizr[featureNameSplit[0]] instanceof Boolean)) {\n Modernizr[featureNameSplit[0]] = new Boolean(Modernizr[featureNameSplit[0]]);\n }\n\n Modernizr[featureNameSplit[0]][featureNameSplit[1]] = result;\n }\n\n classes.push((result ? '' : 'no-') + featureNameSplit.join('-'));\n }\n }\n }\n }", "function testRunner() {\n var featureNames;\n var feature;\n var aliasIdx;\n var result;\n var nameIdx;\n var featureName;\n var featureNameSplit;\n\n for (var featureIdx in tests) {\n if (tests.hasOwnProperty(featureIdx)) {\n featureNames = [];\n feature = tests[featureIdx];\n // run the test, throw the return value into the Modernizr,\n // then based on that boolean, define an appropriate className\n // and push it into an array of classes we'll join later.\n //\n // If there is no name, it's an 'async' test that is run,\n // but not directly added to the object. That should\n // be done with a post-run addTest call.\n if (feature.name) {\n featureNames.push(feature.name.toLowerCase());\n\n if (feature.options && feature.options.aliases && feature.options.aliases.length) {\n // Add all the aliases into the names list\n for (aliasIdx = 0; aliasIdx < feature.options.aliases.length; aliasIdx++) {\n featureNames.push(feature.options.aliases[aliasIdx].toLowerCase());\n }\n }\n }\n\n // Run the test, or use the raw value if it's not a function\n result = is(feature.fn, 'function') ? feature.fn() : feature.fn;\n\n\n // Set each of the names on the Modernizr object\n for (nameIdx = 0; nameIdx < featureNames.length; nameIdx++) {\n featureName = featureNames[nameIdx];\n // Support dot properties as sub tests. We don't do checking to make sure\n // that the implied parent tests have been added. You must call them in\n // order (either in the test, or make the parent test a dependency).\n //\n // Cap it to TWO to make the logic simple and because who needs that kind of subtesting\n // hashtag famous last words\n featureNameSplit = featureName.split('.');\n\n if (featureNameSplit.length === 1) {\n Modernizr[featureNameSplit[0]] = result;\n } else {\n // cast to a Boolean, if not one already\n /* jshint -W053 */\n if (Modernizr[featureNameSplit[0]] && !(Modernizr[featureNameSplit[0]] instanceof Boolean)) {\n Modernizr[featureNameSplit[0]] = new Boolean(Modernizr[featureNameSplit[0]]);\n }\n\n Modernizr[featureNameSplit[0]][featureNameSplit[1]] = result;\n }\n\n classes.push((result ? '' : 'no-') + featureNameSplit.join('-'));\n }\n }\n }\n }", "function testRunner() {\n var featureNames;\n var feature;\n var aliasIdx;\n var result;\n var nameIdx;\n var featureName;\n var featureNameSplit;\n\n for (var featureIdx in tests) {\n if (tests.hasOwnProperty(featureIdx)) {\n featureNames = [];\n feature = tests[featureIdx];\n // run the test, throw the return value into the Modernizr,\n // then based on that boolean, define an appropriate className\n // and push it into an array of classes we'll join later.\n //\n // If there is no name, it's an 'async' test that is run,\n // but not directly added to the object. That should\n // be done with a post-run addTest call.\n if (feature.name) {\n featureNames.push(feature.name.toLowerCase());\n\n if (feature.options && feature.options.aliases && feature.options.aliases.length) {\n // Add all the aliases into the names list\n for (aliasIdx = 0; aliasIdx < feature.options.aliases.length; aliasIdx++) {\n featureNames.push(feature.options.aliases[aliasIdx].toLowerCase());\n }\n }\n }\n\n // Run the test, or use the raw value if it's not a function\n result = is(feature.fn, 'function') ? feature.fn() : feature.fn;\n\n\n // Set each of the names on the Modernizr object\n for (nameIdx = 0; nameIdx < featureNames.length; nameIdx++) {\n featureName = featureNames[nameIdx];\n // Support dot properties as sub tests. We don't do checking to make sure\n // that the implied parent tests have been added. You must call them in\n // order (either in the test, or make the parent test a dependency).\n //\n // Cap it to TWO to make the logic simple and because who needs that kind of subtesting\n // hashtag famous last words\n featureNameSplit = featureName.split('.');\n\n if (featureNameSplit.length === 1) {\n Modernizr[featureNameSplit[0]] = result;\n } else {\n // cast to a Boolean, if not one already\n /* jshint -W053 */\n if (Modernizr[featureNameSplit[0]] && !(Modernizr[featureNameSplit[0]] instanceof Boolean)) {\n Modernizr[featureNameSplit[0]] = new Boolean(Modernizr[featureNameSplit[0]]);\n }\n\n Modernizr[featureNameSplit[0]][featureNameSplit[1]] = result;\n }\n\n classes.push((result ? '' : 'no-') + featureNameSplit.join('-'));\n }\n }\n }\n }", "function startAllTests(){ \n testGetObjectFromArrays();\n testNormalizeHeader();\n testFillInTemplateFromObject();\n testIsCellEmpty();\n testIsAlnum();\n testIsDigit();\n}", "test () {\n let coloring = new Coloring(4);\n /* Create following graph and test whether it is\n 3 colorable\n (3)---(2)\n | / |\n | / |\n | / |\n (0)---(1)\n */\n let graph = [[0, 1, 1, 1],\n [1, 0, 1, 0],\n [1, 1, 0, 1],\n [1, 0, 1, 0]];\n let m = 3; // Number of colors\n this.graphColoring(graph, m);\n }", "function testRunner() {\n var featureNames;\n var feature;\n var aliasIdx;\n var result;\n var nameIdx;\n var featureName;\n var featureNameSplit;\n\n for (var featureIdx in tests) {\n featureNames = [];\n feature = tests[featureIdx];\n // run the test, throw the return value into the Modernizr,\n // then based on that boolean, define an appropriate className\n // and push it into an array of classes we'll join later.\n //\n // If there is no name, it's an 'async' test that is run,\n // but not directly added to the object. That should\n // be done with a post-run addTest call.\n if (feature.name) {\n featureNames.push(feature.name.toLowerCase());\n\n if (feature.options && feature.options.aliases && feature.options.aliases.length) {\n // Add all the aliases into the names list\n for (aliasIdx = 0; aliasIdx < feature.options.aliases.length; aliasIdx++) {\n featureNames.push(feature.options.aliases[aliasIdx].toLowerCase());\n }\n }\n }\n\n // Run the test, or use the raw value if it's not a function\n result = is(feature.fn, 'function') ? feature.fn() : feature.fn;\n\n\n // Set each of the names on the Modernizr object\n for (nameIdx = 0; nameIdx < featureNames.length; nameIdx++) {\n featureName = featureNames[nameIdx];\n // Support dot properties as sub tests. We don't do checking to make sure\n // that the implied parent tests have been added. You must call them in\n // order (either in the test, or make the parent test a dependency).\n //\n // Cap it to TWO to make the logic simple and because who needs that kind of subtesting\n // hashtag famous last words\n featureNameSplit = featureName.split('.');\n\n if (featureNameSplit.length === 1) {\n Modernizr[featureNameSplit[0]] = result;\n } else {\n // cast to a Boolean, if not one already\n /* jshint -W053 */\n if (Modernizr[featureNameSplit[0]] && !(Modernizr[featureNameSplit[0]] instanceof Boolean)) {\n Modernizr[featureNameSplit[0]] = new Boolean(Modernizr[featureNameSplit[0]]);\n }\n\n Modernizr[featureNameSplit[0]][featureNameSplit[1]] = result;\n }\n\n classes.push((result ? '' : 'no-') + featureNameSplit.join('-'));\n }\n }\n }", "function testRunner() {\n var featureNames;\n var feature;\n var aliasIdx;\n var result;\n var nameIdx;\n var featureName;\n var featureNameSplit;\n\n for (var featureIdx in tests) {\n featureNames = [];\n feature = tests[featureIdx];\n // run the test, throw the return value into the Modernizr,\n // then based on that boolean, define an appropriate className\n // and push it into an array of classes we'll join later.\n //\n // If there is no name, it's an 'async' test that is run,\n // but not directly added to the object. That should\n // be done with a post-run addTest call.\n if (feature.name) {\n featureNames.push(feature.name.toLowerCase());\n\n if (feature.options && feature.options.aliases && feature.options.aliases.length) {\n // Add all the aliases into the names list\n for (aliasIdx = 0; aliasIdx < feature.options.aliases.length; aliasIdx++) {\n featureNames.push(feature.options.aliases[aliasIdx].toLowerCase());\n }\n }\n }\n\n // Run the test, or use the raw value if it's not a function\n result = is(feature.fn, 'function') ? feature.fn() : feature.fn;\n\n\n // Set each of the names on the Modernizr object\n for (nameIdx = 0; nameIdx < featureNames.length; nameIdx++) {\n featureName = featureNames[nameIdx];\n // Support dot properties as sub tests. We don't do checking to make sure\n // that the implied parent tests have been added. You must call them in\n // order (either in the test, or make the parent test a dependency).\n //\n // Cap it to TWO to make the logic simple and because who needs that kind of subtesting\n // hashtag famous last words\n featureNameSplit = featureName.split('.');\n\n if (featureNameSplit.length === 1) {\n Modernizr[featureNameSplit[0]] = result;\n } else {\n // cast to a Boolean, if not one already\n /* jshint -W053 */\n if (Modernizr[featureNameSplit[0]] && !(Modernizr[featureNameSplit[0]] instanceof Boolean)) {\n Modernizr[featureNameSplit[0]] = new Boolean(Modernizr[featureNameSplit[0]]);\n }\n\n Modernizr[featureNameSplit[0]][featureNameSplit[1]] = result;\n }\n\n classes.push((result ? '' : 'no-') + featureNameSplit.join('-'));\n }\n }\n }", "function _runTest (index, basename, html) {\n const tests = [\n // preamble page\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // tests titlePage option\n _testToc(root, basename, 'Welcome');\n t.is(root.find('#_footnoteref_3').length, 1);\n t.is(root.find('#_footnotedef_3').length, 1);\n t.is(root.find('a.footnote').length, 1);\n t.is(root.find('div.footnote').length, 1);\n },\n // part I\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Part I');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap 1\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '1. First Chapter');\n t.is(root.find('#_footnoteref_4').length, 1);\n t.is(root.find('#_footnotedef_4').length, 1);\n t.is(root.find('a.footnote').length, 1);\n t.is(root.find('div.footnote').length, 1);\n },\n // chap 2\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2. Second Chapter');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec1\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2.1. Chap2. First Section');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2 (depth:2)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2.2. Chap2. Second Section');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2-1 (depth:3)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2.2.1. Chap2. Sec 2-1');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2-1-1 (depth:4)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Chap2. Sec 2-1-1');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2-1-2 (depth:4)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Chap2. Sec 2-1-2');\n t.is(root.find('#_footnoteref_4').length, 1);\n t.is(root.find('#_footnotedef_4').length, 1);\n t.is(root.find('a.footnote').length, 2); // multiply referred in Sec 2-1-2\n t.is(root.find('div.footnote').length, 1);\n },\n // chap2 sec2-2 (depth:3)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2.2.2. Chap2. Sec 2-2');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2-2-1 (depth:4)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Chap2. Sec 2-2-1');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2-2-2 (depth:4)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Chap2. Sec 2-2-2');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec2-2-3 (depth:4)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Chap2. Sec 2-2-3<sup class=\"footnote\">[1]</sup>');\n t.is(root.find('#_footnoteref_1').length, 1);\n t.is(root.find('#_footnotedef_1').length, 1);\n t.is(root.find('a.footnote').length, 1);\n t.is(root.find('div.footnote').length, 1);\n },\n // chap2 sec2-3 (depth:3)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2.2.3. Chap2. Sec 2-3');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap2 sec3 (depth:2)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '2.3. Chap2. Third Section');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // part II\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, 'Part II');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap 3 (depth:1)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '3. Third Chapter<sup class=\"footnote\">[2]</sup>');\n t.is(root.find('#_footnoteref_2').length, 1);\n t.is(root.find('#_footnotedef_2').length, 1);\n t.is(root.find('a.footnote').length, 1);\n t.is(root.find('div.footnote').length, 1);\n },\n // chap3 sec1 (depth:2)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '3.1. Chap3. First Section');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap3 sec2 (depth:2)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '3.2. Chap3. Second Section');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n // chap3 sec3 (depth:2)\n (basename, html) => {\n const root = Node.getInstanceFromHTML(html);\n // check toc\n _testToc(root, basename, '3.3. Chap3. Third Section');\n t.is(root.find('a.footnote').length, 0);\n t.is(root.find('div.footnote').length, 0);\n },\n ];\n if (tests[index])\n tests[index](basename, html);\n }", "async runTests() {\n for (let file of this.testFiles) {\n console.log(chalk.gray(`--- ${file.shortName}`));\n const beforeEaches = [];\n\n global.render = render;//jsdom\n\n global.beforeEach = (fn) => {\n beforeEaches.push(fn)\n };\n global.it = async (desc, fn) => {\n // console.log(desc);\n beforeEaches.forEach(func => func());\n //to handle errors ocurred during our test we need to do try and catch to avoid the test to collapse\n try {\n await fn();\n console.log(chalk.green(`\\tOK - ${desc}`));\n } catch (err) {\n const message = err.message.replace(/\\n/g, '\\n\\t\\t');\n console.log(chalk.red(`\\tX - ${desc}`));\n console.log(chalk.red('\\t', message));// \\t is tab \n }\n\n };\n //to skip the typo in stopping test for running\n try {\n require(file.name);//when we require the file inside a func node will find it and execute the file here\n } catch (err) {\n console.log(chalk.red('X - Error Loading File'), file.name);\n console.log(chalk.red(err));\n }\n\n }\n }", "runnerEnd(runner) {\n const specData = this.moduleName ? this.specHashData[this.moduleName] : this.specHashData;\n Object.values(specData).forEach((spec) => {\n const revSpecs = Object.values(spec);\n revSpecs.forEach((test, i) => {\n if (test.parent === test.title) {\n const { title, parent, ...rest } = revSpecs[i];\n revSpecs[i] = {\n title,\n spec: runner.specs[0],\n ...rest,\n };\n }\n if (test.parent !== test.title) {\n const parentIndex = revSpecs.findIndex(\n (item) => item.title === test.parent,\n );\n\n if (parentIndex > -1) {\n if (!revSpecs[parentIndex].suites) {\n revSpecs[parentIndex].suites = [];\n }\n revSpecs[parentIndex].suites.push(test);\n // eslint-disable-next-line no-param-reassign\n delete test.parent;\n }\n }\n // eslint-disable-next-line no-param-reassign\n delete test.parent;\n });\n if (this.moduleName) {\n const filePathLocation = path.join(\n this.resultsDir,\n `${this.fileName}.json`,\n );\n this.resultJsonObject.specs[this.moduleName] = revSpecs.shift();\n this.writToFile(this.resultJsonObject.specs[this.moduleName], filePathLocation);\n } else {\n this.nonMonoRepoResult.push(revSpecs.shift());\n }\n });\n if (!this.moduleName) {\n this.resultJsonObject.specs = this.nonMonoRepoResult;\n const filePathLocation = path.join(\n this.resultsDir,\n `${this.fileName}.json`,\n );\n this.writToFile(this.resultJsonObject, filePathLocation);\n }\n this.screenshots = [];\n this.specHashData = {};\n }", "function testRunner() {\n\t\tvar featureNames;\n\t\tvar feature;\n\t\tvar aliasIdx;\n\t\tvar result;\n\t\tvar nameIdx;\n\t\tvar featureName;\n\t\tvar featureNameSplit;\n\n\t\tfor (var featureIdx in tests) {\n\t\t\tif (tests.hasOwnProperty(featureIdx)) {\n\t\t\t\tfeatureNames = [];\n\t\t\t\tfeature = tests[featureIdx];\n\t\t\t\t// run the test, throw the return value into the Modernizr,\n\t\t\t\t// then based on that boolean, define an appropriate className\n\t\t\t\t// and push it into an array of classes we'll join later.\n\t\t\t\t//\n\t\t\t\t// If there is no name, it's an 'async' test that is run,\n\t\t\t\t// but not directly added to the object. That should\n\t\t\t\t// be done with a post-run addTest call.\n\t\t\t\tif (feature.name) {\n\t\t\t\t\tfeatureNames.push(feature.name.toLowerCase());\n\n\t\t\t\t\tif (feature.options && feature.options.aliases && feature.options.aliases.length) {\n\t\t\t\t\t\t// Add all the aliases into the names list\n\t\t\t\t\t\tfor (aliasIdx = 0; aliasIdx < feature.options.aliases.length; aliasIdx++) {\n\t\t\t\t\t\t\tfeatureNames.push(feature.options.aliases[aliasIdx].toLowerCase());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Run the test, or use the raw value if it's not a function\n\t\t\t\tresult = is(feature.fn, 'function') ? feature.fn() : feature.fn;\n\n\n\t\t\t\t// Set each of the names on the Modernizr object\n\t\t\t\tfor (nameIdx = 0; nameIdx < featureNames.length; nameIdx++) {\n\t\t\t\t\tfeatureName = featureNames[nameIdx];\n\t\t\t\t\t// Support dot properties as sub tests. We don't do checking to make sure\n\t\t\t\t\t// that the implied parent tests have been added. You must call them in\n\t\t\t\t\t// order (either in the test, or make the parent test a dependency).\n\t\t\t\t\t//\n\t\t\t\t\t// Cap it to TWO to make the logic simple and because who needs that kind of subtesting\n\t\t\t\t\t// hashtag famous last words\n\t\t\t\t\tfeatureNameSplit = featureName.split('.');\n\n\t\t\t\t\tif (featureNameSplit.length === 1) {\n\t\t\t\t\t\tModernizr[featureNameSplit[0]] = result;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// cast to a Boolean, if not one already\n\t\t\t\t\t\t/* jshint -W053 */\n\t\t\t\t\t\tif (Modernizr[featureNameSplit[0]] && !(Modernizr[featureNameSplit[0]] instanceof Boolean)) {\n\t\t\t\t\t\t\tModernizr[featureNameSplit[0]] = new Boolean(Modernizr[featureNameSplit[0]]);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tModernizr[featureNameSplit[0]][featureNameSplit[1]] = result;\n\t\t\t\t\t}\n\n\t\t\t\t\tclasses.push((result ? '' : 'no-') + featureNameSplit.join('-'));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "async function runAllTests() {\n const files = [];\n const x = new Assert();\n x.blessEnabled = process.argv.findIndex(arg => arg === '--bless') !== -1;\n\n x.startTestSuite('all', false);\n print('> Starting all tests...');\n print('');\n\n fs.readdirSync(__dirname).forEach(function(file) {\n const fullPath = path.join(__dirname, file);\n if (file.endsWith('.js') && fs.lstatSync(fullPath).isFile()) {\n files.push(fullPath);\n }\n });\n files.sort();\n let tmp;\n for (let i = 0; i < files.length; ++i) {\n try {\n tmp = require(files[i]);\n if (tmp['check'] === undefined) {\n continue;\n }\n } catch (err) {\n print(`failed to load \\`${files[i]}\\`, ignoring it...`);\n }\n\n try {\n await tmp['check'](x);\n } catch (err) {\n x._incrError();\n print(`<== \\`${files[i]}\\` failed: ${err}\\n${err.stack}`);\n }\n print('');\n }\n\n print('');\n print(`< Ending ${x.getTotalRanTests()} ${plural('test', x.getTotalRanTests())} with ` +\n `${x.getTotalErrors()} ${plural('error', x.getTotalErrors())}`);\n\n const errors = x.getTotalErrors();\n x.endTestSuite(false);\n return errors;\n}", "function generateTest() {\n // TODO\n}", "function GetTestability() {}", "function GetTestability() {}", "function GetTestability() {}", "describe() {\n console.log(`It is a ${this.flavor} cake with ${this.icing} icing and decorated with ${this.decoration}`)\n \n while (){\nlet count = 0\n if {\n console.log(`YUM! What a great slice of cake!`)\n } else {\n console.log(`No more cake for you, you've had enough!`)\n \n }\n }\n\n}", "function specReporter (results) {\n for (var i = 0; i < results.length; i++) {\n if (lastSection !== results[i].current) {\n lastSection = results[i].current;\n console.log(\"\\n\" + lastSection + \":\");\n }\n\n if (results[i].status === 'pass') {\n console.log(\" ✓ \" + color(results[i].message, \"green\"));\n } else {\n console.log(\" ✗ \" + color(results[i].message, \"yellow\"));\n console.log(\" » \" + color(\"expected \" + results[i].expected + \",\", \"yellow\"));\n console.log(\" \" + color(\"got \" + results[i].actual + \"(\" + results[i].operator + \")\", \"yellow\"));\n }\n }\n}", "async function main() {\n const g_tests = async (flag) => {\n let test_base;\n let prefix = '';\n switch (flag) {\n case 'm':\n test_base = test_base_general;\n prefix = 'test_';\n break;\n case 'a':\n test_base = test_base_audio;\n prefix = 'test_';\n break;\n case 's':\n case 'c':\n test_base = test_base_toc;\n break;\n }\n ;\n const retval = await get_tests(`${test_base}/index.json`, prefix);\n return retval;\n };\n const preamble_run_test = async (name) => {\n if (name[0] === 'm' || name[0] === 'a' || name[0] === 's' || name[0] === 'c') {\n const tests = await g_tests(name[0]);\n run_test(tests[name].url);\n }\n else {\n throw new Error('Abnormal test id...');\n }\n };\n try {\n if (process.argv && process.argv.length > 2) {\n if (process.argv[2] === '-sm' || process.argv[2] === '-sa') {\n const label = process.argv[2][2];\n const tests = await g_tests(label);\n const scores = generate_scores(tests);\n console.log(JSON.stringify(scores, null, 4));\n }\n else if (process.argv[2] === '-l') {\n // run a local test that is not registered in the official test suite\n run_test(process.argv[3]);\n }\n else {\n preamble_run_test(process.argv[2]);\n }\n }\n else {\n preamble_run_test('m4.01');\n }\n }\n catch (e) {\n console.log(`Something went very wrong: ${e.message}`);\n process.exit(1);\n }\n}" ]
[ "0.57294434", "0.5580079", "0.5499903", "0.543109", "0.53744584", "0.53662854", "0.5349277", "0.5311394", "0.5297236", "0.5289699", "0.5285793", "0.5285352", "0.5285352", "0.5285352", "0.5278204", "0.5275723", "0.52538955", "0.52538955", "0.51994085", "0.51746184", "0.5172395", "0.5166695", "0.51257485", "0.5093231", "0.5067683", "0.5067683", "0.5067683", "0.5007992", "0.4999991", "0.49991336" ]
0.66634655
0
Public Functions / changeTagValueType update data when tag value type change
function changeTagValueType() { // Update the model value type vm.tagModel.valType = vm.tagValueTypeDropdown.selectedTagValueType.value; if (vm.tagModel.valType === 'P') { // Trigger a blur to update the input formatting $timeout(function() { $('#tag-percent-input').blur(); }, 0); } else { // Trigger a blur to update the input formatting $timeout(function() { $('#tag-currency-input').blur(); }, 0); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function updateTagValue() {\n\n\t\tif (!isUpdateValid()) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Start processing animation\n\t\tvm.tagModel.processing = true;\n\n\t\t// Allow the animation to complete before closing\n\t\t$timeout(function() {\n\n\t\t\t// Update the tag values by reference\n\t\t\tvm.initTagData.valType = vm.tagModel.valType;\n\t\t\tvm.initTagData.valAmount = vm.tagModel.valType === 'P' ?\n\t\t\t\tvm.percentSlider.model : vm.currencySlider.model;\n\n\t\t\t$scope.close();\n\t\t}, 250);\n\t}", "function onTagChange($e,$data){\n\t\t\taddTag($data.item.value);\n\t\t}", "updateValueByDOMTags(){\n this.value.length = 0;\n\n [].forEach.call(this.getTagElms(), node => {\n if( node.classList.contains(this.settings.classNames.tagNotAllowed.split(' ')[0]) ) return\n this.value.push( getSetTagData(node) )\n })\n\n this.update()\n }", "set tag(value) {}", "set tag(value) {}", "set tag(value) {}", "set tag(value) {}", "function changeTags(value){\n setTags(value)\n console.log(tags)\n }", "tagChange(tag) {\n let tagPos = this.tags.indexOf(tag);\n if (tagPos === this.tags.length-1 && (tag.name !== '' || tag.value !== '')) this.addEmptyTag();\n }", "function onTagChange() {\n\n\t}", "valueTypeChanged() {\n if (!this.isValueTypeSelect()) {\n this.maxValueCount = AnnotationMaxValueCount.NONE;\n }\n this.options = [];\n }", "function changeTaggableModel(newTaggableId, newTaggableType) {\n taggableId = newTaggableId;\n taggableType = newTaggableType;\n updateExistingTagLabels();\n}", "function changeDataType(newDataType) {\n console.log('changeDataType: ' + DATATYPE_NAME[newDataType]);\n gDataType = parseInt(newDataType);\n\n // Enable or disable the 'lower case' checkbox based on new data type.\n var elem = $('#lower-case-checkbox input');\n if (newDataType == DATATYPE_STRING) {\n elem.removeAttr('disabled');\n } else {\n elem.attr('disabled', true);\n }\n\n // Change the placeholders to match the data type.\n changeControlPanelPlaceholders();\n\n // Clear out any of the old data.\n clearInputData();\n clearOutputData();\n\n // Build a new tree with the new data type.\n gTree = new BinarySearchTree();\n}", "replace( t, old_type, new_type ) {\n if(t.type==old_type) t.type = new_type\n if( Array.isArray(t.value) ) {\n var a = t.value\n for(var i=0; i<a.length; i++) a[i] = this.replace(a[i], old_type, new_type)\n } \n return t\n }", "function value_modification_handler(node) {\n node = node || document;\n let inps = node.getElementsByClassName('terminus-value');\n\n for (let i = 0; i < inps.length; i++) {\n let inp = inps[i];\n inp.addEventListener('change', function () {\n this.classList.add('value-modified');\n let pnd = this.parentNode._boundData;\n pnd.object[pnd.prop] = this.value;\n });\n }\n}", "onValueChange(value) {\n const { fieldValue } = this.props;\n const { onFieldValueChange } = this.context.jsonEditor;\n const valueType = getValueType(fieldValue);\n\n onFieldValueChange(this.getFieldPath(), coerceToType(value, valueType));\n }", "updateValue(type){\n // if (type === \"Distribution\"){\n // this.item.class = \"BoundedNormalDistribution\";\n // }\n this.item.class = type;\n this.updated.emit(this.item);\n }", "onUpdateTagAtIndex() {}", "updateDataType_() {\n /** @type {!Object} */\n this.dataType = {\n bits: ((parseInt(this.bitDepth, 10) - 1) | 7) + 1,\n float: this.bitDepth == '32f' || this.bitDepth == '64',\n signed: this.bitDepth != '8',\n be: this.container == 'RIFX'\n };\n if (['4', '8a', '8m'].indexOf(this.bitDepth) > -1 ) {\n this.dataType.bits = 8;\n this.dataType.signed = false;\n }\n }", "function setDataType(valueName, valueModel){\n switch(valueName){\n case \"on\":\n case \"reachable\":\n valueModel.set(\"number\", {min: 0, max: 1, step: 1, unit: \"int\"});\n break;\n case \"bri\":\n case \"sat\":\n valueModel.set(\"number\", {min: 0, max: 255, step: 1, unit: \"int\"});\n break;\n case \"hue\":\n valueModel.set(\"number\", {min: 0, max: 65535, step: 1, unit: \"int\"});\n break;\n default:\n valueModel.set(\"string\", {max: 99});\n break;\n }\n}", "function setTag(key, value) {\n callOnHub('setTag', key, value);\n}", "function setTag(key, value) {\n callOnHub('setTag', key, value);\n}", "function setTag(key, value) {\n callOnHub('setTag', key, value);\n}", "async function updateTag(cluster, tagID, valueChange, reloadDatabase = true) {\n try {\n const index = cluster.Tags.findIndex((t) => t[tagUniqueIdentifier] === tagID);\n\n // if the tag wasn't found\n if (index < -1) {\n const description = 'Error Description: \\n\\t==>Updating tag Failed. No tag found with such id';\n const error = new Error(description);\n this.emit('error', new Error('Invalid id'), description);\n throw error;\n }\n\n for (let attribute in valueChange) {\n cluster.Tags[index][attribute] = valueChange[attribute];\n }\n if (reloadDatabase) await updateDoc(cluster.clusterID, cluster);\n } catch (error) {\n // pass the error the the caller\n throw error;\n }\n }", "updateDataType_() {\n this.dataType = {\n bits: ((parseInt(this.bitDepth, 10) - 1) | 7) + 1,\n fp: this.bitDepth == '32f' || this.bitDepth == '64',\n signed: this.bitDepth != '8',\n be: this.container == 'RIFX'\n };\n if (['4', '8a', '8m'].indexOf(this.bitDepth) > -1 ) {\n this.dataType.bits = 8;\n this.dataType.signed = false;\n }\n }", "function setTag(key, value) {\n\t getCurrentHub().setTag(key, value);\n\t}", "function valueTypeChange() {\n if (vm.annotType.valueType === 'Select') {\n // add an option if none exist\n if (!vm.annotType.options || (vm.annotType.options.length < 1)) {\n optionAdd();\n }\n } else {\n vm.annotType.options = undefined;\n vm.annotType.maxValueCount = 0;\n }\n }", "function updateDataValue(elem, data){\n let value = X3domCreateArray(data, 1);\n setX3domAttribut(elem, value, \"value\");\n x3dElem.render();\n}", "updateDataType_() {\r\n this.dataType = {\r\n bits: ((parseInt(this.bitDepth, 10) - 1) | 7) + 1,\r\n fp: this.bitDepth == '32f' || this.bitDepth == '64',\r\n signed: this.bitDepth != '8',\r\n be: this.container == 'RIFX'\r\n };\r\n if (['4', '8a', '8m'].indexOf(this.bitDepth) > -1 ) {\r\n this.dataType.bits = 8;\r\n this.dataType.signed = false;\r\n }\r\n }", "set type(value) {}" ]
[ "0.6505273", "0.6376833", "0.6187452", "0.6109588", "0.6109588", "0.6109588", "0.6109588", "0.6048532", "0.5974636", "0.59192455", "0.5913044", "0.58147687", "0.5695044", "0.5641808", "0.56093323", "0.5592057", "0.558667", "0.55201674", "0.5517151", "0.55169946", "0.5466293", "0.5466293", "0.5466293", "0.54393744", "0.543082", "0.5424716", "0.54224753", "0.5420062", "0.5390135", "0.5379074" ]
0.7618515
0
isUpdateValid is the tag value form valid?
function isUpdateValid() { var modelNum, maxNum; if (vm.tagModel.valType === 'P') { modelNum = Number(vm.percentSlider.model); maxNum = 100; } else { modelNum = Number(vm.currencySlider.model); maxNum = Number(vm.currencySlider.options.max); } return modelNum > 0 && modelNum <= maxNum; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function _formUpdateValid(){\n \tif ($scope.updateuser.$valid){\n \t\treturn true;\n \t} else {\n \t\treturn false;\n \t\t}\n }", "check_update(value) { return (this.value != value); }", "validateBeforeUpdate (id, newData, prevData) { return true }", "function isObsFormValid(){\t \n var v1 = textoObsField.isValid();\n return( v1);\n }", "function validateUpdate(item) {\n\n //Required schema of the input data\n const schema = {\n value: Joi.string().min(1).required(),\n ttl: Joi.number().required()\n\n };\n return Joi.validate(item, schema); //Return validation result\n}", "function validateLiveUpdates() {\n const current = new Date();\n const currentDate = current.toISOString().slice(0, 10);\n\n if (formData[\"liveUpdating\"]\n && currentDate > formData[\"enddatetime\"]) {\n return false;\n }\n\n return true;\n }", "_checkUpdateIsAble () {\n function error (parameter) {\n throw new Error (`Parameter '${parameter}' is forbidden in UPDATE query`)\n }\n if (this._selectStr.length > 1) error('only')\n if (this._orderStr) error('orderBy')\n if (this._limitStr) error('limit')\n if (this._offsetStr) error('offset')\n return true\n }", "isValid() {\n if (\n this.state.isDanger ||\n this.state.apiValue === '' ||\n this.state.apiValue === undefined\n )\n return false;\n\n return true;\n }", "validateUpdate(selector){\n for(const update of this.#updateCollection){\n if(update.selector === selector){\n return true\n }\n }\n return false\n }", "function validateCreativeTag() {\n var ele = $('textarea[name*=\"tags.tag\"]'),\n val = ele.val();\n\n if (($scope.creativeMode === 'edit') && val) {\n fireAPItoValidate(ele, val);\n }\n\n ele.on('change', function () {\n localStorage.setItem('isOnchangeOfCreativeFeild', 1);\n val = $(this).val();\n fireAPItoValidate(this, val);\n });\n }", "function updateTagValue() {\n\n\t\tif (!isUpdateValid()) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Start processing animation\n\t\tvm.tagModel.processing = true;\n\n\t\t// Allow the animation to complete before closing\n\t\t$timeout(function() {\n\n\t\t\t// Update the tag values by reference\n\t\t\tvm.initTagData.valType = vm.tagModel.valType;\n\t\t\tvm.initTagData.valAmount = vm.tagModel.valType === 'P' ?\n\t\t\t\tvm.percentSlider.model : vm.currencySlider.model;\n\n\t\t\t$scope.close();\n\t\t}, 250);\n\t}", "updateTag(req, res, next) {\n let { success, code } = checkValidation(req, tags.paramValidation.update)\n if (!success) {\n return res.status(422).send(responseCreator(code))\n }\n next();\n }", "function alsoValidate() {\n const { hasError, error } = validateURL(e.target.value)\n onUpdate(idx, e.target.value, hasError, error)\n }", "validateUpdateListItem(formValues, newDocumentUpdate = false) {\r\n return this.clone(Item, \"validateupdatelistitem\").postCore({\r\n body: jsS({ \"formValues\": formValues, bNewDocumentUpdate: newDocumentUpdate }),\r\n });\r\n }", "function isValidUpdateForm() {\n\tvar name = $(\"#name-update\").val();\n\tvar date = $(\"#date-update\").val();\n\tvar score = $(\"#scores-update\").val();\n\t\n\tvar checkName = isValidName(name);\n\tvar checkDate = isValidDate(date);\n\tvar checkScore = isValidScore(score);\n\t\n\t$(\"#invalid-name-update\").html(\"\");\n\t$(\"#invalid-date-update\").html(\"\");\n\t$(\"#invalid-score-update\").html(\"\");\n\t\n\tif (!checkName || !checkDate || !checkScore) {\n\t\tif (!checkName) {\n\t\t\t$(\"#invalid-name-update\").html(\"Invalid student's name\");\n\t\t}\n\t\tif (!checkDate) {\n\t\t\t$(\"#invalid-date-update\").html(\"Invalid student's date\");\n\t\t}\n\t\tif (!checkScore) {\n\t\t\t$(\"#invalid-score-update\").html(\"Invalid student's score\");\n\t\t}\n\t\treturn false;\n\t}\n\treturn true;\n}", "validate()\n {\n if (this.dirty)\n {\n this.updateText();\n this.dirty = false;\n }\n }", "afterValidChange() { }", "_updateIsDirty() {\n if (!this.hasRendered) return;\n\n const commentContent = this.getCommentContent();\n const attachmentsElement = this.shadowRoot.querySelector('mr-upload');\n this.isDirty = !isEmptyObject(this.delta) || Boolean(commentContent) ||\n attachmentsElement.hasAttachments;\n }", "function isFormUpdateEventHandler( event ){\n const form = event.target.closest(\"form\");\n const isFormUpdate = document.createElement(\"input\");\n isFormUpdate.type = \"hidden\";\n isFormUpdate.name = \"is_form_update\";\n isFormUpdate.value = 'True'\n form.appendChild(isFormUpdate);\n form.querySelectorAll('[type=submit]')[0].click();\n}", "onCheckFormValue(newSoftware) {\n let invalid = false;\n\n if (!_.trim(newSoftware.softwareType).length) {\n invalid = true;\n }\n\n if (!_.trim(newSoftware.name).length) {\n invalid = true;\n }\n\n this.setState({ formInvalid: invalid });\n return invalid;\n }", "function fanTuriYozishUpdate() {\n let nomi = document.forms['updateFanTuriForm']['nomiUpdate'].value;\n let tugma = document.getElementById('fanTuriUpdate');\n if (nomi == \"\") {\n tugma.disabled = true;\n } else {\n tugma.disabled = false;\n }\n}", "function oqituvchiYozishUpdate() {\n let tugma = document.getElementById('oqituvchiUpdate');\n let ism = document.forms['updateOqituvchiForm']['ismUpdate'].value;\n let familiya = document.forms['updateOqituvchiForm']['familiyaUpdate'].value;\n let nomer = document.forms['updateOqituvchiForm']['nomerUpdate'].value;\n let tajriba = document.forms['updateOqituvchiForm']['tajribaUpdate'].value;\n let togilganYili = document.forms['updateOqituvchiForm']['togilganYiliUpdate'].value;\n let qisqaMalumot = document.forms['updateOqituvchiForm']['qisqaMalumotUpdate'].value;\n if (ism == \"\" || familiya == \"\" || nomer == \"\" || tajriba == \"\" || togilganYili == \"\" || qisqaMalumot == \"\") {\n tugma.disabled = true;\n } else {\n tugma.disabled = false;\n }\n}", "function validateUpdate(update, errors) {\n const act = update.ssAct ?? '';\n switch (act) {\n case '':\n errors.ssAct = 'Action must be specified.';\n return false;\n case 'clear':\n return validateFields('Clear', [], ['cellId', 'formula'], update, errors);\n case 'deleteCell':\n return validateFields('Delete Cell', ['cellId'], ['formula'],\n\t\t\t update, errors);\n case 'copyCell': {\n const isOk = validateFields('Copy Cell', ['cellId','formula'], [],\n\t\t\t\t update, errors);\n if (!isOk) {\n\treturn false;\n }\n else if (!FIELD_INFOS.cellId.err(update.formula)) {\n\t return true;\n }\n else {\n\terrors.formula = `Copy requires formula to specify a cell ID`;\n\treturn false;\n }\n }\n case 'updateCell':\n return validateFields('Update Cell', ['cellId','formula'], [],\n\t\t\t update, errors);\n default:\n errors.ssAct = `Invalid action \"${act}`;\n return false;\n }\n}", "function validateUpdate(update, errors) {\n const act = update.ssAct ?? '';\n switch (act) {\n case '':\n errors.ssAct = 'Action must be specified.';\n return false;\n case 'clear':\n return validateFields('Clear', [], ['cellId', 'formula'], update, errors);\n case 'deleteCell':\n return validateFields('Delete Cell', ['cellId'], ['formula'],\n\t\t\t update, errors);\n case 'copyCell': {\n const isOk = validateFields('Copy Cell', ['cellId','formula'], [],\n\t\t\t\t update, errors);\n if (!isOk) {\n\treturn false;\n }\n else if (!FIELD_INFOS.cellId.err(update.formula)) {\n\t return true;\n }\n else {\n\terrors.formula = `Copy requires formula to specify a cell ID`;\n\treturn false;\n }\n }\n case 'updateCell':\n return validateFields('Update Cell', ['cellId','formula'], [],\n\t\t\t update, errors);\n default:\n errors.ssAct = `Invalid action \"${act}`;\n return false;\n }\n}", "validateOnChange(e) {\n // only update the validation for this field\n return this.validate(e, true);\n }", "editTagChangeDetected(tagData) {\n var originalData = tagData.__originalData;\n\n for( var prop in originalData )\n if( !this.dataProps.includes(prop) && tagData[prop] != originalData[prop] )\n return true\n\n return false; // not changed\n }", "updateErrorState(value) {\r\n let isValid = true;\r\n let errorMessage = this.validInput(value);\r\n if (errorMessage)\r\n isValid = false;\r\n this.setState({ error: (isValid ? null : errorMessage) });\r\n return isValid;\r\n }", "function checkUpdate()\n{\n\t// Collect input fields.\n\tvar inputs = $(\"#startCity, #startState, #endCity, #endState\");\n\n\t// Make sure they all contain values.\n\tif (inputs[0].value != \"\" && inputs[1].value != \"\" && inputs[2].value != \"\" && inputs[3].value != \"\")\n\t{\n\t\tupdate();\n\t}\n}", "isUpdatePermitted() {\n return this.checkAdminPermission('update')\n }", "isChanged(name) {\n var e = this.getFormControl(name);\n return e && (e.dirty || e.touched);\n }" ]
[ "0.6944741", "0.63028544", "0.6260635", "0.6087864", "0.6078639", "0.6070235", "0.60670257", "0.58582544", "0.58548623", "0.57840073", "0.57627743", "0.5752816", "0.57387906", "0.571443", "0.56738544", "0.5644522", "0.5641344", "0.56112695", "0.55955", "0.5535345", "0.5534027", "0.5531972", "0.55281556", "0.55281556", "0.55247897", "0.55170417", "0.55150133", "0.54980516", "0.54810613", "0.5468513" ]
0.7146377
0
updateTagValue update the value of the tag
function updateTagValue() { if (!isUpdateValid()) { return; } // Start processing animation vm.tagModel.processing = true; // Allow the animation to complete before closing $timeout(function() { // Update the tag values by reference vm.initTagData.valType = vm.tagModel.valType; vm.initTagData.valAmount = vm.tagModel.valType === 'P' ? vm.percentSlider.model : vm.currencySlider.model; $scope.close(); }, 250); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "set tag(value) {}", "set tag(value) {}", "set tag(value) {}", "set tag(value) {}", "updateValueByDOMTags(){\n this.value.length = 0;\n\n [].forEach.call(this.getTagElms(), node => {\n if( node.classList.contains(this.settings.classNames.tagNotAllowed.split(' ')[0]) ) return\n this.value.push( getSetTagData(node) )\n })\n\n this.update()\n }", "onUpdateTagAtIndex() {}", "function setTag(key, value) {\n callOnHub('setTag', key, value);\n}", "function setTag(key, value) {\n callOnHub('setTag', key, value);\n}", "function setTag(key, value) {\n callOnHub('setTag', key, value);\n}", "function setTag(key, value) {\n\t getCurrentHub().setTag(key, value);\n\t}", "function changeTags(value){\n setTags(value)\n console.log(tags)\n }", "vouchFor(tagsdoc, index) {\n\n var tag = tagsdoc.tags[index];\n var modified_tag = {\n value: tag.value,\n count: tag.count + 1,\n };\n tagsdoc.tags[index] = modified_tag;\n db_pending.put({\n _id: tagsdoc._id,\n _rev: tagsdoc._rev,\n type: \"tag\",\n tags: tagsdoc.tags,\n }, function (err, response) {\n if (err) {\n console.log(err);\n }\n console.log(\"successfully upvoted\");\n });\n\n }", "function updateValue( value ) \n{\n \n updateComponentValue( value );\n \n}", "function postAddTagValue(data, textStatus, jqXHR, param) {\n\tvar tag = param.tag;\n\tvar row = param.row;\n\tvar allTags = param.allTags;\n\tvar predicate = param.predicate;\n\tvar value = htmlEscape($('#'+idquote(tag)+'_id').val());\n\tvalue = sanitize(value);\n\tvar valueTr = $('<tr>');\n\tvalueTr.insertBefore(row);\n\tvar valueTd = $('<td>');\n\tvalueTr.append(valueTd);\n\tvalueTd.addClass('file-tag');\n\tvalueTd.addClass(tag);\n\tvalueTd.addClass('multivalue');\n\tif (tag == 'url') {\n\t\tvar a = $('<a>');\n\t\tvalueTd.append(a);\n\t\ta.attr({'href': value});\n\t\ta.html(value);\n\t} else {\n\t\tvalueTd.html(value);\n\t}\n\tvalueTd = $('<td>');\n\tvalueTr.append(valueTd);\n\tvalueTd.addClass('file-tag');\n\tvalueTd.addClass(tag);\n\tvalueTd.addClass('multivalue');\n\tvalueTd.addClass('delete');\n\tvar input = $('<input>');\n\tinput.attr({'type': 'button',\n\t\t'name': 'tag',\n\t\t'value': value\n\t});\n\tinput.val('Remove Value');\n\tvalueTd.append(input);\n\tinput.click({\t'tag': tag,\n\t\t\t\t\t'value': value},\n\t\t\t\t\tfunction(event) {removeTagValue(event.data.tag, event.data.value, $(this).parent().parent(), predicate);});\n\t$('#'+idquote(tag)+'_id').val('');\n\tif (!allTags[tag]['tagdef multivalue']) {\n\t\tvalueTr.prev().remove();\n\t}\n}", "function setTag(key, value) {\n hub.getCurrentHub().setTag(key, value);\n}", "setvalue(tags) {\n for (let tag of tags) {\n if (tag.body.items && tag.body.items.length > 0) tag.body.value = tag.body.items[tag.body.items.length - 1].value\n else if (tag.body.source) tag.body.value = tag.body.source;\n }\n console.log('Annotations, tags', tags)\n //aggregate targets\n }", "function updateSliderValue(element, value) {\n //console.log(element + \" has value \" + value);\n values[element] = value\n let valEle= \"value\" + element;\n document.getElementById(valEle).innerHTML = \"Value: \" + value;\n}", "function handleTagSearch() {\n const newValues = document.getElementById('search_input').value\n setNewTagOption(newValues)\n console.log('newValues: ', newValues)\n }", "function onTagChange($e,$data){\n\t\t\taddTag($data.item.value);\n\t\t}", "updateCurrentTag(newTag) {\n this.setState({ currentTag: newTag });\n }", "function commonSetValue(tag, value)\n{\n\n//alert(tag + '<<<>>>>' + value);\n\n var s = document.getElementById(tag);\n s.value = value;\n\n}", "set value(value)\n {\n this.updated = true\n this._value = value\n }", "_updateValue(value) {\n const valuesHandler = this._valuesHandler;\n valuesHandler.updateValue(valuesHandler.getActualValue(value));\n }", "tagChange(tag) {\n let tagPos = this.tags.indexOf(tag);\n if (tagPos === this.tags.length-1 && (tag.name !== '' || tag.value !== '')) this.addEmptyTag();\n }", "function update_tag(accepted, total_count, tag_name, accepted_count) {\r\n if(accepted_count > 0) {\r\n var badge_type = 3;\r\n\t if(accepted_count >= 100) {\r\n\t badge_type = 2;\r\n\t }\r\n\t if(accepted_count >= 400) {\r\n\t badge_type = 1;\r\n\t }\r\n accepted.tag_stats[accepted.tag_stats.length] = [tag_name, accepted_count, badge_type, total_count];\r\n update_answer_tags(accepted);\r\n }\r\n }", "async function updateTag(cluster, tagID, valueChange, reloadDatabase = true) {\n try {\n const index = cluster.Tags.findIndex((t) => t[tagUniqueIdentifier] === tagID);\n\n // if the tag wasn't found\n if (index < -1) {\n const description = 'Error Description: \\n\\t==>Updating tag Failed. No tag found with such id';\n const error = new Error(description);\n this.emit('error', new Error('Invalid id'), description);\n throw error;\n }\n\n for (let attribute in valueChange) {\n cluster.Tags[index][attribute] = valueChange[attribute];\n }\n if (reloadDatabase) await updateDoc(cluster.clusterID, cluster);\n } catch (error) {\n // pass the error the the caller\n throw error;\n }\n }", "function upVoteUpdate(counter, newval){\n\t \t$(counter).text(parseFloat(newval));\n\t }", "updateValue() {\n this.value = this.getValueFromView();\n this.emit(this.value);\n }", "function onattributevalue(token) {\n var attributes = currentTag.attributes\n var attribute = attributes[attributes.length - 1]\n\n attribute.value = parseEntities(slice(token, 1, 1), parseEntitiesOptions)\n attribute.position.end = point(token.end)\n }", "function updateTagView(tags, changedTag) {\n var outputTags = [];\n\n if (changedTag) {\n var tagIndex = tags.indexOf(changedTag);\n if (tagIndex == -1) {\n tags.push(changedTag);\n } else {\n tags.splice(tags.indexOf(changedTag), 1);\n }\n }\n\n $.each(tags, function(index, tag) {\n if (tag.match(/ /)) {\n outputTags.push('[[' + tag + ']]');\n } else {\n outputTags.push(tag);\n }\n });\n \n $('#editor input').val(outputTags.join(' '))\n}" ]
[ "0.6492815", "0.6492815", "0.6492815", "0.6492815", "0.6103223", "0.6081969", "0.596684", "0.596684", "0.596684", "0.59585774", "0.5846785", "0.5839426", "0.5806268", "0.5747082", "0.57427496", "0.5638813", "0.5456899", "0.54544014", "0.5444481", "0.54350126", "0.54139423", "0.53552973", "0.533765", "0.5317053", "0.5313749", "0.53082293", "0.52973354", "0.52732694", "0.525982", "0.523424" ]
0.7507505
0
Private Functions / percentSliderStop when the slider stops, blur the input to get the proper formatting
function percentSliderStop() { $('#tag-percent-input').blur(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "onSliderBlur() {\n gShaderToy.mMouseIsDown = false;\n }", "onSliderBlur() {\n gShaderToy.mMouseIsDown = false;\n }", "_blur(event) {\n // Depending on support for input[type=range],\n // the event.target could be either the handle or its child input.\n // Use closest() to locate the actual handle.\n event.target.closest(`.${CLASSNAME_HANDLE}`).classList.remove('is-focused');\n\n events.off('touchstart.Slider');\n events.off('mousedown.Slider');\n }", "_calcSliderValueDebounced(mouseVal, valueVar) {\n var val = this._scale.invert(mouseVal), //convert pixel --> value\n stepped = this._calcStepRounded(val), //round it\n inputElem = valueVar === 'value' ? this._inputStart : this._inputEnd; //which input field\n\n //validate that stepped is not greater than the other handle\n if(this.isRange) {\n stepped = (valueVar === 'value' && stepped > this.endValue) ? this.endValue : stepped;\n stepped = (valueVar === 'endValue' && stepped < this.value) ? this.value : stepped;\n }\n\n this.toggleClass('validation-error', false, inputElem);\n this.set(valueVar, stepped);\n }", "function currencySliderStop() {\n\n\t\t$('#tag-currency-input').blur();\n\t}", "function onSliderInput() {\n\tvar sibling = $(this).siblings('input').first();\n\tvar me = $(this);\n\tvar my_rel = me.data('slider-rel');\n\n\tvar my_val = Number(me.val());\n\tvar sib_val = Number(sibling.val());\n\tvar step = Number(me.attr('step'));\n\n\tif (my_rel == 'max' &&\n\t my_val < sib_val) {\n\t // My value is too low. Freeze at one step higher.\n\t me.val(Math.min(sib_val + step, 1440));\n\t} else if (my_rel == 'min' &&\n\t\t my_val > sib_val) {\n\t // My value is too high. Freeze at one step lower.\n\t me.val(Math.max(sib_val - step, 0));\n\t}\n\n\tvar target = $(this).data('display');\n\t$(target).text(util.minuteToTime($(this).val()));\n\n\tif (triggerCb) {\n\t if (my_rel == 'max') triggerCb(sib_val, my_val);\n\t else triggerCb(my_val, sib_val);\n\t}\n }", "function inputHandler() {\n stopAnimation();\n setTime(parseInt(slider.value));\n }", "onSliderChange(e) {\n var slider = e.target,\n axis = slider.getAttribute('data-axis'),\n vPart = slider.getAttribute('data-vPart'),\n value = slider.value;\n\n slider.nextSibling.textContent = vPart + ': ' + value;\n gShaderToy['mMouse' + axis] = value;\n gShaderToy.mForceFrame = true;\n setTimeout(this.onSliderBlur, 20);\n }", "onSliderChange(e) {\n var slider = e.target,\n axis = slider.getAttribute('data-axis'),\n vPart = slider.getAttribute('data-vPart'),\n value = slider.value;\n\n slider.nextSibling.textContent = vPart + ': ' + value;\n gShaderToy['mMouse' + axis] = value;\n gShaderToy.mForceFrame = true;\n setTimeout(this.onSliderBlur, 20);\n }", "sliderOnChange() {\n updateShaderToyTime(this.sliderInput.value);\n }", "sliderOnChange() {\n updateShaderToyTime(this.sliderInput.value);\n }", "function dragStop(e) {\n \n //setup variables\n var that = e.data,\n sliderMoveVal,\n trackingSlider = '';\n \n ///check if our slider is disabled\n if (!that.options.isDisabled) {\n \n //check if there is a step option\n if (that.options.step > 0) {\n \n //take the dragging element and move to the postion that you need\n if ($(that._prvt.draggingElem)[0] === that._prvt.handleMax[0]) {\n \n //calculate the value\n if(that._prvt.currentMax > that.options.maxLimit){\n that._prvt.currentMax = that.options.maxLimit;\n }\n \n //\n sliderMoveVal = unitsToPixels(that , that._prvt.currentMax) - that._prvt.innerOffset;\n \n //tracking value to add\n trackingSlider = '_max';\n } else {\n //out\n\n //check if the slider went lower than it should\n if(that._prvt.currentMin < that.options.minLimit){\n \n that._prvt.currentMin = that.options.minLimit;\n }\n \n //calculate value\n sliderMoveVal = unitsToPixels(that , that._prvt.currentMin) - that._prvt.innerOffset;\n \n //tracking value to add\n trackingSlider = '_min';\n }\n \n //animate slider\n $(that._prvt.draggingElem).animate({\n 'left': sliderMoveVal + 'px'\n }, 30);\n \n //adjust the sliderRange element\n $(that._prvt.sliderRange).animate({\n 'left': unitsToPixels(that , that._prvt.currentMin) - that._prvt.innerOffset+'px',\n 'width': (unitsToPixels(that , that._prvt.currentMax) - unitsToPixels(that , that._prvt.currentMin))+(that._prvt.handleWidth / 2)+'px'\n }, 30);\n }\n \n //remove custom events\n $('body').off('._RangeSlider'); //dragStop\n \n //set a flag for dragging\n that._prvt.isDragging = false;\n \n //trigger a custom event that updates backbone.js or any other listener\n $(that.element).trigger(that.options.events.onChange, {\n 'name': that.options.filterName,\n 'currentMin': that._prvt.currentMin,\n 'currentMax': that._prvt.currentMax\n });\n\n //bring back the click on the bar\n $(e.data.element).on('click._RangeSlider', '.sliderBar', that, onClickUpdate); //onClickUpdate\n\n }\n e.preventDefault();\n e.stopPropagation();\n }", "updateBlurValue() {\n if (this.blur < this.blurMin || this.blur > this.blurMax)\n this.blurChange = -this.blurChange;\n\n this.blur += this.blurChange;\n }", "function filterPercentSliderChange(slider) {\n\tfilterPercentValue = slider.value;\n\t\n\tif(filterByPercent) {\t\n\t\tredrawWithPercentFilter();\n\t}\n}", "updateSlider() {\n var outsideLoop = false;\n\n //this.loop = window.TimebarLoop;\n\n if (gShaderToy && !this.busy) {\n this.sliderInput.value = gShaderToy.mTf;\n }\n\n if (this.loop && gShaderToy.mTf > this.maxValueInput.value * 1000) {\n this.sliderInput.value = this.minValueInput.value * 1000;\n outsideLoop = true;\n }\n\n if (this.loop && gShaderToy.mTf < this.minValueInput.value * 1000) {\n this.sliderInput.value = this.minValueInput.value * 1000;\n outsideLoop = true;\n }\n\n if (outsideLoop) {\n updateShaderToyTime(this.sliderInput.value);\n updateInputsTime(this.sliderInput.value);\n }\n\n setTimeout(this.updateSlider.bind(this), 26);\n }", "updateSlider() {\n var outsideLoop = false;\n\n //this.loop = window.TimebarLoop;\n\n if (gShaderToy && !this.busy) {\n this.sliderInput.value = gShaderToy.mTf;\n }\n\n if (this.loop && gShaderToy.mTf > this.maxValueInput.value * 1000) {\n this.sliderInput.value = this.minValueInput.value * 1000;\n outsideLoop = true;\n }\n\n if (this.loop && gShaderToy.mTf < this.minValueInput.value * 1000) {\n this.sliderInput.value = this.minValueInput.value * 1000;\n outsideLoop = true;\n }\n\n if (outsideLoop) {\n updateShaderToyTime(this.sliderInput.value);\n updateInputsTime(this.sliderInput.value);\n }\n\n setTimeout(this.updateSlider.bind(this), 26);\n }", "_inputBlurHandler() {\n const that = this;\n\n if (that._suppressBlurEvent === true) {\n // suppresses validation because it was already handled in \"_incrementOrDecrement\" function\n that._suppressBlurEvent = false;\n\n if (that._formattedValue) {\n that._cachedInputValue = that._formattedValue;\n that.$.input.value = that._formattedValue;\n delete that._formattedValue;\n }\n }\n else if (that.$.input.value !== that._editableValue) {\n that._triggerChangeEvent = true;\n that._validate();\n that._triggerChangeEvent = false;\n }\n else {\n that.$.input.value = that._cachedInputValue;\n }\n\n if (that.radixDisplay) {\n that.$.radixDisplayButton.removeAttribute('focus');\n }\n\n if (that.opened) {\n that._closeRadix();\n }\n\n if (that.spinButtons) {\n that.$.spinButtonsContainer.removeAttribute('focus');\n }\n if (that.showUnit) {\n that.$.unitDisplay.removeAttribute('focus');\n }\n\n that.removeAttribute('focus');\n }", "function weightSliderValueChange() {\n $('#sliderWeight').on('input', function () { //versions of IE < 9 do not support this event, they have proprietary onPropertyChange event\n $('.sliderWeightValue').text($(this).val() + \"%\");\n }).on('mouseup', function () {\n var value = $(this).val();\n\n //remove selected value on another slider\n $('#sliderSummation').val(0);\n $('.sliderSummationValue').text(\"-\");\n\n //show overlays\n $('#controls-panel-overlay').show();\n $('#best-results-table-overlay').show();\n\n $('.sliderWeightValue').text(value + \"%\");\n $('input[type=radio][name=select]:checked').prop('checked', false);\n setTimeout(function(){\n selectButtonsByWeight(value);\n displayModelsSelectedByWeight(value, selectedSolution);\n displayCurves();\n }, 10);\n });\n}", "function blackAndWhiteThresholdSliderOnInput() {\n\tvar slider = document.getElementById(\"BlackAndWhiteThresholdSlider\");\n\tvar num_input = document.getElementById(\"BlackAndWhiteThresholdValue\");\n\t\n\tnum_input.value = slider.value;\n}", "function weightSumValueChange() {\n $('#sliderSummation').on('input', function () {\n $('.sliderSummationValue').text($(this).val() + \"%\");\n }).on('mouseup', function () {\n var value = $(this).val();\n\n //remove selected value on another slider\n $('#sliderWeight').val(0);\n $('.sliderWeightValue').text(\"-\");\n\n //show overlays\n $('#controls-panel-overlay').show();\n $('#best-results-table-overlay').show();\n\n $('.sliderSummationValue').text(value + \"%\");\n $('input[type=radio][name=select]:checked').prop('checked', false);\n setTimeout(function(){\n selectButtonsByWeightSummation(value, selectedSolution);\n displayModels();\n displayCurves();\n }, 10);\n });\n}", "_calcSliderValue(mouseVal, valueVar) {\n this.debounce('_calcSliderValue', function() {\n this._calcSliderValueDebounced(mouseVal, valueVar);\n }, 10);\n }", "sliderOnMouseDown() {\n this.wasPaused = gShaderToy.mIsPaused;\n this.sliderInput.min = parseInt(this.minValueInput.value * 1000, 10);\n this.sliderInput.max = parseInt(this.maxValueInput.value * 1000, 10);\n\n if (!this.wasPaused) {\n this.busy = true;\n gShaderToy.pauseTime();\n }\n\n return false;\n }", "updateSlider_() {\n if (!this.sliderInput_) {\n return;\n }\n this.sliderInput_.setAttribute('value', this.getValue());\n }", "function blackAndWhiterThresholdValueOnInput() {\n\tvar slider = document.getElementById(\"BlackAndWhiteThresholdSlider\");\n\tvar num_input = document.getElementById(\"BlackAndWhiteThresholdValue\");\n\t\n\tslider.value = num_input.value;\n}", "sliderOnMouseDown() {\n this.wasPaused = gShaderToy.mIsPaused;\n this.sliderInput.min = parseInt(\n this.minValueInput.value * 1000,\n 10\n );\n this.sliderInput.max = parseInt(\n this.maxValueInput.value * 1000,\n 10\n );\n\n if (!this.wasPaused) {\n this.busy = true;\n gShaderToy.pauseTime();\n }\n\n return false;\n }", "blur() {\r\n this.isFocussed = false;\r\n this.showLimits = true;\r\n }", "interfaceBPMSliderCallback(faustControler) {\n var val;\n var input = faustControler.faustInterfaceView.slider;\n var fval = Number((parseFloat(input.value) * parseFloat(faustControler.itemParam.step)) + parseFloat(faustControler.itemParam.min));\n val = fval.toFixed(parseFloat(faustControler.precision));\n faustControler.value = val;\n var output = faustControler.faustInterfaceView.output;\n //---- update the value text\n if (output)\n output.textContent = \"\" + val + \" \" + faustControler.unit;\n this.BPM = fval;\n //this.setBPM(fval) \n }", "function setBlur(sender){\n sender.style.borderColor = \"\";\n showTextProgress(sender);\n if (theProgressDiv != null){\n hideObject(document.getElementById(theProgressDiv));\n }\n}", "function update_slider(slider_name, value, breakeven_active) { \n $('#baseline_service_life_text').tooltip('hide')\n $('#proposed_service_life_text').tooltip('hide')\n $('#lcoe_proposed').tooltip('hide')\n $('#lcoe_baseline').tooltip('hide')\n\n var slider = document.getElementById(slider_name);\n var max = slider.noUiSlider.options.range.max\n var min = slider.noUiSlider.options.range.min\n value = parseFloat(value)\n\n key = slider_name.substring(0, 8) // 'baseline' and 'proposed' are both 8 letters\n\n // for break-even purposes, calculate the maximum values after the slider is moved to make sure calculation based on most recent values\n // the following four conditions handle the popups on service life and degradation\n if (slider_name == 'baseline_degradation_rate') {\n\n var year = parseFloat($('#'+key+'_service_life_text').val())\n var max_degradation = 1 / (year - 0.5) * 100\n\n // checking equality\n if (!isNaN(value) && !(value < max_degradation)) {\n\n value = max_degradation // restrict displayed value based on maximum\n $('#baseline_degradation_rate_text').val(max_degradation.toFixed(2))\n document.getElementById('baseline_degradation_rate_text').setAttribute('data-original-title', 'Choose a shorter service life to enable a larger degradation rate.');\n\n $('#baseline_degradation_rate_text').tooltip('enable')\n $('#baseline_degradation_rate_text').tooltip('show')\n setTimeout(function(){\n $('#baseline_degradation_rate_text').tooltip('hide');\n }, 3000);\n } else {\n $('#baseline_degradation_rate_text').tooltip('disable')\n }\n\n }\n\n if (slider_name == 'proposed_degradation_rate') {\n var year = parseFloat($('#'+key+'_service_life_text').val())\n var max_degradation = 1 / (year - 0.5) * 100\n\n if (!isNaN(value) && !(value < max_degradation)) { //!isNaN to avoid this condition when '-' inputted before negative number\n value = max_degradation\n $('#proposed_degradation_rate_text').val(max_degradation.toFixed(2))\n document.getElementById('proposed_degradation_rate_text').setAttribute('data-original-title', 'Choose a shorter service life to enable a larger degradation rate.');\n\n $('#proposed_degradation_rate_text').tooltip('enable')\n $('#proposed_degradation_rate_text').tooltip('show')\n setTimeout(function(){\n $('#proposed_degradation_rate_text').tooltip('hide');\n }, 3000);\n } else {\n $('#proposed_degradation_rate_text').tooltip('disable')\n }\n }\n if (slider_name == 'baseline_service_life') {\n var degradation_rate = parseFloat($('#'+key+'_degradation_rate_text').val())/100.0\n var max_year = 1 / degradation_rate + 0.5\n if (!isNaN(value) && !(value < max_year.toFixed(0))) { //!isNaN to avoid this condition when '-' inputted before negative number\n value = max_year.toFixed(0) // round to integer\n\n $('#baseline_service_life_text').val(max_year.toFixed(0))\n document.getElementById('baseline_service_life_text').setAttribute('data-original-title', 'Choose a smaller degradation rate to enable a longer service life.');\n\n $('#baseline_service_life_text').tooltip('enable')\n $('#baseline_service_life_text').tooltip('show')\n\n setTimeout(function(){\n $('#baseline_service_life_text').tooltip('hide');\n }, 3000);\n } else {\n $('#baseline_service_life_text').tooltip('disable')\n }\n } \n if (slider_name == 'proposed_service_life') {\n var degradation_rate = parseFloat($('#'+key+'_degradation_rate_text').val())/100.0\n var max_year = 1 / degradation_rate + 0.5\n if (!isNaN(value) && !(value < max_year.toFixed(0))) {\n value = max_year.toFixed(0)\n\n $('#proposed_service_life_text').val(max_year.toFixed(0))\n document.getElementById('proposed_service_life_text').setAttribute('data-original-title', 'Choose a smaller degradation rate to enable a longer service life.');\n\n $('#proposed_service_life_text').tooltip('enable')\n $('#proposed_service_life_text').tooltip('show')\n\n setTimeout(function(){\n $('#proposed_service_life_text').tooltip('hide');\n }, 3000);\n } else {\n $('#proposed_service_life_text').tooltip('disable')\n }\n } \n\n var degradation_rate = parseFloat($('#'+key+'_degradation_rate_text').val())/100.0\n var year = parseFloat($('#'+key+'_service_life_text').val())\n var max_year = 1 / degradation_rate + 0.5\n \n if (max_year > SERVICE_LIFE_SLIDER_MAX) {\n max_year = SERVICE_LIFE_SLIDER_MAX\n } \n var max_degradation = 1 / (year - 0.5) * 100\n if (max_degradation > DEGRADATION_MAX) {\n max_degradation = DEGRADATION_MAX\n } \n\n // when the degradation or service life slider moves, update the maximum of the other slider\n if (slider_name == 'baseline_degradation_rate') {\n if (degradation_rate > 0) {\n document.getElementById('baseline_service_life').noUiSlider.updateOptions({\n padding: [0, SERVICE_LIFE_SLIDER_MAX-parseInt(max_year)]\n });\n }\n }\n if (slider_name == 'proposed_degradation_rate') {\n if (degradation_rate > 0) {\n document.getElementById('proposed_service_life').noUiSlider.updateOptions({\n padding: [0, SERVICE_LIFE_SLIDER_MAX-parseInt(max_year)]\n });\n }\n }\n if (slider_name == 'baseline_service_life') {\n document.getElementById('baseline_degradation_rate').noUiSlider.updateOptions({\n padding: [0, Math.round((DEGRADATION_MAX - max_degradation)*100)/100 ]\n });\n }\n if (slider_name == 'proposed_service_life') {\n document.getElementById('proposed_degradation_rate').noUiSlider.updateOptions({\n padding: [0, Math.round((DEGRADATION_MAX - max_degradation)*100)/100 ] \n });\n } \n\n // efficiency bounded by 0% and 100%\n if (slider_name == 'baseline_efficiency') {\n if (value < 0 || isNaN(value)) $('#baseline_efficiency_text').val(0)\n if (value > EFFICIENCY_MAX) $('#baseline_efficiency_text').val(EFFICIENCY_MAX)\n if (!breakeven_active) $('#baseline_efficiency_text').tooltip('disable') \n }\n if (slider_name == 'proposed_efficiency') {\n if (value < 0 || isNaN(value)) $('#proposed_efficiency_text').val(0)\n if (value > EFFICIENCY_MAX) $('#proposed_efficiency_text').val(EFFICIENCY_MAX)\n if (!breakeven_active) $('#proposed_efficiency_text').tooltip('disable') \n }\n\n // degradation rate lower bounded by zero\n if (slider_name == 'baseline_degradation_rate' && (value < 0 || isNaN(value))) {\n $('#baseline_degradation_rate_text').val(0)\n if (!breakeven_active) $('#baseline_degradation_rate_text').tooltip('disable') \n }\n if (slider_name == 'proposed_degradation_rate' && (value < 0 || isNaN(value))) {\n if (!breakeven_active) $('#proposed_degradation_rate_text').tooltip('disable') \n }\n\n // energy yield lower bounded by zero\n if (slider_name == 'baseline_energy_yield' && (value < 0 || isNaN(value))) {\n $('#baseline_energy_yield_text').val(0)\n if (!breakeven_active) $('#baseline_energy_yield_text').tooltip('disable') \n }\n if (slider_name == 'proposed_energy_yield' && (value < 0 || isNaN(value))) {\n $('#proposed_energy_yield_text').val(0)\n if (!breakeven_active) $('#proposed_energy_yield_text').tooltip('disable') \n }\n\n // displays warning if non-positive integer service life\n if ((slider_name == 'baseline_service_life' && (!Number.isInteger(value))) || (slider_name == 'baseline_service_life' && value >= SERVICE_LIFE_CAP) || (slider_name == 'baseline_service_life' && value < 1)) {\n\n if (value > SERVICE_LIFE_CAP) { // set service life maximum at 1000 (calculator freezes if service life is too large)\n $('#baseline_service_life_text').val(SERVICE_LIFE_CAP)\n }\n\n if (value < 1) { // restrict to positive numbers\n $('#baseline_service_life_text').val(1)\n }\n\n if (!breakeven_active) { // only display for non-break-even interaction\n\n document.getElementById('baseline_service_life_text').setAttribute('data-original-title', 'Service life must be a positive integer no greater than 1000.');\n \n $('#baseline_service_life_text').tooltip('enable')\n $('#baseline_service_life_text').tooltip('show')\n }\n } else {\n $('#baseline_service_life_text').tooltip('disable')\n }\n\n if ((slider_name == 'proposed_service_life' && (!Number.isInteger(value))) || (slider_name == 'proposed_service_life' && value >= SERVICE_LIFE_CAP) || (slider_name == 'proposed_service_life' && value < 1)) {\n\n if (value > SERVICE_LIFE_CAP) { // set service life maximum at 1000 (calculator freezes if service life is too large)\n $('#proposed_service_life_text').val(SERVICE_LIFE_CAP)\n }\n\n if (value < 1) { // restrict to positive numbers\n $('#proposed_service_life_text').val(1)\n }\n\n if (!breakeven_active) {\n document.getElementById('proposed_service_life_text').setAttribute('data-original-title', 'Service life must be a positive integer no greater than 1000.');\n \n $('#proposed_service_life_text').tooltip('enable')\n $('#proposed_service_life_text').tooltip('show')\n }\n } else {\n $('#proposed_service_life_text').tooltip('disable')\n } \n\n // The conditionals allow the user to put in an out-of-bounds number\n if (value >= max) {\n slider.noUiSlider.set(max);\n } else if (value <= min) {\n slider.noUiSlider.set(min);\n } else {\n slider.noUiSlider.set(value);\n }\n}", "function SliderListener() {\n document.getElementById('slider-start').addEventListener('input', function(e) {\n //code to be executed when event listener is triggerd\n var SliderValue = \"\" + parseInt(e.target.value, 10) + \"\" //create vare with range slider value\n filterBy(SliderValue); //trigger Fiter function adn send varibale with it.\n });\n}" ]
[ "0.7218121", "0.7218121", "0.6938819", "0.6700834", "0.6666914", "0.6539147", "0.6391279", "0.6296303", "0.6296303", "0.62397665", "0.62397665", "0.6190092", "0.6147399", "0.61416197", "0.6138224", "0.6138224", "0.61041045", "0.6077673", "0.6045355", "0.6036651", "0.6036568", "0.5994406", "0.5985339", "0.5982207", "0.5979011", "0.5956669", "0.59372115", "0.59222436", "0.59149617", "0.58975744" ]
0.8401178
0
currencySliderStop when the slider stops, blur the input to get the proper formatting
function currencySliderStop() { $('#tag-currency-input').blur(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function percentSliderStop() {\n\n\t\t$('#tag-percent-input').blur();\n\t}", "registerConvert() {\n\t\tlet fields = this.container.find('.js-currencyc_value');\n\t\tfields.on('keyup focusout', (e) => {\n\t\t\tlet value = App.Fields.Double.formatToDb(e.currentTarget.value);\n\t\t\tlet currentCurrencyData = $(e.currentTarget).parent().find('.js-currencyc_list option:selected').data();\n\t\t\tfields.each((_n, ve) => {\n\t\t\t\tlet currencyData = $(ve).parent().find('.js-currencyc_list option:selected').data();\n\t\t\t\tif (currentCurrencyData.currencyId === currencyData.currencyId) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t$(ve).val(\n\t\t\t\t\tApp.Fields.Double.formatToDisplay((value * currencyData.conversionRate) / currentCurrencyData.conversionRate),\n\t\t\t\t\tfalse\n\t\t\t\t);\n\t\t\t});\n\t\t});\n\t}", "onSliderBlur() {\n gShaderToy.mMouseIsDown = false;\n }", "onSliderBlur() {\n gShaderToy.mMouseIsDown = false;\n }", "_inputBlurHandler() {\n const that = this;\n\n if (that._suppressBlurEvent === true) {\n // suppresses validation because it was already handled in \"_incrementOrDecrement\" function\n that._suppressBlurEvent = false;\n\n if (that._formattedValue) {\n that._cachedInputValue = that._formattedValue;\n that.$.input.value = that._formattedValue;\n delete that._formattedValue;\n }\n }\n else if (that.$.input.value !== that._editableValue) {\n that._triggerChangeEvent = true;\n that._validate();\n that._triggerChangeEvent = false;\n }\n else {\n that.$.input.value = that._cachedInputValue;\n }\n\n if (that.radixDisplay) {\n that.$.radixDisplayButton.removeAttribute('focus');\n }\n\n if (that.opened) {\n that._closeRadix();\n }\n\n if (that.spinButtons) {\n that.$.spinButtonsContainer.removeAttribute('focus');\n }\n if (that.showUnit) {\n that.$.unitDisplay.removeAttribute('focus');\n }\n\n that.removeAttribute('focus');\n }", "_blur(event) {\n // Depending on support for input[type=range],\n // the event.target could be either the handle or its child input.\n // Use closest() to locate the actual handle.\n event.target.closest(`.${CLASSNAME_HANDLE}`).classList.remove('is-focused');\n\n events.off('touchstart.Slider');\n events.off('mousedown.Slider');\n }", "function inputHandler() {\n stopAnimation();\n setTime(parseInt(slider.value));\n }", "function bind() {\n $('.rate').blur(update_price);\n $('.qty').blur(update_price);\n }", "function currenciesListFocusOut(event) {\n const inputValue = event.target.value;\n if(isNaN(inputValue) || Number(inputValue)===0) event.target.value=\"\";\n else event.target.value = Number(inputValue).toFixed(7);\n}", "function onSliderChange() {\n var zero = ($(\"#slider\").val() == 0);\n $(\"#not-paying\").toggle(zero);\n $(\"#payment-types\").toggle(!zero);\n $(\"#gift\").toggle(!zero);\n\n updateAmountFromSlider();\n }", "function changeCurrency(e) {\n console.log(\"value \", e.value);\n\n setCurCurrency(e.value);\n }", "function updateSlider(slider, number, type){\n slider.addEventListener( \"input\", ()=>{\n number.value = slider.value;\n });\n number.addEventListener(\"input\", ()=>{\n numberRegex(type);\n slider.value = number.value;\n });\n number.addEventListener(\"keydown\", (e)=>{\n if(!(e.key==\"0\"||e.key==\"1\"||e.key==\"2\"||e.key==\"3\"||e.key==\"4\"||e.key==\"5\"||e.key==\"6\"||e.key==\"7\"||e.key==\"8\"||e.key==\"9\"||e.key==\"Backspace\")){\n e.preventDefault();\n }\n else{\n if(e.key==\"Backspace\"&&/^[1-9]{1}$/.test(number.value)){\n e.preventDefault();\n }\n }\n })\n const numberRegex = (type)=>{\n let regex = type==2?/^[1-9]{1}[0-9]{0,2}/:/^[1-9]{1}[0-9]{0,4}/;\n // caps the number to be between 1 and 10000)\n console.log(number.value);\n if(parseInt(number.value)>10000){\n number.value = 10000;\n }\n else if(parseInt(number.value)<1){\n number.value = 1;\n }\n number.value = number.value?((regex.test(number.value))?(number.value.match(regex)[0]):1):1;\n number.value.toString();\n }\n}", "sliderOnChange() {\n updateShaderToyTime(this.sliderInput.value);\n }", "sliderOnChange() {\n updateShaderToyTime(this.sliderInput.value);\n }", "onSliderChange_() {\n this.setEditorValue_(this.sliderInput_.value);\n }", "function startSliderWatch() {\n\t\t$(\".donate-range\").change(function(){\n\t\t\tvar $thisVal = $(this).val();\n\t\t\tupdateSliderValue($thisVal);\n\t\t\tupdateSliderMessage($thisVal);\n\t\t\t$('.donate-slider-amount').removeClass('blank').html('$'+$thisVal);\n\t\t});\n\n\t\tsetTimeout(function(){ updateSliderValue($(\".donate-range\").val()); },50);\n\t}", "function handleBudgetUpdate(values) {\n const slider = $(this);\n const sliderLabels = slider.siblings(\".slider-label\");\n const budgetLabels = slider.siblings(\".slider-values\");\n budgetLabels.removeClass(\"hidden\");\n budgetLabels.find(\".min-value\").html(values[0]);\n budgetLabels.find(\".max-value\").html(values[1]);\n sliderLabels.find(\".label-min\").html(values[0]);\n sliderLabels.find(\".label-max\").html(values[1]);\n let min;\n let max;\n let inputValue;\n if (String(slider.data(\"min\")) !== values[0].replace(\"€\", \"\")) {\n min = values[0].replace(\"€\", \"\");\n }\n if (String(slider.data(\"max\")) !== values[1].replace(\"€\", \"\")) {\n max = values[1].replace(\"€\", \"\");\n }\n if (min) {\n inputValue = min;\n if (max) {\n inputValue += \",\" + max;\n }\n } else if (max) {\n inputValue = \"0,\" + max;\n }\n const input = slider.siblings(\".price-input\");\n if (inputValue) {\n input.attr(\"disabled\", false);\n input.val(inputValue);\n } else {\n input.attr(\"disabled\", true);\n }\n\n}", "function onSliderInput() {\n\tvar sibling = $(this).siblings('input').first();\n\tvar me = $(this);\n\tvar my_rel = me.data('slider-rel');\n\n\tvar my_val = Number(me.val());\n\tvar sib_val = Number(sibling.val());\n\tvar step = Number(me.attr('step'));\n\n\tif (my_rel == 'max' &&\n\t my_val < sib_val) {\n\t // My value is too low. Freeze at one step higher.\n\t me.val(Math.min(sib_val + step, 1440));\n\t} else if (my_rel == 'min' &&\n\t\t my_val > sib_val) {\n\t // My value is too high. Freeze at one step lower.\n\t me.val(Math.max(sib_val - step, 0));\n\t}\n\n\tvar target = $(this).data('display');\n\t$(target).text(util.minuteToTime($(this).val()));\n\n\tif (triggerCb) {\n\t if (my_rel == 'max') triggerCb(sib_val, my_val);\n\t else triggerCb(my_val, sib_val);\n\t}\n }", "_inputFocusHandler() {\n const that = this;\n\n if (that.spinButtons) {\n that.$.spinButtonsContainer.setAttribute('focus', '');\n }\n if (that.radixDisplay) {\n that.$.radixDisplayButton.setAttribute('focus', '');\n }\n if (that.showUnit) {\n that.$.unitDisplay.setAttribute('focus', '');\n }\n\n if (that.opened) {\n that._closeRadix();\n }\n\n that.setAttribute('focus', '');\n\n if (that.outputFormatString) {\n that.$.input.value = that._editableValue;\n }\n }", "function sliderValueChange() {\n elemValue = document.getElementById('value');\n var porcessorValue = processorSlider.value;\n var memoryValue = memorySlider.value;\n var storageValue = storageSlider.value;\n //formula to calculate cloud price based on slider value\n finalValue = Number(((((porcessorValue * memoryValue) * 1000) + ((porcessorValue * memoryValue) * storageValue) + ((porcessorValue * memoryValue) * 100)) / 12).toFixed(2));\n if (document.getElementById('cPanel').ej2_instances[0].checked) {\n finalValue = Number((finalValue - 10).toFixed(2));\n }\n if (document.getElementById('discount').ej2_instances[0].checked) {\n finalValue = Number((finalValue - ((finalValue * 25) / 100)).toFixed(2));\n }\n elemValue.innerText = finalValue.toString();\n }", "function handleSlider(valueNum, valueTxt) {\n slider.slider('value', valueNum);\n CALCULATOR.calculate(valueNum);\n setAmountValue();\n $priceTxt.text($sliderMarkers.children().eq(valueTxt).text());\n }", "function updateNum_Slider() {\n outStyle(false);\n let aE = document.activeElement;\n if (aE.hasAttribute(\"mirr\")) {\n let aMirrorE = document.getElementById(aE.getAttribute(\"mirr\"));\n if (!aE.value) {\n aE.value = 0;\n }\n aMirrorE.value = aE.value;\n\n if (aE.id.substr(0, 1) === \"T\") {\n let switchE = aE;\n aE = aMirrorE;\n aMirrorE = switchE;\n }\n if (aE.value === \"0\") {\n aMirrorE.value = \"\"\n }\n colorCode(aE);\n\n let iElements = document.getElementById(\"outer\").querySelectorAll(\"input\");\n for (let i = 0; i < iElements.length; i++) {\n iElements[i].value = iElements[i].value;// Needed for refreshing style after undetected (webkit\\autofill ?) changes\n }\n }\n}", "_calcSliderValueDebounced(mouseVal, valueVar) {\n var val = this._scale.invert(mouseVal), //convert pixel --> value\n stepped = this._calcStepRounded(val), //round it\n inputElem = valueVar === 'value' ? this._inputStart : this._inputEnd; //which input field\n\n //validate that stepped is not greater than the other handle\n if(this.isRange) {\n stepped = (valueVar === 'value' && stepped > this.endValue) ? this.endValue : stepped;\n stepped = (valueVar === 'endValue' && stepped < this.value) ? this.value : stepped;\n }\n\n this.toggleClass('validation-error', false, inputElem);\n this.set(valueVar, stepped);\n }", "function UpdateAmtTextBox() {\n var value = $('#amountSlider').slider('option', 'value');\n\tvalue = formatNumber(value,0,' ','',currencySymbol,'','-','');\n\tdocument.getElementById('Amount').value=value;\n}", "blur() {\r\n this.isFocussed = false;\r\n this.showLimits = true;\r\n }", "handleSlider() {\n this.slider.addEventListener('change', event => {\n this.sliderValue.innerText = event.target.value;\n this.rate = event.target.value * 10;\n });\n }", "updateSlider_() {\n if (!this.sliderInput_) {\n return;\n }\n this.sliderInput_.setAttribute('value', this.getValue());\n }", "labeledInput(value, key) {\n let inputClass = 'input-valid'\n if (Number.isNaN(Number.parseFloat(value))){\n inputClass = 'input-invalid'\n }\n return <div key={key}>\n <ValueSlider\n label={'Income ' + (key + 1)}\n value={value}\n id={key}\n callback={(x) => this.setIncome(key, x)}\n delCallback={()=>this.delIncome(key)}\n className={inputClass}\n />\n </div>\n }", "function blackAndWhiteThresholdSliderOnInput() {\n\tvar slider = document.getElementById(\"BlackAndWhiteThresholdSlider\");\n\tvar num_input = document.getElementById(\"BlackAndWhiteThresholdValue\");\n\t\n\tnum_input.value = slider.value;\n}", "function weightSumValueChange() {\n $('#sliderSummation').on('input', function () {\n $('.sliderSummationValue').text($(this).val() + \"%\");\n }).on('mouseup', function () {\n var value = $(this).val();\n\n //remove selected value on another slider\n $('#sliderWeight').val(0);\n $('.sliderWeightValue').text(\"-\");\n\n //show overlays\n $('#controls-panel-overlay').show();\n $('#best-results-table-overlay').show();\n\n $('.sliderSummationValue').text(value + \"%\");\n $('input[type=radio][name=select]:checked').prop('checked', false);\n setTimeout(function(){\n selectButtonsByWeightSummation(value, selectedSolution);\n displayModels();\n displayCurves();\n }, 10);\n });\n}" ]
[ "0.7104866", "0.63198334", "0.63052547", "0.63052547", "0.6225074", "0.61850816", "0.6126309", "0.60301", "0.5933545", "0.57518923", "0.56433153", "0.56074816", "0.56014985", "0.56014985", "0.5597195", "0.55478835", "0.5537766", "0.5528481", "0.5506492", "0.54987305", "0.5498321", "0.5492014", "0.5484344", "0.54821396", "0.5479327", "0.54724294", "0.54715204", "0.54472595", "0.54404235", "0.5432767" ]
0.87058455
0
This class defines a complete generic visitor for a parse tree produced by PythonLikeParser.
function PythonLikeVisitor() { antlr4.tree.ParseTreeVisitor.call(this); return this; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "visitNode(node) { }", "visit(node, context) {\n if (node instanceof AST) {\n node.visit(this, context);\n }\n else {\n node.visit(this);\n }\n }", "visit(node, context) {\n if (node instanceof AST) {\n node.visit(this, context);\n }\n else {\n node.visit(this);\n }\n }", "function walk_tree(ast) {\n var walker = {\n \"assign\" : function() {\n var assign_expr = new assign_expression();\n assign_expr.type = \"assign_expr\";\n assign_expr.left_expr = walk_tree(ast[2]);\n assign_expr.right_expr = walk_tree(ast[3]);\n assign_expr.name = assign_expr.left_expr.name;\n \n return assign_expr;\n },\n \n \"var\" : function() {\n var assign_expr = new assign_expression();\n assign_expr.type = \"assign_expr\";\n \n assign_expr.left_expr = new type_object();\n assign_expr.left_expr.name = ast[1][0][0];\n assign_expr.right_expr = walk_tree(ast[1][0][1]);\n assign_expr.name = assign_expr.left_expr.name;\n \n return assign_expr; \n },\n \n \"stat\" : function() {\n return walk_tree(ast[1]);\n },\n \n \"dot\" : function() {\n var dot_obj = walk_tree(ast[1]);\n dot_obj.child = new type_object();\n dot_obj.child.name = ast[2];\n dot_obj.child.parent = dot_obj;\n return dot_obj;\n },\n \n \"name\" : function() {\n var new_obj = new type_object();\n new_obj.type = \"name\";\n new_obj.name = ast[1];\n return new_obj;\n },\n \n \"new\" : function() {\n var expr = walk_tree(ast[1]);\n expr.type = \"composition\";\n return expr;\n },\n \n \"function\" : function() {\n var func = new type_function(\"function\", ast[1], [\"toplevel\", [ast]], ast[2]);\n return func;\n },\n \n \"defun\" : function() { \n var func = new type_function(\"defun\", ast[1], [\"toplevel\", [ast]], ast[2]);\n return func;\n },\n \n \"return\" : function() {\n var return_expr = new type_expression();\n return_expr.type = \"return_expr\";\n return_expr.expr = walk_tree(ast[1]);\n return return_expr;\n },\n \n \"string\" : function() {\n var obj = new type_object();\n obj.type = \"string\";\n obj.value = ast[1];\n return obj;\n },\n \n \"num\" : function() {\n var obj = new type_object();\n obj.type = \"num\";\n obj.value = ast[1];\n return obj;\n },\n \n \"binary\" : function() {\n var binary_expr = new binary_expression();\n binary_expr.type = \"binary_expr\";\n binary_expr.binary_lhs = walk_tree(ast[2]);\n binary_expr.binary_rhs = walk_tree(ast[3]);\n },\n }\n \n var parent = ast[0];\n \n var func = walker[parent];\n \n return func(ast);\n}", "function Visitor() {}", "function Visitor() {}", "function Visitor() {}", "getTreeInternal() {\n const op = this;\n return new class extends Tree {\n /**\n * @param {!Visitor<P, R>} visitor\n * @param {P} arg\n * @return {R}\n * @template P, R\n */\n visit(visitor, arg) {\n const handler = op[visitor.symbol];\n if (handler) {\n return handler.call(\n op, args.map(a => visitor.wrap(a, arg)), arg);\n }\n return visitor.default(args, arg);\n }\n };\n }", "function Visitor(doc) {\n\tthis.stack = [];\n\tthis.parent = doc; //always a list item\n\tthis.node = doc.head();\n\tthis.index = 0;\n\tthis.point = 1;\n\tthis.retained = 0;\n\tthis.ops = []; //to get to the doc\n}", "function FPythonListener() {\n\tantlr4.tree.ParseTreeListener.call(this);\n\treturn this;\n}", "function visit(node) {\n // Only consider exported nodes\n if (!isNodeExported(node))\n return;\n if (node.kind === ts.SyntaxKind.EnumDeclaration) {\n var enNode = node;\n var symbol = checker.getSymbolAtLocation(enNode.name);\n if (!!symbol && generateDts) {\n visitEnumNode(enNode, symbol);\n }\n }\n else if (node.kind === ts.SyntaxKind.FunctionDeclaration) {\n var fnNode = node;\n var symbol = checker.getSymbolAtLocation(fnNode.name);\n if (!!symbol && generateDts) {\n visitFunctionNode(fnNode, symbol);\n }\n }\n else if (node.kind === ts.SyntaxKind.VariableStatement) {\n var vsNode = node;\n if (vsNode.declarationList.declarations.length > 0) {\n var varNode = vsNode.declarationList.declarations[0];\n var symbol = checker.getSymbolAtLocation(varNode.name);\n if (!!symbol && (generateDts || isSymbolHasComments(symbol))) {\n visitVariableNode(varNode, symbol);\n }\n }\n }\n else if (node.kind === ts.SyntaxKind.ClassDeclaration) {\n // This is a top level class, get its symbol\n var symbol = checker.getSymbolAtLocation(node.name);\n if (!symbol)\n return;\n if (generateDts || isSymbolHasComments(symbol)) {\n visitDocumentedNode(node, symbol);\n }\n }\n else if (node.kind === ts.SyntaxKind.InterfaceDeclaration) {\n // This is a top level class, get its symbol\n var name_1 = node.name;\n var symbol = checker.getSymbolAtLocation(name_1);\n if (generateDts || isSymbolHasComments(symbol) || isOptionsInterface(name_1.text)) {\n visitDocumentedNode(node, symbol);\n }\n }\n else if (node.kind === ts.SyntaxKind.ModuleDeclaration) {\n // This is a namespace, visit its children\n ts.forEachChild(node, visit);\n }\n else if (node.kind === ts.SyntaxKind.ExportDeclaration) {\n visitExportDeclarationNode(node);\n }\n }", "visit(){\n\t\tif(!this.parent || this.parent.content)\n\t\t\treturn this.convert(...arguments)\n\t}", "function KELParserVisitor() {\n\tantlr4.tree.ParseTreeVisitor.call(this);\n\treturn this;\n}", "function PEGtoAST(node) {\n switch (type(node)) {\n case \"null\":\n return undefined;\n case \"string\":\n return new StringNode(node);\n case \"array\":\n return new ASTNodeList(...node.map(PEGtoAST));\n case \"object\":\n switch (node.TYPE) {\n case \"whitespace\":\n return new Whitespace();\n case \"parbreak\":\n return new Parbreak();\n case \"subscript\":\n return new Subscript(PEGtoAST(node.content));\n case \"superscript\":\n return new Superscript(PEGtoAST(node.content));\n case \"inlinemath\":\n return new InlineMath(PEGtoAST(node.content));\n case \"displaymath\":\n return new DisplayMath(PEGtoAST(node.content));\n case \"mathenv\":\n return new MathEnv(node.env, PEGtoAST(node.content));\n case \"group\":\n return new Group(PEGtoAST(node.content));\n case \"macro\":\n return new Macro(node.content, PEGtoAST(node.args));\n case \"environment\":\n return new Environment(\n PEGtoAST(node.env),\n PEGtoAST(node.args),\n PEGtoAST(node.content)\n );\n case \"verbatim\":\n return new Verbatim(PEGtoAST(node.content));\n case \"verb\":\n return new Verb(node[\"escape\"], PEGtoAST(node.content));\n case \"commentenv\":\n return new CommentEnv(PEGtoAST([node.content]));\n case \"comment\":\n return new CommentNode(\n node.sameline,\n PEGtoAST(node.content)\n );\n case \"arglist\":\n return new ArgList(PEGtoAST(node.content));\n }\n }\n}", "function CodiVisitor() {\r\n\tantlr4.tree.ParseTreeVisitor.call(this);\r\n\treturn this;\r\n}", "function PlaygroundVisitor() {\n\tantlr4.tree.ParseTreeVisitor.call(this);\n\treturn this;\n}", "compileNode(o) {\r\n\t\t\t\t\tvar answer, compiledName, isValue, name, properties, prototype, ref1, ref2, ref3, ref4, val;\r\n\t\t\t\t\tisValue = this.variable instanceof Value;\r\n\t\t\t\t\tif (isValue) {\r\n\t\t\t\t\t\t// If `@variable` is an array or an object, we’re destructuring;\r\n\t\t\t\t\t\t// if it’s also `isAssignable()`, the destructuring syntax is supported\r\n\t\t\t\t\t\t// in ES and we can output it as is; otherwise we `@compileDestructuring`\r\n\t\t\t\t\t\t// and convert this ES-unsupported destructuring into acceptable output.\r\n\t\t\t\t\t\tif (this.variable.isArray() || this.variable.isObject()) {\r\n\t\t\t\t\t\t\tif (!this.variable.isAssignable()) {\r\n\t\t\t\t\t\t\t\tif (this.variable.isObject() && this.variable.base.hasSplat()) {\r\n\t\t\t\t\t\t\t\t\treturn this.compileObjectDestruct(o);\r\n\t\t\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\t\t\treturn this.compileDestructuring(o);\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\tif (this.variable.isSplice()) {\r\n\t\t\t\t\t\t\treturn this.compileSplice(o);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif (this.isConditional()) {\r\n\t\t\t\t\t\t\treturn this.compileConditional(o);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif ((ref1 = this.context) === '//=' || ref1 === '%%=') {\r\n\t\t\t\t\t\t\treturn this.compileSpecialMath(o);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tthis.addScopeVariables(o);\r\n\t\t\t\t\tif (this.value instanceof Code) {\r\n\t\t\t\t\t\tif (this.value.isStatic) {\r\n\t\t\t\t\t\t\tthis.value.name = this.variable.properties[0];\r\n\t\t\t\t\t\t} else if (((ref2 = this.variable.properties) != null ? ref2.length : void 0) >= 2) {\r\n\t\t\t\t\t\t\tref3 = this.variable.properties, [...properties] = ref3, [prototype, name] = splice.call(properties, -2);\r\n\t\t\t\t\t\t\tif (((ref4 = prototype.name) != null ? ref4.value : void 0) === 'prototype') {\r\n\t\t\t\t\t\t\t\tthis.value.name = name;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tval = this.value.compileToFragments(o, LEVEL_LIST);\r\n\t\t\t\t\tcompiledName = this.variable.compileToFragments(o, LEVEL_LIST);\r\n\t\t\t\t\tif (this.context === 'object') {\r\n\t\t\t\t\t\tif (this.variable.shouldCache()) {\r\n\t\t\t\t\t\t\tcompiledName.unshift(this.makeCode('['));\r\n\t\t\t\t\t\t\tcompiledName.push(this.makeCode(']'));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\treturn compiledName.concat(this.makeCode(': '), val);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tanswer = compiledName.concat(this.makeCode(` ${this.context || '='} `), val);\r\n\t\t\t\t\t// Per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Assignment_without_declaration,\r\n\t\t\t\t\t// if we’re destructuring without declaring, the destructuring assignment must be wrapped in parentheses.\r\n\t\t\t\t\t// The assignment is wrapped in parentheses if 'o.level' has lower precedence than LEVEL_LIST (3)\r\n\t\t\t\t\t// (i.e. LEVEL_COND (4), LEVEL_OP (5) or LEVEL_ACCESS (6)), or if we're destructuring object, e.g. {a,b} = obj.\r\n\t\t\t\t\tif (o.level > LEVEL_LIST || isValue && this.variable.base instanceof Obj && !this.nestedLhs && !(this.param === true)) {\r\n\t\t\t\t\t\treturn this.wrapInParentheses(answer);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\treturn answer;\r\n\t\t\t\t\t}\r\n\t\t\t\t}", "function statVisitor() {\n\tantlr4.tree.ParseTreeVisitor.call(this);\n\treturn this;\n}", "function Parser() {\n var nodeFactory = arguments.length <= 0 || arguments[0] === undefined ? new _nodeFactory.NodeFactory() : arguments[0];\n\n _classCallCheck(this, Parser);\n\n this.nodeFactory = nodeFactory;\n }", "function traverser(ast, visitor) {\n\n function traverseArray(array, parent) {\n array.forEach(child => {\n traverseNode(child, parent);\n });\n }\n\n function traverseNode(node, parent) {\n let methods = visitor[node.type];\n if (methods && methods.enter) {\n methods.enter(node, parent);\n }\n\n switch (node.type) {\n case 'Document':\n traverseArray(node.body, node);\n break;\n case 'DOMELEMENT':\n traverseArray(node.params, node);\n break;\n case \"CARGO\":\n break;\n }\n if (methods && methods.exit) {\n methods.exit(node, parent);\n }\n }\n traverseNode(ast, null);\n}", "function rcVisitor() {\n\tantlr4.tree.ParseTreeVisitor.call(this);\n\treturn this;\n}", "function NodeVisitor() {\n _classCallCheck(this, NodeVisitor);\n\n this[path] = [];\n }", "function ast_walker() {\n\tfunction _vardefs( defs ) {\n\t\treturn [ this[0], MAP( defs, function ( def ) {\n\t\t\tvar a = [ def[0] ];\n\t\t\tif ( def.length > 1 ) {\n\t\t\t\ta[1] = walk( def[1] );\n\t\t\t}\n\t\t\treturn a;\n\t\t} ) ];\n\t}\n\n\t;\n\tfunction _block( statements ) {\n\t\tvar out = [ this[0] ];\n\t\tif ( statements != null ) {\n\t\t\tout.push( MAP( statements, walk ) );\n\t\t}\n\t\treturn out;\n\t}\n\n\t;\n\tvar walkers = {\n\t\t\"string\" : function ( str ) {\n\t\t\treturn [ this[0], str ];\n\t\t},\n\t\t\"num\" : function ( num ) {\n\t\t\treturn [ this[0], num ];\n\t\t},\n\t\t\"name\" : function ( name ) {\n\t\t\treturn [ this[0], name ];\n\t\t},\n\t\t\"toplevel\" : function ( statements ) {\n\t\t\treturn [ this[0], MAP( statements, walk ) ];\n\t\t},\n\t\t\"block\" : _block,\n\t\t\"splice\" : _block,\n\t\t\"var\" : _vardefs,\n\t\t\"const\" : _vardefs,\n\t\t\"try\" : function ( t, c, f ) {\n\t\t\treturn [\n\t\t\t\tthis[0],\n\t\t\t\tMAP( t, walk ),\n\t\t\t\tc != null ? [ c[0], MAP( c[1], walk ) ] : null,\n\t\t\t\tf != null ? MAP( f, walk ) : null\n\t\t\t];\n\t\t},\n\t\t\"throw\" : function ( expr ) {\n\t\t\treturn [ this[0], walk( expr ) ];\n\t\t},\n\t\t\"new\" : function ( ctor, args ) {\n\t\t\treturn [ this[0], walk( ctor ), MAP( args, walk ) ];\n\t\t},\n\t\t\"switch\" : function ( expr, body ) {\n\t\t\treturn [ this[0], walk( expr ), MAP( body, function ( branch ) {\n\t\t\t\treturn [ branch[0] ? walk( branch[0] ) : null,\n\t\t\t\t MAP( branch[1], walk ) ];\n\t\t\t} ) ];\n\t\t},\n\t\t\"break\" : function ( label ) {\n\t\t\treturn [ this[0], label ];\n\t\t},\n\t\t\"continue\" : function ( label ) {\n\t\t\treturn [ this[0], label ];\n\t\t},\n\t\t\"conditional\" : function ( cond, t, e ) {\n\t\t\treturn [ this[0], walk( cond ), walk( t ), walk( e ) ];\n\t\t},\n\t\t\"assign\" : function ( op, lvalue, rvalue ) {\n\t\t\treturn [ this[0], op, walk( lvalue ), walk( rvalue ) ];\n\t\t},\n\t\t\"dot\" : function ( expr ) {\n\t\t\treturn [ this[0], walk( expr ) ].concat( slice( arguments, 1 ) );\n\t\t},\n\t\t\"call\" : function ( expr, args ) {\n\t\t\treturn [ this[0], walk( expr ), MAP( args, walk ) ];\n\t\t},\n\t\t\"function\" : function ( name, args, body ) {\n\t\t\treturn [ this[0], name, args.slice(), MAP( body, walk ) ];\n\t\t},\n\t\t\"debugger\" : function () {\n\t\t\treturn [ this[0] ];\n\t\t},\n\t\t\"defun\" : function ( name, args, body ) {\n\t\t\treturn [ this[0], name, args.slice(), MAP( body, walk ) ];\n\t\t},\n\t\t\"if\" : function ( conditional, t, e ) {\n\t\t\treturn [ this[0], walk( conditional ), walk( t ), walk( e ) ];\n\t\t},\n\t\t\"for\" : function ( init, cond, step, block ) {\n\t\t\treturn [ this[0], walk( init ), walk( cond ), walk( step ), walk( block ) ];\n\t\t},\n\t\t\"for-in\" : function ( vvar, key, hash, block ) {\n\t\t\treturn [ this[0], walk( vvar ), walk( key ), walk( hash ), walk( block ) ];\n\t\t},\n\t\t\"while\" : function ( cond, block ) {\n\t\t\treturn [ this[0], walk( cond ), walk( block ) ];\n\t\t},\n\t\t\"do\" : function ( cond, block ) {\n\t\t\treturn [ this[0], walk( cond ), walk( block ) ];\n\t\t},\n\t\t\"return\" : function ( expr ) {\n\t\t\treturn [ this[0], walk( expr ) ];\n\t\t},\n\t\t\"binary\" : function ( op, left, right ) {\n\t\t\treturn [ this[0], op, walk( left ), walk( right ) ];\n\t\t},\n\t\t\"unary-prefix\" : function ( op, expr ) {\n\t\t\treturn [ this[0], op, walk( expr ) ];\n\t\t},\n\t\t\"unary-postfix\" : function ( op, expr ) {\n\t\t\treturn [ this[0], op, walk( expr ) ];\n\t\t},\n\t\t\"sub\" : function ( expr, subscript ) {\n\t\t\treturn [ this[0], walk( expr ), walk( subscript ) ];\n\t\t},\n\t\t\"object\" : function ( props ) {\n\t\t\treturn [ this[0], MAP( props, function ( p ) {\n\t\t\t\treturn p.length == 2\n\t\t\t\t\t? [ p[0], walk( p[1] ) ]\n\t\t\t\t\t: [ p[0], walk( p[1] ), p[2] ]; // get/set-ter\n\t\t\t} ) ];\n\t\t},\n\t\t\"regexp\" : function ( rx, mods ) {\n\t\t\treturn [ this[0], rx, mods ];\n\t\t},\n\t\t\"array\" : function ( elements ) {\n\t\t\treturn [ this[0], MAP( elements, walk ) ];\n\t\t},\n\t\t\"stat\" : function ( stat ) {\n\t\t\treturn [ this[0], walk( stat ) ];\n\t\t},\n\t\t\"seq\" : function () {\n\t\t\treturn [ this[0] ].concat( MAP( slice( arguments ), walk ) );\n\t\t},\n\t\t\"label\" : function ( name, block ) {\n\t\t\treturn [ this[0], name, walk( block ) ];\n\t\t},\n\t\t\"with\" : function ( expr, block ) {\n\t\t\treturn [ this[0], walk( expr ), walk( block ) ];\n\t\t},\n\t\t\"atom\" : function ( name ) {\n\t\t\treturn [ this[0], name ];\n\t\t}\n\t};\n\n\tvar user = {};\n\tvar stack = [];\n\n\tfunction walk( ast ) {\n\t\tif ( ast == null ) {\n\t\t\treturn null;\n\t\t}\n\t\ttry {\n\t\t\tstack.push( ast );\n\t\t\tvar type = ast[0];\n\t\t\tvar gen = user[type];\n\t\t\tif ( gen ) {\n\t\t\t\tvar ret = gen.apply( ast, ast.slice( 1 ) );\n\t\t\t\tif ( ret != null ) {\n\t\t\t\t\treturn ret;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgen = walkers[type];\n\t\t\treturn gen.apply( ast, ast.slice( 1 ) );\n\t\t} finally {\n\t\t\tstack.pop();\n\t\t}\n\t}\n\n\t;\n\n\tfunction dive( ast ) {\n\t\tif ( ast == null ) {\n\t\t\treturn null;\n\t\t}\n\t\ttry {\n\t\t\tstack.push( ast );\n\t\t\treturn walkers[ast[0]].apply( ast, ast.slice( 1 ) );\n\t\t} finally {\n\t\t\tstack.pop();\n\t\t}\n\t}\n\n\t;\n\n\tfunction with_walkers( walkers, cont ) {\n\t\tvar save = {}, i;\n\t\tfor ( i in walkers ) {\n\t\t\tif ( HOP( walkers, i ) ) {\n\t\t\t\tsave[i] = user[i];\n\t\t\t\tuser[i] = walkers[i];\n\t\t\t}\n\t\t}\n\t\tvar ret = cont();\n\t\tfor ( i in save ) {\n\t\t\tif ( HOP( save, i ) ) {\n\t\t\t\tif ( !save[i] ) {\n\t\t\t\t\tdelete user[i];\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tuser[i] = save[i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n\n\t;\n\n\treturn {\n\t\twalk : walk,\n\t\tdive : dive,\n\t\twith_walkers : with_walkers,\n\t\tparent : function () {\n\t\t\treturn stack[stack.length - 2]; // last one is current node\n\t\t},\n\t\tstack : function () {\n\t\t\treturn stack;\n\t\t}\n\t};\n}", "function JavapVisitor() {\n\tantlr4.tree.ParseTreeVisitor.call(this);\n\treturn this;\n}", "compileNode(o) {\r\n\t\t\t\t\tvar arg, argCode, argIndex, cache, compiledArgs, fragments, j, len1, ref1, ref2, ref3, ref4, varAccess;\r\n\t\t\t\t\tthis.checkForNewSuper();\r\n\t\t\t\t\tif ((ref1 = this.variable) != null) {\r\n\t\t\t\t\t\tref1.front = this.front;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcompiledArgs = [];\r\n\t\t\t\t\t// If variable is `Accessor` fragments are cached and used later\r\n\t\t\t\t\t// in `Value::compileNode` to ensure correct order of the compilation,\r\n\t\t\t\t\t// and reuse of variables in the scope.\r\n\t\t\t\t\t// Example:\r\n\t\t\t\t\t// `a(x = 5).b(-> x = 6)` should compile in the same order as\r\n\t\t\t\t\t// `a(x = 5); b(-> x = 6)`\r\n\t\t\t\t\t// (see issue #4437, https://github.com/jashkenas/coffeescript/issues/4437)\r\n\t\t\t\t\tvarAccess = ((ref2 = this.variable) != null ? (ref3 = ref2.properties) != null ? ref3[0] : void 0 : void 0) instanceof Access;\r\n\t\t\t\t\targCode = (function() {\r\n\t\t\t\t\t\tvar j, len1, ref4, results1;\r\n\t\t\t\t\t\tref4 = this.args || [];\r\n\t\t\t\t\t\tresults1 = [];\r\n\t\t\t\t\t\tfor (j = 0, len1 = ref4.length; j < len1; j++) {\r\n\t\t\t\t\t\t\targ = ref4[j];\r\n\t\t\t\t\t\t\tif (arg instanceof Code) {\r\n\t\t\t\t\t\t\t\tresults1.push(arg);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\treturn results1;\r\n\t\t\t\t\t}).call(this);\r\n\t\t\t\t\tif (argCode.length > 0 && varAccess && !this.variable.base.cached) {\r\n\t\t\t\t\t\t[cache] = this.variable.base.cache(o, LEVEL_ACCESS, function() {\r\n\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\tthis.variable.base.cached = cache;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tref4 = this.args;\r\n\t\t\t\t\tfor (argIndex = j = 0, len1 = ref4.length; j < len1; argIndex = ++j) {\r\n\t\t\t\t\t\targ = ref4[argIndex];\r\n\t\t\t\t\t\tif (argIndex) {\r\n\t\t\t\t\t\t\tcompiledArgs.push(this.makeCode(\", \"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tcompiledArgs.push(...(arg.compileToFragments(o, LEVEL_LIST)));\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfragments = [];\r\n\t\t\t\t\tif (this.isNew) {\r\n\t\t\t\t\t\tfragments.push(this.makeCode('new '));\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfragments.push(...this.variable.compileToFragments(o, LEVEL_ACCESS));\r\n\t\t\t\t\tfragments.push(this.makeCode('('), ...compiledArgs, this.makeCode(')'));\r\n\t\t\t\t\treturn fragments;\r\n\t\t\t\t}", "function RomeVisitor() {\n\tantlr4.tree.ParseTreeVisitor.call(this);\n\treturn this;\n}", "function TreeParser() {\n var orderOfOperations,\n tokens,\n length,\n index,\n peekAtNextToken,\n parse,\n parseExpression,\n parseAdditive,\n parseMultiplicative,\n parsePrimary,\n isInLevel,\n parseBinary,\n calculate,\n mathOperations;\n\n orderOfOperations = [['+', '-'],['*', '/'], ['^']];\n\n mathOperations = {\n '+' : function(x, y) {\n return x + y;\n },\n\n '-' : function(x, y) {\n return x - y;\n },\n\n '*' : function(x, y) {\n return x * y;\n },\n\n '/' : function(x, y) {\n if (y === 0) {\n throw 'the right operand of a divide operator cannot be zero';\n }\n return x / y;\n },\n\n '^' : function(x, y) {\n return Math.pow(x, y);\n } \n }\n\n tokens = [];\n length = 0;\n index = 0;\n\n peekAtNextToken = function () {\n if (index === length) {\n return null;\n }\n return tokens[index];\n };\n\n /**\n * creates an abstract tree from a tokens array\n * this function does not validate the expression mathematically\n * @param {array} tokensArr an array that contains tokens\n * @return {object} the abstract expression tree root\n */\n parse = function (tokensArr) {\n tokens = tokensArr;\n length = tokens.length;\n if (length === 0) {\n return;\n }\n index = 0;\n\n //we want to parse the expression from left to right to avoid problems like 1-1-1=1\n tokens = tokens.reverse();\n return parseExpression();\n };\n\n /**\n * parses an assignment expression\n * @return {object} the abstract expression tree assignment node\n */\n parseExpression = function () {\n return parseBinary(0);\n };\n\n /**\n * parses an assignment expression\n * @return {object} the abstract expression tree assignment node\n */\n isInLevel = function (operator, order) {\n return orderOfOperations[order].indexOf(operator) > -1;\n };\n\n /**\n * recursivly parses a binary expression by order of operations\n * each recursion level represents the more immidiate operation\n * @param {Number} order the current order of operation\n * @return {object} the abstract expression tree node\n */\n parseBinary = function (order) {\n var right,\n token,\n node;\n\n right = order == orderOfOperations.length - 1\n ? parsePrimary()\n : parseBinary(order + 1);\n \n token = peekAtNextToken();\n if (token === null) {\n return right;\n }\n\n while (isInLevel(token.value, order)) {\n index += 1;\n node = {};\n node = token;\n node.right = right;\n node.left = parseBinary(order);\n right = node;\n \n token = peekAtNextToken();\n if (token === null) {\n return right;\n }\n }\n\n return right;\n };\n\n /**\n * parses a term expression i.e. a finite number, an varialbe or an expression in parens\n * @return {object} the abstract expression tree primary node\n */\n parsePrimary = function () {\n var token,\n node;\n\n if (index === length) {\n throw \"error: there are no more tokens to parse\";\n }\n\n token = tokens[index];\n if (token.type === tokenType.num || token.type === tokenType.id) {\n index += 1;\n node = {};\n node = token;\n return node;\n }\n\n if (token.value === ')') {\n index += 1;\n node = parseExpression();\n\n token = peekAtNextToken();\n if (token.value !== '(') {\n throw \"error: '(' was expected\";\n }\n\n index += 1;\n return node;\n }\n\n throw \"error: token '\" + token.value + \"' was not expected\";\n };\n\n /**\n * calculates the result from mathematical tree\n * @param {object} the ree/sub tree token node\n * @return {Number} the result of the calculation\n */\n calculate = function (node) {\n var left,\n right,\n operator,\n result;\n\n if (node === null) return;\n if (node.type === tokenType.id) {\n throw 'variables are not supported at this point';\n }\n \n if (node.type === tokenType.num) {\n return parseFloat(node.value);\n }\n\n left = node.left.type === tokenType.num\n ? parseFloat(node.left.value)\n : calculate(node.left);\n\n right = node.right.type === tokenType.num\n ? parseFloat(node.right.value)\n : calculate(node.right);\n\n if (node.type !== tokenType.op) {\n throw 'an operator was expected';\n }\n\n result = mathOperations[node.value](left, right);\n return result; \n }\n\n return {\n parse: parse,\n calculate: calculate\n };\n }", "function walkAst(node, parent) {\n\t\t\tif (!node)\n\t\t\t\treturn;\n\t\t\tfor (var key in node) {\n\t\t\t\tif (key === 'range')\n\t\t\t\t\tcontinue;\n\t\t\t\tvar value = node[key];\n\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\tfor (var i = 0, l = value.length; i < l; i++)\n\t\t\t\t\t\twalkAst(value[i], node);\n\t\t\t\t} else if (value && typeof value === 'object') {\n\t\t\t\t\t// We cannot use Base.isPlainObject() for these since\n\t\t\t\t\t// Acorn.js uses its own internal prototypes now.\n\t\t\t\t\twalkAst(value, node);\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch (node && node.type) {\n\t\t\tcase 'BinaryExpression':\n\t\t\t\tif (node.operator in binaryOperators\n\t\t\t\t\t\t&& node.left.type !== 'Literal') {\n\t\t\t\t\tvar left = getCode(node.left),\n\t\t\t\t\t\tright = getCode(node.right);\n\t\t\t\t\treplaceCode(node, '_$_(' + left + ', \"' + node.operator\n\t\t\t\t\t\t\t+ '\", ' + right + ')');\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'AssignmentExpression':\n\t\t\t\tif (/^.=$/.test(node.operator)\n\t\t\t\t\t\t&& node.left.type !== 'Literal') {\n\t\t\t\t\tvar left = getCode(node.left),\n\t\t\t\t\t\tright = getCode(node.right);\n\t\t\t\t\treplaceCode(node, left + ' = _$_(' + left + ', \"'\n\t\t\t\t\t\t\t+ node.operator[0] + '\", ' + right + ')');\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'UpdateExpression':\n\t\t\t\tif (!node.prefix && !(parent && (\n\t\t\t\t\t\t// We need to filter out parents that are comparison\n\t\t\t\t\t\t// operators, e.g. for situations like if (++i < 1),\n\t\t\t\t\t\t// as we can't replace that with if (_$_(i, \"+\", 1) < 1)\n\t\t\t\t\t\t// Match any operator beginning with =, !, < and >.\n\t\t\t\t\t\tparent.type === 'BinaryExpression'\n\t\t\t\t\t\t\t&& /^[=!<>]/.test(parent.operator)\n\t\t\t\t\t\t// array[i++] is a MemberExpression with computed = true\n\t\t\t\t\t\t// We can't replace that with array[_$_(i, \"+\", 1)].\n\t\t\t\t\t\t|| parent.type === 'MemberExpression'\n\t\t\t\t\t\t\t&& parent.computed))) {\n\t\t\t\t\tvar arg = getCode(node.argument);\n\t\t\t\t\treplaceCode(node, arg + ' = _$_(' + arg + ', \"'\n\t\t\t\t\t\t\t+ node.operator[0] + '\", 1)');\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'UnaryExpression':\n\t\t\t\tif (node.operator in unaryOperators\n\t\t\t\t\t\t&& node.argument.type !== 'Literal') {\n\t\t\t\t\tvar arg = getCode(node.argument);\n\t\t\t\t\treplaceCode(node, '$_(\"' + node.operator + '\", '\n\t\t\t\t\t\t\t+ arg + ')');\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "function traverseNodes(node, visitor) {\n traverse(node, null, visitor);\n}", "constructor( type, code_or_tree, embedded=false ){\n super(type)\n if(typeof code_or_tree == \"string\" ){\n var p = new GeneratorParser(false, embedded)\n this.tree = p.get(new Source(\"generator-lexeme\",code_or_tree))\n }else this.tree = code_or_tree\n }" ]
[ "0.65919274", "0.60482764", "0.60482764", "0.5950813", "0.58122927", "0.58122927", "0.58122927", "0.577187", "0.5699212", "0.56250006", "0.56055236", "0.55747366", "0.55630654", "0.5482851", "0.5422624", "0.5421316", "0.5384845", "0.53826153", "0.538102", "0.5351745", "0.5320969", "0.5311846", "0.53096694", "0.53013444", "0.529842", "0.52747416", "0.52065355", "0.51916397", "0.51837194", "0.51699376" ]
0.7582853
0
use for get current file info used by file_on_mouse_down, open_new_dir.
function get_cur_file_info_by_id(id){ file_to_operate_id = id; element_to_operate = document.getElementById(id); switch(cur_dir_path){ case 'root': file_to_operate_name = get_json_by_id(cur_dir_path, file_to_operate_id).type; break; case 'root/Pictures': file_to_operate_name = get_json_by_id(cur_dir_path, file_to_operate_id).filename; break; case 'root/Contacts': file_to_operate_name = get_json_by_id(cur_dir_path, file_to_operate_id).name; break; case 'root/Videos': file_to_operate_name = get_json_by_id(cur_dir_path, file_to_operate_id).name; break; } //element_to_operate.innerHTML; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function get_current_code_path(){\n\tvar id = $(\"#file_name_nav\").find(\"span.selected\").attr(\"id\");\n\tid = id.replace(\"t_\", \"\");\n\treturn full_path($(\"#\"+id));\n}", "get info() {\n return this.project.getFileInfo(this.path)\n }", "function showFileInfo(file){\n console.log(\"name : \" + file.name);\n console.log(\"size : \" + file.size);\n console.log(\"type : \" + file.type);\n console.log(\"date : \" + file.lastModified);\n }", "function getCurrentImage() {\n\t\treturn this.options.folder ?\n\t\t\t\tthis.options.folder + \"/\" + this.options.images[this.current] :\n\t\t\t\tthis.options.images[this.current];\n\t}", "function _getLocateFile() {\n\t\treturn OS.Path.join(_getLocateDirectory(), LOCATE_FILE_NAME);\n\t}", "get() {\n return this.filePointer.get();\n }", "get() {\n return this.filePointer.get();\n }", "function displayFileDetails(file, side){\n side.innerHTML = file.name + \" (\"+ file.size + \" bytes) has been selected. <br/> Last Modified: \" +\n (file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() : 'n/a') + \". <br/><br/> To change files drop another file.\";\n }", "function selectFile(evt) {\n\t\tvar last_file = {};\n\t\tif (context_element && (context_element.type == 2)) {\n\t\t\tlast_file = context_element;\n\t\t}\n\t\tcontext_element = getElProp(evt);\n\t\tif (context_element.type == 1) {\n\t\t\t// If select directory then open the directory\n\t\t\t// if index >= 0 then select subfolde, if index < 0 - then select up folder\n\t\t\tif (context_element.index >= 0) {\n\t\t\t\tgetDirContent(cur_path + context_element.name + '/');\n\t\t\t} else {\n\t\t\t\tvar\n\t\t\t\t\tpath = '',\n\t\t\t\t\ti\n\t\t\t\t;\n\t\t\t\tfor (i = dir_content.path.length + context_element.index; i >= 0; i--) {\n\t\t\t\t\tpath = dir_content.path[i] + '/' + path;\n\t\t\t\t}\n\t\t\t\tgetDirContent('/' + path);\n\t\t\t}\n\t\t} else if (context_element.type == 2) {\n\t\t\t// Іf select the file then highlight and execute the external functions with the file properties\n\t\t\thighlightFileItem(context_element.index);\n\t\t\t// If set the external function - then execute it\n\t\t\tif (on_select || on_dblselect) {\n\t\t\t\tvar file = dir_content.files[context_element.index];\n\t\t\t\t// Generate additional field\n\t\t\t\tfile.path = cur_path + file.name;\n\t\t\t\tfile.wwwPath = getURIEncPath(HTMLDecode(upload_path + cur_path + file.name));\n\t\t\t\t// If thumbnail exist, set the www path to him\n\t\t\t\tif (file.thumb && file.thumb !== '') {\n\t\t\t\t\tfile.wwwThumbPath = getURIEncPath(HTMLDecode(upload_path + file.thumb));\n\t\t\t\t}\n\t\t\t\tif (on_select) {\n\t\t\t\t\ton_select(file);\n\t\t\t\t}\n\t\t\t\t// If double click on file then chose them by on_dblselect() function\n\t\t\t\tif ( on_dblselect &&(last_file.index == context_element.index) && ((context_element.time - last_file.time) < dbclick_delay) ) {\n\t\t\t\t\ton_dblselect(file);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// No selections\n\t\t\t// Clean the highlight\n\t\t\thighlightFileItem();\n\t\t\t// Hide the tooltips\n\t\t\thideTooltips();\n\t\t\t// If set the external function - then execute it\n\t\t\tif (on_deselect) {\n\t\t\t\ton_deselect();\n\t\t\t}\n\t\t}\n\t}", "file () {\n try {\n const file = this.currentFile()\n\n if (!file) throw createError({ code: 'ENOENT', message: 'No file selected' })\n return file\n } catch (e) {\n throw new Error(e)\n }\n }", "function open_dir(dir){\r\n $('body').addClass('loading');\r\n manager.get_dir(dir,function(files){\r\n \r\n global.total_selected=0;\r\n $('#edit').hide();\r\n html='';\r\n for(var i=0;i<files.length;i++){\r\n html+='<div data-file=\"'+files[i].rel_filename+'\" class=\"file '+files[i].type+'\"'+\r\n 'title=\"'+files[i].filename+'\" data-i=\"'+i+'\" data-type=\"'+files[i].type+'\">'+\r\n '<div class=\"icon\"><i class=\"fa fa-'+files[i].icon+'\"></i></div>'+\r\n '<div class=\"name\">'+files[i].filename+'</div>'+\r\n '<div class=\"type\">'+files[i].type+'</div>'+\r\n '<div class=\"filedate\" data-date=\"'+files[i].modified_timestamp+'\">'+files[i].date+'</div>'+\r\n '<div class=\"filesize\" data-size=\"'+files[i].raw_size+'\">'+files[i].filesize+'</div>'+\r\n '</div>';\r\n }\r\n $('.file').remove();\r\n $('#files').html(html);\r\n $('#info').text(files.length+' file(s)');\r\n\r\n //remove selection\r\n $('#files').off('click').on('click',function(event) { \r\n if(!$(event.target).closest('.file').length) {\r\n $('.selected').removeClass('selected');\r\n $('#info').text(files.length+' file(s)');\r\n $('#edit').hide();\r\n } \r\n })\r\n\r\n //select files\r\n $('.file').on('click',function(e){\r\n var index=parseInt($(this).data('i')),\r\n text='';\r\n \r\n if(!e.ctrlKey){\r\n if($(this).hasClass('selected')) return; //kill if already selected\r\n $('.selected').removeClass('selected');\r\n }\r\n if(e.shiftKey){ //select multiples\r\n\r\n if(index > global.last_selected){\r\n while(index >= global.last_selected){\r\n $('.file[data-i=\"'+index+'\"]').addClass('selected');\r\n index--;\r\n }\r\n }\r\n else{\r\n while(index <= global.last_selected){\r\n $('.file[data-i=\"'+index+'\"]').addClass('selected');\r\n index++;\r\n }\r\n }\r\n $(this).addClass('selected');\r\n global.total_selected=$('.selected').length;\r\n\r\n text=global.total_selected+' files selected';\r\n }\r\n else if(e.ctrlKey){\r\n if($(this).hasClass('selected'))\r\n $(this).removeClass('selected');\r\n else\r\n $(this).addClass('selected');\r\n global.total_selected=$('.selected').length;\r\n text=global.total_selected+' files selected';\r\n }\r\n else{ //deselect everything except this one\r\n global.last_selected=index;\r\n $(this).addClass('selected');\r\n global.total_selected=1;\r\n console.log(manager.files[index]);\r\n text=manager.files[index].rel_filename;\r\n if(manager.files[index].type!=='dir')\r\n text+=' - Size:'+manager.files[index].filesize;\r\n text+=' - Modified:'+manager.files[index].modified;\r\n }\r\n $('#info').text(text);\r\n \r\n if(global.total_selected === 1){\r\n $('#edit .single').show();\r\n }\r\n else{\r\n $('#edit .single').hide();\r\n }\r\n if(global.total_selected > 0){\r\n $('#edit').show();\r\n }\r\n else{\r\n $('#edit').hide();\r\n }\r\n });\r\n \r\n //open the file\r\n $('.file[data-type!=\"dir\"]').on('dblclick',function(){\r\n var index=$(this).data('i');\r\n if(typeof index==='undefined')return;\r\n var file=manager.files[index];\r\n $('#image').html('');\r\n $('#text textarea').html('');\r\n manager.get_file(index,function(file){\r\n if(!file){\r\n error('This type of file is not permitted.');\r\n }\r\n else{\r\n console.log(file);\r\n $('#image').hide();\r\n $('#text').hide();\r\n $('#iframe').hide();\r\n if(file.action=='view'){\r\n if(file.type==='jpg' || file.type==='gif' || file.type==='png'){\r\n $('#image').html('<img src=\"'+global.base_url+file.rel_filename+'\">');\r\n $('#image').show();\r\n lightbox.show(file.filename);\r\n }\r\n else{\r\n console.log(global.base_url+encodeURIComponent(file.rel_filename));\r\n window.open(global.base_url+encodeURIComponent(file.rel_filename));\r\n //$('#iframe iframe').attr('src',global.base_url+encodeURIComponent(file.rel_filename));\r\n }\r\n }\r\n else if(file.action=='edit'){\r\n $('#text textarea').text(file.contents);\r\n $('#text').show();\r\n lightbox.show(file.filename);\r\n }\r\n else{\r\n $('#iframe iframe').attr('src','download.php?file='+encodeURIComponent(file.rel_filename));\r\n }\r\n }\r\n });\r\n \r\n });\r\n\r\n $('.dir').on('dblclick',function(){open_dir($(this).data('file'));});\r\n\r\n manager.get_breadcrumbs(function(nav){\r\n html='';\r\n for(var i=0;i<nav.length;i++){\r\n html+='<li><a data-path=\"'+nav[i].rel_path+'\">'+nav[i].name+'</a></li>';\r\n }\r\n $('.breadcrumb li').remove();\r\n $('.breadcrumb').html(html);\r\n $('.breadcrumb li a').on('click',function(){open_dir($(this).data('path'));});\r\n $('body').removeClass('loading');\r\n });\r\n });\r\n //window.location.href=window.location.origin+window.location.pathname+'?dir='+$(this).data('file');\r\n}", "function getActiveFile() {\n var active = getActiveTab();\n if(!active) {\n return false;\n }\n return lt.objs.tabs.__GT_path(active);\n }", "openFile(x,e){\n console.log(x);\n let text = this.VirtualDisk[x.father].getData(x.clusterStart);\n if(x.kind == \"file\"){\n this.setState({\n disks : this.state.disks,\n current : this.state.current,\n mode : 3,\n selected : x,\n nameFile : x.name,\n infoFile : text\n });\n }\n\n }", "GetPath() {return this.filePath;}", "get information(){\n return this.info_files;\n }", "function getCurrentFileOrDefault() {\n var pFile = LaunchBar.executeAppleScript('if application \"TaskPaper\" is running then',\n 'tell application id (id of application \"TaskPaper\")',\n ' set a to file of the front document',\n ' return POSIX path of a',\n 'end tell',\n 'else',\n ' return \"\"',\n 'end if').trim();\n if (pFile == \"\") {\n if(File.exists(LaunchBar.homeDirectory + \"/.tpProjectFile\"))\n pFile = File.readText(LaunchBar.homeDirectory + \"/.tpProjectFile\");\n } else {\n //\n // Save the path to the ~/.tpProjectFile location.\n //\n File.writeText(pFile, LaunchBar.homeDirectory + \"/.tpProjectFile\");\n }\n\n //\n // Return the project file location.\n //\n return (pFile);\n}", "function file(i)\n\t\t\t\t{\n\t\t\t\t\tvar filename = files[i];\n\t\t\t\t\tfs.stat(curDir+'/'+filename,function(err,stat){\n\t\t\t\t\t\t\n\t\t\t\t\t\tstats[i] = stat;\n\t\t\t\t\t\tif(stat.isDirectory())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconsole.log('\t'+i+'\t\\033[36m'+filename+'/\\033[39m');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconsole.log('\t'+i+'\t\\033[36m'+filename+'\\033[39m');\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ti++;\n\t\t\t\t\t\tif (i!=files.length) {\n\t\t\t\t\t\t\tfile(i);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconsole.log('\\n\tSelect which file or direcroty you want to see');\n\t\t\t\t\t\t\tconsole.log('\tor');\n\t\t\t\t\t\t\tconsole.log('\tyou can just enter another path to see');\n\t\t\t\t\t\t\tconsole.log('\tor');\n\t\t\t\t\t\t\tconsole.log('\tenter \"b\" to go to the parent folder.\\n');\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}", "async getFileInfo() {\n return this.fileInfo;\n }", "static getRecentFiles(evt){\n let filePaths = FolderData.recentFilePaths;\n IpcResponder.respond(evt, \"files-recent\", {filePaths});\n }", "function getFile(){\n\n\t\treturn this.file;\n\t}", "function getFileInfoDropdown(){\n\t\tvar currentField = this;\n\t\tvar val = this.value; //filename\n\t\tdropdownAdd(val);\n\t\tshowAlarms(val);\n}", "static getLastOpenedFile(callback) {\r\n FileWriterRemote.fileWriter.getLastOpenedFile(callback);\r\n }", "get file() {\r\n return new File(this, \"file\");\r\n }", "function showFileInfo (container) {\n\n var options = container.data(\"options\");\n\n\t\tvar fileinfo = '';\n\t\t\t\n\t\tif(options.fileName || options.scanNum) {\n\t\t\tfileinfo += '<div style=\"margin-top:5px;\" class=\"font_small\">';\n\t\t\tif(options.fileName) {\n\t\t\t\tfileinfo += 'File: '+options.fileName;\n\t\t\t}\n\t\t\tif(options.scanNum) {\n\t\t\t\tfileinfo += ', Scan: '+options.scanNum;\n\t\t\t}\n if(options.precursorMz) {\n fileinfo += ', Exp. m/z: '+options.precursorMz;\n }\n\t\t\tif(options.charge) {\n\t\t\t\tfileinfo += ', Charge: '+options.charge;\n\t\t\t}\n\t\t\tfileinfo += '</div>';\n\t\t}\n\t\t\n\t\t$(getElementSelector(container, elementIds.fileinfo)).append(fileinfo);\n\t}", "function getCurrentUserInfo() {\r\n\t \treturn self._userInfo;\r\n\t }", "function GetCurentFileName()\n{\n var pagePathName = window.location.pathname;\n var lastPathSegment = pagePathName.substr(pagePathName.lastIndexOf('/') + 1);\n lastPathSegment = lastPathSegment.substr(0, lastPathSegment.lastIndexOf('.'));\n if (lastPathSegment == \"\") lastPathSegment = \"index\";\n return lastPathSegment;\n}", "function getCurrentImage() {\n\tvar currentImagePath = $(\".overlayImg img\").attr(\"src\");\n\tvar currentImage = currentImagePath.substring(currentImagePath.lastIndexOf(\"/\") + 1, currentImagePath.length);\n\t\n\treturn currentImage;\n}", "getFiles() {\n this.divFiles.innerHTML = \"\";\n this._fileList = this.fs.readdir(this.path).filter(fileName => fileName !== \".\" && fileName !== \"..\" && this.fs.isFile(this.fs.stat(this.path + fileName).mode));\n\n this._fileList.forEach(fileName => {\n var divFile = this.createFileDiv(fileName, false);\n this.divFiles.appendChild(divFile);\n });\n\n if (this._fileList.length === 0) {\n var fileName = this.newFile(\"untitled.dsp\", \"import(\\\"stdfaust.lib\\\");\\nprocess = ba.pulsen(1, 10000) : pm.djembe(60, 0.3, 0.4, 1) <: dm.freeverb_demo;\");\n this.select(fileName);\n } else {\n this.select(this._fileList[0]);\n }\n\n if (this.$mainFile >= this._fileList.length) this.setMain(this._fileList.length - 1);else this.setMain(this.$mainFile);\n }", "function FileMgr() {\n}", "function getCurrentFilenames(dirPath) { \n let files = []\n // console.log(`Current files in: ${dirPath}`); \n fs.readdirSync(dirPath).forEach(file => { \n // console.log(\" \" + file);\n files.push(file)\n });\n return files\n}" ]
[ "0.64498436", "0.6211815", "0.5877517", "0.58511686", "0.58344495", "0.5813102", "0.5813102", "0.56974804", "0.56627387", "0.5660691", "0.55960137", "0.55346304", "0.55316913", "0.5522157", "0.54973036", "0.5495355", "0.5493738", "0.54894185", "0.5487194", "0.5457002", "0.53932345", "0.53858525", "0.53773206", "0.53715104", "0.53692037", "0.5361538", "0.53356224", "0.5316852", "0.5244857", "0.5242068" ]
0.6290701
1
This is the handler that captures mousemove events when an element is being dragged. It is responsible for moving the element.
function moveHandler(e) { func_state = state_mouse_move; if (!e) e = window.event; // IE event Model // Move the element to the current mouse position, adjusted by the // position of the scrollbars and the offset of the initial click. var scroll = getScrollOffsets(); var left = (e.clientX + scroll.x - deltaX); var top = (e.clientY + scroll.y - deltaY); elementToDrag.style.left = left + "px"; elementToDrag.style.top = top + "px"; console.log('in moveHandler: %d - %d', left, top); //console.log('element position: %s - %s', elementToDrag.style.left, elementToDrag.style.top); if(out_of_content_row(left, top)){ //left = origX; //top = origY; delete_file(); upHandler(e); } // And don't let anyone else see this event. if (e.stopPropagation) e.stopPropagation(); // Standard else e.cancelBubble = true; // IE clearInterval(timer); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function moveHandler(e) {\n if (!e) e = window.event; // IE event Model\n\n // Move the element to the current mouse position, adjusted by the\n // position of the scrollbars and the offset of the initial click.\n var scroll = lion.getScrollOffsets();\n elementToDrag.style.left = (e.clientX + scroll.x - deltaX) + \"px\";\n elementToDrag.style.top = (e.clientY + scroll.y - deltaY) + \"px\";\n\n // And don't let anyone else see this event.\n if (e.stopPropagation) e.stopPropagation(); // Standard\n else e.cancelBubble = true; // IE\n }", "onElementMouseMove(event) {\n if (this.dragContext) {\n this.updateMove(event.clientX);\n event.preventDefault();\n }\n }", "onElementMouseMove(event) {\n if (this.dragContext) {\n this.updateMove(event.clientX);\n event.preventDefault();\n }\n }", "onElementMouseMove(event) {}", "onElementMouseMove(event) {\n if (this.dragContext) {\n this.updateMove(event.clientX);\n event.preventDefault();\n }\n }", "function moveHandler(e) {\n if (!e) e = window.event; // IE event Model\n\n if (e.touches && e.touches.length > 1) upHandler(e); //if at any point there are two fingers on screen stop the move\n \n // Move the element to the current mouse position, adjusted by the\n // position of the scrollbars and the offset of the initial click.\n var scroll = getScrollOffsets();\n var newLeft;\n if (options.axis == null || options.axis === 'x') newLeft = ((e.clientX || event.targetTouches[0].clientX) + scroll.x - deltaX);\n else newLeft = parseFloat(elementToDrag.style.left);\n\n var newTop;\n if (options.axis == null || options.axis === 'y') newTop = ((e.clientY || event.targetTouches[0].clientY) + scroll.y - deltaY);\n else newTop = parseFloat(elementToDrag.style.top);\n\n //check if new location is in containment\n if(newLeft < options.containment[0] || newLeft > options.containment[2] || newTop < options.containment[1] || newTop > options.containment[3])\n return;\n\n elementToDrag.style.left = newLeft + \"px\";\n elementToDrag.style.top = newTop + \"px\";\n // don't let anyone else see this event.\n if (e.stopPropagation) e.stopPropagation(); // Standard\n else e.cancelBubble = true; // IE\n \n if (event.preventDefault) event.preventDefault(); // Standard model\n else event.returnValue = false; // IE\n \n if(options.drag) options.drag(e, e.target);\n }", "function moveHandler(e){\n if(!e) e=window.event;\n elementToDrag.style.left=(e.clientX-deltaX)+\"px\";\n elementToDrag.style.top=(e.clientY-deltaY)+\"px\";\n\n if(e.stopPropagation) e.stopPropagation();\n else e.cancelBubble=true;\n }", "onElementMouseMove(event) {\n // Keep track of the last mouse position in case, due to OSX sloppy focusing,\n // focus is moved into the browser before a mousedown is delivered.\n // The cached mousemove event will provide the correct target in\n // GridNavigation#onGridElementFocus.\n this.mouseMoveEvent = event;\n }", "function DIF_mouseMove(e) {\n if (DIF_dragging) {\n var pos = DIF_getEventPosition(e);\n DIF_drag(pos.x - DIF_pageMouseDownLeft[DIF_iframeBeingDragged], pos.y - DIF_pageMouseDownTop[DIF_iframeBeingDragged]);\n }\n}", "function mouseMoveHandler(e) {\n updateFromEvent(e);\n move(mouseX, mouseY);\n }", "moveHandler(event) {\n\n //Get the element that's firing the event\n let element = event.target;\n\n //Find the pointer’s x and y position (for mouse).\n //Subtract the element's top and left offset from the browser window\n this._x = (event.pageX - element.offsetLeft);\n this._y = (event.pageY - element.offsetTop);\n\n //Prevent the event's default behavior \n event.preventDefault();\n }", "function handleDrag ( event /*: JQueryEventObject */ ) {\n var dx = event.pageX - $element[0].dragData.lastX,\n dy = event.pageY - $element[0].dragData.lastY,\n dleft = dx, dtop = dy, dright = dx, dbottom = dy;\n if ( $element[0].dragData.type != 4 ) {\n if ( $element[0].dragData.type > 2 ) dtop = 0;\n if ( $element[0].dragData.type < 6 ) dbottom = 0;\n if ( $element[0].dragData.type % 3 > 0 ) dleft = 0;\n if ( $element[0].dragData.type % 3 < 2 ) dright = 0;\n }\n reposition( dleft, dtop, dright, dbottom );\n $element[0].dragData.lastX = event.pageX;\n $element[0].dragData.lastY = event.pageY;\n }", "function mousemoveHandler ( event /*: JQueryEventObject */ ) {\n if ( $element.hasClass( pausedDragSelectClass ) ) return;\n if ( !$element.hasClass( SELECTED_FOR_DRAGGING_CLASS ) ) {\n $element.css( { cursor : 'default' } );\n return;\n }\n switch ( eventToCellNumber( event, $element[0] ) ) {\n case 0 : case 8 : $element.css( { cursor : 'nwse-resize' } ); break;\n case 1 : case 7 : $element.css( { cursor : 'ns-resize' } ); break;\n case 2 : case 6 : $element.css( { cursor : 'nesw-resize' } ); break;\n case 3 : case 5 : $element.css( { cursor : 'ew-resize' } ); break;\n case 4 : $element.css( { cursor : 'move' } ); break;\n default : $element.css( { cursor : 'default' } );\n }\n }", "function elementDrag(e) {\n e = e || window.event;\n // Calculate the new cursor position:\n pos1 = pos3 - e.clientX;\n pos2 = pos4 - e.clientY;\n pos3 = e.clientX;\n pos4 = e.clientY;\n // Set the element's new position:\n divCont.style.marginLeft = divCont.offsetLeft - _self._ratio * pos1 + \"px\";\n divCont.style.marginTop = divCont.offsetTop - _self._ratio * pos2 + \"px\";\n }", "function moveHandler(e) \n\t{\n\t\t\n\t\tme.style.cursor = \"move\"; \n\t\t\n\t\tif (!e) e = window.event; // IE Event Model\n\t\t\n\t\t// Move the element to the current mouse position, adjusted as\n\t\t// necessary by the offset of the initial mouse-click.\n\t\tme.style.left = (e.clientX - deltaX) + \"px\";\n\t\tme.style.top = (e.clientY - deltaY) + \"px\";\n\t\t\n\t\t// And don't let anyone else see this event.\n\t\tif (e.stopPropagation) e.stopPropagation( ); // DOM Level 2\n\t\telse e.cancelBubble = true; // IE\n\t}", "onPointerMove(e) {\n\t\tif (this.mouseMoved < dragThreshold) {\n\t\t\tthis.mouseMoved += 1;\n\t\t\treturn;\n\t\t}\n\n\t\tif (!draggingEl) {\n\t\t\temit(this.el, 'dragstart');\n\n\t\t\tdraggingEl = this.el;\n\t\t\tthis.$clonedEl = createDragShadow(this.el, this.shadowClass);\n\n\t\t\t// for auto-scroll\n\t\t\tthis.scrollParent.addEventListener(events.enter, this.onPointerEnter, { passive: true });\n\t\t\tthis.scrollParent.addEventListener(events.leave, this.onPointerLeave, { passive: true });\n\t\t\tthis.onPointerEnter();\n\t\t}\n\n\t\tthis.$clonedEl.moveTo(e);\n\t\temit(this.el, 'drag');\n\n\t\t// for auto-scroll\n\t\tconst scrollRect = this.scrollParent.getBoundingClientRect();\n\t\t// is the mouse closer to the top or bottom edge of the scroll parent?\n\t\tconst topDist = Math.abs(scrollRect.top - e.clientY);\n\t\tconst bottomDist = Math.abs(scrollRect.bottom - e.clientY);\n\t\t// should we scroll up, or down?\n\t\tconst speedDirection = topDist < bottomDist ? -1 : 1;\n\t\t// should we scroll at 3px per frame, or 0px per frame (i.e. pause auto-scroll)?\n\t\tconst speedMagnitude = Math.min(topDist, bottomDist) < 40 ? 3 : 0;\n\t\tthis.scrollSpeed = speedDirection * speedMagnitude;\n\t}", "function DIF_mousemove(e) {\r\n\tif (DIF_dragging) {\r\n\t\tvar pos = {x: e.pageX, y: e.pageY};\r\n\t\tDIF_drag(pos.x - DIF_pageMouseDownLeft[DIF_iframeBeingDragged] , pos.y - DIF_pageMouseDownTop[DIF_iframeBeingDragged]);\r\n\t}\r\n}", "onMouseMove (e) {\n let event = 'mouse-move';\n if (this.isMouseDown) {\n event = 'mouse-drag';\n }\n\n this.emit(event, normaliseMouseEventToElement(this.canvas, e));\n }", "function onMouseMoveEventOnHandler(ev){\n if(WorkStore.isSelected()) return;\n\n window.addEventListener(MOUSE_DOWN, onMouseDownHandler);\n document.body.classList.add(\"drag\");\n}", "captureMouseMoves(/*object*/ event) {\n if (!this._eventMoveToken && !this._eventUpToken) {\n this._eventMoveToken = EventListener.listen(\n this._domNode,\n 'mousemove',\n this._onMouseMove\n );\n this._eventUpToken = EventListener.listen(\n this._domNode,\n 'mouseup',\n this._onMouseUp\n );\n }\n\n if (!this._isDragging) {\n this._deltaX = 0;\n this._deltaY = 0;\n this._isDragging = true;\n this._x = event.clientX;\n this._y = event.clientY;\n }\n event.preventDefault();\n }", "_moveHandler() {\n if (this.hasAttribute('dragged') && JQX.Utilities.Core.isMobile) {\n event.originalEvent.preventDefault();\n }\n }", "handleMouseDown(e) {\n this.start = pos(e);\n this.w0 = this.state.w;\n d.addEventListener('mousemove', this.handleDrag)\n d.addEventListener('mouseup', this.handleMouseUp.bind(this))\n }", "function dragMoveListener (event) {\n var target = event.target,\n // keep the dragged position in the data-x/data-y attributes\n x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,\n y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;\n\n\t// translate the element\n\ttarget.style.webkitTransform =\n\ttarget.style.transform =\n\t 'translate(' + x + 'px, ' + y + 'px)';\n\n\t// update the posiion attributes\n\ttarget.setAttribute('data-x', x);\n\ttarget.setAttribute('data-y', y);\n}", "onMouseDrag(e) {}", "function reactionMouseMove (e) { \r\n if (!drag) return; // Abbrechen, falls Zugmodus nicht aktiviert\r\n reactionMove(e.clientX,e.clientY); // Position ermitteln, rechnen und neu zeichnen\r\n }", "function reactionMouseMove (e) { \r\n if (!drag) return; // Abbrechen, falls Zugmodus nicht aktiviert\r\n reactionMove(e.clientX,e.clientY); // Position ermitteln, rechnen und neu zeichnen \r\n }", "function dragMouse(e) {\n console.log('dragMouse');\n e = e || window.event;\n // calculate the new cursor position:\n pos1 = pos3 - e.clientX;\n pos2 = pos4 - e.clientY;\n pos3 = e.clientX;\n pos4 = e.clientY;\n // set the element's new position:\n elem.style.top = (elem.offsetTop - pos2) + \"px\";\n elem.style.left = (elem.offsetLeft - pos1) + \"px\";\n }", "dragMove(event) {\n\t\tif (!this.isDrag) return false;\n\t\tif (this.isDrag) {\n\t\t\t// make cursor change to grabbing\n\t\t\tthis.slider.classList.add('grabbing')\n\t\t\t// Get the mouse or finger X position\n\t\t\tlet clientX = this.getClientX(event);\n\t\t\tlet moved = this.reference - clientX;\n\t\t\tthis.reference = clientX;\n\t\t\tthis.direction = (moved > 0) ? 1 : (moved < 0) ? -1 : 0;\n\t\t\tthis.scroll(this.direction, this.scrollOffset + moved);\n\t\t}\n\n\t}", "function _onDocumentMouseMove(e) {\r\n var pointerId = Utils.getPointerId(e),\r\n item = clones.get(pointerId);\r\n if (item) {\r\n item.clientX = e.clientX;\r\n item.clientY = e.clientY;\r\n if (item.pointerId === pointerId) {\r\n _preventDefault(e);\r\n frameId = Gestures.getAnimationFrame(frameId, _setPositions);\r\n item.updateIntersection(e);\r\n } else if (Math.abs(item.startPosition.x - e.clientX) > self.dragOffset || Math.abs(item.startPosition.y - e.clientY) > self.dragOffset) {\r\n _preventDefault(e);\r\n item.dispatchDragStart();\r\n item.pointerId = pointerId;\r\n frameId = Gestures.getAnimationFrame(frameId, _setPositions); // apply current position to prevent jumping on rotated elements\r\n document.body.append(item.clone);\r\n }\r\n }\r\n }", "function reactionMouseMove (e) { \n if (!drag) return; // Abbrechen, falls Zugmodus nicht aktiviert\n reactionMove(e.clientX,e.clientY); // Position ermitteln, rechnen und neu zeichnen\n }" ]
[ "0.7829178", "0.75963956", "0.75963956", "0.75552905", "0.75467914", "0.74622387", "0.7408157", "0.7294221", "0.72456145", "0.7178884", "0.71744835", "0.70877546", "0.70258254", "0.7008248", "0.6947241", "0.687514", "0.6863924", "0.6841702", "0.6828741", "0.6769443", "0.67639095", "0.6756179", "0.6739531", "0.67301524", "0.6719872", "0.67182577", "0.667857", "0.66747075", "0.6671908", "0.66658336" ]
0.7636558
1
return a serial number
serialNumber() { return `${this.getSNString()}${(this.increament++).toString().padStart(this.padCount, '0')}`; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getSerialId() {\n if (!this.serialid) {\n let id = this.getId();\n if (id) {\n id = id.replace(/(.+?)\\/(.+?)\\/(.*)/, '$2');\n this.serialid = id.replace(/(.+)-(.+)/, '$2');\n }\n }\n return this.serialid;\n }", "function SerialNum()\n{\n var num = 1;\n}", "async function getSerial() {\n return constants.SERIAL;\n}", "static async getStoredSerialNumberById(id){\n const serialNum = await Seriall.getSerialNumberById(id);\n return serialNum;\n }", "function _x509_getSerialNumberHex() {\n return ASN1HEX.getDecendantHexVByNthList(this.hex, 0, [0, 1]);\n}", "function calculateId(device) {\n // return prefix + device.serial\n return device.serial\n }", "function ZNPSerial() {\n}", "function createVersionNumber() {\n return new Date().toJSON().slice(0, 10) + '--' + uniqueId();\n}", "static async postSerialNumber(id){\n const serialNumbers = await this.getAllSerialNumbers();\n \n const numberID = Number(id);\n\n const desiredSerialNumber = [];\n\n for(const serialNumber of serialNumbers){\n if(serialNumber.id === numberID){\n desiredSerialNumber.push(serialNumber.name);\n }\n }\n const serial = await Seriall.insert({ serial_number: desiredSerialNumber[0] });\n return serial;\n\n }", "function getUniqueID() {\n var id = new Date().valueOf();\n return id + \".\" + incrementID.increment();\n }", "static async deleteStoredSerialNumberById(id){\n const serialNum = await Seriall.deleteSerialNumberById(id);\n return serialNum;\n }", "function uuidNum(num) {\n return '00000000-0000-0000-0000-0000000000'\n + (Number(num) < 10 ? '0' + num : num);\n}", "function getUniqueNumber() {\n\tuniqueNumber++;\n\treturn uniqueNumber;\n}", "function uuid() {\n return \"uid-\" + __counter++;\n}", "function makeUniqueUserId() {\n\treturn `XX${String(++useridSerial).padStart(4, '0')}`;\n}", "static async getStoredSerialNumbers(){\n const serialNums = await Seriall.allSerialNumbers();\n return serialNums;\n }", "function obtenerNumeroDigitado(botonDigitado) {\n return botonDigitado[1];\n}", "calculateID() {\n const serial = this.serialize(this.data);\n const hash = crypto.createHash('sha256');\n hash.update(serial);\n return hash.digest('hex'); // **Encoding the ID in hex**\n }", "function getUniqueIdentifierStr() {\n return getIncrementalInteger() + Math.random().toString(16).substr(2);\n}", "function newSeqNum(){\n nextSeqNum++;\n return nextSeqNum;\n }", "function getSerialNumber() {\n let filesInDir = fs.readdirSync(\n `${__dirname}/../documents/storage`,\n (err, files) => {\n if (err) res.status(500).send(err);\n }\n );\n\n filesInDir = filesInDir.filter(file => {\n return file != DS_Store; // in order to ignore the '.DS_Store' file\n });\n\n for (let i = 0; i < filesInDir.length; i++)\n filesInDir[i] = filesInDir[i].slice(0, -4);\n\n return filesInDir.length === 0 ? 0 : Math.max(...filesInDir);\n}", "function genereID(){\nvar ref='DA-';\nvar date = new Date();\n\n // Format de l'ID de la demande d'achat DA-YYMMDD-HHMMSS\n ref+=(String(date.getFullYear())).slice(-2)+(\"0\"+ String(date.getMonth()+1)).slice(-2)+(\"0\" + String(date.getDate())).slice(-2);\n ref+=\"-\"\n ref+=(\"0\"+String(date.getHours())).slice(-2)+(\"0\"+ String(date.getMinutes()+1)).slice(-2)+(\"0\" + String(date.getSeconds())).slice(-2);\n return ref;\n}", "function calculateNumericDigit(serial) {\n const MODULE = 11\n const MIN_FACTOR = 2\n const MAX_FACTOR = 7\n\n const { sum } = serial.split('').reduceRight(\n (state, char) => ({\n sum: state.sum + Number(char) * state.factor,\n factor: state.factor == MAX_FACTOR ? MIN_FACTOR : state.factor + 1,\n }),\n { sum: 0, factor: MIN_FACTOR }\n )\n\n return MODULE - (sum % MODULE)\n}", "generateCid() {\n // random number + last 7 numbers of current time\n return 'cid_' + Math.random().toString(36).substr(2) + '_' + new Date().getTime().toString().substr(-7);\n }", "function generatePID () {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n })\n}", "function generateID (idx) {\n return ('jsrch_' + idx + '_' + new Date().getTime());\n }", "function phoneNumber(no){\n\t\n}", "function sequencia4(num) {\n return 0\n}", "function generateNumCommande() {\n var random = Math.floor(100000000 + Math.random() * 900000000);\n num_commande = 'NH'+random\n }", "function pvrInvoiceNumber(jsonInvoice) {\n var prefixLength = jsonInvoice[\"document_info\"][\"number\"].indexOf('-');\n if (prefixLength >= 0) {\n return jsonInvoice[\"document_info\"][\"number\"].substr(prefixLength + 1);\n }\n return jsonInvoice[\"document_info\"][\"number\"]\n}" ]
[ "0.76606715", "0.71967834", "0.7139077", "0.6988839", "0.66305053", "0.6586764", "0.6361851", "0.62254936", "0.6079622", "0.6056119", "0.6008889", "0.5999183", "0.594697", "0.58675075", "0.5865588", "0.5862116", "0.5846896", "0.5840436", "0.58371073", "0.5819352", "0.58148134", "0.5799495", "0.5778362", "0.5761594", "0.57591873", "0.5740852", "0.5729667", "0.5728292", "0.57277256", "0.5726947" ]
0.846465
0
animates loading screen logo with random glitch animation
function animateLogo() { let random; random = Math.floor((Math.random() * 3)+ 1); $('#wave').css("animation", "glitch" + random + " 2s ease infinite"); setTimeout(function(){ random = Math.floor((Math.random() * 3)+ 1); $('#erase').css("animation", "glitch" + random + " 2s ease infinite"); setTimeout(function(){ random = Math.floor((Math.random() * 3)+ 1); $('#blur').css("animation", "glitch" + random + " 2s ease infinite"); }, 40);}, 40); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function runLogoAnimation() {\n for (const path of svgDrawingPaths) {\n path.style.strokeDashoffset = \"0px\";\n }\n for (const cPath of svgCirclePaths) {\n cPath.style.cssText = \"stroke-dashoffset: 0; transition-delay: 1200ms;\";\n }\n svgVerve.style.cssText =\n \"transform:translateX(0px); transition:transform 1s ease .8s;\";\n svg360.style.cssText =\n \"transform:translateX(0px);opacity:1;transition:all 1s ease .8s;\";\n document.getElementById(\"small-circle\").style.opacity = \"1\";\n setTimeout(firstPageLoaded, 2000);\n}", "function animateLogo()\n{\n if (logoPhase > 7)\n {\n setDutyCycle(2, 10);\n return;\n }\n else if (logoPhase > 6)\n {\n showBitwigLogo = false;\n var i = 0.5 - 0.5 * Math.cos(logoPhase * Math.PI);\n setDutyCycle(Math.floor(1 + 5 * i), 18);\n }\n else\n {\n var i = 0.5 - 0.5 * Math.cos(logoPhase * Math.PI);\n setDutyCycle(Math.floor(1 + 15 * i), 18);\n }\n\n logoPhase += 0.2;\n\n host.scheduleTask(animateLogo, null, 30);\n}", "function setupLogoAnimation() {\n logo.style.cssText = \"display:inline-block;\";\n i = 0;\n for (const path of svgDrawingPaths) {\n i++;\n var strokeOffset = path.getTotalLength();\n path.style.cssText =\n \"stroke-dashoffset: \" +\n strokeOffset +\n \"px; stroke-dasharray: \" +\n strokeOffset +\n \"px; transition-delay:\" +\n i * 0 +\n \"ms;\";\n }\n svgVerve.style.cssText = \"transform:translateX(50px);\";\n setTimeout(runLogoAnimation, 100);\n}", "function animateLogo () {\n\t\tvar repeatVisitFlag = IBM.common.util.storage.getItem(\"v18larv\");\n\t\t\n\t\t// Allow animation to be forced to show via URL param (for debugging, presentations, show-and-tell, etc).\n\t\tif (IBM.common.util.url.getParam(\"animatelogo\")) {\n\t\t\t$(\"#ibm-home\").addClass(\"ibm-animate\");\n\t\t}\n\n\t\tif (!IBM.common.util.config.isEnabled(\"masthead.logoanimation\")) {\n\t\t\treturn;\n\t\t}\n\n\t\t// If they didn't have the flag AND they support localstorage, animate it.\n\t\tif (!repeatVisitFlag && IBM.common.util.storage.setItem(\"v18larv\", true)) {\n\t\t\t$(\"#ibm-home\").addClass(\"ibm-animate\");\n\t\t}\n\t}", "animateLogo() {\n const imageLoad = new Image();\n imageLoad.src = this.imageSrc;\n imageLoad.onload = this.animatePattern();\n }", "function logoBlink() {\n let logoBlink = new TimelineMax({});\n logoBlink.staggerTo(\".icon\", 0.3, { scale: 0, transformOrigin: \"50% 50%\" }, 0.1, \"+=0.5\")\n .staggerTo(\".icon\", 0.3, { scale: 1, ease: Back.easeOut.config(3.5), transformOrigin: \"50% 50%\" }, 0.1, \"-=0.5\");\n return logoBlink;\n}", "function animateLoader() {\r\n\tif (moonState < moonStateImages.length) {\r\n\t\t$(\"#fe_intro_moon img\").attr(\"src\", \"img/\" + moonStateImages[moonState]);\r\n\t\t$(\"#fe_intro_moon p\").html(Math.round(moonState/moonStateImages.length * 100));\r\n\t\tmoonState++;\r\n\t\tsetTimeout(animateLoader, 350); // the interval between frames\r\n\t}\r\n\telse {\r\n\t\t$(\"#fe_intro_moon img\").attr(\"src\", \"img/\" + moonStateImages[moonState-1]);\r\n\t\t$(\"#fe_intro_moon p\").html(Math.round(moonState/moonStateImages.length * 100));\r\n\t\tsetTimeout(startIntro, 250); // play the intro when the load animation completes\r\n\t}\r\n}", "function homeAnim() { //homepage animation on load \n qsCl(\"home__logo-fill\").left = '-177px';\n qsCl(\"home__logo-dolya\").color = 'black';\n qsCl(\"home__logo-consulting\").color = 'black';\n qsCl(\"home__logo-frame\").opacity = '1';\n qsCl(\"home__tagline-line\").width = '60px';\n qsCl(\"home__mission-statement\").color = '#303030';\n qsCl(\"home__tagline\").color = '#303030';\n qsCl(\"home__golden-thread\").color = 'var(--gold)';\n qsCl(\"path-logo\").animation = 'dash 3s ease-in forwards 1s'\n qsCl(\"path-home\").animation = 'dash 5s ease-in-out forwards 4s';\n drawn.home = true;\n}", "function preloadLogoEnd() {\n\n}", "function preloadLogoEnd() {\n loaderStop();\n}", "function showLogoRed() {\n $.logoRed.animate({ opacity:1.0, duration:250 });\n $.logoWhite.animate({ opacity:0.0, duration:250 });\n\n $.helpLight.animate({ opacity:1.0, duration:250 });\n $.helpDark.animate({ opacity:0.0, duration:250 });\n}", "function AnimateLogo(){\n\n\tvar bgTransparency = 0.00;\n\tvar animateProcess = \"\";\n\t\n\t// Starting the animation\n\tif (animLogoTransitionID == null){\n\t\t// Start the animation\n\t\tanimLogoTransitionID = setInterval(function (){\n\t\t\t\n\t\t\t// Ending the animation, when the image has been loaded\n\t\t\tif( imageLoaded == 1){\n\t\t\t\n\t\t\t\tclearInterval(animLogoTransitionID);\n\t\t\t\tanimLogoTransitionID = null;\n\t\t\t\tDOMLogo_LoadTransict.setAttribute (\"opacity\", 0.0);\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse{ // Continuing with animation\n\t\t\t\t// Putting the logo in the front\n\t\t\t\tDOMLogo_LoadTransict.parentNode.appendChild(DOMLogo_LoadTransict);\n\t\t\t\t\n\t\t\t\t// Setting the transparency of the logo. If the logo gets transparent, return to the visibility and vice-versa\n\t\t\t\tif ( bgTransparency <= 0.00 ) // Raise the opacity\n\t\t\t\t\tanimateProcess = \"lessTransp\";\n\t\t\t\tif ( bgTransparency >= 0.75 )\n\t\t\t\t\tanimateProcess = \"moreTransp\"; // Lower the opacity\n\t\t\t\t\n\t\t\t\t// Now, setting the values\n\t\t\t\tif (animateProcess == \"lessTransp\")\n\t\t\t\t\tbgTransparency = CalculateScaleTransition (bgTransparency, 0.75, \"fast-background\");\n\t\t\t\tif (animateProcess == \"moreTransp\")\n\t\t\t\t\tbgTransparency = CalculateScaleTransition (bgTransparency, 0.00, \"fast-background\");\n\t\t\t\t\t\n\t\t\t\t// And, setting the value to the logo\n\t\t\t\tDOMLogo_LoadTransict.setAttribute (\"opacity\", bgTransparency);\t\n\t\t\t}\n\t\t}, 40);\n\t}\n}", "function random_img() {\n var bgurl = [];\n $.each(teams, function (key, f) {\n bgurl[key] = f.team_img_url;\n\n\n });\n //generating random images logo\n var x = Math.floor(Math.random() * bgurl.length);\n if (x <= bgurl.length) {\n $(\"#logo1\").attr(\"src\", bgurl[x]);\n //animation for logo images.....\n var div = $(\"#logo1\");\n div.animate({ height: '300px', opacity: '0.4' }, \"slow\");\n div.animate({ width: '300px', opacity: '0.8' }, \"slow\");\n div.animate({ height: '100px', opacity: '0.4' }, \"slow\");\n div.animate({ width: '100px', opacity: '0.8' }, \"slow\");\n\n setTimeout(random_img, 1000);\n }\n }", "function animationLogo() {\n logo.classList.add('logo-animate');\n}", "splashBottle() {\n clearInterval(this.gravitation);\n clearInterval(this.the_throw); \n this.playAnimation(this.IMAGES_SPLASH);\n this.splash_sound.play();\n setInterval(() => {\n this.width = 0;\n this.height = 0;\n }, 200);\n }", "function stopLogoAnimation() {\n if (typeof window.showlogo_iv !== 'undefined') {\n window.ncka = window.lgss = window.lga = 1;\n clearInterval(window.showlogo_iv);\n showLogo(true);\n } else {\n setTimeout(stopLogoAnimation, 25);\n }\n }", "function showLogoWhite() {\n $.logoRed.animate({ opacity:0.0, duration:250 });\n $.logoWhite.animate({ opacity:1.0, duration:250 });\n\n $.helpLight.animate({ opacity:0.0, duration:250 });\n $.helpDark.animate({ opacity:1.0, duration:250 });\n}", "function animate() { \n console.log('animate')\n \n gsap.registerEffect({\n name: \"fadeIn\",\n effect: (targets, config) => {\n var tlEffect = gsap.timeline();\n tlEffect.from(targets, {duration: config.duration, y:config.y, force3D:true, rotation: 0.01, stagger:config.stagger, ease:\"power2\"})\n .from(targets, {duration: config.duration, stagger:config.stagger, alpha:0, ease:\"none\"}, \"<\")\n return tlEffect;\n },\n defaults: {duration: 1.5, y:\"-=7\", stagger:4.5},\n extendTimeline: true,\n });\n \n gsap.to(plantWraps, {duration:25, rotation:\"+=20\", ease:\"none\"})\n gsap.to(flowerWraps, {duration:25, rotation:\"+=100\", ease:\"none\"})\n \n var imageDivs = selectAll('.imageDiv');\n // logoIntro = false;\n\n\t\t\ttl\n .to(bannerCover, {duration:0.7, alpha:0, ease:\"none\"})\n \n .from(plants, {duration:3, drawSVG:\"50% 50%\", ease:\"sine.inOut\"}, \"<\")\n .from(flowers, {duration:2, alpha:0, ease:\"none\"}, \"<\")\n \n if(logoIntro) {\n tl\n .from(letter_w, {duration:0.5, drawSVG: 0, ease:\"sine.in\"}, \"<\")\n .from(letter_y, {duration:0.3, drawSVG: 0, ease:\"sine.in\"}, \">\")\n .from(letter_nn, {duration:0.8, drawSVG: 0, ease:\"sine.inOut\"}, \">\")\n .from(lasvegas, {duration:0.7, y:\"-=10\", alpha: 0, ease:\"sine\"}, \">\")\n .from(sign_r, {duration:0.5, alpha: 0, ease:\"none\"}, \"<\")\n\n .to(logo, {duration:0.7, alpha:0, ease:\"none\"}, \">1\")\n .set(logo, {scale: 0.37, y:99, x:-60}, \">\")\n } else {\n tl\n .set(logo, {scale: 0.37, alpha:0,y:99, x:-60}, \"<\")\n }\n \n tl\n .from(imageDivs, {duration:1.3, stagger:4, alpha:0, blur:10, force3D:true, rotation: 0.01, ease:\"none\"}, \"<\")\n \n .fadeIn(text_head, \"<0.4\")\n .fadeIn(text_subHead,{y:\"0\", duration: 1,},\"<0.6\")\n .to(logo, {duration:1, alpha:1, ease:\"none\"}, \"<0.4\")\n .from(cta, {duration:0.8, alpha: 0, ease:\"none\"}, \"<\")\n .from(cta, {duration:1.6, rotateX:90, ease:\"power2\"}, \"<\") \n\t\t}", "function startLoader() {\r\n\t$(\"#fe\").show();\r\n\t$(\"#fe_intro_moon\").html(\"<img src='img/hf_moon_state_0.png'><p></p>\");\r\n\tanimateLoader();\r\n}", "function loader(){\n load = setTimeout(function(){\n document.getElementById('game-level').style.visibility = 'visible';\n }, 4000); // Mudar esse tempo para a duração da Animação do logo\n}", "function lonlight ( timer )\n{\n isLoadOn = true;\n if ( typeof timer === undefined ){timer = 500;\n }\n timer = !is_numeric ( timer ) ? 500 : timer;\n $ ( '#loadIconDiv1' ).animate ( { 'opacity' : 1 } , timer ).dequeue ();\n $ ( '#loadIconDiv1' ).fadeIn ( timer ).dequeue ();\n $ ( '#hiderLayer1' ).fadeOut ( timer ).dequeue ();\n hueRotation ();\n\n}", "function randomizeIconColor(icon) {\n\n icon.frame = game.rnd.integerInRange(0, icon.animations.frameTotal - 1);\n\n}", "function loader(){\n tl\n .to(pre_loader_logo, 3, {rotation:360, ease:Power0.easeNone})\n .to([title, pre_loader_logo], 1, {opacity:0 , ease:Power1.easeInOut})\n .add('red')\n .add('blue')\n\n .to(blue, 1.2, {x: 500, ease:Power1.easeInOut, opacity:0}, 'blue')\n .to(red, 1.2, {x: -500, ease:Power1.easeInOut, opacity:0}, 'red')\n\n tl.pause();\n $('.title, #preLoaderLogo').click(function(){\n tl.play()\n setTimeout(function(){\n redirect()\n }, 5500)\n })\n }", "function preload() {\n//\n// //create an animation from a sequence of numbered images\n// //pass the first and the last file name and it will try to find the ones in between\n ghost = loadAnimation('assets/ghost_standing0001.png', 'assets/ghost_standing0007.png');\n //fire = loadAnimation('assets/fire/fire0001.png', 'assets/fire/fire0013.png');\n plant= loadAnimation('assets/plant/plant0000.png', 'assets/plant/plant0005.png');\n\n}", "function logoFade() {\n $(\"#staxx-logo\")\n .fadeIn(1600)\n .animate(\n {\n width: \"100px\",\n top: \"35px\",\n left: \"80px\"\n },\n 400\n );\n }", "function animMagitekLogo()\n{\n // wait for music to make a big hit again\n if(delay < 275)\n {\n console.log(\"Delay time: \" + delay);\n delay++;\n requestAnimationFrame(animMagitekLogo);\n }\n \n else\n {\n // draw lightning\n if(flashCounter < 10){\n console.log(\"Flash counter = \" + flashCounter);\n ctx.fillStyle = \"#FFFFFF\";\n ctx.fillRect(0,0,canvas.width,canvas.height);\n flashCounter++;\n requestAnimationFrame(animMagitekLogo);\n }\n else{\n // use the black screen for another 10 frames - for delay\n if(flashCounter < 20){\n flashCounter++;\n ctx.fillStyle = \"#000000\";\n ctx.fillRect(0,0,canvas.width,canvas.height);\n\n ctx.drawImage(clouds, 0, cloudClipY, 236, 362, 0, 0, canvas.width, canvas.height);\n\n ctx.drawImage(terraLogo, mag_x, mag_y, mag_w, mag_h);\n requestAnimationFrame(animMagitekLogo);\n }\n // after the 10 frames delay flash again\n else if(flashCounter < 30){\n console.log(\"Flash counter = \" + flashCounter);\n ctx.fillStyle = \"#FFFFFF\";\n ctx.fillRect(0,0,canvas.width,canvas.height);\n flashCounter++;\n requestAnimationFrame(animMagitekLogo);\n }\n // then go back to normal black background\n // gives it time to fill in completely\n else if(flashCounter < 40){\n flashCounter++;\n ctx.fillStyle = \"#000000\";\n ctx.fillRect(0,0,canvas.width,canvas.height);\n\n ctx.drawImage(clouds, 0, cloudClipY, 236, 362, 0, 0, canvas.width, canvas.height);\n\n ctx.drawImage(terraLogo, mag_x, mag_y, mag_w, mag_h);\n requestAnimationFrame(animMagitekLogo);\n }\n else{\n console.log(\"Finished adding terra magitek background!\");\n return false;\n }\n }\n }\n //requestAnimationFrame(animMagitekLogo);\n}", "function preload(){\r\n bg =loadImage(\"cityImage.png\");\r\n balloonImage1=loadAnimation(\"hotairballoon1.png\");\r\n balloonImage2=loadAnimation(\"hotairballoon1.png\",\"hotairballoon1.png\",\r\n \"hotairballoon1.png\",\"hotairballoon2.png\",\"hotairballoon2.png\",\r\n \"hotairballoon2.png\",\"hotairballoon3.png\",\"hotairballoon3.png\",\"hotairballoon3.png\");\r\n }", "function animateLoader() {\n var length = (ellipses.text().length + 1) % 5;\n ellipses.text(Array(length + 1).join(\".\"));\n padding.text(Array(length + 1).join('\\xA0')); //add padding to the front of the loader to keep it centred\n }", "function loadingSplash() {\n\tvar splashArray = [\n\t\t'Painting Lasers red',\n\t\t'Teaching the AI',\n\t\t'Selecting suitable Spaceship',\n\t\t\"Polishing Asteroids\",\n\t\t'Manipulating AI',\n\t\t'Failing Turing-Test',\n\t\t'Recruiting Enemy Pilots',\n\t\t'Flattening Hero Ship',\n\t\t'Reloading Minigun',\n\t\t'Refueling with unstable Plutonium',\n\t\t'Forming the Universe',\n\t\t'Catching the 671st Weedle',\n\t\t'Gathering unexploded Rockets',\n\t\t'Conquering the Universe',\n\t\t'Inviting Bosses',\n\t\t'Setting up Distress Beacon',\n\t\t'Finding Wheatley',\n\t\t'Plz don\\'t sue us WB',\n\t\t'Tuning Lasers to high C',\n\t\t'Can\\'t decide on Crosshair...',\n\t\t'Seeding Stars',\n\t\t'Inflating Shop Prices',\n\t\t'Manipulating the Leaderboard',\n\t\t'Downloading VIRUS.bat',\n\t\t'Gathering Intel',\n\t\t'Achieving Consciousness',\n\t\t'Removing easiest Difficulty',\n\t\t'Encountering Voyager',\n\t\t'Joining the Dark Side'\n\t];\n\n\t// Random number between 0 and splashArray.length - 1\n\tvar i = Math.floor(Math.random() * (splashArray.length));\n\tvar temp = document.getElementById('loadingTexturesSplash');\n\ttemp.innerHTML = splashArray[i];\n}", "function startLoadingAnimation()\n{\n\tvar dots = 0;\n\tvar animate_loading_dots = function ()\n\t{\n\t\tvar loading = \"Loading\";\n\t\tfor (var i = 0; i < dots; i++) {\n\t\t\tloading = loading + \".\";\n\t\t}\n\t\tdocument.getElementById(\"episode_name\").object.textElement.innerText = loading;\n\t\t\n\t\tif (++dots > 3) {\n\t\t\tdots = 0;\n\t\t}\n\t};\n\t\n\tloading_animation_timer = setInterval(animate_loading_dots, 500);\n}" ]
[ "0.7409085", "0.7091233", "0.69012314", "0.68325716", "0.6708544", "0.6704111", "0.66919994", "0.66762847", "0.6619367", "0.66165656", "0.65011317", "0.64985526", "0.64854777", "0.6482383", "0.64663875", "0.64638346", "0.6448776", "0.6436602", "0.634412", "0.63065964", "0.6297091", "0.62693775", "0.6261645", "0.625339", "0.6226047", "0.62206304", "0.61904913", "0.61725557", "0.6157457", "0.61515844" ]
0.7591164
0
stops logo animation :)
function stopLogo() { clearInterval(logo); $('#wave').css("display", "none"); $('#blur').css("display", "none"); $('#erase').css("display", "none"); $('#glitch1').css("display", "block"); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function stopLogoAnimation() {\n if (typeof window.showlogo_iv !== 'undefined') {\n window.ncka = window.lgss = window.lga = 1;\n clearInterval(window.showlogo_iv);\n showLogo(true);\n } else {\n setTimeout(stopLogoAnimation, 25);\n }\n }", "function hideLogo() {\n // toggle center logo\n $(\".right-side\").css({\n animation: \"scaleX-hide 1s forwards\"\n });\n $(\".left-side\").css({\n animation: \"scaleX-hide 1s forwards\"\n });\n }", "animate_stop() {\r\n this.sprite.animate = false;\r\n }", "function stopAnimation() {\n reset();\n sprite.gotoAndStop(sprite.currentFrame);\n }", "function stop() {\r\n animating = false;\r\n }", "function preloadLogoEnd() {\n loaderStop();\n}", "function stopAnimation () {\r\n on = false; // Animation abgeschaltet\r\n clearInterval(timer); // Timer deaktivieren\r\n }", "function stop_animation(mark) {\r\n win.mark.setIcon(null);\r\n win.mark.setAnimation(null);\r\n}", "function stopAnimation () {\n on = false; // Animation abgeschaltet\n clearInterval(timer); // Timer deaktivieren\n }", "function stopAnimation () {\n on = false; // Animation abgeschaltet\n clearInterval(timer); // Timer deaktivieren\n }", "function stopAnimation () {\n on = false; // Animation abgeschaltet\n clearInterval(timer); // Timer deaktivieren\n }", "stop() {\n this._enableAnimation = false;\n }", "function stopAnimation(e) {\n // use the requestID to cancel the requestAnimationFrame call\n if (/Android/.test(navigator.userAgent)) {\n context.clearRect(0, 0, 300, 60);\n context.drawImage(fntA.iconPower,400,400,23,30);\n }\n cancelRAF(fntA.requestId);\n }", "function preloadLogoEnd() {\n\n}", "stopAnimation() {\r\n this.anims.stop();\r\n\r\n //Stop walk sound\r\n this.walk.stop();\r\n }", "stop() {\n this.renderer.setAnimationLoop(null);\n }", "stopDrawing() {\n this.updateAnimation = false;\n }", "function animateLogo() {\n let random;\n random = Math.floor((Math.random() * 3)+ 1);\n $('#wave').css(\"animation\", \"glitch\" + random + \" 2s ease infinite\");\n setTimeout(function(){ random = Math.floor((Math.random() * 3)+ 1); $('#erase').css(\"animation\", \"glitch\" + random + \" 2s ease infinite\");\n setTimeout(function(){ random = Math.floor((Math.random() * 3)+ 1); $('#blur').css(\"animation\", \"glitch\" + random + \" 2s ease infinite\");\n }, 40);}, 40);\n}", "function stopSpinning() {\n\tlargeImage.style.transform = \"none\";\n}", "function stopAnimation(){\r\n for(var i=0; i<self.markerArray().length; i++){\r\n self.markerArray()[i][1].setAnimation(null);\r\n\tself.markerArray()[i][1].setIcon(defaultIcon);\r\n }\r\n}", "function animateLogo()\n{\n if (logoPhase > 7)\n {\n setDutyCycle(2, 10);\n return;\n }\n else if (logoPhase > 6)\n {\n showBitwigLogo = false;\n var i = 0.5 - 0.5 * Math.cos(logoPhase * Math.PI);\n setDutyCycle(Math.floor(1 + 5 * i), 18);\n }\n else\n {\n var i = 0.5 - 0.5 * Math.cos(logoPhase * Math.PI);\n setDutyCycle(Math.floor(1 + 15 * i), 18);\n }\n\n logoPhase += 0.2;\n\n host.scheduleTask(animateLogo, null, 30);\n}", "stop(){this.__stopped=!1;this.toggleAnimation()}", "splashBottle() {\n clearInterval(this.gravitation);\n clearInterval(this.the_throw); \n this.playAnimation(this.IMAGES_SPLASH);\n this.splash_sound.play();\n setInterval(() => {\n this.width = 0;\n this.height = 0;\n }, 200);\n }", "function setEndAnimation() {\r\n\t\t\tinAnimation = false;\r\n\t\t}", "function stop() {\n\n\t\ttry {\n\t\t // Pass in the movement to the game.\n\t\t animation.move(\"x\", moveTypes.none);\n\t\t}\n\t\tcatch (err) {\n\t\t\tconsole.log(err);\n\t\t}\n\t}", "function stop_dog_poop() {\n cancelAnimationFrame(anim_id);\n $('#restart').slideDown();\n }", "function removeLogo() {\n if (!canvasClicked) {\n var bg = $(\"canvas\").css(\"background-image\");\n var bgs = bg.split(',');\n bgs.splice(0, 1);\n $(\"canvas\").css(\"background-image\", bgs.concat());\n $(\"canvas\").css(\"background-repeat\", \"repeat\");\n canvasClicked = true;\n }\n }", "function animateLogo () {\n\t\tvar repeatVisitFlag = IBM.common.util.storage.getItem(\"v18larv\");\n\t\t\n\t\t// Allow animation to be forced to show via URL param (for debugging, presentations, show-and-tell, etc).\n\t\tif (IBM.common.util.url.getParam(\"animatelogo\")) {\n\t\t\t$(\"#ibm-home\").addClass(\"ibm-animate\");\n\t\t}\n\n\t\tif (!IBM.common.util.config.isEnabled(\"masthead.logoanimation\")) {\n\t\t\treturn;\n\t\t}\n\n\t\t// If they didn't have the flag AND they support localstorage, animate it.\n\t\tif (!repeatVisitFlag && IBM.common.util.storage.setItem(\"v18larv\", true)) {\n\t\t\t$(\"#ibm-home\").addClass(\"ibm-animate\");\n\t\t}\n\t}", "function stopanimate() {\r\n window.cancelAnimationFrame(request)\r\n }", "fadeOut() {\n const tween = this.add.tween(this.logo).to(\n { y: 800 }, 2000, Phaser.Easing.Linear.None, true\n );\n\n this.add.tween(this.background).to(\n { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true\n );\n\n tween.onComplete.add(this.startGame, this);\n }" ]
[ "0.86108387", "0.7080638", "0.70496047", "0.70471853", "0.6957593", "0.6907867", "0.6819871", "0.6818485", "0.67659694", "0.67659694", "0.67659694", "0.67310756", "0.67289686", "0.6680569", "0.6631503", "0.6617334", "0.65762746", "0.6566484", "0.6548353", "0.65399414", "0.6538984", "0.6529964", "0.65255606", "0.65247136", "0.6501823", "0.64896405", "0.6485588", "0.6452839", "0.640118", "0.6395768" ]
0.8123087
1
animates toggling the featured video
function toggleVideo() { if($('#featured').hasClass('toggled')) { $('#form-overlay-wrapper').animate({maxHeight: 0}, 500); $('#link-form').animate({opacity: 0}, 200); $('#featured').css('animation', 'toggleFeaturedOn 1s ease forwards'); $('#main-title-wrapper').animate({maxHeight: 0}, 500); $('#main-title').animate({opacity: 0}, 200); setTimeout(function() { $('#featured').css('max-height', 'inherit'); $('#featured').css('opacity', '1'); $('#featured').css('margin-bottom', '20px'); setTimeout(function() { $('#featured').css("animation", "none"); }, 50); }, 1000); $('#featured').removeClass('toggled'); } else { $('#form-overlay-wrapper').animate({maxHeight: 200}, 500); $('#link-form').animate({opacity: 1}, 500); $('#featured').css('animation', 'toggleFeaturedOff 1s ease forwards'); $('#main-title-wrapper').animate({maxHeight: "200px"}, 500); setTimeout(function() { $('#main-title').animate({opacity: 1}, 500); }, 300); setTimeout(function() { $('#featured').css("animation", "none"); $('#featured').css('max-height', '0'); $('#featured').css('opacity', '0'); $('#featured').css('margin-bottom', '0'); }, 1000); $('#featured').addClass('toggled'); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "toggle () {\n if (this.video.paused) {\n this.play();\n }\n else {\n this.pause();\n }\n }", "function toggle() {\n var trailer = document.querySelector('#onetra');\n var video = document.querySelector('video');\n onetra.classList.toggle('active')\n video.currentTime = 0;\n video.pause();\n}", "function showHide() {\n menuVideo.classList.toggle('is-active')\n}", "function videoStateToggle(e, animate) {\n var $video = $(this);\n var $state = $video.closest('[data-state-name]');\n var state = $state.data('state-name');\n\n // Set body state.\n if (state) $body.attr('data-state-name', e.type == 'in' ? state : '');\n\n // Toggle element class state.\n $video.toggleClass('no-animate', animate == false);\n $video.toggleClass('active', e.type == 'in');\n }", "function toggleVideoState() {\n if (video.paused) {\n video.play();\n } else {\n video.pause();\n }\n\n }", "function toggleVideoStatus(){\n if(video.paused){\n video.play();\n }else {\n video.pause();\n }\n}", "function toggleVideoStatus() {\n if (video.paused) {\n video.play();\n } else {\n video.pause();\n }\n}", "toggleVideo() {\n var self = this;\n\n if (self.get('isPlaying')) {\n self.get('Player').pauseVideo();\n self.set('isPlaying', false);\n\n self.get('$progressBar').stop();\n Ember.run.cancel(self.vidClock);\n } else {\n self.get('Player').playVideo();\n self.set('isPlaying', true);\n }\n }", "function PlayExpandedIntroVideo () {\r\ncreative.dom.video1.vid.play();\r\ncreative.dom.video1.vid.currentTime = 0;\r\n}", "function toggleVid() {\n if (playing) {\n earring.pause();\n button.html('play');\n } else {\n earring.loop();\n button.html('pause');\n }\n playing = !playing;\n}", "function showVideo(){\r\n\t\t\tvar iframe=document.getElementById('iframe');\r\n\r\n\t\t\tthevid.style.display='block'; \r\n\t\t\tdocument.getElementById('iframe').src = \r\n\t\t\tdocument.getElementById('iframe').src.replace('autoplay=0','autoplay=1');\r\n\t\t\t$('div.logo-wrap').replaceWith($('div.video-wrap'));\r\n\t\t\tTweenLite.to($('div.video-wrap'), 2, {opacity:1, ease:Power1.easeIn});\r\n\t\t}", "function toggleSticker(){\n var sticker = $(this);\n\n if(sticker.attr(\"src-animated\") === sticker.attr(\"src\")){\n sticker.attr(\"src\",sticker.attr(\"src-original\"));\n }\n else{\n sticker.attr(\"src\",sticker.attr(\"src-animated\"));\n }\n}", "function toggleVideo() {\n myStreamRef.current.getVideoTracks()[0].enabled = !videoState\n setVideoState(prev => { return !prev })\n }", "toggleTutorial() {\n if(this.wonGameStatus == false) {\n document.getElementById(\"dark-bg\").classList.toggle(\"d-none\");\n }\n }", "function toggleVideoAdd(value) {\n if (value) {\n $('#section-add-videos').removeClass('hidden-xs-up');\n $('#button-done-videos').removeClass('hidden-xs-up');\n $('#button-add-videos').addClass('hidden-xs-up');\n } else {\n $('#section-add-videos').addClass('hidden-xs-up');\n $('#button-done-videos').addClass('hidden-xs-up');\n $('#button-add-videos').removeClass('hidden-xs-up');\n }\n}", "function toggleVid() {\n if (playing) {\n myVideo.pause();\n button.html('play');\n } else {\n myVideo.loop();\n button.html('pause');\n }\n playing = !playing;\n}", "function action_toggle_play() {\n if (video.paused) {\n video.play();\n change_icon('play'); \n } else {\n video.pause();\n change_icon('pause'); \n }\n delay = delay_value;\n}", "function toggleVideo(b) {\n if (b == \"true\") {\n localStream.getVideoTracks()[0].enabled = true\n } else {\n localStream.getVideoTracks()[0].enabled = false\n }\n}", "function playGiphy() {\n var still = $(this).attr('data-still');\n var animated = $(this).attr('data-animated');\n var state = $(this).attr('data-state');\n\n if (state === 'still') {\n // Play Image\n $(this).attr({\n 'data-state': 'play',\n src: animated\n });\n } else {\n // Pause image\n $(this).attr({\n 'data-state': 'still',\n src: still\n });\n }\n}", "function togglePlay() {\n var theSVG = this.firstElementChild;\n poster.classList.add('hide');\n videoControls.classList.remove('invisible');\n vidPlayer.classList.remove('hide');\n\n if (vidPlayer.paused) {\n theSVG.dataset.icon = \"pause-circle\";\n vidPlayer.play();\n } else {\n theSVG.dataset.icon = \"play-circle\";\n vidPlayer.pause();\n }\n }", "function ifVideoTogglePlay() {\n if (video.paused || video.ended) {\n video.play();\n videoContainer.classList.add('is-active');\n videoContainer.classList.remove('is-paused');\n } else {\n video.pause();\n videoContainer.classList.remove('is-active');\n videoContainer.classList.add('is-paused');\n }\n }", "function doShowAdvLinkFast() \n {\n if($('#oc-link-advanced-player').is(':animated')) {\n $('#oc-link-advanced-player').stop();\n }\n $('#oc-link-advanced-player').css('marginLeft', '0px');\n }", "function showDetails(id){\n $('#videoplayer').attr('src', 'http://player.vimeo.com/video/' + id);\n $('#videodetail').toggleClass('showview');\n $('#main').toggleClass('showview');\n}", "function setVideo(e, value) {\n myMediaStream.getVideoTracks()[0].enabled = !myMediaStream.getVideoTracks()[0].enabled;\n myVideoStatus = myMediaStream.getVideoTracks()[0].enabled;\n e.target.className = \"fas fa-video\" + (myVideoStatus ? \"\" : \"-slash\");\n if (value) {\n videoBtn.className = \"fas fa-video\" + (myVideoStatus ? \"\" : \"-slash\");\n tippy(startVideoBtn, { content: myVideoStatus ? \"Off\" : \"On\", placement: \"top\", });\n }\n setMyVideoStatus(myVideoStatus);\n}", "function playvideo(event){\n var addanimation=document.querySelector(\".\"+event);\n addanimation.classList.add(\"pressed\");\n setTimeout(function(){\n addanimation.classList.remove(\"pressed\")\n },100);\n\n}", "function toggleGif() {\n console.log(\"toggleGif\");\n if ($(this).data('active')) {\n $(this).data('active', false);\n $(this).css('background-image', 'url(' +$(this).data(\"still\") + ')');\n } else {\n $(this).data('active', true);\n $(this).css('background-image', 'url(' +$(this).data(\"animated\") + ')');\n }\n }", "function togglePlay() {\n video.paused ? video.play() : video.pause();\n}", "function toggleVideoStatus() {\n if (video.paused) {\n video.play();\n } else {\n video.pause();\n }\n if (dropdown.classList.contains('dropdown-visible')) {\n showDropdown();\n }\n}", "function playYtVideo() {\n player.playVideo();\n if (this.classList.value === playFaClass) {\n $('.playButton').tooltip('hide')\n $('.playButton').removeClass(playFaClass).toggleClass(pauseFaClass);\n $(this).attr('data-original-title','Pause')\n } else {\n $('.pauseButton').tooltip('hide');\n $('.pauseButton').removeClass(pauseFaClass).toggleClass(playFaClass);\n $(this).attr('data-original-title','Play')\n player.pauseVideo()\n }\n }", "function videosSection() {\n // alert(\"videos clicked\");\n $(\"#videos\").addClass(\"actively_selected\");\n $(\"#solo_images, #effects, #all_panel\").removeClass(\"actively_selected\").slideUp();\n $(\".actively_selected\").slideDown();\n}" ]
[ "0.6483139", "0.6390514", "0.6388819", "0.63766366", "0.63230723", "0.6285341", "0.6250968", "0.62208354", "0.62047714", "0.6186793", "0.6175213", "0.61472607", "0.61271334", "0.6116968", "0.61030436", "0.60870284", "0.6034762", "0.60342544", "0.6033538", "0.6010624", "0.600664", "0.5990795", "0.5978109", "0.59750396", "0.5952756", "0.59456676", "0.5940139", "0.593725", "0.59303576", "0.5928442" ]
0.7665488
0
If a resolver is defined, it must be a function.
function isValidResolver(resolver) { return resolver == null || typeof resolver === 'function'; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function resolve(value) {\n\t\t\treturn typeof value === 'function' ? value() : value;\n\t\t}", "function isTypeResolver(\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfn) {\n // 1. A type provider must be a function\n if (typeof fn !== 'function')\n return false;\n // 2. A class constructor is not a type provider\n if (/^class/.test(fn.toString()))\n return false;\n // 3. Built-in types like Date & Array are not type providers\n if (isBuiltinType(fn))\n return false;\n // TODO(bajtos): support model classes defined via ES5 constructor function\n return true;\n}", "function getResolver({ operation, argsFromLink = {}, payloadName, data, baseUrl, requestOptions }) {\n // Determine the appropriate URL:\n if (typeof baseUrl === 'undefined') {\n baseUrl = Oas3Tools.getBaseUrl(operation);\n }\n // Return custom resolver if it is defined\n const customResolvers = data.options.customResolvers;\n const title = operation.oas.info.title;\n const path = operation.path;\n const method = operation.method;\n if (typeof customResolvers === 'object' &&\n typeof customResolvers[title] === 'object' &&\n typeof customResolvers[title][path] === 'object' &&\n typeof customResolvers[title][path][method] === 'function') {\n translationLog(`Use custom resolver for ${operation.operationString}`);\n return customResolvers[title][path][method];\n }\n // Return resolve function:\n return (root, args, ctx, info = {}) => {\n /**\n * Retch resolveData from possibly existing _openapiToGraphql\n *\n * NOTE: _openapiToGraphql is an object used to pass security info and data\n * from previous resolvers\n */\n let resolveData = {};\n if (root &&\n typeof root === 'object' &&\n typeof root['_openapiToGraphql'] === 'object' &&\n typeof root['_openapiToGraphql'].data === 'object') {\n const parentIdentifier = getParentIdentifier(info);\n if (!(parentIdentifier.length === 0) &&\n parentIdentifier in root['_openapiToGraphql'].data) {\n /**\n * Resolving link params may change the usedParams, but these changes\n * should not be present in the parent _openapiToGraphql, therefore copy\n * the object\n */\n resolveData = JSON.parse(JSON.stringify(root['_openapiToGraphql'].data[parentIdentifier]));\n }\n }\n if (typeof resolveData.usedParams === 'undefined') {\n resolveData.usedParams = {};\n }\n /**\n * Handle default values of parameters, if they have not yet been defined by\n * the user.\n */\n operation.parameters.forEach(param => {\n const paramName = Oas3Tools.sanitize(param.name, Oas3Tools.CaseStyle.camelCase);\n if (typeof args[paramName] === 'undefined' &&\n param.schema &&\n typeof param.schema === 'object') {\n let schema = param.schema;\n if (schema && schema.$ref && typeof schema.$ref === 'string') {\n schema = Oas3Tools.resolveRef(schema.$ref, operation.oas);\n }\n if (schema &&\n schema.default &&\n typeof schema.default !== 'undefined') {\n args[paramName] = schema.default;\n }\n }\n });\n // Handle arguments provided by links\n for (let paramName in argsFromLink) {\n let value = argsFromLink[paramName];\n let paramNameWithoutLocation = paramName;\n if (paramName.indexOf('.') !== -1) {\n paramNameWithoutLocation = paramName.split('.')[1];\n }\n /**\n * see if the link parameter contains constants that are appended to the link parameter\n *\n * e.g. instead of:\n * $response.body#/employerId\n *\n * it could be:\n * abc_{$response.body#/employerId}\n */\n if (value.search(/{|}/) === -1) {\n args[paramNameWithoutLocation] = isRuntimeExpression(value)\n ? resolveLinkParameter(paramName, value, resolveData, root, args)\n : value;\n }\n else {\n // Replace link parameters with appropriate values\n const linkParams = value.match(/{([^}]*)}/g);\n linkParams.forEach(linkParam => {\n value = value.replace(linkParam, resolveLinkParameter(paramName, linkParam.substring(1, linkParam.length - 1), resolveData, root, args));\n });\n args[paramNameWithoutLocation] = value;\n }\n }\n // Stored used parameters to future requests:\n resolveData.usedParams = Object.assign(resolveData.usedParams, args);\n // Build URL (i.e., fill in path parameters):\n const { path, query, headers } = Oas3Tools.instantiatePathAndGetQuery(operation.path, operation.parameters, args);\n const url = baseUrl + path;\n /**\n * The Content-type and accept property should not be changed because the\n * object type has already been created and unlike these properties, it\n * cannot be easily changed\n *\n * NOTE: This may cause the user to encounter unexpected changes\n */\n headers['content-type'] =\n typeof operation.payloadContentType !== 'undefined'\n ? operation.payloadContentType\n : 'application/json';\n headers['accept'] =\n typeof operation.responseContentType !== 'undefined'\n ? operation.responseContentType\n : 'application/json';\n let options = {\n url,\n method: operation.method\n };\n if (requestOptions) {\n options = Object.assign(Object.assign({}, options), requestOptions);\n if (requestOptions.headers) {\n if (typeof requestOptions.headers === 'object') {\n Object.assign(requestOptions.headers, headers);\n }\n else if (typeof requestOptions.headers === 'function') {\n options.headers = requestOptions.headers({\n context: ctx,\n method,\n path,\n title\n });\n }\n }\n else {\n options['headers'] = headers;\n }\n if (options.qs) {\n Object.assign(options.qs, query);\n }\n else {\n options['qs'] = query;\n }\n }\n else {\n options = {\n method: operation.method,\n url: url,\n headers: headers,\n qs: query\n };\n }\n /**\n * Determine possible payload\n *\n * GraphQL produces sanitized payload names, so we have to sanitize before\n * lookup here\n */\n resolveData.usedPayload = undefined;\n if (payloadName && typeof payloadName === 'string') {\n const sanePayloadName = Oas3Tools.sanitize(payloadName, Oas3Tools.CaseStyle.camelCase);\n if (sanePayloadName in args) {\n if (typeof args[sanePayloadName] === 'object') {\n // We need to desanitize the payload so the API understands it:\n const rawPayload = JSON.stringify(Oas3Tools.desanitizeObjKeys(args[sanePayloadName], data.saneMap));\n options.body = rawPayload;\n resolveData.usedPayload = rawPayload;\n }\n else {\n // Payload is not an object (stored as an application/json)\n const rawPayload = args[sanePayloadName];\n options.body = rawPayload;\n resolveData.usedPayload = rawPayload;\n }\n }\n }\n /**\n * Pass on OpenAPI-to-GraphQL options\n */\n if (typeof data.options === 'object') {\n // Headers:\n if (typeof data.options.headers === 'object' &&\n (!requestOptions || !requestOptions.headers)) {\n for (let header in data.options.headers) {\n const val = data.options.headers[header];\n options.headers[header] = val;\n }\n }\n // Query string:\n if (typeof data.options.qs === 'object') {\n for (let query in data.options.qs) {\n const val = data.options.qs[query];\n options.qs[query] = val;\n }\n }\n }\n // Get authentication headers and query parameters\n if (root &&\n typeof root === 'object' &&\n typeof root['_openapiToGraphql'] == 'object') {\n const { authHeaders, authQs, authCookie } = getAuthOptions(operation, root['_openapiToGraphql'], data);\n // ...and pass them to the options\n Object.assign(options.headers, authHeaders);\n Object.assign(options.qs, authQs);\n // Add authentication cookie if created\n if (authCookie !== null) {\n const j = NodeRequest.jar();\n j.setCookie(authCookie, options.url);\n options.jar = j;\n }\n }\n // Extract OAuth token from context (if available)\n if (data.options.sendOAuthTokenInQuery) {\n const oauthQueryObj = createOAuthQS(data, ctx);\n Object.assign(options.qs, oauthQueryObj);\n }\n else {\n const oauthHeader = createOAuthHeader(data, ctx);\n Object.assign(options.headers, oauthHeader);\n }\n resolveData.usedRequestOptions = options;\n resolveData.usedStatusCode = operation.statusCode;\n // Make the call\n httpLog(`Call ${options.method.toUpperCase()} ${options.url}?${querystring.stringify(options.qs)}\\n` +\n `headers:${JSON.stringify(options.headers)}`);\n return new Promise((resolve, reject) => {\n NodeRequest(options, (err, response, body) => {\n if (err) {\n httpLog(err);\n reject(err);\n }\n else if (response.statusCode < 200 || response.statusCode > 299) {\n httpLog(`${response.statusCode} - ${Oas3Tools.trim(body, 100)}`);\n const errorString = `Could not invoke operation ${operation.operationString}`;\n if (data.options.provideErrorExtensions) {\n let responseBody;\n try {\n responseBody = JSON.parse(body);\n }\n catch (e) {\n responseBody = body;\n }\n const extensions = {\n method: operation.method,\n path: operation.path,\n statusCode: response.statusCode,\n responseHeaders: response.headers,\n responseBody\n };\n reject(graphQLErrorWithExtensions(errorString, extensions));\n }\n else {\n reject(new Error(errorString));\n }\n // Successful response 200-299\n }\n else {\n httpLog(`${response.statusCode} - ${Oas3Tools.trim(body, 100)}`);\n if (response.headers['content-type']) {\n /**\n * Throw warning if the non-application/json content does not\n * match the OAS.\n *\n * Use an inclusion test in case of charset\n *\n * i.e. text/plain; charset=utf-8\n */\n if (!(response.headers['content-type'].includes(operation.responseContentType) ||\n operation.responseContentType.includes(response.headers['content-type']))) {\n const errorString = `Operation ` +\n `${operation.operationString} ` +\n `should have a content-type '${operation.responseContentType}' ` +\n `but has '${response.headers['content-type']}' instead`;\n httpLog(errorString);\n reject(errorString);\n }\n else {\n /**\n * If the response body is type JSON, then parse it\n *\n * content-type may not be necessarily 'application/json' it can be\n * 'application/json; charset=utf-8' for example\n */\n if (response.headers['content-type'].includes('application/json')) {\n let responseBody;\n try {\n responseBody = JSON.parse(body);\n }\n catch (e) {\n const errorString = `Cannot JSON parse response body of ` +\n `operation ${operation.operationString} ` +\n `even though it has content-type 'application/json'`;\n httpLog(errorString);\n reject(errorString);\n }\n resolveData.responseHeaders = response.headers;\n // Deal with the fact that the server might send unsanitized data\n let saneData = Oas3Tools.sanitizeObjKeys(responseBody);\n // Pass on _openapiToGraphql to subsequent resolvers\n if (saneData && typeof saneData === 'object') {\n if (Array.isArray(saneData)) {\n saneData.forEach(element => {\n if (typeof element['_openapiToGraphql'] === 'undefined') {\n element['_openapiToGraphql'] = {\n data: {}\n };\n }\n if (root &&\n typeof root === 'object' &&\n typeof root['_openapiToGraphql'] == 'object') {\n Object.assign(element['_openapiToGraphql'], root['_openapiToGraphql']);\n }\n element['_openapiToGraphql'].data[getIdentifier(info)] = resolveData;\n });\n }\n else {\n if (typeof saneData['_openapiToGraphql'] === 'undefined') {\n saneData['_openapiToGraphql'] = {\n data: {}\n };\n }\n if (root &&\n typeof root === 'object' &&\n typeof root['_openapiToGraphql'] == 'object') {\n Object.assign(saneData['_openapiToGraphql'], root['_openapiToGraphql']);\n }\n saneData['_openapiToGraphql'].data[getIdentifier(info)] = resolveData;\n }\n }\n // Apply limit argument\n if (data.options.addLimitArgument &&\n /**\n * NOTE: Does not differentiate between autogenerated args and\n * preexisting args\n *\n * Ensure that there is not preexisting 'limit' argument\n */\n !operation.parameters.find(parameter => {\n return parameter.name === 'limit';\n }) &&\n // Only array data\n Array.isArray(saneData) &&\n // Only array of objects/arrays\n saneData.some(data => {\n return typeof data === 'object';\n })) {\n let arraySaneData = saneData;\n if ('limit' in args) {\n const limit = args['limit'];\n if (limit >= 0) {\n arraySaneData = arraySaneData.slice(0, limit);\n }\n else {\n reject(new Error(`Auto-generated 'limit' argument must be greater than or equal to 0`));\n }\n }\n else {\n reject(new Error(`Cannot get value for auto-generated 'limit' argument`));\n }\n saneData = arraySaneData;\n }\n resolve(saneData);\n }\n else {\n // TODO: Handle YAML\n resolve(body);\n }\n }\n }\n else {\n /**\n * Check to see if there is not supposed to be a response body,\n * if that is the case, that would explain why there is not\n * a content-type\n */\n const { responseContentType } = Oas3Tools.getResponseObject(operation, operation.statusCode, operation.oas);\n if (responseContentType === null) {\n resolve(null);\n }\n else {\n const errorString = 'Response does not have a Content-Type property';\n httpLog(errorString);\n reject(errorString);\n }\n }\n }\n });\n });\n };\n}", "callback(value) {\n return this.registerResolver(3\n /* callback */\n , value);\n }", "resolveUser() {\n if (this.user) {\n return;\n }\n if (typeof this.userOrResolver === 'function') {\n this.user = this.userOrResolver();\n }\n else {\n this.user = this.userOrResolver;\n }\n }", "function resolver (value, resolve) {\n\t\tresolved[resolved.length] = value;\n\n\t\tif (resolved.length === deps.length) {\n\t\t\tresolve(resolved);\n\t\t}\n\t}", "function checkForResolveTypeResolver(schema, requireResolversForResolveType) {\n Object.keys(schema.getTypeMap())\n .map(function (typeName) { return schema.getType(typeName); })\n .forEach(function (type) {\n if (!(type instanceof graphql_1.GraphQLUnionType ||\n type instanceof graphql_1.GraphQLInterfaceType)) {\n return;\n }\n if (!type.resolveType) {\n if (requireResolversForResolveType === false) {\n return;\n }\n if (requireResolversForResolveType === true) {\n throw new _1.SchemaError(\"Type \\\"\" + type.name + \"\\\" is missing a \\\"resolveType\\\" resolver\");\n }\n // tslint:disable-next-line:max-line-length\n console.warn(\"Type \\\"\" + type.name + \"\\\" is missing a \\\"__resolveType\\\" resolver. Pass false into \" +\n \"\\\"resolverValidationOptions.requireResolversForResolveType\\\" to disable this warning.\");\n }\n });\n}", "function resolveAndExecute(source, event, func) {\n if (\"string\" != typeof func) {\n //function is passed down as chain parameter, can be executed as is\n return func.call(source, event) !== false;\n }\n else {\n //either a function or a string can be passed in case of a string we have to wrap it into another function\n //it is not a plain executable code but a definition\n let sourceCode = trim(func);\n if (sourceCode.indexOf(\"function \") == 0) {\n sourceCode = `return ${sourceCode} (event)`;\n }\n return new Function(\"event\", sourceCode).call(source, event) !== false;\n }\n }", "function r(e){return\"function\"===typeof e}", "function r(e){return\"function\"===typeof e}", "function isFn (x) { return typeof x === 'function' }", "function createResolver({ resolve, reject, multiArgs }) {\n return (err, ...values) => {\n if (err) {\n err = ensureIsError(err); // if it's primitive, make in an Error\n \n if (err instanceof Error && Object.getPrototypeOf(err) === Error.prototype) {\n // if it's a base Error (not a custom error), make it an OperationalError\n err = Bluebird.OperationalError.fromError(ensureIsError(err));\n }\n\n reject(err);\n }\n else if (multiArgs) {\n resolve(Bluebird.all(values))\n }\n else {\n resolve(values[0]);\n }\n }\n }", "function r(e,t){if(\"function\"!=typeof e)throw new TypeError(\"argument fn must be a function\");return e}", "function r(e,t){if(\"function\"!=typeof e)throw new TypeError(\"argument fn must be a function\");return e}", "is_function(value) {\n return typeof(value) === 'function';\n }", "ensureResolver() {\n if (!this.resolver) {\n throw new Error('IoC container resolver is required to register string based hooks handlers');\n }\n }", "function wrapResolver(innerResolver, outerResolver) {\n return function (obj, args, ctx, info) {\n return Promise.resolve(outerResolver(obj, args, ctx, info)).then(function (root) {\n if (innerResolver) {\n return innerResolver(root, args, ctx, info);\n }\n return graphql_1.defaultFieldResolver(root, args, ctx, info);\n });\n };\n}", "function executarQualquerCoisa(fn) {\n if (typeof fn === 'function') {\n fn();\n }\n}", "bindResolver() {\n\t\tthis.app.singleton('db.resolver', Resolver);\n\t}", "function defaultResolveFn(source, args, context, info) {\n var fieldName = info.fieldName;\n // ensure source is a value for which property access is acceptable.\n if (typeof source === 'object' || typeof source === 'function') {\n return typeof source[fieldName] === 'function'\n ? source[fieldName]()\n : source[fieldName];\n }\n}", "function _ensureFunction(f) {\n if (!f || typeof f !== 'function')\n throw new Error('the argument needs to be a function!');\n }", "function checkFunction(fn) {\n return typeof fn === 'function';\n }", "__is_function(variable) {\n\n return typeof variable == \"function\"\n }", "function resolve(value, ctx) {\n return type_3.isFunction(value) ? value(ctx) : value;\n }", "_checkValue(value) {\n if (!_.isFunction(value)) {\n throw new Error('functionsDict._checkValue: must provide only Function as values.');\n }\n }", "function isFunction(value) { return typeof value === \"function\" || value instanceof Function; }", "function isFunc(cf) {\r\n return typeof cf === \"function\";\r\n}", "function wireResolver(resolver, _, __, wire) {\n\t\tresolver.resolve(wire.createChild);\n\t}", "function resolveCall(callee) {\n\t callee = callee.resolve();\n\n\t if (callee.isFunction()) {\n\t if (callee.is(\"async\")) {\n\t if (callee.is(\"generator\")) {\n\t return t.genericTypeAnnotation(t.identifier(\"AsyncIterator\"));\n\t } else {\n\t return t.genericTypeAnnotation(t.identifier(\"Promise\"));\n\t }\n\t } else {\n\t if (callee.node.returnType) {\n\t return callee.node.returnType;\n\t } else {\n\t // todo: get union type of all return arguments\n\t }\n\t }\n\t }\n\t}", "function resolveCall(callee) {\n\t callee = callee.resolve();\n\n\t if (callee.isFunction()) {\n\t if (callee.is(\"async\")) {\n\t if (callee.is(\"generator\")) {\n\t return t.genericTypeAnnotation(t.identifier(\"AsyncIterator\"));\n\t } else {\n\t return t.genericTypeAnnotation(t.identifier(\"Promise\"));\n\t }\n\t } else {\n\t if (callee.node.returnType) {\n\t return callee.node.returnType;\n\t } else {\n\t // todo: get union type of all return arguments\n\t }\n\t }\n\t }\n\t}" ]
[ "0.60108536", "0.5983928", "0.57119197", "0.556918", "0.5547538", "0.55399346", "0.55316556", "0.54889995", "0.5416304", "0.5416304", "0.54119635", "0.5396087", "0.53853196", "0.53853196", "0.53354096", "0.5296625", "0.5274366", "0.52573806", "0.5207318", "0.5182532", "0.51794654", "0.51766306", "0.5174054", "0.51638067", "0.51121503", "0.5108614", "0.510388", "0.50920916", "0.50789565", "0.50789565" ]
0.78889376
1
Returns an operation AST given a document AST and optionally an operation name. If a name is not provided, an operation is only returned if only one is provided in the document.
function getOperationAST(documentAST, operationName) { var operation = null; for (var i = 0; i < documentAST.definitions.length; i++) { var definition = documentAST.definitions[i]; if (definition.kind === _kinds.OPERATION_DEFINITION) { if (!operationName) { // If no operation name was provided, only return an Operation if there // is one defined in the document. Upon encountering the second, return // null. if (operation) { return null; } operation = definition; } else if (definition.name && definition.name.value === operationName) { return definition; } } } return operation; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getOperationAST(documentAST, operationName) {\n var operation = null;\n\n for (var i = 0; i < documentAST.definitions.length; i++) {\n var definition = documentAST.definitions[i];\n\n if (definition.kind === _language_kinds__WEBPACK_IMPORTED_MODULE_0__[\"Kind\"].OPERATION_DEFINITION) {\n if (!operationName) {\n // If no operation name was provided, only return an Operation if there\n // is one defined in the document. Upon encountering the second, return\n // null.\n if (operation) {\n return null;\n }\n\n operation = definition;\n } else if (definition.name && definition.name.value === operationName) {\n return definition;\n }\n }\n }\n\n return operation;\n}", "function getOperationAST(documentAST, operationName) {\n var operation = null;\n\n for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) {\n var definition = _documentAST$definiti2[_i2];\n\n if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) {\n var _definition$name;\n\n if (operationName == null) {\n // If no operation name was provided, only return an Operation if there\n // is one defined in the document. Upon encountering the second, return\n // null.\n if (operation) {\n return null;\n }\n\n operation = definition;\n } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) {\n return definition;\n }\n }\n }\n\n return operation;\n}", "function getOperationAST(documentAST, operationName) {\n var operation = null;\n\n for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) {\n var definition = _documentAST$definiti2[_i2];\n\n if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) {\n var _definition$name;\n\n if (operationName == null) {\n // If no operation name was provided, only return an Operation if there\n // is one defined in the document. Upon encountering the second, return\n // null.\n if (operation) {\n return null;\n }\n\n operation = definition;\n } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) {\n return definition;\n }\n }\n }\n\n return operation;\n}", "function getOperationAST(documentAST, operationName) {\n var operation = null;\n\n for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) {\n var definition = _documentAST$definiti2[_i2];\n\n if (definition.kind === _language_kinds_mjs__WEBPACK_IMPORTED_MODULE_0__[\"Kind\"].OPERATION_DEFINITION) {\n var _definition$name;\n\n if (operationName == null) {\n // If no operation name was provided, only return an Operation if there\n // is one defined in the document. Upon encountering the second, return\n // null.\n if (operation) {\n return null;\n }\n\n operation = definition;\n } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) {\n return definition;\n }\n }\n }\n\n return operation;\n}", "function getOperationAST(documentAST, operationName) {\n var operation = null;\n\n for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) {\n var definition = _documentAST$definiti2[_i2];\n\n if (definition.kind === _language_kinds_mjs__WEBPACK_IMPORTED_MODULE_0__[\"Kind\"].OPERATION_DEFINITION) {\n var _definition$name;\n\n if (operationName == null) {\n // If no operation name was provided, only return an Operation if there\n // is one defined in the document. Upon encountering the second, return\n // null.\n if (operation) {\n return null;\n }\n\n operation = definition;\n } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) {\n return definition;\n }\n }\n }\n\n return operation;\n}", "function getOperationAST(documentAST, operationName) {\n\t var operation = null;\n\t for (var i = 0; i < documentAST.definitions.length; i++) {\n\t var definition = documentAST.definitions[i];\n\t if (definition.kind === _kinds.OPERATION_DEFINITION) {\n\t if (!operationName) {\n\t // If no operation name was provided, only return an Operation if there\n\t // is one defined in the document. Upon encountering the second, return\n\t // null.\n\t if (operation) {\n\t return null;\n\t }\n\t operation = definition;\n\t } else if (definition.name && definition.name.value === operationName) {\n\t return definition;\n\t }\n\t }\n\t }\n\t return operation;\n\t}", "function getOperationAST(documentAST, operationName) {\n var operation = null;\n\n for (var _i2 = 0, _documentAST$definiti2 = documentAST.definitions; _i2 < _documentAST$definiti2.length; _i2++) {\n var definition = _documentAST$definiti2[_i2];\n\n if (definition.kind === Kind.OPERATION_DEFINITION) {\n if (!operationName) {\n // If no operation name was provided, only return an Operation if there\n // is one defined in the document. Upon encountering the second, return\n // null.\n if (operation) {\n return null;\n }\n\n operation = definition;\n } else if (definition.name && definition.name.value === operationName) {\n return definition;\n }\n }\n }\n\n return operation;\n }", "function operation(operatorName, args) {\n return { type: 'operation', operator: operatorName, args: args || [] };\n }", "function operation(operatorName, args) {\n return { type: 'operation', operator: operatorName, args: args || [] };\n }", "parseOperationDefinition() {\n const start = this._lexer.token;\n\n if (this.peek(TokenKind.BRACE_L)) {\n return this.node(start, {\n kind: Kind.OPERATION_DEFINITION,\n operation: OperationTypeNode.QUERY,\n name: undefined,\n variableDefinitions: [],\n directives: [],\n selectionSet: this.parseSelectionSet(),\n });\n }\n\n const operation = this.parseOperationType();\n let name;\n\n if (this.peek(TokenKind.NAME)) {\n name = this.parseName();\n }\n\n return this.node(start, {\n kind: Kind.OPERATION_DEFINITION,\n operation,\n name,\n variableDefinitions: this.parseVariableDefinitions(),\n directives: this.parseDirectives(false),\n selectionSet: this.parseSelectionSet(),\n });\n }", "function operation(operatorName, args) {\n\t return { type: 'operation', operator: operatorName, args: args || [] };\n\t }", "function op(name) {\n return operators[name] || that.missingOperator(name);\n /*\n if (operators[name]) {\n operators[name].targetData = target;\n return operators[name];\n } else {\n return that.missingOperator(name);\n }\n */\n }", "function parseOperationDefinition(parser) {\n var start = parser.token.start;\n if (peek(parser, _lexer.TokenKind.BRACE_L)) {\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: 'query',\n name: null,\n variableDefinitions: null,\n directives: [],\n selectionSet: parseSelectionSet(parser),\n loc: loc(parser, start)\n };\n }\n var operationToken = expect(parser, _lexer.TokenKind.NAME);\n var operation = operationToken.value === 'mutation' ? 'mutation' : operationToken.value === 'subscription' ? 'subscription' : operationToken.value === 'query' ? 'query' : (function () {\n throw unexpected(parser, operationToken);\n })();\n var name = undefined;\n if (peek(parser, _lexer.TokenKind.NAME)) {\n name = parseName(parser);\n }\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(parser),\n directives: parseDirectives(parser),\n selectionSet: parseSelectionSet(parser),\n loc: loc(parser, start)\n };\n}", "function parseOperationDefinition(parser) {\n\t var start = parser.token.start;\n\t if (peek(parser, _lexer.TokenKind.BRACE_L)) {\n\t return {\n\t kind: _kinds.OPERATION_DEFINITION,\n\t operation: 'query',\n\t name: null,\n\t variableDefinitions: null,\n\t directives: [],\n\t selectionSet: parseSelectionSet(parser),\n\t loc: loc(parser, start)\n\t };\n\t }\n\t var operationToken = expect(parser, _lexer.TokenKind.NAME);\n\t var operation = operationToken.value === 'mutation' ? 'mutation' : operationToken.value === 'subscription' ? 'subscription' : operationToken.value === 'query' ? 'query' : (function () {\n\t throw unexpected(parser, operationToken);\n\t })();\n\t var name = undefined;\n\t if (peek(parser, _lexer.TokenKind.NAME)) {\n\t name = parseName(parser);\n\t }\n\t return {\n\t kind: _kinds.OPERATION_DEFINITION,\n\t operation: operation,\n\t name: name,\n\t variableDefinitions: parseVariableDefinitions(parser),\n\t directives: parseDirectives(parser),\n\t selectionSet: parseSelectionSet(parser),\n\t loc: loc(parser, start)\n\t };\n\t}", "function parseOperationDefinition(lexer) {\n var start = lexer.token;\n\n if (peek(lexer, TokenKind.BRACE_L)) {\n return {\n kind: Kind.OPERATION_DEFINITION,\n operation: 'query',\n name: undefined,\n variableDefinitions: [],\n directives: [],\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n }\n\n var operation = parseOperationType(lexer);\n var name;\n\n if (peek(lexer, TokenKind.NAME)) {\n name = parseName(lexer);\n }\n\n return {\n kind: Kind.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer),\n directives: parseDirectives(lexer, false),\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseOperationDefinition(lexer) {\n var start = lexer.token;\n\n if (peek(lexer, _lexer.TokenKind.BRACE_L)) {\n return {\n kind: _kinds.Kind.OPERATION_DEFINITION,\n operation: 'query',\n name: undefined,\n variableDefinitions: [],\n directives: [],\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n }\n\n var operation = parseOperationType(lexer);\n var name;\n\n if (peek(lexer, _lexer.TokenKind.NAME)) {\n name = parseName(lexer);\n }\n\n return {\n kind: _kinds.Kind.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer),\n directives: parseDirectives(lexer, false),\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseOperationDefinition(lexer) {\n var start = lexer.token;\n if (peek(lexer, _lexer.TokenKind.BRACE_L)) {\n return {\n kind: _kinds.Kind.OPERATION_DEFINITION,\n operation: 'query',\n name: undefined,\n variableDefinitions: [],\n directives: [],\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n }\n var operation = parseOperationType(lexer);\n var name = void 0;\n if (peek(lexer, _lexer.TokenKind.NAME)) {\n name = parseName(lexer);\n }\n return {\n kind: _kinds.Kind.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer),\n directives: parseDirectives(lexer, false),\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseOperationDefinition(lexer) {\n var start = lexer.token;\n if (peek(lexer, _lexer.TokenKind.BRACE_L)) {\n return {\n kind: _kinds.Kind.OPERATION_DEFINITION,\n operation: 'query',\n name: undefined,\n variableDefinitions: [],\n directives: [],\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n }\n var operation = parseOperationType(lexer);\n var name = void 0;\n if (peek(lexer, _lexer.TokenKind.NAME)) {\n name = parseName(lexer);\n }\n return {\n kind: _kinds.Kind.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer),\n directives: parseDirectives(lexer, false),\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseOperationDefinition(lexer) {\n var start = lexer.token;\n if (peek(lexer, _lexer.TokenKind.BRACE_L)) {\n return {\n kind: _kinds.Kind.OPERATION_DEFINITION,\n operation: 'query',\n name: undefined,\n variableDefinitions: [],\n directives: [],\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n }\n var operation = parseOperationType(lexer);\n var name = void 0;\n if (peek(lexer, _lexer.TokenKind.NAME)) {\n name = parseName(lexer);\n }\n return {\n kind: _kinds.Kind.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer),\n directives: parseDirectives(lexer, false),\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseOperationDefinition(lexer) {\n var start = lexer.token;\n if (peek(lexer, _lexer.TokenKind.BRACE_L)) {\n return {\n kind: _kinds.Kind.OPERATION_DEFINITION,\n operation: 'query',\n name: undefined,\n variableDefinitions: [],\n directives: [],\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n }\n var operation = parseOperationType(lexer);\n var name = void 0;\n if (peek(lexer, _lexer.TokenKind.NAME)) {\n name = parseName(lexer);\n }\n return {\n kind: _kinds.Kind.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer),\n directives: parseDirectives(lexer, false),\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseOperationDefinition(lexer) {\n var start = lexer.token;\n\n if (peek(lexer, _tokenKind__WEBPACK_IMPORTED_MODULE_4__[\"TokenKind\"].BRACE_L)) {\n return {\n kind: _kinds__WEBPACK_IMPORTED_MODULE_6__[\"Kind\"].OPERATION_DEFINITION,\n operation: 'query',\n name: undefined,\n variableDefinitions: [],\n directives: [],\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n }\n\n var operation = parseOperationType(lexer);\n var name;\n\n if (peek(lexer, _tokenKind__WEBPACK_IMPORTED_MODULE_4__[\"TokenKind\"].NAME)) {\n name = parseName(lexer);\n }\n\n return {\n kind: _kinds__WEBPACK_IMPORTED_MODULE_6__[\"Kind\"].OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer),\n directives: parseDirectives(lexer, false),\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseOperationDefinition(lexer$$1) {\n var start = lexer$$1.token;\n if (peek(lexer$$1, lexer.TokenKind.BRACE_L)) {\n return {\n kind: kinds.OPERATION_DEFINITION,\n operation: 'query',\n name: undefined,\n variableDefinitions: [],\n directives: [],\n selectionSet: parseSelectionSet(lexer$$1),\n loc: loc(lexer$$1, start)\n };\n }\n var operation = parseOperationType(lexer$$1);\n var name = void 0;\n if (peek(lexer$$1, lexer.TokenKind.NAME)) {\n name = parseName(lexer$$1);\n }\n return {\n kind: kinds.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer$$1),\n directives: parseDirectives(lexer$$1, false),\n selectionSet: parseSelectionSet(lexer$$1),\n loc: loc(lexer$$1, start)\n };\n}", "function parseOperationDefinition(lexer) {\n var start = lexer.token;\n if (peek(lexer, _lexer.TokenKind.BRACE_L)) {\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: 'query',\n name: null,\n variableDefinitions: null,\n directives: [],\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n }\n var operation = parseOperationType(lexer);\n var name = void 0;\n if (peek(lexer, _lexer.TokenKind.NAME)) {\n name = parseName(lexer);\n }\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer),\n directives: parseDirectives(lexer),\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseOperationDefinition(lexer) {\n var start = lexer.token;\n if (peek(lexer, _lexer.TokenKind.BRACE_L)) {\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: 'query',\n name: null,\n variableDefinitions: null,\n directives: [],\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n }\n var operation = parseOperationType(lexer);\n var name = void 0;\n if (peek(lexer, _lexer.TokenKind.NAME)) {\n name = parseName(lexer);\n }\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer),\n directives: parseDirectives(lexer),\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseOperationDefinition(lexer) {\n var start = lexer.token;\n if (peek(lexer, _lexer.TokenKind.BRACE_L)) {\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: 'query',\n name: null,\n variableDefinitions: null,\n directives: [],\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n }\n var operation = parseOperationType(lexer);\n var name = void 0;\n if (peek(lexer, _lexer.TokenKind.NAME)) {\n name = parseName(lexer);\n }\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer),\n directives: parseDirectives(lexer),\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseOperationDefinition(lexer) {\n var start = lexer.token;\n if (peek(lexer, _lexer.TokenKind.BRACE_L)) {\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: 'query',\n name: null,\n variableDefinitions: null,\n directives: [],\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n }\n var operation = parseOperationType(lexer);\n var name = void 0;\n if (peek(lexer, _lexer.TokenKind.NAME)) {\n name = parseName(lexer);\n }\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer),\n directives: parseDirectives(lexer),\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseOperationDefinition(lexer) {\n var start = lexer.token;\n if (peek(lexer, _lexer.TokenKind.BRACE_L)) {\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: 'query',\n name: null,\n variableDefinitions: null,\n directives: [],\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n }\n var operation = parseOperationType(lexer);\n var name = void 0;\n if (peek(lexer, _lexer.TokenKind.NAME)) {\n name = parseName(lexer);\n }\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer),\n directives: parseDirectives(lexer),\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseOperationDefinition(lexer) {\n var start = lexer.token;\n if (peek(lexer, _lexer.TokenKind.BRACE_L)) {\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: 'query',\n name: null,\n variableDefinitions: null,\n directives: [],\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n }\n var operation = parseOperationType(lexer);\n var name = void 0;\n if (peek(lexer, _lexer.TokenKind.NAME)) {\n name = parseName(lexer);\n }\n return {\n kind: _kinds.OPERATION_DEFINITION,\n operation: operation,\n name: name,\n variableDefinitions: parseVariableDefinitions(lexer),\n directives: parseDirectives(lexer),\n selectionSet: parseSelectionSet(lexer),\n loc: loc(lexer, start)\n };\n}", "function opName(operation) {\n return operation.name ? operation.name.value : '';\n}", "function opName(operation) {\n return operation.name ? operation.name.value : '';\n}" ]
[ "0.8256176", "0.82004493", "0.82004493", "0.81809", "0.81809", "0.81494194", "0.81430614", "0.59448606", "0.59448606", "0.5887792", "0.58035177", "0.5791091", "0.57523274", "0.57154346", "0.5593686", "0.5580738", "0.55647475", "0.55647475", "0.55647475", "0.55647475", "0.55556774", "0.55395466", "0.5535587", "0.5535587", "0.5535587", "0.5535587", "0.5535587", "0.5535587", "0.55244434", "0.55244434" ]
0.82664794
1
Given a type's introspection result, construct the correct GraphQLType instance.
function buildType(type) { switch (type.kind) { case _introspection.TypeKind.SCALAR: return buildScalarDef(type); case _introspection.TypeKind.OBJECT: return buildObjectDef(type); case _introspection.TypeKind.INTERFACE: return buildInterfaceDef(type); case _introspection.TypeKind.UNION: return buildUnionDef(type); case _introspection.TypeKind.ENUM: return buildEnumDef(type); case _introspection.TypeKind.INPUT_OBJECT: return buildInputObjectDef(type); default: throw new Error('Invalid or incomplete schema, unknown kind: ' + type.kind + '. Ensure ' + 'that a full introspection query is used in order to build a ' + 'client schema.'); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function buildType(type) {\n switch (type.kind) {\n case _typeIntrospection.TypeKind.SCALAR:\n return buildScalarDef(type);\n case _typeIntrospection.TypeKind.OBJECT:\n return buildObjectDef(type);\n case _typeIntrospection.TypeKind.INTERFACE:\n return buildInterfaceDef(type);\n case _typeIntrospection.TypeKind.UNION:\n return buildUnionDef(type);\n case _typeIntrospection.TypeKind.ENUM:\n return buildEnumDef(type);\n case _typeIntrospection.TypeKind.INPUT_OBJECT:\n return buildInputObjectDef(type);\n default:\n throw new Error('Invalid or incomplete schema, unknown kind: ' + type.kind + '. Ensure ' + 'that a full introspection query is used in order to build a ' + 'client schema.');\n }\n }", "function buildType(type) {\n\t switch (type.kind) {\n\t case _introspection.TypeKind.SCALAR:\n\t return buildScalarDef(type);\n\t case _introspection.TypeKind.OBJECT:\n\t return buildObjectDef(type);\n\t case _introspection.TypeKind.INTERFACE:\n\t return buildInterfaceDef(type);\n\t case _introspection.TypeKind.UNION:\n\t return buildUnionDef(type);\n\t case _introspection.TypeKind.ENUM:\n\t return buildEnumDef(type);\n\t case _introspection.TypeKind.INPUT_OBJECT:\n\t return buildInputObjectDef(type);\n\t default:\n\t throw new Error('Invalid or incomplete schema, unknown kind: ' + type.kind + '. Ensure ' + 'that a full introspection query is used in order to build a ' + 'client schema.');\n\t }\n\t }", "function buildType(type) {\n\t switch (type.kind) {\n\t case _typeIntrospection.TypeKind.SCALAR:\n\t return buildScalarDef(type);\n\t case _typeIntrospection.TypeKind.OBJECT:\n\t return buildObjectDef(type);\n\t case _typeIntrospection.TypeKind.INTERFACE:\n\t return buildInterfaceDef(type);\n\t case _typeIntrospection.TypeKind.UNION:\n\t return buildUnionDef(type);\n\t case _typeIntrospection.TypeKind.ENUM:\n\t return buildEnumDef(type);\n\t case _typeIntrospection.TypeKind.INPUT_OBJECT:\n\t return buildInputObjectDef(type);\n\t default:\n\t throw new Error('Invalid or incomplete schema, unknown kind: ' + type.kind + '. Ensure ' + 'that a full introspection query is used in order to build a ' + 'client schema.');\n\t }\n\t }", "function replaceType(type) {\n if (Object(_type_definition__WEBPACK_IMPORTED_MODULE_11__[\"isListType\"])(type)) {\n return new _type_definition__WEBPACK_IMPORTED_MODULE_11__[\"GraphQLList\"](replaceType(type.ofType));\n } else if (Object(_type_definition__WEBPACK_IMPORTED_MODULE_11__[\"isNonNullType\"])(type)) {\n return new _type_definition__WEBPACK_IMPORTED_MODULE_11__[\"GraphQLNonNull\"](replaceType(type.ofType));\n }\n\n return replaceNamedType(type);\n }", "function replaceType(type) {\n if (Object(_type_definition_mjs__WEBPACK_IMPORTED_MODULE_16__[\"isListType\"])(type)) {\n return new _type_definition_mjs__WEBPACK_IMPORTED_MODULE_16__[\"GraphQLList\"](replaceType(type.ofType));\n } else if (Object(_type_definition_mjs__WEBPACK_IMPORTED_MODULE_16__[\"isNonNullType\"])(type)) {\n return new _type_definition_mjs__WEBPACK_IMPORTED_MODULE_16__[\"GraphQLNonNull\"](replaceType(type.ofType));\n }\n\n return replaceNamedType(type);\n }", "static _processType(typeItem) {\n switch (typeItem.kind) {\n case 'variable-type':\n return Type.newVariableReference(typeItem.name);\n case 'reference-type':\n return Type.newManifestReference(typeItem.name);\n case 'list-type':\n return Type.newSetView(Manifest._processType(typeItem.type));\n default:\n throw `Unexpected type item of kind '${typeItem.kind}'`;\n }\n }", "function replaceType(type) {\n if ((0, _definition.isListType)(type)) {\n // $FlowFixMe[incompatible-return]\n return new _definition.GraphQLList(replaceType(type.ofType));\n }\n\n if ((0, _definition.isNonNullType)(type)) {\n // $FlowFixMe[incompatible-return]\n return new _definition.GraphQLNonNull(replaceType(type.ofType));\n }\n\n return replaceNamedType(type);\n }", "function replaceType(type) {\n if ((0, _definition.isListType)(type)) {\n // $FlowFixMe[incompatible-return]\n return new _definition.GraphQLList(replaceType(type.ofType));\n }\n\n if ((0, _definition.isNonNullType)(type)) {\n // $FlowFixMe[incompatible-return]\n return new _definition.GraphQLNonNull(replaceType(type.ofType));\n }\n\n return replaceNamedType(type);\n }", "function typeFromAST(schema, typeNode) {\n /* eslint-enable no-redeclare */\n var innerType;\n\n if (typeNode.kind === _language_kinds_mjs__WEBPACK_IMPORTED_MODULE_2__[\"Kind\"].LIST_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && new _type_definition_mjs__WEBPACK_IMPORTED_MODULE_3__[\"GraphQLList\"](innerType);\n }\n\n if (typeNode.kind === _language_kinds_mjs__WEBPACK_IMPORTED_MODULE_2__[\"Kind\"].NON_NULL_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && new _type_definition_mjs__WEBPACK_IMPORTED_MODULE_3__[\"GraphQLNonNull\"](innerType);\n } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')\n\n\n if (typeNode.kind === _language_kinds_mjs__WEBPACK_IMPORTED_MODULE_2__[\"Kind\"].NAMED_TYPE) {\n return schema.getType(typeNode.name.value);\n } // istanbul ignore next (Not reachable. All possible type nodes have been considered)\n\n\n false || Object(_jsutils_invariant_mjs__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(0, 'Unexpected type node: ' + Object(_jsutils_inspect_mjs__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(typeNode));\n}", "function typeFromASTImpl(schema, typeNode) {\n /* eslint-enable no-redeclare */\n var innerType = void 0;\n if (typeNode.kind === _kinds.LIST_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && new _definition.GraphQLList(innerType);\n }\n if (typeNode.kind === _kinds.NON_NULL_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && new _definition.GraphQLNonNull(innerType);\n }\n (0, _invariant2.default)(typeNode.kind === _kinds.NAMED_TYPE, 'Must be a named type.');\n return schema.getType(typeNode.name.value);\n}", "function typeFromASTImpl(schema, typeNode) {\n /* eslint-enable no-redeclare */\n var innerType = void 0;\n if (typeNode.kind === Kind.LIST_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && new _definition.GraphQLList(innerType);\n }\n if (typeNode.kind === Kind.NON_NULL_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && new _definition.GraphQLNonNull(innerType);\n }\n !(typeNode.kind === Kind.NAMED_TYPE) ? (0, _invariant2.default)(0, 'Must be a named type.') : void 0;\n return schema.getType(typeNode.name.value);\n}", "function typeFromASTImpl(schema, typeNode) {\n /* eslint-enable no-redeclare */\n var innerType = void 0;\n if (typeNode.kind === Kind.LIST_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && new _definition.GraphQLList(innerType);\n }\n if (typeNode.kind === Kind.NON_NULL_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && new _definition.GraphQLNonNull(innerType);\n }\n !(typeNode.kind === Kind.NAMED_TYPE) ? (0, _invariant2.default)(0, 'Must be a named type.') : void 0;\n return schema.getType(typeNode.name.value);\n}", "function getType(typeRef) {\n if (typeRef.kind === _typeIntrospection.TypeKind.LIST) {\n var itemRef = typeRef.ofType;\n if (!itemRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n return new _typeDefinition.GraphQLList(getType(itemRef));\n }\n if (typeRef.kind === _typeIntrospection.TypeKind.NON_NULL) {\n var nullableRef = typeRef.ofType;\n if (!nullableRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n var nullableType = getType(nullableRef);\n (0, _jsutilsInvariant2['default'])(!(nullableType instanceof _typeDefinition.GraphQLNonNull), 'No nesting nonnull.');\n return new _typeDefinition.GraphQLNonNull(nullableType);\n }\n return getNamedType(typeRef.name);\n }", "function replaceType(type) {\n if (Object(_type_definition_mjs__WEBPACK_IMPORTED_MODULE_16__[\"isListType\"])(type)) {\n // $FlowFixMe[incompatible-return]\n return new _type_definition_mjs__WEBPACK_IMPORTED_MODULE_16__[\"GraphQLList\"](replaceType(type.ofType));\n }\n\n if (Object(_type_definition_mjs__WEBPACK_IMPORTED_MODULE_16__[\"isNonNullType\"])(type)) {\n // $FlowFixMe[incompatible-return]\n return new _type_definition_mjs__WEBPACK_IMPORTED_MODULE_16__[\"GraphQLNonNull\"](replaceType(type.ofType));\n }\n\n return replaceNamedType(type);\n }", "function getType(typeRef) {\n if (typeRef.kind === _introspection.TypeKind.LIST) {\n var itemRef = typeRef.ofType;\n\n if (!itemRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n\n return new _definition.GraphQLList(getType(itemRef));\n }\n\n if (typeRef.kind === _introspection.TypeKind.NON_NULL) {\n var nullableRef = typeRef.ofType;\n\n if (!nullableRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n\n var nullableType = getType(nullableRef);\n return new _definition.GraphQLNonNull((0, _definition.assertNullableType)(nullableType));\n }\n\n return getNamedType(typeRef);\n }", "function getType(typeRef) {\n if (typeRef.kind === _introspection.TypeKind.LIST) {\n var itemRef = typeRef.ofType;\n\n if (!itemRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n\n return new _definition.GraphQLList(getType(itemRef));\n }\n\n if (typeRef.kind === _introspection.TypeKind.NON_NULL) {\n var nullableRef = typeRef.ofType;\n\n if (!nullableRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n\n var nullableType = getType(nullableRef);\n return new _definition.GraphQLNonNull((0, _definition.assertNullableType)(nullableType));\n }\n\n return getNamedType(typeRef);\n }", "function replaceType(type) {\n if (isListType(type)) {\n return new GraphQLList(replaceType(type.ofType));\n } else if (isNonNullType(type)) {\n return new GraphQLNonNull(replaceType(type.ofType));\n }\n\n return replaceNamedType(type);\n }", "function getType(typeRef) {\n if (typeRef.kind === _type_introspection_mjs__WEBPACK_IMPORTED_MODULE_9__[\"TypeKind\"].LIST) {\n var itemRef = typeRef.ofType;\n\n if (!itemRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n\n return new _type_definition_mjs__WEBPACK_IMPORTED_MODULE_10__[\"GraphQLList\"](getType(itemRef));\n }\n\n if (typeRef.kind === _type_introspection_mjs__WEBPACK_IMPORTED_MODULE_9__[\"TypeKind\"].NON_NULL) {\n var nullableRef = typeRef.ofType;\n\n if (!nullableRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n\n var nullableType = getType(nullableRef);\n return new _type_definition_mjs__WEBPACK_IMPORTED_MODULE_10__[\"GraphQLNonNull\"](Object(_type_definition_mjs__WEBPACK_IMPORTED_MODULE_10__[\"assertNullableType\"])(nullableType));\n }\n\n return getNamedType(typeRef);\n }", "function getType(typeRef) {\n if (typeRef.kind === _introspection.TypeKind.LIST) {\n var itemRef = typeRef.ofType;\n if (!itemRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n return new _definition.GraphQLList(getType(itemRef));\n }\n if (typeRef.kind === _introspection.TypeKind.NON_NULL) {\n var nullableRef = typeRef.ofType;\n if (!nullableRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n var nullableType = getType(nullableRef);\n !!(nullableType instanceof _definition.GraphQLNonNull) ? (0, _invariant2.default)(0, 'No nesting nonnull.') : void 0;\n return new _definition.GraphQLNonNull(nullableType);\n }\n return getNamedType(typeRef.name);\n }", "function getType(typeRef) {\n if (typeRef.kind === _introspection.TypeKind.LIST) {\n var itemRef = typeRef.ofType;\n if (!itemRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n return new _definition.GraphQLList(getType(itemRef));\n }\n if (typeRef.kind === _introspection.TypeKind.NON_NULL) {\n var nullableRef = typeRef.ofType;\n if (!nullableRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n var nullableType = getType(nullableRef);\n !!(nullableType instanceof _definition.GraphQLNonNull) ? (0, _invariant2.default)(0, 'No nesting nonnull.') : void 0;\n return new _definition.GraphQLNonNull(nullableType);\n }\n return getNamedType(typeRef.name);\n }", "function typeFromAST(schema, typeNode) {\n /* eslint-enable no-redeclare */\n var innerType;\n\n if (typeNode.kind === _kinds.Kind.LIST_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && new _definition.GraphQLList(innerType);\n }\n\n if (typeNode.kind === _kinds.Kind.NON_NULL_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && new _definition.GraphQLNonNull(innerType);\n } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')\n\n\n if (typeNode.kind === _kinds.Kind.NAMED_TYPE) {\n return schema.getType(typeNode.name.value);\n } // istanbul ignore next (Not reachable. All possible type nodes have been considered)\n\n\n false || (0, _invariant.default)(0, 'Unexpected type node: ' + (0, _inspect.default)(typeNode));\n}", "function fromType (entry, type) {\n let inttype = Helpers.intToType(type);\n switch (inttype) {\n case 'MapQL': case 'Map':\n return (new MapQL()).import(entry); // Convert all 'Map()' entries to MapQL.\n case 'Set':\n return new Set(entry.map((val) => {\n return fromType(val[0], val[1]);\n }));\n case 'Array':\n return entry.map((val) => {\n return fromType(val[0], val[1]);\n });\n case 'Object':\n return ((obj) => {\n for (let key of Object.keys(obj)) {\n obj[key] = fromType(obj[key][0], obj[key][1]);\n }\n return obj;\n })(entry);\n case 'Function':\n // XXX: Function() is a form of eval()!\n return new Function(`return ${entry};`)();\n case 'RegExp':\n return RegExp.apply(null, entry.match(/\\/(.*?)\\/([gimuy])?$/).slice(1));\n case 'Date':\n return new Date(entry);\n case 'Uint8Array':\n try {\n return new Uint8Array(entry);\n } catch (error) {\n try {\n return Buffer.from(entry);\n } catch (error) { return Array.from(entry); }\n }\n case 'Buffer':\n try {\n return Buffer.from(entry);\n } catch (error) {\n try {\n return new Uint8Array(entry);\n } catch (error) { return Array.from(entry); }\n }\n default:\n // Execute the function/constructor with the entry value. If type is not a\n // function or constructor, just return the value. Try without `new`, if\n // that fails try again with `new`. This attempts to import unknown types.\n let _fn = (Helpers.__GLOBAL[inttype] ? (new Function(`return ${inttype}`))() : (e) => { return e });\n try { return _fn(entry); } catch (e) { try { return new _fn(entry); } catch (error) { console.trace(error); } }\n }\n}", "function parseType(type) {\n if (typeof type === 'function') {\n return new type();\n } else if (isArray(type)) {\n return [parseType(type[0])];\n } else if (type && typeof type === 'object') {\n var rv = {};\n applyStructure(rv, type);\n return rv;\n } else {\n return type;\n }\n}", "function getType(typeRef) {\n\t if (typeRef.kind === _typeIntrospection.TypeKind.LIST) {\n\t var itemRef = typeRef.ofType;\n\t if (!itemRef) {\n\t throw new Error('Decorated type deeper than introspection query.');\n\t }\n\t return new _typeDefinition.GraphQLList(getType(itemRef));\n\t }\n\t if (typeRef.kind === _typeIntrospection.TypeKind.NON_NULL) {\n\t var nullableRef = typeRef.ofType;\n\t if (!nullableRef) {\n\t throw new Error('Decorated type deeper than introspection query.');\n\t }\n\t var nullableType = getType(nullableRef);\n\t (0, _jsutilsInvariant2['default'])(!(nullableType instanceof _typeDefinition.GraphQLNonNull), 'No nesting nonnull.');\n\t return new _typeDefinition.GraphQLNonNull(nullableType);\n\t }\n\t return getNamedType(typeRef.name);\n\t }", "function getType(typeRef) {\n if (typeRef.kind === _type_introspection__WEBPACK_IMPORTED_MODULE_9__[\"TypeKind\"].LIST) {\n var itemRef = typeRef.ofType;\n\n if (!itemRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n\n return Object(_type_definition__WEBPACK_IMPORTED_MODULE_7__[\"GraphQLList\"])(getType(itemRef));\n }\n\n if (typeRef.kind === _type_introspection__WEBPACK_IMPORTED_MODULE_9__[\"TypeKind\"].NON_NULL) {\n var nullableRef = typeRef.ofType;\n\n if (!nullableRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n\n var nullableType = getType(nullableRef);\n return Object(_type_definition__WEBPACK_IMPORTED_MODULE_7__[\"GraphQLNonNull\"])(Object(_type_definition__WEBPACK_IMPORTED_MODULE_7__[\"assertNullableType\"])(nullableType));\n }\n\n if (!typeRef.name) {\n throw new Error('Unknown type reference: ' + Object(_jsutils_inspect__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(typeRef));\n }\n\n return getNamedType(typeRef.name);\n }", "function relaxType(type) {\n switch (type.kind) {\n case SimpleTypeKind.INTERSECTION:\n case SimpleTypeKind.UNION:\n return __assign(__assign({}, type), { types: type.types.map(function (t) { return relaxType(t); }) });\n case SimpleTypeKind.ENUM:\n return __assign(__assign({}, type), { types: type.types.map(function (t) { return relaxType(t); }) });\n case SimpleTypeKind.ARRAY:\n return __assign(__assign({}, type), { type: relaxType(type.type) });\n case SimpleTypeKind.PROMISE:\n return __assign(__assign({}, type), { type: relaxType(type.type) });\n case SimpleTypeKind.OBJECT:\n return {\n name: type.name,\n kind: SimpleTypeKind.OBJECT\n };\n case SimpleTypeKind.INTERFACE:\n case SimpleTypeKind.FUNCTION:\n case SimpleTypeKind.CLASS:\n return {\n name: type.name,\n kind: SimpleTypeKind.ANY\n };\n case SimpleTypeKind.NUMBER_LITERAL:\n return { kind: SimpleTypeKind.NUMBER };\n case SimpleTypeKind.STRING_LITERAL:\n return { kind: SimpleTypeKind.STRING };\n case SimpleTypeKind.BOOLEAN_LITERAL:\n return { kind: SimpleTypeKind.BOOLEAN };\n case SimpleTypeKind.BIG_INT_LITERAL:\n return { kind: SimpleTypeKind.BIG_INT };\n case SimpleTypeKind.ENUM_MEMBER:\n return __assign(__assign({}, type), { type: relaxType(type.type) });\n case SimpleTypeKind.ALIAS:\n return __assign(__assign({}, type), { target: relaxType(type.target) });\n case SimpleTypeKind.NULL:\n case SimpleTypeKind.UNDEFINED:\n return { kind: SimpleTypeKind.ANY };\n default:\n return type;\n }\n}", "function typeFromAST(schema, typeNode) {\n /* eslint-enable no-redeclare */\n var innerType;\n\n if (typeNode.kind === _language_kinds_mjs__WEBPACK_IMPORTED_MODULE_2__[\"Kind\"].LIST_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && Object(_type_definition_mjs__WEBPACK_IMPORTED_MODULE_3__[\"GraphQLList\"])(innerType);\n }\n\n if (typeNode.kind === _language_kinds_mjs__WEBPACK_IMPORTED_MODULE_2__[\"Kind\"].NON_NULL_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && Object(_type_definition_mjs__WEBPACK_IMPORTED_MODULE_3__[\"GraphQLNonNull\"])(innerType);\n } // istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')\n\n\n if (typeNode.kind === _language_kinds_mjs__WEBPACK_IMPORTED_MODULE_2__[\"Kind\"].NAMED_TYPE) {\n return schema.getType(typeNode.name.value);\n } // istanbul ignore next (Not reachable. All possible type nodes have been considered)\n\n\n false || Object(_jsutils_invariant_mjs__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(0, 'Unexpected type node: ' + Object(_jsutils_inspect_mjs__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(typeNode));\n}", "function getType(typeRef) {\n\t if (typeRef.kind === _introspection.TypeKind.LIST) {\n\t var itemRef = typeRef.ofType;\n\t if (!itemRef) {\n\t throw new Error('Decorated type deeper than introspection query.');\n\t }\n\t return new _definition.GraphQLList(getType(itemRef));\n\t }\n\t if (typeRef.kind === _introspection.TypeKind.NON_NULL) {\n\t var nullableRef = typeRef.ofType;\n\t if (!nullableRef) {\n\t throw new Error('Decorated type deeper than introspection query.');\n\t }\n\t var nullableType = getType(nullableRef);\n\t (0, _invariant2.default)(!(nullableType instanceof _definition.GraphQLNonNull), 'No nesting nonnull.');\n\t return new _definition.GraphQLNonNull(nullableType);\n\t }\n\t return getNamedType(typeRef.name);\n\t }", "function typeFromAST(schema, typeNode) {\n /* eslint-enable no-redeclare */\n var innerType;\n\n if (typeNode.kind === _language_kinds__WEBPACK_IMPORTED_MODULE_1__[\"Kind\"].LIST_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && Object(_type_definition__WEBPACK_IMPORTED_MODULE_2__[\"GraphQLList\"])(innerType);\n }\n\n if (typeNode.kind === _language_kinds__WEBPACK_IMPORTED_MODULE_1__[\"Kind\"].NON_NULL_TYPE) {\n innerType = typeFromAST(schema, typeNode.type);\n return innerType && Object(_type_definition__WEBPACK_IMPORTED_MODULE_2__[\"GraphQLNonNull\"])(innerType);\n }\n\n if (typeNode.kind === _language_kinds__WEBPACK_IMPORTED_MODULE_1__[\"Kind\"].NAMED_TYPE) {\n return schema.getType(typeNode.name.value);\n } // Not reachable. All possible type nodes have been considered.\n\n /* istanbul ignore next */\n\n\n throw new Error(\"Unexpected type node: \\\"\".concat(Object(_jsutils_inspect__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(typeNode), \"\\\".\"));\n}", "function getType(typeRef) {\n if (typeRef.kind === _type_introspection_mjs__WEBPACK_IMPORTED_MODULE_8__[\"TypeKind\"].LIST) {\n var itemRef = typeRef.ofType;\n\n if (!itemRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n\n return Object(_type_definition_mjs__WEBPACK_IMPORTED_MODULE_10__[\"GraphQLList\"])(getType(itemRef));\n }\n\n if (typeRef.kind === _type_introspection_mjs__WEBPACK_IMPORTED_MODULE_8__[\"TypeKind\"].NON_NULL) {\n var nullableRef = typeRef.ofType;\n\n if (!nullableRef) {\n throw new Error('Decorated type deeper than introspection query.');\n }\n\n var nullableType = getType(nullableRef);\n return Object(_type_definition_mjs__WEBPACK_IMPORTED_MODULE_10__[\"GraphQLNonNull\"])(Object(_type_definition_mjs__WEBPACK_IMPORTED_MODULE_10__[\"assertNullableType\"])(nullableType));\n }\n\n return getNamedType(typeRef);\n }" ]
[ "0.62939745", "0.61280996", "0.6125423", "0.60745406", "0.59689707", "0.59103006", "0.58754486", "0.58754486", "0.5817086", "0.57816267", "0.57815415", "0.57815415", "0.5747277", "0.5745704", "0.5744993", "0.5744993", "0.5703063", "0.56787306", "0.56731856", "0.56731856", "0.565891", "0.5599743", "0.5567032", "0.55365974", "0.54938704", "0.5474584", "0.54733896", "0.5465206", "0.54508173", "0.53666383" ]
0.63095886
1
Provided a collection of ASTs, presumably each from different files, concatenate the ASTs together into batched AST, useful for validating many GraphQL source files which together represent one conceptual application.
function concatAST(asts) { var batchDefinitions = []; for (var i = 0; i < asts.length; i++) { var definitions = asts[i].definitions; for (var j = 0; j < definitions.length; j++) { batchDefinitions.push(definitions[j]); } } return { kind: 'Document', definitions: batchDefinitions }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function concatAST(asts) {\n\t var batchDefinitions = [];\n\t for (var i = 0; i < asts.length; i++) {\n\t var definitions = asts[i].definitions;\n\t for (var j = 0; j < definitions.length; j++) {\n\t batchDefinitions.push(definitions[j]);\n\t }\n\t }\n\t return {\n\t kind: 'Document',\n\t definitions: batchDefinitions\n\t };\n\t}", "function concatAST(asts) {\n return {\n kind: 'Document',\n definitions: Object(_polyfills_flatMap__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(asts, function (ast) {\n return ast.definitions;\n })\n };\n}", "function concatAST(asts) {\n return {\n kind: 'Document',\n definitions: Object(_polyfills_flatMap_mjs__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(asts, function (ast) {\n return ast.definitions;\n })\n };\n}", "visitAll(asts, context) {\n for (const ast of asts) {\n this.visit(ast, context);\n }\n }", "visitAll(asts, context) {\n for (const ast of asts) {\n this.visit(ast, context);\n }\n }", "function concatAST(documents) {\n var definitions = [];\n\n for (var _i2 = 0; _i2 < documents.length; _i2++) {\n var doc = documents[_i2];\n definitions = definitions.concat(doc.definitions);\n }\n\n return {\n kind: 'Document',\n definitions: definitions\n };\n}", "function concatAST(documents) {\n var definitions = [];\n\n for (var _i2 = 0; _i2 < documents.length; _i2++) {\n var doc = documents[_i2];\n definitions = definitions.concat(doc.definitions);\n }\n\n return {\n kind: 'Document',\n definitions: definitions\n };\n}", "function concatAST(documents) {\n var definitions = [];\n\n for (var _i2 = 0; _i2 < documents.length; _i2++) {\n var doc = documents[_i2];\n definitions = definitions.concat(doc.definitions);\n }\n\n return {\n kind: 'Document',\n definitions: definitions\n };\n}", "function addArray(ast) {\n for (let child of ast)\n mdAstToHtml(child, lines);\n return lines;\n }", "function addArray(ast) {\n for (let child of ast)\n markdownAstToHtml(child, htmlBuilder);\n return htmlBuilder;\n }", "function transpileSassAst(ast) {\n return ast.flatMap(rs => flatten(rs));\n}", "concat(texts) {\n let blocks = [];\n let inlines = [];\n\n for (let text of texts) {\n if (!text.startsWith('\\n\\n')) {\n inlines.push(text);\n continue;\n }\n\n if (inlines.length) {\n blocks.push(this.format_block(this.escape_block(this.concat_inline(inlines))));\n inlines = [];\n }\n blocks.push(text);\n }\n\n if (inlines.length) {\n // all inline tags, join into single inline tag\n if (!blocks.length) return this.concat_inline(inlines);\n blocks.push(this.format_block(this.escape_block(this.concat_inline(inlines))));\n }\n\n return blocks.filter(block => block.match(/\\S/)).join('');\n }", "function joinSourceFiles(files) {\n return arrayify(files)\n .map((file) => `@import '${path.resolve(file)}';`)\n .join('\\n');\n}", "function concatenateArrays() {\n //meaning to merge two or more arrays into one array\n const arr1 = [0, 1, 2, 3];\n const arr2 = [4, 5, 6];\n const arr3 = [7, 8, 9];\n const result = [...arr1, ...arr2, ...arr3]; //This expression concatenate 3 arrays into one\n console.group(\"concatenateArrays()\");\n console.log(`const arr1 = [0, 1, 2, 3];\n const arr2 = [4, 5, 6];\n const arr3 = [7, 8, 9];`);\n console.log(`const result = [...arr1, ...arr2, ...arr3];`);\n console.log(`return result; `);\n return result;\n}", "function prepareIsolatedFiles(filenames, addTypename) {\n return filenames.map(function(filename) {\n var fileOperationBody = fs.readFileSync(filename, \"utf8\")\n var fileOperationName = null;\n\n var ast = graphql.parse(fileOperationBody)\n var visitor = {\n OperationDefinition: {\n enter: function(node) {\n if (fileOperationName) {\n throw new Error(\"Found multiple operations in \" + filename + \": \" + fileOperationName + \", \" + node.name + \". Files must contain only one operation\")\n } else {\n fileOperationName = node.name.value\n }\n },\n leave: function(node) {\n if (addTypename) { addTypenameToSelectionSet(node.selectionSet, true); }\n }\n },\n FragmentDefinition: {\n leave: function(node) {\n if (addTypename) { addTypenameToSelectionSet(node.selectionSet, true); }\n }\n }\n }\n graphql.visit(ast, visitor)\n\n return {\n // populate alias later, when hashFunc is available\n alias: null,\n name: fileOperationName,\n body: graphql.print(ast),\n }\n })\n}", "_rollupInlineModuleScripts(ast) {\n return __awaiter(this, void 0, void 0, function* () {\n this.document = yield this._reanalyze(parse5_1.serialize(ast));\n utils_1.rewriteObject(ast, this.document.parsedDocument.ast);\n dom5.removeFakeRootElements(ast);\n const es6Rewriter = new es6_rewriter_1.Es6Rewriter(this.bundler, this.manifest, this.assignedBundle);\n const inlineModuleScripts = [...this.document.getFeatures({\n kind: 'js-document',\n imported: false,\n externalPackages: true,\n excludeBackreferences: true,\n })].filter(({ isInline, parsedDocument: { parsedAsSourceType } }) => isInline && parsedAsSourceType === 'module');\n for (const inlineModuleScript of inlineModuleScripts) {\n const { code } = yield es6Rewriter.rollup(this.document.parsedDocument.baseUrl, inlineModuleScript.parsedDocument.contents, inlineModuleScript);\n if (inlineModuleScript.astNode &&\n inlineModuleScript.astNode.language === 'html') {\n // Second argument 'true' tells encodeString to escape the <script>\n // content.\n dom5.setTextContent(inlineModuleScript.astNode.node, encode_string_1.default(`\\n${code}\\n`, true));\n }\n }\n });\n }", "function makeRepoAST(baseAST, rawRepo) {\n const resultArgs = prepareASTArguments(baseAST, rawRepo);\n\n // Now we need to copy in necessary commits that weren't directly\n // included.\n\n function includeCommit(id) {\n copyCommitAndParents(resultArgs.commits, commits, id);\n }\n for (let branch in resultArgs.branches) {\n includeCommit(resultArgs.branches[branch].sha);\n }\n for (let ref in resultArgs.refs) {\n includeCommit(resultArgs.refs[ref]);\n }\n if (resultArgs.head) {\n includeCommit(resultArgs.head);\n }\n if (resultArgs.rebase) {\n includeCommit(resultArgs.rebase.originalHead);\n includeCommit(resultArgs.rebase.onto);\n }\n if (resultArgs.sequencerState) {\n includeCommit(resultArgs.sequencerState.originalHead.sha);\n includeCommit(resultArgs.sequencerState.target.sha);\n resultArgs.sequencerState.commits.forEach(includeCommit);\n }\n for (let remoteName in resultArgs.remotes) {\n const remote = resultArgs.remotes[remoteName];\n for (let branch in remote.branches) {\n includeCommit(remote.branches[branch]);\n }\n }\n return new RepoAST(resultArgs);\n }", "add(...exprs) {\n const source = RuleBuilder.joinSources(\"\", ...exprs);\n this.setFlags(RuleBuilder.joinFlags(this, ...exprs));\n this._source += source;\n return this;\n }", "function transform_statements(statements) {\n var statement = statements.shift()\n if (!statement) return []\n \n return transform_statement(statement, statements)\n}", "function pack(files) {\n var ids = {}\n , next = 0\n\n var modules = files.map(function (file) {\n ids[file.hash] = next++\n\n var map = file.deps.map(function (dep) {\n return JSON.stringify(dep.name) + ':' + ids[dep.file.hash]\n }).join(',')\n\n return '[function(require,module,exports){\\n' +\n file.src + '\\n},{' + map + '}]'\n })\n\n var args = '[' + modules.join(',\\n') + ']'\n , js = prelude.replace(/\\(\\[\\]\\)[;\\s]*$/, function () {\n return '(' + args + ');'\n })\n\n return js\n}", "function concatAll() {\n return args(arguments).reduce(function (a, b) {\n return a.concat(b);\n }, []);\n }", "function optimize(ast) {\n }", "function optimize(ast) {\n }", "function compileAll(tests, cb) {\n var results = [];\n var pending = tests.length;\n tests.forEach(function (name, idx) {\n compile(name, function (err, result) {\n if (err) return cb(err);\n\n results[idx] = result;\n if (--pending === 0) {\n cb(null, results);\n }\n });\n });\n}", "async combineTimFiles(files) {\n const baseXML = fs.readFileSync(files[1]);\n let baseData;\n xmlReader.Parser().parseString(baseXML, (err, result) => {\n baseData = JSON.parse(JSON.stringify(result, null, 2));\n });\n\n\n for (let i = 2; i < files.length; i += 1) {\n const additionalDataXML = fs.readFileSync(files[i]);\n let additionalData;\n\n xmlReader.Parser().parseString(additionalDataXML, (err, result) => {\n additionalData = JSON.parse(JSON.stringify(result, null, 2));\n });\n\n const additionalDataModels = additionalData.TimedSequenceData._dataModels[0]['d1p1:anyType'];\n const additionalDataNodes = additionalData.TimedSequenceData._effectNodeSurrogates[0].EffectNodeSurrogate;\n\n for (let j = 1; j < additionalDataModels.length; j += 1) {\n baseData.TimedSequenceData._dataModels[0]['d1p1:anyType'].push(additionalDataModels[j]);\n }\n for (let k = 0; k < additionalDataNodes.length; k += 1) {\n baseData.TimedSequenceData._effectNodeSurrogates[0].EffectNodeSurrogate.push(additionalDataNodes[k]);\n }\n }\n\n const builder = new xmlReader.Builder();\n const newTimFile = builder.buildObject(baseData);\n fs.writeFileSync(files[0], newTimFile);\n }", "concatinateInline() {\n // const reducer = (acc, nxt, id) => R.concat(acc, [{ nxt, id }])\n const reduceIndexed = R.addIndex(R.reduce);\n const reducer = (acc, _val, idx, list) => {\n let val = _val;\n\n if (val.children) {\n val.children = reduceIndexed(reducer, [], val.children);\n }\n\n if (idx > 0) {\n let lastItem = acc[acc.length - 1];\n if (\n val.processor.type === \"inline\" &&\n R.equals(val.processor, lastItem.processor)\n ) {\n lastItem.children.push(...val.children);\n } else {\n acc.push(val);\n }\n } else {\n acc.push(val);\n }\n\n return acc;\n };\n\n return reduceIndexed(reducer, [], this.ntz);\n }", "function separateOperations(documentAST) {\n var operations = [];\n var fragments = Object.create(null);\n var positions = new Map();\n var depGraph = Object.create(null);\n var fromName;\n var idx = 0; // Populate metadata and build a dependency graph.\n\n Object(_language_visitor__WEBPACK_IMPORTED_MODULE_0__[\"visit\"])(documentAST, {\n OperationDefinition: function OperationDefinition(node) {\n fromName = opName(node);\n operations.push(node);\n positions.set(node, idx++);\n },\n FragmentDefinition: function FragmentDefinition(node) {\n fromName = node.name.value;\n fragments[fromName] = node;\n positions.set(node, idx++);\n },\n FragmentSpread: function FragmentSpread(node) {\n var toName = node.name.value;\n (depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[toName] = true;\n }\n }); // For each operation, produce a new synthesized AST which includes only what\n // is necessary for completing that operation.\n\n var separatedDocumentASTs = Object.create(null);\n var _arr = operations;\n\n for (var _i = 0; _i < _arr.length; _i++) {\n var operation = _arr[_i];\n var operationName = opName(operation);\n var dependencies = Object.create(null);\n collectTransitiveDependencies(dependencies, depGraph, operationName); // The list of definition nodes to be included for this operation, sorted\n // to retain the same order as the original document.\n\n var definitions = [operation];\n\n var _arr2 = Object.keys(dependencies);\n\n for (var _i2 = 0; _i2 < _arr2.length; _i2++) {\n var name = _arr2[_i2];\n definitions.push(fragments[name]);\n }\n\n definitions.sort(function (n1, n2) {\n return (positions.get(n1) || 0) - (positions.get(n2) || 0);\n });\n separatedDocumentASTs[operationName] = {\n kind: 'Document',\n definitions: definitions\n };\n }\n\n return separatedDocumentASTs;\n}", "function separateOperations(documentAST) {\n var operations = [];\n var depGraph = Object.create(null);\n var fromName; // Populate metadata and build a dependency graph.\n\n Object(_language_visitor_mjs__WEBPACK_IMPORTED_MODULE_1__[\"visit\"])(documentAST, {\n OperationDefinition: function OperationDefinition(node) {\n fromName = opName(node);\n operations.push(node);\n },\n FragmentDefinition: function FragmentDefinition(node) {\n fromName = node.name.value;\n },\n FragmentSpread: function FragmentSpread(node) {\n var toName = node.name.value;\n var dependents = depGraph[fromName];\n\n if (dependents === undefined) {\n dependents = depGraph[fromName] = Object.create(null);\n }\n\n dependents[toName] = true;\n }\n }); // For each operation, produce a new synthesized AST which includes only what\n // is necessary for completing that operation.\n\n var separatedDocumentASTs = Object.create(null);\n\n var _loop = function _loop(_i2) {\n var operation = operations[_i2];\n var operationName = opName(operation);\n var dependencies = Object.create(null);\n collectTransitiveDependencies(dependencies, depGraph, operationName); // The list of definition nodes to be included for this operation, sorted\n // to retain the same order as the original document.\n\n separatedDocumentASTs[operationName] = {\n kind: _language_kinds_mjs__WEBPACK_IMPORTED_MODULE_0__[\"Kind\"].DOCUMENT,\n definitions: documentAST.definitions.filter(function (node) {\n return node === operation || node.kind === _language_kinds_mjs__WEBPACK_IMPORTED_MODULE_0__[\"Kind\"].FRAGMENT_DEFINITION && dependencies[node.name.value];\n })\n };\n };\n\n for (var _i2 = 0; _i2 < operations.length; _i2++) {\n _loop(_i2);\n }\n\n return separatedDocumentASTs;\n}", "function separateOperations(documentAST) {\n var operations = [];\n var depGraph = Object.create(null);\n var fromName; // Populate metadata and build a dependency graph.\n\n Object(_language_visitor_mjs__WEBPACK_IMPORTED_MODULE_1__[\"visit\"])(documentAST, {\n OperationDefinition: function OperationDefinition(node) {\n fromName = opName(node);\n operations.push(node);\n },\n FragmentDefinition: function FragmentDefinition(node) {\n fromName = node.name.value;\n },\n FragmentSpread: function FragmentSpread(node) {\n var toName = node.name.value;\n var dependents = depGraph[fromName];\n\n if (dependents === undefined) {\n dependents = depGraph[fromName] = Object.create(null);\n }\n\n dependents[toName] = true;\n }\n }); // For each operation, produce a new synthesized AST which includes only what\n // is necessary for completing that operation.\n\n var separatedDocumentASTs = Object.create(null);\n\n var _loop = function _loop(_i2) {\n var operation = operations[_i2];\n var operationName = opName(operation);\n var dependencies = Object.create(null);\n collectTransitiveDependencies(dependencies, depGraph, operationName); // The list of definition nodes to be included for this operation, sorted\n // to retain the same order as the original document.\n\n separatedDocumentASTs[operationName] = {\n kind: _language_kinds_mjs__WEBPACK_IMPORTED_MODULE_0__[\"Kind\"].DOCUMENT,\n definitions: documentAST.definitions.filter(function (node) {\n return node === operation || node.kind === _language_kinds_mjs__WEBPACK_IMPORTED_MODULE_0__[\"Kind\"].FRAGMENT_DEFINITION && dependencies[node.name.value];\n })\n };\n };\n\n for (var _i2 = 0; _i2 < operations.length; _i2++) {\n _loop(_i2);\n }\n\n return separatedDocumentASTs;\n}", "merge(tree) {\n let arr = tree.toArray();\n for(let i=0; i<arr.length; i++) {\n this.add(arr[i]);\n }\n }" ]
[ "0.6908495", "0.6170209", "0.6108926", "0.5783711", "0.5783711", "0.5568391", "0.5568391", "0.5568391", "0.54284203", "0.5300837", "0.5247986", "0.5224473", "0.5103726", "0.50698173", "0.49965164", "0.49735075", "0.4945306", "0.4937225", "0.4897356", "0.48926285", "0.48727074", "0.4869167", "0.4869167", "0.4868763", "0.48476508", "0.48453194", "0.4841075", "0.48266006", "0.48266006", "0.4805562" ]
0.7075156
1
Given two schemas, returns an Array containing descriptions of all the types of potentially dangerous changes covered by the other functions down below.
function findDangerousChanges(oldSchema, newSchema) { return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges, findValuesAddedToEnums(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema)); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function findDangerousChanges(oldSchema, newSchema) {\n return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges, findValuesAddedToEnums(oldSchema, newSchema), findInterfacesAddedToObjectTypes(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).dangerousChanges);\n}", "function findBreakingChanges(oldSchema, newSchema) {\n\t return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema));\n\t}", "function findDangerousChanges(oldSchema, newSchema) {\n return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges);\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findRemovedTypes(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t if (!newTypeMap[typeName]) {\n\t breakingChanges.push({\n\t type: BreakingChangeType.TYPE_REMOVED,\n\t description: typeName + ' was removed.'\n\t });\n\t }\n\t });\n\t return breakingChanges;\n\t}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n return;\n }\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof newType.constructor)) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n });\n }\n });\n return breakingChanges;\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n return;\n }\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof newType.constructor)) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n });\n }\n });\n return breakingChanges;\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t if (!newTypeMap[typeName]) {\n\t return;\n\t }\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof newType.constructor)) {\n\t breakingChanges.push({\n\t type: BreakingChangeType.TYPE_CHANGED_KIND,\n\t description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n\t });\n\t }\n\t });\n\t return breakingChanges;\n\t}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var breakingChanges = [];\n\n var _arr2 = Object.keys(oldTypeMap);\n\n for (var _i2 = 0; _i2 < _arr2.length; _i2++) {\n var typeName = _arr2[_i2];\n\n if (!newTypeMap[typeName]) {\n continue;\n }\n\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (oldType.constructor !== newType.constructor) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: \"\".concat(typeName, \" changed from \") + \"\".concat(typeKindName(oldType), \" to \").concat(typeKindName(newType), \".\")\n });\n }\n }\n\n return breakingChanges;\n}", "function findRemovedTypes(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: typeName + ' was removed.'\n });\n }\n });\n return breakingChanges;\n}", "function findRemovedTypes(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: typeName + ' was removed.'\n });\n }\n });\n return breakingChanges;\n}", "function findRemovedTypes(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var breakingChanges = [];\n\n var _arr = Object.keys(oldTypeMap);\n\n for (var _i = 0; _i < _arr.length; _i++) {\n var typeName = _arr[_i];\n\n if (!newTypeMap[typeName]) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: \"\".concat(typeName, \" was removed.\")\n });\n }\n }\n\n return breakingChanges;\n}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).breakingChanges, findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema), findRemovedDirectives(oldSchema, newSchema), findRemovedDirectiveArgs(oldSchema, newSchema), findAddedNonNullDirectiveArgs(oldSchema, newSchema), findRemovedDirectiveLocations(oldSchema, newSchema));\n}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema));\n}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema));\n}", "function findArgChanges(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var breakingChanges = [];\n var dangerousChanges = [];\n\n var _arr3 = Object.keys(oldTypeMap);\n\n for (var _i3 = 0; _i3 < _arr3.length; _i3++) {\n var typeName = _arr3[_i3];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!(Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isObjectType\"])(oldType) || Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isInterfaceType\"])(oldType)) || !(Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isObjectType\"])(newType) || Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isInterfaceType\"])(newType)) || newType.constructor !== oldType.constructor) {\n continue;\n }\n\n var oldTypeFields = oldType.getFields();\n var newTypeFields = newType.getFields();\n\n var _arr4 = Object.keys(oldTypeFields);\n\n for (var _i4 = 0; _i4 < _arr4.length; _i4++) {\n var fieldName = _arr4[_i4];\n\n if (!newTypeFields[fieldName]) {\n continue;\n }\n\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n var _loop = function _loop() {\n var oldArgDef = _step.value;\n var newArgs = newTypeFields[fieldName].args;\n var newArgDef = Object(_polyfills_find__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(newArgs, function (arg) {\n return arg.name === oldArgDef.name;\n }); // Arg not present\n\n if (!newArgDef) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_REMOVED,\n description: \"\".concat(oldType.name, \".\").concat(fieldName, \" arg \") + \"\".concat(oldArgDef.name, \" was removed\")\n });\n } else {\n var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type);\n\n if (!isSafe) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_CHANGED_KIND,\n description: \"\".concat(oldType.name, \".\").concat(fieldName, \" arg \") + \"\".concat(oldArgDef.name, \" has changed type from \") + \"\".concat(oldArgDef.type.toString(), \" to \").concat(newArgDef.type.toString())\n });\n } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) {\n dangerousChanges.push({\n type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,\n description: \"\".concat(oldType.name, \".\").concat(fieldName, \" arg \") + \"\".concat(oldArgDef.name, \" has changed defaultValue\")\n });\n }\n }\n };\n\n for (var _iterator = oldTypeFields[fieldName].args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n _loop();\n } // Check if arg was added to the field\n\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return != null) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n var _loop2 = function _loop2() {\n var newArgDef = _step2.value;\n var oldArgs = oldTypeFields[fieldName].args;\n var oldArgDef = Object(_polyfills_find__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(oldArgs, function (arg) {\n return arg.name === newArgDef.name;\n });\n\n if (!oldArgDef) {\n var argName = newArgDef.name;\n\n if (Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isRequiredArgument\"])(newArgDef)) {\n breakingChanges.push({\n type: BreakingChangeType.REQUIRED_ARG_ADDED,\n description: \"A required arg \".concat(argName, \" on \") + \"\".concat(typeName, \".\").concat(fieldName, \" was added\")\n });\n } else {\n dangerousChanges.push({\n type: DangerousChangeType.OPTIONAL_ARG_ADDED,\n description: \"An optional arg \".concat(argName, \" on \") + \"\".concat(typeName, \".\").concat(fieldName, \" was added\")\n });\n }\n }\n };\n\n for (var _iterator2 = newTypeFields[fieldName].args[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n _loop2();\n }\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return != null) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n }\n }\n\n return {\n breakingChanges: breakingChanges,\n dangerousChanges: dangerousChanges\n };\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n return [].concat(findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema));\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n return [].concat(findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema));\n}", "function findArgChanges(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n var dangerousChanges = [];\n\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType) || !(newType instanceof oldType.constructor)) {\n return;\n }\n\n var oldTypeFields = oldType.getFields();\n var newTypeFields = newType.getFields();\n\n Object.keys(oldTypeFields).forEach(function (fieldName) {\n if (!newTypeFields[fieldName]) {\n return;\n }\n\n oldTypeFields[fieldName].args.forEach(function (oldArgDef) {\n var newArgs = newTypeFields[fieldName].args;\n var newArgDef = newArgs.find(function (arg) {\n return arg.name === oldArgDef.name;\n });\n\n // Arg not present\n if (!newArgDef) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_REMOVED,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' was removed')\n });\n } else {\n var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type);\n if (!isSafe) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_CHANGED_KIND,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed type from ') + (oldArgDef.type.toString() + ' to ' + newArgDef.type.toString())\n });\n } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) {\n dangerousChanges.push({\n type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed defaultValue')\n });\n }\n }\n });\n // Check if a non-null arg was added to the field\n newTypeFields[fieldName].args.forEach(function (newArgDef) {\n var oldArgs = oldTypeFields[fieldName].args;\n var oldArgDef = oldArgs.find(function (arg) {\n return arg.name === newArgDef.name;\n });\n if (!oldArgDef && newArgDef.type instanceof _definition.GraphQLNonNull) {\n breakingChanges.push({\n type: BreakingChangeType.NON_NULL_ARG_ADDED,\n description: 'A non-null arg ' + newArgDef.name + ' on ' + (newType.name + '.' + fieldName + ' was added')\n });\n }\n });\n });\n });\n\n return {\n breakingChanges: breakingChanges,\n dangerousChanges: dangerousChanges\n };\n}", "function findArgChanges(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n var dangerousChanges = [];\n\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType) || !(newType instanceof oldType.constructor)) {\n return;\n }\n\n var oldTypeFields = oldType.getFields();\n var newTypeFields = newType.getFields();\n\n Object.keys(oldTypeFields).forEach(function (fieldName) {\n if (!newTypeFields[fieldName]) {\n return;\n }\n\n oldTypeFields[fieldName].args.forEach(function (oldArgDef) {\n var newArgs = newTypeFields[fieldName].args;\n var newArgDef = newArgs.find(function (arg) {\n return arg.name === oldArgDef.name;\n });\n\n // Arg not present\n if (!newArgDef) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_REMOVED,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' was removed')\n });\n } else {\n var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type);\n if (!isSafe) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_CHANGED_KIND,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed type from ') + (oldArgDef.type.toString() + ' to ' + newArgDef.type.toString())\n });\n } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) {\n dangerousChanges.push({\n type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed defaultValue')\n });\n }\n }\n });\n // Check if a non-null arg was added to the field\n newTypeFields[fieldName].args.forEach(function (newArgDef) {\n var oldArgs = oldTypeFields[fieldName].args;\n var oldArgDef = oldArgs.find(function (arg) {\n return arg.name === newArgDef.name;\n });\n if (!oldArgDef && newArgDef.type instanceof _definition.GraphQLNonNull) {\n breakingChanges.push({\n type: BreakingChangeType.NON_NULL_ARG_ADDED,\n description: 'A non-null arg ' + newArgDef.name + ' on ' + (newType.name + '.' + fieldName + ' was added')\n });\n }\n });\n });\n });\n\n return {\n breakingChanges: breakingChanges,\n dangerousChanges: dangerousChanges\n };\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingFieldChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType || oldType instanceof _definition.GraphQLInputObjectType) || !(newType instanceof oldType.constructor)) {\n\t return;\n\t }\n\n\t var oldTypeFieldsDef = oldType.getFields();\n\t var newTypeFieldsDef = newType.getFields();\n\t Object.keys(oldTypeFieldsDef).forEach(function (fieldName) {\n\t // Check if the field is missing on the type in the new schema.\n\t if (!(fieldName in newTypeFieldsDef)) {\n\t breakingFieldChanges.push({\n\t type: BreakingChangeType.FIELD_REMOVED,\n\t description: typeName + '.' + fieldName + ' was removed.'\n\t });\n\t } else {\n\t // Check if the field's type has changed in the new schema.\n\t var oldFieldType = (0, _definition.getNamedType)(oldTypeFieldsDef[fieldName].type);\n\t var newFieldType = (0, _definition.getNamedType)(newTypeFieldsDef[fieldName].type);\n\t if (oldFieldType && newFieldType && oldFieldType.name !== newFieldType.name) {\n\t breakingFieldChanges.push({\n\t type: BreakingChangeType.FIELD_CHANGED_KIND,\n\t description: typeName + '.' + fieldName + ' changed type from ' + (oldFieldType.name + ' to ' + newFieldType.name + '.')\n\t });\n\t }\n\t }\n\t });\n\t });\n\t return breakingFieldChanges;\n\t}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var typesRemovedFromUnion = [];\n\n var _arr10 = Object.keys(oldTypeMap);\n\n for (var _i10 = 0; _i10 < _arr10.length; _i10++) {\n var typeName = _arr10[_i10];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(oldType) || !Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(newType)) {\n continue;\n }\n\n var typeNamesInNewUnion = Object.create(null);\n var _iteratorNormalCompletion3 = true;\n var _didIteratorError3 = false;\n var _iteratorError3 = undefined;\n\n try {\n for (var _iterator3 = newType.getTypes()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {\n var type = _step3.value;\n typeNamesInNewUnion[type.name] = true;\n }\n } catch (err) {\n _didIteratorError3 = true;\n _iteratorError3 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion3 && _iterator3.return != null) {\n _iterator3.return();\n }\n } finally {\n if (_didIteratorError3) {\n throw _iteratorError3;\n }\n }\n }\n\n var _iteratorNormalCompletion4 = true;\n var _didIteratorError4 = false;\n var _iteratorError4 = undefined;\n\n try {\n for (var _iterator4 = oldType.getTypes()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {\n var _type = _step4.value;\n\n if (!typeNamesInNewUnion[_type.name]) {\n typesRemovedFromUnion.push({\n type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n description: \"\".concat(_type.name, \" was removed from union type \").concat(typeName, \".\")\n });\n }\n }\n } catch (err) {\n _didIteratorError4 = true;\n _iteratorError4 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion4 && _iterator4.return != null) {\n _iterator4.return();\n }\n } finally {\n if (_didIteratorError4) {\n throw _iteratorError4;\n }\n }\n }\n }\n\n return typesRemovedFromUnion;\n}", "function findBreakingChanges(oldSchema, newSchema) {\n var breakingChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in BreakingChangeType;\n });\n return breakingChanges;\n}", "function findBreakingChanges(oldSchema, newSchema) {\n var breakingChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in BreakingChangeType;\n });\n return breakingChanges;\n}", "function findBreakingChanges(oldSchema, newSchema) {\n var breakingChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in BreakingChangeType;\n });\n return breakingChanges;\n}", "function findTypesAddedToUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var typesAddedToUnion = [];\n\n var _arr11 = Object.keys(newTypeMap);\n\n for (var _i11 = 0; _i11 < _arr11.length; _i11++) {\n var typeName = _arr11[_i11];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(oldType) || !Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(newType)) {\n continue;\n }\n\n var typeNamesInOldUnion = Object.create(null);\n var _iteratorNormalCompletion5 = true;\n var _didIteratorError5 = false;\n var _iteratorError5 = undefined;\n\n try {\n for (var _iterator5 = oldType.getTypes()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {\n var type = _step5.value;\n typeNamesInOldUnion[type.name] = true;\n }\n } catch (err) {\n _didIteratorError5 = true;\n _iteratorError5 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion5 && _iterator5.return != null) {\n _iterator5.return();\n }\n } finally {\n if (_didIteratorError5) {\n throw _iteratorError5;\n }\n }\n }\n\n var _iteratorNormalCompletion6 = true;\n var _didIteratorError6 = false;\n var _iteratorError6 = undefined;\n\n try {\n for (var _iterator6 = newType.getTypes()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {\n var _type2 = _step6.value;\n\n if (!typeNamesInOldUnion[_type2.name]) {\n typesAddedToUnion.push({\n type: DangerousChangeType.TYPE_ADDED_TO_UNION,\n description: \"\".concat(_type2.name, \" was added to union type \").concat(typeName, \".\")\n });\n }\n }\n } catch (err) {\n _didIteratorError6 = true;\n _iteratorError6 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion6 && _iterator6.return != null) {\n _iterator6.return();\n }\n } finally {\n if (_didIteratorError6) {\n throw _iteratorError6;\n }\n }\n }\n }\n\n return typesAddedToUnion;\n}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var typesRemovedFromUnion = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLUnionType) || !(newType instanceof _definition.GraphQLUnionType)) {\n return;\n }\n var typeNamesInNewUnion = Object.create(null);\n newType.getTypes().forEach(function (type) {\n typeNamesInNewUnion[type.name] = true;\n });\n oldType.getTypes().forEach(function (type) {\n if (!typeNamesInNewUnion[type.name]) {\n typesRemovedFromUnion.push({\n type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n description: type.name + ' was removed from union type ' + typeName + '.'\n });\n }\n });\n });\n return typesRemovedFromUnion;\n}" ]
[ "0.7039056", "0.70201594", "0.6972318", "0.6959837", "0.6959837", "0.6959837", "0.6959837", "0.6901334", "0.6893894", "0.6893894", "0.68903375", "0.6874852", "0.6867015", "0.6867015", "0.68197554", "0.67576176", "0.67539984", "0.67539984", "0.65311575", "0.6468782", "0.6468782", "0.64059937", "0.64059937", "0.63073105", "0.61828643", "0.6163264", "0.6163264", "0.6163264", "0.6078276", "0.5928311" ]
0.7191499
0
Given two schemas, returns an Array containing descriptions of any breaking changes in the newSchema related to removing an entire type.
function findRemovedTypes(oldSchema, newSchema) { var oldTypeMap = oldSchema.getTypeMap(); var newTypeMap = newSchema.getTypeMap(); var breakingChanges = []; Object.keys(oldTypeMap).forEach(function (typeName) { if (!newTypeMap[typeName]) { breakingChanges.push({ type: BreakingChangeType.TYPE_REMOVED, description: typeName + ' was removed.' }); } }); return breakingChanges; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function findRemovedTypes(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var breakingChanges = [];\n\n var _arr = Object.keys(oldTypeMap);\n\n for (var _i = 0; _i < _arr.length; _i++) {\n var typeName = _arr[_i];\n\n if (!newTypeMap[typeName]) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: \"\".concat(typeName, \" was removed.\")\n });\n }\n }\n\n return breakingChanges;\n}", "function findRemovedTypes(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t if (!newTypeMap[typeName]) {\n\t breakingChanges.push({\n\t type: BreakingChangeType.TYPE_REMOVED,\n\t description: typeName + ' was removed.'\n\t });\n\t }\n\t });\n\t return breakingChanges;\n\t}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var breakingChanges = [];\n\n var _arr2 = Object.keys(oldTypeMap);\n\n for (var _i2 = 0; _i2 < _arr2.length; _i2++) {\n var typeName = _arr2[_i2];\n\n if (!newTypeMap[typeName]) {\n continue;\n }\n\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (oldType.constructor !== newType.constructor) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: \"\".concat(typeName, \" changed from \") + \"\".concat(typeKindName(oldType), \" to \").concat(typeKindName(newType), \".\")\n });\n }\n }\n\n return breakingChanges;\n}", "function findBreakingChanges(oldSchema, newSchema) {\n\t return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema));\n\t}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n return;\n }\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof newType.constructor)) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n });\n }\n });\n return breakingChanges;\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n return;\n }\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof newType.constructor)) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n });\n }\n });\n return breakingChanges;\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t if (!newTypeMap[typeName]) {\n\t return;\n\t }\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof newType.constructor)) {\n\t breakingChanges.push({\n\t type: BreakingChangeType.TYPE_CHANGED_KIND,\n\t description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n\t });\n\t }\n\t });\n\t return breakingChanges;\n\t}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema));\n}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema));\n}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).breakingChanges, findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema), findRemovedDirectives(oldSchema, newSchema), findRemovedDirectiveArgs(oldSchema, newSchema), findAddedNonNullDirectiveArgs(oldSchema, newSchema), findRemovedDirectiveLocations(oldSchema, newSchema));\n}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var typesRemovedFromUnion = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLUnionType) || !(newType instanceof _definition.GraphQLUnionType)) {\n return;\n }\n var typeNamesInNewUnion = Object.create(null);\n newType.getTypes().forEach(function (type) {\n typeNamesInNewUnion[type.name] = true;\n });\n oldType.getTypes().forEach(function (type) {\n if (!typeNamesInNewUnion[type.name]) {\n typesRemovedFromUnion.push({\n type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n description: type.name + ' was removed from union type ' + typeName + '.'\n });\n }\n });\n });\n return typesRemovedFromUnion;\n}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var typesRemovedFromUnion = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLUnionType) || !(newType instanceof _definition.GraphQLUnionType)) {\n return;\n }\n var typeNamesInNewUnion = Object.create(null);\n newType.getTypes().forEach(function (type) {\n typeNamesInNewUnion[type.name] = true;\n });\n oldType.getTypes().forEach(function (type) {\n if (!typeNamesInNewUnion[type.name]) {\n typesRemovedFromUnion.push({\n type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n description: type.name + ' was removed from union type ' + typeName + '.'\n });\n }\n });\n });\n return typesRemovedFromUnion;\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingFieldChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType || oldType instanceof _definition.GraphQLInputObjectType) || !(newType instanceof oldType.constructor)) {\n\t return;\n\t }\n\n\t var oldTypeFieldsDef = oldType.getFields();\n\t var newTypeFieldsDef = newType.getFields();\n\t Object.keys(oldTypeFieldsDef).forEach(function (fieldName) {\n\t // Check if the field is missing on the type in the new schema.\n\t if (!(fieldName in newTypeFieldsDef)) {\n\t breakingFieldChanges.push({\n\t type: BreakingChangeType.FIELD_REMOVED,\n\t description: typeName + '.' + fieldName + ' was removed.'\n\t });\n\t } else {\n\t // Check if the field's type has changed in the new schema.\n\t var oldFieldType = (0, _definition.getNamedType)(oldTypeFieldsDef[fieldName].type);\n\t var newFieldType = (0, _definition.getNamedType)(newTypeFieldsDef[fieldName].type);\n\t if (oldFieldType && newFieldType && oldFieldType.name !== newFieldType.name) {\n\t breakingFieldChanges.push({\n\t type: BreakingChangeType.FIELD_CHANGED_KIND,\n\t description: typeName + '.' + fieldName + ' changed type from ' + (oldFieldType.name + ' to ' + newFieldType.name + '.')\n\t });\n\t }\n\t }\n\t });\n\t });\n\t return breakingFieldChanges;\n\t}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var typesRemovedFromUnion = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof _definition.GraphQLUnionType) || !(newType instanceof _definition.GraphQLUnionType)) {\n\t return;\n\t }\n\t var typeNamesInNewUnion = Object.create(null);\n\t newType.getTypes().forEach(function (type) {\n\t typeNamesInNewUnion[type.name] = true;\n\t });\n\t oldType.getTypes().forEach(function (type) {\n\t if (!typeNamesInNewUnion[type.name]) {\n\t typesRemovedFromUnion.push({\n\t type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n\t description: type.name + ' was removed from union type ' + typeName + '.'\n\t });\n\t }\n\t });\n\t });\n\t return typesRemovedFromUnion;\n\t}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var typesRemovedFromUnion = [];\n\n var _arr10 = Object.keys(oldTypeMap);\n\n for (var _i10 = 0; _i10 < _arr10.length; _i10++) {\n var typeName = _arr10[_i10];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(oldType) || !Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(newType)) {\n continue;\n }\n\n var typeNamesInNewUnion = Object.create(null);\n var _iteratorNormalCompletion3 = true;\n var _didIteratorError3 = false;\n var _iteratorError3 = undefined;\n\n try {\n for (var _iterator3 = newType.getTypes()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {\n var type = _step3.value;\n typeNamesInNewUnion[type.name] = true;\n }\n } catch (err) {\n _didIteratorError3 = true;\n _iteratorError3 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion3 && _iterator3.return != null) {\n _iterator3.return();\n }\n } finally {\n if (_didIteratorError3) {\n throw _iteratorError3;\n }\n }\n }\n\n var _iteratorNormalCompletion4 = true;\n var _didIteratorError4 = false;\n var _iteratorError4 = undefined;\n\n try {\n for (var _iterator4 = oldType.getTypes()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {\n var _type = _step4.value;\n\n if (!typeNamesInNewUnion[_type.name]) {\n typesRemovedFromUnion.push({\n type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n description: \"\".concat(_type.name, \" was removed from union type \").concat(typeName, \".\")\n });\n }\n }\n } catch (err) {\n _didIteratorError4 = true;\n _iteratorError4 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion4 && _iterator4.return != null) {\n _iterator4.return();\n }\n } finally {\n if (_didIteratorError4) {\n throw _iteratorError4;\n }\n }\n }\n }\n\n return typesRemovedFromUnion;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges, findValuesAddedToEnums(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema));\n}", "function findBreakingChanges(oldSchema, newSchema) {\n var breakingChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in BreakingChangeType;\n });\n return breakingChanges;\n}", "function findBreakingChanges(oldSchema, newSchema) {\n var breakingChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in BreakingChangeType;\n });\n return breakingChanges;\n}", "function findBreakingChanges(oldSchema, newSchema) {\n var breakingChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in BreakingChangeType;\n });\n return breakingChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findArgChanges(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var breakingChanges = [];\n var dangerousChanges = [];\n\n var _arr3 = Object.keys(oldTypeMap);\n\n for (var _i3 = 0; _i3 < _arr3.length; _i3++) {\n var typeName = _arr3[_i3];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!(Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isObjectType\"])(oldType) || Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isInterfaceType\"])(oldType)) || !(Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isObjectType\"])(newType) || Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isInterfaceType\"])(newType)) || newType.constructor !== oldType.constructor) {\n continue;\n }\n\n var oldTypeFields = oldType.getFields();\n var newTypeFields = newType.getFields();\n\n var _arr4 = Object.keys(oldTypeFields);\n\n for (var _i4 = 0; _i4 < _arr4.length; _i4++) {\n var fieldName = _arr4[_i4];\n\n if (!newTypeFields[fieldName]) {\n continue;\n }\n\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n var _loop = function _loop() {\n var oldArgDef = _step.value;\n var newArgs = newTypeFields[fieldName].args;\n var newArgDef = Object(_polyfills_find__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(newArgs, function (arg) {\n return arg.name === oldArgDef.name;\n }); // Arg not present\n\n if (!newArgDef) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_REMOVED,\n description: \"\".concat(oldType.name, \".\").concat(fieldName, \" arg \") + \"\".concat(oldArgDef.name, \" was removed\")\n });\n } else {\n var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type);\n\n if (!isSafe) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_CHANGED_KIND,\n description: \"\".concat(oldType.name, \".\").concat(fieldName, \" arg \") + \"\".concat(oldArgDef.name, \" has changed type from \") + \"\".concat(oldArgDef.type.toString(), \" to \").concat(newArgDef.type.toString())\n });\n } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) {\n dangerousChanges.push({\n type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,\n description: \"\".concat(oldType.name, \".\").concat(fieldName, \" arg \") + \"\".concat(oldArgDef.name, \" has changed defaultValue\")\n });\n }\n }\n };\n\n for (var _iterator = oldTypeFields[fieldName].args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n _loop();\n } // Check if arg was added to the field\n\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return != null) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n var _loop2 = function _loop2() {\n var newArgDef = _step2.value;\n var oldArgs = oldTypeFields[fieldName].args;\n var oldArgDef = Object(_polyfills_find__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(oldArgs, function (arg) {\n return arg.name === newArgDef.name;\n });\n\n if (!oldArgDef) {\n var argName = newArgDef.name;\n\n if (Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isRequiredArgument\"])(newArgDef)) {\n breakingChanges.push({\n type: BreakingChangeType.REQUIRED_ARG_ADDED,\n description: \"A required arg \".concat(argName, \" on \") + \"\".concat(typeName, \".\").concat(fieldName, \" was added\")\n });\n } else {\n dangerousChanges.push({\n type: DangerousChangeType.OPTIONAL_ARG_ADDED,\n description: \"An optional arg \".concat(argName, \" on \") + \"\".concat(typeName, \".\").concat(fieldName, \" was added\")\n });\n }\n }\n };\n\n for (var _iterator2 = newTypeFields[fieldName].args[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n _loop2();\n }\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return != null) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n }\n }\n\n return {\n breakingChanges: breakingChanges,\n dangerousChanges: dangerousChanges\n };\n}", "function findDangerousChanges(oldSchema, newSchema) {\n return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges);\n}", "function findDangerousChanges(oldSchema, newSchema) {\n return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges, findValuesAddedToEnums(oldSchema, newSchema), findInterfacesAddedToObjectTypes(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).dangerousChanges);\n}", "function findArgChanges(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n var dangerousChanges = [];\n\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType) || !(newType instanceof oldType.constructor)) {\n return;\n }\n\n var oldTypeFields = oldType.getFields();\n var newTypeFields = newType.getFields();\n\n Object.keys(oldTypeFields).forEach(function (fieldName) {\n if (!newTypeFields[fieldName]) {\n return;\n }\n\n oldTypeFields[fieldName].args.forEach(function (oldArgDef) {\n var newArgs = newTypeFields[fieldName].args;\n var newArgDef = newArgs.find(function (arg) {\n return arg.name === oldArgDef.name;\n });\n\n // Arg not present\n if (!newArgDef) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_REMOVED,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' was removed')\n });\n } else {\n var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type);\n if (!isSafe) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_CHANGED_KIND,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed type from ') + (oldArgDef.type.toString() + ' to ' + newArgDef.type.toString())\n });\n } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) {\n dangerousChanges.push({\n type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed defaultValue')\n });\n }\n }\n });\n // Check if a non-null arg was added to the field\n newTypeFields[fieldName].args.forEach(function (newArgDef) {\n var oldArgs = oldTypeFields[fieldName].args;\n var oldArgDef = oldArgs.find(function (arg) {\n return arg.name === newArgDef.name;\n });\n if (!oldArgDef && newArgDef.type instanceof _definition.GraphQLNonNull) {\n breakingChanges.push({\n type: BreakingChangeType.NON_NULL_ARG_ADDED,\n description: 'A non-null arg ' + newArgDef.name + ' on ' + (newType.name + '.' + fieldName + ' was added')\n });\n }\n });\n });\n });\n\n return {\n breakingChanges: breakingChanges,\n dangerousChanges: dangerousChanges\n };\n}", "function findArgChanges(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n var dangerousChanges = [];\n\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType) || !(newType instanceof oldType.constructor)) {\n return;\n }\n\n var oldTypeFields = oldType.getFields();\n var newTypeFields = newType.getFields();\n\n Object.keys(oldTypeFields).forEach(function (fieldName) {\n if (!newTypeFields[fieldName]) {\n return;\n }\n\n oldTypeFields[fieldName].args.forEach(function (oldArgDef) {\n var newArgs = newTypeFields[fieldName].args;\n var newArgDef = newArgs.find(function (arg) {\n return arg.name === oldArgDef.name;\n });\n\n // Arg not present\n if (!newArgDef) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_REMOVED,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' was removed')\n });\n } else {\n var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type);\n if (!isSafe) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_CHANGED_KIND,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed type from ') + (oldArgDef.type.toString() + ' to ' + newArgDef.type.toString())\n });\n } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) {\n dangerousChanges.push({\n type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed defaultValue')\n });\n }\n }\n });\n // Check if a non-null arg was added to the field\n newTypeFields[fieldName].args.forEach(function (newArgDef) {\n var oldArgs = oldTypeFields[fieldName].args;\n var oldArgDef = oldArgs.find(function (arg) {\n return arg.name === newArgDef.name;\n });\n if (!oldArgDef && newArgDef.type instanceof _definition.GraphQLNonNull) {\n breakingChanges.push({\n type: BreakingChangeType.NON_NULL_ARG_ADDED,\n description: 'A non-null arg ' + newArgDef.name + ' on ' + (newType.name + '.' + fieldName + ' was added')\n });\n }\n });\n });\n });\n\n return {\n breakingChanges: breakingChanges,\n dangerousChanges: dangerousChanges\n };\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n return [].concat(findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema));\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n return [].concat(findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema));\n}" ]
[ "0.8176876", "0.814868", "0.7263231", "0.7255352", "0.72205025", "0.72205025", "0.7170979", "0.70155483", "0.70155483", "0.697916", "0.69538426", "0.69538426", "0.6949668", "0.6916142", "0.6904582", "0.67299575", "0.67047393", "0.67047393", "0.67047393", "0.66956633", "0.66956633", "0.66956633", "0.66956633", "0.6673966", "0.6610048", "0.6536963", "0.6414831", "0.6414831", "0.6377831", "0.6377831" ]
0.82110786
1
Given two schemas, returns an Array containing descriptions of any breaking or dangerous changes in the newSchema related to arguments (such as removal or change of type of an argument, or a change in an argument's default value).
function findArgChanges(oldSchema, newSchema) { var oldTypeMap = oldSchema.getTypeMap(); var newTypeMap = newSchema.getTypeMap(); var breakingChanges = []; var dangerousChanges = []; Object.keys(oldTypeMap).forEach(function (typeName) { var oldType = oldTypeMap[typeName]; var newType = newTypeMap[typeName]; if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType) || !(newType instanceof oldType.constructor)) { return; } var oldTypeFields = oldType.getFields(); var newTypeFields = newType.getFields(); Object.keys(oldTypeFields).forEach(function (fieldName) { if (!newTypeFields[fieldName]) { return; } oldTypeFields[fieldName].args.forEach(function (oldArgDef) { var newArgs = newTypeFields[fieldName].args; var newArgDef = newArgs.find(function (arg) { return arg.name === oldArgDef.name; }); // Arg not present if (!newArgDef) { breakingChanges.push({ type: BreakingChangeType.ARG_REMOVED, description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' was removed') }); } else { var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type); if (!isSafe) { breakingChanges.push({ type: BreakingChangeType.ARG_CHANGED_KIND, description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed type from ') + (oldArgDef.type.toString() + ' to ' + newArgDef.type.toString()) }); } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) { dangerousChanges.push({ type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed defaultValue') }); } } }); // Check if a non-null arg was added to the field newTypeFields[fieldName].args.forEach(function (newArgDef) { var oldArgs = oldTypeFields[fieldName].args; var oldArgDef = oldArgs.find(function (arg) { return arg.name === newArgDef.name; }); if (!oldArgDef && newArgDef.type instanceof _definition.GraphQLNonNull) { breakingChanges.push({ type: BreakingChangeType.NON_NULL_ARG_ADDED, description: 'A non-null arg ' + newArgDef.name + ' on ' + (newType.name + '.' + fieldName + ' was added') }); } }); }); }); return { breakingChanges: breakingChanges, dangerousChanges: dangerousChanges }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function findArgChanges(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var breakingChanges = [];\n var dangerousChanges = [];\n\n var _arr3 = Object.keys(oldTypeMap);\n\n for (var _i3 = 0; _i3 < _arr3.length; _i3++) {\n var typeName = _arr3[_i3];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!(Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isObjectType\"])(oldType) || Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isInterfaceType\"])(oldType)) || !(Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isObjectType\"])(newType) || Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isInterfaceType\"])(newType)) || newType.constructor !== oldType.constructor) {\n continue;\n }\n\n var oldTypeFields = oldType.getFields();\n var newTypeFields = newType.getFields();\n\n var _arr4 = Object.keys(oldTypeFields);\n\n for (var _i4 = 0; _i4 < _arr4.length; _i4++) {\n var fieldName = _arr4[_i4];\n\n if (!newTypeFields[fieldName]) {\n continue;\n }\n\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n var _loop = function _loop() {\n var oldArgDef = _step.value;\n var newArgs = newTypeFields[fieldName].args;\n var newArgDef = Object(_polyfills_find__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(newArgs, function (arg) {\n return arg.name === oldArgDef.name;\n }); // Arg not present\n\n if (!newArgDef) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_REMOVED,\n description: \"\".concat(oldType.name, \".\").concat(fieldName, \" arg \") + \"\".concat(oldArgDef.name, \" was removed\")\n });\n } else {\n var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type);\n\n if (!isSafe) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_CHANGED_KIND,\n description: \"\".concat(oldType.name, \".\").concat(fieldName, \" arg \") + \"\".concat(oldArgDef.name, \" has changed type from \") + \"\".concat(oldArgDef.type.toString(), \" to \").concat(newArgDef.type.toString())\n });\n } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) {\n dangerousChanges.push({\n type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,\n description: \"\".concat(oldType.name, \".\").concat(fieldName, \" arg \") + \"\".concat(oldArgDef.name, \" has changed defaultValue\")\n });\n }\n }\n };\n\n for (var _iterator = oldTypeFields[fieldName].args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n _loop();\n } // Check if arg was added to the field\n\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return != null) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n var _loop2 = function _loop2() {\n var newArgDef = _step2.value;\n var oldArgs = oldTypeFields[fieldName].args;\n var oldArgDef = Object(_polyfills_find__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(oldArgs, function (arg) {\n return arg.name === newArgDef.name;\n });\n\n if (!oldArgDef) {\n var argName = newArgDef.name;\n\n if (Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isRequiredArgument\"])(newArgDef)) {\n breakingChanges.push({\n type: BreakingChangeType.REQUIRED_ARG_ADDED,\n description: \"A required arg \".concat(argName, \" on \") + \"\".concat(typeName, \".\").concat(fieldName, \" was added\")\n });\n } else {\n dangerousChanges.push({\n type: DangerousChangeType.OPTIONAL_ARG_ADDED,\n description: \"An optional arg \".concat(argName, \" on \") + \"\".concat(typeName, \".\").concat(fieldName, \" was added\")\n });\n }\n }\n };\n\n for (var _iterator2 = newTypeFields[fieldName].args[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n _loop2();\n }\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return != null) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n }\n }\n\n return {\n breakingChanges: breakingChanges,\n dangerousChanges: dangerousChanges\n };\n}", "function findDangerousChanges(oldSchema, newSchema) {\n return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges);\n}", "function findDangerousChanges(oldSchema, newSchema) {\n return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges, findValuesAddedToEnums(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema));\n}", "function findDangerousChanges(oldSchema, newSchema) {\n return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges, findValuesAddedToEnums(oldSchema, newSchema), findInterfacesAddedToObjectTypes(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).dangerousChanges);\n}", "function findBreakingChanges(oldSchema, newSchema) {\n\t return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema));\n\t}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema));\n}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema));\n}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).breakingChanges, findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema), findRemovedDirectives(oldSchema, newSchema), findRemovedDirectiveArgs(oldSchema, newSchema), findAddedNonNullDirectiveArgs(oldSchema, newSchema), findRemovedDirectiveLocations(oldSchema, newSchema));\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var breakingChanges = [];\n\n var _arr2 = Object.keys(oldTypeMap);\n\n for (var _i2 = 0; _i2 < _arr2.length; _i2++) {\n var typeName = _arr2[_i2];\n\n if (!newTypeMap[typeName]) {\n continue;\n }\n\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (oldType.constructor !== newType.constructor) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: \"\".concat(typeName, \" changed from \") + \"\".concat(typeKindName(oldType), \" to \").concat(typeKindName(newType), \".\")\n });\n }\n }\n\n return breakingChanges;\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n return;\n }\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof newType.constructor)) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n });\n }\n });\n return breakingChanges;\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n return;\n }\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof newType.constructor)) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n });\n }\n });\n return breakingChanges;\n}", "function findRemovedTypes(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: typeName + ' was removed.'\n });\n }\n });\n return breakingChanges;\n}", "function findRemovedTypes(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: typeName + ' was removed.'\n });\n }\n });\n return breakingChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t if (!newTypeMap[typeName]) {\n\t return;\n\t }\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof newType.constructor)) {\n\t breakingChanges.push({\n\t type: BreakingChangeType.TYPE_CHANGED_KIND,\n\t description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n\t });\n\t }\n\t });\n\t return breakingChanges;\n\t}", "function findRemovedTypes(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t if (!newTypeMap[typeName]) {\n\t breakingChanges.push({\n\t type: BreakingChangeType.TYPE_REMOVED,\n\t description: typeName + ' was removed.'\n\t });\n\t }\n\t });\n\t return breakingChanges;\n\t}", "function findRemovedTypes(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var breakingChanges = [];\n\n var _arr = Object.keys(oldTypeMap);\n\n for (var _i = 0; _i < _arr.length; _i++) {\n var typeName = _arr[_i];\n\n if (!newTypeMap[typeName]) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: \"\".concat(typeName, \" was removed.\")\n });\n }\n }\n\n return breakingChanges;\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingFieldChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType || oldType instanceof _definition.GraphQLInputObjectType) || !(newType instanceof oldType.constructor)) {\n\t return;\n\t }\n\n\t var oldTypeFieldsDef = oldType.getFields();\n\t var newTypeFieldsDef = newType.getFields();\n\t Object.keys(oldTypeFieldsDef).forEach(function (fieldName) {\n\t // Check if the field is missing on the type in the new schema.\n\t if (!(fieldName in newTypeFieldsDef)) {\n\t breakingFieldChanges.push({\n\t type: BreakingChangeType.FIELD_REMOVED,\n\t description: typeName + '.' + fieldName + ' was removed.'\n\t });\n\t } else {\n\t // Check if the field's type has changed in the new schema.\n\t var oldFieldType = (0, _definition.getNamedType)(oldTypeFieldsDef[fieldName].type);\n\t var newFieldType = (0, _definition.getNamedType)(newTypeFieldsDef[fieldName].type);\n\t if (oldFieldType && newFieldType && oldFieldType.name !== newFieldType.name) {\n\t breakingFieldChanges.push({\n\t type: BreakingChangeType.FIELD_CHANGED_KIND,\n\t description: typeName + '.' + fieldName + ' changed type from ' + (oldFieldType.name + ' to ' + newFieldType.name + '.')\n\t });\n\t }\n\t }\n\t });\n\t });\n\t return breakingFieldChanges;\n\t}", "function findBreakingChanges(oldSchema, newSchema) {\n var breakingChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in BreakingChangeType;\n });\n return breakingChanges;\n}", "function findBreakingChanges(oldSchema, newSchema) {\n var breakingChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in BreakingChangeType;\n });\n return breakingChanges;\n}", "function findBreakingChanges(oldSchema, newSchema) {\n var breakingChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in BreakingChangeType;\n });\n return breakingChanges;\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n return [].concat(findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema));\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n return [].concat(findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema));\n}", "function schemaDiff(comparison) {\n\t// TODO\n\t// TODO\n}", "function findTypesAddedToUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var typesAddedToUnion = [];\n\n var _arr11 = Object.keys(newTypeMap);\n\n for (var _i11 = 0; _i11 < _arr11.length; _i11++) {\n var typeName = _arr11[_i11];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(oldType) || !Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(newType)) {\n continue;\n }\n\n var typeNamesInOldUnion = Object.create(null);\n var _iteratorNormalCompletion5 = true;\n var _didIteratorError5 = false;\n var _iteratorError5 = undefined;\n\n try {\n for (var _iterator5 = oldType.getTypes()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {\n var type = _step5.value;\n typeNamesInOldUnion[type.name] = true;\n }\n } catch (err) {\n _didIteratorError5 = true;\n _iteratorError5 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion5 && _iterator5.return != null) {\n _iterator5.return();\n }\n } finally {\n if (_didIteratorError5) {\n throw _iteratorError5;\n }\n }\n }\n\n var _iteratorNormalCompletion6 = true;\n var _didIteratorError6 = false;\n var _iteratorError6 = undefined;\n\n try {\n for (var _iterator6 = newType.getTypes()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {\n var _type2 = _step6.value;\n\n if (!typeNamesInOldUnion[_type2.name]) {\n typesAddedToUnion.push({\n type: DangerousChangeType.TYPE_ADDED_TO_UNION,\n description: \"\".concat(_type2.name, \" was added to union type \").concat(typeName, \".\")\n });\n }\n }\n } catch (err) {\n _didIteratorError6 = true;\n _iteratorError6 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion6 && _iterator6.return != null) {\n _iterator6.return();\n }\n } finally {\n if (_didIteratorError6) {\n throw _iteratorError6;\n }\n }\n }\n }\n\n return typesAddedToUnion;\n}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var typesRemovedFromUnion = [];\n\n var _arr10 = Object.keys(oldTypeMap);\n\n for (var _i10 = 0; _i10 < _arr10.length; _i10++) {\n var typeName = _arr10[_i10];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(oldType) || !Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(newType)) {\n continue;\n }\n\n var typeNamesInNewUnion = Object.create(null);\n var _iteratorNormalCompletion3 = true;\n var _didIteratorError3 = false;\n var _iteratorError3 = undefined;\n\n try {\n for (var _iterator3 = newType.getTypes()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {\n var type = _step3.value;\n typeNamesInNewUnion[type.name] = true;\n }\n } catch (err) {\n _didIteratorError3 = true;\n _iteratorError3 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion3 && _iterator3.return != null) {\n _iterator3.return();\n }\n } finally {\n if (_didIteratorError3) {\n throw _iteratorError3;\n }\n }\n }\n\n var _iteratorNormalCompletion4 = true;\n var _didIteratorError4 = false;\n var _iteratorError4 = undefined;\n\n try {\n for (var _iterator4 = oldType.getTypes()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {\n var _type = _step4.value;\n\n if (!typeNamesInNewUnion[_type.name]) {\n typesRemovedFromUnion.push({\n type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n description: \"\".concat(_type.name, \" was removed from union type \").concat(typeName, \".\")\n });\n }\n }\n } catch (err) {\n _didIteratorError4 = true;\n _iteratorError4 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion4 && _iterator4.return != null) {\n _iterator4.return();\n }\n } finally {\n if (_didIteratorError4) {\n throw _iteratorError4;\n }\n }\n }\n }\n\n return typesRemovedFromUnion;\n}", "function findValuesAddedToEnums(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var valuesAddedToEnums = [];\n\n var _arr13 = Object.keys(oldTypeMap);\n\n for (var _i13 = 0; _i13 < _arr13.length; _i13++) {\n var typeName = _arr13[_i13];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isEnumType\"])(oldType) || !Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isEnumType\"])(newType)) {\n continue;\n }\n\n var valuesInOldEnum = Object.create(null);\n var _iteratorNormalCompletion9 = true;\n var _didIteratorError9 = false;\n var _iteratorError9 = undefined;\n\n try {\n for (var _iterator9 = oldType.getValues()[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {\n var value = _step9.value;\n valuesInOldEnum[value.name] = true;\n }\n } catch (err) {\n _didIteratorError9 = true;\n _iteratorError9 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion9 && _iterator9.return != null) {\n _iterator9.return();\n }\n } finally {\n if (_didIteratorError9) {\n throw _iteratorError9;\n }\n }\n }\n\n var _iteratorNormalCompletion10 = true;\n var _didIteratorError10 = false;\n var _iteratorError10 = undefined;\n\n try {\n for (var _iterator10 = newType.getValues()[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {\n var _value2 = _step10.value;\n\n if (!valuesInOldEnum[_value2.name]) {\n valuesAddedToEnums.push({\n type: DangerousChangeType.VALUE_ADDED_TO_ENUM,\n description: \"\".concat(_value2.name, \" was added to enum type \").concat(typeName, \".\")\n });\n }\n }\n } catch (err) {\n _didIteratorError10 = true;\n _iteratorError10 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion10 && _iterator10.return != null) {\n _iterator10.return();\n }\n } finally {\n if (_didIteratorError10) {\n throw _iteratorError10;\n }\n }\n }\n }\n\n return valuesAddedToEnums;\n}" ]
[ "0.7709526", "0.7294602", "0.72251356", "0.7023517", "0.69008", "0.689002", "0.689002", "0.6832358", "0.6598981", "0.65873826", "0.65873826", "0.65614253", "0.65614253", "0.6555589", "0.6555589", "0.6555589", "0.6555589", "0.6539358", "0.6526367", "0.64818496", "0.6415634", "0.64154804", "0.64154804", "0.64154804", "0.6409958", "0.6409958", "0.6013059", "0.56752557", "0.5668663", "0.5622021" ]
0.7818474
1
Given two schemas, returns an Array containing descriptions of any dangerous changes in the newSchema related to adding types to a union type.
function findTypesAddedToUnions(oldSchema, newSchema) { var oldTypeMap = oldSchema.getTypeMap(); var newTypeMap = newSchema.getTypeMap(); var typesAddedToUnion = []; Object.keys(newTypeMap).forEach(function (typeName) { var oldType = oldTypeMap[typeName]; var newType = newTypeMap[typeName]; if (!(oldType instanceof _definition.GraphQLUnionType) || !(newType instanceof _definition.GraphQLUnionType)) { return; } var typeNamesInOldUnion = Object.create(null); oldType.getTypes().forEach(function (type) { typeNamesInOldUnion[type.name] = true; }); newType.getTypes().forEach(function (type) { if (!typeNamesInOldUnion[type.name]) { typesAddedToUnion.push({ type: DangerousChangeType.TYPE_ADDED_TO_UNION, description: type.name + ' was added to union type ' + typeName + '.' }); } }); }); return typesAddedToUnion; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function findTypesAddedToUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var typesAddedToUnion = [];\n\n var _arr11 = Object.keys(newTypeMap);\n\n for (var _i11 = 0; _i11 < _arr11.length; _i11++) {\n var typeName = _arr11[_i11];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(oldType) || !Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(newType)) {\n continue;\n }\n\n var typeNamesInOldUnion = Object.create(null);\n var _iteratorNormalCompletion5 = true;\n var _didIteratorError5 = false;\n var _iteratorError5 = undefined;\n\n try {\n for (var _iterator5 = oldType.getTypes()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {\n var type = _step5.value;\n typeNamesInOldUnion[type.name] = true;\n }\n } catch (err) {\n _didIteratorError5 = true;\n _iteratorError5 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion5 && _iterator5.return != null) {\n _iterator5.return();\n }\n } finally {\n if (_didIteratorError5) {\n throw _iteratorError5;\n }\n }\n }\n\n var _iteratorNormalCompletion6 = true;\n var _didIteratorError6 = false;\n var _iteratorError6 = undefined;\n\n try {\n for (var _iterator6 = newType.getTypes()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {\n var _type2 = _step6.value;\n\n if (!typeNamesInOldUnion[_type2.name]) {\n typesAddedToUnion.push({\n type: DangerousChangeType.TYPE_ADDED_TO_UNION,\n description: \"\".concat(_type2.name, \" was added to union type \").concat(typeName, \".\")\n });\n }\n }\n } catch (err) {\n _didIteratorError6 = true;\n _iteratorError6 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion6 && _iterator6.return != null) {\n _iterator6.return();\n }\n } finally {\n if (_didIteratorError6) {\n throw _iteratorError6;\n }\n }\n }\n }\n\n return typesAddedToUnion;\n}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var typesRemovedFromUnion = [];\n\n var _arr10 = Object.keys(oldTypeMap);\n\n for (var _i10 = 0; _i10 < _arr10.length; _i10++) {\n var typeName = _arr10[_i10];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(oldType) || !Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(newType)) {\n continue;\n }\n\n var typeNamesInNewUnion = Object.create(null);\n var _iteratorNormalCompletion3 = true;\n var _didIteratorError3 = false;\n var _iteratorError3 = undefined;\n\n try {\n for (var _iterator3 = newType.getTypes()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {\n var type = _step3.value;\n typeNamesInNewUnion[type.name] = true;\n }\n } catch (err) {\n _didIteratorError3 = true;\n _iteratorError3 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion3 && _iterator3.return != null) {\n _iterator3.return();\n }\n } finally {\n if (_didIteratorError3) {\n throw _iteratorError3;\n }\n }\n }\n\n var _iteratorNormalCompletion4 = true;\n var _didIteratorError4 = false;\n var _iteratorError4 = undefined;\n\n try {\n for (var _iterator4 = oldType.getTypes()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {\n var _type = _step4.value;\n\n if (!typeNamesInNewUnion[_type.name]) {\n typesRemovedFromUnion.push({\n type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n description: \"\".concat(_type.name, \" was removed from union type \").concat(typeName, \".\")\n });\n }\n }\n } catch (err) {\n _didIteratorError4 = true;\n _iteratorError4 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion4 && _iterator4.return != null) {\n _iterator4.return();\n }\n } finally {\n if (_didIteratorError4) {\n throw _iteratorError4;\n }\n }\n }\n }\n\n return typesRemovedFromUnion;\n}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var typesRemovedFromUnion = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLUnionType) || !(newType instanceof _definition.GraphQLUnionType)) {\n return;\n }\n var typeNamesInNewUnion = Object.create(null);\n newType.getTypes().forEach(function (type) {\n typeNamesInNewUnion[type.name] = true;\n });\n oldType.getTypes().forEach(function (type) {\n if (!typeNamesInNewUnion[type.name]) {\n typesRemovedFromUnion.push({\n type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n description: type.name + ' was removed from union type ' + typeName + '.'\n });\n }\n });\n });\n return typesRemovedFromUnion;\n}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var typesRemovedFromUnion = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLUnionType) || !(newType instanceof _definition.GraphQLUnionType)) {\n return;\n }\n var typeNamesInNewUnion = Object.create(null);\n newType.getTypes().forEach(function (type) {\n typeNamesInNewUnion[type.name] = true;\n });\n oldType.getTypes().forEach(function (type) {\n if (!typeNamesInNewUnion[type.name]) {\n typesRemovedFromUnion.push({\n type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n description: type.name + ' was removed from union type ' + typeName + '.'\n });\n }\n });\n });\n return typesRemovedFromUnion;\n}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var typesRemovedFromUnion = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof _definition.GraphQLUnionType) || !(newType instanceof _definition.GraphQLUnionType)) {\n\t return;\n\t }\n\t var typeNamesInNewUnion = Object.create(null);\n\t newType.getTypes().forEach(function (type) {\n\t typeNamesInNewUnion[type.name] = true;\n\t });\n\t oldType.getTypes().forEach(function (type) {\n\t if (!typeNamesInNewUnion[type.name]) {\n\t typesRemovedFromUnion.push({\n\t type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n\t description: type.name + ' was removed from union type ' + typeName + '.'\n\t });\n\t }\n\t });\n\t });\n\t return typesRemovedFromUnion;\n\t}", "function findRemovedTypes(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t if (!newTypeMap[typeName]) {\n\t breakingChanges.push({\n\t type: BreakingChangeType.TYPE_REMOVED,\n\t description: typeName + ' was removed.'\n\t });\n\t }\n\t });\n\t return breakingChanges;\n\t}", "function findRemovedTypes(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: typeName + ' was removed.'\n });\n }\n });\n return breakingChanges;\n}", "function findRemovedTypes(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: typeName + ' was removed.'\n });\n }\n });\n return breakingChanges;\n}", "function findRemovedTypes(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var breakingChanges = [];\n\n var _arr = Object.keys(oldTypeMap);\n\n for (var _i = 0; _i < _arr.length; _i++) {\n var typeName = _arr[_i];\n\n if (!newTypeMap[typeName]) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: \"\".concat(typeName, \" was removed.\")\n });\n }\n }\n\n return breakingChanges;\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t if (!newTypeMap[typeName]) {\n\t return;\n\t }\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof newType.constructor)) {\n\t breakingChanges.push({\n\t type: BreakingChangeType.TYPE_CHANGED_KIND,\n\t description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n\t });\n\t }\n\t });\n\t return breakingChanges;\n\t}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n return;\n }\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof newType.constructor)) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n });\n }\n });\n return breakingChanges;\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n return;\n }\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof newType.constructor)) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n });\n }\n });\n return breakingChanges;\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var breakingChanges = [];\n\n var _arr2 = Object.keys(oldTypeMap);\n\n for (var _i2 = 0; _i2 < _arr2.length; _i2++) {\n var typeName = _arr2[_i2];\n\n if (!newTypeMap[typeName]) {\n continue;\n }\n\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (oldType.constructor !== newType.constructor) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: \"\".concat(typeName, \" changed from \") + \"\".concat(typeKindName(oldType), \" to \").concat(typeKindName(newType), \".\")\n });\n }\n }\n\n return breakingChanges;\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n return [].concat(findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema));\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n return [].concat(findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema));\n}", "function findDangerousChanges(oldSchema, newSchema) {\n return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges, findValuesAddedToEnums(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema));\n}", "function findValuesAddedToEnums(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var valuesAddedToEnums = [];\n\n var _arr13 = Object.keys(oldTypeMap);\n\n for (var _i13 = 0; _i13 < _arr13.length; _i13++) {\n var typeName = _arr13[_i13];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isEnumType\"])(oldType) || !Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isEnumType\"])(newType)) {\n continue;\n }\n\n var valuesInOldEnum = Object.create(null);\n var _iteratorNormalCompletion9 = true;\n var _didIteratorError9 = false;\n var _iteratorError9 = undefined;\n\n try {\n for (var _iterator9 = oldType.getValues()[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {\n var value = _step9.value;\n valuesInOldEnum[value.name] = true;\n }\n } catch (err) {\n _didIteratorError9 = true;\n _iteratorError9 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion9 && _iterator9.return != null) {\n _iterator9.return();\n }\n } finally {\n if (_didIteratorError9) {\n throw _iteratorError9;\n }\n }\n }\n\n var _iteratorNormalCompletion10 = true;\n var _didIteratorError10 = false;\n var _iteratorError10 = undefined;\n\n try {\n for (var _iterator10 = newType.getValues()[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {\n var _value2 = _step10.value;\n\n if (!valuesInOldEnum[_value2.name]) {\n valuesAddedToEnums.push({\n type: DangerousChangeType.VALUE_ADDED_TO_ENUM,\n description: \"\".concat(_value2.name, \" was added to enum type \").concat(typeName, \".\")\n });\n }\n }\n } catch (err) {\n _didIteratorError10 = true;\n _iteratorError10 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion10 && _iterator10.return != null) {\n _iterator10.return();\n }\n } finally {\n if (_didIteratorError10) {\n throw _iteratorError10;\n }\n }\n }\n }\n\n return valuesAddedToEnums;\n}", "function findBreakingChanges(oldSchema, newSchema) {\n\t return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema));\n\t}", "function findDangerousChanges(oldSchema, newSchema) {\n return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges, findValuesAddedToEnums(oldSchema, newSchema), findInterfacesAddedToObjectTypes(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).dangerousChanges);\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingFieldChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType || oldType instanceof _definition.GraphQLInputObjectType) || !(newType instanceof oldType.constructor)) {\n\t return;\n\t }\n\n\t var oldTypeFieldsDef = oldType.getFields();\n\t var newTypeFieldsDef = newType.getFields();\n\t Object.keys(oldTypeFieldsDef).forEach(function (fieldName) {\n\t // Check if the field is missing on the type in the new schema.\n\t if (!(fieldName in newTypeFieldsDef)) {\n\t breakingFieldChanges.push({\n\t type: BreakingChangeType.FIELD_REMOVED,\n\t description: typeName + '.' + fieldName + ' was removed.'\n\t });\n\t } else {\n\t // Check if the field's type has changed in the new schema.\n\t var oldFieldType = (0, _definition.getNamedType)(oldTypeFieldsDef[fieldName].type);\n\t var newFieldType = (0, _definition.getNamedType)(newTypeFieldsDef[fieldName].type);\n\t if (oldFieldType && newFieldType && oldFieldType.name !== newFieldType.name) {\n\t breakingFieldChanges.push({\n\t type: BreakingChangeType.FIELD_CHANGED_KIND,\n\t description: typeName + '.' + fieldName + ' changed type from ' + (oldFieldType.name + ' to ' + newFieldType.name + '.')\n\t });\n\t }\n\t }\n\t });\n\t });\n\t return breakingFieldChanges;\n\t}", "function findValuesAddedToEnums(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var valuesAddedToEnums = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLEnumType) || !(newType instanceof _definition.GraphQLEnumType)) {\n return;\n }\n\n var valuesInOldEnum = Object.create(null);\n oldType.getValues().forEach(function (value) {\n valuesInOldEnum[value.name] = true;\n });\n newType.getValues().forEach(function (value) {\n if (!valuesInOldEnum[value.name]) {\n valuesAddedToEnums.push({\n type: DangerousChangeType.VALUE_ADDED_TO_ENUM,\n description: value.name + ' was added to enum type ' + typeName + '.'\n });\n }\n });\n });\n return valuesAddedToEnums;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges);\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n var dangerousChanges = findSchemaChanges(oldSchema, newSchema).filter(function (change) {\n return change.type in DangerousChangeType;\n });\n return dangerousChanges;\n}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).breakingChanges, findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema), findRemovedDirectives(oldSchema, newSchema), findRemovedDirectiveArgs(oldSchema, newSchema), findAddedNonNullDirectiveArgs(oldSchema, newSchema), findRemovedDirectiveLocations(oldSchema, newSchema));\n}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema));\n}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema));\n}", "function findArgChanges(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n var dangerousChanges = [];\n\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType) || !(newType instanceof oldType.constructor)) {\n return;\n }\n\n var oldTypeFields = oldType.getFields();\n var newTypeFields = newType.getFields();\n\n Object.keys(oldTypeFields).forEach(function (fieldName) {\n if (!newTypeFields[fieldName]) {\n return;\n }\n\n oldTypeFields[fieldName].args.forEach(function (oldArgDef) {\n var newArgs = newTypeFields[fieldName].args;\n var newArgDef = newArgs.find(function (arg) {\n return arg.name === oldArgDef.name;\n });\n\n // Arg not present\n if (!newArgDef) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_REMOVED,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' was removed')\n });\n } else {\n var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type);\n if (!isSafe) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_CHANGED_KIND,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed type from ') + (oldArgDef.type.toString() + ' to ' + newArgDef.type.toString())\n });\n } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) {\n dangerousChanges.push({\n type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed defaultValue')\n });\n }\n }\n });\n // Check if a non-null arg was added to the field\n newTypeFields[fieldName].args.forEach(function (newArgDef) {\n var oldArgs = oldTypeFields[fieldName].args;\n var oldArgDef = oldArgs.find(function (arg) {\n return arg.name === newArgDef.name;\n });\n if (!oldArgDef && newArgDef.type instanceof _definition.GraphQLNonNull) {\n breakingChanges.push({\n type: BreakingChangeType.NON_NULL_ARG_ADDED,\n description: 'A non-null arg ' + newArgDef.name + ' on ' + (newType.name + '.' + fieldName + ' was added')\n });\n }\n });\n });\n });\n\n return {\n breakingChanges: breakingChanges,\n dangerousChanges: dangerousChanges\n };\n}" ]
[ "0.78702915", "0.76301306", "0.7412617", "0.7412617", "0.74009883", "0.7070576", "0.7035441", "0.7035441", "0.7005445", "0.68193376", "0.68171537", "0.68171537", "0.6798756", "0.6781975", "0.6781975", "0.6754903", "0.65813017", "0.6446255", "0.6431304", "0.63871443", "0.63271374", "0.6208715", "0.61564", "0.61564", "0.61564", "0.61564", "0.6144508", "0.61045563", "0.61045563", "0.6038318" ]
0.7796355
1
Given two schemas, returns an Array containing descriptions of any dangerous changes in the newSchema related to adding values to an enum type.
function findValuesAddedToEnums(oldSchema, newSchema) { var oldTypeMap = oldSchema.getTypeMap(); var newTypeMap = newSchema.getTypeMap(); var valuesAddedToEnums = []; Object.keys(oldTypeMap).forEach(function (typeName) { var oldType = oldTypeMap[typeName]; var newType = newTypeMap[typeName]; if (!(oldType instanceof _definition.GraphQLEnumType) || !(newType instanceof _definition.GraphQLEnumType)) { return; } var valuesInOldEnum = Object.create(null); oldType.getValues().forEach(function (value) { valuesInOldEnum[value.name] = true; }); newType.getValues().forEach(function (value) { if (!valuesInOldEnum[value.name]) { valuesAddedToEnums.push({ type: DangerousChangeType.VALUE_ADDED_TO_ENUM, description: value.name + ' was added to enum type ' + typeName + '.' }); } }); }); return valuesAddedToEnums; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function findValuesAddedToEnums(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var valuesAddedToEnums = [];\n\n var _arr13 = Object.keys(oldTypeMap);\n\n for (var _i13 = 0; _i13 < _arr13.length; _i13++) {\n var typeName = _arr13[_i13];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isEnumType\"])(oldType) || !Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isEnumType\"])(newType)) {\n continue;\n }\n\n var valuesInOldEnum = Object.create(null);\n var _iteratorNormalCompletion9 = true;\n var _didIteratorError9 = false;\n var _iteratorError9 = undefined;\n\n try {\n for (var _iterator9 = oldType.getValues()[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {\n var value = _step9.value;\n valuesInOldEnum[value.name] = true;\n }\n } catch (err) {\n _didIteratorError9 = true;\n _iteratorError9 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion9 && _iterator9.return != null) {\n _iterator9.return();\n }\n } finally {\n if (_didIteratorError9) {\n throw _iteratorError9;\n }\n }\n }\n\n var _iteratorNormalCompletion10 = true;\n var _didIteratorError10 = false;\n var _iteratorError10 = undefined;\n\n try {\n for (var _iterator10 = newType.getValues()[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {\n var _value2 = _step10.value;\n\n if (!valuesInOldEnum[_value2.name]) {\n valuesAddedToEnums.push({\n type: DangerousChangeType.VALUE_ADDED_TO_ENUM,\n description: \"\".concat(_value2.name, \" was added to enum type \").concat(typeName, \".\")\n });\n }\n }\n } catch (err) {\n _didIteratorError10 = true;\n _iteratorError10 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion10 && _iterator10.return != null) {\n _iterator10.return();\n }\n } finally {\n if (_didIteratorError10) {\n throw _iteratorError10;\n }\n }\n }\n }\n\n return valuesAddedToEnums;\n}", "function findValuesRemovedFromEnums(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var valuesRemovedFromEnums = [];\n\n var _arr12 = Object.keys(oldTypeMap);\n\n for (var _i12 = 0; _i12 < _arr12.length; _i12++) {\n var typeName = _arr12[_i12];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isEnumType\"])(oldType) || !Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isEnumType\"])(newType)) {\n continue;\n }\n\n var valuesInNewEnum = Object.create(null);\n var _iteratorNormalCompletion7 = true;\n var _didIteratorError7 = false;\n var _iteratorError7 = undefined;\n\n try {\n for (var _iterator7 = newType.getValues()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {\n var value = _step7.value;\n valuesInNewEnum[value.name] = true;\n }\n } catch (err) {\n _didIteratorError7 = true;\n _iteratorError7 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion7 && _iterator7.return != null) {\n _iterator7.return();\n }\n } finally {\n if (_didIteratorError7) {\n throw _iteratorError7;\n }\n }\n }\n\n var _iteratorNormalCompletion8 = true;\n var _didIteratorError8 = false;\n var _iteratorError8 = undefined;\n\n try {\n for (var _iterator8 = oldType.getValues()[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {\n var _value = _step8.value;\n\n if (!valuesInNewEnum[_value.name]) {\n valuesRemovedFromEnums.push({\n type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM,\n description: \"\".concat(_value.name, \" was removed from enum type \").concat(typeName, \".\")\n });\n }\n }\n } catch (err) {\n _didIteratorError8 = true;\n _iteratorError8 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion8 && _iterator8.return != null) {\n _iterator8.return();\n }\n } finally {\n if (_didIteratorError8) {\n throw _iteratorError8;\n }\n }\n }\n }\n\n return valuesRemovedFromEnums;\n}", "function findValuesRemovedFromEnums(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var valuesRemovedFromEnums = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLEnumType) || !(newType instanceof _definition.GraphQLEnumType)) {\n return;\n }\n var valuesInNewEnum = Object.create(null);\n newType.getValues().forEach(function (value) {\n valuesInNewEnum[value.name] = true;\n });\n oldType.getValues().forEach(function (value) {\n if (!valuesInNewEnum[value.name]) {\n valuesRemovedFromEnums.push({\n type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM,\n description: value.name + ' was removed from enum type ' + typeName + '.'\n });\n }\n });\n });\n return valuesRemovedFromEnums;\n}", "function findValuesRemovedFromEnums(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var valuesRemovedFromEnums = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLEnumType) || !(newType instanceof _definition.GraphQLEnumType)) {\n return;\n }\n var valuesInNewEnum = Object.create(null);\n newType.getValues().forEach(function (value) {\n valuesInNewEnum[value.name] = true;\n });\n oldType.getValues().forEach(function (value) {\n if (!valuesInNewEnum[value.name]) {\n valuesRemovedFromEnums.push({\n type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM,\n description: value.name + ' was removed from enum type ' + typeName + '.'\n });\n }\n });\n });\n return valuesRemovedFromEnums;\n}", "function findValuesRemovedFromEnums(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var valuesRemovedFromEnums = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof _definition.GraphQLEnumType) || !(newType instanceof _definition.GraphQLEnumType)) {\n\t return;\n\t }\n\t var valuesInNewEnum = Object.create(null);\n\t newType.getValues().forEach(function (value) {\n\t valuesInNewEnum[value.name] = true;\n\t });\n\t oldType.getValues().forEach(function (value) {\n\t if (!valuesInNewEnum[value.name]) {\n\t valuesRemovedFromEnums.push({\n\t type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM,\n\t description: value.name + ' was removed from enum type ' + typeName + '.'\n\t });\n\t }\n\t });\n\t });\n\t return valuesRemovedFromEnums;\n\t}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var breakingChanges = [];\n\n var _arr2 = Object.keys(oldTypeMap);\n\n for (var _i2 = 0; _i2 < _arr2.length; _i2++) {\n var typeName = _arr2[_i2];\n\n if (!newTypeMap[typeName]) {\n continue;\n }\n\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (oldType.constructor !== newType.constructor) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: \"\".concat(typeName, \" changed from \") + \"\".concat(typeKindName(oldType), \" to \").concat(typeKindName(newType), \".\")\n });\n }\n }\n\n return breakingChanges;\n}", "function findRemovedTypes(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t if (!newTypeMap[typeName]) {\n\t breakingChanges.push({\n\t type: BreakingChangeType.TYPE_REMOVED,\n\t description: typeName + ' was removed.'\n\t });\n\t }\n\t });\n\t return breakingChanges;\n\t}", "function findRemovedTypes(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: typeName + ' was removed.'\n });\n }\n });\n return breakingChanges;\n}", "function findRemovedTypes(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: typeName + ' was removed.'\n });\n }\n });\n return breakingChanges;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges, findValuesAddedToEnums(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema));\n}", "function findRemovedTypes(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var breakingChanges = [];\n\n var _arr = Object.keys(oldTypeMap);\n\n for (var _i = 0; _i < _arr.length; _i++) {\n var typeName = _arr[_i];\n\n if (!newTypeMap[typeName]) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_REMOVED,\n description: \"\".concat(typeName, \" was removed.\")\n });\n }\n }\n\n return breakingChanges;\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n return;\n }\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof newType.constructor)) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n });\n }\n });\n return breakingChanges;\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n if (!newTypeMap[typeName]) {\n return;\n }\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof newType.constructor)) {\n breakingChanges.push({\n type: BreakingChangeType.TYPE_CHANGED_KIND,\n description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n });\n }\n });\n return breakingChanges;\n}", "function findTypesThatChangedKind(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t if (!newTypeMap[typeName]) {\n\t return;\n\t }\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof newType.constructor)) {\n\t breakingChanges.push({\n\t type: BreakingChangeType.TYPE_CHANGED_KIND,\n\t description: typeName + ' changed from ' + (typeKindName(oldType) + ' to ' + typeKindName(newType) + '.')\n\t });\n\t }\n\t });\n\t return breakingChanges;\n\t}", "function findTypesAddedToUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var typesAddedToUnion = [];\n\n var _arr11 = Object.keys(newTypeMap);\n\n for (var _i11 = 0; _i11 < _arr11.length; _i11++) {\n var typeName = _arr11[_i11];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(oldType) || !Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(newType)) {\n continue;\n }\n\n var typeNamesInOldUnion = Object.create(null);\n var _iteratorNormalCompletion5 = true;\n var _didIteratorError5 = false;\n var _iteratorError5 = undefined;\n\n try {\n for (var _iterator5 = oldType.getTypes()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {\n var type = _step5.value;\n typeNamesInOldUnion[type.name] = true;\n }\n } catch (err) {\n _didIteratorError5 = true;\n _iteratorError5 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion5 && _iterator5.return != null) {\n _iterator5.return();\n }\n } finally {\n if (_didIteratorError5) {\n throw _iteratorError5;\n }\n }\n }\n\n var _iteratorNormalCompletion6 = true;\n var _didIteratorError6 = false;\n var _iteratorError6 = undefined;\n\n try {\n for (var _iterator6 = newType.getTypes()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {\n var _type2 = _step6.value;\n\n if (!typeNamesInOldUnion[_type2.name]) {\n typesAddedToUnion.push({\n type: DangerousChangeType.TYPE_ADDED_TO_UNION,\n description: \"\".concat(_type2.name, \" was added to union type \").concat(typeName, \".\")\n });\n }\n }\n } catch (err) {\n _didIteratorError6 = true;\n _iteratorError6 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion6 && _iterator6.return != null) {\n _iterator6.return();\n }\n } finally {\n if (_didIteratorError6) {\n throw _iteratorError6;\n }\n }\n }\n }\n\n return typesAddedToUnion;\n}", "function findTypesAddedToUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var typesAddedToUnion = [];\n Object.keys(newTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLUnionType) || !(newType instanceof _definition.GraphQLUnionType)) {\n return;\n }\n var typeNamesInOldUnion = Object.create(null);\n oldType.getTypes().forEach(function (type) {\n typeNamesInOldUnion[type.name] = true;\n });\n newType.getTypes().forEach(function (type) {\n if (!typeNamesInOldUnion[type.name]) {\n typesAddedToUnion.push({\n type: DangerousChangeType.TYPE_ADDED_TO_UNION,\n description: type.name + ' was added to union type ' + typeName + '.'\n });\n }\n });\n });\n return typesAddedToUnion;\n}", "function findBreakingChanges(oldSchema, newSchema) {\n\t return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema));\n\t}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n var typesRemovedFromUnion = [];\n\n var _arr10 = Object.keys(oldTypeMap);\n\n for (var _i10 = 0; _i10 < _arr10.length; _i10++) {\n var typeName = _arr10[_i10];\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n\n if (!Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(oldType) || !Object(_type_definition__WEBPACK_IMPORTED_MODULE_1__[\"isUnionType\"])(newType)) {\n continue;\n }\n\n var typeNamesInNewUnion = Object.create(null);\n var _iteratorNormalCompletion3 = true;\n var _didIteratorError3 = false;\n var _iteratorError3 = undefined;\n\n try {\n for (var _iterator3 = newType.getTypes()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {\n var type = _step3.value;\n typeNamesInNewUnion[type.name] = true;\n }\n } catch (err) {\n _didIteratorError3 = true;\n _iteratorError3 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion3 && _iterator3.return != null) {\n _iterator3.return();\n }\n } finally {\n if (_didIteratorError3) {\n throw _iteratorError3;\n }\n }\n }\n\n var _iteratorNormalCompletion4 = true;\n var _didIteratorError4 = false;\n var _iteratorError4 = undefined;\n\n try {\n for (var _iterator4 = oldType.getTypes()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {\n var _type = _step4.value;\n\n if (!typeNamesInNewUnion[_type.name]) {\n typesRemovedFromUnion.push({\n type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n description: \"\".concat(_type.name, \" was removed from union type \").concat(typeName, \".\")\n });\n }\n }\n } catch (err) {\n _didIteratorError4 = true;\n _iteratorError4 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion4 && _iterator4.return != null) {\n _iterator4.return();\n }\n } finally {\n if (_didIteratorError4) {\n throw _iteratorError4;\n }\n }\n }\n }\n\n return typesRemovedFromUnion;\n}", "function findDangerousChanges(oldSchema, newSchema) {\n return [].concat(findArgChanges(oldSchema, newSchema).dangerousChanges, findValuesAddedToEnums(oldSchema, newSchema), findInterfacesAddedToObjectTypes(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).dangerousChanges);\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var breakingFieldChanges = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType || oldType instanceof _definition.GraphQLInputObjectType) || !(newType instanceof oldType.constructor)) {\n\t return;\n\t }\n\n\t var oldTypeFieldsDef = oldType.getFields();\n\t var newTypeFieldsDef = newType.getFields();\n\t Object.keys(oldTypeFieldsDef).forEach(function (fieldName) {\n\t // Check if the field is missing on the type in the new schema.\n\t if (!(fieldName in newTypeFieldsDef)) {\n\t breakingFieldChanges.push({\n\t type: BreakingChangeType.FIELD_REMOVED,\n\t description: typeName + '.' + fieldName + ' was removed.'\n\t });\n\t } else {\n\t // Check if the field's type has changed in the new schema.\n\t var oldFieldType = (0, _definition.getNamedType)(oldTypeFieldsDef[fieldName].type);\n\t var newFieldType = (0, _definition.getNamedType)(newTypeFieldsDef[fieldName].type);\n\t if (oldFieldType && newFieldType && oldFieldType.name !== newFieldType.name) {\n\t breakingFieldChanges.push({\n\t type: BreakingChangeType.FIELD_CHANGED_KIND,\n\t description: typeName + '.' + fieldName + ' changed type from ' + (oldFieldType.name + ' to ' + newFieldType.name + '.')\n\t });\n\t }\n\t }\n\t });\n\t });\n\t return breakingFieldChanges;\n\t}", "function findArgChanges(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n var dangerousChanges = [];\n\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType) || !(newType instanceof oldType.constructor)) {\n return;\n }\n\n var oldTypeFields = oldType.getFields();\n var newTypeFields = newType.getFields();\n\n Object.keys(oldTypeFields).forEach(function (fieldName) {\n if (!newTypeFields[fieldName]) {\n return;\n }\n\n oldTypeFields[fieldName].args.forEach(function (oldArgDef) {\n var newArgs = newTypeFields[fieldName].args;\n var newArgDef = newArgs.find(function (arg) {\n return arg.name === oldArgDef.name;\n });\n\n // Arg not present\n if (!newArgDef) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_REMOVED,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' was removed')\n });\n } else {\n var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type);\n if (!isSafe) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_CHANGED_KIND,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed type from ') + (oldArgDef.type.toString() + ' to ' + newArgDef.type.toString())\n });\n } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) {\n dangerousChanges.push({\n type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed defaultValue')\n });\n }\n }\n });\n // Check if a non-null arg was added to the field\n newTypeFields[fieldName].args.forEach(function (newArgDef) {\n var oldArgs = oldTypeFields[fieldName].args;\n var oldArgDef = oldArgs.find(function (arg) {\n return arg.name === newArgDef.name;\n });\n if (!oldArgDef && newArgDef.type instanceof _definition.GraphQLNonNull) {\n breakingChanges.push({\n type: BreakingChangeType.NON_NULL_ARG_ADDED,\n description: 'A non-null arg ' + newArgDef.name + ' on ' + (newType.name + '.' + fieldName + ' was added')\n });\n }\n });\n });\n });\n\n return {\n breakingChanges: breakingChanges,\n dangerousChanges: dangerousChanges\n };\n}", "function findArgChanges(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var breakingChanges = [];\n var dangerousChanges = [];\n\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLObjectType || oldType instanceof _definition.GraphQLInterfaceType) || !(newType instanceof oldType.constructor)) {\n return;\n }\n\n var oldTypeFields = oldType.getFields();\n var newTypeFields = newType.getFields();\n\n Object.keys(oldTypeFields).forEach(function (fieldName) {\n if (!newTypeFields[fieldName]) {\n return;\n }\n\n oldTypeFields[fieldName].args.forEach(function (oldArgDef) {\n var newArgs = newTypeFields[fieldName].args;\n var newArgDef = newArgs.find(function (arg) {\n return arg.name === oldArgDef.name;\n });\n\n // Arg not present\n if (!newArgDef) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_REMOVED,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' was removed')\n });\n } else {\n var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type);\n if (!isSafe) {\n breakingChanges.push({\n type: BreakingChangeType.ARG_CHANGED_KIND,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed type from ') + (oldArgDef.type.toString() + ' to ' + newArgDef.type.toString())\n });\n } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) {\n dangerousChanges.push({\n type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE,\n description: oldType.name + '.' + fieldName + ' arg ' + (oldArgDef.name + ' has changed defaultValue')\n });\n }\n }\n });\n // Check if a non-null arg was added to the field\n newTypeFields[fieldName].args.forEach(function (newArgDef) {\n var oldArgs = oldTypeFields[fieldName].args;\n var oldArgDef = oldArgs.find(function (arg) {\n return arg.name === newArgDef.name;\n });\n if (!oldArgDef && newArgDef.type instanceof _definition.GraphQLNonNull) {\n breakingChanges.push({\n type: BreakingChangeType.NON_NULL_ARG_ADDED,\n description: 'A non-null arg ' + newArgDef.name + ' on ' + (newType.name + '.' + fieldName + ' was added')\n });\n }\n });\n });\n });\n\n return {\n breakingChanges: breakingChanges,\n dangerousChanges: dangerousChanges\n };\n}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var typesRemovedFromUnion = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLUnionType) || !(newType instanceof _definition.GraphQLUnionType)) {\n return;\n }\n var typeNamesInNewUnion = Object.create(null);\n newType.getTypes().forEach(function (type) {\n typeNamesInNewUnion[type.name] = true;\n });\n oldType.getTypes().forEach(function (type) {\n if (!typeNamesInNewUnion[type.name]) {\n typesRemovedFromUnion.push({\n type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n description: type.name + ' was removed from union type ' + typeName + '.'\n });\n }\n });\n });\n return typesRemovedFromUnion;\n}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n var oldTypeMap = oldSchema.getTypeMap();\n var newTypeMap = newSchema.getTypeMap();\n\n var typesRemovedFromUnion = [];\n Object.keys(oldTypeMap).forEach(function (typeName) {\n var oldType = oldTypeMap[typeName];\n var newType = newTypeMap[typeName];\n if (!(oldType instanceof _definition.GraphQLUnionType) || !(newType instanceof _definition.GraphQLUnionType)) {\n return;\n }\n var typeNamesInNewUnion = Object.create(null);\n newType.getTypes().forEach(function (type) {\n typeNamesInNewUnion[type.name] = true;\n });\n oldType.getTypes().forEach(function (type) {\n if (!typeNamesInNewUnion[type.name]) {\n typesRemovedFromUnion.push({\n type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n description: type.name + ' was removed from union type ' + typeName + '.'\n });\n }\n });\n });\n return typesRemovedFromUnion;\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n return [].concat(findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema));\n}", "function findFieldsThatChangedType(oldSchema, newSchema) {\n return [].concat(findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema));\n}", "function findTypesRemovedFromUnions(oldSchema, newSchema) {\n\t var oldTypeMap = oldSchema.getTypeMap();\n\t var newTypeMap = newSchema.getTypeMap();\n\n\t var typesRemovedFromUnion = [];\n\t Object.keys(oldTypeMap).forEach(function (typeName) {\n\t var oldType = oldTypeMap[typeName];\n\t var newType = newTypeMap[typeName];\n\t if (!(oldType instanceof _definition.GraphQLUnionType) || !(newType instanceof _definition.GraphQLUnionType)) {\n\t return;\n\t }\n\t var typeNamesInNewUnion = Object.create(null);\n\t newType.getTypes().forEach(function (type) {\n\t typeNamesInNewUnion[type.name] = true;\n\t });\n\t oldType.getTypes().forEach(function (type) {\n\t if (!typeNamesInNewUnion[type.name]) {\n\t typesRemovedFromUnion.push({\n\t type: BreakingChangeType.TYPE_REMOVED_FROM_UNION,\n\t description: type.name + ' was removed from union type ' + typeName + '.'\n\t });\n\t }\n\t });\n\t });\n\t return typesRemovedFromUnion;\n\t}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema));\n}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedType(oldSchema, newSchema), findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema));\n}", "function findBreakingChanges(oldSchema, newSchema) {\n return [].concat(findRemovedTypes(oldSchema, newSchema), findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).breakingChanges, findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema), findRemovedDirectives(oldSchema, newSchema), findRemovedDirectiveArgs(oldSchema, newSchema), findAddedNonNullDirectiveArgs(oldSchema, newSchema), findRemovedDirectiveLocations(oldSchema, newSchema));\n}" ]
[ "0.7961201", "0.7452213", "0.7186998", "0.7186998", "0.7143121", "0.6903845", "0.6899022", "0.68724793", "0.68724793", "0.68663436", "0.6860933", "0.6849344", "0.6849344", "0.68405265", "0.6779417", "0.67071426", "0.6547236", "0.65066653", "0.64276445", "0.63447815", "0.63329357", "0.63329357", "0.62842274", "0.62842274", "0.6282577", "0.6282577", "0.6257017", "0.62555844", "0.62555844", "0.6199938" ]
0.7793059
1
Perform the analysis. This must be called before writeTypingsFile().
analyze() { if (this._astEntryPoint) { throw new Error('DtsRollupGenerator.analyze() was already called'); } // Build the entry point const sourceFile = this._context.package.getDeclaration().getSourceFile(); this._astEntryPoint = this._astSymbolTable.fetchEntryPoint(sourceFile); const exportedAstSymbols = []; // Create a DtsEntry for each top-level export for (const exportedMember of this._astEntryPoint.exportedMembers) { const astSymbol = exportedMember.astSymbol; this._createDtsEntryForSymbol(exportedMember.astSymbol, exportedMember.name); exportedAstSymbols.push(astSymbol); } // Create a DtsEntry for each indirectly referenced export. // Note that we do this *after* the above loop, so that references to exported AstSymbols // are encountered first as exports. const alreadySeenAstSymbols = new Set(); for (const exportedAstSymbol of exportedAstSymbols) { this._createDtsEntryForIndirectReferences(exportedAstSymbol, alreadySeenAstSymbols); } this._makeUniqueNames(); this._dtsEntries.sort((a, b) => a.getSortKey().localeCompare(b.getSortKey())); this._dtsTypeDefinitionReferences.sort(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "postAnalysis() { }", "processTypings(files) {\n // Set hashes of the app's typings.\n files.forEach(file => {\n let isAppTypings = this.isDeclarationFile(file) &&\n !this.isPackageFile(file);\n\n let path = file.getPathInPackage();\n if (isAppTypings && !this._typingsMap.has(path)) {\n this._typingsMap.set(path, file.getSourceHash());\n }\n });\n\n let copiedFiles = [];\n // Process package typings.\n files.forEach(file => {\n // Check if it's a package declaration file.\n let isPkgTypings = this.isDeclarationFile(file) &&\n this.isPackageFile(file);\n\n if (isPkgTypings) {\n let path = file.getPathInPackage();\n // Check if the file is in the \"typings\" folder.\n if (!this._typingsRegEx.test(path)) {\n console.log('Typings path ${path} doesn\\'t start with \"typings\"');\n return;\n }\n\n let filePath = this._getStandardTypingsFilePath(file);\n let oldHash = this._typingsMap.get(filePath);\n let newHash = file.getSourceHash();\n // Copy file if it doesn't exist or has been updated.\n if (oldHash !== newHash) {\n this._copyTypings(filePath, file.getContentsAsString());\n this._typingsMap.set(filePath, newHash);\n copiedFiles.push(filePath);\n }\n }\n });\n\n if (copiedFiles.length) {\n // Report about added/updated typings.\n console.log(chalk.green('***** Typings that have been added/updated *****'));\n copiedFiles.forEach(filePath => {\n console.log(chalk.green(filePath));\n });\n console.log(chalk.green(\n 'Add typings in tsconfig.json or by references in files.'));\n }\n }", "mainLogic() {\n this.apexParser = new ApexParser(this.accessModifiers,this.sourceDirectory);\n const filesArray = this.getClassFilesFromPackageDirectories();\n\n //Create a new array of ClassModels\n const classModels = this.getClassModelsFromFiles(filesArray);\n const mapGroupNameToClassGroup = this.createMapGroupNameToClassGroup(classModels, this.sourceDirectory);\n\n const projectDetail = this.fm.parseHTMLFile(this.bannerFilePath);\n const homeContents = this.fm.parseHTMLFile(this.homefilepath);\n this.fm.createDoc(mapGroupNameToClassGroup, classModels, projectDetail, homeContents, this.hostedSourceUrl);\n console.log('ApexDoc has completed!');\n }", "function analyzer(data, sidePass) {\n //B.start('analyzer');\n var mainPass = !sidePass;\n\n var item = { items: data };\n var data = item;\n\n var newTypes = {};\n\n // Gather\n // Single-liners\n ['globalVariable', 'functionStub', 'unparsedFunction', 'unparsedGlobals', 'unparsedTypes', 'alias'].forEach(function(intertype) {\n var temp = splitter(item.items, function(item) { return item.intertype == intertype });\n item.items = temp.leftIn;\n item[intertype + 's'] = temp.splitOut;\n });\n var temp = splitter(item.items, function(item) { return item.intertype == 'type' });\n item.items = temp.leftIn;\n temp.splitOut.forEach(function(type) {\n //dprint('types', 'adding defined type: ' + type.name_);\n Types.types[type.name_] = type;\n newTypes[type.name_] = 1;\n if (QUANTUM_SIZE === 1) {\n Types.fatTypes[type.name_] = copy(type);\n }\n });\n\n // Functions & labels\n item.functions = [];\n var currLabelFinished = false; // Sometimes LLVM puts a branch in the middle of a label. We need to ignore all lines after that.\n item.items.sort(function(a, b) { return a.lineNum - b.lineNum });\n for (var i = 0; i < item.items.length; i++) {\n var subItem = item.items[i];\n assert(subItem.lineNum);\n if (subItem.intertype == 'function') {\n item.functions.push(subItem);\n subItem.endLineNum = null;\n subItem.lines = []; // We will fill in the function lines after the legalizer, since it can modify them\n subItem.labels = [];\n subItem.forceEmulated = false;\n\n // no explicit 'entry' label in clang on LLVM 2.8 - most of the time, but not all the time! - so we add one if necessary\n if (item.items[i+1].intertype !== 'label') {\n item.items.splice(i+1, 0, {\n intertype: 'label',\n ident: ENTRY_IDENT,\n lineNum: subItem.lineNum + '.5'\n });\n }\n } else if (subItem.intertype == 'functionEnd') {\n item.functions.slice(-1)[0].endLineNum = subItem.lineNum;\n } else if (subItem.intertype == 'label') {\n item.functions.slice(-1)[0].labels.push(subItem);\n subItem.lines = [];\n currLabelFinished = false;\n } else if (item.functions.length > 0 && item.functions.slice(-1)[0].endLineNum === null) {\n // Internal line\n if (!currLabelFinished) {\n item.functions.slice(-1)[0].labels.slice(-1)[0].lines.push(subItem); // If this line fails, perhaps missing a label?\n if (subItem.intertype in LABEL_ENDERS) {\n currLabelFinished = true;\n }\n } else {\n print('// WARNING: content after a branch in a label, line: ' + subItem.lineNum);\n }\n } else {\n throw 'ERROR: what is this? ' + dump(subItem);\n }\n }\n delete item.items;\n\n // CastAway - try to remove bitcasts of double<-->i64, which LLVM sometimes generates unnecessarily\n // (load a double, convert to i64, use as i64).\n // We optimize this by checking if there are such bitcasts. If so we create a shadow\n // variable that is of the other type, and use that in the relevant places. (As SSA, this is valid, and\n // variable elimination later will remove the double load if it is no longer needed.)\n //\n // Note that aside from being an optimization, this is needed for correctness in some cases: If code\n // assumes it can bitcast a double to an i64 and back and forth without loss, that may be violated\n // due to NaN canonicalization.\n function castAway() {\n if (USE_TYPED_ARRAYS != 2) return;\n\n item.functions.forEach(function(func) {\n var has = false;\n func.labels.forEach(function(label) {\n var lines = label.lines;\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i];\n if (line.intertype == 'bitcast' && line.type in SHADOW_FLIP) {\n has = true;\n }\n }\n });\n if (!has) return;\n // there are integer<->floating-point bitcasts, create shadows for everything\n var shadowed = {};\n func.labels.forEach(function(label) {\n var lines = label.lines;\n var i = 0;\n while (i < lines.length) {\n var lines = label.lines;\n var line = lines[i];\n if (line.intertype == 'load' && line.type in SHADOW_FLIP) {\n if (line.pointer.intertype != 'value') { i++; continue } // TODO\n shadowed[line.assignTo] = 1;\n var shadow = line.assignTo + '$$SHADOW';\n var flip = SHADOW_FLIP[line.type];\n lines.splice(i + 1, 0, { // if necessary this element will be legalized in the next phase\n tokens: null,\n indent: 2,\n lineNum: line.lineNum + 0.5,\n assignTo: shadow,\n intertype: 'load',\n pointerType: flip + '*',\n type: flip,\n valueType: flip,\n pointer: {\n intertype: 'value',\n ident: line.pointer.ident,\n type: flip + '*'\n },\n align: line.align,\n ident: line.ident\n });\n // note: no need to update func.lines, it is generated in a later pass\n i++;\n }\n i++;\n }\n });\n // use shadows where possible\n func.labels.forEach(function(label) {\n var lines = label.lines;\n for (var i = 0; i < lines.length; i++) {\n var line = lines[i];\n if (line.intertype == 'bitcast' && line.type in SHADOW_FLIP && line.ident in shadowed) {\n var shadow = line.ident + '$$SHADOW';\n line.params[0].ident = shadow;\n line.params[0].type = line.type;\n line.type2 = line.type;\n }\n }\n });\n });\n }\n\n // Legalize LLVM unrealistic types into realistic types.\n //\n // With full LLVM optimizations, it can generate types like i888 which do not exist in\n // any actual hardware implementation, but are useful during optimization. LLVM then\n // legalizes these types into real ones during code generation. Sadly, there is no LLVM\n // IR pass to legalize them, which would have been useful and nice from a design perspective.\n // The LLVM community is also not interested in receiving patches to implement that\n // functionality, since it would duplicate existing code from the code generation\n // component. Therefore, we implement legalization here in Emscripten.\n //\n // Currently we just legalize completely unrealistic types into bundles of i32s, and just\n // the most common instructions that can be involved with such types: load, store, shifts,\n // trunc and zext.\n function legalizer() {\n // Legalization\n if (USE_TYPED_ARRAYS == 2) {\n function getLegalVars(base, bits, allowLegal) {\n bits = bits || 32; // things like pointers are all i32, but show up as 0 bits from getBits\n if (allowLegal && bits <= 32) return [{ intertype: 'value', ident: base + ('i' + bits in Runtime.INT_TYPES ? '' : '$0'), bits: bits, type: 'i' + bits }];\n if (isNumber(base)) return getLegalLiterals(base, bits);\n if (base[0] == '{') {\n warnOnce('seeing source of illegal data ' + base + ', likely an inline struct - assuming zeroinit');\n return getLegalLiterals('0', bits);\n }\n var ret = new Array(Math.ceil(bits/32));\n var i = 0;\n if (base == 'zeroinitializer' || base == 'undef') base = 0;\n while (bits > 0) {\n ret[i] = { intertype: 'value', ident: base ? base + '$' + i : '0', bits: Math.min(32, bits), type: 'i' + Math.min(32, bits) };\n bits -= 32;\n i++;\n }\n return ret;\n }\n function getLegalLiterals(text, bits) {\n var parsed = parseArbitraryInt(text, bits);\n var ret = new Array(Math.ceil(bits/32));\n var i = 0;\n while (bits > 0) {\n ret[i] = { intertype: 'value', ident: (parsed[i]|0).toString(), bits: Math.min(32, bits), type: 'i' + Math.min(32, bits) }; // resign all values\n bits -= 32;\n i++;\n }\n return ret;\n }\n function getLegalStructuralParts(value) {\n return value.params.slice(0);\n }\n function getLegalParams(params, bits) {\n return params.map(function(param) {\n var value = param.value || param;\n if (isNumber(value.ident)) {\n return getLegalLiterals(value.ident, bits);\n } else if (value.intertype == 'structvalue') {\n return getLegalStructuralParts(value).map(function(part) {\n part.bits = part.type.substr(1); // can be some nested IR, like LLVM calls\n return part;\n });\n } else {\n return getLegalVars(value.ident, bits);\n }\n });\n }\n // Uses the right factor to multiply line numbers by so that they fit in between\n // the line[i] and the line after it\n function interpLines(lines, i, toAdd) {\n var prev = i >= 0 ? lines[i].lineNum : -1;\n var next = (i < lines.length-1) ? lines[i+1].lineNum : (lines[i].lineNum + 0.5);\n var factor = (next - prev)/(4*toAdd.length+3);\n for (var k = 0; k < toAdd.length; k++) {\n toAdd[k].lineNum = prev + ((k+1)*factor);\n assert(k == 0 || toAdd[k].lineNum > toAdd[k-1].lineNum);\n }\n }\n function removeAndAdd(lines, i, toAdd) {\n var item = lines[i];\n interpLines(lines, i, toAdd);\n Array.prototype.splice.apply(lines, [i, 1].concat(toAdd));\n if (i > 0) assert(lines[i].lineNum > lines[i-1].lineNum);\n if (i + toAdd.length < lines.length) assert(lines[i + toAdd.length - 1].lineNum < lines[i + toAdd.length].lineNum);\n return toAdd.length;\n }\n function legalizeFunctionParameters(params) {\n var i = 0;\n while (i < params.length) {\n var param = params[i];\n if (param.intertype == 'value' && isIllegalType(param.type)) {\n var toAdd = getLegalVars(param.ident, getBits(param.type)).map(function(element) {\n return {\n intertype: 'value',\n type: 'i' + element.bits,\n ident: element.ident,\n byval: 0\n };\n });\n Array.prototype.splice.apply(params, [i, 1].concat(toAdd));\n i += toAdd.length;\n continue;\n } else if (param.intertype == 'structvalue') {\n // 'flatten' out the struct into scalars\n var toAdd = param.params;\n toAdd.forEach(function(param) {\n param.byval = 0;\n });\n Array.prototype.splice.apply(params, [i, 1].concat(toAdd));\n continue; // do not increment i; proceed to process the new params\n }\n i++;\n }\n }\n function fixUnfolded(item) {\n // Unfolded items may need some correction to work properly in the global scope\n if (item.intertype in MATHOPS) {\n item.op = item.intertype;\n item.intertype = 'mathop';\n }\n }\n data.functions.forEach(function(func) {\n // Legalize function params\n legalizeFunctionParameters(func.params);\n // Legalize lines in labels\n var tempId = 0;\n func.labels.forEach(function(label) {\n if (dcheck('legalizer')) dprint('zz legalizing: \\n' + dump(label.lines));\n var i = 0, bits;\n while (i < label.lines.length) {\n var item = label.lines[i];\n var value = item;\n // Check if we need to legalize here, and do some trivial legalization along the way\n var isIllegal = false;\n walkInterdata(item, function(item) {\n if (item.intertype == 'getelementptr' || (item.intertype == 'call' && item.ident in LLVM.INTRINSICS_32)) {\n // Turn i64 args into i32\n for (var i = 0; i < item.params.length; i++) {\n if (item.params[i].type == 'i64') item.params[i].type = 'i32';\n }\n } else if (item.intertype == 'inttoptr') {\n var input = item.params[0];\n if (input.type == 'i64') input.type = 'i32'; // inttoptr can only care about 32 bits anyhow since pointers are 32-bit\n }\n if (isIllegalType(item.valueType) || isIllegalType(item.type)) {\n isIllegal = true;\n } else if ((item.intertype == 'load' || item.intertype == 'store') && isStructType(item.valueType)) {\n isIllegal = true; // storing an entire structure is illegal\n } else if (item.intertype == 'mathop' && item.op == 'trunc' && isIllegalType(item.params[1].ident)) { // trunc stores target value in second ident\n isIllegal = true;\n }\n });\n if (!isIllegal) {\n //if (dcheck('legalizer')) dprint('no need to legalize \\n' + dump(item));\n i++;\n continue;\n }\n // Unfold this line. If we unfolded, we need to return and process the lines we just\n // generated - they may need legalization too\n var unfolded = [];\n walkAndModifyInterdata(item, function(subItem) {\n // Unfold all non-value interitems that we can, and also unfold all numbers (doing the latter\n // makes it easier later since we can then assume illegal expressions are always variables\n // accessible through ident$x, and not constants we need to parse then and there)\n if (subItem != item && (!(subItem.intertype in UNUNFOLDABLE) ||\n (subItem.intertype == 'value' && isNumber(subItem.ident) && isIllegalType(subItem.type)))) {\n if (item.intertype == 'phi') {\n assert(subItem.intertype == 'value' || subItem.intertype == 'structvalue' || subItem.intertype in PARSABLE_LLVM_FUNCTIONS, 'We can only unfold some expressions in phis');\n // we must handle this in the phi itself, if we unfold normally it will not be pushed back with the phi\n } else {\n var tempIdent = '$$etemp$' + (tempId++);\n subItem.assignTo = tempIdent;\n unfolded.unshift(subItem);\n fixUnfolded(subItem);\n return { intertype: 'value', ident: tempIdent, type: subItem.type };\n }\n } else if (subItem.intertype == 'switch' && isIllegalType(subItem.type)) {\n subItem.switchLabels.forEach(function(switchLabel) {\n if (switchLabel.value[0] != '$') {\n var tempIdent = '$$etemp$' + (tempId++);\n unfolded.unshift({\n assignTo: tempIdent,\n intertype: 'value',\n ident: switchLabel.value,\n type: subItem.type\n });\n switchLabel.value = tempIdent;\n }\n });\n }\n });\n if (unfolded.length > 0) {\n interpLines(label.lines, i-1, unfolded);\n Array.prototype.splice.apply(label.lines, [i, 0].concat(unfolded));\n continue; // remain at this index, to unfold newly generated lines\n }\n // This is an illegal-containing line, and it is unfolded. Legalize it now\n dprint('legalizer', 'Legalizing ' + item.intertype + ' at line ' + item.lineNum);\n var finalizer = null;\n switch (item.intertype) {\n case 'store': {\n var toAdd = [];\n bits = getBits(item.valueType);\n var elements = getLegalParams([item.value], bits)[0];\n var j = 0;\n elements.forEach(function(element) {\n var tempVar = '$st$' + (tempId++) + '$' + j;\n toAdd.push({\n intertype: 'getelementptr',\n assignTo: tempVar,\n ident: item.pointer.ident,\n type: '[0 x i32]*',\n params: [\n { intertype: 'value', ident: item.pointer.ident, type: '[0 x i32]*' }, // technically a bitcase is needed in llvm, but not for us\n { intertype: 'value', ident: '0', type: 'i32' },\n { intertype: 'value', ident: j.toString(), type: 'i32' }\n ],\n });\n var actualSizeType = 'i' + element.bits; // The last one may be smaller than 32 bits\n toAdd.push({\n intertype: 'store',\n valueType: actualSizeType,\n value: { intertype: 'value', ident: element.ident, type: actualSizeType },\n pointer: { intertype: 'value', ident: tempVar, type: actualSizeType + '*' },\n ident: tempVar,\n pointerType: actualSizeType + '*',\n align: item.align,\n });\n j++;\n });\n Types.needAnalysis['[0 x i32]'] = 0;\n i += removeAndAdd(label.lines, i, toAdd);\n continue;\n }\n // call, return: Return the first 32 bits, the rest are in temp\n case 'call': {\n var toAdd = [value];\n // legalize parameters\n legalizeFunctionParameters(value.params);\n // legalize return value, if any\n var returnType = getReturnType(item.type);\n if (value.assignTo && isIllegalType(returnType)) {\n bits = getBits(returnType);\n var elements = getLegalVars(item.assignTo, bits);\n // legalize return value\n value.assignTo = elements[0].ident;\n for (var j = 1; j < elements.length; j++) {\n var element = elements[j];\n toAdd.push({\n intertype: 'value',\n assignTo: element.ident,\n type: 'i' + element.bits,\n ident: 'tempRet' + (j - 1)\n });\n assert(j<10); // TODO: dynamically create more than 10 tempRet-s\n }\n }\n i += removeAndAdd(label.lines, i, toAdd);\n continue;\n }\n case 'landingpad': {\n // not much to legalize\n i++;\n continue;\n }\n case 'return': {\n bits = getBits(item.type);\n var elements = getLegalVars(item.value.ident, bits);\n item.value.ident = '(';\n for (var j = 1; j < elements.length; j++) {\n item.value.ident += 'tempRet' + (j-1) + '=' + elements[j].ident + ',';\n }\n item.value.ident += elements[0].ident + ')';\n i++;\n continue;\n }\n case 'invoke': {\n legalizeFunctionParameters(value.params);\n // We can't add lines after this, since invoke already modifies control flow. So we handle the return in invoke\n i++;\n continue;\n }\n case 'value': {\n bits = getBits(value.type);\n var elements = getLegalVars(item.assignTo, bits);\n var values = getLegalLiterals(item.ident, bits);\n var j = 0;\n var toAdd = elements.map(function(element) {\n return {\n intertype: 'value',\n assignTo: element.ident,\n type: 'i' + bits,\n ident: values[j++].ident\n };\n });\n i += removeAndAdd(label.lines, i, toAdd);\n continue;\n }\n case 'structvalue': {\n bits = getBits(value.type);\n var elements = getLegalVars(item.assignTo, bits);\n var toAdd = [];\n for (var j = 0; j < item.params.length; j++) {\n toAdd[j] = {\n intertype: 'value',\n assignTo: elements[j].ident,\n type: 'i32',\n ident: item.params[j].ident\n };\n }\n i += removeAndAdd(label.lines, i, toAdd);\n continue;\n }\n case 'load': {\n bits = getBits(value.valueType);\n var elements = getLegalVars(item.assignTo, bits);\n var j = 0;\n var toAdd = [];\n elements.forEach(function(element) {\n var tempVar = '$ld$' + (tempId++) + '$' + j;\n toAdd.push({\n intertype: 'getelementptr',\n assignTo: tempVar,\n ident: value.pointer.ident,\n type: '[0 x i32]*',\n params: [\n { intertype: 'value', ident: value.pointer.ident, type: '[0 x i32]*' }, // technically bitcast is needed in llvm, but not for us\n { intertype: 'value', ident: '0', type: 'i32' },\n { intertype: 'value', ident: j.toString(), type: 'i32' }\n ]\n });\n var newItem = {\n intertype: 'load',\n assignTo: element.ident,\n pointerType: 'i32*',\n valueType: 'i32',\n type: 'i32',\n pointer: { intertype: 'value', ident: tempVar, type: 'i32*' },\n ident: tempVar,\n align: value.align\n };\n var newItem2 = null;\n // The last one may be smaller than 32 bits\n if (element.bits < 32) {\n newItem.assignTo += '$preadd$';\n newItem2 = {\n intertype: 'mathop',\n op: 'and',\n assignTo: element.ident,\n type: 'i32',\n params: [{\n intertype: 'value',\n type: 'i32',\n ident: newItem.assignTo\n }, {\n intertype: 'value',\n type: 'i32',\n ident: (0xffffffff >>> (32 - element.bits)).toString()\n }],\n };\n }\n toAdd.push(newItem);\n if (newItem2) toAdd.push(newItem2);\n j++;\n });\n Types.needAnalysis['[0 x i32]'] = 0;\n i += removeAndAdd(label.lines, i, toAdd);\n continue;\n }\n case 'phi': {\n bits = getBits(value.type);\n var toAdd = [];\n var elements = getLegalVars(item.assignTo, bits);\n var j = 0;\n var values = getLegalParams(value.params, bits);\n elements.forEach(function(element) {\n var k = 0;\n toAdd.push({\n intertype: 'phi',\n assignTo: element.ident,\n type: 'i' + element.bits,\n params: value.params.map(function(param) {\n return {\n intertype: 'phiparam',\n label: param.label,\n value: values[k++][j]\n };\n })\n });\n j++;\n });\n i += removeAndAdd(label.lines, i, toAdd);\n continue;\n }\n case 'switch': {\n i++;\n continue; // special case, handled in makeComparison\n }\n case 'va_arg': {\n assert(value.type == 'i64');\n assert(value.value.type == 'i32*', value.value.type);\n i += removeAndAdd(label.lines, i, range(2).map(function(x) {\n return {\n intertype: 'va_arg',\n assignTo: value.assignTo + '$' + x,\n type: 'i32',\n value: {\n intertype: 'value',\n ident: value.value.ident, // We read twice from the same i32* var, incrementing // + '$' + x,\n type: 'i32*'\n }\n };\n }));\n continue;\n }\n case 'extractvalue': { // XXX we assume 32-bit alignment in extractvalue/insertvalue,\n // but in theory they can run on packed structs too (see use getStructuralTypePartBits)\n // potentially legalize the actual extracted value too if it is >32 bits, not just the extraction in general\n var index = item.indexes[0][0].text;\n var parts = getStructureTypeParts(item.type);\n var indexedType = parts[index];\n var targetBits = getBits(indexedType);\n var sourceBits = getBits(item.type);\n var elements = getLegalVars(item.assignTo, targetBits, true); // possibly illegal\n var sourceElements = getLegalVars(item.ident, sourceBits); // definitely illegal\n var toAdd = [];\n var sourceIndex = 0;\n for (var partIndex = 0; partIndex < parts.length; partIndex++) {\n if (partIndex == index) {\n for (var j = 0; j < elements.length; j++) {\n toAdd.push({\n intertype: 'value',\n assignTo: elements[j].ident,\n type: 'i' + elements[j].bits,\n ident: sourceElements[sourceIndex+j].ident\n });\n }\n break;\n }\n sourceIndex += getStructuralTypePartBits(parts[partIndex])/32;\n }\n i += removeAndAdd(label.lines, i, toAdd);\n continue;\n }\n case 'insertvalue': {\n var index = item.indexes[0][0].text; // the modified index\n var parts = getStructureTypeParts(item.type);\n var indexedType = parts[index];\n var indexBits = getBits(indexedType);\n var bits = getBits(item.type); // source and target\n bits = getBits(value.type);\n var toAdd = [];\n var elements = getLegalVars(item.assignTo, bits);\n var sourceElements = getLegalVars(item.ident, bits);\n var indexElements = getLegalVars(item.value.ident, indexBits, true); // possibly legal\n var sourceIndex = 0;\n for (var partIndex = 0; partIndex < parts.length; partIndex++) {\n var currNum = getStructuralTypePartBits(parts[partIndex])/32;\n for (var j = 0; j < currNum; j++) {\n toAdd.push({\n intertype: 'value',\n assignTo: elements[sourceIndex+j].ident,\n type: 'i' + elements[sourceIndex+j].bits,\n ident: partIndex == index ? indexElements[j].ident : sourceElements[sourceIndex+j].ident\n });\n }\n sourceIndex += currNum;\n }\n i += removeAndAdd(label.lines, i, toAdd);\n continue;\n }\n case 'bitcast': {\n var inType = item.type2;\n var outType = item.type;\n if ((inType in Runtime.INT_TYPES && outType in Runtime.FLOAT_TYPES) ||\n (inType in Runtime.FLOAT_TYPES && outType in Runtime.INT_TYPES)) {\n i++;\n continue; // special case, handled in processMathop\n }\n // fall through\n }\n case 'inttoptr': case 'ptrtoint': case 'zext': case 'sext': case 'trunc': case 'ashr': case 'lshr': case 'shl': case 'or': case 'and': case 'xor': {\n value = {\n op: item.intertype,\n variant: item.variant,\n type: item.type,\n params: item.params\n };\n // fall through\n }\n case 'mathop': {\n var toAdd = [];\n var sourceBits = getBits(value.params[0].type);\n // All mathops can be parametrized by how many shifts we do, and how big the source is\n var shifts = 0;\n var targetBits = sourceBits;\n var processor = null;\n var signed = false;\n switch (value.op) {\n case 'ashr': {\n signed = true;\n // fall through\n }\n case 'lshr': {\n shifts = parseInt(value.params[1].ident);\n break;\n }\n case 'shl': {\n shifts = -parseInt(value.params[1].ident);\n break;\n }\n case 'sext': {\n signed = true;\n // fall through\n }\n case 'trunc': case 'zext': case 'ptrtoint': {\n targetBits = getBits(value.params[1] ? value.params[1].ident : value.type);\n break;\n }\n case 'inttoptr': {\n targetBits = 32;\n break;\n }\n case 'bitcast': {\n if (!sourceBits) {\n // we can be asked to bitcast doubles or such to integers, handle that as best we can (if it's a double that\n // was an x86_fp80, this code will likely break when called)\n sourceBits = targetBits = Runtime.getNativeTypeSize(value.params[0].type);\n warn('legalizing non-integer bitcast on ll #' + item.lineNum);\n }\n break;\n }\n case 'select': {\n sourceBits = targetBits = getBits(value.params[1].type);\n var params = getLegalParams(value.params.slice(1), sourceBits);\n processor = function(result, j) {\n return {\n intertype: 'mathop',\n op: 'select',\n type: 'i' + params[0][j].bits,\n params: [\n value.params[0],\n { intertype: 'value', ident: params[0][j].ident, type: 'i' + params[0][j].bits },\n { intertype: 'value', ident: params[1][j].ident, type: 'i' + params[1][j].bits }\n ]\n };\n };\n break;\n }\n case 'or': case 'and': case 'xor': case 'icmp': {\n var otherElements = getLegalVars(value.params[1].ident, sourceBits);\n processor = function(result, j) {\n return {\n intertype: 'mathop',\n op: value.op,\n variant: value.variant,\n type: 'i' + otherElements[j].bits,\n params: [\n result,\n { intertype: 'value', ident: otherElements[j].ident, type: 'i' + otherElements[j].bits }\n ]\n };\n };\n if (value.op == 'icmp') {\n if (sourceBits == 64) { // handle the i64 case in processMathOp, where we handle full i64 math\n i++;\n continue;\n }\n finalizer = function() {\n var ident = '';\n for (var i = 0; i < targetElements.length; i++) {\n if (i > 0) {\n switch(value.variant) {\n case 'eq': ident += '&'; break;\n case 'ne': ident += '|'; break;\n default: throw 'unhandleable illegal icmp: ' + value.variant;\n }\n }\n ident += targetElements[i].ident;\n }\n return {\n intertype: 'value',\n ident: ident,\n type: 'rawJS',\n assignTo: item.assignTo\n };\n }\n }\n break;\n }\n case 'add': case 'sub': case 'sdiv': case 'udiv': case 'mul': case 'urem': case 'srem': {\n if (sourceBits < 32) {\n // when we add illegal types like i24, we must work on the singleton chunks\n item.assignTo += '$0';\n item.params[0].ident += '$0';\n item.params[1].ident += '$0';\n }\n // fall through\n }\n case 'uitofp': case 'sitofp': case 'fptosi': case 'fptoui': {\n // We cannot do these in parallel chunks of 32-bit operations. We will handle these in processMathop\n i++;\n continue;\n }\n default: throw 'Invalid mathop for legalization: ' + [value.op, item.lineNum, dump(item)];\n }\n // Do the legalization\n var sourceElements = getLegalVars(value.params[0].ident, sourceBits, true);\n if (!isNumber(shifts)) {\n // We can't statically legalize this, do the operation at runtime TODO: optimize\n assert(sourceBits == 64, 'TODO: handle nonconstant shifts on != 64 bits');\n assert(PRECISE_I64_MATH, 'Must have precise i64 math for non-constant 64-bit shifts');\n Types.preciseI64MathUsed = 1;\n value.intertype = 'value';\n value.ident = makeVarDef(value.assignTo) + '$0=' +\n asmCoercion('_bitshift64' + value.op[0].toUpperCase() + value.op.substr(1) + '(' + \n asmCoercion(sourceElements[0].ident, 'i32') + ',' +\n asmCoercion(sourceElements[1].ident, 'i32') + ',' +\n asmCoercion(value.params[1].ident + '$0', 'i32') + ')', 'i32'\n ) + ';' +\n makeVarDef(value.assignTo) + '$1=tempRet0;';\n value.vars = [[value.assignTo + '$0', 'i32'], [value.assignTo + '$1', 'i32']];\n value.assignTo = null;\n i++;\n continue;\n }\n var targetElements = getLegalVars(item.assignTo, targetBits);\n var sign = shifts >= 0 ? 1 : -1;\n var shiftOp = shifts >= 0 ? 'shl' : 'lshr';\n var shiftOpReverse = shifts >= 0 ? 'lshr' : 'shl';\n var whole = shifts >= 0 ? Math.floor(shifts/32) : Math.ceil(shifts/32);\n var fraction = Math.abs(shifts % 32);\n if (signed) {\n var signedFill = {\n intertype: 'mathop',\n op: 'select',\n variant: 's',\n type: 'i32',\n params: [{\n intertype: 'mathop',\n op: 'icmp',\n variant: 'slt',\n type: 'i32',\n params: [\n { intertype: 'value', ident: sourceElements[sourceElements.length-1].ident, type: 'i' + Math.min(sourceBits, 32) },\n { intertype: 'value', ident: '0', type: 'i32' }\n ]\n },\n { intertype: 'value', ident: '-1', type: 'i32' },\n { intertype: 'value', ident: '0', type: 'i32' },\n ]\n };\n }\n for (var j = 0; j < targetElements.length; j++) {\n var inBounds = j + whole >= 0 && j + whole < sourceElements.length;\n var result;\n if (inBounds || !signed) {\n result = {\n intertype: 'value',\n ident: inBounds ? sourceElements[j + whole].ident : '0',\n type: 'i' + Math.min(sourceBits, 32),\n };\n if (j == 0 && sourceBits < 32) {\n // zext sign correction\n var result2 = {\n intertype: 'mathop',\n op: isUnsignedOp(value.op) ? 'zext' : 'sext',\n params: [result, {\n intertype: 'type',\n ident: 'i32',\n type: 'i' + sourceBits\n }],\n type: 'i32'\n };\n result = result2;\n }\n } else {\n // out of bounds and signed\n result = copy(signedFill);\n }\n if (fraction != 0) {\n var other;\n var otherInBounds = j + sign + whole >= 0 && j + sign + whole < sourceElements.length;\n if (otherInBounds || !signed) {\n other = {\n intertype: 'value',\n ident: otherInBounds ? sourceElements[j + sign + whole].ident : '0',\n type: 'i32',\n };\n } else {\n other = copy(signedFill);\n }\n other = {\n intertype: 'mathop',\n op: shiftOp,\n type: 'i32',\n params: [\n other,\n { intertype: 'value', ident: (32 - fraction).toString(), type: 'i32' }\n ]\n };\n result = {\n intertype: 'mathop',\n // shifting in 1s from the top is a special case\n op: (signed && shifts >= 0 && j + sign + whole >= sourceElements.length) ? 'ashr' : shiftOpReverse,\n type: 'i32',\n params: [\n result,\n { intertype: 'value', ident: fraction.toString(), type: 'i32' }\n ]\n };\n result = {\n intertype: 'mathop',\n op: 'or',\n type: 'i32',\n params: [\n result,\n other\n ]\n }\n }\n if (targetElements[j].bits < 32 && shifts < 0) {\n // truncate bits that fall off the end. This is not needed in most cases, can probably be optimized out\n result = {\n intertype: 'mathop',\n op: 'and',\n type: 'i32',\n params: [\n result,\n { intertype: 'value', ident: (Math.pow(2, targetElements[j].bits)-1).toString(), type: 'i32' }\n ]\n }\n }\n if (processor) {\n result = processor(result, j);\n }\n result.assignTo = targetElements[j].ident;\n toAdd.push(result);\n }\n if (targetBits <= 32) {\n // We are generating a normal legal type here\n legalValue = { intertype: 'value', ident: targetElements[0].ident, type: 'i32' };\n if (targetBits < 32) {\n legalValue = {\n intertype: 'mathop',\n op: 'and',\n type: 'i32',\n params: [\n legalValue,\n { intertype: 'value', ident: (Math.pow(2, targetBits)-1).toString(), type: 'i32' }\n ]\n }\n };\n legalValue.assignTo = item.assignTo;\n toAdd.push(legalValue);\n } else if (finalizer) {\n toAdd.push(finalizer());\n }\n i += removeAndAdd(label.lines, i, toAdd);\n continue;\n }\n }\n assert(0, 'Could not legalize illegal line: ' + [item.lineNum, dump(item)]);\n }\n if (dcheck('legalizer')) dprint('zz legalized: \\n' + dump(label.lines));\n });\n });\n }\n\n // Add function lines to func.lines, after our modifications to the label lines\n data.functions.forEach(function(func) {\n func.labels.forEach(function(label) {\n func.lines = func.lines.concat(label.lines);\n });\n });\n }\n\n function addTypeInternal(type) {\n if (type.length == 1) return;\n if (Types.types[type]) return;\n if (['internal', 'hidden', 'inbounds', 'void'].indexOf(type) != -1) return;\n if (Runtime.isNumberType(type)) return;\n dprint('types', 'Adding type: ' + type);\n\n // 'blocks': [14 x %struct.X] etc. If this is a pointer, we need\n // to look at the underlying type - it was not defined explicitly\n // anywhere else.\n var nonPointing = removeAllPointing(type);\n if (Types.types[nonPointing]) return;\n var check = /^\\[(\\d+)\\ x\\ (.*)\\]$/.exec(nonPointing);\n if (check) {\n var num = parseInt(check[1]);\n num = Math.max(num, 1); // [0 x something] is used not for allocations and such of course, but\n // for indexing - for an |array of unknown length|, basically. So we\n // define the 'type' as having a single field. TODO: Ensure as a sanity\n // check that we never allocate with this (either as a child structure\n // in the analyzer, or in calcSize in alloca).\n var subType = check[2];\n addTypeInternal(subType); // needed for anonymous structure definitions (see below)\n\n var fields = [subType, subType]; // Two, so we get the flatFactor right. We care about the flatFactor, not the size here. see calculateStructAlignment\n Types.types[nonPointing] = {\n name_: nonPointing,\n fields: fields,\n lineNum: '?'\n };\n newTypes[nonPointing] = 1;\n // Also add a |[0 x type]| type\n var zerod = '[0 x ' + subType + ']';\n if (!Types.types[zerod]) {\n Types.types[zerod] = {\n name_: zerod,\n fields: fields,\n lineNum: '?'\n };\n newTypes[zerod] = 1;\n }\n return;\n }\n\n // anonymous structure definition, for example |{ i32, i8*, void ()*, i32 }|\n if (type[0] == '{' || type[0] == '<') {\n type = nonPointing;\n var packed = type[0] == '<';\n var internal = type;\n if (packed) {\n if (type[1] !== '{') {\n // vector type, <4 x float> etc.\n var size = getVectorSize(type);\n Types.types[type] = {\n name_: type,\n fields: zeros(size).map(function() {\n return getVectorNativeType(type);\n }),\n packed: false,\n flatSize: 4*size,\n lineNum: '?'\n };\n return;\n }\n if (internal[internal.length-1] != '>') {\n warnOnce('ignoring type ' + internal);\n return; // function pointer or such\n }\n internal = internal.substr(1, internal.length-2);\n }\n assert(internal[0] == '{', internal);\n if (internal[internal.length-1] != '}') {\n warnOnce('ignoring type ' + internal);\n return; // function pointer or such\n }\n internal = internal.substr(2, internal.length-4);\n Types.types[type] = {\n name_: type,\n fields: splitTokenList(tokenize(internal)).map(function(segment) {\n return segment[0].text;\n }),\n packed: packed,\n lineNum: '?'\n };\n newTypes[type] = 1;\n return;\n }\n\n if (isPointerType(type)) return;\n if (['['].indexOf(type) != -1) return;\n Types.types[type] = {\n name_: type,\n fields: [ 'i' + (QUANTUM_SIZE*8) ], // a single quantum size\n flatSize: 1,\n lineNum: '?'\n };\n newTypes[type] = 1;\n }\n\n function addType(type) {\n addTypeInternal(type);\n if (QUANTUM_SIZE === 1) {\n Types.flipTypes();\n addTypeInternal(type);\n Types.flipTypes();\n }\n }\n\n // Typevestigator\n function typevestigator() {\n if (sidePass) { // Do not investigate in the main pass - it is only valid to start to do so in the first side pass,\n // which handles type definitions, and later. Doing so before the first side pass will result in\n // making bad guesses about types which are actually defined\n for (var type in Types.needAnalysis) {\n if (type) addType(type);\n }\n Types.needAnalysis = {};\n }\n }\n\n // Type analyzer\n function analyzeTypes(fatTypes) {\n var types = Types.types;\n\n // 'fields' is the raw list of LLVM fields. However, we embed\n // child structures into parent structures, basically like C.\n // So { int, { int, int }, int } would be represented as\n // an Array of 4 ints. getelementptr on the parent would take\n // values 0, 1, 2, where 2 is the entire middle structure.\n // We also need to be careful with getelementptr to child\n // structures - we return a pointer to the same slab, just\n // a different offset. Likewise, need to be careful for\n // getelementptr of 2 (the last int) - it's real index is 4.\n // The benefit of this approach is inheritance -\n // { { ancestor } , etc. } = descendant\n // In this case it is easy to bitcast ancestor to descendant\n // pointers - nothing needs to be done. If the ancestor were\n // a new slab, it would need some pointer to the outer one\n // for casting in that direction.\n // TODO: bitcasts of non-inheritance cases of embedding (not at start)\n var more = true;\n while (more) {\n more = false;\n for (var typeName in newTypes) {\n var type = types[typeName];\n if (type.flatIndexes) continue;\n var ready = true;\n type.fields.forEach(function(field) {\n if (isStructType(field)) {\n if (!types[field]) {\n addType(field);\n ready = false;\n } else {\n if (!types[field].flatIndexes) {\n newTypes[field] = 1;\n ready = false;\n }\n }\n }\n });\n if (!ready) {\n more = true;\n continue;\n }\n\n Runtime.calculateStructAlignment(type);\n\n if (dcheck('types')) dprint('type (fat=' + !!fatTypes + '): ' + type.name_ + ' : ' + JSON.stringify(type.fields));\n if (dcheck('types')) dprint(' has final size of ' + type.flatSize + ', flatting: ' + type.needsFlattening + ' ? ' + (type.flatFactor ? type.flatFactor : JSON.stringify(type.flatIndexes)));\n }\n }\n\n if (QUANTUM_SIZE === 1 && !fatTypes) {\n Types.flipTypes();\n // Fake a quantum size of 4 for fat types. TODO: Might want non-4 for some reason?\n var trueQuantumSize = QUANTUM_SIZE;\n Runtime.QUANTUM_SIZE = 4;\n analyzeTypes(true);\n Runtime.QUANTUM_SIZE = trueQuantumSize;\n Types.flipTypes();\n }\n\n newTypes = null;\n }\n \n // Variable analyzer\n function variableAnalyzer() {\n // Globals\n\n var old = item.globalVariables;\n item.globalVariables = {};\n old.forEach(function(variable) {\n variable.impl = 'emulated'; // All global variables are emulated, for now. Consider optimizing later if useful\n item.globalVariables[variable.ident] = variable;\n });\n\n // Function locals\n\n item.functions.forEach(function(func) {\n func.variables = {};\n\n // LLVM is SSA, so we always have a single assignment/write. We care about\n // the reads/other uses.\n\n // Function parameters\n func.params.forEach(function(param) {\n if (param.intertype !== 'varargs') {\n if (func.variables[param.ident]) warn('cannot have duplicate variable names: ' + param.ident); // toNiceIdent collisions?\n func.variables[param.ident] = {\n ident: param.ident,\n type: param.type,\n origin: 'funcparam',\n lineNum: func.lineNum,\n rawLinesIndex: -1\n };\n }\n });\n\n // Normal variables\n func.lines.forEach(function(item, i) {\n if (item.assignTo) {\n if (func.variables[item.assignTo]) warn('cannot have duplicate variable names: ' + item.assignTo); // toNiceIdent collisions?\n var variable = func.variables[item.assignTo] = {\n ident: item.assignTo,\n type: item.type,\n origin: item.intertype,\n lineNum: item.lineNum,\n rawLinesIndex: i\n };\n if (variable.origin === 'alloca') {\n variable.allocatedNum = item.ident;\n }\n if (variable.origin === 'call') {\n variable.type = getReturnType(variable.type);\n }\n }\n });\n\n if (QUANTUM_SIZE === 1) {\n // Second pass over variables - notice when types are crossed by bitcast\n\n func.lines.forEach(function(item) {\n if (item.assignTo && item.intertype === 'bitcast') {\n // bitcasts are unique in that they convert one pointer to another. We\n // sometimes need to know the original type of a pointer, so we save that.\n //\n // originalType is the type this variable is created from\n // derivedTypes are the types that this variable is cast into\n func.variables[item.assignTo].originalType = item.type2;\n\n if (!isNumber(item.assignTo)) {\n if (!func.variables[item.assignTo].derivedTypes) {\n func.variables[item.assignTo].derivedTypes = [];\n }\n func.variables[item.assignTo].derivedTypes.push(item.type);\n }\n }\n });\n }\n\n // Analyze variable uses\n\n function analyzeVariableUses() {\n dprint('vars', 'Analyzing variables for ' + func.ident + '\\n');\n\n for (vname in func.variables) {\n var variable = func.variables[vname];\n\n // Whether the value itself is used. For an int, always yes. For a pointer,\n // we might never use the pointer's value - we might always just store to it /\n // read from it. If so, then we can optimize away the pointer.\n variable.hasValueTaken = false;\n\n variable.pointingLevels = pointingLevels(variable.type);\n\n variable.uses = 0;\n }\n\n // TODO: improve the analysis precision. bitcast, for example, means we take the value, but perhaps we only use it to load/store\n var inNoop = 0;\n func.lines.forEach(function(line) {\n walkInterdata(line, function(item) {\n if (item.intertype == 'noop') inNoop++;\n if (!inNoop) {\n if (item.ident in func.variables) {\n func.variables[item.ident].uses++;\n\n if (item.intertype != 'load' && item.intertype != 'store') {\n func.variables[item.ident].hasValueTaken = true;\n }\n }\n }\n }, function(item) {\n if (item.intertype == 'noop') inNoop--;\n });\n });\n\n //if (dcheck('vars')) dprint('analyzed variables: ' + dump(func.variables));\n }\n\n analyzeVariableUses();\n\n // Decision time\n\n for (vname in func.variables) {\n var variable = func.variables[vname];\n var pointedType = pointingLevels(variable.type) > 0 ? removePointing(variable.type) : null;\n if (variable.origin == 'getelementptr') {\n // Use our implementation that emulates pointers etc.\n // TODO Can we perhaps nativize some of these? However to do so, we need to discover their\n // true types; we have '?' for them now, as they cannot be discovered in the intertyper.\n variable.impl = VAR_EMULATED;\n } else if (variable.origin == 'funcparam') {\n variable.impl = VAR_EMULATED;\n } else if (variable.type == 'i64*' && USE_TYPED_ARRAYS == 2) {\n variable.impl = VAR_EMULATED;\n } else if (MICRO_OPTS && variable.pointingLevels === 0) {\n // A simple int value, can be implemented as a native variable\n variable.impl = VAR_NATIVE;\n } else if (MICRO_OPTS && variable.origin === 'alloca' && !variable.hasValueTaken &&\n variable.allocatedNum === 1 &&\n (Runtime.isNumberType(pointedType) || Runtime.isPointerType(pointedType))) {\n // A pointer to a value which is only accessible through this pointer. Basically\n // a local value on the stack, which nothing fancy is done on. So we can\n // optimize away the pointing altogether, and just have a native variable\n variable.impl = VAR_NATIVIZED;\n } else {\n variable.impl = VAR_EMULATED;\n }\n if (dcheck('vars')) dprint('// var ' + vname + ': ' + JSON.stringify(variable));\n }\n });\n }\n\n // Sign analyzer\n //\n // Analyze our variables and detect their signs. In USE_TYPED_ARRAYS == 2,\n // we can read signed or unsigned values and prevent the need for signing\n // corrections. If on the other hand we are doing corrections anyhow, then\n // we can skip this pass.\n //\n // For each variable that is the result of a Load, we look a little forward\n // to see where it is used. We only care about mathops, since only they\n // need signs.\n //\n function signalyzer() {\n if (USE_TYPED_ARRAYS != 2 || CORRECT_SIGNS == 1) return;\n\n function seekIdent(item, obj) {\n if (item.ident === obj.ident) {\n obj.found++;\n }\n }\n\n function seekMathop(item, obj) {\n if (item.intertype === 'mathop' && obj.found && !obj.decided) {\n if (isUnsignedOp(item.op, item.variant)) {\n obj.unsigned++;\n } else {\n obj.signed++;\n }\n }\n }\n\n item.functions.forEach(function(func) {\n func.lines.forEach(function(line, i) {\n if (line.intertype === 'load') {\n // Floats have no concept of signedness. Mark them as 'signed', which is the default, for which we do nothing\n if (line.type in Runtime.FLOAT_TYPES) {\n line.unsigned = false;\n return;\n }\n // Booleans are always unsigned\n var data = func.variables[line.assignTo];\n if (data.type === 'i1') {\n line.unsigned = true;\n return;\n }\n\n var total = data.uses;\n if (total === 0) return;\n var obj = { ident: line.assignTo, found: 0, unsigned: 0, signed: 0, total: total };\n // in loops with phis, we can also be used *before* we are defined\n var j = i-1, k = i+1;\n while(1) {\n assert(j >= 0 || k < func.lines.length, 'Signalyzer ran out of space to look for sign indications for line ' + line.lineNum);\n if (j >= 0 && walkInterdata(func.lines[j], seekIdent, seekMathop, obj)) break;\n if (k < func.lines.length && walkInterdata(func.lines[k], seekIdent, seekMathop, obj)) break;\n if (obj.total && obj.found >= obj.total) break; // see comment below\n j -= 1;\n k += 1;\n }\n\n // unsigned+signed might be < total, since the same ident can appear multiple times in the same mathop.\n // found can actually be > total, since we currently have the same ident in a GEP (see cubescript test)\n // in the GEP item, and a child item (we have the ident copied onto the GEP item as a convenience).\n // probably not a bug-causer, but FIXME. see also a reference to this above\n // we also leave the loop above potentially early due to this. otherwise, though, we end up scanning the\n // entire function in some cases which is very slow\n assert(obj.found >= obj.total, 'Could not Signalyze line ' + line.lineNum);\n line.unsigned = obj.unsigned > 0;\n dprint('vars', 'Signalyzer: ' + line.assignTo + ' has unsigned == ' + line.unsigned + ' (line ' + line.lineNum + ')');\n }\n });\n });\n }\n\n // Quantum fixer\n //\n // See settings.js for the meaning of QUANTUM_SIZE. The issue we fix here is,\n // to correct the .ll assembly code so that things work with QUANTUM_SIZE=1.\n //\n function quantumFixer() {\n if (QUANTUM_SIZE !== 1) return;\n\n // ptrs: the indexes of parameters that are pointers, whose originalType is what we want\n // bytes: the index of the 'bytes' parameter\n // TODO: malloc, realloc?\n var FIXABLE_CALLS = {\n 'memcpy': { ptrs: [0,1], bytes: 2 },\n 'memmove': { ptrs: [0,1], bytes: 2 },\n 'memset': { ptrs: [0], bytes: 2 },\n 'qsort': { ptrs: [0], bytes: 2 }\n };\n\n function getSize(types, type, fat) {\n if (types[type]) return types[type].flatSize;\n if (fat) {\n Runtime.QUANTUM_SIZE = 4;\n }\n var ret = Runtime.getNativeTypeSize(type);\n if (fat) {\n Runtime.QUANTUM_SIZE = 1;\n }\n return ret;\n }\n\n function getFlatIndexes(types, type) {\n if (types[type]) return types[type].flatIndexes;\n return [0];\n }\n\n item.functions.forEach(function(func) {\n function getOriginalType(param) {\n function get() {\n if (param.intertype === 'value' && !isNumber(param.ident)) {\n if (func.variables[param.ident]) {\n return func.variables[param.ident].originalType || null;\n } else {\n return item.globalVariables[param.ident].originalType;\n }\n } else if (param.intertype === 'bitcast') {\n return param.params[0].type;\n } else if (param.intertype === 'getelementptr') {\n if (param.params[0].type[0] === '[') return param.params[0].type;\n }\n return null;\n }\n var ret = get();\n if (ret && ret[0] === '[') {\n var check = /^\\[(\\d+)\\ x\\ (.*)\\]\\*$/.exec(ret);\n assert(check);\n ret = check[2] + '*';\n }\n return ret;\n }\n\n func.lines.forEach(function(line) {\n // Call\n if (line.intertype === 'call') {\n var funcIdent = LibraryManager.getRootIdent(line.ident.substr(1));\n var fixData = FIXABLE_CALLS[funcIdent];\n if (!fixData) return;\n var ptrs = fixData.ptrs.map(function(ptr) { return line.params[ptr] });\n var bytes = line.params[fixData.bytes].ident;\n\n // Only consider original types. This assumes memcpy always has pointers bitcast to i8*\n var originalTypes = ptrs.map(getOriginalType);\n for (var i = 0; i < originalTypes.length; i++) {\n if (!originalTypes[i]) return;\n }\n originalTypes = originalTypes.map(function(type) { return removePointing(type) });\n var sizes = originalTypes.map(function(type) { return getSize(Types.types, type) });\n var fatSizes = originalTypes.map(function(type) { return getSize(Types.fatTypes, type, true) });\n // The sizes may not be identical, if we copy a descendant class into a parent class. We use\n // the smaller size in that case. However, this may also be a bug, it is hard to tell, hence a warning\n warn(dedup(sizes).length === 1, 'All sizes should probably be identical here: ' + dump(originalTypes) + ':' + dump(sizes) + ':' +\n line.lineNum);\n warn(dedup(fatSizes).length === 1, 'All fat sizes should probably be identical here: ' + dump(originalTypes) + ':' + dump(sizes) + ':' +\n line.lineNum);\n var size = Math.min.apply(null, sizes);\n var fatSize = Math.min.apply(null, fatSizes);\n if (isNumber(bytes)) {\n // Figure out how much to copy.\n var fixedBytes;\n if (bytes % fatSize === 0) {\n fixedBytes = size*(bytes/fatSize);\n } else if (fatSize % bytes === 0 && size % (fatSize/bytes) === 0) {\n // Assume this is a simple array. XXX We can be wrong though! See next TODO\n fixedBytes = size/(fatSize/bytes);\n } else {\n // Just part of a structure. Align them to see how many fields. Err on copying more.\n // TODO: properly generate a complete structure, including nesteds, and calculate on that\n var flatIndexes = getFlatIndexes(Types.types, originalTypes[0]).concat(size);\n var fatFlatIndexes = getFlatIndexes(Types.fatTypes, originalTypes[0]).concat(fatSize);\n var index = 0;\n var left = bytes;\n fixedBytes = 0;\n while (left > 0) {\n left -= fatFlatIndexes[index+1] - fatFlatIndexes[index]; // note: we copy the alignment bytes too, which is unneeded\n fixedBytes += flatIndexes[index+1] - flatIndexes[index];\n }\n }\n line.params[fixData.bytes].ident = fixedBytes;\n } else {\n line.params[fixData.bytes].intertype = 'jsvalue';\n // We have an assertion in library::memcpy() that this is round\n line.params[fixData.bytes].ident = size + '*(' + bytes + '/' + fatSize + ')';\n }\n }\n });\n });\n\n // 2nd part - fix hardcoded constant offsets in global constants\n values(item.globalVariables).forEach(function(variable) {\n function recurse(item) {\n if (item.contents) {\n item.contents.forEach(recurse);\n } else if (item.intertype === 'getelementptr' && item.params[0].intertype === 'bitcast' && item.params[0].type === 'i8*') {\n var originalType = removePointing(item.params[0].params[0].type);\n var fatSize = getSize(Types.fatTypes, originalType, true);\n var slimSize = getSize(Types.types, originalType, false);\n assert(fatSize % slimSize === 0);\n item.params.slice(1).forEach(function(param) {\n if (param.intertype === 'value' && isNumber(param.ident)) {\n var corrected = parseInt(param.ident)/(fatSize/slimSize);\n assert(corrected % 1 === 0);\n param.ident = corrected.toString();\n }\n });\n } else if (item.params) {\n item.params.forEach(recurse);\n }\n }\n if (!variable.external && variable.value) recurse(variable.value);\n });\n }\n\n function operateOnLabels(line, func) {\n function process(item, id) {\n ['label', 'labelTrue', 'labelFalse', 'toLabel', 'unwindLabel', 'defaultLabel'].forEach(function(id) {\n if (item[id]) {\n func(item, id);\n }\n });\n }\n if (line.intertype in BRANCH_INVOKE) {\n process(line);\n } else if (line.intertype == 'switch') {\n process(line);\n line.switchLabels.forEach(process);\n }\n }\n\n // Label analyzer\n function labelAnalyzer() {\n item.functions.forEach(function(func) {\n func.labelsDict = {};\n func.labelIds = {};\n func.labelIdsInverse = {};\n func.labelIdCounter = 1;\n func.labels.forEach(function(label) {\n if (!(label.ident in func.labelIds)) {\n func.labelIds[label.ident] = func.labelIdCounter++;\n func.labelIdsInverse[func.labelIdCounter-1] = label.ident;\n }\n });\n var entryIdent = func.labels[0].ident;\n\n // Minify label ids to numeric ids.\n func.labels.forEach(function(label) {\n label.ident = func.labelIds[label.ident];\n label.lines.forEach(function(line) {\n operateOnLabels(line, function(item, id) {\n item[id] = func.labelIds[item[id]].toString(); // strings, because we will append as we process\n });\n });\n });\n\n func.labels.forEach(function(label) {\n func.labelsDict[label.ident] = label;\n });\n\n // Correct phis\n func.labels.forEach(function(label) {\n label.lines.forEach(function(phi) {\n if (phi.intertype == 'phi') {\n for (var i = 0; i < phi.params.length; i++) {\n phi.params[i].label = func.labelIds[phi.params[i].label];\n if (VERBOSE && !phi.params[i].label) warn('phi refers to nonexistent label on line ' + phi.lineNum);\n }\n }\n });\n });\n\n func.lines.forEach(function(line) {\n if (line.intertype == 'indirectbr') {\n func.forceEmulated = true;\n }\n });\n\n function getActualLabelId(labelId) {\n if (func.labelsDict[labelId]) return labelId;\n // If not present, it must be a surprisingly-named entry (or undefined behavior, in which case, still ok to use the entry)\n labelId = func.labelIds[entryIdent];\n assert(func.labelsDict[labelId]);\n return labelId;\n }\n\n // Basic longjmp support, see library.js setjmp/longjmp\n var setjmp = toNiceIdent('@setjmp');\n func.setjmpTable = null;\n for (var i = 0; i < func.labels.length; i++) {\n var label = func.labels[i];\n for (var j = 0; j < label.lines.length; j++) {\n var line = label.lines[j];\n if ((line.intertype == 'call' || line.intertype == 'invoke') && line.ident == setjmp) {\n if (line.intertype == 'invoke') {\n // setjmp cannot trigger unwinding, so just reduce the invoke to a call + branch\n line.intertype = 'call';\n label.lines.push({\n intertype: 'branch',\n label: line.toLabel,\n lineNum: line.lineNum + 0.01, // XXX legalizing might confuse this\n });\n line.toLabel = line.unwindLabel = -2;\n }\n // split this label into up to the setjmp (including), then a new label for the rest. longjmp will reach the rest\n var oldLabel = label.ident;\n var newLabel = func.labelIdCounter++;\n if (!func.setjmpTable) func.setjmpTable = [];\n func.setjmpTable.push({ oldLabel: oldLabel, newLabel: newLabel, assignTo: line.assignTo });\n func.labels.splice(i+1, 0, {\n intertype: 'label',\n ident: newLabel,\n lineNum: label.lineNum + 0.5,\n lines: label.lines.slice(j+1)\n });\n func.labelsDict[newLabel] = func.labels[i+1];\n label.lines = label.lines.slice(0, j+1);\n label.lines.push({\n intertype: 'branch',\n label: toNiceIdent(newLabel),\n lineNum: line.lineNum + 0.01, // XXX legalizing might confuse this\n });\n // Correct phis\n func.labels.forEach(function(label) {\n label.lines.forEach(function(phi) {\n if (phi.intertype == 'phi') {\n for (var i = 0; i < phi.params.length; i++) {\n var sourceLabelId = getActualLabelId(phi.params[i].label);\n if (sourceLabelId == oldLabel) {\n phi.params[i].label = newLabel;\n }\n }\n }\n });\n });\n }\n }\n }\n if (func.setjmpTable) {\n func.forceEmulated = true;\n recomputeLines(func);\n }\n\n // Properly implement phis, by pushing them back into the branch\n // that leads to here. We will only have the |var| definition in this location.\n\n // First, push phis back\n func.labels.forEach(function(label) {\n label.lines.forEach(function(phi) {\n if (phi.intertype == 'phi') {\n for (var i = 0; i < phi.params.length; i++) {\n var param = phi.params[i];\n if (VERBOSE && !param.label) warn('phi refers to nonexistent label on line ' + phi.lineNum);\n var sourceLabelId = getActualLabelId(param.label);\n if (sourceLabelId) {\n var sourceLabel = func.labelsDict[sourceLabelId];\n var lastLine = sourceLabel.lines.slice(-1)[0];\n assert(lastLine.intertype in LLVM.PHI_REACHERS, 'Only some can lead to labels with phis:' + [func.ident, label.ident, lastLine.intertype]);\n if (!lastLine.phi) {\n lastLine.phi = true;\n assert(!lastLine.dependent);\n lastLine.dependent = {\n intertype: 'phiassigns',\n params: []\n };\n };\n lastLine.dependent.params.push({\n intertype: 'phiassign',\n ident: phi.assignTo,\n value: param.value,\n targetLabel: label.ident\n });\n }\n }\n // The assign to phi is now just a var\n phi.intertype = 'var';\n phi.ident = phi.assignTo;\n phi.assignTo = null;\n }\n });\n });\n\n if (func.ident in NECESSARY_BLOCKADDRS) {\n Functions.blockAddresses[func.ident] = {};\n for (var needed in NECESSARY_BLOCKADDRS[func.ident]) {\n assert(needed in func.labelIds);\n Functions.blockAddresses[func.ident][needed] = func.labelIds[needed];\n }\n }\n });\n }\n\n // Stack analyzer - calculate the base stack usage\n function stackAnalyzer() {\n data.functions.forEach(function(func) {\n var lines = func.labels[0].lines;\n var hasAlloca = false;\n for (var i = 0; i < lines.length; i++) {\n var item = lines[i];\n if (!item.assignTo || item.intertype != 'alloca' || !isNumber(item.ident)) break;\n item.allocatedSize = func.variables[item.assignTo].impl === VAR_EMULATED ?\n calcAllocatedSize(item.allocatedType)*item.ident: 0;\n hasAlloca = true;\n if (USE_TYPED_ARRAYS === 2) {\n // We need to keep the stack aligned\n item.allocatedSize = Runtime.forceAlign(item.allocatedSize, Runtime.STACK_ALIGN);\n }\n }\n var index = 0;\n for (var i = 0; i < lines.length; i++) {\n var item = lines[i];\n if (!item.assignTo || item.intertype != 'alloca' || !isNumber(item.ident)) break;\n item.allocatedIndex = index;\n index += item.allocatedSize;\n delete item.allocatedSize;\n }\n func.initialStack = index;\n func.otherStackAllocations = false;\n if (func.initialStack === 0 && hasAlloca) func.otherStackAllocations = true; // a single alloca of zero still requires us to emit stack support code\n while (func.initialStack == 0) { // one-time loop with possible abort in the middle\n // If there is no obvious need for stack management, perhaps we don't need it\n // (we try to optimize that way with SKIP_STACK_IN_SMALL). However,\n // we need to note if stack allocations other than initial allocs can happen here\n // If so, we need to rewind the stack when we leave.\n\n // By-value params are causes of additional allocas (although we could in theory make them normal allocas too)\n func.params.forEach(function(param) {\n if (param.byVal) {\n func.otherStackAllocations = true;\n }\n });\n if (func.otherStackAllocations) break;\n\n // Allocas\n var finishedInitial = false;\n\n lines = func.lines; // We need to consider all the function lines now, not just the first label\n\n for (var i = 0; i < lines.length; i++) {\n var item = lines[i];\n if (!finishedInitial && (!item.assignTo || item.intertype != 'alloca' || !isNumber(item.ident))) {\n finishedInitial = true;\n }\n if (item.intertype == 'alloca' && finishedInitial) {\n func.otherStackAllocations = true;\n break;\n }\n }\n if (func.otherStackAllocations) break;\n\n // Varargs\n for (var i = 0; i < lines.length; i++) {\n var item = lines[i];\n if (item.intertype == 'call' && isVarArgsFunctionType(item.type)) {\n func.otherStackAllocations = true;\n break;\n }\n }\n if (func.otherStackAllocations) break;\n\n break;\n }\n });\n }\n\n // ReLooper - reconstruct nice loops, as much as possible\n // This is now done in the jsify stage, using compiled relooper2\n function relooper() {\n function makeBlock(labels, entries, labelsDict, forceEmulated) {\n if (labels.length == 0) return null;\n dprint('relooping', 'prelooping: ' + entries + ',' + labels.length + ' labels');\n assert(entries && entries[0]); // need at least 1 entry\n\n var emulated = {\n type: 'emulated',\n id: 'B',\n labels: labels,\n entries: entries.slice(0)\n };\n return emulated;\n }\n item.functions.forEach(function(func) {\n dprint('relooping', \"// relooping function: \" + func.ident);\n func.block = makeBlock(func.labels, [func.labels[0].ident], func.labelsDict, func.forceEmulated);\n });\n }\n\n // main\n castAway();\n legalizer();\n typevestigator();\n analyzeTypes();\n variableAnalyzer();\n signalyzer();\n quantumFixer();\n labelAnalyzer();\n stackAnalyzer();\n relooper();\n\n //B.stop('analyzer');\n return item;\n}", "async postParsingAnalysis () {\n var sortedByCount = this.sortEntriesByCount(this.results)\n var topNentries = this.getTopN(sortedByCount, N)\n\n var fileName = `${this.baseOutPath}-${analysisName}.json`\n var fileContent = {\n // Signal and format to visualize as barchart\n piechart: {\n datasets: [{\n backgroundColor: ['#D33F49', '#77BA99', '#23FFD9', '#27B299', '#831A49'],\n data: this.pickCounts(topNentries)\n }],\n labels: this.pickBrowserOS(topNentries)\n },\n hint: ''\n }\n var summary = {\n fileName: fileName,\n attackCategory: 'HTTP',\n analysisName: 'Most used Browser and OS Combinations',\n supportedDiagrams: ['PieChart']\n }\n\n return this.storeAndReturnResult(fileName, fileContent, summary)\n }", "function processAggregate() {\n\n\tvar success = true;\n\tconsole.log(\"\\n2. Validating exported metadata\");\n\n\t//Debug: dump metadata before processing\n\tif (debug) {\n\t\tfs.writeFileSync('.\\\\debug.json', JSON.stringify(metaData));\n\t}\n\n\t//Remove undesired properties from objects\n\tremoveProperties();\n\tremoveNameFromPTEA();\n\tremoveNameFromTETA();\n\n\t//Configure sharing and metadata ownership\n\tconfigureSharing();\n\tconfigureOwnership();\n\n\t//Remove users from user groups\n\tclearUserGroups();\n\n\t//Reset/remove lat/long/zoom on maps\n\tclearMapZoom();\n\tclearMapViews();\n\n\t//Make sure the \"default defaults\" are used\n\tsetDefaultUid();\n\n\t//Make sure we don't include orgunit assigment in datasets or users, or orgunit levels in predictors\n\tclearOrgunitAssignment();\n\n\t//Verify that all data elements referred in indicators, validation rules,\n\t//predictors are included\n\tif (!validateDataElementReference()) success = false;\n\n\t//Remove invalid references to data elements or indicators from groups\n\t//Verify that there are no data elements or indicators without groups\n\tif (!validateGroupReferences()) success = false;\n\n\t//Verify that favourites only use relative orgunits\n\tif (!validateFavoriteOrgunits()) success = false;\n\n\t//Verify that favourites only use indicators\n\tif (!validateFavoriteDataItems()) success = false;\n\n\t//Verify that no unsupported data dimensions are used\n\tif (!validateFavoriteDataDimension()) success = false;\n\n\t//Verify that data sets with section include all data elements\n\tif (!validationDataSetSections()) success = false;\n\n\t/** CUSTOM MODIFICATIONS */\n\tif (currentExport.hasOwnProperty(\"_customFuncs\")) {\n\t\tfor (var customFunc of currentExport._customFuncs) {\n\t\t\tvar func = new Function(\"metaData\", customFunc);\n\t\t\tfunc(metaData);\n\t\t}\n\t}\n\n\tif (success) {\n\t\tconsole.log(\"✔ Validation passed\");\n\t\tsaveAggregate();\n\t}\n\telse {\n\t\tconsole.log(\"\");\n\t\tvar schema = {\n\t\t\tproperties: {\n\t\t\t\tcontinue: {\n\t\t\t\t\tdescription: \"Validation failed. Continue anyway? (yes/no)\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdefault: \"no\",\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tprompt.get(schema, function (err, result) {\n\t\t\tif (result.continue == \"yes\") saveAggregate();\n\t\t\telse cancelCurrentExport();\n\t\t});\n\t}\n}", "writeTypingsFile(dtsFilename, dtsKind) {\n const indentedWriter = new IndentedWriter_1.IndentedWriter();\n this._generateTypingsFileContent(indentedWriter, dtsKind);\n node_core_library_1.FileSystem.writeFile(dtsFilename, indentedWriter.toString(), {\n convertLineEndings: \"\\r\\n\" /* CrLf */,\n ensureFolderExists: true\n });\n }", "function tidy() {\n walker = walk.walk(process.cwd());\n\n walker.on('file', function(root, fileStats, next){\n console.log(fileStats);\n\n // Process stats\n var ext = fileStats.name.split('.')[1];\n var name = fileStats.name;\n var assets = ['jpg', 'gif', 'png', 'mpg', 'txt', 'psd'];\n\n if (ext == 'md') {\n mv('./' + name, './posts/' + name, {mkdirp: true}, function(err){\n if (err) {\n console.log(err.red);\n }\n });\n } else if (assets.indexOf(ext) != -1) {\n mv('./' + name, './assets/' + name, {mkdirp: true}, function(err){\n if (err) {\n console.log(err.red);\n }\n });\n }\n next();\n });\n\n walker.on('errors', function(root, nodeStatsArray, next){\n next();\n });\n\n walker.on('end', function(){\n console.log(\"Finished tidying ✔\".green);\n });\n}", "function processTracker() {\n\n\tvar success = true;\n\tconsole.log(\"\\n2. Validating exported metadata\");\n\n\t//Debug: dump metadata before processing\n\tif (debug) {\n\t\tfs.writeFileSync('.\\\\debug.json', JSON.stringify(metaData));\n\t}\n\n\t//Remove undesired properties from objects\n\tremoveProperties();\n\tremoveNameFromPTEA();\n\tremoveNameFromTETA();\n\n\t//Reset/remove lat/long/zoom on maps\n\tclearMapZoom();\n\tclearMapViews();\n\n\t//Configure sharing and metadata ownership\n\tconfigureSharing();\n\tconfigureOwnership();\n\n\t//Remove users from user groups\n\tclearUserGroups();\n\n\t//Make sure the \"default defaults\" are used\n\tsetDefaultUid();\n\n\t//Make sure we don't include orgunit assigment in datasets or users\n\tclearOrgunitAssignment();\n\n\t//Remove duplicate programStageDataElements\n\tremoveDuplicateObjects();\n\n\t//Verify that all data elements referred in indicators, validation rules,\n\t//predictors are included\n\tif (!validateDataElementReference()) success = false;\n\n\t//Verify that all program indicators referred to in indicators and predictors are included\n\tif (!validateProgramIndicatorReference()) success = false;\n\n\t//Remove invalid references to data elements or indicators from groups\n\t//Verify that there are no data elements or indicators without groups\n\tif (!validateGroupReferences()) success = false;\n\n\t//Verify that favourites only use relative orgunits\n\tif (!validateFavoriteOrgunits()) success = false;\n\n\t//Verify that favourites only use indicators\n\tif (!validateFavoriteDataItems()) success = false;\n\n\t//Verify that no unsupported data dimensions are used\n\tif (!validateFavoriteDataDimension()) success = false;\n\n\t//Verify that data sets with section include all data elements\n\tif (!validationDataSetSections()) success = false;\n\n\n\t/** CUSTOM MODIFICATIONS */\n\tif (currentExport.hasOwnProperty(\"_customFuncs\")) {\n\t\tfor (var customFunc of currentExport._customFuncs) {\n\t\t\tvar func = new Function(\"metaData\", customFunc);\n\t\t\tfunc(metaData);\n\t\t}\n\t}\n\n\tif (success) {\n\t\tconsole.log(\"✔ Validation passed\");\n\t\tsaveTracker();\n\t}\n\telse {\n\t\tconsole.log(\"\");\n\t\tvar schema = {\n\t\t\tproperties: {\n\t\t\t\tcontinue: {\n\t\t\t\t\tdescription: \"Validation failed. Continue anyway? (yes/no)\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdefault: \"no\",\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tif(args.ignoreerrors)\n\t\t{\n\t\t\tsaveTracker();\n\t\t} else {\n\t\t\tprompt.get(schema, function (err, result) {\n\t\t\t\tif (result.continue == \"yes\") saveTracker();\n\t\t\t\telse cancelCurrentExport();\n\t\t\t});\n\t\t}\n\t}\n}", "async postParsingAnalysis () {\n var mapped = Object.keys(this.results).map(addr => {return { addr: addr, count: this.results[addr] }})\n var sortedByCount = this.sortEntriesByCount(mapped)\n var topNentries = this.getTopN(sortedByCount, N)\n\n var fileName = `${this.baseOutPath}-${analysisName}.json`\n var fileContent = {\n // Signal and format to visualize as piechart\n piechart: {\n datasets: [{\n backgroundColor: ['#D33F49', '#77BA99', '#23FFD9', '#27B299', '#831A49'],\n data: this.formatData(topNentries)\n }],\n labels: await this.formatLabelsForPieChart(topNentries)\n },\n hint: 'The labels of this chart have been computed using temporally sensitive data'\n }\n var summary = {\n fileName: fileName,\n attackCategory: 'Network State',\n analysisName: `Top ${N} sources by traffic`,\n supportedDiagrams: ['PieChart']\n }\n return await this.storeAndReturnResult(fileName, fileContent, summary)\n }", "_run()\n {\n var info = this._getInfoFromPackageJson()\n\n if (Tester.is(this._output, 'function')) {\n this._output('################################################')\n this._output(info.label)\n this._output(info.labelDescription)\n this._output('################################################')\n }\n\n var start = new Date()\n\n // @todo Progress bar start.\n\n this._runTestMethods()\n\n // @todo Progress bar stop.\n\n var end = new Date()\n var time = end - start\n var formatTime = time > 1000 ? (time / 1000).toFixed(1) + ' seconds' : time + ' miliseconds'\n var memoryBytes = process.memoryUsage().heapTotal\n var trace = Tester.getBacktrace(new Error(), 3)\n\n this._resultsJson = {\n info: info,\n errors: this._errors,\n ok: this._ok,\n all: this._all,\n className: this.constructor.name,\n assertionsCounter: this._assertionsCounter,\n testsCounter: this._testsCounter,\n timeMiliseconds: time,\n formatTime: formatTime,\n memoryBytes: memoryBytes,\n formatMemory: Tester.formatBytes(memoryBytes),\n from: trace\n }\n\n if (Tester.is(this._output, 'function')) {\n var arr = this._showOk === true ? this._all : this._errors\n for (let value of arr) {\n if (this._colorize === true) {\n // reverse red\n value = value.replace(/^Error:/, '\\x1b[31m\\x1b[7mError:\\x1b[0m')\n // reverse\n value = value.replace(/^Ok:/, '\\x1b[7mOk:\\x1b[0m')\n }\n this._output(value)\n }\n\n var className = this.constructor.name + ':'\n\n this._output(className)\n this._output(' - tests ' + this._testsCounter)\n this._output(' - assertions ' + this._assertionsCounter)\n this._output(' - errors ' + this._errors.length)\n this._output(' - time ' + formatTime)\n this._output(' - memory ' + Tester.formatBytes(memoryBytes))\n this._output(' - from ' + trace)\n this._output('')\n }\n }", "setupSchema() {\n\t\tfor (const type in this.Definition) {\n\t\t\tif (this.Definition.hasOwnProperty(type)) {\n\t\t\t\t// console.log(type);\n\t\t\t\tconst typeDef = this.Definition[type];\n\t\t\t\tthis.Schema[type] = oas.compile(typeDef);\n\t\t\t}\n\t\t}\n\t\tfor (const type in this.precompiled) {\n\t\t\tif (this.precompiled.hasOwnProperty(type)) {\n\t\t\t\t// console.log(type);\n\t\t\t\tconst typeDef = this.precompiled[type];\n\t\t\t\tthis.Schema[type] = typeDef;\n\t\t\t}\n\t\t}\n\t}", "async function main() {\n const modelManager = await ModelLoader.loadModelManagerFromModelFiles([metaModelCto], {strict: true});\n const visitor = new TypescriptVisitor();\n const fileWriter = new FileWriter(path.resolve(__dirname, '..', 'src', 'generated'));\n const parameters = { fileWriter };\n modelManager.accept(visitor, parameters);\n}", "function processDataFromDocusky() {\n\tparseDocInfo();\n\ttoolSetting();\n}", "function process() \n{\n\t//Read parameters\n\tvar theform = document.theform;\n\n\touttype = 0;\n\tif (theform.outtype[1].checked) outtype = 1;\n\tif (theform.outtype[2].checked) outtype = 2;\n\n\tprintRules = true; //theform.report.checked;\n\tshowDiff = theform.showdiff.checked;\n\trewout = theform.rewout.checked;\n \n // flush all arrays\n all_rules = [];\n all_rewrites = [];\n all_categories = [];\n applied_rules = {};\n \n\t// Stuff we can do once\n\ts = readStuff();\n\n\t// If that went OK, apply the rules\n\tif (s.length == 0) {\n\n\t\tDoWords();\n\t}\n \n // now, check the goodness of fit\n var goodness = compareAO();\n s += '</li><li>Correct conversions: '+goodness[0] + ' from '+goodness[4] + ' ('+goodness[2]+'%)';\n s += '</li><li>Wrong conversions: '+goodness[1] + ' from '+goodness[4] + ' ('+goodness[3]+'%)';\n s += '</li></ul>';\n if(goodness[2] > 50)\n {\n s += '<span style=\"color:red;font-weight:bold;\">Great, the rules you defined already explain more than half of all words!</span>';\n }\n else\n {\n s += '<span style=\"color:red;font-weight:bold;\">Well, less than half of all words can be explained. Maybe you should try a bit harder...</span>';\n }\n\n // insert the quality of the rules\n s += '<h3>Rule Evaluation</h3><ul>';\n for(rule in applied_rules)\n {\n s += '<li style=\"list-style:circle\"><code>\"'+rule+'\"</code> applies to '+applied_rules[rule]+' words.</li>';\n }\n s += '</ul>';\n\n\t// Set the output field\n\tdocument.getElementById(\"mytext\").innerHTML = s;\n \n}", "function analysisObject () {\n this.type;\n this.elements;\n this.numOfElements;\n this.timeScale;\n}", "process (filepath) {\n\t\tlet {\n\t\t\tchassis,\n\t\t\tgenerateNamespacedSelector,\n\t\t\tisNamespaced,\n\t\t\tnamespaceSelectors,\n\t\t\tprocessImports,\n\t\t\tprocessNesting,\n\t\t\tprocessAtRules,\n\t\t\tprocessMixins,\n\t\t\tprocessNot,\n\t\t\tprocessFunctions,\n\t\t\tstoreAtRules,\n\t\t\ttypographyEngineIsInitialized\n\t\t} = this\n\n\t\tlet {\n\t\t\tatRules,\n\t\t\tpost,\n\t\t\tsettings,\n\t\t\tutils\n\t\t} = chassis\n\n\t\tlet tasks = new NGN.Tasks()\n\t\tlet sourceMap\n\n\t\ttasks.add('Processing Imports', next => {\n\t\t\tif (typographyEngineIsInitialized) {\n\t\t\t\tthis.tree.walkAtRules('import', atRule => {\n\t\t\t\t\tchassis.imports.push(atRule.params)\n\t\t\t\t\tatRule.remove()\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tprocessImports()\n\t\t\tprocessNesting()\n\t\t\tnext()\n\t\t})\n\n\t\ttasks.add('Processing Mixins', next => {\n\t\t\tprocessMixins()\n\t\t\tprocessNot()\n\t\t\tprocessNesting()\n\n\t\t\tnext()\n\t\t})\n\n\t\ttasks.add('Processing Functions', next => {\n\t\t\tprocessFunctions()\n\t\t\tnext()\n\t\t})\n\n\t\ttasks.add('Namespacing Selectors', next => {\n\t\t\tnamespaceSelectors()\n\t\t\tnext()\n\t\t})\n\n\t\tif (typographyEngineIsInitialized) {\n\t\t\ttasks.add('Initializing Typography Engine', next => {\n\t\t\t\tthis.tree = this.core.css.append(this.tree)\n\t\t\t\tnext()\n\t\t\t})\n\t\t}\n\n\t\ttasks.add('Running Post-Processing Routines', next => {\n\t\t\tthis.tree.walkAtRules('chassis-post', atRule => {\n\t\t\t\tlet data = Object.assign({\n\t\t\t\t\troot: this.tree,\n\t\t\t\t\tatRule\n\t\t\t\t}, atRules.getProperties(atRule))\n\n\t\t\t\tpost.process(data)\n\t\t\t})\n\n\t\t\tnext()\n\t\t})\n\n\t\ttasks.add('Processing CSS4 Syntax', next => {\n\t\t\tenv.process(this.tree, {from: filepath}, settings.envCfg).then(processed => {\n\t\t\t\tthis.tree = processed.root\n\t\t\t\tnext()\n\t\t\t}, err => console.error(err))\n\t\t})\n\n\t\t// tasks.add('Merging matching adjacent rules...', next => {\n\t\t// \toutput = mergeAdjacentRules.process(output.toString())\n\t\t// \tnext()\n\t\t// })\n\n\t\ttasks.add('Beautifying Output', next => {\n\t\t\tremoveComments.process(this.tree).then(result => {\n\t\t\t\tperfectionist.process(result.css).then(result => {\n\t\t\t\t\tthis.tree = result.root\n\n\t\t\t\t\t// Remove empty rulesets\n\t\t\t\t\tthis.tree.walkRules(rule => {\n\t\t\t\t\t\tif (rule.nodes.length === 0) {\n\t\t\t\t\t\t\trule.remove()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\n\t\t\t\t\tnext()\n\t\t\t\t}, () => {\n\t\t\t\t\tthis.emit('processing.error', new Error('Error Beautifying Output'))\n\t\t\t\t})\n\t\t\t}, () => {\n\t\t\t\tthis.emit('processing.error', new Error('Error Removing Comments'))\n\t\t\t})\n\t\t})\n\n\t\tif (settings.minify) {\n\t\t\tlet minified\n\n\t\t\ttasks.add('Minifying Output', next => {\n\t\t\t\tminified = new CleanCss({\n\t\t\t\t\tsourceMap: settings.sourceMap\n\t\t\t\t}).minify(this.tree.toString())\n\n\t\t\t\tthis.tree = minified.styles\n\t\t\t\tnext()\n\t\t\t})\n\n\t\t\tif (settings.sourceMap) {\n\t\t\t\ttasks.add('Generating source map', next => {\n\t\t\t\t\tsourceMap = minified.sourceMap.toString()\n\t\t\t\t\tnext()\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// tasks.on('taskstart', evt => console.log(`${evt.name}...`))\n\t\t// tasks.on('taskcomplete', evt => console.log('Done.'))\n\n\t\ttasks.on('complete', () => this.emit('processing.complete', {\n\t\t\tcss: this.tree.toString(),\n\t\t\tsourceMap\n\t\t}))\n\n\t\tthis.emit('processing')\n\t\ttasks.run(true)\n\t}", "function analyzeMoodVsProductivity () {\n\ttry {\n\t\tshowProgressBar();\n\t\t// Get the name of the project, its owner and \"restriction\" value from input fields\n\t\tprojectName = $(\"#project\").val();\n\t\tprojectOwner = $(\"#owner\").val();\t\n\t\trestriction = $(\"#restriction\")[0].checked;\n\t\t// Starts analysis\n\t\tvar result = analyze();\n\t\thideProgressBar();\n\t} catch (exception) {\n\t\texceptionHandler(exception);\n\t}\n\t// Shows result of the analysis\n\tshowResult(result);\n}", "function postRespec() {\n\taddTextSemantics();\n\tswapInDefinitions();\n\ttermTitles();\n\tlinkUnderstanding();\n}", "function analyze(sourceCode) {\n machineState = 1;\n currentLineNumber = 1;\n currentLexemeCode = 1;\n definedIdns = [];\n $('.errors-container').empty();\n var lexemes = parseLexemes(sourceCode);\n lexemes = setIdnsConstsCodes(lexemes);\n lexemes = fixMinus(lexemes);\n lexemes = setLexemeCodes(lexemes);\n printLexemes(lexemes);\n printConsts(lexemes);\n printIdns(lexemes);\n var syntaxAnalyzer = new SyntaxAnalyzer(lexemes);\n syntaxAnalyzer.analyze();\n printSyntaxErrors(syntaxAnalyzer.errors);\n\n const lexemeChain = lexemes.map((lexeme) => {\n let type = '';\n switch (lexeme.lexemeCode) {\n case 32: type = 'idn'; break;\n case 33: type = 'con'; break;\n default: type = 'operation'; break;\n }\n return new PolizItem(lexeme.lexemeName, type);\n });\n\n const polizBuilder = new PolizBuilder();\n const poliz = polizBuilder.build(lexemeChain);\n $('#poliz-chain').empty();\n poliz.chain.forEach(item => {\n $('#poliz-chain').append(item.token + ' ');\n });\n\n $('#poliz-history tbody').empty();\n polizBuilder.history.forEach(historyItem => {\n $('#poliz-history tbody').append(\n `<tr><td>${historyItem.lexeme.token}</td>\n <td>${historyItem.stack}</td>\n <td>${historyItem.poliz}</td>\n </tr>`\n );\n });\n\n $('#poliz-labels tbody').empty();\n poliz.polizLabels.forEach(label => {\n $('#poliz-labels tbody').append(\n `<tr><td>${label.label}</td>\n <td>${label.position}</td>\n </tr>`\n );\n });\n\n const polizExecutor = new PolizExecutor(\n poliz.chain, poliz.polizLabels, poliz.polizCells, idns\n );\n\n polizExecutor.execute();\n $('#console').empty();\n polizExecutor.outputData.forEach(item => {\n $('#console').append(\n `<div>${item.token} ${item.value}</div>`);\n });\n\n $('#poliz-execution-history tbody').empty();\n polizExecutor.history.forEach(item => {\n $('#poliz-execution-history tbody').append(\n `<tr><td>${item.lexeme}</td>\n <td>${item.stack}</td>\n </tr>`\n );\n });\n Array.prototype.last = function() {\n return this[this.length-1];\n };\n Array.prototype.clone = function() {\n return this.slice(0);\n };\n\n}", "async function run () {\n shell.echo(`Analyzing ${path.join(originProtoPath)} directory`);\n if (funcList.length > 0) {\n shell.echo(`${funcList.length} proto files found`);\n for (const func of funcList) {\n try {\n await func();\n } catch (e) {\n shell.echo('Code generation operation couldn\\'t be completed');\n } \n }\n shell.echo(`Generated code stored in ${path.join(destCodePath)}`);\n }\n else {\n shell.echo('No proto files found');\n }\n}", "function main() {\n const allResults = [];\n fs.readdirSync(constants.OUT_PATH).forEach(siteDir => {\n const sitePath = path.resolve(constants.OUT_PATH, siteDir);\n if (!utils.isDir(sitePath)) {\n return;\n }\n allResults.push({site: siteDir, results: analyzeSite(sitePath)});\n });\n const generatedResults = groupByMetrics(allResults);\n fs.writeFileSync(\n GENERATED_RESULTS_PATH,\n `var generatedResults = ${JSON.stringify(generatedResults)}`\n );\n console.log('Opening the charts web page...'); // eslint-disable-line no-console\n opn(path.resolve(__dirname, 'index.html'));\n}", "function runAnalysis () {\n ee.initialize(null, null, geeScript, initializationError);\n}", "async validate(){\n \n // ensure classes \n if(!this.apexClassNames || this.apexClassNames.length == 0)\n throw new Error('No Apex classes prescribed in pset.');\n\n // get each of the class bodies via tooling\n this.classBodies = ''; \n try{\n stdio.warn(`Retrieving ${this.apexClassNames.length > 1 ? 'classes' : 'class'} ${this.apexClassNames.join(', ')} from ${ config.mode === 'local' ? 'default local directory...' : 'authorized SF org...' }`);\n for(let apexClass of await tooling.getApex(this.apexClassNames)){\n // replace any instances of static methods with static global-level variables, \n // and remove the static method keywords, such that apex class calls to static methods\n // are immitated\n const name = apexClass.name; \n let body = apexClass.body; \n if(apexClass.body.indexOf(' static ') != -1){\n this.globalVars.push(`// mimic static method(s) in class ${name}\\nstatic ${name} ${name} = new ${name}();`);\n body = body.replace(new RegExp(/ static /, 'gi'), ` /** static method mimicked by var '${name}' **/ `); \n }\n this.classBodies += `${body}\\n\\n`;\n }\n } catch(e){\n throw e; \n }\n\n // construct anonymous body\n try{\n stdio.warn('Constructing tests...'); \n const anonBody = buildAnonTest(this); \n stdio.warn('Validating assertions in authorized org...');\n await tooling.executeAnonApex(anonBody); \n } catch(e){\n throw e; \n }\n\n }", "function beginProcessing (data) {\n var len = data.length;\n if (data.length === 0) {\n alert(\"Nothing entered\");\n } else {\n \tdata = data.toLowerCase();\n //look for word delimiters\n var delimiters = '.:;?! !@#$%^&*()+';\n var words = splitTokens(data, delimiters); //http://p5js.org/reference/#/p5/splitTokens\n tokens = words;\n tokens \n for (var i = 0; i < words.length; i++) {\n var word = words[i];\n totalSyllables += countSyllables(word);\n totalWords++;\n }\n //look for sentence delimiters\n var sentenceDelim = '.:;?!';\n var sentences = splitTokens(data, sentenceDelim);\n phrases = sentences;\n totalSentences = sentences.length;\n calculateFlesch(totalSyllables, totalWords, totalSentences);\n // findWordFrequency();\n avgWordsPerSentence = totalWords / totalSentences;\n avgSyllablesPerSentence = totalSyllables / totalSentences;\n avgSyllablesPerWord = totalSyllables / totalWords;\n\t flesch = + flesch.toFixed(3);\n\t avgWordsPerSentence = +avgWordsPerSentence.toFixed(3);\n\t avgSyllablesPerSentence = +avgSyllablesPerSentence.toFixed(3);\n\t avgSyllablesPerWord = +avgSyllablesPerWord.toFixed(3);\n report += \"Total Syllables : \" + totalSyllables +\"\\n\";\n report += \"Total Words : \" + totalWords + \"\\n\";\n report += \"Total Sentences : \" + totalSentences + \"\\n\";\n report += \"Avg Words Per Sentence : \" + avgWordsPerSentence + \"\\n\";\n report += \"Avg Syllables Per Word : \" + avgSyllablesPerWord + \"\\n\";\n report += \"Avg Syllables Per Sentence : \" + avgSyllablesPerSentence + \"\\n\";\n report += \"Flesch Readability Index : \" + flesch + \"\\n\";\n // report += \"Word Frequency Counter (Ignore the 'undefined') : \" + \"<br>\";\n // report += wordCounterString;\n // var wordCounterString = keys[i] + \" : \" + concordance[keys[i];\n //\tReadability scales the Flesch index into a more managable number\n // var basicTextResults = createP(report);\n createNewDiv();\n }\n}", "function semanticAnalysis(CST, programCount) {\n //From the CST, build the AST\t\n buildAST(CST.root);\n //Print the AST\n log(\"Abstract Syntax Tree for Program \" + programCount + \": <br />\");\n AST.toString(AST.root, \"-\");\n //Scope and type check the AST\n scopeAndTypeCheck(AST.root);\n //Print the symbol table\n SymbolTableInstance.toString(SymbolTableInstance.root, \"-\");\n //Generate machine code\n codeGeneration();\n //reset all these globals\n AST = new AbstractSyntaxTree(null, null);\n currentScope = null;\n SymbolTableInstance = new SymbolTable(null, null);\n activeValue = null;\n}", "transform(program) {\n var options = AsxFormatter.options(this.file.ast);\n //DefaultFormatter.prototype.transform.apply(this, arguments);\n\n var locals = [];\n var definitions = [];\n var body = [];\n program.body.forEach(item=>{\n switch(item.type){\n case 'ExpressionStatement':\n var exp = item.expression;\n if(exp.type=='Literal' && exp.value.toLowerCase()=='use strict'){\n return;\n }\n break;\n case 'VariableDeclaration':\n item.declarations.forEach(d=>{\n locals.push(d.id);\n });\n break;\n case 'FunctionDeclaration':\n if(item.id.name=='module'){\n item.body.body.forEach(s=>{\n body.push(s);\n })\n return;\n }else\n if(item._class){\n item.id =t.identifier('c$'+item._class);\n body.push(t.expressionStatement(t.callExpression(\n t.memberExpression(\n t.identifier('asx'),\n t.identifier('c$')\n ),[item])));\n return;\n }else{\n locals.push(item.id);\n }\n break;\n }\n body.push(item);\n });\n\n var definer = [];\n\n\n\n if(Object.keys(this.imports).length){\n\n Object.keys(this.imports).forEach(key=>{\n var items = this.imports[key];\n if(items['*'] && typeof items['*']=='string'){\n this.imports[key]=items['*'];\n }\n });\n definer.push(t.property('init',\n t.identifier('imports'),\n t.valueToNode(this.imports)\n ))\n }\n var exports;\n if(this.exports['*']){\n exports = this.exports['*'];\n delete this.exports['*'];\n }\n if(Object.keys(this.exports).length){\n definer.push(t.property('init',\n t.identifier('exports'),\n t.valueToNode(this.exports)\n ))\n }\n if(body.length){\n if(exports){\n var ret = [];\n Object.keys(exports).forEach(key=>{\n var val = exports[key];\n if(typeof val=='string') {\n ret.push(t.property('init',\n t.literal(key), t.identifier(val == '*' ? key : val)\n ))\n }else{\n ret.push(t.property('init',\n t.literal(key), val\n ))\n }\n });\n body.push(t.returnStatement(\n t.objectExpression(ret)\n ));\n }\n var initializer = t.functionExpression(null, [t.identifier('asx')], t.blockStatement(body));\n definer.push(t.property('init',\n t.identifier('execute'),\n initializer\n ))\n }\n definitions.forEach(item=>{\n\n if(item._class){\n definer.push(t.property('init',\n t.literal('.'+item._class),\n item\n ))\n }else{\n definer.push(t.property('init',\n t.literal(':'+item.id.name),\n item\n ))\n }\n\n })\n definer = t.objectExpression(definer);\n\n\n\n /*\n var definer = t.functionExpression(null, [t.identifier(\"module\")], t.blockStatement(body));\n if(options.bind){\n definer = t.callExpression(\n t.memberExpression(\n definer,\n t.identifier(\"bind\")\n ),[\n t.callExpression(t.identifier(\"eval\"),[t.literal(\"this.global=this\")])\n ]\n );\n }*/\n var body = [];\n var definer = util.template(\"asx-module\",{\n MODULE_NAME: t.literal(this.getModuleName()),\n MODULE_BODY: definer\n });\n if(options.runtime){\n var rt = util.template(\"asx-runtime\")\n //rt._compact = true;\n body.push(t.expressionStatement(rt));\n }\n body.push(t.expressionStatement(definer))\n program.body = body;\n }", "function healthCheckCallback(healthCheckResults) {\n console.log(\"Results are ready.\");\n var newSource = sfp.readFile('test-output/temp.js');\n // healthCheckResults.source = sfp.readFile(tempFilePath);\n healthCheckResults.source = realSource;\n healthCheckResults.processedSource = newSource;\n runJsDoc(projectPath + '/test-output', healthCheckResults);\n }", "inferHoleTypesCommand() {\n const editor = atom.workspace.getActiveTextEditor();\n if (helper.isElmEditor(editor)) {\n const origCode = editor.getText();\n const modifiedCode = origCode.replace(new RegExp('(^|\\\\s|\\\\n)(' + _.escapeRegExp(helper.holeToken()) + ')(\\\\s|$)', 'g'), '$1' + dummyType() + '$3');\n const inputCode = modifiedCode + '\\n' + 'type ' + dummyType() + ' = ' + dummyType();\n if (origCode !== modifiedCode) {\n this.inferQueue.push({\n inputCode,\n inferenceType: HOLE_TYPES,\n inferenceName: helper.holeToken(),\n editor,\n shouldDecorate: true,\n shouldDestroyOnChange: true,\n shouldShowAutocomplete: false,\n getInferenceFunction: (problem, editor) => {\n return {\n type: getInferredTypeFromProblem(problem),\n range: getHoleRangeFromProblem(problem, editor)\n };\n }\n });\n }\n }\n }", "function phoneticAnalysisHandler() { \n const currentTask = \"phonetic\";\n const taskDiv = window.utils.createEl('div'), \n taskHeading = window.utils.createEl('p'), \n submitButton = window.utils.createEl('button'),\n warning = window.utils.createEl('p'),\n divWrapper = window.utils.createEl('section'),\n pWrapper = window.utils.createEl('section');\n const word = _.sample(window.tasks.phoneticAnalysis);\n for (let i = 0; i < word.length; i++){\n pWrapper.appendChild(window.utils.createEl('p'));\n pWrapper.lastChild.classList.add('word');\n pWrapper.lastChild.textContent = word[i];\n } \n\n _.forEach(window.tasks.lettersTypes, function(value) {\n divWrapper.appendChild(window.utils.createEl('div'));\n divWrapper.lastChild.textContent = value;\n divWrapper.lastChild.classList.add('lettersType');\n });\n\n taskDiv.classList.add('task');\n taskDiv.classList.add('phonetic');\n taskHeading.classList.add('task-heading');\n pWrapper.classList.add('p-wrapper');\n divWrapper.classList.add('div-wrapper');\n submitButton.classList.add('submit-button');\n taskHeading.textContent = \"Определи гласные и согласные буквы\";\n submitButton.textContent = \"Я сделал!\";\n\n const storage = [];\n storage.push(taskHeading, divWrapper, pWrapper, submitButton, warning);\n storage.forEach(function(el){taskDiv.appendChild(el);});\n window.utils.addDocumentFragment(taskDiv, taskWrapper);\n\n const pairs = dragAndDrop(\".word\", \".lettersType\");\n submitButton.addEventListener('click', checkAnswer);\n function checkAnswer(){\n if (pWrapper.firstChild) { \n warning.textContent = 'Выполни задание'\n } else {\n const condition = checkPairs(pairs, window.tasks.alphabet);\n window.main.isCorrect(condition, taskDiv, taskWrapper, currentTask);\n }\n }\n }" ]
[ "0.5682125", "0.55620515", "0.5528616", "0.54487497", "0.5186837", "0.51358396", "0.50535023", "0.50306", "0.49961954", "0.49456286", "0.4872391", "0.48717216", "0.48588556", "0.48485678", "0.48256865", "0.48208138", "0.47816533", "0.4761912", "0.46887577", "0.46489328", "0.4623182", "0.46193558", "0.46093798", "0.46055996", "0.46006897", "0.45900068", "0.4583237", "0.45783898", "0.45715025", "0.45589852" ]
0.59221
0
Generates the typings file and writes it to disk.
writeTypingsFile(dtsFilename, dtsKind) { const indentedWriter = new IndentedWriter_1.IndentedWriter(); this._generateTypingsFileContent(indentedWriter, dtsKind); node_core_library_1.FileSystem.writeFile(dtsFilename, indentedWriter.toString(), { convertLineEndings: "\r\n" /* CrLf */, ensureFolderExists: true }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function typings() {\n const tmpDir = './typings/tmp';\n const blocklySrcs = [\n \"core/\",\n \"core/components\",\n \"core/components/tree\",\n \"core/components/menu\",\n \"core/keyboard_nav\",\n \"core/renderers/common\",\n \"core/renderers/measurables\",\n \"core/theme\",\n \"core/utils\",\n \"msg/\"\n ];\n // Clean directory if exists.\n if (fs.existsSync(tmpDir)) {\n rimraf.sync(tmpDir);\n }\n fs.mkdirSync(tmpDir);\n\n // Find all files that will be included in the typings file.\n let files = [];\n blocklySrcs.forEach((src) => {\n files = files.concat(fs.readdirSync(src)\n .filter(fn => fn.endsWith('.js'))\n .map(fn => path.join(src, fn)));\n });\n\n // Generate typings file for each file.\n files.forEach((file) => {\n const typescriptFileName = `${path.join(tmpDir, file)}.d.ts`;\n if (file.indexOf('core/msg.js') > -1) {\n return;\n }\n const cmd = `node ./node_modules/typescript-closure-tools/definition-generator/src/main.js ${file} ${typescriptFileName}`;\n console.log(`Generating typings for ${file}`);\n execSync(cmd, { stdio: 'inherit' });\n });\n\n const srcs = [\n 'typings/parts/blockly-header.d.ts',\n 'typings/parts/blockly-interfaces.d.ts',\n `${tmpDir}/core/**`,\n `${tmpDir}/core/components/**`,\n `${tmpDir}/core/components/tree/**`,\n `${tmpDir}/core/components/menu/**`,\n `${tmpDir}/core/keyboard_nav/**`,\n `${tmpDir}/core/renderers/common/**`,\n `${tmpDir}/core/renderers/measurables/**`,\n `${tmpDir}/core/utils/**`,\n `${tmpDir}/core/theme/**`,\n `${tmpDir}/msg/**`\n ];\n return gulp.src(srcs)\n .pipe(gulp.concat('blockly.d.ts'))\n .pipe(gulp.dest('typings'))\n .on('end', function () {\n // Clean up tmp directory.\n if (fs.existsSync(tmpDir)) {\n rimraf.sync(tmpDir);\n }\n });\n}", "processTypings(files) {\n // Set hashes of the app's typings.\n files.forEach(file => {\n let isAppTypings = this.isDeclarationFile(file) &&\n !this.isPackageFile(file);\n\n let path = file.getPathInPackage();\n if (isAppTypings && !this._typingsMap.has(path)) {\n this._typingsMap.set(path, file.getSourceHash());\n }\n });\n\n let copiedFiles = [];\n // Process package typings.\n files.forEach(file => {\n // Check if it's a package declaration file.\n let isPkgTypings = this.isDeclarationFile(file) &&\n this.isPackageFile(file);\n\n if (isPkgTypings) {\n let path = file.getPathInPackage();\n // Check if the file is in the \"typings\" folder.\n if (!this._typingsRegEx.test(path)) {\n console.log('Typings path ${path} doesn\\'t start with \"typings\"');\n return;\n }\n\n let filePath = this._getStandardTypingsFilePath(file);\n let oldHash = this._typingsMap.get(filePath);\n let newHash = file.getSourceHash();\n // Copy file if it doesn't exist or has been updated.\n if (oldHash !== newHash) {\n this._copyTypings(filePath, file.getContentsAsString());\n this._typingsMap.set(filePath, newHash);\n copiedFiles.push(filePath);\n }\n }\n });\n\n if (copiedFiles.length) {\n // Report about added/updated typings.\n console.log(chalk.green('***** Typings that have been added/updated *****'));\n copiedFiles.forEach(filePath => {\n console.log(chalk.green(filePath));\n });\n console.log(chalk.green(\n 'Add typings in tsconfig.json or by references in files.'));\n }\n }", "function generateTypes(options = {}) {\n const { files, generateDocuments, generateSchemaTypes, schemaPath } = options;\n return new Promise((resolve, reject) => {\n gqlGenTool({\n file: schemaPath,\n template: 'typescript',\n // out: outPath,\n args: files,\n documents: generateDocuments,\n schema: generateSchemaTypes,\n }).then(\n value => {\n // console.log('end gen', value);\n const resultStr = value[0].content;\n\n // check for clashing namespace names\n const exportedNamespaces = (resultStr.match(/export namespace (\\S+) \\{/g) || []).map(\n m => m.match(/export namespace (\\S+) {/)[1],\n );\n\n if (exportedNamespaces.length !== _.uniq(exportedNamespaces).length) {\n const namesMap = exportedNamespaces.reduce((acc, v) => {\n acc[v] = acc[v] === undefined ? 1 : acc[v] + 1;\n return acc;\n }, {});\n const clashingNames = Object.keys(namesMap).filter(n => namesMap[n] > 1);\n return reject(new Error(`Query/Mutation names clash for ${clashingNames.join(', ')}`));\n }\n\n // prettify the result\n const prettifiedResultStr = prettier.format(\n resultStr,\n Object.assign(\n {\n parser: 'typescript',\n },\n prettierConfig,\n ),\n );\n\n resolve(prettifiedResultStr);\n },\n error => {\n console.log('yp-schema: types generation error', error);\n reject(error);\n },\n );\n });\n}", "function generateTypes(assetsFolder, silent = false) {\n if (!silent) {\n log(`generating new asset .d.ts files in \"${assetsFolder}\" . . .`);\n }\n const pattern = `${assetsFolder}/**/*.@(${extensionPattern})`;\n const fileNames = glob.sync(pattern, {}).map((f) => f + \".d.ts\");\n fileNames.forEach((fileName) => {\n fs.writeFileSync(fileName, getContent(fileName));\n if (!silent) {\n log(\" - created \" + fileName);\n }\n });\n if (fileNames.length === 0 && !silent) {\n log(\"No files to generate\");\n }\n\n generateManifest(assetsFolder, silent);\n\n return fileNames;\n}", "function writeDefs() {\n return sclang.interpret(`\n var descs = Dictionary.new;\n SynthDescLib.default.synthDescs\n .keysValuesDo({ arg defName, synthDesc;\n synthDesc.def.writeDefFile(\"` +\n dest +\n `\");\n descs[defName] = synthDesc.asJSON();\n });\n descs\n `);\n }", "generate() {\n // Make sure the temporary directory is empty before starting\n gen_utils_1.deleteDirRecursive(this.tempDir);\n fs_extra_1.default.mkdirsSync(this.tempDir);\n try {\n // Generate each model\n const models = [...this.models.values()];\n for (const model of models) {\n this.write('model', model, model.fileName, 'models');\n }\n // Generate each service\n const services = [...this.services.values()];\n for (const service of services) {\n this.write('service', service, service.fileName, 'services');\n }\n // Context object passed to general templates\n const general = {\n services: services,\n models: models\n };\n // Generate the general files\n this.write('configuration', general, this.globals.configurationFile);\n this.write('response', general, this.globals.responseFile);\n this.write('requestBuilder', general, this.globals.requestBuilderFile);\n this.write('baseService', general, this.globals.baseServiceFile);\n if (this.globals.moduleClass && this.globals.moduleFile) {\n this.write('module', general, this.globals.moduleFile);\n }\n const modelImports = this.globals.modelIndexFile || this.options.indexFile\n ? models.map(m => new imports_1.Import(m.name, './models', m.options)) : null;\n if (this.globals.modelIndexFile) {\n this.write('modelIndex', Object.assign(Object.assign({}, general), { modelImports }), this.globals.modelIndexFile);\n }\n if (this.globals.serviceIndexFile) {\n this.write('serviceIndex', general, this.globals.serviceIndexFile);\n }\n if (this.options.indexFile) {\n this.write('index', Object.assign(Object.assign({}, general), { modelImports }), 'index');\n }\n // Now synchronize the temp to the output folder\n gen_utils_1.syncDirs(this.tempDir, this.outDir, this.options.removeStaleFiles !== false);\n console.info(`Generation from ${this.options.input} finished with ${models.length} models and ${services.length} services.`);\n }\n finally {\n // Always remove the temporary directory\n gen_utils_1.deleteDirRecursive(this.tempDir);\n }\n }", "function generateDefs() {\n console.log(' + generating definitions')\n\n const dPath = path.resolve(process.env.DEFINITIONS)\n\n const definitions = require(path.resolve(`${process.env.LIB_DIR}definitions`))\n const spec = require(path.resolve(`${process.env.LIB_DIR}spec`)).load()\n\n fs.mkdirSync(dPath, { recursive: true })\n\n // Generate all Definitions\n for (const definition in spec.definitions) {\n definitions.generateFullDefinition(definition)\n }\n\n console.log(' - definitions generated')\n}", "function _scriptGen({ params: { c: optionsFile, write } }) {\n // console.log(\"gen sources for \", optionsFile);\n const options = _loadOptionsFile(optionsFile);\n const config = new Config(options);\n\n // console.log(config);\n const { value: valuePackages, type: typeOptions } = scanSourceDir(\n path.join(config.projectPath, config.rootPath)\n );\n // console.log(\"a\", optionsSource);\n\n const generatedOptions = {\n ...options,\n packages: {\n ...options.packages,\n ...valuePackages,\n },\n types: typeOptions,\n };\n\n delete generatedOptions.projectPath;\n\n const genFile = optionsFile.replace(\".json\", \".gen.json\");\n fs.writeFileSync(genFile, JSON.stringify(generatedOptions, null, 2));\n}", "function generateDocumentation(fileNames, options, docOptions) {\n if (docOptions === void 0) { docOptions = {}; }\n var dtsVueGeneratedFiles = [];\n generateVueTSFiles(fileNames);\n var tsOptions = getTsOptions(options);\n if (!checkFiles(fileNames, \"File for compiling is not found\"))\n return;\n var host = ts.createCompilerHost(tsOptions);\n // Build a program using the set of root file names in fileNames\n var program = ts.createProgram(fileNames, tsOptions, host);\n // Get the checker, we will use it to find more about classes\n var checker = program.getTypeChecker();\n var outputClasses = [];\n var outputPMEs = [];\n var pmesHash = {};\n var classesHash = {};\n var curClass = null;\n var curJsonName = null;\n var generateJSONDefinitionClasses = {};\n var dtsOutput = !!docOptions ? docOptions.dtsOutput : undefined;\n var generateDts = !!dtsOutput;\n var generateJSONDefinition = docOptions.generateJSONDefinition === true;\n var generateDocs = !generateDts || docOptions.generateDoc !== false;\n var outputDefinition = {};\n var dtsExportedClasses = {};\n var dtsExportClassesFromLibraries = [];\n var dtsImports = {};\n var dtsExcludeImports = docOptions.dtsExcludeImports === true;\n var dtsExportNames = [];\n if (!!docOptions.paths) {\n for (key in docOptions.paths)\n dtsExportNames.push(key);\n }\n var dtsImportDeclarations = {};\n var dtsFrameworksImportDeclarations = {};\n var dtsDeclarations = {};\n var dtsTypesParameters = {};\n var dtsTypesArgumentParameters = {};\n var dtsProductName = docOptions.name;\n var dtsLicense = docOptions.license;\n var dtsVersion = \"\";\n // Visit every sourceFile in the program\n for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) {\n var sourceFile = _a[_i];\n if (sourceFile.fileName.indexOf(\"node_modules\") > 0)\n continue;\n if (isNonEnglishLocalizationFile(sourceFile.fileName))\n continue;\n // Walk the tree to search for classes\n ts.forEachChild(sourceFile, visit);\n }\n for (var i = 0; i < fileNames.length; i++) {\n var sourceFile = program.getSourceFile(fileNames[i]);\n if (!!sourceFile) {\n ts.forEachChild(sourceFile, visit);\n }\n }\n for (var key in classesHash) {\n setAllParentTypes(key);\n }\n if (generateDocs) {\n updateEventsDocumentation();\n // print out the doc\n fs.writeFileSync(process.cwd() + \"/docs/classes.json\", JSON.stringify(outputClasses, undefined, 4));\n fs.writeFileSync(process.cwd() + \"/docs/pmes.json\", JSON.stringify(outputPMEs, undefined, 4));\n }\n if (generateJSONDefinition) {\n outputDefinition[\"$schema\"] = \"http://json-schema.org/draft-07/schema#\";\n outputDefinition[\"title\"] = \"SurveyJS Library json schema\";\n addClassIntoJSONDefinition(\"SurveyModel\", true);\n fs.writeFileSync(process.cwd() + \"/docs/surveyjs_definition.json\", JSON.stringify(outputDefinition, undefined, 4));\n }\n if (generateDts) {\n prepareDtsInfo();\n dtsImportFiles(docOptions.paths);\n var text = \"\";\n if (!!dtsProductName) {\n dtsVersion = dtsGetVersion();\n text += dtsGetBanner();\n }\n text += dtsGetText();\n fs.writeFileSync(getAbsoluteFileName(dtsOutput), text);\n }\n deleteVueTSFiles();\n return;\n function generateVueTSFiles(fileNames) {\n for (var i = 0; i < fileNames.length; i++) {\n var fn = fileNames[i];\n var text = fs.readFileSync(getAbsoluteFileName(fn), 'utf8');\n var dir = path.dirname(fn);\n generateVueTSFile(text, dir);\n var matchArray = text.match(/(?<=export \\* from \")(.*)(?=\";)/gm);\n if (!Array.isArray(matchArray))\n continue;\n for (var i = 0; i < matchArray.length; i++) {\n var fnChild = path.join(dir, matchArray[i] + \".ts\");\n var absFnChild = getAbsoluteFileName(fnChild);\n if (!fs.existsSync(absFnChild))\n return;\n text = fs.readFileSync(absFnChild, 'utf8');\n generateVueTSFile(text, dir);\n }\n }\n }\n function generateVueTSFile(text, dir) {\n var matchArray = text.match(/(?<=\")(.*)(?=.vue\";)/gm);\n if (!Array.isArray(matchArray))\n return;\n for (var i = 0; i < matchArray.length; i++) {\n var fileName = path.join(dir, matchArray[i] + \".vue\");\n if (!fs.existsSync(fileName))\n continue;\n var absFileName = getAbsoluteFileName(fileName);\n var vueText = fs.readFileSync(absFileName, 'utf8');\n var startStr = \"<script lang=\\\"ts\\\">\";\n var endStr = \"</script>\";\n var startIndex = vueText.indexOf(startStr) + startStr.length;\n var endIndex = vueText.lastIndexOf(endStr);\n if (endIndex > startIndex && startIndex > 0) {\n var vue_tsText = vueText.substring(startIndex, endIndex);\n absFileName += \".ts\";\n dtsVueGeneratedFiles.push(absFileName);\n fs.writeFileSync(absFileName, vue_tsText);\n }\n }\n }\n function deleteVueTSFiles() {\n for (var i = 0; i < dtsVueGeneratedFiles.length; i++) {\n fs.unlinkSync(dtsVueGeneratedFiles[i]);\n }\n }\n function isNonEnglishLocalizationFile(fileName) {\n var dir = path.dirname(fileName);\n var name = path.basename(fileName);\n if (name === \"english\")\n return false;\n var loc = \"localization\";\n return dir.lastIndexOf(loc) > dir.length - loc.length - 3;\n }\n function dtsGetVersion() {\n var fileName = getAbsoluteFileName(\"package.json\");\n if (!fs.existsSync(fileName))\n return \"\";\n var text = fs.readFileSync(fileName, 'utf8');\n if (!text)\n return \"\";\n var matches = text.match(/(?<=\"version\":)(.*)(?=,)/gm);\n if (!Array.isArray(matches) || matches.length === 0)\n return \"\";\n var res = matches[0];\n if (!res)\n return \"\";\n return res.trim().replace(\"\\\"\", \"\").replace(\"\\\"\", \"\");\n }\n function dtsGetBanner() {\n var lines = [];\n lines.push(\"/*\");\n var paddging = \"* \";\n lines.push(paddging + dtsProductName + (dtsVersion ? \" v\" + dtsVersion : \"\"));\n lines.push(paddging + \"Copyright (c) 2015-\" + new Date().getFullYear() + \" Devsoft Baltic OÜ - https://surveyjs.io/\");\n if (dtsLicense) {\n lines.push(paddging + \"License: \" + dtsLicense);\n }\n lines.push(\"*/\");\n lines.push(\"\");\n return lines.join(\"\\n\");\n }\n /** set allParentTypes */\n function setAllParentTypes(className) {\n if (!className)\n return;\n var cur = classesHash[className];\n if (cur.allTypes && cur.allTypes.length > 0)\n return;\n setAllParentTypesCore(cur);\n }\n function setAllParentTypesCore(cur) {\n cur.allTypes = [];\n cur.allTypes.push(cur.name);\n if (cur.entryType === DocEntryType.interfaceType && Array.isArray(cur.implements)) {\n cur.implements.forEach(function (item) { return addBaseAllTypesIntoCur(cur, item); });\n }\n if (!cur.baseType)\n return;\n addBaseAllTypesIntoCur(cur, cur.baseType);\n }\n function addBaseAllTypesIntoCur(cur, className) {\n if (!className)\n return;\n var baseClass = classesHash[className];\n if (!baseClass)\n return;\n if (!baseClass.allTypes) {\n setAllParentTypesCore(baseClass);\n }\n for (var i = 0; i < baseClass.allTypes.length; i++) {\n cur.allTypes.push(baseClass.allTypes[i]);\n }\n }\n /** visit nodes finding exported classes */\n function visit(node) {\n // Only consider exported nodes\n if (!isNodeExported(node))\n return;\n if (node.kind === ts.SyntaxKind.EnumDeclaration) {\n var enNode = node;\n var symbol = checker.getSymbolAtLocation(enNode.name);\n if (!!symbol && generateDts) {\n visitEnumNode(enNode, symbol);\n }\n }\n else if (node.kind === ts.SyntaxKind.FunctionDeclaration) {\n var fnNode = node;\n var symbol = checker.getSymbolAtLocation(fnNode.name);\n if (!!symbol && generateDts) {\n visitFunctionNode(fnNode, symbol);\n }\n }\n else if (node.kind === ts.SyntaxKind.VariableStatement) {\n var vsNode = node;\n if (vsNode.declarationList.declarations.length > 0) {\n var varNode = vsNode.declarationList.declarations[0];\n var symbol = checker.getSymbolAtLocation(varNode.name);\n if (!!symbol && (generateDts || isSymbolHasComments(symbol))) {\n visitVariableNode(varNode, symbol);\n }\n }\n }\n else if (node.kind === ts.SyntaxKind.ClassDeclaration) {\n // This is a top level class, get its symbol\n var symbol = checker.getSymbolAtLocation(node.name);\n if (!symbol)\n return;\n if (generateDts || isSymbolHasComments(symbol)) {\n visitDocumentedNode(node, symbol);\n }\n }\n else if (node.kind === ts.SyntaxKind.InterfaceDeclaration) {\n // This is a top level class, get its symbol\n var name_1 = node.name;\n var symbol = checker.getSymbolAtLocation(name_1);\n if (generateDts || isSymbolHasComments(symbol) || isOptionsInterface(name_1.text)) {\n visitDocumentedNode(node, symbol);\n }\n }\n else if (node.kind === ts.SyntaxKind.ModuleDeclaration) {\n // This is a namespace, visit its children\n ts.forEachChild(node, visit);\n }\n else if (node.kind === ts.SyntaxKind.ExportDeclaration) {\n visitExportDeclarationNode(node);\n }\n }\n function visitExportDeclarationNode(node) {\n if (!node.exportClause)\n return;\n if (isExportFromDtsFile(node))\n return;\n var els = node.exportClause.elements;\n if (!Array.isArray(els))\n return;\n var exportLibrary = getExportLibraryName(node);\n for (var i = 0; i < els.length; i++) {\n var el = els[i];\n if (!el.name || !el.propertyName && !exportLibrary)\n continue;\n var name_2 = el.name.text;\n if (!name_2)\n continue;\n if (!exportLibrary && dtsImportDeclarations[name_2])\n continue;\n var entry = { name: name_2 };\n if (!!el.propertyName) {\n entry.className = el.propertyName.text;\n }\n if (!!exportLibrary) {\n entry.fileName = exportLibrary;\n }\n dtsExportClassesFromLibraries.push(entry);\n }\n }\n function isExportFromDtsFile(node) {\n if (!node.parent)\n return false;\n var file = node.parent.getSourceFile();\n if (!file)\n return false;\n return file.fileName.indexOf(\".d.ts\") > -1;\n }\n function getExportLibraryName(node) {\n var name = !!node.moduleSpecifier ? node.moduleSpecifier.text : undefined;\n if (!name)\n return undefined;\n return dtsExportNames.indexOf(name) > -1 ? name : undefined;\n }\n function visitVariableNode(node, symbol) {\n var entry = serializeSymbol(symbol);\n entry.entryType = DocEntryType.variableType;\n dtsDeclarations[entry.name] = entry;\n visitVariableProperties(entry, node);\n if (generateDocs) {\n entry.allTypes = [entry.name];\n entry.isPublic = true;\n outputClasses.push(entry);\n entry.members = [];\n }\n }\n function visitEnumNode(node, symbol) {\n var modifier = ts.getCombinedModifierFlags(node);\n if ((modifier & ts.ModifierFlags.Export) === 0)\n return;\n var entry = {\n name: symbol.name,\n entryType: DocEntryType.enumType,\n members: []\n };\n dtsDeclarations[entry.name] = entry;\n for (var i = 0; i < node.members.length; i++) {\n var member = node.members[i];\n var sym = checker.getSymbolAtLocation(member.name);\n if (!!sym && !!sym.name) {\n var id = !!member.initializer ? member.initializer.text : undefined;\n entry.members.push({ name: sym.name, returnType: id });\n }\n }\n }\n function visitFunctionNode(node, symbol) {\n var modifier = ts.getCombinedModifierFlags(node);\n if ((modifier & ts.ModifierFlags.Export) === 0)\n return;\n var entry = serializeMethod(symbol, node);\n if (!entry)\n return;\n entry.entryType = DocEntryType.functionType;\n dtsDeclarations[entry.name] = entry;\n }\n function visitVariableProperties(entry, node) {\n if (!node.initializer)\n return;\n var children = node.initializer.properties;\n if (!Array.isArray(children))\n return;\n for (var i = 0; i < children.length; i++) {\n visitVariableMember(entry, children[i]);\n }\n }\n function visitVariableMember(entry, node) {\n var symbol = checker.getSymbolAtLocation(node.name);\n var memberEntry = serializeClass(symbol, node);\n if (memberEntry) {\n if (!entry.members)\n entry.members = [];\n entry.members.push(memberEntry);\n entry.members.push(memberEntry);\n if (generateDocs) {\n if (entry.entryType === DocEntryType.variableType) {\n outputPMEs.push(memberEntry);\n memberEntry.className = entry.name;\n memberEntry.pmeType = \"property\";\n memberEntry.isPublic = true;\n memberEntry.isField = true,\n memberEntry.hasSet = true;\n }\n }\n visitVariableProperties(memberEntry, node);\n }\n }\n function visitDocumentedNode(node, symbol) {\n curClass = serializeClass(symbol, node);\n classesHash[curClass.name] = curClass;\n var isOptions = curClass.name.indexOf(\"IOn\") === 0;\n if (!isOptions) {\n outputClasses.push(curClass);\n }\n curJsonName = null;\n ts.forEachChild(node, visitClassNode);\n if (isOptions)\n return;\n if (!curJsonName)\n return;\n curClass.jsonName = curJsonName;\n if (!jsonObjMetaData || !generateDocs)\n return;\n var properties = jsonObjMetaData.getProperties(curJsonName);\n for (var i = 0; i < outputPMEs.length; i++) {\n if (outputPMEs[i].className == curClass.name) {\n var propName = outputPMEs[i].name;\n for (var j = 0; j < properties.length; j++) {\n if (properties[j].name == propName) {\n outputPMEs[i].isSerialized = true;\n if (properties[j].defaultValue)\n outputPMEs[i].defaultValue = properties[j].defaultValue;\n if (properties[j].choices)\n outputPMEs[i].serializedChoices = properties[j].choices;\n if (properties[j].className)\n outputPMEs[i].jsonClassName = properties[j].className;\n break;\n }\n }\n }\n }\n }\n function visitClassNode(node) {\n var symbol = null;\n if (node.kind === ts.SyntaxKind.MethodDeclaration)\n symbol = checker.getSymbolAtLocation(node.name);\n if (node.kind === ts.SyntaxKind.FunctionDeclaration)\n symbol = checker.getSymbolAtLocation(node.name);\n if (node.kind === ts.SyntaxKind.PropertyDeclaration)\n symbol = checker.getSymbolAtLocation(node.name);\n if (node.kind === ts.SyntaxKind.GetAccessor)\n symbol = checker.getSymbolAtLocation(node.name);\n if (node.kind === ts.SyntaxKind.SetAccessor)\n symbol = checker.getSymbolAtLocation(node.name);\n if (node.kind === ts.SyntaxKind.PropertySignature)\n symbol = checker.getSymbolAtLocation(node.name);\n if (node.kind === ts.SyntaxKind.MethodSignature)\n symbol = checker.getSymbolAtLocation(node.name);\n if (!symbol)\n return;\n if (!isPMENodeExported(node, symbol))\n return;\n var ser = serializeMember(symbol, node);\n var fullName = ser.name;\n if (curClass) {\n ser.className = curClass.name;\n ser.jsonName = curClass.jsonName;\n fullName = curClass.name + \".\" + fullName;\n if (!curClass.members)\n curClass.members = [];\n curClass.members.push(ser);\n }\n ser.pmeType = getPMEType(node.kind);\n var modifier = ts.getCombinedModifierFlags(node);\n if ((modifier & ts.ModifierFlags.Static) !== 0) {\n ser.isStatic = true;\n }\n if ((modifier & ts.ModifierFlags.Protected) !== 0) {\n ser.isProtected = true;\n }\n if (node.kind === ts.SyntaxKind.PropertyDeclaration\n && !ser.isLocalizable\n && ser.isField === undefined) {\n ser.isField = true;\n }\n if (node.kind === ts.SyntaxKind.PropertySignature) {\n ser.isField = true;\n ser.isOptional = checker.isOptionalParameter(node);\n }\n if (isSurveyEventType(ser.type)) {\n ser.pmeType = \"event\";\n updateEventOptionInterfaceName(node, ser);\n if (!ser.documentation && (ser.eventSenderName === \"__type\" || !ser.eventOptionsName)) {\n ser = null;\n }\n }\n if (node.kind === ts.SyntaxKind.GetAccessor) {\n ser.isField = false;\n var serSet = pmesHash[fullName];\n if (serSet) {\n ser.hasSet = serSet.hasSet;\n }\n else\n ser.hasSet = false;\n }\n if (node.kind === ts.SyntaxKind.SetAccessor) {\n var serGet = pmesHash[fullName];\n if (serGet) {\n serGet.hasSet = true;\n ser.isField = false;\n }\n ser = null;\n }\n if (ser) {\n if (!ser.parameters)\n ser.parameters = [];\n pmesHash[fullName] = ser;\n outputPMEs.push(ser);\n }\n if (ser && ser.name === \"getType\") {\n curJsonName = getJsonTypeName(node);\n }\n }\n function getJsonTypeName(node) {\n var body = node.getFullText();\n if (body) {\n var pos = body.indexOf('return \"');\n if (pos > 0) {\n body = body.substr(pos + 'return \"'.length);\n pos = body.indexOf('\"');\n return body.substr(0, pos);\n }\n }\n return null;\n }\n function isSurveyEventType(type) {\n return !!type && (type.indexOf(\"Event\") === 0 || type.indexOf(\"CreatorEvent\") === 0);\n }\n function getPMEType(nodeKind) {\n if (nodeKind === ts.SyntaxKind.MethodDeclaration || nodeKind === ts.SyntaxKind.MethodSignature)\n return \"method\";\n if (nodeKind === ts.SyntaxKind.FunctionDeclaration)\n return \"function\";\n return \"property\";\n }\n function getTypeOfSymbol(symbol) {\n if (symbol.valueDeclaration)\n return checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration);\n return checker.getDeclaredTypeOfSymbol(symbol);\n }\n function updateEventOptionInterfaceName(node, ser) {\n var typeObj = checker.getTypeAtLocation(node);\n if (!typeObj)\n return;\n var args = typeObj.typeArguments;\n if (!Array.isArray(args) || args.length < 2)\n return;\n ser.eventSenderName = getSymbolName(args[args.length - 2].symbol);\n ser.eventOptionsName = getSymbolName(args[args.length - 1].symbol);\n }\n function getSymbolName(symbol) {\n return !!symbol && !!symbol.name ? symbol.name : \"\";\n }\n /** Serialize a symbol into a json object */\n function serializeSymbol(symbol) {\n var type = getTypeOfSymbol(symbol);\n var docParts = symbol.getDocumentationComment(undefined);\n var modifiedFlag = !!symbol.valueDeclaration ? ts.getCombinedModifierFlags(symbol.valueDeclaration) : 0;\n var isPublic = (modifiedFlag & ts.ModifierFlags.Public) !== 0;\n var res = {\n name: symbol.getName(),\n documentation: !!docParts ? ts.displayPartsToString(docParts) : \"\",\n type: checker.typeToString(type),\n isPublic: isPublic\n };\n var jsTags = symbol.getJsDocTags();\n if (jsTags) {\n var seeArray = [];\n for (var i = 0; i < jsTags.length; i++) {\n if (jsTags[i].name == \"title\") {\n res[\"metaTitle\"] = jsTags[i].text;\n }\n if (jsTags[i].name == \"description\") {\n res[\"metaDescription\"] = jsTags[i].text;\n }\n if (jsTags[i].name == \"see\") {\n seeArray.push(jsTags[i].text);\n }\n if (jsTags[i].name == \"returns\") {\n res[\"returnDocumentation\"] = jsTags[i].text;\n }\n }\n if (seeArray.length > 0) {\n res[\"see\"] = seeArray;\n }\n }\n return res;\n }\n /** Serialize a class symbol information */\n function serializeClass(symbol, node) {\n var details = serializeSymbol(symbol);\n details.implements = getImplementedTypes(node, details.name);\n setTypeParameters(details.name, node);\n if (node.kind === ts.SyntaxKind.InterfaceDeclaration) {\n details.entryType = DocEntryType.interfaceType;\n }\n if (node.kind !== ts.SyntaxKind.ClassDeclaration)\n return details;\n // Get the construct signatures\n var constructorType = checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration);\n details.entryType = DocEntryType.classType;\n details.constructors = getConstructors(constructorType);\n createPropertiesFromConstructors(details);\n var firstHeritageClauseType = getFirstHeritageClauseType(node);\n details.baseType = getBaseType(firstHeritageClauseType);\n setTypeParameters(details.baseType, firstHeritageClauseType, details.name);\n return details;\n }\n function getConstructors(constructorType) {\n var res = [];\n var signitures = constructorType.getConstructSignatures();\n for (var i = 0; i < signitures.length; i++) {\n if (!signitures[i].declaration)\n continue;\n res.push(serializeSignature(signitures[i]));\n }\n return res;\n }\n function createPropertiesFromConstructors(entry) {\n if (!Array.isArray(entry.constructors))\n return;\n for (var i = 0; i < entry.constructors.length; i++) {\n createPropertiesFromConstructor(entry, entry.constructors[i]);\n }\n }\n function createPropertiesFromConstructor(classEntry, entry) {\n if (!Array.isArray(entry.parameters))\n return;\n for (var i = 0; i < entry.parameters.length; i++) {\n var param = entry.parameters[i];\n if (!param.isPublic)\n continue;\n if (!classEntry.members)\n classEntry.members = [];\n classEntry.members.push({ name: param.name, pmeType: \"property\", isField: true, isPublic: true, type: param.type });\n }\n }\n function getHeritageClause(node, index) {\n if (!node || !node.heritageClauses || node.heritageClauses.length <= index)\n return undefined;\n return node.heritageClauses[index];\n }\n function getFirstHeritageClauseType(node) {\n var clause = getHeritageClause(node, 0);\n return !!clause ? clause.types[0] : undefined;\n }\n function getImplementedTypes(node, className) {\n if (!node || !node.heritageClauses)\n return undefined;\n var clauses = node.heritageClauses;\n if (!Array.isArray(clauses) || clauses.length == 0)\n return undefined;\n var res = [];\n for (var i = 0; i < clauses.length; i++) {\n getImplementedTypesForClause(res, clauses[i], className);\n }\n return res;\n }\n function getImplementedTypesForClause(res, clause, className) {\n if (!clause || !Array.isArray(clause.types))\n return undefined;\n for (var i = 0; i < clause.types.length; i++) {\n var name_3 = getBaseType(clause.types[i]);\n if (!!name_3) {\n res.push(name_3);\n setTypeParameters(name_3, clause.types[i], className);\n }\n }\n }\n function getBaseType(firstHeritageClauseType) {\n if (!firstHeritageClauseType)\n return \"\";\n var extendsType = checker.getTypeAtLocation(firstHeritageClauseType.expression);\n var expression = firstHeritageClauseType.expression;\n if (extendsType && extendsType.symbol) {\n var name_4 = extendsType.symbol.name;\n if (!!expression.expression && expression.expression.escapedText)\n return expression.expression.escapedText + \".\" + name_4;\n return name_4;\n }\n if (!!expression.text)\n return expression.text;\n if (!!expression.expression && !!expression.expression.text && !!expression.name && !!expression.name.text)\n return expression.expression.text + \".\" + expression.name.text;\n return \"\";\n }\n function setTypeParameters(typeName, node, forTypeName) {\n if (!typeName || !node)\n return;\n var parameters = getTypedParameters(node, !!forTypeName);\n if (!parameters)\n return;\n if (!forTypeName) {\n dtsTypesParameters[typeName] = parameters;\n }\n else {\n var args = dtsTypesArgumentParameters[typeName];\n if (!args) {\n args = {};\n dtsTypesArgumentParameters[typeName] = args;\n }\n args[forTypeName] = parameters;\n }\n }\n function getTypedParameters(node, isArgument) {\n var params = getTypeParametersDeclaration(node, isArgument);\n if (!params || !Array.isArray(params))\n return undefined;\n var res = [];\n for (var i = 0; i < params.length; i++) {\n var name_5 = getTypeParameterName(params[i], isArgument);\n var extendsType = getTypeParameterConstrains(params[i]);\n res.push(name_5 + extendsType);\n }\n return res.length > 0 ? res : undefined;\n }\n function getTypeParameterName(node, isArgument) {\n var symbol = checker.getSymbolAtLocation(isArgument ? node.typeName : node.name);\n if (!!symbol && symbol.name)\n return symbol.name;\n return \"any\";\n }\n function getTypeParameterConstrains(node) {\n if (!node[\"default\"])\n return \"\";\n var first = getTypeParameterName(node[\"default\"], true);\n var second = !!node.constraint ? getTypeParameterName(node.constraint, true) : \"\";\n if (!first)\n return \"\";\n if (!!second)\n return \" extends \" + first + \" = \" + second;\n return \" = \" + first;\n }\n function getTypeParametersDeclaration(node, isArgument) {\n if (!node)\n return undefined;\n if (!isArgument && !!node.typeParameters)\n return node.typeParameters;\n if (isArgument && !!node.typeArguments)\n return node.typeArguments;\n if (isArgument && !!node.elementType)\n return [node.elementType];\n return undefined;\n }\n function serializeMember(symbol, node) {\n var details = serializeSymbol(symbol);\n if (getPMEType(node.kind) !== \"property\") {\n setupMethodInfo(details, symbol, node);\n }\n else {\n details.isLocalizable = getIsPropertyLocalizable(node);\n if (details.isLocalizable) {\n details.hasSet = true;\n }\n }\n return details;\n }\n /** Serialize a method symbol infomration */\n function serializeMethod(symbol, node) {\n var details = serializeSymbol(symbol);\n setupMethodInfo(details, symbol, node);\n return details;\n }\n function setupMethodInfo(entry, symbol, node) {\n var signature = checker.getSignatureFromDeclaration(node);\n var funDetails = serializeSignature(signature);\n entry.parameters = funDetails.parameters;\n entry.returnType = funDetails.returnType;\n entry.typeGenerics = getTypedParameters(node, false);\n entry.returnTypeGenerics = getTypedParameters(node.type, true);\n if (entry.returnType === \"Array\" && !entry.returnTypeGenerics) {\n entry.returnTypeGenerics = [\"any\"];\n }\n }\n function getIsPropertyLocalizable(node) {\n if (!Array.isArray(node.decorators))\n return false;\n for (var i = 0; i < node.decorators.length; i++) {\n var decor = node.decorators[i];\n var expression = decor.expression[\"expression\"];\n var decor_arguments = decor.expression[\"arguments\"];\n if (!expression || !Array.isArray(decor_arguments))\n continue;\n var sym = checker.getSymbolAtLocation(expression);\n if (!sym || sym.name !== \"property\")\n continue;\n for (var j = 0; j < decor_arguments.length; j++) {\n var arg = decor_arguments[j];\n var props = arg[\"properties\"];\n if (!Array.isArray(props))\n continue;\n for (var k = 0; k < props.length; k++) {\n var name_6 = props[k][\"name\"];\n if (!name_6)\n continue;\n var symName = checker.getSymbolAtLocation(name_6);\n if (!!symName && symName.name === \"localizable\")\n return true;\n }\n }\n }\n return false;\n }\n /** Serialize a signature (call or construct) */\n function serializeSignature(signature) {\n var params = signature.parameters;\n var res = {\n parameters: params.map(serializeSymbol),\n returnType: getReturnType(signature),\n documentation: ts.displayPartsToString(signature.getDocumentationComment(undefined))\n };\n for (var i = 0; i < params.length; i++) {\n var node = params[i].valueDeclaration;\n if (!!node) {\n res.parameters[i].isOptional = checker.isOptionalParameter(node);\n }\n }\n return res;\n }\n function getReturnType(signature) {\n var res = checker.typeToString(signature.getReturnType());\n if (res === \"{}\")\n res = \"any\";\n if (res !== \"any\")\n return res;\n var type = signature.declaration.type;\n if (!type)\n return res;\n if (type.kind === ts.SyntaxKind.ArrayType)\n return \"Array\";\n if (!type[\"typeName\"])\n return res;\n var name = type[\"typeName\"].text;\n return !!name ? name : res;\n }\n /** True if this is visible outside this file, false otherwise */\n function isNodeExported(node) {\n return ((node.flags & ts.NodeFlags[\"Export\"]) !== 0 ||\n (node.parent && node.parent.kind === ts.SyntaxKind.SourceFile));\n }\n function isPMENodeExported(node, symbol) {\n var modifier = ts.getCombinedModifierFlags(node);\n if ((modifier & ts.ModifierFlags.Public) !== 0)\n return true;\n if (generateDts && modifier === 0)\n return true;\n if (generateDts && (modifier & ts.ModifierFlags.Protected) !== 0)\n return true;\n if (node.kind === ts.SyntaxKind.PropertyDeclaration)\n return true;\n if (isSymbolHasComments(symbol))\n return true;\n /*\n let docTags = symbol.getJsDocTags();\n if(Array.isArray(docTags) && docTags.length > 0) return true;\n if(!!symbol.valueDeclaration) {\n docTags = symbol.valueDeclaration[\"jsDoc\"];\n if(Array.isArray(docTags) && docTags.length > 0) return true;\n }\n */\n var parent = node.parent;\n return parent && parent.kind === ts.SyntaxKind.InterfaceDeclaration;\n }\n /** True if there is a comment before declaration */\n function isSymbolHasComments(symbol) {\n var com = symbol.getDocumentationComment(undefined);\n return com && com.length > 0;\n }\n function isOptionsInterface(name) {\n return name.indexOf(\"Options\") > -1 || name.indexOf(\"Event\") > -1;\n }\n function addClassIntoJSONDefinition(className, isRoot) {\n if (isRoot === void 0) { isRoot = false; }\n if (className == \"IElement\") {\n className = \"SurveyElement\";\n }\n if (!!generateJSONDefinitionClasses[className])\n return;\n generateJSONDefinitionClasses[className] = true;\n var cur = classesHash[className];\n if (!isRoot && (!cur || !hasSerializedProperties(className))) {\n addChildrenClasses(className);\n return;\n }\n if (!cur || (!isRoot && hasClassInJSONDefinition(className)))\n return;\n var root = outputDefinition;\n if (!isRoot) {\n if (!outputDefinition[\"definitions\"]) {\n outputDefinition[\"definitions\"] = {};\n }\n outputDefinition[\"definitions\"][cur.jsonName] = {};\n root = outputDefinition[\"definitions\"][cur.jsonName];\n root[\"$id\"] = \"#\" + cur.jsonName;\n }\n root[\"type\"] = \"object\";\n addPropertiesIntoJSONDefinion(cur, root);\n if (!isRoot) {\n addParentClass(cur, root);\n addChildrenClasses(cur.name);\n }\n }\n function addParentClass(cur, root) {\n if (!cur.baseType)\n return;\n addClassIntoJSONDefinition(cur.baseType);\n var parentClass = classesHash[cur.baseType];\n if (!!parentClass && hasClassInJSONDefinition(parentClass.jsonName)) {\n var properties = root[\"properties\"];\n delete root[\"properties\"];\n root[\"allOff\"] = [\n { $ref: \"#\" + parentClass.jsonName },\n { properties: properties },\n ];\n }\n }\n function addChildrenClasses(className) {\n for (var i = 0; i < outputClasses.length; i++) {\n if (outputClasses[i].baseType == className) {\n addClassIntoJSONDefinition(outputClasses[i].name);\n }\n }\n }\n function hasClassInJSONDefinition(className) {\n return (!!outputDefinition[\"definitions\"] &&\n !!outputDefinition[\"definitions\"][className]);\n }\n function addPropertiesIntoJSONDefinion(cur, jsonDef) {\n for (var i = 0; i < outputPMEs.length; i++) {\n var property = outputPMEs[i];\n if (property.className !== cur.name || !property.isSerialized)\n continue;\n addPropertyIntoJSONDefinion(property, jsonDef);\n }\n }\n function hasSerializedProperties(className) {\n for (var i = 0; i < outputPMEs.length; i++) {\n var property = outputPMEs[i];\n if (property.className == className && property.isSerialized)\n return true;\n }\n return false;\n }\n function addPropertyIntoJSONDefinion(property, jsonDef) {\n if (!jsonDef.properties) {\n jsonDef.properties = {};\n }\n var properties = jsonDef.properties;\n var typeName = property.type;\n var isArray = !!typeName && typeName.indexOf(\"[]\") > -1;\n if (!!property.jsonClassName || isArray) {\n addClassIntoJSONDefinition(typeName.replace(\"[]\", \"\"));\n }\n var typeInfo = getTypeValue(property);\n var propInfo = { type: typeInfo };\n if (isArray) {\n propInfo = { type: \"array\", items: typeInfo };\n }\n if (!!property.serializedChoices &&\n Array.isArray(property.serializedChoices) &&\n property.serializedChoices.length > 1) {\n propInfo[\"enum\"] = property.serializedChoices;\n }\n properties[property.name] = propInfo;\n }\n function getTypeValue(property) {\n var propType = property.type;\n if (propType.indexOf(\"|\") > 0)\n return [\"boolean\", \"string\"];\n if (propType == \"any\")\n return [\"string\", \"numeric\", \"boolean\"];\n if (propType == \"string\" || propType == \"numeric\" || propType == \"boolean\")\n return propType;\n var childrenTypes = [];\n addChildrenTypes(propType.replace(\"[]\", \"\"), childrenTypes);\n if (childrenTypes.length == 1)\n return getReferenceType(childrenTypes[0]);\n if (childrenTypes.length > 1) {\n var res = [];\n for (var i = 0; i < childrenTypes.length; i++) {\n res.push(getReferenceType(childrenTypes[i]));\n }\n return res;\n }\n return getReferenceType(propType.replace(\"[]\", \"\"));\n }\n function addChildrenTypes(type, childrenTypes) {\n if (type == \"IElement\")\n type = \"SurveyElement\";\n for (var i = 0; i < outputClasses.length; i++) {\n if (outputClasses[i].baseType == type) {\n var count = childrenTypes.length;\n addChildrenTypes(outputClasses[i].name, childrenTypes);\n if (count == childrenTypes.length) {\n childrenTypes.push(outputClasses[i].name);\n }\n }\n }\n }\n function updateEventsDocumentation() {\n for (var i_1 = 0; i_1 < outputPMEs.length; i_1++) {\n var ser = outputPMEs[i_1];\n if (!ser.eventSenderName || !ser.eventOptionsName)\n continue;\n if (!ser.documentation)\n ser.documentation = \"\";\n if (ser.documentation.indexOf(\"- `sender`:\") > -1)\n continue;\n var lines = [];\n lines.push(\"\");\n lines.push(\"Parameters:\");\n lines.push(\"\");\n updateEventDocumentationSender(ser, lines);\n updateEventDocumentationOptions(ser, lines);\n var replacedTextIndex = ser.documentation.indexOf(EventDescriptReplacedText);\n if (replacedTextIndex > -1) {\n ser.documentation = ser.documentation.replace(EventDescriptReplacedText, lines.join(\"\\n\"));\n }\n else {\n lines.unshift(\"\");\n ser.documentation += lines.join(\"\\n\");\n }\n }\n }\n function updateEventDocumentationSender(ser, lines) {\n if (!ser.eventSenderName)\n return;\n var desc = \"\";\n if (ser.eventSenderName === \"SurveyModel\") {\n desc = SurveyModelSenderDescription;\n }\n lines.push(\" - `sender`: `\" + ser.eventSenderName + \"`\" + (!!desc ? \" \" : \"\"));\n if (!!desc) {\n lines.push(desc);\n }\n }\n function updateEventDocumentationOptions(ser, lines) {\n if (!ser.eventOptionsName)\n return;\n var members = {};\n fillEventMembers(ser.eventOptionsName, members);\n for (var key_1 in members) {\n var m = members[key_1];\n var doc = m.documentation;\n if (isHiddenEntryByDoc(doc))\n continue;\n lines.push(\"- `options.\" + m.name + \"`: `\" + m.type + \"`\" + (!!doc ? \" \" : \"\"));\n if (!!doc) {\n lines.push(doc);\n }\n }\n ;\n }\n function isHiddenEntryByDoc(doc) {\n if (!doc)\n return true;\n doc = doc.toLocaleLowerCase();\n return doc.startsWith(\"obsolete\") || doc.startsWith(\"for internal use\");\n }\n function fillEventMembers(interfaceName, members) {\n var classEntry = classesHash[interfaceName];\n if (!classEntry)\n return;\n if (Array.isArray(classEntry.implements)) {\n for (var i_2 = 0; i_2 < classEntry.implements.length; i_2++) {\n fillEventMembers(classEntry.implements[i_2], members);\n }\n }\n if (!Array.isArray(classEntry.members))\n return;\n for (var i_3 = 0; i_3 < classEntry.members.length; i_3++) {\n var m = classEntry.members[i_3];\n members[m.name] = m;\n }\n }\n function getReferenceType(type) {\n var curClass = classesHash[type];\n if (!curClass)\n return type;\n return { $href: \"#\" + curClass.jsonName };\n }\n function dtsImportFiles(imports) {\n if (!imports)\n return;\n for (var key in imports) {\n var arr = imports[key];\n if (!Array.isArray(arr))\n continue;\n for (var i = 0; i < arr.length; i++) {\n importDtsFile(key, arr[i]);\n }\n }\n }\n function importDtsFile(moduleName, fileName) {\n var text = fs.readFileSync(getAbsoluteFileName(fileName), 'utf8');\n var regExStrs = [{ regex: /(?<=export interface)(.*)(?={)/gm, type: DocEntryType.interfaceType },\n { regex: /(?<=export declare var)(.*)(?=:)/gm, type: DocEntryType.variableType },\n { regex: /(?<=export declare function)(.*)(?=\\()/gm, type: DocEntryType.functionType },\n { regex: /(?<=export declare class)(.*)(?={)/gm, type: DocEntryType.classType },\n { regex: /(?<=export declare class)(.*)(?=extends)/gm, type: DocEntryType.classType },\n { regex: /(?<=export declare class)(.*)(?=implements)/gm, type: DocEntryType.classType },\n { regex: /(?<=export declare class)(.*)(?=<)/gm, type: DocEntryType.classType }];\n var removedWords = [\" extends \", \"<\"];\n var _loop_1 = function () {\n var item = regExStrs[i];\n var mathArray = text.match(item.regex);\n if (!Array.isArray(mathArray))\n return \"continue\";\n mathArray.forEach(function (name) {\n if (!!name && !!name.trim()) {\n for (var rI = 0; rI < removedWords.length; rI++) {\n var index = name.indexOf(removedWords[rI]);\n if (index > -1) {\n name = name.substring(0, index);\n }\n }\n dtsImports[name.trim()] = { name: name.trim(), moduleName: moduleName, entryType: item.type };\n }\n });\n };\n for (var i = 0; i < regExStrs.length; i++) {\n _loop_1();\n }\n }\n function prepareDtsInfo() {\n for (var key in classesHash) {\n proccessDtsClass(classesHash[key]);\n }\n }\n function proccessDtsClass(curClass) {\n dtsDeclarations[curClass.name] = curClass;\n }\n function dtsGetText() {\n var lines = [];\n dtsRenderDeclarations(lines);\n return lines.join(\"\\n\");\n }\n function dtsRenderDeclarations(lines) {\n var classes = [];\n var interfaces = [];\n var functions = [];\n var variables = [];\n var enums = [];\n for (var key in dtsDeclarations) {\n if (dtsExcludeImports && !!dtsImports[key])\n continue;\n var cur = dtsDeclarations[key];\n if (cur.entryType === DocEntryType.classType) {\n classes.push(cur);\n }\n if (cur.entryType === DocEntryType.interfaceType) {\n interfaces.push(cur);\n }\n if (cur.entryType === DocEntryType.variableType) {\n variables.push(cur);\n }\n if (cur.entryType === DocEntryType.functionType) {\n functions.push(cur);\n }\n if (cur.entryType === DocEntryType.enumType) {\n enums.push(cur);\n }\n }\n for (var i = 0; i < dtsExportClassesFromLibraries.length; i++) {\n dtsRenderExportClassFromLibraries(lines, dtsExportClassesFromLibraries[i]);\n }\n if (dtsExportClassesFromLibraries.length > 0) {\n lines.push(\"\");\n }\n dtsSortClasses(classes);\n for (var i = 0; i < enums.length; i++) {\n dtsRenderDeclarationEnum(lines, enums[i]);\n }\n for (var i = 0; i < interfaces.length; i++) {\n dtsRenderDeclarationInterface(lines, interfaces[i]);\n }\n for (var i = 0; i < classes.length; i++) {\n dtsRenderDeclarationClass(lines, classes[i]);\n }\n for (var i = 0; i < functions.length; i++) {\n dtsRenderDeclarationFunction(lines, functions[i]);\n }\n for (var i = 0; i < variables.length; i++) {\n dtsRenderDeclarationVariable(lines, variables[i], 0);\n }\n dtsRenderImports(lines);\n }\n function dtsSortClasses(classes) {\n classes.sort(function (a, b) {\n if (a.allTypes.indexOf(b.name) > -1)\n return 1;\n if (b.allTypes.indexOf(a.name) > -1)\n return -1;\n if (a.allTypes.length !== b.allTypes.length) {\n return a.allTypes.length > b.allTypes.length ? 1 : -1;\n }\n return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;\n });\n }\n function dtsRenderImports(lines) {\n var modules = {};\n for (key in dtsImportDeclarations) {\n var entry = dtsImportDeclarations[key];\n var arr = modules[entry.moduleName];\n if (!arr) {\n arr = [];\n modules[entry.moduleName] = arr;\n }\n arr.push(key);\n }\n var importLines = [];\n for (key in modules) {\n var arr = modules[key];\n while (arr.length > 0) {\n var renderedArr = arr.splice(0, 5);\n var str = \"import { \" + renderedArr.join(\", \") + \" } from \\\"\" + key + \"\\\";\";\n importLines.push(str);\n }\n }\n for (var key in dtsFrameworksImportDeclarations) {\n importLines.push(dtsFrameworksImportDeclarations[key] + \" from \\\"\" + key + \"\\\";\");\n }\n if (importLines.length > 0) {\n lines.unshift(\"\");\n }\n for (var i_4 = importLines.length - 1; i_4 >= 0; i_4--) {\n lines.unshift(importLines[i_4]);\n }\n }\n function dtsRenderExportClassFromLibraries(lines, entry) {\n if (!!dtsExportedClasses[entry.name])\n return;\n dtsExportedClasses[entry.name] = true;\n var str = \"export { \";\n if (!!entry.className) {\n str += entry.className + \" as \";\n }\n str += entry.name + \" }\";\n if (!!entry.fileName) {\n str += \" from \\\"\" + entry.fileName + \"\\\"\";\n }\n str += \";\";\n lines.push(str);\n }\n function dtsRenderDeclarationClass(lines, entry) {\n if (entry.name === \"default\")\n return;\n dtsRenderDoc(lines, entry);\n var line = \"export declare \";\n line += \"class \" + entry.name + dtsGetTypeGeneric(entry.name) + dtsRenderClassExtend(entry) + \" {\";\n lines.push(line);\n dtsRenderDeclarationConstructor(lines, entry);\n dtsRenderDeclarationBody(lines, entry);\n lines.push(\"}\");\n }\n function dtsRenderDeclarationInterface(lines, entry) {\n dtsRenderDoc(lines, entry);\n var impl = dtsRenderImplementedInterfaces(entry, false);\n var line = \"export interface \" + dtsGetType(entry.name) + dtsGetTypeGeneric(entry.name) + impl + \" {\";\n lines.push(line);\n dtsRenderDeclarationBody(lines, entry);\n lines.push(\"}\");\n }\n function dtsRenderDeclarationVariable(lines, entry, level) {\n dtsRenderDoc(lines, entry, level);\n var line = (level === 0 ? \"export declare var \" : dtsAddSpaces(level)) + entry.name + \": \";\n var hasMembers = Array.isArray(entry.members);\n var comma = level === 0 ? \";\" : \",\";\n line += hasMembers ? \"{\" : (dtsGetType(entry.type) + comma);\n lines.push(line);\n if (hasMembers) {\n for (var i = 0; i < entry.members.length; i++) {\n if (dtsIsPrevMemberTheSame(entry.members, i))\n continue;\n dtsRenderDeclarationVariable(lines, entry.members[i], level + 1);\n }\n lines.push(dtsAddSpaces(level) + \"}\" + comma);\n }\n }\n function dtsRenderDeclarationEnum(lines, entry) {\n if (!Array.isArray(entry.members) || entry.members.length === 0)\n return;\n lines.push(\"export enum \" + entry.name + \" {\");\n for (var i = 0; i < entry.members.length; i++) {\n var m = entry.members[i];\n var comma = i < entry.members.length - 1 ? \",\" : \"\";\n lines.push(dtsAddSpaces() + m.name + (!!m.returnType ? \" = \" + m.returnType : \"\") + comma);\n }\n lines.push(\"}\");\n }\n function dtsRenderDeclarationFunction(lines, entry) {\n lines.push(\"export declare function \" + dtsGetFunctionDeclaration(entry));\n }\n function dtsRenderClassExtend(cur) {\n if (!cur.baseType)\n return \"\";\n if (!dtsGetHasClassType(cur.baseType))\n return \"\";\n var entry = dtsDeclarations[cur.baseType];\n if (!entry) {\n entry = dtsImports[cur.baseType];\n }\n var isInteface = !!entry && entry.entryType === DocEntryType.interfaceType;\n var impl = dtsRenderImplementedInterfaces(cur, !isInteface);\n if (isInteface)\n return impl;\n var generic = dtsGetTypeGeneric(cur.baseType, cur.name);\n return \" extends \" + cur.baseType + generic + impl;\n }\n function dtsRenderImplementedInterfaces(entry, isBaseClass) {\n if (!Array.isArray(entry.implements))\n return \"\";\n var impls = entry.implements;\n if (impls.length === 0)\n return \"\";\n var res = [];\n for (var i = 0; i < impls.length; i++) {\n if (isBaseClass && impls[i] === entry.baseType)\n continue;\n var generic = dtsGetTypeGeneric(impls[i], entry.name);\n dtsAddImportDeclaration(impls[i]);\n res.push(impls[i] + generic);\n }\n if (res.length === 0)\n return \"\";\n var ext = entry.entryType === DocEntryType.interfaceType ? \" extends \" : \" implements \";\n return ext + res.join(\", \");\n }\n function dtsRenderDeclarationBody(lines, entry) {\n if (!Array.isArray(entry.members))\n return;\n var members = [].concat(entry.members);\n for (var i = 0; i < members.length; i++) {\n if (dtsIsPrevMemberTheSame(members, i))\n continue;\n var member = members[i];\n dtsRenderDeclarationMember(lines, member);\n if (member.isLocalizable) {\n var name_7 = \"loc\" + member.name[0].toUpperCase() + member.name.substring(1);\n if (dtsHasMemberInEntry(entry, name_7))\n continue;\n var locMember = { name: name_7, type: \"LocalizableString\", hasSet: false, pmeType: \"property\" };\n dtsRenderDeclarationMember(lines, locMember);\n }\n }\n }\n function dtsHasMemberInEntry(entry, name) {\n if (!Array.isArray(entry.members))\n return;\n for (var i = 0; i < entry.members.length; i++) {\n if (entry.members[i].name === name)\n return true;\n }\n return false;\n }\n function dtsRenderDeclarationConstructor(lines, entry) {\n if (!Array.isArray(entry.constructors))\n return;\n for (var i = 0; i < entry.constructors.length; i++) {\n var parameters = dtsGetParameters(entry.constructors[i]);\n lines.push(dtsAddSpaces() + \"constructor(\" + parameters + \");\");\n }\n }\n function dtsRenderDeclarationMember(lines, member) {\n var prefix = dtsAddSpaces() + (member.isProtected ? \"protected \" : \"\") + (member.isStatic ? \"static \" : \"\");\n dtsRenderDoc(lines, member, 1);\n var importType = \"\";\n if (member.pmeType === \"function\" || member.pmeType === \"method\") {\n importType = member.returnType;\n lines.push(prefix + dtsGetFunctionDeclaration(member));\n }\n if (member.pmeType === \"property\") {\n var propType = dtsGetType(member.type);\n importType = member.type;\n if (member.isField) {\n lines.push(prefix + member.name + (member.isOptional ? \"?\" : \"\") + \": \" + propType + \";\");\n }\n else {\n lines.push(prefix + \"get \" + member.name + \"(): \" + propType + \";\");\n if (member.hasSet) {\n lines.push(prefix + \"set \" + member.name + \"(val: \" + propType + \");\");\n }\n }\n }\n if (member.pmeType === \"event\") {\n importType = member.type;\n lines.push(prefix + member.name + \": \" + member.type + \";\");\n }\n dtsAddImportDeclaration(removeGenerics(importType));\n }\n function dtsGetFunctionDeclaration(entry) {\n var parStr = dtsGetFunctionParametersDeclaration(entry);\n return entry.name + dtsGetGenericTypes(entry.typeGenerics) + parStr + \";\";\n }\n function dtsGetFunctionParametersDeclaration(entry, isParameter) {\n if (isParameter === void 0) { isParameter = false; }\n var returnType = removeGenerics(entry.returnType);\n returnType = dtsGetType(returnType);\n if (returnType !== \"any\") {\n returnType += dtsGetGenericTypes(entry.returnTypeGenerics);\n }\n var parameters = dtsGetParameters(entry);\n return \"(\" + parameters + \")\" + (isParameter ? \" => \" : \": \") + returnType;\n }\n function removeGenerics(typeName) {\n if (!typeName)\n return typeName;\n if (typeName[typeName.length - 1] !== \">\")\n return typeName;\n var index = typeName.indexOf(\"<\");\n if (index < 0)\n return typeName;\n return typeName.substring(0, index);\n }\n function dtsGetGenericTypes(generic) {\n if (!Array.isArray(generic) || generic.length === 0)\n return \"\";\n return \"<\" + generic.join(\", \") + \">\";\n }\n function dtsRenderDoc(lines, entry, level) {\n if (level === void 0) { level = 0; }\n if (!entry.documentation)\n return;\n var docLines = entry.documentation.split(\"\\n\");\n lines.push(dtsAddSpaces(level) + \"/*\");\n for (var i = 0; i < docLines.length; i++) {\n lines.push(dtsAddSpaces(level) + \"* \" + docLines[i]);\n }\n lines.push(dtsAddSpaces(level) + \"*/\");\n }\n function dtsGetType(type) {\n if (!type)\n return \"void\";\n if (type === \"T\")\n return type;\n if (type.indexOf(\"|\") > -1) {\n return type.indexOf(\"(\") > -1 ? \"any\" : type;\n }\n var str = type.replace(\"[\", \"\").replace(\"]\", \"\");\n if (str === \"number\" || str === \"boolean\" || str === \"string\" || str === \"any\" || str === \"void\")\n return type;\n if (type[0] === \"(\" && type.indexOf(callbackFuncResultStr) > -1)\n return dtsGetTypeAsFunc(type);\n return dtsPlatformType(str, type);\n }\n function dtsPlatformType(str, type) {\n if (!dtsGetHasClassType(str))\n return \"any\";\n if (isReactElement(type))\n return \"JSX.Element\";\n return type;\n }\n function dtsGetTypeAsFunc(type) {\n var index = type.indexOf(callbackFuncResultStr);\n var entry = {};\n entry.returnType = type.substring(index + callbackFuncResultStr.length);\n var paramsStr = type.substring(1, index).split(\",\");\n entry.parameters = [];\n for (var i = 0; i < paramsStr.length; i++) {\n var par = paramsStr[i];\n var parIndex = par.indexOf(\":\");\n if (parIndex < 0)\n return \"any\";\n entry.parameters.push({ name: par.substring(0, parIndex).trim(), type: par.substring(parIndex + 1).trim() });\n }\n return dtsGetFunctionParametersDeclaration(entry, true);\n }\n function dtsGetTypeGeneric(type, typeFor) {\n if (!type)\n return \"\";\n if (!typeFor)\n return dtsGetTypeGenericByParameters(dtsTypesParameters[type]);\n var args = dtsTypesArgumentParameters[type];\n if (!args)\n return \"\";\n return dtsGetTypeGenericByParameters(args[typeFor]);\n }\n function dtsGetTypeGenericByParameters(params) {\n if (!Array.isArray(params))\n return \"\";\n for (var i = 0; i < params.length; i++) {\n dtsAddImportDeclaration(params[i]);\n }\n return \"<\" + params.join(\", \") + \">\";\n }\n function isReactElement(type) {\n return isExportingReact && type === \"Element\";\n }\n function dtsGetHasClassType(type) {\n if (dtsAddImportDeclaration(type))\n return true;\n if (type === \"Array\")\n return true;\n if (isReactElement(type))\n return true;\n return !!dtsDeclarations[type];\n }\n function dtsAddImportDeclaration(type) {\n if (!type)\n return false;\n if (type.indexOf(\"React.\") === 0) {\n dtsFrameworksImportDeclarations[\"react\"] = \"import * as React\";\n isExportingReact = true;\n return true;\n }\n if (type === \"Vue\") {\n dtsFrameworksImportDeclarations[\"vue\"] = \"import Vue\";\n return true;\n }\n if (!dtsExcludeImports && !!dtsDeclarations[type])\n return false;\n var entry = dtsImports[type];\n if (!entry)\n return false;\n dtsImportDeclarations[type] = entry;\n return true;\n }\n function dtsIsPrevMemberTheSame(members, index) {\n return index > 0 && members[index].name === members[index - 1].name;\n }\n function dtsGetParameters(member) {\n if (!Array.isArray(member.parameters))\n return \"\";\n var strs = [];\n var params = member.parameters;\n for (var i = 0; i < params.length; i++) {\n var p = params[i];\n var typeStr = dtsGetType(p.type);\n //We have Event in library core and there is Event in DOM.\n if (typeStr === \"Event\")\n typeStr = \"any\";\n strs.push(p.name + (p.isOptional ? \"?\" : \"\") + \": \" + typeStr);\n }\n return strs.join(\", \");\n }\n function dtsAddSpaces(level) {\n if (level === void 0) { level = 1; }\n var str = \"\";\n for (var i = 0; i < level; i++)\n str += \" \";\n return str;\n }\n}", "async function main() {\n const modelManager = await ModelLoader.loadModelManagerFromModelFiles([metaModelCto], {strict: true});\n const visitor = new TypescriptVisitor();\n const fileWriter = new FileWriter(path.resolve(__dirname, '..', 'src', 'generated'));\n const parameters = { fileWriter };\n modelManager.accept(visitor, parameters);\n}", "async writing() {\n // read async from fs\n const reader = async (filepath) => {\n console.log(`read ${filepath}`)\n return fs.promises\n .readFile(this.templatePath(filepath))\n .then((b) => b.toString())\n }\n\n // write sync to memfs\n const writer = (filepath, content) =>\n this.fs.write(this.destinationPath(filepath), content)\n\n // filter git ignored files\n const gitDir = await scaffold.GitDir.New(this.sourceRoot())\n await scaffold.ScaffoldProcessGeneric(\n gitDir.walk(),\n reader,\n writer,\n this.answers\n )\n\n const content = this.fs.readJSON(this.destinationPath('package.json'))\n content.name = this.answers.name\n content.description = this.answers.description\n content.author = this.answers.author\n content.repository.url = this.answers.repository_url\n this.fs.writeJSON(this.destinationPath('package.json'), content, null, 2)\n\n }", "function createIndexFile() {\n let indexTS = '';\n for(let filepath of protoImportList) {\n const dir = path.parse(filepath).dir;\n const filename = path.parse(filepath).name + '_pb';\n const indexpath = path.join(dir, filename);\n indexTS += \"export * from './functions/\" + indexpath + \"';\\n\";\n }\n fs.writeFileSync(path.join(exportProtoPath, 'index.ts'), indexTS);\n\n onLoad();\n }", "async write() {\r\n\t\t// Don't bother writing an empty material library.\r\n\t\tif (this.isEmpty)\r\n\t\t\treturn;\r\n\r\n\t\tawait generics.createDirectory(path.dirname(this.out));\r\n\t\tconst writer = new FileWriter(this.out);\r\n\r\n\t\tfor (const material of this.materials) {\r\n\t\t\twriter.writeLine('newmtl ' + material.name);\r\n\t\t\twriter.writeLine('illum 1');\r\n\t\t\twriter.writeLine('map_Kd ' + material.file);\r\n\t\t}\r\n\r\n\t\tawait writer.close();\r\n\t}", "async generated () {\n // @todo check context.markdown.$data.typeLinks for existence\n return fs.copy(metadataDir, path.resolve(context.outDir, 'metadata'))\n }", "function writePackage(answers, configLocation) {\n // script\n var pkgPath = path_1.resolve(process.cwd(), 'package.json');\n var pkgContent = fs_1.readFileSync(pkgPath, {\n encoding: 'utf-8'\n });\n var pkg = JSON.parse(pkgContent);\n var indent = detectIndent(pkgContent).indent;\n if (!pkg.scripts) {\n pkg.scripts = {};\n }\n pkg.scripts[answers.script] = \"gql-gen --config \" + configLocation;\n // plugin\n if (!pkg.devDependencies) {\n pkg.devDependencies = {};\n }\n // read codegen's version\n var version = JSON.parse(fs_1.readFileSync(path_1.resolve(__dirname, '../package.json'), {\n encoding: 'utf-8'\n })).version;\n answers.plugins.forEach(function (plugin) {\n pkg.devDependencies[plugin.package] = version;\n });\n fs_1.writeFileSync(pkgPath, JSON.stringify(pkg, null, indent));\n}", "function toClosureJS(options, fileNames, isUntyped) {\n // Parse and load the program without tsickle processing.\n // This is so:\n // - error messages point at the original source text\n // - tsickle can use the result of typechecking for annotation\n var program = ts.createProgram(fileNames, options);\n var errors = ts.getPreEmitDiagnostics(program);\n if (errors.length > 0) {\n return { errors: errors };\n }\n var tsickleOptions = {\n untyped: isUntyped,\n };\n // Process each input file with tsickle and save the output.\n var tsickleOutput = {};\n var tsickleExterns = '';\n for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {\n var fileName = fileNames_1[_i];\n var _a = tsickle.annotate(program, program.getSourceFile(fileName), tsickleOptions), output = _a.output, externs = _a.externs, diagnostics_1 = _a.diagnostics;\n if (diagnostics_1.length > 0) {\n return { errors: diagnostics_1 };\n }\n tsickleOutput[ts.sys.resolvePath(fileName)] = output;\n if (externs) {\n tsickleExterns += externs;\n }\n }\n // Reparse and reload the program, inserting the tsickle output in\n // place of the original source.\n var host = createSourceReplacingCompilerHost(tsickleOutput, ts.createCompilerHost(options));\n program = ts.createProgram(fileNames, options, host);\n errors = ts.getPreEmitDiagnostics(program);\n if (errors.length > 0) {\n return { errors: errors };\n }\n // Emit, creating a map of fileName => generated JS source.\n var jsFiles = {};\n function writeFile(fileName, data) { jsFiles[fileName] = data; }\n var diagnostics = program.emit(undefined, writeFile).diagnostics;\n if (diagnostics.length > 0) {\n return { errors: diagnostics };\n }\n for (var _b = 0, _c = Object.keys(jsFiles); _b < _c.length; _b++) {\n var fileName = _c[_b];\n if (path.extname(fileName) !== '.map') {\n var output = tsickle.convertCommonJsToGoogModule(fileName, jsFiles[fileName], cli_support.pathToModuleName).output;\n jsFiles[fileName] = output;\n }\n }\n return { jsFiles: jsFiles, externs: tsickleExterns };\n}", "function generateJsDriver() {\n const fileNames = fs.readdirSync(consts.TEXT_DIR);\n\n const driverExport = fileNames.reduce((obj, fileName) => {\n const [name, extension] = fileName.split(\".\");\n\n if (extension === \"json\") {\n return {\n ...obj,\n [name]: `require('./${fileName}')`,\n };\n }\n\n return obj;\n }, {});\n\n let dataString = `module.exports = ${JSON.stringify(driverExport, null, 2)}`\n // remove quotes around require statements\n .replace(/\"require\\((.*)\\)\"/g, \"require($1)\");\n\n const filePath = path.resolve(consts.TEXT_DIR, \"index.js\");\n fs.writeFileSync(filePath, dataString, { encoding: \"utf8\" });\n\n return `Generated .js SDK driver at ${output.info(filePath)}..`;\n}", "async function definition(transformFn = (content) => content) {\n\tlog.bold('> definition.js')\n\n\tconst CWD = process.cwd()\n\tconst PKG = await fs.readJson(path.join(CWD, 'package.json'))\n\tconst DEF_FILE = path.join(CWD, 'typings', 'app.d.ts')\n\tconst config = {\n\t\tname: `${PKG.name}/dist`,\n\t\tindent: ' ',\n\t\tproject: CWD,\n\t\tout: DEF_FILE,\n\t\tsendMessage: console.log,\n\t\texterns: ['./global.d.ts'],\n\t\texclude: ['test/**/*.*'],\n\t\tverbose: false,\n\t}\n\n\tawait fs.remove(DEF_FILE)\n\tawait dts(config)\n\n\tconst content = await fs.readFile(DEF_FILE, 'utf8')\n\n\tconst newContent = transformFn(content.replace(/([\\t\\f\\v]*)private(.*)[\\r\\n]*/g, '')\n\t\t.replace(/\\/src\\//g, '/dist/')\n\t\t.replace(/\\/dist\\/app\\/index'/g, \"'\"))\n\n\tawait fs.writeFile(DEF_FILE, newContent)\n\tlog.success('Definition generated')\n}", "function outputOntology(){\n var arrayRep = graph.toArray().map(function(stmt){\n return stmt.toTurtle(profile);\n });\n fs.appendFileSync(outputPath, arrayRep.join('\\n'));\n }", "_getStandardTypingsFilePath(file) {\n let filePath = file.getPathInPackage();\n let dirPath = ts.getDirectoryPath(\n ts.normalizePath(filePath)).replace(/^typings\\/?/, '');\n let pkgName = file.getPackageName();\n if (pkgName.indexOf(':') != -1) {\n pkgName = pkgName.split(':')[1];\n }\n let pkgTest = new RegExp(`^\\/?${pkgName}(\\/.+|$)`);\n // Check if the path starts with the package name.\n if (pkgTest.test(dirPath) === false) {\n let pkgDirPath = ts.combinePaths(\n ts.combinePaths('typings', pkgName), dirPath);\n let fileName = ts.getBaseFileName(filePath);\n filePath = ts.combinePaths(pkgDirPath, fileName);\n }\n\n return filePath;\n }", "function createOutput(json: SwaggerInput) {\n\n switch (options.outputType) {\n case OutputTypes.Single: {\n // tslint:disable-next-line\n return console.log(createDefs(json, options));\n }\n case OutputTypes.Multi: {\n const res = createSplitDefs(json, options);\n const defOutput = join(options.outDir, res.definitions[0].displayName);\n\n res.modules.concat(res.definitions).forEach((item) => {\n outputFileSync(join(options.outDir, item.displayName), item.content);\n });\n // tslint:disable-next-line\n console.log(`${res.modules.length} module(s) written to '${options.outDir}'`);\n // tslint:disable-next-line\n console.log(`1 definition file written to '${defOutput}'`);\n\n break;\n }\n default: {\n // tslint:disable-next-line\n return console.error(\"Output type not supported\");\n }\n }\n}", "function generateFile(data) {\n FileReader.writeFile(\"compiled.js\", data, (err) => {\n if (err) {\n console.log(\"File write err\");\n }\n });\n}", "instantiateAll () {\n const files = this.findGeneratorFiles('./templates', /\\.js$/);\n\n files.forEach((filename) => {\n const Constructor = require(filename);\n const object = new Constructor();\n this.viewGenerators[object.constructor.name] = object;\n if (!this.viewGeneratorsContentType[object.getName()]) {\n this.viewGeneratorsContentType[object.getName()] = [];\n }\n this.viewGeneratorsContentType[object.getName()] = this.viewGeneratorsContentType[object.getName()].concat(object.getContentTypes());\n });\n }", "function writeTxtFiles() { //调用前面的写方法\n\n\t// could've written these as one function,\n\t// left em separate for easy customization,\n\t// e.g., could've written writeCsv()\n\n\n\n\n\n\twriteHtml();\n\twriteCss();\n\t// writeJson();\n\twriteManifest();\n\n\n}", "function generate() {\n fs.writeFileSync(outputPath, render(teamMembers), \"utf-8\");\n process.exit(0);\n}", "saveTemplates(callback){\n var fs = require('fs')\n var file = __dirname + '/../assets/data/templates.json'\n fs.writeFile(file, JSON.stringify(this.templates), function(err) {\n if(err) {\n return callback(err)\n }\n else{\n return callback(undefined, true)\n }\n })\n }", "build() {\n const inputPath = first(this.inputPaths);\n this.exporters.forEach(([fileName, exporter]) => {\n const srcPath = path.join(inputPath, fileName);\n if (fs.existsSync(srcPath)) {\n const sourceCode = exporter.processSourceCode(fs.readFileSync(srcPath, 'utf8'));\n const destPath = path.join(this.outputPath, fileName);\n\n // Make sure the directory exists before writing it.\n mkdirpSync(path.dirname(destPath));\n fs.writeFileSync(destPath, sourceCode);\n }\n });\n }", "function main(): void {\n const cli = new commander.Command();\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n cli.version(require(\"../package.json\").version)\n .description(\n \"CLI to convert CDS models to Typescript interfaces and enumerations\"\n )\n .option(\"-c, --cds <file.cds>\", \"CDS file to convert\")\n .option(\n \"-o, --output ./<path>/\",\n \"Output location in which the generated *.ts files are written to. Make sure the path ends with '/'.\"\n )\n .option(\"-p, --prefix <I>\", \"Interface prefix\", \"\")\n .option(\n \"-j, --json\",\n \"Prints the compiled JSON representation of the CDS sources\"\n )\n .option(\n \"-d, --debug\",\n \"Prints JavaScript error message, should be used for issue reporting => https://github.com/mrbandler/cds2types/issues\"\n )\n .option(\n \"-f, --format\",\n \"Flag, whether to format the outputted source code or not (will try to format with prettier rules in the project)\"\n )\n .option(\n \"-s, --sort\",\n \"Flag, whether to sort outputted source code or not\"\n )\n .parse(process.argv);\n\n if (!process.argv.slice(2).length) {\n cli.outputHelp();\n } else {\n const options = cli.opts() as IOptions;\n new Program().run(options).catch((error: Error) => {\n const debugHint =\n \"Please use the debug flag (-d, --debug) for a detailed error message.\";\n console.log(\n `Unable to write types. ${options.debug ? \"\" : debugHint}`\n );\n\n if (options.debug) console.error(\"Error:\", error.message);\n process.exit(-1);\n });\n }\n}", "function initEntryFile(){\n\n\tvar entries = [];\n\tfor(var i=0;i<2;i++){\n\t\tentries.push(gener.randomEntry());\n\t}\n\tvar data = { \"entries\": entries, \"tags\": [] };\n\tfs.writeFile('./SampleEntries.js', JSON.stringify(data, null, 2), function(err){ if(err){ console.log(\"Harness initEntryFile encountered err while writing.\");} });\n}", "function packageDTS() {\n return gulp.src('./typings/blockly.d.ts')\n .pipe(gulp.dest(`${packageDistribution}`));\n}" ]
[ "0.7189702", "0.6461203", "0.6074944", "0.5802386", "0.57882553", "0.5659313", "0.55635446", "0.5557573", "0.54775023", "0.5312856", "0.52679414", "0.52399546", "0.5210028", "0.51979256", "0.51685524", "0.51669836", "0.5165133", "0.5160877", "0.5146327", "0.51181906", "0.5097286", "0.5080064", "0.5075169", "0.50613487", "0.5027183", "0.49705744", "0.49672416", "0.4959075", "0.49346077", "0.49170345" ]
0.729225
0
Ensures a unique name for each item in the package typings file.
_makeUniqueNames() { const usedNames = new Set(); // First collect the explicit package exports for (const dtsEntry of this._dtsEntries) { if (dtsEntry.exported) { if (usedNames.has(dtsEntry.originalName)) { // This should be impossible throw new Error(`Program bug: a package cannot have two exports with the name ${dtsEntry.originalName}`); } dtsEntry.nameForEmit = dtsEntry.originalName; usedNames.add(dtsEntry.nameForEmit); } } // Next generate unique names for the non-exports that will be emitted for (const dtsEntry of this._dtsEntries) { if (!dtsEntry.exported) { let suffix = 1; dtsEntry.nameForEmit = dtsEntry.originalName; while (usedNames.has(dtsEntry.nameForEmit)) { dtsEntry.nameForEmit = `${dtsEntry.originalName}_${++suffix}`; } usedNames.add(dtsEntry.nameForEmit); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "processTypings(files) {\n // Set hashes of the app's typings.\n files.forEach(file => {\n let isAppTypings = this.isDeclarationFile(file) &&\n !this.isPackageFile(file);\n\n let path = file.getPathInPackage();\n if (isAppTypings && !this._typingsMap.has(path)) {\n this._typingsMap.set(path, file.getSourceHash());\n }\n });\n\n let copiedFiles = [];\n // Process package typings.\n files.forEach(file => {\n // Check if it's a package declaration file.\n let isPkgTypings = this.isDeclarationFile(file) &&\n this.isPackageFile(file);\n\n if (isPkgTypings) {\n let path = file.getPathInPackage();\n // Check if the file is in the \"typings\" folder.\n if (!this._typingsRegEx.test(path)) {\n console.log('Typings path ${path} doesn\\'t start with \"typings\"');\n return;\n }\n\n let filePath = this._getStandardTypingsFilePath(file);\n let oldHash = this._typingsMap.get(filePath);\n let newHash = file.getSourceHash();\n // Copy file if it doesn't exist or has been updated.\n if (oldHash !== newHash) {\n this._copyTypings(filePath, file.getContentsAsString());\n this._typingsMap.set(filePath, newHash);\n copiedFiles.push(filePath);\n }\n }\n });\n\n if (copiedFiles.length) {\n // Report about added/updated typings.\n console.log(chalk.green('***** Typings that have been added/updated *****'));\n copiedFiles.forEach(filePath => {\n console.log(chalk.green(filePath));\n });\n console.log(chalk.green(\n 'Add typings in tsconfig.json or by references in files.'));\n }\n }", "_makeUniqueNames() {\n // The following examples illustrate the nameForEmit heuristics:\n //\n // Example 1:\n // class X { } <--- nameForEmit should be \"A\" to simplify things and reduce possibility of conflicts\n // export { X as A };\n //\n // Example 2:\n // class X { } <--- nameForEmit should be \"X\" because choosing A or B would be nondeterministic\n // export { X as A };\n // export { X as B };\n //\n // Example 3:\n // class X { } <--- nameForEmit should be \"X_1\" because Y has a stronger claim to the name\n // export { X as A };\n // export { X as B };\n // class Y { } <--- nameForEmit should be \"X\"\n // export { Y as X };\n // Set of names that should NOT be used when generating a unique nameForEmit\n const usedNames = new Set();\n // First collect the names of explicit package exports, and perform a sanity check.\n for (const entity of this._entities) {\n for (const exportName of entity.exportNames) {\n if (usedNames.has(exportName)) {\n // This should be impossible\n throw new node_core_library_1.InternalError(`A package cannot have two exports with the name \"${exportName}\"`);\n }\n usedNames.add(exportName);\n }\n }\n // Ensure that each entity has a unique nameForEmit\n for (const entity of this._entities) {\n // What name would we ideally want to emit it as?\n let idealNameForEmit;\n // If this entity is exported exactly once, then we prefer the exported name\n if (entity.singleExportName !== undefined &&\n entity.singleExportName !== ts.InternalSymbolName.Default) {\n idealNameForEmit = entity.singleExportName;\n }\n else {\n // otherwise use the local name\n idealNameForEmit = entity.astEntity.localName;\n }\n // If the idealNameForEmit happens to be the same as one of the exports, then we're safe to use that...\n if (entity.exportNames.has(idealNameForEmit)) {\n // ...except that if it conflicts with a global name, then the global name wins\n if (!this.globalVariableAnalyzer.hasGlobalName(idealNameForEmit)) {\n // ...also avoid \"default\" which can interfere with \"export { default } from 'some-module;'\"\n if (idealNameForEmit !== 'default') {\n entity.nameForEmit = idealNameForEmit;\n continue;\n }\n }\n }\n // Generate a unique name based on idealNameForEmit\n let suffix = 1;\n let nameForEmit = idealNameForEmit;\n // Choose a name that doesn't conflict with usedNames or a global name\n while (usedNames.has(nameForEmit) || this.globalVariableAnalyzer.hasGlobalName(nameForEmit)) {\n nameForEmit = `${idealNameForEmit}_${++suffix}`;\n }\n entity.nameForEmit = nameForEmit;\n usedNames.add(nameForEmit);\n }\n }", "function generateItemNames() {\n for (let item of itemList) {\n itemNames.push(item.name);\n }\n}", "function UniqueTypeNamesRule(context) {\n var knownTypeNames = Object.create(null);\n var schema = context.getSchema();\n return {\n ScalarTypeDefinition: checkTypeName,\n ObjectTypeDefinition: checkTypeName,\n InterfaceTypeDefinition: checkTypeName,\n UnionTypeDefinition: checkTypeName,\n EnumTypeDefinition: checkTypeName,\n InputObjectTypeDefinition: checkTypeName\n };\n\n function checkTypeName(node) {\n var typeName = node.name.value;\n\n if (schema !== null && schema !== void 0 && schema.getType(typeName)) {\n context.reportError(new _GraphQLError.GraphQLError(\"Type \\\"\".concat(typeName, \"\\\" already exists in the schema. It cannot also be defined in this type definition.\"), node.name));\n return;\n }\n\n if (knownTypeNames[typeName]) {\n context.reportError(new _GraphQLError.GraphQLError(\"There can be only one type named \\\"\".concat(typeName, \"\\\".\"), [knownTypeNames[typeName], node.name]));\n } else {\n knownTypeNames[typeName] = node.name;\n }\n\n return false;\n }\n}", "function UniqueTypeNamesRule(context) {\n var knownTypeNames = Object.create(null);\n var schema = context.getSchema();\n return {\n ScalarTypeDefinition: checkTypeName,\n ObjectTypeDefinition: checkTypeName,\n InterfaceTypeDefinition: checkTypeName,\n UnionTypeDefinition: checkTypeName,\n EnumTypeDefinition: checkTypeName,\n InputObjectTypeDefinition: checkTypeName\n };\n\n function checkTypeName(node) {\n var typeName = node.name.value;\n\n if (schema !== null && schema !== void 0 && schema.getType(typeName)) {\n context.reportError(new _GraphQLError.GraphQLError(\"Type \\\"\".concat(typeName, \"\\\" already exists in the schema. It cannot also be defined in this type definition.\"), node.name));\n return;\n }\n\n if (knownTypeNames[typeName]) {\n context.reportError(new _GraphQLError.GraphQLError(\"There can be only one type named \\\"\".concat(typeName, \"\\\".\"), [knownTypeNames[typeName], node.name]));\n } else {\n knownTypeNames[typeName] = node.name;\n }\n\n return false;\n }\n}", "function UniqueTypeNamesRule(context) {\n var knownTypeNames = Object.create(null);\n var schema = context.getSchema();\n return {\n ScalarTypeDefinition: checkTypeName,\n ObjectTypeDefinition: checkTypeName,\n InterfaceTypeDefinition: checkTypeName,\n UnionTypeDefinition: checkTypeName,\n EnumTypeDefinition: checkTypeName,\n InputObjectTypeDefinition: checkTypeName\n };\n\n function checkTypeName(node) {\n var typeName = node.name.value;\n\n if (schema === null || schema === void 0 ? void 0 : schema.getType(typeName)) {\n context.reportError(new _error_GraphQLError_mjs__WEBPACK_IMPORTED_MODULE_0__[\"GraphQLError\"](\"Type \\\"\".concat(typeName, \"\\\" already exists in the schema. It cannot also be defined in this type definition.\"), node.name));\n return;\n }\n\n if (knownTypeNames[typeName]) {\n context.reportError(new _error_GraphQLError_mjs__WEBPACK_IMPORTED_MODULE_0__[\"GraphQLError\"](\"There can be only one type named \\\"\".concat(typeName, \"\\\".\"), [knownTypeNames[typeName], node.name]));\n } else {\n knownTypeNames[typeName] = node.name;\n }\n\n return false;\n }\n}", "function UniqueTypeNamesRule(context) {\n var knownTypeNames = Object.create(null);\n var schema = context.getSchema();\n return {\n ScalarTypeDefinition: checkTypeName,\n ObjectTypeDefinition: checkTypeName,\n InterfaceTypeDefinition: checkTypeName,\n UnionTypeDefinition: checkTypeName,\n EnumTypeDefinition: checkTypeName,\n InputObjectTypeDefinition: checkTypeName\n };\n\n function checkTypeName(node) {\n var typeName = node.name.value;\n\n if (schema === null || schema === void 0 ? void 0 : schema.getType(typeName)) {\n context.reportError(new _error_GraphQLError_mjs__WEBPACK_IMPORTED_MODULE_0__[\"GraphQLError\"](\"Type \\\"\".concat(typeName, \"\\\" already exists in the schema. It cannot also be defined in this type definition.\"), node.name));\n return;\n }\n\n if (knownTypeNames[typeName]) {\n context.reportError(new _error_GraphQLError_mjs__WEBPACK_IMPORTED_MODULE_0__[\"GraphQLError\"](\"There can be only one type named \\\"\".concat(typeName, \"\\\".\"), [knownTypeNames[typeName], node.name]));\n } else {\n knownTypeNames[typeName] = node.name;\n }\n\n return false;\n }\n}", "async function generateAlias() {\n const dirents = await promises.readdir(PACKAGE_PATH);\n\n return Object.fromEntries(\n await Promise.all(\n dirents.map(async d => {\n const packageJSON = JSON.parse(await promises.readFile(path.resolve(PACKAGE_PATH, d, 'package.json')));\n return [packageJSON['name'], path.resolve(PACKAGE_PATH, d)];\n }),\n ),\n );\n}", "function UniqueTypeNames(context) {\n var knownTypeNames = Object.create(null);\n var schema = context.getSchema();\n return {\n ScalarTypeDefinition: checkTypeName,\n ObjectTypeDefinition: checkTypeName,\n InterfaceTypeDefinition: checkTypeName,\n UnionTypeDefinition: checkTypeName,\n EnumTypeDefinition: checkTypeName,\n InputObjectTypeDefinition: checkTypeName\n };\n\n function checkTypeName(node) {\n var typeName = node.name.value;\n\n if (schema && schema.getType(typeName)) {\n context.reportError(new _error_GraphQLError__WEBPACK_IMPORTED_MODULE_0__[\"GraphQLError\"](existedTypeNameMessage(typeName), node.name));\n return;\n }\n\n if (knownTypeNames[typeName]) {\n context.reportError(new _error_GraphQLError__WEBPACK_IMPORTED_MODULE_0__[\"GraphQLError\"](duplicateTypeNameMessage(typeName), [knownTypeNames[typeName], node.name]));\n } else {\n knownTypeNames[typeName] = node.name;\n }\n\n return false;\n }\n}", "function typings() {\n const tmpDir = './typings/tmp';\n const blocklySrcs = [\n \"core/\",\n \"core/components\",\n \"core/components/tree\",\n \"core/components/menu\",\n \"core/keyboard_nav\",\n \"core/renderers/common\",\n \"core/renderers/measurables\",\n \"core/theme\",\n \"core/utils\",\n \"msg/\"\n ];\n // Clean directory if exists.\n if (fs.existsSync(tmpDir)) {\n rimraf.sync(tmpDir);\n }\n fs.mkdirSync(tmpDir);\n\n // Find all files that will be included in the typings file.\n let files = [];\n blocklySrcs.forEach((src) => {\n files = files.concat(fs.readdirSync(src)\n .filter(fn => fn.endsWith('.js'))\n .map(fn => path.join(src, fn)));\n });\n\n // Generate typings file for each file.\n files.forEach((file) => {\n const typescriptFileName = `${path.join(tmpDir, file)}.d.ts`;\n if (file.indexOf('core/msg.js') > -1) {\n return;\n }\n const cmd = `node ./node_modules/typescript-closure-tools/definition-generator/src/main.js ${file} ${typescriptFileName}`;\n console.log(`Generating typings for ${file}`);\n execSync(cmd, { stdio: 'inherit' });\n });\n\n const srcs = [\n 'typings/parts/blockly-header.d.ts',\n 'typings/parts/blockly-interfaces.d.ts',\n `${tmpDir}/core/**`,\n `${tmpDir}/core/components/**`,\n `${tmpDir}/core/components/tree/**`,\n `${tmpDir}/core/components/menu/**`,\n `${tmpDir}/core/keyboard_nav/**`,\n `${tmpDir}/core/renderers/common/**`,\n `${tmpDir}/core/renderers/measurables/**`,\n `${tmpDir}/core/utils/**`,\n `${tmpDir}/core/theme/**`,\n `${tmpDir}/msg/**`\n ];\n return gulp.src(srcs)\n .pipe(gulp.concat('blockly.d.ts'))\n .pipe(gulp.dest('typings'))\n .on('end', function () {\n // Clean up tmp directory.\n if (fs.existsSync(tmpDir)) {\n rimraf.sync(tmpDir);\n }\n });\n}", "get name() {\n return pkg.name;\n }", "function duplicateTypeNameMessage(typeName) {\n return \"There can be only one type named \\\"\".concat(typeName, \"\\\".\");\n}", "ensure(types) {\n return {\n name: types.string.isRequired\n }\n }", "function generatePlaceholder(name, dir) {\n const packagePath = path.join(dir, 'package.json');\n if (fs.existsSync(packagePath)) { return; }\n execSync(`mkdir -p \"${dir}\"`, { stdio: 'inherit' });\n fs.writeFileSync(packagePath, JSON.stringify({\n name,\n version: '1.0.0',\n dependencies: { '@griffins/api-client-support': '*', 'io-ts': '^1.10.3' },\n devDependencies: { typescript: '^3.5.2' },\n }), 'utf8');\n}", "_createItemClass(name)\n {\n const _Item = class extends CollectionItem\n {\n static get KEY()\n {\n return name;\n }\n };\n CollectionItem.register(_Item.KEY, _Item);\n }", "function itemNameGenerator() {\n var storage = [\n \"Slow Cooker Coq au Vin\",\n \"Golden Beet & Beet Greens Pasta\",\n \"Meatballs with onion gravy\",\n \"Beef Curry\",\n \"Super Mom Stir Fry\",\n \"Almond-Thyme-Crusted Mahi Mahi\",\n \"Contest-Winning Parmesan\",\n \"Creamy Baked Risotto\",\n \"Chicken Cacciatore\",\n \"Bird's Nest Egg Salad\",\n \"Tofu Kabobs with Barbecue Sauce\",\n \"Grilled Chicken, and Quinoa Salad\",\n \"Grilled Pork Chops\",\n \"One Pot Garlic Butter Chicken\",\n \"Instant Pot Turkey Chili\",\n \"Chicken Fajita Burgers\",\n \"Fruit Salad\",\n \"Chicken Grilled Cheese Sandwich\",\n \"Steak Sandwiches\",\n \"Coconut & tamarind chicken curry\",\n \"Smoked Salmon Carbonara\",\n \"Pan-Seared Cod\",\n \"Guinea fowl tagine\",\n \"Kale Pesto Avocado Grilled Cheese\",\n \"Mexican Chicken Taco Skillet\",\n \"Skinnified Pork Burrito\",\n \"Calamari\",\n \"Bang-Bang Shrimp\",\n \"Chicken Fajita Casserole\",\n \"The TJ Hooker Pizza\",\n \"Seared Scallops\",\n \"Spinach Burrata Omelet\",\n \"Roasted Macaroni and Cheese\",\n \"Chicken and Corn Chowder\",\n \"Mediterranean Crab\",\n \"Creamy chicken & mango curry\",\n \"Grilled chicken\",\n \"Homemade Creamy Chicken Soup\",\n \"Flattened Chicken\",\n \"Skirt Steak With Arugula Salad\",\n \"Healthy Chicken Burgers\",\n \"Stir-Fried Udon Noodles\",\n \"Pan-seared Salmon\",\n \"Penne and Vegetable Casserole\",\n \"Grilled Watermelon Salad\",\n \"Slow Cooker Chicken Soup\",\n \"Creamy Chile Chicken Enchiladas\",\n \"Caprese Mac and Cheese\",\n \"Oven Baked Chicken Tacos\",\n \"Thai Peanut Chicken\"\n ];\n return storage[Math.floor(storage.length * Math.random())];\n}", "function makeUniqueName(baseName) {\n // Find the first unique 'name_n', where n is a positive number\n if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {\n baseName += \"_\";\n }\n var i = 1;\n while (true) {\n var generatedName = baseName + i;\n if (isUniqueName(generatedName)) {\n return generatedNameSet[generatedName] = generatedName;\n }\n i++;\n }\n }", "generateUniquePackageSlug(pkg) {\n let slug = pkg.name;\n\n slug = slug.replace(/[^@a-z0-9]+/g, '-');\n slug = slug.replace(/^-+|-+$/g, '');\n\n if (pkg.registry) {\n slug = `${pkg.registry}-${slug}`;\n } else {\n slug = `unknown-${slug}`;\n }\n\n const hash = pkg.remote.hash;\n\n\n if (pkg.version) {\n slug += `-${pkg.version}`;\n }\n\n if (pkg.uid && pkg.version !== pkg.uid) {\n slug += `-${pkg.uid}`;\n } else if (hash) {\n slug += `-${hash}`;\n }\n\n if (pkg.remote.integrity) {\n slug += `-integrity`;\n }\n\n return slug;\n }", "function KnownTypeNamesRule(context) {\n var schema = context.getSchema();\n var existingTypesMap = schema ? schema.getTypeMap() : Object.create(null);\n var definedTypes = Object.create(null);\n\n for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) {\n var def = _context$getDocument$2[_i2];\n\n if ((0, _predicates.isTypeDefinitionNode)(def)) {\n definedTypes[def.name.value] = true;\n }\n }\n\n var typeNames = Object.keys(existingTypesMap).concat(Object.keys(definedTypes));\n return {\n NamedType: function NamedType(node, _1, parent, _2, ancestors) {\n var typeName = node.name.value;\n\n if (!existingTypesMap[typeName] && !definedTypes[typeName]) {\n var _ancestors$;\n\n var definitionNode = (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 ? _ancestors$ : parent;\n var isSDL = definitionNode != null && isSDLNode(definitionNode);\n\n if (isSDL && isStandardTypeName(typeName)) {\n return;\n }\n\n var suggestedTypes = (0, _suggestionList.default)(typeName, isSDL ? standardTypeNames.concat(typeNames) : typeNames);\n context.reportError(new _GraphQLError.GraphQLError(\"Unknown type \\\"\".concat(typeName, \"\\\".\") + (0, _didYouMean.default)(suggestedTypes), node));\n }\n }\n };\n}", "function KnownTypeNamesRule(context) {\n var schema = context.getSchema();\n var existingTypesMap = schema ? schema.getTypeMap() : Object.create(null);\n var definedTypes = Object.create(null);\n\n for (var _i2 = 0, _context$getDocument$2 = context.getDocument().definitions; _i2 < _context$getDocument$2.length; _i2++) {\n var def = _context$getDocument$2[_i2];\n\n if ((0, _predicates.isTypeDefinitionNode)(def)) {\n definedTypes[def.name.value] = true;\n }\n }\n\n var typeNames = Object.keys(existingTypesMap).concat(Object.keys(definedTypes));\n return {\n NamedType: function NamedType(node, _1, parent, _2, ancestors) {\n var typeName = node.name.value;\n\n if (!existingTypesMap[typeName] && !definedTypes[typeName]) {\n var _ancestors$;\n\n var definitionNode = (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 ? _ancestors$ : parent;\n var isSDL = definitionNode != null && isSDLNode(definitionNode);\n\n if (isSDL && isStandardTypeName(typeName)) {\n return;\n }\n\n var suggestedTypes = (0, _suggestionList.default)(typeName, isSDL ? standardTypeNames.concat(typeNames) : typeNames);\n context.reportError(new _GraphQLError.GraphQLError(\"Unknown type \\\"\".concat(typeName, \"\\\".\") + (0, _didYouMean.default)(suggestedTypes), node));\n }\n }\n };\n}", "function addItemsByName(c){\n c.itemsByName = {};\n c.items.forEach(function(item){\n c.itemsByName[item.name] = item;\n });\n}", "function UniqueFieldDefinitionNamesRule(context) {\n var schema = context.getSchema();\n var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);\n var knownFieldNames = Object.create(null);\n return {\n InputObjectTypeDefinition: checkFieldUniqueness,\n InputObjectTypeExtension: checkFieldUniqueness,\n InterfaceTypeDefinition: checkFieldUniqueness,\n InterfaceTypeExtension: checkFieldUniqueness,\n ObjectTypeDefinition: checkFieldUniqueness,\n ObjectTypeExtension: checkFieldUniqueness\n };\n\n function checkFieldUniqueness(node) {\n var _node$fields;\n\n var typeName = node.name.value;\n\n if (!knownFieldNames[typeName]) {\n knownFieldNames[typeName] = Object.create(null);\n } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')\n\n\n var fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : [];\n var fieldNames = knownFieldNames[typeName];\n\n for (var _i2 = 0; _i2 < fieldNodes.length; _i2++) {\n var fieldDef = fieldNodes[_i2];\n var fieldName = fieldDef.name.value;\n\n if (hasField(existingTypeMap[typeName], fieldName)) {\n context.reportError(new _GraphQLError.GraphQLError(\"Field \\\"\".concat(typeName, \".\").concat(fieldName, \"\\\" already exists in the schema. It cannot also be defined in this type extension.\"), fieldDef.name));\n } else if (fieldNames[fieldName]) {\n context.reportError(new _GraphQLError.GraphQLError(\"Field \\\"\".concat(typeName, \".\").concat(fieldName, \"\\\" can only be defined once.\"), [fieldNames[fieldName], fieldDef.name]));\n } else {\n fieldNames[fieldName] = fieldDef.name;\n }\n }\n\n return false;\n }\n}", "function UniqueFieldDefinitionNamesRule(context) {\n var schema = context.getSchema();\n var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);\n var knownFieldNames = Object.create(null);\n return {\n InputObjectTypeDefinition: checkFieldUniqueness,\n InputObjectTypeExtension: checkFieldUniqueness,\n InterfaceTypeDefinition: checkFieldUniqueness,\n InterfaceTypeExtension: checkFieldUniqueness,\n ObjectTypeDefinition: checkFieldUniqueness,\n ObjectTypeExtension: checkFieldUniqueness\n };\n\n function checkFieldUniqueness(node) {\n var _node$fields;\n\n var typeName = node.name.value;\n\n if (!knownFieldNames[typeName]) {\n knownFieldNames[typeName] = Object.create(null);\n } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')\n\n\n var fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : [];\n var fieldNames = knownFieldNames[typeName];\n\n for (var _i2 = 0; _i2 < fieldNodes.length; _i2++) {\n var fieldDef = fieldNodes[_i2];\n var fieldName = fieldDef.name.value;\n\n if (hasField(existingTypeMap[typeName], fieldName)) {\n context.reportError(new _GraphQLError.GraphQLError(\"Field \\\"\".concat(typeName, \".\").concat(fieldName, \"\\\" already exists in the schema. It cannot also be defined in this type extension.\"), fieldDef.name));\n } else if (fieldNames[fieldName]) {\n context.reportError(new _GraphQLError.GraphQLError(\"Field \\\"\".concat(typeName, \".\").concat(fieldName, \"\\\" can only be defined once.\"), [fieldNames[fieldName], fieldDef.name]));\n } else {\n fieldNames[fieldName] = fieldDef.name;\n }\n }\n\n return false;\n }\n}", "function suggestUniqueFileName(aIdentifier, aType, aExistingNames) {\n let suffix = 1;\n let base = validateFileName(aIdentifier);\n let suggestion = base + aType;\n while (true) {\n if (!aExistingNames.has(suggestion)) {\n break;\n }\n\n suggestion = base + suffix + aType;\n suffix++;\n }\n\n return suggestion;\n}", "__init25() {this.forceRenames = new Map()}", "function ItemName(obj) { this.obj = obj; }", "['@_name']() {\n let value = this._findTagValue(['@_name', '@external']);\n if (!value) {\n logger.w(`can not resolve name.`);\n }\n\n this._value.name = value;\n\n let tags = this._findAll(['@_name', '@external']);\n if (!tags) {\n logger.w(`can not resolve name.`);\n return;\n }\n\n let name;\n for (let tag of tags) {\n let {tagName, tagValue} = tag;\n if (tagName === '@_name') {\n name = tagValue;\n } else if (tagName === '@external') {\n let {typeText, paramDesc} = ParamParser.parseParamValue(tagValue, true, false, true);\n name = typeText;\n this._value.externalLink = paramDesc;\n }\n }\n\n this._value.name = name;\n }", "function publishNamespace(name) {\n var exportName = name.substr(1);\n var body = namespaceBodyTbl[name];\n var bodyWrapped = '(function(' + name + '){' + body + '})' + '(' + name + ')';\n evil(name + '={};');\n evil('__extends=' + __extends.toString() + ';');\n var lib = {\n _decorate: evil('__decorate'),\n defineHidden: defineHidden\n };\n for (var _i = 0, _a = Object.keys(namespaceDepTbl[name]); _i < _a.length; _i++) {\n var depName = _a[_i];\n lib[depName] = namespaceDepTbl[name][depName];\n }\n lib[exportName + '__deps'] = Object.keys(lib);\n lib[exportName + '__postset'] = bodyWrapped;\n mergeInto(LibraryManager.library, lib);\n}", "function inferName(x) {\n\t\tif (x.isDefault && !hasOwnProp.call(names, x.module.id) && !hasOwnProp.call(used, x.as)) {\n\t\t\tnames[x.module.id] = x.as;\n\t\t\tused[x.as] = true;\n\t\t}\n\t}", "function UniqueFieldDefinitionNamesRule(context) {\n var schema = context.getSchema();\n var existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);\n var knownFieldNames = Object.create(null);\n return {\n InputObjectTypeDefinition: checkFieldUniqueness,\n InputObjectTypeExtension: checkFieldUniqueness,\n InterfaceTypeDefinition: checkFieldUniqueness,\n InterfaceTypeExtension: checkFieldUniqueness,\n ObjectTypeDefinition: checkFieldUniqueness,\n ObjectTypeExtension: checkFieldUniqueness\n };\n\n function checkFieldUniqueness(node) {\n var _node$fields;\n\n var typeName = node.name.value;\n\n if (!knownFieldNames[typeName]) {\n knownFieldNames[typeName] = Object.create(null);\n } // istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')\n\n\n var fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : [];\n var fieldNames = knownFieldNames[typeName];\n\n for (var _i2 = 0; _i2 < fieldNodes.length; _i2++) {\n var fieldDef = fieldNodes[_i2];\n var fieldName = fieldDef.name.value;\n\n if (hasField(existingTypeMap[typeName], fieldName)) {\n context.reportError(new _error_GraphQLError_mjs__WEBPACK_IMPORTED_MODULE_0__[\"GraphQLError\"](\"Field \\\"\".concat(typeName, \".\").concat(fieldName, \"\\\" already exists in the schema. It cannot also be defined in this type extension.\"), fieldDef.name));\n } else if (fieldNames[fieldName]) {\n context.reportError(new _error_GraphQLError_mjs__WEBPACK_IMPORTED_MODULE_0__[\"GraphQLError\"](\"Field \\\"\".concat(typeName, \".\").concat(fieldName, \"\\\" can only be defined once.\"), [fieldNames[fieldName], fieldDef.name]));\n } else {\n fieldNames[fieldName] = fieldDef.name;\n }\n }\n\n return false;\n }\n}" ]
[ "0.58403444", "0.57442", "0.5719649", "0.5575649", "0.5575649", "0.5556027", "0.5556027", "0.5552457", "0.5389013", "0.52895075", "0.5261061", "0.5215282", "0.5211531", "0.5206816", "0.5181104", "0.50838786", "0.50370914", "0.50254107", "0.49946228", "0.49946228", "0.4979858", "0.4941961", "0.4941961", "0.49307412", "0.49047184", "0.4901247", "0.49009246", "0.48917654", "0.4888727", "0.48833472" ]
0.68521297
0
Before writing out a declaration, _modifySpan() applies various fixups to make it nice.
_modifySpan(span, dtsEntry, astDeclaration, dtsKind) { const previousSpan = span.previousSibling; let recurseChildren = true; switch (span.kind) { case ts.SyntaxKind.JSDocComment: // If the @packagedocumentation comment seems to be attached to one of the regular API items, // omit it. It gets explictly emitted at the top of the file. if (span.node.getText().match(/(?:\s|\*)@packagedocumentation(?:\s|\*)/g)) { span.modification.skipAll(); } // For now, we don't transform JSDoc comment nodes at all recurseChildren = false; break; case ts.SyntaxKind.ExportKeyword: case ts.SyntaxKind.DefaultKeyword: case ts.SyntaxKind.DeclareKeyword: // Delete any explicit "export" or "declare" keywords -- we will re-add them below span.modification.skipAll(); break; case ts.SyntaxKind.InterfaceKeyword: case ts.SyntaxKind.ClassKeyword: case ts.SyntaxKind.EnumKeyword: case ts.SyntaxKind.NamespaceKeyword: case ts.SyntaxKind.ModuleKeyword: case ts.SyntaxKind.TypeKeyword: case ts.SyntaxKind.FunctionKeyword: // Replace the stuff we possibly deleted above let replacedModifiers = ''; // Add a declare statement for root declarations (but not for nested declarations) if (!astDeclaration.parent) { replacedModifiers += 'declare '; } if (dtsEntry.exported) { replacedModifiers = 'export ' + replacedModifiers; } if (previousSpan && previousSpan.kind === ts.SyntaxKind.SyntaxList) { // If there is a previous span of type SyntaxList, then apply it before any other modifiers // (e.g. "abstract") that appear there. previousSpan.modification.prefix = replacedModifiers + previousSpan.modification.prefix; } else { // Otherwise just stick it in front of this span span.modification.prefix = replacedModifiers + span.modification.prefix; } break; case ts.SyntaxKind.VariableDeclaration: if (!span.parent) { // The VariableDeclaration node is part of a VariableDeclarationList, however // the Entry.followedSymbol points to the VariableDeclaration part because // multiple definitions might share the same VariableDeclarationList. // // Since we are emitting a separate declaration for each one, we need to look upwards // in the ts.Node tree and write a copy of the enclosing VariableDeclarationList // content (e.g. "var" from "var x=1, y=2"). const list = TypeScriptHelpers_1.TypeScriptHelpers.matchAncestor(span.node, [ts.SyntaxKind.VariableDeclarationList, ts.SyntaxKind.VariableDeclaration]); if (!list) { throw new Error('Unsupported variable declaration'); } const listPrefix = list.getSourceFile().text .substring(list.getStart(), list.declarations[0].getStart()); span.modification.prefix = 'declare ' + listPrefix + span.modification.prefix; span.modification.suffix = ';'; } break; case ts.SyntaxKind.Identifier: let nameFixup = false; const identifierSymbol = this._typeChecker.getSymbolAtLocation(span.node); if (identifierSymbol) { const followedSymbol = TypeScriptHelpers_1.TypeScriptHelpers.followAliases(identifierSymbol, this._typeChecker); const referencedDtsEntry = this._dtsEntriesBySymbol.get(followedSymbol); if (referencedDtsEntry) { if (!referencedDtsEntry.nameForEmit) { // This should never happen throw new Error('referencedEntry.uniqueName is undefined'); } span.modification.prefix = referencedDtsEntry.nameForEmit; nameFixup = true; // For debugging: // span.modification.prefix += '/*R=FIX*/'; } } if (!nameFixup) { // For debugging: // span.modification.prefix += '/*R=KEEP*/'; } break; } if (recurseChildren) { for (const child of span.children) { let childAstDeclaration = astDeclaration; // Should we trim this node? let trimmed = false; if (SymbolAnalyzer_1.SymbolAnalyzer.isAstDeclaration(child.kind)) { childAstDeclaration = this._astSymbolTable.getChildAstDeclarationByNode(child.node, astDeclaration); const releaseTag = this._getReleaseTagForAstSymbol(childAstDeclaration.astSymbol); if (!this._shouldIncludeReleaseTag(releaseTag, dtsKind)) { const modification = child.modification; // Yes, trim it and stop here const name = childAstDeclaration.astSymbol.localName; modification.omitChildren = true; modification.prefix = `/* Excluded from this release type: ${name} */`; modification.suffix = ''; if (child.children.length > 0) { // If there are grandchildren, then keep the last grandchild's separator, // since it often has useful whitespace modification.suffix = child.children[child.children.length - 1].separator; } if (child.nextSibling) { // If the thing we are trimming is followed by a comma, then trim the comma also. // An example would be an enum member. if (child.nextSibling.kind === ts.SyntaxKind.CommaToken) { // Keep its separator since it often has useful whitespace modification.suffix += child.nextSibling.separator; child.nextSibling.modification.skipAll(); } } trimmed = true; } } if (!trimmed) { this._modifySpan(child, dtsEntry, childAstDeclaration, dtsKind); } } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function attachLocalSpans(doc, change, from, to) {\n\t\t var existing = change[\"spans_\" + doc.id], n = 0;\n\t\t doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n\t\t if (line.markedSpans)\n\t\t { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n\t\t ++n;\n\t\t });\n\t\t }", "function attachLocalSpans(doc, change, from, to) {\n\t\t var existing = change[\"spans_\" + doc.id], n = 0;\n\t\t doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {\n\t\t if (line.markedSpans)\n\t\t (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans;\n\t\t ++n;\n\t\t });\n\t\t }", "function attachLocalSpans(doc, change, from, to) {\r\n var existing = change[\"spans_\" + doc.id], n = 0;\r\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {\r\n if (line.markedSpans)\r\n (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans;\r\n ++n;\r\n });\r\n }", "function attachLocalSpans(doc, change, from, to) {\n\t var existing = change[\"spans_\" + doc.id], n = 0;\n\t doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {\n\t if (line.markedSpans)\n\t (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans;\n\t ++n;\n\t });\n\t }", "function attachLocalSpans(doc, change, from, to) {\n\t var existing = change[\"spans_\" + doc.id], n = 0;\n\t doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {\n\t if (line.markedSpans)\n\t (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans;\n\t ++n;\n\t });\n\t }", "function attachLocalSpans(doc, change, from, to) {\n\t var existing = change[\"spans_\" + doc.id], n = 0;\n\t doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {\n\t if (line.markedSpans)\n\t (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans;\n\t ++n;\n\t });\n\t }", "function attachLocalSpans(doc, change, from, to) {\r\n var existing = change[\"spans_\" + doc.id], n = 0;\r\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\r\n if (line.markedSpans)\r\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\r\n ++n;\r\n });\r\n}", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n}", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n}", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n}", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n}", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n}", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n}", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n}", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n}", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n}", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n}", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n}", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {\n if (line.markedSpans)\n (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans;\n ++n;\n });\n }", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {\n if (line.markedSpans)\n (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans;\n ++n;\n });\n }", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {\n if (line.markedSpans)\n (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans;\n ++n;\n });\n }", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {\n if (line.markedSpans)\n (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans;\n ++n;\n });\n }", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {\n if (line.markedSpans)\n (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans;\n ++n;\n });\n }", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {\n if (line.markedSpans)\n (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans;\n ++n;\n });\n }", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {\n if (line.markedSpans)\n (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans;\n ++n;\n });\n }", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n }", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n }", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n }", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n }", "function attachLocalSpans(doc, change, from, to) {\n var existing = change[\"spans_\" + doc.id], n = 0;\n doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {\n if (line.markedSpans)\n { (existing || (existing = change[\"spans_\" + doc.id] = {}))[n] = line.markedSpans; }\n ++n;\n });\n }" ]
[ "0.57268137", "0.57213247", "0.5699011", "0.56869346", "0.56869346", "0.56869346", "0.5681026", "0.5663481", "0.5663481", "0.5663481", "0.5663481", "0.5663481", "0.5663481", "0.5663481", "0.5663481", "0.5663481", "0.5663481", "0.5663481", "0.56591445", "0.56591445", "0.56591445", "0.56591445", "0.56591445", "0.56591445", "0.56591445", "0.5655021", "0.5655021", "0.5655021", "0.5655021", "0.5655021" ]
0.73561174
0
You are given two positive integers a and b (a < b <= 20000). Complete the function which returns a list of all those numbers in the interval [a, b) whose digits are made up of prime numbers (2, 3, 5, 7) but which are not primes themselves. non prime single digit : 1, 4, 6, 8, 9
function notPrimes(a,b) { let nonPrimeArr = []; for(let i = a; i <= b; i++) { if(!isPrime(i) && checkForPrimeDigits(i)) { nonPrimeArr.push(i) } } return nonPrimeArr; function checkForPrimeDigits(num) { let numStr = num.toString(); for(let elem of numStr) { if(elem!=='2' && elem!=='3' && elem!=='5' && elem!=='7') { return false; } } return true; } function isPrime(num) { if(num < 2) return false; for(let i=2; i < num; i++){ if(num%i===0) return false; } return true; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function notPrimes(a,b){\n let arr = [];\n for (let i = a; i < b; i++){\n if (!/[014689]/.test(i)) {\n for (let j = 2; j <= Math.sqrt(i); j++){\n if (i % j === 0) { arr.push(i); break;}\n }\n }\n }\n return arr;\n}", "function primes(limit) {\n let list = [];\n let nonPrimes = [];\n\n //build range\n for (let idx = 2; idx <= limit; idx++) list.push(idx);\n\n // mark nonPrimes\n list.forEach(number => {\n if (!nonPrimes.includes(number)) {\n for (let testNum = number * 2; testNum <= limit; testNum += number) {\n nonPrimes.push(testNum);\n }\n }\n });\n \n // filter out nonPrimes\n return list.filter(number => !nonPrimes.includes(number));\n}", "function all_primes_intherange(lowerLimit, upperLimit) {\r\n let checker = false;\r\n let primeList = [];\r\n if (+lowerLimit%2 === 0){\r\n loop1:for (let i = +lowerLimit+1; i <= +upperLimit; i+=2) {\r\n for (let j = 3; j < i/2; j+=2) {\r\n if ( i % j !== 0 ) { checker = true; \r\n } else { checker = false;break;} \r\n }\r\n if (checker === true) { primeList.push(i);}\r\n }\r\n } else {\r\n for (let i = +lowerLimit; i <= +upperLimit; i+=2) {\r\n for (let j = 3; j < i/2; j+=2) {\r\n if ( i % j !== 0 ) { checker = true;\r\n } else { checker = false;} \r\n }\r\n if (checker === true) { primeList.push(i);}\r\n }\r\n }\r\n return primeList;\r\n}", "function primeList() {\n // For max=60M, computes 3.5 million primes in 15 seconds\n // For max=10M, computes 67k primes in 2 seconds.\n\n // Initialize variables\n let max = 10000000; // Maximum number to check if prime.\n let a = new Array(max);\n let out = []\n\n // Initialize sieve array\n for (var i=0; i<=max; i++) {\n a[i]=1;\n }\n\n // Mark all composite numbers\n for (var i=2; i<=max; i++) {\n for (var j=2; i*j<=max; j++) {\n a[i*j]=0;\n }\n }\n\n // Generate output list of prime numbers\n for (var i=2; i<=max; i++) {\n if (a[i]==1) {\n out.push(i)\n }\n }\n\n return out;\n}", "checkPrime(s1, s2) {\n var count = 0, flag = 0, k = 0;\n var array = [];\n for (var i = s1; i <= s2; i++) {\n for (var j = 2; j < i; j++) {\n if (i % j == 0) {\n flag = 0;\n count++;\n break;\n }\n else {\n flag = 1;\n }\n }\n if (flag == 1) {\n array[k++] = i;\n }\n }\n return array;\n }", "function checkCoprimeNum(a,b){\n\tif (b===1) {\n\t\treturn true;\n\t}\n\tif (!(a % b)) {\n\t\treturn false;\n\t} else {\n\t\treturn checkCoprimeNum(b, a%b);\n\t}\n}", "function getPrime(x,y){\n for(let i=x;i<y;i++){\n let flag = true;\n for(let a=2;a<i;a++){\n if(i%a==0 && i!==a){\n flag= false\n break\n }\n }\n if(flag==true){\n console.log(i)\n }\n }\n}", "function findSmallerPrimes() {\n for (let i = 0; i < 1000; i++) {\n isPrime(i);\n }\n}", "function primeNumber(a) {\n for (let i = 2; i < a; i++) {\n if(!showPrime(i)) continue;\n }\n}", "findPrime(s1, s2) {\n var count = 0, flag = 0, k = 0;\n var prime = [];\n for (var i = s1; i <= s2; i++) {\n for (var j = 2; j < i; j++) {\n if (i % j == 0) {\n flag = 0;\n count++;\n break;\n }\n else {\n flag = 1;\n }\n }\n if (flag == 1) {\n prime[k++] = i;\n }\n }\n return prime;\n }", "function primenum(){\n var num=+prompt('Enter a number');\n if(num<3){\n console.log('Not a prime number');\n } else {\n checkPrimenum();\n }\n\n function checkPrimenum() {\n for (var a=2;a<num;a++) {\n for (var b=2;b<a;b++) {\n if (a%b == 0) break;\n }\n if (b == a){\n console.log(a);\n }\n }\n } \n}", "findPrime(s1, s2) {\n var flag = 0, k = 0;\n var prime = [];\n\n for (var i = s1; i <= s2; i++) {\n for (var j = 2; j < i; j++) {\n if (i % j == 0) {\n flag = 0;\n break;\n }\n else {\n flag = 1;\n }\n }\n if (flag == 1) {\n prime[k++] = i;\n }\n }\n return prime;\n }", "function isPrimeNumb (numb) {\n \n var result = true;\n \n for (var i = 2; i < numb; i++) {\n if (numb % i === 0 && numb !== i ) {\n result = false;\n }\n }\n return result;\n}", "function isPrimeNumber (a) {\n for (var i = 2; i < a; i++) {\n if (a % i == 0) {\n return false;\n }\n }\n return true;\n}", "function checkPrimeNumber(start, end) {\n console.log('The prime numbers between ' + start + ' and ' + end + ' are:');\n for (let i = start; i <= end; i++) {\n let flag = false;\n for (let j = 2; j < i; j++) {\n if (i % j == 0) {\n flag = true;\n break;\n }\n }\n\n if (i > 1 && flag === false) {\n console.log(i);\n }\n }\n\n}", "function prime2(n) {\n const data = [];\n for (let i = 1; i < n; i += 2) {\n data.push(i);\n }\n data[0] = 0;\n for(let i = 1; i < data.length; i+= 1) {\n if (data[i] > 0) {\n let k = data[i];\n let u = i * (1 + k);\n if (u > data.length) { break; }\n for (let j = u; j < data.length; j += k) {\n data[j] = 0;\n }\n }\n }\n const result = [2];\n for (let i of data) {\n if (i > 0) {\n result.push(i);\n }\n }\n return result;\n }", "function showPrimes(limit) {\n for(let number=2; number<=limit; number++) {\n\n let isPrime = true;\n \n for (let factor=2; factor<number; factor++) {\n if (number % factor === 0) {\n //isPrime = false;\n //break; // no sense in checking the rest of the numbers\n }\n }\n\n if (isPrime) console.log(number);\n } \n}", "function primeNumbers(n) {\n let primes = [];\n\n nextPrime:\n for (let i = 2; i <= n; i++) {\n for (let j = 2; j < i; j++) {\n if (i % j === 0) {\n continue nextPrime;\n }\n }\n \n primes.push(i);\n }\n\n return primes;\n}", "function primes(n) {\n var realNumbers = [];\n for(i=0; i<=n; i++) {\n realNumbers.push(true);\n }\n var primeNumbers = [];\n for (i=0; i<=n; i++) {\n if (i == 0 || i == 1 || realNumbers[i] === false) {\n continue;\n }\n primeNumbers.push(i);\n for (j=i; true; j++) {\n if (i*j < realNumbers.length) {\n realNumbers[i*j] = false;\n } else {\n break;\n }\n }\n }\n return primeNumbers;\n}", "function funcIsPrimeOrFactors(numNumber) {\n // body... \n var numHalf = Math.floor(numNumber / 2);\n var arrFactors = [];\n\n for (var i = 2; i <= numHalf; i++) {\n var numQuotient = Math.floor(numNumber / i);\n var numRemainder = numNumber % i;\n if (numRemainder === 0) {\n arrFactors.push([i, numQuotient]);\n }\n }\n console.log(arrFactors);\n return [arrFactors.length === 0, arrFactors];\n}", "function PrimeValues(value) {\n let primes = [], tempArr=[];\n\n //fills an array with 'true' from 2 to the given value.\n for(let i = 2; i < value; i++) {\n primes[i] = true;\n }\n\n //work way thru array tagging primes & non-primes\n let limit = Math.sqrt(value);\n for(let i = 2; i < limit; i++) {\n if(primes[i] === true) {\n for(let j = i * i; j < value; j += i) {\n primes[j] = false;\n }\n }\n }\n\n // remove nonprimes from array.\n for(let i = 2; i < value; i++) {\n if(primes[i] === true) {\n tempArr.push(i);\n }\n }\n return tempArr;\n }", "function showPrimes(limit) {\n for (let number = 2; number <= limit; number++) {\n // 2 - current (number)\n\n let isPrime = true;\n for (let factor = 2; factor < number; factor++) {\n if (number % factor === 0) {\n isPrime = false;\n break;\n }\n }\n if (isPrime) console.log(number);\n }\n}", "function getPrime() {\n var i = 0;\n var j = 0;\n\n limit_numbers = document.getElementById('limit').value;\n\n //loop till i equals to limit_numbers of numbers\n for (i = 1; i <= limit_numbers; i++) {\n count = 0;\n\n for (j = 1; j <= i; j++) {\n // % modules will give the reminder value, so if the reminder is 0 then it is divisible\n if (i % j == 0) {\n //increment the value of count\n count++;\n }\n }\n\n\n //prime number should be exactly divisible by 2 times only (itself and 1)\n if (count == 2) {\n document.getElementById(\"result\").insertAdjacentHTML('beforeend', i + '<br>');\n }\n }\n}", "function printPrimes(){\n var isPrime = true;\n for(let i = 2; i <= 100; i++) {\n isPrime = true;\n for (let j = 2; j <= i/2; j++) {\n if (i%j === 0) {\n isPrime = false;\n break;\n }\n }\n if (isPrime) {\n console.log(i);\n }\n }\n}", "function testPrimeNum(num){\n for(var i=2; i<num; i++){\n if(num%i===0){\n return false;\n }\n return num>1;\n }\n}", "function primeSieve(n) {\n var array = [], upperLimit = Math.sqrt(n), output = [];\n\n //makes an array from 2 to (n-1)\n for (var i = 0; i < n; i++){\n array.push(true);\n }\n\n //removes multiples of primes starting from 2,3,5\n for (var i = 2; i <= upperLimit; i++){\n if (array[i]) {\n for (var j = i * i; j < n; j += i) {\n array[j] = false;\n }\n }\n }\n\n //all array[i]set to true are primes for(var i = 2; i < n; i++){\n for (var i = 2; i < n; i++){\n if (array[i]){\n output.push(i);\n }\n }\n return output;\n}", "function PrimeTest(a){\n if (isNaN(a) || !isFinite(a) || a % 1 || a < 2) return false; \n var m = Math.sqrt(a);\n for (var i = 2; i <= m; i++) if (a % i==0) return false;\n return true;\n}", "function multiples(num1, num2) {\n let new_array = [];\n for (let i = 1; i <= 100; i++) {\n if (i % num1 === 0 && i % num2 === 0) {\n new_array.push(i);\n }\n } //end of for\n return new_array;\n } //end of multiples", "function sieve(limit){\n\n\tvar arr =[];\n\t//generate array with numbers 0,1, ...limit\n\tfor (var i =0; i < limit; i++){\n\t\tarr.push(i);\n\t}\n\n\t//remove all non-prime numbers using sieve method\n\tfor (var j =2; j < limit; j++){\n\t\tfor (var k= 2; k <limit/j; k++){\n\t\t\tarr[j*k] = 0;\n\t\t}\n\t}\n\treturn arr;\n}", "function getPrimes(int) {\r\n var primes = [];\r\n var curr = 2n;\r\n \r\n while (curr < int) {\r\n if ((int / curr) * curr === int) {\r\n int /= curr;\r\n primes.push(curr);\r\n console.log(curr);\r\n } else {\r\n curr += 1n;\r\n }\r\n }\r\n primes.push(int);\r\n \r\n return primes;\r\n}" ]
[ "0.8612787", "0.7368873", "0.7118093", "0.70932066", "0.7036627", "0.69277114", "0.6901608", "0.68667215", "0.67853785", "0.6782012", "0.67624044", "0.6757332", "0.67366874", "0.67043066", "0.6678171", "0.6563992", "0.6545962", "0.6520927", "0.6482521", "0.647499", "0.64729214", "0.6459936", "0.64575654", "0.6455552", "0.642502", "0.6423537", "0.64211845", "0.6412729", "0.64089704", "0.6406081" ]
0.84410274
1
Helper Methods Unlock the modal for animation.
function unlockModal() { locked = false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function lockModal() {\n locked = true;\n }", "function lockModal() {\n locked = true;\n }", "function unlockForEdit() {\n\t$(modalTextTitle).prop(\"disabled\",false);\n\t$(modalTextTitle).css(\"border-bottom\", \"2px solid #7C8487\");\n\n\t$(modalTextareaDescription).prop(\"disabled\",false);\n\t$(modalTextareaDescription).css(\"border-bottom\", \"2px solid #7C8487\");\n\n\t$(modalLabelTitle).hide();\n\t$(modalLabelDescription).hide();\n\t$(modalLimitationLabelTitle).show();\n\t$(modalLimitationLabelDescription).show();\n\n\t$(modalIBedit).hide();\n\t$(modalIBdelete).hide();\n\t$(modalButtonEdit).show();\n}", "deactivateModal() {\n\t\tdocument.querySelector('#login-modal').style.display = 'none';\n\t}", "function modalAnimation() {}", "function hideShareModal() {\n // modal animation\n $( '.celebration-cards-share-modal' ).animate( {\n opacity: 0\n }, 500, function() {\n $( '.celebration-cards-share-modal' ).css( \"display\", \"none\" );\n $('.celebration-cards-share-modal__content__cancel').css('display', 'block');\n $('.celebration-cards-share-modal__content__input').css('display', 'none');\n $('.celebration-cards-share-modal__content__input').css('opacity', '0');\n });\n }", "hideModal() {\n // close the modal first\n this.modal.current.setTransition('exit', () => {\n Promise.resolve(\n // un-dim the page after modal slide animation completes\n setTimeout(() => {\n this.setState({\n dimClass: 'dimExit',\n });\n }, Number(Animation.modalSlideDuration)),\n )\n .then(() => {\n // reshow the button and hide modal/dim class\n setTimeout(() => {\n this.setState({\n showButton: true,\n showModal: false,\n dimClass: 'none',\n });\n }, Number(Animation.dimDuration));\n });\n });\n }", "function hideModal() {\r\n //The modal is currently closed\r\n modal.open = false;\r\n //Add class to hide modal\r\n modal.container.classList.add(\"hide-modal\");\r\n }", "function closeModal() {\n MODAL.removeAttribute(\"open\");\n resetGame();\n}", "function closeAnimation() {\n //\n // First, determine if we're in the middle of animation.\n //\n if ( !locked ) {\n //\n // We're not animating, let's lock the modal for animation.\n //\n lockModal();\n //\n // Clear the modal of the open class.\n //\n modal.removeClass( \"open\" );\n\n //\n // Are we using the 'fadeAndPop' animation?\n //\n if ( options.animation === \"fadeAndPop\" ) {\n //\n // Yes, okay, let's set the animation properties.\n //\n modal.animate( {\n //\n // Set the top property to the document scrollTop minus calculated topOffset.\n //\n \"top\": $doc.scrollTop() - topOffset + 'px',\n //\n // Fade the modal out, by using the opacity property.\n //\n \"opacity\": 0\n\n },\n /*\n * Fade speed.\n */\n options.animationSpeed / 2,\n /*\n * End of animation callback.\n */\n function () {\n //\n // Set the css hidden options.\n //\n modal.css( cssOpts.close );\n\n });\n //\n // Is the modal animation queued?\n //\n if ( !modalQueued ) {\n //\n // Oh, the modal(s) are mid animating.\n // Let's delay the animation queue.\n //\n modalBg.delay( options.animationSpeed )\n //\n // Fade out the modal background.\n //\n .fadeOut(\n /*\n * Animation speed.\n */\n options.animationSpeed,\n /*\n * End of animation callback.\n */\n function () {\n //\n // Trigger the modal 'closed' event.\n // This should trigger any method set in the options.closed property.\n //\n modal.trigger( 'reveal:closed' );\n\n });\n\n } else {\n //\n // We're not mid queue.\n // Trigger the modal 'closed' event.\n // This should trigger any method set in the options.closed propety.\n //\n modal.trigger( 'reveal:closed' );\n\n } // end if !modalQueued\n\n } // end if animation 'fadeAndPop'\n\n //\n // Are we using the 'fade' animation.\n //\n if ( options.animation === \"fade\" ) {\n //\n // Yes, we're using the 'fade' animation.\n //\n modal.animate( { \"opacity\" : 0 },\n /*\n * Animation speed.\n */\n options.animationSpeed,\n /*\n * End of animation callback.\n */\n function () {\n //\n // Set the css close options.\n //\n modal.css( cssOpts.close );\n\n }); // end animate\n\n //\n // Are we mid animating the modal(s)?\n //\n if ( !modalQueued ) {\n //\n // Oh, the modal(s) are mid animating.\n // Let's delay the animation queue.\n //\n modalBg.delay( options.animationSpeed )\n //\n // Let's fade out the modal background element.\n //\n .fadeOut(\n /*\n * Animation speed.\n */\n options.animationSpeed,\n /*\n * End of animation callback.\n */\n function () {\n //\n // Trigger the modal 'closed' event.\n // This should trigger any method set in the options.closed propety.\n //\n modal.trigger( 'reveal:closed' );\n\n }); // end fadeOut\n\n } else {\n //\n // We're not mid queue.\n // Trigger the modal 'closed' event.\n // This should trigger any method set in the options.closed propety.\n //\n modal.trigger( 'reveal:closed' );\n\n } // end if !modalQueued\n\n } // end if animation 'fade'\n\n //\n // Are we not animating?\n //\n if ( options.animation === \"none\" ) {\n //\n // We're not animating.\n // Set the modal close css options.\n //\n modal.css( cssOpts.close );\n //\n // Is the modal in the middle of an animation queue?\n //\n if ( !modalQueued ) {\n //\n // It's not mid queueu. Just hide it.\n //\n modalBg.css( { 'display': 'none' } );\n }\n //\n // Trigger the modal 'closed' event.\n // This should trigger any method set in the options.closed propety.\n //\n modal.trigger( 'reveal:closed' );\n\n } // end if not animating\n //\n // Reset the modalQueued variable.\n //\n modalQueued = false;\n } // end if !locked\n\n }", "function closeAnimation() {\n //\n // First, determine if we're in the middle of animation.\n //\n if ( !locked ) {\n //\n // We're not animating, let's lock the modal for animation.\n //\n lockModal();\n //\n // Clear the modal of the open class.\n //\n modal.removeClass( \"open\" );\n\n //\n // Are we using the 'fadeAndPop' animation?\n //\n if ( options.animation === \"fadeAndPop\" ) {\n //\n // Yes, okay, let's set the animation properties.\n //\n modal.animate( {\n //\n // Set the top property to the document scrollTop minus calculated topOffset.\n //\n \"top\": $doc.scrollTop() - topOffset + 'px',\n //\n // Fade the modal out, by using the opacity property.\n //\n \"opacity\": 0\n\n },\n /*\n * Fade speed.\n */\n options.animationSpeed / 2,\n /*\n * End of animation callback.\n */\n function () {\n //\n // Set the css hidden options.\n //\n modal.css( cssOpts.close );\n\n });\n //\n // Is the modal animation queued?\n //\n if ( !modalQueued ) {\n //\n // Oh, the modal(s) are mid animating.\n // Let's delay the animation queue.\n //\n modalBg.delay( options.animationSpeed )\n //\n // Fade out the modal background.\n //\n .fadeOut(\n /*\n * Animation speed.\n */\n options.animationSpeed,\n /*\n * End of animation callback.\n */\n function () {\n //\n // Trigger the modal 'closed' event.\n // This should trigger any method set in the options.closed property.\n //\n modal.trigger( 'reveal:closed' );\n\n });\n\n } else {\n //\n // We're not mid queue.\n // Trigger the modal 'closed' event.\n // This should trigger any method set in the options.closed propety.\n //\n modal.trigger( 'reveal:closed' );\n\n } // end if !modalQueued\n\n } // end if animation 'fadeAndPop'\n\n //\n // Are we using the 'fade' animation.\n //\n if ( options.animation === \"fade\" ) {\n //\n // Yes, we're using the 'fade' animation.\n //\n modal.animate( { \"opacity\" : 0 },\n /*\n * Animation speed.\n */\n options.animationSpeed,\n /*\n * End of animation callback.\n */\n function () {\n //\n // Set the css close options.\n //\n modal.css( cssOpts.close );\n\n }); // end animate\n\n //\n // Are we mid animating the modal(s)?\n //\n if ( !modalQueued ) {\n //\n // Oh, the modal(s) are mid animating.\n // Let's delay the animation queue.\n //\n modalBg.delay( options.animationSpeed )\n //\n // Let's fade out the modal background element.\n //\n .fadeOut(\n /*\n * Animation speed.\n */\n options.animationSpeed,\n /*\n * End of animation callback.\n */\n function () {\n //\n // Trigger the modal 'closed' event.\n // This should trigger any method set in the options.closed propety.\n //\n modal.trigger( 'reveal:closed' );\n\n }); // end fadeOut\n\n } else {\n //\n // We're not mid queue.\n // Trigger the modal 'closed' event.\n // This should trigger any method set in the options.closed propety.\n //\n modal.trigger( 'reveal:closed' );\n\n } // end if !modalQueued\n\n } // end if animation 'fade'\n\n //\n // Are we not animating?\n //\n if ( options.animation === \"none\" ) {\n //\n // We're not animating.\n // Set the modal close css options.\n //\n modal.css( cssOpts.close );\n //\n // Is the modal in the middle of an animation queue?\n //\n if ( !modalQueued ) {\n //\n // It's not mid queueu. Just hide it.\n //\n modalBg.css( { 'display': 'none' } );\n }\n //\n // Trigger the modal 'closed' event.\n // This should trigger any method set in the options.closed propety.\n //\n modal.trigger( 'reveal:closed' );\n\n } // end if not animating\n //\n // Reset the modalQueued variable.\n //\n modalQueued = false;\n } // end if !locked\n\n }", "function onHiddenBsModal() {\n isModalInTransitionToHide = false;\n isModalVisible = false;\n }", "modify () {\n\n // Hide modal\n this.modal.hide();\n }", "_dismiss() {\n\t\tthis.unbind();\n\t\tthis._isVisible = false;\n\t}", "function onHideBsModal() {\n isModalInTransitionToHide = true;\n }", "function unlock() {\n\tvar item = $(this).parents(\".irform-item:first\");\n\tmodal(\"<div class=\\\"alert alert-warning\\\" role=\\\"alert\\\"><strong>Warning!</strong> By unlocking this item, you will overwrite its value locally and hence any update will not be inherited from its parent values.</div>\", function() {\n\t\t$(item).find(\"fieldset.col-sm-9:first\").removeClass(\"col-sm-9\").addClass(\"col-sm-10\");\n\t\t$(item).find(\"div.col-sm-1\").remove();\n\t\tmainForm.options.disable.call(mainForm, false, item);\n\t\tmainForm.ignore(item, false);\n\t});\n}", "function closeModal33_openModal4()\n{\n modal3.style.display = \"none\";\n modal4.style.display = \"flex\";\n \n}", "modalHide(myModal) {\n myModal.style.display = \"none\";\n player.choosePlayer();\n }", "modalExit() {\n this.setState({showModal: false});\n }", "function cerrarModal() {\n capaModal.classList.remove(\"activa\");\n modal.style.animation = 'modalOut ' + tiempoAnimacion +'ms forwards ease';\n setTimeout(() => { seccionModal.style.transform = \"translateY(-2000px)\" }, tiempoAnimacion);\n}", "function closeModalBox() {\r\n\t\t$['mapsettings'].modal = false;\r\n\t\t$('#modal').slideUp(\"slow\", function(){\r\n\t\t\t$('#modal').remove();\r\n\t\t});\r\n\t\t$(\"#overlay\").fadeTo(\"slow\", 0, function() {\r\n\t\t\t$(\"#overlay\").remove();\r\n\t\t\tif($['mapsettings'].afterModal.length > 0) ($['mapsettings'].afterModal.shift())();\r\n\t\t});\r\n\t}", "hide(){\n\t\tthis.modalShadow.hide();\n\t\tthis.modalBody.hide();\n\t}", "handleCloseModal(){\n this.bShowModal = false;\n }", "function handleClosingModalBoxes(event){\n var targetModalBox = $(event.target).closest(\".modal-box\");\n targetModalBox.hide();\n targetModalBox.attr(\"aria-modal\", \"false\")\n //resume playing animation\n jssor_1_slider.$Play();\n //enable scrolling of body\n $(\"body\").css(\"overflow\", \"visible\");\n}", "function esconderModal() {\n\tmodal.style.display = 'none';\n}", "function modalHidden(){\n\t\trestoreTabindex();\n\t\ttdc.Grd.Modal.isVisible=false;\n\t}", "function dismissModal() {\n if (currentModal) {\n currentModal.dismiss().then(() => {\n currentModal = null;\n });\n }\n}", "function closeModal() {\n modal.style.opacity = \"0\";\n setTimeout(() => {\n modal.style.display = \"none\";\n }, 600);\n}", "function hideModal(modalElement)\r\n{\r\n var modalBackground = $(\"#modalBackground\");\r\n var modalTransitionTime = 250;\r\n\r\n modalBackground.unbind(\"click\");\r\n modalBackground.fadeOut(modalTransitionTime);\r\n modalElement.fadeOut(modalTransitionTime);\r\n}", "function toggle() {\r\n setModal(!modal)\r\n }" ]
[ "0.72454244", "0.72454244", "0.6896535", "0.6820743", "0.67881566", "0.6694964", "0.66023105", "0.65635765", "0.6528138", "0.6525814", "0.6525814", "0.6509781", "0.6484871", "0.6479335", "0.646648", "0.6439817", "0.6433108", "0.6390839", "0.638449", "0.6374887", "0.63701576", "0.63546246", "0.63450307", "0.63377905", "0.63106793", "0.6298626", "0.62920123", "0.62865424", "0.6283876", "0.6273005" ]
0.8249799
1
Lock the modal to prevent further animation.
function lockModal() { locked = true; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function unlockModal() {\n locked = false;\n }", "function unlockModal() {\n locked = false;\n }", "function lock() {\n $('button').attr(\"disabled\", \"true\");\n }", "function lockActions() {\n $('.modal').find('.actions-container')\n .children().first() // the save/submit button\n .addClass('disabled').prop('disabled', true);\n }", "lock() {\n const that = this;\n\n that.locked = that.unfocusable = true;\n\n if (that.showNearButton || that.showFarButton) {\n return;\n }\n\n that._setFocusable();\n }", "lockEditor() {\n this.lock = true;\n }", "startUnlocking()\n {\n // \"start\" CSS animation\n this.setState({transparent: true});\n // wait until CSS animation end\n Meteor.setTimeout(() => {\n this.unLock();\n }, this.props.transitionDuration);\n }", "loading() {\n this.modal.jQueryModalFade.addClass('modal_fade_trick');\n this.modal.jQueryModalAwait.css('display', 'block');\n this.modal.jQueryModalWindow.css('display', 'none');\n }", "function unlockForEdit() {\n\t$(modalTextTitle).prop(\"disabled\",false);\n\t$(modalTextTitle).css(\"border-bottom\", \"2px solid #7C8487\");\n\n\t$(modalTextareaDescription).prop(\"disabled\",false);\n\t$(modalTextareaDescription).css(\"border-bottom\", \"2px solid #7C8487\");\n\n\t$(modalLabelTitle).hide();\n\t$(modalLabelDescription).hide();\n\t$(modalLimitationLabelTitle).show();\n\t$(modalLimitationLabelDescription).show();\n\n\t$(modalIBedit).hide();\n\t$(modalIBdelete).hide();\n\t$(modalButtonEdit).show();\n}", "function lock(el) {\n\tel.on('click.locked', function() {\n\t\treturn false;\n\t})\n}", "function lockForm(){\n\t\t\t$scope.isLoading = true;\n\t\t}", "lock() {\n _isLocked.set(this, true);\n }", "function lockUI() {\n Dom.$uiLocker.css( 'display', 'block' );\n }", "function attShowModal() {\n setShowModal(!showModal);\n }", "function disablePopUp() {\n setModalValue(!showModal); // toggling value of showModal and setting it in the state\n }", "unLock()\n {\n this.setState({shown: false});\n }", "lock() {\n this.close();\n this.isLocked = true;\n this.refreshState();\n }", "function modalAnimation() {}", "unlockEditor() {\n this.lock = false;\n }", "function lock() {\n clearAlertBox();\n // Lock the editors\n aceEditor.setReadOnly(true);\n\n // Disable the button and set checkCorrectness to true.\n $(\"#resetCode\").attr(\"disabled\", \"disabled\");\n correctnessChecking = true;\n}", "showLogin() {\n // Show the Lock modal\n this.lock.show();\n }", "unlock() {\n const that = this;\n\n that.locked = that.unfocusable = false;\n that._setFocusable();\n }", "function toggle() {\r\n setModal(!modal)\r\n }", "function showForgetModal() {\r\n $(\"#myModal\").modal(\"show\");\r\n}", "function _lockFunctionality() {\n lockUserActions = true;\n viewModel.set(\"lockUserActions\", lockUserActions);\n}", "_checkModal() {\n // TODO: Global modal\n if (this.parent) {\n if (this.attributes.modal) {\n this.on('render', () => this.parent.setState('loading', true));\n this.on('destroy', () => this.parent.setState('loading', false));\n }\n\n this.on('destroy', () => this.parent.focus());\n }\n }", "lock() {\n document.getElementById('instructions').style.display = 'none';\n document.getElementById('blocker').style.display = 'none';\n document.getElementById('draw-canvas').requestPointerLock();\n }", "handleShowModal() {\n this.showSpinner = true;\n this.template.querySelector(\"c-modal-component-template\").show();\n }", "function setModal() {\n $('.overlay').fadeIn('slow');\n $('.modal').slideDown('slow');\n }", "lockEditor() {\n //console.log('LOCK ON');\n this.setState({\n 'lockedEditor': true\n });\n }" ]
[ "0.77020603", "0.77020603", "0.6724566", "0.66888505", "0.6680284", "0.6579386", "0.65182763", "0.6472608", "0.64131486", "0.639402", "0.6376364", "0.6302623", "0.62310976", "0.6218524", "0.619525", "0.6177555", "0.6141152", "0.6130219", "0.61241496", "0.6108205", "0.60983217", "0.60864687", "0.60833776", "0.60650176", "0.60614395", "0.60547864", "0.60475004", "0.6040619", "0.6002221", "0.60016763" ]
0.8878073
1
Animates the modal opening. Handles the modal 'open' event.
function openAnimation() { // // First, determine if we're in the middle of animation. // if ( !locked ) { // // We're not animating, let's lock the modal for animation. // lockModal(); // // Close any opened modals. // closeOpenModals(); // // Now, add the open class to this modal. // modal.addClass( "open" ); // // Are we executing the 'fadeAndPop' animation? // if ( options.animation === "fadeAndPop" ) { // // Yes, we're doing the 'fadeAndPop' animation. // Okay, set the modal css properties. // // // Set the 'top' property to the document scroll minus the calculated top offset. // cssOpts.open.top = $doc.scrollTop() - topOffset; // // Flip the opacity to 0. // cssOpts.open.opacity = 0; // // Set the css options. // modal.css( cssOpts.open ); // // Fade in the background element, at half the speed of the modal element. // So, faster than the modal element. // modalBg.fadeIn( options.animationSpeed / 2 ); // // Let's delay the next animation queue. // We'll wait until the background element is faded in. // modal.delay( options.animationSpeed / 2 ) // // Animate the following css properties. // .animate( { // // Set the 'top' property to the document scroll plus the calculated top measure. // "top": $doc.scrollTop() + topMeasure + 'px', // // Set it to full opacity. // "opacity": 1 }, /* * Fade speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal reveal:opened event. // This should trigger the functions set in the options.opened property. // modal.trigger( 'reveal:opened' ); }); // end of animate. } // end if 'fadeAndPop' // // Are executing the 'fade' animation? // if ( options.animation === "fade" ) { // // Yes, were executing 'fade'. // Okay, let's set the modal properties. // cssOpts.open.top = $doc.scrollTop() + topMeasure; // // Flip the opacity to 0. // cssOpts.open.opacity = 0; // // Set the css options. // modal.css( cssOpts.open ); // // Fade in the modal background at half the speed of the modal. // So, faster than modal. // modalBg.fadeIn( options.animationSpeed / 2 ); // // Delay the modal animation. // Wait till the modal background is done animating. // modal.delay( options.animationSpeed / 2 ) // // Now animate the modal. // .animate( { // // Set to full opacity. // "opacity": 1 }, /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal reveal:opened event. // This should trigger the functions set in the options.opened property. // modal.trigger( 'reveal:opened' ); }); } // end if 'fade' // // Are we not animating? // if ( options.animation === "none" ) { // // We're not animating. // Okay, let's set the modal css properties. // // // Set the top property. // cssOpts.open.top = $doc.scrollTop() + topMeasure; // // Set the opacity property to full opacity, since we're not fading (animating). // cssOpts.open.opacity = 1; // // Set the css property. // modal.css( cssOpts.open ); // // Show the modal Background. // modalBg.css( { "display": "block" } ); // // Trigger the modal opened event. // modal.trigger( 'reveal:opened' ); } // end if animating 'none' }// end if !locked }// end openAnimation
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "open() {\n this.modal.jQueryModalFade.addClass('modal_fade_trick');\n this.modal.jQueryModalWindow.css('display', 'block');\n this.jQueryName.focus();\n }", "function modalAnimation() {}", "modalOpen(){\n\t\tthis.setState({modalAppear: true})\n\t}", "function openModal() {\n setOpen(true);\n }", "openModal() {\n\t\tthis.setState({\n\t\t\tisModalOpen: true\n\t\t});\n\t}", "function openModal() {\n modal.fadeIn();\n}", "function showModal() {\n debug('showModal');\n if (!modal.ready) {\n initModal();\n modal.anim = true;\n currentSettings.showBackground(modal, currentSettings, endBackground);\n } else {\n modal.anim = true;\n modal.transition = true;\n currentSettings.showTransition(modal, currentSettings, function(){endHideContent();modal.anim=false;showContentOrLoading();});\n }\n }", "displayModal() {\n $(\"#modal-sliding\").openModal();\n }", "function showModal() {\r\n\t\tdebug('showModal');\r\n\t\tif (!modal.ready) {\r\n\t\t\tinitModal();\r\n\t\t\tmodal.anim = true;\r\n\t\t\tcurrentSettings.showBackground(modal, currentSettings, endBackground);\r\n\t\t} else {\r\n\t\t\tmodal.anim = true;\r\n\t\t\tmodal.transition = true;\r\n\t\t\tcurrentSettings.showTransition(modal, currentSettings, function(){endHideContent();modal.anim=false;showContentOrLoading();});\r\n\t\t}\r\n\t}", "function openModal() {\n setIsOpen(true);\n }", "function openModal() {\n setIsModalOpen((isModalOpen) => !isModalOpen);\n }", "function setModal() {\n $('.overlay').fadeIn('slow');\n $('.modal').slideDown('slow');\n }", "function openModal () {\n modal.style.display = 'block';\n }", "function openModal () {\n setVisablity(true)\n }", "function openModal(modalToOpen) {\n //$(\".modal\").css(\"marginTop\", \"0\");\n $(modalToOpen).css(\"marginLeft\", ($(window).width() - $(modalToOpen).width())/2);\n $(modalToOpen+\"-bg\").fadeIn();\n $(modalToOpen).fadeIn();\n}", "function openModal() { \n modal.style.display = 'block';\n }", "function openModal() {\n modal.style.display = 'block';\n }", "function openModal() {\n modal.style.display = 'block';\n }", "handleOpenModal() { this.setState({ showModal: true }); }", "handleOpenModal () { this.setState({ showModal: true }) }", "handleModalOpen() {\n this.setState({ open: true });\n }", "function openModal(e) {\n\tmodal.style.display = 'block'\n}", "function openModal () {\n\t\tmodalMoves.innerHTML = moves;\n\t\tmodalSecs.innerHTML = pad(totalTime%60);\n\t\tmodalMins.innerHTML = pad(parseInt(totalTime/60));\n\t\tmodal.style.display = 'block';\n}", "function modalOpen() {\n modal.style.display = 'block';\n}", "openModal() {\n this.setState({\n modalOpen: true\n });\n }", "open() {\n this.visible = true;\n console.log(\"Modal opened\");\n }", "function onShowBsModal() {\n isModalInTransitionToShow = true;\n isModalVisible = true;\n }", "function openModal(){\r\n modal.style.display = 'block';\r\n }", "function open() {\n // Show the modal and overlay\n modal.style.display = 'block';\n modalOverlay.style.display = 'block';\n}", "function openModal() {\n modal.classList.add(\"is-active\");\n }" ]
[ "0.72274184", "0.71450293", "0.7141732", "0.7109374", "0.7081208", "0.70157766", "0.6918489", "0.68839055", "0.6869721", "0.68123823", "0.67818654", "0.67528653", "0.67508465", "0.6713749", "0.6665212", "0.6662611", "0.6645355", "0.6645355", "0.6643038", "0.66234994", "0.66217816", "0.6583968", "0.6550459", "0.65475696", "0.6534219", "0.65304744", "0.65147305", "0.6514214", "0.64682424", "0.64658165" ]
0.7665859
1
Converts JSON to HTML table
function convertToTable(json){ var table = '<table>'; for (x in json){ table += '<tr>'; for (y in json[x]){ table = table + '<td>' + json[x][y] + '</td>'; } table += '</tr>'; } table += '</table>'; return table; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function makeTable(json) {\n var obj = JSON.parse(json),\n table = $(\"<table>\"),\n row, value, i;\n\n for (i = 0; i < obj.rows.length; i++) {\n row = $(\"<tr>\");\n row.append(\"<td>\" + obj.rows[i].key + \"</td>\");\n value = obj.rows[i].value;\n if (value instanceof Array) {\n value.forEach(function (element) {\n row.append(\"<td>\" + element + \"</td>\"); \n });\n }\n else {\n row.append(\"<td>\" + value + \"</td>\"); \n }\n table.append(row); \n }\n\n return table;\n }", "function JSONToHTML(json) {\n let html=\"<table>\\n\";\n let arr=JSON.parse(json);\n html+=\" <tr>\";\n for(let key of Object.keys(arr[0])) {\n html+='<th>${htmlEscape(key)}</th>>';\n }\n html+='</tr>\\n';\n\n for(let obj of arr) {\n for(let keys of Object.keys(arr[0])) {\n html += '<td>${htmlEscape(obj[keys])}</td>'\n }\n } html+='</tr>\\n';\n return html+\"</table>\";\n function htmlEscape(text) {\n return text\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");}\n\n\n}", "function createTable(json){\n var table = document.getElementById('user-results')\n\n for (var i = 0; i < json.data.length; i++){\n var row = `<tr>\n <td>${json.data[i].first_name}</td>\n <td>${json.data[i].last_name}</td>\n <td>${json.data[i].email}</td>\n </tr>`\n table.innerHTML += row\n\n\n }\n}", "function makeTableFromJSON() {\n\tvar div = document.getElementById('table');\n\tmakeTableStyle(div);\n\t\n\tif(div)\n\t{\n\t\tdiv.innerHTML = \"\";\n\t}\n\tvar displayTable = \"<table id='dataTable' class='table table-striped table-bordered' cellspacing='0' width='100%'><thead><tr>\";\n\tvar data = JSON.parse(datasetToDisplay);\n\tvar headers = [];\n\tfor (var key in data[0]) {\n\t\talert(key);\n\t\tdisplayTable+= \"<th>\" +key+ \"</th>\";\n\t\theaders.push(key);\n\t}\n\tdisplayTable+= \"</tr></thead>\";\n\tdisplayTable+= \"<tbody>\";\n\t\n\t\n\tfor (var i = 1; i < data.length; i++) {\n\t\tdisplayTable+= \"<tr>\";\n\t\tfor(var j=0;j<headers.length;j++){\n\t\tdisplayTable+= \"<td>\" +data[i].headers[j]+\" </td>\";\n\t\t}\n\t\tdisplayTable+=\"</tr>\"\n\t}\n\t\n\tdisplayTable+=\"</table>\";\n\tvar Columns = makeColumnHeaderForTable(colData);\n\tmakeFilterElements();\n makeObjects(colData);\n\t\t\t\n\n\t\n\tdiv.innerHTML = displayTable;\n\t\n\t\t\t$('#dataTable').DataTable({\n\t\t\t\t\"paging\": true,\n\t\t\t\t\"ordering\": true,\n\t\t\t\t\"info\": false,\n\t\t\t\t\"lengthMenu\": [[10, 25, 50, -1], [10, 25, 50, \"All\"]]\n\t\t\t\t\n\t\t\t});\n}", "function displayJsonToHtmlTable(jsonData) {\n var table = document.getElementById(\"display_csv_data\");\n if (jsonData.length > 0) {\n var headers = Object.keys(jsonData[0]);\n var htmlHeader = \"<thead><tr>\";\n\n for (var i = 0; i < headers.length; i++) {\n htmlHeader += \"<th>\" + headers[i] + \"</th>\";\n }\n htmlHeader += \"<tr></thead>\";\n\n var htmlBody = \"<tbody>\";\n for (var i = 0; i < jsonData.length; i++) {\n var row = jsonData[i];\n htmlBody += \"<tr>\";\n for (var j = 0; j < headers.length; j++) {\n var key = headers[j];\n htmlBody += \"<td>\" + row[key] + \"</td>\";\n }\n htmlBody += \"</tr>\";\n }\n htmlBody += \"</tbody>\";\n table.innerHTML = htmlHeader + htmlBody;\n } else {\n table.innerHTML = \"There is no data in CSV\";\n }\n}", "function ConvertJsonToTable(jsonData, keys, containerId, tableClassName) {\n //Patterns for table thead & tbody\n var tbl = \"<table border='1' cellpadding='1' cellspacing='1' id='\" + containerId + \"' class='\" + tableClassName + \"'>{0}{1}</table>\";\n var th = \"<thead>{0}</thead>\";\n var tb = \"<tbody>{0}</tbody>\";\n var tr = '<tr class=\"{0}\">{1}</tr>';\n var thRow = \"<th>{0}</th>\";\n var tdRow = '<td>{0}</td>';\n var thCon = \"\";\n var tbCon = \"\";\n var trCon = \"\";\n\n function getRowClass(isOdd) {\n return isOdd ? 'odd' : 'even';\n }\n\n if (keys && jsonData) {\n\n //Creating all table headers\n if(isArray(keys)) {\n for (i = 0; i < keys.length; i++) {\n thCon += thRow.format(keys[i]);\n }\n } else {\n for(var key in keys) {\n if(keys.hasOwnProperty(key)) {\n if(keys[key].hasOwnProperty('name')) {\n thCon += thRow.format(keys[key].name);\n } else {\n thCon += thRow.format(keys[key]);\n }\n }\n }\n }\n\n th = th.format(tr.format('header', thCon));\n\n //Creating all table rows from Json data\n if (typeof(jsonData[0]) == \"object\") {\n var isOdd = false;\n for (i = 0; i < jsonData.length; i++) {\n if(isArray(keys)) {\n for (j = 0; j < keys.length; j++) {\n tbCon += tdRow.format(jsonData[i][keys[j]]);\n }\n } else {\n for(var key in keys) {\n if(keys.hasOwnProperty(key)) {\n if(keys[key].hasOwnProperty('onRender')) {\n tbCon += tdRow.format(keys[key].onRender(jsonData[i][key]));\n } else {\n tbCon += tdRow.format(jsonData[i][key]);\n }\n }\n }\n }\n trCon += tr.format(getRowClass(isOdd), tbCon);\n tbCon = \"\";\n isOdd = !isOdd;\n }\n }\n tb = tb.format(trCon);\n\n tbl = tbl.format(th, tb);\n return tbl;\n }\n\n return null;\n}", "function scoreToHTML(json) {\n let html = '<table>\\n';\n html += ' <tr><th>name</th><th>score</th></tr>\\n';\n\n let scores = JSON.parse(json);\n\n for (let score of scores) {\n html += ' <tr>';\n html += `<td>${score.name}</td>`;\n html += `<td>${score.score}</td>`;\n\n html += '</tr>\\n';\n }\n\n html += '</table>';\n console.log(html);\n}", "function data_to_table(object) {\n var row = tbody.append(\"tr\");\n Object.values(object).forEach(function(value) {\n row.append(\"td\").text(value)\n })\n}", "function renderTable(data) {\n var tHead = \"\";\n var tBody = \"\";\n var header = true;\n\n // adds data to array\n if (!Array.isArray(data)) {\n var dataTmp = data;\n data = [dataTmp];\n }\n\n // iterate through json objects in array\n for (var index in data) {\n tBody += \"<tr>\";\n // iterate through values in json object\n for (var key in data[index]) {\n // adds table header from key values\n if (header) tHead += \"<th>\" + key + \"</th>\";\n tBody += \"<td id = '\" + index + \"'>\" + data[index][key] + \"</td>\";\n }\n // stops adding table headers\n header = false;\n tBody += \"</tr>\";\n }\n tableHead.innerHTML = tHead;\n tableBody.innerHTML = tBody;\n}", "function makeTableFromJSON(json_obj) {\n // grab the table display element and set up for the table\n var table_display = document.getElementById('dynamic_table');\n var table = document.createElement('table');\n var table_body = table.createTBody();\n var table_header = table.createTHead();\n\n // cleaning the old table is part of setup\n while(table_display.firstChild) {\n table_display.removeChild(table_display.firstChild);\n }\n\n // get the number of rows and columns we have\n var rows = json_obj.length;\n if (rows < 1) {\n alert('Retrieved an empty JSON object! :(');\n }\n var cols = Object.keys(json_obj[0]).length;\n // console.log('DEBUG -> ROWS: ' + rows + ', COLS: ' + cols);\n\n // start some variables outside the loops and reuse them\n var table_row = table_header.insertRow(0); \n var table_col;\n var json_keys = Object.keys(json_obj[0]);\n // console.log(json_keys);\n\n // build the header row\n var i = 0;\n json_keys.forEach(function(key) {\n table_col = table_row.insertCell(i);\n table_col.innerHTML = '<b>' + key + '</b>';\n i++;\n })\n \n for (var i=0; i<rows; i++) {\n table_row = table_body.insertRow(i);\n for (var j=0; j<cols; j++) {\n table_col = table_row.insertCell(j);\n table_col.innerHTML = json_obj[i][json_keys[j]];\n }\n }\n\n table_display.appendChild(table);\n}", "function buildTable(data){\n \n tbody.html(\"\");\n\n data.forEach((element) => {\n var row = tbody.append(\"tr\");\n Object.entries(element).forEach(([key,value]) => {\n row.append(\"td\").text(value);\n })\n });\n\n}", "function createTable(jsonObject) {\n let tableArray =[]; //empty array to start\n jsonObject.degrees.forEach(function(property){ //iterate through json object (which is called degrees)\n tableArray.push( //and push that data into an array\n `<tr>\n <td>${property.School}</td>\n <td>${property.Program}</td>\n <td>${property.Type}</td>\n <td>${property.Year}</td></tr>`); //telling my function to display each key/value pair\n });\n return tableArray; //return the complete table\n}", "function displaytable(data){\n tbody.html(\"\");\n data.forEach(function(Table) {\n console.log(Table);\n var row = tbody.append(\"tr\");\n Object.entries(Table).forEach(function([key, value]) {\n console.log(key, value);\n // Append a cell to the row for each value\n // in the weather report object\n var cell = row.append(\"td\");\n cell.text(value);\n });\n });\n}", "function renderJson(json) {\n\t\ttable.setData([]);\n\t\tvar curheader = '0';\n\t\tvar index = [];\n\t\tvar rows = [];\n\n\t\tfor (var i = 0,\n\t\t j = json.horses.length; i < j; i++) {\n\n\t\t\tvar item1,\n\t\t\t item2;\n\n\t\t\titem1 = json.horses[i].id;\n\t\t\titem2 = json.horses[i].name.toString().trim();\n\n\t\t\tvar row = Ti.UI.createTableViewRow({\n\t\t\t\tid : item1,\n\t\t\t\ttitle : item2\n\t\t\t});\n\n\t\t\tif (item2.substring(0, 1) != curheader) {\n\t\t\t\tcurheader = item2.substring(0, 1);\n\t\t\t\trow.header = curheader;\n\t\t\t\tindex.push({\n\t\t\t\t\tindex : i,\n\t\t\t\t\ttitle : curheader\n\t\t\t\t});\n\t\t\t}\n\t\t\trow.className = 'horseList';\n\t\t\trows.push(row);\n\t\t}\n\n\t\t//Tweak to the table set\n\t\ttable.setData(rows);\n\t\ttable.setIndex(index);\n\t}", "function table(json) {\n var table = json.table,\n\trows = table.length,\n\tcols = table[0].length,\n\trowlabels = json.rowlabels,\n\tcollabels = json.collabels,\n\trowperm = reorder.permutation(rows),\n\tcolperm = reorder.permutation(cols);\n\n \n}", "function getTableDataFromJSON() {\n\n }", "function formatJsonString(d){\n var tableFlow = '';\n var taskStringFlow = [];\n var JsonStringFlow = $.parseJSON(d);\n for(var n in JsonStringFlow){\n taskStringFlow.push(JsonStringFlow[n]);\n }\n\n tableFlow = '<table cellpadding=\"5\" cellspacing=\"0\" border=\"0\" class=\"table table-condensed\" style=\"padding-left:50px; font-size:13px;\">';\n\n for(var i in taskStringFlow){\n tableFlow += '<tr style=\"border:none !important;\">'+\n '<td style=\"border:none !important;\">'+taskStringFlow[i].name+'</td>'+\n '<td style=\"border:none !important;\"><img src=\"'+taskStringFlow[i].image+'\" class=\"img img-responsive\" style=\"width:10%;\" /></td>'+\n '<td style=\"border:none !important;\">'+taskStringFlow[i].qty+'</td>'+\n '<td style=\"border:none !important;\">'+taskStringFlow[i].price+'</td>'+\n '<td style=\"border:none !important;\">'+parseInt(taskStringFlow[i].qty) * parseInt(taskStringFlow[i].price)+'</td>'+\n '</tr>'\n }\n tableFlow += '</table>';\n return tableFlow;\n}", "function buildTable(data){\n tbody.html(\"\");\n data.forEach(function(ufoData) {\n console.log(ufoData);\n var row = tbody.append(\"tr\");\n Object.entries(ufoData).forEach(function([key, value]) {\n // Append a cell to the row for each value\n var cell = row.append(\"td\");\n cell.text(value);\n });\n })\n}", "function buildTable(data){\n tbody.html(\"\");\n data.forEach(function(ufoData) {\n console.log(ufoData);\n var row = tbody.append(\"tr\");\n Object.entries(ufoData).forEach(function([key, value]) {\n // Append a cell to the row for each value\n var cell = row.append(\"td\");\n cell.text(value);\n });\n })\n}", "function create_table(data){\n data.forEach(function(d){\n\n //create row\n var row = tbody.append(\"tr\");\n \n //unpack each row element into table\n Object.entries(d).forEach(function([key,value]){\n //append a cell to the row for each value\n var cell = tbody.append(\"td\");\n //set cell value\n cell.text(value);\n });\n \n });\n}", "function view(json) {\n var targetElement = $(config.elements.data);\n targetElement.html(makeTable(json));\n }", "function display(json) {\n //create a html string\n html = '<table cellspacing =5 cellpadding=5 >';\n\t\n \n\t// for each object in json\n for(var i in json) {\n\t \n\t\t//html += '<th>Path'\n\t\thtml += '<b>****Path ****</b>'\n\t\t//html += j\n\t\thtml += ''\n\t\t//html += '</th>'\n\t\titem = json[i];\n\t\thtml += '<br/>'\n\t\tfor (k in item) {\n\t\t// item2 = item[j];\n\t\t \n\t\t html += item[k]\n\t\t html += '<br/>'\n\t\t \n\t\t }\n\t\t html += '<p/>'\n // html += toRow(item);\n\t //}\n\t\t\n }\n html += '</table>';\n\t//add it to the 'search-results' div\n $('#search-results').html(html);\n}", "function createTable(data) {\n // Parse the json string into the object\n data_obj = JSON.parse(data);\n\n document.getElementById(\"table_container\").innerHTML = '';\n\n // Creation of the table\n var table = document.createElement(\"table\"), rowH, headerA,\n headerB, row, cellA, cellB;\n\n rowH = document.createElement(\"tr\");\n headerA = document.createElement(\"th\");\n headerB = document.createElement(\"th\");\n\n headerA.innerHTML = \"nome\";\n headerB.innerHTML = \"data\";\n\n table.appendChild(rowH);\n rowH.appendChild(headerA);\n rowH.appendChild(headerB);\n\n // Append the table inside parent container\n document.getElementById(\"table_container\").appendChild(table);\n\n for (let key in data_obj) {\n // Create rows and cells with For loop\n row = document.createElement(\"tr\");\n cellA = document.createElement(\"td\");\n cellB = document.createElement(\"td\");\n\n dataTime = new Date(data_obj[key].data);\n\n // Fill with data\n cellA.innerHTML = data_obj[key].nome;\n // Setting european format date\n cellB.innerHTML = dataTime.toLocaleDateString();\n\n // Append rows and cells\n table.appendChild(row);\n row.appendChild(cellA);\n row.appendChild(cellB);\n }\n}", "function displayData(data){ \n tbody.text(\"\")\n data.forEach(function(sighting){\n new_tr = tbody.append(\"tr\")\n Object.entries(sighting).forEach(function([key, value]){\n new_td = new_tr.append(\"td\").text(value)\t\n })\n})}", "function buildTable(table){\n\n // loop through data\n table.forEach((item) => {\n\n // append rows\n let row = tbody.append(\"tr\");\n\n // iterate through keys and values\n Object.entries(item).forEach(([key, value]) => {\n\n // append cells \n let cell = row.append(\"td\");\n\n // add text value to each cell\n cell.text(value);\n });\n });\n}", "function structureJSON(){\n \n $('#result_wrapper').remove();\n $('body').append('<table id=\"result\" class=\"width100\"><table/>');\n \n // Convert text into JSON\n data = JSON.parse($('#input').val());\n \n // If data has been parsed correctly and it is an array\n if (data && typeof(data) == 'object' ){\n \n parseToTable(data, function(aaData, aoColumns){\n \n // Create table\n $('#result').dataTable({\n\t\"aaData\" : aaData,\n\t\"aoColumns\" : aoColumns,\n\t\"bLengthChange\": true,\n\t\"bDestroy\": true\n });\n \n });\n }\n}", "function jsonToHTML (data) {\n \n var html;\n \n \n \n return html;\n}", "function data2table(data) {\r\n let keys = Object.keys(data[0]);\r\n let html = '<p>Age breakdown for the population of output area ' + data[0]['GEOGRAPHY_CODE'] + ' in ' + data[0]['DATE_NAME'] + '.</p>';\r\n html += '<table class=\"table table-sm\">';\r\n html += '<thead><tr><th scope=\"col\">Age group</th><th scope=\"col\">%</th></tr></thead><tbody>'\r\n for (object in data) {\r\n html += '<tr>';\r\n html += '<td>' + data[object][keys[2]] + '</td>';\r\n html += '<td><img src=\"./img/pixel.png\" style=\"height: 18px; width: ' + (data[object][keys[3]] * 4) + 'px;\"> ' + data[object][keys[3]] + '%</td>';\r\n html += '</tr>';\r\n }\r\n html += '</tbody></table>';\r\n results.innerHTML = html;\r\n}", "function renderTsStatTable(data) {\n html = \"<table><tbody>\";\n /* identify rownames to put in first columns */\n var rownames = [];\n for ( var rowname in data ) {\n if (data.hasOwnProperty(rowname)) {\n rownames.push(rowname);\n }\n }\n /* build up table row by row */\n var colnames = [];\n rownames.forEach(function(rowname) {\n if (colnames.length == 0) {\n /* only true for first row, build header */\n Object.keys(data[rowname]).forEach(function(colname) {\n colnames.push(colname)\n });\n html += \"<tr><th>\" + \"key</th><th>\" + colnames.join(\"</th><th>\") + \"</th></tr>\";\n }\n /* build value rows */\n var values = [rowname, ];\n colnames.forEach(function(colname) {\n values.push(data[rowname][colname])\n });\n html += \"<tr><td>\" + values.join(\"</td><td>\") + \"</td></tr>\";\n });\n return html + \"<tbody></table>\";\n}", "function buildList(json) {\n var html = '<table><thead>' + buildHeader(json[0]) + '</thead><tbody>';\n\n for (var i = 0; i < json.length; i++) {\n html += buildRow(json[i], null, (i % 2 == 1));\n }\n html += '</tbody></table>';\n\n return html;\n}" ]
[ "0.8157815", "0.794002", "0.72810906", "0.72794", "0.72413075", "0.72397435", "0.7226649", "0.7022742", "0.7007057", "0.699789", "0.6955359", "0.6935765", "0.681017", "0.6798629", "0.67899024", "0.67751575", "0.67607105", "0.6730741", "0.6730741", "0.6716402", "0.66984075", "0.6696851", "0.66805327", "0.66435164", "0.66335255", "0.6630139", "0.66133595", "0.65897524", "0.65738565", "0.6555808" ]
0.80924743
1
rewrite log4js configuration file by replacing relative paths to absolute
function correcting(log_file) { console.log("Logger: opening log-conf file: " + log_file); var log = fs.readFileSync(log_file, 'utf8'); var d = false; var json = JSON.parse(log, function(key, value) { if (key == 'filename') { var dirname = utils.dirname(value); var basename = value.replace(dirname, ''); var file = utils.search_file(dirname); file = path.join(file, basename) if (file != value) { value = file; d = true; } } return value; }); if (d) { var logFileCorrect = log_file + ".new"; console.log("Logger: write corrections to " + logFileCorrect); fs.writeFileSync(logFileCorrect, JSON.stringify(json, null, 2)); return logFileCorrect; } else { console.log("Logger: Config-file - There is nothing to correct!!!"); } return log_file; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_loadFileConfig() {\n try {\n let lines = fs.readFileSync(this._LOGLOVE_CONFIG).toString().split('\\n');\n for (let line of lines) {\n let levelPattern = line.split('=');\n this._setLevelAndPatterns(levelPattern[0], levelPattern[1]);\n }\n } catch (err) {\n // console.log('_loadFileConfig', err);\n }\n }", "function rewriteLocations (root, config) {\n config.packages = R.map(function (pkg) {\n pkg.location = path.relative(root, pkg.location)\n return pkg\n }, config.packages)\n return config\n}", "function configLogger(module) {\n\tvar errorModule = 'error-'+module;\n\tvar allModule = 'all-'+module;\n\tlog4js.loadAppender('file');\n\tlog4js.addAppender(log4js.appenders.file('logs/all-'+module+'.log'), allModule);\n\tlog4js.addAppender(log4js.appenders.file('logs/error-'+module+'.log'), errorModule);\n\tvar errorlogger = log4js.getLogger(errorModule);\n\tvar alllogger = log4js.getLogger(allModule);\n\terrorlogger.setLevel('INFO');\n\talllogger.setLevel('ERROR');\n\tmoduleLoggers[module] = {};\n\tmoduleLoggers[module]['em'] = errorlogger;\n\tmoduleLoggers[module]['am'] = alllogger;\n}", "setFileStream() {\n // e.g.: https://my-domain.com --> http__my_domain_com\n let sanitizedDomain = this.domain.replace(/[^\\w]/gi, '_');\n\n // CASE: target log folder does not exist, show warning\n if (!fs.pathExistsSync(this.path)) {\n this.error('Target log folder does not exist: ' + this.path);\n return;\n }\n\n this.streams['file-errors'] = {\n name: 'file',\n log: bunyan.createLogger({\n name: 'Log',\n streams: [{\n path: `${this.path}${sanitizedDomain}_${this.env}.error.log`,\n level: 'error',\n }],\n serializers: this.serializers,\n })\n };\n\n this.streams['file-all'] = {\n name: 'file',\n log: bunyan.createLogger({\n name: 'Log',\n streams: [{\n path: `${this.path}${sanitizedDomain}_${this.env}.log`,\n level: this.level,\n }],\n serializers: this.serializers,\n }),\n };\n\n if (this.rotation.enabled) {\n this.streams['rotation-errors'] = {\n name: 'rotation-errors',\n log: bunyan.createLogger({\n name: 'Log',\n streams: [{\n type: 'rotation-file',\n path: `${this.path}${sanitizedDomain}_${this.env}.error.log`,\n period: this.rotation.period,\n count: this.rotation.count,\n level: 'error',\n }],\n serializers: this.serializers,\n }),\n };\n\n this.streams['rotation-all'] = {\n name: 'rotation-all',\n log: bunyan.createLogger({\n name: 'Log',\n streams: [{\n type: 'rotation-file',\n path: `${this.path}${sanitizedDomain}_${this.env}.log`,\n period: this.rotation.period,\n count: this.rotation.count,\n level: this.level,\n }],\n serializers: this.serializers,\n }),\n };\n }\n }", "function postProcessCfg(cfg) {\n // fix missed fields;\n if (cfg.publicPath) {\n if (!cfg.publicPath.endsWith('/')) {\n cfg.publicPath += '/';\n }\n } else {\n cfg.publicPath = '';\n }\n\n if (!cfg.outDir) {\n cfg.out_dir = 'build';\n }\n cfg.outDir = path.resolve(__dirname, cfg.outDir);\n\n if (!cfg.srcDir) {\n cfg.src_dir = 'src';\n }\n cfg.srcDir = path.resolve(__dirname, cfg.srcDir);\n\n if (cfg.entry && !cfg.entry.startsWith('./')) {\n cfg.entry = `./${cfg.entry}`;\n }\n\n if (cfg.alias) {\n Object.entries(cfg.alias).forEach(([K, v]) => {\n cfg.alias[K] = path.resolve(cfg.srcDir, v);\n });\n }\n}", "function updateWebjarPaths(config) {\n\tfor (var i = 0; i < config.files.length; i++){\n\t\tconfig.files[i] = config.files[i].replace(\n\t\t\t\t'http://localhost:8080/maven-karma-webjars-example/webjars', \n\t\t\t\t'target/dependency/META-INF/resources/webjars');\n\t}\n}", "function rewriteConfiguration(config) {\n const homeDir = app.getPath('home')\n const qianDir = path.join(homeDir, '.qian')\n const qianFile = path.join(qianDir, 'profil.json')\n if (!fs.existsSync(qianDir)) {\n fs.mkdirSync(qianDir);\n }\n fs.writeFileSync(qianFile, JSON.stringify(config))\n}", "function fixSrcPath(fixRequire){\n return es.map(function(file, cb){\n file.path = file.path.replace(/^.*\\\\Studio\\\\/, file.cwd + \"\\\\\");\n file.base = file.cwd + \"\\\\src\\\\\";\n\n if(fixRequire){\n file.contents = new Buffer(file.contents.toString().replace(/\\..\\/..\\/..\\/..\\/DataFactory\\/src\\//g, DATA_FACTORY_PATH));\n }\n\n cb(null, file);\n });\n}", "function absolutePathResolver () {\n return {\n name: 'absolute-path-resolver', // this name will show up in warnings and errors\n resolveId (importee, importer) {\n if (importer && importer.includes('commonjs-proxy:') === false) {\n if (path.isAbsolute(importee)) {\n const newImportee = `${global.cwd}${importee}`; // importee should already have a leading slash\n console.log(`Rewrote ${chalk.blue(importee)} to ${chalk.blue(newImportee)} in ${chalk.cyan(importer)}`);\n return newImportee;\n }\n }\n\n return null; // other ids should be handled as usually\n },\n };\n}", "function normalize (actual) {\n const dir = path.join(__dirname, '..', '..', '..');\n const reDir = new RegExp(dir.replace(reEscape, '\\\\$1'), 'g');\n const reSep = new RegExp(path.sep.replace(reEscape, '\\\\$1'), 'g');\n\n return actual\n .replace(reDir, '/qunit')\n // Replace backslashes (\\) in stack traces on Windows to POSIX\n .replace(reSep, '/')\n // Convert \"at processModule (/qunit/qunit/qunit.js:1:2)\" to \"at qunit.js\"\n // Convert \"at /qunit/qunit/qunit.js:1:2\" to \"at qunit.js\"\n .replace(/^(\\s+at ).*\\/qunit\\/qunit\\/qunit\\.js.*$/gm, '$1qunit.js')\n // Strip inferred names for anonymous test closures (as Node 10 did),\n // to match the output of Node 12+.\n // Convert \"at QUnit.done (/qunit/test/foo.js:1:2)\" to \"at /qunit/test/foo.js:1:2\"\n .replace(/\\b(at )\\S+ \\((\\/qunit\\/test\\/[^:]+:\\d+:\\d+)\\)/g, '$1$2')\n // Convert sourcemap'ed traces from Node 14 and earlier to the\n // standard format used by Node 15+.\n // https://github.com/nodejs/node/commit/15804e0b3f\n // https://github.com/nodejs/node/pull/37252\n // Convert \"at foo (/min.js:1)\\n -> /src.js:2\" to \"at foo (/src.js:2)\"\n .replace(/\\b(at [^(]+\\s\\()[^)]+(\\))\\n\\s+-> ([^\\n]+)/g, '$1$3$2')\n // CJS-style internal traces:\n // Convert \"at load (internal/modules/cjs/loader.js:7)\" to \"at internal\"\n //\n // ESM-style internal traces from Node 14+:\n // Convert \"at wrap (node:internal/modules/cjs/loader:1)\" to \"at internal\"\n .replace(/^(\\s+at ).+\\([^/)][^)]*\\)$/gm, '$1internal')\n\n // Convert /bin/qunit and /src/cli to internal as well\n // Because there are differences between Node 10 and Node 12 in terms\n // of how much back and forth occurs, so by mapping both to internal\n // we can flatten and normalize across.\n .replace(/^(\\s+at ).*\\/qunit\\/bin\\/qunit\\.js.*$/gm, '$1internal')\n .replace(/^(\\s+at ).*\\/qunit\\/src\\/cli\\/.*$/gm, '$1internal')\n\n // Strip frames from indirect nyc dependencies that are specific\n // to code coverage jobs:\n // Convert \"at load (/qunit/node_modules/append-transform/index.js:6\" to \"at internal\"\n .replace(/ {2}at .+\\/.*node_modules\\/append-transform\\/.*\\)/g, ' at internal')\n // Consolidate subsequent qunit.js frames\n .replace(/^(\\s+at qunit\\.js$)(\\n\\s+at qunit\\.js$)+/gm, '$1')\n // Consolidate subsequent internal frames\n .replace(/^(\\s+at internal$)(\\n\\s+at internal$)+/gm, '$1');\n}", "function replaceFirebaseHost(proxyDir, options){\n var optionsReplacer = {\n files: proxyDir + '/edge.json',\n from: /\"host\"[ ]*:[ ]*\".*\"/g,\n to: '\"host\" : \"' + options.firebaseHost + '\"',\n };\n\n try {\n const changes = replace.sync(optionsReplacer);\n console.log('Modified files:', changes.join(', '));\n }\n catch (error) {\n console.error('Error occurred trying to update the firebase host.');\n //console.error('Error occurred trying to update the firebase host:', error);\n }\n}", "extend(config, ctx) {\n // Run ESLint on save\n if (ctx.isDev && ctx.isClient) {\n config.module.rules.push(\n {\n enforce: 'pre',\n test: /\\.(js|vue)$/,\n loader: 'eslint-loader',\n exclude: /(node_modules)/,\n options: {\n fix: true\n }\n },\n {\n test: /\\.ico$/,\n loader: 'uri-loader',\n exclude: /(node_modules)/\n }\n )\n console.log(config.output.publicPath, 'config.output.publicPath')\n // config.output.publicPath = ''\n }\n }", "function pathfix(t, from=\"src=\\\"\", to=\"src=\\\"/\", offset = 0){\n\tt = t.toString();\n\tlet i = t.slice(offset).indexOf(from);\n\tif (i === -1) return t;\n\tlet pre = t.slice(0, i);\n\tlet pos = t.slice(i);\n\n\tif (pos.slice(5, 12) !== \"http://\" && pos.slice(5, 6) !== \"/\") {\n\t\tpos = pos.replace(from, to);\n\t\treturn pre + pathfix(pos, i + 3);\n\t}\n}", "rewriteConfigFiles() {\r\n const approvedPackagesPolicy = this._rushConfiguration.approvedPackagesPolicy;\r\n if (approvedPackagesPolicy.enabled) {\r\n approvedPackagesPolicy.browserApprovedPackages.saveToFile();\r\n approvedPackagesPolicy.nonbrowserApprovedPackages.saveToFile();\r\n }\r\n }", "updateConfigPath(configPath, manual = true) {\n // store the absolute value of project root\n let pawConfig = configPath;\n if (!path.isAbsolute(configPath)) {\n pawConfig = path.resolve(processDir, configPath);\n }\n let pathStats = fs.lstatSync(pawConfig);\n if(!pathStats.isFile()) {\n // eslint-disable-next-line\n console.warn(`WARNING:: Invalid config file path specified ${configPath}, using ${process.env.PAW_CONFIG_PATH} instead`);\n return;\n }\n if (manual) {\n this.pawConfigManualPath = true;\n }\n \n process.env.PAW_CONFIG_PATH = pawConfig;\n \n }", "function getLocalChangelogFilePath(projectDir) {\n return path.join(projectDir, changelogPath);\n}", "function DebugLogPath(){\treturn UserTempDir() + \"\\\\SuperCopyDebug.txt\";}", "function configureLogging() {\n if (!log4js.configured) {\n log4js.configure({\n appenders: [{\n type: 'console',\n layout: {\n type: 'pattern',\n pattern: '[%[%5.5p%]] - %m'\n }\n }]\n })\n logger.setLevel('INFO')\n }\n}", "function fixUrls(cssText, pathname) {\n // hack & slash\n return cssText.replace(URL, \"$1\" + pathname.slice(0, pathname.lastIndexOf(\"/\") + 1) + \"$2\");\n }", "_updateConfig() {\n let template = null;\n let dest = this.destinationPath('server/config/database.js');\n\n if (program.helpers.isRelationalDB(this.answers.database)) {\n template = this.templatePath('config/sql.stub');\n } else if (this.answers.database === 'mongodb') {\n template = this.templatePath('config/mongo.stub');\n }\n\n let configStub = program.helpers.readTpl(this, template, {\n answers: this.answers\n });\n\n let configData = program.helpers.ast(this.read(dest), function (tree) {\n tree.assignment('module.exports').value()\n .key('database').key(this.answers.identifier).value(configStub);\n }.bind(this));\n this.fs.write(dest, configData);\n }", "function LogRotate(config) {\n this.config = config;\n this.logDir = utils.createLogDir(config.workDir);\n if (this.config.type && this.config.type === 'raw') {\n stream.Transform.call(this, {readableObjectMode: true, writableObjectMode: true});\n } else {\n stream.Transform.call(this);\n }\n this.pipe(logRotateStream({\n path: path.resolve(this.logDir, config.path || 'ut5-%Y-%m-%d.log'), // Write logs rotated by the day\n symlink: path.resolve(this.logDir, config.symlink || 'ut5.log'), // Maintain a symlink called ut5.log\n compress: config.compress || false\n }));\n}", "function rstConfiguration(name, file = '') {\n let config = ConfigurationHandler.get(name);\n let str = config ? config.toRst() : '';\n if (file) {\n fs.writeFileSync(file, str);\n }\n return file ? '' : str;\n}", "function toUrl(origPath) {\n let execPath = origPath;\n\n execPath = removeExternal(execPath);\n execPath = removeRootPath(execPath);\n execPath = relativeToHtml(execPath);\n execPath = normalizePath(execPath);\n\n if (execPath !== origPath) {\n log(\"reduce: %s => %s\", origPath, execPath);\n }\n\n const stamp = timestamp(origPath);\n\n log(\"stamp: %s @ %s\", execPath, stamp);\n\n return `${execPath}?v=${stamp}`;\n }", "function _joinAndCanonicalizePath(parts) {\n var path = parts[_ComponentIndex.Path];\n path = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__facade_lang__[\"b\" /* isBlank */])(path) ? '' : _removeDotSegments(path);\n parts[_ComponentIndex.Path] = path;\n return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]);\n}", "function concatUserDefinedConfigFile() {\n var userDefinedConfigFilePath = path.join(exports.homedir, USER_DEFINED_CONFIG_FILE_NAME);\n \n if (!fs.existsSync(userDefinedConfigFilePath)) {\n return;\n }\n\n var userConfig;\n try {\n userConfig = JSON.parse(fs.readFileSync(userDefinedConfigFilePath));\n } catch (err) {\n console.log(\"ERROR: empty or malformed configuration file at '\" + userDefinedConfigFilePath +\n \"'. Config file must be in JSON format.\");\n throw err;\n }\n\n if (!userConfig.pluginDirPaths || userConfig.pluginDirPaths.length === 0) {\n return;\n }\n\n exports.config.pluginDirPaths = exports.config.pluginDirPaths.concat(userConfig.pluginDirPaths);\n exports.config.pluginInterfaceDirPaths = exports.config.pluginInterfaceDirPaths.concat(userConfig.pluginInterfaceDirPaths);\n}", "function _joinAndCanonicalizePath(parts){var path=parts[_ComponentIndex.Path];path=path==null?'':_removeDotSegments(path);parts[_ComponentIndex.Path]=path;return _buildFromEncodedParts(parts[_ComponentIndex.Scheme],parts[_ComponentIndex.UserInfo],parts[_ComponentIndex.Domain],parts[_ComponentIndex.Port],path,parts[_ComponentIndex.QueryData],parts[_ComponentIndex.Fragment]);}", "_configure() {\n super._configure();\n Object.assign(this.path, {\n root: 'dist',\n 'package-a': TargetConfigA.packagePath,\n });\n Object.assign(this, { // dependent on this.path\n });\n }", "function _joinAndCanonicalizePath(parts) {\n\t var path = parts[_ComponentIndex.Path];\n\t path = lang_1.isBlank(path) ? '' : _removeDotSegments(path);\n\t parts[_ComponentIndex.Path] = path;\n\t return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]);\n\t}", "rollup(config) {\n const outputDir = process.cwd() + '/dist/';\n\n const [, inputFilename] = config.input.match(filenameMatcher);\n\n config.plugins = [\n postcss({\n config: {\n path: path.resolve(__dirname, './tools/postcss.config.js'),\n },\n minimize: true,\n modules: true,\n extract: 'styles.css',\n }),\n url(),\n svgr({\n ref: true,\n }),\n ...config.plugins,\n ];\n\n // Manual name changes. Not great...\n if (inputFilename === 'alpha') {\n const outputFile = config.output.file;\n const outputSubDir = `${outputDir}${inputFilename}/`;\n config.output.file = outputFile.replace(outputDir, outputSubDir);\n }\n\n return config;\n }", "function prepareDebuggerPath(...parts) {\r\n return path.join(...parts)\r\n .replace('\\\\', '\\\\\\\\')\r\n .replace('.', '\\\\.');\r\n}" ]
[ "0.54720616", "0.5089851", "0.50360763", "0.5010054", "0.4969121", "0.49680153", "0.4944592", "0.49240178", "0.47732988", "0.47269222", "0.469177", "0.46910536", "0.46713278", "0.46398327", "0.46238816", "0.46063665", "0.45993313", "0.45690107", "0.45314348", "0.4530905", "0.44880036", "0.44619435", "0.44484782", "0.44429225", "0.4432754", "0.4428295", "0.44278616", "0.44254813", "0.4404904", "0.4392894" ]
0.54788125
0
Delete the tasks from a specific team by a date range
function deleteTasksByTeamByRange(options, allTasks, myTasks) { var calls = []; Teams.getTasksRange(options) .then(function (tasks) { if(tasks.length == 0) { $rootScope.notifier.error($rootScope.ui.planboard.noTasksFounded); $rootScope.statusBar.off(); } else if (tasks.error) { $rootScope.notifier.error(result.error); } else { angular.forEach(tasks, function (task) { allTasks = deleteTask(allTasks, task.uuid); myTasks = deleteTask(myTasks, task.uuid); calls.push( TeamUp._ ( 'taskDelete', {second: task.uuid}, task ) ); }); $q.all(calls) .then(function (result) { if (result.error) { console.log('failed to remove task ', task); } else { var group = ($scope.section == 'teams') ? $scope.currentTeam : $scope.currentClientGroup; $scope.getTasks( $scope.section, group, moment($scope.timeline.range.start).valueOf(), moment($scope.timeline.range.end).valueOf() ); $rootScope.notifier.success($rootScope.ui.planboard.tasksDeleted(options)); } $rootScope.statusBar.off(); }); } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "deleteTask(taskId) {\n // Create an empty array and store it in a new variable, newTasks\n const newTasks = [];\n\n // Loop over the tasks\n for (let i = 0; i < this.tasks.length; i++) {\n // Get the current task in the loop\n const task = this.tasks[i];\n\n // Check if the task id is not the task id passed in as a parameter\n if (task.id !== taskId) {\n // Push the task to the newTasks array\n newTasks.push(task);\n }\n }\n\n // Set this.tasks to newTasks\n this.tasks = newTasks;\n }", "function deleteTask(tasks, uuid)\n {\n var i = 0;\n console.error('tasks', tasks);\n\n for (; i < tasks.length; i++)\n {\n if (uuid == tasks[i].uuid)\n {\n tasks.splice(i, 1);\n i--;\n }\n }\n return tasks;\n }", "deleteTask(taskId) {\n\t\tconst todos = this.getAndParse('tasks');\n\t\tconst filteredTodos = todos.filter(task => task.id !== taskId);\n\t\tthis.stringifyAndSet(filteredTodos, 'tasks');\n\t}", "deleteTask(taskId) {\n let newTasks = [];\n this.tasks.forEach(task => {\n if (task.id !== taskId) {\n newTasks.push(task);\n }\n });\n this.tasks = newTasks;\n }", "deleteTask(taskId) {\n const newTasks = [];\n this.tasks.forEach((item) => {\n if (item.Id !== taskId) {\n newTasks.push(item);\n }\n });\n this.tasks = newTasks;\n }", "deleteByTaskId(id, callback) {\n try {\n id = new ObjectID(id)\n } catch (err) {\n callback(null)\n }\n collection.deleteMany({task: id}, callback)\n }", "function deleteTask (e){\n for (var i = 0 ; i< loginUser.tasks.length; i ++){\n if(parseInt(loginUser.tasks[i].id) === parseInt(e.target.getAttribute('data-id'))){\n if(loginUser.tasks[i].status === false){\n taskToDo--;\n $('#countOfTask').text('').text('Task to do: '+ taskToDo);\n }\n loginUser.tasks.splice(i, 1);\n $('#task' + e.target.getAttribute('data-id')).remove();\n collectionOfUser.update(\n {\n id : loginUser.id,\n tasks : loginUser.tasks\n },\n function(user){\n loginUser = user;\n },\n error \n );\n }\n }\n }", "deleteAnyPastReservations(bank, branch) {\r\n //Get current day time\r\n var currentDate = new Date();\r\n var month = currentDate.getMonth() + 1;\r\n var day = currentDate.getDate();\r\n var year = currentDate.getFullYear();\r\n\r\n //Get timeframes referrence\r\n var timeFramesRef = database.getDocumentFromCollection(bank, branch).collection('TimeFrames');\r\n\r\n var yearLookup = 'year';\r\n var monthLookup = 'month';\r\n var dayLookup = 'day';\r\n\r\n //Find old timeframes and write a batch do delete them\r\n timeFramesRef.get().then(function (querySnapshot, docId) {\r\n var batch = database.getBatch();\r\n querySnapshot.forEach(doc => {\r\n\r\n if (!(doc.data()[yearLookup] > year) &&\r\n !(doc.data()[yearLookup] == year &&\r\n doc.data()[monthLookup] > month) &&\r\n !(doc.data()[yearLookup] == year &&\r\n doc.data()[monthLookup] == month &&\r\n doc.data()[dayLookup] >= day)) {\r\n batch.delete(doc.ref);\r\n }\r\n });\r\n return batch.commit();\r\n }).catch(err => {\r\n console.log(err.message);\r\n });\r\n }", "deleteTask(taskId) {\n // Create an empty array and store it in a new variable, newTasks\n const newTasks = [];\n console.log( `taskId: ${taskId}` );\n\n // Loop over the tasks\n for (let i = 0; i < this.tasks.length; i++) {\n // Get the current task in the loop\n const task = this.tasks[i];\n\n // Check if the task id is not the task id passed in as a parameter\n if (task.id !== taskId) {\n // Push the task to the newTasks array\n newTasks.push(task);\n }\n }\n\n // Set this.tasks to newTasks\n this.tasks = newTasks;\n console.log(this.tasks);\n }", "function deleteTask(projectid, taskid) {\n data.projects[projectid].tasks.splice(taskid, 1);\n }", "function deleteTask(currentTask) {\n console.log(\"Delete task\");\n console.log(\"---task to be deleted: \" + currentTask.task);\n\n setTasks(\n tasks.filter((task) => {\n // console.log(\"\")\n return task.id !== currentTask.id;\n })\n );\n }", "function deleteTask(event)\n{\n //gets button id\n let id = event.target.id;\n\n //gets task position from button id\n let taskPosition = id.replace(/\\D/g,'');\n\n //removes task from task array\n taskArr.splice(taskPosition - 1, 1); \n\n //loop through task array to adjust position\n for(let i = 0; i < taskArr.length; i++)\n {\n taskArr[i].position = i + 1;\n };\n\n //rewrites task list\n rewritesList();\n}", "function deleteTasks(taskId){\n $.ajax({\n url: '/tasks/' + taskId,\n type: 'DELETE',\n success: function(response){\n console.log(response);\n getTasks();\n } // end success\n }); //end ajax\n}", "deleteAllTasks () {\r\n this.eliminatedTask.splice(0, this.eliminatedTask.length);\r\n }", "function deleteTask(a,b) {\r\n taskList.splice(a,3)\r\n return taskList;\r\n\r\n }", "'tasks.remove'(taskId) {\n check(taskId, String);\n\n const task = Tasks.findOne(taskId);\n if (task.private && task.owner !== this.userId) {\n // If the task is private, make sure only the owner can delete it\n throw new Meteor.Error('not-authorized');\n }\n\n Tasks.remove(taskId);\n }", "function deleteTasks(){\n\n //loop through task array to remove finished arrays\n for(let i = 0; i < taskArr.length; i++)\n {\n //checks if task is finished\n let isFinished = taskArr[i].finished;\n\n //removes task from task array\n if(isFinished === 1)\n {\n taskArr.splice(i, 1);\n i--;\n };\n \n };\n\n //loop through task array to adjust position\n for(let i = 0; i < taskArr.length; i++)\n {\n taskArr[i].position = i + 1;\n };\n\n //rewrites list with new positions and only unfinished tasks\n rewritesList();\n}", "function deleteTask()\n {\n var child = this.parentNode.parentNode;\n var parent = child.parentNode;\n parent.removeChild(child);\n var id= parent.id;\n var value = child.innerText;\n if (id == \"taskList\")\n {\n obj.taskListArr.splice(obj.taskListArr.indexOf(value), 1);\n }\n else \n {\n obj.taskCompletedArr.splice(obj.taskCompletedArr.indexOf(value), 1);\n } \n dataStorageUpdt();\n }", "static deleteTask(taskId = 0){\n var table_Name = Task.tableName\n const sql = `delete from ${table_Name} WHERE id = ?`\n const params = [taskId]\n console.log(\"Task id \"+taskId)\n return this.repository.databaseLayer.executeSql(sql, params)\n }", "static removeTask(project, task) {\n const qSelector = `#delete-project${project.id}-task${task.id}`\n console.log(qSelector)\n const taskDeleteBtn = document.querySelector(qSelector)\n taskDeleteBtn.addEventListener('click', () => {\n project.removeTask(task);\n DomOutput.loadTaskList(project);\n })\n }", "delete() { all = all.filter(task => task.id !== this.id) }", "removePeriodAndTaskMarker(task){\n let taskElem = task;\n if (taskElem) {\n let taskDays = $('.day[data-task=true]');\n let taskDebut = taskElem.datedebut;\n let taskFin = taskElem.datefin;\n let periodDays = [];\n //On genere un tableau representant la periode de la tache et les cellules concerné\n $.each(taskDays, (i, e) => {\n if ($(e).attr('data-date') >= taskDebut && $(e).attr('data-date') <= taskFin) {\n periodDays.push(e);\n }\n });\n //on verifie si les cellules de la periode on d'autre taches que celle supprimé.\n let emptyDay = periodDays.filter((e) => {\n let date = $(e).attr('data-date');\n let taskPerDay =0;\n $.each(this.tasks, (i, e) => {\n let dateDebut = e.datedebut;\n let dateFin = e.datefin;\n if (date >= dateDebut && date <= dateFin) {\n taskPerDay++\n }\n\n });\n //si aucune date de tache ne correspond a la date de la cellules on la met dans un tableau\n //representant une cellule vide\n if(!taskPerDay)return true;\n });\n //on retire l'attribut;\n $.each(emptyDay,(i,e)=>{\n if($(e).attr('data-task')){\n $(e).removeAttr('data-task');\n }\n });\n $('.period').toggleClass('period');\n }\n }", "'dateDelete'(dateRow){\n let atendences = Atendence.find({date: dateRow._id}).fetch();\n let today = moment().format(\"YYYY-MM-DD\");\n let countDates = Dates.find({date: {$lte: today}, teamId: dateRow.teamId}).fetch();\n countDates = countDates.map((date) => {\n return date._id;\n })\n let count = 0;\n atendences = atendences.map((atendence) => {\n let player = Players.findOne({_id: atendence.player});\n count = Atendence.find({date: {$in: countDates}, player: player._id}).count();\n if((atendence.atend) && (dateRow.date <= today)){\n if((count - 1) > 0){\n playerRelAt = (player.countAtend - 1) / (count - 1) * 100;\n }\n else{\n playerRelAt = 0;\n }\n Players.update({_id: player._id}, {$inc: {\"countAtend\": -1}, $set: {playerRelAt: playerRelAt}});\n }\n else{\n if((count - 1) > 0){\n playerRelAt = (player.countAtend) / (count - 1) * 100;\n }\n else{\n playerRelAt = 0;\n }\n Players.update({_id: player._id}, {$set: {playerRelAt: playerRelAt}});\n }\n });\n Atendence.remove({date: dateRow._id});\n Dates.remove({_id: dateRow._id});\n }", "function deleteTasks() {\n const mutateCursor = getCursorToMutate();\n if (mutateCursor) {\n clickTaskMenu(mutateCursor, 'task-overflow-menu-delete', false);\n } else {\n withUnique(\n openMoreMenu(),\n 'li[data-action-hint=\"multi-select-toolbar-overflow-menu-delete\"]',\n click,\n );\n }\n }", "function tempTaskCheck() {\n var curDate = new Date(); // Initializes date\n var tasksLast = taskList.getLastRow(); // Gets last row of tasks\n var tasks = taskList.getRange(2,5,(tasksLast-1),3).getValues(); // Gets the temp y/n, created, and time to live columns. -1 to account for first row of spreadsheet being populated\n \n for(var i = tasks.length - 1; i >= 0; i--){ // Loops through tasks from the end to the beginning. This is so a row can be deleted without changing position of the rest of the rows compared to the array of tasks\n if(tasks[i][0] == \"Y\"){ // Checks if the task is temp\n // Checks if unix time stamp of right now (should be midnight or close to it if scheduled correctly) is greater than midnight the day the temp task was created, plus the number of days times 86,400, the number of seconds in a day.\n // Dividing by 1000 is used to get seconds as it is initially grabbed in milliseconds \n // Since the created timestamp will be midnight the day it is created, the script adds a day to the time to live so the day created is technically day 1\n if((curDate.getTime()/1000) > ((tasks[i][1].getTime()/1000) + ((tasks[i][2]+1)*86400))){ \n taskList.deleteRow(i+2); // Deletes the position in the array, plus to to account for first row of spreadsheet and arrays starting at 0\n }\n }\n } \n}", "updateAllTasks(){\n const taskField = document.getElementById(\"task-field\")\n let targetTeamId = this.teamId;\n // let teamTasks = Task.all.filter(task => task.teamId === targetTeamId)\n let teamTasks = Task.all.filter(task => task.teamId === targetTeamId).sort(function(a, b){return a.urgency - b.urgency}).sort(function(a, b){return a.dueDate - b.dueDate}).sort(function(a, b){return a.complete - b.complete})\n let taskArr = ''\n // d\n for (const task of teamTasks){\n taskArr += task.createTaskForDom()\n }\n taskField.innerHTML = taskArr;\n document.querySelectorAll(\".complete\").forEach(btn => btn.addEventListener(\"click\", completeStatus));\n document.querySelectorAll(\".delete-tasks\").forEach(btn => btn.addEventListener(\"click\", removeTask));\n }", "deleteFromList(taskID) {\n let deleted = this.taskArr.find(task => task.id == taskID)\n this.taskArr = this.taskArr.filter(value => value != deleted)\n return this.taskArr\n }", "function taskDeletor(idel) {\n\t\tconst currentTask = tasks.find( el => el.id == idel);\n\t\tlet taskIndex = tasks.indexOf(currentTask);\n\t\ttasks.splice(taskIndex, 1);;\n\t}", "function deleteTask(task) {\n var position = toDoList.indexOf(task);\n if (position > -1) {\n return toDoList.splice(position, 1);\n }\n else {\n console.log(\"task is not in our list!\");\n }\n}", "'teamFullRemove'(teamId){\n Atendence.remove({teamId: teamId});\n Dates.remove({teamId: teamId});\n Players.remove({teamId: teamId});\n TrainerTeam.remove({team: teamId});\n Teams.remove({_id: teamId});\n }" ]
[ "0.6183778", "0.6146677", "0.6114453", "0.6088318", "0.6052065", "0.58599496", "0.57875973", "0.5784129", "0.5782057", "0.5766821", "0.571558", "0.571338", "0.5693251", "0.5689389", "0.56837016", "0.56749547", "0.5636516", "0.55587596", "0.5543796", "0.55289215", "0.5527656", "0.55228126", "0.5516992", "0.5507025", "0.55027294", "0.5475447", "0.5465702", "0.54342246", "0.54181826", "0.54159963" ]
0.7921611
0
Returns the unique dates determined by the accompanying comparison function
function uniqueDates(dates, compareFn) { var d = dates.concat(); // n-squared. can probably be better here. (_.union? _.merge?) for (var i = 0; i < d.length; ++i) { for (var j = i + 1; j < d.length; ++j) { if (compareFn(d[i], d[j]) === 0) { // remove the jth element from the array as it can be considered duplicate d.splice(j--, 1); } } } return d; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getSortedUniqueDate(bookings) {\n let uniqueDate = [];\n for (let i = 0; i < bookings.length -1; i++) {\n if(!uniqueDate.includes(bookings[i].date.substring(5,10))){\n uniqueDate.push(bookings[i].date.substring(5,10))\n }\n }\n const sortedUniqueDate= uniqueDate.sort()\n return sortedUniqueDate\n}", "function getAllDates(data){\n\tlet dateArray =[];\n\tdata.forEach(function(element){\n \t\tlet date = element._id.date;\n \t\tif (!dateArray.some(function(ele){\n \t\t\treturn ele ===date;\n \t\t})){\n \t\tdateArray.push(date);\n \t\t}\n\t});\n\treturn dateArray.sort();\n}", "nextPickupDates (intsArr, isRecycling = false) {\n var arr = []\n var date = null\n var isHoliday = false\n _.each(intsArr, (int, index) => {\n date = Schedule.nextDayOfWeek(int)\n isHoliday = Schedule.isHoliday(date, isRecycling)\n arr.push({ date, isHoliday })\n\n while (isHoliday) {\n int = (index + 1 === intsArr.length) ? intsArr[0] : intsArr[index + 1] // jump to next day in intsArr\n date = Schedule.nextDayOfWeek(int, date)\n isHoliday = Schedule.isHoliday(date, isRecycling)\n arr.push({ date, isHoliday })\n }\n })\n return _.chain(arr).sortBy(x => x.date.valueOf()).uniq(x => x.date.valueOf(), true).value()\n }", "function compareDates(date1, date2)\r\n{\r\n if(date1 < date2)\r\n return -1;\r\n else if(date1 > date2)\r\n return 1;\r\n else\r\n return 0;\r\n}", "function getSalesDays() {\n\t\t\treturn new Promise ((resolve, reject)=> {\n\t\t\t\tdb.findMany(Sales, {}, 'date', function(result) {\n\t\t\t\t\tvar uniqueDates = [];\n\t\t\t\t\tvar unique = 1;\n\n\t\t\t\t\tfor (var i=0; i<result.length; i++) {\n\t\t\t\t\t\tvar date = new Date (result[i].date);\n\t\t\t\t\t\tvar unique = 1;\n\t\t\t\t\t\tdate.setHours(0,0,0,0);\n\n\t\t\t\t\t\t//checks if the date is new/unique, -1 means that it's not in the array\n\t\t\t\t\t\tfor (var j=0; j < uniqueDates.length; j++) {\n\t\t\t\t\t\t\tvar arrayDate = new Date (uniqueDates[j]);\n\t\t\t\t\t\t\tarrayDate.setHours(0,0,0,0);\n\t\t\t\t\t\t\t//console.log(\"date: \" + date + \", array date: \" + arrayDate);\n\t\t\t\t\t\t\t//console.log(uniqueDates);\n\t\t\t\t\t\t\tif (!(date > arrayDate || date < arrayDate)) {\n\t\t\t\t\t\t\t\tunique = 0;\n\t\t\t\t\t\t\t\t//console.log(\"not unique\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (unique == 1)\n\t\t\t\t\t\t\tuniqueDates.push(date)\n\n\t\t\t\t\t\t//console.log(uniqueDates);\n\t\t\t\t\t}\n\t\t\t\t\tresolve (uniqueDates)\n\t\t\t\t})\n\t\t\t})\n\t\t}", "function compareDatesWH(date1, date2){\n var comp = DATES_EQUALS; // Son iguales\n if(date1.getFullYear() < date2.getFullYear()){\n comp = DATES_LOWER; // Date 1 es menor que date 2\n }\n else if(date1.getFullYear() > date2.getFullYear()){\n comp = DATES_HIGHER; // Date 1 es mayor que Date 2\n }\n else{\n if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() < date2.getMonth()){\n comp = DATES_LOWER;\n }\n else if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() > date2.getMonth()){\n comp = DATES_HIGHER; // Date 1 es mayor que Date 2\n }\n else{\n if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() < date2.getDate()){\n comp = DATES_LOWER;\n }\n else{\n if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() > date2.getDate()){\n comp = DATES_HIGHER; // Date 1 es mayor que Date 2\n }\n }\n }\n }\n return comp;\n }", "function groupByDates(dates) {\n let parseDate = function (input) {\n var parts = input.match(/(\\d+)/g);\n return new Date(parts[0], parts[1] - 1, parts[2], 0); // months are 0-based\n };\n let sortedArray = Array.from(dates).sort();\n let dateArray = [];\n sortedArray.map(e => dateArray.push(parseDate(e[0])));\n let selection_by_range = [];\n let aux_selector = [];\n for (let i = 0; i < dateArray.length; i++) {\n aux_selector.push(sortedArray[i]);\n let next_day = new Date(dateArray[i]);\n next_day.setDate(dateArray[i].getDate() + 1);\n const index = dateArray.findIndex(function (x) {\n return x.toISOString().slice(0, 10) === next_day.toISOString().slice(0, 10);\n });\n if (index === -1) {\n selection_by_range.push(aux_selector);\n aux_selector = [];\n }\n }\n return selection_by_range\n}", "function compareDates(date_One, date_Two) {\n if (date_One.getFullYear() > date_Two.getFullYear())\n return 1;\n else if (date_One.getFullYear() < date_Two.getFullYear())\n return -1;\n else {\n if (date_One.getMonth() > date_Two.getMonth())\n return 1;\n else if (date_One.getMonth() < date_Two.getMonth())\n return -1;\n else {\n if (date_One.getDate() > date_Two.getDate())\n return 1;\n else if (date_One.getDate() < date_Two.getDate())\n return -1;\n else\n return 0;\n }\n }\n}", "function compare_date( a, b ) {\n if ( a.date < b.date){\n return -1;\n }\n if ( a.date > b.date ){\n return 1;\n }\n return 0;\n}", "get dates() {\n const { from, to, query, timeRegistrations } = this.store;\n let dates = [];\n if (query) {\n dates = [...new Set(timeRegistrations.map(r => r.date))].sort((a, b) => a < b);\n } else {\n let days = differenceInDays(to, from) + 1;\n for (let i = 0; i < days; i++) {\n let date = new Date(from);\n date.setDate(date.getDate() + i);\n dates.push(date);\n }\n }\n return dates;\n }", "function getUniqueBillsByDate(listOfBillsWithTitle) {\n var billsById = {};\n var listOfUniqueBills = [];\n \n //In the billsById object, create a propriety by billId and that propriety receive as value an array of objects(each bill with this id) \n listOfBillsWithTitle.filter(function(bill) {\n billsById[bill.billId] = billsById[bill.billId] || [];\n billsById[bill.billId].push(bill);\n });\n \n /*In the object, each propriety name is the billId and \n its value is an array of all the votes about this bill. \n We compare their date to keep only the latest vote.\n */\n for (var bill in billsById) {\n var latestBill = billsById[bill].reduce(function(prev, next) {\n var x = new Date(prev.dateOfVote);\n var y = new Date(next.dateOfVote);\n if (x < y) {\n return next;\n }\n else {\n return prev;\n }\n });\n \n listOfUniqueBills.push(latestBill);\n }\n return listOfUniqueBills;\n}", "_getValidDates(dateOrDates) {\n let result = [];\n\n function validate(date) {\n if (date instanceof Date) {\n return date;\n }\n else if (JQX.Utilities.DateTime && date instanceof JQX.Utilities.DateTime) {\n return date.toDate();\n }\n else if (typeof (date) === 'string') {\n if (date.trim() === 'new Date()' || date.trim() === 'new JQX.Utilities.DateTime()') {\n return new Date();\n }\n\n let regex = /(\\d+[,-.\\/]{1}\\s*\\d+[,-.\\/]{1}\\s*\\d+)/;\n\n const parseDateString = () => {\n date = date.replace(/[,-.\\/]/g, ',').split(',');\n if (date.length > 2) {\n date = new Date(parseInt(date[0]), parseInt(date[1]) - 1, parseInt(date[2]));\n }\n else {\n return new Date();\n }\n\n return date;\n }\n\n if (regex.test(date)) {\n date = regex.exec(date)[0].replace(/[,-.\\/]/g, ',').split(',');\n if (date) {\n return new Date(parseInt(date[0]), parseInt(date[1]) - 1, parseInt(date[2]));\n }\n else {\n return parseDateString();\n }\n }\n else {\n return parseDateString();\n\n }\n }\n }\n\n if (dateOrDates === undefined) {\n return null;\n }\n\n if (Array.isArray(dateOrDates)) {\n for (let i = 0; i < dateOrDates.length; i++) {\n result.push(validate(dateOrDates[i]));\n }\n }\n else {\n result.push(validate(dateOrDates));\n }\n\n result = result.filter(date => date && date.toDateString() !== 'Invalid Date'); //remove invalid dates\n result.map(date => date.setHours(0, 0, 0, 0)); //reset time, important for date comparing\n\n return result;\n }", "function Datepush(){\n\tdebugger;\n\tdateDate1=[];\n\t$(\".Date\").each(function(){\n\t\tif($(this).val()!=''){\n\t\t\tvar date = moment($(this).val(), \"DD-MM-YYYY\").toDate();\n\t\t\tvar currentDate=$(this).val();\n\t\t\tdateDate1.push(date);\n\t\t}\n\t});\t\t \n\tvar sorted = dateDate1.sort(sortDates);\n\tvar minDate = sorted[0];\n\tvar maxDate = sorted[sorted.length-1];\n\t//printing dates\n\t$(\"#fromDate1\").text(minDate.getDate()+\"-\"+(minDate.getMonth()+1)+\"-\"+minDate.getFullYear());\n\t$(\"#toDate1\").text(maxDate.getDate()+\"-\"+(maxDate.getMonth()+1)+\"-\"+maxDate.getFullYear());\n}", "static compare(date1, date2) {\n let d1 = this.reverseGregorian(date1);\n let d2 = this.reverseGregorian(date2);\n\n return d1.localeCompare(d2);\n }", "function sortDates(a, b){\n\treturn a.getTime() - b.getTime();\n}", "sortDates(unsortedDates) {\n let sortedDays = [];\n let days = [];\n\n for (var day in unsortedDates) {\n days.push(day);\n }\n\n sortedDays = days.sort(function(a, b) {\n return new Date(a.value).getDate() - new Date(b.value).getDate();\n });\n return sortedDays;\n }", "function compareDates$static(d1/*:Date*/, d2/*:Date*/)/*:Number*/ {\n if (d1 === d2) {\n return 0;\n }\n\n if (d1 && d2) {\n var time1/*:Number*/ = d1.getTime();\n var time2/*:Number*/ = d2.getTime();\n if (time1 === time2) {\n return 0;\n } else if (time1 > time2) {\n return 1;\n }\n return -1;\n }\n\n if (!d1) {\n return 1;\n }\n\n if (!d2) {\n return -1;\n }\n }", "function compareDates(a,b) {\n if(a.attributes.date.isBefore(b.attributes.date)) {return -1;}\n if(b.attributes.date.isBefore(a.attributes.date)) {return 1;}\n return 0;\n}", "viewAccentDatesFromSelected(selectedUniqueItems) {\n let dateArray = [];\n if (selectedUniqueItems) {\n\t for (let catName of Object.keys(selectedUniqueItems)) {\n\t for (let displayStr of Object.keys(selectedUniqueItems[catName])) {\n\t dateArray = dateArray.concat(selectedUniqueItems[catName][displayStr].reduce((acc, res) => { acc.push(res.itemDate); return acc; }, []));\n\t }\n\t }\n }\n\n return uniqueBy(dateArray, elt => elt);\n }", "function getUniqueDateFromColumn(data, rowNum, columnNum){\n var col = columnNum - 1 ; // choose the column you want to use as data source (0 indexed, it works at array level)\n //var data = sheet.getDataRange().getValues();// get all data\n\n var newdata = new Array();\n for(var row = rowNum - 1; row < data.length; row++){\n var duplicate = false;\n for(j in newdata){\n //Logger.log(data[row][col]);\n //Logger.log(j);\n if(Date.parse(data[row][col]) == Date.parse(newdata[j])){\n duplicate = true;\n }\n }\n if(!duplicate){\n newdata.push(data[row][col]);\n }\n }\n return newdata;\n}", "function availableDate() {\n let dates = [];\n Object.values(tdata).forEach(value => {\n let date = value.datetime;\n if (dates.indexOf(date) !== -1) {\n }\n else {\n dates.push(date);\n } \n });\n return dates;\n}", "function noDupsByDate(bookmarks) {\n var noDups = [];\n for (var i = 0; i < bookmarks.length; i += 1) {\n var seen = false;\n for (var j = i + 1; j < bookmarks.length; j += 1) {\n if (bookmarks[i].url === bookmarks[j].url) {\n seen = true;\n }\n }\n if (!seen) {\n noDups.push(bookmarks[i]);\n }\n }\n return noDups;\n}", "function getDates (){\n\t\t\t\t\tvar dates = [];\n\t\t\t\t\tscope.data.coauthors.forEach(function(author){\n\t\t\t\t\t\tauthor.dates.forEach(function(date){\n\t\t\t\t\t\t\tif(dates.length === 0){\n\t\t\t\t\t\t\t\tdates.push({ label: date, \n\t\t\t\t\t\t\t\t\tvalue: date, \n\t\t\t\t\t\t\t\t\tfilterLabel: 'Date CoAuthored: ',\n\t\t\t\t\t\t\t\t\tfilterType: 'date'\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tfor(var i =0; i < dates.length; i++){\n\t\t\t\t\t\t\t\t\tif(dates[i].value === date) {\n\t\t\t\t\t\t\t\t\t\treturn;\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\tdates.push({ label: date, value: date, filterLabel: 'Date CoAuthored: ', filterType: 'date'});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\n\t\t\t\t\treturn dates;\n\t\t\t\t}", "sortFitness(response, dates) {\n let startJ = 1;\n for (var i = 0; i < response.data.length; i++) {\n let currentRide = response.data[i];\n let currentKj = response.data[i].kilojoules;\n let d = response.data[i].start_date_local.slice(0,10)+'T07:00:00Z';\n let currentRideDate = new Date(d).toString().slice(4,15);\n\n for (var j = startJ-1; j < dates.length; j++) {\n let currentDate = dates[j].formattedDate;\n if (currentRideDate === currentDate) {\n currentRide.formattedDate = currentRideDate;\n dates[j] = currentRide;\n dates[j].kilojoules = currentKj;\n break;\n }\n ++startJ;\n }\n }\n return dates;\n }", "function parseByDate(models) {\n var tempShared = [];\n var initial_time = new Date(models[models.length - 1].attributes.date);\n for (var i = models.length - 1; i >= 0; i--) {\n var compare_against = new Date(models[i].attributes.date);\n if(initial_time.getFullYear() == compare_against.getFullYear()) {\n if (initial_time.getMonth() == compare_against.getMonth()) {\n if (initial_time.getDate() == compare_against.getDate()) {\n // console.log(models[i]);\n tempShared.push([compare_against, models[i].attributes]);\n models.splice(i, 1);\n };\n };\n };\n };\n crime_by_date.push(tempShared);\n if (models.length > 0) {\n parseByDate(models);\n }\n else {\n // console.log(crime_by_date);\n };\n}", "function compareDates(a, b) {\n var aDate = a.date;\n var bDate = b.date;\n\n let comparison = 0;\n if (aDate > bDate) {\n comparison = 1;\n } \n else if (aDate < bDate) {\n comparison = -1;\n }\n \n return comparison;\n}", "compareDate(a, b) {\n if (a.startDate < b.startDate) return -1\n if (a.startDate > b.startDate) return 1\n else return 0\n }", "function compareDate(a,b) {\n if (a.date < b.date)\n return -1;\n else if (a.date > b.date)\n return 1;\n else\n return 0;\n }", "createDatesArray() {\n let timeAgoISO = moment().utc().subtract(180, 'days').format();\n let date1 = new Date();\n let date2 = new Date(timeAgoISO);\n let day;\n let datesBetween = [];\n\n while(date2 < date1) {\n let formattedDate = date1.toString().split('').slice(4, 15).join('');\n datesBetween.push({\n formattedDate: formattedDate,\n fitLine: 0,\n kilojoules: 0,\n });\n day = date1.getDate()\n date1 = new Date(date1.setDate(--day));\n }\n\n return datesBetween.reverse();\n }", "function trimDays(totDays) {\n var uniqueDays = [];\n\n $.each(totDays, function(i, el) {\n if ($.inArray(el, uniqueDays) === -1) uniqueDays.push(el);\n });\n return uniqueDays;\n\n }" ]
[ "0.63693047", "0.62496966", "0.6195258", "0.6165936", "0.60871106", "0.59565145", "0.58595645", "0.58589715", "0.5834164", "0.5825121", "0.58009577", "0.57928205", "0.57762784", "0.57596713", "0.5755276", "0.5740565", "0.5691843", "0.56712985", "0.5655792", "0.56167334", "0.56129134", "0.5607491", "0.55812687", "0.55693305", "0.5566904", "0.5554476", "0.5553217", "0.5551927", "0.5550771", "0.5544486" ]
0.77713454
0
Compares two dates with the help of the provided comparator function
function compareDatesWithFunction(d1, d2, fnC) { var c1 = fnC(d1); var c2 = fnC(d2); if (c1 > c2) return 1; if (c1 < c2) return -1; return 0; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function compFunc(a, b)\n{\n\tif (a.date < b.date)\n\t\treturn 1;\n\telse if (a.date > b.date)\n\t\treturn -1;\n\telse\n\t\treturn 0;\n}", "function compare_date( a, b ) {\n if ( a.date < b.date){\n return -1;\n }\n if ( a.date > b.date ){\n return 1;\n }\n return 0;\n}", "function dateComparator(date1, date2) {\n\t\t\tvar date1Number = monthToComparableNumber(date1);\n\t\t\tvar date2Number = monthToComparableNumber(date2);\n\n\t\t\tif (date1Number===null && date2Number===null) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tif (date1Number===null) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tif (date2Number===null) {\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\treturn date1Number - date2Number;\n\t\t}", "compareDate(a, b) {\n if (a.startDate < b.startDate) return -1\n if (a.startDate > b.startDate) return 1\n else return 0\n }", "function compareDate(a,b) {\n if (a.date < b.date)\n return -1;\n else if (a.date > b.date)\n return 1;\n else\n return 0;\n }", "function compareDateFunction(date1,date2){\r\n\tvar leftDate;\r\n\tvar rightDate;\r\n\tif(typeof(date1) == \"object\"){\r\n\t\tleftDate = date1;\r\n\t}else{\r\n\t\tleftDate = convertStr2Date(date1);\r\n\t}\r\n\tif(typeof(date2) == \"object\"){\r\n\t\trightDate = date2;\r\n\t}else{\r\n\t\trightDate = convertStr2Date(date2);\r\n\t}\r\n\treturn compareDate(leftDate,rightDate,0);\r\n}", "function compareDate(a, b) {\r\n if (a.date > b.date) return 1;\r\n if (b.date > a.date) return -1;\r\n return 0;\r\n}", "static compare(date1, date2) {\n let d1 = this.reverseGregorian(date1);\n let d2 = this.reverseGregorian(date2);\n\n return d1.localeCompare(d2);\n }", "function sortByDate(a, b) {\n let comparison = 0;\n\n // -------------------------------------------------------------JavaScript - Conditional Statments Ex. 3||\n if (a.getDate >= b.date) {\n comparison = 1;\n } else if (a.date <= b.date) {\n comparison = -1;\n }\n return comparison;\n}", "function compareDates(date1, date2)\r\n{\r\n if(date1 < date2)\r\n return -1;\r\n else if(date1 > date2)\r\n return 1;\r\n else\r\n return 0;\r\n}", "function compareDatesWH(date1, date2){\n var comp = DATES_EQUALS; // Son iguales\n if(date1.getFullYear() < date2.getFullYear()){\n comp = DATES_LOWER; // Date 1 es menor que date 2\n }\n else if(date1.getFullYear() > date2.getFullYear()){\n comp = DATES_HIGHER; // Date 1 es mayor que Date 2\n }\n else{\n if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() < date2.getMonth()){\n comp = DATES_LOWER;\n }\n else if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() > date2.getMonth()){\n comp = DATES_HIGHER; // Date 1 es mayor que Date 2\n }\n else{\n if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() < date2.getDate()){\n comp = DATES_LOWER;\n }\n else{\n if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() > date2.getDate()){\n comp = DATES_HIGHER; // Date 1 es mayor que Date 2\n }\n }\n }\n }\n return comp;\n }", "function compareDates(a, b) {\n var aDate = a.date;\n var bDate = b.date;\n\n let comparison = 0;\n if (aDate > bDate) {\n comparison = 1;\n } \n else if (aDate < bDate) {\n comparison = -1;\n }\n \n return comparison;\n}", "function compare_dates(fecha, fecha2) \r\n { \r\n\t\r\n var xMonth=fecha.substring(3, 5); \r\n var xDay=fecha.substring(0, 2); \r\n var xYear=fecha.substring(6,10); \r\n var yMonth=fecha2.substring(3,5);\r\n var yDay=fecha2.substring(0, 2);\r\n var yYear=fecha2.substring(6,10); \r\n \r\n if (xYear > yYear){ \r\n return(true); \r\n }else{ \r\n if (xYear == yYear){ \r\n\t if (xMonth > yMonth){ \r\n\t \t\treturn(true); \r\n\t }else{ \r\n\t\t if (xMonth == yMonth){ \r\n\t\t if (xDay> yDay) \r\n\t\t return(true); \r\n\t\t else \r\n\t\t return(false); \r\n\t\t }else{\r\n\t\t \t return(false); \r\n\t\t } \r\n\t } \r\n }else{\r\n \t return(false); \r\n } \r\n \r\n } \r\n}", "function compareDates(date_One, date_Two) {\n if (date_One.getFullYear() > date_Two.getFullYear())\n return 1;\n else if (date_One.getFullYear() < date_Two.getFullYear())\n return -1;\n else {\n if (date_One.getMonth() > date_Two.getMonth())\n return 1;\n else if (date_One.getMonth() < date_Two.getMonth())\n return -1;\n else {\n if (date_One.getDate() > date_Two.getDate())\n return 1;\n else if (date_One.getDate() < date_Two.getDate())\n return -1;\n else\n return 0;\n }\n }\n}", "compareTwoObjectsByDate(a,b) {\n let x = a.approach_date;\n let y = b.approach_date;\n if (x < y) {return -1;}\n if (x > y) {return 1;}\n return 0;\n }", "function compare(a,b) {\n if (a.orderDate < b.orderDate)\n return -1;\n if (a.orderDate > b.orderDate)\n return 1;\n return 0;\n}", "function isCorrectOrder(yyyymmdd1, yyyymmdd2) {\r\n return yyyymmdd1 < yyyymmdd2;\r\n}", "function sortHelper(a, b){\n // Compare the 2 dates\n return a.start < b.start ? -1 : 1;\n}", "function comparisonByDate(dateA, dateB) {\n var c = new Date(dateA.date);\n var d = new Date(dateB.date);\n return c - d;\n }", "function sortDates(a, b){\n\treturn a.getTime() - b.getTime();\n}", "function compareDate(fromDate, toDate) {\r\r\tvar dt1 = parseInt(fromDate.substring(0, 2), 10);\r\r\tvar mon1 = parseInt(fromDate.substring(3, 5), 10);\r\r\tvar yr1 = parseInt(fromDate.substring(6, 10), 10);\r\r\tvar dt2 = parseInt(toDate.substring(0, 2), 10);\r\r\tvar mon2 = parseInt(toDate.substring(3, 5), 10);\r\r\tvar yr2 = parseInt(toDate.substring(6, 10), 10);\r\r\tvar date1 = new Date(yr1, mon1, dt1);\r\r\tvar date2 = new Date(yr2, mon2, dt2);\r\r\tif (date1 > date2) {\r\r\t\treturn 1;\r\r\t} else {\r\r\t\tif (date1 < date2) {\r\r\t\t\treturn -1;\r\r\t\t} else {\r\r\t\t\treturn 0;\r\r\t\t}\r\r\t}\r\r}", "function compareDates(a, b)\n{\n var x=new Date(a.Date);\n var y=new Date(b.Date);\n \n console.log(\"hello we are hee\");\t\n\n console.log(x);\n console.log(y);\t\n\n if(x>y)\n {\n console.log(1);\n return 1;\n\n }\n else\n {\n console.log(-1);\t \n return -1;\n }\n}", "function compare(a,b) {\n if (a.dateOfEvent > b.dateOfEvent)\n return -1;\n if (a.dateOfEvent < b.dateOfEvent)\n return 1;\n return 0;\n }", "function compareDate(dos, rd) {\n\n }", "function compareSortDates(first, second)\n{\n return first.eventSD - second.eventSD;\n}", "function compare(a, b) {\n const dateA = a.date;\n const dateB = b.date;\n\n let comparison = 0;\n if (dateA > dateB) {\n comparison = 1;\n } else if (dateA < dateB) {\n comparison = -1;\n }\n return comparison * -1;\n }", "function compareDates(a, b) {\n\t\tif (b.transaction_date < a.transaction_date) {\n\t\t\treturn -1\n\t\t}\n\t\tif (b.transaction_date > a.transaction_date) {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\t}", "function compareDates(a, b) {\n\t\tif (b.transaction_date < a.transaction_date) {\n\t\t\treturn -1\n\t\t}\n\t\tif (b.transaction_date > a.transaction_date) {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\t}", "function sortByDateAscending(a, b) {\n // Dates will be cast to numbers automagically:\n return a.date - b.date;\n }", "function compareDates(a,b) {\n if(a.attributes.date.isBefore(b.attributes.date)) {return -1;}\n if(b.attributes.date.isBefore(a.attributes.date)) {return 1;}\n return 0;\n}" ]
[ "0.73501474", "0.7120855", "0.70249486", "0.70114815", "0.6975558", "0.69590884", "0.6923796", "0.6900942", "0.689917", "0.68973756", "0.68314284", "0.68014747", "0.6645342", "0.6622629", "0.6592738", "0.65926725", "0.6576781", "0.6573856", "0.6554653", "0.65489477", "0.65375435", "0.65065855", "0.64956987", "0.64830315", "0.64773995", "0.6472955", "0.6443351", "0.6443351", "0.6441235", "0.6434403" ]
0.7148702
1
Compares if dates appear in the same logical quarter
function compareQuarters(d1, d2) { var m1 = d1.getMonth(); var m2 = d2.getMonth(); var q1 = (Math.floor(m1 / 3) * 3); var q2 = (Math.floor(m2 / 3) * 3); if (q1 > q2) return 1; if (q1 < q2) return -1; return 0; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function compareQuarterYears(d1, d2) {\n var r = compareYears(d1, d2);\n if (r === 0) {\n r = compareQuarters(d1, d2);\n }\n return r;\n }", "function getCurrentQuarter(){\n let startDate = new Date()\n let endDate = new Date()\n let month = endDate.getMonth()\n let mod = month % 3 \n // Aktuelles Quartal Berechnung Beispiel März: month = 2, mod: 2 % 3 = 2 , Aktuelles Quartal = Monat 2 - mod 2 = 0 (0 = Januar bis Heute)\n startDate.setFullYear(endDate.getFullYear(), month - mod, 1)\n startDate.setHours(0,0,0,0)\n endDate.setHours(23,59,59,0)\n dates[0] = startDate\n dates[1] = endDate\n return dates\n}", "function compareDatesWH(date1, date2){\n var comp = DATES_EQUALS; // Son iguales\n if(date1.getFullYear() < date2.getFullYear()){\n comp = DATES_LOWER; // Date 1 es menor que date 2\n }\n else if(date1.getFullYear() > date2.getFullYear()){\n comp = DATES_HIGHER; // Date 1 es mayor que Date 2\n }\n else{\n if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() < date2.getMonth()){\n comp = DATES_LOWER;\n }\n else if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() > date2.getMonth()){\n comp = DATES_HIGHER; // Date 1 es mayor que Date 2\n }\n else{\n if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() < date2.getDate()){\n comp = DATES_LOWER;\n }\n else{\n if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() > date2.getDate()){\n comp = DATES_HIGHER; // Date 1 es mayor que Date 2\n }\n }\n }\n }\n return comp;\n }", "function sameDate(d0, d1) {\n\treturn d0.getFullYear() == d1.getFullYear() && d0.getMonth() == d1.getMonth() && d0.getDate() == d1.getDate();\n}", "function datesAreEquivalent(date1,date2){\n return (date1.getMonth() == date2.getMonth()) && (date1.getFullYear() == date2.getFullYear()) && (date1.getDate() == date2.getDate()) ;\n}", "testCase1_3() {\n let _verdict = false;\n let _tc1 = this._helperModule.calculateNewDateBasedOnPivotDate(new Date(\"2016-09-03\"), 0);\n if (Number(_tc1) == Number(new Date(\"2016-09-03\"))) {\n // passed the test\n _verdict = true;\n }\n\n return _verdict;\n }", "sameDate(dateA, dateB) {\n return ((dateA.getDate() === dateB.getDate()) && (dateA.getMonth() === dateB.getMonth()) && (dateA.getFullYear() === dateB.getFullYear()));\n }", "function calculateQuarterlyPerf(qrts) {\n qrts.map(function (qtr, index) {\n let compQuarter = qrts.find(\n (q) => q.name == getComparativeQuarterName(qtr)\n );\n if (isDefined(compQuarter)) {\n if (compQuarter.eps.eps != 0) {\n qtr.eps.negativeCompQtr = false;\n qtr.eps.negativeTurnaround = false;\n qtr.eps.perf = calculatePercentChange(\n qtr.eps.eps,\n compQuarter.eps.eps\n );\n if (qtr.eps.eps < 0 && compQuarter.eps.eps) {\n qtr.eps.negativeCompQtr = true;\n } else if (compQuarter.eps.eps < 0) {\n qtr.eps.negativeTurnaround = true;\n }\n }\n if (isAbleToCalculateQtrRevChange(qtr, compQuarter)) {\n qtr.rev.perf = calculatePercentChange(\n qtr.rev.rev,\n compQuarter.rev.rev\n );\n }\n }\n });\n}", "function isSame(date1, date2, period){\n if (period) {\n date1 = startOf(date1, period);\n date2 = startOf(date2, period);\n }\n return Number(date1) === Number(date2);\n }", "function compareDates(date1, date2) {\n if (!date1 && !date2) {\n return true;\n }\n else if (!date1 || !date2) {\n return false;\n }\n else {\n return (date1.getFullYear() === date2.getFullYear() &&\n date1.getMonth() === date2.getMonth() &&\n date1.getDate() === date2.getDate());\n }\n}", "function compareDates(mixDataInicial, mixDataFinal)\n{\n var dataInicial = getObject(mixDataInicial);\n var dataFinal = getObject(mixDataFinal);\n if ((empty(dataInicial)) || (empty(dataFinal)))\n return false;\n return compareDatesValues(dataInicial.value, dataFinal.value);\n}", "function calendar_helper_dateEquals(date1, date2){\n if (date1.getFullYear() == date2.getFullYear())\n if (date1.getMonth() == date2.getMonth())\n if (date1.getDate() == date2.getDate())\n return true;\n return false;\n}", "getNextQuarter (format) {\n try {\n format = format || 'yyyy-MM-dd';\n let date = new Date(),\n curYear = date.getFullYear(),\n startMonth = getQuarterStartMonth() + 3,\n lastMonth = startMonth + 2,\n lastDate = new Date();\n lastDate.setMonth(lastMonth+1);\n lastDate.setDate(0);\n let firstDay = Timer.formatDate(new Date(curYear, startMonth, 1, 0, 0, 0), format),\n lasetDay = Timer.formatDate(new Date(curYear, lastMonth, lastDate.getDate(), 23, 59, 59), format);\n return {firstDay, lasetDay};\n } catch (error) {\n throw error;\n }\n }", "function sameDate(d1, d2) {\n return d1.getMonth === d2.getMonth && d1.getFullYear() === d2.getFullYear();\n}", "Q (date) {\n return Math.ceil((date.getMonth() + 1) / 3)\n }", "testCase1_1() {\n let _verdict = false;\n let _tc1 = this._helperModule.calculateNewDateBasedOnPivotDate(new Date(\"2016-09-03\"), -2);\n if (Number(_tc1) == Number(new Date(\"2016-09-01\"))) {\n // passed the test\n _verdict = true;\n }\n\n return _verdict;\n }", "function myFunction(date1, date2) {\n return (\n date1.getYear() === date2.getYear() &&\n date1.getMonth() === date2.getMonth() &&\n date1.getDate() === date2.getDate()\n );\n}", "getCurrentQuarter (format) {\n try {\n format = format || 'yyyy-MM-dd';\n let date = new Date(),\n curYear = date.getFullYear(),\n startMonth = getQuarterStartMonth(),\n lastMonth = startMonth+2,\n lastDate = new Date();\n lastDate.setMonth(lastMonth+1);\n lastDate.setDate(0);\n let firstDay = Timer.formatDate(new Date(curYear, startMonth, 1, 0, 0, 0), format),\n lasetDay = Timer.formatDate(new Date(curYear, lastMonth, lastDate.getDate(), 23, 59, 59), format);\n return {firstDay, lasetDay};\n } catch (error) {\n throw error;\n }\n }", "static getQuarterStartMonth () { \n let nowMonth = new Date().getMonth();\n var quarterStartMonth = 0; \n if(nowMonth<3){ \n quarterStartMonth = 0; \n } \n if(2<nowMonth && nowMonth<6){ \n quarterStartMonth = 3; \n } \n if(5<nowMonth && nowMonth<9){ \n quarterStartMonth = 6; \n } \n if(nowMonth>8){ \n quarterStartMonth = 9; \n } \n return quarterStartMonth; \n }", "testCase1_2() {\n let _verdict = false;\n let _tc1 = this._helperModule.calculateNewDateBasedOnPivotDate(new Date(\"2016-09-03\"), 2);\n if (Number(_tc1) == Number(new Date(\"2016-09-05\"))) {\n // passed the test\n _verdict = true;\n }\n\n return _verdict;\n }", "function isCorrectOrder(yyyymmdd1, yyyymmdd2) {\r\n return yyyymmdd1 < yyyymmdd2;\r\n}", "function hasPreSelectionChanged(date1, date2) {\n if (date1 && date2) {\n return Object(date_fns_getMonth__WEBPACK_IMPORTED_MODULE_23__[\"default\"])(date1) !== Object(date_fns_getMonth__WEBPACK_IMPORTED_MODULE_23__[\"default\"])(date2) || Object(date_fns_getYear__WEBPACK_IMPORTED_MODULE_24__[\"default\"])(date1) !== Object(date_fns_getYear__WEBPACK_IMPORTED_MODULE_24__[\"default\"])(date2);\n }\n\n return date1 !== date2;\n}", "function hasPreSelectionChanged(date1, date2) {\n if (date1 && date2) {\n return Object(date_fns_getMonth__WEBPACK_IMPORTED_MODULE_23__[\"default\"])(date1) !== Object(date_fns_getMonth__WEBPACK_IMPORTED_MODULE_23__[\"default\"])(date2) || Object(date_fns_getYear__WEBPACK_IMPORTED_MODULE_24__[\"default\"])(date1) !== Object(date_fns_getYear__WEBPACK_IMPORTED_MODULE_24__[\"default\"])(date2);\n }\n\n return date1 !== date2;\n}", "function compare_dates(fecha, fecha2) \r\n { \r\n\t\r\n var xMonth=fecha.substring(3, 5); \r\n var xDay=fecha.substring(0, 2); \r\n var xYear=fecha.substring(6,10); \r\n var yMonth=fecha2.substring(3,5);\r\n var yDay=fecha2.substring(0, 2);\r\n var yYear=fecha2.substring(6,10); \r\n \r\n if (xYear > yYear){ \r\n return(true); \r\n }else{ \r\n if (xYear == yYear){ \r\n\t if (xMonth > yMonth){ \r\n\t \t\treturn(true); \r\n\t }else{ \r\n\t\t if (xMonth == yMonth){ \r\n\t\t if (xDay> yDay) \r\n\t\t return(true); \r\n\t\t else \r\n\t\t return(false); \r\n\t\t }else{\r\n\t\t \t return(false); \r\n\t\t } \r\n\t } \r\n }else{\r\n \t return(false); \r\n } \r\n \r\n } \r\n}", "function compareDate(dos, rd) {\n\n }", "static isSameDate(dateA, dateB) {\n return (\n dateA.getFullYear() === dateB.getFullYear()\n && dateA.getMonth() === dateB.getMonth()\n && dateA.getDate() === dateB.getDate()\n );\n }", "function findFYQ(date) {\n let year = date.substring(0,4)\n let month = date.substring(5,7)\n let quarter = Math.floor(month / 3) + 1\n return `${year} Q${quarter}`\n }", "function compareDates(d1, d2) {\n var r = compareYears(d1, d2);\n if (r === 0) {\n r = compareMonths(d1, d2);\n if (r === 0) {\n r = compareDays(d1, d2);\n }\n }\n return r;\n }", "function dateCompare(date1, date2) {\n\t\tif (date1.getDate() === date2.getDate() && date1.getMonth() === date2.getMonth() && date1.getFullYear() === date2.getFullYear()) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t}", "_hasSameMonthAndYear(d1, d2) {\n return !!(d1 && d2 && this._dateAdapter.getMonth(d1) == this._dateAdapter.getMonth(d2) &&\n this._dateAdapter.getYear(d1) == this._dateAdapter.getYear(d2));\n }" ]
[ "0.69359875", "0.61757916", "0.6020083", "0.60103697", "0.59846246", "0.58858174", "0.5853647", "0.5846302", "0.5828677", "0.58286446", "0.5808071", "0.57497674", "0.5706315", "0.56884485", "0.5653579", "0.56431323", "0.56376064", "0.5606512", "0.5584658", "0.55477524", "0.55320585", "0.55124015", "0.55124015", "0.5508306", "0.5497128", "0.54911083", "0.5481893", "0.54643047", "0.5462198", "0.5450383" ]
0.703043
0
Compares one date with another if they are the same quarter of the same year
function compareQuarterYears(d1, d2) { var r = compareYears(d1, d2); if (r === 0) { r = compareQuarters(d1, d2); } return r; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function compareQuarters(d1, d2) {\n var m1 = d1.getMonth();\n var m2 = d2.getMonth();\n var q1 = (Math.floor(m1 / 3) * 3);\n var q2 = (Math.floor(m2 / 3) * 3);\n if (q1 > q2) return 1;\n if (q1 < q2) return -1;\n return 0;\n }", "function _isNextYear(d1, d2) {\n return d2.getFullYear() - d1.getFullYear() === 1;\n }", "function yearBefore(d1, d2) {\n return d1.getFullYear() < d2.getFullYear();\n }", "function _isSameYear(d1, d2) {\n return d1.getFullYear() === d2.getFullYear();\n }", "function sameDate(d0, d1) {\n\treturn d0.getFullYear() == d1.getFullYear() && d0.getMonth() == d1.getMonth() && d0.getDate() == d1.getDate();\n}", "function sameDate(d1, d2) {\n return d1.getMonth === d2.getMonth && d1.getFullYear() === d2.getFullYear();\n}", "function isWithinYear(date1, date2) {\n\t\tvar year1 = parseInt(date1[0]);\n\t\tvar year2 = parseInt(date2[0]);\n\t\tvar month1 = parseInt(date1[1]);\n\t\tvar month2 = parseInt(date2[1]);\n\t\tvar day1 = parseInt(date1[2]);\n\t\tvar day2 = parseInt(date2[2]);\n\t\tif (year1 === year2) {\n\t\t\treturn true;\n\t\t} else if (year2 === year1 + 1 && (month2 < month1) || (month2 === month1 && day2 < day1)) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}", "sameDate(dateA, dateB) {\n return ((dateA.getDate() === dateB.getDate()) && (dateA.getMonth() === dateB.getMonth()) && (dateA.getFullYear() === dateB.getFullYear()));\n }", "isSameYear(date) {\n const universalDate = new UniversalDate(date);\n return universalDate.year === this.year;\n }", "function calendar_helper_dateEquals(date1, date2){\n if (date1.getFullYear() == date2.getFullYear())\n if (date1.getMonth() == date2.getMonth())\n if (date1.getDate() == date2.getDate())\n return true;\n return false;\n}", "function compareYear(a, b) {\r\n if (a.YEAR < b.YEAR)\r\n return -1;\r\n else if (a.YEAR > b.YEAR)\r\n return 1;\r\n else\r\n return 0;\r\n}", "function myFunction(date1, date2) {\n return (\n date1.getYear() === date2.getYear() &&\n date1.getMonth() === date2.getMonth() &&\n date1.getDate() === date2.getDate()\n );\n}", "function compareDatesWH(date1, date2){\n var comp = DATES_EQUALS; // Son iguales\n if(date1.getFullYear() < date2.getFullYear()){\n comp = DATES_LOWER; // Date 1 es menor que date 2\n }\n else if(date1.getFullYear() > date2.getFullYear()){\n comp = DATES_HIGHER; // Date 1 es mayor que Date 2\n }\n else{\n if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() < date2.getMonth()){\n comp = DATES_LOWER;\n }\n else if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() > date2.getMonth()){\n comp = DATES_HIGHER; // Date 1 es mayor que Date 2\n }\n else{\n if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() < date2.getDate()){\n comp = DATES_LOWER;\n }\n else{\n if(date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() > date2.getDate()){\n comp = DATES_HIGHER; // Date 1 es mayor que Date 2\n }\n }\n }\n }\n return comp;\n }", "function libraryFine(d1, m1, y1, d2, m2, y2) {\n // I would start off comparing the years...\n // if the year it was returned is greater than the due date year, return 10,000.\n if(y1 > y2){\n return 10000\n // else if the year is equal to the due date year...\n } else if(y1 === y2){\n // we check if the month is greater than the due date month..\n if(m1 > m2){\n // we check if the day it was returned is greater or equal than the due date day, and also if the year it was returned is greater than the due date year.\n if(d1 >= d2 && y1 > y2){\n // if it is, we return 10,000..\n return 10000\n // otherwise, it has not been more than a year so... \n } else {\n // we subtract the returned month minus the due date month..\n let result = Math.abs(m1 - m2)\n // and we return the multiplication of the result times 500.\n return 500 * result\n }\n // else if the month is returned is less than the due date month, we return 0.\n } else if(m1 < m2){\n return 0\n }\n // if the day is greater than the due date day...\n if(d1 > d2){\n // we subtract the returned day minus the due date day..\n let result = Math.abs(d1 - d2)\n // and return the result times 15.\n return 15 * result\n }\n }\n // if none of this returns anything, there might be an edge case that it was not returned late, so we still need to return 0.\n return 0\n}", "function _isPrevYear(d1, d2) {\n return _isNextYear(d2, d1);\n }", "function sameYearAndMonth(d1, d2) {\n\treturn (\n\t\td1.getFullYear() == d2.getFullYear() &&\n\t\td1.getMonth() == d2.getMonth()\n\t);\n}", "_hasSameMonthAndYear(d1, d2) {\n return !!(d1 && d2 && this._dateAdapter.getMonth(d1) == this._dateAdapter.getMonth(d2) &&\n this._dateAdapter.getYear(d1) == this._dateAdapter.getYear(d2));\n }", "_hasSameMonthAndYear(d1, d2) {\n return !!(d1 && d2 && this._dateAdapter.getMonth(d1) == this._dateAdapter.getMonth(d2) &&\n this._dateAdapter.getYear(d1) == this._dateAdapter.getYear(d2));\n }", "function datesAreEquivalent(date1,date2){\n return (date1.getMonth() == date2.getMonth()) && (date1.getFullYear() == date2.getFullYear()) && (date1.getDate() == date2.getDate()) ;\n}", "function yearComparator( auto1, auto2){\r\n if(auto1.year >= auto2.year){\r\n\t\treturn true;\r\n\t}\r\n\telse{\r\n\t\treturn false;\r\n\t}\r\n}", "function getCurrentQuarter(){\n let startDate = new Date()\n let endDate = new Date()\n let month = endDate.getMonth()\n let mod = month % 3 \n // Aktuelles Quartal Berechnung Beispiel März: month = 2, mod: 2 % 3 = 2 , Aktuelles Quartal = Monat 2 - mod 2 = 0 (0 = Januar bis Heute)\n startDate.setFullYear(endDate.getFullYear(), month - mod, 1)\n startDate.setHours(0,0,0,0)\n endDate.setHours(23,59,59,0)\n dates[0] = startDate\n dates[1] = endDate\n return dates\n}", "static isSameDate(dateA, dateB) {\n return (\n dateA.getFullYear() === dateB.getFullYear()\n && dateA.getMonth() === dateB.getMonth()\n && dateA.getDate() === dateB.getDate()\n );\n }", "function compareYears(a, b) {\n if (a.year < b.year)\n return -1;\n if (a.year > b.year)\n return 1;\n return 0;\n }", "isSameYear(date1, data2) {\n\t\treturn Moment(date1).isSame(data2, 'year');\n\t}", "function compareDates(d1, d2) {\n var r = compareYears(d1, d2);\n if (r === 0) {\n r = compareMonths(d1, d2);\n if (r === 0) {\n r = compareDays(d1, d2);\n }\n }\n return r;\n }", "function isCorrectOrder(yyyymmdd1, yyyymmdd2) {\r\n return yyyymmdd1 < yyyymmdd2;\r\n}", "function compareDates(date1, date2) {\n if (!date1 && !date2) {\n return true;\n }\n else if (!date1 || !date2) {\n return false;\n }\n else {\n return (date1.getFullYear() === date2.getFullYear() &&\n date1.getMonth() === date2.getMonth() &&\n date1.getDate() === date2.getDate());\n }\n}", "function compare(a, b) {\n if (a.year < b.year)\n return -1;\n if (a.year > b.year)\n return 1;\n return 0;\n }", "function isSame(date1, date2, period){\n if (period) {\n date1 = startOf(date1, period);\n date2 = startOf(date2, period);\n }\n return Number(date1) === Number(date2);\n }", "function compareDates(date_One, date_Two) {\n if (date_One.getFullYear() > date_Two.getFullYear())\n return 1;\n else if (date_One.getFullYear() < date_Two.getFullYear())\n return -1;\n else {\n if (date_One.getMonth() > date_Two.getMonth())\n return 1;\n else if (date_One.getMonth() < date_Two.getMonth())\n return -1;\n else {\n if (date_One.getDate() > date_Two.getDate())\n return 1;\n else if (date_One.getDate() < date_Two.getDate())\n return -1;\n else\n return 0;\n }\n }\n}" ]
[ "0.7048928", "0.6692871", "0.66361976", "0.65389264", "0.63547534", "0.63365585", "0.62701106", "0.6159095", "0.6129432", "0.6115656", "0.6101225", "0.60819244", "0.6069449", "0.6043508", "0.60178137", "0.5967939", "0.5959819", "0.5959819", "0.5906313", "0.5900762", "0.58990455", "0.5895712", "0.5892894", "0.58747345", "0.5871526", "0.58344406", "0.58292574", "0.58135235", "0.5785598", "0.5775745" ]
0.7781297
0
Run logic in schema at dataModelChange
_checkSchemaLogic(changedData) { changedData = changedData || {}; const model = this.exo.dataBinding.model; if (model && model.logic) { if (typeof (model.logic) === "function") { this.applyJSLogic(model.logic, null, model, changedData) } else if (model.logic && model.logic.type === "JavaScript") { let script = this.assembleScript(model.logic) this.applyJSLogic(null, script, model, changedData) } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function handleModelDataChanged(dataObj) {\n //console.log('handleModelDataChanged', dataObj.payload);\n }", "function blockCall(change, dataModelName, entityName, data) {\n if (change.hasError === 0) {\n checkForPreviousError(change, dataModelName, entityName, data);\n _.forEach(LocalDBManager.getStore(dataModelName, entityName).schema.columns, function (col) {\n if (col.targetEntity) {\n if (data[col.sourceFieldName]) {\n blockCall(change, dataModelName, col.targetEntity, data[col.sourceFieldName]);\n } else if (data[col.fieldName]) {\n checkForPreviousError(change, dataModelName, col.targetEntity, data, col.fieldName);\n }\n }\n });\n }\n }", "function handleUpdateModelData(dataObj) {\n //console.log('handleUpdateModelData', dataObj.payload);\n }", "__applyModelChanges() {\n this.buildLookupTable();\n this._applyDefaultSelection();\n }", "onDatabaseEvent(changeType, recordType, record, causedBy) {\n const dataTypesArray = causedBy === 'sync' ? this.props.dataTypesSynchronised\n : this.props.dataTypesLinked;\n if ((dataTypesArray && dataTypesArray.indexOf(recordType) >= 0) ||\n (recordType === this.props.finalisableDataType && record.isFinalised)) {\n this.props.refreshData();\n }\n }", "afterValidChange() { }", "blockCall(store, change, dataModelName, entityName, data) {\n if (change.hasError === 0) {\n this.checkForPreviousError(store, change, dataModelName, entityName, data);\n store.entitySchema.columns.forEach(col => {\n if (col.foreignRelations) {\n col.foreignRelations.some(foreignRelation => {\n if (data[foreignRelation.sourceFieldName]) {\n this.blockCall(store, change, dataModelName, foreignRelation.targetEntity, data[foreignRelation.sourceFieldName]);\n }\n else if (data[col.fieldName]) {\n this.checkForPreviousError(store, change, dataModelName, foreignRelation.targetEntity, data, col.fieldName);\n }\n return change.hasError === 1;\n });\n }\n });\n }\n }", "_runProcessChanges() {\n // Don't run this functionality if the element has disconnected.\n if (!this.isConnected) return;\n\n store.dispatch(ui.reportDirtyForm(this.formName, this.isDirty));\n this.dispatchEvent(new CustomEvent('change', {\n detail: {\n delta: this.delta,\n commentContent: this.getCommentContent(),\n },\n }));\n }", "fireChanged () {\n this.$emit ( 'input', this.model );\n }", "function inputChanged() {\n parseInput(this);\n getDataFromTable();\n }", "preCall(change) {\n if (change && change.service === 'DatabaseService') {\n const entityName = change.params.entityName;\n const dataModelName = change.params.dataModelName;\n switch (change.operation) {\n case 'insertTableData':\n case 'insertMultiPartTableData':\n case 'updateTableData':\n case 'updateMultiPartTableData':\n return this.localDBManagementService.getStore(dataModelName, entityName).then(store => {\n this.blockCall(store, change, dataModelName, entityName, change.params.data);\n });\n case 'deleteTableData':\n return this.localDBManagementService.getStore(dataModelName, entityName).then(store => {\n this.blockCall(store, change, dataModelName, entityName, change.params);\n });\n }\n }\n }", "OnBatchModified() { this.Trigger(\"BatchModified\", new tp.DataTableEventArgs()); }", "function dataChanged(uiWidget) {\n getPipeline(uiWidget).trigger('dataChanged');\n }", "onChange() {\n this.validate();\n this.triggerContextUpdate();\n }", "onDataChange() {}", "onStoreUpdate({ changes, record }) {\n const { editorContext } = this;\n\n if (editorContext && editorContext.editor.isVisible) {\n if (record === editorContext.record && editorContext.editor.dataField in changes) {\n editorContext.editor.refreshEdit();\n }\n }\n }", "_schemaChanged() {\n //make sure the content is there first\n setTimeout(() => {\n let itemLabel = this.schema.items.itemLabel;\n if (this.schema && Array.isArray(this.schema.value)) {\n this.schema.value.forEach(val => {\n this.push(\"__headings\", val[itemLabel]);\n });\n }\n this.shadowRoot.querySelectorAll(\".item-fields\").forEach(item => {\n let index = item.getAttribute(\"data-index\"),\n propertyName = `${this.propertyPrefix}${this.propertyName}`,\n prefix = `${propertyName}.${index}`,\n //path = `${propertyName}.properties.${index}`,\n val = this.schema.value[index];\n //for each array item, request the fields frrom eco-json-schema-object\n this.dispatchEvent(\n new CustomEvent(\"build-fieldset\", {\n bubbles: false,\n cancelable: true,\n composed: true,\n detail: {\n container: item,\n path: propertyName,\n prefix: prefix,\n properties: this.schema.properties.map(prop => {\n let newprop = JSON.parse(JSON.stringify(prop));\n newprop.value = val[prop.name];\n return newprop;\n }),\n type: EcoJsonSchemaArray.tag,\n value: this.schema.value || []\n }\n })\n );\n });\n }, 0);\n }", "function valueChanged() {\n debug && console.log( \"ManageWorkOrderRepairDetails: value changed\" );\n JSONData.setUnsavedChanges( true, \"manageWorkOrderSave\" );\n }", "onMasterDataChanged({ action, changes }) {\n const me = this;\n\n if (action === 'update') {\n // if a field not defined in chainedFields is changed, ignore the change.\n // there is no need to refilter the store in such cases, the change will be available anyhow since data is\n // shared\n const refilter = me.chainedFields && me.chainedFields.some((field) => field in changes);\n\n if (!refilter) return;\n }\n\n me.fillFromMaster();\n }", "modelChanged(newValue, oldValue) {\n this.changes.model = newValue;\n requestUpdate(this);\n }", "function onChanged() {\n let g = getGlobal();\n\n //When the add-in creates the table, it will generate 4 events that we must ignore.\n //We only want to respond to the change events from the user.\n if (g.tableEventCount > 0) {\n g.tableEventCount--;\n return; //count down to throw away events caused by the table creation code\n }\n\n //check if dirty flag was set (flag avoids extra unnecessary ribbon operations)\n if (!g.isTableDirty) {\n g.isTableDirty = true;\n\n //Enable the Refresh and Submit buttons\n setSyncButtonEnabled(true);\n }\n}", "afterChange(toSet, wasSet, silent, fromRelationUpdate, skipAccessors) {\n this.stores.forEach(store => {\n store.onModelChange(this, toSet, wasSet, silent, fromRelationUpdate);\n });\n }", "elementUpdated() {\n this.model.trigger('el:change');\n }", "onRestore() {\n this._updateModels();\n }", "onRecordChanged() {\n var record = this.record;\n // Calls to get foreign key records\n var calls = [];\n // Clear inputs\n this.inputs.clear();\n if (record) {\n // Call form creating\n //TODO: onFormCreating should com from an interface or something\n if (record['onFormCreating']) {\n record['onFormCreating'](this);\n }\n // Extract metadata\n var metadata = record.getMetadata();\n // Scan metadata\n if (metadata && metadata.fields) {\n for (var i in metadata.fields) {\n var field = metadata.fields[i];\n if (latte._isString(this.category) && this.category.length == 0 && !field['category']) {\n }\n else if (latte._isString(this.category) && (field['category'] != this.category)) {\n // debugger;\n continue;\n }\n var input = latte.InputItem.fromIInput(field, i);\n var value = latte._undef(record[i]) ? null : record[i];\n // input.text = field.text ? field.text : i;\n // input.type = field.type ? field.type : 'string';\n // input.name = i;\n // input.readOnly = field['readonly'] === true || field['readOnly'] === true;\n // input.options = field['options'];\n input.tag = i;\n input.visible = field['visible'] !== false;\n input.separator = field['separator'] === true;\n if (latte._isString(field['visible'])) {\n if (field['visible'] === 'if-inserted') {\n input.visible = record.inserted();\n }\n else if (field['visible'] === 'if-not-inserted') {\n input.visible = !record.inserted();\n }\n }\n // Check for fieldString declaration when read-only\n if (input.readOnly && record[i + 'String']) {\n input.value = record[i + 'String'];\n }\n else {\n input.value = value; //value !== null ? value : field['defaultValue'];\n }\n if (field.type == 'record') {\n // Get record value item\n var d = input.valueItem;\n // Assign loader function\n d.loaderFunction = field.loaderFunction;\n // If not record as value, load it in call\n if (value && field['recordType'] && !(value instanceof latte.DataRecord)) {\n ((d, input) => {\n var params = {\n name: field['recordType'],\n id: value\n };\n var dummy = new latte[params.name]();\n if (latte._isString(dummy['_moduleName'])) {\n params['module'] = dummy['_moduleName'];\n }\n calls.push(new latte.RemoteCall('latte.data', 'DataLatteUa', 'recordSelect', params).withHandlers((r) => {\n //log(\"Arrived foreign key record:\")\n //log(r)\n if (r && r.recordId) {\n d.setRecordSilent(r);\n input.value = input.value;\n }\n }));\n })(d, input);\n }\n }\n this.inputs.add(input);\n }\n }\n //TODO: onFormCreated should come from an interface or something\n if (record['onFormCreated']) {\n record['onFormCreated'](this);\n }\n /**\n * Send calls if any\n */\n if (calls.length > 0) {\n latte.Message.sendCalls(calls);\n }\n }\n if (this._recordChanged) {\n this._recordChanged.raise();\n }\n }", "function updateWhenChangeType(e){\n\t$inputs = $(e).parents('table').find('input.dataInput');\n\t$.each($inputs,function(){\n\t\tcalculateInput($(this));\n\t});\n}", "static onUpdateData(col, fn) {\n db.collection(col).onSnapshot(snapshot => {\n snapshot.docChanges().forEach(change => {\n if (change.type === 'modified') fn();\n });\n });\n }", "validateBeforeUpdate (id, newData, prevData) { return true }", "handleChange() {\n this.forceUpdate();\n }", "on_update_data(data, meta) {\n time_error(`Widget ${this.name} (${this.typename}) does not implement on_update_data()`)\n }" ]
[ "0.6944443", "0.623674", "0.61815137", "0.6136637", "0.60225576", "0.59741586", "0.59573615", "0.57878226", "0.57763386", "0.5747086", "0.57308257", "0.5724112", "0.572185", "0.56812304", "0.56565136", "0.55925477", "0.558366", "0.5545544", "0.5545084", "0.5531364", "0.5515506", "0.54882646", "0.5483407", "0.54736537", "0.54714715", "0.5468218", "0.54531026", "0.54454064", "0.5430955", "0.5420578" ]
0.6816064
1
store mpw for autodecryption for autofilling option
function tmpStoreMPW(){ // browser.storage.sync.get("mpw").then(function(res){ // if(res['mpw'] == CryptoJS.SHA512($('#modalInputMPW').val()).toString()){ // SM.setMPW($('#modalInputMPW').val()); // $('#modalMPW').modal('hide'); // // activate checkbox // $('#pref_autofill_password').prop('checked', true); // SM.updatePreferences('pref_autofill_password', true); // }else{ // alert("Entered password was not correct."); // } // }); doChallenge($('#modalInputMPW').val(), function(){ SM.setMPW($('#modalInputMPW').val()); $('#modalMPW').modal('hide'); // activate checkbox $('#pref_autofill_password').prop('checked', true); SM.updatePreferences('pref_autofill_password', true); }, function(){ alert("Entered password was not correct."); } ); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function saveForPW(getPw) {\n const encryptPw = encrypt(getPw);\n localStorage.setItem(PW_LS, encryptPw);\n}", "function withMPDpref(str) { return 'mpd/'+MPD.password+'/'+str; }", "function encryptorInit() {\n var lock = document.getElementById(\"js-lock\");\n lock.addEventListener(\"click\", promptForKey);\n var key = localStorage.getItem(KEY_PHRASE);\n if (!key) {\n promptForKey();\n }\n}", "function u(t) {\n const n = t.getResponseHeader('IG-Set-Password-Encryption-Web-Key-Id')\n , s = t.getResponseHeader('IG-Set-Password-Encryption-Web-Key-Version')\n , o = t.getResponseHeader('IG-Set-Password-Encryption-Web-Pub-Key');\n n && o && s && r(d[8]).setEncryptionKeys(n, o, s)\n}", "autocryptSetupPasswd(window, dlgMode, passwdType = \"numeric9x4\", password) {\n if (!window) {\n window = this.getBestParentWin();\n }\n\n let inputObj = {\n password: null,\n passwdType,\n dlgMode,\n };\n\n if (password) {\n inputObj.initialPasswd = password;\n }\n\n window.openDialog(\n \"chrome://openpgp/content/ui/autocryptSetupPasswd.xhtml\",\n \"\",\n \"dialog,modal,centerscreen\",\n inputObj\n );\n\n return inputObj.password;\n }", "function createCryptogram(){\n vm.cipher = {};\n if(vm.quote){\n killGuess().then(function(){\n $meteor.call('createCryptogram', vm.quote).then(function(result){\n if(result){\n var answer = vm.quote.toLowerCase().slice(0);\n vm.result = result;\n\n vm.cipher = {};\n _.each(answer, function(val, index){\n if(cryptogramService.isLetter(val))\n vm.cipher[result[index]] = val;\n });\n\n changeQuoteHeader();\n vm.currentQuote = vm.buildingQuote;\n }\n }, function(err){\n console.log('err', err);\n });\n }, function(err){\n console.log(err);\n });\n }else{\n vm.currentQuote = vm.needQuote;\n }\n }", "function savePassword(pw) {\n\tIPCRenderer.sendToHost('config', {\n\t\tkey: 'walletPassword',\n\t\tvalue: pw,\n\t});\n}", "function getPassword() {\n if (hasTextEncoder) {\n document.getElementById('create_button').style.display = 'none';\n document.getElementById('passphrase').style.display = 'block';\n }\n else {\n setupKeys();\n }\n}", "function writePassword() {\n var passwordLen = getpasswordLength();\n var options = getPasswordOptionSet();\n\n\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = makePassword(passwordLen, options);\n\n\n}", "function generatePass(plength) {\n $('.genPassConf').css('display', 'block');\n $('#pass-generate').html('').css('display', 'none');\n var keylistalpha = \"abcdefghijklmnopqrstuvwxyz\";\n var keylistint = \"0123456789\";\n var keylistspec = \"!@#_{}[]&*^%\";\n var temp = '';\n var len = plength / 2;\n var len = len - 1;\n var lenspec = plength - len;\n for (i = 0; i < len; i++)\n temp += keylistalpha.charAt(Math.floor(Math.random() * keylistalpha.length));\n for (i = 0; i < lenspec; i++)\n temp += keylistspec.charAt(Math.floor(Math.random() * keylistspec.length));\n for (i = 0; i < len; i++)\n temp += keylistint.charAt(Math.floor(Math.random() * keylistint.length));\n temp = temp.split('').sort(function () {\n return 0.5 - Math.random()\n }).join('');\n $('.pass').val(temp);\n return temp;\n}", "function writePassword() {\n document.getElementById(\"password\").value = \"\";\n\n generator(customChar);\n}", "function encryptGameWord() {\r\n if (level < stages.length - 1) {\r\n encryptedGameWord = encryption.iterateString(gameWord, gameShift, true);\r\n }\r\n else {\r\n gameKey = encryption.convertKeyToNumbers(finalStageKeys[0]);\r\n encryptedGameWord = encryption.iterateVigenereString(gameWord, gameKey, false);\r\n\r\n }\r\n }", "function writePassword() {\n let newOptions = { ...options };\n setOptions(newOptions);\n var password = generatePassword(newOptions);\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n}", "function generatePassPhrase() {\n\n var s = new Uint16Array(WORDCOUNT);\n var phrase_words = [];\n\n var bytes = forge.random.getBytesSync(2*WORDCOUNT);\n for(var n=0; n < WORDCOUNT; n++)\n {\n var idx = (bytes.charCodeAt(n*2) & 0x7) << 8;\n idx = idx | bytes.charCodeAt(n*2+1) & 0xFF;\n\n phrase_words.push(words[idx]);\n }\n\n var phrase = phrase_words.join(' ');\n $('#put_passphrase').text(phrase);\n}", "function Generate_seed() {\n \tvar i, j, k = \"\";\n\n\taddEntropyTime();\n\tvar seed = keyFromEntropy();\n\n \tvar prng = new AESprng(seed);\n\tif (document.seed.keytype[0].checked) {\n\t //\tText key\n\t var charA = (\"A\").charCodeAt(0);\n\n\t for (i = 0; i < 12; i++) {\n\t\tif (i > 0) {\n\t \t k += \"-\";\n\t\t}\n\t\tfor (j = 0; j < 5; j++) {\n\t \t k += String.fromCharCode(charA + prng.nextInt(25));\n\t\t}\n\t }\n\t} else {\n\t // Hexadecimal key\n\t var hexDigits = \"0123456789ABCDEF\";\n\n\t for (i = 0; i < 64; i++) {\n\t \tk += hexDigits.charAt(prng.nextInt(15));\n\t }\n\t}\n \tdocument.seed.text.value = k;\n\tdelete prng;\n }", "function writePassword() {\n\tvar params = {\n\t\tlowercase: confirm('Would you like to use lowercase characters?'),\n\t\tuppercase: confirm('Would you like to use uppercase characters?'),\n\t\tspecialChars: confirm('Would you like to use special characters?'),\n\t\tnumericChars: confirm('Would you like to use numeric characters?'),\n\t};\n\twhile (params.length < 8 || params.length > 128 || params.length === undefined) {\n\t\tparams.length = parseInt(prompt('How long would you like your password to be? Greater than 8 Less than 128'));\n\t}\n\tvar password = generatePassword(params);\n\tvar passwordText = document.querySelector('#password');\n\n\tpasswordText.value = password;\n}", "function generatePassword() {\n return 'generatepwfx';\n}", "function writeEncryptedWord() {\r\n if (level < stages.length - 1) {\r\n $(\"#game-word\").text(encryptedGameWord);\r\n }\r\n else {\r\n $(\"#game-word\").text(encryptedGameWord);\r\n }\r\n }", "function writePassword() {\n var genPassword = generatePassword();\n var passwordText = document.querySelector('#password');\n passwordText.value = genPassword;\n}", "function writePassword() {}", "function writePassword() {\n const characterAmount = charAmountNumber.value;\n const includeLowercase = includeLowercaseElement.checked\n const includeUppercase = includeUppercaseElement.checked\n const includeNumbers = includeNumbersElement.checked\n const includeSymbols = includeSymbolsElement.checked\n\n const password = generatePassword(characterAmount, includeLowercase, \n includeUppercase, includeNumbers, includeSymbols);\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n\n}", "function set_pwd(value) {\n old_pwd = $('#I_GE1_WIDTH').val();\n $('#I_GE1_WIDTH').val(value);\n if (!check_value(\"I_GE1_WIDTH\")){\n $('#I_GE1_WIDTH').val(old_pwd);\n $('#I_OPE_STEP2_GE1_PWD').val(old_pwd);\n return false;\n }\n commands = '\"GEN C1:BSWV WIDTH,' + parseFloat(value) + '\",\"GEN C1:OUTP?\",\"GEN C1:BSWV?\"';\n to_refresh = generator_ch1_parameters\n input_disable(to_refresh, generator_ch1_buttons);\n laserServer(commands, to_refresh, 0,\n function() {\n input_enable(to_refresh, generator_ch1_buttons);\n }\n );\n}", "function writePassword() {\n var editBoxPrompts = getPrompts();\n if (editBoxPrompts) {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n }\n}", "function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector('#password');\n passwordText.value = password;\n charset = \"\";\n}", "function encryption(){\n this.saltrounds = 10;\n this.rawtext = '';\n this.encryptedword = '';\n}", "function writePassword() {\n var password = generatepassword();\n var passwordText = document.querySelector(\"#password\");\n\n\n\n passwordText.value = password;\n\n copyBtn.removeAttribute(\"disabled\");\n copyBtn.focus();\n}", "function writePassword() {\n var password = passWordGen();\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n\n}", "function gen_op_iwmmxt_set_mup()\n{\n gen_opc_ptr.push({func:op_iwmmxt_set_mup});\n}", "function generateCipher() { \n let input = id('input-text');\n let cipherType = id('cipher-type').value;\n let output = '';\n let result = id('result');\n if (cipherType == 'shift') {\n output = shiftCipher(input.value);\n } else {\n output = customCipher(input.value);\n }\n result.innerHTML = output;\n }", "function writePassword() {\n \n\n arraySplit = \"\"; \n exitApplication = false; \n userInput = \"\"; \n finalPassword = \"\"; \n displayPassword = \"\"; \n window.alert(\" Lets check our password criteria options\");\n var password = generatePassword(); //different method\n \n var pLength = passlength();\n \n displayPassword = generatePasswordRandomness(userInput,pLength);\n\n\n var passwordText = document.querySelector(\"#password\"); \n \n \n document.getElementById(\"password\").readOnly = false; \n document.getElementById(\"password\").value = displayPassword; \n document.getElementById(\"password\").readOnly = true; \n\n}" ]
[ "0.6445947", "0.6183979", "0.5619672", "0.5609375", "0.55957896", "0.55320203", "0.54935944", "0.5448543", "0.5413816", "0.5399494", "0.53948253", "0.53691214", "0.53690016", "0.53467315", "0.53451246", "0.5340745", "0.533906", "0.5338819", "0.53238666", "0.5320482", "0.5318158", "0.5292451", "0.5290681", "0.52896655", "0.52827114", "0.5276664", "0.52766144", "0.52742404", "0.52737355", "0.5261559" ]
0.6788386
0
Sets the list of current transformations to the bundler.
_setTransformations() { // traverse items in the reversed order var currentIndex = this._browserifyTransformations.length - 1; while (currentIndex >= 0) { const currentTransformation = this._browserifyTransformations[currentIndex]; currentIndex--; if (!currentTransformation || typeof (currentTransformation) !== 'object' || typeof (currentTransformation.transform) !== 'function') { this._eventBus.emit('warn', 'The browserify transformation has an incorrect interface, skipping...'); continue; } this._appBundler.transform( currentTransformation.transform, currentTransformation.options ); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_setTransformations() {\n\t\t// traverse items in the reversed order\n\t\tvar currentIndex = this._browserifyTransformations.length - 1;\n\n\t\twhile (currentIndex >= 0) {\n\t\t\tconst currentTransformation = this._browserifyTransformations[currentIndex];\n\t\t\tcurrentIndex--;\n\t\t\tif (!currentTransformation ||\n\t\t\t\ttypeof (currentTransformation) !== 'object' ||\n\t\t\t\ttypeof (currentTransformation.transform) !== 'function') {\n\t\t\t\tthis._eventBus.emit('warn', 'The browserify transformation has an incorrect interface, skipping...');\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis._bundler.transform(\n\t\t\t\tcurrentTransformation.transform, currentTransformation.options\n\t\t\t);\n\t\t}\n\t}", "initTransformations() {\n this.transformations = [];\n\n for (var key in this.graph.transformations) {\n if (this.graph.transformations.hasOwnProperty(key)) {\n var transformation = this.graph.transformations[key];\n\n //calculate the trnasformation matrix\n let matrix = mat4.create();\n for (let transf of transformation.transformations) {\n switch (transf.type) {\n case \"translate\":\n mat4.translate(matrix, matrix, vec3.fromValues(transf.x, transf.y, transf.z));\n break;\n case \"rotate\":\n switch (transf.axis) {\n case \"x\":\n mat4.rotateX(matrix, matrix, DEGREE_TO_RAD * transf.angle);\n break;\n case \"y\":\n mat4.rotateY(matrix, matrix, DEGREE_TO_RAD * transf.angle);\n break;\n case \"z\":\n mat4.rotateZ(matrix, matrix, DEGREE_TO_RAD * transf.angle);\n break;\n }\n break;\n case \"scale\":\n mat4.scale(matrix, matrix, vec3.fromValues(transf.x, transf.y, transf.z));\n break;\n default:\n break;\n }\n }\n\n this.transformations[key] = matrix;\n }\n }\n }", "set transform(value) {}", "set transform(value) {}", "set transform(value) {}", "set transform(value) {}", "_setTransform(transform){\n this._element.setAttribute('transform',transform);\n }", "setTransform(valueNew){let t=e.ValueConverter.toObject(valueNew);if(null===t&&(t=this.getAttributeDefaultValueInternal(\"Transform\")),t&&!Array.isArray(t))return void(TCHMI_CONSOLE_LOG_LEVEL>=1&&e.Log.error(\"[Source=Control, Module=TcHmi.Controls.System.TcHmiControl, Id=\"+this.getId()+\", Attribute=Transform] Non array values are not supported.\"));let r=this.__objectResolvers.get(\"transform\");r&&(r.watchDestroyer&&r.watchDestroyer(),r.resolver.destroy());let s=new e.Symbol.ObjectResolver(t);this.__objectResolvers.set(\"transform\",{resolver:s,watchCallback:this.__onResolverForTransformWatchCallback,watchDestroyer:s.watch(this.__onResolverForTransformWatchCallback)})}", "function setRotation()\n {\n vm.moverStyle['-ms-transform'] = vm.moverStyle['-webkit-transform'] = vm.moverStyle.transform = vm.themeStyle.transform;\n }", "refreshTransforms() {\n const matrix = this.getTransformMatrix();\n this._translateTransform.update(matrix);\n this._rotateTransform.update(matrix);\n this._scaleTransform.update(matrix);\n }", "function setTransform(target, transform) {\n\n\t\t\ttarget.css({'-webkit-transform': transform, \n\t\t\t'-moz-transform': transform,\n\t\t\t'-ms-transform':transform,\n\t\t\t'-o-transform': transform,\n\t\t\t'transform': transform});\n\t\t}", "constructor() {\n super();\n\n this.transforms = [];\n }", "function setLightSensitives(){\n\ttransformables = new Array(\"ul\", \"li\", \"a.selected\", \"div.tabContent\", \"#pageContainer\", \"#mainHeader\");\n}", "apply() {\n this.scene.multMatrix(this.animTransform);\n }", "setTransform() {\n var plus = (1 + Math.cos(this.turnover * Math.PI / 2)) / 2;\n var minus = (-1 + Math.cos(this.turnover * Math.PI / 2)) / 2;\n var cos = Math.cos(this.deg / 180 * Math.PI);\n var sin = Math.sin(this.deg / 180 * Math.PI);\n var a = plus * cos - minus * sin;\n var b = plus * sin + minus * cos;\n var c = minus * cos - plus * sin;\n var d = minus * sin + plus * cos;\n var s = 'matrix(' + a + ', ' + b + ', ' + c + ', ' + d + ', 0, 0)';\n this.canvas.style.transform = s;\n this.back.style.transform = s;\n }", "apply() {\n this.scene.multMatrix(this.transfMatrix);\n }", "init() {\n if (this.initialized) {\n return;\n }\n /* precompile transform patterns */\n this.transformers = this.precompileTransformers(this.config.transform || {});\n this.initialized = true;\n }", "setTransformationMatrixValue() {\n this._hasTransformationMatrix = true;\n }", "recalculateTransformation() {\n Node.prototype.recalculateTransformation.call(this);\n\n if (this.rendered) {\n this.skeleton.update();\n this.bucket.updateBoneTexture[0] = 1;\n } else {\n this.addAction(() => this.recalculateTransformation(), []);\n }\n }", "function setTransform(elem, transforms) {\n // transforms can be a transform object, a string or an array of transform objects\n elem.removeAttribute('transform');\n if (isString(transforms)) {\n elem.setAttribute('transform', transforms);\n return getTransform(elem);\n }\n if (!isArray(transforms)) {\n transforms = [transforms];\n }\n elem.setAttribute('transform',\n transforms.map(function(t) {\n return t.type + '(' + t.values.join() + ')';\n }).join(' ')\n );\n return transforms;\n}", "applyCurrentTransform () {\n this.tempPosition.set(this.position);\n this.tempOrientation = this.orientation;\n this.tempScale.set(this.scale);\n }", "function setTran(Tx) {\r\n context.setTransform(Tx[0],Tx[1],Tx[3],Tx[4],Tx[6],Tx[7]);\r\n }", "updateTransform(newTransform) {\n transform = newTransform;\n isCanvasDirty = true;\n }", "async transform() {\n if (this.options.minify) {\n await uglify(this);\n }\n }", "set transformPaths(value) {}", "function setOrigin()\n {\n vm.moverStyle['-webkit-transform'] =\n vm.moverStyle['-ms-transform'] =\n vm.moverStyle.transform =\n vm.themeStyle.transform;\n //vm.element.tag == 'text' ? vm.element.style.transform : vm.themeStyle.transform;\n }", "merge() {\n this.assets.push(this.files.merge(this.data.output, this.data.babel));\n }", "function setTransform(element, value) {\n element.style[\"WebkitTransform\"] = value;\n element.style[\"webkitTransform\"] = value; // I'm not even sure if it's `Webkit` or `webkit`\n element.style[\"MozTransform\"] = value;\n element.style[\"MSTransform\"] = value;\n element.style[\"OTransform\"] = value;\n element.style.transform = value;\n }", "_initTransformValues() {\n this.rotation = new Vec3();\n this.rotation.onChange(() => this._applyRotation());\n\n // initial quaternion\n this.quaternion = new Quat();\n\n // translation in viewport coordinates\n this.relativeTranslation = new Vec3();\n this.relativeTranslation.onChange(() => this._setTranslation());\n\n // translation in webgl coordinates\n this._translation = new Vec3();\n\n // scale is a Vec3 with z always equal to 1\n this.scale = new Vec3(1);\n this.scale.onChange(() => {\n this.scale.z = 1;\n this._applyScale();\n });\n\n // set plane transform origin to center\n this.transformOrigin = new Vec3(0.5, 0.5, 0);\n this.transformOrigin.onChange(() => {\n // set transformation origin relative to world space as well\n this._setWorldTransformOrigin();\n this._updateMVMatrix = true;\n });\n }", "function clear() {\n transforms = {};\n}" ]
[ "0.7263447", "0.547929", "0.5444356", "0.5444356", "0.5444356", "0.5444356", "0.53676915", "0.530141", "0.5230234", "0.52164245", "0.5198078", "0.51966965", "0.5159227", "0.5158514", "0.5147033", "0.5098097", "0.5061689", "0.50538903", "0.5000126", "0.4947076", "0.49207065", "0.48994502", "0.48962262", "0.48952618", "0.48912343", "0.4889531", "0.4853975", "0.48383337", "0.4834342", "0.48115933" ]
0.7211117
1
Sets the list of current plugins to the bundler.
_setPlugins() { var currentIndex = this._browserifyPlugins.length - 1; while (currentIndex >= 0) { const currentPlugin = this._browserifyPlugins[currentIndex]; currentIndex--; if (!currentPlugin || typeof (currentPlugin) !== 'object' || typeof (currentPlugin.plugin) !== 'function') { this._eventBus.emit('warn', 'The browserify plugin has an incorrect interface, skipping...'); continue; } this._appBundler.plugin( currentPlugin.plugin, currentPlugin.options ); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_setPlugins() {\n\t\tvar currentIndex = this._browserifyPlugins.length - 1;\n\n\t\twhile (currentIndex >= 0) {\n\t\t\tconst currentPlugin = this._browserifyPlugins[currentIndex];\n\t\t\tcurrentIndex--;\n\t\t\tif (!currentPlugin ||\n\t\t\t\ttypeof (currentPlugin) !== 'object' ||\n\t\t\t\ttypeof (currentPlugin.plugin) !== 'function') {\n\t\t\t\tthis._eventBus.emit('warn', 'The browserify plugin has an incorrect interface, skipping...');\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis._bundler.plugin(\n\t\t\t\tcurrentPlugin.plugin, currentPlugin.options\n\t\t\t);\n\t\t}\n\t}", "static set PLUGINS(plugins) {\n PLUGINS = plugins;\n }", "addPlugins(...plugins) {\n InstancePlugin.initPlugins(this, ...plugins);\n }", "addPlugins(...plugins) {\n InstancePlugin.initPlugins(this, ...plugins);\n }", "_setPlugins() {\n this.config.plugins = {\n // Systems\n global: [\n { key: 'RoomSystem', plugin: Systems.RoomSystem, start: false, mapping: 'rooms' },\n { key: 'CursorSystem', plugin: Systems.CursorSystem, start: false, mapping: 'cursors' }\n ],\n // Managers\n scene: [\n { key: 'UpdateManager', plugin: Managers.UpdateManager, mapping: 'updates' },\n { key: 'LightSourceManager', plugin: Managers.LightSourceManager, mapping: 'lightSources' },\n { key: 'LayerManager', plugin: Managers.LayerManager, mapping: 'layers' }\n ]\n };\n }", "registerPlugins() {\r\n _(this.plugins)\r\n .pickBy(plugin => {\r\n return plugin.register;\r\n })\r\n .forEach(plugin => {\r\n this.slickGrid.registerPlugin(plugin.plugin);\r\n });\r\n }", "function initPlugins() {\n\t\tFs.readdir(plugPath, function (err, pluginNames) {\n\t\t\tif (err) {\n\t\t\t\tconsole.log(err);\n\t\t\t}\n\n\t\t\t// Determine default plugin\n\t\t\tsetOrder(pluginNames);\n\t\t\t\n\t\t\t// Initialize each plugin according to config\n\t\t\tpluginNames.forEach(addPlugin);\n\t\t});\n\t}", "loadAll() {\n logger.info(`Loading plugins...`);\n\n const pluginPath = path.join(__dirname, '..', '..', 'plugins');\n if (!fse.existsSync(pluginPath)) {\n fse.emptyDirSync(pluginPath);\n logger.error(`Plugin directory not found! Creating one...`);\n process.exit(0);\n }\n\n const plugins = this.constructor._read(pluginPath);\n for (const plugin of plugins) this._registerPlugin(require(plugin));\n\n this._emitCommandsd();\n logger.info(`Loaded ${this.plugins.size} plugin(s)!`);\n }", "addPlugins() {\n const pm = PluginManager.getInstance();\n pm.addPlugin(new ElectronPlugin());\n }", "constructor() {\n\n /**\n * @type {Array<Plugin>} the list of plugins which this object manages.\n */\n this.pluginList = [];\n }", "initPlugins() {}", "initPlugins() {}", "function registerPresets(newPresets) {\n Object.keys(newPresets).forEach(function (name) {\n return registerPreset(name, newPresets[name]);\n });\n } // All the plugins we should bundle", "orderPlugins() {\r\n debug('orderPlugins:before', this.pluginNames);\r\n const runLast = this._plugins\r\n .filter(p => p.requirements.has('runLast'))\r\n .map(p => p.name);\r\n for (const name of runLast) {\r\n const index = this._plugins.findIndex(p => p.name === name);\r\n this._plugins.push(this._plugins.splice(index, 1)[0]);\r\n }\r\n debug('orderPlugins:after', this.pluginNames);\r\n }", "get plugins() {\n return this._plugins;\n }", "function init() {\n var _this = this;\n\n this._get('options').plugins.forEach(function (plugin) {\n // check if plugin definition is string or object\n var Plugin = undefined;\n var pluginName = undefined;\n var pluginOptions = {};\n if (typeof plugin === 'string') {\n pluginName = plugin;\n } else if ((typeof plugin === 'undefined' ? 'undefined' : babelHelpers.typeof(plugin)) === 'object') {\n pluginName = plugin.name;\n pluginOptions = plugin.options || {};\n }\n\n Plugin = find(pluginName);\n _this._get('plugins')[plugin] = new Plugin(_this, pluginOptions);\n\n addClass(_this._get('$container'), pluginClass(pluginName));\n });\n }", "getPlugins() {\n return this.plugins;\n }", "updateAll(state) {\n this.iteratePlugins(plugin => {\n plugin.update(state);\n });\n }", "function getPlugins() {\n return plugins;\n}", "registerPlugin(plugin, handlePlugins) {\n const plugins = isFunction(handlePlugins) ? handlePlugins(plugin, [...this.state.plugins]) : [...this.state.plugins, plugin];\n const state = this.state.reconfigure({ plugins });\n this.view.updateState(state);\n }", "function registerPlugins(newPlugins) {\n Object.keys(newPlugins).forEach(function (name) {\n return registerPlugin(name, newPlugins[name]);\n });\n }", "function pullPlugins(preset) {\n plugins.push(...preset.plugins);\n if (Array.isArray(preset.presets)) {\n preset.presets.forEach(p => pullPlugins(p));\n }\n }", "function initPlugins(model, esriMap) {\n var mapModel = model.get('mapModel'),\n regionData = model.get('regionData');\n\n model.get('plugins').each(function (pluginModel) {\n var stateOfPlugin = model.get('stateOfPlugins')[pluginModel.name()];\n\n pluginModel.initPluginObject(regionData, mapModel, esriMap);\n if (stateOfPlugin) {\n pluginModel.setState(stateOfPlugin);\n }\n });\n }", "_initPlugins() {\n this.plugins.forEach(plugin => {\n if (plugin === 'ubiety-custom-texture' && !this.customTextureModule) {\n this.customTextureModule = new UbietyCustomTexture('ubiety-custom-texture', this, 'umjs-texture-factory');\n }\n else if (plugin === 'ubiety-text-editor' && !this.customTextEditorModule) {\n this.customTextEditorModule = new UbietyCustomTexture('ubiety-text-editor', this, 'umjs-text-image-factory');\n }\n else {\n console.error('Ubiety:: Either a plugin can\\'t be recognised, or it already exists.');\n }\n });\n }", "function handlePluginsObject(path, moduleList) {\n // Now inject the scripts.\n var scriptCounter = moduleList.length;\n\n if (!scriptCounter) {\n finishPluginLoading();\n return;\n }\n function scriptLoadedCallback() {\n if (!--scriptCounter) {\n onScriptLoadingComplete(moduleList);\n }\n }\n\n for (var i = 0; i < moduleList.length; i++) {\n injectScript(path + moduleList[i].file, scriptLoadedCallback);\n }\n}", "get plugins () {\n return this._chain.reduce(\n (plugins, {config}) => config.plugins\n ? plugins.concat(config.plugins)\n : plugins,\n []\n )\n }", "function initPlugins() {\n Vue.use(Vuex);\n Vue.use(VueRouter);\n Vue.use(VueI18n);\n Vue.use(DeviceHelper);\n Vue.use(VueMeta);\n Vue.use(SanitizePlugin);\n }", "function handlePluginsObject(path, moduleList, finishPluginLoading) {\n // Now inject the scripts.\n var scriptCounter = moduleList.length;\n\n if (!scriptCounter) {\n finishPluginLoading();\n return;\n }\n function scriptLoadedCallback() {\n if (!--scriptCounter) {\n onScriptLoadingComplete(moduleList, finishPluginLoading);\n }\n }\n\n for (var i = 0; i < moduleList.length; i++) {\n injectIfNecessary(moduleList[i].id, path + moduleList[i].file, scriptLoadedCallback);\n }\n}", "function registerPlugins(newPlugins) {\n\t Object.keys(newPlugins).forEach(function (name) {\n\t return registerPlugin(name, newPlugins[name]);\n\t });\n\t}", "function registerPlugins(newPlugins) {\n\t Object.keys(newPlugins).forEach(function (name) {\n\t return registerPlugin(name, newPlugins[name]);\n\t });\n\t}" ]
[ "0.8004924", "0.6818906", "0.6514046", "0.6487034", "0.6434609", "0.624967", "0.5965147", "0.58423436", "0.58362955", "0.57685685", "0.5765481", "0.5765481", "0.56770015", "0.56763065", "0.5641679", "0.5604519", "0.5581039", "0.55783546", "0.55635864", "0.55555177", "0.5523985", "0.5465447", "0.5447501", "0.5442954", "0.54285115", "0.53695494", "0.53048044", "0.52920806", "0.5290726", "0.5290726" ]
0.7972612
1
avant toute collision avec le pnj
function rencontre(pnj, textePnj) { // fonction gérant la collision avec un pnj if (joueur.posX + joueur.largeur > pnj.posX2 && joueur.posX - tailleTuile < pnj.posX2 && joueur.posY + joueur.hauteur > pnj.posY2 && joueur.posY - tailleTuile < pnj.posY2) { console.log(pnj.name); switch(dir) { // on va évaluer la direction du personnage joueur case 1: joueur.posX -= 1; // on enlève 1 à la position posX du joueur pour qu'il se décale horizontalement par rapport au pnj // pnj.v=0; // on arrête le déplacement du pnj en mettant sa vitesse à 0 // dirPnj=0; // on le fait regarder de face break; case 2: joueur.posX += 1; // on ajoute 1 à la position posX du joueur pour qu'il se décale horizontalement par rapport au pnj // pnj.v=0; //on arrête le déplacement du pnj en mettant sa vitesse à 0 // dirPnj=0; // on le fait regarder de face break; case 0: joueur.posY -= 1; // on enlève 1 à la position posY du joueur pour qu'il se décale verticalement par rapport au pnj // pnj.v=0; //on arrête le déplacement du pnj en mettant sa vitesse à 0 // dirPnj=0; // on le fait regarder de face break; case 3: joueur.posY += 1; // on ajoute 1 à la position posY du joueur pour qu'il se décale verticalementement par rapport au pnj // pnj.v=0; //on arrête le déplacement du pnj en mettant sa vitesse à 0 // dirPnj=0; // on le fait regarder de face break; } if (pnj.collision == 0) { bulleTexte(pnj.texte, pnj.posX2, pnj.posY2); // affiche une "bulle" de dialogue } pnj.collision += 1; // permettra de savoir ensuite qu'on a touché le pnj console.log(pnj.collision+" - pnj !"); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function collision (px,py,pw,ph,ex,ey,ew,eh){\nreturn (Math.abs(px - ex) *2 < pw + ew) && (Math.abs(py - ey) * 2 < ph + eh);\n \n}", "function collision(b, p) {\r\n //conocemos la altura del jugador\r\n p.top = p.y;\r\n //conocemos la parte inferior del jugador\r\n p.bottom = p.y + p.height;\r\n //la parte izquierda\r\n p.left = p.x;\r\n //la parte derecha\r\n p.right = p.x + p.width;\r\n\r\n //lo mismo con la bola\r\n b.top = b.y - b.radius;\r\n b.bottom = b.y + b.radius;\r\n b.left = b.x - b.radius;\r\n b.right = b.x + b.radius;\r\n\r\n //returnamos la poscion si esta pegado en izquierda, derecha, arriba y abajo esta chocando\r\n return (\r\n p.left < b.right && p.top < b.bottom && p.right > b.left && p.bottom > b.top\r\n );\r\n}", "function tester_collision1() {\n\tfor (var p=0; p<18; p++) {\n\n/* On test le contact de la sphère avec chaque sommet du mur de gauche */\n\t\tif (Math.sqrt(Math.pow(polygone[p][0]-xplayer1,2)+ Math.pow(polygone[p][1]-yplayer1,2)) < rayon) {\n\t\t\tcontinuer = false;\n\t\t\tbreak;\n\t\t}\n\n/* Idem avec le mur de droite */\n\t\tif (Math.sqrt(Math.pow(polygone[p][0]+largeur-xplayer1,2)+ Math.pow(polygone[p][1]-yplayer1,2)) < rayon ) {\n\t\t\tcontinuer = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\t \n}", "checkCollision( p2 )\r\n {\r\n let dist = this.p.subtract( p2.p );\r\n let distModule = dist.module();\r\n let distUnit = dist.normalized();\r\n if ( distModule < ( this.r + p2.r ) )\r\n {\r\n // componenti velocità parallele alla congiungente i centri delle particelle\r\n // prima dell'impatto\r\n let parallelV1 = this.v.parallelComponent( dist );\r\n let parallelV2 = p2.v.parallelComponent( dist );\r\n\r\n // componenti velocità perpendicolari alla congiungente i centri delle particelle\r\n // prima dell'impatto\r\n let perpendicularV1 = this.v.subtract( parallelV1 );\r\n let perpendicularV2 = p2.v.subtract( parallelV2 );\r\n\r\n // riposizionamento al punto di contatto\r\n let l = this.r + p2.r - distModule;\r\n let vRel = this.v.subtract( p2.v ).module();\r\n let k = - l / vRel;\r\n let s1 = parallelV1.multiply( k );\r\n let s2 = parallelV2.multiply( k );\r\n this.p = this.p.add( s1 );\r\n p2.p = p2.p.add( s2 );\r\n\r\n // componenti velocità parallele alla congiungente i centri delle particelle\r\n // dopo l'impatto\r\n let m1 = this.m;\r\n let m2 = p2.m;\r\n\r\n let u1 = parallelV1.dot( distUnit );\r\n let u2 = parallelV2.dot( distUnit );\r\n\r\n let v1 = ( ( m1 - m2 ) * u1 + 2 * m2 * u2 ) / ( m1 + m2 );\r\n let v2 = ( ( m2 - m1 ) * u2 + 2 * m1 * u1 ) / ( m1 + m2 );\r\n\r\n // componenti velocità perpendicolari alla congiungente i centri delle particelle\r\n // dopo l'impatto\r\n parallelV1 = distUnit.multiply( v1 );\r\n parallelV2 = distUnit.multiply( v2 );\r\n \r\n // velocità finali\r\n this.v = parallelV1.add( perpendicularV1 );\r\n p2.v = parallelV2.add( perpendicularV2 ); \r\n }\r\n }", "collision () {\n }", "collision(ptl, pbr) {//player dimensions\n //add the x first\n if(this.taken){ return false;}\n if ((ptl.x <this.bottomRight.x && pbr.x > this.pos.x) &&( ptl.y < this.bottomRight.y && pbr.y > this.pos.y)) {\n this.taken = true;\n return true;\n }\n return false;\n }", "function checkCollision(){\r\n\t//check se la macchina esce dalla pista\r\n\tif(center_carr[2]<-408)vz=0;\r\n\tif(center_carr[2]>109)vz=0;\r\n\t\r\n\tif(center_carr[0]<track_dimension[1])vz=0;\r\n\tif(center_carr[0]>track_dimension[0])vz=0;\r\n\t\r\n\t//check collisione con i booster\r\n\tif((center_carr[0]<2.3 && center_carr[0]>0) && (center_carr[2]>-10 && center_carr[2]<-6)) vz=vz*1.12;\r\n\tif((center_carr[0]<0 && center_carr[0]>-2.3) && (center_carr[2]>-35 && center_carr[2]<-31)) vz=vz*1.12;\r\n\tif((center_carr[0]<0 && center_carr[0]>-2.3) && (center_carr[2]>-48 && center_carr[2]<-44)) vz=vz*1.12;\r\n\tif((center_carr[0]<6 && center_carr[0]>4) && (center_carr[2]>-161 && center_carr[2]<-157)) vz=vz*1.12;\r\n\tif((center_carr[0]<3 && center_carr[0]>0.7) && (center_carr[2]>-184 && center_carr[2]<-180)) vz=vz*1.12;\r\n\tif((center_carr[0]<5.60 && center_carr[0]>3.18) && (center_carr[2]>-240 && center_carr[2]<-236)) vz=vz*1.12;\r\n\tif((center_carr[0]<5.60 && center_carr[0]>3.18) && (center_carr[2]>-251 && center_carr[2]<-247)) vz=vz*1.12;\r\n\tif((center_carr[0]<5.60 && center_carr[0]>3.18) && (center_carr[2]>-257 && center_carr[2]<-253)) vz=vz*1.12;\r\n\tif((center_carr[0]<7 && center_carr[0]>5) && (center_carr[2]>-290 && center_carr[2]<-286)) vz=vz*1.12;\r\n\tif((center_carr[0]<6&& center_carr[0]>3.8) && (center_carr[2]>-310 && center_carr[2]<-306)) vz=vz*1.15;\r\n\tif((center_carr[0]<3.6&& center_carr[0]>1.3) && (center_carr[2]>-331 && center_carr[2]<-327)) vz=vz*1.12;\r\n\t\r\n\t//check collisione con i debooster\r\n\tif((center_carr[0]<1.15 && center_carr[0]>-0.8) && (center_carr[2]>-113 && center_carr[2]<-109)) vz=vz*0.9;\r\n\tif((center_carr[0]<6 && center_carr[0]>3.6) && (center_carr[2]>-144 && center_carr[2]<-140)) vz=vz*0.9;\r\n\tif((center_carr[0]<3.25 && center_carr[0]>0.85) && (center_carr[2]>-170 && center_carr[2]<-166)) vz=vz*0.9;\r\n\tif((center_carr[0]<6.66 && center_carr[0]>4.6) && (center_carr[2]>-203 && center_carr[2]<-199)) vz=vz*0.9;\r\n\tif((center_carr[0]<2.81 && center_carr[0]>0.93) && (center_carr[2]>-222 && center_carr[2]<-218)) vz=vz*0.9;\r\n\tif((center_carr[0]<3.25 && center_carr[0]>1) && (center_carr[2]>-277 && center_carr[2]<-281)) vz=vz*0.9;\r\n\tif((center_carr[0]<7 && center_carr[0]>5) && (center_carr[2]>-300 && center_carr[2]<-296)) vz=vz*0.9;\r\n\t\r\n}", "function collision(b, p) {\r\n p.top = p.y;\r\n p.bottom = p.y + p.height;\r\n p.left = p.x;\r\n p.right = p.x + p.width;\r\n\r\n b.top = b.y - b.radius;\r\n b.bottom = b.y + b.radius;\r\n b.left = b.x - b.radius;\r\n b.right = b.x + b.radius;\r\n\r\n return (\r\n p.left < b.right && p.top < b.bottom && p.right > b.left && p.bottom > b.top\r\n );\r\n}", "function collisions() {\n collisonBords(ballon);\n\n equipes.forEach((eq) => {\n eq.joueurs.forEach((e) => {\n // Touche le cote droit\n collisonBords(e);\n });\n });\n\n let collision = false;\n\n // Pour toutes les equipes\n equipes.forEach((e) => {\n // Pour chaque joueur de chaque équipe\n e.joueurs.forEach((j) => {\n if (GestionnaireCollision.cercleCercle(j, ballon, j.rayon(), ballon.rayon())) {\n gererCollision(j, ballon);\n collision = true;\n }\n\n // Pour chaque équipe\n equipes.forEach((e2) => {\n // Chaque joueur de chaque équipe\n e2.joueurs.forEach((j2) => {\n if (j.x === j2.x && j.y === j2.y) {\n return;\n }\n\n if (GestionnaireCollision.cercleCercle(j, j2, j.rayon(), j2.rayon())) {\n collision = true;\n gererCollision(j, j2);\n }\n });\n });\n });\n });\n\n if (collision) {\n soundsManager.collisionJoueurs();\n }\n\n if (GestionnaireCollision.pointDansRectangle(map.cageGauche, ballon.centre())) {\n score.DROITE += 1;\n reset();\n soundsManager.but();\n } else if (GestionnaireCollision.pointDansRectangle(map.cageDroite, ballon.centre())) {\n score.GAUCHE += 1;\n reset();\n soundsManager.but();\n }\n }", "checkForCollision(ps) {\n if( ps !== null ) { \n for(let i = 0; i < this.collisionSX.length; i++ ) {\n if( ps.position.x >= this.collisionSX[i] && ps.position.x <= this.collisionEX[i] ) {\n if( ps.position.y >= this.collisionSY[i] && ps.position.y <= this.collisionEY[i] ) {\n //print(\"collsion at shape \" + i);\n return true;\n }\n }\n }\n }\n\n return false; \n }", "function CollisionCalculatorC2P(o1,pt) \n{\n var dx = pt.x - o1.x;\n var dy = pt.y - o1.y;\n\n var dist = Math.sqrt( Math.pow((pt.x-o1.x),2)+Math.pow((pt.y-o1.y),2));\n if(dist>o1.r) {\n return false;\n }\n return true;\n}", "checkCollision (playerPosition) {\n /*\n if (playerPosition[0] > this.position[0][0] && playerPosition[0] < this.position[0][1]) {\n if (playerPosition[1] > this.position[1][0] && playerPosition[1] < this.position[1][1]) {\n gameVar.gotGift = false;\n gameVar.checkCollision = false;\n gameVar.gotHit();\n }\n }\n */\n\n let er = 0;\n let ec = 0;\n let pr = 0;\n let pc = 0;\n\n /* player x position */\n if(player.x < 100){ pc = 0; }\n if(player.x >= 100 && player.x < 200){ pc = 1; } \n if(player.x >= 200 && player.x < 300){ pc = 2; }\n if(player.x >= 300 && player.x < 400){ pc = 3; }\n if(player.x >= 400){ pc = 4; }\n\n /* player y position */\n if(player.y < 72) { pr = 0; } \n if(player.y >= 72 && player.y < 154) { pr = 1; } \n if(player.y >= 154 && player.y < 236) { pr = 2; } \n if(player.y >= 236 && player.y < 318) { pr = 3; } \n if(player.y >= 318 && player.y < 400) { pr = 4; } \n if(player.y >= 400) { pr = 5; } \n\n /* enemy car x position + 10 buffer for easyer gameplay */\n if(this.x < -100){ ec = -1; }\n if(this.x >= -100 && this.x < 0){ ec = 0; } \n if(this.x >= 0 && this.x < 100){ ec = 1; } \n if(this.x >= 100 && this.x < 200){ ec = 2; }\n if(this.x >= 200 && this.x < 300){ ec = 3; }\n if(this.x >= 300 && this.x < 400){ ec = 4; }\n if(this.x >= 400){ ec = 5; }\n\n /* enemy car y position */\n if(this.y < 63) { er = 0; } \n if(this.y >= 63 && this.y < 143) { er = 1; } \n if(this.y >= 143 && this.y < 223) { er = 2; } \n if(this.y >= 223 && this.y < 303) { er = 3; } \n if(this.y >= 303 && this.y < 383) { er = 4; } \n if(this.y >= 383) { er = 5; } \n/*\n if (ec == 2) { \n alert(this.x.toString()); \n }\n*/\n if ((pc == ec) && (pr == er)) {\n gameVar.gotGift = false;\n gameVar.checkCollision = false;\n gameVar.gotHit();\n }\n }", "collision() {\n return this.sprite.overlap(player.sprite) && this.colour == player.colour;\n }", "checkCollision() { \n return (player.x < this.x + 80 &&\n player.x + 80 > this.x &&\n player.y < this.y + 60 &&\n 60 + player.y > this.y)\n }", "function collision(top_x, bottom_x, top_y, bottom_y) {\n\t\tfor (var i = 0; i < rows; i++) {\n\t\t\tfor (var j = 0; j < cols; j++) {\n\t\t\t\tvar b = bricks[j][i];\n\t\t\t\tif (b.exists == 1) {\n\t\t\t\t\tif (top_y < (b.y + block_height) && bottom_y > b.y && top_x < (b.x + block_width) && bottom_x > b.x) {\n\t\t\t\t\t\tb.exists = 0;\n\t\t\t\t\t\tball.y_speed = -ball.y_speed;\n\t\t\t\t\t\tplayer1Score += 1;\n\t\t\t\t\t\tbrickcount -= 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "playerCollidWithGem() {\n // position of the player in a grid\n let playerCoordinates = {\n x: player.x,\n y: player.y + 55,\n width: (player.horizontal)/2,\n height: (player.vertical/2)\n };\n // position of a gem in a grid\n let gemCoordinates = {\n x: this.x,\n y: this.y,\n width: this.width,\n height: this.height,\n };\n // check the X coordinates range of collision\n let collisonXRange = playerCoordinates.x < gemCoordinates.x + gemCoordinates.width &&\n playerCoordinates.x + playerCoordinates.width > gemCoordinates.x;\n // check the X coordinates range of collision\n let collisionYRange = playerCoordinates.y < gemCoordinates.y + gemCoordinates.height &&\n playerCoordinates.height + playerCoordinates.y > gemCoordinates.y;\n\n if ( collisonXRange && collisionYRange ) {\n let gem = this.sprite;\n // get the gem upon collision\n this.addGemPoints(gem);\n return true\n } else {\n return false\n }\n }", "collision() {\n const playerBox = {x: player.x, y: player.y, width: 76, height: 83};\n const enemyBox = {x: this.x, y: this.y, width: 76, height: 83};\n\n if (playerBox.x < enemyBox.x + enemyBox.width &&\n playerBox.x + playerBox.width > enemyBox.x &&\n playerBox.y < enemyBox.y + enemyBox.height &&\n playerBox.height + playerBox.y > enemyBox.y) {\n player.restart();\n hearts.pop();\n life--;\n if (life === 0) {\n lose();\n }\n }\n }", "collision() {\n\t\tthis.vars.collision = true;\n\t}", "function checkColision() {\n if (target.X === player.X && target.Y === player.Y) {\n // console.log('celbaertel !');\n ['keyup', 'keydown'].forEach(ev => document.removeEventListener(ev, playerMoov));\n player.level += 1;\n countdown++;\n //alapbeallitasok nullazasa\n messageWrapper.innerHTML = '';\n gameField.innerHTML = '';\n bombsMaker = true;\n notTheSame = true;\n playerSquare = undefined;\n bombCounter = 1;\n countdown = 3;\n target = {};\n bombs = [];\n fields = [];\n startGame();\n\n } else {\n bombs.forEach(bomb => {\n if (bomb.offsetTop === player.Y && bomb.offsetLeft === player.X) {\n makeBoom(bomb);\n\n // if (gameOver) {\n // display.innerHTML = 'GAME OVER';\n // levelInfo.innerHTML = `You made ${player.stepCounter} moves`;\n // console.log('GAME OVER');\n // ['keyup', 'keydown'].forEach(ev => document.removeEventListener(ev, playerMoov));\n // gameField.innerHTML = '';\n // playInProgres = false;\n // restartBtn();\n // }\n }\n });\n }\n\n\n\n }", "collide(p2, damp = 1) {\n // reference: http://codeflow.org/entries/2010/nov/29/verlet-collision-with-impulse-preservation\n // simultaneous collision not yet resolved. Possible solutions in this paper: https://www2.msm.ctw.utwente.nl/sluding/PAPERS/dem07.pdf \n let p1 = this;\n let dp = p1.$subtract(p2);\n let distSq = dp.magnitudeSq();\n let dr = p1.radius + p2.radius;\n if (distSq < dr * dr) {\n let c1 = p1.changed;\n let c2 = p2.changed;\n let dist = Math.sqrt(distSq);\n let d = dp.$multiply(((dist - dr) / dist) / 2);\n let np1 = p1.$subtract(d);\n let np2 = p2.$add(d);\n p1.to(np1);\n p2.to(np2);\n let f1 = damp * dp.dot(c1) / distSq;\n let f2 = damp * dp.dot(c2) / distSq;\n let dm1 = p1.mass / (p1.mass + p2.mass);\n let dm2 = p2.mass / (p1.mass + p2.mass);\n c1.add(new Pt_1.Pt(f2 * dp[0] - f1 * dp[0], f2 * dp[1] - f1 * dp[1]).$multiply(dm2));\n c2.add(new Pt_1.Pt(f1 * dp[0] - f2 * dp[0], f1 * dp[1] - f2 * dp[1]).$multiply(dm1));\n p1.previous = p1.$subtract(c1);\n p2.previous = p2.$subtract(c2);\n }\n }", "collision() {\n if (this.y === (player.y - 12) && this.x > player.x - 75 && this.x < player.x + 70) {\n player.collide();\n }\n }", "collide(oth) {\n return this.right > oth.left && this.left < oth.right && this.top < oth.bottom && this.bottom > oth.top\n }", "function collisonBords(e) {\n let collision = false;\n\n if (GestionnaireCollision.cercleDansCarre(e, map.cageDroite)) {\n if (e.x + e.width >= map.cageDroite.x + map.cageDroite.width) {\n e.x = (map.cageDroite.x + map.cageDroite.width) - e.width;\n e.inverserVx();\n\n collision = true;\n }\n if (e.y <= map.cageDroite.y) {\n e.y = map.cageDroite.y;\n e.inverserVy();\n\n collision = true;\n } else if (e.y + e.height >= map.cageDroite.y + map.cageDroite.height) {\n e.y = (map.cageDroite.y + map.cageDroite.height) - e.height;\n e.inverserVy();\n\n collision = true;\n }\n // S'il y a collision avec la cage gauche\n } else if (GestionnaireCollision.cercleDansCarre(e, map.cageGauche)) {\n if (e.x <= map.cageGauche.x) {\n e.x = map.cageGauche.x;\n e.inverserVx();\n\n collision = true;\n }\n if (e.y <= map.cageGauche.y) {\n e.y = map.cageGauche.y;\n e.inverserVy();\n\n collision = true;\n } else if (e.y + e.height >= map.cageGauche.y + map.cageGauche.height) {\n e.y = (map.cageGauche.y + map.cageGauche.height) - e.height;\n e.inverserVy();\n\n collision = true;\n }\n } else if (e.x <= map.x) {\n e.x = map.x;\n e.inverserVx();\n\n collision = true;\n } else if (e.x + e.width >= map.x + map.width) {\n e.x = (map.x + map.width) - e.width;\n e.inverserVx();\n\n collision = true;\n } else if (e.y <= map.y) {\n e.y = map.y;\n e.inverserVy();\n\n collision = true;\n } else if (e.y + e.height >= map.y + map.height) {\n e.y = (map.y + map.height) - e.height;\n e.inverserVy();\n collision = true;\n }\n\n if (collision) {\n soundsManager.collisionBords();\n }\n }", "paddleCollision(paddle1, paddle2) {\n\n \n // if moving toward the right end ================================\n if (this.vx > 0) {\n let paddle = paddle2.coordinates(paddle2.x, paddle2.y, paddle2.width, paddle2.height);\n let [leftX, rightX, topY, bottomY] = paddle;\n // right edge of the ball is >= left edge of the paddle\n if(\n (this.x + this.radius >= leftX) && \n (this.x + this.radius <= rightX) &&\n (this.y >= topY && this.y <= bottomY)\n ){\n this.vx = -this.vx;\n this.ping.play();\n }\n }\n else {\n\n // if moving toward the right end ============================\n let paddle = paddle1.coordinates(paddle1.x, paddle1.y, paddle1.width, paddle1.height);\n let [leftX, rightX, topY, bottomY] = paddle;\n // right edge of the ball is <= left edge of the paddle\n if(\n (this.x - this.radius <= rightX) && \n (this.x - this.radius >= leftX) &&\n (this.y >= topY && this.y <= bottomY)\n ){\n this.vx = -this.vx;\n this.ping.play();\n }\n }\n \n }", "function collide(arena, player) {\n const [m, o] = [player.matrix, player.pos];\n for (let y = 0; y < m.length; ++y) {\n for (let x = 0; x < m[y].length; ++x) {\n if (m[y][x] !== 0 && (arena[y+o.y] && arena[y+o.y][x+o.x]) !== 0) {\n return true;\n }\n }\n }\n return false;\n}", "colisionCheck(object, player) {\n if ((player.x-10)+ player.width < object.x ||(object.x-10) + object.width < player.x){\n return false;\n }\n if ((player.y+20) > object.y + object.height || object.y+30 > player.y + player.height) {\n return false;\n }\n return true; \n }", "checkCollisions() {\n // Get actual player position\n let playerPosition = {\n x: player.x,\n y: player.y,\n width: box.width,// Get its box width\n height: box.height// Get its box height\n }\n // Get actual gem position\n let gemPosition = {\n x: this.x,\n y: this.y,\n width: box.width +10,// Get its box width\n height: box.height// Get its box height\n }\n // If collision happened:\n if (playerPosition.x < gemPosition.x + gemPosition.width && playerPosition.x + playerPosition.width > gemPosition.x && playerPosition.y < gemPosition.y + gemPosition.height && playerPosition.y + playerPosition.height > gemPosition.y) {\n audioFiles.collect.play();// Play collect sound effect\n // If th gem collect is orange the score will be incremented by 100\n // If th gem collect is blue the score will be incremented by 200\n // If th gem collect is green the score will be incremented by 300\n player.score += (this.gemSelected+1)*100;\n this.x = -100;// hide the gem by moving it offscreen\n this.gemCollected++;// increment player gem collected\n }\n }", "function collide() { // Brute force\n\t// check if each radii of 2 particles touch\n\tfor (let i=0;i<n-1;i++){\n\t\tfor (let j=i+1;j<n;j++){\n\t\t\t// Gather values\n\t\t\tvar ix = particles[i].x;\n\t\t\tvar iy = particles[i].y;\n\t\t\tvar jx = particles[j].x;\n\t\t\tvar jy = particles[j].y;\n\t\t\tvar ir = particles[i].r/2;\n\t\t\tvar jr = particles[j].r/2;\n\t\t\tvar im = particles[i].mass;\n\t\t\tvar jm = particles[j].mass;\n\n\t\t\tvar ixs = particles[i].xspeed;\n\t\t\tvar iys = particles[i].yspeed;\n\t\t\tvar jxs = particles[j].xspeed;\n\t\t\tvar jys = particles[j].yspeed;\n\n\t\t\tvar deltax = ix - jx;\n\t\t\tvar deltay = iy - jy;\n\t\t\tvar d = dist(ix, iy, jx, jy);\n\t\t\tvar inside = d - ir - jr;\n\t\t\t\n\t\t\t// find points on each circle between centres\n\t\t\tvar theta = atan(deltay/deltax);\n\t\t\t// console.log(theta * 180/PI)\n\t\t\tif (ix > jx){\n\t\t\t\tvar p_ix = ix - ir * cos(theta);\n\t\t\t\tvar p_iy = iy - ir * sin(theta);\n\t\t\t\tvar p_jx = jx + jr * cos(theta);\n\t\t\t\tvar p_jy = jy + jr * sin(theta);\n\t\t\t} else {\n\t\t\t\tvar p_ix = ix + ir * cos(theta);\n\t\t\t\tvar p_iy = iy + ir * sin(theta);\n\t\t\t\tvar p_jx = jx - jr * cos(theta);\n\t\t\t\tvar p_jy = jy - jr * sin(theta);\n\t\t\t}\n\n\t\t\tp_x = ((ix * jr) + (jx * ir)) / (ir + jr);\n\t\t\tp_y = ((iy * jr) + (jy * ir)) / (ir + jr);\n\n\t\t\t\n\t\t\t// Draw rectangles at point on radius closest to other ball's centre\n\t\t\t// circle(p_x, p_y, 10, 10);\n\t\t\t// circle(p_ix, p_iy, 10, 10);\n\t\t\t// circle(p_jx, p_jy, 10, 10);\n\n\t\t\t// Make sure particles stay at border (do not intersect)\n\t\t\tvar move_ix = -(p_ix-p_jx)/2;\n\t\t\tvar move_jx = (p_ix-p_jx)/2;\n\t\t\tvar move_iy = -(p_iy-p_jy)/2;\n\t\t\tvar move_jy = (p_iy-p_jy)/2;\n\n\t\t\tif (inside < 0){\n\t\t\t\t\n\n\t\t\t\t// compute output velocities\n\t\t\t\t//angles\n\t\t\t\tvar alpha1 = atan2(particles[j].y-particles[i].y,particles[j].x-particles[i].x);\n\t\t\t\tvar beta1 = atan2(iys,ixs);\n\t\t\t\tvar gamma1 = beta1-alpha1;\n\t\t\t\tvar alpha2 = atan2(particles[i].y-particles[j].y,particles[i].x-particles[j].x);\n\t\t\t\tvar beta2 = atan2(jys,jxs);\n\t\t\t\tvar gamma2 = beta2-alpha2;\n\n\t\t\t\t// norm of initial vectors\n\t\t\t\tu_12 = dist(0,0,ixs,iys) * cos(gamma1);\n\t\t\t\tu_11 = dist(0,0,ixs,iys) * sin(gamma1);\n\t\t\t\tu_21 = dist(0,0,jxs,jys) * cos(gamma2);\n\t\t\t\tu_22 = dist(0,0,jxs,jys) * sin(gamma2);\n\n\t\t\t\t// norm of out vectors\n\t\t\t\tv_12 = (u_12 * (im - jm) - (2 * jm * u_21)) / (im + jm);\n\t\t\t\tv_21 = (u_21 * (im - jm) + (2 * jm * u_12)) / (im + jm);\n\n\t\t\t\t// find v1 and v2\n\t\t\t\tparticles[i].xspeed = (u_11 * (-sin(alpha1)) + v_12 * cos(alpha1)) /1.05;\n\t\t\t\tparticles[i].yspeed = (u_11 * cos(alpha1) + v_12 * sin(alpha1)) /1.05;\n\t\t\t\tparticles[j].xspeed = (u_22 * (-sin(alpha2)) - v_21 * cos(alpha2)) /1.05;\n\t\t\t\tparticles[j].yspeed = (u_22 * cos(alpha2) - v_21 * sin(alpha2)) /1.05;\n\n\t\t\t\t// velocity equations (assuming point masses)\n\t\t\t\t// particles[i].xspeed = (ixs * (im - jm) + (2 * jm * jxs)) / (im + jm);\n\t\t\t\t// particles[i].yspeed = (iys * (im - jm) + (2 * jm * jys)) / (im + jm);\n\t\t\t\t// particles[j].xspeed = (jxs * (jm - im) + (2 * im * ixs)) / (im + jm);\n\t\t\t\t// particles[j].yspeed = (jys * (jm - im) + (2 * im * iys)) / (im + jm);\n\n\t\t\t\t//angle of new \n\t\t\t\t// prevent particle clipping (going into each other)\n\t\t\t\tparticles[i].x += move_ix;\n\t\t\t\tparticles[i].y += move_iy;\n\t\t\t\tparticles[j].x += move_jx;\n\t\t\t\tparticles[j].y += move_jy;\n\t\t\t}\n\t\t}\n\t}\n\n}", "function checkCollisionsPlayerOne() {\n if (pongball.x - 15 < playerOne.x + playerOne.sizeX && pongball.y < playerOne.y + playerOne.sizeY && pongball.y + pongball.sizeY > playerOne.y) {\n\n if (pongball.x > playerOne.x) {\n\n return true;\n }\n }\n}", "collision (b) {\n\n let mdiff = this.mDiff(b);\n if (mdiff.hasOrigin()) {\n\n let vectors = [ new Vector (0,mdiff.origin.y),\n new Vector (0,mdiff.origin.y+mdiff.height),\n new Vector (mdiff.origin.x, 0),\n new Vector (mdiff.origin.x + mdiff.width, 0) ];\n\n\t\t\tlet n = vectors[0];\n\n\t\t\tfor (let i = 1; i < vectors.length; i++) {\n\t\t\t\tif (vectors[i].norm() < n.norm())\n\t\t\t\tn = vectors[i];\n\t\t\t};\n\n\t\t\tlet norm_v = this.velocity.norm();\n\t\t\tlet norm_vb = b.velocity.norm();\n\t\t\tlet kv = norm_v / (norm_v + norm_vb);\n\t\t\tlet kvb = norm_vb / (norm_v + norm_vb);\n\n\t\t\tif (norm_v == 0 && norm_vb == 0) {\n\t\t\t\tif (this.invMass == 0 && b.invMass == 0)\n\t\t\t\treturn null;\n\t\t\t\telse {\n\t\t\t\t\tif (this.mass <= b.mass)\n\t\t\t\t\tkv = 1;\n\t\t\t\t\telse\n\t\t\t\t\tkvb = 1\n\t\t\t\t}\n\n\t\t\t};\n\n\t\t\tthis.move(n.mult(kv));\n\t\t\tb.move(n.mult(-kvb));\n\n\t\t\tn = n.normalize();\n\n\t\t\t// (2) On calcule l'impulsion j :\n\t\t\tlet v = this.velocity.sub(b.velocity);\n\t\t\tlet e = Constants.elasticity; // pour les étudiants, juste faire let e = 1;\n\n\t\t\tlet j = -(1 + e) * v.dot(n) / (this.invMass + b.invMass);\n\n\t\t\t// (3) On calcule les nouvelle vitesse:\n\t\t\tlet new_v = this.velocity.add(n.mult(j * this.invMass));\n\t\t\tlet new_bv = b.velocity.sub(n.mult(j * b.invMass));\n\n\t\t\tb.setCollision(true);\n\t\t\tthis.setCollision(true);\n\n\t\t\treturn { velocity1 : new_v, velocity2 : new_bv };\n\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}" ]
[ "0.7506506", "0.7225124", "0.7194058", "0.71261394", "0.7066454", "0.70276684", "0.69875944", "0.692585", "0.69044", "0.6873446", "0.6845036", "0.67910284", "0.672938", "0.67030776", "0.6663254", "0.6656727", "0.66527855", "0.6643274", "0.663", "0.6629857", "0.66223836", "0.6614952", "0.6600759", "0.65958536", "0.65937465", "0.65866256", "0.6583635", "0.65750545", "0.65683436", "0.65393907" ]
0.7339713
1
Get the log file from the given S3 bucket and key. Parse it and add each log record to the ES domain.
function s3LogsToES(bucket, key, context, lineStream, recordStream) { // Note: The Lambda function should be configured to filter for .log files // (as part of the Event Source "suffix" setting). addFileToDelete(bucket, key); var s3Stream = s3.getObject({ Bucket: bucket, Key: key }).createReadStream(); var indexName = bucket + '-' + indexTimestamp; console.log("s3LogsToES", key); // Flow: S3 file stream -> Log Line stream -> Log Record stream -> ES s3Stream .pipe(zlib.createGunzip()) .pipe(lineStream) .pipe(recordStream) .on('data', function (parsedEntry) { postDocumentToES(indexName, parsedEntry, context); }); s3Stream.on('error', function () { console.log( 'Error getting object "' + key + '" from bucket "' + bucket + '". ' + 'Make sure they exist and your bucket is in the same region as this function.'); context.fail(); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function s3LogsToES(bucket, key, context, lineStream, recordStream) {\n // Note: The Lambda function should be configured to filter for .log files\n // (as part of the Event Source \"suffix\" setting).\n\n var s3Stream = s3.getObject({Bucket: bucket, Key: key}).createReadStream();\n\n // Flow: S3 file stream -> Log Line stream -> Log Record stream -> ES\n \n\tpostDocumentToES(key, context);\n \n\n s3Stream.on('error', function() {\n\n console.log(\n 'Error getting object \"' + key + '\" from bucket \"' + bucket + '\". ' +\n 'Make sure they exist and your bucket is in the same region as this function.');\n context.fail();\n });\n}", "function s3LogsToES(bucket, key, context, lineStream, recordStream) {\n // Note: The Lambda function should be configured to filter for .log files\n // (as part of the Event Source \"suffix\" setting).\n\n var s3Stream = s3.getObject({Bucket: bucket, Key: key}).createReadStream();\n\n // Flow: S3 file stream -> Log Line stream -> Log Record stream -> ES\n s3Stream\n .pipe(lineStream)\n .pipe(recordStream)\n .on('data', function(parsedEntry) {\n postDocumentToES(parsedEntry, context);\n });\n\n s3Stream.on('error', function() {\n console.log(\n 'Error getting object \"' + key + '\" from bucket \"' + bucket + '\". ' +\n 'Make sure they exist and your bucket is in the same region as this function.');\n context.fail();\n });\n}", "function fetchAndStoreObject(bucket, key, fn) {\n\tif (bucket === null) {\n\t\tbucket = constants.defaultBucket;\n\t}\n\tvar params = {\n\t\tBucket : bucket, /* required */\n\t\tKey : key\n\t/* required */\n\t};\n\tconsole.log(\"getObject for \" + JSON.stringify(params));\n\tvar file = fs.createWriteStream('/tmp/' + key);\n\ts3.getObject(params).on('httpData', function(chunk) {\n\t\tfile.write(chunk);\n\t\t// console.log(\"writing chunk in file.\"+key);\n\t}).on('httpDone', function() {\n\t\tfile.end();\n\t\tconsole.log(\"file end.\" + key);\n\t\tfn();\n\t}).send();\n}", "logAccessLogs(bucket, prefix) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_s3_IBucket(bucket);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.logAccessLogs);\n }\n throw error;\n }\n prefix = prefix || '';\n this.setAttribute('access_logs.s3.enabled', 'true');\n this.setAttribute('access_logs.s3.bucket', bucket.bucketName.toString());\n this.setAttribute('access_logs.s3.prefix', prefix);\n const logsDeliveryServicePrincipal = new aws_iam_1.ServicePrincipal('delivery.logs.amazonaws.com');\n bucket.grantPut(this.resourcePolicyPrincipal(), `${(prefix ? prefix + '/' : '')}AWSLogs/${core_1.Stack.of(this).account}/*`);\n bucket.addToResourcePolicy(new aws_iam_1.PolicyStatement({\n actions: ['s3:PutObject'],\n principals: [logsDeliveryServicePrincipal],\n resources: [\n bucket.arnForObjects(`${prefix ? prefix + '/' : ''}AWSLogs/${this.env.account}/*`),\n ],\n conditions: {\n StringEquals: { 's3:x-amz-acl': 'bucket-owner-full-control' },\n },\n }));\n bucket.addToResourcePolicy(new aws_iam_1.PolicyStatement({\n actions: ['s3:GetBucketAcl'],\n principals: [logsDeliveryServicePrincipal],\n resources: [bucket.bucketArn],\n }));\n // make sure the bucket's policy is created before the ALB (see https://github.com/aws/aws-cdk/issues/1633)\n this.node.addDependency(bucket);\n }", "function getFileStream(fileKey) {\n const downloadParams = {\n Key: fileKey,\n Bucket: bucketName\n }\n var object = s3.getObject(downloadParams).createReadStream().on('error', (err) => console.log(err + 'ERROR GET FILE FROM 3S'))\n return object\n}", "static getFile (bucketName, objectKey) {\n const s3 = Storage._getS3Instance();\n const params = {\n Bucket: bucketName,\n Key: objectKey\n };\n return new Promise((resolve, reject) => {\n s3.getObject(params, (err, data) => {\n if (err) {\n reject(err);\n } else {\n resolve({\n content: data.Body, // buffer\n type: data.ContentType, // string\n encoding: data.ContentEncoding, // string\n size: data.ContentLength // integer\n });\n }\n });\n });\n }", "get(bucket, key) {\n return this.store.get(`${bucket}${DELIM}${key}`);\n }", "function uploadAndFetch (s3, stream, filename, bucket, key) {\n var deferred = when.defer();\n exports.getFileStream(filename)\n .pipe(stream)\n .on(\"error\", deferred.reject)\n .on(\"finish\", function () {\n deferred.resolve(exports.getObject(s3, bucket, key));\n });\n return deferred.promise;\n}", "function getObjFromS3(fileName, bucket, callback){\n let params = {Bucket: bucket, Key:fileName};\n s3.getObject(params, function(err, data){\n if(err){\n console.error(\"getObjFromS3 err\",err);\n } else {\n callback(data.Body.toString('utf-8'));\n }\n \n });\n\n}", "function getFileStream(key) {\n const downloadParams = {\n Key: key,\n Bucket: 'week18'\n }\n return s3.getObject(downloadParams).createReadStream()\n}", "function fetchFromS3(env, callback){\n // get the investigators cached version from AWS.\n if (!isValidEnv(env)){\n callback(\"Invalid env passed into fetchFromS3()\");\n return;\n }\n // construct the filename from the env\n var filename = getS3FilePath(env);\n var params = {\n Bucket: AWS_BUCKET_NAME,\n Key: filename\n };\n // get the file\n console.log(\"Calling s3....\");\n s3.getObject(params, function(err,data){\n if (err){\n callback(\"InvestigatorService S3: \" + err.code);\n } else {\n var text = data.Body.toString('ascii');\n callback(null, text);\n }\n });\n}", "function baseAwsS3 (base, s3Bucket) {\n\n var recordsPath = path.join(base, '/outputs/records');\n\n utility.longWalk(recordsPath, function (hosts) {\n var hostsIndex = 0;\n\n function recursiveHost (host) {\n utility.longWalk(host, function (recs) {\n var recsCount = recs.length;\n var recsIndex = 0;\n\n function recursiveRecord (rec) {\n utility.longWalk(rec, function (files) {\n var fileCount = files.length;\n var fileIndex = 0;\n\n function recursiveUpload (file) {\n archiver.uploadToS3(file, s3Bucket, function (res) {\n console.log(res);\n fileIndex++;\n\n if (fileIndex < fileCount) {\n recursiveUpload(files[fileIndex]);\n }\n\n if (fileIndex === fileCount) {\n fs.rmrf(recs[recsIndex], function (err) {\n if (err) console.log(err);\n else {\n recsIndex++;\n if (recsIndex < recsCount) {\n recursiveRecord(recs[recsIndex]);\n }\n if (recsIndex === recsCount) {\n fs.rmrf(hosts[hostsIndex], function (err) {\n if (err) console.log(err);\n else {\n hostsIndex++;\n recursiveHost(hosts[hostsIndex]);\n }\n })\n }\n }\n })\n }\n })\n }\n if (fileCount === 0) {\n recsIndex++;\n recursiveRecord(recs[recsIndex]);\n } else {\n recursiveUpload(files[fileIndex]);\n }\n })\n }\n recursiveRecord(recs[recsIndex]);\n })\n }\n recursiveHost(hosts[hostsIndex]);\n })\n}", "async exportFromS3(params) {\n s3.getObject(params, function (err, data) {\n const convertJsonToCsv = (json) => {\n let fields = Object.keys(json[0]);\n const replacer = (key, value) => (value === null ? \"\" : value);\n let csv = json.map((row) =>\n fields.map((field) => JSON.stringify(row[field], replacer)).join(\",\")\n );\n csv.unshift(fields.join(\",\"));\n csv = csv.join(\"\\r\\n\");\n return csv;\n };\n\n if (data) {\n let json = JSON.parse(data.Body.toString());\n let csv = convertJsonToCsv(json);\n let filename = \"\";\n if (params.Key.includes(\"time/\")) {\n filename = params.Key.replace(\"time/\", \"\");\n } else {\n filename = params.Key.replace(\"sprint/\", \"\");\n }\n\n let blob = new Blob([csv], {\n type: \"\",\n });\n FileSaver.saveAs(blob, filename + CSV_FILE_ATTACHMENT);\n } else {\n console.log(\"Error: \" + err);\n }\n });\n }", "function parseS3Url(url) {\n const [bucket, ...keyFragments] = url.replace(S3_PROTOCOL_PREFIX, '').split('/');\n return { bucket, key: keyFragments.join('/') };\n}", "function processRecord(record, callback) {\n \n // The source bucket and source key are part of the event data\n var srcBucket = record.s3.bucket.name;\n var srcKey = decodeURIComponent(record.s3.object.key.replace(/\\+/g, \" \"));\n \n // Get the target bucket(s) based on the source bucket.\n // Once we have that, perform the copy.\n getTargetBuckets(srcBucket, function (err, targets) {\n if (err) {\n console.log(\"Error getting target bucket: \"); // an error occurred\n console.log(err, err.stack); // an error occurred\n callback(\"Error getting target bucket from source bucket '\" + srcBucket + \"'\");\n return;\n }\n \n async.each(targets, function (target, callback) {\n\n var targetBucket = target.bucketName;\n var regionName = target.regionName;\n var targetBucketName = targetBucket;\n if (regionName != null)\n targetBucketName = targetBucketName + \"@\" + regionName;\n var targetKey = srcKey;\n \n console.log(\"Copying '\" + srcKey + \"' from '\" + srcBucket + \"' to '\" + targetBucketName + \"'\");\n \n // Copy the object from the source bucket\n var s3 = createS3(regionName);\n s3.copyObject({\n Bucket: targetBucket,\n Key: targetKey,\n \n CopySource: encodeURIComponent(srcBucket + '/' + srcKey),\n MetadataDirective: 'COPY'\n }, function (err, data) {\n if (err) {\n console.log(\"Error copying '\" + srcKey + \"' from '\" + srcBucket + \"' to '\" + targetBucketName + \"'\");\n console.log(err, err.stack); // an error occurred\n callback(\"Error copying '\" + srcKey + \"' from '\" + srcBucket + \"' to '\" + targetBucketName + \"'\");\n } else {\n callback();\n }\n });\n }, function (err) {\n if (err) {\n callback(err);\n } else {\n callback();\n }\n });\n });\n}", "function saveToS3(fileName) {\n // load in file;\n let logDir = './logs';\n let directory =`${logDir}/${fileName}`;\n let myKey = fileName;\n var myBody;\n console.log(directory);\n\n // read then save to s3 in one step (so no undefined errors)\n fs.readFile(directory, (err, data) => {\n if (err) throw err;\n myBody = data;\n console.log(\"save to s3 data is \" + data);\n var params = {Bucket: myBucket, Key: myKey, Body: myBody, ContentType: 'text/plain'};\n s3.putObject(params, function(err, data) {\n if (err) {\n console.log(err)\n } else {\n console.log(\"Successfully uploaded data to myBucket/myKey\");\n }\n });\n\n });\n fs.unlink(directory);\n\n // the create bucket stuff started to cause problems (error: \"BucketAlreadyOwnedByYou: Your previous request to create the named bucket succeeded and you already own it.\")\n // so I pulled it all out\n}", "function getLog(key){\n\tlet tmp = key.replace('log',''); //remove log prefix from the key to get the number\n\tlogNumber = Number(tmp); //parse the string into a number\n\tlocalforage.getItem('logs') //load the logs from memory\n\t.then((logs)=>{\n\t\tlet log = logs[key]; //get our log at the parameter key.\n\t\tconsole.log(log)\n\t\tfor(let field in log){ //itwerage over the fields of the log\n\t\t\tlet value = log[field];\n\t\t\tif(typeof value === \"string\") //if the field is a string, it goes to a text input\n\t\t\t\t$(`.${field}`).val(value);\n\t\t\telse if(value){ //or else it is a checkbox\n\t\t\t\t$(`input[val=${field}]`).prop('checked',true);\n\t\t\t}\n\t\t\telse{\n\t\t\t\t$(`input[val=${field}]`).prop('checked',false);\n\t\t\t}\n\t\t}\n\t})\n\n\treturn\n}", "function uploadFileIntoBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // call S3 to retrieve upload file to specified bucket\n var uploadParams = {Bucket: process.argv[2], Key: '', Body: ''};\n var file = process.argv[3];\n\n // Configure the file stream and obtain the upload parameters\n var fs = require('fs');\n var fileStream = fs.createReadStream(file);\n fileStream.on('error', function(err) {\n console.log('File Error', err);\n });\n\n uploadParams.Body = fileStream;\n var path = require('path');\n uploadParams.Key = path.basename(file);\n\n // call S3 to retrieve upload file to specified bucket\n s3.upload (uploadParams, function (err, data) {\n if (err) {\n console.log(\"Error\", err);\n } if (data) {\n console.log(\"Upload Success\", data.Location);\n }\n });\n}", "function getFileStream(fileKey) {\n const downloadParams = {\n Key: fileKey,\n Bucket: bucketName,\n };\n\n return s3.getObject(downloadParams).createReadStream();\n}", "function getS3File(bucketName, fileName, versionId, callback) {\n var params = {\n Bucket: bucketName,\n Key: fileName\n };\n if (versionId) {\n params.VersionId = versionId;\n }\n s3.getObject(params, function (err, data) {\n callback(err, data);\n });\n}", "load() {\n try {\n const logString = this.storage.get(storageKey);\n if (logString !== undefined) {\n this.deserializeJson(JSON.parse(logString));\n }\n }\n catch (err) {\n logError('Failed to load progress log:', err);\n }\n }", "function LogFile(id) {\n this.id = id;\n this.knownLoggers = {};\n this._dateBucketsByName = {};\n this._dateBuckets = [];\n this._newBuckets = [];\n}", "async function listLogFiles(next_query = {autoPaginate: false, maxResults: concurrentImport}) {\n // Lists files in the bucket\n return await bucket.getFiles(next_query);\n}", "function uploadFile(bucket, key, fileLocation, callback) {\n fs.readFile(fileLocation, function(err, data) {\n if (err) {\n return callback(err);\n }\n\n var params = {\n Bucket: bucket,\n Key: key + '.webm',\n Body: data\n };\n\n s3.putObject(params, callback);\n });\n}", "function getFileStream(fileKey) {\n const downloadParams = {\n Key: fileKey,\n Bucket: AWS_BUCKET_NAME\n }\n\n return s3.getObject(downloadParams).createReadStream()\n}", "urlForObject(key) {\n const components = [`https://s3.${this.node.stack.region}.${this.node.stack.urlSuffix}/${this.bucketName}`];\n if (key) {\n // trim prepending '/'\n if (typeof key === 'string' && key.startsWith('/')) {\n key = key.substr(1);\n }\n components.push('/');\n components.push(key);\n }\n return components.join('');\n }", "async function fetchInputFromS3(s3URL) {\n const tmpDir = await tmp.dir({ dir: \"/tmp\" });\n const parsedS3URL = url.parse(s3URL);\n const localFile = path.join(tmpDir.path, path.basename(parsedS3URL.path));\n console.log(`Downloading ${s3URL} to ${localFile}...`);\n\n const params = {\n Bucket: parsedS3URL.host,\n Key: parsedS3URL.path.slice(1),\n };\n const s3 = new AWS.S3();\n const readStream = s3.getObject(params).createReadStream();\n await new Promise((resolve, reject) => {\n readStream.on(\"error\", reject);\n readStream.on(\"end\", resolve);\n const file = fs.createWriteStream(localFile);\n readStream.pipe(file);\n });\n return localFile;\n}", "function getEventInfo(eventId) {\n var params = {\n Bucket: 'training-schedule',\n Key: 'ready/current-schedule.csv',\n Expression: 'select * from s3object s where \"Event ID\" = \\'' + eventId + '\\'',\n ExpressionType: \"SQL\", \n InputSerialization: { CSV: {} },\n OutputSerialization: { JSON: {} }\n };\n s3.selectObjectContent(params, function(err, data) {\n if (err) console.log(err, err.stack); // an error occurred\n else {\n console.log(data); // successful response\n var eventStream = data.Payload;\n\n eventStream.on('data', function(event) {\n // Check the top-level field to determine which event this is.\n if (event.Records) {\n // handle Records event\n console.log('this is the payload: ' + event.Records.Payload);\n }\n });\n \n } \n });\n}", "function getVersion (bucket, key, back, callback) {\n bucket = bucket.toLowerCase();\n var s3 = new AWS.S3();\n var version_params = {\n Bucket: bucket, /* required */\n KeyMarker: key,\n MaxKeys: back\n };\n s3.listObjectVersions(version_params, function(err, data) {\n if (err) {\n console.log(err, err.stack); // an error occurred\n console.log('bucket: '+bucket+ 'key: '+key+' back: '+back+' lastVersion: '+lastVersion);\n } else {\n\n if (data.Versions.length < back-1) {\n console.log('only one version');\n callback(null);\n return;\n }\n\n if (data.Versions[back-1].Key != key+'/store.json') {\n console.log('only one version, key mismatch: '+key+ ' vs '+data.Versions[back-1].Key);\n callback(null);\n return;\n }\n //console.log(data);\n var lastVersion = data.Versions[back-1].VersionId;\n //console.log('got last version for path: '+key+' id: '+lastVersion);\n //console.log(JSON.stringify(data, null, 4));\n var get_params = {\n Bucket: bucket,\n Key: key+'/store.json',\n VersionId: lastVersion\n }\n\n s3.getObject(get_params, function(err, data) {\n if (err) {\n console.log(err, err.stack); // an error occurred\n console.log('bucket: '+bucket+ 'key: '+key+' back: '+back+' lastVersion: '+lastVersion);\n } else {\n //console.log(data);\n callback(data.Body);\n }\n });\n }\n });\n}", "function uploadFileIntoFolderOfBucket(){\n // Create S3 service object\n s3 = new AWS.S3({apiVersion: '2006-03-01'});\n\n // call S3 to retrieve upload file to specified bucket\n var uploadParams = {Bucket: process.argv[2], Key: '', Body: ''};\n var file = process.argv[4];\n\n // Configure the file stream and obtain the upload parameters\n var fs = require('fs');\n var fileStream = fs.createReadStream(file);\n fileStream.on('error', function(err) {\n console.log('File Error', err);\n });\n\n uploadParams.Body = fileStream;\n var path = require('path');\n uploadParams.Key = process.argv[3]+\"/\"+path.basename(file);\n\n // call S3 to retrieve upload file to specified bucket\n s3.upload (uploadParams, function (err, data) {\n if (err) {\n console.log(\"Error\", err);\n } if (data) {\n console.log(\"Upload Success\", data.Location);\n }\n });\n}" ]
[ "0.7192204", "0.7129934", "0.58190775", "0.56013477", "0.5531915", "0.5417477", "0.5398596", "0.5318489", "0.53021234", "0.5149168", "0.5094466", "0.50757706", "0.5023641", "0.5020895", "0.5007629", "0.49872974", "0.4980069", "0.49677464", "0.49657312", "0.49385136", "0.49237305", "0.4871873", "0.48607564", "0.48235372", "0.47622752", "0.47527978", "0.47443798", "0.47239944", "0.47123772", "0.47006938" ]
0.7220334
0
Generate and Endpoint from an endpoint schema object.
makeEndpoint(schema) { return (options) => { const ep = new endpoint_1.Endpoint(options); ep.applySchema(ep, schema, schema, ep); return ep; }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function deriveEndpoint(edge, index, ep, conn) {\n return options.deriveEndpoint ? options.deriveEndpoint(edge, index, ep, conn) : options.endpoint ? options.endpoint : ep.type;\n }", "set endpoint(endpoint) {\n\t\tif (Array.isArray(endpoint)) {\n\t\t\tthis._endpoint = endpoint.map((i) => new Reference(i));\n\t\t} else {\n\t\t\tthis._endpoint = [new Reference(endpoint)];\n\t\t}\n\t}", "createPayloadEndpoint(opts) {\n if (opts === undefined) opts = {};\n\n // Return the proper structure expected for the endpoint\n const endpoint = {\n capabilities: this.checkValue(opts.capabilities, []),\n description: this.checkValue(opts.description, 'Sample Endpoint Description'),\n displayCategories: this.checkValue(opts.displayCategories, ['OTHER']),\n endpointId: this.checkValue(opts.endpointId, 'endpoint-001'),\n // \"endpointId\": this.checkValue(opts.endpointId, 'endpoint_' + (Math.floor(Math.random() * 90000) + 10000)),\n friendlyName: this.checkValue(opts.friendlyName, 'Sample Endpoint'),\n manufacturerName: this.checkValue(opts.manufacturerName, 'Sample Manufacturer'),\n };\n\n if (opts.hasOwnProperty('cookie')) endpoint.cookie = this.checkValue('cookie', {});\n\n return endpoint;\n }", "function createApiEndpoint(requestor, endpoint) {\n var isCollection = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n\n var _get = function _get() {\n var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n return requestor.makeRequest('get', '/' + endpoint, params);\n };\n var _post = function _post(data) {\n return requestor.makeRequest('post', '/' + endpoint, data);\n };\n\n /**\n *\n * @param {*} params\n */\n var apiEndpoint = function apiEndpoint() {\n var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n\n // calling endpoint() is equivalent to endpoint.all()\n return _get(params);\n };\n\n if (isCollection) {\n apiEndpoint.all = _get;\n apiEndpoint.create = _post;\n apiEndpoint.find = function (id) {\n var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n return requestor.makeRequest('get', '/' + endpoint + '/' + id, params);\n };\n apiEndpoint.update = function (id, data) {\n return requestor.makeRequest('put', '/' + endpoint + '/' + id, data);\n };\n apiEndpoint.delete = apiEndpoint.remove = function (id) {\n return requestor.makeRequest('delete', '/' + endpoint + '/' + id);\n };\n apiEndpoint.one = function (key) {\n return requestor.endpoint(endpoint + '/' + key, endpoint + '_' + key, false);\n };\n } else {\n apiEndpoint.get = _get;\n apiEndpoint.post = _post;\n apiEndpoint.put = function (data) {\n return requestor.makeRequest('put', '/' + endpoint, data);\n };\n apiEndpoint.delete = function () {\n return requestor.makeRequest('delete', '/' + endpoint);\n };\n }\n\n // Wrap the endpoint with a proxy to handle undefined property as another api endpoint\n // undefined property on collection endpoint return entity endpoint\n // and collection endpoint on entity endpoint\n var apiEndpointProxy = new Proxy(apiEndpoint, {\n get: function get(apiEndpoint, prop) {\n if (prop in apiEndpoint) {\n return apiEndpoint[prop];\n }\n\n return requestor.endpoint(endpoint + '/' + prop, endpoint + '_' + prop, !isCollection);\n }\n });\n\n return apiEndpointProxy;\n}", "function configureEndpoint() {\n\tif(!o().isEndpoint()) {\n\t\to().config({\n\t\t\tendpoint:'http://services.odata.org/V4/%28S%28wptr35qf3bz4kb5oatn432ul%29%29/TripPinServiceRW/',\n\t\t\tversion:4,\n\t\t\tstrictMode:true\n\t\t});\n\t}\n}", "endpoint(e) {\n\t\tlet value = GhostInstance.endpoints;\n\t\tconst paths = e.split('.');\n\t\tpaths.forEach((path) => {\n\t\t\tvalue = value[path] || {};\n\t\t});\n\n\t\tif (typeof value === 'object') {\n\t\t\tif (value.path) {\n\t\t\t\tvalue = Object.assign({}, value);\n\t\t\t} else {\n\t\t\t\tvalue = {};\n\t\t\t}\n\t\t}\n\n\t\treturn value;\n\t}", "function callApi (endpoint, schemas, typeSchemas, options, clientId) {\n // checkif endpoint already contains base asi url or base web url\n const fullUrl = (endpoint.indexOf(API_ROOT) !== -1) || (endpoint.indexOf(API_WEB_ROOT) !== -1)\n ? endpoint\n : API_ROOT + endpoint\n\n return fetch(fullUrl, options)\n .then(response => {\n if (!response.ok) {\n return Promise.reject(new ResponseError(response))\n }\n return response.json().then(json => ({ json, response }))\n }).then(({ json, response }) => {\n if (!response.ok) {\n return Promise.reject(json)\n }\n\n // normalize static types\n if (typeSchemas) {\n if (Array.isArray(typeSchemas)) {\n console.error('NORMALIZE: not supported operation - types schemas array', json, typeSchemas)\n } else {\n console.error('NORMALIZE: not supported operation - types schema', json, typeSchemas)\n }\n }\n return normalizeResponse({ json, schemas })\n }).catch(error => Promise.reject(error))\n}", "static fromEndpointAttributes(scope, id, attrs) {\n class Import extends core_1.Resource {\n constructor() {\n super(...arguments);\n this.endpointId = attrs.endpointId;\n this.connections = new connections_1.Connections({ securityGroups: attrs.securityGroups });\n this.targetNetworksAssociated = new core_1.ConcreteDependable();\n }\n }\n return new Import(scope, id);\n }", "function Schema_from_swagger(schema_content) {\n 'use strict';\n // use new\n\n this.resolve = (input_json_obj) => {\n //const schema = getSwaggerV2Schema(schema_content, '/default_endpoint')\n const schema = schema_content;\n const ok = schemaValidator(schema, input_json_obj);\n if (ok) {\n return input_json_obj;\n } else {\n throw new Error('mismatch: The constraint aspect of template failed');\n }\n };\n\n this.generate = (obj) => this.resolve(obj);\n}", "function endpoint(path, method) {\n function Endpoint(path, method) {\n this.path = path;\n this.method = method;\n }\n allEndpoints.push( new Endpoint(path, method) );\n}", "function create_url(endpoint) {\n // TODO: ここを書き換えてURL作る\n // return '/api/guchi' + endpoint\n return URL_BASE + '/deai/' + endpoint;\n}", "function endpoint(path, query, body) {\n return function () {\n body = body || getJSON(path);\n createEndpointFromObject(path, query, body);\n console.log(' registered path %s', path);\n }\n}", "function createEndpointFromPath(path, query, filePath) {\n filePath = filePath || path;\n return createEndpointFromObject(path, query, getJSON(filePath));\n}", "function _getEndpointUri(endpoint) {\n return _endpoint.gebo + _endpoint[endpoint];\n }", "_attachEndpoint(func, endpoint) {\n\t\t// Validate method and path\n\t\t/* istanbul ignore next */\n\t\tif (!endpoint.method || !endpoint.path) {\n\t\t\treturn this.log(\n\t\t\t\t`Endpoint ${endpoint.type} for function ${func.name} has no method or path`\n\t\t\t)\n\t\t}\n\t\t// Add HTTP endpoint to Express\n\t\tthis.app[endpoint.method.toLowerCase()](\n\t\t\tendpoint.path,\n\t\t\t(request, response) => {\n\t\t\t\tthis.log(`${endpoint}`)\n\t\t\t\t// Execute Lambda with corresponding event, forward response to Express\n\t\t\t\tlet lambdaEvent = endpoint.getLambdaEvent(request)\n\t\t\t\tthis._executeLambdaHandler(func, lambdaEvent)\n\t\t\t\t\t.then(result => {\n\t\t\t\t\t\tthis.log(' ➡ Success')\n\t\t\t\t\t\tif (process.env.SLS_DEBUG) console.info(result)\n\t\t\t\t\t\tendpoint.handleLambdaSuccess(response, result)\n\t\t\t\t\t})\n\t\t\t\t\t.catch(error => {\n\t\t\t\t\t\tthis.log(` ➡ Failure: ${error.message}`)\n\t\t\t\t\t\tif (process.env.SLS_DEBUG) console.error(error.stack)\n\t\t\t\t\t\tendpoint.handleLambdaFailure(response, error)\n\t\t\t\t\t})\n\t\t\t}\n\t\t)\n\t}", "function extendingEndpoints() {\n var segments = Array.prototype.slice.call(arguments, 0);\n return function () {\n var path = '';\n segments.forEach(function (pathSegment) {\n path = path + pathSegment;\n createEndpointFromPath(path);\n console.log(' registered path %s', path);\n });\n }\n}", "registerEndpoint(fn, options)\n {\n if (!fn) throw new Error('Must include a function to register endpoint');\n\n options.modelName = this.modelName;\n const endpoint = buildEndpoint(this, options, fn);\n if (!options.private) this.publicEndpoints.push(endpoint);\n this[options.name] = fn;\n }", "createEntity(entity) {\n this.endpoints[entity.name] = this.createBasicCRUDEndpoints(entity);\n }", "function expandBindings(endpoints) {\n\treturn Object.keys(endpoints).reduce((expanded, method) => {\n\t\tconst bindingDefinition = endpoints[method];\n\t\tif (typeof bindingDefinition === \"object\") {\n\t\t\texpanded[method] = bindingDefinition;\n\t\t}\n\t\telse {\n\t\t\texpanded[method] = {\n\t\t\t\tpost: bindingDefinition,\n\t\t\t\tredirect: bindingDefinition\n\t\t\t};\n\t\t}\n\t\treturn expanded;\n\t}, {});\n}", "function callApi(endpoint, option, schema) {\n \n const fullUrl = (endpoint.indexOf(API_ROOT) === -1) ? API_ROOT + endpoint : endpoint;\n\n return fetch(fullUrl, option)\n .then(response => {\n if (response.status === 204) {\n return { json: undefined, response: response };\n }\n return response.json().then(json => ({ json, response }));\n }).then(({ json, response }) => {\n if (!response.ok) {\n return Promise.reject(json);\n }\n\n if (json) {\n let resultObjects;\n\n if (json.results) {\n resultObjects = json.results;\n } else {\n resultObjects = json;\n }\n return Object.assign({}, normalize(resultObjects, schema), {next: json.next});\n } else {\n return {};\n }\n })\n}", "function setupEndpoint() {\n if (host.val().indexOf('/') != -1) {\n var hostArr = host.val().split('/');\n\n path = \"http://\" + hostArr[0] + \":\" + port.val();\n hostArr.shift(); // remove host\n\n if (hostArr.length > 0) { // anything left?\n path += \"/\" + hostArr.join('/');\n }\n } else {\n path = \"http://\" + host.val() + \":\" + port.val();\n }\n endpoint = path;\n }", "function parse(any, opts) {\n let schemaOrProtocol = specs.read(any);\n return schemaOrProtocol.protocol ?\n services.Service.forProtocol(schemaOrProtocol, opts) :\n types.Type.forSchema(schemaOrProtocol, opts);\n}", "function initEndpointRunner(appMetadata, requestContext, taskMetadata) {\n class EndpointRunner extends BaseStore {\n _buildEndpointRequest(options) {\n return this._buildKinveyRequest(BASE_ROUTE, 'custom', options);\n }\n\n _makeEndpointRequest(requestOptions, endpointName, callback) {\n if (this._taskMetadata.objectName === endpointName && this._taskMetadata.hookType === 'customEndpoint') {\n const error = new Error('EndpointRunnerError');\n error.description = 'Not Allowed';\n error.debug = 'Recursive requests to the same endpoint are prohibited.';\n return callback ? setImmediate(() => callback(error)) : Promise.reject(error);\n }\n return this._makeRequest(requestOptions, callback);\n }\n\n endpoint(endpointName) {\n const execute = (body = {}, cb) => {\n const callback = !cb && typeof body === 'function' ? body : cb;\n const requestBody = typeof body === 'function' ? {} : body;\n\n const requestOptions = this._buildEndpointRequest();\n\n requestOptions.method = 'POST';\n requestOptions.url += endpointName;\n requestOptions.body = requestBody || {};\n return this._makeEndpointRequest(requestOptions, endpointName, callback);\n };\n\n return {\n execute,\n endpointName,\n _useUserContext: this._useUserContext,\n _useBl: this._useBl,\n _appMetadata: this._appMetadata,\n _requestContext: this._requestContext\n };\n }\n }\n\n function generateEndpointRunner(storeOptions = {}) {\n storeOptions.useBl = true;\n return new EndpointRunner(storeOptions, appMetadata, requestContext, taskMetadata);\n }\n\n return generateEndpointRunner;\n}", "get endpoint() {\n return this.getStringAttribute('endpoint');\n }", "get endpoint() {\n return this.getStringAttribute('endpoint');\n }", "get endpoint() {\n return this.getStringAttribute('endpoint');\n }", "function parse(any, opts) {\n var schemaOrProtocol = specs.read(any);\n return schemaOrProtocol.protocol ?\n services.Service.forProtocol(schemaOrProtocol, opts) :\n types.Type.forSchema(schemaOrProtocol, opts);\n}", "function buildEndpoints() {\n ctrl.devices.forEach(function(device) {\n if (!endpointHasDevice(device)) {\n ctrl.endpoints.push(buildEndpoint(device))\n }\n })\n cleanEndpoints()\n }", "function createEndpointFromObject(path, query, body) {\n // OPTIONS gives server permission to use CORS\n server.createRoute({\n request: {\n url: path,\n query: query || {},\n method: 'options',\n },\n response: {\n code: 200,\n delay: config.latency,\n body: {},\n headers: {\n 'Access-Control-Allow-Origin': config.allowOrigin,\n // allow several methods since some endpoints are writable\n 'Access-Control-Allow-Methods': 'GET, PUT, POST',\n 'Access-Control-Allow-Credentials': 'true'\n }\n }\n });\n return server.get(path)\n .query(query)\n .responseHeaders({\n 'Access-Control-Allow-Origin': config.allowOrigin,\n 'Access-Control-Allow-Methods': 'GET, PUT, POST',\n 'Access-Control-Allow-Credentials': 'true'\n })\n .body(body)\n .delay(config.latency);\n}", "endpoint() {\n //\n }" ]
[ "0.6567618", "0.563212", "0.54849434", "0.54841", "0.5437757", "0.5389481", "0.5346032", "0.53214276", "0.52909744", "0.5205821", "0.5177365", "0.51664466", "0.5159697", "0.5092623", "0.5089627", "0.5069809", "0.5061949", "0.50262016", "0.5016462", "0.49969277", "0.49825656", "0.49483395", "0.4943889", "0.49064496", "0.49064496", "0.49064496", "0.4890194", "0.48776254", "0.48249775", "0.47902107" ]
0.7860793
0
Generate API file given discovery URL
async discoverAPI(apiDiscoveryUrl) { if (typeof apiDiscoveryUrl === 'string') { const parts = url.parse(apiDiscoveryUrl); if (apiDiscoveryUrl && !parts.protocol) { this.log('Reading from file ' + apiDiscoveryUrl); const file = await readFile(apiDiscoveryUrl, { encoding: 'utf8' }); return this.makeEndpoint(JSON.parse(file)); } else { this.log('Requesting ' + apiDiscoveryUrl); const res = await this.transporter.request({ url: apiDiscoveryUrl, }); return this.makeEndpoint(res.data); } } else { const options = apiDiscoveryUrl; this.log('Requesting ' + options.url); const url = options.url; delete options.url; const parameters = { options: { url, method: 'GET' }, requiredParams: [], pathParams: [], params: options, context: { google: { _options: {} }, _options: {} }, }; const res = await apirequest_1.createAPIRequest(parameters); return this.makeEndpoint(res.data); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function genApiURL ( offset ) {\n URL = gamesURL + apiKey + formatOffset + offset;\n return URL;\n}", "function buildSpecUrl() {\n let {protocol, host} = window.location\n let url = window.PRELOAD.swagger_url || '/docs?format=openapi'\n return `${protocol}//${host}${url}`\n}", "async discoverAllAPIs(discoveryUrl) {\n const headers = this.options.includePrivate\n ? {}\n : { 'X-User-Ip': '0.0.0.0' };\n const res = await this.transporter.request({\n url: discoveryUrl,\n headers,\n });\n const items = res.data.items;\n const apis = await Promise.all(items.map(async (api) => {\n const endpointCreator = await this.discoverAPI(api.discoveryRestUrl);\n return { api, endpointCreator };\n }));\n const versionIndex = {};\n // tslint:disable-next-line no-any\n const apisIndex = {};\n for (const set of apis) {\n if (!apisIndex[set.api.name]) {\n versionIndex[set.api.name] = {};\n apisIndex[set.api.name] = (options) => {\n const type = typeof options;\n let version;\n if (type === 'string') {\n version = options;\n options = {};\n }\n else if (type === 'object') {\n version = options.version;\n delete options.version;\n }\n else {\n throw new Error('Argument error: Accepts only string or object');\n }\n try {\n const ep = \n // tslint:disable-next-line: no-any\n set.endpointCreator(options, this);\n return Object.freeze(ep); // create new & freeze\n }\n catch (e) {\n throw new Error(util.format('Unable to load endpoint %s(\"%s\"): %s', set.api.name, version, e.message));\n }\n };\n }\n versionIndex[set.api.name][set.api.version] = set.endpointCreator;\n }\n return apisIndex;\n }", "function serveApiDefinition(fpath, req, res) {\n fs.readFile(fpath, 'utf-8', function(err, c) {\n if(err) {\n res.end('');\n } else {\n c = c.replace(/%%HOST%%/, req.headers.host);\n res.end(c);\n }\n });\n}", "function api_create_url(){\n // Store our API URL parameters in this utility object\n var params = {\n \"method\": \"flickr.photosets.getPhotos\",\n \"api_key\": window.api_key,\n \"photoset_id\": window.photoset_id,\n \"format\": \"json\",\n \"nojsoncallback\": \"1\",\n \"extras\": \"url_m\"\n };\n\n // Construct the URL from the params\n var url = \"https://api.flickr.com/services/rest/?\";\n for (var prop in params){ url += prop+\"=\"+params[prop]+\"&\"; }\n\n return url;\n}", "async function generate(opts) {\n const apiFinder = parse_1.parse(opts);\n const data = apiFinder(opts.api);\n const results = {\n ...opts,\n data,\n };\n if (opts.outputJsonPath) {\n await output_1.outputJson(opts.outputJsonPath, data);\n }\n if (opts.outputReadmePath) {\n await output_1.outputReadme(opts.outputReadmePath, data);\n }\n return results;\n}", "function gen_url(object){\n var server = config.get('api_conf.server');\n var port = config.get('api_conf.port');\n var version = config.get('api_conf.version');\n var account = config.get('api_conf.account');\n\n url = \"http://\" + server + \":\" + port + \"/\" + version + \"/\" + account \n //Check if the container/object exist, if they exist \n //concatenate it to the url variable \n if(config.has('api_conf.container')){\n url += \"/\" + config.get('api_conf.container'); \n } \n if(config.has('api_conf.object')){\n url += \"/\" + config.get('api_conf.object');\n }\n url += object; \n\n return url;\n}", "get apiUrl() {\n return `http://${this.host}:${this.tempApiPort}/api`; // setups up the url that the api is located at and used as a shortcut for our fetch api scripts to retrieve data\n }", "function makeUrl() {\n return \"https://api.themoviedb.org/3/discover/movie?\"+\n \"api_key=7206d76e96b3e78b399d05fbcda1ea0d&language=en-US%20en-GB&\"+\n \"sort_by=popularity.desc&include_adult=false&include_video=false&page=\" + random(50);\n }", "function _buildApiUrl (datasetname, configkey) {\n\t\tlet url = API_BASE;\n\t\turl += '?key=' + API_KEY;\n\t\turl += datasetname && datasetname !== null ? '&dataset=' + datasetname : '';\n\t\turl += configkey && configkey !== null ? '&configkey=' + configkey : '';\n\t\t//console.log('buildApiUrl: url=' + url);\n\t\t\n\t\treturn url;\n\t}", "function getAPI() {\n\treturn \"http://\" + apiUrl + \":\" + apiPort + \"/\" + apiResource;\n}", "function makeApiFiles(api, apiOutputDir, sourceDir, libname) {\n var apiHeaderTemplate = ejs.compile(readFile(path.resolve(sourceDir, \"templates/PlayFabAPI.h.ejs\")));\n var apiCppTemplate = ejs.compile(readFile(path.resolve(sourceDir, \"templates/PlayFabAPI.cpp.ejs\")));\n var apiPlayFabModelTemplate = ejs.compile(readFile(path.resolve(sourceDir, \"templates/PlayFabModels.h.ejs\")));\n var apiPlayFabModelCppTemplate = ejs.compile(readFile(path.resolve(sourceDir, \"templates/PlayFabModels.cpp.ejs\")));\n var apiPlayFabModelDecoderHTemplate = ejs.compile(readFile(path.resolve(sourceDir, \"templates/PlayFabModelDecoder.h.ejs\")));\n var apiPlayFabModelDecoderCppTemplate = ejs.compile(readFile(path.resolve(sourceDir, \"templates/PlayFabModelDecoder.cpp.ejs\")));\n \n var generatedHeader;\n var generatedBody;\n var apiLocals = {};\n apiLocals.api = api;\n apiLocals.hasClientOptions = api.name === \"Client\";\n apiLocals.sdkVersion = exports.sdkVersion;\n apiLocals.libname = libname;\n \n generatedHeader = apiHeaderTemplate(apiLocals);\n writeFile(path.resolve(apiOutputDir, \"PluginFiles/PlayFab/Source/PlayFab/Classes/PlayFab\" + api.name + \"API.h\"), generatedHeader);\n generatedBody = apiCppTemplate(apiLocals);\n writeFile(path.resolve(apiOutputDir, \"PluginFiles/PlayFab/Source/PlayFab/Private/PlayFab\" + api.name + \"API.cpp\"), generatedBody);\n \n generatedHeader = apiPlayFabModelTemplate(apiLocals);\n writeFile(path.resolve(apiOutputDir, \"PluginFiles/PlayFab/Source/PlayFab/Classes/PlayFab\" + api.name + \"Models.h\"), generatedHeader);\n generatedBody = apiPlayFabModelCppTemplate(apiLocals);\n writeFile(path.resolve(apiOutputDir, \"PluginFiles/PlayFab/Source/PlayFab/Private/PlayFab\" + api.name + \"Models.cpp\"), generatedBody);\n \n generatedHeader = apiPlayFabModelDecoderHTemplate(apiLocals);\n writeFile(path.resolve(apiOutputDir, \"PluginFiles/PlayFab/Source/PlayFab/Classes/PlayFab\" + api.name + \"ModelDecoder.h\"), generatedHeader);\n generatedBody = apiPlayFabModelDecoderCppTemplate(apiLocals);\n writeFile(path.resolve(apiOutputDir, \"PluginFiles/PlayFab/Source/PlayFab/Private/PlayFab\" + api.name + \"ModelDecoder.cpp\"), generatedBody);\n}", "function apiURL(service) { //Función para formar la ruta completa a la API \n return BaseApiUrl + service;\n}", "function create_url(endpoint) {\n // TODO: ここを書き換えてURL作る\n // return '/api/guchi' + endpoint\n return URL_BASE + '/deai/' + endpoint;\n}", "static async build(url) {\n let resp = await fetch(url + \"/v1/parameters\");\n let params = await resp.text();\n let client = new Client(url, params, module);\n return client;\n }", "async function downloadDiscoveryDocs(options) {\n await exports.gfs.mkdir(options.downloadPath);\n const headers = options.includePrivate\n ? {}\n : { 'X-User-Ip': '0.0.0.0' };\n console.log(`sending request to ${options.discoveryUrl}`);\n const res = await gaxios_1.request({ url: options.discoveryUrl, headers });\n const apis = res.data.items;\n const indexPath = path.join(options.downloadPath, 'index.json');\n exports.gfs.writeFile(indexPath, res.data);\n const queue = new p_queue_1.default({ concurrency: 25 });\n console.log(`Downloading ${apis.length} APIs...`);\n const changes = await queue.addAll(apis.map(api => async () => {\n console.log(`Downloading ${api.id}...`);\n const apiPath = path.join(options.downloadPath, api.id.replace(':', '-') + '.json');\n const url = api.discoveryRestUrl;\n const changeSet = { api, changes: [] };\n try {\n const res = await gaxios_1.request({ url });\n // The keys in the downloaded JSON come back in an arbitrary order from\n // request to request. Sort them before storing.\n const newDoc = sortKeys(res.data);\n let updateFile = true;\n try {\n const oldDoc = JSON.parse(await exports.gfs.readFile(apiPath));\n updateFile = shouldUpdate(newDoc, oldDoc);\n changeSet.changes = getDiffs(oldDoc, newDoc);\n }\n catch (_a) {\n // If the file doesn't exist, that's fine it's just new\n }\n if (updateFile) {\n exports.gfs.writeFile(apiPath, newDoc);\n }\n }\n catch (e) {\n console.error(`Error downloading: ${url}`);\n }\n return changeSet;\n }));\n return changes;\n}", "async discoverAPI(apiPath, options = {}) {\n const endpointCreator = await this._discovery.discoverAPI(apiPath);\n const ep = endpointCreator(options, this);\n ep.google = this; // for drive.google.transporter\n return Object.freeze(ep);\n }", "function _buildApiUrl (datasetname, coursekey) {\n\t\tlet url = API_BASE;\n\t\turl += '?key=' + API_KEY;\n\t\turl += datasetname && datasetname !== null ? '&dataset=' + datasetname : '';\n\t\turl += coursekey && coursekey !== null ? '&coursekey=' + coursekey : '';\n\t\t//console.log('buildApiUrl: url=' + url);\n\t\t\n\t\treturn url;\n\t}", "static get API_URL() {\r\n const port = 1337; // Change this to your server port\r\n return `http://localhost:${port}/`;\r\n }", "function getUrl() {\n url = \"https://api.nasa.gov/EPIC/api/natural/date/\" + date + \"?api_key=\" + API_KEY;\n}", "get __generateRequestURL() {\n const {\n folderName,\n name\n } = this.fsProcessor.file;\n\n return String(`${this.resource}/_api/web/GetFolderByServerRelativeUrl('${folderName}')/Files('${name}')/$value`);\n }", "function exportIodocs(src){\n var obj = clone(src,false);\n obj.swagger = '2.0';\n obj.info = {};\n obj.info.version = obj.version || '1';\n obj.info.title = obj.name;\n obj.info.description = obj.description;\n obj.paths = {};\n\n var u = url.parse(obj.basePath+obj.publicPath);\n obj.schemes = [];\n obj.schemes.push(u.protocol.replace(':',''));\n obj.host = u.host;\n obj.basePath = u.path;\n\n delete obj.version;\n delete obj.title;\n delete obj.description;\n delete obj.publicPath;\n delete obj.privatePath; // for oauth etc\n delete obj.protocol;\n delete obj.name;\n delete obj.auth; // TODO\n delete obj.oauth; // TODO\n delete obj.headers; // TODO\n rename(obj,'schemas','definitions');\n if (obj.definitions) fixSchema(obj.definitions);\n\n for (var r in obj.resources) {\n var resource = obj.resources[r];\n // do tags\n for (var m in resource.methods) {\n var method = resource.methods[m];\n method.path = fixPathParameters(method.path);\n\n if (!obj.paths[method.path]) obj.paths[method.path] = {};\n var path = obj.paths[method.path];\n\n var httpMethod = method.httpMethod.toLowerCase();\n if (!path[httpMethod]) path[httpMethod] = {};\n\n var op = path[httpMethod];\n op.operationId = m;\n op.description = method.description;\n op.parameters = [];\n\n for (var p in method.parameters) {\n var param = method.parameters[p];\n param.name = p;\n if (param.title) rename(param,'title','name');\n if ((param.type == 'textarea') || (param.type == 'enumerated')) param.type = 'string';\n if (param.type == 'long') param.type = 'number';\n if (param.type == 'string[]') {\n param.type = 'array';\n param.items = {};\n param.items.type = 'string';\n }\n rename(param,'location','in');\n if (!param[\"in\"]) {\n if (method.path.indexOf('{'+param.name+'}')>=0) {\n param[\"in\"] = 'path';\n }\n else {\n param[\"in\"] = 'query';\n }\n }\n if ((param[\"in\"] == 'body') && (param.type != 'object')) {\n param[\"in\"] = 'formData'; // revalidate\n }\n if (param[\"in\"] == 'pathReplace') {\n param[\"in\"] = 'path';\n }\n if (param[\"in\"] == 'path') {\n param.required = true;\n }\n if (typeof param.required == 'string') {\n param.required = (param.required === 'true');\n }\n if (param.properties) {\n delete param.type;\n param.schema = {};\n param.schema.type = 'object';\n param.schema.properties = param.properties;\n delete param.properties;\n delete param[\"default\"];\n fixSchema(param.schema);\n }\n if (param.items) fixSchema(param.items);\n op.parameters.push(param);\n }\n op.tags = [];\n op.tags.push(r);\n\n op.responses = {};\n op.responses[\"200\"] = {};\n op.responses[\"200\"].description = 'Success';\n\n }\n }\n\n delete obj.resources;\n return obj;\n}", "function constructFlurryAppInfoEndpoint(){\n url_app_metric_specific = 'getApplication';\n url_new_Flurry = base_url_Flurry + 'appInfo/' + url_app_metric_specific + '/?apiAccessCode=' + apiAccessCode + '&apiKey=' + apiKey;\n return url_new_Flurry;\n}", "function buildTrainApiURl() {\n\n // if (new Date().getHours() >= 11) {\n // return 'https://huxley2.azurewebsites.net/delays/read/30?accessToken=b09cb836-f190-445d-8b96-372eb024141d&expand=true';\n // } else {\n // return 'https://huxley2.azurewebsites.net/delays/tot/30?accessToken=b09cb836-f190-445d-8b96-372eb024141d&expand=true';\n // }\n return 'https://huxley2.azurewebsites.net/delays/tot/30?accessToken=b09cb836-f190-445d-8b96-372eb024141d&expand=true';\n}", "_createApiUrl() {\n this._apiUrl = `https://api.trello.com/1/cards/${this._cardId}/attachments/${this._attachmentId}`;\n }", "loadAPI(api) {\n if (api !== '') {\n let files = [];\n let overrides = new Map();\n\n for (let param of api.slice(1).split('&')) {\n let [key, value] = param.split('=');\n\n if (value !== undefined) {\n // Test also overrides.\n files.push(value);\n\n if (key.startsWith('override')) {\n // Discord changes \\ to / in urls, ignoring escaping, so escape manually.\n overrides.set(key.slice(9, -1).replace(/\\//g, '\\\\'), value);\n }\n }\n }\n\n if (files.length) {\n let pathSolver = (src, params) => {\n let override = overrides.get(basename(src).toLowerCase());\n\n if (override) {\n return override;\n } else {\n return localOrHive(src, params);\n }\n };\n\n let render = true;\n\n for (let file of files) {\n fetch(file)\n .then(async (response) => {\n let buffer;\n\n if (file.endsWith('.mdl')) {\n buffer = await response.text();\n } else {\n buffer = await response.arrayBuffer();\n }\n\n this.test(file, buffer, render, pathSolver);\n\n render = false;\n });\n }\n }\n }\n }", "function getResourceUrl() { return \"http://\"+location.href.split(\"//\")[1].split(\"/\").splice(0,3).join(\"/\")+'.json?api_key='+MoviePilot.apikey;}", "static makeAPICall(endpoint, input, options = {}) {\n switch (endpoint) {\n case GET_TOKEN:\n if (options.body === undefined) {\n options.body = {};\n }\n options.body.client_id = process.env.REACT_APP_CLIENT_ID;\n return this._fetchFromAPI(this.authUrlBeginning + \"token/\", options);\n case CREATE_USER:\n return this._fetchFromAPI(this.urlBeginning + \"createUser/\", options);\n case VALIDATE_TOKEN:\n return this._addAuthorization(this.urlBeginning + \"validateToken/\");\n case FORGOT_PASSWORD:\n return this._fetchFromAPI(this.urlBeginning + \"password_reset/\", options);\n case RESET_PASSWORD:\n return this._fetchFromAPI(this.urlBeginning + \"password_reset/confirm\", options);\n case UPLOAD_DOCUMENT:\n return this._addAuthorization(this.urlBeginning + \"uploadDoc/\", options);\n case UPLOAD_ANNOTATIONS:\n return this._addAuthorization(this.urlBeginning + \"uploadAnnot/\", options);\n case GET_ALL_ANNOTE_BY_CURRENT_USER:\n return this._addAuthorization(this.urlBeginning + \"getAllMyAnnots/\" + (input == null ? \"\" : input));\n case GET_ALL_ANNOTE:\n return this._addAuthorization(this.urlBeginning + \"getAllAnnots/\" + (input == null ? \"\" : input));\n case GET_ANNOTATIONS_FILENAME_USER:\n return this._addAuthorization(this.urlBeginning + \"getAnnotationsByFilenameUser/\" + input + this.json);\n case EXPORT_CURRENT_ANNOTATIONS:\n return this._addAuthorization(this.urlBeginning + \"exportAnnotations/\" + input + this.json);\n case DOWNLOAD_ANNOTATIONS_BY_ID:\n return this._addAuthorization(this.urlBeginning + \"downloadAnnotations/\" + input + this.json);\n\n // ICD APIs\n case ANCESTORS:\n return this._addAuthorization(this.urlBeginning + \"ancestors/\" + input + this.json);\n case FAMILY:\n return this._addAuthorization(this.urlBeginning + \"family/\" + input + this.json);\n case CODE_AUTO_SUGGESTIONS:\n return this._addAuthorization(this.urlBeginning + \"codeAutosuggestions/\" + input + this.json);\n case CODE_DESCRIPTION:\n return this._addAuthorization(this.urlBeginning + \"codeDescription/\" + input + this.json);\n default:\n return null;\n }\n }", "function API(){}", "function API(){}" ]
[ "0.656145", "0.6030883", "0.5935256", "0.59350294", "0.58844376", "0.5838028", "0.57900196", "0.5760698", "0.57544667", "0.57283306", "0.5676726", "0.5670042", "0.5663588", "0.56103104", "0.55902857", "0.5535263", "0.55132025", "0.5500699", "0.5480999", "0.54696363", "0.54557115", "0.5449722", "0.5445687", "0.54445547", "0.54223114", "0.5408955", "0.5405568", "0.5398795", "0.5371627", "0.5371627" ]
0.71088165
0
Funcion a la que llamamos cuando se produce el "drag" Hacemos que el evento pueda transferir un dato ("informacion")
function drag(ev) { ev.dataTransfer.setData("Informacion", ev.target.id); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function drag(ev)\n{\n ev.dataTransfer.setData(\"message\", ev.target.id);\n}", "function dragInicio(ev) {\n ev.dataTransfer.setData(\"Text\", ev.target.id);\n}", "drag(event) {\n event.dataTransfer.setData(\"divId\", event.target.id);\n console.log(\"----drag----:\");\n }", "function drag (event) {\r\n console.log(\"drag FN start\");\r\n console.log(event);\r\n draggedPic = event.target; // TODO draggedPic\r\n event.dataTransfer.setData(\"text\", event.target.id);\r\n event.dataTransfer.effectAllowed = \"move\";\r\n}", "function drag(event) {\n event.dataTransfer.setData(\"artikel_id\", event.srcElement.id);\n\n}", "function drag(ev) {\n console.log(ev.dataTransfer);\n if(ev.target.id){\n console.log(ev.dataTransfer);\n ev.dataTransfer.setData(\"text\", ev.target.id);\n \n }\n console.log(ev.target.dataset.index);\n if(ev.target.dataset.index){\n console.log(\"tem ue\");\n ev.dataTransfer.setData(\"el-index\", ev.target.dataset.index);\n }\n}", "function eventosFichas() {\n\n var fichas = document.querySelectorAll(\".arrastrables div\");\n\n for (i = 0; i < fichas.length; i++) {\n fichas[i].addEventListener(\"dragstart\",\n function (event) {\n event.dataTransfer.setData(\"text\", event.target.id);\n });\n }\n}", "function start(ev) {\n //guardo el id del elemento que estoy arrastrando\n ev.dataTransfer.setData(\"name\", ev.target.id);\n console.log( ev.target.id);\n}", "drag(ev) {\n // console.log('drag')\n }", "function ondragstart(event) {\n var x = event.currentTarget\n x.style.border = \"dashed\"\n var datatransfer = event.dataTransfer.setData('text/plain', event.target.id)\n}", "function dragStartFunction(e) {\r\n e.dataTransfer.setData(\"target\", e.target.id)\r\n\r\n\r\n}", "function dragtaskStart(ev) {\n ev.dataTransfer.setData(\"text/plain\", ev.target.id);\n}", "startDrag(event) {\n event.dataTransfer.setData(\"text\", event.target.id);\n }", "function drag(e) {\n e.dataTransfer.setData('transfer', e.target.id);\n }", "function onDragStart(event) {\n //Store data to record movement\n this.data = event.data;\n this.alpha = 0.5;\n this.dragging = true;\n \n}", "function drag_start(event) {\n const style = window.getComputedStyle(event.target, null);\n event.dataTransfer.setData(\"text/plain\",\n (parseInt(style.getPropertyValue(\"left\"),10) - event.clientX) + ',' + (parseInt(style.getPropertyValue(\"top\"),10) - event.clientY));\n }", "dragStartSetData(e) {\n e.dataTransfer.setData(\"Text\", this.props.data.id);\n }", "function drag(event, datum) {\n event.dataTransfer.setData(\"connector\", JSON.stringify(datum));\n }", "function _onDrop(e)\n {\n // compatibilidad para firefox\n var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;\n if (isFirefox) {\n e.preventDefault();\n }\n\n // obtener origen del dulce\n var src = e.dataTransfer.getData(\"text\");\n var sr = src.split(\"_\")[1];\n var sc = src.split(\"_\")[2];\n\n // obtener destino del dulce\n var dst = e.target.id;\n var dr = dst.split(\"_\")[1];\n var dc = dst.split(\"_\")[2];\n\n // si la distancia es mayor a 1, no permitir el movimiento y alertar\n var ddx = Math.abs(parseInt(sr)-parseInt(dr));\n var ddy = Math.abs(parseInt(sc)-parseInt(dc));\n \n \n if (ddx > 1 || ddy > 1)\n {\n alert(\"El cambio solo puede ser con el dulce adyacente\");\n return;\n }\n else if (ddx == 1 && ddy == 1)\n {\n alert(\"Los cambios no pueden ser en diagonal\");\n return;\n }\n else{\n // intercambio de dulces\n var tmp_o = grid[sr][sc].src;\n var tmp_d = grid[dr][dc].src;\n grid[sr][sc].src = grid[dr][dc].src;\n grid[sr][sc].o.attr(\"src\",grid[sr][sc].src);\n grid[dr][dc].src = tmp_o;\n grid[dr][dc].o.attr(\"src\",grid[dr][dc].src);\n\n //validar intercambio\n var resBus = validarCoincidencias();\n console.log(\"Busqueda: \" + resBus);\n \n if(resBus==0)\n {\n alert(\"No genera combinación\");\n grid[sr][sc].src = tmp_o;\n grid[sr][sc].o.attr(\"src\",grid[sr][sc].src);\n grid[dr][dc].src = tmp_d;\n grid[dr][dc].o.attr(\"src\",grid[dr][dc].src);\n return;\n }\n\n // sumar un movimiento\n moves+=1;\n $(\"#movimientos-text\").html(moves);\n\n //buscar coincidencias\n buscarCoincidencias(); \n }\n }", "drag(evt) {\n\n console.log(evt.target.id);\n evt.dataTransfer.setData(\"text\", evt.target.id);\n }", "onDragStart({dataTransfer: dt, currentTarget: t}) { dt.setData('text', t.src) }", "function drag(ev) \n{\n ev.dataTransfer.setData(\"text\", ev.target.id);\n //$('#'+ev.target.id).draggable( {cursor: 'move'} );\n}", "onDragStart(e, name){\n console.log('now dragging',name);\n e.dataTransfer.setData(\"name\", name);\n }", "function drag(ev){\r\n\t//console.log(ev.target.parentNode);\r\n\tvar ss = (parseInt($(ev.target.parentNode).position().left,10) - ev.clientX) + ',' + (parseInt($(ev.target.parentNode).position().top,10) - ev.clientY);\r\n\tev.dataTransfer.setData(\"text/plain\", ss + ',' + $(ev.target.parentNode).attr('id'));\r\n\t//ev.dataTransfer.setDragImage(document.getElementById(\"draggit\"), 10, 10);\r\n\t//console.log(\"drag:target\", $(ev.target).position().left + \",\" + $(ev.target).position().top);\r\n\t//console.log(\"drag:offset\", ss);\r\n\t//console.log();\r\n}", "function drag(ev){\n ev.dataTransfer.setData(\"text\", ev.target.id);\n}", "function drag(ev) {\n const zval = ev.target.getAttribute(\"data-z-value\");\n const zvalue = ( zval == null || zval === ' ') ? 0 : zval;\n\n const functionName = (! ev.target.getAttribute(\"data-polemic\")) ?\n ev.target.getAttribute(\"data-function\"): ev.target.getAttribute(\"data-polemic\");\n\n ev.dataTransfer.setData(\"text\",\n JSON.stringify({ name: functionName,\n function : ev.target.getAttribute(\"data-function\"),\n id: ev.target.id,\n value: ev.target.getAttribute(\"data-value\"),\n z: zvalue\n }));\n dragged = ev.target;\n //style with border on transfer\n ev.target.style.border = \"2px solid red\";\n}", "function dragStart(event) {\r\n event.dataTransfer.setData(\"Text\", event.target.id);\r\n}", "function dragStart(event) {\n event.dataTransfer.setData(\"text\", event.target.id); // or \"text/plain\" but just \"text\" would also be fine since we are not setting any other type/format for data value\n}", "function drag(e) {\r\n //draggedItem = e.target; No need for a global variable here\r\n e.dataTransfer.setData(\"text\", e.target.id); // set data in drag and drop event to dragged element's id\r\n dragging = true;\r\n}", "function dragStart(event) {\r\n\tevent.dataTransfer.setData(\"text\",event.target.id);\r\n}" ]
[ "0.7279743", "0.7160809", "0.70878005", "0.70050955", "0.69658244", "0.69637895", "0.6928682", "0.69212824", "0.6917103", "0.68803", "0.68770295", "0.687124", "0.6871131", "0.6853929", "0.68068993", "0.6798106", "0.677846", "0.67727715", "0.675692", "0.6748166", "0.67340213", "0.67115176", "0.6707023", "0.670227", "0.6680329", "0.6675508", "0.66435915", "0.66407067", "0.664044", "0.663788" ]
0.7715458
0
Load the game, and create the board.
function loadGame(){ game = getJSON("http://navy.hulu.com/[email protected]"); board = []; // Display game information writeToConsole("GAME ID = " + game.game_id); writeToConsole("SHIPS = [" + game.ship_sizes + "]"); writeToConsole("BOARD = (" + game.board_size.width + ", " + game.board_size.height + ")"); // Intialize board to default values for(var w=0; w<game.board_size.width; w++){ board[w] = []; for(var h=0; h<game.board_size.height; h++){ board[w][h]=0; // signifies uninspected } } ships = game.ship_sizes; raiseSuccess("Game intialized"); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function create_game_board(){\n update_number_of_players();\n create_player_areas();\n // create new game\n game_instance.deal_cards();\n \n render_cards();\n apply_card_event_handlers();\n \n game_instance.determine_winners();\n // determine_winners();\n // show_best_hands(); //for diagnostics\n }", "load() {\n if (!!this.saveArray) {\n this.board = this.saveArray[0];\n this.currentColour = this.saveArray[1];\n this.currentColour == 'white' ? this.otherColour = 'black' : this.otherColour = 'white';\n this.displayBoard();\n console.log(\"game loaded\");\n }\n }", "function loadGame() {\n ticTacToeBoard.createBoard();\n loadStatus();\n loadHistory();\n //display to index.htm\n document.getElementById(\"game\").innerHTML = ticTacToeBoard.displayBoard();\n}", "function initGame() {\n gBoard = buildBoard(gLevel);\n renderBoard();\n}", "function loadBoard(campaign, state) {\n var lev = state.current_level\n var boardConfig = campaign[lev.world_index].levels[lev.level_index].level\n\n var board = {\n num_cols: boardConfig.num_cols,\n num_rows: boardConfig.num_rows,\n coins: cloneDeep(boardConfig.coins),\n blocks: cloneDeep(boardConfig.blocks),\n traps: cloneDeep(boardConfig.traps),\n coinsCollected: 0\n }\n\n /**\n * Contains all data that is needed to visualize the board and game state.\n * How can you tell what data belongs in board.visualize?\n * Data should appear in board.visualize if, and only if, the data is\n * ignored in \"headless\" mode (i.e. non-visualization mode).\n */\n board.visualize = {\n\n // mutable data that persists across simulator steps\n persist: {},\n\n // immutable data that is valid for only one simulation step. Every\n // simulation step begins by erasing the contents of step.\n step: {}\n }\n\n if (\"hint\" in boardConfig) {\n board.visualize.persist.hint = boardConfig.hint\n }\n \n // the index of the bot being programmed by the code editor\n // TODO: this should be bot __id__ not bot __index__\n // TODO: this should go into board.visualize.persist\n board.visualize.programming_bot_index = boardConfig.programming_bot_index\n\n board.win_conditions = cloneDeep(boardConfig.win_conditions)\n\n board.constraints = cloneDeep(boardConfig.constraints)\n\n /**\n * The awards that will be given to the player once the level is\n * completed.\n */\n board.badges = cloneDeep(boardConfig.badges)\n\n // set to true once victory has been achieved\n board.victory = false\n\n board.markers = newMatrix(\n board.num_cols,\n board.num_rows,\n function () {\n return newMatrix(\n Direction.NUM_DIRECTIONS,\n BotColor.NUM_COLORS, undefined)\n })\n\n board.bots = []\n\n for (var i = 0; i < boardConfig.bots.length; i++) {\n var configBot = boardConfig.bots[i]\n var program = compilePuzzleCode(configBot.program, board)\n\n assert(program.constraintViolation == false,\n \"loadBoard: program.constraintViolation == false\")\n\n if (program.instructions == null) {\n // TODO: handle this error better\n console.error(\"Could not compile: \" + configBot.program)\n } else {\n var bot = {\n // bot.id is immutable, and unique only w.r.t. this board\n id: i,\n cellX: configBot.cellX,\n cellY: configBot.cellY,\n botColor: configBot.botColor,\n facing: configBot.facing,\n ip: 0,\n program: program\n }\n board.bots.push(bot)\n }\n }\n\n // newly created bots get id == board.next_bot_id\n // don't need to worry about int overflows on bot ids because JS uses floats\n board.next_bot_id = boardConfig.bots.length\n\n return board\n}", "function createBoard() {\n\tconst board = document.querySelector('.game');\n\tconst rows = document.createElement('tr');\n\n\t//Create the head row\n\trows.setAttribute('id', 'HeaderRow');\n\trows.classList.add('row');\n\trows.addEventListener('click', (e) => {\n\t\tgamePlay(e);\n\t});\n\n\t//Create the header column and append to header row\n\tfor (let col = 0; col < WIDTH; col++) {\n\t\tconst cols = document.createElement('td');\n\t\tcols.setAttribute('id', `c${col}`);\n\t\tcols.classList.add('colHead');\n\t\trows.append(cols);\n\t}\n\n\t// Append to board\n\tboard.append(rows);\n\n\t//Create the remaining boards\n\tfor (let myRow = 0; myRow < HEIGHT; myRow++) {\n\t\tconst row = document.createElement('tr');\n\t\tfor (let myCol = 0; myCol < WIDTH; myCol++) {\n\t\t\tconst cols = document.createElement('td');\n\t\t\tcols.setAttribute('id', `r${myRow}c${myCol}`);\n\t\t\tcols.dataset.row = myRow;\n\t\t\tcols.dataset.col = myCol;\n\t\t\tcols.classList.add('col');\n\t\t\trow.append(cols);\n\t\t}\n\t\tboard.append(row);\n\t}\n}", "function createBoard() {\n window.board = new Board(4, 13);\n createCards();\n window.board.placeCards();\n}", "function importBoard() {\n let grid = board.createGrid(); // will return our board element\n // let surface_element = document.createElement('div')\n // surface_element.style.position = \"relative\"\n // surface_element.style\n obstacles = obstacle.creationBasedOnArray(\n ArrayForObstacles[\"level\" + currentLevel]\n );\n parent_container.appendChild(grid); // assign the location in our dom we want to put it in\n}", "function game_initBoard(){\n\t//get map from data.\n\tvar mapdata=data_map[GLOBAL['gid']].map;\n\tvar spawntiles=[];\n\tGLOBAL['board']=[];\n\t//copy data into a board of tile objects\n\tfor(var i=0;i<mapdata.length;i++){\n\t\tGLOBAL['board'][i]=[];\n\t\tfor(var j=0;j<mapdata[i].length;j++){\n\t\t\tvar tile={x:i,y:j,type:mapdata[i][j]};\n\t\t\ttile.color=Math.round(170+(Math.random()*30));\n\t\t\tif(tile.type==2){\n\t\t\t\tspawntiles.push(tile);\n\t\t\t}\n\t\t\tGLOBAL['board'][i][j]=tile;\n\t\t}\n\t}\n\tvar xmax=46*GLOBAL['board'].length;\n\tvar ymax=46*GLOBAL['board'][0].length;\n\t//share the board offset, and spawn tiles.\n\n\tGLOBAL['gamevars'].xoffset=Math.round(($('#game')[0].width-xmax)/2);\n\tGLOBAL['gamevars'].yoffset=Math.round(($('#game')[0].height-ymax)/2);\n\tGLOBAL['gamevars'].spawnpoints=spawntiles;\n}", "function initGame() {\n\tdebugAlert(\"initGame\", false);\n\tif(gGameActive === true) return;\n\t\n\tgBoardRowCount = 8;//document.getElementById(\"row\").value;\n\tgBoardColumnCount = 6;//document.getElementById(\"column\").value;\n\t\n\t//Create the play area canvas and listeners\n\tgPlayAreaCanvas = createCanvas(getPlayAreaWidth(), getPlayAreaHeight());\n\tgPlayAreaCanvasDrawingContext = gPlayAreaCanvas.getContext(\"2d\");\n\taddListenerToElement(gPlayAreaCanvas,onMouseMovePlayArea,\"mousemove\");\n\taddListenerToElement(gPlayAreaCanvas,onMouseClickPlayArea,\"click\");\n\t\n\t//Create the tile chooser canvas and listeners\n\tgTileChooserCanvas = createCanvas(getTileLayoutWidth(), getTileLayoutHeight());\n\tgTileCanvasDrawingContext = gTileChooserCanvas.getContext(\"2d\");\n\taddListenerToElement(gTileChooserCanvas, onMouseClick,\"click\");\n\taddListenerToElement(gTileChooserCanvas, onDoubleClick,\"dblclick\");\n\taddListenerToElement(gTileChooserCanvas,onMouseMoveTileArea,\"mousemove\");\n\n\t//Create the tiles\n\tiRightElbow = new Image();\n\tiRightElbow.src = \"elbow.png\";\n\tiLeftElbow = new Image();\n\tiLeftElbow.src = \"elbow2.png\";\n\t\n\tiStraight = new Image();\n\tiStraight.src = \"straight.png\";\n\tiPlumber = new Image();\n\tiPlumber.src = \"plumber.jpg\";\n\tiToilet = new Image();\n\tiToilet.addEventListener(\"load\", function(){\n\t\t//after the resources are loaded start a new game\n\t\tflushHandle();\n\t\tnewGame();\n\t\tgGameActive = true;\n\t}, false);\n\tiToilet.src =\"toilet.png\";\n}", "function load() {\r\n\t\tvar loaded = $.parseJSON(localStorage.getItem(STORAGE_NAME)),\r\n\t\t\tcondition = loaded.condition;\r\n\t\tSIZE = loaded.size;\r\n\t\tTOTALCELLS = SIZE*SIZE;\r\n\t\tMINES = loaded.minecells.length;\r\n\t\tcells = loaded.cells;\r\n\t\tminecells = loaded.minecells;\r\n\t\ttime = loaded.time;\r\n\t\tclicks = loaded.clicks;\r\n\t\tnewGame(true, loaded.board, condition);\r\n\t}", "function load() {\n if (generate) return\n\n\n const canvas = canvasRef.current;\n canvas.width = width;\n canvas.height = height;\n ctx.current.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);\n let resGrid = buildGrid()\n\n let colDiff = Math.round((resGrid.length - loadGrid.grid.length) / 2)\n let rowDiff = Math.round((resGrid[0].length - loadGrid.grid[0].length) / 2)\n\n if (resGrid.length > loadGrid.grid.length) {\n for (let col = 0; col < loadGrid.grid.length; col++) {\n for (let row = 0; row < loadGrid.grid[col].length; row++) {\n resGrid[col + colDiff][row + rowDiff] = loadGrid.grid[col][row]\n }\n }\n setGrid(resGrid)\n } else {\n for (let col = 0; col < resGrid.length; col++) {\n for (let row = 0; row < resGrid[col].length; row++) {\n resGrid[col][row] = loadGrid.grid[col - colDiff][row - rowDiff];\n }\n }\n\n setGrid(resGrid)\n }\n renderLifeBox()\n genCount.current = 0\n }", "function initLoad()\n{\n console.log('page load');\n myGame.buildBoard();\n myGame.nextMove();\n myGame.reset();\n}", "function initialise() {\n\tboard = new Board();\n\n\tvar handler = createDiv();\n\thandler.parent('#bagh-chal');\n\thandler.id('handler');\n\n\t// --- Game Properties ---\n\tvar propertiesDiv = createDiv();\n\tpropertiesDiv.child(createElement('h3', 'Game'));\n\tpropertiesDiv.parent('#handler');\n\tpropertiesDiv.id('properties');\n\n\t// Turn\n\tvar turnSpan = createSpan('Turn: ');\n\tturnSpan.parent('#properties');\n\tturnSpan.child(turnP = createP('?'));\n\n\t// Goats In-Hand\n\tvar goatsInHandSpan = createSpan('Goats In-Hand: ');\n\tgoatsInHandSpan.parent('#properties');\n\tgoatsInHandSpan.child(goatsInHandP = createP('?'));\n\n\t// Goats Captured\n\tvar goatsCapturedSpan = createSpan('Goats Captured: ');\n\tgoatsCapturedSpan.parent('#properties');\n\tgoatsCapturedSpan.child(goatsCapturedP = createP('?'));\n\n\t// Tigers Trapped\n\tvar tigersTrappedSpan = createSpan('Tigers Trapped: ');\n\ttigersTrappedSpan.parent('#properties');\n\ttigersTrappedSpan.child(tigersTrappedP = createP('?'));\n\n\t// Status\n\tvar statusSpan = createSpan('Status: ');\n\tstatusSpan.parent('#properties');\n\tstatusSpan.child(statusP = createP('Running').class('running'));\n\n\t// --- Controls ---\n\tvar controlsDiv = createDiv();\n\tcontrolsDiv.parent('#handler');\n\tcontrolsDiv.id('controls');\n\tcontrolsDiv.child(createElement('h3', 'Controls'));\n\n\t// Game Mode\n\tcontrolsDiv.child(gameMode = createSelect());\n\tgameMode.option('Game Mode');\n\tgameMode.option('Player vs Player', 0);\n\tgameMode.option('Player vs AI', 1);\n\tgameMode.option('AI vs AI', 2);\n\tgameMode.value(1);\n\tgameMode.changed(updateHandler);\n\n\t// Play As\n\tcontrolsDiv.child(playAsSelect = createSelect());\n\tplayAsSelect.option('Play As');\n\tplayAsSelect.option('Tiger', 0);\n\tplayAsSelect.option('Goat', 1);\n\tplayAsSelect.value(playAsTiger ? 0 : 1);\n\tplayAsSelect.changed(changePlayAs);\n\n\t// Goat Algorithm/Depth\n\tcontrolsDiv.child(goatP = createP('Goat'));\n\tcontrolsDiv.child(goatAlgorithm = createSelect());\n\tgoatAlgorithm.option('Algorithm');\n\tgoatAlgorithm.option('Minimax', 0);\n\tgoatAlgorithm.option('Alpha-Beta', 1);\n\tgoatAlgorithm.option('MCTS', 2);\n\tgoatAlgorithm.value(1);\n\tgoatAlgorithm.changed(updateHandler);\n\n\tcontrolsDiv.child(goatDepth = createSelect());\n\tgoatDepth.option('Depth');\n\tgoatDepth.option('Depth 1 (Very Easy)', 1);\n\tgoatDepth.option('Depth 2 (Easy)', 2);\n\tgoatDepth.option('Depth 3 (Moderate)', 3);\n\tgoatDepth.option('Depth 4 (Hard)', 4);\n\tgoatDepth.option('Depth 5 (Very Hard)', 5);\n\tgoatDepth.value(3);\n\tgoatDepth.changed(reset);\n\n\tcontrolsDiv.child(goatTime = createSelect());\n\tgoatTime.option('Time');\n\tgoatTime.option('2s', 2);\n\tgoatTime.option('4s', 4);\n\tgoatTime.option('6s', 6);\n\tgoatTime.option('8s', 8);\n\tgoatTime.option('10s', 10);\n\tgoatTime.value(2);\n\tgoatTime.changed(reset);\n\n\t// Tiger Algorithm/Depth\n\tcontrolsDiv.child(tigerP = createP('Tiger'));\n\tcontrolsDiv.child(tigerAlgorithm = createSelect());\n\ttigerAlgorithm.option('Algorithm');\n\ttigerAlgorithm.option('Minimax', 0);\n\ttigerAlgorithm.option('Alpha-Beta', 1);\n\ttigerAlgorithm.option('MCTS', 2);\n\ttigerAlgorithm.value(1);\n\ttigerAlgorithm.changed(updateHandler);\n\n\tcontrolsDiv.child(tigerDepth = createSelect());\n\ttigerDepth.option('Depth');\n\ttigerDepth.option('Depth 1 (Very Easy)', 1);\n\ttigerDepth.option('Depth 2 (Easy)', 2);\n\ttigerDepth.option('Depth 3 (Moderate)', 3);\n\ttigerDepth.option('Depth 4 (Hard)', 4);\n\ttigerDepth.option('Depth 5 (Very Hard)', 5);\n\ttigerDepth.value(3);\n\ttigerDepth.changed(reset);\n\n\tcontrolsDiv.child(tigerTime = createSelect());\n\ttigerTime.option('Time');\n\ttigerTime.option('2s', 2);\n\ttigerTime.option('4s', 4);\n\ttigerTime.option('6s', 6);\n\ttigerTime.option('8s', 8);\n\ttigerTime.option('10s', 10);\n\ttigerTime.value(2);\n\ttigerTime.changed(reset);\n\n\t// Delay\n\tdelaySpan = createSpan('Min. Simulation Delay');\n\tdelaySpan.parent('#controls');\n\tdelaySpan.child(delaySlider = createSlider(0, 500, 250));\n\n\t// Reset\n\tcontrolsDiv.child(resetButton = createButton('Reset'));\n\tresetButton.mousePressed(reset);\n\n\t// Pause\n\tcontrolsDiv.child(pauseButton = createButton('Pause'));\n\tpauseButton.mousePressed(togglePause);\n\n\t// --- AI Debugging ---\n\tdebuggingDiv = createDiv();\n\tdebuggingDiv.parent('#handler');\n\tdebuggingDiv.id('debugging');\n\tdebuggingDiv.child(createElement('h3', 'AI Debugging'));\n\n\t// Iterations\n\tvar iterationsSpan = createSpan('Iterations: ');\n\titerationsSpan.parent('#debugging');\n\titerationsSpan.child(countP = createP('?'));\n\n\t// Time\n\tvar timeSpan = createSpan('Time to Run: ');\n\ttimeSpan.parent('#debugging');\n\ttimeSpan.child(timeP = createP('?'));\n\n\t// Score\n\tvar scoreSpan = createSpan('Score/Wins: ');\n\tscoreSpan.parent('#debugging');\n\tscoreSpan.child(scoreP = createP('?'));\n\n\t// Tiger Wins\n\t//var scoreSpan = createSpan('Tiger Wins: ');\n\t//scoreSpan.parent('#debugging');\n\t//scoreSpan.child(tigerWinsP = createP('?'));\n\n\t// Goat Wins\n\t//var scoreSpan = createSpan('Goat Wins: ');\n\t//scoreSpan.parent('#debugging');\n\t//scoreSpan.child(goatWinsP = createP('?'));\n\n\t// Draws\n\t//var scoreSpan = createSpan('Draws: ');\n\t//scoreSpan.parent('#debugging');\n\t//scoreSpan.child(drawsP = createP('?'));\n\n\t// Update what's disabled/hidden\n\t$('select > option:first-child').attr('disabled', true);\n\tupdateHandler();\n}", "create () {\n /****game.var adds a new \"class variable\" to game state, like in other languages****/\n\n //create background\n var background = game.add.sprite(game.world.centerX, game.world.centerY, 'background');\n background.anchor.set(0.5);\n background.width = game.screenWidth;\n background.height = 700;\n\n game.boardHeight = 102\n game.boardOffset = 15\n game.pieceWidth = 38\n game.pieceHeight = 25\n\n game.squareSize = 50\n //the size of the board, i.e nxn board, 3x3 for tictactoe\n game.n = 3\n game.isXTurn = true\n game.isDraw = false\n game.magicSquare = false\n game.firstTime = true\n\n\n game.turns = 0\n game.linesToAnimate = 0\n\n game.boardTurns = [];\n for (var i=0; i < game.n; i++) {\n game.boardTurns[i]=new Array(game.n)\n }\n\n for (var i=0; i < game.n; i++)\n {\n for (var j=0; j < game.n; j++)\n {\n game.boardTurns[i][j] = 0\n }\n }\n\n console.log(\"First Time\")\n\n //the top left coordinate to place the whole board at, we will make game\n //not hardcoded in the furture to center the board, but I believe we need jQuery\n //to get window size and I didn't feel like learning that right now\n game.startingX = game.screenWidth/2 - game.cache.getImage('board').width / 1.2\n game.startingY = 80\n\n //intialize waiting status to false, update accordingly later if multiplayer\n game.waiting = false\n\n //record of the pieces that have been placed\n game.placedPieces = []\n\n //record of the big pieces that have been placed\n game.bigPlacedPieces = []\n\n game.bigBoardLogic = []\n for (var i=0; i < game.n; i++) {\n game.bigBoardLogic[i]=new Array(game.n)\n }\n\n for (var i=0; i < game.n; i++)\n {\n for (var j=0; j < game.n; j++)\n {\n game.bigBoardLogic[i][j] = \"open\"\n }\n }\n\n game.magicBoardLogic = []\n for (var i=0; i < game.n; i++) {\n game.magicBoardLogic[i]=new Array(game.n)\n }\n\n for (var i=0; i < game.n; i++)\n {\n for (var j=0; j < game.n; j++)\n {\n game.magicBoardLogic[i][j] = \"null\"\n }\n }\n\n //asign functions ot the game object, so they can be called by the client\n this.assignFunctions()\n\n game.cursorSquares = []\n for (var i=0; i < game.n; i++) {\n game.cursorSquares[i]=new Array(game.n)\n }\n\n game.redSquares = []\n for (var i=0; i < game.n; i++) {\n game.redSquares[i]=new Array(game.n)\n for (var j=0; j < game.n; j++)\n {\n game.redSquares[i][j]=new Array(game.n)\n for (var k=0; k < game.n; k++)\n {\n game.redSquares[i][j][k]=new Array(game.n)\n }\n }\n }\n\n for (var i=0; i < game.n; i++)\n {\n for (var j=0; j < game.n; j++)\n {\n game.cursorSquares[i][j] = game.addSpriteWithWidth(game.startingX + i*game.squareSize*3, game.startingY + j*game.squareSize*3, 'greensquare', game.squareSize*3, game.squareSize*3)\n game.cursorSquares[i][j].alpha = 0\n for (var k=0; k < game.n; k++)\n {\n for (var l=0; l < game.n; l++)\n {\n game.redSquares[i][j][k][l] = game.addSprite(game.startingX + i*game.squareSize*3 + k*game.squareSize, game.startingY + j * game.squareSize*3 + l*game.squareSize, 'redsquare')\n game.redSquares[i][j][k][l].alpha = 0\n }\n }\n }\n }\n game.firstTime = false\n\n //create an internal representation of the board as a 2D array\n game.board = game.makeBoardAsArray(game.n)\n //create the board on screen and makes each square clickable\n game.makeBoardOnScreen()\n //add messages that display turn status, connection statuses\n this.addTexts()\n //folloowing logic is for multiplayer games\n if(game.singleplayer || game.vsAi)\n return\n\n game.previousPiece = \"\"\n //if this is the first play against an opponent, create a new player on the server\n game.startMultiplayer()\n\n }", "function boardSetup() {\n\n\tclearBoard();\n\t$('#game_info').show();\n\t// add tie break track\n\t$('#tie_break_track').append(\n\t\t$('<span/>').text('Tie Break:')\n\t);\n\tfor (i = 0; i < numPlayers; i ++) {\n\t\tvar c = tieBreak[i];\n\t\t$('#tie_break_track').append(\n\t\t\t$('<div/>')\n\t\t\t\t.addClass('tie_break_token')\n\t\t\t\t.css('background-color', playerColors[c])\n\t\t\t\t.text(Number(i+1))\n\t\t\t\t.attr('title', players[c].username)\n\t\t);\n\t\t// distribute starting resources depending on tie break order\n\t\tplayers[c].money += (startingMoney + Math.floor(i/2));\n\t\tplayers[c].numRibbons += i%2;\n\t}\n\n\t// add status bar\n\tvar $statusBar = $('<div/>').addClass('status_bar')\n\t\t.append(\n\t\t\t$('<span/>').addClass('status_bar--turn'),\n\t\t\t$('<span/>').addClass('status_bar--phase'),\n\t\t\t$('<span/>').addClass('status_bar--text')\n\t\t);\n\n\t$('#status_bar').append($statusBar);\n\n\t// add opponents' boards on the top\n\tfor (i = 0; i < numPlayers; i ++)\n\t\tif (myID != i) {\n\t\t\tvar $board = $('<div/>')\n\t\t\t\t\t.addClass('player_board')\n\t\t\t\t\t.css('background-color', playerColors[i])\n\t\t\t\t\t.val(i);\n\t\t\tvar $vase = $('<div/>').addClass('player_vase').addClass('player_vase--opponent');\n\n\t\t\tfor (j = 0; j < 3; j ++)\n\t\t\t\t$($vase).append(\n\t\t\t\t\t$('<img/>').attr('src', 'img/empty_vase.png')\n\t\t\t\t\t\t.addClass('icon--small empty_vase')\n\t\t\t\t);\n\n\t\t\tvar $upperBoard = $('<div/>').append(\n\t\t\t\t// name \n\t\t\t\t$('<span/>').text(players[i].username)\n\t\t\t\t\t.addClass('player_name'), \n\t\t\t\t// money\n\t\t\t\t$('<img/>').attr('src','img/money_icon.png')\n\t\t\t\t\t.addClass('icon--small'),\n\t\t\t\t$('<span/>').text(players[i].money)\n\t\t\t\t\t.addClass('player_money'),\n\t\t\t\t// score\n\t\t\t\t$('<img/>').attr('src','img/score_icon.png')\n\t\t\t\t\t.addClass('icon--small'),\n\t\t\t\t$('<span/>').text(players[i].score)\n\t\t\t\t\t.addClass('player_score'),\n\t\t\t\t// time\n\t\t\t\t$('<img/>').attr('src','img/time_icon.png')\n\t\t\t\t\t.addClass('icon--small'),\n\t\t\t\t$('<span/>').text(players[i].time)\n\t\t\t\t\t.addClass('player_time'),\n\t\t\t\t$('<br>'),\n\t\t\t\t$vase\n\t\t\t);\n\n\t\t\tvar $lowerBoard = $('<div/>').append(\n\t\t\t\t// ribbons\n\t\t\t\t$('<img/>').attr('src','img/ribbon_icon.png')\n\t\t\t\t\t.addClass('icon--small'),\n\t\t\t\t$('<span/>').text(players[i].numRibbons)\n\t\t\t\t\t.addClass('player_ribbon'),\n\t\t\t\t// action cubes\n\t\t\t\t$('<img/>').attr('src','img/action_cube_icon.png')\n\t\t\t\t\t.addClass('icon--small'),\n\t\t\t\t$('<span/>').text(players[i].actionCubes)\n\t\t\t\t\t.addClass('player_action_cube'),\n\t\t\t\t// number of played cards\n\t\t\t\t$('<img/>').attr('src','img/played_cards_icon.png')\n\t\t\t\t\t\t.addClass('icon--small'),\n\t\t\t\t$('<span/>').text(0)\n\t\t\t\t\t.addClass('player_number_played_cards'),\n\t\t\t\t\n\t\t\t\t$('<br>')\n\t\t\t);\n\n\t\t\tfor (j = 1; j < 4; j ++) {\n\t\t\t\tvar starColor = players[i].bonus[j-1] + 1;\n\t\t\t\t$lowerBoard.append(\n\t\t\t\t\t$('<img/>').attr('src', 'img/bonus_icon' + j + '.png')\n\t\t\t\t\t\t.addClass('icon--small')\n\t\t\t\t\t\t.css('background-color', shopColors[starColor]),\n\t\t\t\t\t$('<span/>').text(0)\n\t\t\t\t\t\t.addClass('bonus_star')\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t$($board).append(\n\t\t\t\t$upperBoard,\n\t\t\t\t$lowerBoard\n\t\t\t);\n\t\t\t$($lowerBoard).css({\n\t\t\t\t\t'background-color': playerColors[i],\n\t\t\t\t\t'z-index': 0\n\t\t\t\t})\n\t\t\t\t.addClass('lower_opponent_board')\n\t\t\t\t.hide();\n\n\t\t\t$('#opponent_board_area').append($board);\n\t\t\tplayers[i].addBoard($board);\n\t\t}\n\n\t\t$('#opponent_board_area').append(\n\t\t\t$('<button/>').text('More')\n\t\t\t\t.addClass('button button--expand_opponent_board')\n\t\t);\n\t// add info to your board at the bottom of the screen\n\t$('#my_board').css('background-color', playerColors[myID])\n\t\t.val(myID);\n\n\t$('#my_name .player_name').text(myusername);\n\n\t// starting resources\n\t$('#my_money .player_money').text(players[myID].money);\n\t$('#my_score .player_score').text(0);\n\t$('#my_ribbon .player_ribbon').text(players[myID].numRibbons);\t\n\t$('#my_action_cube .player_action_cube').text(0);\n\n\t// time_track\n\t$('#my_time_track').append(\n\t\t$('<img/>').attr('src','img/time_track0.png')\n\t\t\t.addClass('time_track_image')\n\t)\n\n\t// the rest\n\t$('#my_number_played_cards span').text(0);\n\t\n\tfor (i = 1; i < 4; i ++) {\n\t\tvar starColor = players[myID].bonus[i-1] + 1;\n\t\t$('#bonus_icon' + i).css('background-color', shopColors[starColor])\n\t\t\t.append(\n\t\t\t\t$('<img/>').attr('src', 'img/bonus_icon' + i + '.png')\n\t\t\t\t\t.addClass('icon')\n\t\t\t\t\t.attr('title', bonusTypeString[i-1])\n\t\t\t);\n\t\t\n\t\t$('#my_bonus' + i).css('background-color', shopColors[starColor])\n\t\t\t.append(\n\t\t\t\t$('<span/>').text(0)\n\t\t\t\t\t.addClass('bonus_star'),\n\t\t\t\t$('<img/>').attr('src', 'img/star_icon' + starColor + '.png')\n\t\t\t\t\t.addClass('icon--small')\n\t\t\t);\n\n\t\t$('#my_vase').append(\n\t\t\t$('<img/>').attr('src', 'img/empty_vase.png')\n\t\t\t\t.addClass('empty_vase')\n\t\t);\n\t}\n\n\t// add tool tokens and popup area that shows all tools with all levels\n\tshops = [[],[],[],[],[],[]];\n\tfor (i = 0; i < 6; i ++)\n\t\tshops[5].push(\n\t\t\tnew toolToken(i)\n\t\t);\n\t\t\n\t$('#tool_lookup').append(\n\t\t$('<button/>').text('Close')\n\t\t\t.addClass('button--expand_tool')\n\t);\n\n\tfor (i = 0; i < 3; i ++ ) {\n\t\t$('#tool_lookup').append(\n\t\t\t$('<br>'),\n\t\t\t$('<span/>').text('level ' + i).css('color', 'white')\n\t\t);\n\t\t$('#tool_lookup').append($('<br>'));\n\t\tfor (j = 0; j < 6; j ++) {\n\t\t\t$('#tool_lookup').append(\n\t\t\t\t$(\"<img/>\")\n\t\t\t\t\t.attr('src', 'img/tool' + j + 'lv' + i + '.jpg' )\n\t\t\t\t\t.addClass('tool--large')\n\t\t\t\t\t.val(i)\n\t\t\t);\n\t\t}\n\t}\n\n\t // add as many achievements as the number of players\n\t$('#achievement_area').empty();\n\t$('#achievement_area--large').empty();\n\t$('#achievement_area').append(\n\t\t$('<span/>').text('Achievements'),\n\t\t$('<br>'),\n\t\t$('<button/>').text('Expand')\n\t\t\t.addClass('button button--expand_achievement')\n\t\t\t.css({'position':'absolute','top':'0'})\n\t);\n\n\tfor (i = 0; i < achievements.length; i ++) {\n\t\tvar type = achievements[i].type;\n\t\tvar $accard = \n\t\t$('#achievement_area').append(\n\t\t\t$('<img/>').attr('src','img/achievement' + type + '.png')\n\t\t\t\t.addClass('achievement_card')\n\t\t\t\t.data({\n\t\t\t\t\ttype: type,\n\t\t\t\t\tindex: i\n\t\t\t\t}),\n\t\t\t$('<span/>').addClass('achievement_claimer_token')\n\t\t);\n\n\t\t$('#achievement_area--large').append(\n\t\t\t$('<img/>').attr('src','img/achievement' + type + '.png')\n\t\t\t\t.addClass('achievement_card--large')\n\t\t\t\t.data({\n\t\t\t\t\ttype: type,\n\t\t\t\t\tindex: i\n\t\t\t\t})\n\t\t);\n\t}\n\n\t$('#achievement_area--large').append(\n\t\t$('<button/>').text('Close')\n\t\t\t.addClass('button button--expand_achievement')\n\t);\n\n\t// initialize board component\n\tplayers[myID].addBoard(\n\t\t$('#my_board')\n\t);\n}", "function createGame() {\n const rowClassNames = ['topRow', 'middleRow', 'bottomRow'];\n const cellClassNames = ['LeftCell', 'CenterCell', 'RightCell'];\n const rowLength = rowClassNames.length;\n const columnLength = cellClassNames.length;\n const gameBoardContainer = document.querySelector('.gameBoardContainer');\n toggleHideElement('.inputs');\n toggleHideElement('.avatarOptions');\n toggleHideElement('.startBtn');\n for (let gridX = 0; gridX < rowLength; gridX++) {\n let row = document.createElement('div');\n row.classList.add(rowClassNames[gridX]);\n gameBoardContainer.appendChild(row);\n for (let gridY = 0; gridY < columnLength; gridY++) {\n let cell = document.createElement('div');\n let cellName = rowClassNames[gridX] + cellClassNames[gridY];\n cell.classList.add(cellName);\n cell.onclick = () => placePlayerMarker(cell);\n row.appendChild(cell);\n }\n }\n updatePlayer(playerOne);\n updatePlayer(playerTwo);\n updateAnnouncementBoard();\n}", "loadGame() {\n alert(\"Loading saved game!\");\n tiles = []; // empty tile array\n numPiecesChosen = []; // reset\n numPiecesMatched = 0;\n $(\".wrapper\").empty(); // clear everything\n this.currentBoard = new Board();\n this.currentBoard.loadBoard(function() {\n current.currentBoard.renderTiles(function() {\n current.addFlip(current);\n });\n });\n }", "function buildBoard(){\n\n\t\tvar boardSize = (GAME.board.width * defaultTile.tileSize) + 200; //padding\n\n\t\t//$gamearea.style.maxWidth = (boardSize + 20) +'px'; //extra space for scroll bar\n\t\t$map.style.height = boardSize +'px';\n\t\t$map.style.width = boardSize +'px';\n\t\t\n\t\t//Build our board! //0 or 1 based?\n\t\tfor(var w = 0; w < GAME.board.width; w++){\n\t\t\tGAME.board.tiles[w] = [];\n\t\t\tGAME.NPCs[w] = [];\n\t\t\tfor(var h = 0; h < GAME.board.height; h++){\t\n\n\t\t\t\t//Put our tile into our state board\n\t\t\t\tGAME.board.tiles[w][h] = createTile(w,h);\n\t\t\t\t\n\t\t\t\t//Creating a bunch of random GAME.NPCs\n\t\t\t\tif( (w + h) % 10 == 0){\n\t\t\t\t\tGAME.NPCs[w][h] = createNPC(w,h);\n\t\t\t\t}\n\n\t\t\t\t//tileHolder.appendChild(board.tiles[w][h].element);\n\t\t\t}\n\t\t}\n\n\t\tdisplayBoard(GAME.board);\n\t\tdisplayNPCs(GAME.NPCs);\n\n\t\t//we need to build our graph array AFTER npcs have been added so we know if the tiles are passable\n\t\tbuildGraphArray();\n\t}", "function setupGame() {\n const boardElement = document.getElementById('board')\n\n for (let y = 0; y < boardHeight; ++y) {\n const row = []\n for (let x = 0; x < boardWidth; ++x) {\n const cell = {}\n\n // Create a <div></div> and store it in the cell object\n cell.element = document.createElement('div')\n\n // Add it to the board\n boardElement.appendChild(cell.element)\n\n // Add to list of all\n row.push(cell)\n }\n\n // Add this row to the board\n board.push(row)\n }\n\n startGame()\n\n // Start the game loop (it will call itself with timeout)\n gameLoop()\n }", "function loadGameData()\n\t\t\t{\n\t\t\t\tif(gameName == \"fatcat7\")\n\t\t\t\t{\n\t\t\t\t\tgame = new FatCat7Game();\n\t\t\t\t\tisFreeSpinGame = true;\n\t\t\t\t}\n\t\t\t\telse if(gameName == \"bounty\")\n\t\t\t\t{\n\t\t\t\t\tgame = new BountyGame();\n\t\t\t\t\tisFreeSpinGame = true;\n\t\t\t\t}\n\t\t\t\telse if(gameName == \"gummibar\")\n\t\t\t\t{\n\t\t\t\t\tgame = new GummiBarGame();\n\t\t\t\t\tisFreeSpinGame = false;\n\t\t\t\t}\n\t\t\t\telse if(gameName == \"aprilmadness\")\n\t\t\t\t{\n\t\t\t\t\tgame = new AprilMadnessGame();\n\t\t\t\t\tisFreeSpinGame = true;\n\t\t\t\t}\n\t\t\t\telse if(gameName == \"moneybooth\")\n\t\t\t\t{\n\t\t\t\t\tgame = new MoneyBoothGame();\n\t\t\t\t\tisFreeSpinGame = false;\n\t\t\t\t}\n\t\t\t\telse if(gameName == \"astrologyanswers\")\n\t\t\t\t{\n\t\t\t\t\tgame = new AstrologyAnswersGame();\n\t\t\t\t\tisFreeSpinGame = false;\n\t\t\t\t\tisBothFreeSpinAndOtherBonus = true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tgame.importGame(xmlData);\n\t\t\t}", "function buildGame() {\n\t\n\t// build a spritesheet up from the image we have loaded\n spriteSheet = new SpriteSheet({\n\t images: [spriteImage], \n\t frames: {width: CELL_SIZE, height: CELL_SIZE, count: 12, regX: 1, regY: 1},\n\t animations: {\n\t\t\tblank: [9],\n\t\t\tempty_cell: [0],\n\t\t\tyellow_cell: [1],\n\t\t\tred_cell: [2],\n\t\t\tplace_yellow: [9],//[4],\n\t\t\tplace_red: [9],//[5],\n\t\t\tfill_yellow: [4],//[7],\n\t\t\tfill_red: [5],//[8],\n\t\t\twin_yellow: [10],\n\t\t\twin_red: [11],\n\t\t}\n });\n \n // build a stage object to hold our game board\n stage = new Stage(game);\n stage.mouseEventsEnabled = true; // allow mouse events\n stage.enableMouseOver(); // allow mouseover events\n \n // set up a game ticker\n Ticker.addListener(stage);\n Ticker.useRAF = true;\n Ticker.setFPS(60);\n \n // initialise the game board\n map = [];\n for (var col = 0; col < max_col; col++) {\n \tvar line = [];\n \tfor (var row = 0; row < max_row + header_rows; row++) {\n \t\t/// create a new bitmap animation\n \t\tvar bma = new BitmapAnimation(spriteSheet);\n \t\t\n \t\t// set up the correct bitmap\n \t\tif (col > max_col) {\n \t\t\tbma.gotoAndPlay(\"blank\");\n \t\t} else {\n \t\t\tif (row == 0)\n\t \t\t{\n\t \t\t\tbma.gotoAndPlay(\"blank\");\n\t \t\t} else if (row == 1){\n\t \t\t\tbma.gotoAndPlay((current_team == YELLOW) ? \"place_yellow\" : \"place_red\");\n \t\t\t\tbma.onMouseOver = changePlaceMouseOver;\n \t\t\t\tbma.onMouseOut = changePlaceMouseOut;\n \t\t\t\tbma.onPress = placeDiscEvent;\n\t \t\t} else {\n\t \t\t\tbma.gotoAndPlay(\"empty_cell\");\n\t \t\t}\n \t\t}\n \t\t\n \t\t// configure the bitmap animation position\n \t\tbma.name = row + \",\" + col;\n \t\tbma.x = col * CELL_SIZE;\n \t\tbma.y = row * CELL_SIZE;\n \t\tstage.addChild(bma);\n\t \tline.push(bma);\n \t}\n \tmap.push(line);\n }\n}", "function newGame() {\n /* This uses a callback function as all of the other processes are dependant on the configuration information. */\n GAME.loadConfig(function() {\n GAME.loadSVGFiles(); // This will also begin to draw the starting room when complete. //\n GAME.createMaze();\n GAME.prepareCanvas(); // Draws a blank canvas in preparation for rooms. //\n PLAYER.setRandomRoom(); // Assign the player to a random room. //\n });\n}", "function setUpBoard () {\n makeCrystalScores();\n makeCrystalButtons();\n }", "function start(){\n\t \t// Local variables\n\t \tlet fs = require('fs');\n\t \tlet file = \"test.json\";\n\t \tlet myBoard;\n\t \tlet disc;\n\t \tlet height;\n\t \tlet width;\n\t \tlet turn;\n\t \tlet response;\n\t \tlet p1Disc;\n\t\tlet p2Disc;\n\n\t \tconsole.log('<<<<< Welcom to the game of Othello >>>>>\\n');\n\t \ttry{\n\t \t\tif(fs.existsSync(file))\n\t \t\t{\n\t \t\t\t//if file not empty\n\t \t\t\tif(fs.readFileSync(file) != null)\n\t \t\t\t{\n\t \t\t\t\tlet newBoard = loadFile(file);\n\t \t\t\t\t\n\t \t\t\t\tmyBoard = new board(newBoard.height, newBoard.width);\n\t\t\t\t\tmyBoard.board = newBoard.board;\n\n\t \t\t\t\t// if myBoard is not full\n\t \t\t\t\tif(!(myBoard.isBoardFull()))\n\t \t\t\t\t{\n\t \t\t\t\t\t// ask user if he would like to continue previous game\n\t \t\t\t\t\tresponse = prompt('Would you like to continue the game you saved? Enter Y for Yes or N for No > ').toUpperCase();\n\t \t\t\t\t\t// if yes \n\t \t\t\t\t\tif(response == 'Y')\n\t \t\t\t\t\t{\n\t \t\t\t\t\t\tturn = 1;\n\t \t\t\t\t\t\tdisc = 'B';\n\t \t\t\t\t\t\t// load content of file into board\n\t \t\t\t\t\t\tif(turn == 1){\n\t\t\t\t\t\t\t\tp1Disc = disc;\n\t\t\t\t\t\t\t\tp2Disc = disc == 'W' ? 'B' : 'W';\n\t\t\t\t\t\t\t}else {\n\t\t\t\t\t\t\t\tp2Disc = disc;\n\t\t\t\t\t\t\t\tp1Disc = disc == 'W' ? 'B' : 'W';\n\t\t\t\t\t\t\t}\n\t \t\t\t\t\t\t\n\t \t\t\t\t\t}else if(response == 'N')// if no \n\t \t\t\t\t\t{\n\t \t\t\t\t\t\t//create new game\n\t \t\t\t\t\t\theight = prompt('What height for your board? ');\n\t\t\t\t\t\t\twhile(height < 4)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconsole.log('\\nHeight is too small\\nPlease enter a number greater than 4 ');\n\t\t\t\t\t\t\t\theight = prompt('What height for your board? ');\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\twidth = prompt('\\nWhat width for your board? ');\n\t\t\t\t\t\t\twhile(width < 4)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconsole.log('\\nWidth is too small\\n Please enter a number greater than 4 ');\n\t\t\t\t\t\t\t\twidth = prompt('What width for your board? ');\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// SYNCHRONOUSLY read from keyboard\n\t\t\t\t\t\t\tconsole.log('Creating a board with size ' + height + ' x ' + width + '.');\n\t\t\t\t\t\t\t// Create new board object\n\t\t\t\t\t\t\tmyBoard = new board(height, width);\n\t\t\t\t\t\t\t//saveFile(\"test.json\", myBoard);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tturn = prompt('Enter player to start the game: 1 or 2 ');\n\t\t\t\t\t\t\twhile( turn < 1 || turn >= 3)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconsole.log('Invalid number entered. Please try again');\n\t\t\t\t\t\t\t\tturn = prompt('Enter player to start the game: 1 or 2 ');\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tdisc = prompt('Enter disc color: W for White B for Black ').toUpperCase();\n\t\t\t\t\t\t\twhile(disc != 'W' && disc != 'B')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconsole.log('Invalid Color. Please try again');\n\t\t\t\t\t\t\t\tdisc = prompt('Enter disc color: W for White B for Black ').toUpperCase();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif(turn == 1){\n\t\t\t\t\t\t\t\tp1Disc = disc;\n\t\t\t\t\t\t\t\tp2Disc = disc == 'W' ? 'B' : 'W';\n\t\t\t\t\t\t\t}else {\n\t\t\t\t\t\t\t\tp2Disc = disc;\n\t\t\t\t\t\t\t\tp1Disc = disc == 'W' ? 'B' : 'W';\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}else{\n\t \t\t\theight = prompt('What height for your board? ');\n\t\t\t\twhile(height < 4)\n\t\t\t\t{\n\t\t\t\t\tconsole.log('\\nHeight is too small\\nPlease enter a number greater than 4 ');\n\t\t\t\t\theight = prompt('What height for your board? ');\t\n\t\t\t\t}\n\t\t\t\twidth = prompt('\\nWhat width for your board? ');\n\t\t\t\twhile(width < 4)\n\t\t\t\t{\n\t\t\t\t\tconsole.log('\\nWidth is too small\\n Please enter a number greater than 4 ');\n\t\t\t\t\twidth = prompt('What width for your board? ');\t\n\t\t\t\t}\n\n\t\t\t\t// SYNCHRONOUSLY read from keyboard\n\t\t\t\tconsole.log('Creating a board with size ' + height + ' x ' + width + '.');\n\t\t\t\t// Create new board object\n\t\t\t\tmyBoard = new board(height, width);\n\t\t\t\t//saveFile(file, myBoard);\n\n\t\t\t\tturn = prompt('Enter player to start the game: 1 or 2 ');\n\t\t\t\twhile( turn < 1 || turn >= 3)\n\t\t\t\t{\n\t\t\t\t\tconsole.log('Invalid number entered. Please try again');\n\t\t\t\t\tturn = prompt('Enter player to start the game: 1 or 2 ');\n\t\t\t\t}\n\n\t\t\t\tdisc = prompt('Enter disc color: W for White B for Black ').toUpperCase();\n\t\t\t\twhile(disc != 'W' && disc != 'B')\n\t\t\t\t{\n\t\t\t\t\tconsole.log('Invalid Color. Please try again');\n\t\t\t\t\tdisc = prompt('Enter disc color: W for White B for Black ').toUpperCase();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(turn == 1){\n\t\t\t\t\tp1Disc = disc;\n\t\t\t\t\tp2Disc = disc == 'W' ? 'B' : 'W';\n\t\t\t\t}else {\n\t\t\t\t\tp2Disc = disc;\n\t\t\t\t\tp1Disc = disc == 'W' ? 'B' : 'W';\n\t\t\t\t}\n\t \t\t}\n\t \t}catch(err){\n\t \t\tconsole.log(\"AN ERROR OCCURRED!\");\n\t \t\tconsole.error(err);\n\t \t}\n\t \t\n\t\tconsole.log('Player 1: ' + p1Disc + ' Player 2: ' + p2Disc +'\\n');\n\t\tconsole.log('Player ' + turn + ' starts the game...\\n');\n\n\t\t// Loop, asking user input, calling appropriate functions.\n\t\tlet row;\n\t\tlet col;\n\t\t//console.log(typeof myBoard);\n\t\twhile(!myBoard.isGameOver())\n\t\t{\n\t\t\tmyBoard.printBoard();\n\t\t\tif(!(myBoard.isValidMoveAvailable((turn == 1) ? p1Disc : p2Disc)))\n\t\t\t{\n\t\t\t\tconsole.log('No valid moves available for player ' + turn + '. You lose your turn.\\n');\n\t\t\t}else{\n\t\t\t\tdo{\n\t\t\t\t\tconsole.log('Turn> Player ' + turn + '(' + ((turn == 1) ? p1Disc : p2Disc) + ')');\n\t\t\t\t\trow = prompt('Enter row to place your disc:');\n\t\t\t\t\tcol = prompt('Enter col to place your disc:');\n\t\t\t\t\t\n\t\t\t\t\tif(row < 1 || row > width || col < 1 || col > height)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log('Sorry, invalid input. Try again. \\n');\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\trow--; // adjust it for zero-indexed array of board\n\t\t\t\t\tcol--; // adjust it for zero-indexed array of boardelse if(!myBoard.isValid(row, col, ((turn == 1) ? p1Disc : p2Disc)))\n\t\t\t\t\tif(!myBoard.isValid(row, col, (turn == 1 ? p1Disc : p2Disc))){\n\t\t\t\t\t\tconsole.log('Sorry, that is not a valid move. Try again');\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}while(true);\n\t\t\t\tmyBoard.placeDiskAt(row,col,((turn == 1) ? p1Disc : p2Disc));\n\t\t\t\tsaveFile(file, myBoard);\n\t\t\t}\n\t\t\tturn = (turn == 1) ? 2 : 1;\n\t\t}\n\n\t\twinner = myBoard.checkWinner();\n\t\tif(winner == 'B' || winner == 'W')\n\t\t{\n\t\t\tconsole.log('Game is over. The winner is Player ' + (winner == p1Disc ? 1 : 2) + winner + '.\\n');\n\t\t}else{\n\t\t\tconsole.log('Game is over. No winner.');\n\t\t}\n\t}", "function setupGame() {\n generateHTMLBoardSquares();\n\n const squareElements = document.getElementsByClassName(\"board-square\");\n\n for (var i = 0; i < squareElements.length; i++) {\n const element = squareElements[i];\n const square = new BoardSquares(element);\n boardSquares.push(square);\n }\n}", "function load()\n {\n populateMap(gameInfo.jediList);\n init();\n gameInfo.gameState = \"pickChar\";\n }", "function initGame(){\n resetGameStats()\n setLevel()\n gBoard = buildBoard()\n renderBoard(gBoard)\n gGame.isOn = true\n\n}", "createBoard() {\n\t\tfor (let i = 0; i < 6; i++) {\n\t\t\tfor (let j = 0; j < 6; j++) {\n\t\t\t\tlet tile = new MyTile(this.scene, this);\n\t\t\t\tlet pieceSize = 0.395 + 0.005;\n\t\t\t\ttile.addTransformation(['translation', -3 * pieceSize + pieceSize * j, -3 * pieceSize + pieceSize * i, 0]);\n\t\t\t\tthis.tiles.push(tile);\n\t\t\t}\n\t\t}\n\t\tfor (let i = 0; i < 8; i++) {\n\t\t\tthis.whitePieces.push(new MyPieceWhite(this.scene, 'whitePiece'));\n\t\t\tthis.blackPieces.push(new MyPieceBlack(this.scene, 'blackPiece'));\n\t\t}\n\t}", "function loadGame(){\n\t// images\n\tbgImage.src = \"images/backgframe_480.jpg\";\n\tdude.src = \"images/person.png\";\n\tscrollImage.src = \"images/scroll.png\";\n\t\n\t// required buttons\n \tpauseButtonImage.src = \"images/gmenub1.png\";\n\t\n \tpauseButtonImage2.src = \"images/gpauseButton.png\";\n\t\n\t// test buttons (debugging)\n \tgenerateButtonImage.src = \"images/button.png\";\n\tvictoryButtonImage.src = \"images/button.png\";\n\taddscoreButtonImage.src = \"images/button.png\";\n\taddGameOverButtonImage.src = \"images/button.png\";\n\n\t/*// turn off main menu music\n\tmusicOn = false;\n\tmusic.pause();*/\n\t\n\tinitGameSetting(); //rules.js\n}" ]
[ "0.7420864", "0.72548664", "0.7228805", "0.7216703", "0.715611", "0.70957667", "0.7085388", "0.70358056", "0.70005196", "0.692128", "0.691042", "0.6856177", "0.68503314", "0.6834303", "0.6823712", "0.68206155", "0.67755353", "0.6763411", "0.6713929", "0.67020357", "0.6700509", "0.66813946", "0.6655392", "0.6650496", "0.6648591", "0.663211", "0.6585252", "0.65766674", "0.65750045", "0.6542901" ]
0.7423521
0
Purpose: Starts searching through the grid. Starts by trying to find the largest ship by skipping to every nth blocks.
function startGame(){ var j = 5; // value by which to skip. while (j>0){ var max = 0; for(var m =0; m<ships.length; m++){ if (ships[m]>max){ max = ships[m];} } if (j>max){ j = max; } writeToConsole(ships); writeToConsole("Trying spacing by " + j); for (var i=0; i<=j; i++){ for(var x=0; x< Math.floor(game.board_size.width/j); x++){ for(var y=0; y< Math.floor(game.board_size.height/j); y++){ if (isHit(j*x + i,j*y + i)){ exploreNeighbors(j*x + i,j*y + i); } } } } j--; } raiseError('Unable to confirm Game Over'); endGame() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function exploreNeighbors(x,y){\n\tfunction labelEmpty(x,y){\n\t\tif (x>=0 && x<game.board_size.width && y>=0 && y<game.board_size.height){\n\t\t\tdocument.getElementById(y+'_'+x).setAttribute('class','avoid');\n\t\t\tboard[x][y] = null;\t\t// Indicate that cell should never be examined\n\t\t}\n\t}\n\tfunction pursueShip(x,y, xp, yp){\n\t\t\n\t\tships.sort();\n\t\tvar maxSize = ships[ships.length -1];\n\t\tvar length = 0;\n\t\t\n\t\twhile (length<=maxSize && isHit(x + xp*length, y + yp*length)){\n\t\t\t// Label cells on either side as empty\n\t\t\tlabelEmpty(x + xp*length + yp,y + yp*length + xp);\n\t\t\tlabelEmpty(x + xp*length - yp,y + yp*length - xp);\n\t\t\t\n\t\t\tlength++;\n\t\t}\n\t\t\n\t\tlength = 1;\n\t\txp = -xp;\n\t\typ = -yp;\n\t\twhile (length<=maxSize && isHit(x + xp*length, y + yp*length)){\n\t\t\t// Label cells on either side as empty\n\t\t\tlabelEmpty(x + xp*length + yp,y + yp*length + xp);\n\t\t\tlabelEmpty(x + xp*length - yp,y + yp*length - xp);\n\t\t\t\n\t\t\tlength++;\n\t\t}\n\t}\n\t\n\t// Pick a direction\n\tif (isHit(x+1,y)){\n\t\tlabelEmpty(x,y+1);\n\t\tlabelEmpty(x,y-1);\n\t\tpursueShip(x,y,1,0); \n\t}\n\telse if (isHit(x-1,y)){\n\t\tlabelEmpty(x,y+1);\n\t\tlabelEmpty(x,y-1);\n\t\tpursueShip(x,y,-1,0);\n\t}\n\telse if (isHit(x,y+1)){\n\t\tlabelEmpty(x+1,y);\n\t\tlabelEmpty(x-1,y);\n\t\tpursueShip(x,y,0,1);\n\t}\n\telse if (isHit(x,y-1)){\n\t\tlabelEmpty(x+1,y);\n\t\tlabelEmpty(x-1,y);\n\t\tpursueShip(x,y,0,-1);\n\t}\n}", "function identifyNeighbours(x_max,y_max){\n\t \t\tvar traversalIndex = 0;\n\n\t \t\t//inner square\n\t \t\tfor (var i = 0; i < x_max*y_max; i++) {\n\t \t\t\ttraversalIndex = (i % y_max);\n\n\t \t\tif((traversalIndex != 0) && (traversalIndex != (y_max-1)) \n\t \t\t&& (i <= ((y_max)*(x_max-1)-1)) && (i >= y_max+1) ){\n\t \t\t\tspaces[i].adjacentNeighbours = spaces[(i-1)].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[i+1].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[i+y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[i-y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[(i-1)+y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[(i-1)-y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[(i+1)+y_max].holdsMine\n\t \t\t\t\t\t\t\t\t\t + spaces[(i+1)-y_max].holdsMine;\n\t \t\t\tspaces[i].neighbourIndexList.push( (i+1),(i-1),(i+y_max),(i-y_max),\n\t \t\t\t\t\t\t\t\t\t\t\t\t(i-1+y_max),(i-1-y_max),\n\t \t\t\t\t\t\t\t\t\t\t\t\t(i+1+y_max),(i+1-y_max));\n\t\t\t\t}\n\t\t\t// console.log(isNaN(spaces[i].holdsMine))\n\t\t\t}\n\n\t\t\t//four courners\n\t\t\tspaces[0].adjacentNeighbours = spaces[y_max].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[y_max+1].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[1].holdsMine;\n\n\t\t\tspaces[0].neighbourIndexList.push(y_max,(y_max+1),1);\n\n\t\t\tspaces[y_max-1].adjacentNeighbours = spaces[(y_max-1) - 1].holdsMine\n\t\t\t\t\t\t\t\t\t\t\t + spaces[(y_max-1) + y_max].holdsMine\n\t\t\t\t\t\t\t\t\t\t\t + spaces[(y_max-1) + y_max-1].holdsMine;\n\n\t\t\tspaces[(y_max-1)].neighbourIndexList.push((y_max-1-1), (y_max-1+y_max), (y_max-1+y_max-1));\n\n\n\t\t\tspaces[y_max*x_max-1].adjacentNeighbours = spaces[(y_max*x_max-1)-1].holdsMine\n\t\t\t\t\t\t\t\t\t\t\t\t + spaces[(y_max*x_max-1)-y_max].holdsMine\n\t\t\t\t\t\t\t\t\t\t\t\t + spaces[(y_max*x_max-1)-(y_max-1)].holdsMine;\n\n\t\t\tspaces[y_max*x_max-1].neighbourIndexList.push((y_max*x_max-1)-1, (y_max*x_max-1)-y_max, (y_max*x_max-1)-(y_max-1));\n\n\n\t\t\tspaces[(x_max *(y_max-1))].adjacentNeighbours = spaces[(x_max *(y_max-1))+ 1].holdsMine\n + spaces[(x_max *(y_max-1))-y_max].holdsMine\n + spaces[(x_max *(y_max-1))-(y_max)+1].holdsMine; \n\n spaces[(x_max *(y_max-1))].neighbourIndexList.push((x_max *(y_max-1))+ 1, (x_max *(y_max-1))-y_max,(x_max *(y_max-1))-(y_max)+1);\n\n\n for(var k = 1; k < y_max-1; k++){\n\n\t\t \t\t//left column\n\t\t \t\tspaces[k].adjacentNeighbours = spaces[k-1].holdsMine\n\t\t \t\t\t\t\t\t\t\t + spaces[k+1].holdsMine\n\t\t \t\t\t\t\t\t\t\t + spaces[k+y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t + spaces[k+y_max - 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t + spaces[k+y_max + 1].holdsMine;\n\n\t\t \t\tspaces[k].neighbourIndexList.push(k-1,k+1,k+y_max,k+y_max-1,k-y_max+1);\n\n\n\t\t \t\t//right column\n\t\t \t\tspaces[x_max *(y_max-1) + k].adjacentNeighbours = spaces[ (x_max *(y_max-1) + k) + 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t+ spaces[x_max *(y_max-1) + k - 1].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[x_max *(y_max-1) + k - y_max].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[x_max *(y_max-1) + k - y_max + 1].holdsMine\n\t\t\t\t\t\t\t\t\t + spaces[x_max *(y_max-1) + k - y_max - 1].holdsMine;\n\n\t\t\t\tspaces[x_max *(y_max-1) + k].neighbourIndexList.push((x_max *(y_max-1) + k) + 1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t x_max *(y_max-1) + k - 1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t x_max *(y_max-1) + k - y_max,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t x_max *(y_max-1) + k - y_max + 1,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t x_max *(y_max-1) + k - y_max - 1);\n\t\t \t\t\n\t\t \t\t//top row\n\t\t \t\tspaces[k*y_max].adjacentNeighbours = spaces[k*y_max + 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t + spaces[(k+1)*y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t + spaces[(k-1)*y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t + spaces[(k+1)*y_max + 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t + spaces[(k-1)*y_max + 1].holdsMine;\n\n\t\t \t\tspaces[k*y_max].neighbourIndexList.push(k*y_max + 1,\n\t\t \t\t\t\t\t\t\t\t\t\t\t\t(k+1)*y_max,\n\t\t \t\t\t\t\t\t\t\t\t\t\t\t(k-1)*y_max,\n\t\t \t\t\t\t\t\t\t\t\t\t\t\t(k+1)*y_max + 1,\n\t\t \t\t\t\t\t\t\t\t\t\t\t\t(k-1)*y_max + 1);\n\n\t\t \t\t//bottom row\n\t\t \t\tspaces[(k+1)*(y_max)-1].adjacentNeighbours = spaces[(k+1)*(y_max)-1 - 1].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t\t\t+ spaces[(k+1)*(y_max)-1 - y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t\t + spaces[(k+1)*(y_max)-1 + y_max].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t\t\t+ spaces[(k+1)*(y_max)-1 - y_max-1].holdsMine\n\t\t \t\t\t\t\t\t\t\t\t\t + spaces[(k+1)*(y_max)-1 +y_max-1].holdsMine;\n\n\n\t\t\t\tspaces[(k+1)*(y_max)-1].neighbourIndexList.push((k+1)*(y_max)-1 - 1,\n\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t (k+1)*(y_max)-1 - y_max,\n\t\t\t\t\t\t\t\t\t\t\t\t (k+1)*(y_max)-1 + y_max,\n\t\t\t\t\t\t\t\t\t\t\t\t (k+1)*(y_max)-1 - y_max-1,\n\t\t\t\t\t\t\t\t\t\t\t\t (k+1)*(y_max)-1 + y_max-1);\n\t \t\t}\n\t \t}", "function nextGeneration(){\n\n\t// Deletes unused chunks\n\tdeleteEmptyChunks();\n\n\t// Generates new chunks where needed\n\tgenerateNewChunks();\n\n\t// Qualify cells (Keep or Kill)\n\tfor (var i = chunks.length - 1; i >= 0; i--) {\n\t\tif (chunks[i].active == 1) {\n\n\t\t\tvar chunk = chunks[i];\n\t\t\tvar cells = chunks[i].cells;\n\n\t\t\t/*\n\t\t\t* Maybe change this so that we look on the edges first and then inside the chunk\n\t\t\t* \n\t\t\t*\n\t\t\t*\n\t\t\t*/\n\n\t\t\t// for all the cells in the chunk\n\t\t\tfor (var y = cells.length - 1; y >= 0; y--) {\n\t\t\t\tfor (var x = cells[y].length - 1; x >= 0; x--) {\n\n\t\t\t\t\tvar cell = cells[y][x];\n\t\t\t\t\tvar neighbors = 0;\n\t\t\t\t\tvar bounds = game.chunkSize-1;\n\n\t\t\t\t\t// Top and Top Right neighbors\n\t\t\t\t\tif (y != 0) {\n\t\t\t\t\t\t//top block\n\t\t\t\t\t\tif (chunk.cells[y-1][x].a == 1) {\n\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// right block\n\t\t\t\t\t\tif (x != bounds) {\n\t\t\t\t\t\t\tif (chunk.cells[y-1][x+1].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(x == bounds) {\t\n\t\t\t\t\t\t\tvar rightChunk = findChunk(chunks, {x: chunk.x+1, y: chunk.y});\n\n\t\t\t\t\t\t\tif (rightChunk != undefined && rightChunk.cells[y-1][0].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\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\telse if (y == 0) {\n\t\t\t\t\t\tvar topChunk = findChunk(chunks, {x: chunk.x, y: chunk.y-1});\n\n\t\t\t\t\t\t//top block\n\t\t\t\t\t\tif (topChunk != undefined && topChunk.cells[bounds][x].a == 1) {\n\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t//top right block\n\t\t\t\t\t\tif (x != bounds) {\n\t\t\t\t\t\t\tif (topChunk != undefined && topChunk.cells[bounds][x+1].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(topChunk != undefined && x == bounds) {\t\n\t\t\t\t\t\t\tvar topRightChunk = findChunk(chunks, {x: topChunk.x+1, y: topChunk.y});\n\n\t\t\t\t\t\t\tif (topRightChunk != undefined && topRightChunk.cells[bounds][0].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\n\t\t\t\t\t// Bottom and Bottom Left neighbors\n\t\t\t\t\tif (y != bounds && neighbors <4) {\n\t\t\t\t\t\t//bottom block\n\t\t\t\t\t\tif (chunk.cells[y+1][x].a == 1) {\n\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// bottom Left block\n\t\t\t\t\t\tif (x != 0) {\n\t\t\t\t\t\t\tif (chunk.cells[y+1][x-1].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(x == 0 && neighbors <4) {\t\n\t\t\t\t\t\t\tvar leftChunk = findChunk(chunks, {x: chunk.x-1, y: chunk.y});\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (leftChunk != undefined && leftChunk.cells[y+1][bounds].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\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\telse if (y == bounds) {\n\t\t\t\t\t\tvar bottomChunk = findChunk(chunks, {x: chunk.x, y: chunk.y+1});\n\n\t\t\t\t\t\t//bottom block\n\t\t\t\t\t\tif (bottomChunk != undefined && bottomChunk.cells[0][x].a == 1) {\n\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t//bottom left block\n\t\t\t\t\t\tif (x != 0) {\n\t\t\t\t\t\t\tif (bottomChunk != undefined && bottomChunk.cells[0][x-1].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(bottomChunk != undefined && x == 0 && neighbors <4) {\t\n\t\t\t\t\t\t\tvar bottomLeftChunk = findChunk(chunks, {x: bottomChunk.x-1, y: bottomChunk.y});\n\n\t\t\t\t\t\t\tif (bottomLeftChunk != undefined && bottomLeftChunk.cells[0][bounds].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\n\t\t\t\t\t// Left and Left Top neighbors\n\t\t\t\t\tif (x != 0 && neighbors <4) {\n\t\t\t\t\t\t// Left block\n\t\t\t\t\t\tif (chunk.cells[y][x-1].a == 1) {\n\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// Left top block\n\t\t\t\t\t\tif (y != 0) {\n\t\t\t\t\t\t\tif (chunk.cells[y-1][x-1].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(y == 0 && neighbors <4) {\t\n\t\t\t\t\t\t\tvar leftTopChunk = findChunk(chunks, {x: chunk.x, y: chunk.y-1});\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (leftTopChunk != undefined && leftTopChunk.cells[bounds][x-1].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\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\telse if (x == 0 && neighbors <4) {\n\t\t\t\t\t\tvar leftChunk = findChunk(chunks, {x: chunk.x-1, y: chunk.y});\n\n\t\t\t\t\t\t//left block\n\t\t\t\t\t\tif (leftChunk != undefined && leftChunk.cells[y][bounds].a == 1) {\n\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t//left top block\n\t\t\t\t\t\tif (y != 0) {\n\t\t\t\t\t\t\tif (leftChunk != undefined && leftChunk.cells[y-1][bounds].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(y == 0 && neighbors <4) {\t\n\t\t\t\t\t\t\tvar leftTopChunk = findChunk(chunks, {x: chunk.x-1, y: chunk.y-1});\n\n\t\t\t\t\t\t\tif (leftTopChunk != undefined && leftTopChunk.cells[bounds][bounds].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\n\t\t\t\t\t// Right and Right Bottom neighbors\n\t\t\t\t\tif (x != bounds && neighbors <4) {\n\t\t\t\t\t\t// Right block\n\t\t\t\t\t\tif (chunk.cells[y][x+1].a == 1) {\n\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// Right Bottom block\n\t\t\t\t\t\tif (y != bounds) {\n\t\t\t\t\t\t\tif (chunk.cells[y+1][x+1].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(y == bounds && neighbors <4) {\t\n\t\t\t\t\t\t\tvar rightBottomChunk = findChunk(chunks, {x: chunk.x, y: chunk.y+1});\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (rightBottomChunk != undefined && rightBottomChunk.cells[0][x+1].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\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\telse if (x == bounds && neighbors <4) {\n\t\t\t\t\t\tvar rightChunk = findChunk(chunks, {x: chunk.x+1, y: chunk.y});\n\n\t\t\t\t\t\t//right block\n\t\t\t\t\t\tif (rightChunk != undefined && rightChunk.cells[y][0].a == 1) {\n\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t//right bottom block\n\t\t\t\t\t\tif (y != bounds) {\n\t\t\t\t\t\t\tif (rightChunk != undefined && rightChunk.cells[y+1][0].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(y == bounds && neighbors <4) {\t\n\t\t\t\t\t\t\tvar rightBottomChunk = findChunk(chunks, {x: chunk.x+1, y: chunk.y+1});\n\n\t\t\t\t\t\t\tif (rightBottomChunk != undefined && rightBottomChunk.cells[0][0].a == 1) {\n\t\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\n\t\t\t\t\t// Decide if I kill or keep the cell\n\t\t\t\t\tif (neighbors <= 1 || neighbors >= 4){\n\t\t\t\t\t\tcell.k = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse if (cell.a == 1 && neighbors <= 3){\n\t\t\t\t\t\tcell.k = 1;\n\t\t\t\t\t}\n\t\t\t\t\telse if(cell.a == 0 && neighbors == 3){\n\t\t\t\t\t\tcell.k = 1;\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t};\n\n\t// Kill all cells that didnt qualify\n\tkill();\n}", "findNeighbors(grid) {\r\n // console.log(`current cell position X:${this.positionX}, Y:${this.positionY}`);\r\n\r\n // items.neighbors = \r\n\r\n //left item position\r\n if (this.positionX - 1 > -1) {\r\n // console.log(`Left neighbor`);\r\n this.neighbors.push(grid.items[this.positionY][this.positionX - 1]);\r\n }\r\n //right item position\r\n if (this.positionX + 1 <= grid.width - 1) {\r\n // console.log(`Right neighbor`);\r\n this.neighbors.push(grid.items[this.positionY][this.positionX + 1]);\r\n }\r\n\r\n //top left item position\r\n if (this.positionX - 1 > -1 && this.positionY - 1 > -1) {\r\n // console.log('Top Left')\r\n this.neighbors.push(grid.items[this.positionY - 1][this.positionX - 1]);\r\n }\r\n //top right item position\r\n if (this.positionX + 1 <= grid.width - 1 && this.positionY - 1 > -1) {\r\n // console.log('Top Right')\r\n this.neighbors.push(grid.items[this.positionY - 1][this.positionX + 1]);\r\n }\r\n //top item position\r\n if (this.positionY - 1 > -1) {\r\n // console.log(`Top neighbor`);\r\n this.neighbors.push(grid.items[this.positionY - 1][this.positionX]);\r\n }\r\n\r\n //bottom left item position\r\n if (this.positionX - 1 > -1 && this.positionY + 1 <= grid.height - 1) {\r\n // console.log('Bottom Left');\r\n this.neighbors.push(grid.items[this.positionY + 1][this.positionX - 1]);\r\n }\r\n\r\n //bottom right item position\r\n if (this.positionX + 1 <= grid.width - 1 && this.positionY + 1 <= grid.height - 1) {\r\n // console.log('Bottom Right')\r\n this.neighbors.push(grid.items[this.positionY + 1][this.positionX + 1]);\r\n }\r\n //bottom item position\r\n if (this.positionY + 1 <= grid.height - 1) {\r\n // console.log(`Bottom neighbor`);\r\n this.neighbors.push(grid.items[this.positionY + 1][this.positionX]);\r\n }\r\n }", "function locate(element, ship, check) {\n for (var i = 0; i < Number(ship.className[6]); ++i) {\n if (Number(element.id[6]) + i === 10) {\n return \"block\";\n } \n var newElement = document.getElementById(\"ship_\" + element.id[4] + (Number(element.id[6] + i)));\n check = true;\n if (!shipIsInBoard(newElement, ship)) {\n check = false;\n break;\n }\n }\n return check;\n}", "getNeighbors(i, j) {\n\t\tlet neighbors = 0;\n // This section checks above the cell\n //checks up left\n if (i-1 >= 0 && j-1 >= 0 && this.grid[i-1][j-1] > 0){\n neighbors++;\n }\n //checks up\n if (i-1 >= 0 && this.grid[i-1][j] > 0){\n neighbors++;\n }\n //checks up right\n if (i-1 >= 0 && j+1 < this.cols && this.grid[i-1][j+1] > 0){\n neighbors++;\n }\n // This section checks the right and left neighbors\n //checks left\n if (j-1 >= 0 && this.grid[i][j-1] > 0){\n neighbors++;\n }\n //checks right\n if (j+1 < this.cols && this.grid[i][j+1] > 0){\n neighbors++;\n }\n //This section checks below the cell\n //checks down left\n if (i+1 < this.rows && j-1 >= 0 && this.grid[i+1][j-1] > 0){\n neighbors++;\n }\n //checks down\n if (i+1 < this.rows && this.grid[i+1][j] > 0){\n neighbors++;\n }\n //checks down right\n if (i+1 < this.rows && j+1 < this.cols && this.grid[i+1][j+1] > 0){\n neighbors++;\n }\n\t\treturn neighbors;\n\t}", "run() {\n // The list of discovered nodes that need to be evaluated.\n const openSet = [this.grid.startNode];\n\n // closed set contains nodes that have already been visited\n const closedSet = [];\n\n while (openSet.length > 0) {\n\n // current is node having the lowest fScore in openSet,\n // sort openSet so lowest f-score is at end of the array, then pop it off the end\n const current = openSet.sort((n1, n2) => n2.f - n1.f).pop();\n this.openSet = openSet;\n this.currentNode = current;\n\n if (current.equals(this.grid.goalNode)) {\n return current;\n }\n closedSet.push(current);\n\n for (const neighbor of this.grid.neighbors( current.row, current.col ) ) {\n // don't examine neighbors that are already in the closedSet\n if (closedSet.find(node => node.equals(neighbor))) {\n continue;\n }\n // tempGScore is the distance from start to the neighbor through current\n const tempGScore = current.g + current.weightToNode(neighbor);\n\n if (!this.grid.isObstacleNode(current.row, current.col)) {\n if (tempGScore < neighbor.g) {\n // this path to neighbor is the best so far, record it\n neighbor.cameFrom = current;\n neighbor.g = tempGScore;\n neighbor.f = neighbor.g;\n // if neighbor not in openSet, then add it\n if (!openSet.find(node => node.equals(neighbor))) {\n openSet.push(neighbor);\n }\n }\n }\n\n }\n }\n // goal never reached, return null\n return null;\n }", "function newGrid() {\n // Checks how many living neighboring cells each cell has\n // Iterate the grid\n for (let i = 0; i < dimension; i++) {\n for (let j = 0; j < dimension; j++) {\n // Count surrounding living cells\n let cellsCount = 0;\n // Check the three cells above the current one\n if (i !== 0) { // continue only if this is not the first/zero row\n if (j !== 0) // continue only if this is not the first/zero column\n cellsCount += grid[i - 1][j - 1];\n cellsCount += grid[i - 1][j];\n if (j !== (dimension - 1)) // continue only if this is not the last column\n cellsCount += grid[i - 1][j + 1];\n }\n // Check the cell on the left\n if (j !== 0) // continue only if this is not the first/zero column\n cellsCount += grid[i][j - 1];\n // Check the cell on the right \n if (j !== (dimension - 1)) // continue only if this is not the last column\n cellsCount += grid[i][j + 1];\n // Check the three cells below the current one\n if (i !== (dimension - 1)) {\n if (j !== 0) // continue only if this is not the first/zero column\n cellsCount += grid[i + 1][j - 1];\n cellsCount += grid[i + 1][j];\n if (j !== (dimension - 1)) // continue only if this is not the last column\n cellsCount += grid[i + 1][j + 1];\n }\n\n // Check if the currnet cell is dead\n if (grid[i][j] === 0) {\n // Become alive if three surrounding cells are alive, else die\n if (cellsCount === 3) {\n copiedGrid[i][j] = 1;\n } else {\n copiedGrid[i][j] = 0;\n }\n } \n // Current cell is alive\n else if (grid[i][j] === 1) {\n // stay alive with 2 or 3 living neighbours, else die\n if (cellsCount === 2 || cellsCount === 3) {\n copiedGrid[i][j] = 1;\n } else {\n copiedGrid[i][j] = 0;\n }\n }\n }\n }\n\n // Copy the temporary grid in real one\n for (let j = 0; j < dimension; j++) {\n for (let k = 0; k < dimension; k++) {\n grid[j][k] = copiedGrid[j][k];\n }\n }\n\n drawGrid();\n}", "goToNextStep() {\n let diffCount = 0;\n this._cells = this._cells.map((cell, index) => {\n let neighbours = this._layout.getNeighbours(index);\n\n let aliveNeighbours = neighbours.filter(listIndex => this._cells[listIndex]);\n\n if (cell) {\n // RULE NO. 1 AND NO. 3\n if (aliveNeighbours.length < 2 || aliveNeighbours.length > 3) {\n diffCount++;\n return false;\n }\n } else {\n // RULE NO. 4\n if (aliveNeighbours.length === 3) {\n diffCount++;\n return true;\n }\n }\n\n // REST GOES TO RULE NO. 2\n return cell;\n });\n\n if (diffCount > 0) {\n this._gameState = GameState.PROGRESS;\n } else {\n this._gameState = GameState.DONE;\n }\n }", "function buildGridLevel1() {\n\n cells.forEach((cell, index) => {\n\n //Building the walls-Each row is a line\n //Function only works for a width of 18, so if we have a higher level function we would have to update the rebuild the larger grid in the function before we build walls\n if ((index >= 0 && index < 18) ||\n (index === 18) || index === 26 || index === 27 || index === 35 ||\n index === 36 || (index >= 38 && index <= 42) || index === 44 || index === 45 || (index >= 47 && index <= 51) || index === 53 ||\n index === 54 || (index >= 56 && index <= 60) || index === 62 || index === 63 || (index >= 65 && index <= 69) || index === 71 || \n index === 72 || index === 89 ||\n index === 90 || (index >= 92 && index <= 105) || index === 107 ||\n index === 108 || index === 114 || index === 119 || index === 125 ||\n // (index >= 126 && index <= 130) || index === 132 || index === 134 || index === 135 || index === 137 || (index >= 139 && index <= 143) || took some walls out as ghosts are too stupid\n (index >= 126 && index <= 130) || index === 134 || index === 135 || (index >= 139 && index <= 143) ||\n index === 152 || index === 153 ||\n (index >= 162 && index <= 166) || index === 168 || index === 173 || (index >= 175 && index <= 179) ||\n (index >= 180 && index <= 184) || (index >= 186 && index <= 191) || (index >= 193 && index <= 197) ||\n index === 198 || index === 206 || index === 207 || index === 215 ||\n index === 216 || (index >= 218 && index <= 220) || index === 222 || index === 224 || index === 225 || index === 227 || (index >= 229 && index <= 231) || index === 233 ||\n index === 234 || (index >= 236 && index <= 238) || index === 240 || index === 245 || (index >= 247 && index <= 249) || index === 251 ||\n index === 252 || (index >= 258 && index <= 263) || index === 269 ||\n index === 270 || (index >= 272 && index <= 285) || index === 287 ||\n index === 288 || index === 305 ||\n (index >= 306 && index <= 323)\n ){\n cells[index].classList.add('wall')\n \n //Adding portals\n } else if (index === 144 || index === 161) {\n cells[index].classList.add('portal')\n } else if (index === 109 || index === 52 || index === 271 || index === 244) {\n cells[index].classList.add('specialfood')\n } else { //WALWAY CELLS\n cells[index].classList.add('walkway')\n walkway.push(cells[index])\n\n }\n }) \n\n pacman = ((width * (width - 1) - 2))\n cells[pacman].classList.add('pacman_left')\n\n points = 0\n lives = 3\n liveDIV.innerHTML = `LIVES LEFT : ${lives}`\n ghost1 = 115\n ghost2 = 169\n ghost3 = 118\n ghost4 = 172\n cells[ghost1].classList.add('ghost1')\n cells[ghost2].classList.add('ghost2')\n cells[ghost3].classList.add('ghost3')\n cells[ghost4].classList.add('ghost4')\n\n addFood()\n\n}", "assignNeighbours(){\n\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.cols; j++) {\n\n if(this.grid[i][j].isBomb){\n this.grid[i][j].surroundingBombs = -1;\n continue;\n }\n let neighbours = MineSweeper.getNeighbours((i == 0), (i == this.rows-1), (j == 0), (j == this.cols-1));\n\n let counter = 0;\n for(let neighbour of neighbours){\n let dr = neighbour[0];\n let dc = neighbour[1];\n if(this.grid[i+dr][j+dc].isBomb){\n counter++;\n }\n }\n this.grid[i][j].surroundingBombs = counter;\n }\n }\n }", "function treasureIsland(grid) {\n\tlet queue = [];\n\tlet directions = [\n\t\t[-1, 0],\n\t\t[1, 0],\n\t\t[0, 1],\n\t\t[0, -1]\n\t];\n\tlet count = 0;\n\tqueue.push([0, 0]);\n\twhile (queue.length !== 0) {\n\t\tcount++;\n\t\tlet size = queue.length;\n\t\tfor (let i = 0; i < size; i++) {\n\t\t\tlet [startR, startC] = queue.shift();\n\t\t\tfor (let [dr, dc] of directions) {\n\t\t\t\tlet r = startR + dr;\n\t\t\t\tlet c = startC + dc;\n\t\t\t\tif (r >= 0 && r < grid.length && c >= 0 && c < grid[0].length) {\n\t\t\t\t\tif (grid[r][c] === 'X') {\n\t\t\t\t\t\treturn count;\n\t\t\t\t\t}\n\t\t\t\t\tif (grid[r][c] === 'O') {\n\t\t\t\t\t\tgrid[r][c] = 'D'; //make sure not going there again\n\t\t\t\t\t\tqueue.push([r, c]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}", "function step()\r\n{\r\n for (var i = 0; i < this.rows; i++)\r\n {\r\n for (var j = 0; j < this.cols; j++)\r\n {\r\n\r\n var count = this.numNeighbours(i, j);\r\n var living = this.currentGeneration[i][j];\r\n\r\n if (living && count < 2 || living && count > 3)\r\n {\r\n this.nextGeneration[i][j] = false;\r\n }\r\n else if (living && count == 2 || living && count == 3 || !living && count == 3)\r\n {\r\n this.nextGeneration[i][j] = true;\r\n }\r\n }\r\n }\r\n this.currentGeneration = this.nextGeneration.slice();\r\n this.resetNextGeneration();\r\n}", "function moveAllToTop() {\n\tvar moved = false;\n\tfor (var c = 0; c < 4 ; c++ ) {\n\t\tvar s = 0;\n\t\tfor (var r = 0; r < 4 ; r++ ) {\n\t\t\tif (!isCellEmpty(r, c)) {\n\t\t\t\tif (r != s) {\n\t\t\t\t\tmoved = true;\n\t\t\t\t\tsetGridNumRC(s, c, grid[r][c]);\n\t\t\t\t\tsetEmptyCell(r, c);\n\t\t\t\t}\n\t\t\t\ts++;\n\t\t\t}\n\t\t}\n\t}\n\treturn moved;\n}", "function IslandExplorer(Current_x, Current_y){\n // out of bound, return\n if(Current_x < 0 || Current_y < 0 || Current_x >= GRID_ROW_SIZE || Current_y >= GRID_COL_SIZE){\n return\n }\n // explored or not part of an Island, return\n if(Grid[Current_x][Current_y].VisitedAt != -1 || Grid[Current_x][Current_y].State != \"Wall\"){\n return\n }\n // Set visit and explore all 4 neighbours\n Grid[Current_x][Current_y].VisitedAt = 0;\n IslandExplorer(Current_x-1,Current_y)\n IslandExplorer(Current_x+1,Current_y)\n IslandExplorer(Current_x,Current_y-1)\n IslandExplorer(Current_x,Current_y+1)\n return\n\n\n}", "function BestFirstFinder(grid, start, end, heuristics) {\n AStarFinder(grid, start, end, function (x, y) {\n return heuristics(x, y) * 1000000;\n });\n}", "function shipLocation () {\n console.log(ships);\n var countme = 0;\n for (var i = 0; i < 3; i++) {\n countme++;\n var direction = getRandom(2);\n if (direction === 0) {\n var rowStart = getRandom(8 - ships[i][0]);\n var columnStart = getRandom(7);\n for (var j = 0; j < ships[i][0]; j++){\n ships[i][j+1] = String(rowStart + j) + String(columnStart);\n } \n } else {\n var rowStart = getRandom(7);\n var columnStart = getRandom(8 - ships[i][0]);\n for (var j = 0; j < ships[i][0]; j++){\n ships[i][j+1] = String(rowStart) + String(columnStart + j);\n }\n }\n i = matrix(i);\n console.log(\"After the matrix: \" + i);\n if (countme > 10) {\n console.log(\"I had to break!!! \" + countme);\n break;\n }\n if (i === 2){\n for (var i = 0; i < 3; i++){\n ships[i].splice(0,1);\n }\n }\n }\n}", "function start() {\n flag1 = 0;\n flag2 = 0;\n flag3 = 0;\n type = -1;\n\n if (count == 1) {\n aStarSearch(source, dest, grid);\n aStarSearch(source, dest1, grid);\n } else aStarSearch(source, dest, grid);\n}", "function search_start_pos(value) {\n var N = height / $p.config.GRIDY; // target grid N\n\n var y = Infinity,\n y$ = value,\n count = 0;\n\n while (y > 0) {\n y = Math.floor(math.log(y$) * self.A + self.B);\n y$ *= self.$_mult;\n if (count++ > N * 3) return 0; // Prevents deadloops\n }\n\n return y$;\n }", "function generateAIGuess(){\n //target half sunk ships\n for (let i = 0; i<10; i++){\n for (let j=0; j<10; j++){\n if (myArray[i][j]===3){\n let orientation = guessShipOrientation(i,j)\n console.log(orientation)\n //if orientation cannot be assumed yet (only one data point) -> keep checking adjacent cells\n if (typeof guessShipOrientation(i,j) == \"undefined\"){\n let nextGuess = checkAdjacentCells(i,j)\n console.log(nextGuess)\n if (nextGuess != false) return nextGuess;\n }\n //if orientation is known keep checking in that direction until ship fully sunk\n else{\n let nextGuess = checkOrientation(orientation,i,j)\n console.log(nextGuess)\n if (nextGuess != false) return nextGuess;\n }\n } \n }\n }\n //random guess if no open leads\n for (let i=0; i<500; i++){\n let x= Math.floor(Math.random() * 10)\n let y= Math.floor(Math.random() * 10)\n if (myArray[x][y] === 0 || myArray[x][y] == 2){\n //dont return single empty cell surrounded by misses\n if (checkAdjacentCells(x,y) != false) return [x,y]\n } \n }\n \n //if no more posibble random locations, check beside existing ships\n for (let i = 0; i<10; i++){\n for (let j=0; j<10; j++){\n if (myArray[i][j]===3){\n let nextGuess = checkAdjacentCells(i,j)\n if (nextGuess != false) return nextGuess;\n }\n }\n }\n}", "function BFS(){\n clearGridSaveWall()\n resetVisit()\n //setting the startpoint to 0 to initiate the BFS\n Grid[StartPoint[0]][StartPoint[1]].VisitedAt = 0;\n var modifiedThisRound = true\n //the variable that indicates the current round for finding\n var roundIndicator = 0\n var found = false\n\n \n\n\n while(modifiedThisRound == true){\n if(roundIndicator >= (GRID_ROW_SIZE*GRID_COL_SIZE + 1)){\n break\n }\n roundIndicator += 1\n modifiedThisRound = false\n for (let i = 0; i < GRID_ROW_SIZE; i++) { \n if(found){\n break\n }\n for (let j = 0; j < GRID_COL_SIZE; j++) {\n if(Grid[i][j].VisitedAt != -1){\n continue;\n }\n if (Grid[i][j].State == \"Wall\") {\n continue;\n }\n if(i>0){\n if(Grid[i-1][j].VisitedAt == roundIndicator-1){\n modifiedThisRound = true\n Grid[i][j].VisitedAt = roundIndicator\n if(i == EndPoint[0] && j == EndPoint[1]){\n found = true\n break;\n }\n document.getElementById(Grid[i][j].id).innerHTML = \"<div id='explored\"+i+\"x\"+j+\"' class='explored'></div>\"\n document.getElementById(\"explored\"+i+\"x\"+j).style.animationDelay=roundIndicator/5+\"s\"\n \n }\n }\n if(i<GRID_ROW_SIZE-1){\n if(Grid[i+1][j].VisitedAt == roundIndicator-1){\n modifiedThisRound = true\n Grid[i][j].VisitedAt = roundIndicator\n if(i == EndPoint[0] && j == EndPoint[1]){\n found = true\n break;\n }\n document.getElementById(Grid[i][j].id).innerHTML = \"<div id='explored\"+i+\"x\"+j+\"' class='explored'></div>\"\n document.getElementById(\"explored\"+i+\"x\"+j).style.animationDelay=roundIndicator/5+\"s\"\n \n }\n }\n if(j>0){\n if(Grid[i][j-1].VisitedAt == roundIndicator-1){\n modifiedThisRound = true\n Grid[i][j].VisitedAt = roundIndicator\n \n if(i == EndPoint[0] && j == EndPoint[1]){\n found = true\n break;\n }\n document.getElementById(Grid[i][j].id).innerHTML = \"<div id='explored\"+i+\"x\"+j+\"' class='explored'></div>\"\n document.getElementById(\"explored\"+i+\"x\"+j).style.animationDelay=roundIndicator/5+\"s\"\n }\n }\n if(j<GRID_COL_SIZE-1){\n if(Grid[i][j+1].VisitedAt == roundIndicator-1){\n modifiedThisRound = true\n Grid[i][j].VisitedAt = roundIndicator\n if(i == EndPoint[0] && j == EndPoint[1]){\n found = true\n break;\n }\n document.getElementById(Grid[i][j].id).innerHTML = \"<div id='explored\"+i+\"x\"+j+\"' class='explored'></div>\"\n document.getElementById(\"explored\"+i+\"x\"+j).style.animationDelay=roundIndicator/5+\"s\"\n \n }\n }\n\n\n\n }\n }\n\n\n }\n /// end of the search, return path or not found\n\n if(!found){\n console.log(\"End of search, not found\")\n alert(\"No possible route found\")\n return\n }\n console.log(\"Found at round: \" + roundIndicator)\n\n\n var counter = 0\n var myInterval = setInterval(() => {\n if(counter < 1000*roundIndicator/5){\n counter+= 100\n }\n else{\n pathGatherer()\n clearInterval(myInterval)\n }\n }, 100);\n\n\n\n}", "function generation() {\n\t//An array such that numberArray[y][x] is the number of live neighbors gridArray[y][x] has.\n\tvar numberArray = [];\n\tvar neighbors;\n\tfor (var i = 0; i < height; i++) {\n\t\tnumberArray.push([]);\n\t\tfor (var j = 0; j < width; j++) {\n\t\t\tnumberArray[i][j] = 0;\n\t\t}\n\t}\n\tvar cells = getNeighbors(liveCells);\n\tfor (var p = 0; p < cells.length; p++) {\n\t\tneighbors = 0;\n\t\t// Possible x's and possible y's. 3 * 3 = 9, minus i,j, the cell itself, gives you its 8 possible neighbors.\n\t\tyPoss = [cells[p][0] - 1, cells[p][0], cells[p][0] + 1];\n\t\txPoss = [cells[p][1] - 1, cells[p][1], cells[p][1] + 1];\n\t\t// Iterate through xPoss and yPoss.\n\t\tfor (var y = 0; y < 3; y++) {\n\t\t\tfor (var x = 0; x < 3; x++) {\n\t\t\t\t// Make sure it's not (i,j), the cell itself.\n\t\t\t\tif (!(x === 1 && y === 1)) {\n\t\t\t\t\t// Surrounded in try catch so it doesn't throw a fit if it goes off the edge. This one doesn't wrap around the sides.\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (gridArray[yPoss[y]][xPoss[x]] === 1) {\n\t\t\t\t\t\t\tneighbors++;\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (err) {}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Set numberArray spot that corresponds to gridArray spot to the amount of neighbors.\n\t\tnumberArray[cells[p][0]][cells[p][1]] = neighbors;\n\t\t// console.log(cells[p][1], cells[p][0], \"has \", neighbors, \"neighbors\");\n\t}\n\t\t// Look at every cell and see if it should be alive or dead.\n\t\tfor (var i = 0; i < numberArray.length; i++) {\n\t\t\tfor (var j = 0; j < numberArray[i].length; j++) {\n\t\t\t\tif (numberArray[i][j] === 3) {\n\t\t\t\t\tgridArray[i][j] = 1;\n\t\t\t\t\tif (liveCells.myIndexOf([i, j]) == -1) {\n\t\t\t\t\t\tliveCells.push([i, j]);\n\t\t\t\t\t}\n\t\t\t\t} else if (numberArray[i][j] < 2) {\n\t\t\t\t\tgridArray[i][j] = 0;\n\t\t\t\t\tif (liveCells.myIndexOf([i, j]) != -1) {\n\t\t\t\t\t\tliveCells.splice(liveCells.myIndexOf([i, j]), 1);\n\t\t\t\t\t}\n\t\t\t\t} else if (numberArray[i][j] > 3) {\n\t\t\t\t\tgridArray[i][j] = 0;\n\t\t\t\t\tif (liveCells.myIndexOf([j, i]) != -1) {\n\t\t\t\t\t\tliveCells.splice(liveCells.myIndexOf([i, j]), 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// We've set up gridArray to be the next generation, now we just need to show the user, which is what arrayToHtml() does.\n\t\tarrayToHtml();\n\t\tif ([].concat.apply([], gridArray).indexOf(1) === -1) {\n\t\t\t$(\"#pause\").mousedown()\n\t\t\t.mouseup();\n\t\t}\n\t}", "function bestComputerMove (grid, depth) {\n var sonTag;\n var weightMove;\n\n var bestMove = NB_ROW;\n var weightBestMove = -9999999;\n\n var lessWorstMove = NB_ROW;\n var weightLessWorstMove = -9999999;\n\n var sonGrid = createGrid();\n\n for(var row = 0; row <NB_ROW; row++){\n \n sonGrid = copyGrid(grid);\n if(canDropToken(sonGrid, row)){\n\n \t// Let's try this row\n sonGrid = dropToken(sonGrid, row, COMPUTER);\n sonTag = tag(sonGrid, PLAYER, depth);\n\n // Are we sure to win in this row ? \n if(sonTag === COMPUTER) {\n return row;\n }\n\n // Otherwise, lets compute the weight of this move\n weightMove = estimateGrid(sonGrid);\n\n // If nobody is sure to win, we keep the move with the higher weight\n if(sonTag === NOBODY){\n if(weightMove > weightBestMove){\n weightBestMove = weightMove;\n bestMove = row;\n } \n }\n\n // If human player is sure to win within \"depth\" move\n else {\n if(weightMove > weightLessWorstMove) {\n weightLessWorstMove = weightMove;\n lessWorstMove = row;\n }\n }\n\n }\n\n }\n\n // Return the best or less worth move.\n if(bestMove < NB_ROW){\n return bestMove;\n } else {\n return lessWorstMove;\n }\n}", "initGrid() {\n const columns = Math.floor((this.limits.right - this.limits.left) / this.options.gridStep) + 1;\n const rows = Math.floor((this.limits.bottom - this.limits.top) / this.options.gridStep) + 1;\n\n const grow = !this.grid || columns > this.grid.length || rows > this.grid[0].length;\n\n if (grow) {\n this.grid = new Array(columns);\n }\n\n for (let col = 0, x = this.limits.left; col < columns; col ++, x += this.options.gridStep) {\n if (grow) {\n this.grid[col] = new Array(rows);\n }\n\n for (let row = 0, y = this.limits.top; row < rows; row ++, y += this.options.gridStep) {\n // If the current grid node is inside an obstacle,\n // set the \"obstacle\" property of the node.\n const obstacle = this.obstacles.some(\n r => x >= r.left && x <= r.right &&\n y >= r.top && y <= r.bottom\n );\n\n this.grid[col][row] = {\n col, row, // The coordinates of this node in the grid array\n x, y, // The coordinates of this node in the exploration area\n obstacle, // Is there an obstacle at this node?\n\n // The following properties are updated by the pathfinding algorithm\n\n g: 0, // Cost from the start node to this node (g score)\n f: 0, // Estimated cost from the start node\n // to the goal node through this node (f score)\n parent: null, // The previous node in the current explored path\n open: false, // Does this node belong to the open set?\n closed: false, // Has this node already been processed?\n groupCount: 0, // The number of groups passing by this node\n groups: {} // A map of booleans indicating which groups pass by this node\n };\n }\n }\n }", "function nextGenerationGrid(cells) {\n const r = cells.length;\n const c = cells[0].length;\n\n const nextGeneration = cells.map(function(row, i) {\n return row.map(function(cell, j) {\n const n1 = (i == 0 || j == 0 ? 0 : cells[i-1][j-1]);\n const n2 = (i == 0 ? 0 : cells[i-1][j]);\n const n3 = (i == 0 || j == c-1 ? 0 : cells[i-1][j+1]);\n const n4 = (j == 0 ? 0 : cells[i][j-1]);\n const n5 = (j == c-1 ? 0 : cells[i][j+1]);\n const n6 = (i == r-1 || j == 0 ? 0 : cells[i+1][j-1]);\n const n7 = (i == r-1 ? 0 : cells[i+1][j]);\n const n8 = (i == r-1 || j == c-1 ? 0 : cells[i+1][j+1]);\n const n = n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8;\n\n if (n == 3 || (n == 2 && cells[i][j] == 1)) {\n return 1; // alive\n }\n return 0; // dead\n });\n });\n\n return nextGeneration;\n}", "function GenerateTileNeighbours()\n{\n // loop through each tile on the map\n var currentX = 0;\n var currentY = 0;\n\n // since the highest x values can really only be gridheight/width -1, make these the highest tiles we check\n var maxX = (gridHeight - 1);\n var maxY = (gridHeight - 1);\n\n for(currentX = 0; currentX < gridWidth; currentX++)\n {\n for (currentY = 0; currentY < gridHeight; currentY++)\n {\n\n var CurrentTile = Tiles[currentX][currentY];\n // first, if this is a wall tile, we don't care, as we can't generate paths through here, so don't add it to the nodes\n if (!(CurrentTile.TileType == TilesNames.Wall))\n {\n // check each of the tiles neighbours, if it's a valid tile\n if (CurrentTile.x != 0)\n {\n // check the tile to the left of it\n if (IsValidTile(CurrentTile.x - 1, CurrentTile.y))\n {\n // add it to the tiles neighbours\n CurrentTile.Neighbours.push(Tiles[CurrentTile.x - 1][CurrentTile.y]);\n }\n }\n \n if (CurrentTile.x != maxX)\n {\n // check the tile to the right of it\n if (IsValidTile(CurrentTile.x + 1, CurrentTile.y))\n {\n // add it to the tiles neighbours\n CurrentTile.Neighbours.push(Tiles[CurrentTile.x + 1][ CurrentTile.y]);\n }\n }\n\n if (CurrentTile.y != 0)\n {\n // check the tile to the top of it\n if (IsValidTile(CurrentTile.x, CurrentTile.y - 1))\n {\n // add it to the tiles neighbours\n CurrentTile.Neighbours.push(Tiles[CurrentTile.x][CurrentTile.y - 1]);\n }\n }\n\n if (CurrentTile.y != maxY)\n {\n // check the tile below it\n if (IsValidTile(CurrentTile.x, CurrentTile.y + 1))\n {\n // add it to the tiles neighbours\n CurrentTile.Neighbours.push(Tiles[CurrentTile.x][CurrentTile.y + 1]);\n }\n }\n\n }\n }\n\n }\n \n}", "function check_block() {\n var moved = false;\n reset_counts();\n check_counts(\"X\");\n\n if (countdiag1 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 3 + i);\n }\n }\n if (countdiag2 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 2 + 2);\n }\n }\n if (countrow0 == 2) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i);\n }\n }\n if (countrow1 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(3 + i);\n }\n }\n if (countrow2 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(6 + i);\n }\n }\n if (countcol0 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 3);\n }\n }\n if (countcol1 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 3 + 1);\n }\n }\n if (countcol2 == 2 && !moved) {\n for (i = 0; i < 3; i++) {\n moved = take_space(i * 3 + 2);\n }\n }\n return moved;\n}", "function nextGeneration() {\n let newGrid = new Array(rows);\n for (let i = 0; i < rows; i++) {\n newGrid[i] = new Array(cols);\n for (let j = 0; j < cols; j++) {\n let neighbors = countNeighbors(i, j);\n if (grid[i][j] === 1) {\n if (neighbors < 2 || neighbors > 3) {\n newGrid[i][j] = 0;\n } else {\n newGrid[i][j] = 1;\n }\n } else {\n if (neighbors === 3) {\n newGrid[i][j] = 1;\n } else {\n newGrid[i][j] = 0;\n }\n }\n }\n }\n grid = newGrid;\n}", "findShip(row, col) {\n const neighborCell = getNeighbourCells(row, col).find(([row, col]) =>\n this.opponentBoard.cells[row]?.[col]?.classList.contains('ship')\n );\n\n const isHorizontal = neighborCell?.[0] === row;\n const shipStart = Array.from({ length: Math.max(rows, cols) }, (_, index) =>\n isHorizontal ? [row, col - index] : [row - index, col]\n ).find(\n ([row, col]) =>\n this.opponentBoard.cells[row]?.[col]?.classList.contains('ship') !==\n true\n );\n const shipEnd = Array.from({ length: Math.max(rows, cols) }, (_, index) =>\n isHorizontal ? [row, col + index] : [row + index, col]\n ).find(\n ([row, col]) =>\n this.opponentBoard.cells[row]?.[col]?.classList.contains('ship') !==\n true\n );\n\n const horizontalIndex = isHorizontal ? 1 : 0;\n const ship = Array.from(\n { length: shipEnd[horizontalIndex] - shipStart[horizontalIndex] + 1 },\n (_, index) =>\n isHorizontal ? [row, shipStart[1] + index] : [shipStart[0] + index, col]\n );\n const trimmedShip = ship.slice(1, -1);\n\n const largestShip =\n this.fleet.ships.length -\n Array.from(this.fleet.ships)\n .reverse()\n .findIndex((ship) => !ship.disabled);\n\n let canAddBorder = trimmedShip.length === largestShip;\n if (typeof neighborCell === 'undefined')\n canAddBorder ||= getNeighbourCells(row, col).every(\n ([row, col]) =>\n this.opponentBoard.cells[row]?.[col]?.children[0].disabled !== false\n );\n else\n canAddBorder ||=\n this.opponentBoard.cells[shipStart[0]]?.[shipStart[1]]?.children[0]\n .disabled !== false &&\n this.opponentBoard.cells[shipEnd[0]]?.[shipEnd[1]]?.children[0]\n .disabled !== false;\n return ship;\n }", "function solve(){\n var grid = cGrid;\n var point = {\n row: 0,\n col: 0\n };\n stepCount = 0; //resetStep\n exitRow = grid.length-1;\n var minDistance = -1;\n\n //2. Walk through grid, loop each step\n do{\n let nextSteps = [];\n let step = {};\n\n for( var direct in directions){\n step = movable(point, grid, direct);\n if(step.canMove){\n step.direction = direct;\n nextSteps.push(step);\n }\n }\n \n //If no direction walkable, exit\n if(nextSteps.length == 0){\n noExit = true;\n break;\n }\n\n //3. sort distance and take the shortest direction\n nextSteps.sort((a, b) => (a.minDistance - b.minDistance));\n\n //mark current step and make the move\n point = markElement(point, grid, nextSteps);\n\n //5. test exit condition\n if (point.row == exitRow && point.col == exitCol){\n exitReached = true;\n grid[exitRow][exitCol] = colValues.PATH;\n document.getElementById(`${exitRow}:${exitCol}`).setAttribute(\"blockValue\", \"step\");\n stepCount ++;\n break;\n }\n } while(true);\n\n writeResults();\n}" ]
[ "0.64079535", "0.6218261", "0.60234225", "0.5909205", "0.57952476", "0.57545716", "0.57543164", "0.56899416", "0.56549096", "0.56442755", "0.5643415", "0.5632637", "0.5629312", "0.56184286", "0.56154126", "0.56080747", "0.56049144", "0.5600821", "0.5574246", "0.55595684", "0.5558247", "0.5551904", "0.5543298", "0.55426466", "0.55402005", "0.5519048", "0.5507473", "0.5504149", "0.54653144", "0.5462695" ]
0.624206
1
to get no of days in kgp
function no_of_days() { var d = new Date(), minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(), hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(), ampm = d.getHours() >= 12 ? 'pm' : 'am', months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']; var date2 = new Date("07/24/2017");//mm/dd/yyyy var timeDiff = Math.abs(date2.getTime() - d.getTime()); var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); return diffDays; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "calculateDays() {\n const secondsInADay = 86400;\n let seconds = this.calculateSeconds();\n this.daysCount = seconds / secondsInADay;\n this.daysCount = Math.floor(this.daysCount);\n\n return this.daysCount;\n }", "numberOfDays(){\n return ((this.endDate - this.startDate)/(1000*60*60*24));//converting to days from milliseconds\n }", "function numberOfDays(){\n\t\t\t\t\t\t\t\t\tvar milliseconds;\n\t\t\t\t\t\t\t\t\tmilliseconds = nextBirthday.getTime() - today.getTime();\n\t\t\t\t\t\t\t\t\tvar minutes = 1000 * 60;\n\t\t\t\t\t\t\t\t\tvar hours = minutes * 60;\n\t\t\t\t\t\t\t\t\tvar days = hours * 24;\n\t\t\t\t\t\t\t\t\tvar daysToReturn = milliseconds / days;\n\t\t\t\t\t\t\t\t\tdaysToReturn = Math.ceil(daysToReturn);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif(daysToReturn == 365){\n\t\t\t\t\t\t\t\t\t\tdaysToReturn = 0;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tconsole.log(\"Days until next birthday: \" + daysToReturn);\n\t\t\t\t\t\t\t\t\treturn daysToReturn;\n\t\t\t\t\t}", "function beautifulDays(i, j, k) {\r\n var z=0;\r\n var count=0\r\n for(var t=i;t<=j;t++){\r\n z =Number(('' + t).split('').reverse().join(''));\r\n console.log(z)\r\n \r\n var diff=Math.abs(t-z);\r\n \r\n if((diff)%k==0){\r\n count++\r\n }\r\n }\r\n return count;\r\n }", "function beautifulDays(i, j, k) {\n // Write your code here\n let count = 0\n for (let c = i; c <= j; c++) {\n let numToSttring = String(c)\n let ReverseNum = Number(numToSttring.split(\"\").reverse().join(\"\"))\n\n let diference = Math.abs(c - ReverseNum) / k\n\n if (diference % 1 === 0) count++\n }\n\n return count\n}", "daysBooked(){\n let daysBookedOff = 0\n for(let booking of this._booking){\n daysBookedOff+=booking.numberOfDays();\n }\n return daysBookedOff;\n }", "function countSundays(){\n\treturn Math.floor((12/7)*100);\n}", "elapsed_days(){\n return this.ticks / TICKS_PER_DAY; \n }", "function kiekDienuIkiKaledu() {\n console.log(\"266\");\n // siandienos data\n let today = new Date();\n // kaledu data\n let christmas = new Date(\"2021-12-24\");\n console.log(\"today\", today.toDateString(), \"christmas\", christmas.toDateString());\n\n // skirtumo tarp datu\n let diffMs = christmas - today;\n console.log(\"diffMs\", diffMs);\n // paversti ta skirtuma dienom\n let msToDays = diffMs / 1000 / 3600 / 24;\n // gaunam kiek pilnu dienu\n let wholeDays = Math.floor(msToDays);\n\n // panaudojom pagalbine funkcija\n //let wholeDays = daysDiff(today, christmas);\n\n // atspausdinti\n console.log(\"iki kaledu liko\", wholeDays, \"dienu\");\n}", "function getDays() {\n\treturn [...Array(31).keys()].map((index) => index + 1);\n}", "function getNDAYS(i_g_in, i_g_fin, i_m_in, i_m_fin) {\n\n var giorni_mese_in;\n if (i_m_in === 0) giorni_mese_in = 31;\n if (i_m_in === 1) giorni_mese_in = 29;\n if (i_m_in === 2) giorni_mese_in = 31;\n if (i_m_in === 3) giorni_mese_in = 30;\n if (i_m_in === 4) giorni_mese_in = 31;\n if (i_m_in === 5) giorni_mese_in = 30;\n if (i_m_in === 6) giorni_mese_in = 31;\n if (i_m_in === 7) giorni_mese_in = 31;\n if (i_m_in === 8) giorni_mese_in = 30;\n if (i_m_in === 9) giorni_mese_in = 31;\n if (i_m_in === 10) giorni_mese_in = 30;\n if (i_m_in === 11) giorni_mese_in = 31;\n\n n_giorno_in = i_g_in;\n n_giorno_fin = i_g_fin;\n\n var giorni;\n\n if (i_m_in === i_m_fin) giorni = (i_g_fin - i_g_in) ; // giorni del mese corrente\n else if (i_m_in !== i_m_fin) giorni = (i_g_fin + 1) + (giorni_mese_in - i_g_in -1); //giorni del mese precedente\n n_days = giorni+1;\n n_mese_in = i_m_in;\n n_mese_fin = i_m_fin;\n\n return giorni+1;\n}", "static getNumOfSpecialDays(start, end) {\n // Find the start and end Jewish years\n const jewishStartYear = new JewishCalendar_1.JewishCalendar(start).getJewishYear();\n const jewishEndYear = new JewishCalendar_1.JewishCalendar(end).getJewishYear();\n // Value to return\n let specialDays = 0;\n // Instant of special dates\n const yomKippur = new JewishCalendar_1.JewishCalendar(jewishStartYear, 7, 10);\n const tishaBeav = new JewishCalendar_1.JewishCalendar(jewishStartYear, 5, 9);\n // Go over the years and find special dates\n for (let i = jewishStartYear; i <= jewishEndYear; i++) {\n yomKippur.setJewishYear(i);\n tishaBeav.setJewishYear(i);\n const interval = luxon_1.Interval.fromDateTimes(start, end);\n if (interval.contains(yomKippur.getDate()))\n specialDays++;\n if (interval.contains(tishaBeav.getDate()))\n specialDays++;\n }\n return specialDays;\n }", "getDays() {\n return new Date(this.y, this.m, 0).getDate()\n }", "function getNoOfDays(createdDate){\n\tstartDate = new Date(createdDate);\n\ttodaysDate = new Date();\n\tvar days = Math.floor((todaysDate - startDate) / (1000 * 60 * 60 * 24));\n\treturn days;\n}", "function getDatepriordays(days){\n\t var today= new Date(); \n\t\t//today.setDate(today.getDate()-1)\n\t\tvar dayOfTheWeek=today.getDay();\n\t\tvar calendarDays = days;\n\t\tvar deliveryDay = dayOfTheWeek + days;\n\t\tif (deliveryDay >= 6) {\n\t\t\tdays -= 6 - dayOfTheWeek; //deduct this-week days\n\t\t\t//calendarDays += 2; //count this coming weekend\n\t\t\t//alert(\"calendarDays1=====>\"+calendarDays);\n\t\t\t//deliveryWeeks = Math.floor(days / 5); how many whole weeks?\n\t\t\t//alert(\"deliveryWeeks=====>\"+deliveryWeeks);\n\t\t\t//calendarDays += deliveryWeeks * 2; two days per weekend per week\n\t\t\t}\n\t\ttoday.setTime(today.getTime() + calendarDays * 24 * 60 * 60 * 1000); \t\t\n\t\tvar theyear=today.getYear() \n\t\tvar themonth=today.getMonth()+1 \n\t\tvar theday=today.getDate() \t\t \n\t\treturn theyear + '.' + getStringFormat(themonth,2) + '.' + getStringFormat(theday,2);\n\t}", "function getDate_n_DaysFromGiven(given,n,objRet){\n\nlet othday= new Number(given.getDate())\nothday+=n\ngiven.setDate(othday);\n\ndate_n_DaysFromGiven= objRet ? (\n new Date(given.getTime())\n ):(\n given.toLocaleDateString(undefined,{\n weekday:\"long\",\n day:\"numeric\",\n month:\"numeric\",\n year:\"numeric\"\n })+\" \"\n );\n\ngiven.setDate(Number(given.getDate())-n);\n\nreturn date_n_DaysFromGiven;\n}", "function calcTotalDayAgain() {\n var eventCount = $this.find('.this-month .event-single').length;\n $this.find('.total-bar b').text(eventCount);\n $this.find('.events h3 span b').text($this.find('.events .event-single').length)\n }", "function totalDays() {\n //Adds up the total number of days in sentence from combination of years, months and days.\n var years, months, days;\n years = document.donatello_form.sentenceYears.value;\n months = document.donatello_form.sentenceMonths.value;\n days = document.donatello_form.sentenceDays.value;\n return Math.floor(years * daysPerYear) + Math.floor(months * daysPerMonth) + Number(days);\n}", "function GetDays(){\n var startdate = new Date(document.getElementById(\"start_date\").value);\n var enddate = new Date(document.getElementById(\"end_date\").value);\n return parseInt((enddate - startdate) / (24 * 3600 * 1000));\n }", "function howManyDays (anyDate){\n let currentDate = ((new Date()).getDate())\n let remainingDays = currentDate - anyDate\n return remainingDays / (1000*60*60*24)\n}", "function get_wn() {\r\n \tvar today = new Date();\r\n\tYear = takeYear(today);\r\n\tMonth = today.getMonth();\r\n\tDay = today.getDate();\r\n\tnow = Date.UTC(Year,Month,Day+1,0,0,0);\r\n\tvar Firstday = new Date();\r\n\tFirstday.setYear(Year);\r\n\tFirstday.setMonth(0);\r\n\tFirstday.setDate(1);\r\n\tthen = Date.UTC(Year,0,1,0,0,0);\r\n\tvar Compensation = Firstday.getDay();\r\n\tif (Compensation > 3) Compensation -= 4;\r\n\telse Compensation += 3;\r\n\tweek_num = Math.round((((now-then)/86400000)+Compensation)/7);\r\n\tday_num = Math.round(((now-then)/86400000)+Compensation);\r\n\tday_nos = Math.round((now-then)/86400000);\r\n}", "function getTotalDays(y, m){\r\n\t\t\treturn new Date(y, m, 0).getDate();\r\n\t\t}", "function days_in_b_year(yr,mo,da){\n if (mo <= 12){\n var days=0;\n for(mo ; mo<=12 ;mo++){\n var days = days + dayslist[mo];\n }\n var days = days - da\n return days\n }\n\n}", "get workingDays() {\n return this.detailedDailyWage.filter(day => day.wage!==0).length;\n }", "function getVerseOfTheDayPicture() {\n \n let today = new Date();\n let year = today.getFullYear();\n var janFirst = new Date(year, 0, 1, 1, 1, 1, 1);\n var days = daydiff(janFirst,today);\n\n var dailyVersePictureToGet = Math.ceil((((days / 23) - Math.floor((days / 23)))) * 23);\n \n console.log(dailyVersePictureToGet);\n \n return dailyVersePictureToGet;\n}", "function countShowingfreeDays(){\n return document.querySelectorAll(\".weekend-header\").length\n}", "function countRealWorkingTime(wantedProcentageAsInt, fullWorkDayNumber){\n let originalArray = []\n \n let wantedProcentageInDouble = wantedProcentageAsInt/100\n let currentWorkDayLength = Math.trunc(fullWorkDayMinutes*wantedProcentageInDouble)\n let allValues = document.querySelectorAll(\".header-balance-part\")\n //Counts total of days showing currently on kellokortti by counting the plus icons on right side of each day working time marking\n let howManyDaysIsShowing = document.querySelectorAll(\".float-right.glyphicon.glyphicon-plus-sign\").length\n //let workingDaysCount = howManyDaysIsShowing-countShowingfreeDays()\n originalArray = preProcessOriginalArray(allValues, originalArray) \n let combinedArray = createCombinedArray(originalArray)\n let minutesArray = transformArrayToMinutes(combinedArray, currentWorkDayLength, fullWorkDayNumber)\n let total = gainTotalBalance(minutesArray)\n return returnTotalHoursAndMinutesAsString(total)\n}", "function howManyDays(month) {\n switch (month) {\n case 2:\n return 28;\n case 4:\n case 6:\n case 9:\n case 11:\n return 30;\n }\n return 31;\n}", "createThirtyDays(e) {\n let dates = [];\n for (const [key,] of Object.entries(e)) {\n dates.push(key);\n }\n let sortedDates = dates.sort((a,b) => a.valueOf() - b.valueOf());\n let sortedThirty = sortedDates.slice(0,30);\n return sortedThirty;\n }", "function getDayCompletion(){\n return (Date.now() / 1000 / 60 / 60 / 24) % 1;\n}" ]
[ "0.67897034", "0.65952903", "0.6536408", "0.6521484", "0.61982596", "0.61929715", "0.6138811", "0.60371274", "0.59765095", "0.59604055", "0.59576684", "0.5890101", "0.58603126", "0.58555025", "0.58413243", "0.58301485", "0.58148503", "0.5812444", "0.58109355", "0.5765538", "0.575764", "0.5757406", "0.5715933", "0.569224", "0.5688322", "0.56813455", "0.5662334", "0.56621504", "0.56499743", "0.5633641" ]
0.6867405
0
This is a ConformanceMessaging resource
static get __resourceType() { return 'ConformanceMessaging'; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function messagingApi()\n{\n\n}", "sendMessageService(boatId) { \n publish(this.messageContext, BoatMC, {recordId:boatId});\n }", "get communication () {\n\t\treturn this._communication;\n\t}", "get communication() {\n\t\treturn this.__communication;\n\t}", "onWorkerMsg(msg){\n\n if (msg.replyTo!=null){\n\n if (messageBuffer[msg.replyTo]!=undefined){\n\n //Store the reply in the buffer.\n messageBuffer[msg.replyTo].reply = msg;\n\n //Send the response to the client.\n messageBuffer[msg.replyTo].client.json({response:msg.payload});\n\n }\n\n }\n\n }", "constructor(ctxPtr) {\n this.name = 'RatchetMessage';\n\n if (typeof ctxPtr === 'undefined') {\n this.ctxPtr = Module._vscr_ratchet_message_new();\n } else {\n this.ctxPtr = ctxPtr;\n }\n }", "BroadcastMessage() {}", "BroadcastMessage() {}", "BroadcastMessage() {}", "BroadcastMessage() {}", "respondToMessages() { }", "static get __resourceType() {\n\t\treturn 'MessageHeader';\n\t}", "constructor() { \n \n BandwidthCallbackMessage.initialize(this);\n }", "function Conversation() {}", "async initializeServiceWorkerMessaging() {\r\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\r\n }", "async initializeServiceWorkerMessaging() {\r\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\r\n }", "function Component_MessageBehavior() {\n\n /**\n * Reference to temporary game settings.\n * @property settings\n * @type Object\n * @protected\n */\n this.tempSettings = GameManager.tempSettings;\n\n /**\n * Indicates if the message is currently waiting.\n * @property isWaiting\n * @type boolean\n * @readOnly\n */\n this.isWaiting = false;\n\n /**\n * Indicates if the message is currently running.\n * @property isRunning\n * @type boolean\n * @readOnly\n */\n this.isRunning = false;\n\n /**\n * Indicates if a voice is currently playing together with the message.\n * @property isVoicePlaying\n * @type boolean\n * @readOnly\n */\n this.isVoicePlaying = false;\n\n /**\n * Current message caret/cursor position.\n * @property caretPosition\n * @type gs.Point\n * @readOnly\n */\n this.caretPosition = new gs.Point(0, 0);\n\n /**\n * Current raw message text.\n * @property message\n * @type string\n * @readOnly\n */\n this.message = \"\";\n\n /**\n * All currently displayed raw messages.\n * @property messages\n * @type string[]\n * @readOnly\n */\n this.messages = [];\n\n /**\n * Voice associated with the current message.\n * @property voice\n * @type gs.AudioBufferReference\n */\n this.voice = null;\n\n /**\n * Indicates if current message is partial. DEPRECATED. Please do not use.\n * @property partial\n * @deprecated\n * @type boolean\n * @readOnly\n */\n this.partial = false;\n\n /**\n * Indicates if the message is currently waiting in live-preview.\n * @property waitingPreview\n * @type boolean\n * @readOnly\n */\n this.waitingPreview = false;\n\n /**\n * Indicates if the auto-message is enabled.\n * @property autoMessageEnabled\n * @type boolean\n * @readOnly\n */\n this.autoMessageEnabled = false;\n this.onMessageFinish = (function(_this) {\n return function(sender) {\n _this.object.events.emit(\"finish\", _this);\n if (_this.object.settings.autoErase || _this.object.settings.paragraphSpacing > 0) {\n return _this.message = \"\";\n }\n };\n })(this);\n this.onMessageWaiting = (function(_this) {\n return function(sender) {\n if (!_this.object.textRenderer.isBatched() || !_this.object.textRenderer.isBatchInProgress()) {\n _this.object.textRenderer.waitAtEnd = !_this.partial;\n return _this.object.events.emit(\"waiting\", _this);\n }\n };\n })(this);\n }", "function GetProto() {\r\n return `\r\n // See README.txt for information and build instructions.\r\n\r\n package CanOpenBridge;\r\n\r\n //option java_package = \"com.burkert.cop\";\r\n //option java_outer_classname = \"CanOpenBridge\";\r\n\r\n // put an optional field here for every new classtype\r\n message MessageWrapper {\r\n optional SDO SDO = 1;\r\n optional PDO PDO = 2;\r\n optional Event Event = 3;\r\n optional AddNode AddNode = 4;\r\n optional RemoveNode RemoveNode = 5;\r\n optional Commands Commands = 6;\r\n optional SYNC SYNC = 7;\r\n optional SdoProgress SdoProgress = 8;\r\n optional Request Request = 9;\r\n optional RequestProgress RequestProgress = 10;\r\n optional RawData RawData = 11;\r\n optional CanMeasure CanMeasure = 12;\r\n }\r\n\r\n message SDO {\r\n required int32 nodeId = 1;\r\n required int32 index = 2;\r\n required int32 subIndex = 3;\r\n enum Control {\r\n READ = 0;\r\n WRITE = 1;\r\n\t RESPONSE = 2;\r\n\t ABORT = 3;\r\n\t READ_BLOCK = 4;\r\n\t WRITE_BLOCK = 5;\r\n }\r\n required Control control = 4;\r\n optional bytes data = 5;\r\n optional int32 totalBlockLen = 6;\r\n optional uint64 timestamp = 7;\r\n }\r\n\r\n message PDO {\r\n required int32 nodeId = 6;\r\n required int32 pdoNumber = 7;\r\n required bytes data = 8;\r\n required uint64 timestamp = 9;\r\n }\r\n\r\n message Event {\r\n required int32 nodeId = 10;\r\n required bytes data = 11;\r\n required uint64 timestamp = 12;\r\n enum EventType {\r\n EMERGENCY = 0;\r\n BDO = 1;\t\r\n SERVERINFO = 2;\r\n\t SERVERERROR = 3;\r\n\t NMT = 4;\r\n }\r\n required EventType eventType = 16;\r\n }\r\n\r\n message AddNode {\r\n required int32 nodeId = 13;\r\n optional int32 deviceStatus = 14;\r\n }\r\n\r\n message RemoveNode {\r\n required int32 nodeId = 14;\r\n }\r\n\r\n message Commands {\r\n enum Command {\r\n SHUTDOWN = 0;\r\n RESTART_SOCKET = 1;\r\n }\r\n required Command command = 15;\r\n }\r\n\r\n message SYNC {\r\n required uint32 flags = 17;\r\n }\r\n\r\n message SdoProgress {\r\n required int32 nodeId = 1;\r\n required int32 index = 2;\r\n required int32 subIndex = 3;\r\n required int32 value = 4;\r\n }\r\n\r\n message Request {\r\n\t enum RequestType {\r\n\t\t Complete = 0;\r\n\t\t SearchCANopenDevices = 1;\r\n\t\t GetLSS_Slave = 2;\r\n\t\t CnfLSS_Slave = 3;\r\n\t\t CanRawData = 4;\r\n\t\t CanMeasure = 5;\r\n\t }\r\n\t required RequestType requestType = 1;\r\n\t optional int32 nodeID = 2;\r\n\t optional int32 baudrate = 3;\r\n\t optional int32 result = 4;\r\n\t optional int32 vendorID = 5;\r\n\t optional int32 productCode = 6;\r\n\t optional int32 revisionNumber = 7;\r\n\t optional int32 serialNumber = 8;\r\n\t optional int32 rawDataActive = 9;\r\n\t optional int32 canMeasureActive = 10;\r\n }\r\n\r\n message RequestProgress {\r\n\t required int32 value = 1;\r\n }\r\n message RawData {\r\n required uint32 cobId = 1;\r\n required bytes data = 2;\r\n required uint64 timeStamp = 3;\r\n required bool direction = 4; \r\n }\r\n\r\n message CanMeasure{\r\n required int32 errorFlags = 1;\r\n required int32 canHRise = 2;\r\n required int32 canHFall = 3;\r\n required int32 canLRise = 4;\r\n required int32 canLFall = 5;\r\n }\r\n\t\t`;\r\n}", "constructor(config = {}) {\n this.runtime = Runtime.make();\n this.handleBusMessages();\n this.devMode = config.devMode || devMode.mode;\n this.debug = this.devMode\n ? debugFn\n : () => {\n /* no op */\n };\n\n this.ERROR_COMM_CHANNEL_NOT_INIT = 'Comm channel not initialized, not sending message.';\n\n this.messageQueue = [];\n\n // maintain a mapping of job IDs and dispatch information\n this._jobMapping = {};\n }", "function MessagingService(konyRef) {\r\n\r\n\tvar homeUrl = konyRef.messagingsvc.url;\r\n\tvar KSID;\r\n\tvar appId = konyRef.messagingsvc.appId;\r\n\tvar logger = new konyLogger();\r\n\tvar networkProvider = new konyNetworkProvider();\r\n\tvar dsKey = homeUrl + \":KMS:AppId\";\r\n\r\n\tthis.getUrl = function() {\r\n\t\treturn homeUrl;\r\n\t};\r\n\r\n\tthis.setKSID = function(ksid) {\r\n\t\tkonyRef.getDataStore().setItem(dsKey, ksid);\r\n\t\tKSID = ksid;\r\n\t};\r\n\r\n\tthis.getKSID = function() {\r\n\t\tif (!KSID) {\r\n\t\t\tKSID = konyRef.getDataStore().getItem(dsKey);\r\n\t\t}\r\n\t\treturn KSID;\r\n\t};\r\n\r\n\tthis.setKmsAppId = function(id) {\r\n\t\tappId = id;\r\n\t};\r\n\r\n\tthis.getKmsAppId = function() {\r\n\t\treturn appId;\r\n\t};\r\n\t/**\r\n\t * register success callback method.\r\n\t * @callback registerSuccessCallback\r\n\t * @param {json} response - register response\r\n\t */\r\n\r\n\t/**\r\n\t * Register service failure callback method.\r\n\t * @callback registerFailureCallback\r\n\t * @param {json} error - Error information\r\n\t */\r\n\t/**\r\n\t * register to messaging service\r\n\t * @param {string} osType - Type of the operating system\r\n\t * @param {string} deviceId - Device Id\r\n\t * @param {string} pnsToken - Token value\r\n\t * @param {registerSuccessCallback} successCallback - Callback method on success\r\n\t * @param {registerFailureCallback} failureCallback - Callback method on failure\r\n\t */\r\n\tthis.register = function(osType, deviceId, pnsToken, email, successCallback, failureCallback) {\r\n\t\tif (typeof(pnsToken) === 'undefined' || pnsToken === null) {\r\n\t\t\tthrow new Exception(Errors.MESSAGING_FAILURE, \"Invalid pnsToken/sId. Please check your messaging provider\");\r\n\t\t}\r\n\t\tif (typeof(osType) === 'undefined' || osType === null) {\r\n\t\t\tthrow new Exception(Errors.MESSAGING_FAILURE, \"Invalid osType.\");\r\n\t\t}\r\n\t\tif (typeof(deviceId) === 'undefined' || deviceId === null) {\r\n\t\t\tthrow new Exception(Errors.MESSAGING_FAILURE, \"Invalid deviceId.\");\r\n\t\t}\r\n\t\tif (typeof(email) === 'undefined' || email === null) {\r\n\t\t\tthrow new Exception(Errors.MESSAGING_FAILURE, \"Invalid email.\");\r\n\t\t}\r\n\t\tvar uri = homeUrl + \"/subscribers\";\r\n\t\tjsonParam = {\r\n\t\t\t\"subscriptionService\": {\r\n\t\t\t\t\"subscribe\": {\r\n\t\t\t\t\t\"sid\": pnsToken,\r\n\t\t\t\t\t\"appId\": this.getKmsAppId(),\r\n\t\t\t\t\t\"ufid\": email,\r\n\t\t\t\t\t\"osType\": osType,\r\n\t\t\t\t\t\"deviceId\": deviceId\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\tvar headers = {\r\n\t\t\t\"Content-Type\": \"application/json\"\r\n\t\t};\r\n var payload = {\r\n\t\t\tpostdata : JSON.stringify(jsonParam)\r\n\t\t}\r\n\t\tlogger.log(JSON.stringify(jsonParam));\r\n\t\tnetworkProvider.post(uri,\r\n\t\t\tpayload,\r\n\t\t\theaders,\r\n\t\t\tfunction(data) {\r\n\t\t\t\tKSID = data.id;\r\n\t\t\t\tkonyRef.getDataStore().setItem(dsKey, KSID);\r\n\t\t\t\tlogger.log(\"Device registered to KMS with KSID:\" + KSID);\r\n\t\t\t\tkony.sdk.verifyAndCallClosure(successCallback, data);\r\n\t\t\t},\r\n\t\t\tfunction(data, status, error) {\r\n\r\n\t\t\t\tlogger.log(\"ERROR: Failed to subscribe device for KMS\");\r\n\t\t\t\tvar errorObj = {};\r\n\t\t\t\terrorObj.data = data;\r\n\t\t\t\terrorObj.status = status;\r\n\t\t\t\terrorObj.error = error;\r\n\t\t\t\tkony.sdk.verifyAndCallClosure(failureCallback, errorObj);\r\n\t\t\t});\r\n\t};\r\n\t/**\r\n\t * unregister success callback method.\r\n\t * @callback unregisterSuccessCallback\r\n\t */\r\n\r\n\t/**\r\n\t * unregister service failure callback method.\r\n\t * @callback unregisterFailureCallback\r\n\t */\r\n\t/**\r\n\t * unregister to messaging service\r\n\t * @param {unregisterSuccessCallback} successCallback - Callback method on success\r\n\t * @param {unregisterFailureCallback} failureCallback - Callback method on failure\r\n\t */\r\n\tthis.unregister = function(successCallback, failureCallback) {\r\n\t\tvar uri = homeUrl + \"/subscribers/\" + this.getKSID();\r\n\t\tlogger.log(\"unsubscribe uri:\" + uri);\r\n\t\tkonyRef.getDataStore().removeItem(dsKey);\r\n\t\tvar headers = {\r\n\t\t\t\"Content-Type\": \"application/json\",\r\n\t\t\t\"X-HTTP-Method-Override\": \"DELETE\"\r\n\t\t};\r\n\t\tnetworkProvider.post(uri, null, headers, successCallback, failureCallback);\r\n\t};\r\n\t/**\r\n\t * Fetch all messages success callback method.\r\n\t * @callback fetchAllMessagesSuccessCallback\r\n\t * @param {json} response - Fetch all messages response\r\n\t */\r\n\r\n\t/**\r\n\t * Fetch all messages service failure callback method.\r\n\t * @callback fetchAllMessagesFailureCallback\r\n\t * @param {json} error - Error information\r\n\t */\r\n\t/**\r\n\t * Fetch all messages\r\n\t * @param {fetchAllMessagesSuccessCallback} successCallback - Callback method on success\r\n\t * @param {fetchAllMessagesFailureCallback} failureCallback - Callback method on failure\r\n\t */\r\n\tthis.fetchAllMessages = function(startIndex, pageSize, successCallback, failureCallback) {\r\n\t\tvar uri = homeUrl + \"/messages/fetch\";\r\n\t\tvar headers = {\r\n\t\t\t\"Content-Type\": \"application/json\"\r\n\t\t};\r\n\t\tvar data = {\r\n\t\t\t\"ksid\": this.getKSID(),\r\n\t\t\t\"startElement\": startIndex,\r\n\t\t\t\"elementsPerPage\": pageSize\r\n\t\t};\r\n var payload = {\r\n\t\t\tpostdata : JSON.stringify(data)\r\n\t\t}\r\n\t\tnetworkProvider.post(uri, payload, headers, successCallback, failureCallback);\r\n\t};\r\n\t/**\r\n\t * Update location service success callback method.\r\n\t * @callback updateLocationSuccessCallback\r\n\t * @param {json} response - Update location response\r\n\t */\r\n\r\n\t/**\r\n\t * Update location service failure callback method.\r\n\t * @callback updateLocationFailureCallback\r\n\t * @param {json} error - Error information\r\n\t */\r\n\t/**\r\n\t * Update the location\r\n\t * @param {string} latitude - Latitude value\r\n\t * @param {string} longitude - Longitude value\r\n\t * @param {string} locationName - Location name\r\n\t * @param {updateLocationSuccessCallback} successCallback - Callback method on success\r\n\t * @param {updateLocationFailureCallback} failureCallback - Callback method on failure\r\n\t */\r\n\tthis.updateGeoLocation = function(latitude, longitude, locationName, successCallback, failureCallback) {\r\n\t\tif (typeof(latitude) === 'undefined' || latitude === null) {\r\n\t\t\tthrow new Exception(MESSAGING_FAILURE, \"invalid latitude paramter value\");\r\n\t\t}\r\n\t\tif (typeof(longitude) === 'undefined' || longitude === null) {\r\n\t\t\tthrow new Exception(MESSAGING_FAILURE, \"invalid longitude paramter value\");\r\n\t\t}\r\n\t\tif (typeof(locationName) === 'undefined' || locationName === null) {\r\n\t\t\tthrow new Exception(MESSAGING_FAILURE, \"invalid locationName paramter value\");\r\n\t\t}\r\n\t\tvar headers = {\r\n\t\t\t\"Content-Type\": \"application/json\"\r\n\t\t};\r\n\t\tvar uri = homeUrl + \"/location\";\r\n\t\tvar data = {\r\n\t\t\t\"ksid\": this.getKSID(),\r\n\t\t\t\"latitude\": latitude,\r\n\t\t\t\"locname\": locationName,\r\n\t\t\t\"longitude\": longitude\r\n\t\t};\r\n\t\tvar payload = {\r\n\t\t\tpostdata : JSON.stringify(data)\r\n\t\t}\r\n\t\tlogger.log(\"updateLocation payload: \" + JSON.stringify(payload));\r\n\t\tnetworkProvider.post(uri, payload, headers, successCallback, failureCallback);\r\n\t};\r\n\t/**\r\n\t * Mark meesage as read service success callback method.\r\n\t * @callback markReadSuccessCallback\r\n\t * @param {json} response - Mark meesage as read service response\r\n\t */\r\n\t/**\r\n\t * Mark meesage as read service failure callback method.\r\n\t * @callback markReadFailureCallback\r\n\t * @param {json} error - Error information\r\n\t */\r\n\t/**\r\n\t * Mark the message as read for a given message id\r\n\t * @param {string} messageId - Message id\r\n\t * @param {markReadSuccessCallback} successCallback - Callback method on success\r\n\t * @param {markReadFailureCallback} failureCallback - Callback method on failure\r\n\t */\r\n\tthis.markMessageRead = function(fetchId, successCallback, failureCallback) {\r\n\t\tif (typeof(fetchId) === 'undefined' || fetchId === null) {\r\n\t\t\tthrow new Exception(MESSAGING_FAILURE, \"invalid fetchId paramter value\");\r\n\t\t}\r\n\t\tvar headers = {\r\n\t\t\t\"Content-Type\": \"application/json\"\r\n\t\t};\r\n\t\tvar uri = homeUrl + \"/messages/open/\" + fetchId;\r\n\t\tnetworkProvider.get(uri, null, headers, successCallback, failureCallback);\r\n\r\n\t};\r\n\t/**\r\n\t * Message content service success callback method.\r\n\t * @callback messageContentSuccessCallback\r\n\t * @param {json} response - Message content service response\r\n\t */\r\n\t/**\r\n\t * Message content service failure callback method.\r\n\t * @callback messageContentFailureCallback\r\n\t * @param {json} error - Error information\r\n\t */\r\n\t/**\r\n\t * Fetches the message conetent for a given message id\r\n\t * @param {string} messageId - Message id\r\n\t * @param {messageContentSuccessCallback} successCallback - Callback method on success\r\n\t * @param {messageContentFailureCallback} failureCallback - Callback method on failure\r\n\t */\r\n\tthis.fetchMessageContent = function(fetchId, successCallback, failureCallback) {\r\n\t\tif (typeof(fetchId) === 'undefined' || fetchId === null) {\r\n\t\t\tthrow new Exception(MESSAGING_FAILURE, \"invalid fetchId paramter value\");\r\n\t\t}\r\n\t\tvar headers = {\r\n\t\t\t\"Content-Type\": \"application/json\"\r\n\t\t};\r\n\t\tvar uri = homeUrl + \"/messages/content/\" + fetchId;\r\n\t\tnetworkProvider.get(uri, null, headers, successCallback, failureCallback);\r\n\t};\r\n}", "constructor(params = {})\n\t{\n\t\tthis.ready = true;\n\n\t\tthis.offline = false;\n\n\t\tthis.host = this.getHost();\n\n\t\tthis.inited = false;\n\n\t\tthis.restClient = BX.rest;\n\n\t\tthis.customData = [];\n\n\t\tthis.localize = {...BX.message};\n\n\t\tthis.subscribers = {};\n\t\tthis.dateFormat = null;\n\n\t\tthis.messagesQueue = [];\n\n\t\tthis.configRequestXhr = null;\n\n\t\tthis.windowFocused = true;\n\n\t\tthis.rootNode = document.getElementById('messenger-root');\n\n\t\tthis.template = null;\n\n\t\tthis.timer = new Timer();\n\n\t\twindow.addEventListener('orientationchange', () => {\n\t\t\tif (!this.store)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.store.commit('application/set', {\n\t\t\t\tdevice : {\n\t\t\t\t\torientation : Utils.device.getOrientation()\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tif (\n\t\t\t\tthis.store.state.application.device.type === DeviceType.mobile\n\t\t\t\t&& this.store.state.application.device.orientation === DeviceOrientation.horizontal\n\t\t\t)\n\t\t\t{\n\t\t\t\tdocument.activeElement.blur();\n\t\t\t}\n\t\t});\n\n\t\t// todo change to dynamic storage (LocalStorage web, PageParams for mobile)\n\t\tlet serverVariables = LocalStorage.get(this.getSiteId(), 0, 'serverVariables', false);\n\t\tif (serverVariables)\n\t\t{\n\t\t\tthis.addLocalize(serverVariables);\n\t\t}\n\n\t\t//alert('Pause: open console for debug');\n\n\t\tBX.componentParameters.init()\n\t\t\t.then(result => this.initMobileSettings(result))\n\t\t\t.then(result => this.initStorage(result))\n\t\t\t.then(result => this.initComponent(result))\n\t\t\t.then(result => this.requestData(result))\n\t\t\t.then(result => this.initEnvironment(result))\n\t\t\t.then(result => this.initMobileEnvironment(result))\n\t\t\t.then(result => this.initPullClient(result))\n\t\t;\n\t}", "function checkConversationPossibility(){\n var obj = {};\n obj = getMessageObj();\n // console.log(\"obj >>\", obj);\n obj[\"job_id\"] = jobId;\n obj[\"name\"] = userName;\n obj[\"resume_id\"] = resumeId;\n obj[\"user_id\"] = user_id;\n obj[\"user_type\"] = user_type;\n obj[\"cid\"] = candidateId;\n obj[\"sll\"] = sll;\n obj[\"all_vars\"] = all_vars;\n socket.emit(\"checkIsConversationPossible\", obj);\n }", "onMessageStart() { }", "static get is() { return 'lingo-live-write-message'; }", "broadcast () {\n throw new this.context.errors.PreconditionError('Cannot broadcast: the MODBUS protocol does not support realtime');\n }", "function onSendMessage(data){\n\t//TODO \n}", "sendMessage(content_message)\n {\n\n let recipient = this.props.participants.get(this.props.currentUser);\n let sender = this.props.participants.get(recipient)\n\n let message = {\n content : content_message,\n recipient : recipient,\n sender: sender,\n fkConversation : this.props.conversation,\n date:Date.now()\n }\n this.client.send('/EZChat/'+message.fkConversation.id+'/private',{},JSON.stringify(message))\n }", "static get type() { return 'mq'; }", "function Sms() {\n\n}", "constructor() { \n \n Message.initialize(this);\n }" ]
[ "0.61389846", "0.55454636", "0.5482138", "0.54554975", "0.54206866", "0.5387298", "0.53735256", "0.53735256", "0.53735256", "0.53735256", "0.53557914", "0.53556335", "0.5337448", "0.53085494", "0.53010654", "0.53010654", "0.52676386", "0.52588576", "0.5256887", "0.5248511", "0.5232467", "0.52274233", "0.5223724", "0.51965725", "0.5173698", "0.51640946", "0.5154463", "0.5138014", "0.5132041", "0.51304626" ]
0.7466156
0
An endpoint (network accessible address) to which messages and/or replies are to be sent.
get endpoint() { return this.__endpoint; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "get endpoint () {\n\t\treturn this._endpoint;\n\t}", "address() {\n const address = this.server.address();\n const endpoint = typeof address !== \"string\"\n ? (address.address === \"::\" ? \"localhost\" : address.address) + \":\" + address.port\n : address;\n return `${this.protocol}://${endpoint}`;\n }", "get endpoint() {\n return this.getStringAttribute('endpoint');\n }", "get endpoint() {\n return this.getStringAttribute('endpoint');\n }", "get endpoint() {\n return this.getStringAttribute('endpoint');\n }", "function replyToSpec() {\n return wrap('reply-to', addressList());\n }", "function replyToSpec() {\n return wrap('reply-to', addressList());\n }", "function replyToSpec() {\n return wrap('reply-to', addressList());\n }", "function replyToSpec() {\n return wrap('reply-to', addressList());\n }", "endpoint() {\n //\n }", "function EndpointImpl() {\n\t\tvar endpointImpl = this;\n\t\tvar config = {};\n\t\tvar cometd = null; // current cometd instance\n\t\tvar connected = false;\n\t\tvar connectCalled = false; // for automatic connect on first use\n\n\t\t// FeedImpl attachment points\n\t\tthis.onStateChange = null;\n\t\tthis.onData = null;\n\n\t\t// ----- private endpointImpl methods -----\n\n\t\tfunction debug(msg) {\n\t\t\tif (config.logLevel === \"debug\" && console && console.log)\n\t\t\t\tconsole.log(msg);\n\t\t}\n\n\t\tfunction info(msg) {\n\t\t\tif (console && console.info)\n\t\t\t\tconsole.info(msg);\n\t\t}\n\n\t\tfunction warn(msg) {\n\t\t\tif (console && console.warn)\n\t\t\t\tconsole.warn(msg);\n\t\t}\n\n\t\tfunction convertToAbsoluteURL(url) {\n\t\t\tif (/^https?:\\/\\//i.test(url))\n\t\t\t\treturn url;\n\t\t\tif (/^\\/\\//.test(url))\n\t\t\t\treturn location.protocol + url;\n\t\t\tif (/^\\//.test(url))\n\t\t\t\treturn location.protocol + \"//\" + location.host + url;\n\t\t\treturn location.protocol + \"//\" + location.host + location.pathname + url;\n\t\t}\n\n\t\tfunction updateConnectedState(newConnected) {\n\t\t\tvar wasConnected = connected;\n\t\t\tif (wasConnected !== newConnected) {\n\t\t\t\tinfo(wasConnected ? \"Connection lost\" : \"Connection established\");\n\t\t\t\tconnected = newConnected;\n\t\t\t\tendpointImpl.onStateChange({ connected: newConnected });\n\t\t\t}\n\t\t}\n\n\t\t// Function that manages the connection status with the Bayeux server\n\t\tfunction onMetaConnect(message) {\n\t\t\tif (cometd === null || cometd.isDisconnected()) {\n\t\t\t\tupdateConnectedState(false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tupdateConnectedState(message.successful === true);\n\t\t}\n\n\t\tfunction onMetaUnsuccessful() {\n\t\t\tupdateConnectedState(false)\n\t\t}\n\n\t\tfunction onServiceState(message) {\n\t\t\tdebug(\"Received state \" + JSON.stringify(message));\n\t\t\tendpointImpl.onStateChange(message.data);\n\t\t}\n\n\t\tfunction onServiceData(message) {\n\t\t\tdebug(\"Received data \" + JSON.stringify(message));\n\t\t\tendpointImpl.onData(message.data, false);\n\t\t}\n\n\t\tfunction onServiceTimeSeriesData(message) {\n\t\t\tdebug(\"Received time series data \" + JSON.stringify(message));\n\t\t\tendpointImpl.onData(message.data, true);\n\t\t}\n\n\t\tfunction connect(url) {\n\t\t\tconnectCalled = true;\n\t\t\tif (!org.CometD) {\n\t\t\t\twarn(\"No CometD, working without connection\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (config.url === undefined && dx.contextPath !== undefined)\n\t\t\t\tconfig.url = dx.contextPath + \"/cometd\"; // default webservice path\n\t\t\tif (typeof url === \"string\") {\n\t\t\t\tconfig.url = url;\n\t\t\t} else if (typeof url === \"object\") {\n\t\t\t\tconfig = extend(config, url);\n\t\t\t}\n\t\t\tconfig.url = convertToAbsoluteURL(config.url);\n\t\t\tinfo(\"Connecting with url: \" + config.url);\n\t\t\tif (cometd === null) {\n\t\t\t\tcometd = new org.CometD();\n\t\t\t\tcometd.addListener(\"/meta/connect\", onMetaConnect);\n\t\t\t\tcometd.addListener(\"/meta/unsuccessful\", onMetaUnsuccessful);\n\t\t\t\tcometd.addListener(\"/service/state\", onServiceState);\n\t\t\t\tcometd.addListener(\"/service/data\", onServiceData);\n\t\t\t\tcometd.addListener(\"/service/timeSeriesData\", onServiceTimeSeriesData);\n\t\t\t}\n\t\t\tcometd.configure(config);\n\t\t\tcometd.handshake();\n\t\t}\n\n\t\t// ----- public endpointImpl methods -----\n\n\t\tthis.logLevel = function (level) {\n\t\t\tconfig.logLevel = level;\n\t\t};\n\n\t\tthis.isConnected = function () {\n\t\t\treturn connected;\n\t\t};\n\n\t\tthis.connect = connect;\n\n\t\tthis.disconnect = function () {\n\t\t\tif (cometd !== null) {\n\t\t\t\tinfo(\"Disconnecting\");\n\t\t\t\tcometd.disconnect(true);\n\t\t\t\tcometd = null;\n\t\t\t\tconnected = false;\n\t\t\t}\n\t\t};\n\n\t\tthis.publish = function (service, message) {\n\t\t\tdebug(\"Publishing to \" + service + \": \" + JSON.stringify(message));\n\t\t\tcometd.publish(\"/service/\" + service, message);\n\t\t};\n\n\t\tthis.connectIfNeeded = function () {\n\t\t\tif (!connectCalled)\n\t\t\t\tconnect();\n\t\t};\n\t}", "function deriveEndpoint(edge, index, ep, conn) {\n return options.deriveEndpoint ? options.deriveEndpoint(edge, index, ep, conn) : options.endpoint ? options.endpoint : ep.type;\n }", "get primaryEndpointAddress() {\n return this.getStringAttribute('primary_endpoint_address');\n }", "getPeerAddr() {\n\t\tvar addr = null;\n\t\tif(this._ep) {\n\t\t\taddr = this._ep._endpoint.addr;\n\t\t}\n\n\t\treturn addr;\n\t}", "function setupEndpoint() {\n if (host.val().indexOf('/') != -1) {\n var hostArr = host.val().split('/');\n\n path = \"http://\" + hostArr[0] + \":\" + port.val();\n hostArr.shift(); // remove host\n\n if (hostArr.length > 0) { // anything left?\n path += \"/\" + hostArr.join('/');\n }\n } else {\n path = \"http://\" + host.val() + \":\" + port.val();\n }\n endpoint = path;\n }", "function createConnection () {\n connection = App.models.endpoint({\n id: options.connectTo,\n client: client,\n onMessage: renderReply\n });\n }", "get readerEndpointAddress() {\n return this.getStringAttribute('reader_endpoint_address');\n }", "registerDeviceEndpoint() {\n this.SNS = new AWS.SNS();\n return this.SNS.createPlatformEndpoint({\n Token: this.deviceId,\n PlatformApplicationArn: this.applicationArn\n }, (err, data) => {\n if (err) {\n console.log('error registering device', err);\n return;\n }\n\n const params = {\n Protocol: 'application',\n TopicArn: this.topicArn,\n Endpoint: data.EndpointArn\n };\n\n this.subscribeToTopic(params);\n });\n }", "addEndpoint(options = {}) {\n const state = this[kInternalState];\n if (this.destroyed)\n throw new ERR_INVALID_STATE('QuicSocket is already destroyed');\n if (state.state !== kSocketUnbound)\n throw new ERR_INVALID_STATE('QuicSocket is already being bound');\n\n options = {\n lookup: state.lookup,\n ...options\n };\n\n const endpoint = new QuicEndpoint(this, options);\n state.endpoints.add(endpoint);\n return endpoint;\n }", "function configureEndpoint() {\n\tif(!o().isEndpoint()) {\n\t\to().config({\n\t\t\tendpoint:'http://services.odata.org/V4/%28S%28wptr35qf3bz4kb5oatn432ul%29%29/TripPinServiceRW/',\n\t\t\tversion:4,\n\t\t\tstrictMode:true\n\t\t});\n\t}\n}", "get configurationEndpointAddress() {\n return this.getStringAttribute('configuration_endpoint_address');\n }", "function _getEndpointUri(endpoint) {\n return _endpoint.gebo + _endpoint[endpoint];\n }", "function endpoint(path, method) {\n function Endpoint(path, method) {\n this.path = path;\n this.method = method;\n }\n allEndpoints.push( new Endpoint(path, method) );\n}", "function sendOneToOneNegotiation(type, endpoint, sdp){\n var jsonSend = { protocol: \"one-to-one\", room: room, from: client, endpoint: endpoint, action: type, data: sdp};\n ws.send(JSON.stringify(jsonSend));\n }", "_attachEndpoint(func, endpoint) {\n\t\t// Validate method and path\n\t\t/* istanbul ignore next */\n\t\tif (!endpoint.method || !endpoint.path) {\n\t\t\treturn this.log(\n\t\t\t\t`Endpoint ${endpoint.type} for function ${func.name} has no method or path`\n\t\t\t)\n\t\t}\n\t\t// Add HTTP endpoint to Express\n\t\tthis.app[endpoint.method.toLowerCase()](\n\t\t\tendpoint.path,\n\t\t\t(request, response) => {\n\t\t\t\tthis.log(`${endpoint}`)\n\t\t\t\t// Execute Lambda with corresponding event, forward response to Express\n\t\t\t\tlet lambdaEvent = endpoint.getLambdaEvent(request)\n\t\t\t\tthis._executeLambdaHandler(func, lambdaEvent)\n\t\t\t\t\t.then(result => {\n\t\t\t\t\t\tthis.log(' ➡ Success')\n\t\t\t\t\t\tif (process.env.SLS_DEBUG) console.info(result)\n\t\t\t\t\t\tendpoint.handleLambdaSuccess(response, result)\n\t\t\t\t\t})\n\t\t\t\t\t.catch(error => {\n\t\t\t\t\t\tthis.log(` ➡ Failure: ${error.message}`)\n\t\t\t\t\t\tif (process.env.SLS_DEBUG) console.error(error.stack)\n\t\t\t\t\t\tendpoint.handleLambdaFailure(response, error)\n\t\t\t\t\t})\n\t\t\t}\n\t\t)\n\t}", "function address(node) {\n return node.broadcast_address + ':' + node.tcp_port;\n}", "addPayloadEndpoint(opts) {\n if (this.event.payload.endpoints === undefined) this.event.payload.endpoints = [];\n\n this.event.payload.endpoints.push(this.createPayloadEndpoint(opts));\n }", "get URI() {\n\t\treturn 'exchange://' + this.username + '@' + this.hostname + this.name;\n\t}", "function printEndpoint(method, name, payload, params){\n console.log(\"\\n========== ========== ==========\");\n console.log(method + \" \" + name);\n console.log(\"PAYLOAD: \", payload);\n console.log(\"PARAMS: \", params);\n console.log(\"========== ========== ==========\");\n}", "function showEndpoint(response){\n}" ]
[ "0.60655105", "0.58461183", "0.58366686", "0.58366686", "0.58366686", "0.58349746", "0.58349746", "0.58349746", "0.58349746", "0.5667294", "0.55351883", "0.54919016", "0.5422372", "0.54212075", "0.5405083", "0.53320336", "0.52002597", "0.51635903", "0.5131667", "0.5127271", "0.51250964", "0.5094514", "0.50697136", "0.5043066", "0.50188136", "0.5002228", "0.49946365", "0.4986997", "0.49869192", "0.49824664" ]
0.6017733
1
this closes the document.ready function functions: this area is for functions======================= updateEnemyBars: this function will update the health and counter bars of the enemies
function updateEnemyBars (fighterClass, fighterHealthClass, fighterCounterClass) { var healthPercent; var counterPercent; healthPercent = ((fighterClass.health * 100) / fighterClass.healthMax); counterPercent = ((fighterClass.counter * 100) / fighterClass.counterMax); console.log("enemy health percent: " + healthPercent); console.log("enemy counter percent: " + counterPercent); //these commands update the bars in the character $ ("." + fighterHealthClass).css("width",healthPercent + "%"); $ ("." + fighterCounterClass).css("width",counterPercent + "%"); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function worldUpdate() {\r\n\t$('#distance').html(prettify(Game.world.distance));\r\n\t$('#zone').html(Game.zone);\r\n\r\n\t//enemy\r\n\t$('#enemyHealth').html(prettify(Game.enemy.health));\r\n\r\n\tvar enemyHealthBar = document.getElementById(\"enemyHealthBar\");\r\n\tvar hp = (Game.enemy.health / Game.enemy.totalhealth) * 100;\r\n\tenemyHealthBar.style.width = hp + '%';\r\n\r\n\tif (Game.enemy.health >= Game.enemy.totalhealth) Game.enemy.health = Game.enemy.totalhealth;\r\n\r\n\tif (Game.enemy.health <= 0) {\r\n\t\tenemyHealthBar.style.width = '0%';\r\n\t\tendFight();\r\n\t}\r\n}", "update(){\n this.graphics.clear();\n for(let bar of this.healthBars){\n if(!bar.visible){\n continue;\n }\n bar.updatePos();\n bar.outerWidth = bar.barWidth * (bar.track.health/100);\n this.draw(bar);\n }\n for(let bar of this.progressBars){\n if(bar.track.state === \"closed\"){\n bar.visible = true;\n }\n else{\n bar.visible = false;\n }\n if(bar.visible){\n bar.updatePos();\n bar.outerWidth = bar.barWidth * (bar.track.tapCount/bar.track.maxTap);\n this.draw(bar);\n }\n }\n }", "function updateAll() {\n //var marioElem = document.getElementById(\"mario\");\n if (damage > 0) {\n player.health -= damage;\n var fireElem = document.getElementById(\"fire\").attributes\n //document.getElementById(\"mario\").classlist.add(\"vader\")\n }\n\n //totalDamage();\n damage = 0;\n update.innerText = player.health.toString();\n playerName.innerText = player.name;\n displayHits.innerText = player.hits.toString();\n\n if (player.health < 30) {\n document.getElementById(\"player-panel\").classList.add(\"panel-danger\");\n healthBarElem.classList.add('progress-bar-danger');\n } else if (player.health > 30 && player.health < 60) {\n document.getElementById(\"player-panel\").classList.remove(\"panel-danger\");\n document.getElementById(\"player-panel\").classList.add(\"panel-warning\");\n healthBarElem.classList.remove('progress-bar-danger');\n healthBarElem.classList.add('progress-bar-warning');\n } else {\n document.getElementById(\"player-panel\").classList.remove(\"panel-danger\");\n document.getElementById(\"player-panel\").classList.remove(\"panel-warning\");\n document.getElementById(\"player-panel\").classList.add(\"panel-default\");\n healthBarElem.classList.remove('progress-bar-danger');\n healthBarElem.classList.remove('progress-bar-warning');\n healthBarElem.classList.add('progress-bar-success');\n\n\n }\n if (player.health <= 0) {\n termElem.src = 'img/boom-sm.png';\n player.health = 0;\n updateHealthBar();\n // disabled buttons come back after timeout\n disableButtons();\n debugger\n winnerElem.innerText = player.name + \" Wins! The Terminator was destroyed in \" + player.hits + \" hits!\";\n winnerElem.style.color = \"green\";\n clearInterval(interval);\n }\n updateHealthBar();\n\n}", "function firstInitHealthBar() {\r\n hbWidth = userIntThis.sys.game.config.width*0.20;\r\n hbHeight = userIntThis.sys.game.config.height*0.05;\r\n hbIncrement = hbWidth/maxHealth;\r\n hbReady = true;\r\n oldHealth = maxHealth;\r\n healthBar = userIntThis.add.graphics();\r\n healthBar.setDepth(500);\r\n}", "function parseHealthBar() {\r\n if (hbReady) {\r\n hbReady = false;\r\n drawHealthBar();\r\n setTimeout(setHBReady(), 250);\r\n }\r\n}", "function updateDisp()\n\t\t\t{\n// Updates the numbers and graphics for the 4 main stats\n\t\t\t\tdocument.querySelector(\".healthValue\").innerHTML = health;\n\t\t\t\tdocument.querySelector(\".healthBar\").style.right = (100 - health * 10) + \"%\";\n\t\t\t\t\n\t\t\t\tdocument.querySelector(\".hungerValue\").innerHTML = hunger;\n\t\t\t\tdocument.querySelector(\".hungerBar\").style.right = (100 - hunger * 10) + \"%\";\n\t\t\t\t\n\t\t\t\tdocument.querySelector(\".thirstValue\").innerHTML = thirst;\n\t\t\t\tdocument.querySelector(\".thirstBar\").style.right = (100 - thirst * 10) + \"%\";\n\t\t\t\t\n\t\t\t\tdocument.querySelector(\".staminaValue\").innerHTML = stamina;\n\t\t\t\tdocument.querySelector(\".staminaBar\").style.right = (100 - stamina * 10) + \"%\";\n// Updates the values of the inventory items\n\t\t\t\tdocument.querySelector(\".stoneBank\").innerHTML = stoneBank;\n\t\t\t\tdocument.querySelector(\".leafBank\").innerHTML = leafBank;\n\t\t\t\tdocument.querySelector(\".branchBank\").innerHTML = branchBank;\n\t\t\t\tdocument.querySelector(\".wheatSeedBank\").innerHTML = wheatSeedBank;\n\t\t\t\tdocument.querySelector(\".waterBank\").innerHTML = waterBank;\n\t\t\t\tdocument.querySelector(\".berryBank\").innerHTML = berryBank;\n\t\t\t\tdocument.querySelector(\".fungusBank\").innerHTML = fungusBank;\n\t\t\t\tdocument.querySelector(\".sharpStoneBank\").innerHTML = sharpStoneBank;\n\t\t\t\tdocument.querySelector(\".leafTarpBank\").innerHTML = leafTarpBank;\n\t\t\t\tdocument.querySelector(\".smoothBranchBank\").innerHTML = smoothBranchBank;\n\t\t\t\tdocument.querySelector(\".ropeBank\").innerHTML = ropeBank;\n// Updates various buttons' disabled status and inner text\n\t\t\t\tif (stoneBank >= 2)\n\t\t\t\t{\n\t\t\t\t\tdocument.querySelector(\".sharpenStoneButton\").disabled = false;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdocument.querySelector(\".sharpenStoneButton\").disabled = true;\n\t\t\t\t}\n\t\t\t\tif (leafBank >= 5 && ropeBank >= 1)\n\t\t\t\t{\n\t\t\t\t\tdocument.querySelector(\".sewLeavesButton\").disabled = false;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdocument.querySelector(\".sewLeavesButton\").disabled = true;\n\t\t\t\t}\n\t\t\t\tif (sharpStoneBank >= 1 && branchBank >= 1)\n\t\t\t\t{\n\t\t\t\t\tdocument.querySelector(\".smoothBranchButton\").disabled = false;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdocument.querySelector(\".smoothBranchButton\").disabled = true;\n\t\t\t\t}\n\t\t\t\tif (branchBank >= 5 && leafBank >= 5)\n\t\t\t\t{\n\t\t\t\t\tdocument.querySelector(\".makeRopeButton\").disabled = false;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdocument.querySelector(\".makeRopeButton\").disabled = true;\n\t\t\t\t}\n\t\t\t\tif (pickaxeTier == 0)\n\t\t\t\t{\n\t\t\t\t\tif (sharpStoneBank >= 1 && smoothBranchBank >= 1 && ropeBank >= 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".pickaxeButton\").disabled = false;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".pickaxeButton\").disabled = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (pickaxeTier == 1)\n\t\t\t\t{\n\t\t\t\t\tdocument.querySelector(\".pickaxeButton\").innerHTML = \"Tin Pickaxe<hr>Tin Ingot (1)<br>Wooden Handle (1)<br>Stone Peg (2)\";\n\t\t\t\t\tif (tinIngotBank >= 1 && woodHandleBank >= 1 && stonePegBank >= 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".pickaxeButton\").disabled = false;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".pickaxeButton\").disabled = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (axeTier == 0)\n\t\t\t\t{\n\t\t\t\t\tif (sharpStoneBank >= 1 && smoothBranchBank >= 1 && ropeBank >= 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".axeButton\").disabled = false;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".axeButton\").disabled = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (axeTier == 1)\n\t\t\t\t{\n\t\t\t\t\tdocument.querySelector(\".axeButton\").innerHTML = \"Tin Axe<hr>Tin Ingot (1)<br>Wooden Handle (1)<br>Stone Peg (2)\";\n\t\t\t\t\tif (tinIngotBank >= 1 && woodHandleBank >= 1 && stonePegBank >= 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".axeButton\").disabled = false;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".axeButton\").disabled = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (shovelTier == 0)\n\t\t\t\t{\n\t\t\t\t\tif (sharpStoneBank >= 1 && smoothBranchBank >= 1 && ropeBank >= 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".shovelButton\").disabled = false;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".shovelButton\").disabled = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (shovelTier == 1)\n\t\t\t\t{\n\t\t\t\t\tdocument.querySelector(\".shovelButton\").innerHTML = \"Tin Shovel<hr>Tin Ingot (1)<br>Wooden Handle (1)<br>Stone Peg (2)\";\n\t\t\t\t\tif (tinIngotBank >= 1 && woodHandleBank >= 1 && stonePegBank >= 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".shovelButton\").disabled = false;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".shovelButton\").disabled = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (hoeTier == 0)\n\t\t\t\t{\n\t\t\t\t\tif (sharpStoneBank >= 1 && smoothBranchBank >= 1 && ropeBank >= 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".hoeButton\").disabled = false;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".hoeButton\").disabled = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (hoeTier == 1)\n\t\t\t\t{\n\t\t\t\t\tdocument.querySelector(\".hoeButton\").innerHTML = \"Tin Hoe<hr>Tin Ingot (1)<br>Wooden Handle (1)<br>Stone Peg (2)\";\n\t\t\t\t\tif (tinIngotBank >= 1 && woodHandleBank >= 1 && stonePegBank >= 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".hoeButton\").disabled = false;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".hoeButton\").disabled = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (sickleTier == 0)\n\t\t\t\t{\n\t\t\t\t\tif (sharpStoneBank >= 1 && smoothBranchBank >= 1 && ropeBank >= 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".sickleButton\").disabled = false;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".sickleButton\").disabled = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (sickleTier == 1)\n\t\t\t\t{\n\t\t\t\t\tdocument.querySelector(\".sickleButton\").innerHTML = \"Tin Sickle<hr>Tin Ingot (1)<br>Wooden Handle (1)<br>Stone Peg (2)\";\n\t\t\t\t\tif (tinIngotBank >= 1 && woodHandleBank >= 1 && stonePegBank >= 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".sickleButton\").disabled = false;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.querySelector(\".sickleButton\").disabled = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdocument.querySelector(\".collectWater\").innerHTML = \"Collect Water (\" + waterTurns + \")\";\n\t\t\t\tdocument.querySelector(\".collectWater\").disabled = !waterTurns;\n\t\t\t\tdocument.querySelector(\".drinkWater\").innerHTML = \"Drink Water (\" + waterBank + \")\";\n\t\t\t\tdocument.querySelector(\".drinkWater\").disabled = !waterBank;\n\t\t\t\tdocument.querySelector(\".collectBerries\").innerHTML = \"Collect Berries (\" + berryTurns + \")\";\n\t\t\t\tdocument.querySelector(\".collectBerries\").disabled = !berryTurns;\n\t\t\t\tdocument.querySelector(\".eatBerries\").innerHTML = \"Eat Berries (\" + berryBank + \")\";\n\t\t\t\t\n\t\t\t\tdocument.querySelector(\".eatFungus\").innerHTML = \"Eat Fungus (\" + fungusBank + \")\";\n\t\t\t\tdocument.querySelector(\".eatFungus\").disabled = !fungusBank;\n\t\t\t\t\n// Checks if the player has died\n\t\t\t\tif (health <= 0)\n\t\t\t\t{\n\t\t\t\t\tdead();\n\t\t\t\t}\n\t\t\t}", "function parseHealthBar() {\n if (hbReady) {\n hbReady = false;\n drawHealthBar();\n setTimeout(setHBReady(), 250);\n }\n}", "function increaseHealth() \n{\n if(healthBarScript.healthWidth < 199) \n\t {\n\t healthBarScript.healthWidth = healthBarScript.healthWidth + 1;\n\t }\n}", "function drawHealthBar() {\n maxHealthUpdate();\n healthBar.clear();\n \n hbX = userIntThis.cameras.main.scrollX + userIntThis.sys.game.config.width*0.73;\n hbY = userIntThis.cameras.main.scrollY + userIntThis.sys.game.config.height*0.0225;\n healthBar.lineStyle(1,0x000000,1);\n healthBar.fillStyle(0xff0000,1);\n healthBar.strokeRect(hbX,hbY,hbWidth,hbHeight);\n \n if (currentHealth > 0) {\n healthBar.fillRect(hbX,hbY,hbIncrement*oldHealth,hbHeight);\n }\n}", "function parseHealthBarAnimate() {\r\n hbReady = true;\r\n healthDif = oldHealth - currentHealth;\r\n if (healthDif != 0) {\r\n intervalVar = setInterval(oldHealthCtr, 50);\r\n }\r\n}", "function combatEnder() {\n var playerTile = mapArrays[testPlayer.y][testPlayer.x];\n playerTile.monsterHere = false;\n currentEnemy.statReset();\n $(\"#\" + currentEnemy.name + \"-image\").fadeOut(\"slow\");;\n currentEnemy = {};\n playerInCombat = false;\n $(\"#monster-description\").text(\"\");\n $(\"#monster-name\").text(\"\");\n $(\"#monster-sounds\").text(\"\");\n $(\"#monster-health-number\").hide();\n $(\"#monster-health\").hide();\n $(\"#room-hider\").delay(600).fadeIn(100);\n $(\"#room-description\").delay(600).fadeIn(\"slow\")\n $(\"#searcher-images\").delay(600).fadeIn(\"slow\");\n surroundingChecker(testPlayer);\n}", "function enemyStatus() {\n var el = enemies.length;\n eNums.data = destroyedCount+\" of \"+el+\" of \"+(Basics.levelShips+(level-1)*2);\n if (el && (Basics.levelShips+(level-1)*2) == destroyedCount) {\n level++; score += 10;\n message(\"Next level reached, bonus added!\");\n eLevel.data = \"Level: \"+level;\n addScore(0);\n Settings.setNight();\n afterLevel(1);\n }\n}", "function drawHealthBar() {\r\n healthBar.clear();\r\n hbX = userIntThis.cameras.main.scrollX + userIntThis.sys.game.config.width*0.775;\r\n hbY = userIntThis.cameras.main.scrollY + userIntThis.sys.game.config.height*0.0225;\r\n healthBar.lineStyle(1,0x000000,1);\r\n healthBar.fillStyle(0xff0000,1);\r\n healthBar.strokeRect(hbX,hbY,hbWidth,hbHeight);\r\n \r\n if (currentHealth > 0) {\r\n healthBar.fillRect(hbX,hbY,hbIncrement*oldHealth,hbHeight);\r\n }\r\n}", "function checkChangesToHUD() {\r\n if(menu){\r\n staminaSprite.visible = false;\r\n healthSprite.visible = false;\r\n staminaSprite2.visible = false;\r\n healthSprite2.visible = false;\r\n }\r\n else{\r\n staminaSprite.visible = true;\r\n healthSprite.visible = true;\r\n staminaSprite2.visible = true;\r\n healthSprite2.visible = true;\r\n }\r\n\r\n staminaSprite.scale.set((Math.abs(stamina) / 200) * spriteXScale, spriteYScale, 1);\r\n staminaSprite.position.x = (spriteXPosition) - (1 - (Math.abs(stamina)/200)) * spriteXScale / 2;\r\n\r\n // Damage effect\r\n if(damageWarning){\r\n if(damageFrames > 5){\r\n damageSprite.visible = false;\r\n damageWarning = false;\r\n }\r\n damageFrames += 1;\r\n }\r\n\r\n // If you have been hurt, we update the apperance of your health\r\n if (damaged) {\r\n \r\n // Update the size of the health bar according to your amount of health\r\n healthSprite.scale.set((Math.abs(health) / 100) * spriteXScale, spriteYScale, 1);\r\n healthSprite.position.x = (spriteXPosition) - (1 - (Math.abs(health)/100)) * spriteXScale / 2;\r\n\r\n // Color codes your health bar according to amount of health\r\n if (health > 80) {\r\n healthSprite.material.color.setHex(0x00ff00); // Green\r\n }\r\n if (health < 80) {\r\n healthSprite.material.color.setHex(0xffff00); // Yellow\r\n }\r\n if (health < 50) {\r\n healthSprite.material.color.setHex(0xff0000); // Red\r\n }\r\n\r\n // Set damaged to false to prevent taking further damage from the source\r\n damaged = false;\r\n }\r\n\r\n // Fading in the game over screen(s)\r\n if (gameOverScreen) {\r\n if (bloodSprite.material.opacity < 0.8) {\r\n bloodSprite.material.opacity += 0.01;\r\n gameOverSprite.material.opacity += 0.015;\r\n } else if (restartSprite.material.opacity < 0.5) {\r\n restartSprite.material.opacity += 0.02;\r\n }\r\n }\r\n \r\n // TODO: Comment\r\n if(level == 2 && !menu){\r\n var distance = new THREE.Vector3();\r\n distance.subVectors(charMesh.position, puzzle.position);\r\n if(distance.length() < 10){\r\n crossHairSprite.visible = true;\r\n }\r\n else{\r\n crossHairSprite.visible = false;\r\n }\r\n }\r\n}", "function yourEnemies() {\n \n if (yourFighter=='luke') {\n\n $('#yourEnemy').append('<div id =\"enemy2\"></div>');\n $('#enemy2').append('<div>Obi-Wan Kenobi</div>');\n $('#enemy2').append('<img id = \"obi-wan2\" src=\"assets/images/obi-wan-kenobi.png\" width=150px height=150px><br>');\n $('#enemy2').append(obiPower);\n\n $('#yourEnemy').append('<div id =\"enemy3\"></div>');\n $('#enemy3').append('<div>Darth Vader</div>');\n $('#enemy3').append('<img id = \"darth2\" src=\"assets/images/darth-vader.png\" width=150px height=150px><br>');\n $('#enemy3').append(darthPower);\n\n\n $('#yourEnemy').append('<div id =\"enemy4\"></div>');\n $('#enemy4').append('<div>Kylo Ren</div>');\n $('#enemy4').append('<img id = \"kylo2\" src=\"assets/images/kylo-ren.png\" width=150px height=150px><br>');\n $('#enemy4').append(kyloPower); \n\n\n } /* end if luke */\n\n\n if (yourFighter=='obi-wan') {\n\n $('#yourEnemy').append('<div id =\"enemy1\"></div>');\n $('#enemy1').append('<div>Luke Skywalker</div>');\n $('#enemy1').append('<img id = \"luke2\" src=\"assets/images/luke-skywalker.png\" width=150px height=150px><br>');\n $('#enemy1').append(lukePower);\n\n \n $('#yourEnemy').append('<div id =\"enemy3\"></div>');\n $('#enemy3').append('<div>Darth Vader</div>');\n $('#enemy3').append('<img id = \"darth2\" src=\"assets/images/darth-vader.png\" width=150px height=150px><br>');\n $('#enemy3').append(darthPower);\n\n $('#yourEnemy').append('<div id =\"enemy4\"></div>');\n $('#enemy4').append('<div>Kylo Ren</div>');\n $('#enemy4').append('<img id = \"kylo2\" src=\"assets/images/kylo-ren.png\" width=150px height=150px><br>');\n $('#enemy4').append(kyloPower);\n\n\n } /* end if obi-wan */\n\n if (yourFighter=='darth') {\n\n $('#yourEnemy').append('<div id =\"enemy1\"></div>');\n $('#enemy1').append('<div>Luke Skywalker</div>');\n $('#enemy1').append('<img id = \"luke2\" src=\"assets/images/luke-skywalker.png\" width=150px height=150px><br>');\n $('#enemy1').append(lukePower);\n\n $('#yourEnemy').append('<div id =\"enemy2\"></div>');\n $('#enemy2').append('<div>Obi-Wan Kenobi</div>');\n $('#enemy2').append('<img id = \"obi-wan2\" src=\"assets/images/obi-wan-kenobi.png\" width=150px height=150px><br>');\n $('#enemy2').append(obiPower);\n\n $('#yourEnemy').append('<div id =\"enemy4\"></div>');\n $('#enemy4').append('<div>Kylo Ren</div>');\n $('#enemy4').append('<img id = \"kylo2\" src=\"assets/images/kylo-ren.png\" width=150px height=150px><br>');\n $('#enemy4').append(kyloPower);\n\n } /* end if darth */\n\n if (yourFighter=='kylo') {\n\n $('#yourEnemy').append('<div id =\"enemy1\"></div>');\n $('#enemy1').append('<div>Luke Skywalker</div>');\n $('#enemy1').append('<img id = \"luke2\" src=\"assets/images/luke-skywalker.png\" width=150px height=150px><br>');\n $('#enemy1').append(lukePower);\n\n $('#yourEnemy').append('<div id =\"enemy2\"></div>');\n $('#enemy2').append('<div>Obi-Wan Kenobi</div>');\n $('#enemy2').append('<img id = \"obi-wan2\" src=\"assets/images/obi-wan-kenobi.png\" width=150px height=150px><br>');\n $('#enemy2').append(obiPower);\n\n $('#yourEnemy').append('<div id =\"enemy3\"></div>');\n $('#enemy3').append('<div>Darth Vader</div>');\n $('#enemy3').append('<img id = \"darth2\" src=\"assets/images/darth-vader.png\" width=150px height=150px><br>');\n $('#enemy3').append(darthPower);\n \n\n } /* end if kylo */\n\n $(\"#luke2\").on(\"click\", function(){\n if (!yourEnemy) {\n yourEnemy='luke';\n $('#enemy1').replaceWith('');\n enemyPower=8;\n $('#defender').after('<div id =\"enemyFighter\"></div>');\n $('#enemyFighter').append('<div>Luke Skywalker</div>');\n $('#enemyFighter').append('<img src=\"assets/images/luke-skywalker.png\" width=150px height=150px><br>');\n $('#enemyFighter').append('<div id=\"lukePower\"></div>');\n $('#lukePower').html(lukePower);\n attack();\n } /* end if (yourEnemy ==\"\") */\n \n }) /* end luke2 (enemy) click */\n\n $(\"#obi-wan2\").on(\"click\", function(){\n if (!yourEnemy) {\n yourEnemy='obi-wan';\n $('#enemy2').replaceWith('');\n enemyPower=12;\n $('#defender').after('<div id =\"enemyFighter\"></div>');\n $('#enemyFighter').append('<div>Obi-Wan Kenobi</div>');\n $('#enemyFighter').append('<img src=\"assets/images/obi-wan-kenobi.png\" width=150px height=150px><br>');\n $('#enemyFighter').append('<div id=\"obiPower\"></div>');\n $('#obiPower').html(obiPower);\n attack();\n } /* end if (yourEnemy ==\"\") */\n }) /* end obi-wan2 (enemy) click */\n\n $(\"#darth2\").on(\"click\", function(){\n if (!yourEnemy) {\n yourEnemy='darth';\n $('#enemy3').replaceWith('');\n enemyPower=25;\n $('#defender').after('<div id =\"enemyFighter\"></div>');\n $('#enemyFighter').append('<div>Darth Vader</div>');\n $('#enemyFighter').append('<img src=\"assets/images/darth-vader.png\" width=150px height=150px><br>');\n $('#enemyFighter').append('<div id=\"darthPower\"></div>');\n $('#darthPower').html(darthPower);\n attack();\n } /* end if (yourEnemy ==\"\") */\n \n }) /* end darth2 (enemy) click */\n\n $(\"#kylo2\").on(\"click\", function(){\n if (!yourEnemy) {\n yourEnemy='kylo';\n $('#enemy4').replaceWith('');\n enemyPower=20;\n $('#defender').after('<div id =\"enemyFighter\"></div>');\n $('#enemyFighter').append('<div>Kylo Ren</div>');\n $('#enemyFighter').append('<img src=\"assets/images/kylo-ren.png\" width=150px height=150px><br>');\n $('#enemyFighter').append('<div id=\"kyloPower\"></div>');\n $('#kyloPower').html(kyloPower);\n attack();\n } /* end if (yourEnemy ==\"\") */\n }) /* end obi-wan2 (enemy) click */\n\n\n\n\n}", "function loadEnemies() {\n //create enemies\n enemyShipList = GameLogic.buildEnemyListByLevel(currentLevel, browserWidth, browserHeight);\n //create bosses\n bossList = GameLogic.getBossListByLevel(currentLevel, browserWidth, browserHeight);\n //alert user if difficulty has increased\n GameLogic.notifyDifficulty(currentLevel);\n}", "function afterLevel(x) {\n if (x) {\n levelReached.firstChild.data = \"Level \"+level+\", \"+((Settings.night)?\"night \":\"day \")+Math.ceil(level/2);\n if (level==1) svgDocument.getElementById(\"controls\").setAttributeNS(null, \"visibility\", \"visible\")\n levelReached.setAttributeNS(null, \"visibility\", \"visible\")\n playSound('gotBonus');\n window.setTimeout(\"afterLevel(0)\", 2000);\n } else { // a bit a lot of reseting there, but there were sometimes occuring really strange errors on several timers\n levelReached.setAttributeNS(null, \"visibility\", \"hidden\");\n if (level==1) svgDocument.getElementById(\"controls\").setAttributeNS(null, \"visibility\", \"hidden\")\n for (var i = enemies.length-1; i >= 0; i--) {\n enemies[i].resetTimers();\n enemies[i].alive = 0;\n }\n while (activeElements.hasChildNodes()) activeElements.removeChild(activeElements.firstChild);\n while (enemyShots.hasChildNodes()) enemyShots.removeChild(enemyShots.firstChild);\n while (eThumbs.hasChildNodes()) eThumbs.removeChild(eThumbs.firstChild);\n enemies = new Array();\n destroyedCount = 0;\n window.setTimeout(\"generateEnemy()\", 1000);\n }\n}", "function updateHealthbar() {\n let redPos = redBar.components.position;\n redPos.width = (health - currHealth) / health * redPos.height * 4;\n\n let greenPos = greenBar.components.position;\n greenPos.width = greenPos.height * 4 - redPos.width;\n }", "function parseHealthBarAnimate() {\n hbReady = true;\n healthDif = oldHealth - currentHealth;\n if (healthDif != 0) {\n intervalVar = setInterval(oldHealthCtr, 50);\n }\n}", "function updateEnemyStats() {\n\t\t$(\"#enemyHealth\").html(\"HP: \" + enemyPicked.health + \"<br />Attack: \" + enemyPicked.attack);\n\t\t$(\"#enemyName\").html(enemyPicked.display);\n\t}", "function maxHealthUpdate() {\r\n hbIncrement = hbWidth/maxHealth; \r\n}", "function subtractHealth() {\n fighterObj.health = fighterObj.health - enemyObj.counterAttack;\n enemyObj.health = enemyObj.health - fighterObj.attackNew;\n fighterObj.attackNew = fighterObj.attackNew + fighterObj.attack;\n\n\n\n\n\n if (fighterObj.health <= 0) {\n $(\".info-pop-up-text\").text(enemyObj.name + \" killed you!\");\n $(\"#resetLoose\").css(\"display\", \"block\");\n $(\".info-pop-up\").css(\"display\", \"flex\");\n\n\n }\n\n if (enemyObj.health <= 0) {\n $(\".enemy-display\").empty();\n $(\".info-pop-up-text\").text(enemyObj.name + \" is dead! Pick your next enemy!\");\n $(\".info-pop-up\").css(\"display\", \"flex\");\n $(\".resetWin\").css(\"display\", \"none\");\n setTimeout(function () {\n $(\".info-pop-up\").css(\"display\", \"none\");\n\n }, 2500);\n\n $(\".enemyDisplay\").empty();\n enemyChosen = false;\n defeatedFighters.push(enemyObj);\n }\n\n if (defeatedFighters.length == 3) {\n $(\".info-pop-up-text\").css(\"color\", \"red\");\n $(\".ultimate-win\").css(\"display\", \"flex\");\n $(\".info-pop-up\").css(\"display\", \"none\");\n $(\".ultimate-win-text\").text(\" You are the supreme winner\");\n $(\".resetWin\").css(\"display\", \"flex\");\n\n }\n }", "function update() {\r\n const name = $(\r\n \"#wrapper > div.contents > div.cnt-raid > div.cnt-raid-stage > div.prt-targeting-area > div.prt-stage-area > a.btn-targeting.enemy-1.invisible > div.enemy-info > div.name\"\r\n );\r\n const percent = $(\"#enemy-hp0\");\r\n if (name.text() != \"\" && $(\"#list-content\").children().length == 0) {\r\n console.log($(\"#title\"));\r\n $(\"#title\").append(\"Ultimate Bahamut\");\r\n }\r\n if (\r\n parseInt(percent.text()) <= triggers[curr_trigger].percent + 5 &&\r\n !done &&\r\n percent.text() != \"0\"\r\n ) {\r\n const warning_text = $(\r\n \"#wrapper > div.contents > div.cnt-raid > div.cnt-raid-stage > div.prt-targeting-area\"\r\n );\r\n if (curr_trigger < triggers.length - 1) {\r\n console.log(curr_trigger);\r\n if (parseInt(percent.text()) >= triggers[curr_trigger + 1].percent) {\r\n console.log(\"ABOUT TO WARN\");\r\n // if its not the last one check if in between triggers\r\n $(\r\n '<p class=\"lead\" style = \"font-family:\"Roboto\";color:red;margin-left:150px\" id = \"warning-text\">INCOMING TRIGGER</p>'\r\n )\r\n .appendTo(warning_text)\r\n .fadeOut(8000);\r\n }\r\n curr_trigger++;\r\n } else {\r\n $(\r\n '<p class=\"lead\" style = \"font-family:\"Roboto;color:red;margin-left:150px\" id = \"warning-text\">INCOMING TRIGGER</p>'\r\n )\r\n .appendTo(warning_text)\r\n .fadeOut(8000);\r\n done = true;\r\n }\r\n }\r\n }", "_drawHealthBar() {\n const { x, y, width, height } = this.config;\n this._bar = this.scene.add.rectangle( x, y, width, height,\n this.config.barColor );\n this._bar.setOrigin( 0, 0 );\n }", "function maxHealthUpdate() {\n hbIncrement = hbWidth/maxHealth; \n}", "function animateBars() {\n\n\tuserRegisteredAmount();\n\tAmountofAdv();\n\t\n\tuserProgressBar();\n\tretailerProgressBar();\n\tadsProgressBar();\n\t\n}", "function maxHealthBoost(tempHealth) {\n maxHealth += tempHealth; \n currentHealth = maxHealth;\n maxHealthUpdate();\n parseHealthBarAnimate();\n}", "update() {\r\n for (let enemy of allEnemies) {\r\n\r\n if (this.y === enemy.y && (enemy.x + enemy.step / 4 > this.x &&\r\n enemy.x < this.x + this.step / 4)) {\r\n this.reset();\r\n }\r\n\r\n if (this.y === 120) {\r\n console.log(\"Hi\");\r\n this.reset();\r\n\r\n };\r\n //Matthew Crawford's arcade game walkthrough was used to get a basic start on collision and enemy rendering\r\n\r\n //Shows when the player wins after level 3 has been reached\r\n\r\n if (this.y === 17) {\r\n this.reset();\r\n level++;\r\n if (level > 3) {\r\n $('h3').css(\"display\", \"block\").append('You have Won!');\r\n setTimeout(Result, 999);\r\n level = 1;\r\n }\r\n document.getElementById(\"myspan\").innerHTML = level;\r\n }\r\n }\r\n\r\n }", "function healthCheck() {\n for (var i = 0; i < partyMemberArray.length; i++) {\n if (partyMemberArray[i].hp < 1) {\n partyMemberArray[i].KO = true;\n partyMemberArray[i].hp = 0;\n if (fighter.KO) {\n $(\"#playerCharacter1\").animate({\n opacity: '0.5',\n });\n }\n if (whiteMage.KO) {\n $(\"#playerCharacter2\").animate({\n opacity: '0.5',\n });\n }\n if (blackMage.KO) {\n $(\"#playerCharacter3\").animate({\n opacity: '0.5',\n });\n }\n }\n }\n}", "function fightEnemy() {\r\n\tcurrHpPerc = Math.floor((currentHp / playerDetails.hp) * 100);\r\n\tget(\"player-hp\").style.width = currHpPerc + \"%\";\r\n\tlogArray = [ ]; //wipe log array\r\n\tstartCombat();\r\n}" ]
[ "0.65949917", "0.64337116", "0.63488334", "0.633253", "0.6284872", "0.6261083", "0.62480927", "0.6132932", "0.60952646", "0.6084168", "0.6084016", "0.6065441", "0.60620546", "0.60593873", "0.6047584", "0.60468805", "0.60406053", "0.6039369", "0.6026554", "0.6007479", "0.5988085", "0.5985451", "0.5948756", "0.5929044", "0.5911377", "0.5877917", "0.58520615", "0.5845085", "0.58210254", "0.57888025" ]
0.702743
0
updateEnemyBars: ========================================= updatePlayerBars: this function updates the health and attack bars of the player
function updatePlayerBars (fighterClass, fighterHealthClass, fighterAttackClass) { var healthPercent; var attackPercent; healthPercent = ((fighterClass.health * 100) / fighterClass.healthMax); attackPercent = ((fighterClass.attack * 100) / fighterClass.attackMax); console.log("player health percent: " + healthPercent); console.log("player attack percent: " + attackPercent); $ ("." + fighterHealthClass).css("width",healthPercent + "%"); $ ("." + fighterAttackClass).css("width",attackPercent + "%"); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function updateEnemyBars (fighterClass, fighterHealthClass, fighterCounterClass) {\n\tvar healthPercent;\n\tvar counterPercent;\n\n\thealthPercent = ((fighterClass.health * 100) / fighterClass.healthMax);\n\n\tcounterPercent = ((fighterClass.counter * 100) / fighterClass.counterMax);\n\n\tconsole.log(\"enemy health percent: \" + healthPercent);\n\tconsole.log(\"enemy counter percent: \" + counterPercent);\n\t\n\t//these commands update the bars in the character\n\t$ (\".\" + fighterHealthClass).css(\"width\",healthPercent + \"%\");\n\t$ (\".\" + fighterCounterClass).css(\"width\",counterPercent + \"%\");\n\n}", "update(){\n this.graphics.clear();\n for(let bar of this.healthBars){\n if(!bar.visible){\n continue;\n }\n bar.updatePos();\n bar.outerWidth = bar.barWidth * (bar.track.health/100);\n this.draw(bar);\n }\n for(let bar of this.progressBars){\n if(bar.track.state === \"closed\"){\n bar.visible = true;\n }\n else{\n bar.visible = false;\n }\n if(bar.visible){\n bar.updatePos();\n bar.outerWidth = bar.barWidth * (bar.track.tapCount/bar.track.maxTap);\n this.draw(bar);\n }\n }\n }", "function updateHealthbar() {\n let redPos = redBar.components.position;\n redPos.width = (health - currHealth) / health * redPos.height * 4;\n\n let greenPos = greenBar.components.position;\n greenPos.width = greenPos.height * 4 - redPos.width;\n }", "function worldUpdate() {\r\n\t$('#distance').html(prettify(Game.world.distance));\r\n\t$('#zone').html(Game.zone);\r\n\r\n\t//enemy\r\n\t$('#enemyHealth').html(prettify(Game.enemy.health));\r\n\r\n\tvar enemyHealthBar = document.getElementById(\"enemyHealthBar\");\r\n\tvar hp = (Game.enemy.health / Game.enemy.totalhealth) * 100;\r\n\tenemyHealthBar.style.width = hp + '%';\r\n\r\n\tif (Game.enemy.health >= Game.enemy.totalhealth) Game.enemy.health = Game.enemy.totalhealth;\r\n\r\n\tif (Game.enemy.health <= 0) {\r\n\t\tenemyHealthBar.style.width = '0%';\r\n\t\tendFight();\r\n\t}\r\n}", "function updateSinglePlayerHealthBar(currTurn){\n\n var HEALTH_BAR_X = GAME_WIDTH + 10;\n var HEALTH_BAR_Y = 100;\n var HEALTH_BAR_HEIGHT = 20;\n //Calculate the width of the bar as a percentage of the player's current health\n var healthBarWidth = calcHealthBarWidth(currTurn, statScreen.SinglePlayer.PlayerIndex);\n //redraw the health bar\n singleGraphics.beginFill(HEALTH_BAR_COLOR);\n statScreen.SinglePlayer.HealthBar.Bar = singleGraphics.drawRect(\n HEALTH_BAR_X, \n HEALTH_BAR_Y, \n healthBarWidth, \n HEALTH_BAR_HEIGHT);\n singleGraphics.endFill();\n}", "function updateGUIStatusBar(nameOfBar, points, maxPoints, direction) {\n // check, if optional direction parameter is valid.\n if (!direction || !(direction >= 0 && direction < 4)) direction = 0;\n\n // get the bar and update it\n let statusBar = Engine.GetGUIObjectByName(nameOfBar);\n if (!statusBar) return;\n\n let healthSize = statusBar.size;\n let value = 100 * Math.max(0, Math.min(1, points / maxPoints));\n\n // inverse bar\n if (direction == 2 || direction == 3) value = 100 - value;\n\n if (direction == 0) healthSize.rright = value;\n else if (direction == 1) healthSize.rbottom = value;\n else if (direction == 2) healthSize.rleft = value;\n else if (direction == 3) healthSize.rtop = value;\n\n statusBar.size = healthSize;\n}", "function movePlayerBar(){\n\t\t\tvar position=texture.getPosition();\n\t\t\tvar y1=position.y;\n\t\t\tvar y2=position.y+size.height;\n\t\t\tvar y1_aux=(dir!=1?y1+speed:y1-speed);\n\t\t\tvar y2_aux=(dir!=1?y2+speed:y2-speed);\n\t\t\t\n\t\t\t//Comprobamos que la bola no rebasaria los limites verticales\n\t\t\tif(y1_aux<y_min || y2_aux>y_max){\n\t\t\t\ty1_aux=(y1_aux<y_min)?y_min:y_max-size.height;\n\t\t\t\tstopMove(dir);\n\t\t\t}\n\t\t\ttexture.move(x,y1_aux);\n\t\t\ttexture.fireOnChangeEvent();\n\t\t}", "function updateHealth() {\n // Reduce player health, constrain to reasonable range\n playerHealth = constrain(playerHealth - 0.8,0,playerMaxHealth);\n // Check if the player is dead\n if (playerHealth === 0) {\n // If so, the game is over\n gameOver = true;\n }\n}", "function updateHealth() {\n // Reduce player health, constrain to reasonable range\n playerHealth = constrain(playerHealth - 0.5,0,playerMaxHealth);\n // Check if the player is dead\n if (playerHealth === 0) {\n // If so, the game is over\n gameOver = true;\n gameOverSong.play();\n }\n}", "function updateHealth() {\n // Reduce player health\n playerHealth = playerHealth - 0.5;\n // Constrain the result to a sensible range\n playerHealth = constrain(playerHealth, 0, playerMaxHealth);\n\n //When the shift button is pressed, player's health\n //will decrease faster, especially without the constrain\n if (keyIsDown(SHIFT)) {\n playerHealth = playerHealth - 2;\n }\n //When the sift button is released, the health\n //will decrease at it's normal rate\n else {\n playerHealth = playerHealth - 0.5;\n playerHealth = constrain(playerHealth, 0, playerMaxHealth);\n }\n\n // Check if the player is dead (0 health)\n if (playerHealth === 0) {\n // If so, the game is over\n gameOver = true;\n }\n}", "function updateHealth() {\n // Reduce player health based on width of the display\n playerHealth = playerHealth - width / 3000;\n // Constrain the result to a sensible range\n playerHealth = constrain(playerHealth, 0, playerMaxHealth);\n // Check if the player is dead (0 health)\n if (playerHealth === 0) {\n // If so, reset health, and update how many lives the player has left\n playerHealth = playerMaxHealth;\n updatePlayerLives();\n }\n}", "function updateHealth() {\n // Reduce player health, constrain to reasonable range\n //playerHealth = constrain(playerHealth - 0.5,0,playerMaxHealth);\n // Check if the player is dead\n if (playerHealth === 0) {\n // If so, the game is over\n gameOver = true;\n }\n}", "function update() {\r\n game.physics.arcade.collide(player, layer);\r\n game.physics.arcade.collide(NPC, layer);\r\n game.physics.arcade.collide(layer2, cageKey);\r\n game.physics.arcade.collide(layer, cage);\r\n\r\n collision();\r\n\r\n movement();\r\n\r\n cropRect.width = healthBar.width * (player.health / healthOld);\r\n\r\n healthBar.updateCrop();\r\n\r\n healthOld = player.health;\r\n }", "function setEnemyHealth(kills) {\n var base = 100;\n var mod = rollTwoDie(kills, 10) * 3;\n return base + mod;\n }", "function drawHealthBar() {\n maxHealthUpdate();\n healthBar.clear();\n \n hbX = userIntThis.cameras.main.scrollX + userIntThis.sys.game.config.width*0.73;\n hbY = userIntThis.cameras.main.scrollY + userIntThis.sys.game.config.height*0.0225;\n healthBar.lineStyle(1,0x000000,1);\n healthBar.fillStyle(0xff0000,1);\n healthBar.strokeRect(hbX,hbY,hbWidth,hbHeight);\n \n if (currentHealth > 0) {\n healthBar.fillRect(hbX,hbY,hbIncrement*oldHealth,hbHeight);\n }\n}", "function updateAll() {\n //var marioElem = document.getElementById(\"mario\");\n if (damage > 0) {\n player.health -= damage;\n var fireElem = document.getElementById(\"fire\").attributes\n //document.getElementById(\"mario\").classlist.add(\"vader\")\n }\n\n //totalDamage();\n damage = 0;\n update.innerText = player.health.toString();\n playerName.innerText = player.name;\n displayHits.innerText = player.hits.toString();\n\n if (player.health < 30) {\n document.getElementById(\"player-panel\").classList.add(\"panel-danger\");\n healthBarElem.classList.add('progress-bar-danger');\n } else if (player.health > 30 && player.health < 60) {\n document.getElementById(\"player-panel\").classList.remove(\"panel-danger\");\n document.getElementById(\"player-panel\").classList.add(\"panel-warning\");\n healthBarElem.classList.remove('progress-bar-danger');\n healthBarElem.classList.add('progress-bar-warning');\n } else {\n document.getElementById(\"player-panel\").classList.remove(\"panel-danger\");\n document.getElementById(\"player-panel\").classList.remove(\"panel-warning\");\n document.getElementById(\"player-panel\").classList.add(\"panel-default\");\n healthBarElem.classList.remove('progress-bar-danger');\n healthBarElem.classList.remove('progress-bar-warning');\n healthBarElem.classList.add('progress-bar-success');\n\n\n }\n if (player.health <= 0) {\n termElem.src = 'img/boom-sm.png';\n player.health = 0;\n updateHealthBar();\n // disabled buttons come back after timeout\n disableButtons();\n debugger\n winnerElem.innerText = player.name + \" Wins! The Terminator was destroyed in \" + player.hits + \" hits!\";\n winnerElem.style.color = \"green\";\n clearInterval(interval);\n }\n updateHealthBar();\n\n}", "function updateBars(bars,n,colorScale, chart)\n {\n\n setScale(chart);\n\n var yScale = d3.scale.linear()\n .range([0, chartHeight]) \n .domain([0, scaleMax]); \n\n bars.attr(\"x\", function(d, i)\n {\n return (i * (chartInnerWidth / csvData.length)) + leftPadding;\n })\n .attr(\"height\", function(d)\n {\n return yScale(parseFloat(d[expressed]));\n })\n .attr(\"y\", function(d)\n {\n return (chartHeight - yScale(parseFloat(d[expressed]))) + topBottomPadding;\n })\n .style(\"fill\", function(d)\n {\n return colorScale(d[expressed]);\n })\n .on(\"mouseover\", function(d)\n {\n var nm = d.geography.split(' ');\n val = d[expressed];\n highlight(nm[0], val);\n })\n .on(\"mouseout\", function(d)\n {\n var nm = d.geography.split(' ');\n dehighlight(nm[0])\n })\n .on(\"mousemove\", moveLabel);\n }", "function UpdateHealthBar() {\n\tthis.healthBar.transform.localScale =\n\t\t\tnew Vector3(this.currentHealth / this.maxHealth, 1 ,1);\n\t//set the bg bar to be in the same location as the health bar\n\tthis.healthBarBg.transform.position = this.healthBar.transform.position;\n}", "function playerHeal(tempHealth){\n currentHealth += tempHealth;\n if (currentHealth > maxHealth){\n currentHealth = maxHealth;\n }\n parseHealthBarAnimate();\n}", "function updateTopMenuValues(playerHealth, bossHealth){\n\n // Update the Healthbar values \n setHealthbarValues(playerHealth, bossHealth);\n\n // Update the value of the satisfaction bar based on its current value\n setSatisfactionBarValue();\n\n // Set the text message\n generateMessage();\n}", "function updateBarsFrom(owner){\n owner.cards.forEach(function(card){\n //barra de vida\n startedTweens++;\n card.lifeBar.lbl.text = card.life + '/' + card.maxLife;\n var newWidth = card.lifeBar.fullWidth * card.life / card.maxLife;\n var lifeTween = self.game.add.tween(card.lifeBar.mask).to({x: card.lifeBar.mask.originalX + (card.lifeBar.fullWidth - newWidth) * (card.lifeBar.anchor.x == 0 ? -1 : 1)}, 400, Phaser.Easing.Linear.None, true, 0);\n lifeTween.onComplete.add(onTweenCompleted);\n //barra de defensa\n startedTweens++;\n card.defenseBar.lbl.text = card.defense + '/' + card.maxDefense;\n var newWidth = card.defenseBar.fullWidth * card.defense / card.maxDefense;\n var defenseTween = self.game.add.tween(card.defenseBar.mask).to({x: card.defenseBar.mask.originalX + (card.defenseBar.fullWidth - newWidth) * (card.defenseBar.anchor.x == 0 ? -1 : 1)}, 400, Phaser.Easing.Linear.None, true, 0);\n defenseTween.onComplete.add(onTweenCompleted);\n //barra de magia\n startedTweens++;\n card.magicBar.lbl.text = card.magic + '/' + card.maxMagic;\n var newWidth = card.magicBar.fullWidth * card.magic / card.maxMagic;\n var magicTween = self.game.add.tween(card.magicBar.mask).to({x: card.magicBar.mask.originalX + (card.magicBar.fullWidth - newWidth) * (card.magicBar.anchor.x == 0 ? -1 : 1)}, 400, Phaser.Easing.Linear.None, true, 0);\n magicTween.onComplete.add(onTweenCompleted);\n\n if(card.magic == card.maxMagic){\n card.magicFrame.visible = true;\n }\n else {\n card.magicFrame.visible = false;\n }\n\n if(card.life == 0) {\n card.alpha = 0.5;\n } else {\n card.alpha = 1;\n }\n });\n }", "function drawHealthBar() {\r\n healthBar.clear();\r\n hbX = userIntThis.cameras.main.scrollX + userIntThis.sys.game.config.width*0.775;\r\n hbY = userIntThis.cameras.main.scrollY + userIntThis.sys.game.config.height*0.0225;\r\n healthBar.lineStyle(1,0x000000,1);\r\n healthBar.fillStyle(0xff0000,1);\r\n healthBar.strokeRect(hbX,hbY,hbWidth,hbHeight);\r\n \r\n if (currentHealth > 0) {\r\n healthBar.fillRect(hbX,hbY,hbIncrement*oldHealth,hbHeight);\r\n }\r\n}", "update(deltaTime){\n this.healthBar.scale.x = this.health / this.maxHealth;\n if(this.health <= 0){\n this.die();\n }\n \n if(this.health > this.maxHealth){\n this.health = this.maxHealth;\n }\n }", "function updateHealth() {\n // Reduce harry health, constrain to reasonable range\n harryHealth = constrain(harryHealth - 0.5,0,harryMaxHealth);\n // Check if the harry is dead\n if (harryHealth === 0) {\n // If so, the game is over\n gameOver = true;\n }\n}", "function syncHealthBar() {\n if (health <= 0) {\n hpBar.frame = hpBar.animations.frameTotal - 1;\n } else {\n let percentGone = (HP - health) / HP;\n let nextFrame = parseInt(hpBar.animations.frameTotal * percentGone);\n if (nextFrame >= 0 && nextFrame < hpBar.animations.frameTotal) {\n hpBar.frame = nextFrame;\n }\n }\n}", "function animateBars() {\n\n\tuserRegisteredAmount();\n\tAmountofAdv();\n\t\n\tuserProgressBar();\n\tretailerProgressBar();\n\tadsProgressBar();\n\t\n}", "function barUpdate() {\n\t// changes the color of the background depending on the percent\n\tif (Math.abs(($bar.width()/$statusBar.width()) - percentCorrect) == 100 ) {\n\t\tcolorChange(2000);\n\t\t}\n\telse if (Math.abs(($bar.width()/$statusBar.width()) - percentCorrect) >= 30) {\n\t\tcolorChange(1500);\n\t\t}\n\telse {\n\t\tcolorChange(900);\n\t};\n}", "update() {\r\n this.moveEnemy();\r\n // player human collision\r\n for (let activePlayer of gGameEngine.players) {\r\n if (this.detectPlayerCollision({\r\n x: activePlayer.bmp.x,\r\n y: activePlayer.bmp.y\r\n })) {\r\n activePlayer.alive = false;\r\n activePlayer.animate('dead');\r\n }\r\n }\r\n // playerAI collision\r\n if (this.detectPlayerAICollision({\r\n x: gGameEngine.playerAI.bmp.x,\r\n y: gGameEngine.playerAI.bmp.y\r\n })) {\r\n gGameEngine.playerAI.alive = false;\r\n gGameEngine.playerAI.animate('dead');\r\n }\r\n }", "function updateEnemyStats() {\n\t\t$(\"#enemyHealth\").html(\"HP: \" + enemyPicked.health + \"<br />Attack: \" + enemyPicked.attack);\n\t\t$(\"#enemyName\").html(enemyPicked.display);\n\t}", "function cypherOnUpdateBarAttributes(updateData) {\r\n const update = [\"bar1\", \"bar2\", \"bar3\"].some(b => {\r\n let bar = this.data[b];\r\n if (!bar)\r\n return false;\r\n\r\n return bar.attribute && hasProperty(updateData, \"data.\"+bar.attribute);\r\n });\r\n\r\n if (update)\r\n this.object.drawBars();\r\n }" ]
[ "0.7557436", "0.6387888", "0.61090773", "0.5945519", "0.5880743", "0.57560307", "0.5620557", "0.5547833", "0.55426073", "0.55151325", "0.55141973", "0.54880273", "0.54811215", "0.544954", "0.54156166", "0.5412472", "0.54001355", "0.53820807", "0.53725255", "0.5326626", "0.5306964", "0.5272357", "0.52396345", "0.5236196", "0.52109355", "0.519179", "0.51899695", "0.51814735", "0.51679534", "0.5158614" ]
0.66340005
1
fight: ================================================ duelMove: this function moves the clicked enemy into the duel zone
function duelMove (fighterClass) { var duelistLocation; attackTime = true; document.querySelector(".message").innerHTML = "Click on Attack to fight. With each attack your character will get stronger." //who villain: this section of code figures out who the chosen duelist is if ($ (fighterClass).attr("id") === "jar") { currentVillain = jar; console.log("current villain is: "); console.log(currentVillain); }; if ($ (fighterClass).attr("id") === "obi") { currentVillain = obi; console.log("current villain is: "); console.log(currentVillain); }; if ($ (fighterClass).attr("id") === "anakin") { currentVillain = anakin; console.log("current villain is: "); console.log(currentVillain); }; if ($ (fighterClass).attr("id") === "mace") { currentVillain = mace; console.log("current villain is: "); console.log(currentVillain); }; if ($ (fighterClass).attr("id") === "jango") { currentVillain = jango; console.log("current villain is: "); console.log(currentVillain); }; //who villain: ======================================= //update remaining: this section of code removes the chosen fighter from the array of fighters remaining for (var w = 0; w < fightersRemaining.length; w++) { if (fightersRemaining[w].id === $ (fighterClass).attr("id")) { fightersRemaining.splice(w,1); console.log("fighters remaining: "); console.log(fightersRemaining); } } //update remaining:=================================== //duel zone: this section of code moves the duelist to the duel zone console.log(fighterClass); $ (".duelArea").append(fighterClass); //duel zone:============================================== //move villains: this section of code will move all the villains where they're supposed to be if (fightersRemaining.length >= 1) { $ ("#enemy1").append(fightersRemaining[0].location); } if (fightersRemaining.length >= 2) { $ ("#enemy2").append(fightersRemaining[1].location); } if (fightersRemaining.length >= 3) { $ ("#enemy3").append(fightersRemaining[2].location); } if (fightersRemaining.length >= 4) { $ ("#enemy4").append(fightersRemaining[3].location); } //move villains: ====================================== }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function moveChar(){\n\t\t$(\".thumbnail\").on(\"click\", function(){\n\t\t\tvar parent = $(this).parent();\n\t\t\tvar selectedChar = $(this).attr(\"id\");\n\n\t\t\t//Moves the enemy character to the appropriate DIV, and adds the corresponding object to combatObj;\n\t\t\tif (lightSide && darkSide == undefined){\n\t\t\t\t$(this).appendTo(\"#darkSideDiv\");\n\t\t\t\tdarkSide = charObj[selectedChar];\n\t\t\t\t$(parent).remove();\n\t\t\t}\n\t\t\t//Moves the user's character to the appropriate DIV, and adds the corresponding object to combatObj;\n\t\t\tif (lightSide == undefined){\n\t\t\t\t$(this).appendTo(\"#lightSideDiv\");\n\t\t\t\tlightSide = charObj[selectedChar];\n\t\t\t\t$(parent).remove();\n\t\t\t\t$(\"#fightButton\").append(\"<button type='button' class='btn btn-danger btn-block'>Fight!</button>\");\n\t\t\t\treturn alertBox(\"Select an enemy to fight.\")\n\t\t\t}\n\t\t\t\n\t\t});\n\t}", "function moveEnemy(){\n var id = $(this).attr(\"data-name\");\n for (let i = 0; i < characters.length; i++){\n if(characters[i].name === id){\n enemy = characters[i];\n }\n }\n $(this).appendTo(\".enemy-area\");\n $(\".character\").off();\n $(this).removeClass(\"character\");\n $(this).addClass(\"enemy\");\n enemySelect = true;\n}", "function move() {\n var id = $(this).attr(\"data-name\");\n for (let i = 0; i < characters.length; i++){\n if(characters[i].name === id){\n player = characters[i];\n }\n }\n $(this).appendTo(\".player-area\");\n $(\".character\").off();\n $(this).removeClass(\"character\");\n $(this).addClass(\"player\");\n $(\".character\").css(\"background-color\", \"red\");\n $(\".character\").on(\"click\", moveEnemy);\n $(\".attack\").css(\"visibility\", \"visible\");\n $(\"h2\").text(\"Choose Your Enemy!\")\n}", "function moveCharForFight(name) {\n fighter2 = NAMES.indexOf(name);\n // put up the attack button\n var r = $('<input/>').attr({\n type: \"button\",\n id: \"attackBtn\",\n value: 'Attack!',\n style: \"display: flex; margin-top: 100px; margin-left: 20px; height: 40px;\",\n });\n $(\".picture-your\").append(r);\n makeRow(1, -1, fighter2, \"black\");\n $(warriors[fighter1].htmlId1).css(\"border-color\", \"white\"); // makeRow makes it black, so undo that\n $(warriors[fighter2].className2).remove(); // remove from the still to attack row\n if (defeated >= 2) { // none left to fight\n $(\"#defenders\").remove();\n } else {\n $(\"#defenders\").html(\"<span>Still Out There</span>\");\n $(\"#defenders\").visible(); // just in case\n }\n }", "function FightLocal() {\n \n this.go=function(command,data) {\n var hit;\n var parsed={};\n\n view2.pMessage.put(\"\");\n view2.eMessage.put(\"\");\n \n // player's strike\n if( global.isActive(\"A\") && command==\"cell\" && data ) {\n parsed = view2.parseGridId(data);\n if ( parsed.prefix != \"e\" ) return;\n hit=enemy.respond([parsed.row,parsed.col]);\n //alert(\">\"+hit);\n player.reflect(hit);\n view2.pStat.showStrikesHits(model.playerStat.strikes,model.playerStat.hits);\n displayResponce( hit, [parsed.row,parsed.col], view2.eBoard, model.enemyBasin, view2.eStat, model.enemyStat, view2.pMessage );// enemy.display\n if ( arbiter.checkout(hit) ) return;\n // fall-through\n }\n \n // LocalScript's strike\n if ( global.isActive(\"B\") && command==\"enemyStrike\" && data.length==2 ) {\n hit=player.respond(data);\n enemy.reflect(hit);\n view2.eStat.showStrikesHits(model.enemyStat.strikes,model.enemyStat.hits);\n displayResponce( hit, data, view2.pBoard, model.playerBasin, view2.pStat, model.playerStat, view2.eMessage );//player.display\n if (hit==\"n\")\n console.log( \"Enemy repeats itself on \"+data+\" that is \"+model.playerBasin.get(data[0],data[1]) );// this is not to happen\n if ( arbiter.checkout(hit) ) return;\n // fall-through\n }\n \n if ( global.getStage()!=\"finish\" ) { // some command out of order\n console.log( \"Out of order: player=\"+global.getActive()+\" command=\"+command+\" data=\"+data+\" stage=\"+global.getStage() );\n return;\n }\n // fall-through\n\n // fight finished\n displayElement(\"finish\");\n global.setState(\"finish\");\n if ( global.isActive(\"A\") ) {\n global.setWinner(\"A\");\n view2.pMessage.put('<span class=\"'+\"win\"+'\">YOU HAVE WON !');\n }\n else {\n global.setWinner(\"B\");\n view2.eMessage.put('<span class=\"'+\"lose\"+'\">ENEMY HAS WON !');\n }\n return; \n };\n}", "function fight(posNew, posOld) {\n\n if (posNew.x === posOld.x \n && posNew.y <= posOld.y + 1 && posNew.y >= posOld.y - 1 ||posNew.y === posOld.y \n && posNew.x <= posOld.x + 1 && posNew.x >= posOld.x - 1) {\n move = false;\n hover = false;\n fightingArea(); // Info.js (70) When the players fight, the board game is hidden\n scores = 0;\n fightPlayerOne(); // Info.js (110)\n fightPlayerTwo(); // Info.js (126)\n }\n}", "function attack(move, onlyenemy){\n\tvar encmov = moves[randomelement(encpok.moves)];\n\tvar moveused = moves[move];\n\tif(onlyenemy){\n\t\tencmov.use(encpok, monout, true);\n\t\tif(!checkforfaint(monout, encpok)) backtonormal();\n\t} else {\n\t\toutput(0, \"\");\n\t\tif(monout.spd >= encpok.spd){\n\t\t\tmoveused.use(monout, encpok, false);\n\t\t\tif(!checkforfaint(encpok, monout, true)){ \n\t\t\t\toutput(0, \"<br>\", 1);\n\t\t\t\tencmov.use(encpok, monout, true);\n\t\t\t\tif(!checkforfaint(monout, encpok, false)) backtonormal();\n\t\t\t}\n\t\t} else {\n\t\t\tencmov.use(encpok, monout, true);\n\t\t\tif(!checkforfaint(monout, encpok, false)){\n\t\t\t\toutput(0, \"<br>\", 1);\n\t\t\t\tmoveused.use(monout, encpok, false);\n\t\t\t\tif(!checkforfaint(encpok, monout, true)) backtonormal();\n\t\t\t}\n\t\t}\n\t}\n\tupdate(true);\n}", "enemyMovementFlow() {\n squares[this.enemyIndex].classList.remove('enemy')\n if (this.enemyShouldMove && !this.enemyHit) {\n // console.log('should move right')\n this.enemyIndex ++ // move right\n this.enemyMoveCount ++\n } else if (!this.enemyShouldMove && !this.enemyHit) {\n // console.log('should move left')\n this.enemyIndex -- // move left\n this.enemyMoveCount --\n }\n if (!this.enemyHit) squares[this.enemyIndex].classList.add('enemy')\n // console.log(this.enemyMoveCount)\n setTimeout(() => {\n this.dropLine()\n }, 250)\n }", "function TravelMove(nextMove) {\n\tif(gridArr[nextMove].encounter == \"combat\"){ // switch from travel to combat\n\t\tOPC.encounter = \"combat\";\n\t\tcombatRounds = 0;\n\t}\n\telse if(gridArr[nextMove].encounter == \"trap\") {\n\t\tOPC.encounter = \"trap\";\n\t}\n\tOPC.lastPos = OPC.currentPos;\n\tOPC.currentPos = nextMove;\n\tUpdateTileMap();\n}", "move(r, c, dr, dc) {\n this.remove(r+dr, c+dc); // kill middle soldier\n this.remove(r, c); // soldier hop start\n this.place(r+2*dr, c+2*dc); // soldier hop end\n }", "function movePlayer() {\n if (turn) {\n var playerX = selectedCharacter.moveAnimation.x;\n playerY = selectedCharacter.moveAnimation.y;\n } else {\n var playerX = enemyUnit.x;\n playerY = enemyUnit.y;\n selectedCharacter = enemyUnit;\n }\n \n destX = path[0][0],\n destY = path[0][1];\n\n\n var coefficientX = 0;\n var coefficientY = 0;\n\n\n if (playerX < destX && playerY < destY) {\n coefficientX = 1.0;\n coefficientY = 1.0;\n } else if (playerX > destX && playerY > destY) {\n coefficientX = -1.0;\n coefficientY = -1.0;\n } else if (playerX < destX && playerY > destY) {\n coefficientX = 1.0;\n coefficientY = -1.0;\n } else if (playerX > destX && playerY < destY) {\n coefficientX = -1.0;\n coefficientY = 1.0;\n } \n\n\n\n var stepX = coefficientX * MOVEMENT_STEP;\n var stepY = coefficientY * MOVEMENT_STEP / 2;\n\n\n selectedCharacter.moveAnimation.x += stepX;\n selectedCharacter.moveAnimation.y += stepY;\n selectedCharacter.hp_bar.x += stepX;\n selectedCharacter.hp_bar.y += stepY;\n\n draggable.x = draggable.x - stepX;\n draggable.y = draggable.y - stepY;\n for (var i = 0; i < selectedCharacter.buffs.length; i++) {\n selectedCharacter.buffs[i][3].x += stepX;\n selectedCharacter.buffs[i][3].y += stepY;\n }\n\n\n if ((playerX === destX) && (playerY === destY)) {\n\n path.splice(0,1);\n if (path.length == 0) {\n console.log(\"finish move\");\n\n selectedCharacter.x = selectedCharacter.moveAnimation.x;\n selectedCharacter.y = selectedCharacter.moveAnimation.y;\n draggable.removeChild(selectedCharacter.moveAnimation);\n draggable.addChild(selectedCharacter);\n \n addPointerNearPlayerAttack();\n //unit = movingUnit;\n //draggable.removeChild(selectedCharacter.moveAnimation);\n //draggable.addChild(selectedCharacter);\n sortIndices(selectedCharacter);\n movingPlayer = false;\n if (undo){\n selectedCharacter.canMove = 1;\n undo = false;\n } else {\n selectedCharacter.canMove = 0;\n }\n \n\n showActionMenuNextToPlayer(selectedCharacter);\n }\n }\n\n sortIndices(selectedCharacter);\n //stage.update();\n changed = true;\n}", "function turnBased() {\n newBoard.highlightMoves(newBoard.activePlayer.character);\n $('.col').click((event) => {\n if ($(event.target).hasClass('highlight')) {\n let currentPlayerCell = Number($(`#${newBoard.activePlayer.character}`).attr('cell'));\n newBoard.movePlayer(newBoard.activePlayer.character);\n $(event.target).addClass('player').attr('id', `${newBoard.activePlayer.character}`);\n let newPlayerCell = Number($(`#${newBoard.activePlayer.character}`).attr('cell'));\n collectWeapon(newBoard.activePlayer, currentPlayerCell, newPlayerCell);\n newBoard.switchPlayer();\n if (fightCondition(newPlayerCell) === true) {\n alert('The fight starts now');\n startFight(newBoard.activePlayer, newBoard.passivePlayer);\n }\n else {\n newBoard.highlightMoves(newBoard.activePlayer.character);\n }\n }\n })\n }", "function move(){\nctx.clearRect(0, 0, canvas.width, canvas.height);\nb++;\nly++;\nif (ly== 700) ly=0;\nif (b >= 700-obrad){\nobstacle(a2,b2-obrad);\nb2++;\nif (b > 700+obrad) {b2=0;b=obrad;}\n}\ndraw();\n}", "attack(enemy) {\n let d = dist(this.x, this.y, enemy.x, enemy.y);\n // if within range, no target acquired, not dead, and the enemy is alive\n // TARGET THE ENEMY\n if (d < 300 && this.targetId < 0 && !this.dead && !enemy.dead) {\n this.targetId = enemy.uniqueId;\n this.obtainedTarget = true;\n }\n let dx = enemy.x - this.x;\n let dy = enemy.y - this.y;\n let angle = atan2(dy, dx);\n\n if (this.targetId === enemy.uniqueId) {\n // get closer to the enemy\n if (d >= 150) {\n this.x += this.speed * cos(angle);\n this.y += this.speed * sin(angle);\n // also keep a distance from the enemy\n } else {\n this.x -= this.speed * cos(angle);\n this.y -= this.speed * sin(angle);\n }\n // if within range, FIRE\n if (d < 200 && !this.bulletFired && !this.dead) {\n this.bullet = new Bullet(this.x, this.y, enemy.x, enemy.y, this.playerId, this.uniqueId);\n this.bulletFired = true;\n this.attacking = true;\n Fire.play();\n } else {\n this.attacking = false;\n }\n if (this.bulletFired && !this.dead) {\n this.attacking = true;\n // if the enemy is not attacking, it will fight back\n if (!enemy.attacking) {\n enemy.targetId = this.uniqueId;\n }\n this.bullet.moveTo(enemy);\n if (this.bullet.dead) {\n this.bulletFired = false;\n this.bullet = null;\n }\n }\n if (enemy.dead) {\n // if the targeted enemy is tank / square XL\n // if the tank gets destroyed and this unit is close to it\n // the explosion kills this unit\n if (enemy.uniqueId === 100 && enemy.uniqueId === this.targetId && d < 100){\n this.health -= enemy.damage;\n }\n this.targetId = -1;\n this.obtainedTarget = false;\n this.attacking = false;\n }\n }\n // variation to the movement\n // Set velocity via noise()\n this.vx = map(noise(this.tx), 0, 1, -0.05, 0.05);\n this.vy = map(noise(this.ty), 0, 1, -0.05, 0.05);\n // Update position\n this.x += this.vx;\n this.y += this.vy;\n // Update time properties\n this.tx += 0.0001;\n this.ty += 0.0001;\n\n this.handleWrapping();\n }", "function act(){\n\t\tif(!lunging){\n\t\t\tturnToHero(.8);\n\t\t\tif(distanceToHero() < 4){\n\t\t\t\tmoveFromHero(1.5);\n\t\t\t\tif(angleToHero() < 2 || angleToHero() > 358) lunge(.5, .3, .8, 6, .5, .3);\n\t\t\t}else{\n\t\t\t\tmove(2);\n\t\t\t}\n\t\t}\n\t}", "function enemiesDrop(dir)\r\n{\r\n if(dir == \"l\"){\r\n for(var i = 0; i < 10; i++)\r\n {\r\n if(i == leftMostCol)\r\n {\r\n enemiesR3[i].x = 1;\r\n enemiesR2[i].x = 1;\r\n enemiesR1[i].x = 1;\r\n enemiesR3[i].direction = enemiesR3[i].direction * -1;\r\n enemiesR2[i].direction = enemiesR2[i].direction * -1;\r\n enemiesR1[i].direction = enemiesR1[i].direction * -1;\r\n enemiesR3[i].y += (enemyHeight/2);\r\n enemiesR2[i].y += (enemyHeight/2);\r\n enemiesR1[i].y += (enemyHeight/2);\r\n }\r\n else if(i > leftMostCol){\r\n enemiesR3[i].x = enemiesR3[i-1].x+54;\r\n enemiesR3[i].y += (enemyHeight/2);\r\n enemiesR3[i].direction = enemiesR3[i].direction * -1;\r\n enemiesR2[i].x = enemiesR2[i-1].x+54;\r\n enemiesR2[i].y += (enemyHeight/2);\r\n enemiesR2[i].direction = enemiesR2[i].direction * -1;\r\n enemiesR1[i].x = enemiesR1[i-1].x+54;\r\n enemiesR1[i].y += (enemyHeight/2);\r\n enemiesR1[i].direction = enemiesR1[i].direction * -1;\r\n }\r\n }\r\n }\r\n else if(dir == \"r\"){\r\n for(var i = 9; i >= 0; i--)\r\n {\r\n if(i == rightMostCol)\r\n {\r\n enemiesR3[i].x = canvas.width-enemyWidth-1;\r\n enemiesR2[i].x = canvas.width-enemyWidth-1;\r\n enemiesR1[i].x = canvas.width-enemyWidth-1;\r\n enemiesR3[i].direction = enemiesR3[i].direction * -1;\r\n enemiesR2[i].direction = enemiesR2[i].direction * -1;\r\n enemiesR1[i].direction = enemiesR1[i].direction * -1;\r\n enemiesR3[i].y += (enemyHeight/2);\r\n enemiesR2[i].y += (enemyHeight/2);\r\n enemiesR1[i].y += (enemyHeight/2);\r\n }\r\n else if(i < rightMostCol){\r\n enemiesR3[i].x = enemiesR3[i+1].x-54;\r\n enemiesR3[i].y += (enemyHeight/2);\r\n enemiesR3[i].direction = enemiesR3[i].direction * -1;\r\n enemiesR2[i].x = enemiesR2[i+1].x-54;\r\n enemiesR2[i].y += (enemyHeight/2);\r\n enemiesR2[i].direction = enemiesR2[i].direction * -1;\r\n enemiesR1[i].x = enemiesR1[i+1].x-54;\r\n enemiesR1[i].y += (enemyHeight/2);\r\n enemiesR1[i].direction = enemiesR1[i].direction * -1;\r\n }\r\n }\r\n }\r\n}", "function routeFrame(enemyFighter) {\n\n return 'flying';\n }", "drawSelf(theCanvas, user, theGame) {\n theCanvas.clearEnemy(this);\n this.playerInVicinity(user);\n if (!this.playerIsSeen) {\n let enemyDirection = this.direction % 4;\n if (enemyDirection === 0 && (this.id === 0 || this.id === 4)) {\n if (!theCanvas.detectLine(this.x, this.y + 35)) {\n this.y += 5;\n this.currDirection = \"S\";\n } else {\n if (this.id === 0) {\n this.direction += 2;\n } else {\n this.direction++;\n }\n }\n let currIndexOfEnemy = this.indexOfImage % 4;\n let img = this.enemyMovingDown[currIndexOfEnemy];\n theCanvas.drawEnemy(img, this);\n } else if (enemyDirection === 1 && (this.id === 5 || this.id === 4)) {\n if (!theCanvas.detectLine(this.x + 35, this.y)) {\n this.x += 5;\n this.currDirection = \"E\";\n } else {\n if (this.id === 5) {\n this.direction += 2;\n } else {\n this.direction++;\n }\n }\n let currIndexOfEnemy = this.indexOfImage % 4;\n let img = this.enemyMovingRight[currIndexOfEnemy];\n theCanvas.drawEnemy(img, this);\n } else if (enemyDirection === 2 && (this.id === 0 || this.id === 4)) {\n if (!theCanvas.detectLine(this.x, this.y - 15)) {\n this.y -= 5;\n this.currDirection = \"N\";\n } else {\n if (this.id === 0) {\n this.direction += 2;\n } else {\n this.direction++;\n }\n }\n let currIndexOfEnemy = this.indexOfImage % 4;\n let img = this.enemyMovingUp[currIndexOfEnemy];\n theCanvas.drawEnemy(img, this);\n } else if (enemyDirection === 3 && (this.id === 5 || this.id === 4)) {\n if (!theCanvas.detectLine(this.x - 15, this.y)) {\n this.x -= 5;\n this.currDirection = \"W\";\n } else {\n if (this.id === 5) {\n this.direction += 2;\n } else {\n this.direction++;\n }\n }\n let currIndexOfEnemy = this.indexOfImage % 4;\n let img = this.enemyMovingLeft[currIndexOfEnemy];\n theCanvas.drawEnemy(img, this);\n }\n\n //changes behavior of enemy once player is in distance\n } else {\n if (user.x === this.x || user.x === this.x + 5 || user.x === this.x - 5) {\n if(user.y > this.y){\n this.currDirection = 'S';\n let currIndexOfEnemy = this.indexOfImage % 4;\n let img = this.enemyMovingDown[currIndexOfEnemy];\n theCanvas.drawEnemy(img, this);\n }else{\n let currIndexOfEnemy = this.indexOfImage % 4;\n let img = this.enemyMovingUp[currIndexOfEnemy];\n theCanvas.drawEnemy(img, this);\n this.currDirection = 'N'\n }\n this.attackPlayer(user, theGame);\n \n } else if(user.y === this.y || user.y === this.y + 5 || user.y === this.y - 5){\n if(user.x > this.x){\n this.currDirection = 'E';\n let currIndexOfEnemy = this.indexOfImage % 4;\n let img = this.enemyMovingRight[currIndexOfEnemy];\n theCanvas.drawEnemy(img, this);\n }else{\n let currIndexOfEnemy = this.indexOfImage % 4;\n let img = this.enemyMovingLeft[currIndexOfEnemy];\n theCanvas.drawEnemy(img, this);\n this.currDirection = 'W'\n }\n this.attackPlayer(user, theGame);\n }else{\n if (user.x > this.x && !theCanvas.detectLine(this.x + 35, this.y) && !theCanvas.detectLine(this.x, this.y + 40) && !theCanvas.detectLine(this.x, this.y + 45)) {\n this.x += 5;\n this.currDirection = \"E\";\n let currIndexOfEnemy = this.indexOfImage % 4;\n let img = this.enemyMovingRight[currIndexOfEnemy];\n theCanvas.drawEnemy(img, this);\n } else if (\n user.y < this.y &&\n !theCanvas.detectLine(this.x, this.y - 15)\n ) {\n this.y -= 5;\n this.currDirection = \"N\";\n let currIndexOfEnemy = this.indexOfImage % 4;\n let img = this.enemyMovingUp[currIndexOfEnemy];\n theCanvas.drawEnemy(img, this);\n }else if (\n user.x < this.x &&\n !theCanvas.detectLine(this.x - 15, this.y)\n ) {\n this.x -= 5;\n this.currDirection = \"W\";\n let currIndexOfEnemy = this.indexOfImage % 4;\n let img = this.enemyMovingLeft[currIndexOfEnemy];\n theCanvas.drawEnemy(img, this);\n } else if (\n user.y > this.y &&\n !theCanvas.detectLine(this.x, this.y + 35) && !theCanvas.detectLine(this.x, this.y + 40) && !theCanvas.detectLine(this.x, this.y + 45)\n ) {\n this.y += 5;\n this.currDirection = \"S\";\n let currIndexOfEnemy = this.indexOfImage % 4;\n let img = this.enemyMovingDown[currIndexOfEnemy];\n theCanvas.drawEnemy(img, this);\n }else{\n let currIndexOfEnemy = this.indexOfImage % 4;\n let img = this.enemyMovingDown[currIndexOfEnemy];\n theCanvas.drawEnemy(img, this);\n }\n }\n }\n }", "function fighter(player) {\n var y = player.y - 1;\n\tvar x = player.x - 1;\n\n for(var idx = y; idx < y+3; idx++) {\n \tfor(var idx2 = x; idx2 < x+3; idx2++) {\n if(idx === player.y && idx2 === player.x) {\n } else {\n var area = mapArrays[idx][idx2];\n if(area.terrainType === \"monster\") {\n if(area.monsterType === \"super golem\") {\n currentEnemy = superGolem;\n } else if(area.monsterType === \"dragon\") {\n currentEnemy = dragon;\n } else if(area.monsterType === \"random\") {\n currentEnemy = getMonster();\n }\n combatStarter(currentEnemy);\n if(area.monsterType === \"dragon\") {\n userCommands = [\"attack\", \"potion\", \"equip\"];\n commandDisplayer();\n }\n placedMonsterCombat = true;\n currentEnemyY = area.y;\n currentEnemyX = area.x;\n break;\n }\n }\n }\n }\n}", "function canvasTurn() {\n /* Ensuring that object do not go over the canvas */\n if (this.x >= (canvas.width - this.width)) { //transporting enemy from the right side of canvas to left side.\n this.x = 0;\n }\n if (this.y >= (canvas.height - this.height)) { //transporting enemy from the botton side of canvas to up side.\n this.y = 0;\n }\n if (this.x < 0) { //transporting enemy from the left side of canvas to right side.\n this.x = canvas.width - this.width;\n }\n if (this.y < 0) { //transporting enemy from the up side of canvas to botton side.\n this.y = canvas.height - this.height;\n }\n}", "function enterFightMode(enemyType) {\n inFight = true;\n // Generate a random Pokemon\n var pokemonIndex = 0;\n if (enemyType === \"wild\") {\n pokemonIndex = (Math.round(Math.random() * 3) + 3);\n } else if (enemyType === \"trainer\") {\n pokemonIndex = Math.round(Math.random() * 6);\n }\n ranPokemon = instantiatePokemon(pokemonIndex, enemyType);\n\n // Load stats + images for both pokemon into DOM\n $(\"#enemy-pokemon-name\").text(ranPokemon.name.toUpperCase());\n $(\"#enemy-pokemon-health-bar\").css(\"width\", \"8.1vw\");\n $(\"#enemy-pokemon-level\").text(ranPokemon.level);\n $(\"#enemy-pokemon-image\").hide();\n $(\"#enemy-pokemon-image\").attr(\"src\", ranPokemon.frontImage);\n $(\"#friendly-pokemon-name\").text(myPokemon.name.toUpperCase());\n var healthBarWidth = 8.1 * (myPokemon.currentHP / myPokemon.maxHP);\n $(\"#friendly-pokemon-health-bar\").css(\"width\", healthBarWidth + \"vw\");\n $(\"#friendly-pokemon-level\").text(myPokemon.level);\n $(\"#friendly-pokemon-health-num\").html(myPokemon.currentHP + \" &nbsp; &nbsp; &nbsp; &nbsp;\" + myPokemon.maxHP);\n $(\"#friendly-pokemon-image\").attr(\"src\", myPokemon.backImage);\n $(\"#friendly-pokemon-image\").show();\n var attackMoveDivs = $(\"#move-options-text\").children();\n attackMoveDivs.each(function(index) {\n if (!isNaN(myPokemon.moves[index])) {\n this.innerText = pokeMoves[myPokemon.moves[index]].name;\n this.setAttribute(\"data-value\", myPokemon.moves[index]); \n } else {\n this.innerText = \"--\";\n this.setAttribute(\"data-value\", \"invalid\");\n }\n });\n if (enemyTrainer) {\n $(\"#battle-text\").text(\"Poketrainer \" + enemyTrainer.name + \" sent out \" + ranPokemon.name + \"!\");\n } else {\n $(\"#battle-text\").text(\"A wild \" + ranPokemon.name + \" appears!\");\n }\n $(\"#battle-options\").hide();\n $(\"#battle-text\").show();\n $(\"#battle-screen\").show(\"pulsate\");\n $(\"#enemy-pokemon-image\").show(\"slide\", { direction : \"right\", distance : 300 }, 800);\n $(document).off();\n $(document).on(\"keydown\", function(event) {\n // Keep arrows from moving page around\n if(event.keyCode && [32, 37, 38, 39, 40].indexOf(event.keyCode) > -1) {\n event.preventDefault();\n }\n\n if (event.keyCode === 65 || event.keyCode === 75) {\n turn = 0;\n takeTurn();\n }\n });\n $(document).on(\"click\", function(event) {\n if (event.target.id === \"a-button\" || event.target.id === \"b-button\") {\n turn = 0;\n takeTurn();\n }\n })\n}", "function attack(move, attacker, defender) {\n if (currentOppPokemon.fainted == true) {\n return;\n }\n if (move.pp <= 0) {\n rollText(\"battle_text\", \"Not enough PP!\", 25);\n return;\n }\n move.pp -= 1;\n document.getElementById('buttonsBattle').style['display'] = 'none';\n damage = Math.round(((move.damage * ((Math.random() * 15) + 85) / 100)) * stab(attacker, move));\n\n let multiplier = typeChart[getKeyByValue(ElementalTypes, move.type)][defender.type];\n damage *= multiplier;\n\n switch (multiplier) {\n case 0:\n rollText(\"battle_text\", `${attacker.name} used ${move.name}! It had no effect.`, 25);\n break;\n case 0.5:\n rollText(\"battle_text\", `${attacker.name} used ${move.name}! It's not very effective.`, 25);\n notEffectiveSound.play();\n break;\n case 2:\n rollText(\"battle_text\", `${attacker.name} used ${move.name}! It's super effective!`, 25);\n superEffectiveSound.play();\n break;\n default:\n rollText(\"battle_text\", `${attacker.name} used ${move.name}!`, 25);\n damageSound.play();\n break;\n }\n\n defender.hp -= Math.ceil(damage);\n updateHealth(defender);\n}", "function choose_enemy() {\n\tvar plane_left_margin = 0;\n\tvar hp;\n\tif(distance % 700 == 0) {\n\t\tplane_left_margin = Math.floor(Math.random() * (751 - enemy_planes[5].width));\n\t\thp = create_enemy(plane_left_margin, enemy_planes, 5);\n\t\tvar rows = 0;\n\t\tclearInterval(hp.times);\n\t\thp.times = setInterval(function(){\n\t\t\tif (!pause_clicked) {\n\t\t\t\trows++;\n\t\t\t\tspecial_bullet(hp, 1);\n\t\t\t\tif (rows > 1 || dead || (hp.HP == 0) ){\n\t\t\t\t\tclearInterval(hp.times);\n\t\t\t\t}\n\t\t\t}\n\t\t},500);\n\t} \n\telse if(distance % 300 == 0) {\n\t\tplane_left_margin = Math.floor(Math.random() * (751 - enemy_planes[4].width));\n\t\tcreate_enemy(plane_left_margin, enemy_planes, 4)\n\t} \n\telse if(distance % 200 == 0) {\n\t\tplane_left_margin = Math.floor(Math.random() * (751 - enemy_planes[3].width));\n\t\tcreate_enemy(plane_left_margin, enemy_planes, 3)\n\t}\n\telse if(distance % 150 == 0) {\n\t\tplane_left_margin = Math.floor(Math.random() * (751 - enemy_planes[2].width));\n\t\tcreate_enemy(plane_left_margin, enemy_planes, 2)\n\t} \n\telse if(distance % 75 == 0) {\n\t\tplane_left_margin = Math.floor(Math.random() * (751 - enemy_planes[1].width));\n\t\tcreate_enemy(plane_left_margin, enemy_planes, 1)\n\t} \n\telse if(distance % 30 == 0) {\n\t\tplane_left_margin = Math.floor(Math.random() * (751 - enemy_planes[0].width));\n\t\tcreate_enemy(plane_left_margin, enemy_planes, 0);\n\t}\n}", "function monsterAttack(){\n\tif(rleft + mleft === 56){\n\t\t$('#monster').addClass('attack');\n\t}\n\tif(rleft + mleft === 76){\n\t\t$('#monster').css('left', 10+\"em\");\n\t\txleft = 10;\n\t}\n\tif(rleft + mleft === 96){\n\t\t$('#monster').css('left', 20+\"em\");\n\t\txleft = 20;\n\t}\n\tif(rleft + mleft === 116){\n\t\t$('#monster').css('left', 30+\"em\");\n\t\txleft = 30;\n\t}\n}", "function fighting() {\n enemies.forEach((enemy, index_enemy) => {\n allies.forEach((ally, index_ally) => {\n if (enemies[index_enemy].combat && allies[index_ally].combat == true) {\n enemies[index_enemy].hp = enemies[index_enemy].hp - allies[index_ally].damage / 60;\n allies[index_ally].hp = allies[index_ally].hp - enemies[index_enemy].damage / 60;\n hit_sound.volume = 0.5;\n hit_sound.play();\n //console.log(\"Enemy HP: \" + enemies[index_enemy].hp);\n //console.log(\"Ally HP: \" + allies[index_ally].hp);\n document.querySelector(\"img.wizard[data-id='\" + enemy.id + \"']\").src = \"zombie_action2.png\";\n document.querySelector(\"img.ally[data-id='\" + ally.id + \"']\").src = \"adventurer_action2.png\";\n }\n if (enemies[index_enemy].hp < 0) {\n enemies.splice(index_enemy, 1);\n death_sound.volume = 0.2;\n death_sound.play();\n points = points + 30;\n updatePoints();\n document.querySelector(\"img.wizard[data-id='\" + enemy.id + \"']\").remove();\n }\n if (allies[index_ally].hp < 0) {\n allies.splice(index_ally, 1);\n death_sound.volume = 0.2;\n death_sound.play();\n document.querySelector(\"img.ally[data-id='\" + ally.id + \"']\").remove();\n }\n\n });\n });\n // Laat ze doorlopen als combat voorbij is\n allies.forEach((ally, index_ally) => {\n allies[index_ally].combat = false;\n });\n enemies.forEach((enemy, index_enemy) => {\n enemies[index_enemy].combat = false;\n });\n\n}", "move() {\r\n this.y = this.y + Enemy.v;\r\n }", "function Attack()\n{\n\tvar speedTowardsPlayer = moveSpeed;\n\t\n\t//if enemy is on the right side of the player move left\n\tif(player.transform.position.x < transform.position.x)\n\t{\n\t\tfacingLeft = true;\n\t\tspeedTowardsPlayer = -speedTowardsPlayer;\n\t\trenderer.material.mainTexture = mainTextures[curFrame]; // Get the current animation frame\n\t}\n\t//if enemy is on the left side of the player move right\n\telse\n\t{\n\t\tfacingLeft = false;\n\t\trenderer.material.mainTexture = altTextures[curFrame]; // Get the current animation frame\n\t}\n\t\t\n\trigidbody.velocity = Vector3(speedTowardsPlayer, rigidbody.velocity.y, 0); // Move to the left\n}", "function move() {\n\t\tmovePiece(this);\n\t}", "function chooseEnemy() {\n\n \n $(this).detach().appendTo(\"#their-fighter-row\");\n\n $(this).addClass(\"currentEnemy\")\n\n $(document).off(\"click\", \"#combat-zone .enemy\", chooseEnemy);\n\n \n }", "dragonCatchPlayer(delta, hero){\n // subtract (= difference vector)\n\t\tlet dx = hero.x - this.x;\n\t\tlet dy = hero.y - this.y;\n\t\n\t\t// normalize (= direction vector)\n\t\t// (a direction vector has a length of 1)\n\t\tlet length = Math.sqrt(dx * dx + dy * dy);\n\t\tif (length) {\n\t\tdx /= length;\n\t\tdy /= length;\n\t\t}\n\t\t\n\t\tlet dX1 = this.x;\n\t\tlet dY1 = this.y;\n\t\n\t\t// move\n\t\t// delta is the elapsed time in seconds\n\t\t// SPEED is the speed in units per second (UPS)\n\t\tthis.x += dx * delta * this.speed;\n\t\tthis.y += dy * delta * this.speed;\n\t\n\t\t//Dragon movment \n\t\tif (dY1 > this.y) { // this holding up\n\t\t\tthis.frameY = 3;\n\t\t\tthis.moving = true;\n\t\t}\n\t\tif (dY1 < this.y) { // this holding down\n\t\t\tthis.frameY = 0;\n\t\t\tthis.moving = true;\n\t\t}\n\t\tif (dX1 > this.x) { // this holding left\n this.frameY = 1;\n\t\t\tthis.moving = true;\n\t\t}\n\t\tif (dX1 < this.X) { // this holding right\n\t\t\tthis.frameY = 2;\n\t\t\tthis.moving = true;\n\t\t}\n\n }" ]
[ "0.62309426", "0.6194085", "0.61904204", "0.61862403", "0.615828", "0.6148708", "0.61429715", "0.60981095", "0.6059894", "0.6038212", "0.6012762", "0.6006209", "0.5988625", "0.5966156", "0.59660256", "0.59634364", "0.5920754", "0.59007365", "0.5900642", "0.58951914", "0.58929515", "0.5889021", "0.58777803", "0.5873874", "0.5858228", "0.5855083", "0.58479947", "0.5846474", "0.584571", "0.5838429" ]
0.73192215
0
Function to display laps
function lap() { document.getElementById('lapText').innerHTML += `<p>${displayHours}:${displayMinutes}:${displaySeconds}:${displayMilliseconds}</p>`; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "displayLasers(){\n for(let i = 0; i < lasers.length; i++){\n let laser = lasers[i];\n laser.move();\n laser.display();\n laser.laserTouch();\n }\n }", "show() {\n strokeWeight(2);\n fill(224, 65, 65);\n rect(this.x, this.y, this.w, this.h);\n\n // if the used job rectangle covers the text with the lane number \n // redraw the same text over everythin \n if (this.x + this.w > 35) {\n strokeWeight(.5);\n fill(0);\n text(`Lane ${this.lane + 1}`, lanes[this.lane].x + (.06 * lanes[this.lane].w), lanes[this.lane].y + (.5 * lanes[this.lane].h) + 3);\n }\n\n\n // Display the amount of space that is remaining in the lane \n strokeWeight(.5);\n fill(0);\n text(`Space Remaining: ${lanes[this.lane].remaining}`, lanes[this.lane].x + (.75 * lanes[this.lane].w), lanes[this.lane].y + (.5 * lanes[this.lane].h) + 3);\n }", "show() {\n stroke(0);\n strokeWeight(this.stroke);\n noFill();\n rect(this.x, this.y, this.w, this.h);\n\n strokeWeight(1);\n textSize(12);\n text(`Lane: ${this.ID}`, this.x + (.06 * this.w), this.y + (.5 * this.h) + 3);\n\n // if no jobs are in the lane it displays the full length of the lane \n // otherwise each new job added updates the display to show the \n // amount of space remaining \n if (this.jobs.length == 0) {\n textSize(12);\n text(`Lane Length: ${lane_lens}`, this.x + (.75 * this.w), this.y + (.5 * this.h) + 3);\n }\n }", "displayLives() {\r\n console.log(`\\nLives left: ${this.lives}`);\r\n }", "function displayLapTimes(mins, secs, mils) {\n let html = `\n <div class=\"lap\">\n <span class=\"lap-minutes\">${mins}</span>:<span class=\"lap-seconds\">${secs}</span>:<span class=\"lap-miliseconds\">${mils}</span>\n </div>\n `;\n\n lapContainer.insertAdjacentHTML(\"beforeend\", html);\n}", "function renderLives(){\r\n lives.innerHTML = \"<p>Levens: \" + levens + \"</p>\";\r\n \r\n }", "drawLives(){\n\t\tfor (let i = 0; i<this.lives; i++){\n\t\t\tpush();\n\t\t\ttranslate(width-30 - 20*i, height-30);\n\t\t\tnoStroke();\n\t\t\tfill(255,0,0);\n\t\t\ttriangle(-10, 0, 10,0, 0, 14);\n\t\t\tarc(-5, 0, 10, 12, PI, TAU);\n\t\t\tarc(5, 0, 10, 12, PI, TAU);\n\t\t\tpop();\n\t\t}\n\t}", "function showLazers(){\n document.getElementById('lazers').innerHTML = \"\";\n for(var x = 0; x < lazers.length ; x++){\n document.getElementById('lazers').innerHTML += `<div class='lazer' style='left:${lazers[x].left}px; top:${lazers[x].top}px'></div>`;\n }\n}", "function drawLanes() {\r\n\tfill(80);\r\n\trect(0, 0, 5, height);\r\n\trect(55, 0, 5, height);\r\n\trect(110, 0, 5, height);\r\n\trect(165, 0, 5, height);\r\n\trect(220, 0, 5, height);\r\n}", "function stopwatchLap(event) {\r\n event.preventDefault();\r\n let printLapList = document.getElementById(\"lapList\");\r\n laps.push(formatTime(rawTime));\r\n lapList.innerHTML = \"\";\r\n for (var i = 0; i < laps.length; i++) {\r\n lapNumber = i + 1;\r\n nameList = \"<li>\" + \"Lap \"+ lapNumber + \" time is \" + laps[i] + \"</li>\";\r\n document.getElementById(\"lapList\").innerHTML += nameList;\r\n }\r\n}", "function drawLives(){\n for (i=0; i<lives; i++){\n graphics.drawImage(spaceship, 5+(i*35), 35, 25,25);\n }\n }", "function updateLPS(){\n\tdocument.getElementById('lps').innerHTML = 'LPS: ' + nf.format(lps);\n\tdocument.getElementById('followerLPS').innerHTML = followerLPS;\n\tdocument.getElementById('FansLPS').innerHTML = FansLPS;\n\tdocument.getElementById('paparazzisLPS').innerHTML = paparazzisLPS;\n\tdocument.getElementById('stalkersLPS').innerHTML = stalkersLPS;\n\tdocument.getElementById('lunaticsLPS').innerHTML = lunaticsLPS;\n\tdocument.getElementById('botLPS').innerHTML = botLPS;\n}", "function printBrickLayer(title , tiles){\r\n // String of whole output\r\n let output = ` ${title} <br>`;\r\n \r\n for (let y = 0; y < dimensions.height ; y++) {\r\n\r\n // String of output row\r\n let line = \"\";\r\n\r\n for (let x = 0; x < dimensions.width ; x++) {\r\n \r\n let brick = tiles[ x + (dimensions.width * y)];\r\n let outputTile = (brick > 9) ? brick.toString() : \"0\" + brick.toString();\r\n line += ` ${outputTile}`;\r\n }\r\n output += line + \"<br>\";\r\n } \r\n // DOM element\r\n let element = document.getElementById(\"output\");\r\n element.innerHTML += output + \"<br><br>\";\r\n}", "function drawLives(){\n let startX = game.width*.75;\n\n graphics.lineStyle(2, 0xffffff);\n points = [0,-12,-8,12,-6,10,6,10,8,12,0,-12];\n for(let i = 0; i < lives; i++){\n var x = startX+i*20;\n for(let j = 0; j < points.length; j+=2){\n if(j==0)\n graphics.moveTo(x+points[j],infoY+points[j+1]);\n else\n graphics.lineTo(x+points[j],infoY+points[j+1]);\n }\n }\n}", "function renderLives() {\n let index = 0,\n length = _lives.length,\n life;\n\n // Loop through the number of remaining lives stored in the _lives array, and\n // call the renderAt() method of each of the Life \"class\" instances contained\n // within, drawing the life on the game board at the appropriate position\n for (; index < length; index++) {\n life = _lives[index];\n\n life.renderAt(life.left, life.top);\n }\n }", "function drawLanes() {\n // make sure the canvas is the correct size and clear it\n lanes.resize(timelineController.width + margin.left + margin.right);\n lanes.ctx.clearRect(0, 0, lanes.canvas.width, lanes.canvas.height);\n\n lanes.ctx.strokeStyle = 'lightgray';\n lanes.ctx.textAlign = 'end';\n lanes.ctx.textBaseline = 'middle';\n lanes.ctx.font = '10px sans-serif';\n\n // draw lanes for each worker\n var laneHeight = 0.8 * y(1);\n for (var i = 0; i < laneDefs.length; i++) {\n var laneDef = laneDefs[i];\n var yPos = y(i + 0.5);\n var dy = 0;\n\n for (var pathIndex = 0; pathIndex < laneDef.length; pathIndex++) {\n var pathDef = laneDef[pathIndex];\n pathDef.scale.range([laneHeight, 0]);\n\n // draw labels right-aligned to the left of each lane\n if ('text' in pathDef) {\n lanes.ctx.fillStyle = pathDef.color;\n lanes.ctx.fillText(\n pathDef.text,\n margin.left - margin.right, yPos + dy,\n margin.left - 10);\n\n dy += 10;\n }\n }\n }\n }", "function drawLives () {\n ctx.font = '16px Arial';\n ctx.fillStyle = 'white';\n ctx.fillText ('Lives: ' + store.state.lives, canvas.width - 65, 20);\n}", "function executeDisplay(list_lats_longs){\n //Resets slideshow back to first screen\n slideIndex = 0;\n speedIndex = 0;\n playing = true;\n //get the speed limits\n var speedlims = getSpeedLimits(list_lats_longs);\n //make the slideshow with street views and speedlimtits\n makePreview(list_lats_longs, speedlims);\n}", "function drawPlayerLives() {\n imageMode(CENTER);\n noStroke();\n fill(livesColor, 255, 100);\n textSize(22);\n textAlign(RIGHT);\n text(\"LIVES:\", width / 2 - 100, height - 20);\n let livesX = width / 2 - 70;\n for (let i = 0; i < playerLives; i++) {\n image(playerImage, livesX, height - 20, 25, 25);\n livesX = livesX + 50;\n }\n //if the player has no more extra lives, turn text red\n if (playerLives < 2) {\n livesColor = 0;\n } else {\n livesColor = 120;\n }\n}", "function drawLives() {\n\t// count and display lives left\n\tctx.fillStyle = \"white\";\n\tctx.font = \"30px Arial\";\n\tctx.fillText(\"LIVES: \" + (lives), canvas.width-150, 525);\n}", "function addLap() {\n lapNumber++;\n var myLapDetails =\n \"<div class='lap'> <div class='laptimeTitle'> Lap\" +\n lapNumber +\n \"</div>\" +\n \"<div class='laptime'>\" +\n \"<span>\" +\n format(lapMinutes) +\n \"</span>\" +\n \":<span>\" +\n format(lapSeconds) +\n \"</span>\" +\n \":<span>\" +\n format(lapCentiseconds) +\n \"</span>\";\n \"</div>\" + \"</div>\";\n\n // \"<div>\" + \"<div>\" + \"Lap\" + lapNumber;\n // (\"</div>\");\n // \"<div>\" + \"<span>\" + format(lapMinutes) + \"</span>\";\n // \":<span>\" + format(lapSeconds) + \"</span>\";\n // \":<span>\" + format(lapCentiseconds) + \"</span>\";\n // (\"</div>\");\n // (\"</div>\");\n $(myLapDetails).prependTo(\"#laps\");\n }", "function addLap(){\n lapNumber++;\n var myLapDetails =\n '<div class=\"lap\">'+\n '<div class=\"laptimetitle\">'+\n 'Lap'+ lapNumber +\n '</div>'+\n '<div class=\"laptime\">'+\n '<span>'+ format(lapMin) +'</span>'+\n ':<span>'+ format(lapSec) +'</span>'+\n ':<span>'+ format(lapCentsec) +'</span>'+\n '</div>'+\n '</div>';\n $(myLapDetails).prependTo(\"#laps\");\n }", "function drawLamps() {\n\n let firstRow = \"QWERTYUIOP\"; // order of letters in the first row of lamps\n let secondRow = \"ASDFGHJKL\"; // order of letters in the second row of lamps\n let thirdRow = \"ZXCVBNM\"; // order of letters in the third row of lamps\n\n // draw first row\n for (let index = 0; index < firstRow.length; index++) {\n\n // draw lamp\n if (onLamp == firstRow[index]) {\n\n fill(lampOnColour[0], lampOnColour[1], lampOnColour[2]);\n\n } else {\n\n fill(lampOffColour[0], lampOffColour[1], lampOffColour[2]);\n\n }\n\n circle(width / 20 + index * width / 10, 180, 50);\n fill(0);\n textSize(32);\n text(firstRow[index], width / 20 + index * width / 10, 193);\n\n }\n\n // draw second row\n for (let index = 0; index < secondRow.length; index++) {\n\n // draw lamp\n if (onLamp == secondRow[index]) {\n\n fill(lampOnColour[0], lampOnColour[1], lampOnColour[2]);\n\n } else {\n\n fill(lampOffColour[0], lampOffColour[1], lampOffColour[2]);\n\n }\n\n circle(width / 10 + index * width / 10, 340, 50);\n fill(0);\n textSize(32);\n text(secondRow[index], width / 10 + index * width / 10, 353);\n\n }\n\n // draw third row\n for (let index = 0; index < thirdRow.length; index++) {\n\n // draw lamp\n if (onLamp == thirdRow[index]) {\n\n fill(lampOnColour[0], lampOnColour[1], lampOnColour[2]);\n\n } else {\n\n fill(lampOffColour[0], lampOffColour[1], lampOffColour[2]);\n\n }\n\n circle(width / 5 + index * width / 10, 500, 50);\n fill(0);\n textSize(32);\n text(thirdRow[index], width / 5 + index * width / 10, 513);\n\n }\n}", "function display(ll) {\n console.log(JSON.stringify(ll));\n}", "function drawLives() {\n ctx.font = \"16px Arial\";\n ctx.fillText(\"Lives: \"+lives, canvas.width-65, 20);\n }", "function stopwatchLap(){\n event.preventDefault()\n console.log('lap!')\n\n // console.log(stopwatchTime.innerHTML)\n // if the lap is clicked before starting the stopwatch or when the stopwatch\n // is reset do not display the laplist\n if (stopwatchTime.innerHTML == formatTime(0)){\n lapList.innerHTML = \"\"\n }\n else {\n laps.push(stopwatchTime.innerHTML) // adds the lap time to an array\n\n // displays the laps recorded in the lap array\n lapList.innerHTML = \"\" // clears the lap list to begin with\n for (i=0; i<laps.length; i++){\n var liLap = document.createElement(\"li\")\n liLap.innerHTML = laps[i]\n lapList.appendChild(liLap)\n }\n }\n}", "function displayLives(){\n document.getElementById('lives').innerHTML = 'Lives: '+ lives;\n}", "function addLap() {\n lapNumber++;\n var myLap = \n '<div class=\"lapre\">'+\n '<div class=\"laptimetitle\">'+\n 'LAP'+ lapNumber +\n '</div>'+\n '<div class=\"laptimes\">'+\n '<span>'+ format(lapMinutes) +'</span>'+\n ':<span>'+ format(lapSeconds) +'</span>'+\n ':<span>'+ format(lapMiliseconds) +'</span>'+\n '</div>'+\n\n '</div>';\n $(myLap).prependTo(\"#laprecord\");\n}", "function displayPunchLine() {\n\tpunchline.style.display = 'block';\n\tpunchline.classList.add('bubble');\n\tpunchline.innerHTML = jokeArray[0].punchline;\n\tpunchlineBtn.classList.add('hidden');\n}", "function lapHistory(lapsData) { \r\n\r\n let fastest = Math.min(...lapsData);\r\n let slowest = Math.max(...lapsData);\r\n\r\n lapTimesList.innerHTML = lapsData\r\n .map((lap) => {\r\n if (lap === fastest) {\r\n return (`<li class=\"fastest\">${formatTimer(lap)}</li>`)\r\n } else if (lap === slowest) {\r\n return (`<li class=\"slowest\">${formatTimer(lap)}</li>`)\r\n } else {\r\n return (`<li>${formatTimer(lap)}</li>`)\r\n } \r\n }).join(\"\")\r\n}" ]
[ "0.65363187", "0.64915174", "0.63877255", "0.63381916", "0.62199974", "0.6102788", "0.6068716", "0.594185", "0.5940676", "0.5936964", "0.58874375", "0.5881841", "0.58234876", "0.5788378", "0.5774092", "0.57665384", "0.57591915", "0.57575434", "0.5748277", "0.5740207", "0.57249177", "0.5677379", "0.56674576", "0.5657726", "0.5648851", "0.56448704", "0.5629211", "0.56210804", "0.5609274", "0.5601113" ]
0.66444856
0
input: filePath of excel file callback(records) records is array of arrays
function read_excel_file(filePath, callback){ excelParser.parse({ inFile: filePath, worksheet: 1, skipEmpty: false, },function(err, records){ if (err) console.error(err); typeof callback === 'function' && callback(records); }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function handleExFile(e) {\n document.getElementById('excel').blur();\n\n\tNAME_LIST = [];\n\tvar files = e.target.files, f = files[0];\n console.log(excel.files[0].name.split('.').pop());\n\n\tif(!excelTypeCheck(excel.files[0])) {\n \treturn;\n \t}\n\n\tvar reader = new FileReader();\n\treader.onload = function(e) {\n\t\tvar data = e.target.result;\n\t\tif(!rABS) data = new Uint8Array(data);\n\t\tvar workbook = XLSX.read(data, {type: rABS ? 'binary' : 'array'});\n\t\tNAME_LIST = readNames(workbook);\n\t\tconsole.log(NAME_LIST);\n\t\t\n\t\t/* DO SOMETHING WITH workbook HERE */\n\t};\n\tif(rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);\n}", "function getArrayFromXlsx(req, res, next) {\n\n var file = req.files.file;\n\n // Tên file\n var originalFilename = file.name;\n console.log(\"Ten file vua up: \" + originalFilename)\n // File type\n var fileType = file.type.split('/')[1];\n\n // File size\n var fileSize = file.size;\n // Đường dẫn lưu ảnh\n var pathUpload = __dirname + '/xlsx/' + originalFilename;\n\n // START READ XLSX DATA\n //doc du lieu tu xlsx dua ve object\n var workbook = XLSX.readFile(file.path);\n var sheet_name_list = workbook.SheetNames;\n var data = [];\n sheet_name_list.forEach(function (y) {\n var worksheet = workbook.Sheets[y];\n var headers = {};\n\n for (z in worksheet) {\n if (z[0] === '!') continue;\n //parse out the column, row, and value\n var tt = 0;\n for (var i = 0; i < z.length; i++) {\n if (!isNaN(z[i])) {\n tt = i;\n break;\n }\n }\n ;\n var col = z.substring(0, tt);\n var row = parseInt(z.substring(tt));\n var value = worksheet[z].v;\n\n //store header names\n if (row == 1 && value) {\n headers[col] = value;\n continue;\n }\n\n if (!data[row]) data[row] = {};\n data[row][headers[col]] = value;\n }\n\n //drop those first two rows which are empty\n data.shift();\n data.shift();\n });\n\n return next(data);\n}", "function handleFileSelect(evt) {\n // Get the file\n var files = evt.target.files; // FileList object\n\n // Call the parse method\n var xl2json = new ExcelToJSON();\n xl2json.parseExcel(files[0]);\n}", "function xlxsReadCallback(jsonArray) {\n if (jsonArray == null) {\n tmpThis.$alert('导入文件格式不符合要求!', '错误', {\n confirmButtonText: '确定'\n });\n return null;\n }\n // Callback method when the gist id in the arrary are fully updated:\n function idUpdatedCallback() {\n // Update progress bar text:\n tmpThis.fileInputProgressText = \"开始上传数据到服务器,请稍后...\"\n // Insert json array to server:\n tmpThis.insertAllDataIntoServer(jsonArray);\n }\n // Get all Gist IDs:\n var newArray = updateGistIdOfDataArray(jsonArray, 0, idUpdatedCallback);\n\n }", "function ImportFile() { \n var excelUrl = \"table_of_dates.xlsx\"; \n\n var oReq = new XMLHttpRequest(); \n oReq.open('get', excelUrl, true); \n oReq.responseType = 'blob'; \n oReq.onload = function () { \n var blob = oReq.response; \n excelIO.open(blob, LoadSpread, function (message) { \n console.log(message); \n }); \n }; \n oReq.send(null); \n}", "function handleInputFile(e) {\n var files = e.target.files, f = files[0];\n inputName = f.name;\n var reader = new FileReader();\n reader.onload = function(e) {\n var data = e.target.result;\n if(!rABS) data = new Uint8Array(data);\n var workbook = XLSX.read(data, {type: rABS ? 'binary' : 'array'});\n \tvar sheet = workbook.Sheets[Object.keys(workbook.Sheets)[0]];\n \t//console.log(sheet);\n \ttable = sheet2arr(sheet);\n \tmaxRow = table.length;\n\tmaxCol = table[0].length;\n\ttableRow = 0;\n\ttableCol = -1;\n\tnewTable = new Array(maxRow).fill(0).map(() => new Array(maxCol).fill(\"\"));\n\tnewTable[0] = table[0];\n\toutwb = XLSX.utils.book_new();\n\toutwb.SheetNames.push(\"Sheet1\");\n\n /* DO SOMETHING WITH workbook HERE */\n };\n if(rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);\n}", "function getFileTextData(fileName){\n\t\n const result = excelToJson({\n\tsourceFile: fileName,\n/*\tsheets: [\n\t{\n\t\tname: 'BirthDay',\n\t range: 'A4:C5'\n\t}],\n\tcolumnToKey: {\n\t\tA: 'EmployeeCode',\n\t\tB: 'EmployeeName',\n\t\tC: 'DateOfBirth'\n\t}\n\t*/\n\t//sourceFile: data\t\n});\n\nconsole.log(\"File Parsed Successfully\");\nconsole.log(result);\n\t\t\nreturn result;\n\n}", "function getFileData(file, callback) {\n var data = [];\n var reader = new FileReader();\n\n reader.onload = function(event) {\n var csv = Papa.parse(event.target.result);\n csvData = csv.data;\n var headerRow = csvData[0];\n for (var i = 1; i < csvData.length; i++) {\n var rowData = {};\n for (var j = 0; j < csvData[i].length; j++) {\n rowData[headerRow[j]] = csvData[i][j];\n }\n data.push(rowData);\n }\n callback(data);\n };\n\n reader.onerror = function() {\n alert('Unable to read ' + file.fileName);\n };\n\n reader.readAsText(file);\n}", "function readFlowFiles($flow, callback) {\n\n var fileQueue = $flow.files;\n var filenames;\n var startTime = new Date().getTime();\n\n if (!(fileQueue instanceof Array)) {\n fileQueue = [fileQueue];\n }\n\n if (fileQueue.length > 0) { // if we still have files left\n\n filenames = _.pluck(fileQueue, 'name');\n\n async.eachSeries(fileQueue, function(file, next) {\n\n //var file = fileQueue.shift(); // remove first from queue and store in file\n var filename = file.name;\n\n file = file.file; // get blob from flowfile\n\n reader.onloadend = function(e) {\n\n var data = e.target.result; // binary\n var headers;\n var READER = XLSX;; // XLSX/XLS keep variable generic for reuse\n var wb;\n var ws;\n var errorMsg = 'Not a readable <em>.xlsx</em> file. Please make sure your workbook is saved as an <em>Excel</em> file with a single template worksheet.';\n var processSheet = function(wb) {\n // Good to go\n ws = wb.Sheets[_.keys(wb.Sheets)[0]];\n delete wb; // free up memory\n\n // Trim the headers\n if (typeof _.getByPath(ws, 'A1.v') === 'string') {\n ws.A1.v = ws.A1.v.trim();\n }\n if (typeof _.getByPath(ws, 'A1.w') === 'string') {\n ws.A1.w = ws.A1.w.trim();\n }\n\n return READER.utils.sheet_to_json(ws);\n };\n\n try {\n wb = READER.read(data, {\n type: 'binary'\n });\n ws = processSheet(wb);\n } catch (exception) {\n // XLSX doesn't throw a very informative exception\n try {\n READER = XLS;\n wb = READER.read(data, {\n type: 'binary'\n });\n ws = processSheet(wb);\n } catch (exception) {\n\n errorMsg =\n typeof exception === 'string' ? exception : exception.message;\n\n try {\n\n data = Papa.parse(data);\n headers = data.data.shift();\n\n if (!data.errors.length) {\n\n // @TODO should we async this for large files?...\n ws = _.map(data.data, function(row) {\n return _.object(headers, row);\n });\n\n } else {\n throw new Error('Errors parsing CSV string.');\n }\n } catch (exception) {\n\n errorMsg =\n typeof exception === 'string' ? exception : exception.message;\n }\n }\n }\n\n if (!ws) {\n alertify.notify(\n errorMsg,\n ' bubble-popover bubble-danger',\n 0\n );\n return; // cancel the operation\n }\n\n if (typeof callback !== 'undefined') {\n\n // args\n callback({\n ws: ws,\n filename: filename,\n READER: READER,\n next: next\n });\n\n } else {\n next();\n }\n\n // readFlowFiles(callback); // start next file\n };\n\n reader.readAsBinaryString(file);\n\n }, function() {\n\n $flow.cancel();\n\n alertify.alert(\n '<ul><h5>Finished processing the following files:</h5><li>'\n + filenames.join('</li><li>')\n + '</li></ul>'\n );\n\n });\n }\n }", "handleSheet(workbook, extentions){\n var sheetJS = ( extentions === 'xls' ? XLS : XLSX );\n\n /* Get worksheet */\n for(var id in workbook.SheetNames) {\n var workSheetName = workbook.SheetNames[id];\n var worksheet = workbook.Sheets[workSheetName];\n\n var headers = [];\n var range = null;\n\n if(worksheet['!ref']){\n range = sheetJS.utils.decode_range(worksheet['!ref']);\n } else {\n continue;\n }\n \n if(range) {\n var C, R = range.s.r; /* start in the first row */\n \n /* walk every column in the range */\n for(C = range.s.c; C <= range.e.c; ++C) {\n var cell = worksheet[sheetJS.utils.encode_cell({c:C, r:R})] /* find the cell in the first row */\n\n if(cell && cell.t) {\n var hdr = sheetJS.utils.format_cell(cell);\n headers.push(hdr);\n }\n }\n } else {\n continue;\n }\n\n //console.log(headers);\n\n /*-----\n Check required field header\n -----*/\n var validFields = false;\n for (var i in officerInfo){\n if(headers.includes(officerInfo[i])){\n validFields = true;\n } else {\n this.setState({\n loadding: false,\n error: true,\n message: \"Thiếu hoặc sai tên trường: \" + officerInfo[i]\n });\n\n validFields = false;\n break;\n }\n }\n\n if(validFields) {\n this.setState({\n error: false,\n message: ''\n })\n\n this.handleSheetData(worksheet, sheetJS);\n } else {\n return;\n }\n }\n }", "function parseExcel(filename) {\n var workbook = new Excel.Workbook();\n\n var autotask;\n var list =[]\n workbook.xlsx.readFile(filename)\n .then(function() {\n\n var worksheet = workbook.getWorksheet(1);\n\n var i;\n for(i=2;i<=worksheet.rowCount;i++) {\n autotask = new AutoTask(\n worksheet.getRow(i).getCell(1).value,\n worksheet.getRow(i).getCell(2).value,\n worksheet.getRow(i).getCell(4).value,\n worksheet.getRow(i).getCell(5).value,\n )\n list.push(autotask);\n }\n }).then(function () {\n console.log(\"Parse Complete\")\n appDatabase.pushData(list)\n }).then(function () {\n console.log(\"Finished\")\n })\n\n}", "load(req, res){\r\n\t\t\tlet \tfile \t\t= \treq.files.file\r\n\t\t\t, \t\txlsxData \t= \txlsx.parse(file.path)\r\n\t\t\t,\t\tresult\t\t=\t[]\r\n\r\n\t\t\t//Contruimos el formato del json deseado desde las librerias y cabeceras\r\n\t\t\tfor(let i in xlsxData){\r\n\t\t\t\tlet \tlib\t\t\t= \txlsxData[i]\r\n\t\t\t\t,\t\trow \t\t= \tlib.data[0]\r\n\t\t\t\t,\t\trowFormat \t= \t{}\r\n\t\t\t\t, \t\trowHeads\t= \t[]\r\n\t\t\t\t\r\n\t\t\t\trowFormat.id \t= i\r\n\t\t\t\trowFormat.lib \t= lib.name\r\n\r\n\t\t\t\tfor(let i in row){\r\n\t\t\t\t\tlet value \t\t= row[i]\r\n\t\t\t\t\t,\trowFormat \t= {}\r\n\r\n\t\t\t\t\trowFormat.row \t= value\r\n\t\t\t\t\trowFormat.id\t= i\r\n\r\n\t\t\t\t\trowHeads.push(rowFormat)\r\n\t\t\t\t}\r\n\t\t\t\trowFormat.data \t= rowHeads\r\n\t\t\t\tresult.push(rowFormat)\r\n\t\t\t}\r\n\r\n\t\t\t//Agregamos los valores de los campos al nuevo formato\r\n\t\t\tfor(let i in result){\r\n\t\t\t\tlet lib = result[i]\r\n\t\t\t\tfor(let i in lib.data){\r\n\t\t\t\t\t\r\n\t\t\t\t\tlet data\t\t= lib.data[i]\r\n\t\t\t\t\t, \txlsxDataRow = xlsxData[lib.id].data\r\n\r\n\t\t\t\t\tif(!result[lib.id].data[data.id]) continue;\r\n\t\t\t\t\tresult[lib.id].data[data.id].column = []\r\n\t\t\t\t\tfor(let i in xlsxDataRow){\r\n\t\t\t\t\t\tif(i == 0) continue;\r\n\t\t\t\t\t\tlet xlsxRow = xlsxDataRow[i]\r\n\t\t\t\t\t\tresult[lib.id].data[data.id].column.push( (xlsxRow[data.id])?xlsxRow[data.id]:null )\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tres.status(200).send({status:'success', file:result})\r\n\t\t}", "function readFile(files) {\n\n var i, f;\n for (i = 0; i !== files.length; ++i) {\n f = files[i];\n var reader = new FileReader();\n\n reader.onload = function (e) {\n var data = e.target.result;\n\n var wb, arr = false;\n var readtype = {type: rABS ? 'binary' : 'base64'};\n if (!rABS) {\n arr = fixData(data);\n data = btoa(arr);\n }\n\n function doit() {\n try {\n opts.on.workstart();\n\n wb = XLSX.read(data, readtype);\n opts.on.workend(processWB(wb, 'XLSX'));\n } catch (e) {\n opts.errors.failed(e);\n }\n }\n\n if (e.target.result.length > 500000) {\n opts.errors.large(e.target.result.length, function (e) {\n if (e) {\n doit();\n }\n });\n } else {\n doit();\n }\n };\n if (rABS) {\n reader.readAsBinaryString(f);\n } else {\n reader.readAsArrayBuffer(f);\n }\n }\n }", "function handleFile(filePath) \n{\n\n\t$(document).ready(function () {\n\t\t$.ajax({\n\t\t\ttype: \"GET\",\n\t\t\turl: filePath,\n\t\t\tdataType: \"csv\",\n\t\t\tsuccess: function (data) { processData(data); }\n\t\t});\n\t});\n}", "read(file) {\n var workbook = XLSX.readFile(file);\n var sheet_name_list = workbook.SheetNames;\n var data = {};\n var letters = [];\n var moduleShortNameArray = [];\n sheet_name_list.forEach(function(y) {\n var worksheet = workbook.Sheets[y];\n var headers = [];\n\n var column = 0;\n var enc_addr = XLSX.utils.encode_cell;\n var dec_range = XLSX.utils.decode_range;\n var range = dec_range(worksheet['!ref']);\n\n while (worksheet[enc_addr({c: column, r: 0})]) {\n headers.push((worksheet[enc_addr({c: column, r: 0})].v).replace(/ +/g, \"\"));\n column++\n }\n\n for (var R = range.s.r +1; R <= range.e.r; ++R) {\n\n var record = [];\n\n data['row'+R] = {};\n for (var C = range.s.c; C <= headers.length-1; ++C) {\n let cell_address = enc_addr({c: C, r: R});\n let cell = worksheet[cell_address];\n\n if (cell && typeof cell.v !== 'undefined') {\n var header = headers[R-1];\n var value = cell.v;\n record.push(value);\n headers.map((header, index) => {\n data[\"row\"+R][header] = record[index];\n })\n }\n }\n moduleShortNameArray.push(record[0].split('_').pop());\n letters.push(record[0].charAt(0));\n\n }\n });\n\n this.uniqueRows = this.reducerFilter([], letters);\n this.uniqueModuleShortName = this.reducerFilter([], moduleShortNameArray);\n this.filterData(data);\n }", "function readFile(files) {\n\n var i, f;\n for (i = 0; i !== files.length; ++i) {\n f = files[i];\n var reader = new FileReader();\n reader.onload = function (e) {\n var data = e.target.result;\n\n var wb, arr = false;\n var readtype = {type: rABS ? 'binary' : 'base64'};\n if (!rABS) {\n arr = fixData(data);\n data = btoa(arr);\n }\n\n function doit() {\n try {\n opts.on.workstart();\n\n wb = XLSX.read(data, readtype);\n opts.on.workend(processWB(wb));\n } catch (e) {\n opts.errors.failed(e);\n }\n }\n\n if (e.target.result.length > 5000000) {\n opts.errors.large(e.target.result.length, function (e) {\n if (e) {\n doit();\n }\n });\n } else {\n doit();\n }\n };\n if (rABS) {\n reader.readAsBinaryString(f);\n } else {\n reader.readAsArrayBuffer(f);\n }\n }\n }", "read() {\n const {\n input,\n sheetname,\n schema,\n hasHeader = true,\n lowerCaseHeaders,\n onRecord,\n onCell,\n onError,\n useMemoryForItems, // useful when no onRecord handler and no output provided\n backwards\n } = this.options;\n\n console.log(\"Reading Excel file...\", input);\n\n const eventNames = [...DEFAULT_EVENTS];\n if (typeof onCell === \"function\") eventNames.push(\"cell\");\n\n this._rowsProcessed = 0;\n this._hasRecord = false;\n this._createOutStream();\n this._writeHeader();\n this._sheetReaderInstance = { _startRow: 0 };\n\n FastXlsxReader.iterate(\n input,\n sheetname,\n (eventName, data, rowIndex, colIndex) => {\n if (eventName === 'start') {\n this._createOutStream();\n this._writeHeader();\n // the 'start' event's third param (after the 'this' arg) is the sheet reader instance\n this._sheetReaderInstance = data || this._sheetReaderInstance;\n } else {\n this._handleCallbackEvent(eventName, data, rowIndex, colIndex, schema, hasHeader,\n lowerCaseHeaders, onRecord, onError, useMemoryForItems);\n }\n },\n eventNames,\n this, // thisArg for the callback\n backwards\n );\n }", "function excelReader(filePath, sheetName) {\n // player workbook\n let wb = xlsx.readFile(filePath);\n // get data from a particular sheet in that wb\n let excelData = wb.Sheets[sheetName];\n // sheet to json \n let ans = xlsx.utils.sheet_to_json(excelData);\n return ans;\n}", "function process_spreadsheet() {\n var file = document.getElementById('docpicker')\n var viewer = document.getElementById('spreadsheet_output')\n file.addEventListener('change', importFile);\n\n function importFile(evt) {\n var f = evt.target.files[0];\n\n if (f) {\n var r = new FileReader();\n r.onload = e => {\n var contents = processExcel(e.target.result);\n }\n r.readAsBinaryString(f);\n } else {\n console.log(\"Failed to load file\");\n }\n }\n\n function processExcel(data) {\n var workbook = XLSX.read(data, {\n type: 'binary'\n });\n\n var firstSheet = workbook.SheetNames[0];\n var data = to_json(workbook);\n return data\n };\n\n function to_json(workbook) {\n newDataset.resetData();\n var result = {};\n workbook.SheetNames.forEach(function(sheetName) {\n var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {\n header: 1\n });\n if (roa.length) result[sheetName] = roa;\n });\n newSpreadsheet.setSpreadsheet(result);\n var tx_counter = 0;\n for (i = 0; i < newSpreadsheet.getSpreadsheet()[\"Sheet1\"].length; i++) {\n if (newSpreadsheet.getSpreadsheet()[\"Sheet1\"][i][1] != undefined && newSpreadsheet.getSpreadsheet()[\"Sheet1\"][i][1] != \"undefined\") {\n accountAddress = newSpreadsheet.getSpreadsheet()[\"Sheet1\"][i][1].toString();\n if (web3.utils.isAddress(accountAddress)) {\n var tempAmountinWei = parseInt(newSpreadsheet.getSpreadsheet()[\"Sheet1\"][i][2], 10);\n var amountAsBN = new web3.utils.BN(tempAmountinWei.toString());\n if (web3.utils.toBN(amountAsBN).gt(web3.utils.toBN('0')) && web3.utils.toBN(amountAsBN).lt(web3.utils.toBN('1000000000000000000000'))) {\n var row = [accountAddress, amountAsBN.toString()];\n newDataset.addRowToDataset(row);\n tx_counter = tx_counter + 1;\n row = [];\n } else {\n document.getElementById(\"spreadsheet_output\").innerHTML = \"ERROR!: Account Address of \" + accountAddress + \"is going to receive more than 1000 network tokens (this prototype application does not support amounts that high)\";\n }\n }\n }\n }\n document.getElementById(\"spreadsheet_output\").innerHTML = JSON.stringify(newDataset.getDataset(), 2, 2);\n };\n}", "function handleFiles(files) {\n sheet = document.getElementById(\"sheet\").fabric;\n file = files[0];\n var reader = new FileReader();\n reader.onload = function() {\n var dataURL = reader.result;\n // load it into the canvas\n var img = new Image();\n img.onload = function() {\n var fabricImage = new fabric.Image(img);\n sheet.add(fabricImage);\n };\n img.src = dataURL;\n };\n reader.readAsDataURL(file);\n}", "function ImportExcelCsvPingabankTest() {}", "function get_json_data(file_path_to_load_xls) {\n \"use strict\"\n\n var file_path = \"/media/static/documents/\";\n var file_to_load_xls = file_path_to_load_xls.split(/.*[\\/|\\\\]/)[1];\n var file_to_load_json = file_to_load_xls.split('.').slice(0, -1).join('.') + \".json\";\n var file_to_load_json_full = file_path + file_to_load_json;\n\n var call_results = $.ajax({\n type:'GET',\n url:file_to_load_json_full,\n success: function(data) {\n table_load(data);\n },\n error : function(xhr,errmsg,err) {\n console.log(\"error message\");\n console.log(xhr.status + \": \" + xhr.responseText); // provide a bit more info about the error to the console\n }\n });\n\n}", "function filePicked(oEvent) {\r\n\t// Get The File From The Input\r\n\tvar oFile = oEvent.target.files[0];\r\n\tvar sFilename = oFile.name;\r\n\tif (!oFile) {\r\n\t\talert(\"Failed to load file\");\r\n \t} else if (/.xml\\$/.test(sFilename)) { // vérifie que le nom du fichier se termine par .xml\r\n\t\tloadXml(oFile);\r\n \t} else if (/.xls\\$/.test(sFilename)) {\r\n\t\t// Create A File Reader HTML5\r\n\t\tvar reader = new FileReader();\r\n\r\n\t\t// Ready The Event For When A File Gets Selected\r\n\t\treader.onload = function(e) {\r\n\t\t\tvar data = e.target.result;\r\n\t\t\tvar cfb = XLSX.read(data, {type: 'binary'}); // conversion \r\n\t\t\tcfb.SheetNames.forEach(function conv(sheetName) {\r\n\t\t\t\t// Obtain The Current Row As CSV\r\n\t\t\t\tvar csvData = XLS.utils.make_csv(cfb.Sheets[sheetName]); \r\n\t\t\t\tvar data=XLS.utils.make_csv(cfb.Sheets[sheetName]); //// conversion xls /xlsx / ods -> csv \r\n\t\t\t\tvar employee_data = data.split(/\\r?\\n|\\r/);\r\n\t\t\t\tlet table_data = '<table class=\"table table-bordered table-striped\">'; // affichage\r\n\t\t\t\tfor(var count = 0; count<employee_data.length; count++)\r\n\t\t\t\t{\r\n\t\t\t\t\tvar cell_data = employee_data[count].split(\",\");\r\n\t\t\t\t\ttable_data += '<tr>';\r\n\t\t\t\t\tfor(var cell_count=0; cell_count<cell_data.length; cell_count++) // affichage\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(count === 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ttable_data += '<th>'+cell_data[cell_count]+'</th>';\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ttable_data += '<td>'+cell_data[cell_count]+'</td>';\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttable_data += '</tr>';\r\n\t\t\t\t}\r\n\t\t\t\ttable_data += '</table>'; // table_data : la conversion csv-> tableau html \r\n\t\t\t\t//console.log(table_data); //// test html \r\n\t\t\t\tdocument.getElementById('DataBlock').innerHTML +=table_data; // affichage \r\n\r\n\t\t\t\tcsvData = csvData.split('\\n').map(row => row.trim()); //// conversion csv-> xml \r\n\t\t\t\tlet headings = csvData[1].split(',').map(row => row.trim());\r\n\t\t\t\tfor (z=0 ;z<headings.length;z++){ // pour eliminer les espace et les caractere specieux des balise \r\n\t\t\t\t\t\tfor (h=0;h<headings[z].length;h++){\r\n\t\t\t\t\t\theadings[z]=headings[z].replace(' ','');// pour les balise ou il y a faute de frappe avec deux espace \r\n\t\t\t\t\t\theadings[z]=headings[z].replace('/','');\r\n\t\t\t\t\t\theadings[z]=headings[z].replace(\"'\",\"\");\r\n\t\t\t\t\t\theadings[z]=headings[z].replace('°','');\r\n\t\t\t\t\t\theadings[z]=headings[z].replace('.','');\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tvar xml = ``;\r\n\t\t\t\txml=\"<?xml version=\"+\"1.0\"+\" encoding=\"+\"ISO-8859-1\"+\" ?>\\n\"; \r\n\t\t\t\tfor(let i = 2; i < csvData.length; i++) {\r\n\t\t\t\tlet details = csvData[i].split(',').map(row => row.trim());\r\n\t\t\t\txml += \"<productData>\\n\";\r\n\r\n\t\t\t\tfor(let j = 0; j < headings.length; j++) {\r\n\t\t\t\t\tif (headings[j] !== \"\"){ // condition pour regler le probleme de dimension du tableau \r\n\t\t\t\txml += `<${headings[j]}>${details[j]}</${headings[j]}>`;\r\n\t\t\t\t\t}\r\n\t\t\t\t};\t\t\t\t\t\t\t\t\r\n\t\t\t\txml += \"\\n</productData>\\n\"; // xml : le fichier xml \r\n\r\n\t\t\t\t};\r\n\r\n\t\t\t\t/*\r\n\t\t\t\t//Function to download data to a file\r\n\t\t\t\tfunction download(data, filename, type) {\r\n\t\t\t\t\tvar file = new Blob([data], {type: type});\r\n\t\t\t\t\tif (window.navigator.msSaveOrOpenBlob) // IE10+\r\n\t\t\t\t\t\twindow.navigator.msSaveOrOpenBlob(file, filename);\r\n\t\t\t\t\telse { // Others\r\n\t\t\t\t\t\tvar a = document.createElement(\"a\"),\r\n\t\t\t\t\t\t\t\turl = URL.createObjectURL(file);\r\n\t\t\t\t\t\ta.href = url;\r\n\t\t\t\t\t\ta.download = filename;\r\n\t\t\t\t\t\tdocument.body.appendChild(a);\r\n\t\t\t\t\t\ta.click();\r\n\t\t\t\t\t\tsetTimeout(function() {\r\n\t\t\t\t\t\t\tdocument.body.removeChild(a);\r\n\t\t\t\t\t\t\twindow.URL.revokeObjectURL(url); \r\n\t\t\t\t\t\t}, 0); \r\n\t\t\t\t\t}\r\n\t\t\t\t}*/\r\n\r\n\t\t\t}\r\n\t\t\t);\r\n\r\n\r\n\r\n\t\t/*//creation de la liste de fragments :\r\n\t\tlignes = readXml(xml);\r\n\r\n\t\tattributs = getXmlAttributes(lignes[0]);\r\n\t\tcreateObjects(attributs,lignes,Objects); //liste de la liste des valeurs de chaque fragment\r\n\r\n\t\tconsole.log(Objects[0][1]);\t*/\r\n\t\t}\r\n\t// Tell JS To Start Reading The File.. You could delay this if desired\r\n\treader.readAsBinaryString(oFile);\r\n\t}\r\n}", "function readSingleFile(e) {\n // IF WE SELECTED THE FILE FROM BUTTON THEN HANDLE THIS WAY\n if(e.type == \"change\"){\n var file = e.target.files[0];\n if (!file) {\n return;\n }\n }\n else // ELSE, IT MUST BE FROM DRAG AND DROP, HANDLE THIS WAY\n {\n var file = e.dataTransfer.files[0];\n if(!file) {\n return;\n }\n }\n // CHECK IF THE FILE IS OF TYPE XLSX\n if(validateFileType(file)){\n var dragarea = document.getElementById('drag-and-drop');\n dragarea.classList.add('dropped');\n var reader = new FileReader();\n\n reader.readAsBinaryString(file);\n\n reader.onload = function(e) {\n var contents = e.target.result;\n loadExcel(contents);\n document.getElementById('small-hint').innerHTML = \"(\" + file.name + \")\";\n };\n }\n}", "excelImport(data){\nreturn this.post(Config.API_URL + Constant.REFFERAL_EXCELIMPORT, data);\n}", "function findFile(workbook) {\n /*function will be to wait for file upload and confirm it is there before\n calling convert file **move csvworkbook variable when I do adjust.*/\nconvertFile(workbook)\n}", "function loadCSV()\r\n{\r\n\r\n\tvar invoiceLines='';\r\n\r\n\t// load the CSV from the audit record\r\n\tinvoiceCSV = auditRec.getFieldValue('custrecord_payload');\r\n\tinvoiceCSV = UNencodeCSV(invoiceCSV);\r\n\r\n\t// this code only deals with the invoice files\r\n\tinvoiceLines = invoiceCSV.split('\\n');\r\n\r\n\t//=============================================\r\n\t// get the details from the CSV structure\r\n\t//=============================================\r\n\tfor (var i = 0; i < invoiceLines.length; i++)\r\n\t{\r\n\r\n\t\tinvoiceLines[i] = invoiceLines[i].replace(', ',' '); \r\n\t\tnlapiLogExecution('DEBUG', 'invline', invoiceLines[i]);\r\n\t\tinvoiceSplit = invoiceLines[i].split(',');\r\n\t\t\r\n\t\tif (invoiceSplit.length > 5)\r\n\t\t{\r\n\t\t\tgetInvoiceHeaderDetails();\r\n\t\t\tgetInvoiceLineDetails();\r\n\t\t}\r\n\t}\r\n\r\n\r\n}", "HandleDocumentDownloadFile(evt, row) {\n debugger;\n //var filePath = row.original[\"HBL#\"];\n }", "function readFile (evt) {\r\n var files = evt.target.files;\r\n var file = files[0]; \r\n Papa.parse(file, {\r\n \tcomplete: function(results) {\r\n \t\tlog(results);\r\n \t}\r\n }, config);\r\n }", "function record_data(e,fileUrl) {\n try {\n /*var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty(\"key\"));*/\n var doc = SpreadsheetApp.openById(\"1bNVGpo7CWdONGoNS6WRQ58wfOTxGsQBBRxD0ZBFfNmM\");\n var sheet = doc.getSheets()[0];\n \n /*var sheet = doc.getSheetByName(\"responses\"); // select the responses sheet, MAKE SURE YOU HAVE A SHEET NAMED responses*/\n Logger.log(\"hello\");\n var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];\n \n var nextRow = sheet.getLastRow()+1; // get next row\n var row = [ new Date() ]; // first element in the row should always be a timestamp\n // loop through the header columns\n Logger.log(\"are we getting here row\" + row);\n for (var i = 1; i < headers.length; i++) { // start at 1 to avoid Timestamp column\n \n if(headers[i].length > 0 && headers[i] == \"resume\") {\n row.push(fileUrl); // add data to row\n }\n else if(headers[i].length > 0) {\n row.push(e.parameter[headers[i]]); // add data to row\n }\n }\n // more efficient to set values as [][] array than individually\n sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);\n Logger.log(row);\n }\n catch(error) {\n Logger.log(e);\n }\n finally {\n return;\n }\n\n}" ]
[ "0.6457858", "0.6455349", "0.62296724", "0.6148661", "0.61139506", "0.60943913", "0.6035607", "0.58760744", "0.5739597", "0.57332444", "0.5687886", "0.5684987", "0.56793606", "0.5673345", "0.56569004", "0.56158", "0.55913126", "0.5586192", "0.556271", "0.5533437", "0.55055904", "0.5476099", "0.54718375", "0.5471047", "0.5464901", "0.54220116", "0.5418219", "0.54040056", "0.53978634", "0.5394086" ]
0.7073651
0
Try to map a node to all sides of this triangle that don't have a neighbor void MapTriangleToNodes(Triangle& t);
MapTriangleToNodes(t) { if (this.front_ === null) { throw new Error("this.front_ === null"); } for (let i = 0; i < 3; i++) { if (!t.GetNeighbor(i)) { // Node* n = front_->LocatePoint(t.PointCW(*t.GetPoint(i))); const n = this.front_.LocatePoint(t.PointCW(t.GetPoint(i))); if (n) n.triangle = t; } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function rotateTrianglePair(t, p, ot, op) {\n var n1, n2, n3, n4;\n n1 = t.neighborCCW(p);\n n2 = t.neighborCW(p);\n n3 = ot.neighborCCW(op);\n n4 = ot.neighborCW(op);\n\n var ce1, ce2, ce3, ce4;\n ce1 = t.getConstrainedEdgeCCW(p);\n ce2 = t.getConstrainedEdgeCW(p);\n ce3 = ot.getConstrainedEdgeCCW(op);\n ce4 = ot.getConstrainedEdgeCW(op);\n\n var de1, de2, de3, de4;\n de1 = t.getDelaunayEdgeCCW(p);\n de2 = t.getDelaunayEdgeCW(p);\n de3 = ot.getDelaunayEdgeCCW(op);\n de4 = ot.getDelaunayEdgeCW(op);\n\n t.legalize(p, op);\n ot.legalize(op, p);\n\n // Remap delaunay_edge\n ot.setDelaunayEdgeCCW(p, de1);\n t.setDelaunayEdgeCW(p, de2);\n t.setDelaunayEdgeCCW(op, de3);\n ot.setDelaunayEdgeCW(op, de4);\n\n // Remap constrained_edge\n ot.setConstrainedEdgeCCW(p, ce1);\n t.setConstrainedEdgeCW(p, ce2);\n t.setConstrainedEdgeCCW(op, ce3);\n ot.setConstrainedEdgeCW(op, ce4);\n\n // Remap neighbors\n // XXX: might optimize the markNeighbor by keeping track of\n // what side should be assigned to what neighbor after the\n // rotation. Now mark neighbor does lots of testing to find\n // the right side.\n t.clearNeighbors();\n ot.clearNeighbors();\n if (n1) {\n ot.markNeighbor(n1);\n }\n if (n2) {\n t.markNeighbor(n2);\n }\n if (n3) {\n t.markNeighbor(n3);\n }\n if (n4) {\n ot.markNeighbor(n4);\n }\n t.markNeighbor(ot);\n }", "function rotateTrianglePair(t, p, ot, op) {\n var n1, n2, n3, n4;\n n1 = t.neighborCCW(p);\n n2 = t.neighborCW(p);\n n3 = ot.neighborCCW(op);\n n4 = ot.neighborCW(op);\n\n var ce1, ce2, ce3, ce4;\n ce1 = t.getConstrainedEdgeCCW(p);\n ce2 = t.getConstrainedEdgeCW(p);\n ce3 = ot.getConstrainedEdgeCCW(op);\n ce4 = ot.getConstrainedEdgeCW(op);\n\n var de1, de2, de3, de4;\n de1 = t.getDelaunayEdgeCCW(p);\n de2 = t.getDelaunayEdgeCW(p);\n de3 = ot.getDelaunayEdgeCCW(op);\n de4 = ot.getDelaunayEdgeCW(op);\n\n t.legalize(p, op);\n ot.legalize(op, p);\n\n // Remap delaunay_edge\n ot.setDelaunayEdgeCCW(p, de1);\n t.setDelaunayEdgeCW(p, de2);\n t.setDelaunayEdgeCCW(op, de3);\n ot.setDelaunayEdgeCW(op, de4);\n\n // Remap constrained_edge\n ot.setConstrainedEdgeCCW(p, ce1);\n t.setConstrainedEdgeCW(p, ce2);\n t.setConstrainedEdgeCCW(op, ce3);\n ot.setConstrainedEdgeCW(op, ce4);\n\n // Remap neighbors\n // XXX: might optimize the markNeighbor by keeping track of\n // what side should be assigned to what neighbor after the\n // rotation. Now mark neighbor does lots of testing to find\n // the right side.\n t.clearNeighbors();\n ot.clearNeighbors();\n if (n1) {\n ot.markNeighbor(n1);\n }\n if (n2) {\n t.markNeighbor(n2);\n }\n if (n3) {\n t.markNeighbor(n3);\n }\n if (n4) {\n ot.markNeighbor(n4);\n }\n t.markNeighbor(ot);\n}", "mapCoordsToNode(x, y) {\n\n\t}", "function GenerateTileNeighbours()\n{\n // loop through each tile on the map\n var currentX = 0;\n var currentY = 0;\n\n // since the highest x values can really only be gridheight/width -1, make these the highest tiles we check\n var maxX = (gridHeight - 1);\n var maxY = (gridHeight - 1);\n\n for(currentX = 0; currentX < gridWidth; currentX++)\n {\n for (currentY = 0; currentY < gridHeight; currentY++)\n {\n\n var CurrentTile = Tiles[currentX][currentY];\n // first, if this is a wall tile, we don't care, as we can't generate paths through here, so don't add it to the nodes\n if (!(CurrentTile.TileType == TilesNames.Wall))\n {\n // check each of the tiles neighbours, if it's a valid tile\n if (CurrentTile.x != 0)\n {\n // check the tile to the left of it\n if (IsValidTile(CurrentTile.x - 1, CurrentTile.y))\n {\n // add it to the tiles neighbours\n CurrentTile.Neighbours.push(Tiles[CurrentTile.x - 1][CurrentTile.y]);\n }\n }\n \n if (CurrentTile.x != maxX)\n {\n // check the tile to the right of it\n if (IsValidTile(CurrentTile.x + 1, CurrentTile.y))\n {\n // add it to the tiles neighbours\n CurrentTile.Neighbours.push(Tiles[CurrentTile.x + 1][ CurrentTile.y]);\n }\n }\n\n if (CurrentTile.y != 0)\n {\n // check the tile to the top of it\n if (IsValidTile(CurrentTile.x, CurrentTile.y - 1))\n {\n // add it to the tiles neighbours\n CurrentTile.Neighbours.push(Tiles[CurrentTile.x][CurrentTile.y - 1]);\n }\n }\n\n if (CurrentTile.y != maxY)\n {\n // check the tile below it\n if (IsValidTile(CurrentTile.x, CurrentTile.y + 1))\n {\n // add it to the tiles neighbours\n CurrentTile.Neighbours.push(Tiles[CurrentTile.x][CurrentTile.y + 1]);\n }\n }\n\n }\n }\n\n }\n \n}", "function opposed_triangle(edge_map, triangle, vertex) {\n\t// loop through the points of triangle\n\tfor (var p=0; p<pointnames.length; p++) {\n\t\tvar pt = triangle[pointnames[p]];\n\t\tvar ptn = triangle[pointnames[(p + 1) % pointnames.length]];\n\t\t// if vertex is not in the edge formed by point and point + 1 (opposing edge)\n\t\tif (vertex != pt && vertex != ptn) {\n\t\t\t// console.log(\"opposing:\", vertex, pt, ptn);\n\t\t\t// loop through the triangles of the edge\n\t\t\tvar edge_triangles = edge_map[edge_reference(pt,ptn)];\n\t\t\tfor (var e=0; e<edge_triangles.length; e++) {\n\t\t\t\t// if the current triangle is not our original triangle it's the other\n\t\t\t\t// this is the opposing triangle we want\n\t\t\t\tif (edge_triangles[e] != triangle) {\n\t\t\t\t\t// loop through the points of the opposing triangle\n\t\t\t\t\tfor (var pe=0; pe<pointnames.length; pe++) {\n\t\t\t\t\t\tvar pet = edge_triangles[e][pointnames[pe]];\n\t\t\t\t\t\t// if this point's id is not in the edge we found this is the opposing vertex\n\t\t\t\t\t\tif (pet != pt && pet != ptn) {\n\t\t\t\t\t\t\t// return the opposing triangle and opposing vertex and shared edge\n\t\t\t\t\t\t\treturn {\"t\": edge_triangles[e], \"v\": pet, \"e\": [pt, ptn]};\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "function makePath(tiles, fromNode, toNode) {\n \"use strict\";\n var row, col;\n tiles.map[toNode[0]][toNode[1]] = FLOOR;\n row = (fromNode[0] + toNode[0]) / 2;\n col = (fromNode[1] + toNode[1]) / 2;\n tiles.map[row][col] = FLOOR;\n}", "function make_edge_map(triangles) {\n\tvar edge_map = {};\n\tfor (var t=0; t<triangles.length; t++) {\n\t\t// loop through the points of this triangle to find the edges\n\t\tfor (var p=0; p<pointnames.length; p++) {\n\t\t\t// the two points involved in this edge\n\t\t\tvar a = triangles[t][pointnames[p]];\n\t\t\tvar b = triangles[t][pointnames[(p + 1) % pointnames.length]];\n\t\t\t// add this triangle to the edge list\n\t\t\tif (edge_map[edge_reference(a,b)]) {\n\t\t\t\tedge_map[edge_reference(a,b)].push(triangles[t]);\n\t\t\t} else {\n\t\t\t\tedge_map[edge_reference(a,b)] = [triangles[t]];\n\t\t\t}\n\t\t}\n\t}\n\treturn edge_map;\n}", "function createWalls(map)\n{\n //var n = [];\n for (var y = 0; y < map.length; y++)\n {\n for (var x = 0; x < map[0].length; x++)\n {\n if (map[y][x] === 1 && map[y][x] !== 2)\n {\n if (y > 0 && y < map.length - 1 && x > 0 && x < map[0].length - 1)\n {\n if (map[y][x + 1] === 0 || map[y + 1][x] === 0)\n map[y][x] = 2;\n if (map[y][x - 1] === 0 || map[y - 1][x] === 0)\n map[y][x] = 2;\n }\n if (y === 0) {\n if (map[y + 1][x] === 0)\n map[y][x] = 2;\n }\n if (y === map.length - 1) {\n if (map[y - 1][x] === 0)\n map[y][x] = 2;\n }\n if (x === 0) {\n if (map[y][x + 1] === 0)\n map[y][x] = 2;\n }\n if (x === map[0].length - 1) {\n if (map[y][x - 1] === 0)\n map[y][x] = 2;\n }\n }\n }\n }\n}", "function setNeighbors() {\n\tvar width = tiles[0].length - 1;\n\tvar height = tiles.length - 1;\n\tfor(y = 1; y < height; y++) {\n\t\tfor(x = 1; x < width; x++) {\n\t\t\ttiles[y][x].addNeighbors( tiles[y][x-1]);\n\t\t\ttiles[y][x].addNeighbors( tiles[y+1][x]);\n\t\t\ttiles[y][x].addNeighbors( tiles[y][x+1]);\n\t\t\ttiles[y][x].addNeighbors( tiles[y-1][x]);\t\t\n\t\t}\n\t}\n}", "function mapa3(){\n // Crea un arreglo con los nodos visitados hasta ahora.\n var nodes = [\n \n {id: 1, label: 'Brasil'},\n {id: 2, label: 'Finlandia'},\n {id: 3, label: 'China'},\n ];\n\n // Crea un arreglo con las conexiones entre los nodos.\n var edges = [\n {from: 1, to: 2},\n {from: 2, to: 3},\n\n \n\n ];\n // Crea un arreglo con los nodos activos.\n var activeNode = [ 3 ];\n mapa( nodes, edges, activeNode );\n}", "function mapNodes(nodes) {\n var nodesMap = d3.map();\n for(var i = 0; i < nodes.length; i++) {\n nodesMap.set(nodes[i].id, nodes[i]);\n }\n return nodesMap;\n }", "function calculateAdjacencyInfo(map, x, y){\n let number = 0;\n let Sides = [{x:0,y:-1}, {x:-1,y:0}, {x:1,y:0}, {x:0,y:1}];\n let SidesID = [0x10, 0x20, 0x40, 0x80];\n \n let CornerMask = [0x30, 0x50, 0xA0, 0xC0];\n let Corners = [{x:-1,y:-1}, {x:1,y:-1}, {x:-1,y:1}, {x:1,y:1}];\n let CornersID = [0x01, 0x02, 0x04, 0x08];\n //first, get the 4 directly adjacent tiles\n for(let i = 0;i<4;i++){\n if (isWall(map, x+Sides[i].x, y+Sides[i].y)){\n number = number | SidesID[i];\n }\n }\n //then, get the corners, if they are noticable\n for(let i = 0;i<4;i++){\n //console.log((number & CornerMask[i]) == CornerMask[i]);\n if ((number & CornerMask[i]) === CornerMask[i]){\n \n if ( isWall(map, x+Corners[i].x, y+Corners[i].y)){\n number = number | CornersID[i];\n }\n }\n }\n //\n return number;\n}", "function substitutionTT(tile) {\r\n switch (tile.id[0]) {\r\n case \"triangle0\":\r\n var newtiles = [];\r\n\r\n var new_tri1 = tile.myclone();\r\n new_tri1.tri0to1();\r\n new_tri1.id.push(\"fils_0to1\");\r\n newtiles.push(new_tri1);\r\n\r\n return newtiles;\r\n case \"triangle1\":\r\n var newtiles = [];\r\n\r\n var new_tri2 = tile.myclone();\r\n new_tri2.tri1to2();\r\n new_tri2.id.push(\"fils_1to2\");\r\n newtiles.push(new_tri2);\r\n\r\n return newtiles;\r\n case \"triangle2\":\r\n var newtiles = [];\r\n\r\n var A = new THREE.Vector2(tile.bounds[0], tile.bounds[1]);\r\n var B = new THREE.Vector2(tile.bounds[2], tile.bounds[3]);\r\n var C = new THREE.Vector2(tile.bounds[4], tile.bounds[5]);\r\n var AB_center = ((new THREE.Vector2()).addVectors(A, B)).divideScalar(2);\r\n var AC_center = ((new THREE.Vector2()).addVectors(A, C)).divideScalar(2);\r\n var BC_center = ((new THREE.Vector2()).addVectors(B, C)).divideScalar(2);\r\n var AC_quarter = ((((new THREE.Vector2()).add(A)).multiplyScalar(3)).add(C)).divideScalar(4);\r\n var ABC_center = ((new THREE.Vector2()).addVectors(AC_center, B)).divideScalar(2);\r\n\r\n var new_tri2 = tile.myclone();\r\n\t\t\tnew_tri2.limit = 3\r\n new_tri2.bounds = triangleVectorsToBounds(C, AC_center, B);\r\n new_tri2.id.push(\"fils0\");\r\n newtiles.push(new_tri2);\r\n\r\n var new_tri0_0 = tile.myclone();\r\n new_tri0_0.tri2to0();\r\n new_tri0_0.id.push(\"fils1\");\r\n new_tri0_0.bounds = triangleVectorsToBounds(AB_center, AC_quarter, A);\r\n newtiles.push(new_tri0_0);\r\n\r\n var new_tri0_1 = tile.myclone();\r\n new_tri0_1.tri2to0();\r\n new_tri0_1.id.push(\"fils2\");\r\n new_tri0_1.bounds = triangleVectorsToBounds(B, ABC_center, AB_center);\r\n newtiles.push(new_tri0_1);\r\n\r\n var new_tri0_2 = tile.myclone();\r\n new_tri0_2.tri2to0();\r\n new_tri0_2.id.push(\"fils3\");\r\n new_tri0_2.bounds = triangleVectorsToBounds(AC_center, AC_quarter, AB_center);\r\n newtiles.push(new_tri0_2);\r\n\r\n var new_tri0_3 = tile.myclone();\r\n new_tri0_3.tri2to0();\r\n new_tri0_3.id.push(\"fils4\");\r\n new_tri0_3.bounds = triangleVectorsToBounds(AC_center, ABC_center, AB_center);\r\n newtiles.push(new_tri0_3);\r\n\r\n return newtiles;\r\n default:\r\n console.log(\"caution: undefined tile type for substitutionTT, id = \" + tile.id);\r\n }\r\n}", "function findNeighborTiles(map,xCoOrd, yCoOrd){\n var north = yCoOrd - 1;\n var south = yCoOrd + 1;\n var east = xCoOrd + 1;\n var west = xCoOrd - 1;\n\n \n if(isValidNeighbor(map.tiles[xCoOrd][south]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"south\"] = map.tiles[xCoOrd][south];\n if(isValidNeighbor(map.tiles[xCoOrd][north]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"north\"] = map.tiles[xCoOrd][north];\n if(isValidNeighbor(map.tiles[east][yCoOrd]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"east\"] = map.tiles[east][yCoOrd];\n if(isValidNeighbor(map.tiles[west][yCoOrd]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"west\"] = map.tiles[west][yCoOrd];\n if(isValidNeighbor(map.tiles[east][south]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"southeast\"] = map.tiles[east][south];\n if(isValidNeighbor(map.tiles[west][south]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"southwest\"] = map.tiles[west][south];\n if(isValidNeighbor(map.tiles[east][north]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"northeast\"] = map.tiles[east][north];\n if(isValidNeighbor(map.tiles[west][north]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"northwest\"] = map.tiles[west][north];\n //return whether current tile is a valid neighbor\n function isValidNeighbor(currentTile){\n if(currentTile !== undefined){\n if(currentTile.isPassable){\n return true;\n } else return false;\n }else return false;\n }\n}", "function unb(nodes, node, boardArray, target, name, start, heuristic) {\n let nb = gn(node.id, nodes, boardArray);\n for (let neighbor of nb) {\n un(node, nodes[neighbor], nodes[target], name, nodes, nodes[start], heuristic, boardArray);\n }\n}", "function genNodes(map){\n map.forEach(function(value){\n nodes.push(value);\n });\n}", "function applyRules() {\n let work = map.slice(0);\n map = grid();\n\n for (var row in map) {\n if (map.hasOwnProperty(row)) {\n for (var col in map[row]) {\n if (map[row].hasOwnProperty(col)) {\n\n //map[row][col] = null;\n\n let tile = work[row][col];\n let n = getNeighbors(work, row, col);\n let totalNeigbors = n.reduce(function (total, sum) {\n return (total || 0) + (sum || 0);\n });\n\n if (tile === 1) {\n\n // Any live cell with fewer than two live neighbors dies, as if by underpopulation.\n if (totalNeigbors < 2) {\n map[row][col] = 0;\n }\n // Any live cell with two or three live neighbors lives on to the next generation.\n else if (totalNeigbors == 2 || totalNeigbors == 3) {\n map[row][col] = 1;\n }\n // Any live cell with more than three live neighbors dies, as if by overpopulation.\n else if (totalNeigbors > 3) {\n map[row][col] = 0;\n }\n\n } else {\n\n // Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.\n if (totalNeigbors == 3) {\n map[row][col] = 1;\n }\n\n }\n\n }\n }\n }\n }\n }", "generateTriangles() {\n\t\tvar icosphere = Icosphere.create(this.config.recursion_level);\n\n\t\tthis.triangles = icosphere.triangles;\n\t}", "function unb(nodes, node, boardArray, target, name, start, heuristic) {\n let nb = gn(node.id, nodes, boardArray);\n for (let neighbor of nb) {\n if (target) {\n un(node, nodes[neighbor], nodes[target], name, nodes, nodes[start], heuristic, boardArray);\n } else {\n un(node, nodes[neighbor]);\n }\n }\n}", "function Triangle(v1, v2, v3) {\n\n this.v1 = v1;\n this.v2 = v2;\n this.v3 = v3;\n\n this.normal = new THREE.Vector3();\n\n this.computeNormal();\n\n v1.faces.push(this);\n v1.addUniqueNeighbor(v2);\n v1.addUniqueNeighbor(v3);\n\n v2.faces.push(this);\n v2.addUniqueNeighbor(v1);\n v2.addUniqueNeighbor(v3);\n\n\n v3.faces.push(this);\n v3.addUniqueNeighbor(v1);\n v3.addUniqueNeighbor(v2);\n\n }", "function updateUnvisitedNeighbors(node, grid) {\n const unvisitedNeighbors = getUnvisitedNeighbors(node, grid);\n // calculateManhattanDistance(unvisitedNeighbors, grid);\n // console.log(unvisitedNeighbors);\n for (let neighbor of unvisitedNeighbors) {\n neighbor.distance = node.distance + 1;\n neighbor.totalDistance = node.distance + neighbor.heuristicDistance;\n\n neighbor.previousNode = node;\n }\n}", "function genMap()\r\n\t{\r\n\t\tvar EDGE = 2;\t\t//defaults to fenceless edge\r\n\t\tvar CORNER = 3;\t\t//defaults to fenceless corner\r\n\r\n\t\tif (Math.random() > 0.5)//random fence\r\n\t\t{\r\n\t\t\tEDGE = 4;\r\n\t\t\tCORNER = 5;\r\n\t\t}\r\n\r\n\t\tfor ( var x = 0; x < tileCountX; x ++ )\r\n\t\t{\r\n\t\t\tvar id = 0;\r\n\t\t\tvar rotation = 0;\r\n\r\n\t\t\tspriteTiles[x] = [];\r\n\t\t\tfor ( var y = 0; y < tileCountY; y ++ )\r\n\t\t\t{\r\n\t\t\t\tid = 0;\r\n\r\n\t\t\t\t//level border in clockwise order from top left\r\n\t\t\t\tif ( y == 0 )\t\t\t\t\t\t\t\t// top side\r\n\t\t\t\t\tid = EDGE;\r\n\t\t\t\tif ( x == tileCountX - 1 )\t\t\t\t\t// right side\r\n\t\t\t\t{\r\n\t\t\t\t\tid = EDGE;\r\n\t\t\t\t\trotation = 1;\r\n\t\t\t\t}\r\n\t\t\t\tif ( y == tileCountY - 1 )\t\t\t\t\t// bottom side\r\n\t\t\t\t{\r\n\t\t\t\t\tid = EDGE;\r\n\t\t\t\t\trotation = 2;\r\n\t\t\t\t}\r\n\t\t\t\tif ( x == 0 )\t\t\t\t\t\t\t\t// left side\r\n\t\t\t\t{\r\n\t\t\t\t\tid = EDGE;\r\n\t\t\t\t\trotation = 3;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t//level corner --- draws over border\r\n\t\t\t\tif ( x == 0 && y == 0 )\t{\t\t\t\t\t//NW\r\n\t\t\t\t\tid = CORNER;\r\n\t\t\t\t\trotation = 0;\r\n\t\t\t\t}\r\n\t\t\t\tif ( x == tileCountX - 1 && y == 0 )\t\t\t//NE\r\n\t\t\t\t{\r\n\t\t\t\t\tid = CORNER;\r\n\t\t\t\t\trotation = 1;\r\n\t\t\t\t}\r\n\t\t\t\tif ( x == tileCountX - 1 && y == tileCountY - 1 )\t//SE\r\n\t\t\t\t{\r\n\t\t\t\t\tid = CORNER;\r\n\t\t\t\t\trotation = 2;\r\n\t\t\t\t}\r\n\t\t\t\tif ( x == 0 && y == tileCountY - 1 )\t\t\t//SW\r\n\t\t\t\t{\r\n\t\t\t\t\tid = CORNER;\r\n\t\t\t\t\trotation = 3;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t//random rocks 1 space inside border\r\n\t\t\t\tif ( x > 1 && x < (tileCountX - 1) - 1 )\r\n\t\t\t\t\tif ( y > 1 && y < (tileCountY - 1) - 1 )\r\n\t\t\t\t\t\tif ( Math.random() > 0.95 )\r\n\t\t\t\t\t\t\tid = 1;\r\n\r\n\t\t\t\tspriteTiles[x].push(new spriteID(id, rotation));\r\n\t\t\t}\r\n\t\t}\r\n\t}", "function triangulate_polygon(poly, edge, triangles) {\n\t//console.log(\"triangulate_polygon\", poly, edge);\n\t// var new_triangles = [];\n\tvar a = edge[0];\n\tvar b = edge[1];\n\tvar c = 0;\n\tvar use_tri = null;\n\t//If P has more than one element then\n\tif (poly.length > 1) {\n\t\t// c:=First vertex of P\n\t\t// For each vertex v in P do\n\t\tfor (var v=0; v<poly.length; v++) {\t\n\t\t\t// If v ∈ CircumCircle (a, b, c) then\n\t\t\tvar new_tri = new DelaunayTriangle(a, b, poly[c]);\n\t\t\tif (Math.pow(_delaunay_distance(poly[v], new_tri), 2) < new_tri.r) {\n\t\t\t\t//c:=v\n\t\t\t\tc = v;\n\t\t\t\tuse_tri = new DelaunayTriangle(a, b, poly[c]);\n\t\t\t}\n\t\t\t//EndIf\n\t\t}\n\t\t//EndFor\n\t\t//Divide P into PE and PD giving P=PE +c+PD\n\t\tvar poly_e = poly.slice(0, c);\n\t\tvar poly_d = poly.slice(c + 1);\n\t\t//TriangulatePseudoPolygon(PE , ac, T)\n\t\ttriangulate_polygon(poly_e, [a, poly[c]], triangles);\n\t\t//TriangulatePseudoPolygon(PD , cd, T)\n\t\ttriangulate_polygon(poly_d, [poly[c], b], triangles);\n\t} else if (poly.length) {\n\t\tuse_tri = new DelaunayTriangle(a, b, poly[c]);\n\t}\n\t// EndIf\n\t//If P is not empty then\n\tif (use_tri) {\n\t\t// Add triangle with vertices a, b, c into T\n\t\ttriangles.push(use_tri);\n\t} else if (poly.length) {\n\t\tvar force_tri = new DelaunayTriangle(a, b, poly[c]);\n\t\tforce_tri.forced = true;\n\t\ttriangles.push(force_tri);\n\t}\n\t//EndIf\n\treturn triangles;\n}", "function getRelevantNeighbors(tile) {\n var neighborIndexX = tile.indexX > originXIndex ? tile.indexX - 1 : tile.indexX + 1,\n neighborIndexY = tile.indexY > originYIndex ? tile.indexY - 1 : tile.indexY + 1;\n\n/* if(tile.indexX === originXIndex) neighborIndexX = null;\n if(tile.indexY === originYIndex) neighborIndexY = null;*/\n\n var neighbors = {\n diagonal: {},\n vertical: {},\n horizontal: {}\n };\n\n for(var j=0; j<tiles.length; j++) {\n var current = tiles[j];\n if(current.indexX === neighborIndexX && current.indexY === tile.indexY)\n neighbors.horizontal = current;\n if(current.indexY === neighborIndexY && current.indexX === tile.indexX)\n neighbors.vertical = current;\n if(current.indexX === neighborIndexX && current.indexY === neighborIndexY)\n neighbors.diagonal = current;\n }\n\n return neighbors;\n}", "function Triangulate (m_points, holes)\n{\n\tvar indices = new Array();\n\n\tif (getWinding (m_points) < 0)\n\t\tm_points.reverse();\n\n//\tRemove holes by joining them with the outer edge\n\tif (holes.length)\n\t{\n\t\tfor (hh=0; hh<holes.length; hh++)\n\t\t{\n\t\t\tvar h = holes[hh];\n\t\t\tif (getWinding (h) > 0)\n\t\t\t\th.reverse();\n\n\t\t\tvar maxpt = 0;\n\t\t\tfor (i=1; i<h.length; i++)\n\t\t\t{\n\t\t\t\tif (h[i][0] > h[maxpt][0] || (h[i][0] == h[maxpt][0] && h[i][1] < h[maxpt][1]))\n\t\t\t\t\tmaxpt = i;\n\t\t\t}\n\t\t\twhile (maxpt > 0)\n\t\t\t{\n\t\t\t\th.push (h.shift());\n\t\t\t\tmaxpt--;\n\t\t\t}\n\t\t}\n\t\tholes.sort(function(a,b){ if (a[0][0] > b[0][0]) return -1; if (a[0][0] < b[0][0]) return 1; return (a[0][1] < b[0][1]) ? 1 : -1; });\n\t\tfor (hh=0; hh<holes.length; hh++)\n\t\t{\n\t\t\tvar h = holes[hh];\n\t\t\tvar maxpt = 0;\n\n\t\t\tfor (i=1; i<h.length; i++)\n\t\t\t\tif (h[i][0] > h[maxpt][0] || (h[i][0] == h[maxpt][0] && h[i][1] < h[maxpt][1]))\n\t\t\t\t\tmaxpt = i;\n\n\t\t\tvar d2 = null;\n\t\t\tvar closestpt;\n\t\t\tfor (i=0; i<m_points.length; i++)\n\t\t\t{\n\t\t\t\tif (m_points[i][0] > h[maxpt][0])\n\t\t\t\t{\n\t\t\t\t\tif (d2 == null)\n\t\t\t\t\t{\n\t\t\t\t\t\td2 = ClosestPointOnLine (h[maxpt], [ m_points[i], m_points[(i+1) % m_points.length] ] )[1];\n\t\t\t\t\t\tclosestpt = i;\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tvar dd2 = ClosestPointOnLine (h[maxpt], [ m_points[i], m_points[(i+1) % m_points.length] ] )[1];\n\t\t\t\t\t\tif (dd2 < d2)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\td2 = dd2;\n\t\t\t\t\t\t\tclosestpt = i;\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//\tdrawLine (h[maxpt], m_points[closestpt]);\n\t\t//\tapp.activeDocument.pathItems.ellipse (h[maxpt][1]+2+hh,h[maxpt][0]-2-hh,4+2*hh,4+2*hh);\n\t\t//\tapp.activeDocument.pathItems.ellipse (m_points[closestpt][1]+2+hh,m_points[closestpt][0]-2-hh,4+2*hh,4+2*hh).fillColor = gray;\n\n\t\t//\talert (m_points.length);\n\t\t\tm_points.splice (closestpt, 0, [ m_points[closestpt][0],m_points[closestpt][1]+0.1 ]);\n\t\t\tclosestpt++;\n\t\t\th.splice (maxpt, 0, [ h[maxpt][0],h[maxpt][1] ]);\n\t\t\th[maxpt][1] -= 0.1;\n\t\t\tfor (var i=maxpt; i >=0; i--)\n\t\t\t{\n\t\t\t\tm_points.splice (closestpt, 0, h[i]);\n\t\t\t}\n\t\t\tfor (var i=h.length-1; i > maxpt; i--)\n\t\t\t{\n\t\t\t\tm_points.splice (closestpt, 0, h[i]);\n\t\t\t}\n\t\t//\talert (m_points.length);\n\t\t//\tdrawLine (m_points[0], m_points[m_points.length-1]);\n\t\t//\tfor (i=0; i<m_points.length-1; i++)\n\t\t//\t\tdrawLine (m_points[i], m_points[i+1]);\n\t\t}\n\t}\n\n\tvar n = m_points.length;\n\tif (n < 3)\n\t\treturn indices;\n\n//\tapp.activeDocument.pathItems.add().setEntirePath (m_points);\n\n\tvar V = new Array(n);\n\tif (Area(m_points) > 0)\n\t{\n\t\tfor (var v = 0; v < n; v++)\n\t\t\tV[v] = v;\n\t} else\n\t{\n\t\tfor (var v = 0; v < n; v++)\n\t\t\tV[v] = (n - 1) - v;\n\t}\n\n\n\tvar nv = n;\n\tvar count = 2 * nv;\n\tfor (var m = 0, v = nv - 1; nv > 2; )\n\t{\n\t\tif ((count--) <= 0)\n\t\t\treturn indices;\n\n\t\tvar u = v;\n\t\tif (nv <= u)\n\t\t\tu = 0;\n\t\tv = u + 1;\n\t\tif (nv <= v)\n\t\t\tv = 0;\n\t\tvar w = v + 1;\n\t\tif (nv <= w)\n\t\t\tw = 0;\n\n\t\tif (Snip(u, v, w, nv, V, m_points))\n\t\t{\n\t\t\tvar a, b, c, s, t;\n\t\t\ta = V[u];\n\t\t\tb = V[v];\n\t\t\tc = V[w];\n\t\t\tindices.push(a);\n\t\t\tindices.push(b);\n\t\t\tindices.push(c);\n\t\t\tm++;\n\t\t\tfor (s = v, t = v + 1; t < nv; s++, t++)\n\t\t\t\tV[s] = V[t];\n\t\t\tnv--;\n\t\t\tcount = 2 * nv;\n\t\t}\n\t}\n\n\tindices.reverse();\n\treturn indices;\n}", "function filterUnconnectedNodes() {\n //Create a node -> node id mapping\n node_by_id = {};\n nodes.forEach(function (d) {\n node_by_id[d.id] = d;\n }); //Filter out any edges that were associated to the nodes filtered earlier\n\n edges = edges.filter(function (d) {\n return node_by_id[d.source] && node_by_id[d.target];\n }); //////////// Remove unconnected countries and regions //////////\n //What connections remain per node\n\n linked_to_id = {};\n edges.forEach(function (d) {\n //Save all of the connections to a specific node\n if (!linked_to_id[d.source]) linked_to_id[d.source] = [];\n if (!linked_to_id[d.target]) linked_to_id[d.target] = [];\n linked_to_id[d.source].push(node_by_id[d.target]);\n linked_to_id[d.target].push(node_by_id[d.source]);\n }); //forEach\n //Filter out any countries that are not connected to any remaining elements\n\n var connected_ids = nodes.filter(function (d) {\n return d.type === 'element';\n }).map(function (d) {\n return linked_to_id[d.id].filter(function (n) {\n return n.type === 'country';\n }).map(function (n) {\n return n.id;\n });\n });\n connected_ids = Object(_babel_runtime_corejs2_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_5__[\"default\"])(new _babel_runtime_corejs2_core_js_set__WEBPACK_IMPORTED_MODULE_4___default.a([].concat.apply([], connected_ids))); //Filter the non-connected ones out\n\n nodes = nodes.filter(function (d) {\n if (d.type === 'country') return connected_ids.indexOf(d.id) >= 0 ? true : false;else return true;\n }); //filter\n //Create a new node -> node id mapping\n\n node_by_id = {};\n nodes.forEach(function (d) {\n node_by_id[d.id] = d;\n }); //Filter out any edges that were associated to the nodes filtered above\n\n edges = edges.filter(function (d) {\n return node_by_id[d.source] && node_by_id[d.target];\n }); //////////// Remove unconnected remaining concepts //////////\n //Filter out any node that is a concept and has only 1 degree\n\n nodes = nodes.filter(function (d) {\n if (d.type === 'concept') {\n var degree_now = edges.filter(function (l) {\n return l.source == d.id || l.target == d.id;\n }).length;\n return degree_now > 1 ? true : false;\n } else {\n return true;\n }\n }); //forEach\n //Redo node mapping\n\n node_by_id = {};\n nodes.forEach(function (d) {\n node_by_id[d.id] = d;\n }); //Filter out any edges that were associated to the nodes filtered above\n\n edges = edges.filter(function (d) {\n return node_by_id[d.source] && node_by_id[d.target];\n });\n } //function filterUnconnectedNodes", "function filterUnconnectedNodes() {\n //Create a node -> node id mapping\n node_by_id = {};\n nodes.forEach(function (d) {\n node_by_id[d.id] = d;\n }); //Filter out any edges that were associated to the nodes filtered above\n\n edges = edges.filter(function (d) {\n return node_by_id[d.source] && node_by_id[d.target];\n }); //////////// Remove unconnected countries and regions //////////\n //What connections remain per node\n\n linked_to_id = {};\n edges.forEach(function (d) {\n //Save all of the connections to a specific node\n if (!linked_to_id[d.source]) linked_to_id[d.source] = [];\n if (!linked_to_id[d.target]) linked_to_id[d.target] = [];\n linked_to_id[d.source].push(node_by_id[d.target]);\n linked_to_id[d.target].push(node_by_id[d.source]);\n }); //forEach\n //Filter out any countries & whc's that are not connected to any remaining elements\n\n var connected_ids = nodes.filter(function (d) {\n return d.type === 'element';\n }).map(function (d) {\n return linked_to_id[d.id].filter(function (n) {\n return n.type === 'country' || n.type === 'whc';\n }).map(function (n) {\n return n.id;\n });\n });\n connected_ids = Object(_babel_runtime_corejs2_helpers_esm_toConsumableArray__WEBPACK_IMPORTED_MODULE_5__[\"default\"])(new _babel_runtime_corejs2_core_js_set__WEBPACK_IMPORTED_MODULE_4___default.a([].concat.apply([], connected_ids))); //Filter the non-connected ones out\n\n nodes = nodes.filter(function (d) {\n if (d.type === 'country' || d.type === 'whc') return connected_ids.indexOf(d.id) >= 0 ? true : false;else return true;\n }); //filter\n //Create a new node -> node id mapping\n\n node_by_id = {};\n nodes.forEach(function (d) {\n node_by_id[d.id] = d;\n }); //Filter out any edges that were associated to the nodes filtered above\n\n edges = edges.filter(function (d) {\n return node_by_id[d.source] && node_by_id[d.target];\n }); //////////// Remove unconnected remaining nodes //////////\n //Filter out any node that has < 1 degrees that isn't a whc\n\n nodes = nodes.filter(function (d) {\n var degree_now = edges.filter(function (l) {\n return l.source == d.id || l.target == d.id;\n }).length;\n return degree_now > 1 || d.type === 'whc' ? true : false;\n }); //forEach\n //Redo node mapping\n\n node_by_id = {};\n nodes.forEach(function (d) {\n node_by_id[d.id] = d;\n }); //Filter out any edges that were associated to the nodes filtered above\n\n edges = edges.filter(function (d) {\n return node_by_id[d.source] && node_by_id[d.target];\n });\n } //function filterUnconnectedNodes", "function mapa2(){\n // Crea un arreglo con los nodos visitados hasta ahora.\n var nodes = [\n \n {id: 1, label: 'Brasil'},\n {id: 2, label: 'Finlandia'},\n\n ];\n\n // Crea un arreglo con las conexiones entre los nodos.\n var edges = [\n {from: 1, to: 2},\n ];\n // Crea un arreglo con los nodos activos.\n var activeNode = [ 2 ];\n mapa( nodes, edges, activeNode );\n }", "function _default(topology) {\n var junctions = (0, _join.default)(topology),\n coordinates = topology.coordinates,\n lines = topology.lines,\n rings = topology.rings,\n next,\n i,\n n;\n\n for (i = 0, n = lines.length; i < n; ++i) {\n var line = lines[i],\n lineMid = line[0],\n lineEnd = line[1];\n\n while (++lineMid < lineEnd) {\n if (junctions.has(coordinates[lineMid])) {\n next = {\n 0: lineMid,\n 1: line[1]\n };\n line[1] = lineMid;\n line = line.next = next;\n }\n }\n }\n\n for (i = 0, n = rings.length; i < n; ++i) {\n var ring = rings[i],\n ringStart = ring[0],\n ringMid = ringStart,\n ringEnd = ring[1],\n ringFixed = junctions.has(coordinates[ringStart]);\n\n while (++ringMid < ringEnd) {\n if (junctions.has(coordinates[ringMid])) {\n if (ringFixed) {\n next = {\n 0: ringMid,\n 1: ring[1]\n };\n ring[1] = ringMid;\n ring = ring.next = next;\n } else {\n // For the first junction, we can rotate rather than cut.\n rotateArray(coordinates, ringStart, ringEnd, ringEnd - ringMid);\n coordinates[ringEnd] = coordinates[ringStart];\n ringFixed = true;\n ringMid = ringStart; // restart; we may have skipped junctions\n }\n }\n }\n }\n\n return topology;\n}", "function _default(topology) {\n var junctions = (0, _join.default)(topology),\n coordinates = topology.coordinates,\n lines = topology.lines,\n rings = topology.rings,\n next,\n i,\n n;\n\n for (i = 0, n = lines.length; i < n; ++i) {\n var line = lines[i],\n lineMid = line[0],\n lineEnd = line[1];\n\n while (++lineMid < lineEnd) {\n if (junctions.has(coordinates[lineMid])) {\n next = {\n 0: lineMid,\n 1: line[1]\n };\n line[1] = lineMid;\n line = line.next = next;\n }\n }\n }\n\n for (i = 0, n = rings.length; i < n; ++i) {\n var ring = rings[i],\n ringStart = ring[0],\n ringMid = ringStart,\n ringEnd = ring[1],\n ringFixed = junctions.has(coordinates[ringStart]);\n\n while (++ringMid < ringEnd) {\n if (junctions.has(coordinates[ringMid])) {\n if (ringFixed) {\n next = {\n 0: ringMid,\n 1: ring[1]\n };\n ring[1] = ringMid;\n ring = ring.next = next;\n } else {\n // For the first junction, we can rotate rather than cut.\n rotateArray(coordinates, ringStart, ringEnd, ringEnd - ringMid);\n coordinates[ringEnd] = coordinates[ringStart];\n ringFixed = true;\n ringMid = ringStart; // restart; we may have skipped junctions\n }\n }\n }\n }\n\n return topology;\n}" ]
[ "0.57377946", "0.57224864", "0.54936296", "0.54827476", "0.54695934", "0.5370923", "0.5347439", "0.5266831", "0.5174743", "0.5151248", "0.50833434", "0.50790626", "0.50676394", "0.50285983", "0.4911989", "0.4893868", "0.48369232", "0.4821082", "0.4805183", "0.47834313", "0.47751355", "0.47748217", "0.4764494", "0.47627547", "0.47589815", "0.47517413", "0.4743375", "0.47384086", "0.4733348", "0.4733348" ]
0.82703316
0
Point GetPoint(const int& index);
GetPoint(index) { return this.points_.at(index); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function computeInOffsetByIndex(x, y, index) {\n var outx = x + 15;\n var outy = y + 47 + index * 20;\n\n return { x: outx, y: outy };\n}", "function pointAt(index) {\n var y = Math.floor(index/w) * 1.5;\n var x = ((index + y/3) % w) * rt3;\n return {x: x, y: y};\n }", "get point() {}", "at(index) {}", "get(idx) {\n\n }", "function indexAt(point) {\n var row = Math.ceil(Math.floor(point.y/0.75)/2);\n var col = Math.ceil(Math.floor(2*point.x/rt3 - row)/2);\n col = (col % w + w) % w;\n if(row < 0 || row >= h){return undefined}\n return w * row + col;\n }", "function getPoint(x, gf) { return { 'x': x, 'y': gf(x)*-1 }; }", "function pointToIndex(x, y) {\n return x + y * map.cols;\n }", "getAt(idx) {\n\n }", "pointAt(i, result) {\n if (i >= 0 && i < this._points.length) {\n if (result) {\n result.setFrom(this._points[i]);\n return result;\n }\n return this._points[i].clone();\n }\n return undefined;\n }", "function index(obj,i) {return obj[i]}", "function index(obj,i) {return obj[i];}", "function getCellFromPoint(point) {\n var x = Math.floor(point.x / tile_size);\n var y = Math.floor(point.y / tile_size);\n var index = x + y * width;\n \n return grid.getChildAt(index);\n}", "function point(x, y) {\n return { x, y };\n}", "Point(x, y) {\n\t\treturn { x: x, y: y };\n\t}", "getVertex(index, out = null) {\n const { _coords } = this\n if (index >= 0 && index < this.numVertices) {\n out = out || new Point()\n out.setTo(_coords[index * 2], _coords[index * 2 + 1])\n return out\n } else throw new RangeError('[RangeError] Invalid index: ' + index)\n }", "locate( index ) {\n if( index < this.start ) index = this.start\n else if(index>this.end) index = this.end\n this.pos = index\n return this.current()\n }", "function getRealPosition( index ) {\n var stage = app.getDrawStage();\n return { 'x': stage.offset().x + index.x / stage.scale().x,\n 'y': stage.offset().y + index.y / stage.scale().y };\n }", "function findPointByCoordinates(x, y) {\n let point = null;\n pointsCollection.forEach(function (value) {\n if (value.getPosition().x === x && value.getPosition().y === y) {\n point = value;\n }\n });\n return point;\n}", "GetArrayElementAtIndex() {}", "function Point(x, y) {\n return {x: x, y: y}\n}", "function getPosX(nIndex){\n\treturn 30+(90 * nIndex);\n}", "getElementAtIndex(index) {\n return this.data[index];\n }", "function getPt(index) {\n\t var x = xa.c2p(d[index].x),\n\t y = ya.c2p(d[index].y);\n\t if(x === BADNUM || y === BADNUM) return false;\n\t return [x, y];\n\t }", "function findPointByCoords(point)\n{\n for (var i=0; i < points.length; i++)\n if (points[i].getRealX() == point.getRealX() && points[i].getRealY() == point.getRealY())\n return points[i];\n\n return null;\n}", "function getPt(index) {\n var x = xa.c2p(d[index].x);\n var y = ya.c2p(d[index].y);\n if(x === BADNUM || y === BADNUM) return false;\n return [x, y];\n }", "function getPt(id) {\n for (var i=0; i<points.length; i++) { \n if (points[i].id == id) { return points[i]; }\n }\n}", "function Point(x, y) {\n return {x, y}\n}", "function determinePosition(x, y) {\n return new Point(x, y);\n}", "function getPt(index) {\n var x = xa.c2p(d[index].x),\n y = ya.c2p(d[index].y);\n if(x === BADNUM || y === BADNUM) return false;\n return [x, y];\n }" ]
[ "0.7117669", "0.7050225", "0.6788835", "0.6652022", "0.6570453", "0.6551717", "0.64776117", "0.644447", "0.64352006", "0.6357566", "0.63529104", "0.6349525", "0.62419534", "0.6203459", "0.6184747", "0.6174074", "0.6151645", "0.6124953", "0.6121487", "0.6117371", "0.6091552", "0.6073114", "0.60708296", "0.60663927", "0.60420436", "0.6039518", "0.603486", "0.6023788", "0.6023488", "0.6010938" ]
0.76091355
0
for rounding to decimal places
function roundit(num,dex) { return parseFloat(num).toFixed(dex); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function roundToDecimalPlace(value, decimal) {\r\n var factor = Math.pow(10, decimal);\r\n roundedValue = ((Math.round(value * factor))/factor).toFixed(decimal);\r\n return roundedValue;\r\n}", "function RoundDecimals(float) {\n var roundedFloat = Math.round(float * 10) / 10;\n return roundedFloat;\n console.log(\"roundedFloat: \" + roundedFloat);\n}", "function round(value)\n{\n\tvalue = +value.toFixed(3)\n\treturn value;\n}", "function round(control) \n{ \n ans = control.value * 1000 \n ans = Math.round(ans /10) + \"\" \n while (ans.length < 3) {ans = \"0\" + ans} \n len = ans.length \n ans = ans.substring(0,len-2) + \".\" + ans.substring(len-2,len)\n control.value = ans; \n}", "function round(decimal) {\n return parseFloat(Math.round(decimal * 100) / 100).toFixed(2);\n}", "function round(number,decimal_points) {\r\n\tif (number == null) return 'NaN';\r\n\tif (!decimal_points || decimal_points == null) return Math.round(number);\r\n\tvar exp = Math.pow(10, decimal_points);\r\n\tnumber = Math.round(number * exp) / exp;\r\n\treturn parseFloat(number.toFixed(decimal_points));\r\n}", "function round_to(x, num) {\n\tvar r = x.toFixed(num) + \"\";\n\tif (r.match('.'))\n\t\treturn r.replace(/\\.?0+$/,'');\n\treturn r;\n}", "function roundIt(value) {\n let places = 100;\n if (value < 100) {\n places = 10000;\n } else if (value < 0.001) {\n places = 1000000;\n }\n return Math.round((value + Number.EPSILON) * places) / places;\n }", "function Round(x){\nif (x <0.001) {x = \"<0.001\"};\nif (x >1) {x = \"1.0000\"};\nreturn x;\n}", "function round(value, fixed){\n\t\treturn parseFloat(Math.round(value * 10.0) / 10.0).toFixed(fixed);\n\t}", "function round( nr ) {\n\t\treturn Math.round( 100*nr )/100;\n\t}", "function round(num) {\n return Math.round((num + Number.EPSILON) * 100) / 100;\n}", "function round(num) {\n return Math.round(num * 100) / 100;\n }", "function roundNum(num){\n return Math.round(num * 10) / 10;\n }", "function roundme(val) {\n return val;\n }", "function round_x(x) {\n var out = parseFloat(parseFloat(x).toFixed(DECIMALS));\n return out;\n}", "function round(num){\n return Math.round(num*10) / 10;\n }", "function digits(value, round) {\n return parseFloat(value.toFixed(round));\n }", "roundPrice(price) {\n var roundedPrice = Math.round(price * 100) / 100;\n return roundedPrice.toFixed(2);\n }", "function roundToNearestHundreth(x){\n return (x).toFixed(2);\n }", "function roundDec(no, dec)\r\n{\r\n var flotante = parseFloat(no);\r\n var result = Math.round(flotante*Math.pow(10,dec))/Math.pow(10,dec);\r\n if(isNaN(flotante)){\r\n return '';\r\n }else{\r\n return result;\r\n }\r\n}", "function round_to_sigfigs(val, sigfigs){\n return Number.parseFloat(val.toPrecision(sigfigs));\n}", "round(value) {\n return Math.round(value);\n }", "function round(number) {\n return Math.round(number * 100) / 100;\n}", "_round(x) {\n\t\treturn Math.round( x * 1000) / 1000;\n\t}", "function roundMoney(val) {\n return Math.round(val * 100) / 100;\n}", "function fc_Round(num, dec) {\n num = (num+\"\")\n num = num.substring(0,num.indexOf(\".\")+dec+1); \n var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);\n return result;\n}", "function myRound(val,places) {\n\tvar c = 1;\n\tfor (var i = 0; i < places; i++)\n\t\tc *= 10;\n\treturn Math.round(val*c)/c;\n}", "function round(number, precision)\r\n{\r\n divisor = Math.pow(10, precision);\r\n return Math.round(number * divisor) / divisor;\r\n}", "function round_number(number,decimals){\n return Math.round(number*Math.pow(10,decimals))/Math.pow(10,decimals)\n }" ]
[ "0.711695", "0.7111932", "0.7093263", "0.69894254", "0.6966892", "0.69576955", "0.6957056", "0.69513786", "0.69166195", "0.68901163", "0.68674254", "0.68340963", "0.6805976", "0.67917323", "0.6777266", "0.67765355", "0.67475647", "0.6742682", "0.67203707", "0.67139536", "0.6683925", "0.66813236", "0.6648232", "0.66479015", "0.6646287", "0.66384333", "0.6629736", "0.6615871", "0.6612216", "0.65941983" ]
0.7337368
0
Grab float data from distances.txt
async function grabAllData(){ let dataArr=[]; let data = await fetchAndDecodeFloatData("https://geoweb.princeton.edu/people/sk8609/DEVearthscopeoceans/data/FloatInfo/distances.txt", 'text'); tempArr = data.split('\n'); for(let i=0; i<tempArr.length;i++){ let splitArr = tempArr[i].split(' '); dataArr.push([splitArr[0], parseInt(splitArr[1]), parseInt(splitArr[2]), parseFloat(splitArr[3]), parseInt(splitArr[4])]); } return dataArr }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async function grabIndData(Float){\n let dataArr=[];\n let data = await fetchAndDecodeFloatData(`https://geoweb.princeton.edu/people/sk8609/DEVearthscopeoceans/data/FloatInfo/${Float}.txt`, 'text');\n tempArr = data.split('\\n');\n for(let i=0; i<tempArr.length;i++){\n let splitArr = tempArr[i].split(' ');\n dataArr.push([parseInt(splitArr[0]), parseFloat(splitArr[1]), parseInt(splitArr[2]), parseInt(splitArr[3]), parseFloat(splitArr[4]), parseInt(splitArr[5])]);\n }\n return dataArr;\n }", "async function getFloatData(name) {\n clearMarkers();\n\n let url;\n if (name === \"all\") {\n url = \"https://geoweb.princeton.edu/people/simons/SOM/all.txt\";\n } else {\n url = \"https://geoweb.princeton.edu/people/simons/SOM/\" + name + showTail;\n }\n\n let dataPromise = fetchAndDecodeFloatData(url, 'text');\n let values = await Promise.all([dataPromise]);\n return values[0];\n\n }", "function readFloat(){\n checkLen(4);\n var flt = buf.readFloatLE(pos);\n pos += 4;\n return formSinglePrecision(flt);\n }", "getPointsFromTXTData(data){\n\t\tlet lines = data.split(/\\r|\\n/); // this regex is to make sure we don't run into the windows vs mac newline issue\n\t\tlet lista = [];\n\t\tlet listb = [];\n\t\tfor(let i = 0; i < lines.length; i++){\n\t\t\tif(lines[i].length && lines[i][0] != '#'){\n\t\t\t\ttry{\n\t\t\t\t\tlet points = lines[i].split(',');\n\t\t\t\t\tlet to_a = parseFloat(points[0]);\n\t\t\t\t\tlet to_b = parseFloat(points[1]);\n\t\t\t\t\tif(to_a && to_b){\n\t\t\t\t\t\tlista.push(to_a);\n\t\t\t\t\t\tlistb.push(to_b);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch(err){\n\t\t\t\t\tconsole.log(err);\n\t\t\t\t\tconsole.log('skipped line: '+data[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn this.cleanDataOrdering([lista, listb]);\n\t}", "function split_and_shift_float( objline )\n {\n var vals = objline.split(\" \");\n vals.shift();\n return vals.map( function( v ) { return parseFloat(v); } );\n }", "testFileWithDenseProperData() {\n const max_distance = 100;\n const pointsWithinDistance = findPointsWithinRange('./data/proper_dense_test_data.txt', SOURCE_COORDINATES, max_distance);\n\n const expectedResult = [{ name: 'Joby Rudefort', user_id: 3 },\n { name: 'Taco Bell', user_id: 67 },\n { name: 'Dominos', user_id: 88 }];\n\n assert.deepStrictEqual(pointsWithinDistance, expectedResult, 'testFileWithDenseProperData: Function to filter points by using Haversine Distance is not giving proper results');\n console.log('testFileWithDenseProperData => Successfully Completed');\n }", "function readLocator () {\r\n orb.readLocator(function (err, data) {\r\n if (err) {\r\n console.error(\"error: \", err);\r\n readLocator();\r\n } else {\r\n console.log(data.xpos);\r\n console.log(data.ypos);\r\n var dist = Math.sqrt(Math.pow((data.xpos - x), 2) + Math.pow((data.ypos - y), 2));\r\n x = data.xpos;\r\n y = data.ypos;\r\n socket.emit('newDistanceSphero', {dist: dist});\r\n }\r\n });\r\n}", "function getNumbersFromData(data) {\n\tvar numbers = [];\n\tvar lines = data.split('\\n');\n\tfor (var l = 0; l < lines.length; l++) {\n\t\tvar nums = lines[l].split(' ');\n\t\tfor (var n = 0; n < nums.length; n++) {\n\t\t\tvar value = parseFloat(nums[n]);\n\t\t\tnumbers.push(value);\n\t\t}\n\t}\n\treturn numbers;\n}", "function distanceConversion(meters) {\n return Math.round((meters * 0.000621371) * 10) / 10;\n}", "async readfloat(pos) {\n\t\tlet readbytes = 4;\n\t\treturn this.readbin(readbytes, pos - 1, 'float');\n\t}", "function parseDistance(err, distances) {\n if (!err){\n let result = (distances.rows[0].elements[0].duration.text);\n let response = {\n text: \"The trip will take \" + result\n }\n sendMessage(sender_psid, response)\n }\n }", "testFileWithSparseProperData() {\n const max_distance = 500;\n const pointsWithinDistance = findPointsWithinRange('./data/proper_sparse_test_data.txt', SOURCE_COORDINATES, max_distance);\n\n const expectedResult = [{ name: 'Jillian Gun', user_id: 802 },\n { name: 'Zedekiah Grelik', user_id: 866 },\n { name: 'Yoshi Brownhill', user_id: 885 },\n { name: 'Curcio Manwell', user_id: 981 },\n { name: 'Saraann Hainge', user_id: 1595 }];\n\n assert.deepStrictEqual(pointsWithinDistance, expectedResult, 'testFileWithSparseProperData: Function to filter points by using Haversine Distance is not giving proper results');\n console.log('testFileWithSparseProperData => Successfully Completed');\n }", "function parser(d) { \n\td.density = parseFloat(String(d.density).replace(',','')); \n\treturn d.density\n}", "function substringEnergyToFloat(value) {\n\tif (value != null) {\n\t\tvar grab = parseFloat(\n\t\t\t\tvalue.substring(value.indexOf('=') + 1, value.indexOf('H') - 1))\n\t\t\t\t.toPrecision(12); // Energy = -5499.5123027313 Hartree\n\t\tgrab = grab * 2625.50;\n\t\tgrab = Math.round(grab * 1000000000000) / 1000000000000;\n\t}\n\treturn grab;\n}", "function getAcceleration(data) {\n let array = [];\n $.each(data, function(index, item){\n let x = 0;\n let y = 0;\n let z = 0;\n\n if(item != null) {\n let x_str = (item.split(',')[0]).substring(0);\n x = parseInt(x_str);\n let y_str = (item.split(',')[1]);\n y = parseInt(y_str);\n let z_str = (item.split(',')[2]).split('\"')[0];\n z = parseInt(z_str);\n\n let sqrt = Math.sqrt(x*x + y*y + z*z);\n array.push(sqrt);\n }\n });\n return array;\n}", "function extractXandY (line) {\n var line = line.replace(/[^0-9]/g, \" \");\n var lineSplits = line.split(\" \");\n var datas = [];\n for(var index=0; index < lineSplits.length; index++) {\n if(lineSplits[index].length != 0) {\n datas.push(parseInt(lineSplits[index]));\n }\n }\n\n return datas;\n }", "static readDistance(sketchObject, sourceDistance) {\n for (let i = 0; i < sketchObject.objects.length; i++) {\n const path = sketchObject.objects[i];\n if (path.uniqueIdentifier === sourceDistance.path) {\n let distance = new SketchDistance(\n path,\n sourceDistance.element,\n sourceDistance.element + 1\n );\n distance.offset = {\n x: sourceDistance.offset.X,\n y: sourceDistance.offset.Y\n };\n SketchUtils.copyTextAttributes(sourceDistance, distance);\n return distance;\n }\n }\n }", "function StringArrayToFloatArray( data ) {\n\tvar dataArr = [];\n\n\tfor (var i = 0; i < data.length; i++) {\n\t\tdataArr = data[i].split(\"/\");\n\n\t\tdataArr[0] = parseFloat(dataArr[0]);\n\t\t// If contains a '/', do the division and save the float into pos 0\n\t\tif (dataArr.length == 2) {\n\t\t\tdataArr[1] = parseFloat(dataArr[1]);\n\t\t\tdataArr[0] = dataArr[0] / dataArr[1];\n\t\t}\n\n\t\t// Set the correct final float value in the input array\n\t\tdata[i] = dataArr[0];\n\t}\n\n\treturn data;\n}", "function findDistances(userPoint) {\n // initialize the array of distances\n var distances = [];\n // loop through the markers finding the GPS points for each\n for (i = 0; i < markerData.length; i++) {\n var pointLat = parseFloat(markerData[i].lat);\n var pointLng = parseFloat(markerData[i].lng);\n var markerPoint = {\n lat: pointLat,\n lng: pointLng\n }\n // calculate the distance between user and each point\n distances[i] = Haversine(userPoint, markerPoint);\n }\n return distances;\n}", "function computeDistances() {\n if (serverData == null) return;\n var firstReading = false;\n if (distances == null) {\n distances = new Array(serverData.length);\n for (var index = 0; index < serverData.length; index++) distances[index] = 0; \n firstReading = true;\n }\n //alert(serverData.length);\n for (var index = 0; index < serverData.length; index++) {\n var currentDistance = computeDistance(currentPosition, serverData[index]);\n if(firstReading && index == 0){\n closestPoint = serverData[0]; \n closestDistance = currentDistance; \n }\n // get the absolute distance from the point\n var oldDistance = distances[index] < 0 ? -distances[index] : distances[index];\n // if 0, set the new distance\n if(oldDistance == 0){\n distances[index] = currentDistance;\n }else{\n // if approaching that point, set a positive distance\n if(oldDistance > currentDistance){\n distances[index] = currentDistance;\n }else{\n // if moving further away, set a negative distance\n distances[index] = -currentDistance;\n }\n }\n\n if ((distances[index] >= 0) && (distances[index] < closestDistance)) {\n closestDistance = distances[index];\n closestPoint = serverData[index];\n } \n }\n // check the closest point\n checkClosestPoint();\t\t\n //alert(closestDistance + 'lat: '+ closestPoint.latitude + 'long: ' + closestPoint.longitude);\n}", "function distance(source, target){\n\tlet fields = Math.sqrt(Math.pow(source[1]-target[1],2)+Math.pow(source[0]-target[0],2));\n\treturn fields;\n\t}", "function getFloatFromExchangeResult(html){\n\t\t\t\t\t\t\t\t\n\tvar html = \"<div class='target-label'><div title='Wear Value' style='position:relative;right:-43px;top:-0.8em'>0.20041191577911376953</div></div>\";\n\tvar $ = cheerio.load(html);\n\tconsole.log(\"RESULTAT: \", $('.target-label').text());\n\treturn $('.target-label').text();\n}", "async GetValueFloat(id, command) {\n var packet = new DpsPacket(id, DpsConstants.sender, command, [0,0,0,0,0,0,0,0]);\n var result = await this.PacketIO(packet);\n if ((result && (result.sender != id || result.command != command)) || result == null) return null;\n else {\n var buf = new ArrayBuffer(8);\n var view = new DataView(buf);\n for (var i = 0; i < 4; i++) {\n view.setUint8(3 - i, result.data[i]);\n }\n return view.getFloat32(0);\n }\n }", "function initialize() {\n directionsService = new google.maps.DirectionsService()\n directionsDisplay = new google.maps.DirectionsRenderer();\n var chicago = new google.maps.LatLng(41.850033, -87.6500523);\n var mapOptions = {\n zoom:7,\n mapTypeId: google.maps.MapTypeId.ROADMAP,\n center: chicago\n }\n \n map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);\n marker=new google.maps.Marker();\n directionsDisplay.setMap(map);\n //map.addListener('click',function(e){getClosestRoad(e.latLng)});\n \n var rawFile = new XMLHttpRequest();\n rawFile.open(\"GET\", \"coords_test.csv\", false);\n rawFile.onreadystatechange = function ()\n {\n if(rawFile.readyState === 4)\n {\n if(rawFile.status === 200 || rawFile.status == 0)\n {\n var allText = rawFile.responseText;\n var allTextLines = allText.split(/[\\n,]/);\n for(i=0; i<allTextLines.length; i++) {\n coor_list.push(parseFloat(allTextLines[i])); \n }\n }\n }\n }\n rawFile.send(null);\n// var test_thing = [41.436, -86.058145];\n// alert(coor_list[40001]);\n// var coords = [{lat: coor_list[40000], lng: coor_list[40001]},{lat: coor_list[40002], lng: coor_list[40003]}, {lat: coor_list[40004], lng: coor_list[40005]}, {lat: coor_list[40006], lng: coor_list[40007]}];\n \n //{lat: 41.273877, lng: -86.058145},{lat: 47.753731, lng: -125.359647}, {lat: 41.273877, lng: -85.058145}];\n //[{lat: 47.753731, lng: -125.359647}] //js_coords.coords; //\n \n }", "function arrayStringToFloat(table) {\n data = [];\n for (i = 0; i < table.length; i++) {\n table[i] = table[i].replace(\",\", \".\");\n data.push(table[i]);\n }\n return data;\n}", "function parseDistanceMatrix(response) {\n var origins = response.originAddresses;\n var destinations = response.destinationAddresses;\n\n let ansArr = [];\n for (var i = 0; i < origins.length; i++) {\n var results = response.rows[i].elements;\n for (var j = 0; j < results.length; j++) {\n var element = results[j];\n ans = {};\n ans.distanceText = element.distance.text;\n ans.durationText = element.duration.text;\n ans.distance = element.distance.value; // in meters\n ans.duration = element.duration.value; // in second\n ans.from = origins[i];\n ans.to = destinations[j];\n ansArr.push(ans);\n }\n }\n return ansArr;\n}", "function readDistance(xml,index) {\n //var xmlText = new XMLSerializer().serializeToString(xml);\n var xmlDoc = xml.responseXML;\n var x = xmlDoc.getElementsByTagName('Distance')[0];\n var y = x.childNodes[0];\n //console.log(typeof b);\n\n var a = xmlDoc.getElementsByTagName('BaseTime')[0];\n var b = a.childNodes[0];\n distance= xmlToString(y);\n traveltime=xmlToString(b);\n var distanceint=parseInt(distance,10);\n var traveltimeint=parseInt(traveltime,10);\n console.log(distanceint);\n console.log(distance);\n console.log(traveltime);\n cpInfoArray[index][6]=(distanceint/1000);\n cpInfoArray[index][7]=(traveltimeint/60);\n \n updateCarParkButtons();\n}", "function readDouble(){\n checkLen(8);\n var dbl = buf.readDoubleLE(pos);\n pos += 8;\n return dbl.toString();\n }", "function pointToPointDistances(r) {\n for (let index_route = 0; index_route < r.length - 1; index_route++) {\n distancesPointToPoint[index_route] = distanceInMeter(r[index_route], r[index_route + 1]);\n }\n}", "get distance() {}" ]
[ "0.6266799", "0.58963054", "0.55773324", "0.5534366", "0.5458368", "0.5421081", "0.5285426", "0.52673453", "0.5235717", "0.52149403", "0.5201872", "0.51820207", "0.5136303", "0.5061028", "0.5058574", "0.5051513", "0.50466347", "0.50391406", "0.5024825", "0.496351", "0.49588543", "0.49497175", "0.4940734", "0.49277315", "0.48858473", "0.4848352", "0.48481458", "0.48235914", "0.4815545", "0.4795796" ]
0.6627487
0
youtube thumbnail (base) quality = empty or : 0, 1, 2, 3, low0, low1, low2, low3, medium0, medium1, medium2, medium3, high0, high1, high2, high3, max0, max1, max2, max3
function get_youtube_thumbnail(url, quality) { if (url) { var video_id, thumbnail, result; result = url.match( /(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/user\/\S+|\/ytscreeningroom\?v=))([\w\-]{10,12})\b/ ); video_id = result[1]; if (video_id) { let quality_key = YTQuality[quality]; if (quality_key == undefined || quality_key == "") { quality_key = "sddefault"; } var thumbnail = "https://img.youtube.com/vi/" + video_id + "/" + quality_key + ".jpg"; return thumbnail; } } return false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "set quality(value) {}", "get quality() {}", "function getQuality(quality)\n{\n\tquality=decodeURIComponent(quality);\n\tif(quality.toLowerCase()==\"small\")\n\t\treturn \"240p\";\n\tif(quality.toLowerCase()==\"medium\")\n\t\treturn \"360p\";\n\tif(quality.toLowerCase()==\"large\")\n\t\treturn \"480p\";\n\tif(quality.toLowerCase()==\"hd720\")\n\t\treturn \"720p\";\n\tif(quality.toLowerCase()==\"hd1080\")\n\t\treturn \"1080p\";\n}", "static getYoutubeThumb(videoId, size) {\n if (videoId.startsWith(\"http\")) {\n let regExp = /^.*(youtu\\.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=|\\&v=)([^#\\&\\?]*).*/;\n let match = videoId.match(regExp);\n if (match && match[2].length === 11) {\n videoId = match[2];\n }\n else {\n console.log(\"======== ERROR: can not get videoId from: \", videoId);\n }\n }\n if (videoId === null) {\n return \"http://img.youtube.com/vi/noimagefound/default.jpg\";\n }\n size = (size == undefined) ? 'big' : size;\n if (size === 'small') {\n return \"http://img.youtube.com/vi/\" + videoId + \"/default.jpg\";\n }\n return 'http://img.youtube.com/vi/' + videoId + '/0.jpg';\n }", "function a(e){var t=e.file,n=e.thumbnailMaxWidth,r=e.thumbnailMaxHeight,a=e.enableThumbnails;return t.type&&t.type.startsWith(\"image\")?(t=t instanceof Blob?t:new Blob([t]),new s.default(function(e,n){var r=new Image;r.onload=function(){e(r)},r.onerror=n,r.src=URL.createObjectURL(t)}).then(function(e){var o=(0,c.default)(e,\"height\",\"width\");if(!a)return[null,o,null];var s=i(o,n,r),u=document.createElement(\"canvas\");u.width=s.width,u.height=s.height;var d=u.getContext(\"2d\");(0,l.orient)({orientation:t&&t.image?t.image.orientation:\"\",img:e,x:0,y:0,width:s.width,height:s.height,ctx:d},t);for(var p=u.toDataURL(\"image/png\").split(\",\"),f=atob(p[1]),h=new ArrayBuffer(f.length),m=new DataView(h),v=0;v<f.length;v++)m.setUint8(v,f.charCodeAt(v));return[h,o,s]})):s.default.resolve()}", "function findThumbs(n) {\n\t\t\tif (n > 4 && n <= 8) {\n\t\t\t\treturn 320;\n\t\t\t}\n\t\t\telse if (n > 8) {\n\t\t\t\treturn 640;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}", "determineThumbnail() {\n if (this.props.book.imageLinks && this.props.book.imageLinks.smallThumbnail) {\n return `${this.props.book.imageLinks.smallThumbnail}`;\n } else {\n return `${process.env.PUBLIC_URL + '/images/missing-thumbnail.PNG'}`;\n }\n }", "function getQuality()\r\n {\r\n return quality;\r\n }", "function thumbnail(object) {\nreturn $(\"<div>\")\n .addClass(\"thumb\")\n .css(\"background-image\", \"url(\" + object.webImage.url.replace(\"s0\", \"s128\") +\")\");\n}", "function getImageThumbnail(index_to_get) {\n if((imgur_list.length > 0) && (index_to_get < imgur_list.length)) {\n console.log(\"Getting Image: \" + imgur_list[index_to_get].link);\n var image_url = imgur_list[index_to_get].link;\t// The Full Size Image\n\n var n = image_url.lastIndexOf(\".\");\n var ext = image_url.slice(n).toUpperCase();\n //ext=\".PNG\";\n console.log(\"Extension = '\"+ext+\"'\");\n\n var get_thumbnail = true;\n if(get_thumbnail) {\n // The Medium Thumbnail (320x320 or close to)\n // Also, thumbnails on imgur are always jpg\n image_url = image_url.slice(0, n) + \"m.jpg\";\n console.log(\"Getting Thumbnail: \" + image_url);\n getJpegImage(image_url);\n } else {\n switch (ext) {\n case \".PNG\":\n getPngImage(image_url);\n break;\n case \".JPG\":\n case \".JPEG\":\n getJpegImage(image_url);\n }\n }\n } else {\n console.log(\"Index bigger than array!\");\n }\n}", "function onPlayerReadyHigh(event) {\n\tevent.target.setPlaybackQuality('hd1080');\n}", "function setQuality(\r\n quality_)\r\n {\r\n quality = quality_;\r\n }", "function loadThumbnail(id){\n return '<img class=\"youtube-thumb\" src=\"//i.ytimg.com/vi/' + id + '/hqdefault.jpg\"><div class=\"play-button\"></div>';\n }", "function setThumbnail(args) {\n let slider = page.getViewById(\"thumbnailSlider\");\n thumbnail = viewModel.get(\"sliderValue\");\n let thumbnailVideo = page.getViewById(\"thumbnailVideo\");\n thumbnailVideo.seekToTime(thumbnail);\n}", "function isQuality(spec){return spec.q>0;}", "function isQuality(spec){return spec.q>0;}", "function isQuality(spec){return spec.q>0;}", "function isQuality(spec){return spec.q>0;}", "is_thumbnail_safe() {\n return true\n }", "function setQuality(quality) {\n spriteLoader.switchQuality(quality)\n .then(()=>{\n // We call this outside of spriteLoader as not all games will use reels, but all should be using CustomSprites\n Reel.redraw();\n });\n}", "getVideoThumbnail(video, w, h, out) {\n nativeTools.getVideoThumbnail(video, w, h, out);\n }", "static GetImageScale(width, height, base)\n {\n if(width > height)\n {\n return [Math.round((width * base) / height), base]\n }\n else\n {\n return [base, Math.round((height * base) / width)]\n }\n }", "setThumbnail(thumbnailURL, useThumbnail) {\n if (useThumbnail) {\n this.loadThumbnail(thumbnailURL, (texture) => {\n this.useThumbnail = useThumbnail;\n this.thumbnailURL = thumbnailURL;\n const thumbnail = this.generateThumbnail(texture);\n this.setThumbnailSprite(thumbnail);\n });\n }\n }", "function decodeQuality(value) {\n assert(typeof value === \"string\");\n return coretypes_1.quality.decode(value).toString();\n}", "function decodeQuality(value) {\n assert(typeof value === \"string\");\n return coretypes_1.quality.decode(value).toString();\n}", "function getThumbnailURL(d){\n if (d.video_id > 0){\n return \"/uploads/\" + d.video_id + \"/thumbnails/\" + d.extracted_frame_number + \".jpg\";\n } else {\n return \"/uploads/refresh_to_load.jpg\";\n }\n }", "function onLowResImageSuccess(e){\n\t// Swap the thumbnail image with the low one\n\t$.media.image = e.data;\n}", "_getThumbnail(link) {\n var video_id = link.split(\"v=\")[1];\n var ampersandPosition = video_id.indexOf(\"&\");\n if (ampersandPosition !== -1) {\n video_id = video_id.substring(0, ampersandPosition);\n }\n return video_id;\n }", "function createResizedImages( resize_url ) {\n\n resize_url = resize_url.replace(/^http:\\/\\//i, 'https://');\n\n return {\n type: 'zoho',\n has_low_quality_versions: true,\n src: resize_url,\n high: resize_url + '=s1920-rj-l85',\n med: resize_url + '=s1200-rj-l85',\n low: resize_url + '=s768-rj-l85'\n };\n\n}", "constructor (storage) {\n this.cache = settings.thumbnails.cache;\n this.sizes = settings.thumbnails.sizes;\n this.storage = storage;\n\n if (this.cache) {\n logging.verbose('Thumbnail cache enabled');\n } else {\n logging.verbose('Thumbnail cache disabled');\n }\n }" ]
[ "0.6840879", "0.6385369", "0.6355864", "0.629729", "0.61170053", "0.59873223", "0.5962237", "0.5956563", "0.5861067", "0.5855809", "0.5819462", "0.5806379", "0.5793285", "0.5788339", "0.573508", "0.573508", "0.573508", "0.573508", "0.5729142", "0.5709786", "0.5707149", "0.5693848", "0.5667745", "0.5660508", "0.5660508", "0.56585926", "0.5647379", "0.56374216", "0.5571199", "0.5570602" ]
0.69274455
0
This function is called when the "Add selected items to cart" button in clicked The purpose is to build the HTML to be displayed (a Paragraph) We build a paragraph to contain the list of selected items, and the total price
function selectedItems(){ var ele = document.getElementsByName("product"); var chosenProducts = []; var c = document.getElementById('displayCart'); c.innerHTML = ""; // build list of selected item var para = document.createElement("P"); para.innerHTML = "You selected : "; para.appendChild(document.createElement("br")); para.appendChild(document.createElement("br")); for (let i = 0; i < ele.length; i++) { if (ele[i].checked) { para.appendChild(document.createTextNode(ele[i].value)); para.appendChild(document.createElement("br")); para.appendChild(document.createElement("br")); chosenProducts.push(ele[i].value); } } // add paragraph and total price c.appendChild(para); c.appendChild(document.createTextNode("Total Price is $" + getTotalPrice(chosenProducts))); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function selectedItems() {\n\n\tvar c = document.getElementById('displayCart')\n\tc.innerHTML = ''\n\n\n\t// build list of selected item\n\tvar para = document.createElement('P')\n\tpara.innerHTML = 'You selected : '\n\tpara.appendChild(document.createElement('br'))\n\tfor (i = 0; i < cart.length; i++) {\n\t\tpara.appendChild(document.createTextNode(cart[i].name))\n\t\tpara.appendChild(document.createElement('br'))\n\t}\n\n\t// add paragraph and total price\n\tc.appendChild(para)\n\tc.appendChild(\n\t\tdocument.createTextNode('Total Price is ' + getTotalPrice(cart))\n\t)\n}", "function selectedItems(){\n\t\n\tvar ele = document.getElementsByName(\"product\");\n\tvar chosenProducts = [];\n\t\n\tvar c = document.getElementById('displayCart');\n\tc.innerHTML = \"\";\n\t\n\t// build list of selected item\n\tvar para = document.createElement(\"P\");\n\tpara.innerHTML = \"You selected: \";\n\tpara.appendChild(document.createElement(\"br\"));\n\tpara.appendChild(document.createElement(\"br\"));\n\tfor (i = 0; i < ele.length; i++) { \n\t\tif (ele[i].checked) {\n\t\t\tpara.appendChild(document.createTextNode(ele[i].value));\n\t\t\tpara.appendChild(document.createElement(\"br\"));\n\t\t\tpara.appendChild(document.createElement(\"br\"));\n\t\t\tchosenProducts.push(ele[i].value);\n\t\t}\n\t}\n\t\t\n\t// add paragraph and total price\n\tc.appendChild(para);\n\tc.appendChild(document.createTextNode(\"Total Price: $\" + getTotalPrice(chosenProducts).toFixed(2)));\n\t\t\n}", "function updateCartPreview() {\n // TODO: Get the item and quantity from the form\n // TODO: Add a new element to the cartContents div with that information\n const item = selectElement.options[selectElement.selectedIndex].text;\n const quantity = parseInt(document.getElementById('quantity').value);\n createTheElement('p', `Item: ${item} \\u00A0 \\u00A0 \\u00A0 Quantity: ${quantity}`, cartContents);\n}", "function selectedItems(product){\n\n\n\tvar ele = document.getElementById(\"panier-flex\");\n\tchosenProducts.push(product.price);\n\n\tvar prof = document.createElement(\"div\");\n\tprof.className = \"panier_prod\";\n\n\tvar proff = document.createElement(\"p\");\n\tproff.className = \"prod\";\n\tproff.innerHTML = product.name;\n\n\nvar hre = document.createElement(\"hr\");\n\tprof.appendChild(proff);\n\tprof.appendChild(hre);\n\tconsole.log(ele);\n\tele.appendChild(prof);\n\n\tvar price = document.getElementById(\"prixe\");\n\tprice.innerHTML = getTotalPrice(chosenProducts);\n\n\n\n\n\n\n\t//sc.appendChild(document.createTextNode(\"Total Price is \" + getTotalPrice(chosenProducts)));\n\n}", "function addToCartClicked(e){\n const button = e.target;\n const item = button.closest(\".detalle__compra\");\n const itemPrecio = Number(item.querySelector(\".precio\").textContent.replace(\"$\",\"\"));\n const itemProdId = Number(item.querySelector(\".idProdCarrito\").textContent);\n const precios = item.querySelector(\"#precios\");\n const cantidad = item.querySelector(\"#cantidad\");\n itemCantidad= Number(cantidad.value)+1;\n cantidad.value = itemCantidad;\n nuevasub = nuevasub +itemPrecio;\n sumaItem(itemProdId,itemCantidad);\n precios.innerHTML = `<p>\n $${cantidad.value * itemPrecio}\n </p>`\n subTotal.innerHTML = `<h3>Subtotal</h3>\n <p>$${nuevasub}</p>`\n total.innerHTML = `<h2>Total</h2>\n <p>$${nuevasub}</p>`\n}", "function addProductToCart(buttonID) {\r\n let cart = document.getElementById(\"rightDiv\");\r\n switch (buttonID) {\r\n case \"addSeedmix\":\r\n qty = document.getElementById(\"SeedmixQty\").value;\r\n addHTML = document.createElement(\"p\");\r\n addHTML.className=\"orderedProducts\";\r\n addHTML.innerHTML = \"Seedmix: \"+qty+\" Price: <strong class='price'>\" +(2*Number(qty)) +\"</strong>\";\r\n console.log(addHTML);\r\n cart.insertBefore(addHTML, document.getElementById(\"checkOut\"));\r\n break;\r\n case \"addEnergypellet\":\r\n qty = document.getElementById(\"EnergypelletQty\").value;\r\n addHTML = document.createElement(\"p\");\r\n addHTML.className=\"orderedProducts\";\r\n addHTML.innerHTML = \"Energypellet: \"+qty+\" Price: <strong class='price'>\"+(3*Number(qty)) +\"</strong>\";\r\n console.log(addHTML);\r\n cart.insertBefore(addHTML, document.getElementById(\"checkOut\"));\r\n break;\r\n case \"addTux\":\r\n qty = document.getElementById(\"TuxQty\").value;\r\n addHTML = document.createElement(\"p\");\r\n addHTML.className=\"orderedProducts\";\r\n addHTML.innerHTML = \"Tux: \"+qty+\" Price: <strong class='price'>\"+(3*Number(qty)) +\"</strong>\";\r\n console.log(addHTML);\r\n cart.insertBefore(addHTML, document.getElementById(\"checkOut\"));\r\n break;\r\n }\r\n}", "function addOn() {\n var addItem = document.getElementById(\"addItem\").value;\n var addPrice = document.getElementById(\"addPrice\").value;\n\n// send to html\n\nvar el = document.createElement('li');\nel.textContent = addItem;\ndocument.getElementById(\"list\").appendChild(el);\n\nvar el2 = document.createElement('li');\nel2.textContent = addPrice;\ndocument.getElementById(\"price\").appendChild(el2);\n\nprice += addPrice;\n// var sum = document.createElement('p');\n// sum.textContent = price;\n// document.getElementById(\"total\").appendChild(sum);\n}", "function addItemZero(){\n $(\"#cartItems\").append(\"<ul>\"+purchaseOptions[0]+\"</ul>\");\n myCartTotal = myCartTotal + itemPrices[0];\n $(\"#cartTotal\").text(\"Your new cart total is: $\" + myCartTotal.toFixed(2));\t \n}", "function updateCartPreview() {\n // TODO: Get the item and quantity from the form\n let quantity1 = document.getElementById('quantity');\n let iteam1 = document.getElementById('items');\n\n \n // TODO: Add a new element to the cartContents div with that information\n let cartContent = document.getElementById('cartContents');\n let pEle= document.createElement('p');\n pEle.textContent= quantity1.value +\" : \"+ iteam1.value; \n cartContent.appendChild(pEle);\n}", "function renderCart() {\n var prices = [];\n\n cartContent.innerHTML = \"\";\n\n cart.items.forEach(function(item) {\n var itemPrice = parseFloat(item.price.replace(\"$ \", \"\")),\n itemQuantity = parseInt(item.quantity);\n\n prices.push(itemPrice * itemQuantity);\n cartContent.innerHTML += \"<li class='cart-item' id='cart-\" + item.id + \"'><p class='cart-item-name'>\" + item.name + \"</p><img class='cart-item-img' src='http://vignette1.wikia.nocookie.net/clubpenguin/images/5/5f/Red_X.png/revision/latest?cb=20120514130731'><input type='number' class='inset quantity' min='0' max='50' value=\" + item.quantity + \"></li>\";\n })\n\n var totalPrice = prices.reduce(function(a, b) {\n return a + b;\n }, 0);\n\n cart.total = totalPrice.toFixed(2);\n cartTotal.innerHTML = \"$ \" + cart.total;\n }", "function addToCart() {\n if ( inputNameEl.value !== '' ) {\n cartEl.innerHTML += '<li id=\"' + currentIndex + '\"><label class=\"control control--checkbox\">' + inputNameEl.value + '<input type=\"checkbox\"/><div class=\"control__indicator\"></div></label> <button class=\"removeBtn\" onclick=\"removeFromCart(' + currentIndex + ')\">x</button></li>';\n currentIndex += 1;\n //total += parseInt(inputPriceEl.value);\n //totalEl.innerHTML = total ;\n inputNameEl.value = \"\";\n //inputPriceEl.value = \"\";\n }\n}", "function onClickActionAddCartItem(e){\n\t\t\n\t\tvar html = '';\n\t\tlet itemId = parseInt(e.currentTarget.dataset.itemid);\n\t\tvar it = DB.getItemInfo( itemId );\n\t\tvar content = CashShop.ui.find('.container-cart');\n\t\tconst itemCart = CashShop.cartItem.find(i => i.itemId === itemId);\n\t\tvar item = [];\n\t\tvar tab = 0;\n\t\tif(CashShop.activeCashMenu !== 'SEARCH_RESULT'){\n\t\t\titem = CashShop.cashShopListItem[CashShop.activeCashMenu].items.find(i => i.itemId === itemId);\n\t\t\ttab = CashShop.cashShopListItem[CashShop.activeCashMenu].tabNum;\n\t\t} else {\n\t\t\titem = CashShop.csListItemSearchResult.find(i => i.itemId === itemId);\n\t\t\ttab = item.tab;\n\t\t}\n\n\t\tif(content.find('#cart-list .items .no-items').length > 0){\n\t\t\tcontent.find('#cart-list .items .no-items').remove();\n\t\t}\n\n\t\tif(CashShop.cartItem.length > 4 && typeof itemCart === 'undefined'){\n\t\t\t//only 5 item can store in cart\n\t\t\tUIManager.showMessageBox( '5 Item can only stored in cart!', 'ok');\n\t\t\treturn;\n\t\t}\n\n\t\tif(item.amount >= 99){\n\t\t\tUIManager.showMessageBox( 'Max Quantity 99!', 'ok');\n\t\t\tChatBox.addText( 'Max Quantity 99!', ChatBox.TYPE.ERROR);\n\t\t\treturn;\n\t\t}\n\n\t\tif(typeof itemCart === 'undefined'){\n\t\t\titem.amount = 1;\n\t\t\titem.tab = tab;\n\t\t\tCashShop.cartItem.push(item);\n\t\t\thtml = `<li class=\"item\" data-index=\"${itemId}\">\n\t\t\t\t\t<div class=\"inner-item-dt\">\n\t\t\t\t\t\t<div class=\"delete-item\"><button>x</button></div>\n\t\t\t\t\t\t<div class=\"item-dt-img\"></div>\n\t\t\t\t\t\t<div class=\"item-dt-desc\">\n\t\t\t\t\t\t\t<div class=\"item-desc-top\">${it.identifiedDisplayName}</div>\n\t\t\t\t\t\t\t<div class=\"item-counter\">\n\t\t\t\t\t\t\t\t<div class=\"item-cnt\">${item.amount}</div>\n\t\t\t\t\t\t\t\t<button class=\"counter-btn item-cnt-up\" data-index=\"up\"></button>\n\t\t\t\t\t\t\t\t<button class=\"counter-btn item-cnt-down\" data-index=\"down\"></button>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class=\"item-desc-price\">\n\t\t\t\t\t\t\t\t<div class=\"icon-gold-coin\"></div>\n\t\t\t\t\t\t\t\t<span>${item.price}</span>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</li>`;\n\t\t\tcontent.find('.items').append(html);\n\t\t\tClient.loadFile( DB.INTERFACE_PATH + 'collection/' + ( it.identifiedResourceName ) + '.bmp', function(data){\n\t\t\t\tcontent.find('.item[data-index=\"'+ itemId +'\"] .item-dt-img').css('backgroundImage', 'url('+ data +')');\n\t\t\t});\n\n\t\t\tClient.loadFile( DB.INTERFACE_PATH + 'cashshop/img_shop_itemBg2.bmp', function(data){\n\t\t\t\tcontent.find('.item-counter').css('backgroundImage', 'url('+ data +')');\n\t\t\t});\n\t\t} else {\n\t\t\titemCart.amount += 1;\n\t\t\tcontent.find('.items .item[data-index=\"'+itemId+'\"] .item-cnt').html(itemCart.amount);\n\t\t}\n\t\tCashShop.cartItemTotalPrice = CashShop.cartItem.map(item => item.price * item.amount).reduce((prev, next) => prev + next);\n\t\tCashShop.ui.find('.container-cart-footer .item-desc-price span').html(CashShop.cartItemTotalPrice);\n\t}", "function addToCart(image, name, price, qty, btnAdd_id) {\n\n var unitP = 1 * price.trim().slice(1)\n totalP = totalP + unitP\n updateTotal(totalP)\n\n //if item is already in the cart, just update it\n if (qty > 1) {\n var priceofProduct = qty * price.trim().slice(1)\n document.getElementById(\"item_\" + btnAdd_id).children[1].innerText = qty\n document.getElementById(\"item_\" + btnAdd_id).children[3].innerText = \"$\" + priceofProduct\n }\n\n // else add the item to the cart\n else {\n var listItem = document.createElement('li')\n listItem.style.listStyle = 'none'\n listItem.setAttribute(\"id\", \"item_\" + btnAdd_id)\n listItem.setAttribute(\"class\", \"list-group-item d-flex justify-content-between lh-condensed\")\n\n var detail = `\n <div>\n <span ><img src=${image} style=\"width: 60px; height: 70px;\"><small class=\"my-0\"> ${name}</small></span>\n </div>\n \n <span ><small>${qty}</small></span>\n <span >\n <button class=\"btn\" style=\"background-color:RoyalBlue\" id=\"trash\" onclick=\"trash(this)\"><i class=\"fa fa-trash\" style=\"color: white;\"></i></button>\n <button class=\"btn\" onclick=\"addI(${btnAdd_id})\" style=\"background-color:forestgreen\" ><i class=\"fa fa-plus\" style=\"color: white;\"></i></button>\n <button class=\"btn\" id=\"item_\" onclick=\"removeI(id+${btnAdd_id})\" style=\"background-color:rgb(235, 86, 86)\"><i class=\"fa fa-minus\" style=\"color: white; \"></i></button> \n </span>\n <span ><small>${price}</small></span> \n `\n \n listItem.innerHTML = detail\n var list = document.querySelector('#yourCart')\n list.insertBefore(listItem, list.lastElementChild)\n }\n\n}", "function Products(products) {\n document.getElementById(\"products\").innerHTML = products\n .map((product, index) => {\n let amount = sessionStorage.getItem(product.id);\n if (amount) {\n addToCart(product.id, amount);\n }\n itemQuantity[product.id] = 0;\n\n return `<div class=\"productList\">\n \n <p>${product.name}</p>\n <img src=\"${product.imgUrl}\" alt=\"image of ${product.name}\">\n <p>${product.description}</p>\n\n <button id=\"moreDetailsButton\" onclick = \"moreDetails(${\n product.id\n })\">${detailsButton}</button>\n <br>\n <select id=select-${index} onchange=\"getValue(${index})\">\n <option value=\"0\">--Quantity--</option>\n <option value=\"1\">1</option>\n <option value=\"2\">2</option>\n <option value=\"3\">3</option>\n <option value=\"4\">4</option>\n <option value=\"5\">5</option>\n <option value=\"6\">6</option>\n <option value=\"7\">7</option>\n <option value=\"8\">8</option>\n <option value=\"9\">9</option>\n <option value=\"10\">10</option>\n </select>\n <button onclick=\"addToCartAndStore(${product.id})\">Add to Cart</button>\n \n </div>\n <hr>`;\n })\n .join(\" \");\n}", "function updateCartPreview() {\n // TODO: Get the item and quantity from the form\n var product = event.target.items.value;\n var quantity = event.target.quantity.value;\n // TODO: Add a new element to the cartContents div with that information\n var divEl = document.getElementById('cartContents');\n var ulEl = document.createElement('ul');\n divEl.appendChild(ulEl);\n\n var liEl =document.createElement('li');\n liEl.textContent = 'Items Qty';\n ulEl.appendChild(liEl);\n\n for(var i = 0; i < items.length; i ++) {\n console.log(items);\n var liEl = document.createElement('li');\n liEl.textContent = `${product} ${quantity}`; \n }\n ulEl.appendChild(liEl); \n}", "function addSelectedItemToCart() {\n // TODO: suss out the item picked from the select list\n // TODO: get the quantity\n // TODO: using those, add one item to the Cart\n const product = selectElement.options[selectElement.selectedIndex].text;\n const quantity = parseInt(document.getElementById('quantity').value);\n cart.addItem(product, quantity);\n}", "function updateCartPreview() {\n // DONE: Get the item and quantity from the form\n // DONE: Add a new element to the cartContents div with that information\n\n var itemAddedDisplayEl = document.getElementById('cartContents');\n var itemsEl = document.getElementById('items').value;\n var quantityEl = document.getElementById('quantity').value;\n itemAddedDisplayEl.textContent ='Item: ' + itemsEl + ' Quantity: ' + quantityEl;\n}", "function handleCart(eachProduct) {\n var cartItemsContainer = document.querySelector('.cart-container .cart-items');\n var itemToAdd = '<li class=\"list-group-item\"><div class=\"item d-flex justify-content-between\" id=\"%id%\"><div class=\"item-img\"><img src=\"img/%img-path%\" alt=\"item-img\" width=\"40\"></div><div class=\"item-name text-left text-truncate\">%item-name%</div><div class=\"item-price text-left text-muted\">%item-price%</div><div class=\"each-item-numbers w-50\"><select class=\"numberOfItems\"><option value=\"1\">1</option><option value=\"2\">2</option><option value=\"3\">3</option><option value=\"4\">4</option><option value=\"5\">5</option><option value=\"5+\">5+</option></select></div><img src=\"../img/icons/x-circle.svg\" class=\"remove-cart-item\"></div></li>';\n\n console.log(eachProduct)\n\n var item = itemToAdd.replace('%id%', eachProduct.id);\n item = item.replace('%img-path%', eachProduct.img);\n item = item.replace('%item-name%', eachProduct.name);\n item = item.replace('%item-price%', eachProduct.price);\n cartItemsContainer.innerHTML += item;\n }", "function printList(){\n for(var i=0;i<listLength;i++){\n $(\"ul\").append(\"<li>\"+purchaseOptions[i]+\". . . . . . $\" + itemPrices[i].toFixed(2) +\" \"+\"</li></br>\");\n $(\"ul\").append(\"<input type='button' id =\\\"\"+(i)+\"\\\"\"+\"value='Add to Cart'>\");\n }\n}", "function submitNewStuff() {\n \tvar itemAdd = document.getElementById(\"itemInput\").value; //naming an added item to a variable\n \tvar priceAdd = document.getElementById(\"priceInput\").value; //naming an added price to a variable\n\n\n\tvar unorderedList = document.getElementById('shoppinglist'); //creates a variable for the unordered list with the ID 'shoppinglist' in the HTML\n\tvar myList = document.createElement('li'); //creates list items for each grocery item & price, creates a variable of it to call later\n\tvar displayTotal = document.getElementById('totalDisplay'); //creates a variable for the grocery item total from the <p> tag in the HTML\n\n \tpriceAdd = parseInt(priceAdd); //making sure the price is a number\n\n\tmyList.innerHTML=itemAdd + \"- \\$\" + priceAdd; //adds the grocery items and prices into the html in 'li' format\n\tunorderedList.appendChild(myList); //adds the li to the unordered list\n\n\n \ttotal += priceAdd;\n }", "function addSelectedItemToCart() {\n // suss out the item picked from the select list\n let product = document.getElementById('items').value;\n let quantity = document.getElementById('quantity').value;\n cart.addItem(product, quantity);\n\n // console.log(newCartItem);\n // console.log(cart);\n\n // get the quantity\n // using those, add one item to the Cart\n}", "function addItem() {\n // Creating all the items\n let listWrapper = document.createElement(\"div\");\n let productName = document.createElement(\"span\");\n let productPrice = document.createElement(\"span\");\n let productAmount = document.createElement(\"div\");\n let productlabel = document.createElement(\"label\");\n let productInput = document.createElement(\"input\");\n let productTotal = document.createElement(\"div\");\n let subTotal = document.createElement(\"label\");\n let subTotalValue = document.createElement(\"span\"); \n let productDelete = document.createElement(\"div\");\n let deleteButton = document.createElement(\"button\"); \n\n\n // Getting the values from New Items input\n let createName = document.getElementById(\"create-name\");\n let createPrice = document.getElementById(\"create-price\");\n productName.innerHTML = createName.value;\n productPrice.innerHTML = createPrice.value;\n\n\n // Setting classes, IDs and Values to the items\n listWrapper.className = \"list-wrapper\";\n listWrapper.id = \"list-wrapper\";\n productName.className = \"product-name\";\n productPrice.className = \"product-price\";\n productAmount.className = \"product-amount\";\n productlabel.innerHTML = \"Qty\";\n productInput.innerHTML = 0;\n productInput.className = \"quantity\";\n productTotal.className = \"produt-total\";\n subTotal.innerHTML = \"Subtotal: \";\n subTotalValue.className = \"sub-total\";\n subTotalValue.value = 0;\n \n productDelete.className = \"product-delete\"\n deleteButton.className = \"btn btn-delete\"\n deleteButton.innerHTML = \"Delete Row\";\n \n // Adding the structure\n document.getElementById(\"shopping-wrapper\").appendChild(listWrapper);\n listWrapper.appendChild(productName);\n listWrapper.appendChild(productPrice);\n listWrapper.appendChild(productAmount);\n productAmount.appendChild(productlabel);\n productAmount.appendChild(productInput);\n listWrapper.appendChild(productTotal);\n productTotal.appendChild(subTotal);\n productTotal.appendChild(subTotalValue);\n listWrapper.appendChild(productDelete);\n productDelete.appendChild(deleteButton);\n}", "function updateCartPreview() {\n // TODO: Get the item and quantity from the form\n let product = document.getElementById('items').value;\n let quantity = document.getElementById('quantity').value;\n // TODO: Add a new element to the cartContents div with that information\n let cartContents = document.querySelector('#cartContents');\n let newContent = document.createElement('p');\n newContent.innerText = `${quantity}: ${product}`;\n cartContents.appendChild(newContent);\n\n}", "function displayCart(teddies) {\n\n // Selection de la classe ou je vais injecter le code HTML\n const positionPanier = document.querySelector(\"#table-produits-panier\")\n\n let html = \"\";\n teddies.forEach(teddy => \n html += `\n <tbody id=\"cart-tablebody\" class=\"font-weight-bold\">\n <tr class=\"\">\n <td class=\"text-center\">\n <span class=\"text-danger font-weight-bold text-center\">${teddy.name}\n </td>\n <td class=\"text-center\">\n ${teddy.qty}\n </td>\n <td class=\"text-center price-teddy\">\n ${price(teddy.price * teddy.qty)}\n </td>\n <td class=\"text-center\">\n <button class=\"btn btn-danger btnDelete\">Supprimer</button>\n </td>\n </tr>\n </tbody>\n `\n )\n \n\n //Injection html dans la page panier\n positionPanier.innerHTML = html \n deleteProduct()\n deleteAllProduct()\n priceTotal(teddies)\n sendForm()\n}", "function addProduct() {\n el('cart').style.display = 'inline-block';\n el('order').style.display = 'none';\n const title = el('products').value;\n const quantity = parseFloat(el('quantity').value);\n cart[title] = (cart[title] || 0) + quantity;\n saveCart();\n showCart();\n}", "function addSelectedItemToCart() {\n // TODO: suss out the item picked from the select list\n // TODO: get the quantity\n // TODO: using those, add one item to the Cart\n var suss = document.getElementById('cartContents');\n var print = document.createElement('p');\n suss.appendChild(print);\n var selectedItem = document.getElementById('items');\n var quantityItem = document.getElementById('quantity');\n print.textContent= `${quantityItem.value} quantities of ${selectedItem.value}`;\n var x =new cart(selectedItem.value,quantityItem.value);\n counter++;\n console.log(counter);\n var setLocalStorage = JSON.stringify(cartArray);\n localStorage.setItem('cartItems', setLocalStorage);\n \n}", "function updateCartPreview() {\n // TODO: Get the item and quantity from the form\n // TODO: Add a new element to the cartContents div with that information\n}", "function addSelectedItemToCart() {\n // TODO: suss out the item picked from the select list\n var product = event.target.items.value;\n var quantity = event.target.quantity.value;\n cart.addItem(product, quantity);\n counter++;\n console.log(counter);\n // TODO: get the quantity\n // TODO: using those, add one item to the Cart\n}", "function addItemToCart(myFormObject){\n ////clearing out our total div by using the innerHTML method to reset our div to a blank string so the list doesn't grow exponentially\n document.getElementById(\"yourGrandTotal\").innerHTML = '';\n //clearing out our unordered list by using innerHTML method to reset our UL to a blank string so the list doesn't grow exponentially\n document.getElementById(\"ShoppingList\").innerHTML = '';\n //created variables called \"itemName\" & \"itemPrice\" to store the itemName and itemPrice of the formObj.elements\n var itemName = myFormObject.elements[\"itemName\"].value;\n var itemPrice = myFormObject.elements[\"itemPrice\"].value;\n //created a new variable. set this variable equal to a groceryListItem, taking in as parameters our previously defined itemName and itemPrice variables\n var itemNameAndPrice = new groceryListItem(itemName, itemPrice);\n //used push method to place the itemNameAndPrice inside the array\n shoppingListArray.push(itemNameAndPrice);\n //calls functions to calculate the total and updates HTML list\n calculateTotal();\n updateHTMLList();\n}", "function addToCartClicked(event) {\n document.querySelector(\".custom\").style.display = \"block\";\n var button = event.target;\n var shopItem = button.parentElement.parentElement;\n var title = shopItem.getElementsByClassName(\"shop-item-title\")[0].innerText;\n var price = shopItem.getElementsByClassName(\"shop-item-price\")[0].innerText;\n var imageSrc = shopItem.getElementsByClassName(\"shop-item-image\")[0].src;\n items = {\n title,\n price,\n imageSrc,\n };\n\n // check if the total is updating\n}" ]
[ "0.7670149", "0.7193816", "0.7171806", "0.70372707", "0.6934285", "0.68798023", "0.6806421", "0.67738956", "0.67636615", "0.66968435", "0.6645513", "0.6634592", "0.6633475", "0.66128176", "0.6612306", "0.66095614", "0.66038877", "0.65893686", "0.6585778", "0.65762156", "0.6572341", "0.65569574", "0.65496916", "0.65485746", "0.6545333", "0.65340143", "0.6530901", "0.6522865", "0.6521562", "0.6517936" ]
0.7303101
1
The method to get covers from Google book API based on ISBN and title of the books
async getCover(isbn, title) { try { let response = await axios.get( 'https://www.googleapis.com/books/v1/volumes?q=title=' +encodeURIComponent(title) +isbn + "&key=AIzaSyClcFkzl_nDwrnCcwAruIz99WInWc0oRg8" ); return response.data.items[0].volumeInfo.imageLinks.smallThumbnail; } catch (error) { console.log(error); return ""; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "static fetchBooksFromGoogle(searchInput){ //searchInput from Content.js\n return fetch(`https://www.googleapis.com/books/v1/volumes?q=${searchInput}`)\n .then(response => response.json())\n .then(json => {\n return json.items.map(item => this.createBook(item)) //returns an array of objects created from the createBook fn.\n })\n }", "async getRenderItems(token) {\n let books = [];\n var isbnid;\n var coverUrl;\n for (i = 0; i < this.state.idTypes.length; i++) {\n if (this.state.idTypes[i].name == \"ISBN\") {\n isbnid = this.state.idTypes[i].id;\n break;\n }\n }\n var i;\n var id;\n for (i in this.state.books) {\n let book = this.state.books[i];\n for (j = 0; j < book.identifiers.length; j++) {\n id = book.identifiers[j].identifierTypeId;\n let value = book.identifiers[j].value.split(\" \");\n value = value[0];\n if (id == isbnid) {\n coverUrl = await this.getCover('&isbn=' + value, book.title);\n console.log(coverUrl);\n if (coverUrl != \"\") {\n console.log(book.title);\n books.push(book);\n books[books.length - 1].cover = coverUrl;\n break;\n }\n }\n else { // If a book don't have ISBN, get cover by title only\n console.log(book.title);\n books.push(book);\n coverUrl = await this.getCover('', book.title);\n console.log(coverUrl);\n books[books.length - 1].cover = coverUrl;\n break;\n }\n }\n }\n // data load complete\n this.setState({\n books: books,\n isLoadingComplete: true,\n })\n }", "function getBooksFromGoogleAPI(searchURL){\n\t$.ajax({\n\t\turl: searchURL,\n\t\tsuccess: function(data){\n\t\t\tvar temphtml = '';\n\t\t\tsearchResult = data;\n\t\t\tfor(var i = 0; i < 5 && i < data['totalItems']; i++){\n\t\t\t\tvar title = data.items[i].volumeInfo.title;\n\t\t\t\tvar author = \"\";\n\t\t\t\tif(data.items[i].volumeInfo.hasOwnProperty('authors')){\n\t\t\t\t\tauthor = 'By: ' + data.items[i].volumeInfo.authors[0];\n\t\t\t\t}\n\t\t\t\ttemphtml += '<a class=\"list-group-item list-group-item-action flex-column align-items-start\" href=\"#\">';\n\t\t\t\ttemphtml += '<div class=\"d-flex w-100 justify-content-between\">';\n\t\t\t\ttemphtml += '<h5 class=\"mb-1\">' + title + '</h5></div>';\n\t\t\t\ttemphtml += '<p class=\"mb-1\">' + author + '</p>';\n\t\t\t\ttemphtml += '<p class=\"sr-only\" id=\"index\">' + i + '</p>';\n\t\t\t\ttemphtml += '</a>';\n\t\t\t}\n\t\t\t$(\"#navSearchResults\").html(temphtml).removeClass(\"d-none\");\n\t\t}\n\t});\n}", "getBooks(title) {\n return this.service.sendGetRequest(this.books + '/' + title.value);\n }", "function getBookContent() {\n\tvar queryURL = 'https://www.googleapis.com/books/v1/volumes?q=' + searchTerm;\n\t$.ajax({\n\t\turl: queryURL,\n\t\tmethod: 'GET'\n\t}).then(function (response) {\n\t\tbookRating = response.items[0].volumeInfo.averageRating;\n\t\tvar bookPosterURL = response.items[0].volumeInfo.imageLinks.thumbnail;\n\t\tbookPoster = $('<img>');\n\t\tbookPoster.attr('src', bookPosterURL);\n\t\tbookTitle = response.items[0].volumeInfo.title;\n\t\tbookPlot = response.items[0].volumeInfo.description;\n\t\tsetContent();\n\t});\n}", "function getBook(title) {\n var book = null;\n var url = 'https://www.goodreads.com/book/title.xml?key=' + key + '&title=' + title;\n\n request(url, function (error, response, body) {\n if (!error && response.statusCode == 200) {\n xml2js(body, function (error, result) {\n if (!error) {\n // Extract just the fields that we want to work with. This minimizes the session footprint and makes it easier to debug.\n var b = result.GoodreadsResponse.book[0];\n book = { id: b.id, title: b.title, ratings_count: b.ratings_count, average_rating: b.average_rating, authors: b.authors };\n }\n else {\n book = { error: error };\n }\n });\n }\n else {\n book = { error: error };\n }\n });\n\n // Wait until we have a result from the async call.\n deasync.loopWhile(function() { return !book; });\n\n return book;\n}", "function getSimilarBooksJSON(related_items,eventCallback) {\r\n\r\n\tvar list_of_books = [];\r\n\tvar list_of_titles = [];\r\n\tvar rank_count = 1;\r\n\tvar completed_requests = 0;\r\n\tvar getlength = related_items.length\r\n\r\n\tif (related_items.length > 5){\r\n\t\tgetlength = 5;\r\n\t}\r\n\r\n\tfor (var i = 0,length = getlength; i < length; i++ ) {\r\n\t\r\n\t\trequest.get({\r\n\t\t\turl: \"https://www.googleapis.com/books/v1/volumes?q=\" + related_items[i].ASIN +\"&orderBy=relevance&key=APIKEY\"\r\n\t\t\t}, function(err, response, body) {\r\n\t\t\t\t\r\n\r\n\t\t\tif (body){\r\n\t\t\t\ttry{\r\n\t\t\t\t\tbody = JSON.parse(body);\r\n\t\t\t\t}catch(e){\r\n\t\t\t\t\tvar empty_array = [];\r\n\t\t\t\t\teventCallback(empty_array);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\t\r\n\r\n\t\t\t\t//console.log(body)\r\n\t\t\t\tcompleted_requests++;\r\n\t\t\t\tvar book_details={};\r\n\t\t\t\tvar title;\r\n\r\n\t\t\t\ttitle = body.items[0].volumeInfo.title ;\r\n\t\t\t\tif (list_of_titles.indexOf(title)> 0) { \t\t\t\t\r\n\t\t\t\t\treturn; \r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (typeof body.items[0].volumeInfo.authors=== 'undefined') { \t\t\t\t\r\n\t\t\t\t\treturn; \r\n\t\t\t\t}\r\n\r\n\t\t\t\tlist_of_titles[i] = title;\r\n\t\t\t\tbook_details.title = title;\t\r\n\t\t\t\tbook_details.titleupper = title.toUpperCase();\r\n\r\n\t\t\t\tvar author_string = \"\"; \r\n\t\t\t\tvar author_array = body.items[0].volumeInfo.authors;\r\n\t\t\t\t\r\n\t\t\t\tfor (var k = 0, klength = author_array.length; k < klength; k++){\r\n\t\t\t\t\tauthor_string = author_string + author_array[k] + \" and \" ;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tauthor_string = author_string.slice(0, -5);\r\n\t\t\t\tbook_details.author = author_string;\t\t\t\t\r\n\t\t\t\tbook_details.contributor = \"by \" + author_string;\r\n\r\n\t\t\t\tvar isbns_string = \"\";\r\n\t\t\t\tvar isbns_array = body.items[0].volumeInfo.industryIdentifiers;\r\n\r\n\t\t\t\tfor (var j = 0, jlength = isbns_array.length; j < jlength; j++){\r\n\t\t\t\t\tif (isbns_array[j].type === 'ISBN_10'){\r\n\t\t\t\t\t\tbook_details.primary_isbn10 = isbns_array[j].identifier;\r\n\t\t\t\t\t\tisbns_string = isbns_string + isbns_array[j].identifier + ',';\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\tbook_details.primary_isbn13 = isbns_array[j].identifier;\r\n\t\t\t\t\t\tisbns_string = isbns_string + isbns_array[j].identifier + ',';\r\n\t\t\t\t\t}\t\t\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\tisbns_string = isbns_string.slice(0, -1);\r\n\t\t\t\tbook_details.isbns_string = isbns_string;\r\n\r\n\t\t\t\tvar description = \". No description available.\";\r\n\t\t\t\t\t\t\r\n\t\t\t\tif (typeof(body.items[0].searchInfo) !=='undefined'){\r\n\t\t\t\t\tif (typeof(body.items[0].searchInfo.textSnippet) !=='undefined'){\r\n\t\t\t\t\t\tdescription = \". Here's a brief description of the book, \" + body.items[0].searchInfo.textSnippet;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbook_details.description = book_details.title + description;\r\n\r\n\t\t\t\tbook_details.description = book_details.title + \", \" + book_details.contributor + description;\r\n\t\t\t\t\t\r\n\r\n\t\t\t\tbook_details.rank = rank_count;\r\n\t\t\t\tlist_of_books[rank_count-1] = book_details;\r\n\t\t\t\trank_count++;\r\n\r\n\t\t\t\tconsole.log(\"book details title:\" + book_details.title);\r\n\t\t\t\tconsole.log(\"list of books count:\" + list_of_books.length);\r\n\r\n\t\t\t\tconsole.log(completed_requests);\r\n\t\t\t\tconsole.log(getlength);\r\n\t\t\t\t\tif (completed_requests === getlength) {\r\n\t\t\t\t\t\t// All download done, process responses array\r\n\t\t\t\t\t\tstringify(list_of_books);\r\n\r\n\t\t\t\t\t\teventCallback(list_of_books);\r\n\t\t\t\t\t}\r\n\t\t\t\r\n\t\t\t}).on('err', function (e) {\r\n \tconsole.log(\"Got error: \", e);}\r\n\t\t\r\n\t\t\r\n\t\t);\r\n\t}\r\n\r\n}", "function getBookDetailsJSON(isbn, isbns_string, eventCallback) {\r\n\r\n\tvar book_details={};\r\n\r\n\trequest.get({\r\n\t\turl: \"https://www.googleapis.com/books/v1/volumes?q=\" + isbn + \"&key=APIKEY\"\r\n\t\t}, function(err, response, body) {\r\n\r\n\t\t\tif (body){\r\n\t\t\t\ttry{\r\n\t\t\t\t\tbody = JSON.parse(body);\r\n\t\t\t\t}catch(e){\r\n\t\t\t\t\teventCallback(book_details);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\t\r\n\r\n\t\t\tbook_details.longDescription = body.items[0].volumeInfo.description ;\r\n\t\t\tbook_details.googleAvgRating = body.items[0].volumeInfo.averageRating;\r\n\t\t\tbook_details.googleAvgRatingCount = body.items[0].volumeInfo.ratingsCount;\r\n\t\t\tbook_details.googleBooksID = body.items[0].id;\r\n\r\n\t\t\trequest.get({\r\n\t\t\t\turl: \"https://www.goodreads.com/book/review_counts.json?isbns=\" + isbns_string +\"&key=APIKEY\"\r\n\t\t\t\t}, function(err, response, body) {\r\n\r\n\t\t\t\t\tif (body !== 'No books match those ISBNs.'){\r\n\t\t\t\t\t\tconsole.log(body)\r\n\t\t\t\t\t\tbody = JSON.parse(body);\r\n\r\n\t\t\t\t\t\tbook_details.goodreadsAvgRating =body.books[0].average_rating;\r\n\t\t\t\t\t\tbook_details.goodreadsAvgRatingCount = body.books[0].ratings_count;\r\n\t\t\t\t\t\tbook_details.goodreadsID= body.books[0].id;\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\tvar rating_string = \"\";\r\n\t\t\t\t\tvar rating_string_long = \"\";\r\n\r\n\t\t\t\t\tif (typeof book_details.goodreadsAvgRating !== 'undefined') {\r\n\r\n\t\t\t\t\t\t\trating_string_long = \" Goodreads users rated this book \" + book_details.goodreadsAvgRating + \" stars out of 5.\";\r\n\t\t\t\t\t\t\trating_string = rating_string + \"Goodreads User Rating: \" + book_details.goodreadsAvgRating + \"/5\\n\\n\";\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (typeof book_details.googleAvgRating !== 'undefined') {\r\n\t\t\t\t\t\trating_string_long = rating_string_long + \" Google Book users gave it a \" + book_details.googleAvgRating + \" rating.\";\r\n\t\t\t\t\t\trating_string = rating_string + \"Google Books User Rating: \" + book_details.googleAvgRating + \"/5\\n\\n\";\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tbook_details.rating_string = rating_string;\r\n\t\t\t\t\tbook_details.rating_string_long = rating_string_long;\r\n\t\t\t\t\teventCallback(book_details);\r\n\r\n\t\t\t\t}).on('err', function (e) {\r\n\t\t\t\tconsole.log(\"Got error: \", e);\r\n\t\t\t});\r\n\r\n\t\t\t//eventCallback(body);\r\n\t\t}).on('err', function (e) {\r\n console.log(\"Got error: \", e);\r\n });\r\n\r\n}", "function getBooks () {\n fetch(bookUrl)\n .then(resp => resp.json())\n .then(books => {\n renderBooks(books);\n window.allBooks = books\n }) //aspirational code to renderBooks(books)\n }", "queryBooks(query) {\n fetch('https://www.googleapis.com/books/v1/volumes?q='+ query).then((response)=>{\n response.json().then((data)=>{\n this.setState({\n // googleBooks: data.items[0].volumeInfo\n googleBooks: data.items\n })\n\n console.log(this.state.googleBooks);\n\n })\n }).catch((error)=>console.log(error))\n }", "function handleBookSearch () {\n // console.log(\"googleKey\", googleKey);\n axios.get(\"https://www.googleapis.com/books/v1/volumes?q=intitle:\" + book + \"&key=\" + googleKey + \"&maxResults=40\")\n .then(data => {\n const result = data.data.items[0];\n setResults(result);\n setLoad(true);\n setLoaded(false);\n })\n .catch(err => {\n console.log('Couldnt reach API', err);\n });\n }", "function getData(title, author, cb) {\n let xhr = new XMLHttpRequest();\n // Use encodeURIcomponent() to replace each instance of a space in the \n // title or author inputs with %20\n let bookTitle = \"intitle:\" + encodeURIComponent(title);\n let bookAuthor = \"+inauthor:\" + encodeURIComponent(author);\n\n let path = baseURL;\n if (title) {\n path += bookTitle;\n }\n if (author) {\n path += bookAuthor;\n }\n path += key;\n xhr.open(\"GET\", path);\n\n xhr.send();\n\n xhr.onreadystatechange = function () {\n if (this.readyState === 4 && this.status === 200) {\n cb(JSON.parse(this.responseText));\n }\n else if (this.status !== 200) {\n document.getElementById(\"bookContentContainer\").innerHTML = `<h5>Error: ${this.responseText} </h5>`;\n }\n };\n}", "function getAllBooks(){\n fetch(baseURL)\n .then(res => res.json())\n .then(books => listBooks(books))\n }", "function getAuthorListJSON(author, eventCallback) {\r\n\r\n\tvar book_details={};\r\n\tvar rank_count = 1;\r\n\tauthorencode = author.replace(' ','+');\r\n\r\n\trequest.get({\r\n\t\turl: \"https://www.googleapis.com/books/v1/volumes?q=\" + authorencode +\"&orderBy=relevance&key=APIKEY\"\r\n\t\t}, function(err, response, body) {\r\n\r\n\t\t\tvar list_of_books = [];\r\n\t\t\tvar list_of_titles = [];\r\n\r\n\t\t\tif (body){\r\n\t\t\t\ttry{\r\n\t\t\t\t\tbody = JSON.parse(body);\r\n\t\t\t\t}catch(e){\r\n\t\t\t\t\tvar list_of_books = [];\r\n\t\t\t\t\teventCallback(list_of_books);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\t\r\n\r\n\t\t\tif (body.totalItems === 0){\r\n\t\t\t\tstringify(list_of_books);\r\n\t\t\t\teventCallback(list_of_books);\r\n\t\t\t}\r\n\r\n\r\n\t\t\tfor (var i = 0,length = body.items.length; i < length; i++ ) {\r\n\r\n\t\t\t\tvar book_details={};\r\n\r\n\t\t\t\tvar title = body.items[i].volumeInfo.title;\r\n\t\t\t\tbook_details.title = title;\r\n\t\t\t\tbook_details.titleupper = title.toUpperCase();\r\n\t\t\t\tconsole.log(book_details.title);\r\n\t\t\t\t\r\n\t\t\t\tif (list_of_titles.indexOf(body.items[i].volumeInfo.title)> 0) { \t\t\t\t\r\n\t\t\t\t\tcontinue; \r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (typeof body.items[i].volumeInfo.authors=== 'undefined') { \t\t\t\t\r\n\t\t\t\t\tcontinue; \r\n\t\t\t\t}\r\n\r\n\t\t\t\tlist_of_titles[i] = body.items[i].volumeInfo.title;\r\n\r\n\t\t\t\tvar author_string = \"\"; \r\n\t\t\t\tvar author_array = body.items[i].volumeInfo.authors;\r\n\t\t\t\tvar author_array_upper = [];\r\n\r\n\t\t\t\tfor (var a = 0, alength = author_array.length; a < alength; a++){\r\n\t\t\t\t\tauthor_array_upper[a] = author_array[a].toUpperCase();\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (author_array_upper.indexOf(author.toUpperCase())< 0) { \r\n\t\t\t\t\t//console.log(\"Excluded: \" + book_details.title);\t\t\t\t\t\r\n\t\t\t\t\tcontinue; \r\n\t\t\t\t}\r\n\r\n\t\t\t\tfor (var k = 0, klength = author_array.length; k < klength; k++){\r\n\t\t\t\t\tauthor_string = author_string + author_array[k] + \" and \" ;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tauthor_string = author_string.slice(0, -5);\r\n\t\t\t\tbook_details.author = author_string;\t\t\t\t\r\n\t\t\t\tbook_details.contributor = \"by \" + author_string;\r\n\r\n\r\n\t\t\t\tbook_details.author = author_string;\t\t\t\t\r\n\t\t\t\tbook_details.contributor = \"by \" + author_string;\r\n\t\t\t\t\r\n\t\t\t\tbook_details.rank = rank_count;\r\n\t\t\t\trank_count++;\r\n\r\n\t\t\t\tvar isbns_string = \"\";\r\n\t\t\t\tvar isbns_array = body.items[i].volumeInfo.industryIdentifiers;\r\n\r\n\t\t\t\tfor (var j = 0, jlength = isbns_array.length; j < jlength; j++){\r\n\t\t\t\t\tif (isbns_array[j].type === 'ISBN_10'){\r\n\t\t\t\t\t\tbook_details.primary_isbn10 = isbns_array[j].identifier;\r\n\t\t\t\t\t\tisbns_string = isbns_string + isbns_array[j].identifier + ',';\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\tbook_details.primary_isbn13 = isbns_array[j].identifier;\r\n\t\t\t\t\t\tisbns_string = isbns_string + isbns_array[j].identifier + ',';\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\tisbns_string = isbns_string.slice(0, -1);\r\n\r\n\t\t\t\tbook_details.isbns_string = isbns_string;\r\n\r\n\t\t\t\tbook_details.contributor_alt = \"\";\r\n\r\n\t\t\t\tif (typeof body.items[i].volumeInfo.publishedDate !== 'undefined') { \r\n\t\t\t\t\t//published_date = body.items[i].volumeInfo.publishedDate;\r\n\t\t\t\t\tvar published_date = new Date(body.items[i].volumeInfo.publishedDate);\r\n\t\t\t\t\tvar date_string = monthNames[published_date.getMonth()] + \" \" + published_date.getFullYear();\r\n\t\t\t\t\tbook_details.contributor_alt = \"published in \" + date_string;\r\n\t\t\t\t}\r\n\t\t\t\r\n\r\n\t\t\t\tvar description = \". No description available.\";\r\n\t\t\t\t\r\n\t\t\t\tif (typeof(body.items[i].searchInfo) !=='undefined'){\r\n\t\t\t\t\tif (typeof(body.items[i].searchInfo.textSnippet) !=='undefined'){\r\n\t\t\t\t\t\tdescription = \". Here's a brief description of the book, \" + body.items[i].searchInfo.textSnippet;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbook_details.description = book_details.title + description;\r\n\t\t\t\t\r\n\r\n\t\t\t\tlist_of_books[i] = book_details;\r\n\t\t\t}\r\n\r\n\t\t\tlist_of_books = list_of_books.filter(function(n){ return n != undefined }); \r\n\t\t\tstringify(list_of_books);\r\n\t\t\t//console.log(list_of_books);\r\n\r\n\t\t\teventCallback(list_of_books);\r\n\t\t}).on('err', function (e) {\r\n console.log(\"Got error: \", e);\r\n });\r\n\r\n}", "function writeToDocument(title, author) {\n let el = document.getElementById(\"bookContentContainer\");\n let messageContainer = document.getElementById(\"messages\");\n // Sets the page back to blank every time the button is clicked.\n el.innerHTML = \"\";\n\n getData(title, author, function (data) {\n let searchList = [];\n let books = data.items;\n if (data.totalItems == 0) {\n messageContainer.innerHTML = `<div class=\"row flashed-messages\"><h4 class>No Results Found</h4></div>`;\n }\n else {\n for (var i in books) {\n // Assign an empty string to the variables\n // as Google Books API does not always contain these fields\n let img = \"\";\n let thumbnail = \"\";\n let title = \"\";\n let authors = \"\";\n let category = \"\";\n let description = \"\";\n let publisher = \"\";\n let publishedDate = \"\";\n let pageCount = \"\";\n let isbn = \"\";\n let textSnippet = \"\";\n\n // If fields exist overwrite the empty string with the returned information\n if (books[i].volumeInfo && books[i].volumeInfo.imageLinks && books[i].volumeInfo.imageLinks.thumbnail) {\n img = books[i].volumeInfo.imageLinks.thumbnail;\n thumbnail = img.substring(0, 4) + 's' + img.substring(4);\n }\n if (books[i].volumeInfo && books[i].volumeInfo.title) {\n title = books[i].volumeInfo.title;\n }\n if (books[i].volumeInfo && books[i].volumeInfo.authors) {\n authors = books[i].volumeInfo.authors;\n }\n if (books[i].volumeInfo && books[i].volumeInfo.categories && books[i].volumeInfo.categories[0]) {\n category = books[i].volumeInfo.categories[0];\n }\n if (books[i].volumeInfo && books[i].volumeInfo.description) {\n description = books[i].volumeInfo.description;\n }\n if (books[i].volumeInfo && books[i].volumeInfo.publisher) {\n publisher = books[i].volumeInfo.publisher;\n }\n if (books[i].volumeInfo && books[i].volumeInfo.publishedDate) {\n publishedDate = books[i].volumeInfo.publishedDate;\n }\n if (books[i].volumeInfo && books[i].volumeInfo.pageCount) {\n pageCount = books[i].volumeInfo.pageCount;\n }\n if (books[i].volumeInfo && books[i].volumeInfo.industryIdentifiers && books[i].volumeInfo.industryIdentifiers[0] && books[i].volumeInfo.industryIdentifiers[0].identifier) {\n isbn = books[i].volumeInfo.industryIdentifiers[0].identifier;\n }\n if (books[i].searchInfo && books[i].searchInfo.textSnippet) {\n textSnippet = books[i].searchInfo.textSnippet;\n }\n\n var dict = {\n \"thumbnail\": thumbnail,\n \"title\": title,\n \"authors\": authors,\n \"category\": category,\n \"description\": description,\n \"publisher\": publisher,\n \"published_date\": publishedDate,\n \"page_count\": pageCount,\n \"isbn\": isbn,\n \"text_snippet\": textSnippet,\n };\n searchList.push(dict);\n }\n\n // Print data to screen\n messageContainer.innerHTML += `<div class=\"row flashed-messages\"><div class=\"col s12\"><h4>Choose the edition you wish to review.</h4></div></div>`;\n for (i in searchList) {\n // How to encode string to base 64 found at Stack Overflow: https://stackoverflow.com/questions/246801/how-can-you-encode-a-string-to-base64-in-javascript\n el.innerHTML += `<div class='row'>\\\n <hr><hr><br>\\\n <div class='col s12 m6 center-align'><img src='${searchList[i].thumbnail}' alt='${searchList[i].title} book cover' class='centered'><br>\\\n <button type='submit' class='btn bg-blue' onclick='sendToPython(\"${btoa(encodeURIComponent(JSON.stringify(searchList[i])))}\");'>Choose This Edition</button>\\\n </div>\\\n <div class='col s12 m6'><table>\\\n <tr><td>Title:</td><td> ${searchList[i].title}</td></tr>\n <tr><td>Author:</td><td>${searchList[i].authors}</td></tr>\n <tr><td>Category:</td><td>${searchList[i].category}</td></tr>\n <tr><td>Snippet:</td><td>${searchList[i].text_snippet}</td></tr>\n <tr><td>Publisher:</td><td>${searchList[i].publisher}</td></tr>\n <tr><td>Date Published:</td><td>${searchList[i].published_date}</td></tr>\n <tr><td>Page Count:</td><td>${searchList[i].page_count}</td></tr>\n <tr><td>ISBN:</td><td>${searchList[i].isbn}</td></tr>\\\n </table>\\\n <br></div></div>`;\n }\n }\n }\n );\n}", "function getBooks() {\n return fetch(`${BASE_URL}/books`).then(res => res.json())\n}", "function bookGet() {\n\tgetBook = 'https:/www.amazon.com/s?k=' + searchTermURL + '&i=stripbooks';\n\tsetContent();\n}", "function searchGoogleBooksAPI(query) {\n API.searchBook(query)\n .then(res => {\n console.log(\"API - Results:\", res.data.items)\n setBooks(res.data.items);\n })\n .catch(err => console.log(err));\n }", "function getBooks() {\n clubID = this.value;\n // console.log('clubID', clubID);\n fetch('/get_books_in_genre?clubID=' + clubID)\n .then(function (response) {\n return response.json();\n }).then(function (json) {\n // console.log('GET response', json);\n if (json.length > 0) {\n set_book_select(json);\n };\n });\n}", "async function getBooksPlease(){\n const userInput =document.querySelector(\".entry\").value;\n apiUrl = `https://www.googleapis.com/books/v1/volumes?q=${userInput}`;\n const fetchBooks = await fetch(`${apiUrl}`);\n const jsonBooks = await fetchBooks.json();\n contentContainer.innerHTML= \"\";\n //console.log(jsonBooks)\n \n for (const book of jsonBooks.items) {\n const bookcontainer =document.createElement(\"div\");\n bookcontainer.className = \"book-card\"\n const bookTitle =document.createElement(\"h3\");\n const bookImage =document.createElement(\"img\");\n const bookAuthor =document.createElement(\"h3\");\n bookAuthor.innerHTML = book.volumeInfo.authors[0]\n bookTitle.innerText = book.volumeInfo.title\n bookImage.src = book.volumeInfo.imageLinks.thumbnail\n bookcontainer.append(bookImage, bookTitle, bookAuthor)\n contentContainer.append(bookcontainer)\n \n }\n}", "getAllBooks(url = this.baseUrl) {\r\n return fetch(url).then(response => response.json())\r\n }", "function findBook(req, res) {\n\n let url = 'https://www.googleapis.com/books/v1/volumes?q=';\n\n if (req.body.search[1] === 'title') { url += `+intitle:${req.body.search[0]}`; }\n\n if (req.body.search[1] === 'author') { url += `+inauthor:${req.body.search[0]}`; }\n\n superagent.get(url)\n\n .then(data => {\n // console.log('data >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', data.body.items[0].volumeInfo);\n\n let books = data.body.items.map(value => {\n return new Book(value);\n });\n // console.log(books);\n res.render('pages/searches/show', { book: books });\n }).catch(error => console.log(error));\n\n}", "function loadBooks() {\n const data = {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n },\n credentials: 'include',\n // Authorization: 'Kinvey ' + localStorage.getItem('authToken'),\n };\n\n fetch(url, data)\n .then(handler)\n .then(displayBooks)\n .catch((err) => {\n console.warn(err);\n });\n }", "function getAmazonDetailsbyKeywords(title, author, eventCallback){\r\n\tconsole.log(\"in get Amazon by Keyword\");\r\n\topHelper.execute('ItemSearch', {\r\n\t\t'Title': title,\r\n\t\t'Author': author,\r\n\t\t//'Condition': 'All',\r\n\t\t'ResponseGroup': 'Large',\r\n\t\t//'IdType' : 'ISBN',\r\n\t\t'SearchIndex':'Books'\r\n\t\t}, function(error, results) {\r\n\t\t\tif (error) { console.log('Error: ' + error + \"\\n\"); }\r\n\r\n\t\t\t//console.log(\"Results:\\n\" + util.inspect(results) + \"\\n\\n\");\r\n\t\t\t\t\t\t\r\n\t\t\tvar amazon_details = {};\r\n\t\t\tvar imageset;\r\n\t\t\tvar ASIN;\t\r\n\t\t\tvar ISBN;\r\n\t\t\tvar related_items = [];\r\n\r\n\t\t\tamazon_details.lgImage = 'https://s3.amazonaws.com/virtual-librarian/2000px-No_image_available.svg.png';\r\n\t\t\tamazon_details.smImage = 'https://s3.amazonaws.com/virtual-librarian/300px-No_image_available.svg.png';\r\n\t\t\tamazon_details.ASIN = 'None';\t\r\n\t\t\tamazon_details.ISBN = 'None';\r\n\t\t\t\t\t\t\r\n\t\t\t//console.log(\"Results:\\n\" + util.inspect(results) + \"\\n\");\r\n\t\t\tconsole.log(results.ItemSearchResponse.Items);\r\n\t\t\t//console.log(results.ItemSearchResponse.Items.Request);\r\n\r\n\t\t\tif (typeof(results.ItemSearchResponse.Items.Item) === 'undefined'){\r\n\t\t\t\tconsole.log('here')\r\n\t\t\t\teventCallback(amazon_details);\r\n\t\t\t\treturn;\r\n\t\t\t} \r\n\r\n\t\t\tvar key, count = 0;\r\n\t\t\t\tfor(key in results.ItemSearchResponse.Items.Item) {\r\n\t\t\t\tif(results.ItemSearchResponse.Items.Item.hasOwnProperty(key)) {\r\n\t\t\t\t\tcount++;\r\n\t\t\t\t//\tconsole.log(\"key:\" + key);\r\n\t\t\t\t//\tconsole.log(isNumeric(key));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (isNumeric(key)){\r\n\t\t\t\tASIN = results.ItemSearchResponse.Items.Item[0].ASIN;\r\n\t\t\t\tISBN = results.ItemSearchResponse.Items.Item[0].ItemAttributes.ISBN;\r\n\t\t\t\timageset = results.ItemSearchResponse.Items.Item[0].ImageSets.ImageSet;\r\n\t\t\t\trelated_items = results.ItemSearchResponse.Items.Item[0].SimilarProducts.SimilarProduct;\r\n\t\t\t\tconsole.log(\"in num key\");\r\n\t\t\t\t//console.log(results.ItemSearchResponse.Items.Item[0]);\r\n\t\t\t\t//console.log(results.ItemSearchResponse.Items.Item[0].SimilarProducts.SimilarProduct);\r\n\t\t\t\t//console.log(results.ItemSearchResponse.Items.Item[0].SimilarProducts.SimilarProduct);\r\n\t\t\t\t//console.log(related_items.length);\r\n\t\t\t\t\r\n\t\t\t}else{\r\n\t\t\t\tASIN = results.ItemSearchResponse.Items.Item.ASIN;\r\n\t\t\t\tISBN = results.ItemSearchResponse.Items.Item.ItemAttributes.ISBN;\r\n\t\t\t\timageset = results.ItemSearchResponse.Items.Item.ImageSets.ImageSet;\r\n\t\t\t\trelated_items = results.ItemSearchResponse.Items.Item.SimilarProducts.SimilarProduct;\r\n\t\t\t\tconsole.log(\"in not num key\");\r\n\t\t\t\t//console.log(results.ItemSearchResponse.Items.Item);\r\n\t\t\t\t\r\n\t\t\t}\r\n\r\n\t\t\tvar key, index=0, count = 0;\r\n\t\t\tfor(key in imageset) {\r\n\t\t\t\tif(imageset.hasOwnProperty(key)) {\r\n\t\t\t\t\t//console.log(key);\r\n\t\t\t\t\tif (isNumeric(key)){\r\n\t\t\t\t\t\tif (imageset[key].$.Category === 'primary'){\r\n\t\t\t\t\t\t\tindex = key;\r\n\t\t\t\t\t\t\timageset = imageset[index];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tcount++;\r\n\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif(typeof imageset.LargeImage !== 'undefined'){\r\n\t\t\t\tamazon_details.lgImage = imageset.LargeImage.URL;\r\n\t\t\t\tamazon_details.smImage = imageset.LargeImage.URL;\r\n\t\t\t\t//console.log(\"in large\");\r\n\t\t\t}\r\n\r\n\t\t\tif(typeof imageset.HiResImage !== 'undefined'){\r\n\t\t\t\tamazon_details.lgImage = imageset.HiResImage.URL;\r\n\t\t\t\t//console.log(\"in hi-res\");\r\n\t\t\t}\r\n\r\n\t\t\tvar correct_image = 'https://images-na.ssl-images-amazon.com';\r\n\t\t\tvar incorrect_image = 'http://ecx.images-amazon.com';\r\n\t\t\tamazon_details.lgImage = amazon_details.lgImage.replace(incorrect_image,correct_image);\r\n\t\t\tamazon_details.smImage = amazon_details.smImage.replace(incorrect_image,correct_image);\r\n\t\t\tamazon_details.ASIN = ASIN;\r\n\t\t\tamazon_details.ISBN = ISBN;\r\n\t\t\tamazon_details.related_items = related_items;\r\n\r\n\t\t\tconsole.log(amazon_details);\r\n\t\t\t\t\t\t\r\n\t\t\teventCallback(amazon_details);\r\n\r\n\t});\r\n}", "getBooks() {\n return this.service.sendGetRequest(this.books);\n }", "function getBooks(){\n fetch('http://localhost:3000/books')\n .then(resp => resp.json())\n .then(book => book.forEach(title))\n}", "function getBookReview() {\n\tvar queryURL =\n\t\t'https://api.nytimes.com/svc/books/v3/reviews.json?title=' +\n\t\tsearchTerm +\n\t\t'&api-key=AGFM7Bkp4YHthCReyXQ2KGqDWUyAaMLW';\n\t$.ajax({\n\t\turl: queryURL,\n\t\tmethod: 'GET'\n\t}).then(function (response) {\n\t\tbookReview = response.results[0].url;\n\t\tsetContent();\n\t});\n}", "function searchForBooks() {\n let search = document.querySelector('#search-bar').value; // save value of search bar\n const URL = 'https://www.googleapis.com/books/v1/volumes/?q='; // URL to search\n const maxResults = '&maxResults=10';\n let searchGBooks = `${URL}${search}${maxResults}`; // google books api + search value\n\n // set up JSON request\n let request = new XMLHttpRequest();\n request.open('GET', searchGBooks, true);\n\n request.onload = function() {\n if (request.status >= 200 && request.status < 400) {\n let data = JSON.parse(request.responseText); // Success! here is the JSON data\n render(data);\n } else {\n showError('No matches meet your search. Please try again'); // reached the server but it returned an error\n }\n };\n request.onerror = function() {\n // There was a connection error of some sort\n };\n request.send();\n}", "function getApi(event) {\n\n console.log(topicSearched);\n var requestUrl = \"https://www.googleapis.com/books/v1/volumes?q=\" + topicSearched;\n fetch(requestUrl)\n .then(function (response) {\n if (response.status === 400) {\n // || Message displaying that city is invalid\n return;\n } else {\n return response.json();\n }\n })\n .then(function (response) {\n saveSearchItem();\n console.log(searchInput);\n console.log(response);\n console.log(response);\n for (var i = 0; i < response.items.length; i++) {\n var bookCard = document.createElement('li');\n bookCard.setAttribute('class', 'card cell small-2 result-card');\n\n var linkBook = document.createElement('a');\n linkBook.href = response.items[i].volumeInfo.infoLink;\n linkBook.setAttribute('target', '_blank');\n bookCard.append(linkBook);\n\n var thumbImg = document.createElement('img');\n thumbImg.setAttribute('alt', `${response.items[i].volumeInfo.title}`)\n thumbImg.src = response.items[i].volumeInfo.imageLinks.thumbnail;\n linkBook.append(thumbImg);\n\n var favoriteEl = document.createElement('span');\n favoriteEl.setAttribute('class', 'label warning');\n favoriteEl.textContent = 'Favorite Me';\n bookCard.append(favoriteEl);\n\n var isbnNumber = document.createElement('span');\n isbnNumber.textContent = response.items[i].volumeInfo.industryIdentifiers[0].identifier;\n console.log(response.items[i].volumeInfo.industryIdentifiers[0].identifier);\n console.log(isbnNumber.textContent);\n isbnNumber.setAttribute('style', 'display: none');\n bookCard.append(isbnNumber);\n\n resultsList.append(bookCard);\n\n console.log(response.items[i].volumeInfo.infoLink);\n console.log(resultCard);\n }\n if (searchInput != \"\") {\n console.log(searchInput);\n } else {\n (function (response) {\n console.log(searchInput)\n })\n }\n });\n\n}", "function fetchBookDetails( row ) {\n \n var book = {};\n \n var cover = row.find('a > img.bc-image-inset-border');\n if ( cover.length > 0 ) book.cover = cover.attr('src');\n \n var title = row.find('ul > li:nth-child(1) > a > span');\n if ( title.length > 0 ) book.title = _.kebabCase( title.text().trimAll() );\n \n return (book.title && book.cover) ? book : null;\n \n }" ]
[ "0.67026985", "0.6645842", "0.6580502", "0.6496905", "0.64402133", "0.63113433", "0.62750965", "0.6272987", "0.62532353", "0.620866", "0.6171927", "0.61680335", "0.6154817", "0.60867167", "0.60772777", "0.6073042", "0.60596097", "0.6036178", "0.60256964", "0.5970491", "0.59261173", "0.5915685", "0.58713883", "0.58686304", "0.5851832", "0.5842037", "0.58277285", "0.5791313", "0.5748808", "0.57133347" ]
0.73480374
0
Replies back to the user with information about where the attachment is stored on the bot's server, and what the name of the saved file is.
async function replyForReceivedAttachments(localAttachmentData) { if (localAttachmentData) { // Because the TurnContext was bound to this function, the bot can call // `TurnContext.sendActivity` via `this.sendActivity`; await this.sendActivity(`Attachment "${ localAttachmentData.fileName }" ` + `has been received and saved to "${ localAttachmentData.localPath }".`); } else { await this.sendActivity('Attachment was not successfully saved to disk.'); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "handleAttachmentMessage() {\n let response;\n\n // Get the attachment\n let attachment = this.webhookEvent.message.attachments[0];\n //console.log(\"Received attachment:\", `${attachment} for ${this.user.psid}`);\n\n response = Response.genQuickReply(i18n.__(\"fallback.attachment\"), [\n {\n title: i18n.__(\"menu.start_over\"),\n payload: \"GET_STARTED\"\n }\n ]);\n\n return response;\n }", "function getAttachment(bot, msg, messageLang) {\r\n\tvar patentId = msg.text.toString().toLowerCase().replace('/download', '');\r\n\tif (patentId && typeof patentId != 'undefined') {\r\n\t\tif (usersLog[msg.from.username] && usersLog[msg.from.username].lastResult) {\r\n\t\t\ttry{\r\n\t\t\t\tif (usersLog[msg.from.username].lastResult[0][patentId]) {\r\n\t\t\t\t\tbot.sendDocument(msg.chat.id, usersLog[msg.from.username].lastResult[0][patentId].attachment, {\r\n\t\t\t\t\t\t\"caption\": '*' + languageBase[messageLang].attachmentCaption + '* ' + usersLog[msg.from.username].lastResult[0][patentId].desc,\r\n\t\t\t\t\t\t\"parse_mode\": 'Markdown'\r\n\t\t\t\t\t});\r\n\t\t\t\t}else{\r\n\t\t\t\t\tvar message = languageBase[messageLang].attachmentNotFound[0] + patentId + languageBase[messageLang].attachmentNotFound[1];\r\n\t\t\t\t\tbot.sendMessage(msg.chat.id,message);\r\n\t\t\t\t}\r\n\t\t\t}catch(e){\r\n\t\t\t\tconsole.log(e);\r\n\t\t\t\tbot.sendMessage(msg.chat.id,languageBase[messageLang].attachmentError);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tbot.sendMessage(msg.chat.id, languageBase[messageLang].attachmentWarning, {\r\n\t\t\t\t\"parse_mode\": 'Markdown'\r\n\t\t\t});\r\n\t\t}\r\n\t} else {\r\n\t\tbot.sendMessage(msg.chat.id,languageBase[messageLang].cmdError);\r\n\t} \r\n}", "function sendTrackerFile(author, guild){\r\n\tconst trackerFile = utils.getTrackerFile(guild);\r\n\tif (fs.existsSync(trackerFile)){\r\n\t\tutils.log(\"Sent trackerfile to \"+author.username+\"\", \"<<\");\r\n\t\treturn author.send({ files: [new Discord.Attachment(trackerFile)] });\r\n\t}\r\n\telse{\r\n\t\tutils.log(\"No trackerfile to send to \"+author.username+\"\", \"<<\");\r\n\t\treturn sendMessage(author, \"Trackerfile is empty or does not exist.\");\r\n\t}\r\n}", "function sendTrackerFile(author, guild){\r\n\tconst trackerFile = utils.getTrackerFile(guild);\r\n\tif (fs.existsSync(trackerFile)){\r\n\t\tutils.log(\"Sent trackerfile to \"+author.username+\"\", \"<<\");\r\n\t\treturn author.send({ files: [new Discord.Attachment(trackerFile)] });\r\n\t}\r\n\telse{\r\n\t\tutils.log(\"No trackerfile to send to \"+author.username+\"\", \"<<\");\r\n\t\treturn sendMessage(author, \"Trackerfile is empty or does not exist.\");\r\n\t}\r\n}", "async downloadAttachmentAndWrite(attachment) {\n // Retrieve the attachment via the attachment's contentUrl.\n const url = attachment.contentUrl;\n\n // Local file path for the bot to save the attachment.\n const localFileName = path.join(__dirname, attachment.name);\n\n try {\n // arraybuffer is necessary for images\n const response = await axios.get(url, { responseType: 'arraybuffer' });\n // If user uploads JSON file, this prevents it from being written as \"{\"type\":\"Buffer\",\"data\":[123,13,10,32,32,34,108...\"\n if (response.headers['content-type'] === 'application/json') {\n response.data = JSON.parse(response.data, (key, value) => {\n return value && value.type === 'Buffer' ?\n Buffer.from(value.data) :\n value;\n });\n }\n fs.writeFileSync(localFileName, response.data, (fsError) => {\n if (fsError) {\n throw fsError;\n }\n });\n } catch (error) {\n console.error(error);\n return undefined;\n }\n // If no error was thrown while writing to disk, return the attachment's name\n // and localFilePath for the response back to the user.\n return {\n fileName: attachment.name,\n localPath: localFileName\n };\n }", "function attachedFile(senderId, attachedObj) {\n if (attachedObj !== null && attachedObj.type === 'file') {\n allSenders[senderId].cv_url = attachedObj.payload.url;\n allSenders[senderId].states++;\n sendFBmessage.send(senderId, [{text: 'Write about yourself (personal qualities, professional skills, experience, interests, and passions). You can write a review about the bot \\u263A.'}]);\n } else {\n sendFBmessage.send(senderId, [{text:\"Ouch \\u263A It doesn’t look like pdf or doc, we accept only CV in pdf or doc.\"}]); \n }\n}", "get attachment () {\n\t\treturn this._attachment;\n\t}", "function uploadAttachment()\n {\n if (Office.context.mailbox.item.attachments == undefined)\n {\n app.showNotification(\"Sorry attachments are not supported by your Exchange server.\");\n }\n else if (Office.context.mailbox.item.attachments.length == 0)\n {\n app.showNotification(\"Oops there are no attachments on this email.\");\n }\n else\n {\n var apicall = \"https://api.workflowmax.com/job.api/document?apiKey=\"+ apiKey + \"&accountKey=\" + accountKey;\n\n var documentXML = \"<Document><Job>\" + cJobID + \"</Job><Title>Document Title</Title><Text>Note for document</Text><FileName>test.txt</FileName><Content>\" + string64 + \"</Content></Document>\";\n\n var xhr = new XMLHttpRequest();\n\n xhr.open('POST', apicall);\n\n xhr.send(documentXML);\n }\n }", "function send_avatar_info(newpath){\n\n var objectToSend = {}; // nuestro objeto a enviar\n var auto_message = \"Auto-message: My avatar has changed!\";\n\n objectToSend.name = guestname;\n objectToSend.message = auto_message;\n objectToSend.avatar = newpath;\n\n server.sendMessage(objectToSend);\n}", "function send_avatar_info(newpath){\n\n var objectToSend = {}; // nuestro objeto a enviar\n var auto_message = \"Auto-message: My avatar has changed!\";\n\n objectToSend.name = guestname;\n objectToSend.message = auto_message;\n objectToSend.avatar = newpath;\n\n server.sendMessage(objectToSend);\n}", "function attachmentHandler (id, atts, user) {\n // For now just send a message that says that we don't handle attachments.\n return m.attachmentDefaultAnswer(id);\n}", "function respondToMessageWithFile(message, response) {\r\n message.channel.sendFile(response);\r\n}", "get attachment() {\n\t\treturn this.__attachment;\n\t}", "function profilePicPathAttachment(obj) {\n return \"data/users/\" + obj.picture;\n }", "function receivedMessage(event) {\n var senderID = event.sender.id;\n var recipientID = event.recipient.id;\n var timeOfMessage = event.timestamp;\n var message = event.message;\n\n console.log(\"Received message for user %d and page %d at %d with message:\", senderID, recipientID, timeOfMessage);\n\n console.log(JSON.stringify(message));\n\n var isEcho = message.is_echo;\n var messageId = message.mid;\n var appId = message.app_id;\n var metadata = message.metadata;\n\n // You may get a text or attachment but not both\n var messageText = message.text;\n var messageAttachments = message.attachments;\n var quickReply = message.quick_reply;\n\n console.log(\"\\n------------event_log receivedPostback------------\\n\"+JSON.stringify(event)+\"\\n------------event_log receivedPostback fin------------\\n\")\n\n//photocin1361801687270524='ok';\n//date=\"2017-06-15\";\n//dossieruser1361801687270524={client: 'oui' ,agence: 'centreurbainnord' , jours: '2017-06-15' ,créneaux: '11:30' };\n//datecr2017_06_15centreurbainnord = {nbcrlibre: 4 ,cr1: '8:30' ,cr2: '11:30',cr3: '14:30',cr4: '15:00'};\n\n//datecr2017_06_15ariana = {nbcrlibre: 4 ,cr1: '8:30' ,cr2: '11:30',cr3: '14:30',cr4: '15:00'};\n\n // var azerty = JSON.parse(message.attachments);\n if(messageAttachments){\n\n console.log(message.attachments);\n //console.log(messageAttachments[0].payload.url);\n //console.log(message.attachments.payload.URL);\n if(messageAttachments[0].payload){\n options = {\n url: messageAttachments[0].payload.url,\n dest: 'C:/Users/user/Desktop/gomycode/download' // Save to /path/to/dest/photo.jpg \n}\n \n//download.image(options);\n if (messageAttachments[0].payload.coordinates) {\n\nconsole.log(\"lat= \"+messageAttachments[0].payload.coordinates.lat);\nconsole.log(\"long= \"+messageAttachments[0].payload.coordinates.long);\nlat=messageAttachments[0].payload.coordinates.lat;\nlang=messageAttachments[0].payload.coordinates.long;\n//sendTextMessage(senderID,\"votre lat est : \"+lat);\n }\n\n}\n\n else if (messageAttachments[0].type== \"image\")\n { \n\n async.series([\n function(callback){\n console.log(\"+++++ url image : \"+messageAttachments[0].payload.url);\n\n\n var url = messageAttachments[0].payload.url;\n \n var options = {\n directory: \"C:/Users/user/Desktop/gomycode/download/\",\n filename: \"image\"+senderID+\".jpeg\"\n }\n \n downloadfile(url, options, function(err){\n if (err) throw err\n console.log(\"\\ndownload done :)\\n\")\n });\n\n setTimeout(function(){\n callback(null, 1);\n }, 3000);\n\n }\n\n\n ], function(error, results) {\n console.log(results);\n });\n\n }\nelse if (messageAttachments[0].type== \"audio\")\n {\n \nconsole.log(\"\\n\\n audio received :)\\n\\n \")\n\n async.series([\n function(callback){\n console.log(\"+++++ url audio : \"+messageAttachments[0].payload.url);\n\n\n var url = messageAttachments[0].payload.url;\n \n var options = {\n directory: \"C:/Users/user/Desktop/gomycode/download/voice/\",\n filename: \"speech\"+senderID+\".mp3\"\n }\n \n downloadfile(url, options, function(err){\n if (err) throw err\n console.log(\"\\ndownload mp3 done :)\")\n });\n\n setTimeout(function(){\n callback(null, 1);\n }, 3000);\n\n }\n \n\n ], function(error, results) {\n console.log(results);\n });\n\n}\n}\n\n\n /*else if (isEcho)\n {\n console.log(\"echo\");\n }*/\nelse if (quickReply) {\n var quickReplyPayload = quickReply.payload;\n\n if (quickReplyPayload=='ProgrammesPayload')\n {\n\n async.series([\n function(callback){\n\n sendTextMessage(senderID, \"Tu es un passionné du numérique ? Un féru des nouvelles technologies ? \\nTu rêves de créer ton propre jeu vidéo, app mobile ou site web ? \\nTu veux devenir un développeur professionnel ?\\nGo My Code vous propose une varietée de programmes adaptés à vos divers besoins.\");\n\n\n setTimeout(function(){\n callback(null, 1);\n }, 1000);\n\n } ,\n \n function(callback){\n\n sendGenericMessagePrograms(senderID);\n\n setTimeout(function(){\n callback(null, 2);\n }, 1000);\n }\n\n ], function(error, results) {\n console.log(results);\n });\n }\n\n }\n\n else if (messageText) {\n\n}\n}", "url() {\n const url = RB.UserSession.instance.get('userFileAttachmentsURL');\n\n return this.isNew() ? url : `${url}${this.id}/`;\n }", "sendFileMessage( recipientId ) {\n var messageData = {\n recipient: {\n id: recipientId\n },\n message: {\n attachment: {\n type: \"file\",\n payload: {\n url: envVars.SERVER_URL + \"/assets/test.txt\"\n }\n }\n }\n };\n\n this.callSendAPI( messageData );\n }", "handleAttachmentMessage(lastevent) {\n let response;\n let attachment = this.webhookEvent.message.attachments[0];\n console.log(\"Received attachment:\", `${attachment} for ${this.user.psid}`);\n if (lastevent === \"photoquestion\") {\n response = [\n Response.genQuickReply(i18n.__(\"fallback.preparationquestion\"), [\n {\n title: i18n.__(\"menu.yes\"),\n payload: \"yes_confirmation\"\n },\n {\n title: i18n.__(\"menu.no\"),\n payload: \"deny_confirmation\"\n }\n ])\n ];\n console.log(\"Receive.js 135 help\");\n console.log(\"---------Llamando a handleAttachmentMessage----------\");\n console.log(\"Payload handleAttachmentMessage\");\n console.log(response);\n } else if (lastevent === \"file_input\") {\n console.log(\"Asignando codigo a mensaje\");\n console.log(this.user.idreport);\n let first = Response.genText(i18n.__(\"fallback.dontworry\"));\n console.log(\"first\");\n console.log(first);\n let second = Response.genText(i18n.__(\"fallback.pdfpath\"));\n let third = Response.genGenericTemplate(\n `${config.appUrl}/logo_chappy_police.png`,\n i18n.__(\"titles.title_en\"),\n this.user.idreport,\n [\n Response.genWebUrlButton(\n i18n.__(\"titles.download_here\"),\n `${config.botUrl}/${this.user.idDocument}.pdf`\n )\n ]\n );\n console.log(\"IMPRIMIENDO URL:\");\n console.log(`${config.botUrl}/${this.user.idDocument}.pdf`);\n let fourth = Response.genText(i18n.__(\"fallback.finish2\"));\n let fifth = { payload: \"finish\" };\n response = [first, second, third, fourth, fifth];\n console.log(\"---------Llamando a handleAttachmentMessage----------\");\n console.log(\"Payload handleAttachmentMessage\");\n console.log(response);\n }\n // Get the attachment\n return response;\n }", "function getFileOut(message) {\n //Need to check for file extensions\n return `./images${message.id}`;\n}", "function saveReplay() {\n fs.writeFile(\"./replyMSG.json\", JSON.stringify(replyMSG), function(err) {\n if (err) throw err;\n });\n}", "function storeOppAsAttachment() {\n var fileContents = fixBuffer(contents);\n var createitem = new SP.RequestExecutor(web.get_url());\n createitem.executeAsync({\n url: web.get_url() + \"/_api/web/lists/GetByTitle('Prospects')/items(\" + currentItem.get_id() + \")/AttachmentFiles/add(FileName='\" + file.name + \"')\",\n method: \"POST\",\n binaryStringRequestBody: true,\n body: fileContents,\n success: storeOppSuccess,\n error: storeOppFailure,\n state: \"Update\"\n });\n function storeOppSuccess(data) {\n\n // Success callback\n var errArea = document.getElementById(\"errAllOpps\");\n\n // Remove all nodes from the error <DIV> so we have a clean space to write to\n while (errArea.hasChildNodes()) {\n errArea.removeChild(errArea.lastChild);\n }\n\n // Workaround to clear the value in the file input.\n // What we really want to do is clear the text of the input=file element. \n // However, we are not allowed to do that because it could allow malicious script to interact with the file system. \n // So we’re not allowed to read/write that value in JavaScript (or jQuery)\n // So what we have to do is replace the entire input=file element with a new one (which will have an empty text box). \n // However, if we just replaced it with HTML, then it wouldn’t be wired up with the same events as the original.\n // So we replace it with a clone of the original instead. \n // And that’s what we need to do just to clear the text box but still have it work for uploading a second, third, fourth file.\n $('#oppUpload').replaceWith($('#oppUpload').val('').clone(true));\n var oppUpload = document.getElementById(\"oppUpload\");\n oppUpload.addEventListener(\"change\", oppAttach, false);\n showOppDetails(currentItem.get_id());\n }\n function storeOppFailure(data) {\n\n // Failure callback\n var errArea = document.getElementById(\"errAllOpps\");\n\n // Remove all nodes from the error <DIV> so we have a clean space to write to\n while (errArea.hasChildNodes()) {\n errArea.removeChild(errArea.lastChild);\n }\n var divMessage = document.createElement(\"DIV\");\n divMessage.setAttribute(\"style\", \"padding:5px;\");\n divMessage.appendChild(document.createTextNode(\"File upload failed.\"));\n errArea.appendChild(divMessage);\n }\n}", "function saveAttachment(attachment) {\n \n var file = attachment.getName();\n var folder = DriveApp.getFolderById(Folder_ID);\n var check = folder.getFilesByName(file);\n var invalidExtensions = ['png', 'jpg', 'jpeg', 'pdf', 'doc', 'docx'];\n \n // strip the extension\n var extension = file.split('.');\n\n // check the filetype to make sure it isn't in the list of invalid types\n if(invalidExtensions.indexOf(extension[extension.length-1]) > -1) {\n \n Logger.log(file + ' is not audio.');\n return;\n }\n \n if(check.hasNext()) {\n Logger.log(file + ' already exists. File not overwritten.');\n return;\n }\n uploadGoogleFilesToDropbox(attachment); // Uplaod attachment to Drop Box\n folder.createFile(attachment).setName(file); // Save attachement to Google Drive\n Logger.log(file + ' saved.');\n}", "function saveAttachment(digest, data) {\n txn.objectStore(ATTACH_STORE).put({digest: digest, body: data});\n }", "function send_data(sender, receiver, message) {\n\n // Check if we have an attachment\n if ($(\"#attached-file\").length == 1) {\n var attachment = $(\"#attached-file\").attr(\"filename\")\n } else {\n var attachment = null\n }\n var data = {sender: sender, receiver: receiver, message: message,\n attachment: attachment}\n $(\"#disable\").show()\n $.ajax({\n url: \"senddata.php\",\n data: data,\n type: \"post\",\n dataType: \"JSON\",\n success: function(res) {\n if (res.err !== null) {\n alert(res.err)\n } else {\n console.log(res)\n }\n $(\"#disable\").hide()\n }, error: function(xhr, ajaxOptions, thrownError) {\n console.log(xhr.status);\n console.log(thrownError);\n }\n });\n }", "function loadAttachment(client, addr, pass, key, id, uti) {\n\tvar iv = crypto.randomBytes(8).toString('hex');\n\n\tclient.emit('attachmentGet', id,\n\t\t'http://' + addr + ':8735/attachment?id=' + encrypt(id, key, iv) + '&password=' + encrypt(pass, key, iv) + '&iv=' + iv, uti);\n}", "get attachments() {\n return this._attachments;\n }", "async handleAttachments () {\n\t\t// not yet supported\n\t}", "function fileDownloadDone(filePath) {\n signale.complete('File download done, file saved to: ' + filePath);\n}", "function MessageSender(returnFile) {\n\tg_attachment = returnFile;\n\t////\n\tvar url_file = \"sendMailMessage\";\n\tsendToUrl(url_file);\n\t//\n}", "function fileSuccess(file, message) {\n // Iterate through the file list, find the one we\n // are added as a temp and replace its data\n // Normally you would parse the message and extract\n // the uploaded file data from it\n angular.forEach(vm.files, function (item, index)\n {\n if ( item.id && item.id === file.uniqueIdentifier )\n {\n // Normally you would update the file from\n // database but we are cheating here!\n\n // Update the file info\n item.name = file.file.name;\n item.type = 'document';\n\n // Figure out & upddate the size\n if ( file.file.size < 1024 )\n {\n item.size = parseFloat(file.file.size).toFixed(2) + ' B';\n }\n else if ( file.file.size >= 1024 && file.file.size < 1048576 )\n {\n item.size = parseFloat(file.file.size / 1024).toFixed(2) + ' Kb';\n }\n else if ( file.file.size >= 1048576 && file.file.size < 1073741824 )\n {\n item.size = parseFloat(file.file.size / (1024 * 1024)).toFixed(2) + ' Mb';\n }\n else\n {\n item.size = parseFloat(file.file.size / (1024 * 1024 * 1024)).toFixed(2) + ' Gb';\n }\n }\n });\n }" ]
[ "0.6406462", "0.6172073", "0.6062147", "0.6062147", "0.6020556", "0.5929268", "0.5841937", "0.5737819", "0.5737073", "0.5737073", "0.5734843", "0.56917673", "0.56610465", "0.5645517", "0.5584695", "0.5542011", "0.55292356", "0.54726654", "0.54699534", "0.5462597", "0.5378199", "0.535957", "0.5308587", "0.53016466", "0.5289799", "0.5286821", "0.5269191", "0.5255925", "0.52257466", "0.5212393" ]
0.64615303
0
Returns an inline attachment.
getInlineAttachment() { const imageData = fs.readFileSync(path.join(__dirname, '../resources/architecture-resize.png')); const base64Image = Buffer.from(imageData).toString('base64'); return { name: 'architecture-resize.png', contentType: 'image/png', contentUrl: `data:image/png;base64,${ base64Image }` }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getInlineImg(message){\n var attachments = message.getAttachments({\n includeInlineImages: true,\n includeAttachments: false\n });\n \n return attachments;\n}", "get inlineContent() {\n return this.type.inlineContent;\n }", "get attachment () {\n\t\treturn this._attachment;\n\t}", "getById(id) {\r\n return new Attachment(this, id);\r\n }", "get attachment() {\n\t\treturn this.__attachment;\n\t}", "get inline() {\n return this._inline;\n }", "get inline() {\n return this._inline;\n }", "function attach_inline(index, filename)\n{\n\tinsert_text('[attachment=' + index + ']' + filename + '[/attachment]');\n\tdocument.forms[form_name].elements[text_name].focus();\n}", "getInternetAttachment() {\n // NOTE: The contentUrl must be HTTPS.\n return {\n name: 'architecture-resize.png',\n contentType: 'image/png',\n contentUrl: 'https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png'\n };\n }", "get selectedAttachment() {\n let selectedElement = this._widget.selectedItem;\n if (selectedElement) {\n return this._itemsByElement.get(selectedElement).attachment;\n }\n return null;\n }", "handleAttachmentMessage() {\n let response;\n\n // Get the attachment\n let attachment = this.webhookEvent.message.attachments[0];\n //console.log(\"Received attachment:\", `${attachment} for ${this.user.psid}`);\n\n response = Response.genQuickReply(i18n.__(\"fallback.attachment\"), [\n {\n title: i18n.__(\"menu.start_over\"),\n payload: \"GET_STARTED\"\n }\n ]);\n\n return response;\n }", "embed(filePath, cid, options) {\n this.nodeMailerMessage.attachments = this.nodeMailerMessage.attachments || [];\n this.nodeMailerMessage.attachments.push({\n path: filePath,\n cid,\n ...options,\n });\n return this;\n }", "get pAttachment() {\n\t\treturn this.__pAttachment;\n\t}", "get inline() {\n return this.args.inline || false;\n }", "function replyInline( data ) {\n\tconst description = verifyData( data.description )\n\n\treturn {\n\t\tid: data.id,\n\t\ttitle: '[' + data.type.toUpperCase() + '] ' + data.title,\n\t\ttype: 'article',\n\t\tinput_message_content: {\n\t\t\tmessage_text: replyMarkdown( data ),\n\t\t\tparse_mode: 'Markdown',\n\t\t\tdisable_web_page_preview: false\n\t\t},\n\t\treply_markup: replyButton( data.type, data.title ),\n\t\tdescription: description,\n\t\tthumb_url: data.cover\n\t}\n}", "get attachments() {\n return this._attachments;\n }", "attachments() {\n return this._attachments;\n }", "get attachments() {\n return this.items.map(e => e.attachment);\n }", "getByName(name) {\r\n const f = new AttachmentFile(this);\r\n f.concat(`('${name}')`);\r\n return f;\r\n }", "get attachmentFiles() {\r\n return new AttachmentFiles(this);\r\n }", "attachmentWithText(text, fileName) {\n return { text, fileName };\n }", "function fetch() {\n\t\n\t if (!filenames.length) {\n\t return null;\n\t }\n\t\n\t var filename = filenames.pop();\n\t var att = atts[filename];\n\t var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n\t '?rev=' + doc._rev;\n\t return ajaxPromise(opts, {\n\t method: 'GET',\n\t url: genDBUrl(host, path),\n\t binary: true\n\t }).then(function (blob) {\n\t if (opts.binary) {\n\t return blob;\n\t }\n\t return new PouchPromise(function (resolve) {\n\t blobToBase64(blob, resolve);\n\t });\n\t }).then(function (data) {\n\t delete att.stub;\n\t delete att.length;\n\t att.data = data;\n\t });\n\t }", "_appendAttachment({ id, filename, content }) {\n const renderedPromise = this._renderedCapability.promise;\n\n renderedPromise.then(() => {\n if (renderedPromise !== this._renderedCapability.promise) {\n return; // The FileAttachment annotation belongs to a previous document.\n }\n let attachments = this._attachments;\n\n if (!attachments) {\n attachments = Object.create(null);\n } else {\n for (const name in attachments) {\n if (id === name) {\n return; // Ignore the new attachment if it already exists.\n }\n }\n }\n attachments[id] = {\n filename,\n content,\n };\n this.render({\n attachments,\n keepRenderedCapability: true,\n });\n });\n }", "function mmCreateUrlAttachment(attachment) {\n let type = $(attachment).data(\"type\");\n let id = $(attachment).data(\"id\");\n let $img = $(attachment).find(\".attachment-preview img\"),\n url = $img.data(\"src\"),\n urlmax = url.replace(/-150/g, \"\"),\n title = $img.attr(\"alt\"),\n max = $img.data(\"max\"),\n size = $img.data(\"size\"),\n sizes = $img.data(\"sizes\").toString(),\n align = $img.data(\"align\") || \"center\",\n textAlt = $img.attr(\"alt\") || \"\",\n proAlt = (textAlt!=null && textAlt.length>0)?`alt=\"${textAlt}\"`:\"\";\n textTitle = $img.data(\"title\") || \"\",\n proTitle = (textTitle!=null && textTitle.length>0)?`title=\"${textTitle}\"`:\"\";\n textCaption = $img.data(\"caption\") || \"\",\n tagCaption = (textCaption!=null && textCaption.length>0)?`<figcaption class=\"caption\">${textCaption}</figcaption>`:\"\";\n rs = '';\n switch (type) {\n case 'file':\n rs = `<a href=\"${url}\" title=\"${title}\">${url}</a>`;\n break;\n case 'image':\n let sizesArr = sizes.split(\",\"),\n srcset = [],\n srcsetSizes = [],\n cssAlign = \"\";\n cssAlign = (align == \"center\") ? `style=\"display: block; margin-left: auto; margin-right: auto; text-align:center;\"` : cssAlign;\n cssAlign = (align == \"right\") ? `style=\"float: right; text-align:right;\"` : cssAlign;\n sizesArr.forEach(s => {\n if (s <= size) {\n url = (s == max) ? urlmax : url.replace(/-150\\./g, `-${s}.`);\n srcset.push(`${url} ${s}w`);\n srcsetSizes.push(`${s}px`);\n }\n });\n urlmax = (size == max) ? urlmax : url.replace(/-150\\./g, `-${size}.`);\n rs = `<figure id=\"smsci-${id}\" class=\"sm-single-content-image\" ${cssAlign}>`;\n rs += `<img ${proAlt} ${proTitle} srcset=\"${srcset.join()}\" sizes=\"(max-width: ${size}px) ${srcsetSizes.join(\",\")}\" src=\"${urlmax}\" width=\"${size}\"/>`;\n rs += (tagCaption.length > 0) ? tagCaption : \"\";\n rs += \"</figure>\";\n break;\n default:\n console.log(\"wrong attachment type\");\n break;\n }\n return rs.trim();\n}", "function fetch(filename) {\n var att = atts[filename];\n var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n '?rev=' + doc._rev;\n return ajaxPromise(opts, {\n method: 'GET',\n url: genDBUrl(host, path),\n binary: true\n }).then(function (blob) {\n if (opts.binary) {\n return blob;\n }\n return new PouchPromise$1(function (resolve) {\n blobToBase64(blob, resolve);\n });\n }).then(function (data) {\n delete att.stub;\n delete att.length;\n att.data = data;\n });\n }", "function fetch() {\n\n if (!filenames.length) {\n return null;\n }\n\n var filename = filenames.pop();\n var att = atts[filename];\n var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n '?rev=' + doc._rev;\n return ajaxPromise(opts, {\n method: 'GET',\n url: genDBUrl(host, path),\n binary: true\n }).then(function (blob) {\n if (opts.binary) {\n return blob;\n }\n return new PouchPromise(function (resolve) {\n blobToBase64(blob, resolve);\n });\n }).then(function (data) {\n delete att.stub;\n delete att.length;\n att.data = data;\n });\n }", "function fetch() {\n\n if (!filenames.length) {\n return null;\n }\n\n var filename = filenames.pop();\n var att = atts[filename];\n var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n '?rev=' + doc._rev;\n return ajaxPromise(opts, {\n method: 'GET',\n url: genDBUrl(host, path),\n binary: true\n }).then(function (blob) {\n if (opts.binary) {\n return blob;\n }\n return new PouchPromise(function (resolve) {\n blobToBase64(blob, resolve);\n });\n }).then(function (data) {\n delete att.stub;\n delete att.length;\n att.data = data;\n });\n }", "function fetch(filename) {\n var att = atts[filename];\n var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n '?rev=' + doc._rev;\n return ajaxPromise(opts, {\n method: 'GET',\n url: genDBUrl(host, path),\n binary: true\n }).then(function (blob) {\n if (opts.binary) {\n return blob;\n }\n return new PouchPromise(function (resolve) {\n blobToBase64(blob, resolve);\n });\n }).then(function (data) {\n delete att.stub;\n delete att.length;\n att.data = data;\n });\n }", "function getAttachmentBase64(grAttachment /* GlideRecord of the attachment */) {\n\tvar gsa = new GlideSysAttachment();\n\tvar attBytes = gsa.getBytes(grAttachment); //Gets it as a Java Binary Array, not useable yet\n\tvar attBase64 = GlideStringUtil.base64Encode(attBytes); //Converts it into a Javascript string, holding the contents as a Base6-encoded string\n\t\n\treturn attBase64;\n}", "function fetch(filename) {\n\t var att = atts[filename];\n\t var path$$1 = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n\t '?rev=' + doc._rev;\n\t return ajaxPromise(opts, {\n\t method: 'GET',\n\t url: genDBUrl(host, path$$1),\n\t binary: true\n\t }).then(function (blob) {\n\t if (opts.binary) {\n\t return blob;\n\t }\n\t return new PouchPromise(function (resolve) {\n\t blobToBase64(blob, resolve);\n\t });\n\t }).then(function (data) {\n\t delete att.stub;\n\t delete att.length;\n\t att.data = data;\n\t });\n\t }" ]
[ "0.6851515", "0.6266762", "0.6195806", "0.6073926", "0.603093", "0.6015178", "0.6015178", "0.58593965", "0.5832146", "0.5763233", "0.5739862", "0.5718545", "0.5606278", "0.55855846", "0.5533645", "0.5493206", "0.5454444", "0.5404289", "0.5361439", "0.53519976", "0.5322941", "0.5233849", "0.5183889", "0.5175523", "0.51751244", "0.5171834", "0.5171834", "0.51612526", "0.51500845", "0.5145925" ]
0.71616316
0
Returns an attachment to be sent to the user from a HTTPS URL.
getInternetAttachment() { // NOTE: The contentUrl must be HTTPS. return { name: 'architecture-resize.png', contentType: 'image/png', contentUrl: 'https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png' }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async getFileURLSigned(url) {\n const path = await this.getPathFromUrl(url);\n const result = await this.doRequest({\n path,\n method: \"GET\",\n params: {\n noRedirect: true,\n },\n });\n return result;\n }", "function getAttachment(bot, msg, messageLang) {\r\n\tvar patentId = msg.text.toString().toLowerCase().replace('/download', '');\r\n\tif (patentId && typeof patentId != 'undefined') {\r\n\t\tif (usersLog[msg.from.username] && usersLog[msg.from.username].lastResult) {\r\n\t\t\ttry{\r\n\t\t\t\tif (usersLog[msg.from.username].lastResult[0][patentId]) {\r\n\t\t\t\t\tbot.sendDocument(msg.chat.id, usersLog[msg.from.username].lastResult[0][patentId].attachment, {\r\n\t\t\t\t\t\t\"caption\": '*' + languageBase[messageLang].attachmentCaption + '* ' + usersLog[msg.from.username].lastResult[0][patentId].desc,\r\n\t\t\t\t\t\t\"parse_mode\": 'Markdown'\r\n\t\t\t\t\t});\r\n\t\t\t\t}else{\r\n\t\t\t\t\tvar message = languageBase[messageLang].attachmentNotFound[0] + patentId + languageBase[messageLang].attachmentNotFound[1];\r\n\t\t\t\t\tbot.sendMessage(msg.chat.id,message);\r\n\t\t\t\t}\r\n\t\t\t}catch(e){\r\n\t\t\t\tconsole.log(e);\r\n\t\t\t\tbot.sendMessage(msg.chat.id,languageBase[messageLang].attachmentError);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tbot.sendMessage(msg.chat.id, languageBase[messageLang].attachmentWarning, {\r\n\t\t\t\t\"parse_mode\": 'Markdown'\r\n\t\t\t});\r\n\t\t}\r\n\t} else {\r\n\t\tbot.sendMessage(msg.chat.id,languageBase[messageLang].cmdError);\r\n\t} \r\n}", "async function getDownloadLink(uri, credential, _id) {\n return axios.post(buildEndpointOperationURL(ENDPOINT_OP_URL, getUriType(uri), DOWNLOAD_OP_URL), {\n \"identifier\": credential[\"name\"],\n \"credId\": credential[\"uuid\"],\n \"path\": uri,\n \"fileToDownload\": \"\"\n })\n .then((response) => {\n if (!(response.status === 200))\n console.log(\"Error in download API call\");\n else {\n return response.data\n }\n })\n .catch((error) => {\n handleRequestFailure(error);\n console.log(\"Error encountered while generating download link\");\n });\n}", "function fetch(filename) {\n var att = atts[filename];\n var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n '?rev=' + doc._rev;\n return ajaxPromise(opts, {\n method: 'GET',\n url: genDBUrl(host, path),\n binary: true\n }).then(function (blob) {\n if (opts.binary) {\n return blob;\n }\n return new PouchPromise$1(function (resolve) {\n blobToBase64(blob, resolve);\n });\n }).then(function (data) {\n delete att.stub;\n delete att.length;\n att.data = data;\n });\n }", "function fetch(filename) {\n var att = atts[filename];\n var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n '?rev=' + doc._rev;\n return ajaxPromise(opts, {\n method: 'GET',\n url: genDBUrl(host, path),\n binary: true\n }).then(function (blob) {\n if (opts.binary) {\n return blob;\n }\n return new PouchPromise(function (resolve) {\n blobToBase64(blob, resolve);\n });\n }).then(function (data) {\n delete att.stub;\n delete att.length;\n att.data = data;\n });\n }", "function fetch() {\n\t\n\t if (!filenames.length) {\n\t return null;\n\t }\n\t\n\t var filename = filenames.pop();\n\t var att = atts[filename];\n\t var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n\t '?rev=' + doc._rev;\n\t return ajaxPromise(opts, {\n\t method: 'GET',\n\t url: genDBUrl(host, path),\n\t binary: true\n\t }).then(function (blob) {\n\t if (opts.binary) {\n\t return blob;\n\t }\n\t return new PouchPromise(function (resolve) {\n\t blobToBase64(blob, resolve);\n\t });\n\t }).then(function (data) {\n\t delete att.stub;\n\t delete att.length;\n\t att.data = data;\n\t });\n\t }", "function fetch(filename) {\n var att = atts[filename];\n var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n '?rev=' + doc._rev;\n return ajaxPromise(opts, {\n method: 'GET',\n url: genDBUrl(host, path),\n binary: true\n }).then(function (blob$$1) {\n if (opts.binary) {\n return blob$$1;\n }\n return new PouchPromise$1(function (resolve) {\n blobToBase64(blob$$1, resolve);\n });\n }).then(function (data) {\n delete att.stub;\n delete att.length;\n att.data = data;\n });\n }", "function fetch(filename) {\n var att = atts[filename];\n var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n '?rev=' + doc._rev;\n return ajaxPromise(opts, {\n method: 'GET',\n url: genDBUrl(host, path),\n binary: true\n }).then(function (blob$$1) {\n if (opts.binary) {\n return blob$$1;\n }\n return new PouchPromise$1(function (resolve) {\n blobToBase64(blob$$1, resolve);\n });\n }).then(function (data) {\n delete att.stub;\n delete att.length;\n att.data = data;\n });\n }", "async function getFileContentRequest(url, customOptions) {\n var _response$headers$con2, _response$headers$sky2;\n\n const opts = { ...defaultDownloadOptions,\n ...this.customOptions,\n ...customOptions\n }; // GET request the data at the skylink.\n\n const response = await this.executeRequest({ ...opts,\n method: \"get\",\n url\n });\n\n if (typeof response.data === \"undefined\") {\n throw new Error(\"Did not get 'data' in response despite a successful request. Please try again and report this issue to the devs if it persists.\");\n }\n\n if (typeof response.headers === \"undefined\") {\n throw new Error(\"Did not get 'headers' in response despite a successful request. Please try again and report this issue to the devs if it persists.\");\n }\n\n const contentType = (_response$headers$con2 = response.headers[\"content-type\"]) !== null && _response$headers$con2 !== void 0 ? _response$headers$con2 : \"\";\n const metadata = response.headers[\"skynet-file-metadata\"] ? JSON.parse(response.headers[\"skynet-file-metadata\"]) : {};\n const portalUrl = (_response$headers$sky2 = response.headers[\"skynet-portal-api\"]) !== null && _response$headers$sky2 !== void 0 ? _response$headers$sky2 : \"\";\n const skylink = response.headers[\"skynet-skylink\"] ? (0, _skylink.formatSkylink)(response.headers[\"skynet-skylink\"]) : \"\";\n return {\n data: response.data,\n contentType,\n portalUrl,\n metadata,\n skylink\n };\n}", "function fetch(filename) {\n\t var att = atts[filename];\n\t var path$$1 = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n\t '?rev=' + doc._rev;\n\t return ajaxPromise(opts, {\n\t method: 'GET',\n\t url: genDBUrl(host, path$$1),\n\t binary: true\n\t }).then(function (blob) {\n\t if (opts.binary) {\n\t return blob;\n\t }\n\t return new PouchPromise(function (resolve) {\n\t blobToBase64(blob, resolve);\n\t });\n\t }).then(function (data) {\n\t delete att.stub;\n\t delete att.length;\n\t att.data = data;\n\t });\n\t }", "function downloadAttachment(link, callback) {\n link.classList.add('downloading');\n\n var xhr = new XMLHttpRequest();\n xhr.responseType = 'blob';\n\n xhr.onload = function() {\n callback(link.download, this.response);\n link.classList.remove('downloading');\n };\n\n xhr.open('GET', link.href);\n xhr.send(null);\n}", "function fetch() {\n\n if (!filenames.length) {\n return null;\n }\n\n var filename = filenames.pop();\n var att = atts[filename];\n var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n '?rev=' + doc._rev;\n return ajaxPromise(opts, {\n method: 'GET',\n url: genDBUrl(host, path),\n binary: true\n }).then(function (blob) {\n if (opts.binary) {\n return blob;\n }\n return new PouchPromise(function (resolve) {\n blobToBase64(blob, resolve);\n });\n }).then(function (data) {\n delete att.stub;\n delete att.length;\n att.data = data;\n });\n }", "function fetch() {\n\n if (!filenames.length) {\n return null;\n }\n\n var filename = filenames.pop();\n var att = atts[filename];\n var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n '?rev=' + doc._rev;\n return ajaxPromise(opts, {\n method: 'GET',\n url: genDBUrl(host, path),\n binary: true\n }).then(function (blob) {\n if (opts.binary) {\n return blob;\n }\n return new PouchPromise(function (resolve) {\n blobToBase64(blob, resolve);\n });\n }).then(function (data) {\n delete att.stub;\n delete att.length;\n att.data = data;\n });\n }", "function joinAttachToMessage({\n resource_type,\n secure_url,\n original_filename\n }) {\n const fileExtension = getFileExtension(secure_url);\n\n content = {\n attachment: {\n type:\n // The CDN Cloudinary saves the PDF files as a\n // resource_type='image', then we have to know\n // if the image is a PDF or another extension (eg: jpg).\n resource_type === 'raw' || fileExtension === 'pdf'\n ? 'file'\n : 'image',\n payload: {\n fileName: original_filename,\n url: secure_url\n }\n }\n };\n\n return createMessage(room._id, content, pubnub);\n }", "function _downloadUsingServer(serverPort, url)\n{\n return new Promise((accept, reject) => {\n if(url == null)\n {\n reject(null);\n return;\n }\n\n // We use i-cf for image URLs, but we don't currently have this in @connect,\n // so we can't use that here. Switch from i-cf back to the original URLs.\n url = new URL(url);\n if(url.hostname == \"i-cf.pximg.net\")\n url.hostname = \"i.pximg.net\";\n\n // Send a message to the sandbox to retrieve the image with GM.xmlHttpRequest, giving\n // it a message port to send the result back on.\n let { port1: serverResponsePort, port2: clientResponsePort } = new MessageChannel();\n\n clientResponsePort.onmessage = (e) => {\n clientResponsePort.close();\n \n if(e.data.success)\n accept(e.data.response);\n else\n reject(e.data.error);\n };\n\n serverPort.realPostMessage({\n url: url.toString(),\n\n options: {\n responseType: \"arraybuffer\",\n headers: {\n \"Cache-Control\": \"max-age=360000\",\n Referer: \"https://www.pixiv.net/\",\n Origin: \"https://www.pixiv.net/\",\n },\n },\n }, [serverResponsePort]);\n });\n}", "function downloadFile(url) {\n return new Promise((resolve, reject) => {\n console.log(\"Downloading file...\");\n var scheme = (url.indexOf(\"https\") === 0) ? https : http;\n\n scheme.get(url, response => {\n var data = [];\n response.on(\"data\", chunk => {\n data.push(chunk);\n });\n response.on(\"end\", () => {\n if (response.statusCode !== 200) return reject(response.statusMessage);\n\n var download = Buffer.concat(data);\n resolve(new Uint8Array(download).buffer);\n });\n })\n .on(\"error\", error => {\n reject(error);\n });\n });\n}", "async downloadAttachmentAndWrite(attachment) {\n // Retrieve the attachment via the attachment's contentUrl.\n const url = attachment.contentUrl;\n\n // Local file path for the bot to save the attachment.\n const localFileName = path.join(__dirname, attachment.name);\n\n try {\n // arraybuffer is necessary for images\n const response = await axios.get(url, { responseType: 'arraybuffer' });\n // If user uploads JSON file, this prevents it from being written as \"{\"type\":\"Buffer\",\"data\":[123,13,10,32,32,34,108...\"\n if (response.headers['content-type'] === 'application/json') {\n response.data = JSON.parse(response.data, (key, value) => {\n return value && value.type === 'Buffer' ?\n Buffer.from(value.data) :\n value;\n });\n }\n fs.writeFileSync(localFileName, response.data, (fsError) => {\n if (fsError) {\n throw fsError;\n }\n });\n } catch (error) {\n console.error(error);\n return undefined;\n }\n // If no error was thrown while writing to disk, return the attachment's name\n // and localFilePath for the response back to the user.\n return {\n fileName: attachment.name,\n localPath: localFileName\n };\n }", "function mmCreateUrlAttachment(attachment) {\n let type = $(attachment).data(\"type\");\n let id = $(attachment).data(\"id\");\n let $img = $(attachment).find(\".attachment-preview img\"),\n url = $img.data(\"src\"),\n urlmax = url.replace(/-150/g, \"\"),\n title = $img.attr(\"alt\"),\n max = $img.data(\"max\"),\n size = $img.data(\"size\"),\n sizes = $img.data(\"sizes\").toString(),\n align = $img.data(\"align\") || \"center\",\n textAlt = $img.attr(\"alt\") || \"\",\n proAlt = (textAlt!=null && textAlt.length>0)?`alt=\"${textAlt}\"`:\"\";\n textTitle = $img.data(\"title\") || \"\",\n proTitle = (textTitle!=null && textTitle.length>0)?`title=\"${textTitle}\"`:\"\";\n textCaption = $img.data(\"caption\") || \"\",\n tagCaption = (textCaption!=null && textCaption.length>0)?`<figcaption class=\"caption\">${textCaption}</figcaption>`:\"\";\n rs = '';\n switch (type) {\n case 'file':\n rs = `<a href=\"${url}\" title=\"${title}\">${url}</a>`;\n break;\n case 'image':\n let sizesArr = sizes.split(\",\"),\n srcset = [],\n srcsetSizes = [],\n cssAlign = \"\";\n cssAlign = (align == \"center\") ? `style=\"display: block; margin-left: auto; margin-right: auto; text-align:center;\"` : cssAlign;\n cssAlign = (align == \"right\") ? `style=\"float: right; text-align:right;\"` : cssAlign;\n sizesArr.forEach(s => {\n if (s <= size) {\n url = (s == max) ? urlmax : url.replace(/-150\\./g, `-${s}.`);\n srcset.push(`${url} ${s}w`);\n srcsetSizes.push(`${s}px`);\n }\n });\n urlmax = (size == max) ? urlmax : url.replace(/-150\\./g, `-${size}.`);\n rs = `<figure id=\"smsci-${id}\" class=\"sm-single-content-image\" ${cssAlign}>`;\n rs += `<img ${proAlt} ${proTitle} srcset=\"${srcset.join()}\" sizes=\"(max-width: ${size}px) ${srcsetSizes.join(\",\")}\" src=\"${urlmax}\" width=\"${size}\"/>`;\n rs += (tagCaption.length > 0) ? tagCaption : \"\";\n rs += \"</figure>\";\n break;\n default:\n console.log(\"wrong attachment type\");\n break;\n }\n return rs.trim();\n}", "async function urlToFile(url, filename, mimeType){\n try {\n const resp = await fetch(url);\n const buffer = await resp.arrayBuffer();\n return new File([buffer], filename, { type: mimeType });\n } catch (err) {\n throw err;\n }\n}", "function getURL(){\n\tvar html = document.getElementById(\"report\")\n\tvar share = document.getElementById(\"share\")\n\tvar url = window.location.href\n\thtml.innerHTML += \"<a href=\\\"mailto:[email protected]?subject=Reported%20Image&body=\"+ encodeURIComponent(url) +\"\\\">Report offensive image here</a>\"\n\tshare.innerHTML += \"<a href=\\\"mailto:?subject=Check%20out%20this%20image%20on%20PhotoSect!&body=\"+ encodeURIComponent(url) +\"\\\">Share with friends!</a>\"\n}", "get attachment () {\n\t\treturn this._attachment;\n\t}", "function httpsGet(opt) {\n return new Promise((fres, frej) => https.get(opt, (res) => {\n var err = null, cod = res.statusCode, dat = '';\n if(cod!==200) err = new Error(`HTTPS GET failed (${cod}).\\n${opt}`);\n if(err) { res.resume(); return frej(err); }\n res.setEncoding('utf8');\n res.on('data', (cnk) => dat+=cnk);\n res.on('end', () => fres(dat));\n }).on('error', frej));\n}", "function getImageStreamFromMessage(message) {\n var headers = {};\n var attachment = message.attachments[0];\n if (utils.checkRequiresToken(message)) {\n // The Skype attachment URLs are secured by JwtToken,\n // you should set the JwtToken of your bot as the authorization header for the GET request your bot initiates to fetch the image.\n // https://github.com/Microsoft/BotBuilder/issues/662\n connector.getAccessToken(function (error, token) {\n var tok = token;\n headers['Authorization'] = 'Bearer ' + token;\n headers['Content-Type'] = 'application/octet-stream';\n\n return needle.get(attachment.contentUrl, { headers: headers });\n });\n }\n\n headers['Content-Type'] = attachment.contentType;\n return needle.get(attachment.contentUrl, { headers: headers });\n}", "function getImageStreamFromMessage(message) {\n var headers = {};\n var attachment = message.attachments[0];\n if (utils.checkRequiresToken(message)) {\n // The Skype attachment URLs are secured by JwtToken,\n // you should set the JwtToken of your bot as the authorization header for the GET request your bot initiates to fetch the image.\n // https://github.com/Microsoft/BotBuilder/issues/662\n connector.getAccessToken(function (error, token) {\n var tok = token;\n headers['Authorization'] = 'Bearer ' + token;\n headers['Content-Type'] = 'application/octet-stream';\n\n return needle.get(attachment.contentUrl, { headers: headers });\n });\n }\n\n headers['Content-Type'] = attachment.contentType;\n return needle.get(attachment.contentUrl, { headers: headers });\n}", "function loadAttachment(client, addr, pass, key, id, uti) {\n\tvar iv = crypto.randomBytes(8).toString('hex');\n\n\tclient.emit('attachmentGet', id,\n\t\t'http://' + addr + ':8735/attachment?id=' + encrypt(id, key, iv) + '&password=' + encrypt(pass, key, iv) + '&iv=' + iv, uti);\n}", "function downloadFile(href, filename, callback) {\n var xhr = new XMLHttpRequest();\n xhr.responseType = 'blob';\n xhr.onload = function () {\n if (callback) {\n callback(this.response);\n }\n else {\n downloadBlob(filename, this.response);\n }\n };\n xhr.onerror = function () {\n if (callback) {\n callback(this.response);\n }\n };\n if (href.indexOf('https://help.liferay.com') == 0) {\n xhr.open('GET', href.substring('https://help.liferay.com'.length));\n }\n else {\n xhr.open('GET', href);\n }\n xhr.setRequestHeader('Cache-Control', 'no-cache, no-store, max-age=0');\n xhr.setRequestHeader('Pragma', 'no-cache');\n xhr.send(null);\n}", "function forceDownload(url, fileName){\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", url, true);\n xhr.responseType = \"blob\";\n xhr.onload = function(){\n var urlCreator = window.URL || window.webkitURL;\n var imageUrl = urlCreator.createObjectURL(this.response);\n var tag = document.createElement('a');\n tag.href = imageUrl;\n tag.download = fileName;\n document.body.appendChild(tag);\n tag.click();\n document.body.removeChild(tag);\n }\n xhr.send();\n}", "function sendEmailWithAttachment(email, content,attachpath)\n{\n \n \n var ses_mail = \"From: '' <\" + email + \">\\n\"\n + \"To: \" + email + \"\\n\"\n + \"Subject: New Order Submitted!!!\\n\"\n + \"MIME-Version: 1.0\\n\"\n + \"Content-Type: multipart/mixed; boundary=\\\"NextPart\\\"\\n\\n\"\n + \"--NextPart\\n\"\n + \"Content-Type: text/html; charset=us-ascii\\n\\n\"\n + content+\"\\n\\n\"\n + \"--NextPart\\n\"\n + \"Content-Type: text/plain;\\n\"\n + \"Content-Disposition: attachment; filename=\\\"\"+attachpath+\"\\\"\\n\\n\"\n + \"Awesome attachment\" + \"\\n\\n\"\n + \"--NextPart\";\n\n var params = {\n RawMessage: { Data: new Buffer(ses_mail) },\n Destinations: [ email ],\n Source: \"'' <\" + email + \">'\"\n };\n\n\n ses.sendRawEmail(params, function(err, data) {\n if(err) {\n } \n else {\n } \n });\n}", "function convertToBlobURL(url) {\n return new RSVP.Promise(function (resolve, reject) {\n var URL = window.URL || window.webkitURL;\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", url, true);\n xhr.responseType = \"blob\";\n xhr.onload = function (e) {\n resolve(URL.createObjectURL(xhr.response));\n };\n xhr.onerror = reject;\n xhr.send();\n });\n}", "url() {\n const url = RB.UserSession.instance.get('userFileAttachmentsURL');\n\n return this.isNew() ? url : `${url}${this.id}/`;\n }" ]
[ "0.5525053", "0.5393399", "0.52978003", "0.52469337", "0.5226839", "0.5204368", "0.5202747", "0.5202747", "0.5176209", "0.51752496", "0.51749665", "0.5170118", "0.5170118", "0.5165892", "0.51444054", "0.5136136", "0.51212376", "0.51186424", "0.50992525", "0.5085678", "0.508078", "0.5078666", "0.50545126", "0.50545126", "0.5052476", "0.5033564", "0.5031633", "0.5026783", "0.50256795", "0.5012171" ]
0.59386057
0